From 2e5beb16874d748c5deac974572e18bd9c005d26 Mon Sep 17 00:00:00 2001 From: Jiachi Liu Date: Wed, 26 Jan 2022 13:40:47 +0100 Subject: [PATCH 01/15] swc parse --- packages/next-swc/crates/napi/src/lib.rs | 4 +- packages/next-swc/crates/napi/src/parse.rs | 97 +++++++++++++++++++ packages/next/build/swc/index.js | 12 +++ packages/next/build/swc/options.js | 6 +- .../loaders/next-flight-server-loader.ts | 24 ++++- packages/next/server/dev/next-dev-server.ts | 1 + 6 files changed, 135 insertions(+), 9 deletions(-) create mode 100644 packages/next-swc/crates/napi/src/parse.rs diff --git a/packages/next-swc/crates/napi/src/lib.rs b/packages/next-swc/crates/napi/src/lib.rs index 4d097014d18b..dcc6441fbff6 100644 --- a/packages/next-swc/crates/napi/src/lib.rs +++ b/packages/next-swc/crates/napi/src/lib.rs @@ -44,7 +44,7 @@ mod bundle; mod minify; mod transform; mod util; - +mod parse; static COMPILER: Lazy> = Lazy::new(|| { let cm = Arc::new(SourceMap::new(FilePathMapping::empty())); @@ -68,6 +68,8 @@ fn init(mut exports: JsObject) -> napi::Result<()> { exports.create_named_method("minify", minify::minify)?; exports.create_named_method("minifySync", minify::minify_sync)?; + + exports.create_named_method("parse", parse::parse)?; Ok(()) } diff --git a/packages/next-swc/crates/napi/src/parse.rs b/packages/next-swc/crates/napi/src/parse.rs new file mode 100644 index 000000000000..201d89b02a6f --- /dev/null +++ b/packages/next-swc/crates/napi/src/parse.rs @@ -0,0 +1,97 @@ +use crate::{ + get_compiler, + util::{deserialize_json, CtxtExt, MapErr}, +}; +use anyhow::Context as _; +use napi::{CallContext, Either, Env, JsObject, JsString, JsUndefined, Task}; +use std::{sync::Arc}; +use swc::{try_with_handler, config::ParseOptions, Compiler}; +use swc_common::FileName; +use swc_ecmascript::ast::Program; + +pub struct ParseTask { + pub c: Arc, + pub filename: FileName, + pub src: String, + pub options: String, +} + +pub fn complete_parse<'a>(env: &Env, program: Program, _c: &Compiler) -> napi::Result { + let s = serde_json::to_string(&program) + .context("failed to serialize Program") + .convert_err()?; + env.create_string_from_std(s) +} + + +impl Task for ParseTask { + type Output = Program; + type JsValue = JsString; + + fn compute(&mut self) -> napi::Result { + // println!("compute"); + let options: ParseOptions = deserialize_json(&self.options).convert_err()?; + // println!("compute.options"); + let fm = self + .c + .cm + .new_source_file(self.filename.clone(), self.src.clone()); + println!("target {:?}", options.target); + println!("syntax {:?}", options.syntax); + println!("is_module {:?}", options.is_module); + println!("comments {:?}", options.comments); + let program = try_with_handler(self.c.cm.clone(), false, |handler| { + self.c.parse_js( + fm, + &handler, + options.target, + options.syntax, + options.is_module, + options.comments, + ) + }) + .convert_err()?; + + Ok(program) + } + + fn resolve(self, env: Env, result: Self::Output) -> napi::Result { + complete_parse(&env, result, &self.c) + } +} + + + +#[js_function(3)] +pub fn parse(ctx: CallContext) -> napi::Result { + println!("get_compiler"); + let c = get_compiler(&ctx); + println!("ctx.src"); + + let src = ctx.get_deserialized(0)?; + + // let src = ctx.get::(0)?.into_utf8()?; + println!("ctx.opts"); + // let options = ctx.get_deserialized(1)?; + let options = ctx.get_buffer_as_string(1)?; + // let mut options: TransformOptions = cx.get_deserialized(2)?; + println!("ctx.filename"); + let filename = ctx.get::>(2)?; + println!("ctx.filename2"); + let filename = if let Either::A(value) = filename { + println!("ctx.filename if"); + FileName::Real(value.into_utf8()?.as_str()?.to_owned().into()) + } else { + println!("ctx.filename else"); + FileName::Anon + }; + + ctx.env + .spawn(ParseTask { + c: c.clone(), + filename, + src, + options, + }) + .map(|t| t.promise_object()) +} diff --git a/packages/next/build/swc/index.js b/packages/next/build/swc/index.js index 6907c51e8605..6e6715382463 100644 --- a/packages/next/build/swc/index.js +++ b/packages/next/build/swc/index.js @@ -72,6 +72,9 @@ async function loadWasm() { minify(src, options) { return Promise.resolve(bindings.minifySync(src.toString(), options)) }, + parse(src, options) { + return Promise.resolve(bindings.parse(src.toString(), options)) + }, } return wasmBindings } catch (e) { @@ -179,6 +182,10 @@ function loadNative() { bundle(options) { return bindings.bundle(toBuffer(options)) }, + + parse(src, options) { + return bindings.parse(toBuffer(src), toBuffer(options ?? {})) + }, } return nativeBindings } @@ -219,3 +226,8 @@ export async function bundle(options) { let bindings = loadBindingsSync() return bindings.bundle(toBuffer(options)) } + +export function parse(src, options) { + let bindings = loadBindingsSync() + return bindings.parse(src, options) +} diff --git a/packages/next/build/swc/options.js b/packages/next/build/swc/options.js index 103119885e47..c6d3e560e491 100644 --- a/packages/next/build/swc/options.js +++ b/packages/next/build/swc/options.js @@ -5,7 +5,7 @@ const regeneratorRuntimePath = require.resolve( 'next/dist/compiled/regenerator-runtime' ) -function getBaseSWCOptions({ +export function getBaseSWCOptions({ filename, jest, development, @@ -45,9 +45,9 @@ function getBaseSWCOptions({ pragma: 'React.createElement', pragmaFrag: 'React.Fragment', throwIfNamespace: true, - development: development, + development: !!development, useBuiltins: true, - refresh: hasReactRefresh, + refresh: !!hasReactRefresh, }, optimizer: { simplify: false, diff --git a/packages/next/build/webpack/loaders/next-flight-server-loader.ts b/packages/next/build/webpack/loaders/next-flight-server-loader.ts index 6c7f1bfc1eab..f848e1426fba 100644 --- a/packages/next/build/webpack/loaders/next-flight-server-loader.ts +++ b/packages/next/build/webpack/loaders/next-flight-server-loader.ts @@ -1,4 +1,8 @@ -import * as acorn from 'next/dist/compiled/acorn' +// import * as acorn from 'next/dist/compiled/acorn' +// @ts-ignore +import { parse } from '../../swc' +// @ts-ignore +import { getBaseSWCOptions } from '../../swc/options' import { getRawPageExtensions } from '../../utils' function isClientComponent(importSource: string, pageExtensions: string[]) { @@ -28,6 +32,7 @@ export function isImageImport(importSource: string) { } async function parseImportsInfo( + resourcePath: string, source: string, imports: Array, isClientCompilation: boolean, @@ -36,10 +41,18 @@ async function parseImportsInfo( source: string defaultExportName: string }> { - const { body } = acorn.parse(source, { - ecmaVersion: 11, - sourceType: 'module', - }) as any + const opts = getBaseSWCOptions({ + filename: resourcePath, + // jest, + // development, + // hasReactRefresh, + globalWindow: isClientCompilation, + // nextConfig, + // resolvedBaseUrl, + // jsConfig, + }) + + const { body } = parse(source, { ...opts.jsc.parser, isModule: true }) let transformedSource = '' let lastIndex = 0 @@ -129,6 +142,7 @@ export default async function transformSource( const imports: string[] = [] const { source: transformedSource, defaultExportName } = await parseImportsInfo( + resourcePath, source, imports, isClientCompilation, diff --git a/packages/next/server/dev/next-dev-server.ts b/packages/next/server/dev/next-dev-server.ts index 8577f70101b8..b4b87be0890e 100644 --- a/packages/next/server/dev/next-dev-server.ts +++ b/packages/next/server/dev/next-dev-server.ts @@ -672,6 +672,7 @@ export default class DevServer extends Server { } } + console.error(err) if (!usedOriginalStack) { if (type === 'warning') { Log.warn(err + '') From 7c37609efe709c402bd9ca5a77920f04850c66ed Mon Sep 17 00:00:00 2001 From: Jiachi Liu Date: Wed, 26 Jan 2022 16:15:53 +0100 Subject: [PATCH 02/15] swc ast tree --- packages/next-swc/crates/napi/src/parse.rs | 2 -- .../webpack/loaders/next-flight-server-loader.ts | 11 +++++++---- .../app/pages/index.server.js | 4 ++++ 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/next-swc/crates/napi/src/parse.rs b/packages/next-swc/crates/napi/src/parse.rs index 201d89b02a6f..a29df9201f8a 100644 --- a/packages/next-swc/crates/napi/src/parse.rs +++ b/packages/next-swc/crates/napi/src/parse.rs @@ -60,8 +60,6 @@ impl Task for ParseTask { } } - - #[js_function(3)] pub fn parse(ctx: CallContext) -> napi::Result { println!("get_compiler"); diff --git a/packages/next/build/webpack/loaders/next-flight-server-loader.ts b/packages/next/build/webpack/loaders/next-flight-server-loader.ts index f848e1426fba..14b1c99b50d5 100644 --- a/packages/next/build/webpack/loaders/next-flight-server-loader.ts +++ b/packages/next/build/webpack/loaders/next-flight-server-loader.ts @@ -52,8 +52,10 @@ async function parseImportsInfo( // jsConfig, }) - const { body } = parse(source, { ...opts.jsc.parser, isModule: true }) + const ast = await parse(source, { ...opts.jsc.parser, isModule: true }) + const body = JSON.parse(ast).body + console.log('body', body) let transformedSource = '' let lastIndex = 0 let defaultExportName = 'RSCComponent' @@ -102,11 +104,12 @@ async function parseImportsInfo( continue } case 'ExportDefaultDeclaration': { - const def = node.declaration + const def = node.decl if (def.type === 'Identifier') { + console.log('def', def) defaultExportName = def.name - } else if (def.type === 'FunctionDeclaration') { - defaultExportName = def.id.name + } else if (def.type === 'FunctionExpression') { + defaultExportName = def.identifier.value } break } diff --git a/test/integration/react-streaming-and-server-components/app/pages/index.server.js b/test/integration/react-streaming-and-server-components/app/pages/index.server.js index 84efc4ddaefe..266218374f85 100644 --- a/test/integration/react-streaming-and-server-components/app/pages/index.server.js +++ b/test/integration/react-streaming-and-server-components/app/pages/index.server.js @@ -3,6 +3,10 @@ import Foo from '../components/foo.client' const envVar = process.env.ENV_VAR_TEST const headerKey = 'x-next-test-client' +const a = () => { + console.log('a') +} + export default function Index({ header, router }) { return (
From e62ea2a35961de9c6be34ed2769d6538722443b5 Mon Sep 17 00:00:00 2001 From: Jiachi Liu Date: Wed, 26 Jan 2022 22:33:41 +0100 Subject: [PATCH 03/15] port to swc ast --- packages/next-swc/crates/napi/src/parse.rs | 19 ------- packages/next/build/swc/index.js | 4 +- .../loaders/next-flight-client-loader.ts | 57 ++++++++----------- .../loaders/next-flight-server-loader.ts | 29 ++++------ packages/next/server/dev/next-dev-server.ts | 1 - .../components/client-exports-all.client.js | 1 + .../app/components/client-exports-all.js | 20 +++++++ .../app/components/client-exports.js | 10 ++++ .../app/pages/client-exports-all.server.js | 25 ++++++++ .../app/pages/client-exports.server.js | 13 +++++ .../app/pages/index.server.js | 4 -- 11 files changed, 105 insertions(+), 78 deletions(-) create mode 100644 test/integration/react-streaming-and-server-components/app/components/client-exports-all.client.js create mode 100644 test/integration/react-streaming-and-server-components/app/components/client-exports-all.js create mode 100644 test/integration/react-streaming-and-server-components/app/components/client-exports.js create mode 100644 test/integration/react-streaming-and-server-components/app/pages/client-exports-all.server.js create mode 100644 test/integration/react-streaming-and-server-components/app/pages/client-exports.server.js diff --git a/packages/next-swc/crates/napi/src/parse.rs b/packages/next-swc/crates/napi/src/parse.rs index a29df9201f8a..382d28aeb873 100644 --- a/packages/next-swc/crates/napi/src/parse.rs +++ b/packages/next-swc/crates/napi/src/parse.rs @@ -23,23 +23,16 @@ pub fn complete_parse<'a>(env: &Env, program: Program, _c: &Compiler) -> napi::R env.create_string_from_std(s) } - impl Task for ParseTask { type Output = Program; type JsValue = JsString; fn compute(&mut self) -> napi::Result { - // println!("compute"); let options: ParseOptions = deserialize_json(&self.options).convert_err()?; - // println!("compute.options"); let fm = self .c .cm .new_source_file(self.filename.clone(), self.src.clone()); - println!("target {:?}", options.target); - println!("syntax {:?}", options.syntax); - println!("is_module {:?}", options.is_module); - println!("comments {:?}", options.comments); let program = try_with_handler(self.c.cm.clone(), false, |handler| { self.c.parse_js( fm, @@ -62,25 +55,13 @@ impl Task for ParseTask { #[js_function(3)] pub fn parse(ctx: CallContext) -> napi::Result { - println!("get_compiler"); let c = get_compiler(&ctx); - println!("ctx.src"); - let src = ctx.get_deserialized(0)?; - - // let src = ctx.get::(0)?.into_utf8()?; - println!("ctx.opts"); - // let options = ctx.get_deserialized(1)?; let options = ctx.get_buffer_as_string(1)?; - // let mut options: TransformOptions = cx.get_deserialized(2)?; - println!("ctx.filename"); let filename = ctx.get::>(2)?; - println!("ctx.filename2"); let filename = if let Either::A(value) = filename { - println!("ctx.filename if"); FileName::Real(value.into_utf8()?.as_str()?.to_owned().into()) } else { - println!("ctx.filename else"); FileName::Anon }; diff --git a/packages/next/build/swc/index.js b/packages/next/build/swc/index.js index 6e6715382463..677d782c762b 100644 --- a/packages/next/build/swc/index.js +++ b/packages/next/build/swc/index.js @@ -227,7 +227,7 @@ export async function bundle(options) { return bindings.bundle(toBuffer(options)) } -export function parse(src, options) { +export async function parse(src, options) { let bindings = loadBindingsSync() - return bindings.parse(src, options) + return bindings.parse(src, options).then((astStr) => JSON.parse(astStr)) } diff --git a/packages/next/build/webpack/loaders/next-flight-client-loader.ts b/packages/next/build/webpack/loaders/next-flight-client-loader.ts index 2a78484a4868..94921fe4eff7 100644 --- a/packages/next/build/webpack/loaders/next-flight-client-loader.ts +++ b/packages/next/build/webpack/loaders/next-flight-client-loader.ts @@ -5,7 +5,12 @@ * LICENSE file in the root directory of this source tree. */ -import * as acorn from 'next/dist/compiled/acorn' +// import * as acorn from 'next/dist/compiled/acorn' +// TODO: add ts support for next-swc api +// @ts-ignore +import { parse } from '../../swc' +// @ts-ignore +import { getBaseSWCOptions } from '../../swc/options' type ResolveContext = { conditions: Array @@ -18,16 +23,12 @@ type ResolveFunction = ( resolve: ResolveFunction ) => { url: string } | Promise<{ url: string }> -type TransformSourceFunction = (url: string, callback: () => void) => void - -type Source = string | ArrayBuffer | Uint8Array - let stashedResolve: null | ResolveFunction = null function addExportNames(names: string[], node: any) { switch (node.type) { case 'Identifier': - names.push(node.name) + names.push(node.value) return case 'ObjectPattern': for (let i = 0; i < node.properties.length; i++) @@ -75,31 +76,24 @@ function resolveClientImport( } async function parseExportNamesInto( + resourcePath: string, transformedSource: string, - names: Array, - parentURL: string, - loadModule: TransformSourceFunction + names: Array ): Promise { - const { body } = acorn.parse(transformedSource, { - ecmaVersion: 11, - sourceType: 'module', - }) as any + const opts = getBaseSWCOptions({ + filename: resourcePath, + globalWindow: true, + }) + + const { body } = await parse(transformedSource, { + ...opts.jsc.parser, + isModule: true, + }) for (let i = 0; i < body.length; i++) { const node = body[i] switch (node.type) { - case 'ExportAllDeclaration': - if (node.exported) { - addExportNames(names, node.exported) - continue - } else { - const { url } = await resolveClientImport( - node.source.value, - parentURL - ) - const source = '' - parseExportNamesInto(source, names, url, loadModule) - continue - } + // TODO: support export * from module path + // case 'ExportAllDeclaration': case 'ExportDefaultDeclaration': names.push('default') continue @@ -129,8 +123,8 @@ async function parseExportNamesInto( export default async function transformSource( this: any, - source: Source -): Promise { + source: string +): Promise { const { resourcePath, resourceQuery } = this if (resourceQuery !== '?flight') return source @@ -142,12 +136,7 @@ export default async function transformSource( } const names: string[] = [] - await parseExportNamesInto( - transformedSource as string, - names, - url + resourceQuery, - this.loadModule - ) + await parseExportNamesInto(resourcePath, transformedSource, names) // next.js/packages/next/.js if (/[\\/]next[\\/](link|image)\.js$/.test(url)) { diff --git a/packages/next/build/webpack/loaders/next-flight-server-loader.ts b/packages/next/build/webpack/loaders/next-flight-server-loader.ts index 14b1c99b50d5..8d5b84927e23 100644 --- a/packages/next/build/webpack/loaders/next-flight-server-loader.ts +++ b/packages/next/build/webpack/loaders/next-flight-server-loader.ts @@ -1,4 +1,4 @@ -// import * as acorn from 'next/dist/compiled/acorn' +// TODO: add ts support for next-swc api // @ts-ignore import { parse } from '../../swc' // @ts-ignore @@ -43,29 +43,20 @@ async function parseImportsInfo( }> { const opts = getBaseSWCOptions({ filename: resourcePath, - // jest, - // development, - // hasReactRefresh, globalWindow: isClientCompilation, - // nextConfig, - // resolvedBaseUrl, - // jsConfig, }) const ast = await parse(source, { ...opts.jsc.parser, isModule: true }) - const body = JSON.parse(ast).body - - console.log('body', body) + const { body } = ast + const beginPos = ast.span.start let transformedSource = '' let lastIndex = 0 - let defaultExportName = 'RSCComponent' - + let defaultExportName for (let i = 0; i < body.length; i++) { const node = body[i] switch (node.type) { case 'ImportDeclaration': { const importSource = node.source.value - if (!isClientCompilation) { if ( !( @@ -76,10 +67,11 @@ async function parseImportsInfo( ) { continue } - transformedSource += source.substring( + const importDeclarations = source.substring( lastIndex, - node.source.start - 1 + node.source.span.start - beginPos ) + transformedSource += importDeclarations transformedSource += JSON.stringify(`${node.source.value}?flight`) } else { // For the client compilation, we skip all modules imports but @@ -99,14 +91,13 @@ async function parseImportsInfo( } } - lastIndex = node.source.end + lastIndex = node.source.span.end - beginPos imports.push(`require(${JSON.stringify(importSource)})`) continue } case 'ExportDefaultDeclaration': { const def = node.decl if (def.type === 'Identifier') { - console.log('def', def) defaultExportName = def.name } else if (def.type === 'FunctionExpression') { defaultExportName = def.identifier.value @@ -167,7 +158,9 @@ export default async function transformSource( const noop = `export const __rsc_noop__=()=>{${imports.join(';')}}` const defaultExportNoop = isClientCompilation ? `export default function ${defaultExportName}(){}\n${defaultExportName}.__next_rsc__=1;` - : `${defaultExportName}.__next_rsc__=1;` + : defaultExportName + ? `${defaultExportName}.__next_rsc__=1;` + : '' const transformed = transformedSource + '\n' + noop + '\n' + defaultExportNoop diff --git a/packages/next/server/dev/next-dev-server.ts b/packages/next/server/dev/next-dev-server.ts index b4b87be0890e..8577f70101b8 100644 --- a/packages/next/server/dev/next-dev-server.ts +++ b/packages/next/server/dev/next-dev-server.ts @@ -672,7 +672,6 @@ export default class DevServer extends Server { } } - console.error(err) if (!usedOriginalStack) { if (type === 'warning') { Log.warn(err + '') diff --git a/test/integration/react-streaming-and-server-components/app/components/client-exports-all.client.js b/test/integration/react-streaming-and-server-components/app/components/client-exports-all.client.js new file mode 100644 index 000000000000..aa9197254b20 --- /dev/null +++ b/test/integration/react-streaming-and-server-components/app/components/client-exports-all.client.js @@ -0,0 +1 @@ +export * from './client-exports' diff --git a/test/integration/react-streaming-and-server-components/app/components/client-exports-all.js b/test/integration/react-streaming-and-server-components/app/components/client-exports-all.js new file mode 100644 index 000000000000..d7d3f726f5a1 --- /dev/null +++ b/test/integration/react-streaming-and-server-components/app/components/client-exports-all.js @@ -0,0 +1,20 @@ +export * from './client-exports' + +// TODO: add exports all test case in pages +/** + +import * as all from '../components/client-exports-all' +import * as allClient from '../components/client-exports-all.client' + +export default function Page() { + const { a, b, c, d, e } = all + const { a: ac, b: bc, c: cc, d: dc, e: ec } = allClient + return ( +
+
{a}{b}{c}{d}{e[0]}
+
{ac}{bc}{cc}{dc}{ec[0]}
+
+ ) +} + +*/ diff --git a/test/integration/react-streaming-and-server-components/app/components/client-exports.js b/test/integration/react-streaming-and-server-components/app/components/client-exports.js new file mode 100644 index 000000000000..6fd69b677b4d --- /dev/null +++ b/test/integration/react-streaming-and-server-components/app/components/client-exports.js @@ -0,0 +1,10 @@ +const a = 'a' +const b = 'b' +const _c = 'c' +const _d = 'd' +const _e = 'e' +const _eArr = [_e] + +export const c = _c +export { a, b } +export { _d as d, _eArr as e } diff --git a/test/integration/react-streaming-and-server-components/app/pages/client-exports-all.server.js b/test/integration/react-streaming-and-server-components/app/pages/client-exports-all.server.js new file mode 100644 index 000000000000..d4a270114143 --- /dev/null +++ b/test/integration/react-streaming-and-server-components/app/pages/client-exports-all.server.js @@ -0,0 +1,25 @@ +import * as all from '../components/client-exports-all' +import * as allClient from '../components/client-exports-all.client' + +export default function Page() { + const { a, b, c, d, e } = all + const { a: ac, b: bc, c: cc, d: dc, e: ec } = allClient + return ( +
+
+ {a} + {b} + {c} + {d} + {e[0]} +
+
+ {ac} + {bc} + {cc} + {dc} + {ec[0]} +
+
+ ) +} diff --git a/test/integration/react-streaming-and-server-components/app/pages/client-exports.server.js b/test/integration/react-streaming-and-server-components/app/pages/client-exports.server.js new file mode 100644 index 000000000000..68bb37e7ee1d --- /dev/null +++ b/test/integration/react-streaming-and-server-components/app/pages/client-exports.server.js @@ -0,0 +1,13 @@ +import { a, b, c, d, e } from '../components/client-exports' + +export default function Page() { + return ( +
+ {a} + {b} + {c} + {d} + {e[0]} +
+ ) +} diff --git a/test/integration/react-streaming-and-server-components/app/pages/index.server.js b/test/integration/react-streaming-and-server-components/app/pages/index.server.js index 266218374f85..84efc4ddaefe 100644 --- a/test/integration/react-streaming-and-server-components/app/pages/index.server.js +++ b/test/integration/react-streaming-and-server-components/app/pages/index.server.js @@ -3,10 +3,6 @@ import Foo from '../components/foo.client' const envVar = process.env.ENV_VAR_TEST const headerKey = 'x-next-test-client' -const a = () => { - console.log('a') -} - export default function Index({ header, router }) { return (
From cc0e5f35d3d2eebdfc1a958d3e8e3e1c27e054cb Mon Sep 17 00:00:00 2001 From: Jiachi Liu Date: Wed, 26 Jan 2022 23:01:05 +0100 Subject: [PATCH 04/15] remove acorn compiled dep --- .../loaders/next-flight-client-loader.ts | 19 ----------------- packages/next/compiled/acorn/LICENSE | 21 ------------------- packages/next/compiled/acorn/acorn.js | 1 - packages/next/compiled/acorn/package.json | 1 - packages/next/taskfile.js | 10 --------- packages/next/types/misc.d.ts | 4 ---- 6 files changed, 56 deletions(-) delete mode 100644 packages/next/compiled/acorn/LICENSE delete mode 100644 packages/next/compiled/acorn/acorn.js delete mode 100644 packages/next/compiled/acorn/package.json diff --git a/packages/next/build/webpack/loaders/next-flight-client-loader.ts b/packages/next/build/webpack/loaders/next-flight-client-loader.ts index 94921fe4eff7..9cce14ac526c 100644 --- a/packages/next/build/webpack/loaders/next-flight-client-loader.ts +++ b/packages/next/build/webpack/loaders/next-flight-client-loader.ts @@ -5,7 +5,6 @@ * LICENSE file in the root directory of this source tree. */ -// import * as acorn from 'next/dist/compiled/acorn' // TODO: add ts support for next-swc api // @ts-ignore import { parse } from '../../swc' @@ -57,24 +56,6 @@ function addExportNames(names: string[], node: any) { } } -function resolveClientImport( - specifier: string, - parentURL: string -): { url: string } | Promise<{ url: string }> { - // Resolve an import specifier as if it was loaded by the client. This doesn't use - // the overrides that this loader does but instead reverts to the default. - // This resolution algorithm will not necessarily have the same configuration - // as the actual client loader. It should mostly work and if it doesn't you can - // always convert to explicit exported names instead. - const conditions = ['node', 'import'] - if (stashedResolve === null) { - throw new Error( - 'Expected resolve to have been called before transformSource' - ) - } - return stashedResolve(specifier, { conditions, parentURL }, stashedResolve) -} - async function parseExportNamesInto( resourcePath: string, transformedSource: string, diff --git a/packages/next/compiled/acorn/LICENSE b/packages/next/compiled/acorn/LICENSE deleted file mode 100644 index d6be6db2cfff..000000000000 --- a/packages/next/compiled/acorn/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (C) 2012-2020 by various contributors (see AUTHORS) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/packages/next/compiled/acorn/acorn.js b/packages/next/compiled/acorn/acorn.js deleted file mode 100644 index 1b37fdba121b..000000000000 --- a/packages/next/compiled/acorn/acorn.js +++ /dev/null @@ -1 +0,0 @@ -(()=>{var e={108:function(e,t){(function(e,i){true?i(t):0})(this,(function(e){"use strict";var t={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"};var i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var s={5:i,"5module":i+" export import",6:i+" const class extends export import super"};var r=/^in(stanceof)?$/;var a="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-鿼ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var n="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var o=new RegExp("["+a+"]");var h=new RegExp("["+a+n+"]");a=n=null;var p=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];var c=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];function isInAstralSet(e,t){var i=65536;for(var s=0;se){return false}i+=t[s+1];if(i>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&o.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,p)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&h.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,p)||isInAstralSet(e,c)}var l=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new l(e,{beforeExpr:true,binop:t})}var u={beforeExpr:true},f={startsExpr:true};var d={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return d[e]=new l(e,t)}var m={num:new l("num",f),regexp:new l("regexp",f),string:new l("string",f),name:new l("name",f),privateId:new l("privateId",f),eof:new l("eof"),bracketL:new l("[",{beforeExpr:true,startsExpr:true}),bracketR:new l("]"),braceL:new l("{",{beforeExpr:true,startsExpr:true}),braceR:new l("}"),parenL:new l("(",{beforeExpr:true,startsExpr:true}),parenR:new l(")"),comma:new l(",",u),semi:new l(";",u),colon:new l(":",u),dot:new l("."),question:new l("?",u),questionDot:new l("?."),arrow:new l("=>",u),template:new l("template"),invalidTemplate:new l("invalidTemplate"),ellipsis:new l("...",u),backQuote:new l("`",f),dollarBraceL:new l("${",{beforeExpr:true,startsExpr:true}),eq:new l("=",{beforeExpr:true,isAssign:true}),assign:new l("_=",{beforeExpr:true,isAssign:true}),incDec:new l("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new l("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new l("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new l("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",u),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",u),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",u),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",f),_if:kw("if"),_return:kw("return",u),_switch:kw("switch"),_throw:kw("throw",u),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",f),_super:kw("super",f),_class:kw("class",f),_extends:kw("extends",u),_export:kw("export"),_import:kw("import",f),_null:kw("null",f),_true:kw("true",f),_false:kw("false",f),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var g=/\r\n?|\n|\u2028|\u2029/;var x=new RegExp(g.source,"g");function isNewLine(e){return e===10||e===13||e===8232||e===8233}var v=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var y=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var k=Object.prototype;var b=k.hasOwnProperty;var w=k.toString;function has(e,t){return b.call(e,t)}var _=Array.isArray||function(e){return w.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var S=function Position(e,t){this.line=e;this.column=t};S.prototype.offset=function offset(e){return new S(this.line,this.column+e)};var C=function SourceLocation(e,t,i){this.start=t;this.end=i;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var i=1,s=0;;){x.lastIndex=s;var r=x.exec(e);if(r&&r.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(_(t.onToken)){var s=t.onToken;t.onToken=function(e){return s.push(e)}}if(_(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(i,s,r,a,n,o){var h={type:i?"Block":"Line",value:s,start:r,end:a};if(e.locations){h.loc=new C(this,n,o)}if(e.ranges){h.range=[r,a]}t.push(h)}}var A=1,P=2,N=4,T=8,V=16,L=32,R=64,D=128,O=256,B=A|P|O;function functionFlags(e,t){return P|(e?N:0)|(t?T:0)}var M=0,F=1,U=2,q=3,H=4,G=5;var j=function Parser(e,i,r){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(s[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var a="";if(e.allowReserved!==true){a=t[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3];if(e.sourceType==="module"){a+=" await"}}this.reservedWords=wordsRegexp(a);var n=(a?a+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(n);this.reservedWordsStrictBind=wordsRegexp(n+" "+t.strictBind);this.input=String(i);this.containsEsc=false;if(r){this.pos=r;this.lineStart=this.input.lastIndexOf("\n",r-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(g).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=m.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.potentialArrowInForAwait=false;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports=Object.create(null);if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(A);this.regexpState=null;this.privateNameStack=[]};var z={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},canAwait:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true},allowNewDotTarget:{configurable:true},inClassStaticBlock:{configurable:true}};j.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};z.inFunction.get=function(){return(this.currentVarScope().flags&P)>0};z.inGenerator.get=function(){return(this.currentVarScope().flags&T)>0&&!this.currentVarScope().inClassFieldInit};z.inAsync.get=function(){return(this.currentVarScope().flags&N)>0&&!this.currentVarScope().inClassFieldInit};z.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&O){return false}if(t.flags&P){return(t.flags&N)>0}}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};z.allowSuper.get=function(){var e=this.currentThisScope();var t=e.flags;var i=e.inClassFieldInit;return(t&R)>0||i||this.options.allowSuperOutsideMethod};z.allowDirectSuper.get=function(){return(this.currentThisScope().flags&D)>0};z.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};z.allowNewDotTarget.get=function(){var e=this.currentThisScope();var t=e.flags;var i=e.inClassFieldInit;return(t&(P|O))>0||i};z.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&O)>0};j.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var i=this;for(var s=0;s=,?^&]/.test(r)||r==="!"&&this.input.charAt(s+1)==="=")}e+=t[0].length;y.lastIndex=e;e+=y.exec(this.input)[0].length;if(this.input[e]===";"){e++}}};W.eat=function(e){if(this.type===e){this.next();return true}else{return false}};W.isContextual=function(e){return this.type===m.name&&this.value===e&&!this.containsEsc};W.eatContextual=function(e){if(!this.isContextual(e)){return false}this.next();return true};W.expectContextual=function(e){if(!this.eatContextual(e)){this.unexpected()}};W.canInsertSemicolon=function(){return this.type===m.eof||this.type===m.braceR||g.test(this.input.slice(this.lastTokEnd,this.start))};W.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};W.semicolon=function(){if(!this.eat(m.semi)&&!this.insertSemicolon()){this.unexpected()}};W.afterTrailingComma=function(e,t){if(this.type===e){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!t){this.next()}return true}};W.expect=function(e){this.eat(e)||this.unexpected()};W.unexpected=function(e){this.raise(e!=null?e:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}W.checkPatternErrors=function(e,t){if(!e){return}if(e.trailingComma>-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var i=t?e.parenthesizedAssign:e.parenthesizedBind;if(i>-1){this.raiseRecoverable(i,"Parenthesized pattern")}};W.checkExpressionErrors=function(e,t){if(!e){return false}var i=e.shorthandAssign;var s=e.doubleProto;if(!t){return i>=0||s>=0}if(i>=0){this.raise(i,"Shorthand property assignments are valid only in destructuring patterns")}if(s>=0){this.raiseRecoverable(s,"Redefinition of __proto__ property")}};W.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&s<56320){return true}if(e){return false}if(s===123){return true}if(isIdentifierStart(s,true)){var a=i+1;while(isIdentifierChar(s=this.input.charCodeAt(a),true)){++a}if(s===92||s>55295&&s<56320){return true}var n=this.input.slice(i,a);if(!r.test(n)){return true}}return false};K.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async")){return false}y.lastIndex=this.pos;var e=y.exec(this.input);var t=this.pos+e[0].length,i;return!g.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)==="function"&&(t+8===this.input.length||!(isIdentifierChar(i=this.input.charCodeAt(t+8))||i>55295&&i<56320))};K.parseStatement=function(e,t,i){var s=this.type,r=this.startNode(),a;if(this.isLet(e)){s=m._var;a="let"}switch(s){case m._break:case m._continue:return this.parseBreakContinueStatement(r,s.keyword);case m._debugger:return this.parseDebuggerStatement(r);case m._do:return this.parseDoStatement(r);case m._for:return this.parseForStatement(r);case m._function:if(e&&(this.strict||e!=="if"&&e!=="label")&&this.options.ecmaVersion>=6){this.unexpected()}return this.parseFunctionStatement(r,false,!e);case m._class:if(e){this.unexpected()}return this.parseClass(r,true);case m._if:return this.parseIfStatement(r);case m._return:return this.parseReturnStatement(r);case m._switch:return this.parseSwitchStatement(r);case m._throw:return this.parseThrowStatement(r);case m._try:return this.parseTryStatement(r);case m._const:case m._var:a=a||this.value;if(e&&a!=="var"){this.unexpected()}return this.parseVarStatement(r,a);case m._while:return this.parseWhileStatement(r);case m._with:return this.parseWithStatement(r);case m.braceL:return this.parseBlock(true,r);case m.semi:return this.parseEmptyStatement(r);case m._export:case m._import:if(this.options.ecmaVersion>10&&s===m._import){y.lastIndex=this.pos;var n=y.exec(this.input);var o=this.pos+n[0].length,h=this.input.charCodeAt(o);if(h===40||h===46){return this.parseExpressionStatement(r,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return s===m._import?this.parseImport(r):this.parseExport(r,i);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(r,true,!e)}var p=this.value,c=this.parseExpression();if(s===m.name&&c.type==="Identifier"&&this.eat(m.colon)){return this.parseLabeledStatement(r,p,c,e)}else{return this.parseExpressionStatement(r,c)}}};K.parseBreakContinueStatement=function(e,t){var i=t==="break";this.next();if(this.eat(m.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==m.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var s=0;for(;s=6){this.eat(m.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};K.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(Y);this.enterScope(0);this.expect(m.parenL);if(this.type===m.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var i=this.isLet();if(this.type===m._var||this.type===m._const||i){var s=this.startNode(),r=i?"let":this.value;this.next();this.parseVar(s,true,r);this.finishNode(s,"VariableDeclaration");if((this.type===m._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&s.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===m._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,s)}if(t>-1){this.unexpected(t)}return this.parseFor(e,s)}var a=this.isContextual("let"),n=false;var o=new DestructuringErrors;var h=this.parseExpression(t>-1?"await":true,o);if(this.type===m._in||(n=this.options.ecmaVersion>=6&&this.isContextual("of"))){if(this.options.ecmaVersion>=9){if(this.type===m._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}if(a&&n){this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'.")}this.toAssignable(h,false,o);this.checkLValPattern(h);return this.parseForIn(e,h)}else{this.checkExpressionErrors(o,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,h)};K.parseFunctionStatement=function(e,t,i){this.next();return this.parseFunction(e,Z|(i?0:J),false,t)};K.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(m._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};K.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(m.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};K.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(m.braceL);this.labels.push(X);this.enterScope(0);var t;for(var i=false;this.type!==m.braceR;){if(this.type===m._case||this.type===m._default){var s=this.type===m._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(s){t.test=this.parseExpression()}else{if(i){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}i=true;t.test=null}this.expect(m.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};K.parseThrowStatement=function(e){this.next();if(g.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var $=[];K.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===m._catch){var t=this.startNode();this.next();if(this.eat(m.parenL)){t.param=this.parseBindingAtom();var i=t.param.type==="Identifier";this.enterScope(i?L:0);this.checkLValPattern(t.param,i?H:U);this.expect(m.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(m._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};K.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};K.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(Y);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};K.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};K.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};K.parseLabeledStatement=function(e,t,i,s){for(var r=0,a=this.labels;r=0;h--){var p=this.labels[h];if(p.statementStart===e.start){p.statementStart=this.start;p.kind=o}else{break}}this.labels.push({name:t,kind:o,statementStart:this.start});e.body=this.parseStatement(s?s.indexOf("label")===-1?s+"label":s:"label");this.labels.pop();e.label=i;return this.finishNode(e,"LabeledStatement")};K.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};K.parseBlock=function(e,t,i){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(m.braceL);if(e){this.enterScope(0)}while(this.type!==m.braceR){var s=this.parseStatement(null);t.body.push(s)}if(i){this.strict=false}this.next();if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};K.parseFor=function(e,t){e.init=t;this.expect(m.semi);e.test=this.type===m.semi?null:this.parseExpression();this.expect(m.semi);e.update=this.type===m.parenR?null:this.parseExpression();this.expect(m.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};K.parseForIn=function(e,t){var i=this.type===m._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!i||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(i?"for-in":"for-of")+" loop variable declaration may not have an initializer")}e.left=t;e.right=i?this.parseExpression():this.parseMaybeAssign();this.expect(m.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,i?"ForInStatement":"ForOfStatement")};K.parseVar=function(e,t,i){e.declarations=[];e.kind=i;for(;;){var s=this.startNode();this.parseVarId(s,i);if(this.eat(m.eq)){s.init=this.parseMaybeAssign(t)}else if(i==="const"&&!(this.type===m._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(s.id.type!=="Identifier"&&!(t&&(this.type===m._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{s.init=null}e.declarations.push(this.finishNode(s,"VariableDeclarator"));if(!this.eat(m.comma)){break}}return e};K.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLValPattern(e.id,t==="var"?F:U,false)};var Z=1,J=2,ee=4;K.parseFunction=function(e,t,i,s,r){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!s){if(this.type===m.star&&t&J){this.unexpected()}e.generator=this.eat(m.star)}if(this.options.ecmaVersion>=8){e.async=!!s}if(t&Z){e.id=t&ee&&this.type!==m.name?null:this.parseIdent();if(e.id&&!(t&J)){this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?F:U:q)}}var a=this.yieldPos,n=this.awaitPos,o=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&Z)){e.id=this.type===m.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,i,false,r);this.yieldPos=a;this.awaitPos=n;this.awaitIdentPos=o;return this.finishNode(e,t&Z?"FunctionDeclaration":"FunctionExpression")};K.parseFunctionParams=function(e){this.expect(m.parenL);e.params=this.parseBindingList(m.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};K.parseClass=function(e,t){this.next();var i=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var s=this.enterClassBody();var r=this.startNode();var a=false;r.body=[];this.expect(m.braceL);while(this.type!==m.braceR){var n=this.parseClassElement(e.superClass!==null);if(n){r.body.push(n);if(n.type==="MethodDefinition"&&n.kind==="constructor"){if(a){this.raise(n.start,"Duplicate constructor in the same class")}a=true}else if(n.key&&n.key.type==="PrivateIdentifier"&&isPrivateNameConflicted(s,n)){this.raiseRecoverable(n.key.start,"Identifier '#"+n.key.name+"' has already been declared")}}}this.strict=i;this.next();e.body=this.finishNode(r,"ClassBody");this.exitClassBody();return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};K.parseClassElement=function(e){if(this.eat(m.semi)){return null}var t=this.options.ecmaVersion;var i=this.startNode();var s="";var r=false;var a=false;var n="method";var o=false;if(this.eatContextual("static")){if(t>=13&&this.eat(m.braceL)){this.parseClassStaticBlock(i);return i}if(this.isClassElementNameStart()||this.type===m.star){o=true}else{s="static"}}i.static=o;if(!s&&t>=8&&this.eatContextual("async")){if((this.isClassElementNameStart()||this.type===m.star)&&!this.canInsertSemicolon()){a=true}else{s="async"}}if(!s&&(t>=9||!a)&&this.eat(m.star)){r=true}if(!s&&!a&&!r){var h=this.value;if(this.eatContextual("get")||this.eatContextual("set")){if(this.isClassElementNameStart()){n=h}else{s=h}}}if(s){i.computed=false;i.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc);i.key.name=s;this.finishNode(i.key,"Identifier")}else{this.parseClassElementName(i)}if(t<13||this.type===m.parenL||n!=="method"||r||a){var p=!i.static&&checkKeyName(i,"constructor");var c=p&&e;if(p&&n!=="method"){this.raise(i.key.start,"Constructor can't have get/set modifier")}i.kind=p?"constructor":n;this.parseClassMethod(i,r,a,c)}else{this.parseClassField(i)}return i};K.isClassElementNameStart=function(){return this.type===m.name||this.type===m.privateId||this.type===m.num||this.type===m.string||this.type===m.bracketL||this.type.keyword};K.parseClassElementName=function(e){if(this.type===m.privateId){if(this.value==="constructor"){this.raise(this.start,"Classes can't have an element named '#constructor'")}e.computed=false;e.key=this.parsePrivateIdent()}else{this.parsePropertyName(e)}};K.parseClassMethod=function(e,t,i,s){var r=e.key;if(e.kind==="constructor"){if(t){this.raise(r.start,"Constructor can't be a generator")}if(i){this.raise(r.start,"Constructor can't be an async method")}}else if(e.static&&checkKeyName(e,"prototype")){this.raise(r.start,"Classes may not have a static property named prototype")}var a=e.value=this.parseMethod(t,i,s);if(e.kind==="get"&&a.params.length!==0){this.raiseRecoverable(a.start,"getter should have no params")}if(e.kind==="set"&&a.params.length!==1){this.raiseRecoverable(a.start,"setter should have exactly one param")}if(e.kind==="set"&&a.params[0].type==="RestElement"){this.raiseRecoverable(a.params[0].start,"Setter cannot use rest params")}return this.finishNode(e,"MethodDefinition")};K.parseClassField=function(e){if(checkKeyName(e,"constructor")){this.raise(e.key.start,"Classes can't have a field named 'constructor'")}else if(e.static&&checkKeyName(e,"prototype")){this.raise(e.key.start,"Classes can't have a static field named 'prototype'")}if(this.eat(m.eq)){var t=this.currentThisScope();var i=t.inClassFieldInit;t.inClassFieldInit=true;e.value=this.parseMaybeAssign();t.inClassFieldInit=i}else{e.value=null}this.semicolon();return this.finishNode(e,"PropertyDefinition")};K.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;this.labels=[];this.enterScope(O|R);while(this.type!==m.braceR){var i=this.parseStatement(null);e.body.push(i)}this.next();this.exitScope();this.labels=t;return this.finishNode(e,"StaticBlock")};K.parseClassId=function(e,t){if(this.type===m.name){e.id=this.parseIdent();if(t){this.checkLValSimple(e.id,U,false)}}else{if(t===true){this.unexpected()}e.id=null}};K.parseClassSuper=function(e){e.superClass=this.eat(m._extends)?this.parseExprSubscripts(false):null};K.enterClassBody=function(){var e={declared:Object.create(null),used:[]};this.privateNameStack.push(e);return e.declared};K.exitClassBody=function(){var e=this.privateNameStack.pop();var t=e.declared;var i=e.used;var s=this.privateNameStack.length;var r=s===0?null:this.privateNameStack[s-1];for(var a=0;a=11){if(this.eatContextual("as")){e.exported=this.parseIdent(true);this.checkExport(t,e.exported.name,this.lastTokStart)}else{e.exported=null}}this.expectContextual("from");if(this.type!==m.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(m._default)){this.checkExport(t,"default",this.lastTokStart);var i;if(this.type===m._function||(i=this.isAsyncFunction())){var s=this.startNode();this.next();if(i){this.next()}e.declaration=this.parseFunction(s,Z|ee,false,i)}else if(this.type===m._class){var r=this.startNode();e.declaration=this.parseClass(r,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==m.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var a=0,n=e.specifiers;a=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(i){this.checkPatternErrors(i,true)}for(var s=0,r=e.properties;s=8&&!n&&o.name==="async"&&!this.canInsertSemicolon()&&this.eat(m._function)){this.overrideContext(se.f_expr);return this.parseFunction(this.startNodeAt(r,a),0,false,true,t)}if(s&&!this.canInsertSemicolon()){if(this.eat(m.arrow)){return this.parseArrowExpression(this.startNodeAt(r,a),[o],false,t)}if(this.options.ecmaVersion>=8&&o.name==="async"&&this.type===m.name&&!n&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc)){o=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(m.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(r,a),[o],true,t)}}return o;case m.regexp:var h=this.value;i=this.parseLiteral(h.value);i.regex={pattern:h.pattern,flags:h.flags};return i;case m.num:case m.string:return this.parseLiteral(this.value);case m._null:case m._true:case m._false:i=this.startNode();i.value=this.type===m._null?null:this.type===m._true;i.raw=this.type.keyword;this.next();return this.finishNode(i,"Literal");case m.parenL:var p=this.start,c=this.parseParenAndDistinguishExpression(s,t);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)){e.parenthesizedAssign=p}if(e.parenthesizedBind<0){e.parenthesizedBind=p}}return c;case m.bracketL:i=this.startNode();this.next();i.elements=this.parseExprList(m.bracketR,true,true,e);return this.finishNode(i,"ArrayExpression");case m.braceL:this.overrideContext(se.b_expr);return this.parseObj(false,e);case m._function:i=this.startNode();this.next();return this.parseFunction(i,0);case m._class:return this.parseClass(this.startNode(),false);case m._new:return this.parseNew();case m.backQuote:return this.parseTemplate();case m._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};ae.parseExprImport=function(){var e=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var t=this.parseIdent(true);switch(this.type){case m.parenL:return this.parseDynamicImport(e);case m.dot:e.meta=t;return this.parseImportMeta(e);default:this.unexpected()}};ae.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(m.parenR)){var t=this.start;if(this.eat(m.comma)&&this.eat(m.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="meta"){this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'")}if(t){this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere){this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(e,"MetaProperty")};ae.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(t,"Literal")};ae.parseParenExpression=function(){this.expect(m.parenL);var e=this.parseExpression();this.expect(m.parenR);return e};ae.parseParenAndDistinguishExpression=function(e,t){var i=this.start,s=this.startLoc,r,a=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var n=this.start,o=this.startLoc;var h=[],p=true,c=false;var l=new DestructuringErrors,u=this.yieldPos,f=this.awaitPos,d;this.yieldPos=0;this.awaitPos=0;while(this.type!==m.parenR){p?p=false:this.expect(m.comma);if(a&&this.afterTrailingComma(m.parenR,true)){c=true;break}else if(this.type===m.ellipsis){d=this.start;h.push(this.parseParenItem(this.parseRestBinding()));if(this.type===m.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{h.push(this.parseMaybeAssign(false,l,this.parseParenItem))}}var g=this.lastTokEnd,x=this.lastTokEndLoc;this.expect(m.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(m.arrow)){this.checkPatternErrors(l,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=u;this.awaitPos=f;return this.parseParenArrowList(i,s,h,t)}if(!h.length||c){this.unexpected(this.lastTokStart)}if(d){this.unexpected(d)}this.checkExpressionErrors(l,true);this.yieldPos=u||this.yieldPos;this.awaitPos=f||this.awaitPos;if(h.length>1){r=this.startNodeAt(n,o);r.expressions=h;this.finishNodeAt(r,"SequenceExpression",g,x)}else{r=h[0]}}else{r=this.parseParenExpression()}if(this.options.preserveParens){var v=this.startNodeAt(i,s);v.expression=r;return this.finishNode(v,"ParenthesizedExpression")}else{return r}};ae.parseParenItem=function(e){return e};ae.parseParenArrowList=function(e,t,i,s){return this.parseArrowExpression(this.startNodeAt(e,t),i,s)};var ne=[];ae.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(m.dot)){e.meta=t;var i=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"){this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'")}if(i){this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters")}if(!this.allowNewDotTarget){this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block")}return this.finishNode(e,"MetaProperty")}var s=this.start,r=this.startLoc,a=this.type===m._import;e.callee=this.parseSubscripts(this.parseExprAtom(),s,r,true,false);if(a&&e.callee.type==="ImportExpression"){this.raise(s,"Cannot use new with import()")}if(this.eat(m.parenL)){e.arguments=this.parseExprList(m.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=ne}return this.finishNode(e,"NewExpression")};ae.parseTemplateElement=function(e){var t=e.isTagged;var i=this.startNode();if(this.type===m.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}i.value={raw:this.value,cooked:null}}else{i.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();i.tail=this.type===m.backQuote;return this.finishNode(i,"TemplateElement")};ae.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var i=this.startNode();this.next();i.expressions=[];var s=this.parseTemplateElement({isTagged:t});i.quasis=[s];while(!s.tail){if(this.type===m.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(m.dollarBraceL);i.expressions.push(this.parseExpression());this.expect(m.braceR);i.quasis.push(s=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(i,"TemplateLiteral")};ae.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===m.name||this.type===m.num||this.type===m.string||this.type===m.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===m.star)&&!g.test(this.input.slice(this.lastTokEnd,this.start))};ae.parseObj=function(e,t){var i=this.startNode(),s=true,r={};i.properties=[];this.next();while(!this.eat(m.braceR)){if(!s){this.expect(m.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(m.braceR)){break}}else{s=false}var a=this.parseProperty(e,t);if(!e){this.checkPropClash(a,r,t)}i.properties.push(a)}return this.finishNode(i,e?"ObjectPattern":"ObjectExpression")};ae.parseProperty=function(e,t){var i=this.startNode(),s,r,a,n;if(this.options.ecmaVersion>=9&&this.eat(m.ellipsis)){if(e){i.argument=this.parseIdent(false);if(this.type===m.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(i,"RestElement")}if(this.type===m.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}i.argument=this.parseMaybeAssign(false,t);if(this.type===m.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(i,"SpreadElement")}if(this.options.ecmaVersion>=6){i.method=false;i.shorthand=false;if(e||t){a=this.start;n=this.startLoc}if(!e){s=this.eat(m.star)}}var o=this.containsEsc;this.parsePropertyName(i);if(!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(i)){r=true;s=this.options.ecmaVersion>=9&&this.eat(m.star);this.parsePropertyName(i,t)}else{r=false}this.parsePropertyValue(i,e,s,r,a,n,t,o);return this.finishNode(i,"Property")};ae.parsePropertyValue=function(e,t,i,s,r,a,n,o){if((i||s)&&this.type===m.colon){this.unexpected()}if(this.eat(m.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,n);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===m.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(i,s)}else if(!t&&!o&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==m.comma&&this.type!==m.braceR&&this.type!==m.eq)){if(i||s){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var h=e.kind==="get"?0:1;if(e.value.params.length!==h){var p=e.value.start;if(e.kind==="get"){this.raiseRecoverable(p,"getter should have no params")}else{this.raiseRecoverable(p,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(i||s){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=r}e.kind="init";if(t){e.value=this.parseMaybeDefault(r,a,this.copyNode(e.key))}else if(this.type===m.eq&&n){if(n.shorthandAssign<0){n.shorthandAssign=this.start}e.value=this.parseMaybeDefault(r,a,this.copyNode(e.key))}else{e.value=this.copyNode(e.key)}e.shorthand=true}else{this.unexpected()}};ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(m.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(m.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===m.num||this.type===m.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ae.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};ae.parseMethod=function(e,t,i){var s=this.startNode(),r=this.yieldPos,a=this.awaitPos,n=this.awaitIdentPos;this.initFunction(s);if(this.options.ecmaVersion>=6){s.generator=e}if(this.options.ecmaVersion>=8){s.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,s.generator)|R|(i?D:0));this.expect(m.parenL);s.params=this.parseBindingList(m.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(s,false,true,false);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=n;return this.finishNode(s,"FunctionExpression")};ae.parseArrowExpression=function(e,t,i,s){var r=this.yieldPos,a=this.awaitPos,n=this.awaitIdentPos;this.enterScope(functionFlags(i,false)|V);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!i}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false,s);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=n;return this.finishNode(e,"ArrowFunctionExpression")};ae.parseFunctionBody=function(e,t,i,s){var r=t&&this.type!==m.braceL;var a=this.strict,n=false;if(r){e.body=this.parseMaybeAssign(s);e.expression=true;this.checkParams(e,false)}else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!a||o){n=this.strictDirective(this.end);if(n&&o){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var h=this.labels;this.labels=[];if(n){this.strict=true}this.checkParams(e,!a&&!n&&!t&&!i&&this.isSimpleParamList(e.params));if(this.strict&&e.id){this.checkLValSimple(e.id,G)}e.body=this.parseBlock(false,undefined,n&&!a);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=h}this.exitScope()};ae.isSimpleParamList=function(e){for(var t=0,i=e;t-1||r.functions.indexOf(e)>-1||r.var.indexOf(e)>-1;r.lexical.push(e);if(this.inModule&&r.flags&A){delete this.undefinedExports[e]}}else if(t===H){var a=this.currentScope();a.lexical.push(e)}else if(t===q){var n=this.currentScope();if(this.treatFunctionsAsVar){s=n.lexical.indexOf(e)>-1}else{s=n.lexical.indexOf(e)>-1||n.var.indexOf(e)>-1}n.functions.push(e)}else{for(var o=this.scopeStack.length-1;o>=0;--o){var h=this.scopeStack[o];if(h.lexical.indexOf(e)>-1&&!(h.flags&L&&h.lexical[0]===e)||!this.treatFunctionsAsVarInScope(h)&&h.functions.indexOf(e)>-1){s=true;break}h.var.push(e);if(this.inModule&&h.flags&A){delete this.undefinedExports[e]}if(h.flags&B){break}}}if(s){this.raiseRecoverable(i,"Identifier '"+e+"' has already been declared")}};he.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};he.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};he.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&B){return t}}};he.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&B&&!(t.flags&V)){return t}}};var ce=function Node(e,t,i){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new C(e,i)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var le=j.prototype;le.startNode=function(){return new ce(this,this.start,this.startLoc)};le.startNodeAt=function(e,t){return new ce(this,e,t)};function finishNodeAt(e,t,i,s){e.type=t;e.end=i;if(this.options.locations){e.loc.end=s}if(this.options.ranges){e.range[1]=i}return e}le.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};le.finishNodeAt=function(e,t,i,s){return finishNodeAt.call(this,e,t,i,s)};le.copyNode=function(e){var t=new ce(this,e.start,this.startLoc);for(var i in e){t[i]=e[i]}return t};var ue="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var fe=ue+" Extended_Pictographic";var de=fe;var me=de+" EBase EComp EMod EPres ExtPict";var ge={9:ue,10:fe,11:de,12:me};var xe="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ve="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ye=ve+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ke=ye+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var be=ke+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";var we={9:ve,10:ye,11:ke,12:be};var _e={};function buildUnicodeData(e){var t=_e[e]={binary:wordsRegexp(ge[e]+" "+xe),nonBinary:{General_Category:wordsRegexp(xe),Script:wordsRegexp(we[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);buildUnicodeData(12);var Se=j.prototype;var Ce=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"");this.unicodeProperties=_e[e.options.ecmaVersion>=12?12:e.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};Ce.prototype.reset=function reset(e,t,i){var s=i.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=i;this.switchU=s&&this.parser.options.ecmaVersion>=6;this.switchN=s&&this.parser.options.ecmaVersion>=9};Ce.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};Ce.prototype.at=function at(e,t){if(t===void 0)t=false;var i=this.source;var s=i.length;if(e>=s){return-1}var r=i.charCodeAt(e);if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=s){return r}var a=i.charCodeAt(e+1);return a>=56320&&a<=57343?(r<<10)+a-56613888:r};Ce.prototype.nextIndex=function nextIndex(e,t){if(t===void 0)t=false;var i=this.source;var s=i.length;if(e>=s){return s}var r=i.charCodeAt(e),a;if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=s||(a=i.charCodeAt(e+1))<56320||a>57343){return e+1}return e+2};Ce.prototype.current=function current(e){if(e===void 0)e=false;return this.at(this.pos,e)};Ce.prototype.lookahead=function lookahead(e){if(e===void 0)e=false;return this.at(this.nextIndex(this.pos,e),e)};Ce.prototype.advance=function advance(e){if(e===void 0)e=false;this.pos=this.nextIndex(this.pos,e)};Ce.prototype.eat=function eat(e,t){if(t===void 0)t=false;if(this.current(t)===e){this.advance(t);return true}return false};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Se.validateRegExpFlags=function(e){var t=e.validFlags;var i=e.flags;for(var s=0;s-1){this.raise(e.start,"Duplicate regular expression flag")}}};Se.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};Se.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,i=e.backReferenceNames;t=9){i=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!i;return true}}e.pos=t;return false};Se.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};Se.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};Se.regexp_eatBracedQuantifier=function(e,t){var i=e.pos;if(e.eat(123)){var s=0,r=-1;if(this.regexp_eatDecimalDigits(e)){s=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){r=e.lastIntValue}if(e.eat(125)){if(r!==-1&&r=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};Se.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};Se.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};Se.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}Se.regexp_eatPatternCharacters=function(e){var t=e.pos;var i=0;while((i=e.current())!==-1&&!isSyntaxCharacter(i)){e.advance()}return e.pos!==t};Se.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};Se.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};Se.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};Se.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString(e.lastIntValue)}return true}return false};Se.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var i=this.options.ecmaVersion>=11;var s=e.current(i);e.advance(i);if(s===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)){s=e.lastIntValue}if(isRegExpIdentifierStart(s)){e.lastIntValue=s;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}Se.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var i=this.options.ecmaVersion>=11;var s=e.current(i);e.advance(i);if(s===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)){s=e.lastIntValue}if(isRegExpIdentifierPart(s)){e.lastIntValue=s;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}Se.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};Se.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var i=e.lastIntValue;if(e.switchU){if(i>e.maxBackReference){e.maxBackReference=i}return true}if(i<=e.numCapturingParens){return true}e.pos=t}return false};Se.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};Se.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,false)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};Se.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};Se.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};Se.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};Se.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}Se.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){if(t===void 0)t=false;var i=e.pos;var s=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var r=e.lastIntValue;if(s&&r>=55296&&r<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var n=e.lastIntValue;if(n>=56320&&n<=57343){e.lastIntValue=(r-55296)*1024+(n-56320)+65536;return true}}e.pos=a;e.lastIntValue=r}return true}if(s&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(s){e.raise("Invalid unicode escape")}e.pos=i}return false};function isValidUnicode(e){return e>=0&&e<=1114111}Se.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};Se.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};Se.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}Se.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var i=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var s=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,i,s);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var r=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,r);return true}return false};Se.regexp_validateUnicodePropertyNameAndValue=function(e,t,i){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(i)){e.raise("Invalid property value")}};Se.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};Se.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}Se.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}Se.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};Se.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};Se.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var i=e.lastIntValue;if(e.switchU&&(t===-1||i===-1)){e.raise("Invalid character class")}if(t!==-1&&i!==-1&&t>i){e.raise("Range out of order in character class")}}}};Se.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var i=e.current();if(i===99||isOctalDigit(i)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var s=e.current();if(s!==93){e.lastIntValue=s;e.advance();return true}return false};Se.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};Se.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};Se.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};Se.regexp_eatDecimalDigits=function(e){var t=e.pos;var i=0;e.lastIntValue=0;while(isDecimalDigit(i=e.current())){e.lastIntValue=10*e.lastIntValue+(i-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}Se.regexp_eatHexDigits=function(e){var t=e.pos;var i=0;e.lastIntValue=0;while(isHexDigit(i=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(i);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}Se.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var i=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+i*8+e.lastIntValue}else{e.lastIntValue=t*8+i}}else{e.lastIntValue=t}return true}return false};Se.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}Se.regexp_eatFixedHexDigits=function(e,t){var i=e.pos;e.lastIntValue=0;for(var s=0;s=this.input.length){return this.finishToken(m.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};Ie.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};Ie.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320){return e}var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888};Ie.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,i=this.input.indexOf("*/",this.pos+=2);if(i===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=i+2;if(this.options.locations){x.lastIndex=t;var s;while((s=x.exec(this.input))&&s.index8&&e<14||e>=5760&&v.test(String.fromCharCode(e))){++this.pos}else{break e}}}};Ie.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var i=this.type;this.type=e;this.value=t;this.updateContext(i)};Ie.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(m.ellipsis)}else{++this.pos;return this.finishToken(m.dot)}};Ie.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(m.assign,2)}return this.finishOp(m.slash,1)};Ie.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var i=1;var s=e===42?m.star:m.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++i;s=m.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(m.assign,i+1)}return this.finishOp(s,i)};Ie.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var i=this.input.charCodeAt(this.pos+2);if(i===61){return this.finishOp(m.assign,3)}}return this.finishOp(e===124?m.logicalOR:m.logicalAND,2)}if(t===61){return this.finishOp(m.assign,2)}return this.finishOp(e===124?m.bitwiseOR:m.bitwiseAND,1)};Ie.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(m.assign,2)}return this.finishOp(m.bitwiseXOR,1)};Ie.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||g.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(m.incDec,2)}if(t===61){return this.finishOp(m.assign,2)}return this.finishOp(m.plusMin,1)};Ie.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var i=1;if(t===e){i=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+i)===61){return this.finishOp(m.assign,i+1)}return this.finishOp(m.bitShift,i)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){i=2}return this.finishOp(m.relational,i)};Ie.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(m.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(m.arrow)}return this.finishOp(e===61?m.eq:m.prefix,1)};Ie.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var i=this.input.charCodeAt(this.pos+2);if(i<48||i>57){return this.finishOp(m.questionDot,2)}}if(t===63){if(e>=12){var s=this.input.charCodeAt(this.pos+2);if(s===61){return this.finishOp(m.assign,3)}}return this.finishOp(m.coalesce,2)}}return this.finishOp(m.question,1)};Ie.readToken_numberSign=function(){var e=this.options.ecmaVersion;var t=35;if(e>=13){++this.pos;t=this.fullCharCodeAtPos();if(isIdentifierStart(t,true)||t===92){return this.finishToken(m.privateId,this.readWord1())}}this.raise(this.pos,"Unexpected character '"+codePointToString$1(t)+"'")};Ie.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(m.parenL);case 41:++this.pos;return this.finishToken(m.parenR);case 59:++this.pos;return this.finishToken(m.semi);case 44:++this.pos;return this.finishToken(m.comma);case 91:++this.pos;return this.finishToken(m.bracketL);case 93:++this.pos;return this.finishToken(m.bracketR);case 123:++this.pos;return this.finishToken(m.braceL);case 125:++this.pos;return this.finishToken(m.braceR);case 58:++this.pos;return this.finishToken(m.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(m.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(m.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+codePointToString$1(e)+"'")};Ie.finishOp=function(e,t){var i=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,i)};Ie.readRegexp=function(){var e,t,i=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(i,"Unterminated regular expression")}var s=this.input.charAt(this.pos);if(g.test(s)){this.raise(i,"Unterminated regular expression")}if(!e){if(s==="["){t=true}else if(s==="]"&&t){t=false}else if(s==="/"&&!t){break}e=s==="\\"}else{e=false}++this.pos}var r=this.input.slice(i,this.pos);++this.pos;var a=this.pos;var n=this.readWord1();if(this.containsEsc){this.unexpected(a)}var o=this.regexpState||(this.regexpState=new Ce(this));o.reset(i,r,n);this.validateRegExpFlags(o);this.validateRegExpPattern(o);var h=null;try{h=new RegExp(r,n)}catch(e){}return this.finishToken(m.regexp,{pattern:r,flags:n,value:h})};Ie.readInt=function(e,t,i){var s=this.options.ecmaVersion>=12&&t===undefined;var r=i&&this.input.charCodeAt(this.pos)===48;var a=this.pos,n=0,o=0;for(var h=0,p=t==null?Infinity:t;h=97){l=c-97+10}else if(c>=65){l=c-65+10}else if(c>=48&&c<=57){l=c-48}else{l=Infinity}if(l>=e){break}o=c;n=n*e+l}if(s&&o===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===a||t!=null&&this.pos-a!==t){return null}return n};function stringToNumber(e,t){if(t){return parseInt(e,8)}return parseFloat(e.replace(/_/g,""))}function stringToBigInt(e){if(typeof BigInt!=="function"){return null}return BigInt(e.replace(/_/g,""))}Ie.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var i=this.readInt(e);if(i==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){i=stringToBigInt(this.input.slice(t,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(m.num,i)};Ie.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10,undefined,true)===null){this.raise(t,"Invalid number")}var i=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(i&&this.strict){this.raise(t,"Invalid number")}var s=this.input.charCodeAt(this.pos);if(!i&&!e&&this.options.ecmaVersion>=11&&s===110){var r=stringToBigInt(this.input.slice(t,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(m.num,r)}if(i&&/[89]/.test(this.input.slice(t,this.pos))){i=false}if(s===46&&!i){++this.pos;this.readInt(10);s=this.input.charCodeAt(this.pos)}if((s===69||s===101)&&!i){s=this.input.charCodeAt(++this.pos);if(s===43||s===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var a=stringToNumber(this.input.slice(t,this.pos),i);return this.finishToken(m.num,a)};Ie.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var i=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(i,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Ie.readString=function(e){var t="",i=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var s=this.input.charCodeAt(this.pos);if(s===e){break}if(s===92){t+=this.input.slice(i,this.pos);t+=this.readEscapedChar(false);i=this.pos}else if(s===8232||s===8233){if(this.options.ecmaVersion<10){this.raise(this.start,"Unterminated string constant")}++this.pos;if(this.options.locations){this.curLine++;this.lineStart=this.pos}}else{if(isNewLine(s)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(i,this.pos++);return this.finishToken(m.string,t)};var Ae={};Ie.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===Ae){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};Ie.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw Ae}else{this.raise(e,t)}};Ie.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var i=this.input.charCodeAt(this.pos);if(i===96||i===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===m.template||this.type===m.invalidTemplate)){if(i===36){this.pos+=2;return this.finishToken(m.dollarBraceL)}else{++this.pos;return this.finishToken(m.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(m.template,e)}if(i===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(i)){e+=this.input.slice(t,this.pos);++this.pos;switch(i){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(i);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};Ie.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var s=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var r=parseInt(s,8);if(r>255){s=s.slice(0,-1);r=parseInt(s,8)}this.pos+=s.length-1;t=this.input.charCodeAt(this.pos);if((s!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-s.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(r)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};Ie.readHexChar=function(e){var t=this.pos;var i=this.readInt(16,e);if(i===null){this.invalidStringToken(t,"Bad character escape sequence")}return i};Ie.readWord1=function(){this.containsEsc=false;var e="",t=true,i=this.pos;var s=this.options.ecmaVersion>=6;while(this.pos Date: Wed, 26 Jan 2022 23:17:26 +0100 Subject: [PATCH 05/15] rm unused types --- .../webpack/loaders/next-flight-client-loader.ts | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/packages/next/build/webpack/loaders/next-flight-client-loader.ts b/packages/next/build/webpack/loaders/next-flight-client-loader.ts index 9cce14ac526c..6a916a364e39 100644 --- a/packages/next/build/webpack/loaders/next-flight-client-loader.ts +++ b/packages/next/build/webpack/loaders/next-flight-client-loader.ts @@ -11,19 +11,6 @@ import { parse } from '../../swc' // @ts-ignore import { getBaseSWCOptions } from '../../swc/options' -type ResolveContext = { - conditions: Array - parentURL: string | void -} - -type ResolveFunction = ( - specifier: string, - context: ResolveContext, - resolve: ResolveFunction -) => { url: string } | Promise<{ url: string }> - -let stashedResolve: null | ResolveFunction = null - function addExportNames(names: string[], node: any) { switch (node.type) { case 'Identifier': From 0df1273f2992f949dd5c29ea87841a1098a107d2 Mon Sep 17 00:00:00 2001 From: Jiachi Liu Date: Wed, 26 Jan 2022 23:33:09 +0100 Subject: [PATCH 06/15] add test --- .../test/index.test.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/test/integration/react-streaming-and-server-components/test/index.test.js b/test/integration/react-streaming-and-server-components/test/index.test.js index dfb68408db28..9b556bcea3a5 100644 --- a/test/integration/react-streaming-and-server-components/test/index.test.js +++ b/test/integration/react-streaming-and-server-components/test/index.test.js @@ -400,6 +400,19 @@ async function runBasicTests(context, env) { expect(imageTag.attr('src')).toContain('data:image') }) + it('should handle various exports', async () => { + const clientExportsHTML = await renderViaHTTP( + context.appPort, + '/client-exports' + ) + const $clientExports = cheerio.load(clientExportsHTML) + expect($clientExports('div[hidden] > div').text()).toBe('abcde') + + const browser = await webdriver(context.appPort, '/client-exports') + const text = await browser.waitForElementByCss('#__next').text() + expect(text).toBe('abcde') + }) + it('should support multi-level server component imports', async () => { const html = await renderViaHTTP(context.appPort, '/multi') expect(html).toContain('bar.server.js:') From f880010163150eaef6e5d2234c1cc74d6fb46d0a Mon Sep 17 00:00:00 2001 From: Jiachi Liu Date: Wed, 26 Jan 2022 23:33:36 +0100 Subject: [PATCH 07/15] update compiled --- packages/next/compiled/@vercel/nft/index.js | 6 +- packages/next/compiled/terser/bundle.min.js | 2 +- packages/next/compiled/webpack/bundle5.js | 232416 +++++++++-------- 3 files changed, 118997 insertions(+), 113427 deletions(-) diff --git a/packages/next/compiled/@vercel/nft/index.js b/packages/next/compiled/@vercel/nft/index.js index 734c300cf272..047fab796424 100644 --- a/packages/next/compiled/@vercel/nft/index.js +++ b/packages/next/compiled/@vercel/nft/index.js @@ -1,12 +1,12 @@ -(()=>{var __webpack_modules__={111:(e,t,r)=>{"use strict";e.exports=t;t.mockS3Http=r(7048).get_mockS3Http();t.mockS3Http("on");const a=t.mockS3Http("get");const o=r(7147);const s=r(1017);const u=r(1400);const c=r(9658);c.disableProgress();const d=r(5677);const f=r(2361).EventEmitter;const p=r(3837).inherits;const h=["clean","install","reinstall","build","rebuild","package","testpackage","publish","unpublish","info","testbinary","reveal","configure"];const v={};c.heading="node-pre-gyp";if(a){c.warn(`mocking s3 to ${process.env.node_pre_gyp_mock_s3}`)}Object.defineProperty(t,"find",{get:function(){return r(3093).find},enumerable:true});function Run({package_json_path:e="./package.json",argv:t}){this.package_json_path=e;this.commands={};const r=this;h.forEach((e=>{r.commands[e]=function(t,a){c.verbose("command",e,t);return require("./"+e)(r,t,a)}}));this.parseArgv(t);this.binaryHostSet=false}p(Run,f);t.Run=Run;const _=Run.prototype;_.package=r(9286);_.configDefs={help:Boolean,arch:String,debug:Boolean,directory:String,proxy:String,loglevel:String};_.shorthands={release:"--no-debug",C:"--directory",debug:"--debug",j:"--jobs",silent:"--loglevel=silent",silly:"--loglevel=silly",verbose:"--loglevel=verbose"};_.aliases=v;_.parseArgv=function parseOpts(e){this.opts=u(this.configDefs,this.shorthands,e);this.argv=this.opts.argv.remain.slice();const t=this.todo=[];e=this.argv.map((e=>{if(e in this.aliases){e=this.aliases[e]}return e}));e.slice().forEach((r=>{if(r in this.commands){const a=e.splice(0,e.indexOf(r));e.shift();if(t.length>0){t[t.length-1].args=a}t.push({name:r,args:[]})}}));if(t.length>0){t[t.length-1].args=e.splice(0)}let r=this.package_json_path;if(this.opts.directory){r=s.join(this.opts.directory,r)}this.package_json=JSON.parse(o.readFileSync(r));this.todo=d.expand_commands(this.package_json,this.opts,t);const a="npm_config_";Object.keys(process.env).forEach((e=>{if(e.indexOf(a)!==0)return;const t=process.env[e];if(e===a+"loglevel"){c.level=t}else{e=e.substring(a.length);if(e==="argv"){if(this.opts.argv&&this.opts.argv.remain&&this.opts.argv.remain.length){}else{this.opts[e]=t}}else{this.opts[e]=t}}}));if(this.opts.loglevel){c.level=this.opts.loglevel}c.resume()};_.setBinaryHostProperty=function(e){if(this.binaryHostSet){return this.package_json.binary.host}const t=this.package_json;if(!t||!t.binary||t.binary.host){return""}if(!t.binary.staging_host||!t.binary.production_host){return""}let r="production_host";if(e==="publish"){r="staging_host"}const a=process.env.node_pre_gyp_s3_host;if(a==="staging"||a==="production"){r=`${a}_host`}else if(this.opts["s3_host"]==="staging"||this.opts["s3_host"]==="production"){r=`${this.opts["s3_host"]}_host`}else if(this.opts["s3_host"]||a){throw new Error(`invalid s3_host ${this.opts["s3_host"]||a}`)}t.binary.host=t.binary[r];this.binaryHostSet=true;return t.binary.host};_.usage=function usage(){const e=[""," Usage: node-pre-gyp [options]",""," where is one of:",h.map((e=>" - "+e+" - "+require("./"+e).usage)).join("\n"),"","node-pre-gyp@"+this.version+" "+s.resolve(__dirname,".."),"node@"+process.versions.node].join("\n");return e};Object.defineProperty(_,"version",{get:function(){return this.package.version},enumerable:true})},3093:(e,t,r)=>{"use strict";const a=r(111);const o=r(302);const s=r(5677);const u=r(7147).existsSync||r(1017).existsSync;const c=r(1017);e.exports=t;t.usage="Finds the require path for the node-pre-gyp installed module";t.validate=function(e,t){o.validate_config(e,t)};t.find=function(e,t){if(!u(e)){throw new Error(e+"does not exist")}const r=new a.Run({package_json_path:e,argv:process.argv});r.setBinaryHostProperty();const d=r.package_json;o.validate_config(d,t);let f;if(s.get_napi_build_versions(d,t)){f=s.get_best_napi_build_version(d,t)}t=t||{};if(!t.module_root)t.module_root=c.dirname(e);const p=o.evaluate(d,t,f);return p.module}},5677:(e,t,r)=>{"use strict";const a=r(7147);e.exports=t;const o=process.version.substr(1).replace(/-.*$/,"").split(".").map((e=>+e));const s=["build","clean","configure","package","publish","reveal","testbinary","testpackage","unpublish"];const u="napi_build_version=";e.exports.get_napi_version=function(){let e=process.versions.napi;if(!e){if(o[0]===9&&o[1]>=3)e=2;else if(o[0]===8)e=1}return e};e.exports.get_napi_version_as_string=function(t){const r=e.exports.get_napi_version(t);return r?""+r:""};e.exports.validate_package_json=function(t,r){const a=t.binary;const o=pathOK(a.module_path);const s=pathOK(a.remote_path);const u=pathOK(a.package_name);const c=e.exports.get_napi_build_versions(t,r,true);const d=e.exports.get_napi_build_versions_raw(t);if(c){c.forEach((e=>{if(!(parseInt(e,10)===e&&e>0)){throw new Error("All values specified in napi_versions must be positive integers.")}}))}if(c&&(!o||!s&&!u)){throw new Error("When napi_versions is specified; module_path and either remote_path or "+"package_name must contain the substitution string '{napi_build_version}`.")}if((o||s||u)&&!d){throw new Error("When the substitution string '{napi_build_version}` is specified in "+"module_path, remote_path, or package_name; napi_versions must also be specified.")}if(c&&!e.exports.get_best_napi_build_version(t,r)&&e.exports.build_napi_only(t)){throw new Error("The Node-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports Node-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}if(d&&!c&&e.exports.build_napi_only(t)){throw new Error("The Node-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports Node-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}};function pathOK(e){return e&&(e.indexOf("{napi_build_version}")!==-1||e.indexOf("{node_napi_label}")!==-1)}e.exports.expand_commands=function(t,r,a){const o=[];const c=e.exports.get_napi_build_versions(t,r);a.forEach((a=>{if(c&&a.name==="install"){const s=e.exports.get_best_napi_build_version(t,r);const c=s?[u+s]:[];o.push({name:a.name,args:c})}else if(c&&s.indexOf(a.name)!==-1){c.forEach((e=>{const t=a.args.slice();t.push(u+e);o.push({name:a.name,args:t})}))}else{o.push(a)}}));return o};e.exports.get_napi_build_versions=function(t,a,o){const s=r(9658);let u=[];const c=e.exports.get_napi_version(a?a.target:undefined);if(t.binary&&t.binary.napi_versions){t.binary.napi_versions.forEach((e=>{const t=u.indexOf(e)!==-1;if(!t&&c&&e<=c){u.push(e)}else if(o&&!t&&c){s.info("This Node instance does not support builds for Node-API version",e)}}))}if(a&&a["build-latest-napi-version-only"]){let e=0;u.forEach((t=>{if(t>e)e=t}));u=e?[e]:[]}return u.length?u:undefined};e.exports.get_napi_build_versions_raw=function(e){const t=[];if(e.binary&&e.binary.napi_versions){e.binary.napi_versions.forEach((e=>{if(t.indexOf(e)===-1){t.push(e)}}))}return t.length?t:undefined};e.exports.get_command_arg=function(e){return u+e};e.exports.get_napi_build_version_from_command_args=function(e){for(let t=0;t{if(e>a&&e<=t){a=e}}))}return a===0?undefined:a};e.exports.build_napi_only=function(e){return e.binary&&e.binary.package_name&&e.binary.package_name.indexOf("{node_napi_label}")===-1}},7048:(e,t,r)=>{"use strict";e.exports=t;const a=r(7310);const o=r(7147);const s=r(1017);e.exports.detect=function(e,t){const r=e.hosted_path;const o=a.parse(r);t.prefix=!o.pathname||o.pathname==="/"?"":o.pathname.replace("/","");if(e.bucket&&e.region){t.bucket=e.bucket;t.region=e.region;t.endpoint=e.host;t.s3ForcePathStyle=e.s3ForcePathStyle}else{const e=o.hostname.split(".s3");const r=e[0];if(!r){return}if(!t.bucket){t.bucket=r}if(!t.region){const r=e[1].slice(1).split(".")[0];if(r==="amazonaws"){t.region="us-east-1"}else{t.region=r}}}};e.exports.get_s3=function(e){if(process.env.node_pre_gyp_mock_s3){const e=r(2722);const t=r(2037);e.config.basePath=`${t.tmpdir()}/mock`;const a=e.S3();const wcb=e=>(t,...r)=>{if(t&&t.code==="ENOENT"){t.code="NotFound"}return e(t,...r)};return{listObjects(e,t){return a.listObjects(e,wcb(t))},headObject(e,t){return a.headObject(e,wcb(t))},deleteObject(e,t){return a.deleteObject(e,wcb(t))},putObject(e,t){return a.putObject(e,wcb(t))}}}const t=r(918);t.config.update(e);const a=new t.S3;return{listObjects(e,t){return a.listObjects(e,t)},headObject(e,t){return a.headObject(e,t)},deleteObject(e,t){return a.deleteObject(e,t)},putObject(e,t){return a.putObject(e,t)}}};e.exports.get_mockS3Http=function(){let e=false;if(!process.env.node_pre_gyp_mock_s3){return()=>e}const t=r(3902);const a="https://mapbox-node-pre-gyp-public-testing-bucket.s3.us-east-1.amazonaws.com";const u=process.env.node_pre_gyp_mock_s3+"/mapbox-node-pre-gyp-public-testing-bucket";const mock_http=()=>{function get(e,t){const r=s.join(u,e.replace("%2B","+"));try{o.accessSync(r,o.constants.R_OK)}catch(e){return[404,"not found\n"]}return[200,o.createReadStream(r)]}return t(a).persist().get((()=>e)).reply(get)};mock_http(t,a,u);const mockS3Http=t=>{const r=e;if(t==="off"){e=false}else if(t==="on"){e=true}else if(t!=="get"){throw new Error(`illegal action for setMockHttp ${t}`)}return r};return mockS3Http}},302:(e,t,r)=>{"use strict";e.exports=t;const a=r(1017);const o=r(7849);const s=r(7310);const u=r(2157);const c=r(5677);let d;if(process.env.NODE_PRE_GYP_ABI_CROSSWALK){d=require(process.env.NODE_PRE_GYP_ABI_CROSSWALK)}else{d=r(2339)}const f={};Object.keys(d).forEach((e=>{const t=e.split(".")[0];if(!f[t]){f[t]=e}}));function get_electron_abi(e,t){if(!e){throw new Error("get_electron_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if electron is the target.")}const r=o.parse(t);return e+"-v"+r.major+"."+r.minor}e.exports.get_electron_abi=get_electron_abi;function get_node_webkit_abi(e,t){if(!e){throw new Error("get_node_webkit_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if node-webkit is the target.")}return e+"-v"+t}e.exports.get_node_webkit_abi=get_node_webkit_abi;function get_node_abi(e,t){if(!e){throw new Error("get_node_abi requires valid runtime arg")}if(!t){throw new Error("get_node_abi requires valid process.versions object")}const r=o.parse(t.node);if(r.major===0&&r.minor%2){return e+"-v"+t.node}else{return t.modules?e+"-v"+ +t.modules:"v8-"+t.v8.split(".").slice(0,2).join(".")}}e.exports.get_node_abi=get_node_abi;function get_runtime_abi(e,t){if(!e){throw new Error("get_runtime_abi requires valid runtime arg")}if(e==="node-webkit"){return get_node_webkit_abi(e,t||process.versions["node-webkit"])}else if(e==="electron"){return get_electron_abi(e,t||process.versions.electron)}else{if(e!=="node"){throw new Error("Unknown Runtime: '"+e+"'")}if(!t){return get_node_abi(e,process.versions)}else{let r;if(d[t]){r=d[t]}else{const e=t.split(".").map((e=>+e));if(e.length!==3){throw new Error("Unknown target version: "+t)}const a=e[0];let o=e[1];let s=e[2];if(a===1){while(true){if(o>0)--o;if(s>0)--s;const e=""+a+"."+o+"."+s;if(d[e]){r=d[e];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+e+" as ABI compatible target");break}if(o===0&&s===0){break}}}else if(a>=2){if(f[a]){r=d[f[a]];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+f[a]+" as ABI compatible target")}}else if(a===0){if(e[1]%2===0){while(--s>0){const e=""+a+"."+o+"."+s;if(d[e]){r=d[e];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+e+" as ABI compatible target");break}}}}}if(!r){throw new Error("Unsupported target version: "+t)}const a={node:t,v8:r.v8+".0",modules:r.node_abi>1?r.node_abi:undefined};return get_node_abi(e,a)}}}e.exports.get_runtime_abi=get_runtime_abi;const p=["module_name","module_path","host"];function validate_config(e,t){const r=e.name+" package.json is not node-pre-gyp ready:\n";const a=[];if(!e.main){a.push("main")}if(!e.version){a.push("version")}if(!e.name){a.push("name")}if(!e.binary){a.push("binary")}const o=e.binary;if(o){p.forEach((e=>{if(!o[e]||typeof o[e]!=="string"){a.push("binary."+e)}}))}if(a.length>=1){throw new Error(r+"package.json must declare these properties: \n"+a.join("\n"))}if(o){const e=s.parse(o.host).protocol;if(e==="http:"){throw new Error("'host' protocol ("+e+") is invalid - only 'https:' is accepted")}}c.validate_package_json(e,t)}e.exports.validate_config=validate_config;function eval_template(e,t){Object.keys(t).forEach((r=>{const a="{"+r+"}";while(e.indexOf(a)>-1){e=e.replace(a,t[r])}}));return e}function fix_slashes(e){if(e.slice(-1)!=="/"){return e+"/"}return e}function drop_double_slashes(e){return e.replace(/\/\//g,"/")}function get_process_runtime(e){let t="node";if(e["node-webkit"]){t="node-webkit"}else if(e.electron){t="electron"}return t}e.exports.get_process_runtime=get_process_runtime;const h="{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz";const v="";e.exports.evaluate=function(e,t,r){t=t||{};validate_config(e,t);const d=e.version;const f=o.parse(d);const p=t.runtime||get_process_runtime(process.versions);const _={name:e.name,configuration:t.debug?"Debug":"Release",debug:t.debug,module_name:e.binary.module_name,version:f.version,prerelease:f.prerelease.length?f.prerelease.join("."):"",build:f.build.length?f.build.join("."):"",major:f.major,minor:f.minor,patch:f.patch,runtime:p,node_abi:get_runtime_abi(p,t.target),node_abi_napi:c.get_napi_version(t.target)?"napi":get_runtime_abi(p,t.target),napi_version:c.get_napi_version(t.target),napi_build_version:r||"",node_napi_label:r?"napi-v"+r:get_runtime_abi(p,t.target),target:t.target||"",platform:t.target_platform||process.platform,target_platform:t.target_platform||process.platform,arch:t.target_arch||process.arch,target_arch:t.target_arch||process.arch,libc:t.target_libc||u.family||"unknown",module_main:e.main,toolset:t.toolset||"",bucket:e.binary.bucket,region:e.binary.region,s3ForcePathStyle:e.binary.s3ForcePathStyle||false};const g=_.module_name.replace("-","_");const y=process.env["npm_config_"+g+"_binary_host_mirror"]||e.binary.host;_.host=fix_slashes(eval_template(y,_));_.module_path=eval_template(e.binary.module_path,_);if(t.module_root){_.module_path=a.join(t.module_root,_.module_path)}else{_.module_path=a.resolve(_.module_path)}_.module=a.join(_.module_path,_.module_name+".node");_.remote_path=e.binary.remote_path?drop_double_slashes(fix_slashes(eval_template(e.binary.remote_path,_))):v;const m=e.binary.package_name?e.binary.package_name:h;_.package_name=eval_template(m,_);_.staged_tarball=a.join("build/stage",_.remote_path,_.package_name);_.hosted_path=s.resolve(_.host,_.remote_path);_.hosted_tarball=s.resolve(_.hosted_path,_.package_name);return _}},1400:(e,t,r)=>{var a=process.env.DEBUG_NOPT||process.env.NOPT_DEBUG?function(){console.error.apply(console,arguments)}:function(){};var o=r(7310),s=r(1017),u=r(2781).Stream,c=r(5920),d=r(2037);e.exports=t=nopt;t.clean=clean;t.typeDefs={String:{type:String,validate:validateString},Boolean:{type:Boolean,validate:validateBoolean},url:{type:o,validate:validateUrl},Number:{type:Number,validate:validateNumber},path:{type:s,validate:validatePath},Stream:{type:u,validate:validateStream},Date:{type:Date,validate:validateDate}};function nopt(e,r,o,s){o=o||process.argv;e=e||{};r=r||{};if(typeof s!=="number")s=2;a(e,r,o,s);o=o.slice(s);var u={},c,d={remain:[],cooked:o,original:o.slice(0)};parse(o,u,d.remain,e,r);clean(u,e,t.typeDefs);u.argv=d;Object.defineProperty(u.argv,"toString",{value:function(){return this.original.map(JSON.stringify).join(" ")},enumerable:false});return u}function clean(e,r,o){o=o||t.typeDefs;var s={},u=[false,true,null,String,Array];Object.keys(e).forEach((function(c){if(c==="argv")return;var d=e[c],f=Array.isArray(d),p=r[c];if(!f)d=[d];if(!p)p=u;if(p===Array)p=u.concat(Array);if(!Array.isArray(p))p=[p];a("val=%j",d);a("types=",p);d=d.map((function(u){if(typeof u==="string"){a("string %j",u);u=u.trim();if(u==="null"&&~p.indexOf(null)||u==="true"&&(~p.indexOf(true)||~p.indexOf(Boolean))||u==="false"&&(~p.indexOf(false)||~p.indexOf(Boolean))){u=JSON.parse(u);a("jsonable %j",u)}else if(~p.indexOf(Number)&&!isNaN(u)){a("convert to number",u);u=+u}else if(~p.indexOf(Date)&&!isNaN(Date.parse(u))){a("convert to date",u);u=new Date(u)}}if(!r.hasOwnProperty(c)){return u}if(u===false&&~p.indexOf(null)&&!(~p.indexOf(false)||~p.indexOf(Boolean))){u=null}var d={};d[c]=u;a("prevalidated val",d,u,r[c]);if(!validate(d,c,u,r[c],o)){if(t.invalidHandler){t.invalidHandler(c,u,r[c],e)}else if(t.invalidHandler!==false){a("invalid: "+c+"="+u,r[c])}return s}a("validated val",d,u,r[c]);return d[c]})).filter((function(e){return e!==s}));if(!d.length&&p.indexOf(Array)===-1){a("VAL HAS NO LENGTH, DELETE IT",d,c,p.indexOf(Array));delete e[c]}else if(f){a(f,e[c],d);e[c]=d}else e[c]=d[0];a("k=%s val=%j",c,d,e[c])}))}function validateString(e,t,r){e[t]=String(r)}function validatePath(e,t,r){if(r===true)return false;if(r===null)return true;r=String(r);var a=process.platform==="win32",o=a?/^~(\/|\\)/:/^~\//,u=d.homedir();if(u&&r.match(o)){e[t]=s.resolve(u,r.substr(2))}else{e[t]=s.resolve(r)}return true}function validateNumber(e,t,r){a("validate Number %j %j %j",t,r,isNaN(r));if(isNaN(r))return false;e[t]=+r}function validateDate(e,t,r){var o=Date.parse(r);a("validate Date %j %j %j",t,r,o);if(isNaN(o))return false;e[t]=new Date(r)}function validateBoolean(e,t,r){if(r instanceof Boolean)r=r.valueOf();else if(typeof r==="string"){if(!isNaN(r))r=!!+r;else if(r==="null"||r==="false")r=false;else r=true}else r=!!r;e[t]=r}function validateUrl(e,t,r){r=o.parse(String(r));if(!r.host)return false;e[t]=r.href}function validateStream(e,t,r){if(!(r instanceof u))return false;e[t]=r}function validate(e,t,r,o,s){if(Array.isArray(o)){for(var u=0,c=o.length;u1){var _=h.indexOf("=");if(_>-1){v=true;var g=h.substr(_+1);h=h.substr(0,_);e.splice(p,1,h,g)}var y=resolveShort(h,s,f,d);a("arg=%j shRes=%j",h,y);if(y){a(h,y);e.splice.apply(e,[p,1].concat(y));if(h!==y[0]){p--;continue}}h=h.replace(/^-+/,"");var m=null;while(h.toLowerCase().indexOf("no-")===0){m=!m;h=h.substr(3)}if(d[h])h=d[h];var w=o[h];var x=Array.isArray(w);if(x&&w.length===1){x=false;w=w[0]}var E=w===Array||x&&w.indexOf(Array)!==-1;if(!o.hasOwnProperty(h)&&t.hasOwnProperty(h)){if(!Array.isArray(t[h]))t[h]=[t[h]];E=true}var S,k=e[p+1];var R=typeof m==="boolean"||w===Boolean||x&&w.indexOf(Boolean)!==-1||typeof w==="undefined"&&!v||k==="false"&&(w===null||x&&~w.indexOf(null));if(R){S=!m;if(k==="true"||k==="false"){S=JSON.parse(k);k=null;if(m)S=!S;p++}if(x&&k){if(~w.indexOf(k)){S=k;p++}else if(k==="null"&&~w.indexOf(null)){S=null;p++}else if(!k.match(/^-{2,}[^-]/)&&!isNaN(k)&&~w.indexOf(Number)){S=+k;p++}else if(!k.match(/^-[^-]/)&&~w.indexOf(String)){S=k;p++}}if(E)(t[h]=t[h]||[]).push(S);else t[h]=S;continue}if(w===String){if(k===undefined){k=""}else if(k.match(/^-{1,2}[^-]+/)){k="";p--}}if(k&&k.match(/^-{2,}$/)){k=undefined;p--}S=k===undefined?true:k;if(E)(t[h]=t[h]||[]).push(S);else t[h]=S;p++;continue}r.push(h)}}function resolveShort(e,t,r,o){e=e.replace(/^-+/,"");if(o[e]===e)return null;if(t[e]){if(t[e]&&!Array.isArray(t[e]))t[e]=t[e].split(/\s+/);return t[e]}var s=t.___singles;if(!s){s=Object.keys(t).filter((function(e){return e.length===1})).reduce((function(e,t){e[t]=true;return e}),{});t.___singles=s;a("shorthand singles",s)}var u=e.split("").filter((function(e){return s[e]}));if(u.join("")===e)return u.map((function(e){return t[e]})).reduce((function(e,t){return e.concat(t)}),[]);if(o[e]&&!t[e])return null;if(r[e])e=r[e];if(t[e]&&!Array.isArray(t[e]))t[e]=t[e].split(/\s+/);return t[e]}},6286:(e,t,r)=>{const a=r(9491);const o=r(1017);const s=r(7147);let u=undefined;try{u=r(3535)}catch(e){}const c={nosort:true,silent:true};let d=0;const f=process.platform==="win32";const defaults=e=>{const t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach((t=>{e[t]=e[t]||s[t];t=t+"Sync";e[t]=e[t]||s[t]}));e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&u===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||c};const rimraf=(e,t,r)=>{if(typeof t==="function"){r=t;t={}}a(e,"rimraf: missing path");a.equal(typeof e,"string","rimraf: path should be a string");a.equal(typeof r,"function","rimraf: callback function required");a(t,"rimraf: invalid options argument provided");a.equal(typeof t,"object","rimraf: options should be object");defaults(t);let o=0;let s=null;let c=0;const next=e=>{s=s||e;if(--c===0)r(s)};const afterGlob=(e,a)=>{if(e)return r(e);c=a.length;if(c===0)return r();a.forEach((e=>{const CB=r=>{if(r){if((r.code==="EBUSY"||r.code==="ENOTEMPTY"||r.code==="EPERM")&&orimraf_(e,t,CB)),o*100)}if(r.code==="EMFILE"&&drimraf_(e,t,CB)),d++)}if(r.code==="ENOENT")r=null}d=0;next(r)};rimraf_(e,t,CB)}))};if(t.disableGlob||!u.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,((r,a)=>{if(!r)return afterGlob(null,[e]);u(e,t.glob,afterGlob)}))};const rimraf_=(e,t,r)=>{a(e);a(t);a(typeof r==="function");t.lstat(e,((a,o)=>{if(a&&a.code==="ENOENT")return r(null);if(a&&a.code==="EPERM"&&f)fixWinEPERM(e,t,a,r);if(o&&o.isDirectory())return rmdir(e,t,a,r);t.unlink(e,(a=>{if(a){if(a.code==="ENOENT")return r(null);if(a.code==="EPERM")return f?fixWinEPERM(e,t,a,r):rmdir(e,t,a,r);if(a.code==="EISDIR")return rmdir(e,t,a,r)}return r(a)}))}))};const fixWinEPERM=(e,t,r,o)=>{a(e);a(t);a(typeof o==="function");t.chmod(e,438,(a=>{if(a)o(a.code==="ENOENT"?null:r);else t.stat(e,((a,s)=>{if(a)o(a.code==="ENOENT"?null:r);else if(s.isDirectory())rmdir(e,t,r,o);else t.unlink(e,o)}))}))};const fixWinEPERMSync=(e,t,r)=>{a(e);a(t);try{t.chmodSync(e,438)}catch(e){if(e.code==="ENOENT")return;else throw r}let o;try{o=t.statSync(e)}catch(e){if(e.code==="ENOENT")return;else throw r}if(o.isDirectory())rmdirSync(e,t,r);else t.unlinkSync(e)};const rmdir=(e,t,r,o)=>{a(e);a(t);a(typeof o==="function");t.rmdir(e,(a=>{if(a&&(a.code==="ENOTEMPTY"||a.code==="EEXIST"||a.code==="EPERM"))rmkids(e,t,o);else if(a&&a.code==="ENOTDIR")o(r);else o(a)}))};const rmkids=(e,t,r)=>{a(e);a(t);a(typeof r==="function");t.readdir(e,((a,s)=>{if(a)return r(a);let u=s.length;if(u===0)return t.rmdir(e,r);let c;s.forEach((a=>{rimraf(o.join(e,a),t,(a=>{if(c)return;if(a)return r(c=a);if(--u===0)t.rmdir(e,r)}))}))}))};const rimrafSync=(e,t)=>{t=t||{};defaults(t);a(e,"rimraf: missing path");a.equal(typeof e,"string","rimraf: path should be a string");a(t,"rimraf: missing options");a.equal(typeof t,"object","rimraf: options should be object");let r;if(t.disableGlob||!u.hasMagic(e)){r=[e]}else{try{t.lstatSync(e);r=[e]}catch(a){r=u.sync(e,t.glob)}}if(!r.length)return;for(let e=0;e{a(e);a(t);try{t.rmdirSync(e)}catch(a){if(a.code==="ENOENT")return;if(a.code==="ENOTDIR")throw r;if(a.code==="ENOTEMPTY"||a.code==="EEXIST"||a.code==="EPERM")rmkidsSync(e,t)}};const rmkidsSync=(e,t)=>{a(e);a(t);t.readdirSync(e).forEach((r=>rimrafSync(o.join(e,r),t)));const r=f?100:1;let s=0;do{let a=true;try{const o=t.rmdirSync(e,t);a=false;return o}finally{if(++sq,env:{NODE_ENV:u.UNKNOWN,[u.UNKNOWN]:true},[u.UNKNOWN]:true};const T=Symbol();const C=Symbol();const j=Symbol();const N=Symbol();const L=Symbol();const I=Symbol();const P=Symbol();const D=Symbol();const M={access:I,accessSync:I,createReadStream:I,exists:I,existsSync:I,fstat:I,fstatSync:I,lstat:I,lstatSync:I,open:I,readFile:I,readFileSync:I,stat:I,statSync:I};const W=Object.assign(Object.create(null),{bindings:{default:P},express:{default:function(){return{[u.UNKNOWN]:true,set:T,engine:C}}},fs:Object.assign({default:M},M),process:Object.assign({default:O},O),path:{default:{}},os:Object.assign({default:k.default},k.default),"@mapbox/node-pre-gyp":Object.assign({default:w.default},w.default),"node-pre-gyp":v.pregyp,"node-pre-gyp/lib/pre-binding":v.pregyp,"node-pre-gyp/lib/pre-binding.js":v.pregyp,"node-gyp-build":{default:D},nbind:{init:j,default:{init:j}},"resolve-from":{default:A.default},"strong-globalize":{default:{SetRootDir:N},SetRootDir:N},pkginfo:{default:L}});const F={_interopRequireDefault:_.normalizeDefaultRequire,_interopRequireWildcard:_.normalizeWildcardRequire,__importDefault:_.normalizeDefaultRequire,__importStar:_.normalizeWildcardRequire,MONGOOSE_DRIVER_PATH:undefined,URL:x.URL,Object:{assign:Object.assign}};F.global=F.GLOBAL=F.globalThis=F;const B=Symbol();v.pregyp.find[B]=true;const $=W.path;Object.keys(o.default).forEach((e=>{const t=o.default[e];if(typeof t==="function"){const r=function mockPath(){return t.apply(mockPath,arguments)};r[B]=true;$[e]=$.default[e]=r}else{$[e]=$.default[e]=t}}));$.resolve=$.default.resolve=function(...e){return o.default.resolve.apply(this,[q,...e])};$.resolve[B]=true;const U=new Set([".h",".cmake",".c",".cpp"]);const H=new Set(["CHANGELOG.md","README.md","readme.md","changelog.md"]);let q;const G=/^\/[^\/]+|^[a-z]:[\\/][^\\/]+/i;function isAbsolutePathOrUrl(e){if(e instanceof x.URL)return e.protocol==="file:";if(typeof e==="string"){if(e.startsWith("file:")){try{new x.URL(e);return true}catch(e){return false}}return G.test(e)}return false}const K=Symbol();const z=/([\/\\]\*\*[\/\\]\*)+/g;async function analyze(e,t,r){const a=new Set;const c=new Set;const _=new Set;const w=o.default.dirname(e);q=r.cwd;const k=h.getPackageBase(e);const emitAssetDirectory=e=>{if(!r.analysis.emitGlobs)return;const t=e.indexOf(u.WILDCARD);const s=t===-1?e.length:e.lastIndexOf(o.default.sep,t);const c=e.substr(0,s);const d=e.substr(s);const f=d.replace(u.wildcardRegEx,((e,t)=>d[t-1]===o.default.sep?"**/*":"*")).replace(z,"/**/*")||"/**/*";if(r.ignoreFn(o.default.relative(r.base,c+f)))return;A=A.then((async()=>{if(r.log)console.log("Globbing "+c+f);const e=await new Promise(((e,t)=>p.default(c+f,{mark:true,ignore:c+"/**/node_modules/**/*"},((r,a)=>r?t(r):e(a)))));e.filter((e=>!U.has(o.default.extname(e))&&!H.has(o.default.basename(e))&&!e.endsWith("/"))).forEach((e=>a.add(e)))}))};let A=Promise.resolve();t=t.replace(/^#![^\n\r]*[\r\n]/,"");let M;let $=false;try{M=S.parse(t,{ecmaVersion:"latest",allowReturnOutsideFunction:true});$=false}catch(t){const a=t&&t.message&&t.message.includes("sourceType: module");if(!a){r.warnings.add(new Error(`Failed to parse ${e} as script:\n${t&&t.message}`))}}if(!M){try{M=S.parse(t,{ecmaVersion:"latest",sourceType:"module",allowAwaitOutsideFunction:true});$=true}catch(t){r.warnings.add(new Error(`Failed to parse ${e} as module:\n${t&&t.message}`));return{assets:a,deps:c,imports:_,isESM:false}}}const V=x.pathToFileURL(e).href;const Y=Object.assign(Object.create(null),{__dirname:{shadowDepth:0,value:{value:o.default.resolve(e,"..")}},__filename:{shadowDepth:0,value:{value:e}},process:{shadowDepth:0,value:{value:O}}});if(!$||r.mixedModules){Y.require={shadowDepth:0,value:{value:{[u.FUNCTION](e){c.add(e);const t=W[e];return t.default},resolve(t){return y.default(t,e,r)}}}};Y.require.value.value.resolve[B]=true}function setKnownBinding(e,t){if(e==="require")return;Y[e]={shadowDepth:0,value:t}}function getKnownBinding(e){const t=Y[e];if(t){if(t.shadowDepth===0){return t.value}}return undefined}function hasKnownBindingValue(e){const t=Y[e];return t&&t.shadowDepth===0}if(($||r.mixedModules)&&isAst(M)){for(const e of M.body){if(e.type==="ImportDeclaration"){const t=String(e.source.value);c.add(t);const r=W[t];if(r){for(const t of e.specifiers){if(t.type==="ImportNamespaceSpecifier")setKnownBinding(t.local.name,{value:r});else if(t.type==="ImportDefaultSpecifier"&&"default"in r)setKnownBinding(t.local.name,{value:r.default});else if(t.type==="ImportSpecifier"&&t.imported.name in r)setKnownBinding(t.local.name,{value:r[t.imported.name]})}}}else if(e.type==="ExportNamedDeclaration"||e.type==="ExportAllDeclaration"){if(e.source)c.add(String(e.source.value))}}}async function computePureStaticValue(e,t=true){const r=Object.create(null);Object.keys(F).forEach((e=>{r[e]={value:F[e]}}));Object.keys(Y).forEach((e=>{r[e]=getKnownBinding(e)}));r["import.meta"]={url:V};const a=await u.evaluate(e,r,t);return a}let Q;let X;let Z=false;function emitWildcardRequire(e){if(!r.analysis.emitGlobs||!e.startsWith("./")&&!e.startsWith("../"))return;e=o.default.resolve(w,e);const t=e.indexOf(u.WILDCARD);const s=t===-1?e.length:e.lastIndexOf(o.default.sep,t);const c=e.substr(0,s);const d=e.substr(s);let f=d.replace(u.wildcardRegEx,((e,t)=>d[t-1]===o.default.sep?"**/*":"*"))||"/**/*";if(!f.endsWith("*"))f+="?("+(r.ts?".ts|.tsx|":"")+".js|.json|.node)";if(r.ignoreFn(o.default.relative(r.base,c+f)))return;A=A.then((async()=>{if(r.log)console.log("Globbing "+c+f);const e=await new Promise(((e,t)=>p.default(c+f,{mark:true,ignore:c+"/**/node_modules/**/*"},((r,a)=>r?t(r):e(a)))));e.filter((e=>!U.has(o.default.extname(e))&&!H.has(o.default.basename(e))&&!e.endsWith("/"))).forEach((e=>a.add(e)))}))}async function processRequireArg(e,t=false){if(e.type==="ConditionalExpression"){await processRequireArg(e.consequent,t);await processRequireArg(e.alternate,t);return}if(e.type==="LogicalExpression"){await processRequireArg(e.left,t);await processRequireArg(e.right,t);return}let r=await computePureStaticValue(e,true);if(!r)return;if("value"in r&&typeof r.value==="string"){if(!r.wildcards)(t?_:c).add(r.value);else if(r.wildcards.length>=1)emitWildcardRequire(r.value)}else{if("then"in r&&typeof r.then==="string")(t?_:c).add(r.then);if("else"in r&&typeof r.else==="string")(t?_:c).add(r.else)}}let J=s.attachScopes(M,"scope");if(isAst(M)){R.handleWrappers(M);await g.default({id:e,ast:M,emitAsset:e=>a.add(e),emitAssetDirectory:emitAssetDirectory,job:r})}async function backtrack(e,t){if(!Q)throw new Error("Internal error: No staticChildNode for backtrack.");const r=await computePureStaticValue(e,true);if(r){if("value"in r&&typeof r.value!=="symbol"||"then"in r&&typeof r.then!=="symbol"&&typeof r.else!=="symbol"){X=r;Q=e;if(t)t.skip();return}}await emitStaticChildAsset()}await E(M,{async enter(t,s){var u;const p=t;const h=s;if(p.scope){J=p.scope;for(const e in p.scope.declarations){if(e in Y)Y[e].shadowDepth++}}if(Q)return;if(!h)return;if(p.type==="Identifier"){if(f.isIdentifierRead(p,h)&&r.analysis.computeFileReferences){let e;if(typeof(e=(u=getKnownBinding(p.name))===null||u===void 0?void 0:u.value)==="string"&&e.match(G)||e&&(typeof e==="function"||typeof e==="object")&&e[B]){X={value:typeof e==="string"?e:undefined};Q=p;await backtrack(h,this)}}}else if(r.analysis.computeFileReferences&&p.type==="MemberExpression"&&p.object.type==="MetaProperty"&&p.object.meta.name==="import"&&p.object.property.name==="meta"&&(p.property.computed?p.property.value:p.property.name)==="url"){X={value:V};Q=p;await backtrack(h,this)}else if(p.type==="ImportExpression"){await processRequireArg(p.source,true);return}else if(p.type==="CallExpression"){if((!$||r.mixedModules)&&p.callee.type==="Identifier"&&p.arguments.length){if(p.callee.name==="require"&&Y.require.shadowDepth===0){await processRequireArg(p.arguments[0]);return}}else if((!$||r.mixedModules)&&p.callee.type==="MemberExpression"&&p.callee.object.type==="Identifier"&&p.callee.object.name==="module"&&"module"in Y===false&&p.callee.property.type==="Identifier"&&!p.callee.computed&&p.callee.property.name==="require"&&p.arguments.length){await processRequireArg(p.arguments[0]);return}const t=r.analysis.evaluatePureExpressions&&await computePureStaticValue(p.callee,false);if(t&&"value"in t&&typeof t.value==="function"&&t.value[B]&&r.analysis.computeFileReferences){X=await computePureStaticValue(p,true);if(X&&h){Q=p;await backtrack(h,this)}}else if(t&&"value"in t&&typeof t.value==="symbol"){switch(t.value){case K:if(p.arguments.length===1&&p.arguments[0].type==="Literal"&&p.callee.type==="Identifier"&&Y.require.shadowDepth===0){await processRequireArg(p.arguments[0])}break;case P:if(p.arguments.length){const e=await computePureStaticValue(p.arguments[0],false);if(e&&"value"in e&&e.value){let t;if(typeof e.value==="object")t=e.value;else if(typeof e.value==="string")t={bindings:e.value};if(!t.path){t.path=true}t.module_root=k;let r;try{r=d.default(t)}catch(e){}if(r){X={value:r};Q=p;await emitStaticChildAsset()}}}break;case D:if(p.arguments.length===1&&p.arguments[0].type==="Identifier"&&p.arguments[0].name==="__dirname"&&Y.__dirname.shadowDepth===0){let e;try{e=m.default.path(w)}catch(e){}if(e){X={value:e};Q=p;await emitStaticChildAsset()}}break;case j:if(p.arguments.length){const e=await computePureStaticValue(p.arguments[0],false);if(e&&"value"in e&&(typeof e.value==="string"||typeof e.value==="undefined")){const t=v.nbind(e.value);if(t&&t.path){c.add(o.default.relative(w,t.path).replace(/\\/g,"/"));return this.skip()}}}break;case T:if(p.arguments.length===2&&p.arguments[0].type==="Literal"&&p.arguments[0].value==="view engine"&&!Z){await processRequireArg(p.arguments[1]);return this.skip()}break;case C:Z=true;break;case I:if(p.arguments[0]&&r.analysis.computeFileReferences){X=await computePureStaticValue(p.arguments[0],true);if(X){Q=p.arguments[0];await backtrack(h,this);return this.skip()}}break;case N:if(p.arguments[0]){const e=await computePureStaticValue(p.arguments[0],false);if(e&&"value"in e&&e.value)emitAssetDirectory(e.value+"/intl");return this.skip()}break;case L:let t=o.default.resolve(e,"../package.json");const s=o.default.resolve("/package.json");while(t!==s&&await r.stat(t)===null)t=o.default.resolve(t,"../../package.json");if(t!==s)a.add(t);break}}}else if(p.type==="VariableDeclaration"&&h&&!f.isVarLoop(h)&&r.analysis.evaluatePureExpressions){for(const e of p.declarations){if(!e.init)continue;const t=await computePureStaticValue(e.init,true);if(t){if(e.id.type==="Identifier"){setKnownBinding(e.id.name,t)}else if(e.id.type==="ObjectPattern"&&"value"in t){for(const r of e.id.properties){if(r.type!=="Property"||r.key.type!=="Identifier"||r.value.type!=="Identifier"||typeof t.value!=="object"||t.value===null||!(r.key.name in t.value))continue;setKnownBinding(r.value.name,{value:t.value[r.key.name]})}}if(!("value"in t)&&isAbsolutePathOrUrl(t.then)&&isAbsolutePathOrUrl(t.else)){X=t;Q=e.init;await emitStaticChildAsset()}}}}else if(p.type==="AssignmentExpression"&&h&&!f.isLoop(h)&&r.analysis.evaluatePureExpressions){if(!hasKnownBindingValue(p.left.name)){const e=await computePureStaticValue(p.right,false);if(e&&"value"in e){if(p.left.type==="Identifier"){setKnownBinding(p.left.name,e)}else if(p.left.type==="ObjectPattern"){for(const t of p.left.properties){if(t.type!=="Property"||t.key.type!=="Identifier"||t.value.type!=="Identifier"||typeof e.value!=="object"||e.value===null||!(t.key.name in e.value))continue;setKnownBinding(t.value.name,{value:e.value[t.key.name]})}}if(isAbsolutePathOrUrl(e.value)){X=e;Q=p.right;await emitStaticChildAsset()}}}}else if((!$||r.mixedModules)&&(p.type==="FunctionDeclaration"||p.type==="FunctionExpression"||p.type==="ArrowFunctionExpression")&&(p.arguments||p.params)[0]&&(p.arguments||p.params)[0].type==="Identifier"){let e;let t;if((p.type==="ArrowFunctionExpression"||p.type==="FunctionExpression")&&h&&h.type==="VariableDeclarator"&&h.id.type==="Identifier"){e=h.id;t=p.arguments||p.params}else if(p.id){e=p.id;t=p.arguments||p.params}if(e&&p.body.body){let r,a=false;for(let e=0;ee&&e.id&&e.id.type==="Identifier"&&e.init&&e.init.type==="CallExpression"&&e.init.callee.type==="Identifier"&&e.init.callee.name==="require"&&Y.require.shadowDepth===0&&e.init.arguments[0]&&e.init.arguments[0].type==="Identifier"&&e.init.arguments[0].name===t[0].name))}if(r&&p.body.body[e].type==="ReturnStatement"&&p.body.body[e].argument&&p.body.body[e].argument.type==="Identifier"&&p.body.body[e].argument.name===r.id.name){a=true;break}}if(a)setKnownBinding(e.name,{value:K})}}},async leave(e,t){const r=e;const a=t;if(r.scope){if(J.parent){J=J.parent}for(const e in r.scope.declarations){if(e in Y){if(Y[e].shadowDepth>0)Y[e].shadowDepth--;else delete Y[e]}}}if(Q&&a)await backtrack(a,this)}});await A;return{assets:a,deps:c,imports:_,isESM:$};async function emitAssetPath(e){const t=e.indexOf(u.WILDCARD);const s=t===-1?e.length:e.lastIndexOf(o.default.sep,t);const c=e.substr(0,s);try{var d=await r.stat(c);if(d===null){throw new Error("file not found")}}catch(e){return}if(t!==-1&&d.isFile())return;if(d.isFile()){a.add(e)}else if(d.isDirectory()){if(validWildcard(e))emitAssetDirectory(e)}}function validWildcard(t){let a="";if(t.endsWith(o.default.sep))a=o.default.sep;else if(t.endsWith(o.default.sep+u.WILDCARD))a=o.default.sep+u.WILDCARD;else if(t.endsWith(u.WILDCARD))a=u.WILDCARD;if(t===w+a)return false;if(t===q+a)return false;if(t.endsWith(o.default.sep+"node_modules"+a))return false;if(w.startsWith(t.substr(0,t.length-a.length)+o.default.sep))return false;if(k){const a=e.substr(0,e.indexOf(o.default.sep+"node_modules"))+o.default.sep+"node_modules"+o.default.sep;if(!t.startsWith(a)){if(r.log)console.log("Skipping asset emission of "+t.replace(u.wildcardRegEx,"*")+" for "+e+" as it is outside the package base "+k);return false}}return true}function resolveAbsolutePathOrUrl(e){return e instanceof x.URL?x.fileURLToPath(e):e.startsWith("file:")?x.fileURLToPath(new x.URL(e)):o.default.resolve(e)}async function emitStaticChildAsset(){if(!X){return}if("value"in X&&isAbsolutePathOrUrl(X.value)){try{const e=resolveAbsolutePathOrUrl(X.value);await emitAssetPath(e)}catch(e){}}else if("then"in X&&"else"in X&&isAbsolutePathOrUrl(X.then)&&isAbsolutePathOrUrl(X.else)){let e;try{e=resolveAbsolutePathOrUrl(X.then)}catch(e){}let t;try{t=resolveAbsolutePathOrUrl(X.else)}catch(e){}if(e)await emitAssetPath(e);if(t)await emitAssetPath(t)}else if(Q&&Q.type==="ArrayExpression"&&"value"in X&&X.value instanceof Array){for(const e of X.value){try{const t=resolveAbsolutePathOrUrl(e);await emitAssetPath(t)}catch(e){}}}Q=X=undefined}}t["default"]=analyze;function isAst(e){return"body"in e}},9582:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){if(a===undefined)a=r;Object.defineProperty(e,a,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,a){if(a===undefined)a=r;e[a]=t[r]});var o=this&&this.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!t.hasOwnProperty(r))a(t,e,r)};Object.defineProperty(t,"__esModule",{value:true});o(r(3864),t);var s=r(3471);Object.defineProperty(t,"nodeFileTrace",{enumerable:true,get:function(){return s.nodeFileTrace}})},3471:function(e,t,r){"use strict";var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.Job=t.nodeFileTrace=void 0;const o=r(1017);const s=a(r(552));const u=a(r(8827));const c=a(r(2278));const d=r(2540);const f=r(2985);const p=r(1017);const h=s.default.promises.readFile;const v=s.default.promises.readlink;const _=s.default.promises.stat;function inPath(e,t){const r=p.join(t,o.sep);return e.startsWith(r)&&e!==r}async function nodeFileTrace(e,t={}){const r=new Job(t);if(t.readFile)r.readFile=t.readFile;if(t.stat)r.stat=t.stat;if(t.readlink)r.readlink=t.readlink;if(t.resolve)r.resolve=t.resolve;r.ts=true;await Promise.all(e.map((async e=>{const t=o.resolve(e);await r.emitFile(t,"initial");if(t.endsWith(".js")||t.endsWith(".cjs")||t.endsWith(".mjs")||t.endsWith(".node")||r.ts&&(t.endsWith(".ts")||t.endsWith(".tsx"))){return r.emitDependency(t)}return undefined})));const a={fileList:r.fileList,esmFileList:r.esmFileList,reasons:r.reasons,warnings:r.warnings};return a}t.nodeFileTrace=nodeFileTrace;class Job{constructor({base:e=process.cwd(),processCwd:t,exports:r,conditions:a=r||["node"],exportsOnly:s=false,paths:u={},ignore:c,log:f=false,mixedModules:p=false,ts:h=true,analysis:v={},cache:_}){this.reasons=new Map;this.ts=h;e=o.resolve(e);this.ignoreFn=e=>{if(e.startsWith(".."+o.sep))return true;return false};if(typeof c==="string")c=[c];if(typeof c==="function"){const e=c;this.ignoreFn=t=>{if(t.startsWith(".."+o.sep))return true;if(e(t))return true;return false}}else if(Array.isArray(c)){const t=c.map((t=>o.relative(e,o.resolve(e||process.cwd(),t))));this.ignoreFn=e=>{if(e.startsWith(".."+o.sep))return true;if(d.isMatch(e,t))return true;return false}}this.base=e;this.cwd=o.resolve(t||e);this.conditions=a;this.exportsOnly=s;const g={};for(const t of Object.keys(u)){const r=u[t].endsWith("/");const a=o.resolve(e,u[t]);g[t]=a+(r?"/":"")}this.paths=g;this.log=f;this.mixedModules=p;this.analysis={};if(v!==false){Object.assign(this.analysis,{emitGlobs:true,computeFileReferences:true,evaluatePureExpressions:true},v===true?{}:v)}this.fileCache=_&&_.fileCache||new Map;this.statCache=_&&_.statCache||new Map;this.symlinkCache=_&&_.symlinkCache||new Map;this.analysisCache=_&&_.analysisCache||new Map;if(_){_.fileCache=this.fileCache;_.statCache=this.statCache;_.symlinkCache=this.symlinkCache;_.analysisCache=this.analysisCache}this.fileList=new Set;this.esmFileList=new Set;this.processed=new Set;this.warnings=new Set}async readlink(e){const t=this.symlinkCache.get(e);if(t!==undefined)return t;try{const t=await v(e);const r=this.statCache.get(e);if(r)this.statCache.set(o.resolve(e,t),r);this.symlinkCache.set(e,t);return t}catch(t){if(t.code!=="EINVAL"&&t.code!=="ENOENT"&&t.code!=="UNKNOWN")throw t;this.symlinkCache.set(e,null);return null}}async isFile(e){const t=await this.stat(e);if(t)return t.isFile();return false}async isDir(e){const t=await this.stat(e);if(t)return t.isDirectory();return false}async stat(e){const t=this.statCache.get(e);if(t)return t;try{const t=await _(e);this.statCache.set(e,t);return t}catch(t){if(t.code==="ENOENT"){this.statCache.set(e,null);return null}throw t}}async resolve(e,t,r,a){return c.default(e,t,r,a)}async readFile(e){const t=this.fileCache.get(e);if(t!==undefined)return t;try{const t=(await h(e)).toString();this.fileCache.set(e,t);return t}catch(t){if(t.code==="ENOENT"||t.code==="EISDIR"){this.fileCache.set(e,null);return null}throw t}}async realpath(e,t,r=new Set){if(r.has(e))throw new Error("Recursive symlink detected resolving "+e);r.add(e);const a=await this.readlink(e);if(a){const s=o.dirname(e);const u=o.resolve(s,a);const c=await this.realpath(s,t);if(inPath(e,c))await this.emitFile(e,"resolve",t,true);return this.realpath(u,t,r)}if(!inPath(e,this.base))return e;return p.join(await this.realpath(o.dirname(e),t,r),o.basename(e))}async emitFile(e,t,r,a=false){if(!a){e=await this.realpath(e,r)}e=o.relative(this.base,e);if(r){r=o.relative(this.base,r)}let s=this.reasons.get(e);if(!s){s={type:t,ignored:false,parents:new Set};this.reasons.set(e,s)}if(r&&this.ignoreFn(e,r)){if(!this.fileList.has(e)&&s){s.ignored=true}return false}if(r){s.parents.add(r)}this.fileList.add(e);return true}async getPjsonBoundary(e){const t=e.indexOf(o.sep);let r;while((r=e.lastIndexOf(o.sep))>t){e=e.substr(0,r);if(await this.isFile(e+o.sep+"package.json"))return e}return undefined}async emitDependency(e,t){if(this.processed.has(e)){if(t){await this.emitFile(e,"dependency",t)}return}this.processed.add(e);const r=await this.emitFile(e,"dependency",t);if(!r)return;if(e.endsWith(".json"))return;if(e.endsWith(".node"))return await f.sharedLibEmit(e,this);if(e.endsWith(".js")){const t=await this.getPjsonBoundary(e);if(t)await this.emitFile(t+o.sep+"package.json","resolve",e)}let a;const s=this.analysisCache.get(e);if(s){a=s}else{const t=await this.readFile(e);if(t===null)throw new Error("File "+e+" does not exist.");a=await u.default(e,t.toString(),this);this.analysisCache.set(e,a)}const{deps:c,imports:d,assets:p,isESM:h}=a;if(h)this.esmFileList.add(o.relative(this.base,e));await Promise.all([...[...p].map((async t=>{const r=o.extname(t);if(r===".js"||r===".mjs"||r===".node"||r===""||this.ts&&(r===".ts"||r===".tsx")&&t.startsWith(this.base)&&t.substr(this.base.length).indexOf(o.sep+"node_modules"+o.sep)===-1)await this.emitDependency(t,e);else await this.emitFile(t,"asset",e)})),...[...c].map((async t=>{try{var r=await this.resolve(t,e,this,!h)}catch(e){this.warnings.add(new Error(`Failed to resolve dependency ${t}:\n${e&&e.message}`));return}if(Array.isArray(r)){for(const t of r){if(t.startsWith("node:"))return;await this.emitDependency(t,e)}}else{if(r.startsWith("node:"))return;await this.emitDependency(r,e)}})),...[...d].map((async t=>{try{var r=await this.resolve(t,e,this,false)}catch(e){this.warnings.add(new Error(`Failed to resolve dependency ${t}:\n${e&&e.message}`));return}if(Array.isArray(r)){for(const t of r){if(t.startsWith("node:"))return;await this.emitDependency(t,e)}}else{if(r.startsWith("node:"))return;await this.emitDependency(r,e)}}))])}}t.Job=Job},2278:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});const a=r(1017);async function resolveDependency(e,t,r,o=true){let s;if(a.isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")){const o=e.endsWith("/");s=await resolvePath(a.resolve(t,"..",e)+(o?"/":""),t,r)}else if(e[0]==="#"){s=await packageImportsResolve(e,t,r,o)}else{s=await resolvePackage(e,t,r,o)}if(Array.isArray(s)){return Promise.all(s.map((e=>r.realpath(e,t))))}else if(s.startsWith("node:")){return s}else{return r.realpath(s,t)}}t["default"]=resolveDependency;async function resolvePath(e,t,r){const a=await resolveFile(e,t,r)||await resolveDir(e,t,r);if(!a){throw new NotFoundError(e,t)}return a}async function resolveFile(e,t,r){if(e.endsWith("/"))return undefined;e=await r.realpath(e,t);if(await r.isFile(e))return e;if(r.ts&&e.startsWith(r.base)&&e.substr(r.base.length).indexOf(a.sep+"node_modules"+a.sep)===-1&&await r.isFile(e+".ts"))return e+".ts";if(r.ts&&e.startsWith(r.base)&&e.substr(r.base.length).indexOf(a.sep+"node_modules"+a.sep)===-1&&await r.isFile(e+".tsx"))return e+".tsx";if(await r.isFile(e+".js"))return e+".js";if(await r.isFile(e+".json"))return e+".json";if(await r.isFile(e+".node"))return e+".node";return undefined}async function resolveDir(e,t,r){if(e.endsWith("/"))e=e.slice(0,-1);if(!await r.isDir(e))return;const o=await getPkgCfg(e,r);if(o&&typeof o.main==="string"){const s=await resolveFile(a.resolve(e,o.main),t,r)||await resolveFile(a.resolve(e,o.main,"index"),t,r);if(s){await r.emitFile(e+a.sep+"package.json","resolve",t);return s}}return resolveFile(a.resolve(e,"index"),t,r)}class NotFoundError extends Error{constructor(e,t){super("Cannot find module '"+e+"' loaded from "+t);this.code="MODULE_NOT_FOUND"}}const o=new Set([...r(8102)._builtinLibs,"constants","module","timers","console","_stream_writable","_stream_readable","_stream_duplex","process","sys"]);function getPkgName(e){const t=e.split("/");if(e[0]==="@"&&t.length>1)return t.length>1?t.slice(0,2).join("/"):null;return t.length?t[0]:null}async function getPkgCfg(e,t){const r=await t.readFile(e+a.sep+"package.json");if(r){try{return JSON.parse(r.toString())}catch(e){}}return undefined}function getExportsTarget(e,t,r){if(typeof e==="string"){return e}else if(e===null){return e}else if(Array.isArray(e)){for(const a of e){const e=getExportsTarget(a,t,r);if(e===null||typeof e==="string"&&e.startsWith("./"))return e}}else if(typeof e==="object"){for(const a of Object.keys(e)){if(a==="default"||a==="require"&&r||a==="import"&&!r||t.includes(a)){const o=getExportsTarget(e[a],t,r);if(o!==undefined)return o}}}return undefined}function resolveExportsImports(e,t,r,a,o,s){let u;if(o){if(!(typeof t==="object"&&!Array.isArray(t)&&t!==null))return undefined;u=t}else if(typeof t==="string"||Array.isArray(t)||t===null||typeof t==="object"&&Object.keys(t).length&&Object.keys(t)[0][0]!=="."){u={".":t}}else{u=t}if(r in u){const t=getExportsTarget(u[r],a.conditions,s);if(typeof t==="string"&&t.startsWith("./"))return e+t.slice(1)}for(const t of Object.keys(u).sort(((e,t)=>t.length-e.length))){if(t.endsWith("*")&&r.startsWith(t.slice(0,-1))){const o=getExportsTarget(u[t],a.conditions,s);if(typeof o==="string"&&o.startsWith("./"))return e+o.slice(1).replace(/\*/g,r.slice(t.length-1))}if(!t.endsWith("/"))continue;if(r.startsWith(t)){const o=getExportsTarget(u[t],a.conditions,s);if(typeof o==="string"&&o.endsWith("/")&&o.startsWith("./"))return e+o.slice(1)+r.slice(t.length)}}return undefined}async function packageImportsResolve(e,t,r,o){if(e!=="#"&&!e.startsWith("#/")&&r.conditions){const s=await r.getPjsonBoundary(t);if(s){const u=await getPkgCfg(s,r);const{imports:c}=u||{};if(u&&c!==null&&c!==undefined){let u=resolveExportsImports(s,c,e,r,true,o);if(u){if(o)u=await resolveFile(u,t,r)||await resolveDir(u,t,r);else if(!await r.isFile(u))throw new NotFoundError(u,t);if(u){await r.emitFile(s+a.sep+"package.json","resolve",t);return u}}}}}throw new NotFoundError(e,t)}async function resolvePackage(e,t,r,s){let u=t;if(o.has(e))return"node:"+e;const c=getPkgName(e)||"";let d;if(r.conditions){const o=await r.getPjsonBoundary(t);if(o){const u=await getPkgCfg(o,r);const{exports:f}=u||{};if(u&&u.name&&u.name===c&&f!==null&&f!==undefined){d=resolveExportsImports(o,f,"."+e.slice(c.length),r,false,s);if(d){if(s)d=await resolveFile(d,t,r)||await resolveDir(d,t,r);else if(!await r.isFile(d))throw new NotFoundError(d,t)}if(d)await r.emitFile(o+a.sep+"package.json","resolve",t)}}}let f;const p=u.indexOf(a.sep);while((f=u.lastIndexOf(a.sep))>p){u=u.substr(0,f);const o=u+a.sep+"node_modules";const p=await r.stat(o);if(!p||!p.isDirectory())continue;const h=await getPkgCfg(o+a.sep+c,r);const{exports:v}=h||{};if(r.conditions&&v!==undefined&&v!==null&&!d){let u;if(!r.exportsOnly)u=await resolveFile(o+a.sep+e,t,r)||await resolveDir(o+a.sep+e,t,r);let d=resolveExportsImports(o+a.sep+c,v,"."+e.slice(c.length),r,false,s);if(d){if(s)d=await resolveFile(d,t,r)||await resolveDir(d,t,r);else if(!await r.isFile(d))throw new NotFoundError(d,t)}if(d){await r.emitFile(o+a.sep+c+a.sep+"package.json","resolve",t);if(u&&u!==d)return[d,u];return d}if(u)return u}else{const s=await resolveFile(o+a.sep+e,t,r)||await resolveDir(o+a.sep+e,t,r);if(s){if(d&&d!==s)return[s,d];return s}}}if(d)return d;if(Object.hasOwnProperty.call(r.paths,e)){return r.paths[e]}for(const a of Object.keys(r.paths)){if(a.endsWith("/")&&e.startsWith(a)){const o=r.paths[a]+e.slice(a.length);const s=await resolveFile(o,t,r)||await resolveDir(o,t,r);if(!s){throw new NotFoundError(e,t)}return s}}throw new NotFoundError(e,t)}},3864:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true})},5078:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.isLoop=t.isVarLoop=t.isIdentifierRead=void 0;function isIdentifierRead(e,t){switch(t.type){case"ObjectPattern":case"ArrayPattern":return false;case"AssignmentExpression":return t.right===e;case"MemberExpression":return t.computed||e===t.object;case"Property":return e===t.value;case"MethodDefinition":return false;case"VariableDeclarator":return t.id!==e;case"ExportSpecifier":return false;case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":return false;default:return true}}t.isIdentifierRead=isIdentifierRead;function isVarLoop(e){return e.type==="ForStatement"||e.type==="ForInStatement"||e.type==="ForOfStatement"}t.isVarLoop=isVarLoop;function isLoop(e){return e.type==="ForStatement"||e.type==="ForInStatement"||e.type==="ForOfStatement"||e.type==="WhileStatement"||e.type==="DoWhileStatement"}t.isLoop=isLoop},2774:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:true});exports.nbind=exports.pregyp=void 0;const path_1=__importDefault(__nccwpck_require__(1017));const graceful_fs_1=__importDefault(__nccwpck_require__(552));const versioning=__nccwpck_require__(5574);const napi=__nccwpck_require__(9248);const pregypFind=(e,t)=>{const r=JSON.parse(graceful_fs_1.default.readFileSync(e).toString());versioning.validate_config(r,t);var a;if(napi.get_napi_build_versions(r,t)){a=napi.get_best_napi_build_version(r,t)}t=t||{};if(!t.module_root)t.module_root=path_1.default.dirname(e);var o=versioning.evaluate(r,t,a);return o.module};exports.pregyp={default:{find:pregypFind},find:pregypFind};function makeModulePathList(e,t){return[[e,t],[e,"build",t],[e,"build","Debug",t],[e,"build","Release",t],[e,"out","Debug",t],[e,"Debug",t],[e,"out","Release",t],[e,"Release",t],[e,"build","default",t],[e,process.env["NODE_BINDINGS_COMPILED_DIR"]||"compiled",process.versions.node,process.platform,process.arch,t]]}function findCompiledModule(basePath,specList){var resolvedList=[];var ext=path_1.default.extname(basePath);for(var _i=0,specList_1=specList;_i{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.getPackageName=t.getPackageBase=void 0;const r=/^(@[^\\\/]+[\\\/])?[^\\\/]+/;function getPackageBase(e){const t=e.lastIndexOf("node_modules");if(t!==-1&&(e[t-1]==="/"||e[t-1]==="\\")&&(e[t+12]==="/"||e[t+12]==="\\")){const a=e.substr(t+13).match(r);if(a)return e.substr(0,t+13+a[0].length)}return undefined}t.getPackageBase=getPackageBase;function getPackageName(e){const t=e.lastIndexOf("node_modules");if(t!==-1&&(e[t-1]==="/"||e[t-1]==="\\")&&(e[t+12]==="/"||e[t+12]==="\\")){const a=e.substr(t+13).match(r);if(a&&a.length>0){return a[0].replace(/\\/g,"/")}}return undefined}t.getPackageName=getPackageName},216:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.normalizeWildcardRequire=t.normalizeDefaultRequire=void 0;function normalizeDefaultRequire(e){if(e&&e.__esModule)return e;return{default:e}}t.normalizeDefaultRequire=normalizeDefaultRequire;const r=Object.prototype.hasOwnProperty;function normalizeWildcardRequire(e){if(e&&e.__esModule)return e;const t={};for(const a in e){if(!r.call(e,a))continue;t[a]=e[a]}t["default"]=e;return t}t.normalizeWildcardRequire=normalizeWildcardRequire},2985:function(e,t,r){"use strict";var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.sharedLibEmit=void 0;const o=a(r(2037));const s=a(r(3535));const u=r(7468);let c="";switch(o.default.platform()){case"darwin":c="/**/*.@(dylib|so?(.*))";break;case"win32":c="/**/*.dll";break;default:c="/**/*.so?(.*)"}async function sharedLibEmit(e,t){const r=u.getPackageBase(e);if(!r)return;const a=await new Promise(((e,t)=>s.default(r+c,{ignore:r+"/**/node_modules/**/*"},((r,a)=>r?t(r):e(a)))));await Promise.all(a.map((r=>t.emitFile(r,"sharedlib",e))))}t.sharedLibEmit=sharedLibEmit},5735:function(e,t,r){"use strict";var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const o=r(1017);const s=a(r(2278));const u=r(7468);const c=r(552);const d={"@generated/photon"({id:e,emitAssetDirectory:t}){if(e.endsWith("@generated/photon/index.js")){t(o.resolve(o.dirname(e),"runtime/"))}},argon2({id:e,emitAssetDirectory:t}){if(e.endsWith("argon2/argon2.js")){t(o.resolve(o.dirname(e),"build","Release"));t(o.resolve(o.dirname(e),"prebuilds"));t(o.resolve(o.dirname(e),"lib","binding"))}},bull({id:e,emitAssetDirectory:t}){if(e.endsWith("bull/lib/commands/index.js")){t(o.resolve(o.dirname(e)))}},camaro({id:e,emitAsset:t}){if(e.endsWith("camaro/dist/camaro.js")){t(o.resolve(o.dirname(e),"camaro.wasm"))}},esbuild({id:e,emitAssetDirectory:t}){if(e.endsWith("esbuild/lib/main.js")){const r=o.resolve(e,"..","..","package.json");const a=JSON.parse(c.readFileSync(r,"utf8"));for(const r of Object.keys(a.optionalDependencies||{})){const a=o.resolve(e,"..","..","..",r);t(a)}}},"google-gax"({id:e,ast:t,emitAssetDirectory:r}){if(e.endsWith("google-gax/build/src/grpc.js")){for(const a of t.body){if(a.type==="VariableDeclaration"&&a.declarations[0].id.type==="Identifier"&&a.declarations[0].id.name==="googleProtoFilesDir"){r(o.resolve(o.dirname(e),"../../../google-proto-files"))}}}},oracledb({id:e,ast:t,emitAsset:r}){if(e.endsWith("oracledb/lib/oracledb.js")){for(const a of t.body){if(a.type==="ForStatement"&&"body"in a.body&&a.body.body&&Array.isArray(a.body.body)&&a.body.body[0]&&a.body.body[0].type==="TryStatement"&&a.body.body[0].block.body[0]&&a.body.body[0].block.body[0].type==="ExpressionStatement"&&a.body.body[0].block.body[0].expression.type==="AssignmentExpression"&&a.body.body[0].block.body[0].expression.operator==="="&&a.body.body[0].block.body[0].expression.left.type==="Identifier"&&a.body.body[0].block.body[0].expression.left.name==="oracledbCLib"&&a.body.body[0].block.body[0].expression.right.type==="CallExpression"&&a.body.body[0].block.body[0].expression.right.callee.type==="Identifier"&&a.body.body[0].block.body[0].expression.right.callee.name==="require"&&a.body.body[0].block.body[0].expression.right.arguments.length===1&&a.body.body[0].block.body[0].expression.right.arguments[0].type==="MemberExpression"&&a.body.body[0].block.body[0].expression.right.arguments[0].computed===true&&a.body.body[0].block.body[0].expression.right.arguments[0].object.type==="Identifier"&&a.body.body[0].block.body[0].expression.right.arguments[0].object.name==="binaryLocations"&&a.body.body[0].block.body[0].expression.right.arguments[0].property.type==="Identifier"&&a.body.body[0].block.body[0].expression.right.arguments[0].property.name==="i"){a.body.body[0].block.body[0].expression.right.arguments=[{type:"Literal",value:"_"}];const t=global._unit?"3.0.0":JSON.parse(c.readFileSync(e.slice(0,-15)+"package.json","utf8")).version;const s=Number(t.slice(0,t.indexOf(".")))>=4;const u="oracledb-"+(s?t:"abi"+process.versions.modules)+"-"+process.platform+"-"+process.arch+".node";r(o.resolve(e,"../../build/Release/"+u))}}}},"phantomjs-prebuilt"({id:e,emitAssetDirectory:t}){if(e.endsWith("phantomjs-prebuilt/lib/phantomjs.js")){t(o.resolve(o.dirname(e),"..","bin"))}},"remark-prism"({id:e,emitAssetDirectory:t}){const r="remark-prism/src/highlight.js";if(e.endsWith(r)){try{const a=e.slice(0,-r.length);t(o.resolve(a,"prismjs","components"))}catch(e){}}},semver({id:e,emitAsset:t}){if(e.endsWith("semver/index.js")){t(o.resolve(e.replace("index.js","preload.js")))}},"socket.io":async function({id:e,ast:t,job:r}){if(e.endsWith("socket.io/lib/index.js")){async function replaceResolvePathStatement(t){if(t.type==="ExpressionStatement"&&t.expression.type==="AssignmentExpression"&&t.expression.operator==="="&&t.expression.right.type==="CallExpression"&&t.expression.right.callee.type==="Identifier"&&t.expression.right.callee.name==="read"&&t.expression.right.arguments.length>=1&&t.expression.right.arguments[0].type==="CallExpression"&&t.expression.right.arguments[0].callee.type==="Identifier"&&t.expression.right.arguments[0].callee.name==="resolvePath"&&t.expression.right.arguments[0].arguments.length===1&&t.expression.right.arguments[0].arguments[0].type==="Literal"){const a=t.expression.right.arguments[0].arguments[0].value;let u;try{const t=await s.default(String(a),e,r);if(typeof t==="string"){u=t}else{return undefined}}catch(e){return undefined}const c="/"+o.relative(o.dirname(e),u);t.expression.right.arguments[0]={type:"BinaryExpression",start:t.expression.right.arguments[0].start,end:t.expression.right.arguments[0].end,operator:"+",left:{type:"Identifier",name:"__dirname"},right:{type:"Literal",value:c,raw:JSON.stringify(c)}}}return undefined}for(const e of t.body){if(e.type==="ExpressionStatement"&&e.expression.type==="AssignmentExpression"&&e.expression.operator==="="&&e.expression.left.type==="MemberExpression"&&e.expression.left.object.type==="MemberExpression"&&e.expression.left.object.object.type==="Identifier"&&e.expression.left.object.object.name==="Server"&&e.expression.left.object.property.type==="Identifier"&&e.expression.left.object.property.name==="prototype"&&e.expression.left.property.type==="Identifier"&&e.expression.left.property.name==="serveClient"&&e.expression.right.type==="FunctionExpression"){for(const t of e.expression.right.body.body){if(t.type==="IfStatement"&&t.consequent&&"body"in t.consequent&&t.consequent.body){const e=t.consequent.body;let r=false;if(Array.isArray(e)&&e[0]&&e[0].type==="ExpressionStatement"){r=await replaceResolvePathStatement(e[0])}if(Array.isArray(e)&&e[1]&&e[1].type==="TryStatement"&&e[1].block.body&&e[1].block.body[0]){r=await replaceResolvePathStatement(e[1].block.body[0])||r}return}}}}}},typescript({id:e,emitAssetDirectory:t}){if(e.endsWith("typescript/lib/tsc.js")){t(o.resolve(e,"../"))}},"uglify-es"({id:e,emitAsset:t}){if(e.endsWith("uglify-es/tools/node.js")){t(o.resolve(e,"../../lib/utils.js"));t(o.resolve(e,"../../lib/ast.js"));t(o.resolve(e,"../../lib/parse.js"));t(o.resolve(e,"../../lib/transform.js"));t(o.resolve(e,"../../lib/scope.js"));t(o.resolve(e,"../../lib/output.js"));t(o.resolve(e,"../../lib/compress.js"));t(o.resolve(e,"../../lib/sourcemap.js"));t(o.resolve(e,"../../lib/mozilla-ast.js"));t(o.resolve(e,"../../lib/propmangle.js"));t(o.resolve(e,"../../lib/minify.js"));t(o.resolve(e,"../exports.js"))}},"uglify-js"({id:e,emitAsset:t,emitAssetDirectory:r}){if(e.endsWith("uglify-js/tools/node.js")){r(o.resolve(e,"../../lib"));t(o.resolve(e,"../exports.js"))}},"playwright-core"({id:e,emitAsset:t}){if(e.endsWith("playwright-core/index.js")){t(o.resolve(o.dirname(e),"browsers.json"))}},"geo-tz"({id:e,emitAsset:t}){if(e.endsWith("geo-tz/dist/geo-tz.js")){t(o.resolve(o.dirname(e),"../data/geo.dat"))}}};async function handleSpecialCases({id:e,ast:t,emitAsset:r,emitAssetDirectory:a,job:o}){const s=u.getPackageName(e);const c=d[s||""];e=e.replace(/\\/g,"/");if(c)await c({id:e,ast:t,emitAsset:r,emitAssetDirectory:a,job:o})}t["default"]=handleSpecialCases},5401:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.wildcardRegEx=t.WILDCARD=t.FUNCTION=t.UNKNOWN=t.evaluate=void 0;const a=r(7310);async function evaluate(e,t={},r=true){const a={computeBranches:r,vars:t};return walk(e);function walk(e){const t=o[e.type];if(t){return t.call(a,e,walk)}return undefined}}t.evaluate=evaluate;t.UNKNOWN=Symbol();t.FUNCTION=Symbol();t.WILDCARD="";t.wildcardRegEx=/\x1a/g;function countWildcards(e){t.wildcardRegEx.lastIndex=0;let r=0;while(t.wildcardRegEx.exec(e))r++;return r}const o={ArrayExpression:async function ArrayExpression(e,t){const r=[];for(let a=0,o=e.elements.length;aa.value}}}return undefined},BinaryExpression:async function BinaryExpression(e,r){const a=e.operator;let o=await r(e.left);if(!o&&a!=="+")return;let s=await r(e.right);if(!o&&!s)return;if(!o){if(this.computeBranches&&s&&"value"in s&&typeof s.value==="string")return{value:t.WILDCARD+s.value,wildcards:[e.left,...s.wildcards||[]]};return}if(!s){if(this.computeBranches&&a==="+"){if(o&&"value"in o&&typeof o.value==="string")return{value:o.value+t.WILDCARD,wildcards:[...o.wildcards||[],e.right]}}if(!("test"in o)&&a==="||"&&o.value)return o;return}if("test"in o&&"value"in s){const e=s.value;if(a==="==")return{test:o.test,then:o.then==e,else:o.else==e};if(a==="===")return{test:o.test,then:o.then===e,else:o.else===e};if(a==="!=")return{test:o.test,then:o.then!=e,else:o.else!=e};if(a==="!==")return{test:o.test,then:o.then!==e,else:o.else!==e};if(a==="+")return{test:o.test,then:o.then+e,else:o.else+e};if(a==="-")return{test:o.test,then:o.then-e,else:o.else-e};if(a==="*")return{test:o.test,then:o.then*e,else:o.else*e};if(a==="/")return{test:o.test,then:o.then/e,else:o.else/e};if(a==="%")return{test:o.test,then:o.then%e,else:o.else%e};if(a==="<")return{test:o.test,then:o.then")return{test:o.test,then:o.then>e,else:o.else>e};if(a===">=")return{test:o.test,then:o.then>=e,else:o.else>=e};if(a==="|")return{test:o.test,then:o.then|e,else:o.else|e};if(a==="&")return{test:o.test,then:o.then&e,else:o.else&e};if(a==="^")return{test:o.test,then:o.then^e,else:o.else^e};if(a==="&&")return{test:o.test,then:o.then&&e,else:o.else&&e};if(a==="||")return{test:o.test,then:o.then||e,else:o.else||e}}else if("test"in s&&"value"in o){const e=o.value;if(a==="==")return{test:s.test,then:e==s.then,else:e==s.else};if(a==="===")return{test:s.test,then:e===s.then,else:e===s.else};if(a==="!=")return{test:s.test,then:e!=s.then,else:e!=s.else};if(a==="!==")return{test:s.test,then:e!==s.then,else:e!==s.else};if(a==="+")return{test:s.test,then:e+s.then,else:e+s.else};if(a==="-")return{test:s.test,then:e-s.then,else:e-s.else};if(a==="*")return{test:s.test,then:e*s.then,else:e*s.else};if(a==="/")return{test:s.test,then:e/s.then,else:e/s.else};if(a==="%")return{test:s.test,then:e%s.then,else:e%s.else};if(a==="<")return{test:s.test,then:e")return{test:s.test,then:e>s.then,else:e>s.else};if(a===">=")return{test:s.test,then:e>=s.then,else:e>=s.else};if(a==="|")return{test:s.test,then:e|s.then,else:e|s.else};if(a==="&")return{test:s.test,then:e&s.then,else:e&s.else};if(a==="^")return{test:s.test,then:e^s.then,else:e^s.else};if(a==="&&")return{test:s.test,then:e&&s.then,else:o&&s.else};if(a==="||")return{test:s.test,then:e||s.then,else:o||s.else}}else if("value"in o&&"value"in s){if(a==="==")return{value:o.value==s.value};if(a==="===")return{value:o.value===s.value};if(a==="!=")return{value:o.value!=s.value};if(a==="!==")return{value:o.value!==s.value};if(a==="+"){const e={value:o.value+s.value};let t=[];if("wildcards"in o&&o.wildcards){t=t.concat(o.wildcards)}if("wildcards"in s&&s.wildcards){t=t.concat(s.wildcards)}if(t.length>0){e.wildcards=t}return e}if(a==="-")return{value:o.value-s.value};if(a==="*")return{value:o.value*s.value};if(a==="/")return{value:o.value/s.value};if(a==="%")return{value:o.value%s.value};if(a==="<")return{value:o.value")return{value:o.value>s.value};if(a===">=")return{value:o.value>=s.value};if(a==="|")return{value:o.value|s.value};if(a==="&")return{value:o.value&s.value};if(a==="^")return{value:o.value^s.value};if(a==="&&")return{value:o.value&&s.value};if(a==="||")return{value:o.value||s.value}}return},CallExpression:async function CallExpression(e,r){var a;const o=await r(e.callee);if(!o||"test"in o)return;let s=o.value;if(typeof s==="object"&&s!==null)s=s[t.FUNCTION];if(typeof s!=="function")return;let u=null;if(e.callee.object){u=await r(e.callee.object);u=u&&"value"in u&&u.value?u.value:null}let c;let d=[];let f;let p=e.arguments.length>0&&((a=e.callee.property)===null||a===void 0?void 0:a.name)!=="concat";const h=[];for(let a=0,o=e.arguments.length;ah.push(e)))}else{if(!this.computeBranches)return;o={value:t.WILDCARD};h.push(e.arguments[a])}if("test"in o){if(h.length)return;if(c)return;c=o.test;f=d.concat([]);d.push(o.then);f.push(o.else)}else{d.push(o.value);if(f)f.push(o.value)}}if(p)return;try{const e=await s.apply(u,d);if(e===t.UNKNOWN)return;if(!c){if(h.length){if(typeof e!=="string"||countWildcards(e)!==h.length)return;return{value:e,wildcards:h}}return{value:e}}const r=await s.apply(u,f);if(e===t.UNKNOWN)return;return{test:c,then:e,else:r}}catch(e){return}},ConditionalExpression:async function ConditionalExpression(e,t){const r=await t(e.test);if(r&&"value"in r)return r.value?t(e.consequent):t(e.alternate);if(!this.computeBranches)return;const a=await t(e.consequent);if(!a||"wildcards"in a||"test"in a)return;const o=await t(e.alternate);if(!o||"wildcards"in o||"test"in o)return;return{test:e.test,then:a.value,else:o.value}},ExpressionStatement:async function ExpressionStatement(e,t){return t(e.expression)},Identifier:async function Identifier(e,t){if(Object.hasOwnProperty.call(this.vars,e.name))return this.vars[e.name];return undefined},Literal:async function Literal(e,t){return{value:e.value}},MemberExpression:async function MemberExpression(e,r){const a=await r(e.object);if(!a||"test"in a||typeof a.value==="function"){return undefined}if(e.property.type==="Identifier"){if(typeof a.value==="string"&&e.property.name==="concat"){return{value:{[t.FUNCTION]:(...e)=>a.value.concat(e)}}}if(typeof a.value==="object"&&a.value!==null){const o=a.value;if(e.computed){const s=await r(e.property);if(s&&"value"in s&&s.value){const e=o[s.value];if(e===t.UNKNOWN)return undefined;return{value:e}}if(!o[t.UNKNOWN]&&Object.keys(a).length===0){return{value:undefined}}}else if(e.property.name in o){const r=o[e.property.name];if(r===t.UNKNOWN)return undefined;return{value:r}}else if(o[t.UNKNOWN])return undefined}else{return{value:undefined}}}const o=await r(e.property);if(!o||"test"in o)return undefined;if(typeof a.value==="object"&&a.value!==null){if(o.value in a.value){const e=a.value[o.value];if(e===t.UNKNOWN)return undefined;return{value:e}}else if(a.value[t.UNKNOWN]){return undefined}}else{return{value:undefined}}return undefined},MetaProperty:async function MetaProperty(e){if(e.meta.name==="import"&&e.property.name==="meta")return{value:this.vars["import.meta"]};return undefined},NewExpression:async function NewExpression(e,t){const r=await t(e.callee);if(r&&"value"in r&&r.value===a.URL&&e.arguments.length){const r=await t(e.arguments[0]);if(!r)return undefined;let o=null;if(e.arguments[1]){o=await t(e.arguments[1]);if(!o||!("value"in o))return undefined}if("value"in r){if(o){try{return{value:new a.URL(r.value,o.value)}}catch(e){return undefined}}try{return{value:new a.URL(r.value)}}catch(e){return undefined}}else{const e=r.test;if(o){try{return{test:e,then:new a.URL(r.then,o.value),else:new a.URL(r.else,o.value)}}catch(e){return undefined}}try{return{test:e,then:new a.URL(r.then),else:new a.URL(r.else)}}catch(e){return undefined}}}return undefined},ObjectExpression:async function ObjectExpression(e,r){const a={};for(let o=0;o{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.handleWrappers=void 0;const a=r(7470);function isUndefinedOrVoid(e){return e.type==="Identifier"&&e.name==="undefined"||e.type==="UnaryExpression"&&e.operator==="void"&&e.argument.type==="Literal"&&e.argument.value===0}function handleWrappers(e){var t;let r;if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="UnaryExpression"&&e.body[0].expression.operator==="!"&&e.body[0].expression.argument.type==="CallExpression"&&e.body[0].expression.argument.callee.type==="FunctionExpression"&&e.body[0].expression.argument.arguments.length===1)r=e.body[0].expression.argument;else if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="CallExpression"&&e.body[0].expression.callee.type==="FunctionExpression"&&(e.body[0].expression.arguments.length===1||e.body[0].expression.arguments.length===0))r=e.body[0].expression;else if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="AssignmentExpression"&&e.body[0].expression.left.type==="MemberExpression"&&e.body[0].expression.left.object.type==="Identifier"&&e.body[0].expression.left.object.name==="module"&&e.body[0].expression.left.property.type==="Identifier"&&e.body[0].expression.left.property.name==="exports"&&e.body[0].expression.right.type==="CallExpression"&&e.body[0].expression.right.callee.type==="FunctionExpression"&&e.body[0].expression.right.arguments.length===1)r=e.body[0].expression.right;if(r){let e;let o;if(r.arguments[0]&&r.arguments[0].type==="ConditionalExpression"&&r.arguments[0].test.type==="LogicalExpression"&&r.arguments[0].test.operator==="&&"&&r.arguments[0].test.left.type==="BinaryExpression"&&r.arguments[0].test.left.operator==="==="&&r.arguments[0].test.left.left.type==="UnaryExpression"&&r.arguments[0].test.left.left.operator==="typeof"&&"name"in r.arguments[0].test.left.left.argument&&r.arguments[0].test.left.left.argument.name==="define"&&r.arguments[0].test.left.right.type==="Literal"&&r.arguments[0].test.left.right.value==="function"&&r.arguments[0].test.right.type==="MemberExpression"&&r.arguments[0].test.right.object.type==="Identifier"&&r.arguments[0].test.right.property.type==="Identifier"&&r.arguments[0].test.right.property.name==="amd"&&r.arguments[0].test.right.computed===false&&r.arguments[0].alternate.type==="FunctionExpression"&&r.arguments[0].alternate.params.length===1&&r.arguments[0].alternate.params[0].type==="Identifier"&&r.arguments[0].alternate.body.body.length===1&&r.arguments[0].alternate.body.body[0].type==="ExpressionStatement"&&r.arguments[0].alternate.body.body[0].expression.type==="AssignmentExpression"&&r.arguments[0].alternate.body.body[0].expression.left.type==="MemberExpression"&&r.arguments[0].alternate.body.body[0].expression.left.object.type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.left.object.name==="module"&&r.arguments[0].alternate.body.body[0].expression.left.property.type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.left.property.name==="exports"&&r.arguments[0].alternate.body.body[0].expression.left.computed===false&&r.arguments[0].alternate.body.body[0].expression.right.type==="CallExpression"&&r.arguments[0].alternate.body.body[0].expression.right.callee.type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.right.callee.name===r.arguments[0].alternate.params[0].name&&"body"in r.callee&&"body"in r.callee.body&&Array.isArray(r.callee.body.body)&&r.arguments[0].alternate.body.body[0].expression.right.arguments.length===1&&r.arguments[0].alternate.body.body[0].expression.right.arguments[0].type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.right.arguments[0].name==="require"){let e=r.callee.body.body;if(e[0].type==="ExpressionStatement"&&e[0].expression.type==="Literal"&&e[0].expression.value==="use strict"){e=e.slice(1)}if(e.length===1&&e[0].type==="ExpressionStatement"&&e[0].expression.type==="CallExpression"&&e[0].expression.callee.type==="Identifier"&&e[0].expression.callee.name===r.arguments[0].test.right.object.name&&e[0].expression.arguments.length===1&&e[0].expression.arguments[0].type==="FunctionExpression"&&e[0].expression.arguments[0].params.length===1&&e[0].expression.arguments[0].params[0].type==="Identifier"&&e[0].expression.arguments[0].params[0].name==="require"){const t=e[0].expression.arguments[0];t.params=[];try{delete t.scope.declarations.require}catch(e){}}}else if(r.arguments[0]&&r.arguments[0].type==="FunctionExpression"&&r.arguments[0].params.length===0&&(r.arguments[0].body.body.length===1||r.arguments[0].body.body.length===2&&r.arguments[0].body.body[0].type==="VariableDeclaration"&&r.arguments[0].body.body[0].declarations.length===3&&r.arguments[0].body.body[0].declarations.every((e=>e.init===null&&e.id.type==="Identifier")))&&r.arguments[0].body.body[r.arguments[0].body.body.length-1].type==="ReturnStatement"&&(e=r.arguments[0].body.body[r.arguments[0].body.body.length-1])&&((t=e.argument)===null||t===void 0?void 0:t.type)==="CallExpression"&&e.argument.arguments.length&&e.argument.arguments.every((e=>e&&e.type==="Literal"&&typeof e.value==="number"))&&e.argument.callee.type==="CallExpression"&&(e.argument.callee.callee.type==="FunctionExpression"||e.argument.callee.callee.type==="CallExpression"&&e.argument.callee.callee.callee.type==="FunctionExpression"&&e.argument.callee.callee.arguments.length===0)&&e.argument.callee.arguments.length===3&&e.argument.callee.arguments[0].type==="ObjectExpression"&&e.argument.callee.arguments[1].type==="ObjectExpression"&&e.argument.callee.arguments[2].type==="ArrayExpression"){const t=e.argument.callee.arguments[0].properties;const r={};if(t.every((e=>{if(e.type!=="Property"||e.computed!==false||e.key.type!=="Literal"||typeof e.key.value!=="number"||e.value.type!=="ArrayExpression"||e.value.elements.length!==2||!e.value.elements[0]||!e.value.elements[1]||e.value.elements[0].type!=="FunctionExpression"||e.value.elements[1].type!=="ObjectExpression"){return false}const t=e.value.elements[1].properties;for(const e of t){if(e.type!=="Property"||e.value.type!=="Identifier"&&e.value.type!=="Literal"&&!isUndefinedOrVoid(e.value)||!(e.key.type==="Literal"&&typeof e.key.value==="string"||e.key.type==="Identifier")||e.computed){return false}if(isUndefinedOrVoid(e.value)){if(e.key.type==="Identifier"){r[e.key.name]={type:"Literal",start:e.key.start,end:e.key.end,value:e.key.name,raw:JSON.stringify(e.key.name)}}else if(e.key.type==="Literal"){r[String(e.key.value)]=e.key}}}return true}))){const t=Object.keys(r);const a=e.argument.callee.arguments[1];a.properties=t.map((e=>({type:"Property",method:false,shorthand:false,computed:false,kind:"init",key:r[e],value:{type:"ObjectExpression",properties:[{type:"Property",kind:"init",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"exports"},value:{type:"CallExpression",optional:false,callee:{type:"Identifier",name:"require"},arguments:[r[e]]}}]}})))}}else if(r.arguments[0]&&r.arguments[0].type==="FunctionExpression"&&r.arguments[0].params.length===2&&r.arguments[0].params[0].type==="Identifier"&&r.arguments[0].params[1].type==="Identifier"&&"body"in r.callee&&"body"in r.callee.body&&Array.isArray(r.callee.body.body)&&r.callee.body.body.length===1){const e=r.callee.body.body[0];if(e.type==="IfStatement"&&e.test.type==="LogicalExpression"&&e.test.operator==="&&"&&e.test.left.type==="BinaryExpression"&&e.test.left.left.type==="UnaryExpression"&&e.test.left.left.operator==="typeof"&&e.test.left.left.argument.type==="Identifier"&&e.test.left.left.argument.name==="module"&&e.test.left.right.type==="Literal"&&e.test.left.right.value==="object"&&e.test.right.type==="BinaryExpression"&&e.test.right.left.type==="UnaryExpression"&&e.test.right.left.operator==="typeof"&&e.test.right.left.argument.type==="MemberExpression"&&e.test.right.left.argument.object.type==="Identifier"&&e.test.right.left.argument.object.name==="module"&&e.test.right.left.argument.property.type==="Identifier"&&e.test.right.left.argument.property.name==="exports"&&e.test.right.right.type==="Literal"&&e.test.right.right.value==="object"&&e.consequent.type==="BlockStatement"&&e.consequent.body.length>0){let t;if(e.consequent.body[0].type==="VariableDeclaration"&&e.consequent.body[0].declarations[0].init&&e.consequent.body[0].declarations[0].init.type==="CallExpression")t=e.consequent.body[0].declarations[0].init;else if(e.consequent.body[0].type==="ExpressionStatement"&&e.consequent.body[0].expression.type==="CallExpression")t=e.consequent.body[0].expression;else if(e.consequent.body[0].type==="ExpressionStatement"&&e.consequent.body[0].expression.type==="AssignmentExpression"&&e.consequent.body[0].expression.operator==="="&&e.consequent.body[0].expression.right.type==="CallExpression")t=e.consequent.body[0].expression.right;if(t&&t.callee.type==="Identifier"&&"params"in r.callee&&r.callee.params.length>0&&"name"in r.callee.params[0]&&t.callee.name===r.callee.params[0].name&&t.arguments.length===2&&t.arguments[0].type==="Identifier"&&t.arguments[0].name==="require"&&t.arguments[1].type==="Identifier"&&t.arguments[1].name==="exports"){const e=r.arguments[0];e.params=[];try{const t=e.scope;delete t.declarations.require;delete t.declarations.exports}catch(e){}}}}else if(r.callee.type==="FunctionExpression"&&r.callee.body.body.length>2&&r.callee.body.body[0].type==="VariableDeclaration"&&r.callee.body.body[0].declarations.length===1&&r.callee.body.body[0].declarations[0].type==="VariableDeclarator"&&r.callee.body.body[0].declarations[0].id.type==="Identifier"&&r.callee.body.body[0].declarations[0].init&&(r.callee.body.body[0].declarations[0].init.type==="ObjectExpression"&&r.callee.body.body[0].declarations[0].init.properties.length===0||r.callee.body.body[0].declarations[0].init.type==="CallExpression"&&r.callee.body.body[0].declarations[0].init.arguments.length===1)&&(r.callee.body.body[1]&&r.callee.body.body[1].type==="FunctionDeclaration"&&r.callee.body.body[1].params.length===1&&r.callee.body.body[1].body.body.length>=3||r.callee.body.body[2]&&r.callee.body.body[2].type==="FunctionDeclaration"&&r.callee.body.body[2].params.length===1&&r.callee.body.body[2].body.body.length>=3)&&(r.arguments[0]&&(r.arguments[0].type==="ArrayExpression"&&(o=r.arguments[0])&&r.arguments[0].elements.length>0&&r.arguments[0].elements.every((e=>e&&e.type==="FunctionExpression"))||r.arguments[0].type==="ObjectExpression"&&(o=r.arguments[0])&&r.arguments[0].properties&&r.arguments[0].properties.length>0&&r.arguments[0].properties.every((e=>e&&e.type==="Property"&&!e.computed&&e.key&&e.key.type==="Literal"&&(typeof e.key.value==="string"||typeof e.key.value==="number")&&e.value&&e.value.type==="FunctionExpression"))))||r.arguments.length===0&&r.callee.type==="FunctionExpression"&&r.callee.params.length===0&&r.callee.body.type==="BlockStatement"&&r.callee.body.body.length>5&&r.callee.body.body[0].type==="VariableDeclaration"&&r.callee.body.body[0].declarations.length===1&&r.callee.body.body[0].declarations[0].id.type==="Identifier"&&r.callee.body.body[1].type==="ExpressionStatement"&&r.callee.body.body[1].expression.type==="AssignmentExpression"&&r.callee.body.body[2].type==="ExpressionStatement"&&r.callee.body.body[2].expression.type==="AssignmentExpression"&&r.callee.body.body[3].type==="ExpressionStatement"&&r.callee.body.body[3].expression.type==="AssignmentExpression"&&r.callee.body.body[3].expression.left.type==="MemberExpression"&&r.callee.body.body[3].expression.left.object.type==="Identifier"&&r.callee.body.body[3].expression.left.object.name===r.callee.body.body[0].declarations[0].id.name&&r.callee.body.body[3].expression.left.property.type==="Identifier"&&r.callee.body.body[3].expression.left.property.name==="modules"&&r.callee.body.body[3].expression.right.type==="ObjectExpression"&&r.callee.body.body[3].expression.right.properties.every((e=>e&&e.type==="Property"&&!e.computed&&e.key&&e.key.type==="Literal"&&(typeof e.key.value==="string"||typeof e.key.value==="number")&&e.value&&e.value.type==="FunctionExpression"))&&(o=r.callee.body.body[3].expression.right)&&(r.callee.body.body[4].type==="VariableDeclaration"&&r.callee.body.body[4].declarations.length===1&&r.callee.body.body[4].declarations[0].init&&r.callee.body.body[4].declarations[0].init.type==="CallExpression"&&r.callee.body.body[4].declarations[0].init.callee.type==="Identifier"&&r.callee.body.body[4].declarations[0].init.callee.name==="require"||r.callee.body.body[5].type==="VariableDeclaration"&&r.callee.body.body[5].declarations.length===1&&r.callee.body.body[5].declarations[0].init&&r.callee.body.body[5].declarations[0].init.type==="CallExpression"&&r.callee.body.body[5].declarations[0].init.callee.type==="Identifier"&&r.callee.body.body[5].declarations[0].init.callee.name==="require")){const e=new Map;let t;if(o.type==="ArrayExpression")t=o.elements.filter((e=>(e===null||e===void 0?void 0:e.type)==="FunctionExpression")).map(((e,t)=>[String(t),e]));else t=o.properties.map((e=>[String(e.key.value),e.value]));for(const[r,a]of t){const t=a.body.body.length===1?a.body.body[0]:(a.body.body.length===2||a.body.body.length===3&&a.body.body[2].type==="EmptyStatement")&&a.body.body[0].type==="ExpressionStatement"&&a.body.body[0].expression.type==="Literal"&&a.body.body[0].expression.value==="use strict"?a.body.body[1]:null;if(t&&t.type==="ExpressionStatement"&&t.expression.type==="AssignmentExpression"&&t.expression.operator==="="&&t.expression.left.type==="MemberExpression"&&t.expression.left.object.type==="Identifier"&&"params"in a&&a.params.length>0&&"name"in a.params[0]&&t.expression.left.object.name===a.params[0].name&&t.expression.left.property.type==="Identifier"&&t.expression.left.property.name==="exports"&&t.expression.right.type==="CallExpression"&&t.expression.right.callee.type==="Identifier"&&t.expression.right.callee.name==="require"&&t.expression.right.arguments.length===1&&t.expression.right.arguments[0].type==="Literal"){e.set(r,t.expression.right.arguments[0].value)}}for(const[,r]of t){if("params"in r&&r.params.length===3&&r.params[2].type==="Identifier"){const t=new Map;a.walk(r.body,{enter(a,o){const s=a;const u=o;if(s.type==="CallExpression"&&s.callee.type==="Identifier"&&"name"in r.params[2]&&s.callee.name===r.params[2].name&&s.arguments.length===1&&s.arguments[0].type==="Literal"){const r=e.get(String(s.arguments[0].value));if(r){const e={type:"CallExpression",optional:false,callee:{type:"Identifier",name:"require"},arguments:[{type:"Literal",value:r}]};const a=u;if("right"in a&&a.right===s){a.right=e}else if("left"in a&&a.left===s){a.left=e}else if("object"in a&&a.object===s){a.object=e}else if("callee"in a&&a.callee===s){a.callee=e}else if("arguments"in a&&a.arguments.some((e=>e===s))){a.arguments=a.arguments.map((t=>t===s?e:t))}else if("init"in a&&a.init===s){if(a.type==="VariableDeclarator"&&a.id.type==="Identifier")t.set(a.id.name,r);a.init=e}}}else if(s.type==="CallExpression"&&s.callee.type==="MemberExpression"&&s.callee.object.type==="Identifier"&&"name"in r.params[2]&&s.callee.object.name===r.params[2].name&&s.callee.property.type==="Identifier"&&s.callee.property.name==="n"&&s.arguments.length===1&&s.arguments[0].type==="Identifier"){if(u&&"init"in u&&u.init===s){const e=s.arguments[0];const t={type:"CallExpression",optional:false,callee:{type:"MemberExpression",computed:false,optional:false,object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"assign"}},arguments:[{type:"ArrowFunctionExpression",expression:true,params:[],body:e},{type:"ObjectExpression",properties:[{type:"Property",kind:"init",method:false,computed:false,shorthand:false,key:{type:"Identifier",name:"a"},value:e}]}]};u.init=t}}}})}}}}}t.handleWrappers=handleWrappers},5920:(e,t)=>{e.exports=t=abbrev.abbrev=abbrev;abbrev.monkeyPatch=monkeyPatch;function monkeyPatch(){Object.defineProperty(Array.prototype,"abbrev",{value:function(){return abbrev(this)},enumerable:false,configurable:true,writable:true});Object.defineProperty(Object.prototype,"abbrev",{value:function(){return abbrev(Object.keys(this))},enumerable:false,configurable:true,writable:true})}function abbrev(e){if(arguments.length!==1||!Array.isArray(e)){e=Array.prototype.slice.call(arguments,0)}for(var t=0,r=e.length,a=[];tt?1:-1}},5534:e=>{"use strict";function isArguments(e){return e!=null&&typeof e==="object"&&e.hasOwnProperty("callee")}var t={"*":{label:"any",check:function(){return true}},A:{label:"array",check:function(e){return Array.isArray(e)||isArguments(e)}},S:{label:"string",check:function(e){return typeof e==="string"}},N:{label:"number",check:function(e){return typeof e==="number"}},F:{label:"function",check:function(e){return typeof e==="function"}},O:{label:"object",check:function(e){return typeof e==="object"&&e!=null&&!t.A.check(e)&&!t.E.check(e)}},B:{label:"boolean",check:function(e){return typeof e==="boolean"}},E:{label:"error",check:function(e){return e instanceof Error}},Z:{label:"null",check:function(e){return e==null}}};function addSchema(e,t){var r=t[e.length]=t[e.length]||[];if(r.indexOf(e)===-1)r.push(e)}var r=e.exports=function(e,r){if(arguments.length!==2)throw wrongNumberOfArgs(["SA"],arguments.length);if(!e)throw missingRequiredArg(0,"rawSchemas");if(!r)throw missingRequiredArg(1,"args");if(!t.S.check(e))throw invalidType(0,["string"],e);if(!t.A.check(r))throw invalidType(1,["array"],r);var a=e.split("|");var o={};a.forEach((function(e){for(var r=0;r{"use strict";t.TrackerGroup=r(2952);t.Tracker=r(6189);t.TrackerStream=r(5849)},8313:(e,t,r)=>{"use strict";var a=r(2361).EventEmitter;var o=r(3837);var s=0;var u=e.exports=function(e){a.call(this);this.id=++s;this.name=e};o.inherits(u,a)},2952:(e,t,r)=>{"use strict";var a=r(3837);var o=r(8313);var s=r(6189);var u=r(5849);var c=e.exports=function(e){o.call(this,e);this.parentGroup=null;this.trackers=[];this.completion={};this.weight={};this.totalWeight=0;this.finished=false;this.bubbleChange=bubbleChange(this)};a.inherits(c,o);function bubbleChange(e){return function(t,r,a){e.completion[a.id]=r;if(e.finished)return;e.emit("change",t||e.name,e.completed(),e)}}c.prototype.nameInTree=function(){var e=[];var t=this;while(t){e.unshift(t.name);t=t.parentGroup}return e.join("/")};c.prototype.addUnit=function(e,t){if(e.addUnit){var r=this;while(r){if(e===r){throw new Error("Attempted to add tracker group "+e.name+" to tree that already includes it "+this.nameInTree(this))}r=r.parentGroup}e.parentGroup=this}this.weight[e.id]=t||1;this.totalWeight+=this.weight[e.id];this.trackers.push(e);this.completion[e.id]=e.completed();e.on("change",this.bubbleChange);if(!this.finished)this.emit("change",e.name,this.completion[e.id],e);return e};c.prototype.completed=function(){if(this.trackers.length===0)return 0;var e=1/this.totalWeight;var t=0;for(var r=0;r{"use strict";var a=r(3837);var o=r(675);var s=r(1722);var u=r(6189);var c=e.exports=function(e,t,r){o.Transform.call(this,r);this.tracker=new u(e,t);this.name=e;this.id=this.tracker.id;this.tracker.on("change",delegateChange(this))};a.inherits(c,o.Transform);function delegateChange(e){return function(t,r,a){e.emit("change",t,r,e)}}c.prototype._transform=function(e,t,r){this.tracker.completeWork(e.length?e.length:1);this.push(e);r()};c.prototype._flush=function(e){this.tracker.finish();e()};s(c.prototype,"tracker").method("completed").method("addWork").method("finish")},6189:(e,t,r)=>{"use strict";var a=r(3837);var o=r(8313);var s=e.exports=function(e,t){o.call(this,e);this.workDone=0;this.workTodo=t||0};a.inherits(s,o);s.prototype.completed=function(){return this.workTodo===0?0:this.workDone/this.workTodo};s.prototype.addWork=function(e){this.workTodo+=e;this.emit("change",this.name,this.completed(),this)};s.prototype.completeWork=function(e){this.workDone+=e;if(this.workDone>this.workTodo)this.workDone=this.workTodo;this.emit("change",this.name,this.completed(),this)};s.prototype.finish=function(){this.workTodo=this.workDone=1;this.emit("change",this.name,1,this)}},5706:(module,exports,__nccwpck_require__)=>{var fs=__nccwpck_require__(7147),path=__nccwpck_require__(1017),fileURLToPath=__nccwpck_require__(9001),join=path.join,dirname=path.dirname,exists=fs.accessSync&&function(e){try{fs.accessSync(e)}catch(e){return false}return true}||fs.existsSync||path.existsSync,defaults={arrow:process.env.NODE_BINDINGS_ARROW||" → ",compiled:process.env.NODE_BINDINGS_COMPILED_DIR||"compiled",platform:process.platform,arch:process.arch,nodePreGyp:"node-v"+process.versions.modules+"-"+process.platform+"-"+process.arch,version:process.versions.node,bindings:"bindings.node",try:[["module_root","build","bindings"],["module_root","build","Debug","bindings"],["module_root","build","Release","bindings"],["module_root","out","Debug","bindings"],["module_root","Debug","bindings"],["module_root","out","Release","bindings"],["module_root","Release","bindings"],["module_root","build","default","bindings"],["module_root","compiled","version","platform","arch","bindings"],["module_root","addon-build","release","install-root","bindings"],["module_root","addon-build","debug","install-root","bindings"],["module_root","addon-build","default","install-root","bindings"],["module_root","lib","binding","nodePreGyp","bindings"]]};function bindings(opts){if(typeof opts=="string"){opts={bindings:opts}}else if(!opts){opts={}}Object.keys(defaults).map((function(e){if(!(e in opts))opts[e]=defaults[e]}));if(!opts.module_root){opts.module_root=exports.getRoot(exports.getFileName())}if(path.extname(opts.bindings)!=".node"){opts.bindings+=".node"}var requireFunc=true?eval("require"):0;var tries=[],i=0,l=opts.try.length,n,b,err;for(;i{"use strict";e.exports=function(e,t){if(e===null||e===undefined){throw TypeError()}e=String(e);var r=e.length;var a=t?Number(t):0;if(Number.isNaN(a)){a=0}if(a<0||a>=r){return undefined}var o=e.charCodeAt(a);if(o>=55296&&o<=56319&&r>a+1){var s=e.charCodeAt(a+1);if(s>=56320&&s<=57343){return(o-55296)*1024+s-56320+65536}}return o}},6322:(e,t)=>{"use strict";var r="[";t.up=function up(e){return r+(e||"")+"A"};t.down=function down(e){return r+(e||"")+"B"};t.forward=function forward(e){return r+(e||"")+"C"};t.back=function back(e){return r+(e||"")+"D"};t.nextLine=function nextLine(e){return r+(e||"")+"E"};t.previousLine=function previousLine(e){return r+(e||"")+"F"};t.horizontalAbsolute=function horizontalAbsolute(e){if(e==null)throw new Error("horizontalAboslute requires a column to position to");return r+e+"G"};t.eraseData=function eraseData(){return r+"J"};t.eraseLine=function eraseLine(){return r+"K"};t.goto=function(e,t){return r+t+";"+e+"H"};t.gotoSOL=function(){return"\r"};t.beep=function(){return""};t.hideCursor=function hideCursor(){return r+"?25l"};t.showCursor=function showCursor(){return r+"?25h"};var a={reset:0,bold:1,italic:3,underline:4,inverse:7,stopBold:22,stopItalic:23,stopUnderline:24,stopInverse:27,white:37,black:30,blue:34,cyan:36,green:32,magenta:35,red:31,yellow:33,bgWhite:47,bgBlack:40,bgBlue:44,bgCyan:46,bgGreen:42,bgMagenta:45,bgRed:41,bgYellow:43,grey:90,brightBlack:90,brightRed:91,brightGreen:92,brightYellow:93,brightBlue:94,brightMagenta:95,brightCyan:96,brightWhite:97,bgGrey:100,bgBrightBlack:100,bgBrightRed:101,bgBrightGreen:102,bgBrightYellow:103,bgBrightBlue:104,bgBrightMagenta:105,bgBrightCyan:106,bgBrightWhite:107};t.color=function color(e){if(arguments.length!==1||!Array.isArray(e)){e=Array.prototype.slice.call(arguments)}return r+e.map(colorNameToCode).join(";")+"m"};function colorNameToCode(e){if(a[e]!=null)return a[e];throw new Error("Unknown color or style name: "+e)}},3487:(e,t)=>{function isArray(e){if(Array.isArray){return Array.isArray(e)}return objectToString(e)==="[object Array]"}t.isArray=isArray;function isBoolean(e){return typeof e==="boolean"}t.isBoolean=isBoolean;function isNull(e){return e===null}t.isNull=isNull;function isNullOrUndefined(e){return e==null}t.isNullOrUndefined=isNullOrUndefined;function isNumber(e){return typeof e==="number"}t.isNumber=isNumber;function isString(e){return typeof e==="string"}t.isString=isString;function isSymbol(e){return typeof e==="symbol"}t.isSymbol=isSymbol;function isUndefined(e){return e===void 0}t.isUndefined=isUndefined;function isRegExp(e){return objectToString(e)==="[object RegExp]"}t.isRegExp=isRegExp;function isObject(e){return typeof e==="object"&&e!==null}t.isObject=isObject;function isDate(e){return objectToString(e)==="[object Date]"}t.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}t.isError=isError;function isFunction(e){return typeof e==="function"}t.isFunction=isFunction;function isPrimitive(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}t.isPrimitive=isPrimitive;t.isBuffer=Buffer.isBuffer;function objectToString(e){return Object.prototype.toString.call(e)}},1722:e=>{e.exports=Delegator;function Delegator(e,t){if(!(this instanceof Delegator))return new Delegator(e,t);this.proto=e;this.target=t;this.methods=[];this.getters=[];this.setters=[];this.fluents=[]}Delegator.prototype.method=function(e){var t=this.proto;var r=this.target;this.methods.push(e);t[e]=function(){return this[r][e].apply(this[r],arguments)};return this};Delegator.prototype.access=function(e){return this.getter(e).setter(e)};Delegator.prototype.getter=function(e){var t=this.proto;var r=this.target;this.getters.push(e);t.__defineGetter__(e,(function(){return this[r][e]}));return this};Delegator.prototype.setter=function(e){var t=this.proto;var r=this.target;this.setters.push(e);t.__defineSetter__(e,(function(t){return this[r][e]=t}));return this};Delegator.prototype.fluent=function(e){var t=this.proto;var r=this.target;this.fluents.push(e);t[e]=function(t){if("undefined"!=typeof t){this[r][e]=t;return this}else{return this[r][e]}};return this}},2157:(e,t,r)=>{"use strict";var a=r(2037).platform();var o=r(2081).spawnSync;var s=r(7147).readdirSync;var u="glibc";var c="musl";var d={encoding:"utf8",env:process.env};if(!o){o=function(){return{status:126,stdout:"",stderr:""}}}function contains(e){return function(t){return t.indexOf(e)!==-1}}function versionFromMuslLdd(e){return e.split(/[\r\n]+/)[1].trim().split(/\s/)[1]}function safeReaddirSync(e){try{return s(e)}catch(e){}return[]}var f="";var p="";var h="";if(a==="linux"){var v=o("getconf",["GNU_LIBC_VERSION"],d);if(v.status===0){f=u;p=v.stdout.trim().split(" ")[1];h="getconf"}else{var _=o("ldd",["--version"],d);if(_.status===0&&_.stdout.indexOf(c)!==-1){f=c;p=versionFromMuslLdd(_.stdout);h="ldd"}else if(_.status===1&&_.stderr.indexOf(c)!==-1){f=c;p=versionFromMuslLdd(_.stderr);h="ldd"}else{var g=safeReaddirSync("/lib");if(g.some(contains("-linux-gnu"))){f=u;h="filesystem"}else if(g.some(contains("libc.musl-"))){f=c;h="filesystem"}else if(g.some(contains("ld-musl-"))){f=c;h="filesystem"}else{var y=safeReaddirSync("/usr/sbin");if(y.some(contains("glibc"))){f=u;h="filesystem"}}}}}var m=f!==""&&f!==u;e.exports={GLIBC:u,MUSL:c,family:f,version:p,method:h,isNonGlibcLinux:m}},9001:(e,t,r)=>{var a=r(1017).sep||"/";e.exports=fileUriToPath;function fileUriToPath(e){if("string"!=typeof e||e.length<=7||"file://"!=e.substring(0,7)){throw new TypeError("must pass in a file:// URI to convert to a file path")}var t=decodeURI(e.substring(7));var r=t.indexOf("/");var o=t.substring(0,r);var s=t.substring(r+1);if("localhost"==o)o="";if(o){o=a+a+o}s=s.replace(/^(.+)\|/,"$1:");if(a=="\\"){s=s.replace(/\//g,"\\")}if(/^.+\:/.test(s)){}else{s=a+s}return o+s}},1271:(e,t,r)=>{"use strict";var a=r(1021);var o=r(5791);e.exports={activityIndicator:function(e,t,r){if(e.spun==null)return;return a(t,e.spun)},progressbar:function(e,t,r){if(e.completed==null)return;return o(t,r,e.completed)}}},2479:(e,t,r)=>{"use strict";var a=r(3837);var o=t.User=function User(e){var t=new Error(e);Error.captureStackTrace(t,User);t.code="EGAUGE";return t};t.MissingTemplateValue=function MissingTemplateValue(e,t){var r=new o(a.format('Missing template value "%s"',e.type));Error.captureStackTrace(r,MissingTemplateValue);r.template=e;r.values=t;return r};t.Internal=function Internal(e){var t=new Error(e);Error.captureStackTrace(t,Internal);t.code="EGAUGEINTERNAL";return t}},3278:e=>{"use strict";e.exports=isWin32()||isColorTerm();function isWin32(){return process.platform==="win32"}function isColorTerm(){var e=/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i;return!!process.env.COLORTERM||e.test(process.env.TERM)}},6054:(e,t,r)=>{"use strict";var a=r(4708);var o=r(7963);var s=r(3278);var u=r(2028);var c=r(7987);var d=r(75);var f=r(9186);var p=r(6401);e.exports=Gauge;function callWith(e,t){return function(){return t.call(e)}}function Gauge(e,t){var r,o;if(e&&e.write){o=e;r=t||{}}else if(t&&t.write){o=t;r=e||{}}else{o=f.stderr;r=e||t||{}}this._status={spun:0,section:"",subsection:""};this._paused=false;this._disabled=true;this._showing=false;this._onScreen=false;this._needsRedraw=false;this._hideCursor=r.hideCursor==null?true:r.hideCursor;this._fixedFramerate=r.fixedFramerate==null?!/^v0\.8\./.test(f.version):r.fixedFramerate;this._lastUpdateAt=null;this._updateInterval=r.updateInterval==null?50:r.updateInterval;this._themes=r.themes||c;this._theme=r.theme;var s=this._computeTheme(r.theme);var u=r.template||[{type:"progressbar",length:20},{type:"activityIndicator",kerning:1,length:1},{type:"section",kerning:1,default:""},{type:"subsection",kerning:1,default:""}];this.setWriteTo(o,r.tty);var d=r.Plumbing||a;this._gauge=new d(s,u,this.getWidth());this._$$doRedraw=callWith(this,this._doRedraw);this._$$handleSizeChange=callWith(this,this._handleSizeChange);this._cleanupOnExit=r.cleanupOnExit==null||r.cleanupOnExit;this._removeOnExit=null;if(r.enabled||r.enabled==null&&this._tty&&this._tty.isTTY){this.enable()}else{this.disable()}}Gauge.prototype={};Gauge.prototype.isEnabled=function(){return!this._disabled};Gauge.prototype.setTemplate=function(e){this._gauge.setTemplate(e);if(this._showing)this._requestRedraw()};Gauge.prototype._computeTheme=function(e){if(!e)e={};if(typeof e==="string"){e=this._themes.getTheme(e)}else if(e&&(Object.keys(e).length===0||e.hasUnicode!=null||e.hasColor!=null)){var t=e.hasUnicode==null?o():e.hasUnicode;var r=e.hasColor==null?s:e.hasColor;e=this._themes.getDefault({hasUnicode:t,hasColor:r,platform:e.platform})}return e};Gauge.prototype.setThemeset=function(e){this._themes=e;this.setTheme(this._theme)};Gauge.prototype.setTheme=function(e){this._gauge.setTheme(this._computeTheme(e));if(this._showing)this._requestRedraw();this._theme=e};Gauge.prototype._requestRedraw=function(){this._needsRedraw=true;if(!this._fixedFramerate)this._doRedraw()};Gauge.prototype.getWidth=function(){return(this._tty&&this._tty.columns||80)-1};Gauge.prototype.setWriteTo=function(e,t){var r=!this._disabled;if(r)this.disable();this._writeTo=e;this._tty=t||e===f.stderr&&f.stdout.isTTY&&f.stdout||e.isTTY&&e||this._tty;if(this._gauge)this._gauge.setWidth(this.getWidth());if(r)this.enable()};Gauge.prototype.enable=function(){if(!this._disabled)return;this._disabled=false;if(this._tty)this._enableEvents();if(this._showing)this.show()};Gauge.prototype.disable=function(){if(this._disabled)return;if(this._showing){this._lastUpdateAt=null;this._showing=false;this._doRedraw();this._showing=true}this._disabled=true;if(this._tty)this._disableEvents()};Gauge.prototype._enableEvents=function(){if(this._cleanupOnExit){this._removeOnExit=u(callWith(this,this.disable))}this._tty.on("resize",this._$$handleSizeChange);if(this._fixedFramerate){this.redrawTracker=d(this._$$doRedraw,this._updateInterval);if(this.redrawTracker.unref)this.redrawTracker.unref()}};Gauge.prototype._disableEvents=function(){this._tty.removeListener("resize",this._$$handleSizeChange);if(this._fixedFramerate)clearInterval(this.redrawTracker);if(this._removeOnExit)this._removeOnExit()};Gauge.prototype.hide=function(e){if(this._disabled)return e&&f.nextTick(e);if(!this._showing)return e&&f.nextTick(e);this._showing=false;this._doRedraw();e&&p(e)};Gauge.prototype.show=function(e,t){this._showing=true;if(typeof e==="string"){this._status.section=e}else if(typeof e==="object"){var r=Object.keys(e);for(var a=0;a{"use strict";var a=r(8753);e.exports=function(e){if(a(e)){return false}if(e>=4352&&(e<=4447||9001===e||9002===e||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141)){return true}return false}},5511:(e,t,r)=>{"use strict";var a=r(7518);var o=r(6708);var s=r(6062);e.exports=function(e){if(typeof e!=="string"||e.length===0){return 0}var t=0;e=a(e);for(var r=0;r=127&&u<=159){continue}if(u>=65536){r++}if(s(u)){t+=2}else{t++}}return t}},4708:(e,t,r)=>{"use strict";var a=r(6322);var o=r(4293);var s=r(5534);var u=e.exports=function(e,t,r){if(!r)r=80;s("OAN",[e,t,r]);this.showing=false;this.theme=e;this.width=r;this.template=t};u.prototype={};u.prototype.setTheme=function(e){s("O",[e]);this.theme=e};u.prototype.setTemplate=function(e){s("A",[e]);this.template=e};u.prototype.setWidth=function(e){s("N",[e]);this.width=e};u.prototype.hide=function(){return a.gotoSOL()+a.eraseLine()};u.prototype.hideCursor=a.hideCursor;u.prototype.showCursor=a.showCursor;u.prototype.show=function(e){var t=Object.create(this.theme);for(var r in e){t[r]=e[r]}return o(this.width,this.template,t).trim()+a.color("reset")+a.eraseLine()+a.gotoSOL()}},9186:e=>{"use strict";e.exports=process},5791:(e,t,r)=>{"use strict";var a=r(5534);var o=r(4293);var s=r(2343);var u=r(5511);e.exports=function(e,t,r){a("ONN",[e,t,r]);if(r<0)r=0;if(r>1)r=1;if(t<=0)return"";var s=Math.round(t*r);var u=t-s;var c=[{type:"complete",value:repeat(e.complete,s),length:s},{type:"remaining",value:repeat(e.remaining,u),length:u}];return o(t,c,e)};function repeat(e,t){var r="";var a=t;do{if(a%2){r+=e}a=Math.floor(a/2);e+=e}while(a&&u(r){"use strict";var a=r(7568);var o=r(5534);var s=r(1800);var u=r(2343);var c=r(2479);var d=r(5205);function renderValueWithValues(e){return function(t){return renderValue(t,e)}}var f=e.exports=function(e,t,r){var o=prepareItems(e,t,r);var s=o.map(renderValueWithValues(r)).join("");return a.left(u(s,e),e)};function preType(e){var t=e.type[0].toUpperCase()+e.type.slice(1);return"pre"+t}function postType(e){var t=e.type[0].toUpperCase()+e.type.slice(1);return"post"+t}function hasPreOrPost(e,t){if(!e.type)return;return t[preType(e)]||t[postType(e)]}function generatePreAndPost(e,t){var r=s({},e);var a=Object.create(t);var o=[];var u=preType(r);var c=postType(r);if(a[u]){o.push({value:a[u]});a[u]=null}r.minLength=null;r.length=null;r.maxLength=null;o.push(r);a[r.type]=a[r.type];if(a[c]){o.push({value:a[c]});a[c]=null}return function(e,t,r){return f(r,o,a)}}function prepareItems(e,t,r){function cloneAndObjectify(t,a,o){var s=new d(t,e);var u=s.type;if(s.value==null){if(!(u in r)){if(s.default==null){throw new c.MissingTemplateValue(s,r)}else{s.value=s.default}}else{s.value=r[u]}}if(s.value==null||s.value==="")return null;s.index=a;s.first=a===0;s.last=a===o.length-1;if(hasPreOrPost(s,r))s.value=generatePreAndPost(s,r);return s}var a=t.map(cloneAndObjectify).filter((function(e){return e!=null}));var o=0;var s=e;var u=a.length;function consumeSpace(e){if(e>s)e=s;o+=e;s-=e}function finishSizing(e,t){if(e.finished)throw new c.Internal("Tried to finish template item that was already finished");if(t===Infinity)throw new c.Internal("Length of template item cannot be infinity");if(t!=null)e.length=t;e.minLength=null;e.maxLength=null;--u;e.finished=true;if(e.length==null)e.length=e.getBaseLength();if(e.length==null)throw new c.Internal("Finished template items must have a length");consumeSpace(e.getLength())}a.forEach((function(e){if(!e.kerning)return;var t=e.first?0:a[e.index-1].padRight;if(!e.first&&t=h){finishSizing(e,e.minLength);p=true}}))}while(p&&f++{"use strict";var a=r(9186);try{e.exports=setImmediate}catch(t){e.exports=a.nextTick}},75:e=>{"use strict";e.exports=setInterval},1021:e=>{"use strict";e.exports=function spin(e,t){return e[t%e.length]}},5205:(e,t,r)=>{"use strict";var a=r(5511);e.exports=TemplateItem;function isPercent(e){if(typeof e!=="string")return false;return e.slice(-1)==="%"}function percent(e){return Number(e.slice(0,-1))/100}function TemplateItem(e,t){this.overallOutputLength=t;this.finished=false;this.type=null;this.value=null;this.length=null;this.maxLength=null;this.minLength=null;this.kerning=null;this.align="left";this.padLeft=0;this.padRight=0;this.index=null;this.first=null;this.last=null;if(typeof e==="string"){this.value=e}else{for(var r in e)this[r]=e[r]}if(isPercent(this.length)){this.length=Math.round(this.overallOutputLength*percent(this.length))}if(isPercent(this.minLength)){this.minLength=Math.round(this.overallOutputLength*percent(this.minLength))}if(isPercent(this.maxLength)){this.maxLength=Math.round(this.overallOutputLength*percent(this.maxLength))}return this}TemplateItem.prototype={};TemplateItem.prototype.getBaseLength=function(){var e=this.length;if(e==null&&typeof this.value==="string"&&this.maxLength==null&&this.minLength==null){e=a(this.value)}return e};TemplateItem.prototype.getLength=function(){var e=this.getBaseLength();if(e==null)return null;return e+this.padLeft+this.padRight};TemplateItem.prototype.getMaxLength=function(){if(this.maxLength==null)return null;return this.maxLength+this.padLeft+this.padRight};TemplateItem.prototype.getMinLength=function(){if(this.minLength==null)return null;return this.minLength+this.padLeft+this.padRight}},3117:(e,t,r)=>{"use strict";var a=r(1800);e.exports=function(){return o.newThemeSet()};var o={};o.baseTheme=r(1271);o.newTheme=function(e,t){if(!t){t=e;e=this.baseTheme}return a({},e,t)};o.getThemeNames=function(){return Object.keys(this.themes)};o.addTheme=function(e,t,r){this.themes[e]=this.newTheme(t,r)};o.addToAllThemes=function(e){var t=this.themes;Object.keys(t).forEach((function(r){a(t[r],e)}));a(this.baseTheme,e)};o.getTheme=function(e){if(!this.themes[e])throw this.newMissingThemeError(e);return this.themes[e]};o.setDefault=function(e,t){if(t==null){t=e;e={}}var r=e.platform==null?"fallback":e.platform;var a=!!e.hasUnicode;var o=!!e.hasColor;if(!this.defaults[r])this.defaults[r]={true:{},false:{}};this.defaults[r][a][o]=t};o.getDefault=function(e){if(!e)e={};var t=e.platform||process.platform;var r=this.defaults[t]||this.defaults.fallback;var o=!!e.hasUnicode;var s=!!e.hasColor;if(!r)throw this.newMissingDefaultThemeError(t,o,s);if(!r[o][s]){if(o&&s&&r[!o][s]){o=false}else if(o&&s&&r[o][!s]){s=false}else if(o&&s&&r[!o][!s]){o=false;s=false}else if(o&&!s&&r[!o][s]){o=false}else if(!o&&s&&r[o][!s]){s=false}else if(r===this.defaults.fallback){throw this.newMissingDefaultThemeError(t,o,s)}}if(r[o][s]){return this.getTheme(r[o][s])}else{return this.getDefault(a({},e,{platform:"fallback"}))}};o.newMissingThemeError=function newMissingThemeError(e){var t=new Error('Could not find a gauge theme named "'+e+'"');Error.captureStackTrace.call(t,newMissingThemeError);t.theme=e;t.code="EMISSINGTHEME";return t};o.newMissingDefaultThemeError=function newMissingDefaultThemeError(e,t,r){var a=new Error("Could not find a gauge theme for your platform/unicode/color use combo:\n"+" platform = "+e+"\n"+" hasUnicode = "+t+"\n"+" hasColor = "+r);Error.captureStackTrace.call(a,newMissingDefaultThemeError);a.platform=e;a.hasUnicode=t;a.hasColor=r;a.code="EMISSINGTHEME";return a};o.newThemeSet=function(){var themeset=function(e){return themeset.getDefault(e)};return a(themeset,o,{themes:a({},this.themes),baseTheme:a({},this.baseTheme),defaults:JSON.parse(JSON.stringify(this.defaults||{}))})}},7987:(e,t,r)=>{"use strict";var a=r(6322);var o=r(3117);var s=e.exports=new o;s.addTheme("ASCII",{preProgressbar:"[",postProgressbar:"]",progressbarTheme:{complete:"#",remaining:"."},activityIndicatorTheme:"-\\|/",preSubsection:">"});s.addTheme("colorASCII",s.getTheme("ASCII"),{progressbarTheme:{preComplete:a.color("inverse"),complete:" ",postComplete:a.color("stopInverse"),preRemaining:a.color("brightBlack"),remaining:".",postRemaining:a.color("reset")}});s.addTheme("brailleSpinner",{preProgressbar:"⸨",postProgressbar:"⸩",progressbarTheme:{complete:"░",remaining:"⠂"},activityIndicatorTheme:"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏",preSubsection:">"});s.addTheme("colorBrailleSpinner",s.getTheme("brailleSpinner"),{progressbarTheme:{preComplete:a.color("inverse"),complete:" ",postComplete:a.color("stopInverse"),preRemaining:a.color("brightBlack"),remaining:"░",postRemaining:a.color("reset")}});s.setDefault({},"ASCII");s.setDefault({hasColor:true},"colorASCII");s.setDefault({platform:"darwin",hasUnicode:true},"brailleSpinner");s.setDefault({platform:"darwin",hasUnicode:true,hasColor:true},"colorBrailleSpinner")},2343:(e,t,r)=>{"use strict";var a=r(5511);var o=r(7518);e.exports=wideTruncate;function wideTruncate(e,t){if(a(e)===0)return e;if(t<=0)return"";if(a(e)<=t)return e;var r=o(e);var s=e.length+r.length;var u=e.slice(0,t+s);while(a(u)>t){u=u.slice(0,-1)}return u}},9132:e=>{"use strict";e.exports=clone;var t=Object.getPrototypeOf||function(e){return e.__proto__};function clone(e){if(e===null||typeof e!=="object")return e;if(e instanceof Object)var r={__proto__:t(e)};else var r=Object.create(null);Object.getOwnPropertyNames(e).forEach((function(t){Object.defineProperty(r,t,Object.getOwnPropertyDescriptor(e,t))}));return r}},552:(e,t,r)=>{var a=r(7147);var o=r(1290);var s=r(4410);var u=r(9132);var c=r(3837);var d;var f;if(typeof Symbol==="function"&&typeof Symbol.for==="function"){d=Symbol.for("graceful-fs.queue");f=Symbol.for("graceful-fs.previous")}else{d="___graceful-fs.queue";f="___graceful-fs.previous"}function noop(){}function publishQueue(e,t){Object.defineProperty(e,d,{get:function(){return t}})}var p=noop;if(c.debuglog)p=c.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))p=function(){var e=c.format.apply(c,arguments);e="GFS4: "+e.split(/\n/).join("\nGFS4: ");console.error(e)};if(!a[d]){var h=global[d]||[];publishQueue(a,h);a.close=function(e){function close(t,r){return e.call(a,t,(function(e){if(!e){resetQueue()}if(typeof r==="function")r.apply(this,arguments)}))}Object.defineProperty(close,f,{value:e});return close}(a.close);a.closeSync=function(e){function closeSync(t){e.apply(a,arguments);resetQueue()}Object.defineProperty(closeSync,f,{value:e});return closeSync}(a.closeSync);if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")){process.on("exit",(function(){p(a[d]);r(9491).equal(a[d].length,0)}))}}if(!global[d]){publishQueue(global,a[d])}e.exports=patch(u(a));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!a.__patched){e.exports=patch(a);a.__patched=true}function patch(e){o(e);e.gracefulify=patch;e.createReadStream=createReadStream;e.createWriteStream=createWriteStream;var t=e.readFile;e.readFile=readFile;function readFile(e,r,a){if(typeof r==="function")a=r,r=null;return go$readFile(e,r,a);function go$readFile(e,r,a,o){return t(e,r,(function(t){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))enqueue([go$readFile,[e,r,a],t,o||Date.now(),Date.now()]);else{if(typeof a==="function")a.apply(this,arguments)}}))}}var r=e.writeFile;e.writeFile=writeFile;function writeFile(e,t,a,o){if(typeof a==="function")o=a,a=null;return go$writeFile(e,t,a,o);function go$writeFile(e,t,a,o,s){return r(e,t,a,(function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))enqueue([go$writeFile,[e,t,a,o],r,s||Date.now(),Date.now()]);else{if(typeof o==="function")o.apply(this,arguments)}}))}}var a=e.appendFile;if(a)e.appendFile=appendFile;function appendFile(e,t,r,o){if(typeof r==="function")o=r,r=null;return go$appendFile(e,t,r,o);function go$appendFile(e,t,r,o,s){return a(e,t,r,(function(a){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))enqueue([go$appendFile,[e,t,r,o],a,s||Date.now(),Date.now()]);else{if(typeof o==="function")o.apply(this,arguments)}}))}}var u=e.copyFile;if(u)e.copyFile=copyFile;function copyFile(e,t,r,a){if(typeof r==="function"){a=r;r=0}return go$copyFile(e,t,r,a);function go$copyFile(e,t,r,a,o){return u(e,t,r,(function(s){if(s&&(s.code==="EMFILE"||s.code==="ENFILE"))enqueue([go$copyFile,[e,t,r,a],s,o||Date.now(),Date.now()]);else{if(typeof a==="function")a.apply(this,arguments)}}))}}var c=e.readdir;e.readdir=readdir;function readdir(e,t,r){if(typeof t==="function")r=t,t=null;return go$readdir(e,t,r);function go$readdir(e,t,r,a){return c(e,t,(function(o,s){if(o&&(o.code==="EMFILE"||o.code==="ENFILE"))enqueue([go$readdir,[e,t,r],o,a||Date.now(),Date.now()]);else{if(s&&s.sort)s.sort();if(typeof r==="function")r.call(this,o,s)}}))}}if(process.version.substr(0,4)==="v0.8"){var d=s(e);ReadStream=d.ReadStream;WriteStream=d.WriteStream}var f=e.ReadStream;if(f){ReadStream.prototype=Object.create(f.prototype);ReadStream.prototype.open=ReadStream$open}var p=e.WriteStream;if(p){WriteStream.prototype=Object.create(p.prototype);WriteStream.prototype.open=WriteStream$open}Object.defineProperty(e,"ReadStream",{get:function(){return ReadStream},set:function(e){ReadStream=e},enumerable:true,configurable:true});Object.defineProperty(e,"WriteStream",{get:function(){return WriteStream},set:function(e){WriteStream=e},enumerable:true,configurable:true});var h=ReadStream;Object.defineProperty(e,"FileReadStream",{get:function(){return h},set:function(e){h=e},enumerable:true,configurable:true});var v=WriteStream;Object.defineProperty(e,"FileWriteStream",{get:function(){return v},set:function(e){v=e},enumerable:true,configurable:true});function ReadStream(e,t){if(this instanceof ReadStream)return f.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var e=this;open(e.path,e.flags,e.mode,(function(t,r){if(t){if(e.autoClose)e.destroy();e.emit("error",t)}else{e.fd=r;e.emit("open",r);e.read()}}))}function WriteStream(e,t){if(this instanceof WriteStream)return p.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var e=this;open(e.path,e.flags,e.mode,(function(t,r){if(t){e.destroy();e.emit("error",t)}else{e.fd=r;e.emit("open",r)}}))}function createReadStream(t,r){return new e.ReadStream(t,r)}function createWriteStream(t,r){return new e.WriteStream(t,r)}var _=e.open;e.open=open;function open(e,t,r,a){if(typeof r==="function")a=r,r=null;return go$open(e,t,r,a);function go$open(e,t,r,a,o){return _(e,t,r,(function(s,u){if(s&&(s.code==="EMFILE"||s.code==="ENFILE"))enqueue([go$open,[e,t,r,a],s,o||Date.now(),Date.now()]);else{if(typeof a==="function")a.apply(this,arguments)}}))}}return e}function enqueue(e){p("ENQUEUE",e[0].name,e[1]);a[d].push(e);retry()}var v;function resetQueue(){var e=Date.now();for(var t=0;t2){a[d][t][3]=e;a[d][t][4]=e}}retry()}function retry(){clearTimeout(v);v=undefined;if(a[d].length===0)return;var e=a[d].shift();var t=e[0];var r=e[1];var o=e[2];var s=e[3];var u=e[4];if(s===undefined){p("RETRY",t.name,r);t.apply(null,r)}else if(Date.now()-s>=6e4){p("TIMEOUT",t.name,r);var c=r.pop();if(typeof c==="function")c.call(null,o)}else{var f=Date.now()-u;var h=Math.max(u-s,1);var _=Math.min(h*1.2,100);if(f>=_){p("RETRY",t.name,r);t.apply(null,r.concat([s]))}else{a[d].push(e)}}if(v===undefined){v=setTimeout(retry,0)}}},4410:(e,t,r)=>{var a=r(2781).Stream;e.exports=legacy;function legacy(e){return{ReadStream:ReadStream,WriteStream:WriteStream};function ReadStream(t,r){if(!(this instanceof ReadStream))return new ReadStream(t,r);a.call(this);var o=this;this.path=t;this.fd=null;this.readable=true;this.paused=false;this.flags="r";this.mode=438;this.bufferSize=64*1024;r=r||{};var s=Object.keys(r);for(var u=0,c=s.length;uthis.end){throw new Error("start must be <= end")}this.pos=this.start}if(this.fd!==null){process.nextTick((function(){o._read()}));return}e.open(this.path,this.flags,this.mode,(function(e,t){if(e){o.emit("error",e);o.readable=false;return}o.fd=t;o.emit("open",t);o._read()}))}function WriteStream(t,r){if(!(this instanceof WriteStream))return new WriteStream(t,r);a.call(this);this.path=t;this.fd=null;this.writable=true;this.flags="w";this.encoding="binary";this.mode=438;this.bytesWritten=0;r=r||{};var o=Object.keys(r);for(var s=0,u=o.length;s= zero")}this.pos=this.start}this.busy=false;this._queue=[];if(this.fd===null){this._open=e.open;this._queue.push([this._open,this.path,this.flags,this.mode,undefined]);this.flush()}}}},1290:(e,t,r)=>{var a=r(2057);var o=process.cwd;var s=null;var u=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!s)s=o.call(process);return s};try{process.cwd()}catch(e){}if(typeof process.chdir==="function"){var c=process.chdir;process.chdir=function(e){s=null;c.call(process,e)};if(Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,c)}e.exports=patch;function patch(e){if(a.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)){patchLchmod(e)}if(!e.lutimes){patchLutimes(e)}e.chown=chownFix(e.chown);e.fchown=chownFix(e.fchown);e.lchown=chownFix(e.lchown);e.chmod=chmodFix(e.chmod);e.fchmod=chmodFix(e.fchmod);e.lchmod=chmodFix(e.lchmod);e.chownSync=chownFixSync(e.chownSync);e.fchownSync=chownFixSync(e.fchownSync);e.lchownSync=chownFixSync(e.lchownSync);e.chmodSync=chmodFixSync(e.chmodSync);e.fchmodSync=chmodFixSync(e.fchmodSync);e.lchmodSync=chmodFixSync(e.lchmodSync);e.stat=statFix(e.stat);e.fstat=statFix(e.fstat);e.lstat=statFix(e.lstat);e.statSync=statFixSync(e.statSync);e.fstatSync=statFixSync(e.fstatSync);e.lstatSync=statFixSync(e.lstatSync);if(!e.lchmod){e.lchmod=function(e,t,r){if(r)process.nextTick(r)};e.lchmodSync=function(){}}if(!e.lchown){e.lchown=function(e,t,r,a){if(a)process.nextTick(a)};e.lchownSync=function(){}}if(u==="win32"){e.rename=function(t){return function(r,a,o){var s=Date.now();var u=0;t(r,a,(function CB(c){if(c&&(c.code==="EACCES"||c.code==="EPERM")&&Date.now()-s<6e4){setTimeout((function(){e.stat(a,(function(e,s){if(e&&e.code==="ENOENT")t(r,a,CB);else o(c)}))}),u);if(u<100)u+=10;return}if(o)o(c)}))}}(e.rename)}e.read=function(t){function read(r,a,o,s,u,c){var d;if(c&&typeof c==="function"){var f=0;d=function(p,h,v){if(p&&p.code==="EAGAIN"&&f<10){f++;return t.call(e,r,a,o,s,u,d)}c.apply(this,arguments)}}return t.call(e,r,a,o,s,u,d)}if(Object.setPrototypeOf)Object.setPrototypeOf(read,t);return read}(e.read);e.readSync=function(t){return function(r,a,o,s,u){var c=0;while(true){try{return t.call(e,r,a,o,s,u)}catch(e){if(e.code==="EAGAIN"&&c<10){c++;continue}throw e}}}}(e.readSync);function patchLchmod(e){e.lchmod=function(t,r,o){e.open(t,a.O_WRONLY|a.O_SYMLINK,r,(function(t,a){if(t){if(o)o(t);return}e.fchmod(a,r,(function(t){e.close(a,(function(e){if(o)o(t||e)}))}))}))};e.lchmodSync=function(t,r){var o=e.openSync(t,a.O_WRONLY|a.O_SYMLINK,r);var s=true;var u;try{u=e.fchmodSync(o,r);s=false}finally{if(s){try{e.closeSync(o)}catch(e){}}else{e.closeSync(o)}}return u}}function patchLutimes(e){if(a.hasOwnProperty("O_SYMLINK")){e.lutimes=function(t,r,o,s){e.open(t,a.O_SYMLINK,(function(t,a){if(t){if(s)s(t);return}e.futimes(a,r,o,(function(t){e.close(a,(function(e){if(s)s(t||e)}))}))}))};e.lutimesSync=function(t,r,o){var s=e.openSync(t,a.O_SYMLINK);var u;var c=true;try{u=e.futimesSync(s,r,o);c=false}finally{if(c){try{e.closeSync(s)}catch(e){}}else{e.closeSync(s)}}return u}}else{e.lutimes=function(e,t,r,a){if(a)process.nextTick(a)};e.lutimesSync=function(){}}}function chmodFix(t){if(!t)return t;return function(r,a,o){return t.call(e,r,a,(function(e){if(chownErOk(e))e=null;if(o)o.apply(this,arguments)}))}}function chmodFixSync(t){if(!t)return t;return function(r,a){try{return t.call(e,r,a)}catch(e){if(!chownErOk(e))throw e}}}function chownFix(t){if(!t)return t;return function(r,a,o,s){return t.call(e,r,a,o,(function(e){if(chownErOk(e))e=null;if(s)s.apply(this,arguments)}))}}function chownFixSync(t){if(!t)return t;return function(r,a,o){try{return t.call(e,r,a,o)}catch(e){if(!chownErOk(e))throw e}}}function statFix(t){if(!t)return t;return function(r,a,o){if(typeof a==="function"){o=a;a=null}function callback(e,t){if(t){if(t.uid<0)t.uid+=4294967296;if(t.gid<0)t.gid+=4294967296}if(o)o.apply(this,arguments)}return a?t.call(e,r,a,callback):t.call(e,r,callback)}}function statFixSync(t){if(!t)return t;return function(r,a){var o=a?t.call(e,r,a):t.call(e,r);if(o){if(o.uid<0)o.uid+=4294967296;if(o.gid<0)o.gid+=4294967296}return o}}function chownErOk(e){if(!e)return true;if(e.code==="ENOSYS")return true;var t=!process.getuid||process.getuid()!==0;if(t){if(e.code==="EINVAL"||e.code==="EPERM")return true}return false}}},7963:(e,t,r)=>{"use strict";var a=r(2037);var o=e.exports=function(){if(a.type()=="Windows_NT"){return false}var e=/UTF-?8$/i;var t=process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG;return e.test(t)}},6919:(e,t,r)=>{try{var a=r(3837);if(typeof a.inherits!=="function")throw"";e.exports=a.inherits}catch(t){e.exports=r(7526)}},7526:e=>{if(typeof Object.create==="function"){e.exports=function inherits(e,t){if(t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}}else{e.exports=function inherits(e,t){if(t){e.super_=t;var TempCtor=function(){};TempCtor.prototype=t.prototype;e.prototype=new TempCtor;e.prototype.constructor=e}}}},9842:e=>{var t={}.toString;e.exports=Array.isArray||function(e){return t.call(e)=="[object Array]"}},3277:(module,__unused_webpack_exports,__nccwpck_require__)=>{var fs=__nccwpck_require__(7147);var path=__nccwpck_require__(1017);var os=__nccwpck_require__(2037);var runtimeRequire=true?eval("require"):0;var vars=process.config&&process.config.variables||{};var prebuildsOnly=!!process.env.PREBUILDS_ONLY;var abi=process.versions.modules;var runtime=isElectron()?"electron":"node";var arch=os.arch();var platform=os.platform();var libc=process.env.LIBC||(isAlpine(platform)?"musl":"glibc");var armv=process.env.ARM_VERSION||(arch==="arm64"?"8":vars.arm_version)||"";var uv=(process.versions.uv||"").split(".")[0];module.exports=load;function load(e){return runtimeRequire(load.path(e))}load.path=function(e){e=path.resolve(e||".");try{var t=runtimeRequire(path.join(e,"package.json")).name.toUpperCase().replace(/-/g,"_");if(process.env[t+"_PREBUILD"])e=process.env[t+"_PREBUILD"]}catch(e){}if(!prebuildsOnly){var r=getFirst(path.join(e,"build/Release"),matchBuild);if(r)return r;var a=getFirst(path.join(e,"build/Debug"),matchBuild);if(a)return a}var o=resolve(e);if(o)return o;var s=resolve(path.dirname(process.execPath));if(s)return s;var u=["platform="+platform,"arch="+arch,"runtime="+runtime,"abi="+abi,"uv="+uv,armv?"armv="+armv:"","libc="+libc,"node="+process.versions.node,process.versions&&process.versions.electron?"electron="+process.versions.electron:"",true?"webpack=true":0].filter(Boolean).join(" ");throw new Error("No native build was found for "+u+"\n loaded from: "+e+"\n");function resolve(e){var t=path.join(e,"prebuilds",platform+"-"+arch);var r=readdirSync(t).map(parseTags);var a=r.filter(matchTags(runtime,abi));var o=a.sort(compareTags(runtime))[0];if(o)return path.join(t,o.file)}};function readdirSync(e){try{return fs.readdirSync(e)}catch(e){return[]}}function getFirst(e,t){var r=readdirSync(e).filter(t);return r[0]&&path.join(e,r[0])}function matchBuild(e){return/\.node$/.test(e)}function parseTags(e){var t=e.split(".");var r=t.pop();var a={file:e,specificity:0};if(r!=="node")return;for(var o=0;or.specificity?-1:1}else{return 0}}}function isElectron(){if(process.versions&&process.versions.electron)return true;if(process.env.ELECTRON_RUN_AS_NODE)return true;return typeof window!=="undefined"&&window.process&&window.process.type==="renderer"}function isAlpine(e){return e==="linux"&&fs.existsSync("/etc/alpine-release")}load.parseTags=parseTags;load.matchTags=matchTags;load.compareTags=compareTags},9248:(e,t,r)=>{"use strict";var a=r(7147);var o=r(3632);var s=r(9658);e.exports=t;var u=process.version.substr(1).replace(/-.*$/,"").split(".").map((function(e){return+e}));var c=["build","clean","configure","package","publish","reveal","testbinary","testpackage","unpublish"];var d="napi_build_version=";e.exports.get_napi_version=function(e){var t=process.versions.napi;if(!t){if(u[0]===9&&u[1]>=3)t=2;else if(u[0]===8)t=1}return t};e.exports.get_napi_version_as_string=function(t){var r=e.exports.get_napi_version(t);return r?""+r:""};e.exports.validate_package_json=function(t,r){var a=t.binary;var o=pathOK(a.module_path);var s=pathOK(a.remote_path);var u=pathOK(a.package_name);var c=e.exports.get_napi_build_versions(t,r,true);var d=e.exports.get_napi_build_versions_raw(t);if(c){c.forEach((function(e){if(!(parseInt(e,10)===e&&e>0)){throw new Error("All values specified in napi_versions must be positive integers.")}}))}if(c&&(!o||!s&&!u)){throw new Error("When napi_versions is specified; module_path and either remote_path or "+"package_name must contain the substitution string '{napi_build_version}`.")}if((o||s||u)&&!d){throw new Error("When the substitution string '{napi_build_version}` is specified in "+"module_path, remote_path, or package_name; napi_versions must also be specified.")}if(c&&!e.exports.get_best_napi_build_version(t,r)&&e.exports.build_napi_only(t)){throw new Error("The N-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports N-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}if(d&&!c&&e.exports.build_napi_only(t)){throw new Error("The N-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports N-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}};function pathOK(e){return e&&(e.indexOf("{napi_build_version}")!==-1||e.indexOf("{node_napi_label}")!==-1)}e.exports.expand_commands=function(t,r,a){var o=[];var s=e.exports.get_napi_build_versions(t,r);a.forEach((function(a){if(s&&a.name==="install"){var u=e.exports.get_best_napi_build_version(t,r);var f=u?[d+u]:[];o.push({name:a.name,args:f})}else if(s&&c.indexOf(a.name)!==-1){s.forEach((function(e){var t=a.args.slice();t.push(d+e);o.push({name:a.name,args:t})}))}else{o.push(a)}}));return o};e.exports.get_napi_build_versions=function(t,r,a){var o=[];var u=e.exports.get_napi_version(r?r.target:undefined);if(t.binary&&t.binary.napi_versions){t.binary.napi_versions.forEach((function(e){var t=o.indexOf(e)!==-1;if(!t&&u&&e<=u){o.push(e)}else if(a&&!t&&u){s.info("This Node instance does not support builds for N-API version",e)}}))}if(r&&r["build-latest-napi-version-only"]){var c=0;o.forEach((function(e){if(e>c)c=e}));o=c?[c]:[]}return o.length?o:undefined};e.exports.get_napi_build_versions_raw=function(e){var t=[];if(e.binary&&e.binary.napi_versions){e.binary.napi_versions.forEach((function(e){if(t.indexOf(e)===-1){t.push(e)}}))}return t.length?t:undefined};e.exports.get_command_arg=function(e){return d+e};e.exports.get_napi_build_version_from_command_args=function(e){for(var t=0;ta&&e<=s){a=e}}))}return a===0?undefined:a};e.exports.build_napi_only=function(e){return e.binary&&e.binary.package_name&&e.binary.package_name.indexOf("{node_napi_label}")===-1}},5574:(e,t,r)=>{"use strict";e.exports=t;var a=r(1017);var o=r(7849);var s=r(7310);var u=r(2157);var c=r(9248);var d;if(process.env.NODE_PRE_GYP_ABI_CROSSWALK){d=require(process.env.NODE_PRE_GYP_ABI_CROSSWALK)}else{d=r(7316)}var f={};Object.keys(d).forEach((function(e){var t=e.split(".")[0];if(!f[t]){f[t]=e}}));function get_electron_abi(e,t){if(!e){throw new Error("get_electron_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if electron is the target.")}var r=o.parse(t);return e+"-v"+r.major+"."+r.minor}e.exports.get_electron_abi=get_electron_abi;function get_node_webkit_abi(e,t){if(!e){throw new Error("get_node_webkit_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if node-webkit is the target.")}return e+"-v"+t}e.exports.get_node_webkit_abi=get_node_webkit_abi;function get_node_abi(e,t){if(!e){throw new Error("get_node_abi requires valid runtime arg")}if(!t){throw new Error("get_node_abi requires valid process.versions object")}var r=o.parse(t.node);if(r.major===0&&r.minor%2){return e+"-v"+t.node}else{return t.modules?e+"-v"+ +t.modules:"v8-"+t.v8.split(".").slice(0,2).join(".")}}e.exports.get_node_abi=get_node_abi;function get_runtime_abi(e,t){if(!e){throw new Error("get_runtime_abi requires valid runtime arg")}if(e==="node-webkit"){return get_node_webkit_abi(e,t||process.versions["node-webkit"])}else if(e==="electron"){return get_electron_abi(e,t||process.versions.electron)}else{if(e!="node"){throw new Error("Unknown Runtime: '"+e+"'")}if(!t){return get_node_abi(e,process.versions)}else{var r;if(d[t]){r=d[t]}else{var a=t.split(".").map((function(e){return+e}));if(a.length!=3){throw new Error("Unknown target version: "+t)}var o=a[0];var s=a[1];var u=a[2];if(o===1){while(true){if(s>0)--s;if(u>0)--u;var c=""+o+"."+s+"."+u;if(d[c]){r=d[c];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+c+" as ABI compatible target");break}if(s===0&&u===0){break}}}else if(o>=2){if(f[o]){r=d[f[o]];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+f[o]+" as ABI compatible target")}}else if(o===0){if(a[1]%2===0){while(--u>0){var p=""+o+"."+s+"."+u;if(d[p]){r=d[p];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+p+" as ABI compatible target");break}}}}}if(!r){throw new Error("Unsupported target version: "+t)}var h={node:t,v8:r.v8+".0",modules:r.node_abi>1?r.node_abi:undefined};return get_node_abi(e,h)}}}e.exports.get_runtime_abi=get_runtime_abi;var p=["module_name","module_path","host"];function validate_config(e,t){var r=e.name+" package.json is not node-pre-gyp ready:\n";var a=[];if(!e.main){a.push("main")}if(!e.version){a.push("version")}if(!e.name){a.push("name")}if(!e.binary){a.push("binary")}var o=e.binary;p.forEach((function(e){if(a.indexOf("binary")>-1){a.pop("binary")}if(!o||o[e]===undefined||o[e]===""){a.push("binary."+e)}}));if(a.length>=1){throw new Error(r+"package.json must declare these properties: \n"+a.join("\n"))}if(o){var u=s.parse(o.host).protocol;if(u==="http:"){throw new Error("'host' protocol ("+u+") is invalid - only 'https:' is accepted")}}c.validate_package_json(e,t)}e.exports.validate_config=validate_config;function eval_template(e,t){Object.keys(t).forEach((function(r){var a="{"+r+"}";while(e.indexOf(a)>-1){e=e.replace(a,t[r])}}));return e}function fix_slashes(e){if(e.slice(-1)!="/"){return e+"/"}return e}function drop_double_slashes(e){return e.replace(/\/\//g,"/")}function get_process_runtime(e){var t="node";if(e["node-webkit"]){t="node-webkit"}else if(e.electron){t="electron"}return t}e.exports.get_process_runtime=get_process_runtime;var h="{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz";var v="";e.exports.evaluate=function(e,t,r){t=t||{};validate_config(e,t);var d=e.version;var f=o.parse(d);var p=t.runtime||get_process_runtime(process.versions);var _={name:e.name,configuration:Boolean(t.debug)?"Debug":"Release",debug:t.debug,module_name:e.binary.module_name,version:f.version,prerelease:f.prerelease.length?f.prerelease.join("."):"",build:f.build.length?f.build.join("."):"",major:f.major,minor:f.minor,patch:f.patch,runtime:p,node_abi:get_runtime_abi(p,t.target),node_abi_napi:c.get_napi_version(t.target)?"napi":get_runtime_abi(p,t.target),napi_version:c.get_napi_version(t.target),napi_build_version:r||"",node_napi_label:r?"napi-v"+r:get_runtime_abi(p,t.target),target:t.target||"",platform:t.target_platform||process.platform,target_platform:t.target_platform||process.platform,arch:t.target_arch||process.arch,target_arch:t.target_arch||process.arch,libc:t.target_libc||u.family||"unknown",module_main:e.main,toolset:t.toolset||""};var g=process.env["npm_config_"+_.module_name+"_binary_host_mirror"]||e.binary.host;_.host=fix_slashes(eval_template(g,_));_.module_path=eval_template(e.binary.module_path,_);if(t.module_root){_.module_path=a.join(t.module_root,_.module_path)}else{_.module_path=a.resolve(_.module_path)}_.module=a.join(_.module_path,_.module_name+".node");_.remote_path=e.binary.remote_path?drop_double_slashes(fix_slashes(eval_template(e.binary.remote_path,_))):v;var y=e.binary.package_name?e.binary.package_name:h;_.package_name=eval_template(y,_);_.staged_tarball=a.join("build/stage",_.remote_path,_.package_name);_.hosted_path=s.resolve(_.host,_.remote_path);_.hosted_tarball=s.resolve(_.hosted_path,_.package_name);return _}},3632:(e,t,r)=>{e.exports=rimraf;rimraf.sync=rimrafSync;var a=r(9491);var o=r(1017);var s=r(7147);var u=undefined;try{u=r(3535)}catch(e){}var c=parseInt("666",8);var d={nosort:true,silent:true};var f=0;var p=process.platform==="win32";function defaults(e){var t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach((function(t){e[t]=e[t]||s[t];t=t+"Sync";e[t]=e[t]||s[t]}));e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&u===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||d}function rimraf(e,t,r){if(typeof t==="function"){r=t;t={}}a(e,"rimraf: missing path");a.equal(typeof e,"string","rimraf: path should be a string");a.equal(typeof r,"function","rimraf: callback function required");a(t,"rimraf: invalid options argument provided");a.equal(typeof t,"object","rimraf: options should be object");defaults(t);var o=0;var s=null;var c=0;if(t.disableGlob||!u.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,(function(r,a){if(!r)return afterGlob(null,[e]);u(e,t.glob,afterGlob)}));function next(e){s=s||e;if(--c===0)r(s)}function afterGlob(e,a){if(e)return r(e);c=a.length;if(c===0)return r();a.forEach((function(e){rimraf_(e,t,(function CB(r){if(r){if((r.code==="EBUSY"||r.code==="ENOTEMPTY"||r.code==="EPERM")&&o{"use strict";var a=r(2717);var o=r(6054);var s=r(2361).EventEmitter;var u=t=e.exports=new s;var c=r(3837);var d=r(8834);var f=r(6322);d(true);var p=process.stderr;Object.defineProperty(u,"stream",{set:function(e){p=e;if(this.gauge)this.gauge.setWriteTo(p,p)},get:function(){return p}});var h;u.useColor=function(){return h!=null?h:p.isTTY};u.enableColor=function(){h=true;this.gauge.setTheme({hasColor:h,hasUnicode:v})};u.disableColor=function(){h=false;this.gauge.setTheme({hasColor:h,hasUnicode:v})};u.level="info";u.gauge=new o(p,{enabled:false,theme:{hasColor:u.useColor()},template:[{type:"progressbar",length:20},{type:"activityIndicator",kerning:1,length:1},{type:"section",default:""},":",{type:"logline",kerning:1,default:""}]});u.tracker=new a.TrackerGroup;u.progressEnabled=u.gauge.isEnabled();var v;u.enableUnicode=function(){v=true;this.gauge.setTheme({hasColor:this.useColor(),hasUnicode:v})};u.disableUnicode=function(){v=false;this.gauge.setTheme({hasColor:this.useColor(),hasUnicode:v})};u.setGaugeThemeset=function(e){this.gauge.setThemeset(e)};u.setGaugeTemplate=function(e){this.gauge.setTemplate(e)};u.enableProgress=function(){if(this.progressEnabled)return;this.progressEnabled=true;this.tracker.on("change",this.showProgress);if(this._pause)return;this.gauge.enable()};u.disableProgress=function(){if(!this.progressEnabled)return;this.progressEnabled=false;this.tracker.removeListener("change",this.showProgress);this.gauge.disable()};var _=["newGroup","newItem","newStream"];var mixinLog=function(e){Object.keys(u).forEach((function(t){if(t[0]==="_")return;if(_.filter((function(e){return e===t})).length)return;if(e[t])return;if(typeof u[t]!=="function")return;var r=u[t];e[t]=function(){return r.apply(u,arguments)}}));if(e instanceof a.TrackerGroup){_.forEach((function(t){var r=e[t];e[t]=function(){return mixinLog(r.apply(e,arguments))}}))}return e};_.forEach((function(e){u[e]=function(){return mixinLog(this.tracker[e].apply(this.tracker,arguments))}}));u.clearProgress=function(e){if(!this.progressEnabled)return e&&process.nextTick(e);this.gauge.hide(e)};u.showProgress=function(e,t){if(!this.progressEnabled)return;var r={};if(e)r.section=e;var a=u.record[u.record.length-1];if(a){r.subsection=a.prefix;var o=u.disp[a.level]||a.level;var s=this._format(o,u.style[a.level]);if(a.prefix)s+=" "+this._format(a.prefix,this.prefixStyle);s+=" "+a.message.split(/\r?\n/)[0];r.logline=s}r.completed=t||this.tracker.completed();this.gauge.show(r)}.bind(u);u.pause=function(){this._paused=true;if(this.progressEnabled)this.gauge.disable()};u.resume=function(){if(!this._paused)return;this._paused=false;var e=this._buffer;this._buffer=[];e.forEach((function(e){this.emitLog(e)}),this);if(this.progressEnabled)this.gauge.enable()};u._buffer=[];var g=0;u.record=[];u.maxRecordSize=1e4;u.log=function(e,t,r){var a=this.levels[e];if(a===undefined){return this.emit("error",new Error(c.format("Undefined log level: %j",e)))}var o=new Array(arguments.length-2);var s=null;for(var u=2;up/10){var v=Math.floor(p*.9);this.record=this.record.slice(-1*v)}this.emitLog(f)}.bind(u);u.emitLog=function(e){if(this._paused){this._buffer.push(e);return}if(this.progressEnabled)this.gauge.pulse(e.prefix);var t=this.levels[e.level];if(t===undefined)return;if(t0&&!isFinite(t))return;var r=u.disp[e.level]!=null?u.disp[e.level]:e.level;this.clearProgress();e.message.split(/\r?\n/).forEach((function(t){if(this.heading){this.write(this.heading,this.headingStyle);this.write(" ")}this.write(r,u.style[e.level]);var a=e.prefix||"";if(a)this.write(" ");this.write(a,this.prefixStyle);this.write(" "+t+"\n")}),this);this.showProgress()};u._format=function(e,t){if(!p)return;var r="";if(this.useColor()){t=t||{};var a=[];if(t.fg)a.push(t.fg);if(t.bg)a.push("bg"+t.bg[0].toUpperCase()+t.bg.slice(1));if(t.bold)a.push("bold");if(t.underline)a.push("underline");if(t.inverse)a.push("inverse");if(a.length)r+=f.color(a);if(t.beep)r+=f.beep()}r+=e;if(this.useColor()){r+=f.color("reset")}return r};u.write=function(e,t){if(!p)return;p.write(this._format(e,t))};u.addLevel=function(e,t,r,a){if(a==null)a=e;this.levels[e]=t;this.style[e]=r;if(!this[e]){this[e]=function(){var t=new Array(arguments.length+1);t[0]=e;for(var r=0;r{"use strict";e.exports=Number.isNaN||function(e){return e!==e}},1800:e=>{"use strict"; +(()=>{var __webpack_modules__={111:(e,t,r)=>{"use strict";e.exports=t;t.mockS3Http=r(7048).get_mockS3Http();t.mockS3Http("on");const s=t.mockS3Http("get");const a=r(7147);const o=r(1017);const u=r(1400);const c=r(9658);c.disableProgress();const f=r(5677);const p=r(2361).EventEmitter;const d=r(3837).inherits;const h=["clean","install","reinstall","build","rebuild","package","testpackage","publish","unpublish","info","testbinary","reveal","configure"];const v={};c.heading="node-pre-gyp";if(s){c.warn(`mocking s3 to ${process.env.node_pre_gyp_mock_s3}`)}Object.defineProperty(t,"find",{get:function(){return r(3093).find},enumerable:true});function Run({package_json_path:e="./package.json",argv:t}){this.package_json_path=e;this.commands={};const r=this;h.forEach((e=>{r.commands[e]=function(t,s){c.verbose("command",e,t);return require("./"+e)(r,t,s)}}));this.parseArgv(t);this.binaryHostSet=false}d(Run,p);t.Run=Run;const g=Run.prototype;g.package=r(9286);g.configDefs={help:Boolean,arch:String,debug:Boolean,directory:String,proxy:String,loglevel:String};g.shorthands={release:"--no-debug",C:"--directory",debug:"--debug",j:"--jobs",silent:"--loglevel=silent",silly:"--loglevel=silly",verbose:"--loglevel=verbose"};g.aliases=v;g.parseArgv=function parseOpts(e){this.opts=u(this.configDefs,this.shorthands,e);this.argv=this.opts.argv.remain.slice();const t=this.todo=[];e=this.argv.map((e=>{if(e in this.aliases){e=this.aliases[e]}return e}));e.slice().forEach((r=>{if(r in this.commands){const s=e.splice(0,e.indexOf(r));e.shift();if(t.length>0){t[t.length-1].args=s}t.push({name:r,args:[]})}}));if(t.length>0){t[t.length-1].args=e.splice(0)}let r=this.package_json_path;if(this.opts.directory){r=o.join(this.opts.directory,r)}this.package_json=JSON.parse(a.readFileSync(r));this.todo=f.expand_commands(this.package_json,this.opts,t);const s="npm_config_";Object.keys(process.env).forEach((e=>{if(e.indexOf(s)!==0)return;const t=process.env[e];if(e===s+"loglevel"){c.level=t}else{e=e.substring(s.length);if(e==="argv"){if(this.opts.argv&&this.opts.argv.remain&&this.opts.argv.remain.length){}else{this.opts[e]=t}}else{this.opts[e]=t}}}));if(this.opts.loglevel){c.level=this.opts.loglevel}c.resume()};g.setBinaryHostProperty=function(e){if(this.binaryHostSet){return this.package_json.binary.host}const t=this.package_json;if(!t||!t.binary||t.binary.host){return""}if(!t.binary.staging_host||!t.binary.production_host){return""}let r="production_host";if(e==="publish"){r="staging_host"}const s=process.env.node_pre_gyp_s3_host;if(s==="staging"||s==="production"){r=`${s}_host`}else if(this.opts["s3_host"]==="staging"||this.opts["s3_host"]==="production"){r=`${this.opts["s3_host"]}_host`}else if(this.opts["s3_host"]||s){throw new Error(`invalid s3_host ${this.opts["s3_host"]||s}`)}t.binary.host=t.binary[r];this.binaryHostSet=true;return t.binary.host};g.usage=function usage(){const e=[""," Usage: node-pre-gyp [options]",""," where is one of:",h.map((e=>" - "+e+" - "+require("./"+e).usage)).join("\n"),"","node-pre-gyp@"+this.version+" "+o.resolve(__dirname,".."),"node@"+process.versions.node].join("\n");return e};Object.defineProperty(g,"version",{get:function(){return this.package.version},enumerable:true})},3093:(e,t,r)=>{"use strict";const s=r(111);const a=r(302);const o=r(5677);const u=r(7147).existsSync||r(1017).existsSync;const c=r(1017);e.exports=t;t.usage="Finds the require path for the node-pre-gyp installed module";t.validate=function(e,t){a.validate_config(e,t)};t.find=function(e,t){if(!u(e)){throw new Error(e+"does not exist")}const r=new s.Run({package_json_path:e,argv:process.argv});r.setBinaryHostProperty();const f=r.package_json;a.validate_config(f,t);let p;if(o.get_napi_build_versions(f,t)){p=o.get_best_napi_build_version(f,t)}t=t||{};if(!t.module_root)t.module_root=c.dirname(e);const d=a.evaluate(f,t,p);return d.module}},5677:(e,t,r)=>{"use strict";const s=r(7147);e.exports=t;const a=process.version.substr(1).replace(/-.*$/,"").split(".").map((e=>+e));const o=["build","clean","configure","package","publish","reveal","testbinary","testpackage","unpublish"];const u="napi_build_version=";e.exports.get_napi_version=function(){let e=process.versions.napi;if(!e){if(a[0]===9&&a[1]>=3)e=2;else if(a[0]===8)e=1}return e};e.exports.get_napi_version_as_string=function(t){const r=e.exports.get_napi_version(t);return r?""+r:""};e.exports.validate_package_json=function(t,r){const s=t.binary;const a=pathOK(s.module_path);const o=pathOK(s.remote_path);const u=pathOK(s.package_name);const c=e.exports.get_napi_build_versions(t,r,true);const f=e.exports.get_napi_build_versions_raw(t);if(c){c.forEach((e=>{if(!(parseInt(e,10)===e&&e>0)){throw new Error("All values specified in napi_versions must be positive integers.")}}))}if(c&&(!a||!o&&!u)){throw new Error("When napi_versions is specified; module_path and either remote_path or "+"package_name must contain the substitution string '{napi_build_version}`.")}if((a||o||u)&&!f){throw new Error("When the substitution string '{napi_build_version}` is specified in "+"module_path, remote_path, or package_name; napi_versions must also be specified.")}if(c&&!e.exports.get_best_napi_build_version(t,r)&&e.exports.build_napi_only(t)){throw new Error("The Node-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports Node-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}if(f&&!c&&e.exports.build_napi_only(t)){throw new Error("The Node-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports Node-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}};function pathOK(e){return e&&(e.indexOf("{napi_build_version}")!==-1||e.indexOf("{node_napi_label}")!==-1)}e.exports.expand_commands=function(t,r,s){const a=[];const c=e.exports.get_napi_build_versions(t,r);s.forEach((s=>{if(c&&s.name==="install"){const o=e.exports.get_best_napi_build_version(t,r);const c=o?[u+o]:[];a.push({name:s.name,args:c})}else if(c&&o.indexOf(s.name)!==-1){c.forEach((e=>{const t=s.args.slice();t.push(u+e);a.push({name:s.name,args:t})}))}else{a.push(s)}}));return a};e.exports.get_napi_build_versions=function(t,s,a){const o=r(9658);let u=[];const c=e.exports.get_napi_version(s?s.target:undefined);if(t.binary&&t.binary.napi_versions){t.binary.napi_versions.forEach((e=>{const t=u.indexOf(e)!==-1;if(!t&&c&&e<=c){u.push(e)}else if(a&&!t&&c){o.info("This Node instance does not support builds for Node-API version",e)}}))}if(s&&s["build-latest-napi-version-only"]){let e=0;u.forEach((t=>{if(t>e)e=t}));u=e?[e]:[]}return u.length?u:undefined};e.exports.get_napi_build_versions_raw=function(e){const t=[];if(e.binary&&e.binary.napi_versions){e.binary.napi_versions.forEach((e=>{if(t.indexOf(e)===-1){t.push(e)}}))}return t.length?t:undefined};e.exports.get_command_arg=function(e){return u+e};e.exports.get_napi_build_version_from_command_args=function(e){for(let t=0;t{if(e>s&&e<=t){s=e}}))}return s===0?undefined:s};e.exports.build_napi_only=function(e){return e.binary&&e.binary.package_name&&e.binary.package_name.indexOf("{node_napi_label}")===-1}},7048:(e,t,r)=>{"use strict";e.exports=t;const s=r(7310);const a=r(7147);const o=r(1017);e.exports.detect=function(e,t){const r=e.hosted_path;const a=s.parse(r);t.prefix=!a.pathname||a.pathname==="/"?"":a.pathname.replace("/","");if(e.bucket&&e.region){t.bucket=e.bucket;t.region=e.region;t.endpoint=e.host;t.s3ForcePathStyle=e.s3ForcePathStyle}else{const e=a.hostname.split(".s3");const r=e[0];if(!r){return}if(!t.bucket){t.bucket=r}if(!t.region){const r=e[1].slice(1).split(".")[0];if(r==="amazonaws"){t.region="us-east-1"}else{t.region=r}}}};e.exports.get_s3=function(e){if(process.env.node_pre_gyp_mock_s3){const e=r(2722);const t=r(2037);e.config.basePath=`${t.tmpdir()}/mock`;const s=e.S3();const wcb=e=>(t,...r)=>{if(t&&t.code==="ENOENT"){t.code="NotFound"}return e(t,...r)};return{listObjects(e,t){return s.listObjects(e,wcb(t))},headObject(e,t){return s.headObject(e,wcb(t))},deleteObject(e,t){return s.deleteObject(e,wcb(t))},putObject(e,t){return s.putObject(e,wcb(t))}}}const t=r(918);t.config.update(e);const s=new t.S3;return{listObjects(e,t){return s.listObjects(e,t)},headObject(e,t){return s.headObject(e,t)},deleteObject(e,t){return s.deleteObject(e,t)},putObject(e,t){return s.putObject(e,t)}}};e.exports.get_mockS3Http=function(){let e=false;if(!process.env.node_pre_gyp_mock_s3){return()=>e}const t=r(3902);const s="https://mapbox-node-pre-gyp-public-testing-bucket.s3.us-east-1.amazonaws.com";const u=process.env.node_pre_gyp_mock_s3+"/mapbox-node-pre-gyp-public-testing-bucket";const mock_http=()=>{function get(e,t){const r=o.join(u,e.replace("%2B","+"));try{a.accessSync(r,a.constants.R_OK)}catch(e){return[404,"not found\n"]}return[200,a.createReadStream(r)]}return t(s).persist().get((()=>e)).reply(get)};mock_http(t,s,u);const mockS3Http=t=>{const r=e;if(t==="off"){e=false}else if(t==="on"){e=true}else if(t!=="get"){throw new Error(`illegal action for setMockHttp ${t}`)}return r};return mockS3Http}},302:(e,t,r)=>{"use strict";e.exports=t;const s=r(1017);const a=r(7849);const o=r(7310);const u=r(2157);const c=r(5677);let f;if(process.env.NODE_PRE_GYP_ABI_CROSSWALK){f=require(process.env.NODE_PRE_GYP_ABI_CROSSWALK)}else{f=r(2339)}const p={};Object.keys(f).forEach((e=>{const t=e.split(".")[0];if(!p[t]){p[t]=e}}));function get_electron_abi(e,t){if(!e){throw new Error("get_electron_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if electron is the target.")}const r=a.parse(t);return e+"-v"+r.major+"."+r.minor}e.exports.get_electron_abi=get_electron_abi;function get_node_webkit_abi(e,t){if(!e){throw new Error("get_node_webkit_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if node-webkit is the target.")}return e+"-v"+t}e.exports.get_node_webkit_abi=get_node_webkit_abi;function get_node_abi(e,t){if(!e){throw new Error("get_node_abi requires valid runtime arg")}if(!t){throw new Error("get_node_abi requires valid process.versions object")}const r=a.parse(t.node);if(r.major===0&&r.minor%2){return e+"-v"+t.node}else{return t.modules?e+"-v"+ +t.modules:"v8-"+t.v8.split(".").slice(0,2).join(".")}}e.exports.get_node_abi=get_node_abi;function get_runtime_abi(e,t){if(!e){throw new Error("get_runtime_abi requires valid runtime arg")}if(e==="node-webkit"){return get_node_webkit_abi(e,t||process.versions["node-webkit"])}else if(e==="electron"){return get_electron_abi(e,t||process.versions.electron)}else{if(e!=="node"){throw new Error("Unknown Runtime: '"+e+"'")}if(!t){return get_node_abi(e,process.versions)}else{let r;if(f[t]){r=f[t]}else{const e=t.split(".").map((e=>+e));if(e.length!==3){throw new Error("Unknown target version: "+t)}const s=e[0];let a=e[1];let o=e[2];if(s===1){while(true){if(a>0)--a;if(o>0)--o;const e=""+s+"."+a+"."+o;if(f[e]){r=f[e];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+e+" as ABI compatible target");break}if(a===0&&o===0){break}}}else if(s>=2){if(p[s]){r=f[p[s]];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+p[s]+" as ABI compatible target")}}else if(s===0){if(e[1]%2===0){while(--o>0){const e=""+s+"."+a+"."+o;if(f[e]){r=f[e];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+e+" as ABI compatible target");break}}}}}if(!r){throw new Error("Unsupported target version: "+t)}const s={node:t,v8:r.v8+".0",modules:r.node_abi>1?r.node_abi:undefined};return get_node_abi(e,s)}}}e.exports.get_runtime_abi=get_runtime_abi;const d=["module_name","module_path","host"];function validate_config(e,t){const r=e.name+" package.json is not node-pre-gyp ready:\n";const s=[];if(!e.main){s.push("main")}if(!e.version){s.push("version")}if(!e.name){s.push("name")}if(!e.binary){s.push("binary")}const a=e.binary;if(a){d.forEach((e=>{if(!a[e]||typeof a[e]!=="string"){s.push("binary."+e)}}))}if(s.length>=1){throw new Error(r+"package.json must declare these properties: \n"+s.join("\n"))}if(a){const e=o.parse(a.host).protocol;if(e==="http:"){throw new Error("'host' protocol ("+e+") is invalid - only 'https:' is accepted")}}c.validate_package_json(e,t)}e.exports.validate_config=validate_config;function eval_template(e,t){Object.keys(t).forEach((r=>{const s="{"+r+"}";while(e.indexOf(s)>-1){e=e.replace(s,t[r])}}));return e}function fix_slashes(e){if(e.slice(-1)!=="/"){return e+"/"}return e}function drop_double_slashes(e){return e.replace(/\/\//g,"/")}function get_process_runtime(e){let t="node";if(e["node-webkit"]){t="node-webkit"}else if(e.electron){t="electron"}return t}e.exports.get_process_runtime=get_process_runtime;const h="{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz";const v="";e.exports.evaluate=function(e,t,r){t=t||{};validate_config(e,t);const f=e.version;const p=a.parse(f);const d=t.runtime||get_process_runtime(process.versions);const g={name:e.name,configuration:t.debug?"Debug":"Release",debug:t.debug,module_name:e.binary.module_name,version:p.version,prerelease:p.prerelease.length?p.prerelease.join("."):"",build:p.build.length?p.build.join("."):"",major:p.major,minor:p.minor,patch:p.patch,runtime:d,node_abi:get_runtime_abi(d,t.target),node_abi_napi:c.get_napi_version(t.target)?"napi":get_runtime_abi(d,t.target),napi_version:c.get_napi_version(t.target),napi_build_version:r||"",node_napi_label:r?"napi-v"+r:get_runtime_abi(d,t.target),target:t.target||"",platform:t.target_platform||process.platform,target_platform:t.target_platform||process.platform,arch:t.target_arch||process.arch,target_arch:t.target_arch||process.arch,libc:t.target_libc||u.family||"unknown",module_main:e.main,toolset:t.toolset||"",bucket:e.binary.bucket,region:e.binary.region,s3ForcePathStyle:e.binary.s3ForcePathStyle||false};const m=g.module_name.replace("-","_");const _=process.env["npm_config_"+m+"_binary_host_mirror"]||e.binary.host;g.host=fix_slashes(eval_template(_,g));g.module_path=eval_template(e.binary.module_path,g);if(t.module_root){g.module_path=s.join(t.module_root,g.module_path)}else{g.module_path=s.resolve(g.module_path)}g.module=s.join(g.module_path,g.module_name+".node");g.remote_path=e.binary.remote_path?drop_double_slashes(fix_slashes(eval_template(e.binary.remote_path,g))):v;const y=e.binary.package_name?e.binary.package_name:h;g.package_name=eval_template(y,g);g.staged_tarball=s.join("build/stage",g.remote_path,g.package_name);g.hosted_path=o.resolve(g.host,g.remote_path);g.hosted_tarball=o.resolve(g.hosted_path,g.package_name);return g}},1400:(e,t,r)=>{var s=process.env.DEBUG_NOPT||process.env.NOPT_DEBUG?function(){console.error.apply(console,arguments)}:function(){};var a=r(7310),o=r(1017),u=r(2781).Stream,c=r(5920),f=r(2037);e.exports=t=nopt;t.clean=clean;t.typeDefs={String:{type:String,validate:validateString},Boolean:{type:Boolean,validate:validateBoolean},url:{type:a,validate:validateUrl},Number:{type:Number,validate:validateNumber},path:{type:o,validate:validatePath},Stream:{type:u,validate:validateStream},Date:{type:Date,validate:validateDate}};function nopt(e,r,a,o){a=a||process.argv;e=e||{};r=r||{};if(typeof o!=="number")o=2;s(e,r,a,o);a=a.slice(o);var u={},c,f={remain:[],cooked:a,original:a.slice(0)};parse(a,u,f.remain,e,r);clean(u,e,t.typeDefs);u.argv=f;Object.defineProperty(u.argv,"toString",{value:function(){return this.original.map(JSON.stringify).join(" ")},enumerable:false});return u}function clean(e,r,a){a=a||t.typeDefs;var o={},u=[false,true,null,String,Array];Object.keys(e).forEach((function(c){if(c==="argv")return;var f=e[c],p=Array.isArray(f),d=r[c];if(!p)f=[f];if(!d)d=u;if(d===Array)d=u.concat(Array);if(!Array.isArray(d))d=[d];s("val=%j",f);s("types=",d);f=f.map((function(u){if(typeof u==="string"){s("string %j",u);u=u.trim();if(u==="null"&&~d.indexOf(null)||u==="true"&&(~d.indexOf(true)||~d.indexOf(Boolean))||u==="false"&&(~d.indexOf(false)||~d.indexOf(Boolean))){u=JSON.parse(u);s("jsonable %j",u)}else if(~d.indexOf(Number)&&!isNaN(u)){s("convert to number",u);u=+u}else if(~d.indexOf(Date)&&!isNaN(Date.parse(u))){s("convert to date",u);u=new Date(u)}}if(!r.hasOwnProperty(c)){return u}if(u===false&&~d.indexOf(null)&&!(~d.indexOf(false)||~d.indexOf(Boolean))){u=null}var f={};f[c]=u;s("prevalidated val",f,u,r[c]);if(!validate(f,c,u,r[c],a)){if(t.invalidHandler){t.invalidHandler(c,u,r[c],e)}else if(t.invalidHandler!==false){s("invalid: "+c+"="+u,r[c])}return o}s("validated val",f,u,r[c]);return f[c]})).filter((function(e){return e!==o}));if(!f.length&&d.indexOf(Array)===-1){s("VAL HAS NO LENGTH, DELETE IT",f,c,d.indexOf(Array));delete e[c]}else if(p){s(p,e[c],f);e[c]=f}else e[c]=f[0];s("k=%s val=%j",c,f,e[c])}))}function validateString(e,t,r){e[t]=String(r)}function validatePath(e,t,r){if(r===true)return false;if(r===null)return true;r=String(r);var s=process.platform==="win32",a=s?/^~(\/|\\)/:/^~\//,u=f.homedir();if(u&&r.match(a)){e[t]=o.resolve(u,r.substr(2))}else{e[t]=o.resolve(r)}return true}function validateNumber(e,t,r){s("validate Number %j %j %j",t,r,isNaN(r));if(isNaN(r))return false;e[t]=+r}function validateDate(e,t,r){var a=Date.parse(r);s("validate Date %j %j %j",t,r,a);if(isNaN(a))return false;e[t]=new Date(r)}function validateBoolean(e,t,r){if(r instanceof Boolean)r=r.valueOf();else if(typeof r==="string"){if(!isNaN(r))r=!!+r;else if(r==="null"||r==="false")r=false;else r=true}else r=!!r;e[t]=r}function validateUrl(e,t,r){r=a.parse(String(r));if(!r.host)return false;e[t]=r.href}function validateStream(e,t,r){if(!(r instanceof u))return false;e[t]=r}function validate(e,t,r,a,o){if(Array.isArray(a)){for(var u=0,c=a.length;u1){var g=h.indexOf("=");if(g>-1){v=true;var m=h.substr(g+1);h=h.substr(0,g);e.splice(d,1,h,m)}var _=resolveShort(h,o,p,f);s("arg=%j shRes=%j",h,_);if(_){s(h,_);e.splice.apply(e,[d,1].concat(_));if(h!==_[0]){d--;continue}}h=h.replace(/^-+/,"");var y=null;while(h.toLowerCase().indexOf("no-")===0){y=!y;h=h.substr(3)}if(f[h])h=f[h];var x=a[h];var w=Array.isArray(x);if(w&&x.length===1){w=false;x=x[0]}var E=x===Array||w&&x.indexOf(Array)!==-1;if(!a.hasOwnProperty(h)&&t.hasOwnProperty(h)){if(!Array.isArray(t[h]))t[h]=[t[h]];E=true}var S,k=e[d+1];var A=typeof y==="boolean"||x===Boolean||w&&x.indexOf(Boolean)!==-1||typeof x==="undefined"&&!v||k==="false"&&(x===null||w&&~x.indexOf(null));if(A){S=!y;if(k==="true"||k==="false"){S=JSON.parse(k);k=null;if(y)S=!S;d++}if(w&&k){if(~x.indexOf(k)){S=k;d++}else if(k==="null"&&~x.indexOf(null)){S=null;d++}else if(!k.match(/^-{2,}[^-]/)&&!isNaN(k)&&~x.indexOf(Number)){S=+k;d++}else if(!k.match(/^-[^-]/)&&~x.indexOf(String)){S=k;d++}}if(E)(t[h]=t[h]||[]).push(S);else t[h]=S;continue}if(x===String){if(k===undefined){k=""}else if(k.match(/^-{1,2}[^-]+/)){k="";d--}}if(k&&k.match(/^-{2,}$/)){k=undefined;d--}S=k===undefined?true:k;if(E)(t[h]=t[h]||[]).push(S);else t[h]=S;d++;continue}r.push(h)}}function resolveShort(e,t,r,a){e=e.replace(/^-+/,"");if(a[e]===e)return null;if(t[e]){if(t[e]&&!Array.isArray(t[e]))t[e]=t[e].split(/\s+/);return t[e]}var o=t.___singles;if(!o){o=Object.keys(t).filter((function(e){return e.length===1})).reduce((function(e,t){e[t]=true;return e}),{});t.___singles=o;s("shorthand singles",o)}var u=e.split("").filter((function(e){return o[e]}));if(u.join("")===e)return u.map((function(e){return t[e]})).reduce((function(e,t){return e.concat(t)}),[]);if(a[e]&&!t[e])return null;if(r[e])e=r[e];if(t[e]&&!Array.isArray(t[e]))t[e]=t[e].split(/\s+/);return t[e]}},6286:(e,t,r)=>{const s=r(9491);const a=r(1017);const o=r(7147);let u=undefined;try{u=r(3535)}catch(e){}const c={nosort:true,silent:true};let f=0;const p=process.platform==="win32";const defaults=e=>{const t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach((t=>{e[t]=e[t]||o[t];t=t+"Sync";e[t]=e[t]||o[t]}));e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&u===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||c};const rimraf=(e,t,r)=>{if(typeof t==="function"){r=t;t={}}s(e,"rimraf: missing path");s.equal(typeof e,"string","rimraf: path should be a string");s.equal(typeof r,"function","rimraf: callback function required");s(t,"rimraf: invalid options argument provided");s.equal(typeof t,"object","rimraf: options should be object");defaults(t);let a=0;let o=null;let c=0;const next=e=>{o=o||e;if(--c===0)r(o)};const afterGlob=(e,s)=>{if(e)return r(e);c=s.length;if(c===0)return r();s.forEach((e=>{const CB=r=>{if(r){if((r.code==="EBUSY"||r.code==="ENOTEMPTY"||r.code==="EPERM")&&arimraf_(e,t,CB)),a*100)}if(r.code==="EMFILE"&&frimraf_(e,t,CB)),f++)}if(r.code==="ENOENT")r=null}f=0;next(r)};rimraf_(e,t,CB)}))};if(t.disableGlob||!u.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,((r,s)=>{if(!r)return afterGlob(null,[e]);u(e,t.glob,afterGlob)}))};const rimraf_=(e,t,r)=>{s(e);s(t);s(typeof r==="function");t.lstat(e,((s,a)=>{if(s&&s.code==="ENOENT")return r(null);if(s&&s.code==="EPERM"&&p)fixWinEPERM(e,t,s,r);if(a&&a.isDirectory())return rmdir(e,t,s,r);t.unlink(e,(s=>{if(s){if(s.code==="ENOENT")return r(null);if(s.code==="EPERM")return p?fixWinEPERM(e,t,s,r):rmdir(e,t,s,r);if(s.code==="EISDIR")return rmdir(e,t,s,r)}return r(s)}))}))};const fixWinEPERM=(e,t,r,a)=>{s(e);s(t);s(typeof a==="function");t.chmod(e,438,(s=>{if(s)a(s.code==="ENOENT"?null:r);else t.stat(e,((s,o)=>{if(s)a(s.code==="ENOENT"?null:r);else if(o.isDirectory())rmdir(e,t,r,a);else t.unlink(e,a)}))}))};const fixWinEPERMSync=(e,t,r)=>{s(e);s(t);try{t.chmodSync(e,438)}catch(e){if(e.code==="ENOENT")return;else throw r}let a;try{a=t.statSync(e)}catch(e){if(e.code==="ENOENT")return;else throw r}if(a.isDirectory())rmdirSync(e,t,r);else t.unlinkSync(e)};const rmdir=(e,t,r,a)=>{s(e);s(t);s(typeof a==="function");t.rmdir(e,(s=>{if(s&&(s.code==="ENOTEMPTY"||s.code==="EEXIST"||s.code==="EPERM"))rmkids(e,t,a);else if(s&&s.code==="ENOTDIR")a(r);else a(s)}))};const rmkids=(e,t,r)=>{s(e);s(t);s(typeof r==="function");t.readdir(e,((s,o)=>{if(s)return r(s);let u=o.length;if(u===0)return t.rmdir(e,r);let c;o.forEach((s=>{rimraf(a.join(e,s),t,(s=>{if(c)return;if(s)return r(c=s);if(--u===0)t.rmdir(e,r)}))}))}))};const rimrafSync=(e,t)=>{t=t||{};defaults(t);s(e,"rimraf: missing path");s.equal(typeof e,"string","rimraf: path should be a string");s(t,"rimraf: missing options");s.equal(typeof t,"object","rimraf: options should be object");let r;if(t.disableGlob||!u.hasMagic(e)){r=[e]}else{try{t.lstatSync(e);r=[e]}catch(s){r=u.sync(e,t.glob)}}if(!r.length)return;for(let e=0;e{s(e);s(t);try{t.rmdirSync(e)}catch(s){if(s.code==="ENOENT")return;if(s.code==="ENOTDIR")throw r;if(s.code==="ENOTEMPTY"||s.code==="EEXIST"||s.code==="EPERM")rmkidsSync(e,t)}};const rmkidsSync=(e,t)=>{s(e);s(t);t.readdirSync(e).forEach((r=>rimrafSync(a.join(e,r),t)));const r=p?100:1;let o=0;do{let s=true;try{const a=t.rmdirSync(e,t);s=false;return a}finally{if(++oe){return false}r+=t[s+1];if(r>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&c.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,p)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&f.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,p)||isInAstralSet(e,d)}var h=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new h(e,{beforeExpr:true,binop:t})}var v={beforeExpr:true},g={startsExpr:true};var m={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return m[e]=new h(e,t)}var _={num:new h("num",g),regexp:new h("regexp",g),string:new h("string",g),name:new h("name",g),privateId:new h("privateId",g),eof:new h("eof"),bracketL:new h("[",{beforeExpr:true,startsExpr:true}),bracketR:new h("]"),braceL:new h("{",{beforeExpr:true,startsExpr:true}),braceR:new h("}"),parenL:new h("(",{beforeExpr:true,startsExpr:true}),parenR:new h(")"),comma:new h(",",v),semi:new h(";",v),colon:new h(":",v),dot:new h("."),question:new h("?",v),questionDot:new h("?."),arrow:new h("=>",v),template:new h("template"),invalidTemplate:new h("invalidTemplate"),ellipsis:new h("...",v),backQuote:new h("`",g),dollarBraceL:new h("${",{beforeExpr:true,startsExpr:true}),eq:new h("=",{beforeExpr:true,isAssign:true}),assign:new h("_=",{beforeExpr:true,isAssign:true}),incDec:new h("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new h("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new h("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new h("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",v),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",v),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",v),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",g),_if:kw("if"),_return:kw("return",v),_switch:kw("switch"),_throw:kw("throw",v),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",g),_super:kw("super",g),_class:kw("class",g),_extends:kw("extends",v),_export:kw("export"),_import:kw("import",g),_null:kw("null",g),_true:kw("true",g),_false:kw("false",g),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var y=/\r\n?|\n|\u2028|\u2029/;var x=new RegExp(y.source,"g");function isNewLine(e){return e===10||e===13||e===8232||e===8233}var w=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var E=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var S=Object.prototype;var k=S.hasOwnProperty;var A=S.toString;function has(e,t){return k.call(e,t)}var C=Array.isArray||function(e){return A.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var R=function Position(e,t){this.line=e;this.column=t};R.prototype.offset=function offset(e){return new R(this.line,this.column+e)};var T=function SourceLocation(e,t,r){this.start=t;this.end=r;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var r=1,s=0;;){x.lastIndex=s;var a=x.exec(e);if(a&&a.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(C(t.onToken)){var s=t.onToken;t.onToken=function(e){return s.push(e)}}if(C(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(r,s,a,o,u,c){var f={type:r?"Block":"Line",value:s,start:a,end:o};if(e.locations){f.loc=new T(this,u,c)}if(e.ranges){f.range=[a,o]}t.push(f)}}var N=1,P=2,L=4,j=8,D=16,M=32,F=64,B=128,W=256,U=N|P|W;function functionFlags(e,t){return P|(e?L:0)|(t?j:0)}var V=0,q=1,H=2,$=3,G=4,K=5;var z=function Parser(e,r,a){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(s[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var o="";if(e.allowReserved!==true){o=t[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3];if(e.sourceType==="module"){o+=" await"}}this.reservedWords=wordsRegexp(o);var u=(o?o+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(u);this.reservedWordsStrictBind=wordsRegexp(u+" "+t.strictBind);this.input=String(r);this.containsEsc=false;if(a){this.pos=a;this.lineStart=this.input.lastIndexOf("\n",a-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(y).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=_.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.potentialArrowInForAwait=false;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports=Object.create(null);if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(N);this.regexpState=null;this.privateNameStack=[]};var Q={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},canAwait:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true},allowNewDotTarget:{configurable:true},inClassStaticBlock:{configurable:true}};z.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};Q.inFunction.get=function(){return(this.currentVarScope().flags&P)>0};Q.inGenerator.get=function(){return(this.currentVarScope().flags&j)>0&&!this.currentVarScope().inClassFieldInit};Q.inAsync.get=function(){return(this.currentVarScope().flags&L)>0&&!this.currentVarScope().inClassFieldInit};Q.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&W){return false}if(t.flags&P){return(t.flags&L)>0}}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};Q.allowSuper.get=function(){var e=this.currentThisScope();var t=e.flags;var r=e.inClassFieldInit;return(t&F)>0||r||this.options.allowSuperOutsideMethod};Q.allowDirectSuper.get=function(){return(this.currentThisScope().flags&B)>0};Q.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};Q.allowNewDotTarget.get=function(){var e=this.currentThisScope();var t=e.flags;var r=e.inClassFieldInit;return(t&(P|W))>0||r};Q.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&W)>0};z.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var r=this;for(var s=0;s=,?^&]/.test(a)||a==="!"&&this.input.charAt(s+1)==="=")}e+=t[0].length;E.lastIndex=e;e+=E.exec(this.input)[0].length;if(this.input[e]===";"){e++}}};Y.eat=function(e){if(this.type===e){this.next();return true}else{return false}};Y.isContextual=function(e){return this.type===_.name&&this.value===e&&!this.containsEsc};Y.eatContextual=function(e){if(!this.isContextual(e)){return false}this.next();return true};Y.expectContextual=function(e){if(!this.eatContextual(e)){this.unexpected()}};Y.canInsertSemicolon=function(){return this.type===_.eof||this.type===_.braceR||y.test(this.input.slice(this.lastTokEnd,this.start))};Y.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};Y.semicolon=function(){if(!this.eat(_.semi)&&!this.insertSemicolon()){this.unexpected()}};Y.afterTrailingComma=function(e,t){if(this.type===e){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!t){this.next()}return true}};Y.expect=function(e){this.eat(e)||this.unexpected()};Y.unexpected=function(e){this.raise(e!=null?e:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}Y.checkPatternErrors=function(e,t){if(!e){return}if(e.trailingComma>-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var r=t?e.parenthesizedAssign:e.parenthesizedBind;if(r>-1){this.raiseRecoverable(r,"Parenthesized pattern")}};Y.checkExpressionErrors=function(e,t){if(!e){return false}var r=e.shorthandAssign;var s=e.doubleProto;if(!t){return r>=0||s>=0}if(r>=0){this.raise(r,"Shorthand property assignments are valid only in destructuring patterns")}if(s>=0){this.raiseRecoverable(s,"Redefinition of __proto__ property")}};Y.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&s<56320){return true}if(e){return false}if(s===123){return true}if(isIdentifierStart(s,true)){var o=r+1;while(isIdentifierChar(s=this.input.charCodeAt(o),true)){++o}if(s===92||s>55295&&s<56320){return true}var u=this.input.slice(r,o);if(!a.test(u)){return true}}return false};Z.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async")){return false}E.lastIndex=this.pos;var e=E.exec(this.input);var t=this.pos+e[0].length,r;return!y.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)==="function"&&(t+8===this.input.length||!(isIdentifierChar(r=this.input.charCodeAt(t+8))||r>55295&&r<56320))};Z.parseStatement=function(e,t,r){var s=this.type,a=this.startNode(),o;if(this.isLet(e)){s=_._var;o="let"}switch(s){case _._break:case _._continue:return this.parseBreakContinueStatement(a,s.keyword);case _._debugger:return this.parseDebuggerStatement(a);case _._do:return this.parseDoStatement(a);case _._for:return this.parseForStatement(a);case _._function:if(e&&(this.strict||e!=="if"&&e!=="label")&&this.options.ecmaVersion>=6){this.unexpected()}return this.parseFunctionStatement(a,false,!e);case _._class:if(e){this.unexpected()}return this.parseClass(a,true);case _._if:return this.parseIfStatement(a);case _._return:return this.parseReturnStatement(a);case _._switch:return this.parseSwitchStatement(a);case _._throw:return this.parseThrowStatement(a);case _._try:return this.parseTryStatement(a);case _._const:case _._var:o=o||this.value;if(e&&o!=="var"){this.unexpected()}return this.parseVarStatement(a,o);case _._while:return this.parseWhileStatement(a);case _._with:return this.parseWithStatement(a);case _.braceL:return this.parseBlock(true,a);case _.semi:return this.parseEmptyStatement(a);case _._export:case _._import:if(this.options.ecmaVersion>10&&s===_._import){E.lastIndex=this.pos;var u=E.exec(this.input);var c=this.pos+u[0].length,f=this.input.charCodeAt(c);if(f===40||f===46){return this.parseExpressionStatement(a,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return s===_._import?this.parseImport(a):this.parseExport(a,r);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(a,true,!e)}var p=this.value,d=this.parseExpression();if(s===_.name&&d.type==="Identifier"&&this.eat(_.colon)){return this.parseLabeledStatement(a,p,d,e)}else{return this.parseExpressionStatement(a,d)}}};Z.parseBreakContinueStatement=function(e,t){var r=t==="break";this.next();if(this.eat(_.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==_.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var s=0;for(;s=6){this.eat(_.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};Z.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(J);this.enterScope(0);this.expect(_.parenL);if(this.type===_.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var r=this.isLet();if(this.type===_._var||this.type===_._const||r){var s=this.startNode(),a=r?"let":this.value;this.next();this.parseVar(s,true,a);this.finishNode(s,"VariableDeclaration");if((this.type===_._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&s.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===_._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,s)}if(t>-1){this.unexpected(t)}return this.parseFor(e,s)}var o=this.isContextual("let"),u=false;var c=new DestructuringErrors;var f=this.parseExpression(t>-1?"await":true,c);if(this.type===_._in||(u=this.options.ecmaVersion>=6&&this.isContextual("of"))){if(this.options.ecmaVersion>=9){if(this.type===_._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}if(o&&u){this.raise(f.start,"The left-hand side of a for-of loop may not start with 'let'.")}this.toAssignable(f,false,c);this.checkLValPattern(f);return this.parseForIn(e,f)}else{this.checkExpressionErrors(c,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,f)};Z.parseFunctionStatement=function(e,t,r){this.next();return this.parseFunction(e,ie|(r?0:re),false,t)};Z.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(_._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};Z.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(_.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};Z.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(_.braceL);this.labels.push(ee);this.enterScope(0);var t;for(var r=false;this.type!==_.braceR;){if(this.type===_._case||this.type===_._default){var s=this.type===_._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(s){t.test=this.parseExpression()}else{if(r){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}r=true;t.test=null}this.expect(_.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};Z.parseThrowStatement=function(e){this.next();if(y.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var te=[];Z.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===_._catch){var t=this.startNode();this.next();if(this.eat(_.parenL)){t.param=this.parseBindingAtom();var r=t.param.type==="Identifier";this.enterScope(r?M:0);this.checkLValPattern(t.param,r?G:H);this.expect(_.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(_._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};Z.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};Z.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(J);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};Z.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};Z.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};Z.parseLabeledStatement=function(e,t,r,s){for(var a=0,o=this.labels;a=0;f--){var p=this.labels[f];if(p.statementStart===e.start){p.statementStart=this.start;p.kind=c}else{break}}this.labels.push({name:t,kind:c,statementStart:this.start});e.body=this.parseStatement(s?s.indexOf("label")===-1?s+"label":s:"label");this.labels.pop();e.label=r;return this.finishNode(e,"LabeledStatement")};Z.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};Z.parseBlock=function(e,t,r){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(_.braceL);if(e){this.enterScope(0)}while(this.type!==_.braceR){var s=this.parseStatement(null);t.body.push(s)}if(r){this.strict=false}this.next();if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};Z.parseFor=function(e,t){e.init=t;this.expect(_.semi);e.test=this.type===_.semi?null:this.parseExpression();this.expect(_.semi);e.update=this.type===_.parenR?null:this.parseExpression();this.expect(_.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};Z.parseForIn=function(e,t){var r=this.type===_._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!r||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(r?"for-in":"for-of")+" loop variable declaration may not have an initializer")}e.left=t;e.right=r?this.parseExpression():this.parseMaybeAssign();this.expect(_.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,r?"ForInStatement":"ForOfStatement")};Z.parseVar=function(e,t,r){e.declarations=[];e.kind=r;for(;;){var s=this.startNode();this.parseVarId(s,r);if(this.eat(_.eq)){s.init=this.parseMaybeAssign(t)}else if(r==="const"&&!(this.type===_._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(s.id.type!=="Identifier"&&!(t&&(this.type===_._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{s.init=null}e.declarations.push(this.finishNode(s,"VariableDeclarator"));if(!this.eat(_.comma)){break}}return e};Z.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLValPattern(e.id,t==="var"?q:H,false)};var ie=1,re=2,ne=4;Z.parseFunction=function(e,t,r,s,a){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!s){if(this.type===_.star&&t&re){this.unexpected()}e.generator=this.eat(_.star)}if(this.options.ecmaVersion>=8){e.async=!!s}if(t&ie){e.id=t&ne&&this.type!==_.name?null:this.parseIdent();if(e.id&&!(t&re)){this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?q:H:$)}}var o=this.yieldPos,u=this.awaitPos,c=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&ie)){e.id=this.type===_.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,r,false,a);this.yieldPos=o;this.awaitPos=u;this.awaitIdentPos=c;return this.finishNode(e,t&ie?"FunctionDeclaration":"FunctionExpression")};Z.parseFunctionParams=function(e){this.expect(_.parenL);e.params=this.parseBindingList(_.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};Z.parseClass=function(e,t){this.next();var r=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var s=this.enterClassBody();var a=this.startNode();var o=false;a.body=[];this.expect(_.braceL);while(this.type!==_.braceR){var u=this.parseClassElement(e.superClass!==null);if(u){a.body.push(u);if(u.type==="MethodDefinition"&&u.kind==="constructor"){if(o){this.raise(u.start,"Duplicate constructor in the same class")}o=true}else if(u.key&&u.key.type==="PrivateIdentifier"&&isPrivateNameConflicted(s,u)){this.raiseRecoverable(u.key.start,"Identifier '#"+u.key.name+"' has already been declared")}}}this.strict=r;this.next();e.body=this.finishNode(a,"ClassBody");this.exitClassBody();return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};Z.parseClassElement=function(e){if(this.eat(_.semi)){return null}var t=this.options.ecmaVersion;var r=this.startNode();var s="";var a=false;var o=false;var u="method";var c=false;if(this.eatContextual("static")){if(t>=13&&this.eat(_.braceL)){this.parseClassStaticBlock(r);return r}if(this.isClassElementNameStart()||this.type===_.star){c=true}else{s="static"}}r.static=c;if(!s&&t>=8&&this.eatContextual("async")){if((this.isClassElementNameStart()||this.type===_.star)&&!this.canInsertSemicolon()){o=true}else{s="async"}}if(!s&&(t>=9||!o)&&this.eat(_.star)){a=true}if(!s&&!o&&!a){var f=this.value;if(this.eatContextual("get")||this.eatContextual("set")){if(this.isClassElementNameStart()){u=f}else{s=f}}}if(s){r.computed=false;r.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc);r.key.name=s;this.finishNode(r.key,"Identifier")}else{this.parseClassElementName(r)}if(t<13||this.type===_.parenL||u!=="method"||a||o){var p=!r.static&&checkKeyName(r,"constructor");var d=p&&e;if(p&&u!=="method"){this.raise(r.key.start,"Constructor can't have get/set modifier")}r.kind=p?"constructor":u;this.parseClassMethod(r,a,o,d)}else{this.parseClassField(r)}return r};Z.isClassElementNameStart=function(){return this.type===_.name||this.type===_.privateId||this.type===_.num||this.type===_.string||this.type===_.bracketL||this.type.keyword};Z.parseClassElementName=function(e){if(this.type===_.privateId){if(this.value==="constructor"){this.raise(this.start,"Classes can't have an element named '#constructor'")}e.computed=false;e.key=this.parsePrivateIdent()}else{this.parsePropertyName(e)}};Z.parseClassMethod=function(e,t,r,s){var a=e.key;if(e.kind==="constructor"){if(t){this.raise(a.start,"Constructor can't be a generator")}if(r){this.raise(a.start,"Constructor can't be an async method")}}else if(e.static&&checkKeyName(e,"prototype")){this.raise(a.start,"Classes may not have a static property named prototype")}var o=e.value=this.parseMethod(t,r,s);if(e.kind==="get"&&o.params.length!==0){this.raiseRecoverable(o.start,"getter should have no params")}if(e.kind==="set"&&o.params.length!==1){this.raiseRecoverable(o.start,"setter should have exactly one param")}if(e.kind==="set"&&o.params[0].type==="RestElement"){this.raiseRecoverable(o.params[0].start,"Setter cannot use rest params")}return this.finishNode(e,"MethodDefinition")};Z.parseClassField=function(e){if(checkKeyName(e,"constructor")){this.raise(e.key.start,"Classes can't have a field named 'constructor'")}else if(e.static&&checkKeyName(e,"prototype")){this.raise(e.key.start,"Classes can't have a static field named 'prototype'")}if(this.eat(_.eq)){var t=this.currentThisScope();var r=t.inClassFieldInit;t.inClassFieldInit=true;e.value=this.parseMaybeAssign();t.inClassFieldInit=r}else{e.value=null}this.semicolon();return this.finishNode(e,"PropertyDefinition")};Z.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;this.labels=[];this.enterScope(W|F);while(this.type!==_.braceR){var r=this.parseStatement(null);e.body.push(r)}this.next();this.exitScope();this.labels=t;return this.finishNode(e,"StaticBlock")};Z.parseClassId=function(e,t){if(this.type===_.name){e.id=this.parseIdent();if(t){this.checkLValSimple(e.id,H,false)}}else{if(t===true){this.unexpected()}e.id=null}};Z.parseClassSuper=function(e){e.superClass=this.eat(_._extends)?this.parseExprSubscripts(false):null};Z.enterClassBody=function(){var e={declared:Object.create(null),used:[]};this.privateNameStack.push(e);return e.declared};Z.exitClassBody=function(){var e=this.privateNameStack.pop();var t=e.declared;var r=e.used;var s=this.privateNameStack.length;var a=s===0?null:this.privateNameStack[s-1];for(var o=0;o=11){if(this.eatContextual("as")){e.exported=this.parseIdent(true);this.checkExport(t,e.exported.name,this.lastTokStart)}else{e.exported=null}}this.expectContextual("from");if(this.type!==_.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(_._default)){this.checkExport(t,"default",this.lastTokStart);var r;if(this.type===_._function||(r=this.isAsyncFunction())){var s=this.startNode();this.next();if(r){this.next()}e.declaration=this.parseFunction(s,ie|ne,false,r)}else if(this.type===_._class){var a=this.startNode();e.declaration=this.parseClass(a,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==_.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var o=0,u=e.specifiers;o=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(r){this.checkPatternErrors(r,true)}for(var s=0,a=e.properties;s=8&&!u&&c.name==="async"&&!this.canInsertSemicolon()&&this.eat(_._function)){this.overrideContext(oe.f_expr);return this.parseFunction(this.startNodeAt(a,o),0,false,true,t)}if(s&&!this.canInsertSemicolon()){if(this.eat(_.arrow)){return this.parseArrowExpression(this.startNodeAt(a,o),[c],false,t)}if(this.options.ecmaVersion>=8&&c.name==="async"&&this.type===_.name&&!u&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc)){c=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(_.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(a,o),[c],true,t)}}return c;case _.regexp:var f=this.value;r=this.parseLiteral(f.value);r.regex={pattern:f.pattern,flags:f.flags};return r;case _.num:case _.string:return this.parseLiteral(this.value);case _._null:case _._true:case _._false:r=this.startNode();r.value=this.type===_._null?null:this.type===_._true;r.raw=this.type.keyword;this.next();return this.finishNode(r,"Literal");case _.parenL:var p=this.start,d=this.parseParenAndDistinguishExpression(s,t);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(d)){e.parenthesizedAssign=p}if(e.parenthesizedBind<0){e.parenthesizedBind=p}}return d;case _.bracketL:r=this.startNode();this.next();r.elements=this.parseExprList(_.bracketR,true,true,e);return this.finishNode(r,"ArrayExpression");case _.braceL:this.overrideContext(oe.b_expr);return this.parseObj(false,e);case _._function:r=this.startNode();this.next();return this.parseFunction(r,0);case _._class:return this.parseClass(this.startNode(),false);case _._new:return this.parseNew();case _.backQuote:return this.parseTemplate();case _._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};ue.parseExprImport=function(){var e=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var t=this.parseIdent(true);switch(this.type){case _.parenL:return this.parseDynamicImport(e);case _.dot:e.meta=t;return this.parseImportMeta(e);default:this.unexpected()}};ue.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(_.parenR)){var t=this.start;if(this.eat(_.comma)&&this.eat(_.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};ue.parseImportMeta=function(e){this.next();var t=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="meta"){this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'")}if(t){this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere){this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(e,"MetaProperty")};ue.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(t,"Literal")};ue.parseParenExpression=function(){this.expect(_.parenL);var e=this.parseExpression();this.expect(_.parenR);return e};ue.parseParenAndDistinguishExpression=function(e,t){var r=this.start,s=this.startLoc,a,o=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var u=this.start,c=this.startLoc;var f=[],p=true,d=false;var h=new DestructuringErrors,v=this.yieldPos,g=this.awaitPos,m;this.yieldPos=0;this.awaitPos=0;while(this.type!==_.parenR){p?p=false:this.expect(_.comma);if(o&&this.afterTrailingComma(_.parenR,true)){d=true;break}else if(this.type===_.ellipsis){m=this.start;f.push(this.parseParenItem(this.parseRestBinding()));if(this.type===_.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{f.push(this.parseMaybeAssign(false,h,this.parseParenItem))}}var y=this.lastTokEnd,x=this.lastTokEndLoc;this.expect(_.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(_.arrow)){this.checkPatternErrors(h,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=v;this.awaitPos=g;return this.parseParenArrowList(r,s,f,t)}if(!f.length||d){this.unexpected(this.lastTokStart)}if(m){this.unexpected(m)}this.checkExpressionErrors(h,true);this.yieldPos=v||this.yieldPos;this.awaitPos=g||this.awaitPos;if(f.length>1){a=this.startNodeAt(u,c);a.expressions=f;this.finishNodeAt(a,"SequenceExpression",y,x)}else{a=f[0]}}else{a=this.parseParenExpression()}if(this.options.preserveParens){var w=this.startNodeAt(r,s);w.expression=a;return this.finishNode(w,"ParenthesizedExpression")}else{return a}};ue.parseParenItem=function(e){return e};ue.parseParenArrowList=function(e,t,r,s){return this.parseArrowExpression(this.startNodeAt(e,t),r,false,s)};var ce=[];ue.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(_.dot)){e.meta=t;var r=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"){this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'")}if(r){this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters")}if(!this.allowNewDotTarget){this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block")}return this.finishNode(e,"MetaProperty")}var s=this.start,a=this.startLoc,o=this.type===_._import;e.callee=this.parseSubscripts(this.parseExprAtom(),s,a,true,false);if(o&&e.callee.type==="ImportExpression"){this.raise(s,"Cannot use new with import()")}if(this.eat(_.parenL)){e.arguments=this.parseExprList(_.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=ce}return this.finishNode(e,"NewExpression")};ue.parseTemplateElement=function(e){var t=e.isTagged;var r=this.startNode();if(this.type===_.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}r.value={raw:this.value,cooked:null}}else{r.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();r.tail=this.type===_.backQuote;return this.finishNode(r,"TemplateElement")};ue.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var r=this.startNode();this.next();r.expressions=[];var s=this.parseTemplateElement({isTagged:t});r.quasis=[s];while(!s.tail){if(this.type===_.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(_.dollarBraceL);r.expressions.push(this.parseExpression());this.expect(_.braceR);r.quasis.push(s=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(r,"TemplateLiteral")};ue.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===_.name||this.type===_.num||this.type===_.string||this.type===_.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===_.star)&&!y.test(this.input.slice(this.lastTokEnd,this.start))};ue.parseObj=function(e,t){var r=this.startNode(),s=true,a={};r.properties=[];this.next();while(!this.eat(_.braceR)){if(!s){this.expect(_.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(_.braceR)){break}}else{s=false}var o=this.parseProperty(e,t);if(!e){this.checkPropClash(o,a,t)}r.properties.push(o)}return this.finishNode(r,e?"ObjectPattern":"ObjectExpression")};ue.parseProperty=function(e,t){var r=this.startNode(),s,a,o,u;if(this.options.ecmaVersion>=9&&this.eat(_.ellipsis)){if(e){r.argument=this.parseIdent(false);if(this.type===_.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(r,"RestElement")}if(this.type===_.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}r.argument=this.parseMaybeAssign(false,t);if(this.type===_.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(r,"SpreadElement")}if(this.options.ecmaVersion>=6){r.method=false;r.shorthand=false;if(e||t){o=this.start;u=this.startLoc}if(!e){s=this.eat(_.star)}}var c=this.containsEsc;this.parsePropertyName(r);if(!e&&!c&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(r)){a=true;s=this.options.ecmaVersion>=9&&this.eat(_.star);this.parsePropertyName(r,t)}else{a=false}this.parsePropertyValue(r,e,s,a,o,u,t,c);return this.finishNode(r,"Property")};ue.parsePropertyValue=function(e,t,r,s,a,o,u,c){if((r||s)&&this.type===_.colon){this.unexpected()}if(this.eat(_.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,u);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===_.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(r,s)}else if(!t&&!c&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==_.comma&&this.type!==_.braceR&&this.type!==_.eq)){if(r||s){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var f=e.kind==="get"?0:1;if(e.value.params.length!==f){var p=e.value.start;if(e.kind==="get"){this.raiseRecoverable(p,"getter should have no params")}else{this.raiseRecoverable(p,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(r||s){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=a}e.kind="init";if(t){e.value=this.parseMaybeDefault(a,o,this.copyNode(e.key))}else if(this.type===_.eq&&u){if(u.shorthandAssign<0){u.shorthandAssign=this.start}e.value=this.parseMaybeDefault(a,o,this.copyNode(e.key))}else{e.value=this.copyNode(e.key)}e.shorthand=true}else{this.unexpected()}};ue.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(_.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(_.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===_.num||this.type===_.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ue.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};ue.parseMethod=function(e,t,r){var s=this.startNode(),a=this.yieldPos,o=this.awaitPos,u=this.awaitIdentPos;this.initFunction(s);if(this.options.ecmaVersion>=6){s.generator=e}if(this.options.ecmaVersion>=8){s.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,s.generator)|F|(r?B:0));this.expect(_.parenL);s.params=this.parseBindingList(_.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(s,false,true,false);this.yieldPos=a;this.awaitPos=o;this.awaitIdentPos=u;return this.finishNode(s,"FunctionExpression")};ue.parseArrowExpression=function(e,t,r,s){var a=this.yieldPos,o=this.awaitPos,u=this.awaitIdentPos;this.enterScope(functionFlags(r,false)|D);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!r}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false,s);this.yieldPos=a;this.awaitPos=o;this.awaitIdentPos=u;return this.finishNode(e,"ArrowFunctionExpression")};ue.parseFunctionBody=function(e,t,r,s){var a=t&&this.type!==_.braceL;var o=this.strict,u=false;if(a){e.body=this.parseMaybeAssign(s);e.expression=true;this.checkParams(e,false)}else{var c=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!o||c){u=this.strictDirective(this.end);if(u&&c){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var f=this.labels;this.labels=[];if(u){this.strict=true}this.checkParams(e,!o&&!u&&!t&&!r&&this.isSimpleParamList(e.params));if(this.strict&&e.id){this.checkLValSimple(e.id,K)}e.body=this.parseBlock(false,undefined,u&&!o);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=f}this.exitScope()};ue.isSimpleParamList=function(e){for(var t=0,r=e;t-1||a.functions.indexOf(e)>-1||a.var.indexOf(e)>-1;a.lexical.push(e);if(this.inModule&&a.flags&N){delete this.undefinedExports[e]}}else if(t===G){var o=this.currentScope();o.lexical.push(e)}else if(t===$){var u=this.currentScope();if(this.treatFunctionsAsVar){s=u.lexical.indexOf(e)>-1}else{s=u.lexical.indexOf(e)>-1||u.var.indexOf(e)>-1}u.functions.push(e)}else{for(var c=this.scopeStack.length-1;c>=0;--c){var f=this.scopeStack[c];if(f.lexical.indexOf(e)>-1&&!(f.flags&M&&f.lexical[0]===e)||!this.treatFunctionsAsVarInScope(f)&&f.functions.indexOf(e)>-1){s=true;break}f.var.push(e);if(this.inModule&&f.flags&N){delete this.undefinedExports[e]}if(f.flags&U){break}}}if(s){this.raiseRecoverable(r,"Identifier '"+e+"' has already been declared")}};pe.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};pe.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pe.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&U){return t}}};pe.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&U&&!(t.flags&D)){return t}}};var he=function Node(e,t,r){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new T(e,r)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var ve=z.prototype;ve.startNode=function(){return new he(this,this.start,this.startLoc)};ve.startNodeAt=function(e,t){return new he(this,e,t)};function finishNodeAt(e,t,r,s){e.type=t;e.end=r;if(this.options.locations){e.loc.end=s}if(this.options.ranges){e.range[1]=r}return e}ve.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};ve.finishNodeAt=function(e,t,r,s){return finishNodeAt.call(this,e,t,r,s)};ve.copyNode=function(e){var t=new he(this,e.start,this.startLoc);for(var r in e){t[r]=e[r]}return t};var be="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var ge=be+" Extended_Pictographic";var me=ge;var _e=me+" EBase EComp EMod EPres ExtPict";var ye={9:be,10:ge,11:me,12:_e};var xe="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var we="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var Ee=we+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var Se=Ee+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var ke=Se+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";var Ae={9:we,10:Ee,11:Se,12:ke};var Ce={};function buildUnicodeData(e){var t=Ce[e]={binary:wordsRegexp(ye[e]+" "+xe),nonBinary:{General_Category:wordsRegexp(xe),Script:wordsRegexp(Ae[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);buildUnicodeData(12);var Re=z.prototype;var Te=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"");this.unicodeProperties=Ce[e.options.ecmaVersion>=12?12:e.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};Te.prototype.reset=function reset(e,t,r){var s=r.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=r;this.switchU=s&&this.parser.options.ecmaVersion>=6;this.switchN=s&&this.parser.options.ecmaVersion>=9};Te.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};Te.prototype.at=function at(e,t){if(t===void 0)t=false;var r=this.source;var s=r.length;if(e>=s){return-1}var a=r.charCodeAt(e);if(!(t||this.switchU)||a<=55295||a>=57344||e+1>=s){return a}var o=r.charCodeAt(e+1);return o>=56320&&o<=57343?(a<<10)+o-56613888:a};Te.prototype.nextIndex=function nextIndex(e,t){if(t===void 0)t=false;var r=this.source;var s=r.length;if(e>=s){return s}var a=r.charCodeAt(e),o;if(!(t||this.switchU)||a<=55295||a>=57344||e+1>=s||(o=r.charCodeAt(e+1))<56320||o>57343){return e+1}return e+2};Te.prototype.current=function current(e){if(e===void 0)e=false;return this.at(this.pos,e)};Te.prototype.lookahead=function lookahead(e){if(e===void 0)e=false;return this.at(this.nextIndex(this.pos,e),e)};Te.prototype.advance=function advance(e){if(e===void 0)e=false;this.pos=this.nextIndex(this.pos,e)};Te.prototype.eat=function eat(e,t){if(t===void 0)t=false;if(this.current(t)===e){this.advance(t);return true}return false};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Re.validateRegExpFlags=function(e){var t=e.validFlags;var r=e.flags;for(var s=0;s-1){this.raise(e.start,"Duplicate regular expression flag")}}};Re.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};Re.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,r=e.backReferenceNames;t=9){r=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!r;return true}}e.pos=t;return false};Re.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};Re.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};Re.regexp_eatBracedQuantifier=function(e,t){var r=e.pos;if(e.eat(123)){var s=0,a=-1;if(this.regexp_eatDecimalDigits(e)){s=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){a=e.lastIntValue}if(e.eat(125)){if(a!==-1&&a=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};Re.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};Re.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};Re.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}Re.regexp_eatPatternCharacters=function(e){var t=e.pos;var r=0;while((r=e.current())!==-1&&!isSyntaxCharacter(r)){e.advance()}return e.pos!==t};Re.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};Re.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};Re.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};Re.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString$1(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString$1(e.lastIntValue)}return true}return false};Re.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var r=this.options.ecmaVersion>=11;var s=e.current(r);e.advance(r);if(s===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,r)){s=e.lastIntValue}if(isRegExpIdentifierStart(s)){e.lastIntValue=s;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}Re.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var r=this.options.ecmaVersion>=11;var s=e.current(r);e.advance(r);if(s===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,r)){s=e.lastIntValue}if(isRegExpIdentifierPart(s)){e.lastIntValue=s;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}Re.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};Re.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var r=e.lastIntValue;if(e.switchU){if(r>e.maxBackReference){e.maxBackReference=r}return true}if(r<=e.numCapturingParens){return true}e.pos=t}return false};Re.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};Re.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,false)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};Re.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};Re.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};Re.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};Re.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}Re.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){if(t===void 0)t=false;var r=e.pos;var s=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var a=e.lastIntValue;if(s&&a>=55296&&a<=56319){var o=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var u=e.lastIntValue;if(u>=56320&&u<=57343){e.lastIntValue=(a-55296)*1024+(u-56320)+65536;return true}}e.pos=o;e.lastIntValue=a}return true}if(s&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(s){e.raise("Invalid unicode escape")}e.pos=r}return false};function isValidUnicode(e){return e>=0&&e<=1114111}Re.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};Re.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};Re.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}Re.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var r=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var s=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,r,s);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var a=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,a);return true}return false};Re.regexp_validateUnicodePropertyNameAndValue=function(e,t,r){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(r)){e.raise("Invalid property value")}};Re.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};Re.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString$1(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}Re.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString$1(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}Re.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};Re.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};Re.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var r=e.lastIntValue;if(e.switchU&&(t===-1||r===-1)){e.raise("Invalid character class")}if(t!==-1&&r!==-1&&t>r){e.raise("Range out of order in character class")}}}};Re.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var r=e.current();if(r===99||isOctalDigit(r)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var s=e.current();if(s!==93){e.lastIntValue=s;e.advance();return true}return false};Re.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};Re.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};Re.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};Re.regexp_eatDecimalDigits=function(e){var t=e.pos;var r=0;e.lastIntValue=0;while(isDecimalDigit(r=e.current())){e.lastIntValue=10*e.lastIntValue+(r-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}Re.regexp_eatHexDigits=function(e){var t=e.pos;var r=0;e.lastIntValue=0;while(isHexDigit(r=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(r);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}Re.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var r=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+r*8+e.lastIntValue}else{e.lastIntValue=t*8+r}}else{e.lastIntValue=t}return true}return false};Re.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}Re.regexp_eatFixedHexDigits=function(e,t){var r=e.pos;e.lastIntValue=0;for(var s=0;s=this.input.length){return this.finishToken(_.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};Oe.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};Oe.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320){return e}var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888};Oe.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,r=this.input.indexOf("*/",this.pos+=2);if(r===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=r+2;if(this.options.locations){x.lastIndex=t;var s;while((s=x.exec(this.input))&&s.index8&&e<14||e>=5760&&w.test(String.fromCharCode(e))){++this.pos}else{break e}}}};Oe.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var r=this.type;this.type=e;this.value=t;this.updateContext(r)};Oe.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(_.ellipsis)}else{++this.pos;return this.finishToken(_.dot)}};Oe.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(_.assign,2)}return this.finishOp(_.slash,1)};Oe.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var r=1;var s=e===42?_.star:_.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++r;s=_.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(_.assign,r+1)}return this.finishOp(s,r)};Oe.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var r=this.input.charCodeAt(this.pos+2);if(r===61){return this.finishOp(_.assign,3)}}return this.finishOp(e===124?_.logicalOR:_.logicalAND,2)}if(t===61){return this.finishOp(_.assign,2)}return this.finishOp(e===124?_.bitwiseOR:_.bitwiseAND,1)};Oe.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(_.assign,2)}return this.finishOp(_.bitwiseXOR,1)};Oe.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||y.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(_.incDec,2)}if(t===61){return this.finishOp(_.assign,2)}return this.finishOp(_.plusMin,1)};Oe.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var r=1;if(t===e){r=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+r)===61){return this.finishOp(_.assign,r+1)}return this.finishOp(_.bitShift,r)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){r=2}return this.finishOp(_.relational,r)};Oe.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(_.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(_.arrow)}return this.finishOp(e===61?_.eq:_.prefix,1)};Oe.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var r=this.input.charCodeAt(this.pos+2);if(r<48||r>57){return this.finishOp(_.questionDot,2)}}if(t===63){if(e>=12){var s=this.input.charCodeAt(this.pos+2);if(s===61){return this.finishOp(_.assign,3)}}return this.finishOp(_.coalesce,2)}}return this.finishOp(_.question,1)};Oe.readToken_numberSign=function(){var e=this.options.ecmaVersion;var t=35;if(e>=13){++this.pos;t=this.fullCharCodeAtPos();if(isIdentifierStart(t,true)||t===92){return this.finishToken(_.privateId,this.readWord1())}}this.raise(this.pos,"Unexpected character '"+codePointToString(t)+"'")};Oe.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(_.parenL);case 41:++this.pos;return this.finishToken(_.parenR);case 59:++this.pos;return this.finishToken(_.semi);case 44:++this.pos;return this.finishToken(_.comma);case 91:++this.pos;return this.finishToken(_.bracketL);case 93:++this.pos;return this.finishToken(_.bracketR);case 123:++this.pos;return this.finishToken(_.braceL);case 125:++this.pos;return this.finishToken(_.braceR);case 58:++this.pos;return this.finishToken(_.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(_.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(_.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+codePointToString(e)+"'")};Oe.finishOp=function(e,t){var r=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,r)};Oe.readRegexp=function(){var e,t,r=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(r,"Unterminated regular expression")}var s=this.input.charAt(this.pos);if(y.test(s)){this.raise(r,"Unterminated regular expression")}if(!e){if(s==="["){t=true}else if(s==="]"&&t){t=false}else if(s==="/"&&!t){break}e=s==="\\"}else{e=false}++this.pos}var a=this.input.slice(r,this.pos);++this.pos;var o=this.pos;var u=this.readWord1();if(this.containsEsc){this.unexpected(o)}var c=this.regexpState||(this.regexpState=new Te(this));c.reset(r,a,u);this.validateRegExpFlags(c);this.validateRegExpPattern(c);var f=null;try{f=new RegExp(a,u)}catch(e){}return this.finishToken(_.regexp,{pattern:a,flags:u,value:f})};Oe.readInt=function(e,t,r){var s=this.options.ecmaVersion>=12&&t===undefined;var a=r&&this.input.charCodeAt(this.pos)===48;var o=this.pos,u=0,c=0;for(var f=0,p=t==null?Infinity:t;f=97){h=d-97+10}else if(d>=65){h=d-65+10}else if(d>=48&&d<=57){h=d-48}else{h=Infinity}if(h>=e){break}c=d;u=u*e+h}if(s&&c===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===o||t!=null&&this.pos-o!==t){return null}return u};function stringToNumber(e,t){if(t){return parseInt(e,8)}return parseFloat(e.replace(/_/g,""))}function stringToBigInt(e){if(typeof BigInt!=="function"){return null}return BigInt(e.replace(/_/g,""))}Oe.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var r=this.readInt(e);if(r==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){r=stringToBigInt(this.input.slice(t,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(_.num,r)};Oe.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10,undefined,true)===null){this.raise(t,"Invalid number")}var r=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(r&&this.strict){this.raise(t,"Invalid number")}var s=this.input.charCodeAt(this.pos);if(!r&&!e&&this.options.ecmaVersion>=11&&s===110){var a=stringToBigInt(this.input.slice(t,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(_.num,a)}if(r&&/[89]/.test(this.input.slice(t,this.pos))){r=false}if(s===46&&!r){++this.pos;this.readInt(10);s=this.input.charCodeAt(this.pos)}if((s===69||s===101)&&!r){s=this.input.charCodeAt(++this.pos);if(s===43||s===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var o=stringToNumber(this.input.slice(t,this.pos),r);return this.finishToken(_.num,o)};Oe.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var r=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(r,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Oe.readString=function(e){var t="",r=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var s=this.input.charCodeAt(this.pos);if(s===e){break}if(s===92){t+=this.input.slice(r,this.pos);t+=this.readEscapedChar(false);r=this.pos}else if(s===8232||s===8233){if(this.options.ecmaVersion<10){this.raise(this.start,"Unterminated string constant")}++this.pos;if(this.options.locations){this.curLine++;this.lineStart=this.pos}}else{if(isNewLine(s)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(r,this.pos++);return this.finishToken(_.string,t)};var Ne={};Oe.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===Ne){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};Oe.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw Ne}else{this.raise(e,t)}};Oe.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var r=this.input.charCodeAt(this.pos);if(r===96||r===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===_.template||this.type===_.invalidTemplate)){if(r===36){this.pos+=2;return this.finishToken(_.dollarBraceL)}else{++this.pos;return this.finishToken(_.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(_.template,e)}if(r===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(r)){e+=this.input.slice(t,this.pos);++this.pos;switch(r){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(r);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};Oe.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var s=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var a=parseInt(s,8);if(a>255){s=s.slice(0,-1);a=parseInt(s,8)}this.pos+=s.length-1;t=this.input.charCodeAt(this.pos);if((s!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-s.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(a)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};Oe.readHexChar=function(e){var t=this.pos;var r=this.readInt(16,e);if(r===null){this.invalidStringToken(t,"Bad character escape sequence")}return r};Oe.readWord1=function(){this.containsEsc=false;var e="",t=true,r=this.pos;var s=this.options.ecmaVersion>=6;while(this.posH,env:{NODE_ENV:u.UNKNOWN,[u.UNKNOWN]:true},[u.UNKNOWN]:true};const T=Symbol();const I=Symbol();const O=Symbol();const N=Symbol();const P=Symbol();const L=Symbol();const j=Symbol();const D=Symbol();const M={access:L,accessSync:L,createReadStream:L,exists:L,existsSync:L,fstat:L,fstatSync:L,lstat:L,lstatSync:L,open:L,readFile:L,readFileSync:L,stat:L,statSync:L};const F=Object.assign(Object.create(null),{bindings:{default:j},express:{default:function(){return{[u.UNKNOWN]:true,set:T,engine:I}}},fs:Object.assign({default:M},M),process:Object.assign({default:R},R),path:{default:{}},os:Object.assign({default:k.default},k.default),"@mapbox/node-pre-gyp":Object.assign({default:x.default},x.default),"node-pre-gyp":v.pregyp,"node-pre-gyp/lib/pre-binding":v.pregyp,"node-pre-gyp/lib/pre-binding.js":v.pregyp,"node-gyp-build":{default:D},nbind:{init:O,default:{init:O}},"resolve-from":{default:C.default},"strong-globalize":{default:{SetRootDir:N},SetRootDir:N},pkginfo:{default:P}});const B={_interopRequireDefault:g.normalizeDefaultRequire,_interopRequireWildcard:g.normalizeWildcardRequire,__importDefault:g.normalizeDefaultRequire,__importStar:g.normalizeWildcardRequire,MONGOOSE_DRIVER_PATH:undefined,URL:w.URL,Object:{assign:Object.assign}};B.global=B.GLOBAL=B.globalThis=B;const W=Symbol();v.pregyp.find[W]=true;const U=F.path;Object.keys(a.default).forEach((e=>{const t=a.default[e];if(typeof t==="function"){const r=function mockPath(){return t.apply(mockPath,arguments)};r[W]=true;U[e]=U.default[e]=r}else{U[e]=U.default[e]=t}}));U.resolve=U.default.resolve=function(...e){return a.default.resolve.apply(this,[H,...e])};U.resolve[W]=true;const V=new Set([".h",".cmake",".c",".cpp"]);const q=new Set(["CHANGELOG.md","README.md","readme.md","changelog.md"]);let H;const $=/^\/[^\/]+|^[a-z]:[\\/][^\\/]+/i;function isAbsolutePathOrUrl(e){if(e instanceof w.URL)return e.protocol==="file:";if(typeof e==="string"){if(e.startsWith("file:")){try{new w.URL(e);return true}catch(e){return false}}return $.test(e)}return false}const G=Symbol();const K=/([\/\\]\*\*[\/\\]\*)+/g;async function analyze(e,t,r){const s=new Set;const c=new Set;const g=new Set;const x=a.default.dirname(e);H=r.cwd;const k=h.getPackageBase(e);const emitAssetDirectory=e=>{if(!r.analysis.emitGlobs)return;const t=e.indexOf(u.WILDCARD);const o=t===-1?e.length:e.lastIndexOf(a.default.sep,t);const c=e.substr(0,o);const f=e.substr(o);const p=f.replace(u.wildcardRegEx,((e,t)=>f[t-1]===a.default.sep?"**/*":"*")).replace(K,"/**/*")||"/**/*";if(r.ignoreFn(a.default.relative(r.base,c+p)))return;C=C.then((async()=>{if(r.log)console.log("Globbing "+c+p);const e=await new Promise(((e,t)=>d.default(c+p,{mark:true,ignore:c+"/**/node_modules/**/*"},((r,s)=>r?t(r):e(s)))));e.filter((e=>!V.has(a.default.extname(e))&&!q.has(a.default.basename(e))&&!e.endsWith("/"))).forEach((e=>s.add(e)))}))};let C=Promise.resolve();t=t.replace(/^#![^\n\r]*[\r\n]/,"");let M;let U=false;try{M=S.parse(t,{ecmaVersion:"latest",allowReturnOutsideFunction:true});U=false}catch(t){const s=t&&t.message&&t.message.includes("sourceType: module");if(!s){r.warnings.add(new Error(`Failed to parse ${e} as script:\n${t&&t.message}`))}}if(!M){try{M=S.parse(t,{ecmaVersion:"latest",sourceType:"module",allowAwaitOutsideFunction:true});U=true}catch(t){r.warnings.add(new Error(`Failed to parse ${e} as module:\n${t&&t.message}`));return{assets:s,deps:c,imports:g,isESM:false}}}const z=w.pathToFileURL(e).href;const Q=Object.assign(Object.create(null),{__dirname:{shadowDepth:0,value:{value:a.default.resolve(e,"..")}},__filename:{shadowDepth:0,value:{value:e}},process:{shadowDepth:0,value:{value:R}}});if(!U||r.mixedModules){Q.require={shadowDepth:0,value:{value:{[u.FUNCTION](e){c.add(e);const t=F[e];return t.default},resolve(t){return _.default(t,e,r)}}}};Q.require.value.value.resolve[W]=true}function setKnownBinding(e,t){if(e==="require")return;Q[e]={shadowDepth:0,value:t}}function getKnownBinding(e){const t=Q[e];if(t){if(t.shadowDepth===0){return t.value}}return undefined}function hasKnownBindingValue(e){const t=Q[e];return t&&t.shadowDepth===0}if((U||r.mixedModules)&&isAst(M)){for(const e of M.body){if(e.type==="ImportDeclaration"){const t=String(e.source.value);c.add(t);const r=F[t];if(r){for(const t of e.specifiers){if(t.type==="ImportNamespaceSpecifier")setKnownBinding(t.local.name,{value:r});else if(t.type==="ImportDefaultSpecifier"&&"default"in r)setKnownBinding(t.local.name,{value:r.default});else if(t.type==="ImportSpecifier"&&t.imported.name in r)setKnownBinding(t.local.name,{value:r[t.imported.name]})}}}else if(e.type==="ExportNamedDeclaration"||e.type==="ExportAllDeclaration"){if(e.source)c.add(String(e.source.value))}}}async function computePureStaticValue(e,t=true){const r=Object.create(null);Object.keys(B).forEach((e=>{r[e]={value:B[e]}}));Object.keys(Q).forEach((e=>{r[e]=getKnownBinding(e)}));r["import.meta"]={url:z};const s=await u.evaluate(e,r,t);return s}let Y;let X;let Z=false;function emitWildcardRequire(e){if(!r.analysis.emitGlobs||!e.startsWith("./")&&!e.startsWith("../"))return;e=a.default.resolve(x,e);const t=e.indexOf(u.WILDCARD);const o=t===-1?e.length:e.lastIndexOf(a.default.sep,t);const c=e.substr(0,o);const f=e.substr(o);let p=f.replace(u.wildcardRegEx,((e,t)=>f[t-1]===a.default.sep?"**/*":"*"))||"/**/*";if(!p.endsWith("*"))p+="?("+(r.ts?".ts|.tsx|":"")+".js|.json|.node)";if(r.ignoreFn(a.default.relative(r.base,c+p)))return;C=C.then((async()=>{if(r.log)console.log("Globbing "+c+p);const e=await new Promise(((e,t)=>d.default(c+p,{mark:true,ignore:c+"/**/node_modules/**/*"},((r,s)=>r?t(r):e(s)))));e.filter((e=>!V.has(a.default.extname(e))&&!q.has(a.default.basename(e))&&!e.endsWith("/"))).forEach((e=>s.add(e)))}))}async function processRequireArg(e,t=false){if(e.type==="ConditionalExpression"){await processRequireArg(e.consequent,t);await processRequireArg(e.alternate,t);return}if(e.type==="LogicalExpression"){await processRequireArg(e.left,t);await processRequireArg(e.right,t);return}let r=await computePureStaticValue(e,true);if(!r)return;if("value"in r&&typeof r.value==="string"){if(!r.wildcards)(t?g:c).add(r.value);else if(r.wildcards.length>=1)emitWildcardRequire(r.value)}else{if("then"in r&&typeof r.then==="string")(t?g:c).add(r.then);if("else"in r&&typeof r.else==="string")(t?g:c).add(r.else)}}let J=o.attachScopes(M,"scope");if(isAst(M)){A.handleWrappers(M);await m.default({id:e,ast:M,emitAsset:e=>s.add(e),emitAssetDirectory:emitAssetDirectory,job:r})}async function backtrack(e,t){if(!Y)throw new Error("Internal error: No staticChildNode for backtrack.");const r=await computePureStaticValue(e,true);if(r){if("value"in r&&typeof r.value!=="symbol"||"then"in r&&typeof r.then!=="symbol"&&typeof r.else!=="symbol"){X=r;Y=e;if(t)t.skip();return}}await emitStaticChildAsset()}await E(M,{async enter(t,o){var u;const d=t;const h=o;if(d.scope){J=d.scope;for(const e in d.scope.declarations){if(e in Q)Q[e].shadowDepth++}}if(Y)return;if(!h)return;if(d.type==="Identifier"){if(p.isIdentifierRead(d,h)&&r.analysis.computeFileReferences){let e;if(typeof(e=(u=getKnownBinding(d.name))===null||u===void 0?void 0:u.value)==="string"&&e.match($)||e&&(typeof e==="function"||typeof e==="object")&&e[W]){X={value:typeof e==="string"?e:undefined};Y=d;await backtrack(h,this)}}}else if(r.analysis.computeFileReferences&&d.type==="MemberExpression"&&d.object.type==="MetaProperty"&&d.object.meta.name==="import"&&d.object.property.name==="meta"&&(d.property.computed?d.property.value:d.property.name)==="url"){X={value:z};Y=d;await backtrack(h,this)}else if(d.type==="ImportExpression"){await processRequireArg(d.source,true);return}else if(d.type==="CallExpression"){if((!U||r.mixedModules)&&d.callee.type==="Identifier"&&d.arguments.length){if(d.callee.name==="require"&&Q.require.shadowDepth===0){await processRequireArg(d.arguments[0]);return}}else if((!U||r.mixedModules)&&d.callee.type==="MemberExpression"&&d.callee.object.type==="Identifier"&&d.callee.object.name==="module"&&"module"in Q===false&&d.callee.property.type==="Identifier"&&!d.callee.computed&&d.callee.property.name==="require"&&d.arguments.length){await processRequireArg(d.arguments[0]);return}const t=r.analysis.evaluatePureExpressions&&await computePureStaticValue(d.callee,false);if(t&&"value"in t&&typeof t.value==="function"&&t.value[W]&&r.analysis.computeFileReferences){X=await computePureStaticValue(d,true);if(X&&h){Y=d;await backtrack(h,this)}}else if(t&&"value"in t&&typeof t.value==="symbol"){switch(t.value){case G:if(d.arguments.length===1&&d.arguments[0].type==="Literal"&&d.callee.type==="Identifier"&&Q.require.shadowDepth===0){await processRequireArg(d.arguments[0])}break;case j:if(d.arguments.length){const e=await computePureStaticValue(d.arguments[0],false);if(e&&"value"in e&&e.value){let t;if(typeof e.value==="object")t=e.value;else if(typeof e.value==="string")t={bindings:e.value};if(!t.path){t.path=true}t.module_root=k;let r;try{r=f.default(t)}catch(e){}if(r){X={value:r};Y=d;await emitStaticChildAsset()}}}break;case D:if(d.arguments.length===1&&d.arguments[0].type==="Identifier"&&d.arguments[0].name==="__dirname"&&Q.__dirname.shadowDepth===0){let e;try{e=y.default.path(x)}catch(e){}if(e){X={value:e};Y=d;await emitStaticChildAsset()}}break;case O:if(d.arguments.length){const e=await computePureStaticValue(d.arguments[0],false);if(e&&"value"in e&&(typeof e.value==="string"||typeof e.value==="undefined")){const t=v.nbind(e.value);if(t&&t.path){c.add(a.default.relative(x,t.path).replace(/\\/g,"/"));return this.skip()}}}break;case T:if(d.arguments.length===2&&d.arguments[0].type==="Literal"&&d.arguments[0].value==="view engine"&&!Z){await processRequireArg(d.arguments[1]);return this.skip()}break;case I:Z=true;break;case L:if(d.arguments[0]&&r.analysis.computeFileReferences){X=await computePureStaticValue(d.arguments[0],true);if(X){Y=d.arguments[0];await backtrack(h,this);return this.skip()}}break;case N:if(d.arguments[0]){const e=await computePureStaticValue(d.arguments[0],false);if(e&&"value"in e&&e.value)emitAssetDirectory(e.value+"/intl");return this.skip()}break;case P:let t=a.default.resolve(e,"../package.json");const o=a.default.resolve("/package.json");while(t!==o&&await r.stat(t)===null)t=a.default.resolve(t,"../../package.json");if(t!==o)s.add(t);break}}}else if(d.type==="VariableDeclaration"&&h&&!p.isVarLoop(h)&&r.analysis.evaluatePureExpressions){for(const e of d.declarations){if(!e.init)continue;const t=await computePureStaticValue(e.init,true);if(t){if(e.id.type==="Identifier"){setKnownBinding(e.id.name,t)}else if(e.id.type==="ObjectPattern"&&"value"in t){for(const r of e.id.properties){if(r.type!=="Property"||r.key.type!=="Identifier"||r.value.type!=="Identifier"||typeof t.value!=="object"||t.value===null||!(r.key.name in t.value))continue;setKnownBinding(r.value.name,{value:t.value[r.key.name]})}}if(!("value"in t)&&isAbsolutePathOrUrl(t.then)&&isAbsolutePathOrUrl(t.else)){X=t;Y=e.init;await emitStaticChildAsset()}}}}else if(d.type==="AssignmentExpression"&&h&&!p.isLoop(h)&&r.analysis.evaluatePureExpressions){if(!hasKnownBindingValue(d.left.name)){const e=await computePureStaticValue(d.right,false);if(e&&"value"in e){if(d.left.type==="Identifier"){setKnownBinding(d.left.name,e)}else if(d.left.type==="ObjectPattern"){for(const t of d.left.properties){if(t.type!=="Property"||t.key.type!=="Identifier"||t.value.type!=="Identifier"||typeof e.value!=="object"||e.value===null||!(t.key.name in e.value))continue;setKnownBinding(t.value.name,{value:e.value[t.key.name]})}}if(isAbsolutePathOrUrl(e.value)){X=e;Y=d.right;await emitStaticChildAsset()}}}}else if((!U||r.mixedModules)&&(d.type==="FunctionDeclaration"||d.type==="FunctionExpression"||d.type==="ArrowFunctionExpression")&&(d.arguments||d.params)[0]&&(d.arguments||d.params)[0].type==="Identifier"){let e;let t;if((d.type==="ArrowFunctionExpression"||d.type==="FunctionExpression")&&h&&h.type==="VariableDeclarator"&&h.id.type==="Identifier"){e=h.id;t=d.arguments||d.params}else if(d.id){e=d.id;t=d.arguments||d.params}if(e&&d.body.body){let r,s=false;for(let e=0;ee&&e.id&&e.id.type==="Identifier"&&e.init&&e.init.type==="CallExpression"&&e.init.callee.type==="Identifier"&&e.init.callee.name==="require"&&Q.require.shadowDepth===0&&e.init.arguments[0]&&e.init.arguments[0].type==="Identifier"&&e.init.arguments[0].name===t[0].name))}if(r&&d.body.body[e].type==="ReturnStatement"&&d.body.body[e].argument&&d.body.body[e].argument.type==="Identifier"&&d.body.body[e].argument.name===r.id.name){s=true;break}}if(s)setKnownBinding(e.name,{value:G})}}},async leave(e,t){const r=e;const s=t;if(r.scope){if(J.parent){J=J.parent}for(const e in r.scope.declarations){if(e in Q){if(Q[e].shadowDepth>0)Q[e].shadowDepth--;else delete Q[e]}}}if(Y&&s)await backtrack(s,this)}});await C;return{assets:s,deps:c,imports:g,isESM:U};async function emitAssetPath(e){const t=e.indexOf(u.WILDCARD);const o=t===-1?e.length:e.lastIndexOf(a.default.sep,t);const c=e.substr(0,o);try{var f=await r.stat(c);if(f===null){throw new Error("file not found")}}catch(e){return}if(t!==-1&&f.isFile())return;if(f.isFile()){s.add(e)}else if(f.isDirectory()){if(validWildcard(e))emitAssetDirectory(e)}}function validWildcard(t){let s="";if(t.endsWith(a.default.sep))s=a.default.sep;else if(t.endsWith(a.default.sep+u.WILDCARD))s=a.default.sep+u.WILDCARD;else if(t.endsWith(u.WILDCARD))s=u.WILDCARD;if(t===x+s)return false;if(t===H+s)return false;if(t.endsWith(a.default.sep+"node_modules"+s))return false;if(x.startsWith(t.substr(0,t.length-s.length)+a.default.sep))return false;if(k){const s=e.substr(0,e.indexOf(a.default.sep+"node_modules"))+a.default.sep+"node_modules"+a.default.sep;if(!t.startsWith(s)){if(r.log)console.log("Skipping asset emission of "+t.replace(u.wildcardRegEx,"*")+" for "+e+" as it is outside the package base "+k);return false}}return true}function resolveAbsolutePathOrUrl(e){return e instanceof w.URL?w.fileURLToPath(e):e.startsWith("file:")?w.fileURLToPath(new w.URL(e)):a.default.resolve(e)}async function emitStaticChildAsset(){if(!X){return}if("value"in X&&isAbsolutePathOrUrl(X.value)){try{const e=resolveAbsolutePathOrUrl(X.value);await emitAssetPath(e)}catch(e){}}else if("then"in X&&"else"in X&&isAbsolutePathOrUrl(X.then)&&isAbsolutePathOrUrl(X.else)){let e;try{e=resolveAbsolutePathOrUrl(X.then)}catch(e){}let t;try{t=resolveAbsolutePathOrUrl(X.else)}catch(e){}if(e)await emitAssetPath(e);if(t)await emitAssetPath(t)}else if(Y&&Y.type==="ArrayExpression"&&"value"in X&&X.value instanceof Array){for(const e of X.value){try{const t=resolveAbsolutePathOrUrl(e);await emitAssetPath(t)}catch(e){}}}Y=X=undefined}}t["default"]=analyze;function isAst(e){return"body"in e}},9582:function(e,t,r){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){if(s===undefined)s=r;Object.defineProperty(e,s,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,s){if(s===undefined)s=r;e[s]=t[r]});var a=this&&this.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!t.hasOwnProperty(r))s(t,e,r)};Object.defineProperty(t,"__esModule",{value:true});a(r(3864),t);var o=r(3471);Object.defineProperty(t,"nodeFileTrace",{enumerable:true,get:function(){return o.nodeFileTrace}})},3471:function(e,t,r){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.Job=t.nodeFileTrace=void 0;const a=r(1017);const o=s(r(552));const u=s(r(8827));const c=s(r(2278));const f=r(2540);const p=r(2985);const d=r(1017);const h=o.default.promises.readFile;const v=o.default.promises.readlink;const g=o.default.promises.stat;function inPath(e,t){const r=d.join(t,a.sep);return e.startsWith(r)&&e!==r}async function nodeFileTrace(e,t={}){const r=new Job(t);if(t.readFile)r.readFile=t.readFile;if(t.stat)r.stat=t.stat;if(t.readlink)r.readlink=t.readlink;if(t.resolve)r.resolve=t.resolve;r.ts=true;await Promise.all(e.map((async e=>{const t=a.resolve(e);await r.emitFile(t,"initial");if(t.endsWith(".js")||t.endsWith(".cjs")||t.endsWith(".mjs")||t.endsWith(".node")||r.ts&&(t.endsWith(".ts")||t.endsWith(".tsx"))){return r.emitDependency(t)}return undefined})));const s={fileList:r.fileList,esmFileList:r.esmFileList,reasons:r.reasons,warnings:r.warnings};return s}t.nodeFileTrace=nodeFileTrace;class Job{constructor({base:e=process.cwd(),processCwd:t,exports:r,conditions:s=r||["node"],exportsOnly:o=false,paths:u={},ignore:c,log:p=false,mixedModules:d=false,ts:h=true,analysis:v={},cache:g}){this.reasons=new Map;this.ts=h;e=a.resolve(e);this.ignoreFn=e=>{if(e.startsWith(".."+a.sep))return true;return false};if(typeof c==="string")c=[c];if(typeof c==="function"){const e=c;this.ignoreFn=t=>{if(t.startsWith(".."+a.sep))return true;if(e(t))return true;return false}}else if(Array.isArray(c)){const t=c.map((t=>a.relative(e,a.resolve(e||process.cwd(),t))));this.ignoreFn=e=>{if(e.startsWith(".."+a.sep))return true;if(f.isMatch(e,t))return true;return false}}this.base=e;this.cwd=a.resolve(t||e);this.conditions=s;this.exportsOnly=o;const m={};for(const t of Object.keys(u)){const r=u[t].endsWith("/");const s=a.resolve(e,u[t]);m[t]=s+(r?"/":"")}this.paths=m;this.log=p;this.mixedModules=d;this.analysis={};if(v!==false){Object.assign(this.analysis,{emitGlobs:true,computeFileReferences:true,evaluatePureExpressions:true},v===true?{}:v)}this.fileCache=g&&g.fileCache||new Map;this.statCache=g&&g.statCache||new Map;this.symlinkCache=g&&g.symlinkCache||new Map;this.analysisCache=g&&g.analysisCache||new Map;if(g){g.fileCache=this.fileCache;g.statCache=this.statCache;g.symlinkCache=this.symlinkCache;g.analysisCache=this.analysisCache}this.fileList=new Set;this.esmFileList=new Set;this.processed=new Set;this.warnings=new Set}async readlink(e){const t=this.symlinkCache.get(e);if(t!==undefined)return t;try{const t=await v(e);const r=this.statCache.get(e);if(r)this.statCache.set(a.resolve(e,t),r);this.symlinkCache.set(e,t);return t}catch(t){if(t.code!=="EINVAL"&&t.code!=="ENOENT"&&t.code!=="UNKNOWN")throw t;this.symlinkCache.set(e,null);return null}}async isFile(e){const t=await this.stat(e);if(t)return t.isFile();return false}async isDir(e){const t=await this.stat(e);if(t)return t.isDirectory();return false}async stat(e){const t=this.statCache.get(e);if(t)return t;try{const t=await g(e);this.statCache.set(e,t);return t}catch(t){if(t.code==="ENOENT"){this.statCache.set(e,null);return null}throw t}}async resolve(e,t,r,s){return c.default(e,t,r,s)}async readFile(e){const t=this.fileCache.get(e);if(t!==undefined)return t;try{const t=(await h(e)).toString();this.fileCache.set(e,t);return t}catch(t){if(t.code==="ENOENT"||t.code==="EISDIR"){this.fileCache.set(e,null);return null}throw t}}async realpath(e,t,r=new Set){if(r.has(e))throw new Error("Recursive symlink detected resolving "+e);r.add(e);const s=await this.readlink(e);if(s){const o=a.dirname(e);const u=a.resolve(o,s);const c=await this.realpath(o,t);if(inPath(e,c))await this.emitFile(e,"resolve",t,true);return this.realpath(u,t,r)}if(!inPath(e,this.base))return e;return d.join(await this.realpath(a.dirname(e),t,r),a.basename(e))}async emitFile(e,t,r,s=false){if(!s){e=await this.realpath(e,r)}e=a.relative(this.base,e);if(r){r=a.relative(this.base,r)}let o=this.reasons.get(e);if(!o){o={type:t,ignored:false,parents:new Set};this.reasons.set(e,o)}if(r&&this.ignoreFn(e,r)){if(!this.fileList.has(e)&&o){o.ignored=true}return false}if(r){o.parents.add(r)}this.fileList.add(e);return true}async getPjsonBoundary(e){const t=e.indexOf(a.sep);let r;while((r=e.lastIndexOf(a.sep))>t){e=e.substr(0,r);if(await this.isFile(e+a.sep+"package.json"))return e}return undefined}async emitDependency(e,t){if(this.processed.has(e)){if(t){await this.emitFile(e,"dependency",t)}return}this.processed.add(e);const r=await this.emitFile(e,"dependency",t);if(!r)return;if(e.endsWith(".json"))return;if(e.endsWith(".node"))return await p.sharedLibEmit(e,this);if(e.endsWith(".js")){const t=await this.getPjsonBoundary(e);if(t)await this.emitFile(t+a.sep+"package.json","resolve",e)}let s;const o=this.analysisCache.get(e);if(o){s=o}else{const t=await this.readFile(e);if(t===null)throw new Error("File "+e+" does not exist.");s=await u.default(e,t.toString(),this);this.analysisCache.set(e,s)}const{deps:c,imports:f,assets:d,isESM:h}=s;if(h)this.esmFileList.add(a.relative(this.base,e));await Promise.all([...[...d].map((async t=>{const r=a.extname(t);if(r===".js"||r===".mjs"||r===".node"||r===""||this.ts&&(r===".ts"||r===".tsx")&&t.startsWith(this.base)&&t.substr(this.base.length).indexOf(a.sep+"node_modules"+a.sep)===-1)await this.emitDependency(t,e);else await this.emitFile(t,"asset",e)})),...[...c].map((async t=>{try{var r=await this.resolve(t,e,this,!h)}catch(e){this.warnings.add(new Error(`Failed to resolve dependency ${t}:\n${e&&e.message}`));return}if(Array.isArray(r)){for(const t of r){if(t.startsWith("node:"))return;await this.emitDependency(t,e)}}else{if(r.startsWith("node:"))return;await this.emitDependency(r,e)}})),...[...f].map((async t=>{try{var r=await this.resolve(t,e,this,false)}catch(e){this.warnings.add(new Error(`Failed to resolve dependency ${t}:\n${e&&e.message}`));return}if(Array.isArray(r)){for(const t of r){if(t.startsWith("node:"))return;await this.emitDependency(t,e)}}else{if(r.startsWith("node:"))return;await this.emitDependency(r,e)}}))])}}t.Job=Job},2278:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});const s=r(1017);async function resolveDependency(e,t,r,a=true){let o;if(s.isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")){const a=e.endsWith("/");o=await resolvePath(s.resolve(t,"..",e)+(a?"/":""),t,r)}else if(e[0]==="#"){o=await packageImportsResolve(e,t,r,a)}else{o=await resolvePackage(e,t,r,a)}if(Array.isArray(o)){return Promise.all(o.map((e=>r.realpath(e,t))))}else if(o.startsWith("node:")){return o}else{return r.realpath(o,t)}}t["default"]=resolveDependency;async function resolvePath(e,t,r){const s=await resolveFile(e,t,r)||await resolveDir(e,t,r);if(!s){throw new NotFoundError(e,t)}return s}async function resolveFile(e,t,r){if(e.endsWith("/"))return undefined;e=await r.realpath(e,t);if(await r.isFile(e))return e;if(r.ts&&e.startsWith(r.base)&&e.substr(r.base.length).indexOf(s.sep+"node_modules"+s.sep)===-1&&await r.isFile(e+".ts"))return e+".ts";if(r.ts&&e.startsWith(r.base)&&e.substr(r.base.length).indexOf(s.sep+"node_modules"+s.sep)===-1&&await r.isFile(e+".tsx"))return e+".tsx";if(await r.isFile(e+".js"))return e+".js";if(await r.isFile(e+".json"))return e+".json";if(await r.isFile(e+".node"))return e+".node";return undefined}async function resolveDir(e,t,r){if(e.endsWith("/"))e=e.slice(0,-1);if(!await r.isDir(e))return;const a=await getPkgCfg(e,r);if(a&&typeof a.main==="string"){const o=await resolveFile(s.resolve(e,a.main),t,r)||await resolveFile(s.resolve(e,a.main,"index"),t,r);if(o){await r.emitFile(e+s.sep+"package.json","resolve",t);return o}}return resolveFile(s.resolve(e,"index"),t,r)}class NotFoundError extends Error{constructor(e,t){super("Cannot find module '"+e+"' loaded from "+t);this.code="MODULE_NOT_FOUND"}}const a=new Set([...r(8102)._builtinLibs,"constants","module","timers","console","_stream_writable","_stream_readable","_stream_duplex","process","sys"]);function getPkgName(e){const t=e.split("/");if(e[0]==="@"&&t.length>1)return t.length>1?t.slice(0,2).join("/"):null;return t.length?t[0]:null}async function getPkgCfg(e,t){const r=await t.readFile(e+s.sep+"package.json");if(r){try{return JSON.parse(r.toString())}catch(e){}}return undefined}function getExportsTarget(e,t,r){if(typeof e==="string"){return e}else if(e===null){return e}else if(Array.isArray(e)){for(const s of e){const e=getExportsTarget(s,t,r);if(e===null||typeof e==="string"&&e.startsWith("./"))return e}}else if(typeof e==="object"){for(const s of Object.keys(e)){if(s==="default"||s==="require"&&r||s==="import"&&!r||t.includes(s)){const a=getExportsTarget(e[s],t,r);if(a!==undefined)return a}}}return undefined}function resolveExportsImports(e,t,r,s,a,o){let u;if(a){if(!(typeof t==="object"&&!Array.isArray(t)&&t!==null))return undefined;u=t}else if(typeof t==="string"||Array.isArray(t)||t===null||typeof t==="object"&&Object.keys(t).length&&Object.keys(t)[0][0]!=="."){u={".":t}}else{u=t}if(r in u){const t=getExportsTarget(u[r],s.conditions,o);if(typeof t==="string"&&t.startsWith("./"))return e+t.slice(1)}for(const t of Object.keys(u).sort(((e,t)=>t.length-e.length))){if(t.endsWith("*")&&r.startsWith(t.slice(0,-1))){const a=getExportsTarget(u[t],s.conditions,o);if(typeof a==="string"&&a.startsWith("./"))return e+a.slice(1).replace(/\*/g,r.slice(t.length-1))}if(!t.endsWith("/"))continue;if(r.startsWith(t)){const a=getExportsTarget(u[t],s.conditions,o);if(typeof a==="string"&&a.endsWith("/")&&a.startsWith("./"))return e+a.slice(1)+r.slice(t.length)}}return undefined}async function packageImportsResolve(e,t,r,a){if(e!=="#"&&!e.startsWith("#/")&&r.conditions){const o=await r.getPjsonBoundary(t);if(o){const u=await getPkgCfg(o,r);const{imports:c}=u||{};if(u&&c!==null&&c!==undefined){let u=resolveExportsImports(o,c,e,r,true,a);if(u){if(a)u=await resolveFile(u,t,r)||await resolveDir(u,t,r);else if(!await r.isFile(u))throw new NotFoundError(u,t);if(u){await r.emitFile(o+s.sep+"package.json","resolve",t);return u}}}}}throw new NotFoundError(e,t)}async function resolvePackage(e,t,r,o){let u=t;if(a.has(e))return"node:"+e;const c=getPkgName(e)||"";let f;if(r.conditions){const a=await r.getPjsonBoundary(t);if(a){const u=await getPkgCfg(a,r);const{exports:p}=u||{};if(u&&u.name&&u.name===c&&p!==null&&p!==undefined){f=resolveExportsImports(a,p,"."+e.slice(c.length),r,false,o);if(f){if(o)f=await resolveFile(f,t,r)||await resolveDir(f,t,r);else if(!await r.isFile(f))throw new NotFoundError(f,t)}if(f)await r.emitFile(a+s.sep+"package.json","resolve",t)}}}let p;const d=u.indexOf(s.sep);while((p=u.lastIndexOf(s.sep))>d){u=u.substr(0,p);const a=u+s.sep+"node_modules";const d=await r.stat(a);if(!d||!d.isDirectory())continue;const h=await getPkgCfg(a+s.sep+c,r);const{exports:v}=h||{};if(r.conditions&&v!==undefined&&v!==null&&!f){let u;if(!r.exportsOnly)u=await resolveFile(a+s.sep+e,t,r)||await resolveDir(a+s.sep+e,t,r);let f=resolveExportsImports(a+s.sep+c,v,"."+e.slice(c.length),r,false,o);if(f){if(o)f=await resolveFile(f,t,r)||await resolveDir(f,t,r);else if(!await r.isFile(f))throw new NotFoundError(f,t)}if(f){await r.emitFile(a+s.sep+c+s.sep+"package.json","resolve",t);if(u&&u!==f)return[f,u];return f}if(u)return u}else{const o=await resolveFile(a+s.sep+e,t,r)||await resolveDir(a+s.sep+e,t,r);if(o){if(f&&f!==o)return[o,f];return o}}}if(f)return f;if(Object.hasOwnProperty.call(r.paths,e)){return r.paths[e]}for(const s of Object.keys(r.paths)){if(s.endsWith("/")&&e.startsWith(s)){const a=r.paths[s]+e.slice(s.length);const o=await resolveFile(a,t,r)||await resolveDir(a,t,r);if(!o){throw new NotFoundError(e,t)}return o}}throw new NotFoundError(e,t)}},3864:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true})},5078:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.isLoop=t.isVarLoop=t.isIdentifierRead=void 0;function isIdentifierRead(e,t){switch(t.type){case"ObjectPattern":case"ArrayPattern":return false;case"AssignmentExpression":return t.right===e;case"MemberExpression":return t.computed||e===t.object;case"Property":return e===t.value;case"MethodDefinition":return false;case"VariableDeclarator":return t.id!==e;case"ExportSpecifier":return false;case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":return false;default:return true}}t.isIdentifierRead=isIdentifierRead;function isVarLoop(e){return e.type==="ForStatement"||e.type==="ForInStatement"||e.type==="ForOfStatement"}t.isVarLoop=isVarLoop;function isLoop(e){return e.type==="ForStatement"||e.type==="ForInStatement"||e.type==="ForOfStatement"||e.type==="WhileStatement"||e.type==="DoWhileStatement"}t.isLoop=isLoop},2774:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:true});exports.nbind=exports.pregyp=void 0;const path_1=__importDefault(__nccwpck_require__(1017));const graceful_fs_1=__importDefault(__nccwpck_require__(552));const versioning=__nccwpck_require__(5574);const napi=__nccwpck_require__(9248);const pregypFind=(e,t)=>{const r=JSON.parse(graceful_fs_1.default.readFileSync(e).toString());versioning.validate_config(r,t);var s;if(napi.get_napi_build_versions(r,t)){s=napi.get_best_napi_build_version(r,t)}t=t||{};if(!t.module_root)t.module_root=path_1.default.dirname(e);var a=versioning.evaluate(r,t,s);return a.module};exports.pregyp={default:{find:pregypFind},find:pregypFind};function makeModulePathList(e,t){return[[e,t],[e,"build",t],[e,"build","Debug",t],[e,"build","Release",t],[e,"out","Debug",t],[e,"Debug",t],[e,"out","Release",t],[e,"Release",t],[e,"build","default",t],[e,process.env["NODE_BINDINGS_COMPILED_DIR"]||"compiled",process.versions.node,process.platform,process.arch,t]]}function findCompiledModule(basePath,specList){var resolvedList=[];var ext=path_1.default.extname(basePath);for(var _i=0,specList_1=specList;_i{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.getPackageName=t.getPackageBase=void 0;const r=/^(@[^\\\/]+[\\\/])?[^\\\/]+/;function getPackageBase(e){const t=e.lastIndexOf("node_modules");if(t!==-1&&(e[t-1]==="/"||e[t-1]==="\\")&&(e[t+12]==="/"||e[t+12]==="\\")){const s=e.substr(t+13).match(r);if(s)return e.substr(0,t+13+s[0].length)}return undefined}t.getPackageBase=getPackageBase;function getPackageName(e){const t=e.lastIndexOf("node_modules");if(t!==-1&&(e[t-1]==="/"||e[t-1]==="\\")&&(e[t+12]==="/"||e[t+12]==="\\")){const s=e.substr(t+13).match(r);if(s&&s.length>0){return s[0].replace(/\\/g,"/")}}return undefined}t.getPackageName=getPackageName},216:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.normalizeWildcardRequire=t.normalizeDefaultRequire=void 0;function normalizeDefaultRequire(e){if(e&&e.__esModule)return e;return{default:e}}t.normalizeDefaultRequire=normalizeDefaultRequire;const r=Object.prototype.hasOwnProperty;function normalizeWildcardRequire(e){if(e&&e.__esModule)return e;const t={};for(const s in e){if(!r.call(e,s))continue;t[s]=e[s]}t["default"]=e;return t}t.normalizeWildcardRequire=normalizeWildcardRequire},2985:function(e,t,r){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.sharedLibEmit=void 0;const a=s(r(2037));const o=s(r(3535));const u=r(7468);let c="";switch(a.default.platform()){case"darwin":c="/**/*.@(dylib|so?(.*))";break;case"win32":c="/**/*.dll";break;default:c="/**/*.so?(.*)"}async function sharedLibEmit(e,t){const r=u.getPackageBase(e);if(!r)return;const s=await new Promise(((e,t)=>o.default(r+c,{ignore:r+"/**/node_modules/**/*"},((r,s)=>r?t(r):e(s)))));await Promise.all(s.map((r=>t.emitFile(r,"sharedlib",e))))}t.sharedLibEmit=sharedLibEmit},5735:function(e,t,r){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const a=r(1017);const o=s(r(2278));const u=r(7468);const c=r(552);const f={"@generated/photon"({id:e,emitAssetDirectory:t}){if(e.endsWith("@generated/photon/index.js")){t(a.resolve(a.dirname(e),"runtime/"))}},argon2({id:e,emitAssetDirectory:t}){if(e.endsWith("argon2/argon2.js")){t(a.resolve(a.dirname(e),"build","Release"));t(a.resolve(a.dirname(e),"prebuilds"));t(a.resolve(a.dirname(e),"lib","binding"))}},bull({id:e,emitAssetDirectory:t}){if(e.endsWith("bull/lib/commands/index.js")){t(a.resolve(a.dirname(e)))}},camaro({id:e,emitAsset:t}){if(e.endsWith("camaro/dist/camaro.js")){t(a.resolve(a.dirname(e),"camaro.wasm"))}},esbuild({id:e,emitAssetDirectory:t}){if(e.endsWith("esbuild/lib/main.js")){const r=a.resolve(e,"..","..","package.json");const s=JSON.parse(c.readFileSync(r,"utf8"));for(const r of Object.keys(s.optionalDependencies||{})){const s=a.resolve(e,"..","..","..",r);t(s)}}},"google-gax"({id:e,ast:t,emitAssetDirectory:r}){if(e.endsWith("google-gax/build/src/grpc.js")){for(const s of t.body){if(s.type==="VariableDeclaration"&&s.declarations[0].id.type==="Identifier"&&s.declarations[0].id.name==="googleProtoFilesDir"){r(a.resolve(a.dirname(e),"../../../google-proto-files"))}}}},oracledb({id:e,ast:t,emitAsset:r}){if(e.endsWith("oracledb/lib/oracledb.js")){for(const s of t.body){if(s.type==="ForStatement"&&"body"in s.body&&s.body.body&&Array.isArray(s.body.body)&&s.body.body[0]&&s.body.body[0].type==="TryStatement"&&s.body.body[0].block.body[0]&&s.body.body[0].block.body[0].type==="ExpressionStatement"&&s.body.body[0].block.body[0].expression.type==="AssignmentExpression"&&s.body.body[0].block.body[0].expression.operator==="="&&s.body.body[0].block.body[0].expression.left.type==="Identifier"&&s.body.body[0].block.body[0].expression.left.name==="oracledbCLib"&&s.body.body[0].block.body[0].expression.right.type==="CallExpression"&&s.body.body[0].block.body[0].expression.right.callee.type==="Identifier"&&s.body.body[0].block.body[0].expression.right.callee.name==="require"&&s.body.body[0].block.body[0].expression.right.arguments.length===1&&s.body.body[0].block.body[0].expression.right.arguments[0].type==="MemberExpression"&&s.body.body[0].block.body[0].expression.right.arguments[0].computed===true&&s.body.body[0].block.body[0].expression.right.arguments[0].object.type==="Identifier"&&s.body.body[0].block.body[0].expression.right.arguments[0].object.name==="binaryLocations"&&s.body.body[0].block.body[0].expression.right.arguments[0].property.type==="Identifier"&&s.body.body[0].block.body[0].expression.right.arguments[0].property.name==="i"){s.body.body[0].block.body[0].expression.right.arguments=[{type:"Literal",value:"_"}];const t=global._unit?"3.0.0":JSON.parse(c.readFileSync(e.slice(0,-15)+"package.json","utf8")).version;const o=Number(t.slice(0,t.indexOf(".")))>=4;const u="oracledb-"+(o?t:"abi"+process.versions.modules)+"-"+process.platform+"-"+process.arch+".node";r(a.resolve(e,"../../build/Release/"+u))}}}},"phantomjs-prebuilt"({id:e,emitAssetDirectory:t}){if(e.endsWith("phantomjs-prebuilt/lib/phantomjs.js")){t(a.resolve(a.dirname(e),"..","bin"))}},"remark-prism"({id:e,emitAssetDirectory:t}){const r="remark-prism/src/highlight.js";if(e.endsWith(r)){try{const s=e.slice(0,-r.length);t(a.resolve(s,"prismjs","components"))}catch(e){}}},semver({id:e,emitAsset:t}){if(e.endsWith("semver/index.js")){t(a.resolve(e.replace("index.js","preload.js")))}},"socket.io":async function({id:e,ast:t,job:r}){if(e.endsWith("socket.io/lib/index.js")){async function replaceResolvePathStatement(t){if(t.type==="ExpressionStatement"&&t.expression.type==="AssignmentExpression"&&t.expression.operator==="="&&t.expression.right.type==="CallExpression"&&t.expression.right.callee.type==="Identifier"&&t.expression.right.callee.name==="read"&&t.expression.right.arguments.length>=1&&t.expression.right.arguments[0].type==="CallExpression"&&t.expression.right.arguments[0].callee.type==="Identifier"&&t.expression.right.arguments[0].callee.name==="resolvePath"&&t.expression.right.arguments[0].arguments.length===1&&t.expression.right.arguments[0].arguments[0].type==="Literal"){const s=t.expression.right.arguments[0].arguments[0].value;let u;try{const t=await o.default(String(s),e,r);if(typeof t==="string"){u=t}else{return undefined}}catch(e){return undefined}const c="/"+a.relative(a.dirname(e),u);t.expression.right.arguments[0]={type:"BinaryExpression",start:t.expression.right.arguments[0].start,end:t.expression.right.arguments[0].end,operator:"+",left:{type:"Identifier",name:"__dirname"},right:{type:"Literal",value:c,raw:JSON.stringify(c)}}}return undefined}for(const e of t.body){if(e.type==="ExpressionStatement"&&e.expression.type==="AssignmentExpression"&&e.expression.operator==="="&&e.expression.left.type==="MemberExpression"&&e.expression.left.object.type==="MemberExpression"&&e.expression.left.object.object.type==="Identifier"&&e.expression.left.object.object.name==="Server"&&e.expression.left.object.property.type==="Identifier"&&e.expression.left.object.property.name==="prototype"&&e.expression.left.property.type==="Identifier"&&e.expression.left.property.name==="serveClient"&&e.expression.right.type==="FunctionExpression"){for(const t of e.expression.right.body.body){if(t.type==="IfStatement"&&t.consequent&&"body"in t.consequent&&t.consequent.body){const e=t.consequent.body;let r=false;if(Array.isArray(e)&&e[0]&&e[0].type==="ExpressionStatement"){r=await replaceResolvePathStatement(e[0])}if(Array.isArray(e)&&e[1]&&e[1].type==="TryStatement"&&e[1].block.body&&e[1].block.body[0]){r=await replaceResolvePathStatement(e[1].block.body[0])||r}return}}}}}},typescript({id:e,emitAssetDirectory:t}){if(e.endsWith("typescript/lib/tsc.js")){t(a.resolve(e,"../"))}},"uglify-es"({id:e,emitAsset:t}){if(e.endsWith("uglify-es/tools/node.js")){t(a.resolve(e,"../../lib/utils.js"));t(a.resolve(e,"../../lib/ast.js"));t(a.resolve(e,"../../lib/parse.js"));t(a.resolve(e,"../../lib/transform.js"));t(a.resolve(e,"../../lib/scope.js"));t(a.resolve(e,"../../lib/output.js"));t(a.resolve(e,"../../lib/compress.js"));t(a.resolve(e,"../../lib/sourcemap.js"));t(a.resolve(e,"../../lib/mozilla-ast.js"));t(a.resolve(e,"../../lib/propmangle.js"));t(a.resolve(e,"../../lib/minify.js"));t(a.resolve(e,"../exports.js"))}},"uglify-js"({id:e,emitAsset:t,emitAssetDirectory:r}){if(e.endsWith("uglify-js/tools/node.js")){r(a.resolve(e,"../../lib"));t(a.resolve(e,"../exports.js"))}},"playwright-core"({id:e,emitAsset:t}){if(e.endsWith("playwright-core/index.js")){t(a.resolve(a.dirname(e),"browsers.json"))}},"geo-tz"({id:e,emitAsset:t}){if(e.endsWith("geo-tz/dist/geo-tz.js")){t(a.resolve(a.dirname(e),"../data/geo.dat"))}}};async function handleSpecialCases({id:e,ast:t,emitAsset:r,emitAssetDirectory:s,job:a}){const o=u.getPackageName(e);const c=f[o||""];e=e.replace(/\\/g,"/");if(c)await c({id:e,ast:t,emitAsset:r,emitAssetDirectory:s,job:a})}t["default"]=handleSpecialCases},5401:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.wildcardRegEx=t.WILDCARD=t.FUNCTION=t.UNKNOWN=t.evaluate=void 0;const s=r(7310);async function evaluate(e,t={},r=true){const s={computeBranches:r,vars:t};return walk(e);function walk(e){const t=a[e.type];if(t){return t.call(s,e,walk)}return undefined}}t.evaluate=evaluate;t.UNKNOWN=Symbol();t.FUNCTION=Symbol();t.WILDCARD="";t.wildcardRegEx=/\x1a/g;function countWildcards(e){t.wildcardRegEx.lastIndex=0;let r=0;while(t.wildcardRegEx.exec(e))r++;return r}const a={ArrayExpression:async function ArrayExpression(e,t){const r=[];for(let s=0,a=e.elements.length;ss.value}}}return undefined},BinaryExpression:async function BinaryExpression(e,r){const s=e.operator;let a=await r(e.left);if(!a&&s!=="+")return;let o=await r(e.right);if(!a&&!o)return;if(!a){if(this.computeBranches&&o&&"value"in o&&typeof o.value==="string")return{value:t.WILDCARD+o.value,wildcards:[e.left,...o.wildcards||[]]};return}if(!o){if(this.computeBranches&&s==="+"){if(a&&"value"in a&&typeof a.value==="string")return{value:a.value+t.WILDCARD,wildcards:[...a.wildcards||[],e.right]}}if(!("test"in a)&&s==="||"&&a.value)return a;return}if("test"in a&&"value"in o){const e=o.value;if(s==="==")return{test:a.test,then:a.then==e,else:a.else==e};if(s==="===")return{test:a.test,then:a.then===e,else:a.else===e};if(s==="!=")return{test:a.test,then:a.then!=e,else:a.else!=e};if(s==="!==")return{test:a.test,then:a.then!==e,else:a.else!==e};if(s==="+")return{test:a.test,then:a.then+e,else:a.else+e};if(s==="-")return{test:a.test,then:a.then-e,else:a.else-e};if(s==="*")return{test:a.test,then:a.then*e,else:a.else*e};if(s==="/")return{test:a.test,then:a.then/e,else:a.else/e};if(s==="%")return{test:a.test,then:a.then%e,else:a.else%e};if(s==="<")return{test:a.test,then:a.then")return{test:a.test,then:a.then>e,else:a.else>e};if(s===">=")return{test:a.test,then:a.then>=e,else:a.else>=e};if(s==="|")return{test:a.test,then:a.then|e,else:a.else|e};if(s==="&")return{test:a.test,then:a.then&e,else:a.else&e};if(s==="^")return{test:a.test,then:a.then^e,else:a.else^e};if(s==="&&")return{test:a.test,then:a.then&&e,else:a.else&&e};if(s==="||")return{test:a.test,then:a.then||e,else:a.else||e}}else if("test"in o&&"value"in a){const e=a.value;if(s==="==")return{test:o.test,then:e==o.then,else:e==o.else};if(s==="===")return{test:o.test,then:e===o.then,else:e===o.else};if(s==="!=")return{test:o.test,then:e!=o.then,else:e!=o.else};if(s==="!==")return{test:o.test,then:e!==o.then,else:e!==o.else};if(s==="+")return{test:o.test,then:e+o.then,else:e+o.else};if(s==="-")return{test:o.test,then:e-o.then,else:e-o.else};if(s==="*")return{test:o.test,then:e*o.then,else:e*o.else};if(s==="/")return{test:o.test,then:e/o.then,else:e/o.else};if(s==="%")return{test:o.test,then:e%o.then,else:e%o.else};if(s==="<")return{test:o.test,then:e")return{test:o.test,then:e>o.then,else:e>o.else};if(s===">=")return{test:o.test,then:e>=o.then,else:e>=o.else};if(s==="|")return{test:o.test,then:e|o.then,else:e|o.else};if(s==="&")return{test:o.test,then:e&o.then,else:e&o.else};if(s==="^")return{test:o.test,then:e^o.then,else:e^o.else};if(s==="&&")return{test:o.test,then:e&&o.then,else:a&&o.else};if(s==="||")return{test:o.test,then:e||o.then,else:a||o.else}}else if("value"in a&&"value"in o){if(s==="==")return{value:a.value==o.value};if(s==="===")return{value:a.value===o.value};if(s==="!=")return{value:a.value!=o.value};if(s==="!==")return{value:a.value!==o.value};if(s==="+"){const e={value:a.value+o.value};let t=[];if("wildcards"in a&&a.wildcards){t=t.concat(a.wildcards)}if("wildcards"in o&&o.wildcards){t=t.concat(o.wildcards)}if(t.length>0){e.wildcards=t}return e}if(s==="-")return{value:a.value-o.value};if(s==="*")return{value:a.value*o.value};if(s==="/")return{value:a.value/o.value};if(s==="%")return{value:a.value%o.value};if(s==="<")return{value:a.value")return{value:a.value>o.value};if(s===">=")return{value:a.value>=o.value};if(s==="|")return{value:a.value|o.value};if(s==="&")return{value:a.value&o.value};if(s==="^")return{value:a.value^o.value};if(s==="&&")return{value:a.value&&o.value};if(s==="||")return{value:a.value||o.value}}return},CallExpression:async function CallExpression(e,r){var s;const a=await r(e.callee);if(!a||"test"in a)return;let o=a.value;if(typeof o==="object"&&o!==null)o=o[t.FUNCTION];if(typeof o!=="function")return;let u=null;if(e.callee.object){u=await r(e.callee.object);u=u&&"value"in u&&u.value?u.value:null}let c;let f=[];let p;let d=e.arguments.length>0&&((s=e.callee.property)===null||s===void 0?void 0:s.name)!=="concat";const h=[];for(let s=0,a=e.arguments.length;sh.push(e)))}else{if(!this.computeBranches)return;a={value:t.WILDCARD};h.push(e.arguments[s])}if("test"in a){if(h.length)return;if(c)return;c=a.test;p=f.concat([]);f.push(a.then);p.push(a.else)}else{f.push(a.value);if(p)p.push(a.value)}}if(d)return;try{const e=await o.apply(u,f);if(e===t.UNKNOWN)return;if(!c){if(h.length){if(typeof e!=="string"||countWildcards(e)!==h.length)return;return{value:e,wildcards:h}}return{value:e}}const r=await o.apply(u,p);if(e===t.UNKNOWN)return;return{test:c,then:e,else:r}}catch(e){return}},ConditionalExpression:async function ConditionalExpression(e,t){const r=await t(e.test);if(r&&"value"in r)return r.value?t(e.consequent):t(e.alternate);if(!this.computeBranches)return;const s=await t(e.consequent);if(!s||"wildcards"in s||"test"in s)return;const a=await t(e.alternate);if(!a||"wildcards"in a||"test"in a)return;return{test:e.test,then:s.value,else:a.value}},ExpressionStatement:async function ExpressionStatement(e,t){return t(e.expression)},Identifier:async function Identifier(e,t){if(Object.hasOwnProperty.call(this.vars,e.name))return this.vars[e.name];return undefined},Literal:async function Literal(e,t){return{value:e.value}},MemberExpression:async function MemberExpression(e,r){const s=await r(e.object);if(!s||"test"in s||typeof s.value==="function"){return undefined}if(e.property.type==="Identifier"){if(typeof s.value==="string"&&e.property.name==="concat"){return{value:{[t.FUNCTION]:(...e)=>s.value.concat(e)}}}if(typeof s.value==="object"&&s.value!==null){const a=s.value;if(e.computed){const o=await r(e.property);if(o&&"value"in o&&o.value){const e=a[o.value];if(e===t.UNKNOWN)return undefined;return{value:e}}if(!a[t.UNKNOWN]&&Object.keys(s).length===0){return{value:undefined}}}else if(e.property.name in a){const r=a[e.property.name];if(r===t.UNKNOWN)return undefined;return{value:r}}else if(a[t.UNKNOWN])return undefined}else{return{value:undefined}}}const a=await r(e.property);if(!a||"test"in a)return undefined;if(typeof s.value==="object"&&s.value!==null){if(a.value in s.value){const e=s.value[a.value];if(e===t.UNKNOWN)return undefined;return{value:e}}else if(s.value[t.UNKNOWN]){return undefined}}else{return{value:undefined}}return undefined},MetaProperty:async function MetaProperty(e){if(e.meta.name==="import"&&e.property.name==="meta")return{value:this.vars["import.meta"]};return undefined},NewExpression:async function NewExpression(e,t){const r=await t(e.callee);if(r&&"value"in r&&r.value===s.URL&&e.arguments.length){const r=await t(e.arguments[0]);if(!r)return undefined;let a=null;if(e.arguments[1]){a=await t(e.arguments[1]);if(!a||!("value"in a))return undefined}if("value"in r){if(a){try{return{value:new s.URL(r.value,a.value)}}catch(e){return undefined}}try{return{value:new s.URL(r.value)}}catch(e){return undefined}}else{const e=r.test;if(a){try{return{test:e,then:new s.URL(r.then,a.value),else:new s.URL(r.else,a.value)}}catch(e){return undefined}}try{return{test:e,then:new s.URL(r.then),else:new s.URL(r.else)}}catch(e){return undefined}}}return undefined},ObjectExpression:async function ObjectExpression(e,r){const s={};for(let a=0;a{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.handleWrappers=void 0;const s=r(7470);function isUndefinedOrVoid(e){return e.type==="Identifier"&&e.name==="undefined"||e.type==="UnaryExpression"&&e.operator==="void"&&e.argument.type==="Literal"&&e.argument.value===0}function handleWrappers(e){var t;let r;if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="UnaryExpression"&&e.body[0].expression.operator==="!"&&e.body[0].expression.argument.type==="CallExpression"&&e.body[0].expression.argument.callee.type==="FunctionExpression"&&e.body[0].expression.argument.arguments.length===1)r=e.body[0].expression.argument;else if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="CallExpression"&&e.body[0].expression.callee.type==="FunctionExpression"&&(e.body[0].expression.arguments.length===1||e.body[0].expression.arguments.length===0))r=e.body[0].expression;else if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="AssignmentExpression"&&e.body[0].expression.left.type==="MemberExpression"&&e.body[0].expression.left.object.type==="Identifier"&&e.body[0].expression.left.object.name==="module"&&e.body[0].expression.left.property.type==="Identifier"&&e.body[0].expression.left.property.name==="exports"&&e.body[0].expression.right.type==="CallExpression"&&e.body[0].expression.right.callee.type==="FunctionExpression"&&e.body[0].expression.right.arguments.length===1)r=e.body[0].expression.right;if(r){let e;let a;if(r.arguments[0]&&r.arguments[0].type==="ConditionalExpression"&&r.arguments[0].test.type==="LogicalExpression"&&r.arguments[0].test.operator==="&&"&&r.arguments[0].test.left.type==="BinaryExpression"&&r.arguments[0].test.left.operator==="==="&&r.arguments[0].test.left.left.type==="UnaryExpression"&&r.arguments[0].test.left.left.operator==="typeof"&&"name"in r.arguments[0].test.left.left.argument&&r.arguments[0].test.left.left.argument.name==="define"&&r.arguments[0].test.left.right.type==="Literal"&&r.arguments[0].test.left.right.value==="function"&&r.arguments[0].test.right.type==="MemberExpression"&&r.arguments[0].test.right.object.type==="Identifier"&&r.arguments[0].test.right.property.type==="Identifier"&&r.arguments[0].test.right.property.name==="amd"&&r.arguments[0].test.right.computed===false&&r.arguments[0].alternate.type==="FunctionExpression"&&r.arguments[0].alternate.params.length===1&&r.arguments[0].alternate.params[0].type==="Identifier"&&r.arguments[0].alternate.body.body.length===1&&r.arguments[0].alternate.body.body[0].type==="ExpressionStatement"&&r.arguments[0].alternate.body.body[0].expression.type==="AssignmentExpression"&&r.arguments[0].alternate.body.body[0].expression.left.type==="MemberExpression"&&r.arguments[0].alternate.body.body[0].expression.left.object.type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.left.object.name==="module"&&r.arguments[0].alternate.body.body[0].expression.left.property.type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.left.property.name==="exports"&&r.arguments[0].alternate.body.body[0].expression.left.computed===false&&r.arguments[0].alternate.body.body[0].expression.right.type==="CallExpression"&&r.arguments[0].alternate.body.body[0].expression.right.callee.type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.right.callee.name===r.arguments[0].alternate.params[0].name&&"body"in r.callee&&"body"in r.callee.body&&Array.isArray(r.callee.body.body)&&r.arguments[0].alternate.body.body[0].expression.right.arguments.length===1&&r.arguments[0].alternate.body.body[0].expression.right.arguments[0].type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.right.arguments[0].name==="require"){let e=r.callee.body.body;if(e[0].type==="ExpressionStatement"&&e[0].expression.type==="Literal"&&e[0].expression.value==="use strict"){e=e.slice(1)}if(e.length===1&&e[0].type==="ExpressionStatement"&&e[0].expression.type==="CallExpression"&&e[0].expression.callee.type==="Identifier"&&e[0].expression.callee.name===r.arguments[0].test.right.object.name&&e[0].expression.arguments.length===1&&e[0].expression.arguments[0].type==="FunctionExpression"&&e[0].expression.arguments[0].params.length===1&&e[0].expression.arguments[0].params[0].type==="Identifier"&&e[0].expression.arguments[0].params[0].name==="require"){const t=e[0].expression.arguments[0];t.params=[];try{delete t.scope.declarations.require}catch(e){}}}else if(r.arguments[0]&&r.arguments[0].type==="FunctionExpression"&&r.arguments[0].params.length===0&&(r.arguments[0].body.body.length===1||r.arguments[0].body.body.length===2&&r.arguments[0].body.body[0].type==="VariableDeclaration"&&r.arguments[0].body.body[0].declarations.length===3&&r.arguments[0].body.body[0].declarations.every((e=>e.init===null&&e.id.type==="Identifier")))&&r.arguments[0].body.body[r.arguments[0].body.body.length-1].type==="ReturnStatement"&&(e=r.arguments[0].body.body[r.arguments[0].body.body.length-1])&&((t=e.argument)===null||t===void 0?void 0:t.type)==="CallExpression"&&e.argument.arguments.length&&e.argument.arguments.every((e=>e&&e.type==="Literal"&&typeof e.value==="number"))&&e.argument.callee.type==="CallExpression"&&(e.argument.callee.callee.type==="FunctionExpression"||e.argument.callee.callee.type==="CallExpression"&&e.argument.callee.callee.callee.type==="FunctionExpression"&&e.argument.callee.callee.arguments.length===0)&&e.argument.callee.arguments.length===3&&e.argument.callee.arguments[0].type==="ObjectExpression"&&e.argument.callee.arguments[1].type==="ObjectExpression"&&e.argument.callee.arguments[2].type==="ArrayExpression"){const t=e.argument.callee.arguments[0].properties;const r={};if(t.every((e=>{if(e.type!=="Property"||e.computed!==false||e.key.type!=="Literal"||typeof e.key.value!=="number"||e.value.type!=="ArrayExpression"||e.value.elements.length!==2||!e.value.elements[0]||!e.value.elements[1]||e.value.elements[0].type!=="FunctionExpression"||e.value.elements[1].type!=="ObjectExpression"){return false}const t=e.value.elements[1].properties;for(const e of t){if(e.type!=="Property"||e.value.type!=="Identifier"&&e.value.type!=="Literal"&&!isUndefinedOrVoid(e.value)||!(e.key.type==="Literal"&&typeof e.key.value==="string"||e.key.type==="Identifier")||e.computed){return false}if(isUndefinedOrVoid(e.value)){if(e.key.type==="Identifier"){r[e.key.name]={type:"Literal",start:e.key.start,end:e.key.end,value:e.key.name,raw:JSON.stringify(e.key.name)}}else if(e.key.type==="Literal"){r[String(e.key.value)]=e.key}}}return true}))){const t=Object.keys(r);const s=e.argument.callee.arguments[1];s.properties=t.map((e=>({type:"Property",method:false,shorthand:false,computed:false,kind:"init",key:r[e],value:{type:"ObjectExpression",properties:[{type:"Property",kind:"init",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"exports"},value:{type:"CallExpression",optional:false,callee:{type:"Identifier",name:"require"},arguments:[r[e]]}}]}})))}}else if(r.arguments[0]&&r.arguments[0].type==="FunctionExpression"&&r.arguments[0].params.length===2&&r.arguments[0].params[0].type==="Identifier"&&r.arguments[0].params[1].type==="Identifier"&&"body"in r.callee&&"body"in r.callee.body&&Array.isArray(r.callee.body.body)&&r.callee.body.body.length===1){const e=r.callee.body.body[0];if(e.type==="IfStatement"&&e.test.type==="LogicalExpression"&&e.test.operator==="&&"&&e.test.left.type==="BinaryExpression"&&e.test.left.left.type==="UnaryExpression"&&e.test.left.left.operator==="typeof"&&e.test.left.left.argument.type==="Identifier"&&e.test.left.left.argument.name==="module"&&e.test.left.right.type==="Literal"&&e.test.left.right.value==="object"&&e.test.right.type==="BinaryExpression"&&e.test.right.left.type==="UnaryExpression"&&e.test.right.left.operator==="typeof"&&e.test.right.left.argument.type==="MemberExpression"&&e.test.right.left.argument.object.type==="Identifier"&&e.test.right.left.argument.object.name==="module"&&e.test.right.left.argument.property.type==="Identifier"&&e.test.right.left.argument.property.name==="exports"&&e.test.right.right.type==="Literal"&&e.test.right.right.value==="object"&&e.consequent.type==="BlockStatement"&&e.consequent.body.length>0){let t;if(e.consequent.body[0].type==="VariableDeclaration"&&e.consequent.body[0].declarations[0].init&&e.consequent.body[0].declarations[0].init.type==="CallExpression")t=e.consequent.body[0].declarations[0].init;else if(e.consequent.body[0].type==="ExpressionStatement"&&e.consequent.body[0].expression.type==="CallExpression")t=e.consequent.body[0].expression;else if(e.consequent.body[0].type==="ExpressionStatement"&&e.consequent.body[0].expression.type==="AssignmentExpression"&&e.consequent.body[0].expression.operator==="="&&e.consequent.body[0].expression.right.type==="CallExpression")t=e.consequent.body[0].expression.right;if(t&&t.callee.type==="Identifier"&&"params"in r.callee&&r.callee.params.length>0&&"name"in r.callee.params[0]&&t.callee.name===r.callee.params[0].name&&t.arguments.length===2&&t.arguments[0].type==="Identifier"&&t.arguments[0].name==="require"&&t.arguments[1].type==="Identifier"&&t.arguments[1].name==="exports"){const e=r.arguments[0];e.params=[];try{const t=e.scope;delete t.declarations.require;delete t.declarations.exports}catch(e){}}}}else if(r.callee.type==="FunctionExpression"&&r.callee.body.body.length>2&&r.callee.body.body[0].type==="VariableDeclaration"&&r.callee.body.body[0].declarations.length===1&&r.callee.body.body[0].declarations[0].type==="VariableDeclarator"&&r.callee.body.body[0].declarations[0].id.type==="Identifier"&&r.callee.body.body[0].declarations[0].init&&(r.callee.body.body[0].declarations[0].init.type==="ObjectExpression"&&r.callee.body.body[0].declarations[0].init.properties.length===0||r.callee.body.body[0].declarations[0].init.type==="CallExpression"&&r.callee.body.body[0].declarations[0].init.arguments.length===1)&&(r.callee.body.body[1]&&r.callee.body.body[1].type==="FunctionDeclaration"&&r.callee.body.body[1].params.length===1&&r.callee.body.body[1].body.body.length>=3||r.callee.body.body[2]&&r.callee.body.body[2].type==="FunctionDeclaration"&&r.callee.body.body[2].params.length===1&&r.callee.body.body[2].body.body.length>=3)&&(r.arguments[0]&&(r.arguments[0].type==="ArrayExpression"&&(a=r.arguments[0])&&r.arguments[0].elements.length>0&&r.arguments[0].elements.every((e=>e&&e.type==="FunctionExpression"))||r.arguments[0].type==="ObjectExpression"&&(a=r.arguments[0])&&r.arguments[0].properties&&r.arguments[0].properties.length>0&&r.arguments[0].properties.every((e=>e&&e.type==="Property"&&!e.computed&&e.key&&e.key.type==="Literal"&&(typeof e.key.value==="string"||typeof e.key.value==="number")&&e.value&&e.value.type==="FunctionExpression"))))||r.arguments.length===0&&r.callee.type==="FunctionExpression"&&r.callee.params.length===0&&r.callee.body.type==="BlockStatement"&&r.callee.body.body.length>5&&r.callee.body.body[0].type==="VariableDeclaration"&&r.callee.body.body[0].declarations.length===1&&r.callee.body.body[0].declarations[0].id.type==="Identifier"&&r.callee.body.body[1].type==="ExpressionStatement"&&r.callee.body.body[1].expression.type==="AssignmentExpression"&&r.callee.body.body[2].type==="ExpressionStatement"&&r.callee.body.body[2].expression.type==="AssignmentExpression"&&r.callee.body.body[3].type==="ExpressionStatement"&&r.callee.body.body[3].expression.type==="AssignmentExpression"&&r.callee.body.body[3].expression.left.type==="MemberExpression"&&r.callee.body.body[3].expression.left.object.type==="Identifier"&&r.callee.body.body[3].expression.left.object.name===r.callee.body.body[0].declarations[0].id.name&&r.callee.body.body[3].expression.left.property.type==="Identifier"&&r.callee.body.body[3].expression.left.property.name==="modules"&&r.callee.body.body[3].expression.right.type==="ObjectExpression"&&r.callee.body.body[3].expression.right.properties.every((e=>e&&e.type==="Property"&&!e.computed&&e.key&&e.key.type==="Literal"&&(typeof e.key.value==="string"||typeof e.key.value==="number")&&e.value&&e.value.type==="FunctionExpression"))&&(a=r.callee.body.body[3].expression.right)&&(r.callee.body.body[4].type==="VariableDeclaration"&&r.callee.body.body[4].declarations.length===1&&r.callee.body.body[4].declarations[0].init&&r.callee.body.body[4].declarations[0].init.type==="CallExpression"&&r.callee.body.body[4].declarations[0].init.callee.type==="Identifier"&&r.callee.body.body[4].declarations[0].init.callee.name==="require"||r.callee.body.body[5].type==="VariableDeclaration"&&r.callee.body.body[5].declarations.length===1&&r.callee.body.body[5].declarations[0].init&&r.callee.body.body[5].declarations[0].init.type==="CallExpression"&&r.callee.body.body[5].declarations[0].init.callee.type==="Identifier"&&r.callee.body.body[5].declarations[0].init.callee.name==="require")){const e=new Map;let t;if(a.type==="ArrayExpression")t=a.elements.filter((e=>(e===null||e===void 0?void 0:e.type)==="FunctionExpression")).map(((e,t)=>[String(t),e]));else t=a.properties.map((e=>[String(e.key.value),e.value]));for(const[r,s]of t){const t=s.body.body.length===1?s.body.body[0]:(s.body.body.length===2||s.body.body.length===3&&s.body.body[2].type==="EmptyStatement")&&s.body.body[0].type==="ExpressionStatement"&&s.body.body[0].expression.type==="Literal"&&s.body.body[0].expression.value==="use strict"?s.body.body[1]:null;if(t&&t.type==="ExpressionStatement"&&t.expression.type==="AssignmentExpression"&&t.expression.operator==="="&&t.expression.left.type==="MemberExpression"&&t.expression.left.object.type==="Identifier"&&"params"in s&&s.params.length>0&&"name"in s.params[0]&&t.expression.left.object.name===s.params[0].name&&t.expression.left.property.type==="Identifier"&&t.expression.left.property.name==="exports"&&t.expression.right.type==="CallExpression"&&t.expression.right.callee.type==="Identifier"&&t.expression.right.callee.name==="require"&&t.expression.right.arguments.length===1&&t.expression.right.arguments[0].type==="Literal"){e.set(r,t.expression.right.arguments[0].value)}}for(const[,r]of t){if("params"in r&&r.params.length===3&&r.params[2].type==="Identifier"){const t=new Map;s.walk(r.body,{enter(s,a){const o=s;const u=a;if(o.type==="CallExpression"&&o.callee.type==="Identifier"&&"name"in r.params[2]&&o.callee.name===r.params[2].name&&o.arguments.length===1&&o.arguments[0].type==="Literal"){const r=e.get(String(o.arguments[0].value));if(r){const e={type:"CallExpression",optional:false,callee:{type:"Identifier",name:"require"},arguments:[{type:"Literal",value:r}]};const s=u;if("right"in s&&s.right===o){s.right=e}else if("left"in s&&s.left===o){s.left=e}else if("object"in s&&s.object===o){s.object=e}else if("callee"in s&&s.callee===o){s.callee=e}else if("arguments"in s&&s.arguments.some((e=>e===o))){s.arguments=s.arguments.map((t=>t===o?e:t))}else if("init"in s&&s.init===o){if(s.type==="VariableDeclarator"&&s.id.type==="Identifier")t.set(s.id.name,r);s.init=e}}}else if(o.type==="CallExpression"&&o.callee.type==="MemberExpression"&&o.callee.object.type==="Identifier"&&"name"in r.params[2]&&o.callee.object.name===r.params[2].name&&o.callee.property.type==="Identifier"&&o.callee.property.name==="n"&&o.arguments.length===1&&o.arguments[0].type==="Identifier"){if(u&&"init"in u&&u.init===o){const e=o.arguments[0];const t={type:"CallExpression",optional:false,callee:{type:"MemberExpression",computed:false,optional:false,object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"assign"}},arguments:[{type:"ArrowFunctionExpression",expression:true,params:[],body:e},{type:"ObjectExpression",properties:[{type:"Property",kind:"init",method:false,computed:false,shorthand:false,key:{type:"Identifier",name:"a"},value:e}]}]};u.init=t}}}})}}}}}t.handleWrappers=handleWrappers},5920:(e,t)=>{e.exports=t=abbrev.abbrev=abbrev;abbrev.monkeyPatch=monkeyPatch;function monkeyPatch(){Object.defineProperty(Array.prototype,"abbrev",{value:function(){return abbrev(this)},enumerable:false,configurable:true,writable:true});Object.defineProperty(Object.prototype,"abbrev",{value:function(){return abbrev(Object.keys(this))},enumerable:false,configurable:true,writable:true})}function abbrev(e){if(arguments.length!==1||!Array.isArray(e)){e=Array.prototype.slice.call(arguments,0)}for(var t=0,r=e.length,s=[];tt?1:-1}},5534:e=>{"use strict";function isArguments(e){return e!=null&&typeof e==="object"&&e.hasOwnProperty("callee")}var t={"*":{label:"any",check:function(){return true}},A:{label:"array",check:function(e){return Array.isArray(e)||isArguments(e)}},S:{label:"string",check:function(e){return typeof e==="string"}},N:{label:"number",check:function(e){return typeof e==="number"}},F:{label:"function",check:function(e){return typeof e==="function"}},O:{label:"object",check:function(e){return typeof e==="object"&&e!=null&&!t.A.check(e)&&!t.E.check(e)}},B:{label:"boolean",check:function(e){return typeof e==="boolean"}},E:{label:"error",check:function(e){return e instanceof Error}},Z:{label:"null",check:function(e){return e==null}}};function addSchema(e,t){var r=t[e.length]=t[e.length]||[];if(r.indexOf(e)===-1)r.push(e)}var r=e.exports=function(e,r){if(arguments.length!==2)throw wrongNumberOfArgs(["SA"],arguments.length);if(!e)throw missingRequiredArg(0,"rawSchemas");if(!r)throw missingRequiredArg(1,"args");if(!t.S.check(e))throw invalidType(0,["string"],e);if(!t.A.check(r))throw invalidType(1,["array"],r);var s=e.split("|");var a={};s.forEach((function(e){for(var r=0;r{"use strict";t.TrackerGroup=r(2952);t.Tracker=r(6189);t.TrackerStream=r(5849)},8313:(e,t,r)=>{"use strict";var s=r(2361).EventEmitter;var a=r(3837);var o=0;var u=e.exports=function(e){s.call(this);this.id=++o;this.name=e};a.inherits(u,s)},2952:(e,t,r)=>{"use strict";var s=r(3837);var a=r(8313);var o=r(6189);var u=r(5849);var c=e.exports=function(e){a.call(this,e);this.parentGroup=null;this.trackers=[];this.completion={};this.weight={};this.totalWeight=0;this.finished=false;this.bubbleChange=bubbleChange(this)};s.inherits(c,a);function bubbleChange(e){return function(t,r,s){e.completion[s.id]=r;if(e.finished)return;e.emit("change",t||e.name,e.completed(),e)}}c.prototype.nameInTree=function(){var e=[];var t=this;while(t){e.unshift(t.name);t=t.parentGroup}return e.join("/")};c.prototype.addUnit=function(e,t){if(e.addUnit){var r=this;while(r){if(e===r){throw new Error("Attempted to add tracker group "+e.name+" to tree that already includes it "+this.nameInTree(this))}r=r.parentGroup}e.parentGroup=this}this.weight[e.id]=t||1;this.totalWeight+=this.weight[e.id];this.trackers.push(e);this.completion[e.id]=e.completed();e.on("change",this.bubbleChange);if(!this.finished)this.emit("change",e.name,this.completion[e.id],e);return e};c.prototype.completed=function(){if(this.trackers.length===0)return 0;var e=1/this.totalWeight;var t=0;for(var r=0;r{"use strict";var s=r(3837);var a=r(675);var o=r(1722);var u=r(6189);var c=e.exports=function(e,t,r){a.Transform.call(this,r);this.tracker=new u(e,t);this.name=e;this.id=this.tracker.id;this.tracker.on("change",delegateChange(this))};s.inherits(c,a.Transform);function delegateChange(e){return function(t,r,s){e.emit("change",t,r,e)}}c.prototype._transform=function(e,t,r){this.tracker.completeWork(e.length?e.length:1);this.push(e);r()};c.prototype._flush=function(e){this.tracker.finish();e()};o(c.prototype,"tracker").method("completed").method("addWork").method("finish")},6189:(e,t,r)=>{"use strict";var s=r(3837);var a=r(8313);var o=e.exports=function(e,t){a.call(this,e);this.workDone=0;this.workTodo=t||0};s.inherits(o,a);o.prototype.completed=function(){return this.workTodo===0?0:this.workDone/this.workTodo};o.prototype.addWork=function(e){this.workTodo+=e;this.emit("change",this.name,this.completed(),this)};o.prototype.completeWork=function(e){this.workDone+=e;if(this.workDone>this.workTodo)this.workDone=this.workTodo;this.emit("change",this.name,this.completed(),this)};o.prototype.finish=function(){this.workTodo=this.workDone=1;this.emit("change",this.name,1,this)}},5706:(module,exports,__nccwpck_require__)=>{var fs=__nccwpck_require__(7147),path=__nccwpck_require__(1017),fileURLToPath=__nccwpck_require__(9001),join=path.join,dirname=path.dirname,exists=fs.accessSync&&function(e){try{fs.accessSync(e)}catch(e){return false}return true}||fs.existsSync||path.existsSync,defaults={arrow:process.env.NODE_BINDINGS_ARROW||" → ",compiled:process.env.NODE_BINDINGS_COMPILED_DIR||"compiled",platform:process.platform,arch:process.arch,nodePreGyp:"node-v"+process.versions.modules+"-"+process.platform+"-"+process.arch,version:process.versions.node,bindings:"bindings.node",try:[["module_root","build","bindings"],["module_root","build","Debug","bindings"],["module_root","build","Release","bindings"],["module_root","out","Debug","bindings"],["module_root","Debug","bindings"],["module_root","out","Release","bindings"],["module_root","Release","bindings"],["module_root","build","default","bindings"],["module_root","compiled","version","platform","arch","bindings"],["module_root","addon-build","release","install-root","bindings"],["module_root","addon-build","debug","install-root","bindings"],["module_root","addon-build","default","install-root","bindings"],["module_root","lib","binding","nodePreGyp","bindings"]]};function bindings(opts){if(typeof opts=="string"){opts={bindings:opts}}else if(!opts){opts={}}Object.keys(defaults).map((function(e){if(!(e in opts))opts[e]=defaults[e]}));if(!opts.module_root){opts.module_root=exports.getRoot(exports.getFileName())}if(path.extname(opts.bindings)!=".node"){opts.bindings+=".node"}var requireFunc=true?eval("require"):0;var tries=[],i=0,l=opts.try.length,n,b,err;for(;i{"use strict";e.exports=function(e,t){if(e===null||e===undefined){throw TypeError()}e=String(e);var r=e.length;var s=t?Number(t):0;if(Number.isNaN(s)){s=0}if(s<0||s>=r){return undefined}var a=e.charCodeAt(s);if(a>=55296&&a<=56319&&r>s+1){var o=e.charCodeAt(s+1);if(o>=56320&&o<=57343){return(a-55296)*1024+o-56320+65536}}return a}},6322:(e,t)=>{"use strict";var r="[";t.up=function up(e){return r+(e||"")+"A"};t.down=function down(e){return r+(e||"")+"B"};t.forward=function forward(e){return r+(e||"")+"C"};t.back=function back(e){return r+(e||"")+"D"};t.nextLine=function nextLine(e){return r+(e||"")+"E"};t.previousLine=function previousLine(e){return r+(e||"")+"F"};t.horizontalAbsolute=function horizontalAbsolute(e){if(e==null)throw new Error("horizontalAboslute requires a column to position to");return r+e+"G"};t.eraseData=function eraseData(){return r+"J"};t.eraseLine=function eraseLine(){return r+"K"};t.goto=function(e,t){return r+t+";"+e+"H"};t.gotoSOL=function(){return"\r"};t.beep=function(){return""};t.hideCursor=function hideCursor(){return r+"?25l"};t.showCursor=function showCursor(){return r+"?25h"};var s={reset:0,bold:1,italic:3,underline:4,inverse:7,stopBold:22,stopItalic:23,stopUnderline:24,stopInverse:27,white:37,black:30,blue:34,cyan:36,green:32,magenta:35,red:31,yellow:33,bgWhite:47,bgBlack:40,bgBlue:44,bgCyan:46,bgGreen:42,bgMagenta:45,bgRed:41,bgYellow:43,grey:90,brightBlack:90,brightRed:91,brightGreen:92,brightYellow:93,brightBlue:94,brightMagenta:95,brightCyan:96,brightWhite:97,bgGrey:100,bgBrightBlack:100,bgBrightRed:101,bgBrightGreen:102,bgBrightYellow:103,bgBrightBlue:104,bgBrightMagenta:105,bgBrightCyan:106,bgBrightWhite:107};t.color=function color(e){if(arguments.length!==1||!Array.isArray(e)){e=Array.prototype.slice.call(arguments)}return r+e.map(colorNameToCode).join(";")+"m"};function colorNameToCode(e){if(s[e]!=null)return s[e];throw new Error("Unknown color or style name: "+e)}},3487:(e,t)=>{function isArray(e){if(Array.isArray){return Array.isArray(e)}return objectToString(e)==="[object Array]"}t.isArray=isArray;function isBoolean(e){return typeof e==="boolean"}t.isBoolean=isBoolean;function isNull(e){return e===null}t.isNull=isNull;function isNullOrUndefined(e){return e==null}t.isNullOrUndefined=isNullOrUndefined;function isNumber(e){return typeof e==="number"}t.isNumber=isNumber;function isString(e){return typeof e==="string"}t.isString=isString;function isSymbol(e){return typeof e==="symbol"}t.isSymbol=isSymbol;function isUndefined(e){return e===void 0}t.isUndefined=isUndefined;function isRegExp(e){return objectToString(e)==="[object RegExp]"}t.isRegExp=isRegExp;function isObject(e){return typeof e==="object"&&e!==null}t.isObject=isObject;function isDate(e){return objectToString(e)==="[object Date]"}t.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}t.isError=isError;function isFunction(e){return typeof e==="function"}t.isFunction=isFunction;function isPrimitive(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}t.isPrimitive=isPrimitive;t.isBuffer=Buffer.isBuffer;function objectToString(e){return Object.prototype.toString.call(e)}},1722:e=>{e.exports=Delegator;function Delegator(e,t){if(!(this instanceof Delegator))return new Delegator(e,t);this.proto=e;this.target=t;this.methods=[];this.getters=[];this.setters=[];this.fluents=[]}Delegator.prototype.method=function(e){var t=this.proto;var r=this.target;this.methods.push(e);t[e]=function(){return this[r][e].apply(this[r],arguments)};return this};Delegator.prototype.access=function(e){return this.getter(e).setter(e)};Delegator.prototype.getter=function(e){var t=this.proto;var r=this.target;this.getters.push(e);t.__defineGetter__(e,(function(){return this[r][e]}));return this};Delegator.prototype.setter=function(e){var t=this.proto;var r=this.target;this.setters.push(e);t.__defineSetter__(e,(function(t){return this[r][e]=t}));return this};Delegator.prototype.fluent=function(e){var t=this.proto;var r=this.target;this.fluents.push(e);t[e]=function(t){if("undefined"!=typeof t){this[r][e]=t;return this}else{return this[r][e]}};return this}},2157:(e,t,r)=>{"use strict";var s=r(2037).platform();var a=r(2081).spawnSync;var o=r(7147).readdirSync;var u="glibc";var c="musl";var f={encoding:"utf8",env:process.env};if(!a){a=function(){return{status:126,stdout:"",stderr:""}}}function contains(e){return function(t){return t.indexOf(e)!==-1}}function versionFromMuslLdd(e){return e.split(/[\r\n]+/)[1].trim().split(/\s/)[1]}function safeReaddirSync(e){try{return o(e)}catch(e){}return[]}var p="";var d="";var h="";if(s==="linux"){var v=a("getconf",["GNU_LIBC_VERSION"],f);if(v.status===0){p=u;d=v.stdout.trim().split(" ")[1];h="getconf"}else{var g=a("ldd",["--version"],f);if(g.status===0&&g.stdout.indexOf(c)!==-1){p=c;d=versionFromMuslLdd(g.stdout);h="ldd"}else if(g.status===1&&g.stderr.indexOf(c)!==-1){p=c;d=versionFromMuslLdd(g.stderr);h="ldd"}else{var m=safeReaddirSync("/lib");if(m.some(contains("-linux-gnu"))){p=u;h="filesystem"}else if(m.some(contains("libc.musl-"))){p=c;h="filesystem"}else if(m.some(contains("ld-musl-"))){p=c;h="filesystem"}else{var _=safeReaddirSync("/usr/sbin");if(_.some(contains("glibc"))){p=u;h="filesystem"}}}}}var y=p!==""&&p!==u;e.exports={GLIBC:u,MUSL:c,family:p,version:d,method:h,isNonGlibcLinux:y}},9001:(e,t,r)=>{var s=r(1017).sep||"/";e.exports=fileUriToPath;function fileUriToPath(e){if("string"!=typeof e||e.length<=7||"file://"!=e.substring(0,7)){throw new TypeError("must pass in a file:// URI to convert to a file path")}var t=decodeURI(e.substring(7));var r=t.indexOf("/");var a=t.substring(0,r);var o=t.substring(r+1);if("localhost"==a)a="";if(a){a=s+s+a}o=o.replace(/^(.+)\|/,"$1:");if(s=="\\"){o=o.replace(/\//g,"\\")}if(/^.+\:/.test(o)){}else{o=s+o}return a+o}},1271:(e,t,r)=>{"use strict";var s=r(1021);var a=r(5791);e.exports={activityIndicator:function(e,t,r){if(e.spun==null)return;return s(t,e.spun)},progressbar:function(e,t,r){if(e.completed==null)return;return a(t,r,e.completed)}}},2479:(e,t,r)=>{"use strict";var s=r(3837);var a=t.User=function User(e){var t=new Error(e);Error.captureStackTrace(t,User);t.code="EGAUGE";return t};t.MissingTemplateValue=function MissingTemplateValue(e,t){var r=new a(s.format('Missing template value "%s"',e.type));Error.captureStackTrace(r,MissingTemplateValue);r.template=e;r.values=t;return r};t.Internal=function Internal(e){var t=new Error(e);Error.captureStackTrace(t,Internal);t.code="EGAUGEINTERNAL";return t}},3278:e=>{"use strict";e.exports=isWin32()||isColorTerm();function isWin32(){return process.platform==="win32"}function isColorTerm(){var e=/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i;return!!process.env.COLORTERM||e.test(process.env.TERM)}},6054:(e,t,r)=>{"use strict";var s=r(4708);var a=r(7963);var o=r(3278);var u=r(2028);var c=r(7987);var f=r(75);var p=r(9186);var d=r(6401);e.exports=Gauge;function callWith(e,t){return function(){return t.call(e)}}function Gauge(e,t){var r,a;if(e&&e.write){a=e;r=t||{}}else if(t&&t.write){a=t;r=e||{}}else{a=p.stderr;r=e||t||{}}this._status={spun:0,section:"",subsection:""};this._paused=false;this._disabled=true;this._showing=false;this._onScreen=false;this._needsRedraw=false;this._hideCursor=r.hideCursor==null?true:r.hideCursor;this._fixedFramerate=r.fixedFramerate==null?!/^v0\.8\./.test(p.version):r.fixedFramerate;this._lastUpdateAt=null;this._updateInterval=r.updateInterval==null?50:r.updateInterval;this._themes=r.themes||c;this._theme=r.theme;var o=this._computeTheme(r.theme);var u=r.template||[{type:"progressbar",length:20},{type:"activityIndicator",kerning:1,length:1},{type:"section",kerning:1,default:""},{type:"subsection",kerning:1,default:""}];this.setWriteTo(a,r.tty);var f=r.Plumbing||s;this._gauge=new f(o,u,this.getWidth());this._$$doRedraw=callWith(this,this._doRedraw);this._$$handleSizeChange=callWith(this,this._handleSizeChange);this._cleanupOnExit=r.cleanupOnExit==null||r.cleanupOnExit;this._removeOnExit=null;if(r.enabled||r.enabled==null&&this._tty&&this._tty.isTTY){this.enable()}else{this.disable()}}Gauge.prototype={};Gauge.prototype.isEnabled=function(){return!this._disabled};Gauge.prototype.setTemplate=function(e){this._gauge.setTemplate(e);if(this._showing)this._requestRedraw()};Gauge.prototype._computeTheme=function(e){if(!e)e={};if(typeof e==="string"){e=this._themes.getTheme(e)}else if(e&&(Object.keys(e).length===0||e.hasUnicode!=null||e.hasColor!=null)){var t=e.hasUnicode==null?a():e.hasUnicode;var r=e.hasColor==null?o:e.hasColor;e=this._themes.getDefault({hasUnicode:t,hasColor:r,platform:e.platform})}return e};Gauge.prototype.setThemeset=function(e){this._themes=e;this.setTheme(this._theme)};Gauge.prototype.setTheme=function(e){this._gauge.setTheme(this._computeTheme(e));if(this._showing)this._requestRedraw();this._theme=e};Gauge.prototype._requestRedraw=function(){this._needsRedraw=true;if(!this._fixedFramerate)this._doRedraw()};Gauge.prototype.getWidth=function(){return(this._tty&&this._tty.columns||80)-1};Gauge.prototype.setWriteTo=function(e,t){var r=!this._disabled;if(r)this.disable();this._writeTo=e;this._tty=t||e===p.stderr&&p.stdout.isTTY&&p.stdout||e.isTTY&&e||this._tty;if(this._gauge)this._gauge.setWidth(this.getWidth());if(r)this.enable()};Gauge.prototype.enable=function(){if(!this._disabled)return;this._disabled=false;if(this._tty)this._enableEvents();if(this._showing)this.show()};Gauge.prototype.disable=function(){if(this._disabled)return;if(this._showing){this._lastUpdateAt=null;this._showing=false;this._doRedraw();this._showing=true}this._disabled=true;if(this._tty)this._disableEvents()};Gauge.prototype._enableEvents=function(){if(this._cleanupOnExit){this._removeOnExit=u(callWith(this,this.disable))}this._tty.on("resize",this._$$handleSizeChange);if(this._fixedFramerate){this.redrawTracker=f(this._$$doRedraw,this._updateInterval);if(this.redrawTracker.unref)this.redrawTracker.unref()}};Gauge.prototype._disableEvents=function(){this._tty.removeListener("resize",this._$$handleSizeChange);if(this._fixedFramerate)clearInterval(this.redrawTracker);if(this._removeOnExit)this._removeOnExit()};Gauge.prototype.hide=function(e){if(this._disabled)return e&&p.nextTick(e);if(!this._showing)return e&&p.nextTick(e);this._showing=false;this._doRedraw();e&&d(e)};Gauge.prototype.show=function(e,t){this._showing=true;if(typeof e==="string"){this._status.section=e}else if(typeof e==="object"){var r=Object.keys(e);for(var s=0;s{"use strict";var s=r(8753);e.exports=function(e){if(s(e)){return false}if(e>=4352&&(e<=4447||9001===e||9002===e||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141)){return true}return false}},5511:(e,t,r)=>{"use strict";var s=r(7518);var a=r(6708);var o=r(6062);e.exports=function(e){if(typeof e!=="string"||e.length===0){return 0}var t=0;e=s(e);for(var r=0;r=127&&u<=159){continue}if(u>=65536){r++}if(o(u)){t+=2}else{t++}}return t}},4708:(e,t,r)=>{"use strict";var s=r(6322);var a=r(4293);var o=r(5534);var u=e.exports=function(e,t,r){if(!r)r=80;o("OAN",[e,t,r]);this.showing=false;this.theme=e;this.width=r;this.template=t};u.prototype={};u.prototype.setTheme=function(e){o("O",[e]);this.theme=e};u.prototype.setTemplate=function(e){o("A",[e]);this.template=e};u.prototype.setWidth=function(e){o("N",[e]);this.width=e};u.prototype.hide=function(){return s.gotoSOL()+s.eraseLine()};u.prototype.hideCursor=s.hideCursor;u.prototype.showCursor=s.showCursor;u.prototype.show=function(e){var t=Object.create(this.theme);for(var r in e){t[r]=e[r]}return a(this.width,this.template,t).trim()+s.color("reset")+s.eraseLine()+s.gotoSOL()}},9186:e=>{"use strict";e.exports=process},5791:(e,t,r)=>{"use strict";var s=r(5534);var a=r(4293);var o=r(2343);var u=r(5511);e.exports=function(e,t,r){s("ONN",[e,t,r]);if(r<0)r=0;if(r>1)r=1;if(t<=0)return"";var o=Math.round(t*r);var u=t-o;var c=[{type:"complete",value:repeat(e.complete,o),length:o},{type:"remaining",value:repeat(e.remaining,u),length:u}];return a(t,c,e)};function repeat(e,t){var r="";var s=t;do{if(s%2){r+=e}s=Math.floor(s/2);e+=e}while(s&&u(r){"use strict";var s=r(7568);var a=r(5534);var o=r(1800);var u=r(2343);var c=r(2479);var f=r(5205);function renderValueWithValues(e){return function(t){return renderValue(t,e)}}var p=e.exports=function(e,t,r){var a=prepareItems(e,t,r);var o=a.map(renderValueWithValues(r)).join("");return s.left(u(o,e),e)};function preType(e){var t=e.type[0].toUpperCase()+e.type.slice(1);return"pre"+t}function postType(e){var t=e.type[0].toUpperCase()+e.type.slice(1);return"post"+t}function hasPreOrPost(e,t){if(!e.type)return;return t[preType(e)]||t[postType(e)]}function generatePreAndPost(e,t){var r=o({},e);var s=Object.create(t);var a=[];var u=preType(r);var c=postType(r);if(s[u]){a.push({value:s[u]});s[u]=null}r.minLength=null;r.length=null;r.maxLength=null;a.push(r);s[r.type]=s[r.type];if(s[c]){a.push({value:s[c]});s[c]=null}return function(e,t,r){return p(r,a,s)}}function prepareItems(e,t,r){function cloneAndObjectify(t,s,a){var o=new f(t,e);var u=o.type;if(o.value==null){if(!(u in r)){if(o.default==null){throw new c.MissingTemplateValue(o,r)}else{o.value=o.default}}else{o.value=r[u]}}if(o.value==null||o.value==="")return null;o.index=s;o.first=s===0;o.last=s===a.length-1;if(hasPreOrPost(o,r))o.value=generatePreAndPost(o,r);return o}var s=t.map(cloneAndObjectify).filter((function(e){return e!=null}));var a=0;var o=e;var u=s.length;function consumeSpace(e){if(e>o)e=o;a+=e;o-=e}function finishSizing(e,t){if(e.finished)throw new c.Internal("Tried to finish template item that was already finished");if(t===Infinity)throw new c.Internal("Length of template item cannot be infinity");if(t!=null)e.length=t;e.minLength=null;e.maxLength=null;--u;e.finished=true;if(e.length==null)e.length=e.getBaseLength();if(e.length==null)throw new c.Internal("Finished template items must have a length");consumeSpace(e.getLength())}s.forEach((function(e){if(!e.kerning)return;var t=e.first?0:s[e.index-1].padRight;if(!e.first&&t=h){finishSizing(e,e.minLength);d=true}}))}while(d&&p++{"use strict";var s=r(9186);try{e.exports=setImmediate}catch(t){e.exports=s.nextTick}},75:e=>{"use strict";e.exports=setInterval},1021:e=>{"use strict";e.exports=function spin(e,t){return e[t%e.length]}},5205:(e,t,r)=>{"use strict";var s=r(5511);e.exports=TemplateItem;function isPercent(e){if(typeof e!=="string")return false;return e.slice(-1)==="%"}function percent(e){return Number(e.slice(0,-1))/100}function TemplateItem(e,t){this.overallOutputLength=t;this.finished=false;this.type=null;this.value=null;this.length=null;this.maxLength=null;this.minLength=null;this.kerning=null;this.align="left";this.padLeft=0;this.padRight=0;this.index=null;this.first=null;this.last=null;if(typeof e==="string"){this.value=e}else{for(var r in e)this[r]=e[r]}if(isPercent(this.length)){this.length=Math.round(this.overallOutputLength*percent(this.length))}if(isPercent(this.minLength)){this.minLength=Math.round(this.overallOutputLength*percent(this.minLength))}if(isPercent(this.maxLength)){this.maxLength=Math.round(this.overallOutputLength*percent(this.maxLength))}return this}TemplateItem.prototype={};TemplateItem.prototype.getBaseLength=function(){var e=this.length;if(e==null&&typeof this.value==="string"&&this.maxLength==null&&this.minLength==null){e=s(this.value)}return e};TemplateItem.prototype.getLength=function(){var e=this.getBaseLength();if(e==null)return null;return e+this.padLeft+this.padRight};TemplateItem.prototype.getMaxLength=function(){if(this.maxLength==null)return null;return this.maxLength+this.padLeft+this.padRight};TemplateItem.prototype.getMinLength=function(){if(this.minLength==null)return null;return this.minLength+this.padLeft+this.padRight}},3117:(e,t,r)=>{"use strict";var s=r(1800);e.exports=function(){return a.newThemeSet()};var a={};a.baseTheme=r(1271);a.newTheme=function(e,t){if(!t){t=e;e=this.baseTheme}return s({},e,t)};a.getThemeNames=function(){return Object.keys(this.themes)};a.addTheme=function(e,t,r){this.themes[e]=this.newTheme(t,r)};a.addToAllThemes=function(e){var t=this.themes;Object.keys(t).forEach((function(r){s(t[r],e)}));s(this.baseTheme,e)};a.getTheme=function(e){if(!this.themes[e])throw this.newMissingThemeError(e);return this.themes[e]};a.setDefault=function(e,t){if(t==null){t=e;e={}}var r=e.platform==null?"fallback":e.platform;var s=!!e.hasUnicode;var a=!!e.hasColor;if(!this.defaults[r])this.defaults[r]={true:{},false:{}};this.defaults[r][s][a]=t};a.getDefault=function(e){if(!e)e={};var t=e.platform||process.platform;var r=this.defaults[t]||this.defaults.fallback;var a=!!e.hasUnicode;var o=!!e.hasColor;if(!r)throw this.newMissingDefaultThemeError(t,a,o);if(!r[a][o]){if(a&&o&&r[!a][o]){a=false}else if(a&&o&&r[a][!o]){o=false}else if(a&&o&&r[!a][!o]){a=false;o=false}else if(a&&!o&&r[!a][o]){a=false}else if(!a&&o&&r[a][!o]){o=false}else if(r===this.defaults.fallback){throw this.newMissingDefaultThemeError(t,a,o)}}if(r[a][o]){return this.getTheme(r[a][o])}else{return this.getDefault(s({},e,{platform:"fallback"}))}};a.newMissingThemeError=function newMissingThemeError(e){var t=new Error('Could not find a gauge theme named "'+e+'"');Error.captureStackTrace.call(t,newMissingThemeError);t.theme=e;t.code="EMISSINGTHEME";return t};a.newMissingDefaultThemeError=function newMissingDefaultThemeError(e,t,r){var s=new Error("Could not find a gauge theme for your platform/unicode/color use combo:\n"+" platform = "+e+"\n"+" hasUnicode = "+t+"\n"+" hasColor = "+r);Error.captureStackTrace.call(s,newMissingDefaultThemeError);s.platform=e;s.hasUnicode=t;s.hasColor=r;s.code="EMISSINGTHEME";return s};a.newThemeSet=function(){var themeset=function(e){return themeset.getDefault(e)};return s(themeset,a,{themes:s({},this.themes),baseTheme:s({},this.baseTheme),defaults:JSON.parse(JSON.stringify(this.defaults||{}))})}},7987:(e,t,r)=>{"use strict";var s=r(6322);var a=r(3117);var o=e.exports=new a;o.addTheme("ASCII",{preProgressbar:"[",postProgressbar:"]",progressbarTheme:{complete:"#",remaining:"."},activityIndicatorTheme:"-\\|/",preSubsection:">"});o.addTheme("colorASCII",o.getTheme("ASCII"),{progressbarTheme:{preComplete:s.color("inverse"),complete:" ",postComplete:s.color("stopInverse"),preRemaining:s.color("brightBlack"),remaining:".",postRemaining:s.color("reset")}});o.addTheme("brailleSpinner",{preProgressbar:"⸨",postProgressbar:"⸩",progressbarTheme:{complete:"░",remaining:"⠂"},activityIndicatorTheme:"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏",preSubsection:">"});o.addTheme("colorBrailleSpinner",o.getTheme("brailleSpinner"),{progressbarTheme:{preComplete:s.color("inverse"),complete:" ",postComplete:s.color("stopInverse"),preRemaining:s.color("brightBlack"),remaining:"░",postRemaining:s.color("reset")}});o.setDefault({},"ASCII");o.setDefault({hasColor:true},"colorASCII");o.setDefault({platform:"darwin",hasUnicode:true},"brailleSpinner");o.setDefault({platform:"darwin",hasUnicode:true,hasColor:true},"colorBrailleSpinner")},2343:(e,t,r)=>{"use strict";var s=r(5511);var a=r(7518);e.exports=wideTruncate;function wideTruncate(e,t){if(s(e)===0)return e;if(t<=0)return"";if(s(e)<=t)return e;var r=a(e);var o=e.length+r.length;var u=e.slice(0,t+o);while(s(u)>t){u=u.slice(0,-1)}return u}},9132:e=>{"use strict";e.exports=clone;var t=Object.getPrototypeOf||function(e){return e.__proto__};function clone(e){if(e===null||typeof e!=="object")return e;if(e instanceof Object)var r={__proto__:t(e)};else var r=Object.create(null);Object.getOwnPropertyNames(e).forEach((function(t){Object.defineProperty(r,t,Object.getOwnPropertyDescriptor(e,t))}));return r}},552:(e,t,r)=>{var s=r(7147);var a=r(1290);var o=r(4410);var u=r(9132);var c=r(3837);var f;var p;if(typeof Symbol==="function"&&typeof Symbol.for==="function"){f=Symbol.for("graceful-fs.queue");p=Symbol.for("graceful-fs.previous")}else{f="___graceful-fs.queue";p="___graceful-fs.previous"}function noop(){}function publishQueue(e,t){Object.defineProperty(e,f,{get:function(){return t}})}var d=noop;if(c.debuglog)d=c.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))d=function(){var e=c.format.apply(c,arguments);e="GFS4: "+e.split(/\n/).join("\nGFS4: ");console.error(e)};if(!s[f]){var h=global[f]||[];publishQueue(s,h);s.close=function(e){function close(t,r){return e.call(s,t,(function(e){if(!e){resetQueue()}if(typeof r==="function")r.apply(this,arguments)}))}Object.defineProperty(close,p,{value:e});return close}(s.close);s.closeSync=function(e){function closeSync(t){e.apply(s,arguments);resetQueue()}Object.defineProperty(closeSync,p,{value:e});return closeSync}(s.closeSync);if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")){process.on("exit",(function(){d(s[f]);r(9491).equal(s[f].length,0)}))}}if(!global[f]){publishQueue(global,s[f])}e.exports=patch(u(s));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!s.__patched){e.exports=patch(s);s.__patched=true}function patch(e){a(e);e.gracefulify=patch;e.createReadStream=createReadStream;e.createWriteStream=createWriteStream;var t=e.readFile;e.readFile=readFile;function readFile(e,r,s){if(typeof r==="function")s=r,r=null;return go$readFile(e,r,s);function go$readFile(e,r,s,a){return t(e,r,(function(t){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))enqueue([go$readFile,[e,r,s],t,a||Date.now(),Date.now()]);else{if(typeof s==="function")s.apply(this,arguments)}}))}}var r=e.writeFile;e.writeFile=writeFile;function writeFile(e,t,s,a){if(typeof s==="function")a=s,s=null;return go$writeFile(e,t,s,a);function go$writeFile(e,t,s,a,o){return r(e,t,s,(function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))enqueue([go$writeFile,[e,t,s,a],r,o||Date.now(),Date.now()]);else{if(typeof a==="function")a.apply(this,arguments)}}))}}var s=e.appendFile;if(s)e.appendFile=appendFile;function appendFile(e,t,r,a){if(typeof r==="function")a=r,r=null;return go$appendFile(e,t,r,a);function go$appendFile(e,t,r,a,o){return s(e,t,r,(function(s){if(s&&(s.code==="EMFILE"||s.code==="ENFILE"))enqueue([go$appendFile,[e,t,r,a],s,o||Date.now(),Date.now()]);else{if(typeof a==="function")a.apply(this,arguments)}}))}}var u=e.copyFile;if(u)e.copyFile=copyFile;function copyFile(e,t,r,s){if(typeof r==="function"){s=r;r=0}return go$copyFile(e,t,r,s);function go$copyFile(e,t,r,s,a){return u(e,t,r,(function(o){if(o&&(o.code==="EMFILE"||o.code==="ENFILE"))enqueue([go$copyFile,[e,t,r,s],o,a||Date.now(),Date.now()]);else{if(typeof s==="function")s.apply(this,arguments)}}))}}var c=e.readdir;e.readdir=readdir;function readdir(e,t,r){if(typeof t==="function")r=t,t=null;return go$readdir(e,t,r);function go$readdir(e,t,r,s){return c(e,t,(function(a,o){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))enqueue([go$readdir,[e,t,r],a,s||Date.now(),Date.now()]);else{if(o&&o.sort)o.sort();if(typeof r==="function")r.call(this,a,o)}}))}}if(process.version.substr(0,4)==="v0.8"){var f=o(e);ReadStream=f.ReadStream;WriteStream=f.WriteStream}var p=e.ReadStream;if(p){ReadStream.prototype=Object.create(p.prototype);ReadStream.prototype.open=ReadStream$open}var d=e.WriteStream;if(d){WriteStream.prototype=Object.create(d.prototype);WriteStream.prototype.open=WriteStream$open}Object.defineProperty(e,"ReadStream",{get:function(){return ReadStream},set:function(e){ReadStream=e},enumerable:true,configurable:true});Object.defineProperty(e,"WriteStream",{get:function(){return WriteStream},set:function(e){WriteStream=e},enumerable:true,configurable:true});var h=ReadStream;Object.defineProperty(e,"FileReadStream",{get:function(){return h},set:function(e){h=e},enumerable:true,configurable:true});var v=WriteStream;Object.defineProperty(e,"FileWriteStream",{get:function(){return v},set:function(e){v=e},enumerable:true,configurable:true});function ReadStream(e,t){if(this instanceof ReadStream)return p.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var e=this;open(e.path,e.flags,e.mode,(function(t,r){if(t){if(e.autoClose)e.destroy();e.emit("error",t)}else{e.fd=r;e.emit("open",r);e.read()}}))}function WriteStream(e,t){if(this instanceof WriteStream)return d.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var e=this;open(e.path,e.flags,e.mode,(function(t,r){if(t){e.destroy();e.emit("error",t)}else{e.fd=r;e.emit("open",r)}}))}function createReadStream(t,r){return new e.ReadStream(t,r)}function createWriteStream(t,r){return new e.WriteStream(t,r)}var g=e.open;e.open=open;function open(e,t,r,s){if(typeof r==="function")s=r,r=null;return go$open(e,t,r,s);function go$open(e,t,r,s,a){return g(e,t,r,(function(o,u){if(o&&(o.code==="EMFILE"||o.code==="ENFILE"))enqueue([go$open,[e,t,r,s],o,a||Date.now(),Date.now()]);else{if(typeof s==="function")s.apply(this,arguments)}}))}}return e}function enqueue(e){d("ENQUEUE",e[0].name,e[1]);s[f].push(e);retry()}var v;function resetQueue(){var e=Date.now();for(var t=0;t2){s[f][t][3]=e;s[f][t][4]=e}}retry()}function retry(){clearTimeout(v);v=undefined;if(s[f].length===0)return;var e=s[f].shift();var t=e[0];var r=e[1];var a=e[2];var o=e[3];var u=e[4];if(o===undefined){d("RETRY",t.name,r);t.apply(null,r)}else if(Date.now()-o>=6e4){d("TIMEOUT",t.name,r);var c=r.pop();if(typeof c==="function")c.call(null,a)}else{var p=Date.now()-u;var h=Math.max(u-o,1);var g=Math.min(h*1.2,100);if(p>=g){d("RETRY",t.name,r);t.apply(null,r.concat([o]))}else{s[f].push(e)}}if(v===undefined){v=setTimeout(retry,0)}}},4410:(e,t,r)=>{var s=r(2781).Stream;e.exports=legacy;function legacy(e){return{ReadStream:ReadStream,WriteStream:WriteStream};function ReadStream(t,r){if(!(this instanceof ReadStream))return new ReadStream(t,r);s.call(this);var a=this;this.path=t;this.fd=null;this.readable=true;this.paused=false;this.flags="r";this.mode=438;this.bufferSize=64*1024;r=r||{};var o=Object.keys(r);for(var u=0,c=o.length;uthis.end){throw new Error("start must be <= end")}this.pos=this.start}if(this.fd!==null){process.nextTick((function(){a._read()}));return}e.open(this.path,this.flags,this.mode,(function(e,t){if(e){a.emit("error",e);a.readable=false;return}a.fd=t;a.emit("open",t);a._read()}))}function WriteStream(t,r){if(!(this instanceof WriteStream))return new WriteStream(t,r);s.call(this);this.path=t;this.fd=null;this.writable=true;this.flags="w";this.encoding="binary";this.mode=438;this.bytesWritten=0;r=r||{};var a=Object.keys(r);for(var o=0,u=a.length;o= zero")}this.pos=this.start}this.busy=false;this._queue=[];if(this.fd===null){this._open=e.open;this._queue.push([this._open,this.path,this.flags,this.mode,undefined]);this.flush()}}}},1290:(e,t,r)=>{var s=r(2057);var a=process.cwd;var o=null;var u=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!o)o=a.call(process);return o};try{process.cwd()}catch(e){}if(typeof process.chdir==="function"){var c=process.chdir;process.chdir=function(e){o=null;c.call(process,e)};if(Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,c)}e.exports=patch;function patch(e){if(s.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)){patchLchmod(e)}if(!e.lutimes){patchLutimes(e)}e.chown=chownFix(e.chown);e.fchown=chownFix(e.fchown);e.lchown=chownFix(e.lchown);e.chmod=chmodFix(e.chmod);e.fchmod=chmodFix(e.fchmod);e.lchmod=chmodFix(e.lchmod);e.chownSync=chownFixSync(e.chownSync);e.fchownSync=chownFixSync(e.fchownSync);e.lchownSync=chownFixSync(e.lchownSync);e.chmodSync=chmodFixSync(e.chmodSync);e.fchmodSync=chmodFixSync(e.fchmodSync);e.lchmodSync=chmodFixSync(e.lchmodSync);e.stat=statFix(e.stat);e.fstat=statFix(e.fstat);e.lstat=statFix(e.lstat);e.statSync=statFixSync(e.statSync);e.fstatSync=statFixSync(e.fstatSync);e.lstatSync=statFixSync(e.lstatSync);if(!e.lchmod){e.lchmod=function(e,t,r){if(r)process.nextTick(r)};e.lchmodSync=function(){}}if(!e.lchown){e.lchown=function(e,t,r,s){if(s)process.nextTick(s)};e.lchownSync=function(){}}if(u==="win32"){e.rename=function(t){return function(r,s,a){var o=Date.now();var u=0;t(r,s,(function CB(c){if(c&&(c.code==="EACCES"||c.code==="EPERM")&&Date.now()-o<6e4){setTimeout((function(){e.stat(s,(function(e,o){if(e&&e.code==="ENOENT")t(r,s,CB);else a(c)}))}),u);if(u<100)u+=10;return}if(a)a(c)}))}}(e.rename)}e.read=function(t){function read(r,s,a,o,u,c){var f;if(c&&typeof c==="function"){var p=0;f=function(d,h,v){if(d&&d.code==="EAGAIN"&&p<10){p++;return t.call(e,r,s,a,o,u,f)}c.apply(this,arguments)}}return t.call(e,r,s,a,o,u,f)}if(Object.setPrototypeOf)Object.setPrototypeOf(read,t);return read}(e.read);e.readSync=function(t){return function(r,s,a,o,u){var c=0;while(true){try{return t.call(e,r,s,a,o,u)}catch(e){if(e.code==="EAGAIN"&&c<10){c++;continue}throw e}}}}(e.readSync);function patchLchmod(e){e.lchmod=function(t,r,a){e.open(t,s.O_WRONLY|s.O_SYMLINK,r,(function(t,s){if(t){if(a)a(t);return}e.fchmod(s,r,(function(t){e.close(s,(function(e){if(a)a(t||e)}))}))}))};e.lchmodSync=function(t,r){var a=e.openSync(t,s.O_WRONLY|s.O_SYMLINK,r);var o=true;var u;try{u=e.fchmodSync(a,r);o=false}finally{if(o){try{e.closeSync(a)}catch(e){}}else{e.closeSync(a)}}return u}}function patchLutimes(e){if(s.hasOwnProperty("O_SYMLINK")){e.lutimes=function(t,r,a,o){e.open(t,s.O_SYMLINK,(function(t,s){if(t){if(o)o(t);return}e.futimes(s,r,a,(function(t){e.close(s,(function(e){if(o)o(t||e)}))}))}))};e.lutimesSync=function(t,r,a){var o=e.openSync(t,s.O_SYMLINK);var u;var c=true;try{u=e.futimesSync(o,r,a);c=false}finally{if(c){try{e.closeSync(o)}catch(e){}}else{e.closeSync(o)}}return u}}else{e.lutimes=function(e,t,r,s){if(s)process.nextTick(s)};e.lutimesSync=function(){}}}function chmodFix(t){if(!t)return t;return function(r,s,a){return t.call(e,r,s,(function(e){if(chownErOk(e))e=null;if(a)a.apply(this,arguments)}))}}function chmodFixSync(t){if(!t)return t;return function(r,s){try{return t.call(e,r,s)}catch(e){if(!chownErOk(e))throw e}}}function chownFix(t){if(!t)return t;return function(r,s,a,o){return t.call(e,r,s,a,(function(e){if(chownErOk(e))e=null;if(o)o.apply(this,arguments)}))}}function chownFixSync(t){if(!t)return t;return function(r,s,a){try{return t.call(e,r,s,a)}catch(e){if(!chownErOk(e))throw e}}}function statFix(t){if(!t)return t;return function(r,s,a){if(typeof s==="function"){a=s;s=null}function callback(e,t){if(t){if(t.uid<0)t.uid+=4294967296;if(t.gid<0)t.gid+=4294967296}if(a)a.apply(this,arguments)}return s?t.call(e,r,s,callback):t.call(e,r,callback)}}function statFixSync(t){if(!t)return t;return function(r,s){var a=s?t.call(e,r,s):t.call(e,r);if(a){if(a.uid<0)a.uid+=4294967296;if(a.gid<0)a.gid+=4294967296}return a}}function chownErOk(e){if(!e)return true;if(e.code==="ENOSYS")return true;var t=!process.getuid||process.getuid()!==0;if(t){if(e.code==="EINVAL"||e.code==="EPERM")return true}return false}}},7963:(e,t,r)=>{"use strict";var s=r(2037);var a=e.exports=function(){if(s.type()=="Windows_NT"){return false}var e=/UTF-?8$/i;var t=process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG;return e.test(t)}},6919:(e,t,r)=>{try{var s=r(3837);if(typeof s.inherits!=="function")throw"";e.exports=s.inherits}catch(t){e.exports=r(7526)}},7526:e=>{if(typeof Object.create==="function"){e.exports=function inherits(e,t){if(t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}}else{e.exports=function inherits(e,t){if(t){e.super_=t;var TempCtor=function(){};TempCtor.prototype=t.prototype;e.prototype=new TempCtor;e.prototype.constructor=e}}}},9842:e=>{var t={}.toString;e.exports=Array.isArray||function(e){return t.call(e)=="[object Array]"}},3277:(module,__unused_webpack_exports,__nccwpck_require__)=>{var fs=__nccwpck_require__(7147);var path=__nccwpck_require__(1017);var os=__nccwpck_require__(2037);var runtimeRequire=true?eval("require"):0;var vars=process.config&&process.config.variables||{};var prebuildsOnly=!!process.env.PREBUILDS_ONLY;var abi=process.versions.modules;var runtime=isElectron()?"electron":"node";var arch=os.arch();var platform=os.platform();var libc=process.env.LIBC||(isAlpine(platform)?"musl":"glibc");var armv=process.env.ARM_VERSION||(arch==="arm64"?"8":vars.arm_version)||"";var uv=(process.versions.uv||"").split(".")[0];module.exports=load;function load(e){return runtimeRequire(load.path(e))}load.path=function(e){e=path.resolve(e||".");try{var t=runtimeRequire(path.join(e,"package.json")).name.toUpperCase().replace(/-/g,"_");if(process.env[t+"_PREBUILD"])e=process.env[t+"_PREBUILD"]}catch(e){}if(!prebuildsOnly){var r=getFirst(path.join(e,"build/Release"),matchBuild);if(r)return r;var s=getFirst(path.join(e,"build/Debug"),matchBuild);if(s)return s}var a=resolve(e);if(a)return a;var o=resolve(path.dirname(process.execPath));if(o)return o;var u=["platform="+platform,"arch="+arch,"runtime="+runtime,"abi="+abi,"uv="+uv,armv?"armv="+armv:"","libc="+libc,"node="+process.versions.node,process.versions&&process.versions.electron?"electron="+process.versions.electron:"",true?"webpack=true":0].filter(Boolean).join(" ");throw new Error("No native build was found for "+u+"\n loaded from: "+e+"\n");function resolve(e){var t=path.join(e,"prebuilds",platform+"-"+arch);var r=readdirSync(t).map(parseTags);var s=r.filter(matchTags(runtime,abi));var a=s.sort(compareTags(runtime))[0];if(a)return path.join(t,a.file)}};function readdirSync(e){try{return fs.readdirSync(e)}catch(e){return[]}}function getFirst(e,t){var r=readdirSync(e).filter(t);return r[0]&&path.join(e,r[0])}function matchBuild(e){return/\.node$/.test(e)}function parseTags(e){var t=e.split(".");var r=t.pop();var s={file:e,specificity:0};if(r!=="node")return;for(var a=0;ar.specificity?-1:1}else{return 0}}}function isElectron(){if(process.versions&&process.versions.electron)return true;if(process.env.ELECTRON_RUN_AS_NODE)return true;return typeof window!=="undefined"&&window.process&&window.process.type==="renderer"}function isAlpine(e){return e==="linux"&&fs.existsSync("/etc/alpine-release")}load.parseTags=parseTags;load.matchTags=matchTags;load.compareTags=compareTags},9248:(e,t,r)=>{"use strict";var s=r(7147);var a=r(3632);var o=r(9658);e.exports=t;var u=process.version.substr(1).replace(/-.*$/,"").split(".").map((function(e){return+e}));var c=["build","clean","configure","package","publish","reveal","testbinary","testpackage","unpublish"];var f="napi_build_version=";e.exports.get_napi_version=function(e){var t=process.versions.napi;if(!t){if(u[0]===9&&u[1]>=3)t=2;else if(u[0]===8)t=1}return t};e.exports.get_napi_version_as_string=function(t){var r=e.exports.get_napi_version(t);return r?""+r:""};e.exports.validate_package_json=function(t,r){var s=t.binary;var a=pathOK(s.module_path);var o=pathOK(s.remote_path);var u=pathOK(s.package_name);var c=e.exports.get_napi_build_versions(t,r,true);var f=e.exports.get_napi_build_versions_raw(t);if(c){c.forEach((function(e){if(!(parseInt(e,10)===e&&e>0)){throw new Error("All values specified in napi_versions must be positive integers.")}}))}if(c&&(!a||!o&&!u)){throw new Error("When napi_versions is specified; module_path and either remote_path or "+"package_name must contain the substitution string '{napi_build_version}`.")}if((a||o||u)&&!f){throw new Error("When the substitution string '{napi_build_version}` is specified in "+"module_path, remote_path, or package_name; napi_versions must also be specified.")}if(c&&!e.exports.get_best_napi_build_version(t,r)&&e.exports.build_napi_only(t)){throw new Error("The N-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports N-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}if(f&&!c&&e.exports.build_napi_only(t)){throw new Error("The N-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports N-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}};function pathOK(e){return e&&(e.indexOf("{napi_build_version}")!==-1||e.indexOf("{node_napi_label}")!==-1)}e.exports.expand_commands=function(t,r,s){var a=[];var o=e.exports.get_napi_build_versions(t,r);s.forEach((function(s){if(o&&s.name==="install"){var u=e.exports.get_best_napi_build_version(t,r);var p=u?[f+u]:[];a.push({name:s.name,args:p})}else if(o&&c.indexOf(s.name)!==-1){o.forEach((function(e){var t=s.args.slice();t.push(f+e);a.push({name:s.name,args:t})}))}else{a.push(s)}}));return a};e.exports.get_napi_build_versions=function(t,r,s){var a=[];var u=e.exports.get_napi_version(r?r.target:undefined);if(t.binary&&t.binary.napi_versions){t.binary.napi_versions.forEach((function(e){var t=a.indexOf(e)!==-1;if(!t&&u&&e<=u){a.push(e)}else if(s&&!t&&u){o.info("This Node instance does not support builds for N-API version",e)}}))}if(r&&r["build-latest-napi-version-only"]){var c=0;a.forEach((function(e){if(e>c)c=e}));a=c?[c]:[]}return a.length?a:undefined};e.exports.get_napi_build_versions_raw=function(e){var t=[];if(e.binary&&e.binary.napi_versions){e.binary.napi_versions.forEach((function(e){if(t.indexOf(e)===-1){t.push(e)}}))}return t.length?t:undefined};e.exports.get_command_arg=function(e){return f+e};e.exports.get_napi_build_version_from_command_args=function(e){for(var t=0;ts&&e<=o){s=e}}))}return s===0?undefined:s};e.exports.build_napi_only=function(e){return e.binary&&e.binary.package_name&&e.binary.package_name.indexOf("{node_napi_label}")===-1}},5574:(e,t,r)=>{"use strict";e.exports=t;var s=r(1017);var a=r(7849);var o=r(7310);var u=r(2157);var c=r(9248);var f;if(process.env.NODE_PRE_GYP_ABI_CROSSWALK){f=require(process.env.NODE_PRE_GYP_ABI_CROSSWALK)}else{f=r(7316)}var p={};Object.keys(f).forEach((function(e){var t=e.split(".")[0];if(!p[t]){p[t]=e}}));function get_electron_abi(e,t){if(!e){throw new Error("get_electron_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if electron is the target.")}var r=a.parse(t);return e+"-v"+r.major+"."+r.minor}e.exports.get_electron_abi=get_electron_abi;function get_node_webkit_abi(e,t){if(!e){throw new Error("get_node_webkit_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if node-webkit is the target.")}return e+"-v"+t}e.exports.get_node_webkit_abi=get_node_webkit_abi;function get_node_abi(e,t){if(!e){throw new Error("get_node_abi requires valid runtime arg")}if(!t){throw new Error("get_node_abi requires valid process.versions object")}var r=a.parse(t.node);if(r.major===0&&r.minor%2){return e+"-v"+t.node}else{return t.modules?e+"-v"+ +t.modules:"v8-"+t.v8.split(".").slice(0,2).join(".")}}e.exports.get_node_abi=get_node_abi;function get_runtime_abi(e,t){if(!e){throw new Error("get_runtime_abi requires valid runtime arg")}if(e==="node-webkit"){return get_node_webkit_abi(e,t||process.versions["node-webkit"])}else if(e==="electron"){return get_electron_abi(e,t||process.versions.electron)}else{if(e!="node"){throw new Error("Unknown Runtime: '"+e+"'")}if(!t){return get_node_abi(e,process.versions)}else{var r;if(f[t]){r=f[t]}else{var s=t.split(".").map((function(e){return+e}));if(s.length!=3){throw new Error("Unknown target version: "+t)}var a=s[0];var o=s[1];var u=s[2];if(a===1){while(true){if(o>0)--o;if(u>0)--u;var c=""+a+"."+o+"."+u;if(f[c]){r=f[c];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+c+" as ABI compatible target");break}if(o===0&&u===0){break}}}else if(a>=2){if(p[a]){r=f[p[a]];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+p[a]+" as ABI compatible target")}}else if(a===0){if(s[1]%2===0){while(--u>0){var d=""+a+"."+o+"."+u;if(f[d]){r=f[d];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+d+" as ABI compatible target");break}}}}}if(!r){throw new Error("Unsupported target version: "+t)}var h={node:t,v8:r.v8+".0",modules:r.node_abi>1?r.node_abi:undefined};return get_node_abi(e,h)}}}e.exports.get_runtime_abi=get_runtime_abi;var d=["module_name","module_path","host"];function validate_config(e,t){var r=e.name+" package.json is not node-pre-gyp ready:\n";var s=[];if(!e.main){s.push("main")}if(!e.version){s.push("version")}if(!e.name){s.push("name")}if(!e.binary){s.push("binary")}var a=e.binary;d.forEach((function(e){if(s.indexOf("binary")>-1){s.pop("binary")}if(!a||a[e]===undefined||a[e]===""){s.push("binary."+e)}}));if(s.length>=1){throw new Error(r+"package.json must declare these properties: \n"+s.join("\n"))}if(a){var u=o.parse(a.host).protocol;if(u==="http:"){throw new Error("'host' protocol ("+u+") is invalid - only 'https:' is accepted")}}c.validate_package_json(e,t)}e.exports.validate_config=validate_config;function eval_template(e,t){Object.keys(t).forEach((function(r){var s="{"+r+"}";while(e.indexOf(s)>-1){e=e.replace(s,t[r])}}));return e}function fix_slashes(e){if(e.slice(-1)!="/"){return e+"/"}return e}function drop_double_slashes(e){return e.replace(/\/\//g,"/")}function get_process_runtime(e){var t="node";if(e["node-webkit"]){t="node-webkit"}else if(e.electron){t="electron"}return t}e.exports.get_process_runtime=get_process_runtime;var h="{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz";var v="";e.exports.evaluate=function(e,t,r){t=t||{};validate_config(e,t);var f=e.version;var p=a.parse(f);var d=t.runtime||get_process_runtime(process.versions);var g={name:e.name,configuration:Boolean(t.debug)?"Debug":"Release",debug:t.debug,module_name:e.binary.module_name,version:p.version,prerelease:p.prerelease.length?p.prerelease.join("."):"",build:p.build.length?p.build.join("."):"",major:p.major,minor:p.minor,patch:p.patch,runtime:d,node_abi:get_runtime_abi(d,t.target),node_abi_napi:c.get_napi_version(t.target)?"napi":get_runtime_abi(d,t.target),napi_version:c.get_napi_version(t.target),napi_build_version:r||"",node_napi_label:r?"napi-v"+r:get_runtime_abi(d,t.target),target:t.target||"",platform:t.target_platform||process.platform,target_platform:t.target_platform||process.platform,arch:t.target_arch||process.arch,target_arch:t.target_arch||process.arch,libc:t.target_libc||u.family||"unknown",module_main:e.main,toolset:t.toolset||""};var m=process.env["npm_config_"+g.module_name+"_binary_host_mirror"]||e.binary.host;g.host=fix_slashes(eval_template(m,g));g.module_path=eval_template(e.binary.module_path,g);if(t.module_root){g.module_path=s.join(t.module_root,g.module_path)}else{g.module_path=s.resolve(g.module_path)}g.module=s.join(g.module_path,g.module_name+".node");g.remote_path=e.binary.remote_path?drop_double_slashes(fix_slashes(eval_template(e.binary.remote_path,g))):v;var _=e.binary.package_name?e.binary.package_name:h;g.package_name=eval_template(_,g);g.staged_tarball=s.join("build/stage",g.remote_path,g.package_name);g.hosted_path=o.resolve(g.host,g.remote_path);g.hosted_tarball=o.resolve(g.hosted_path,g.package_name);return g}},3632:(e,t,r)=>{e.exports=rimraf;rimraf.sync=rimrafSync;var s=r(9491);var a=r(1017);var o=r(7147);var u=undefined;try{u=r(3535)}catch(e){}var c=parseInt("666",8);var f={nosort:true,silent:true};var p=0;var d=process.platform==="win32";function defaults(e){var t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach((function(t){e[t]=e[t]||o[t];t=t+"Sync";e[t]=e[t]||o[t]}));e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&u===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||f}function rimraf(e,t,r){if(typeof t==="function"){r=t;t={}}s(e,"rimraf: missing path");s.equal(typeof e,"string","rimraf: path should be a string");s.equal(typeof r,"function","rimraf: callback function required");s(t,"rimraf: invalid options argument provided");s.equal(typeof t,"object","rimraf: options should be object");defaults(t);var a=0;var o=null;var c=0;if(t.disableGlob||!u.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,(function(r,s){if(!r)return afterGlob(null,[e]);u(e,t.glob,afterGlob)}));function next(e){o=o||e;if(--c===0)r(o)}function afterGlob(e,s){if(e)return r(e);c=s.length;if(c===0)return r();s.forEach((function(e){rimraf_(e,t,(function CB(r){if(r){if((r.code==="EBUSY"||r.code==="ENOTEMPTY"||r.code==="EPERM")&&a{"use strict";var s=r(2717);var a=r(6054);var o=r(2361).EventEmitter;var u=t=e.exports=new o;var c=r(3837);var f=r(8834);var p=r(6322);f(true);var d=process.stderr;Object.defineProperty(u,"stream",{set:function(e){d=e;if(this.gauge)this.gauge.setWriteTo(d,d)},get:function(){return d}});var h;u.useColor=function(){return h!=null?h:d.isTTY};u.enableColor=function(){h=true;this.gauge.setTheme({hasColor:h,hasUnicode:v})};u.disableColor=function(){h=false;this.gauge.setTheme({hasColor:h,hasUnicode:v})};u.level="info";u.gauge=new a(d,{enabled:false,theme:{hasColor:u.useColor()},template:[{type:"progressbar",length:20},{type:"activityIndicator",kerning:1,length:1},{type:"section",default:""},":",{type:"logline",kerning:1,default:""}]});u.tracker=new s.TrackerGroup;u.progressEnabled=u.gauge.isEnabled();var v;u.enableUnicode=function(){v=true;this.gauge.setTheme({hasColor:this.useColor(),hasUnicode:v})};u.disableUnicode=function(){v=false;this.gauge.setTheme({hasColor:this.useColor(),hasUnicode:v})};u.setGaugeThemeset=function(e){this.gauge.setThemeset(e)};u.setGaugeTemplate=function(e){this.gauge.setTemplate(e)};u.enableProgress=function(){if(this.progressEnabled)return;this.progressEnabled=true;this.tracker.on("change",this.showProgress);if(this._pause)return;this.gauge.enable()};u.disableProgress=function(){if(!this.progressEnabled)return;this.progressEnabled=false;this.tracker.removeListener("change",this.showProgress);this.gauge.disable()};var g=["newGroup","newItem","newStream"];var mixinLog=function(e){Object.keys(u).forEach((function(t){if(t[0]==="_")return;if(g.filter((function(e){return e===t})).length)return;if(e[t])return;if(typeof u[t]!=="function")return;var r=u[t];e[t]=function(){return r.apply(u,arguments)}}));if(e instanceof s.TrackerGroup){g.forEach((function(t){var r=e[t];e[t]=function(){return mixinLog(r.apply(e,arguments))}}))}return e};g.forEach((function(e){u[e]=function(){return mixinLog(this.tracker[e].apply(this.tracker,arguments))}}));u.clearProgress=function(e){if(!this.progressEnabled)return e&&process.nextTick(e);this.gauge.hide(e)};u.showProgress=function(e,t){if(!this.progressEnabled)return;var r={};if(e)r.section=e;var s=u.record[u.record.length-1];if(s){r.subsection=s.prefix;var a=u.disp[s.level]||s.level;var o=this._format(a,u.style[s.level]);if(s.prefix)o+=" "+this._format(s.prefix,this.prefixStyle);o+=" "+s.message.split(/\r?\n/)[0];r.logline=o}r.completed=t||this.tracker.completed();this.gauge.show(r)}.bind(u);u.pause=function(){this._paused=true;if(this.progressEnabled)this.gauge.disable()};u.resume=function(){if(!this._paused)return;this._paused=false;var e=this._buffer;this._buffer=[];e.forEach((function(e){this.emitLog(e)}),this);if(this.progressEnabled)this.gauge.enable()};u._buffer=[];var m=0;u.record=[];u.maxRecordSize=1e4;u.log=function(e,t,r){var s=this.levels[e];if(s===undefined){return this.emit("error",new Error(c.format("Undefined log level: %j",e)))}var a=new Array(arguments.length-2);var o=null;for(var u=2;ud/10){var v=Math.floor(d*.9);this.record=this.record.slice(-1*v)}this.emitLog(p)}.bind(u);u.emitLog=function(e){if(this._paused){this._buffer.push(e);return}if(this.progressEnabled)this.gauge.pulse(e.prefix);var t=this.levels[e.level];if(t===undefined)return;if(t0&&!isFinite(t))return;var r=u.disp[e.level]!=null?u.disp[e.level]:e.level;this.clearProgress();e.message.split(/\r?\n/).forEach((function(t){if(this.heading){this.write(this.heading,this.headingStyle);this.write(" ")}this.write(r,u.style[e.level]);var s=e.prefix||"";if(s)this.write(" ");this.write(s,this.prefixStyle);this.write(" "+t+"\n")}),this);this.showProgress()};u._format=function(e,t){if(!d)return;var r="";if(this.useColor()){t=t||{};var s=[];if(t.fg)s.push(t.fg);if(t.bg)s.push("bg"+t.bg[0].toUpperCase()+t.bg.slice(1));if(t.bold)s.push("bold");if(t.underline)s.push("underline");if(t.inverse)s.push("inverse");if(s.length)r+=p.color(s);if(t.beep)r+=p.beep()}r+=e;if(this.useColor()){r+=p.color("reset")}return r};u.write=function(e,t){if(!d)return;d.write(this._format(e,t))};u.addLevel=function(e,t,r,s){if(s==null)s=e;this.levels[e]=t;this.style[e]=r;if(!this[e]){this[e]=function(){var t=new Array(arguments.length+1);t[0]=e;for(var r=0;r{"use strict";e.exports=Number.isNaN||function(e){return e!==e}},1800:e=>{"use strict"; /* object-assign (c) Sindre Sorhus @license MIT -*/var t=Object.getOwnPropertySymbols;var r=Object.prototype.hasOwnProperty;var a=Object.prototype.propertyIsEnumerable;function toObject(e){if(e===null||e===undefined){throw new TypeError("Object.assign cannot be called with null or undefined")}return Object(e)}function shouldUseNative(){try{if(!Object.assign){return false}var e=new String("abc");e[5]="de";if(Object.getOwnPropertyNames(e)[0]==="5"){return false}var t={};for(var r=0;r<10;r++){t["_"+String.fromCharCode(r)]=r}var a=Object.getOwnPropertyNames(t).map((function(e){return t[e]}));if(a.join("")!=="0123456789"){return false}var o={};"abcdefghijklmnopqrst".split("").forEach((function(e){o[e]=e}));if(Object.keys(Object.assign({},o)).join("")!=="abcdefghijklmnopqrst"){return false}return true}catch(e){return false}}e.exports=shouldUseNative()?Object.assign:function(e,o){var s;var u=toObject(e);var c;for(var d=1;d{"use strict";if(typeof process==="undefined"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){e.exports={nextTick:nextTick}}else{e.exports=process}function nextTick(e,t,r,a){if(typeof e!=="function"){throw new TypeError('"callback" argument must be a function')}var o=arguments.length;var s,u;switch(o){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick((function afterTickOne(){e.call(null,t)}));case 3:return process.nextTick((function afterTickTwo(){e.call(null,t,r)}));case 4:return process.nextTick((function afterTickThree(){e.call(null,t,r,a)}));default:s=new Array(o-1);u=0;while(u{"use strict";var a=r(7843);var o=Object.keys||function(e){var t=[];for(var r in e){t.push(r)}return t};e.exports=Duplex;var s=Object.create(r(3487));s.inherits=r(6919);var u=r(284);var c=r(6100);s.inherits(Duplex,u);{var d=o(c.prototype);for(var f=0;f{"use strict";e.exports=PassThrough;var a=r(5469);var o=Object.create(r(3487));o.inherits=r(6919);o.inherits(PassThrough,a);function PassThrough(e){if(!(this instanceof PassThrough))return new PassThrough(e);a.call(this,e)}PassThrough.prototype._transform=function(e,t,r){r(null,e)}},284:(e,t,r)=>{"use strict";var a=r(7843);e.exports=Readable;var o=r(9842);var s;Readable.ReadableState=ReadableState;var u=r(2361).EventEmitter;var EElistenerCount=function(e,t){return e.listeners(t).length};var c=r(5016);var d=r(4810).Buffer;var f=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return d.from(e)}function _isUint8Array(e){return d.isBuffer(e)||e instanceof f}var p=Object.create(r(3487));p.inherits=r(6919);var h=r(3837);var v=void 0;if(h&&h.debuglog){v=h.debuglog("stream")}else{v=function(){}}var _=r(8739);var g=r(3090);var y;p.inherits(Readable,c);var m=["error","close","destroy","pause","resume"];function prependListener(e,t,r){if(typeof e.prependListener==="function")return e.prependListener(t,r);if(!e._events||!e._events[t])e.on(t,r);else if(o(e._events[t]))e._events[t].unshift(r);else e._events[t]=[r,e._events[t]]}function ReadableState(e,t){s=s||r(8393);e=e||{};var a=t instanceof s;this.objectMode=!!e.objectMode;if(a)this.objectMode=this.objectMode||!!e.readableObjectMode;var o=e.highWaterMark;var u=e.readableHighWaterMark;var c=this.objectMode?16:16*1024;if(o||o===0)this.highWaterMark=o;else if(a&&(u||u===0))this.highWaterMark=u;else this.highWaterMark=c;this.highWaterMark=Math.floor(this.highWaterMark);this.buffer=new _;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.destroyed=false;this.defaultEncoding=e.defaultEncoding||"utf8";this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(e.encoding){if(!y)y=r(6224).s;this.decoder=new y(e.encoding);this.encoding=e.encoding}}function Readable(e){s=s||r(8393);if(!(this instanceof Readable))return new Readable(e);this._readableState=new ReadableState(e,this);this.readable=true;if(e){if(typeof e.read==="function")this._read=e.read;if(typeof e.destroy==="function")this._destroy=e.destroy}c.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{get:function(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function(e){if(!this._readableState){return}this._readableState.destroyed=e}});Readable.prototype.destroy=g.destroy;Readable.prototype._undestroy=g.undestroy;Readable.prototype._destroy=function(e,t){this.push(null);t(e)};Readable.prototype.push=function(e,t){var r=this._readableState;var a;if(!r.objectMode){if(typeof e==="string"){t=t||r.defaultEncoding;if(t!==r.encoding){e=d.from(e,t);t=""}a=true}}else{a=true}return readableAddChunk(this,e,t,false,a)};Readable.prototype.unshift=function(e){return readableAddChunk(this,e,null,true,false)};function readableAddChunk(e,t,r,a,o){var s=e._readableState;if(t===null){s.reading=false;onEofChunk(e,s)}else{var u;if(!o)u=chunkInvalid(s,t);if(u){e.emit("error",u)}else if(s.objectMode||t&&t.length>0){if(typeof t!=="string"&&!s.objectMode&&Object.getPrototypeOf(t)!==d.prototype){t=_uint8ArrayToBuffer(t)}if(a){if(s.endEmitted)e.emit("error",new Error("stream.unshift() after end event"));else addChunk(e,s,t,true)}else if(s.ended){e.emit("error",new Error("stream.push() after EOF"))}else{s.reading=false;if(s.decoder&&!r){t=s.decoder.write(t);if(s.objectMode||t.length!==0)addChunk(e,s,t,false);else maybeReadMore(e,s)}else{addChunk(e,s,t,false)}}}else if(!a){s.reading=false}}return needMoreData(s)}function addChunk(e,t,r,a){if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(a)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)emitReadable(e)}maybeReadMore(e,t)}function chunkInvalid(e,t){var r;if(!_isUint8Array(t)&&typeof t!=="string"&&t!==undefined&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function needMoreData(e){return!e.ended&&(e.needReadable||e.length=w){e=w}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function howMuchToRead(e,t){if(e<=0||t.length===0&&t.ended)return 0;if(t.objectMode)return 1;if(e!==e){if(t.flowing&&t.length)return t.buffer.head.data.length;else return t.length}if(e>t.highWaterMark)t.highWaterMark=computeNewHighWaterMark(e);if(e<=t.length)return e;if(!t.ended){t.needReadable=true;return 0}return t.length}Readable.prototype.read=function(e){v("read",e);e=parseInt(e,10);var t=this._readableState;var r=e;if(e!==0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){v("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)endReadable(this);else emitReadable(this);return null}e=howMuchToRead(e,t);if(e===0&&t.ended){if(t.length===0)endReadable(this);return null}var a=t.needReadable;v("need readable",a);if(t.length===0||t.length-e0)o=fromList(e,t);else o=null;if(o===null){t.needReadable=true;e=0}else{t.length-=e}if(t.length===0){if(!t.ended)t.needReadable=true;if(r!==e&&t.ended)endReadable(this)}if(o!==null)this.emit("data",o);return o};function onEofChunk(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;emitReadable(e)}function emitReadable(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){v("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)a.nextTick(emitReadable_,e);else emitReadable_(e)}}function emitReadable_(e){v("emit readable");e.emit("readable");flow(e)}function maybeReadMore(e,t){if(!t.readingMore){t.readingMore=true;a.nextTick(maybeReadMore_,e,t)}}function maybeReadMore_(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length1&&indexOf(o.pipes,e)!==-1)&&!d){v("false write response, pause",r._readableState.awaitDrain);r._readableState.awaitDrain++;f=true}r.pause()}}function onerror(t){v("onerror",t);unpipe();e.removeListener("error",onerror);if(EElistenerCount(e,"error")===0)e.emit("error",t)}prependListener(e,"error",onerror);function onclose(){e.removeListener("finish",onfinish);unpipe()}e.once("close",onclose);function onfinish(){v("onfinish");e.removeListener("close",onclose);unpipe()}e.once("finish",onfinish);function unpipe(){v("unpipe");r.unpipe(e)}e.emit("pipe",r);if(!o.flowing){v("pipe resume");r.resume()}return e};function pipeOnDrain(e){return function(){var t=e._readableState;v("pipeOnDrain",t.awaitDrain);if(t.awaitDrain)t.awaitDrain--;if(t.awaitDrain===0&&EElistenerCount(e,"data")){t.flowing=true;flow(e)}}}Readable.prototype.unpipe=function(e){var t=this._readableState;var r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1){if(e&&e!==t.pipes)return this;if(!e)e=t.pipes;t.pipes=null;t.pipesCount=0;t.flowing=false;if(e)e.emit("unpipe",this,r);return this}if(!e){var a=t.pipes;var o=t.pipesCount;t.pipes=null;t.pipesCount=0;t.flowing=false;for(var s=0;s=t.length){if(t.decoder)r=t.buffer.join("");else if(t.buffer.length===1)r=t.buffer.head.data;else r=t.buffer.concat(t.length);t.buffer.clear()}else{r=fromListPartial(e,t.buffer,t.decoder)}return r}function fromListPartial(e,t,r){var a;if(es.length?s.length:e;if(u===s.length)o+=s;else o+=s.slice(0,e);e-=u;if(e===0){if(u===s.length){++a;if(r.next)t.head=r.next;else t.head=t.tail=null}else{t.head=r;r.data=s.slice(u)}break}++a}t.length-=a;return o}function copyFromBuffer(e,t){var r=d.allocUnsafe(e);var a=t.head;var o=1;a.data.copy(r);e-=a.data.length;while(a=a.next){var s=a.data;var u=e>s.length?s.length:e;s.copy(r,r.length-e,0,u);e-=u;if(e===0){if(u===s.length){++o;if(a.next)t.head=a.next;else t.head=t.tail=null}else{t.head=a;a.data=s.slice(u)}break}++o}t.length-=o;return r}function endReadable(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!t.endEmitted){t.ended=true;a.nextTick(endReadableNT,t,e)}}function endReadableNT(e,t){if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end")}}function indexOf(e,t){for(var r=0,a=e.length;r{"use strict";e.exports=Transform;var a=r(8393);var o=Object.create(r(3487));o.inherits=r(6919);o.inherits(Transform,a);function afterTransform(e,t){var r=this._transformState;r.transforming=false;var a=r.writecb;if(!a){return this.emit("error",new Error("write callback called multiple times"))}r.writechunk=null;r.writecb=null;if(t!=null)this.push(t);a(e);var o=this._readableState;o.reading=false;if(o.needReadable||o.length{"use strict";var a=r(7843);e.exports=Writable;function WriteReq(e,t,r){this.chunk=e;this.encoding=t;this.callback=r;this.next=null}function CorkedRequest(e){var t=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(t,e)}}var o=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:a.nextTick;var s;Writable.WritableState=WritableState;var u=Object.create(r(3487));u.inherits=r(6919);var c={deprecate:r(9209)};var d=r(5016);var f=r(4810).Buffer;var p=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return f.from(e)}function _isUint8Array(e){return f.isBuffer(e)||e instanceof p}var h=r(3090);u.inherits(Writable,d);function nop(){}function WritableState(e,t){s=s||r(8393);e=e||{};var a=t instanceof s;this.objectMode=!!e.objectMode;if(a)this.objectMode=this.objectMode||!!e.writableObjectMode;var o=e.highWaterMark;var u=e.writableHighWaterMark;var c=this.objectMode?16:16*1024;if(o||o===0)this.highWaterMark=o;else if(a&&(u||u===0))this.highWaterMark=u;else this.highWaterMark=c;this.highWaterMark=Math.floor(this.highWaterMark);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;var d=e.decodeStrings===false;this.decodeStrings=!d;this.defaultEncoding=e.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(e){onwrite(t,e)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var e=this.bufferedRequest;var t=[];while(e){t.push(e);e=e.next}return t};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:c.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}catch(e){}})();var v;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){v=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(e){if(v.call(this,e))return true;if(this!==Writable)return false;return e&&e._writableState instanceof WritableState}})}else{v=function(e){return e instanceof this}}function Writable(e){s=s||r(8393);if(!v.call(Writable,this)&&!(this instanceof s)){return new Writable(e)}this._writableState=new WritableState(e,this);this.writable=true;if(e){if(typeof e.write==="function")this._write=e.write;if(typeof e.writev==="function")this._writev=e.writev;if(typeof e.destroy==="function")this._destroy=e.destroy;if(typeof e.final==="function")this._final=e.final}d.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(e,t){var r=new Error("write after end");e.emit("error",r);a.nextTick(t,r)}function validChunk(e,t,r,o){var s=true;var u=false;if(r===null){u=new TypeError("May not write null values to stream")}else if(typeof r!=="string"&&r!==undefined&&!t.objectMode){u=new TypeError("Invalid non-string/buffer chunk")}if(u){e.emit("error",u);a.nextTick(o,u);s=false}return s}Writable.prototype.write=function(e,t,r){var a=this._writableState;var o=false;var s=!a.objectMode&&_isUint8Array(e);if(s&&!f.isBuffer(e)){e=_uint8ArrayToBuffer(e)}if(typeof t==="function"){r=t;t=null}if(s)t="buffer";else if(!t)t=a.defaultEncoding;if(typeof r!=="function")r=nop;if(a.ended)writeAfterEnd(this,r);else if(s||validChunk(this,a,e,r)){a.pendingcb++;o=writeOrBuffer(this,a,s,e,t,r)}return o};Writable.prototype.cork=function(){var e=this._writableState;e.corked++};Writable.prototype.uncork=function(){var e=this._writableState;if(e.corked){e.corked--;if(!e.writing&&!e.corked&&!e.finished&&!e.bufferProcessing&&e.bufferedRequest)clearBuffer(this,e)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(e){if(typeof e==="string")e=e.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e;return this};function decodeChunk(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=f.from(t,r)}return t}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function writeOrBuffer(e,t,r,a,o,s){if(!r){var u=decodeChunk(t,a,o);if(a!==u){r=true;o="buffer";a=u}}var c=t.objectMode?1:a.length;t.length+=c;var d=t.length{"use strict";function _classCallCheck(e,t){if(!(e instanceof t)){throw new TypeError("Cannot call a class as a function")}}var a=r(4810).Buffer;var o=r(3837);function copyBuffer(e,t,r){e.copy(t,r)}e.exports=function(){function BufferList(){_classCallCheck(this,BufferList);this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function push(e){var t={data:e,next:null};if(this.length>0)this.tail.next=t;else this.head=t;this.tail=t;++this.length};BufferList.prototype.unshift=function unshift(e){var t={data:e,next:this.head};if(this.length===0)this.tail=t;this.head=t;++this.length};BufferList.prototype.shift=function shift(){if(this.length===0)return;var e=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return e};BufferList.prototype.clear=function clear(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function join(e){if(this.length===0)return"";var t=this.head;var r=""+t.data;while(t=t.next){r+=e+t.data}return r};BufferList.prototype.concat=function concat(e){if(this.length===0)return a.alloc(0);if(this.length===1)return this.head.data;var t=a.allocUnsafe(e>>>0);var r=this.head;var o=0;while(r){copyBuffer(r.data,t,o);o+=r.data.length;r=r.next}return t};return BufferList}();if(o&&o.inspect&&o.inspect.custom){e.exports.prototype[o.inspect.custom]=function(){var e=o.inspect({length:this.length});return this.constructor.name+" "+e}}},3090:(e,t,r)=>{"use strict";var a=r(7843);function destroy(e,t){var r=this;var o=this._readableState&&this._readableState.destroyed;var s=this._writableState&&this._writableState.destroyed;if(o||s){if(t){t(e)}else if(e&&(!this._writableState||!this._writableState.errorEmitted)){a.nextTick(emitErrorNT,this,e)}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(e||null,(function(e){if(!t&&e){a.nextTick(emitErrorNT,r,e);if(r._writableState){r._writableState.errorEmitted=true}}else if(t){t(e)}}));return this}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(e,t){e.emit("error",t)}e.exports={destroy:destroy,undestroy:undestroy}},5016:(e,t,r)=>{e.exports=r(2781)},4810:(e,t,r)=>{var a=r(4300);var o=a.Buffer;function copyProps(e,t){for(var r in e){t[r]=e[r]}}if(o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow){e.exports=a}else{copyProps(a,t);t.Buffer=SafeBuffer}function SafeBuffer(e,t,r){return o(e,t,r)}copyProps(o,SafeBuffer);SafeBuffer.from=function(e,t,r){if(typeof e==="number"){throw new TypeError("Argument must not be a number")}return o(e,t,r)};SafeBuffer.alloc=function(e,t,r){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}var a=o(e);if(t!==undefined){if(typeof r==="string"){a.fill(t,r)}else{a.fill(t)}}else{a.fill(0)}return a};SafeBuffer.allocUnsafe=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return o(e)};SafeBuffer.allocUnsafeSlow=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return a.SlowBuffer(e)}},6224:(e,t,r)=>{"use strict";var a=r(4810).Buffer;var o=a.isEncoding||function(e){e=""+e;switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function _normalizeEncoding(e){if(!e)return"utf8";var t;while(true){switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase();t=true}}}function normalizeEncoding(e){var t=_normalizeEncoding(e);if(typeof t!=="string"&&(a.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}t.s=StringDecoder;function StringDecoder(e){this.encoding=normalizeEncoding(e);var t;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;t=4;break;case"utf8":this.fillLast=utf8FillLast;t=4;break;case"base64":this.text=base64Text;this.end=base64End;t=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=a.allocUnsafe(t)}StringDecoder.prototype.write=function(e){if(e.length===0)return"";var t;var r;if(this.lastNeed){t=this.fillLast(e);if(t===undefined)return"";r=this.lastNeed;this.lastNeed=0}else{r=0}if(r>5===6)return 2;else if(e>>4===14)return 3;else if(e>>3===30)return 4;return e>>6===2?-1:-2}function utf8CheckIncomplete(e,t,r){var a=t.length-1;if(a=0){if(o>0)e.lastNeed=o-1;return o}if(--a=0){if(o>0)e.lastNeed=o-2;return o}if(--a=0){if(o>0){if(o===2)o=0;else e.lastNeed=o-3}return o}return 0}function utf8CheckExtraBytes(e,t,r){if((t[0]&192)!==128){e.lastNeed=0;return"�"}if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128){e.lastNeed=1;return"�"}if(e.lastNeed>2&&t.length>2){if((t[2]&192)!==128){e.lastNeed=2;return"�"}}}}function utf8FillLast(e){var t=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,e,t);if(r!==undefined)return r;if(this.lastNeed<=e.length){e.copy(this.lastChar,t,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}e.copy(this.lastChar,t,0,e.length);this.lastNeed-=e.length}function utf8Text(e,t){var r=utf8CheckIncomplete(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var a=e.length-(r-this.lastNeed);e.copy(this.lastChar,0,a);return e.toString("utf8",t,a)}function utf8End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+"�";return t}function utf16Text(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var a=r.charCodeAt(r.length-1);if(a>=55296&&a<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=e[e.length-1];return e.toString("utf16le",t,e.length-1)}function utf16End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function base64Text(e,t){var r=(e.length-t)%3;if(r===0)return e.toString("base64",t);this.lastNeed=3-r;this.lastTotal=3;if(r===1){this.lastChar[0]=e[e.length-1]}else{this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1]}return e.toString("base64",t,e.length-r)}function base64End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+this.lastChar.toString("base64",0,3-this.lastNeed);return t}function simpleWrite(e){return e.toString(this.encoding)}function simpleEnd(e){return e&&e.length?this.write(e):""}},675:(e,t,r)=>{var a=r(2781);if(process.env.READABLE_STREAM==="disable"&&a){e.exports=a;t=e.exports=a.Readable;t.Readable=a.Readable;t.Writable=a.Writable;t.Duplex=a.Duplex;t.Transform=a.Transform;t.PassThrough=a.PassThrough;t.Stream=a}else{t=e.exports=r(284);t.Stream=a||t;t.Readable=t;t.Writable=r(6100);t.Duplex=r(8393);t.Transform=r(5469);t.PassThrough=r(5125)}},2753:(e,t,r)=>{"use strict";const a=r(1017);const o=r(8188);const s=r(7147);const resolveFrom=(e,t,r)=>{if(typeof e!=="string"){throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof e}\``)}if(typeof t!=="string"){throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof t}\``)}try{e=s.realpathSync(e)}catch(t){if(t.code==="ENOENT"){e=a.resolve(e)}else if(r){return}else{throw t}}const u=a.join(e,"noop.js");const resolveFileName=()=>o._resolveFilename(t,{id:u,filename:u,paths:o._nodeModulePaths(e)});if(r){try{return resolveFileName()}catch(e){return}}return resolveFileName()};e.exports=(e,t)=>resolveFrom(e,t);e.exports.silent=(e,t)=>resolveFrom(e,t,true)},7586:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});function _interopDefault(e){return e&&typeof e==="object"&&"default"in e?e["default"]:e}var a=r(1017);var o=_interopDefault(a);var s=r(619);var u=_interopDefault(r(3837));const c=function addExtension(e,t=".js"){if(!a.extname(e))e+=t;return e};const d={ArrayPattern(e,t){for(const r of t.elements){if(r)d[r.type](e,r)}},AssignmentPattern(e,t){d[t.left.type](e,t.left)},Identifier(e,t){e.push(t.name)},MemberExpression(){},ObjectPattern(e,t){for(const r of t.properties){if(r.type==="RestElement"){d.RestElement(e,r)}else{d[r.value.type](e,r.value)}}},RestElement(e,t){d[t.argument.type](e,t.argument)}};const f=function extractAssignedNames(e){const t=[];d[e.type](t,e);return t};const p={const:true,let:true};class Scope{constructor(e={}){this.parent=e.parent;this.isBlockScope=!!e.block;this.declarations=Object.create(null);if(e.params){e.params.forEach((e=>{f(e).forEach((e=>{this.declarations[e]=true}))}))}}addDeclaration(e,t,r){if(!t&&this.isBlockScope){this.parent.addDeclaration(e,t,r)}else if(e.id){f(e.id).forEach((e=>{this.declarations[e]=true}))}}contains(e){return this.declarations[e]||(this.parent?this.parent.contains(e):false)}}const h=function attachScopes(e,t="scope"){let r=new Scope;s.walk(e,{enter(e,a){if(/(Function|Class)Declaration/.test(e.type)){r.addDeclaration(e,false,false)}if(e.type==="VariableDeclaration"){const t=e.kind;const a=p[t];e.declarations.forEach((e=>{r.addDeclaration(e,a,true)}))}let o;if(/Function/.test(e.type)){o=new Scope({parent:r,block:false,params:e.params});if(e.type==="FunctionExpression"&&e.id){o.addDeclaration(e,false,false)}}if(e.type==="BlockStatement"&&!/Function/.test(a.type)){o=new Scope({parent:r,block:true})}if(e.type==="CatchClause"){o=new Scope({parent:r,params:e.param?[e.param]:[],block:true})}if(o){Object.defineProperty(e,t,{value:o,configurable:true});r=o}},leave(e){if(e[t])r=r.parent}});return r};function createCommonjsModule(e,t){return t={exports:{}},e(t,t.exports),t.exports}var v=createCommonjsModule((function(e,t){t.isInteger=e=>{if(typeof e==="number"){return Number.isInteger(e)}if(typeof e==="string"&&e.trim()!==""){return Number.isInteger(Number(e))}return false};t.find=(e,t)=>e.nodes.find((e=>e.type===t));t.exceedsLimit=(e,r,a=1,o)=>{if(o===false)return false;if(!t.isInteger(e)||!t.isInteger(r))return false;return(Number(r)-Number(e))/Number(a)>=o};t.escapeNode=(e,t=0,r)=>{let a=e.nodes[t];if(!a)return;if(r&&a.type===r||a.type==="open"||a.type==="close"){if(a.escaped!==true){a.value="\\"+a.value;a.escaped=true}}};t.encloseBrace=e=>{if(e.type!=="brace")return false;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}return false};t.isInvalidBrace=e=>{if(e.type!=="brace")return false;if(e.invalid===true||e.dollar)return true;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}if(e.open!==true||e.close!==true){e.invalid=true;return true}return false};t.isOpenOrClose=e=>{if(e.type==="open"||e.type==="close"){return true}return e.open===true||e.close===true};t.reduce=e=>e.reduce(((e,t)=>{if(t.type==="text")e.push(t.value);if(t.type==="range")t.type="text";return e}),[]);t.flatten=(...e)=>{const t=[];const flat=e=>{for(let r=0;r{let stringify=(e,r={})=>{let a=t.escapeInvalid&&v.isInvalidBrace(r);let o=e.invalid===true&&t.escapeInvalid===true;let s="";if(e.value){if((a||o)&&v.isOpenOrClose(e)){return"\\"+e.value}return e.value}if(e.value){return e.value}if(e.nodes){for(let t of e.nodes){s+=stringify(t)}}return s};return stringify(e)}; +*/var t=Object.getOwnPropertySymbols;var r=Object.prototype.hasOwnProperty;var s=Object.prototype.propertyIsEnumerable;function toObject(e){if(e===null||e===undefined){throw new TypeError("Object.assign cannot be called with null or undefined")}return Object(e)}function shouldUseNative(){try{if(!Object.assign){return false}var e=new String("abc");e[5]="de";if(Object.getOwnPropertyNames(e)[0]==="5"){return false}var t={};for(var r=0;r<10;r++){t["_"+String.fromCharCode(r)]=r}var s=Object.getOwnPropertyNames(t).map((function(e){return t[e]}));if(s.join("")!=="0123456789"){return false}var a={};"abcdefghijklmnopqrst".split("").forEach((function(e){a[e]=e}));if(Object.keys(Object.assign({},a)).join("")!=="abcdefghijklmnopqrst"){return false}return true}catch(e){return false}}e.exports=shouldUseNative()?Object.assign:function(e,a){var o;var u=toObject(e);var c;for(var f=1;f{"use strict";if(typeof process==="undefined"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){e.exports={nextTick:nextTick}}else{e.exports=process}function nextTick(e,t,r,s){if(typeof e!=="function"){throw new TypeError('"callback" argument must be a function')}var a=arguments.length;var o,u;switch(a){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick((function afterTickOne(){e.call(null,t)}));case 3:return process.nextTick((function afterTickTwo(){e.call(null,t,r)}));case 4:return process.nextTick((function afterTickThree(){e.call(null,t,r,s)}));default:o=new Array(a-1);u=0;while(u{"use strict";var s=r(7843);var a=Object.keys||function(e){var t=[];for(var r in e){t.push(r)}return t};e.exports=Duplex;var o=Object.create(r(3487));o.inherits=r(6919);var u=r(284);var c=r(6100);o.inherits(Duplex,u);{var f=a(c.prototype);for(var p=0;p{"use strict";e.exports=PassThrough;var s=r(5469);var a=Object.create(r(3487));a.inherits=r(6919);a.inherits(PassThrough,s);function PassThrough(e){if(!(this instanceof PassThrough))return new PassThrough(e);s.call(this,e)}PassThrough.prototype._transform=function(e,t,r){r(null,e)}},284:(e,t,r)=>{"use strict";var s=r(7843);e.exports=Readable;var a=r(9842);var o;Readable.ReadableState=ReadableState;var u=r(2361).EventEmitter;var EElistenerCount=function(e,t){return e.listeners(t).length};var c=r(5016);var f=r(4810).Buffer;var p=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return f.from(e)}function _isUint8Array(e){return f.isBuffer(e)||e instanceof p}var d=Object.create(r(3487));d.inherits=r(6919);var h=r(3837);var v=void 0;if(h&&h.debuglog){v=h.debuglog("stream")}else{v=function(){}}var g=r(8739);var m=r(3090);var _;d.inherits(Readable,c);var y=["error","close","destroy","pause","resume"];function prependListener(e,t,r){if(typeof e.prependListener==="function")return e.prependListener(t,r);if(!e._events||!e._events[t])e.on(t,r);else if(a(e._events[t]))e._events[t].unshift(r);else e._events[t]=[r,e._events[t]]}function ReadableState(e,t){o=o||r(8393);e=e||{};var s=t instanceof o;this.objectMode=!!e.objectMode;if(s)this.objectMode=this.objectMode||!!e.readableObjectMode;var a=e.highWaterMark;var u=e.readableHighWaterMark;var c=this.objectMode?16:16*1024;if(a||a===0)this.highWaterMark=a;else if(s&&(u||u===0))this.highWaterMark=u;else this.highWaterMark=c;this.highWaterMark=Math.floor(this.highWaterMark);this.buffer=new g;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.destroyed=false;this.defaultEncoding=e.defaultEncoding||"utf8";this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(e.encoding){if(!_)_=r(6224).s;this.decoder=new _(e.encoding);this.encoding=e.encoding}}function Readable(e){o=o||r(8393);if(!(this instanceof Readable))return new Readable(e);this._readableState=new ReadableState(e,this);this.readable=true;if(e){if(typeof e.read==="function")this._read=e.read;if(typeof e.destroy==="function")this._destroy=e.destroy}c.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{get:function(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function(e){if(!this._readableState){return}this._readableState.destroyed=e}});Readable.prototype.destroy=m.destroy;Readable.prototype._undestroy=m.undestroy;Readable.prototype._destroy=function(e,t){this.push(null);t(e)};Readable.prototype.push=function(e,t){var r=this._readableState;var s;if(!r.objectMode){if(typeof e==="string"){t=t||r.defaultEncoding;if(t!==r.encoding){e=f.from(e,t);t=""}s=true}}else{s=true}return readableAddChunk(this,e,t,false,s)};Readable.prototype.unshift=function(e){return readableAddChunk(this,e,null,true,false)};function readableAddChunk(e,t,r,s,a){var o=e._readableState;if(t===null){o.reading=false;onEofChunk(e,o)}else{var u;if(!a)u=chunkInvalid(o,t);if(u){e.emit("error",u)}else if(o.objectMode||t&&t.length>0){if(typeof t!=="string"&&!o.objectMode&&Object.getPrototypeOf(t)!==f.prototype){t=_uint8ArrayToBuffer(t)}if(s){if(o.endEmitted)e.emit("error",new Error("stream.unshift() after end event"));else addChunk(e,o,t,true)}else if(o.ended){e.emit("error",new Error("stream.push() after EOF"))}else{o.reading=false;if(o.decoder&&!r){t=o.decoder.write(t);if(o.objectMode||t.length!==0)addChunk(e,o,t,false);else maybeReadMore(e,o)}else{addChunk(e,o,t,false)}}}else if(!s){o.reading=false}}return needMoreData(o)}function addChunk(e,t,r,s){if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(s)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)emitReadable(e)}maybeReadMore(e,t)}function chunkInvalid(e,t){var r;if(!_isUint8Array(t)&&typeof t!=="string"&&t!==undefined&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function needMoreData(e){return!e.ended&&(e.needReadable||e.length=x){e=x}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function howMuchToRead(e,t){if(e<=0||t.length===0&&t.ended)return 0;if(t.objectMode)return 1;if(e!==e){if(t.flowing&&t.length)return t.buffer.head.data.length;else return t.length}if(e>t.highWaterMark)t.highWaterMark=computeNewHighWaterMark(e);if(e<=t.length)return e;if(!t.ended){t.needReadable=true;return 0}return t.length}Readable.prototype.read=function(e){v("read",e);e=parseInt(e,10);var t=this._readableState;var r=e;if(e!==0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){v("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)endReadable(this);else emitReadable(this);return null}e=howMuchToRead(e,t);if(e===0&&t.ended){if(t.length===0)endReadable(this);return null}var s=t.needReadable;v("need readable",s);if(t.length===0||t.length-e0)a=fromList(e,t);else a=null;if(a===null){t.needReadable=true;e=0}else{t.length-=e}if(t.length===0){if(!t.ended)t.needReadable=true;if(r!==e&&t.ended)endReadable(this)}if(a!==null)this.emit("data",a);return a};function onEofChunk(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;emitReadable(e)}function emitReadable(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){v("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)s.nextTick(emitReadable_,e);else emitReadable_(e)}}function emitReadable_(e){v("emit readable");e.emit("readable");flow(e)}function maybeReadMore(e,t){if(!t.readingMore){t.readingMore=true;s.nextTick(maybeReadMore_,e,t)}}function maybeReadMore_(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length1&&indexOf(a.pipes,e)!==-1)&&!f){v("false write response, pause",r._readableState.awaitDrain);r._readableState.awaitDrain++;p=true}r.pause()}}function onerror(t){v("onerror",t);unpipe();e.removeListener("error",onerror);if(EElistenerCount(e,"error")===0)e.emit("error",t)}prependListener(e,"error",onerror);function onclose(){e.removeListener("finish",onfinish);unpipe()}e.once("close",onclose);function onfinish(){v("onfinish");e.removeListener("close",onclose);unpipe()}e.once("finish",onfinish);function unpipe(){v("unpipe");r.unpipe(e)}e.emit("pipe",r);if(!a.flowing){v("pipe resume");r.resume()}return e};function pipeOnDrain(e){return function(){var t=e._readableState;v("pipeOnDrain",t.awaitDrain);if(t.awaitDrain)t.awaitDrain--;if(t.awaitDrain===0&&EElistenerCount(e,"data")){t.flowing=true;flow(e)}}}Readable.prototype.unpipe=function(e){var t=this._readableState;var r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1){if(e&&e!==t.pipes)return this;if(!e)e=t.pipes;t.pipes=null;t.pipesCount=0;t.flowing=false;if(e)e.emit("unpipe",this,r);return this}if(!e){var s=t.pipes;var a=t.pipesCount;t.pipes=null;t.pipesCount=0;t.flowing=false;for(var o=0;o=t.length){if(t.decoder)r=t.buffer.join("");else if(t.buffer.length===1)r=t.buffer.head.data;else r=t.buffer.concat(t.length);t.buffer.clear()}else{r=fromListPartial(e,t.buffer,t.decoder)}return r}function fromListPartial(e,t,r){var s;if(eo.length?o.length:e;if(u===o.length)a+=o;else a+=o.slice(0,e);e-=u;if(e===0){if(u===o.length){++s;if(r.next)t.head=r.next;else t.head=t.tail=null}else{t.head=r;r.data=o.slice(u)}break}++s}t.length-=s;return a}function copyFromBuffer(e,t){var r=f.allocUnsafe(e);var s=t.head;var a=1;s.data.copy(r);e-=s.data.length;while(s=s.next){var o=s.data;var u=e>o.length?o.length:e;o.copy(r,r.length-e,0,u);e-=u;if(e===0){if(u===o.length){++a;if(s.next)t.head=s.next;else t.head=t.tail=null}else{t.head=s;s.data=o.slice(u)}break}++a}t.length-=a;return r}function endReadable(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!t.endEmitted){t.ended=true;s.nextTick(endReadableNT,t,e)}}function endReadableNT(e,t){if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end")}}function indexOf(e,t){for(var r=0,s=e.length;r{"use strict";e.exports=Transform;var s=r(8393);var a=Object.create(r(3487));a.inherits=r(6919);a.inherits(Transform,s);function afterTransform(e,t){var r=this._transformState;r.transforming=false;var s=r.writecb;if(!s){return this.emit("error",new Error("write callback called multiple times"))}r.writechunk=null;r.writecb=null;if(t!=null)this.push(t);s(e);var a=this._readableState;a.reading=false;if(a.needReadable||a.length{"use strict";var s=r(7843);e.exports=Writable;function WriteReq(e,t,r){this.chunk=e;this.encoding=t;this.callback=r;this.next=null}function CorkedRequest(e){var t=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(t,e)}}var a=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:s.nextTick;var o;Writable.WritableState=WritableState;var u=Object.create(r(3487));u.inherits=r(6919);var c={deprecate:r(9209)};var f=r(5016);var p=r(4810).Buffer;var d=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return p.from(e)}function _isUint8Array(e){return p.isBuffer(e)||e instanceof d}var h=r(3090);u.inherits(Writable,f);function nop(){}function WritableState(e,t){o=o||r(8393);e=e||{};var s=t instanceof o;this.objectMode=!!e.objectMode;if(s)this.objectMode=this.objectMode||!!e.writableObjectMode;var a=e.highWaterMark;var u=e.writableHighWaterMark;var c=this.objectMode?16:16*1024;if(a||a===0)this.highWaterMark=a;else if(s&&(u||u===0))this.highWaterMark=u;else this.highWaterMark=c;this.highWaterMark=Math.floor(this.highWaterMark);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;var f=e.decodeStrings===false;this.decodeStrings=!f;this.defaultEncoding=e.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(e){onwrite(t,e)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var e=this.bufferedRequest;var t=[];while(e){t.push(e);e=e.next}return t};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:c.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}catch(e){}})();var v;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){v=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(e){if(v.call(this,e))return true;if(this!==Writable)return false;return e&&e._writableState instanceof WritableState}})}else{v=function(e){return e instanceof this}}function Writable(e){o=o||r(8393);if(!v.call(Writable,this)&&!(this instanceof o)){return new Writable(e)}this._writableState=new WritableState(e,this);this.writable=true;if(e){if(typeof e.write==="function")this._write=e.write;if(typeof e.writev==="function")this._writev=e.writev;if(typeof e.destroy==="function")this._destroy=e.destroy;if(typeof e.final==="function")this._final=e.final}f.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(e,t){var r=new Error("write after end");e.emit("error",r);s.nextTick(t,r)}function validChunk(e,t,r,a){var o=true;var u=false;if(r===null){u=new TypeError("May not write null values to stream")}else if(typeof r!=="string"&&r!==undefined&&!t.objectMode){u=new TypeError("Invalid non-string/buffer chunk")}if(u){e.emit("error",u);s.nextTick(a,u);o=false}return o}Writable.prototype.write=function(e,t,r){var s=this._writableState;var a=false;var o=!s.objectMode&&_isUint8Array(e);if(o&&!p.isBuffer(e)){e=_uint8ArrayToBuffer(e)}if(typeof t==="function"){r=t;t=null}if(o)t="buffer";else if(!t)t=s.defaultEncoding;if(typeof r!=="function")r=nop;if(s.ended)writeAfterEnd(this,r);else if(o||validChunk(this,s,e,r)){s.pendingcb++;a=writeOrBuffer(this,s,o,e,t,r)}return a};Writable.prototype.cork=function(){var e=this._writableState;e.corked++};Writable.prototype.uncork=function(){var e=this._writableState;if(e.corked){e.corked--;if(!e.writing&&!e.corked&&!e.finished&&!e.bufferProcessing&&e.bufferedRequest)clearBuffer(this,e)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(e){if(typeof e==="string")e=e.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e;return this};function decodeChunk(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=p.from(t,r)}return t}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function writeOrBuffer(e,t,r,s,a,o){if(!r){var u=decodeChunk(t,s,a);if(s!==u){r=true;a="buffer";s=u}}var c=t.objectMode?1:s.length;t.length+=c;var f=t.length{"use strict";function _classCallCheck(e,t){if(!(e instanceof t)){throw new TypeError("Cannot call a class as a function")}}var s=r(4810).Buffer;var a=r(3837);function copyBuffer(e,t,r){e.copy(t,r)}e.exports=function(){function BufferList(){_classCallCheck(this,BufferList);this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function push(e){var t={data:e,next:null};if(this.length>0)this.tail.next=t;else this.head=t;this.tail=t;++this.length};BufferList.prototype.unshift=function unshift(e){var t={data:e,next:this.head};if(this.length===0)this.tail=t;this.head=t;++this.length};BufferList.prototype.shift=function shift(){if(this.length===0)return;var e=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return e};BufferList.prototype.clear=function clear(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function join(e){if(this.length===0)return"";var t=this.head;var r=""+t.data;while(t=t.next){r+=e+t.data}return r};BufferList.prototype.concat=function concat(e){if(this.length===0)return s.alloc(0);if(this.length===1)return this.head.data;var t=s.allocUnsafe(e>>>0);var r=this.head;var a=0;while(r){copyBuffer(r.data,t,a);a+=r.data.length;r=r.next}return t};return BufferList}();if(a&&a.inspect&&a.inspect.custom){e.exports.prototype[a.inspect.custom]=function(){var e=a.inspect({length:this.length});return this.constructor.name+" "+e}}},3090:(e,t,r)=>{"use strict";var s=r(7843);function destroy(e,t){var r=this;var a=this._readableState&&this._readableState.destroyed;var o=this._writableState&&this._writableState.destroyed;if(a||o){if(t){t(e)}else if(e&&(!this._writableState||!this._writableState.errorEmitted)){s.nextTick(emitErrorNT,this,e)}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(e||null,(function(e){if(!t&&e){s.nextTick(emitErrorNT,r,e);if(r._writableState){r._writableState.errorEmitted=true}}else if(t){t(e)}}));return this}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(e,t){e.emit("error",t)}e.exports={destroy:destroy,undestroy:undestroy}},5016:(e,t,r)=>{e.exports=r(2781)},4810:(e,t,r)=>{var s=r(4300);var a=s.Buffer;function copyProps(e,t){for(var r in e){t[r]=e[r]}}if(a.from&&a.alloc&&a.allocUnsafe&&a.allocUnsafeSlow){e.exports=s}else{copyProps(s,t);t.Buffer=SafeBuffer}function SafeBuffer(e,t,r){return a(e,t,r)}copyProps(a,SafeBuffer);SafeBuffer.from=function(e,t,r){if(typeof e==="number"){throw new TypeError("Argument must not be a number")}return a(e,t,r)};SafeBuffer.alloc=function(e,t,r){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}var s=a(e);if(t!==undefined){if(typeof r==="string"){s.fill(t,r)}else{s.fill(t)}}else{s.fill(0)}return s};SafeBuffer.allocUnsafe=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return a(e)};SafeBuffer.allocUnsafeSlow=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return s.SlowBuffer(e)}},6224:(e,t,r)=>{"use strict";var s=r(4810).Buffer;var a=s.isEncoding||function(e){e=""+e;switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function _normalizeEncoding(e){if(!e)return"utf8";var t;while(true){switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase();t=true}}}function normalizeEncoding(e){var t=_normalizeEncoding(e);if(typeof t!=="string"&&(s.isEncoding===a||!a(e)))throw new Error("Unknown encoding: "+e);return t||e}t.s=StringDecoder;function StringDecoder(e){this.encoding=normalizeEncoding(e);var t;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;t=4;break;case"utf8":this.fillLast=utf8FillLast;t=4;break;case"base64":this.text=base64Text;this.end=base64End;t=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=s.allocUnsafe(t)}StringDecoder.prototype.write=function(e){if(e.length===0)return"";var t;var r;if(this.lastNeed){t=this.fillLast(e);if(t===undefined)return"";r=this.lastNeed;this.lastNeed=0}else{r=0}if(r>5===6)return 2;else if(e>>4===14)return 3;else if(e>>3===30)return 4;return e>>6===2?-1:-2}function utf8CheckIncomplete(e,t,r){var s=t.length-1;if(s=0){if(a>0)e.lastNeed=a-1;return a}if(--s=0){if(a>0)e.lastNeed=a-2;return a}if(--s=0){if(a>0){if(a===2)a=0;else e.lastNeed=a-3}return a}return 0}function utf8CheckExtraBytes(e,t,r){if((t[0]&192)!==128){e.lastNeed=0;return"�"}if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128){e.lastNeed=1;return"�"}if(e.lastNeed>2&&t.length>2){if((t[2]&192)!==128){e.lastNeed=2;return"�"}}}}function utf8FillLast(e){var t=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,e,t);if(r!==undefined)return r;if(this.lastNeed<=e.length){e.copy(this.lastChar,t,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}e.copy(this.lastChar,t,0,e.length);this.lastNeed-=e.length}function utf8Text(e,t){var r=utf8CheckIncomplete(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var s=e.length-(r-this.lastNeed);e.copy(this.lastChar,0,s);return e.toString("utf8",t,s)}function utf8End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+"�";return t}function utf16Text(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var s=r.charCodeAt(r.length-1);if(s>=55296&&s<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=e[e.length-1];return e.toString("utf16le",t,e.length-1)}function utf16End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function base64Text(e,t){var r=(e.length-t)%3;if(r===0)return e.toString("base64",t);this.lastNeed=3-r;this.lastTotal=3;if(r===1){this.lastChar[0]=e[e.length-1]}else{this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1]}return e.toString("base64",t,e.length-r)}function base64End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+this.lastChar.toString("base64",0,3-this.lastNeed);return t}function simpleWrite(e){return e.toString(this.encoding)}function simpleEnd(e){return e&&e.length?this.write(e):""}},675:(e,t,r)=>{var s=r(2781);if(process.env.READABLE_STREAM==="disable"&&s){e.exports=s;t=e.exports=s.Readable;t.Readable=s.Readable;t.Writable=s.Writable;t.Duplex=s.Duplex;t.Transform=s.Transform;t.PassThrough=s.PassThrough;t.Stream=s}else{t=e.exports=r(284);t.Stream=s||t;t.Readable=t;t.Writable=r(6100);t.Duplex=r(8393);t.Transform=r(5469);t.PassThrough=r(5125)}},2753:(e,t,r)=>{"use strict";const s=r(1017);const a=r(8188);const o=r(7147);const resolveFrom=(e,t,r)=>{if(typeof e!=="string"){throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof e}\``)}if(typeof t!=="string"){throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof t}\``)}try{e=o.realpathSync(e)}catch(t){if(t.code==="ENOENT"){e=s.resolve(e)}else if(r){return}else{throw t}}const u=s.join(e,"noop.js");const resolveFileName=()=>a._resolveFilename(t,{id:u,filename:u,paths:a._nodeModulePaths(e)});if(r){try{return resolveFileName()}catch(e){return}}return resolveFileName()};e.exports=(e,t)=>resolveFrom(e,t);e.exports.silent=(e,t)=>resolveFrom(e,t,true)},7586:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});function _interopDefault(e){return e&&typeof e==="object"&&"default"in e?e["default"]:e}var s=r(1017);var a=_interopDefault(s);var o=r(619);var u=_interopDefault(r(3837));const c=function addExtension(e,t=".js"){if(!s.extname(e))e+=t;return e};const f={ArrayPattern(e,t){for(const r of t.elements){if(r)f[r.type](e,r)}},AssignmentPattern(e,t){f[t.left.type](e,t.left)},Identifier(e,t){e.push(t.name)},MemberExpression(){},ObjectPattern(e,t){for(const r of t.properties){if(r.type==="RestElement"){f.RestElement(e,r)}else{f[r.value.type](e,r.value)}}},RestElement(e,t){f[t.argument.type](e,t.argument)}};const p=function extractAssignedNames(e){const t=[];f[e.type](t,e);return t};const d={const:true,let:true};class Scope{constructor(e={}){this.parent=e.parent;this.isBlockScope=!!e.block;this.declarations=Object.create(null);if(e.params){e.params.forEach((e=>{p(e).forEach((e=>{this.declarations[e]=true}))}))}}addDeclaration(e,t,r){if(!t&&this.isBlockScope){this.parent.addDeclaration(e,t,r)}else if(e.id){p(e.id).forEach((e=>{this.declarations[e]=true}))}}contains(e){return this.declarations[e]||(this.parent?this.parent.contains(e):false)}}const h=function attachScopes(e,t="scope"){let r=new Scope;o.walk(e,{enter(e,s){if(/(Function|Class)Declaration/.test(e.type)){r.addDeclaration(e,false,false)}if(e.type==="VariableDeclaration"){const t=e.kind;const s=d[t];e.declarations.forEach((e=>{r.addDeclaration(e,s,true)}))}let a;if(/Function/.test(e.type)){a=new Scope({parent:r,block:false,params:e.params});if(e.type==="FunctionExpression"&&e.id){a.addDeclaration(e,false,false)}}if(e.type==="BlockStatement"&&!/Function/.test(s.type)){a=new Scope({parent:r,block:true})}if(e.type==="CatchClause"){a=new Scope({parent:r,params:e.param?[e.param]:[],block:true})}if(a){Object.defineProperty(e,t,{value:a,configurable:true});r=a}},leave(e){if(e[t])r=r.parent}});return r};function createCommonjsModule(e,t){return t={exports:{}},e(t,t.exports),t.exports}var v=createCommonjsModule((function(e,t){t.isInteger=e=>{if(typeof e==="number"){return Number.isInteger(e)}if(typeof e==="string"&&e.trim()!==""){return Number.isInteger(Number(e))}return false};t.find=(e,t)=>e.nodes.find((e=>e.type===t));t.exceedsLimit=(e,r,s=1,a)=>{if(a===false)return false;if(!t.isInteger(e)||!t.isInteger(r))return false;return(Number(r)-Number(e))/Number(s)>=a};t.escapeNode=(e,t=0,r)=>{let s=e.nodes[t];if(!s)return;if(r&&s.type===r||s.type==="open"||s.type==="close"){if(s.escaped!==true){s.value="\\"+s.value;s.escaped=true}}};t.encloseBrace=e=>{if(e.type!=="brace")return false;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}return false};t.isInvalidBrace=e=>{if(e.type!=="brace")return false;if(e.invalid===true||e.dollar)return true;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}if(e.open!==true||e.close!==true){e.invalid=true;return true}return false};t.isOpenOrClose=e=>{if(e.type==="open"||e.type==="close"){return true}return e.open===true||e.close===true};t.reduce=e=>e.reduce(((e,t)=>{if(t.type==="text")e.push(t.value);if(t.type==="range")t.type="text";return e}),[]);t.flatten=(...e)=>{const t=[];const flat=e=>{for(let r=0;r{let stringify=(e,r={})=>{let s=t.escapeInvalid&&v.isInvalidBrace(r);let a=e.invalid===true&&t.escapeInvalid===true;let o="";if(e.value){if((s||a)&&v.isOpenOrClose(e)){return"\\"+e.value}return e.value}if(e.value){return e.value}if(e.nodes){for(let t of e.nodes){o+=stringify(t)}}return o};return stringify(e)}; /*! * is-number * * Copyright (c) 2014-present, Jon Schlinkert. * Released under the MIT License. - */var isNumber=function(e){if(typeof e==="number"){return e-e===0}if(typeof e==="string"&&e.trim()!==""){return Number.isFinite?Number.isFinite(+e):isFinite(+e)}return false};const toRegexRange=(e,t,r)=>{if(isNumber(e)===false){throw new TypeError("toRegexRange: expected the first argument to be a number")}if(t===void 0||e===t){return String(e)}if(isNumber(t)===false){throw new TypeError("toRegexRange: expected the second argument to be a number.")}let a=Object.assign({relaxZeros:true},r);if(typeof a.strictZeros==="boolean"){a.relaxZeros=a.strictZeros===false}let o=String(a.relaxZeros);let s=String(a.shorthand);let u=String(a.capture);let c=String(a.wrap);let d=e+":"+t+"="+o+s+u+c;if(toRegexRange.cache.hasOwnProperty(d)){return toRegexRange.cache[d].result}let f=Math.min(e,t);let p=Math.max(e,t);if(Math.abs(f-p)===1){let r=e+"|"+t;if(a.capture){return`(${r})`}if(a.wrap===false){return r}return`(?:${r})`}let h=hasPadding(e)||hasPadding(t);let v={min:e,max:t,a:f,b:p};let _=[];let g=[];if(h){v.isPadded=h;v.maxLen=String(v.max).length}if(f<0){let e=p<0?Math.abs(p):1;g=splitToPatterns(e,Math.abs(f),v,a);f=v.a=0}if(p>=0){_=splitToPatterns(f,p,v,a)}v.negatives=g;v.positives=_;v.result=collatePatterns(g,_,a);if(a.capture===true){v.result=`(${v.result})`}else if(a.wrap!==false&&_.length+g.length>1){v.result=`(?:${v.result})`}toRegexRange.cache[d]=v;return v.result};function collatePatterns(e,t,r){let a=filterPatterns(e,t,"-",false,r)||[];let o=filterPatterns(t,e,"",false,r)||[];let s=filterPatterns(e,t,"-?",true,r)||[];let u=a.concat(s).concat(o);return u.join("|")}function splitToRanges(e,t){let r=1;let a=1;let o=countNines(e,r);let s=new Set([t]);while(e<=o&&o<=t){s.add(o);r+=1;o=countNines(e,r)}o=countZeros(t+1,a)-1;while(e1){c.count.pop()}c.count.push(d.count[0]);c.string=c.pattern+toQuantifier(c.count);u=t+1;continue}if(r.isPadded){f=padZeros(t,r,a)}d.string=f+d.pattern+toQuantifier(d.count);s.push(d);u=t+1;c=d}return s}function filterPatterns(e,t,r,a,o){let s=[];for(let o of e){let{string:e}=o;if(!a&&!contains(t,"string",e)){s.push(r+e)}if(a&&contains(t,"string",e)){s.push(r+e)}}return s}function zip(e,t){let r=[];for(let a=0;at?1:t>e?-1:0}function contains(e,t,r){return e.some((e=>e[t]===r))}function countNines(e,t){return Number(String(e).slice(0,-t)+"9".repeat(t))}function countZeros(e,t){return e-e%Math.pow(10,t)}function toQuantifier(e){let[t=0,r=""]=e;if(r||t>1){return`{${t+(r?","+r:"")}}`}return""}function toCharacterClass(e,t,r){return`[${e}${t-e===1?"":"-"}${t}]`}function hasPadding(e){return/^-?(0+)\d/.test(e)}function padZeros(e,t,r){if(!t.isPadded){return e}let a=Math.abs(t.maxLen-String(e).length);let o=r.relaxZeros!==false;switch(a){case 0:return"";case 1:return o?"0?":"0";case 2:return o?"0{0,2}":"00";default:{return o?`0{0,${a}}`:`0{${a}}`}}}toRegexRange.cache={};toRegexRange.clearCache=()=>toRegexRange.cache={};var R=toRegexRange;const isObject=e=>e!==null&&typeof e==="object"&&!Array.isArray(e);const transform=e=>t=>e===true?Number(t):String(t);const isValidValue=e=>typeof e==="number"||typeof e==="string"&&e!=="";const isNumber$1=e=>Number.isInteger(+e);const zeros=e=>{let t=`${e}`;let r=-1;if(t[0]==="-")t=t.slice(1);if(t==="0")return false;while(t[++r]==="0");return r>0};const stringify$1=(e,t,r)=>{if(typeof e==="string"||typeof t==="string"){return true}return r.stringify===true};const pad=(e,t,r)=>{if(t>0){let r=e[0]==="-"?"-":"";if(r)e=e.slice(1);e=r+e.padStart(r?t-1:t,"0")}if(r===false){return String(e)}return e};const toMaxLen=(e,t)=>{let r=e[0]==="-"?"-":"";if(r){e=e.slice(1);t--}while(e.length{e.negatives.sort(((e,t)=>et?1:0));e.positives.sort(((e,t)=>et?1:0));let r=t.capture?"":"?:";let a="";let o="";let s;if(e.positives.length){a=e.positives.join("|")}if(e.negatives.length){o=`-(${r}${e.negatives.join("|")})`}if(a&&o){s=`${a}|${o}`}else{s=a||o}if(t.wrap){return`(${r}${s})`}return s};const toRange=(e,t,r,a)=>{if(r){return R(e,t,Object.assign({wrap:false},a))}let o=String.fromCharCode(e);if(e===t)return o;let s=String.fromCharCode(t);return`[${o}-${s}]`};const toRegex=(e,t,r)=>{if(Array.isArray(e)){let t=r.wrap===true;let a=r.capture?"":"?:";return t?`(${a}${e.join("|")})`:e.join("|")}return R(e,t,r)};const rangeError=(...e)=>new RangeError("Invalid range arguments: "+u.inspect(...e));const invalidRange=(e,t,r)=>{if(r.strictRanges===true)throw rangeError([e,t]);return[]};const invalidStep=(e,t)=>{if(t.strictRanges===true){throw new TypeError(`Expected step "${e}" to be a number`)}return[]};const fillNumbers=(e,t,r=1,a={})=>{let o=Number(e);let s=Number(t);if(!Number.isInteger(o)||!Number.isInteger(s)){if(a.strictRanges===true)throw rangeError([e,t]);return[]}if(o===0)o=0;if(s===0)s=0;let u=o>s;let c=String(e);let d=String(t);let f=String(r);r=Math.max(Math.abs(r),1);let p=zeros(c)||zeros(d)||zeros(f);let h=p?Math.max(c.length,d.length,f.length):0;let v=p===false&&stringify$1(e,t,a)===false;let _=a.transform||transform(v);if(a.toRegex&&r===1){return toRange(toMaxLen(e,h),toMaxLen(t,h),true,a)}let g={negatives:[],positives:[]};let push=e=>g[e<0?"negatives":"positives"].push(Math.abs(e));let y=[];let m=0;while(u?o>=s:o<=s){if(a.toRegex===true&&r>1){push(o)}else{y.push(pad(_(o,m),h,v))}o=u?o-r:o+r;m++}if(a.toRegex===true){return r>1?toSequence(g,a):toRegex(y,null,Object.assign({wrap:false},a))}return y};const fillLetters=(e,t,r=1,a={})=>{if(!isNumber$1(e)&&e.length>1||!isNumber$1(t)&&t.length>1){return invalidRange(e,t,a)}let o=a.transform||(e=>String.fromCharCode(e));let s=`${e}`.charCodeAt(0);let u=`${t}`.charCodeAt(0);let c=s>u;let d=Math.min(s,u);let f=Math.max(s,u);if(a.toRegex&&r===1){return toRange(d,f,false,a)}let p=[];let h=0;while(c?s>=u:s<=u){p.push(o(s,h));s=c?s-r:s+r;h++}if(a.toRegex===true){return toRegex(p,null,{wrap:false,options:a})}return p};const fill=(e,t,r,a={})=>{if(t==null&&isValidValue(e)){return[e]}if(!isValidValue(e)||!isValidValue(t)){return invalidRange(e,t,a)}if(typeof r==="function"){return fill(e,t,1,{transform:r})}if(isObject(r)){return fill(e,t,0,r)}let o=Object.assign({},a);if(o.capture===true)o.wrap=true;r=r||o.step||1;if(!isNumber$1(r)){if(r!=null&&!isObject(r))return invalidStep(r,o);return fill(e,t,1,r)}if(isNumber$1(e)&&isNumber$1(t)){return fillNumbers(e,t,r,o)}return fillLetters(e,t,Math.max(Math.abs(r),1),o)};var A=fill;const compile=(e,t={})=>{let walk=(e,r={})=>{let a=v.isInvalidBrace(r);let o=e.invalid===true&&t.escapeInvalid===true;let s=a===true||o===true;let u=t.escapeInvalid===true?"\\":"";let c="";if(e.isOpen===true){return u+e.value}if(e.isClose===true){return u+e.value}if(e.type==="open"){return s?u+e.value:"("}if(e.type==="close"){return s?u+e.value:")"}if(e.type==="comma"){return e.prev.type==="comma"?"":s?e.value:"|"}if(e.value){return e.value}if(e.nodes&&e.ranges>0){let r=v.reduce(e.nodes);let a=A(...r,Object.assign({},t,{wrap:false,toRegex:true}));if(a.length!==0){return r.length>1&&a.length>1?`(${a})`:a}}if(e.nodes){for(let t of e.nodes){c+=walk(t,e)}}return c};return walk(e)};var O=compile;const append=(e="",t="",r=false)=>{let a=[];e=[].concat(e);t=[].concat(t);if(!t.length)return e;if(!e.length){return r?v.flatten(t).map((e=>`{${e}}`)):t}for(let o of e){if(Array.isArray(o)){for(let e of o){a.push(append(e,t,r))}}else{for(let e of t){if(r===true&&typeof e==="string")e=`{${e}}`;a.push(Array.isArray(e)?append(o,e,r):o+e)}}}return v.flatten(a)};const expand=(e,t={})=>{let r=t.rangeLimit===void 0?1e3:t.rangeLimit;let walk=(e,a={})=>{e.queue=[];let o=a;let s=a.queue;while(o.type!=="brace"&&o.type!=="root"&&o.parent){o=o.parent;s=o.queue}if(e.invalid||e.dollar){s.push(append(s.pop(),stringify(e,t)));return}if(e.type==="brace"&&e.invalid!==true&&e.nodes.length===2){s.push(append(s.pop(),["{}"]));return}if(e.nodes&&e.ranges>0){let a=v.reduce(e.nodes);if(v.exceedsLimit(...a,t.step,r)){throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.")}let o=A(...a,t);if(o.length===0){o=stringify(e,t)}s.push(append(s.pop(),o));e.nodes=[];return}let u=v.encloseBrace(e);let c=e.queue;let d=e;while(d.type!=="brace"&&d.type!=="root"&&d.parent){d=d.parent;c=d.queue}for(let t=0;t",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:"\t",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\ufeff"};const{MAX_LENGTH:j,CHAR_BACKSLASH:N,CHAR_BACKTICK:L,CHAR_COMMA:I,CHAR_DOT:P,CHAR_LEFT_PARENTHESES:D,CHAR_RIGHT_PARENTHESES:M,CHAR_LEFT_CURLY_BRACE:W,CHAR_RIGHT_CURLY_BRACE:F,CHAR_LEFT_SQUARE_BRACKET:B,CHAR_RIGHT_SQUARE_BRACKET:$,CHAR_DOUBLE_QUOTE:U,CHAR_SINGLE_QUOTE:H,CHAR_NO_BREAK_SPACE:q,CHAR_ZERO_WIDTH_NOBREAK_SPACE:G}=C;const parse=(e,t={})=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}let r=t||{};let a=typeof r.maxLength==="number"?Math.min(j,r.maxLength):j;if(e.length>a){throw new SyntaxError(`Input length (${e.length}), exceeds max characters (${a})`)}let o={type:"root",input:e,nodes:[]};let s=[o];let u=o;let c=o;let d=0;let f=e.length;let p=0;let h=0;let v;const advance=()=>e[p++];const push=e=>{if(e.type==="text"&&c.type==="dot"){c.type="text"}if(c&&c.type==="text"&&e.type==="text"){c.value+=e.value;return}u.nodes.push(e);e.parent=u;e.prev=c;c=e;return e};push({type:"bos"});while(p0){if(u.ranges>0){u.ranges=0;let e=u.nodes.shift();u.nodes=[e,{type:"text",value:stringify(u)}]}push({type:"comma",value:v});u.commas++;continue}if(v===P&&h>0&&u.commas===0){let e=u.nodes;if(h===0||e.length===0){push({type:"text",value:v});continue}if(c.type==="dot"){u.range=[];c.value+=v;c.type="range";if(u.nodes.length!==3&&u.nodes.length!==5){u.invalid=true;u.ranges=0;c.type="text";continue}u.ranges++;u.args=[];continue}if(c.type==="range"){e.pop();let t=e[e.length-1];t.value+=c.value+v;c=t;u.ranges--;continue}push({type:"dot",value:v});continue}push({type:"text",value:v})}do{u=s.pop();if(u.type!=="root"){u.nodes.forEach((e=>{if(!e.nodes){if(e.type==="open")e.isOpen=true;if(e.type==="close")e.isClose=true;if(!e.nodes)e.type="text";e.invalid=true}}));let e=s[s.length-1];let t=e.nodes.indexOf(u);e.nodes.splice(t,1,...u.nodes)}}while(s.length>0);push({type:"eos"});return o};var K=parse;const braces=(e,t={})=>{let r=[];if(Array.isArray(e)){for(let a of e){let e=braces.create(a,t);if(Array.isArray(e)){r.push(...e)}else{r.push(e)}}}else{r=[].concat(braces.create(e,t))}if(t&&t.expand===true&&t.nodupes===true){r=[...new Set(r)]}return r};braces.parse=(e,t={})=>K(e,t);braces.stringify=(e,t={})=>{if(typeof e==="string"){return stringify(braces.parse(e,t),t)}return stringify(e,t)};braces.compile=(e,t={})=>{if(typeof e==="string"){e=braces.parse(e,t)}return O(e,t)};braces.expand=(e,t={})=>{if(typeof e==="string"){e=braces.parse(e,t)}let r=T(e,t);if(t.noempty===true){r=r.filter(Boolean)}if(t.nodupes===true){r=[...new Set(r)]}return r};braces.create=(e,t={})=>{if(e===""||e.length<3){return[e]}return t.expand!==true?braces.compile(e,t):braces.expand(e,t)};var z=braces;const V="\\\\/";const Y=`[^${V}]`;const Q="\\.";const X="\\+";const Z="\\?";const J="\\/";const ee="(?=.)";const te="[^/]";const ne=`(?:${J}|$)`;const re=`(?:^|${J})`;const ie=`${Q}{1,2}${ne}`;const ae=`(?!${Q})`;const oe=`(?!${re}${ie})`;const se=`(?!${Q}{0,1}${ne})`;const le=`(?!${ie})`;const ue=`[^.${J}]`;const ce=`${te}*?`;const de={DOT_LITERAL:Q,PLUS_LITERAL:X,QMARK_LITERAL:Z,SLASH_LITERAL:J,ONE_CHAR:ee,QMARK:te,END_ANCHOR:ne,DOTS_SLASH:ie,NO_DOT:ae,NO_DOTS:oe,NO_DOT_SLASH:se,NO_DOTS_SLASH:le,QMARK_NO_DOT:ue,STAR:ce,START_ANCHOR:re};const fe=Object.assign({},de,{SLASH_LITERAL:`[${V}]`,QMARK:Y,STAR:`${Y}*?`,DOTS_SLASH:`${Q}{1,2}(?:[${V}]|$)`,NO_DOT:`(?!${Q})`,NO_DOTS:`(?!(?:^|[${V}])${Q}{1,2}(?:[${V}]|$))`,NO_DOT_SLASH:`(?!${Q}{0,1}(?:[${V}]|$))`,NO_DOTS_SLASH:`(?!${Q}{1,2}(?:[${V}]|$))`,QMARK_NO_DOT:`[^.${V}]`,START_ANCHOR:`(?:^|[${V}])`,END_ANCHOR:`(?:[${V}]|$)`});const pe={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};var he={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:pe,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHAR:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:o.sep,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?fe:de}};var be=createCommonjsModule((function(e,t){const r=process.platform==="win32";const{REGEX_SPECIAL_CHARS:a,REGEX_SPECIAL_CHARS_GLOBAL:s,REGEX_REMOVE_BACKSLASH:u}=he;t.isObject=e=>e!==null&&typeof e==="object"&&!Array.isArray(e);t.hasRegexChars=e=>a.test(e);t.isRegexChar=e=>e.length===1&&t.hasRegexChars(e);t.escapeRegex=e=>e.replace(s,"\\$1");t.toPosixSlashes=e=>e.replace(/\\/g,"/");t.removeBackslashes=e=>e.replace(u,(e=>e==="\\"?"":e));t.supportsLookbehinds=()=>{let e=process.version.slice(1).split(".");if(e.length===3&&+e[0]>=9||+e[0]===8&&+e[1]>=10){return true}return false};t.isWindows=e=>{if(e&&typeof e.windows==="boolean"){return e.windows}return r===true||o.sep==="\\"};t.escapeLast=(e,r,a)=>{let o=e.lastIndexOf(r,a);if(o===-1)return e;if(e[o-1]==="\\")return t.escapeLast(e,r,o-1);return e.slice(0,o)+"\\"+e.slice(o)}}));var ve=be.isObject;var _e=be.hasRegexChars;var ge=be.isRegexChar;var ye=be.escapeRegex;var me=be.toPosixSlashes;var we=be.removeBackslashes;var xe=be.supportsLookbehinds;var Ee=be.isWindows;var Se=be.escapeLast;const{CHAR_ASTERISK:ke,CHAR_AT:Re,CHAR_BACKWARD_SLASH:Ae,CHAR_COMMA:Oe,CHAR_DOT:Te,CHAR_EXCLAMATION_MARK:Ce,CHAR_FORWARD_SLASH:je,CHAR_LEFT_CURLY_BRACE:Ne,CHAR_LEFT_PARENTHESES:Le,CHAR_LEFT_SQUARE_BRACKET:Ie,CHAR_PLUS:Pe,CHAR_QUESTION_MARK:De,CHAR_RIGHT_CURLY_BRACE:Me,CHAR_RIGHT_PARENTHESES:We,CHAR_RIGHT_SQUARE_BRACKET:Fe}=he;const isPathSeparator=e=>e===je||e===Ae;var scan=(e,t)=>{let r=t||{};let a=e.length-1;let o=-1;let s=0;let u=0;let c=false;let d=false;let f=false;let p=0;let h;let v;let _=false;let eos=()=>o>=a;let advance=()=>{h=v;return e.charCodeAt(++o)};while(o0){g=e.slice(0,s);e=e.slice(s);u-=s}if(m&&c===true&&u>0){m=e.slice(0,u);w=e.slice(u)}else if(c===true){m="";w=e}else{m=e}if(m&&m!==""&&m!=="/"&&m!==e){if(isPathSeparator(m.charCodeAt(m.length-1))){m=m.slice(0,-1)}}if(r.unescape===true){if(w)w=be.removeBackslashes(w);if(m&&d===true){m=be.removeBackslashes(m)}}return{prefix:g,input:y,base:m,glob:w,negated:f,isGlob:c}};const{MAX_LENGTH:Be,POSIX_REGEX_SOURCE:$e,REGEX_NON_SPECIAL_CHAR:Ue,REGEX_SPECIAL_CHARS_BACKREF:He,REPLACEMENTS:qe}=he;const expandRange=(e,t)=>{if(typeof t.expandRange==="function"){return t.expandRange(...e,t)}e.sort();let r=`[${e.join("-")}]`;try{}catch(t){return e.map((e=>be.escapeRegex(e))).join("..")}return r};const negate=e=>{let t=1;while(e.peek()==="!"&&(e.peek(2)!=="("||e.peek(3)==="?")){e.advance();e.start++;t++}if(t%2===0){return false}e.negated=true;e.start++;return true};const syntaxError=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`;const parse$1=(e,t)=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}e=qe[e]||e;let r=Object.assign({},t);let a=typeof r.maxLength==="number"?Math.min(Be,r.maxLength):Be;let o=e.length;if(o>a){throw new SyntaxError(`Input length: ${o}, exceeds maximum allowed length: ${a}`)}let s={type:"bos",value:"",output:r.prepend||""};let u=[s];let c=r.capture?"":"?:";let d=be.isWindows(t);const f=he.globChars(d);const p=he.extglobChars(f);const{DOT_LITERAL:h,PLUS_LITERAL:v,SLASH_LITERAL:_,ONE_CHAR:g,DOTS_SLASH:y,NO_DOT:m,NO_DOT_SLASH:w,NO_DOTS_SLASH:x,QMARK:E,QMARK_NO_DOT:S,STAR:k,START_ANCHOR:R}=f;const globstar=e=>`(${c}(?:(?!${R}${e.dot?y:h}).)*?)`;let A=r.dot?"":m;let O=r.bash===true?globstar(r):k;let T=r.dot?E:S;if(r.capture){O=`(${O})`}if(typeof r.noext==="boolean"){r.noextglob=r.noext}let C={index:-1,start:0,consumed:"",output:"",backtrack:false,brackets:0,braces:0,parens:0,quotes:0,tokens:u};let j=[];let N=[];let L=s;let I;const eos=()=>C.index===o-1;const P=C.peek=(t=1)=>e[C.index+t];const D=C.advance=()=>e[++C.index];const append=e=>{C.output+=e.output!=null?e.output:e.value;C.consumed+=e.value||""};const increment=e=>{C[e]++;N.push(e)};const decrement=e=>{C[e]--;N.pop()};const push=e=>{if(L.type==="globstar"){let t=C.braces>0&&(e.type==="comma"||e.type==="brace");let r=j.length&&(e.type==="pipe"||e.type==="paren");if(e.type!=="slash"&&e.type!=="paren"&&!t&&!r){C.output=C.output.slice(0,-L.output.length);L.type="star";L.value="*";L.output=O;C.output+=L.output}}if(j.length&&e.type!=="paren"&&!p[e.value]){j[j.length-1].inner+=e.value}if(e.value||e.output)append(e);if(L&&L.type==="text"&&e.type==="text"){L.value+=e.value;return}e.prev=L;u.push(e);L=e};const extglobOpen=(e,t)=>{let a=Object.assign({},p[t],{conditions:1,inner:""});a.prev=L;a.parens=C.parens;a.output=C.output;let o=(r.capture?"(":"")+a.open;push({type:e,value:t,output:C.output?"":g});push({type:"paren",extglob:true,value:D(),output:o});increment("parens");j.push(a)};const extglobClose=t=>{let a=t.close+(r.capture?")":"");if(t.type==="negate"){let o=O;if(t.inner&&t.inner.length>1&&t.inner.includes("/")){o=globstar(r)}if(o!==O||eos()||/^\)+$/.test(e.slice(C.index+1))){a=t.close=")$))"+o}if(t.prev.type==="bos"&&eos()){C.negatedExtglob=true}}push({type:"paren",extglob:true,value:I,output:a});decrement("parens")};if(r.fastpaths!==false&&!/(^[*!]|[/{[()\]}"])/.test(e)){let t=false;let a=e.replace(He,((e,r,a,o,s,u)=>{if(o==="\\"){t=true;return e}if(o==="?"){if(r){return r+o+(s?E.repeat(s.length):"")}if(u===0){return T+(s?E.repeat(s.length):"")}return E.repeat(a.length)}if(o==="."){return h.repeat(a.length)}if(o==="*"){if(r){return r+o+(s?O:"")}return O}return r?e:"\\"+e}));if(t===true){if(r.unescape===true){a=a.replace(/\\/g,"")}else{a=a.replace(/\\+/g,(e=>e.length%2===0?"\\\\":e?"\\":""))}}C.output=a;return C}while(!eos()){I=D();if(I==="\0"){continue}if(I==="\\"){let t=P();if(t==="/"&&r.bash!==true){continue}if(t==="."||t===";"){continue}if(!t){I+="\\";push({type:"text",value:I});continue}let a=/^\\+/.exec(e.slice(C.index+1));let o=0;if(a&&a[0].length>2){o=a[0].length;C.index+=o;if(o%2!==0){I+="\\"}}if(r.unescape===true){I=D()||""}else{I+=D()||""}if(C.brackets===0){push({type:"text",value:I});continue}}if(C.brackets>0&&(I!=="]"||L.value==="["||L.value==="[^")){if(r.posix!==false&&I===":"){let e=L.value.slice(1);if(e.includes("[")){L.posix=true;if(e.includes(":")){let e=L.value.lastIndexOf("[");let t=L.value.slice(0,e);let r=L.value.slice(e+2);let a=$e[r];if(a){L.value=t+a;C.backtrack=true;D();if(!s.output&&u.indexOf(L)===1){s.output=g}continue}}}}if(I==="["&&P()!==":"||I==="-"&&P()==="]"){I="\\"+I}if(I==="]"&&(L.value==="["||L.value==="[^")){I="\\"+I}if(r.posix===true&&I==="!"&&L.value==="["){I="^"}L.value+=I;append({value:I});continue}if(C.quotes===1&&I!=='"'){I=be.escapeRegex(I);L.value+=I;append({value:I});continue}if(I==='"'){C.quotes=C.quotes===1?0:1;if(r.keepQuotes===true){push({type:"text",value:I})}continue}if(I==="("){push({type:"paren",value:I});increment("parens");continue}if(I===")"){if(C.parens===0&&r.strictBrackets===true){throw new SyntaxError(syntaxError("opening","("))}let e=j[j.length-1];if(e&&C.parens===e.parens+1){extglobClose(j.pop());continue}push({type:"paren",value:I,output:C.parens?")":"\\)"});decrement("parens");continue}if(I==="["){if(r.nobracket===true||!e.slice(C.index+1).includes("]")){if(r.nobracket!==true&&r.strictBrackets===true){throw new SyntaxError(syntaxError("closing","]"))}I="\\"+I}else{increment("brackets")}push({type:"bracket",value:I});continue}if(I==="]"){if(r.nobracket===true||L&&L.type==="bracket"&&L.value.length===1){push({type:"text",value:I,output:"\\"+I});continue}if(C.brackets===0){if(r.strictBrackets===true){throw new SyntaxError(syntaxError("opening","["))}push({type:"text",value:I,output:"\\"+I});continue}decrement("brackets");let e=L.value.slice(1);if(L.posix!==true&&e[0]==="^"&&!e.includes("/")){I="/"+I}L.value+=I;append({value:I});if(r.literalBrackets===false||be.hasRegexChars(e)){continue}let t=be.escapeRegex(L.value);C.output=C.output.slice(0,-L.value.length);if(r.literalBrackets===true){C.output+=t;L.value=t;continue}L.value=`(${c}${t}|${L.value})`;C.output+=L.value;continue}if(I==="{"&&r.nobrace!==true){push({type:"brace",value:I,output:"("});increment("braces");continue}if(I==="}"){if(r.nobrace===true||C.braces===0){push({type:"text",value:I,output:"\\"+I});continue}let e=")";if(C.dots===true){let t=u.slice();let a=[];for(let e=t.length-1;e>=0;e--){u.pop();if(t[e].type==="brace"){break}if(t[e].type!=="dots"){a.unshift(t[e].value)}}e=expandRange(a,r);C.backtrack=true}push({type:"brace",value:I,output:e});decrement("braces");continue}if(I==="|"){if(j.length>0){j[j.length-1].conditions++}push({type:"text",value:I});continue}if(I===","){let e=I;if(C.braces>0&&N[N.length-1]==="braces"){e="|"}push({type:"comma",value:I,output:e});continue}if(I==="/"){if(L.type==="dot"&&C.index===1){C.start=C.index+1;C.consumed="";C.output="";u.pop();L=s;continue}push({type:"slash",value:I,output:_});continue}if(I==="."){if(C.braces>0&&L.type==="dot"){if(L.value===".")L.output=h;L.type="dots";L.output+=I;L.value+=I;C.dots=true;continue}push({type:"dot",value:I,output:h});continue}if(I==="?"){if(L&&L.type==="paren"){let e=P();let t=I;if(e==="<"&&!be.supportsLookbehinds()){throw new Error("Node.js v10 or higher is required for regex lookbehinds")}if(L.value==="("&&!/[!=<:]/.test(e)||e==="<"&&!/[!=]/.test(P(2))){t="\\"+I}push({type:"text",value:I,output:t});continue}if(r.noextglob!==true&&P()==="("&&P(2)!=="?"){extglobOpen("qmark",I);continue}if(r.dot!==true&&(L.type==="slash"||L.type==="bos")){push({type:"qmark",value:I,output:S});continue}push({type:"qmark",value:I,output:E});continue}if(I==="!"){if(r.noextglob!==true&&P()==="("){if(P(2)!=="?"||!/[!=<:]/.test(P(3))){extglobOpen("negate",I);continue}}if(r.nonegate!==true&&C.index===0){negate(C);continue}}if(I==="+"){if(r.noextglob!==true&&P()==="("&&P(2)!=="?"){extglobOpen("plus",I);continue}if(L&&(L.type==="bracket"||L.type==="paren"||L.type==="brace")){let e=L.extglob===true?"\\"+I:I;push({type:"plus",value:I,output:e});continue}if(C.parens>0&&r.regex!==false){push({type:"plus",value:I});continue}push({type:"plus",value:v});continue}if(I==="@"){if(r.noextglob!==true&&P()==="("&&P(2)!=="?"){push({type:"at",value:I,output:""});continue}push({type:"text",value:I});continue}if(I!=="*"){if(I==="$"||I==="^"){I="\\"+I}let t=Ue.exec(e.slice(C.index+1));if(t){I+=t[0];C.index+=t[0].length}push({type:"text",value:I});continue}if(L&&(L.type==="globstar"||L.star===true)){L.type="star";L.star=true;L.value+=I;L.output=O;C.backtrack=true;C.consumed+=I;continue}if(r.noextglob!==true&&P()==="("&&P(2)!=="?"){extglobOpen("star",I);continue}if(L.type==="star"){if(r.noglobstar===true){C.consumed+=I;continue}let t=L.prev;let a=t.prev;let o=t.type==="slash"||t.type==="bos";let s=a&&(a.type==="star"||a.type==="globstar");if(r.bash===true&&(!o||!eos()&&P()!=="/")){push({type:"star",value:I,output:""});continue}let u=C.braces>0&&(t.type==="comma"||t.type==="brace");let c=j.length&&(t.type==="pipe"||t.type==="paren");if(!o&&t.type!=="paren"&&!u&&!c){push({type:"star",value:I,output:""});continue}while(e.slice(C.index+1,C.index+4)==="/**"){let t=e[C.index+4];if(t&&t!=="/"){break}C.consumed+="/**";C.index+=3}if(t.type==="bos"&&eos()){L.type="globstar";L.value+=I;L.output=globstar(r);C.output=L.output;C.consumed+=I;continue}if(t.type==="slash"&&t.prev.type!=="bos"&&!s&&eos()){C.output=C.output.slice(0,-(t.output+L.output).length);t.output="(?:"+t.output;L.type="globstar";L.output=globstar(r)+"|$)";L.value+=I;C.output+=t.output+L.output;C.consumed+=I;continue}let d=P();if(t.type==="slash"&&t.prev.type!=="bos"&&d==="/"){let e=P(2)!==void 0?"|$":"";C.output=C.output.slice(0,-(t.output+L.output).length);t.output="(?:"+t.output;L.type="globstar";L.output=`${globstar(r)}${_}|${_}${e})`;L.value+=I;C.output+=t.output+L.output;C.consumed+=I+D();push({type:"slash",value:I,output:""});continue}if(t.type==="bos"&&d==="/"){L.type="globstar";L.value+=I;L.output=`(?:^|${_}|${globstar(r)}${_})`;C.output=L.output;C.consumed+=I+D();push({type:"slash",value:I,output:""});continue}C.output=C.output.slice(0,-L.output.length);L.type="globstar";L.output=globstar(r);L.value+=I;C.output+=L.output;C.consumed+=I;continue}let t={type:"star",value:I,output:O};if(r.bash===true){t.output=".*?";if(L.type==="bos"||L.type==="slash"){t.output=A+t.output}push(t);continue}if(L&&(L.type==="bracket"||L.type==="paren")&&r.regex===true){t.output=I;push(t);continue}if(C.index===C.start||L.type==="slash"||L.type==="dot"){if(L.type==="dot"){C.output+=w;L.output+=w}else if(r.dot===true){C.output+=x;L.output+=x}else{C.output+=A;L.output+=A}if(P()!=="*"){C.output+=g;L.output+=g}}push(t)}while(C.brackets>0){if(r.strictBrackets===true)throw new SyntaxError(syntaxError("closing","]"));C.output=be.escapeLast(C.output,"[");decrement("brackets")}while(C.parens>0){if(r.strictBrackets===true)throw new SyntaxError(syntaxError("closing",")"));C.output=be.escapeLast(C.output,"(");decrement("parens")}while(C.braces>0){if(r.strictBrackets===true)throw new SyntaxError(syntaxError("closing","}"));C.output=be.escapeLast(C.output,"{");decrement("braces")}if(r.strictSlashes!==true&&(L.type==="star"||L.type==="bracket")){push({type:"maybe_slash",value:"",output:`${_}?`})}if(C.backtrack===true){C.output="";for(let e of C.tokens){C.output+=e.output!=null?e.output:e.value;if(e.suffix){C.output+=e.suffix}}}return C};parse$1.fastpaths=(e,t)=>{let r=Object.assign({},t);let a=typeof r.maxLength==="number"?Math.min(Be,r.maxLength):Be;let o=e.length;if(o>a){throw new SyntaxError(`Input length: ${o}, exceeds maximum allowed length: ${a}`)}e=qe[e]||e;let s=be.isWindows(t);const{DOT_LITERAL:u,SLASH_LITERAL:c,ONE_CHAR:d,DOTS_SLASH:f,NO_DOT:p,NO_DOTS:h,NO_DOTS_SLASH:v,STAR:_,START_ANCHOR:g}=he.globChars(s);let y=r.capture?"":"?:";let m=r.bash===true?".*?":_;let w=r.dot?h:p;let x=r.dot?v:p;if(r.capture){m=`(${m})`}const globstar=e=>`(${y}(?:(?!${g}${e.dot?f:u}).)*?)`;const create=e=>{switch(e){case"*":return`${w}${d}${m}`;case".*":return`${u}${d}${m}`;case"*.*":return`${w}${m}${u}${d}${m}`;case"*/*":return`${w}${m}${c}${d}${x}${m}`;case"**":return w+globstar(r);case"**/*":return`(?:${w}${globstar(r)}${c})?${x}${d}${m}`;case"**/*.*":return`(?:${w}${globstar(r)}${c})?${x}${m}${u}${d}${m}`;case"**/.*":return`(?:${w}${globstar(r)}${c})?${u}${d}${m}`;default:{let r=/^(.*?)\.(\w+)$/.exec(e);if(!r)return;let a=create(r[1],t);if(!a)return;return a+u+r[2]}}};let E=create(e);if(E&&r.strictSlashes!==true){E+=`${c}?`}return E};var Ge=parse$1;const picomatch=(e,t,r=false)=>{if(Array.isArray(e)){let a=e.map((e=>picomatch(e,t,r)));return e=>{for(let t of a){let r=t(e);if(r)return r}return false}}if(typeof e!=="string"||e===""){throw new TypeError("Expected pattern to be a non-empty string")}let a=t||{};let o=be.isWindows(t);let s=picomatch.makeRe(e,t,false,true);let u=s.state;delete s.state;let isIgnored=()=>false;if(a.ignore){let e=Object.assign({},t,{ignore:null,onMatch:null,onResult:null});isIgnored=picomatch(a.ignore,e,r)}const matcher=(r,c=false)=>{let{isMatch:d,match:f,output:p}=picomatch.test(r,s,t,{glob:e,posix:o});let h={glob:e,state:u,regex:s,posix:o,input:r,output:p,match:f,isMatch:d};if(typeof a.onResult==="function"){a.onResult(h)}if(d===false){h.isMatch=false;return c?h:false}if(isIgnored(r)){if(typeof a.onIgnore==="function"){a.onIgnore(h)}h.isMatch=false;return c?h:false}if(typeof a.onMatch==="function"){a.onMatch(h)}return c?h:true};if(r){matcher.state=u}return matcher};picomatch.test=(e,t,r,{glob:a,posix:o}={})=>{if(typeof e!=="string"){throw new TypeError("Expected input to be a string")}if(e===""){return{isMatch:false,output:""}}let s=r||{};let u=s.format||(o?be.toPosixSlashes:null);let c=e===a;let d=c&&u?u(e):e;if(c===false){d=u?u(e):e;c=d===a}if(c===false||s.capture===true){if(s.matchBase===true||s.basename===true){c=picomatch.matchBase(e,t,r,o)}else{c=t.exec(d)}}return{isMatch:!!c,match:c,output:d}};picomatch.matchBase=(e,t,r,a=be.isWindows(r))=>{let s=t instanceof RegExp?t:picomatch.makeRe(t,r);return s.test(o.basename(e))};picomatch.isMatch=(e,t,r)=>picomatch(t,r)(e);picomatch.parse=(e,t)=>Ge(e,t);picomatch.scan=(e,t)=>scan(e,t);picomatch.makeRe=(e,t,r=false,a=false)=>{if(!e||typeof e!=="string"){throw new TypeError("Expected a non-empty string")}let o=t||{};let s=o.contains?"":"^";let u=o.contains?"":"$";let c={negated:false,fastpaths:true};let d="";let f;if(e.startsWith("./")){e=e.slice(2);d=c.prefix="./"}if(o.fastpaths!==false&&(e[0]==="."||e[0]==="*")){f=Ge.fastpaths(e,t)}if(f===void 0){c=picomatch.parse(e,t);c.prefix=d+(c.prefix||"");f=c.output}if(r===true){return f}let p=`${s}(?:${f})${u}`;if(c&&c.negated===true){p=`^(?!${p}).*$`}let h=picomatch.toRegex(p,t);if(a===true){h.state=c}return h};picomatch.toRegex=(e,t)=>{try{let r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(e){if(t&&t.debug===true)throw e;return/$^/}};picomatch.constants=he;var Ke=picomatch;var ze=Ke;const isEmptyString=e=>typeof e==="string"&&(e===""||e==="./");const micromatch=(e,t,r)=>{t=[].concat(t);e=[].concat(e);let a=new Set;let o=new Set;let s=new Set;let u=0;let onResult=e=>{s.add(e.output);if(r&&r.onResult){r.onResult(e)}};for(let s=0;s!a.has(e)));if(r&&d.length===0){if(r.failglob===true){throw new Error(`No matches found for "${t.join(", ")}"`)}if(r.nonull===true||r.nullglob===true){return r.unescape?t.map((e=>e.replace(/\\/g,""))):t}}return d};micromatch.match=micromatch;micromatch.matcher=(e,t)=>ze(e,t);micromatch.isMatch=(e,t,r)=>ze(t,r)(e);micromatch.any=micromatch.isMatch;micromatch.not=(e,t,r={})=>{t=[].concat(t).map(String);let a=new Set;let o=[];let onResult=e=>{if(r.onResult)r.onResult(e);o.push(e.output)};let s=micromatch(e,t,Object.assign({},r,{onResult:onResult}));for(let e of o){if(!s.includes(e)){a.add(e)}}return[...a]};micromatch.contains=(e,t,r)=>{if(typeof e!=="string"){throw new TypeError(`Expected a string: "${u.inspect(e)}"`)}if(Array.isArray(t)){return t.some((t=>micromatch.contains(e,t,r)))}if(typeof t==="string"){if(isEmptyString(e)||isEmptyString(t)){return false}if(e.includes(t)||e.startsWith("./")&&e.slice(2).includes(t)){return true}}return micromatch.isMatch(e,t,Object.assign({},r,{contains:true}))};micromatch.matchKeys=(e,t,r)=>{if(!be.isObject(e)){throw new TypeError("Expected the first argument to be an object")}let a=micromatch(Object.keys(e),t,r);let o={};for(let t of a)o[t]=e[t];return o};micromatch.some=(e,t,r)=>{let a=[].concat(e);for(let e of[].concat(t)){let t=ze(String(e),r);if(a.some((e=>t(e)))){return true}}return false};micromatch.every=(e,t,r)=>{let a=[].concat(e);for(let e of[].concat(t)){let t=ze(String(e),r);if(!a.every((e=>t(e)))){return false}}return true};micromatch.all=(e,t,r)=>{if(typeof e!=="string"){throw new TypeError(`Expected a string: "${u.inspect(e)}"`)}return[].concat(t).every((t=>ze(t,r)(e)))};micromatch.capture=(e,t,r)=>{let a=be.isWindows(r);let o=ze.makeRe(String(e),Object.assign({},r,{capture:true}));let s=o.exec(a?be.toPosixSlashes(t):t);if(s){return s.slice(1).map((e=>e===void 0?"":e))}};micromatch.makeRe=(...e)=>ze.makeRe(...e);micromatch.scan=(...e)=>ze.scan(...e);micromatch.parse=(e,t)=>{let r=[];for(let a of[].concat(e||[])){for(let e of z(String(a),t)){r.push(ze.parse(e,t))}}return r};micromatch.braces=(e,t)=>{if(typeof e!=="string")throw new TypeError("Expected a string");if(t&&t.nobrace===true||!/\{.*\}/.test(e)){return[e]}return z(e,t)};micromatch.braceExpand=(e,t)=>{if(typeof e!=="string")throw new TypeError("Expected a string");return micromatch.braces(e,Object.assign({},t,{expand:true}))};var Ve=micromatch;function ensureArray(e){if(Array.isArray(e))return e;if(e==undefined)return[];return[e]}function getMatcherString(e,t){if(t===false){return e}return a.resolve(...typeof t==="string"?[t,e]:[e])}const Ye=function createFilter(e,t,r){const o=r&&r.resolve;const getMatcher=e=>e instanceof RegExp?e:{test:Ve.matcher(getMatcherString(e,o).split(a.sep).join("/"),{dot:true})};const s=ensureArray(e).map(getMatcher);const u=ensureArray(t).map(getMatcher);return function(e){if(typeof e!=="string")return false;if(/\0/.test(e))return false;e=e.split(a.sep).join("/");for(let t=0;tt.toUpperCase())).replace(/[^$_a-zA-Z0-9]/g,"_");if(/\d/.test(e[0])||Ze.has(e)){e=`_${e}`}return e||"_"};function stringify$2(e){return(JSON.stringify(e)||"undefined").replace(/[\u2028\u2029]/g,(e=>`\\u${("000"+e.charCodeAt(0).toString(16)).slice(-4)}`))}function serializeArray(e,t,r){let a="[";const o=t?"\n"+r+t:"";for(let s=0;s0?",":""}${o}${serialize(u,t,r+t)}`}return a+`${t?"\n"+r:""}]`}function serializeObject(e,t,r){let a="{";const o=t?"\n"+r+t:"";const s=Object.keys(e);for(let u=0;u0?",":""}${o}${d}:${t?" ":""}${serialize(e[c],t,r+t)}`}return a+`${t?"\n"+r:""}}`}function serialize(e,t,r){if(e===Infinity)return"Infinity";if(e===-Infinity)return"-Infinity";if(e===0&&1/e===-Infinity)return"-0";if(e instanceof Date)return"new Date("+e.getTime()+")";if(e instanceof RegExp)return e.toString();if(e!==e)return"NaN";if(Array.isArray(e))return serializeArray(e,t,r);if(e===null)return"null";if(typeof e==="object")return serializeObject(e,t,r);return stringify$2(e)}const et=function dataToEsm(e,t={}){const r=t.compact?"":"indent"in t?t.indent:"\t";const a=t.compact?"":" ";const o=t.compact?"":"\n";const s=t.preferConst?"const":"var";if(t.namedExports===false||typeof e!=="object"||Array.isArray(e)||e instanceof Date||e instanceof RegExp||e===null){const o=serialize(e,t.compact?null:r,"");const s=a||(/^[{[\-\/]/.test(o)?"":" ");return`export default${s}${o};`}let u="";const c=[];const d=Object.keys(e);for(let f=0;ft=true};const a={};const o=Object.prototype.toString;function isArray(e){return o.call(e)==="[object Array]"}function visit(e,o,s,u,c,d){if(!e)return;if(s){const a=t;t=false;s.call(r,e,o,c,d);const u=t;t=a;if(u)return}const f=e.type&&a[e.type]||(a[e.type]=Object.keys(e).filter((t=>typeof e[t]==="object")));for(let t=0;t{e.exports=function(e){[process.stdout,process.stderr].forEach((function(t){if(t._handle&&t.isTTY&&typeof t._handle.setBlocking==="function"){t._handle.setBlocking(e)}}))}},2028:(e,t,r)=>{var a=r(9491);var o=r(19);var s=r(2361);if(typeof s!=="function"){s=s.EventEmitter}var u;if(process.__signal_exit_emitter__){u=process.__signal_exit_emitter__}else{u=process.__signal_exit_emitter__=new s;u.count=0;u.emitted={}}if(!u.infinite){u.setMaxListeners(Infinity);u.infinite=true}e.exports=function(e,t){a.equal(typeof e,"function","a callback must be provided for exit handler");if(d===false){load()}var r="exit";if(t&&t.alwaysLast){r="afterexit"}var remove=function(){u.removeListener(r,e);if(u.listeners("exit").length===0&&u.listeners("afterexit").length===0){unload()}};u.on(r,e);return remove};e.exports.unload=unload;function unload(){if(!d){return}d=false;o.forEach((function(e){try{process.removeListener(e,c[e])}catch(e){}}));process.emit=p;process.reallyExit=f;u.count-=1}function emit(e,t,r){if(u.emitted[e]){return}u.emitted[e]=true;u.emit(e,t,r)}var c={};o.forEach((function(e){c[e]=function listener(){var t=process.listeners(e);if(t.length===u.count){unload();emit("exit",null,e);emit("afterexit",null,e);process.kill(process.pid,e)}}}));e.exports.signals=function(){return o};e.exports.load=load;var d=false;function load(){if(d){return}d=true;u.count+=1;o=o.filter((function(e){try{process.on(e,c[e]);return true}catch(e){return false}}));process.emit=processEmit;process.reallyExit=processReallyExit}var f=process.reallyExit;function processReallyExit(e){process.exitCode=e||0;emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);f.call(process,process.exitCode)}var p=process.emit;function processEmit(e,t){if(e==="exit"){if(t!==undefined){process.exitCode=t}var r=p.apply(this,arguments);emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);return r}else{return p.apply(this,arguments)}}},19:e=>{e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32"){e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT")}if(process.platform==="linux"){e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}},9209:(e,t,r)=>{e.exports=r(3837).deprecate},7568:(e,t,r)=>{"use strict";var a=r(3062);t.center=alignCenter;t.left=alignLeft;t.right=alignRight;function createPadding(e){var t="";var r=" ";var a=e;do{if(a%2){t+=r}a=Math.floor(a/2);r+=r}while(a);return t}function alignLeft(e,t){var r=e.trimRight();if(r.length===0&&e.length>=t)return e;var o="";var s=a(r);if(s=t)return e;var o="";var s=a(r);if(s=t)return e;var o="";var s="";var u=a(r);if(u{"use strict";e.exports=e=>{if(Number.isNaN(e)){return false}if(e>=4352&&(e<=4447||e===9001||e===9002||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141)){return true}return false}},3062:(e,t,r)=>{"use strict";const a=r(7518);const o=r(4994);e.exports=e=>{if(typeof e!=="string"||e.length===0){return 0}e=a(e);let t=0;for(let r=0;r=127&&a<=159){continue}if(a>=768&&a<=879){continue}if(a>65535){r++}t+=o(a)?2:1}return t}},918:module=>{module.exports=eval("require")("aws-sdk")},2722:module=>{module.exports=eval("require")("mock-aws-s3")},3902:module=>{module.exports=eval("require")("nock")},9491:e=>{"use strict";e.exports=require("assert")},4300:e=>{"use strict";e.exports=require("buffer")},2081:e=>{"use strict";e.exports=require("child_process")},2057:e=>{"use strict";e.exports=require("constants")},2361:e=>{"use strict";e.exports=require("events")},7147:e=>{"use strict";e.exports=require("fs")},8188:e=>{"use strict";e.exports=require("module")},1988:e=>{"use strict";e.exports=require("next/dist/compiled/acorn")},3535:e=>{"use strict";e.exports=require("next/dist/compiled/glob")},2540:e=>{"use strict";e.exports=require("next/dist/compiled/micromatch")},7849:e=>{"use strict";e.exports=require("next/dist/compiled/semver")},7518:e=>{"use strict";e.exports=require("next/dist/compiled/strip-ansi")},2037:e=>{"use strict";e.exports=require("os")},1017:e=>{"use strict";e.exports=require("path")},8102:e=>{"use strict";e.exports=require("repl")},2781:e=>{"use strict";e.exports=require("stream")},7310:e=>{"use strict";e.exports=require("url")},3837:e=>{"use strict";e.exports=require("util")},7470:function(e,t){(function(e,r){true?r(t):0})(this,(function(e){"use strict";class WalkerBase{constructor(){this.should_skip=false;this.should_remove=false;this.replacement=null;this.context={skip:()=>this.should_skip=true,remove:()=>this.should_remove=true,replace:e=>this.replacement=e}}replace(e,t,r,a){if(e){if(r!==null){e[t][r]=a}else{e[t]=a}}}remove(e,t,r){if(e){if(r!==null){e[t].splice(r,1)}else{delete e[t]}}}}class SyncWalker extends WalkerBase{constructor(e,t){super();this.enter=e;this.leave=t}visit(e,t,r,a){if(e){if(this.enter){const o=this.should_skip;const s=this.should_remove;const u=this.replacement;this.should_skip=false;this.should_remove=false;this.replacement=null;this.enter.call(this.context,e,t,r,a);if(this.replacement){e=this.replacement;this.replace(t,r,a,e)}if(this.should_remove){this.remove(t,r,a)}const c=this.should_skip;const d=this.should_remove;this.should_skip=o;this.should_remove=s;this.replacement=u;if(c)return e;if(d)return null}for(const t in e){const r=e[t];if(typeof r!=="object"){continue}else if(Array.isArray(r)){for(let a=0;a{"use strict";e.exports=JSON.parse('{"0.1.14":{"node_abi":null,"v8":"1.3"},"0.1.15":{"node_abi":null,"v8":"1.3"},"0.1.16":{"node_abi":null,"v8":"1.3"},"0.1.17":{"node_abi":null,"v8":"1.3"},"0.1.18":{"node_abi":null,"v8":"1.3"},"0.1.19":{"node_abi":null,"v8":"2.0"},"0.1.20":{"node_abi":null,"v8":"2.0"},"0.1.21":{"node_abi":null,"v8":"2.0"},"0.1.22":{"node_abi":null,"v8":"2.0"},"0.1.23":{"node_abi":null,"v8":"2.0"},"0.1.24":{"node_abi":null,"v8":"2.0"},"0.1.25":{"node_abi":null,"v8":"2.0"},"0.1.26":{"node_abi":null,"v8":"2.0"},"0.1.27":{"node_abi":null,"v8":"2.1"},"0.1.28":{"node_abi":null,"v8":"2.1"},"0.1.29":{"node_abi":null,"v8":"2.1"},"0.1.30":{"node_abi":null,"v8":"2.1"},"0.1.31":{"node_abi":null,"v8":"2.1"},"0.1.32":{"node_abi":null,"v8":"2.1"},"0.1.33":{"node_abi":null,"v8":"2.1"},"0.1.90":{"node_abi":null,"v8":"2.2"},"0.1.91":{"node_abi":null,"v8":"2.2"},"0.1.92":{"node_abi":null,"v8":"2.2"},"0.1.93":{"node_abi":null,"v8":"2.2"},"0.1.94":{"node_abi":null,"v8":"2.2"},"0.1.95":{"node_abi":null,"v8":"2.2"},"0.1.96":{"node_abi":null,"v8":"2.2"},"0.1.97":{"node_abi":null,"v8":"2.2"},"0.1.98":{"node_abi":null,"v8":"2.2"},"0.1.99":{"node_abi":null,"v8":"2.2"},"0.1.100":{"node_abi":null,"v8":"2.2"},"0.1.101":{"node_abi":null,"v8":"2.3"},"0.1.102":{"node_abi":null,"v8":"2.3"},"0.1.103":{"node_abi":null,"v8":"2.3"},"0.1.104":{"node_abi":null,"v8":"2.3"},"0.2.0":{"node_abi":1,"v8":"2.3"},"0.2.1":{"node_abi":1,"v8":"2.3"},"0.2.2":{"node_abi":1,"v8":"2.3"},"0.2.3":{"node_abi":1,"v8":"2.3"},"0.2.4":{"node_abi":1,"v8":"2.3"},"0.2.5":{"node_abi":1,"v8":"2.3"},"0.2.6":{"node_abi":1,"v8":"2.3"},"0.3.0":{"node_abi":1,"v8":"2.5"},"0.3.1":{"node_abi":1,"v8":"2.5"},"0.3.2":{"node_abi":1,"v8":"3.0"},"0.3.3":{"node_abi":1,"v8":"3.0"},"0.3.4":{"node_abi":1,"v8":"3.0"},"0.3.5":{"node_abi":1,"v8":"3.0"},"0.3.6":{"node_abi":1,"v8":"3.0"},"0.3.7":{"node_abi":1,"v8":"3.0"},"0.3.8":{"node_abi":1,"v8":"3.1"},"0.4.0":{"node_abi":1,"v8":"3.1"},"0.4.1":{"node_abi":1,"v8":"3.1"},"0.4.2":{"node_abi":1,"v8":"3.1"},"0.4.3":{"node_abi":1,"v8":"3.1"},"0.4.4":{"node_abi":1,"v8":"3.1"},"0.4.5":{"node_abi":1,"v8":"3.1"},"0.4.6":{"node_abi":1,"v8":"3.1"},"0.4.7":{"node_abi":1,"v8":"3.1"},"0.4.8":{"node_abi":1,"v8":"3.1"},"0.4.9":{"node_abi":1,"v8":"3.1"},"0.4.10":{"node_abi":1,"v8":"3.1"},"0.4.11":{"node_abi":1,"v8":"3.1"},"0.4.12":{"node_abi":1,"v8":"3.1"},"0.5.0":{"node_abi":1,"v8":"3.1"},"0.5.1":{"node_abi":1,"v8":"3.4"},"0.5.2":{"node_abi":1,"v8":"3.4"},"0.5.3":{"node_abi":1,"v8":"3.4"},"0.5.4":{"node_abi":1,"v8":"3.5"},"0.5.5":{"node_abi":1,"v8":"3.5"},"0.5.6":{"node_abi":1,"v8":"3.6"},"0.5.7":{"node_abi":1,"v8":"3.6"},"0.5.8":{"node_abi":1,"v8":"3.6"},"0.5.9":{"node_abi":1,"v8":"3.6"},"0.5.10":{"node_abi":1,"v8":"3.7"},"0.6.0":{"node_abi":1,"v8":"3.6"},"0.6.1":{"node_abi":1,"v8":"3.6"},"0.6.2":{"node_abi":1,"v8":"3.6"},"0.6.3":{"node_abi":1,"v8":"3.6"},"0.6.4":{"node_abi":1,"v8":"3.6"},"0.6.5":{"node_abi":1,"v8":"3.6"},"0.6.6":{"node_abi":1,"v8":"3.6"},"0.6.7":{"node_abi":1,"v8":"3.6"},"0.6.8":{"node_abi":1,"v8":"3.6"},"0.6.9":{"node_abi":1,"v8":"3.6"},"0.6.10":{"node_abi":1,"v8":"3.6"},"0.6.11":{"node_abi":1,"v8":"3.6"},"0.6.12":{"node_abi":1,"v8":"3.6"},"0.6.13":{"node_abi":1,"v8":"3.6"},"0.6.14":{"node_abi":1,"v8":"3.6"},"0.6.15":{"node_abi":1,"v8":"3.6"},"0.6.16":{"node_abi":1,"v8":"3.6"},"0.6.17":{"node_abi":1,"v8":"3.6"},"0.6.18":{"node_abi":1,"v8":"3.6"},"0.6.19":{"node_abi":1,"v8":"3.6"},"0.6.20":{"node_abi":1,"v8":"3.6"},"0.6.21":{"node_abi":1,"v8":"3.6"},"0.7.0":{"node_abi":1,"v8":"3.8"},"0.7.1":{"node_abi":1,"v8":"3.8"},"0.7.2":{"node_abi":1,"v8":"3.8"},"0.7.3":{"node_abi":1,"v8":"3.9"},"0.7.4":{"node_abi":1,"v8":"3.9"},"0.7.5":{"node_abi":1,"v8":"3.9"},"0.7.6":{"node_abi":1,"v8":"3.9"},"0.7.7":{"node_abi":1,"v8":"3.9"},"0.7.8":{"node_abi":1,"v8":"3.9"},"0.7.9":{"node_abi":1,"v8":"3.11"},"0.7.10":{"node_abi":1,"v8":"3.9"},"0.7.11":{"node_abi":1,"v8":"3.11"},"0.7.12":{"node_abi":1,"v8":"3.11"},"0.8.0":{"node_abi":1,"v8":"3.11"},"0.8.1":{"node_abi":1,"v8":"3.11"},"0.8.2":{"node_abi":1,"v8":"3.11"},"0.8.3":{"node_abi":1,"v8":"3.11"},"0.8.4":{"node_abi":1,"v8":"3.11"},"0.8.5":{"node_abi":1,"v8":"3.11"},"0.8.6":{"node_abi":1,"v8":"3.11"},"0.8.7":{"node_abi":1,"v8":"3.11"},"0.8.8":{"node_abi":1,"v8":"3.11"},"0.8.9":{"node_abi":1,"v8":"3.11"},"0.8.10":{"node_abi":1,"v8":"3.11"},"0.8.11":{"node_abi":1,"v8":"3.11"},"0.8.12":{"node_abi":1,"v8":"3.11"},"0.8.13":{"node_abi":1,"v8":"3.11"},"0.8.14":{"node_abi":1,"v8":"3.11"},"0.8.15":{"node_abi":1,"v8":"3.11"},"0.8.16":{"node_abi":1,"v8":"3.11"},"0.8.17":{"node_abi":1,"v8":"3.11"},"0.8.18":{"node_abi":1,"v8":"3.11"},"0.8.19":{"node_abi":1,"v8":"3.11"},"0.8.20":{"node_abi":1,"v8":"3.11"},"0.8.21":{"node_abi":1,"v8":"3.11"},"0.8.22":{"node_abi":1,"v8":"3.11"},"0.8.23":{"node_abi":1,"v8":"3.11"},"0.8.24":{"node_abi":1,"v8":"3.11"},"0.8.25":{"node_abi":1,"v8":"3.11"},"0.8.26":{"node_abi":1,"v8":"3.11"},"0.8.27":{"node_abi":1,"v8":"3.11"},"0.8.28":{"node_abi":1,"v8":"3.11"},"0.9.0":{"node_abi":1,"v8":"3.11"},"0.9.1":{"node_abi":10,"v8":"3.11"},"0.9.2":{"node_abi":10,"v8":"3.11"},"0.9.3":{"node_abi":10,"v8":"3.13"},"0.9.4":{"node_abi":10,"v8":"3.13"},"0.9.5":{"node_abi":10,"v8":"3.13"},"0.9.6":{"node_abi":10,"v8":"3.15"},"0.9.7":{"node_abi":10,"v8":"3.15"},"0.9.8":{"node_abi":10,"v8":"3.15"},"0.9.9":{"node_abi":11,"v8":"3.15"},"0.9.10":{"node_abi":11,"v8":"3.15"},"0.9.11":{"node_abi":11,"v8":"3.14"},"0.9.12":{"node_abi":11,"v8":"3.14"},"0.10.0":{"node_abi":11,"v8":"3.14"},"0.10.1":{"node_abi":11,"v8":"3.14"},"0.10.2":{"node_abi":11,"v8":"3.14"},"0.10.3":{"node_abi":11,"v8":"3.14"},"0.10.4":{"node_abi":11,"v8":"3.14"},"0.10.5":{"node_abi":11,"v8":"3.14"},"0.10.6":{"node_abi":11,"v8":"3.14"},"0.10.7":{"node_abi":11,"v8":"3.14"},"0.10.8":{"node_abi":11,"v8":"3.14"},"0.10.9":{"node_abi":11,"v8":"3.14"},"0.10.10":{"node_abi":11,"v8":"3.14"},"0.10.11":{"node_abi":11,"v8":"3.14"},"0.10.12":{"node_abi":11,"v8":"3.14"},"0.10.13":{"node_abi":11,"v8":"3.14"},"0.10.14":{"node_abi":11,"v8":"3.14"},"0.10.15":{"node_abi":11,"v8":"3.14"},"0.10.16":{"node_abi":11,"v8":"3.14"},"0.10.17":{"node_abi":11,"v8":"3.14"},"0.10.18":{"node_abi":11,"v8":"3.14"},"0.10.19":{"node_abi":11,"v8":"3.14"},"0.10.20":{"node_abi":11,"v8":"3.14"},"0.10.21":{"node_abi":11,"v8":"3.14"},"0.10.22":{"node_abi":11,"v8":"3.14"},"0.10.23":{"node_abi":11,"v8":"3.14"},"0.10.24":{"node_abi":11,"v8":"3.14"},"0.10.25":{"node_abi":11,"v8":"3.14"},"0.10.26":{"node_abi":11,"v8":"3.14"},"0.10.27":{"node_abi":11,"v8":"3.14"},"0.10.28":{"node_abi":11,"v8":"3.14"},"0.10.29":{"node_abi":11,"v8":"3.14"},"0.10.30":{"node_abi":11,"v8":"3.14"},"0.10.31":{"node_abi":11,"v8":"3.14"},"0.10.32":{"node_abi":11,"v8":"3.14"},"0.10.33":{"node_abi":11,"v8":"3.14"},"0.10.34":{"node_abi":11,"v8":"3.14"},"0.10.35":{"node_abi":11,"v8":"3.14"},"0.10.36":{"node_abi":11,"v8":"3.14"},"0.10.37":{"node_abi":11,"v8":"3.14"},"0.10.38":{"node_abi":11,"v8":"3.14"},"0.10.39":{"node_abi":11,"v8":"3.14"},"0.10.40":{"node_abi":11,"v8":"3.14"},"0.10.41":{"node_abi":11,"v8":"3.14"},"0.10.42":{"node_abi":11,"v8":"3.14"},"0.10.43":{"node_abi":11,"v8":"3.14"},"0.10.44":{"node_abi":11,"v8":"3.14"},"0.10.45":{"node_abi":11,"v8":"3.14"},"0.10.46":{"node_abi":11,"v8":"3.14"},"0.10.47":{"node_abi":11,"v8":"3.14"},"0.10.48":{"node_abi":11,"v8":"3.14"},"0.11.0":{"node_abi":12,"v8":"3.17"},"0.11.1":{"node_abi":12,"v8":"3.18"},"0.11.2":{"node_abi":12,"v8":"3.19"},"0.11.3":{"node_abi":12,"v8":"3.19"},"0.11.4":{"node_abi":12,"v8":"3.20"},"0.11.5":{"node_abi":12,"v8":"3.20"},"0.11.6":{"node_abi":12,"v8":"3.20"},"0.11.7":{"node_abi":12,"v8":"3.20"},"0.11.8":{"node_abi":13,"v8":"3.21"},"0.11.9":{"node_abi":13,"v8":"3.22"},"0.11.10":{"node_abi":13,"v8":"3.22"},"0.11.11":{"node_abi":14,"v8":"3.22"},"0.11.12":{"node_abi":14,"v8":"3.22"},"0.11.13":{"node_abi":14,"v8":"3.25"},"0.11.14":{"node_abi":14,"v8":"3.26"},"0.11.15":{"node_abi":14,"v8":"3.28"},"0.11.16":{"node_abi":14,"v8":"3.28"},"0.12.0":{"node_abi":14,"v8":"3.28"},"0.12.1":{"node_abi":14,"v8":"3.28"},"0.12.2":{"node_abi":14,"v8":"3.28"},"0.12.3":{"node_abi":14,"v8":"3.28"},"0.12.4":{"node_abi":14,"v8":"3.28"},"0.12.5":{"node_abi":14,"v8":"3.28"},"0.12.6":{"node_abi":14,"v8":"3.28"},"0.12.7":{"node_abi":14,"v8":"3.28"},"0.12.8":{"node_abi":14,"v8":"3.28"},"0.12.9":{"node_abi":14,"v8":"3.28"},"0.12.10":{"node_abi":14,"v8":"3.28"},"0.12.11":{"node_abi":14,"v8":"3.28"},"0.12.12":{"node_abi":14,"v8":"3.28"},"0.12.13":{"node_abi":14,"v8":"3.28"},"0.12.14":{"node_abi":14,"v8":"3.28"},"0.12.15":{"node_abi":14,"v8":"3.28"},"0.12.16":{"node_abi":14,"v8":"3.28"},"0.12.17":{"node_abi":14,"v8":"3.28"},"0.12.18":{"node_abi":14,"v8":"3.28"},"1.0.0":{"node_abi":42,"v8":"3.31"},"1.0.1":{"node_abi":42,"v8":"3.31"},"1.0.2":{"node_abi":42,"v8":"3.31"},"1.0.3":{"node_abi":42,"v8":"4.1"},"1.0.4":{"node_abi":42,"v8":"4.1"},"1.1.0":{"node_abi":43,"v8":"4.1"},"1.2.0":{"node_abi":43,"v8":"4.1"},"1.3.0":{"node_abi":43,"v8":"4.1"},"1.4.1":{"node_abi":43,"v8":"4.1"},"1.4.2":{"node_abi":43,"v8":"4.1"},"1.4.3":{"node_abi":43,"v8":"4.1"},"1.5.0":{"node_abi":43,"v8":"4.1"},"1.5.1":{"node_abi":43,"v8":"4.1"},"1.6.0":{"node_abi":43,"v8":"4.1"},"1.6.1":{"node_abi":43,"v8":"4.1"},"1.6.2":{"node_abi":43,"v8":"4.1"},"1.6.3":{"node_abi":43,"v8":"4.1"},"1.6.4":{"node_abi":43,"v8":"4.1"},"1.7.1":{"node_abi":43,"v8":"4.1"},"1.8.1":{"node_abi":43,"v8":"4.1"},"1.8.2":{"node_abi":43,"v8":"4.1"},"1.8.3":{"node_abi":43,"v8":"4.1"},"1.8.4":{"node_abi":43,"v8":"4.1"},"2.0.0":{"node_abi":44,"v8":"4.2"},"2.0.1":{"node_abi":44,"v8":"4.2"},"2.0.2":{"node_abi":44,"v8":"4.2"},"2.1.0":{"node_abi":44,"v8":"4.2"},"2.2.0":{"node_abi":44,"v8":"4.2"},"2.2.1":{"node_abi":44,"v8":"4.2"},"2.3.0":{"node_abi":44,"v8":"4.2"},"2.3.1":{"node_abi":44,"v8":"4.2"},"2.3.2":{"node_abi":44,"v8":"4.2"},"2.3.3":{"node_abi":44,"v8":"4.2"},"2.3.4":{"node_abi":44,"v8":"4.2"},"2.4.0":{"node_abi":44,"v8":"4.2"},"2.5.0":{"node_abi":44,"v8":"4.2"},"3.0.0":{"node_abi":45,"v8":"4.4"},"3.1.0":{"node_abi":45,"v8":"4.4"},"3.2.0":{"node_abi":45,"v8":"4.4"},"3.3.0":{"node_abi":45,"v8":"4.4"},"3.3.1":{"node_abi":45,"v8":"4.4"},"4.0.0":{"node_abi":46,"v8":"4.5"},"4.1.0":{"node_abi":46,"v8":"4.5"},"4.1.1":{"node_abi":46,"v8":"4.5"},"4.1.2":{"node_abi":46,"v8":"4.5"},"4.2.0":{"node_abi":46,"v8":"4.5"},"4.2.1":{"node_abi":46,"v8":"4.5"},"4.2.2":{"node_abi":46,"v8":"4.5"},"4.2.3":{"node_abi":46,"v8":"4.5"},"4.2.4":{"node_abi":46,"v8":"4.5"},"4.2.5":{"node_abi":46,"v8":"4.5"},"4.2.6":{"node_abi":46,"v8":"4.5"},"4.3.0":{"node_abi":46,"v8":"4.5"},"4.3.1":{"node_abi":46,"v8":"4.5"},"4.3.2":{"node_abi":46,"v8":"4.5"},"4.4.0":{"node_abi":46,"v8":"4.5"},"4.4.1":{"node_abi":46,"v8":"4.5"},"4.4.2":{"node_abi":46,"v8":"4.5"},"4.4.3":{"node_abi":46,"v8":"4.5"},"4.4.4":{"node_abi":46,"v8":"4.5"},"4.4.5":{"node_abi":46,"v8":"4.5"},"4.4.6":{"node_abi":46,"v8":"4.5"},"4.4.7":{"node_abi":46,"v8":"4.5"},"4.5.0":{"node_abi":46,"v8":"4.5"},"4.6.0":{"node_abi":46,"v8":"4.5"},"4.6.1":{"node_abi":46,"v8":"4.5"},"4.6.2":{"node_abi":46,"v8":"4.5"},"4.7.0":{"node_abi":46,"v8":"4.5"},"4.7.1":{"node_abi":46,"v8":"4.5"},"4.7.2":{"node_abi":46,"v8":"4.5"},"4.7.3":{"node_abi":46,"v8":"4.5"},"4.8.0":{"node_abi":46,"v8":"4.5"},"4.8.1":{"node_abi":46,"v8":"4.5"},"4.8.2":{"node_abi":46,"v8":"4.5"},"4.8.3":{"node_abi":46,"v8":"4.5"},"4.8.4":{"node_abi":46,"v8":"4.5"},"4.8.5":{"node_abi":46,"v8":"4.5"},"4.8.6":{"node_abi":46,"v8":"4.5"},"4.8.7":{"node_abi":46,"v8":"4.5"},"4.9.0":{"node_abi":46,"v8":"4.5"},"4.9.1":{"node_abi":46,"v8":"4.5"},"5.0.0":{"node_abi":47,"v8":"4.6"},"5.1.0":{"node_abi":47,"v8":"4.6"},"5.1.1":{"node_abi":47,"v8":"4.6"},"5.2.0":{"node_abi":47,"v8":"4.6"},"5.3.0":{"node_abi":47,"v8":"4.6"},"5.4.0":{"node_abi":47,"v8":"4.6"},"5.4.1":{"node_abi":47,"v8":"4.6"},"5.5.0":{"node_abi":47,"v8":"4.6"},"5.6.0":{"node_abi":47,"v8":"4.6"},"5.7.0":{"node_abi":47,"v8":"4.6"},"5.7.1":{"node_abi":47,"v8":"4.6"},"5.8.0":{"node_abi":47,"v8":"4.6"},"5.9.0":{"node_abi":47,"v8":"4.6"},"5.9.1":{"node_abi":47,"v8":"4.6"},"5.10.0":{"node_abi":47,"v8":"4.6"},"5.10.1":{"node_abi":47,"v8":"4.6"},"5.11.0":{"node_abi":47,"v8":"4.6"},"5.11.1":{"node_abi":47,"v8":"4.6"},"5.12.0":{"node_abi":47,"v8":"4.6"},"6.0.0":{"node_abi":48,"v8":"5.0"},"6.1.0":{"node_abi":48,"v8":"5.0"},"6.2.0":{"node_abi":48,"v8":"5.0"},"6.2.1":{"node_abi":48,"v8":"5.0"},"6.2.2":{"node_abi":48,"v8":"5.0"},"6.3.0":{"node_abi":48,"v8":"5.0"},"6.3.1":{"node_abi":48,"v8":"5.0"},"6.4.0":{"node_abi":48,"v8":"5.0"},"6.5.0":{"node_abi":48,"v8":"5.1"},"6.6.0":{"node_abi":48,"v8":"5.1"},"6.7.0":{"node_abi":48,"v8":"5.1"},"6.8.0":{"node_abi":48,"v8":"5.1"},"6.8.1":{"node_abi":48,"v8":"5.1"},"6.9.0":{"node_abi":48,"v8":"5.1"},"6.9.1":{"node_abi":48,"v8":"5.1"},"6.9.2":{"node_abi":48,"v8":"5.1"},"6.9.3":{"node_abi":48,"v8":"5.1"},"6.9.4":{"node_abi":48,"v8":"5.1"},"6.9.5":{"node_abi":48,"v8":"5.1"},"6.10.0":{"node_abi":48,"v8":"5.1"},"6.10.1":{"node_abi":48,"v8":"5.1"},"6.10.2":{"node_abi":48,"v8":"5.1"},"6.10.3":{"node_abi":48,"v8":"5.1"},"6.11.0":{"node_abi":48,"v8":"5.1"},"6.11.1":{"node_abi":48,"v8":"5.1"},"6.11.2":{"node_abi":48,"v8":"5.1"},"6.11.3":{"node_abi":48,"v8":"5.1"},"6.11.4":{"node_abi":48,"v8":"5.1"},"6.11.5":{"node_abi":48,"v8":"5.1"},"6.12.0":{"node_abi":48,"v8":"5.1"},"6.12.1":{"node_abi":48,"v8":"5.1"},"6.12.2":{"node_abi":48,"v8":"5.1"},"6.12.3":{"node_abi":48,"v8":"5.1"},"6.13.0":{"node_abi":48,"v8":"5.1"},"6.13.1":{"node_abi":48,"v8":"5.1"},"6.14.0":{"node_abi":48,"v8":"5.1"},"6.14.1":{"node_abi":48,"v8":"5.1"},"6.14.2":{"node_abi":48,"v8":"5.1"},"6.14.3":{"node_abi":48,"v8":"5.1"},"6.14.4":{"node_abi":48,"v8":"5.1"},"6.15.0":{"node_abi":48,"v8":"5.1"},"6.15.1":{"node_abi":48,"v8":"5.1"},"6.16.0":{"node_abi":48,"v8":"5.1"},"6.17.0":{"node_abi":48,"v8":"5.1"},"6.17.1":{"node_abi":48,"v8":"5.1"},"7.0.0":{"node_abi":51,"v8":"5.4"},"7.1.0":{"node_abi":51,"v8":"5.4"},"7.2.0":{"node_abi":51,"v8":"5.4"},"7.2.1":{"node_abi":51,"v8":"5.4"},"7.3.0":{"node_abi":51,"v8":"5.4"},"7.4.0":{"node_abi":51,"v8":"5.4"},"7.5.0":{"node_abi":51,"v8":"5.4"},"7.6.0":{"node_abi":51,"v8":"5.5"},"7.7.0":{"node_abi":51,"v8":"5.5"},"7.7.1":{"node_abi":51,"v8":"5.5"},"7.7.2":{"node_abi":51,"v8":"5.5"},"7.7.3":{"node_abi":51,"v8":"5.5"},"7.7.4":{"node_abi":51,"v8":"5.5"},"7.8.0":{"node_abi":51,"v8":"5.5"},"7.9.0":{"node_abi":51,"v8":"5.5"},"7.10.0":{"node_abi":51,"v8":"5.5"},"7.10.1":{"node_abi":51,"v8":"5.5"},"8.0.0":{"node_abi":57,"v8":"5.8"},"8.1.0":{"node_abi":57,"v8":"5.8"},"8.1.1":{"node_abi":57,"v8":"5.8"},"8.1.2":{"node_abi":57,"v8":"5.8"},"8.1.3":{"node_abi":57,"v8":"5.8"},"8.1.4":{"node_abi":57,"v8":"5.8"},"8.2.0":{"node_abi":57,"v8":"5.8"},"8.2.1":{"node_abi":57,"v8":"5.8"},"8.3.0":{"node_abi":57,"v8":"6.0"},"8.4.0":{"node_abi":57,"v8":"6.0"},"8.5.0":{"node_abi":57,"v8":"6.0"},"8.6.0":{"node_abi":57,"v8":"6.0"},"8.7.0":{"node_abi":57,"v8":"6.1"},"8.8.0":{"node_abi":57,"v8":"6.1"},"8.8.1":{"node_abi":57,"v8":"6.1"},"8.9.0":{"node_abi":57,"v8":"6.1"},"8.9.1":{"node_abi":57,"v8":"6.1"},"8.9.2":{"node_abi":57,"v8":"6.1"},"8.9.3":{"node_abi":57,"v8":"6.1"},"8.9.4":{"node_abi":57,"v8":"6.1"},"8.10.0":{"node_abi":57,"v8":"6.2"},"8.11.0":{"node_abi":57,"v8":"6.2"},"8.11.1":{"node_abi":57,"v8":"6.2"},"8.11.2":{"node_abi":57,"v8":"6.2"},"8.11.3":{"node_abi":57,"v8":"6.2"},"8.11.4":{"node_abi":57,"v8":"6.2"},"8.12.0":{"node_abi":57,"v8":"6.2"},"8.13.0":{"node_abi":57,"v8":"6.2"},"8.14.0":{"node_abi":57,"v8":"6.2"},"8.14.1":{"node_abi":57,"v8":"6.2"},"8.15.0":{"node_abi":57,"v8":"6.2"},"8.15.1":{"node_abi":57,"v8":"6.2"},"8.16.0":{"node_abi":57,"v8":"6.2"},"8.16.1":{"node_abi":57,"v8":"6.2"},"8.16.2":{"node_abi":57,"v8":"6.2"},"8.17.0":{"node_abi":57,"v8":"6.2"},"9.0.0":{"node_abi":59,"v8":"6.2"},"9.1.0":{"node_abi":59,"v8":"6.2"},"9.2.0":{"node_abi":59,"v8":"6.2"},"9.2.1":{"node_abi":59,"v8":"6.2"},"9.3.0":{"node_abi":59,"v8":"6.2"},"9.4.0":{"node_abi":59,"v8":"6.2"},"9.5.0":{"node_abi":59,"v8":"6.2"},"9.6.0":{"node_abi":59,"v8":"6.2"},"9.6.1":{"node_abi":59,"v8":"6.2"},"9.7.0":{"node_abi":59,"v8":"6.2"},"9.7.1":{"node_abi":59,"v8":"6.2"},"9.8.0":{"node_abi":59,"v8":"6.2"},"9.9.0":{"node_abi":59,"v8":"6.2"},"9.10.0":{"node_abi":59,"v8":"6.2"},"9.10.1":{"node_abi":59,"v8":"6.2"},"9.11.0":{"node_abi":59,"v8":"6.2"},"9.11.1":{"node_abi":59,"v8":"6.2"},"9.11.2":{"node_abi":59,"v8":"6.2"},"10.0.0":{"node_abi":64,"v8":"6.6"},"10.1.0":{"node_abi":64,"v8":"6.6"},"10.2.0":{"node_abi":64,"v8":"6.6"},"10.2.1":{"node_abi":64,"v8":"6.6"},"10.3.0":{"node_abi":64,"v8":"6.6"},"10.4.0":{"node_abi":64,"v8":"6.7"},"10.4.1":{"node_abi":64,"v8":"6.7"},"10.5.0":{"node_abi":64,"v8":"6.7"},"10.6.0":{"node_abi":64,"v8":"6.7"},"10.7.0":{"node_abi":64,"v8":"6.7"},"10.8.0":{"node_abi":64,"v8":"6.7"},"10.9.0":{"node_abi":64,"v8":"6.8"},"10.10.0":{"node_abi":64,"v8":"6.8"},"10.11.0":{"node_abi":64,"v8":"6.8"},"10.12.0":{"node_abi":64,"v8":"6.8"},"10.13.0":{"node_abi":64,"v8":"6.8"},"10.14.0":{"node_abi":64,"v8":"6.8"},"10.14.1":{"node_abi":64,"v8":"6.8"},"10.14.2":{"node_abi":64,"v8":"6.8"},"10.15.0":{"node_abi":64,"v8":"6.8"},"10.15.1":{"node_abi":64,"v8":"6.8"},"10.15.2":{"node_abi":64,"v8":"6.8"},"10.15.3":{"node_abi":64,"v8":"6.8"},"10.16.0":{"node_abi":64,"v8":"6.8"},"10.16.1":{"node_abi":64,"v8":"6.8"},"10.16.2":{"node_abi":64,"v8":"6.8"},"10.16.3":{"node_abi":64,"v8":"6.8"},"10.17.0":{"node_abi":64,"v8":"6.8"},"10.18.0":{"node_abi":64,"v8":"6.8"},"10.18.1":{"node_abi":64,"v8":"6.8"},"10.19.0":{"node_abi":64,"v8":"6.8"},"10.20.0":{"node_abi":64,"v8":"6.8"},"10.20.1":{"node_abi":64,"v8":"6.8"},"10.21.0":{"node_abi":64,"v8":"6.8"},"10.22.0":{"node_abi":64,"v8":"6.8"},"10.22.1":{"node_abi":64,"v8":"6.8"},"10.23.0":{"node_abi":64,"v8":"6.8"},"10.23.1":{"node_abi":64,"v8":"6.8"},"10.23.2":{"node_abi":64,"v8":"6.8"},"10.23.3":{"node_abi":64,"v8":"6.8"},"10.24.0":{"node_abi":64,"v8":"6.8"},"10.24.1":{"node_abi":64,"v8":"6.8"},"11.0.0":{"node_abi":67,"v8":"7.0"},"11.1.0":{"node_abi":67,"v8":"7.0"},"11.2.0":{"node_abi":67,"v8":"7.0"},"11.3.0":{"node_abi":67,"v8":"7.0"},"11.4.0":{"node_abi":67,"v8":"7.0"},"11.5.0":{"node_abi":67,"v8":"7.0"},"11.6.0":{"node_abi":67,"v8":"7.0"},"11.7.0":{"node_abi":67,"v8":"7.0"},"11.8.0":{"node_abi":67,"v8":"7.0"},"11.9.0":{"node_abi":67,"v8":"7.0"},"11.10.0":{"node_abi":67,"v8":"7.0"},"11.10.1":{"node_abi":67,"v8":"7.0"},"11.11.0":{"node_abi":67,"v8":"7.0"},"11.12.0":{"node_abi":67,"v8":"7.0"},"11.13.0":{"node_abi":67,"v8":"7.0"},"11.14.0":{"node_abi":67,"v8":"7.0"},"11.15.0":{"node_abi":67,"v8":"7.0"},"12.0.0":{"node_abi":72,"v8":"7.4"},"12.1.0":{"node_abi":72,"v8":"7.4"},"12.2.0":{"node_abi":72,"v8":"7.4"},"12.3.0":{"node_abi":72,"v8":"7.4"},"12.3.1":{"node_abi":72,"v8":"7.4"},"12.4.0":{"node_abi":72,"v8":"7.4"},"12.5.0":{"node_abi":72,"v8":"7.5"},"12.6.0":{"node_abi":72,"v8":"7.5"},"12.7.0":{"node_abi":72,"v8":"7.5"},"12.8.0":{"node_abi":72,"v8":"7.5"},"12.8.1":{"node_abi":72,"v8":"7.5"},"12.9.0":{"node_abi":72,"v8":"7.6"},"12.9.1":{"node_abi":72,"v8":"7.6"},"12.10.0":{"node_abi":72,"v8":"7.6"},"12.11.0":{"node_abi":72,"v8":"7.7"},"12.11.1":{"node_abi":72,"v8":"7.7"},"12.12.0":{"node_abi":72,"v8":"7.7"},"12.13.0":{"node_abi":72,"v8":"7.7"},"12.13.1":{"node_abi":72,"v8":"7.7"},"12.14.0":{"node_abi":72,"v8":"7.7"},"12.14.1":{"node_abi":72,"v8":"7.7"},"12.15.0":{"node_abi":72,"v8":"7.7"},"12.16.0":{"node_abi":72,"v8":"7.8"},"12.16.1":{"node_abi":72,"v8":"7.8"},"12.16.2":{"node_abi":72,"v8":"7.8"},"12.16.3":{"node_abi":72,"v8":"7.8"},"12.17.0":{"node_abi":72,"v8":"7.8"},"12.18.0":{"node_abi":72,"v8":"7.8"},"12.18.1":{"node_abi":72,"v8":"7.8"},"12.18.2":{"node_abi":72,"v8":"7.8"},"12.18.3":{"node_abi":72,"v8":"7.8"},"12.18.4":{"node_abi":72,"v8":"7.8"},"12.19.0":{"node_abi":72,"v8":"7.8"},"12.19.1":{"node_abi":72,"v8":"7.8"},"12.20.0":{"node_abi":72,"v8":"7.8"},"12.20.1":{"node_abi":72,"v8":"7.8"},"12.20.2":{"node_abi":72,"v8":"7.8"},"12.21.0":{"node_abi":72,"v8":"7.8"},"12.22.0":{"node_abi":72,"v8":"7.8"},"12.22.1":{"node_abi":72,"v8":"7.8"},"13.0.0":{"node_abi":79,"v8":"7.8"},"13.0.1":{"node_abi":79,"v8":"7.8"},"13.1.0":{"node_abi":79,"v8":"7.8"},"13.2.0":{"node_abi":79,"v8":"7.9"},"13.3.0":{"node_abi":79,"v8":"7.9"},"13.4.0":{"node_abi":79,"v8":"7.9"},"13.5.0":{"node_abi":79,"v8":"7.9"},"13.6.0":{"node_abi":79,"v8":"7.9"},"13.7.0":{"node_abi":79,"v8":"7.9"},"13.8.0":{"node_abi":79,"v8":"7.9"},"13.9.0":{"node_abi":79,"v8":"7.9"},"13.10.0":{"node_abi":79,"v8":"7.9"},"13.10.1":{"node_abi":79,"v8":"7.9"},"13.11.0":{"node_abi":79,"v8":"7.9"},"13.12.0":{"node_abi":79,"v8":"7.9"},"13.13.0":{"node_abi":79,"v8":"7.9"},"13.14.0":{"node_abi":79,"v8":"7.9"},"14.0.0":{"node_abi":83,"v8":"8.1"},"14.1.0":{"node_abi":83,"v8":"8.1"},"14.2.0":{"node_abi":83,"v8":"8.1"},"14.3.0":{"node_abi":83,"v8":"8.1"},"14.4.0":{"node_abi":83,"v8":"8.1"},"14.5.0":{"node_abi":83,"v8":"8.3"},"14.6.0":{"node_abi":83,"v8":"8.4"},"14.7.0":{"node_abi":83,"v8":"8.4"},"14.8.0":{"node_abi":83,"v8":"8.4"},"14.9.0":{"node_abi":83,"v8":"8.4"},"14.10.0":{"node_abi":83,"v8":"8.4"},"14.10.1":{"node_abi":83,"v8":"8.4"},"14.11.0":{"node_abi":83,"v8":"8.4"},"14.12.0":{"node_abi":83,"v8":"8.4"},"14.13.0":{"node_abi":83,"v8":"8.4"},"14.13.1":{"node_abi":83,"v8":"8.4"},"14.14.0":{"node_abi":83,"v8":"8.4"},"14.15.0":{"node_abi":83,"v8":"8.4"},"14.15.1":{"node_abi":83,"v8":"8.4"},"14.15.2":{"node_abi":83,"v8":"8.4"},"14.15.3":{"node_abi":83,"v8":"8.4"},"14.15.4":{"node_abi":83,"v8":"8.4"},"14.15.5":{"node_abi":83,"v8":"8.4"},"14.16.0":{"node_abi":83,"v8":"8.4"},"14.16.1":{"node_abi":83,"v8":"8.4"},"15.0.0":{"node_abi":88,"v8":"8.6"},"15.0.1":{"node_abi":88,"v8":"8.6"},"15.1.0":{"node_abi":88,"v8":"8.6"},"15.2.0":{"node_abi":88,"v8":"8.6"},"15.2.1":{"node_abi":88,"v8":"8.6"},"15.3.0":{"node_abi":88,"v8":"8.6"},"15.4.0":{"node_abi":88,"v8":"8.6"},"15.5.0":{"node_abi":88,"v8":"8.6"},"15.5.1":{"node_abi":88,"v8":"8.6"},"15.6.0":{"node_abi":88,"v8":"8.6"},"15.7.0":{"node_abi":88,"v8":"8.6"},"15.8.0":{"node_abi":88,"v8":"8.6"},"15.9.0":{"node_abi":88,"v8":"8.6"},"15.10.0":{"node_abi":88,"v8":"8.6"},"15.11.0":{"node_abi":88,"v8":"8.6"},"15.12.0":{"node_abi":88,"v8":"8.6"},"15.13.0":{"node_abi":88,"v8":"8.6"},"15.14.0":{"node_abi":88,"v8":"8.6"},"16.0.0":{"node_abi":93,"v8":"9.0"}}')},9286:e=>{"use strict";e.exports=JSON.parse('{"name":"@mapbox/node-pre-gyp","description":"Node.js native addon binary install tool","version":"1.0.5","keywords":["native","addon","module","c","c++","bindings","binary"],"license":"BSD-3-Clause","author":"Dane Springmeyer ","repository":{"type":"git","url":"git://github.com/mapbox/node-pre-gyp.git"},"bin":"./bin/node-pre-gyp","main":"./lib/node-pre-gyp.js","dependencies":{"detect-libc":"^1.0.3","https-proxy-agent":"^5.0.0","make-dir":"^3.1.0","node-fetch":"^2.6.1","nopt":"^5.0.0","npmlog":"^4.1.2","rimraf":"^3.0.2","semver":"^7.3.4","tar":"^6.1.0"},"devDependencies":{"@mapbox/cloudfriend":"^4.6.0","@mapbox/eslint-config-mapbox":"^3.0.0","action-walk":"^2.2.0","aws-sdk":"^2.840.0","codecov":"^3.8.1","eslint":"^7.18.0","eslint-plugin-node":"^11.1.0","mock-aws-s3":"^4.0.1","nock":"^12.0.3","node-addon-api":"^3.1.0","nyc":"^15.1.0","tape":"^5.2.2","tar-fs":"^2.1.1"},"nyc":{"all":true,"skip-full":false,"exclude":["test/**"]},"scripts":{"coverage":"nyc --all --include index.js --include lib/ npm test","upload-coverage":"nyc report --reporter json && codecov --clear --flags=unit --file=./coverage/coverage-final.json","lint":"eslint bin/node-pre-gyp lib/*js lib/util/*js test/*js scripts/*js","fix":"npm run lint -- --fix","update-crosswalk":"node scripts/abi_crosswalk.js","test":"tape test/*test.js"}}')},7316:e=>{"use strict";e.exports=JSON.parse('{"0.1.14":{"node_abi":null,"v8":"1.3"},"0.1.15":{"node_abi":null,"v8":"1.3"},"0.1.16":{"node_abi":null,"v8":"1.3"},"0.1.17":{"node_abi":null,"v8":"1.3"},"0.1.18":{"node_abi":null,"v8":"1.3"},"0.1.19":{"node_abi":null,"v8":"2.0"},"0.1.20":{"node_abi":null,"v8":"2.0"},"0.1.21":{"node_abi":null,"v8":"2.0"},"0.1.22":{"node_abi":null,"v8":"2.0"},"0.1.23":{"node_abi":null,"v8":"2.0"},"0.1.24":{"node_abi":null,"v8":"2.0"},"0.1.25":{"node_abi":null,"v8":"2.0"},"0.1.26":{"node_abi":null,"v8":"2.0"},"0.1.27":{"node_abi":null,"v8":"2.1"},"0.1.28":{"node_abi":null,"v8":"2.1"},"0.1.29":{"node_abi":null,"v8":"2.1"},"0.1.30":{"node_abi":null,"v8":"2.1"},"0.1.31":{"node_abi":null,"v8":"2.1"},"0.1.32":{"node_abi":null,"v8":"2.1"},"0.1.33":{"node_abi":null,"v8":"2.1"},"0.1.90":{"node_abi":null,"v8":"2.2"},"0.1.91":{"node_abi":null,"v8":"2.2"},"0.1.92":{"node_abi":null,"v8":"2.2"},"0.1.93":{"node_abi":null,"v8":"2.2"},"0.1.94":{"node_abi":null,"v8":"2.2"},"0.1.95":{"node_abi":null,"v8":"2.2"},"0.1.96":{"node_abi":null,"v8":"2.2"},"0.1.97":{"node_abi":null,"v8":"2.2"},"0.1.98":{"node_abi":null,"v8":"2.2"},"0.1.99":{"node_abi":null,"v8":"2.2"},"0.1.100":{"node_abi":null,"v8":"2.2"},"0.1.101":{"node_abi":null,"v8":"2.3"},"0.1.102":{"node_abi":null,"v8":"2.3"},"0.1.103":{"node_abi":null,"v8":"2.3"},"0.1.104":{"node_abi":null,"v8":"2.3"},"0.2.0":{"node_abi":1,"v8":"2.3"},"0.2.1":{"node_abi":1,"v8":"2.3"},"0.2.2":{"node_abi":1,"v8":"2.3"},"0.2.3":{"node_abi":1,"v8":"2.3"},"0.2.4":{"node_abi":1,"v8":"2.3"},"0.2.5":{"node_abi":1,"v8":"2.3"},"0.2.6":{"node_abi":1,"v8":"2.3"},"0.3.0":{"node_abi":1,"v8":"2.5"},"0.3.1":{"node_abi":1,"v8":"2.5"},"0.3.2":{"node_abi":1,"v8":"3.0"},"0.3.3":{"node_abi":1,"v8":"3.0"},"0.3.4":{"node_abi":1,"v8":"3.0"},"0.3.5":{"node_abi":1,"v8":"3.0"},"0.3.6":{"node_abi":1,"v8":"3.0"},"0.3.7":{"node_abi":1,"v8":"3.0"},"0.3.8":{"node_abi":1,"v8":"3.1"},"0.4.0":{"node_abi":1,"v8":"3.1"},"0.4.1":{"node_abi":1,"v8":"3.1"},"0.4.2":{"node_abi":1,"v8":"3.1"},"0.4.3":{"node_abi":1,"v8":"3.1"},"0.4.4":{"node_abi":1,"v8":"3.1"},"0.4.5":{"node_abi":1,"v8":"3.1"},"0.4.6":{"node_abi":1,"v8":"3.1"},"0.4.7":{"node_abi":1,"v8":"3.1"},"0.4.8":{"node_abi":1,"v8":"3.1"},"0.4.9":{"node_abi":1,"v8":"3.1"},"0.4.10":{"node_abi":1,"v8":"3.1"},"0.4.11":{"node_abi":1,"v8":"3.1"},"0.4.12":{"node_abi":1,"v8":"3.1"},"0.5.0":{"node_abi":1,"v8":"3.1"},"0.5.1":{"node_abi":1,"v8":"3.4"},"0.5.2":{"node_abi":1,"v8":"3.4"},"0.5.3":{"node_abi":1,"v8":"3.4"},"0.5.4":{"node_abi":1,"v8":"3.5"},"0.5.5":{"node_abi":1,"v8":"3.5"},"0.5.6":{"node_abi":1,"v8":"3.6"},"0.5.7":{"node_abi":1,"v8":"3.6"},"0.5.8":{"node_abi":1,"v8":"3.6"},"0.5.9":{"node_abi":1,"v8":"3.6"},"0.5.10":{"node_abi":1,"v8":"3.7"},"0.6.0":{"node_abi":1,"v8":"3.6"},"0.6.1":{"node_abi":1,"v8":"3.6"},"0.6.2":{"node_abi":1,"v8":"3.6"},"0.6.3":{"node_abi":1,"v8":"3.6"},"0.6.4":{"node_abi":1,"v8":"3.6"},"0.6.5":{"node_abi":1,"v8":"3.6"},"0.6.6":{"node_abi":1,"v8":"3.6"},"0.6.7":{"node_abi":1,"v8":"3.6"},"0.6.8":{"node_abi":1,"v8":"3.6"},"0.6.9":{"node_abi":1,"v8":"3.6"},"0.6.10":{"node_abi":1,"v8":"3.6"},"0.6.11":{"node_abi":1,"v8":"3.6"},"0.6.12":{"node_abi":1,"v8":"3.6"},"0.6.13":{"node_abi":1,"v8":"3.6"},"0.6.14":{"node_abi":1,"v8":"3.6"},"0.6.15":{"node_abi":1,"v8":"3.6"},"0.6.16":{"node_abi":1,"v8":"3.6"},"0.6.17":{"node_abi":1,"v8":"3.6"},"0.6.18":{"node_abi":1,"v8":"3.6"},"0.6.19":{"node_abi":1,"v8":"3.6"},"0.6.20":{"node_abi":1,"v8":"3.6"},"0.6.21":{"node_abi":1,"v8":"3.6"},"0.7.0":{"node_abi":1,"v8":"3.8"},"0.7.1":{"node_abi":1,"v8":"3.8"},"0.7.2":{"node_abi":1,"v8":"3.8"},"0.7.3":{"node_abi":1,"v8":"3.9"},"0.7.4":{"node_abi":1,"v8":"3.9"},"0.7.5":{"node_abi":1,"v8":"3.9"},"0.7.6":{"node_abi":1,"v8":"3.9"},"0.7.7":{"node_abi":1,"v8":"3.9"},"0.7.8":{"node_abi":1,"v8":"3.9"},"0.7.9":{"node_abi":1,"v8":"3.11"},"0.7.10":{"node_abi":1,"v8":"3.9"},"0.7.11":{"node_abi":1,"v8":"3.11"},"0.7.12":{"node_abi":1,"v8":"3.11"},"0.8.0":{"node_abi":1,"v8":"3.11"},"0.8.1":{"node_abi":1,"v8":"3.11"},"0.8.2":{"node_abi":1,"v8":"3.11"},"0.8.3":{"node_abi":1,"v8":"3.11"},"0.8.4":{"node_abi":1,"v8":"3.11"},"0.8.5":{"node_abi":1,"v8":"3.11"},"0.8.6":{"node_abi":1,"v8":"3.11"},"0.8.7":{"node_abi":1,"v8":"3.11"},"0.8.8":{"node_abi":1,"v8":"3.11"},"0.8.9":{"node_abi":1,"v8":"3.11"},"0.8.10":{"node_abi":1,"v8":"3.11"},"0.8.11":{"node_abi":1,"v8":"3.11"},"0.8.12":{"node_abi":1,"v8":"3.11"},"0.8.13":{"node_abi":1,"v8":"3.11"},"0.8.14":{"node_abi":1,"v8":"3.11"},"0.8.15":{"node_abi":1,"v8":"3.11"},"0.8.16":{"node_abi":1,"v8":"3.11"},"0.8.17":{"node_abi":1,"v8":"3.11"},"0.8.18":{"node_abi":1,"v8":"3.11"},"0.8.19":{"node_abi":1,"v8":"3.11"},"0.8.20":{"node_abi":1,"v8":"3.11"},"0.8.21":{"node_abi":1,"v8":"3.11"},"0.8.22":{"node_abi":1,"v8":"3.11"},"0.8.23":{"node_abi":1,"v8":"3.11"},"0.8.24":{"node_abi":1,"v8":"3.11"},"0.8.25":{"node_abi":1,"v8":"3.11"},"0.8.26":{"node_abi":1,"v8":"3.11"},"0.8.27":{"node_abi":1,"v8":"3.11"},"0.8.28":{"node_abi":1,"v8":"3.11"},"0.9.0":{"node_abi":1,"v8":"3.11"},"0.9.1":{"node_abi":10,"v8":"3.11"},"0.9.2":{"node_abi":10,"v8":"3.11"},"0.9.3":{"node_abi":10,"v8":"3.13"},"0.9.4":{"node_abi":10,"v8":"3.13"},"0.9.5":{"node_abi":10,"v8":"3.13"},"0.9.6":{"node_abi":10,"v8":"3.15"},"0.9.7":{"node_abi":10,"v8":"3.15"},"0.9.8":{"node_abi":10,"v8":"3.15"},"0.9.9":{"node_abi":11,"v8":"3.15"},"0.9.10":{"node_abi":11,"v8":"3.15"},"0.9.11":{"node_abi":11,"v8":"3.14"},"0.9.12":{"node_abi":11,"v8":"3.14"},"0.10.0":{"node_abi":11,"v8":"3.14"},"0.10.1":{"node_abi":11,"v8":"3.14"},"0.10.2":{"node_abi":11,"v8":"3.14"},"0.10.3":{"node_abi":11,"v8":"3.14"},"0.10.4":{"node_abi":11,"v8":"3.14"},"0.10.5":{"node_abi":11,"v8":"3.14"},"0.10.6":{"node_abi":11,"v8":"3.14"},"0.10.7":{"node_abi":11,"v8":"3.14"},"0.10.8":{"node_abi":11,"v8":"3.14"},"0.10.9":{"node_abi":11,"v8":"3.14"},"0.10.10":{"node_abi":11,"v8":"3.14"},"0.10.11":{"node_abi":11,"v8":"3.14"},"0.10.12":{"node_abi":11,"v8":"3.14"},"0.10.13":{"node_abi":11,"v8":"3.14"},"0.10.14":{"node_abi":11,"v8":"3.14"},"0.10.15":{"node_abi":11,"v8":"3.14"},"0.10.16":{"node_abi":11,"v8":"3.14"},"0.10.17":{"node_abi":11,"v8":"3.14"},"0.10.18":{"node_abi":11,"v8":"3.14"},"0.10.19":{"node_abi":11,"v8":"3.14"},"0.10.20":{"node_abi":11,"v8":"3.14"},"0.10.21":{"node_abi":11,"v8":"3.14"},"0.10.22":{"node_abi":11,"v8":"3.14"},"0.10.23":{"node_abi":11,"v8":"3.14"},"0.10.24":{"node_abi":11,"v8":"3.14"},"0.10.25":{"node_abi":11,"v8":"3.14"},"0.10.26":{"node_abi":11,"v8":"3.14"},"0.10.27":{"node_abi":11,"v8":"3.14"},"0.10.28":{"node_abi":11,"v8":"3.14"},"0.10.29":{"node_abi":11,"v8":"3.14"},"0.10.30":{"node_abi":11,"v8":"3.14"},"0.10.31":{"node_abi":11,"v8":"3.14"},"0.10.32":{"node_abi":11,"v8":"3.14"},"0.10.33":{"node_abi":11,"v8":"3.14"},"0.10.34":{"node_abi":11,"v8":"3.14"},"0.10.35":{"node_abi":11,"v8":"3.14"},"0.10.36":{"node_abi":11,"v8":"3.14"},"0.10.37":{"node_abi":11,"v8":"3.14"},"0.10.38":{"node_abi":11,"v8":"3.14"},"0.10.39":{"node_abi":11,"v8":"3.14"},"0.10.40":{"node_abi":11,"v8":"3.14"},"0.10.41":{"node_abi":11,"v8":"3.14"},"0.10.42":{"node_abi":11,"v8":"3.14"},"0.10.43":{"node_abi":11,"v8":"3.14"},"0.10.44":{"node_abi":11,"v8":"3.14"},"0.10.45":{"node_abi":11,"v8":"3.14"},"0.10.46":{"node_abi":11,"v8":"3.14"},"0.10.47":{"node_abi":11,"v8":"3.14"},"0.10.48":{"node_abi":11,"v8":"3.14"},"0.11.0":{"node_abi":12,"v8":"3.17"},"0.11.1":{"node_abi":12,"v8":"3.18"},"0.11.2":{"node_abi":12,"v8":"3.19"},"0.11.3":{"node_abi":12,"v8":"3.19"},"0.11.4":{"node_abi":12,"v8":"3.20"},"0.11.5":{"node_abi":12,"v8":"3.20"},"0.11.6":{"node_abi":12,"v8":"3.20"},"0.11.7":{"node_abi":12,"v8":"3.20"},"0.11.8":{"node_abi":13,"v8":"3.21"},"0.11.9":{"node_abi":13,"v8":"3.22"},"0.11.10":{"node_abi":13,"v8":"3.22"},"0.11.11":{"node_abi":14,"v8":"3.22"},"0.11.12":{"node_abi":14,"v8":"3.22"},"0.11.13":{"node_abi":14,"v8":"3.25"},"0.11.14":{"node_abi":14,"v8":"3.26"},"0.11.15":{"node_abi":14,"v8":"3.28"},"0.11.16":{"node_abi":14,"v8":"3.28"},"0.12.0":{"node_abi":14,"v8":"3.28"},"0.12.1":{"node_abi":14,"v8":"3.28"},"0.12.2":{"node_abi":14,"v8":"3.28"},"0.12.3":{"node_abi":14,"v8":"3.28"},"0.12.4":{"node_abi":14,"v8":"3.28"},"0.12.5":{"node_abi":14,"v8":"3.28"},"0.12.6":{"node_abi":14,"v8":"3.28"},"0.12.7":{"node_abi":14,"v8":"3.28"},"0.12.8":{"node_abi":14,"v8":"3.28"},"0.12.9":{"node_abi":14,"v8":"3.28"},"0.12.10":{"node_abi":14,"v8":"3.28"},"0.12.11":{"node_abi":14,"v8":"3.28"},"0.12.12":{"node_abi":14,"v8":"3.28"},"0.12.13":{"node_abi":14,"v8":"3.28"},"0.12.14":{"node_abi":14,"v8":"3.28"},"0.12.15":{"node_abi":14,"v8":"3.28"},"0.12.16":{"node_abi":14,"v8":"3.28"},"0.12.17":{"node_abi":14,"v8":"3.28"},"0.12.18":{"node_abi":14,"v8":"3.28"},"1.0.0":{"node_abi":42,"v8":"3.31"},"1.0.1":{"node_abi":42,"v8":"3.31"},"1.0.2":{"node_abi":42,"v8":"3.31"},"1.0.3":{"node_abi":42,"v8":"4.1"},"1.0.4":{"node_abi":42,"v8":"4.1"},"1.1.0":{"node_abi":43,"v8":"4.1"},"1.2.0":{"node_abi":43,"v8":"4.1"},"1.3.0":{"node_abi":43,"v8":"4.1"},"1.4.1":{"node_abi":43,"v8":"4.1"},"1.4.2":{"node_abi":43,"v8":"4.1"},"1.4.3":{"node_abi":43,"v8":"4.1"},"1.5.0":{"node_abi":43,"v8":"4.1"},"1.5.1":{"node_abi":43,"v8":"4.1"},"1.6.0":{"node_abi":43,"v8":"4.1"},"1.6.1":{"node_abi":43,"v8":"4.1"},"1.6.2":{"node_abi":43,"v8":"4.1"},"1.6.3":{"node_abi":43,"v8":"4.1"},"1.6.4":{"node_abi":43,"v8":"4.1"},"1.7.1":{"node_abi":43,"v8":"4.1"},"1.8.1":{"node_abi":43,"v8":"4.1"},"1.8.2":{"node_abi":43,"v8":"4.1"},"1.8.3":{"node_abi":43,"v8":"4.1"},"1.8.4":{"node_abi":43,"v8":"4.1"},"2.0.0":{"node_abi":44,"v8":"4.2"},"2.0.1":{"node_abi":44,"v8":"4.2"},"2.0.2":{"node_abi":44,"v8":"4.2"},"2.1.0":{"node_abi":44,"v8":"4.2"},"2.2.0":{"node_abi":44,"v8":"4.2"},"2.2.1":{"node_abi":44,"v8":"4.2"},"2.3.0":{"node_abi":44,"v8":"4.2"},"2.3.1":{"node_abi":44,"v8":"4.2"},"2.3.2":{"node_abi":44,"v8":"4.2"},"2.3.3":{"node_abi":44,"v8":"4.2"},"2.3.4":{"node_abi":44,"v8":"4.2"},"2.4.0":{"node_abi":44,"v8":"4.2"},"2.5.0":{"node_abi":44,"v8":"4.2"},"3.0.0":{"node_abi":45,"v8":"4.4"},"3.1.0":{"node_abi":45,"v8":"4.4"},"3.2.0":{"node_abi":45,"v8":"4.4"},"3.3.0":{"node_abi":45,"v8":"4.4"},"3.3.1":{"node_abi":45,"v8":"4.4"},"4.0.0":{"node_abi":46,"v8":"4.5"},"4.1.0":{"node_abi":46,"v8":"4.5"},"4.1.1":{"node_abi":46,"v8":"4.5"},"4.1.2":{"node_abi":46,"v8":"4.5"},"4.2.0":{"node_abi":46,"v8":"4.5"},"4.2.1":{"node_abi":46,"v8":"4.5"},"4.2.2":{"node_abi":46,"v8":"4.5"},"4.2.3":{"node_abi":46,"v8":"4.5"},"4.2.4":{"node_abi":46,"v8":"4.5"},"4.2.5":{"node_abi":46,"v8":"4.5"},"4.2.6":{"node_abi":46,"v8":"4.5"},"4.3.0":{"node_abi":46,"v8":"4.5"},"4.3.1":{"node_abi":46,"v8":"4.5"},"4.3.2":{"node_abi":46,"v8":"4.5"},"4.4.0":{"node_abi":46,"v8":"4.5"},"4.4.1":{"node_abi":46,"v8":"4.5"},"4.4.2":{"node_abi":46,"v8":"4.5"},"4.4.3":{"node_abi":46,"v8":"4.5"},"4.4.4":{"node_abi":46,"v8":"4.5"},"4.4.5":{"node_abi":46,"v8":"4.5"},"4.4.6":{"node_abi":46,"v8":"4.5"},"4.4.7":{"node_abi":46,"v8":"4.5"},"4.5.0":{"node_abi":46,"v8":"4.5"},"4.6.0":{"node_abi":46,"v8":"4.5"},"4.6.1":{"node_abi":46,"v8":"4.5"},"4.6.2":{"node_abi":46,"v8":"4.5"},"4.7.0":{"node_abi":46,"v8":"4.5"},"4.7.1":{"node_abi":46,"v8":"4.5"},"4.7.2":{"node_abi":46,"v8":"4.5"},"4.7.3":{"node_abi":46,"v8":"4.5"},"4.8.0":{"node_abi":46,"v8":"4.5"},"4.8.1":{"node_abi":46,"v8":"4.5"},"4.8.2":{"node_abi":46,"v8":"4.5"},"4.8.3":{"node_abi":46,"v8":"4.5"},"4.8.4":{"node_abi":46,"v8":"4.5"},"4.8.5":{"node_abi":46,"v8":"4.5"},"4.8.6":{"node_abi":46,"v8":"4.5"},"4.8.7":{"node_abi":46,"v8":"4.5"},"4.9.0":{"node_abi":46,"v8":"4.5"},"4.9.1":{"node_abi":46,"v8":"4.5"},"5.0.0":{"node_abi":47,"v8":"4.6"},"5.1.0":{"node_abi":47,"v8":"4.6"},"5.1.1":{"node_abi":47,"v8":"4.6"},"5.2.0":{"node_abi":47,"v8":"4.6"},"5.3.0":{"node_abi":47,"v8":"4.6"},"5.4.0":{"node_abi":47,"v8":"4.6"},"5.4.1":{"node_abi":47,"v8":"4.6"},"5.5.0":{"node_abi":47,"v8":"4.6"},"5.6.0":{"node_abi":47,"v8":"4.6"},"5.7.0":{"node_abi":47,"v8":"4.6"},"5.7.1":{"node_abi":47,"v8":"4.6"},"5.8.0":{"node_abi":47,"v8":"4.6"},"5.9.0":{"node_abi":47,"v8":"4.6"},"5.9.1":{"node_abi":47,"v8":"4.6"},"5.10.0":{"node_abi":47,"v8":"4.6"},"5.10.1":{"node_abi":47,"v8":"4.6"},"5.11.0":{"node_abi":47,"v8":"4.6"},"5.11.1":{"node_abi":47,"v8":"4.6"},"5.12.0":{"node_abi":47,"v8":"4.6"},"6.0.0":{"node_abi":48,"v8":"5.0"},"6.1.0":{"node_abi":48,"v8":"5.0"},"6.2.0":{"node_abi":48,"v8":"5.0"},"6.2.1":{"node_abi":48,"v8":"5.0"},"6.2.2":{"node_abi":48,"v8":"5.0"},"6.3.0":{"node_abi":48,"v8":"5.0"},"6.3.1":{"node_abi":48,"v8":"5.0"},"6.4.0":{"node_abi":48,"v8":"5.0"},"6.5.0":{"node_abi":48,"v8":"5.1"},"6.6.0":{"node_abi":48,"v8":"5.1"},"6.7.0":{"node_abi":48,"v8":"5.1"},"6.8.0":{"node_abi":48,"v8":"5.1"},"6.8.1":{"node_abi":48,"v8":"5.1"},"6.9.0":{"node_abi":48,"v8":"5.1"},"6.9.1":{"node_abi":48,"v8":"5.1"},"6.9.2":{"node_abi":48,"v8":"5.1"},"6.9.3":{"node_abi":48,"v8":"5.1"},"6.9.4":{"node_abi":48,"v8":"5.1"},"6.9.5":{"node_abi":48,"v8":"5.1"},"6.10.0":{"node_abi":48,"v8":"5.1"},"6.10.1":{"node_abi":48,"v8":"5.1"},"6.10.2":{"node_abi":48,"v8":"5.1"},"6.10.3":{"node_abi":48,"v8":"5.1"},"6.11.0":{"node_abi":48,"v8":"5.1"},"6.11.1":{"node_abi":48,"v8":"5.1"},"6.11.2":{"node_abi":48,"v8":"5.1"},"6.11.3":{"node_abi":48,"v8":"5.1"},"6.11.4":{"node_abi":48,"v8":"5.1"},"6.11.5":{"node_abi":48,"v8":"5.1"},"6.12.0":{"node_abi":48,"v8":"5.1"},"6.12.1":{"node_abi":48,"v8":"5.1"},"6.12.2":{"node_abi":48,"v8":"5.1"},"6.12.3":{"node_abi":48,"v8":"5.1"},"6.13.0":{"node_abi":48,"v8":"5.1"},"6.13.1":{"node_abi":48,"v8":"5.1"},"6.14.0":{"node_abi":48,"v8":"5.1"},"6.14.1":{"node_abi":48,"v8":"5.1"},"6.14.2":{"node_abi":48,"v8":"5.1"},"6.14.3":{"node_abi":48,"v8":"5.1"},"6.14.4":{"node_abi":48,"v8":"5.1"},"6.15.0":{"node_abi":48,"v8":"5.1"},"6.15.1":{"node_abi":48,"v8":"5.1"},"6.16.0":{"node_abi":48,"v8":"5.1"},"6.17.0":{"node_abi":48,"v8":"5.1"},"6.17.1":{"node_abi":48,"v8":"5.1"},"7.0.0":{"node_abi":51,"v8":"5.4"},"7.1.0":{"node_abi":51,"v8":"5.4"},"7.2.0":{"node_abi":51,"v8":"5.4"},"7.2.1":{"node_abi":51,"v8":"5.4"},"7.3.0":{"node_abi":51,"v8":"5.4"},"7.4.0":{"node_abi":51,"v8":"5.4"},"7.5.0":{"node_abi":51,"v8":"5.4"},"7.6.0":{"node_abi":51,"v8":"5.5"},"7.7.0":{"node_abi":51,"v8":"5.5"},"7.7.1":{"node_abi":51,"v8":"5.5"},"7.7.2":{"node_abi":51,"v8":"5.5"},"7.7.3":{"node_abi":51,"v8":"5.5"},"7.7.4":{"node_abi":51,"v8":"5.5"},"7.8.0":{"node_abi":51,"v8":"5.5"},"7.9.0":{"node_abi":51,"v8":"5.5"},"7.10.0":{"node_abi":51,"v8":"5.5"},"7.10.1":{"node_abi":51,"v8":"5.5"},"8.0.0":{"node_abi":57,"v8":"5.8"},"8.1.0":{"node_abi":57,"v8":"5.8"},"8.1.1":{"node_abi":57,"v8":"5.8"},"8.1.2":{"node_abi":57,"v8":"5.8"},"8.1.3":{"node_abi":57,"v8":"5.8"},"8.1.4":{"node_abi":57,"v8":"5.8"},"8.2.0":{"node_abi":57,"v8":"5.8"},"8.2.1":{"node_abi":57,"v8":"5.8"},"8.3.0":{"node_abi":57,"v8":"6.0"},"8.4.0":{"node_abi":57,"v8":"6.0"},"8.5.0":{"node_abi":57,"v8":"6.0"},"8.6.0":{"node_abi":57,"v8":"6.0"},"8.7.0":{"node_abi":57,"v8":"6.1"},"8.8.0":{"node_abi":57,"v8":"6.1"},"8.8.1":{"node_abi":57,"v8":"6.1"},"8.9.0":{"node_abi":57,"v8":"6.1"},"8.9.1":{"node_abi":57,"v8":"6.1"},"8.9.2":{"node_abi":57,"v8":"6.1"},"8.9.3":{"node_abi":57,"v8":"6.1"},"8.9.4":{"node_abi":57,"v8":"6.1"},"8.10.0":{"node_abi":57,"v8":"6.2"},"8.11.0":{"node_abi":57,"v8":"6.2"},"8.11.1":{"node_abi":57,"v8":"6.2"},"8.11.2":{"node_abi":57,"v8":"6.2"},"8.11.3":{"node_abi":57,"v8":"6.2"},"8.11.4":{"node_abi":57,"v8":"6.2"},"8.12.0":{"node_abi":57,"v8":"6.2"},"8.13.0":{"node_abi":57,"v8":"6.2"},"8.14.0":{"node_abi":57,"v8":"6.2"},"8.14.1":{"node_abi":57,"v8":"6.2"},"8.15.0":{"node_abi":57,"v8":"6.2"},"8.15.1":{"node_abi":57,"v8":"6.2"},"8.16.0":{"node_abi":57,"v8":"6.2"},"9.0.0":{"node_abi":59,"v8":"6.2"},"9.1.0":{"node_abi":59,"v8":"6.2"},"9.2.0":{"node_abi":59,"v8":"6.2"},"9.2.1":{"node_abi":59,"v8":"6.2"},"9.3.0":{"node_abi":59,"v8":"6.2"},"9.4.0":{"node_abi":59,"v8":"6.2"},"9.5.0":{"node_abi":59,"v8":"6.2"},"9.6.0":{"node_abi":59,"v8":"6.2"},"9.6.1":{"node_abi":59,"v8":"6.2"},"9.7.0":{"node_abi":59,"v8":"6.2"},"9.7.1":{"node_abi":59,"v8":"6.2"},"9.8.0":{"node_abi":59,"v8":"6.2"},"9.9.0":{"node_abi":59,"v8":"6.2"},"9.10.0":{"node_abi":59,"v8":"6.2"},"9.10.1":{"node_abi":59,"v8":"6.2"},"9.11.0":{"node_abi":59,"v8":"6.2"},"9.11.1":{"node_abi":59,"v8":"6.2"},"9.11.2":{"node_abi":59,"v8":"6.2"},"10.0.0":{"node_abi":64,"v8":"6.6"},"10.1.0":{"node_abi":64,"v8":"6.6"},"10.2.0":{"node_abi":64,"v8":"6.6"},"10.2.1":{"node_abi":64,"v8":"6.6"},"10.3.0":{"node_abi":64,"v8":"6.6"},"10.4.0":{"node_abi":64,"v8":"6.7"},"10.4.1":{"node_abi":64,"v8":"6.7"},"10.5.0":{"node_abi":64,"v8":"6.7"},"10.6.0":{"node_abi":64,"v8":"6.7"},"10.7.0":{"node_abi":64,"v8":"6.7"},"10.8.0":{"node_abi":64,"v8":"6.7"},"10.9.0":{"node_abi":64,"v8":"6.8"},"10.10.0":{"node_abi":64,"v8":"6.8"},"10.11.0":{"node_abi":64,"v8":"6.8"},"10.12.0":{"node_abi":64,"v8":"6.8"},"10.13.0":{"node_abi":64,"v8":"6.8"},"10.14.0":{"node_abi":64,"v8":"6.8"},"10.14.1":{"node_abi":64,"v8":"6.8"},"10.14.2":{"node_abi":64,"v8":"6.8"},"10.15.0":{"node_abi":64,"v8":"6.8"},"10.15.1":{"node_abi":64,"v8":"6.8"},"10.15.2":{"node_abi":64,"v8":"6.8"},"10.15.3":{"node_abi":64,"v8":"6.8"},"11.0.0":{"node_abi":67,"v8":"7.0"},"11.1.0":{"node_abi":67,"v8":"7.0"},"11.2.0":{"node_abi":67,"v8":"7.0"},"11.3.0":{"node_abi":67,"v8":"7.0"},"11.4.0":{"node_abi":67,"v8":"7.0"},"11.5.0":{"node_abi":67,"v8":"7.0"},"11.6.0":{"node_abi":67,"v8":"7.0"},"11.7.0":{"node_abi":67,"v8":"7.0"},"11.8.0":{"node_abi":67,"v8":"7.0"},"11.9.0":{"node_abi":67,"v8":"7.0"},"11.10.0":{"node_abi":67,"v8":"7.0"},"11.10.1":{"node_abi":67,"v8":"7.0"},"11.11.0":{"node_abi":67,"v8":"7.0"},"11.12.0":{"node_abi":67,"v8":"7.0"},"11.13.0":{"node_abi":67,"v8":"7.0"},"11.14.0":{"node_abi":67,"v8":"7.0"},"12.0.0":{"node_abi":72,"v8":"7.4"}}')}};var __webpack_module_cache__={};function __nccwpck_require__(e){var t=__webpack_module_cache__[e];if(t!==undefined){return t.exports}var r=__webpack_module_cache__[e]={exports:{}};var a=true;try{__webpack_modules__[e].call(r.exports,r,r.exports,__nccwpck_require__);a=false}finally{if(a)delete __webpack_module_cache__[e]}return r.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var __webpack_exports__=__nccwpck_require__(9582);module.exports=__webpack_exports__})(); \ No newline at end of file + */var isNumber=function(e){if(typeof e==="number"){return e-e===0}if(typeof e==="string"&&e.trim()!==""){return Number.isFinite?Number.isFinite(+e):isFinite(+e)}return false};const toRegexRange=(e,t,r)=>{if(isNumber(e)===false){throw new TypeError("toRegexRange: expected the first argument to be a number")}if(t===void 0||e===t){return String(e)}if(isNumber(t)===false){throw new TypeError("toRegexRange: expected the second argument to be a number.")}let s=Object.assign({relaxZeros:true},r);if(typeof s.strictZeros==="boolean"){s.relaxZeros=s.strictZeros===false}let a=String(s.relaxZeros);let o=String(s.shorthand);let u=String(s.capture);let c=String(s.wrap);let f=e+":"+t+"="+a+o+u+c;if(toRegexRange.cache.hasOwnProperty(f)){return toRegexRange.cache[f].result}let p=Math.min(e,t);let d=Math.max(e,t);if(Math.abs(p-d)===1){let r=e+"|"+t;if(s.capture){return`(${r})`}if(s.wrap===false){return r}return`(?:${r})`}let h=hasPadding(e)||hasPadding(t);let v={min:e,max:t,a:p,b:d};let g=[];let m=[];if(h){v.isPadded=h;v.maxLen=String(v.max).length}if(p<0){let e=d<0?Math.abs(d):1;m=splitToPatterns(e,Math.abs(p),v,s);p=v.a=0}if(d>=0){g=splitToPatterns(p,d,v,s)}v.negatives=m;v.positives=g;v.result=collatePatterns(m,g,s);if(s.capture===true){v.result=`(${v.result})`}else if(s.wrap!==false&&g.length+m.length>1){v.result=`(?:${v.result})`}toRegexRange.cache[f]=v;return v.result};function collatePatterns(e,t,r){let s=filterPatterns(e,t,"-",false,r)||[];let a=filterPatterns(t,e,"",false,r)||[];let o=filterPatterns(e,t,"-?",true,r)||[];let u=s.concat(o).concat(a);return u.join("|")}function splitToRanges(e,t){let r=1;let s=1;let a=countNines(e,r);let o=new Set([t]);while(e<=a&&a<=t){o.add(a);r+=1;a=countNines(e,r)}a=countZeros(t+1,s)-1;while(e1){c.count.pop()}c.count.push(f.count[0]);c.string=c.pattern+toQuantifier(c.count);u=t+1;continue}if(r.isPadded){p=padZeros(t,r,s)}f.string=p+f.pattern+toQuantifier(f.count);o.push(f);u=t+1;c=f}return o}function filterPatterns(e,t,r,s,a){let o=[];for(let a of e){let{string:e}=a;if(!s&&!contains(t,"string",e)){o.push(r+e)}if(s&&contains(t,"string",e)){o.push(r+e)}}return o}function zip(e,t){let r=[];for(let s=0;st?1:t>e?-1:0}function contains(e,t,r){return e.some((e=>e[t]===r))}function countNines(e,t){return Number(String(e).slice(0,-t)+"9".repeat(t))}function countZeros(e,t){return e-e%Math.pow(10,t)}function toQuantifier(e){let[t=0,r=""]=e;if(r||t>1){return`{${t+(r?","+r:"")}}`}return""}function toCharacterClass(e,t,r){return`[${e}${t-e===1?"":"-"}${t}]`}function hasPadding(e){return/^-?(0+)\d/.test(e)}function padZeros(e,t,r){if(!t.isPadded){return e}let s=Math.abs(t.maxLen-String(e).length);let a=r.relaxZeros!==false;switch(s){case 0:return"";case 1:return a?"0?":"0";case 2:return a?"0{0,2}":"00";default:{return a?`0{0,${s}}`:`0{${s}}`}}}toRegexRange.cache={};toRegexRange.clearCache=()=>toRegexRange.cache={};var A=toRegexRange;const isObject=e=>e!==null&&typeof e==="object"&&!Array.isArray(e);const transform=e=>t=>e===true?Number(t):String(t);const isValidValue=e=>typeof e==="number"||typeof e==="string"&&e!=="";const isNumber$1=e=>Number.isInteger(+e);const zeros=e=>{let t=`${e}`;let r=-1;if(t[0]==="-")t=t.slice(1);if(t==="0")return false;while(t[++r]==="0");return r>0};const stringify$1=(e,t,r)=>{if(typeof e==="string"||typeof t==="string"){return true}return r.stringify===true};const pad=(e,t,r)=>{if(t>0){let r=e[0]==="-"?"-":"";if(r)e=e.slice(1);e=r+e.padStart(r?t-1:t,"0")}if(r===false){return String(e)}return e};const toMaxLen=(e,t)=>{let r=e[0]==="-"?"-":"";if(r){e=e.slice(1);t--}while(e.length{e.negatives.sort(((e,t)=>et?1:0));e.positives.sort(((e,t)=>et?1:0));let r=t.capture?"":"?:";let s="";let a="";let o;if(e.positives.length){s=e.positives.join("|")}if(e.negatives.length){a=`-(${r}${e.negatives.join("|")})`}if(s&&a){o=`${s}|${a}`}else{o=s||a}if(t.wrap){return`(${r}${o})`}return o};const toRange=(e,t,r,s)=>{if(r){return A(e,t,Object.assign({wrap:false},s))}let a=String.fromCharCode(e);if(e===t)return a;let o=String.fromCharCode(t);return`[${a}-${o}]`};const toRegex=(e,t,r)=>{if(Array.isArray(e)){let t=r.wrap===true;let s=r.capture?"":"?:";return t?`(${s}${e.join("|")})`:e.join("|")}return A(e,t,r)};const rangeError=(...e)=>new RangeError("Invalid range arguments: "+u.inspect(...e));const invalidRange=(e,t,r)=>{if(r.strictRanges===true)throw rangeError([e,t]);return[]};const invalidStep=(e,t)=>{if(t.strictRanges===true){throw new TypeError(`Expected step "${e}" to be a number`)}return[]};const fillNumbers=(e,t,r=1,s={})=>{let a=Number(e);let o=Number(t);if(!Number.isInteger(a)||!Number.isInteger(o)){if(s.strictRanges===true)throw rangeError([e,t]);return[]}if(a===0)a=0;if(o===0)o=0;let u=a>o;let c=String(e);let f=String(t);let p=String(r);r=Math.max(Math.abs(r),1);let d=zeros(c)||zeros(f)||zeros(p);let h=d?Math.max(c.length,f.length,p.length):0;let v=d===false&&stringify$1(e,t,s)===false;let g=s.transform||transform(v);if(s.toRegex&&r===1){return toRange(toMaxLen(e,h),toMaxLen(t,h),true,s)}let m={negatives:[],positives:[]};let push=e=>m[e<0?"negatives":"positives"].push(Math.abs(e));let _=[];let y=0;while(u?a>=o:a<=o){if(s.toRegex===true&&r>1){push(a)}else{_.push(pad(g(a,y),h,v))}a=u?a-r:a+r;y++}if(s.toRegex===true){return r>1?toSequence(m,s):toRegex(_,null,Object.assign({wrap:false},s))}return _};const fillLetters=(e,t,r=1,s={})=>{if(!isNumber$1(e)&&e.length>1||!isNumber$1(t)&&t.length>1){return invalidRange(e,t,s)}let a=s.transform||(e=>String.fromCharCode(e));let o=`${e}`.charCodeAt(0);let u=`${t}`.charCodeAt(0);let c=o>u;let f=Math.min(o,u);let p=Math.max(o,u);if(s.toRegex&&r===1){return toRange(f,p,false,s)}let d=[];let h=0;while(c?o>=u:o<=u){d.push(a(o,h));o=c?o-r:o+r;h++}if(s.toRegex===true){return toRegex(d,null,{wrap:false,options:s})}return d};const fill=(e,t,r,s={})=>{if(t==null&&isValidValue(e)){return[e]}if(!isValidValue(e)||!isValidValue(t)){return invalidRange(e,t,s)}if(typeof r==="function"){return fill(e,t,1,{transform:r})}if(isObject(r)){return fill(e,t,0,r)}let a=Object.assign({},s);if(a.capture===true)a.wrap=true;r=r||a.step||1;if(!isNumber$1(r)){if(r!=null&&!isObject(r))return invalidStep(r,a);return fill(e,t,1,r)}if(isNumber$1(e)&&isNumber$1(t)){return fillNumbers(e,t,r,a)}return fillLetters(e,t,Math.max(Math.abs(r),1),a)};var C=fill;const compile=(e,t={})=>{let walk=(e,r={})=>{let s=v.isInvalidBrace(r);let a=e.invalid===true&&t.escapeInvalid===true;let o=s===true||a===true;let u=t.escapeInvalid===true?"\\":"";let c="";if(e.isOpen===true){return u+e.value}if(e.isClose===true){return u+e.value}if(e.type==="open"){return o?u+e.value:"("}if(e.type==="close"){return o?u+e.value:")"}if(e.type==="comma"){return e.prev.type==="comma"?"":o?e.value:"|"}if(e.value){return e.value}if(e.nodes&&e.ranges>0){let r=v.reduce(e.nodes);let s=C(...r,Object.assign({},t,{wrap:false,toRegex:true}));if(s.length!==0){return r.length>1&&s.length>1?`(${s})`:s}}if(e.nodes){for(let t of e.nodes){c+=walk(t,e)}}return c};return walk(e)};var R=compile;const append=(e="",t="",r=false)=>{let s=[];e=[].concat(e);t=[].concat(t);if(!t.length)return e;if(!e.length){return r?v.flatten(t).map((e=>`{${e}}`)):t}for(let a of e){if(Array.isArray(a)){for(let e of a){s.push(append(e,t,r))}}else{for(let e of t){if(r===true&&typeof e==="string")e=`{${e}}`;s.push(Array.isArray(e)?append(a,e,r):a+e)}}}return v.flatten(s)};const expand=(e,t={})=>{let r=t.rangeLimit===void 0?1e3:t.rangeLimit;let walk=(e,s={})=>{e.queue=[];let a=s;let o=s.queue;while(a.type!=="brace"&&a.type!=="root"&&a.parent){a=a.parent;o=a.queue}if(e.invalid||e.dollar){o.push(append(o.pop(),stringify(e,t)));return}if(e.type==="brace"&&e.invalid!==true&&e.nodes.length===2){o.push(append(o.pop(),["{}"]));return}if(e.nodes&&e.ranges>0){let s=v.reduce(e.nodes);if(v.exceedsLimit(...s,t.step,r)){throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.")}let a=C(...s,t);if(a.length===0){a=stringify(e,t)}o.push(append(o.pop(),a));e.nodes=[];return}let u=v.encloseBrace(e);let c=e.queue;let f=e;while(f.type!=="brace"&&f.type!=="root"&&f.parent){f=f.parent;c=f.queue}for(let t=0;t",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:"\t",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\ufeff"};const{MAX_LENGTH:O,CHAR_BACKSLASH:N,CHAR_BACKTICK:P,CHAR_COMMA:L,CHAR_DOT:j,CHAR_LEFT_PARENTHESES:D,CHAR_RIGHT_PARENTHESES:M,CHAR_LEFT_CURLY_BRACE:F,CHAR_RIGHT_CURLY_BRACE:B,CHAR_LEFT_SQUARE_BRACKET:W,CHAR_RIGHT_SQUARE_BRACKET:U,CHAR_DOUBLE_QUOTE:V,CHAR_SINGLE_QUOTE:q,CHAR_NO_BREAK_SPACE:H,CHAR_ZERO_WIDTH_NOBREAK_SPACE:$}=I;const parse=(e,t={})=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}let r=t||{};let s=typeof r.maxLength==="number"?Math.min(O,r.maxLength):O;if(e.length>s){throw new SyntaxError(`Input length (${e.length}), exceeds max characters (${s})`)}let a={type:"root",input:e,nodes:[]};let o=[a];let u=a;let c=a;let f=0;let p=e.length;let d=0;let h=0;let v;const advance=()=>e[d++];const push=e=>{if(e.type==="text"&&c.type==="dot"){c.type="text"}if(c&&c.type==="text"&&e.type==="text"){c.value+=e.value;return}u.nodes.push(e);e.parent=u;e.prev=c;c=e;return e};push({type:"bos"});while(d0){if(u.ranges>0){u.ranges=0;let e=u.nodes.shift();u.nodes=[e,{type:"text",value:stringify(u)}]}push({type:"comma",value:v});u.commas++;continue}if(v===j&&h>0&&u.commas===0){let e=u.nodes;if(h===0||e.length===0){push({type:"text",value:v});continue}if(c.type==="dot"){u.range=[];c.value+=v;c.type="range";if(u.nodes.length!==3&&u.nodes.length!==5){u.invalid=true;u.ranges=0;c.type="text";continue}u.ranges++;u.args=[];continue}if(c.type==="range"){e.pop();let t=e[e.length-1];t.value+=c.value+v;c=t;u.ranges--;continue}push({type:"dot",value:v});continue}push({type:"text",value:v})}do{u=o.pop();if(u.type!=="root"){u.nodes.forEach((e=>{if(!e.nodes){if(e.type==="open")e.isOpen=true;if(e.type==="close")e.isClose=true;if(!e.nodes)e.type="text";e.invalid=true}}));let e=o[o.length-1];let t=e.nodes.indexOf(u);e.nodes.splice(t,1,...u.nodes)}}while(o.length>0);push({type:"eos"});return a};var G=parse;const braces=(e,t={})=>{let r=[];if(Array.isArray(e)){for(let s of e){let e=braces.create(s,t);if(Array.isArray(e)){r.push(...e)}else{r.push(e)}}}else{r=[].concat(braces.create(e,t))}if(t&&t.expand===true&&t.nodupes===true){r=[...new Set(r)]}return r};braces.parse=(e,t={})=>G(e,t);braces.stringify=(e,t={})=>{if(typeof e==="string"){return stringify(braces.parse(e,t),t)}return stringify(e,t)};braces.compile=(e,t={})=>{if(typeof e==="string"){e=braces.parse(e,t)}return R(e,t)};braces.expand=(e,t={})=>{if(typeof e==="string"){e=braces.parse(e,t)}let r=T(e,t);if(t.noempty===true){r=r.filter(Boolean)}if(t.nodupes===true){r=[...new Set(r)]}return r};braces.create=(e,t={})=>{if(e===""||e.length<3){return[e]}return t.expand!==true?braces.compile(e,t):braces.expand(e,t)};var K=braces;const z="\\\\/";const Q=`[^${z}]`;const Y="\\.";const X="\\+";const Z="\\?";const J="\\/";const ee="(?=.)";const te="[^/]";const ie=`(?:${J}|$)`;const re=`(?:^|${J})`;const ne=`${Y}{1,2}${ie}`;const se=`(?!${Y})`;const ae=`(?!${re}${ne})`;const oe=`(?!${Y}{0,1}${ie})`;const le=`(?!${ne})`;const ue=`[^.${J}]`;const ce=`${te}*?`;const fe={DOT_LITERAL:Y,PLUS_LITERAL:X,QMARK_LITERAL:Z,SLASH_LITERAL:J,ONE_CHAR:ee,QMARK:te,END_ANCHOR:ie,DOTS_SLASH:ne,NO_DOT:se,NO_DOTS:ae,NO_DOT_SLASH:oe,NO_DOTS_SLASH:le,QMARK_NO_DOT:ue,STAR:ce,START_ANCHOR:re};const pe=Object.assign({},fe,{SLASH_LITERAL:`[${z}]`,QMARK:Q,STAR:`${Q}*?`,DOTS_SLASH:`${Y}{1,2}(?:[${z}]|$)`,NO_DOT:`(?!${Y})`,NO_DOTS:`(?!(?:^|[${z}])${Y}{1,2}(?:[${z}]|$))`,NO_DOT_SLASH:`(?!${Y}{0,1}(?:[${z}]|$))`,NO_DOTS_SLASH:`(?!${Y}{1,2}(?:[${z}]|$))`,QMARK_NO_DOT:`[^.${z}]`,START_ANCHOR:`(?:^|[${z}])`,END_ANCHOR:`(?:[${z}]|$)`});const de={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};var he={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:de,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHAR:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:a.sep,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?pe:fe}};var ve=createCommonjsModule((function(e,t){const r=process.platform==="win32";const{REGEX_SPECIAL_CHARS:s,REGEX_SPECIAL_CHARS_GLOBAL:o,REGEX_REMOVE_BACKSLASH:u}=he;t.isObject=e=>e!==null&&typeof e==="object"&&!Array.isArray(e);t.hasRegexChars=e=>s.test(e);t.isRegexChar=e=>e.length===1&&t.hasRegexChars(e);t.escapeRegex=e=>e.replace(o,"\\$1");t.toPosixSlashes=e=>e.replace(/\\/g,"/");t.removeBackslashes=e=>e.replace(u,(e=>e==="\\"?"":e));t.supportsLookbehinds=()=>{let e=process.version.slice(1).split(".");if(e.length===3&&+e[0]>=9||+e[0]===8&&+e[1]>=10){return true}return false};t.isWindows=e=>{if(e&&typeof e.windows==="boolean"){return e.windows}return r===true||a.sep==="\\"};t.escapeLast=(e,r,s)=>{let a=e.lastIndexOf(r,s);if(a===-1)return e;if(e[a-1]==="\\")return t.escapeLast(e,r,a-1);return e.slice(0,a)+"\\"+e.slice(a)}}));var be=ve.isObject;var ge=ve.hasRegexChars;var me=ve.isRegexChar;var _e=ve.escapeRegex;var ye=ve.toPosixSlashes;var xe=ve.removeBackslashes;var we=ve.supportsLookbehinds;var Ee=ve.isWindows;var Se=ve.escapeLast;const{CHAR_ASTERISK:ke,CHAR_AT:Ae,CHAR_BACKWARD_SLASH:Ce,CHAR_COMMA:Re,CHAR_DOT:Te,CHAR_EXCLAMATION_MARK:Ie,CHAR_FORWARD_SLASH:Oe,CHAR_LEFT_CURLY_BRACE:Ne,CHAR_LEFT_PARENTHESES:Pe,CHAR_LEFT_SQUARE_BRACKET:Le,CHAR_PLUS:je,CHAR_QUESTION_MARK:De,CHAR_RIGHT_CURLY_BRACE:Me,CHAR_RIGHT_PARENTHESES:Fe,CHAR_RIGHT_SQUARE_BRACKET:Be}=he;const isPathSeparator=e=>e===Oe||e===Ce;var scan=(e,t)=>{let r=t||{};let s=e.length-1;let a=-1;let o=0;let u=0;let c=false;let f=false;let p=false;let d=0;let h;let v;let g=false;let eos=()=>a>=s;let advance=()=>{h=v;return e.charCodeAt(++a)};while(a0){m=e.slice(0,o);e=e.slice(o);u-=o}if(y&&c===true&&u>0){y=e.slice(0,u);x=e.slice(u)}else if(c===true){y="";x=e}else{y=e}if(y&&y!==""&&y!=="/"&&y!==e){if(isPathSeparator(y.charCodeAt(y.length-1))){y=y.slice(0,-1)}}if(r.unescape===true){if(x)x=ve.removeBackslashes(x);if(y&&f===true){y=ve.removeBackslashes(y)}}return{prefix:m,input:_,base:y,glob:x,negated:p,isGlob:c}};const{MAX_LENGTH:We,POSIX_REGEX_SOURCE:Ue,REGEX_NON_SPECIAL_CHAR:Ve,REGEX_SPECIAL_CHARS_BACKREF:qe,REPLACEMENTS:He}=he;const expandRange=(e,t)=>{if(typeof t.expandRange==="function"){return t.expandRange(...e,t)}e.sort();let r=`[${e.join("-")}]`;try{}catch(t){return e.map((e=>ve.escapeRegex(e))).join("..")}return r};const negate=e=>{let t=1;while(e.peek()==="!"&&(e.peek(2)!=="("||e.peek(3)==="?")){e.advance();e.start++;t++}if(t%2===0){return false}e.negated=true;e.start++;return true};const syntaxError=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`;const parse$1=(e,t)=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}e=He[e]||e;let r=Object.assign({},t);let s=typeof r.maxLength==="number"?Math.min(We,r.maxLength):We;let a=e.length;if(a>s){throw new SyntaxError(`Input length: ${a}, exceeds maximum allowed length: ${s}`)}let o={type:"bos",value:"",output:r.prepend||""};let u=[o];let c=r.capture?"":"?:";let f=ve.isWindows(t);const p=he.globChars(f);const d=he.extglobChars(p);const{DOT_LITERAL:h,PLUS_LITERAL:v,SLASH_LITERAL:g,ONE_CHAR:m,DOTS_SLASH:_,NO_DOT:y,NO_DOT_SLASH:x,NO_DOTS_SLASH:w,QMARK:E,QMARK_NO_DOT:S,STAR:k,START_ANCHOR:A}=p;const globstar=e=>`(${c}(?:(?!${A}${e.dot?_:h}).)*?)`;let C=r.dot?"":y;let R=r.bash===true?globstar(r):k;let T=r.dot?E:S;if(r.capture){R=`(${R})`}if(typeof r.noext==="boolean"){r.noextglob=r.noext}let I={index:-1,start:0,consumed:"",output:"",backtrack:false,brackets:0,braces:0,parens:0,quotes:0,tokens:u};let O=[];let N=[];let P=o;let L;const eos=()=>I.index===a-1;const j=I.peek=(t=1)=>e[I.index+t];const D=I.advance=()=>e[++I.index];const append=e=>{I.output+=e.output!=null?e.output:e.value;I.consumed+=e.value||""};const increment=e=>{I[e]++;N.push(e)};const decrement=e=>{I[e]--;N.pop()};const push=e=>{if(P.type==="globstar"){let t=I.braces>0&&(e.type==="comma"||e.type==="brace");let r=O.length&&(e.type==="pipe"||e.type==="paren");if(e.type!=="slash"&&e.type!=="paren"&&!t&&!r){I.output=I.output.slice(0,-P.output.length);P.type="star";P.value="*";P.output=R;I.output+=P.output}}if(O.length&&e.type!=="paren"&&!d[e.value]){O[O.length-1].inner+=e.value}if(e.value||e.output)append(e);if(P&&P.type==="text"&&e.type==="text"){P.value+=e.value;return}e.prev=P;u.push(e);P=e};const extglobOpen=(e,t)=>{let s=Object.assign({},d[t],{conditions:1,inner:""});s.prev=P;s.parens=I.parens;s.output=I.output;let a=(r.capture?"(":"")+s.open;push({type:e,value:t,output:I.output?"":m});push({type:"paren",extglob:true,value:D(),output:a});increment("parens");O.push(s)};const extglobClose=t=>{let s=t.close+(r.capture?")":"");if(t.type==="negate"){let a=R;if(t.inner&&t.inner.length>1&&t.inner.includes("/")){a=globstar(r)}if(a!==R||eos()||/^\)+$/.test(e.slice(I.index+1))){s=t.close=")$))"+a}if(t.prev.type==="bos"&&eos()){I.negatedExtglob=true}}push({type:"paren",extglob:true,value:L,output:s});decrement("parens")};if(r.fastpaths!==false&&!/(^[*!]|[/{[()\]}"])/.test(e)){let t=false;let s=e.replace(qe,((e,r,s,a,o,u)=>{if(a==="\\"){t=true;return e}if(a==="?"){if(r){return r+a+(o?E.repeat(o.length):"")}if(u===0){return T+(o?E.repeat(o.length):"")}return E.repeat(s.length)}if(a==="."){return h.repeat(s.length)}if(a==="*"){if(r){return r+a+(o?R:"")}return R}return r?e:"\\"+e}));if(t===true){if(r.unescape===true){s=s.replace(/\\/g,"")}else{s=s.replace(/\\+/g,(e=>e.length%2===0?"\\\\":e?"\\":""))}}I.output=s;return I}while(!eos()){L=D();if(L==="\0"){continue}if(L==="\\"){let t=j();if(t==="/"&&r.bash!==true){continue}if(t==="."||t===";"){continue}if(!t){L+="\\";push({type:"text",value:L});continue}let s=/^\\+/.exec(e.slice(I.index+1));let a=0;if(s&&s[0].length>2){a=s[0].length;I.index+=a;if(a%2!==0){L+="\\"}}if(r.unescape===true){L=D()||""}else{L+=D()||""}if(I.brackets===0){push({type:"text",value:L});continue}}if(I.brackets>0&&(L!=="]"||P.value==="["||P.value==="[^")){if(r.posix!==false&&L===":"){let e=P.value.slice(1);if(e.includes("[")){P.posix=true;if(e.includes(":")){let e=P.value.lastIndexOf("[");let t=P.value.slice(0,e);let r=P.value.slice(e+2);let s=Ue[r];if(s){P.value=t+s;I.backtrack=true;D();if(!o.output&&u.indexOf(P)===1){o.output=m}continue}}}}if(L==="["&&j()!==":"||L==="-"&&j()==="]"){L="\\"+L}if(L==="]"&&(P.value==="["||P.value==="[^")){L="\\"+L}if(r.posix===true&&L==="!"&&P.value==="["){L="^"}P.value+=L;append({value:L});continue}if(I.quotes===1&&L!=='"'){L=ve.escapeRegex(L);P.value+=L;append({value:L});continue}if(L==='"'){I.quotes=I.quotes===1?0:1;if(r.keepQuotes===true){push({type:"text",value:L})}continue}if(L==="("){push({type:"paren",value:L});increment("parens");continue}if(L===")"){if(I.parens===0&&r.strictBrackets===true){throw new SyntaxError(syntaxError("opening","("))}let e=O[O.length-1];if(e&&I.parens===e.parens+1){extglobClose(O.pop());continue}push({type:"paren",value:L,output:I.parens?")":"\\)"});decrement("parens");continue}if(L==="["){if(r.nobracket===true||!e.slice(I.index+1).includes("]")){if(r.nobracket!==true&&r.strictBrackets===true){throw new SyntaxError(syntaxError("closing","]"))}L="\\"+L}else{increment("brackets")}push({type:"bracket",value:L});continue}if(L==="]"){if(r.nobracket===true||P&&P.type==="bracket"&&P.value.length===1){push({type:"text",value:L,output:"\\"+L});continue}if(I.brackets===0){if(r.strictBrackets===true){throw new SyntaxError(syntaxError("opening","["))}push({type:"text",value:L,output:"\\"+L});continue}decrement("brackets");let e=P.value.slice(1);if(P.posix!==true&&e[0]==="^"&&!e.includes("/")){L="/"+L}P.value+=L;append({value:L});if(r.literalBrackets===false||ve.hasRegexChars(e)){continue}let t=ve.escapeRegex(P.value);I.output=I.output.slice(0,-P.value.length);if(r.literalBrackets===true){I.output+=t;P.value=t;continue}P.value=`(${c}${t}|${P.value})`;I.output+=P.value;continue}if(L==="{"&&r.nobrace!==true){push({type:"brace",value:L,output:"("});increment("braces");continue}if(L==="}"){if(r.nobrace===true||I.braces===0){push({type:"text",value:L,output:"\\"+L});continue}let e=")";if(I.dots===true){let t=u.slice();let s=[];for(let e=t.length-1;e>=0;e--){u.pop();if(t[e].type==="brace"){break}if(t[e].type!=="dots"){s.unshift(t[e].value)}}e=expandRange(s,r);I.backtrack=true}push({type:"brace",value:L,output:e});decrement("braces");continue}if(L==="|"){if(O.length>0){O[O.length-1].conditions++}push({type:"text",value:L});continue}if(L===","){let e=L;if(I.braces>0&&N[N.length-1]==="braces"){e="|"}push({type:"comma",value:L,output:e});continue}if(L==="/"){if(P.type==="dot"&&I.index===1){I.start=I.index+1;I.consumed="";I.output="";u.pop();P=o;continue}push({type:"slash",value:L,output:g});continue}if(L==="."){if(I.braces>0&&P.type==="dot"){if(P.value===".")P.output=h;P.type="dots";P.output+=L;P.value+=L;I.dots=true;continue}push({type:"dot",value:L,output:h});continue}if(L==="?"){if(P&&P.type==="paren"){let e=j();let t=L;if(e==="<"&&!ve.supportsLookbehinds()){throw new Error("Node.js v10 or higher is required for regex lookbehinds")}if(P.value==="("&&!/[!=<:]/.test(e)||e==="<"&&!/[!=]/.test(j(2))){t="\\"+L}push({type:"text",value:L,output:t});continue}if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){extglobOpen("qmark",L);continue}if(r.dot!==true&&(P.type==="slash"||P.type==="bos")){push({type:"qmark",value:L,output:S});continue}push({type:"qmark",value:L,output:E});continue}if(L==="!"){if(r.noextglob!==true&&j()==="("){if(j(2)!=="?"||!/[!=<:]/.test(j(3))){extglobOpen("negate",L);continue}}if(r.nonegate!==true&&I.index===0){negate(I);continue}}if(L==="+"){if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){extglobOpen("plus",L);continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")){let e=P.extglob===true?"\\"+L:L;push({type:"plus",value:L,output:e});continue}if(I.parens>0&&r.regex!==false){push({type:"plus",value:L});continue}push({type:"plus",value:v});continue}if(L==="@"){if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){push({type:"at",value:L,output:""});continue}push({type:"text",value:L});continue}if(L!=="*"){if(L==="$"||L==="^"){L="\\"+L}let t=Ve.exec(e.slice(I.index+1));if(t){L+=t[0];I.index+=t[0].length}push({type:"text",value:L});continue}if(P&&(P.type==="globstar"||P.star===true)){P.type="star";P.star=true;P.value+=L;P.output=R;I.backtrack=true;I.consumed+=L;continue}if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){extglobOpen("star",L);continue}if(P.type==="star"){if(r.noglobstar===true){I.consumed+=L;continue}let t=P.prev;let s=t.prev;let a=t.type==="slash"||t.type==="bos";let o=s&&(s.type==="star"||s.type==="globstar");if(r.bash===true&&(!a||!eos()&&j()!=="/")){push({type:"star",value:L,output:""});continue}let u=I.braces>0&&(t.type==="comma"||t.type==="brace");let c=O.length&&(t.type==="pipe"||t.type==="paren");if(!a&&t.type!=="paren"&&!u&&!c){push({type:"star",value:L,output:""});continue}while(e.slice(I.index+1,I.index+4)==="/**"){let t=e[I.index+4];if(t&&t!=="/"){break}I.consumed+="/**";I.index+=3}if(t.type==="bos"&&eos()){P.type="globstar";P.value+=L;P.output=globstar(r);I.output=P.output;I.consumed+=L;continue}if(t.type==="slash"&&t.prev.type!=="bos"&&!o&&eos()){I.output=I.output.slice(0,-(t.output+P.output).length);t.output="(?:"+t.output;P.type="globstar";P.output=globstar(r)+"|$)";P.value+=L;I.output+=t.output+P.output;I.consumed+=L;continue}let f=j();if(t.type==="slash"&&t.prev.type!=="bos"&&f==="/"){let e=j(2)!==void 0?"|$":"";I.output=I.output.slice(0,-(t.output+P.output).length);t.output="(?:"+t.output;P.type="globstar";P.output=`${globstar(r)}${g}|${g}${e})`;P.value+=L;I.output+=t.output+P.output;I.consumed+=L+D();push({type:"slash",value:L,output:""});continue}if(t.type==="bos"&&f==="/"){P.type="globstar";P.value+=L;P.output=`(?:^|${g}|${globstar(r)}${g})`;I.output=P.output;I.consumed+=L+D();push({type:"slash",value:L,output:""});continue}I.output=I.output.slice(0,-P.output.length);P.type="globstar";P.output=globstar(r);P.value+=L;I.output+=P.output;I.consumed+=L;continue}let t={type:"star",value:L,output:R};if(r.bash===true){t.output=".*?";if(P.type==="bos"||P.type==="slash"){t.output=C+t.output}push(t);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&r.regex===true){t.output=L;push(t);continue}if(I.index===I.start||P.type==="slash"||P.type==="dot"){if(P.type==="dot"){I.output+=x;P.output+=x}else if(r.dot===true){I.output+=w;P.output+=w}else{I.output+=C;P.output+=C}if(j()!=="*"){I.output+=m;P.output+=m}}push(t)}while(I.brackets>0){if(r.strictBrackets===true)throw new SyntaxError(syntaxError("closing","]"));I.output=ve.escapeLast(I.output,"[");decrement("brackets")}while(I.parens>0){if(r.strictBrackets===true)throw new SyntaxError(syntaxError("closing",")"));I.output=ve.escapeLast(I.output,"(");decrement("parens")}while(I.braces>0){if(r.strictBrackets===true)throw new SyntaxError(syntaxError("closing","}"));I.output=ve.escapeLast(I.output,"{");decrement("braces")}if(r.strictSlashes!==true&&(P.type==="star"||P.type==="bracket")){push({type:"maybe_slash",value:"",output:`${g}?`})}if(I.backtrack===true){I.output="";for(let e of I.tokens){I.output+=e.output!=null?e.output:e.value;if(e.suffix){I.output+=e.suffix}}}return I};parse$1.fastpaths=(e,t)=>{let r=Object.assign({},t);let s=typeof r.maxLength==="number"?Math.min(We,r.maxLength):We;let a=e.length;if(a>s){throw new SyntaxError(`Input length: ${a}, exceeds maximum allowed length: ${s}`)}e=He[e]||e;let o=ve.isWindows(t);const{DOT_LITERAL:u,SLASH_LITERAL:c,ONE_CHAR:f,DOTS_SLASH:p,NO_DOT:d,NO_DOTS:h,NO_DOTS_SLASH:v,STAR:g,START_ANCHOR:m}=he.globChars(o);let _=r.capture?"":"?:";let y=r.bash===true?".*?":g;let x=r.dot?h:d;let w=r.dot?v:d;if(r.capture){y=`(${y})`}const globstar=e=>`(${_}(?:(?!${m}${e.dot?p:u}).)*?)`;const create=e=>{switch(e){case"*":return`${x}${f}${y}`;case".*":return`${u}${f}${y}`;case"*.*":return`${x}${y}${u}${f}${y}`;case"*/*":return`${x}${y}${c}${f}${w}${y}`;case"**":return x+globstar(r);case"**/*":return`(?:${x}${globstar(r)}${c})?${w}${f}${y}`;case"**/*.*":return`(?:${x}${globstar(r)}${c})?${w}${y}${u}${f}${y}`;case"**/.*":return`(?:${x}${globstar(r)}${c})?${u}${f}${y}`;default:{let r=/^(.*?)\.(\w+)$/.exec(e);if(!r)return;let s=create(r[1],t);if(!s)return;return s+u+r[2]}}};let E=create(e);if(E&&r.strictSlashes!==true){E+=`${c}?`}return E};var $e=parse$1;const picomatch=(e,t,r=false)=>{if(Array.isArray(e)){let s=e.map((e=>picomatch(e,t,r)));return e=>{for(let t of s){let r=t(e);if(r)return r}return false}}if(typeof e!=="string"||e===""){throw new TypeError("Expected pattern to be a non-empty string")}let s=t||{};let a=ve.isWindows(t);let o=picomatch.makeRe(e,t,false,true);let u=o.state;delete o.state;let isIgnored=()=>false;if(s.ignore){let e=Object.assign({},t,{ignore:null,onMatch:null,onResult:null});isIgnored=picomatch(s.ignore,e,r)}const matcher=(r,c=false)=>{let{isMatch:f,match:p,output:d}=picomatch.test(r,o,t,{glob:e,posix:a});let h={glob:e,state:u,regex:o,posix:a,input:r,output:d,match:p,isMatch:f};if(typeof s.onResult==="function"){s.onResult(h)}if(f===false){h.isMatch=false;return c?h:false}if(isIgnored(r)){if(typeof s.onIgnore==="function"){s.onIgnore(h)}h.isMatch=false;return c?h:false}if(typeof s.onMatch==="function"){s.onMatch(h)}return c?h:true};if(r){matcher.state=u}return matcher};picomatch.test=(e,t,r,{glob:s,posix:a}={})=>{if(typeof e!=="string"){throw new TypeError("Expected input to be a string")}if(e===""){return{isMatch:false,output:""}}let o=r||{};let u=o.format||(a?ve.toPosixSlashes:null);let c=e===s;let f=c&&u?u(e):e;if(c===false){f=u?u(e):e;c=f===s}if(c===false||o.capture===true){if(o.matchBase===true||o.basename===true){c=picomatch.matchBase(e,t,r,a)}else{c=t.exec(f)}}return{isMatch:!!c,match:c,output:f}};picomatch.matchBase=(e,t,r,s=ve.isWindows(r))=>{let o=t instanceof RegExp?t:picomatch.makeRe(t,r);return o.test(a.basename(e))};picomatch.isMatch=(e,t,r)=>picomatch(t,r)(e);picomatch.parse=(e,t)=>$e(e,t);picomatch.scan=(e,t)=>scan(e,t);picomatch.makeRe=(e,t,r=false,s=false)=>{if(!e||typeof e!=="string"){throw new TypeError("Expected a non-empty string")}let a=t||{};let o=a.contains?"":"^";let u=a.contains?"":"$";let c={negated:false,fastpaths:true};let f="";let p;if(e.startsWith("./")){e=e.slice(2);f=c.prefix="./"}if(a.fastpaths!==false&&(e[0]==="."||e[0]==="*")){p=$e.fastpaths(e,t)}if(p===void 0){c=picomatch.parse(e,t);c.prefix=f+(c.prefix||"");p=c.output}if(r===true){return p}let d=`${o}(?:${p})${u}`;if(c&&c.negated===true){d=`^(?!${d}).*$`}let h=picomatch.toRegex(d,t);if(s===true){h.state=c}return h};picomatch.toRegex=(e,t)=>{try{let r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(e){if(t&&t.debug===true)throw e;return/$^/}};picomatch.constants=he;var Ge=picomatch;var Ke=Ge;const isEmptyString=e=>typeof e==="string"&&(e===""||e==="./");const micromatch=(e,t,r)=>{t=[].concat(t);e=[].concat(e);let s=new Set;let a=new Set;let o=new Set;let u=0;let onResult=e=>{o.add(e.output);if(r&&r.onResult){r.onResult(e)}};for(let o=0;o!s.has(e)));if(r&&f.length===0){if(r.failglob===true){throw new Error(`No matches found for "${t.join(", ")}"`)}if(r.nonull===true||r.nullglob===true){return r.unescape?t.map((e=>e.replace(/\\/g,""))):t}}return f};micromatch.match=micromatch;micromatch.matcher=(e,t)=>Ke(e,t);micromatch.isMatch=(e,t,r)=>Ke(t,r)(e);micromatch.any=micromatch.isMatch;micromatch.not=(e,t,r={})=>{t=[].concat(t).map(String);let s=new Set;let a=[];let onResult=e=>{if(r.onResult)r.onResult(e);a.push(e.output)};let o=micromatch(e,t,Object.assign({},r,{onResult:onResult}));for(let e of a){if(!o.includes(e)){s.add(e)}}return[...s]};micromatch.contains=(e,t,r)=>{if(typeof e!=="string"){throw new TypeError(`Expected a string: "${u.inspect(e)}"`)}if(Array.isArray(t)){return t.some((t=>micromatch.contains(e,t,r)))}if(typeof t==="string"){if(isEmptyString(e)||isEmptyString(t)){return false}if(e.includes(t)||e.startsWith("./")&&e.slice(2).includes(t)){return true}}return micromatch.isMatch(e,t,Object.assign({},r,{contains:true}))};micromatch.matchKeys=(e,t,r)=>{if(!ve.isObject(e)){throw new TypeError("Expected the first argument to be an object")}let s=micromatch(Object.keys(e),t,r);let a={};for(let t of s)a[t]=e[t];return a};micromatch.some=(e,t,r)=>{let s=[].concat(e);for(let e of[].concat(t)){let t=Ke(String(e),r);if(s.some((e=>t(e)))){return true}}return false};micromatch.every=(e,t,r)=>{let s=[].concat(e);for(let e of[].concat(t)){let t=Ke(String(e),r);if(!s.every((e=>t(e)))){return false}}return true};micromatch.all=(e,t,r)=>{if(typeof e!=="string"){throw new TypeError(`Expected a string: "${u.inspect(e)}"`)}return[].concat(t).every((t=>Ke(t,r)(e)))};micromatch.capture=(e,t,r)=>{let s=ve.isWindows(r);let a=Ke.makeRe(String(e),Object.assign({},r,{capture:true}));let o=a.exec(s?ve.toPosixSlashes(t):t);if(o){return o.slice(1).map((e=>e===void 0?"":e))}};micromatch.makeRe=(...e)=>Ke.makeRe(...e);micromatch.scan=(...e)=>Ke.scan(...e);micromatch.parse=(e,t)=>{let r=[];for(let s of[].concat(e||[])){for(let e of K(String(s),t)){r.push(Ke.parse(e,t))}}return r};micromatch.braces=(e,t)=>{if(typeof e!=="string")throw new TypeError("Expected a string");if(t&&t.nobrace===true||!/\{.*\}/.test(e)){return[e]}return K(e,t)};micromatch.braceExpand=(e,t)=>{if(typeof e!=="string")throw new TypeError("Expected a string");return micromatch.braces(e,Object.assign({},t,{expand:true}))};var ze=micromatch;function ensureArray(e){if(Array.isArray(e))return e;if(e==undefined)return[];return[e]}function getMatcherString(e,t){if(t===false){return e}return s.resolve(...typeof t==="string"?[t,e]:[e])}const Qe=function createFilter(e,t,r){const a=r&&r.resolve;const getMatcher=e=>e instanceof RegExp?e:{test:ze.matcher(getMatcherString(e,a).split(s.sep).join("/"),{dot:true})};const o=ensureArray(e).map(getMatcher);const u=ensureArray(t).map(getMatcher);return function(e){if(typeof e!=="string")return false;if(/\0/.test(e))return false;e=e.split(s.sep).join("/");for(let t=0;tt.toUpperCase())).replace(/[^$_a-zA-Z0-9]/g,"_");if(/\d/.test(e[0])||Ze.has(e)){e=`_${e}`}return e||"_"};function stringify$2(e){return(JSON.stringify(e)||"undefined").replace(/[\u2028\u2029]/g,(e=>`\\u${("000"+e.charCodeAt(0).toString(16)).slice(-4)}`))}function serializeArray(e,t,r){let s="[";const a=t?"\n"+r+t:"";for(let o=0;o0?",":""}${a}${serialize(u,t,r+t)}`}return s+`${t?"\n"+r:""}]`}function serializeObject(e,t,r){let s="{";const a=t?"\n"+r+t:"";const o=Object.keys(e);for(let u=0;u0?",":""}${a}${f}:${t?" ":""}${serialize(e[c],t,r+t)}`}return s+`${t?"\n"+r:""}}`}function serialize(e,t,r){if(e===Infinity)return"Infinity";if(e===-Infinity)return"-Infinity";if(e===0&&1/e===-Infinity)return"-0";if(e instanceof Date)return"new Date("+e.getTime()+")";if(e instanceof RegExp)return e.toString();if(e!==e)return"NaN";if(Array.isArray(e))return serializeArray(e,t,r);if(e===null)return"null";if(typeof e==="object")return serializeObject(e,t,r);return stringify$2(e)}const et=function dataToEsm(e,t={}){const r=t.compact?"":"indent"in t?t.indent:"\t";const s=t.compact?"":" ";const a=t.compact?"":"\n";const o=t.preferConst?"const":"var";if(t.namedExports===false||typeof e!=="object"||Array.isArray(e)||e instanceof Date||e instanceof RegExp||e===null){const a=serialize(e,t.compact?null:r,"");const o=s||(/^[{[\-\/]/.test(a)?"":" ");return`export default${o}${a};`}let u="";const c=[];const f=Object.keys(e);for(let p=0;pt=true};const s={};const a=Object.prototype.toString;function isArray(e){return a.call(e)==="[object Array]"}function visit(e,a,o,u,c,f){if(!e)return;if(o){const s=t;t=false;o.call(r,e,a,c,f);const u=t;t=s;if(u)return}const p=e.type&&s[e.type]||(s[e.type]=Object.keys(e).filter((t=>typeof e[t]==="object")));for(let t=0;t{e.exports=function(e){[process.stdout,process.stderr].forEach((function(t){if(t._handle&&t.isTTY&&typeof t._handle.setBlocking==="function"){t._handle.setBlocking(e)}}))}},2028:(e,t,r)=>{var s=r(9491);var a=r(19);var o=r(2361);if(typeof o!=="function"){o=o.EventEmitter}var u;if(process.__signal_exit_emitter__){u=process.__signal_exit_emitter__}else{u=process.__signal_exit_emitter__=new o;u.count=0;u.emitted={}}if(!u.infinite){u.setMaxListeners(Infinity);u.infinite=true}e.exports=function(e,t){s.equal(typeof e,"function","a callback must be provided for exit handler");if(f===false){load()}var r="exit";if(t&&t.alwaysLast){r="afterexit"}var remove=function(){u.removeListener(r,e);if(u.listeners("exit").length===0&&u.listeners("afterexit").length===0){unload()}};u.on(r,e);return remove};e.exports.unload=unload;function unload(){if(!f){return}f=false;a.forEach((function(e){try{process.removeListener(e,c[e])}catch(e){}}));process.emit=d;process.reallyExit=p;u.count-=1}function emit(e,t,r){if(u.emitted[e]){return}u.emitted[e]=true;u.emit(e,t,r)}var c={};a.forEach((function(e){c[e]=function listener(){var t=process.listeners(e);if(t.length===u.count){unload();emit("exit",null,e);emit("afterexit",null,e);process.kill(process.pid,e)}}}));e.exports.signals=function(){return a};e.exports.load=load;var f=false;function load(){if(f){return}f=true;u.count+=1;a=a.filter((function(e){try{process.on(e,c[e]);return true}catch(e){return false}}));process.emit=processEmit;process.reallyExit=processReallyExit}var p=process.reallyExit;function processReallyExit(e){process.exitCode=e||0;emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);p.call(process,process.exitCode)}var d=process.emit;function processEmit(e,t){if(e==="exit"){if(t!==undefined){process.exitCode=t}var r=d.apply(this,arguments);emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);return r}else{return d.apply(this,arguments)}}},19:e=>{e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32"){e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT")}if(process.platform==="linux"){e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}},9209:(e,t,r)=>{e.exports=r(3837).deprecate},7568:(e,t,r)=>{"use strict";var s=r(3062);t.center=alignCenter;t.left=alignLeft;t.right=alignRight;function createPadding(e){var t="";var r=" ";var s=e;do{if(s%2){t+=r}s=Math.floor(s/2);r+=r}while(s);return t}function alignLeft(e,t){var r=e.trimRight();if(r.length===0&&e.length>=t)return e;var a="";var o=s(r);if(o=t)return e;var a="";var o=s(r);if(o=t)return e;var a="";var o="";var u=s(r);if(u{"use strict";e.exports=e=>{if(Number.isNaN(e)){return false}if(e>=4352&&(e<=4447||e===9001||e===9002||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141)){return true}return false}},3062:(e,t,r)=>{"use strict";const s=r(7518);const a=r(4994);e.exports=e=>{if(typeof e!=="string"||e.length===0){return 0}e=s(e);let t=0;for(let r=0;r=127&&s<=159){continue}if(s>=768&&s<=879){continue}if(s>65535){r++}t+=a(s)?2:1}return t}},918:module=>{module.exports=eval("require")("aws-sdk")},2722:module=>{module.exports=eval("require")("mock-aws-s3")},3902:module=>{module.exports=eval("require")("nock")},9491:e=>{"use strict";e.exports=require("assert")},4300:e=>{"use strict";e.exports=require("buffer")},2081:e=>{"use strict";e.exports=require("child_process")},2057:e=>{"use strict";e.exports=require("constants")},2361:e=>{"use strict";e.exports=require("events")},7147:e=>{"use strict";e.exports=require("fs")},8188:e=>{"use strict";e.exports=require("module")},3535:e=>{"use strict";e.exports=require("next/dist/compiled/glob")},2540:e=>{"use strict";e.exports=require("next/dist/compiled/micromatch")},7849:e=>{"use strict";e.exports=require("next/dist/compiled/semver")},7518:e=>{"use strict";e.exports=require("next/dist/compiled/strip-ansi")},2037:e=>{"use strict";e.exports=require("os")},1017:e=>{"use strict";e.exports=require("path")},8102:e=>{"use strict";e.exports=require("repl")},2781:e=>{"use strict";e.exports=require("stream")},7310:e=>{"use strict";e.exports=require("url")},3837:e=>{"use strict";e.exports=require("util")},7470:function(e,t){(function(e,r){true?r(t):0})(this,(function(e){"use strict";class WalkerBase{constructor(){this.should_skip=false;this.should_remove=false;this.replacement=null;this.context={skip:()=>this.should_skip=true,remove:()=>this.should_remove=true,replace:e=>this.replacement=e}}replace(e,t,r,s){if(e){if(r!==null){e[t][r]=s}else{e[t]=s}}}remove(e,t,r){if(e){if(r!==null){e[t].splice(r,1)}else{delete e[t]}}}}class SyncWalker extends WalkerBase{constructor(e,t){super();this.enter=e;this.leave=t}visit(e,t,r,s){if(e){if(this.enter){const a=this.should_skip;const o=this.should_remove;const u=this.replacement;this.should_skip=false;this.should_remove=false;this.replacement=null;this.enter.call(this.context,e,t,r,s);if(this.replacement){e=this.replacement;this.replace(t,r,s,e)}if(this.should_remove){this.remove(t,r,s)}const c=this.should_skip;const f=this.should_remove;this.should_skip=a;this.should_remove=o;this.replacement=u;if(c)return e;if(f)return null}for(const t in e){const r=e[t];if(typeof r!=="object"){continue}else if(Array.isArray(r)){for(let s=0;s{"use strict";e.exports=JSON.parse('{"0.1.14":{"node_abi":null,"v8":"1.3"},"0.1.15":{"node_abi":null,"v8":"1.3"},"0.1.16":{"node_abi":null,"v8":"1.3"},"0.1.17":{"node_abi":null,"v8":"1.3"},"0.1.18":{"node_abi":null,"v8":"1.3"},"0.1.19":{"node_abi":null,"v8":"2.0"},"0.1.20":{"node_abi":null,"v8":"2.0"},"0.1.21":{"node_abi":null,"v8":"2.0"},"0.1.22":{"node_abi":null,"v8":"2.0"},"0.1.23":{"node_abi":null,"v8":"2.0"},"0.1.24":{"node_abi":null,"v8":"2.0"},"0.1.25":{"node_abi":null,"v8":"2.0"},"0.1.26":{"node_abi":null,"v8":"2.0"},"0.1.27":{"node_abi":null,"v8":"2.1"},"0.1.28":{"node_abi":null,"v8":"2.1"},"0.1.29":{"node_abi":null,"v8":"2.1"},"0.1.30":{"node_abi":null,"v8":"2.1"},"0.1.31":{"node_abi":null,"v8":"2.1"},"0.1.32":{"node_abi":null,"v8":"2.1"},"0.1.33":{"node_abi":null,"v8":"2.1"},"0.1.90":{"node_abi":null,"v8":"2.2"},"0.1.91":{"node_abi":null,"v8":"2.2"},"0.1.92":{"node_abi":null,"v8":"2.2"},"0.1.93":{"node_abi":null,"v8":"2.2"},"0.1.94":{"node_abi":null,"v8":"2.2"},"0.1.95":{"node_abi":null,"v8":"2.2"},"0.1.96":{"node_abi":null,"v8":"2.2"},"0.1.97":{"node_abi":null,"v8":"2.2"},"0.1.98":{"node_abi":null,"v8":"2.2"},"0.1.99":{"node_abi":null,"v8":"2.2"},"0.1.100":{"node_abi":null,"v8":"2.2"},"0.1.101":{"node_abi":null,"v8":"2.3"},"0.1.102":{"node_abi":null,"v8":"2.3"},"0.1.103":{"node_abi":null,"v8":"2.3"},"0.1.104":{"node_abi":null,"v8":"2.3"},"0.2.0":{"node_abi":1,"v8":"2.3"},"0.2.1":{"node_abi":1,"v8":"2.3"},"0.2.2":{"node_abi":1,"v8":"2.3"},"0.2.3":{"node_abi":1,"v8":"2.3"},"0.2.4":{"node_abi":1,"v8":"2.3"},"0.2.5":{"node_abi":1,"v8":"2.3"},"0.2.6":{"node_abi":1,"v8":"2.3"},"0.3.0":{"node_abi":1,"v8":"2.5"},"0.3.1":{"node_abi":1,"v8":"2.5"},"0.3.2":{"node_abi":1,"v8":"3.0"},"0.3.3":{"node_abi":1,"v8":"3.0"},"0.3.4":{"node_abi":1,"v8":"3.0"},"0.3.5":{"node_abi":1,"v8":"3.0"},"0.3.6":{"node_abi":1,"v8":"3.0"},"0.3.7":{"node_abi":1,"v8":"3.0"},"0.3.8":{"node_abi":1,"v8":"3.1"},"0.4.0":{"node_abi":1,"v8":"3.1"},"0.4.1":{"node_abi":1,"v8":"3.1"},"0.4.2":{"node_abi":1,"v8":"3.1"},"0.4.3":{"node_abi":1,"v8":"3.1"},"0.4.4":{"node_abi":1,"v8":"3.1"},"0.4.5":{"node_abi":1,"v8":"3.1"},"0.4.6":{"node_abi":1,"v8":"3.1"},"0.4.7":{"node_abi":1,"v8":"3.1"},"0.4.8":{"node_abi":1,"v8":"3.1"},"0.4.9":{"node_abi":1,"v8":"3.1"},"0.4.10":{"node_abi":1,"v8":"3.1"},"0.4.11":{"node_abi":1,"v8":"3.1"},"0.4.12":{"node_abi":1,"v8":"3.1"},"0.5.0":{"node_abi":1,"v8":"3.1"},"0.5.1":{"node_abi":1,"v8":"3.4"},"0.5.2":{"node_abi":1,"v8":"3.4"},"0.5.3":{"node_abi":1,"v8":"3.4"},"0.5.4":{"node_abi":1,"v8":"3.5"},"0.5.5":{"node_abi":1,"v8":"3.5"},"0.5.6":{"node_abi":1,"v8":"3.6"},"0.5.7":{"node_abi":1,"v8":"3.6"},"0.5.8":{"node_abi":1,"v8":"3.6"},"0.5.9":{"node_abi":1,"v8":"3.6"},"0.5.10":{"node_abi":1,"v8":"3.7"},"0.6.0":{"node_abi":1,"v8":"3.6"},"0.6.1":{"node_abi":1,"v8":"3.6"},"0.6.2":{"node_abi":1,"v8":"3.6"},"0.6.3":{"node_abi":1,"v8":"3.6"},"0.6.4":{"node_abi":1,"v8":"3.6"},"0.6.5":{"node_abi":1,"v8":"3.6"},"0.6.6":{"node_abi":1,"v8":"3.6"},"0.6.7":{"node_abi":1,"v8":"3.6"},"0.6.8":{"node_abi":1,"v8":"3.6"},"0.6.9":{"node_abi":1,"v8":"3.6"},"0.6.10":{"node_abi":1,"v8":"3.6"},"0.6.11":{"node_abi":1,"v8":"3.6"},"0.6.12":{"node_abi":1,"v8":"3.6"},"0.6.13":{"node_abi":1,"v8":"3.6"},"0.6.14":{"node_abi":1,"v8":"3.6"},"0.6.15":{"node_abi":1,"v8":"3.6"},"0.6.16":{"node_abi":1,"v8":"3.6"},"0.6.17":{"node_abi":1,"v8":"3.6"},"0.6.18":{"node_abi":1,"v8":"3.6"},"0.6.19":{"node_abi":1,"v8":"3.6"},"0.6.20":{"node_abi":1,"v8":"3.6"},"0.6.21":{"node_abi":1,"v8":"3.6"},"0.7.0":{"node_abi":1,"v8":"3.8"},"0.7.1":{"node_abi":1,"v8":"3.8"},"0.7.2":{"node_abi":1,"v8":"3.8"},"0.7.3":{"node_abi":1,"v8":"3.9"},"0.7.4":{"node_abi":1,"v8":"3.9"},"0.7.5":{"node_abi":1,"v8":"3.9"},"0.7.6":{"node_abi":1,"v8":"3.9"},"0.7.7":{"node_abi":1,"v8":"3.9"},"0.7.8":{"node_abi":1,"v8":"3.9"},"0.7.9":{"node_abi":1,"v8":"3.11"},"0.7.10":{"node_abi":1,"v8":"3.9"},"0.7.11":{"node_abi":1,"v8":"3.11"},"0.7.12":{"node_abi":1,"v8":"3.11"},"0.8.0":{"node_abi":1,"v8":"3.11"},"0.8.1":{"node_abi":1,"v8":"3.11"},"0.8.2":{"node_abi":1,"v8":"3.11"},"0.8.3":{"node_abi":1,"v8":"3.11"},"0.8.4":{"node_abi":1,"v8":"3.11"},"0.8.5":{"node_abi":1,"v8":"3.11"},"0.8.6":{"node_abi":1,"v8":"3.11"},"0.8.7":{"node_abi":1,"v8":"3.11"},"0.8.8":{"node_abi":1,"v8":"3.11"},"0.8.9":{"node_abi":1,"v8":"3.11"},"0.8.10":{"node_abi":1,"v8":"3.11"},"0.8.11":{"node_abi":1,"v8":"3.11"},"0.8.12":{"node_abi":1,"v8":"3.11"},"0.8.13":{"node_abi":1,"v8":"3.11"},"0.8.14":{"node_abi":1,"v8":"3.11"},"0.8.15":{"node_abi":1,"v8":"3.11"},"0.8.16":{"node_abi":1,"v8":"3.11"},"0.8.17":{"node_abi":1,"v8":"3.11"},"0.8.18":{"node_abi":1,"v8":"3.11"},"0.8.19":{"node_abi":1,"v8":"3.11"},"0.8.20":{"node_abi":1,"v8":"3.11"},"0.8.21":{"node_abi":1,"v8":"3.11"},"0.8.22":{"node_abi":1,"v8":"3.11"},"0.8.23":{"node_abi":1,"v8":"3.11"},"0.8.24":{"node_abi":1,"v8":"3.11"},"0.8.25":{"node_abi":1,"v8":"3.11"},"0.8.26":{"node_abi":1,"v8":"3.11"},"0.8.27":{"node_abi":1,"v8":"3.11"},"0.8.28":{"node_abi":1,"v8":"3.11"},"0.9.0":{"node_abi":1,"v8":"3.11"},"0.9.1":{"node_abi":10,"v8":"3.11"},"0.9.2":{"node_abi":10,"v8":"3.11"},"0.9.3":{"node_abi":10,"v8":"3.13"},"0.9.4":{"node_abi":10,"v8":"3.13"},"0.9.5":{"node_abi":10,"v8":"3.13"},"0.9.6":{"node_abi":10,"v8":"3.15"},"0.9.7":{"node_abi":10,"v8":"3.15"},"0.9.8":{"node_abi":10,"v8":"3.15"},"0.9.9":{"node_abi":11,"v8":"3.15"},"0.9.10":{"node_abi":11,"v8":"3.15"},"0.9.11":{"node_abi":11,"v8":"3.14"},"0.9.12":{"node_abi":11,"v8":"3.14"},"0.10.0":{"node_abi":11,"v8":"3.14"},"0.10.1":{"node_abi":11,"v8":"3.14"},"0.10.2":{"node_abi":11,"v8":"3.14"},"0.10.3":{"node_abi":11,"v8":"3.14"},"0.10.4":{"node_abi":11,"v8":"3.14"},"0.10.5":{"node_abi":11,"v8":"3.14"},"0.10.6":{"node_abi":11,"v8":"3.14"},"0.10.7":{"node_abi":11,"v8":"3.14"},"0.10.8":{"node_abi":11,"v8":"3.14"},"0.10.9":{"node_abi":11,"v8":"3.14"},"0.10.10":{"node_abi":11,"v8":"3.14"},"0.10.11":{"node_abi":11,"v8":"3.14"},"0.10.12":{"node_abi":11,"v8":"3.14"},"0.10.13":{"node_abi":11,"v8":"3.14"},"0.10.14":{"node_abi":11,"v8":"3.14"},"0.10.15":{"node_abi":11,"v8":"3.14"},"0.10.16":{"node_abi":11,"v8":"3.14"},"0.10.17":{"node_abi":11,"v8":"3.14"},"0.10.18":{"node_abi":11,"v8":"3.14"},"0.10.19":{"node_abi":11,"v8":"3.14"},"0.10.20":{"node_abi":11,"v8":"3.14"},"0.10.21":{"node_abi":11,"v8":"3.14"},"0.10.22":{"node_abi":11,"v8":"3.14"},"0.10.23":{"node_abi":11,"v8":"3.14"},"0.10.24":{"node_abi":11,"v8":"3.14"},"0.10.25":{"node_abi":11,"v8":"3.14"},"0.10.26":{"node_abi":11,"v8":"3.14"},"0.10.27":{"node_abi":11,"v8":"3.14"},"0.10.28":{"node_abi":11,"v8":"3.14"},"0.10.29":{"node_abi":11,"v8":"3.14"},"0.10.30":{"node_abi":11,"v8":"3.14"},"0.10.31":{"node_abi":11,"v8":"3.14"},"0.10.32":{"node_abi":11,"v8":"3.14"},"0.10.33":{"node_abi":11,"v8":"3.14"},"0.10.34":{"node_abi":11,"v8":"3.14"},"0.10.35":{"node_abi":11,"v8":"3.14"},"0.10.36":{"node_abi":11,"v8":"3.14"},"0.10.37":{"node_abi":11,"v8":"3.14"},"0.10.38":{"node_abi":11,"v8":"3.14"},"0.10.39":{"node_abi":11,"v8":"3.14"},"0.10.40":{"node_abi":11,"v8":"3.14"},"0.10.41":{"node_abi":11,"v8":"3.14"},"0.10.42":{"node_abi":11,"v8":"3.14"},"0.10.43":{"node_abi":11,"v8":"3.14"},"0.10.44":{"node_abi":11,"v8":"3.14"},"0.10.45":{"node_abi":11,"v8":"3.14"},"0.10.46":{"node_abi":11,"v8":"3.14"},"0.10.47":{"node_abi":11,"v8":"3.14"},"0.10.48":{"node_abi":11,"v8":"3.14"},"0.11.0":{"node_abi":12,"v8":"3.17"},"0.11.1":{"node_abi":12,"v8":"3.18"},"0.11.2":{"node_abi":12,"v8":"3.19"},"0.11.3":{"node_abi":12,"v8":"3.19"},"0.11.4":{"node_abi":12,"v8":"3.20"},"0.11.5":{"node_abi":12,"v8":"3.20"},"0.11.6":{"node_abi":12,"v8":"3.20"},"0.11.7":{"node_abi":12,"v8":"3.20"},"0.11.8":{"node_abi":13,"v8":"3.21"},"0.11.9":{"node_abi":13,"v8":"3.22"},"0.11.10":{"node_abi":13,"v8":"3.22"},"0.11.11":{"node_abi":14,"v8":"3.22"},"0.11.12":{"node_abi":14,"v8":"3.22"},"0.11.13":{"node_abi":14,"v8":"3.25"},"0.11.14":{"node_abi":14,"v8":"3.26"},"0.11.15":{"node_abi":14,"v8":"3.28"},"0.11.16":{"node_abi":14,"v8":"3.28"},"0.12.0":{"node_abi":14,"v8":"3.28"},"0.12.1":{"node_abi":14,"v8":"3.28"},"0.12.2":{"node_abi":14,"v8":"3.28"},"0.12.3":{"node_abi":14,"v8":"3.28"},"0.12.4":{"node_abi":14,"v8":"3.28"},"0.12.5":{"node_abi":14,"v8":"3.28"},"0.12.6":{"node_abi":14,"v8":"3.28"},"0.12.7":{"node_abi":14,"v8":"3.28"},"0.12.8":{"node_abi":14,"v8":"3.28"},"0.12.9":{"node_abi":14,"v8":"3.28"},"0.12.10":{"node_abi":14,"v8":"3.28"},"0.12.11":{"node_abi":14,"v8":"3.28"},"0.12.12":{"node_abi":14,"v8":"3.28"},"0.12.13":{"node_abi":14,"v8":"3.28"},"0.12.14":{"node_abi":14,"v8":"3.28"},"0.12.15":{"node_abi":14,"v8":"3.28"},"0.12.16":{"node_abi":14,"v8":"3.28"},"0.12.17":{"node_abi":14,"v8":"3.28"},"0.12.18":{"node_abi":14,"v8":"3.28"},"1.0.0":{"node_abi":42,"v8":"3.31"},"1.0.1":{"node_abi":42,"v8":"3.31"},"1.0.2":{"node_abi":42,"v8":"3.31"},"1.0.3":{"node_abi":42,"v8":"4.1"},"1.0.4":{"node_abi":42,"v8":"4.1"},"1.1.0":{"node_abi":43,"v8":"4.1"},"1.2.0":{"node_abi":43,"v8":"4.1"},"1.3.0":{"node_abi":43,"v8":"4.1"},"1.4.1":{"node_abi":43,"v8":"4.1"},"1.4.2":{"node_abi":43,"v8":"4.1"},"1.4.3":{"node_abi":43,"v8":"4.1"},"1.5.0":{"node_abi":43,"v8":"4.1"},"1.5.1":{"node_abi":43,"v8":"4.1"},"1.6.0":{"node_abi":43,"v8":"4.1"},"1.6.1":{"node_abi":43,"v8":"4.1"},"1.6.2":{"node_abi":43,"v8":"4.1"},"1.6.3":{"node_abi":43,"v8":"4.1"},"1.6.4":{"node_abi":43,"v8":"4.1"},"1.7.1":{"node_abi":43,"v8":"4.1"},"1.8.1":{"node_abi":43,"v8":"4.1"},"1.8.2":{"node_abi":43,"v8":"4.1"},"1.8.3":{"node_abi":43,"v8":"4.1"},"1.8.4":{"node_abi":43,"v8":"4.1"},"2.0.0":{"node_abi":44,"v8":"4.2"},"2.0.1":{"node_abi":44,"v8":"4.2"},"2.0.2":{"node_abi":44,"v8":"4.2"},"2.1.0":{"node_abi":44,"v8":"4.2"},"2.2.0":{"node_abi":44,"v8":"4.2"},"2.2.1":{"node_abi":44,"v8":"4.2"},"2.3.0":{"node_abi":44,"v8":"4.2"},"2.3.1":{"node_abi":44,"v8":"4.2"},"2.3.2":{"node_abi":44,"v8":"4.2"},"2.3.3":{"node_abi":44,"v8":"4.2"},"2.3.4":{"node_abi":44,"v8":"4.2"},"2.4.0":{"node_abi":44,"v8":"4.2"},"2.5.0":{"node_abi":44,"v8":"4.2"},"3.0.0":{"node_abi":45,"v8":"4.4"},"3.1.0":{"node_abi":45,"v8":"4.4"},"3.2.0":{"node_abi":45,"v8":"4.4"},"3.3.0":{"node_abi":45,"v8":"4.4"},"3.3.1":{"node_abi":45,"v8":"4.4"},"4.0.0":{"node_abi":46,"v8":"4.5"},"4.1.0":{"node_abi":46,"v8":"4.5"},"4.1.1":{"node_abi":46,"v8":"4.5"},"4.1.2":{"node_abi":46,"v8":"4.5"},"4.2.0":{"node_abi":46,"v8":"4.5"},"4.2.1":{"node_abi":46,"v8":"4.5"},"4.2.2":{"node_abi":46,"v8":"4.5"},"4.2.3":{"node_abi":46,"v8":"4.5"},"4.2.4":{"node_abi":46,"v8":"4.5"},"4.2.5":{"node_abi":46,"v8":"4.5"},"4.2.6":{"node_abi":46,"v8":"4.5"},"4.3.0":{"node_abi":46,"v8":"4.5"},"4.3.1":{"node_abi":46,"v8":"4.5"},"4.3.2":{"node_abi":46,"v8":"4.5"},"4.4.0":{"node_abi":46,"v8":"4.5"},"4.4.1":{"node_abi":46,"v8":"4.5"},"4.4.2":{"node_abi":46,"v8":"4.5"},"4.4.3":{"node_abi":46,"v8":"4.5"},"4.4.4":{"node_abi":46,"v8":"4.5"},"4.4.5":{"node_abi":46,"v8":"4.5"},"4.4.6":{"node_abi":46,"v8":"4.5"},"4.4.7":{"node_abi":46,"v8":"4.5"},"4.5.0":{"node_abi":46,"v8":"4.5"},"4.6.0":{"node_abi":46,"v8":"4.5"},"4.6.1":{"node_abi":46,"v8":"4.5"},"4.6.2":{"node_abi":46,"v8":"4.5"},"4.7.0":{"node_abi":46,"v8":"4.5"},"4.7.1":{"node_abi":46,"v8":"4.5"},"4.7.2":{"node_abi":46,"v8":"4.5"},"4.7.3":{"node_abi":46,"v8":"4.5"},"4.8.0":{"node_abi":46,"v8":"4.5"},"4.8.1":{"node_abi":46,"v8":"4.5"},"4.8.2":{"node_abi":46,"v8":"4.5"},"4.8.3":{"node_abi":46,"v8":"4.5"},"4.8.4":{"node_abi":46,"v8":"4.5"},"4.8.5":{"node_abi":46,"v8":"4.5"},"4.8.6":{"node_abi":46,"v8":"4.5"},"4.8.7":{"node_abi":46,"v8":"4.5"},"4.9.0":{"node_abi":46,"v8":"4.5"},"4.9.1":{"node_abi":46,"v8":"4.5"},"5.0.0":{"node_abi":47,"v8":"4.6"},"5.1.0":{"node_abi":47,"v8":"4.6"},"5.1.1":{"node_abi":47,"v8":"4.6"},"5.2.0":{"node_abi":47,"v8":"4.6"},"5.3.0":{"node_abi":47,"v8":"4.6"},"5.4.0":{"node_abi":47,"v8":"4.6"},"5.4.1":{"node_abi":47,"v8":"4.6"},"5.5.0":{"node_abi":47,"v8":"4.6"},"5.6.0":{"node_abi":47,"v8":"4.6"},"5.7.0":{"node_abi":47,"v8":"4.6"},"5.7.1":{"node_abi":47,"v8":"4.6"},"5.8.0":{"node_abi":47,"v8":"4.6"},"5.9.0":{"node_abi":47,"v8":"4.6"},"5.9.1":{"node_abi":47,"v8":"4.6"},"5.10.0":{"node_abi":47,"v8":"4.6"},"5.10.1":{"node_abi":47,"v8":"4.6"},"5.11.0":{"node_abi":47,"v8":"4.6"},"5.11.1":{"node_abi":47,"v8":"4.6"},"5.12.0":{"node_abi":47,"v8":"4.6"},"6.0.0":{"node_abi":48,"v8":"5.0"},"6.1.0":{"node_abi":48,"v8":"5.0"},"6.2.0":{"node_abi":48,"v8":"5.0"},"6.2.1":{"node_abi":48,"v8":"5.0"},"6.2.2":{"node_abi":48,"v8":"5.0"},"6.3.0":{"node_abi":48,"v8":"5.0"},"6.3.1":{"node_abi":48,"v8":"5.0"},"6.4.0":{"node_abi":48,"v8":"5.0"},"6.5.0":{"node_abi":48,"v8":"5.1"},"6.6.0":{"node_abi":48,"v8":"5.1"},"6.7.0":{"node_abi":48,"v8":"5.1"},"6.8.0":{"node_abi":48,"v8":"5.1"},"6.8.1":{"node_abi":48,"v8":"5.1"},"6.9.0":{"node_abi":48,"v8":"5.1"},"6.9.1":{"node_abi":48,"v8":"5.1"},"6.9.2":{"node_abi":48,"v8":"5.1"},"6.9.3":{"node_abi":48,"v8":"5.1"},"6.9.4":{"node_abi":48,"v8":"5.1"},"6.9.5":{"node_abi":48,"v8":"5.1"},"6.10.0":{"node_abi":48,"v8":"5.1"},"6.10.1":{"node_abi":48,"v8":"5.1"},"6.10.2":{"node_abi":48,"v8":"5.1"},"6.10.3":{"node_abi":48,"v8":"5.1"},"6.11.0":{"node_abi":48,"v8":"5.1"},"6.11.1":{"node_abi":48,"v8":"5.1"},"6.11.2":{"node_abi":48,"v8":"5.1"},"6.11.3":{"node_abi":48,"v8":"5.1"},"6.11.4":{"node_abi":48,"v8":"5.1"},"6.11.5":{"node_abi":48,"v8":"5.1"},"6.12.0":{"node_abi":48,"v8":"5.1"},"6.12.1":{"node_abi":48,"v8":"5.1"},"6.12.2":{"node_abi":48,"v8":"5.1"},"6.12.3":{"node_abi":48,"v8":"5.1"},"6.13.0":{"node_abi":48,"v8":"5.1"},"6.13.1":{"node_abi":48,"v8":"5.1"},"6.14.0":{"node_abi":48,"v8":"5.1"},"6.14.1":{"node_abi":48,"v8":"5.1"},"6.14.2":{"node_abi":48,"v8":"5.1"},"6.14.3":{"node_abi":48,"v8":"5.1"},"6.14.4":{"node_abi":48,"v8":"5.1"},"6.15.0":{"node_abi":48,"v8":"5.1"},"6.15.1":{"node_abi":48,"v8":"5.1"},"6.16.0":{"node_abi":48,"v8":"5.1"},"6.17.0":{"node_abi":48,"v8":"5.1"},"6.17.1":{"node_abi":48,"v8":"5.1"},"7.0.0":{"node_abi":51,"v8":"5.4"},"7.1.0":{"node_abi":51,"v8":"5.4"},"7.2.0":{"node_abi":51,"v8":"5.4"},"7.2.1":{"node_abi":51,"v8":"5.4"},"7.3.0":{"node_abi":51,"v8":"5.4"},"7.4.0":{"node_abi":51,"v8":"5.4"},"7.5.0":{"node_abi":51,"v8":"5.4"},"7.6.0":{"node_abi":51,"v8":"5.5"},"7.7.0":{"node_abi":51,"v8":"5.5"},"7.7.1":{"node_abi":51,"v8":"5.5"},"7.7.2":{"node_abi":51,"v8":"5.5"},"7.7.3":{"node_abi":51,"v8":"5.5"},"7.7.4":{"node_abi":51,"v8":"5.5"},"7.8.0":{"node_abi":51,"v8":"5.5"},"7.9.0":{"node_abi":51,"v8":"5.5"},"7.10.0":{"node_abi":51,"v8":"5.5"},"7.10.1":{"node_abi":51,"v8":"5.5"},"8.0.0":{"node_abi":57,"v8":"5.8"},"8.1.0":{"node_abi":57,"v8":"5.8"},"8.1.1":{"node_abi":57,"v8":"5.8"},"8.1.2":{"node_abi":57,"v8":"5.8"},"8.1.3":{"node_abi":57,"v8":"5.8"},"8.1.4":{"node_abi":57,"v8":"5.8"},"8.2.0":{"node_abi":57,"v8":"5.8"},"8.2.1":{"node_abi":57,"v8":"5.8"},"8.3.0":{"node_abi":57,"v8":"6.0"},"8.4.0":{"node_abi":57,"v8":"6.0"},"8.5.0":{"node_abi":57,"v8":"6.0"},"8.6.0":{"node_abi":57,"v8":"6.0"},"8.7.0":{"node_abi":57,"v8":"6.1"},"8.8.0":{"node_abi":57,"v8":"6.1"},"8.8.1":{"node_abi":57,"v8":"6.1"},"8.9.0":{"node_abi":57,"v8":"6.1"},"8.9.1":{"node_abi":57,"v8":"6.1"},"8.9.2":{"node_abi":57,"v8":"6.1"},"8.9.3":{"node_abi":57,"v8":"6.1"},"8.9.4":{"node_abi":57,"v8":"6.1"},"8.10.0":{"node_abi":57,"v8":"6.2"},"8.11.0":{"node_abi":57,"v8":"6.2"},"8.11.1":{"node_abi":57,"v8":"6.2"},"8.11.2":{"node_abi":57,"v8":"6.2"},"8.11.3":{"node_abi":57,"v8":"6.2"},"8.11.4":{"node_abi":57,"v8":"6.2"},"8.12.0":{"node_abi":57,"v8":"6.2"},"8.13.0":{"node_abi":57,"v8":"6.2"},"8.14.0":{"node_abi":57,"v8":"6.2"},"8.14.1":{"node_abi":57,"v8":"6.2"},"8.15.0":{"node_abi":57,"v8":"6.2"},"8.15.1":{"node_abi":57,"v8":"6.2"},"8.16.0":{"node_abi":57,"v8":"6.2"},"8.16.1":{"node_abi":57,"v8":"6.2"},"8.16.2":{"node_abi":57,"v8":"6.2"},"8.17.0":{"node_abi":57,"v8":"6.2"},"9.0.0":{"node_abi":59,"v8":"6.2"},"9.1.0":{"node_abi":59,"v8":"6.2"},"9.2.0":{"node_abi":59,"v8":"6.2"},"9.2.1":{"node_abi":59,"v8":"6.2"},"9.3.0":{"node_abi":59,"v8":"6.2"},"9.4.0":{"node_abi":59,"v8":"6.2"},"9.5.0":{"node_abi":59,"v8":"6.2"},"9.6.0":{"node_abi":59,"v8":"6.2"},"9.6.1":{"node_abi":59,"v8":"6.2"},"9.7.0":{"node_abi":59,"v8":"6.2"},"9.7.1":{"node_abi":59,"v8":"6.2"},"9.8.0":{"node_abi":59,"v8":"6.2"},"9.9.0":{"node_abi":59,"v8":"6.2"},"9.10.0":{"node_abi":59,"v8":"6.2"},"9.10.1":{"node_abi":59,"v8":"6.2"},"9.11.0":{"node_abi":59,"v8":"6.2"},"9.11.1":{"node_abi":59,"v8":"6.2"},"9.11.2":{"node_abi":59,"v8":"6.2"},"10.0.0":{"node_abi":64,"v8":"6.6"},"10.1.0":{"node_abi":64,"v8":"6.6"},"10.2.0":{"node_abi":64,"v8":"6.6"},"10.2.1":{"node_abi":64,"v8":"6.6"},"10.3.0":{"node_abi":64,"v8":"6.6"},"10.4.0":{"node_abi":64,"v8":"6.7"},"10.4.1":{"node_abi":64,"v8":"6.7"},"10.5.0":{"node_abi":64,"v8":"6.7"},"10.6.0":{"node_abi":64,"v8":"6.7"},"10.7.0":{"node_abi":64,"v8":"6.7"},"10.8.0":{"node_abi":64,"v8":"6.7"},"10.9.0":{"node_abi":64,"v8":"6.8"},"10.10.0":{"node_abi":64,"v8":"6.8"},"10.11.0":{"node_abi":64,"v8":"6.8"},"10.12.0":{"node_abi":64,"v8":"6.8"},"10.13.0":{"node_abi":64,"v8":"6.8"},"10.14.0":{"node_abi":64,"v8":"6.8"},"10.14.1":{"node_abi":64,"v8":"6.8"},"10.14.2":{"node_abi":64,"v8":"6.8"},"10.15.0":{"node_abi":64,"v8":"6.8"},"10.15.1":{"node_abi":64,"v8":"6.8"},"10.15.2":{"node_abi":64,"v8":"6.8"},"10.15.3":{"node_abi":64,"v8":"6.8"},"10.16.0":{"node_abi":64,"v8":"6.8"},"10.16.1":{"node_abi":64,"v8":"6.8"},"10.16.2":{"node_abi":64,"v8":"6.8"},"10.16.3":{"node_abi":64,"v8":"6.8"},"10.17.0":{"node_abi":64,"v8":"6.8"},"10.18.0":{"node_abi":64,"v8":"6.8"},"10.18.1":{"node_abi":64,"v8":"6.8"},"10.19.0":{"node_abi":64,"v8":"6.8"},"10.20.0":{"node_abi":64,"v8":"6.8"},"10.20.1":{"node_abi":64,"v8":"6.8"},"10.21.0":{"node_abi":64,"v8":"6.8"},"10.22.0":{"node_abi":64,"v8":"6.8"},"10.22.1":{"node_abi":64,"v8":"6.8"},"10.23.0":{"node_abi":64,"v8":"6.8"},"10.23.1":{"node_abi":64,"v8":"6.8"},"10.23.2":{"node_abi":64,"v8":"6.8"},"10.23.3":{"node_abi":64,"v8":"6.8"},"10.24.0":{"node_abi":64,"v8":"6.8"},"10.24.1":{"node_abi":64,"v8":"6.8"},"11.0.0":{"node_abi":67,"v8":"7.0"},"11.1.0":{"node_abi":67,"v8":"7.0"},"11.2.0":{"node_abi":67,"v8":"7.0"},"11.3.0":{"node_abi":67,"v8":"7.0"},"11.4.0":{"node_abi":67,"v8":"7.0"},"11.5.0":{"node_abi":67,"v8":"7.0"},"11.6.0":{"node_abi":67,"v8":"7.0"},"11.7.0":{"node_abi":67,"v8":"7.0"},"11.8.0":{"node_abi":67,"v8":"7.0"},"11.9.0":{"node_abi":67,"v8":"7.0"},"11.10.0":{"node_abi":67,"v8":"7.0"},"11.10.1":{"node_abi":67,"v8":"7.0"},"11.11.0":{"node_abi":67,"v8":"7.0"},"11.12.0":{"node_abi":67,"v8":"7.0"},"11.13.0":{"node_abi":67,"v8":"7.0"},"11.14.0":{"node_abi":67,"v8":"7.0"},"11.15.0":{"node_abi":67,"v8":"7.0"},"12.0.0":{"node_abi":72,"v8":"7.4"},"12.1.0":{"node_abi":72,"v8":"7.4"},"12.2.0":{"node_abi":72,"v8":"7.4"},"12.3.0":{"node_abi":72,"v8":"7.4"},"12.3.1":{"node_abi":72,"v8":"7.4"},"12.4.0":{"node_abi":72,"v8":"7.4"},"12.5.0":{"node_abi":72,"v8":"7.5"},"12.6.0":{"node_abi":72,"v8":"7.5"},"12.7.0":{"node_abi":72,"v8":"7.5"},"12.8.0":{"node_abi":72,"v8":"7.5"},"12.8.1":{"node_abi":72,"v8":"7.5"},"12.9.0":{"node_abi":72,"v8":"7.6"},"12.9.1":{"node_abi":72,"v8":"7.6"},"12.10.0":{"node_abi":72,"v8":"7.6"},"12.11.0":{"node_abi":72,"v8":"7.7"},"12.11.1":{"node_abi":72,"v8":"7.7"},"12.12.0":{"node_abi":72,"v8":"7.7"},"12.13.0":{"node_abi":72,"v8":"7.7"},"12.13.1":{"node_abi":72,"v8":"7.7"},"12.14.0":{"node_abi":72,"v8":"7.7"},"12.14.1":{"node_abi":72,"v8":"7.7"},"12.15.0":{"node_abi":72,"v8":"7.7"},"12.16.0":{"node_abi":72,"v8":"7.8"},"12.16.1":{"node_abi":72,"v8":"7.8"},"12.16.2":{"node_abi":72,"v8":"7.8"},"12.16.3":{"node_abi":72,"v8":"7.8"},"12.17.0":{"node_abi":72,"v8":"7.8"},"12.18.0":{"node_abi":72,"v8":"7.8"},"12.18.1":{"node_abi":72,"v8":"7.8"},"12.18.2":{"node_abi":72,"v8":"7.8"},"12.18.3":{"node_abi":72,"v8":"7.8"},"12.18.4":{"node_abi":72,"v8":"7.8"},"12.19.0":{"node_abi":72,"v8":"7.8"},"12.19.1":{"node_abi":72,"v8":"7.8"},"12.20.0":{"node_abi":72,"v8":"7.8"},"12.20.1":{"node_abi":72,"v8":"7.8"},"12.20.2":{"node_abi":72,"v8":"7.8"},"12.21.0":{"node_abi":72,"v8":"7.8"},"12.22.0":{"node_abi":72,"v8":"7.8"},"12.22.1":{"node_abi":72,"v8":"7.8"},"13.0.0":{"node_abi":79,"v8":"7.8"},"13.0.1":{"node_abi":79,"v8":"7.8"},"13.1.0":{"node_abi":79,"v8":"7.8"},"13.2.0":{"node_abi":79,"v8":"7.9"},"13.3.0":{"node_abi":79,"v8":"7.9"},"13.4.0":{"node_abi":79,"v8":"7.9"},"13.5.0":{"node_abi":79,"v8":"7.9"},"13.6.0":{"node_abi":79,"v8":"7.9"},"13.7.0":{"node_abi":79,"v8":"7.9"},"13.8.0":{"node_abi":79,"v8":"7.9"},"13.9.0":{"node_abi":79,"v8":"7.9"},"13.10.0":{"node_abi":79,"v8":"7.9"},"13.10.1":{"node_abi":79,"v8":"7.9"},"13.11.0":{"node_abi":79,"v8":"7.9"},"13.12.0":{"node_abi":79,"v8":"7.9"},"13.13.0":{"node_abi":79,"v8":"7.9"},"13.14.0":{"node_abi":79,"v8":"7.9"},"14.0.0":{"node_abi":83,"v8":"8.1"},"14.1.0":{"node_abi":83,"v8":"8.1"},"14.2.0":{"node_abi":83,"v8":"8.1"},"14.3.0":{"node_abi":83,"v8":"8.1"},"14.4.0":{"node_abi":83,"v8":"8.1"},"14.5.0":{"node_abi":83,"v8":"8.3"},"14.6.0":{"node_abi":83,"v8":"8.4"},"14.7.0":{"node_abi":83,"v8":"8.4"},"14.8.0":{"node_abi":83,"v8":"8.4"},"14.9.0":{"node_abi":83,"v8":"8.4"},"14.10.0":{"node_abi":83,"v8":"8.4"},"14.10.1":{"node_abi":83,"v8":"8.4"},"14.11.0":{"node_abi":83,"v8":"8.4"},"14.12.0":{"node_abi":83,"v8":"8.4"},"14.13.0":{"node_abi":83,"v8":"8.4"},"14.13.1":{"node_abi":83,"v8":"8.4"},"14.14.0":{"node_abi":83,"v8":"8.4"},"14.15.0":{"node_abi":83,"v8":"8.4"},"14.15.1":{"node_abi":83,"v8":"8.4"},"14.15.2":{"node_abi":83,"v8":"8.4"},"14.15.3":{"node_abi":83,"v8":"8.4"},"14.15.4":{"node_abi":83,"v8":"8.4"},"14.15.5":{"node_abi":83,"v8":"8.4"},"14.16.0":{"node_abi":83,"v8":"8.4"},"14.16.1":{"node_abi":83,"v8":"8.4"},"15.0.0":{"node_abi":88,"v8":"8.6"},"15.0.1":{"node_abi":88,"v8":"8.6"},"15.1.0":{"node_abi":88,"v8":"8.6"},"15.2.0":{"node_abi":88,"v8":"8.6"},"15.2.1":{"node_abi":88,"v8":"8.6"},"15.3.0":{"node_abi":88,"v8":"8.6"},"15.4.0":{"node_abi":88,"v8":"8.6"},"15.5.0":{"node_abi":88,"v8":"8.6"},"15.5.1":{"node_abi":88,"v8":"8.6"},"15.6.0":{"node_abi":88,"v8":"8.6"},"15.7.0":{"node_abi":88,"v8":"8.6"},"15.8.0":{"node_abi":88,"v8":"8.6"},"15.9.0":{"node_abi":88,"v8":"8.6"},"15.10.0":{"node_abi":88,"v8":"8.6"},"15.11.0":{"node_abi":88,"v8":"8.6"},"15.12.0":{"node_abi":88,"v8":"8.6"},"15.13.0":{"node_abi":88,"v8":"8.6"},"15.14.0":{"node_abi":88,"v8":"8.6"},"16.0.0":{"node_abi":93,"v8":"9.0"}}')},9286:e=>{"use strict";e.exports=JSON.parse('{"name":"@mapbox/node-pre-gyp","description":"Node.js native addon binary install tool","version":"1.0.5","keywords":["native","addon","module","c","c++","bindings","binary"],"license":"BSD-3-Clause","author":"Dane Springmeyer ","repository":{"type":"git","url":"git://github.com/mapbox/node-pre-gyp.git"},"bin":"./bin/node-pre-gyp","main":"./lib/node-pre-gyp.js","dependencies":{"detect-libc":"^1.0.3","https-proxy-agent":"^5.0.0","make-dir":"^3.1.0","node-fetch":"^2.6.1","nopt":"^5.0.0","npmlog":"^4.1.2","rimraf":"^3.0.2","semver":"^7.3.4","tar":"^6.1.0"},"devDependencies":{"@mapbox/cloudfriend":"^4.6.0","@mapbox/eslint-config-mapbox":"^3.0.0","action-walk":"^2.2.0","aws-sdk":"^2.840.0","codecov":"^3.8.1","eslint":"^7.18.0","eslint-plugin-node":"^11.1.0","mock-aws-s3":"^4.0.1","nock":"^12.0.3","node-addon-api":"^3.1.0","nyc":"^15.1.0","tape":"^5.2.2","tar-fs":"^2.1.1"},"nyc":{"all":true,"skip-full":false,"exclude":["test/**"]},"scripts":{"coverage":"nyc --all --include index.js --include lib/ npm test","upload-coverage":"nyc report --reporter json && codecov --clear --flags=unit --file=./coverage/coverage-final.json","lint":"eslint bin/node-pre-gyp lib/*js lib/util/*js test/*js scripts/*js","fix":"npm run lint -- --fix","update-crosswalk":"node scripts/abi_crosswalk.js","test":"tape test/*test.js"}}')},7316:e=>{"use strict";e.exports=JSON.parse('{"0.1.14":{"node_abi":null,"v8":"1.3"},"0.1.15":{"node_abi":null,"v8":"1.3"},"0.1.16":{"node_abi":null,"v8":"1.3"},"0.1.17":{"node_abi":null,"v8":"1.3"},"0.1.18":{"node_abi":null,"v8":"1.3"},"0.1.19":{"node_abi":null,"v8":"2.0"},"0.1.20":{"node_abi":null,"v8":"2.0"},"0.1.21":{"node_abi":null,"v8":"2.0"},"0.1.22":{"node_abi":null,"v8":"2.0"},"0.1.23":{"node_abi":null,"v8":"2.0"},"0.1.24":{"node_abi":null,"v8":"2.0"},"0.1.25":{"node_abi":null,"v8":"2.0"},"0.1.26":{"node_abi":null,"v8":"2.0"},"0.1.27":{"node_abi":null,"v8":"2.1"},"0.1.28":{"node_abi":null,"v8":"2.1"},"0.1.29":{"node_abi":null,"v8":"2.1"},"0.1.30":{"node_abi":null,"v8":"2.1"},"0.1.31":{"node_abi":null,"v8":"2.1"},"0.1.32":{"node_abi":null,"v8":"2.1"},"0.1.33":{"node_abi":null,"v8":"2.1"},"0.1.90":{"node_abi":null,"v8":"2.2"},"0.1.91":{"node_abi":null,"v8":"2.2"},"0.1.92":{"node_abi":null,"v8":"2.2"},"0.1.93":{"node_abi":null,"v8":"2.2"},"0.1.94":{"node_abi":null,"v8":"2.2"},"0.1.95":{"node_abi":null,"v8":"2.2"},"0.1.96":{"node_abi":null,"v8":"2.2"},"0.1.97":{"node_abi":null,"v8":"2.2"},"0.1.98":{"node_abi":null,"v8":"2.2"},"0.1.99":{"node_abi":null,"v8":"2.2"},"0.1.100":{"node_abi":null,"v8":"2.2"},"0.1.101":{"node_abi":null,"v8":"2.3"},"0.1.102":{"node_abi":null,"v8":"2.3"},"0.1.103":{"node_abi":null,"v8":"2.3"},"0.1.104":{"node_abi":null,"v8":"2.3"},"0.2.0":{"node_abi":1,"v8":"2.3"},"0.2.1":{"node_abi":1,"v8":"2.3"},"0.2.2":{"node_abi":1,"v8":"2.3"},"0.2.3":{"node_abi":1,"v8":"2.3"},"0.2.4":{"node_abi":1,"v8":"2.3"},"0.2.5":{"node_abi":1,"v8":"2.3"},"0.2.6":{"node_abi":1,"v8":"2.3"},"0.3.0":{"node_abi":1,"v8":"2.5"},"0.3.1":{"node_abi":1,"v8":"2.5"},"0.3.2":{"node_abi":1,"v8":"3.0"},"0.3.3":{"node_abi":1,"v8":"3.0"},"0.3.4":{"node_abi":1,"v8":"3.0"},"0.3.5":{"node_abi":1,"v8":"3.0"},"0.3.6":{"node_abi":1,"v8":"3.0"},"0.3.7":{"node_abi":1,"v8":"3.0"},"0.3.8":{"node_abi":1,"v8":"3.1"},"0.4.0":{"node_abi":1,"v8":"3.1"},"0.4.1":{"node_abi":1,"v8":"3.1"},"0.4.2":{"node_abi":1,"v8":"3.1"},"0.4.3":{"node_abi":1,"v8":"3.1"},"0.4.4":{"node_abi":1,"v8":"3.1"},"0.4.5":{"node_abi":1,"v8":"3.1"},"0.4.6":{"node_abi":1,"v8":"3.1"},"0.4.7":{"node_abi":1,"v8":"3.1"},"0.4.8":{"node_abi":1,"v8":"3.1"},"0.4.9":{"node_abi":1,"v8":"3.1"},"0.4.10":{"node_abi":1,"v8":"3.1"},"0.4.11":{"node_abi":1,"v8":"3.1"},"0.4.12":{"node_abi":1,"v8":"3.1"},"0.5.0":{"node_abi":1,"v8":"3.1"},"0.5.1":{"node_abi":1,"v8":"3.4"},"0.5.2":{"node_abi":1,"v8":"3.4"},"0.5.3":{"node_abi":1,"v8":"3.4"},"0.5.4":{"node_abi":1,"v8":"3.5"},"0.5.5":{"node_abi":1,"v8":"3.5"},"0.5.6":{"node_abi":1,"v8":"3.6"},"0.5.7":{"node_abi":1,"v8":"3.6"},"0.5.8":{"node_abi":1,"v8":"3.6"},"0.5.9":{"node_abi":1,"v8":"3.6"},"0.5.10":{"node_abi":1,"v8":"3.7"},"0.6.0":{"node_abi":1,"v8":"3.6"},"0.6.1":{"node_abi":1,"v8":"3.6"},"0.6.2":{"node_abi":1,"v8":"3.6"},"0.6.3":{"node_abi":1,"v8":"3.6"},"0.6.4":{"node_abi":1,"v8":"3.6"},"0.6.5":{"node_abi":1,"v8":"3.6"},"0.6.6":{"node_abi":1,"v8":"3.6"},"0.6.7":{"node_abi":1,"v8":"3.6"},"0.6.8":{"node_abi":1,"v8":"3.6"},"0.6.9":{"node_abi":1,"v8":"3.6"},"0.6.10":{"node_abi":1,"v8":"3.6"},"0.6.11":{"node_abi":1,"v8":"3.6"},"0.6.12":{"node_abi":1,"v8":"3.6"},"0.6.13":{"node_abi":1,"v8":"3.6"},"0.6.14":{"node_abi":1,"v8":"3.6"},"0.6.15":{"node_abi":1,"v8":"3.6"},"0.6.16":{"node_abi":1,"v8":"3.6"},"0.6.17":{"node_abi":1,"v8":"3.6"},"0.6.18":{"node_abi":1,"v8":"3.6"},"0.6.19":{"node_abi":1,"v8":"3.6"},"0.6.20":{"node_abi":1,"v8":"3.6"},"0.6.21":{"node_abi":1,"v8":"3.6"},"0.7.0":{"node_abi":1,"v8":"3.8"},"0.7.1":{"node_abi":1,"v8":"3.8"},"0.7.2":{"node_abi":1,"v8":"3.8"},"0.7.3":{"node_abi":1,"v8":"3.9"},"0.7.4":{"node_abi":1,"v8":"3.9"},"0.7.5":{"node_abi":1,"v8":"3.9"},"0.7.6":{"node_abi":1,"v8":"3.9"},"0.7.7":{"node_abi":1,"v8":"3.9"},"0.7.8":{"node_abi":1,"v8":"3.9"},"0.7.9":{"node_abi":1,"v8":"3.11"},"0.7.10":{"node_abi":1,"v8":"3.9"},"0.7.11":{"node_abi":1,"v8":"3.11"},"0.7.12":{"node_abi":1,"v8":"3.11"},"0.8.0":{"node_abi":1,"v8":"3.11"},"0.8.1":{"node_abi":1,"v8":"3.11"},"0.8.2":{"node_abi":1,"v8":"3.11"},"0.8.3":{"node_abi":1,"v8":"3.11"},"0.8.4":{"node_abi":1,"v8":"3.11"},"0.8.5":{"node_abi":1,"v8":"3.11"},"0.8.6":{"node_abi":1,"v8":"3.11"},"0.8.7":{"node_abi":1,"v8":"3.11"},"0.8.8":{"node_abi":1,"v8":"3.11"},"0.8.9":{"node_abi":1,"v8":"3.11"},"0.8.10":{"node_abi":1,"v8":"3.11"},"0.8.11":{"node_abi":1,"v8":"3.11"},"0.8.12":{"node_abi":1,"v8":"3.11"},"0.8.13":{"node_abi":1,"v8":"3.11"},"0.8.14":{"node_abi":1,"v8":"3.11"},"0.8.15":{"node_abi":1,"v8":"3.11"},"0.8.16":{"node_abi":1,"v8":"3.11"},"0.8.17":{"node_abi":1,"v8":"3.11"},"0.8.18":{"node_abi":1,"v8":"3.11"},"0.8.19":{"node_abi":1,"v8":"3.11"},"0.8.20":{"node_abi":1,"v8":"3.11"},"0.8.21":{"node_abi":1,"v8":"3.11"},"0.8.22":{"node_abi":1,"v8":"3.11"},"0.8.23":{"node_abi":1,"v8":"3.11"},"0.8.24":{"node_abi":1,"v8":"3.11"},"0.8.25":{"node_abi":1,"v8":"3.11"},"0.8.26":{"node_abi":1,"v8":"3.11"},"0.8.27":{"node_abi":1,"v8":"3.11"},"0.8.28":{"node_abi":1,"v8":"3.11"},"0.9.0":{"node_abi":1,"v8":"3.11"},"0.9.1":{"node_abi":10,"v8":"3.11"},"0.9.2":{"node_abi":10,"v8":"3.11"},"0.9.3":{"node_abi":10,"v8":"3.13"},"0.9.4":{"node_abi":10,"v8":"3.13"},"0.9.5":{"node_abi":10,"v8":"3.13"},"0.9.6":{"node_abi":10,"v8":"3.15"},"0.9.7":{"node_abi":10,"v8":"3.15"},"0.9.8":{"node_abi":10,"v8":"3.15"},"0.9.9":{"node_abi":11,"v8":"3.15"},"0.9.10":{"node_abi":11,"v8":"3.15"},"0.9.11":{"node_abi":11,"v8":"3.14"},"0.9.12":{"node_abi":11,"v8":"3.14"},"0.10.0":{"node_abi":11,"v8":"3.14"},"0.10.1":{"node_abi":11,"v8":"3.14"},"0.10.2":{"node_abi":11,"v8":"3.14"},"0.10.3":{"node_abi":11,"v8":"3.14"},"0.10.4":{"node_abi":11,"v8":"3.14"},"0.10.5":{"node_abi":11,"v8":"3.14"},"0.10.6":{"node_abi":11,"v8":"3.14"},"0.10.7":{"node_abi":11,"v8":"3.14"},"0.10.8":{"node_abi":11,"v8":"3.14"},"0.10.9":{"node_abi":11,"v8":"3.14"},"0.10.10":{"node_abi":11,"v8":"3.14"},"0.10.11":{"node_abi":11,"v8":"3.14"},"0.10.12":{"node_abi":11,"v8":"3.14"},"0.10.13":{"node_abi":11,"v8":"3.14"},"0.10.14":{"node_abi":11,"v8":"3.14"},"0.10.15":{"node_abi":11,"v8":"3.14"},"0.10.16":{"node_abi":11,"v8":"3.14"},"0.10.17":{"node_abi":11,"v8":"3.14"},"0.10.18":{"node_abi":11,"v8":"3.14"},"0.10.19":{"node_abi":11,"v8":"3.14"},"0.10.20":{"node_abi":11,"v8":"3.14"},"0.10.21":{"node_abi":11,"v8":"3.14"},"0.10.22":{"node_abi":11,"v8":"3.14"},"0.10.23":{"node_abi":11,"v8":"3.14"},"0.10.24":{"node_abi":11,"v8":"3.14"},"0.10.25":{"node_abi":11,"v8":"3.14"},"0.10.26":{"node_abi":11,"v8":"3.14"},"0.10.27":{"node_abi":11,"v8":"3.14"},"0.10.28":{"node_abi":11,"v8":"3.14"},"0.10.29":{"node_abi":11,"v8":"3.14"},"0.10.30":{"node_abi":11,"v8":"3.14"},"0.10.31":{"node_abi":11,"v8":"3.14"},"0.10.32":{"node_abi":11,"v8":"3.14"},"0.10.33":{"node_abi":11,"v8":"3.14"},"0.10.34":{"node_abi":11,"v8":"3.14"},"0.10.35":{"node_abi":11,"v8":"3.14"},"0.10.36":{"node_abi":11,"v8":"3.14"},"0.10.37":{"node_abi":11,"v8":"3.14"},"0.10.38":{"node_abi":11,"v8":"3.14"},"0.10.39":{"node_abi":11,"v8":"3.14"},"0.10.40":{"node_abi":11,"v8":"3.14"},"0.10.41":{"node_abi":11,"v8":"3.14"},"0.10.42":{"node_abi":11,"v8":"3.14"},"0.10.43":{"node_abi":11,"v8":"3.14"},"0.10.44":{"node_abi":11,"v8":"3.14"},"0.10.45":{"node_abi":11,"v8":"3.14"},"0.10.46":{"node_abi":11,"v8":"3.14"},"0.10.47":{"node_abi":11,"v8":"3.14"},"0.10.48":{"node_abi":11,"v8":"3.14"},"0.11.0":{"node_abi":12,"v8":"3.17"},"0.11.1":{"node_abi":12,"v8":"3.18"},"0.11.2":{"node_abi":12,"v8":"3.19"},"0.11.3":{"node_abi":12,"v8":"3.19"},"0.11.4":{"node_abi":12,"v8":"3.20"},"0.11.5":{"node_abi":12,"v8":"3.20"},"0.11.6":{"node_abi":12,"v8":"3.20"},"0.11.7":{"node_abi":12,"v8":"3.20"},"0.11.8":{"node_abi":13,"v8":"3.21"},"0.11.9":{"node_abi":13,"v8":"3.22"},"0.11.10":{"node_abi":13,"v8":"3.22"},"0.11.11":{"node_abi":14,"v8":"3.22"},"0.11.12":{"node_abi":14,"v8":"3.22"},"0.11.13":{"node_abi":14,"v8":"3.25"},"0.11.14":{"node_abi":14,"v8":"3.26"},"0.11.15":{"node_abi":14,"v8":"3.28"},"0.11.16":{"node_abi":14,"v8":"3.28"},"0.12.0":{"node_abi":14,"v8":"3.28"},"0.12.1":{"node_abi":14,"v8":"3.28"},"0.12.2":{"node_abi":14,"v8":"3.28"},"0.12.3":{"node_abi":14,"v8":"3.28"},"0.12.4":{"node_abi":14,"v8":"3.28"},"0.12.5":{"node_abi":14,"v8":"3.28"},"0.12.6":{"node_abi":14,"v8":"3.28"},"0.12.7":{"node_abi":14,"v8":"3.28"},"0.12.8":{"node_abi":14,"v8":"3.28"},"0.12.9":{"node_abi":14,"v8":"3.28"},"0.12.10":{"node_abi":14,"v8":"3.28"},"0.12.11":{"node_abi":14,"v8":"3.28"},"0.12.12":{"node_abi":14,"v8":"3.28"},"0.12.13":{"node_abi":14,"v8":"3.28"},"0.12.14":{"node_abi":14,"v8":"3.28"},"0.12.15":{"node_abi":14,"v8":"3.28"},"0.12.16":{"node_abi":14,"v8":"3.28"},"0.12.17":{"node_abi":14,"v8":"3.28"},"0.12.18":{"node_abi":14,"v8":"3.28"},"1.0.0":{"node_abi":42,"v8":"3.31"},"1.0.1":{"node_abi":42,"v8":"3.31"},"1.0.2":{"node_abi":42,"v8":"3.31"},"1.0.3":{"node_abi":42,"v8":"4.1"},"1.0.4":{"node_abi":42,"v8":"4.1"},"1.1.0":{"node_abi":43,"v8":"4.1"},"1.2.0":{"node_abi":43,"v8":"4.1"},"1.3.0":{"node_abi":43,"v8":"4.1"},"1.4.1":{"node_abi":43,"v8":"4.1"},"1.4.2":{"node_abi":43,"v8":"4.1"},"1.4.3":{"node_abi":43,"v8":"4.1"},"1.5.0":{"node_abi":43,"v8":"4.1"},"1.5.1":{"node_abi":43,"v8":"4.1"},"1.6.0":{"node_abi":43,"v8":"4.1"},"1.6.1":{"node_abi":43,"v8":"4.1"},"1.6.2":{"node_abi":43,"v8":"4.1"},"1.6.3":{"node_abi":43,"v8":"4.1"},"1.6.4":{"node_abi":43,"v8":"4.1"},"1.7.1":{"node_abi":43,"v8":"4.1"},"1.8.1":{"node_abi":43,"v8":"4.1"},"1.8.2":{"node_abi":43,"v8":"4.1"},"1.8.3":{"node_abi":43,"v8":"4.1"},"1.8.4":{"node_abi":43,"v8":"4.1"},"2.0.0":{"node_abi":44,"v8":"4.2"},"2.0.1":{"node_abi":44,"v8":"4.2"},"2.0.2":{"node_abi":44,"v8":"4.2"},"2.1.0":{"node_abi":44,"v8":"4.2"},"2.2.0":{"node_abi":44,"v8":"4.2"},"2.2.1":{"node_abi":44,"v8":"4.2"},"2.3.0":{"node_abi":44,"v8":"4.2"},"2.3.1":{"node_abi":44,"v8":"4.2"},"2.3.2":{"node_abi":44,"v8":"4.2"},"2.3.3":{"node_abi":44,"v8":"4.2"},"2.3.4":{"node_abi":44,"v8":"4.2"},"2.4.0":{"node_abi":44,"v8":"4.2"},"2.5.0":{"node_abi":44,"v8":"4.2"},"3.0.0":{"node_abi":45,"v8":"4.4"},"3.1.0":{"node_abi":45,"v8":"4.4"},"3.2.0":{"node_abi":45,"v8":"4.4"},"3.3.0":{"node_abi":45,"v8":"4.4"},"3.3.1":{"node_abi":45,"v8":"4.4"},"4.0.0":{"node_abi":46,"v8":"4.5"},"4.1.0":{"node_abi":46,"v8":"4.5"},"4.1.1":{"node_abi":46,"v8":"4.5"},"4.1.2":{"node_abi":46,"v8":"4.5"},"4.2.0":{"node_abi":46,"v8":"4.5"},"4.2.1":{"node_abi":46,"v8":"4.5"},"4.2.2":{"node_abi":46,"v8":"4.5"},"4.2.3":{"node_abi":46,"v8":"4.5"},"4.2.4":{"node_abi":46,"v8":"4.5"},"4.2.5":{"node_abi":46,"v8":"4.5"},"4.2.6":{"node_abi":46,"v8":"4.5"},"4.3.0":{"node_abi":46,"v8":"4.5"},"4.3.1":{"node_abi":46,"v8":"4.5"},"4.3.2":{"node_abi":46,"v8":"4.5"},"4.4.0":{"node_abi":46,"v8":"4.5"},"4.4.1":{"node_abi":46,"v8":"4.5"},"4.4.2":{"node_abi":46,"v8":"4.5"},"4.4.3":{"node_abi":46,"v8":"4.5"},"4.4.4":{"node_abi":46,"v8":"4.5"},"4.4.5":{"node_abi":46,"v8":"4.5"},"4.4.6":{"node_abi":46,"v8":"4.5"},"4.4.7":{"node_abi":46,"v8":"4.5"},"4.5.0":{"node_abi":46,"v8":"4.5"},"4.6.0":{"node_abi":46,"v8":"4.5"},"4.6.1":{"node_abi":46,"v8":"4.5"},"4.6.2":{"node_abi":46,"v8":"4.5"},"4.7.0":{"node_abi":46,"v8":"4.5"},"4.7.1":{"node_abi":46,"v8":"4.5"},"4.7.2":{"node_abi":46,"v8":"4.5"},"4.7.3":{"node_abi":46,"v8":"4.5"},"4.8.0":{"node_abi":46,"v8":"4.5"},"4.8.1":{"node_abi":46,"v8":"4.5"},"4.8.2":{"node_abi":46,"v8":"4.5"},"4.8.3":{"node_abi":46,"v8":"4.5"},"4.8.4":{"node_abi":46,"v8":"4.5"},"4.8.5":{"node_abi":46,"v8":"4.5"},"4.8.6":{"node_abi":46,"v8":"4.5"},"4.8.7":{"node_abi":46,"v8":"4.5"},"4.9.0":{"node_abi":46,"v8":"4.5"},"4.9.1":{"node_abi":46,"v8":"4.5"},"5.0.0":{"node_abi":47,"v8":"4.6"},"5.1.0":{"node_abi":47,"v8":"4.6"},"5.1.1":{"node_abi":47,"v8":"4.6"},"5.2.0":{"node_abi":47,"v8":"4.6"},"5.3.0":{"node_abi":47,"v8":"4.6"},"5.4.0":{"node_abi":47,"v8":"4.6"},"5.4.1":{"node_abi":47,"v8":"4.6"},"5.5.0":{"node_abi":47,"v8":"4.6"},"5.6.0":{"node_abi":47,"v8":"4.6"},"5.7.0":{"node_abi":47,"v8":"4.6"},"5.7.1":{"node_abi":47,"v8":"4.6"},"5.8.0":{"node_abi":47,"v8":"4.6"},"5.9.0":{"node_abi":47,"v8":"4.6"},"5.9.1":{"node_abi":47,"v8":"4.6"},"5.10.0":{"node_abi":47,"v8":"4.6"},"5.10.1":{"node_abi":47,"v8":"4.6"},"5.11.0":{"node_abi":47,"v8":"4.6"},"5.11.1":{"node_abi":47,"v8":"4.6"},"5.12.0":{"node_abi":47,"v8":"4.6"},"6.0.0":{"node_abi":48,"v8":"5.0"},"6.1.0":{"node_abi":48,"v8":"5.0"},"6.2.0":{"node_abi":48,"v8":"5.0"},"6.2.1":{"node_abi":48,"v8":"5.0"},"6.2.2":{"node_abi":48,"v8":"5.0"},"6.3.0":{"node_abi":48,"v8":"5.0"},"6.3.1":{"node_abi":48,"v8":"5.0"},"6.4.0":{"node_abi":48,"v8":"5.0"},"6.5.0":{"node_abi":48,"v8":"5.1"},"6.6.0":{"node_abi":48,"v8":"5.1"},"6.7.0":{"node_abi":48,"v8":"5.1"},"6.8.0":{"node_abi":48,"v8":"5.1"},"6.8.1":{"node_abi":48,"v8":"5.1"},"6.9.0":{"node_abi":48,"v8":"5.1"},"6.9.1":{"node_abi":48,"v8":"5.1"},"6.9.2":{"node_abi":48,"v8":"5.1"},"6.9.3":{"node_abi":48,"v8":"5.1"},"6.9.4":{"node_abi":48,"v8":"5.1"},"6.9.5":{"node_abi":48,"v8":"5.1"},"6.10.0":{"node_abi":48,"v8":"5.1"},"6.10.1":{"node_abi":48,"v8":"5.1"},"6.10.2":{"node_abi":48,"v8":"5.1"},"6.10.3":{"node_abi":48,"v8":"5.1"},"6.11.0":{"node_abi":48,"v8":"5.1"},"6.11.1":{"node_abi":48,"v8":"5.1"},"6.11.2":{"node_abi":48,"v8":"5.1"},"6.11.3":{"node_abi":48,"v8":"5.1"},"6.11.4":{"node_abi":48,"v8":"5.1"},"6.11.5":{"node_abi":48,"v8":"5.1"},"6.12.0":{"node_abi":48,"v8":"5.1"},"6.12.1":{"node_abi":48,"v8":"5.1"},"6.12.2":{"node_abi":48,"v8":"5.1"},"6.12.3":{"node_abi":48,"v8":"5.1"},"6.13.0":{"node_abi":48,"v8":"5.1"},"6.13.1":{"node_abi":48,"v8":"5.1"},"6.14.0":{"node_abi":48,"v8":"5.1"},"6.14.1":{"node_abi":48,"v8":"5.1"},"6.14.2":{"node_abi":48,"v8":"5.1"},"6.14.3":{"node_abi":48,"v8":"5.1"},"6.14.4":{"node_abi":48,"v8":"5.1"},"6.15.0":{"node_abi":48,"v8":"5.1"},"6.15.1":{"node_abi":48,"v8":"5.1"},"6.16.0":{"node_abi":48,"v8":"5.1"},"6.17.0":{"node_abi":48,"v8":"5.1"},"6.17.1":{"node_abi":48,"v8":"5.1"},"7.0.0":{"node_abi":51,"v8":"5.4"},"7.1.0":{"node_abi":51,"v8":"5.4"},"7.2.0":{"node_abi":51,"v8":"5.4"},"7.2.1":{"node_abi":51,"v8":"5.4"},"7.3.0":{"node_abi":51,"v8":"5.4"},"7.4.0":{"node_abi":51,"v8":"5.4"},"7.5.0":{"node_abi":51,"v8":"5.4"},"7.6.0":{"node_abi":51,"v8":"5.5"},"7.7.0":{"node_abi":51,"v8":"5.5"},"7.7.1":{"node_abi":51,"v8":"5.5"},"7.7.2":{"node_abi":51,"v8":"5.5"},"7.7.3":{"node_abi":51,"v8":"5.5"},"7.7.4":{"node_abi":51,"v8":"5.5"},"7.8.0":{"node_abi":51,"v8":"5.5"},"7.9.0":{"node_abi":51,"v8":"5.5"},"7.10.0":{"node_abi":51,"v8":"5.5"},"7.10.1":{"node_abi":51,"v8":"5.5"},"8.0.0":{"node_abi":57,"v8":"5.8"},"8.1.0":{"node_abi":57,"v8":"5.8"},"8.1.1":{"node_abi":57,"v8":"5.8"},"8.1.2":{"node_abi":57,"v8":"5.8"},"8.1.3":{"node_abi":57,"v8":"5.8"},"8.1.4":{"node_abi":57,"v8":"5.8"},"8.2.0":{"node_abi":57,"v8":"5.8"},"8.2.1":{"node_abi":57,"v8":"5.8"},"8.3.0":{"node_abi":57,"v8":"6.0"},"8.4.0":{"node_abi":57,"v8":"6.0"},"8.5.0":{"node_abi":57,"v8":"6.0"},"8.6.0":{"node_abi":57,"v8":"6.0"},"8.7.0":{"node_abi":57,"v8":"6.1"},"8.8.0":{"node_abi":57,"v8":"6.1"},"8.8.1":{"node_abi":57,"v8":"6.1"},"8.9.0":{"node_abi":57,"v8":"6.1"},"8.9.1":{"node_abi":57,"v8":"6.1"},"8.9.2":{"node_abi":57,"v8":"6.1"},"8.9.3":{"node_abi":57,"v8":"6.1"},"8.9.4":{"node_abi":57,"v8":"6.1"},"8.10.0":{"node_abi":57,"v8":"6.2"},"8.11.0":{"node_abi":57,"v8":"6.2"},"8.11.1":{"node_abi":57,"v8":"6.2"},"8.11.2":{"node_abi":57,"v8":"6.2"},"8.11.3":{"node_abi":57,"v8":"6.2"},"8.11.4":{"node_abi":57,"v8":"6.2"},"8.12.0":{"node_abi":57,"v8":"6.2"},"8.13.0":{"node_abi":57,"v8":"6.2"},"8.14.0":{"node_abi":57,"v8":"6.2"},"8.14.1":{"node_abi":57,"v8":"6.2"},"8.15.0":{"node_abi":57,"v8":"6.2"},"8.15.1":{"node_abi":57,"v8":"6.2"},"8.16.0":{"node_abi":57,"v8":"6.2"},"9.0.0":{"node_abi":59,"v8":"6.2"},"9.1.0":{"node_abi":59,"v8":"6.2"},"9.2.0":{"node_abi":59,"v8":"6.2"},"9.2.1":{"node_abi":59,"v8":"6.2"},"9.3.0":{"node_abi":59,"v8":"6.2"},"9.4.0":{"node_abi":59,"v8":"6.2"},"9.5.0":{"node_abi":59,"v8":"6.2"},"9.6.0":{"node_abi":59,"v8":"6.2"},"9.6.1":{"node_abi":59,"v8":"6.2"},"9.7.0":{"node_abi":59,"v8":"6.2"},"9.7.1":{"node_abi":59,"v8":"6.2"},"9.8.0":{"node_abi":59,"v8":"6.2"},"9.9.0":{"node_abi":59,"v8":"6.2"},"9.10.0":{"node_abi":59,"v8":"6.2"},"9.10.1":{"node_abi":59,"v8":"6.2"},"9.11.0":{"node_abi":59,"v8":"6.2"},"9.11.1":{"node_abi":59,"v8":"6.2"},"9.11.2":{"node_abi":59,"v8":"6.2"},"10.0.0":{"node_abi":64,"v8":"6.6"},"10.1.0":{"node_abi":64,"v8":"6.6"},"10.2.0":{"node_abi":64,"v8":"6.6"},"10.2.1":{"node_abi":64,"v8":"6.6"},"10.3.0":{"node_abi":64,"v8":"6.6"},"10.4.0":{"node_abi":64,"v8":"6.7"},"10.4.1":{"node_abi":64,"v8":"6.7"},"10.5.0":{"node_abi":64,"v8":"6.7"},"10.6.0":{"node_abi":64,"v8":"6.7"},"10.7.0":{"node_abi":64,"v8":"6.7"},"10.8.0":{"node_abi":64,"v8":"6.7"},"10.9.0":{"node_abi":64,"v8":"6.8"},"10.10.0":{"node_abi":64,"v8":"6.8"},"10.11.0":{"node_abi":64,"v8":"6.8"},"10.12.0":{"node_abi":64,"v8":"6.8"},"10.13.0":{"node_abi":64,"v8":"6.8"},"10.14.0":{"node_abi":64,"v8":"6.8"},"10.14.1":{"node_abi":64,"v8":"6.8"},"10.14.2":{"node_abi":64,"v8":"6.8"},"10.15.0":{"node_abi":64,"v8":"6.8"},"10.15.1":{"node_abi":64,"v8":"6.8"},"10.15.2":{"node_abi":64,"v8":"6.8"},"10.15.3":{"node_abi":64,"v8":"6.8"},"11.0.0":{"node_abi":67,"v8":"7.0"},"11.1.0":{"node_abi":67,"v8":"7.0"},"11.2.0":{"node_abi":67,"v8":"7.0"},"11.3.0":{"node_abi":67,"v8":"7.0"},"11.4.0":{"node_abi":67,"v8":"7.0"},"11.5.0":{"node_abi":67,"v8":"7.0"},"11.6.0":{"node_abi":67,"v8":"7.0"},"11.7.0":{"node_abi":67,"v8":"7.0"},"11.8.0":{"node_abi":67,"v8":"7.0"},"11.9.0":{"node_abi":67,"v8":"7.0"},"11.10.0":{"node_abi":67,"v8":"7.0"},"11.10.1":{"node_abi":67,"v8":"7.0"},"11.11.0":{"node_abi":67,"v8":"7.0"},"11.12.0":{"node_abi":67,"v8":"7.0"},"11.13.0":{"node_abi":67,"v8":"7.0"},"11.14.0":{"node_abi":67,"v8":"7.0"},"12.0.0":{"node_abi":72,"v8":"7.4"}}')}};var __webpack_module_cache__={};function __nccwpck_require__(e){var t=__webpack_module_cache__[e];if(t!==undefined){return t.exports}var r=__webpack_module_cache__[e]={exports:{}};var s=true;try{__webpack_modules__[e].call(r.exports,r,r.exports,__nccwpck_require__);s=false}finally{if(s)delete __webpack_module_cache__[e]}return r.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var __webpack_exports__=__nccwpck_require__(9582);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/packages/next/compiled/terser/bundle.min.js b/packages/next/compiled/terser/bundle.min.js index be28ed1f6cdf..6f10e1864e68 100644 --- a/packages/next/compiled/terser/bundle.min.js +++ b/packages/next/compiled/terser/bundle.min.js @@ -1 +1 @@ -(()=>{var e={988:e=>{"use strict";e.exports=require("next/dist/compiled/acorn")},749:e=>{"use strict";e.exports=require("next/dist/compiled/source-map")},405:function(e,t,n){(function(e,r){true?r(t,n(749)):0})(this,(function(e,t){"use strict";function _interopDefaultLegacy(e){return e&&typeof e==="object"&&"default"in e?e:{default:e}}var r=_interopDefaultLegacy(t);function characters(e){return e.split("")}function member(e,t){return t.includes(e)}class DefaultsError extends Error{constructor(e,t){super();this.name="DefaultsError";this.message=e;this.defs=t}}function defaults(e,t,n){if(e===true){e={}}else if(e!=null&&typeof e==="object"){e={...e}}const r=e||{};if(n)for(const e in r)if(HOP(r,e)&&!HOP(t,e)){throw new DefaultsError("`"+e+"` is not a supported option",t)}for(const n in t)if(HOP(t,n)){if(!e||!HOP(e,n)){r[n]=t[n]}else if(n==="ecma"){let t=e[n]|0;if(t>5&&t<2015)t+=2009;r[n]=t}else{r[n]=e&&HOP(e,n)?e[n]:t[n]}}return r}function noop(){}function return_false(){return false}function return_true(){return true}function return_this(){return this}function return_null(){return null}var i=function(){function MAP(t,n,r){var i=[],o=[],a;function doit(){var s=n(t[a],a);var u=s instanceof Last;if(u)s=s.v;if(s instanceof AtTop){s=s.v;if(s instanceof Splice){o.push.apply(o,r?s.v.slice().reverse():s.v)}else{o.push(s)}}else if(s!==e){if(s instanceof Splice){i.push.apply(i,r?s.v.slice().reverse():s.v)}else{i.push(s)}}return u}if(Array.isArray(t)){if(r){for(a=t.length;--a>=0;)if(doit())break;i.reverse();o.reverse()}else{for(a=0;a=0;){if(e[n]===t)e.splice(n,1)}}function mergeSort(e,t){if(e.length<2)return e.slice();function merge(e,n){var r=[],i=0,o=0,a=0;while(i{n+=e}))}return n}function has_annotation(e,t){return e._annotations&t}function set_annotation(e,t){e._annotations|=t}var s="";var u=true;var l="break case catch class const continue debugger default delete do else export extends finally for function if in instanceof let new return switch throw try typeof var void while with";var c="false null true";var f="enum implements import interface package private protected public static super this "+c+" "+l;var _="return new delete throw else case yield await";l=makePredicate(l);f=makePredicate(f);_=makePredicate(_);c=makePredicate(c);var p=makePredicate(characters("+-*&%=<>!?|~^"));var d=/[0-9a-f]/i;var m=/^0x[0-9a-f]+$/i;var h=/^0[0-7]+$/;var E=/^0o[0-7]+$/i;var g=/^0b[01]+$/i;var v=/^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;var D=/^(0[xob])?[0-9a-f]+n$/i;var b=makePredicate(["in","instanceof","typeof","new","void","delete","++","--","+","-","!","~","&","|","^","*","**","/","%",">>","<<",">>>","<",">","<=",">=","==","===","!=","!==","?","=","+=","-=","||=","&&=","??=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&=","&&","??","||"]);var S=makePredicate(characters("  \n\r\t\f\v​           \u2028\u2029   \ufeff"));var A=makePredicate(characters("\n\r\u2028\u2029"));var y=makePredicate(characters(";]),:"));var T=makePredicate(characters("[{(,;:"));var k=makePredicate(characters("[]{}(),;:"));var C={ID_Start:/[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/(?:[$0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF])+/};function get_full_char(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){if(is_surrogate_pair_tail(e.charCodeAt(t+1))){return e.charAt(t)+e.charAt(t+1)}}else if(is_surrogate_pair_tail(e.charCodeAt(t))){if(is_surrogate_pair_head(e.charCodeAt(t-1))){return e.charAt(t-1)+e.charAt(t)}}return e.charAt(t)}function get_full_char_code(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){return 65536+(e.charCodeAt(t)-55296<<10)+e.charCodeAt(t+1)-56320}return e.charCodeAt(t)}function get_full_char_length(e){var t=0;for(var n=0;n65535){e-=65536;return String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)}return String.fromCharCode(e)}function is_surrogate_pair_head(e){return e>=55296&&e<=56319}function is_surrogate_pair_tail(e){return e>=56320&&e<=57343}function is_digit(e){return e>=48&&e<=57}function is_identifier_start(e){return C.ID_Start.test(e)}function is_identifier_char(e){return C.ID_Continue.test(e)}const R=/^[a-z_$][a-z0-9_$]*$/i;function is_basic_identifier_string(e){return R.test(e)}function is_identifier_string(e,t){if(R.test(e)){return true}if(!t&&/[\ud800-\udfff]/.test(e)){return false}var n=C.ID_Start.exec(e);if(!n||n.index!==0){return false}e=e.slice(n[0].length);if(!e){return true}n=C.ID_Continue.exec(e);return!!n&&n[0].length===e.length}function parse_js_number(e,t=true){if(!t&&e.includes("e")){return NaN}if(m.test(e)){return parseInt(e.substr(2),16)}else if(h.test(e)){return parseInt(e.substr(1),8)}else if(E.test(e)){return parseInt(e.substr(2),8)}else if(g.test(e)){return parseInt(e.substr(2),2)}else if(v.test(e)){return parseFloat(e)}else{var n=parseFloat(e);if(n==e)return n}}class JS_Parse_Error extends Error{constructor(e,t,n,r,i){super();this.name="SyntaxError";this.message=e;this.filename=t;this.line=n;this.col=r;this.pos=i}}function js_error(e,t,n,r,i){throw new JS_Parse_Error(e,t,n,r,i)}function is_token(e,t,n){return e.type==t&&(n==null||e.value==n)}var F={};function tokenizer(e,t,n,r){var i={text:e,filename:t,pos:0,tokpos:0,line:1,tokline:0,col:0,tokcol:0,newline_before:false,regex_allowed:false,brace_counter:0,template_braces:[],comments_before:[],directives:{},directive_stack:[]};function peek(){return get_full_char(i.text,i.pos)}function is_option_chain_op(){const e=i.text.charCodeAt(i.pos+1)===46;if(!e)return false;const t=i.text.charCodeAt(i.pos+2);return t<48||t>57}function next(e,t){var n=get_full_char(i.text,i.pos++);if(e&&!n)throw F;if(A.has(n)){i.newline_before=i.newline_before||!t;++i.line;i.col=0;if(n=="\r"&&peek()=="\n"){++i.pos;n="\n"}}else{if(n.length>1){++i.pos;++i.col}++i.col}return n}function forward(e){while(e--)next()}function looking_at(e){return i.text.substr(i.pos,e.length)==e}function find_eol(){var e=i.text;for(var t=i.pos,n=i.text.length;t="0"&&e<="7"}function read_escaped_char(e,t,n){var r=next(true,e);switch(r.charCodeAt(0)){case 110:return"\n";case 114:return"\r";case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 120:return String.fromCharCode(hex_bytes(2,t));case 117:if(peek()=="{"){next(true);if(peek()==="}")parse_error("Expecting hex-character between {}");while(peek()=="0")next(true);var o,a=find("}",true)-i.pos;if(a>6||(o=hex_bytes(a,t))>1114111){parse_error("Unicode reference out of bounds")}next(true);return from_char_code(o)}return String.fromCharCode(hex_bytes(4,t));case 10:return"";case 13:if(peek()=="\n"){next(true,e);return""}}if(is_octal(r)){if(n&&t){const e=r==="0"&&!is_octal(peek());if(!e){parse_error("Octal escape sequences are not allowed in template strings")}}return read_octal_escape_sequence(r,t)}return r}function read_octal_escape_sequence(e,t){var n=peek();if(n>="0"&&n<="7"){e+=next(true);if(e[0]<="3"&&(n=peek())>="0"&&n<="7")e+=next(true)}if(e==="0")return"\0";if(e.length>0&&next_token.has_directive("use strict")&&t)parse_error("Legacy octal escape sequences are not allowed in strict mode");return String.fromCharCode(parseInt(e,8))}function hex_bytes(e,t){var n=0;for(;e>0;--e){if(!t&&isNaN(parseInt(peek(),16))){return parseInt(n,16)||""}var r=next(true);if(isNaN(parseInt(r,16)))parse_error("Invalid hex-character pattern in string");n+=r}return parseInt(n,16)}var E=with_eof_error("Unterminated string constant",(function(){const e=i.pos;var t=next(),n=[];for(;;){var r=next(true,true);if(r=="\\")r=read_escaped_char(true,true);else if(r=="\r"||r=="\n")parse_error("Unterminated string constant");else if(r==t)break;n.push(r)}var o=token("string",n.join(""));s=i.text.slice(e,i.pos);o.quote=t;return o}));var g=with_eof_error("Unterminated template",(function(e){if(e){i.template_braces.push(i.brace_counter)}var t="",n="",r,o;next(true,true);while((r=next(true,true))!="`"){if(r=="\r"){if(peek()=="\n")++i.pos;r="\n"}else if(r=="$"&&peek()=="{"){next(true,true);i.brace_counter++;o=token(e?"template_head":"template_substitution",t);s=n;u=false;return o}n+=r;if(r=="\\"){var l=i.pos;var c=a&&(a.type==="name"||a.type==="punc"&&(a.value===")"||a.value==="]"));r=read_escaped_char(true,!c,true);n+=i.text.substr(l,i.pos-l)}t+=r}i.template_braces.pop();o=token(e?"template_head":"template_substitution",t);s=n;u=true;return o}));function skip_line_comment(e){var t=i.regex_allowed;var n=find_eol(),r;if(n==-1){r=i.text.substr(i.pos);i.pos=i.text.length}else{r=i.text.substring(i.pos,n);i.pos=n}i.col=i.tokcol+(i.pos-i.tokpos);i.comments_before.push(token(e,r,true));i.regex_allowed=t;return next_token}var v=with_eof_error("Unterminated multiline comment",(function(){var e=i.regex_allowed;var t=find("*/",true);var n=i.text.substring(i.pos,t).replace(/\r\n|\r|\u2028|\u2029/g,"\n");forward(get_full_char_length(n)+2);i.comments_before.push(token("comment2",n,true));i.newline_before=i.newline_before||n.includes("\n");i.regex_allowed=e;return next_token}));var y=with_eof_error("Unterminated identifier name",(function(){var e=[],t,n=false;var read_escaped_identifier_char=function(){n=true;next();if(peek()!=="u"){parse_error("Expecting UnicodeEscapeSequence -- uXXXX or u{XXXX}")}return read_escaped_char(false,true)};if((t=peek())==="\\"){t=read_escaped_identifier_char();if(!is_identifier_start(t)){parse_error("First identifier char is an invalid identifier char")}}else if(is_identifier_start(t)){next()}else{return""}e.push(t);while((t=peek())!=null){if((t=peek())==="\\"){t=read_escaped_identifier_char();if(!is_identifier_char(t)){parse_error("Invalid escaped identifier char")}}else{if(!is_identifier_char(t)){break}next()}e.push(t)}const r=e.join("");if(f.has(r)&&n){parse_error("Escaped characters are not allowed in keywords")}return r}));var C=with_eof_error("Unterminated regular expression",(function(e){var t=false,n,r=false;while(n=next(true))if(A.has(n)){parse_error("Unexpected line terminator")}else if(t){e+="\\"+n;t=false}else if(n=="["){r=true;e+=n}else if(n=="]"&&r){r=false;e+=n}else if(n=="/"&&!r){break}else if(n=="\\"){t=true}else{e+=n}const i=y();return token("regexp","/"+e+"/"+i)}));function read_operator(e){function grow(e){if(!peek())return e;var t=e+peek();if(b.has(t)){next();return grow(t)}else{return e}}return token("operator",grow(e||next()))}function handle_slash(){next();switch(peek()){case"/":next();return skip_line_comment("comment1");case"*":next();return v()}return i.regex_allowed?C(""):read_operator("/")}function handle_eq_sign(){next();if(peek()===">"){next();return token("arrow","=>")}else{return read_operator("=")}}function handle_dot(){next();if(is_digit(peek().charCodeAt(0))){return read_num(".")}if(peek()==="."){next();next();return token("expand","...")}return token("punc",".")}function read_word(){var e=y();if(o)return token("name",e);return c.has(e)?token("atom",e):!l.has(e)?token("name",e):b.has(e)?token("operator",e):token("keyword",e)}function read_private_word(){next();return token("privatename",y())}function with_eof_error(e,t){return function(n){try{return t(n)}catch(t){if(t===F)parse_error(e);else throw t}}}function next_token(e){if(e!=null)return C(e);if(r&&i.pos==0&&looking_at("#!")){start_token();forward(2);skip_line_comment("comment5")}for(;;){skip_whitespace();start_token();if(n){if(looking_at("\x3c!--")){forward(4);skip_line_comment("comment3");continue}if(looking_at("--\x3e")&&i.newline_before){forward(3);skip_line_comment("comment4");continue}}var t=peek();if(!t)return token("eof");var o=t.charCodeAt(0);switch(o){case 34:case 39:return E();case 46:return handle_dot();case 47:{var a=handle_slash();if(a===next_token)continue;return a}case 61:return handle_eq_sign();case 63:{if(!is_option_chain_op())break;next();next();return token("punc","?.")}case 96:return g(true);case 123:i.brace_counter++;break;case 125:i.brace_counter--;if(i.template_braces.length>0&&i.template_braces[i.template_braces.length-1]===i.brace_counter)return g(false);break}if(is_digit(o))return read_num();if(k.has(t))return token("punc",next());if(p.has(t))return read_operator();if(o==92||is_identifier_start(t))return read_word();if(o==35)return read_private_word();break}parse_error("Unexpected character '"+t+"'")}next_token.next=next;next_token.peek=peek;next_token.context=function(e){if(e)i=e;return i};next_token.add_directive=function(e){i.directive_stack[i.directive_stack.length-1].push(e);if(i.directives[e]===undefined){i.directives[e]=1}else{i.directives[e]++}};next_token.push_directives_stack=function(){i.directive_stack.push([])};next_token.pop_directives_stack=function(){var e=i.directive_stack[i.directive_stack.length-1];for(var t=0;t0};return next_token}var O=makePredicate(["typeof","void","delete","--","++","!","~","-","+"]);var M=makePredicate(["--","++"]);var x=makePredicate(["=","+=","-=","??=","&&=","||=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&="]);var N=makePredicate(["??=","&&=","||="]);var w=function(e,t){for(var n=0;n","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],{});var I=makePredicate(["atom","num","big_int","string","regexp","name"]);function parse(e,t){const n=new WeakMap;t=defaults(t,{bare_returns:false,ecma:null,expression:false,filename:null,html5_comments:true,module:false,shebang:true,strict:false,toplevel:null},true);var r={input:typeof e=="string"?tokenizer(e,t.filename,t.html5_comments,t.shebang):e,token:null,prev:null,peeked:null,in_function:0,in_async:-1,in_generator:-1,in_directives:true,in_loop:0,labels:[]};r.token=next();function is(e,t){return is_token(r.token,e,t)}function peek(){return r.peeked||(r.peeked=r.input())}function next(){r.prev=r.token;if(!r.peeked)peek();r.token=r.peeked;r.peeked=null;r.in_directives=r.in_directives&&(r.token.type=="string"||is("punc",";"));return r.token}function prev(){return r.prev}function croak(e,t,n,i){var o=r.input.context();js_error(e,o.filename,t!=null?t:o.tokline,n!=null?n:o.tokcol,i!=null?i:o.tokpos)}function token_error(e,t){croak(t,e.line,e.col)}function unexpected(e){if(e==null)e=r.token;token_error(e,"Unexpected token: "+e.type+" ("+e.value+")")}function expect_token(e,t){if(is(e,t)){return next()}token_error(r.token,"Unexpected token "+r.token.type+" «"+r.token.value+"»"+", expected "+e+" «"+t+"»")}function expect(e){return expect_token("punc",e)}function has_newline_before(e){return e.nlb||!e.comments_before.every((e=>!e.nlb))}function can_insert_semicolon(){return!t.strict&&(is("eof")||is("punc","}")||has_newline_before(r.token))}function is_in_generator(){return r.in_generator===r.in_function}function is_in_async(){return r.in_async===r.in_function}function can_await(){return r.in_async===r.in_function||r.in_function===0&&r.input.has_directive("use strict")}function semicolon(e){if(is("punc",";"))next();else if(!e&&!can_insert_semicolon())unexpected()}function parenthesised(){expect("(");var e=expression(true);expect(")");return e}function embed_tokens(e){return function _embed_tokens_wrapper(...t){const n=r.token;const i=e(...t);i.start=n;i.end=prev();return i}}function handle_regexp(){if(is("operator","/")||is("operator","/=")){r.peeked=null;r.token=r.input(r.token.value.substr(1))}}var i=embed_tokens((function statement(e,n,i){handle_regexp();switch(r.token.type){case"string":if(r.in_directives){var o=peek();if(!s.includes("\\")&&(is_token(o,"punc",";")||is_token(o,"punc","}")||has_newline_before(o)||is_token(o,"eof"))){r.input.add_directive(r.token.value)}else{r.in_directives=false}}var a=r.in_directives,u=simple_statement();return a&&u.body instanceof Kt?new K(u.body):u;case"template_head":case"num":case"big_int":case"regexp":case"operator":case"atom":return simple_statement();case"name":if(r.token.value=="async"&&is_token(peek(),"keyword","function")){next();next();if(n){croak("functions are not allowed as the body of a loop")}return function_(ce,false,true,e)}if(r.token.value=="import"&&!is_token(peek(),"punc","(")&&!is_token(peek(),"punc",".")){next();var l=import_();semicolon();return l}return is_token(peek(),"punc",":")?labeled_statement():simple_statement();case"punc":switch(r.token.value){case"{":return new X({start:r.token,body:block_(),end:prev()});case"[":case"(":return simple_statement();case";":r.in_directives=false;next();return new W;default:unexpected()}case"keyword":switch(r.token.value){case"break":next();return break_cont(De);case"continue":next();return break_cont(be);case"debugger":next();semicolon();return new z;case"do":next();var c=in_loop(statement);expect_token("keyword","while");var f=parenthesised();semicolon(true);return new Z({body:c,condition:f});case"while":next();return new Q({condition:parenthesised(),body:in_loop((function(){return statement(false,true)}))});case"for":next();return for_();case"class":next();if(n){croak("classes are not allowed as the body of a loop")}if(i){croak("classes are not allowed as the body of an if")}return class_(mt,e);case"function":next();if(n){croak("functions are not allowed as the body of a loop")}return function_(ce,false,false,e);case"if":next();return if_();case"return":if(r.in_function==0&&!t.bare_returns)croak("'return' outside of function");next();var _=null;if(is("punc",";")){next()}else if(!can_insert_semicolon()){_=expression(true);semicolon()}return new Ee({value:_});case"switch":next();return new Te({expression:parenthesised(),body:in_loop(switch_body_)});case"throw":next();if(has_newline_before(r.token))croak("Illegal newline after 'throw'");var _=expression(true);semicolon();return new ge({value:_});case"try":next();return try_();case"var":next();var l=var_();semicolon();return l;case"let":next();var l=let_();semicolon();return l;case"const":next();var l=const_();semicolon();return l;case"with":if(r.input.has_directive("use strict")){croak("Strict mode may not include a with statement")}next();return new ne({expression:parenthesised(),body:statement()});case"export":if(!is_token(peek(),"punc","(")){next();var l=export_();if(is("punc",";"))semicolon();return l}}}unexpected()}));function labeled_statement(){var e=as_symbol(wt);if(e.name==="await"&&is_in_async()){token_error(r.prev,"await cannot be used as label inside async function")}if(r.labels.some((t=>t.name===e.name))){croak("Label "+e.name+" defined twice")}expect(":");r.labels.push(e);var t=i();r.labels.pop();if(!(t instanceof j)){e.references.forEach((function(t){if(t instanceof be){t=t.label.start;croak("Continue label `"+e.name+"` refers to non-IterationStatement.",t.line,t.col,t.pos)}}))}return new Y({body:t,label:e})}function simple_statement(e){return new G({body:(e=expression(true),semicolon(),e)})}function break_cont(e){var t=null,n;if(!can_insert_semicolon()){t=as_symbol(Lt,true)}if(t!=null){n=r.labels.find((e=>e.name===t.name));if(!n)croak("Undefined label "+t.name);t.thedef=n}else if(r.in_loop==0)croak(e.TYPE+" not inside a loop or switch");semicolon();var i=new e({label:t});if(n)n.references.push(i);return i}function for_(){var e="`for await` invalid in this context";var t=r.token;if(t.type=="name"&&t.value=="await"){if(!can_await()){token_error(t,e)}next()}else{t=false}expect("(");var n=null;if(!is("punc",";")){n=is("keyword","var")?(next(),var_(true)):is("keyword","let")?(next(),let_(true)):is("keyword","const")?(next(),const_(true)):expression(true,true);var i=is("operator","in");var o=is("name","of");if(t&&!o){token_error(t,e)}if(i||o){if(n instanceof xe){if(n.definitions.length>1)token_error(n.start,"Only one variable declaration allowed in for..in loop")}else if(!(is_assignable(n)||(n=to_destructuring(n))instanceof fe)){token_error(n.start,"Invalid left-hand side in for..in loop")}next();if(i){return for_in(n)}else{return for_of(n,!!t)}}}else if(t){token_error(t,e)}return regular_for(n)}function regular_for(e){expect(";");var t=is("punc",";")?null:expression(true);expect(";");var n=is("punc",")")?null:expression(true);expect(")");return new J({init:e,condition:t,step:n,body:in_loop((function(){return i(false,true)}))})}function for_of(e,t){var n=e instanceof xe?e.definitions[0].name:null;var r=expression(true);expect(")");return new te({await:t,init:e,name:n,object:r,body:in_loop((function(){return i(false,true)}))})}function for_in(e){var t=expression(true);expect(")");return new ee({init:e,object:t,body:in_loop((function(){return i(false,true)}))})}var arrow_function=function(e,t,n){if(has_newline_before(r.token)){croak("Unexpected newline before arrow (=>)")}expect_token("arrow","=>");var i=_function_body(is("punc","{"),false,n);var o=i instanceof Array&&i.length?i[i.length-1].end:i instanceof Array?e:i.end;return new le({start:e,end:o,async:n,argnames:t,body:i})};var function_=function(e,t,n,r){var i=e===ce;var o=is("operator","*");if(o){next()}var a=is("name")?as_symbol(i?Tt:Rt):null;if(i&&!a){if(r){e=ue}else{unexpected()}}if(a&&e!==se&&!(a instanceof vt))unexpected(prev());var s=[];var u=_function_body(true,o||t,n,a,s);return new e({start:s.start,end:u.end,is_generator:o,async:n,name:a,argnames:s,body:u})};function track_used_binding_identifiers(e,t){var n=new Set;var r=false;var i=false;var o=false;var a=!!t;var s={add_parameter:function(t){if(n.has(t.value)){if(r===false){r=t}s.check_strict()}else{n.add(t.value);if(e){switch(t.value){case"arguments":case"eval":case"yield":if(a){token_error(t,"Unexpected "+t.value+" identifier as parameter inside strict mode")}break;default:if(f.has(t.value)){unexpected()}}}}},mark_default_assignment:function(e){if(i===false){i=e}},mark_spread:function(e){if(o===false){o=e}},mark_strict_mode:function(){a=true},is_strict:function(){return i!==false||o!==false||a},check_strict:function(){if(s.is_strict()&&r!==false){token_error(r,"Parameter "+r.value+" was used already")}}};return s}function parameters(e){var t=track_used_binding_identifiers(true,r.input.has_directive("use strict"));expect("(");while(!is("punc",")")){var n=parameter(t);e.push(n);if(!is("punc",")")){expect(",")}if(n instanceof oe){break}}next()}function parameter(e,t){var n;var i=false;if(e===undefined){e=track_used_binding_identifiers(true,r.input.has_directive("use strict"))}if(is("expand","...")){i=r.token;e.mark_spread(r.token);next()}n=binding_element(e,t);if(is("operator","=")&&i===false){e.mark_default_assignment(r.token);next();n=new tt({start:n.start,left:n,operator:"=",right:expression(false),end:r.token})}if(i!==false){if(!is("punc",")")){unexpected()}n=new oe({start:i,expression:n,end:i})}e.check_strict();return n}function binding_element(e,t){var n=[];var i=true;var o=false;var a;var s=r.token;if(e===undefined){e=track_used_binding_identifiers(false,r.input.has_directive("use strict"))}t=t===undefined?yt:t;if(is("punc","[")){next();while(!is("punc","]")){if(i){i=false}else{expect(",")}if(is("expand","...")){o=true;a=r.token;e.mark_spread(r.token);next()}if(is("punc")){switch(r.token.value){case",":n.push(new $t({start:r.token,end:r.token}));continue;case"]":break;case"[":case"{":n.push(binding_element(e,t));break;default:unexpected()}}else if(is("name")){e.add_parameter(r.token);n.push(as_symbol(t))}else{croak("Invalid function parameter")}if(is("operator","=")&&o===false){e.mark_default_assignment(r.token);next();n[n.length-1]=new tt({start:n[n.length-1].start,left:n[n.length-1],operator:"=",right:expression(false),end:r.token})}if(o){if(!is("punc","]")){croak("Rest element must be last element")}n[n.length-1]=new oe({start:a,expression:n[n.length-1],end:a})}}expect("]");e.check_strict();return new fe({start:s,names:n,is_array:true,end:prev()})}else if(is("punc","{")){next();while(!is("punc","}")){if(i){i=false}else{expect(",")}if(is("expand","...")){o=true;a=r.token;e.mark_spread(r.token);next()}if(is("name")&&(is_token(peek(),"punc")||is_token(peek(),"operator"))&&[",","}","="].includes(peek().value)){e.add_parameter(r.token);var u=prev();var l=as_symbol(t);if(o){n.push(new oe({start:a,expression:l,end:l.end}))}else{n.push(new ot({start:u,key:l.name,value:l,end:l.end}))}}else if(is("punc","}")){continue}else{var c=r.token;var f=as_property_name();if(f===null){unexpected(prev())}else if(prev().type==="name"&&!is("punc",":")){n.push(new ot({start:prev(),key:f,value:new t({start:prev(),name:f,end:prev()}),end:prev()}))}else{expect(":");n.push(new ot({start:c,quote:c.quote,key:f,value:binding_element(e,t),end:prev()}))}}if(o){if(!is("punc","}")){croak("Rest element must be last element")}}else if(is("operator","=")){e.mark_default_assignment(r.token);next();n[n.length-1].value=new tt({start:n[n.length-1].value.start,left:n[n.length-1].value,operator:"=",right:expression(false),end:r.token})}}expect("}");e.check_strict();return new fe({start:s,names:n,is_array:false,end:prev()})}else if(is("name")){e.add_parameter(r.token);return as_symbol(t)}else{croak("Invalid function parameter")}}function params_or_seq_(e,t){var n;var i;var o;var a=[];expect("(");while(!is("punc",")")){if(n)unexpected(n);if(is("expand","...")){n=r.token;if(t)i=r.token;next();a.push(new oe({start:prev(),expression:expression(),end:r.token}))}else{a.push(expression())}if(!is("punc",")")){expect(",");if(is("punc",")")){o=prev();if(t)i=o}}}expect(")");if(e&&is("arrow","=>")){if(n&&o)unexpected(o)}else if(i){unexpected(i)}return a}function _function_body(e,t,n,i,o){var a=r.in_loop;var s=r.labels;var u=r.in_generator;var l=r.in_async;++r.in_function;if(t)r.in_generator=r.in_function;if(n)r.in_async=r.in_function;if(o)parameters(o);if(e)r.in_directives=true;r.in_loop=0;r.labels=[];if(e){r.input.push_directives_stack();var c=block_();if(i)_verify_symbol(i);if(o)o.forEach(_verify_symbol);r.input.pop_directives_stack()}else{var c=[new Ee({start:r.token,value:expression(false),end:r.token})]}--r.in_function;r.in_loop=a;r.labels=s;r.in_generator=u;r.in_async=l;return c}function _await_expression(){if(!can_await()){croak("Unexpected await expression outside async function",r.prev.line,r.prev.col,r.prev.pos)}return new Se({start:prev(),end:r.token,expression:maybe_unary(true)})}function _yield_expression(){if(!is_in_generator()){croak("Unexpected yield expression outside generator function",r.prev.line,r.prev.col,r.prev.pos)}var e=r.token;var t=false;var n=true;if(can_insert_semicolon()||is("punc")&&y.has(r.token.value)){n=false}else if(is("operator","*")){t=true;next()}return new Ae({start:e,is_star:t,expression:n?expression():null,end:prev()})}function if_(){var e=parenthesised(),t=i(false,false,true),n=null;if(is("keyword","else")){next();n=i(false,false,true)}return new ye({condition:e,body:t,alternative:n})}function block_(){expect("{");var e=[];while(!is("punc","}")){if(is("eof"))unexpected();e.push(i())}next();return e}function switch_body_(){expect("{");var e=[],t=null,n=null,o;while(!is("punc","}")){if(is("eof"))unexpected();if(is("keyword","case")){if(n)n.end=prev();t=[];n=new Re({start:(o=r.token,next(),o),expression:expression(true),body:t});e.push(n);expect(":")}else if(is("keyword","default")){if(n)n.end=prev();t=[];n=new Ce({start:(o=r.token,next(),expect(":"),o),body:t});e.push(n)}else{if(!t)unexpected();t.push(i())}}if(n)n.end=prev();next();return e}function try_(){var e=block_(),t=null,n=null;if(is("keyword","catch")){var i=r.token;next();if(is("punc","{")){var o=null}else{expect("(");var o=parameter(undefined,Mt);expect(")")}t=new Oe({start:i,argname:o,body:block_(),end:prev()})}if(is("keyword","finally")){var i=r.token;next();n=new Me({start:i,body:block_(),end:prev()})}if(!t&&!n)croak("Missing catch/finally blocks");return new Fe({body:e,bcatch:t,bfinally:n})}function vardefs(e,t){var n=[];var i;for(;;){var o=t==="var"?Dt:t==="const"?St:t==="let"?At:null;if(is("punc","{")||is("punc","[")){i=new Pe({start:r.token,name:binding_element(undefined,o),value:is("operator","=")?(expect_token("operator","="),expression(false,e)):null,end:prev()})}else{i=new Pe({start:r.token,name:as_symbol(o),value:is("operator","=")?(next(),expression(false,e)):!e&&t==="const"?croak("Missing initializer in const declaration"):null,end:prev()});if(i.name.name=="import")croak("Unexpected token: import")}n.push(i);if(!is("punc",","))break;next()}return n}var var_=function(e){return new Ne({start:prev(),definitions:vardefs(e,"var"),end:prev()})};var let_=function(e){return new we({start:prev(),definitions:vardefs(e,"let"),end:prev()})};var const_=function(e){return new Ie({start:prev(),definitions:vardefs(e,"const"),end:prev()})};var new_=function(e){var t=r.token;expect_token("operator","new");if(is("punc",".")){next();expect_token("name","target");return subscripts(new gt({start:t,end:prev()}),e)}var n=expr_atom(false),i;if(is("punc","(")){next();i=expr_list(")",true)}else{i=[]}var o=new Ke({start:t,expression:n,args:i,end:prev()});annotate(o);return subscripts(o,e)};function as_atom_node(){var e=r.token,t;switch(e.type){case"name":t=_make_symbol(It);break;case"num":t=new Gt({start:e,end:e,value:e.value,raw:s});break;case"big_int":t=new Ht({start:e,end:e,value:e.value});break;case"string":t=new Kt({start:e,end:e,value:e.value,quote:e.quote});break;case"regexp":const[n,r,i]=e.value.match(/^\/(.*)\/(\w*)$/);t=new Xt({start:e,end:e,value:{source:r,flags:i}});break;case"atom":switch(e.value){case"false":t=new Jt({start:e,end:e});break;case"true":t=new en({start:e,end:e});break;case"null":t=new qt({start:e,end:e});break}break}next();return t}function to_fun_args(e,t){var insert_default=function(e,t){if(t){return new tt({start:e.start,left:e,operator:"=",right:t,end:t.end})}return e};if(e instanceof rt){return insert_default(new fe({start:e.start,end:e.end,is_array:false,names:e.properties.map((e=>to_fun_args(e)))}),t)}else if(e instanceof ot){e.value=to_fun_args(e.value);return insert_default(e,t)}else if(e instanceof $t){return e}else if(e instanceof fe){e.names=e.names.map((e=>to_fun_args(e)));return insert_default(e,t)}else if(e instanceof It){return insert_default(new yt({name:e.name,start:e.start,end:e.end}),t)}else if(e instanceof oe){e.expression=to_fun_args(e.expression);return insert_default(e,t)}else if(e instanceof nt){return insert_default(new fe({start:e.start,end:e.end,is_array:true,names:e.elements.map((e=>to_fun_args(e)))}),t)}else if(e instanceof et){return insert_default(to_fun_args(e.left,e.right),t)}else if(e instanceof tt){e.left=to_fun_args(e.left);return e}else{croak("Invalid function parameter",e.start.line,e.start.col)}}var expr_atom=function(e,t){if(is("operator","new")){return new_(e)}if(is("operator","import")){return import_meta()}var i=r.token;var a;var s=is("name","async")&&(a=peek()).value!="["&&a.type!="arrow"&&as_atom_node();if(is("punc")){switch(r.token.value){case"(":if(s&&!e)break;var u=params_or_seq_(t,!s);if(t&&is("arrow","=>")){return arrow_function(i,u.map((e=>to_fun_args(e))),!!s)}var c=s?new ze({expression:s,args:u}):u.length==1?u[0]:new Ge({expressions:u});if(c.start){const e=i.comments_before.length;n.set(i,e);c.start.comments_before.unshift(...i.comments_before);i.comments_before=c.start.comments_before;if(e==0&&i.comments_before.length>0){var f=i.comments_before[0];if(!f.nlb){f.nlb=i.nlb;i.nlb=false}}i.comments_after=c.start.comments_after}c.start=i;var _=prev();if(c.end){_.comments_before=c.end.comments_before;c.end.comments_after.push(..._.comments_after);_.comments_after=c.end.comments_after}c.end=_;if(c instanceof ze)annotate(c);return subscripts(c,e);case"[":return subscripts(o(),e);case"{":return subscripts(l(),e)}if(!s)unexpected()}if(t&&is("name")&&is_token(peek(),"arrow")){var p=new yt({name:r.token.value,start:i,end:i});next();return arrow_function(i,[p],!!s)}if(is("keyword","function")){next();var d=function_(ue,false,!!s);d.start=i;d.end=prev();return subscripts(d,e)}if(s)return subscripts(s,e);if(is("keyword","class")){next();var m=class_(ht);m.start=i;m.end=prev();return subscripts(m,e)}if(is("template_head")){return subscripts(template_string(),e)}if(I.has(r.token.type)){return subscripts(as_atom_node(),e)}unexpected()};function template_string(){var e=[],t=r.token;e.push(new de({start:r.token,raw:s,value:r.token.value,end:r.token}));while(!u){next();handle_regexp();e.push(expression(true));e.push(new de({start:r.token,raw:s,value:r.token.value,end:r.token}))}next();return new pe({start:t,segments:e,end:r.token})}function expr_list(e,t,n){var i=true,o=[];while(!is("punc",e)){if(i)i=false;else expect(",");if(t&&is("punc",e))break;if(is("punc",",")&&n){o.push(new $t({start:r.token,end:r.token}))}else if(is("expand","...")){next();o.push(new oe({start:prev(),expression:expression(),end:r.token}))}else{o.push(expression(false))}}next();return o}var o=embed_tokens((function(){expect("[");return new nt({elements:expr_list("]",!t.strict,true)})}));var a=embed_tokens(((e,t)=>function_(se,e,t)));var l=embed_tokens((function object_or_destructuring_(){var e=r.token,n=true,i=[];expect("{");while(!is("punc","}")){if(n)n=false;else expect(",");if(!t.strict&&is("punc","}"))break;e=r.token;if(e.type=="expand"){next();i.push(new oe({start:e,expression:expression(false),end:prev()}));continue}var o=as_property_name();var a;if(!is("punc",":")){var s=concise_method_or_getset(o,e);if(s){i.push(s);continue}a=new It({start:prev(),name:o,end:prev()})}else if(o===null){unexpected(prev())}else{next();a=expression(false)}if(is("operator","=")){next();a=new et({start:e,left:a,operator:"=",right:expression(false),logical:false,end:prev()})}i.push(new ot({start:e,quote:e.quote,key:o instanceof V?o:""+o,value:a,end:prev()}))}next();return new rt({properties:i})}));function class_(e,t){var n,i,o,a,s=[];r.input.push_directives_stack();r.input.add_directive("use strict");if(r.token.type=="name"&&r.token.value!="extends"){o=as_symbol(e===mt?Ft:Ot)}if(e===mt&&!o){if(t){e=ht}else{unexpected()}}if(r.token.value=="extends"){next();a=expression(true)}expect("{");while(is("punc",";")){next()}while(!is("punc","}")){n=r.token;i=concise_method_or_getset(as_property_name(),n,true);if(!i){unexpected()}s.push(i);while(is("punc",";")){next()}}r.input.pop_directives_stack();next();return new e({start:n,name:o,extends:a,properties:s,end:prev()})}function concise_method_or_getset(e,t,n){const get_symbol_ast=(e,n=kt)=>{if(typeof e==="string"||typeof e==="number"){return new n({start:t,name:""+e,end:prev()})}else if(e===null){unexpected()}return e};const is_not_method_start=()=>!is("punc","(")&&!is("punc",",")&&!is("punc","}")&&!is("operator","=");var r=false;var i=false;var o=false;var s=false;var u=null;if(n&&e==="static"&&is_not_method_start()){i=true;e=as_property_name()}if(e==="async"&&is_not_method_start()){r=true;e=as_property_name()}if(prev().type==="operator"&&prev().value==="*"){o=true;e=as_property_name()}if((e==="get"||e==="set")&&is_not_method_start()){u=e;e=as_property_name()}if(prev().type==="privatename"){s=true}const l=prev();if(u!=null){if(!s){const n=u==="get"?lt:ut;e=get_symbol_ast(e);return new n({start:t,static:i,key:e,quote:e instanceof kt?l.quote:undefined,value:a(),end:prev()})}else{const n=u==="get"?st:at;return new n({start:t,static:i,key:get_symbol_ast(e),value:a(),end:prev()})}}if(is("punc","(")){e=get_symbol_ast(e);const n=s?ft:ct;var c=new n({start:t,static:i,is_generator:o,async:r,key:e,quote:e instanceof kt?l.quote:undefined,value:a(o,r),end:prev()});return c}if(n){const n=get_symbol_ast(e,Ct);const r=n instanceof Ct?l.quote:undefined;const o=s?dt:pt;if(is("operator","=")){next();return new o({start:t,static:i,quote:r,key:n,value:expression(false),end:prev()})}else if(is("name")||is("privatename")||is("operator","*")||is("punc",";")||is("punc","}")){return new o({start:t,static:i,quote:r,key:n,end:prev()})}}}function import_(){var e=prev();var t;var n;if(is("name")){t=as_symbol(xt)}if(is("punc",",")){next()}n=map_names(true);if(n||t){expect_token("name","from")}var i=r.token;if(i.type!=="string"){unexpected()}next();return new Le({start:e,imported_name:t,imported_names:n,module_name:new Kt({start:i,value:i.value,quote:i.quote,end:i}),end:r.token})}function import_meta(){var e=r.token;expect_token("operator","import");expect_token("punc",".");expect_token("name","meta");return subscripts(new Ve({start:e,end:prev()}),false)}function map_name(e){function make_symbol(e){return new e({name:as_property_name(),start:prev(),end:prev()})}var t=e?Nt:Bt;var n=e?xt:Pt;var i=r.token;var o;var a;if(e){o=make_symbol(t)}else{a=make_symbol(n)}if(is("name","as")){next();if(e){a=make_symbol(n)}else{o=make_symbol(t)}}else if(e){a=new n(o)}else{o=new t(a)}return new Be({start:i,foreign_name:o,name:a,end:prev()})}function map_nameAsterisk(e,t){var n=e?Nt:Bt;var i=e?xt:Pt;var o=r.token;var a;var s=prev();t=t||new i({name:"*",start:o,end:s});a=new n({name:"*",start:o,end:s});return new Be({start:o,foreign_name:a,name:t,end:s})}function map_names(e){var t;if(is("punc","{")){next();t=[];while(!is("punc","}")){t.push(map_name(e));if(is("punc",",")){next()}}next()}else if(is("operator","*")){var n;next();if(e&&is("name","as")){next();n=as_symbol(e?xt:Bt)}t=[map_nameAsterisk(e,n)]}return t}function export_(){var e=r.token;var t;var n;if(is("keyword","default")){t=true;next()}else if(n=map_names(false)){if(is("name","from")){next();var o=r.token;if(o.type!=="string"){unexpected()}next();return new Ue({start:e,is_default:t,exported_names:n,module_name:new Kt({start:o,value:o.value,quote:o.quote,end:o}),end:prev()})}else{return new Ue({start:e,is_default:t,exported_names:n,end:prev()})}}var a;var s;var u;if(is("punc","{")||t&&(is("keyword","class")||is("keyword","function"))&&is_token(peek(),"punc")){s=expression(false);semicolon()}else if((a=i(t))instanceof xe&&t){unexpected(a.start)}else if(a instanceof xe||a instanceof ce||a instanceof mt){u=a}else if(a instanceof ht||a instanceof ue){s=a}else if(a instanceof G){s=a.body}else{unexpected(a.start)}return new Ue({start:e,is_default:t,exported_value:s,exported_definition:u,end:prev()})}function as_property_name(){var e=r.token;switch(e.type){case"punc":if(e.value==="["){next();var t=expression(false);expect("]");return t}else unexpected(e);case"operator":if(e.value==="*"){next();return null}if(!["delete","in","instanceof","new","typeof","void"].includes(e.value)){unexpected(e)}case"name":case"privatename":case"string":case"num":case"big_int":case"keyword":case"atom":next();return e.value;default:unexpected(e)}}function as_name(){var e=r.token;if(e.type!="name"&&e.type!="privatename")unexpected();next();return e.value}function _make_symbol(e){var t=r.token.value;return new(t=="this"?Vt:t=="super"?Ut:e)({name:String(t),start:r.token,end:r.token})}function _verify_symbol(e){var t=e.name;if(is_in_generator()&&t=="yield"){token_error(e.start,"Yield cannot be used as identifier inside generators")}if(r.input.has_directive("use strict")){if(t=="yield"){token_error(e.start,"Unexpected yield identifier inside strict mode")}if(e instanceof vt&&(t=="arguments"||t=="eval")){token_error(e.start,"Unexpected "+t+" in strict mode")}}}function as_symbol(e,t){if(!is("name")){if(!t)croak("Name expected");return null}var n=_make_symbol(e);_verify_symbol(n);next();return n}function annotate(e){var t=e.start;var r=t.comments_before;const i=n.get(t);var o=i!=null?i:r.length;while(--o>=0){var a=r[o];if(/[@#]__/.test(a.value)){if(/[@#]__PURE__/.test(a.value)){set_annotation(e,nn);break}if(/[@#]__INLINE__/.test(a.value)){set_annotation(e,rn);break}if(/[@#]__NOINLINE__/.test(a.value)){set_annotation(e,on);break}}}}var subscripts=function(e,t,n){var r=e.start;if(is("punc",".")){next();const i=is("privatename")?We:Xe;return subscripts(new i({start:r,expression:e,optional:false,property:as_name(),end:prev()}),t,n)}if(is("punc","[")){next();var i=expression(true);expect("]");return subscripts(new qe({start:r,expression:e,optional:false,property:i,end:prev()}),t,n)}if(t&&is("punc","(")){next();var o=new ze({start:r,expression:e,optional:false,args:call_args(),end:prev()});annotate(o);return subscripts(o,true,n)}if(is("punc","?.")){next();let n;if(t&&is("punc","(")){next();const t=new ze({start:r,optional:true,expression:e,args:call_args(),end:prev()});annotate(t);n=subscripts(t,true,true)}else if(is("name")||is("privatename")){const i=is("privatename")?We:Xe;n=subscripts(new i({start:r,expression:e,optional:true,property:as_name(),end:prev()}),t,true)}else if(is("punc","[")){next();const i=expression(true);expect("]");n=subscripts(new qe({start:r,expression:e,optional:true,property:i,end:prev()}),t,true)}if(!n)unexpected();if(n instanceof Ye)return n;return new Ye({start:r,expression:n,end:prev()})}if(is("template_head")){if(n){unexpected()}return subscripts(new _e({start:r,prefix:e,template_string:template_string(),end:prev()}),t)}return e};function call_args(){var e=[];while(!is("punc",")")){if(is("expand","...")){next();e.push(new oe({start:prev(),expression:expression(false),end:prev()}))}else{e.push(expression(false))}if(!is("punc",")")){expect(",")}}next();return e}var maybe_unary=function(e,t){var n=r.token;if(n.type=="name"&&n.value=="await"&&can_await()){next();return _await_expression()}if(is("operator")&&O.has(n.value)){next();handle_regexp();var i=make_unary($e,n,maybe_unary(e));i.start=n;i.end=prev();return i}var o=expr_atom(e,t);while(is("operator")&&M.has(r.token.value)&&!has_newline_before(r.token)){if(o instanceof le)unexpected();o=make_unary(Ze,r.token,o);o.start=n;o.end=r.token;next()}return o};function make_unary(e,t,n){var i=t.value;switch(i){case"++":case"--":if(!is_assignable(n))croak("Invalid use of "+i+" operator",t.line,t.col,t.pos);break;case"delete":if(n instanceof It&&r.input.has_directive("use strict"))croak("Calling delete on expression not allowed in strict mode",n.start.line,n.start.col,n.start.pos);break}return new e({operator:i,expression:n})}var expr_op=function(e,t,n){var i=is("operator")?r.token.value:null;if(i=="in"&&n)i=null;if(i=="**"&&e instanceof $e&&!is_token(e.start,"punc","(")&&e.operator!=="--"&&e.operator!=="++")unexpected(e.start);var o=i!=null?w[i]:null;if(o!=null&&(o>t||i==="**"&&t===o)){next();var a=expr_op(maybe_unary(true),o,n);return expr_op(new Qe({start:e.start,left:e,operator:i,right:a,end:a.end}),t,n)}return e};function expr_ops(e){return expr_op(maybe_unary(true,true),0,e)}var maybe_conditional=function(e){var t=r.token;var n=expr_ops(e);if(is("operator","?")){next();var i=expression(false);expect(":");return new Je({start:t,condition:n,consequent:i,alternative:expression(false,e),end:prev()})}return n};function is_assignable(e){return e instanceof He||e instanceof It}function to_destructuring(e){if(e instanceof rt){e=new fe({start:e.start,names:e.properties.map(to_destructuring),is_array:false,end:e.end})}else if(e instanceof nt){var t=[];for(var n=0;n=0;){o+="this."+t[a]+" = props."+t[a]+";"}const s=r&&Object.create(r.prototype);if(s&&s.initialize||n&&n.initialize)o+="this.initialize();";o+="}";o+="this.flags = 0;";o+="}";var u=new Function(o)();if(s){u.prototype=s;u.BASE=r}if(r)r.SUBCLASSES.push(u);u.prototype.CTOR=u;u.prototype.constructor=u;u.PROPS=t||null;u.SELF_PROPS=i;u.SUBCLASSES=[];if(e){u.prototype.TYPE=u.TYPE=e}if(n)for(a in n)if(HOP(n,a)){if(a[0]==="$"){u[a.substr(1)]=n[a]}else{u.prototype[a]=n[a]}}u.DEFMETHOD=function(e,t){this.prototype[e]=t};return u}const has_tok_flag=(e,t)=>Boolean(e.flags&t);const set_tok_flag=(e,t,n)=>{if(n){e.flags|=t}else{e.flags&=~t}};const P=1;const B=2;const L=4;class AST_Token{constructor(e,t,n,r,i,o,a,s,u){this.flags=o?1:0;this.type=e;this.value=t;this.line=n;this.col=r;this.pos=i;this.comments_before=a;this.comments_after=s;this.file=u;Object.seal(this)}get nlb(){return has_tok_flag(this,P)}set nlb(e){set_tok_flag(this,P,e)}get quote(){return!has_tok_flag(this,L)?"":has_tok_flag(this,B)?"'":'"'}set quote(e){set_tok_flag(this,B,e==="'");set_tok_flag(this,L,!!e)}}var V=DEFNODE("Node","start end",{_clone:function(e){if(e){var t=this.clone();return t.transform(new TreeTransformer((function(e){if(e!==t){return e.clone(true)}})))}return new this.CTOR(this)},clone:function(e){return this._clone(e)},$documentation:"Base class of all AST nodes",$propdoc:{start:"[AST_Token] The first token of this node",end:"[AST_Token] The last token of this node"},_walk:function(e){return e._visit(this)},walk:function(e){return this._walk(e)},_children_backwards:()=>{}},null);var U=DEFNODE("Statement",null,{$documentation:"Base class of all statements"});var z=DEFNODE("Debugger",null,{$documentation:"Represents a debugger statement"},U);var K=DEFNODE("Directive","value quote",{$documentation:'Represents a directive, like "use strict";',$propdoc:{value:"[string] The value of this directive as a plain string (it's not an AST_String!)",quote:"[string] the original quote character"}},U);var G=DEFNODE("SimpleStatement","body",{$documentation:"A statement consisting of an expression, i.e. a = 1 + 2",$propdoc:{body:"[AST_Node] an expression node (should not be instanceof AST_Statement)"},_walk:function(e){return e._visit(this,(function(){this.body._walk(e)}))},_children_backwards(e){e(this.body)}},U);function walk_body(e,t){const n=e.body;for(var r=0,i=n.length;r SymbolDef for all variables/functions defined in this scope",uses_with:"[boolean/S] tells whether this scope uses the `with` statement",uses_eval:"[boolean/S] tells whether this scope contains a direct call to the global `eval`",parent_scope:"[AST_Scope?/S] link to the parent scope",enclosed:"[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",cname:"[integer/S] current index for mangling variables (used internally by the mangler)"},get_defun_scope:function(){var e=this;while(e.is_block_scope()){e=e.parent_scope}return e},clone:function(e,t){var n=this._clone(e);if(e&&this.variables&&t&&!this._block_scope){n.figure_out_scope({},{toplevel:t,parent_scope:this.parent_scope})}else{if(this.variables)n.variables=new Map(this.variables);if(this.enclosed)n.enclosed=this.enclosed.slice();if(this._block_scope)n._block_scope=this._block_scope}return n},pinned:function(){return this.uses_eval||this.uses_with}},H);var ie=DEFNODE("Toplevel","globals",{$documentation:"The toplevel scope",$propdoc:{globals:"[Map/S] a map of name -> SymbolDef for all undeclared names"},wrap_commonjs:function(e){var t=this.body;var n="(function(exports){'$ORIG';})(typeof "+e+"=='undefined'?("+e+"={}):"+e+");";n=parse(n);n=n.transform(new TreeTransformer((function(e){if(e instanceof K&&e.value=="$ORIG"){return i.splice(t)}})));return n},wrap_enclose:function(e){if(typeof e!="string")e="";var t=e.indexOf(":");if(t<0)t=e.length;var n=this.body;return parse(["(function(",e.slice(0,t),'){"$ORIG"})(',e.slice(t+1),")"].join("")).transform(new TreeTransformer((function(e){if(e instanceof K&&e.value=="$ORIG"){return i.splice(n)}})))}},re);var oe=DEFNODE("Expansion","expression",{$documentation:"An expandible argument, such as ...rest, a splat, such as [1,2,...all], or an expansion in a variable declaration, such as var [first, ...rest] = list",$propdoc:{expression:"[AST_Node] the thing to be expanded"},_walk:function(e){return e._visit(this,(function(){this.expression.walk(e)}))},_children_backwards(e){e(this.expression)}});var ae=DEFNODE("Lambda","name argnames uses_arguments is_generator async",{$documentation:"Base class for functions",$propdoc:{name:"[AST_SymbolDeclaration?] the name of this function",argnames:"[AST_SymbolFunarg|AST_Destructuring|AST_Expansion|AST_DefaultAssign*] array of function arguments, destructurings, or expanding arguments",uses_arguments:"[boolean/S] tells whether this function accesses the arguments array",is_generator:"[boolean] is this a generator method",async:"[boolean] is this method async"},args_as_names:function(){var e=[];for(var t=0;t b)"},ae);var ce=DEFNODE("Defun",null,{$documentation:"A function definition"},ae);var fe=DEFNODE("Destructuring","names is_array",{$documentation:"A destructuring of several names. Used in destructuring assignment and with destructuring function argument names",$propdoc:{names:"[AST_Node*] Array of properties or elements",is_array:"[Boolean] Whether the destructuring represents an object or array"},_walk:function(e){return e._visit(this,(function(){this.names.forEach((function(t){t._walk(e)}))}))},_children_backwards(e){let t=this.names.length;while(t--)e(this.names[t])},all_symbols:function(){var e=[];this.walk(new TreeWalker((function(t){if(t instanceof Et){e.push(t)}})));return e}});var _e=DEFNODE("PrefixedTemplateString","template_string prefix",{$documentation:"A templatestring with a prefix, such as String.raw`foobarbaz`",$propdoc:{template_string:"[AST_TemplateString] The template string",prefix:"[AST_Node] The prefix, which will get called."},_walk:function(e){return e._visit(this,(function(){this.prefix._walk(e);this.template_string._walk(e)}))},_children_backwards(e){e(this.template_string);e(this.prefix)}});var pe=DEFNODE("TemplateString","segments",{$documentation:"A template string literal",$propdoc:{segments:"[AST_Node*] One or more segments, starting with AST_TemplateSegment. AST_Node may follow AST_TemplateSegment, but each AST_Node must be followed by AST_TemplateSegment."},_walk:function(e){return e._visit(this,(function(){this.segments.forEach((function(t){t._walk(e)}))}))},_children_backwards(e){let t=this.segments.length;while(t--)e(this.segments[t])}});var de=DEFNODE("TemplateSegment","value raw",{$documentation:"A segment of a template string literal",$propdoc:{value:"Content of the segment",raw:"Raw source of the segment"}});var me=DEFNODE("Jump",null,{$documentation:"Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"},U);var he=DEFNODE("Exit","value",{$documentation:"Base class for “exits” (`return` and `throw`)",$propdoc:{value:"[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"},_walk:function(e){return e._visit(this,this.value&&function(){this.value._walk(e)})},_children_backwards(e){if(this.value)e(this.value)}},me);var Ee=DEFNODE("Return",null,{$documentation:"A `return` statement"},he);var ge=DEFNODE("Throw",null,{$documentation:"A `throw` statement"},he);var ve=DEFNODE("LoopControl","label",{$documentation:"Base class for loop control statements (`break` and `continue`)",$propdoc:{label:"[AST_LabelRef?] the label, or null if none"},_walk:function(e){return e._visit(this,this.label&&function(){this.label._walk(e)})},_children_backwards(e){if(this.label)e(this.label)}},me);var De=DEFNODE("Break",null,{$documentation:"A `break` statement"},ve);var be=DEFNODE("Continue",null,{$documentation:"A `continue` statement"},ve);var Se=DEFNODE("Await","expression",{$documentation:"An `await` statement",$propdoc:{expression:"[AST_Node] the mandatory expression being awaited"},_walk:function(e){return e._visit(this,(function(){this.expression._walk(e)}))},_children_backwards(e){e(this.expression)}});var Ae=DEFNODE("Yield","expression is_star",{$documentation:"A `yield` statement",$propdoc:{expression:"[AST_Node?] the value returned or thrown by this statement; could be null (representing undefined) but only when is_star is set to false",is_star:"[Boolean] Whether this is a yield or yield* statement"},_walk:function(e){return e._visit(this,this.expression&&function(){this.expression._walk(e)})},_children_backwards(e){if(this.expression)e(this.expression)}});var ye=DEFNODE("If","condition alternative",{$documentation:"A `if` statement",$propdoc:{condition:"[AST_Node] the `if` condition",alternative:"[AST_Statement?] the `else` part, or null if not present"},_walk:function(e){return e._visit(this,(function(){this.condition._walk(e);this.body._walk(e);if(this.alternative)this.alternative._walk(e)}))},_children_backwards(e){if(this.alternative){e(this.alternative)}e(this.body);e(this.condition)}},q);var Te=DEFNODE("Switch","expression",{$documentation:"A `switch` statement",$propdoc:{expression:"[AST_Node] the `switch` “discriminant”"},_walk:function(e){return e._visit(this,(function(){this.expression._walk(e);walk_body(this,e)}))},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},H);var ke=DEFNODE("SwitchBranch",null,{$documentation:"Base class for `switch` branches"},H);var Ce=DEFNODE("Default",null,{$documentation:"A `default` switch branch"},ke);var Re=DEFNODE("Case","expression",{$documentation:"A `case` switch branch",$propdoc:{expression:"[AST_Node] the `case` expression"},_walk:function(e){return e._visit(this,(function(){this.expression._walk(e);walk_body(this,e)}))},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},ke);var Fe=DEFNODE("Try","bcatch bfinally",{$documentation:"A `try` statement",$propdoc:{bcatch:"[AST_Catch?] the catch block, or null if not present",bfinally:"[AST_Finally?] the finally block, or null if not present"},_walk:function(e){return e._visit(this,(function(){walk_body(this,e);if(this.bcatch)this.bcatch._walk(e);if(this.bfinally)this.bfinally._walk(e)}))},_children_backwards(e){if(this.bfinally)e(this.bfinally);if(this.bcatch)e(this.bcatch);let t=this.body.length;while(t--)e(this.body[t])}},H);var Oe=DEFNODE("Catch","argname",{$documentation:"A `catch` node; only makes sense as part of a `try` statement",$propdoc:{argname:"[AST_SymbolCatch|AST_Destructuring|AST_Expansion|AST_DefaultAssign] symbol for the exception"},_walk:function(e){return e._visit(this,(function(){if(this.argname)this.argname._walk(e);walk_body(this,e)}))},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);if(this.argname)e(this.argname)}},H);var Me=DEFNODE("Finally",null,{$documentation:"A `finally` node; only makes sense as part of a `try` statement"},H);var xe=DEFNODE("Definitions","definitions",{$documentation:"Base class for `var` or `const` nodes (variable declarations/initializations)",$propdoc:{definitions:"[AST_VarDef*] array of variable definitions"},_walk:function(e){return e._visit(this,(function(){var t=this.definitions;for(var n=0,r=t.length;n a`"},Qe);var nt=DEFNODE("Array","elements",{$documentation:"An array literal",$propdoc:{elements:"[AST_Node*] array of elements"},_walk:function(e){return e._visit(this,(function(){var t=this.elements;for(var n=0,r=t.length;nt._walk(e)))}))},_children_backwards(e){let t=this.properties.length;while(t--)e(this.properties[t]);if(this.extends)e(this.extends);if(this.name)e(this.name)}},re);var pt=DEFNODE("ClassProperty","static quote",{$documentation:"A class property",$propdoc:{static:"[boolean] whether this is a static key",quote:"[string] which quote is being used"},_walk:function(e){return e._visit(this,(function(){if(this.key instanceof V)this.key._walk(e);if(this.value instanceof V)this.value._walk(e)}))},_children_backwards(e){if(this.value instanceof V)e(this.value);if(this.key instanceof V)e(this.key)},computed_key(){return!(this.key instanceof Ct)}},it);var dt=DEFNODE("ClassProperty","",{$documentation:"A class property for a private property"},pt);var mt=DEFNODE("DefClass",null,{$documentation:"A class definition"},_t);var ht=DEFNODE("ClassExpression",null,{$documentation:"A class expression."},_t);var Et=DEFNODE("Symbol","scope name thedef",{$propdoc:{name:"[string] name of this symbol",scope:"[AST_Scope/S] the current scope (not necessarily the definition scope)",thedef:"[SymbolDef/S] the definition of this symbol"},$documentation:"Base class for all symbols"});var gt=DEFNODE("NewTarget",null,{$documentation:"A reference to new.target"});var vt=DEFNODE("SymbolDeclaration","init",{$documentation:"A declaration symbol (symbol in var/const, function name or argument, symbol in catch)"},Et);var Dt=DEFNODE("SymbolVar",null,{$documentation:"Symbol defining a variable"},vt);var bt=DEFNODE("SymbolBlockDeclaration",null,{$documentation:"Base class for block-scoped declaration symbols"},vt);var St=DEFNODE("SymbolConst",null,{$documentation:"A constant declaration"},bt);var At=DEFNODE("SymbolLet",null,{$documentation:"A block-scoped `let` declaration"},bt);var yt=DEFNODE("SymbolFunarg",null,{$documentation:"Symbol naming a function argument"},Dt);var Tt=DEFNODE("SymbolDefun",null,{$documentation:"Symbol defining a function"},vt);var kt=DEFNODE("SymbolMethod",null,{$documentation:"Symbol in an object defining a method"},Et);var Ct=DEFNODE("SymbolClassProperty",null,{$documentation:"Symbol for a class property"},Et);var Rt=DEFNODE("SymbolLambda",null,{$documentation:"Symbol naming a function expression"},vt);var Ft=DEFNODE("SymbolDefClass",null,{$documentation:"Symbol naming a class's name in a class declaration. Lexically scoped to its containing scope, and accessible within the class."},bt);var Ot=DEFNODE("SymbolClass",null,{$documentation:"Symbol naming a class's name. Lexically scoped to the class."},vt);var Mt=DEFNODE("SymbolCatch",null,{$documentation:"Symbol naming the exception in catch"},bt);var xt=DEFNODE("SymbolImport",null,{$documentation:"Symbol referring to an imported name"},bt);var Nt=DEFNODE("SymbolImportForeign",null,{$documentation:"A symbol imported from a module, but it is defined in the other module, and its real name is irrelevant for this module's purposes"},Et);var wt=DEFNODE("Label","references",{$documentation:"Symbol naming a label (declaration)",$propdoc:{references:"[AST_LoopControl*] a list of nodes referring to this label"},initialize:function(){this.references=[];this.thedef=this}},Et);var It=DEFNODE("SymbolRef",null,{$documentation:"Reference to some symbol (not definition/declaration)"},Et);var Pt=DEFNODE("SymbolExport",null,{$documentation:"Symbol referring to a name to export"},It);var Bt=DEFNODE("SymbolExportForeign",null,{$documentation:"A symbol exported from this module, but it is used in the other module, and its real name is irrelevant for this module's purposes"},Et);var Lt=DEFNODE("LabelRef",null,{$documentation:"Reference to a label symbol"},Et);var Vt=DEFNODE("This",null,{$documentation:"The `this` symbol"},Et);var Ut=DEFNODE("Super",null,{$documentation:"The `super` symbol"},Vt);var zt=DEFNODE("Constant",null,{$documentation:"Base class for all constants",getValue:function(){return this.value}});var Kt=DEFNODE("String","value quote",{$documentation:"A string literal",$propdoc:{value:"[string] the contents of this string",quote:"[string] the original quote character"}},zt);var Gt=DEFNODE("Number","value raw",{$documentation:"A number literal",$propdoc:{value:"[number] the numeric value",raw:"[string] numeric value as string"}},zt);var Ht=DEFNODE("BigInt","value",{$documentation:"A big int literal",$propdoc:{value:"[string] big int value"}},zt);var Xt=DEFNODE("RegExp","value",{$documentation:"A regexp literal",$propdoc:{value:"[RegExp] the actual regexp"}},zt);var Wt=DEFNODE("Atom",null,{$documentation:"Base class for atoms"},zt);var qt=DEFNODE("Null",null,{$documentation:"The `null` atom",value:null},Wt);var Yt=DEFNODE("NaN",null,{$documentation:"The impossible value",value:0/0},Wt);var jt=DEFNODE("Undefined",null,{$documentation:"The `undefined` value",value:function(){}()},Wt);var $t=DEFNODE("Hole",null,{$documentation:"A hole in an array",value:function(){}()},Wt);var Zt=DEFNODE("Infinity",null,{$documentation:"The `Infinity` value",value:1/0},Wt);var Qt=DEFNODE("Boolean",null,{$documentation:"Base class for booleans"},Wt);var Jt=DEFNODE("False",null,{$documentation:"The `false` atom",value:false},Qt);var en=DEFNODE("True",null,{$documentation:"The `true` atom",value:true},Qt);function walk(e,t,n=[e]){const r=n.push.bind(n);while(n.length){const e=n.pop();const i=t(e,n);if(i){if(i===tn)return true;continue}e._children_backwards(r)}return false}function walk_parent(e,t,n){const r=[e];const i=r.push.bind(r);const o=n?n.slice():[];const a=[];let s;const u={parent:(e=0)=>{if(e===-1){return s}if(n&&e>=o.length){e-=o.length;return n[n.length-(e+1)]}return o[o.length-(1+e)]}};while(r.length){s=r.pop();while(a.length&&r.length==a[a.length-1]){o.pop();a.pop()}const e=t(s,u);if(e){if(e===tn)return true;continue}const n=r.length;s._children_backwards(i);if(r.length>n){o.push(s);a.push(n-1)}}return false}const tn=Symbol("abort walk");class TreeWalker{constructor(e){this.visit=e;this.stack=[];this.directives=Object.create(null)}_visit(e,t){this.push(e);var n=this.visit(e,t?function(){t.call(e)}:noop);if(!n&&t){t.call(e)}this.pop();return n}parent(e){return this.stack[this.stack.length-2-(e||0)]}push(e){if(e instanceof ae){this.directives=Object.create(this.directives)}else if(e instanceof K&&!this.directives[e.value]){this.directives[e.value]=e}else if(e instanceof _t){this.directives=Object.create(this.directives);if(!this.directives["use strict"]){this.directives["use strict"]=e}}this.stack.push(e)}pop(){var e=this.stack.pop();if(e instanceof ae||e instanceof _t){this.directives=Object.getPrototypeOf(this.directives)}}self(){return this.stack[this.stack.length-1]}find_parent(e){var t=this.stack;for(var n=t.length;--n>=0;){var r=t[n];if(r instanceof e)return r}}has_directive(e){var t=this.directives[e];if(t)return t;var n=this.stack[this.stack.length-1];if(n instanceof re&&n.body){for(var r=0;r=0;){var r=t[n];if(r instanceof Y&&r.label.name==e.label.name)return r.body}else for(var n=t.length;--n>=0;){var r=t[n];if(r instanceof j||e instanceof De&&r instanceof Te)return r}}}class TreeTransformer extends TreeWalker{constructor(e,t){super();this.before=e;this.after=t}}const nn=1;const rn=2;const on=4;var an=Object.freeze({__proto__:null,AST_Accessor:se,AST_Array:nt,AST_Arrow:le,AST_Assign:et,AST_Atom:Wt,AST_Await:Se,AST_BigInt:Ht,AST_Binary:Qe,AST_Block:H,AST_BlockStatement:X,AST_Boolean:Qt,AST_Break:De,AST_Call:ze,AST_Case:Re,AST_Catch:Oe,AST_Chain:Ye,AST_Class:_t,AST_ClassExpression:ht,AST_ClassPrivateProperty:dt,AST_ClassProperty:pt,AST_ConciseMethod:ct,AST_Conditional:Je,AST_Const:Ie,AST_Constant:zt,AST_Continue:be,AST_Debugger:z,AST_Default:Ce,AST_DefaultAssign:tt,AST_DefClass:mt,AST_Definitions:xe,AST_Defun:ce,AST_Destructuring:fe,AST_Directive:K,AST_Do:Z,AST_Dot:Xe,AST_DotHash:We,AST_DWLoop:$,AST_EmptyStatement:W,AST_Exit:he,AST_Expansion:oe,AST_Export:Ue,AST_False:Jt,AST_Finally:Me,AST_For:J,AST_ForIn:ee,AST_ForOf:te,AST_Function:ue,AST_Hole:$t,AST_If:ye,AST_Import:Le,AST_ImportMeta:Ve,AST_Infinity:Zt,AST_IterationStatement:j,AST_Jump:me,AST_Label:wt,AST_LabeledStatement:Y,AST_LabelRef:Lt,AST_Lambda:ae,AST_Let:we,AST_LoopControl:ve,AST_NameMapping:Be,AST_NaN:Yt,AST_New:Ke,AST_NewTarget:gt,AST_Node:V,AST_Null:qt,AST_Number:Gt,AST_Object:rt,AST_ObjectGetter:lt,AST_ObjectKeyVal:ot,AST_ObjectProperty:it,AST_ObjectSetter:ut,AST_PrefixedTemplateString:_e,AST_PrivateGetter:st,AST_PrivateMethod:ft,AST_PrivateSetter:at,AST_PropAccess:He,AST_RegExp:Xt,AST_Return:Ee,AST_Scope:re,AST_Sequence:Ge,AST_SimpleStatement:G,AST_Statement:U,AST_StatementWithBody:q,AST_String:Kt,AST_Sub:qe,AST_Super:Ut,AST_Switch:Te,AST_SwitchBranch:ke,AST_Symbol:Et,AST_SymbolBlockDeclaration:bt,AST_SymbolCatch:Mt,AST_SymbolClass:Ot,AST_SymbolClassProperty:Ct,AST_SymbolConst:St,AST_SymbolDeclaration:vt,AST_SymbolDefClass:Ft,AST_SymbolDefun:Tt,AST_SymbolExport:Pt,AST_SymbolExportForeign:Bt,AST_SymbolFunarg:yt,AST_SymbolImport:xt,AST_SymbolImportForeign:Nt,AST_SymbolLambda:Rt,AST_SymbolLet:At,AST_SymbolMethod:kt,AST_SymbolRef:It,AST_SymbolVar:Dt,AST_TemplateSegment:de,AST_TemplateString:pe,AST_This:Vt,AST_Throw:ge,AST_Token:AST_Token,AST_Toplevel:ie,AST_True:en,AST_Try:Fe,AST_Unary:je,AST_UnaryPostfix:Ze,AST_UnaryPrefix:$e,AST_Undefined:jt,AST_Var:Ne,AST_VarDef:Pe,AST_While:Q,AST_With:ne,AST_Yield:Ae,TreeTransformer:TreeTransformer,TreeWalker:TreeWalker,walk:walk,walk_abort:tn,walk_body:walk_body,walk_parent:walk_parent,_INLINE:rn,_NOINLINE:on,_PURE:nn});function def_transform(e,t){e.DEFMETHOD("transform",(function(e,n){let r=undefined;e.push(this);if(e.before)r=e.before(this,t,n);if(r===undefined){r=this;t(r,e);if(e.after){const t=e.after(r,n);if(t!==undefined)r=t}}e.pop();return r}))}function do_list(e,t){return i(e,(function(e){return e.transform(t,true)}))}def_transform(V,noop);def_transform(Y,(function(e,t){e.label=e.label.transform(t);e.body=e.body.transform(t)}));def_transform(G,(function(e,t){e.body=e.body.transform(t)}));def_transform(H,(function(e,t){e.body=do_list(e.body,t)}));def_transform(Z,(function(e,t){e.body=e.body.transform(t);e.condition=e.condition.transform(t)}));def_transform(Q,(function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t)}));def_transform(J,(function(e,t){if(e.init)e.init=e.init.transform(t);if(e.condition)e.condition=e.condition.transform(t);if(e.step)e.step=e.step.transform(t);e.body=e.body.transform(t)}));def_transform(ee,(function(e,t){e.init=e.init.transform(t);e.object=e.object.transform(t);e.body=e.body.transform(t)}));def_transform(ne,(function(e,t){e.expression=e.expression.transform(t);e.body=e.body.transform(t)}));def_transform(he,(function(e,t){if(e.value)e.value=e.value.transform(t)}));def_transform(ve,(function(e,t){if(e.label)e.label=e.label.transform(t)}));def_transform(ye,(function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t);if(e.alternative)e.alternative=e.alternative.transform(t)}));def_transform(Te,(function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)}));def_transform(Re,(function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)}));def_transform(Fe,(function(e,t){e.body=do_list(e.body,t);if(e.bcatch)e.bcatch=e.bcatch.transform(t);if(e.bfinally)e.bfinally=e.bfinally.transform(t)}));def_transform(Oe,(function(e,t){if(e.argname)e.argname=e.argname.transform(t);e.body=do_list(e.body,t)}));def_transform(xe,(function(e,t){e.definitions=do_list(e.definitions,t)}));def_transform(Pe,(function(e,t){e.name=e.name.transform(t);if(e.value)e.value=e.value.transform(t)}));def_transform(fe,(function(e,t){e.names=do_list(e.names,t)}));def_transform(ae,(function(e,t){if(e.name)e.name=e.name.transform(t);e.argnames=do_list(e.argnames,t);if(e.body instanceof V){e.body=e.body.transform(t)}else{e.body=do_list(e.body,t)}}));def_transform(ze,(function(e,t){e.expression=e.expression.transform(t);e.args=do_list(e.args,t)}));def_transform(Ge,(function(e,t){const n=do_list(e.expressions,t);e.expressions=n.length?n:[new Gt({value:0})]}));def_transform(Xe,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(qe,(function(e,t){e.expression=e.expression.transform(t);e.property=e.property.transform(t)}));def_transform(Ye,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(Ae,(function(e,t){if(e.expression)e.expression=e.expression.transform(t)}));def_transform(Se,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(je,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(Qe,(function(e,t){e.left=e.left.transform(t);e.right=e.right.transform(t)}));def_transform(Je,(function(e,t){e.condition=e.condition.transform(t);e.consequent=e.consequent.transform(t);e.alternative=e.alternative.transform(t)}));def_transform(nt,(function(e,t){e.elements=do_list(e.elements,t)}));def_transform(rt,(function(e,t){e.properties=do_list(e.properties,t)}));def_transform(it,(function(e,t){if(e.key instanceof V){e.key=e.key.transform(t)}if(e.value)e.value=e.value.transform(t)}));def_transform(_t,(function(e,t){if(e.name)e.name=e.name.transform(t);if(e.extends)e.extends=e.extends.transform(t);e.properties=do_list(e.properties,t)}));def_transform(oe,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(Be,(function(e,t){e.foreign_name=e.foreign_name.transform(t);e.name=e.name.transform(t)}));def_transform(Le,(function(e,t){if(e.imported_name)e.imported_name=e.imported_name.transform(t);if(e.imported_names)do_list(e.imported_names,t);e.module_name=e.module_name.transform(t)}));def_transform(Ue,(function(e,t){if(e.exported_definition)e.exported_definition=e.exported_definition.transform(t);if(e.exported_value)e.exported_value=e.exported_value.transform(t);if(e.exported_names)do_list(e.exported_names,t);if(e.module_name)e.module_name=e.module_name.transform(t)}));def_transform(pe,(function(e,t){e.segments=do_list(e.segments,t)}));def_transform(_e,(function(e,t){e.prefix=e.prefix.transform(t);e.template_string=e.template_string.transform(t)}));(function(){var normalize_directives=function(e){var t=true;for(var n=0;n1||e.guardedHandlers&&e.guardedHandlers.length){throw new Error("Multiple catch clauses are not supported.")}return new Fe({start:my_start_token(e),end:my_end_token(e),body:from_moz(e.block).body,bcatch:from_moz(t[0]),bfinally:e.finalizer?new Me(from_moz(e.finalizer)):null})},Property:function(e){var t=e.key;var n={start:my_start_token(t||e.value),end:my_end_token(e.value),key:t.type=="Identifier"?t.name:t.value,value:from_moz(e.value)};if(e.computed){n.key=from_moz(e.key)}if(e.method){n.is_generator=e.value.generator;n.async=e.value.async;if(!e.computed){n.key=new kt({name:n.key})}else{n.key=from_moz(e.key)}return new ct(n)}if(e.kind=="init"){if(t.type!="Identifier"&&t.type!="Literal"){n.key=from_moz(t)}return new ot(n)}if(typeof n.key==="string"||typeof n.key==="number"){n.key=new kt({name:n.key})}n.value=new se(n.value);if(e.kind=="get")return new lt(n);if(e.kind=="set")return new ut(n);if(e.kind=="method"){n.async=e.value.async;n.is_generator=e.value.generator;n.quote=e.computed?'"':null;return new ct(n)}},MethodDefinition:function(e){var t={start:my_start_token(e),end:my_end_token(e),key:e.computed?from_moz(e.key):new kt({name:e.key.name||e.key.value}),value:from_moz(e.value),static:e.static};if(e.kind=="get"){return new lt(t)}if(e.kind=="set"){return new ut(t)}t.is_generator=e.value.generator;t.async=e.value.async;return new ct(t)},FieldDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in FieldDefinition");t=from_moz(e.key)}return new pt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},PropertyDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in PropertyDefinition");t=from_moz(e.key)}return new pt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},ArrayExpression:function(e){return new nt({start:my_start_token(e),end:my_end_token(e),elements:e.elements.map((function(e){return e===null?new $t:from_moz(e)}))})},ObjectExpression:function(e){return new rt({start:my_start_token(e),end:my_end_token(e),properties:e.properties.map((function(e){if(e.type==="SpreadElement"){return from_moz(e)}e.type="Property";return from_moz(e)}))})},SequenceExpression:function(e){return new Ge({start:my_start_token(e),end:my_end_token(e),expressions:e.expressions.map(from_moz)})},MemberExpression:function(e){return new(e.computed?qe:Xe)({start:my_start_token(e),end:my_end_token(e),property:e.computed?from_moz(e.property):e.property.name,expression:from_moz(e.object),optional:e.optional||false})},ChainExpression:function(e){return new Ye({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.expression)})},SwitchCase:function(e){return new(e.test?Re:Ce)({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.test),body:e.consequent.map(from_moz)})},VariableDeclaration:function(e){return new(e.kind==="const"?Ie:e.kind==="let"?we:Ne)({start:my_start_token(e),end:my_end_token(e),definitions:e.declarations.map(from_moz)})},ImportDeclaration:function(e){var t=null;var n=null;e.specifiers.forEach((function(e){if(e.type==="ImportSpecifier"){if(!n){n=[]}n.push(new Be({start:my_start_token(e),end:my_end_token(e),foreign_name:from_moz(e.imported),name:from_moz(e.local)}))}else if(e.type==="ImportDefaultSpecifier"){t=from_moz(e.local)}else if(e.type==="ImportNamespaceSpecifier"){if(!n){n=[]}n.push(new Be({start:my_start_token(e),end:my_end_token(e),foreign_name:new Nt({name:"*"}),name:from_moz(e.local)}))}}));return new Le({start:my_start_token(e),end:my_end_token(e),imported_name:t,imported_names:n,module_name:from_moz(e.source)})},ExportAllDeclaration:function(e){return new Ue({start:my_start_token(e),end:my_end_token(e),exported_names:[new Be({name:new Bt({name:"*"}),foreign_name:new Bt({name:"*"})})],module_name:from_moz(e.source)})},ExportNamedDeclaration:function(e){return new Ue({start:my_start_token(e),end:my_end_token(e),exported_definition:from_moz(e.declaration),exported_names:e.specifiers&&e.specifiers.length?e.specifiers.map((function(e){return new Be({foreign_name:from_moz(e.exported),name:from_moz(e.local)})})):null,module_name:from_moz(e.source)})},ExportDefaultDeclaration:function(e){return new Ue({start:my_start_token(e),end:my_end_token(e),exported_value:from_moz(e.declaration),is_default:true})},Literal:function(e){var t=e.value,n={start:my_start_token(e),end:my_end_token(e)};var r=e.regex;if(r&&r.pattern){n.value={source:r.pattern,flags:r.flags};return new Xt(n)}else if(r){const r=e.raw||t;const i=r.match(/^\/(.*)\/(\w*)$/);if(!i)throw new Error("Invalid regex source "+r);const[o,a,s]=i;n.value={source:a,flags:s};return new Xt(n)}if(t===null)return new qt(n);switch(typeof t){case"string":n.value=t;return new Kt(n);case"number":n.value=t;n.raw=e.raw||t.toString();return new Gt(n);case"boolean":return new(t?en:Jt)(n)}},MetaProperty:function(e){if(e.meta.name==="new"&&e.property.name==="target"){return new gt({start:my_start_token(e),end:my_end_token(e)})}else if(e.meta.name==="import"&&e.property.name==="meta"){return new Ve({start:my_start_token(e),end:my_end_token(e)})}},Identifier:function(e){var n=t[t.length-2];return new(n.type=="LabeledStatement"?wt:n.type=="VariableDeclarator"&&n.id===e?n.kind=="const"?St:n.kind=="let"?At:Dt:/Import.*Specifier/.test(n.type)?n.local===e?xt:Nt:n.type=="ExportSpecifier"?n.local===e?Pt:Bt:n.type=="FunctionExpression"?n.id===e?Rt:yt:n.type=="FunctionDeclaration"?n.id===e?Tt:yt:n.type=="ArrowFunctionExpression"?n.params.includes(e)?yt:It:n.type=="ClassExpression"?n.id===e?Ot:It:n.type=="Property"?n.key===e&&n.computed||n.value===e?It:kt:n.type=="PropertyDefinition"||n.type==="FieldDefinition"?n.key===e&&n.computed||n.value===e?It:Ct:n.type=="ClassDeclaration"?n.id===e?Ft:It:n.type=="MethodDefinition"?n.computed?It:kt:n.type=="CatchClause"?Mt:n.type=="BreakStatement"||n.type=="ContinueStatement"?Lt:It)({start:my_start_token(e),end:my_end_token(e),name:e.name})},BigIntLiteral(e){return new Ht({start:my_start_token(e),end:my_end_token(e),value:e.value})}};e.UpdateExpression=e.UnaryExpression=function To_Moz_Unary(e){var t="prefix"in e?e.prefix:e.type=="UnaryExpression"?true:false;return new(t?$e:Ze)({start:my_start_token(e),end:my_end_token(e),operator:e.operator,expression:from_moz(e.argument)})};e.ClassDeclaration=e.ClassExpression=function From_Moz_Class(e){return new(e.type==="ClassDeclaration"?mt:ht)({start:my_start_token(e),end:my_end_token(e),name:from_moz(e.id),extends:from_moz(e.superClass),properties:e.body.body.map(from_moz)})};map("EmptyStatement",W);map("BlockStatement",X,"body@body");map("IfStatement",ye,"test>condition, consequent>body, alternate>alternative");map("LabeledStatement",Y,"label>label, body>body");map("BreakStatement",De,"label>label");map("ContinueStatement",be,"label>label");map("WithStatement",ne,"object>expression, body>body");map("SwitchStatement",Te,"discriminant>expression, cases@body");map("ReturnStatement",Ee,"argument>value");map("ThrowStatement",ge,"argument>value");map("WhileStatement",Q,"test>condition, body>body");map("DoWhileStatement",Z,"test>condition, body>body");map("ForStatement",J,"init>init, test>condition, update>step, body>body");map("ForInStatement",ee,"left>init, right>object, body>body");map("ForOfStatement",te,"left>init, right>object, body>body, await=await");map("AwaitExpression",Se,"argument>expression");map("YieldExpression",Ae,"argument>expression, delegate=is_star");map("DebuggerStatement",z);map("VariableDeclarator",Pe,"id>name, init>value");map("CatchClause",Oe,"param>argname, body%body");map("ThisExpression",Vt);map("Super",Ut);map("BinaryExpression",Qe,"operator=operator, left>left, right>right");map("LogicalExpression",Qe,"operator=operator, left>left, right>right");map("AssignmentExpression",et,"operator=operator, left>left, right>right");map("ConditionalExpression",Je,"test>condition, consequent>consequent, alternate>alternative");map("NewExpression",Ke,"callee>expression, arguments@args");map("CallExpression",ze,"callee>expression, optional=optional, arguments@args");def_to_moz(ie,(function To_Moz_Program(e){return to_moz_scope("Program",e)}));def_to_moz(oe,(function To_Moz_Spread(e){return{type:to_moz_in_destructuring()?"RestElement":"SpreadElement",argument:to_moz(e.expression)}}));def_to_moz(_e,(function To_Moz_TaggedTemplateExpression(e){return{type:"TaggedTemplateExpression",tag:to_moz(e.prefix),quasi:to_moz(e.template_string)}}));def_to_moz(pe,(function To_Moz_TemplateLiteral(e){var t=[];var n=[];for(var r=0;r({type:"BigIntLiteral",value:e.value})));Qt.DEFMETHOD("to_mozilla_ast",zt.prototype.to_mozilla_ast);qt.DEFMETHOD("to_mozilla_ast",zt.prototype.to_mozilla_ast);$t.DEFMETHOD("to_mozilla_ast",(function To_Moz_ArrayHole(){return null}));H.DEFMETHOD("to_mozilla_ast",X.prototype.to_mozilla_ast);ae.DEFMETHOD("to_mozilla_ast",ue.prototype.to_mozilla_ast);function my_start_token(e){var t=e.loc,n=t&&t.start;var r=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,r?r[0]:e.start,false,[],[],t&&t.source)}function my_end_token(e){var t=e.loc,n=t&&t.end;var r=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,r?r[0]:e.end,false,[],[],t&&t.source)}function map(t,n,r){var i="function From_Moz_"+t+"(M){\n";i+="return new U2."+n.name+"({\n"+"start: my_start_token(M),\n"+"end: my_end_token(M)";var o="function To_Moz_"+t+"(M){\n";o+="return {\n"+"type: "+JSON.stringify(t);if(r)r.split(/\s*,\s*/).forEach((function(e){var t=/([a-z0-9$_]+)([=@>%])([a-z0-9$_]+)/i.exec(e);if(!t)throw new Error("Can't understand property map: "+e);var n=t[1],r=t[2],a=t[3];i+=",\n"+a+": ";o+=",\n"+n+": ";switch(r){case"@":i+="M."+n+".map(from_moz)";o+="M."+a+".map(to_moz)";break;case">":i+="from_moz(M."+n+")";o+="to_moz(M."+a+")";break;case"=":i+="M."+n;o+="M."+a;break;case"%":i+="from_moz(M."+n+").body";o+="to_moz_block(M)";break;default:throw new Error("Can't understand operator in propmap: "+e)}}));i+="\n})\n}";o+="\n}\n}";i=new Function("U2","my_start_token","my_end_token","from_moz","return("+i+")")(an,my_start_token,my_end_token,from_moz);o=new Function("to_moz","to_moz_block","to_moz_scope","return("+o+")")(to_moz,to_moz_block,to_moz_scope);e[t]=i;def_to_moz(n,o)}var t=null;function from_moz(n){t.push(n);var r=n!=null?e[n.type](n):null;t.pop();return r}V.from_mozilla_ast=function(e){var n=t;t=[];var r=from_moz(e);t=n;return r};function set_moz_loc(e,t){var n=e.start;var r=e.end;if(!(n&&r)){return t}if(n.pos!=null&&r.endpos!=null){t.range=[n.pos,r.endpos]}if(n.line){t.loc={start:{line:n.line,column:n.col},end:r.endline?{line:r.endline,column:r.endcol}:null};if(n.file){t.loc.source=n.file}}return t}function def_to_moz(e,t){e.DEFMETHOD("to_mozilla_ast",(function(e){return set_moz_loc(this,t(this,e))}))}var n=null;function to_moz(e){if(n===null){n=[]}n.push(e);var t=e!=null?e.to_mozilla_ast(n[n.length-2]):null;n.pop();if(n.length===0){n=null}return t}function to_moz_in_destructuring(){var e=n.length;while(e--){if(n[e]instanceof fe){return true}}return false}function to_moz_block(e){return{type:"BlockStatement",body:e.body.map(to_moz)}}function to_moz_scope(e,t){var n=t.body.map(to_moz);if(t.body[0]instanceof G&&t.body[0].body instanceof Kt){n.unshift(to_moz(new W(t.body[0])))}return{type:e,body:n}}})();function first_in_statement(e){let t=e.parent(-1);for(let n=0,r;r=e.parent(n);n++){if(r instanceof U&&r.body===t)return true;if(r instanceof Ge&&r.expressions[0]===t||r.TYPE==="Call"&&r.expression===t||r instanceof _e&&r.prefix===t||r instanceof Xe&&r.expression===t||r instanceof qe&&r.expression===t||r instanceof Je&&r.condition===t||r instanceof Qe&&r.left===t||r instanceof Ze&&r.expression===t){t=r}else{return false}}}function left_is_object(e){if(e instanceof rt)return true;if(e instanceof Ge)return left_is_object(e.expressions[0]);if(e.TYPE==="Call")return left_is_object(e.expression);if(e instanceof _e)return left_is_object(e.prefix);if(e instanceof Xe||e instanceof qe)return left_is_object(e.expression);if(e instanceof Je)return left_is_object(e.condition);if(e instanceof Qe)return left_is_object(e.left);if(e instanceof Ze)return left_is_object(e.expression);return false}const sn=/^$|[;{][\s\n]*$/;const un=10;const ln=32;const cn=/[@#]__(PURE|INLINE|NOINLINE)__/g;function is_some_comments(e){return(e.type==="comment2"||e.type==="comment1")&&/@preserve|@lic|@cc_on|^\**!/i.test(e.value)}function OutputStream(e){var t=!e;e=defaults(e,{ascii_only:false,beautify:false,braces:false,comments:"some",ecma:5,ie8:false,indent_level:4,indent_start:0,inline_script:true,keep_numbers:false,keep_quoted_props:false,max_line_len:false,preamble:null,preserve_annotations:false,quote_keys:false,quote_style:0,safari10:false,semicolons:true,shebang:true,shorthand:undefined,source_map:null,webkit:false,width:80,wrap_iife:false,wrap_func_args:true},true);if(e.shorthand===undefined)e.shorthand=e.ecma>5;var n=return_false;if(e.comments){let t=e.comments;if(typeof e.comments==="string"&&/^\/.*\/[a-zA-Z]*$/.test(e.comments)){var r=e.comments.lastIndexOf("/");t=new RegExp(e.comments.substr(1,r-1),e.comments.substr(r+1))}if(t instanceof RegExp){n=function(e){return e.type!="comment5"&&t.test(e.value)}}else if(typeof t==="function"){n=function(e){return e.type!="comment5"&&t(this,e)}}else if(t==="some"){n=is_some_comments}else{n=return_true}}var i=0;var o=0;var a=1;var s=0;var u="";let l=new Set;var c=e.ascii_only?function(t,n){if(e.ecma>=2015&&!e.safari10){t=t.replace(/[\ud800-\udbff][\udc00-\udfff]/g,(function(e){var t=get_full_char_code(e,0).toString(16);return"\\u{"+t+"}"}))}return t.replace(/[\u0000-\u001f\u007f-\uffff]/g,(function(e){var t=e.charCodeAt(0).toString(16);if(t.length<=2&&!n){while(t.length<2)t="0"+t;return"\\x"+t}else{while(t.length<4)t="0"+t;return"\\u"+t}}))}:function(e){return e.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g,(function(e,t){if(t){return"\\u"+t.charCodeAt(0).toString(16)}return e}))};function make_string(t,n){var r=0,i=0;t=t.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,(function(n,o){switch(n){case'"':++r;return'"';case"'":++i;return"'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\t":return"\\t";case"\b":return"\\b";case"\f":return"\\f";case"\v":return e.ie8?"\\x0B":"\\v";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";case"\ufeff":return"\\ufeff";case"\0":return/[0-9]/.test(get_full_char(t,o+1))?"\\x00":"\\0"}return n}));function quote_single(){return"'"+t.replace(/\x27/g,"\\'")+"'"}function quote_double(){return'"'+t.replace(/\x22/g,'\\"')+'"'}function quote_template(){return"`"+t.replace(/`/g,"\\`")+"`"}t=c(t);if(n==="`")return quote_template();switch(e.quote_style){case 1:return quote_single();case 2:return quote_double();case 3:return n=="'"?quote_single():quote_double();default:return r>i?quote_single():quote_double()}}function encode_string(t,n){var r=make_string(t,n);if(e.inline_script){r=r.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi,"<\\/$1$2");r=r.replace(/\x3c!--/g,"\\x3c!--");r=r.replace(/--\x3e/g,"--\\x3e")}return r}function make_name(e){e=e.toString();e=c(e,true);return e}function make_indent(t){return" ".repeat(e.indent_start+i-t*e.indent_level)}var f=false;var _=false;var p=false;var d=0;var m=false;var h=false;var E=-1;var g="";var v,D,b=e.source_map&&[];var S=b?function(){b.forEach((function(t){try{let n=!t.name&&t.token.type=="name"?t.token.value:t.name;if(n instanceof Et){n=n.name}e.source_map.add(t.token.file,t.line,t.col,t.token.line,t.token.col,is_basic_identifier_string(n)?n:undefined)}catch(e){}}));b=[]}:noop;var A=e.max_line_len?function(){if(o>e.max_line_len){if(d){var t=u.slice(0,d);var n=u.slice(d);if(b){var r=n.length-o;b.forEach((function(e){e.line++;e.col+=r}))}u=t+"\n"+n;a++;s++;o=n.length}}if(d){d=0;S()}}:noop;var y=makePredicate("( [ + * / - , . `");function print(t){t=String(t);var n=get_full_char(t,0);if(m&&n){m=false;if(n!=="\n"){print("\n");k()}}if(h&&n){h=false;if(!/[\s;})]/.test(n)){T()}}E=-1;var r=g.charAt(g.length-1);if(p){p=false;if(r===":"&&n==="}"||(!n||!";}".includes(n))&&r!==";"){if(e.semicolons||y.has(n)){u+=";";o++;s++}else{A();if(o>0){u+="\n";s++;a++;o=0}if(/^\s+$/.test(t)){p=true}}if(!e.beautify)_=false}}if(_){if(is_identifier_char(r)&&(is_identifier_char(n)||n=="\\")||n=="/"&&n==r||(n=="+"||n=="-")&&n==g){u+=" ";o++;s++}_=false}if(v){b.push({token:v,name:D,line:a,col:o});v=false;if(!d)S()}u+=t;f=t[t.length-1]=="(";s+=t.length;var i=t.split(/\r?\n/),l=i.length-1;a+=l;o+=i[0].length;if(l>0){A();o=i[l].length}g=t}var star=function(){print("*")};var T=e.beautify?function(){print(" ")}:function(){_=true};var k=e.beautify?function(t){if(e.beautify){print(make_indent(t?.5:0))}}:noop;var C=e.beautify?function(e,t){if(e===true)e=next_indent();var n=i;i=e;var r=t();i=n;return r}:function(e,t){return t()};var R=e.beautify?function(){if(E<0)return print("\n");if(u[E]!="\n"){u=u.slice(0,E)+"\n"+u.slice(E);s++;a++}E++}:e.max_line_len?function(){A();d=u.length}:noop;var F=e.beautify?function(){print(";")}:function(){p=true};function force_semicolon(){p=false;print(";")}function next_indent(){return i+e.indent_level}function with_block(e){var t;print("{");R();C(next_indent(),(function(){t=e()}));k();print("}");return t}function with_parens(e){print("(");var t=e();print(")");return t}function with_square(e){print("[");var t=e();print("]");return t}function comma(){print(",");T()}function colon(){print(":");T()}var O=b?function(e,t){v=e;D=t}:noop;function get(){if(d){A()}return u}function has_nlb(){let e=u.length-1;while(e>=0){const t=u.charCodeAt(e);if(t===un){return true}if(t!==ln){return false}e--}return true}function filter_comment(t){if(!e.preserve_annotations){t=t.replace(cn," ")}if(/^\s*$/.test(t)){return""}return t.replace(/(<\s*\/\s*)(script)/i,"<\\/$2")}function prepend_comments(t){var r=this;var i=t.start;if(!i)return;var o=r.printed_comments;const a=t instanceof he&&t.value;if(i.comments_before&&o.has(i.comments_before)){if(a){i.comments_before=[]}else{return}}var u=i.comments_before;if(!u){u=i.comments_before=[]}o.add(u);if(a){var l=new TreeWalker((function(e){var t=l.parent();if(t instanceof he||t instanceof Qe&&t.left===e||t.TYPE=="Call"&&t.expression===e||t instanceof Je&&t.condition===e||t instanceof Xe&&t.expression===e||t instanceof Ge&&t.expressions[0]===e||t instanceof qe&&t.expression===e||t instanceof Ze){if(!e.start)return;var n=e.start.comments_before;if(n&&!o.has(n)){o.add(n);u=u.concat(n)}}else{return true}}));l.push(t);t.value.walk(l)}if(s==0){if(u.length>0&&e.shebang&&u[0].type==="comment5"&&!o.has(u[0])){print("#!"+u.shift().value+"\n");k()}var c=e.preamble;if(c){print(c.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g,"\n"))}}u=u.filter(n,t).filter((e=>!o.has(e)));if(u.length==0)return;var f=has_nlb();u.forEach((function(e,t){o.add(e);if(!f){if(e.nlb){print("\n");k();f=true}else if(t>0){T()}}if(/comment[134]/.test(e.type)){var n=filter_comment(e.value);if(n){print("//"+n+"\n");k()}f=true}else if(e.type=="comment2"){var n=filter_comment(e.value);if(n){print("/*"+n+"*/")}f=false}}));if(!f){if(i.nlb){print("\n");k()}else{T()}}}function append_comments(e,t){var r=this;var i=e.end;if(!i)return;var o=r.printed_comments;var a=i[t?"comments_before":"comments_after"];if(!a||o.has(a))return;if(!(e instanceof U||a.every((e=>!/comment[134]/.test(e.type)))))return;o.add(a);var s=u.length;a.filter(n,e).forEach((function(e,n){if(o.has(e))return;o.add(e);h=false;if(m){print("\n");k();m=false}else if(e.nlb&&(n>0||!has_nlb())){print("\n");k()}else if(n>0||!t){T()}if(/comment[134]/.test(e.type)){const t=filter_comment(e.value);if(t){print("//"+t)}m=true}else if(e.type=="comment2"){const t=filter_comment(e.value);if(t){print("/*"+t+"*/")}h=true}}));if(u.length>s)E=s}var M=[];return{get:get,toString:get,indent:k,in_directive:false,use_asm:null,active_scope:null,indentation:function(){return i},current_width:function(){return o-i},should_break:function(){return e.width&&this.current_width()>=e.width},has_parens:function(){return f},newline:R,print:print,star:star,space:T,comma:comma,colon:colon,last:function(){return g},semicolon:F,force_semicolon:force_semicolon,to_utf8:c,print_name:function(e){print(make_name(e))},print_string:function(e,t,n){var r=encode_string(e,t);if(n===true&&!r.includes("\\")){if(!sn.test(u)){force_semicolon()}force_semicolon()}print(r)},print_template_string_chars:function(e){var t=encode_string(e,"`").replace(/\${/g,"\\${");return print(t.substr(1,t.length-2))},encode_string:encode_string,next_indent:next_indent,with_indent:C,with_block:with_block,with_parens:with_parens,with_square:with_square,add_mapping:O,option:function(t){return e[t]},printed_comments:l,prepend_comments:t?noop:prepend_comments,append_comments:t||n===return_false?noop:append_comments,line:function(){return a},col:function(){return o},pos:function(){return s},push_node:function(e){M.push(e)},pop_node:function(){return M.pop()},parent:function(e){return M[M.length-2-(e||0)]}}}(function(){function DEFPRINT(e,t){e.DEFMETHOD("_codegen",t)}V.DEFMETHOD("print",(function(e,t){var n=this,r=n._codegen;if(n instanceof re){e.active_scope=n}else if(!e.use_asm&&n instanceof K&&n.value=="use asm"){e.use_asm=e.active_scope}function doit(){e.prepend_comments(n);n.add_source_map(e);r(n,e);e.append_comments(n)}e.push_node(n);if(t||n.needs_parens(e)){e.with_parens(doit)}else{doit()}e.pop_node();if(n===e.use_asm){e.use_asm=null}}));V.DEFMETHOD("_print",V.prototype.print);V.DEFMETHOD("print_to_string",(function(e){var t=OutputStream(e);this.print(t);return t.get()}));function PARENS(e,t){if(Array.isArray(e)){e.forEach((function(e){PARENS(e,t)}))}else{e.DEFMETHOD("needs_parens",t)}}PARENS(V,return_false);PARENS(ue,(function(e){if(!e.has_parens()&&first_in_statement(e)){return true}if(e.option("webkit")){var t=e.parent();if(t instanceof He&&t.expression===this){return true}}if(e.option("wrap_iife")){var t=e.parent();if(t instanceof ze&&t.expression===this){return true}}if(e.option("wrap_func_args")){var t=e.parent();if(t instanceof ze&&t.args.includes(this)){return true}}return false}));PARENS(le,(function(e){var t=e.parent();if(e.option("wrap_func_args")&&t instanceof ze&&t.args.includes(this)){return true}return t instanceof He&&t.expression===this}));PARENS(rt,(function(e){return!e.has_parens()&&first_in_statement(e)}));PARENS(ht,first_in_statement);PARENS(je,(function(e){var t=e.parent();return t instanceof He&&t.expression===this||t instanceof ze&&t.expression===this||t instanceof Qe&&t.operator==="**"&&this instanceof $e&&t.left===this&&this.operator!=="++"&&this.operator!=="--"}));PARENS(Se,(function(e){var t=e.parent();return t instanceof He&&t.expression===this||t instanceof ze&&t.expression===this||t instanceof Qe&&t.operator==="**"&&t.left===this||e.option("safari10")&&t instanceof $e}));PARENS(Ge,(function(e){var t=e.parent();return t instanceof ze||t instanceof je||t instanceof Qe||t instanceof Pe||t instanceof He||t instanceof nt||t instanceof it||t instanceof Je||t instanceof le||t instanceof tt||t instanceof oe||t instanceof te&&this===t.object||t instanceof Ae||t instanceof Ue}));PARENS(Qe,(function(e){var t=e.parent();if(t instanceof ze&&t.expression===this)return true;if(t instanceof je)return true;if(t instanceof He&&t.expression===this)return true;if(t instanceof Qe){const e=t.operator;const n=this.operator;if(n==="??"&&(e==="||"||e==="&&")){return true}if(e==="??"&&(n==="||"||n==="&&")){return true}const r=w[e];const i=w[n];if(r>i||r==i&&(this===t.right||e=="**")){return true}}}));PARENS(Ae,(function(e){var t=e.parent();if(t instanceof Qe&&t.operator!=="=")return true;if(t instanceof ze&&t.expression===this)return true;if(t instanceof Je&&t.condition===this)return true;if(t instanceof je)return true;if(t instanceof He&&t.expression===this)return true}));PARENS(He,(function(e){var t=e.parent();if(t instanceof Ke&&t.expression===this){return walk(this,(e=>{if(e instanceof re)return true;if(e instanceof ze){return tn}}))}}));PARENS(ze,(function(e){var t=e.parent(),n;if(t instanceof Ke&&t.expression===this||t instanceof Ue&&t.is_default&&this.expression instanceof ue)return true;return this.expression instanceof ue&&t instanceof He&&t.expression===this&&(n=e.parent(1))instanceof et&&n.left===t}));PARENS(Ke,(function(e){var t=e.parent();if(this.args.length===0&&(t instanceof He||t instanceof ze&&t.expression===this))return true}));PARENS(Gt,(function(e){var t=e.parent();if(t instanceof He&&t.expression===this){var n=this.getValue();if(n<0||/^0/.test(make_num(n))){return true}}}));PARENS(Ht,(function(e){var t=e.parent();if(t instanceof He&&t.expression===this){var n=this.getValue();if(n.startsWith("-")){return true}}}));PARENS([et,Je],(function(e){var t=e.parent();if(t instanceof je)return true;if(t instanceof Qe&&!(t instanceof et))return true;if(t instanceof ze&&t.expression===this)return true;if(t instanceof Je&&t.condition===this)return true;if(t instanceof He&&t.expression===this)return true;if(this instanceof et&&this.left instanceof fe&&this.left.is_array===false)return true}));DEFPRINT(K,(function(e,t){t.print_string(e.value,e.quote);t.semicolon()}));DEFPRINT(oe,(function(e,t){t.print("...");e.expression.print(t)}));DEFPRINT(fe,(function(e,t){t.print(e.is_array?"[":"{");var n=e.names.length;e.names.forEach((function(e,r){if(r>0)t.comma();e.print(t);if(r==n-1&&e instanceof $t)t.comma()}));t.print(e.is_array?"]":"}")}));DEFPRINT(z,(function(e,t){t.print("debugger");t.semicolon()}));function display_body(e,t,n,r){var i=e.length-1;n.in_directive=r;e.forEach((function(e,r){if(n.in_directive===true&&!(e instanceof K||e instanceof W||e instanceof G&&e.body instanceof Kt)){n.in_directive=false}if(!(e instanceof W)){n.indent();e.print(n);if(!(r==i&&t)){n.newline();if(t)n.newline()}}if(n.in_directive===true&&e instanceof G&&e.body instanceof Kt){n.in_directive=false}}));n.in_directive=false}q.DEFMETHOD("_do_print_body",(function(e){force_statement(this.body,e)}));DEFPRINT(U,(function(e,t){e.body.print(t);t.semicolon()}));DEFPRINT(ie,(function(e,t){display_body(e.body,true,t,true);t.print("")}));DEFPRINT(Y,(function(e,t){e.label.print(t);t.colon();e.body.print(t)}));DEFPRINT(G,(function(e,t){e.body.print(t);t.semicolon()}));function print_braced_empty(e,t){t.print("{");t.with_indent(t.next_indent(),(function(){t.append_comments(e,true)}));t.print("}")}function print_braced(e,t,n){if(e.body.length>0){t.with_block((function(){display_body(e.body,false,t,n)}))}else print_braced_empty(e,t)}DEFPRINT(X,(function(e,t){print_braced(e,t)}));DEFPRINT(W,(function(e,t){t.semicolon()}));DEFPRINT(Z,(function(e,t){t.print("do");t.space();make_block(e.body,t);t.space();t.print("while");t.space();t.with_parens((function(){e.condition.print(t)}));t.semicolon()}));DEFPRINT(Q,(function(e,t){t.print("while");t.space();t.with_parens((function(){e.condition.print(t)}));t.space();e._do_print_body(t)}));DEFPRINT(J,(function(e,t){t.print("for");t.space();t.with_parens((function(){if(e.init){if(e.init instanceof xe){e.init.print(t)}else{parenthesize_for_noin(e.init,t,true)}t.print(";");t.space()}else{t.print(";")}if(e.condition){e.condition.print(t);t.print(";");t.space()}else{t.print(";")}if(e.step){e.step.print(t)}}));t.space();e._do_print_body(t)}));DEFPRINT(ee,(function(e,t){t.print("for");if(e.await){t.space();t.print("await")}t.space();t.with_parens((function(){e.init.print(t);t.space();t.print(e instanceof te?"of":"in");t.space();e.object.print(t)}));t.space();e._do_print_body(t)}));DEFPRINT(ne,(function(e,t){t.print("with");t.space();t.with_parens((function(){e.expression.print(t)}));t.space();e._do_print_body(t)}));ae.DEFMETHOD("_do_print",(function(e,t){var n=this;if(!t){if(n.async){e.print("async");e.space()}e.print("function");if(n.is_generator){e.star()}if(n.name){e.space()}}if(n.name instanceof Et){n.name.print(e)}else if(t&&n.name instanceof V){e.with_square((function(){n.name.print(e)}))}e.with_parens((function(){n.argnames.forEach((function(t,n){if(n)e.comma();t.print(e)}))}));e.space();print_braced(n,e,true)}));DEFPRINT(ae,(function(e,t){e._do_print(t)}));DEFPRINT(_e,(function(e,t){var n=e.prefix;var r=n instanceof ae||n instanceof Qe||n instanceof Je||n instanceof Ge||n instanceof je||n instanceof Xe&&n.expression instanceof rt;if(r)t.print("(");e.prefix.print(t);if(r)t.print(")");e.template_string.print(t)}));DEFPRINT(pe,(function(e,t){var n=t.parent()instanceof _e;t.print("`");for(var r=0;r");e.space();const i=t.body[0];if(t.body.length===1&&i instanceof Ee){const t=i.value;if(!t){e.print("{}")}else if(left_is_object(t)){e.print("(");t.print(e);e.print(")")}else{t.print(e)}}else{print_braced(t,e)}if(r){e.print(")")}}));he.DEFMETHOD("_do_print",(function(e,t){e.print(t);if(this.value){e.space();const t=this.value.start.comments_before;if(t&&t.length&&!e.printed_comments.has(t)){e.print("(");this.value.print(e);e.print(")")}else{this.value.print(e)}}e.semicolon()}));DEFPRINT(Ee,(function(e,t){e._do_print(t,"return")}));DEFPRINT(ge,(function(e,t){e._do_print(t,"throw")}));DEFPRINT(Ae,(function(e,t){var n=e.is_star?"*":"";t.print("yield"+n);if(e.expression){t.space();e.expression.print(t)}}));DEFPRINT(Se,(function(e,t){t.print("await");t.space();var n=e.expression;var r=!(n instanceof ze||n instanceof It||n instanceof He||n instanceof je||n instanceof zt||n instanceof Se||n instanceof rt);if(r)t.print("(");e.expression.print(t);if(r)t.print(")")}));ve.DEFMETHOD("_do_print",(function(e,t){e.print(t);if(this.label){e.space();this.label.print(e)}e.semicolon()}));DEFPRINT(De,(function(e,t){e._do_print(t,"break")}));DEFPRINT(be,(function(e,t){e._do_print(t,"continue")}));function make_then(e,t){var n=e.body;if(t.option("braces")||t.option("ie8")&&n instanceof Z)return make_block(n,t);if(!n)return t.force_semicolon();while(true){if(n instanceof ye){if(!n.alternative){make_block(e.body,t);return}n=n.alternative}else if(n instanceof q){n=n.body}else break}force_statement(e.body,t)}DEFPRINT(ye,(function(e,t){t.print("if");t.space();t.with_parens((function(){e.condition.print(t)}));t.space();if(e.alternative){make_then(e,t);t.space();t.print("else");t.space();if(e.alternative instanceof ye)e.alternative.print(t);else force_statement(e.alternative,t)}else{e._do_print_body(t)}}));DEFPRINT(Te,(function(e,t){t.print("switch");t.space();t.with_parens((function(){e.expression.print(t)}));t.space();var n=e.body.length-1;if(n<0)print_braced_empty(e,t);else t.with_block((function(){e.body.forEach((function(e,r){t.indent(true);e.print(t);if(r0)t.newline()}))}))}));ke.DEFMETHOD("_do_print_body",(function(e){e.newline();this.body.forEach((function(t){e.indent();t.print(e);e.newline()}))}));DEFPRINT(Ce,(function(e,t){t.print("default:");e._do_print_body(t)}));DEFPRINT(Re,(function(e,t){t.print("case");t.space();e.expression.print(t);t.print(":");e._do_print_body(t)}));DEFPRINT(Fe,(function(e,t){t.print("try");t.space();print_braced(e,t);if(e.bcatch){t.space();e.bcatch.print(t)}if(e.bfinally){t.space();e.bfinally.print(t)}}));DEFPRINT(Oe,(function(e,t){t.print("catch");if(e.argname){t.space();t.with_parens((function(){e.argname.print(t)}))}t.space();print_braced(e,t)}));DEFPRINT(Me,(function(e,t){t.print("finally");t.space();print_braced(e,t)}));xe.DEFMETHOD("_do_print",(function(e,t){e.print(t);e.space();this.definitions.forEach((function(t,n){if(n)e.comma();t.print(e)}));var n=e.parent();var r=n instanceof J||n instanceof ee;var i=!r||n&&n.init!==this;if(i)e.semicolon()}));DEFPRINT(we,(function(e,t){e._do_print(t,"let")}));DEFPRINT(Ne,(function(e,t){e._do_print(t,"var")}));DEFPRINT(Ie,(function(e,t){e._do_print(t,"const")}));DEFPRINT(Le,(function(e,t){t.print("import");t.space();if(e.imported_name){e.imported_name.print(t)}if(e.imported_name&&e.imported_names){t.print(",");t.space()}if(e.imported_names){if(e.imported_names.length===1&&e.imported_names[0].foreign_name.name==="*"){e.imported_names[0].print(t)}else{t.print("{");e.imported_names.forEach((function(n,r){t.space();n.print(t);if(r{if(e instanceof re)return true;if(e instanceof Qe&&e.operator=="in"){return tn}}))}e.print(t,r)}DEFPRINT(Pe,(function(e,t){e.name.print(t);if(e.value){t.space();t.print("=");t.space();var n=t.parent(1);var r=n instanceof J||n instanceof ee;parenthesize_for_noin(e.value,t,r)}}));DEFPRINT(ze,(function(e,t){e.expression.print(t);if(e instanceof Ke&&e.args.length===0)return;if(e.expression instanceof ze||e.expression instanceof ae){t.add_mapping(e.start)}if(e.optional)t.print("?.");t.with_parens((function(){e.args.forEach((function(e,n){if(n)t.comma();e.print(t)}))}))}));DEFPRINT(Ke,(function(e,t){t.print("new");t.space();ze.prototype._codegen(e,t)}));Ge.DEFMETHOD("_do_print",(function(e){this.expressions.forEach((function(t,n){if(n>0){e.comma();if(e.should_break()){e.newline();e.indent()}}t.print(e)}))}));DEFPRINT(Ge,(function(e,t){e._do_print(t)}));DEFPRINT(Xe,(function(e,t){var n=e.expression;n.print(t);var r=e.property;var i=f.has(r)?t.option("ie8"):!is_identifier_string(r,t.option("ecma")>=2015||t.option("safari10"));if(e.optional)t.print("?.");if(i){t.print("[");t.add_mapping(e.end);t.print_string(r);t.print("]")}else{if(n instanceof Gt&&n.getValue()>=0){if(!/[xa-f.)]/i.test(t.last())){t.print(".")}}if(!e.optional)t.print(".");t.add_mapping(e.end);t.print_name(r)}}));DEFPRINT(We,(function(e,t){var n=e.expression;n.print(t);var r=e.property;if(e.optional)t.print("?");t.print(".#");t.print_name(r)}));DEFPRINT(qe,(function(e,t){e.expression.print(t);if(e.optional)t.print("?.");t.print("[");e.property.print(t);t.print("]")}));DEFPRINT(Ye,(function(e,t){e.expression.print(t)}));DEFPRINT($e,(function(e,t){var n=e.operator;t.print(n);if(/^[a-z]/i.test(n)||/[+-]$/.test(n)&&e.expression instanceof $e&&/^[+-]/.test(e.expression.operator)){t.space()}e.expression.print(t)}));DEFPRINT(Ze,(function(e,t){e.expression.print(t);t.print(e.operator)}));DEFPRINT(Qe,(function(e,t){var n=e.operator;e.left.print(t);if(n[0]==">"&&e.left instanceof Ze&&e.left.operator=="--"){t.print(" ")}else{t.space()}t.print(n);if((n=="<"||n=="<<")&&e.right instanceof $e&&e.right.operator=="!"&&e.right.expression instanceof $e&&e.right.expression.operator=="--"){t.print(" ")}else{t.space()}e.right.print(t)}));DEFPRINT(Je,(function(e,t){e.condition.print(t);t.space();t.print("?");t.space();e.consequent.print(t);t.space();t.colon();e.alternative.print(t)}));DEFPRINT(nt,(function(e,t){t.with_square((function(){var n=e.elements,r=n.length;if(r>0)t.space();n.forEach((function(e,n){if(n)t.comma();e.print(t);if(n===r-1&&e instanceof $t)t.comma()}));if(r>0)t.space()}))}));DEFPRINT(rt,(function(e,t){if(e.properties.length>0)t.with_block((function(){e.properties.forEach((function(e,n){if(n){t.print(",");t.newline()}t.indent();e.print(t)}));t.newline()}));else print_braced_empty(e,t)}));DEFPRINT(_t,(function(e,t){t.print("class");t.space();if(e.name){e.name.print(t);t.space()}if(e.extends){var n=!(e.extends instanceof It)&&!(e.extends instanceof He)&&!(e.extends instanceof ht)&&!(e.extends instanceof ue);t.print("extends");if(n){t.print("(")}else{t.space()}e.extends.print(t);if(n){t.print(")")}else{t.space()}}if(e.properties.length>0)t.with_block((function(){e.properties.forEach((function(e,n){if(n){t.newline()}t.indent();e.print(t)}));t.newline()}));else t.print("{}")}));DEFPRINT(gt,(function(e,t){t.print("new.target")}));function print_property_name(e,t,n){if(n.option("quote_keys")){return n.print_string(e)}if(""+ +e==e&&e>=0){if(n.option("keep_numbers")){return n.print(e)}return n.print(make_num(e))}var r=f.has(e)?n.option("ie8"):n.option("ecma")<2015||n.option("safari10")?!is_basic_identifier_string(e):!is_identifier_string(e,true);if(r||t&&n.option("keep_quoted_props")){return n.print_string(e,t)}return n.print_name(e)}DEFPRINT(ot,(function(e,t){function get_name(e){var t=e.definition();return t?t.mangled_name||t.name:e.name}var n=t.option("shorthand");if(n&&e.value instanceof Et&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value)===e.key&&!f.has(e.key)){print_property_name(e.key,e.quote,t)}else if(n&&e.value instanceof tt&&e.value.left instanceof Et&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value.left)===e.key){print_property_name(e.key,e.quote,t);t.space();t.print("=");t.space();e.value.right.print(t)}else{if(!(e.key instanceof V)){print_property_name(e.key,e.quote,t)}else{t.with_square((function(){e.key.print(t)}))}t.colon();e.value.print(t)}}));DEFPRINT(dt,((e,t)=>{if(e.static){t.print("static");t.space()}t.print("#");print_property_name(e.key.name,e.quote,t);if(e.value){t.print("=");e.value.print(t)}t.semicolon()}));DEFPRINT(pt,((e,t)=>{if(e.static){t.print("static");t.space()}if(e.key instanceof Ct){print_property_name(e.key.name,e.quote,t)}else{t.print("[");e.key.print(t);t.print("]")}if(e.value){t.print("=");e.value.print(t)}t.semicolon()}));it.DEFMETHOD("_print_getter_setter",(function(e,t,n){var r=this;if(r.static){n.print("static");n.space()}if(e){n.print(e);n.space()}if(r.key instanceof kt){if(t)n.print("#");print_property_name(r.key.name,r.quote,n)}else{n.with_square((function(){r.key.print(n)}))}r.value._do_print(n,true)}));DEFPRINT(ut,(function(e,t){e._print_getter_setter("set",false,t)}));DEFPRINT(lt,(function(e,t){e._print_getter_setter("get",false,t)}));DEFPRINT(at,(function(e,t){e._print_getter_setter("set",true,t)}));DEFPRINT(st,(function(e,t){e._print_getter_setter("get",true,t)}));DEFPRINT(ft,(function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,true,t)}));DEFPRINT(ct,(function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,false,t)}));Et.DEFMETHOD("_do_print",(function(e){var t=this.definition();e.print_name(t?t.mangled_name||t.name:this.name)}));DEFPRINT(Et,(function(e,t){e._do_print(t)}));DEFPRINT($t,noop);DEFPRINT(Vt,(function(e,t){t.print("this")}));DEFPRINT(Ut,(function(e,t){t.print("super")}));DEFPRINT(zt,(function(e,t){t.print(e.getValue())}));DEFPRINT(Kt,(function(e,t){t.print_string(e.getValue(),e.quote,t.in_directive)}));DEFPRINT(Gt,(function(e,t){if((t.option("keep_numbers")||t.use_asm)&&e.raw){t.print(e.raw)}else{t.print(make_num(e.getValue()))}}));DEFPRINT(Ht,(function(e,t){t.print(e.getValue()+"n")}));const e=/(<\s*\/\s*script)/i;const slash_script_replace=(e,t)=>t.replace("/","\\/");DEFPRINT(Xt,(function(t,n){let{source:r,flags:i}=t.getValue();r=regexp_source_fix(r);i=i?sort_regexp_flags(i):"";r=r.replace(e,slash_script_replace);n.print(n.to_utf8(`/${r}/${i}`));const o=n.parent();if(o instanceof Qe&&/^\w/.test(o.operator)&&o.left===t){n.print(" ")}}));function force_statement(e,t){if(t.option("braces")){make_block(e,t)}else{if(!e||e instanceof W)t.force_semicolon();else e.print(t)}}function best_of(e){var t=e[0],n=t.length;for(var r=1;re===null&&t===null||e.TYPE===t.TYPE&&e.shallow_cmp(t);const equivalent_to=(e,t)=>{if(!shallow_cmp(e,t))return false;const n=[e];const r=[t];const i=n.push.bind(n);const o=r.push.bind(r);while(n.length&&r.length){const e=n.pop();const t=r.pop();if(!shallow_cmp(e,t))return false;e._children_backwards(i);t._children_backwards(o);if(n.length!==r.length){return false}}return n.length==0&&r.length==0};const mkshallow=e=>{const t=Object.keys(e).map((t=>{if(e[t]==="eq"){return`this.${t} === other.${t}`}else if(e[t]==="exist"){return`(this.${t} == null ? other.${t} == null : this.${t} === other.${t})`}else{throw new Error(`mkshallow: Unexpected instruction: ${e[t]}`)}})).join(" && ");return new Function("other","return "+t)};const pass_through=()=>true;V.prototype.shallow_cmp=function(){throw new Error("did not find a shallow_cmp function for "+this.constructor.name)};z.prototype.shallow_cmp=pass_through;K.prototype.shallow_cmp=mkshallow({value:"eq"});G.prototype.shallow_cmp=pass_through;H.prototype.shallow_cmp=pass_through;W.prototype.shallow_cmp=pass_through;Y.prototype.shallow_cmp=mkshallow({"label.name":"eq"});Z.prototype.shallow_cmp=pass_through;Q.prototype.shallow_cmp=pass_through;J.prototype.shallow_cmp=mkshallow({init:"exist",condition:"exist",step:"exist"});ee.prototype.shallow_cmp=pass_through;te.prototype.shallow_cmp=pass_through;ne.prototype.shallow_cmp=pass_through;ie.prototype.shallow_cmp=pass_through;oe.prototype.shallow_cmp=pass_through;ae.prototype.shallow_cmp=mkshallow({is_generator:"eq",async:"eq"});fe.prototype.shallow_cmp=mkshallow({is_array:"eq"});_e.prototype.shallow_cmp=pass_through;pe.prototype.shallow_cmp=pass_through;de.prototype.shallow_cmp=mkshallow({value:"eq"});me.prototype.shallow_cmp=pass_through;ve.prototype.shallow_cmp=pass_through;Se.prototype.shallow_cmp=pass_through;Ae.prototype.shallow_cmp=mkshallow({is_star:"eq"});ye.prototype.shallow_cmp=mkshallow({alternative:"exist"});Te.prototype.shallow_cmp=pass_through;ke.prototype.shallow_cmp=pass_through;Fe.prototype.shallow_cmp=mkshallow({bcatch:"exist",bfinally:"exist"});Oe.prototype.shallow_cmp=mkshallow({argname:"exist"});Me.prototype.shallow_cmp=pass_through;xe.prototype.shallow_cmp=pass_through;Pe.prototype.shallow_cmp=mkshallow({value:"exist"});Be.prototype.shallow_cmp=pass_through;Le.prototype.shallow_cmp=mkshallow({imported_name:"exist",imported_names:"exist"});Ve.prototype.shallow_cmp=pass_through;Ue.prototype.shallow_cmp=mkshallow({exported_definition:"exist",exported_value:"exist",exported_names:"exist",module_name:"eq",is_default:"eq"});ze.prototype.shallow_cmp=pass_through;Ge.prototype.shallow_cmp=pass_through;He.prototype.shallow_cmp=pass_through;Ye.prototype.shallow_cmp=pass_through;Xe.prototype.shallow_cmp=mkshallow({property:"eq"});We.prototype.shallow_cmp=mkshallow({property:"eq"});je.prototype.shallow_cmp=mkshallow({operator:"eq"});Qe.prototype.shallow_cmp=mkshallow({operator:"eq"});Je.prototype.shallow_cmp=pass_through;nt.prototype.shallow_cmp=pass_through;rt.prototype.shallow_cmp=pass_through;it.prototype.shallow_cmp=pass_through;ot.prototype.shallow_cmp=mkshallow({key:"eq"});ut.prototype.shallow_cmp=mkshallow({static:"eq"});lt.prototype.shallow_cmp=mkshallow({static:"eq"});ct.prototype.shallow_cmp=mkshallow({static:"eq",is_generator:"eq",async:"eq"});_t.prototype.shallow_cmp=mkshallow({name:"exist",extends:"exist"});pt.prototype.shallow_cmp=mkshallow({static:"eq"});Et.prototype.shallow_cmp=mkshallow({name:"eq"});gt.prototype.shallow_cmp=pass_through;Vt.prototype.shallow_cmp=pass_through;Ut.prototype.shallow_cmp=pass_through;Kt.prototype.shallow_cmp=mkshallow({value:"eq"});Gt.prototype.shallow_cmp=mkshallow({value:"eq"});Ht.prototype.shallow_cmp=mkshallow({value:"eq"});Xt.prototype.shallow_cmp=function(e){return this.value.flags===e.value.flags&&this.value.source===e.value.source};Wt.prototype.shallow_cmp=pass_through;const _n=1<<0;const pn=1<<1;let dn=null;let mn=null;class SymbolDef{constructor(e,t,n){this.name=t.name;this.orig=[t];this.init=n;this.eliminated=0;this.assignments=0;this.scope=e;this.replaced=0;this.global=false;this.export=0;this.mangled_name=null;this.undeclared=false;this.id=SymbolDef.next_id++;this.chained=false;this.direct_access=false;this.escaped=0;this.recursive_refs=0;this.references=[];this.should_replace=undefined;this.single_use=false;this.fixed=false;Object.seal(this)}fixed_value(){if(!this.fixed||this.fixed instanceof V)return this.fixed;return this.fixed()}unmangleable(e){if(!e)e={};if(dn&&dn.has(this.id)&&keep_name(e.keep_fnames,this.orig[0].name))return true;return this.global&&!e.toplevel||this.export&_n||this.undeclared||!e.eval&&this.scope.pinned()||(this.orig[0]instanceof Rt||this.orig[0]instanceof Tt)&&keep_name(e.keep_fnames,this.orig[0].name)||this.orig[0]instanceof kt||(this.orig[0]instanceof Ot||this.orig[0]instanceof Ft)&&keep_name(e.keep_classnames,this.orig[0].name)}mangle(e){const t=e.cache&&e.cache.props;if(this.global&&t&&t.has(this.name)){this.mangled_name=t.get(this.name)}else if(!this.mangled_name&&!this.unmangleable(e)){var n=this.scope;var r=this.orig[0];if(e.ie8&&r instanceof Rt)n=n.parent_scope;const i=redefined_catch_def(this);this.mangled_name=i?i.mangled_name||i.name:n.next_mangled(e,this);if(this.global&&t){t.set(this.name,this.mangled_name)}}}}SymbolDef.next_id=1;function redefined_catch_def(e){if(e.orig[0]instanceof Mt&&e.scope.is_block_scope()){return e.scope.get_defun_scope().variables.get(e.name)}}re.DEFMETHOD("figure_out_scope",(function(e,{parent_scope:t=null,toplevel:n=this}={}){e=defaults(e,{cache:null,ie8:false,safari10:false});if(!(n instanceof ie)){throw new Error("Invalid toplevel scope")}var r=this.parent_scope=t;var i=new Map;var o=null;var a=null;var s=[];var u=new TreeWalker(((t,n)=>{if(t.is_block_scope()){const i=r;t.block_scope=r=new re(t);r._block_scope=true;const o=t instanceof Oe?i.parent_scope:i;r.init_scope_vars(o);r.uses_with=i.uses_with;r.uses_eval=i.uses_eval;if(e.safari10){if(t instanceof J||t instanceof ee){s.push(r)}}if(t instanceof Te){const e=r;r=i;t.expression.walk(u);r=e;for(let e=0;e{if(e===t)return true;if(t instanceof bt){return e instanceof Rt}return!(e instanceof At||e instanceof St)}))){js_error(`"${t.name}" is redeclared`,t.start.file,t.start.line,t.start.col,t.start.pos)}if(!(t instanceof yt))mark_export(d,2);if(o!==r){t.mark_enclosed();var d=r.find_variable(t);if(t.thedef!==d){t.thedef=d;t.reference()}}}else if(t instanceof Lt){var m=i.get(t.name);if(!m)throw new Error(string_template("Undefined label {name} [{line},{col}]",{name:t.name,line:t.start.line,col:t.start.col}));t.thedef=m}if(!(r instanceof ie)&&(t instanceof Ue||t instanceof Le)){js_error(`"${t.TYPE}" statement may only appear at the top level`,t.start.file,t.start.line,t.start.col,t.start.pos)}}));this.walk(u);function mark_export(e,t){if(a){var n=0;do{t++}while(u.parent(n++)!==a)}var r=u.parent(t);if(e.export=r instanceof Ue?_n:0){var i=r.exported_definition;if((i instanceof ce||i instanceof mt)&&r.is_default){e.export=pn}}}const l=this instanceof ie;if(l){this.globals=new Map}var u=new TreeWalker((e=>{if(e instanceof ve&&e.label){e.label.thedef.references.push(e);return true}if(e instanceof It){var t=e.name;if(t=="eval"&&u.parent()instanceof ze){for(var r=e.scope;r&&!r.uses_eval;r=r.parent_scope){r.uses_eval=true}}var i;if(u.parent()instanceof Be&&u.parent(1).module_name||!(i=e.scope.find_variable(t))){i=n.def_global(e);if(e instanceof Pt)i.export=_n}else if(i.scope instanceof ae&&t=="arguments"){i.scope.uses_arguments=true}e.thedef=i;e.reference();if(e.scope.is_block_scope()&&!(i.orig[0]instanceof bt)){e.scope=e.scope.get_defun_scope()}return true}var o;if(e instanceof Mt&&(o=redefined_catch_def(e.definition()))){var r=e.scope;while(r){push_uniq(r.enclosed,o);if(r===o.scope)break;r=r.parent_scope}}}));this.walk(u);if(e.ie8||e.safari10){walk(this,(e=>{if(e instanceof Mt){var t=e.name;var r=e.thedef.references;var i=e.scope.get_defun_scope();var o=i.find_variable(t)||n.globals.get(t)||i.def_variable(e);r.forEach((function(e){e.thedef=o;e.reference()}));e.thedef=o;e.reference();return true}}))}if(e.safari10){for(const e of s){e.parent_scope.variables.forEach((function(t){push_uniq(e.enclosed,t)}))}}}));ie.DEFMETHOD("def_global",(function(e){var t=this.globals,n=e.name;if(t.has(n)){return t.get(n)}else{var r=new SymbolDef(this,e);r.undeclared=true;r.global=true;t.set(n,r);return r}}));re.DEFMETHOD("init_scope_vars",(function(e){this.variables=new Map;this.uses_with=false;this.uses_eval=false;this.parent_scope=e;this.enclosed=[];this.cname=-1}));re.DEFMETHOD("conflicting_def",(function(e){return this.enclosed.find((t=>t.name===e))||this.variables.has(e)||this.parent_scope&&this.parent_scope.conflicting_def(e)}));re.DEFMETHOD("conflicting_def_shallow",(function(e){return this.enclosed.find((t=>t.name===e))||this.variables.has(e)}));re.DEFMETHOD("add_child_scope",(function(e){if(e.parent_scope===this)return;e.parent_scope=this;const t=(()=>{const e=[];let t=this;do{e.push(t)}while(t=t.parent_scope);e.reverse();return e})();const n=new Set(e.enclosed);const r=[];for(const e of t){r.forEach((t=>push_uniq(e.enclosed,t)));for(const t of e.variables.values()){if(n.has(t)){push_uniq(r,t);push_uniq(e.enclosed,t)}}}}));function find_scopes_visible_from(e){const t=new Set;for(const n of new Set(e)){(function bubble_up(e){if(e==null||t.has(e))return;t.add(e);bubble_up(e.parent_scope)})(n)}return[...t]}re.DEFMETHOD("create_symbol",(function(e,{source:t,tentative_name:n,scope:r,conflict_scopes:i=[r],init:o=null}={}){let a;i=find_scopes_visible_from(i);if(n){n=a=n.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/gi,"_");let e=0;while(i.find((e=>e.conflicting_def_shallow(a)))){a=n+"$"+e++}}if(!a){throw new Error("No symbol name could be generated in create_symbol()")}const s=make_node(e,t,{name:a,scope:r});this.def_variable(s,o||null);s.mark_enclosed();return s}));V.DEFMETHOD("is_block_scope",return_false);_t.DEFMETHOD("is_block_scope",return_false);ae.DEFMETHOD("is_block_scope",return_false);ie.DEFMETHOD("is_block_scope",return_false);ke.DEFMETHOD("is_block_scope",return_false);H.DEFMETHOD("is_block_scope",return_true);re.DEFMETHOD("is_block_scope",(function(){return this._block_scope||false}));j.DEFMETHOD("is_block_scope",return_true);ae.DEFMETHOD("init_scope_vars",(function(){re.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false;this.def_variable(new yt({name:"arguments",start:this.start,end:this.end}))}));le.DEFMETHOD("init_scope_vars",(function(){re.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false}));Et.DEFMETHOD("mark_enclosed",(function(){var e=this.definition();var t=this.scope;while(t){push_uniq(t.enclosed,e);if(t===e.scope)break;t=t.parent_scope}}));Et.DEFMETHOD("reference",(function(){this.definition().references.push(this);this.mark_enclosed()}));re.DEFMETHOD("find_variable",(function(e){if(e instanceof Et)e=e.name;return this.variables.get(e)||this.parent_scope&&this.parent_scope.find_variable(e)}));re.DEFMETHOD("def_function",(function(e,t){var n=this.def_variable(e,t);if(!n.init||n.init instanceof ce)n.init=t;return n}));re.DEFMETHOD("def_variable",(function(e,t){var n=this.variables.get(e.name);if(n){n.orig.push(e);if(n.init&&(n.scope!==e.scope||n.init instanceof ue)){n.init=t}}else{n=new SymbolDef(this,e,t);this.variables.set(e.name,n);n.global=!this.parent_scope}return e.thedef=n}));function next_mangled(e,t){var n=e.enclosed;e:while(true){var r=hn(++e.cname);if(f.has(r))continue;if(t.reserved.has(r))continue;if(mn&&mn.has(r))continue e;for(let e=n.length;--e>=0;){const i=n[e];const o=i.mangled_name||i.unmangleable(t)&&i.name;if(r==o)continue e}return r}}re.DEFMETHOD("next_mangled",(function(e){return next_mangled(this,e)}));ie.DEFMETHOD("next_mangled",(function(e){let t;const n=this.mangled_names;do{t=next_mangled(this,e)}while(n.has(t));return t}));ue.DEFMETHOD("next_mangled",(function(e,t){var n=t.orig[0]instanceof yt&&this.name&&this.name.definition();var r=n?n.mangled_name||n.name:null;while(true){var i=next_mangled(this,e);if(!r||r!=i)return i}}));Et.DEFMETHOD("unmangleable",(function(e){var t=this.definition();return!t||t.unmangleable(e)}));wt.DEFMETHOD("unmangleable",return_false);Et.DEFMETHOD("unreferenced",(function(){return!this.definition().references.length&&!this.scope.pinned()}));Et.DEFMETHOD("definition",(function(){return this.thedef}));Et.DEFMETHOD("global",(function(){return this.thedef.global}));ie.DEFMETHOD("_default_mangler_options",(function(e){e=defaults(e,{eval:false,ie8:false,keep_classnames:false,keep_fnames:false,module:false,reserved:[],toplevel:false});if(e.module)e.toplevel=true;if(!Array.isArray(e.reserved)&&!(e.reserved instanceof Set)){e.reserved=[]}e.reserved=new Set(e.reserved);e.reserved.add("arguments");return e}));ie.DEFMETHOD("mangle_names",(function(e){e=this._default_mangler_options(e);var t=-1;var n=[];if(e.keep_fnames){dn=new Set}const r=this.mangled_names=new Set;if(e.cache){this.globals.forEach(collect);if(e.cache.props){e.cache.props.forEach((function(e){r.add(e)}))}}var i=new TreeWalker((function(r,i){if(r instanceof Y){var o=t;i();t=o;return true}if(r instanceof re){r.variables.forEach(collect);return}if(r.is_block_scope()){r.block_scope.variables.forEach(collect);return}if(dn&&r instanceof Pe&&r.value instanceof ae&&!r.value.name&&keep_name(e.keep_fnames,r.name.name)){dn.add(r.name.definition().id);return}if(r instanceof wt){let e;do{e=hn(++t)}while(f.has(e));r.mangled_name=e;return true}if(!(e.ie8||e.safari10)&&r instanceof Mt){n.push(r.definition());return}}));this.walk(i);if(e.keep_fnames||e.keep_classnames){mn=new Set;n.forEach((t=>{if(t.name.length<6&&t.unmangleable(e)){mn.add(t.name)}}))}n.forEach((t=>{t.mangle(e)}));dn=null;mn=null;function collect(t){const r=!e.reserved.has(t.name)&&!(t.export&_n);if(r){n.push(t)}}}));ie.DEFMETHOD("find_colliding_names",(function(e){const t=e.cache&&e.cache.props;const n=new Set;e.reserved.forEach(to_avoid);this.globals.forEach(add_def);this.walk(new TreeWalker((function(e){if(e instanceof re)e.variables.forEach(add_def);if(e instanceof Mt)add_def(e.definition())})));return n;function to_avoid(e){n.add(e)}function add_def(n){var r=n.name;if(n.global&&t&&t.has(r))r=t.get(r);else if(!n.unmangleable(e))return;to_avoid(r)}}));ie.DEFMETHOD("expand_names",(function(e){hn.reset();hn.sort();e=this._default_mangler_options(e);var t=this.find_colliding_names(e);var n=0;this.globals.forEach(rename);this.walk(new TreeWalker((function(e){if(e instanceof re)e.variables.forEach(rename);if(e instanceof Mt)rename(e.definition())})));function next_name(){var e;do{e=hn(n++)}while(t.has(e)||f.has(e));return e}function rename(t){if(t.global&&e.cache)return;if(t.unmangleable(e))return;if(e.reserved.has(t.name))return;const n=redefined_catch_def(t);const r=t.name=n?n.name:next_name();t.orig.forEach((function(e){e.name=r}));t.references.forEach((function(e){e.name=r}))}}));V.DEFMETHOD("tail_node",return_this);Ge.DEFMETHOD("tail_node",(function(){return this.expressions[this.expressions.length-1]}));ie.DEFMETHOD("compute_char_frequency",(function(e){e=this._default_mangler_options(e);try{V.prototype.print=function(t,n){this._print(t,n);if(this instanceof Et&&!this.unmangleable(e)){hn.consider(this.name,-1)}else if(e.properties){if(this instanceof We){hn.consider("#"+this.property,-1)}else if(this instanceof Xe){hn.consider(this.property,-1)}else if(this instanceof qe){skip_string(this.property)}}};hn.consider(this.print_to_string(),1)}finally{V.prototype.print=V.prototype._print}hn.sort();function skip_string(e){if(e instanceof Kt){hn.consider(e.value,-1)}else if(e instanceof Je){skip_string(e.consequent);skip_string(e.alternative)}else if(e instanceof Ge){skip_string(e.tail_node())}}}));const hn=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");const t="0123456789".split("");let n;let r;function reset(){r=new Map;e.forEach((function(e){r.set(e,0)}));t.forEach((function(e){r.set(e,0)}))}base54.consider=function(e,t){for(var n=e.length;--n>=0;){r.set(e[n],r.get(e[n])+t)}};function compare(e,t){return r.get(t)-r.get(e)}base54.sort=function(){n=mergeSort(e,compare).concat(mergeSort(t,compare))};base54.reset=reset;reset();function base54(e){var t="",r=54;e++;do{e--;t+=n[e%r];e=Math.floor(e/r);r=64}while(e>0);return t}return base54})();let En=undefined;V.prototype.size=function(e,t){En=e&&e.mangle_options;let n=0;walk_parent(this,((e,t)=>{n+=e._size(t);if(e instanceof le&&e.is_braceless()){n+=e.body[0].value._size(t);return true}}),t||e&&e.stack);En=undefined;return n};V.prototype._size=()=>0;z.prototype._size=()=>8;K.prototype._size=function(){return 2+this.value.length};const list_overhead=e=>e.length&&e.length-1;H.prototype._size=function(){return 2+list_overhead(this.body)};ie.prototype._size=function(){return list_overhead(this.body)};W.prototype._size=()=>1;Y.prototype._size=()=>2;Z.prototype._size=()=>9;Q.prototype._size=()=>7;J.prototype._size=()=>8;ee.prototype._size=()=>8;ne.prototype._size=()=>6;oe.prototype._size=()=>3;const lambda_modifiers=e=>(e.is_generator?1:0)+(e.async?6:0);se.prototype._size=function(){return lambda_modifiers(this)+4+list_overhead(this.argnames)+list_overhead(this.body)};ue.prototype._size=function(e){const t=!!first_in_statement(e);return t*2+lambda_modifiers(this)+12+list_overhead(this.argnames)+list_overhead(this.body)};ce.prototype._size=function(){return lambda_modifiers(this)+13+list_overhead(this.argnames)+list_overhead(this.body)};le.prototype._size=function(){let e=2+list_overhead(this.argnames);if(!(this.argnames.length===1&&this.argnames[0]instanceof Et)){e+=2}const t=this.is_braceless()?0:list_overhead(this.body)+2;return lambda_modifiers(this)+e+t};fe.prototype._size=()=>2;pe.prototype._size=function(){return 2+Math.floor(this.segments.length/2)*3};de.prototype._size=function(){return this.value.length};Ee.prototype._size=function(){return this.value?7:6};ge.prototype._size=()=>6;De.prototype._size=function(){return this.label?6:5};be.prototype._size=function(){return this.label?9:8};ye.prototype._size=()=>4;Te.prototype._size=function(){return 8+list_overhead(this.body)};Re.prototype._size=function(){return 5+list_overhead(this.body)};Ce.prototype._size=function(){return 8+list_overhead(this.body)};Fe.prototype._size=function(){return 3+list_overhead(this.body)};Oe.prototype._size=function(){let e=7+list_overhead(this.body);if(this.argname){e+=2}return e};Me.prototype._size=function(){return 7+list_overhead(this.body)};const def_size=(e,t)=>e+list_overhead(t.definitions);Ne.prototype._size=function(){return def_size(4,this)};we.prototype._size=function(){return def_size(4,this)};Ie.prototype._size=function(){return def_size(6,this)};Pe.prototype._size=function(){return this.value?1:0};Be.prototype._size=function(){return this.name?4:0};Le.prototype._size=function(){let e=6;if(this.imported_name)e+=1;if(this.imported_name||this.imported_names)e+=5;if(this.imported_names){e+=2+list_overhead(this.imported_names)}return e};Ve.prototype._size=()=>11;Ue.prototype._size=function(){let e=7+(this.is_default?8:0);if(this.exported_value){e+=this.exported_value._size()}if(this.exported_names){e+=2+list_overhead(this.exported_names)}if(this.module_name){e+=5}return e};ze.prototype._size=function(){if(this.optional){return 4+list_overhead(this.args)}return 2+list_overhead(this.args)};Ke.prototype._size=function(){return 6+list_overhead(this.args)};Ge.prototype._size=function(){return list_overhead(this.expressions)};Xe.prototype._size=function(){if(this.optional){return this.property.length+2}return this.property.length+1};We.prototype._size=function(){if(this.optional){return this.property.length+3}return this.property.length+2};qe.prototype._size=function(){return this.optional?4:2};je.prototype._size=function(){if(this.operator==="typeof")return 7;if(this.operator==="void")return 5;return this.operator.length};Qe.prototype._size=function(e){if(this.operator==="in")return 4;let t=this.operator.length;if((this.operator==="+"||this.operator==="-")&&this.right instanceof je&&this.right.operator===this.operator){t+=1}if(this.needs_parens(e)){t+=2}return t};Je.prototype._size=()=>3;nt.prototype._size=function(){return 2+list_overhead(this.elements)};rt.prototype._size=function(e){let t=2;if(first_in_statement(e)){t+=2}return t+list_overhead(this.properties)};const key_size=e=>typeof e==="string"?e.length:0;ot.prototype._size=function(){return key_size(this.key)+1};const static_size=e=>e?7:0;lt.prototype._size=function(){return 5+static_size(this.static)+key_size(this.key)};ut.prototype._size=function(){return 5+static_size(this.static)+key_size(this.key)};ct.prototype._size=function(){return static_size(this.static)+key_size(this.key)+lambda_modifiers(this)};ft.prototype._size=function(){return ct.prototype._size.call(this)+1};st.prototype._size=at.prototype._size=function(){return ct.prototype._size.call(this)+4};_t.prototype._size=function(){return(this.name?8:7)+(this.extends?8:0)};pt.prototype._size=function(){return static_size(this.static)+(typeof this.key==="string"?this.key.length+2:0)+(this.value?1:0)};dt.prototype._size=function(){return pt.prototype._size.call(this)+1};Et.prototype._size=function(){return!En||this.definition().unmangleable(En)?this.name.length:1};Ct.prototype._size=function(){return this.name.length};It.prototype._size=vt.prototype._size=function(){const{name:e,thedef:t}=this;if(t&&t.global)return e.length;if(e==="arguments")return 9;return Et.prototype._size.call(this)};gt.prototype._size=()=>10;Nt.prototype._size=function(){return this.name.length};Bt.prototype._size=function(){return this.name.length};Vt.prototype._size=()=>4;Ut.prototype._size=()=>5;Kt.prototype._size=function(){return this.value.length+2};Gt.prototype._size=function(){const{value:e}=this;if(e===0)return 1;if(e>0&&Math.floor(e)===e){return Math.floor(Math.log10(e)+1)}return e.toString().length};Ht.prototype._size=function(){return this.value.length};Xt.prototype._size=function(){return this.value.toString().length};qt.prototype._size=()=>4;Yt.prototype._size=()=>3;jt.prototype._size=()=>6;$t.prototype._size=()=>0;Zt.prototype._size=()=>8;en.prototype._size=()=>4;Jt.prototype._size=()=>5;Se.prototype._size=()=>6;Ae.prototype._size=()=>6;const gn=1;const vn=2;const Dn=4;const bn=8;const Sn=16;const An=32;const yn=256;const Tn=512;const kn=1024;const Cn=yn|Tn|kn;const has_flag=(e,t)=>e.flags&t;const set_flag=(e,t)=>{e.flags|=t};const clear_flag=(e,t)=>{e.flags&=~t};class Compressor extends TreeWalker{constructor(e,{false_by_default:t=false,mangle_options:n=false}){super();if(e.defaults!==undefined&&!e.defaults)t=true;this.options=defaults(e,{arguments:false,arrows:!t,booleans:!t,booleans_as_integers:false,collapse_vars:!t,comparisons:!t,computed_props:!t,conditionals:!t,dead_code:!t,defaults:true,directives:!t,drop_console:false,drop_debugger:!t,ecma:5,evaluate:!t,expression:false,global_defs:false,hoist_funs:false,hoist_props:!t,hoist_vars:false,ie8:false,if_return:!t,inline:!t,join_vars:!t,keep_classnames:false,keep_fargs:true,keep_fnames:false,keep_infinity:false,loops:!t,module:false,negate_iife:!t,passes:1,properties:!t,pure_getters:!t&&"strict",pure_funcs:null,reduce_funcs:!t,reduce_vars:!t,sequences:!t,side_effects:!t,switches:!t,top_retain:null,toplevel:!!(e&&e["top_retain"]),typeofs:!t,unsafe:false,unsafe_arrows:false,unsafe_comps:false,unsafe_Function:false,unsafe_math:false,unsafe_symbols:false,unsafe_methods:false,unsafe_proto:false,unsafe_regexp:false,unsafe_undefined:false,unused:!t,warnings:false},true);var r=this.options["global_defs"];if(typeof r=="object")for(var i in r){if(i[0]==="@"&&HOP(r,i)){r[i.slice(1)]=parse(r[i],{expression:true})}}if(this.options["inline"]===true)this.options["inline"]=3;var o=this.options["pure_funcs"];if(typeof o=="function"){this.pure_funcs=o}else{this.pure_funcs=o?function(e){return!o.includes(e.expression.print_to_string())}:return_true}var a=this.options["top_retain"];if(a instanceof RegExp){this.top_retain=function(e){return a.test(e.name)}}else if(typeof a=="function"){this.top_retain=a}else if(a){if(typeof a=="string"){a=a.split(/,/)}this.top_retain=function(e){return a.includes(e.name)}}if(this.options["module"]){this.directives["use strict"]=true;this.options["toplevel"]=true}var s=this.options["toplevel"];this.toplevel=typeof s=="string"?{funcs:/funcs/.test(s),vars:/vars/.test(s)}:{funcs:s,vars:s};var u=this.options["sequences"];this.sequences_limit=u==1?800:u|0;this.evaluated_regexps=new Map;this._toplevel=undefined;this.mangle_options=n}option(e){return this.options[e]}exposed(e){if(e.export)return true;if(e.global)for(var t=0,n=e.orig.length;t0||this.option("reduce_vars")){this._toplevel.reset_opt_flags(this)}this._toplevel=this._toplevel.transform(this);if(t>1){let e=0;walk(this._toplevel,(()=>{e++}));if(e=0){i.body[a]=i.body[a].transform(r)}}else if(i instanceof ye){i.body=i.body.transform(r);if(i.alternative){i.alternative=i.alternative.transform(r)}}else if(i instanceof ne){i.body=i.body.transform(r)}return i}));n.transform(r)}));function read_property(e,t){t=get_value(t);if(t instanceof V)return;var n;if(e instanceof nt){var r=e.elements;if(t=="length")return make_node_from_constant(r.length,e);if(typeof t=="number"&&t in r)n=r[t]}else if(e instanceof rt){t=""+t;var i=e.properties;for(var o=i.length;--o>=0;){var a=i[o];if(!(a instanceof ot))return;if(!n&&i[o].key===t)n=i[o].value}}return n instanceof It&&n.fixed_value()||n}function is_modified(e,t,n,r,i,o){var a=t.parent(i);var s=is_lhs(n,a);if(s)return s;if(!o&&a instanceof ze&&a.expression===n&&!(r instanceof le)&&!(r instanceof _t)&&!a.is_callee_pure(e)&&(!(r instanceof ue)||!(a instanceof Ke)&&r.contains_this())){return true}if(a instanceof nt){return is_modified(e,t,a,a,i+1)}if(a instanceof ot&&n===a.value){var u=t.parent(i+1);return is_modified(e,t,u,u,i+2)}if(a instanceof He&&a.expression===n){var l=read_property(r,a.property);return!o&&is_modified(e,t,a,l,i+1)}}(function(e){e(V,noop);function reset_def(e,t){t.assignments=0;t.chained=false;t.direct_access=false;t.escaped=0;t.recursive_refs=0;t.references=[];t.single_use=undefined;if(t.scope.pinned()){t.fixed=false}else if(t.orig[0]instanceof St||!e.exposed(t)){t.fixed=t.init}else{t.fixed=false}}function reset_variables(e,t,n){n.variables.forEach((function(n){reset_def(t,n);if(n.fixed===null){e.defs_to_safe_ids.set(n.id,e.safe_ids);mark(e,n,true)}else if(n.fixed){e.loop_ids.set(n.id,e.in_loop);mark(e,n,true)}}))}function reset_block_variables(e,t){if(t.block_scope)t.block_scope.variables.forEach((t=>{reset_def(e,t)}))}function push(e){e.safe_ids=Object.create(e.safe_ids)}function pop(e){e.safe_ids=Object.getPrototypeOf(e.safe_ids)}function mark(e,t,n){e.safe_ids[t.id]=n}function safe_to_read(e,t){if(t.single_use=="m")return false;if(e.safe_ids[t.id]){if(t.fixed==null){var n=t.orig[0];if(n instanceof yt||n.name=="arguments")return false;t.fixed=make_node(jt,n)}return true}return t.fixed instanceof ce}function safe_to_assign(e,t,n,r){if(t.fixed===undefined)return true;let i;if(t.fixed===null&&(i=e.defs_to_safe_ids.get(t.id))){i[t.id]=false;e.defs_to_safe_ids.delete(t.id);return true}if(!HOP(e.safe_ids,t.id))return false;if(!safe_to_read(e,t))return false;if(t.fixed===false)return false;if(t.fixed!=null&&(!r||t.references.length>t.assignments))return false;if(t.fixed instanceof ce){return r instanceof V&&t.fixed.parent_scope===n}return t.orig.every((e=>!(e instanceof St||e instanceof Tt||e instanceof Rt)))}function ref_once(e,t,n){return t.option("unused")&&!n.scope.pinned()&&n.references.length-n.recursive_refs==1&&e.loop_ids.get(n.id)===e.in_loop}function is_immutable(e){if(!e)return false;return e.is_constant()||e instanceof ae||e instanceof Vt}function mark_escaped(e,t,n,r,i,o=0,a=1){var s=e.parent(o);if(i){if(i.is_constant())return;if(i instanceof ht)return}if(s instanceof et&&(s.operator==="="||s.logical)&&r===s.right||s instanceof ze&&(r!==s.expression||s instanceof Ke)||s instanceof he&&r===s.value&&r.scope!==t.scope||s instanceof Pe&&r===s.value||s instanceof Ae&&r===s.value&&r.scope!==t.scope){if(a>1&&!(i&&i.is_constant_expression(n)))a=1;if(!t.escaped||t.escaped>a)t.escaped=a;return}else if(s instanceof nt||s instanceof Se||s instanceof Qe&&On.has(s.operator)||s instanceof Je&&r!==s.condition||s instanceof oe||s instanceof Ge&&r===s.tail_node()){mark_escaped(e,t,n,s,s,o+1,a)}else if(s instanceof ot&&r===s.value){var u=e.parent(o+1);mark_escaped(e,t,n,u,u,o+2,a)}else if(s instanceof He&&r===s.expression){i=read_property(i,s.property);mark_escaped(e,t,n,s,i,o+1,a+1);if(i)return}if(o>0)return;if(s instanceof Ge&&r!==s.tail_node())return;if(s instanceof G)return;t.direct_access=true}const suppress=e=>walk(e,(e=>{if(!(e instanceof Et))return;var t=e.definition();if(!t)return;if(e instanceof It)t.references.push(e);t.fixed=false}));e(se,(function(e,t,n){push(e);reset_variables(e,n,this);t();pop(e);return true}));e(et,(function(e,t,n){var r=this;if(r.left instanceof fe){suppress(r.left);return}const finish_walk=()=>{if(r.logical){r.left.walk(e);push(e);r.right.walk(e);pop(e);return true}};var i=r.left;if(!(i instanceof It))return finish_walk();var o=i.definition();var a=safe_to_assign(e,o,i.scope,r.right);o.assignments++;if(!a)return finish_walk();var s=o.fixed;if(!s&&r.operator!="="&&!r.logical)return finish_walk();var u=r.operator=="=";var l=u?r.right:r;if(is_modified(n,e,r,l,0))return finish_walk();o.references.push(i);if(!r.logical){if(!u)o.chained=true;o.fixed=u?function(){return r.right}:function(){return make_node(Qe,r,{operator:r.operator.slice(0,-1),left:s instanceof V?s:s(),right:r.right})}}if(r.logical){mark(e,o,false);push(e);r.right.walk(e);pop(e);return true}mark(e,o,false);r.right.walk(e);mark(e,o,true);mark_escaped(e,o,i.scope,r,l,0,1);return true}));e(Qe,(function(e){if(!On.has(this.operator))return;this.left.walk(e);push(e);this.right.walk(e);pop(e);return true}));e(H,(function(e,t,n){reset_block_variables(n,this)}));e(Re,(function(e){push(e);this.expression.walk(e);pop(e);push(e);walk_body(this,e);pop(e);return true}));e(_t,(function(e,t){clear_flag(this,Sn);push(e);t();pop(e);return true}));e(Je,(function(e){this.condition.walk(e);push(e);this.consequent.walk(e);pop(e);push(e);this.alternative.walk(e);pop(e);return true}));e(Ye,(function(e,t){const n=e.safe_ids;t();e.safe_ids=n;return true}));e(ze,(function(e){this.expression.walk(e);if(this.optional){push(e)}for(const t of this.args)t.walk(e);return true}));e(He,(function(e){if(!this.optional)return;this.expression.walk(e);push(e);if(this.property instanceof V)this.property.walk(e);return true}));e(Ce,(function(e,t){push(e);t();pop(e);return true}));function mark_lambda(e,t,n){clear_flag(this,Sn);push(e);reset_variables(e,n,this);if(this.uses_arguments){t();pop(e);return}var r;if(!this.name&&(r=e.parent())instanceof ze&&r.expression===this&&!r.args.some((e=>e instanceof oe))&&this.argnames.every((e=>e instanceof Et))){this.argnames.forEach(((t,n)=>{if(!t.definition)return;var i=t.definition();if(i.orig.length>1)return;if(i.fixed===undefined&&(!this.uses_arguments||e.has_directive("use strict"))){i.fixed=function(){return r.args[n]||make_node(jt,r)};e.loop_ids.set(i.id,e.in_loop);mark(e,i,true)}else{i.fixed=false}}))}t();pop(e);return true}e(ae,mark_lambda);e(Z,(function(e,t,n){reset_block_variables(n,this);const r=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);if(has_break_or_continue(this)){pop(e);push(e)}this.condition.walk(e);pop(e);e.in_loop=r;return true}));e(J,(function(e,t,n){reset_block_variables(n,this);if(this.init)this.init.walk(e);const r=e.in_loop;e.in_loop=this;push(e);if(this.condition)this.condition.walk(e);this.body.walk(e);if(this.step){if(has_break_or_continue(this)){pop(e);push(e)}this.step.walk(e)}pop(e);e.in_loop=r;return true}));e(ee,(function(e,t,n){reset_block_variables(n,this);suppress(this.init);this.object.walk(e);const r=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);pop(e);e.in_loop=r;return true}));e(ye,(function(e){this.condition.walk(e);push(e);this.body.walk(e);pop(e);if(this.alternative){push(e);this.alternative.walk(e);pop(e)}return true}));e(Y,(function(e){push(e);this.body.walk(e);pop(e);return true}));e(Mt,(function(){this.definition().fixed=false}));e(It,(function(e,t,n){var r=this.definition();r.references.push(this);if(r.references.length==1&&!r.fixed&&r.orig[0]instanceof Tt){e.loop_ids.set(r.id,e.in_loop)}var i;if(r.fixed===undefined||!safe_to_read(e,r)){r.fixed=false}else if(r.fixed){i=this.fixed_value();if(i instanceof ae&&recursive_ref(e,r)){r.recursive_refs++}else if(i&&!n.exposed(r)&&ref_once(e,n,r)){r.single_use=i instanceof ae&&!i.pinned()||i instanceof _t||r.scope===this.scope&&i.is_constant_expression()}else{r.single_use=false}if(is_modified(n,e,this,i,0,is_immutable(i))){if(r.single_use){r.single_use="m"}else{r.fixed=false}}}mark_escaped(e,r,this.scope,this,i,0,1)}));e(ie,(function(e,t,n){this.globals.forEach((function(e){reset_def(n,e)}));reset_variables(e,n,this)}));e(Fe,(function(e,t,n){reset_block_variables(n,this);push(e);walk_body(this,e);pop(e);if(this.bcatch){push(e);this.bcatch.walk(e);pop(e)}if(this.bfinally)this.bfinally.walk(e);return true}));e(je,(function(e){var t=this;if(t.operator!=="++"&&t.operator!=="--")return;var n=t.expression;if(!(n instanceof It))return;var r=n.definition();var i=safe_to_assign(e,r,n.scope,true);r.assignments++;if(!i)return;var o=r.fixed;if(!o)return;r.references.push(n);r.chained=true;r.fixed=function(){return make_node(Qe,t,{operator:t.operator.slice(0,-1),left:make_node($e,t,{operator:"+",expression:o instanceof V?o:o()}),right:make_node(Gt,t,{value:1})})};mark(e,r,true);return true}));e(Pe,(function(e,t){var n=this;if(n.name instanceof fe){suppress(n.name);return}var r=n.name.definition();if(n.value){if(safe_to_assign(e,r,n.name.scope,n.value)){r.fixed=function(){return n.value};e.loop_ids.set(r.id,e.in_loop);mark(e,r,false);t();mark(e,r,true);return true}else{r.fixed=false}}}));e(Q,(function(e,t,n){reset_block_variables(n,this);const r=e.in_loop;e.in_loop=this;push(e);t();pop(e);e.in_loop=r;return true}))})((function(e,t){e.DEFMETHOD("reduce_vars",t)}));ie.DEFMETHOD("reset_opt_flags",(function(e){const t=this;const n=e.option("reduce_vars");const r=new TreeWalker((function(i,o){clear_flag(i,Cn);if(n){if(e.top_retain&&i instanceof ce&&r.parent()===t){set_flag(i,kn)}return i.reduce_vars(r,o,e)}}));r.safe_ids=Object.create(null);r.in_loop=null;r.loop_ids=new Map;r.defs_to_safe_ids=new Map;t.walk(r)}));Et.DEFMETHOD("fixed_value",(function(){var e=this.thedef.fixed;if(!e||e instanceof V)return e;return e()}));It.DEFMETHOD("is_immutable",(function(){var e=this.definition().orig;return e.length==1&&e[0]instanceof Rt}));function is_func_expr(e){return e instanceof le||e instanceof ue}function is_lhs_read_only(e){if(e instanceof Vt)return true;if(e instanceof It)return e.definition().orig[0]instanceof Rt;if(e instanceof He){e=e.expression;if(e instanceof It){if(e.is_immutable())return false;e=e.fixed_value()}if(!e)return true;if(e instanceof Xt)return false;if(e instanceof zt)return true;return is_lhs_read_only(e)}return false}function is_ref_of(e,t){if(!(e instanceof It))return false;var n=e.definition().orig;for(var r=n.length;--r>=0;){if(n[r]instanceof t)return true}}function find_scope(e){for(let t=0;;t++){const n=e.parent(t);if(n instanceof ie)return n;if(n instanceof ae)return n;if(n.block_scope)return n.block_scope}}function find_variable(e,t){var n,r=0;while(n=e.parent(r++)){if(n instanceof re)break;if(n instanceof Oe&&n.argname){n=n.argname.definition().scope;break}}return n.find_variable(t)}function make_sequence(e,t){if(t.length==1)return t[0];if(t.length==0)throw new Error("trying to create a sequence with length zero!");return make_node(Ge,e,{expressions:t.reduce(merge_sequence,[])})}function make_node_from_constant(e,t){switch(typeof e){case"string":return make_node(Kt,t,{value:e});case"number":if(isNaN(e))return make_node(Yt,t);if(isFinite(e)){return 1/e<0?make_node($e,t,{operator:"-",expression:make_node(Gt,t,{value:-e})}):make_node(Gt,t,{value:e})}return e<0?make_node($e,t,{operator:"-",expression:make_node(Zt,t)}):make_node(Zt,t);case"boolean":return make_node(e?en:Jt,t);case"undefined":return make_node(jt,t);default:if(e===null){return make_node(qt,t,{value:null})}if(e instanceof RegExp){return make_node(Xt,t,{value:{source:regexp_source_fix(e.source),flags:e.flags}})}throw new Error(string_template("Can't handle constant of type: {type}",{type:typeof e}))}}function maintain_this_binding(e,t,n){if(e instanceof $e&&e.operator=="delete"||e instanceof ze&&e.expression===t&&(n instanceof He||n instanceof It&&n.name=="eval")){return make_sequence(t,[make_node(Gt,t,{value:0}),n])}return n}function merge_sequence(e,t){if(t instanceof Ge){e.push(...t.expressions)}else{e.push(t)}return e}function as_statement_array(e){if(e===null)return[];if(e instanceof X)return e.body;if(e instanceof W)return[];if(e instanceof U)return[e];throw new Error("Can't convert thing to statement array")}function is_empty(e){if(e===null)return true;if(e instanceof W)return true;if(e instanceof X)return e.body.length==0;return false}function can_be_evicted_from_block(e){return!(e instanceof mt||e instanceof ce||e instanceof we||e instanceof Ie||e instanceof Ue||e instanceof Le)}function loop_body(e){if(e instanceof j){return e.body instanceof X?e.body:e}return e}function is_iife_call(e){if(e.TYPE!="Call")return false;return e.expression instanceof ue||is_iife_call(e.expression)}function is_undeclared_ref(e){return e instanceof It&&e.definition().undeclared}var Rn=makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");It.DEFMETHOD("is_declared",(function(e){return!this.definition().undeclared||e.option("unsafe")&&Rn.has(this.name)}));var Fn=makePredicate("Infinity NaN undefined");function is_identifier_atom(e){return e instanceof Zt||e instanceof Yt||e instanceof jt}function tighten_body(e,t){var n,r;var o=t.find_parent(re).get_defun_scope();find_loop_scope_try();var a,s=10;do{a=false;eliminate_spurious_blocks(e);if(t.option("dead_code")){eliminate_dead_code(e,t)}if(t.option("if_return")){handle_if_return(e,t)}if(t.sequences_limit>0){sequencesize(e,t);sequencesize_2(e,t)}if(t.option("join_vars")){join_consecutive_vars(e)}if(t.option("collapse_vars")){collapse(e,t)}}while(a&&s-- >0);function find_loop_scope_try(){var e=t.self(),i=0;do{if(e instanceof Oe||e instanceof Me){i++}else if(e instanceof j){n=true}else if(e instanceof re){o=e;break}else if(e instanceof Fe){r=true}}while(e=t.parent(i++))}function collapse(e,t){if(o.pinned())return e;var s;var u=[];var l=e.length;var c=new TreeTransformer((function(e){if(k)return e;if(!T){if(e!==_[p])return e;p++;if(p<_.length)return handle_custom_scan_order(e);T=true;h=find_stop(e,0);if(h===e)k=true;return e}var n=c.parent();if(e instanceof et&&(e.logical||e.operator!="="&&g.equivalent_to(e.left))||e instanceof Se||e instanceof ze&&g instanceof He&&g.equivalent_to(e.expression)||e instanceof z||e instanceof fe||e instanceof oe&&e.expression instanceof Et&&(e.expression instanceof Vt||e.expression.definition().references.length>1)||e instanceof j&&!(e instanceof J)||e instanceof ve||e instanceof Fe||e instanceof ne||e instanceof Ae||e instanceof Ue||e instanceof _t||n instanceof J&&e!==n.init||!S&&(e instanceof It&&!e.is_declared(t)&&!Pn.has(e))||e instanceof It&&n instanceof ze&&has_annotation(n,on)){k=true;return e}if(!E&&(!D||!S)&&(n instanceof Qe&&On.has(n.operator)&&n.left!==e||n instanceof Je&&n.condition!==e||n instanceof ye&&n.condition!==e)){E=n}if(R&&!(e instanceof vt)&&g.equivalent_to(e)){if(E){k=true;return e}if(is_lhs(e,n)){if(m)C++;return e}else{C++;if(m&&d instanceof Pe)return e}a=k=true;if(d instanceof Ze){return make_node($e,d,d)}if(d instanceof Pe){var i=d.name.definition();var o=d.value;if(i.references.length-i.replaced==1&&!t.exposed(i)){i.replaced++;if(y&&is_identifier_atom(o)){return o.transform(t)}else{return maintain_this_binding(n,e,o)}}return make_node(et,d,{operator:"=",logical:false,left:make_node(It,d.name,d.name),right:o})}clear_flag(d,An);return d}var s;if(e instanceof ze||e instanceof he&&(b||g instanceof He||may_modify(g))||e instanceof He&&(b||e.expression.may_throw_on_access(t))||e instanceof It&&(v.get(e.name)||b&&may_modify(e))||e instanceof Pe&&e.value&&(v.has(e.name.name)||b&&may_modify(e.name))||(s=is_lhs(e.left,e))&&(s instanceof He||v.has(s.name))||A&&(r?e.has_side_effects(t):side_effects_external(e))){h=e;if(e instanceof re)k=true}return handle_custom_scan_order(e)}),(function(e){if(k)return;if(h===e)k=true;if(E===e)E=null}));var f=new TreeTransformer((function(e){if(k)return e;if(!T){if(e!==_[p])return e;p++;if(p<_.length)return;T=true;return e}if(e instanceof It&&e.name==M.name){if(!--C)k=true;if(is_lhs(e,f.parent()))return e;M.replaced++;m.replaced--;return d.value}if(e instanceof Ce||e instanceof re)return e}));while(--l>=0){if(l==0&&t.option("unused"))extract_args();var _=[];extract_candidates(e[l]);while(u.length>0){_=u.pop();var p=0;var d=_[_.length-1];var m=null;var h=null;var E=null;var g=get_lhs(d);if(!g||is_lhs_read_only(g)||g.has_side_effects(t))continue;var v=get_lvalues(d);var D=is_lhs_local(g);if(g instanceof It)v.set(g.name,false);var b=value_has_side_effects(d);var S=replace_all_symbols();var A=d.may_throw(t);var y=d.name instanceof yt;var T=y;var k=false,C=0,R=!s||!T;if(!R){for(var F=t.self().argnames.lastIndexOf(d.name)+1;!k&&FC)C=false;else{k=false;p=0;T=y;for(var O=l;!k&&O!(e instanceof oe)))){var r=t.has_directive("use strict");if(r&&!member(r,n.body))r=false;var i=n.argnames.length;s=e.args.slice(i);var o=new Set;for(var a=i;--a>=0;){var l=n.argnames[a];var c=e.args[a];const i=l.definition&&l.definition();const _=i&&i.orig.length>1;if(_)continue;s.unshift(make_node(Pe,l,{name:l,value:c}));if(o.has(l.name))continue;o.add(l.name);if(l instanceof oe){var f=e.args.slice(a);if(f.every((e=>!has_overlapping_symbol(n,e,r)))){u.unshift([make_node(Pe,l,{name:l.expression,value:make_node(nt,e,{elements:f})})])}}else{if(!c){c=make_node(jt,l).transform(t)}else if(c instanceof ae&&c.pinned()||has_overlapping_symbol(n,c,r)){c=null}if(c)u.unshift([make_node(Pe,l,{name:l,value:c})])}}}}function extract_candidates(e){_.push(e);if(e instanceof et){if(!e.left.has_side_effects(t)&&!(e.right instanceof Ye)){u.push(_.slice())}extract_candidates(e.right)}else if(e instanceof Qe){extract_candidates(e.left);extract_candidates(e.right)}else if(e instanceof ze&&!has_annotation(e,on)){extract_candidates(e.expression);e.args.forEach(extract_candidates)}else if(e instanceof Re){extract_candidates(e.expression)}else if(e instanceof Je){extract_candidates(e.condition);extract_candidates(e.consequent);extract_candidates(e.alternative)}else if(e instanceof xe){var n=e.definitions.length;var r=n-200;if(r<0)r=0;for(;r1&&!(e.name instanceof yt)||(r>1?mangleable_var(e):!t.exposed(n))){return make_node(It,e.name,e.name)}}else{const t=e instanceof et?e.left:e.expression;return!is_ref_of(t,St)&&!is_ref_of(t,At)&&t}}function get_rvalue(e){if(e instanceof et){return e.right}else{return e.value}}function get_lvalues(e){var n=new Map;if(e instanceof je)return n;var r=new TreeWalker((function(e){var i=e;while(i instanceof He)i=i.expression;if(i instanceof It||i instanceof Vt){n.set(i.name,n.get(i.name)||is_modified(t,r,e,e,0))}}));get_rvalue(e).walk(r);return n}function remove_candidate(n){if(n.name instanceof yt){var r=t.parent(),o=t.self().argnames;var a=o.indexOf(n.name);if(a<0){r.args.length=Math.min(r.args.length,o.length-1)}else{var s=r.args;if(s[a])s[a]=make_node(Gt,s[a],{value:0})}return true}var u=false;return e[l].transform(new TreeTransformer((function(e,t,r){if(u)return e;if(e===n||e.body===n){u=true;if(e instanceof Pe){e.value=e.name instanceof St?make_node(jt,e.value):null;return e}return r?i.skip:null}}),(function(e){if(e instanceof Ge)switch(e.expressions.length){case 0:return null;case 1:return e.expressions[0]}})))}function is_lhs_local(e){while(e instanceof He)e=e.expression;return e instanceof It&&e.definition().scope===o&&!(n&&(v.has(e.name)||d instanceof je||d instanceof et&&!d.logical&&d.operator!="="))}function value_has_side_effects(e){if(e instanceof je)return Mn.has(e.operator);return get_rvalue(e).has_side_effects(t)}function replace_all_symbols(){if(b)return false;if(m)return true;if(g instanceof It){var e=g.definition();if(e.references.length-e.replaced==(d instanceof Pe?1:2)){return true}}return false}function may_modify(e){if(!e.definition)return true;var t=e.definition();if(t.orig.length==1&&t.orig[0]instanceof Tt)return false;if(t.scope.get_defun_scope()!==o)return true;return!t.references.every((e=>{var t=e.scope.get_defun_scope();if(t.TYPE=="Scope")t=t.parent_scope;return t===o}))}function side_effects_external(e,t){if(e instanceof et)return side_effects_external(e.left,true);if(e instanceof je)return side_effects_external(e.expression,true);if(e instanceof Pe)return e.value&&side_effects_external(e.value);if(t){if(e instanceof Xe)return side_effects_external(e.expression,true);if(e instanceof qe)return side_effects_external(e.expression,true);if(e instanceof It)return e.definition().scope!==o}return false}}function eliminate_spurious_blocks(e){var t=[];for(var n=0;n=0;){var s=e[o];var u=next_index(o);var l=e[u];if(i&&!l&&s instanceof Ee){if(!s.value){a=true;e.splice(o,1);continue}if(s.value instanceof $e&&s.value.operator=="void"){a=true;e[o]=make_node(G,s,{body:s.value.expression});continue}}if(s instanceof ye){var c=aborts(s.body);if(can_merge_flow(c)){if(c.label){remove(c.label.thedef.references,c)}a=true;s=s.clone();s.condition=s.condition.negate(t);var f=as_statement_array_with_return(s.body,c);s.body=make_node(X,s,{body:as_statement_array(s.alternative).concat(extract_functions())});s.alternative=make_node(X,s,{body:f});e[o]=s.transform(t);continue}var c=aborts(s.alternative);if(can_merge_flow(c)){if(c.label){remove(c.label.thedef.references,c)}a=true;s=s.clone();s.body=make_node(X,s.body,{body:as_statement_array(s.body).concat(extract_functions())});var f=as_statement_array_with_return(s.alternative,c);s.alternative=make_node(X,s.alternative,{body:f});e[o]=s.transform(t);continue}}if(s instanceof ye&&s.body instanceof Ee){var _=s.body.value;if(!_&&!s.alternative&&(i&&!l||l instanceof Ee&&!l.value)){a=true;e[o]=make_node(G,s.condition,{body:s.condition});continue}if(_&&!s.alternative&&l instanceof Ee&&l.value){a=true;s=s.clone();s.alternative=l;e[o]=s.transform(t);e.splice(u,1);continue}if(_&&!s.alternative&&(!l&&i&&r||l instanceof Ee)){a=true;s=s.clone();s.alternative=l||make_node(Ee,s,{value:null});e[o]=s.transform(t);if(l)e.splice(u,1);continue}var p=e[prev_index(o)];if(t.option("sequences")&&i&&!s.alternative&&p instanceof ye&&p.body instanceof Ee&&next_index(u)==e.length&&l instanceof G){a=true;s=s.clone();s.alternative=make_node(X,l,{body:[l,make_node(Ee,l,{value:null})]});e[o]=s.transform(t);e.splice(u,1);continue}}}function has_multiple_if_returns(e){var t=0;for(var n=e.length;--n>=0;){var r=e[n];if(r instanceof ye&&r.body instanceof Ee){if(++t>1)return true}}return false}function is_return_void(e){return!e||e instanceof $e&&e.operator=="void"}function can_merge_flow(r){if(!r)return false;for(var a=o+1,s=e.length;a=0;){var r=e[n];if(!(r instanceof Ne&&declarations_only(r))){break}}return n}}function eliminate_dead_code(e,t){var n;var r=t.self();for(var i=0,o=0,s=e.length;i!e.value))}function sequencesize(e,t){if(e.length<2)return;var n=[],r=0;function push_seq(){if(!n.length)return;var t=make_sequence(n[0],n);e[r++]=make_node(G,t,{body:t});n=[]}for(var i=0,o=e.length;i=t.sequences_limit)push_seq();var u=s.body;if(n.length>0)u=u.drop_side_effect_free(t);if(u)merge_sequence(n,u)}else if(s instanceof xe&&declarations_only(s)||s instanceof ce){e[r++]=s}else{push_seq();e[r++]=s}}push_seq();e.length=r;if(r!=o)a=true}function to_simple_statement(e,t){if(!(e instanceof X))return e;var n=null;for(var r=0,i=e.body.length;r{if(e instanceof re)return true;if(e instanceof Qe&&e.operator==="in"){return tn}}));if(!e){if(o.init)o.init=cons_seq(o.init);else{o.init=r.body;n--;a=true}}}}else if(o instanceof ee){if(!(o.init instanceof Ie)&&!(o.init instanceof we)){o.object=cons_seq(o.object)}}else if(o instanceof ye){o.condition=cons_seq(o.condition)}else if(o instanceof Te){o.expression=cons_seq(o.expression)}else if(o instanceof ne){o.expression=cons_seq(o.expression)}}if(t.option("conditionals")&&o instanceof ye){var s=[];var u=to_simple_statement(o.body,s);var l=to_simple_statement(o.alternative,s);if(u!==false&&l!==false&&s.length>0){var c=s.length;s.push(make_node(ye,o,{condition:o.condition,body:u||make_node(W,o.body),alternative:l}));s.unshift(n,1);[].splice.apply(e,s);i+=c;n+=c+1;r=null;a=true;continue}}e[n++]=o;r=o instanceof G?o:null}e.length=n}function join_object_assignments(e,n){if(!(e instanceof xe))return;var r=e.definitions[e.definitions.length-1];if(!(r.value instanceof rt))return;var i;if(n instanceof et&&!n.logical){i=[n]}else if(n instanceof Ge){i=n.expressions.slice()}if(!i)return;var a=false;do{var s=i[0];if(!(s instanceof et))break;if(s.operator!="=")break;if(!(s.left instanceof He))break;var u=s.left.expression;if(!(u instanceof It))break;if(r.name.name!=u.name)break;if(!s.right.is_constant_expression(o))break;var l=s.left.property;if(l instanceof V){l=l.evaluate(t)}if(l instanceof V)break;l=""+l;var c=t.option("ecma")<2015&&t.has_directive("use strict")?function(e){return e.key!=l&&(e.key&&e.key.name!=l)}:function(e){return e.key&&e.key.name!=l};if(!r.value.properties.every(c))break;var f=r.value.properties.filter((function(e){return e.key===l}))[0];if(!f){r.value.properties.push(make_node(ot,s,{key:l,value:s.right}))}else{f.value=new Ge({start:f.start,expressions:[f.value.clone(),s.right.clone()],end:f.end})}i.shift();a=true}while(i.length);return a&&i}function join_consecutive_vars(e){var t;for(var n=0,r=-1,i=e.length;n{if(r instanceof Ne){r.remove_initializers();n.push(r);return true}if(r instanceof ce&&(r===t||!e.has_directive("use strict"))){n.push(r===t?r:make_node(Ne,r,{definitions:[make_node(Pe,r,{name:make_node(Dt,r.name,r.name),value:null})]}));return true}if(r instanceof Ue||r instanceof Le){n.push(r);return true}if(r instanceof re){return true}}))}function get_value(e){if(e instanceof zt){return e.getValue()}if(e instanceof $e&&e.operator=="void"&&e.expression instanceof zt){return}return e}function is_undefined(e,t){return has_flag(e,bn)||e instanceof jt||e instanceof $e&&e.operator=="void"&&!e.expression.has_side_effects(t)}(function(e){V.DEFMETHOD("may_throw_on_access",(function(e){return!e.option("pure_getters")||this._dot_throw(e)}));function is_strict(e){return/strict/.test(e.option("pure_getters"))}e(V,is_strict);e(qt,return_true);e(jt,return_true);e(zt,return_false);e(nt,return_false);e(rt,(function(e){if(!is_strict(e))return false;for(var t=this.properties.length;--t>=0;)if(this.properties[t]._dot_throw(e))return true;return false}));e(_t,return_false);e(it,return_false);e(lt,return_true);e(oe,(function(e){return this.expression._dot_throw(e)}));e(ue,return_false);e(le,return_false);e(Ze,return_false);e($e,(function(){return this.operator=="void"}));e(Qe,(function(e){return(this.operator=="&&"||this.operator=="||"||this.operator=="??")&&(this.left._dot_throw(e)||this.right._dot_throw(e))}));e(et,(function(e){if(this.logical)return true;return this.operator=="="&&this.right._dot_throw(e)}));e(Je,(function(e){return this.consequent._dot_throw(e)||this.alternative._dot_throw(e)}));e(Xe,(function(e){if(!is_strict(e))return false;if(this.property=="prototype"){return!(this.expression instanceof ue||this.expression instanceof _t)}return true}));e(Ye,(function(e){return this.expression._dot_throw(e)}));e(Ge,(function(e){return this.tail_node()._dot_throw(e)}));e(It,(function(e){if(this.name==="arguments")return false;if(has_flag(this,bn))return true;if(!is_strict(e))return false;if(is_undeclared_ref(this)&&this.is_declared(e))return false;if(this.is_immutable())return false;var t=this.fixed_value();return!t||t._dot_throw(e)}))})((function(e,t){e.DEFMETHOD("_dot_throw",t)}));(function(e){const t=makePredicate("! delete");const n=makePredicate("in instanceof == != === !== < <= >= >");e(V,return_false);e($e,(function(){return t.has(this.operator)}));e(Qe,(function(){return n.has(this.operator)||On.has(this.operator)&&this.left.is_boolean()&&this.right.is_boolean()}));e(Je,(function(){return this.consequent.is_boolean()&&this.alternative.is_boolean()}));e(et,(function(){return this.operator=="="&&this.right.is_boolean()}));e(Ge,(function(){return this.tail_node().is_boolean()}));e(en,return_true);e(Jt,return_true)})((function(e,t){e.DEFMETHOD("is_boolean",t)}));(function(e){e(V,return_false);e(Gt,return_true);var t=makePredicate("+ - ~ ++ --");e(je,(function(){return t.has(this.operator)}));var n=makePredicate("- * / % & | ^ << >> >>>");e(Qe,(function(e){return n.has(this.operator)||this.operator=="+"&&this.left.is_number(e)&&this.right.is_number(e)}));e(et,(function(e){return n.has(this.operator.slice(0,-1))||this.operator=="="&&this.right.is_number(e)}));e(Ge,(function(e){return this.tail_node().is_number(e)}));e(Je,(function(e){return this.consequent.is_number(e)&&this.alternative.is_number(e)}))})((function(e,t){e.DEFMETHOD("is_number",t)}));(function(e){e(V,return_false);e(Kt,return_true);e(pe,return_true);e($e,(function(){return this.operator=="typeof"}));e(Qe,(function(e){return this.operator=="+"&&(this.left.is_string(e)||this.right.is_string(e))}));e(et,(function(e){return(this.operator=="="||this.operator=="+=")&&this.right.is_string(e)}));e(Ge,(function(e){return this.tail_node().is_string(e)}));e(Je,(function(e){return this.consequent.is_string(e)&&this.alternative.is_string(e)}))})((function(e,t){e.DEFMETHOD("is_string",t)}));var On=makePredicate("&& || ??");var Mn=makePredicate("delete ++ --");function is_lhs(e,t){if(t instanceof je&&Mn.has(t.operator))return t.expression;if(t instanceof et&&t.left===e)return e}(function(e){function to_node(e,t){if(e instanceof V)return make_node(e.CTOR,t,e);if(Array.isArray(e))return make_node(nt,t,{elements:e.map((function(e){return to_node(e,t)}))});if(e&&typeof e=="object"){var n=[];for(var r in e)if(HOP(e,r)){n.push(make_node(ot,t,{key:r,value:to_node(e[r],t)}))}return make_node(rt,t,{properties:n})}return make_node_from_constant(e,t)}ie.DEFMETHOD("resolve_defines",(function(e){if(!e.option("global_defs"))return this;this.figure_out_scope({ie8:e.option("ie8")});return this.transform(new TreeTransformer((function(t){var n=t._find_defs(e,"");if(!n)return;var r=0,i=t,o;while(o=this.parent(r++)){if(!(o instanceof He))break;if(o.expression!==i)break;i=o}if(is_lhs(i,o)){return}return n})))}));e(V,noop);e(Ye,(function(e,t){return this.expression._find_defs(e,t)}));e(Xe,(function(e,t){return this.expression._find_defs(e,"."+this.property+t)}));e(vt,(function(){if(!this.global())return}));e(It,(function(e,t){if(!this.global())return;var n=e.option("global_defs");var r=this.name+t;if(HOP(n,r))return to_node(n[r],this)}))})((function(e,t){e.DEFMETHOD("_find_defs",t)}));function best_of_expression(e,t){return e.size()>t.size()?t:e}function best_of_statement(e,t){return best_of_expression(make_node(G,e,{body:e}),make_node(G,t,{body:t})).body}function best_of(e,t,n){return(first_in_statement(e)?best_of_statement:best_of_expression)(t,n)}function convert_to_predicate(e){const t=new Map;for(var n of Object.keys(e)){t.set(n,makePredicate(e[n]))}return t}var xn=["constructor","toString","valueOf"];var Nn=convert_to_predicate({Array:["indexOf","join","lastIndexOf","slice"].concat(xn),Boolean:xn,Function:xn,Number:["toExponential","toFixed","toPrecision"].concat(xn),Object:xn,RegExp:["test"].concat(xn),String:["charAt","charCodeAt","concat","indexOf","italics","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","trim"].concat(xn)});var wn=convert_to_predicate({Array:["isArray"],Math:["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","atan2","pow","max","min"],Number:["isFinite","isNaN"],Object:["create","getOwnPropertyDescriptor","getOwnPropertyNames","getPrototypeOf","isExtensible","isFrozen","isSealed","keys"],String:["fromCharCode"]});(function(e){V.DEFMETHOD("evaluate",(function(e){if(!e.option("evaluate"))return this;var t=this._eval(e,1);if(!t||t instanceof RegExp)return t;if(typeof t=="function"||typeof t=="object")return this;return t}));var t=makePredicate("! ~ - + void");V.DEFMETHOD("is_constant",(function(){if(this instanceof zt){return!(this instanceof Xt)}else{return this instanceof $e&&this.expression instanceof zt&&t.has(this.operator)}}));e(U,(function(){throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]",this.start))}));e(ae,return_this);e(_t,return_this);e(V,return_this);e(zt,(function(){return this.getValue()}));e(Ht,return_this);e(Xt,(function(e){let t=e.evaluated_regexps.get(this);if(t===undefined){try{t=(0,eval)(this.print_to_string())}catch(e){t=null}e.evaluated_regexps.set(this,t)}return t||this}));e(pe,(function(){if(this.segments.length!==1)return this;return this.segments[0].value}));e(ue,(function(e){if(e.option("unsafe")){var fn=function(){};fn.node=this;fn.toString=()=>this.print_to_string();return fn}return this}));e(nt,(function(e,t){if(e.option("unsafe")){var n=[];for(var r=0,i=this.elements.length;rtypeof e==="object"||typeof e==="function"||typeof e==="symbol";e(Qe,(function(e,t){if(!r.has(this.operator))t++;var n=this.left._eval(e,t);if(n===this.left)return this;var o=this.right._eval(e,t);if(o===this.right)return this;var a;if(n!=null&&o!=null&&i.has(this.operator)&&has_identity(n)&&has_identity(o)&&typeof n===typeof o){return this}switch(this.operator){case"&&":a=n&&o;break;case"||":a=n||o;break;case"??":a=n!=null?n:o;break;case"|":a=n|o;break;case"&":a=n&o;break;case"^":a=n^o;break;case"+":a=n+o;break;case"*":a=n*o;break;case"**":a=Math.pow(n,o);break;case"/":a=n/o;break;case"%":a=n%o;break;case"-":a=n-o;break;case"<<":a=n<>":a=n>>o;break;case">>>":a=n>>>o;break;case"==":a=n==o;break;case"===":a=n===o;break;case"!=":a=n!=o;break;case"!==":a=n!==o;break;case"<":a=n":a=n>o;break;case">=":a=n>=o;break;default:return this}if(isNaN(a)&&e.find_parent(ne)){return this}return a}));e(Je,(function(e,t){var n=this.condition._eval(e,t);if(n===this.condition)return this;var r=n?this.consequent:this.alternative;var i=r._eval(e,t);return i===r?this:i}));const o=new Set;e(It,(function(e,t){if(o.has(this))return this;var n=this.fixed_value();if(!n)return this;o.add(this);const r=n._eval(e,t);o.delete(this);if(r===n)return this;if(r&&typeof r=="object"){var i=this.definition().escaped;if(i&&t>i)return this}return r}));var a={Array:Array,Math:Math,Number:Number,Object:Object,String:String};var s=convert_to_predicate({Math:["E","LN10","LN2","LOG2E","LOG10E","PI","SQRT1_2","SQRT2"],Number:["MAX_VALUE","MIN_VALUE","NaN","NEGATIVE_INFINITY","POSITIVE_INFINITY"]});const u=new Set(["dotAll","global","ignoreCase","multiline","sticky","unicode"]);e(He,(function(e,t){if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")){var n=this.property;if(n instanceof V){n=n._eval(e,t);if(n===this.property)return this}var r=this.expression;var i;if(is_undeclared_ref(r)){var o;var l=r.name==="hasOwnProperty"&&n==="call"&&(o=e.parent()&&e.parent().args)&&(o&&o[0]&&o[0].evaluate(e));l=l instanceof Xe?l.expression:l;if(l==null||l.thedef&&l.thedef.undeclared){return this.clone()}var c=s.get(r.name);if(!c||!c.has(n))return this;i=a[r.name]}else{i=r._eval(e,t+1);if(i instanceof RegExp){if(n=="source"){return regexp_source_fix(i.source)}else if(n=="flags"||u.has(n)){return i[n]}}if(!i||i===r||!HOP(i,n))return this;if(typeof i=="function")switch(n){case"name":return i.node.name?i.node.name.name:"";case"length":return i.node.length_property();default:return this}}return i[n]}return this}));e(Ye,(function(e,t){const n=this.expression._eval(e,t);return n===this.expression?this:n}));e(ze,(function(e,t){var n=this.expression;if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")&&n instanceof He){var r=n.property;if(r instanceof V){r=r._eval(e,t);if(r===n.property)return this}var i;var o=n.expression;if(is_undeclared_ref(o)){var s=o.name==="hasOwnProperty"&&r==="call"&&(this.args[0]&&this.args[0].evaluate(e));s=s instanceof Xe?s.expression:s;if(s==null||s.thedef&&s.thedef.undeclared){return this.clone()}var u=wn.get(o.name);if(!u||!u.has(r))return this;i=a[o.name]}else{i=o._eval(e,t+1);if(i===o||!i)return this;var l=Nn.get(i.constructor.name);if(!l||!l.has(r))return this}var c=[];for(var f=0,_=this.args.length;f<_;f++){var p=this.args[f];var d=p._eval(e,t);if(p===d)return this;if(p instanceof ae)return this;c.push(d)}try{return i[r].apply(i,c)}catch(e){}}return this}));e(Ke,return_this)})((function(e,t){e.DEFMETHOD("_eval",t)}));(function(e){function basic_negation(e){return make_node($e,e,{operator:"!",expression:e})}function best(e,t,n){var r=basic_negation(e);if(n){var i=make_node(G,t,{body:t});return best_of_expression(r,i)===i?t:r}return best_of_expression(r,t)}e(V,(function(){return basic_negation(this)}));e(U,(function(){throw new Error("Cannot negate a statement")}));e(ue,(function(){return basic_negation(this)}));e(le,(function(){return basic_negation(this)}));e($e,(function(){if(this.operator=="!")return this.expression;return basic_negation(this)}));e(Ge,(function(e){var t=this.expressions.slice();t.push(t.pop().negate(e));return make_sequence(this,t)}));e(Je,(function(e,t){var n=this.clone();n.consequent=n.consequent.negate(e);n.alternative=n.alternative.negate(e);return best(this,n,t)}));e(Qe,(function(e,t){var n=this.clone(),r=this.operator;if(e.option("unsafe_comps")){switch(r){case"<=":n.operator=">";return n;case"<":n.operator=">=";return n;case">=":n.operator="<";return n;case">":n.operator="<=";return n}}switch(r){case"==":n.operator="!=";return n;case"!=":n.operator="==";return n;case"===":n.operator="!==";return n;case"!==":n.operator="===";return n;case"&&":n.operator="||";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"||":n.operator="&&";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"??":n.right=n.right.negate(e);return best(this,n,t)}return basic_negation(this)}))})((function(e,t){e.DEFMETHOD("negate",(function(e,n){return t.call(this,e,n)}))}));var In=makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");ze.DEFMETHOD("is_callee_pure",(function(e){if(e.option("unsafe")){var t=this.expression;var n=this.args&&this.args[0]&&this.args[0].evaluate(e);if(t.expression&&t.expression.name==="hasOwnProperty"&&(n==null||n.thedef&&n.thedef.undeclared)){return false}if(is_undeclared_ref(t)&&In.has(t.name))return true;let r;if(t instanceof Xe&&is_undeclared_ref(t.expression)&&(r=wn.get(t.expression.name))&&r.has(t.property)){return true}}return!!has_annotation(this,nn)||!e.pure_funcs(this)}));V.DEFMETHOD("is_call_pure",return_false);Xe.DEFMETHOD("is_call_pure",(function(e){if(!e.option("unsafe"))return;const t=this.expression;let n;if(t instanceof nt){n=Nn.get("Array")}else if(t.is_boolean()){n=Nn.get("Boolean")}else if(t.is_number(e)){n=Nn.get("Number")}else if(t instanceof Xt){n=Nn.get("RegExp")}else if(t.is_string(e)){n=Nn.get("String")}else if(!this.may_throw_on_access(e)){n=Nn.get("Object")}return n&&n.has(this.property)}));const Pn=new Set(["Number","String","Array","Object","Function","Promise"]);(function(e){e(V,return_true);e(W,return_false);e(zt,return_false);e(Vt,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].has_side_effects(t))return true;return false}e(H,(function(e){return any(this.body,e)}));e(ze,(function(e){if(!this.is_callee_pure(e)&&(!this.expression.is_call_pure(e)||this.expression.has_side_effects(e))){return true}return any(this.args,e)}));e(Te,(function(e){return this.expression.has_side_effects(e)||any(this.body,e)}));e(Re,(function(e){return this.expression.has_side_effects(e)||any(this.body,e)}));e(Fe,(function(e){return any(this.body,e)||this.bcatch&&this.bcatch.has_side_effects(e)||this.bfinally&&this.bfinally.has_side_effects(e)}));e(ye,(function(e){return this.condition.has_side_effects(e)||this.body&&this.body.has_side_effects(e)||this.alternative&&this.alternative.has_side_effects(e)}));e(Y,(function(e){return this.body.has_side_effects(e)}));e(G,(function(e){return this.body.has_side_effects(e)}));e(ae,return_false);e(_t,(function(e){if(this.extends&&this.extends.has_side_effects(e)){return true}return any(this.properties,e)}));e(Qe,(function(e){return this.left.has_side_effects(e)||this.right.has_side_effects(e)}));e(et,return_true);e(Je,(function(e){return this.condition.has_side_effects(e)||this.consequent.has_side_effects(e)||this.alternative.has_side_effects(e)}));e(je,(function(e){return Mn.has(this.operator)||this.expression.has_side_effects(e)}));e(It,(function(e){return!this.is_declared(e)&&!Pn.has(this.name)}));e(Ct,return_false);e(vt,return_false);e(rt,(function(e){return any(this.properties,e)}));e(it,(function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.value&&this.value.has_side_effects(e)}));e(pt,(function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.static&&this.value&&this.value.has_side_effects(e)}));e(ct,(function(e){return this.computed_key()&&this.key.has_side_effects(e)}));e(lt,(function(e){return this.computed_key()&&this.key.has_side_effects(e)}));e(ut,(function(e){return this.computed_key()&&this.key.has_side_effects(e)}));e(nt,(function(e){return any(this.elements,e)}));e(Xe,(function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)}));e(qe,(function(e){if(this.optional&&is_nullish(this.expression,e)){return false}return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)||this.property.has_side_effects(e)}));e(Ye,(function(e){return this.expression.has_side_effects(e)}));e(Ge,(function(e){return any(this.expressions,e)}));e(xe,(function(e){return any(this.definitions,e)}));e(Pe,(function(){return this.value}));e(de,return_false);e(pe,(function(e){return any(this.segments,e)}))})((function(e,t){e.DEFMETHOD("has_side_effects",t)}));(function(e){e(V,return_true);e(zt,return_false);e(W,return_false);e(ae,return_false);e(vt,return_false);e(Vt,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].may_throw(t))return true;return false}e(_t,(function(e){if(this.extends&&this.extends.may_throw(e))return true;return any(this.properties,e)}));e(nt,(function(e){return any(this.elements,e)}));e(et,(function(e){if(this.right.may_throw(e))return true;if(!e.has_directive("use strict")&&this.operator=="="&&this.left instanceof It){return false}return this.left.may_throw(e)}));e(Qe,(function(e){return this.left.may_throw(e)||this.right.may_throw(e)}));e(H,(function(e){return any(this.body,e)}));e(ze,(function(e){if(this.optional&&is_nullish(this.expression,e))return false;if(any(this.args,e))return true;if(this.is_callee_pure(e))return false;if(this.expression.may_throw(e))return true;return!(this.expression instanceof ae)||any(this.expression.body,e)}));e(Re,(function(e){return this.expression.may_throw(e)||any(this.body,e)}));e(Je,(function(e){return this.condition.may_throw(e)||this.consequent.may_throw(e)||this.alternative.may_throw(e)}));e(xe,(function(e){return any(this.definitions,e)}));e(ye,(function(e){return this.condition.may_throw(e)||this.body&&this.body.may_throw(e)||this.alternative&&this.alternative.may_throw(e)}));e(Y,(function(e){return this.body.may_throw(e)}));e(rt,(function(e){return any(this.properties,e)}));e(it,(function(e){return this.value?this.value.may_throw(e):false}));e(pt,(function(e){return this.computed_key()&&this.key.may_throw(e)||this.static&&this.value&&this.value.may_throw(e)}));e(ct,(function(e){return this.computed_key()&&this.key.may_throw(e)}));e(lt,(function(e){return this.computed_key()&&this.key.may_throw(e)}));e(ut,(function(e){return this.computed_key()&&this.key.may_throw(e)}));e(Ee,(function(e){return this.value&&this.value.may_throw(e)}));e(Ge,(function(e){return any(this.expressions,e)}));e(G,(function(e){return this.body.may_throw(e)}));e(Xe,(function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)}));e(qe,(function(e){if(this.optional&&is_nullish(this.expression,e))return false;return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)||this.property.may_throw(e)}));e(Ye,(function(e){return this.expression.may_throw(e)}));e(Te,(function(e){return this.expression.may_throw(e)||any(this.body,e)}));e(It,(function(e){return!this.is_declared(e)&&!Pn.has(this.name)}));e(Ct,return_false);e(Fe,(function(e){return this.bcatch?this.bcatch.may_throw(e):any(this.body,e)||this.bfinally&&this.bfinally.may_throw(e)}));e(je,(function(e){if(this.operator=="typeof"&&this.expression instanceof It)return false;return this.expression.may_throw(e)}));e(Pe,(function(e){if(!this.value)return false;return this.value.may_throw(e)}))})((function(e,t){e.DEFMETHOD("may_throw",t)}));(function(e){function all_refs_local(e){let t=true;walk(this,(n=>{if(n instanceof It){if(has_flag(this,Sn)){t=false;return tn}var r=n.definition();if(member(r,this.enclosed)&&!this.variables.has(r.name)){if(e){var i=e.find_variable(n);if(r.undeclared?!i:i===r){t="f";return true}}t=false;return tn}return true}if(n instanceof Vt&&this instanceof le){t=false;return tn}}));return t}e(V,return_false);e(zt,return_true);e(_t,(function(e){if(this.extends&&!this.extends.is_constant_expression(e)){return false}for(const t of this.properties){if(t.computed_key()&&!t.key.is_constant_expression(e)){return false}if(t.static&&t.value&&!t.value.is_constant_expression(e)){return false}}return all_refs_local.call(this,e)}));e(ae,all_refs_local);e(je,(function(){return this.expression.is_constant_expression()}));e(Qe,(function(){return this.left.is_constant_expression()&&this.right.is_constant_expression()}));e(nt,(function(){return this.elements.every((e=>e.is_constant_expression()))}));e(rt,(function(){return this.properties.every((e=>e.is_constant_expression()))}));e(it,(function(){return!!(!(this.key instanceof V)&&this.value&&this.value.is_constant_expression())}))})((function(e,t){e.DEFMETHOD("is_constant_expression",t)}));function aborts(e){return e&&e.aborts()}(function(e){e(U,return_null);e(me,return_this);function block_aborts(){for(var e=0;e{if(e instanceof vt){const n=e.definition();if((t||n.global)&&!a.has(n.id)){a.set(n.id,n)}}}))}if(n.value){if(n.name instanceof fe){n.walk(f)}else{var i=n.name.definition();map_add(l,i.id,n.value);if(!i.chained&&n.name.fixed_value()===n.value){s.set(i.id,n)}}if(n.value.has_side_effects(e)){n.value.walk(f)}}}));return true}return scan_ref_scoped(i,o)}));t.walk(f);f=new TreeWalker(scan_ref_scoped);a.forEach((function(e){var t=l.get(e.id);if(t)t.forEach((function(e){e.walk(f)}))}));var _=new TreeTransformer((function before(l,f,p){var d=_.parent();if(r){const e=o(l);if(e instanceof It){var m=e.definition();var h=a.has(m.id);if(l instanceof et){if(!h||s.has(m.id)&&s.get(m.id)!==l){return maintain_this_binding(d,l,l.right.transform(_))}}else if(!h)return p?i.skip:make_node(Gt,l,{value:0})}}if(c!==t)return;var m;if(l.name&&(l instanceof ht&&!keep_name(e.option("keep_classnames"),(m=l.name.definition()).name)||l instanceof ue&&!keep_name(e.option("keep_fnames"),(m=l.name.definition()).name))){if(!a.has(m.id)||m.orig.length>1)l.name=null}if(l instanceof ae&&!(l instanceof se)){var E=!e.option("keep_fargs");for(var g=l.argnames,v=g.length;--v>=0;){var D=g[v];if(D instanceof oe){D=D.expression}if(D instanceof tt){D=D.left}if(!(D instanceof fe)&&!a.has(D.definition().id)){set_flag(D,gn);if(E){g.pop()}}else{E=false}}}if((l instanceof ce||l instanceof mt)&&l!==t){const t=l.name.definition();let r=t.global&&!n||a.has(t.id);if(!r){t.eliminated++;if(l instanceof mt){const t=l.drop_side_effect_free(e);if(t){return make_node(G,l,{body:t})}}return p?i.skip:make_node(W,l)}}if(l instanceof xe&&!(d instanceof ee&&d.init===l)){var b=!(d instanceof ie)&&!(l instanceof Ne);var S=[],A=[],y=[];var T=[];l.definitions.forEach((function(t){if(t.value)t.value=t.value.transform(_);var n=t.name instanceof fe;var i=n?new SymbolDef(null,{name:""}):t.name.definition();if(b&&i.global)return y.push(t);if(!(r||b)||n&&(t.name.names.length||t.name.is_array||e.option("pure_getters")!=true)||a.has(i.id)){if(t.value&&s.has(i.id)&&s.get(i.id)!==t){t.value=t.value.drop_side_effect_free(e)}if(t.name instanceof Dt){var o=u.get(i.id);if(o.length>1&&(!t.value||i.orig.indexOf(t.name)>i.eliminated)){if(t.value){var c=make_node(It,t.name,t.name);i.references.push(c);var f=make_node(et,t,{operator:"=",logical:false,left:c,right:t.value});if(s.get(i.id)===t){s.set(i.id,f)}T.push(f.transform(_))}remove(o,t);i.eliminated++;return}}if(t.value){if(T.length>0){if(y.length>0){T.push(t.value);t.value=make_sequence(t.value,T)}else{S.push(make_node(G,l,{body:make_sequence(l,T)}))}T=[]}y.push(t)}else{A.push(t)}}else if(i.orig[0]instanceof Mt){var p=t.value&&t.value.drop_side_effect_free(e);if(p)T.push(p);t.value=null;A.push(t)}else{var p=t.value&&t.value.drop_side_effect_free(e);if(p){T.push(p)}i.eliminated++}}));if(A.length>0||y.length>0){l.definitions=A.concat(y);S.push(l)}if(T.length>0){S.push(make_node(G,l,{body:make_sequence(l,T)}))}switch(S.length){case 0:return p?i.skip:make_node(W,l);case 1:return S[0];default:return p?i.splice(S):make_node(X,l,{body:S})}}if(l instanceof J){f(l,this);var k;if(l.init instanceof X){k=l.init;l.init=k.body.pop();k.body.push(l)}if(l.init instanceof G){l.init=l.init.body}else if(is_empty(l.init)){l.init=null}return!k?l:p?i.splice(k.body):k}if(l instanceof Y&&l.body instanceof J){f(l,this);if(l.body instanceof X){var k=l.body;l.body=k.body.pop();k.body.push(l);return p?i.splice(k.body):k}return l}if(l instanceof X){f(l,this);if(p&&l.body.every(can_be_evicted_from_block)){return i.splice(l.body)}return l}if(l instanceof re){const e=c;c=l;f(l,this);c=e;return l}}));t.transform(_);function scan_ref_scoped(e,n){var r;const i=o(e);if(i instanceof It&&!is_ref_of(e.left,bt)&&t.variables.get(i.name)===(r=i.definition())){if(e instanceof et){e.right.walk(f);if(!r.chained&&e.left.fixed_value()===e.right){s.set(r.id,e)}}return true}if(e instanceof It){r=e.definition();if(!a.has(r.id)){a.set(r.id,r);if(r.orig[0]instanceof Mt){const e=r.scope.is_block_scope()&&r.scope.get_defun_scope().variables.get(r.name);if(e)a.set(e.id,e)}}return true}if(e instanceof re){var u=c;c=e;n();c=u;return true}}}));re.DEFMETHOD("hoist_declarations",(function(e){var t=this;if(e.has_directive("use asm"))return t;if(!Array.isArray(t.body))return t;var n=e.option("hoist_funs");var r=e.option("hoist_vars");if(n||r){var i=[];var o=[];var a=new Map,s=0,u=0;walk(t,(e=>{if(e instanceof re&&e!==t)return true;if(e instanceof Ne){++u;return true}}));r=r&&u>1;var l=new TreeTransformer((function before(u){if(u!==t){if(u instanceof K){i.push(u);return make_node(W,u)}if(n&&u instanceof ce&&!(l.parent()instanceof Ue)&&l.parent()===t){o.push(u);return make_node(W,u)}if(r&&u instanceof Ne&&!u.definitions.some((e=>e.name instanceof fe))){u.definitions.forEach((function(e){a.set(e.name.name,e);++s}));var c=u.to_assignments(e);var f=l.parent();if(f instanceof ee&&f.init===u){if(c==null){var _=u.definitions[0].name;return make_node(It,_,_)}return c}if(f instanceof J&&f.init===u){return c}if(!c)return make_node(W,u);return make_node(G,u,{body:c})}if(u instanceof re)return u}}));t=t.transform(l);if(s>0){var c=[];const e=t instanceof ae;const n=e?t.args_as_names():null;a.forEach(((t,r)=>{if(e&&n.some((e=>e.name===t.name.name))){a.delete(r)}else{t=t.clone();t.value=null;c.push(t);a.set(r,t)}}));if(c.length>0){for(var f=0;fe instanceof oe||e.computed_key()))){s(a,this);const e=new Map;const n=[];c.properties.forEach((({key:r,value:i})=>{const s=find_scope(o);const l=t.create_symbol(u.CTOR,{source:u,scope:s,conflict_scopes:new Set([s,...u.definition().references.map((e=>e.scope))]),tentative_name:u.name+"_"+r});e.set(String(r),l.definition());n.push(make_node(Pe,a,{name:l,value:i}))}));r.set(l.id,e);return i.splice(n)}}else if(a instanceof He&&a.expression instanceof It){const e=r.get(a.expression.definition().id);if(e){const t=e.get(String(get_value(a.property)));const n=make_node(It,a,{name:t.name,scope:a.expression.scope,thedef:t});n.reference({});return n}}}));return t.transform(o)}));(function(e){function trim(e,t,n){var r=e.length;if(!r)return null;var i=[],o=false;for(var a=0;a0){a[0].body=o.concat(a[0].body)}e.body=a;while(n=a[a.length-1]){var d=n.body[n.body.length-1];if(d instanceof De&&t.loopcontrol_target(d)===e)n.body.pop();if(n.body.length||n instanceof Re&&(s||n.expression.has_side_effects(t)))break;if(a.pop()===s)s=null}if(a.length==0){return make_node(X,e,{body:o.concat(make_node(G,e.expression,{body:e.expression}))}).optimize(t)}if(a.length==1&&(a[0]===u||a[0]===s)){var m=false;var h=new TreeWalker((function(t){if(m||t instanceof ae||t instanceof G)return true;if(t instanceof De&&h.loopcontrol_target(t)===e)m=true}));e.walk(h);if(!m){var E=a[0].body.slice();var f=a[0].expression;if(f)E.unshift(make_node(G,f,{body:f}));E.unshift(make_node(G,e.expression,{body:e.expression}));return make_node(X,e,{body:E}).optimize(t)}}return e;function eliminate_branch(e,n){if(n&&!aborts(n)){n.body=n.body.concat(e.body)}else{trim_unreachable_code(t,e,o)}}}));def_optimize(Fe,(function(e,t){tighten_body(e.body,t);if(e.bcatch&&e.bfinally&&e.bfinally.body.every(is_empty))e.bfinally=null;if(t.option("dead_code")&&e.body.every(is_empty)){var n=[];if(e.bcatch){trim_unreachable_code(t,e.bcatch,n)}if(e.bfinally)n.push(...e.bfinally.body);return make_node(X,e,{body:n}).optimize(t)}return e}));xe.DEFMETHOD("remove_initializers",(function(){var e=[];this.definitions.forEach((function(t){if(t.name instanceof vt){t.value=null;e.push(t)}else{walk(t.name,(n=>{if(n instanceof vt){e.push(make_node(Pe,t,{name:n,value:null}))}}))}}));this.definitions=e}));xe.DEFMETHOD("to_assignments",(function(e){var t=e.option("reduce_vars");var n=[];for(const e of this.definitions){if(e.value){var r=make_node(It,e.name,e.name);n.push(make_node(et,e,{operator:"=",logical:false,left:r,right:e.value}));if(t)r.definition().fixed=false}else if(e.value){var i=make_node(Pe,e,{name:e.name,value:e.value});var o=make_node(Ne,e,{definitions:[i]});n.push(o)}const a=e.name.definition();a.eliminated++;a.replaced--}if(n.length==0)return null;return make_sequence(this,n)}));def_optimize(xe,(function(e){if(e.definitions.length==0)return make_node(W,e);return e}));def_optimize(Pe,(function(e,t){if(e.name instanceof At&&e.value!=null&&is_undefined(e.value,t)){e.value=null}return e}));def_optimize(Le,(function(e){return e}));function retain_top_func(e,t){return t.top_retain&&e instanceof ce&&has_flag(e,kn)&&e.name&&t.top_retain(e.name)}def_optimize(ze,(function(e,t){var n=e.expression;var r=n;inline_array_like_spread(e.args);var i=e.args.every((e=>!(e instanceof oe)));if(t.option("reduce_vars")&&r instanceof It&&!has_annotation(e,on)){const e=r.fixed_value();if(!retain_top_func(e,t)){r=e}}if(e.optional&&is_nullish(r,t)){return make_node(jt,e)}var o=r instanceof ae;if(o&&r.pinned())return e;if(t.option("unused")&&i&&o&&!r.uses_arguments){var a=0,s=0;for(var u=0,l=e.args.length;u=r.argnames.length;if(f||has_flag(r.argnames[u],gn)){var c=e.args[u].drop_side_effect_free(t);if(c){e.args[a++]=c}else if(!f){e.args[a++]=make_node(Gt,e.args[u],{value:0});continue}}else{e.args[a++]=e.args[u]}s=a}e.args.length=s}if(t.option("unsafe")){if(is_undeclared_ref(n))switch(n.name){case"Array":if(e.args.length!=1){return make_node(nt,e,{elements:e.args}).optimize(t)}else if(e.args[0]instanceof Gt&&e.args[0].value<=11){const t=[];for(let n=0;n=1&&e.args.length<=2&&e.args.every((e=>{var n=e.evaluate(t);_.push(n);return e!==n}))){let[n,r]=_;n=regexp_source_fix(new RegExp(n).source);const i=make_node(Xt,e,{value:{source:n,flags:r}});if(i._eval(t)!==i){return i}}break}else if(n instanceof Xe)switch(n.property){case"toString":if(e.args.length==0&&!n.expression.may_throw_on_access(t)){return make_node(Qe,e,{left:make_node(Kt,e,{value:""}),operator:"+",right:n.expression}).optimize(t)}break;case"join":if(n.expression instanceof nt)e:{var p;if(e.args.length>0){p=e.args[0].evaluate(t);if(p===e.args[0])break e}var d=[];var m=[];for(var u=0,l=n.expression.elements.length;u0){d.push(make_node(Kt,e,{value:m.join(p)}));m.length=0}d.push(h)}}if(m.length>0){d.push(make_node(Kt,e,{value:m.join(p)}))}if(d.length==0)return make_node(Kt,e,{value:""});if(d.length==1){if(d[0].is_string(t)){return d[0]}return make_node(Qe,d[0],{operator:"+",left:make_node(Kt,e,{value:""}),right:d[0]})}if(p==""){var g;if(d[0].is_string(t)||d[1].is_string(t)){g=d.shift()}else{g=make_node(Kt,e,{value:""})}return d.reduce((function(e,t){return make_node(Qe,t,{operator:"+",left:e,right:t})}),g).optimize(t)}var c=e.clone();c.expression=c.expression.clone();c.expression.expression=c.expression.expression.clone();c.expression.expression.elements=d;return best_of(t,e,c)}break;case"charAt":if(n.expression.is_string(t)){var v=e.args[0];var D=v?v.evaluate(t):0;if(D!==v){return make_node(qe,n,{expression:n.expression,property:make_node_from_constant(D|0,v||n)}).optimize(t)}}break;case"apply":if(e.args.length==2&&e.args[1]instanceof nt){var b=e.args[1].elements.slice();b.unshift(e.args[0]);return make_node(ze,e,{expression:make_node(Xe,n,{expression:n.expression,optional:false,property:"call"}),args:b}).optimize(t)}break;case"call":var S=n.expression;if(S instanceof It){S=S.fixed_value()}if(S instanceof ae&&!S.contains_this()){return(e.args.length?make_sequence(this,[e.args[0],make_node(ze,e,{expression:n.expression,args:e.args.slice(1)})]):make_node(ze,e,{expression:n.expression,args:[]})).optimize(t)}break}}if(t.option("unsafe_Function")&&is_undeclared_ref(n)&&n.name=="Function"){if(e.args.length==0)return make_node(ue,e,{argnames:[],body:[]}).optimize(t);if(e.args.every((e=>e instanceof Kt))){try{var A="n(function("+e.args.slice(0,-1).map((function(e){return e.value})).join(",")+"){"+e.args[e.args.length-1].value+"})";var y=parse(A);var T={ie8:t.option("ie8")};y.figure_out_scope(T);var k=new Compressor(t.options,{mangle_options:t.mangle_options});y=y.transform(k);y.figure_out_scope(T);hn.reset();y.compute_char_frequency(T);y.mangle_names(T);var C;walk(y,(e=>{if(is_func_expr(e)){C=e;return tn}}));var A=OutputStream();X.prototype._codegen.call(C,C,A);e.args=[make_node(Kt,e,{value:C.argnames.map((function(e){return e.print_to_string()})).join(",")}),make_node(Kt,e.args[e.args.length-1],{value:A.get().replace(/^{|}$/g,"")})];return e}catch(e){if(!(e instanceof JS_Parse_Error)){throw e}}}}var R=o&&r.body[0];var F=o&&!r.is_generator&&!r.async;var O=F&&t.option("inline")&&!e.is_callee_pure(t);if(O&&R instanceof Ee){let n=R.value;if(!n||n.is_constant_expression()){if(n){n=n.clone(true)}else{n=make_node(jt,e)}const r=e.args.concat(n);return make_sequence(e,r).optimize(t)}if(r.argnames.length===1&&r.argnames[0]instanceof yt&&e.args.length<2&&n instanceof It&&n.name===r.argnames[0].name){const n=(e.args[0]||make_node(jt)).optimize(t);let r;if(n instanceof He&&(r=t.parent())instanceof ze&&r.expression===e){return make_sequence(e,[make_node(Gt,e,{value:0}),n])}return n}}if(O){var M,x,N=-1;let o;let a;let s;if(i&&!r.uses_arguments&&!(t.parent()instanceof _t)&&!(r.name&&r instanceof ue)&&(a=can_flatten_body(R))&&(n===r||has_annotation(e,rn)||t.option("unused")&&(o=n.definition()).references.length==1&&!recursive_ref(t,o)&&r.is_constant_expression(n.scope))&&!has_annotation(e,nn|on)&&!r.contains_this()&&can_inject_symbols()&&(s=find_scope(t))&&!scope_encloses_variables_in_this_scope(s,r)&&!function in_default_assign(){let e=0;let n;while(n=t.parent(e++)){if(n instanceof tt)return true;if(n instanceof H)break}return false}()&&!(M instanceof _t)){set_flag(r,yn);s.add_child_scope(r);return make_sequence(e,flatten_fn(a)).optimize(t)}}if(O&&has_annotation(e,rn)){set_flag(r,yn);r=make_node(r.CTOR===ce?ue:r.CTOR,r,r);r.figure_out_scope({},{parent_scope:find_scope(t),toplevel:t.get_toplevel()});return make_node(ze,e,{expression:r,args:e.args}).optimize(t)}const w=F&&t.option("side_effects")&&r.body.every(is_empty);if(w){var b=e.args.concat(make_node(jt,e));return make_sequence(e,b).optimize(t)}if(t.option("negate_iife")&&t.parent()instanceof G&&is_iife_call(e)){return e.negate(t,true)}var I=e.evaluate(t);if(I!==e){I=make_node_from_constant(I,e).optimize(t);return best_of(t,I,e)}return e;function return_value(t){if(!t)return make_node(jt,e);if(t instanceof Ee){if(!t.value)return make_node(jt,e);return t.value.clone(true)}if(t instanceof G){return make_node($e,t,{operator:"void",expression:t.body.clone(true)})}}function can_flatten_body(e){var n=r.body;var i=n.length;if(t.option("inline")<3){return i==1&&return_value(e)}e=null;for(var o=0;o!e.value))){return false}}else if(e){return false}else if(!(a instanceof W)){e=a}}return return_value(e)}function can_inject_args(e,t){for(var n=0,i=r.argnames.length;n=0;){var s=o.definitions[a].name;if(s instanceof fe||e.has(s.name)||Fn.has(s.name)||M.conflicting_def(s.name)){return false}if(x)x.push(s.definition())}}return true}function can_inject_symbols(){var e=new Set;do{M=t.parent(++N);if(M.is_block_scope()&&M.block_scope){M.block_scope.variables.forEach((function(t){e.add(t.name)}))}if(M instanceof Oe){if(M.argname){e.add(M.argname.name)}}else if(M instanceof j){x=[]}else if(M instanceof It){if(M.fixed_value()instanceof re)return false}}while(!(M instanceof re));var n=!(M instanceof ie)||t.toplevel.vars;var i=t.option("inline");if(!can_inject_vars(e,i>=3&&n))return false;if(!can_inject_args(e,i>=2&&n))return false;return!x||x.length==0||!is_reachable(r,x)}function append_var(t,n,r,i){var o=r.definition();const a=M.variables.has(r.name);if(!a){M.variables.set(r.name,o);M.enclosed.push(o);t.push(make_node(Pe,r,{name:r,value:null}))}var s=make_node(It,r,r);o.references.push(s);if(i)n.push(make_node(et,e,{operator:"=",logical:false,left:s,right:i.clone()}))}function flatten_args(t,n){var i=r.argnames.length;for(var o=e.args.length;--o>=i;){n.push(e.args[o])}for(o=i;--o>=0;){var a=r.argnames[o];var s=e.args[o];if(has_flag(a,gn)||!a.name||M.conflicting_def(a.name)){if(s)n.push(s)}else{var u=make_node(Dt,a,a);a.definition().orig.push(u);if(!s&&x)s=make_node(jt,e);append_var(t,n,u,s)}}t.reverse();n.reverse()}function flatten_vars(e,t){var n=t.length;for(var i=0,o=r.body.length;ie.name!=c.name))){var f=r.variables.get(c.name);var _=make_node(It,c,c);f.references.push(_);t.splice(n++,0,make_node(et,l,{operator:"=",logical:false,left:_,right:make_node(jt,c)}))}}}}function flatten_fn(e){var n=[];var i=[];flatten_args(n,i);flatten_vars(n,i);i.push(e);if(n.length){const e=M.body.indexOf(t.parent(N-1))+1;M.body.splice(e,0,make_node(Ne,r,{definitions:n}))}return i.map((e=>e.clone(true)))}}));def_optimize(Ke,(function(e,t){if(t.option("unsafe")&&is_undeclared_ref(e.expression)&&["Object","RegExp","Function","Error","Array"].includes(e.expression.name))return make_node(ze,e,e).transform(t);return e}));def_optimize(Ge,(function(e,t){if(!t.option("side_effects"))return e;var n=[];filter_for_side_effects();var r=n.length-1;trim_right_for_undefined();if(r==0){e=maintain_this_binding(t.parent(),t.self(),n[0]);if(!(e instanceof Ge))e=e.optimize(t);return e}e.expressions=n;return e;function filter_for_side_effects(){var r=first_in_statement(t);var i=e.expressions.length-1;e.expressions.forEach((function(e,o){if(o0&&is_undefined(n[r],t))r--;if(r0){var n=this.clone();n.right=make_sequence(this.right,t.slice(o));t=t.slice(0,o);t.push(n);return make_sequence(this,t).optimize(e)}}}return this}));var Vn=makePredicate("== === != !== * & | ^");function is_object(e){return e instanceof nt||e instanceof ae||e instanceof rt||e instanceof _t}def_optimize(Qe,(function(e,t){function reversible(){return e.left.is_constant()||e.right.is_constant()||!e.left.has_side_effects(t)&&!e.right.has_side_effects(t)}function reverse(t){if(reversible()){if(t)e.operator=t;var n=e.left;e.left=e.right;e.right=n}}if(Vn.has(e.operator)){if(e.right.is_constant()&&!e.left.is_constant()){if(!(e.left instanceof Qe&&w[e.left.operator]>=w[e.operator])){reverse()}}}e=e.lift_sequences(t);if(t.option("comparisons"))switch(e.operator){case"===":case"!==":var n=true;if(e.left.is_string(t)&&e.right.is_string(t)||e.left.is_number(t)&&e.right.is_number(t)||e.left.is_boolean()&&e.right.is_boolean()||e.left.equivalent_to(e.right)){e.operator=e.operator.substr(0,2)}case"==":case"!=":if(!n&&is_undefined(e.left,t)){e.left=make_node(qt,e.left)}else if(t.option("typeofs")&&e.left instanceof Kt&&e.left.value=="undefined"&&e.right instanceof $e&&e.right.operator=="typeof"){var r=e.right.expression;if(r instanceof It?r.is_declared(t):!(r instanceof He&&t.option("ie8"))){e.right=r;e.left=make_node(jt,e.left).optimize(t);if(e.operator.length==2)e.operator+="="}}else if(e.left instanceof It&&e.right instanceof It&&e.left.definition()===e.right.definition()&&is_object(e.left.fixed_value())){return make_node(e.operator[0]=="="?en:Jt,e)}break;case"&&":case"||":var i=e.left;if(i.operator==e.operator){i=i.right}if(i instanceof Qe&&i.operator==(e.operator=="&&"?"!==":"===")&&e.right instanceof Qe&&i.operator==e.right.operator&&(is_undefined(i.left,t)&&e.right.left instanceof qt||i.left instanceof qt&&is_undefined(e.right.left,t))&&!i.right.has_side_effects(t)&&i.right.equivalent_to(e.right.right)){var o=make_node(Qe,e,{operator:i.operator.slice(0,-1),left:make_node(qt,e),right:i.right});if(i!==e.left){o=make_node(Qe,e,{operator:e.operator,left:e.left.left,right:o})}return o}break}if(e.operator=="+"&&t.in_boolean_context()){var a=e.left.evaluate(t);var s=e.right.evaluate(t);if(a&&typeof a=="string"){return make_sequence(e,[e.right,make_node(en,e)]).optimize(t)}if(s&&typeof s=="string"){return make_sequence(e,[e.left,make_node(en,e)]).optimize(t)}}if(t.option("comparisons")&&e.is_boolean()){if(!(t.parent()instanceof Qe)||t.parent()instanceof et){var u=make_node($e,e,{operator:"!",expression:e.negate(t,first_in_statement(t))});e=best_of(t,e,u)}if(t.option("unsafe_comps")){switch(e.operator){case"<":reverse(">");break;case"<=":reverse(">=");break}}}if(e.operator=="+"){if(e.right instanceof Kt&&e.right.getValue()==""&&e.left.is_string(t)){return e.left}if(e.left instanceof Kt&&e.left.getValue()==""&&e.right.is_string(t)){return e.right}if(e.left instanceof Qe&&e.left.operator=="+"&&e.left.left instanceof Kt&&e.left.left.getValue()==""&&e.right.is_string(t)){e.left=e.left.right;return e}}if(t.option("evaluate")){switch(e.operator){case"&&":var a=has_flag(e.left,vn)?true:has_flag(e.left,Dn)?false:e.left.evaluate(t);if(!a){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}else if(!(a instanceof V)){return make_sequence(e,[e.left,e.right]).optimize(t)}var s=e.right.evaluate(t);if(!s){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(Jt,e)]).optimize(t)}else{set_flag(e,Dn)}}else if(!(s instanceof V)){var l=t.parent();if(l.operator=="&&"&&l.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}if(e.left.operator=="||"){var c=e.left.right.evaluate(t);if(!c)return make_node(Je,e,{condition:e.left.left,consequent:e.right,alternative:e.left.right}).optimize(t)}break;case"||":var a=has_flag(e.left,vn)?true:has_flag(e.left,Dn)?false:e.left.evaluate(t);if(!a){return make_sequence(e,[e.left,e.right]).optimize(t)}else if(!(a instanceof V)){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}var s=e.right.evaluate(t);if(!s){var l=t.parent();if(l.operator=="||"&&l.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}else if(!(s instanceof V)){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(en,e)]).optimize(t)}else{set_flag(e,vn)}}if(e.left.operator=="&&"){var c=e.left.right.evaluate(t);if(c&&!(c instanceof V))return make_node(Je,e,{condition:e.left.left,consequent:e.left.right,alternative:e.right}).optimize(t)}break;case"??":if(is_nullish(e.left,t)){return e.right}var a=e.left.evaluate(t);if(!(a instanceof V)){return a==null?e.right:e.left}if(t.in_boolean_context()){const n=e.right.evaluate(t);if(!(n instanceof V)&&!n){return e.left}}}var f=true;switch(e.operator){case"+":if(e.right instanceof zt&&e.left instanceof Qe&&e.left.operator=="+"&&e.left.is_string(t)){var _=make_node(Qe,e,{operator:"+",left:e.left.right,right:e.right});var p=_.optimize(t);if(_!==p){e=make_node(Qe,e,{operator:"+",left:e.left.left,right:p})}}if(e.left instanceof Qe&&e.left.operator=="+"&&e.left.is_string(t)&&e.right instanceof Qe&&e.right.operator=="+"&&e.right.is_string(t)){var _=make_node(Qe,e,{operator:"+",left:e.left.right,right:e.right.left});var d=_.optimize(t);if(_!==d){e=make_node(Qe,e,{operator:"+",left:make_node(Qe,e.left,{operator:"+",left:e.left.left,right:d}),right:e.right.right})}}if(e.right instanceof $e&&e.right.operator=="-"&&e.left.is_number(t)){e=make_node(Qe,e,{operator:"-",left:e.left,right:e.right.expression});break}if(e.left instanceof $e&&e.left.operator=="-"&&reversible()&&e.right.is_number(t)){e=make_node(Qe,e,{operator:"-",left:e.right,right:e.left.expression});break}if(e.left instanceof pe){var m=e.left;var p=e.right.evaluate(t);if(p!=e.right){m.segments[m.segments.length-1].value+=String(p);return m}}if(e.right instanceof pe){var p=e.right;var m=e.left.evaluate(t);if(m!=e.left){p.segments[0].value=String(m)+p.segments[0].value;return p}}if(e.left instanceof pe&&e.right instanceof pe){var m=e.left;var h=m.segments;var p=e.right;h[h.length-1].value+=p.segments[0].value;for(var E=1;E=w[e.operator])){var g=make_node(Qe,e,{operator:e.operator,left:e.right,right:e.left});if(e.right instanceof zt&&!(e.left instanceof zt)){e=best_of(t,g,e)}else{e=best_of(t,e,g)}}if(f&&e.is_number(t)){if(e.right instanceof Qe&&e.right.operator==e.operator){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left,right:e.right.left,start:e.left.start,end:e.right.left.end}),right:e.right.right})}if(e.right instanceof zt&&e.left instanceof Qe&&e.left.operator==e.operator){if(e.left.left instanceof zt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left.left,right:e.right,start:e.left.left.start,end:e.right.end}),right:e.left.right})}else if(e.left.right instanceof zt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left.right,right:e.right,start:e.left.right.start,end:e.right.end}),right:e.left.left})}}if(e.left instanceof Qe&&e.left.operator==e.operator&&e.left.right instanceof zt&&e.right instanceof Qe&&e.right.operator==e.operator&&e.right.left instanceof zt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:make_node(Qe,e.left.left,{operator:e.operator,left:e.left.right,right:e.right.left,start:e.left.right.start,end:e.right.left.end}),right:e.left.left}),right:e.right.right})}}}}if(e.right instanceof Qe&&e.right.operator==e.operator&&(On.has(e.operator)||e.operator=="+"&&(e.right.left.is_string(t)||e.left.is_string(t)&&e.right.right.is_string(t)))){e.left=make_node(Qe,e.left,{operator:e.operator,left:e.left.transform(t),right:e.right.left.transform(t)});e.right=e.right.right.transform(t);return e.transform(t)}var v=e.evaluate(t);if(v!==e){v=make_node_from_constant(v,e).optimize(t);return best_of(t,v,e)}return e}));def_optimize(Pt,(function(e){return e}));function recursive_ref(e,t){var n;for(var r=0;n=e.parent(r);r++){if(n instanceof ae||n instanceof _t){var i=n.name;if(i&&i.definition()===t)break}}return n}function within_array_or_object_literal(e){var t,n=0;while(t=e.parent(n++)){if(t instanceof U)return false;if(t instanceof nt||t instanceof ot||t instanceof rt){return true}}return false}def_optimize(It,(function(e,t){if(!t.option("ie8")&&is_undeclared_ref(e)&&!t.find_parent(ne)){switch(e.name){case"undefined":return make_node(jt,e).optimize(t);case"NaN":return make_node(Yt,e).optimize(t);case"Infinity":return make_node(Zt,e).optimize(t)}}const n=t.parent();if(t.option("reduce_vars")&&is_lhs(e,n)!==e){const o=e.definition();const a=find_scope(t);if(t.top_retain&&o.global&&t.top_retain(o)){o.fixed=false;o.single_use=false;return e}let s=e.fixed_value();let u=o.single_use&&!(n instanceof ze&&n.is_callee_pure(t)||has_annotation(n,on))&&!(n instanceof Ue&&s instanceof ae&&s.name);if(u&&s instanceof V){u=!s.has_side_effects(t)&&!s.may_throw(t)}if(u&&(s instanceof ae||s instanceof _t)){if(retain_top_func(s,t)){u=false}else if(o.scope!==e.scope&&(o.escaped==1||has_flag(s,Sn)||within_array_or_object_literal(t)||!t.option("reduce_funcs"))){u=false}else if(recursive_ref(t,o)){u=false}else if(o.scope!==e.scope||o.orig[0]instanceof yt){u=s.is_constant_expression(e.scope);if(u=="f"){var r=e.scope;do{if(r instanceof ce||is_func_expr(r)){set_flag(r,Sn)}}while(r=r.parent_scope)}}}if(u&&s instanceof ae){u=o.scope===e.scope&&!scope_encloses_variables_in_this_scope(a,s)||n instanceof ze&&n.expression===e&&!scope_encloses_variables_in_this_scope(a,s)&&!(s.name&&s.name.definition().recursive_refs>0)}if(u&&s){if(s instanceof mt){set_flag(s,yn);s=make_node(ht,s,s)}if(s instanceof ce){set_flag(s,yn);s=make_node(ue,s,s)}if(o.recursive_refs>0&&s.name instanceof Tt){const e=s.name.definition();let t=s.variables.get(s.name.name);let n=t&&t.orig[0];if(!(n instanceof Rt)){n=make_node(Rt,s.name,s.name);n.scope=s;s.name=n;t=s.def_function(n)}walk(s,(n=>{if(n instanceof It&&n.definition()===e){n.thedef=t;t.references.push(n)}}))}if((s instanceof ae||s instanceof _t)&&s.parent_scope!==a){s=s.clone(true,t.get_toplevel());a.add_child_scope(s)}return s.optimize(t)}if(s){let n;if(s instanceof Vt){if(!(o.orig[0]instanceof yt)&&o.references.every((e=>o.scope===e.scope))){n=s}}else{var i=s.evaluate(t);if(i!==s&&(t.option("unsafe_regexp")||!(i instanceof RegExp))){n=make_node_from_constant(i,s)}}if(n){const r=e.size(t);const i=n.size(t);let a=0;if(t.option("unused")&&!t.exposed(o)){a=(r+2+i)/(o.references.length-o.assignments)}if(i<=r+a){return n}}}}return e}));function scope_encloses_variables_in_this_scope(e,t){for(const n of t.enclosed){if(t.variables.has(n.name)){continue}const r=e.find_variable(n.name);if(r){if(r===n)continue;return true}}return false}function is_atomic(e,t){return e instanceof It||e.TYPE===t.TYPE}def_optimize(jt,(function(e,t){if(t.option("unsafe_undefined")){var n=find_variable(t,"undefined");if(n){var r=make_node(It,e,{name:"undefined",scope:n.scope,thedef:n});set_flag(r,bn);return r}}var i=is_lhs(t.self(),t.parent());if(i&&is_atomic(i,e))return e;return make_node($e,e,{operator:"void",expression:make_node(Gt,e,{value:0})})}));def_optimize(Zt,(function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&is_atomic(n,e))return e;if(t.option("keep_infinity")&&!(n&&!is_atomic(n,e))&&!find_variable(t,"Infinity")){return e}return make_node(Qe,e,{operator:"/",left:make_node(Gt,e,{value:1}),right:make_node(Gt,e,{value:0})})}));def_optimize(Yt,(function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&!is_atomic(n,e)||find_variable(t,"NaN")){return make_node(Qe,e,{operator:"/",left:make_node(Gt,e,{value:0}),right:make_node(Gt,e,{value:0})})}return e}));function is_reachable(e,t){const find_ref=e=>{if(e instanceof It&&member(e.definition(),t)){return tn}};return walk_parent(e,((t,n)=>{if(t instanceof re&&t!==e){var r=n.parent();if(r instanceof ze&&r.expression===t)return;if(walk(t,find_ref))return tn;return true}}))}const Un=makePredicate("+ - / * % >> << >>> | ^ &");const zn=makePredicate("* | ^ &");def_optimize(et,(function(e,t){if(e.logical){return e.lift_sequences(t)}var n;if(t.option("dead_code")&&e.left instanceof It&&(n=e.left.definition()).scope===t.find_parent(ae)){var r=0,i,o=e;do{i=o;o=t.parent(r++);if(o instanceof he){if(in_try(r,o))break;if(is_reachable(n.scope,[n]))break;if(e.operator=="=")return e.right;n.fixed=false;return make_node(Qe,e,{operator:e.operator.slice(0,-1),left:e.left,right:e.right}).optimize(t)}}while(o instanceof Qe&&o.right===i||o instanceof Ge&&o.tail_node()===i)}e=e.lift_sequences(t);if(e.operator=="="&&e.left instanceof It&&e.right instanceof Qe){if(e.right.left instanceof It&&e.right.left.name==e.left.name&&Un.has(e.right.operator)){e.operator=e.right.operator+"=";e.right=e.right.right}else if(e.right.right instanceof It&&e.right.right.name==e.left.name&&zn.has(e.right.operator)&&!e.right.left.has_side_effects(t)){e.operator=e.right.operator+"=";e.right=e.right.left}}return e;function in_try(n,r){var i=e.right;e.right=make_node(qt,i);var o=r.may_throw(t);e.right=i;var a=e.left.definition().scope;var s;while((s=t.parent(n++))!==a){if(s instanceof Fe){if(s.bfinally)return true;if(o&&s.bcatch)return true}}}}));def_optimize(tt,(function(e,t){if(!t.option("evaluate")){return e}var n=e.right.evaluate(t);if(n===undefined){e=e.left}else if(n!==e.right){n=make_node_from_constant(n,e.right);e.right=best_of_expression(n,e.right)}return e}));function is_nullish(e,t){let n;return e instanceof qt||is_undefined(e,t)||e instanceof It&&(n=e.definition().fixed)instanceof V&&is_nullish(n,t)||e instanceof He&&e.optional&&is_nullish(e.expression,t)||e instanceof ze&&e.optional&&is_nullish(e.expression,t)||e instanceof Ye&&is_nullish(e.expression,t)}function is_nullish_check(e,t,n){if(t.may_throw(n))return false;let r;if(e instanceof Qe&&e.operator==="=="&&((r=is_nullish(e.left,n)&&e.left)||(r=is_nullish(e.right,n)&&e.right))&&(r===e.left?e.right:e.left).equivalent_to(t)){return true}if(e instanceof Qe&&e.operator==="||"){let r;let i;const find_comparison=e=>{if(!(e instanceof Qe&&(e.operator==="==="||e.operator==="=="))){return false}let o=0;let a;if(e.left instanceof qt){o++;r=e;a=e.right}if(e.right instanceof qt){o++;r=e;a=e.left}if(is_undefined(e.left,n)){o++;i=e;a=e.right}if(is_undefined(e.right,n)){o++;i=e;a=e.left}if(o!==1){return false}if(!a.equivalent_to(t)){return false}return true};if(!find_comparison(e.left))return false;if(!find_comparison(e.right))return false;if(r&&i&&r!==i){return true}}return false}def_optimize(Je,(function(e,t){if(!t.option("conditionals"))return e;if(e.condition instanceof Ge){var n=e.condition.expressions.slice();e.condition=n.pop();n.push(e);return make_sequence(e,n)}var r=e.condition.evaluate(t);if(r!==e.condition){if(r){return maintain_this_binding(t.parent(),t.self(),e.consequent)}else{return maintain_this_binding(t.parent(),t.self(),e.alternative)}}var i=r.negate(t,first_in_statement(t));if(best_of(t,r,i)===i){e=make_node(Je,e,{condition:i,consequent:e.alternative,alternative:e.consequent})}var o=e.condition;var a=e.consequent;var s=e.alternative;if(o instanceof It&&a instanceof It&&o.definition()===a.definition()){return make_node(Qe,e,{operator:"||",left:o,right:s})}if(a instanceof et&&s instanceof et&&a.operator===s.operator&&a.logical===s.logical&&a.left.equivalent_to(s.left)&&(!e.condition.has_side_effects(t)||a.operator=="="&&!a.left.has_side_effects(t))){return make_node(et,e,{operator:a.operator,left:a.left,logical:a.logical,right:make_node(Je,e,{condition:e.condition,consequent:a.right,alternative:s.right})})}var u;if(a instanceof ze&&s.TYPE===a.TYPE&&a.args.length>0&&a.args.length==s.args.length&&a.expression.equivalent_to(s.expression)&&!e.condition.has_side_effects(t)&&!a.expression.has_side_effects(t)&&typeof(u=single_arg_diff())=="number"){var l=a.clone();l.args[u]=make_node(Je,e,{condition:e.condition,consequent:a.args[u],alternative:s.args[u]});return l}if(s instanceof Je&&a.equivalent_to(s.consequent)){return make_node(Je,e,{condition:make_node(Qe,e,{operator:"||",left:o,right:s.condition}),consequent:a,alternative:s.alternative}).optimize(t)}if(t.option("ecma")>=2020&&is_nullish_check(o,s,t)){return make_node(Qe,e,{operator:"??",left:s,right:a}).optimize(t)}if(s instanceof Ge&&a.equivalent_to(s.expressions[s.expressions.length-1])){return make_sequence(e,[make_node(Qe,e,{operator:"||",left:o,right:make_sequence(e,s.expressions.slice(0,-1))}),a]).optimize(t)}if(s instanceof Qe&&s.operator=="&&"&&a.equivalent_to(s.right)){return make_node(Qe,e,{operator:"&&",left:make_node(Qe,e,{operator:"||",left:o,right:s.left}),right:a}).optimize(t)}if(a instanceof Je&&a.alternative.equivalent_to(s)){return make_node(Je,e,{condition:make_node(Qe,e,{left:e.condition,operator:"&&",right:a.condition}),consequent:a.consequent,alternative:s})}if(a.equivalent_to(s)){return make_sequence(e,[e.condition,a]).optimize(t)}if(a instanceof Qe&&a.operator=="||"&&a.right.equivalent_to(s)){return make_node(Qe,e,{operator:"||",left:make_node(Qe,e,{operator:"&&",left:e.condition,right:a.left}),right:s}).optimize(t)}var c=t.in_boolean_context();if(is_true(e.consequent)){if(is_false(e.alternative)){return booleanize(e.condition)}return make_node(Qe,e,{operator:"||",left:booleanize(e.condition),right:e.alternative})}if(is_false(e.consequent)){if(is_true(e.alternative)){return booleanize(e.condition.negate(t))}return make_node(Qe,e,{operator:"&&",left:booleanize(e.condition.negate(t)),right:e.alternative})}if(is_true(e.alternative)){return make_node(Qe,e,{operator:"||",left:booleanize(e.condition.negate(t)),right:e.consequent})}if(is_false(e.alternative)){return make_node(Qe,e,{operator:"&&",left:booleanize(e.condition),right:e.consequent})}return e;function booleanize(e){if(e.is_boolean())return e;return make_node($e,e,{operator:"!",expression:e.negate(t)})}function is_true(e){return e instanceof en||c&&e instanceof zt&&e.getValue()||e instanceof $e&&e.operator=="!"&&e.expression instanceof zt&&!e.expression.getValue()}function is_false(e){return e instanceof Jt||c&&e instanceof zt&&!e.getValue()||e instanceof $e&&e.operator=="!"&&e.expression instanceof zt&&e.expression.getValue()}function single_arg_diff(){var e=a.args;var t=s.args;for(var n=0,r=e.length;n=2015;var r=this.expression;if(r instanceof rt){var i=r.properties;for(var o=i.length;--o>=0;){var a=i[o];if(""+(a instanceof ct?a.key.name:a.key)==e){const e=i.every((e=>(e instanceof ot||n&&e instanceof ct&&!e.is_generator)&&!e.computed_key()));if(!e)return;if(!safe_to_flatten(a.value,t))return;return make_node(qe,this,{expression:make_node(nt,r,{elements:i.map((function(e){var t=e.value;if(t instanceof se){t=make_node(ue,t,t)}var n=e.key;if(n instanceof V&&!(n instanceof kt)){return make_sequence(e,[n,t])}return t}))}),property:make_node(Gt,this,{value:o})})}}}}));def_optimize(qe,(function(e,t){var n=e.expression;var r=e.property;if(t.option("properties")){var i=r.evaluate(t);if(i!==r){if(typeof i=="string"){if(i=="undefined"){i=undefined}else{var o=parseFloat(i);if(o.toString()==i){i=o}}}r=e.property=best_of_expression(r,make_node_from_constant(i,r).transform(t));var a=""+i;if(is_basic_identifier_string(a)&&a.length<=r.size()+1){return make_node(Xe,e,{expression:n,optional:e.optional,property:a,quote:r.quote}).optimize(t)}}}var s;e:if(t.option("arguments")&&n instanceof It&&n.name=="arguments"&&n.definition().orig.length==1&&(s=n.scope)instanceof ae&&s.uses_arguments&&!(s instanceof le)&&r instanceof Gt){var u=r.getValue();var l=new Set;var c=s.argnames;for(var f=0;f1){p=null}}else if(!p&&!t.option("keep_fargs")&&u=s.argnames.length){p=s.create_symbol(yt,{source:s,scope:s,tentative_name:"argument_"+s.argnames.length});s.argnames.push(p)}}if(p){var m=make_node(It,e,p);m.reference({});clear_flag(p,gn);return m}}if(is_lhs(e,t.parent()))return e;if(i!==r){var h=e.flatten_object(a,t);if(h){n=e.expression=h.expression;r=e.property=h.property}}if(t.option("properties")&&t.option("side_effects")&&r instanceof Gt&&n instanceof nt){var u=r.getValue();var E=n.elements;var g=E[u];e:if(safe_to_flatten(g,t)){var v=true;var D=[];for(var b=E.length;--b>u;){var o=E[b].drop_side_effect_free(t);if(o){D.unshift(o);if(v&&o.has_side_effects(t))v=false}}if(g instanceof oe)break e;g=g instanceof $t?make_node(jt,g):g;if(!v)D.unshift(g);while(--b>=0){var o=E[b];if(o instanceof oe)break e;o=o.drop_side_effect_free(t);if(o)D.unshift(o);else u--}if(v){D.push(g);return make_sequence(e,D).optimize(t)}else return make_node(qe,e,{expression:make_node(nt,n,{elements:D}),property:make_node(Gt,r,{value:u})})}}var S=e.evaluate(t);if(S!==e){S=make_node_from_constant(S,e).optimize(t);return best_of(t,S,e)}if(e.optional&&is_nullish(e.expression,t)){return make_node(jt,e)}return e}));def_optimize(Ye,(function(e,t){e.expression=e.expression.optimize(t);return e}));ae.DEFMETHOD("contains_this",(function(){return walk(this,(e=>{if(e instanceof Vt)return tn;if(e!==this&&e instanceof re&&!(e instanceof le)){return true}}))}));def_optimize(Xe,(function(e,t){const n=t.parent();if(is_lhs(e,n))return e;if(t.option("unsafe_proto")&&e.expression instanceof Xe&&e.expression.property=="prototype"){var r=e.expression.expression;if(is_undeclared_ref(r))switch(r.name){case"Array":e.expression=make_node(nt,e.expression,{elements:[]});break;case"Function":e.expression=make_node(ue,e.expression,{argnames:[],body:[]});break;case"Number":e.expression=make_node(Gt,e.expression,{value:0});break;case"Object":e.expression=make_node(rt,e.expression,{properties:[]});break;case"RegExp":e.expression=make_node(Xt,e.expression,{value:{source:"t",flags:""}});break;case"String":e.expression=make_node(Kt,e.expression,{value:""});break}}if(!(n instanceof ze)||!has_annotation(n,on)){const n=e.flatten_object(e.property,t);if(n)return n.optimize(t)}let i=e.evaluate(t);if(i!==e){i=make_node_from_constant(i,e).optimize(t);return best_of(t,i,e)}if(e.optional&&is_nullish(e.expression,t)){return make_node(jt,e)}return e}));function literals_in_boolean_context(e,t){if(t.in_boolean_context()){return best_of(t,e,make_sequence(e,[e,make_node(en,e)]).optimize(t))}return e}function inline_array_like_spread(e){for(var t=0;te instanceof $t))){e.splice(t,1,...r.elements);t--}}}}def_optimize(nt,(function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_array_like_spread(e.elements);return e}));function inline_object_prop_spread(e,t){for(var n=0;ne instanceof ot))){e.splice(n,1,...i.properties);n--}else if(i instanceof zt&&!(i instanceof Kt)){e.splice(n,1)}else if(is_nullish(i,t)){e.splice(n,1)}}}}def_optimize(rt,(function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_object_prop_spread(e.properties,t);return e}));def_optimize(Xt,literals_in_boolean_context);def_optimize(Ee,(function(e,t){if(e.value&&is_undefined(e.value,t)){e.value=null}return e}));def_optimize(le,opt_AST_Lambda);def_optimize(ue,(function(e,t){e=opt_AST_Lambda(e,t);if(t.option("unsafe_arrows")&&t.option("ecma")>=2015&&!e.name&&!e.is_generator&&!e.uses_arguments&&!e.pinned()){const n=walk(e,(e=>{if(e instanceof Vt)return tn}));if(!n)return make_node(le,e,e).optimize(t)}return e}));def_optimize(_t,(function(e){return e}));def_optimize(Ae,(function(e,t){if(e.expression&&!e.is_star&&is_undefined(e.expression,t)){e.expression=null}return e}));def_optimize(pe,(function(e,t){if(!t.option("evaluate")||t.parent()instanceof _e){return e}var n=[];for(var r=0;r=2015&&(!(n instanceof RegExp)||n.test(e.key+""))){var r=e.key;var i=e.value;var o=i instanceof le&&Array.isArray(i.body)&&!i.contains_this();if((o||i instanceof ue)&&!i.name){return make_node(ct,e,{async:i.async,is_generator:i.is_generator,key:r instanceof V?r:make_node(kt,e,{name:r}),value:make_node(se,i,i),quote:e.quote})}}return e}));def_optimize(fe,(function(e,t){if(t.option("pure_getters")==true&&t.option("unused")&&!e.is_array&&Array.isArray(e.names)&&!is_destructuring_export_decl(t)&&!(e.names[e.names.length-1]instanceof oe)){var n=[];for(var r=0;r1)throw new Error("inline source map only works with singular input");t.sourceMap.content=read_source_map(e[o])}}}i=t.parse.toplevel}if(r&&t.mangle.properties.keep_quoted!=="strict"){reserve_quoted_keys(i,r)}if(t.wrap){i=i.wrap_commonjs(t.wrap)}if(t.enclose){i=i.wrap_enclose(t.enclose)}if(n)n.rename=Date.now();if(n)n.compress=Date.now();if(t.compress){i=new Compressor(t.compress,{mangle_options:t.mangle}).compress(i)}if(n)n.scope=Date.now();if(t.mangle)i.figure_out_scope(t.mangle);if(n)n.mangle=Date.now();if(t.mangle){hn.reset();i.compute_char_frequency(t.mangle);i.mangle_names(t.mangle)}if(n)n.properties=Date.now();if(t.mangle&&t.mangle.properties){i=mangle_properties(i,t.mangle.properties)}if(n)n.format=Date.now();var a={};if(t.format.ast){a.ast=i}if(t.format.spidermonkey){a.ast=i.to_mozilla_ast()}if(!HOP(t.format,"code")||t.format.code){if(t.sourceMap){t.format.source_map=await SourceMap({file:t.sourceMap.filename,orig:t.sourceMap.content,root:t.sourceMap.root});if(t.sourceMap.includeSources){if(e instanceof ie){throw new Error("original source content unavailable")}else for(var o in e)if(HOP(e,o)){t.format.source_map.get().setSourceContent(o,e[o])}}}delete t.format.ast;delete t.format.code;delete t.format.spidermonkey;var s=OutputStream(t.format);i.print(s);a.code=s.get();if(t.sourceMap){if(t.sourceMap.asObject){a.map=t.format.source_map.get().toJSON()}else{a.map=t.format.source_map.toString()}if(t.sourceMap.url=="inline"){var u=typeof a.map==="object"?JSON.stringify(a.map):a.map;a.code+="\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,"+Hn(u)}else if(t.sourceMap.url){a.code+="\n//# sourceMappingURL="+t.sourceMap.url}}}if(t.nameCache&&t.mangle){if(t.mangle.cache)t.nameCache.vars=cache_to_json(t.mangle.cache);if(t.mangle.properties&&t.mangle.properties.cache){t.nameCache.props=cache_to_json(t.mangle.properties.cache)}}if(t.format&&t.format.source_map){t.format.source_map.destroy()}if(n){n.end=Date.now();a.timings={parse:.001*(n.rename-n.parse),rename:.001*(n.compress-n.rename),compress:.001*(n.scope-n.compress),scope:.001*(n.mangle-n.scope),mangle:.001*(n.properties-n.mangle),properties:.001*(n.format-n.properties),format:.001*(n.end-n.format),total:.001*(n.end-n.start)}}return a}async function run_cli({program:e,packageJson:t,fs:r,path:i}){const o=new Set(["cname","parent_scope","scope","uses_eval","uses_with"]);var a={};var s={compress:false,mangle:false};const u=await _default_options();e.version(t.name+" "+t.version);e.parseArgv=e.parse;e.parse=undefined;if(process.argv.includes("ast"))e.helpInformation=describe_ast;else if(process.argv.includes("options"))e.helpInformation=function(){var e=[];for(var t in u){e.push("--"+(t==="sourceMap"?"source-map":t)+" options:");e.push(format_object(u[t]));e.push("")}return e.join("\n")};e.option("-p, --parse ","Specify parser options.",parse_js());e.option("-c, --compress [options]","Enable compressor/specify compressor options.",parse_js());e.option("-m, --mangle [options]","Mangle names/specify mangler options.",parse_js());e.option("--mangle-props [options]","Mangle properties/specify mangler options.",parse_js());e.option("-f, --format [options]","Format options.",parse_js());e.option("-b, --beautify [options]","Alias for --format.",parse_js());e.option("-o, --output ","Output file (default STDOUT).");e.option("--comments [filter]","Preserve copyright comments in the output.");e.option("--config-file ","Read minify() options from JSON file.");e.option("-d, --define [=value]","Global definitions.",parse_js("define"));e.option("--ecma ","Specify ECMAScript release: 5, 2015, 2016 or 2017...");e.option("-e, --enclose [arg[,...][:value[,...]]]","Embed output in a big function with configurable arguments and values.");e.option("--ie8","Support non-standard Internet Explorer 8.");e.option("--keep-classnames","Do not mangle/drop class names.");e.option("--keep-fnames","Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");e.option("--module","Input is an ES6 module");e.option("--name-cache ","File to hold mangled name mappings.");e.option("--rename","Force symbol expansion.");e.option("--no-rename","Disable symbol expansion.");e.option("--safari10","Support non-standard Safari 10.");e.option("--source-map [options]","Enable source map/specify source map options.",parse_js());e.option("--timings","Display operations run time on STDERR.");e.option("--toplevel","Compress and/or mangle variables in toplevel scope.");e.option("--wrap ","Embed everything as a function with “exports” corresponding to “name” globally.");e.arguments("[files...]").parseArgv(process.argv);if(e.configFile){s=JSON.parse(read_file(e.configFile))}if(!e.output&&e.sourceMap&&e.sourceMap.url!="inline"){fatal("ERROR: cannot write source map to STDOUT")}["compress","enclose","ie8","mangle","module","safari10","sourceMap","toplevel","wrap"].forEach((function(t){if(t in e){s[t]=e[t]}}));if("ecma"in e){if(e.ecma!=(e.ecma|0))fatal("ERROR: ecma must be an integer");const t=e.ecma|0;if(t>5&&t<2015)s.ecma=t+2009;else s.ecma=t}if(e.format||e.beautify){const t=e.format||e.beautify;s.format=typeof t==="object"?t:{}}if(e.comments){if(typeof s.format!="object")s.format={};s.format.comments=typeof e.comments=="string"?e.comments=="false"?false:e.comments:"some"}if(e.define){if(typeof s.compress!="object")s.compress={};if(typeof s.compress.global_defs!="object")s.compress.global_defs={};for(var l in e.define){s.compress.global_defs[l]=e.define[l]}}if(e.keepClassnames){s.keep_classnames=true}if(e.keepFnames){s.keep_fnames=true}if(e.mangleProps){if(e.mangleProps.domprops){delete e.mangleProps.domprops}else{if(typeof e.mangleProps!="object")e.mangleProps={};if(!Array.isArray(e.mangleProps.reserved))e.mangleProps.reserved=[]}if(typeof s.mangle!="object")s.mangle={};s.mangle.properties=e.mangleProps}if(e.nameCache){s.nameCache=JSON.parse(read_file(e.nameCache,"{}"))}if(e.output=="ast"){s.format={ast:true,code:false}}if(e.parse){if(!e.parse.acorn&&!e.parse.spidermonkey){s.parse=e.parse}else if(e.sourceMap&&e.sourceMap.content=="inline"){fatal("ERROR: inline source map only works with built-in parser")}}if(~e.rawArgs.indexOf("--rename")){s.rename=true}else if(!e.rename){s.rename=false}let convert_path=e=>e;if(typeof e.sourceMap=="object"&&"base"in e.sourceMap){convert_path=function(){var t=e.sourceMap.base;delete s.sourceMap.base;return function(e){return i.relative(t,e)}}()}let c;if(s.files&&s.files.length){c=s.files;delete s.files}else if(e.args.length){c=e.args}if(c){simple_glob(c).forEach((function(e){a[convert_path(e)]=read_file(e)}))}else{await new Promise((e=>{var t=[];process.stdin.setEncoding("utf8");process.stdin.on("data",(function(e){t.push(e)})).on("end",(function(){a=[t.join("")];e()}));process.stdin.resume()}))}await run_cli();function convert_ast(e){return V.from_mozilla_ast(Object.keys(a).reduce(e,null))}async function run_cli(){var t=e.sourceMap&&e.sourceMap.content;if(t&&t!=="inline"){s.sourceMap.content=read_file(t,t)}if(e.timings)s.timings=true;try{if(e.parse){if(e.parse.acorn){a=convert_ast((function(t,r){return n(988).parse(a[r],{ecmaVersion:2018,locations:true,program:t,sourceFile:r,sourceType:s.module||e.parse.module?"module":"script"})}))}else if(e.parse.spidermonkey){a=convert_ast((function(e,t){var n=JSON.parse(a[t]);if(!e)return n;e.body=e.body.concat(n.body);return e}))}}}catch(e){fatal(e)}let i;try{i=await minify(a,s)}catch(e){if(e.name=="SyntaxError"){print_error("Parse error at "+e.filename+":"+e.line+","+e.col);var u=e.col;var l=a[e.filename].split(/\r?\n/);var c=l[e.line-1];if(!c&&!u){c=l[e.line-2];u=c.length}if(c){var f=70;if(u>f){c=c.slice(u-f);u=f}print_error(c.slice(0,80));print_error(c.slice(0,u).replace(/\S/g," ")+"^")}}if(e.defs){print_error("Supported options:");print_error(format_object(e.defs))}fatal(e);return}if(e.output=="ast"){if(!s.compress&&!s.mangle){i.ast.figure_out_scope({})}console.log(JSON.stringify(i.ast,(function(e,t){if(t)switch(e){case"thedef":return symdef(t);case"enclosed":return t.length?t.map(symdef):undefined;case"variables":case"globals":return t.size?collect_from_map(t,symdef):undefined}if(o.has(e))return;if(t instanceof AST_Token)return;if(t instanceof Map)return;if(t instanceof V){var n={_class:"AST_"+t.TYPE};if(t.block_scope){n.variables=t.block_scope.variables;n.enclosed=t.block_scope.enclosed}t.CTOR.PROPS.forEach((function(e){n[e]=t[e]}));return n}return t}),2))}else if(e.output=="spidermonkey"){try{const e=await minify(i.code,{compress:false,mangle:false,format:{ast:true,code:false}});console.log(JSON.stringify(e.ast.to_mozilla_ast(),null,2))}catch(e){fatal(e);return}}else if(e.output){r.writeFileSync(e.output,i.code);if(s.sourceMap&&s.sourceMap.url!=="inline"&&i.map){r.writeFileSync(e.output+".map",i.map)}}else{console.log(i.code)}if(e.nameCache){r.writeFileSync(e.nameCache,JSON.stringify(s.nameCache))}if(i.timings)for(var _ in i.timings){print_error("- "+_+": "+i.timings[_].toFixed(3)+"s")}}function fatal(e){if(e instanceof Error)e=e.stack.replace(/^\S*?Error:/,"ERROR:");print_error(e);process.exit(1)}function simple_glob(e){if(Array.isArray(e)){return[].concat.apply([],e.map(simple_glob))}if(e&&e.match(/[*?]/)){var t=i.dirname(e);try{var n=r.readdirSync(t)}catch(e){}if(n){var o="^"+i.basename(e).replace(/[.+^$[\]\\(){}]/g,"\\$&").replace(/\*/g,"[^/\\\\]*").replace(/\?/g,"[^/\\\\]")+"$";var a=process.platform==="win32"?"i":"";var s=new RegExp(o,a);var u=n.filter((function(e){return s.test(e)})).map((function(e){return i.join(t,e)}));if(u.length)return u}}return[e]}function read_file(e,t){try{return r.readFileSync(e,"utf8")}catch(e){if((e.code=="ENOENT"||e.code=="ENAMETOOLONG")&&t!=null)return t;fatal(e)}}function parse_js(e){return function(t,n){n=n||{};try{walk(parse(t,{expression:true}),(t=>{if(t instanceof et){var r=t.left.print_to_string();var i=t.right;if(e){n[r]=i}else if(i instanceof nt){n[r]=i.elements.map(to_string)}else if(i instanceof Xt){i=i.value;n[r]=new RegExp(i.source,i.flags)}else{n[r]=to_string(i)}return true}if(t instanceof Et||t instanceof He){var r=t.print_to_string();n[r]=true;return true}if(!(t instanceof Ge))throw t;function to_string(e){return e instanceof zt?e.getValue():e.print_to_string({quote_keys:true})}}))}catch(r){if(e){fatal("Error parsing arguments for '"+e+"': "+t)}else{n[t]=null}}return n}}function symdef(e){var t=1e6+e.id+" "+e.name;if(e.mangled_name)t+=" "+e.mangled_name;return t}function collect_from_map(e,t){var n=[];e.forEach((function(e){n.push(t(e))}));return n}function format_object(e){var t=[];var n="";Object.keys(e).map((function(t){if(n.length!/^\$/.test(e)));if(n.length>0){e.space();e.with_parens((function(){n.forEach((function(t,n){if(n)e.space();e.print(t)}))}))}if(t.documentation){e.space();e.print_string(t.documentation)}if(t.SUBCLASSES.length>0){e.space();e.with_block((function(){t.SUBCLASSES.forEach((function(t){e.indent();doitem(t);e.newline()}))}))}}doitem(V);return e+"\n"}}async function _default_options(){const e={};Object.keys(infer_options({0:0})).forEach((t=>{const n=infer_options({[t]:{0:0}});if(n)e[t]=n}));return e}async function infer_options(e){try{await minify("",e)}catch(e){return e.defs}}e._default_options=_default_options;e._run_cli=run_cli;e.minify=minify}))}};var t={};function __nccwpck_require__(n){var r=t[n];if(r!==undefined){return r.exports}var i=t[n]={exports:{}};var o=true;try{e[n].call(i.exports,i,i.exports,__nccwpck_require__);o=false}finally{if(o)delete t[n]}return i.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var n=__nccwpck_require__(405);module.exports=n})(); \ No newline at end of file +(()=>{var e={108:function(e,t){(function(e,n){true?n(t):0})(this,(function(e){"use strict";var t={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"};var n="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var i={5:n,"5module":n+" export import",6:n+" const class extends export import super"};var r=/^in(stanceof)?$/;var a="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-鿼ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var o="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var s=new RegExp("["+a+"]");var u=new RegExp("["+a+o+"]");a=o=null;var l=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];var c=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];function isInAstralSet(e,t){var n=65536;for(var i=0;ie){return false}n+=t[i+1];if(n>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&s.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,l)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&u.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,l)||isInAstralSet(e,c)}var f=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new f(e,{beforeExpr:true,binop:t})}var p={beforeExpr:true},_={startsExpr:true};var d={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return d[e]=new f(e,t)}var h={num:new f("num",_),regexp:new f("regexp",_),string:new f("string",_),name:new f("name",_),privateId:new f("privateId",_),eof:new f("eof"),bracketL:new f("[",{beforeExpr:true,startsExpr:true}),bracketR:new f("]"),braceL:new f("{",{beforeExpr:true,startsExpr:true}),braceR:new f("}"),parenL:new f("(",{beforeExpr:true,startsExpr:true}),parenR:new f(")"),comma:new f(",",p),semi:new f(";",p),colon:new f(":",p),dot:new f("."),question:new f("?",p),questionDot:new f("?."),arrow:new f("=>",p),template:new f("template"),invalidTemplate:new f("invalidTemplate"),ellipsis:new f("...",p),backQuote:new f("`",_),dollarBraceL:new f("${",{beforeExpr:true,startsExpr:true}),eq:new f("=",{beforeExpr:true,isAssign:true}),assign:new f("_=",{beforeExpr:true,isAssign:true}),incDec:new f("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new f("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new f("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new f("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",p),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",p),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",p),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",_),_if:kw("if"),_return:kw("return",p),_switch:kw("switch"),_throw:kw("throw",p),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",_),_super:kw("super",_),_class:kw("class",_),_extends:kw("extends",p),_export:kw("export"),_import:kw("import",_),_null:kw("null",_),_true:kw("true",_),_false:kw("false",_),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var m=/\r\n?|\n|\u2028|\u2029/;var E=new RegExp(m.source,"g");function isNewLine(e){return e===10||e===13||e===8232||e===8233}var g=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var v=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var b=Object.prototype;var D=b.hasOwnProperty;var y=b.toString;function has(e,t){return D.call(e,t)}var S=Array.isArray||function(e){return y.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var A=function Position(e,t){this.line=e;this.column=t};A.prototype.offset=function offset(e){return new A(this.line,this.column+e)};var k=function SourceLocation(e,t,n){this.start=t;this.end=n;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var n=1,i=0;;){E.lastIndex=i;var r=E.exec(e);if(r&&r.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(S(t.onToken)){var i=t.onToken;t.onToken=function(e){return i.push(e)}}if(S(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(n,i,r,a,o,s){var u={type:n?"Block":"Line",value:i,start:r,end:a};if(e.locations){u.loc=new k(this,o,s)}if(e.ranges){u.range=[r,a]}t.push(u)}}var C=1,R=2,w=4,O=8,F=16,N=32,M=64,I=128,P=256,L=C|R|P;function functionFlags(e,t){return R|(e?w:0)|(t?O:0)}var B=0,V=1,U=2,z=3,K=4,G=5;var H=function Parser(e,n,r){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(i[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var a="";if(e.allowReserved!==true){a=t[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3];if(e.sourceType==="module"){a+=" await"}}this.reservedWords=wordsRegexp(a);var o=(a?a+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(o);this.reservedWordsStrictBind=wordsRegexp(o+" "+t.strictBind);this.input=String(n);this.containsEsc=false;if(r){this.pos=r;this.lineStart=this.input.lastIndexOf("\n",r-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(m).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=h.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.potentialArrowInForAwait=false;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports=Object.create(null);if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(C);this.regexpState=null;this.privateNameStack=[]};var X={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},canAwait:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true},allowNewDotTarget:{configurable:true},inClassStaticBlock:{configurable:true}};H.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};X.inFunction.get=function(){return(this.currentVarScope().flags&R)>0};X.inGenerator.get=function(){return(this.currentVarScope().flags&O)>0&&!this.currentVarScope().inClassFieldInit};X.inAsync.get=function(){return(this.currentVarScope().flags&w)>0&&!this.currentVarScope().inClassFieldInit};X.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&P){return false}if(t.flags&R){return(t.flags&w)>0}}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};X.allowSuper.get=function(){var e=this.currentThisScope();var t=e.flags;var n=e.inClassFieldInit;return(t&M)>0||n||this.options.allowSuperOutsideMethod};X.allowDirectSuper.get=function(){return(this.currentThisScope().flags&I)>0};X.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};X.allowNewDotTarget.get=function(){var e=this.currentThisScope();var t=e.flags;var n=e.inClassFieldInit;return(t&(R|P))>0||n};X.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&P)>0};H.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var n=this;for(var i=0;i=,?^&]/.test(r)||r==="!"&&this.input.charAt(i+1)==="=")}e+=t[0].length;v.lastIndex=e;e+=v.exec(this.input)[0].length;if(this.input[e]===";"){e++}}};W.eat=function(e){if(this.type===e){this.next();return true}else{return false}};W.isContextual=function(e){return this.type===h.name&&this.value===e&&!this.containsEsc};W.eatContextual=function(e){if(!this.isContextual(e)){return false}this.next();return true};W.expectContextual=function(e){if(!this.eatContextual(e)){this.unexpected()}};W.canInsertSemicolon=function(){return this.type===h.eof||this.type===h.braceR||m.test(this.input.slice(this.lastTokEnd,this.start))};W.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};W.semicolon=function(){if(!this.eat(h.semi)&&!this.insertSemicolon()){this.unexpected()}};W.afterTrailingComma=function(e,t){if(this.type===e){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!t){this.next()}return true}};W.expect=function(e){this.eat(e)||this.unexpected()};W.unexpected=function(e){this.raise(e!=null?e:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}W.checkPatternErrors=function(e,t){if(!e){return}if(e.trailingComma>-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var n=t?e.parenthesizedAssign:e.parenthesizedBind;if(n>-1){this.raiseRecoverable(n,"Parenthesized pattern")}};W.checkExpressionErrors=function(e,t){if(!e){return false}var n=e.shorthandAssign;var i=e.doubleProto;if(!t){return n>=0||i>=0}if(n>=0){this.raise(n,"Shorthand property assignments are valid only in destructuring patterns")}if(i>=0){this.raiseRecoverable(i,"Redefinition of __proto__ property")}};W.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&i<56320){return true}if(e){return false}if(i===123){return true}if(isIdentifierStart(i,true)){var a=n+1;while(isIdentifierChar(i=this.input.charCodeAt(a),true)){++a}if(i===92||i>55295&&i<56320){return true}var o=this.input.slice(n,a);if(!r.test(o)){return true}}return false};Y.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async")){return false}v.lastIndex=this.pos;var e=v.exec(this.input);var t=this.pos+e[0].length,n;return!m.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)==="function"&&(t+8===this.input.length||!(isIdentifierChar(n=this.input.charCodeAt(t+8))||n>55295&&n<56320))};Y.parseStatement=function(e,t,n){var i=this.type,r=this.startNode(),a;if(this.isLet(e)){i=h._var;a="let"}switch(i){case h._break:case h._continue:return this.parseBreakContinueStatement(r,i.keyword);case h._debugger:return this.parseDebuggerStatement(r);case h._do:return this.parseDoStatement(r);case h._for:return this.parseForStatement(r);case h._function:if(e&&(this.strict||e!=="if"&&e!=="label")&&this.options.ecmaVersion>=6){this.unexpected()}return this.parseFunctionStatement(r,false,!e);case h._class:if(e){this.unexpected()}return this.parseClass(r,true);case h._if:return this.parseIfStatement(r);case h._return:return this.parseReturnStatement(r);case h._switch:return this.parseSwitchStatement(r);case h._throw:return this.parseThrowStatement(r);case h._try:return this.parseTryStatement(r);case h._const:case h._var:a=a||this.value;if(e&&a!=="var"){this.unexpected()}return this.parseVarStatement(r,a);case h._while:return this.parseWhileStatement(r);case h._with:return this.parseWithStatement(r);case h.braceL:return this.parseBlock(true,r);case h.semi:return this.parseEmptyStatement(r);case h._export:case h._import:if(this.options.ecmaVersion>10&&i===h._import){v.lastIndex=this.pos;var o=v.exec(this.input);var s=this.pos+o[0].length,u=this.input.charCodeAt(s);if(u===40||u===46){return this.parseExpressionStatement(r,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return i===h._import?this.parseImport(r):this.parseExport(r,n);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(r,true,!e)}var l=this.value,c=this.parseExpression();if(i===h.name&&c.type==="Identifier"&&this.eat(h.colon)){return this.parseLabeledStatement(r,l,c,e)}else{return this.parseExpressionStatement(r,c)}}};Y.parseBreakContinueStatement=function(e,t){var n=t==="break";this.next();if(this.eat(h.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==h.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(h.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};Y.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(j);this.enterScope(0);this.expect(h.parenL);if(this.type===h.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var n=this.isLet();if(this.type===h._var||this.type===h._const||n){var i=this.startNode(),r=n?"let":this.value;this.next();this.parseVar(i,true,r);this.finishNode(i,"VariableDeclaration");if((this.type===h._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&i.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===h._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,i)}if(t>-1){this.unexpected(t)}return this.parseFor(e,i)}var a=this.isContextual("let"),o=false;var s=new DestructuringErrors;var u=this.parseExpression(t>-1?"await":true,s);if(this.type===h._in||(o=this.options.ecmaVersion>=6&&this.isContextual("of"))){if(this.options.ecmaVersion>=9){if(this.type===h._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}if(a&&o){this.raise(u.start,"The left-hand side of a for-of loop may not start with 'let'.")}this.toAssignable(u,false,s);this.checkLValPattern(u);return this.parseForIn(e,u)}else{this.checkExpressionErrors(s,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,u)};Y.parseFunctionStatement=function(e,t,n){this.next();return this.parseFunction(e,Q|(n?0:J),false,t)};Y.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(h._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};Y.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(h.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};Y.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(h.braceL);this.labels.push($);this.enterScope(0);var t;for(var n=false;this.type!==h.braceR;){if(this.type===h._case||this.type===h._default){var i=this.type===h._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(i){t.test=this.parseExpression()}else{if(n){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}n=true;t.test=null}this.expect(h.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};Y.parseThrowStatement=function(e){this.next();if(m.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var Z=[];Y.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===h._catch){var t=this.startNode();this.next();if(this.eat(h.parenL)){t.param=this.parseBindingAtom();var n=t.param.type==="Identifier";this.enterScope(n?N:0);this.checkLValPattern(t.param,n?K:U);this.expect(h.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(h._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};Y.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};Y.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(j);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};Y.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};Y.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};Y.parseLabeledStatement=function(e,t,n,i){for(var r=0,a=this.labels;r=0;u--){var l=this.labels[u];if(l.statementStart===e.start){l.statementStart=this.start;l.kind=s}else{break}}this.labels.push({name:t,kind:s,statementStart:this.start});e.body=this.parseStatement(i?i.indexOf("label")===-1?i+"label":i:"label");this.labels.pop();e.label=n;return this.finishNode(e,"LabeledStatement")};Y.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};Y.parseBlock=function(e,t,n){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(h.braceL);if(e){this.enterScope(0)}while(this.type!==h.braceR){var i=this.parseStatement(null);t.body.push(i)}if(n){this.strict=false}this.next();if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};Y.parseFor=function(e,t){e.init=t;this.expect(h.semi);e.test=this.type===h.semi?null:this.parseExpression();this.expect(h.semi);e.update=this.type===h.parenR?null:this.parseExpression();this.expect(h.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};Y.parseForIn=function(e,t){var n=this.type===h._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!n||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(n?"for-in":"for-of")+" loop variable declaration may not have an initializer")}e.left=t;e.right=n?this.parseExpression():this.parseMaybeAssign();this.expect(h.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,n?"ForInStatement":"ForOfStatement")};Y.parseVar=function(e,t,n){e.declarations=[];e.kind=n;for(;;){var i=this.startNode();this.parseVarId(i,n);if(this.eat(h.eq)){i.init=this.parseMaybeAssign(t)}else if(n==="const"&&!(this.type===h._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(i.id.type!=="Identifier"&&!(t&&(this.type===h._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{i.init=null}e.declarations.push(this.finishNode(i,"VariableDeclarator"));if(!this.eat(h.comma)){break}}return e};Y.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLValPattern(e.id,t==="var"?V:U,false)};var Q=1,J=2,ee=4;Y.parseFunction=function(e,t,n,i,r){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!i){if(this.type===h.star&&t&J){this.unexpected()}e.generator=this.eat(h.star)}if(this.options.ecmaVersion>=8){e.async=!!i}if(t&Q){e.id=t&ee&&this.type!==h.name?null:this.parseIdent();if(e.id&&!(t&J)){this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?V:U:z)}}var a=this.yieldPos,o=this.awaitPos,s=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&Q)){e.id=this.type===h.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,n,false,r);this.yieldPos=a;this.awaitPos=o;this.awaitIdentPos=s;return this.finishNode(e,t&Q?"FunctionDeclaration":"FunctionExpression")};Y.parseFunctionParams=function(e){this.expect(h.parenL);e.params=this.parseBindingList(h.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};Y.parseClass=function(e,t){this.next();var n=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var i=this.enterClassBody();var r=this.startNode();var a=false;r.body=[];this.expect(h.braceL);while(this.type!==h.braceR){var o=this.parseClassElement(e.superClass!==null);if(o){r.body.push(o);if(o.type==="MethodDefinition"&&o.kind==="constructor"){if(a){this.raise(o.start,"Duplicate constructor in the same class")}a=true}else if(o.key&&o.key.type==="PrivateIdentifier"&&isPrivateNameConflicted(i,o)){this.raiseRecoverable(o.key.start,"Identifier '#"+o.key.name+"' has already been declared")}}}this.strict=n;this.next();e.body=this.finishNode(r,"ClassBody");this.exitClassBody();return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};Y.parseClassElement=function(e){if(this.eat(h.semi)){return null}var t=this.options.ecmaVersion;var n=this.startNode();var i="";var r=false;var a=false;var o="method";var s=false;if(this.eatContextual("static")){if(t>=13&&this.eat(h.braceL)){this.parseClassStaticBlock(n);return n}if(this.isClassElementNameStart()||this.type===h.star){s=true}else{i="static"}}n.static=s;if(!i&&t>=8&&this.eatContextual("async")){if((this.isClassElementNameStart()||this.type===h.star)&&!this.canInsertSemicolon()){a=true}else{i="async"}}if(!i&&(t>=9||!a)&&this.eat(h.star)){r=true}if(!i&&!a&&!r){var u=this.value;if(this.eatContextual("get")||this.eatContextual("set")){if(this.isClassElementNameStart()){o=u}else{i=u}}}if(i){n.computed=false;n.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc);n.key.name=i;this.finishNode(n.key,"Identifier")}else{this.parseClassElementName(n)}if(t<13||this.type===h.parenL||o!=="method"||r||a){var l=!n.static&&checkKeyName(n,"constructor");var c=l&&e;if(l&&o!=="method"){this.raise(n.key.start,"Constructor can't have get/set modifier")}n.kind=l?"constructor":o;this.parseClassMethod(n,r,a,c)}else{this.parseClassField(n)}return n};Y.isClassElementNameStart=function(){return this.type===h.name||this.type===h.privateId||this.type===h.num||this.type===h.string||this.type===h.bracketL||this.type.keyword};Y.parseClassElementName=function(e){if(this.type===h.privateId){if(this.value==="constructor"){this.raise(this.start,"Classes can't have an element named '#constructor'")}e.computed=false;e.key=this.parsePrivateIdent()}else{this.parsePropertyName(e)}};Y.parseClassMethod=function(e,t,n,i){var r=e.key;if(e.kind==="constructor"){if(t){this.raise(r.start,"Constructor can't be a generator")}if(n){this.raise(r.start,"Constructor can't be an async method")}}else if(e.static&&checkKeyName(e,"prototype")){this.raise(r.start,"Classes may not have a static property named prototype")}var a=e.value=this.parseMethod(t,n,i);if(e.kind==="get"&&a.params.length!==0){this.raiseRecoverable(a.start,"getter should have no params")}if(e.kind==="set"&&a.params.length!==1){this.raiseRecoverable(a.start,"setter should have exactly one param")}if(e.kind==="set"&&a.params[0].type==="RestElement"){this.raiseRecoverable(a.params[0].start,"Setter cannot use rest params")}return this.finishNode(e,"MethodDefinition")};Y.parseClassField=function(e){if(checkKeyName(e,"constructor")){this.raise(e.key.start,"Classes can't have a field named 'constructor'")}else if(e.static&&checkKeyName(e,"prototype")){this.raise(e.key.start,"Classes can't have a static field named 'prototype'")}if(this.eat(h.eq)){var t=this.currentThisScope();var n=t.inClassFieldInit;t.inClassFieldInit=true;e.value=this.parseMaybeAssign();t.inClassFieldInit=n}else{e.value=null}this.semicolon();return this.finishNode(e,"PropertyDefinition")};Y.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;this.labels=[];this.enterScope(P|M);while(this.type!==h.braceR){var n=this.parseStatement(null);e.body.push(n)}this.next();this.exitScope();this.labels=t;return this.finishNode(e,"StaticBlock")};Y.parseClassId=function(e,t){if(this.type===h.name){e.id=this.parseIdent();if(t){this.checkLValSimple(e.id,U,false)}}else{if(t===true){this.unexpected()}e.id=null}};Y.parseClassSuper=function(e){e.superClass=this.eat(h._extends)?this.parseExprSubscripts(false):null};Y.enterClassBody=function(){var e={declared:Object.create(null),used:[]};this.privateNameStack.push(e);return e.declared};Y.exitClassBody=function(){var e=this.privateNameStack.pop();var t=e.declared;var n=e.used;var i=this.privateNameStack.length;var r=i===0?null:this.privateNameStack[i-1];for(var a=0;a=11){if(this.eatContextual("as")){e.exported=this.parseIdent(true);this.checkExport(t,e.exported.name,this.lastTokStart)}else{e.exported=null}}this.expectContextual("from");if(this.type!==h.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(h._default)){this.checkExport(t,"default",this.lastTokStart);var n;if(this.type===h._function||(n=this.isAsyncFunction())){var i=this.startNode();this.next();if(n){this.next()}e.declaration=this.parseFunction(i,Q|ee,false,n)}else if(this.type===h._class){var r=this.startNode();e.declaration=this.parseClass(r,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==h.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var a=0,o=e.specifiers;a=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(n){this.checkPatternErrors(n,true)}for(var i=0,r=e.properties;i=8&&!o&&s.name==="async"&&!this.canInsertSemicolon()&&this.eat(h._function)){this.overrideContext(ie.f_expr);return this.parseFunction(this.startNodeAt(r,a),0,false,true,t)}if(i&&!this.canInsertSemicolon()){if(this.eat(h.arrow)){return this.parseArrowExpression(this.startNodeAt(r,a),[s],false,t)}if(this.options.ecmaVersion>=8&&s.name==="async"&&this.type===h.name&&!o&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc)){s=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(h.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(r,a),[s],true,t)}}return s;case h.regexp:var u=this.value;n=this.parseLiteral(u.value);n.regex={pattern:u.pattern,flags:u.flags};return n;case h.num:case h.string:return this.parseLiteral(this.value);case h._null:case h._true:case h._false:n=this.startNode();n.value=this.type===h._null?null:this.type===h._true;n.raw=this.type.keyword;this.next();return this.finishNode(n,"Literal");case h.parenL:var l=this.start,c=this.parseParenAndDistinguishExpression(i,t);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)){e.parenthesizedAssign=l}if(e.parenthesizedBind<0){e.parenthesizedBind=l}}return c;case h.bracketL:n=this.startNode();this.next();n.elements=this.parseExprList(h.bracketR,true,true,e);return this.finishNode(n,"ArrayExpression");case h.braceL:this.overrideContext(ie.b_expr);return this.parseObj(false,e);case h._function:n=this.startNode();this.next();return this.parseFunction(n,0);case h._class:return this.parseClass(this.startNode(),false);case h._new:return this.parseNew();case h.backQuote:return this.parseTemplate();case h._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};ae.parseExprImport=function(){var e=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var t=this.parseIdent(true);switch(this.type){case h.parenL:return this.parseDynamicImport(e);case h.dot:e.meta=t;return this.parseImportMeta(e);default:this.unexpected()}};ae.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(h.parenR)){var t=this.start;if(this.eat(h.comma)&&this.eat(h.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="meta"){this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'")}if(t){this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere){this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(e,"MetaProperty")};ae.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(t,"Literal")};ae.parseParenExpression=function(){this.expect(h.parenL);var e=this.parseExpression();this.expect(h.parenR);return e};ae.parseParenAndDistinguishExpression=function(e,t){var n=this.start,i=this.startLoc,r,a=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var o=this.start,s=this.startLoc;var u=[],l=true,c=false;var f=new DestructuringErrors,p=this.yieldPos,_=this.awaitPos,d;this.yieldPos=0;this.awaitPos=0;while(this.type!==h.parenR){l?l=false:this.expect(h.comma);if(a&&this.afterTrailingComma(h.parenR,true)){c=true;break}else if(this.type===h.ellipsis){d=this.start;u.push(this.parseParenItem(this.parseRestBinding()));if(this.type===h.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{u.push(this.parseMaybeAssign(false,f,this.parseParenItem))}}var m=this.lastTokEnd,E=this.lastTokEndLoc;this.expect(h.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(h.arrow)){this.checkPatternErrors(f,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=p;this.awaitPos=_;return this.parseParenArrowList(n,i,u,t)}if(!u.length||c){this.unexpected(this.lastTokStart)}if(d){this.unexpected(d)}this.checkExpressionErrors(f,true);this.yieldPos=p||this.yieldPos;this.awaitPos=_||this.awaitPos;if(u.length>1){r=this.startNodeAt(o,s);r.expressions=u;this.finishNodeAt(r,"SequenceExpression",m,E)}else{r=u[0]}}else{r=this.parseParenExpression()}if(this.options.preserveParens){var g=this.startNodeAt(n,i);g.expression=r;return this.finishNode(g,"ParenthesizedExpression")}else{return r}};ae.parseParenItem=function(e){return e};ae.parseParenArrowList=function(e,t,n,i){return this.parseArrowExpression(this.startNodeAt(e,t),n,i)};var oe=[];ae.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(h.dot)){e.meta=t;var n=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"){this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'")}if(n){this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters")}if(!this.allowNewDotTarget){this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block")}return this.finishNode(e,"MetaProperty")}var i=this.start,r=this.startLoc,a=this.type===h._import;e.callee=this.parseSubscripts(this.parseExprAtom(),i,r,true,false);if(a&&e.callee.type==="ImportExpression"){this.raise(i,"Cannot use new with import()")}if(this.eat(h.parenL)){e.arguments=this.parseExprList(h.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=oe}return this.finishNode(e,"NewExpression")};ae.parseTemplateElement=function(e){var t=e.isTagged;var n=this.startNode();if(this.type===h.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}n.value={raw:this.value,cooked:null}}else{n.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();n.tail=this.type===h.backQuote;return this.finishNode(n,"TemplateElement")};ae.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var n=this.startNode();this.next();n.expressions=[];var i=this.parseTemplateElement({isTagged:t});n.quasis=[i];while(!i.tail){if(this.type===h.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(h.dollarBraceL);n.expressions.push(this.parseExpression());this.expect(h.braceR);n.quasis.push(i=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(n,"TemplateLiteral")};ae.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===h.name||this.type===h.num||this.type===h.string||this.type===h.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===h.star)&&!m.test(this.input.slice(this.lastTokEnd,this.start))};ae.parseObj=function(e,t){var n=this.startNode(),i=true,r={};n.properties=[];this.next();while(!this.eat(h.braceR)){if(!i){this.expect(h.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(h.braceR)){break}}else{i=false}var a=this.parseProperty(e,t);if(!e){this.checkPropClash(a,r,t)}n.properties.push(a)}return this.finishNode(n,e?"ObjectPattern":"ObjectExpression")};ae.parseProperty=function(e,t){var n=this.startNode(),i,r,a,o;if(this.options.ecmaVersion>=9&&this.eat(h.ellipsis)){if(e){n.argument=this.parseIdent(false);if(this.type===h.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(n,"RestElement")}if(this.type===h.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}n.argument=this.parseMaybeAssign(false,t);if(this.type===h.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(n,"SpreadElement")}if(this.options.ecmaVersion>=6){n.method=false;n.shorthand=false;if(e||t){a=this.start;o=this.startLoc}if(!e){i=this.eat(h.star)}}var s=this.containsEsc;this.parsePropertyName(n);if(!e&&!s&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(n)){r=true;i=this.options.ecmaVersion>=9&&this.eat(h.star);this.parsePropertyName(n,t)}else{r=false}this.parsePropertyValue(n,e,i,r,a,o,t,s);return this.finishNode(n,"Property")};ae.parsePropertyValue=function(e,t,n,i,r,a,o,s){if((n||i)&&this.type===h.colon){this.unexpected()}if(this.eat(h.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,o);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===h.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(n,i)}else if(!t&&!s&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==h.comma&&this.type!==h.braceR&&this.type!==h.eq)){if(n||i){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var u=e.kind==="get"?0:1;if(e.value.params.length!==u){var l=e.value.start;if(e.kind==="get"){this.raiseRecoverable(l,"getter should have no params")}else{this.raiseRecoverable(l,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(n||i){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=r}e.kind="init";if(t){e.value=this.parseMaybeDefault(r,a,this.copyNode(e.key))}else if(this.type===h.eq&&o){if(o.shorthandAssign<0){o.shorthandAssign=this.start}e.value=this.parseMaybeDefault(r,a,this.copyNode(e.key))}else{e.value=this.copyNode(e.key)}e.shorthand=true}else{this.unexpected()}};ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(h.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(h.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===h.num||this.type===h.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ae.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};ae.parseMethod=function(e,t,n){var i=this.startNode(),r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;this.initFunction(i);if(this.options.ecmaVersion>=6){i.generator=e}if(this.options.ecmaVersion>=8){i.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,i.generator)|M|(n?I:0));this.expect(h.parenL);i.params=this.parseBindingList(h.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(i,false,true,false);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=o;return this.finishNode(i,"FunctionExpression")};ae.parseArrowExpression=function(e,t,n,i){var r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;this.enterScope(functionFlags(n,false)|F);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!n}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false,i);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=o;return this.finishNode(e,"ArrowFunctionExpression")};ae.parseFunctionBody=function(e,t,n,i){var r=t&&this.type!==h.braceL;var a=this.strict,o=false;if(r){e.body=this.parseMaybeAssign(i);e.expression=true;this.checkParams(e,false)}else{var s=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!a||s){o=this.strictDirective(this.end);if(o&&s){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var u=this.labels;this.labels=[];if(o){this.strict=true}this.checkParams(e,!a&&!o&&!t&&!n&&this.isSimpleParamList(e.params));if(this.strict&&e.id){this.checkLValSimple(e.id,G)}e.body=this.parseBlock(false,undefined,o&&!a);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=u}this.exitScope()};ae.isSimpleParamList=function(e){for(var t=0,n=e;t-1||r.functions.indexOf(e)>-1||r.var.indexOf(e)>-1;r.lexical.push(e);if(this.inModule&&r.flags&C){delete this.undefinedExports[e]}}else if(t===K){var a=this.currentScope();a.lexical.push(e)}else if(t===z){var o=this.currentScope();if(this.treatFunctionsAsVar){i=o.lexical.indexOf(e)>-1}else{i=o.lexical.indexOf(e)>-1||o.var.indexOf(e)>-1}o.functions.push(e)}else{for(var s=this.scopeStack.length-1;s>=0;--s){var u=this.scopeStack[s];if(u.lexical.indexOf(e)>-1&&!(u.flags&N&&u.lexical[0]===e)||!this.treatFunctionsAsVarInScope(u)&&u.functions.indexOf(e)>-1){i=true;break}u.var.push(e);if(this.inModule&&u.flags&C){delete this.undefinedExports[e]}if(u.flags&L){break}}}if(i){this.raiseRecoverable(n,"Identifier '"+e+"' has already been declared")}};ue.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};ue.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};ue.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&L){return t}}};ue.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&L&&!(t.flags&F)){return t}}};var ce=function Node(e,t,n){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new k(e,n)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var fe=H.prototype;fe.startNode=function(){return new ce(this,this.start,this.startLoc)};fe.startNodeAt=function(e,t){return new ce(this,e,t)};function finishNodeAt(e,t,n,i){e.type=t;e.end=n;if(this.options.locations){e.loc.end=i}if(this.options.ranges){e.range[1]=n}return e}fe.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};fe.finishNodeAt=function(e,t,n,i){return finishNodeAt.call(this,e,t,n,i)};fe.copyNode=function(e){var t=new ce(this,e.start,this.startLoc);for(var n in e){t[n]=e[n]}return t};var pe="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var _e=pe+" Extended_Pictographic";var de=_e;var he=de+" EBase EComp EMod EPres ExtPict";var me={9:pe,10:_e,11:de,12:he};var Ee="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ge="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ve=ge+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var be=ve+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var De=be+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";var ye={9:ge,10:ve,11:be,12:De};var Se={};function buildUnicodeData(e){var t=Se[e]={binary:wordsRegexp(me[e]+" "+Ee),nonBinary:{General_Category:wordsRegexp(Ee),Script:wordsRegexp(ye[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);buildUnicodeData(12);var Ae=H.prototype;var ke=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"");this.unicodeProperties=Se[e.options.ecmaVersion>=12?12:e.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};ke.prototype.reset=function reset(e,t,n){var i=n.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=n;this.switchU=i&&this.parser.options.ecmaVersion>=6;this.switchN=i&&this.parser.options.ecmaVersion>=9};ke.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};ke.prototype.at=function at(e,t){if(t===void 0)t=false;var n=this.source;var i=n.length;if(e>=i){return-1}var r=n.charCodeAt(e);if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=i){return r}var a=n.charCodeAt(e+1);return a>=56320&&a<=57343?(r<<10)+a-56613888:r};ke.prototype.nextIndex=function nextIndex(e,t){if(t===void 0)t=false;var n=this.source;var i=n.length;if(e>=i){return i}var r=n.charCodeAt(e),a;if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=i||(a=n.charCodeAt(e+1))<56320||a>57343){return e+1}return e+2};ke.prototype.current=function current(e){if(e===void 0)e=false;return this.at(this.pos,e)};ke.prototype.lookahead=function lookahead(e){if(e===void 0)e=false;return this.at(this.nextIndex(this.pos,e),e)};ke.prototype.advance=function advance(e){if(e===void 0)e=false;this.pos=this.nextIndex(this.pos,e)};ke.prototype.eat=function eat(e,t){if(t===void 0)t=false;if(this.current(t)===e){this.advance(t);return true}return false};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Ae.validateRegExpFlags=function(e){var t=e.validFlags;var n=e.flags;for(var i=0;i-1){this.raise(e.start,"Duplicate regular expression flag")}}};Ae.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};Ae.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,n=e.backReferenceNames;t=9){n=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!n;return true}}e.pos=t;return false};Ae.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};Ae.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};Ae.regexp_eatBracedQuantifier=function(e,t){var n=e.pos;if(e.eat(123)){var i=0,r=-1;if(this.regexp_eatDecimalDigits(e)){i=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){r=e.lastIntValue}if(e.eat(125)){if(r!==-1&&r=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};Ae.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};Ae.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};Ae.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}Ae.regexp_eatPatternCharacters=function(e){var t=e.pos;var n=0;while((n=e.current())!==-1&&!isSyntaxCharacter(n)){e.advance()}return e.pos!==t};Ae.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};Ae.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};Ae.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};Ae.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString(e.lastIntValue)}return true}return false};Ae.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var n=this.options.ecmaVersion>=11;var i=e.current(n);e.advance(n);if(i===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)){i=e.lastIntValue}if(isRegExpIdentifierStart(i)){e.lastIntValue=i;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}Ae.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var n=this.options.ecmaVersion>=11;var i=e.current(n);e.advance(n);if(i===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)){i=e.lastIntValue}if(isRegExpIdentifierPart(i)){e.lastIntValue=i;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}Ae.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};Ae.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var n=e.lastIntValue;if(e.switchU){if(n>e.maxBackReference){e.maxBackReference=n}return true}if(n<=e.numCapturingParens){return true}e.pos=t}return false};Ae.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};Ae.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,false)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};Ae.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};Ae.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};Ae.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};Ae.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}Ae.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){if(t===void 0)t=false;var n=e.pos;var i=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var r=e.lastIntValue;if(i&&r>=55296&&r<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343){e.lastIntValue=(r-55296)*1024+(o-56320)+65536;return true}}e.pos=a;e.lastIntValue=r}return true}if(i&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(i){e.raise("Invalid unicode escape")}e.pos=n}return false};function isValidUnicode(e){return e>=0&&e<=1114111}Ae.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};Ae.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};Ae.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}Ae.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var n=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var i=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,n,i);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var r=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,r);return true}return false};Ae.regexp_validateUnicodePropertyNameAndValue=function(e,t,n){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(n)){e.raise("Invalid property value")}};Ae.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};Ae.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}Ae.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}Ae.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};Ae.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};Ae.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var n=e.lastIntValue;if(e.switchU&&(t===-1||n===-1)){e.raise("Invalid character class")}if(t!==-1&&n!==-1&&t>n){e.raise("Range out of order in character class")}}}};Ae.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var n=e.current();if(n===99||isOctalDigit(n)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var i=e.current();if(i!==93){e.lastIntValue=i;e.advance();return true}return false};Ae.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};Ae.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};Ae.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};Ae.regexp_eatDecimalDigits=function(e){var t=e.pos;var n=0;e.lastIntValue=0;while(isDecimalDigit(n=e.current())){e.lastIntValue=10*e.lastIntValue+(n-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}Ae.regexp_eatHexDigits=function(e){var t=e.pos;var n=0;e.lastIntValue=0;while(isHexDigit(n=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(n);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}Ae.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var n=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+n*8+e.lastIntValue}else{e.lastIntValue=t*8+n}}else{e.lastIntValue=t}return true}return false};Ae.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}Ae.regexp_eatFixedHexDigits=function(e,t){var n=e.pos;e.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(h.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};xe.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};xe.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320){return e}var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888};xe.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,n=this.input.indexOf("*/",this.pos+=2);if(n===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=n+2;if(this.options.locations){E.lastIndex=t;var i;while((i=E.exec(this.input))&&i.index8&&e<14||e>=5760&&g.test(String.fromCharCode(e))){++this.pos}else{break e}}}};xe.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var n=this.type;this.type=e;this.value=t;this.updateContext(n)};xe.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(h.ellipsis)}else{++this.pos;return this.finishToken(h.dot)}};xe.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(h.assign,2)}return this.finishOp(h.slash,1)};xe.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var n=1;var i=e===42?h.star:h.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++n;i=h.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(h.assign,n+1)}return this.finishOp(i,n)};xe.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var n=this.input.charCodeAt(this.pos+2);if(n===61){return this.finishOp(h.assign,3)}}return this.finishOp(e===124?h.logicalOR:h.logicalAND,2)}if(t===61){return this.finishOp(h.assign,2)}return this.finishOp(e===124?h.bitwiseOR:h.bitwiseAND,1)};xe.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(h.assign,2)}return this.finishOp(h.bitwiseXOR,1)};xe.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||m.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(h.incDec,2)}if(t===61){return this.finishOp(h.assign,2)}return this.finishOp(h.plusMin,1)};xe.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var n=1;if(t===e){n=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+n)===61){return this.finishOp(h.assign,n+1)}return this.finishOp(h.bitShift,n)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){n=2}return this.finishOp(h.relational,n)};xe.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(h.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(h.arrow)}return this.finishOp(e===61?h.eq:h.prefix,1)};xe.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var n=this.input.charCodeAt(this.pos+2);if(n<48||n>57){return this.finishOp(h.questionDot,2)}}if(t===63){if(e>=12){var i=this.input.charCodeAt(this.pos+2);if(i===61){return this.finishOp(h.assign,3)}}return this.finishOp(h.coalesce,2)}}return this.finishOp(h.question,1)};xe.readToken_numberSign=function(){var e=this.options.ecmaVersion;var t=35;if(e>=13){++this.pos;t=this.fullCharCodeAtPos();if(isIdentifierStart(t,true)||t===92){return this.finishToken(h.privateId,this.readWord1())}}this.raise(this.pos,"Unexpected character '"+codePointToString$1(t)+"'")};xe.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(h.parenL);case 41:++this.pos;return this.finishToken(h.parenR);case 59:++this.pos;return this.finishToken(h.semi);case 44:++this.pos;return this.finishToken(h.comma);case 91:++this.pos;return this.finishToken(h.bracketL);case 93:++this.pos;return this.finishToken(h.bracketR);case 123:++this.pos;return this.finishToken(h.braceL);case 125:++this.pos;return this.finishToken(h.braceR);case 58:++this.pos;return this.finishToken(h.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(h.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(h.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+codePointToString$1(e)+"'")};xe.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,n)};xe.readRegexp=function(){var e,t,n=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(n,"Unterminated regular expression")}var i=this.input.charAt(this.pos);if(m.test(i)){this.raise(n,"Unterminated regular expression")}if(!e){if(i==="["){t=true}else if(i==="]"&&t){t=false}else if(i==="/"&&!t){break}e=i==="\\"}else{e=false}++this.pos}var r=this.input.slice(n,this.pos);++this.pos;var a=this.pos;var o=this.readWord1();if(this.containsEsc){this.unexpected(a)}var s=this.regexpState||(this.regexpState=new ke(this));s.reset(n,r,o);this.validateRegExpFlags(s);this.validateRegExpPattern(s);var u=null;try{u=new RegExp(r,o)}catch(e){}return this.finishToken(h.regexp,{pattern:r,flags:o,value:u})};xe.readInt=function(e,t,n){var i=this.options.ecmaVersion>=12&&t===undefined;var r=n&&this.input.charCodeAt(this.pos)===48;var a=this.pos,o=0,s=0;for(var u=0,l=t==null?Infinity:t;u=97){f=c-97+10}else if(c>=65){f=c-65+10}else if(c>=48&&c<=57){f=c-48}else{f=Infinity}if(f>=e){break}s=c;o=o*e+f}if(i&&s===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===a||t!=null&&this.pos-a!==t){return null}return o};function stringToNumber(e,t){if(t){return parseInt(e,8)}return parseFloat(e.replace(/_/g,""))}function stringToBigInt(e){if(typeof BigInt!=="function"){return null}return BigInt(e.replace(/_/g,""))}xe.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var n=this.readInt(e);if(n==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){n=stringToBigInt(this.input.slice(t,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(h.num,n)};xe.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10,undefined,true)===null){this.raise(t,"Invalid number")}var n=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(n&&this.strict){this.raise(t,"Invalid number")}var i=this.input.charCodeAt(this.pos);if(!n&&!e&&this.options.ecmaVersion>=11&&i===110){var r=stringToBigInt(this.input.slice(t,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(h.num,r)}if(n&&/[89]/.test(this.input.slice(t,this.pos))){n=false}if(i===46&&!n){++this.pos;this.readInt(10);i=this.input.charCodeAt(this.pos)}if((i===69||i===101)&&!n){i=this.input.charCodeAt(++this.pos);if(i===43||i===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var a=stringToNumber(this.input.slice(t,this.pos),n);return this.finishToken(h.num,a)};xe.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var n=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(n,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}xe.readString=function(e){var t="",n=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var i=this.input.charCodeAt(this.pos);if(i===e){break}if(i===92){t+=this.input.slice(n,this.pos);t+=this.readEscapedChar(false);n=this.pos}else if(i===8232||i===8233){if(this.options.ecmaVersion<10){this.raise(this.start,"Unterminated string constant")}++this.pos;if(this.options.locations){this.curLine++;this.lineStart=this.pos}}else{if(isNewLine(i)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(n,this.pos++);return this.finishToken(h.string,t)};var Ce={};xe.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===Ce){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};xe.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw Ce}else{this.raise(e,t)}};xe.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var n=this.input.charCodeAt(this.pos);if(n===96||n===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===h.template||this.type===h.invalidTemplate)){if(n===36){this.pos+=2;return this.finishToken(h.dollarBraceL)}else{++this.pos;return this.finishToken(h.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(h.template,e)}if(n===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(n)){e+=this.input.slice(t,this.pos);++this.pos;switch(n){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(n);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};xe.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var i=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var r=parseInt(i,8);if(r>255){i=i.slice(0,-1);r=parseInt(i,8)}this.pos+=i.length-1;t=this.input.charCodeAt(this.pos);if((i!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-i.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(r)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};xe.readHexChar=function(e){var t=this.pos;var n=this.readInt(16,e);if(n===null){this.invalidStringToken(t,"Bad character escape sequence")}return n};xe.readWord1=function(){this.containsEsc=false;var e="",t=true,n=this.pos;var i=this.options.ecmaVersion>=6;while(this.pos{"use strict";e.exports=require("next/dist/compiled/source-map")},405:function(e,t,n){(function(e,i){true?i(t,n(749)):0})(this,(function(e,t){"use strict";function _interopDefaultLegacy(e){return e&&typeof e==="object"&&"default"in e?e:{default:e}}var i=_interopDefaultLegacy(t);function characters(e){return e.split("")}function member(e,t){return t.includes(e)}class DefaultsError extends Error{constructor(e,t){super();this.name="DefaultsError";this.message=e;this.defs=t}}function defaults(e,t,n){if(e===true){e={}}else if(e!=null&&typeof e==="object"){e={...e}}const i=e||{};if(n)for(const e in i)if(HOP(i,e)&&!HOP(t,e)){throw new DefaultsError("`"+e+"` is not a supported option",t)}for(const n in t)if(HOP(t,n)){if(!e||!HOP(e,n)){i[n]=t[n]}else if(n==="ecma"){let t=e[n]|0;if(t>5&&t<2015)t+=2009;i[n]=t}else{i[n]=e&&HOP(e,n)?e[n]:t[n]}}return i}function noop(){}function return_false(){return false}function return_true(){return true}function return_this(){return this}function return_null(){return null}var r=function(){function MAP(t,n,i){var r=[],a=[],o;function doit(){var s=n(t[o],o);var u=s instanceof Last;if(u)s=s.v;if(s instanceof AtTop){s=s.v;if(s instanceof Splice){a.push.apply(a,i?s.v.slice().reverse():s.v)}else{a.push(s)}}else if(s!==e){if(s instanceof Splice){r.push.apply(r,i?s.v.slice().reverse():s.v)}else{r.push(s)}}return u}if(Array.isArray(t)){if(i){for(o=t.length;--o>=0;)if(doit())break;r.reverse();a.reverse()}else{for(o=0;o=0;){if(e[n]===t)e.splice(n,1)}}function mergeSort(e,t){if(e.length<2)return e.slice();function merge(e,n){var i=[],r=0,a=0,o=0;while(r{n+=e}))}return n}function has_annotation(e,t){return e._annotations&t}function set_annotation(e,t){e._annotations|=t}var s="";var u=true;var l="break case catch class const continue debugger default delete do else export extends finally for function if in instanceof let new return switch throw try typeof var void while with";var c="false null true";var f="enum implements import interface package private protected public static super this "+c+" "+l;var p="return new delete throw else case yield await";l=makePredicate(l);f=makePredicate(f);p=makePredicate(p);c=makePredicate(c);var _=makePredicate(characters("+-*&%=<>!?|~^"));var d=/[0-9a-f]/i;var h=/^0x[0-9a-f]+$/i;var m=/^0[0-7]+$/;var E=/^0o[0-7]+$/i;var g=/^0b[01]+$/i;var v=/^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;var b=/^(0[xob])?[0-9a-f]+n$/i;var D=makePredicate(["in","instanceof","typeof","new","void","delete","++","--","+","-","!","~","&","|","^","*","**","/","%",">>","<<",">>>","<",">","<=",">=","==","===","!=","!==","?","=","+=","-=","||=","&&=","??=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&=","&&","??","||"]);var y=makePredicate(characters("  \n\r\t\f\v​           \u2028\u2029   \ufeff"));var S=makePredicate(characters("\n\r\u2028\u2029"));var A=makePredicate(characters(";]),:"));var k=makePredicate(characters("[{(,;:"));var T=makePredicate(characters("[]{}(),;:"));var x={ID_Start:/[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/(?:[$0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF])+/};function get_full_char(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){if(is_surrogate_pair_tail(e.charCodeAt(t+1))){return e.charAt(t)+e.charAt(t+1)}}else if(is_surrogate_pair_tail(e.charCodeAt(t))){if(is_surrogate_pair_head(e.charCodeAt(t-1))){return e.charAt(t-1)+e.charAt(t)}}return e.charAt(t)}function get_full_char_code(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){return 65536+(e.charCodeAt(t)-55296<<10)+e.charCodeAt(t+1)-56320}return e.charCodeAt(t)}function get_full_char_length(e){var t=0;for(var n=0;n65535){e-=65536;return String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)}return String.fromCharCode(e)}function is_surrogate_pair_head(e){return e>=55296&&e<=56319}function is_surrogate_pair_tail(e){return e>=56320&&e<=57343}function is_digit(e){return e>=48&&e<=57}function is_identifier_start(e){return x.ID_Start.test(e)}function is_identifier_char(e){return x.ID_Continue.test(e)}const C=/^[a-z_$][a-z0-9_$]*$/i;function is_basic_identifier_string(e){return C.test(e)}function is_identifier_string(e,t){if(C.test(e)){return true}if(!t&&/[\ud800-\udfff]/.test(e)){return false}var n=x.ID_Start.exec(e);if(!n||n.index!==0){return false}e=e.slice(n[0].length);if(!e){return true}n=x.ID_Continue.exec(e);return!!n&&n[0].length===e.length}function parse_js_number(e,t=true){if(!t&&e.includes("e")){return NaN}if(h.test(e)){return parseInt(e.substr(2),16)}else if(m.test(e)){return parseInt(e.substr(1),8)}else if(E.test(e)){return parseInt(e.substr(2),8)}else if(g.test(e)){return parseInt(e.substr(2),2)}else if(v.test(e)){return parseFloat(e)}else{var n=parseFloat(e);if(n==e)return n}}class JS_Parse_Error extends Error{constructor(e,t,n,i,r){super();this.name="SyntaxError";this.message=e;this.filename=t;this.line=n;this.col=i;this.pos=r}}function js_error(e,t,n,i,r){throw new JS_Parse_Error(e,t,n,i,r)}function is_token(e,t,n){return e.type==t&&(n==null||e.value==n)}var R={};function tokenizer(e,t,n,i){var r={text:e,filename:t,pos:0,tokpos:0,line:1,tokline:0,col:0,tokcol:0,newline_before:false,regex_allowed:false,brace_counter:0,template_braces:[],comments_before:[],directives:{},directive_stack:[]};function peek(){return get_full_char(r.text,r.pos)}function is_option_chain_op(){const e=r.text.charCodeAt(r.pos+1)===46;if(!e)return false;const t=r.text.charCodeAt(r.pos+2);return t<48||t>57}function next(e,t){var n=get_full_char(r.text,r.pos++);if(e&&!n)throw R;if(S.has(n)){r.newline_before=r.newline_before||!t;++r.line;r.col=0;if(n=="\r"&&peek()=="\n"){++r.pos;n="\n"}}else{if(n.length>1){++r.pos;++r.col}++r.col}return n}function forward(e){while(e--)next()}function looking_at(e){return r.text.substr(r.pos,e.length)==e}function find_eol(){var e=r.text;for(var t=r.pos,n=r.text.length;t="0"&&e<="7"}function read_escaped_char(e,t,n){var i=next(true,e);switch(i.charCodeAt(0)){case 110:return"\n";case 114:return"\r";case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 120:return String.fromCharCode(hex_bytes(2,t));case 117:if(peek()=="{"){next(true);if(peek()==="}")parse_error("Expecting hex-character between {}");while(peek()=="0")next(true);var a,o=find("}",true)-r.pos;if(o>6||(a=hex_bytes(o,t))>1114111){parse_error("Unicode reference out of bounds")}next(true);return from_char_code(a)}return String.fromCharCode(hex_bytes(4,t));case 10:return"";case 13:if(peek()=="\n"){next(true,e);return""}}if(is_octal(i)){if(n&&t){const e=i==="0"&&!is_octal(peek());if(!e){parse_error("Octal escape sequences are not allowed in template strings")}}return read_octal_escape_sequence(i,t)}return i}function read_octal_escape_sequence(e,t){var n=peek();if(n>="0"&&n<="7"){e+=next(true);if(e[0]<="3"&&(n=peek())>="0"&&n<="7")e+=next(true)}if(e==="0")return"\0";if(e.length>0&&next_token.has_directive("use strict")&&t)parse_error("Legacy octal escape sequences are not allowed in strict mode");return String.fromCharCode(parseInt(e,8))}function hex_bytes(e,t){var n=0;for(;e>0;--e){if(!t&&isNaN(parseInt(peek(),16))){return parseInt(n,16)||""}var i=next(true);if(isNaN(parseInt(i,16)))parse_error("Invalid hex-character pattern in string");n+=i}return parseInt(n,16)}var E=with_eof_error("Unterminated string constant",(function(){const e=r.pos;var t=next(),n=[];for(;;){var i=next(true,true);if(i=="\\")i=read_escaped_char(true,true);else if(i=="\r"||i=="\n")parse_error("Unterminated string constant");else if(i==t)break;n.push(i)}var a=token("string",n.join(""));s=r.text.slice(e,r.pos);a.quote=t;return a}));var g=with_eof_error("Unterminated template",(function(e){if(e){r.template_braces.push(r.brace_counter)}var t="",n="",i,a;next(true,true);while((i=next(true,true))!="`"){if(i=="\r"){if(peek()=="\n")++r.pos;i="\n"}else if(i=="$"&&peek()=="{"){next(true,true);r.brace_counter++;a=token(e?"template_head":"template_substitution",t);s=n;u=false;return a}n+=i;if(i=="\\"){var l=r.pos;var c=o&&(o.type==="name"||o.type==="punc"&&(o.value===")"||o.value==="]"));i=read_escaped_char(true,!c,true);n+=r.text.substr(l,r.pos-l)}t+=i}r.template_braces.pop();a=token(e?"template_head":"template_substitution",t);s=n;u=true;return a}));function skip_line_comment(e){var t=r.regex_allowed;var n=find_eol(),i;if(n==-1){i=r.text.substr(r.pos);r.pos=r.text.length}else{i=r.text.substring(r.pos,n);r.pos=n}r.col=r.tokcol+(r.pos-r.tokpos);r.comments_before.push(token(e,i,true));r.regex_allowed=t;return next_token}var v=with_eof_error("Unterminated multiline comment",(function(){var e=r.regex_allowed;var t=find("*/",true);var n=r.text.substring(r.pos,t).replace(/\r\n|\r|\u2028|\u2029/g,"\n");forward(get_full_char_length(n)+2);r.comments_before.push(token("comment2",n,true));r.newline_before=r.newline_before||n.includes("\n");r.regex_allowed=e;return next_token}));var A=with_eof_error("Unterminated identifier name",(function(){var e=[],t,n=false;var read_escaped_identifier_char=function(){n=true;next();if(peek()!=="u"){parse_error("Expecting UnicodeEscapeSequence -- uXXXX or u{XXXX}")}return read_escaped_char(false,true)};if((t=peek())==="\\"){t=read_escaped_identifier_char();if(!is_identifier_start(t)){parse_error("First identifier char is an invalid identifier char")}}else if(is_identifier_start(t)){next()}else{return""}e.push(t);while((t=peek())!=null){if((t=peek())==="\\"){t=read_escaped_identifier_char();if(!is_identifier_char(t)){parse_error("Invalid escaped identifier char")}}else{if(!is_identifier_char(t)){break}next()}e.push(t)}const i=e.join("");if(f.has(i)&&n){parse_error("Escaped characters are not allowed in keywords")}return i}));var x=with_eof_error("Unterminated regular expression",(function(e){var t=false,n,i=false;while(n=next(true))if(S.has(n)){parse_error("Unexpected line terminator")}else if(t){e+="\\"+n;t=false}else if(n=="["){i=true;e+=n}else if(n=="]"&&i){i=false;e+=n}else if(n=="/"&&!i){break}else if(n=="\\"){t=true}else{e+=n}const r=A();return token("regexp","/"+e+"/"+r)}));function read_operator(e){function grow(e){if(!peek())return e;var t=e+peek();if(D.has(t)){next();return grow(t)}else{return e}}return token("operator",grow(e||next()))}function handle_slash(){next();switch(peek()){case"/":next();return skip_line_comment("comment1");case"*":next();return v()}return r.regex_allowed?x(""):read_operator("/")}function handle_eq_sign(){next();if(peek()===">"){next();return token("arrow","=>")}else{return read_operator("=")}}function handle_dot(){next();if(is_digit(peek().charCodeAt(0))){return read_num(".")}if(peek()==="."){next();next();return token("expand","...")}return token("punc",".")}function read_word(){var e=A();if(a)return token("name",e);return c.has(e)?token("atom",e):!l.has(e)?token("name",e):D.has(e)?token("operator",e):token("keyword",e)}function read_private_word(){next();return token("privatename",A())}function with_eof_error(e,t){return function(n){try{return t(n)}catch(t){if(t===R)parse_error(e);else throw t}}}function next_token(e){if(e!=null)return x(e);if(i&&r.pos==0&&looking_at("#!")){start_token();forward(2);skip_line_comment("comment5")}for(;;){skip_whitespace();start_token();if(n){if(looking_at("\x3c!--")){forward(4);skip_line_comment("comment3");continue}if(looking_at("--\x3e")&&r.newline_before){forward(3);skip_line_comment("comment4");continue}}var t=peek();if(!t)return token("eof");var a=t.charCodeAt(0);switch(a){case 34:case 39:return E();case 46:return handle_dot();case 47:{var o=handle_slash();if(o===next_token)continue;return o}case 61:return handle_eq_sign();case 63:{if(!is_option_chain_op())break;next();next();return token("punc","?.")}case 96:return g(true);case 123:r.brace_counter++;break;case 125:r.brace_counter--;if(r.template_braces.length>0&&r.template_braces[r.template_braces.length-1]===r.brace_counter)return g(false);break}if(is_digit(a))return read_num();if(T.has(t))return token("punc",next());if(_.has(t))return read_operator();if(a==92||is_identifier_start(t))return read_word();if(a==35)return read_private_word();break}parse_error("Unexpected character '"+t+"'")}next_token.next=next;next_token.peek=peek;next_token.context=function(e){if(e)r=e;return r};next_token.add_directive=function(e){r.directive_stack[r.directive_stack.length-1].push(e);if(r.directives[e]===undefined){r.directives[e]=1}else{r.directives[e]++}};next_token.push_directives_stack=function(){r.directive_stack.push([])};next_token.pop_directives_stack=function(){var e=r.directive_stack[r.directive_stack.length-1];for(var t=0;t0};return next_token}var w=makePredicate(["typeof","void","delete","--","++","!","~","-","+"]);var O=makePredicate(["--","++"]);var F=makePredicate(["=","+=","-=","??=","&&=","||=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&="]);var N=makePredicate(["??=","&&=","||="]);var M=function(e,t){for(var n=0;n","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],{});var I=makePredicate(["atom","num","big_int","string","regexp","name"]);function parse(e,t){const n=new WeakMap;t=defaults(t,{bare_returns:false,ecma:null,expression:false,filename:null,html5_comments:true,module:false,shebang:true,strict:false,toplevel:null},true);var i={input:typeof e=="string"?tokenizer(e,t.filename,t.html5_comments,t.shebang):e,token:null,prev:null,peeked:null,in_function:0,in_async:-1,in_generator:-1,in_directives:true,in_loop:0,labels:[]};i.token=next();function is(e,t){return is_token(i.token,e,t)}function peek(){return i.peeked||(i.peeked=i.input())}function next(){i.prev=i.token;if(!i.peeked)peek();i.token=i.peeked;i.peeked=null;i.in_directives=i.in_directives&&(i.token.type=="string"||is("punc",";"));return i.token}function prev(){return i.prev}function croak(e,t,n,r){var a=i.input.context();js_error(e,a.filename,t!=null?t:a.tokline,n!=null?n:a.tokcol,r!=null?r:a.tokpos)}function token_error(e,t){croak(t,e.line,e.col)}function unexpected(e){if(e==null)e=i.token;token_error(e,"Unexpected token: "+e.type+" ("+e.value+")")}function expect_token(e,t){if(is(e,t)){return next()}token_error(i.token,"Unexpected token "+i.token.type+" «"+i.token.value+"»"+", expected "+e+" «"+t+"»")}function expect(e){return expect_token("punc",e)}function has_newline_before(e){return e.nlb||!e.comments_before.every((e=>!e.nlb))}function can_insert_semicolon(){return!t.strict&&(is("eof")||is("punc","}")||has_newline_before(i.token))}function is_in_generator(){return i.in_generator===i.in_function}function is_in_async(){return i.in_async===i.in_function}function can_await(){return i.in_async===i.in_function||i.in_function===0&&i.input.has_directive("use strict")}function semicolon(e){if(is("punc",";"))next();else if(!e&&!can_insert_semicolon())unexpected()}function parenthesised(){expect("(");var e=expression(true);expect(")");return e}function embed_tokens(e){return function _embed_tokens_wrapper(...t){const n=i.token;const r=e(...t);r.start=n;r.end=prev();return r}}function handle_regexp(){if(is("operator","/")||is("operator","/=")){i.peeked=null;i.token=i.input(i.token.value.substr(1))}}var r=embed_tokens((function statement(e,n,r){handle_regexp();switch(i.token.type){case"string":if(i.in_directives){var a=peek();if(!s.includes("\\")&&(is_token(a,"punc",";")||is_token(a,"punc","}")||has_newline_before(a)||is_token(a,"eof"))){i.input.add_directive(i.token.value)}else{i.in_directives=false}}var o=i.in_directives,u=simple_statement();return o&&u.body instanceof Gt?new K(u.body):u;case"template_head":case"num":case"big_int":case"regexp":case"operator":case"atom":return simple_statement();case"name":if(i.token.value=="async"&&is_token(peek(),"keyword","function")){next();next();if(n){croak("functions are not allowed as the body of a loop")}return function_(ce,false,true,e)}if(i.token.value=="import"&&!is_token(peek(),"punc","(")&&!is_token(peek(),"punc",".")){next();var l=import_();semicolon();return l}return is_token(peek(),"punc",":")?labeled_statement():simple_statement();case"punc":switch(i.token.value){case"{":return new X({start:i.token,body:block_(),end:prev()});case"[":case"(":return simple_statement();case";":i.in_directives=false;next();return new W;default:unexpected()}case"keyword":switch(i.token.value){case"break":next();return break_cont(be);case"continue":next();return break_cont(De);case"debugger":next();semicolon();return new z;case"do":next();var c=in_loop(statement);expect_token("keyword","while");var f=parenthesised();semicolon(true);return new Z({body:c,condition:f});case"while":next();return new Q({condition:parenthesised(),body:in_loop((function(){return statement(false,true)}))});case"for":next();return for_();case"class":next();if(n){croak("classes are not allowed as the body of a loop")}if(r){croak("classes are not allowed as the body of an if")}return class_(mt,e);case"function":next();if(n){croak("functions are not allowed as the body of a loop")}return function_(ce,false,false,e);case"if":next();return if_();case"return":if(i.in_function==0&&!t.bare_returns)croak("'return' outside of function");next();var p=null;if(is("punc",";")){next()}else if(!can_insert_semicolon()){p=expression(true);semicolon()}return new Ee({value:p});case"switch":next();return new ke({expression:parenthesised(),body:in_loop(switch_body_)});case"throw":next();if(has_newline_before(i.token))croak("Illegal newline after 'throw'");var p=expression(true);semicolon();return new ge({value:p});case"try":next();return try_();case"var":next();var l=var_();semicolon();return l;case"let":next();var l=let_();semicolon();return l;case"const":next();var l=const_();semicolon();return l;case"with":if(i.input.has_directive("use strict")){croak("Strict mode may not include a with statement")}next();return new ne({expression:parenthesised(),body:statement()});case"export":if(!is_token(peek(),"punc","(")){next();var l=export_();if(is("punc",";"))semicolon();return l}}}unexpected()}));function labeled_statement(){var e=as_symbol(It);if(e.name==="await"&&is_in_async()){token_error(i.prev,"await cannot be used as label inside async function")}if(i.labels.some((t=>t.name===e.name))){croak("Label "+e.name+" defined twice")}expect(":");i.labels.push(e);var t=r();i.labels.pop();if(!(t instanceof j)){e.references.forEach((function(t){if(t instanceof De){t=t.label.start;croak("Continue label `"+e.name+"` refers to non-IterationStatement.",t.line,t.col,t.pos)}}))}return new Y({body:t,label:e})}function simple_statement(e){return new G({body:(e=expression(true),semicolon(),e)})}function break_cont(e){var t=null,n;if(!can_insert_semicolon()){t=as_symbol(Vt,true)}if(t!=null){n=i.labels.find((e=>e.name===t.name));if(!n)croak("Undefined label "+t.name);t.thedef=n}else if(i.in_loop==0)croak(e.TYPE+" not inside a loop or switch");semicolon();var r=new e({label:t});if(n)n.references.push(r);return r}function for_(){var e="`for await` invalid in this context";var t=i.token;if(t.type=="name"&&t.value=="await"){if(!can_await()){token_error(t,e)}next()}else{t=false}expect("(");var n=null;if(!is("punc",";")){n=is("keyword","var")?(next(),var_(true)):is("keyword","let")?(next(),let_(true)):is("keyword","const")?(next(),const_(true)):expression(true,true);var r=is("operator","in");var a=is("name","of");if(t&&!a){token_error(t,e)}if(r||a){if(n instanceof Fe){if(n.definitions.length>1)token_error(n.start,"Only one variable declaration allowed in for..in loop")}else if(!(is_assignable(n)||(n=to_destructuring(n))instanceof fe)){token_error(n.start,"Invalid left-hand side in for..in loop")}next();if(r){return for_in(n)}else{return for_of(n,!!t)}}}else if(t){token_error(t,e)}return regular_for(n)}function regular_for(e){expect(";");var t=is("punc",";")?null:expression(true);expect(";");var n=is("punc",")")?null:expression(true);expect(")");return new J({init:e,condition:t,step:n,body:in_loop((function(){return r(false,true)}))})}function for_of(e,t){var n=e instanceof Fe?e.definitions[0].name:null;var i=expression(true);expect(")");return new te({await:t,init:e,name:n,object:i,body:in_loop((function(){return r(false,true)}))})}function for_in(e){var t=expression(true);expect(")");return new ee({init:e,object:t,body:in_loop((function(){return r(false,true)}))})}var arrow_function=function(e,t,n){if(has_newline_before(i.token)){croak("Unexpected newline before arrow (=>)")}expect_token("arrow","=>");var r=_function_body(is("punc","{"),false,n);var a=r instanceof Array&&r.length?r[r.length-1].end:r instanceof Array?e:r.end;return new le({start:e,end:a,async:n,argnames:t,body:r})};var function_=function(e,t,n,i){var r=e===ce;var a=is("operator","*");if(a){next()}var o=is("name")?as_symbol(r?Tt:Rt):null;if(r&&!o){if(i){e=ue}else{unexpected()}}if(o&&e!==se&&!(o instanceof bt))unexpected(prev());var s=[];var u=_function_body(true,a||t,n,o,s);return new e({start:s.start,end:u.end,is_generator:a,async:n,name:o,argnames:s,body:u})};function track_used_binding_identifiers(e,t){var n=new Set;var i=false;var r=false;var a=false;var o=!!t;var s={add_parameter:function(t){if(n.has(t.value)){if(i===false){i=t}s.check_strict()}else{n.add(t.value);if(e){switch(t.value){case"arguments":case"eval":case"yield":if(o){token_error(t,"Unexpected "+t.value+" identifier as parameter inside strict mode")}break;default:if(f.has(t.value)){unexpected()}}}}},mark_default_assignment:function(e){if(r===false){r=e}},mark_spread:function(e){if(a===false){a=e}},mark_strict_mode:function(){o=true},is_strict:function(){return r!==false||a!==false||o},check_strict:function(){if(s.is_strict()&&i!==false){token_error(i,"Parameter "+i.value+" was used already")}}};return s}function parameters(e){var t=track_used_binding_identifiers(true,i.input.has_directive("use strict"));expect("(");while(!is("punc",")")){var n=parameter(t);e.push(n);if(!is("punc",")")){expect(",")}if(n instanceof ae){break}}next()}function parameter(e,t){var n;var r=false;if(e===undefined){e=track_used_binding_identifiers(true,i.input.has_directive("use strict"))}if(is("expand","...")){r=i.token;e.mark_spread(i.token);next()}n=binding_element(e,t);if(is("operator","=")&&r===false){e.mark_default_assignment(i.token);next();n=new tt({start:n.start,left:n,operator:"=",right:expression(false),end:i.token})}if(r!==false){if(!is("punc",")")){unexpected()}n=new ae({start:r,expression:n,end:r})}e.check_strict();return n}function binding_element(e,t){var n=[];var r=true;var a=false;var o;var s=i.token;if(e===undefined){e=track_used_binding_identifiers(false,i.input.has_directive("use strict"))}t=t===undefined?kt:t;if(is("punc","[")){next();while(!is("punc","]")){if(r){r=false}else{expect(",")}if(is("expand","...")){a=true;o=i.token;e.mark_spread(i.token);next()}if(is("punc")){switch(i.token.value){case",":n.push(new Zt({start:i.token,end:i.token}));continue;case"]":break;case"[":case"{":n.push(binding_element(e,t));break;default:unexpected()}}else if(is("name")){e.add_parameter(i.token);n.push(as_symbol(t))}else{croak("Invalid function parameter")}if(is("operator","=")&&a===false){e.mark_default_assignment(i.token);next();n[n.length-1]=new tt({start:n[n.length-1].start,left:n[n.length-1],operator:"=",right:expression(false),end:i.token})}if(a){if(!is("punc","]")){croak("Rest element must be last element")}n[n.length-1]=new ae({start:o,expression:n[n.length-1],end:o})}}expect("]");e.check_strict();return new fe({start:s,names:n,is_array:true,end:prev()})}else if(is("punc","{")){next();while(!is("punc","}")){if(r){r=false}else{expect(",")}if(is("expand","...")){a=true;o=i.token;e.mark_spread(i.token);next()}if(is("name")&&(is_token(peek(),"punc")||is_token(peek(),"operator"))&&[",","}","="].includes(peek().value)){e.add_parameter(i.token);var u=prev();var l=as_symbol(t);if(a){n.push(new ae({start:o,expression:l,end:l.end}))}else{n.push(new ot({start:u,key:l.name,value:l,end:l.end}))}}else if(is("punc","}")){continue}else{var c=i.token;var f=as_property_name();if(f===null){unexpected(prev())}else if(prev().type==="name"&&!is("punc",":")){n.push(new ot({start:prev(),key:f,value:new t({start:prev(),name:f,end:prev()}),end:prev()}))}else{expect(":");n.push(new ot({start:c,quote:c.quote,key:f,value:binding_element(e,t),end:prev()}))}}if(a){if(!is("punc","}")){croak("Rest element must be last element")}}else if(is("operator","=")){e.mark_default_assignment(i.token);next();n[n.length-1].value=new tt({start:n[n.length-1].value.start,left:n[n.length-1].value,operator:"=",right:expression(false),end:i.token})}}expect("}");e.check_strict();return new fe({start:s,names:n,is_array:false,end:prev()})}else if(is("name")){e.add_parameter(i.token);return as_symbol(t)}else{croak("Invalid function parameter")}}function params_or_seq_(e,t){var n;var r;var a;var o=[];expect("(");while(!is("punc",")")){if(n)unexpected(n);if(is("expand","...")){n=i.token;if(t)r=i.token;next();o.push(new ae({start:prev(),expression:expression(),end:i.token}))}else{o.push(expression())}if(!is("punc",")")){expect(",");if(is("punc",")")){a=prev();if(t)r=a}}}expect(")");if(e&&is("arrow","=>")){if(n&&a)unexpected(a)}else if(r){unexpected(r)}return o}function _function_body(e,t,n,r,a){var o=i.in_loop;var s=i.labels;var u=i.in_generator;var l=i.in_async;++i.in_function;if(t)i.in_generator=i.in_function;if(n)i.in_async=i.in_function;if(a)parameters(a);if(e)i.in_directives=true;i.in_loop=0;i.labels=[];if(e){i.input.push_directives_stack();var c=block_();if(r)_verify_symbol(r);if(a)a.forEach(_verify_symbol);i.input.pop_directives_stack()}else{var c=[new Ee({start:i.token,value:expression(false),end:i.token})]}--i.in_function;i.in_loop=o;i.labels=s;i.in_generator=u;i.in_async=l;return c}function _await_expression(){if(!can_await()){croak("Unexpected await expression outside async function",i.prev.line,i.prev.col,i.prev.pos)}return new ye({start:prev(),end:i.token,expression:maybe_unary(true)})}function _yield_expression(){if(!is_in_generator()){croak("Unexpected yield expression outside generator function",i.prev.line,i.prev.col,i.prev.pos)}var e=i.token;var t=false;var n=true;if(can_insert_semicolon()||is("punc")&&A.has(i.token.value)){n=false}else if(is("operator","*")){t=true;next()}return new Se({start:e,is_star:t,expression:n?expression():null,end:prev()})}function if_(){var e=parenthesised(),t=r(false,false,true),n=null;if(is("keyword","else")){next();n=r(false,false,true)}return new Ae({condition:e,body:t,alternative:n})}function block_(){expect("{");var e=[];while(!is("punc","}")){if(is("eof"))unexpected();e.push(r())}next();return e}function switch_body_(){expect("{");var e=[],t=null,n=null,a;while(!is("punc","}")){if(is("eof"))unexpected();if(is("keyword","case")){if(n)n.end=prev();t=[];n=new Ce({start:(a=i.token,next(),a),expression:expression(true),body:t});e.push(n);expect(":")}else if(is("keyword","default")){if(n)n.end=prev();t=[];n=new xe({start:(a=i.token,next(),expect(":"),a),body:t});e.push(n)}else{if(!t)unexpected();t.push(r())}}if(n)n.end=prev();next();return e}function try_(){var e=block_(),t=null,n=null;if(is("keyword","catch")){var r=i.token;next();if(is("punc","{")){var a=null}else{expect("(");var a=parameter(undefined,Ft);expect(")")}t=new we({start:r,argname:a,body:block_(),end:prev()})}if(is("keyword","finally")){var r=i.token;next();n=new Oe({start:r,body:block_(),end:prev()})}if(!t&&!n)croak("Missing catch/finally blocks");return new Re({body:e,bcatch:t,bfinally:n})}function vardefs(e,t){var n=[];var r;for(;;){var a=t==="var"?Dt:t==="const"?St:t==="let"?At:null;if(is("punc","{")||is("punc","[")){r=new Pe({start:i.token,name:binding_element(undefined,a),value:is("operator","=")?(expect_token("operator","="),expression(false,e)):null,end:prev()})}else{r=new Pe({start:i.token,name:as_symbol(a),value:is("operator","=")?(next(),expression(false,e)):!e&&t==="const"?croak("Missing initializer in const declaration"):null,end:prev()});if(r.name.name=="import")croak("Unexpected token: import")}n.push(r);if(!is("punc",","))break;next()}return n}var var_=function(e){return new Ne({start:prev(),definitions:vardefs(e,"var"),end:prev()})};var let_=function(e){return new Me({start:prev(),definitions:vardefs(e,"let"),end:prev()})};var const_=function(e){return new Ie({start:prev(),definitions:vardefs(e,"const"),end:prev()})};var new_=function(e){var t=i.token;expect_token("operator","new");if(is("punc",".")){next();expect_token("name","target");return subscripts(new vt({start:t,end:prev()}),e)}var n=expr_atom(false),r;if(is("punc","(")){next();r=expr_list(")",true)}else{r=[]}var a=new Ke({start:t,expression:n,args:r,end:prev()});annotate(a);return subscripts(a,e)};function as_atom_node(){var e=i.token,t;switch(e.type){case"name":t=_make_symbol(Pt);break;case"num":t=new Ht({start:e,end:e,value:e.value,raw:s});break;case"big_int":t=new Xt({start:e,end:e,value:e.value});break;case"string":t=new Gt({start:e,end:e,value:e.value,quote:e.quote});break;case"regexp":const[n,i,r]=e.value.match(/^\/(.*)\/(\w*)$/);t=new Wt({start:e,end:e,value:{source:i,flags:r}});break;case"atom":switch(e.value){case"false":t=new en({start:e,end:e});break;case"true":t=new tn({start:e,end:e});break;case"null":t=new Yt({start:e,end:e});break}break}next();return t}function to_fun_args(e,t){var insert_default=function(e,t){if(t){return new tt({start:e.start,left:e,operator:"=",right:t,end:t.end})}return e};if(e instanceof it){return insert_default(new fe({start:e.start,end:e.end,is_array:false,names:e.properties.map((e=>to_fun_args(e)))}),t)}else if(e instanceof ot){e.value=to_fun_args(e.value);return insert_default(e,t)}else if(e instanceof Zt){return e}else if(e instanceof fe){e.names=e.names.map((e=>to_fun_args(e)));return insert_default(e,t)}else if(e instanceof Pt){return insert_default(new kt({name:e.name,start:e.start,end:e.end}),t)}else if(e instanceof ae){e.expression=to_fun_args(e.expression);return insert_default(e,t)}else if(e instanceof nt){return insert_default(new fe({start:e.start,end:e.end,is_array:true,names:e.elements.map((e=>to_fun_args(e)))}),t)}else if(e instanceof et){return insert_default(to_fun_args(e.left,e.right),t)}else if(e instanceof tt){e.left=to_fun_args(e.left);return e}else{croak("Invalid function parameter",e.start.line,e.start.col)}}var expr_atom=function(e,t){if(is("operator","new")){return new_(e)}if(is("operator","import")){return import_meta()}var r=i.token;var o;var s=is("name","async")&&(o=peek()).value!="["&&o.type!="arrow"&&as_atom_node();if(is("punc")){switch(i.token.value){case"(":if(s&&!e)break;var u=params_or_seq_(t,!s);if(t&&is("arrow","=>")){return arrow_function(r,u.map((e=>to_fun_args(e))),!!s)}var c=s?new ze({expression:s,args:u}):u.length==1?u[0]:new Ge({expressions:u});if(c.start){const e=r.comments_before.length;n.set(r,e);c.start.comments_before.unshift(...r.comments_before);r.comments_before=c.start.comments_before;if(e==0&&r.comments_before.length>0){var f=r.comments_before[0];if(!f.nlb){f.nlb=r.nlb;r.nlb=false}}r.comments_after=c.start.comments_after}c.start=r;var p=prev();if(c.end){p.comments_before=c.end.comments_before;c.end.comments_after.push(...p.comments_after);p.comments_after=c.end.comments_after}c.end=p;if(c instanceof ze)annotate(c);return subscripts(c,e);case"[":return subscripts(a(),e);case"{":return subscripts(l(),e)}if(!s)unexpected()}if(t&&is("name")&&is_token(peek(),"arrow")){var _=new kt({name:i.token.value,start:r,end:r});next();return arrow_function(r,[_],!!s)}if(is("keyword","function")){next();var d=function_(ue,false,!!s);d.start=r;d.end=prev();return subscripts(d,e)}if(s)return subscripts(s,e);if(is("keyword","class")){next();var h=class_(Et);h.start=r;h.end=prev();return subscripts(h,e)}if(is("template_head")){return subscripts(template_string(),e)}if(I.has(i.token.type)){return subscripts(as_atom_node(),e)}unexpected()};function template_string(){var e=[],t=i.token;e.push(new de({start:i.token,raw:s,value:i.token.value,end:i.token}));while(!u){next();handle_regexp();e.push(expression(true));e.push(new de({start:i.token,raw:s,value:i.token.value,end:i.token}))}next();return new _e({start:t,segments:e,end:i.token})}function expr_list(e,t,n){var r=true,a=[];while(!is("punc",e)){if(r)r=false;else expect(",");if(t&&is("punc",e))break;if(is("punc",",")&&n){a.push(new Zt({start:i.token,end:i.token}))}else if(is("expand","...")){next();a.push(new ae({start:prev(),expression:expression(),end:i.token}))}else{a.push(expression(false))}}next();return a}var a=embed_tokens((function(){expect("[");return new nt({elements:expr_list("]",!t.strict,true)})}));var o=embed_tokens(((e,t)=>function_(se,e,t)));var l=embed_tokens((function object_or_destructuring_(){var e=i.token,n=true,r=[];expect("{");while(!is("punc","}")){if(n)n=false;else expect(",");if(!t.strict&&is("punc","}"))break;e=i.token;if(e.type=="expand"){next();r.push(new ae({start:e,expression:expression(false),end:prev()}));continue}var a=as_property_name();var o;if(!is("punc",":")){var s=concise_method_or_getset(a,e);if(s){r.push(s);continue}o=new Pt({start:prev(),name:a,end:prev()})}else if(a===null){unexpected(prev())}else{next();o=expression(false)}if(is("operator","=")){next();o=new et({start:e,left:o,operator:"=",right:expression(false),logical:false,end:prev()})}r.push(new ot({start:e,quote:e.quote,key:a instanceof V?a:""+a,value:o,end:prev()}))}next();return new it({properties:r})}));function class_(e,t){var n,r,a,o,s=[];i.input.push_directives_stack();i.input.add_directive("use strict");if(i.token.type=="name"&&i.token.value!="extends"){a=as_symbol(e===mt?wt:Ot)}if(e===mt&&!a){if(t){e=Et}else{unexpected()}}if(i.token.value=="extends"){next();o=expression(true)}expect("{");while(is("punc",";")){next()}while(!is("punc","}")){n=i.token;r=concise_method_or_getset(as_property_name(),n,true);if(!r){unexpected()}s.push(r);while(is("punc",";")){next()}}i.input.pop_directives_stack();next();return new e({start:n,name:a,extends:o,properties:s,end:prev()})}function concise_method_or_getset(e,t,n){const get_symbol_ast=(e,n=xt)=>{if(typeof e==="string"||typeof e==="number"){return new n({start:t,name:""+e,end:prev()})}else if(e===null){unexpected()}return e};const is_not_method_start=()=>!is("punc","(")&&!is("punc",",")&&!is("punc","}")&&!is("operator","=");var i=false;var r=false;var a=false;var s=false;var u=null;if(n&&e==="static"&&is_not_method_start()){r=true;e=as_property_name()}if(e==="async"&&is_not_method_start()){i=true;e=as_property_name()}if(prev().type==="operator"&&prev().value==="*"){a=true;e=as_property_name()}if((e==="get"||e==="set")&&is_not_method_start()){u=e;e=as_property_name()}if(prev().type==="privatename"){s=true}const l=prev();if(u!=null){if(!s){const n=u==="get"?ct:lt;e=get_symbol_ast(e);return new n({start:t,static:r,key:e,quote:e instanceof xt?l.quote:undefined,value:o(),end:prev()})}else{const n=u==="get"?ut:st;return new n({start:t,static:r,key:get_symbol_ast(e),value:o(),end:prev()})}}if(is("punc","(")){e=get_symbol_ast(e);const n=s?pt:ft;var c=new n({start:t,static:r,is_generator:a,async:i,key:e,quote:e instanceof xt?l.quote:undefined,value:o(a,i),end:prev()});return c}if(n){const n=get_symbol_ast(e,Ct);const i=n instanceof Ct?l.quote:undefined;const a=s?ht:dt;if(is("operator","=")){next();return new a({start:t,static:r,quote:i,key:n,value:expression(false),end:prev()})}else if(is("name")||is("privatename")||is("operator","*")||is("punc",";")||is("punc","}")){return new a({start:t,static:r,quote:i,key:n,end:prev()})}}}function import_(){var e=prev();var t;var n;if(is("name")){t=as_symbol(Nt)}if(is("punc",",")){next()}n=map_names(true);if(n||t){expect_token("name","from")}var r=i.token;if(r.type!=="string"){unexpected()}next();return new Be({start:e,imported_name:t,imported_names:n,module_name:new Gt({start:r,value:r.value,quote:r.quote,end:r}),end:i.token})}function import_meta(){var e=i.token;expect_token("operator","import");expect_token("punc",".");expect_token("name","meta");return subscripts(new Ve({start:e,end:prev()}),false)}function map_name(e){function make_symbol(e){return new e({name:as_property_name(),start:prev(),end:prev()})}var t=e?Mt:Bt;var n=e?Nt:Lt;var r=i.token;var a;var o;if(e){a=make_symbol(t)}else{o=make_symbol(n)}if(is("name","as")){next();if(e){o=make_symbol(n)}else{a=make_symbol(t)}}else if(e){o=new n(a)}else{a=new t(o)}return new Le({start:r,foreign_name:a,name:o,end:prev()})}function map_nameAsterisk(e,t){var n=e?Mt:Bt;var r=e?Nt:Lt;var a=i.token;var o;var s=prev();t=t||new r({name:"*",start:a,end:s});o=new n({name:"*",start:a,end:s});return new Le({start:a,foreign_name:o,name:t,end:s})}function map_names(e){var t;if(is("punc","{")){next();t=[];while(!is("punc","}")){t.push(map_name(e));if(is("punc",",")){next()}}next()}else if(is("operator","*")){var n;next();if(e&&is("name","as")){next();n=as_symbol(e?Nt:Bt)}t=[map_nameAsterisk(e,n)]}return t}function export_(){var e=i.token;var t;var n;if(is("keyword","default")){t=true;next()}else if(n=map_names(false)){if(is("name","from")){next();var a=i.token;if(a.type!=="string"){unexpected()}next();return new Ue({start:e,is_default:t,exported_names:n,module_name:new Gt({start:a,value:a.value,quote:a.quote,end:a}),end:prev()})}else{return new Ue({start:e,is_default:t,exported_names:n,end:prev()})}}var o;var s;var u;if(is("punc","{")||t&&(is("keyword","class")||is("keyword","function"))&&is_token(peek(),"punc")){s=expression(false);semicolon()}else if((o=r(t))instanceof Fe&&t){unexpected(o.start)}else if(o instanceof Fe||o instanceof ce||o instanceof mt){u=o}else if(o instanceof Et||o instanceof ue){s=o}else if(o instanceof G){s=o.body}else{unexpected(o.start)}return new Ue({start:e,is_default:t,exported_value:s,exported_definition:u,end:prev()})}function as_property_name(){var e=i.token;switch(e.type){case"punc":if(e.value==="["){next();var t=expression(false);expect("]");return t}else unexpected(e);case"operator":if(e.value==="*"){next();return null}if(!["delete","in","instanceof","new","typeof","void"].includes(e.value)){unexpected(e)}case"name":case"privatename":case"string":case"num":case"big_int":case"keyword":case"atom":next();return e.value;default:unexpected(e)}}function as_name(){var e=i.token;if(e.type!="name"&&e.type!="privatename")unexpected();next();return e.value}function _make_symbol(e){var t=i.token.value;return new(t=="this"?Ut:t=="super"?zt:e)({name:String(t),start:i.token,end:i.token})}function _verify_symbol(e){var t=e.name;if(is_in_generator()&&t=="yield"){token_error(e.start,"Yield cannot be used as identifier inside generators")}if(i.input.has_directive("use strict")){if(t=="yield"){token_error(e.start,"Unexpected yield identifier inside strict mode")}if(e instanceof bt&&(t=="arguments"||t=="eval")){token_error(e.start,"Unexpected "+t+" in strict mode")}}}function as_symbol(e,t){if(!is("name")){if(!t)croak("Name expected");return null}var n=_make_symbol(e);_verify_symbol(n);next();return n}function annotate(e){var t=e.start;var i=t.comments_before;const r=n.get(t);var a=r!=null?r:i.length;while(--a>=0){var o=i[a];if(/[@#]__/.test(o.value)){if(/[@#]__PURE__/.test(o.value)){set_annotation(e,rn);break}if(/[@#]__INLINE__/.test(o.value)){set_annotation(e,an);break}if(/[@#]__NOINLINE__/.test(o.value)){set_annotation(e,on);break}}}}var subscripts=function(e,t,n){var i=e.start;if(is("punc",".")){next();const r=is("privatename")?We:Xe;return subscripts(new r({start:i,expression:e,optional:false,property:as_name(),end:prev()}),t,n)}if(is("punc","[")){next();var r=expression(true);expect("]");return subscripts(new qe({start:i,expression:e,optional:false,property:r,end:prev()}),t,n)}if(t&&is("punc","(")){next();var a=new ze({start:i,expression:e,optional:false,args:call_args(),end:prev()});annotate(a);return subscripts(a,true,n)}if(is("punc","?.")){next();let n;if(t&&is("punc","(")){next();const t=new ze({start:i,optional:true,expression:e,args:call_args(),end:prev()});annotate(t);n=subscripts(t,true,true)}else if(is("name")||is("privatename")){const r=is("privatename")?We:Xe;n=subscripts(new r({start:i,expression:e,optional:true,property:as_name(),end:prev()}),t,true)}else if(is("punc","[")){next();const r=expression(true);expect("]");n=subscripts(new qe({start:i,expression:e,optional:true,property:r,end:prev()}),t,true)}if(!n)unexpected();if(n instanceof Ye)return n;return new Ye({start:i,expression:n,end:prev()})}if(is("template_head")){if(n){unexpected()}return subscripts(new pe({start:i,prefix:e,template_string:template_string(),end:prev()}),t)}return e};function call_args(){var e=[];while(!is("punc",")")){if(is("expand","...")){next();e.push(new ae({start:prev(),expression:expression(false),end:prev()}))}else{e.push(expression(false))}if(!is("punc",")")){expect(",")}}next();return e}var maybe_unary=function(e,t){var n=i.token;if(n.type=="name"&&n.value=="await"&&can_await()){next();return _await_expression()}if(is("operator")&&w.has(n.value)){next();handle_regexp();var r=make_unary($e,n,maybe_unary(e));r.start=n;r.end=prev();return r}var a=expr_atom(e,t);while(is("operator")&&O.has(i.token.value)&&!has_newline_before(i.token)){if(a instanceof le)unexpected();a=make_unary(Ze,i.token,a);a.start=n;a.end=i.token;next()}return a};function make_unary(e,t,n){var r=t.value;switch(r){case"++":case"--":if(!is_assignable(n))croak("Invalid use of "+r+" operator",t.line,t.col,t.pos);break;case"delete":if(n instanceof Pt&&i.input.has_directive("use strict"))croak("Calling delete on expression not allowed in strict mode",n.start.line,n.start.col,n.start.pos);break}return new e({operator:r,expression:n})}var expr_op=function(e,t,n){var r=is("operator")?i.token.value:null;if(r=="in"&&n)r=null;if(r=="**"&&e instanceof $e&&!is_token(e.start,"punc","(")&&e.operator!=="--"&&e.operator!=="++")unexpected(e.start);var a=r!=null?M[r]:null;if(a!=null&&(a>t||r==="**"&&t===a)){next();var o=expr_op(maybe_unary(true),a,n);return expr_op(new Qe({start:e.start,left:e,operator:r,right:o,end:o.end}),t,n)}return e};function expr_ops(e){return expr_op(maybe_unary(true,true),0,e)}var maybe_conditional=function(e){var t=i.token;var n=expr_ops(e);if(is("operator","?")){next();var r=expression(false);expect(":");return new Je({start:t,condition:n,consequent:r,alternative:expression(false,e),end:prev()})}return n};function is_assignable(e){return e instanceof He||e instanceof Pt}function to_destructuring(e){if(e instanceof it){e=new fe({start:e.start,names:e.properties.map(to_destructuring),is_array:false,end:e.end})}else if(e instanceof nt){var t=[];for(var n=0;n=0;){a+="this."+t[o]+" = props."+t[o]+";"}const s=i&&Object.create(i.prototype);if(s&&s.initialize||n&&n.initialize)a+="this.initialize();";a+="}";a+="this.flags = 0;";a+="}";var u=new Function(a)();if(s){u.prototype=s;u.BASE=i}if(i)i.SUBCLASSES.push(u);u.prototype.CTOR=u;u.prototype.constructor=u;u.PROPS=t||null;u.SELF_PROPS=r;u.SUBCLASSES=[];if(e){u.prototype.TYPE=u.TYPE=e}if(n)for(o in n)if(HOP(n,o)){if(o[0]==="$"){u[o.substr(1)]=n[o]}else{u.prototype[o]=n[o]}}u.DEFMETHOD=function(e,t){this.prototype[e]=t};return u}const has_tok_flag=(e,t)=>Boolean(e.flags&t);const set_tok_flag=(e,t,n)=>{if(n){e.flags|=t}else{e.flags&=~t}};const P=1;const L=2;const B=4;class AST_Token{constructor(e,t,n,i,r,a,o,s,u){this.flags=a?1:0;this.type=e;this.value=t;this.line=n;this.col=i;this.pos=r;this.comments_before=o;this.comments_after=s;this.file=u;Object.seal(this)}get nlb(){return has_tok_flag(this,P)}set nlb(e){set_tok_flag(this,P,e)}get quote(){return!has_tok_flag(this,B)?"":has_tok_flag(this,L)?"'":'"'}set quote(e){set_tok_flag(this,L,e==="'");set_tok_flag(this,B,!!e)}}var V=DEFNODE("Node","start end",{_clone:function(e){if(e){var t=this.clone();return t.transform(new TreeTransformer((function(e){if(e!==t){return e.clone(true)}})))}return new this.CTOR(this)},clone:function(e){return this._clone(e)},$documentation:"Base class of all AST nodes",$propdoc:{start:"[AST_Token] The first token of this node",end:"[AST_Token] The last token of this node"},_walk:function(e){return e._visit(this)},walk:function(e){return this._walk(e)},_children_backwards:()=>{}},null);var U=DEFNODE("Statement",null,{$documentation:"Base class of all statements"});var z=DEFNODE("Debugger",null,{$documentation:"Represents a debugger statement"},U);var K=DEFNODE("Directive","value quote",{$documentation:'Represents a directive, like "use strict";',$propdoc:{value:"[string] The value of this directive as a plain string (it's not an AST_String!)",quote:"[string] the original quote character"}},U);var G=DEFNODE("SimpleStatement","body",{$documentation:"A statement consisting of an expression, i.e. a = 1 + 2",$propdoc:{body:"[AST_Node] an expression node (should not be instanceof AST_Statement)"},_walk:function(e){return e._visit(this,(function(){this.body._walk(e)}))},_children_backwards(e){e(this.body)}},U);function walk_body(e,t){const n=e.body;for(var i=0,r=n.length;i SymbolDef for all variables/functions defined in this scope",uses_with:"[boolean/S] tells whether this scope uses the `with` statement",uses_eval:"[boolean/S] tells whether this scope contains a direct call to the global `eval`",parent_scope:"[AST_Scope?/S] link to the parent scope",enclosed:"[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",cname:"[integer/S] current index for mangling variables (used internally by the mangler)"},get_defun_scope:function(){var e=this;while(e.is_block_scope()){e=e.parent_scope}return e},clone:function(e,t){var n=this._clone(e);if(e&&this.variables&&t&&!this._block_scope){n.figure_out_scope({},{toplevel:t,parent_scope:this.parent_scope})}else{if(this.variables)n.variables=new Map(this.variables);if(this.enclosed)n.enclosed=this.enclosed.slice();if(this._block_scope)n._block_scope=this._block_scope}return n},pinned:function(){return this.uses_eval||this.uses_with}},H);var re=DEFNODE("Toplevel","globals",{$documentation:"The toplevel scope",$propdoc:{globals:"[Map/S] a map of name -> SymbolDef for all undeclared names"},wrap_commonjs:function(e){var t=this.body;var n="(function(exports){'$ORIG';})(typeof "+e+"=='undefined'?("+e+"={}):"+e+");";n=parse(n);n=n.transform(new TreeTransformer((function(e){if(e instanceof K&&e.value=="$ORIG"){return r.splice(t)}})));return n},wrap_enclose:function(e){if(typeof e!="string")e="";var t=e.indexOf(":");if(t<0)t=e.length;var n=this.body;return parse(["(function(",e.slice(0,t),'){"$ORIG"})(',e.slice(t+1),")"].join("")).transform(new TreeTransformer((function(e){if(e instanceof K&&e.value=="$ORIG"){return r.splice(n)}})))}},ie);var ae=DEFNODE("Expansion","expression",{$documentation:"An expandible argument, such as ...rest, a splat, such as [1,2,...all], or an expansion in a variable declaration, such as var [first, ...rest] = list",$propdoc:{expression:"[AST_Node] the thing to be expanded"},_walk:function(e){return e._visit(this,(function(){this.expression.walk(e)}))},_children_backwards(e){e(this.expression)}});var oe=DEFNODE("Lambda","name argnames uses_arguments is_generator async",{$documentation:"Base class for functions",$propdoc:{name:"[AST_SymbolDeclaration?] the name of this function",argnames:"[AST_SymbolFunarg|AST_Destructuring|AST_Expansion|AST_DefaultAssign*] array of function arguments, destructurings, or expanding arguments",uses_arguments:"[boolean/S] tells whether this function accesses the arguments array",is_generator:"[boolean] is this a generator method",async:"[boolean] is this method async"},args_as_names:function(){var e=[];for(var t=0;t b)"},oe);var ce=DEFNODE("Defun",null,{$documentation:"A function definition"},oe);var fe=DEFNODE("Destructuring","names is_array",{$documentation:"A destructuring of several names. Used in destructuring assignment and with destructuring function argument names",$propdoc:{names:"[AST_Node*] Array of properties or elements",is_array:"[Boolean] Whether the destructuring represents an object or array"},_walk:function(e){return e._visit(this,(function(){this.names.forEach((function(t){t._walk(e)}))}))},_children_backwards(e){let t=this.names.length;while(t--)e(this.names[t])},all_symbols:function(){var e=[];this.walk(new TreeWalker((function(t){if(t instanceof gt){e.push(t)}})));return e}});var pe=DEFNODE("PrefixedTemplateString","template_string prefix",{$documentation:"A templatestring with a prefix, such as String.raw`foobarbaz`",$propdoc:{template_string:"[AST_TemplateString] The template string",prefix:"[AST_Node] The prefix, which will get called."},_walk:function(e){return e._visit(this,(function(){this.prefix._walk(e);this.template_string._walk(e)}))},_children_backwards(e){e(this.template_string);e(this.prefix)}});var _e=DEFNODE("TemplateString","segments",{$documentation:"A template string literal",$propdoc:{segments:"[AST_Node*] One or more segments, starting with AST_TemplateSegment. AST_Node may follow AST_TemplateSegment, but each AST_Node must be followed by AST_TemplateSegment."},_walk:function(e){return e._visit(this,(function(){this.segments.forEach((function(t){t._walk(e)}))}))},_children_backwards(e){let t=this.segments.length;while(t--)e(this.segments[t])}});var de=DEFNODE("TemplateSegment","value raw",{$documentation:"A segment of a template string literal",$propdoc:{value:"Content of the segment",raw:"Raw source of the segment"}});var he=DEFNODE("Jump",null,{$documentation:"Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"},U);var me=DEFNODE("Exit","value",{$documentation:"Base class for “exits” (`return` and `throw`)",$propdoc:{value:"[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"},_walk:function(e){return e._visit(this,this.value&&function(){this.value._walk(e)})},_children_backwards(e){if(this.value)e(this.value)}},he);var Ee=DEFNODE("Return",null,{$documentation:"A `return` statement"},me);var ge=DEFNODE("Throw",null,{$documentation:"A `throw` statement"},me);var ve=DEFNODE("LoopControl","label",{$documentation:"Base class for loop control statements (`break` and `continue`)",$propdoc:{label:"[AST_LabelRef?] the label, or null if none"},_walk:function(e){return e._visit(this,this.label&&function(){this.label._walk(e)})},_children_backwards(e){if(this.label)e(this.label)}},he);var be=DEFNODE("Break",null,{$documentation:"A `break` statement"},ve);var De=DEFNODE("Continue",null,{$documentation:"A `continue` statement"},ve);var ye=DEFNODE("Await","expression",{$documentation:"An `await` statement",$propdoc:{expression:"[AST_Node] the mandatory expression being awaited"},_walk:function(e){return e._visit(this,(function(){this.expression._walk(e)}))},_children_backwards(e){e(this.expression)}});var Se=DEFNODE("Yield","expression is_star",{$documentation:"A `yield` statement",$propdoc:{expression:"[AST_Node?] the value returned or thrown by this statement; could be null (representing undefined) but only when is_star is set to false",is_star:"[Boolean] Whether this is a yield or yield* statement"},_walk:function(e){return e._visit(this,this.expression&&function(){this.expression._walk(e)})},_children_backwards(e){if(this.expression)e(this.expression)}});var Ae=DEFNODE("If","condition alternative",{$documentation:"A `if` statement",$propdoc:{condition:"[AST_Node] the `if` condition",alternative:"[AST_Statement?] the `else` part, or null if not present"},_walk:function(e){return e._visit(this,(function(){this.condition._walk(e);this.body._walk(e);if(this.alternative)this.alternative._walk(e)}))},_children_backwards(e){if(this.alternative){e(this.alternative)}e(this.body);e(this.condition)}},q);var ke=DEFNODE("Switch","expression",{$documentation:"A `switch` statement",$propdoc:{expression:"[AST_Node] the `switch` “discriminant”"},_walk:function(e){return e._visit(this,(function(){this.expression._walk(e);walk_body(this,e)}))},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},H);var Te=DEFNODE("SwitchBranch",null,{$documentation:"Base class for `switch` branches"},H);var xe=DEFNODE("Default",null,{$documentation:"A `default` switch branch"},Te);var Ce=DEFNODE("Case","expression",{$documentation:"A `case` switch branch",$propdoc:{expression:"[AST_Node] the `case` expression"},_walk:function(e){return e._visit(this,(function(){this.expression._walk(e);walk_body(this,e)}))},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},Te);var Re=DEFNODE("Try","bcatch bfinally",{$documentation:"A `try` statement",$propdoc:{bcatch:"[AST_Catch?] the catch block, or null if not present",bfinally:"[AST_Finally?] the finally block, or null if not present"},_walk:function(e){return e._visit(this,(function(){walk_body(this,e);if(this.bcatch)this.bcatch._walk(e);if(this.bfinally)this.bfinally._walk(e)}))},_children_backwards(e){if(this.bfinally)e(this.bfinally);if(this.bcatch)e(this.bcatch);let t=this.body.length;while(t--)e(this.body[t])}},H);var we=DEFNODE("Catch","argname",{$documentation:"A `catch` node; only makes sense as part of a `try` statement",$propdoc:{argname:"[AST_SymbolCatch|AST_Destructuring|AST_Expansion|AST_DefaultAssign] symbol for the exception"},_walk:function(e){return e._visit(this,(function(){if(this.argname)this.argname._walk(e);walk_body(this,e)}))},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);if(this.argname)e(this.argname)}},H);var Oe=DEFNODE("Finally",null,{$documentation:"A `finally` node; only makes sense as part of a `try` statement"},H);var Fe=DEFNODE("Definitions","definitions",{$documentation:"Base class for `var` or `const` nodes (variable declarations/initializations)",$propdoc:{definitions:"[AST_VarDef*] array of variable definitions"},_walk:function(e){return e._visit(this,(function(){var t=this.definitions;for(var n=0,i=t.length;n a`"},Qe);var nt=DEFNODE("Array","elements",{$documentation:"An array literal",$propdoc:{elements:"[AST_Node*] array of elements"},_walk:function(e){return e._visit(this,(function(){var t=this.elements;for(var n=0,i=t.length;nt._walk(e)))}))},_children_backwards(e){let t=this.properties.length;while(t--)e(this.properties[t]);if(this.extends)e(this.extends);if(this.name)e(this.name)}},ie);var dt=DEFNODE("ClassProperty","static quote",{$documentation:"A class property",$propdoc:{static:"[boolean] whether this is a static key",quote:"[string] which quote is being used"},_walk:function(e){return e._visit(this,(function(){if(this.key instanceof V)this.key._walk(e);if(this.value instanceof V)this.value._walk(e)}))},_children_backwards(e){if(this.value instanceof V)e(this.value);if(this.key instanceof V)e(this.key)},computed_key(){return!(this.key instanceof Ct)}},rt);var ht=DEFNODE("ClassProperty","",{$documentation:"A class property for a private property"},dt);var mt=DEFNODE("DefClass",null,{$documentation:"A class definition"},_t);var Et=DEFNODE("ClassExpression",null,{$documentation:"A class expression."},_t);var gt=DEFNODE("Symbol","scope name thedef",{$propdoc:{name:"[string] name of this symbol",scope:"[AST_Scope/S] the current scope (not necessarily the definition scope)",thedef:"[SymbolDef/S] the definition of this symbol"},$documentation:"Base class for all symbols"});var vt=DEFNODE("NewTarget",null,{$documentation:"A reference to new.target"});var bt=DEFNODE("SymbolDeclaration","init",{$documentation:"A declaration symbol (symbol in var/const, function name or argument, symbol in catch)"},gt);var Dt=DEFNODE("SymbolVar",null,{$documentation:"Symbol defining a variable"},bt);var yt=DEFNODE("SymbolBlockDeclaration",null,{$documentation:"Base class for block-scoped declaration symbols"},bt);var St=DEFNODE("SymbolConst",null,{$documentation:"A constant declaration"},yt);var At=DEFNODE("SymbolLet",null,{$documentation:"A block-scoped `let` declaration"},yt);var kt=DEFNODE("SymbolFunarg",null,{$documentation:"Symbol naming a function argument"},Dt);var Tt=DEFNODE("SymbolDefun",null,{$documentation:"Symbol defining a function"},bt);var xt=DEFNODE("SymbolMethod",null,{$documentation:"Symbol in an object defining a method"},gt);var Ct=DEFNODE("SymbolClassProperty",null,{$documentation:"Symbol for a class property"},gt);var Rt=DEFNODE("SymbolLambda",null,{$documentation:"Symbol naming a function expression"},bt);var wt=DEFNODE("SymbolDefClass",null,{$documentation:"Symbol naming a class's name in a class declaration. Lexically scoped to its containing scope, and accessible within the class."},yt);var Ot=DEFNODE("SymbolClass",null,{$documentation:"Symbol naming a class's name. Lexically scoped to the class."},bt);var Ft=DEFNODE("SymbolCatch",null,{$documentation:"Symbol naming the exception in catch"},yt);var Nt=DEFNODE("SymbolImport",null,{$documentation:"Symbol referring to an imported name"},yt);var Mt=DEFNODE("SymbolImportForeign",null,{$documentation:"A symbol imported from a module, but it is defined in the other module, and its real name is irrelevant for this module's purposes"},gt);var It=DEFNODE("Label","references",{$documentation:"Symbol naming a label (declaration)",$propdoc:{references:"[AST_LoopControl*] a list of nodes referring to this label"},initialize:function(){this.references=[];this.thedef=this}},gt);var Pt=DEFNODE("SymbolRef",null,{$documentation:"Reference to some symbol (not definition/declaration)"},gt);var Lt=DEFNODE("SymbolExport",null,{$documentation:"Symbol referring to a name to export"},Pt);var Bt=DEFNODE("SymbolExportForeign",null,{$documentation:"A symbol exported from this module, but it is used in the other module, and its real name is irrelevant for this module's purposes"},gt);var Vt=DEFNODE("LabelRef",null,{$documentation:"Reference to a label symbol"},gt);var Ut=DEFNODE("This",null,{$documentation:"The `this` symbol"},gt);var zt=DEFNODE("Super",null,{$documentation:"The `super` symbol"},Ut);var Kt=DEFNODE("Constant",null,{$documentation:"Base class for all constants",getValue:function(){return this.value}});var Gt=DEFNODE("String","value quote",{$documentation:"A string literal",$propdoc:{value:"[string] the contents of this string",quote:"[string] the original quote character"}},Kt);var Ht=DEFNODE("Number","value raw",{$documentation:"A number literal",$propdoc:{value:"[number] the numeric value",raw:"[string] numeric value as string"}},Kt);var Xt=DEFNODE("BigInt","value",{$documentation:"A big int literal",$propdoc:{value:"[string] big int value"}},Kt);var Wt=DEFNODE("RegExp","value",{$documentation:"A regexp literal",$propdoc:{value:"[RegExp] the actual regexp"}},Kt);var qt=DEFNODE("Atom",null,{$documentation:"Base class for atoms"},Kt);var Yt=DEFNODE("Null",null,{$documentation:"The `null` atom",value:null},qt);var jt=DEFNODE("NaN",null,{$documentation:"The impossible value",value:0/0},qt);var $t=DEFNODE("Undefined",null,{$documentation:"The `undefined` value",value:function(){}()},qt);var Zt=DEFNODE("Hole",null,{$documentation:"A hole in an array",value:function(){}()},qt);var Qt=DEFNODE("Infinity",null,{$documentation:"The `Infinity` value",value:1/0},qt);var Jt=DEFNODE("Boolean",null,{$documentation:"Base class for booleans"},qt);var en=DEFNODE("False",null,{$documentation:"The `false` atom",value:false},Jt);var tn=DEFNODE("True",null,{$documentation:"The `true` atom",value:true},Jt);function walk(e,t,n=[e]){const i=n.push.bind(n);while(n.length){const e=n.pop();const r=t(e,n);if(r){if(r===nn)return true;continue}e._children_backwards(i)}return false}function walk_parent(e,t,n){const i=[e];const r=i.push.bind(i);const a=n?n.slice():[];const o=[];let s;const u={parent:(e=0)=>{if(e===-1){return s}if(n&&e>=a.length){e-=a.length;return n[n.length-(e+1)]}return a[a.length-(1+e)]}};while(i.length){s=i.pop();while(o.length&&i.length==o[o.length-1]){a.pop();o.pop()}const e=t(s,u);if(e){if(e===nn)return true;continue}const n=i.length;s._children_backwards(r);if(i.length>n){a.push(s);o.push(n-1)}}return false}const nn=Symbol("abort walk");class TreeWalker{constructor(e){this.visit=e;this.stack=[];this.directives=Object.create(null)}_visit(e,t){this.push(e);var n=this.visit(e,t?function(){t.call(e)}:noop);if(!n&&t){t.call(e)}this.pop();return n}parent(e){return this.stack[this.stack.length-2-(e||0)]}push(e){if(e instanceof oe){this.directives=Object.create(this.directives)}else if(e instanceof K&&!this.directives[e.value]){this.directives[e.value]=e}else if(e instanceof _t){this.directives=Object.create(this.directives);if(!this.directives["use strict"]){this.directives["use strict"]=e}}this.stack.push(e)}pop(){var e=this.stack.pop();if(e instanceof oe||e instanceof _t){this.directives=Object.getPrototypeOf(this.directives)}}self(){return this.stack[this.stack.length-1]}find_parent(e){var t=this.stack;for(var n=t.length;--n>=0;){var i=t[n];if(i instanceof e)return i}}has_directive(e){var t=this.directives[e];if(t)return t;var n=this.stack[this.stack.length-1];if(n instanceof ie&&n.body){for(var i=0;i=0;){var i=t[n];if(i instanceof Y&&i.label.name==e.label.name)return i.body}else for(var n=t.length;--n>=0;){var i=t[n];if(i instanceof j||e instanceof be&&i instanceof ke)return i}}}class TreeTransformer extends TreeWalker{constructor(e,t){super();this.before=e;this.after=t}}const rn=1;const an=2;const on=4;var sn=Object.freeze({__proto__:null,AST_Accessor:se,AST_Array:nt,AST_Arrow:le,AST_Assign:et,AST_Atom:qt,AST_Await:ye,AST_BigInt:Xt,AST_Binary:Qe,AST_Block:H,AST_BlockStatement:X,AST_Boolean:Jt,AST_Break:be,AST_Call:ze,AST_Case:Ce,AST_Catch:we,AST_Chain:Ye,AST_Class:_t,AST_ClassExpression:Et,AST_ClassPrivateProperty:ht,AST_ClassProperty:dt,AST_ConciseMethod:ft,AST_Conditional:Je,AST_Const:Ie,AST_Constant:Kt,AST_Continue:De,AST_Debugger:z,AST_Default:xe,AST_DefaultAssign:tt,AST_DefClass:mt,AST_Definitions:Fe,AST_Defun:ce,AST_Destructuring:fe,AST_Directive:K,AST_Do:Z,AST_Dot:Xe,AST_DotHash:We,AST_DWLoop:$,AST_EmptyStatement:W,AST_Exit:me,AST_Expansion:ae,AST_Export:Ue,AST_False:en,AST_Finally:Oe,AST_For:J,AST_ForIn:ee,AST_ForOf:te,AST_Function:ue,AST_Hole:Zt,AST_If:Ae,AST_Import:Be,AST_ImportMeta:Ve,AST_Infinity:Qt,AST_IterationStatement:j,AST_Jump:he,AST_Label:It,AST_LabeledStatement:Y,AST_LabelRef:Vt,AST_Lambda:oe,AST_Let:Me,AST_LoopControl:ve,AST_NameMapping:Le,AST_NaN:jt,AST_New:Ke,AST_NewTarget:vt,AST_Node:V,AST_Null:Yt,AST_Number:Ht,AST_Object:it,AST_ObjectGetter:ct,AST_ObjectKeyVal:ot,AST_ObjectProperty:rt,AST_ObjectSetter:lt,AST_PrefixedTemplateString:pe,AST_PrivateGetter:ut,AST_PrivateMethod:pt,AST_PrivateSetter:st,AST_PropAccess:He,AST_RegExp:Wt,AST_Return:Ee,AST_Scope:ie,AST_Sequence:Ge,AST_SimpleStatement:G,AST_Statement:U,AST_StatementWithBody:q,AST_String:Gt,AST_Sub:qe,AST_Super:zt,AST_Switch:ke,AST_SwitchBranch:Te,AST_Symbol:gt,AST_SymbolBlockDeclaration:yt,AST_SymbolCatch:Ft,AST_SymbolClass:Ot,AST_SymbolClassProperty:Ct,AST_SymbolConst:St,AST_SymbolDeclaration:bt,AST_SymbolDefClass:wt,AST_SymbolDefun:Tt,AST_SymbolExport:Lt,AST_SymbolExportForeign:Bt,AST_SymbolFunarg:kt,AST_SymbolImport:Nt,AST_SymbolImportForeign:Mt,AST_SymbolLambda:Rt,AST_SymbolLet:At,AST_SymbolMethod:xt,AST_SymbolRef:Pt,AST_SymbolVar:Dt,AST_TemplateSegment:de,AST_TemplateString:_e,AST_This:Ut,AST_Throw:ge,AST_Token:AST_Token,AST_Toplevel:re,AST_True:tn,AST_Try:Re,AST_Unary:je,AST_UnaryPostfix:Ze,AST_UnaryPrefix:$e,AST_Undefined:$t,AST_Var:Ne,AST_VarDef:Pe,AST_While:Q,AST_With:ne,AST_Yield:Se,TreeTransformer:TreeTransformer,TreeWalker:TreeWalker,walk:walk,walk_abort:nn,walk_body:walk_body,walk_parent:walk_parent,_INLINE:an,_NOINLINE:on,_PURE:rn});function def_transform(e,t){e.DEFMETHOD("transform",(function(e,n){let i=undefined;e.push(this);if(e.before)i=e.before(this,t,n);if(i===undefined){i=this;t(i,e);if(e.after){const t=e.after(i,n);if(t!==undefined)i=t}}e.pop();return i}))}function do_list(e,t){return r(e,(function(e){return e.transform(t,true)}))}def_transform(V,noop);def_transform(Y,(function(e,t){e.label=e.label.transform(t);e.body=e.body.transform(t)}));def_transform(G,(function(e,t){e.body=e.body.transform(t)}));def_transform(H,(function(e,t){e.body=do_list(e.body,t)}));def_transform(Z,(function(e,t){e.body=e.body.transform(t);e.condition=e.condition.transform(t)}));def_transform(Q,(function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t)}));def_transform(J,(function(e,t){if(e.init)e.init=e.init.transform(t);if(e.condition)e.condition=e.condition.transform(t);if(e.step)e.step=e.step.transform(t);e.body=e.body.transform(t)}));def_transform(ee,(function(e,t){e.init=e.init.transform(t);e.object=e.object.transform(t);e.body=e.body.transform(t)}));def_transform(ne,(function(e,t){e.expression=e.expression.transform(t);e.body=e.body.transform(t)}));def_transform(me,(function(e,t){if(e.value)e.value=e.value.transform(t)}));def_transform(ve,(function(e,t){if(e.label)e.label=e.label.transform(t)}));def_transform(Ae,(function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t);if(e.alternative)e.alternative=e.alternative.transform(t)}));def_transform(ke,(function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)}));def_transform(Ce,(function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)}));def_transform(Re,(function(e,t){e.body=do_list(e.body,t);if(e.bcatch)e.bcatch=e.bcatch.transform(t);if(e.bfinally)e.bfinally=e.bfinally.transform(t)}));def_transform(we,(function(e,t){if(e.argname)e.argname=e.argname.transform(t);e.body=do_list(e.body,t)}));def_transform(Fe,(function(e,t){e.definitions=do_list(e.definitions,t)}));def_transform(Pe,(function(e,t){e.name=e.name.transform(t);if(e.value)e.value=e.value.transform(t)}));def_transform(fe,(function(e,t){e.names=do_list(e.names,t)}));def_transform(oe,(function(e,t){if(e.name)e.name=e.name.transform(t);e.argnames=do_list(e.argnames,t);if(e.body instanceof V){e.body=e.body.transform(t)}else{e.body=do_list(e.body,t)}}));def_transform(ze,(function(e,t){e.expression=e.expression.transform(t);e.args=do_list(e.args,t)}));def_transform(Ge,(function(e,t){const n=do_list(e.expressions,t);e.expressions=n.length?n:[new Ht({value:0})]}));def_transform(Xe,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(qe,(function(e,t){e.expression=e.expression.transform(t);e.property=e.property.transform(t)}));def_transform(Ye,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(Se,(function(e,t){if(e.expression)e.expression=e.expression.transform(t)}));def_transform(ye,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(je,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(Qe,(function(e,t){e.left=e.left.transform(t);e.right=e.right.transform(t)}));def_transform(Je,(function(e,t){e.condition=e.condition.transform(t);e.consequent=e.consequent.transform(t);e.alternative=e.alternative.transform(t)}));def_transform(nt,(function(e,t){e.elements=do_list(e.elements,t)}));def_transform(it,(function(e,t){e.properties=do_list(e.properties,t)}));def_transform(rt,(function(e,t){if(e.key instanceof V){e.key=e.key.transform(t)}if(e.value)e.value=e.value.transform(t)}));def_transform(_t,(function(e,t){if(e.name)e.name=e.name.transform(t);if(e.extends)e.extends=e.extends.transform(t);e.properties=do_list(e.properties,t)}));def_transform(ae,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(Le,(function(e,t){e.foreign_name=e.foreign_name.transform(t);e.name=e.name.transform(t)}));def_transform(Be,(function(e,t){if(e.imported_name)e.imported_name=e.imported_name.transform(t);if(e.imported_names)do_list(e.imported_names,t);e.module_name=e.module_name.transform(t)}));def_transform(Ue,(function(e,t){if(e.exported_definition)e.exported_definition=e.exported_definition.transform(t);if(e.exported_value)e.exported_value=e.exported_value.transform(t);if(e.exported_names)do_list(e.exported_names,t);if(e.module_name)e.module_name=e.module_name.transform(t)}));def_transform(_e,(function(e,t){e.segments=do_list(e.segments,t)}));def_transform(pe,(function(e,t){e.prefix=e.prefix.transform(t);e.template_string=e.template_string.transform(t)}));(function(){var normalize_directives=function(e){var t=true;for(var n=0;n1||e.guardedHandlers&&e.guardedHandlers.length){throw new Error("Multiple catch clauses are not supported.")}return new Re({start:my_start_token(e),end:my_end_token(e),body:from_moz(e.block).body,bcatch:from_moz(t[0]),bfinally:e.finalizer?new Oe(from_moz(e.finalizer)):null})},Property:function(e){var t=e.key;var n={start:my_start_token(t||e.value),end:my_end_token(e.value),key:t.type=="Identifier"?t.name:t.value,value:from_moz(e.value)};if(e.computed){n.key=from_moz(e.key)}if(e.method){n.is_generator=e.value.generator;n.async=e.value.async;if(!e.computed){n.key=new xt({name:n.key})}else{n.key=from_moz(e.key)}return new ft(n)}if(e.kind=="init"){if(t.type!="Identifier"&&t.type!="Literal"){n.key=from_moz(t)}return new ot(n)}if(typeof n.key==="string"||typeof n.key==="number"){n.key=new xt({name:n.key})}n.value=new se(n.value);if(e.kind=="get")return new ct(n);if(e.kind=="set")return new lt(n);if(e.kind=="method"){n.async=e.value.async;n.is_generator=e.value.generator;n.quote=e.computed?'"':null;return new ft(n)}},MethodDefinition:function(e){var t={start:my_start_token(e),end:my_end_token(e),key:e.computed?from_moz(e.key):new xt({name:e.key.name||e.key.value}),value:from_moz(e.value),static:e.static};if(e.kind=="get"){return new ct(t)}if(e.kind=="set"){return new lt(t)}t.is_generator=e.value.generator;t.async=e.value.async;return new ft(t)},FieldDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in FieldDefinition");t=from_moz(e.key)}return new dt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},PropertyDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in PropertyDefinition");t=from_moz(e.key)}return new dt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},ArrayExpression:function(e){return new nt({start:my_start_token(e),end:my_end_token(e),elements:e.elements.map((function(e){return e===null?new Zt:from_moz(e)}))})},ObjectExpression:function(e){return new it({start:my_start_token(e),end:my_end_token(e),properties:e.properties.map((function(e){if(e.type==="SpreadElement"){return from_moz(e)}e.type="Property";return from_moz(e)}))})},SequenceExpression:function(e){return new Ge({start:my_start_token(e),end:my_end_token(e),expressions:e.expressions.map(from_moz)})},MemberExpression:function(e){return new(e.computed?qe:Xe)({start:my_start_token(e),end:my_end_token(e),property:e.computed?from_moz(e.property):e.property.name,expression:from_moz(e.object),optional:e.optional||false})},ChainExpression:function(e){return new Ye({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.expression)})},SwitchCase:function(e){return new(e.test?Ce:xe)({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.test),body:e.consequent.map(from_moz)})},VariableDeclaration:function(e){return new(e.kind==="const"?Ie:e.kind==="let"?Me:Ne)({start:my_start_token(e),end:my_end_token(e),definitions:e.declarations.map(from_moz)})},ImportDeclaration:function(e){var t=null;var n=null;e.specifiers.forEach((function(e){if(e.type==="ImportSpecifier"){if(!n){n=[]}n.push(new Le({start:my_start_token(e),end:my_end_token(e),foreign_name:from_moz(e.imported),name:from_moz(e.local)}))}else if(e.type==="ImportDefaultSpecifier"){t=from_moz(e.local)}else if(e.type==="ImportNamespaceSpecifier"){if(!n){n=[]}n.push(new Le({start:my_start_token(e),end:my_end_token(e),foreign_name:new Mt({name:"*"}),name:from_moz(e.local)}))}}));return new Be({start:my_start_token(e),end:my_end_token(e),imported_name:t,imported_names:n,module_name:from_moz(e.source)})},ExportAllDeclaration:function(e){return new Ue({start:my_start_token(e),end:my_end_token(e),exported_names:[new Le({name:new Bt({name:"*"}),foreign_name:new Bt({name:"*"})})],module_name:from_moz(e.source)})},ExportNamedDeclaration:function(e){return new Ue({start:my_start_token(e),end:my_end_token(e),exported_definition:from_moz(e.declaration),exported_names:e.specifiers&&e.specifiers.length?e.specifiers.map((function(e){return new Le({foreign_name:from_moz(e.exported),name:from_moz(e.local)})})):null,module_name:from_moz(e.source)})},ExportDefaultDeclaration:function(e){return new Ue({start:my_start_token(e),end:my_end_token(e),exported_value:from_moz(e.declaration),is_default:true})},Literal:function(e){var t=e.value,n={start:my_start_token(e),end:my_end_token(e)};var i=e.regex;if(i&&i.pattern){n.value={source:i.pattern,flags:i.flags};return new Wt(n)}else if(i){const i=e.raw||t;const r=i.match(/^\/(.*)\/(\w*)$/);if(!r)throw new Error("Invalid regex source "+i);const[a,o,s]=r;n.value={source:o,flags:s};return new Wt(n)}if(t===null)return new Yt(n);switch(typeof t){case"string":n.value=t;return new Gt(n);case"number":n.value=t;n.raw=e.raw||t.toString();return new Ht(n);case"boolean":return new(t?tn:en)(n)}},MetaProperty:function(e){if(e.meta.name==="new"&&e.property.name==="target"){return new vt({start:my_start_token(e),end:my_end_token(e)})}else if(e.meta.name==="import"&&e.property.name==="meta"){return new Ve({start:my_start_token(e),end:my_end_token(e)})}},Identifier:function(e){var n=t[t.length-2];return new(n.type=="LabeledStatement"?It:n.type=="VariableDeclarator"&&n.id===e?n.kind=="const"?St:n.kind=="let"?At:Dt:/Import.*Specifier/.test(n.type)?n.local===e?Nt:Mt:n.type=="ExportSpecifier"?n.local===e?Lt:Bt:n.type=="FunctionExpression"?n.id===e?Rt:kt:n.type=="FunctionDeclaration"?n.id===e?Tt:kt:n.type=="ArrowFunctionExpression"?n.params.includes(e)?kt:Pt:n.type=="ClassExpression"?n.id===e?Ot:Pt:n.type=="Property"?n.key===e&&n.computed||n.value===e?Pt:xt:n.type=="PropertyDefinition"||n.type==="FieldDefinition"?n.key===e&&n.computed||n.value===e?Pt:Ct:n.type=="ClassDeclaration"?n.id===e?wt:Pt:n.type=="MethodDefinition"?n.computed?Pt:xt:n.type=="CatchClause"?Ft:n.type=="BreakStatement"||n.type=="ContinueStatement"?Vt:Pt)({start:my_start_token(e),end:my_end_token(e),name:e.name})},BigIntLiteral(e){return new Xt({start:my_start_token(e),end:my_end_token(e),value:e.value})}};e.UpdateExpression=e.UnaryExpression=function To_Moz_Unary(e){var t="prefix"in e?e.prefix:e.type=="UnaryExpression"?true:false;return new(t?$e:Ze)({start:my_start_token(e),end:my_end_token(e),operator:e.operator,expression:from_moz(e.argument)})};e.ClassDeclaration=e.ClassExpression=function From_Moz_Class(e){return new(e.type==="ClassDeclaration"?mt:Et)({start:my_start_token(e),end:my_end_token(e),name:from_moz(e.id),extends:from_moz(e.superClass),properties:e.body.body.map(from_moz)})};map("EmptyStatement",W);map("BlockStatement",X,"body@body");map("IfStatement",Ae,"test>condition, consequent>body, alternate>alternative");map("LabeledStatement",Y,"label>label, body>body");map("BreakStatement",be,"label>label");map("ContinueStatement",De,"label>label");map("WithStatement",ne,"object>expression, body>body");map("SwitchStatement",ke,"discriminant>expression, cases@body");map("ReturnStatement",Ee,"argument>value");map("ThrowStatement",ge,"argument>value");map("WhileStatement",Q,"test>condition, body>body");map("DoWhileStatement",Z,"test>condition, body>body");map("ForStatement",J,"init>init, test>condition, update>step, body>body");map("ForInStatement",ee,"left>init, right>object, body>body");map("ForOfStatement",te,"left>init, right>object, body>body, await=await");map("AwaitExpression",ye,"argument>expression");map("YieldExpression",Se,"argument>expression, delegate=is_star");map("DebuggerStatement",z);map("VariableDeclarator",Pe,"id>name, init>value");map("CatchClause",we,"param>argname, body%body");map("ThisExpression",Ut);map("Super",zt);map("BinaryExpression",Qe,"operator=operator, left>left, right>right");map("LogicalExpression",Qe,"operator=operator, left>left, right>right");map("AssignmentExpression",et,"operator=operator, left>left, right>right");map("ConditionalExpression",Je,"test>condition, consequent>consequent, alternate>alternative");map("NewExpression",Ke,"callee>expression, arguments@args");map("CallExpression",ze,"callee>expression, optional=optional, arguments@args");def_to_moz(re,(function To_Moz_Program(e){return to_moz_scope("Program",e)}));def_to_moz(ae,(function To_Moz_Spread(e){return{type:to_moz_in_destructuring()?"RestElement":"SpreadElement",argument:to_moz(e.expression)}}));def_to_moz(pe,(function To_Moz_TaggedTemplateExpression(e){return{type:"TaggedTemplateExpression",tag:to_moz(e.prefix),quasi:to_moz(e.template_string)}}));def_to_moz(_e,(function To_Moz_TemplateLiteral(e){var t=[];var n=[];for(var i=0;i({type:"BigIntLiteral",value:e.value})));Jt.DEFMETHOD("to_mozilla_ast",Kt.prototype.to_mozilla_ast);Yt.DEFMETHOD("to_mozilla_ast",Kt.prototype.to_mozilla_ast);Zt.DEFMETHOD("to_mozilla_ast",(function To_Moz_ArrayHole(){return null}));H.DEFMETHOD("to_mozilla_ast",X.prototype.to_mozilla_ast);oe.DEFMETHOD("to_mozilla_ast",ue.prototype.to_mozilla_ast);function my_start_token(e){var t=e.loc,n=t&&t.start;var i=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,i?i[0]:e.start,false,[],[],t&&t.source)}function my_end_token(e){var t=e.loc,n=t&&t.end;var i=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,i?i[0]:e.end,false,[],[],t&&t.source)}function map(t,n,i){var r="function From_Moz_"+t+"(M){\n";r+="return new U2."+n.name+"({\n"+"start: my_start_token(M),\n"+"end: my_end_token(M)";var a="function To_Moz_"+t+"(M){\n";a+="return {\n"+"type: "+JSON.stringify(t);if(i)i.split(/\s*,\s*/).forEach((function(e){var t=/([a-z0-9$_]+)([=@>%])([a-z0-9$_]+)/i.exec(e);if(!t)throw new Error("Can't understand property map: "+e);var n=t[1],i=t[2],o=t[3];r+=",\n"+o+": ";a+=",\n"+n+": ";switch(i){case"@":r+="M."+n+".map(from_moz)";a+="M."+o+".map(to_moz)";break;case">":r+="from_moz(M."+n+")";a+="to_moz(M."+o+")";break;case"=":r+="M."+n;a+="M."+o;break;case"%":r+="from_moz(M."+n+").body";a+="to_moz_block(M)";break;default:throw new Error("Can't understand operator in propmap: "+e)}}));r+="\n})\n}";a+="\n}\n}";r=new Function("U2","my_start_token","my_end_token","from_moz","return("+r+")")(sn,my_start_token,my_end_token,from_moz);a=new Function("to_moz","to_moz_block","to_moz_scope","return("+a+")")(to_moz,to_moz_block,to_moz_scope);e[t]=r;def_to_moz(n,a)}var t=null;function from_moz(n){t.push(n);var i=n!=null?e[n.type](n):null;t.pop();return i}V.from_mozilla_ast=function(e){var n=t;t=[];var i=from_moz(e);t=n;return i};function set_moz_loc(e,t){var n=e.start;var i=e.end;if(!(n&&i)){return t}if(n.pos!=null&&i.endpos!=null){t.range=[n.pos,i.endpos]}if(n.line){t.loc={start:{line:n.line,column:n.col},end:i.endline?{line:i.endline,column:i.endcol}:null};if(n.file){t.loc.source=n.file}}return t}function def_to_moz(e,t){e.DEFMETHOD("to_mozilla_ast",(function(e){return set_moz_loc(this,t(this,e))}))}var n=null;function to_moz(e){if(n===null){n=[]}n.push(e);var t=e!=null?e.to_mozilla_ast(n[n.length-2]):null;n.pop();if(n.length===0){n=null}return t}function to_moz_in_destructuring(){var e=n.length;while(e--){if(n[e]instanceof fe){return true}}return false}function to_moz_block(e){return{type:"BlockStatement",body:e.body.map(to_moz)}}function to_moz_scope(e,t){var n=t.body.map(to_moz);if(t.body[0]instanceof G&&t.body[0].body instanceof Gt){n.unshift(to_moz(new W(t.body[0])))}return{type:e,body:n}}})();function first_in_statement(e){let t=e.parent(-1);for(let n=0,i;i=e.parent(n);n++){if(i instanceof U&&i.body===t)return true;if(i instanceof Ge&&i.expressions[0]===t||i.TYPE==="Call"&&i.expression===t||i instanceof pe&&i.prefix===t||i instanceof Xe&&i.expression===t||i instanceof qe&&i.expression===t||i instanceof Je&&i.condition===t||i instanceof Qe&&i.left===t||i instanceof Ze&&i.expression===t){t=i}else{return false}}}function left_is_object(e){if(e instanceof it)return true;if(e instanceof Ge)return left_is_object(e.expressions[0]);if(e.TYPE==="Call")return left_is_object(e.expression);if(e instanceof pe)return left_is_object(e.prefix);if(e instanceof Xe||e instanceof qe)return left_is_object(e.expression);if(e instanceof Je)return left_is_object(e.condition);if(e instanceof Qe)return left_is_object(e.left);if(e instanceof Ze)return left_is_object(e.expression);return false}const un=/^$|[;{][\s\n]*$/;const ln=10;const cn=32;const pn=/[@#]__(PURE|INLINE|NOINLINE)__/g;function is_some_comments(e){return(e.type==="comment2"||e.type==="comment1")&&/@preserve|@lic|@cc_on|^\**!/i.test(e.value)}function OutputStream(e){var t=!e;e=defaults(e,{ascii_only:false,beautify:false,braces:false,comments:"some",ecma:5,ie8:false,indent_level:4,indent_start:0,inline_script:true,keep_numbers:false,keep_quoted_props:false,max_line_len:false,preamble:null,preserve_annotations:false,quote_keys:false,quote_style:0,safari10:false,semicolons:true,shebang:true,shorthand:undefined,source_map:null,webkit:false,width:80,wrap_iife:false,wrap_func_args:true},true);if(e.shorthand===undefined)e.shorthand=e.ecma>5;var n=return_false;if(e.comments){let t=e.comments;if(typeof e.comments==="string"&&/^\/.*\/[a-zA-Z]*$/.test(e.comments)){var i=e.comments.lastIndexOf("/");t=new RegExp(e.comments.substr(1,i-1),e.comments.substr(i+1))}if(t instanceof RegExp){n=function(e){return e.type!="comment5"&&t.test(e.value)}}else if(typeof t==="function"){n=function(e){return e.type!="comment5"&&t(this,e)}}else if(t==="some"){n=is_some_comments}else{n=return_true}}var r=0;var a=0;var o=1;var s=0;var u="";let l=new Set;var c=e.ascii_only?function(t,n){if(e.ecma>=2015&&!e.safari10){t=t.replace(/[\ud800-\udbff][\udc00-\udfff]/g,(function(e){var t=get_full_char_code(e,0).toString(16);return"\\u{"+t+"}"}))}return t.replace(/[\u0000-\u001f\u007f-\uffff]/g,(function(e){var t=e.charCodeAt(0).toString(16);if(t.length<=2&&!n){while(t.length<2)t="0"+t;return"\\x"+t}else{while(t.length<4)t="0"+t;return"\\u"+t}}))}:function(e){return e.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g,(function(e,t){if(t){return"\\u"+t.charCodeAt(0).toString(16)}return e}))};function make_string(t,n){var i=0,r=0;t=t.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,(function(n,a){switch(n){case'"':++i;return'"';case"'":++r;return"'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\t":return"\\t";case"\b":return"\\b";case"\f":return"\\f";case"\v":return e.ie8?"\\x0B":"\\v";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";case"\ufeff":return"\\ufeff";case"\0":return/[0-9]/.test(get_full_char(t,a+1))?"\\x00":"\\0"}return n}));function quote_single(){return"'"+t.replace(/\x27/g,"\\'")+"'"}function quote_double(){return'"'+t.replace(/\x22/g,'\\"')+'"'}function quote_template(){return"`"+t.replace(/`/g,"\\`")+"`"}t=c(t);if(n==="`")return quote_template();switch(e.quote_style){case 1:return quote_single();case 2:return quote_double();case 3:return n=="'"?quote_single():quote_double();default:return i>r?quote_single():quote_double()}}function encode_string(t,n){var i=make_string(t,n);if(e.inline_script){i=i.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi,"<\\/$1$2");i=i.replace(/\x3c!--/g,"\\x3c!--");i=i.replace(/--\x3e/g,"--\\x3e")}return i}function make_name(e){e=e.toString();e=c(e,true);return e}function make_indent(t){return" ".repeat(e.indent_start+r-t*e.indent_level)}var f=false;var p=false;var _=false;var d=0;var h=false;var m=false;var E=-1;var g="";var v,b,D=e.source_map&&[];var y=D?function(){D.forEach((function(t){try{let n=!t.name&&t.token.type=="name"?t.token.value:t.name;if(n instanceof gt){n=n.name}e.source_map.add(t.token.file,t.line,t.col,t.token.line,t.token.col,is_basic_identifier_string(n)?n:undefined)}catch(e){}}));D=[]}:noop;var S=e.max_line_len?function(){if(a>e.max_line_len){if(d){var t=u.slice(0,d);var n=u.slice(d);if(D){var i=n.length-a;D.forEach((function(e){e.line++;e.col+=i}))}u=t+"\n"+n;o++;s++;a=n.length}}if(d){d=0;y()}}:noop;var A=makePredicate("( [ + * / - , . `");function print(t){t=String(t);var n=get_full_char(t,0);if(h&&n){h=false;if(n!=="\n"){print("\n");T()}}if(m&&n){m=false;if(!/[\s;})]/.test(n)){k()}}E=-1;var i=g.charAt(g.length-1);if(_){_=false;if(i===":"&&n==="}"||(!n||!";}".includes(n))&&i!==";"){if(e.semicolons||A.has(n)){u+=";";a++;s++}else{S();if(a>0){u+="\n";s++;o++;a=0}if(/^\s+$/.test(t)){_=true}}if(!e.beautify)p=false}}if(p){if(is_identifier_char(i)&&(is_identifier_char(n)||n=="\\")||n=="/"&&n==i||(n=="+"||n=="-")&&n==g){u+=" ";a++;s++}p=false}if(v){D.push({token:v,name:b,line:o,col:a});v=false;if(!d)y()}u+=t;f=t[t.length-1]=="(";s+=t.length;var r=t.split(/\r?\n/),l=r.length-1;o+=l;a+=r[0].length;if(l>0){S();a=r[l].length}g=t}var star=function(){print("*")};var k=e.beautify?function(){print(" ")}:function(){p=true};var T=e.beautify?function(t){if(e.beautify){print(make_indent(t?.5:0))}}:noop;var x=e.beautify?function(e,t){if(e===true)e=next_indent();var n=r;r=e;var i=t();r=n;return i}:function(e,t){return t()};var C=e.beautify?function(){if(E<0)return print("\n");if(u[E]!="\n"){u=u.slice(0,E)+"\n"+u.slice(E);s++;o++}E++}:e.max_line_len?function(){S();d=u.length}:noop;var R=e.beautify?function(){print(";")}:function(){_=true};function force_semicolon(){_=false;print(";")}function next_indent(){return r+e.indent_level}function with_block(e){var t;print("{");C();x(next_indent(),(function(){t=e()}));T();print("}");return t}function with_parens(e){print("(");var t=e();print(")");return t}function with_square(e){print("[");var t=e();print("]");return t}function comma(){print(",");k()}function colon(){print(":");k()}var w=D?function(e,t){v=e;b=t}:noop;function get(){if(d){S()}return u}function has_nlb(){let e=u.length-1;while(e>=0){const t=u.charCodeAt(e);if(t===ln){return true}if(t!==cn){return false}e--}return true}function filter_comment(t){if(!e.preserve_annotations){t=t.replace(pn," ")}if(/^\s*$/.test(t)){return""}return t.replace(/(<\s*\/\s*)(script)/i,"<\\/$2")}function prepend_comments(t){var i=this;var r=t.start;if(!r)return;var a=i.printed_comments;const o=t instanceof me&&t.value;if(r.comments_before&&a.has(r.comments_before)){if(o){r.comments_before=[]}else{return}}var u=r.comments_before;if(!u){u=r.comments_before=[]}a.add(u);if(o){var l=new TreeWalker((function(e){var t=l.parent();if(t instanceof me||t instanceof Qe&&t.left===e||t.TYPE=="Call"&&t.expression===e||t instanceof Je&&t.condition===e||t instanceof Xe&&t.expression===e||t instanceof Ge&&t.expressions[0]===e||t instanceof qe&&t.expression===e||t instanceof Ze){if(!e.start)return;var n=e.start.comments_before;if(n&&!a.has(n)){a.add(n);u=u.concat(n)}}else{return true}}));l.push(t);t.value.walk(l)}if(s==0){if(u.length>0&&e.shebang&&u[0].type==="comment5"&&!a.has(u[0])){print("#!"+u.shift().value+"\n");T()}var c=e.preamble;if(c){print(c.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g,"\n"))}}u=u.filter(n,t).filter((e=>!a.has(e)));if(u.length==0)return;var f=has_nlb();u.forEach((function(e,t){a.add(e);if(!f){if(e.nlb){print("\n");T();f=true}else if(t>0){k()}}if(/comment[134]/.test(e.type)){var n=filter_comment(e.value);if(n){print("//"+n+"\n");T()}f=true}else if(e.type=="comment2"){var n=filter_comment(e.value);if(n){print("/*"+n+"*/")}f=false}}));if(!f){if(r.nlb){print("\n");T()}else{k()}}}function append_comments(e,t){var i=this;var r=e.end;if(!r)return;var a=i.printed_comments;var o=r[t?"comments_before":"comments_after"];if(!o||a.has(o))return;if(!(e instanceof U||o.every((e=>!/comment[134]/.test(e.type)))))return;a.add(o);var s=u.length;o.filter(n,e).forEach((function(e,n){if(a.has(e))return;a.add(e);m=false;if(h){print("\n");T();h=false}else if(e.nlb&&(n>0||!has_nlb())){print("\n");T()}else if(n>0||!t){k()}if(/comment[134]/.test(e.type)){const t=filter_comment(e.value);if(t){print("//"+t)}h=true}else if(e.type=="comment2"){const t=filter_comment(e.value);if(t){print("/*"+t+"*/")}m=true}}));if(u.length>s)E=s}var O=[];return{get:get,toString:get,indent:T,in_directive:false,use_asm:null,active_scope:null,indentation:function(){return r},current_width:function(){return a-r},should_break:function(){return e.width&&this.current_width()>=e.width},has_parens:function(){return f},newline:C,print:print,star:star,space:k,comma:comma,colon:colon,last:function(){return g},semicolon:R,force_semicolon:force_semicolon,to_utf8:c,print_name:function(e){print(make_name(e))},print_string:function(e,t,n){var i=encode_string(e,t);if(n===true&&!i.includes("\\")){if(!un.test(u)){force_semicolon()}force_semicolon()}print(i)},print_template_string_chars:function(e){var t=encode_string(e,"`").replace(/\${/g,"\\${");return print(t.substr(1,t.length-2))},encode_string:encode_string,next_indent:next_indent,with_indent:x,with_block:with_block,with_parens:with_parens,with_square:with_square,add_mapping:w,option:function(t){return e[t]},printed_comments:l,prepend_comments:t?noop:prepend_comments,append_comments:t||n===return_false?noop:append_comments,line:function(){return o},col:function(){return a},pos:function(){return s},push_node:function(e){O.push(e)},pop_node:function(){return O.pop()},parent:function(e){return O[O.length-2-(e||0)]}}}(function(){function DEFPRINT(e,t){e.DEFMETHOD("_codegen",t)}V.DEFMETHOD("print",(function(e,t){var n=this,i=n._codegen;if(n instanceof ie){e.active_scope=n}else if(!e.use_asm&&n instanceof K&&n.value=="use asm"){e.use_asm=e.active_scope}function doit(){e.prepend_comments(n);n.add_source_map(e);i(n,e);e.append_comments(n)}e.push_node(n);if(t||n.needs_parens(e)){e.with_parens(doit)}else{doit()}e.pop_node();if(n===e.use_asm){e.use_asm=null}}));V.DEFMETHOD("_print",V.prototype.print);V.DEFMETHOD("print_to_string",(function(e){var t=OutputStream(e);this.print(t);return t.get()}));function PARENS(e,t){if(Array.isArray(e)){e.forEach((function(e){PARENS(e,t)}))}else{e.DEFMETHOD("needs_parens",t)}}PARENS(V,return_false);PARENS(ue,(function(e){if(!e.has_parens()&&first_in_statement(e)){return true}if(e.option("webkit")){var t=e.parent();if(t instanceof He&&t.expression===this){return true}}if(e.option("wrap_iife")){var t=e.parent();if(t instanceof ze&&t.expression===this){return true}}if(e.option("wrap_func_args")){var t=e.parent();if(t instanceof ze&&t.args.includes(this)){return true}}return false}));PARENS(le,(function(e){var t=e.parent();if(e.option("wrap_func_args")&&t instanceof ze&&t.args.includes(this)){return true}return t instanceof He&&t.expression===this}));PARENS(it,(function(e){return!e.has_parens()&&first_in_statement(e)}));PARENS(Et,first_in_statement);PARENS(je,(function(e){var t=e.parent();return t instanceof He&&t.expression===this||t instanceof ze&&t.expression===this||t instanceof Qe&&t.operator==="**"&&this instanceof $e&&t.left===this&&this.operator!=="++"&&this.operator!=="--"}));PARENS(ye,(function(e){var t=e.parent();return t instanceof He&&t.expression===this||t instanceof ze&&t.expression===this||t instanceof Qe&&t.operator==="**"&&t.left===this||e.option("safari10")&&t instanceof $e}));PARENS(Ge,(function(e){var t=e.parent();return t instanceof ze||t instanceof je||t instanceof Qe||t instanceof Pe||t instanceof He||t instanceof nt||t instanceof rt||t instanceof Je||t instanceof le||t instanceof tt||t instanceof ae||t instanceof te&&this===t.object||t instanceof Se||t instanceof Ue}));PARENS(Qe,(function(e){var t=e.parent();if(t instanceof ze&&t.expression===this)return true;if(t instanceof je)return true;if(t instanceof He&&t.expression===this)return true;if(t instanceof Qe){const e=t.operator;const n=this.operator;if(n==="??"&&(e==="||"||e==="&&")){return true}if(e==="??"&&(n==="||"||n==="&&")){return true}const i=M[e];const r=M[n];if(i>r||i==r&&(this===t.right||e=="**")){return true}}}));PARENS(Se,(function(e){var t=e.parent();if(t instanceof Qe&&t.operator!=="=")return true;if(t instanceof ze&&t.expression===this)return true;if(t instanceof Je&&t.condition===this)return true;if(t instanceof je)return true;if(t instanceof He&&t.expression===this)return true}));PARENS(He,(function(e){var t=e.parent();if(t instanceof Ke&&t.expression===this){return walk(this,(e=>{if(e instanceof ie)return true;if(e instanceof ze){return nn}}))}}));PARENS(ze,(function(e){var t=e.parent(),n;if(t instanceof Ke&&t.expression===this||t instanceof Ue&&t.is_default&&this.expression instanceof ue)return true;return this.expression instanceof ue&&t instanceof He&&t.expression===this&&(n=e.parent(1))instanceof et&&n.left===t}));PARENS(Ke,(function(e){var t=e.parent();if(this.args.length===0&&(t instanceof He||t instanceof ze&&t.expression===this))return true}));PARENS(Ht,(function(e){var t=e.parent();if(t instanceof He&&t.expression===this){var n=this.getValue();if(n<0||/^0/.test(make_num(n))){return true}}}));PARENS(Xt,(function(e){var t=e.parent();if(t instanceof He&&t.expression===this){var n=this.getValue();if(n.startsWith("-")){return true}}}));PARENS([et,Je],(function(e){var t=e.parent();if(t instanceof je)return true;if(t instanceof Qe&&!(t instanceof et))return true;if(t instanceof ze&&t.expression===this)return true;if(t instanceof Je&&t.condition===this)return true;if(t instanceof He&&t.expression===this)return true;if(this instanceof et&&this.left instanceof fe&&this.left.is_array===false)return true}));DEFPRINT(K,(function(e,t){t.print_string(e.value,e.quote);t.semicolon()}));DEFPRINT(ae,(function(e,t){t.print("...");e.expression.print(t)}));DEFPRINT(fe,(function(e,t){t.print(e.is_array?"[":"{");var n=e.names.length;e.names.forEach((function(e,i){if(i>0)t.comma();e.print(t);if(i==n-1&&e instanceof Zt)t.comma()}));t.print(e.is_array?"]":"}")}));DEFPRINT(z,(function(e,t){t.print("debugger");t.semicolon()}));function display_body(e,t,n,i){var r=e.length-1;n.in_directive=i;e.forEach((function(e,i){if(n.in_directive===true&&!(e instanceof K||e instanceof W||e instanceof G&&e.body instanceof Gt)){n.in_directive=false}if(!(e instanceof W)){n.indent();e.print(n);if(!(i==r&&t)){n.newline();if(t)n.newline()}}if(n.in_directive===true&&e instanceof G&&e.body instanceof Gt){n.in_directive=false}}));n.in_directive=false}q.DEFMETHOD("_do_print_body",(function(e){force_statement(this.body,e)}));DEFPRINT(U,(function(e,t){e.body.print(t);t.semicolon()}));DEFPRINT(re,(function(e,t){display_body(e.body,true,t,true);t.print("")}));DEFPRINT(Y,(function(e,t){e.label.print(t);t.colon();e.body.print(t)}));DEFPRINT(G,(function(e,t){e.body.print(t);t.semicolon()}));function print_braced_empty(e,t){t.print("{");t.with_indent(t.next_indent(),(function(){t.append_comments(e,true)}));t.print("}")}function print_braced(e,t,n){if(e.body.length>0){t.with_block((function(){display_body(e.body,false,t,n)}))}else print_braced_empty(e,t)}DEFPRINT(X,(function(e,t){print_braced(e,t)}));DEFPRINT(W,(function(e,t){t.semicolon()}));DEFPRINT(Z,(function(e,t){t.print("do");t.space();make_block(e.body,t);t.space();t.print("while");t.space();t.with_parens((function(){e.condition.print(t)}));t.semicolon()}));DEFPRINT(Q,(function(e,t){t.print("while");t.space();t.with_parens((function(){e.condition.print(t)}));t.space();e._do_print_body(t)}));DEFPRINT(J,(function(e,t){t.print("for");t.space();t.with_parens((function(){if(e.init){if(e.init instanceof Fe){e.init.print(t)}else{parenthesize_for_noin(e.init,t,true)}t.print(";");t.space()}else{t.print(";")}if(e.condition){e.condition.print(t);t.print(";");t.space()}else{t.print(";")}if(e.step){e.step.print(t)}}));t.space();e._do_print_body(t)}));DEFPRINT(ee,(function(e,t){t.print("for");if(e.await){t.space();t.print("await")}t.space();t.with_parens((function(){e.init.print(t);t.space();t.print(e instanceof te?"of":"in");t.space();e.object.print(t)}));t.space();e._do_print_body(t)}));DEFPRINT(ne,(function(e,t){t.print("with");t.space();t.with_parens((function(){e.expression.print(t)}));t.space();e._do_print_body(t)}));oe.DEFMETHOD("_do_print",(function(e,t){var n=this;if(!t){if(n.async){e.print("async");e.space()}e.print("function");if(n.is_generator){e.star()}if(n.name){e.space()}}if(n.name instanceof gt){n.name.print(e)}else if(t&&n.name instanceof V){e.with_square((function(){n.name.print(e)}))}e.with_parens((function(){n.argnames.forEach((function(t,n){if(n)e.comma();t.print(e)}))}));e.space();print_braced(n,e,true)}));DEFPRINT(oe,(function(e,t){e._do_print(t)}));DEFPRINT(pe,(function(e,t){var n=e.prefix;var i=n instanceof oe||n instanceof Qe||n instanceof Je||n instanceof Ge||n instanceof je||n instanceof Xe&&n.expression instanceof it;if(i)t.print("(");e.prefix.print(t);if(i)t.print(")");e.template_string.print(t)}));DEFPRINT(_e,(function(e,t){var n=t.parent()instanceof pe;t.print("`");for(var i=0;i");e.space();const r=t.body[0];if(t.body.length===1&&r instanceof Ee){const t=r.value;if(!t){e.print("{}")}else if(left_is_object(t)){e.print("(");t.print(e);e.print(")")}else{t.print(e)}}else{print_braced(t,e)}if(i){e.print(")")}}));me.DEFMETHOD("_do_print",(function(e,t){e.print(t);if(this.value){e.space();const t=this.value.start.comments_before;if(t&&t.length&&!e.printed_comments.has(t)){e.print("(");this.value.print(e);e.print(")")}else{this.value.print(e)}}e.semicolon()}));DEFPRINT(Ee,(function(e,t){e._do_print(t,"return")}));DEFPRINT(ge,(function(e,t){e._do_print(t,"throw")}));DEFPRINT(Se,(function(e,t){var n=e.is_star?"*":"";t.print("yield"+n);if(e.expression){t.space();e.expression.print(t)}}));DEFPRINT(ye,(function(e,t){t.print("await");t.space();var n=e.expression;var i=!(n instanceof ze||n instanceof Pt||n instanceof He||n instanceof je||n instanceof Kt||n instanceof ye||n instanceof it);if(i)t.print("(");e.expression.print(t);if(i)t.print(")")}));ve.DEFMETHOD("_do_print",(function(e,t){e.print(t);if(this.label){e.space();this.label.print(e)}e.semicolon()}));DEFPRINT(be,(function(e,t){e._do_print(t,"break")}));DEFPRINT(De,(function(e,t){e._do_print(t,"continue")}));function make_then(e,t){var n=e.body;if(t.option("braces")||t.option("ie8")&&n instanceof Z)return make_block(n,t);if(!n)return t.force_semicolon();while(true){if(n instanceof Ae){if(!n.alternative){make_block(e.body,t);return}n=n.alternative}else if(n instanceof q){n=n.body}else break}force_statement(e.body,t)}DEFPRINT(Ae,(function(e,t){t.print("if");t.space();t.with_parens((function(){e.condition.print(t)}));t.space();if(e.alternative){make_then(e,t);t.space();t.print("else");t.space();if(e.alternative instanceof Ae)e.alternative.print(t);else force_statement(e.alternative,t)}else{e._do_print_body(t)}}));DEFPRINT(ke,(function(e,t){t.print("switch");t.space();t.with_parens((function(){e.expression.print(t)}));t.space();var n=e.body.length-1;if(n<0)print_braced_empty(e,t);else t.with_block((function(){e.body.forEach((function(e,i){t.indent(true);e.print(t);if(i0)t.newline()}))}))}));Te.DEFMETHOD("_do_print_body",(function(e){e.newline();this.body.forEach((function(t){e.indent();t.print(e);e.newline()}))}));DEFPRINT(xe,(function(e,t){t.print("default:");e._do_print_body(t)}));DEFPRINT(Ce,(function(e,t){t.print("case");t.space();e.expression.print(t);t.print(":");e._do_print_body(t)}));DEFPRINT(Re,(function(e,t){t.print("try");t.space();print_braced(e,t);if(e.bcatch){t.space();e.bcatch.print(t)}if(e.bfinally){t.space();e.bfinally.print(t)}}));DEFPRINT(we,(function(e,t){t.print("catch");if(e.argname){t.space();t.with_parens((function(){e.argname.print(t)}))}t.space();print_braced(e,t)}));DEFPRINT(Oe,(function(e,t){t.print("finally");t.space();print_braced(e,t)}));Fe.DEFMETHOD("_do_print",(function(e,t){e.print(t);e.space();this.definitions.forEach((function(t,n){if(n)e.comma();t.print(e)}));var n=e.parent();var i=n instanceof J||n instanceof ee;var r=!i||n&&n.init!==this;if(r)e.semicolon()}));DEFPRINT(Me,(function(e,t){e._do_print(t,"let")}));DEFPRINT(Ne,(function(e,t){e._do_print(t,"var")}));DEFPRINT(Ie,(function(e,t){e._do_print(t,"const")}));DEFPRINT(Be,(function(e,t){t.print("import");t.space();if(e.imported_name){e.imported_name.print(t)}if(e.imported_name&&e.imported_names){t.print(",");t.space()}if(e.imported_names){if(e.imported_names.length===1&&e.imported_names[0].foreign_name.name==="*"){e.imported_names[0].print(t)}else{t.print("{");e.imported_names.forEach((function(n,i){t.space();n.print(t);if(i{if(e instanceof ie)return true;if(e instanceof Qe&&e.operator=="in"){return nn}}))}e.print(t,i)}DEFPRINT(Pe,(function(e,t){e.name.print(t);if(e.value){t.space();t.print("=");t.space();var n=t.parent(1);var i=n instanceof J||n instanceof ee;parenthesize_for_noin(e.value,t,i)}}));DEFPRINT(ze,(function(e,t){e.expression.print(t);if(e instanceof Ke&&e.args.length===0)return;if(e.expression instanceof ze||e.expression instanceof oe){t.add_mapping(e.start)}if(e.optional)t.print("?.");t.with_parens((function(){e.args.forEach((function(e,n){if(n)t.comma();e.print(t)}))}))}));DEFPRINT(Ke,(function(e,t){t.print("new");t.space();ze.prototype._codegen(e,t)}));Ge.DEFMETHOD("_do_print",(function(e){this.expressions.forEach((function(t,n){if(n>0){e.comma();if(e.should_break()){e.newline();e.indent()}}t.print(e)}))}));DEFPRINT(Ge,(function(e,t){e._do_print(t)}));DEFPRINT(Xe,(function(e,t){var n=e.expression;n.print(t);var i=e.property;var r=f.has(i)?t.option("ie8"):!is_identifier_string(i,t.option("ecma")>=2015||t.option("safari10"));if(e.optional)t.print("?.");if(r){t.print("[");t.add_mapping(e.end);t.print_string(i);t.print("]")}else{if(n instanceof Ht&&n.getValue()>=0){if(!/[xa-f.)]/i.test(t.last())){t.print(".")}}if(!e.optional)t.print(".");t.add_mapping(e.end);t.print_name(i)}}));DEFPRINT(We,(function(e,t){var n=e.expression;n.print(t);var i=e.property;if(e.optional)t.print("?");t.print(".#");t.print_name(i)}));DEFPRINT(qe,(function(e,t){e.expression.print(t);if(e.optional)t.print("?.");t.print("[");e.property.print(t);t.print("]")}));DEFPRINT(Ye,(function(e,t){e.expression.print(t)}));DEFPRINT($e,(function(e,t){var n=e.operator;t.print(n);if(/^[a-z]/i.test(n)||/[+-]$/.test(n)&&e.expression instanceof $e&&/^[+-]/.test(e.expression.operator)){t.space()}e.expression.print(t)}));DEFPRINT(Ze,(function(e,t){e.expression.print(t);t.print(e.operator)}));DEFPRINT(Qe,(function(e,t){var n=e.operator;e.left.print(t);if(n[0]==">"&&e.left instanceof Ze&&e.left.operator=="--"){t.print(" ")}else{t.space()}t.print(n);if((n=="<"||n=="<<")&&e.right instanceof $e&&e.right.operator=="!"&&e.right.expression instanceof $e&&e.right.expression.operator=="--"){t.print(" ")}else{t.space()}e.right.print(t)}));DEFPRINT(Je,(function(e,t){e.condition.print(t);t.space();t.print("?");t.space();e.consequent.print(t);t.space();t.colon();e.alternative.print(t)}));DEFPRINT(nt,(function(e,t){t.with_square((function(){var n=e.elements,i=n.length;if(i>0)t.space();n.forEach((function(e,n){if(n)t.comma();e.print(t);if(n===i-1&&e instanceof Zt)t.comma()}));if(i>0)t.space()}))}));DEFPRINT(it,(function(e,t){if(e.properties.length>0)t.with_block((function(){e.properties.forEach((function(e,n){if(n){t.print(",");t.newline()}t.indent();e.print(t)}));t.newline()}));else print_braced_empty(e,t)}));DEFPRINT(_t,(function(e,t){t.print("class");t.space();if(e.name){e.name.print(t);t.space()}if(e.extends){var n=!(e.extends instanceof Pt)&&!(e.extends instanceof He)&&!(e.extends instanceof Et)&&!(e.extends instanceof ue);t.print("extends");if(n){t.print("(")}else{t.space()}e.extends.print(t);if(n){t.print(")")}else{t.space()}}if(e.properties.length>0)t.with_block((function(){e.properties.forEach((function(e,n){if(n){t.newline()}t.indent();e.print(t)}));t.newline()}));else t.print("{}")}));DEFPRINT(vt,(function(e,t){t.print("new.target")}));function print_property_name(e,t,n){if(n.option("quote_keys")){return n.print_string(e)}if(""+ +e==e&&e>=0){if(n.option("keep_numbers")){return n.print(e)}return n.print(make_num(e))}var i=f.has(e)?n.option("ie8"):n.option("ecma")<2015||n.option("safari10")?!is_basic_identifier_string(e):!is_identifier_string(e,true);if(i||t&&n.option("keep_quoted_props")){return n.print_string(e,t)}return n.print_name(e)}DEFPRINT(ot,(function(e,t){function get_name(e){var t=e.definition();return t?t.mangled_name||t.name:e.name}var n=t.option("shorthand");if(n&&e.value instanceof gt&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value)===e.key&&!f.has(e.key)){print_property_name(e.key,e.quote,t)}else if(n&&e.value instanceof tt&&e.value.left instanceof gt&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value.left)===e.key){print_property_name(e.key,e.quote,t);t.space();t.print("=");t.space();e.value.right.print(t)}else{if(!(e.key instanceof V)){print_property_name(e.key,e.quote,t)}else{t.with_square((function(){e.key.print(t)}))}t.colon();e.value.print(t)}}));DEFPRINT(ht,((e,t)=>{if(e.static){t.print("static");t.space()}t.print("#");print_property_name(e.key.name,e.quote,t);if(e.value){t.print("=");e.value.print(t)}t.semicolon()}));DEFPRINT(dt,((e,t)=>{if(e.static){t.print("static");t.space()}if(e.key instanceof Ct){print_property_name(e.key.name,e.quote,t)}else{t.print("[");e.key.print(t);t.print("]")}if(e.value){t.print("=");e.value.print(t)}t.semicolon()}));rt.DEFMETHOD("_print_getter_setter",(function(e,t,n){var i=this;if(i.static){n.print("static");n.space()}if(e){n.print(e);n.space()}if(i.key instanceof xt){if(t)n.print("#");print_property_name(i.key.name,i.quote,n)}else{n.with_square((function(){i.key.print(n)}))}i.value._do_print(n,true)}));DEFPRINT(lt,(function(e,t){e._print_getter_setter("set",false,t)}));DEFPRINT(ct,(function(e,t){e._print_getter_setter("get",false,t)}));DEFPRINT(st,(function(e,t){e._print_getter_setter("set",true,t)}));DEFPRINT(ut,(function(e,t){e._print_getter_setter("get",true,t)}));DEFPRINT(pt,(function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,true,t)}));DEFPRINT(ft,(function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,false,t)}));gt.DEFMETHOD("_do_print",(function(e){var t=this.definition();e.print_name(t?t.mangled_name||t.name:this.name)}));DEFPRINT(gt,(function(e,t){e._do_print(t)}));DEFPRINT(Zt,noop);DEFPRINT(Ut,(function(e,t){t.print("this")}));DEFPRINT(zt,(function(e,t){t.print("super")}));DEFPRINT(Kt,(function(e,t){t.print(e.getValue())}));DEFPRINT(Gt,(function(e,t){t.print_string(e.getValue(),e.quote,t.in_directive)}));DEFPRINT(Ht,(function(e,t){if((t.option("keep_numbers")||t.use_asm)&&e.raw){t.print(e.raw)}else{t.print(make_num(e.getValue()))}}));DEFPRINT(Xt,(function(e,t){t.print(e.getValue()+"n")}));const e=/(<\s*\/\s*script)/i;const slash_script_replace=(e,t)=>t.replace("/","\\/");DEFPRINT(Wt,(function(t,n){let{source:i,flags:r}=t.getValue();i=regexp_source_fix(i);r=r?sort_regexp_flags(r):"";i=i.replace(e,slash_script_replace);n.print(n.to_utf8(`/${i}/${r}`));const a=n.parent();if(a instanceof Qe&&/^\w/.test(a.operator)&&a.left===t){n.print(" ")}}));function force_statement(e,t){if(t.option("braces")){make_block(e,t)}else{if(!e||e instanceof W)t.force_semicolon();else e.print(t)}}function best_of(e){var t=e[0],n=t.length;for(var i=1;ie===null&&t===null||e.TYPE===t.TYPE&&e.shallow_cmp(t);const equivalent_to=(e,t)=>{if(!shallow_cmp(e,t))return false;const n=[e];const i=[t];const r=n.push.bind(n);const a=i.push.bind(i);while(n.length&&i.length){const e=n.pop();const t=i.pop();if(!shallow_cmp(e,t))return false;e._children_backwards(r);t._children_backwards(a);if(n.length!==i.length){return false}}return n.length==0&&i.length==0};const mkshallow=e=>{const t=Object.keys(e).map((t=>{if(e[t]==="eq"){return`this.${t} === other.${t}`}else if(e[t]==="exist"){return`(this.${t} == null ? other.${t} == null : this.${t} === other.${t})`}else{throw new Error(`mkshallow: Unexpected instruction: ${e[t]}`)}})).join(" && ");return new Function("other","return "+t)};const pass_through=()=>true;V.prototype.shallow_cmp=function(){throw new Error("did not find a shallow_cmp function for "+this.constructor.name)};z.prototype.shallow_cmp=pass_through;K.prototype.shallow_cmp=mkshallow({value:"eq"});G.prototype.shallow_cmp=pass_through;H.prototype.shallow_cmp=pass_through;W.prototype.shallow_cmp=pass_through;Y.prototype.shallow_cmp=mkshallow({"label.name":"eq"});Z.prototype.shallow_cmp=pass_through;Q.prototype.shallow_cmp=pass_through;J.prototype.shallow_cmp=mkshallow({init:"exist",condition:"exist",step:"exist"});ee.prototype.shallow_cmp=pass_through;te.prototype.shallow_cmp=pass_through;ne.prototype.shallow_cmp=pass_through;re.prototype.shallow_cmp=pass_through;ae.prototype.shallow_cmp=pass_through;oe.prototype.shallow_cmp=mkshallow({is_generator:"eq",async:"eq"});fe.prototype.shallow_cmp=mkshallow({is_array:"eq"});pe.prototype.shallow_cmp=pass_through;_e.prototype.shallow_cmp=pass_through;de.prototype.shallow_cmp=mkshallow({value:"eq"});he.prototype.shallow_cmp=pass_through;ve.prototype.shallow_cmp=pass_through;ye.prototype.shallow_cmp=pass_through;Se.prototype.shallow_cmp=mkshallow({is_star:"eq"});Ae.prototype.shallow_cmp=mkshallow({alternative:"exist"});ke.prototype.shallow_cmp=pass_through;Te.prototype.shallow_cmp=pass_through;Re.prototype.shallow_cmp=mkshallow({bcatch:"exist",bfinally:"exist"});we.prototype.shallow_cmp=mkshallow({argname:"exist"});Oe.prototype.shallow_cmp=pass_through;Fe.prototype.shallow_cmp=pass_through;Pe.prototype.shallow_cmp=mkshallow({value:"exist"});Le.prototype.shallow_cmp=pass_through;Be.prototype.shallow_cmp=mkshallow({imported_name:"exist",imported_names:"exist"});Ve.prototype.shallow_cmp=pass_through;Ue.prototype.shallow_cmp=mkshallow({exported_definition:"exist",exported_value:"exist",exported_names:"exist",module_name:"eq",is_default:"eq"});ze.prototype.shallow_cmp=pass_through;Ge.prototype.shallow_cmp=pass_through;He.prototype.shallow_cmp=pass_through;Ye.prototype.shallow_cmp=pass_through;Xe.prototype.shallow_cmp=mkshallow({property:"eq"});We.prototype.shallow_cmp=mkshallow({property:"eq"});je.prototype.shallow_cmp=mkshallow({operator:"eq"});Qe.prototype.shallow_cmp=mkshallow({operator:"eq"});Je.prototype.shallow_cmp=pass_through;nt.prototype.shallow_cmp=pass_through;it.prototype.shallow_cmp=pass_through;rt.prototype.shallow_cmp=pass_through;ot.prototype.shallow_cmp=mkshallow({key:"eq"});lt.prototype.shallow_cmp=mkshallow({static:"eq"});ct.prototype.shallow_cmp=mkshallow({static:"eq"});ft.prototype.shallow_cmp=mkshallow({static:"eq",is_generator:"eq",async:"eq"});_t.prototype.shallow_cmp=mkshallow({name:"exist",extends:"exist"});dt.prototype.shallow_cmp=mkshallow({static:"eq"});gt.prototype.shallow_cmp=mkshallow({name:"eq"});vt.prototype.shallow_cmp=pass_through;Ut.prototype.shallow_cmp=pass_through;zt.prototype.shallow_cmp=pass_through;Gt.prototype.shallow_cmp=mkshallow({value:"eq"});Ht.prototype.shallow_cmp=mkshallow({value:"eq"});Xt.prototype.shallow_cmp=mkshallow({value:"eq"});Wt.prototype.shallow_cmp=function(e){return this.value.flags===e.value.flags&&this.value.source===e.value.source};qt.prototype.shallow_cmp=pass_through;const _n=1<<0;const dn=1<<1;let hn=null;let mn=null;class SymbolDef{constructor(e,t,n){this.name=t.name;this.orig=[t];this.init=n;this.eliminated=0;this.assignments=0;this.scope=e;this.replaced=0;this.global=false;this.export=0;this.mangled_name=null;this.undeclared=false;this.id=SymbolDef.next_id++;this.chained=false;this.direct_access=false;this.escaped=0;this.recursive_refs=0;this.references=[];this.should_replace=undefined;this.single_use=false;this.fixed=false;Object.seal(this)}fixed_value(){if(!this.fixed||this.fixed instanceof V)return this.fixed;return this.fixed()}unmangleable(e){if(!e)e={};if(hn&&hn.has(this.id)&&keep_name(e.keep_fnames,this.orig[0].name))return true;return this.global&&!e.toplevel||this.export&_n||this.undeclared||!e.eval&&this.scope.pinned()||(this.orig[0]instanceof Rt||this.orig[0]instanceof Tt)&&keep_name(e.keep_fnames,this.orig[0].name)||this.orig[0]instanceof xt||(this.orig[0]instanceof Ot||this.orig[0]instanceof wt)&&keep_name(e.keep_classnames,this.orig[0].name)}mangle(e){const t=e.cache&&e.cache.props;if(this.global&&t&&t.has(this.name)){this.mangled_name=t.get(this.name)}else if(!this.mangled_name&&!this.unmangleable(e)){var n=this.scope;var i=this.orig[0];if(e.ie8&&i instanceof Rt)n=n.parent_scope;const r=redefined_catch_def(this);this.mangled_name=r?r.mangled_name||r.name:n.next_mangled(e,this);if(this.global&&t){t.set(this.name,this.mangled_name)}}}}SymbolDef.next_id=1;function redefined_catch_def(e){if(e.orig[0]instanceof Ft&&e.scope.is_block_scope()){return e.scope.get_defun_scope().variables.get(e.name)}}ie.DEFMETHOD("figure_out_scope",(function(e,{parent_scope:t=null,toplevel:n=this}={}){e=defaults(e,{cache:null,ie8:false,safari10:false});if(!(n instanceof re)){throw new Error("Invalid toplevel scope")}var i=this.parent_scope=t;var r=new Map;var a=null;var o=null;var s=[];var u=new TreeWalker(((t,n)=>{if(t.is_block_scope()){const r=i;t.block_scope=i=new ie(t);i._block_scope=true;const a=t instanceof we?r.parent_scope:r;i.init_scope_vars(a);i.uses_with=r.uses_with;i.uses_eval=r.uses_eval;if(e.safari10){if(t instanceof J||t instanceof ee){s.push(i)}}if(t instanceof ke){const e=i;i=r;t.expression.walk(u);i=e;for(let e=0;e{if(e===t)return true;if(t instanceof yt){return e instanceof Rt}return!(e instanceof At||e instanceof St)}))){js_error(`"${t.name}" is redeclared`,t.start.file,t.start.line,t.start.col,t.start.pos)}if(!(t instanceof kt))mark_export(d,2);if(a!==i){t.mark_enclosed();var d=i.find_variable(t);if(t.thedef!==d){t.thedef=d;t.reference()}}}else if(t instanceof Vt){var h=r.get(t.name);if(!h)throw new Error(string_template("Undefined label {name} [{line},{col}]",{name:t.name,line:t.start.line,col:t.start.col}));t.thedef=h}if(!(i instanceof re)&&(t instanceof Ue||t instanceof Be)){js_error(`"${t.TYPE}" statement may only appear at the top level`,t.start.file,t.start.line,t.start.col,t.start.pos)}}));this.walk(u);function mark_export(e,t){if(o){var n=0;do{t++}while(u.parent(n++)!==o)}var i=u.parent(t);if(e.export=i instanceof Ue?_n:0){var r=i.exported_definition;if((r instanceof ce||r instanceof mt)&&i.is_default){e.export=dn}}}const l=this instanceof re;if(l){this.globals=new Map}var u=new TreeWalker((e=>{if(e instanceof ve&&e.label){e.label.thedef.references.push(e);return true}if(e instanceof Pt){var t=e.name;if(t=="eval"&&u.parent()instanceof ze){for(var i=e.scope;i&&!i.uses_eval;i=i.parent_scope){i.uses_eval=true}}var r;if(u.parent()instanceof Le&&u.parent(1).module_name||!(r=e.scope.find_variable(t))){r=n.def_global(e);if(e instanceof Lt)r.export=_n}else if(r.scope instanceof oe&&t=="arguments"){r.scope.uses_arguments=true}e.thedef=r;e.reference();if(e.scope.is_block_scope()&&!(r.orig[0]instanceof yt)){e.scope=e.scope.get_defun_scope()}return true}var a;if(e instanceof Ft&&(a=redefined_catch_def(e.definition()))){var i=e.scope;while(i){push_uniq(i.enclosed,a);if(i===a.scope)break;i=i.parent_scope}}}));this.walk(u);if(e.ie8||e.safari10){walk(this,(e=>{if(e instanceof Ft){var t=e.name;var i=e.thedef.references;var r=e.scope.get_defun_scope();var a=r.find_variable(t)||n.globals.get(t)||r.def_variable(e);i.forEach((function(e){e.thedef=a;e.reference()}));e.thedef=a;e.reference();return true}}))}if(e.safari10){for(const e of s){e.parent_scope.variables.forEach((function(t){push_uniq(e.enclosed,t)}))}}}));re.DEFMETHOD("def_global",(function(e){var t=this.globals,n=e.name;if(t.has(n)){return t.get(n)}else{var i=new SymbolDef(this,e);i.undeclared=true;i.global=true;t.set(n,i);return i}}));ie.DEFMETHOD("init_scope_vars",(function(e){this.variables=new Map;this.uses_with=false;this.uses_eval=false;this.parent_scope=e;this.enclosed=[];this.cname=-1}));ie.DEFMETHOD("conflicting_def",(function(e){return this.enclosed.find((t=>t.name===e))||this.variables.has(e)||this.parent_scope&&this.parent_scope.conflicting_def(e)}));ie.DEFMETHOD("conflicting_def_shallow",(function(e){return this.enclosed.find((t=>t.name===e))||this.variables.has(e)}));ie.DEFMETHOD("add_child_scope",(function(e){if(e.parent_scope===this)return;e.parent_scope=this;const t=(()=>{const e=[];let t=this;do{e.push(t)}while(t=t.parent_scope);e.reverse();return e})();const n=new Set(e.enclosed);const i=[];for(const e of t){i.forEach((t=>push_uniq(e.enclosed,t)));for(const t of e.variables.values()){if(n.has(t)){push_uniq(i,t);push_uniq(e.enclosed,t)}}}}));function find_scopes_visible_from(e){const t=new Set;for(const n of new Set(e)){(function bubble_up(e){if(e==null||t.has(e))return;t.add(e);bubble_up(e.parent_scope)})(n)}return[...t]}ie.DEFMETHOD("create_symbol",(function(e,{source:t,tentative_name:n,scope:i,conflict_scopes:r=[i],init:a=null}={}){let o;r=find_scopes_visible_from(r);if(n){n=o=n.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/gi,"_");let e=0;while(r.find((e=>e.conflicting_def_shallow(o)))){o=n+"$"+e++}}if(!o){throw new Error("No symbol name could be generated in create_symbol()")}const s=make_node(e,t,{name:o,scope:i});this.def_variable(s,a||null);s.mark_enclosed();return s}));V.DEFMETHOD("is_block_scope",return_false);_t.DEFMETHOD("is_block_scope",return_false);oe.DEFMETHOD("is_block_scope",return_false);re.DEFMETHOD("is_block_scope",return_false);Te.DEFMETHOD("is_block_scope",return_false);H.DEFMETHOD("is_block_scope",return_true);ie.DEFMETHOD("is_block_scope",(function(){return this._block_scope||false}));j.DEFMETHOD("is_block_scope",return_true);oe.DEFMETHOD("init_scope_vars",(function(){ie.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false;this.def_variable(new kt({name:"arguments",start:this.start,end:this.end}))}));le.DEFMETHOD("init_scope_vars",(function(){ie.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false}));gt.DEFMETHOD("mark_enclosed",(function(){var e=this.definition();var t=this.scope;while(t){push_uniq(t.enclosed,e);if(t===e.scope)break;t=t.parent_scope}}));gt.DEFMETHOD("reference",(function(){this.definition().references.push(this);this.mark_enclosed()}));ie.DEFMETHOD("find_variable",(function(e){if(e instanceof gt)e=e.name;return this.variables.get(e)||this.parent_scope&&this.parent_scope.find_variable(e)}));ie.DEFMETHOD("def_function",(function(e,t){var n=this.def_variable(e,t);if(!n.init||n.init instanceof ce)n.init=t;return n}));ie.DEFMETHOD("def_variable",(function(e,t){var n=this.variables.get(e.name);if(n){n.orig.push(e);if(n.init&&(n.scope!==e.scope||n.init instanceof ue)){n.init=t}}else{n=new SymbolDef(this,e,t);this.variables.set(e.name,n);n.global=!this.parent_scope}return e.thedef=n}));function next_mangled(e,t){var n=e.enclosed;e:while(true){var i=En(++e.cname);if(f.has(i))continue;if(t.reserved.has(i))continue;if(mn&&mn.has(i))continue e;for(let e=n.length;--e>=0;){const r=n[e];const a=r.mangled_name||r.unmangleable(t)&&r.name;if(i==a)continue e}return i}}ie.DEFMETHOD("next_mangled",(function(e){return next_mangled(this,e)}));re.DEFMETHOD("next_mangled",(function(e){let t;const n=this.mangled_names;do{t=next_mangled(this,e)}while(n.has(t));return t}));ue.DEFMETHOD("next_mangled",(function(e,t){var n=t.orig[0]instanceof kt&&this.name&&this.name.definition();var i=n?n.mangled_name||n.name:null;while(true){var r=next_mangled(this,e);if(!i||i!=r)return r}}));gt.DEFMETHOD("unmangleable",(function(e){var t=this.definition();return!t||t.unmangleable(e)}));It.DEFMETHOD("unmangleable",return_false);gt.DEFMETHOD("unreferenced",(function(){return!this.definition().references.length&&!this.scope.pinned()}));gt.DEFMETHOD("definition",(function(){return this.thedef}));gt.DEFMETHOD("global",(function(){return this.thedef.global}));re.DEFMETHOD("_default_mangler_options",(function(e){e=defaults(e,{eval:false,ie8:false,keep_classnames:false,keep_fnames:false,module:false,reserved:[],toplevel:false});if(e.module)e.toplevel=true;if(!Array.isArray(e.reserved)&&!(e.reserved instanceof Set)){e.reserved=[]}e.reserved=new Set(e.reserved);e.reserved.add("arguments");return e}));re.DEFMETHOD("mangle_names",(function(e){e=this._default_mangler_options(e);var t=-1;var n=[];if(e.keep_fnames){hn=new Set}const i=this.mangled_names=new Set;if(e.cache){this.globals.forEach(collect);if(e.cache.props){e.cache.props.forEach((function(e){i.add(e)}))}}var r=new TreeWalker((function(i,r){if(i instanceof Y){var a=t;r();t=a;return true}if(i instanceof ie){i.variables.forEach(collect);return}if(i.is_block_scope()){i.block_scope.variables.forEach(collect);return}if(hn&&i instanceof Pe&&i.value instanceof oe&&!i.value.name&&keep_name(e.keep_fnames,i.name.name)){hn.add(i.name.definition().id);return}if(i instanceof It){let e;do{e=En(++t)}while(f.has(e));i.mangled_name=e;return true}if(!(e.ie8||e.safari10)&&i instanceof Ft){n.push(i.definition());return}}));this.walk(r);if(e.keep_fnames||e.keep_classnames){mn=new Set;n.forEach((t=>{if(t.name.length<6&&t.unmangleable(e)){mn.add(t.name)}}))}n.forEach((t=>{t.mangle(e)}));hn=null;mn=null;function collect(t){const i=!e.reserved.has(t.name)&&!(t.export&_n);if(i){n.push(t)}}}));re.DEFMETHOD("find_colliding_names",(function(e){const t=e.cache&&e.cache.props;const n=new Set;e.reserved.forEach(to_avoid);this.globals.forEach(add_def);this.walk(new TreeWalker((function(e){if(e instanceof ie)e.variables.forEach(add_def);if(e instanceof Ft)add_def(e.definition())})));return n;function to_avoid(e){n.add(e)}function add_def(n){var i=n.name;if(n.global&&t&&t.has(i))i=t.get(i);else if(!n.unmangleable(e))return;to_avoid(i)}}));re.DEFMETHOD("expand_names",(function(e){En.reset();En.sort();e=this._default_mangler_options(e);var t=this.find_colliding_names(e);var n=0;this.globals.forEach(rename);this.walk(new TreeWalker((function(e){if(e instanceof ie)e.variables.forEach(rename);if(e instanceof Ft)rename(e.definition())})));function next_name(){var e;do{e=En(n++)}while(t.has(e)||f.has(e));return e}function rename(t){if(t.global&&e.cache)return;if(t.unmangleable(e))return;if(e.reserved.has(t.name))return;const n=redefined_catch_def(t);const i=t.name=n?n.name:next_name();t.orig.forEach((function(e){e.name=i}));t.references.forEach((function(e){e.name=i}))}}));V.DEFMETHOD("tail_node",return_this);Ge.DEFMETHOD("tail_node",(function(){return this.expressions[this.expressions.length-1]}));re.DEFMETHOD("compute_char_frequency",(function(e){e=this._default_mangler_options(e);try{V.prototype.print=function(t,n){this._print(t,n);if(this instanceof gt&&!this.unmangleable(e)){En.consider(this.name,-1)}else if(e.properties){if(this instanceof We){En.consider("#"+this.property,-1)}else if(this instanceof Xe){En.consider(this.property,-1)}else if(this instanceof qe){skip_string(this.property)}}};En.consider(this.print_to_string(),1)}finally{V.prototype.print=V.prototype._print}En.sort();function skip_string(e){if(e instanceof Gt){En.consider(e.value,-1)}else if(e instanceof Je){skip_string(e.consequent);skip_string(e.alternative)}else if(e instanceof Ge){skip_string(e.tail_node())}}}));const En=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");const t="0123456789".split("");let n;let i;function reset(){i=new Map;e.forEach((function(e){i.set(e,0)}));t.forEach((function(e){i.set(e,0)}))}base54.consider=function(e,t){for(var n=e.length;--n>=0;){i.set(e[n],i.get(e[n])+t)}};function compare(e,t){return i.get(t)-i.get(e)}base54.sort=function(){n=mergeSort(e,compare).concat(mergeSort(t,compare))};base54.reset=reset;reset();function base54(e){var t="",i=54;e++;do{e--;t+=n[e%i];e=Math.floor(e/i);i=64}while(e>0);return t}return base54})();let gn=undefined;V.prototype.size=function(e,t){gn=e&&e.mangle_options;let n=0;walk_parent(this,((e,t)=>{n+=e._size(t);if(e instanceof le&&e.is_braceless()){n+=e.body[0].value._size(t);return true}}),t||e&&e.stack);gn=undefined;return n};V.prototype._size=()=>0;z.prototype._size=()=>8;K.prototype._size=function(){return 2+this.value.length};const list_overhead=e=>e.length&&e.length-1;H.prototype._size=function(){return 2+list_overhead(this.body)};re.prototype._size=function(){return list_overhead(this.body)};W.prototype._size=()=>1;Y.prototype._size=()=>2;Z.prototype._size=()=>9;Q.prototype._size=()=>7;J.prototype._size=()=>8;ee.prototype._size=()=>8;ne.prototype._size=()=>6;ae.prototype._size=()=>3;const lambda_modifiers=e=>(e.is_generator?1:0)+(e.async?6:0);se.prototype._size=function(){return lambda_modifiers(this)+4+list_overhead(this.argnames)+list_overhead(this.body)};ue.prototype._size=function(e){const t=!!first_in_statement(e);return t*2+lambda_modifiers(this)+12+list_overhead(this.argnames)+list_overhead(this.body)};ce.prototype._size=function(){return lambda_modifiers(this)+13+list_overhead(this.argnames)+list_overhead(this.body)};le.prototype._size=function(){let e=2+list_overhead(this.argnames);if(!(this.argnames.length===1&&this.argnames[0]instanceof gt)){e+=2}const t=this.is_braceless()?0:list_overhead(this.body)+2;return lambda_modifiers(this)+e+t};fe.prototype._size=()=>2;_e.prototype._size=function(){return 2+Math.floor(this.segments.length/2)*3};de.prototype._size=function(){return this.value.length};Ee.prototype._size=function(){return this.value?7:6};ge.prototype._size=()=>6;be.prototype._size=function(){return this.label?6:5};De.prototype._size=function(){return this.label?9:8};Ae.prototype._size=()=>4;ke.prototype._size=function(){return 8+list_overhead(this.body)};Ce.prototype._size=function(){return 5+list_overhead(this.body)};xe.prototype._size=function(){return 8+list_overhead(this.body)};Re.prototype._size=function(){return 3+list_overhead(this.body)};we.prototype._size=function(){let e=7+list_overhead(this.body);if(this.argname){e+=2}return e};Oe.prototype._size=function(){return 7+list_overhead(this.body)};const def_size=(e,t)=>e+list_overhead(t.definitions);Ne.prototype._size=function(){return def_size(4,this)};Me.prototype._size=function(){return def_size(4,this)};Ie.prototype._size=function(){return def_size(6,this)};Pe.prototype._size=function(){return this.value?1:0};Le.prototype._size=function(){return this.name?4:0};Be.prototype._size=function(){let e=6;if(this.imported_name)e+=1;if(this.imported_name||this.imported_names)e+=5;if(this.imported_names){e+=2+list_overhead(this.imported_names)}return e};Ve.prototype._size=()=>11;Ue.prototype._size=function(){let e=7+(this.is_default?8:0);if(this.exported_value){e+=this.exported_value._size()}if(this.exported_names){e+=2+list_overhead(this.exported_names)}if(this.module_name){e+=5}return e};ze.prototype._size=function(){if(this.optional){return 4+list_overhead(this.args)}return 2+list_overhead(this.args)};Ke.prototype._size=function(){return 6+list_overhead(this.args)};Ge.prototype._size=function(){return list_overhead(this.expressions)};Xe.prototype._size=function(){if(this.optional){return this.property.length+2}return this.property.length+1};We.prototype._size=function(){if(this.optional){return this.property.length+3}return this.property.length+2};qe.prototype._size=function(){return this.optional?4:2};je.prototype._size=function(){if(this.operator==="typeof")return 7;if(this.operator==="void")return 5;return this.operator.length};Qe.prototype._size=function(e){if(this.operator==="in")return 4;let t=this.operator.length;if((this.operator==="+"||this.operator==="-")&&this.right instanceof je&&this.right.operator===this.operator){t+=1}if(this.needs_parens(e)){t+=2}return t};Je.prototype._size=()=>3;nt.prototype._size=function(){return 2+list_overhead(this.elements)};it.prototype._size=function(e){let t=2;if(first_in_statement(e)){t+=2}return t+list_overhead(this.properties)};const key_size=e=>typeof e==="string"?e.length:0;ot.prototype._size=function(){return key_size(this.key)+1};const static_size=e=>e?7:0;ct.prototype._size=function(){return 5+static_size(this.static)+key_size(this.key)};lt.prototype._size=function(){return 5+static_size(this.static)+key_size(this.key)};ft.prototype._size=function(){return static_size(this.static)+key_size(this.key)+lambda_modifiers(this)};pt.prototype._size=function(){return ft.prototype._size.call(this)+1};ut.prototype._size=st.prototype._size=function(){return ft.prototype._size.call(this)+4};_t.prototype._size=function(){return(this.name?8:7)+(this.extends?8:0)};dt.prototype._size=function(){return static_size(this.static)+(typeof this.key==="string"?this.key.length+2:0)+(this.value?1:0)};ht.prototype._size=function(){return dt.prototype._size.call(this)+1};gt.prototype._size=function(){return!gn||this.definition().unmangleable(gn)?this.name.length:1};Ct.prototype._size=function(){return this.name.length};Pt.prototype._size=bt.prototype._size=function(){const{name:e,thedef:t}=this;if(t&&t.global)return e.length;if(e==="arguments")return 9;return gt.prototype._size.call(this)};vt.prototype._size=()=>10;Mt.prototype._size=function(){return this.name.length};Bt.prototype._size=function(){return this.name.length};Ut.prototype._size=()=>4;zt.prototype._size=()=>5;Gt.prototype._size=function(){return this.value.length+2};Ht.prototype._size=function(){const{value:e}=this;if(e===0)return 1;if(e>0&&Math.floor(e)===e){return Math.floor(Math.log10(e)+1)}return e.toString().length};Xt.prototype._size=function(){return this.value.length};Wt.prototype._size=function(){return this.value.toString().length};Yt.prototype._size=()=>4;jt.prototype._size=()=>3;$t.prototype._size=()=>6;Zt.prototype._size=()=>0;Qt.prototype._size=()=>8;tn.prototype._size=()=>4;en.prototype._size=()=>5;ye.prototype._size=()=>6;Se.prototype._size=()=>6;const vn=1;const bn=2;const Dn=4;const yn=8;const Sn=16;const An=32;const kn=256;const Tn=512;const xn=1024;const Cn=kn|Tn|xn;const has_flag=(e,t)=>e.flags&t;const set_flag=(e,t)=>{e.flags|=t};const clear_flag=(e,t)=>{e.flags&=~t};class Compressor extends TreeWalker{constructor(e,{false_by_default:t=false,mangle_options:n=false}){super();if(e.defaults!==undefined&&!e.defaults)t=true;this.options=defaults(e,{arguments:false,arrows:!t,booleans:!t,booleans_as_integers:false,collapse_vars:!t,comparisons:!t,computed_props:!t,conditionals:!t,dead_code:!t,defaults:true,directives:!t,drop_console:false,drop_debugger:!t,ecma:5,evaluate:!t,expression:false,global_defs:false,hoist_funs:false,hoist_props:!t,hoist_vars:false,ie8:false,if_return:!t,inline:!t,join_vars:!t,keep_classnames:false,keep_fargs:true,keep_fnames:false,keep_infinity:false,loops:!t,module:false,negate_iife:!t,passes:1,properties:!t,pure_getters:!t&&"strict",pure_funcs:null,reduce_funcs:!t,reduce_vars:!t,sequences:!t,side_effects:!t,switches:!t,top_retain:null,toplevel:!!(e&&e["top_retain"]),typeofs:!t,unsafe:false,unsafe_arrows:false,unsafe_comps:false,unsafe_Function:false,unsafe_math:false,unsafe_symbols:false,unsafe_methods:false,unsafe_proto:false,unsafe_regexp:false,unsafe_undefined:false,unused:!t,warnings:false},true);var i=this.options["global_defs"];if(typeof i=="object")for(var r in i){if(r[0]==="@"&&HOP(i,r)){i[r.slice(1)]=parse(i[r],{expression:true})}}if(this.options["inline"]===true)this.options["inline"]=3;var a=this.options["pure_funcs"];if(typeof a=="function"){this.pure_funcs=a}else{this.pure_funcs=a?function(e){return!a.includes(e.expression.print_to_string())}:return_true}var o=this.options["top_retain"];if(o instanceof RegExp){this.top_retain=function(e){return o.test(e.name)}}else if(typeof o=="function"){this.top_retain=o}else if(o){if(typeof o=="string"){o=o.split(/,/)}this.top_retain=function(e){return o.includes(e.name)}}if(this.options["module"]){this.directives["use strict"]=true;this.options["toplevel"]=true}var s=this.options["toplevel"];this.toplevel=typeof s=="string"?{funcs:/funcs/.test(s),vars:/vars/.test(s)}:{funcs:s,vars:s};var u=this.options["sequences"];this.sequences_limit=u==1?800:u|0;this.evaluated_regexps=new Map;this._toplevel=undefined;this.mangle_options=n}option(e){return this.options[e]}exposed(e){if(e.export)return true;if(e.global)for(var t=0,n=e.orig.length;t0||this.option("reduce_vars")){this._toplevel.reset_opt_flags(this)}this._toplevel=this._toplevel.transform(this);if(t>1){let e=0;walk(this._toplevel,(()=>{e++}));if(e=0){r.body[o]=r.body[o].transform(i)}}else if(r instanceof Ae){r.body=r.body.transform(i);if(r.alternative){r.alternative=r.alternative.transform(i)}}else if(r instanceof ne){r.body=r.body.transform(i)}return r}));n.transform(i)}));function read_property(e,t){t=get_value(t);if(t instanceof V)return;var n;if(e instanceof nt){var i=e.elements;if(t=="length")return make_node_from_constant(i.length,e);if(typeof t=="number"&&t in i)n=i[t]}else if(e instanceof it){t=""+t;var r=e.properties;for(var a=r.length;--a>=0;){var o=r[a];if(!(o instanceof ot))return;if(!n&&r[a].key===t)n=r[a].value}}return n instanceof Pt&&n.fixed_value()||n}function is_modified(e,t,n,i,r,a){var o=t.parent(r);var s=is_lhs(n,o);if(s)return s;if(!a&&o instanceof ze&&o.expression===n&&!(i instanceof le)&&!(i instanceof _t)&&!o.is_callee_pure(e)&&(!(i instanceof ue)||!(o instanceof Ke)&&i.contains_this())){return true}if(o instanceof nt){return is_modified(e,t,o,o,r+1)}if(o instanceof ot&&n===o.value){var u=t.parent(r+1);return is_modified(e,t,u,u,r+2)}if(o instanceof He&&o.expression===n){var l=read_property(i,o.property);return!a&&is_modified(e,t,o,l,r+1)}}(function(e){e(V,noop);function reset_def(e,t){t.assignments=0;t.chained=false;t.direct_access=false;t.escaped=0;t.recursive_refs=0;t.references=[];t.single_use=undefined;if(t.scope.pinned()){t.fixed=false}else if(t.orig[0]instanceof St||!e.exposed(t)){t.fixed=t.init}else{t.fixed=false}}function reset_variables(e,t,n){n.variables.forEach((function(n){reset_def(t,n);if(n.fixed===null){e.defs_to_safe_ids.set(n.id,e.safe_ids);mark(e,n,true)}else if(n.fixed){e.loop_ids.set(n.id,e.in_loop);mark(e,n,true)}}))}function reset_block_variables(e,t){if(t.block_scope)t.block_scope.variables.forEach((t=>{reset_def(e,t)}))}function push(e){e.safe_ids=Object.create(e.safe_ids)}function pop(e){e.safe_ids=Object.getPrototypeOf(e.safe_ids)}function mark(e,t,n){e.safe_ids[t.id]=n}function safe_to_read(e,t){if(t.single_use=="m")return false;if(e.safe_ids[t.id]){if(t.fixed==null){var n=t.orig[0];if(n instanceof kt||n.name=="arguments")return false;t.fixed=make_node($t,n)}return true}return t.fixed instanceof ce}function safe_to_assign(e,t,n,i){if(t.fixed===undefined)return true;let r;if(t.fixed===null&&(r=e.defs_to_safe_ids.get(t.id))){r[t.id]=false;e.defs_to_safe_ids.delete(t.id);return true}if(!HOP(e.safe_ids,t.id))return false;if(!safe_to_read(e,t))return false;if(t.fixed===false)return false;if(t.fixed!=null&&(!i||t.references.length>t.assignments))return false;if(t.fixed instanceof ce){return i instanceof V&&t.fixed.parent_scope===n}return t.orig.every((e=>!(e instanceof St||e instanceof Tt||e instanceof Rt)))}function ref_once(e,t,n){return t.option("unused")&&!n.scope.pinned()&&n.references.length-n.recursive_refs==1&&e.loop_ids.get(n.id)===e.in_loop}function is_immutable(e){if(!e)return false;return e.is_constant()||e instanceof oe||e instanceof Ut}function mark_escaped(e,t,n,i,r,a=0,o=1){var s=e.parent(a);if(r){if(r.is_constant())return;if(r instanceof Et)return}if(s instanceof et&&(s.operator==="="||s.logical)&&i===s.right||s instanceof ze&&(i!==s.expression||s instanceof Ke)||s instanceof me&&i===s.value&&i.scope!==t.scope||s instanceof Pe&&i===s.value||s instanceof Se&&i===s.value&&i.scope!==t.scope){if(o>1&&!(r&&r.is_constant_expression(n)))o=1;if(!t.escaped||t.escaped>o)t.escaped=o;return}else if(s instanceof nt||s instanceof ye||s instanceof Qe&&On.has(s.operator)||s instanceof Je&&i!==s.condition||s instanceof ae||s instanceof Ge&&i===s.tail_node()){mark_escaped(e,t,n,s,s,a+1,o)}else if(s instanceof ot&&i===s.value){var u=e.parent(a+1);mark_escaped(e,t,n,u,u,a+2,o)}else if(s instanceof He&&i===s.expression){r=read_property(r,s.property);mark_escaped(e,t,n,s,r,a+1,o+1);if(r)return}if(a>0)return;if(s instanceof Ge&&i!==s.tail_node())return;if(s instanceof G)return;t.direct_access=true}const suppress=e=>walk(e,(e=>{if(!(e instanceof gt))return;var t=e.definition();if(!t)return;if(e instanceof Pt)t.references.push(e);t.fixed=false}));e(se,(function(e,t,n){push(e);reset_variables(e,n,this);t();pop(e);return true}));e(et,(function(e,t,n){var i=this;if(i.left instanceof fe){suppress(i.left);return}const finish_walk=()=>{if(i.logical){i.left.walk(e);push(e);i.right.walk(e);pop(e);return true}};var r=i.left;if(!(r instanceof Pt))return finish_walk();var a=r.definition();var o=safe_to_assign(e,a,r.scope,i.right);a.assignments++;if(!o)return finish_walk();var s=a.fixed;if(!s&&i.operator!="="&&!i.logical)return finish_walk();var u=i.operator=="=";var l=u?i.right:i;if(is_modified(n,e,i,l,0))return finish_walk();a.references.push(r);if(!i.logical){if(!u)a.chained=true;a.fixed=u?function(){return i.right}:function(){return make_node(Qe,i,{operator:i.operator.slice(0,-1),left:s instanceof V?s:s(),right:i.right})}}if(i.logical){mark(e,a,false);push(e);i.right.walk(e);pop(e);return true}mark(e,a,false);i.right.walk(e);mark(e,a,true);mark_escaped(e,a,r.scope,i,l,0,1);return true}));e(Qe,(function(e){if(!On.has(this.operator))return;this.left.walk(e);push(e);this.right.walk(e);pop(e);return true}));e(H,(function(e,t,n){reset_block_variables(n,this)}));e(Ce,(function(e){push(e);this.expression.walk(e);pop(e);push(e);walk_body(this,e);pop(e);return true}));e(_t,(function(e,t){clear_flag(this,Sn);push(e);t();pop(e);return true}));e(Je,(function(e){this.condition.walk(e);push(e);this.consequent.walk(e);pop(e);push(e);this.alternative.walk(e);pop(e);return true}));e(Ye,(function(e,t){const n=e.safe_ids;t();e.safe_ids=n;return true}));e(ze,(function(e){this.expression.walk(e);if(this.optional){push(e)}for(const t of this.args)t.walk(e);return true}));e(He,(function(e){if(!this.optional)return;this.expression.walk(e);push(e);if(this.property instanceof V)this.property.walk(e);return true}));e(xe,(function(e,t){push(e);t();pop(e);return true}));function mark_lambda(e,t,n){clear_flag(this,Sn);push(e);reset_variables(e,n,this);if(this.uses_arguments){t();pop(e);return}var i;if(!this.name&&(i=e.parent())instanceof ze&&i.expression===this&&!i.args.some((e=>e instanceof ae))&&this.argnames.every((e=>e instanceof gt))){this.argnames.forEach(((t,n)=>{if(!t.definition)return;var r=t.definition();if(r.orig.length>1)return;if(r.fixed===undefined&&(!this.uses_arguments||e.has_directive("use strict"))){r.fixed=function(){return i.args[n]||make_node($t,i)};e.loop_ids.set(r.id,e.in_loop);mark(e,r,true)}else{r.fixed=false}}))}t();pop(e);return true}e(oe,mark_lambda);e(Z,(function(e,t,n){reset_block_variables(n,this);const i=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);if(has_break_or_continue(this)){pop(e);push(e)}this.condition.walk(e);pop(e);e.in_loop=i;return true}));e(J,(function(e,t,n){reset_block_variables(n,this);if(this.init)this.init.walk(e);const i=e.in_loop;e.in_loop=this;push(e);if(this.condition)this.condition.walk(e);this.body.walk(e);if(this.step){if(has_break_or_continue(this)){pop(e);push(e)}this.step.walk(e)}pop(e);e.in_loop=i;return true}));e(ee,(function(e,t,n){reset_block_variables(n,this);suppress(this.init);this.object.walk(e);const i=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);pop(e);e.in_loop=i;return true}));e(Ae,(function(e){this.condition.walk(e);push(e);this.body.walk(e);pop(e);if(this.alternative){push(e);this.alternative.walk(e);pop(e)}return true}));e(Y,(function(e){push(e);this.body.walk(e);pop(e);return true}));e(Ft,(function(){this.definition().fixed=false}));e(Pt,(function(e,t,n){var i=this.definition();i.references.push(this);if(i.references.length==1&&!i.fixed&&i.orig[0]instanceof Tt){e.loop_ids.set(i.id,e.in_loop)}var r;if(i.fixed===undefined||!safe_to_read(e,i)){i.fixed=false}else if(i.fixed){r=this.fixed_value();if(r instanceof oe&&recursive_ref(e,i)){i.recursive_refs++}else if(r&&!n.exposed(i)&&ref_once(e,n,i)){i.single_use=r instanceof oe&&!r.pinned()||r instanceof _t||i.scope===this.scope&&r.is_constant_expression()}else{i.single_use=false}if(is_modified(n,e,this,r,0,is_immutable(r))){if(i.single_use){i.single_use="m"}else{i.fixed=false}}}mark_escaped(e,i,this.scope,this,r,0,1)}));e(re,(function(e,t,n){this.globals.forEach((function(e){reset_def(n,e)}));reset_variables(e,n,this)}));e(Re,(function(e,t,n){reset_block_variables(n,this);push(e);walk_body(this,e);pop(e);if(this.bcatch){push(e);this.bcatch.walk(e);pop(e)}if(this.bfinally)this.bfinally.walk(e);return true}));e(je,(function(e){var t=this;if(t.operator!=="++"&&t.operator!=="--")return;var n=t.expression;if(!(n instanceof Pt))return;var i=n.definition();var r=safe_to_assign(e,i,n.scope,true);i.assignments++;if(!r)return;var a=i.fixed;if(!a)return;i.references.push(n);i.chained=true;i.fixed=function(){return make_node(Qe,t,{operator:t.operator.slice(0,-1),left:make_node($e,t,{operator:"+",expression:a instanceof V?a:a()}),right:make_node(Ht,t,{value:1})})};mark(e,i,true);return true}));e(Pe,(function(e,t){var n=this;if(n.name instanceof fe){suppress(n.name);return}var i=n.name.definition();if(n.value){if(safe_to_assign(e,i,n.name.scope,n.value)){i.fixed=function(){return n.value};e.loop_ids.set(i.id,e.in_loop);mark(e,i,false);t();mark(e,i,true);return true}else{i.fixed=false}}}));e(Q,(function(e,t,n){reset_block_variables(n,this);const i=e.in_loop;e.in_loop=this;push(e);t();pop(e);e.in_loop=i;return true}))})((function(e,t){e.DEFMETHOD("reduce_vars",t)}));re.DEFMETHOD("reset_opt_flags",(function(e){const t=this;const n=e.option("reduce_vars");const i=new TreeWalker((function(r,a){clear_flag(r,Cn);if(n){if(e.top_retain&&r instanceof ce&&i.parent()===t){set_flag(r,xn)}return r.reduce_vars(i,a,e)}}));i.safe_ids=Object.create(null);i.in_loop=null;i.loop_ids=new Map;i.defs_to_safe_ids=new Map;t.walk(i)}));gt.DEFMETHOD("fixed_value",(function(){var e=this.thedef.fixed;if(!e||e instanceof V)return e;return e()}));Pt.DEFMETHOD("is_immutable",(function(){var e=this.definition().orig;return e.length==1&&e[0]instanceof Rt}));function is_func_expr(e){return e instanceof le||e instanceof ue}function is_lhs_read_only(e){if(e instanceof Ut)return true;if(e instanceof Pt)return e.definition().orig[0]instanceof Rt;if(e instanceof He){e=e.expression;if(e instanceof Pt){if(e.is_immutable())return false;e=e.fixed_value()}if(!e)return true;if(e instanceof Wt)return false;if(e instanceof Kt)return true;return is_lhs_read_only(e)}return false}function is_ref_of(e,t){if(!(e instanceof Pt))return false;var n=e.definition().orig;for(var i=n.length;--i>=0;){if(n[i]instanceof t)return true}}function find_scope(e){for(let t=0;;t++){const n=e.parent(t);if(n instanceof re)return n;if(n instanceof oe)return n;if(n.block_scope)return n.block_scope}}function find_variable(e,t){var n,i=0;while(n=e.parent(i++)){if(n instanceof ie)break;if(n instanceof we&&n.argname){n=n.argname.definition().scope;break}}return n.find_variable(t)}function make_sequence(e,t){if(t.length==1)return t[0];if(t.length==0)throw new Error("trying to create a sequence with length zero!");return make_node(Ge,e,{expressions:t.reduce(merge_sequence,[])})}function make_node_from_constant(e,t){switch(typeof e){case"string":return make_node(Gt,t,{value:e});case"number":if(isNaN(e))return make_node(jt,t);if(isFinite(e)){return 1/e<0?make_node($e,t,{operator:"-",expression:make_node(Ht,t,{value:-e})}):make_node(Ht,t,{value:e})}return e<0?make_node($e,t,{operator:"-",expression:make_node(Qt,t)}):make_node(Qt,t);case"boolean":return make_node(e?tn:en,t);case"undefined":return make_node($t,t);default:if(e===null){return make_node(Yt,t,{value:null})}if(e instanceof RegExp){return make_node(Wt,t,{value:{source:regexp_source_fix(e.source),flags:e.flags}})}throw new Error(string_template("Can't handle constant of type: {type}",{type:typeof e}))}}function maintain_this_binding(e,t,n){if(e instanceof $e&&e.operator=="delete"||e instanceof ze&&e.expression===t&&(n instanceof He||n instanceof Pt&&n.name=="eval")){return make_sequence(t,[make_node(Ht,t,{value:0}),n])}return n}function merge_sequence(e,t){if(t instanceof Ge){e.push(...t.expressions)}else{e.push(t)}return e}function as_statement_array(e){if(e===null)return[];if(e instanceof X)return e.body;if(e instanceof W)return[];if(e instanceof U)return[e];throw new Error("Can't convert thing to statement array")}function is_empty(e){if(e===null)return true;if(e instanceof W)return true;if(e instanceof X)return e.body.length==0;return false}function can_be_evicted_from_block(e){return!(e instanceof mt||e instanceof ce||e instanceof Me||e instanceof Ie||e instanceof Ue||e instanceof Be)}function loop_body(e){if(e instanceof j){return e.body instanceof X?e.body:e}return e}function is_iife_call(e){if(e.TYPE!="Call")return false;return e.expression instanceof ue||is_iife_call(e.expression)}function is_undeclared_ref(e){return e instanceof Pt&&e.definition().undeclared}var Rn=makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");Pt.DEFMETHOD("is_declared",(function(e){return!this.definition().undeclared||e.option("unsafe")&&Rn.has(this.name)}));var wn=makePredicate("Infinity NaN undefined");function is_identifier_atom(e){return e instanceof Qt||e instanceof jt||e instanceof $t}function tighten_body(e,t){var n,i;var a=t.find_parent(ie).get_defun_scope();find_loop_scope_try();var o,s=10;do{o=false;eliminate_spurious_blocks(e);if(t.option("dead_code")){eliminate_dead_code(e,t)}if(t.option("if_return")){handle_if_return(e,t)}if(t.sequences_limit>0){sequencesize(e,t);sequencesize_2(e,t)}if(t.option("join_vars")){join_consecutive_vars(e)}if(t.option("collapse_vars")){collapse(e,t)}}while(o&&s-- >0);function find_loop_scope_try(){var e=t.self(),r=0;do{if(e instanceof we||e instanceof Oe){r++}else if(e instanceof j){n=true}else if(e instanceof ie){a=e;break}else if(e instanceof Re){i=true}}while(e=t.parent(r++))}function collapse(e,t){if(a.pinned())return e;var s;var u=[];var l=e.length;var c=new TreeTransformer((function(e){if(T)return e;if(!k){if(e!==p[_])return e;_++;if(_1)||e instanceof j&&!(e instanceof J)||e instanceof ve||e instanceof Re||e instanceof ne||e instanceof Se||e instanceof Ue||e instanceof _t||n instanceof J&&e!==n.init||!y&&(e instanceof Pt&&!e.is_declared(t)&&!Ln.has(e))||e instanceof Pt&&n instanceof ze&&has_annotation(n,on)){T=true;return e}if(!E&&(!b||!y)&&(n instanceof Qe&&On.has(n.operator)&&n.left!==e||n instanceof Je&&n.condition!==e||n instanceof Ae&&n.condition!==e)){E=n}if(C&&!(e instanceof bt)&&g.equivalent_to(e)){if(E){T=true;return e}if(is_lhs(e,n)){if(h)x++;return e}else{x++;if(h&&d instanceof Pe)return e}o=T=true;if(d instanceof Ze){return make_node($e,d,d)}if(d instanceof Pe){var r=d.name.definition();var a=d.value;if(r.references.length-r.replaced==1&&!t.exposed(r)){r.replaced++;if(A&&is_identifier_atom(a)){return a.transform(t)}else{return maintain_this_binding(n,e,a)}}return make_node(et,d,{operator:"=",logical:false,left:make_node(Pt,d.name,d.name),right:a})}clear_flag(d,An);return d}var s;if(e instanceof ze||e instanceof me&&(D||g instanceof He||may_modify(g))||e instanceof He&&(D||e.expression.may_throw_on_access(t))||e instanceof Pt&&(v.get(e.name)||D&&may_modify(e))||e instanceof Pe&&e.value&&(v.has(e.name.name)||D&&may_modify(e.name))||(s=is_lhs(e.left,e))&&(s instanceof He||v.has(s.name))||S&&(i?e.has_side_effects(t):side_effects_external(e))){m=e;if(e instanceof ie)T=true}return handle_custom_scan_order(e)}),(function(e){if(T)return;if(m===e)T=true;if(E===e)E=null}));var f=new TreeTransformer((function(e){if(T)return e;if(!k){if(e!==p[_])return e;_++;if(_=0){if(l==0&&t.option("unused"))extract_args();var p=[];extract_candidates(e[l]);while(u.length>0){p=u.pop();var _=0;var d=p[p.length-1];var h=null;var m=null;var E=null;var g=get_lhs(d);if(!g||is_lhs_read_only(g)||g.has_side_effects(t))continue;var v=get_lvalues(d);var b=is_lhs_local(g);if(g instanceof Pt)v.set(g.name,false);var D=value_has_side_effects(d);var y=replace_all_symbols();var S=d.may_throw(t);var A=d.name instanceof kt;var k=A;var T=false,x=0,C=!s||!k;if(!C){for(var R=t.self().argnames.lastIndexOf(d.name)+1;!T&&Rx)x=false;else{T=false;_=0;k=A;for(var w=l;!T&&w!(e instanceof ae)))){var i=t.has_directive("use strict");if(i&&!member(i,n.body))i=false;var r=n.argnames.length;s=e.args.slice(r);var a=new Set;for(var o=r;--o>=0;){var l=n.argnames[o];var c=e.args[o];const r=l.definition&&l.definition();const p=r&&r.orig.length>1;if(p)continue;s.unshift(make_node(Pe,l,{name:l,value:c}));if(a.has(l.name))continue;a.add(l.name);if(l instanceof ae){var f=e.args.slice(o);if(f.every((e=>!has_overlapping_symbol(n,e,i)))){u.unshift([make_node(Pe,l,{name:l.expression,value:make_node(nt,e,{elements:f})})])}}else{if(!c){c=make_node($t,l).transform(t)}else if(c instanceof oe&&c.pinned()||has_overlapping_symbol(n,c,i)){c=null}if(c)u.unshift([make_node(Pe,l,{name:l,value:c})])}}}}function extract_candidates(e){p.push(e);if(e instanceof et){if(!e.left.has_side_effects(t)&&!(e.right instanceof Ye)){u.push(p.slice())}extract_candidates(e.right)}else if(e instanceof Qe){extract_candidates(e.left);extract_candidates(e.right)}else if(e instanceof ze&&!has_annotation(e,on)){extract_candidates(e.expression);e.args.forEach(extract_candidates)}else if(e instanceof Ce){extract_candidates(e.expression)}else if(e instanceof Je){extract_candidates(e.condition);extract_candidates(e.consequent);extract_candidates(e.alternative)}else if(e instanceof Fe){var n=e.definitions.length;var i=n-200;if(i<0)i=0;for(;i1&&!(e.name instanceof kt)||(i>1?mangleable_var(e):!t.exposed(n))){return make_node(Pt,e.name,e.name)}}else{const t=e instanceof et?e.left:e.expression;return!is_ref_of(t,St)&&!is_ref_of(t,At)&&t}}function get_rvalue(e){if(e instanceof et){return e.right}else{return e.value}}function get_lvalues(e){var n=new Map;if(e instanceof je)return n;var i=new TreeWalker((function(e){var r=e;while(r instanceof He)r=r.expression;if(r instanceof Pt||r instanceof Ut){n.set(r.name,n.get(r.name)||is_modified(t,i,e,e,0))}}));get_rvalue(e).walk(i);return n}function remove_candidate(n){if(n.name instanceof kt){var i=t.parent(),a=t.self().argnames;var o=a.indexOf(n.name);if(o<0){i.args.length=Math.min(i.args.length,a.length-1)}else{var s=i.args;if(s[o])s[o]=make_node(Ht,s[o],{value:0})}return true}var u=false;return e[l].transform(new TreeTransformer((function(e,t,i){if(u)return e;if(e===n||e.body===n){u=true;if(e instanceof Pe){e.value=e.name instanceof St?make_node($t,e.value):null;return e}return i?r.skip:null}}),(function(e){if(e instanceof Ge)switch(e.expressions.length){case 0:return null;case 1:return e.expressions[0]}})))}function is_lhs_local(e){while(e instanceof He)e=e.expression;return e instanceof Pt&&e.definition().scope===a&&!(n&&(v.has(e.name)||d instanceof je||d instanceof et&&!d.logical&&d.operator!="="))}function value_has_side_effects(e){if(e instanceof je)return Fn.has(e.operator);return get_rvalue(e).has_side_effects(t)}function replace_all_symbols(){if(D)return false;if(h)return true;if(g instanceof Pt){var e=g.definition();if(e.references.length-e.replaced==(d instanceof Pe?1:2)){return true}}return false}function may_modify(e){if(!e.definition)return true;var t=e.definition();if(t.orig.length==1&&t.orig[0]instanceof Tt)return false;if(t.scope.get_defun_scope()!==a)return true;return!t.references.every((e=>{var t=e.scope.get_defun_scope();if(t.TYPE=="Scope")t=t.parent_scope;return t===a}))}function side_effects_external(e,t){if(e instanceof et)return side_effects_external(e.left,true);if(e instanceof je)return side_effects_external(e.expression,true);if(e instanceof Pe)return e.value&&side_effects_external(e.value);if(t){if(e instanceof Xe)return side_effects_external(e.expression,true);if(e instanceof qe)return side_effects_external(e.expression,true);if(e instanceof Pt)return e.definition().scope!==a}return false}}function eliminate_spurious_blocks(e){var t=[];for(var n=0;n=0;){var s=e[a];var u=next_index(a);var l=e[u];if(r&&!l&&s instanceof Ee){if(!s.value){o=true;e.splice(a,1);continue}if(s.value instanceof $e&&s.value.operator=="void"){o=true;e[a]=make_node(G,s,{body:s.value.expression});continue}}if(s instanceof Ae){var c=aborts(s.body);if(can_merge_flow(c)){if(c.label){remove(c.label.thedef.references,c)}o=true;s=s.clone();s.condition=s.condition.negate(t);var f=as_statement_array_with_return(s.body,c);s.body=make_node(X,s,{body:as_statement_array(s.alternative).concat(extract_functions())});s.alternative=make_node(X,s,{body:f});e[a]=s.transform(t);continue}var c=aborts(s.alternative);if(can_merge_flow(c)){if(c.label){remove(c.label.thedef.references,c)}o=true;s=s.clone();s.body=make_node(X,s.body,{body:as_statement_array(s.body).concat(extract_functions())});var f=as_statement_array_with_return(s.alternative,c);s.alternative=make_node(X,s.alternative,{body:f});e[a]=s.transform(t);continue}}if(s instanceof Ae&&s.body instanceof Ee){var p=s.body.value;if(!p&&!s.alternative&&(r&&!l||l instanceof Ee&&!l.value)){o=true;e[a]=make_node(G,s.condition,{body:s.condition});continue}if(p&&!s.alternative&&l instanceof Ee&&l.value){o=true;s=s.clone();s.alternative=l;e[a]=s.transform(t);e.splice(u,1);continue}if(p&&!s.alternative&&(!l&&r&&i||l instanceof Ee)){o=true;s=s.clone();s.alternative=l||make_node(Ee,s,{value:null});e[a]=s.transform(t);if(l)e.splice(u,1);continue}var _=e[prev_index(a)];if(t.option("sequences")&&r&&!s.alternative&&_ instanceof Ae&&_.body instanceof Ee&&next_index(u)==e.length&&l instanceof G){o=true;s=s.clone();s.alternative=make_node(X,l,{body:[l,make_node(Ee,l,{value:null})]});e[a]=s.transform(t);e.splice(u,1);continue}}}function has_multiple_if_returns(e){var t=0;for(var n=e.length;--n>=0;){var i=e[n];if(i instanceof Ae&&i.body instanceof Ee){if(++t>1)return true}}return false}function is_return_void(e){return!e||e instanceof $e&&e.operator=="void"}function can_merge_flow(i){if(!i)return false;for(var o=a+1,s=e.length;o=0;){var i=e[n];if(!(i instanceof Ne&&declarations_only(i))){break}}return n}}function eliminate_dead_code(e,t){var n;var i=t.self();for(var r=0,a=0,s=e.length;r!e.value))}function sequencesize(e,t){if(e.length<2)return;var n=[],i=0;function push_seq(){if(!n.length)return;var t=make_sequence(n[0],n);e[i++]=make_node(G,t,{body:t});n=[]}for(var r=0,a=e.length;r=t.sequences_limit)push_seq();var u=s.body;if(n.length>0)u=u.drop_side_effect_free(t);if(u)merge_sequence(n,u)}else if(s instanceof Fe&&declarations_only(s)||s instanceof ce){e[i++]=s}else{push_seq();e[i++]=s}}push_seq();e.length=i;if(i!=a)o=true}function to_simple_statement(e,t){if(!(e instanceof X))return e;var n=null;for(var i=0,r=e.body.length;i{if(e instanceof ie)return true;if(e instanceof Qe&&e.operator==="in"){return nn}}));if(!e){if(a.init)a.init=cons_seq(a.init);else{a.init=i.body;n--;o=true}}}}else if(a instanceof ee){if(!(a.init instanceof Ie)&&!(a.init instanceof Me)){a.object=cons_seq(a.object)}}else if(a instanceof Ae){a.condition=cons_seq(a.condition)}else if(a instanceof ke){a.expression=cons_seq(a.expression)}else if(a instanceof ne){a.expression=cons_seq(a.expression)}}if(t.option("conditionals")&&a instanceof Ae){var s=[];var u=to_simple_statement(a.body,s);var l=to_simple_statement(a.alternative,s);if(u!==false&&l!==false&&s.length>0){var c=s.length;s.push(make_node(Ae,a,{condition:a.condition,body:u||make_node(W,a.body),alternative:l}));s.unshift(n,1);[].splice.apply(e,s);r+=c;n+=c+1;i=null;o=true;continue}}e[n++]=a;i=a instanceof G?a:null}e.length=n}function join_object_assignments(e,n){if(!(e instanceof Fe))return;var i=e.definitions[e.definitions.length-1];if(!(i.value instanceof it))return;var r;if(n instanceof et&&!n.logical){r=[n]}else if(n instanceof Ge){r=n.expressions.slice()}if(!r)return;var o=false;do{var s=r[0];if(!(s instanceof et))break;if(s.operator!="=")break;if(!(s.left instanceof He))break;var u=s.left.expression;if(!(u instanceof Pt))break;if(i.name.name!=u.name)break;if(!s.right.is_constant_expression(a))break;var l=s.left.property;if(l instanceof V){l=l.evaluate(t)}if(l instanceof V)break;l=""+l;var c=t.option("ecma")<2015&&t.has_directive("use strict")?function(e){return e.key!=l&&(e.key&&e.key.name!=l)}:function(e){return e.key&&e.key.name!=l};if(!i.value.properties.every(c))break;var f=i.value.properties.filter((function(e){return e.key===l}))[0];if(!f){i.value.properties.push(make_node(ot,s,{key:l,value:s.right}))}else{f.value=new Ge({start:f.start,expressions:[f.value.clone(),s.right.clone()],end:f.end})}r.shift();o=true}while(r.length);return o&&r}function join_consecutive_vars(e){var t;for(var n=0,i=-1,r=e.length;n{if(i instanceof Ne){i.remove_initializers();n.push(i);return true}if(i instanceof ce&&(i===t||!e.has_directive("use strict"))){n.push(i===t?i:make_node(Ne,i,{definitions:[make_node(Pe,i,{name:make_node(Dt,i.name,i.name),value:null})]}));return true}if(i instanceof Ue||i instanceof Be){n.push(i);return true}if(i instanceof ie){return true}}))}function get_value(e){if(e instanceof Kt){return e.getValue()}if(e instanceof $e&&e.operator=="void"&&e.expression instanceof Kt){return}return e}function is_undefined(e,t){return has_flag(e,yn)||e instanceof $t||e instanceof $e&&e.operator=="void"&&!e.expression.has_side_effects(t)}(function(e){V.DEFMETHOD("may_throw_on_access",(function(e){return!e.option("pure_getters")||this._dot_throw(e)}));function is_strict(e){return/strict/.test(e.option("pure_getters"))}e(V,is_strict);e(Yt,return_true);e($t,return_true);e(Kt,return_false);e(nt,return_false);e(it,(function(e){if(!is_strict(e))return false;for(var t=this.properties.length;--t>=0;)if(this.properties[t]._dot_throw(e))return true;return false}));e(_t,return_false);e(rt,return_false);e(ct,return_true);e(ae,(function(e){return this.expression._dot_throw(e)}));e(ue,return_false);e(le,return_false);e(Ze,return_false);e($e,(function(){return this.operator=="void"}));e(Qe,(function(e){return(this.operator=="&&"||this.operator=="||"||this.operator=="??")&&(this.left._dot_throw(e)||this.right._dot_throw(e))}));e(et,(function(e){if(this.logical)return true;return this.operator=="="&&this.right._dot_throw(e)}));e(Je,(function(e){return this.consequent._dot_throw(e)||this.alternative._dot_throw(e)}));e(Xe,(function(e){if(!is_strict(e))return false;if(this.property=="prototype"){return!(this.expression instanceof ue||this.expression instanceof _t)}return true}));e(Ye,(function(e){return this.expression._dot_throw(e)}));e(Ge,(function(e){return this.tail_node()._dot_throw(e)}));e(Pt,(function(e){if(this.name==="arguments")return false;if(has_flag(this,yn))return true;if(!is_strict(e))return false;if(is_undeclared_ref(this)&&this.is_declared(e))return false;if(this.is_immutable())return false;var t=this.fixed_value();return!t||t._dot_throw(e)}))})((function(e,t){e.DEFMETHOD("_dot_throw",t)}));(function(e){const t=makePredicate("! delete");const n=makePredicate("in instanceof == != === !== < <= >= >");e(V,return_false);e($e,(function(){return t.has(this.operator)}));e(Qe,(function(){return n.has(this.operator)||On.has(this.operator)&&this.left.is_boolean()&&this.right.is_boolean()}));e(Je,(function(){return this.consequent.is_boolean()&&this.alternative.is_boolean()}));e(et,(function(){return this.operator=="="&&this.right.is_boolean()}));e(Ge,(function(){return this.tail_node().is_boolean()}));e(tn,return_true);e(en,return_true)})((function(e,t){e.DEFMETHOD("is_boolean",t)}));(function(e){e(V,return_false);e(Ht,return_true);var t=makePredicate("+ - ~ ++ --");e(je,(function(){return t.has(this.operator)}));var n=makePredicate("- * / % & | ^ << >> >>>");e(Qe,(function(e){return n.has(this.operator)||this.operator=="+"&&this.left.is_number(e)&&this.right.is_number(e)}));e(et,(function(e){return n.has(this.operator.slice(0,-1))||this.operator=="="&&this.right.is_number(e)}));e(Ge,(function(e){return this.tail_node().is_number(e)}));e(Je,(function(e){return this.consequent.is_number(e)&&this.alternative.is_number(e)}))})((function(e,t){e.DEFMETHOD("is_number",t)}));(function(e){e(V,return_false);e(Gt,return_true);e(_e,return_true);e($e,(function(){return this.operator=="typeof"}));e(Qe,(function(e){return this.operator=="+"&&(this.left.is_string(e)||this.right.is_string(e))}));e(et,(function(e){return(this.operator=="="||this.operator=="+=")&&this.right.is_string(e)}));e(Ge,(function(e){return this.tail_node().is_string(e)}));e(Je,(function(e){return this.consequent.is_string(e)&&this.alternative.is_string(e)}))})((function(e,t){e.DEFMETHOD("is_string",t)}));var On=makePredicate("&& || ??");var Fn=makePredicate("delete ++ --");function is_lhs(e,t){if(t instanceof je&&Fn.has(t.operator))return t.expression;if(t instanceof et&&t.left===e)return e}(function(e){function to_node(e,t){if(e instanceof V)return make_node(e.CTOR,t,e);if(Array.isArray(e))return make_node(nt,t,{elements:e.map((function(e){return to_node(e,t)}))});if(e&&typeof e=="object"){var n=[];for(var i in e)if(HOP(e,i)){n.push(make_node(ot,t,{key:i,value:to_node(e[i],t)}))}return make_node(it,t,{properties:n})}return make_node_from_constant(e,t)}re.DEFMETHOD("resolve_defines",(function(e){if(!e.option("global_defs"))return this;this.figure_out_scope({ie8:e.option("ie8")});return this.transform(new TreeTransformer((function(t){var n=t._find_defs(e,"");if(!n)return;var i=0,r=t,a;while(a=this.parent(i++)){if(!(a instanceof He))break;if(a.expression!==r)break;r=a}if(is_lhs(r,a)){return}return n})))}));e(V,noop);e(Ye,(function(e,t){return this.expression._find_defs(e,t)}));e(Xe,(function(e,t){return this.expression._find_defs(e,"."+this.property+t)}));e(bt,(function(){if(!this.global())return}));e(Pt,(function(e,t){if(!this.global())return;var n=e.option("global_defs");var i=this.name+t;if(HOP(n,i))return to_node(n[i],this)}))})((function(e,t){e.DEFMETHOD("_find_defs",t)}));function best_of_expression(e,t){return e.size()>t.size()?t:e}function best_of_statement(e,t){return best_of_expression(make_node(G,e,{body:e}),make_node(G,t,{body:t})).body}function best_of(e,t,n){return(first_in_statement(e)?best_of_statement:best_of_expression)(t,n)}function convert_to_predicate(e){const t=new Map;for(var n of Object.keys(e)){t.set(n,makePredicate(e[n]))}return t}var Nn=["constructor","toString","valueOf"];var Mn=convert_to_predicate({Array:["indexOf","join","lastIndexOf","slice"].concat(Nn),Boolean:Nn,Function:Nn,Number:["toExponential","toFixed","toPrecision"].concat(Nn),Object:Nn,RegExp:["test"].concat(Nn),String:["charAt","charCodeAt","concat","indexOf","italics","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","trim"].concat(Nn)});var In=convert_to_predicate({Array:["isArray"],Math:["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","atan2","pow","max","min"],Number:["isFinite","isNaN"],Object:["create","getOwnPropertyDescriptor","getOwnPropertyNames","getPrototypeOf","isExtensible","isFrozen","isSealed","keys"],String:["fromCharCode"]});(function(e){V.DEFMETHOD("evaluate",(function(e){if(!e.option("evaluate"))return this;var t=this._eval(e,1);if(!t||t instanceof RegExp)return t;if(typeof t=="function"||typeof t=="object")return this;return t}));var t=makePredicate("! ~ - + void");V.DEFMETHOD("is_constant",(function(){if(this instanceof Kt){return!(this instanceof Wt)}else{return this instanceof $e&&this.expression instanceof Kt&&t.has(this.operator)}}));e(U,(function(){throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]",this.start))}));e(oe,return_this);e(_t,return_this);e(V,return_this);e(Kt,(function(){return this.getValue()}));e(Xt,return_this);e(Wt,(function(e){let t=e.evaluated_regexps.get(this);if(t===undefined){try{t=(0,eval)(this.print_to_string())}catch(e){t=null}e.evaluated_regexps.set(this,t)}return t||this}));e(_e,(function(){if(this.segments.length!==1)return this;return this.segments[0].value}));e(ue,(function(e){if(e.option("unsafe")){var fn=function(){};fn.node=this;fn.toString=()=>this.print_to_string();return fn}return this}));e(nt,(function(e,t){if(e.option("unsafe")){var n=[];for(var i=0,r=this.elements.length;itypeof e==="object"||typeof e==="function"||typeof e==="symbol";e(Qe,(function(e,t){if(!i.has(this.operator))t++;var n=this.left._eval(e,t);if(n===this.left)return this;var a=this.right._eval(e,t);if(a===this.right)return this;var o;if(n!=null&&a!=null&&r.has(this.operator)&&has_identity(n)&&has_identity(a)&&typeof n===typeof a){return this}switch(this.operator){case"&&":o=n&&a;break;case"||":o=n||a;break;case"??":o=n!=null?n:a;break;case"|":o=n|a;break;case"&":o=n&a;break;case"^":o=n^a;break;case"+":o=n+a;break;case"*":o=n*a;break;case"**":o=Math.pow(n,a);break;case"/":o=n/a;break;case"%":o=n%a;break;case"-":o=n-a;break;case"<<":o=n<>":o=n>>a;break;case">>>":o=n>>>a;break;case"==":o=n==a;break;case"===":o=n===a;break;case"!=":o=n!=a;break;case"!==":o=n!==a;break;case"<":o=n":o=n>a;break;case">=":o=n>=a;break;default:return this}if(isNaN(o)&&e.find_parent(ne)){return this}return o}));e(Je,(function(e,t){var n=this.condition._eval(e,t);if(n===this.condition)return this;var i=n?this.consequent:this.alternative;var r=i._eval(e,t);return r===i?this:r}));const a=new Set;e(Pt,(function(e,t){if(a.has(this))return this;var n=this.fixed_value();if(!n)return this;a.add(this);const i=n._eval(e,t);a.delete(this);if(i===n)return this;if(i&&typeof i=="object"){var r=this.definition().escaped;if(r&&t>r)return this}return i}));var o={Array:Array,Math:Math,Number:Number,Object:Object,String:String};var s=convert_to_predicate({Math:["E","LN10","LN2","LOG2E","LOG10E","PI","SQRT1_2","SQRT2"],Number:["MAX_VALUE","MIN_VALUE","NaN","NEGATIVE_INFINITY","POSITIVE_INFINITY"]});const u=new Set(["dotAll","global","ignoreCase","multiline","sticky","unicode"]);e(He,(function(e,t){if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")){var n=this.property;if(n instanceof V){n=n._eval(e,t);if(n===this.property)return this}var i=this.expression;var r;if(is_undeclared_ref(i)){var a;var l=i.name==="hasOwnProperty"&&n==="call"&&(a=e.parent()&&e.parent().args)&&(a&&a[0]&&a[0].evaluate(e));l=l instanceof Xe?l.expression:l;if(l==null||l.thedef&&l.thedef.undeclared){return this.clone()}var c=s.get(i.name);if(!c||!c.has(n))return this;r=o[i.name]}else{r=i._eval(e,t+1);if(r instanceof RegExp){if(n=="source"){return regexp_source_fix(r.source)}else if(n=="flags"||u.has(n)){return r[n]}}if(!r||r===i||!HOP(r,n))return this;if(typeof r=="function")switch(n){case"name":return r.node.name?r.node.name.name:"";case"length":return r.node.length_property();default:return this}}return r[n]}return this}));e(Ye,(function(e,t){const n=this.expression._eval(e,t);return n===this.expression?this:n}));e(ze,(function(e,t){var n=this.expression;if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")&&n instanceof He){var i=n.property;if(i instanceof V){i=i._eval(e,t);if(i===n.property)return this}var r;var a=n.expression;if(is_undeclared_ref(a)){var s=a.name==="hasOwnProperty"&&i==="call"&&(this.args[0]&&this.args[0].evaluate(e));s=s instanceof Xe?s.expression:s;if(s==null||s.thedef&&s.thedef.undeclared){return this.clone()}var u=In.get(a.name);if(!u||!u.has(i))return this;r=o[a.name]}else{r=a._eval(e,t+1);if(r===a||!r)return this;var l=Mn.get(r.constructor.name);if(!l||!l.has(i))return this}var c=[];for(var f=0,p=this.args.length;f";return n;case"<":n.operator=">=";return n;case">=":n.operator="<";return n;case">":n.operator="<=";return n}}switch(i){case"==":n.operator="!=";return n;case"!=":n.operator="==";return n;case"===":n.operator="!==";return n;case"!==":n.operator="===";return n;case"&&":n.operator="||";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"||":n.operator="&&";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"??":n.right=n.right.negate(e);return best(this,n,t)}return basic_negation(this)}))})((function(e,t){e.DEFMETHOD("negate",(function(e,n){return t.call(this,e,n)}))}));var Pn=makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");ze.DEFMETHOD("is_callee_pure",(function(e){if(e.option("unsafe")){var t=this.expression;var n=this.args&&this.args[0]&&this.args[0].evaluate(e);if(t.expression&&t.expression.name==="hasOwnProperty"&&(n==null||n.thedef&&n.thedef.undeclared)){return false}if(is_undeclared_ref(t)&&Pn.has(t.name))return true;let i;if(t instanceof Xe&&is_undeclared_ref(t.expression)&&(i=In.get(t.expression.name))&&i.has(t.property)){return true}}return!!has_annotation(this,rn)||!e.pure_funcs(this)}));V.DEFMETHOD("is_call_pure",return_false);Xe.DEFMETHOD("is_call_pure",(function(e){if(!e.option("unsafe"))return;const t=this.expression;let n;if(t instanceof nt){n=Mn.get("Array")}else if(t.is_boolean()){n=Mn.get("Boolean")}else if(t.is_number(e)){n=Mn.get("Number")}else if(t instanceof Wt){n=Mn.get("RegExp")}else if(t.is_string(e)){n=Mn.get("String")}else if(!this.may_throw_on_access(e)){n=Mn.get("Object")}return n&&n.has(this.property)}));const Ln=new Set(["Number","String","Array","Object","Function","Promise"]);(function(e){e(V,return_true);e(W,return_false);e(Kt,return_false);e(Ut,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].has_side_effects(t))return true;return false}e(H,(function(e){return any(this.body,e)}));e(ze,(function(e){if(!this.is_callee_pure(e)&&(!this.expression.is_call_pure(e)||this.expression.has_side_effects(e))){return true}return any(this.args,e)}));e(ke,(function(e){return this.expression.has_side_effects(e)||any(this.body,e)}));e(Ce,(function(e){return this.expression.has_side_effects(e)||any(this.body,e)}));e(Re,(function(e){return any(this.body,e)||this.bcatch&&this.bcatch.has_side_effects(e)||this.bfinally&&this.bfinally.has_side_effects(e)}));e(Ae,(function(e){return this.condition.has_side_effects(e)||this.body&&this.body.has_side_effects(e)||this.alternative&&this.alternative.has_side_effects(e)}));e(Y,(function(e){return this.body.has_side_effects(e)}));e(G,(function(e){return this.body.has_side_effects(e)}));e(oe,return_false);e(_t,(function(e){if(this.extends&&this.extends.has_side_effects(e)){return true}return any(this.properties,e)}));e(Qe,(function(e){return this.left.has_side_effects(e)||this.right.has_side_effects(e)}));e(et,return_true);e(Je,(function(e){return this.condition.has_side_effects(e)||this.consequent.has_side_effects(e)||this.alternative.has_side_effects(e)}));e(je,(function(e){return Fn.has(this.operator)||this.expression.has_side_effects(e)}));e(Pt,(function(e){return!this.is_declared(e)&&!Ln.has(this.name)}));e(Ct,return_false);e(bt,return_false);e(it,(function(e){return any(this.properties,e)}));e(rt,(function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.value&&this.value.has_side_effects(e)}));e(dt,(function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.static&&this.value&&this.value.has_side_effects(e)}));e(ft,(function(e){return this.computed_key()&&this.key.has_side_effects(e)}));e(ct,(function(e){return this.computed_key()&&this.key.has_side_effects(e)}));e(lt,(function(e){return this.computed_key()&&this.key.has_side_effects(e)}));e(nt,(function(e){return any(this.elements,e)}));e(Xe,(function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)}));e(qe,(function(e){if(this.optional&&is_nullish(this.expression,e)){return false}return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)||this.property.has_side_effects(e)}));e(Ye,(function(e){return this.expression.has_side_effects(e)}));e(Ge,(function(e){return any(this.expressions,e)}));e(Fe,(function(e){return any(this.definitions,e)}));e(Pe,(function(){return this.value}));e(de,return_false);e(_e,(function(e){return any(this.segments,e)}))})((function(e,t){e.DEFMETHOD("has_side_effects",t)}));(function(e){e(V,return_true);e(Kt,return_false);e(W,return_false);e(oe,return_false);e(bt,return_false);e(Ut,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].may_throw(t))return true;return false}e(_t,(function(e){if(this.extends&&this.extends.may_throw(e))return true;return any(this.properties,e)}));e(nt,(function(e){return any(this.elements,e)}));e(et,(function(e){if(this.right.may_throw(e))return true;if(!e.has_directive("use strict")&&this.operator=="="&&this.left instanceof Pt){return false}return this.left.may_throw(e)}));e(Qe,(function(e){return this.left.may_throw(e)||this.right.may_throw(e)}));e(H,(function(e){return any(this.body,e)}));e(ze,(function(e){if(this.optional&&is_nullish(this.expression,e))return false;if(any(this.args,e))return true;if(this.is_callee_pure(e))return false;if(this.expression.may_throw(e))return true;return!(this.expression instanceof oe)||any(this.expression.body,e)}));e(Ce,(function(e){return this.expression.may_throw(e)||any(this.body,e)}));e(Je,(function(e){return this.condition.may_throw(e)||this.consequent.may_throw(e)||this.alternative.may_throw(e)}));e(Fe,(function(e){return any(this.definitions,e)}));e(Ae,(function(e){return this.condition.may_throw(e)||this.body&&this.body.may_throw(e)||this.alternative&&this.alternative.may_throw(e)}));e(Y,(function(e){return this.body.may_throw(e)}));e(it,(function(e){return any(this.properties,e)}));e(rt,(function(e){return this.value?this.value.may_throw(e):false}));e(dt,(function(e){return this.computed_key()&&this.key.may_throw(e)||this.static&&this.value&&this.value.may_throw(e)}));e(ft,(function(e){return this.computed_key()&&this.key.may_throw(e)}));e(ct,(function(e){return this.computed_key()&&this.key.may_throw(e)}));e(lt,(function(e){return this.computed_key()&&this.key.may_throw(e)}));e(Ee,(function(e){return this.value&&this.value.may_throw(e)}));e(Ge,(function(e){return any(this.expressions,e)}));e(G,(function(e){return this.body.may_throw(e)}));e(Xe,(function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)}));e(qe,(function(e){if(this.optional&&is_nullish(this.expression,e))return false;return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)||this.property.may_throw(e)}));e(Ye,(function(e){return this.expression.may_throw(e)}));e(ke,(function(e){return this.expression.may_throw(e)||any(this.body,e)}));e(Pt,(function(e){return!this.is_declared(e)&&!Ln.has(this.name)}));e(Ct,return_false);e(Re,(function(e){return this.bcatch?this.bcatch.may_throw(e):any(this.body,e)||this.bfinally&&this.bfinally.may_throw(e)}));e(je,(function(e){if(this.operator=="typeof"&&this.expression instanceof Pt)return false;return this.expression.may_throw(e)}));e(Pe,(function(e){if(!this.value)return false;return this.value.may_throw(e)}))})((function(e,t){e.DEFMETHOD("may_throw",t)}));(function(e){function all_refs_local(e){let t=true;walk(this,(n=>{if(n instanceof Pt){if(has_flag(this,Sn)){t=false;return nn}var i=n.definition();if(member(i,this.enclosed)&&!this.variables.has(i.name)){if(e){var r=e.find_variable(n);if(i.undeclared?!r:r===i){t="f";return true}}t=false;return nn}return true}if(n instanceof Ut&&this instanceof le){t=false;return nn}}));return t}e(V,return_false);e(Kt,return_true);e(_t,(function(e){if(this.extends&&!this.extends.is_constant_expression(e)){return false}for(const t of this.properties){if(t.computed_key()&&!t.key.is_constant_expression(e)){return false}if(t.static&&t.value&&!t.value.is_constant_expression(e)){return false}}return all_refs_local.call(this,e)}));e(oe,all_refs_local);e(je,(function(){return this.expression.is_constant_expression()}));e(Qe,(function(){return this.left.is_constant_expression()&&this.right.is_constant_expression()}));e(nt,(function(){return this.elements.every((e=>e.is_constant_expression()))}));e(it,(function(){return this.properties.every((e=>e.is_constant_expression()))}));e(rt,(function(){return!!(!(this.key instanceof V)&&this.value&&this.value.is_constant_expression())}))})((function(e,t){e.DEFMETHOD("is_constant_expression",t)}));function aborts(e){return e&&e.aborts()}(function(e){e(U,return_null);e(he,return_this);function block_aborts(){for(var e=0;e{if(e instanceof bt){const n=e.definition();if((t||n.global)&&!o.has(n.id)){o.set(n.id,n)}}}))}if(n.value){if(n.name instanceof fe){n.walk(f)}else{var r=n.name.definition();map_add(l,r.id,n.value);if(!r.chained&&n.name.fixed_value()===n.value){s.set(r.id,n)}}if(n.value.has_side_effects(e)){n.value.walk(f)}}}));return true}return scan_ref_scoped(r,a)}));t.walk(f);f=new TreeWalker(scan_ref_scoped);o.forEach((function(e){var t=l.get(e.id);if(t)t.forEach((function(e){e.walk(f)}))}));var p=new TreeTransformer((function before(l,f,_){var d=p.parent();if(i){const e=a(l);if(e instanceof Pt){var h=e.definition();var m=o.has(h.id);if(l instanceof et){if(!m||s.has(h.id)&&s.get(h.id)!==l){return maintain_this_binding(d,l,l.right.transform(p))}}else if(!m)return _?r.skip:make_node(Ht,l,{value:0})}}if(c!==t)return;var h;if(l.name&&(l instanceof Et&&!keep_name(e.option("keep_classnames"),(h=l.name.definition()).name)||l instanceof ue&&!keep_name(e.option("keep_fnames"),(h=l.name.definition()).name))){if(!o.has(h.id)||h.orig.length>1)l.name=null}if(l instanceof oe&&!(l instanceof se)){var E=!e.option("keep_fargs");for(var g=l.argnames,v=g.length;--v>=0;){var b=g[v];if(b instanceof ae){b=b.expression}if(b instanceof tt){b=b.left}if(!(b instanceof fe)&&!o.has(b.definition().id)){set_flag(b,vn);if(E){g.pop()}}else{E=false}}}if((l instanceof ce||l instanceof mt)&&l!==t){const t=l.name.definition();let i=t.global&&!n||o.has(t.id);if(!i){t.eliminated++;if(l instanceof mt){const t=l.drop_side_effect_free(e);if(t){return make_node(G,l,{body:t})}}return _?r.skip:make_node(W,l)}}if(l instanceof Fe&&!(d instanceof ee&&d.init===l)){var D=!(d instanceof re)&&!(l instanceof Ne);var y=[],S=[],A=[];var k=[];l.definitions.forEach((function(t){if(t.value)t.value=t.value.transform(p);var n=t.name instanceof fe;var r=n?new SymbolDef(null,{name:""}):t.name.definition();if(D&&r.global)return A.push(t);if(!(i||D)||n&&(t.name.names.length||t.name.is_array||e.option("pure_getters")!=true)||o.has(r.id)){if(t.value&&s.has(r.id)&&s.get(r.id)!==t){t.value=t.value.drop_side_effect_free(e)}if(t.name instanceof Dt){var a=u.get(r.id);if(a.length>1&&(!t.value||r.orig.indexOf(t.name)>r.eliminated)){if(t.value){var c=make_node(Pt,t.name,t.name);r.references.push(c);var f=make_node(et,t,{operator:"=",logical:false,left:c,right:t.value});if(s.get(r.id)===t){s.set(r.id,f)}k.push(f.transform(p))}remove(a,t);r.eliminated++;return}}if(t.value){if(k.length>0){if(A.length>0){k.push(t.value);t.value=make_sequence(t.value,k)}else{y.push(make_node(G,l,{body:make_sequence(l,k)}))}k=[]}A.push(t)}else{S.push(t)}}else if(r.orig[0]instanceof Ft){var _=t.value&&t.value.drop_side_effect_free(e);if(_)k.push(_);t.value=null;S.push(t)}else{var _=t.value&&t.value.drop_side_effect_free(e);if(_){k.push(_)}r.eliminated++}}));if(S.length>0||A.length>0){l.definitions=S.concat(A);y.push(l)}if(k.length>0){y.push(make_node(G,l,{body:make_sequence(l,k)}))}switch(y.length){case 0:return _?r.skip:make_node(W,l);case 1:return y[0];default:return _?r.splice(y):make_node(X,l,{body:y})}}if(l instanceof J){f(l,this);var T;if(l.init instanceof X){T=l.init;l.init=T.body.pop();T.body.push(l)}if(l.init instanceof G){l.init=l.init.body}else if(is_empty(l.init)){l.init=null}return!T?l:_?r.splice(T.body):T}if(l instanceof Y&&l.body instanceof J){f(l,this);if(l.body instanceof X){var T=l.body;l.body=T.body.pop();T.body.push(l);return _?r.splice(T.body):T}return l}if(l instanceof X){f(l,this);if(_&&l.body.every(can_be_evicted_from_block)){return r.splice(l.body)}return l}if(l instanceof ie){const e=c;c=l;f(l,this);c=e;return l}}));t.transform(p);function scan_ref_scoped(e,n){var i;const r=a(e);if(r instanceof Pt&&!is_ref_of(e.left,yt)&&t.variables.get(r.name)===(i=r.definition())){if(e instanceof et){e.right.walk(f);if(!i.chained&&e.left.fixed_value()===e.right){s.set(i.id,e)}}return true}if(e instanceof Pt){i=e.definition();if(!o.has(i.id)){o.set(i.id,i);if(i.orig[0]instanceof Ft){const e=i.scope.is_block_scope()&&i.scope.get_defun_scope().variables.get(i.name);if(e)o.set(e.id,e)}}return true}if(e instanceof ie){var u=c;c=e;n();c=u;return true}}}));ie.DEFMETHOD("hoist_declarations",(function(e){var t=this;if(e.has_directive("use asm"))return t;if(!Array.isArray(t.body))return t;var n=e.option("hoist_funs");var i=e.option("hoist_vars");if(n||i){var r=[];var a=[];var o=new Map,s=0,u=0;walk(t,(e=>{if(e instanceof ie&&e!==t)return true;if(e instanceof Ne){++u;return true}}));i=i&&u>1;var l=new TreeTransformer((function before(u){if(u!==t){if(u instanceof K){r.push(u);return make_node(W,u)}if(n&&u instanceof ce&&!(l.parent()instanceof Ue)&&l.parent()===t){a.push(u);return make_node(W,u)}if(i&&u instanceof Ne&&!u.definitions.some((e=>e.name instanceof fe))){u.definitions.forEach((function(e){o.set(e.name.name,e);++s}));var c=u.to_assignments(e);var f=l.parent();if(f instanceof ee&&f.init===u){if(c==null){var p=u.definitions[0].name;return make_node(Pt,p,p)}return c}if(f instanceof J&&f.init===u){return c}if(!c)return make_node(W,u);return make_node(G,u,{body:c})}if(u instanceof ie)return u}}));t=t.transform(l);if(s>0){var c=[];const e=t instanceof oe;const n=e?t.args_as_names():null;o.forEach(((t,i)=>{if(e&&n.some((e=>e.name===t.name.name))){o.delete(i)}else{t=t.clone();t.value=null;c.push(t);o.set(i,t)}}));if(c.length>0){for(var f=0;fe instanceof ae||e.computed_key()))){s(o,this);const e=new Map;const n=[];c.properties.forEach((({key:i,value:r})=>{const s=find_scope(a);const l=t.create_symbol(u.CTOR,{source:u,scope:s,conflict_scopes:new Set([s,...u.definition().references.map((e=>e.scope))]),tentative_name:u.name+"_"+i});e.set(String(i),l.definition());n.push(make_node(Pe,o,{name:l,value:r}))}));i.set(l.id,e);return r.splice(n)}}else if(o instanceof He&&o.expression instanceof Pt){const e=i.get(o.expression.definition().id);if(e){const t=e.get(String(get_value(o.property)));const n=make_node(Pt,o,{name:t.name,scope:o.expression.scope,thedef:t});n.reference({});return n}}}));return t.transform(a)}));(function(e){function trim(e,t,n){var i=e.length;if(!i)return null;var r=[],a=false;for(var o=0;o0){o[0].body=a.concat(o[0].body)}e.body=o;while(n=o[o.length-1]){var d=n.body[n.body.length-1];if(d instanceof be&&t.loopcontrol_target(d)===e)n.body.pop();if(n.body.length||n instanceof Ce&&(s||n.expression.has_side_effects(t)))break;if(o.pop()===s)s=null}if(o.length==0){return make_node(X,e,{body:a.concat(make_node(G,e.expression,{body:e.expression}))}).optimize(t)}if(o.length==1&&(o[0]===u||o[0]===s)){var h=false;var m=new TreeWalker((function(t){if(h||t instanceof oe||t instanceof G)return true;if(t instanceof be&&m.loopcontrol_target(t)===e)h=true}));e.walk(m);if(!h){var E=o[0].body.slice();var f=o[0].expression;if(f)E.unshift(make_node(G,f,{body:f}));E.unshift(make_node(G,e.expression,{body:e.expression}));return make_node(X,e,{body:E}).optimize(t)}}return e;function eliminate_branch(e,n){if(n&&!aborts(n)){n.body=n.body.concat(e.body)}else{trim_unreachable_code(t,e,a)}}}));def_optimize(Re,(function(e,t){tighten_body(e.body,t);if(e.bcatch&&e.bfinally&&e.bfinally.body.every(is_empty))e.bfinally=null;if(t.option("dead_code")&&e.body.every(is_empty)){var n=[];if(e.bcatch){trim_unreachable_code(t,e.bcatch,n)}if(e.bfinally)n.push(...e.bfinally.body);return make_node(X,e,{body:n}).optimize(t)}return e}));Fe.DEFMETHOD("remove_initializers",(function(){var e=[];this.definitions.forEach((function(t){if(t.name instanceof bt){t.value=null;e.push(t)}else{walk(t.name,(n=>{if(n instanceof bt){e.push(make_node(Pe,t,{name:n,value:null}))}}))}}));this.definitions=e}));Fe.DEFMETHOD("to_assignments",(function(e){var t=e.option("reduce_vars");var n=[];for(const e of this.definitions){if(e.value){var i=make_node(Pt,e.name,e.name);n.push(make_node(et,e,{operator:"=",logical:false,left:i,right:e.value}));if(t)i.definition().fixed=false}else if(e.value){var r=make_node(Pe,e,{name:e.name,value:e.value});var a=make_node(Ne,e,{definitions:[r]});n.push(a)}const o=e.name.definition();o.eliminated++;o.replaced--}if(n.length==0)return null;return make_sequence(this,n)}));def_optimize(Fe,(function(e){if(e.definitions.length==0)return make_node(W,e);return e}));def_optimize(Pe,(function(e,t){if(e.name instanceof At&&e.value!=null&&is_undefined(e.value,t)){e.value=null}return e}));def_optimize(Be,(function(e){return e}));function retain_top_func(e,t){return t.top_retain&&e instanceof ce&&has_flag(e,xn)&&e.name&&t.top_retain(e.name)}def_optimize(ze,(function(e,t){var n=e.expression;var i=n;inline_array_like_spread(e.args);var r=e.args.every((e=>!(e instanceof ae)));if(t.option("reduce_vars")&&i instanceof Pt&&!has_annotation(e,on)){const e=i.fixed_value();if(!retain_top_func(e,t)){i=e}}if(e.optional&&is_nullish(i,t)){return make_node($t,e)}var a=i instanceof oe;if(a&&i.pinned())return e;if(t.option("unused")&&r&&a&&!i.uses_arguments){var o=0,s=0;for(var u=0,l=e.args.length;u=i.argnames.length;if(f||has_flag(i.argnames[u],vn)){var c=e.args[u].drop_side_effect_free(t);if(c){e.args[o++]=c}else if(!f){e.args[o++]=make_node(Ht,e.args[u],{value:0});continue}}else{e.args[o++]=e.args[u]}s=o}e.args.length=s}if(t.option("unsafe")){if(is_undeclared_ref(n))switch(n.name){case"Array":if(e.args.length!=1){return make_node(nt,e,{elements:e.args}).optimize(t)}else if(e.args[0]instanceof Ht&&e.args[0].value<=11){const t=[];for(let n=0;n=1&&e.args.length<=2&&e.args.every((e=>{var n=e.evaluate(t);p.push(n);return e!==n}))){let[n,i]=p;n=regexp_source_fix(new RegExp(n).source);const r=make_node(Wt,e,{value:{source:n,flags:i}});if(r._eval(t)!==r){return r}}break}else if(n instanceof Xe)switch(n.property){case"toString":if(e.args.length==0&&!n.expression.may_throw_on_access(t)){return make_node(Qe,e,{left:make_node(Gt,e,{value:""}),operator:"+",right:n.expression}).optimize(t)}break;case"join":if(n.expression instanceof nt)e:{var _;if(e.args.length>0){_=e.args[0].evaluate(t);if(_===e.args[0])break e}var d=[];var h=[];for(var u=0,l=n.expression.elements.length;u0){d.push(make_node(Gt,e,{value:h.join(_)}));h.length=0}d.push(m)}}if(h.length>0){d.push(make_node(Gt,e,{value:h.join(_)}))}if(d.length==0)return make_node(Gt,e,{value:""});if(d.length==1){if(d[0].is_string(t)){return d[0]}return make_node(Qe,d[0],{operator:"+",left:make_node(Gt,e,{value:""}),right:d[0]})}if(_==""){var g;if(d[0].is_string(t)||d[1].is_string(t)){g=d.shift()}else{g=make_node(Gt,e,{value:""})}return d.reduce((function(e,t){return make_node(Qe,t,{operator:"+",left:e,right:t})}),g).optimize(t)}var c=e.clone();c.expression=c.expression.clone();c.expression.expression=c.expression.expression.clone();c.expression.expression.elements=d;return best_of(t,e,c)}break;case"charAt":if(n.expression.is_string(t)){var v=e.args[0];var b=v?v.evaluate(t):0;if(b!==v){return make_node(qe,n,{expression:n.expression,property:make_node_from_constant(b|0,v||n)}).optimize(t)}}break;case"apply":if(e.args.length==2&&e.args[1]instanceof nt){var D=e.args[1].elements.slice();D.unshift(e.args[0]);return make_node(ze,e,{expression:make_node(Xe,n,{expression:n.expression,optional:false,property:"call"}),args:D}).optimize(t)}break;case"call":var y=n.expression;if(y instanceof Pt){y=y.fixed_value()}if(y instanceof oe&&!y.contains_this()){return(e.args.length?make_sequence(this,[e.args[0],make_node(ze,e,{expression:n.expression,args:e.args.slice(1)})]):make_node(ze,e,{expression:n.expression,args:[]})).optimize(t)}break}}if(t.option("unsafe_Function")&&is_undeclared_ref(n)&&n.name=="Function"){if(e.args.length==0)return make_node(ue,e,{argnames:[],body:[]}).optimize(t);if(e.args.every((e=>e instanceof Gt))){try{var S="n(function("+e.args.slice(0,-1).map((function(e){return e.value})).join(",")+"){"+e.args[e.args.length-1].value+"})";var A=parse(S);var k={ie8:t.option("ie8")};A.figure_out_scope(k);var T=new Compressor(t.options,{mangle_options:t.mangle_options});A=A.transform(T);A.figure_out_scope(k);En.reset();A.compute_char_frequency(k);A.mangle_names(k);var x;walk(A,(e=>{if(is_func_expr(e)){x=e;return nn}}));var S=OutputStream();X.prototype._codegen.call(x,x,S);e.args=[make_node(Gt,e,{value:x.argnames.map((function(e){return e.print_to_string()})).join(",")}),make_node(Gt,e.args[e.args.length-1],{value:S.get().replace(/^{|}$/g,"")})];return e}catch(e){if(!(e instanceof JS_Parse_Error)){throw e}}}}var C=a&&i.body[0];var R=a&&!i.is_generator&&!i.async;var w=R&&t.option("inline")&&!e.is_callee_pure(t);if(w&&C instanceof Ee){let n=C.value;if(!n||n.is_constant_expression()){if(n){n=n.clone(true)}else{n=make_node($t,e)}const i=e.args.concat(n);return make_sequence(e,i).optimize(t)}if(i.argnames.length===1&&i.argnames[0]instanceof kt&&e.args.length<2&&n instanceof Pt&&n.name===i.argnames[0].name){const n=(e.args[0]||make_node($t)).optimize(t);let i;if(n instanceof He&&(i=t.parent())instanceof ze&&i.expression===e){return make_sequence(e,[make_node(Ht,e,{value:0}),n])}return n}}if(w){var O,F,N=-1;let a;let o;let s;if(r&&!i.uses_arguments&&!(t.parent()instanceof _t)&&!(i.name&&i instanceof ue)&&(o=can_flatten_body(C))&&(n===i||has_annotation(e,an)||t.option("unused")&&(a=n.definition()).references.length==1&&!recursive_ref(t,a)&&i.is_constant_expression(n.scope))&&!has_annotation(e,rn|on)&&!i.contains_this()&&can_inject_symbols()&&(s=find_scope(t))&&!scope_encloses_variables_in_this_scope(s,i)&&!function in_default_assign(){let e=0;let n;while(n=t.parent(e++)){if(n instanceof tt)return true;if(n instanceof H)break}return false}()&&!(O instanceof _t)){set_flag(i,kn);s.add_child_scope(i);return make_sequence(e,flatten_fn(o)).optimize(t)}}if(w&&has_annotation(e,an)){set_flag(i,kn);i=make_node(i.CTOR===ce?ue:i.CTOR,i,i);i.figure_out_scope({},{parent_scope:find_scope(t),toplevel:t.get_toplevel()});return make_node(ze,e,{expression:i,args:e.args}).optimize(t)}const M=R&&t.option("side_effects")&&i.body.every(is_empty);if(M){var D=e.args.concat(make_node($t,e));return make_sequence(e,D).optimize(t)}if(t.option("negate_iife")&&t.parent()instanceof G&&is_iife_call(e)){return e.negate(t,true)}var I=e.evaluate(t);if(I!==e){I=make_node_from_constant(I,e).optimize(t);return best_of(t,I,e)}return e;function return_value(t){if(!t)return make_node($t,e);if(t instanceof Ee){if(!t.value)return make_node($t,e);return t.value.clone(true)}if(t instanceof G){return make_node($e,t,{operator:"void",expression:t.body.clone(true)})}}function can_flatten_body(e){var n=i.body;var r=n.length;if(t.option("inline")<3){return r==1&&return_value(e)}e=null;for(var a=0;a!e.value))){return false}}else if(e){return false}else if(!(o instanceof W)){e=o}}return return_value(e)}function can_inject_args(e,t){for(var n=0,r=i.argnames.length;n=0;){var s=a.definitions[o].name;if(s instanceof fe||e.has(s.name)||wn.has(s.name)||O.conflicting_def(s.name)){return false}if(F)F.push(s.definition())}}return true}function can_inject_symbols(){var e=new Set;do{O=t.parent(++N);if(O.is_block_scope()&&O.block_scope){O.block_scope.variables.forEach((function(t){e.add(t.name)}))}if(O instanceof we){if(O.argname){e.add(O.argname.name)}}else if(O instanceof j){F=[]}else if(O instanceof Pt){if(O.fixed_value()instanceof ie)return false}}while(!(O instanceof ie));var n=!(O instanceof re)||t.toplevel.vars;var r=t.option("inline");if(!can_inject_vars(e,r>=3&&n))return false;if(!can_inject_args(e,r>=2&&n))return false;return!F||F.length==0||!is_reachable(i,F)}function append_var(t,n,i,r){var a=i.definition();const o=O.variables.has(i.name);if(!o){O.variables.set(i.name,a);O.enclosed.push(a);t.push(make_node(Pe,i,{name:i,value:null}))}var s=make_node(Pt,i,i);a.references.push(s);if(r)n.push(make_node(et,e,{operator:"=",logical:false,left:s,right:r.clone()}))}function flatten_args(t,n){var r=i.argnames.length;for(var a=e.args.length;--a>=r;){n.push(e.args[a])}for(a=r;--a>=0;){var o=i.argnames[a];var s=e.args[a];if(has_flag(o,vn)||!o.name||O.conflicting_def(o.name)){if(s)n.push(s)}else{var u=make_node(Dt,o,o);o.definition().orig.push(u);if(!s&&F)s=make_node($t,e);append_var(t,n,u,s)}}t.reverse();n.reverse()}function flatten_vars(e,t){var n=t.length;for(var r=0,a=i.body.length;re.name!=c.name))){var f=i.variables.get(c.name);var p=make_node(Pt,c,c);f.references.push(p);t.splice(n++,0,make_node(et,l,{operator:"=",logical:false,left:p,right:make_node($t,c)}))}}}}function flatten_fn(e){var n=[];var r=[];flatten_args(n,r);flatten_vars(n,r);r.push(e);if(n.length){const e=O.body.indexOf(t.parent(N-1))+1;O.body.splice(e,0,make_node(Ne,i,{definitions:n}))}return r.map((e=>e.clone(true)))}}));def_optimize(Ke,(function(e,t){if(t.option("unsafe")&&is_undeclared_ref(e.expression)&&["Object","RegExp","Function","Error","Array"].includes(e.expression.name))return make_node(ze,e,e).transform(t);return e}));def_optimize(Ge,(function(e,t){if(!t.option("side_effects"))return e;var n=[];filter_for_side_effects();var i=n.length-1;trim_right_for_undefined();if(i==0){e=maintain_this_binding(t.parent(),t.self(),n[0]);if(!(e instanceof Ge))e=e.optimize(t);return e}e.expressions=n;return e;function filter_for_side_effects(){var i=first_in_statement(t);var r=e.expressions.length-1;e.expressions.forEach((function(e,a){if(a0&&is_undefined(n[i],t))i--;if(i0){var n=this.clone();n.right=make_sequence(this.right,t.slice(a));t=t.slice(0,a);t.push(n);return make_sequence(this,t).optimize(e)}}}return this}));var Un=makePredicate("== === != !== * & | ^");function is_object(e){return e instanceof nt||e instanceof oe||e instanceof it||e instanceof _t}def_optimize(Qe,(function(e,t){function reversible(){return e.left.is_constant()||e.right.is_constant()||!e.left.has_side_effects(t)&&!e.right.has_side_effects(t)}function reverse(t){if(reversible()){if(t)e.operator=t;var n=e.left;e.left=e.right;e.right=n}}if(Un.has(e.operator)){if(e.right.is_constant()&&!e.left.is_constant()){if(!(e.left instanceof Qe&&M[e.left.operator]>=M[e.operator])){reverse()}}}e=e.lift_sequences(t);if(t.option("comparisons"))switch(e.operator){case"===":case"!==":var n=true;if(e.left.is_string(t)&&e.right.is_string(t)||e.left.is_number(t)&&e.right.is_number(t)||e.left.is_boolean()&&e.right.is_boolean()||e.left.equivalent_to(e.right)){e.operator=e.operator.substr(0,2)}case"==":case"!=":if(!n&&is_undefined(e.left,t)){e.left=make_node(Yt,e.left)}else if(t.option("typeofs")&&e.left instanceof Gt&&e.left.value=="undefined"&&e.right instanceof $e&&e.right.operator=="typeof"){var i=e.right.expression;if(i instanceof Pt?i.is_declared(t):!(i instanceof He&&t.option("ie8"))){e.right=i;e.left=make_node($t,e.left).optimize(t);if(e.operator.length==2)e.operator+="="}}else if(e.left instanceof Pt&&e.right instanceof Pt&&e.left.definition()===e.right.definition()&&is_object(e.left.fixed_value())){return make_node(e.operator[0]=="="?tn:en,e)}break;case"&&":case"||":var r=e.left;if(r.operator==e.operator){r=r.right}if(r instanceof Qe&&r.operator==(e.operator=="&&"?"!==":"===")&&e.right instanceof Qe&&r.operator==e.right.operator&&(is_undefined(r.left,t)&&e.right.left instanceof Yt||r.left instanceof Yt&&is_undefined(e.right.left,t))&&!r.right.has_side_effects(t)&&r.right.equivalent_to(e.right.right)){var a=make_node(Qe,e,{operator:r.operator.slice(0,-1),left:make_node(Yt,e),right:r.right});if(r!==e.left){a=make_node(Qe,e,{operator:e.operator,left:e.left.left,right:a})}return a}break}if(e.operator=="+"&&t.in_boolean_context()){var o=e.left.evaluate(t);var s=e.right.evaluate(t);if(o&&typeof o=="string"){return make_sequence(e,[e.right,make_node(tn,e)]).optimize(t)}if(s&&typeof s=="string"){return make_sequence(e,[e.left,make_node(tn,e)]).optimize(t)}}if(t.option("comparisons")&&e.is_boolean()){if(!(t.parent()instanceof Qe)||t.parent()instanceof et){var u=make_node($e,e,{operator:"!",expression:e.negate(t,first_in_statement(t))});e=best_of(t,e,u)}if(t.option("unsafe_comps")){switch(e.operator){case"<":reverse(">");break;case"<=":reverse(">=");break}}}if(e.operator=="+"){if(e.right instanceof Gt&&e.right.getValue()==""&&e.left.is_string(t)){return e.left}if(e.left instanceof Gt&&e.left.getValue()==""&&e.right.is_string(t)){return e.right}if(e.left instanceof Qe&&e.left.operator=="+"&&e.left.left instanceof Gt&&e.left.left.getValue()==""&&e.right.is_string(t)){e.left=e.left.right;return e}}if(t.option("evaluate")){switch(e.operator){case"&&":var o=has_flag(e.left,bn)?true:has_flag(e.left,Dn)?false:e.left.evaluate(t);if(!o){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}else if(!(o instanceof V)){return make_sequence(e,[e.left,e.right]).optimize(t)}var s=e.right.evaluate(t);if(!s){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(en,e)]).optimize(t)}else{set_flag(e,Dn)}}else if(!(s instanceof V)){var l=t.parent();if(l.operator=="&&"&&l.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}if(e.left.operator=="||"){var c=e.left.right.evaluate(t);if(!c)return make_node(Je,e,{condition:e.left.left,consequent:e.right,alternative:e.left.right}).optimize(t)}break;case"||":var o=has_flag(e.left,bn)?true:has_flag(e.left,Dn)?false:e.left.evaluate(t);if(!o){return make_sequence(e,[e.left,e.right]).optimize(t)}else if(!(o instanceof V)){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}var s=e.right.evaluate(t);if(!s){var l=t.parent();if(l.operator=="||"&&l.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}else if(!(s instanceof V)){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(tn,e)]).optimize(t)}else{set_flag(e,bn)}}if(e.left.operator=="&&"){var c=e.left.right.evaluate(t);if(c&&!(c instanceof V))return make_node(Je,e,{condition:e.left.left,consequent:e.left.right,alternative:e.right}).optimize(t)}break;case"??":if(is_nullish(e.left,t)){return e.right}var o=e.left.evaluate(t);if(!(o instanceof V)){return o==null?e.right:e.left}if(t.in_boolean_context()){const n=e.right.evaluate(t);if(!(n instanceof V)&&!n){return e.left}}}var f=true;switch(e.operator){case"+":if(e.right instanceof Kt&&e.left instanceof Qe&&e.left.operator=="+"&&e.left.is_string(t)){var p=make_node(Qe,e,{operator:"+",left:e.left.right,right:e.right});var _=p.optimize(t);if(p!==_){e=make_node(Qe,e,{operator:"+",left:e.left.left,right:_})}}if(e.left instanceof Qe&&e.left.operator=="+"&&e.left.is_string(t)&&e.right instanceof Qe&&e.right.operator=="+"&&e.right.is_string(t)){var p=make_node(Qe,e,{operator:"+",left:e.left.right,right:e.right.left});var d=p.optimize(t);if(p!==d){e=make_node(Qe,e,{operator:"+",left:make_node(Qe,e.left,{operator:"+",left:e.left.left,right:d}),right:e.right.right})}}if(e.right instanceof $e&&e.right.operator=="-"&&e.left.is_number(t)){e=make_node(Qe,e,{operator:"-",left:e.left,right:e.right.expression});break}if(e.left instanceof $e&&e.left.operator=="-"&&reversible()&&e.right.is_number(t)){e=make_node(Qe,e,{operator:"-",left:e.right,right:e.left.expression});break}if(e.left instanceof _e){var h=e.left;var _=e.right.evaluate(t);if(_!=e.right){h.segments[h.segments.length-1].value+=String(_);return h}}if(e.right instanceof _e){var _=e.right;var h=e.left.evaluate(t);if(h!=e.left){_.segments[0].value=String(h)+_.segments[0].value;return _}}if(e.left instanceof _e&&e.right instanceof _e){var h=e.left;var m=h.segments;var _=e.right;m[m.length-1].value+=_.segments[0].value;for(var E=1;E<_.segments.length;E++){m.push(_.segments[E])}return h}case"*":f=t.option("unsafe_math");case"&":case"|":case"^":if(e.left.is_number(t)&&e.right.is_number(t)&&reversible()&&!(e.left instanceof Qe&&e.left.operator!=e.operator&&M[e.left.operator]>=M[e.operator])){var g=make_node(Qe,e,{operator:e.operator,left:e.right,right:e.left});if(e.right instanceof Kt&&!(e.left instanceof Kt)){e=best_of(t,g,e)}else{e=best_of(t,e,g)}}if(f&&e.is_number(t)){if(e.right instanceof Qe&&e.right.operator==e.operator){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left,right:e.right.left,start:e.left.start,end:e.right.left.end}),right:e.right.right})}if(e.right instanceof Kt&&e.left instanceof Qe&&e.left.operator==e.operator){if(e.left.left instanceof Kt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left.left,right:e.right,start:e.left.left.start,end:e.right.end}),right:e.left.right})}else if(e.left.right instanceof Kt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left.right,right:e.right,start:e.left.right.start,end:e.right.end}),right:e.left.left})}}if(e.left instanceof Qe&&e.left.operator==e.operator&&e.left.right instanceof Kt&&e.right instanceof Qe&&e.right.operator==e.operator&&e.right.left instanceof Kt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:make_node(Qe,e.left.left,{operator:e.operator,left:e.left.right,right:e.right.left,start:e.left.right.start,end:e.right.left.end}),right:e.left.left}),right:e.right.right})}}}}if(e.right instanceof Qe&&e.right.operator==e.operator&&(On.has(e.operator)||e.operator=="+"&&(e.right.left.is_string(t)||e.left.is_string(t)&&e.right.right.is_string(t)))){e.left=make_node(Qe,e.left,{operator:e.operator,left:e.left.transform(t),right:e.right.left.transform(t)});e.right=e.right.right.transform(t);return e.transform(t)}var v=e.evaluate(t);if(v!==e){v=make_node_from_constant(v,e).optimize(t);return best_of(t,v,e)}return e}));def_optimize(Lt,(function(e){return e}));function recursive_ref(e,t){var n;for(var i=0;n=e.parent(i);i++){if(n instanceof oe||n instanceof _t){var r=n.name;if(r&&r.definition()===t)break}}return n}function within_array_or_object_literal(e){var t,n=0;while(t=e.parent(n++)){if(t instanceof U)return false;if(t instanceof nt||t instanceof ot||t instanceof it){return true}}return false}def_optimize(Pt,(function(e,t){if(!t.option("ie8")&&is_undeclared_ref(e)&&!t.find_parent(ne)){switch(e.name){case"undefined":return make_node($t,e).optimize(t);case"NaN":return make_node(jt,e).optimize(t);case"Infinity":return make_node(Qt,e).optimize(t)}}const n=t.parent();if(t.option("reduce_vars")&&is_lhs(e,n)!==e){const a=e.definition();const o=find_scope(t);if(t.top_retain&&a.global&&t.top_retain(a)){a.fixed=false;a.single_use=false;return e}let s=e.fixed_value();let u=a.single_use&&!(n instanceof ze&&n.is_callee_pure(t)||has_annotation(n,on))&&!(n instanceof Ue&&s instanceof oe&&s.name);if(u&&s instanceof V){u=!s.has_side_effects(t)&&!s.may_throw(t)}if(u&&(s instanceof oe||s instanceof _t)){if(retain_top_func(s,t)){u=false}else if(a.scope!==e.scope&&(a.escaped==1||has_flag(s,Sn)||within_array_or_object_literal(t)||!t.option("reduce_funcs"))){u=false}else if(recursive_ref(t,a)){u=false}else if(a.scope!==e.scope||a.orig[0]instanceof kt){u=s.is_constant_expression(e.scope);if(u=="f"){var i=e.scope;do{if(i instanceof ce||is_func_expr(i)){set_flag(i,Sn)}}while(i=i.parent_scope)}}}if(u&&s instanceof oe){u=a.scope===e.scope&&!scope_encloses_variables_in_this_scope(o,s)||n instanceof ze&&n.expression===e&&!scope_encloses_variables_in_this_scope(o,s)&&!(s.name&&s.name.definition().recursive_refs>0)}if(u&&s){if(s instanceof mt){set_flag(s,kn);s=make_node(Et,s,s)}if(s instanceof ce){set_flag(s,kn);s=make_node(ue,s,s)}if(a.recursive_refs>0&&s.name instanceof Tt){const e=s.name.definition();let t=s.variables.get(s.name.name);let n=t&&t.orig[0];if(!(n instanceof Rt)){n=make_node(Rt,s.name,s.name);n.scope=s;s.name=n;t=s.def_function(n)}walk(s,(n=>{if(n instanceof Pt&&n.definition()===e){n.thedef=t;t.references.push(n)}}))}if((s instanceof oe||s instanceof _t)&&s.parent_scope!==o){s=s.clone(true,t.get_toplevel());o.add_child_scope(s)}return s.optimize(t)}if(s){let n;if(s instanceof Ut){if(!(a.orig[0]instanceof kt)&&a.references.every((e=>a.scope===e.scope))){n=s}}else{var r=s.evaluate(t);if(r!==s&&(t.option("unsafe_regexp")||!(r instanceof RegExp))){n=make_node_from_constant(r,s)}}if(n){const i=e.size(t);const r=n.size(t);let o=0;if(t.option("unused")&&!t.exposed(a)){o=(i+2+r)/(a.references.length-a.assignments)}if(r<=i+o){return n}}}}return e}));function scope_encloses_variables_in_this_scope(e,t){for(const n of t.enclosed){if(t.variables.has(n.name)){continue}const i=e.find_variable(n.name);if(i){if(i===n)continue;return true}}return false}function is_atomic(e,t){return e instanceof Pt||e.TYPE===t.TYPE}def_optimize($t,(function(e,t){if(t.option("unsafe_undefined")){var n=find_variable(t,"undefined");if(n){var i=make_node(Pt,e,{name:"undefined",scope:n.scope,thedef:n});set_flag(i,yn);return i}}var r=is_lhs(t.self(),t.parent());if(r&&is_atomic(r,e))return e;return make_node($e,e,{operator:"void",expression:make_node(Ht,e,{value:0})})}));def_optimize(Qt,(function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&is_atomic(n,e))return e;if(t.option("keep_infinity")&&!(n&&!is_atomic(n,e))&&!find_variable(t,"Infinity")){return e}return make_node(Qe,e,{operator:"/",left:make_node(Ht,e,{value:1}),right:make_node(Ht,e,{value:0})})}));def_optimize(jt,(function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&!is_atomic(n,e)||find_variable(t,"NaN")){return make_node(Qe,e,{operator:"/",left:make_node(Ht,e,{value:0}),right:make_node(Ht,e,{value:0})})}return e}));function is_reachable(e,t){const find_ref=e=>{if(e instanceof Pt&&member(e.definition(),t)){return nn}};return walk_parent(e,((t,n)=>{if(t instanceof ie&&t!==e){var i=n.parent();if(i instanceof ze&&i.expression===t)return;if(walk(t,find_ref))return nn;return true}}))}const zn=makePredicate("+ - / * % >> << >>> | ^ &");const Kn=makePredicate("* | ^ &");def_optimize(et,(function(e,t){if(e.logical){return e.lift_sequences(t)}var n;if(t.option("dead_code")&&e.left instanceof Pt&&(n=e.left.definition()).scope===t.find_parent(oe)){var i=0,r,a=e;do{r=a;a=t.parent(i++);if(a instanceof me){if(in_try(i,a))break;if(is_reachable(n.scope,[n]))break;if(e.operator=="=")return e.right;n.fixed=false;return make_node(Qe,e,{operator:e.operator.slice(0,-1),left:e.left,right:e.right}).optimize(t)}}while(a instanceof Qe&&a.right===r||a instanceof Ge&&a.tail_node()===r)}e=e.lift_sequences(t);if(e.operator=="="&&e.left instanceof Pt&&e.right instanceof Qe){if(e.right.left instanceof Pt&&e.right.left.name==e.left.name&&zn.has(e.right.operator)){e.operator=e.right.operator+"=";e.right=e.right.right}else if(e.right.right instanceof Pt&&e.right.right.name==e.left.name&&Kn.has(e.right.operator)&&!e.right.left.has_side_effects(t)){e.operator=e.right.operator+"=";e.right=e.right.left}}return e;function in_try(n,i){var r=e.right;e.right=make_node(Yt,r);var a=i.may_throw(t);e.right=r;var o=e.left.definition().scope;var s;while((s=t.parent(n++))!==o){if(s instanceof Re){if(s.bfinally)return true;if(a&&s.bcatch)return true}}}}));def_optimize(tt,(function(e,t){if(!t.option("evaluate")){return e}var n=e.right.evaluate(t);if(n===undefined){e=e.left}else if(n!==e.right){n=make_node_from_constant(n,e.right);e.right=best_of_expression(n,e.right)}return e}));function is_nullish(e,t){let n;return e instanceof Yt||is_undefined(e,t)||e instanceof Pt&&(n=e.definition().fixed)instanceof V&&is_nullish(n,t)||e instanceof He&&e.optional&&is_nullish(e.expression,t)||e instanceof ze&&e.optional&&is_nullish(e.expression,t)||e instanceof Ye&&is_nullish(e.expression,t)}function is_nullish_check(e,t,n){if(t.may_throw(n))return false;let i;if(e instanceof Qe&&e.operator==="=="&&((i=is_nullish(e.left,n)&&e.left)||(i=is_nullish(e.right,n)&&e.right))&&(i===e.left?e.right:e.left).equivalent_to(t)){return true}if(e instanceof Qe&&e.operator==="||"){let i;let r;const find_comparison=e=>{if(!(e instanceof Qe&&(e.operator==="==="||e.operator==="=="))){return false}let a=0;let o;if(e.left instanceof Yt){a++;i=e;o=e.right}if(e.right instanceof Yt){a++;i=e;o=e.left}if(is_undefined(e.left,n)){a++;r=e;o=e.right}if(is_undefined(e.right,n)){a++;r=e;o=e.left}if(a!==1){return false}if(!o.equivalent_to(t)){return false}return true};if(!find_comparison(e.left))return false;if(!find_comparison(e.right))return false;if(i&&r&&i!==r){return true}}return false}def_optimize(Je,(function(e,t){if(!t.option("conditionals"))return e;if(e.condition instanceof Ge){var n=e.condition.expressions.slice();e.condition=n.pop();n.push(e);return make_sequence(e,n)}var i=e.condition.evaluate(t);if(i!==e.condition){if(i){return maintain_this_binding(t.parent(),t.self(),e.consequent)}else{return maintain_this_binding(t.parent(),t.self(),e.alternative)}}var r=i.negate(t,first_in_statement(t));if(best_of(t,i,r)===r){e=make_node(Je,e,{condition:r,consequent:e.alternative,alternative:e.consequent})}var a=e.condition;var o=e.consequent;var s=e.alternative;if(a instanceof Pt&&o instanceof Pt&&a.definition()===o.definition()){return make_node(Qe,e,{operator:"||",left:a,right:s})}if(o instanceof et&&s instanceof et&&o.operator===s.operator&&o.logical===s.logical&&o.left.equivalent_to(s.left)&&(!e.condition.has_side_effects(t)||o.operator=="="&&!o.left.has_side_effects(t))){return make_node(et,e,{operator:o.operator,left:o.left,logical:o.logical,right:make_node(Je,e,{condition:e.condition,consequent:o.right,alternative:s.right})})}var u;if(o instanceof ze&&s.TYPE===o.TYPE&&o.args.length>0&&o.args.length==s.args.length&&o.expression.equivalent_to(s.expression)&&!e.condition.has_side_effects(t)&&!o.expression.has_side_effects(t)&&typeof(u=single_arg_diff())=="number"){var l=o.clone();l.args[u]=make_node(Je,e,{condition:e.condition,consequent:o.args[u],alternative:s.args[u]});return l}if(s instanceof Je&&o.equivalent_to(s.consequent)){return make_node(Je,e,{condition:make_node(Qe,e,{operator:"||",left:a,right:s.condition}),consequent:o,alternative:s.alternative}).optimize(t)}if(t.option("ecma")>=2020&&is_nullish_check(a,s,t)){return make_node(Qe,e,{operator:"??",left:s,right:o}).optimize(t)}if(s instanceof Ge&&o.equivalent_to(s.expressions[s.expressions.length-1])){return make_sequence(e,[make_node(Qe,e,{operator:"||",left:a,right:make_sequence(e,s.expressions.slice(0,-1))}),o]).optimize(t)}if(s instanceof Qe&&s.operator=="&&"&&o.equivalent_to(s.right)){return make_node(Qe,e,{operator:"&&",left:make_node(Qe,e,{operator:"||",left:a,right:s.left}),right:o}).optimize(t)}if(o instanceof Je&&o.alternative.equivalent_to(s)){return make_node(Je,e,{condition:make_node(Qe,e,{left:e.condition,operator:"&&",right:o.condition}),consequent:o.consequent,alternative:s})}if(o.equivalent_to(s)){return make_sequence(e,[e.condition,o]).optimize(t)}if(o instanceof Qe&&o.operator=="||"&&o.right.equivalent_to(s)){return make_node(Qe,e,{operator:"||",left:make_node(Qe,e,{operator:"&&",left:e.condition,right:o.left}),right:s}).optimize(t)}var c=t.in_boolean_context();if(is_true(e.consequent)){if(is_false(e.alternative)){return booleanize(e.condition)}return make_node(Qe,e,{operator:"||",left:booleanize(e.condition),right:e.alternative})}if(is_false(e.consequent)){if(is_true(e.alternative)){return booleanize(e.condition.negate(t))}return make_node(Qe,e,{operator:"&&",left:booleanize(e.condition.negate(t)),right:e.alternative})}if(is_true(e.alternative)){return make_node(Qe,e,{operator:"||",left:booleanize(e.condition.negate(t)),right:e.consequent})}if(is_false(e.alternative)){return make_node(Qe,e,{operator:"&&",left:booleanize(e.condition),right:e.consequent})}return e;function booleanize(e){if(e.is_boolean())return e;return make_node($e,e,{operator:"!",expression:e.negate(t)})}function is_true(e){return e instanceof tn||c&&e instanceof Kt&&e.getValue()||e instanceof $e&&e.operator=="!"&&e.expression instanceof Kt&&!e.expression.getValue()}function is_false(e){return e instanceof en||c&&e instanceof Kt&&!e.getValue()||e instanceof $e&&e.operator=="!"&&e.expression instanceof Kt&&e.expression.getValue()}function single_arg_diff(){var e=o.args;var t=s.args;for(var n=0,i=e.length;n=2015;var i=this.expression;if(i instanceof it){var r=i.properties;for(var a=r.length;--a>=0;){var o=r[a];if(""+(o instanceof ft?o.key.name:o.key)==e){const e=r.every((e=>(e instanceof ot||n&&e instanceof ft&&!e.is_generator)&&!e.computed_key()));if(!e)return;if(!safe_to_flatten(o.value,t))return;return make_node(qe,this,{expression:make_node(nt,i,{elements:r.map((function(e){var t=e.value;if(t instanceof se){t=make_node(ue,t,t)}var n=e.key;if(n instanceof V&&!(n instanceof xt)){return make_sequence(e,[n,t])}return t}))}),property:make_node(Ht,this,{value:a})})}}}}));def_optimize(qe,(function(e,t){var n=e.expression;var i=e.property;if(t.option("properties")){var r=i.evaluate(t);if(r!==i){if(typeof r=="string"){if(r=="undefined"){r=undefined}else{var a=parseFloat(r);if(a.toString()==r){r=a}}}i=e.property=best_of_expression(i,make_node_from_constant(r,i).transform(t));var o=""+r;if(is_basic_identifier_string(o)&&o.length<=i.size()+1){return make_node(Xe,e,{expression:n,optional:e.optional,property:o,quote:i.quote}).optimize(t)}}}var s;e:if(t.option("arguments")&&n instanceof Pt&&n.name=="arguments"&&n.definition().orig.length==1&&(s=n.scope)instanceof oe&&s.uses_arguments&&!(s instanceof le)&&i instanceof Ht){var u=i.getValue();var l=new Set;var c=s.argnames;for(var f=0;f1){_=null}}else if(!_&&!t.option("keep_fargs")&&u=s.argnames.length){_=s.create_symbol(kt,{source:s,scope:s,tentative_name:"argument_"+s.argnames.length});s.argnames.push(_)}}if(_){var h=make_node(Pt,e,_);h.reference({});clear_flag(_,vn);return h}}if(is_lhs(e,t.parent()))return e;if(r!==i){var m=e.flatten_object(o,t);if(m){n=e.expression=m.expression;i=e.property=m.property}}if(t.option("properties")&&t.option("side_effects")&&i instanceof Ht&&n instanceof nt){var u=i.getValue();var E=n.elements;var g=E[u];e:if(safe_to_flatten(g,t)){var v=true;var b=[];for(var D=E.length;--D>u;){var a=E[D].drop_side_effect_free(t);if(a){b.unshift(a);if(v&&a.has_side_effects(t))v=false}}if(g instanceof ae)break e;g=g instanceof Zt?make_node($t,g):g;if(!v)b.unshift(g);while(--D>=0){var a=E[D];if(a instanceof ae)break e;a=a.drop_side_effect_free(t);if(a)b.unshift(a);else u--}if(v){b.push(g);return make_sequence(e,b).optimize(t)}else return make_node(qe,e,{expression:make_node(nt,n,{elements:b}),property:make_node(Ht,i,{value:u})})}}var y=e.evaluate(t);if(y!==e){y=make_node_from_constant(y,e).optimize(t);return best_of(t,y,e)}if(e.optional&&is_nullish(e.expression,t)){return make_node($t,e)}return e}));def_optimize(Ye,(function(e,t){e.expression=e.expression.optimize(t);return e}));oe.DEFMETHOD("contains_this",(function(){return walk(this,(e=>{if(e instanceof Ut)return nn;if(e!==this&&e instanceof ie&&!(e instanceof le)){return true}}))}));def_optimize(Xe,(function(e,t){const n=t.parent();if(is_lhs(e,n))return e;if(t.option("unsafe_proto")&&e.expression instanceof Xe&&e.expression.property=="prototype"){var i=e.expression.expression;if(is_undeclared_ref(i))switch(i.name){case"Array":e.expression=make_node(nt,e.expression,{elements:[]});break;case"Function":e.expression=make_node(ue,e.expression,{argnames:[],body:[]});break;case"Number":e.expression=make_node(Ht,e.expression,{value:0});break;case"Object":e.expression=make_node(it,e.expression,{properties:[]});break;case"RegExp":e.expression=make_node(Wt,e.expression,{value:{source:"t",flags:""}});break;case"String":e.expression=make_node(Gt,e.expression,{value:""});break}}if(!(n instanceof ze)||!has_annotation(n,on)){const n=e.flatten_object(e.property,t);if(n)return n.optimize(t)}let r=e.evaluate(t);if(r!==e){r=make_node_from_constant(r,e).optimize(t);return best_of(t,r,e)}if(e.optional&&is_nullish(e.expression,t)){return make_node($t,e)}return e}));function literals_in_boolean_context(e,t){if(t.in_boolean_context()){return best_of(t,e,make_sequence(e,[e,make_node(tn,e)]).optimize(t))}return e}function inline_array_like_spread(e){for(var t=0;te instanceof Zt))){e.splice(t,1,...i.elements);t--}}}}def_optimize(nt,(function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_array_like_spread(e.elements);return e}));function inline_object_prop_spread(e,t){for(var n=0;ne instanceof ot))){e.splice(n,1,...r.properties);n--}else if(r instanceof Kt&&!(r instanceof Gt)){e.splice(n,1)}else if(is_nullish(r,t)){e.splice(n,1)}}}}def_optimize(it,(function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_object_prop_spread(e.properties,t);return e}));def_optimize(Wt,literals_in_boolean_context);def_optimize(Ee,(function(e,t){if(e.value&&is_undefined(e.value,t)){e.value=null}return e}));def_optimize(le,opt_AST_Lambda);def_optimize(ue,(function(e,t){e=opt_AST_Lambda(e,t);if(t.option("unsafe_arrows")&&t.option("ecma")>=2015&&!e.name&&!e.is_generator&&!e.uses_arguments&&!e.pinned()){const n=walk(e,(e=>{if(e instanceof Ut)return nn}));if(!n)return make_node(le,e,e).optimize(t)}return e}));def_optimize(_t,(function(e){return e}));def_optimize(Se,(function(e,t){if(e.expression&&!e.is_star&&is_undefined(e.expression,t)){e.expression=null}return e}));def_optimize(_e,(function(e,t){if(!t.option("evaluate")||t.parent()instanceof pe){return e}var n=[];for(var i=0;i=2015&&(!(n instanceof RegExp)||n.test(e.key+""))){var i=e.key;var r=e.value;var a=r instanceof le&&Array.isArray(r.body)&&!r.contains_this();if((a||r instanceof ue)&&!r.name){return make_node(ft,e,{async:r.async,is_generator:r.is_generator,key:i instanceof V?i:make_node(xt,e,{name:i}),value:make_node(se,r,r),quote:e.quote})}}return e}));def_optimize(fe,(function(e,t){if(t.option("pure_getters")==true&&t.option("unused")&&!e.is_array&&Array.isArray(e.names)&&!is_destructuring_export_decl(t)&&!(e.names[e.names.length-1]instanceof ae)){var n=[];for(var i=0;i1)throw new Error("inline source map only works with singular input");t.sourceMap.content=read_source_map(e[a])}}}r=t.parse.toplevel}if(i&&t.mangle.properties.keep_quoted!=="strict"){reserve_quoted_keys(r,i)}if(t.wrap){r=r.wrap_commonjs(t.wrap)}if(t.enclose){r=r.wrap_enclose(t.enclose)}if(n)n.rename=Date.now();if(n)n.compress=Date.now();if(t.compress){r=new Compressor(t.compress,{mangle_options:t.mangle}).compress(r)}if(n)n.scope=Date.now();if(t.mangle)r.figure_out_scope(t.mangle);if(n)n.mangle=Date.now();if(t.mangle){En.reset();r.compute_char_frequency(t.mangle);r.mangle_names(t.mangle)}if(n)n.properties=Date.now();if(t.mangle&&t.mangle.properties){r=mangle_properties(r,t.mangle.properties)}if(n)n.format=Date.now();var o={};if(t.format.ast){o.ast=r}if(t.format.spidermonkey){o.ast=r.to_mozilla_ast()}if(!HOP(t.format,"code")||t.format.code){if(t.sourceMap){t.format.source_map=await SourceMap({file:t.sourceMap.filename,orig:t.sourceMap.content,root:t.sourceMap.root});if(t.sourceMap.includeSources){if(e instanceof re){throw new Error("original source content unavailable")}else for(var a in e)if(HOP(e,a)){t.format.source_map.get().setSourceContent(a,e[a])}}}delete t.format.ast;delete t.format.code;delete t.format.spidermonkey;var s=OutputStream(t.format);r.print(s);o.code=s.get();if(t.sourceMap){if(t.sourceMap.asObject){o.map=t.format.source_map.get().toJSON()}else{o.map=t.format.source_map.toString()}if(t.sourceMap.url=="inline"){var u=typeof o.map==="object"?JSON.stringify(o.map):o.map;o.code+="\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,"+Xn(u)}else if(t.sourceMap.url){o.code+="\n//# sourceMappingURL="+t.sourceMap.url}}}if(t.nameCache&&t.mangle){if(t.mangle.cache)t.nameCache.vars=cache_to_json(t.mangle.cache);if(t.mangle.properties&&t.mangle.properties.cache){t.nameCache.props=cache_to_json(t.mangle.properties.cache)}}if(t.format&&t.format.source_map){t.format.source_map.destroy()}if(n){n.end=Date.now();o.timings={parse:.001*(n.rename-n.parse),rename:.001*(n.compress-n.rename),compress:.001*(n.scope-n.compress),scope:.001*(n.mangle-n.scope),mangle:.001*(n.properties-n.mangle),properties:.001*(n.format-n.properties),format:.001*(n.end-n.format),total:.001*(n.end-n.start)}}return o}async function run_cli({program:e,packageJson:t,fs:i,path:r}){const a=new Set(["cname","parent_scope","scope","uses_eval","uses_with"]);var o={};var s={compress:false,mangle:false};const u=await _default_options();e.version(t.name+" "+t.version);e.parseArgv=e.parse;e.parse=undefined;if(process.argv.includes("ast"))e.helpInformation=describe_ast;else if(process.argv.includes("options"))e.helpInformation=function(){var e=[];for(var t in u){e.push("--"+(t==="sourceMap"?"source-map":t)+" options:");e.push(format_object(u[t]));e.push("")}return e.join("\n")};e.option("-p, --parse ","Specify parser options.",parse_js());e.option("-c, --compress [options]","Enable compressor/specify compressor options.",parse_js());e.option("-m, --mangle [options]","Mangle names/specify mangler options.",parse_js());e.option("--mangle-props [options]","Mangle properties/specify mangler options.",parse_js());e.option("-f, --format [options]","Format options.",parse_js());e.option("-b, --beautify [options]","Alias for --format.",parse_js());e.option("-o, --output ","Output file (default STDOUT).");e.option("--comments [filter]","Preserve copyright comments in the output.");e.option("--config-file ","Read minify() options from JSON file.");e.option("-d, --define [=value]","Global definitions.",parse_js("define"));e.option("--ecma ","Specify ECMAScript release: 5, 2015, 2016 or 2017...");e.option("-e, --enclose [arg[,...][:value[,...]]]","Embed output in a big function with configurable arguments and values.");e.option("--ie8","Support non-standard Internet Explorer 8.");e.option("--keep-classnames","Do not mangle/drop class names.");e.option("--keep-fnames","Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");e.option("--module","Input is an ES6 module");e.option("--name-cache ","File to hold mangled name mappings.");e.option("--rename","Force symbol expansion.");e.option("--no-rename","Disable symbol expansion.");e.option("--safari10","Support non-standard Safari 10.");e.option("--source-map [options]","Enable source map/specify source map options.",parse_js());e.option("--timings","Display operations run time on STDERR.");e.option("--toplevel","Compress and/or mangle variables in toplevel scope.");e.option("--wrap ","Embed everything as a function with “exports” corresponding to “name” globally.");e.arguments("[files...]").parseArgv(process.argv);if(e.configFile){s=JSON.parse(read_file(e.configFile))}if(!e.output&&e.sourceMap&&e.sourceMap.url!="inline"){fatal("ERROR: cannot write source map to STDOUT")}["compress","enclose","ie8","mangle","module","safari10","sourceMap","toplevel","wrap"].forEach((function(t){if(t in e){s[t]=e[t]}}));if("ecma"in e){if(e.ecma!=(e.ecma|0))fatal("ERROR: ecma must be an integer");const t=e.ecma|0;if(t>5&&t<2015)s.ecma=t+2009;else s.ecma=t}if(e.format||e.beautify){const t=e.format||e.beautify;s.format=typeof t==="object"?t:{}}if(e.comments){if(typeof s.format!="object")s.format={};s.format.comments=typeof e.comments=="string"?e.comments=="false"?false:e.comments:"some"}if(e.define){if(typeof s.compress!="object")s.compress={};if(typeof s.compress.global_defs!="object")s.compress.global_defs={};for(var l in e.define){s.compress.global_defs[l]=e.define[l]}}if(e.keepClassnames){s.keep_classnames=true}if(e.keepFnames){s.keep_fnames=true}if(e.mangleProps){if(e.mangleProps.domprops){delete e.mangleProps.domprops}else{if(typeof e.mangleProps!="object")e.mangleProps={};if(!Array.isArray(e.mangleProps.reserved))e.mangleProps.reserved=[]}if(typeof s.mangle!="object")s.mangle={};s.mangle.properties=e.mangleProps}if(e.nameCache){s.nameCache=JSON.parse(read_file(e.nameCache,"{}"))}if(e.output=="ast"){s.format={ast:true,code:false}}if(e.parse){if(!e.parse.acorn&&!e.parse.spidermonkey){s.parse=e.parse}else if(e.sourceMap&&e.sourceMap.content=="inline"){fatal("ERROR: inline source map only works with built-in parser")}}if(~e.rawArgs.indexOf("--rename")){s.rename=true}else if(!e.rename){s.rename=false}let convert_path=e=>e;if(typeof e.sourceMap=="object"&&"base"in e.sourceMap){convert_path=function(){var t=e.sourceMap.base;delete s.sourceMap.base;return function(e){return r.relative(t,e)}}()}let c;if(s.files&&s.files.length){c=s.files;delete s.files}else if(e.args.length){c=e.args}if(c){simple_glob(c).forEach((function(e){o[convert_path(e)]=read_file(e)}))}else{await new Promise((e=>{var t=[];process.stdin.setEncoding("utf8");process.stdin.on("data",(function(e){t.push(e)})).on("end",(function(){o=[t.join("")];e()}));process.stdin.resume()}))}await run_cli();function convert_ast(e){return V.from_mozilla_ast(Object.keys(o).reduce(e,null))}async function run_cli(){var t=e.sourceMap&&e.sourceMap.content;if(t&&t!=="inline"){s.sourceMap.content=read_file(t,t)}if(e.timings)s.timings=true;try{if(e.parse){if(e.parse.acorn){o=convert_ast((function(t,i){return n(108).parse(o[i],{ecmaVersion:2018,locations:true,program:t,sourceFile:i,sourceType:s.module||e.parse.module?"module":"script"})}))}else if(e.parse.spidermonkey){o=convert_ast((function(e,t){var n=JSON.parse(o[t]);if(!e)return n;e.body=e.body.concat(n.body);return e}))}}}catch(e){fatal(e)}let r;try{r=await minify(o,s)}catch(e){if(e.name=="SyntaxError"){print_error("Parse error at "+e.filename+":"+e.line+","+e.col);var u=e.col;var l=o[e.filename].split(/\r?\n/);var c=l[e.line-1];if(!c&&!u){c=l[e.line-2];u=c.length}if(c){var f=70;if(u>f){c=c.slice(u-f);u=f}print_error(c.slice(0,80));print_error(c.slice(0,u).replace(/\S/g," ")+"^")}}if(e.defs){print_error("Supported options:");print_error(format_object(e.defs))}fatal(e);return}if(e.output=="ast"){if(!s.compress&&!s.mangle){r.ast.figure_out_scope({})}console.log(JSON.stringify(r.ast,(function(e,t){if(t)switch(e){case"thedef":return symdef(t);case"enclosed":return t.length?t.map(symdef):undefined;case"variables":case"globals":return t.size?collect_from_map(t,symdef):undefined}if(a.has(e))return;if(t instanceof AST_Token)return;if(t instanceof Map)return;if(t instanceof V){var n={_class:"AST_"+t.TYPE};if(t.block_scope){n.variables=t.block_scope.variables;n.enclosed=t.block_scope.enclosed}t.CTOR.PROPS.forEach((function(e){n[e]=t[e]}));return n}return t}),2))}else if(e.output=="spidermonkey"){try{const e=await minify(r.code,{compress:false,mangle:false,format:{ast:true,code:false}});console.log(JSON.stringify(e.ast.to_mozilla_ast(),null,2))}catch(e){fatal(e);return}}else if(e.output){i.writeFileSync(e.output,r.code);if(s.sourceMap&&s.sourceMap.url!=="inline"&&r.map){i.writeFileSync(e.output+".map",r.map)}}else{console.log(r.code)}if(e.nameCache){i.writeFileSync(e.nameCache,JSON.stringify(s.nameCache))}if(r.timings)for(var p in r.timings){print_error("- "+p+": "+r.timings[p].toFixed(3)+"s")}}function fatal(e){if(e instanceof Error)e=e.stack.replace(/^\S*?Error:/,"ERROR:");print_error(e);process.exit(1)}function simple_glob(e){if(Array.isArray(e)){return[].concat.apply([],e.map(simple_glob))}if(e&&e.match(/[*?]/)){var t=r.dirname(e);try{var n=i.readdirSync(t)}catch(e){}if(n){var a="^"+r.basename(e).replace(/[.+^$[\]\\(){}]/g,"\\$&").replace(/\*/g,"[^/\\\\]*").replace(/\?/g,"[^/\\\\]")+"$";var o=process.platform==="win32"?"i":"";var s=new RegExp(a,o);var u=n.filter((function(e){return s.test(e)})).map((function(e){return r.join(t,e)}));if(u.length)return u}}return[e]}function read_file(e,t){try{return i.readFileSync(e,"utf8")}catch(e){if((e.code=="ENOENT"||e.code=="ENAMETOOLONG")&&t!=null)return t;fatal(e)}}function parse_js(e){return function(t,n){n=n||{};try{walk(parse(t,{expression:true}),(t=>{if(t instanceof et){var i=t.left.print_to_string();var r=t.right;if(e){n[i]=r}else if(r instanceof nt){n[i]=r.elements.map(to_string)}else if(r instanceof Wt){r=r.value;n[i]=new RegExp(r.source,r.flags)}else{n[i]=to_string(r)}return true}if(t instanceof gt||t instanceof He){var i=t.print_to_string();n[i]=true;return true}if(!(t instanceof Ge))throw t;function to_string(e){return e instanceof Kt?e.getValue():e.print_to_string({quote_keys:true})}}))}catch(i){if(e){fatal("Error parsing arguments for '"+e+"': "+t)}else{n[t]=null}}return n}}function symdef(e){var t=1e6+e.id+" "+e.name;if(e.mangled_name)t+=" "+e.mangled_name;return t}function collect_from_map(e,t){var n=[];e.forEach((function(e){n.push(t(e))}));return n}function format_object(e){var t=[];var n="";Object.keys(e).map((function(t){if(n.length!/^\$/.test(e)));if(n.length>0){e.space();e.with_parens((function(){n.forEach((function(t,n){if(n)e.space();e.print(t)}))}))}if(t.documentation){e.space();e.print_string(t.documentation)}if(t.SUBCLASSES.length>0){e.space();e.with_block((function(){t.SUBCLASSES.forEach((function(t){e.indent();doitem(t);e.newline()}))}))}}doitem(V);return e+"\n"}}async function _default_options(){const e={};Object.keys(infer_options({0:0})).forEach((t=>{const n=infer_options({[t]:{0:0}});if(n)e[t]=n}));return e}async function infer_options(e){try{await minify("",e)}catch(e){return e.defs}}e._default_options=_default_options;e._run_cli=run_cli;e.minify=minify}))}};var t={};function __nccwpck_require__(n){var i=t[n];if(i!==undefined){return i.exports}var r=t[n]={exports:{}};var a=true;try{e[n].call(r.exports,r,r.exports,__nccwpck_require__);a=false}finally{if(a)delete t[n]}return r.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var n=__nccwpck_require__(405);module.exports=n})(); \ No newline at end of file diff --git a/packages/next/compiled/webpack/bundle5.js b/packages/next/compiled/webpack/bundle5.js index a4327a64d1de..e83999145ae4 100644 --- a/packages/next/compiled/webpack/bundle5.js +++ b/packages/next/compiled/webpack/bundle5.js @@ -9383,7 +9383,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports.importAssertions = importAssertions; -var _acorn = _interopRequireWildcard(__webpack_require__(31988)); +var _acorn = _interopRequireWildcard(__webpack_require__(70108)); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } @@ -9671,7234 +9671,10073 @@ function importAssertions(Parser) { /***/ }), -/***/ 5787: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 70108: +/***/ (function(__unused_webpack_module, exports) { -"use strict"; +(function (global, factory) { + true ? factory(exports) : + 0; +}(this, (function (exports) { 'use strict'; -/** - * trace-event - A library to create a trace of your node app per - * Google's Trace Event format: - * // JSSTYLED - * https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __webpack_require__(32087); -var stream_1 = __webpack_require__(12781); -function evCommon() { - var hrtime = process.hrtime(); // [seconds, nanoseconds] - var ts = hrtime[0] * 1000000 + Math.round(hrtime[1] / 1000); // microseconds - return { - ts: ts, - pid: process.pid, - tid: process.pid // no meaningful tid for node.js - }; -} -var Tracer = /** @class */ (function (_super) { - tslib_1.__extends(Tracer, _super); - function Tracer(opts) { - if (opts === void 0) { opts = {}; } - var _this = _super.call(this) || this; - _this.noStream = false; - _this.events = []; - if (typeof opts !== "object") { - throw new Error("Invalid options passed (must be an object)"); - } - if (opts.parent != null && typeof opts.parent !== "object") { - throw new Error("Invalid option (parent) passed (must be an object)"); - } - if (opts.fields != null && typeof opts.fields !== "object") { - throw new Error("Invalid option (fields) passed (must be an object)"); - } - if (opts.objectMode != null && - (opts.objectMode !== true && opts.objectMode !== false)) { - throw new Error("Invalid option (objectsMode) passed (must be a boolean)"); - } - _this.noStream = opts.noStream || false; - _this.parent = opts.parent; - if (_this.parent) { - _this.fields = Object.assign({}, opts.parent && opts.parent.fields); - } - else { - _this.fields = {}; - } - if (opts.fields) { - Object.assign(_this.fields, opts.fields); - } - if (!_this.fields.cat) { - // trace-viewer *requires* `cat`, so let's have a fallback. - _this.fields.cat = "default"; - } - else if (Array.isArray(_this.fields.cat)) { - _this.fields.cat = _this.fields.cat.join(","); - } - if (!_this.fields.args) { - // trace-viewer *requires* `args`, so let's have a fallback. - _this.fields.args = {}; - } - if (_this.parent) { - // TODO: Not calling Readable ctor here. Does that cause probs? - // Probably if trying to pipe from the child. - // Might want a serpate TracerChild class for these guys. - _this._push = _this.parent._push.bind(_this.parent); - } - else { - _this._objectMode = Boolean(opts.objectMode); - var streamOpts = { objectMode: _this._objectMode }; - if (_this._objectMode) { - _this._push = _this.push; - } - else { - _this._push = _this._pushString; - streamOpts.encoding = "utf8"; - } - stream_1.Readable.call(_this, streamOpts); - } - return _this; + // Reserved word lists for various dialects of the language + + var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" + }; + + // And the keywords + + var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; + + var keywords = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" + }; + + var keywordRelationalOperator = /^in(stanceof)?$/; + + // ## Character categories + + // Big ugly regular expressions that match characters in the + // whitespace, identifier, and identifier-start categories. These + // are only applied when a character is found to actually have a + // code point above 128. + // Generated by `bin/generate-identifier-regex.js`. + var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; + + var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + + nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; + + // These are a run-length and offset encoded representation of the + // >0xffff code points that are a valid part of identifiers. The + // offset starts at 0x10000, and each pair of numbers represents an + // offset to the next range, and then a size of the range. They were + // generated by bin/generate-identifier-regex.js + + // eslint-disable-next-line comma-spacing + var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938]; + + // eslint-disable-next-line comma-spacing + var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239]; + + // This has a complexity linear to the value of the code. The + // assumption is that looking up astral identifier characters is + // rare. + function isInAstralSet(code, set) { + var pos = 0x10000; + for (var i = 0; i < set.length; i += 2) { + pos += set[i]; + if (pos > code) { return false } + pos += set[i + 1]; + if (pos >= code) { return true } } - /** - * If in no streamMode in order to flush out the trace - * you need to call flush. - */ - Tracer.prototype.flush = function () { - if (this.noStream === true) { - for (var _i = 0, _a = this.events; _i < _a.length; _i++) { - var evt = _a[_i]; - this._push(evt); - } - this._flush(); - } - }; - Tracer.prototype._read = function (_) { }; - Tracer.prototype._pushString = function (ev) { - var separator = ""; - if (!this.firstPush) { - this.push("["); - this.firstPush = true; - } - else { - separator = ",\n"; - } - this.push(separator + JSON.stringify(ev), "utf8"); - }; - Tracer.prototype._flush = function () { - if (!this._objectMode) { - this.push("]"); - } - }; - Tracer.prototype.child = function (fields) { - return new Tracer({ - parent: this, - fields: fields - }); - }; - Tracer.prototype.begin = function (fields) { - return this.mkEventFunc("b")(fields); - }; - Tracer.prototype.end = function (fields) { - return this.mkEventFunc("e")(fields); - }; - Tracer.prototype.completeEvent = function (fields) { - return this.mkEventFunc("X")(fields); - }; - Tracer.prototype.instantEvent = function (fields) { - return this.mkEventFunc("I")(fields); - }; - Tracer.prototype.mkEventFunc = function (ph) { - var _this = this; - return function (fields) { - var ev = evCommon(); - // Assign the event phase. - ev.ph = ph; - if (fields) { - if (typeof fields === "string") { - ev.name = fields; - } - else { - for (var _i = 0, _a = Object.keys(fields); _i < _a.length; _i++) { - var k = _a[_i]; - if (k === "cat") { - ev.cat = fields.cat.join(","); - } - else { - ev[k] = fields[k]; - } - } - } - } - if (!_this.noStream) { - _this._push(ev); - } - else { - _this.events.push(ev); - } - }; - }; - return Tracer; -}(stream_1.Readable)); -exports.Tracer = Tracer; -/* - * These correspond to the "Async events" in the Trace Events doc. - * - * Required fields: - * - name - * - id - * - * Optional fields: - * - cat (array) - * - args (object) - * - TODO: stack fields, other optional fields? - * - * Dev Note: We don't explicitly assert that correct fields are - * used for speed (premature optimization alert!). - */ -//# sourceMappingURL=trace-event.js.map + } -/***/ }), + // Test whether a given character code starts an identifier. -/***/ 32087: -/***/ (function(module) { + function isIdentifierStart(code, astral) { + if (code < 65) { return code === 36 } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) + } -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - - __extends = function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function (m, exports) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - }; - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - } - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); + // Test whether a given character is part of an identifier. + + function isIdentifierChar(code, astral) { + if (code < 48) { return code === 36 } + if (code < 58) { return true } + if (code < 65) { return false } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) + } + // ## Token types -/***/ }), + // The assignment of fine-grained, information-carrying type objects + // allows the tokenizer to store the information it has about a + // token in a way that is very cheap for the parser to look up. -/***/ 70665: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // All token type variables start with an underscore, to make them + // easy to recognize. -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki + // The `beforeExpr` property is used to disambiguate between regular + // expressions and divisions. It is set on all token types that can + // be followed by an expression (thus, a slash after them would be a + // regular expression). + // + // The `startsExpr` property is used to check if the token ends a + // `yield` expression. It is set on all token types that either can + // directly start an expression (like a quotation mark) or can + // continue an expression (like the body of a string). + // + // `isLoop` marks a keyword as starting a loop, which is important + // to know when parsing a label, in order to allow or disallow + // continue jumps to that label. + + var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; + + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; + }; - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) + } + var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + // Map keyword names to token types. - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + var keywords$1 = {}; + // Succinct definitions of keyword token types + function kw(name, options) { + if ( options === void 0 ) options = {}; -const Variable = __webpack_require__(82971); + options.keyword = name; + return keywords$1[name] = new TokenType(name, options) + } -/** - * @class Definition - */ -class Definition { - constructor(type, name, node, parent, index, kind) { + var types = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + privateId: new TokenType("privateId", startsExpr), + eof: new TokenType("eof"), + + // Punctuation token types. + bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), + bracketR: new TokenType("]"), + braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), + braceR: new TokenType("}"), + parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + eq: new TokenType("=", {beforeExpr: true, isAssign: true}), + assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), + incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), + prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", {beforeExpr: true}), + coalesce: binop("??", 1), + + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", {isLoop: true, beforeExpr: true}), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", {isLoop: true}), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", {isLoop: true}), + _with: kw("with"), + _new: kw("new", {beforeExpr: true, startsExpr: true}), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import", startsExpr), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", {beforeExpr: true, binop: 7}), + _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), + _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), + _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), + _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) + }; - /** - * @member {String} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). - */ - this.type = type; + // Matches a whole line break (where CRLF is considered a single + // line break). Used to count lines. - /** - * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence. - */ - this.name = name; + var lineBreak = /\r\n?|\n|\u2028|\u2029/; + var lineBreakG = new RegExp(lineBreak.source, "g"); - /** - * @member {espree.Node} Definition#node - the enclosing node of the identifier. - */ - this.node = node; + function isNewLine(code) { + return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 + } - /** - * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier. - */ - this.parent = parent; + var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; - /** - * @member {Number?} Definition#index - the index in the declaration statement. - */ - this.index = index; + var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; - /** - * @member {String?} Definition#kind - the kind of the declaration statement. - */ - this.kind = kind; - } -} + var ref = Object.prototype; + var hasOwnProperty = ref.hasOwnProperty; + var toString = ref.toString; -/** - * @class ParameterDefinition - */ -class ParameterDefinition extends Definition { - constructor(name, node, index, rest) { - super(Variable.Parameter, name, node, null, index, null); + // Checks if an object has a property. - /** - * Whether the parameter definition is a part of a rest parameter. - * @member {boolean} ParameterDefinition#rest - */ - this.rest = rest; - } -} + function has(obj, propName) { + return hasOwnProperty.call(obj, propName) + } -module.exports = { - ParameterDefinition, - Definition -}; + var isArray = Array.isArray || (function (obj) { return ( + toString.call(obj) === "[object Array]" + ); }); -/* vim: set sw=4 ts=4 et tw=80 : */ + function wordsRegexp(words) { + return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") + } + // These are used when `options.locations` is on, for the + // `startLoc` and `endLoc` properties. -/***/ }), + var Position = function Position(line, col) { + this.line = line; + this.column = col; + }; -/***/ 36007: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) + }; -"use strict"; -/* - Copyright (C) 2012-2014 Yusuke Suzuki - Copyright (C) 2013 Alex Seville - Copyright (C) 2014 Thiago de Arruda + var SourceLocation = function SourceLocation(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { this.source = p.sourceFile; } + }; - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + // The `getLineInfo` function is mostly useful when the + // `locations` option is off (for performance reasons) and you + // want to find the line/column position for a given character + // offset. `input` should be the code string that the offset refers + // into. + + function getLineInfo(input, offset) { + for (var line = 1, cur = 0;;) { + lineBreakG.lastIndex = cur; + var match = lineBreakG.exec(input); + if (match && match.index < offset) { + ++line; + cur = match.index + match[0].length; + } else { + return new Position(line, offset - cur) + } + } + } - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + // A second argument must be given to configure the parser process. + // These options are recognized (only `ecmaVersion` is required): + + var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the + // latest version the library supports). This influences support + // for strict mode, the set of reserved words, and support for + // new syntax features. + ecmaVersion: null, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called + // when a semicolon is automatically inserted. It will be passed + // the position of the comma as an offset, and if `locations` is + // enabled, it is given the location as a `{line, column}` object + // as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program, and an import.meta expression + // in a script isn't considered an error. + allowImportExportEverywhere: false, + // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: null, + // When enabled, super identifiers are not constrained to + // appearing in methods and do not raise an error when they appear elsewhere. + allowSuperOutsideMethod: null, + // When enabled, hashbang directive in the beginning of file + // is allowed and treated as a line comment. + allowHashBang: false, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false + }; - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + // Interpret and default an options object -/** - * Escope (escope) is an ECMAScript - * scope analyzer extracted from the esmangle project. - *

- * escope finds lexical scopes in a source program, i.e. areas of that - * program where different occurrences of the same identifier refer to the same - * variable. With each scope the contained variables are collected, and each - * identifier reference in code is linked to its corresponding variable (if - * possible). - *

- * escope works on a syntax tree of the parsed source code which has - * to adhere to the - * Mozilla Parser API. E.g. espree is a parser - * that produces such syntax trees. - *

- * The main interface is the {@link analyze} function. - * @module escope - */ + var warnedAboutEcmaVersion = false; + function getOptions(opts) { + var options = {}; -/* eslint no-underscore-dangle: ["error", { "allow": ["__currentScope"] }] */ + for (var opt in defaultOptions) + { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; } -const assert = __webpack_require__(39491); + if (options.ecmaVersion === "latest") { + options.ecmaVersion = 1e8; + } else if (options.ecmaVersion == null) { + if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { + warnedAboutEcmaVersion = true; + console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); + } + options.ecmaVersion = 11; + } else if (options.ecmaVersion >= 2015) { + options.ecmaVersion -= 2009; + } -const ScopeManager = __webpack_require__(96988); -const Referencer = __webpack_require__(44585); -const Reference = __webpack_require__(64945); -const Variable = __webpack_require__(82971); -const Scope = (__webpack_require__(16313).Scope); -const version = (__webpack_require__(30290)/* .version */ .i8); + if (options.allowReserved == null) + { options.allowReserved = options.ecmaVersion < 5; } -/** - * Set the default options - * @returns {Object} options - */ -function defaultOptions() { - return { - optimistic: false, - directive: false, - nodejsScope: false, - impliedStrict: false, - sourceType: "script", // one of ['script', 'module'] - ecmaVersion: 5, - childVisitorKeys: null, - fallback: "iteration" - }; -} + if (isArray(options.onToken)) { + var tokens = options.onToken; + options.onToken = function (token) { return tokens.push(token); }; + } + if (isArray(options.onComment)) + { options.onComment = pushComment(options, options.onComment); } -/** - * Preform deep update on option object - * @param {Object} target - Options - * @param {Object} override - Updates - * @returns {Object} Updated options - */ -function updateDeeply(target, override) { + return options + } - /** - * Is hash object - * @param {Object} value - Test value - * @returns {boolean} Result - */ - function isHashObject(value) { - return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp); + function pushComment(options, array) { + return function(block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? "Block" : "Line", + value: text, + start: start, + end: end + }; + if (options.locations) + { comment.loc = new SourceLocation(this, startLoc, endLoc); } + if (options.ranges) + { comment.range = [start, end]; } + array.push(comment); } + } - for (const key in override) { - if (Object.prototype.hasOwnProperty.call(override, key)) { - const val = override[key]; + // Each scope gets a bitset that may contain these flags + var + SCOPE_TOP = 1, + SCOPE_FUNCTION = 2, + SCOPE_ASYNC = 4, + SCOPE_GENERATOR = 8, + SCOPE_ARROW = 16, + SCOPE_SIMPLE_CATCH = 32, + SCOPE_SUPER = 64, + SCOPE_DIRECT_SUPER = 128, + SCOPE_CLASS_STATIC_BLOCK = 256, + SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; + + function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) + } - if (isHashObject(val)) { - if (isHashObject(target[key])) { - updateDeeply(target[key], val); - } else { - target[key] = updateDeeply({}, val); - } - } else { - target[key] = val; - } - } + // Used in checkLVal* and declareName to determine the type of a binding + var + BIND_NONE = 0, // Not a binding + BIND_VAR = 1, // Var-style binding + BIND_LEXICAL = 2, // Let- or const-style binding + BIND_FUNCTION = 3, // Function declaration + BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding + BIND_OUTSIDE = 5; // Special case for function names as bound inside the function + + var Parser = function Parser(options, input, startPos) { + this.options = options = getOptions(options); + this.sourceFile = options.sourceFile; + this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); + var reserved = ""; + if (options.allowReserved !== true) { + reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; + if (options.sourceType === "module") { reserved += " await"; } + } + this.reservedWords = wordsRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = wordsRegexp(reservedStrict); + this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + this.containsEsc = false; + + // Set up token state + + // The current position of the tokenizer in the input. + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; } - return target; -} -/** - * Main interface function. Takes an Espree syntax tree and returns the - * analyzed scopes. - * @function analyze - * @param {espree.Tree} tree - Abstract Syntax Tree - * @param {Object} providedOptions - Options that tailor the scope analysis - * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag - * @param {boolean} [providedOptions.directive=false]- the directive flag - * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls - * @param {boolean} [providedOptions.nodejsScope=false]- whether the whole - * script is executed under node.js environment. When enabled, escope adds - * a function scope immediately following the global scope. - * @param {boolean} [providedOptions.impliedStrict=false]- implied strict mode - * (if ecmaVersion >= 5). - * @param {string} [providedOptions.sourceType='script']- the source type of the script. one of 'script' and 'module' - * @param {number} [providedOptions.ecmaVersion=5]- which ECMAScript version is considered - * @param {Object} [providedOptions.childVisitorKeys=null] - Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option. - * @param {string} [providedOptions.fallback='iteration'] - A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option. - * @returns {ScopeManager} ScopeManager - */ -function analyze(tree, providedOptions) { - const options = updateDeeply(defaultOptions(), providedOptions); - const scopeManager = new ScopeManager(options); - const referencer = new Referencer(options, scopeManager); + // Properties of the current token: + // Its type + this.type = types.eof; + // For tokens that include more information than their type, the value + this.value = null; + // Its start and end offset + this.start = this.end = this.pos; + // And, if locations are used, the {line, column} object + // corresponding to those offsets + this.startLoc = this.endLoc = this.curPosition(); + + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + + // The context stack is used to superficially track syntactic + // context to predict whether a regular expression is allowed in a + // given position. + this.context = this.initialContext(); + this.exprAllowed = true; + + // Figure out if it's a module code. + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); + + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1; + this.potentialArrowInForAwait = false; + + // Positions to delayed-check that yield/await does not exist in default parameters. + this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; + // Labels in scope. + this.labels = []; + // Thus-far undefined exports. + this.undefinedExports = Object.create(null); - referencer.visit(tree); + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") + { this.skipLineComment(2); } - assert(scopeManager.__currentScope === null, "currentScope should be null."); + // Scope tracking for duplicate variable names (see scope.js) + this.scopeStack = []; + this.enterScope(SCOPE_TOP); - return scopeManager; -} + // For RegExp validation + this.regexpState = null; -module.exports = { + // The stack of private names. + // Each element has two properties: 'declared' and 'used'. + // When it exited from the outermost class definition, all used private names must be declared. + this.privateNameStack = []; + }; - /** @name module:escope.version */ - version, + var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; - /** @name module:escope.Reference */ - Reference, + Parser.prototype.parse = function parse () { + var node = this.options.program || this.startNode(); + this.nextToken(); + return this.parseTopLevel(node) + }; - /** @name module:escope.Variable */ - Variable, + prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; + prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }; + prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; + prototypeAccessors.canAwait.get = function () { + for (var i = this.scopeStack.length - 1; i >= 0; i--) { + var scope = this.scopeStack[i]; + if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false } + if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } + } + return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction + }; + prototypeAccessors.allowSuper.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod + }; + prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; + prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; + prototypeAccessors.allowNewDotTarget.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit + }; + prototypeAccessors.inClassStaticBlock.get = function () { + return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 + }; - /** @name module:escope.Scope */ - Scope, + Parser.extend = function extend () { + var plugins = [], len = arguments.length; + while ( len-- ) plugins[ len ] = arguments[ len ]; - /** @name module:escope.ScopeManager */ - ScopeManager, - analyze -}; + var cls = this; + for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } + return cls + }; + Parser.parse = function parse (input, options) { + return new this(options, input).parse() + }; -/* vim: set sw=4 ts=4 et tw=80 : */ + Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression() + }; + Parser.tokenizer = function tokenizer (input, options) { + return new this(options, input) + }; -/***/ }), + Object.defineProperties( Parser.prototype, prototypeAccessors ); + + var pp = Parser.prototype; + + // ## Parser utilities + + var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; + pp.strictDirective = function(start) { + for (;;) { + // Try to find string literal. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match = literal.exec(this.input.slice(start)); + if (!match) { return false } + if ((match[1] || match[2]) === "use strict") { + skipWhiteSpace.lastIndex = start + match[0].length; + var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; + var next = this.input.charAt(end); + return next === ";" || next === "}" || + (lineBreak.test(spaceAfter[0]) && + !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) + } + start += match[0].length; -/***/ 54162: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Skip semicolon, if any. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") + { start++; } + } + }; -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki + // Predicate that tests whether the next token is of the given + // type, and if yes, consumes it as a side effect. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + pp.eat = function(type) { + if (this.type === type) { + this.next(); + return true + } else { + return false + } + }; - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + // Tests whether parsed token is a contextual keyword. - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + pp.isContextual = function(name) { + return this.type === types.name && this.value === name && !this.containsEsc + }; + // Consumes contextual keyword if possible. -/* eslint-disable no-undefined */ + pp.eatContextual = function(name) { + if (!this.isContextual(name)) { return false } + this.next(); + return true + }; -const Syntax = (__webpack_require__(18350).Syntax); -const esrecurse = __webpack_require__(81217); + // Asserts that following token is given contextual keyword. -/** - * Get last array element - * @param {array} xs - array - * @returns {any} Last elment - */ -function getLast(xs) { - return xs[xs.length - 1] || null; -} + pp.expectContextual = function(name) { + if (!this.eatContextual(name)) { this.unexpected(); } + }; -class PatternVisitor extends esrecurse.Visitor { - static isPattern(node) { - const nodeType = node.type; + // Test whether a semicolon can be inserted at the current position. - return ( - nodeType === Syntax.Identifier || - nodeType === Syntax.ObjectPattern || - nodeType === Syntax.ArrayPattern || - nodeType === Syntax.SpreadElement || - nodeType === Syntax.RestElement || - nodeType === Syntax.AssignmentPattern - ); - } + pp.canInsertSemicolon = function() { + return this.type === types.eof || + this.type === types.braceR || + lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; - constructor(options, rootPattern, callback) { - super(null, options); - this.rootPattern = rootPattern; - this.callback = callback; - this.assignments = []; - this.rightHandNodes = []; - this.restElements = []; + pp.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } + return true } + }; - Identifier(pattern) { - const lastRestElement = getLast(this.restElements); + // Consume a semicolon, or, failing that, see if we are allowed to + // pretend that there is a semicolon at this position. - this.callback(pattern, { - topLevel: pattern === this.rootPattern, - rest: lastRestElement !== null && lastRestElement !== undefined && lastRestElement.argument === pattern, - assignments: this.assignments - }); + pp.semicolon = function() { + if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } + }; + + pp.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) + { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } + if (!notNext) + { this.next(); } + return true } + }; - Property(property) { + // Expect a token of a given type. If found, consume it, otherwise, + // raise an unexpected token error. - // Computed property's key is a right hand node. - if (property.computed) { - this.rightHandNodes.push(property.key); - } + pp.expect = function(type) { + this.eat(type) || this.unexpected(); + }; - // If it's shorthand, its key is same as its value. - // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). - // If it's not shorthand, the name of new variable is its value's. - this.visit(property.value); - } + // Raise an unexpected token error. - ArrayPattern(pattern) { - for (let i = 0, iz = pattern.elements.length; i < iz; ++i) { - const element = pattern.elements[i]; + pp.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); + }; - this.visit(element); - } - } + function DestructuringErrors() { + this.shorthandAssign = + this.trailingComma = + this.parenthesizedAssign = + this.parenthesizedBind = + this.doubleProto = + -1; + } - AssignmentPattern(pattern) { - this.assignments.push(pattern); - this.visit(pattern.left); - this.rightHandNodes.push(pattern.right); - this.assignments.pop(); + pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { return } + if (refDestructuringErrors.trailingComma > -1) + { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } + }; + + pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { return false } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } + if (shorthandAssign >= 0) + { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } + if (doubleProto >= 0) + { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } + }; + + pp.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) + { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } + if (this.awaitPos) + { this.raise(this.awaitPos, "Await expression cannot be a default value"); } + }; + + pp.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") + { return this.isSimpleAssignTarget(expr.expression) } + return expr.type === "Identifier" || expr.type === "MemberExpression" + }; + + var pp$1 = Parser.prototype; + + // ### Statement parsing + + // Parse a program. Initializes the parser, reads any number of + // statements, and wraps them in a Program node. Optionally takes a + // `program` argument. If present, the statements will be appended + // to its body instead of creating a new node. + + pp$1.parseTopLevel = function(node) { + var exports = Object.create(null); + if (!node.body) { node.body = []; } + while (this.type !== types.eof) { + var stmt = this.parseStatement(null, true, exports); + node.body.push(stmt); } + if (this.inModule) + { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) + { + var name = list[i]; + + this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); + } } + this.adaptDirectivePrologue(node.body); + this.next(); + node.sourceType = this.options.sourceType; + return this.finishNode(node, "Program") + }; - RestElement(pattern) { - this.restElements.push(pattern); - this.visit(pattern.argument); - this.restElements.pop(); + var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; + + pp$1.isLet = function(context) { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + // For ambiguous cases, determine if a LexicalDeclaration (or only a + // Statement) is allowed here. If context is not empty then only a Statement + // is allowed. However, `let [` is an explicit negative lookahead for + // ExpressionStatement, so special-case it first. + if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral + if (context) { return false } + + if (nextCh === 123) { return true } // '{' + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } + if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) { return true } } + return false + }; - MemberExpression(node) { + // check 'async [no LineTerminator here] function' + // - 'async /*foo*/ function' is OK. + // - 'async /*\n*/ function' is invalid. + pp$1.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) + { return false } + + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, after; + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 === this.input.length || + !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) + }; - // Computed property's key is a right hand node. - if (node.computed) { - this.rightHandNodes.push(node.property); - } + // Parse a single statement. + // + // If expecting a statement and finding a slash operator, parse a + // regular expression literal. This is to handle cases like + // `if (foo) /blah/.exec(foo)`, where looking at the previous token + // does not help. - // the object is only read, write to its property. - this.rightHandNodes.push(node.object); + pp$1.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind; + + if (this.isLet(context)) { + starttype = types._var; + kind = "let"; } - // - // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression. - // By spec, LeftHandSideExpression is Pattern or MemberExpression. - // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758) - // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc... - // + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword) + case types._debugger: return this.parseDebuggerStatement(node) + case types._do: return this.parseDoStatement(node) + case types._for: return this.parseForStatement(node) + case types._function: + // Function as sole body of either an if statement or a labeled statement + // works, but not when it is part of a labeled statement that is the sole + // body of an if statement. + if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } + return this.parseFunctionStatement(node, false, !context) + case types._class: + if (context) { this.unexpected(); } + return this.parseClass(node, true) + case types._if: return this.parseIfStatement(node) + case types._return: return this.parseReturnStatement(node) + case types._switch: return this.parseSwitchStatement(node) + case types._throw: return this.parseThrowStatement(node) + case types._try: return this.parseTryStatement(node) + case types._const: case types._var: + kind = kind || this.value; + if (context && kind !== "var") { this.unexpected(); } + return this.parseVarStatement(node, kind) + case types._while: return this.parseWhileStatement(node) + case types._with: return this.parseWithStatement(node) + case types.braceL: return this.parseBlock(true, node) + case types.semi: return this.parseEmptyStatement(node) + case types._export: + case types._import: + if (this.options.ecmaVersion > 10 && starttype === types._import) { + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 40 || nextCh === 46) // '(' or '.' + { return this.parseExpressionStatement(node, this.parseExpression()) } + } - SpreadElement(node) { - this.visit(node.argument); + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) + { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } + if (!this.inModule) + { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } + } + return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports) + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction()) { + if (context) { this.unexpected(); } + this.next(); + return this.parseFunctionStatement(node, true, !context) + } + + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) + { return this.parseLabeledStatement(node, maybeName, expr, context) } + else { return this.parseExpressionStatement(node, expr) } } + }; - ArrayExpression(node) { - node.elements.forEach(this.visit, this); + pp$1.parseBreakContinueStatement = function(node, keyword) { + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; } + else if (this.type !== types.name) { this.unexpected(); } + else { + node.label = this.parseIdent(); + this.semicolon(); } - AssignmentExpression(node) { - this.assignments.push(node); - this.visit(node.left); - this.rightHandNodes.push(node.right); - this.assignments.pop(); + // Verify that there is an actual destination to break or + // continue to. + var i = 0; + for (; i < this.labels.length; ++i) { + var lab = this.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } + if (node.label && isBreak) { break } + } } + if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") + }; - CallExpression(node) { + pp$1.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement") + }; - // arguments are right hand nodes. - node.arguments.forEach(a => { - this.rightHandNodes.push(a); - }); - this.visit(node.callee); - } -} + pp$1.parseDoStatement = function(node) { + this.next(); + this.labels.push(loopLabel); + node.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types._while); + node.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) + { this.eat(types.semi); } + else + { this.semicolon(); } + return this.finishNode(node, "DoWhileStatement") + }; -module.exports = PatternVisitor; + // Disambiguating between a `for` and a `for`/`in` or `for`/`of` + // loop is non-trivial. Basically, we have to parse the init `var` + // statement or expression, disallowing the `in` operator (see + // the second parameter to `parseExpression`), and then check + // whether the next token is `in` or `of`. When there is no init + // part (semicolon immediately after the opening parenthesis), it + // is a regular `for` loop. + + pp$1.parseForStatement = function(node) { + this.next(); + var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types.parenL); + if (this.type === types.semi) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, null) + } + var isLet = this.isLet(); + if (this.type === types._var || this.type === types._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + return this.parseForIn(node, init$1) + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init$1) + } + var startsWithLet = this.isContextual("let"), isForOf = false; + var refDestructuringErrors = new DestructuringErrors; + var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); + if (this.type === types._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLValPattern(init); + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init) + }; -/* vim: set sw=4 ts=4 et tw=80 : */ + pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) + }; + pp$1.parseIfStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + // allow function declarations in branches, but only in non-strict mode + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement") + }; -/***/ }), + pp$1.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + { this.raise(this.start, "'return' outside of function"); } + this.next(); -/***/ 64945: -/***/ (function(module) { + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki + if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; } + else { node.argument = this.parseExpression(); this.semicolon(); } + return this.finishNode(node, "ReturnStatement") + }; - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + pp$1.parseSwitchStatement = function(node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types.braceL); + this.labels.push(switchLabel); + this.enterScope(0); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + var cur; + for (var sawDefault = false; this.type !== types.braceR;) { + if (this.type === types._case || this.type === types._default) { + var isCase = this.type === types._case; + if (cur) { this.finishNode(cur, "SwitchCase"); } + node.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } + sawDefault = true; + cur.test = null; + } + this.expect(types.colon); + } else { + if (!cur) { this.unexpected(); } + cur.consequent.push(this.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { this.finishNode(cur, "SwitchCase"); } + this.next(); // Closing brace + this.labels.pop(); + return this.finishNode(node, "SwitchStatement") + }; - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + pp$1.parseThrowStatement = function(node) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) + { this.raise(this.lastTokEnd, "Illegal newline after throw"); } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement") + }; - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + // Reused empty array added for node fields that are always empty. + var empty = []; -const READ = 0x1; -const WRITE = 0x2; -const RW = READ | WRITE; + pp$1.parseTryStatement = function(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.type === types._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types.parenL)) { + clause.param = this.parseBindingAtom(); + var simple = clause.param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types.parenR); + } else { + if (this.options.ecmaVersion < 10) { this.unexpected(); } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) + { this.raise(node.start, "Missing catch or finally clause"); } + return this.finishNode(node, "TryStatement") + }; -/** - * A Reference represents a single occurrence of an identifier in code. - * @class Reference - */ -class Reference { - constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) { + pp$1.parseVarStatement = function(node, kind) { + this.next(); + this.parseVar(node, false, kind); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration") + }; - /** - * Identifier syntax node. - * @member {espreeIdentifier} Reference#identifier - */ - this.identifier = ident; + pp$1.parseWhileStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node, "WhileStatement") + }; - /** - * Reference to the enclosing Scope. - * @member {Scope} Reference#from - */ - this.from = scope; + pp$1.parseWithStatement = function(node) { + if (this.strict) { this.raise(this.start, "'with' in strict mode"); } + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement("with"); + return this.finishNode(node, "WithStatement") + }; - /** - * Whether the reference comes from a dynamic scope (such as 'eval', - * 'with', etc.), and may be trapped by dynamic scopes. - * @member {boolean} Reference#tainted - */ - this.tainted = false; + pp$1.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement") + }; - /** - * The variable this reference is resolved with. - * @member {Variable} Reference#resolved - */ - this.resolved = null; + pp$1.parseLabeledStatement = function(node, maybeName, expr, context) { + for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) + { + var label = list[i$1]; + + if (label.name === maybeName) + { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } } + var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; + for (var i = this.labels.length - 1; i >= 0; i--) { + var label$1 = this.labels[i]; + if (label$1.statementStart === node.start) { + // Update information about previous labels on this node + label$1.statementStart = this.start; + label$1.kind = kind; + } else { break } + } + this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement") + }; - /** - * The read-write mode of the reference. (Value is one of {@link - * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). - * @member {number} Reference#flag - * @private - */ - this.flag = flag; - if (this.isWrite()) { + pp$1.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement") + }; - /** - * If reference is writeable, this is the tree being written to it. - * @member {espreeNode} Reference#writeExpr - */ - this.writeExpr = writeExpr; + // Parse a semicolon-enclosed block of statements, handling `"use + // strict"` declarations when `allowStrict` is true (used for + // function bodies). - /** - * Whether the Reference might refer to a partial value of writeExpr. - * @member {boolean} Reference#partial - */ - this.partial = partial; + pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) { + if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; + if ( node === void 0 ) node = this.startNode(); - /** - * Whether the Reference is to write of initialization. - * @member {boolean} Reference#init - */ - this.init = init; - } - this.__maybeImplicitGlobal = maybeImplicitGlobal; + node.body = []; + this.expect(types.braceL); + if (createNewLexicalScope) { this.enterScope(0); } + while (this.type !== types.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); } + if (exitStrict) { this.strict = false; } + this.next(); + if (createNewLexicalScope) { this.exitScope(); } + return this.finishNode(node, "BlockStatement") + }; - /** - * Whether the reference is static. - * @method Reference#isStatic - * @returns {boolean} static - */ - isStatic() { - return !this.tainted && this.resolved && this.resolved.scope.isStatic(); - } + // Parse a regular `for` loop. The disambiguation code in + // `parseStatement` will already have parsed the init statement or + // expression. + + pp$1.parseFor = function(node, init) { + node.init = init; + this.expect(types.semi); + node.test = this.type === types.semi ? null : this.parseExpression(); + this.expect(types.semi); + node.update = this.type === types.parenR ? null : this.parseExpression(); + this.expect(types.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, "ForStatement") + }; - /** - * Whether the reference is writeable. - * @method Reference#isWrite - * @returns {boolean} write - */ - isWrite() { - return !!(this.flag & Reference.WRITE); - } + // Parse a `for`/`in` and `for`/`of` loop, which are almost + // same from parser's perspective. - /** - * Whether the reference is readable. - * @method Reference#isRead - * @returns {boolean} read - */ - isRead() { - return !!(this.flag & Reference.READ); - } + pp$1.parseForIn = function(node, init) { + var isForIn = this.type === types._in; + this.next(); - /** - * Whether the reference is read-only. - * @method Reference#isReadOnly - * @returns {boolean} read only - */ - isReadOnly() { - return this.flag === Reference.READ; + if ( + init.type === "VariableDeclaration" && + init.declarations[0].init != null && + ( + !isForIn || + this.options.ecmaVersion < 8 || + this.strict || + init.kind !== "var" || + init.declarations[0].id.type !== "Identifier" + ) + ) { + this.raise( + init.start, + ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") + ); } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") + }; - /** - * Whether the reference is write-only. - * @method Reference#isWriteOnly - * @returns {boolean} write only - */ - isWriteOnly() { - return this.flag === Reference.WRITE; + // Parse a list of variable declarations. + + pp$1.parseVar = function(node, isFor, kind) { + node.declarations = []; + node.kind = kind; + for (;;) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + if (this.eat(types.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { + this.unexpected(); + } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) { + this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types.comma)) { break } } + return node + }; - /** - * Whether the reference is read-write. - * @method Reference#isReadWrite - * @returns {boolean} read write - */ - isReadWrite() { - return this.flag === Reference.RW; - } -} + pp$1.parseVarId = function(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); + }; -/** - * @constant Reference.READ - * @private - */ -Reference.READ = READ; + var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; -/** - * @constant Reference.WRITE - * @private - */ -Reference.WRITE = WRITE; + // Parse a function declaration or literal (depending on the + // `statement & FUNC_STATEMENT`). -/** - * @constant Reference.RW - * @private - */ -Reference.RW = RW; + // Remove `allowExpressionBody` for 7.0.0, as it is only called with false + pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { + this.initFunction(node); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { + if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT)) + { this.unexpected(); } + node.generator = this.eat(types.star); + } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + if (statement & FUNC_STATEMENT) { + node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent(); + if (node.id && !(statement & FUNC_HANGING_STATEMENT)) + // If it is a regular function declaration in sloppy mode, then it is + // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding + // mode depends on properties of the current scope (see + // treatFunctionsAsVar). + { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } + } -module.exports = Reference; + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(node.async, node.generator)); -/* vim: set sw=4 ts=4 et tw=80 : */ + if (!(statement & FUNC_STATEMENT)) + { node.id = this.type === types.name ? this.parseIdent() : null; } + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody, false, forInit); -/***/ }), + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") + }; -/***/ 44585: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + pp$1.parseFunctionParams = function(node) { + this.expect(types.parenL); + node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + }; -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki + // Parse a class declaration or literal (depending on the + // `isStatement` parameter). + + pp$1.parseClass = function(node, isStatement) { + this.next(); + + // ecma-262 14.6 Class Definitions + // A class definition is always strict mode code. + var oldStrict = this.strict; + this.strict = true; + + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + var privateNameMap = this.enterClassBody(); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types.braceL); + while (this.type !== types.braceR) { + var element = this.parseClassElement(node.superClass !== null); + if (element) { + classBody.body.push(element); + if (element.type === "MethodDefinition" && element.kind === "constructor") { + if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); } + hadConstructor = true; + } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { + this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); + } + } + } + this.strict = oldStrict; + this.next(); + node.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") + }; - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + pp$1.parseClassElement = function(constructorAllowsSuper) { + if (this.eat(types.semi)) { return null } + + var ecmaVersion = this.options.ecmaVersion; + var node = this.startNode(); + var keyName = ""; + var isGenerator = false; + var isAsync = false; + var kind = "method"; + var isStatic = false; + + if (this.eatContextual("static")) { + // Parse static init block + if (ecmaVersion >= 13 && this.eat(types.braceL)) { + this.parseClassStaticBlock(node); + return node + } + if (this.isClassElementNameStart() || this.type === types.star) { + isStatic = true; + } else { + keyName = "static"; + } + } + node.static = isStatic; + if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === types.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + var lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + // Parse element name + if (keyName) { + // 'async', 'get', 'set', or 'static' were not a keyword contextually. + // The last token is any of those. Make it the element name. + node.computed = false; + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node.key.name = keyName; + this.finishNode(node.key, "Identifier"); + } else { + this.parseClassElementName(node); + } - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + // Parse element value + if (ecmaVersion < 13 || this.type === types.parenL || kind !== "method" || isGenerator || isAsync) { + var isConstructor = !node.static && checkKeyName(node, "constructor"); + var allowsDirectSuper = isConstructor && constructorAllowsSuper; + // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. + if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } + node.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node); + } + return node + }; -/* eslint-disable no-underscore-dangle */ -/* eslint-disable no-undefined */ + pp$1.isClassElementNameStart = function() { + return ( + this.type === types.name || + this.type === types.privateId || + this.type === types.num || + this.type === types.string || + this.type === types.bracketL || + this.type.keyword + ) + }; -const Syntax = (__webpack_require__(18350).Syntax); -const esrecurse = __webpack_require__(81217); -const Reference = __webpack_require__(64945); -const Variable = __webpack_require__(82971); -const PatternVisitor = __webpack_require__(54162); -const definition = __webpack_require__(70665); -const assert = __webpack_require__(39491); + pp$1.parseClassElementName = function(element) { + if (this.type === types.privateId) { + if (this.value === "constructor") { + this.raise(this.start, "Classes can't have an element named '#constructor'"); + } + element.computed = false; + element.key = this.parsePrivateIdent(); + } else { + this.parsePropertyName(element); + } + }; -const ParameterDefinition = definition.ParameterDefinition; -const Definition = definition.Definition; + pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + // Check key and flags + var key = method.key; + if (method.kind === "constructor") { + if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } + if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } + } else if (method.static && checkKeyName(method, "prototype")) { + this.raise(key.start, "Classes may not have a static property named prototype"); + } -/** - * Traverse identifier in pattern - * @param {Object} options - options - * @param {pattern} rootPattern - root pattern - * @param {Refencer} referencer - referencer - * @param {callback} callback - callback - * @returns {void} - */ -function traverseIdentifierInPattern(options, rootPattern, referencer, callback) { + // Parse value + var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); - // Call the callback at left hand identifier nodes, and Collect right hand nodes. - const visitor = new PatternVisitor(options, rootPattern, callback); + // Check value + if (method.kind === "get" && value.params.length !== 0) + { this.raiseRecoverable(value.start, "getter should have no params"); } + if (method.kind === "set" && value.params.length !== 1) + { this.raiseRecoverable(value.start, "setter should have exactly one param"); } + if (method.kind === "set" && value.params[0].type === "RestElement") + { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } - visitor.visit(rootPattern); + return this.finishNode(method, "MethodDefinition") + }; - // Process the right hand nodes recursively. - if (referencer !== null && referencer !== undefined) { - visitor.rightHandNodes.forEach(referencer.visit, referencer); + pp$1.parseClassField = function(field) { + if (checkKeyName(field, "constructor")) { + this.raise(field.key.start, "Classes can't have a field named 'constructor'"); + } else if (field.static && checkKeyName(field, "prototype")) { + this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); } -} - -// Importing ImportDeclaration. -// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation -// https://github.com/estree/estree/blob/master/es6.md#importdeclaration -// FIXME: Now, we don't create module environment, because the context is -// implementation dependent. -class Importer extends esrecurse.Visitor { - constructor(declaration, referencer) { - super(null, referencer.options); - this.declaration = declaration; - this.referencer = referencer; + if (this.eat(types.eq)) { + // To raise SyntaxError if 'arguments' exists in the initializer. + var scope = this.currentThisScope(); + var inClassFieldInit = scope.inClassFieldInit; + scope.inClassFieldInit = true; + field.value = this.parseMaybeAssign(); + scope.inClassFieldInit = inClassFieldInit; + } else { + field.value = null; } + this.semicolon(); - visitImport(id, specifier) { - this.referencer.visitPattern(id, pattern => { - this.referencer.currentScope().__define(pattern, - new Definition( - Variable.ImportBinding, - pattern, - specifier, - this.declaration, - null, - null - )); - }); - } + return this.finishNode(field, "PropertyDefinition") + }; - ImportNamespaceSpecifier(node) { - const local = (node.local || node.id); + pp$1.parseClassStaticBlock = function(node) { + node.body = []; - if (local) { - this.visitImport(local, node); - } + var oldLabels = this.labels; + this.labels = []; + this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); + while (this.type !== types.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); } + this.next(); + this.exitScope(); + this.labels = oldLabels; - ImportDefaultSpecifier(node) { - const local = (node.local || node.id); + return this.finishNode(node, "StaticBlock") + }; - this.visitImport(local, node); + pp$1.parseClassId = function(node, isStatement) { + if (this.type === types.name) { + node.id = this.parseIdent(); + if (isStatement) + { this.checkLValSimple(node.id, BIND_LEXICAL, false); } + } else { + if (isStatement === true) + { this.unexpected(); } + node.id = null; } + }; - ImportSpecifier(node) { - const local = (node.local || node.id); + pp$1.parseClassSuper = function(node) { + node.superClass = this.eat(types._extends) ? this.parseExprSubscripts(false) : null; + }; - if (node.name) { - this.visitImport(node.name, node); + pp$1.enterClassBody = function() { + var element = {declared: Object.create(null), used: []}; + this.privateNameStack.push(element); + return element.declared + }; + + pp$1.exitClassBody = function() { + var ref = this.privateNameStack.pop(); + var declared = ref.declared; + var used = ref.used; + var len = this.privateNameStack.length; + var parent = len === 0 ? null : this.privateNameStack[len - 1]; + for (var i = 0; i < used.length; ++i) { + var id = used[i]; + if (!has(declared, id.name)) { + if (parent) { + parent.used.push(id); } else { - this.visitImport(local, node); + this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); } + } } -} + }; -// Referencing variables and creating bindings. -class Referencer extends esrecurse.Visitor { - constructor(options, scopeManager) { - super(null, options); - this.options = options; - this.scopeManager = scopeManager; - this.parent = null; - this.isInnerMethodDefinition = false; + function isPrivateNameConflicted(privateNameMap, element) { + var name = element.key.name; + var curr = privateNameMap[name]; + + var next = "true"; + if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { + next = (element.static ? "s" : "i") + element.kind; } - currentScope() { - return this.scopeManager.__currentScope; + // `class { get #a(){}; static set #a(_){} }` is also conflict. + if ( + curr === "iget" && next === "iset" || + curr === "iset" && next === "iget" || + curr === "sget" && next === "sset" || + curr === "sset" && next === "sget" + ) { + privateNameMap[name] = "true"; + return false + } else if (!curr) { + privateNameMap[name] = next; + return false + } else { + return true } + } - close(node) { - while (this.currentScope() && node === this.currentScope().block) { - this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); + function checkKeyName(node, name) { + var computed = node.computed; + var key = node.key; + return !computed && ( + key.type === "Identifier" && key.name === name || + key.type === "Literal" && key.value === name + ) + } + + // Parses module export declaration. + + pp$1.parseExport = function(node, exports) { + this.next(); + // export * from '...' + if (this.eat(types.star)) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseIdent(true); + this.checkExport(exports, node.exported.name, this.lastTokStart); + } else { + node.exported = null; } + } + this.expectContextual("from"); + if (this.type !== types.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration") + } + if (this.eat(types._default)) { // export default ... + this.checkExport(exports, "default", this.lastTokStart); + var isAsync; + if (this.type === types._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { this.next(); } + node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); + } else if (this.type === types._class) { + var cNode = this.startNode(); + node.declaration = this.parseClass(cNode, "nullableID"); + } else { + node.declaration = this.parseMaybeAssign(); + this.semicolon(); + } + return this.finishNode(node, "ExportDefaultDeclaration") } + // export var|const|let|function|class ... + if (this.shouldParseExportStatement()) { + node.declaration = this.parseStatement(null); + if (node.declaration.type === "VariableDeclaration") + { this.checkVariableExport(exports, node.declaration.declarations); } + else + { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } + node.specifiers = []; + node.source = null; + } else { // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== types.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + } else { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) { + // check for keywords used as local names + var spec = list[i]; - pushInnerMethodDefinition(isInnerMethodDefinition) { - const previous = this.isInnerMethodDefinition; + this.checkUnreserved(spec.local); + // check if export is defined + this.checkLocalExport(spec.local); + } - this.isInnerMethodDefinition = isInnerMethodDefinition; - return previous; + node.source = null; + } + this.semicolon(); } + return this.finishNode(node, "ExportNamedDeclaration") + }; - popInnerMethodDefinition(isInnerMethodDefinition) { - this.isInnerMethodDefinition = isInnerMethodDefinition; + pp$1.checkExport = function(exports, name, pos) { + if (!exports) { return } + if (has(exports, name)) + { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } + exports[name] = true; + }; + + pp$1.checkPatternExport = function(exports, pat) { + var type = pat.type; + if (type === "Identifier") + { this.checkExport(exports, pat.name, pat.start); } + else if (type === "ObjectPattern") + { for (var i = 0, list = pat.properties; i < list.length; i += 1) + { + var prop = list[i]; + + this.checkPatternExport(exports, prop); + } } + else if (type === "ArrayPattern") + { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + + if (elt) { this.checkPatternExport(exports, elt); } + } } + else if (type === "Property") + { this.checkPatternExport(exports, pat.value); } + else if (type === "AssignmentPattern") + { this.checkPatternExport(exports, pat.left); } + else if (type === "RestElement") + { this.checkPatternExport(exports, pat.argument); } + else if (type === "ParenthesizedExpression") + { this.checkPatternExport(exports, pat.expression); } + }; + + pp$1.checkVariableExport = function(exports, decls) { + if (!exports) { return } + for (var i = 0, list = decls; i < list.length; i += 1) + { + var decl = list[i]; + + this.checkPatternExport(exports, decl.id); } + }; - referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { - const scope = this.currentScope(); + pp$1.shouldParseExportStatement = function() { + return this.type.keyword === "var" || + this.type.keyword === "const" || + this.type.keyword === "class" || + this.type.keyword === "function" || + this.isLet() || + this.isAsyncFunction() + }; - assignments.forEach(assignment => { - scope.__referencing( - pattern, - Reference.WRITE, - assignment.right, - maybeImplicitGlobal, - pattern !== assignment.left, - init - ); - }); + // Parses a comma-separated list of module exports. + + pp$1.parseExportSpecifiers = function(exports) { + var nodes = [], first = true; + // export { x, y as z } [from '...'] + this.expect(types.braceL); + while (!this.eat(types.braceR)) { + if (!first) { + this.expect(types.comma); + if (this.afterTrailingComma(types.braceR)) { break } + } else { first = false; } + + var node = this.startNode(); + node.local = this.parseIdent(true); + node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local; + this.checkExport(exports, node.exported.name, node.exported.start); + nodes.push(this.finishNode(node, "ExportSpecifier")); } + return nodes + }; - visitPattern(node, options, callback) { - let visitPatternOptions = options; - let visitPatternCallback = callback; + // Parses import declaration. - if (typeof options === "function") { - visitPatternCallback = options; - visitPatternOptions = { processRightHandNodes: false }; - } + pp$1.parseImport = function(node) { + this.next(); + // import '...' + if (this.type === types.string) { + node.specifiers = empty; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected(); + } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration") + }; - traverseIdentifierInPattern( - this.options, - node, - visitPatternOptions.processRightHandNodes ? this : null, - visitPatternCallback - ); + // Parses a comma-separated list of module imports. + + pp$1.parseImportSpecifiers = function() { + var nodes = [], first = true; + if (this.type === types.name) { + // import defaultObj, { x, y as z } from '...' + var node = this.startNode(); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); + if (!this.eat(types.comma)) { return nodes } + } + if (this.type === types.star) { + var node$1 = this.startNode(); + this.next(); + this.expectContextual("as"); + node$1.local = this.parseIdent(); + this.checkLValSimple(node$1.local, BIND_LEXICAL); + nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); + return nodes + } + this.expect(types.braceL); + while (!this.eat(types.braceR)) { + if (!first) { + this.expect(types.comma); + if (this.afterTrailingComma(types.braceR)) { break } + } else { first = false; } + + var node$2 = this.startNode(); + node$2.imported = this.parseIdent(true); + if (this.eatContextual("as")) { + node$2.local = this.parseIdent(); + } else { + this.checkUnreserved(node$2.imported); + node$2.local = node$2.imported; + } + this.checkLValSimple(node$2.local, BIND_LEXICAL); + nodes.push(this.finishNode(node$2, "ImportSpecifier")); } + return nodes + }; - visitFunction(node) { - let i, iz; + // Set `ExpressionStatement#directive` property for directive prologues. + pp$1.adaptDirectivePrologue = function(statements) { + for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { + statements[i].directive = statements[i].expression.raw.slice(1, -1); + } + }; + pp$1.isDirectiveCandidate = function(statement) { + return ( + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + typeof statement.expression.value === "string" && + // Reject parenthesized strings. + (this.input[statement.start] === "\"" || this.input[statement.start] === "'") + ) + }; - // FunctionDeclaration name is defined in upper scope - // NOTE: Not referring variableScope. It is intended. - // Since - // in ES5, FunctionDeclaration should be in FunctionBody. - // in ES6, FunctionDeclaration should be block scoped. + var pp$2 = Parser.prototype; + + // Convert existing expression atom to assignable pattern + // if possible. + + pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") + { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } + break + + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break + + case "ObjectExpression": + node.type = "ObjectPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.toAssignable(prop, isBinding); + // Early error: + // AssignmentRestProperty[Yield, Await] : + // `...` DestructuringAssignmentTarget[Yield, Await] + // + // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. + if ( + prop.type === "RestElement" && + (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") + ) { + this.raise(prop.argument.start, "Unexpected token"); + } + } + break + + case "Property": + // AssignmentProperty has type === "Property" + if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } + this.toAssignable(node.value, isBinding); + break + + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + this.toAssignableList(node.elements, isBinding); + break + + case "SpreadElement": + node.type = "RestElement"; + this.toAssignable(node.argument, isBinding); + if (node.argument.type === "AssignmentPattern") + { this.raise(node.argument.start, "Rest elements cannot have a default value"); } + break + + case "AssignmentExpression": + if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding); + break + + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break + + case "ChainExpression": + this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (!isBinding) { break } - if (node.type === Syntax.FunctionDeclaration) { + default: + this.raise(node.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + return node + }; - // id is defined in upper scope - this.currentScope().__define(node.id, - new Definition( - Variable.FunctionName, - node.id, - node, - null, - null, - null - )); - } + // Convert list of expression atoms to binding list. - // FunctionExpression with name creates its special scope; - // FunctionExpressionNameScope. - if (node.type === Syntax.FunctionExpression && node.id) { - this.scopeManager.__nestFunctionExpressionNameScope(node); - } + pp$2.toAssignableList = function(exprList, isBinding) { + var end = exprList.length; + for (var i = 0; i < end; i++) { + var elt = exprList[i]; + if (elt) { this.toAssignable(elt, isBinding); } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") + { this.unexpected(last.argument.start); } + } + return exprList + }; - // Consider this function is in the MethodDefinition. - this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); + // Parses spread element. - const that = this; + pp$2.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement") + }; - /** - * Visit pattern callback - * @param {pattern} pattern - pattern - * @param {Object} info - info - * @returns {void} - */ - function visitPatternCallback(pattern, info) { - that.currentScope().__define(pattern, - new ParameterDefinition( - pattern, - node, - i, - info.rest - )); + pp$2.parseRestBinding = function() { + var node = this.startNode(); + this.next(); - that.referencingDefaultValue(pattern, info.assignments, null, true); - } + // RestElement inside of a function parameter must be an identifier + if (this.options.ecmaVersion === 6 && this.type !== types.name) + { this.unexpected(); } - // Process parameter declarations. - for (i = 0, iz = node.params.length; i < iz; ++i) { - this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback); - } + node.argument = this.parseBindingAtom(); - // if there's a rest argument, add that - if (node.rest) { - this.visitPattern({ - type: "RestElement", - argument: node.rest - }, pattern => { - this.currentScope().__define(pattern, - new ParameterDefinition( - pattern, - node, - node.params.length, - true - )); - }); - } + return this.finishNode(node, "RestElement") + }; - // In TypeScript there are a number of function-like constructs which have no body, - // so check it exists before traversing - if (node.body) { + // Parses lvalue (assignable) atom. - // Skip BlockStatement to prevent creating BlockStatement scope. - if (node.body.type === Syntax.BlockStatement) { - this.visitChildren(node.body); - } else { - this.visit(node.body); - } - } + pp$2.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types.bracketR, true, true); + return this.finishNode(node, "ArrayPattern") - this.close(node); + case types.braceL: + return this.parseObj(true) + } } + return this.parseIdent() + }; - visitClass(node) { - if (node.type === Syntax.ClassDeclaration) { - this.currentScope().__define(node.id, - new Definition( - Variable.ClassName, - node.id, - node, - null, - null, - null - )); - } + pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { + var elts = [], first = true; + while (!this.eat(close)) { + if (first) { first = false; } + else { this.expect(types.comma); } + if (allowEmpty && this.type === types.comma) { + elts.push(null); + } else if (allowTrailingComma && this.afterTrailingComma(close)) { + break + } else if (this.type === types.ellipsis) { + var rest = this.parseRestBinding(); + this.parseBindingListItem(rest); + elts.push(rest); + if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } + this.expect(close); + break + } else { + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + elts.push(elem); + } + } + return elts + }; - this.visit(node.superClass); + pp$2.parseBindingListItem = function(param) { + return param + }; - this.scopeManager.__nestClassScope(node); + // Parses assignment pattern around given atom if possible. - if (node.id) { - this.currentScope().__define(node.id, - new Definition( - Variable.ClassName, - node.id, - node - )); + pp$2.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern") + }; + + // The following three functions all verify that a node is an lvalue — + // something that can be bound, or assigned to. In order to do so, they perform + // a variety of checks: + // + // - Check that none of the bound/assigned-to identifiers are reserved words. + // - Record name declarations for bindings in the appropriate scope. + // - Check duplicate argument names, if checkClashes is set. + // + // If a complex binding pattern is encountered (e.g., object and array + // destructuring), the entire pattern is recursively checked. + // + // There are three versions of checkLVal*() appropriate for different + // circumstances: + // + // - checkLValSimple() shall be used if the syntactic construct supports + // nothing other than identifiers and member expressions. Parenthesized + // expressions are also correctly handled. This is generally appropriate for + // constructs for which the spec says + // + // > It is a Syntax Error if AssignmentTargetType of [the production] is not + // > simple. + // + // It is also appropriate for checking if an identifier is valid and not + // defined elsewhere, like import declarations or function/class identifiers. + // + // Examples where this is used include: + // a += …; + // import a from '…'; + // where a is the node to be checked. + // + // - checkLValPattern() shall be used if the syntactic construct supports + // anything checkLValSimple() supports, as well as object and array + // destructuring patterns. This is generally appropriate for constructs for + // which the spec says + // + // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor + // > an ArrayLiteral and AssignmentTargetType of [the production] is not + // > simple. + // + // Examples where this is used include: + // (a = …); + // const a = …; + // try { … } catch (a) { … } + // where a is the node to be checked. + // + // - checkLValInnerPattern() shall be used if the syntactic construct supports + // anything checkLValPattern() supports, as well as default assignment + // patterns, rest elements, and other constructs that may appear within an + // object or array destructuring pattern. + // + // As a special case, function parameters also use checkLValInnerPattern(), + // as they also support defaults and rest constructs. + // + // These functions deliberately support both assignment and binding constructs, + // as the logic for both is exceedingly similar. If the node is the target of + // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it + // should be set to the appropriate BIND_* constant, like BIND_VAR or + // BIND_LEXICAL. + // + // If the function is called with a non-BIND_NONE bindingType, then + // additionally a checkClashes object may be specified to allow checking for + // duplicate argument names. checkClashes is ignored if the provided construct + // is an assignment (i.e., bindingType is BIND_NONE). + + pp$2.checkLValSimple = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + var isBind = bindingType !== BIND_NONE; + + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } + if (isBind) { + if (bindingType === BIND_LEXICAL && expr.name === "let") + { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } + if (checkClashes) { + if (has(checkClashes, expr.name)) + { this.raiseRecoverable(expr.start, "Argument name clash"); } + checkClashes[expr.name] = true; } - this.visit(node.body); + if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } + } + break - this.close(node); + case "ChainExpression": + this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } + break + + case "ParenthesizedExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } + return this.checkLValSimple(expr.expression, bindingType, checkClashes) + + default: + this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); } + }; - visitProperty(node) { - let previous; + pp$2.checkLValPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; - if (node.computed) { - this.visit(node.key); - } + switch (expr.type) { + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) { + var prop = list[i]; - const isMethodDefinition = node.type === Syntax.MethodDefinition; + this.checkLValInnerPattern(prop, bindingType, checkClashes); + } + break - if (isMethodDefinition) { - previous = this.pushInnerMethodDefinition(true); - } - this.visit(node.value); - if (isMethodDefinition) { - this.popInnerMethodDefinition(previous); - } + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + + if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } + } + break + + default: + this.checkLValSimple(expr, bindingType, checkClashes); } + }; - visitForIn(node) { - if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") { - this.scopeManager.__nestForScope(node); - } + pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; - if (node.left.type === Syntax.VariableDeclaration) { - this.visit(node.left); - this.visitPattern(node.left.declarations[0].id, pattern => { - this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true); - }); - } else { - this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { - let maybeImplicitGlobal = null; + switch (expr.type) { + case "Property": + // AssignmentProperty has type === "Property" + this.checkLValInnerPattern(expr.value, bindingType, checkClashes); + break - if (!this.currentScope().isStrict) { - maybeImplicitGlobal = { - pattern, - node - }; - } - this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); - this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false); - }); - } - this.visit(node.right); - this.visit(node.body); + case "AssignmentPattern": + this.checkLValPattern(expr.left, bindingType, checkClashes); + break - this.close(node); + case "RestElement": + this.checkLValPattern(expr.argument, bindingType, checkClashes); + break + + default: + this.checkLValPattern(expr, bindingType, checkClashes); } + }; - visitVariableDeclaration(variableTargetScope, type, node, index) { + // The algorithm used to determine whether a regexp can appear at a - const decl = node.declarations[index]; - const init = decl.init; + var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; + }; - this.visitPattern(decl.id, { processRightHandNodes: true }, (pattern, info) => { - variableTargetScope.__define( - pattern, - new Definition( - type, - pattern, - decl, - node, - index, - node.kind - ) - ); + var types$1 = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) + }; - this.referencingDefaultValue(pattern, info.assignments, null, true); - if (init) { - this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true); - } - }); - } + var pp$3 = Parser.prototype; - AssignmentExpression(node) { - if (PatternVisitor.isPattern(node.left)) { - if (node.operator === "=") { - this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { - let maybeImplicitGlobal = null; + pp$3.initialContext = function() { + return [types$1.b_stat] + }; - if (!this.currentScope().isStrict) { - maybeImplicitGlobal = { - pattern, - node - }; - } - this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); - this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false); - }); - } else { - this.currentScope().__referencing(node.left, Reference.RW, node.right); - } - } else { - this.visit(node.left); - } - this.visit(node.right); + pp$3.curContext = function() { + return this.context[this.context.length - 1] + }; + + pp$3.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types$1.f_expr || parent === types$1.f_stat) + { return true } + if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) + { return !parent.isExpr } + + // The check for `tt.name && exprAllowed` detects whether we are + // after a `yield` or `of` construct. See the `updateContext` for + // `tt.name`. + if (prevType === types._return || prevType === types.name && this.exprAllowed) + { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } + if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) + { return true } + if (prevType === types.braceL) + { return parent === types$1.b_stat } + if (prevType === types._var || prevType === types._const || prevType === types.name) + { return false } + return !this.exprAllowed + }; + + pp$3.inGeneratorContext = function() { + for (var i = this.context.length - 1; i >= 1; i--) { + var context = this.context[i]; + if (context.token === "function") + { return context.generator } } + return false + }; - CatchClause(node) { - this.scopeManager.__nestCatchScope(node); + pp$3.updateContext = function(prevType) { + var update, type = this.type; + if (type.keyword && prevType === types.dot) + { this.exprAllowed = false; } + else if (update = type.updateContext) + { update.call(this, prevType); } + else + { this.exprAllowed = type.beforeExpr; } + }; - this.visitPattern(node.param, { processRightHandNodes: true }, (pattern, info) => { - this.currentScope().__define(pattern, - new Definition( - Variable.CatchClause, - node.param, - node, - null, - null, - null - )); - this.referencingDefaultValue(pattern, info.assignments, null, true); - }); - this.visit(node.body); + // Used to handle egde case when token context could not be inferred correctly in tokenize phase + pp$3.overrideContext = function(tokenCtx) { + if (this.curContext() !== tokenCtx) { + this.context[this.context.length - 1] = tokenCtx; + } + }; - this.close(node); + // Token-specific context update code + + types.parenR.updateContext = types.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return + } + var out = this.context.pop(); + if (out === types$1.b_stat && this.curContext().token === "function") { + out = this.context.pop(); } + this.exprAllowed = !out.isExpr; + }; - Program(node) { - this.scopeManager.__nestGlobalScope(node); + types.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); + this.exprAllowed = true; + }; - if (this.scopeManager.__isNodejsScope()) { + types.dollarBraceL.updateContext = function() { + this.context.push(types$1.b_tmpl); + this.exprAllowed = true; + }; - // Force strictness of GlobalScope to false when using node.js scope. - this.currentScope().isStrict = false; - this.scopeManager.__nestFunctionScope(node, false); - } + types.parenL.updateContext = function(prevType) { + var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; + this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); + this.exprAllowed = true; + }; - if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { - this.scopeManager.__nestModuleScope(node); - } + types.incDec.updateContext = function() { + // tokExprAllowed stays unchanged + }; - if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) { - this.currentScope().isStrict = true; - } + types._function.updateContext = types._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types._else && + !(prevType === types.semi && this.curContext() !== types$1.p_stat) && + !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && + !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) + { this.context.push(types$1.f_expr); } + else + { this.context.push(types$1.f_stat); } + this.exprAllowed = false; + }; - this.visitChildren(node); - this.close(node); - } + types.backQuote.updateContext = function() { + if (this.curContext() === types$1.q_tmpl) + { this.context.pop(); } + else + { this.context.push(types$1.q_tmpl); } + this.exprAllowed = false; + }; - Identifier(node) { - this.currentScope().__referencing(node); + types.star.updateContext = function(prevType) { + if (prevType === types._function) { + var index = this.context.length - 1; + if (this.context[index] === types$1.f_expr) + { this.context[index] = types$1.f_expr_gen; } + else + { this.context[index] = types$1.f_gen; } } + this.exprAllowed = true; + }; - UpdateExpression(node) { - if (PatternVisitor.isPattern(node.argument)) { - this.currentScope().__referencing(node.argument, Reference.RW, null); - } else { - this.visitChildren(node); - } + types.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types.dot) { + if (this.value === "of" && !this.exprAllowed || + this.value === "yield" && this.inGeneratorContext()) + { allowed = true; } } + this.exprAllowed = allowed; + }; - MemberExpression(node) { - this.visit(node.object); - if (node.computed) { - this.visit(node.property); + // A recursive descent parser operates by defining functions for all + + var pp$4 = Parser.prototype; + + // Check if property name clashes with already added. + // Object/class getters and setters are not allowed to clash — + // either with each other or with an init property — and in + // strict mode, init properties are also not allowed to be repeated. + + pp$4.checkPropClash = function(prop, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") + { return } + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) + { return } + var key = prop.key; + var name; + switch (key.type) { + case "Identifier": name = key.name; break + case "Literal": name = String(key.value); break + default: return + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors) { + if (refDestructuringErrors.doubleProto < 0) + { refDestructuringErrors.doubleProto = key.start; } + // Backwards-compat kludge. Can be removed in version 6.0 + } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } } + propHash.proto = true; + } + return } + name = "$" + name; + var other = propHash[name]; + if (other) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other.init || other.get || other.set; + } else { + redefinition = other.init || other[kind]; + } + if (redefinition) + { this.raiseRecoverable(key.start, "Redefinition of property"); } + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other[kind] = true; + }; - Property(node) { - this.visitProperty(node); + // ### Expression parsing + + // These nest, from the most general expression type at the top to + // 'atomic', nondivisible expression types at the bottom. Most of + // the functions will simply let the function(s) below them parse, + // and, *if* the syntactic construct they handle is present, wrap + // the AST node that the inner parser gave them in another node. + + // Parse a full expression. The optional arguments are used to + // forbid the `in` operator (in for loops initalization expressions) + // and provide reference for storing '=' operator inside shorthand + // property assignment in contexts where both object expression + // and object pattern might appear (so it's possible to raise + // delayed syntax error at correct position). + + pp$4.parseExpression = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); + if (this.type === types.comma) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } + return this.finishNode(node, "SequenceExpression") } + return expr + }; - MethodDefinition(node) { - this.visitProperty(node); + // Parse an assignment expression. This includes applications of + // operators like `+=`. + + pp$4.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { return this.parseYield(forInit) } + // The tokenizer will assume an expression is allowed after + // `yield`, but this isn't that kind of yield + else { this.exprAllowed = false; } } - BreakStatement() {} // eslint-disable-line class-methods-use-this + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors; + ownDestructuringErrors = true; + } - ContinueStatement() {} // eslint-disable-line class-methods-use-this + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types.parenL || this.type === types.name) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + var left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + if (this.type === types.eq) + { left = this.toAssignable(left, false, refDestructuringErrors); } + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) + { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly + if (this.type === types.eq) + { this.checkLValPattern(left); } + else + { this.checkLValSimple(left); } + node.left = left; + this.next(); + node.right = this.parseMaybeAssign(forInit); + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } + } + if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } + if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } + return left + }; - LabeledStatement(node) { - this.visit(node.body); + // Parse a ternary conditional (`?:`) operator. + + pp$4.parseMaybeConditional = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + if (this.eat(types.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types.colon); + node.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node, "ConditionalExpression") } + return expr + }; - ForStatement(node) { + // Start the precedence parser. - // Create ForStatement declaration. - // NOTE: In ES6, ForStatement dynamically generates - // per iteration environment. However, escope is - // a static analyzer, we only generate one scope for ForStatement. - if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") { - this.scopeManager.__nestForScope(node); + pp$4.parseExprOps = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) + }; + + // Parse binary operators with the operator precedence parsing + // algorithm. `left` is the left-hand side of the operator. + // `minPrec` provides context that allows the function to stop and + // defer further parser to one of its callers when it encounters an + // operator that has a lower precedence than the set it is parsing. + + pp$4.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { + var prec = this.type.binop; + if (prec != null && (!forInit || this.type !== types._in)) { + if (prec > minPrec) { + var logical = this.type === types.logicalOR || this.type === types.logicalAND; + var coalesce = this.type === types.coalesce; + if (coalesce) { + // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. + // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. + prec = types.logicalAND.binop; + } + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); + if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) { + this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); } + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) + } + } + return left + }; - this.visitChildren(node); + pp$4.buildBinary = function(startPos, startLoc, left, right, op, logical) { + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.operator = op; + node.right = right; + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") + }; - this.close(node); + // Parse unary operators, both prefix and postfix. + + pp$4.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && this.canAwait) { + expr = this.parseAwait(forInit); + sawUnary = true; + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === types.incDec; + node.operator = this.value; + node.prefix = true; + this.next(); + node.argument = this.parseMaybeUnary(null, true, update, forInit); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { this.checkLValSimple(node.argument); } + else if (this.strict && node.operator === "delete" && + node.argument.type === "Identifier") + { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } + else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) + { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } + else { sawUnary = true; } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else { + expr = this.parseExprSubscripts(refDestructuringErrors, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.operator = this.value; + node$1.prefix = false; + node$1.argument = expr; + this.checkLValSimple(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } } - ClassExpression(node) { - this.visitClass(node); + if (!incDec && this.eat(types.starstar)) { + if (sawUnary) + { this.unexpected(this.lastTokStart); } + else + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } + } else { + return expr } + }; - ClassDeclaration(node) { - this.visitClass(node); - } + function isPrivateFieldAccess(node) { + return ( + node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || + node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) + ) + } - CallExpression(node) { + // Parse call, dot, and `[]`-subscript expressions. + + pp$4.parseExprSubscripts = function(refDestructuringErrors, forInit) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors, forInit); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") + { return expr } + var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } + if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } + if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } + } + return result + }; - // Check this is direct call to eval - if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") { + pp$4.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && + this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && + this.potentialArrowAt === base.start; + var optionalChained = false; - // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and - // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. - this.currentScope().variableScope.__detectEval(); + while (true) { + var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); + + if (element.optional) { optionalChained = true; } + if (element === base || element.type === "ArrowFunctionExpression") { + if (optionalChained) { + var chainNode = this.startNodeAt(startPos, startLoc); + chainNode.expression = element; + element = this.finishNode(chainNode, "ChainExpression"); } - this.visitChildren(node); + return element + } + + base = element; } + }; - BlockStatement(node) { - if (this.scopeManager.__isES6()) { - this.scopeManager.__nestBlockScope(node); + pp$4.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { + var optionalSupported = this.options.ecmaVersion >= 11; + var optional = optionalSupported && this.eat(types.questionDot); + if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } + + var computed = this.eat(types.bracketL); + if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + if (computed) { + node.property = this.parseExpression(); + this.expect(types.bracketR); + } else if (this.type === types.privateId && base.type !== "Super") { + node.property = this.parsePrivateIdent(); + } else { + node.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node.computed = !!computed; + if (optionalSupported) { + node.optional = optional; + } + base = this.finishNode(node, "MemberExpression"); + } else if (!noCalls && this.eat(types.parenL)) { + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) + { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.callee = base; + node$1.arguments = exprList; + if (optionalSupported) { + node$1.optional = optional; + } + base = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types.backQuote) { + if (optional || optionalChained) { + this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + } + var node$2 = this.startNodeAt(startPos, startLoc); + node$2.tag = base; + node$2.quasi = this.parseTemplate({isTagged: true}); + base = this.finishNode(node$2, "TaggedTemplateExpression"); + } + return base + }; + + // Parse an atomic expression — either a single token that is an + // expression, an expression started by a keyword like `function` or + // `new`, or an expression wrapped in punctuation like `()`, `[]`, + // or `{}`. + + pp$4.parseExprAtom = function(refDestructuringErrors, forInit) { + // If a division operator appears in an expression position, the + // tokenizer got confused, and we force it to read a regexp instead. + if (this.type === types.slash) { this.readRegexp(); } + + var node, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types._super: + if (!this.allowSuper) + { this.raise(this.start, "'super' keyword outside a method"); } + node = this.startNode(); + this.next(); + if (this.type === types.parenL && !this.allowDirectSuper) + { this.raise(node.start, "super() call outside constructor of a subclass"); } + // The `super` keyword can appear at below: + // SuperProperty: + // super [ Expression ] + // super . IdentifierName + // SuperCall: + // super ( Arguments ) + if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) + { this.unexpected(); } + return this.finishNode(node, "Super") + + case types._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression") + + case types.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id = this.parseIdent(false); + if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) { + this.overrideContext(types$1.f_expr); + return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) + } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types.arrow)) + { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc && + (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types.arrow)) + { this.unexpected(); } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) } + } + return id - this.visitChildren(node); + case types.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = {pattern: value.pattern, flags: value.flags}; + return node - this.close(node); - } + case types.num: case types.string: + return this.parseLiteral(this.value) - ThisExpression() { - this.currentScope().variableScope.__detectThis(); - } + case types._null: case types._true: case types._false: + node = this.startNode(); + node.value = this.type === types._null ? null : this.type === types._true; + node.raw = this.type.keyword; + this.next(); + return this.finishNode(node, "Literal") + + case types.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) + { refDestructuringErrors.parenthesizedAssign = start; } + if (refDestructuringErrors.parenthesizedBind < 0) + { refDestructuringErrors.parenthesizedBind = start; } + } + return expr - WithStatement(node) { - this.visit(node.object); + case types.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression") - // Then nest scope for WithStatement. - this.scopeManager.__nestWithScope(node); + case types.braceL: + this.overrideContext(types$1.b_expr); + return this.parseObj(false, refDestructuringErrors) - this.visit(node.body); + case types._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0) - this.close(node); - } + case types._class: + return this.parseClass(this.startNode(), false) - VariableDeclaration(node) { - const variableTargetScope = (node.kind === "var") ? this.currentScope().variableScope : this.currentScope(); + case types._new: + return this.parseNew() - for (let i = 0, iz = node.declarations.length; i < iz; ++i) { - const decl = node.declarations[i]; + case types.backQuote: + return this.parseTemplate() - this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i); - if (decl.init) { - this.visit(decl.init); - } - } - } + case types._import: + if (this.options.ecmaVersion >= 11) { + return this.parseExprImport() + } else { + return this.unexpected() + } - // sec 13.11.8 - SwitchStatement(node) { - this.visit(node.discriminant); + default: + this.unexpected(); + } + }; - if (this.scopeManager.__isES6()) { - this.scopeManager.__nestSwitchScope(node); - } + pp$4.parseExprImport = function() { + var node = this.startNode(); - for (let i = 0, iz = node.cases.length; i < iz; ++i) { - this.visit(node.cases[i]); - } + // Consume `import` as an identifier for `import.meta`. + // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } + var meta = this.parseIdent(true); - this.close(node); + switch (this.type) { + case types.parenL: + return this.parseDynamicImport(node) + case types.dot: + node.meta = meta; + return this.parseImportMeta(node) + default: + this.unexpected(); } + }; - FunctionDeclaration(node) { - this.visitFunction(node); - } + pp$4.parseDynamicImport = function(node) { + this.next(); // skip `(` - FunctionExpression(node) { - this.visitFunction(node); - } + // Parse node.source. + node.source = this.parseMaybeAssign(); - ForOfStatement(node) { - this.visitForIn(node); + // Verify ending. + if (!this.eat(types.parenR)) { + var errorPos = this.start; + if (this.eat(types.comma) && this.eat(types.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } } - ForInStatement(node) { - this.visitForIn(node); - } + return this.finishNode(node, "ImportExpression") + }; - ArrowFunctionExpression(node) { - this.visitFunction(node); - } + pp$4.parseImportMeta = function(node) { + this.next(); // skip `.` - ImportDeclaration(node) { - assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context."); + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); - const importer = new Importer(node, this); + if (node.property.name !== "meta") + { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } + if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) + { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } - importer.visit(node); - } + return this.finishNode(node, "MetaProperty") + }; - visitExportDeclaration(node) { - if (node.source) { - return; - } - if (node.declaration) { - this.visit(node.declaration); - return; + pp$4.parseLiteral = function(value) { + var node = this.startNode(); + node.value = value; + node.raw = this.input.slice(this.start, this.end); + if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } + this.next(); + return this.finishNode(node, "Literal") + }; + + pp$4.parseParenExpression = function() { + this.expect(types.parenL); + var val = this.parseExpression(); + this.expect(types.parenR); + return val + }; + + pp$4.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + // Do not save awaitIdentPos to allow checking awaits nested in parameters + while (this.type !== types.parenR) { + first ? first = false : this.expect(types.comma); + if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) { + lastIsComma = true; + break + } else if (this.type === types.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } + break + } else { + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); } + } + var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; + this.expect(types.parenR); + + if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList, forInit) + } - this.visitChildren(node); + if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } + if (spreadStart) { this.unexpected(spreadStart); } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); } - // TODO: ExportDeclaration doesn't exist. for bc? - ExportDeclaration(node) { - this.visitExportDeclaration(node); + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression") + } else { + return val } + }; - ExportAllDeclaration(node) { - this.visitExportDeclaration(node); + pp$4.parseParenItem = function(item) { + return item + }; + + pp$4.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, forInit) + }; + + // New's precedence is slightly tricky. It must allow its argument to + // be a `[]` or dot subscript expression, but not a call — at least, + // not without wrapping it in parentheses. Thus, it uses the noCalls + // argument to parseSubscripts to prevent it from consuming the + // argument list. + + var empty$1 = []; + + pp$4.parseNew = function() { + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } + var node = this.startNode(); + var meta = this.parseIdent(true); + if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) { + node.meta = meta; + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target") + { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } + if (!this.allowNewDotTarget) + { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import; + node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false); + if (isImport && node.callee.type === "ImportExpression") { + this.raise(startPos, "Cannot use new with import()"); } + if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); } + else { node.arguments = empty$1; } + return this.finishNode(node, "NewExpression") + }; - ExportDefaultDeclaration(node) { - this.visitExportDeclaration(node); + // Parse template expression. + + pp$4.parseTemplateElement = function(ref) { + var isTagged = ref.isTagged; + + var elem = this.startNode(); + if (this.type === types.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value, + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; } + this.next(); + elem.tail = this.type === types.backQuote; + return this.finishNode(elem, "TemplateElement") + }; - ExportNamedDeclaration(node) { - this.visitExportDeclaration(node); + pp$4.parseTemplate = function(ref) { + if ( ref === void 0 ) ref = {}; + var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; + + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement({isTagged: isTagged}); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); } + this.expect(types.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(types.braceR); + node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); } + this.next(); + return this.finishNode(node, "TemplateLiteral") + }; - ExportSpecifier(node) { + pp$4.isAsyncProp = function(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && + (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) && + !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; - // TODO: `node.id` doesn't exist. for bc? - const local = (node.id || node.local); + // Parse an object literal or binding pattern. + + pp$4.parseObj = function(isPattern, refDestructuringErrors) { + var node = this.startNode(), first = true, propHash = {}; + node.properties = []; + this.next(); + while (!this.eat(types.braceR)) { + if (!first) { + this.expect(types.comma); + if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break } + } else { first = false; } + + var prop = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } + node.properties.push(prop); + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") + }; - this.visit(local); + pp$4.parseProperty = function(isPattern, refDestructuringErrors) { + var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { + if (isPattern) { + prop.argument = this.parseIdent(false); + if (this.type === types.comma) { + this.raise(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop, "RestElement") + } + // To disallow parenthesized identifier via `this.toAssignable()`. + if (this.type === types.parenL && refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0) { + refDestructuringErrors.parenthesizedAssign = this.start; + } + if (refDestructuringErrors.parenthesizedBind < 0) { + refDestructuringErrors.parenthesizedBind = this.start; + } + } + // Parse argument. + prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); + // To disallow trailing comma via `this.toAssignable()`. + if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + // Finish + return this.finishNode(prop, "SpreadElement") + } + if (this.options.ecmaVersion >= 6) { + prop.method = false; + prop.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) + { isGenerator = this.eat(types.star); } } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); + this.parsePropertyName(prop, refDestructuringErrors); + } else { + isAsync = false; + } + this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop, "Property") + }; - MetaProperty() { // eslint-disable-line class-methods-use-this + pp$4.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types.colon) + { this.unexpected(); } + + if (this.eat(types.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) { + if (isPattern) { this.unexpected(); } + prop.kind = "init"; + prop.method = true; + prop.value = this.parseMethod(isGenerator, isAsync); + } else if (!isPattern && !containsEsc && + this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set") && + (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) { + if (isGenerator || isAsync) { this.unexpected(); } + prop.kind = prop.key.name; + this.parsePropertyName(prop); + prop.value = this.parseMethod(false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.value.params.length !== paramCount) { + var start = prop.value.start; + if (prop.kind === "get") + { this.raiseRecoverable(start, "getter should have no params"); } + else + { this.raiseRecoverable(start, "setter should have exactly one param"); } + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") + { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } + } + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (isGenerator || isAsync) { this.unexpected(); } + this.checkUnreserved(prop.key); + if (prop.key.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = startPos; } + prop.kind = "init"; + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else if (this.type === types.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) + { refDestructuringErrors.shorthandAssign = this.start; } + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else { + prop.value = this.copyNode(prop.key); + } + prop.shorthand = true; + } else { this.unexpected(); } + }; - // do nothing. + pp$4.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types.bracketR); + return prop.key + } else { + prop.computed = false; + } } -} + return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") + }; -module.exports = Referencer; + // Initialize empty function node. -/* vim: set sw=4 ts=4 et tw=80 : */ + pp$4.initFunction = function(node) { + node.id = null; + if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } + if (this.options.ecmaVersion >= 8) { node.async = false; } + }; + // Parse object or class method. -/***/ }), + pp$4.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; -/***/ 96988: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.initFunction(node); + if (this.options.ecmaVersion >= 6) + { node.generator = isGenerator; } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + this.expect(types.parenL); + node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true, false); - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression") + }; - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + // Parse arrow function expression with given parameters. + pp$4.parseArrowExpression = function(node, params, isAsync, forInit) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; -/* eslint-disable no-underscore-dangle */ + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } -const Scope = __webpack_require__(16313); -const assert = __webpack_require__(39491); + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; -const GlobalScope = Scope.GlobalScope; -const CatchScope = Scope.CatchScope; -const WithScope = Scope.WithScope; -const ModuleScope = Scope.ModuleScope; -const ClassScope = Scope.ClassScope; -const SwitchScope = Scope.SwitchScope; -const FunctionScope = Scope.FunctionScope; -const ForScope = Scope.ForScope; -const FunctionExpressionNameScope = Scope.FunctionExpressionNameScope; -const BlockScope = Scope.BlockScope; + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true, false, forInit); -/** - * @class ScopeManager - */ -class ScopeManager { - constructor(options) { - this.scopes = []; - this.globalScope = null; - this.__nodeToScope = new WeakMap(); - this.__currentScope = null; - this.__options = options; - this.__declaredVariables = new WeakMap(); - } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression") + }; - __useDirective() { - return this.__options.directive; - } + // Parse function body and check parameters. - __isOptimistic() { - return this.__options.optimistic; - } + pp$4.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { + var isExpression = isArrowFunction && this.type !== types.braceL; + var oldStrict = this.strict, useStrict = false; - __ignoreEval() { - return this.__options.ignoreEval; + if (isExpression) { + node.body = this.parseMaybeAssign(forInit); + node.expression = true; + this.checkParams(node, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + if (useStrict && nonSimple) + { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } + } + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { this.strict = true; } + + // Add the params to varDeclaredNames to ensure that an error is thrown + // if a let/const declaration in the function clashes with one of the params. + this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); + // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' + if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } + node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; } + this.exitScope(); + }; - __isNodejsScope() { - return this.__options.nodejsScope; + pp$4.isSimpleParamList = function(params) { + for (var i = 0, list = params; i < list.length; i += 1) + { + var param = list[i]; + + if (param.type !== "Identifier") { return false + } } + return true + }; + + // Checks function params for various disallowed patterns such as using "eval" + // or "arguments" and duplicate parameters. + + pp$4.checkParams = function(node, allowDuplicates) { + var nameHash = Object.create(null); + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); } + }; - isModule() { - return this.__options.sourceType === "module"; + // Parses a comma-separated list of expressions, and returns them as + // an array. `close` is the token type that ends the list, and + // `allowEmpty` can be turned on to allow subsequent commas with + // nothing in between them to be parsed as `null` (which is needed + // for array literals). + + pp$4.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var elts = [], first = true; + while (!this.eat(close)) { + if (!first) { + this.expect(types.comma); + if (allowTrailingComma && this.afterTrailingComma(close)) { break } + } else { first = false; } + + var elt = (void 0); + if (allowEmpty && this.type === types.comma) + { elt = null; } + else if (this.type === types.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0) + { refDestructuringErrors.trailingComma = this.start; } + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); } + return elts + }; - isImpliedStrict() { - return this.__options.impliedStrict; + pp$4.checkUnreserved = function(ref) { + var start = ref.start; + var end = ref.end; + var name = ref.name; + + if (this.inGenerator && name === "yield") + { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } + if (this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } + if (this.currentThisScope().inClassFieldInit && name === "arguments") + { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } + if (this.inClassStaticBlock && (name === "arguments" || name === "await")) + { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } + if (this.keywords.test(name)) + { this.raise(start, ("Unexpected keyword '" + name + "'")); } + if (this.options.ecmaVersion < 6 && + this.input.slice(start, end).indexOf("\\") !== -1) { return } + var re = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re.test(name)) { + if (!this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } + this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); } + }; - isStrictModeSupported() { - return this.__options.ecmaVersion >= 5; + // Parse the next token as an identifier. If `liberal` is true (used + // when parsing properties), it will also convert keywords into + // identifiers. + + pp$4.parseIdent = function(liberal, isBinding) { + var node = this.startNode(); + if (this.type === types.name) { + node.name = this.value; + } else if (this.type.keyword) { + node.name = this.type.keyword; + + // To fix https://github.com/acornjs/acorn/issues/575 + // `class` and `function` keywords push new context into this.context. + // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. + // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword + if ((node.name === "class" || node.name === "function") && + (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + } else { + this.unexpected(); } + this.next(!!liberal); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = node.start; } + } + return node + }; - // Returns appropriate scope for this node. - __get(node) { - return this.__nodeToScope.get(node); + pp$4.parsePrivateIdent = function() { + var node = this.startNode(); + if (this.type === types.privateId) { + node.name = this.value; + } else { + this.unexpected(); } + this.next(); + this.finishNode(node, "PrivateIdentifier"); - /** - * Get variables that are declared by the node. - * - * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`. - * If the node declares nothing, this method returns an empty array. - * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details. - * - * @param {Espree.Node} node - a node to get. - * @returns {Variable[]} variables that declared by the node. - */ - getDeclaredVariables(node) { - return this.__declaredVariables.get(node) || []; + // For validating existence + if (this.privateNameStack.length === 0) { + this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); + } else { + this.privateNameStack[this.privateNameStack.length - 1].used.push(node); } - /** - * acquire scope from node. - * @method ScopeManager#acquire - * @param {Espree.Node} node - node for the acquired scope. - * @param {boolean=} inner - look up the most inner scope, default value is false. - * @returns {Scope?} Scope from node - */ - acquire(node, inner) { + return node + }; - /** - * predicate - * @param {Scope} testScope - scope to test - * @returns {boolean} predicate - */ - function predicate(testScope) { - if (testScope.type === "function" && testScope.functionExpressionScope) { - return false; - } - return true; - } + // Parses yield expression inside generator. - const scopes = this.__get(node); + pp$4.parseYield = function(forInit) { + if (!this.yieldPos) { this.yieldPos = this.start; } - if (!scopes || scopes.length === 0) { - return null; - } + var node = this.startNode(); + this.next(); + if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types.star); + node.argument = this.parseMaybeAssign(forInit); + } + return this.finishNode(node, "YieldExpression") + }; - // Heuristic selection from all scopes. - // If you would like to get all scopes, please use ScopeManager#acquireAll. - if (scopes.length === 1) { - return scopes[0]; - } + pp$4.parseAwait = function(forInit) { + if (!this.awaitPos) { this.awaitPos = this.start; } - if (inner) { - for (let i = scopes.length - 1; i >= 0; --i) { - const scope = scopes[i]; + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true, false, forInit); + return this.finishNode(node, "AwaitExpression") + }; - if (predicate(scope)) { - return scope; - } - } - } else { - for (let i = 0, iz = scopes.length; i < iz; ++i) { - const scope = scopes[i]; + var pp$5 = Parser.prototype; - if (predicate(scope)) { - return scope; - } - } - } + // This function is used to raise exceptions on parse errors. It + // takes an offset integer (into the current `input`) to indicate + // the location of the error, attaches the position to the end + // of the error message, and then raises a `SyntaxError` with that + // message. - return null; - } + pp$5.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + var err = new SyntaxError(message); + err.pos = pos; err.loc = loc; err.raisedAt = this.pos; + throw err + }; - /** - * acquire all scopes from node. - * @method ScopeManager#acquireAll - * @param {Espree.Node} node - node for the acquired scope. - * @returns {Scopes?} Scope array - */ - acquireAll(node) { - return this.__get(node); + pp$5.raiseRecoverable = pp$5.raise; + + pp$5.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) } + }; - /** - * release the node. - * @method ScopeManager#release - * @param {Espree.Node} node - releasing node. - * @param {boolean=} inner - look up the most inner scope, default value is false. - * @returns {Scope?} upper scope for the node. - */ - release(node, inner) { - const scopes = this.__get(node); + var pp$6 = Parser.prototype; + + var Scope = function Scope(flags) { + this.flags = flags; + // A list of var-declared names in the current lexical scope + this.var = []; + // A list of lexically-declared names in the current lexical scope + this.lexical = []; + // A list of lexically-declared FunctionDeclaration names in the current lexical scope + this.functions = []; + // A switch to disallow the identifier reference 'arguments' + this.inClassFieldInit = false; + }; - if (scopes && scopes.length) { - const scope = scopes[0].upper; + // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. - if (!scope) { - return null; - } - return this.acquire(scope.block, inner); - } - return null; - } + pp$6.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); + }; - attach() { } // eslint-disable-line class-methods-use-this + pp$6.exitScope = function() { + this.scopeStack.pop(); + }; - detach() { } // eslint-disable-line class-methods-use-this + // The spec says: + // > At the top level of a function, or script, function declarations are + // > treated like var declarations rather than like lexical declarations. + pp$6.treatFunctionsAsVarInScope = function(scope) { + return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) + }; - __nestScope(scope) { - if (scope instanceof GlobalScope) { - assert(this.__currentScope === null); - this.globalScope = scope; + pp$6.declareName = function(name, bindingType, pos) { + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + if (this.inModule && (scope.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + if (this.treatFunctionsAsVar) + { redeclared = scope$2.lexical.indexOf(name) > -1; } + else + { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } + scope$2.functions.push(name); + } else { + for (var i = this.scopeStack.length - 1; i >= 0; --i) { + var scope$3 = this.scopeStack[i]; + if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || + !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { + redeclared = true; + break } - this.__currentScope = scope; - return scope; + scope$3.var.push(name); + if (this.inModule && (scope$3.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + if (scope$3.flags & SCOPE_VAR) { break } + } } + if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } + }; - __nestGlobalScope(node) { - return this.__nestScope(new GlobalScope(this, node)); + pp$6.checkLocalExport = function(id) { + // scope.functions must be empty as Module code is always strict. + if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && + this.scopeStack[0].var.indexOf(id.name) === -1) { + this.undefinedExports[id.name] = id; } + }; - __nestBlockScope(node) { - return this.__nestScope(new BlockScope(this, this.__currentScope, node)); - } + pp$6.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] + }; - __nestFunctionScope(node, isMethodDefinition) { - return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + pp$6.currentVarScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR) { return scope } } + }; - __nestForScope(node) { - return this.__nestScope(new ForScope(this, this.__currentScope, node)); + // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. + pp$6.currentThisScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } } + }; - __nestCatchScope(node) { - return this.__nestScope(new CatchScope(this, this.__currentScope, node)); - } - - __nestWithScope(node) { - return this.__nestScope(new WithScope(this, this.__currentScope, node)); - } - - __nestClassScope(node) { - return this.__nestScope(new ClassScope(this, this.__currentScope, node)); - } - - __nestSwitchScope(node) { - return this.__nestScope(new SwitchScope(this, this.__currentScope, node)); - } + var Node = function Node(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser.options.locations) + { this.loc = new SourceLocation(parser, loc); } + if (parser.options.directSourceFile) + { this.sourceFile = parser.options.directSourceFile; } + if (parser.options.ranges) + { this.range = [pos, 0]; } + }; - __nestModuleScope(node) { - return this.__nestScope(new ModuleScope(this, this.__currentScope, node)); - } + // Start an AST node, attaching a start offset. - __nestFunctionExpressionNameScope(node) { - return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node)); - } + var pp$7 = Parser.prototype; - __isES6() { - return this.__options.ecmaVersion >= 6; - } -} + pp$7.startNode = function() { + return new Node(this, this.start, this.startLoc) + }; -module.exports = ScopeManager; + pp$7.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) + }; -/* vim: set sw=4 ts=4 et tw=80 : */ + // Finish an AST node, adding `type` and `end` properties. + function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + if (this.options.locations) + { node.loc.end = loc; } + if (this.options.ranges) + { node.range[1] = pos; } + return node + } -/***/ }), + pp$7.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) + }; -/***/ 16313: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Finish node at given position -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki + pp$7.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) + }; - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + pp$7.copyNode = function(node) { + var newNode = new Node(this, node.start, this.startLoc); + for (var prop in node) { newNode[prop] = node[prop]; } + return newNode + }; - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + // This file contains Unicode properties extracted from the ECMAScript + // specification. The lists are extracted like so: + // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) + + // #table-binary-unicode-properties + var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; + var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; + var ecma11BinaryProperties = ecma10BinaryProperties; + var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; + var unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties, + 12: ecma12BinaryProperties + }; - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + // #table-unicode-general-category-values + var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; + + // #table-unicode-script-values + var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; + var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; + var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; + var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; + var unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues, + 12: ecma12ScriptValues + }; + var data = {}; + function buildUnicodeData(ecmaVersion) { + var d = data[ecmaVersion] = { + binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), + nonBinary: { + General_Category: wordsRegexp(unicodeGeneralCategoryValues), + Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) + } + }; + d.nonBinary.Script_Extensions = d.nonBinary.Script; -/* eslint-disable no-underscore-dangle */ -/* eslint-disable no-undefined */ + d.nonBinary.gc = d.nonBinary.General_Category; + d.nonBinary.sc = d.nonBinary.Script; + d.nonBinary.scx = d.nonBinary.Script_Extensions; + } + buildUnicodeData(9); + buildUnicodeData(10); + buildUnicodeData(11); + buildUnicodeData(12); + + var pp$8 = Parser.prototype; + + var RegExpValidationState = function RegExpValidationState(parser) { + this.parser = parser; + this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : ""); + this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion]; + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = []; + this.backReferenceNames = []; + }; -const Syntax = (__webpack_require__(18350).Syntax); + RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; + }; -const Reference = __webpack_require__(64945); -const Variable = __webpack_require__(82971); -const Definition = (__webpack_require__(70665).Definition); -const assert = __webpack_require__(39491); + RegExpValidationState.prototype.raise = function raise (message) { + this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); + }; -/** - * Test if scope is struct - * @param {Scope} scope - scope - * @param {Block} block - block - * @param {boolean} isMethodDefinition - is method definition - * @param {boolean} useDirective - use directive - * @returns {boolean} is strict scope - */ -function isStrictScope(scope, block, isMethodDefinition, useDirective) { - let body; + // If u flag is given, this returns the code point at the index (it combines a surrogate pair). + // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). + RegExpValidationState.prototype.at = function at (i, forceU) { + if ( forceU === void 0 ) forceU = false; - // When upper scope is exists and strict, inner scope is also strict. - if (scope.upper && scope.upper.isStrict) { - return true; + var s = this.source; + var l = s.length; + if (i >= l) { + return -1 } - - if (isMethodDefinition) { - return true; + var c = s.charCodeAt(i); + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { + return c } + var next = s.charCodeAt(i + 1); + return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c + }; - if (scope.type === "class" || scope.type === "module") { - return true; - } + RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { + if ( forceU === void 0 ) forceU = false; - if (scope.type === "block" || scope.type === "switch") { - return false; + var s = this.source; + var l = s.length; + if (i >= l) { + return l + } + var c = s.charCodeAt(i), next; + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || + (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { + return i + 1 } + return i + 2 + }; - if (scope.type === "function") { - if (block.type === Syntax.ArrowFunctionExpression && block.body.type !== Syntax.BlockStatement) { - return false; - } + RegExpValidationState.prototype.current = function current (forceU) { + if ( forceU === void 0 ) forceU = false; - if (block.type === Syntax.Program) { - body = block; - } else { - body = block.body; - } + return this.at(this.pos, forceU) + }; - if (!body) { - return false; - } - } else if (scope.type === "global") { - body = block; - } else { - return false; - } + RegExpValidationState.prototype.lookahead = function lookahead (forceU) { + if ( forceU === void 0 ) forceU = false; - // Search 'use strict' directive. - if (useDirective) { - for (let i = 0, iz = body.body.length; i < iz; ++i) { - const stmt = body.body[i]; + return this.at(this.nextIndex(this.pos, forceU), forceU) + }; - if (stmt.type !== Syntax.DirectiveStatement) { - break; - } - if (stmt.raw === "\"use strict\"" || stmt.raw === "'use strict'") { - return true; - } - } - } else { - for (let i = 0, iz = body.body.length; i < iz; ++i) { - const stmt = body.body[i]; + RegExpValidationState.prototype.advance = function advance (forceU) { + if ( forceU === void 0 ) forceU = false; - if (stmt.type !== Syntax.ExpressionStatement) { - break; - } - const expr = stmt.expression; + this.pos = this.nextIndex(this.pos, forceU); + }; - if (expr.type !== Syntax.Literal || typeof expr.value !== "string") { - break; - } - if (expr.raw !== null && expr.raw !== undefined) { - if (expr.raw === "\"use strict\"" || expr.raw === "'use strict'") { - return true; - } - } else { - if (expr.value === "use strict") { - return true; - } - } - } - } - return false; -} + RegExpValidationState.prototype.eat = function eat (ch, forceU) { + if ( forceU === void 0 ) forceU = false; -/** - * Register scope - * @param {ScopeManager} scopeManager - scope manager - * @param {Scope} scope - scope - * @returns {void} - */ -function registerScope(scopeManager, scope) { - scopeManager.scopes.push(scope); + if (this.current(forceU) === ch) { + this.advance(forceU); + return true + } + return false + }; - const scopes = scopeManager.__nodeToScope.get(scope.block); + function codePointToString(ch) { + if (ch <= 0xFFFF) { return String.fromCharCode(ch) } + ch -= 0x10000; + return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) + } - if (scopes) { - scopes.push(scope); - } else { - scopeManager.__nodeToScope.set(scope.block, [scope]); + /** + * Validate the flags part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$8.validateRegExpFlags = function(state) { + var validFlags = state.validFlags; + var flags = state.flags; + + for (var i = 0; i < flags.length; i++) { + var flag = flags.charAt(i); + if (validFlags.indexOf(flag) === -1) { + this.raise(state.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i + 1) > -1) { + this.raise(state.start, "Duplicate regular expression flag"); + } } -} + }; -/** - * Should be statically - * @param {Object} def - def - * @returns {boolean} should be statically - */ -function shouldBeStatically(def) { - return ( - (def.type === Variable.ClassName) || - (def.type === Variable.Variable && def.parent.kind !== "var") - ); -} + /** + * Validate the pattern part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$8.validateRegExpPattern = function(state) { + this.regexp_pattern(state); + + // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of + // parsing contains a |GroupName|, reparse with the goal symbol + // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* + // exception if _P_ did not conform to the grammar, if any elements of _P_ + // were not matched by the parse, or if any Early Error conditions exist. + if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { + state.switchN = true; + this.regexp_pattern(state); + } + }; -/** - * @class Scope - */ -class Scope { - constructor(scopeManager, type, upperScope, block, isMethodDefinition) { + // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern + pp$8.regexp_pattern = function(state) { + state.pos = 0; + state.lastIntValue = 0; + state.lastStringValue = ""; + state.lastAssertionIsQuantifiable = false; + state.numCapturingParens = 0; + state.maxBackReference = 0; + state.groupNames.length = 0; + state.backReferenceNames.length = 0; + + this.regexp_disjunction(state); + + if (state.pos !== state.source.length) { + // Make the same messages as V8. + if (state.eat(0x29 /* ) */)) { + state.raise("Unmatched ')'"); + } + if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { + state.raise("Lone quantifier brackets"); + } + } + if (state.maxBackReference > state.numCapturingParens) { + state.raise("Invalid escape"); + } + for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { + var name = list[i]; - /** - * One of 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'. - * @member {String} Scope#type - */ - this.type = type; + if (state.groupNames.indexOf(name) === -1) { + state.raise("Invalid named capture referenced"); + } + } + }; - /** - * The scoped {@link Variable}s of this scope, as { Variable.name - * : Variable }. - * @member {Map} Scope#set - */ - this.set = new Map(); + // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction + pp$8.regexp_disjunction = function(state) { + this.regexp_alternative(state); + while (state.eat(0x7C /* | */)) { + this.regexp_alternative(state); + } - /** - * The tainted variables of this scope, as { Variable.name : - * boolean }. - * @member {Map} Scope#taints */ - this.taints = new Map(); + // Make the same message as V8. + if (this.regexp_eatQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + if (state.eat(0x7B /* { */)) { + state.raise("Lone quantifier brackets"); + } + }; - /** - * Generally, through the lexical scoping of JS you can always know - * which variable an identifier in the source code refers to. There are - * a few exceptions to this rule. With 'global' and 'with' scopes you - * can only decide at runtime which variable a reference refers to. - * Moreover, if 'eval()' is used in a scope, it might introduce new - * bindings in this or its parent scopes. - * All those scopes are considered 'dynamic'. - * @member {boolean} Scope#dynamic - */ - this.dynamic = this.type === "global" || this.type === "with"; + // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative + pp$8.regexp_alternative = function(state) { + while (state.pos < state.source.length && this.regexp_eatTerm(state)) + { } + }; - /** - * A reference to the scope-defining syntax node. - * @member {espree.Node} Scope#block - */ - this.block = block; + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term + pp$8.regexp_eatTerm = function(state) { + if (this.regexp_eatAssertion(state)) { + // Handle `QuantifiableAssertion Quantifier` alternative. + // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion + // is a QuantifiableAssertion. + if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { + // Make the same message as V8. + if (state.switchU) { + state.raise("Invalid quantifier"); + } + } + return true + } - /** - * The {@link Reference|references} that are not resolved with this scope. - * @member {Reference[]} Scope#through - */ - this.through = []; + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true + } - /** - * The scoped {@link Variable}s of this scope. In the case of a - * 'function' scope this includes the automatic argument arguments as - * its first element, as well as all further formal arguments. - * @member {Variable[]} Scope#variables - */ - this.variables = []; + return false + }; - /** - * Any variable {@link Reference|reference} found in this scope. This - * includes occurrences of local variables as well as variables from - * parent scopes (including the global scope). For local variables - * this also includes defining occurrences (like in a 'var' statement). - * In a 'function' scope this does not include the occurrences of the - * formal parameter in the parameter list. - * @member {Reference[]} Scope#references - */ - this.references = []; + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion + pp$8.regexp_eatAssertion = function(state) { + var start = state.pos; + state.lastAssertionIsQuantifiable = false; - /** - * For 'global' and 'function' scopes, this is a self-reference. For - * other scope types this is the variableScope value of the - * parent scope. - * @member {Scope} Scope#variableScope - */ - this.variableScope = - (this.type === "global" || this.type === "function" || this.type === "module") ? this : upperScope.variableScope; + // ^, $ + if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { + return true + } - /** - * Whether this scope is created by a FunctionExpression. - * @member {boolean} Scope#functionExpressionScope - */ - this.functionExpressionScope = false; + // \b \B + if (state.eat(0x5C /* \ */)) { + if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { + return true + } + state.pos = start; + } - /** - * Whether this is a scope that contains an 'eval()' invocation. - * @member {boolean} Scope#directCallToEvalScope - */ - this.directCallToEvalScope = false; + // Lookahead / Lookbehind + if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state.eat(0x3C /* < */); + } + if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { + this.regexp_disjunction(state); + if (!state.eat(0x29 /* ) */)) { + state.raise("Unterminated group"); + } + state.lastAssertionIsQuantifiable = !lookbehind; + return true + } + } - /** - * @member {boolean} Scope#thisFound - */ - this.thisFound = false; + state.pos = start; + return false + }; - this.__left = []; + // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier + pp$8.regexp_eatQuantifier = function(state, noError) { + if ( noError === void 0 ) noError = false; - /** - * Reference to the parent {@link Scope|scope}. - * @member {Scope} Scope#upper - */ - this.upper = upperScope; + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat(0x3F /* ? */); + return true + } + return false + }; - /** - * Whether 'use strict' is in effect in this scope. - * @member {boolean} Scope#isStrict - */ - this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective()); + // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix + pp$8.regexp_eatQuantifierPrefix = function(state, noError) { + return ( + state.eat(0x2A /* * */) || + state.eat(0x2B /* + */) || + state.eat(0x3F /* ? */) || + this.regexp_eatBracedQuantifier(state, noError) + ) + }; + pp$8.regexp_eatBracedQuantifier = function(state, noError) { + var start = state.pos; + if (state.eat(0x7B /* { */)) { + var min = 0, max = -1; + if (this.regexp_eatDecimalDigits(state)) { + min = state.lastIntValue; + if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { + max = state.lastIntValue; + } + if (state.eat(0x7D /* } */)) { + // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term + if (max !== -1 && max < min && !noError) { + state.raise("numbers out of order in {} quantifier"); + } + return true + } + } + if (state.switchU && !noError) { + state.raise("Incomplete quantifier"); + } + state.pos = start; + } + return false + }; - /** - * List of nested {@link Scope}s. - * @member {Scope[]} Scope#childScopes - */ - this.childScopes = []; - if (this.upper) { - this.upper.childScopes.push(this); + // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom + pp$8.regexp_eatAtom = function(state) { + return ( + this.regexp_eatPatternCharacters(state) || + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) + ) + }; + pp$8.regexp_eatReverseSolidusAtomEscape = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatAtomEscape(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$8.regexp_eatUncapturingGroup = function(state) { + var start = state.pos; + if (state.eat(0x28 /* ( */)) { + if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + return true } + state.raise("Unterminated group"); + } + state.pos = start; + } + return false + }; + pp$8.regexp_eatCapturingGroup = function(state) { + if (state.eat(0x28 /* ( */)) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state); + } else if (state.current() === 0x3F /* ? */) { + state.raise("Invalid group"); + } + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + state.numCapturingParens += 1; + return true + } + state.raise("Unterminated group"); + } + return false + }; - this.__declaredVariables = scopeManager.__declaredVariables; + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom + pp$8.regexp_eatExtendedAtom = function(state) { + return ( + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) || + this.regexp_eatInvalidBracedQuantifier(state) || + this.regexp_eatExtendedPatternCharacter(state) + ) + }; - registerScope(scopeManager, this); + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier + pp$8.regexp_eatInvalidBracedQuantifier = function(state) { + if (this.regexp_eatBracedQuantifier(state, true)) { + state.raise("Nothing to repeat"); } + return false + }; - __shouldStaticallyClose(scopeManager) { - return (!this.dynamic || scopeManager.__isOptimistic()); + // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter + pp$8.regexp_eatSyntaxCharacter = function(state) { + var ch = state.current(); + if (isSyntaxCharacter(ch)) { + state.lastIntValue = ch; + state.advance(); + return true } + return false + }; + function isSyntaxCharacter(ch) { + return ( + ch === 0x24 /* $ */ || + ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || + ch === 0x2E /* . */ || + ch === 0x3F /* ? */ || + ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) + } - __shouldStaticallyCloseForGlobal(ref) { + // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter + // But eat eager. + pp$8.regexp_eatPatternCharacters = function(state) { + var start = state.pos; + var ch = 0; + while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { + state.advance(); + } + return state.pos !== start + }; - // On global scope, let/const/class declarations should be resolved statically. - const name = ref.identifier.name; + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter + pp$8.regexp_eatExtendedPatternCharacter = function(state) { + var ch = state.current(); + if ( + ch !== -1 && + ch !== 0x24 /* $ */ && + !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && + ch !== 0x2E /* . */ && + ch !== 0x3F /* ? */ && + ch !== 0x5B /* [ */ && + ch !== 0x5E /* ^ */ && + ch !== 0x7C /* | */ + ) { + state.advance(); + return true + } + return false + }; - if (!this.set.has(name)) { - return false; + // GroupSpecifier :: + // [empty] + // `?` GroupName + pp$8.regexp_groupSpecifier = function(state) { + if (state.eat(0x3F /* ? */)) { + if (this.regexp_eatGroupName(state)) { + if (state.groupNames.indexOf(state.lastStringValue) !== -1) { + state.raise("Duplicate capture group name"); } + state.groupNames.push(state.lastStringValue); + return + } + state.raise("Invalid group"); + } + }; - const variable = this.set.get(name); - const defs = variable.defs; - - return defs.length > 0 && defs.every(shouldBeStatically); + // GroupName :: + // `<` RegExpIdentifierName `>` + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$8.regexp_eatGroupName = function(state) { + state.lastStringValue = ""; + if (state.eat(0x3C /* < */)) { + if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { + return true + } + state.raise("Invalid capture group name"); } + return false + }; - __staticCloseRef(ref) { - if (!this.__resolve(ref)) { - this.__delegateToUpperScope(ref); - } + // RegExpIdentifierName :: + // RegExpIdentifierStart + // RegExpIdentifierName RegExpIdentifierPart + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$8.regexp_eatRegExpIdentifierName = function(state) { + state.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + } + return true } + return false + }; - __dynamicCloseRef(ref) { + // RegExpIdentifierStart :: + // UnicodeIDStart + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + pp$8.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true + } - // notify all names are through to global - let current = this; + state.pos = start; + return false + }; + function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ + } - do { - current.through.push(ref); - current = current.upper; - } while (current); + // RegExpIdentifierPart :: + // UnicodeIDContinue + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + // + // + pp$8.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true } - __globalCloseRef(ref) { + state.pos = start; + return false + }; + function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ + } - // let/const/class declarations should be resolved statically. - // others should be resolved dynamically. - if (this.__shouldStaticallyCloseForGlobal(ref)) { - this.__staticCloseRef(ref); - } else { - this.__dynamicCloseRef(ref); + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape + pp$8.regexp_eatAtomEscape = function(state) { + if ( + this.regexp_eatBackReference(state) || + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) || + (state.switchN && this.regexp_eatKGroupName(state)) + ) { + return true + } + if (state.switchU) { + // Make the same message as V8. + if (state.current() === 0x63 /* c */) { + state.raise("Invalid unicode escape"); + } + state.raise("Invalid escape"); + } + return false + }; + pp$8.regexp_eatBackReference = function(state) { + var start = state.pos; + if (this.regexp_eatDecimalEscape(state)) { + var n = state.lastIntValue; + if (state.switchU) { + // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape + if (n > state.maxBackReference) { + state.maxBackReference = n; } + return true + } + if (n <= state.numCapturingParens) { + return true + } + state.pos = start; + } + return false + }; + pp$8.regexp_eatKGroupName = function(state) { + if (state.eat(0x6B /* k */)) { + if (this.regexp_eatGroupName(state)) { + state.backReferenceNames.push(state.lastStringValue); + return true + } + state.raise("Invalid named reference"); } + return false + }; - __close(scopeManager) { - let closeRef; + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape + pp$8.regexp_eatCharacterEscape = function(state) { + return ( + this.regexp_eatControlEscape(state) || + this.regexp_eatCControlLetter(state) || + this.regexp_eatZero(state) || + this.regexp_eatHexEscapeSequence(state) || + this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || + (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || + this.regexp_eatIdentityEscape(state) + ) + }; + pp$8.regexp_eatCControlLetter = function(state) { + var start = state.pos; + if (state.eat(0x63 /* c */)) { + if (this.regexp_eatControlLetter(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$8.regexp_eatZero = function(state) { + if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { + state.lastIntValue = 0; + state.advance(); + return true + } + return false + }; - if (this.__shouldStaticallyClose(scopeManager)) { - closeRef = this.__staticCloseRef; - } else if (this.type !== "global") { - closeRef = this.__dynamicCloseRef; - } else { - closeRef = this.__globalCloseRef; - } + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape + pp$8.regexp_eatControlEscape = function(state) { + var ch = state.current(); + if (ch === 0x74 /* t */) { + state.lastIntValue = 0x09; /* \t */ + state.advance(); + return true + } + if (ch === 0x6E /* n */) { + state.lastIntValue = 0x0A; /* \n */ + state.advance(); + return true + } + if (ch === 0x76 /* v */) { + state.lastIntValue = 0x0B; /* \v */ + state.advance(); + return true + } + if (ch === 0x66 /* f */) { + state.lastIntValue = 0x0C; /* \f */ + state.advance(); + return true + } + if (ch === 0x72 /* r */) { + state.lastIntValue = 0x0D; /* \r */ + state.advance(); + return true + } + return false + }; - // Try Resolving all references in this scope. - for (let i = 0, iz = this.__left.length; i < iz; ++i) { - const ref = this.__left[i]; + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter + pp$8.regexp_eatControlLetter = function(state) { + var ch = state.current(); + if (isControlLetter(ch)) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + function isControlLetter(ch) { + return ( + (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || + (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) + ) + } - closeRef.call(this, ref); + // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence + pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { + if ( forceU === void 0 ) forceU = false; + + var start = state.pos; + var switchU = forceU || state.switchU; + + if (state.eat(0x75 /* u */)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { + var leadSurrogateEnd = state.pos; + if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { + var trail = state.lastIntValue; + if (trail >= 0xDC00 && trail <= 0xDFFF) { + state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + return true + } + } + state.pos = leadSurrogateEnd; + state.lastIntValue = lead; } - this.__left = null; + return true + } + if ( + switchU && + state.eat(0x7B /* { */) && + this.regexp_eatHexDigits(state) && + state.eat(0x7D /* } */) && + isValidUnicode(state.lastIntValue) + ) { + return true + } + if (switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; + } - return this.upper; + return false + }; + function isValidUnicode(ch) { + return ch >= 0 && ch <= 0x10FFFF + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape + pp$8.regexp_eatIdentityEscape = function(state) { + if (state.switchU) { + if (this.regexp_eatSyntaxCharacter(state)) { + return true + } + if (state.eat(0x2F /* / */)) { + state.lastIntValue = 0x2F; /* / */ + return true + } + return false } - // To override by function scopes. - // References in default parameters isn't resolved to variables which are in their function body. - __isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars - return true; + var ch = state.current(); + if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { + state.lastIntValue = ch; + state.advance(); + return true } - __resolve(ref) { - const name = ref.identifier.name; + return false + }; - if (!this.set.has(name)) { - return false; - } - const variable = this.set.get(name); + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape + pp$8.regexp_eatDecimalEscape = function(state) { + state.lastIntValue = 0; + var ch = state.current(); + if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { + do { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) + return true + } + return false + }; - if (!this.__isValidResolution(ref, variable)) { - return false; - } - variable.references.push(ref); - variable.stack = variable.stack && ref.from.variableScope === this.variableScope; - if (ref.tainted) { - variable.tainted = true; - this.taints.set(variable.name, true); - } - ref.resolved = variable; + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape + pp$8.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); - return true; + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return true } - __delegateToUpperScope(ref) { - if (this.upper) { - this.upper.__left.push(ref); - } - this.through.push(ref); + if ( + state.switchU && + this.options.ecmaVersion >= 9 && + (ch === 0x50 /* P */ || ch === 0x70 /* p */) + ) { + state.lastIntValue = -1; + state.advance(); + if ( + state.eat(0x7B /* { */) && + this.regexp_eatUnicodePropertyValueExpression(state) && + state.eat(0x7D /* } */) + ) { + return true + } + state.raise("Invalid property name"); } - __addDeclaredVariablesOfNode(variable, node) { - if (node === null || node === undefined) { - return; - } + return false + }; + function isCharacterClassEscape(ch) { + return ( + ch === 0x64 /* d */ || + ch === 0x44 /* D */ || + ch === 0x73 /* s */ || + ch === 0x53 /* S */ || + ch === 0x77 /* w */ || + ch === 0x57 /* W */ + ) + } - let variables = this.__declaredVariables.get(node); + // UnicodePropertyValueExpression :: + // UnicodePropertyName `=` UnicodePropertyValue + // LoneUnicodePropertyNameOrValue + pp$8.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; + + // UnicodePropertyName `=` UnicodePropertyValue + if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { + var name = state.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state)) { + var value = state.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state, name, value); + return true + } + } + state.pos = start; - if (variables === null || variables === undefined) { - variables = []; - this.__declaredVariables.set(node, variables); - } - if (variables.indexOf(variable) === -1) { - variables.push(variable); - } + // LoneUnicodePropertyNameOrValue + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { + var nameOrValue = state.lastStringValue; + this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); + return true } + return false + }; + pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { + if (!has(state.unicodeProperties.nonBinary, name)) + { state.raise("Invalid property name"); } + if (!state.unicodeProperties.nonBinary[name].test(value)) + { state.raise("Invalid property value"); } + }; + pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { + if (!state.unicodeProperties.binary.test(nameOrValue)) + { state.raise("Invalid property name"); } + }; - __defineGeneric(name, set, variables, node, def) { - let variable; + // UnicodePropertyName :: + // UnicodePropertyNameCharacters + pp$8.regexp_eatUnicodePropertyName = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 0x5F /* _ */ + } - variable = set.get(name); - if (!variable) { - variable = new Variable(name, this); - set.set(name, variable); - variables.push(variable); - } + // UnicodePropertyValue :: + // UnicodePropertyValueCharacters + pp$8.regexp_eatUnicodePropertyValue = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) + } - if (def) { - variable.defs.push(def); - this.__addDeclaredVariablesOfNode(variable, def.node); - this.__addDeclaredVariablesOfNode(variable, def.parent); - } - if (node) { - variable.identifiers.push(node); - } + // LoneUnicodePropertyNameOrValue :: + // UnicodePropertyValueCharacters + pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass + pp$8.regexp_eatCharacterClass = function(state) { + if (state.eat(0x5B /* [ */)) { + state.eat(0x5E /* ^ */); + this.regexp_classRanges(state); + if (state.eat(0x5D /* ] */)) { + return true + } + // Unreachable since it threw "unterminated regular expression" error before. + state.raise("Unterminated character class"); } + return false + }; - __define(node, def) { - if (node && node.type === Syntax.Identifier) { - this.__defineGeneric( - node.name, - this.set, - this.variables, - node, - def - ); + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash + pp$8.regexp_classRanges = function(state) { + while (this.regexp_eatClassAtom(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { + var right = state.lastIntValue; + if (state.switchU && (left === -1 || right === -1)) { + state.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); } + } } + }; - __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) { - - // because Array element may be null - if (!node || node.type !== Syntax.Identifier) { - return; - } + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash + pp$8.regexp_eatClassAtom = function(state) { + var start = state.pos; - // Specially handle like `this`. - if (node.name === "super") { - return; + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatClassEscape(state)) { + return true + } + if (state.switchU) { + // Make the same message as V8. + var ch$1 = state.current(); + if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { + state.raise("Invalid class escape"); } + state.raise("Invalid escape"); + } + state.pos = start; + } - const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init); - - this.references.push(ref); - this.__left.push(ref); + var ch = state.current(); + if (ch !== 0x5D /* ] */) { + state.lastIntValue = ch; + state.advance(); + return true } - __detectEval() { - let current = this; + return false + }; - this.directCallToEvalScope = true; - do { - current.dynamic = true; - current = current.upper; - } while (current); + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape + pp$8.regexp_eatClassEscape = function(state) { + var start = state.pos; + + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true } - __detectThis() { - this.thisFound = true; + if (state.switchU && state.eat(0x2D /* - */)) { + state.lastIntValue = 0x2D; /* - */ + return true } - __isClosed() { - return this.__left === null; + if (!state.switchU && state.eat(0x63 /* c */)) { + if (this.regexp_eatClassControlLetter(state)) { + return true + } + state.pos = start; } - /** - * returns resolved {Reference} - * @method Scope#resolve - * @param {Espree.Identifier} ident - identifier to be resolved. - * @returns {Reference} reference - */ - resolve(ident) { - let ref, i, iz; + return ( + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) + ) + }; - assert(this.__isClosed(), "Scope should be closed."); - assert(ident.type === Syntax.Identifier, "Target should be identifier."); - for (i = 0, iz = this.references.length; i < iz; ++i) { - ref = this.references[i]; - if (ref.identifier === ident) { - return ref; - } - } - return null; + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter + pp$8.regexp_eatClassControlLetter = function(state) { + var ch = state.current(); + if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true } + return false + }; - /** - * returns this scope is static - * @method Scope#isStatic - * @returns {boolean} static - */ - isStatic() { - return !this.dynamic; + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$8.regexp_eatHexEscapeSequence = function(state) { + var start = state.pos; + if (state.eat(0x78 /* x */)) { + if (this.regexp_eatFixedHexDigits(state, 2)) { + return true + } + if (state.switchU) { + state.raise("Invalid escape"); + } + state.pos = start; } + return false + }; - /** - * returns this scope has materialized arguments - * @method Scope#isArgumentsMaterialized - * @returns {boolean} arguemnts materialized - */ - isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this - return true; + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits + pp$8.regexp_eatDecimalDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isDecimalDigit(ch = state.current())) { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); } + return state.pos !== start + }; + function isDecimalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ + } - /** - * returns this scope has materialized `this` reference - * @method Scope#isThisMaterialized - * @returns {boolean} this materialized - */ - isThisMaterialized() { // eslint-disable-line class-methods-use-this - return true; + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits + pp$8.regexp_eatHexDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isHexDigit(ch = state.current())) { + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return state.pos !== start + }; + function isHexDigit(ch) { + return ( + (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || + (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || + (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) + ) + } + function hexToInt(ch) { + if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { + return 10 + (ch - 0x41 /* A */) } + if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { + return 10 + (ch - 0x61 /* a */) + } + return ch - 0x30 /* 0 */ + } - isUsedName(name) { - if (this.set.has(name)) { - return true; - } - for (let i = 0, iz = this.through.length; i < iz; ++i) { - if (this.through[i].identifier.name === name) { - return true; - } + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence + // Allows only 0-377(octal) i.e. 0-255(decimal). + pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) { + if (this.regexp_eatOctalDigit(state)) { + var n1 = state.lastIntValue; + if (this.regexp_eatOctalDigit(state)) { + var n2 = state.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { + state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; + } else { + state.lastIntValue = n1 * 8 + n2; } - return false; + } else { + state.lastIntValue = n1; + } + return true } -} + return false + }; -class GlobalScope extends Scope { - constructor(scopeManager, block) { - super(scopeManager, "global", null, block, false); - this.implicit = { - set: new Map(), - variables: [], + // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit + pp$8.regexp_eatOctalDigit = function(state) { + var ch = state.current(); + if (isOctalDigit(ch)) { + state.lastIntValue = ch - 0x30; /* 0 */ + state.advance(); + return true + } + state.lastIntValue = 0; + return false + }; + function isOctalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ + } - /** - * List of {@link Reference}s that are left to be resolved (i.e. which - * need to be linked to the variable they refer to). - * @member {Reference[]} Scope#implicit#left - */ - left: [] - }; + // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit + // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$8.regexp_eatFixedHexDigits = function(state, length) { + var start = state.pos; + state.lastIntValue = 0; + for (var i = 0; i < length; ++i) { + var ch = state.current(); + if (!isHexDigit(ch)) { + state.pos = start; + return false + } + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); } + return true + }; - __close(scopeManager) { - const implicit = []; + // Object type used to represent tokens. Note that normally, tokens + // simply exist as properties on the parser object. This is only + // used for the onToken callback and the external tokenizer. + + var Token = function Token(p) { + this.type = p.type; + this.value = p.value; + this.start = p.start; + this.end = p.end; + if (p.options.locations) + { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } + if (p.options.ranges) + { this.range = [p.start, p.end]; } + }; - for (let i = 0, iz = this.__left.length; i < iz; ++i) { - const ref = this.__left[i]; + // ## Tokenizer - if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { - implicit.push(ref.__maybeImplicitGlobal); - } - } + var pp$9 = Parser.prototype; - // create an implicit global variable from assignment expression - for (let i = 0, iz = implicit.length; i < iz; ++i) { - const info = implicit[i]; + // Move to the next token - this.__defineImplicit(info.pattern, - new Definition( - Variable.ImplicitGlobalVariable, - info.pattern, - info.node, - null, - null, - null - )); + pp$9.next = function(ignoreEscapeSequenceInKeyword) { + if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) + { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } + if (this.options.onToken) + { this.options.onToken(new Token(this)); } - } + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); + }; - this.implicit.left = this.__left; + pp$9.getToken = function() { + this.next(); + return new Token(this) + }; - return super.__close(scopeManager); - } + // If we're in an ES6 environment, make parsers iterable + if (typeof Symbol !== "undefined") + { pp$9[Symbol.iterator] = function() { + var this$1 = this; - __defineImplicit(node, def) { - if (node && node.type === Syntax.Identifier) { - this.__defineGeneric( - node.name, - this.implicit.set, - this.implicit.variables, - node, - def - ); + return { + next: function () { + var token = this$1.getToken(); + return { + done: token.type === types.eof, + value: token + } } - } -} + } + }; } -class ModuleScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "module", upperScope, block, false); - } -} + // Toggle strict mode. Re-reads the next number or string to please + // pedantic tests (`"use strict"; 010;` should fail). -class FunctionExpressionNameScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "function-expression-name", upperScope, block, false); - this.__define(block.id, - new Definition( - Variable.FunctionName, - block.id, - block, - null, - null, - null - )); - this.functionExpressionScope = true; - } -} + // Read a single token, updating the parser object's token-related + // properties. -class CatchScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "catch", upperScope, block, false); - } -} + pp$9.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } -class WithScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "with", upperScope, block, false); - } + this.start = this.pos; + if (this.options.locations) { this.startLoc = this.curPosition(); } + if (this.pos >= this.input.length) { return this.finishToken(types.eof) } - __close(scopeManager) { - if (this.__shouldStaticallyClose(scopeManager)) { - return super.__close(scopeManager); - } + if (curContext.override) { return curContext.override(this) } + else { this.readToken(this.fullCharCodeAtPos()); } + }; - for (let i = 0, iz = this.__left.length; i < iz; ++i) { - const ref = this.__left[i]; + pp$9.readToken = function(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) + { return this.readWord() } - ref.tainted = true; - this.__delegateToUpperScope(ref); - } - this.__left = null; + return this.getTokenFromCode(code) + }; - return this.upper; - } -} + pp$9.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos); + if (code <= 0xd7ff || code >= 0xdc00) { return code } + var next = this.input.charCodeAt(this.pos + 1); + return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 + }; -class BlockScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "block", upperScope, block, false); + pp$9.skipBlockComment = function() { + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } + this.pos = end + 2; + if (this.options.locations) { + lineBreakG.lastIndex = start; + var match; + while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { + ++this.curLine; + this.lineStart = match.index + match[0].length; + } } -} + if (this.options.onComment) + { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, + startLoc, this.curPosition()); } + }; -class SwitchScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "switch", upperScope, block, false); + pp$9.skipLineComment = function(startSkip) { + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this.input.charCodeAt(++this.pos); } -} - -class FunctionScope extends Scope { - constructor(scopeManager, upperScope, block, isMethodDefinition) { - super(scopeManager, "function", upperScope, block, isMethodDefinition); + if (this.options.onComment) + { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, + startLoc, this.curPosition()); } + }; - // section 9.2.13, FunctionDeclarationInstantiation. - // NOTE Arrow functions never have an arguments objects. - if (this.block.type !== Syntax.ArrowFunctionExpression) { - this.__defineArguments(); + // Called at the start of the parse and after every token. Skips + // whitespace and comments, and. + + pp$9.skipSpace = function() { + loop: while (this.pos < this.input.length) { + var ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 32: case 160: // ' ' + ++this.pos; + break + case 13: + if (this.input.charCodeAt(this.pos + 1) === 10) { + ++this.pos; } + case 10: case 8232: case 8233: + ++this.pos; + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + break + case 47: // '/' + switch (this.input.charCodeAt(this.pos + 1)) { + case 42: // '*' + this.skipBlockComment(); + break + case 47: + this.skipLineComment(2); + break + default: + break loop + } + break + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.pos; + } else { + break loop + } + } } + }; - isArgumentsMaterialized() { + // Called at the end of every token. Sets `end`, `val`, and + // maintains `context` and `exprAllowed`, and skips the space after + // the token, so that the next one's `start` will point at the + // right position. - // TODO(Constellation) - // We can more aggressive on this condition like this. - // - // function t() { - // // arguments of t is always hidden. - // function arguments() { - // } - // } - if (this.block.type === Syntax.ArrowFunctionExpression) { - return false; - } + pp$9.finishToken = function(type, val) { + this.end = this.pos; + if (this.options.locations) { this.endLoc = this.curPosition(); } + var prevType = this.type; + this.type = type; + this.value = val; - if (!this.isStatic()) { - return true; - } + this.updateContext(prevType); + }; - const variable = this.set.get("arguments"); + // ### Token reading - assert(variable, "Always have arguments variable."); - return variable.tainted || variable.references.length !== 0; + // This is the function that is called to fetch the next token. It + // is somewhat obscure, because it works in character codes rather + // than characters, and because operator parsing has been inlined + // into it. + // + // All in the name of speed. + // + pp$9.readToken_dot = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next >= 48 && next <= 57) { return this.readNumber(true) } + var next2 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' + this.pos += 3; + return this.finishToken(types.ellipsis) + } else { + ++this.pos; + return this.finishToken(types.dot) } + }; - isThisMaterialized() { - if (!this.isStatic()) { - return true; - } - return this.thisFound; + pp$9.readToken_slash = function() { // '/' + var next = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { ++this.pos; return this.readRegexp() } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.slash, 1) + }; + + pp$9.readToken_mult_modulo_exp = function(code) { // '%*' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types.star : types.modulo; + + // exponentiation operator ** and **= + if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { + ++size; + tokentype = types.starstar; + next = this.input.charCodeAt(this.pos + 2); } - __defineArguments() { - this.__defineGeneric( - "arguments", - this.set, - this.variables, - null, - null - ); - this.taints.set("arguments", true); + if (next === 61) { return this.finishOp(types.assign, size + 1) } + return this.finishOp(tokentype, size) + }; + + pp$9.readToken_pipe_amp = function(code) { // '|&' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (this.options.ecmaVersion >= 12) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 === 61) { return this.finishOp(types.assign, 3) } + } + return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) + }; - // References in default parameters isn't resolved to variables which are in their function body. - // const x = 1 - // function f(a = x) { // This `x` is resolved to the `x` in the outer scope. - // const x = 2 - // console.log(a) - // } - __isValidResolution(ref, variable) { + pp$9.readToken_caret = function() { // '^' + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.bitwiseXOR, 1) + }; - // If `options.nodejsScope` is true, `this.block` becomes a Program node. - if (this.block.type === "Program") { - return true; - } + pp$9.readToken_plus_min = function(code) { // '+-' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && + (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + // A `-->` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types.incDec, 2) + } + if (next === 61) { return this.finishOp(types.assign, 2) } + return this.finishOp(types.plusMin, 1) + }; - const bodyStart = this.block.body.range[0]; + pp$9.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } + return this.finishOp(types.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // ` SYNC --[event loop tick]--> ASYNC_ACTIVE --[interval tick]-> ASYNC_PASSIVE + ^ | + +---------[insert data]-------+ +*/ - // initialize - outer = { - root: root - }; - element = new Element(root, null, null, new Reference(outer, 'root')); - worklist.push(element); - leavelist.push(element); +const STORAGE_MODE_IDLE = 0; +const STORAGE_MODE_SYNC = 1; +const STORAGE_MODE_ASYNC = 2; - while (worklist.length) { - element = worklist.pop(); +class CacheBackend { + /** + * @param {number} duration max cache duration of items + * @param {any} provider async method + * @param {any} syncProvider sync method + * @param {any} providerContext call context for the provider methods + */ + constructor(duration, provider, syncProvider, providerContext) { + this._duration = duration; + this._provider = provider; + this._syncProvider = syncProvider; + this._providerContext = providerContext; + /** @type {Map} */ + this._activeAsyncOperations = new Map(); + /** @type {Map }>} */ + this._data = new Map(); + /** @type {Set[]} */ + this._levels = []; + for (let i = 0; i < 10; i++) this._levels.push(new Set()); + for (let i = 5000; i < duration; i += 500) this._levels.push(new Set()); + this._currentLevel = 0; + this._tickInterval = Math.floor(duration / this._levels.length); + /** @type {STORAGE_MODE_IDLE | STORAGE_MODE_SYNC | STORAGE_MODE_ASYNC} */ + this._mode = STORAGE_MODE_IDLE; - if (element === sentinel) { - element = leavelist.pop(); + /** @type {NodeJS.Timeout | undefined} */ + this._timeout = undefined; + /** @type {number | undefined} */ + this._nextDecay = undefined; - target = this.__execute(visitor.leave, element); + this.provide = provider ? this.provide.bind(this) : null; + this.provideSync = syncProvider ? this.provideSync.bind(this) : null; + } - // node may be replaced with null, - // so distinguish between undefined and null in this place - if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { - // replace - element.ref.replace(target); - } + provide(path, options, callback) { + if (typeof options === "function") { + callback = options; + options = undefined; + } + if (typeof path !== "string") { + callback(new TypeError("path must be a string")); + return; + } + if (options) { + return this._provider.call( + this._providerContext, + path, + options, + callback + ); + } - if (this.__state === REMOVE || target === REMOVE) { - removeElem(element); - } + // When in sync mode we can move to async mode + if (this._mode === STORAGE_MODE_SYNC) { + this._enterAsyncMode(); + } - if (this.__state === BREAK || target === BREAK) { - return outer.root; - } - continue; - } + // Check in cache + let cacheEntry = this._data.get(path); + if (cacheEntry !== undefined) { + if (cacheEntry.err) return nextTick(callback, cacheEntry.err); + return nextTick(callback, null, cacheEntry.result); + } - target = this.__execute(visitor.enter, element); + // Check if there is already the same operation running + let callbacks = this._activeAsyncOperations.get(path); + if (callbacks !== undefined) { + callbacks.push(callback); + return; + } + this._activeAsyncOperations.set(path, (callbacks = [callback])); - // node may be replaced with null, - // so distinguish between undefined and null in this place - if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { - // replace - element.ref.replace(target); - element.node = target; - } + // Run the operation + this._provider.call(this._providerContext, path, (err, result) => { + this._activeAsyncOperations.delete(path); + this._storeResult(path, err, result); - if (this.__state === REMOVE || target === REMOVE) { - removeElem(element); - element.node = null; - } + // Enter async mode if not yet done + this._enterAsyncMode(); - if (this.__state === BREAK || target === BREAK) { - return outer.root; - } + runCallbacks(callbacks, err, result); + }); + } - // node may be null - node = element.node; - if (!node) { - continue; - } + provideSync(path, options) { + if (typeof path !== "string") { + throw new TypeError("path must be a string"); + } + if (options) { + return this._syncProvider.call(this._providerContext, path, options); + } - worklist.push(sentinel); - leavelist.push(element); + // In sync mode we may have to decay some cache items + if (this._mode === STORAGE_MODE_SYNC) { + this._runDecays(); + } - if (this.__state === SKIP || target === SKIP) { - continue; - } + // Check in cache + let cacheEntry = this._data.get(path); + if (cacheEntry !== undefined) { + if (cacheEntry.err) throw cacheEntry.err; + return cacheEntry.result; + } - nodeType = node.type || element.wrap; - candidates = this.__keys[nodeType]; - if (!candidates) { - if (this.__fallback) { - candidates = this.__fallback(node); - } else { - throw new Error('Unknown node type ' + nodeType + '.'); - } - } + // Get all active async operations + // This sync operation will also complete them + const callbacks = this._activeAsyncOperations.get(path); + this._activeAsyncOperations.delete(path); - current = candidates.length; - while ((current -= 1) >= 0) { - key = candidates[current]; - candidate = node[key]; - if (!candidate) { - continue; - } + // Run the operation + // When in idle mode, we will enter sync mode + let result; + try { + result = this._syncProvider.call(this._providerContext, path); + } catch (err) { + this._storeResult(path, err, undefined); + this._enterSyncModeWhenIdle(); + if (callbacks) runCallbacks(callbacks, err, undefined); + throw err; + } + this._storeResult(path, undefined, result); + this._enterSyncModeWhenIdle(); + if (callbacks) runCallbacks(callbacks, undefined, result); + return result; + } - if (Array.isArray(candidate)) { - current2 = candidate.length; - while ((current2 -= 1) >= 0) { - if (!candidate[current2]) { - continue; - } - if (isProperty(nodeType, candidates[current])) { - element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); - } else if (isNode(candidate[current2])) { - element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); - } else { - continue; - } - worklist.push(element); - } - } else if (isNode(candidate)) { - worklist.push(new Element(candidate, key, null, new Reference(node, key))); - } - } - } + purge(what) { + if (!what) { + if (this._mode !== STORAGE_MODE_IDLE) { + this._data.clear(); + for (const level of this._levels) { + level.clear(); + } + this._enterIdleMode(); + } + } else if (typeof what === "string") { + for (let [key, data] of this._data) { + if (key.startsWith(what)) { + this._data.delete(key); + data.level.delete(key); + } + } + if (this._data.size === 0) { + this._enterIdleMode(); + } + } else { + for (let [key, data] of this._data) { + for (const item of what) { + if (key.startsWith(item)) { + this._data.delete(key); + data.level.delete(key); + break; + } + } + } + if (this._data.size === 0) { + this._enterIdleMode(); + } + } + } - return outer.root; - }; + purgeParent(what) { + if (!what) { + this.purge(); + } else if (typeof what === "string") { + this.purge(dirname(what)); + } else { + const set = new Set(); + for (const item of what) { + set.add(dirname(item)); + } + this.purge(set); + } + } - function traverse(root, visitor) { - var controller = new Controller(); - return controller.traverse(root, visitor); - } + _storeResult(path, err, result) { + if (this._data.has(path)) return; + const level = this._levels[this._currentLevel]; + this._data.set(path, { err, result, level }); + level.add(path); + } - function replace(root, visitor) { - var controller = new Controller(); - return controller.replace(root, visitor); - } + _decayLevel() { + const nextLevel = (this._currentLevel + 1) % this._levels.length; + const decay = this._levels[nextLevel]; + this._currentLevel = nextLevel; + for (let item of decay) { + this._data.delete(item); + } + decay.clear(); + if (this._data.size === 0) { + this._enterIdleMode(); + } else { + // @ts-ignore _nextDecay is always a number in sync mode + this._nextDecay += this._tickInterval; + } + } - function extendCommentRange(comment, tokens) { - var target; + _runDecays() { + while ( + /** @type {number} */ (this._nextDecay) <= Date.now() && + this._mode !== STORAGE_MODE_IDLE + ) { + this._decayLevel(); + } + } - target = upperBound(tokens, function search(token) { - return token.range[0] > comment.range[0]; - }); + _enterAsyncMode() { + let timeout = 0; + switch (this._mode) { + case STORAGE_MODE_ASYNC: + return; + case STORAGE_MODE_IDLE: + this._nextDecay = Date.now() + this._tickInterval; + timeout = this._tickInterval; + break; + case STORAGE_MODE_SYNC: + this._runDecays(); + // @ts-ignore _runDecays may change the mode + if (this._mode === STORAGE_MODE_IDLE) return; + timeout = Math.max( + 0, + /** @type {number} */ (this._nextDecay) - Date.now() + ); + break; + } + this._mode = STORAGE_MODE_ASYNC; + const ref = setTimeout(() => { + this._mode = STORAGE_MODE_SYNC; + this._runDecays(); + }, timeout); + if (ref.unref) ref.unref(); + this._timeout = ref; + } - comment.extendedRange = [comment.range[0], comment.range[1]]; + _enterSyncModeWhenIdle() { + if (this._mode === STORAGE_MODE_IDLE) { + this._mode = STORAGE_MODE_SYNC; + this._nextDecay = Date.now() + this._tickInterval; + } + } - if (target !== tokens.length) { - comment.extendedRange[1] = tokens[target].range[0]; - } + _enterIdleMode() { + this._mode = STORAGE_MODE_IDLE; + this._nextDecay = undefined; + if (this._timeout) clearTimeout(this._timeout); + } +} - target -= 1; - if (target >= 0) { - comment.extendedRange[0] = tokens[target].range[1]; - } +const createBackend = (duration, provider, syncProvider, providerContext) => { + if (duration > 0) { + return new CacheBackend(duration, provider, syncProvider, providerContext); + } + return new OperationMergerBackend(provider, syncProvider, providerContext); +}; - return comment; - } +module.exports = class CachedInputFileSystem { + constructor(fileSystem, duration) { + this.fileSystem = fileSystem; - function attachComments(tree, providedComments, tokens) { - // At first, we should calculate extended comment ranges. - var comments = [], comment, len, i, cursor; + this._lstatBackend = createBackend( + duration, + this.fileSystem.lstat, + this.fileSystem.lstatSync, + this.fileSystem + ); + const lstat = this._lstatBackend.provide; + this.lstat = /** @type {FileSystem["lstat"]} */ (lstat); + const lstatSync = this._lstatBackend.provideSync; + this.lstatSync = /** @type {SyncFileSystem["lstatSync"]} */ (lstatSync); - if (!tree.range) { - throw new Error('attachComments needs range information'); - } + this._statBackend = createBackend( + duration, + this.fileSystem.stat, + this.fileSystem.statSync, + this.fileSystem + ); + const stat = this._statBackend.provide; + this.stat = /** @type {FileSystem["stat"]} */ (stat); + const statSync = this._statBackend.provideSync; + this.statSync = /** @type {SyncFileSystem["statSync"]} */ (statSync); - // tokens array is empty, we attach comments to tree as 'leadingComments' - if (!tokens.length) { - if (providedComments.length) { - for (i = 0, len = providedComments.length; i < len; i += 1) { - comment = deepCopy(providedComments[i]); - comment.extendedRange = [0, tree.range[0]]; - comments.push(comment); - } - tree.leadingComments = comments; - } - return tree; - } + this._readdirBackend = createBackend( + duration, + this.fileSystem.readdir, + this.fileSystem.readdirSync, + this.fileSystem + ); + const readdir = this._readdirBackend.provide; + this.readdir = /** @type {FileSystem["readdir"]} */ (readdir); + const readdirSync = this._readdirBackend.provideSync; + this.readdirSync = /** @type {SyncFileSystem["readdirSync"]} */ (readdirSync); - for (i = 0, len = providedComments.length; i < len; i += 1) { - comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); - } + this._readFileBackend = createBackend( + duration, + this.fileSystem.readFile, + this.fileSystem.readFileSync, + this.fileSystem + ); + const readFile = this._readFileBackend.provide; + this.readFile = /** @type {FileSystem["readFile"]} */ (readFile); + const readFileSync = this._readFileBackend.provideSync; + this.readFileSync = /** @type {SyncFileSystem["readFileSync"]} */ (readFileSync); - // This is based on John Freeman's implementation. - cursor = 0; - traverse(tree, { - enter: function (node) { - var comment; + this._readJsonBackend = createBackend( + duration, + this.fileSystem.readJson || + (this.readFile && + ((path, callback) => { + // @ts-ignore + this.readFile(path, (err, buffer) => { + if (err) return callback(err); + if (!buffer || buffer.length === 0) + return callback(new Error("No file content")); + let data; + try { + data = JSON.parse(buffer.toString("utf-8")); + } catch (e) { + return callback(e); + } + callback(null, data); + }); + })), + this.fileSystem.readJsonSync || + (this.readFileSync && + (path => { + const buffer = this.readFileSync(path); + const data = JSON.parse(buffer.toString("utf-8")); + return data; + })), + this.fileSystem + ); + const readJson = this._readJsonBackend.provide; + this.readJson = /** @type {FileSystem["readJson"]} */ (readJson); + const readJsonSync = this._readJsonBackend.provideSync; + this.readJsonSync = /** @type {SyncFileSystem["readJsonSync"]} */ (readJsonSync); - while (cursor < comments.length) { - comment = comments[cursor]; - if (comment.extendedRange[1] > node.range[0]) { - break; - } + this._readlinkBackend = createBackend( + duration, + this.fileSystem.readlink, + this.fileSystem.readlinkSync, + this.fileSystem + ); + const readlink = this._readlinkBackend.provide; + this.readlink = /** @type {FileSystem["readlink"]} */ (readlink); + const readlinkSync = this._readlinkBackend.provideSync; + this.readlinkSync = /** @type {SyncFileSystem["readlinkSync"]} */ (readlinkSync); + } - if (comment.extendedRange[1] === node.range[0]) { - if (!node.leadingComments) { - node.leadingComments = []; - } - node.leadingComments.push(comment); - comments.splice(cursor, 1); - } else { - cursor += 1; - } - } + purge(what) { + this._statBackend.purge(what); + this._lstatBackend.purge(what); + this._readdirBackend.purgeParent(what); + this._readFileBackend.purge(what); + this._readlinkBackend.purge(what); + this._readJsonBackend.purge(what); + } +}; - // already out of owned node - if (cursor === comments.length) { - return VisitorOption.Break; - } - if (comments[cursor].extendedRange[0] > node.range[1]) { - return VisitorOption.Skip; - } - } - }); +/***/ }), - cursor = 0; - traverse(tree, { - leave: function (node) { - var comment; +/***/ 2020: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - while (cursor < comments.length) { - comment = comments[cursor]; - if (node.range[1] < comment.extendedRange[0]) { - break; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (node.range[1] === comment.extendedRange[0]) { - if (!node.trailingComments) { - node.trailingComments = []; - } - node.trailingComments.push(comment); - comments.splice(cursor, 1); - } else { - cursor += 1; - } - } - // already out of owned node - if (cursor === comments.length) { - return VisitorOption.Break; - } - if (comments[cursor].extendedRange[0] > node.range[1]) { - return VisitorOption.Skip; - } - } - }); +const basename = (__webpack_require__(48608).basename); - return tree; - } +/** @typedef {import("./Resolver")} Resolver */ - exports.version = (__webpack_require__(15535)/* .version */ .i8); - exports.Syntax = Syntax; - exports.traverse = traverse; - exports.replace = replace; - exports.attachComments = attachComments; - exports.VisitorKeys = VisitorKeys; - exports.VisitorOption = VisitorOption; - exports.Controller = Controller; - exports.cloneEnvironment = function () { return clone({}); }; +module.exports = class CloneBasenamePlugin { + constructor(source, target) { + this.source = source; + this.target = target; + } - return exports; -}(exports)); -/* vim: set sw=4 ts=4 et tw=80 : */ + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("CloneBasenamePlugin", (request, resolveContext, callback) => { + const filename = basename(request.path); + const filePath = resolver.join(request.path, filename); + const obj = { + ...request, + path: filePath, + relativePath: + request.relativePath && + resolver.join(request.relativePath, filename) + }; + resolver.doResolve( + target, + obj, + "using path: " + filePath, + resolveContext, + callback + ); + }); + } +}; /***/ }), -/***/ 86140: +/***/ 44193: /***/ (function(module) { -module.exports = function (glob, opts) { - if (typeof glob !== 'string') { - throw new TypeError('Expected a string'); - } - - var str = String(glob); - - // The regexp we are building, as a string. - var reStr = ""; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Whether we are matching so called "extended" globs (like bash) and should - // support single character matching, matching ranges of characters, group - // matching, etc. - var extended = opts ? !!opts.extended : false; - // When globstar is _false_ (default), '/foo/*' is translated a regexp like - // '^\/foo\/.*$' which will match any string beginning with '/foo/' - // When globstar is _true_, '/foo/*' is translated to regexp like - // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT - // which does not have a '/' to the right of it. - // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but - // these will not '/foo/bar/baz', '/foo/bar/baz.txt' - // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when - // globstar is _false_ - var globstar = opts ? !!opts.globstar : false; - // If we are doing extended matching, this boolean is true when we are inside - // a group (eg {*.html,*.js}), and false otherwise. - var inGroup = false; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - // RegExp flags (eg "i" ) to pass in to RegExp constructor. - var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; +module.exports = class ConditionalPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Partial} test compare object + * @param {string | null} message log message + * @param {boolean} allowAlternatives when false, do not continue with the current step when "test" matches + * @param {string | ResolveStepHook} target target + */ + constructor(source, test, message, allowAlternatives, target) { + this.source = source; + this.test = test; + this.message = message; + this.allowAlternatives = allowAlternatives; + this.target = target; + } - var c; - for (var i = 0, len = str.length; i < len; i++) { - c = str[i]; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const { test, message, allowAlternatives } = this; + const keys = Object.keys(test); + resolver + .getHook(this.source) + .tapAsync("ConditionalPlugin", (request, resolveContext, callback) => { + for (const prop of keys) { + if (request[prop] !== test[prop]) return callback(); + } + resolver.doResolve( + target, + request, + message, + resolveContext, + allowAlternatives + ? callback + : (err, result) => { + if (err) return callback(err); - switch (c) { - case "/": - case "$": - case "^": - case "+": - case ".": - case "(": - case ")": - case "=": - case "!": - case "|": - reStr += "\\" + c; - break; + // Don't allow other alternatives + if (result === undefined) return callback(null, null); + callback(null, result); + } + ); + }); + } +}; - case "?": - if (extended) { - reStr += "."; - break; - } - case "[": - case "]": - if (extended) { - reStr += c; - break; - } +/***/ }), - case "{": - if (extended) { - inGroup = true; - reStr += "("; - break; - } +/***/ 66826: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - case "}": - if (extended) { - inGroup = false; - reStr += ")"; - break; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - case ",": - if (inGroup) { - reStr += "|"; - break; - } - reStr += "\\" + c; - break; - case "*": - // Move over all consecutive "*"'s. - // Also store the previous and next characters - var prevChar = str[i - 1]; - var starCount = 1; - while(str[i + 1] === "*") { - starCount++; - i++; - } - var nextChar = str[i + 1]; - if (!globstar) { - // globstar is disabled, so treat any number of "*" as one - reStr += ".*"; - } else { - // globstar is enabled, so determine if this is a globstar segment - var isGlobstar = starCount > 1 // multiple "*"'s - && (prevChar === "/" || prevChar === undefined) // from the start of the segment - && (nextChar === "/" || nextChar === undefined) // to the end of the segment +const DescriptionFileUtils = __webpack_require__(702); - if (isGlobstar) { - // it's a globstar, so match zero or more path segments - reStr += "((?:[^/]*(?:\/|$))*)"; - i++; // move over the "/" - } else { - // it's not a globstar, so only match one path segment - reStr += "([^/]*)"; - } - } - break; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - default: - reStr += c; - } - } +module.exports = class DescriptionFilePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string[]} filenames filenames + * @param {boolean} pathIsFile pathIsFile + * @param {string | ResolveStepHook} target target + */ + constructor(source, filenames, pathIsFile, target) { + this.source = source; + this.filenames = filenames; + this.pathIsFile = pathIsFile; + this.target = target; + } - // When regexp 'g' flag is specified don't - // constrain the regular expression with ^ & $ - if (!flags || !~flags.indexOf('g')) { - reStr = "^" + reStr + "$"; - } + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "DescriptionFilePlugin", + (request, resolveContext, callback) => { + const path = request.path; + if (!path) return callback(); + const directory = this.pathIsFile + ? DescriptionFileUtils.cdUp(path) + : path; + if (!directory) return callback(); + DescriptionFileUtils.loadDescriptionFile( + resolver, + directory, + this.filenames, + request.descriptionFilePath + ? { + path: request.descriptionFilePath, + content: request.descriptionFileData, + directory: /** @type {string} */ (request.descriptionFileRoot) + } + : undefined, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (!result) { + if (resolveContext.log) + resolveContext.log( + `No description file found in ${directory} or above` + ); + return callback(); + } + const relativePath = + "." + path.substr(result.directory.length).replace(/\\/g, "/"); + const obj = { + ...request, + descriptionFilePath: result.path, + descriptionFileData: result.content, + descriptionFileRoot: result.directory, + relativePath: relativePath + }; + resolver.doResolve( + target, + obj, + "using description file: " + + result.path + + " (relative path: " + + relativePath + + ")", + resolveContext, + (err, result) => { + if (err) return callback(err); - return new RegExp(reStr, flags); + // Don't allow other processing + if (result === undefined) return callback(null, null); + callback(null, result); + } + ); + } + ); + } + ); + } }; /***/ }), -/***/ 89132: -/***/ (function(module) { +/***/ 702: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -module.exports = clone - -var getPrototypeOf = Object.getPrototypeOf || function (obj) { - return obj.__proto__ -} - -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj - - if (obj instanceof Object) - var copy = { __proto__: getPrototypeOf(obj) } - else - var copy = Object.create(null) - - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) - - return copy -} - - -/***/ }), -/***/ 90552: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const forEachBail = __webpack_require__(8266); -var fs = __webpack_require__(57147) -var polyfills = __webpack_require__(11290) -var legacy = __webpack_require__(54410) -var clone = __webpack_require__(89132) +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ -var util = __webpack_require__(73837) +/** + * @typedef {Object} DescriptionFileInfo + * @property {any=} content + * @property {string} path + * @property {string} directory + */ -/* istanbul ignore next - node 0.x polyfill */ -var gracefulQueue -var previousSymbol +/** + * @callback ErrorFirstCallback + * @param {Error|null=} error + * @param {DescriptionFileInfo=} result + */ -/* istanbul ignore else - node 0.x polyfill */ -if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { - gracefulQueue = Symbol.for('graceful-fs.queue') - // This is used in testing by future versions - previousSymbol = Symbol.for('graceful-fs.previous') -} else { - gracefulQueue = '___graceful-fs.queue' - previousSymbol = '___graceful-fs.previous' -} - -function noop () {} - -function publishQueue(context, queue) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue - } - }) -} - -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } - -// Once time initialization -if (!fs[gracefulQueue]) { - // This queue can be shared by multiple loaded instances - var queue = global[gracefulQueue] || [] - publishQueue(fs, queue) - - // Patch fs.close/closeSync to shared queue version, because we need - // to retry() whenever a close happens *anywhere* in the program. - // This is essential when multiple graceful-fs instances are - // in play at the same time. - fs.close = (function (fs$close) { - function close (fd, cb) { - return fs$close.call(fs, fd, function (err) { - // This function uses the graceful-fs shared queue - if (!err) { - resetQueue() - } - - if (typeof cb === 'function') - cb.apply(this, arguments) - }) - } - - Object.defineProperty(close, previousSymbol, { - value: fs$close - }) - return close - })(fs.close) +/** + * @param {Resolver} resolver resolver + * @param {string} directory directory + * @param {string[]} filenames filenames + * @param {DescriptionFileInfo|undefined} oldInfo oldInfo + * @param {ResolveContext} resolveContext resolveContext + * @param {ErrorFirstCallback} callback callback + */ +function loadDescriptionFile( + resolver, + directory, + filenames, + oldInfo, + resolveContext, + callback +) { + (function findDescriptionFile() { + if (oldInfo && oldInfo.directory === directory) { + // We already have info for this directory and can reuse it + return callback(null, oldInfo); + } + forEachBail( + filenames, + (filename, callback) => { + const descriptionFilePath = resolver.join(directory, filename); + if (resolver.fileSystem.readJson) { + resolver.fileSystem.readJson(descriptionFilePath, (err, content) => { + if (err) { + if (typeof err.code !== "undefined") { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(descriptionFilePath); + } + return callback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + return onJson(err); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + onJson(null, content); + }); + } else { + resolver.fileSystem.readFile(descriptionFilePath, (err, content) => { + if (err) { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(descriptionFilePath); + } + return callback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + let json; - fs.closeSync = (function (fs$closeSync) { - function closeSync (fd) { - // This function uses the graceful-fs shared queue - fs$closeSync.apply(fs, arguments) - resetQueue() - } + if (content) { + try { + json = JSON.parse(content.toString()); + } catch (e) { + return onJson(e); + } + } else { + return onJson(new Error("No content in file")); + } - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }) - return closeSync - })(fs.closeSync) + onJson(null, json); + }); + } - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(fs[gracefulQueue]) - __webpack_require__(39491).equal(fs[gracefulQueue].length, 0) - }) - } + function onJson(err, content) { + if (err) { + if (resolveContext.log) + resolveContext.log( + descriptionFilePath + " (directory description file): " + err + ); + else + err.message = + descriptionFilePath + " (directory description file): " + err; + return callback(err); + } + callback(null, { + content, + directory, + path: descriptionFilePath + }); + } + }, + (err, result) => { + if (err) return callback(err); + if (result) { + return callback(null, result); + } else { + const dir = cdUp(directory); + if (!dir) { + return callback(); + } else { + directory = dir; + return findDescriptionFile(); + } + } + } + ); + })(); } -if (!global[gracefulQueue]) { - publishQueue(global, fs[gracefulQueue]); +/** + * @param {any} content content + * @param {string|string[]} field field + * @returns {object|string|number|boolean|undefined} field data + */ +function getField(content, field) { + if (!content) return undefined; + if (Array.isArray(field)) { + let current = content; + for (let j = 0; j < field.length; j++) { + if (current === null || typeof current !== "object") { + current = null; + break; + } + current = current[field[j]]; + } + return current; + } else { + return content[field]; + } } -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; +/** + * @param {string} directory directory + * @returns {string|null} parent directory or null + */ +function cdUp(directory) { + if (directory === "/") return null; + const i = directory.lastIndexOf("/"), + j = directory.lastIndexOf("\\"); + const p = i < 0 ? j : j < 0 ? i : i < j ? j : i; + if (p < 0) return null; + return directory.substr(0, p || 1); } -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch +exports.loadDescriptionFile = loadDescriptionFile; +exports.getField = getField; +exports.cdUp = cdUp; - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null - return go$readFile(path, options, cb) +/***/ }), - function go$readFile (path, options, cb, startTime) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } +/***/ 73688: +/***/ (function(module) { - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - return go$writeFile(path, data, options, cb) - function go$writeFile (path, data, options, cb, startTime) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - return go$appendFile(path, data, options, cb) +module.exports = class DirectoryExistsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } - function go$appendFile (path, data, options, cb, startTime) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "DirectoryExistsPlugin", + (request, resolveContext, callback) => { + const fs = resolver.fileSystem; + const directory = request.path; + if (!directory) return callback(); + fs.stat(directory, (err, stat) => { + if (err || !stat) { + if (resolveContext.missingDependencies) + resolveContext.missingDependencies.add(directory); + if (resolveContext.log) + resolveContext.log(directory + " doesn't exist"); + return callback(); + } + if (!stat.isDirectory()) { + if (resolveContext.missingDependencies) + resolveContext.missingDependencies.add(directory); + if (resolveContext.log) + resolveContext.log(directory + " is not a directory"); + return callback(); + } + if (resolveContext.fileDependencies) + resolveContext.fileDependencies.add(directory); + resolver.doResolve( + target, + request, + `existing directory ${directory}`, + resolveContext, + callback + ); + }); + } + ); + } +}; - var fs$copyFile = fs.copyFile - if (fs$copyFile) - fs.copyFile = copyFile - function copyFile (src, dest, flags, cb) { - if (typeof flags === 'function') { - cb = flags - flags = 0 - } - return go$copyFile(src, dest, flags, cb) - function go$copyFile (src, dest, flags, cb, startTime) { - return fs$copyFile(src, dest, flags, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } +/***/ }), - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null +/***/ 80163: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return go$readdir(path, options, cb) +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, options, function (err, files) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (files && files.sort) - files.sort() - if (typeof cb === 'function') - cb.call(this, err, files) - } - }) - } - } - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } +const path = __webpack_require__(71017); +const DescriptionFileUtils = __webpack_require__(702); +const forEachBail = __webpack_require__(8266); +const { processExportsField } = __webpack_require__(28348); +const { parseIdentifier } = __webpack_require__(7780); +const { checkExportsFieldTarget } = __webpack_require__(3011); - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./util/entrypoints").ExportsField} ExportsField */ +/** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } +module.exports = class ExportsFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} conditionNames condition names + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} target target + */ + constructor(source, conditionNames, fieldNamePath, target) { + this.source = source; + this.target = target; + this.conditionNames = conditionNames; + this.fieldName = fieldNamePath; + /** @type {WeakMap} */ + this.fieldProcessorCache = new WeakMap(); + } - Object.defineProperty(fs, 'ReadStream', { - get: function () { - return ReadStream - }, - set: function (val) { - ReadStream = val - }, - enumerable: true, - configurable: true - }) - Object.defineProperty(fs, 'WriteStream', { - get: function () { - return WriteStream - }, - set: function (val) { - WriteStream = val - }, - enumerable: true, - configurable: true - }) + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ExportsFieldPlugin", (request, resolveContext, callback) => { + // When there is no description file, abort + if (!request.descriptionFilePath) return callback(); + if ( + // When the description file is inherited from parent, abort + // (There is no description file inside of this package) + request.relativePath !== "." || + request.request === undefined + ) + return callback(); - // legacy names - var FileReadStream = ReadStream - Object.defineProperty(fs, 'FileReadStream', { - get: function () { - return FileReadStream - }, - set: function (val) { - FileReadStream = val - }, - enumerable: true, - configurable: true - }) - var FileWriteStream = WriteStream - Object.defineProperty(fs, 'FileWriteStream', { - get: function () { - return FileWriteStream - }, - set: function (val) { - FileWriteStream = val - }, - enumerable: true, - configurable: true - }) + const remainingRequest = + request.query || request.fragment + ? (request.request === "." ? "./" : request.request) + + request.query + + request.fragment + : request.request; + /** @type {ExportsField|null} */ + const exportsField = DescriptionFileUtils.getField( + request.descriptionFileData, + this.fieldName + ); + if (!exportsField) return callback(); - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } + if (request.directory) { + return callback( + new Error( + `Resolving to directories is not possible with the exports field (request was ${remainingRequest}/)` + ) + ); + } - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() + let paths; - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } + try { + // We attach the cache to the description file instead of the exportsField value + // because we use a WeakMap and the exportsField could be a string too. + // Description file is always an object when exports field can be accessed. + let fieldProcessor = this.fieldProcessorCache.get( + request.descriptionFileData + ); + if (fieldProcessor === undefined) { + fieldProcessor = processExportsField(exportsField); + this.fieldProcessorCache.set( + request.descriptionFileData, + fieldProcessor + ); + } + paths = fieldProcessor(remainingRequest, this.conditionNames); + } catch (err) { + if (resolveContext.log) { + resolveContext.log( + `Exports field in ${request.descriptionFilePath} can't be processed: ${err}` + ); + } + return callback(err); + } - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } + if (paths.length === 0) { + return callback( + new Error( + `Package path ${remainingRequest} is not exported from package ${request.descriptionFileRoot} (see exports field in ${request.descriptionFilePath})` + ) + ); + } - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } + forEachBail( + paths, + (p, callback) => { + const parsedIdentifier = parseIdentifier(p); - function createReadStream (path, options) { - return new fs.ReadStream(path, options) - } + if (!parsedIdentifier) return callback(); - function createWriteStream (path, options) { - return new fs.WriteStream(path, options) - } + const [relativePath, query, fragment] = parsedIdentifier; - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null + const error = checkExportsFieldTarget(relativePath); - return go$open(path, flags, mode, cb) + if (error) { + return callback(error); + } - function go$open (path, flags, mode, cb, startTime) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + const obj = { + ...request, + request: undefined, + path: path.join( + /** @type {string} */ (request.descriptionFileRoot), + relativePath + ), + relativePath, + query, + fragment + }; - return fs -} + resolver.doResolve( + target, + obj, + "using exports field: " + p, + resolveContext, + callback + ); + }, + (err, result) => callback(err, result || null) + ); + }); + } +}; -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - fs[gracefulQueue].push(elem) - retry() -} -// keep track of the timeout between retry() calls -var retryTimer +/***/ }), -// reset the startTime and lastTime to now -// this resets the start of the 60 second overall timeout as well as the -// delay between attempts so that we'll retry these jobs sooner -function resetQueue () { - var now = Date.now() - for (var i = 0; i < fs[gracefulQueue].length; ++i) { - // entries that are only a length of 2 are from an older version, don't - // bother modifying those since they'll be retried anyway. - if (fs[gracefulQueue][i].length > 2) { - fs[gracefulQueue][i][3] = now // startTime - fs[gracefulQueue][i][4] = now // lastTime - } - } - // call retry to make sure we're actively processing the queue - retry() -} +/***/ 98699: +/***/ (function(module) { -function retry () { - // clear the timer and remove it to help prevent unintended concurrency - clearTimeout(retryTimer) - retryTimer = undefined +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (fs[gracefulQueue].length === 0) - return - var elem = fs[gracefulQueue].shift() - var fn = elem[0] - var args = elem[1] - // these items may be unset if they were added by an older graceful-fs - var err = elem[2] - var startTime = elem[3] - var lastTime = elem[4] - // if we don't have a startTime we have no way of knowing if we've waited - // long enough, so go ahead and retry this item now - if (startTime === undefined) { - debug('RETRY', fn.name, args) - fn.apply(null, args) - } else if (Date.now() - startTime >= 60000) { - // it's been more than 60 seconds total, bail now - debug('TIMEOUT', fn.name, args) - var cb = args.pop() - if (typeof cb === 'function') - cb.call(null, err) - } else { - // the amount of time between the last attempt and right now - var sinceAttempt = Date.now() - lastTime - // the amount of time between when we first tried, and when we last tried - // rounded up to at least 1 - var sinceStart = Math.max(lastTime - startTime, 1) - // backoff. wait longer than the total time we've been retrying, but only - // up to a maximum of 100ms - var desiredDelay = Math.min(sinceStart * 1.2, 100) - // it's been long enough since the last retry, do it again - if (sinceAttempt >= desiredDelay) { - debug('RETRY', fn.name, args) - fn.apply(null, args.concat([startTime])) - } else { - // if we can't do this job yet, push it to the end of the queue - // and let the next iteration check again - fs[gracefulQueue].push(elem) - } - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - // schedule our next run if one isn't already scheduled - if (retryTimer === undefined) { - retryTimer = setTimeout(retry, 0) - } -} +module.exports = class FileExistsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const fs = resolver.fileSystem; + resolver + .getHook(this.source) + .tapAsync("FileExistsPlugin", (request, resolveContext, callback) => { + const file = request.path; + if (!file) return callback(); + fs.stat(file, (err, stat) => { + if (err || !stat) { + if (resolveContext.missingDependencies) + resolveContext.missingDependencies.add(file); + if (resolveContext.log) resolveContext.log(file + " doesn't exist"); + return callback(); + } + if (!stat.isFile()) { + if (resolveContext.missingDependencies) + resolveContext.missingDependencies.add(file); + if (resolveContext.log) resolveContext.log(file + " is not a file"); + return callback(); + } + if (resolveContext.fileDependencies) + resolveContext.fileDependencies.add(file); + resolver.doResolve( + target, + request, + "existing file: " + file, + resolveContext, + callback + ); + }); + }); + } +}; /***/ }), -/***/ 54410: +/***/ 86058: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -var Stream = (__webpack_require__(12781).Stream) +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ -module.exports = legacy -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); +const path = __webpack_require__(71017); +const DescriptionFileUtils = __webpack_require__(702); +const forEachBail = __webpack_require__(8266); +const { processImportsField } = __webpack_require__(28348); +const { parseIdentifier } = __webpack_require__(7780); - Stream.call(this); +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ +/** @typedef {import("./util/entrypoints").ImportsField} ImportsField */ - var self = this; +const dotCode = ".".charCodeAt(0); - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; +module.exports = class ImportsFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} conditionNames condition names + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} targetFile target file + * @param {string | ResolveStepHook} targetPackage target package + */ + constructor( + source, + conditionNames, + fieldNamePath, + targetFile, + targetPackage + ) { + this.source = source; + this.targetFile = targetFile; + this.targetPackage = targetPackage; + this.conditionNames = conditionNames; + this.fieldName = fieldNamePath; + /** @type {WeakMap} */ + this.fieldProcessorCache = new WeakMap(); + } - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const targetFile = resolver.ensureHook(this.targetFile); + const targetPackage = resolver.ensureHook(this.targetPackage); - options = options || {}; + resolver + .getHook(this.source) + .tapAsync("ImportsFieldPlugin", (request, resolveContext, callback) => { + // When there is no description file, abort + if (!request.descriptionFilePath || request.request === undefined) { + return callback(); + } - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } + const remainingRequest = + request.request + request.query + request.fragment; + /** @type {ImportsField|null} */ + const importsField = DescriptionFileUtils.getField( + request.descriptionFileData, + this.fieldName + ); + if (!importsField) return callback(); - if (this.encoding) this.setEncoding(this.encoding); + if (request.directory) { + return callback( + new Error( + `Resolving to directories is not possible with the imports field (request was ${remainingRequest}/)` + ) + ); + } - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } + let paths; - if (this.start > this.end) { - throw new Error('start must be <= end'); - } + try { + // We attach the cache to the description file instead of the importsField value + // because we use a WeakMap and the importsField could be a string too. + // Description file is always an object when exports field can be accessed. + let fieldProcessor = this.fieldProcessorCache.get( + request.descriptionFileData + ); + if (fieldProcessor === undefined) { + fieldProcessor = processImportsField(importsField); + this.fieldProcessorCache.set( + request.descriptionFileData, + fieldProcessor + ); + } + paths = fieldProcessor(remainingRequest, this.conditionNames); + } catch (err) { + if (resolveContext.log) { + resolveContext.log( + `Imports field in ${request.descriptionFilePath} can't be processed: ${err}` + ); + } + return callback(err); + } - this.pos = this.start; - } + if (paths.length === 0) { + return callback( + new Error( + `Package import ${remainingRequest} is not imported from package ${request.descriptionFileRoot} (see imports field in ${request.descriptionFilePath})` + ) + ); + } - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } + forEachBail( + paths, + (p, callback) => { + const parsedIdentifier = parseIdentifier(p); - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } + if (!parsedIdentifier) return callback(); - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } + const [path_, query, fragment] = parsedIdentifier; - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); + switch (path_.charCodeAt(0)) { + // should be relative + case dotCode: { + const obj = { + ...request, + request: undefined, + path: path.join( + /** @type {string} */ (request.descriptionFileRoot), + path_ + ), + relativePath: path_, + query, + fragment + }; - Stream.call(this); + resolver.doResolve( + targetFile, + obj, + "using imports field: " + p, + resolveContext, + callback + ); + break; + } - this.path = path; - this.fd = null; - this.writable = true; + // package resolving + default: { + const obj = { + ...request, + request: path_, + relativePath: path_, + fullySpecified: true, + query, + fragment + }; - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; + resolver.doResolve( + targetPackage, + obj, + "using imports field: " + p, + resolveContext, + callback + ); + } + } + }, + (err, result) => callback(err, result || null) + ); + }); + } +}; - options = options || {}; - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +/***/ }), - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } +/***/ 20879: +/***/ (function(module) { - this.pos = this.start; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - this.busy = false; - this._queue = []; - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } - } -} +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/***/ }), +const namespaceStartCharCode = "@".charCodeAt(0); -/***/ 11290: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +module.exports = class JoinRequestPartPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } -var constants = __webpack_require__(22057) + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "JoinRequestPartPlugin", + (request, resolveContext, callback) => { + const req = request.request || ""; + let i = req.indexOf("/", 3); -var origCwd = process.cwd -var cwd = null - -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} + if (i >= 0 && req.charCodeAt(2) === namespaceStartCharCode) { + i = req.indexOf("/", i + 1); + } -// This check is needed until node.js 12 is required -if (typeof process.chdir === 'function') { - var chdir = process.chdir - process.chdir = function (d) { - cwd = null - chdir.call(process, d) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) -} + let moduleName, remainingRequest, fullySpecified; + if (i < 0) { + moduleName = req; + remainingRequest = "."; + fullySpecified = false; + } else { + moduleName = req.slice(0, i); + remainingRequest = "." + req.slice(i); + fullySpecified = request.fullySpecified; + } + const obj = { + ...request, + path: resolver.join(request.path, moduleName), + relativePath: + request.relativePath && + resolver.join(request.relativePath, moduleName), + request: remainingRequest, + fullySpecified + }; + resolver.doResolve(target, obj, null, resolveContext, callback); + } + ); + } +}; -module.exports = patch -function patch (fs) { - // (re-)implement some things that are known busted or missing. +/***/ }), - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } +/***/ 71474: +/***/ (function(module) { - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) +module.exports = class JoinRequestPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("JoinRequestPlugin", (request, resolveContext, callback) => { + const obj = { + ...request, + path: resolver.join(request.path, request.request), + relativePath: + request.relativePath && + resolver.join(request.relativePath, request.request), + request: undefined + }; + resolver.doResolve(target, obj, null, resolveContext, callback); + }); + } +}; - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) +/***/ }), - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } +/***/ 47032: +/***/ (function(module) { - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) - } - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - // This ensures `util.promisify` works as it does for native `fs.read`. - if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) - return read - })(fs.read) +/** @typedef {import("./Resolver")} Resolver */ - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) +module.exports = class LogInfoPlugin { + constructor(source) { + this.source = source; + } - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const source = this.source; + resolver + .getHook(this.source) + .tapAsync("LogInfoPlugin", (request, resolveContext, callback) => { + if (!resolveContext.log) return callback(); + const log = resolveContext.log; + const prefix = "[" + source + "] "; + if (request.path) + log(prefix + "Resolving in directory: " + request.path); + if (request.request) + log(prefix + "Resolving request: " + request.request); + if (request.module) log(prefix + "Request is an module request."); + if (request.directory) log(prefix + "Request is a directory request."); + if (request.query) + log(prefix + "Resolving request query: " + request.query); + if (request.fragment) + log(prefix + "Resolving request fragment: " + request.fragment); + if (request.descriptionFilePath) + log( + prefix + "Has description data from " + request.descriptionFilePath + ); + if (request.relativePath) + log( + prefix + + "Relative path from description file is: " + + request.relativePath + ); + callback(); + }); + } +}; - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } +/***/ }), - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } +/***/ 73507: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } +const path = __webpack_require__(71017); +const DescriptionFileUtils = __webpack_require__(702); +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {{name: string|Array, forceRelative: boolean}} MainFieldOptions */ - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +const alreadyTriedMainField = Symbol("alreadyTriedMainField"); - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } +module.exports = class MainFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {MainFieldOptions} options options + * @param {string | ResolveStepHook} target target + */ + constructor(source, options, target) { + this.source = source; + this.options = options; + this.target = target; + } - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) - } - } + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("MainFieldPlugin", (request, resolveContext, callback) => { + if ( + request.path !== request.descriptionFileRoot || + request[alreadyTriedMainField] === request.descriptionFilePath || + !request.descriptionFilePath + ) + return callback(); + const filename = path.basename(request.descriptionFilePath); + let mainModule = DescriptionFileUtils.getField( + request.descriptionFileData, + this.options.name + ); - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - return stats; - } - } + if ( + !mainModule || + typeof mainModule !== "string" || + mainModule === "." || + mainModule === "./" + ) { + return callback(); + } + if (this.options.forceRelative && !/^\.\.?\//.test(mainModule)) + mainModule = "./" + mainModule; + const obj = { + ...request, + request: mainModule, + module: false, + directory: mainModule.endsWith("/"), + [alreadyTriedMainField]: request.descriptionFilePath + }; + return resolver.doResolve( + target, + obj, + "use " + + mainModule + + " from " + + this.options.name + + " in " + + filename, + resolveContext, + callback + ); + }); + } +}; - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true - if (er.code === "ENOSYS") - return true +/***/ }), - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } +/***/ 3688: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return false - } -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/***/ }), -/***/ 15235: -/***/ (function(module) { +const forEachBail = __webpack_require__(8266); +const getPaths = __webpack_require__(48608); -"use strict"; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +module.exports = class ModulesInHierachicDirectoriesPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | Array} directories directories + * @param {string | ResolveStepHook} target target + */ + constructor(source, directories, target) { + this.source = source; + this.directories = /** @type {Array} */ ([]).concat(directories); + this.target = target; + } -module.exports = parseJson -function parseJson (txt, reviver, context) { - context = context || 20 - try { - return JSON.parse(txt, reviver) - } catch (e) { - if (typeof txt !== 'string') { - const isEmptyArray = Array.isArray(txt) && txt.length === 0 - const errorMessage = 'Cannot parse ' + - (isEmptyArray ? 'an empty array' : String(txt)) - throw new TypeError(errorMessage) - } - const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) - const errIdx = syntaxErr - ? +syntaxErr[1] - : e.message.match(/^Unexpected end of JSON.*/i) - ? txt.length - 1 - : null - if (errIdx != null) { - const start = errIdx <= context - ? 0 - : errIdx - context - const end = errIdx + context >= txt.length - ? txt.length - : errIdx + context - e.message += ` while parsing near '${ - start === 0 ? '' : '...' - }${txt.slice(start, end)}${ - end === txt.length ? '' : '...' - }'` - } else { - e.message += ` while parsing '${txt.slice(0, context * 2)}'` - } - throw e - } -} + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "ModulesInHierachicDirectoriesPlugin", + (request, resolveContext, callback) => { + const fs = resolver.fileSystem; + const addrs = getPaths(request.path) + .paths.map(p => { + return this.directories.map(d => resolver.join(p, d)); + }) + .reduce((array, p) => { + array.push.apply(array, p); + return array; + }, []); + forEachBail( + addrs, + (addr, callback) => { + fs.stat(addr, (err, stat) => { + if (!err && stat && stat.isDirectory()) { + const obj = { + ...request, + path: addr, + request: "./" + request.request, + module: false + }; + const message = "looking for modules in " + addr; + return resolver.doResolve( + target, + obj, + message, + resolveContext, + callback + ); + } + if (resolveContext.log) + resolveContext.log( + addr + " doesn't exist or is not a directory" + ); + if (resolveContext.missingDependencies) + resolveContext.missingDependencies.add(addr); + return callback(); + }); + }, + callback + ); + } + ); + } +}; /***/ }), -/***/ 54983: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 48952: +/***/ (function(module) { "use strict"; -var __webpack_unused_export__; - +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -__webpack_unused_export__ = ({ - value: true -}); -exports.Z = void 0; -const { - stringHints, - numberHints -} = __webpack_require__(79926); -/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */ -/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */ +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {import("./validate").Schema} Schema */ +module.exports = class ModulesInRootPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} path path + * @param {string | ResolveStepHook} target target + */ + constructor(source, path, target) { + this.source = source; + this.path = path; + this.target = target; + } -/** @typedef {import("./validate").ValidationErrorConfiguration} ValidationErrorConfiguration */ + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ModulesInRootPlugin", (request, resolveContext, callback) => { + const obj = { + ...request, + path: this.path, + request: "./" + request.request, + module: false + }; + resolver.doResolve( + target, + obj, + "looking for modules in " + this.path, + resolveContext, + callback + ); + }); + } +}; -/** @typedef {import("./validate").PostFormatter} PostFormatter */ -/** @typedef {import("./validate").SchemaUtilErrorObject} SchemaUtilErrorObject */ +/***/ }), -/** @enum {number} */ +/***/ 79135: +/***/ (function(module) { +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -const SPECIFICITY = { - type: 1, - not: 1, - oneOf: 1, - anyOf: 1, - if: 1, - enum: 1, - const: 1, - instanceof: 1, - required: 2, - pattern: 2, - patternRequired: 2, - format: 2, - formatMinimum: 2, - formatMaximum: 2, - minimum: 2, - exclusiveMinimum: 2, - maximum: 2, - exclusiveMaximum: 2, - multipleOf: 2, - uniqueItems: 2, - contains: 2, - minLength: 2, - maxLength: 2, - minItems: 2, - maxItems: 2, - minProperties: 2, - maxProperties: 2, - dependencies: 2, - propertyNames: 2, - additionalItems: 2, - additionalProperties: 2, - absolutePath: 2 -}; -/** - * - * @param {Array} array - * @param {(item: SchemaUtilErrorObject) => number} fn - * @returns {Array} - */ -function filterMax(array, fn) { - const evaluatedMax = array.reduce((max, item) => Math.max(max, fn(item)), 0); - return array.filter(item => fn(item) === evaluatedMax); -} -/** - * - * @param {Array} children - * @returns {Array} - */ +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -function filterChildren(children) { - let newChildren = children; - newChildren = filterMax(newChildren, - /** - * - * @param {SchemaUtilErrorObject} error - * @returns {number} - */ - error => error.dataPath ? error.dataPath.length : 0); - newChildren = filterMax(newChildren, - /** - * @param {SchemaUtilErrorObject} error - * @returns {number} - */ - error => SPECIFICITY[ - /** @type {keyof typeof SPECIFICITY} */ - error.keyword] || 2); - return newChildren; -} -/** - * Find all children errors - * @param {Array} children - * @param {Array} schemaPaths - * @return {number} returns index of first child - */ +module.exports = class NextPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("NextPlugin", (request, resolveContext, callback) => { + resolver.doResolve(target, request, null, resolveContext, callback); + }); + } +}; -function findAllChildren(children, schemaPaths) { - let i = children.length - 1; - const predicate = - /** - * @param {string} schemaPath - * @returns {boolean} - */ - schemaPath => children[i].schemaPath.indexOf(schemaPath) !== 0; +/***/ }), - while (i > -1 && !schemaPaths.every(predicate)) { - if (children[i].keyword === "anyOf" || children[i].keyword === "oneOf") { - const refs = extractRefs(children[i]); - const childrenStart = findAllChildren(children.slice(0, i), refs.concat(children[i].schemaPath)); - i = childrenStart - 1; - } else { - i -= 1; - } - } +/***/ 15234: +/***/ (function(module) { - return i + 1; -} -/** - * Extracts all refs from schema - * @param {SchemaUtilErrorObject} error - * @return {Array} - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -function extractRefs(error) { - const { - schema - } = error; - if (!Array.isArray(schema)) { - return []; - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - return schema.map(({ - $ref - }) => $ref).filter(s => s); -} -/** - * Groups children by their first level parent (assuming that error is root) - * @param {Array} children - * @return {Array} - */ +module.exports = class ParsePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Partial} requestOptions request options + * @param {string | ResolveStepHook} target target + */ + constructor(source, requestOptions, target) { + this.source = source; + this.requestOptions = requestOptions; + this.target = target; + } + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ParsePlugin", (request, resolveContext, callback) => { + const parsed = resolver.parse(/** @type {string} */ (request.request)); + const obj = { ...request, ...parsed, ...this.requestOptions }; + if (request.query && !parsed.query) { + obj.query = request.query; + } + if (request.fragment && !parsed.fragment) { + obj.fragment = request.fragment; + } + if (parsed && resolveContext.log) { + if (parsed.module) resolveContext.log("Parsed request is a module"); + if (parsed.directory) + resolveContext.log("Parsed request is a directory"); + } + // There is an edge-case where a request with # can be a path or a fragment -> try both + if (obj.request && !obj.query && obj.fragment) { + const directory = obj.fragment.endsWith("/"); + const alternative = { + ...obj, + directory, + request: + obj.request + + (obj.directory ? "/" : "") + + (directory ? obj.fragment.slice(0, -1) : obj.fragment), + fragment: "" + }; + resolver.doResolve( + target, + alternative, + null, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + resolver.doResolve(target, obj, null, resolveContext, callback); + } + ); + return; + } + resolver.doResolve(target, obj, null, resolveContext, callback); + }); + } +}; -function groupChildrenByFirstChild(children) { - const result = []; - let i = children.length - 1; - while (i > 0) { - const child = children[i]; +/***/ }), - if (child.keyword === "anyOf" || child.keyword === "oneOf") { - const refs = extractRefs(child); - const childrenStart = findAllChildren(children.slice(0, i), refs.concat(child.schemaPath)); +/***/ 71488: +/***/ (function(module) { - if (childrenStart !== i) { - result.push(Object.assign({}, child, { - children: children.slice(childrenStart, i) - })); - i = childrenStart; - } else { - result.push(child); - } - } else { - result.push(child); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Maël Nison @arcanis +*/ - i -= 1; - } - if (i === 0) { - result.push(children[i]); - } - return result.reverse(); -} +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ /** - * @param {string} str - * @param {string} prefix - * @returns {string} + * @typedef {Object} PnpApiImpl + * @property {function(string, string, object): string} resolveToUnqualified */ +module.exports = class PnpPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {PnpApiImpl} pnpApi pnpApi + * @param {string | ResolveStepHook} target target + */ + constructor(source, pnpApi, target) { + this.source = source; + this.pnpApi = pnpApi; + this.target = target; + } -function indent(str, prefix) { - return str.replace(/\n(?!$)/g, `\n${prefix}`); -} -/** - * @param {Schema} schema - * @returns {schema is (Schema & {not: Schema})} - */ + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("PnpPlugin", (request, resolveContext, callback) => { + const req = request.request; + if (!req) return callback(); + // The trailing slash indicates to PnP that this value is a folder rather than a file + const issuer = `${request.path}/`; -function hasNotInSchema(schema) { - return !!schema.not; -} -/** - * @param {Schema} schema - * @return {Schema} - */ + const packageMatch = /^(@[^/]+\/)?[^/]+/.exec(req); + if (!packageMatch) return callback(); + const packageName = packageMatch[0]; + const innerRequest = `.${req.slice(packageName.length)}`; -function findFirstTypedSchema(schema) { - if (hasNotInSchema(schema)) { - return findFirstTypedSchema(schema.not); - } + let resolution; + let apiResolution; + try { + resolution = this.pnpApi.resolveToUnqualified(packageName, issuer, { + considerBuiltins: false + }); + if (resolveContext.fileDependencies) { + apiResolution = this.pnpApi.resolveToUnqualified("pnpapi", issuer, { + considerBuiltins: false + }); + } + } catch (error) { + if ( + error.code === "MODULE_NOT_FOUND" && + error.pnpCode === "UNDECLARED_DEPENDENCY" + ) { + // This is not a PnP managed dependency. + // Try to continue resolving with our alternatives + if (resolveContext.log) { + resolveContext.log(`request is not managed by the pnpapi`); + for (const line of error.message.split("\n").filter(Boolean)) + resolveContext.log(` ${line}`); + } + return callback(); + } + return callback(error); + } - return schema; -} -/** - * @param {Schema} schema - * @return {boolean} - */ + if (resolution === packageName) return callback(); + if (apiResolution && resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(apiResolution); + } -function canApplyNot(schema) { - const typedSchema = findFirstTypedSchema(schema); - return likeNumber(typedSchema) || likeInteger(typedSchema) || likeString(typedSchema) || likeNull(typedSchema) || likeBoolean(typedSchema); -} -/** - * @param {any} maybeObj - * @returns {boolean} - */ + const obj = { + ...request, + path: resolution, + request: innerRequest, + ignoreSymlinks: true, + fullySpecified: request.fullySpecified && innerRequest !== "." + }; + resolver.doResolve( + target, + obj, + `resolved by pnp to ${resolution}`, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + // Skip alternatives + return callback(null, null); + } + ); + }); + } +}; -function isObject(maybeObj) { - return typeof maybeObj === "object" && maybeObj !== null; -} -/** - * @param {Schema} schema - * @returns {boolean} - */ +/***/ }), + +/***/ 37432: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -function likeNumber(schema) { - return schema.type === "number" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; -} -/** - * @param {Schema} schema - * @returns {boolean} - */ -function likeInteger(schema) { - return schema.type === "integer" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; -} -/** - * @param {Schema} schema - * @returns {boolean} - */ +const { AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } = __webpack_require__(41242); +const createInnerContext = __webpack_require__(95478); +const { parseIdentifier } = __webpack_require__(7780); +const { + normalize, + cachedJoin: join, + getType, + PathType +} = __webpack_require__(3011); +/** @typedef {import("./ResolverFactory").ResolveOptions} ResolveOptions */ -function likeString(schema) { - return schema.type === "string" || typeof schema.minLength !== "undefined" || typeof schema.maxLength !== "undefined" || typeof schema.pattern !== "undefined" || typeof schema.format !== "undefined" || typeof schema.formatMinimum !== "undefined" || typeof schema.formatMaximum !== "undefined"; -} /** - * @param {Schema} schema - * @returns {boolean} + * @typedef {Object} FileSystemStats + * @property {function(): boolean} isDirectory + * @property {function(): boolean} isFile */ - -function likeBoolean(schema) { - return schema.type === "boolean"; -} /** - * @param {Schema} schema - * @returns {boolean} + * @typedef {Object} FileSystemDirent + * @property {Buffer | string} name + * @property {function(): boolean} isDirectory + * @property {function(): boolean} isFile */ - -function likeArray(schema) { - return schema.type === "array" || typeof schema.minItems === "number" || typeof schema.maxItems === "number" || typeof schema.uniqueItems !== "undefined" || typeof schema.items !== "undefined" || typeof schema.additionalItems !== "undefined" || typeof schema.contains !== "undefined"; -} /** - * @param {Schema & {patternRequired?: Array}} schema - * @returns {boolean} + * @typedef {Object} PossibleFileSystemError + * @property {string=} code + * @property {number=} errno + * @property {string=} path + * @property {string=} syscall */ - -function likeObject(schema) { - return schema.type === "object" || typeof schema.minProperties !== "undefined" || typeof schema.maxProperties !== "undefined" || typeof schema.required !== "undefined" || typeof schema.properties !== "undefined" || typeof schema.patternProperties !== "undefined" || typeof schema.additionalProperties !== "undefined" || typeof schema.dependencies !== "undefined" || typeof schema.propertyNames !== "undefined" || typeof schema.patternRequired !== "undefined"; -} /** - * @param {Schema} schema - * @returns {boolean} + * @template T + * @callback FileSystemCallback + * @param {PossibleFileSystemError & Error | null | undefined} err + * @param {T=} result */ - -function likeNull(schema) { - return schema.type === "null"; -} /** - * @param {string} type - * @returns {string} + * @typedef {Object} FileSystem + * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} readFile + * @property {(function(string, FileSystemCallback<(Buffer | string)[] | FileSystemDirent[]>): void) & function(string, object, FileSystemCallback<(Buffer | string)[] | FileSystemDirent[]>): void} readdir + * @property {((function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void)=} readJson + * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} readlink + * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void=} lstat + * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} stat */ - -function getArticle(type) { - if (/^[aeiou]/i.test(type)) { - return "an"; - } - - return "a"; -} /** - * @param {Schema=} schema - * @returns {string} + * @typedef {Object} SyncFileSystem + * @property {function(string, object=): Buffer | string} readFileSync + * @property {function(string, object=): (Buffer | string)[] | FileSystemDirent[]} readdirSync + * @property {(function(string, object=): object)=} readJsonSync + * @property {function(string, object=): Buffer | string} readlinkSync + * @property {function(string, object=): FileSystemStats=} lstatSync + * @property {function(string, object=): FileSystemStats} statSync */ +/** + * @typedef {Object} ParsedIdentifier + * @property {string} request + * @property {string} query + * @property {string} fragment + * @property {boolean} directory + * @property {boolean} module + * @property {boolean} file + * @property {boolean} internal + */ -function getSchemaNonTypes(schema) { - if (!schema) { - return ""; - } - - if (!schema.type) { - if (likeNumber(schema) || likeInteger(schema)) { - return " | should be any non-number"; - } - - if (likeString(schema)) { - return " | should be any non-string"; - } - - if (likeArray(schema)) { - return " | should be any non-array"; - } +/** + * @typedef {Object} BaseResolveRequest + * @property {string | false} path + * @property {string=} descriptionFilePath + * @property {string=} descriptionFileRoot + * @property {object=} descriptionFileData + * @property {string=} relativePath + * @property {boolean=} ignoreSymlinks + * @property {boolean=} fullySpecified + */ - if (likeObject(schema)) { - return " | should be any non-object"; - } - } +/** @typedef {BaseResolveRequest & Partial} ResolveRequest */ - return ""; -} /** - * @param {Array} hints - * @returns {string} + * String with special formatting + * @typedef {string} StackEntry */ +/** @template T @typedef {{ add: (T) => void }} WriteOnlySet */ -function formatHints(hints) { - return hints.length > 0 ? `(${hints.join(", ")})` : ""; -} /** - * @param {Schema} schema - * @param {boolean} logic - * @returns {string[]} + * Resolve context + * @typedef {Object} ResolveContext + * @property {WriteOnlySet=} contextDependencies + * @property {WriteOnlySet=} fileDependencies files that was found on file system + * @property {WriteOnlySet=} missingDependencies dependencies that was not found on file system + * @property {Set=} stack set of hooks' calls. For instance, `resolve → parsedResolve → describedResolve`, + * @property {(function(string): void)=} log log function */ +/** @typedef {AsyncSeriesBailHook<[ResolveRequest, ResolveContext], ResolveRequest | null>} ResolveStepHook */ -function getHints(schema, logic) { - if (likeNumber(schema) || likeInteger(schema)) { - return numberHints(schema, logic); - } else if (likeString(schema)) { - return stringHints(schema, logic); - } - - return []; +/** + * @param {string} str input string + * @returns {string} in camel case + */ +function toCamelCase(str) { + return str.replace(/-([a-z])/g, str => str.substr(1).toUpperCase()); } -class ValidationError extends Error { - /** - * @param {Array} errors - * @param {Schema} schema - * @param {ValidationErrorConfiguration} configuration - */ - constructor(errors, schema, configuration = {}) { - super(); - /** @type {string} */ +class Resolver { + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @returns {StackEntry} stack entry + */ + static createStackEntry(hook, request) { + return ( + hook.name + + ": (" + + request.path + + ") " + + (request.request || "") + + (request.query || "") + + (request.fragment || "") + + (request.directory ? " directory" : "") + + (request.module ? " module" : "") + ); + } - this.name = "ValidationError"; - /** @type {Array} */ + /** + * @param {FileSystem} fileSystem a filesystem + * @param {ResolveOptions} options options + */ + constructor(fileSystem, options) { + this.fileSystem = fileSystem; + this.options = options; + this.hooks = { + /** @type {SyncHook<[ResolveStepHook, ResolveRequest], void>} */ + resolveStep: new SyncHook(["hook", "request"], "resolveStep"), + /** @type {SyncHook<[ResolveRequest, Error]>} */ + noResolve: new SyncHook(["request", "error"], "noResolve"), + /** @type {ResolveStepHook} */ + resolve: new AsyncSeriesBailHook( + ["request", "resolveContext"], + "resolve" + ), + /** @type {AsyncSeriesHook<[ResolveRequest, ResolveContext]>} */ + result: new AsyncSeriesHook(["result", "resolveContext"], "result") + }; + } - this.errors = errors; - /** @type {Schema} */ + /** + * @param {string | ResolveStepHook} name hook name or hook itself + * @returns {ResolveStepHook} the hook + */ + ensureHook(name) { + if (typeof name !== "string") { + return name; + } + name = toCamelCase(name); + if (/^before/.test(name)) { + return /** @type {ResolveStepHook} */ (this.ensureHook( + name[6].toLowerCase() + name.substr(7) + ).withOptions({ + stage: -10 + })); + } + if (/^after/.test(name)) { + return /** @type {ResolveStepHook} */ (this.ensureHook( + name[5].toLowerCase() + name.substr(6) + ).withOptions({ + stage: 10 + })); + } + const hook = this.hooks[name]; + if (!hook) { + return (this.hooks[name] = new AsyncSeriesBailHook( + ["request", "resolveContext"], + name + )); + } + return hook; + } - this.schema = schema; - let headerNameFromSchema; - let baseDataPathFromSchema; + /** + * @param {string | ResolveStepHook} name hook name or hook itself + * @returns {ResolveStepHook} the hook + */ + getHook(name) { + if (typeof name !== "string") { + return name; + } + name = toCamelCase(name); + if (/^before/.test(name)) { + return /** @type {ResolveStepHook} */ (this.getHook( + name[6].toLowerCase() + name.substr(7) + ).withOptions({ + stage: -10 + })); + } + if (/^after/.test(name)) { + return /** @type {ResolveStepHook} */ (this.getHook( + name[5].toLowerCase() + name.substr(6) + ).withOptions({ + stage: 10 + })); + } + const hook = this.hooks[name]; + if (!hook) { + throw new Error(`Hook ${name} doesn't exist`); + } + return hook; + } - if (schema.title && (!configuration.name || !configuration.baseDataPath)) { - const splittedTitleFromSchema = schema.title.match(/^(.+) (.+)$/); + /** + * @param {object} context context information object + * @param {string} path context path + * @param {string} request request string + * @returns {string | false} result + */ + resolveSync(context, path, request) { + /** @type {Error | null | undefined} */ + let err = undefined; + /** @type {string | false | undefined} */ + let result = undefined; + let sync = false; + this.resolve(context, path, request, {}, (e, r) => { + err = e; + result = r; + sync = true; + }); + if (!sync) { + throw new Error( + "Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!" + ); + } + if (err) throw err; + if (result === undefined) throw new Error("No result"); + return result; + } - if (splittedTitleFromSchema) { - if (!configuration.name) { - [, headerNameFromSchema] = splittedTitleFromSchema; - } + /** + * @param {object} context context information object + * @param {string} path context path + * @param {string} request request string + * @param {ResolveContext} resolveContext resolve context + * @param {function(Error | null, (string|false)=, ResolveRequest=): void} callback callback function + * @returns {void} + */ + resolve(context, path, request, resolveContext, callback) { + if (!context || typeof context !== "object") + return callback(new Error("context argument is not an object")); + if (typeof path !== "string") + return callback(new Error("path argument is not a string")); + if (typeof request !== "string") + return callback(new Error("path argument is not a string")); + if (!resolveContext) + return callback(new Error("resolveContext argument is not set")); - if (!configuration.baseDataPath) { - [,, baseDataPathFromSchema] = splittedTitleFromSchema; - } - } - } - /** @type {string} */ + const obj = { + context: context, + path: path, + request: request + }; + const message = `resolve '${request}' in '${path}'`; - this.headerName = configuration.name || headerNameFromSchema || "Object"; - /** @type {string} */ + const finishResolved = result => { + return callback( + null, + result.path === false + ? false + : `${result.path.replace(/#/g, "\0#")}${ + result.query ? result.query.replace(/#/g, "\0#") : "" + }${result.fragment || ""}`, + result + ); + }; - this.baseDataPath = configuration.baseDataPath || baseDataPathFromSchema || "configuration"; - /** @type {PostFormatter | null} */ + const finishWithoutResolve = log => { + /** + * @type {Error & {details?: string}} + */ + const error = new Error("Can't " + message); + error.details = log.join("\n"); + this.hooks.noResolve.call(obj, error); + return callback(error); + }; - this.postFormatter = configuration.postFormatter || null; - const header = `Invalid ${this.baseDataPath} object. ${this.headerName} has been initialized using ${getArticle(this.baseDataPath)} ${this.baseDataPath} object that does not match the API schema.\n`; - /** @type {string} */ + if (resolveContext.log) { + // We need log anyway to capture it in case of an error + const parentLog = resolveContext.log; + const log = []; + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: msg => { + parentLog(msg); + log.push(msg); + }, + fileDependencies: resolveContext.fileDependencies, + contextDependencies: resolveContext.contextDependencies, + missingDependencies: resolveContext.missingDependencies, + stack: resolveContext.stack + }, + (err, result) => { + if (err) return callback(err); - this.message = `${header}${this.formatValidationErrors(errors)}`; - Error.captureStackTrace(this, this.constructor); - } - /** - * @param {string} path - * @returns {Schema} - */ + if (result) return finishResolved(result); + return finishWithoutResolve(log); + } + ); + } else { + // Try to resolve assuming there is no error + // We don't log stuff in this case + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: undefined, + fileDependencies: resolveContext.fileDependencies, + contextDependencies: resolveContext.contextDependencies, + missingDependencies: resolveContext.missingDependencies, + stack: resolveContext.stack + }, + (err, result) => { + if (err) return callback(err); - getSchemaPart(path) { - const newPath = path.split("/"); - let schemaPart = this.schema; + if (result) return finishResolved(result); - for (let i = 1; i < newPath.length; i++) { - const inner = schemaPart[ - /** @type {keyof Schema} */ - newPath[i]]; + // log is missing for the error details + // so we redo the resolving for the log info + // this is more expensive to the success case + // is assumed by default - if (!inner) { - break; - } + const log = []; - schemaPart = inner; - } + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: msg => log.push(msg), + stack: resolveContext.stack + }, + (err, result) => { + if (err) return callback(err); - return schemaPart; - } - /** - * @param {Schema} schema - * @param {boolean} logic - * @param {Array} prevSchemas - * @returns {string} - */ + return finishWithoutResolve(log); + } + ); + } + ); + } + } + doResolve(hook, request, message, resolveContext, callback) { + const stackEntry = Resolver.createStackEntry(hook, request); - formatSchema(schema, logic = true, prevSchemas = []) { - let newLogic = logic; + let newStack; + if (resolveContext.stack) { + newStack = new Set(resolveContext.stack); + if (resolveContext.stack.has(stackEntry)) { + /** + * Prevent recursion + * @type {Error & {recursion?: boolean}} + */ + const recursionError = new Error( + "Recursion in resolving\nStack:\n " + + Array.from(newStack).join("\n ") + ); + recursionError.recursion = true; + if (resolveContext.log) + resolveContext.log("abort resolving because of recursion"); + return callback(recursionError); + } + newStack.add(stackEntry); + } else { + newStack = new Set([stackEntry]); + } + this.hooks.resolveStep.call(hook, request); - const formatInnerSchema = - /** - * - * @param {Object} innerSchema - * @param {boolean=} addSelf - * @returns {string} - */ - (innerSchema, addSelf) => { - if (!addSelf) { - return this.formatSchema(innerSchema, newLogic, prevSchemas); - } + if (hook.isUsed()) { + const innerContext = createInnerContext( + { + log: resolveContext.log, + fileDependencies: resolveContext.fileDependencies, + contextDependencies: resolveContext.contextDependencies, + missingDependencies: resolveContext.missingDependencies, + stack: newStack + }, + message + ); + return hook.callAsync(request, innerContext, (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + callback(); + }); + } else { + callback(); + } + } - if (prevSchemas.includes(innerSchema)) { - return "(recursive)"; - } + /** + * @param {string} identifier identifier + * @returns {ParsedIdentifier} parsed identifier + */ + parse(identifier) { + const part = { + request: "", + query: "", + fragment: "", + module: false, + directory: false, + file: false, + internal: false + }; - return this.formatSchema(innerSchema, newLogic, prevSchemas.concat(schema)); - }; + const parsedIdentifier = parseIdentifier(identifier); - if (hasNotInSchema(schema) && !likeObject(schema)) { - if (canApplyNot(schema.not)) { - newLogic = !logic; - return formatInnerSchema(schema.not); - } + if (!parsedIdentifier) return part; - const needApplyLogicHere = !schema.not.not; - const prefix = logic ? "" : "non "; - newLogic = !logic; - return needApplyLogicHere ? prefix + formatInnerSchema(schema.not) : formatInnerSchema(schema.not); - } + [part.request, part.query, part.fragment] = parsedIdentifier; - if ( - /** @type {Schema & {instanceof: string | Array}} */ - schema.instanceof) { - const { - instanceof: value - } = - /** @type {Schema & {instanceof: string | Array}} */ - schema; - const values = !Array.isArray(value) ? [value] : value; - return values.map( - /** - * @param {string} item - * @returns {string} - */ - item => item === "Function" ? "function" : item).join(" | "); - } + if (part.request.length > 0) { + part.internal = this.isPrivate(identifier); + part.module = this.isModule(part.request); + part.directory = this.isDirectory(part.request); + if (part.directory) { + part.request = part.request.substr(0, part.request.length - 1); + } + } - if (schema.enum) { - return ( - /** @type {Array} */ - schema.enum.map(item => JSON.stringify(item)).join(" | ") - ); - } + return part; + } - if (typeof schema.const !== "undefined") { - return JSON.stringify(schema.const); - } + isModule(path) { + return getType(path) === PathType.Normal; + } - if (schema.oneOf) { - return ( - /** @type {Array} */ - schema.oneOf.map(item => formatInnerSchema(item, true)).join(" | ") - ); - } + isPrivate(path) { + return getType(path) === PathType.Internal; + } - if (schema.anyOf) { - return ( - /** @type {Array} */ - schema.anyOf.map(item => formatInnerSchema(item, true)).join(" | ") - ); - } + /** + * @param {string} path a path + * @returns {boolean} true, if the path is a directory path + */ + isDirectory(path) { + return path.endsWith("/"); + } - if (schema.allOf) { - return ( - /** @type {Array} */ - schema.allOf.map(item => formatInnerSchema(item, true)).join(" & ") - ); - } + join(path, request) { + return join(path, request); + } - if ( - /** @type {JSONSchema7} */ - schema.if) { - const { - if: ifValue, - then: thenValue, - else: elseValue - } = - /** @type {JSONSchema7} */ - schema; - return `${ifValue ? `if ${formatInnerSchema(ifValue)}` : ""}${thenValue ? ` then ${formatInnerSchema(thenValue)}` : ""}${elseValue ? ` else ${formatInnerSchema(elseValue)}` : ""}`; - } + normalize(path) { + return normalize(path); + } +} - if (schema.$ref) { - return formatInnerSchema(this.getSchemaPart(schema.$ref), true); - } +module.exports = Resolver; - if (likeNumber(schema) || likeInteger(schema)) { - const [type, ...hints] = getHints(schema, logic); - const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; - return logic ? str : hints.length > 0 ? `non-${type} | ${str}` : `non-${type}`; - } - if (likeString(schema)) { - const [type, ...hints] = getHints(schema, logic); - const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; - return logic ? str : str === "string" ? "non-string" : `non-string | ${str}`; - } +/***/ }), - if (likeBoolean(schema)) { - return `${logic ? "" : "non-"}boolean`; - } +/***/ 53990: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - if (likeArray(schema)) { - // not logic already applied in formatValidationError - newLogic = true; - const hints = []; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (typeof schema.minItems === "number") { - hints.push(`should not have fewer than ${schema.minItems} item${schema.minItems > 1 ? "s" : ""}`); - } - if (typeof schema.maxItems === "number") { - hints.push(`should not have more than ${schema.maxItems} item${schema.maxItems > 1 ? "s" : ""}`); - } - if (schema.uniqueItems) { - hints.push("should not have duplicate items"); - } +const versions = (__webpack_require__(77282).versions); +const Resolver = __webpack_require__(37432); +const { getType, PathType } = __webpack_require__(3011); + +const SyncAsyncFileSystemDecorator = __webpack_require__(57746); + +const AliasFieldPlugin = __webpack_require__(42752); +const AliasPlugin = __webpack_require__(51547); +const AppendPlugin = __webpack_require__(66477); +const ConditionalPlugin = __webpack_require__(44193); +const DescriptionFilePlugin = __webpack_require__(66826); +const DirectoryExistsPlugin = __webpack_require__(73688); +const ExportsFieldPlugin = __webpack_require__(80163); +const FileExistsPlugin = __webpack_require__(98699); +const ImportsFieldPlugin = __webpack_require__(86058); +const JoinRequestPartPlugin = __webpack_require__(20879); +const JoinRequestPlugin = __webpack_require__(71474); +const MainFieldPlugin = __webpack_require__(73507); +const ModulesInHierachicDirectoriesPlugin = __webpack_require__(3688); +const ModulesInRootPlugin = __webpack_require__(48952); +const NextPlugin = __webpack_require__(79135); +const ParsePlugin = __webpack_require__(15234); +const PnpPlugin = __webpack_require__(71488); +const RestrictionsPlugin = __webpack_require__(39222); +const ResultPlugin = __webpack_require__(10615); +const RootsPlugin = __webpack_require__(34403); +const SelfReferencePlugin = __webpack_require__(32317); +const SymlinkPlugin = __webpack_require__(21300); +const TryNextPlugin = __webpack_require__(16442); +const UnsafeCachePlugin = __webpack_require__(3501); +const UseFilePlugin = __webpack_require__(50318); - const hasAdditionalItems = typeof schema.additionalItems === "undefined" || Boolean(schema.additionalItems); - let items = ""; +/** @typedef {import("./AliasPlugin").AliasOption} AliasOptionEntry */ +/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ - if (schema.items) { - if (Array.isArray(schema.items) && schema.items.length > 0) { - items = `${ - /** @type {Array} */ - schema.items.map(item => formatInnerSchema(item)).join(", ")}`; +/** @typedef {string|string[]|false} AliasOptionNewRequest */ +/** @typedef {{[k: string]: AliasOptionNewRequest}} AliasOptions */ +/** @typedef {{apply: function(Resolver): void} | function(this: Resolver, Resolver): void} Plugin */ - if (hasAdditionalItems) { - if (schema.additionalItems && isObject(schema.additionalItems) && Object.keys(schema.additionalItems).length > 0) { - hints.push(`additional items should be ${formatInnerSchema(schema.additionalItems)}`); - } - } - } else if (schema.items && Object.keys(schema.items).length > 0) { - // "additionalItems" is ignored - items = `${formatInnerSchema(schema.items)}`; - } else { - // Fallback for empty `items` value - items = "any"; - } - } else { - // "additionalItems" is ignored - items = "any"; - } +/** + * @typedef {Object} UserResolveOptions + * @property {(AliasOptions | AliasOptionEntry[])=} alias A list of module alias configurations or an object which maps key to value + * @property {(AliasOptions | AliasOptionEntry[])=} fallback A list of module alias configurations or an object which maps key to value, applied only after modules option + * @property {(string | string[])[]=} aliasFields A list of alias fields in description files + * @property {(function(ResolveRequest): boolean)=} cachePredicate A function which decides whether a request should be cached or not. An object is passed with at least `path` and `request` properties. + * @property {boolean=} cacheWithContext Whether or not the unsafeCache should include request context as part of the cache key. + * @property {string[]=} descriptionFiles A list of description files to read from + * @property {string[]=} conditionNames A list of exports field condition names. + * @property {boolean=} enforceExtension Enforce that a extension from extensions must be used + * @property {(string | string[])[]=} exportsFields A list of exports fields in description files + * @property {(string | string[])[]=} importsFields A list of imports fields in description files + * @property {string[]=} extensions A list of extensions which should be tried for files + * @property {FileSystem} fileSystem The file system which should be used + * @property {(object | boolean)=} unsafeCache Use this cache object to unsafely cache the successful requests + * @property {boolean=} symlinks Resolve symlinks to their symlinked location + * @property {Resolver=} resolver A prepared Resolver to which the plugins are attached + * @property {string[] | string=} modules A list of directories to resolve modules from, can be absolute path or folder name + * @property {(string | string[] | {name: string | string[], forceRelative: boolean})[]=} mainFields A list of main fields in description files + * @property {string[]=} mainFiles A list of main files in directories + * @property {Plugin[]=} plugins A list of additional resolve plugins which should be applied + * @property {PnpApi | null=} pnpApi A PnP API that should be used - null is "never", undefined is "auto" + * @property {string[]=} roots A list of root paths + * @property {boolean=} fullySpecified The request is already fully specified and no extensions or directories are resolved for it + * @property {boolean=} resolveToContext Resolve to a context instead of a file + * @property {(string|RegExp)[]=} restrictions A list of resolve restrictions + * @property {boolean=} useSyncFileSystemCalls Use only the sync constiants of the file system calls + * @property {boolean=} preferRelative Prefer to resolve module requests as relative requests before falling back to modules + * @property {boolean=} preferAbsolute Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots + */ - if (schema.contains && Object.keys(schema.contains).length > 0) { - hints.push(`should contains at least one ${this.formatSchema(schema.contains)} item`); - } +/** + * @typedef {Object} ResolveOptions + * @property {AliasOptionEntry[]} alias + * @property {AliasOptionEntry[]} fallback + * @property {Set} aliasFields + * @property {(function(ResolveRequest): boolean)} cachePredicate + * @property {boolean} cacheWithContext + * @property {Set} conditionNames A list of exports field condition names. + * @property {string[]} descriptionFiles + * @property {boolean} enforceExtension + * @property {Set} exportsFields + * @property {Set} importsFields + * @property {Set} extensions + * @property {FileSystem} fileSystem + * @property {object | false} unsafeCache + * @property {boolean} symlinks + * @property {Resolver=} resolver + * @property {Array} modules + * @property {{name: string[], forceRelative: boolean}[]} mainFields + * @property {Set} mainFiles + * @property {Plugin[]} plugins + * @property {PnpApi | null} pnpApi + * @property {Set} roots + * @property {boolean} fullySpecified + * @property {boolean} resolveToContext + * @property {Set} restrictions + * @property {boolean} preferRelative + * @property {boolean} preferAbsolute + */ - return `[${items}${hasAdditionalItems ? ", ..." : ""}]${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; - } +/** + * @param {PnpApi | null=} option option + * @returns {PnpApi | null} processed option + */ +function processPnpApiOption(option) { + if ( + option === undefined && + /** @type {NodeJS.ProcessVersions & {pnp: string}} */ versions.pnp + ) { + // @ts-ignore + return __webpack_require__(35125); // eslint-disable-line node/no-missing-require + } - if (likeObject(schema)) { - // not logic already applied in formatValidationError - newLogic = true; - const hints = []; + return option || null; +} - if (typeof schema.minProperties === "number") { - hints.push(`should not have fewer than ${schema.minProperties} ${schema.minProperties > 1 ? "properties" : "property"}`); - } +/** + * @param {AliasOptions | AliasOptionEntry[] | undefined} alias alias + * @returns {AliasOptionEntry[]} normalized aliases + */ +function normalizeAlias(alias) { + return typeof alias === "object" && !Array.isArray(alias) && alias !== null + ? Object.keys(alias).map(key => { + /** @type {AliasOptionEntry} */ + const obj = { name: key, onlyModule: false, alias: alias[key] }; - if (typeof schema.maxProperties === "number") { - hints.push(`should not have more than ${schema.maxProperties} ${schema.minProperties && schema.minProperties > 1 ? "properties" : "property"}`); - } + if (/\$$/.test(key)) { + obj.onlyModule = true; + obj.name = key.substr(0, key.length - 1); + } - if (schema.patternProperties && Object.keys(schema.patternProperties).length > 0) { - const patternProperties = Object.keys(schema.patternProperties); - hints.push(`additional property names should match pattern${patternProperties.length > 1 ? "s" : ""} ${patternProperties.map(pattern => JSON.stringify(pattern)).join(" | ")}`); - } + return obj; + }) + : /** @type {Array} */ (alias) || []; +} - const properties = schema.properties ? Object.keys(schema.properties) : []; - const required = schema.required ? schema.required : []; - const allProperties = [...new Set( - /** @type {Array} */ - [].concat(required).concat(properties))]; - const objectStructure = allProperties.map(property => { - const isRequired = required.includes(property); // Some properties need quotes, maybe we should add check - // Maybe we should output type of property (`foo: string`), but it is looks very unreadable +/** + * @param {UserResolveOptions} options input options + * @returns {ResolveOptions} output options + */ +function createOptions(options) { + const mainFieldsSet = new Set(options.mainFields || ["main"]); + const mainFields = []; - return `${property}${isRequired ? "" : "?"}`; - }).concat(typeof schema.additionalProperties === "undefined" || Boolean(schema.additionalProperties) ? schema.additionalProperties && isObject(schema.additionalProperties) ? [`: ${formatInnerSchema(schema.additionalProperties)}`] : ["…"] : []).join(", "); - const { - dependencies, - propertyNames, - patternRequired - } = - /** @type {Schema & {patternRequired?: Array;}} */ - schema; + for (const item of mainFieldsSet) { + if (typeof item === "string") { + mainFields.push({ + name: [item], + forceRelative: true + }); + } else if (Array.isArray(item)) { + mainFields.push({ + name: item, + forceRelative: true + }); + } else { + mainFields.push({ + name: Array.isArray(item.name) ? item.name : [item.name], + forceRelative: item.forceRelative + }); + } + } - if (dependencies) { - Object.keys(dependencies).forEach(dependencyName => { - const dependency = dependencies[dependencyName]; + return { + alias: normalizeAlias(options.alias), + fallback: normalizeAlias(options.fallback), + aliasFields: new Set(options.aliasFields), + cachePredicate: + options.cachePredicate || + function () { + return true; + }, + cacheWithContext: + typeof options.cacheWithContext !== "undefined" + ? options.cacheWithContext + : true, + exportsFields: new Set(options.exportsFields || ["exports"]), + importsFields: new Set(options.importsFields || ["imports"]), + conditionNames: new Set(options.conditionNames), + descriptionFiles: Array.from( + new Set(options.descriptionFiles || ["package.json"]) + ), + enforceExtension: + options.enforceExtension === undefined + ? options.extensions && options.extensions.includes("") + ? true + : false + : options.enforceExtension, + extensions: new Set(options.extensions || [".js", ".json", ".node"]), + fileSystem: options.useSyncFileSystemCalls + ? new SyncAsyncFileSystemDecorator( + /** @type {SyncFileSystem} */ ( + /** @type {unknown} */ (options.fileSystem) + ) + ) + : options.fileSystem, + unsafeCache: + options.unsafeCache && typeof options.unsafeCache !== "object" + ? {} + : options.unsafeCache || false, + symlinks: typeof options.symlinks !== "undefined" ? options.symlinks : true, + resolver: options.resolver, + modules: mergeFilteredToArray( + Array.isArray(options.modules) + ? options.modules + : options.modules + ? [options.modules] + : ["node_modules"], + item => { + const type = getType(item); + return type === PathType.Normal || type === PathType.Relative; + } + ), + mainFields, + mainFiles: new Set(options.mainFiles || ["index"]), + plugins: options.plugins || [], + pnpApi: processPnpApiOption(options.pnpApi), + roots: new Set(options.roots || undefined), + fullySpecified: options.fullySpecified || false, + resolveToContext: options.resolveToContext || false, + preferRelative: options.preferRelative || false, + preferAbsolute: options.preferAbsolute || false, + restrictions: new Set(options.restrictions) + }; +} - if (Array.isArray(dependency)) { - hints.push(`should have ${dependency.length > 1 ? "properties" : "property"} ${dependency.map(dep => `'${dep}'`).join(", ")} when property '${dependencyName}' is present`); - } else { - hints.push(`should be valid according to the schema ${formatInnerSchema(dependency)} when property '${dependencyName}' is present`); - } - }); - } +/** + * @param {UserResolveOptions} options resolve options + * @returns {Resolver} created resolver + */ +exports.createResolver = function (options) { + const normalizedOptions = createOptions(options); - if (propertyNames && Object.keys(propertyNames).length > 0) { - hints.push(`each property name should match format ${JSON.stringify(schema.propertyNames.format)}`); - } + const { + alias, + fallback, + aliasFields, + cachePredicate, + cacheWithContext, + conditionNames, + descriptionFiles, + enforceExtension, + exportsFields, + importsFields, + extensions, + fileSystem, + fullySpecified, + mainFields, + mainFiles, + modules, + plugins: userPlugins, + pnpApi, + resolveToContext, + preferRelative, + preferAbsolute, + symlinks, + unsafeCache, + resolver: customResolver, + restrictions, + roots + } = normalizedOptions; - if (patternRequired && patternRequired.length > 0) { - hints.push(`should have property matching pattern ${patternRequired.map( - /** - * @param {string} item - * @returns {string} - */ - item => JSON.stringify(item))}`); - } + const plugins = userPlugins.slice(); - return `object {${objectStructure ? ` ${objectStructure} ` : ""}}${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; - } + const resolver = customResolver + ? customResolver + : new Resolver(fileSystem, normalizedOptions); - if (likeNull(schema)) { - return `${logic ? "" : "non-"}null`; - } - - if (Array.isArray(schema.type)) { - // not logic already applied in formatValidationError - return `${schema.type.join(" | ")}`; - } // Fallback for unknown keywords - // not logic already applied in formatValidationError - - /* istanbul ignore next */ + //// pipeline //// + resolver.ensureHook("resolve"); + resolver.ensureHook("internalResolve"); + resolver.ensureHook("newInteralResolve"); + resolver.ensureHook("parsedResolve"); + resolver.ensureHook("describedResolve"); + resolver.ensureHook("internal"); + resolver.ensureHook("rawModule"); + resolver.ensureHook("module"); + resolver.ensureHook("resolveAsModule"); + resolver.ensureHook("undescribedResolveInPackage"); + resolver.ensureHook("resolveInPackage"); + resolver.ensureHook("resolveInExistingDirectory"); + resolver.ensureHook("relative"); + resolver.ensureHook("describedRelative"); + resolver.ensureHook("directory"); + resolver.ensureHook("undescribedExistingDirectory"); + resolver.ensureHook("existingDirectory"); + resolver.ensureHook("undescribedRawFile"); + resolver.ensureHook("rawFile"); + resolver.ensureHook("file"); + resolver.ensureHook("finalFile"); + resolver.ensureHook("existingFile"); + resolver.ensureHook("resolved"); - return JSON.stringify(schema, null, 2); - } - /** - * @param {Schema=} schemaPart - * @param {(boolean | Array)=} additionalPath - * @param {boolean=} needDot - * @param {boolean=} logic - * @returns {string} - */ + // resolve + for (const { source, resolveOptions } of [ + { source: "resolve", resolveOptions: { fullySpecified } }, + { source: "internal-resolve", resolveOptions: { fullySpecified: false } } + ]) { + if (unsafeCache) { + plugins.push( + new UnsafeCachePlugin( + source, + cachePredicate, + unsafeCache, + cacheWithContext, + `new-${source}` + ) + ); + plugins.push( + new ParsePlugin(`new-${source}`, resolveOptions, "parsed-resolve") + ); + } else { + plugins.push(new ParsePlugin(source, resolveOptions, "parsed-resolve")); + } + } + // parsed-resolve + plugins.push( + new DescriptionFilePlugin( + "parsed-resolve", + descriptionFiles, + false, + "described-resolve" + ) + ); + plugins.push(new NextPlugin("after-parsed-resolve", "described-resolve")); - getSchemaPartText(schemaPart, additionalPath, needDot = false, logic = true) { - if (!schemaPart) { - return ""; - } + // described-resolve + plugins.push(new NextPlugin("described-resolve", "normal-resolve")); + if (fallback.length > 0) { + plugins.push( + new AliasPlugin("described-resolve", fallback, "internal-resolve") + ); + } - if (Array.isArray(additionalPath)) { - for (let i = 0; i < additionalPath.length; i++) { - /** @type {Schema | undefined} */ - const inner = schemaPart[ - /** @type {keyof Schema} */ - additionalPath[i]]; + // normal-resolve + if (alias.length > 0) + plugins.push(new AliasPlugin("normal-resolve", alias, "internal-resolve")); + aliasFields.forEach(item => { + plugins.push( + new AliasFieldPlugin("normal-resolve", item, "internal-resolve") + ); + }); + if (preferRelative) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } + plugins.push( + new ConditionalPlugin( + "after-normal-resolve", + { module: true }, + "resolve as module", + false, + "raw-module" + ) + ); + plugins.push( + new ConditionalPlugin( + "after-normal-resolve", + { internal: true }, + "resolve as internal import", + false, + "internal" + ) + ); + if (preferAbsolute) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } + if (roots.size > 0) { + plugins.push(new RootsPlugin("after-normal-resolve", roots, "relative")); + } + if (!preferRelative && !preferAbsolute) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } - if (inner) { - // eslint-disable-next-line no-param-reassign - schemaPart = inner; - } else { - break; - } - } - } + // internal + importsFields.forEach(importsField => { + plugins.push( + new ImportsFieldPlugin( + "internal", + conditionNames, + importsField, + "relative", + "internal-resolve" + ) + ); + }); - while (schemaPart.$ref) { - // eslint-disable-next-line no-param-reassign - schemaPart = this.getSchemaPart(schemaPart.$ref); - } + // raw-module + exportsFields.forEach(exportsField => { + plugins.push( + new SelfReferencePlugin("raw-module", exportsField, "resolve-as-module") + ); + }); + modules.forEach(item => { + if (Array.isArray(item)) { + if (item.includes("node_modules") && pnpApi) { + plugins.push( + new ModulesInHierachicDirectoriesPlugin( + "raw-module", + item.filter(i => i !== "node_modules"), + "module" + ) + ); + plugins.push( + new PnpPlugin("raw-module", pnpApi, "undescribed-resolve-in-package") + ); + } else { + plugins.push( + new ModulesInHierachicDirectoriesPlugin("raw-module", item, "module") + ); + } + } else { + plugins.push(new ModulesInRootPlugin("raw-module", item, "module")); + } + }); - let schemaText = `${this.formatSchema(schemaPart, logic)}${needDot ? "." : ""}`; + // module + plugins.push(new JoinRequestPartPlugin("module", "resolve-as-module")); - if (schemaPart.description) { - schemaText += `\n-> ${schemaPart.description}`; - } + // resolve-as-module + if (!resolveToContext) { + plugins.push( + new ConditionalPlugin( + "resolve-as-module", + { directory: false, request: "." }, + "single file module", + true, + "undescribed-raw-file" + ) + ); + } + plugins.push( + new DirectoryExistsPlugin( + "resolve-as-module", + "undescribed-resolve-in-package" + ) + ); - if (schemaPart.link) { - schemaText += `\n-> Read more at ${schemaPart.link}`; - } + // undescribed-resolve-in-package + plugins.push( + new DescriptionFilePlugin( + "undescribed-resolve-in-package", + descriptionFiles, + false, + "resolve-in-package" + ) + ); + plugins.push( + new NextPlugin("after-undescribed-resolve-in-package", "resolve-in-package") + ); - return schemaText; - } - /** - * @param {Schema=} schemaPart - * @returns {string} - */ + // resolve-in-package + exportsFields.forEach(exportsField => { + plugins.push( + new ExportsFieldPlugin( + "resolve-in-package", + conditionNames, + exportsField, + "relative" + ) + ); + }); + plugins.push( + new NextPlugin("resolve-in-package", "resolve-in-existing-directory") + ); + // resolve-in-existing-directory + plugins.push( + new JoinRequestPlugin("resolve-in-existing-directory", "relative") + ); - getSchemaPartDescription(schemaPart) { - if (!schemaPart) { - return ""; - } + // relative + plugins.push( + new DescriptionFilePlugin( + "relative", + descriptionFiles, + true, + "described-relative" + ) + ); + plugins.push(new NextPlugin("after-relative", "described-relative")); - while (schemaPart.$ref) { - // eslint-disable-next-line no-param-reassign - schemaPart = this.getSchemaPart(schemaPart.$ref); - } + // described-relative + if (resolveToContext) { + plugins.push(new NextPlugin("described-relative", "directory")); + } else { + plugins.push( + new ConditionalPlugin( + "described-relative", + { directory: false }, + null, + true, + "raw-file" + ) + ); + plugins.push( + new ConditionalPlugin( + "described-relative", + { fullySpecified: false }, + "as directory", + true, + "directory" + ) + ); + } - let schemaText = ""; + // directory + plugins.push( + new DirectoryExistsPlugin("directory", "undescribed-existing-directory") + ); - if (schemaPart.description) { - schemaText += `\n-> ${schemaPart.description}`; - } + if (resolveToContext) { + // undescribed-existing-directory + plugins.push(new NextPlugin("undescribed-existing-directory", "resolved")); + } else { + // undescribed-existing-directory + plugins.push( + new DescriptionFilePlugin( + "undescribed-existing-directory", + descriptionFiles, + false, + "existing-directory" + ) + ); + mainFiles.forEach(item => { + plugins.push( + new UseFilePlugin( + "undescribed-existing-directory", + item, + "undescribed-raw-file" + ) + ); + }); - if (schemaPart.link) { - schemaText += `\n-> Read more at ${schemaPart.link}`; - } + // described-existing-directory + mainFields.forEach(item => { + plugins.push( + new MainFieldPlugin( + "existing-directory", + item, + "resolve-in-existing-directory" + ) + ); + }); + mainFiles.forEach(item => { + plugins.push( + new UseFilePlugin("existing-directory", item, "undescribed-raw-file") + ); + }); - return schemaText; - } - /** - * @param {SchemaUtilErrorObject} error - * @returns {string} - */ + // undescribed-raw-file + plugins.push( + new DescriptionFilePlugin( + "undescribed-raw-file", + descriptionFiles, + true, + "raw-file" + ) + ); + plugins.push(new NextPlugin("after-undescribed-raw-file", "raw-file")); + // raw-file + plugins.push( + new ConditionalPlugin( + "raw-file", + { fullySpecified: true }, + null, + false, + "file" + ) + ); + if (!enforceExtension) { + plugins.push(new TryNextPlugin("raw-file", "no extension", "file")); + } + extensions.forEach(item => { + plugins.push(new AppendPlugin("raw-file", item, "file")); + }); - formatValidationError(error) { - const { - keyword, - dataPath: errorDataPath - } = error; - const dataPath = `${this.baseDataPath}${errorDataPath}`; + // file + if (alias.length > 0) + plugins.push(new AliasPlugin("file", alias, "internal-resolve")); + aliasFields.forEach(item => { + plugins.push(new AliasFieldPlugin("file", item, "internal-resolve")); + }); + plugins.push(new NextPlugin("file", "final-file")); - switch (keyword) { - case "type": - { - const { - parentSchema, - params - } = error; // eslint-disable-next-line default-case + // final-file + plugins.push(new FileExistsPlugin("final-file", "existing-file")); - switch ( - /** @type {import("ajv").TypeParams} */ - params.type) { - case "number": - return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + // existing-file + if (symlinks) + plugins.push(new SymlinkPlugin("existing-file", "existing-file")); + plugins.push(new NextPlugin("existing-file", "resolved")); + } - case "integer": - return `${dataPath} should be an ${this.getSchemaPartText(parentSchema, false, true)}`; + // resolved + if (restrictions.size > 0) { + plugins.push(new RestrictionsPlugin(resolver.hooks.resolved, restrictions)); + } + plugins.push(new ResultPlugin(resolver.hooks.resolved)); - case "string": - return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + //// RESOLVER //// - case "boolean": - return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + for (const plugin of plugins) { + if (typeof plugin === "function") { + plugin.call(resolver, resolver); + } else { + plugin.apply(resolver); + } + } - case "array": - return `${dataPath} should be an array:\n${this.getSchemaPartText(parentSchema)}`; + return resolver; +}; - case "object": - return `${dataPath} should be an object:\n${this.getSchemaPartText(parentSchema)}`; +/** + * Merging filtered elements + * @param {string[]} array source array + * @param {function(string): boolean} filter predicate + * @returns {Array} merge result + */ +function mergeFilteredToArray(array, filter) { + /** @type {Array} */ + const result = []; + const set = new Set(array); - case "null": - return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; + for (const item of set) { + if (filter(item)) { + const lastElement = + result.length > 0 ? result[result.length - 1] : undefined; + if (Array.isArray(lastElement)) { + lastElement.push(item); + } else { + result.push([item]); + } + } else { + result.push(item); + } + } - default: - return `${dataPath} should be:\n${this.getSchemaPartText(parentSchema)}`; - } - } + return result; +} - case "instanceof": - { - const { - parentSchema - } = error; - return `${dataPath} should be an instance of ${this.getSchemaPartText(parentSchema, false, true)}`; - } - case "pattern": - { - const { - params, - parentSchema - } = error; - const { - pattern - } = - /** @type {import("ajv").PatternParams} */ - params; - return `${dataPath} should match pattern ${JSON.stringify(pattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } +/***/ }), - case "format": - { - const { - params, - parentSchema - } = error; - const { - format - } = - /** @type {import("ajv").FormatParams} */ - params; - return `${dataPath} should match format ${JSON.stringify(format)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } +/***/ 39222: +/***/ (function(module) { - case "formatMinimum": - case "formatMaximum": - { - const { - params, - parentSchema - } = error; - const { - comparison, - limit - } = - /** @type {import("ajv").ComparisonParams} */ - params; - return `${dataPath} should be ${comparison} ${JSON.stringify(limit)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - case "minimum": - case "maximum": - case "exclusiveMinimum": - case "exclusiveMaximum": - { - const { - parentSchema, - params - } = error; - const { - comparison, - limit - } = - /** @type {import("ajv").ComparisonParams} */ - params; - const [, ...hints] = getHints( - /** @type {Schema} */ - parentSchema, true); - if (hints.length === 0) { - hints.push(`should be ${comparison} ${limit}`); - } - return `${dataPath} ${hints.join(" ")}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - case "multipleOf": - { - const { - params, - parentSchema - } = error; - const { - multipleOf - } = - /** @type {import("ajv").MultipleOfParams} */ - params; - return `${dataPath} should be multiple of ${multipleOf}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } +const slashCode = "/".charCodeAt(0); +const backslashCode = "\\".charCodeAt(0); - case "patternRequired": - { - const { - params, - parentSchema - } = error; - const { - missingPattern - } = - /** @type {import("ajv").PatternRequiredParams} */ - params; - return `${dataPath} should have property matching pattern ${JSON.stringify(missingPattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } +const isInside = (path, parent) => { + if (!path.startsWith(parent)) return false; + if (path.length === parent.length) return true; + const charCode = path.charCodeAt(parent.length); + return charCode === slashCode || charCode === backslashCode; +}; - case "minLength": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; +module.exports = class RestrictionsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} restrictions restrictions + */ + constructor(source, restrictions) { + this.source = source; + this.restrictions = restrictions; + } - if (limit === 1) { - return `${dataPath} should be a non-empty string${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + resolver + .getHook(this.source) + .tapAsync("RestrictionsPlugin", (request, resolveContext, callback) => { + if (typeof request.path === "string") { + const path = request.path; + for (const rule of this.restrictions) { + if (typeof rule === "string") { + if (!isInside(path, rule)) { + if (resolveContext.log) { + resolveContext.log( + `${path} is not inside of the restriction ${rule}` + ); + } + return callback(null, null); + } + } else if (!rule.test(path)) { + if (resolveContext.log) { + resolveContext.log( + `${path} doesn't match the restriction ${rule}` + ); + } + return callback(null, null); + } + } + } - const length = limit - 1; - return `${dataPath} should be longer than ${length} character${length > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + callback(); + }); + } +}; - case "minItems": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; - if (limit === 1) { - return `${dataPath} should be a non-empty array${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } +/***/ }), - return `${dataPath} should not have fewer than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } +/***/ 10615: +/***/ (function(module) { - case "minProperties": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (limit === 1) { - return `${dataPath} should be a non-empty object${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } - return `${dataPath} should not have fewer than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } - case "maxLength": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; - const max = limit + 1; - return `${dataPath} should be shorter than ${max} character${max > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - case "maxItems": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; - return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } +module.exports = class ResultPlugin { + /** + * @param {ResolveStepHook} source source + */ + constructor(source) { + this.source = source; + } - case "maxProperties": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; - return `${dataPath} should not have more than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + this.source.tapAsync( + "ResultPlugin", + (request, resolverContext, callback) => { + const obj = { ...request }; + if (resolverContext.log) + resolverContext.log("reporting result " + obj.path); + resolver.hooks.result.callAsync(obj, resolverContext, err => { + if (err) return callback(err); + callback(null, obj); + }); + } + ); + } +}; - case "uniqueItems": - { - const { - params, - parentSchema - } = error; - const { - i - } = - /** @type {import("ajv").UniqueItemsParams} */ - params; - return `${dataPath} should not contain the item '${error.data[i]}' twice${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } - case "additionalItems": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; - return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}. These items are valid:\n${this.getSchemaPartText(parentSchema)}`; - } +/***/ }), - case "contains": - { - const { - parentSchema - } = error; - return `${dataPath} should contains at least one ${this.getSchemaPartText(parentSchema, ["contains"])} item${getSchemaNonTypes(parentSchema)}.`; - } +/***/ 34403: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - case "required": - { - const { - parentSchema, - params - } = error; - const missingProperty = - /** @type {import("ajv").DependenciesParams} */ - params.missingProperty.replace(/^\./, ""); - const hasProperty = parentSchema && Boolean( - /** @type {Schema} */ - parentSchema.properties && - /** @type {Schema} */ - parentSchema.properties[missingProperty]); - return `${dataPath} misses the property '${missingProperty}'${getSchemaNonTypes(parentSchema)}.${hasProperty ? ` Should be:\n${this.getSchemaPartText(parentSchema, ["properties", missingProperty])}` : this.getSchemaPartDescription(parentSchema)}`; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - case "additionalProperties": - { - const { - params, - parentSchema - } = error; - const { - additionalProperty - } = - /** @type {import("ajv").AdditionalPropertiesParams} */ - params; - return `${dataPath} has an unknown property '${additionalProperty}'${getSchemaNonTypes(parentSchema)}. These properties are valid:\n${this.getSchemaPartText(parentSchema)}`; - } - case "dependencies": - { - const { - params, - parentSchema - } = error; - const { - property, - deps - } = - /** @type {import("ajv").DependenciesParams} */ - params; - const dependencies = deps.split(",").map( - /** - * @param {string} dep - * @returns {string} - */ - dep => `'${dep.trim()}'`).join(", "); - return `${dataPath} should have properties ${dependencies} when property '${property}' is present${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } - case "propertyNames": - { - const { - params, - parentSchema, - schema - } = error; - const { - propertyName - } = - /** @type {import("ajv").PropertyNamesParams} */ - params; - return `${dataPath} property name '${propertyName}' is invalid${getSchemaNonTypes(parentSchema)}. Property names should be match format ${JSON.stringify(schema.format)}.${this.getSchemaPartDescription(parentSchema)}`; - } +const forEachBail = __webpack_require__(8266); - case "enum": - { - const { - parentSchema - } = error; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - if (parentSchema && - /** @type {Schema} */ - parentSchema.enum && - /** @type {Schema} */ - parentSchema.enum.length === 1) { - return `${dataPath} should be ${this.getSchemaPartText(parentSchema, false, true)}`; - } +class RootsPlugin { + /** + * @param {string | ResolveStepHook} source source hook + * @param {Set} roots roots + * @param {string | ResolveStepHook} target target hook + */ + constructor(source, roots, target) { + this.roots = Array.from(roots); + this.source = source; + this.target = target; + } - return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; - } + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); - case "const": - { - const { - parentSchema - } = error; - return `${dataPath} should be equal to constant ${this.getSchemaPartText(parentSchema, false, true)}`; - } + resolver + .getHook(this.source) + .tapAsync("RootsPlugin", (request, resolveContext, callback) => { + const req = request.request; + if (!req) return callback(); + if (!req.startsWith("/")) return callback(); - case "not": - { - const postfix = likeObject( - /** @type {Schema} */ - error.parentSchema) ? `\n${this.getSchemaPartText(error.parentSchema)}` : ""; - const schemaOutput = this.getSchemaPartText(error.schema, false, false, false); + forEachBail( + this.roots, + (root, callback) => { + const path = resolver.join(root, req.slice(1)); + const obj = { + ...request, + path, + relativePath: request.relativePath && path + }; + resolver.doResolve( + target, + obj, + `root path ${root}`, + resolveContext, + callback + ); + }, + callback + ); + }); + } +} - if (canApplyNot(error.schema)) { - return `${dataPath} should be any ${schemaOutput}${postfix}.`; - } +module.exports = RootsPlugin; - const { - schema, - parentSchema - } = error; - return `${dataPath} should not be ${this.getSchemaPartText(schema, false, true)}${parentSchema && likeObject(parentSchema) ? `\n${this.getSchemaPartText(parentSchema)}` : ""}`; - } - case "oneOf": - case "anyOf": - { - const { - parentSchema, - children - } = error; +/***/ }), - if (children && children.length > 0) { - if (error.schema.length === 1) { - const lastChild = children[children.length - 1]; - const remainingChildren = children.slice(0, children.length - 1); - return this.formatValidationError(Object.assign({}, lastChild, { - children: remainingChildren, - parentSchema: Object.assign({}, parentSchema, lastChild.parentSchema) - })); - } +/***/ 32317: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - let filteredChildren = filterChildren(children); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (filteredChildren.length === 1) { - return this.formatValidationError(filteredChildren[0]); - } - filteredChildren = groupChildrenByFirstChild(filteredChildren); - return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}\nDetails:\n${filteredChildren.map( - /** - * @param {SchemaUtilErrorObject} nestedError - * @returns {string} - */ - nestedError => ` * ${indent(this.formatValidationError(nestedError), " ")}`).join("\n")}`; - } - return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; - } +const DescriptionFileUtils = __webpack_require__(702); - case "if": - { - const { - params, - parentSchema - } = error; - const { - failingKeyword - } = - /** @type {import("ajv").IfParams} */ - params; - return `${dataPath} should match "${failingKeyword}" schema:\n${this.getSchemaPartText(parentSchema, [failingKeyword])}`; - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - case "absolutePath": - { - const { - message, - parentSchema - } = error; - return `${dataPath}: ${message}${this.getSchemaPartDescription(parentSchema)}`; - } +const slashCode = "/".charCodeAt(0); - /* istanbul ignore next */ +module.exports = class SelfReferencePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} target target + */ + constructor(source, fieldNamePath, target) { + this.source = source; + this.target = target; + this.fieldName = fieldNamePath; + } - default: - { - const { - message, - parentSchema - } = error; - const ErrorInJSON = JSON.stringify(error, null, 2); // For `custom`, `false schema`, `$ref` keywords - // Fallback for unknown keywords + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("SelfReferencePlugin", (request, resolveContext, callback) => { + if (!request.descriptionFilePath) return callback(); - return `${dataPath} ${message} (${ErrorInJSON}).\n${this.getSchemaPartText(parentSchema, false)}`; - } - } - } - /** - * @param {Array} errors - * @returns {string} - */ + const req = request.request; + if (!req) return callback(); + // Feature is only enabled when an exports field is present + const exportsField = DescriptionFileUtils.getField( + request.descriptionFileData, + this.fieldName + ); + if (!exportsField) return callback(); - formatValidationErrors(errors) { - return errors.map(error => { - let formattedError = this.formatValidationError(error); + const name = DescriptionFileUtils.getField( + request.descriptionFileData, + "name" + ); + if (typeof name !== "string") return callback(); - if (this.postFormatter) { - formattedError = this.postFormatter(formattedError, error); - } + if ( + req.startsWith(name) && + (req.length === name.length || + req.charCodeAt(name.length) === slashCode) + ) { + const remainingRequest = `.${req.slice(name.length)}`; - return ` - ${indent(formattedError, " ")}`; - }).join("\n"); - } + const obj = { + ...request, + request: remainingRequest, + path: /** @type {string} */ (request.descriptionFileRoot), + relativePath: "." + }; -} + resolver.doResolve( + target, + obj, + "self reference", + resolveContext, + callback + ); + } else { + return callback(); + } + }); + } +}; -var _default = ValidationError; -exports.Z = _default; /***/ }), -/***/ 81184: -/***/ (function(module) { +/***/ 21300: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * @typedef {[number, boolean]} RangeValue - */ - -/** - * @callback RangeValueCallback - * @param {RangeValue} rangeValue - * @returns {boolean} - */ -class Range { - /** - * @param {"left" | "right"} side - * @param {boolean} exclusive - * @returns {">" | ">=" | "<" | "<="} - */ - static getOperator(side, exclusive) { - if (side === "left") { - return exclusive ? ">" : ">="; - } - - return exclusive ? "<" : "<="; - } - /** - * @param {number} value - * @param {boolean} logic is not logic applied - * @param {boolean} exclusive is range exclusive - * @returns {string} - */ - - - static formatRight(value, logic, exclusive) { - if (logic === false) { - return Range.formatLeft(value, !logic, !exclusive); - } - - return `should be ${Range.getOperator("right", exclusive)} ${value}`; - } - /** - * @param {number} value - * @param {boolean} logic is not logic applied - * @param {boolean} exclusive is range exclusive - * @returns {string} - */ - - - static formatLeft(value, logic, exclusive) { - if (logic === false) { - return Range.formatRight(value, !logic, !exclusive); - } - - return `should be ${Range.getOperator("left", exclusive)} ${value}`; - } - /** - * @param {number} start left side value - * @param {number} end right side value - * @param {boolean} startExclusive is range exclusive from left side - * @param {boolean} endExclusive is range exclusive from right side - * @param {boolean} logic is not logic applied - * @returns {string} - */ - - - static formatRange(start, end, startExclusive, endExclusive, logic) { - let result = "should be"; - result += ` ${Range.getOperator(logic ? "left" : "right", logic ? startExclusive : !startExclusive)} ${start} `; - result += logic ? "and" : "or"; - result += ` ${Range.getOperator(logic ? "right" : "left", logic ? endExclusive : !endExclusive)} ${end}`; - return result; - } - /** - * @param {Array} values - * @param {boolean} logic is not logic applied - * @return {RangeValue} computed value and it's exclusive flag - */ - - - static getRangeValue(values, logic) { - let minMax = logic ? Infinity : -Infinity; - let j = -1; - const predicate = logic ? - /** @type {RangeValueCallback} */ - ([value]) => value <= minMax : - /** @type {RangeValueCallback} */ - ([value]) => value >= minMax; - for (let i = 0; i < values.length; i++) { - if (predicate(values[i])) { - [minMax] = values[i]; - j = i; - } - } +const forEachBail = __webpack_require__(8266); +const getPaths = __webpack_require__(48608); +const { getType, PathType } = __webpack_require__(3011); - if (j > -1) { - return values[j]; - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - return [Infinity, true]; - } +module.exports = class SymlinkPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } - constructor() { - /** @type {Array} */ - this._left = []; - /** @type {Array} */ + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const fs = resolver.fileSystem; + resolver + .getHook(this.source) + .tapAsync("SymlinkPlugin", (request, resolveContext, callback) => { + if (request.ignoreSymlinks) return callback(); + const pathsResult = getPaths(request.path); + const pathSeqments = pathsResult.seqments; + const paths = pathsResult.paths; - this._right = []; - } - /** - * @param {number} value - * @param {boolean=} exclusive - */ + let containsSymlink = false; + let idx = -1; + forEachBail( + paths, + (path, callback) => { + idx++; + if (resolveContext.fileDependencies) + resolveContext.fileDependencies.add(path); + fs.readlink(path, (err, result) => { + if (!err && result) { + pathSeqments[idx] = result; + containsSymlink = true; + // Shortcut when absolute symlink found + const resultType = getType(result.toString()); + if ( + resultType === PathType.AbsoluteWin || + resultType === PathType.AbsolutePosix + ) { + return callback(null, idx); + } + } + callback(); + }); + }, + (err, idx) => { + if (!containsSymlink) return callback(); + const resultSeqments = + typeof idx === "number" + ? pathSeqments.slice(0, idx + 1) + : pathSeqments.slice(); + const result = resultSeqments.reduceRight((a, b) => { + return resolver.join(a, b); + }); + const obj = { + ...request, + path: result + }; + resolver.doResolve( + target, + obj, + "resolved symlink to " + result, + resolveContext, + callback + ); + } + ); + }); + } +}; - left(value, exclusive = false) { - this._left.push([value, exclusive]); - } - /** - * @param {number} value - * @param {boolean=} exclusive - */ +/***/ }), +/***/ 57746: +/***/ (function(module) { - right(value, exclusive = false) { - this._right.push([value, exclusive]); - } - /** - * @param {boolean} logic is not logic applied - * @return {string} "smart" range string representation - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - format(logic = true) { - const [start, leftExclusive] = Range.getRangeValue(this._left, logic); - const [end, rightExclusive] = Range.getRangeValue(this._right, !logic); - if (!Number.isFinite(start) && !Number.isFinite(end)) { - return ""; - } +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ - const realStart = leftExclusive ? start + 1 : start; - const realEnd = rightExclusive ? end - 1 : end; // e.g. 5 < x < 7, 5 < x <= 6, 6 <= x <= 6 +/** + * @param {SyncFileSystem} fs file system implementation + * @constructor + */ +function SyncAsyncFileSystemDecorator(fs) { + this.fs = fs; - if (realStart === realEnd) { - return `should be ${logic ? "" : "!"}= ${realStart}`; - } // e.g. 4 < x < ∞ + this.lstat = undefined; + this.lstatSync = undefined; + const lstatSync = fs.lstatSync; + if (lstatSync) { + this.lstat = (arg, options, callback) => { + let result; + try { + result = lstatSync.call(fs, arg); + } catch (e) { + return (callback || options)(e); + } + (callback || options)(null, result); + }; + this.lstatSync = (arg, options) => lstatSync.call(fs, arg, options); + } + this.stat = (arg, options, callback) => { + let result; + try { + result = callback ? fs.statSync(arg, options) : fs.statSync(arg); + } catch (e) { + return (callback || options)(e); + } + (callback || options)(null, result); + }; + this.statSync = (arg, options) => fs.statSync(arg, options); - if (Number.isFinite(start) && !Number.isFinite(end)) { - return Range.formatLeft(start, logic, leftExclusive); - } // e.g. ∞ < x < 4 + this.readdir = (arg, options, callback) => { + let result; + try { + result = fs.readdirSync(arg); + } catch (e) { + return (callback || options)(e); + } + (callback || options)(null, result); + }; + this.readdirSync = (arg, options) => fs.readdirSync(arg, options); + this.readFile = (arg, options, callback) => { + let result; + try { + result = fs.readFileSync(arg); + } catch (e) { + return (callback || options)(e); + } + (callback || options)(null, result); + }; + this.readFileSync = (arg, options) => fs.readFileSync(arg, options); - if (!Number.isFinite(start) && Number.isFinite(end)) { - return Range.formatRight(end, logic, rightExclusive); - } + this.readlink = (arg, options, callback) => { + let result; + try { + result = fs.readlinkSync(arg); + } catch (e) { + return (callback || options)(e); + } + (callback || options)(null, result); + }; + this.readlinkSync = (arg, options) => fs.readlinkSync(arg, options); - return Range.formatRange(start, end, leftExclusive, rightExclusive, logic); - } + this.readJson = undefined; + this.readJsonSync = undefined; + const readJsonSync = fs.readJsonSync; + if (readJsonSync) { + this.readJson = (arg, options, callback) => { + let result; + try { + result = readJsonSync.call(fs, arg); + } catch (e) { + return (callback || options)(e); + } + (callback || options)(null, result); + }; + this.readJsonSync = (arg, options) => readJsonSync.call(fs, arg, options); + } } +module.exports = SyncAsyncFileSystemDecorator; -module.exports = Range; /***/ }), -/***/ 79926: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 16442: +/***/ (function(module) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -const Range = __webpack_require__(81184); -/** @typedef {import("../validate").Schema} Schema */ - -/** - * @param {Schema} schema - * @param {boolean} logic - * @return {string[]} - */ - - -module.exports.stringHints = function stringHints(schema, logic) { - const hints = []; - let type = "string"; - const currentSchema = { ...schema - }; - - if (!logic) { - const tmpLength = currentSchema.minLength; - const tmpFormat = currentSchema.formatMinimum; - const tmpExclusive = currentSchema.formatExclusiveMaximum; - currentSchema.minLength = currentSchema.maxLength; - currentSchema.maxLength = tmpLength; - currentSchema.formatMinimum = currentSchema.formatMaximum; - currentSchema.formatMaximum = tmpFormat; - currentSchema.formatExclusiveMaximum = !currentSchema.formatExclusiveMinimum; - currentSchema.formatExclusiveMinimum = !tmpExclusive; - } - - if (typeof currentSchema.minLength === "number") { - if (currentSchema.minLength === 1) { - type = "non-empty string"; - } else { - const length = Math.max(currentSchema.minLength - 1, 0); - hints.push(`should be longer than ${length} character${length > 1 ? "s" : ""}`); - } - } - - if (typeof currentSchema.maxLength === "number") { - if (currentSchema.maxLength === 0) { - type = "empty string"; - } else { - const length = currentSchema.maxLength + 1; - hints.push(`should be shorter than ${length} character${length > 1 ? "s" : ""}`); - } - } - - if (currentSchema.pattern) { - hints.push(`should${logic ? "" : " not"} match pattern ${JSON.stringify(currentSchema.pattern)}`); - } - - if (currentSchema.format) { - hints.push(`should${logic ? "" : " not"} match format ${JSON.stringify(currentSchema.format)}`); - } - if (currentSchema.formatMinimum) { - hints.push(`should be ${currentSchema.formatExclusiveMinimum ? ">" : ">="} ${JSON.stringify(currentSchema.formatMinimum)}`); - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - if (currentSchema.formatMaximum) { - hints.push(`should be ${currentSchema.formatExclusiveMaximum ? "<" : "<="} ${JSON.stringify(currentSchema.formatMaximum)}`); - } +module.exports = class TryNextPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} message message + * @param {string | ResolveStepHook} target target + */ + constructor(source, message, target) { + this.source = source; + this.message = message; + this.target = target; + } - return [type].concat(hints); + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("TryNextPlugin", (request, resolveContext, callback) => { + resolver.doResolve( + target, + request, + this.message, + resolveContext, + callback + ); + }); + } }; -/** - * @param {Schema} schema - * @param {boolean} logic - * @return {string[]} - */ -module.exports.numberHints = function numberHints(schema, logic) { - const hints = [schema.type === "integer" ? "integer" : "number"]; - const range = new Range(); +/***/ }), - if (typeof schema.minimum === "number") { - range.left(schema.minimum); - } +/***/ 3501: +/***/ (function(module) { - if (typeof schema.exclusiveMinimum === "number") { - range.left(schema.exclusiveMinimum, true); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (typeof schema.maximum === "number") { - range.right(schema.maximum); - } - if (typeof schema.exclusiveMaximum === "number") { - range.right(schema.exclusiveMaximum, true); - } - const rangeFormat = range.format(logic); +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {{[k: string]: any}} Cache */ - if (rangeFormat) { - hints.push(rangeFormat); - } +function getCacheId(request, withContext) { + return JSON.stringify({ + context: withContext ? request.context : "", + path: request.path, + query: request.query, + fragment: request.fragment, + request: request.request + }); +} - if (typeof schema.multipleOf === "number") { - hints.push(`should${logic ? "" : " not"} be multiple of ${schema.multipleOf}`); - } +module.exports = class UnsafeCachePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {function(ResolveRequest): boolean} filterPredicate filterPredicate + * @param {Cache} cache cache + * @param {boolean} withContext withContext + * @param {string | ResolveStepHook} target target + */ + constructor(source, filterPredicate, cache, withContext, target) { + this.source = source; + this.filterPredicate = filterPredicate; + this.withContext = withContext; + this.cache = cache; + this.target = target; + } - return hints; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("UnsafeCachePlugin", (request, resolveContext, callback) => { + if (!this.filterPredicate(request)) return callback(); + const cacheId = getCacheId(request, this.withContext); + const cacheEntry = this.cache[cacheId]; + if (cacheEntry) { + return callback(null, cacheEntry); + } + resolver.doResolve( + target, + request, + null, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, (this.cache[cacheId] = result)); + callback(); + } + ); + }); + } }; + /***/ }), -/***/ 74315: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 50318: +/***/ (function(module) { "use strict"; /* @@ -16908,282 +19747,131 @@ module.exports.numberHints = function numberHints(schema, logic) { -const RuntimeGlobals = __webpack_require__(16475); -const WebpackError = __webpack_require__(53799); -const ConstDependency = __webpack_require__(76911); -const BasicEvaluatedExpression = __webpack_require__(950); -const { - toConstantDependency, - evaluateToString -} = __webpack_require__(93998); -const ChunkNameRuntimeModule = __webpack_require__(84519); -const GetFullHashRuntimeModule = __webpack_require__(88732); - -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/* 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 +module.exports = class UseFilePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} filename filename + * @param {string | ResolveStepHook} target target + */ + constructor(source, filename, target) { + this.source = source; + this.filename = filename; + this.target = target; } -}; -/* eslint-enable camelcase */ -class APIPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {Resolver} resolver the resolver * @returns {void} */ - apply(compiler) { - compiler.hooks.compilation.tap( - "APIPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("UseFilePlugin", (request, resolveContext, callback) => { + const filePath = resolver.join(request.path, this.filename); + const obj = { + ...request, + path: filePath, + relativePath: + request.relativePath && + resolver.join(request.relativePath, this.filename) + }; + resolver.doResolve( + target, + obj, + "using path: " + filePath, + resolveContext, + callback ); + }); + } +}; - 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)); - } - }); +/***/ 95478: +/***/ (function(module) { - 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) - ); - }; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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; + +module.exports = function createInnerContext( + options, + message, + messageOptional +) { + let messageReported = false; + let innerLog = undefined; + if (options.log) { + if (message) { + innerLog = msg => { + if (!messageReported) { + options.log(message); + messageReported = true; + } + options.log(" " + msg); + }; + } else { + innerLog = options.log; + } + } + const childContext = { + log: innerLog, + fileDependencies: options.fileDependencies, + contextDependencies: options.contextDependencies, + missingDependencies: options.missingDependencies, + stack: options.stack + }; + return childContext; +}; /***/ }), -/***/ 77198: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 8266: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const WebpackError = __webpack_require__(53799); -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 = function forEachBail(array, iterator, callback) { + if (array.length === 0) return callback(); -module.exports = AbstractMethodError; + let i = 0; + const next = () => { + let loop = undefined; + iterator(array[i++], (err, result) => { + if (err || result !== undefined || i >= array.length) { + return callback(err, result); + } + if (loop === false) while (next()); + loop = true; + }); + if (!loop) loop = false; + return loop; + }; + while (next()); +}; /***/ }), -/***/ 47736: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 50290: +/***/ (function(module) { "use strict"; /* @@ -17193,949 +19881,924 @@ module.exports = AbstractMethodError; -const DependenciesBlock = __webpack_require__(71040); -const makeSerializable = __webpack_require__(33032); - -/** @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 }; +module.exports = function getInnerRequest(resolver, request) { + if ( + typeof request.__innerRequest === "string" && + request.__innerRequest_request === request.request && + request.__innerRequest_relativePath === request.relativePath + ) + return request.__innerRequest; + let innerRequest; + if (request.request) { + innerRequest = request.request; + if (/^\.\.?(?:\/|$)/.test(innerRequest) && request.relativePath) { + innerRequest = resolver.join(request.relativePath, innerRequest); } - this.groupOptions = groupOptions; - this.loc = loc; - this.request = request; - this._stringifiedGroupOptions = undefined; + } else { + innerRequest = request.relativePath; } + request.__innerRequest_request = request.request; + request.__innerRequest_relativePath = request.relativePath; + return (request.__innerRequest = innerRequest); +}; - /** - * @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) { - if (this.groupOptions.name !== value) { - this.groupOptions.name = value; - this._stringifiedGroupOptions = undefined; - } - } +/***/ }), - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - const { chunkGraph } = context; - if (this._stringifiedGroupOptions === undefined) { - this._stringifiedGroupOptions = JSON.stringify(this.groupOptions); - } - const chunkGroup = chunkGraph.getBlockChunkGroup(this); - hash.update( - `${this._stringifiedGroupOptions}${chunkGroup ? chunkGroup.id : ""}` - ); - super.updateHash(hash, context); - } +/***/ 48608: +/***/ (function(module) { - serialize(context) { - const { write } = context; - write(this.groupOptions); - write(this.loc); - write(this.request); - super.serialize(context); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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 = function getPaths(path) { + const parts = path.split(/(.*?[\\/]+)/); + const paths = [path]; + const seqments = [parts[parts.length - 1]]; + let part = parts[parts.length - 1]; + path = path.substr(0, path.length - part.length - 1); + for (let i = parts.length - 2; i > 2; i -= 2) { + paths.push(path); + part = parts[i]; + path = path.substr(0, path.length - part.length) || "/"; + seqments.push(part.substr(0, part.length - 1)); } -}); + part = parts[1]; + seqments.push(part); + paths.push(part); + return { + paths: paths, + seqments: seqments + }; +}; -module.exports = AsyncDependenciesBlock; +module.exports.basename = function basename(path) { + const i = path.lastIndexOf("/"), + j = path.lastIndexOf("\\"); + const p = i < 0 ? j : j < 0 ? i : i < j ? j : i; + if (p < 0) return null; + const s = path.substr(p + 1); + return s; +}; /***/ }), -/***/ 30111: +/***/ 30662: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn + Author Tobias Koppers @sokra */ -const WebpackError = __webpack_require__(53799); +const fs = __webpack_require__(90552); +const CachedInputFileSystem = __webpack_require__(89429); +const ResolverFactory = __webpack_require__(53990); -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Module")} Module */ +/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./ResolverFactory").Plugin} Plugin */ +/** @typedef {import("./ResolverFactory").UserResolveOptions} ResolveOptions */ -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.` - ); +const nodeFileSystem = new CachedInputFileSystem(fs, 4000); - this.name = "AsyncDependencyToInitialChunkError"; - this.module = module; - this.loc = loc; +const nodeContext = { + environments: ["node+es3+es5+process+native"] +}; + +const asyncResolver = ResolverFactory.createResolver({ + conditionNames: ["node"], + extensions: [".js", ".json", ".node"], + fileSystem: nodeFileSystem +}); +function resolve(context, path, request, resolveContext, callback) { + if (typeof context === "string") { + callback = resolveContext; + resolveContext = request; + request = path; + path = context; + context = nodeContext; + } + if (typeof callback !== "function") { + callback = resolveContext; } + asyncResolver.resolve(context, path, request, resolveContext, callback); } -module.exports = AsyncDependencyToInitialChunkError; +const syncResolver = ResolverFactory.createResolver({ + conditionNames: ["node"], + extensions: [".js", ".json", ".node"], + useSyncFileSystemCalls: true, + fileSystem: nodeFileSystem +}); +function resolveSync(context, path, request) { + if (typeof context === "string") { + request = path; + path = context; + context = nodeContext; + } + return syncResolver.resolveSync(context, path, request); +} + +function create(options) { + options = { + fileSystem: nodeFileSystem, + ...options + }; + const resolver = ResolverFactory.createResolver(options); + return function (context, path, request, resolveContext, callback) { + if (typeof context === "string") { + callback = resolveContext; + resolveContext = request; + request = path; + path = context; + context = nodeContext; + } + if (typeof callback !== "function") { + callback = resolveContext; + } + resolver.resolve(context, path, request, resolveContext, callback); + }; +} + +function createSync(options) { + options = { + useSyncFileSystemCalls: true, + fileSystem: nodeFileSystem, + ...options + }; + const resolver = ResolverFactory.createResolver(options); + return function (context, path, request) { + if (typeof context === "string") { + request = path; + path = context; + context = nodeContext; + } + return resolver.resolveSync(context, path, request); + }; +} + +/** + * @template A + * @template B + * @param {A} obj input a + * @param {B} exports input b + * @returns {A & B} merged + */ +const mergeExports = (obj, exports) => { + const descriptors = Object.getOwnPropertyDescriptors(exports); + Object.defineProperties(obj, descriptors); + return /** @type {A & B} */ (Object.freeze(obj)); +}; + +module.exports = mergeExports(resolve, { + get sync() { + return resolveSync; + }, + create: mergeExports(create, { + get sync() { + return createSync; + } + }), + ResolverFactory, + CachedInputFileSystem, + get CloneBasenamePlugin() { + return __webpack_require__(2020); + }, + get LogInfoPlugin() { + return __webpack_require__(47032); + }, + get forEachBail() { + return __webpack_require__(8266); + } +}); /***/ }), -/***/ 17714: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 28348: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const asyncLib = __webpack_require__(78175); -const NormalModule = __webpack_require__(39); -const PrefetchDependency = __webpack_require__(31618); +/** @typedef {string|(string|ConditionalMapping)[]} DirectMapping */ +/** @typedef {{[k: string]: MappingValue}} ConditionalMapping */ +/** @typedef {ConditionalMapping|DirectMapping|null} MappingValue */ +/** @typedef {Record|ConditionalMapping|DirectMapping} ExportsField */ +/** @typedef {Record} ImportsField */ -/** @typedef {import("./Compiler")} Compiler */ +/** + * @typedef {Object} PathTreeNode + * @property {Map|null} children + * @property {MappingValue} folder + * @property {Map|null} wildcards + * @property {Map} files + */ -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 = []; +/** + * Processing exports/imports field + * @callback FieldProcessor + * @param {string} request request + * @param {Set} conditionNames condition names + * @returns {string[]} resolved paths + */ - 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); - } - ); - } - ); - } +/* +Example exports field: +{ + ".": "./main.js", + "./feature": { + "browser": "./feature-browser.js", + "default": "./feature.js" + } } -module.exports = AutomaticPrefetchPlugin; +Terminology: +Enhanced-resolve name keys ("." and "./feature") as exports field keys. -/***/ }), +If value is string or string[], mapping is called as a direct mapping +and value called as a direct export. -/***/ 21242: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +If value is key-value object, mapping is called as a conditional mapping +and value called as a conditional export. -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +Key in conditional mapping is called condition name. +Conditional mapping nested in another conditional mapping is called nested mapping. +---------- -const { ConcatSource } = __webpack_require__(51255); -const Compilation = __webpack_require__(85720); -const ModuleFilenameHelpers = __webpack_require__(88821); -const Template = __webpack_require__(1626); -const createSchemaValidation = __webpack_require__(32540); +Example imports field: +{ + "#a": "./main.js", + "#moment": { + "browser": "./moment/index.js", + "default": "moment" + }, + "#moment/": { + "browser": "./moment/", + "default": "moment/" + } +} +Terminology: -/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */ -/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */ -/** @typedef {import("./Compiler")} Compiler */ +Enhanced-resolve name keys ("#a" and "#moment/", "#moment") as imports field keys. -const validate = createSchemaValidation( - __webpack_require__(42173), - () => __webpack_require__(49052), - { - name: "Banner Plugin", - baseDataPath: "options" - } -); +If value is string or string[], mapping is called as a direct mapping +and value called as a direct export. -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 */`; -}; +If value is key-value object, mapping is called as a conditional mapping +and value called as a conditional export. -class BannerPlugin { - /** - * @param {BannerPluginArgument} options options object - */ - constructor(options) { - if (typeof options === "string" || typeof options === "function") { - options = { - banner: options - }; - } +Key in conditional mapping is called condition name. - validate(options); +Conditional mapping nested in another conditional mapping is called nested mapping. - 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; - } - } +const slashCode = "/".charCodeAt(0); +const dotCode = ".".charCodeAt(0); +const hashCode = "#".charCodeAt(0); - /** - * 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 - ); +/** + * @param {ExportsField} exportsField the exports field + * @returns {FieldProcessor} process callback + */ +module.exports.processExportsField = function processExportsField( + exportsField +) { + return createFieldProcessor( + buildExportsFieldPathTree(exportsField), + assertExportsFieldRequest, + assertExportTarget + ); +}; - 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; - } +/** + * @param {ImportsField} importsField the exports field + * @returns {FieldProcessor} process callback + */ +module.exports.processImportsField = function processImportsField( + importsField +) { + return createFieldProcessor( + buildImportsFieldPathTree(importsField), + assertImportsFieldRequest, + assertImportTarget + ); +}; - for (const file of chunk.files) { - if (!matchObject(file)) { - continue; - } +/** + * @param {PathTreeNode} treeRoot root + * @param {(s: string) => string} assertRequest assertRequest + * @param {(s: string, f: boolean) => void} assertTarget assertTarget + * @returns {FieldProcessor} field processor + */ +function createFieldProcessor(treeRoot, assertRequest, assertTarget) { + return function fieldProcessor(request, conditionNames) { + request = assertRequest(request); - const data = { - chunk, - filename: file - }; + const match = findMatch(request, treeRoot); - const comment = compilation.getPath(banner, data); + if (match === null) return []; - compilation.updateAsset( - file, - old => new ConcatSource(comment, "\n", old) - ); - } - } - } - ); - }); - } -} + const [mapping, remainRequestIndex] = match; -module.exports = BannerPlugin; + /** @type {DirectMapping|null} */ + let direct = null; + if (isConditionalMapping(mapping)) { + direct = conditionalMapping( + /** @type {ConditionalMapping} */ (mapping), + conditionNames + ); -/***/ }), + // matching not found + if (direct === null) return []; + } else { + direct = /** @type {DirectMapping} */ (mapping); + } -/***/ 7592: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const remainingRequest = + remainRequestIndex === request.length + 1 + ? undefined + : remainRequestIndex < 0 + ? request.slice(-remainRequestIndex - 1) + : request.slice(remainRequestIndex); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return directMapping( + remainingRequest, + remainRequestIndex < 0, + direct, + conditionNames, + assertTarget + ); + }; +} +/** + * @param {string} request request + * @returns {string} updated request + */ +function assertExportsFieldRequest(request) { + if (request.charCodeAt(0) !== dotCode) { + throw new Error('Request should be relative path and start with "."'); + } + if (request.length === 1) return ""; + if (request.charCodeAt(1) !== slashCode) { + throw new Error('Request should be relative path and start with "./"'); + } + if (request.charCodeAt(request.length - 1) === slashCode) { + throw new Error("Only requesting file allowed"); + } + return request.slice(2); +} -const { AsyncParallelHook, AsyncSeriesBailHook, SyncHook } = __webpack_require__(6967); -const { - makeWebpackError, - makeWebpackErrorCallback -} = __webpack_require__(11351); +/** + * @param {string} request request + * @returns {string} updated request + */ +function assertImportsFieldRequest(request) { + if (request.charCodeAt(0) !== hashCode) { + throw new Error('Request should start with "#"'); + } + if (request.length === 1) { + throw new Error("Request should have at least 2 characters"); + } + if (request.charCodeAt(1) === slashCode) { + throw new Error('Request should not start with "#/"'); + } + if (request.charCodeAt(request.length - 1) === slashCode) { + throw new Error("Only requesting file allowed"); + } -/** @typedef {import("./WebpackError")} WebpackError */ + return request.slice(1); +} /** - * @typedef {Object} Etag - * @property {function(): string} toString + * @param {string} exp export target + * @param {boolean} expectFolder is folder expected */ +function assertExportTarget(exp, expectFolder) { + if ( + exp.charCodeAt(0) === slashCode || + (exp.charCodeAt(0) === dotCode && exp.charCodeAt(1) !== slashCode) + ) { + throw new Error( + `Export should be relative path and start with "./", got ${JSON.stringify( + exp + )}.` + ); + } + + const isFolder = exp.charCodeAt(exp.length - 1) === slashCode; + + if (isFolder !== expectFolder) { + throw new Error( + expectFolder + ? `Expecting folder to folder mapping. ${JSON.stringify( + exp + )} should end with "/"` + : `Expecting file to file mapping. ${JSON.stringify( + exp + )} should not end with "/"` + ); + } +} /** - * @template T - * @callback CallbackCache - * @param {(WebpackError | null)=} err - * @param {T=} result - * @returns {void} + * @param {string} imp import target + * @param {boolean} expectFolder is folder expected */ +function assertImportTarget(imp, expectFolder) { + const isFolder = imp.charCodeAt(imp.length - 1) === slashCode; + + if (isFolder !== expectFolder) { + throw new Error( + expectFolder + ? `Expecting folder to folder mapping. ${JSON.stringify( + imp + )} should end with "/"` + : `Expecting file to file mapping. ${JSON.stringify( + imp + )} should not end with "/"` + ); + } +} /** - * @callback GotHandler - * @param {any} result - * @param {function(Error=): void} callback - * @returns {void} + * Trying to match request to field + * @param {string} request request + * @param {PathTreeNode} treeRoot path tree root + * @returns {[MappingValue, number]|null} match or null, number is negative and one less when it's a folder mapping, number is request.length + 1 for direct mappings */ +function findMatch(request, treeRoot) { + if (request.length === 0) { + const value = treeRoot.files.get(""); -const needCalls = (times, callback) => { - return err => { - if (--times === 0) { - return callback(err); - } - if (err && times > 0) { - times = 0; - return callback(err); - } - }; -}; + return value ? [value, 1] : null; + } -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]>} */ - storeBuildDependencies: new AsyncParallelHook(["dependencies"]), - /** @type {SyncHook<[]>} */ - beginIdle: new SyncHook([]), - /** @type {AsyncParallelHook<[]>} */ - endIdle: new AsyncParallelHook([]), - /** @type {AsyncParallelHook<[]>} */ - shutdown: new AsyncParallelHook([]) - }; + if ( + treeRoot.children === null && + treeRoot.folder === null && + treeRoot.wildcards === null + ) { + const value = treeRoot.files.get(request); + + return value ? [value, request.length + 1] : null; } - /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @param {CallbackCache} 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; + let node = treeRoot; + let lastNonSlashIndex = 0; + let slashIndex = request.indexOf("/", 0); + + /** @type {[MappingValue, number]|null} */ + let lastFolderMatch = null; + + const applyFolderMapping = () => { + const folderMapping = node.folder; + if (folderMapping) { + if (lastFolderMatch) { + lastFolderMatch[0] = folderMapping; + lastFolderMatch[1] = -lastNonSlashIndex - 1; + } else { + lastFolderMatch = [folderMapping, -lastNonSlashIndex - 1]; } - if (gotHandlers.length > 1) { - const innerCallback = needCalls(gotHandlers.length, () => - callback(null, result) - ); - for (const gotHandler of gotHandlers) { - gotHandler(result, innerCallback); + } + }; + + const applyWildcardMappings = (wildcardMappings, remainingRequest) => { + if (wildcardMappings) { + for (const [key, target] of wildcardMappings) { + if (remainingRequest.startsWith(key)) { + if (!lastFolderMatch) { + lastFolderMatch = [target, lastNonSlashIndex + key.length]; + } else if (lastFolderMatch[1] < lastNonSlashIndex + key.length) { + lastFolderMatch[0] = target; + lastFolderMatch[1] = lastNonSlashIndex + key.length; + } } - } 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} 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") - ); - } + while (slashIndex !== -1) { + applyFolderMapping(); - /** - * After this method has succeeded the cache can only be restored when build dependencies are - * @param {Iterable} dependencies list of all build dependencies - * @param {CallbackCache} callback signals when the dependencies are stored - * @returns {void} - */ - storeBuildDependencies(dependencies, callback) { - this.hooks.storeBuildDependencies.callAsync( - dependencies, - makeWebpackErrorCallback(callback, "Cache.hooks.storeBuildDependencies") - ); - } + const wildcardMappings = node.wildcards; - /** - * @returns {void} - */ - beginIdle() { - this.hooks.beginIdle.call(); - } + if (!wildcardMappings && node.children === null) return lastFolderMatch; - /** - * @param {CallbackCache} callback signals when the call finishes - * @returns {void} - */ - endIdle(callback) { - this.hooks.endIdle.callAsync( - makeWebpackErrorCallback(callback, "Cache.hooks.endIdle") - ); - } + const folder = request.slice(lastNonSlashIndex, slashIndex); - /** - * @param {CallbackCache} callback signals when the call finishes - * @returns {void} - */ - shutdown(callback) { - this.hooks.shutdown.callAsync( - makeWebpackErrorCallback(callback, "Cache.hooks.shutdown") - ); - } -} + applyWildcardMappings(wildcardMappings, folder); -Cache.STAGE_MEMORY = -10; -Cache.STAGE_DEFAULT = 0; -Cache.STAGE_DISK = 10; -Cache.STAGE_NETWORK = 20; + if (node.children === null) return lastFolderMatch; -module.exports = Cache; + const newNode = node.children.get(folder); + if (!newNode) { + return lastFolderMatch; + } -/***/ }), + node = newNode; + lastNonSlashIndex = slashIndex + 1; + slashIndex = request.indexOf("/", lastNonSlashIndex); + } -/***/ 55392: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const remainingRequest = + lastNonSlashIndex > 0 ? request.slice(lastNonSlashIndex) : request; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const value = node.files.get(remainingRequest); + if (value) { + return [value, request.length + 1]; + } + applyFolderMapping(); -const { forEachBail } = __webpack_require__(9256); -const asyncLib = __webpack_require__(78175); -const getLazyHashedEtag = __webpack_require__(94075); -const mergeEtags = __webpack_require__(54980); + applyWildcardMappings(node.wildcards, remainingRequest); -/** @typedef {import("./Cache")} Cache */ -/** @typedef {import("./Cache").Etag} Etag */ -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./cache/getLazyHashedEtag").HashableObject} HashableObject */ -/** @typedef {typeof import("./util/Hash")} HashConstructor */ + return lastFolderMatch; +} /** - * @template T - * @callback CallbackCache - * @param {(WebpackError | null)=} err - * @param {T=} result - * @returns {void} + * @param {ConditionalMapping|DirectMapping|null} mapping mapping + * @returns {boolean} is conditional mapping */ +function isConditionalMapping(mapping) { + return ( + mapping !== null && typeof mapping === "object" && !Array.isArray(mapping) + ); +} /** - * @template T - * @callback CallbackNormalErrorCache - * @param {(Error | null)=} err - * @param {T=} result - * @returns {void} + * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings + * @param {boolean} subpathMapping true, for subpath mappings + * @param {DirectMapping|null} mappingTarget direct export + * @param {Set} conditionNames condition names + * @param {(d: string, f: boolean) => void} assert asserting direct value + * @returns {string[]} mapping result */ +function directMapping( + remainingRequest, + subpathMapping, + mappingTarget, + conditionNames, + assert +) { + if (mappingTarget === null) return []; -class MultiItemCache { - /** - * @param {ItemCacheFacade[]} items item caches - */ - constructor(items) { - this._items = items; - if (items.length === 1) return /** @type {any} */ (items[0]); + if (typeof mappingTarget === "string") { + return [ + targetMapping(remainingRequest, subpathMapping, mappingTarget, assert) + ]; } - /** - * @template T - * @param {CallbackCache} callback signals when the value is retrieved - * @returns {void} - */ - get(callback) { - forEachBail(this._items, (item, callback) => item.get(callback), callback); - } + const targets = []; - /** - * @template T - * @returns {Promise} 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); - } + for (const exp of mappingTarget) { + if (typeof exp === "string") { + targets.push( + targetMapping(remainingRequest, subpathMapping, exp, assert) + ); + continue; + } - /** - * @template T - * @param {T} data the value to store - * @param {CallbackCache} callback signals when the value is stored - * @returns {void} - */ - store(data, callback) { - asyncLib.each( - this._items, - (item, callback) => item.store(data, callback), - callback + const mapping = conditionalMapping(exp, conditionNames); + if (!mapping) continue; + const innerExports = directMapping( + remainingRequest, + subpathMapping, + mapping, + conditionNames, + assert ); + for (const innerExport of innerExports) { + targets.push(innerExport); + } } - /** - * @template T - * @param {T} data the value to store - * @returns {Promise} promise signals when the value is stored - */ - storePromise(data) { - return Promise.all(this._items.map(item => item.storePromise(data))).then( - () => {} - ); - } + return targets; } -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; +/** + * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings + * @param {boolean} subpathMapping true, for subpath mappings + * @param {string} mappingTarget direct export + * @param {(d: string, f: boolean) => void} assert asserting direct value + * @returns {string} mapping result + */ +function targetMapping( + remainingRequest, + subpathMapping, + mappingTarget, + assert +) { + if (remainingRequest === undefined) { + assert(mappingTarget, false); + return mappingTarget; } - - /** - * @template T - * @param {CallbackCache} callback signals when the value is retrieved - * @returns {void} - */ - get(callback) { - this._cache.get(this._name, this._etag, callback); + if (subpathMapping) { + assert(mappingTarget, true); + return mappingTarget + remainingRequest; } + assert(mappingTarget, false); + return mappingTarget.replace(/\*/g, remainingRequest.replace(/\$/g, "$$")); +} - /** - * @template T - * @returns {Promise} 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); +/** + * @param {ConditionalMapping} conditionalMapping_ conditional mapping + * @param {Set} conditionNames condition names + * @returns {DirectMapping|null} direct mapping if found + */ +function conditionalMapping(conditionalMapping_, conditionNames) { + /** @type {[ConditionalMapping, string[], number][]} */ + let lookup = [[conditionalMapping_, Object.keys(conditionalMapping_), 0]]; + + loop: while (lookup.length > 0) { + const [mapping, conditions, j] = lookup[lookup.length - 1]; + const last = conditions.length - 1; + + for (let i = j; i < conditions.length; i++) { + const condition = conditions[i]; + + // assert default. Could be last only + if (i !== last) { + if (condition === "default") { + throw new Error("Default condition should be last one"); + } + } else if (condition === "default") { + const innerMapping = mapping[condition]; + // is nested + if (isConditionalMapping(innerMapping)) { + const conditionalMapping = /** @type {ConditionalMapping} */ (innerMapping); + lookup[lookup.length - 1][2] = i + 1; + lookup.push([conditionalMapping, Object.keys(conditionalMapping), 0]); + continue loop; } - }); - }); - } - /** - * @template T - * @param {T} data the value to store - * @param {CallbackCache} callback signals when the value is stored - * @returns {void} - */ - store(data, callback) { - this._cache.store(this._name, this._etag, data, callback); - } + return /** @type {DirectMapping} */ (innerMapping); + } - /** - * @template T - * @param {T} data the value to store - * @returns {Promise} 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(); + if (conditionNames.has(condition)) { + const innerMapping = mapping[condition]; + // is nested + if (isConditionalMapping(innerMapping)) { + const conditionalMapping = /** @type {ConditionalMapping} */ (innerMapping); + lookup[lookup.length - 1][2] = i + 1; + lookup.push([conditionalMapping, Object.keys(conditionalMapping), 0]); + continue loop; } - }); - }); - } - /** - * @template T - * @param {function(CallbackNormalErrorCache): void} computer function to compute the value if not cached - * @param {CallbackNormalErrorCache} 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); - }); - }); - }); - } + return /** @type {DirectMapping} */ (innerMapping); + } + } - /** - * @template T - * @param {function(): Promise | T} computer function to compute the value if not cached - * @returns {Promise} 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; + lookup.pop(); } + + return null; } -class CacheFacade { - /** - * @param {Cache} cache the root cache - * @param {string} name the child cache name - * @param {string | HashConstructor} hashFunction the hash function to use - */ - constructor(cache, name, hashFunction) { - this._cache = cache; - this._name = name; - this._hashFunction = hashFunction; - } +/** + * Internal helper to create path tree node + * to ensure that each node gets the same hidden class + * @returns {PathTreeNode} node + */ +function createNode() { + return { + children: null, + folder: null, + wildcards: null, + files: new Map() + }; +} - /** - * @param {string} name the child cache name# - * @returns {CacheFacade} child cache - */ - getChildCache(name) { - return new CacheFacade( - this._cache, - `${this._name}|${name}`, - this._hashFunction - ); +/** + * Internal helper for building path tree + * @param {PathTreeNode} root root + * @param {string} path path + * @param {MappingValue} target target + */ +function walkPath(root, path, target) { + if (path.length === 0) { + root.folder = target; + return; } - /** - * @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 - ); - } + let node = root; + // Typical path tree can looks like + // root + // - files: ["a.js", "b.js"] + // - children: + // node1: + // - files: ["a.js", "b.js"] + let lastNonSlashIndex = 0; + let slashIndex = path.indexOf("/", 0); - /** - * @param {HashableObject} obj an hashable object - * @returns {Etag} an etag that is lazy hashed - */ - getLazyHashedEtag(obj) { - return getLazyHashedEtag(obj, this._hashFunction); - } + while (slashIndex !== -1) { + const folder = path.slice(lastNonSlashIndex, slashIndex); + let newNode; - /** - * @param {Etag} a an etag - * @param {Etag} b another etag - * @returns {Etag} an etag that represents both - */ - mergeEtags(a, b) { - return mergeEtags(a, b); - } + if (node.children === null) { + newNode = createNode(); + node.children = new Map(); + node.children.set(folder, newNode); + } else { + newNode = node.children.get(folder); - /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @param {CallbackCache} callback signals when the value is retrieved - * @returns {void} - */ - get(identifier, etag, callback) { - this._cache.get(`${this._name}|${identifier}`, etag, callback); + if (!newNode) { + newNode = createNode(); + node.children.set(folder, newNode); + } + } + + node = newNode; + lastNonSlashIndex = slashIndex + 1; + slashIndex = path.indexOf("/", lastNonSlashIndex); } - /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @returns {Promise} 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); - } - }); - }); + if (lastNonSlashIndex >= path.length) { + node.folder = target; + } else { + const file = lastNonSlashIndex > 0 ? path.slice(lastNonSlashIndex) : path; + if (file.endsWith("*")) { + if (node.wildcards === null) node.wildcards = new Map(); + node.wildcards.set(file.slice(0, -1), target); + } else { + node.files.set(file, target); + } } +} - /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @param {T} data the value to store - * @param {CallbackCache} callback signals when the value is stored - * @returns {void} - */ - store(identifier, etag, data, callback) { - this._cache.store(`${this._name}|${identifier}`, etag, data, callback); +/** + * @param {ExportsField} field exports field + * @returns {PathTreeNode} tree root + */ +function buildExportsFieldPathTree(field) { + const root = createNode(); + + // handle syntax sugar, if exports field is direct mapping for "." + if (typeof field === "string") { + root.files.set("", field); + + return root; + } else if (Array.isArray(field)) { + root.files.set("", field.slice()); + + return root; } - /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @param {T} data the value to store - * @returns {Promise} 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(); + const keys = Object.keys(field); + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + + if (key.charCodeAt(0) !== dotCode) { + // handle syntax sugar, if exports field is conditional mapping for "." + if (i === 0) { + while (i < keys.length) { + const charCode = keys[i].charCodeAt(0); + if (charCode === dotCode || charCode === slashCode) { + throw new Error( + `Exports field key should be relative path and start with "." (key: ${JSON.stringify( + key + )})` + ); + } + i++; } - }); - }); - } - /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @param {function(CallbackNormalErrorCache): void} computer function to compute the value if not cached - * @param {CallbackNormalErrorCache} 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); - }); - }); - }); - } + root.files.set("", field); + return root; + } - /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @param {function(): Promise | T} computer function to compute the value if not cached - * @returns {Promise} 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; + throw new Error( + `Exports field key should be relative path and start with "." (key: ${JSON.stringify( + key + )})` + ); + } + + if (key.length === 1) { + root.files.set("", field[key]); + continue; + } + + if (key.charCodeAt(1) !== slashCode) { + throw new Error( + `Exports field key should be relative path and start with "./" (key: ${JSON.stringify( + key + )})` + ); + } + + walkPath(root, key.slice(2), field[key]); } + + return root; } -module.exports = CacheFacade; -module.exports.ItemCacheFacade = ItemCacheFacade; -module.exports.MultiItemCache = MultiItemCache; +/** + * @param {ImportsField} field imports field + * @returns {PathTreeNode} root + */ +function buildImportsFieldPathTree(field) { + const root = createNode(); + + const keys = Object.keys(field); + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + + if (key.charCodeAt(0) !== hashCode) { + throw new Error( + `Imports field key should start with "#" (key: ${JSON.stringify(key)})` + ); + } + + if (key.length === 1) { + throw new Error( + `Imports field key should have at least 2 characters (key: ${JSON.stringify( + key + )})` + ); + } + + if (key.charCodeAt(1) === slashCode) { + throw new Error( + `Imports field key should not start with "#/" (key: ${JSON.stringify( + key + )})` + ); + } + + walkPath(root, key.slice(1), field[key]); + } + + return root; +} /***/ }), -/***/ 77975: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 7780: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const WebpackError = __webpack_require__(53799); - -/** @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.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; - }); -}; +const PATH_QUERY_FRAGMENT_REGEXP = /^(#?(?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; /** - * @param {Module[]} modules each module from throw - * @param {ModuleGraph} moduleGraph the module graph - * @returns {string} each message from provided modules + * @param {string} identifier identifier + * @returns {[string, string, string]|null} parsed identifier */ -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"); -}; +function parseIdentifier(identifier) { + const match = PATH_QUERY_FRAGMENT_REGEXP.exec(identifier); -class CaseSensitiveModulesWarning extends WebpackError { - /** - * Creates an instance of CaseSensitiveModulesWarning. - * @param {Iterable} modules modules that were detected - * @param {ModuleGraph} moduleGraph the module graph - */ - constructor(modules, moduleGraph) { - const sortedModules = sortModules(Array.from(modules)); - const modulesList = createModulesListMessage(sortedModules, moduleGraph); - super(`There are multiple modules with names that only differ in casing. -This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. -Use equal casing. Compare these module identifiers: -${modulesList}`); + if (!match) return null; - this.name = "CaseSensitiveModulesWarning"; - this.module = sortedModules[0]; - } + return [ + match[1].replace(/\0(.)/g, "$1"), + match[2] ? match[2].replace(/\0(.)/g, "$1") : "", + match[3] || "" + ]; } -module.exports = CaseSensitiveModulesWarning; +module.exports.parseIdentifier = parseIdentifier; /***/ }), -/***/ 39385: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 3011: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -18145,13990 +20808,7578 @@ module.exports = CaseSensitiveModulesWarning; -const ChunkGraph = __webpack_require__(64971); -const Entrypoint = __webpack_require__(13795); -const { intersect } = __webpack_require__(93347); -const SortableSet = __webpack_require__(13098); -const StringXor = __webpack_require__(40293); -const { - compareModulesByIdentifier, - compareChunkGroupsByIndex, - compareModulesById -} = __webpack_require__(29579); -const { createArrayToSetDeprecationSet } = __webpack_require__(64518); -const { mergeRuntime } = __webpack_require__(17156); +const path = __webpack_require__(71017); -/** @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 CHAR_HASH = "#".charCodeAt(0); +const CHAR_SLASH = "/".charCodeAt(0); +const CHAR_BACKSLASH = "\\".charCodeAt(0); +const CHAR_A = "A".charCodeAt(0); +const CHAR_Z = "Z".charCodeAt(0); +const CHAR_LOWER_A = "a".charCodeAt(0); +const CHAR_LOWER_Z = "z".charCodeAt(0); +const CHAR_DOT = ".".charCodeAt(0); +const CHAR_COLON = ":".charCodeAt(0); -const ChunkFilesSet = createArrayToSetDeprecationSet("chunk.files"); +const posixNormalize = path.posix.normalize; +const winNormalize = path.win32.normalize; /** - * @typedef {Object} WithId an object who has an id property * - * @property {string | number} id the id of the object + * @enum {number} */ +const PathType = Object.freeze({ + Empty: 0, + Normal: 1, + Relative: 2, + AbsoluteWin: 3, + AbsolutePosix: 4, + Internal: 5 +}); +exports.PathType = PathType; /** - * @deprecated - * @typedef {Object} ChunkMaps - * @property {Record} hash - * @property {Record>} contentHash - * @property {Record} name + * @param {string} p a path + * @returns {PathType} type of path */ +const getType = p => { + switch (p.length) { + case 0: + return PathType.Empty; + case 1: { + const c0 = p.charCodeAt(0); + switch (c0) { + case CHAR_DOT: + return PathType.Relative; + case CHAR_SLASH: + return PathType.AbsolutePosix; + case CHAR_HASH: + return PathType.Internal; + } + return PathType.Normal; + } + case 2: { + const c0 = p.charCodeAt(0); + switch (c0) { + case CHAR_DOT: { + const c1 = p.charCodeAt(1); + switch (c1) { + case CHAR_DOT: + case CHAR_SLASH: + return PathType.Relative; + } + return PathType.Normal; + } + case CHAR_SLASH: + return PathType.AbsolutePosix; + case CHAR_HASH: + return PathType.Internal; + } + const c1 = p.charCodeAt(1); + if (c1 === CHAR_COLON) { + if ( + (c0 >= CHAR_A && c0 <= CHAR_Z) || + (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z) + ) { + return PathType.AbsoluteWin; + } + } + return PathType.Normal; + } + } + const c0 = p.charCodeAt(0); + switch (c0) { + case CHAR_DOT: { + const c1 = p.charCodeAt(1); + switch (c1) { + case CHAR_SLASH: + return PathType.Relative; + case CHAR_DOT: { + const c2 = p.charCodeAt(2); + if (c2 === CHAR_SLASH) return PathType.Relative; + return PathType.Normal; + } + } + return PathType.Normal; + } + case CHAR_SLASH: + return PathType.AbsolutePosix; + case CHAR_HASH: + return PathType.Internal; + } + const c1 = p.charCodeAt(1); + if (c1 === CHAR_COLON) { + const c2 = p.charCodeAt(2); + if ( + (c2 === CHAR_BACKSLASH || c2 === CHAR_SLASH) && + ((c0 >= CHAR_A && c0 <= CHAR_Z) || + (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z)) + ) { + return PathType.AbsoluteWin; + } + } + return PathType.Normal; +}; +exports.getType = getType; /** - * @deprecated - * @typedef {Object} ChunkModuleMaps - * @property {Record} id - * @property {Record} hash + * @param {string} p a path + * @returns {string} the normalized path */ - -let debugId = 1000; +const normalize = p => { + switch (getType(p)) { + case PathType.Empty: + return p; + case PathType.AbsoluteWin: + return winNormalize(p); + case PathType.Relative: { + const r = posixNormalize(p); + return getType(r) === PathType.Relative ? r : `./${r}`; + } + } + return posixNormalize(p); +}; +exports.normalize = normalize; /** - * A Chunk is a unit of encapsulation for Modules. - * Chunks are "rendered" into bundles that get emitted when the build completes. + * @param {string} rootPath the root path + * @param {string | undefined} request the request path + * @returns {string} the joined path */ -class Chunk { - /** - * @param {string=} name of chunk being created, is optional (for subclasses) - * @param {boolean} backCompat enable backward-compatibility - */ - constructor(name, backCompat = true) { - /** @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} */ - this.idNameHints = new SortableSet(); - /** @type {boolean} */ - this.preventIntegration = false; - /** @type {(string | function(PathData, AssetInfo=): string)?} */ - this.filenameTemplate = undefined; - /** @type {(string | function(PathData, AssetInfo=): string)?} */ - this.cssFilenameTemplate = undefined; - /** @private @type {SortableSet} */ - this._groups = new SortableSet(undefined, compareChunkGroupsByIndex); - /** @type {RuntimeSpec} */ - this.runtime = undefined; - /** @type {Set} */ - this.files = backCompat ? new ChunkFilesSet() : new Set(); - /** @type {Set} */ - this.auxiliaryFiles = new Set(); - /** @type {boolean} */ - this.rendered = false; - /** @type {string=} */ - this.hash = undefined; - /** @type {Record} */ - this.contentHash = Object.create(null); - /** @type {string=} */ - this.renderedHash = undefined; - /** @type {string=} */ - this.chunkReason = undefined; - /** @type {boolean} */ - this.extraAsync = false; +const join = (rootPath, request) => { + if (!request) return normalize(rootPath); + const requestType = getType(request); + switch (requestType) { + case PathType.AbsolutePosix: + return posixNormalize(request); + case PathType.AbsoluteWin: + return winNormalize(request); } - - // 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)" - ); + switch (getType(rootPath)) { + case PathType.Normal: + case PathType.Relative: + case PathType.AbsolutePosix: + return posixNormalize(`${rootPath}/${request}`); + case PathType.AbsoluteWin: + return winNormalize(`${rootPath}\\${request}`); + } + switch (requestType) { + case PathType.Empty: + return rootPath; + case PathType.Relative: { + const r = posixNormalize(rootPath); + return getType(r) === PathType.Relative ? r : `./${r}`; } } + return posixNormalize(rootPath); +}; +exports.join = join; - /** - * @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 - ); - } +const joinCache = new Map(); - /** - * @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 {string} rootPath the root path + * @param {string | undefined} request the request path + * @returns {string} the joined path + */ +const cachedJoin = (rootPath, request) => { + let cacheEntry; + let cache = joinCache.get(rootPath); + if (cache === undefined) { + joinCache.set(rootPath, (cache = new Map())); + } else { + cacheEntry = cache.get(request); + if (cacheEntry !== undefined) return cacheEntry; } + cacheEntry = join(rootPath, request); + cache.set(request, cacheEntry); + return cacheEntry; +}; +exports.cachedJoin = cachedJoin; - /** - * @param {Module} module the module - * @returns {void} - */ - removeModule(module) { - ChunkGraph.getChunkGraphForChunk( - this, - "Chunk.removeModule", - "DEP_WEBPACK_CHUNK_REMOVE_MODULE" - ).disconnectChunkAndModule(this, module); - } +const checkExportsFieldTarget = relativePath => { + let lastNonSlashIndex = 2; + let slashIndex = relativePath.indexOf("/", 2); + let cd = 0; - /** - * @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); - } + while (slashIndex !== -1) { + const folder = relativePath.slice(lastNonSlashIndex, slashIndex); - get modulesIterable() { - const chunkGraph = ChunkGraph.getChunkGraphForChunk( - this, - "Chunk.modulesIterable", - "DEP_WEBPACK_CHUNK_MODULES_ITERABLE" - ); - return chunkGraph.getOrderedChunkModulesIterable( - this, - compareModulesByIdentifier - ); - } + switch (folder) { + case "..": { + cd--; + if (cd < 0) + return new Error( + `Trying to access out of package scope. Requesting ${relativePath}` + ); + break; + } + default: + cd++; + break; + } - /** - * @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); + lastNonSlashIndex = slashIndex + 1; + slashIndex = relativePath.indexOf("/", lastNonSlashIndex); } +}; +exports.checkExportsFieldTarget = checkExportsFieldTarget; - /** - * @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(); - } +/***/ 70665: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @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); - } +"use strict"; +/* + Copyright (C) 2015 Yusuke Suzuki - /** - * @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; - } - } + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - /** - * @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); - } + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - /** - * @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; - } + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ - /** - * @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); - } +const Variable = __webpack_require__(82971); - /** - * @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); - } +/** + * @class Definition + */ +class Definition { + constructor(type, name, node, parent, index, kind) { - /** - * @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} */ - const chunkModuleIdMap = Object.create(null); - /** @type {Record} */ - const chunkModuleHashMap = Object.create(null); + /** + * @member {String} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). + */ + this.type = type; - 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 - ); - } - } - } + /** + * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence. + */ + this.name = name; - return { - id: chunkModuleIdMap, - hash: chunkModuleHashMap - }; - } + /** + * @member {espree.Node} Definition#node - the enclosing node of the identifier. + */ + this.node = node; - /** - * @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); - } + /** + * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier. + */ + this.parent = parent; - /** - * @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} */ - const chunkHashMap = Object.create(null); - /** @type {Record>} */ - const chunkContentHashMap = Object.create(null); - /** @type {Record} */ - const chunkNameMap = Object.create(null); + /** + * @member {Number?} Definition#index - the index in the declaration statement. + */ + this.index = index; - 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; - } - } + /** + * @member {String?} Definition#kind - the kind of the declaration statement. + */ + this.kind = kind; + } +} - return { - hash: chunkHashMap, - contentHash: chunkContentHashMap, - name: chunkNameMap - }; - } - // BACKWARD-COMPAT END +/** + * @class ParameterDefinition + */ +class ParameterDefinition extends Definition { + constructor(name, node, index, rest) { + super(Variable.Parameter, name, node, null, index, null); - /** - * @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; - } + /** + * Whether the parameter definition is a part of a rest parameter. + * @member {boolean} ParameterDefinition#rest + */ + this.rest = rest; + } +} - /** - * @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; - } +module.exports = { + ParameterDefinition, + Definition +}; - /** - * @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; - } +/* vim: set sw=4 ts=4 et tw=80 : */ - /** - * @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); - } +/***/ 36007: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @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); - } +"use strict"; +/* + Copyright (C) 2012-2014 Yusuke Suzuki + Copyright (C) 2013 Alex Seville + Copyright (C) 2014 Thiago de Arruda - /** - * @returns {number} the amount of groups that the said chunk is in - */ - getNumberOfGroups() { - return this._groups.size; - } + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - /** - * @returns {Iterable} the chunkGroups that the said chunk is referenced in - */ - get groupsIterable() { - this._groups.sort(); - return this._groups; - } + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - /** - * @returns {void} - */ - disconnectFromGroups() { - for (const chunkGroup of this._groups) { - chunkGroup.removeChunk(this); - } - } + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ - /** - * @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); - } +/** + * Escope (escope) is an ECMAScript + * scope analyzer extracted from the esmangle project. + *

+ * escope finds lexical scopes in a source program, i.e. areas of that + * program where different occurrences of the same identifier refer to the same + * variable. With each scope the contained variables are collected, and each + * identifier reference in code is linked to its corresponding variable (if + * possible). + *

+ * escope works on a syntax tree of the parsed source code which has + * to adhere to the + * Mozilla Parser API. E.g. espree is a parser + * that produces such syntax trees. + *

+ * The main interface is the {@link analyze} function. + * @module escope + */ - /** - * @param {Hash} hash hash (will be modified) - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {void} - */ - updateHash(hash, chunkGraph) { - hash.update( - `${this.id} ${this.ids ? this.ids.join() : ""} ${this.name || ""} ` - ); - const xor = new StringXor(); - for (const m of chunkGraph.getChunkModulesIterable(this)) { - xor.add(chunkGraph.getModuleHash(m, this.runtime)); - } - xor.updateHash(hash); - const entryModules = - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(this); - for (const [m, chunkGroup] of entryModules) { - hash.update(`entry${chunkGraph.getModuleId(m)}${chunkGroup.id}`); - } - } - /** - * @returns {Set} a set of all the async chunks - */ - getAllAsyncChunks() { - const queue = new Set(); - const chunks = new Set(); +/* eslint no-underscore-dangle: ["error", { "allow": ["__currentScope"] }] */ - const initialChunks = intersect( - Array.from(this.groupsIterable, g => new Set(g.chunks)) - ); +const assert = __webpack_require__(39491); - const initialQueue = new Set(this.groupsIterable); +const ScopeManager = __webpack_require__(96988); +const Referencer = __webpack_require__(44585); +const Reference = __webpack_require__(64945); +const Variable = __webpack_require__(82971); +const Scope = (__webpack_require__(16313).Scope); +const version = (__webpack_require__(30290)/* .version */ .i8); - for (const chunkGroup of initialQueue) { - for (const child of chunkGroup.childrenIterable) { - if (child instanceof Entrypoint) { - initialQueue.add(child); - } else { - queue.add(child); - } - } - } +/** + * Set the default options + * @returns {Object} options + */ +function defaultOptions() { + return { + optimistic: false, + directive: false, + nodejsScope: false, + impliedStrict: false, + sourceType: "script", // one of ['script', 'module'] + ecmaVersion: 5, + childVisitorKeys: null, + fallback: "iteration" + }; +} - 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); - } - } +/** + * Preform deep update on option object + * @param {Object} target - Options + * @param {Object} override - Updates + * @returns {Object} Updated options + */ +function updateDeeply(target, override) { - return chunks; - } + /** + * Is hash object + * @param {Object} value - Test value + * @returns {boolean} Result + */ + function isHashObject(value) { + return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp); + } - /** - * @returns {Set} a set of all the initial chunks (including itself) - */ - getAllInitialChunks() { - const chunks = new Set(); - const queue = new Set(this.groupsIterable); - for (const group of queue) { - if (group.isInitial()) { - for (const c of group.chunks) chunks.add(c); - for (const g of group.childrenIterable) queue.add(g); - } - } - return chunks; - } + for (const key in override) { + if (Object.prototype.hasOwnProperty.call(override, key)) { + const val = override[key]; - /** - * @returns {Set} a set of all the referenced chunks (including itself) - */ - getAllReferencedChunks() { - const queue = new Set(this.groupsIterable); - const chunks = new Set(); + if (isHashObject(val)) { + if (isHashObject(target[key])) { + updateDeeply(target[key], val); + } else { + target[key] = updateDeeply({}, val); + } + } else { + target[key] = val; + } + } + } + return target; +} - for (const chunkGroup of queue) { - for (const chunk of chunkGroup.chunks) { - chunks.add(chunk); - } - for (const child of chunkGroup.childrenIterable) { - queue.add(child); - } - } +/** + * Main interface function. Takes an Espree syntax tree and returns the + * analyzed scopes. + * @function analyze + * @param {espree.Tree} tree - Abstract Syntax Tree + * @param {Object} providedOptions - Options that tailor the scope analysis + * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag + * @param {boolean} [providedOptions.directive=false]- the directive flag + * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls + * @param {boolean} [providedOptions.nodejsScope=false]- whether the whole + * script is executed under node.js environment. When enabled, escope adds + * a function scope immediately following the global scope. + * @param {boolean} [providedOptions.impliedStrict=false]- implied strict mode + * (if ecmaVersion >= 5). + * @param {string} [providedOptions.sourceType='script']- the source type of the script. one of 'script' and 'module' + * @param {number} [providedOptions.ecmaVersion=5]- which ECMAScript version is considered + * @param {Object} [providedOptions.childVisitorKeys=null] - Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option. + * @param {string} [providedOptions.fallback='iteration'] - A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option. + * @returns {ScopeManager} ScopeManager + */ +function analyze(tree, providedOptions) { + const options = updateDeeply(defaultOptions(), providedOptions); + const scopeManager = new ScopeManager(options); + const referencer = new Referencer(options, scopeManager); - return chunks; - } + referencer.visit(tree); - /** - * @returns {Set} a set of all the referenced entrypoints - */ - getAllReferencedAsyncEntrypoints() { - const queue = new Set(this.groupsIterable); - const entrypoints = new Set(); + assert(scopeManager.__currentScope === null, "currentScope should be null."); - for (const chunkGroup of queue) { - for (const entrypoint of chunkGroup.asyncEntrypointsIterable) { - entrypoints.add(entrypoint); - } - for (const child of chunkGroup.childrenIterable) { - queue.add(child); - } - } + return scopeManager; +} - return entrypoints; - } +module.exports = { - /** - * @returns {boolean} true, if the chunk references async chunks - */ - hasAsyncChunks() { - const queue = new Set(); + /** @name module:escope.version */ + version, - const initialChunks = intersect( - Array.from(this.groupsIterable, g => new Set(g.chunks)) - ); + /** @name module:escope.Reference */ + Reference, - for (const chunkGroup of this.groupsIterable) { - for (const child of chunkGroup.childrenIterable) { - queue.add(child); - } - } + /** @name module:escope.Variable */ + Variable, - 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); - } - } + /** @name module:escope.Scope */ + Scope, - return false; - } + /** @name module:escope.ScopeManager */ + ScopeManager, + analyze +}; - /** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {ChunkFilterPredicate=} filterFn function used to filter chunks - * @returns {Record} a record object of names to lists of child ids(?) - */ - getChildIdsByOrders(chunkGraph, filterFn) { - /** @type {Map} */ - 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} */ - 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} */ - 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 }[]} 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; - } +/* vim: set sw=4 ts=4 et tw=80 : */ - /** - * @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>} a record object of names to lists of child ids(?) by chunk id - */ - getChildIdsByOrdersMap(chunkGraph, includeDirectChildren, filterFn) { - /** @type {Record>} */ - 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} */ - 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); - } - } +/***/ 54162: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - for (const chunk of this.getAllAsyncChunks()) { - addChildIdsByOrdersToMap(chunk); - } +"use strict"; +/* + Copyright (C) 2015 Yusuke Suzuki - return chunkMaps; - } -} + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: -module.exports = Chunk; + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ -/***/ }), -/***/ 64971: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/* eslint-disable no-undefined */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const Syntax = (__webpack_require__(18350).Syntax); +const esrecurse = __webpack_require__(81217); +/** + * Get last array element + * @param {array} xs - array + * @returns {any} Last elment + */ +function getLast(xs) { + return xs[xs.length - 1] || null; +} +class PatternVisitor extends esrecurse.Visitor { + static isPattern(node) { + const nodeType = node.type; -const util = __webpack_require__(73837); -const Entrypoint = __webpack_require__(13795); -const ModuleGraphConnection = __webpack_require__(40639); -const { first } = __webpack_require__(93347); -const SortableSet = __webpack_require__(13098); -const { - compareModulesById, - compareIterables, - compareModulesByIdentifier, - concatComparators, - compareSelect, - compareIds -} = __webpack_require__(29579); -const createHash = __webpack_require__(49835); -const findGraphRoots = __webpack_require__(6261); -const { - RuntimeSpecMap, - RuntimeSpecSet, - runtimeToString, - mergeRuntime, - forEachRuntime -} = __webpack_require__(17156); + return ( + nodeType === Syntax.Identifier || + nodeType === Syntax.ObjectPattern || + nodeType === Syntax.ArrayPattern || + nodeType === Syntax.SpreadElement || + nodeType === Syntax.RestElement || + nodeType === Syntax.AssignmentPattern + ); + } -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./RuntimeModule")} RuntimeModule */ -/** @typedef {typeof import("./util/Hash")} Hash */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + constructor(options, rootPattern, callback) { + super(null, options); + this.rootPattern = rootPattern; + this.callback = callback; + this.assignments = []; + this.rightHandNodes = []; + this.restElements = []; + } -/** @type {ReadonlySet} */ -const EMPTY_SET = new Set(); + Identifier(pattern) { + const lastRestElement = getLast(this.restElements); -const ZERO_BIG_INT = BigInt(0); + this.callback(pattern, { + topLevel: pattern === this.rootPattern, + rest: lastRestElement !== null && lastRestElement !== undefined && lastRestElement.argument === pattern, + assignments: this.assignments + }); + } -const compareModuleIterables = compareIterables(compareModulesByIdentifier); + Property(property) { -/** @typedef {(c: Chunk, chunkGraph: ChunkGraph) => boolean} ChunkFilterPredicate */ -/** @typedef {(m: Module) => boolean} ModuleFilterPredicate */ + // Computed property's key is a right hand node. + if (property.computed) { + this.rightHandNodes.push(property.key); + } -/** - * @typedef {Object} ChunkSizeOptions - * @property {number=} chunkOverhead constant overhead for a chunk - * @property {number=} entryChunkMultiplicator multiplicator for initial chunks - */ + // If it's shorthand, its key is same as its value. + // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). + // If it's not shorthand, the name of new variable is its value's. + this.visit(property.value); + } -class ModuleHashInfo { - constructor(hash, renderedHash) { - this.hash = hash; - this.renderedHash = renderedHash; - } -} + ArrayPattern(pattern) { + for (let i = 0, iz = pattern.elements.length; i < iz; ++i) { + const element = pattern.elements[i]; -/** @template T @typedef {(set: SortableSet) => T[]} SetToArrayFunction */ + this.visit(element); + } + } -/** - * @template T - * @param {SortableSet} set the set - * @returns {T[]} set as array - */ -const getArray = set => { - return Array.from(set); -}; + AssignmentPattern(pattern) { + this.assignments.push(pattern); + this.visit(pattern.left); + this.rightHandNodes.push(pattern.right); + this.assignments.pop(); + } -/** - * @param {SortableSet} chunks the chunks - * @returns {RuntimeSpecSet} runtimes - */ -const getModuleRuntimes = chunks => { - const runtimes = new RuntimeSpecSet(); - for (const chunk of chunks) { - runtimes.add(chunk.runtime); - } - return runtimes; -}; + RestElement(pattern) { + this.restElements.push(pattern); + this.visit(pattern.argument); + this.restElements.pop(); + } -/** - * @param {SortableSet} set the set - * @returns {Map>} modules by source type - */ -const modulesBySourceType = set => { - /** @type {Map>} */ - const map = new Map(); - for (const module of set) { - for (const sourceType of module.getSourceTypes()) { - let innerSet = map.get(sourceType); - if (innerSet === undefined) { - innerSet = new SortableSet(); - map.set(sourceType, innerSet); - } - innerSet.add(module); - } - } - for (const [key, innerSet] of map) { - // When all modules have the source type, we reuse the original SortableSet - // to benefit from the shared cache (especially for sorting) - if (innerSet.size === set.size) { - map.set(key, set); - } - } - return map; -}; + MemberExpression(node) { -/** @type {WeakMap} */ -const createOrderedArrayFunctionMap = new WeakMap(); + // Computed property's key is a right hand node. + if (node.computed) { + this.rightHandNodes.push(node.property); + } -/** - * @template T - * @param {function(T, T): -1|0|1} comparator comparator function - * @returns {SetToArrayFunction} set as ordered array - */ -const createOrderedArrayFunction = comparator => { - /** @type {SetToArrayFunction} */ - let fn = createOrderedArrayFunctionMap.get(comparator); - if (fn !== undefined) return fn; - fn = set => { - set.sortWith(comparator); - return Array.from(set); - }; - createOrderedArrayFunctionMap.set(comparator, fn); - return fn; -}; + // the object is only read, write to its property. + this.rightHandNodes.push(node.object); + } -/** - * @param {Iterable} modules the modules to get the count/size of - * @returns {number} the size of the modules - */ -const getModulesSize = modules => { - let size = 0; - for (const module of modules) { - for (const type of module.getSourceTypes()) { - size += module.size(type); - } - } - return size; -}; + // + // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression. + // By spec, LeftHandSideExpression is Pattern or MemberExpression. + // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758) + // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc... + // -/** - * @param {Iterable} modules the sortable Set to get the size of - * @returns {Record} the sizes of the modules - */ -const getModulesSizes = modules => { - let sizes = Object.create(null); - for (const module of modules) { - for (const type of module.getSourceTypes()) { - sizes[type] = (sizes[type] || 0) + module.size(type); - } - } - return sizes; -}; + SpreadElement(node) { + this.visit(node.argument); + } -/** - * @param {Chunk} a chunk - * @param {Chunk} b chunk - * @returns {boolean} true, if a is always a parent of b - */ -const isAvailableChunk = (a, b) => { - const queue = new Set(b.groupsIterable); - for (const chunkGroup of queue) { - if (a.isInGroup(chunkGroup)) continue; - if (chunkGroup.isInitial()) return false; - for (const parent of chunkGroup.parentsIterable) { - queue.add(parent); - } - } - return true; -}; + ArrayExpression(node) { + node.elements.forEach(this.visit, this); + } -class ChunkGraphModule { - constructor() { - /** @type {SortableSet} */ - this.chunks = new SortableSet(); - /** @type {Set | undefined} */ - this.entryInChunks = undefined; - /** @type {Set | undefined} */ - this.runtimeInChunks = undefined; - /** @type {RuntimeSpecMap} */ - this.hashes = undefined; - /** @type {string | number} */ - this.id = null; - /** @type {RuntimeSpecMap> | undefined} */ - this.runtimeRequirements = undefined; - /** @type {RuntimeSpecMap} */ - this.graphHashes = undefined; - /** @type {RuntimeSpecMap} */ - this.graphHashesWithConnections = undefined; - } -} + AssignmentExpression(node) { + this.assignments.push(node); + this.visit(node.left); + this.rightHandNodes.push(node.right); + this.assignments.pop(); + } -class ChunkGraphChunk { - constructor() { - /** @type {SortableSet} */ - this.modules = new SortableSet(); - /** @type {Map} */ - this.entryModules = new Map(); - /** @type {SortableSet} */ - this.runtimeModules = new SortableSet(); - /** @type {Set | undefined} */ - this.fullHashModules = undefined; - /** @type {Set | undefined} */ - this.dependentHashModules = undefined; - /** @type {Set | undefined} */ - this.runtimeRequirements = undefined; - /** @type {Set} */ - this.runtimeRequirementsInTree = new Set(); - } + CallExpression(node) { + + // arguments are right hand nodes. + node.arguments.forEach(a => { + this.rightHandNodes.push(a); + }); + this.visit(node.callee); + } } -class ChunkGraph { - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {string | Hash} hashFunction the hash function to use - */ - constructor(moduleGraph, hashFunction = "md4") { - /** @private @type {WeakMap} */ - this._modules = new WeakMap(); - /** @private @type {WeakMap} */ - this._chunks = new WeakMap(); - /** @private @type {WeakMap} */ - this._blockChunkGroups = new WeakMap(); - /** @private @type {Map} */ - this._runtimeIds = new Map(); - /** @type {ModuleGraph} */ - this.moduleGraph = moduleGraph; +module.exports = PatternVisitor; - this._hashFunction = hashFunction; +/* vim: set sw=4 ts=4 et tw=80 : */ - this._getGraphRoots = this._getGraphRoots.bind(this); - } - /** - * @private - * @param {Module} module the module - * @returns {ChunkGraphModule} internal module - */ - _getChunkGraphModule(module) { - let cgm = this._modules.get(module); - if (cgm === undefined) { - cgm = new ChunkGraphModule(); - this._modules.set(module, cgm); - } - return cgm; - } +/***/ }), - /** - * @private - * @param {Chunk} chunk the chunk - * @returns {ChunkGraphChunk} internal chunk - */ - _getChunkGraphChunk(chunk) { - let cgc = this._chunks.get(chunk); - if (cgc === undefined) { - cgc = new ChunkGraphChunk(); - this._chunks.set(chunk, cgc); - } - return cgc; - } +/***/ 64945: +/***/ (function(module) { - /** - * @param {SortableSet} set the sortable Set to get the roots of - * @returns {Module[]} the graph roots - */ - _getGraphRoots(set) { - const { moduleGraph } = this; - return Array.from( - findGraphRoots(set, module => { - /** @type {Set} */ - const set = new Set(); - const addDependencies = module => { - for (const connection of moduleGraph.getOutgoingConnections(module)) { - if (!connection.module) continue; - const activeState = connection.getActiveState(undefined); - if (activeState === false) continue; - if (activeState === ModuleGraphConnection.TRANSITIVE_ONLY) { - addDependencies(connection.module); - continue; - } - set.add(connection.module); - } - }; - addDependencies(module); - return set; - }) - ).sort(compareModulesByIdentifier); - } +"use strict"; +/* + Copyright (C) 2015 Yusuke Suzuki - /** - * @param {Chunk} chunk the new chunk - * @param {Module} module the module - * @returns {void} - */ - connectChunkAndModule(chunk, module) { - const cgm = this._getChunkGraphModule(module); - const cgc = this._getChunkGraphChunk(chunk); - cgm.chunks.add(chunk); - cgc.modules.add(module); - } + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - /** - * @param {Chunk} chunk the chunk - * @param {Module} module the module - * @returns {void} - */ - disconnectChunkAndModule(chunk, module) { - const cgm = this._getChunkGraphModule(module); - const cgc = this._getChunkGraphChunk(chunk); - cgc.modules.delete(module); - cgm.chunks.delete(chunk); - } + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - /** - * @param {Chunk} chunk the chunk which will be disconnected - * @returns {void} - */ - disconnectChunk(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - for (const module of cgc.modules) { - const cgm = this._getChunkGraphModule(module); - cgm.chunks.delete(chunk); - } - cgc.modules.clear(); - chunk.disconnectFromGroups(); - ChunkGraph.clearChunkGraphForChunk(chunk); - } + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ - /** - * @param {Chunk} chunk the chunk - * @param {Iterable} modules the modules - * @returns {void} - */ - attachModules(chunk, modules) { - const cgc = this._getChunkGraphChunk(chunk); - for (const module of modules) { - cgc.modules.add(module); - } - } - /** - * @param {Chunk} chunk the chunk - * @param {Iterable} modules the runtime modules - * @returns {void} - */ - attachRuntimeModules(chunk, modules) { - const cgc = this._getChunkGraphChunk(chunk); - for (const module of modules) { - cgc.runtimeModules.add(module); - } - } +const READ = 0x1; +const WRITE = 0x2; +const RW = READ | WRITE; - /** - * @param {Chunk} chunk the chunk - * @param {Iterable} modules the modules that require a full hash - * @returns {void} - */ - attachFullHashModules(chunk, modules) { - const cgc = this._getChunkGraphChunk(chunk); - if (cgc.fullHashModules === undefined) cgc.fullHashModules = new Set(); - for (const module of modules) { - cgc.fullHashModules.add(module); - } - } +/** + * A Reference represents a single occurrence of an identifier in code. + * @class Reference + */ +class Reference { + constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) { - /** - * @param {Chunk} chunk the chunk - * @param {Iterable} modules the modules that require a full hash - * @returns {void} - */ - attachDependentHashModules(chunk, modules) { - const cgc = this._getChunkGraphChunk(chunk); - if (cgc.dependentHashModules === undefined) - cgc.dependentHashModules = new Set(); - for (const module of modules) { - cgc.dependentHashModules.add(module); - } - } + /** + * Identifier syntax node. + * @member {espreeIdentifier} Reference#identifier + */ + this.identifier = ident; - /** - * @param {Module} oldModule the replaced module - * @param {Module} newModule the replacing module - * @returns {void} - */ - replaceModule(oldModule, newModule) { - const oldCgm = this._getChunkGraphModule(oldModule); - const newCgm = this._getChunkGraphModule(newModule); + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; - for (const chunk of oldCgm.chunks) { - const cgc = this._getChunkGraphChunk(chunk); - cgc.modules.delete(oldModule); - cgc.modules.add(newModule); - newCgm.chunks.add(chunk); - } - oldCgm.chunks.clear(); + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; - if (oldCgm.entryInChunks !== undefined) { - if (newCgm.entryInChunks === undefined) { - newCgm.entryInChunks = new Set(); - } - for (const chunk of oldCgm.entryInChunks) { - const cgc = this._getChunkGraphChunk(chunk); - const old = cgc.entryModules.get(oldModule); - /** @type {Map} */ - const newEntryModules = new Map(); - for (const [m, cg] of cgc.entryModules) { - if (m === oldModule) { - newEntryModules.set(newModule, old); - } else { - newEntryModules.set(m, cg); - } - } - cgc.entryModules = newEntryModules; - newCgm.entryInChunks.add(chunk); - } - oldCgm.entryInChunks = undefined; - } + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; - if (oldCgm.runtimeInChunks !== undefined) { - if (newCgm.runtimeInChunks === undefined) { - newCgm.runtimeInChunks = new Set(); - } - for (const chunk of oldCgm.runtimeInChunks) { - const cgc = this._getChunkGraphChunk(chunk); - cgc.runtimeModules.delete(/** @type {RuntimeModule} */ (oldModule)); - cgc.runtimeModules.add(/** @type {RuntimeModule} */ (newModule)); - newCgm.runtimeInChunks.add(chunk); - if ( - cgc.fullHashModules !== undefined && - cgc.fullHashModules.has(/** @type {RuntimeModule} */ (oldModule)) - ) { - cgc.fullHashModules.delete(/** @type {RuntimeModule} */ (oldModule)); - cgc.fullHashModules.add(/** @type {RuntimeModule} */ (newModule)); - } - if ( - cgc.dependentHashModules !== undefined && - cgc.dependentHashModules.has(/** @type {RuntimeModule} */ (oldModule)) - ) { - cgc.dependentHashModules.delete( - /** @type {RuntimeModule} */ (oldModule) - ); - cgc.dependentHashModules.add( - /** @type {RuntimeModule} */ (newModule) - ); - } - } - oldCgm.runtimeInChunks = undefined; - } - } + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + * @private + */ + this.flag = flag; + if (this.isWrite()) { - /** - * @param {Module} module the checked module - * @param {Chunk} chunk the checked chunk - * @returns {boolean} true, if the chunk contains the module - */ - isModuleInChunk(module, chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules.has(module); - } + /** + * If reference is writeable, this is the tree being written to it. + * @member {espreeNode} Reference#writeExpr + */ + this.writeExpr = writeExpr; - /** - * @param {Module} module the checked module - * @param {ChunkGroup} chunkGroup the checked chunk group - * @returns {boolean} true, if the chunk contains the module - */ - isModuleInChunkGroup(module, chunkGroup) { - for (const chunk of chunkGroup.chunks) { - if (this.isModuleInChunk(module, chunk)) return true; - } - return false; - } + /** + * Whether the Reference might refer to a partial value of writeExpr. + * @member {boolean} Reference#partial + */ + this.partial = partial; - /** - * @param {Module} module the checked module - * @returns {boolean} true, if the module is entry of any chunk - */ - isEntryModule(module) { - const cgm = this._getChunkGraphModule(module); - return cgm.entryInChunks !== undefined; - } + /** + * Whether the Reference is to write of initialization. + * @member {boolean} Reference#init + */ + this.init = init; + } + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } - /** - * @param {Module} module the module - * @returns {Iterable} iterable of chunks (do not modify) - */ - getModuleChunksIterable(module) { - const cgm = this._getChunkGraphModule(module); - return cgm.chunks; - } + /** + * Whether the reference is static. + * @method Reference#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + } - /** - * @param {Module} module the module - * @param {function(Chunk, Chunk): -1|0|1} sortFn sort function - * @returns {Iterable} iterable of chunks (do not modify) - */ - getOrderedModuleChunksIterable(module, sortFn) { - const cgm = this._getChunkGraphModule(module); - cgm.chunks.sortWith(sortFn); - return cgm.chunks; - } + /** + * Whether the reference is writeable. + * @method Reference#isWrite + * @returns {boolean} write + */ + isWrite() { + return !!(this.flag & Reference.WRITE); + } - /** - * @param {Module} module the module - * @returns {Chunk[]} array of chunks (cached, do not modify) - */ - getModuleChunks(module) { - const cgm = this._getChunkGraphModule(module); - return cgm.chunks.getFromCache(getArray); - } + /** + * Whether the reference is readable. + * @method Reference#isRead + * @returns {boolean} read + */ + isRead() { + return !!(this.flag & Reference.READ); + } - /** - * @param {Module} module the module - * @returns {number} the number of chunk which contain the module - */ - getNumberOfModuleChunks(module) { - const cgm = this._getChunkGraphModule(module); - return cgm.chunks.size; - } + /** + * Whether the reference is read-only. + * @method Reference#isReadOnly + * @returns {boolean} read only + */ + isReadOnly() { + return this.flag === Reference.READ; + } - /** - * @param {Module} module the module - * @returns {RuntimeSpecSet} runtimes - */ - getModuleRuntimes(module) { - const cgm = this._getChunkGraphModule(module); - return cgm.chunks.getFromUnorderedCache(getModuleRuntimes); - } + /** + * Whether the reference is write-only. + * @method Reference#isWriteOnly + * @returns {boolean} write only + */ + isWriteOnly() { + return this.flag === Reference.WRITE; + } - /** - * @param {Chunk} chunk the chunk - * @returns {number} the number of modules which are contained in this chunk - */ - getNumberOfChunkModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules.size; - } + /** + * Whether the reference is read-write. + * @method Reference#isReadWrite + * @returns {boolean} read write + */ + isReadWrite() { + return this.flag === Reference.RW; + } +} - /** - * @param {Chunk} chunk the chunk - * @returns {number} the number of full hash modules which are contained in this chunk - */ - getNumberOfChunkFullHashModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.fullHashModules === undefined ? 0 : cgc.fullHashModules.size; - } +/** + * @constant Reference.READ + * @private + */ +Reference.READ = READ; - /** - * @param {Chunk} chunk the chunk - * @returns {Iterable} return the modules for this chunk - */ - getChunkModulesIterable(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules; - } +/** + * @constant Reference.WRITE + * @private + */ +Reference.WRITE = WRITE; - /** - * @param {Chunk} chunk the chunk - * @param {string} sourceType source type - * @returns {Iterable | undefined} return the modules for this chunk - */ - getChunkModulesIterableBySourceType(chunk, sourceType) { - const cgc = this._getChunkGraphChunk(chunk); - const modulesWithSourceType = cgc.modules - .getFromUnorderedCache(modulesBySourceType) - .get(sourceType); - return modulesWithSourceType; - } +/** + * @constant Reference.RW + * @private + */ +Reference.RW = RW; - /** - * @param {Chunk} chunk the chunk - * @param {function(Module, Module): -1|0|1} comparator comparator function - * @returns {Iterable} return the modules for this chunk - */ - getOrderedChunkModulesIterable(chunk, comparator) { - const cgc = this._getChunkGraphChunk(chunk); - cgc.modules.sortWith(comparator); - return cgc.modules; - } +module.exports = Reference; - /** - * @param {Chunk} chunk the chunk - * @param {string} sourceType source type - * @param {function(Module, Module): -1|0|1} comparator comparator function - * @returns {Iterable | undefined} return the modules for this chunk - */ - getOrderedChunkModulesIterableBySourceType(chunk, sourceType, comparator) { - const cgc = this._getChunkGraphChunk(chunk); - const modulesWithSourceType = cgc.modules - .getFromUnorderedCache(modulesBySourceType) - .get(sourceType); - if (modulesWithSourceType === undefined) return undefined; - modulesWithSourceType.sortWith(comparator); - return modulesWithSourceType; - } +/* vim: set sw=4 ts=4 et tw=80 : */ - /** - * @param {Chunk} chunk the chunk - * @returns {Module[]} return the modules for this chunk (cached, do not modify) - */ - getChunkModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules.getFromUnorderedCache(getArray); - } - /** - * @param {Chunk} chunk the chunk - * @param {function(Module, Module): -1|0|1} comparator comparator function - * @returns {Module[]} return the modules for this chunk (cached, do not modify) - */ - getOrderedChunkModules(chunk, comparator) { - const cgc = this._getChunkGraphChunk(chunk); - const arrayFunction = createOrderedArrayFunction(comparator); - return cgc.modules.getFromUnorderedCache(arrayFunction); - } +/***/ }), - /** - * @param {Chunk} chunk the chunk - * @param {ModuleFilterPredicate} filterFn function used to filter modules - * @param {boolean} includeAllChunks all chunks or only async chunks - * @returns {Record} chunk to module ids object - */ - getChunkModuleIdMap(chunk, filterFn, includeAllChunks = false) { - /** @type {Record} */ - const chunkModuleIdMap = Object.create(null); +/***/ 44585: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - for (const asyncChunk of includeAllChunks - ? chunk.getAllReferencedChunks() - : chunk.getAllAsyncChunks()) { - /** @type {(string|number)[]} */ - let array; - for (const module of this.getOrderedChunkModulesIterable( - asyncChunk, - compareModulesById(this) - )) { - if (filterFn(module)) { - if (array === undefined) { - array = []; - chunkModuleIdMap[asyncChunk.id] = array; - } - const moduleId = this.getModuleId(module); - array.push(moduleId); - } - } - } +"use strict"; +/* + Copyright (C) 2015 Yusuke Suzuki - return chunkModuleIdMap; - } + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - /** - * @param {Chunk} chunk the chunk - * @param {ModuleFilterPredicate} filterFn function used to filter modules - * @param {number} hashLength length of the hash - * @param {boolean} includeAllChunks all chunks or only async chunks - * @returns {Record>} chunk to module id to module hash object - */ - getChunkModuleRenderedHashMap( - chunk, - filterFn, - hashLength = 0, - includeAllChunks = false - ) { - /** @type {Record>} */ - const chunkModuleHashMap = Object.create(null); + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - for (const asyncChunk of includeAllChunks - ? chunk.getAllReferencedChunks() - : chunk.getAllAsyncChunks()) { - /** @type {Record} */ - let idToHashMap; - for (const module of this.getOrderedChunkModulesIterable( - asyncChunk, - compareModulesById(this) - )) { - if (filterFn(module)) { - if (idToHashMap === undefined) { - idToHashMap = Object.create(null); - chunkModuleHashMap[asyncChunk.id] = idToHashMap; - } - const moduleId = this.getModuleId(module); - const hash = this.getRenderedModuleHash(module, asyncChunk.runtime); - idToHashMap[moduleId] = hashLength ? hash.slice(0, hashLength) : hash; - } - } - } + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ - return chunkModuleHashMap; - } - /** - * @param {Chunk} chunk the chunk - * @param {ChunkFilterPredicate} filterFn function used to filter chunks - * @returns {Record} chunk map - */ - getChunkConditionMap(chunk, filterFn) { - const map = Object.create(null); - for (const c of chunk.getAllReferencedChunks()) { - map[c.id] = filterFn(c, this); - } - return map; - } +/* eslint-disable no-underscore-dangle */ +/* eslint-disable no-undefined */ - /** - * @param {Chunk} chunk the chunk - * @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(chunk, filterFn, filterChunkFn) { - const queue = new Set(chunk.groupsIterable); - const chunksProcessed = new Set(); +const Syntax = (__webpack_require__(18350).Syntax); +const esrecurse = __webpack_require__(81217); +const Reference = __webpack_require__(64945); +const Variable = __webpack_require__(82971); +const PatternVisitor = __webpack_require__(54162); +const definition = __webpack_require__(70665); +const assert = __webpack_require__(39491); - for (const chunkGroup of queue) { - for (const innerChunk of chunkGroup.chunks) { - if (!chunksProcessed.has(innerChunk)) { - chunksProcessed.add(innerChunk); - if (!filterChunkFn || filterChunkFn(innerChunk, this)) { - for (const module of this.getChunkModulesIterable(innerChunk)) { - if (filterFn(module)) { - return true; - } - } - } - } - } - for (const child of chunkGroup.childrenIterable) { - queue.add(child); - } - } - return false; - } +const ParameterDefinition = definition.ParameterDefinition; +const Definition = definition.Definition; - /** - * @param {Chunk} chunkA first chunk - * @param {Chunk} chunkB second chunk - * @returns {-1|0|1} this is a comparator function like sort and returns -1, 0, or 1 based on sort order - */ - compareChunks(chunkA, chunkB) { - const cgcA = this._getChunkGraphChunk(chunkA); - const cgcB = this._getChunkGraphChunk(chunkB); - if (cgcA.modules.size > cgcB.modules.size) return -1; - if (cgcA.modules.size < cgcB.modules.size) return 1; - cgcA.modules.sortWith(compareModulesByIdentifier); - cgcB.modules.sortWith(compareModulesByIdentifier); - return compareModuleIterables(cgcA.modules, cgcB.modules); - } +/** + * Traverse identifier in pattern + * @param {Object} options - options + * @param {pattern} rootPattern - root pattern + * @param {Refencer} referencer - referencer + * @param {callback} callback - callback + * @returns {void} + */ +function traverseIdentifierInPattern(options, rootPattern, referencer, callback) { - /** - * @param {Chunk} chunk the chunk - * @returns {number} total size of all modules in the chunk - */ - getChunkModulesSize(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules.getFromUnorderedCache(getModulesSize); - } + // Call the callback at left hand identifier nodes, and Collect right hand nodes. + const visitor = new PatternVisitor(options, rootPattern, callback); - /** - * @param {Chunk} chunk the chunk - * @returns {Record} total sizes of all modules in the chunk by source type - */ - getChunkModulesSizes(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules.getFromUnorderedCache(getModulesSizes); - } + visitor.visit(rootPattern); - /** - * @param {Chunk} chunk the chunk - * @returns {Module[]} root modules of the chunks (ordered by identifier) - */ - getChunkRootModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules.getFromUnorderedCache(this._getGraphRoots); - } + // Process the right hand nodes recursively. + if (referencer !== null && referencer !== undefined) { + visitor.rightHandNodes.forEach(referencer.visit, referencer); + } +} - /** - * @param {Chunk} chunk the chunk - * @param {ChunkSizeOptions} options options object - * @returns {number} total size of the chunk - */ - getChunkSize(chunk, options = {}) { - const cgc = this._getChunkGraphChunk(chunk); - const modulesSize = cgc.modules.getFromUnorderedCache(getModulesSize); - const chunkOverhead = - typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; - const entryChunkMultiplicator = - typeof options.entryChunkMultiplicator === "number" - ? options.entryChunkMultiplicator - : 10; - return ( - chunkOverhead + - modulesSize * (chunk.canBeInitial() ? entryChunkMultiplicator : 1) - ); - } +// Importing ImportDeclaration. +// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation +// https://github.com/estree/estree/blob/master/es6.md#importdeclaration +// FIXME: Now, we don't create module environment, because the context is +// implementation dependent. - /** - * @param {Chunk} chunkA chunk - * @param {Chunk} chunkB chunk - * @param {ChunkSizeOptions} options options object - * @returns {number} total size of the chunk or false if chunks can't be integrated - */ - getIntegratedChunksSize(chunkA, chunkB, options = {}) { - const cgcA = this._getChunkGraphChunk(chunkA); - const cgcB = this._getChunkGraphChunk(chunkB); - const allModules = new Set(cgcA.modules); - for (const m of cgcB.modules) allModules.add(m); - let modulesSize = getModulesSize(allModules); - const chunkOverhead = - typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; - const entryChunkMultiplicator = - typeof options.entryChunkMultiplicator === "number" - ? options.entryChunkMultiplicator - : 10; - return ( - chunkOverhead + - modulesSize * - (chunkA.canBeInitial() || chunkB.canBeInitial() - ? entryChunkMultiplicator - : 1) - ); - } +class Importer extends esrecurse.Visitor { + constructor(declaration, referencer) { + super(null, referencer.options); + this.declaration = declaration; + this.referencer = referencer; + } - /** - * @param {Chunk} chunkA chunk - * @param {Chunk} chunkB chunk - * @returns {boolean} true, if chunks could be integrated - */ - canChunksBeIntegrated(chunkA, chunkB) { - if (chunkA.preventIntegration || chunkB.preventIntegration) { - return false; - } + visitImport(id, specifier) { + this.referencer.visitPattern(id, pattern => { + this.referencer.currentScope().__define(pattern, + new Definition( + Variable.ImportBinding, + pattern, + specifier, + this.declaration, + null, + null + )); + }); + } - const hasRuntimeA = chunkA.hasRuntime(); - const hasRuntimeB = chunkB.hasRuntime(); + ImportNamespaceSpecifier(node) { + const local = (node.local || node.id); - if (hasRuntimeA !== hasRuntimeB) { - if (hasRuntimeA) { - return isAvailableChunk(chunkA, chunkB); - } else if (hasRuntimeB) { - return isAvailableChunk(chunkB, chunkA); - } else { - return false; - } - } + if (local) { + this.visitImport(local, node); + } + } - if ( - this.getNumberOfEntryModules(chunkA) > 0 || - this.getNumberOfEntryModules(chunkB) > 0 - ) { - return false; - } + ImportDefaultSpecifier(node) { + const local = (node.local || node.id); - return true; - } + this.visitImport(local, node); + } - /** - * @param {Chunk} chunkA the target chunk - * @param {Chunk} chunkB the chunk to integrate - * @returns {void} - */ - integrateChunks(chunkA, chunkB) { - // Decide for one name (deterministic) - if (chunkA.name && chunkB.name) { - if ( - this.getNumberOfEntryModules(chunkA) > 0 === - this.getNumberOfEntryModules(chunkB) > 0 - ) { - // When both chunks have entry modules or none have one, use - // shortest name - if (chunkA.name.length !== chunkB.name.length) { - chunkA.name = - chunkA.name.length < chunkB.name.length ? chunkA.name : chunkB.name; - } else { - chunkA.name = chunkA.name < chunkB.name ? chunkA.name : chunkB.name; - } - } else if (this.getNumberOfEntryModules(chunkB) > 0) { - // Pick the name of the chunk with the entry module - chunkA.name = chunkB.name; - } - } else if (chunkB.name) { - chunkA.name = chunkB.name; - } + ImportSpecifier(node) { + const local = (node.local || node.id); - // Merge id name hints - for (const hint of chunkB.idNameHints) { - chunkA.idNameHints.add(hint); - } + if (node.name) { + this.visitImport(node.name, node); + } else { + this.visitImport(local, node); + } + } +} - // Merge runtime - chunkA.runtime = mergeRuntime(chunkA.runtime, chunkB.runtime); +// Referencing variables and creating bindings. +class Referencer extends esrecurse.Visitor { + constructor(options, scopeManager) { + super(null, options); + this.options = options; + this.scopeManager = scopeManager; + this.parent = null; + this.isInnerMethodDefinition = false; + } - // getChunkModules is used here to create a clone, because disconnectChunkAndModule modifies - for (const module of this.getChunkModules(chunkB)) { - this.disconnectChunkAndModule(chunkB, module); - this.connectChunkAndModule(chunkA, module); - } + currentScope() { + return this.scopeManager.__currentScope; + } - for (const [module, chunkGroup] of Array.from( - this.getChunkEntryModulesWithChunkGroupIterable(chunkB) - )) { - this.disconnectChunkAndEntryModule(chunkB, module); - this.connectChunkAndEntryModule(chunkA, module, chunkGroup); - } + close(node) { + while (this.currentScope() && node === this.currentScope().block) { + this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); + } + } - for (const chunkGroup of chunkB.groupsIterable) { - chunkGroup.replaceChunk(chunkB, chunkA); - chunkA.addGroup(chunkGroup); - chunkB.removeGroup(chunkGroup); - } - ChunkGraph.clearChunkGraphForChunk(chunkB); - } + pushInnerMethodDefinition(isInnerMethodDefinition) { + const previous = this.isInnerMethodDefinition; - /** - * @param {Chunk} chunk the chunk to upgrade - * @returns {void} - */ - upgradeDependentToFullHashModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - if (cgc.dependentHashModules === undefined) return; - if (cgc.fullHashModules === undefined) { - cgc.fullHashModules = cgc.dependentHashModules; - } else { - for (const m of cgc.dependentHashModules) { - cgc.fullHashModules.add(m); - } - cgc.dependentHashModules = undefined; - } - } + this.isInnerMethodDefinition = isInnerMethodDefinition; + return previous; + } - /** - * @param {Module} module the checked module - * @param {Chunk} chunk the checked chunk - * @returns {boolean} true, if the chunk contains the module as entry - */ - isEntryModuleInChunk(module, chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.entryModules.has(module); - } + popInnerMethodDefinition(isInnerMethodDefinition) { + this.isInnerMethodDefinition = isInnerMethodDefinition; + } - /** - * @param {Chunk} chunk the new chunk - * @param {Module} module the entry module - * @param {Entrypoint=} entrypoint the chunk group which must be loaded before the module is executed - * @returns {void} - */ - connectChunkAndEntryModule(chunk, module, entrypoint) { - const cgm = this._getChunkGraphModule(module); - const cgc = this._getChunkGraphChunk(chunk); - if (cgm.entryInChunks === undefined) { - cgm.entryInChunks = new Set(); - } - cgm.entryInChunks.add(chunk); - cgc.entryModules.set(module, entrypoint); - } + referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { + const scope = this.currentScope(); - /** - * @param {Chunk} chunk the new chunk - * @param {RuntimeModule} module the runtime module - * @returns {void} - */ - connectChunkAndRuntimeModule(chunk, module) { - const cgm = this._getChunkGraphModule(module); - const cgc = this._getChunkGraphChunk(chunk); - if (cgm.runtimeInChunks === undefined) { - cgm.runtimeInChunks = new Set(); - } - cgm.runtimeInChunks.add(chunk); - cgc.runtimeModules.add(module); - } + assignments.forEach(assignment => { + scope.__referencing( + pattern, + Reference.WRITE, + assignment.right, + maybeImplicitGlobal, + pattern !== assignment.left, + init + ); + }); + } - /** - * @param {Chunk} chunk the new chunk - * @param {RuntimeModule} module the module that require a full hash - * @returns {void} - */ - addFullHashModuleToChunk(chunk, module) { - const cgc = this._getChunkGraphChunk(chunk); - if (cgc.fullHashModules === undefined) cgc.fullHashModules = new Set(); - cgc.fullHashModules.add(module); - } + visitPattern(node, options, callback) { + let visitPatternOptions = options; + let visitPatternCallback = callback; - /** - * @param {Chunk} chunk the new chunk - * @param {RuntimeModule} module the module that require a full hash - * @returns {void} - */ - addDependentHashModuleToChunk(chunk, module) { - const cgc = this._getChunkGraphChunk(chunk); - if (cgc.dependentHashModules === undefined) - cgc.dependentHashModules = new Set(); - cgc.dependentHashModules.add(module); - } + if (typeof options === "function") { + visitPatternCallback = options; + visitPatternOptions = { processRightHandNodes: false }; + } - /** - * @param {Chunk} chunk the new chunk - * @param {Module} module the entry module - * @returns {void} - */ - disconnectChunkAndEntryModule(chunk, module) { - const cgm = this._getChunkGraphModule(module); - const cgc = this._getChunkGraphChunk(chunk); - cgm.entryInChunks.delete(chunk); - if (cgm.entryInChunks.size === 0) { - cgm.entryInChunks = undefined; - } - cgc.entryModules.delete(module); - } + traverseIdentifierInPattern( + this.options, + node, + visitPatternOptions.processRightHandNodes ? this : null, + visitPatternCallback + ); + } - /** - * @param {Chunk} chunk the new chunk - * @param {RuntimeModule} module the runtime module - * @returns {void} - */ - disconnectChunkAndRuntimeModule(chunk, module) { - const cgm = this._getChunkGraphModule(module); - const cgc = this._getChunkGraphChunk(chunk); - cgm.runtimeInChunks.delete(chunk); - if (cgm.runtimeInChunks.size === 0) { - cgm.runtimeInChunks = undefined; - } - cgc.runtimeModules.delete(module); - } + visitFunction(node) { + let i, iz; - /** - * @param {Module} module the entry module, it will no longer be entry - * @returns {void} - */ - disconnectEntryModule(module) { - const cgm = this._getChunkGraphModule(module); - for (const chunk of cgm.entryInChunks) { - const cgc = this._getChunkGraphChunk(chunk); - cgc.entryModules.delete(module); - } - cgm.entryInChunks = undefined; - } + // FunctionDeclaration name is defined in upper scope + // NOTE: Not referring variableScope. It is intended. + // Since + // in ES5, FunctionDeclaration should be in FunctionBody. + // in ES6, FunctionDeclaration should be block scoped. - /** - * @param {Chunk} chunk the chunk, for which all entries will be removed - * @returns {void} - */ - disconnectEntries(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - for (const module of cgc.entryModules.keys()) { - const cgm = this._getChunkGraphModule(module); - cgm.entryInChunks.delete(chunk); - if (cgm.entryInChunks.size === 0) { - cgm.entryInChunks = undefined; - } - } - cgc.entryModules.clear(); - } + if (node.type === Syntax.FunctionDeclaration) { - /** - * @param {Chunk} chunk the chunk - * @returns {number} the amount of entry modules in chunk - */ - getNumberOfEntryModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.entryModules.size; - } + // id is defined in upper scope + this.currentScope().__define(node.id, + new Definition( + Variable.FunctionName, + node.id, + node, + null, + null, + null + )); + } - /** - * @param {Chunk} chunk the chunk - * @returns {number} the amount of entry modules in chunk - */ - getNumberOfRuntimeModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.runtimeModules.size; - } + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + if (node.type === Syntax.FunctionExpression && node.id) { + this.scopeManager.__nestFunctionExpressionNameScope(node); + } - /** - * @param {Chunk} chunk the chunk - * @returns {Iterable} iterable of modules (do not modify) - */ - getChunkEntryModulesIterable(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.entryModules.keys(); - } + // Consider this function is in the MethodDefinition. + this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); - /** - * @param {Chunk} chunk the chunk - * @returns {Iterable} iterable of chunks - */ - getChunkEntryDependentChunksIterable(chunk) { - /** @type {Set} */ - const set = new Set(); - for (const chunkGroup of chunk.groupsIterable) { - if (chunkGroup instanceof Entrypoint) { - const entrypointChunk = chunkGroup.getEntrypointChunk(); - const cgc = this._getChunkGraphChunk(entrypointChunk); - for (const chunkGroup of cgc.entryModules.values()) { - for (const c of chunkGroup.chunks) { - if (c !== chunk && c !== entrypointChunk && !c.hasRuntime()) { - set.add(c); - } - } - } - } - } + const that = this; - return set; - } + /** + * Visit pattern callback + * @param {pattern} pattern - pattern + * @param {Object} info - info + * @returns {void} + */ + function visitPatternCallback(pattern, info) { + that.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + i, + info.rest + )); - /** - * @param {Chunk} chunk the chunk - * @returns {boolean} true, when it has dependent chunks - */ - hasChunkEntryDependentChunks(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - for (const chunkGroup of cgc.entryModules.values()) { - for (const c of chunkGroup.chunks) { - if (c !== chunk) { - return true; - } - } - } - return false; - } + that.referencingDefaultValue(pattern, info.assignments, null, true); + } - /** - * @param {Chunk} chunk the chunk - * @returns {Iterable} iterable of modules (do not modify) - */ - getChunkRuntimeModulesIterable(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.runtimeModules; - } + // Process parameter declarations. + for (i = 0, iz = node.params.length; i < iz; ++i) { + this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback); + } - /** - * @param {Chunk} chunk the chunk - * @returns {RuntimeModule[]} array of modules in order of execution - */ - getChunkRuntimeModulesInOrder(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - const array = Array.from(cgc.runtimeModules); - array.sort( - concatComparators( - compareSelect( - /** - * @param {RuntimeModule} r runtime module - * @returns {number=} stage - */ - r => r.stage, - compareIds - ), - compareModulesByIdentifier - ) - ); - return array; - } + // if there's a rest argument, add that + if (node.rest) { + this.visitPattern({ + type: "RestElement", + argument: node.rest + }, pattern => { + this.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + node.params.length, + true + )); + }); + } - /** - * @param {Chunk} chunk the chunk - * @returns {Iterable | undefined} iterable of modules (do not modify) - */ - getChunkFullHashModulesIterable(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.fullHashModules; - } + // In TypeScript there are a number of function-like constructs which have no body, + // so check it exists before traversing + if (node.body) { - /** - * @param {Chunk} chunk the chunk - * @returns {ReadonlySet | undefined} set of modules (do not modify) - */ - getChunkFullHashModulesSet(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.fullHashModules; - } + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === Syntax.BlockStatement) { + this.visitChildren(node.body); + } else { + this.visit(node.body); + } + } - /** - * @param {Chunk} chunk the chunk - * @returns {Iterable | undefined} iterable of modules (do not modify) - */ - getChunkDependentHashModulesIterable(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.dependentHashModules; - } + this.close(node); + } - /** @typedef {[Module, Entrypoint | undefined]} EntryModuleWithChunkGroup */ + visitClass(node) { + if (node.type === Syntax.ClassDeclaration) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node, + null, + null, + null + )); + } - /** - * @param {Chunk} chunk the chunk - * @returns {Iterable} iterable of modules (do not modify) - */ - getChunkEntryModulesWithChunkGroupIterable(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.entryModules; - } + this.visit(node.superClass); - /** - * @param {AsyncDependenciesBlock} depBlock the async block - * @returns {ChunkGroup} the chunk group - */ - getBlockChunkGroup(depBlock) { - return this._blockChunkGroups.get(depBlock); - } + this.scopeManager.__nestClassScope(node); - /** - * @param {AsyncDependenciesBlock} depBlock the async block - * @param {ChunkGroup} chunkGroup the chunk group - * @returns {void} - */ - connectBlockAndChunkGroup(depBlock, chunkGroup) { - this._blockChunkGroups.set(depBlock, chunkGroup); - chunkGroup.addBlock(depBlock); - } + if (node.id) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node + )); + } + this.visit(node.body); - /** - * @param {ChunkGroup} chunkGroup the chunk group - * @returns {void} - */ - disconnectChunkGroup(chunkGroup) { - for (const block of chunkGroup.blocksIterable) { - this._blockChunkGroups.delete(block); - } - // TODO refactor by moving blocks list into ChunkGraph - chunkGroup._blocks.clear(); - } + this.close(node); + } - /** - * @param {Module} module the module - * @returns {string | number} the id of the module - */ - getModuleId(module) { - const cgm = this._getChunkGraphModule(module); - return cgm.id; - } + visitProperty(node) { + let previous; - /** - * @param {Module} module the module - * @param {string | number} id the id of the module - * @returns {void} - */ - setModuleId(module, id) { - const cgm = this._getChunkGraphModule(module); - cgm.id = id; - } + if (node.computed) { + this.visit(node.key); + } - /** - * @param {string} runtime runtime - * @returns {string | number} the id of the runtime - */ - getRuntimeId(runtime) { - return this._runtimeIds.get(runtime); - } + const isMethodDefinition = node.type === Syntax.MethodDefinition; - /** - * @param {string} runtime runtime - * @param {string | number} id the id of the runtime - * @returns {void} - */ - setRuntimeId(runtime, id) { - this._runtimeIds.set(runtime, id); - } + if (isMethodDefinition) { + previous = this.pushInnerMethodDefinition(true); + } + this.visit(node.value); + if (isMethodDefinition) { + this.popInnerMethodDefinition(previous); + } + } - /** - * @template T - * @param {Module} module the module - * @param {RuntimeSpecMap} hashes hashes data - * @param {RuntimeSpec} runtime the runtime - * @returns {T} hash - */ - _getModuleHashInfo(module, hashes, runtime) { - if (!hashes) { - throw new Error( - `Module ${module.identifier()} has no hash info for runtime ${runtimeToString( - runtime - )} (hashes not set at all)` - ); - } else if (runtime === undefined) { - const hashInfoItems = new Set(hashes.values()); - if (hashInfoItems.size !== 1) { - throw new Error( - `No unique hash info entry for unspecified runtime for ${module.identifier()} (existing runtimes: ${Array.from( - hashes.keys(), - r => runtimeToString(r) - ).join(", ")}). -Caller might not support runtime-dependent code generation (opt-out via optimization.usedExports: "global").` - ); - } - return first(hashInfoItems); - } else { - const hashInfo = hashes.get(runtime); - if (!hashInfo) { - throw new Error( - `Module ${module.identifier()} has no hash info for runtime ${runtimeToString( - runtime - )} (available runtimes ${Array.from( - hashes.keys(), - runtimeToString - ).join(", ")})` - ); - } - return hashInfo; - } - } + visitForIn(node) { + if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") { + this.scopeManager.__nestForScope(node); + } - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, if the module has hashes for this runtime - */ - hasModuleHashes(module, runtime) { - const cgm = this._getChunkGraphModule(module); - const hashes = cgm.hashes; - return hashes && hashes.has(runtime); - } + if (node.left.type === Syntax.VariableDeclaration) { + this.visit(node.left); + this.visitPattern(node.left.declarations[0].id, pattern => { + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true); + }); + } else { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {string} hash - */ - getModuleHash(module, runtime) { - const cgm = this._getChunkGraphModule(module); - const hashes = cgm.hashes; - return this._getModuleHashInfo(module, hashes, runtime).hash; - } + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false); + }); + } + this.visit(node.right); + this.visit(node.body); - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {string} hash - */ - getRenderedModuleHash(module, runtime) { - const cgm = this._getChunkGraphModule(module); - const hashes = cgm.hashes; - return this._getModuleHashInfo(module, hashes, runtime).renderedHash; - } + this.close(node); + } - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @param {string} hash the full hash - * @param {string} renderedHash the shortened hash for rendering - * @returns {void} - */ - setModuleHashes(module, runtime, hash, renderedHash) { - const cgm = this._getChunkGraphModule(module); - if (cgm.hashes === undefined) { - cgm.hashes = new RuntimeSpecMap(); - } - cgm.hashes.set(runtime, new ModuleHashInfo(hash, renderedHash)); - } + visitVariableDeclaration(variableTargetScope, type, node, index) { - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @param {Set} items runtime requirements to be added (ownership of this Set is given to ChunkGraph when transferOwnership not false) - * @param {boolean} transferOwnership true: transfer ownership of the items object, false: items is immutable and shared and won't be modified - * @returns {void} - */ - addModuleRuntimeRequirements( - module, - runtime, - items, - transferOwnership = true - ) { - const cgm = this._getChunkGraphModule(module); - const runtimeRequirementsMap = cgm.runtimeRequirements; - if (runtimeRequirementsMap === undefined) { - const map = new RuntimeSpecMap(); - // TODO avoid cloning item and track ownership instead - map.set(runtime, transferOwnership ? items : new Set(items)); - cgm.runtimeRequirements = map; - return; - } - runtimeRequirementsMap.update(runtime, runtimeRequirements => { - if (runtimeRequirements === undefined) { - return transferOwnership ? items : new Set(items); - } else if (!transferOwnership || runtimeRequirements.size >= items.size) { - for (const item of items) runtimeRequirements.add(item); - return runtimeRequirements; - } else { - for (const item of runtimeRequirements) items.add(item); - return items; - } - }); - } + const decl = node.declarations[index]; + const init = decl.init; - /** - * @param {Chunk} chunk the chunk - * @param {Set} items runtime requirements to be added (ownership of this Set is given to ChunkGraph) - * @returns {void} - */ - addChunkRuntimeRequirements(chunk, items) { - const cgc = this._getChunkGraphChunk(chunk); - const runtimeRequirements = cgc.runtimeRequirements; - if (runtimeRequirements === undefined) { - cgc.runtimeRequirements = items; - } else if (runtimeRequirements.size >= items.size) { - for (const item of items) runtimeRequirements.add(item); - } else { - for (const item of runtimeRequirements) items.add(item); - cgc.runtimeRequirements = items; - } - } + this.visitPattern(decl.id, { processRightHandNodes: true }, (pattern, info) => { + variableTargetScope.__define( + pattern, + new Definition( + type, + pattern, + decl, + node, + index, + node.kind + ) + ); - /** - * @param {Chunk} chunk the chunk - * @param {Iterable} items runtime requirements to be added - * @returns {void} - */ - addTreeRuntimeRequirements(chunk, items) { - const cgc = this._getChunkGraphChunk(chunk); - const runtimeRequirements = cgc.runtimeRequirementsInTree; - for (const item of items) runtimeRequirements.add(item); - } + this.referencingDefaultValue(pattern, info.assignments, null, true); + if (init) { + this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true); + } + }); + } - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {ReadonlySet} runtime requirements - */ - getModuleRuntimeRequirements(module, runtime) { - const cgm = this._getChunkGraphModule(module); - const runtimeRequirements = - cgm.runtimeRequirements && cgm.runtimeRequirements.get(runtime); - return runtimeRequirements === undefined ? EMPTY_SET : runtimeRequirements; - } + AssignmentExpression(node) { + if (PatternVisitor.isPattern(node.left)) { + if (node.operator === "=") { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; - /** - * @param {Chunk} chunk the chunk - * @returns {ReadonlySet} runtime requirements - */ - getChunkRuntimeRequirements(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - const runtimeRequirements = cgc.runtimeRequirements; - return runtimeRequirements === undefined ? EMPTY_SET : runtimeRequirements; - } + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false); + }); + } else { + this.currentScope().__referencing(node.left, Reference.RW, node.right); + } + } else { + this.visit(node.left); + } + this.visit(node.right); + } - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @param {boolean} withConnections include connections - * @returns {string} hash - */ - getModuleGraphHash(module, runtime, withConnections = true) { - const cgm = this._getChunkGraphModule(module); - return withConnections - ? this._getModuleGraphHashWithConnections(cgm, module, runtime) - : this._getModuleGraphHashBigInt(cgm, module, runtime).toString(16); - } + CatchClause(node) { + this.scopeManager.__nestCatchScope(node); - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @param {boolean} withConnections include connections - * @returns {bigint} hash - */ - getModuleGraphHashBigInt(module, runtime, withConnections = true) { - const cgm = this._getChunkGraphModule(module); - return withConnections - ? BigInt( - `0x${this._getModuleGraphHashWithConnections(cgm, module, runtime)}` - ) - : this._getModuleGraphHashBigInt(cgm, module, runtime); - } + this.visitPattern(node.param, { processRightHandNodes: true }, (pattern, info) => { + this.currentScope().__define(pattern, + new Definition( + Variable.CatchClause, + node.param, + node, + null, + null, + null + )); + this.referencingDefaultValue(pattern, info.assignments, null, true); + }); + this.visit(node.body); - /** - * @param {ChunkGraphModule} cgm the ChunkGraphModule - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {bigint} hash as big int - */ - _getModuleGraphHashBigInt(cgm, module, runtime) { - if (cgm.graphHashes === undefined) { - cgm.graphHashes = new RuntimeSpecMap(); - } - const graphHash = cgm.graphHashes.provide(runtime, () => { - const hash = createHash(this._hashFunction); - hash.update(`${cgm.id}${this.moduleGraph.isAsync(module)}`); - this.moduleGraph.getExportsInfo(module).updateHash(hash, runtime); - return BigInt(`0x${/** @type {string} */ (hash.digest("hex"))}`); - }); - return graphHash; - } + this.close(node); + } - /** - * @param {ChunkGraphModule} cgm the ChunkGraphModule - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {string} hash - */ - _getModuleGraphHashWithConnections(cgm, module, runtime) { - if (cgm.graphHashesWithConnections === undefined) { - cgm.graphHashesWithConnections = new RuntimeSpecMap(); - } - const activeStateToString = state => { - if (state === false) return "F"; - if (state === true) return "T"; - if (state === ModuleGraphConnection.TRANSITIVE_ONLY) return "O"; - throw new Error("Not implemented active state"); - }; - const strict = module.buildMeta && module.buildMeta.strictHarmonyModule; - return cgm.graphHashesWithConnections.provide(runtime, () => { - const graphHash = this._getModuleGraphHashBigInt( - cgm, - module, - runtime - ).toString(16); - const connections = this.moduleGraph.getOutgoingConnections(module); - /** @type {Set} */ - const activeNamespaceModules = new Set(); - /** @type {Map>} */ - const connectedModules = new Map(); - const processConnection = (connection, stateInfo) => { - const module = connection.module; - stateInfo += module.getExportsType(this.moduleGraph, strict); - // cspell:word Tnamespace - if (stateInfo === "Tnamespace") activeNamespaceModules.add(module); - else { - const oldModule = connectedModules.get(stateInfo); - if (oldModule === undefined) { - connectedModules.set(stateInfo, module); - } else if (oldModule instanceof Set) { - oldModule.add(module); - } else if (oldModule !== module) { - connectedModules.set(stateInfo, new Set([oldModule, module])); - } - } - }; - if (runtime === undefined || typeof runtime === "string") { - for (const connection of connections) { - const state = connection.getActiveState(runtime); - if (state === false) continue; - processConnection(connection, state === true ? "T" : "O"); - } - } else { - // cspell:word Tnamespace - for (const connection of connections) { - const states = new Set(); - let stateInfo = ""; - forEachRuntime( - runtime, - runtime => { - const state = connection.getActiveState(runtime); - states.add(state); - stateInfo += activeStateToString(state) + runtime; - }, - true - ); - if (states.size === 1) { - const state = first(states); - if (state === false) continue; - stateInfo = activeStateToString(state); - } - processConnection(connection, stateInfo); - } - } - // cspell:word Tnamespace - if (activeNamespaceModules.size === 0 && connectedModules.size === 0) - return graphHash; - const connectedModulesInOrder = - connectedModules.size > 1 - ? Array.from(connectedModules).sort(([a], [b]) => (a < b ? -1 : 1)) - : connectedModules; - const hash = createHash(this._hashFunction); - const addModuleToHash = module => { - hash.update( - this._getModuleGraphHashBigInt( - this._getChunkGraphModule(module), - module, - runtime - ).toString(16) - ); - }; - const addModulesToHash = modules => { - let xor = ZERO_BIG_INT; - for (const m of modules) { - xor = - xor ^ - this._getModuleGraphHashBigInt( - this._getChunkGraphModule(m), - m, - runtime - ); - } - hash.update(xor.toString(16)); - }; - if (activeNamespaceModules.size === 1) - addModuleToHash(activeNamespaceModules.values().next().value); - else if (activeNamespaceModules.size > 1) - addModulesToHash(activeNamespaceModules); - for (const [stateInfo, modules] of connectedModulesInOrder) { - hash.update(stateInfo); - if (modules instanceof Set) { - addModulesToHash(modules); - } else { - addModuleToHash(modules); - } - } - hash.update(graphHash); - return /** @type {string} */ (hash.digest("hex")); - }); - } + Program(node) { + this.scopeManager.__nestGlobalScope(node); - /** - * @param {Chunk} chunk the chunk - * @returns {ReadonlySet} runtime requirements - */ - getTreeRuntimeRequirements(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.runtimeRequirementsInTree; - } + if (this.scopeManager.__isNodejsScope()) { - // 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 {ChunkGraph} the chunk graph - */ - static getChunkGraphForModule(module, deprecateMessage, deprecationCode) { - const fn = deprecateGetChunkGraphForModuleMap.get(deprecateMessage); - if (fn) return fn(module); - const newFn = util.deprecate( - /** - * @param {Module} module the module - * @returns {ChunkGraph} the chunk graph - */ - module => { - const chunkGraph = chunkGraphForModuleMap.get(module); - if (!chunkGraph) - throw new Error( - deprecateMessage + - ": There was no ChunkGraph assigned to the Module for backward-compat (Use the new API)" - ); - return chunkGraph; - }, - deprecateMessage + ": Use new ChunkGraph API", - deprecationCode - ); - deprecateGetChunkGraphForModuleMap.set(deprecateMessage, newFn); - return newFn(module); - } + // Force strictness of GlobalScope to false when using node.js scope. + this.currentScope().isStrict = false; + this.scopeManager.__nestFunctionScope(node, false); + } - // TODO remove in webpack 6 - /** - * @param {Module} module the module - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {void} - */ - static setChunkGraphForModule(module, chunkGraph) { - chunkGraphForModuleMap.set(module, chunkGraph); - } + if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { + this.scopeManager.__nestModuleScope(node); + } - // TODO remove in webpack 6 - /** - * @param {Module} module the module - * @returns {void} - */ - static clearChunkGraphForModule(module) { - chunkGraphForModuleMap.delete(module); - } + if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) { + this.currentScope().isStrict = true; + } - // TODO remove in webpack 6 - /** - * @param {Chunk} chunk the chunk - * @param {string} deprecateMessage message for the deprecation message - * @param {string} deprecationCode code for the deprecation - * @returns {ChunkGraph} the chunk graph - */ - static getChunkGraphForChunk(chunk, deprecateMessage, deprecationCode) { - const fn = deprecateGetChunkGraphForChunkMap.get(deprecateMessage); - if (fn) return fn(chunk); - const newFn = util.deprecate( - /** - * @param {Chunk} chunk the chunk - * @returns {ChunkGraph} the chunk graph - */ - chunk => { - const chunkGraph = chunkGraphForChunkMap.get(chunk); - if (!chunkGraph) - throw new Error( - deprecateMessage + - "There was no ChunkGraph assigned to the Chunk for backward-compat (Use the new API)" - ); - return chunkGraph; - }, - deprecateMessage + ": Use new ChunkGraph API", - deprecationCode - ); - deprecateGetChunkGraphForChunkMap.set(deprecateMessage, newFn); - return newFn(chunk); - } + this.visitChildren(node); + this.close(node); + } - // TODO remove in webpack 6 - /** - * @param {Chunk} chunk the chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {void} - */ - static setChunkGraphForChunk(chunk, chunkGraph) { - chunkGraphForChunkMap.set(chunk, chunkGraph); - } + Identifier(node) { + this.currentScope().__referencing(node); + } - // TODO remove in webpack 6 - /** - * @param {Chunk} chunk the chunk - * @returns {void} - */ - static clearChunkGraphForChunk(chunk) { - chunkGraphForChunkMap.delete(chunk); - } -} + UpdateExpression(node) { + if (PatternVisitor.isPattern(node.argument)) { + this.currentScope().__referencing(node.argument, Reference.RW, null); + } else { + this.visitChildren(node); + } + } -// TODO remove in webpack 6 -/** @type {WeakMap} */ -const chunkGraphForModuleMap = new WeakMap(); + MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } -// TODO remove in webpack 6 -/** @type {WeakMap} */ -const chunkGraphForChunkMap = new WeakMap(); + Property(node) { + this.visitProperty(node); + } -// TODO remove in webpack 6 -/** @type {Map ChunkGraph>} */ -const deprecateGetChunkGraphForModuleMap = new Map(); + MethodDefinition(node) { + this.visitProperty(node); + } -// TODO remove in webpack 6 -/** @type {Map ChunkGraph>} */ -const deprecateGetChunkGraphForChunkMap = new Map(); + BreakStatement() {} // eslint-disable-line class-methods-use-this -module.exports = ChunkGraph; + ContinueStatement() {} // eslint-disable-line class-methods-use-this + LabeledStatement(node) { + this.visit(node.body); + } -/***/ }), + ForStatement(node) { -/***/ 15626: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Create ForStatement declaration. + // NOTE: In ES6, ForStatement dynamically generates + // per iteration environment. However, escope is + // a static analyzer, we only generate one scope for ForStatement. + if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") { + this.scopeManager.__nestForScope(node); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.visitChildren(node); + this.close(node); + } + ClassExpression(node) { + this.visitClass(node); + } -const util = __webpack_require__(73837); -const SortableSet = __webpack_require__(13098); -const { - compareLocations, - compareChunks, - compareIterables -} = __webpack_require__(29579); + ClassDeclaration(node) { + this.visitClass(node); + } -/** @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 */ + CallExpression(node) { -/** @typedef {{id: number}} HasId */ -/** @typedef {{module: Module, loc: DependencyLocation, request: string}} OriginRecord */ + // Check this is direct call to eval + if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") { -/** - * @typedef {Object} RawChunkGroupOptions - * @property {number=} preloadOrder - * @property {number=} prefetchOrder - */ + // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and + // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. + this.currentScope().variableScope.__detectEval(); + } + this.visitChildren(node); + } -/** @typedef {RawChunkGroupOptions & { name?: string }} ChunkGroupOptions */ + BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } -let debugId = 5000; + this.visitChildren(node); -/** - * @template T - * @param {SortableSet} set set to convert to array. - * @returns {T[]} the array format of existing set - */ -const getArray = set => Array.from(set); + this.close(node); + } -/** - * 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; -}; + ThisExpression() { + this.currentScope().variableScope.__detectThis(); + } -/** - * @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); -}; + WithStatement(node) { + this.visit(node.object); -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} */ - this._children = new SortableSet(undefined, sortById); - /** @type {SortableSet} */ - this._parents = new SortableSet(undefined, sortById); - /** @type {SortableSet} */ - 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} */ - this._modulePreOrderIndices = new Map(); - /** Indices in bottom-up order */ - /** @private @type {Map} */ - this._modulePostOrderIndices = new Map(); - /** @type {number} */ - this.index = undefined; - } + // Then nest scope for WithStatement. + this.scopeManager.__nestWithScope(node); - /** - * 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}` - ); - } - } - } - } + this.visit(node.body); - /** - * returns the name of current ChunkGroup - * @returns {string|undefined} returns the ChunkGroup name - */ - get name() { - return this.options.name; - } + this.close(node); + } - /** - * sets a new name for current ChunkGroup - * @param {string} value the new name for ChunkGroup - * @returns {void} - */ - set name(value) { - this.options.name = value; - } + VariableDeclaration(node) { + const variableTargetScope = (node.kind === "var") ? this.currentScope().variableScope : this.currentScope(); - /* 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("+"); - } + for (let i = 0, iz = node.declarations.length; i < iz; ++i) { + const decl = node.declarations[i]; - /** - * 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("+"); - } + this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i); + if (decl.init) { + this.visit(decl.init); + } + } + } - /** - * 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; - } + // sec 13.11.8 + SwitchStatement(node) { + this.visit(node.discriminant); - /** - * 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; - } + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestSwitchScope(node); + } - /** - * 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; - } + for (let i = 0, iz = node.cases.length; i < iz; ++i) { + this.visit(node.cases[i]); + } - /** - * @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; - } - } + this.close(node); + } - /** - * @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; - } + FunctionDeclaration(node) { + this.visitFunction(node); + } - /** - * @returns {boolean} true, when this chunk group will be loaded on initial page load - */ - isInitial() { - return false; - } + FunctionExpression(node) { + this.visitFunction(node); + } - /** - * @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; - } + ForOfStatement(node) { + this.visitForIn(node); + } - /** - * @returns {ChunkGroup[]} returns the children of this group - */ - getChildren() { - return this._children.getFromCache(getArray); - } + ForInStatement(node) { + this.visitForIn(node); + } - getNumberOfChildren() { - return this._children.size; - } + ArrowFunctionExpression(node) { + this.visitFunction(node); + } - get childrenIterable() { - return this._children; - } + ImportDeclaration(node) { + assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context."); - /** - * @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; - } + const importer = new Importer(node, this); - this._children.delete(group); - group.removeParent(this); - return true; - } + importer.visit(node); + } - /** - * @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; - } + visitExportDeclaration(node) { + if (node.source) { + return; + } + if (node.declaration) { + this.visit(node.declaration); + return; + } - /** - * @returns {ChunkGroup[]} returns the parents of this group - */ - getParents() { - return this._parents.getFromCache(getArray); - } + this.visitChildren(node); + } - getNumberOfParents() { - return this._parents.size; - } + // TODO: ExportDeclaration doesn't exist. for bc? + ExportDeclaration(node) { + this.visitExportDeclaration(node); + } - /** - * @param {ChunkGroup} parent the parent group - * @returns {boolean} returns true if the parent group contains this group - */ - hasParent(parent) { - return this._parents.has(parent); - } + ExportAllDeclaration(node) { + this.visitExportDeclaration(node); + } - get parentsIterable() { - return this._parents; - } + ExportDefaultDeclaration(node) { + this.visitExportDeclaration(node); + } - /** - * @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; - } + ExportNamedDeclaration(node) { + this.visitExportDeclaration(node); + } - /** - * @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; - } + ExportSpecifier(node) { - get asyncEntrypointsIterable() { - return this._asyncEntrypoints; - } + // TODO: `node.id` doesn't exist. for bc? + const local = (node.id || node.local); - /** - * @returns {Array} an array containing the blocks - */ - getBlocks() { - return this._blocks.getFromCache(getArray); - } + this.visit(local); + } - getNumberOfBlocks() { - return this._blocks.size; - } + MetaProperty() { // eslint-disable-line class-methods-use-this - hasBlock(block) { - return this._blocks.has(block); - } + // do nothing. + } +} - /** - * @returns {Iterable} blocks - */ - get blocksIterable() { - return this._blocks; - } +module.exports = Referencer; - /** - * @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; - } +/* vim: set sw=4 ts=4 et tw=80 : */ - /** - * @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); - } - } +/***/ 96988: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return Array.from(files); - } +"use strict"; +/* + Copyright (C) 2015 Yusuke Suzuki - /** - * @returns {void} - */ - remove() { - // cleanup parents - for (const parentChunkGroup of this._parents) { - // remove this chunk from its parents - parentChunkGroup._children.delete(this); + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - // 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); - } - } + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - /** - * 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); - } + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ - // remove chunks - for (const chunk of this.chunks) { - chunk.removeGroup(this); - } - } - sortItems() { - this.origins.sort(sortOrigin); - } +/* eslint-disable no-underscore-dangle */ - /** - * 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 - ); - } +const Scope = __webpack_require__(16313); +const assert = __webpack_require__(39491); - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {Record} mapping from children type to ordered list of ChunkGroups - */ - getChildrenByOrders(moduleGraph, chunkGraph) { - /** @type {Map} */ - 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} */ - 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; - } +const GlobalScope = Scope.GlobalScope; +const CatchScope = Scope.CatchScope; +const WithScope = Scope.WithScope; +const ModuleScope = Scope.ModuleScope; +const ClassScope = Scope.ClassScope; +const SwitchScope = Scope.SwitchScope; +const FunctionScope = Scope.FunctionScope; +const ForScope = Scope.ForScope; +const FunctionExpressionNameScope = Scope.FunctionExpressionNameScope; +const BlockScope = Scope.BlockScope; - /** - * 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); - } +/** + * @class ScopeManager + */ +class ScopeManager { + constructor(options) { + this.scopes = []; + this.globalScope = null; + this.__nodeToScope = new WeakMap(); + this.__currentScope = null; + this.__options = options; + this.__declaredVariables = new WeakMap(); + } - /** - * 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); - } + __useDirective() { + return this.__options.directive; + } - /** - * 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); - } + __isOptimistic() { + return this.__options.optimistic; + } - /** - * 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); - } + __ignoreEval() { + return this.__options.ignoreEval; + } - /* 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}` - ); - } - } - } -} + __isNodejsScope() { + return this.__options.nodejsScope; + } -ChunkGroup.prototype.getModuleIndex = util.deprecate( - ChunkGroup.prototype.getModulePreOrderIndex, - "ChunkGroup.getModuleIndex was renamed to getModulePreOrderIndex", - "DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX" -); + isModule() { + return this.__options.sourceType === "module"; + } -ChunkGroup.prototype.getModuleIndex2 = util.deprecate( - ChunkGroup.prototype.getModulePostOrderIndex, - "ChunkGroup.getModuleIndex2 was renamed to getModulePostOrderIndex", - "DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX_2" -); + isImpliedStrict() { + return this.__options.impliedStrict; + } -module.exports = ChunkGroup; + isStrictModeSupported() { + return this.__options.ecmaVersion >= 5; + } + // Returns appropriate scope for this node. + __get(node) { + return this.__nodeToScope.get(node); + } -/***/ }), + /** + * Get variables that are declared by the node. + * + * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`. + * If the node declares nothing, this method returns an empty array. + * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details. + * + * @param {Espree.Node} node - a node to get. + * @returns {Variable[]} variables that declared by the node. + */ + getDeclaredVariables(node) { + return this.__declaredVariables.get(node) || []; + } -/***/ 918: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * acquire scope from node. + * @method ScopeManager#acquire + * @param {Espree.Node} node - node for the acquired scope. + * @param {boolean=} inner - look up the most inner scope, default value is false. + * @returns {Scope?} Scope from node + */ + acquire(node, inner) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * predicate + * @param {Scope} testScope - scope to test + * @returns {boolean} predicate + */ + function predicate(testScope) { + if (testScope.type === "function" && testScope.functionExpressionScope) { + return false; + } + return true; + } + const scopes = this.__get(node); + if (!scopes || scopes.length === 0) { + return null; + } -const WebpackError = __webpack_require__(53799); + // Heuristic selection from all scopes. + // If you would like to get all scopes, please use ScopeManager#acquireAll. + if (scopes.length === 1) { + return scopes[0]; + } -/** @typedef {import("./Chunk")} Chunk */ + if (inner) { + for (let i = scopes.length - 1; i >= 0; --i) { + const scope = scopes[i]; -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(); + if (predicate(scope)) { + return scope; + } + } + } else { + for (let i = 0, iz = scopes.length; i < iz; ++i) { + const scope = scopes[i]; - this.name = "ChunkRenderError"; - this.error = error; - this.message = error.message; - this.details = error.stack; - this.file = file; - this.chunk = chunk; - } -} + if (predicate(scope)) { + return scope; + } + } + } -module.exports = ChunkRenderError; + return null; + } + /** + * acquire all scopes from node. + * @method ScopeManager#acquireAll + * @param {Espree.Node} node - node for the acquired scope. + * @returns {Scopes?} Scope array + */ + acquireAll(node) { + return this.__get(node); + } -/***/ }), + /** + * release the node. + * @method ScopeManager#release + * @param {Espree.Node} node - releasing node. + * @param {boolean=} inner - look up the most inner scope, default value is false. + * @returns {Scope?} upper scope for the node. + */ + release(node, inner) { + const scopes = this.__get(node); -/***/ 46341: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (scopes && scopes.length) { + const scope = scopes[0].upper; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (!scope) { + return null; + } + return this.acquire(scope.block, inner); + } + return null; + } + attach() { } // eslint-disable-line class-methods-use-this + detach() { } // eslint-disable-line class-methods-use-this -const util = __webpack_require__(73837); -const memoize = __webpack_require__(78676); + __nestScope(scope) { + if (scope instanceof GlobalScope) { + assert(this.__currentScope === null); + this.globalScope = scope; + } + this.__currentScope = scope; + return scope; + } -/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */ -/** @typedef {import("./Compilation")} Compilation */ + __nestGlobalScope(node) { + return this.__nestScope(new GlobalScope(this, node)); + } -const getJavascriptModulesPlugin = memoize(() => - __webpack_require__(89464) -); + __nestBlockScope(node) { + return this.__nestScope(new BlockScope(this, this.__currentScope, node)); + } -// 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" - ) - } - }); - } + __nestFunctionScope(node, isMethodDefinition) { + return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + } + + __nestForScope(node) { + return this.__nestScope(new ForScope(this, this.__currentScope, node)); + } + + __nestCatchScope(node) { + return this.__nestScope(new CatchScope(this, this.__currentScope, node)); + } + + __nestWithScope(node) { + return this.__nestScope(new WithScope(this, this.__currentScope, node)); + } + + __nestClassScope(node) { + return this.__nestScope(new ClassScope(this, this.__currentScope, node)); + } + + __nestSwitchScope(node) { + return this.__nestScope(new SwitchScope(this, this.__currentScope, node)); + } + + __nestModuleScope(node) { + return this.__nestScope(new ModuleScope(this, this.__currentScope, node)); + } + + __nestFunctionExpressionNameScope(node) { + return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node)); + } + + __isES6() { + return this.__options.ecmaVersion >= 6; + } } -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 = ScopeManager; -module.exports = ChunkTemplate; +/* vim: set sw=4 ts=4 et tw=80 : */ /***/ }), -/***/ 31085: +/***/ 16313: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov -*/ + Copyright (C) 2015 Yusuke Suzuki + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. -const asyncLib = __webpack_require__(78175); -const { SyncBailHook } = __webpack_require__(6967); -const Compilation = __webpack_require__(85720); -const createSchemaValidation = __webpack_require__(32540); -const { join } = __webpack_require__(17139); -const processAsyncTree = __webpack_require__(42791); + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ -/** @typedef {import("../declarations/WebpackOptions").CleanOptions} CleanOptions */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./logging/Logger").Logger} Logger */ -/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ -/** @typedef {import("./util/fs").StatsCallback} StatsCallback */ -/** @typedef {(function(string):boolean)|RegExp} IgnoreItem */ -/** @typedef {function(IgnoreItem): void} AddToIgnoreCallback */ +/* eslint-disable no-underscore-dangle */ +/* eslint-disable no-undefined */ + +const Syntax = (__webpack_require__(18350).Syntax); + +const Reference = __webpack_require__(64945); +const Variable = __webpack_require__(82971); +const Definition = (__webpack_require__(70665).Definition); +const assert = __webpack_require__(39491); /** - * @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 + * Test if scope is struct + * @param {Scope} scope - scope + * @param {Block} block - block + * @param {boolean} isMethodDefinition - is method definition + * @param {boolean} useDirective - use directive + * @returns {boolean} is strict scope */ +function isStrictScope(scope, block, isMethodDefinition, useDirective) { + let body; -const validate = createSchemaValidation( - undefined, - () => { - const { definitions } = __webpack_require__(73342); - return { - definitions, - oneOf: [{ $ref: "#/definitions/CleanOptions" }] - }; - }, - { - name: "Clean Plugin", - baseDataPath: "options" - } -); + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } + + if (isMethodDefinition) { + return true; + } + + if (scope.type === "class" || scope.type === "module") { + return true; + } + + if (scope.type === "block" || scope.type === "switch") { + return false; + } + + if (scope.type === "function") { + if (block.type === Syntax.ArrowFunctionExpression && block.body.type !== Syntax.BlockStatement) { + return false; + } + + if (block.type === Syntax.Program) { + body = block; + } else { + body = block.body; + } + + if (!body) { + return false; + } + } else if (scope.type === "global") { + body = block; + } else { + return false; + } + + // Search 'use strict' directive. + if (useDirective) { + for (let i = 0, iz = body.body.length; i < iz; ++i) { + const stmt = body.body[i]; + + if (stmt.type !== Syntax.DirectiveStatement) { + break; + } + if (stmt.raw === "\"use strict\"" || stmt.raw === "'use strict'") { + return true; + } + } + } else { + for (let i = 0, iz = body.body.length; i < iz; ++i) { + const stmt = body.body[i]; + + if (stmt.type !== Syntax.ExpressionStatement) { + break; + } + const expr = stmt.expression; + + if (expr.type !== Syntax.Literal || typeof expr.value !== "string") { + break; + } + if (expr.raw !== null && expr.raw !== undefined) { + if (expr.raw === "\"use strict\"" || expr.raw === "'use strict'") { + return true; + } + } else { + if (expr.value === "use strict") { + return true; + } + } + } + } + return false; +} /** - * @param {OutputFileSystem} fs filesystem - * @param {string} outputPath output path - * @param {Set} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator) - * @param {function((Error | null)=, Set=): void} callback returns the filenames of the assets that shouldn't be there + * Register scope + * @param {ScopeManager} scopeManager - scope manager + * @param {Scope} scope - scope * @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); +function registerScope(scopeManager, scope) { + scopeManager.scopes.push(scope); - callback(null, diff); - } - ); -}; + const scopes = scopeManager.__nodeToScope.get(scope.block); -/** - * @param {Set} currentAssets assets list - * @param {Set} oldAssets old assets list - * @returns {Set} diff - */ -const getDiffToOldAssets = (currentAssets, oldAssets) => { - const diff = new Set(); - for (const asset of oldAssets) { - if (!currentAssets.has(asset)) diff.add(asset); - } - return diff; -}; + if (scopes) { + scopes.push(scope); + } else { + scopeManager.__nodeToScope.set(scope.block, [scope]); + } +} /** - * @param {OutputFileSystem} fs filesystem - * @param {string} filename path to file - * @param {StatsCallback} callback callback for provided filename - * @returns {void} + * Should be statically + * @param {Object} def - def + * @returns {boolean} should be statically */ -const doStat = (fs, filename, callback) => { - if ("lstat" in fs) { - fs.lstat(filename, callback); - } else { - fs.stat(filename, callback); - } -}; +function shouldBeStatically(def) { + return ( + (def.type === Variable.ClassName) || + (def.type === Variable.Variable && def.parent.kind !== "var") + ); +} /** - * @param {OutputFileSystem} fs filesystem - * @param {string} outputPath output path - * @param {boolean} dry only log instead of fs modification - * @param {Logger} logger logger - * @param {Set} 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} + * @class Scope */ -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); - } - doStat(fs, 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 - ); -}; +class Scope { + constructor(scopeManager, type, upperScope, block, isMethodDefinition) { -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); + /** + * One of 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'. + * @member {String} Scope#type + */ + this.type = type; -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(options); - this.options = { dry: false, ...options }; - } + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const { dry, keep } = this.options; + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints */ + this.taints = new Map(); - const keepFn = - typeof keep === "function" - ? keep - : typeof keep === "string" - ? path => path.startsWith(keep) - : typeof keep === "object" && keep.test - ? path => keep.test(path) - : () => false; + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its parent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === "global" || this.type === "with"; - // 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; + /** + * A reference to the scope-defining syntax node. + * @member {espree.Node} Scope#block + */ + this.block = block; - 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; + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; - if (!fs.readdir) { - return callback( - new Error( - "CleanPlugin: Output filesystem doesn't support listing directories (readdir)" - ) - ); - } + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; - 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); - } + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; - const outputPath = compilation.getPath(compiler.outputPath, {}); + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = + (this.type === "global" || this.type === "function" || this.type === "module") ? this : upperScope.variableScope; - const isKept = path => { - const result = hooks.keep.call(path); - if (result !== undefined) return result; - return keepFn(path); - }; + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = false; - 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); - }); - }; + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; - if (oldAssets) { - diffCallback(null, getDiffToOldAssets(currentAssets, oldAssets)); - } else { - getDiffToFs(fs, outputPath, currentAssets, diffCallback); - } - } - ); - } -} + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; -module.exports = CleanPlugin; + this.__left = []; + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = upperScope; -/***/ }), + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective()); -/***/ 2102: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (this.upper) { + this.upper.childScopes.push(this); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.__declaredVariables = scopeManager.__declaredVariables; + registerScope(scopeManager, this); + } + __shouldStaticallyClose(scopeManager) { + return (!this.dynamic || scopeManager.__isOptimistic()); + } -const WebpackError = __webpack_require__(53799); + __shouldStaticallyCloseForGlobal(ref) { -/** @typedef {import("./Module")} Module */ + // On global scope, let/const/class declarations should be resolved statically. + const name = ref.identifier.name; -class CodeGenerationError extends WebpackError { - /** - * Create a new CodeGenerationError - * @param {Module} module related module - * @param {Error} error Original error - */ - constructor(module, error) { - super(); + if (!this.set.has(name)) { + return false; + } - this.name = "CodeGenerationError"; - this.error = error; - this.message = error.message; - this.details = error.stack; - this.module = module; - } -} + const variable = this.set.get(name); + const defs = variable.defs; -module.exports = CodeGenerationError; + return defs.length > 0 && defs.every(shouldBeStatically); + } + __staticCloseRef(ref) { + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } + } -/***/ }), + __dynamicCloseRef(ref) { -/***/ 71426: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // notify all names are through to global + let current = this; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + do { + current.through.push(ref); + current = current.upper; + } while (current); + } + __globalCloseRef(ref) { + // let/const/class declarations should be resolved statically. + // others should be resolved dynamically. + if (this.__shouldStaticallyCloseForGlobal(ref)) { + this.__staticCloseRef(ref); + } else { + this.__dynamicCloseRef(ref); + } + } -const { provide } = __webpack_require__(82482); -const { first } = __webpack_require__(93347); -const createHash = __webpack_require__(49835); -const { runtimeToString, RuntimeSpecMap } = __webpack_require__(17156); + __close(scopeManager) { + let closeRef; -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {typeof import("./util/Hash")} Hash */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + if (this.__shouldStaticallyClose(scopeManager)) { + closeRef = this.__staticCloseRef; + } else if (this.type !== "global") { + closeRef = this.__dynamicCloseRef; + } else { + closeRef = this.__globalCloseRef; + } -class CodeGenerationResults { - /** - * @param {string | Hash} hashFunction the hash function to use - */ - constructor(hashFunction = "md4") { - /** @type {Map>} */ - this.map = new Map(); - this._hashFunction = hashFunction; - } + // Try Resolving all references in this scope. + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; - /** - * @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; - } + closeRef.call(this, ref); + } + this.__left = null; - /** - * @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; - } - } + return this.upper; + } - /** - * @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); - } + // To override by function scopes. + // References in default parameters isn't resolved to variables which are in their function body. + __isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars + return true; + } - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime runtime(s) - * @returns {ReadonlySet} runtime requirements - */ - getRuntimeRequirements(module, runtime) { - return this.get(module, runtime).runtimeRequirements; - } + __resolve(ref) { + const name = ref.identifier.name; - /** - * @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); - } + if (!this.set.has(name)) { + return false; + } + const variable = this.set.get(name); - /** - * @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(this._hashFunction); - 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"))); - } + if (!this.__isValidResolution(ref, variable)) { + return false; + } + variable.references.push(ref); + variable.stack = variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; - /** - * @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); - } -} + return true; + } -module.exports = CodeGenerationResults; + __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.__left.push(ref); + } + this.through.push(ref); + } + __addDeclaredVariablesOfNode(variable, node) { + if (node === null || node === undefined) { + return; + } -/***/ }), + let variables = this.__declaredVariables.get(node); -/***/ 98427: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (variables === null || variables === undefined) { + variables = []; + this.__declaredVariables.set(node, variables); + } + if (variables.indexOf(variable) === -1) { + variables.push(variable); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + __defineGeneric(name, set, variables, node, def) { + let variable; + variable = set.get(name); + if (!variable) { + variable = new Variable(name, this); + set.set(name, variable); + variables.push(variable); + } + if (def) { + variable.defs.push(def); + this.__addDeclaredVariablesOfNode(variable, def.node); + this.__addDeclaredVariablesOfNode(variable, def.parent); + } + if (node) { + variable.identifiers.push(node); + } + } -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); + __define(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.set, + this.variables, + node, + def + ); + } + } -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) { -class CommentCompilationWarning extends WebpackError { - /** - * - * @param {string} message warning message - * @param {DependencyLocation} loc affected lines of code - */ - constructor(message, loc) { - super(message); + // because Array element may be null + if (!node || node.type !== Syntax.Identifier) { + return; + } - this.name = "CommentCompilationWarning"; + // Specially handle like `this`. + if (node.name === "super") { + return; + } - this.loc = loc; - } -} + const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init); -makeSerializable( - CommentCompilationWarning, - "webpack/lib/CommentCompilationWarning" -); + this.references.push(ref); + this.__left.push(ref); + } -module.exports = CommentCompilationWarning; + __detectEval() { + let current = this; + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + } -/***/ }), + __detectThis() { + this.thisFound = true; + } -/***/ 94258: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + __isClosed() { + return this.__left === null; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * returns resolved {Reference} + * @method Scope#resolve + * @param {Espree.Identifier} ident - identifier to be resolved. + * @returns {Reference} reference + */ + resolve(ident) { + let ref, i, iz; + assert(this.__isClosed(), "Scope should be closed."); + assert(ident.type === Syntax.Identifier, "Target should be identifier."); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } + } + return null; + } + /** + * returns this scope is static + * @method Scope#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.dynamic; + } -const ConstDependency = __webpack_require__(76911); + /** + * returns this scope has materialized arguments + * @method Scope#isArgumentsMaterialized + * @returns {boolean} arguemnts materialized + */ + isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this + return true; + } -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ + /** + * returns this scope has materialized `this` reference + * @method Scope#isThisMaterialized + * @returns {boolean} this materialized + */ + isThisMaterialized() { // eslint-disable-line class-methods-use-this + return true; + } -const nestedWebpackRequireTag = Symbol("nested __webpack_require__"); + isUsedName(name) { + if (this.set.has(name)) { + return true; + } + for (let i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; + } + } + return false; + } +} -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() - ); +class GlobalScope extends Scope { + constructor(scopeManager, block) { + super(scopeManager, "global", null, block, false); + this.implicit = { + set: new Map(), + variables: [], - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("CompatibilityPlugin", (parser, parserOptions) => { - if ( - parserOptions.browserify !== undefined && - !parserOptions.browserify - ) - return; + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + * @member {Reference[]} Scope#implicit#left + */ + left: [] + }; + } - 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; - }); - }); + __close(scopeManager) { + const implicit = []; - /** - * @param {JavascriptParser} parser the parser - * @returns {void} - */ - const handler = parser => { - // Handle nested requires - 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; - }); + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; - // Handle hashbang - parser.hooks.program.tap( - "CompatibilityPlugin", - (program, comments) => { - if (comments.length === 0) return; - const c = comments[0]; - if (c.type === "Line" && c.range[0] === 0) { - if (parser.state.source.slice(0, 2).toString() !== "#!") return; - // this is a hashbang comment - const dep = new ConstDependency("//", 0); - dep.loc = c.loc; - parser.state.module.addPresentationalDependency(dep); - } - } - ); - }; + if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + implicit.push(ref.__maybeImplicitGlobal); + } + } - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("CompatibilityPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("CompatibilityPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("CompatibilityPlugin", handler); - } - ); - } -} -module.exports = CompatibilityPlugin; + // create an implicit global variable from assignment expression + for (let i = 0, iz = implicit.length; i < iz; ++i) { + const info = implicit[i]; + this.__defineImplicit(info.pattern, + new Definition( + Variable.ImplicitGlobalVariable, + info.pattern, + info.node, + null, + null, + null + )); -/***/ }), + } -/***/ 85720: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.implicit.left = this.__left; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return super.__close(scopeManager); + } + __defineImplicit(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.implicit.set, + this.implicit.variables, + node, + def + ); + } + } +} +class ModuleScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "module", upperScope, block, false); + } +} -const asyncLib = __webpack_require__(78175); -const { - HookMap, - SyncHook, - SyncBailHook, - SyncWaterfallHook, - AsyncSeriesHook, - AsyncSeriesBailHook, - AsyncParallelHook -} = __webpack_require__(6967); -const util = __webpack_require__(73837); -const { CachedSource } = __webpack_require__(51255); -const { MultiItemCache } = __webpack_require__(55392); -const Chunk = __webpack_require__(39385); -const ChunkGraph = __webpack_require__(64971); -const ChunkGroup = __webpack_require__(15626); -const ChunkRenderError = __webpack_require__(918); -const ChunkTemplate = __webpack_require__(46341); -const CodeGenerationError = __webpack_require__(2102); -const CodeGenerationResults = __webpack_require__(71426); -const Dependency = __webpack_require__(54912); -const DependencyTemplates = __webpack_require__(9163); -const Entrypoint = __webpack_require__(13795); -const ErrorHelpers = __webpack_require__(59985); -const FileSystemInfo = __webpack_require__(79453); -const { - connectChunkGroupAndChunk, - connectChunkGroupParentAndChild -} = __webpack_require__(37234); -const { - makeWebpackError, - tryRunOrWebpackError -} = __webpack_require__(11351); -const MainTemplate = __webpack_require__(12856); -const Module = __webpack_require__(73208); -const ModuleDependencyError = __webpack_require__(67409); -const ModuleDependencyWarning = __webpack_require__(29656); -const ModuleGraph = __webpack_require__(99988); -const ModuleNotFoundError = __webpack_require__(32882); -const ModuleProfile = __webpack_require__(36418); -const ModuleRestoreError = __webpack_require__(94560); -const ModuleStoreError = __webpack_require__(59001); -const ModuleTemplate = __webpack_require__(62677); -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeTemplate = __webpack_require__(18777); -const Stats = __webpack_require__(31743); -const WebpackError = __webpack_require__(53799); -const buildChunkGraph = __webpack_require__(79233); -const BuildCycleError = __webpack_require__(22273); -const { Logger, LogType } = __webpack_require__(32597); -const StatsFactory = __webpack_require__(92629); -const StatsPrinter = __webpack_require__(30198); -const { equals: arrayEquals } = __webpack_require__(84953); -const AsyncQueue = __webpack_require__(12260); -const LazySet = __webpack_require__(38938); -const { provide } = __webpack_require__(82482); -const WeakTupleMap = __webpack_require__(28745); -const { cachedCleverMerge } = __webpack_require__(60839); -const { - compareLocations, - concatComparators, - compareSelect, - compareIds, - compareStringsNumeric, - compareModulesByIdentifier -} = __webpack_require__(29579); -const createHash = __webpack_require__(49835); -const { - arrayToSetDeprecation, - soonFrozenObjectDeprecation, - createFakeHook -} = __webpack_require__(64518); -const processAsyncTree = __webpack_require__(42791); -const { getRuntimeKey } = __webpack_require__(17156); -const { isSourceEqual } = __webpack_require__(41245); +class FunctionExpressionNameScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "function-expression-name", upperScope, block, false); + this.__define(block.id, + new Definition( + Variable.FunctionName, + block.id, + block, + null, + null, + null + )); + this.functionExpressionScope = true; + } +} -/** @template T @typedef {import("tapable").AsArray} AsArray */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ -/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ -/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ -/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ -/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("./Cache")} Cache */ -/** @typedef {import("./CacheFacade")} CacheFacade */ -/** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Compiler").CompilationParams} CompilationParams */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ -/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ -/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("./ModuleFactory")} ModuleFactory */ -/** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */ -/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./RuntimeModule")} RuntimeModule */ -/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry */ -/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */ -/** @typedef {import("./util/Hash")} Hash */ -/** @template T @typedef {import("./util/deprecation").FakeHook} FakeHook */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +class CatchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "catch", upperScope, block, false); + } +} -/** - * @callback Callback - * @param {(WebpackError | null)=} err - * @returns {void} - */ +class WithScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "with", upperScope, block, false); + } -/** - * @callback ModuleCallback - * @param {(WebpackError | null)=} err - * @param {Module=} result - * @returns {void} - */ + __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + return super.__close(scopeManager); + } -/** - * @callback ModuleFactoryResultCallback - * @param {(WebpackError | null)=} err - * @param {ModuleFactoryResult=} result - * @returns {void} - */ + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; -/** - * @callback ModuleOrFactoryResultCallback - * @param {(WebpackError | null)=} err - * @param {Module | ModuleFactoryResult=} result - * @returns {void} - */ + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + this.__left = null; -/** - * @callback ExecuteModuleCallback - * @param {(WebpackError | null)=} err - * @param {ExecuteModuleResult=} result - * @returns {void} - */ + return this.upper; + } +} -/** - * @callback DepBlockVarDependenciesCallback - * @param {Dependency} dependency - * @returns {any} - */ +class BlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "block", upperScope, block, false); + } +} -/** @typedef {new (...args: any[]) => Dependency} DepConstructor */ -/** @typedef {Record} CompilationAssets */ +class SwitchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "switch", upperScope, block, false); + } +} -/** - * @typedef {Object} AvailableModulesChunkGroupMapping - * @property {ChunkGroup} chunkGroup - * @property {Set} availableModules - * @property {boolean} needCopy - */ +class FunctionScope extends Scope { + constructor(scopeManager, upperScope, block, isMethodDefinition) { + super(scopeManager, "function", upperScope, block, isMethodDefinition); -/** - * @typedef {Object} DependenciesBlockLike - * @property {Dependency[]} dependencies - * @property {AsyncDependenciesBlock[]} blocks - */ + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + if (this.block.type !== Syntax.ArrowFunctionExpression) { + this.__defineArguments(); + } + } -/** - * @typedef {Object} ChunkPathData - * @property {string|number} id - * @property {string=} name - * @property {string} hash - * @property {function(number): string=} hashWithLength - * @property {(Record)=} contentHash - * @property {(Record string>)=} contentHashWithLength - */ + isArgumentsMaterialized() { -/** - * @typedef {Object} ChunkHashContext - * @property {RuntimeTemplate} runtimeTemplate the runtime template - * @property {ModuleGraph} moduleGraph the module graph - * @property {ChunkGraph} chunkGraph the chunk graph - */ - -/** - * @typedef {Object} RuntimeRequirementsContext - * @property {ChunkGraph} chunkGraph the chunk graph - * @property {CodeGenerationResults} codeGenerationResults the code generation results - */ - -/** - * @typedef {Object} ExecuteModuleOptions - * @property {EntryOptions=} entryOptions - */ - -/** - * @typedef {Object} ExecuteModuleResult - * @property {any} exports - * @property {boolean} cacheable - * @property {Map} assets - * @property {LazySet} fileDependencies - * @property {LazySet} contextDependencies - * @property {LazySet} missingDependencies - * @property {LazySet} buildDependencies - */ - -/** - * @typedef {Object} ExecuteModuleArgument - * @property {Module} module - * @property {{ id: string, exports: any, loaded: boolean }=} moduleObject - * @property {any} preparedInfo - * @property {CodeGenerationResult} codeGenerationResult - */ + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + if (this.block.type === Syntax.ArrowFunctionExpression) { + return false; + } -/** - * @typedef {Object} ExecuteModuleContext - * @property {Map} assets - * @property {Chunk} chunk - * @property {ChunkGraph} chunkGraph - * @property {function(string): any=} __webpack_require__ - */ + if (!this.isStatic()) { + return true; + } -/** - * @typedef {Object} EntryData - * @property {Dependency[]} dependencies dependencies of the entrypoint that should be evaluated at startup - * @property {Dependency[]} includeDependencies dependencies of the entrypoint that should be included but not evaluated - * @property {EntryOptions} options options of the entrypoint - */ + const variable = this.set.get("arguments"); -/** - * @typedef {Object} LogEntry - * @property {string} type - * @property {any[]} args - * @property {number} time - * @property {string[]=} trace - */ + assert(variable, "Always have arguments variable."); + return variable.tainted || variable.references.length !== 0; + } -/** - * @typedef {Object} KnownAssetInfo - * @property {boolean=} immutable true, if the asset can be long term cached forever (contains a hash) - * @property {boolean=} minimized whether the asset is minimized - * @property {string | string[]=} fullhash the value(s) of the full hash used for this asset - * @property {string | string[]=} chunkhash the value(s) of the chunk hash used for this asset - * @property {string | string[]=} modulehash the value(s) of the module hash used for this asset - * @property {string | string[]=} contenthash the value(s) of the content hash used for this asset - * @property {string=} sourceFilename when asset was created from a source file (potentially transformed), the original filename relative to compilation context - * @property {number=} size size in bytes, only set after asset has been emitted - * @property {boolean=} development true, when asset is only used for development and doesn't count towards user-facing assets - * @property {boolean=} hotModuleReplacement true, when asset ships data for updating an existing application (HMR) - * @property {boolean=} javascriptModule true, when asset is javascript and an ESM - * @property {Record=} related object of pointers to other assets, keyed by type of relation (only points from parent to child) - */ + isThisMaterialized() { + if (!this.isStatic()) { + return true; + } + return this.thisFound; + } -/** @typedef {KnownAssetInfo & Record} AssetInfo */ + __defineArguments() { + this.__defineGeneric( + "arguments", + this.set, + this.variables, + null, + null + ); + this.taints.set("arguments", true); + } -/** - * @typedef {Object} Asset - * @property {string} name the filename of the asset - * @property {Source} source source of the asset - * @property {AssetInfo} info info about the asset - */ + // References in default parameters isn't resolved to variables which are in their function body. + // const x = 1 + // function f(a = x) { // This `x` is resolved to the `x` in the outer scope. + // const x = 2 + // console.log(a) + // } + __isValidResolution(ref, variable) { -/** - * @typedef {Object} ModulePathData - * @property {string|number} id - * @property {string} hash - * @property {function(number): string=} hashWithLength - */ + // If `options.nodejsScope` is true, `this.block` becomes a Program node. + if (this.block.type === "Program") { + return true; + } -/** - * @typedef {Object} PathData - * @property {ChunkGraph=} chunkGraph - * @property {string=} hash - * @property {function(number): string=} hashWithLength - * @property {(Chunk|ChunkPathData)=} chunk - * @property {(Module|ModulePathData)=} module - * @property {RuntimeSpec=} runtime - * @property {string=} filename - * @property {string=} basename - * @property {string=} query - * @property {string=} contentHashType - * @property {string=} contentHash - * @property {function(number): string=} contentHashWithLength - * @property {boolean=} noChunkHash - * @property {string=} url - */ + const bodyStart = this.block.body.range[0]; -/** - * @typedef {Object} KnownNormalizedStatsOptions - * @property {string} context - * @property {RequestShortener} requestShortener - * @property {string} chunksSort - * @property {string} modulesSort - * @property {string} chunkModulesSort - * @property {string} nestedModulesSort - * @property {string} assetsSort - * @property {boolean} ids - * @property {boolean} cachedAssets - * @property {boolean} groupAssetsByEmitStatus - * @property {boolean} groupAssetsByPath - * @property {boolean} groupAssetsByExtension - * @property {number} assetsSpace - * @property {((value: string, asset: StatsAsset) => boolean)[]} excludeAssets - * @property {((name: string, module: StatsModule, type: "module" | "chunk" | "root-of-chunk" | "nested") => boolean)[]} excludeModules - * @property {((warning: StatsError, textValue: string) => boolean)[]} warningsFilter - * @property {boolean} cachedModules - * @property {boolean} orphanModules - * @property {boolean} dependentModules - * @property {boolean} runtimeModules - * @property {boolean} groupModulesByCacheStatus - * @property {boolean} groupModulesByLayer - * @property {boolean} groupModulesByAttributes - * @property {boolean} groupModulesByPath - * @property {boolean} groupModulesByExtension - * @property {boolean} groupModulesByType - * @property {boolean | "auto"} entrypoints - * @property {boolean} chunkGroups - * @property {boolean} chunkGroupAuxiliary - * @property {boolean} chunkGroupChildren - * @property {number} chunkGroupMaxAssets - * @property {number} modulesSpace - * @property {number} chunkModulesSpace - * @property {number} nestedModulesSpace - * @property {false|"none"|"error"|"warn"|"info"|"log"|"verbose"} logging - * @property {((value: string) => boolean)[]} loggingDebug - * @property {boolean} loggingTrace - * @property {any} _env - */ + // It's invalid resolution in the following case: + return !( + variable.scope === this && + ref.identifier.range[0] < bodyStart && // the reference is in the parameter part. + variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body. + ); + } +} -/** @typedef {KnownNormalizedStatsOptions & Omit & Record} NormalizedStatsOptions */ +class ForScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "for", upperScope, block, false); + } +} -/** - * @typedef {Object} KnownCreateStatsOptionsContext - * @property {boolean=} forToString - */ +class ClassScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class", upperScope, block, false); + } +} -/** @typedef {KnownCreateStatsOptionsContext & Record} CreateStatsOptionsContext */ +module.exports = { + Scope, + GlobalScope, + ModuleScope, + FunctionExpressionNameScope, + CatchScope, + WithScope, + BlockScope, + SwitchScope, + FunctionScope, + ForScope, + ClassScope +}; -/** @type {AssetInfo} */ -const EMPTY_ASSET_INFO = Object.freeze({}); +/* vim: set sw=4 ts=4 et tw=80 : */ -const esmDependencyCategory = "esm"; -// TODO webpack 6: remove -const deprecatedNormalModuleLoaderHook = util.deprecate( - compilation => { - return (__webpack_require__(39).getCompilationHooks)(compilation).loader; - }, - "Compilation.hooks.normalModuleLoader was moved to NormalModule.getCompilationHooks(compilation).loader", - "DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK" -); -// TODO webpack 6: remove -const defineRemovedModuleTemplates = moduleTemplates => { - Object.defineProperties(moduleTemplates, { - asset: { - enumerable: false, - configurable: false, - get: () => { - throw new WebpackError( - "Compilation.moduleTemplates.asset has been removed" - ); - } - }, - webassembly: { - enumerable: false, - configurable: false, - get: () => { - throw new WebpackError( - "Compilation.moduleTemplates.webassembly has been removed" - ); - } - } - }); - moduleTemplates = undefined; -}; +/***/ }), -const byId = compareSelect( - /** - * @param {Chunk} c chunk - * @returns {number | string} id - */ c => c.id, - compareIds -); +/***/ 82971: +/***/ (function(module) { -const byNameOrHash = concatComparators( - compareSelect( - /** - * @param {Compilation} c compilation - * @returns {string} name - */ - c => c.name, - compareIds - ), - compareSelect( - /** - * @param {Compilation} c compilation - * @returns {string} hash - */ c => c.fullHash, - compareIds - ) -); +"use strict"; +/* + Copyright (C) 2015 Yusuke Suzuki -const byMessage = compareSelect(err => `${err.message}`, compareStringsNumeric); + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: -const byModule = compareSelect( - err => (err.module && err.module.identifier()) || "", - compareStringsNumeric -); + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. -const byLocation = compareSelect(err => err.loc, compareLocations); + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ -const compareErrors = concatComparators(byModule, byLocation, byMessage); -/** @type {WeakMap} */ -const unsafeCacheDependencies = new WeakMap(); +/** + * A Variable represents a locally scoped identifier. These include arguments to + * functions. + * @class Variable + */ +class Variable { + constructor(name, scope) { -/** @type {WeakMap} */ -const unsafeCacheData = new WeakMap(); + /** + * The variable name, as given in the source code. + * @member {String} Variable#name + */ + this.name = name; -class Compilation { - /** - * Creates an instance of Compilation. - * @param {Compiler} compiler the compiler which created the compilation - * @param {CompilationParams} params the compilation parameters - */ - constructor(compiler, params) { - this._backCompat = compiler._backCompat; + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {espree.Identifier[]} Variable#identifiers + */ + this.identifiers = []; - const getNormalModuleLoader = () => deprecatedNormalModuleLoaderHook(this); - /** @typedef {{ additionalAssets?: true | Function }} ProcessAssetsAdditionalOptions */ - /** @type {AsyncSeriesHook<[CompilationAssets], ProcessAssetsAdditionalOptions>} */ - const processAssetsHook = new AsyncSeriesHook(["assets"]); + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; - let savedAssets = new Set(); - const popNewAssets = assets => { - let newAssets = undefined; - for (const file of Object.keys(assets)) { - if (savedAssets.has(file)) continue; - if (newAssets === undefined) { - newAssets = Object.create(null); - } - newAssets[file] = assets[file]; - savedAssets.add(file); - } - return newAssets; - }; - processAssetsHook.intercept({ - name: "Compilation", - call: () => { - savedAssets = new Set(Object.keys(this.assets)); - }, - register: tap => { - const { type, name } = tap; - const { fn, additionalAssets, ...remainingTap } = tap; - const additionalAssetsFn = - additionalAssets === true ? fn : additionalAssets; - const processedAssets = additionalAssetsFn ? new WeakSet() : undefined; - switch (type) { - case "sync": - if (additionalAssetsFn) { - this.hooks.processAdditionalAssets.tap(name, assets => { - if (processedAssets.has(this.assets)) - additionalAssetsFn(assets); - }); - } - return { - ...remainingTap, - type: "async", - fn: (assets, callback) => { - try { - fn(assets); - } catch (e) { - return callback(e); - } - if (processedAssets !== undefined) - processedAssets.add(this.assets); - const newAssets = popNewAssets(assets); - if (newAssets !== undefined) { - this.hooks.processAdditionalAssets.callAsync( - newAssets, - callback - ); - return; - } - callback(); - } - }; - case "async": - if (additionalAssetsFn) { - this.hooks.processAdditionalAssets.tapAsync( - name, - (assets, callback) => { - if (processedAssets.has(this.assets)) - return additionalAssetsFn(assets, callback); - callback(); - } - ); - } - return { - ...remainingTap, - fn: (assets, callback) => { - fn(assets, err => { - if (err) return callback(err); - if (processedAssets !== undefined) - processedAssets.add(this.assets); - const newAssets = popNewAssets(assets); - if (newAssets !== undefined) { - this.hooks.processAdditionalAssets.callAsync( - newAssets, - callback - ); - return; - } - callback(); - }); - } - }; - case "promise": - if (additionalAssetsFn) { - this.hooks.processAdditionalAssets.tapPromise(name, assets => { - if (processedAssets.has(this.assets)) - return additionalAssetsFn(assets); - return Promise.resolve(); - }); - } - return { - ...remainingTap, - fn: assets => { - const p = fn(assets); - if (!p || !p.then) return p; - return p.then(() => { - if (processedAssets !== undefined) - processedAssets.add(this.assets); - const newAssets = popNewAssets(assets); - if (newAssets !== undefined) { - return this.hooks.processAdditionalAssets.promise( - newAssets - ); - } - }); - } - }; - } - } - }); + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @member {Definition[]} Variable#defs + */ + this.defs = []; - /** @type {SyncHook<[CompilationAssets]>} */ - const afterProcessAssetsHook = new SyncHook(["assets"]); + this.tainted = false; - /** - * @template T - * @param {string} name name of the hook - * @param {number} stage new stage - * @param {function(): AsArray} getArgs get old hook function args - * @param {string=} code deprecation code (not deprecated when unset) - * @returns {FakeHook, "tap" | "tapAsync" | "tapPromise" | "name">>} fake hook which redirects - */ - const createProcessAssetsHook = (name, stage, getArgs, code) => { - if (!this._backCompat && code) return undefined; - const errorMessage = - reason => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}. -BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a single Compilation.hooks.processAssets hook.`; - const getOptions = options => { - if (typeof options === "string") options = { name: options }; - if (options.stage) { - throw new Error(errorMessage("it's using the 'stage' option")); - } - return { ...options, stage: stage }; - }; - return createFakeHook( - { - name, - /** @type {AsyncSeriesHook["intercept"]} */ - intercept(interceptor) { - throw new Error(errorMessage("it's using 'intercept'")); - }, - /** @type {AsyncSeriesHook["tap"]} */ - tap: (options, fn) => { - processAssetsHook.tap(getOptions(options), () => fn(...getArgs())); - }, - /** @type {AsyncSeriesHook["tapAsync"]} */ - tapAsync: (options, fn) => { - processAssetsHook.tapAsync( - getOptions(options), - (assets, callback) => - /** @type {any} */ (fn)(...getArgs(), callback) - ); - }, - /** @type {AsyncSeriesHook["tapPromise"]} */ - tapPromise: (options, fn) => { - processAssetsHook.tapPromise(getOptions(options), () => - fn(...getArgs()) - ); - } - }, - `${name} is deprecated (use Compilation.hooks.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)`, - code - ); - }; - this.hooks = Object.freeze({ - /** @type {SyncHook<[Module]>} */ - buildModule: new SyncHook(["module"]), - /** @type {SyncHook<[Module]>} */ - rebuildModule: new SyncHook(["module"]), - /** @type {SyncHook<[Module, WebpackError]>} */ - failedModule: new SyncHook(["module", "error"]), - /** @type {SyncHook<[Module]>} */ - succeedModule: new SyncHook(["module"]), - /** @type {SyncHook<[Module]>} */ - stillValidModule: new SyncHook(["module"]), + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; - /** @type {SyncHook<[Dependency, EntryOptions]>} */ - addEntry: new SyncHook(["entry", "options"]), - /** @type {SyncHook<[Dependency, EntryOptions, Error]>} */ - failedEntry: new SyncHook(["entry", "options", "error"]), - /** @type {SyncHook<[Dependency, EntryOptions, Module]>} */ - succeedEntry: new SyncHook(["entry", "options", "module"]), + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; + } +} - /** @type {SyncWaterfallHook<[(string[] | ReferencedExport)[], Dependency, RuntimeSpec]>} */ - dependencyReferencedExports: new SyncWaterfallHook([ - "referencedExports", - "dependency", - "runtime" - ]), +Variable.CatchClause = "CatchClause"; +Variable.Parameter = "Parameter"; +Variable.FunctionName = "FunctionName"; +Variable.ClassName = "ClassName"; +Variable.Variable = "Variable"; +Variable.ImportBinding = "ImportBinding"; +Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable"; - /** @type {SyncHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */ - executeModule: new SyncHook(["options", "context"]), - /** @type {AsyncParallelHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */ - prepareModuleExecution: new AsyncParallelHook(["options", "context"]), +module.exports = Variable; - /** @type {AsyncSeriesHook<[Iterable]>} */ - finishModules: new AsyncSeriesHook(["modules"]), - /** @type {AsyncSeriesHook<[Module]>} */ - finishRebuildingModule: new AsyncSeriesHook(["module"]), - /** @type {SyncHook<[]>} */ - unseal: new SyncHook([]), - /** @type {SyncHook<[]>} */ - seal: new SyncHook([]), +/* vim: set sw=4 ts=4 et tw=80 : */ - /** @type {SyncHook<[]>} */ - beforeChunks: new SyncHook([]), - /** @type {SyncHook<[Iterable]>} */ - afterChunks: new SyncHook(["chunks"]), - /** @type {SyncBailHook<[Iterable]>} */ - optimizeDependencies: new SyncBailHook(["modules"]), - /** @type {SyncHook<[Iterable]>} */ - afterOptimizeDependencies: new SyncHook(["modules"]), +/***/ }), - /** @type {SyncHook<[]>} */ - optimize: new SyncHook([]), - /** @type {SyncBailHook<[Iterable]>} */ - optimizeModules: new SyncBailHook(["modules"]), - /** @type {SyncHook<[Iterable]>} */ - afterOptimizeModules: new SyncHook(["modules"]), +/***/ 81217: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - /** @type {SyncBailHook<[Iterable, ChunkGroup[]]>} */ - optimizeChunks: new SyncBailHook(["chunks", "chunkGroups"]), - /** @type {SyncHook<[Iterable, ChunkGroup[]]>} */ - afterOptimizeChunks: new SyncHook(["chunks", "chunkGroups"]), +/* + Copyright (C) 2014 Yusuke Suzuki - /** @type {AsyncSeriesHook<[Iterable, Iterable]>} */ - optimizeTree: new AsyncSeriesHook(["chunks", "modules"]), - /** @type {SyncHook<[Iterable, Iterable]>} */ - afterOptimizeTree: new SyncHook(["chunks", "modules"]), + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - /** @type {AsyncSeriesBailHook<[Iterable, Iterable]>} */ - optimizeChunkModules: new AsyncSeriesBailHook(["chunks", "modules"]), - /** @type {SyncHook<[Iterable, Iterable]>} */ - afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]), - /** @type {SyncBailHook<[], boolean>} */ - shouldRecord: new SyncBailHook([]), + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - /** @type {SyncHook<[Chunk, Set, RuntimeRequirementsContext]>} */ - additionalChunkRuntimeRequirements: new SyncHook([ - "chunk", - "runtimeRequirements", - "context" - ]), - /** @type {HookMap, RuntimeRequirementsContext]>>} */ - runtimeRequirementInChunk: new HookMap( - () => new SyncBailHook(["chunk", "runtimeRequirements", "context"]) - ), - /** @type {SyncHook<[Module, Set, RuntimeRequirementsContext]>} */ - additionalModuleRuntimeRequirements: new SyncHook([ - "module", - "runtimeRequirements", - "context" - ]), - /** @type {HookMap, RuntimeRequirementsContext]>>} */ - runtimeRequirementInModule: new HookMap( - () => new SyncBailHook(["module", "runtimeRequirements", "context"]) - ), - /** @type {SyncHook<[Chunk, Set, RuntimeRequirementsContext]>} */ - additionalTreeRuntimeRequirements: new SyncHook([ - "chunk", - "runtimeRequirements", - "context" - ]), - /** @type {HookMap, RuntimeRequirementsContext]>>} */ - runtimeRequirementInTree: new HookMap( - () => new SyncBailHook(["chunk", "runtimeRequirements", "context"]) - ), + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +(function () { + 'use strict'; - /** @type {SyncHook<[RuntimeModule, Chunk]>} */ - runtimeModule: new SyncHook(["module", "chunk"]), + var estraverse = __webpack_require__(50165); - /** @type {SyncHook<[Iterable, any]>} */ - reviveModules: new SyncHook(["modules", "records"]), - /** @type {SyncHook<[Iterable]>} */ - beforeModuleIds: new SyncHook(["modules"]), - /** @type {SyncHook<[Iterable]>} */ - moduleIds: new SyncHook(["modules"]), - /** @type {SyncHook<[Iterable]>} */ - optimizeModuleIds: new SyncHook(["modules"]), - /** @type {SyncHook<[Iterable]>} */ - afterOptimizeModuleIds: new SyncHook(["modules"]), + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } - /** @type {SyncHook<[Iterable, any]>} */ - reviveChunks: new SyncHook(["chunks", "records"]), - /** @type {SyncHook<[Iterable]>} */ - beforeChunkIds: new SyncHook(["chunks"]), - /** @type {SyncHook<[Iterable]>} */ - chunkIds: new SyncHook(["chunks"]), - /** @type {SyncHook<[Iterable]>} */ - optimizeChunkIds: new SyncHook(["chunks"]), - /** @type {SyncHook<[Iterable]>} */ - afterOptimizeChunkIds: new SyncHook(["chunks"]), + function isProperty(nodeType, key) { + return (nodeType === estraverse.Syntax.ObjectExpression || nodeType === estraverse.Syntax.ObjectPattern) && key === 'properties'; + } - /** @type {SyncHook<[Iterable, any]>} */ - recordModules: new SyncHook(["modules", "records"]), - /** @type {SyncHook<[Iterable, any]>} */ - recordChunks: new SyncHook(["chunks", "records"]), + function Visitor(visitor, options) { + options = options || {}; - /** @type {SyncHook<[Iterable]>} */ - optimizeCodeGeneration: new SyncHook(["modules"]), + this.__visitor = visitor || this; + this.__childVisitorKeys = options.childVisitorKeys + ? Object.assign({}, estraverse.VisitorKeys, options.childVisitorKeys) + : estraverse.VisitorKeys; + if (options.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof options.fallback === 'function') { + this.__fallback = options.fallback; + } + } - /** @type {SyncHook<[]>} */ - beforeModuleHash: new SyncHook([]), - /** @type {SyncHook<[]>} */ - afterModuleHash: new SyncHook([]), + /* Default method for visiting children. + * When you need to call default visiting operation inside custom visiting + * operation, you can use it with `this.visitChildren(node)`. + */ + Visitor.prototype.visitChildren = function (node) { + var type, children, i, iz, j, jz, child; - /** @type {SyncHook<[]>} */ - beforeCodeGeneration: new SyncHook([]), - /** @type {SyncHook<[]>} */ - afterCodeGeneration: new SyncHook([]), + if (node == null) { + return; + } - /** @type {SyncHook<[]>} */ - beforeRuntimeRequirements: new SyncHook([]), - /** @type {SyncHook<[]>} */ - afterRuntimeRequirements: new SyncHook([]), + type = node.type || estraverse.Syntax.Property; - /** @type {SyncHook<[]>} */ - beforeHash: new SyncHook([]), - /** @type {SyncHook<[Chunk]>} */ - contentHash: new SyncHook(["chunk"]), - /** @type {SyncHook<[]>} */ - afterHash: new SyncHook([]), - /** @type {SyncHook<[any]>} */ - recordHash: new SyncHook(["records"]), - /** @type {SyncHook<[Compilation, any]>} */ - record: new SyncHook(["compilation", "records"]), + children = this.__childVisitorKeys[type]; + if (!children) { + if (this.__fallback) { + children = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + type + '.'); + } + } - /** @type {SyncHook<[]>} */ - beforeModuleAssets: new SyncHook([]), - /** @type {SyncBailHook<[], boolean>} */ - shouldGenerateChunkAssets: new SyncBailHook([]), - /** @type {SyncHook<[]>} */ - beforeChunkAssets: new SyncHook([]), - // TODO webpack 6 remove - /** @deprecated */ - additionalChunkAssets: createProcessAssetsHook( - "additionalChunkAssets", - Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, - () => [this.chunks], - "DEP_WEBPACK_COMPILATION_ADDITIONAL_CHUNK_ASSETS" - ), + for (i = 0, iz = children.length; i < iz; ++i) { + child = node[children[i]]; + if (child) { + if (Array.isArray(child)) { + for (j = 0, jz = child.length; j < jz; ++j) { + if (child[j]) { + if (isNode(child[j]) || isProperty(type, children[i])) { + this.visit(child[j]); + } + } + } + } else if (isNode(child)) { + this.visit(child); + } + } + } + }; - // TODO webpack 6 deprecate - /** @deprecated */ - additionalAssets: createProcessAssetsHook( - "additionalAssets", - Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, - () => [] - ), - // TODO webpack 6 remove - /** @deprecated */ - optimizeChunkAssets: createProcessAssetsHook( - "optimizeChunkAssets", - Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE, - () => [this.chunks], - "DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS" - ), - // TODO webpack 6 remove - /** @deprecated */ - afterOptimizeChunkAssets: createProcessAssetsHook( - "afterOptimizeChunkAssets", - Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE + 1, - () => [this.chunks], - "DEP_WEBPACK_COMPILATION_AFTER_OPTIMIZE_CHUNK_ASSETS" - ), - // TODO webpack 6 deprecate - /** @deprecated */ - optimizeAssets: processAssetsHook, - // TODO webpack 6 deprecate - /** @deprecated */ - afterOptimizeAssets: afterProcessAssetsHook, + /* Dispatching node. */ + Visitor.prototype.visit = function (node) { + var type; - processAssets: processAssetsHook, - afterProcessAssets: afterProcessAssetsHook, - /** @type {AsyncSeriesHook<[CompilationAssets]>} */ - processAdditionalAssets: new AsyncSeriesHook(["assets"]), + if (node == null) { + return; + } - /** @type {SyncBailHook<[], boolean>} */ - needAdditionalSeal: new SyncBailHook([]), - /** @type {AsyncSeriesHook<[]>} */ - afterSeal: new AsyncSeriesHook([]), + type = node.type || estraverse.Syntax.Property; + if (this.__visitor[type]) { + this.__visitor[type].call(this, node); + return; + } + this.visitChildren(node); + }; - /** @type {SyncWaterfallHook<[RenderManifestEntry[], RenderManifestOptions]>} */ - renderManifest: new SyncWaterfallHook(["result", "options"]), + exports.version = __webpack_require__(12166).version; + exports.Visitor = Visitor; + exports.visit = function (node, visitor, options) { + var v = new Visitor(visitor, options); + v.visit(node); + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ - /** @type {SyncHook<[Hash]>} */ - fullHash: new SyncHook(["hash"]), - /** @type {SyncHook<[Chunk, Hash, ChunkHashContext]>} */ - chunkHash: new SyncHook(["chunk", "chunkHash", "ChunkHashContext"]), - /** @type {SyncHook<[Module, string]>} */ - moduleAsset: new SyncHook(["module", "filename"]), - /** @type {SyncHook<[Chunk, string]>} */ - chunkAsset: new SyncHook(["chunk", "filename"]), +/***/ }), - /** @type {SyncWaterfallHook<[string, object, AssetInfo]>} */ - assetPath: new SyncWaterfallHook(["path", "options", "assetInfo"]), +/***/ 50165: +/***/ (function(__unused_webpack_module, exports) { - /** @type {SyncBailHook<[], boolean>} */ - needAdditionalPass: new SyncBailHook([]), +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat - /** @type {SyncHook<[Compiler, string, number]>} */ - childCompiler: new SyncHook([ - "childCompiler", - "compilerName", - "compilerIndex" - ]), + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - /** @type {SyncBailHook<[string, LogEntry], true>} */ - log: new SyncBailHook(["origin", "logEntry"]), + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - /** @type {SyncWaterfallHook<[WebpackError[]]>} */ - processWarnings: new SyncWaterfallHook(["warnings"]), - /** @type {SyncWaterfallHook<[WebpackError[]]>} */ - processErrors: new SyncWaterfallHook(["errors"]), + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true*/ +(function clone(exports) { + 'use strict'; - /** @type {HookMap, CreateStatsOptionsContext]>>} */ - statsPreset: new HookMap(() => new SyncHook(["options", "context"])), - /** @type {SyncHook<[Partial, CreateStatsOptionsContext]>} */ - statsNormalize: new SyncHook(["options", "context"]), - /** @type {SyncHook<[StatsFactory, NormalizedStatsOptions]>} */ - statsFactory: new SyncHook(["statsFactory", "options"]), - /** @type {SyncHook<[StatsPrinter, NormalizedStatsOptions]>} */ - statsPrinter: new SyncHook(["statsPrinter", "options"]), + var Syntax, + VisitorOption, + VisitorKeys, + BREAK, + SKIP, + REMOVE; - get normalModuleLoader() { - return getNormalModuleLoader(); - } - }); - /** @type {string=} */ - this.name = undefined; - this.startTime = undefined; - this.endTime = undefined; - /** @type {Compiler} */ - this.compiler = compiler; - this.resolverFactory = compiler.resolverFactory; - this.inputFileSystem = compiler.inputFileSystem; - this.fileSystemInfo = new FileSystemInfo(this.inputFileSystem, { - managedPaths: compiler.managedPaths, - immutablePaths: compiler.immutablePaths, - logger: this.getLogger("webpack.FileSystemInfo"), - hashFunction: compiler.options.output.hashFunction - }); - if (compiler.fileTimestamps) { - this.fileSystemInfo.addFileTimestamps(compiler.fileTimestamps, true); - } - if (compiler.contextTimestamps) { - this.fileSystemInfo.addContextTimestamps( - compiler.contextTimestamps, - true - ); - } - /** @type {Map>} */ - this.valueCacheVersions = new Map(); - this.requestShortener = compiler.requestShortener; - this.compilerPath = compiler.compilerPath; + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } - this.logger = this.getLogger("webpack.Compilation"); + // based on LLVM libc++ upper_bound / lower_bound + // MIT License - const options = compiler.options; - this.options = options; - this.outputOptions = options && options.output; - /** @type {boolean} */ - this.bail = (options && options.bail) || false; - /** @type {boolean} */ - this.profile = (options && options.profile) || false; + function upperBound(array, func) { + var diff, len, i, current; - this.params = params; - this.mainTemplate = new MainTemplate(this.outputOptions, this); - this.chunkTemplate = new ChunkTemplate(this.outputOptions, this); - this.runtimeTemplate = new RuntimeTemplate( - this, - this.outputOptions, - this.requestShortener - ); - /** @type {{javascript: ModuleTemplate}} */ - this.moduleTemplates = { - javascript: new ModuleTemplate(this.runtimeTemplate, this) - }; - defineRemovedModuleTemplates(this.moduleTemplates); + len = array.length; + i = 0; - /** @type {Map> | undefined} */ - this.moduleMemCaches = undefined; - /** @type {Map> | undefined} */ - this.moduleMemCaches2 = undefined; - this.moduleGraph = new ModuleGraph(); - /** @type {ChunkGraph} */ - this.chunkGraph = undefined; - /** @type {CodeGenerationResults} */ - this.codeGenerationResults = undefined; + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } - /** @type {AsyncQueue} */ - this.processDependenciesQueue = new AsyncQueue({ - name: "processDependencies", - parallelism: options.parallelism || 100, - processor: this._processModuleDependencies.bind(this) - }); - /** @type {AsyncQueue} */ - this.addModuleQueue = new AsyncQueue({ - name: "addModule", - parent: this.processDependenciesQueue, - getKey: module => module.identifier(), - processor: this._addModule.bind(this) - }); - /** @type {AsyncQueue} */ - this.factorizeQueue = new AsyncQueue({ - name: "factorize", - parent: this.addModuleQueue, - processor: this._factorizeModule.bind(this) - }); - /** @type {AsyncQueue} */ - this.buildQueue = new AsyncQueue({ - name: "build", - parent: this.factorizeQueue, - processor: this._buildModule.bind(this) - }); - /** @type {AsyncQueue} */ - this.rebuildQueue = new AsyncQueue({ - name: "rebuild", - parallelism: options.parallelism || 100, - processor: this._rebuildModule.bind(this) - }); + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ChainExpression: 'ChainExpression', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportExpression: 'ImportExpression', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; - /** - * Modules in value are building during the build of Module in key. - * Means value blocking key from finishing. - * Needed to detect build cycles. - * @type {WeakMap>} - */ - this.creatingModuleDuringBuild = new WeakMap(); + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ChainExpression: ['expression'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportExpression: ['source'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: ['key', 'value'], + RestElement: [ 'argument' ], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; - /** @type {Map} */ - this.entries = new Map(); - /** @type {EntryData} */ - this.globalEntry = { - dependencies: [], - includeDependencies: [], - options: { - name: undefined - } - }; - /** @type {Map} */ - this.entrypoints = new Map(); - /** @type {Entrypoint[]} */ - this.asyncEntrypoints = []; - /** @type {Set} */ - this.chunks = new Set(); - /** @type {ChunkGroup[]} */ - this.chunkGroups = []; - /** @type {Map} */ - this.namedChunkGroups = new Map(); - /** @type {Map} */ - this.namedChunks = new Map(); - /** @type {Set} */ - this.modules = new Set(); - if (this._backCompat) { - arrayToSetDeprecation(this.chunks, "Compilation.chunks"); - arrayToSetDeprecation(this.modules, "Compilation.modules"); - } - /** @private @type {Map} */ - this._modules = new Map(); - this.records = null; - /** @type {string[]} */ - this.additionalChunkAssets = []; - /** @type {CompilationAssets} */ - this.assets = {}; - /** @type {Map} */ - this.assetsInfo = new Map(); - /** @type {Map>>} */ - this._assetsRelatedIn = new Map(); - /** @type {WebpackError[]} */ - this.errors = []; - /** @type {WebpackError[]} */ - this.warnings = []; - /** @type {Compilation[]} */ - this.children = []; - /** @type {Map} */ - this.logging = new Map(); - /** @type {Map} */ - this.dependencyFactories = new Map(); - /** @type {DependencyTemplates} */ - this.dependencyTemplates = new DependencyTemplates( - this.outputOptions.hashFunction - ); - this.childrenCounters = {}; - /** @type {Set} */ - this.usedChunkIds = null; - /** @type {Set} */ - this.usedModuleIds = null; - /** @type {boolean} */ - this.needAdditionalPass = false; - /** @type {Set} */ - this._restoredUnsafeCacheModuleEntries = new Set(); - /** @type {Map} */ - this._restoredUnsafeCacheEntries = new Map(); - /** @type {WeakSet} */ - this.builtModules = new WeakSet(); - /** @type {WeakSet} */ - this.codeGeneratedModules = new WeakSet(); - /** @type {WeakSet} */ - this.buildTimeExecutedModules = new WeakSet(); - /** @private @type {Map} */ - this._rebuildingModules = new Map(); - /** @type {Set} */ - this.emittedAssets = new Set(); - /** @type {Set} */ - this.comparedForEmitAssets = new Set(); - /** @type {LazySet} */ - this.fileDependencies = new LazySet(); - /** @type {LazySet} */ - this.contextDependencies = new LazySet(); - /** @type {LazySet} */ - this.missingDependencies = new LazySet(); - /** @type {LazySet} */ - this.buildDependencies = new LazySet(); - // TODO webpack 6 remove - this.compilationDependencies = { - add: util.deprecate( - item => this.fileDependencies.add(item), - "Compilation.compilationDependencies is deprecated (used Compilation.fileDependencies instead)", - "DEP_WEBPACK_COMPILATION_COMPILATION_DEPENDENCIES" - ) - }; + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; - this._modulesCache = this.getCache("Compilation/modules"); - this._assetsCache = this.getCache("Compilation/assets"); - this._codeGenerationCache = this.getCache("Compilation/codeGeneration"); + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; - const unsafeCache = options.module.unsafeCache; - this._unsafeCache = !!unsafeCache; - this._unsafeCachePredicate = - typeof unsafeCache === "function" ? unsafeCache : () => true; - } + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } - getStats() { - return new Stats(this); - } + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; - /** - * @param {StatsOptions | string} optionsOrPreset stats option value - * @param {CreateStatsOptionsContext} context context - * @returns {NormalizedStatsOptions} normalized options - */ - createStatsOptions(optionsOrPreset, context = {}) { - if ( - typeof optionsOrPreset === "boolean" || - typeof optionsOrPreset === "string" - ) { - optionsOrPreset = { preset: optionsOrPreset }; - } - if (typeof optionsOrPreset === "object" && optionsOrPreset !== null) { - // We use this method of shallow cloning this object to include - // properties in the prototype chain - /** @type {Partial} */ - const options = {}; - for (const key in optionsOrPreset) { - options[key] = optionsOrPreset[key]; - } - if (options.preset !== undefined) { - this.hooks.statsPreset.for(options.preset).call(options, context); - } - this.hooks.statsNormalize.call(options, context); - return /** @type {NormalizedStatsOptions} */ (options); - } else { - /** @type {Partial} */ - const options = {}; - this.hooks.statsNormalize.call(options, context); - return /** @type {NormalizedStatsOptions} */ (options); - } - } + Reference.prototype.remove = function remove() { + if (Array.isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; - createStatsFactory(options) { - const statsFactory = new StatsFactory(); - this.hooks.statsFactory.call(statsFactory, options); - return statsFactory; - } + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } - createStatsPrinter(options) { - const statsPrinter = new StatsPrinter(); - this.hooks.statsPrinter.call(statsPrinter, options); - return statsPrinter; - } + function Controller() { } - /** - * @param {string} name cache name - * @returns {CacheFacade} the cache facade instance - */ - getCache(name) { - return this.compiler.getCache(name); - } + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; - /** - * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name - * @returns {Logger} a logger with that name - */ - getLogger(name) { - if (!name) { - throw new TypeError("Compilation.getLogger(name) called without a name"); - } - /** @type {LogEntry[] | undefined} */ - let logEntries; - return new Logger( - (type, args) => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compilation.getLogger(name) called with a function not returning a name" - ); - } - } - let trace; - switch (type) { - case LogType.warn: - case LogType.error: - case LogType.trace: - trace = ErrorHelpers.cutOffLoaderExecution(new Error("Trace").stack) - .split("\n") - .slice(3); - break; - } - /** @type {LogEntry} */ - const logEntry = { - time: Date.now(), - type, - args, - trace - }; - if (this.hooks.log.call(name, logEntry) === undefined) { - if (logEntry.type === LogType.profileEnd) { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.profileEnd === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.profileEnd(`[${name}] ${logEntry.args[0]}`); - } - } - if (logEntries === undefined) { - logEntries = this.logging.get(name); - if (logEntries === undefined) { - logEntries = []; - this.logging.set(name, logEntries); - } - } - logEntries.push(logEntry); - if (logEntry.type === LogType.profile) { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.profile === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.profile(`[${name}] ${logEntry.args[0]}`); - } - } - } - }, - childName => { - if (typeof name === "function") { - if (typeof childName === "function") { - return this.getLogger(() => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compilation.getLogger(name) called with a function not returning a name" - ); - } - } - if (typeof childName === "function") { - childName = childName(); - if (!childName) { - throw new TypeError( - "Logger.getChildLogger(name) called with a function not returning a name" - ); - } - } - return `${name}/${childName}`; - }); - } else { - return this.getLogger(() => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compilation.getLogger(name) called with a function not returning a name" - ); - } - } - return `${name}/${childName}`; - }); - } - } else { - if (typeof childName === "function") { - return this.getLogger(() => { - if (typeof childName === "function") { - childName = childName(); - if (!childName) { - throw new TypeError( - "Logger.getChildLogger(name) called with a function not returning a name" - ); - } - } - return `${name}/${childName}`; - }); - } else { - return this.getLogger(`${name}/${childName}`); - } - } - } - ); - } + function addToPath(result, path) { + if (Array.isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } - /** - * @param {Module} module module to be added that was created - * @param {ModuleCallback} callback returns the module in the compilation, - * it could be the passed one (if new), or an already existing in the compilation - * @returns {void} - */ - addModule(module, callback) { - this.addModuleQueue.add(module, callback); - } + // root node + if (!this.__current.path) { + return null; + } - /** - * @param {Module} module module to be added that was created - * @param {ModuleCallback} callback returns the module in the compilation, - * it could be the passed one (if new), or an already existing in the compilation - * @returns {void} - */ - _addModule(module, callback) { - const identifier = module.identifier(); - const alreadyAddedModule = this._modules.get(identifier); - if (alreadyAddedModule) { - return callback(null, alreadyAddedModule); - } + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; - const currentProfile = this.profile - ? this.moduleGraph.getProfile(module) - : undefined; - if (currentProfile !== undefined) { - currentProfile.markRestoringStart(); - } + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; - this._modulesCache.get(identifier, null, (err, cacheModule) => { - if (err) return callback(new ModuleRestoreError(module, err)); + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; - if (currentProfile !== undefined) { - currentProfile.markRestoringEnd(); - currentProfile.markIntegrationStart(); - } + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } - if (cacheModule) { - cacheModule.updateCacheModule(module); + return result; + }; - module = cacheModule; - } - this._modules.set(identifier, module); - this.modules.add(module); - if (this._backCompat) - ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); - if (currentProfile !== undefined) { - currentProfile.markIntegrationEnd(); - } - callback(null, module); - }); - } + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; - /** - * Fetches a module from a compilation by its identifier - * @param {Module} module the module provided - * @returns {Module} the module requested - */ - getModule(module) { - const identifier = module.identifier(); - return this._modules.get(identifier); - } + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; - /** - * Attempts to search for a module by its identifier - * @param {string} identifier identifier (usually path) for module - * @returns {Module|undefined} attempt to search for module and return it, else undefined - */ - findModule(identifier) { - return this._modules.get(identifier); - } + result = undefined; - /** - * Schedules a build of the module object - * - * @param {Module} module module to be built - * @param {ModuleCallback} callback the callback - * @returns {void} - */ - buildModule(module, callback) { - this.buildQueue.add(module, callback); - } + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; - /** - * Builds the module object - * - * @param {Module} module module to be built - * @param {ModuleCallback} callback the callback - * @returns {void} - */ - _buildModule(module, callback) { - const currentProfile = this.profile - ? this.moduleGraph.getProfile(module) - : undefined; - if (currentProfile !== undefined) { - currentProfile.markBuildingStart(); - } + return result; + }; - module.needBuild( - { - compilation: this, - fileSystemInfo: this.fileSystemInfo, - valueCacheVersions: this.valueCacheVersions - }, - (err, needBuild) => { - if (err) return callback(err); + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; - if (!needBuild) { - if (currentProfile !== undefined) { - currentProfile.markBuildingEnd(); - } - this.hooks.stillValidModule.call(module); - return callback(); - } + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; - this.hooks.buildModule.call(module); - this.builtModules.add(module); - module.build( - this.options, - this, - this.resolverFactory.get("normal", module.resolveOptions), - this.inputFileSystem, - err => { - if (currentProfile !== undefined) { - currentProfile.markBuildingEnd(); - } - if (err) { - this.hooks.failedModule.call(module, err); - return callback(err); - } - if (currentProfile !== undefined) { - currentProfile.markStoringStart(); - } - this._modulesCache.store(module.identifier(), null, module, err => { - if (currentProfile !== undefined) { - currentProfile.markStoringEnd(); - } - if (err) { - this.hooks.failedModule.call(module, err); - return callback(new ModuleStoreError(module, err)); - } - this.hooks.succeedModule.call(module); - return callback(); - }); - } - ); - } - ); - } + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; - /** - * @param {Module} module to be processed for deps - * @param {ModuleCallback} callback callback to be triggered - * @returns {void} - */ - processModuleDependencies(module, callback) { - this.processDependenciesQueue.add(module, callback); - } + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; - /** - * @param {Module} module to be processed for deps - * @returns {void} - */ - processModuleDependenciesNonRecursive(module) { - const processDependenciesBlock = block => { - if (block.dependencies) { - let i = 0; - for (const dep of block.dependencies) { - this.moduleGraph.setParents(dep, block, module, i++); - } - } - if (block.blocks) { - for (const b of block.blocks) processDependenciesBlock(b); - } - }; + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } - processDependenciesBlock(module); - } + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); + } + }; - /** - * @param {Module} module to be processed for deps - * @param {ModuleCallback} callback callback to be triggered - * @returns {void} - */ - _processModuleDependencies(module, callback) { - /** @type {Array<{factory: ModuleFactory, dependencies: Dependency[], originModule: Module|null}>} */ - const sortedDependencies = []; + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } - /** @type {DependenciesBlock} */ - let currentBlock; + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + + function candidateExistsInLeaveList(leavelist, candidate) { + for (var i = leavelist.length - 1; i >= 0; --i) { + if (leavelist[i].node === candidate) { + return true; + } + } + return false; + } - /** @type {Map>} */ - let dependencies; - /** @type {DepConstructor} */ - let factoryCacheKey; - /** @type {ModuleFactory} */ - let factoryCacheKey2; - /** @type {Map} */ - let factoryCacheValue; - /** @type {string} */ - let listCacheKey1; - /** @type {string} */ - let listCacheKey2; - /** @type {Dependency[]} */ - let listCacheValue; + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; - let inProgressSorting = 1; - let inProgressTransitive = 1; + this.__initialize(root, visitor); - const onDependenciesSorted = err => { - if (err) return callback(err); + sentinel = {}; - // early exit without changing parallelism back and forth - if (sortedDependencies.length === 0 && inProgressTransitive === 1) { - return callback(); - } + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; - // This is nested so we need to allow one additional task - this.processDependenciesQueue.increaseParallelism(); + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); - for (const item of sortedDependencies) { - inProgressTransitive++; - this.handleModuleCreation(item, err => { - // In V8, the Error objects keep a reference to the functions on the stack. These warnings & - // errors are created inside closures that keep a reference to the Compilation, so errors are - // leaking the Compilation object. - if (err && this.bail) { - if (inProgressTransitive <= 0) return; - inProgressTransitive = -1; - // eslint-disable-next-line no-self-assign - err.stack = err.stack; - onTransitiveTasksFinished(err); - return; - } - if (--inProgressTransitive === 0) onTransitiveTasksFinished(); - }); - } - if (--inProgressTransitive === 0) onTransitiveTasksFinished(); - }; + while (worklist.length) { + element = worklist.pop(); - const onTransitiveTasksFinished = err => { - if (err) return callback(err); - this.processDependenciesQueue.decreaseParallelism(); + if (element === sentinel) { + element = leavelist.pop(); - return callback(); - }; + ret = this.__execute(visitor.leave, element); - /** - * @param {Dependency} dep dependency - * @param {number} index index in block - * @returns {void} - */ - const processDependency = (dep, index) => { - this.moduleGraph.setParents(dep, currentBlock, module, index); - if (this._unsafeCache) { - try { - const unsafeCachedModule = unsafeCacheDependencies.get(dep); - if (unsafeCachedModule === null) return; - if (unsafeCachedModule !== undefined) { - if ( - this._restoredUnsafeCacheModuleEntries.has(unsafeCachedModule) - ) { - this._handleExistingModuleFromUnsafeCache( - module, - dep, - unsafeCachedModule - ); - return; - } - const identifier = unsafeCachedModule.identifier(); - const cachedModule = - this._restoredUnsafeCacheEntries.get(identifier); - if (cachedModule !== undefined) { - // update unsafe cache to new module - unsafeCacheDependencies.set(dep, cachedModule); - this._handleExistingModuleFromUnsafeCache( - module, - dep, - cachedModule - ); - return; - } - inProgressSorting++; - this._modulesCache.get(identifier, null, (err, cachedModule) => { - if (err) { - if (inProgressSorting <= 0) return; - inProgressSorting = -1; - onDependenciesSorted(err); - return; - } - try { - if (!this._restoredUnsafeCacheEntries.has(identifier)) { - const data = unsafeCacheData.get(cachedModule); - if (data === undefined) { - processDependencyForResolving(dep); - if (--inProgressSorting === 0) onDependenciesSorted(); - return; - } - if (cachedModule !== unsafeCachedModule) { - unsafeCacheDependencies.set(dep, cachedModule); - } - cachedModule.restoreFromUnsafeCache( - data, - this.params.normalModuleFactory, - this.params - ); - this._restoredUnsafeCacheEntries.set( - identifier, - cachedModule - ); - this._restoredUnsafeCacheModuleEntries.add(cachedModule); - if (!this.modules.has(cachedModule)) { - inProgressTransitive++; - this._handleNewModuleFromUnsafeCache( - module, - dep, - cachedModule, - err => { - if (err) { - if (inProgressTransitive <= 0) return; - inProgressTransitive = -1; - onTransitiveTasksFinished(err); - } - if (--inProgressTransitive === 0) - return onTransitiveTasksFinished(); - } - ); - if (--inProgressSorting === 0) onDependenciesSorted(); - return; - } - } - if (unsafeCachedModule !== cachedModule) { - unsafeCacheDependencies.set(dep, cachedModule); - } - this._handleExistingModuleFromUnsafeCache( - module, - dep, - cachedModule - ); // a3 - } catch (err) { - if (inProgressSorting <= 0) return; - inProgressSorting = -1; - onDependenciesSorted(err); - return; - } - if (--inProgressSorting === 0) onDependenciesSorted(); - }); - return; - } - } catch (e) { - console.error(e); - } - } - processDependencyForResolving(dep); - }; + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } - /** - * @param {Dependency} dep dependency - * @returns {void} - */ - const processDependencyForResolving = dep => { - const resourceIdent = dep.getResourceIdentifier(); - if (resourceIdent !== undefined && resourceIdent !== null) { - const category = dep.category; - const constructor = /** @type {DepConstructor} */ (dep.constructor); - if (factoryCacheKey === constructor) { - // Fast path 1: same constructor as prev item - if (listCacheKey1 === category && listCacheKey2 === resourceIdent) { - // Super fast path 1: also same resource - listCacheValue.push(dep); - return; - } - } else { - const factory = this.dependencyFactories.get(constructor); - if (factory === undefined) { - throw new Error( - `No module factory available for dependency type: ${constructor.name}` - ); - } - if (factoryCacheKey2 === factory) { - // Fast path 2: same factory as prev item - factoryCacheKey = constructor; - if (listCacheKey1 === category && listCacheKey2 === resourceIdent) { - // Super fast path 2: also same resource - listCacheValue.push(dep); - return; - } - } else { - // Slow path - if (factoryCacheKey2 !== undefined) { - // Archive last cache entry - if (dependencies === undefined) dependencies = new Map(); - dependencies.set(factoryCacheKey2, factoryCacheValue); - factoryCacheValue = dependencies.get(factory); - if (factoryCacheValue === undefined) { - factoryCacheValue = new Map(); - } - } else { - factoryCacheValue = new Map(); - } - factoryCacheKey = constructor; - factoryCacheKey2 = factory; - } - } - // Here webpack is using heuristic that assumes - // mostly esm dependencies would be used - // so we don't allocate extra string for them - const cacheKey = - category === esmDependencyCategory - ? resourceIdent - : `${category}${resourceIdent}`; - let list = factoryCacheValue.get(cacheKey); - if (list === undefined) { - factoryCacheValue.set(cacheKey, (list = [])); - sortedDependencies.push({ - factory: factoryCacheKey2, - dependencies: list, - originModule: module - }); - } - list.push(dep); - listCacheKey1 = category; - listCacheKey2 = resourceIdent; - listCacheValue = list; - } - }; + if (element.node) { - try { - /** @type {DependenciesBlock[]} */ - const queue = [module]; - do { - const block = queue.pop(); - if (block.dependencies) { - currentBlock = block; - let i = 0; - for (const dep of block.dependencies) processDependency(dep, i++); - } - if (block.blocks) { - for (const b of block.blocks) queue.push(b); - } - } while (queue.length !== 0); - } catch (e) { - return callback(e); - } + ret = this.__execute(visitor.enter, element); - if (--inProgressSorting === 0) onDependenciesSorted(); - } + if (this.__state === BREAK || ret === BREAK) { + return; + } - _handleNewModuleFromUnsafeCache(originModule, dependency, module, callback) { - const moduleGraph = this.moduleGraph; + worklist.push(sentinel); + leavelist.push(element); - moduleGraph.setResolvedModule(originModule, dependency, module); + if (this.__state === SKIP || ret === SKIP) { + continue; + } - moduleGraph.setIssuerIfUnset( - module, - originModule !== undefined ? originModule : null - ); + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } - this._modules.set(module.identifier(), module); - this.modules.add(module); - if (this._backCompat) - ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } - this._handleModuleBuildAndDependencies( - originModule, - module, - true, - callback - ); - } + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } - _handleExistingModuleFromUnsafeCache(originModule, dependency, module) { - const moduleGraph = this.moduleGraph; + if (candidateExistsInLeaveList(leavelist, candidate[current2])) { + continue; + } - moduleGraph.setResolvedModule(originModule, dependency, module); - } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + if (candidateExistsInLeaveList(leavelist, candidate)) { + continue; + } - /** - * @typedef {Object} HandleModuleCreationOptions - * @property {ModuleFactory} factory - * @property {Dependency[]} dependencies - * @property {Module | null} originModule - * @property {Partial=} contextInfo - * @property {string=} context - * @property {boolean=} recursive recurse into dependencies of the created module - * @property {boolean=} connectOrigin connect the resolved module with the origin module - */ + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; - /** - * @param {HandleModuleCreationOptions} options options object - * @param {ModuleCallback} callback callback - * @returns {void} - */ - handleModuleCreation( - { - factory, - dependencies, - originModule, - contextInfo, - context, - recursive = true, - connectOrigin = recursive - }, - callback - ) { - const moduleGraph = this.moduleGraph; + Controller.prototype.replace = function replace(root, visitor) { + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; - const currentProfile = this.profile ? new ModuleProfile() : undefined; + function removeElem(element) { + var i, + key, + nextElem, + parent; - this.factorizeModule( - { - currentProfile, - factory, - dependencies, - factoryResult: true, - originModule, - contextInfo, - context - }, - (err, factoryResult) => { - const applyFactoryResultDependencies = () => { - const { fileDependencies, contextDependencies, missingDependencies } = - factoryResult; - if (fileDependencies) { - this.fileDependencies.addAll(fileDependencies); - } - if (contextDependencies) { - this.contextDependencies.addAll(contextDependencies); - } - if (missingDependencies) { - this.missingDependencies.addAll(missingDependencies); - } - }; - if (err) { - if (factoryResult) applyFactoryResultDependencies(); - if (dependencies.every(d => d.optional)) { - this.warnings.push(err); - return callback(); - } else { - this.errors.push(err); - return callback(err); - } - } + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; - const newModule = factoryResult.module; + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } - if (!newModule) { - applyFactoryResultDependencies(); - return callback(); - } + this.__initialize(root, visitor); - if (currentProfile !== undefined) { - moduleGraph.setProfile(newModule, currentProfile); - } + sentinel = {}; - this.addModule(newModule, (err, module) => { - if (err) { - applyFactoryResultDependencies(); - if (!err.module) { - err.module = module; - } - this.errors.push(err); + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; - return callback(err); - } + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); - if ( - this._unsafeCache && - factoryResult.cacheable !== false && - /** @type {any} */ (module).restoreFromUnsafeCache && - this._unsafeCachePredicate(module) - ) { - const unsafeCacheableModule = - /** @type {Module & { restoreFromUnsafeCache: Function }} */ ( - module - ); - for (let i = 0; i < dependencies.length; i++) { - const dependency = dependencies[i]; - moduleGraph.setResolvedModule( - connectOrigin ? originModule : null, - dependency, - unsafeCacheableModule - ); - unsafeCacheDependencies.set(dependency, unsafeCacheableModule); - } - if (!unsafeCacheData.has(unsafeCacheableModule)) { - unsafeCacheData.set( - unsafeCacheableModule, - unsafeCacheableModule.getUnsafeCacheData() - ); - } - } else { - applyFactoryResultDependencies(); - for (let i = 0; i < dependencies.length; i++) { - const dependency = dependencies[i]; - moduleGraph.setResolvedModule( - connectOrigin ? originModule : null, - dependency, - module - ); - } - } + while (worklist.length) { + element = worklist.pop(); - moduleGraph.setIssuerIfUnset( - module, - originModule !== undefined ? originModule : null - ); - if (module !== newModule) { - if (currentProfile !== undefined) { - const otherProfile = moduleGraph.getProfile(module); - if (otherProfile !== undefined) { - currentProfile.mergeInto(otherProfile); - } else { - moduleGraph.setProfile(module, currentProfile); - } - } - } + if (element === sentinel) { + element = leavelist.pop(); - this._handleModuleBuildAndDependencies( - originModule, - module, - recursive, - callback - ); - }); - } - ); - } + target = this.__execute(visitor.leave, element); - _handleModuleBuildAndDependencies(originModule, module, recursive, callback) { - // Check for cycles when build is trigger inside another build - let creatingModuleDuringBuildSet = undefined; - if (!recursive && this.buildQueue.isProcessing(originModule)) { - // Track build dependency - creatingModuleDuringBuildSet = - this.creatingModuleDuringBuild.get(originModule); - if (creatingModuleDuringBuildSet === undefined) { - creatingModuleDuringBuildSet = new Set(); - this.creatingModuleDuringBuild.set( - originModule, - creatingModuleDuringBuildSet - ); - } - creatingModuleDuringBuildSet.add(module); + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } - // When building is blocked by another module - // search for a cycle, cancel the cycle by throwing - // an error (otherwise this would deadlock) - const blockReasons = this.creatingModuleDuringBuild.get(module); - if (blockReasons !== undefined) { - const set = new Set(blockReasons); - for (const item of set) { - const blockReasons = this.creatingModuleDuringBuild.get(item); - if (blockReasons !== undefined) { - for (const m of blockReasons) { - if (m === module) { - return callback(new BuildCycleError(module)); - } - set.add(m); - } - } - } - } - } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } - this.buildModule(module, err => { - if (creatingModuleDuringBuildSet !== undefined) { - creatingModuleDuringBuildSet.delete(module); - } - if (err) { - if (!err.module) { - err.module = module; - } - this.errors.push(err); + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } - return callback(err); - } + target = this.__execute(visitor.enter, element); - if (!recursive) { - this.processModuleDependenciesNonRecursive(module); - callback(null, module); - return; - } + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } - // This avoids deadlocks for circular dependencies - if (this.processDependenciesQueue.isProcessing(module)) { - return callback(); - } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } - this.processModuleDependencies(module, err => { - if (err) { - return callback(err); - } - callback(null, module); - }); - }); - } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } - /** - * @param {FactorizeModuleOptions} options options object - * @param {ModuleOrFactoryResultCallback} callback callback - * @returns {void} - */ - _factorizeModule( - { - currentProfile, - factory, - dependencies, - originModule, - factoryResult, - contextInfo, - context - }, - callback - ) { - if (currentProfile !== undefined) { - currentProfile.markFactoryStart(); - } - factory.create( - { - contextInfo: { - issuer: originModule ? originModule.nameForCondition() : "", - issuerLayer: originModule ? originModule.layer : null, - compiler: this.compiler.name, - ...contextInfo - }, - resolveOptions: originModule ? originModule.resolveOptions : undefined, - context: context - ? context - : originModule - ? originModule.context - : this.compiler.context, - dependencies: dependencies - }, - (err, result) => { - if (result) { - // TODO webpack 6: remove - // For backward-compat - if (result.module === undefined && result instanceof Module) { - result = { - module: result - }; - } - if (!factoryResult) { - const { - fileDependencies, - contextDependencies, - missingDependencies - } = result; - if (fileDependencies) { - this.fileDependencies.addAll(fileDependencies); - } - if (contextDependencies) { - this.contextDependencies.addAll(contextDependencies); - } - if (missingDependencies) { - this.missingDependencies.addAll(missingDependencies); - } - } - } - if (err) { - const notFoundError = new ModuleNotFoundError( - originModule, - err, - dependencies.map(d => d.loc).filter(Boolean)[0] - ); - return callback(notFoundError, factoryResult ? result : undefined); - } - if (!result) { - return callback(); - } + // node may be null + node = element.node; + if (!node) { + continue; + } - if (currentProfile !== undefined) { - currentProfile.markFactoryEnd(); - } + worklist.push(sentinel); + leavelist.push(element); - callback(null, factoryResult ? result : result.module); - } - ); - } + if (this.__state === SKIP || target === SKIP) { + continue; + } - /** - * @param {string} context context string path - * @param {Dependency} dependency dependency used to create Module chain - * @param {ModuleCallback} callback callback for when module chain is complete - * @returns {void} will throw if dependency instance is not a valid Dependency - */ - addModuleChain(context, dependency, callback) { - return this.addModuleTree({ context, dependency }, callback); - } + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } - /** - * @param {Object} options options - * @param {string} options.context context string path - * @param {Dependency} options.dependency dependency used to create Module chain - * @param {Partial=} options.contextInfo additional context info for the root module - * @param {ModuleCallback} callback callback for when module chain is complete - * @returns {void} will throw if dependency instance is not a valid Dependency - */ - addModuleTree({ context, dependency, contextInfo }, callback) { - if ( - typeof dependency !== "object" || - dependency === null || - !dependency.constructor - ) { - return callback( - new WebpackError("Parameter 'dependency' must be a Dependency") - ); - } - const Dep = /** @type {DepConstructor} */ (dependency.constructor); - const moduleFactory = this.dependencyFactories.get(Dep); - if (!moduleFactory) { - return callback( - new WebpackError( - `No dependency factory available for this dependency type: ${dependency.constructor.name}` - ) - ); - } + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } - this.handleModuleCreation( - { - factory: moduleFactory, - dependencies: [dependency], - originModule: null, - contextInfo, - context - }, - (err, result) => { - if (err && this.bail) { - callback(err); - this.buildQueue.stop(); - this.rebuildQueue.stop(); - this.processDependenciesQueue.stop(); - this.factorizeQueue.stop(); - } else if (!err && result) { - callback(null, result); - } else { - callback(); - } - } - ); - } + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } - /** - * @param {string} context context path for entry - * @param {Dependency} entry entry dependency that should be followed - * @param {string | EntryOptions} optionsOrName options or deprecated name of entry - * @param {ModuleCallback} callback callback function - * @returns {void} returns - */ - addEntry(context, entry, optionsOrName, callback) { - // TODO webpack 6 remove - const options = - typeof optionsOrName === "object" - ? optionsOrName - : { name: optionsOrName }; + return outer.root; + }; - this._addEntryItem(context, entry, "dependencies", options, callback); - } + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } - /** - * @param {string} context context path for entry - * @param {Dependency} dependency dependency that should be followed - * @param {EntryOptions} options options - * @param {ModuleCallback} callback callback function - * @returns {void} returns - */ - addInclude(context, dependency, options, callback) { - this._addEntryItem( - context, - dependency, - "includeDependencies", - options, - callback - ); - } + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } - /** - * @param {string} context context path for entry - * @param {Dependency} entry entry dependency that should be followed - * @param {"dependencies" | "includeDependencies"} target type of entry - * @param {EntryOptions} options options - * @param {ModuleCallback} callback callback function - * @returns {void} returns - */ - _addEntryItem(context, entry, target, options, callback) { - const { name } = options; - let entryData = - name !== undefined ? this.entries.get(name) : this.globalEntry; - if (entryData === undefined) { - entryData = { - dependencies: [], - includeDependencies: [], - options: { - name: undefined, - ...options - } - }; - entryData[target].push(entry); - this.entries.set(name, entryData); - } else { - entryData[target].push(entry); - for (const key of Object.keys(options)) { - if (options[key] === undefined) continue; - if (entryData.options[key] === options[key]) continue; - if ( - Array.isArray(entryData.options[key]) && - Array.isArray(options[key]) && - arrayEquals(entryData.options[key], options[key]) - ) { - continue; - } - if (entryData.options[key] === undefined) { - entryData.options[key] = options[key]; - } else { - return callback( - new WebpackError( - `Conflicting entry option ${key} = ${entryData.options[key]} vs ${options[key]}` - ) - ); - } - } - } + function extendCommentRange(comment, tokens) { + var target; - this.hooks.addEntry.call(entry, options); + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); - this.addModuleTree( - { - context, - dependency: entry, - contextInfo: entryData.options.layer - ? { issuerLayer: entryData.options.layer } - : undefined - }, - (err, module) => { - if (err) { - this.hooks.failedEntry.call(entry, options, err); - return callback(err); - } - this.hooks.succeedEntry.call(entry, options, module); - return callback(null, module); - } - ); - } + comment.extendedRange = [comment.range[0], comment.range[1]]; - /** - * @param {Module} module module to be rebuilt - * @param {ModuleCallback} callback callback when module finishes rebuilding - * @returns {void} - */ - rebuildModule(module, callback) { - this.rebuildQueue.add(module, callback); - } + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } - /** - * @param {Module} module module to be rebuilt - * @param {ModuleCallback} callback callback when module finishes rebuilding - * @returns {void} - */ - _rebuildModule(module, callback) { - this.hooks.rebuildModule.call(module); - const oldDependencies = module.dependencies.slice(); - const oldBlocks = module.blocks.slice(); - module.invalidateBuild(); - this.buildQueue.invalidate(module); - this.buildModule(module, err => { - if (err) { - return this.hooks.finishRebuildingModule.callAsync(module, err2 => { - if (err2) { - callback( - makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule") - ); - return; - } - callback(err); - }); - } + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } - this.processDependenciesQueue.invalidate(module); - this.moduleGraph.unfreeze(); - this.processModuleDependencies(module, err => { - if (err) return callback(err); - this.removeReasonsOfDependencyBlock(module, { - dependencies: oldDependencies, - blocks: oldBlocks - }); - this.hooks.finishRebuildingModule.callAsync(module, err2 => { - if (err2) { - callback( - makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule") - ); - return; - } - callback(null, module); - }); - }); - }); - } + return comment; + } - _computeAffectedModules(modules) { - const moduleMemCacheCache = this.compiler.moduleMemCaches; - if (!moduleMemCacheCache) return; - if (!this.moduleMemCaches) { - this.moduleMemCaches = new Map(); - this.moduleGraph.setModuleMemCaches(this.moduleMemCaches); - } - const { moduleGraph, moduleMemCaches } = this; - const affectedModules = new Set(); - const infectedModules = new Set(); - let statNew = 0; - let statChanged = 0; - let statUnchanged = 0; - let statReferencesChanged = 0; - let statWithoutBuild = 0; + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; - const computeReferences = module => { - /** @type {WeakMap} */ - let references = undefined; - for (const connection of moduleGraph.getOutgoingConnections(module)) { - const d = connection.dependency; - const m = connection.module; - if (!d || !m || unsafeCacheDependencies.has(d)) continue; - if (references === undefined) references = new WeakMap(); - references.set(d, m); - } - return references; - }; + if (!tree.range) { + throw new Error('attachComments needs range information'); + } - /** - * @param {Module} module the module - * @param {WeakMap} references references - * @returns {boolean} true, when the references differ - */ - const compareReferences = (module, references) => { - if (references === undefined) return true; - for (const connection of moduleGraph.getOutgoingConnections(module)) { - const d = connection.dependency; - if (!d) continue; - const entry = references.get(d); - if (entry === undefined) continue; - if (entry !== connection.module) return false; - } - return true; - }; + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } - const modulesWithoutCache = new Set(modules); - for (const [module, cachedMemCache] of moduleMemCacheCache) { - if (modulesWithoutCache.has(module)) { - const buildInfo = module.buildInfo; - if (buildInfo) { - if (cachedMemCache.buildInfo !== buildInfo) { - // use a new one - const memCache = new WeakTupleMap(); - moduleMemCaches.set(module, memCache); - affectedModules.add(module); - cachedMemCache.buildInfo = buildInfo; - cachedMemCache.references = computeReferences(module); - cachedMemCache.memCache = memCache; - statChanged++; - } else if (!compareReferences(module, cachedMemCache.references)) { - // use a new one - const memCache = new WeakTupleMap(); - moduleMemCaches.set(module, memCache); - affectedModules.add(module); - cachedMemCache.references = computeReferences(module); - cachedMemCache.memCache = memCache; - statReferencesChanged++; - } else { - // keep the old mem cache - moduleMemCaches.set(module, cachedMemCache.memCache); - statUnchanged++; - } - } else { - infectedModules.add(module); - moduleMemCacheCache.delete(module); - statWithoutBuild++; - } - modulesWithoutCache.delete(module); - } else { - moduleMemCacheCache.delete(module); - } - } + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } - for (const module of modulesWithoutCache) { - const buildInfo = module.buildInfo; - if (buildInfo) { - // create a new entry - const memCache = new WeakTupleMap(); - moduleMemCacheCache.set(module, { - buildInfo, - references: computeReferences(module), - memCache - }); - moduleMemCaches.set(module, memCache); - affectedModules.add(module); - statNew++; - } else { - infectedModules.add(module); - statWithoutBuild++; - } - } + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; - const reduceAffectType = connections => { - let affected = false; - for (const { dependency } of connections) { - if (!dependency) continue; - const type = dependency.couldAffectReferencingModule(); - if (type === Dependency.TRANSITIVE) return Dependency.TRANSITIVE; - if (type === false) continue; - affected = true; - } - return affected; - }; - const directOnlyInfectedModules = new Set(); - for (const module of infectedModules) { - for (const [ - referencingModule, - connections - ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { - if (!referencingModule) continue; - if (infectedModules.has(referencingModule)) continue; - const type = reduceAffectType(connections); - if (!type) continue; - if (type === true) { - directOnlyInfectedModules.add(referencingModule); - } else { - infectedModules.add(referencingModule); - } - } - } - for (const module of directOnlyInfectedModules) infectedModules.add(module); - const directOnlyAffectModules = new Set(); - for (const module of affectedModules) { - for (const [ - referencingModule, - connections - ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { - if (!referencingModule) continue; - if (infectedModules.has(referencingModule)) continue; - if (affectedModules.has(referencingModule)) continue; - const type = reduceAffectType(connections); - if (!type) continue; - if (type === true) { - directOnlyAffectModules.add(referencingModule); - } else { - affectedModules.add(referencingModule); - } - const memCache = new WeakTupleMap(); - const cache = moduleMemCacheCache.get(referencingModule); - cache.memCache = memCache; - moduleMemCaches.set(referencingModule, memCache); - } - } - for (const module of directOnlyAffectModules) affectedModules.add(module); - this.logger.log( - `${Math.round( - (100 * (affectedModules.size + infectedModules.size)) / - this.modules.size - )}% (${affectedModules.size} affected + ${ - infectedModules.size - } infected of ${ - this.modules.size - }) modules flagged as affected (${statNew} new modules, ${statChanged} changed, ${statReferencesChanged} references changed, ${statUnchanged} unchanged, ${statWithoutBuild} were not built)` - ); - } + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } - _computeAffectedModulesWithChunkGraph() { - const { moduleMemCaches } = this; - if (!moduleMemCaches) return; - const moduleMemCaches2 = (this.moduleMemCaches2 = new Map()); - const { moduleGraph, chunkGraph } = this; - const key = "memCache2"; - let statUnchanged = 0; - let statChanged = 0; - let statNew = 0; - /** - * @param {Module} module module - * @returns {{ id: string | number, modules?: Map, blocks?: (string | number)[] }} references - */ - const computeReferences = module => { - const id = chunkGraph.getModuleId(module); - /** @type {Map} */ - let modules = undefined; - /** @type {(string | number)[] | undefined} */ - let blocks = undefined; - const outgoing = moduleGraph.getOutgoingConnectionsByModule(module); - if (outgoing !== undefined) { - for (const m of outgoing.keys()) { - if (!m) continue; - if (modules === undefined) modules = new Map(); - modules.set(m, chunkGraph.getModuleId(m)); - } - } - if (module.blocks.length > 0) { - blocks = []; - const queue = Array.from(module.blocks); - for (const block of queue) { - const chunkGroup = chunkGraph.getBlockChunkGroup(block); - if (chunkGroup) { - for (const chunk of chunkGroup.chunks) { - blocks.push(chunk.id); - } - } else { - blocks.push(null); - } - queue.push.apply(queue, block.blocks); - } - } - return { id, modules, blocks }; - }; - /** - * @param {Module} module module - * @param {Object} references references - * @param {string | number} references.id id - * @param {Map=} references.modules modules - * @param {(string | number)[]=} references.blocks blocks - * @returns {boolean} ok? - */ - const compareReferences = (module, { id, modules, blocks }) => { - if (id !== chunkGraph.getModuleId(module)) return false; - if (modules !== undefined) { - for (const [module, id] of modules) { - if (chunkGraph.getModuleId(module) !== id) return false; - } - } - if (blocks !== undefined) { - const queue = Array.from(module.blocks); - let i = 0; - for (const block of queue) { - const chunkGroup = chunkGraph.getBlockChunkGroup(block); - if (chunkGroup) { - for (const chunk of chunkGroup.chunks) { - if (i >= blocks.length || blocks[i++] !== chunk.id) return false; - } - } else { - if (i >= blocks.length || blocks[i++] !== null) return false; - } - queue.push.apply(queue, block.blocks); - } - if (i !== blocks.length) return false; - } - return true; - }; + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } - for (const [module, memCache] of moduleMemCaches) { - /** @type {{ references: { id: string | number, modules?: Map, blocks?: (string | number)[]}, memCache: WeakTupleMap }} */ - const cache = memCache.get(key); - if (cache === undefined) { - const memCache2 = new WeakTupleMap(); - memCache.set(key, { - references: computeReferences(module), - memCache: memCache2 - }); - moduleMemCaches2.set(module, memCache2); - statNew++; - } else if (!compareReferences(module, cache.references)) { - const memCache = new WeakTupleMap(); - cache.references = computeReferences(module); - cache.memCache = memCache; - moduleMemCaches2.set(module, memCache); - statChanged++; - } else { - moduleMemCaches2.set(module, cache.memCache); - statUnchanged++; - } - } - - this.logger.log( - `${Math.round( - (100 * statChanged) / (statNew + statChanged + statUnchanged) - )}% modules flagged as affected by chunk graph (${statNew} new modules, ${statChanged} changed, ${statUnchanged} unchanged)` - ); - } + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } - finish(callback) { - this.factorizeQueue.clear(); - if (this.profile) { - this.logger.time("finish module profiles"); - const ParallelismFactorCalculator = __webpack_require__(50780); - const p = new ParallelismFactorCalculator(); - const moduleGraph = this.moduleGraph; - const modulesWithProfiles = new Map(); - for (const module of this.modules) { - const profile = moduleGraph.getProfile(module); - if (!profile) continue; - modulesWithProfiles.set(module, profile); - p.range( - profile.buildingStartTime, - profile.buildingEndTime, - f => (profile.buildingParallelismFactor = f) - ); - p.range( - profile.factoryStartTime, - profile.factoryEndTime, - f => (profile.factoryParallelismFactor = f) - ); - p.range( - profile.integrationStartTime, - profile.integrationEndTime, - f => (profile.integrationParallelismFactor = f) - ); - p.range( - profile.storingStartTime, - profile.storingEndTime, - f => (profile.storingParallelismFactor = f) - ); - p.range( - profile.restoringStartTime, - profile.restoringEndTime, - f => (profile.restoringParallelismFactor = f) - ); - if (profile.additionalFactoryTimes) { - for (const { start, end } of profile.additionalFactoryTimes) { - const influence = (end - start) / profile.additionalFactories; - p.range( - start, - end, - f => - (profile.additionalFactoriesParallelismFactor += f * influence) - ); - } - } - } - p.calculate(); + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); - const logger = this.getLogger("webpack.Compilation.ModuleProfile"); - const logByValue = (value, msg) => { - if (value > 1000) { - logger.error(msg); - } else if (value > 500) { - logger.warn(msg); - } else if (value > 200) { - logger.info(msg); - } else if (value > 30) { - logger.log(msg); - } else { - logger.debug(msg); - } - }; - const logNormalSummary = (category, getDuration, getParallelism) => { - let sum = 0; - let max = 0; - for (const [module, profile] of modulesWithProfiles) { - const p = getParallelism(profile); - const d = getDuration(profile); - if (d === 0 || p === 0) continue; - const t = d / p; - sum += t; - if (t <= 10) continue; - logByValue( - t, - ` | ${Math.round(t)} ms${ - p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : "" - } ${category} > ${module.readableIdentifier(this.requestShortener)}` - ); - max = Math.max(max, t); - } - if (sum <= 10) return; - logByValue( - Math.max(sum / 10, max), - `${Math.round(sum)} ms ${category}` - ); - }; - const logByLoadersSummary = (category, getDuration, getParallelism) => { - const map = new Map(); - for (const [module, profile] of modulesWithProfiles) { - const list = provide( - map, - module.type + "!" + module.identifier().replace(/(!|^)[^!]*$/, ""), - () => [] - ); - list.push({ module, profile }); - } + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; - let sum = 0; - let max = 0; - for (const [key, modules] of map) { - let innerSum = 0; - let innerMax = 0; - for (const { module, profile } of modules) { - const p = getParallelism(profile); - const d = getDuration(profile); - if (d === 0 || p === 0) continue; - const t = d / p; - innerSum += t; - if (t <= 10) continue; - logByValue( - t, - ` | | ${Math.round(t)} ms${ - p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : "" - } ${category} > ${module.readableIdentifier( - this.requestShortener - )}` - ); - innerMax = Math.max(innerMax, t); - } - sum += innerSum; - if (innerSum <= 10) continue; - const idx = key.indexOf("!"); - const loaders = key.slice(idx + 1); - const moduleType = key.slice(0, idx); - const t = Math.max(innerSum / 10, innerMax); - logByValue( - t, - ` | ${Math.round(innerSum)} ms ${category} > ${ - loaders - ? `${ - modules.length - } x ${moduleType} with ${this.requestShortener.shorten( - loaders - )}` - : `${modules.length} x ${moduleType}` - }` - ); - max = Math.max(max, t); - } - if (sum <= 10) return; - logByValue( - Math.max(sum / 10, max), - `${Math.round(sum)} ms ${category}` - ); - }; - logNormalSummary( - "resolve to new modules", - p => p.factory, - p => p.factoryParallelismFactor - ); - logNormalSummary( - "resolve to existing modules", - p => p.additionalFactories, - p => p.additionalFactoriesParallelismFactor - ); - logNormalSummary( - "integrate modules", - p => p.restoring, - p => p.restoringParallelismFactor - ); - logByLoadersSummary( - "build modules", - p => p.building, - p => p.buildingParallelismFactor - ); - logNormalSummary( - "store modules", - p => p.storing, - p => p.storingParallelismFactor - ); - logNormalSummary( - "restore modules", - p => p.restoring, - p => p.restoringParallelismFactor - ); - this.logger.timeEnd("finish module profiles"); - } - this.logger.time("compute affected modules"); - this._computeAffectedModules(this.modules); - this.logger.timeEnd("compute affected modules"); - this.logger.time("finish modules"); - const { modules, moduleMemCaches } = this; - this.hooks.finishModules.callAsync(modules, err => { - this.logger.timeEnd("finish modules"); - if (err) return callback(err); + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } - // extract warnings and errors from modules - this.moduleGraph.freeze("dependency errors"); - // TODO keep a cacheToken (= {}) for each module in the graph - // create a new one per compilation and flag all updated files - // and parents with it - this.logger.time("report dependency errors and warnings"); - for (const module of modules) { - // TODO only run for modules with changed cacheToken - // global WeakMap> to keep modules without errors/warnings - const memCache = moduleMemCaches && moduleMemCaches.get(module); - if (memCache && memCache.get("noWarningsOrErrors")) continue; - let hasProblems = this.reportDependencyErrorsAndWarnings(module, [ - module - ]); - const errors = module.getErrors(); - if (errors !== undefined) { - for (const error of errors) { - if (!error.module) { - error.module = module; - } - this.errors.push(error); - hasProblems = true; - } - } - const warnings = module.getWarnings(); - if (warnings !== undefined) { - for (const warning of warnings) { - if (!warning.module) { - warning.module = module; - } - this.warnings.push(warning); - hasProblems = true; - } - } - if (!hasProblems && memCache) memCache.set("noWarningsOrErrors", true); - } - this.moduleGraph.unfreeze(); - this.logger.timeEnd("report dependency errors and warnings"); + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } - callback(); - }); - } + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } - unseal() { - this.hooks.unseal.call(); - this.chunks.clear(); - this.chunkGroups.length = 0; - this.namedChunks.clear(); - this.namedChunkGroups.clear(); - this.entrypoints.clear(); - this.additionalChunkAssets.length = 0; - this.assets = {}; - this.assetsInfo.clear(); - this.moduleGraph.removeAllModuleAttributes(); - this.moduleGraph.unfreeze(); - this.moduleMemCaches2 = undefined; - } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); - /** - * @param {Callback} callback signals when the call finishes - * @returns {void} - */ - seal(callback) { - const finalCallback = err => { - this.factorizeQueue.clear(); - this.buildQueue.clear(); - this.rebuildQueue.clear(); - this.processDependenciesQueue.clear(); - this.addModuleQueue.clear(); - return callback(err); - }; - const chunkGraph = new ChunkGraph( - this.moduleGraph, - this.outputOptions.hashFunction - ); - this.chunkGraph = chunkGraph; + return tree; + } - if (this._backCompat) { - for (const module of this.modules) { - ChunkGraph.setChunkGraphForModule(module, chunkGraph); - } - } + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { return clone({}); }; - this.hooks.seal.call(); + return exports; +}(exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ - this.logger.time("optimize dependencies"); - while (this.hooks.optimizeDependencies.call(this.modules)) { - /* empty */ - } - this.hooks.afterOptimizeDependencies.call(this.modules); - this.logger.timeEnd("optimize dependencies"); - this.logger.time("create chunks"); - this.hooks.beforeChunks.call(); - this.moduleGraph.freeze("seal"); - /** @type {Map} */ - const chunkGraphInit = new Map(); - for (const [name, { dependencies, includeDependencies, options }] of this - .entries) { - const chunk = this.addChunk(name); - if (options.filename) { - chunk.filenameTemplate = options.filename; - } - const entrypoint = new Entrypoint(options); - if (!options.dependOn && !options.runtime) { - entrypoint.setRuntimeChunk(chunk); - } - entrypoint.setEntrypointChunk(chunk); - this.namedChunkGroups.set(name, entrypoint); - this.entrypoints.set(name, entrypoint); - this.chunkGroups.push(entrypoint); - connectChunkGroupAndChunk(entrypoint, chunk); +/***/ }), - const entryModules = new Set(); - for (const dep of [...this.globalEntry.dependencies, ...dependencies]) { - entrypoint.addOrigin(null, { name }, /** @type {any} */ (dep).request); +/***/ 18350: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - const module = this.moduleGraph.getModule(dep); - if (module) { - chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint); - entryModules.add(module); - const modulesList = chunkGraphInit.get(entrypoint); - if (modulesList === undefined) { - chunkGraphInit.set(entrypoint, [module]); - } else { - modulesList.push(module); - } - } - } +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat - this.assignDepths(entryModules); + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - const mapAndSort = deps => - deps - .map(dep => this.moduleGraph.getModule(dep)) - .filter(Boolean) - .sort(compareModulesByIdentifier); - const includedModules = [ - ...mapAndSort(this.globalEntry.includeDependencies), - ...mapAndSort(includeDependencies) - ]; + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - let modulesList = chunkGraphInit.get(entrypoint); - if (modulesList === undefined) { - chunkGraphInit.set(entrypoint, (modulesList = [])); - } - for (const module of includedModules) { - this.assignDepth(module); - modulesList.push(module); - } - } - const runtimeChunks = new Set(); - outer: for (const [ - name, - { - options: { dependOn, runtime } - } - ] of this.entries) { - if (dependOn && runtime) { - const err = - new WebpackError(`Entrypoint '${name}' has 'dependOn' and 'runtime' specified. This is not valid. -Entrypoints that depend on other entrypoints do not have their own runtime. -They will use the runtime(s) from referenced entrypoints instead. -Remove the 'runtime' option from the entrypoint.`); - const entry = this.entrypoints.get(name); - err.chunk = entry.getEntrypointChunk(); - this.errors.push(err); - } - if (dependOn) { - const entry = this.entrypoints.get(name); - const referencedChunks = entry - .getEntrypointChunk() - .getAllReferencedChunks(); - const dependOnEntries = []; - for (const dep of dependOn) { - const dependency = this.entrypoints.get(dep); - if (!dependency) { - throw new Error( - `Entry ${name} depends on ${dep}, but this entry was not found` - ); - } - if (referencedChunks.has(dependency.getEntrypointChunk())) { - const err = new WebpackError( - `Entrypoints '${name}' and '${dep}' use 'dependOn' to depend on each other in a circular way.` - ); - const entryChunk = entry.getEntrypointChunk(); - err.chunk = entryChunk; - this.errors.push(err); - entry.setRuntimeChunk(entryChunk); - continue outer; - } - dependOnEntries.push(dependency); - } - for (const dependency of dependOnEntries) { - connectChunkGroupParentAndChild(dependency, entry); - } - } else if (runtime) { - const entry = this.entrypoints.get(name); - let chunk = this.namedChunks.get(runtime); - if (chunk) { - if (!runtimeChunks.has(chunk)) { - const err = - new WebpackError(`Entrypoint '${name}' has a 'runtime' option which points to another entrypoint named '${runtime}'. -It's not valid to use other entrypoints as runtime chunk. -Did you mean to use 'dependOn: ${JSON.stringify( - runtime - )}' instead to allow using entrypoint '${name}' within the runtime of entrypoint '${runtime}'? For this '${runtime}' must always be loaded when '${name}' is used. -Or do you want to use the entrypoints '${name}' and '${runtime}' independently on the same page with a shared runtime? In this case give them both the same value for the 'runtime' option. It must be a name not already used by an entrypoint.`); - const entryChunk = entry.getEntrypointChunk(); - err.chunk = entryChunk; - this.errors.push(err); - entry.setRuntimeChunk(entryChunk); - continue; - } - } else { - chunk = this.addChunk(runtime); - chunk.preventIntegration = true; - runtimeChunks.add(chunk); - } - entry.unshiftChunk(chunk); - chunk.addGroup(entry); - entry.setRuntimeChunk(chunk); - } - } - buildChunkGraph(this, chunkGraphInit); - this.hooks.afterChunks.call(this.chunks); - this.logger.timeEnd("create chunks"); + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true*/ +(function clone(exports) { + 'use strict'; - this.logger.time("optimize"); - this.hooks.optimize.call(); + var Syntax, + VisitorOption, + VisitorKeys, + BREAK, + SKIP, + REMOVE; - while (this.hooks.optimizeModules.call(this.modules)) { - /* empty */ - } - this.hooks.afterOptimizeModules.call(this.modules); + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } - while (this.hooks.optimizeChunks.call(this.chunks, this.chunkGroups)) { - /* empty */ - } - this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups); + // based on LLVM libc++ upper_bound / lower_bound + // MIT License - this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => { - if (err) { - return finalCallback( - makeWebpackError(err, "Compilation.hooks.optimizeTree") - ); - } + function upperBound(array, func) { + var diff, len, i, current; - this.hooks.afterOptimizeTree.call(this.chunks, this.modules); + len = array.length; + i = 0; - this.hooks.optimizeChunkModules.callAsync( - this.chunks, - this.modules, - err => { - if (err) { - return finalCallback( - makeWebpackError(err, "Compilation.hooks.optimizeChunkModules") - ); - } + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } - this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules); + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportExpression: 'ImportExpression', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; - const shouldRecord = this.hooks.shouldRecord.call() !== false; + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportExpression: ['source'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: ['key', 'value'], + RestElement: [ 'argument' ], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; - this.hooks.reviveModules.call(this.modules, this.records); - this.hooks.beforeModuleIds.call(this.modules); - this.hooks.moduleIds.call(this.modules); - this.hooks.optimizeModuleIds.call(this.modules); - this.hooks.afterOptimizeModuleIds.call(this.modules); + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; - this.hooks.reviveChunks.call(this.chunks, this.records); - this.hooks.beforeChunkIds.call(this.chunks); - this.hooks.chunkIds.call(this.chunks); - this.hooks.optimizeChunkIds.call(this.chunks); - this.hooks.afterOptimizeChunkIds.call(this.chunks); + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; - this.assignRuntimeIds(); + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } - this.logger.time("compute affected modules with chunk graph"); - this._computeAffectedModulesWithChunkGraph(); - this.logger.timeEnd("compute affected modules with chunk graph"); + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; - this.sortItemsWithChunkIds(); + Reference.prototype.remove = function remove() { + if (Array.isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; - if (shouldRecord) { - this.hooks.recordModules.call(this.modules, this.records); - this.hooks.recordChunks.call(this.chunks, this.records); - } + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } - this.hooks.optimizeCodeGeneration.call(this.modules); - this.logger.timeEnd("optimize"); + function Controller() { } - this.logger.time("module hashing"); - this.hooks.beforeModuleHash.call(); - this.createModuleHashes(); - this.hooks.afterModuleHash.call(); - this.logger.timeEnd("module hashing"); + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; - this.logger.time("code generation"); - this.hooks.beforeCodeGeneration.call(); - this.codeGeneration(err => { - if (err) { - return finalCallback(err); - } - this.hooks.afterCodeGeneration.call(); - this.logger.timeEnd("code generation"); + function addToPath(result, path) { + if (Array.isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } - this.logger.time("runtime requirements"); - this.hooks.beforeRuntimeRequirements.call(); - this.processRuntimeRequirements(); - this.hooks.afterRuntimeRequirements.call(); - this.logger.timeEnd("runtime requirements"); + // root node + if (!this.__current.path) { + return null; + } - this.logger.time("hashing"); - this.hooks.beforeHash.call(); - const codeGenerationJobs = this.createHash(); - this.hooks.afterHash.call(); - this.logger.timeEnd("hashing"); + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; - this._runCodeGenerationJobs(codeGenerationJobs, err => { - if (err) { - return finalCallback(err); - } + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; - if (shouldRecord) { - this.logger.time("record hash"); - this.hooks.recordHash.call(this.records); - this.logger.timeEnd("record hash"); - } + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; - this.logger.time("module assets"); - this.clearAssets(); + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } - this.hooks.beforeModuleAssets.call(); - this.createModuleAssets(); - this.logger.timeEnd("module assets"); + return result; + }; - const cont = () => { - this.logger.time("process assets"); - this.hooks.processAssets.callAsync(this.assets, err => { - if (err) { - return finalCallback( - makeWebpackError(err, "Compilation.hooks.processAssets") - ); - } - this.hooks.afterProcessAssets.call(this.assets); - this.logger.timeEnd("process assets"); - this.assets = this._backCompat - ? soonFrozenObjectDeprecation( - this.assets, - "Compilation.assets", - "DEP_WEBPACK_COMPILATION_ASSETS", - `BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation. - Do changes to assets earlier, e. g. in Compilation.hooks.processAssets. - Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.` - ) - : Object.freeze(this.assets); + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; - this.summarizeDependencies(); - if (shouldRecord) { - this.hooks.record.call(this, this.records); - } + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; - if (this.hooks.needAdditionalSeal.call()) { - this.unseal(); - return this.seal(callback); - } - return this.hooks.afterSeal.callAsync(err => { - if (err) { - return finalCallback( - makeWebpackError(err, "Compilation.hooks.afterSeal") - ); - } - this.fileSystemInfo.logStatistics(); - finalCallback(); - }); - }); - }; + result = undefined; - this.logger.time("create chunk assets"); - if (this.hooks.shouldGenerateChunkAssets.call() !== false) { - this.hooks.beforeChunkAssets.call(); - this.createChunkAssets(err => { - this.logger.timeEnd("create chunk assets"); - if (err) { - return finalCallback(err); - } - cont(); - }); - } else { - this.logger.timeEnd("create chunk assets"); - cont(); - } - }); - }); - } - ); - }); - } + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; - /** - * @param {Module} module module to report from - * @param {DependenciesBlock[]} blocks blocks to report from - * @returns {boolean} true, when it has warnings or errors - */ - reportDependencyErrorsAndWarnings(module, blocks) { - let hasProblems = false; - for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { - const block = blocks[indexBlock]; - const dependencies = block.dependencies; + return result; + }; - for (let indexDep = 0; indexDep < dependencies.length; indexDep++) { - const d = dependencies[indexDep]; + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; - const warnings = d.getWarnings(this.moduleGraph); - if (warnings) { - for (let indexWar = 0; indexWar < warnings.length; indexWar++) { - const w = warnings[indexWar]; + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; - const warning = new ModuleDependencyWarning(module, w, d.loc); - this.warnings.push(warning); - hasProblems = true; - } - } - const errors = d.getErrors(this.moduleGraph); - if (errors) { - for (let indexErr = 0; indexErr < errors.length; indexErr++) { - const e = errors[indexErr]; + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; - const error = new ModuleDependencyError(module, e, d.loc); - this.errors.push(error); - hasProblems = true; - } - } - } + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; - if (this.reportDependencyErrorsAndWarnings(module, block.blocks)) - hasProblems = true; - } - return hasProblems; - } + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } - codeGeneration(callback) { - const { chunkGraph } = this; - this.codeGenerationResults = new CodeGenerationResults( - this.outputOptions.hashFunction - ); - /** @type {{module: Module, hash: string, runtime: RuntimeSpec, runtimes: RuntimeSpec[]}[]} */ - const jobs = []; - for (const module of this.modules) { - const runtimes = chunkGraph.getModuleRuntimes(module); - if (runtimes.size === 1) { - for (const runtime of runtimes) { - const hash = chunkGraph.getModuleHash(module, runtime); - jobs.push({ module, hash, runtime, runtimes: [runtime] }); - } - } else if (runtimes.size > 1) { - /** @type {Map} */ - const map = new Map(); - for (const runtime of runtimes) { - const hash = chunkGraph.getModuleHash(module, runtime); - const job = map.get(hash); - if (job === undefined) { - const newJob = { module, hash, runtime, runtimes: [runtime] }; - jobs.push(newJob); - map.set(hash, newJob); - } else { - job.runtimes.push(runtime); - } - } - } - } + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); + } + }; - this._runCodeGenerationJobs(jobs, callback); - } + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } - _runCodeGenerationJobs(jobs, callback) { - let statModulesFromCache = 0; - let statModulesGenerated = 0; - const { chunkGraph, moduleGraph, dependencyTemplates, runtimeTemplate } = - this; - const results = this.codeGenerationResults; - const errors = []; - /** @type {Set | undefined} */ - let notCodeGeneratedModules = undefined; - const runIteration = () => { - let delayedJobs = []; - let delayedModules = new Set(); - asyncLib.eachLimit( - jobs, - this.options.parallelism, - (job, callback) => { - const { module } = job; - const { codeGenerationDependencies } = module; - if (codeGenerationDependencies !== undefined) { - if ( - notCodeGeneratedModules === undefined || - codeGenerationDependencies.some(dep => { - const referencedModule = moduleGraph.getModule(dep); - return notCodeGeneratedModules.has(referencedModule); - }) - ) { - delayedJobs.push(job); - delayedModules.add(module); - return callback(); - } - } - const { hash, runtime, runtimes } = job; - this._codeGenerationModule( - module, - runtime, - runtimes, - hash, - dependencyTemplates, - chunkGraph, - moduleGraph, - runtimeTemplate, - errors, - results, - (err, codeGenerated) => { - if (codeGenerated) statModulesGenerated++; - else statModulesFromCache++; - callback(err); - } - ); - }, - err => { - if (err) return callback(err); - if (delayedJobs.length > 0) { - if (delayedJobs.length === jobs.length) { - return callback( - new Error( - `Unable to make progress during code generation because of circular code generation dependency: ${Array.from( - delayedModules, - m => m.identifier() - ).join(", ")}` - ) - ); - } - jobs = delayedJobs; - delayedJobs = []; - notCodeGeneratedModules = delayedModules; - delayedModules = new Set(); - return runIteration(); - } - if (errors.length > 0) { - errors.sort( - compareSelect(err => err.module, compareModulesByIdentifier) - ); - for (const error of errors) { - this.errors.push(error); - } - } - this.logger.log( - `${Math.round( - (100 * statModulesGenerated) / - (statModulesGenerated + statModulesFromCache) - )}% code generated (${statModulesGenerated} generated, ${statModulesFromCache} from cache)` - ); - callback(); - } - ); - }; - runIteration(); - } + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } - /** - * @param {Module} module module - * @param {RuntimeSpec} runtime runtime - * @param {RuntimeSpec[]} runtimes runtimes - * @param {string} hash hash - * @param {DependencyTemplates} dependencyTemplates dependencyTemplates - * @param {ChunkGraph} chunkGraph chunkGraph - * @param {ModuleGraph} moduleGraph moduleGraph - * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate - * @param {WebpackError[]} errors errors - * @param {CodeGenerationResults} results results - * @param {function(WebpackError=, boolean=): void} callback callback - */ - _codeGenerationModule( - module, - runtime, - runtimes, - hash, - dependencyTemplates, - chunkGraph, - moduleGraph, - runtimeTemplate, - errors, - results, - callback - ) { - let codeGenerated = false; - const cache = new MultiItemCache( - runtimes.map(runtime => - this._codeGenerationCache.getItemCache( - `${module.identifier()}|${getRuntimeKey(runtime)}`, - `${hash}|${dependencyTemplates.getHash()}` - ) - ) - ); - cache.get((err, cachedResult) => { - if (err) return callback(err); - let result; - if (!cachedResult) { - try { - codeGenerated = true; - this.codeGeneratedModules.add(module); - result = module.codeGeneration({ - chunkGraph, - moduleGraph, - dependencyTemplates, - runtimeTemplate, - runtime, - codeGenerationResults: results - }); - } catch (err) { - errors.push(new CodeGenerationError(module, err)); - result = cachedResult = { - sources: new Map(), - runtimeRequirements: null - }; - } - } else { - result = cachedResult; - } - for (const runtime of runtimes) { - results.add(module, runtime, result); - } - if (!cachedResult) { - cache.store(result, err => callback(err, codeGenerated)); - } else { - callback(null, codeGenerated); - } - }); - } + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; - _getChunkGraphEntries() { - /** @type {Set} */ - const treeEntries = new Set(); - for (const ep of this.entrypoints.values()) { - const chunk = ep.getRuntimeChunk(); - if (chunk) treeEntries.add(chunk); - } - for (const ep of this.asyncEntrypoints) { - const chunk = ep.getRuntimeChunk(); - if (chunk) treeEntries.add(chunk); - } - return treeEntries; - } + this.__initialize(root, visitor); - /** - * @param {Object} options options - * @param {ChunkGraph=} options.chunkGraph the chunk graph - * @param {Iterable=} options.modules modules - * @param {Iterable=} options.chunks chunks - * @param {CodeGenerationResults=} options.codeGenerationResults codeGenerationResults - * @param {Iterable=} options.chunkGraphEntries chunkGraphEntries - * @returns {void} - */ - processRuntimeRequirements({ - chunkGraph = this.chunkGraph, - modules = this.modules, - chunks = this.chunks, - codeGenerationResults = this.codeGenerationResults, - chunkGraphEntries = this._getChunkGraphEntries() - } = {}) { - const context = { chunkGraph, codeGenerationResults }; - const { moduleMemCaches2 } = this; - this.logger.time("runtime requirements.modules"); - const additionalModuleRuntimeRequirements = - this.hooks.additionalModuleRuntimeRequirements; - const runtimeRequirementInModule = this.hooks.runtimeRequirementInModule; - for (const module of modules) { - if (chunkGraph.getNumberOfModuleChunks(module) > 0) { - const memCache = moduleMemCaches2 && moduleMemCaches2.get(module); - for (const runtime of chunkGraph.getModuleRuntimes(module)) { - if (memCache) { - const cached = memCache.get( - `moduleRuntimeRequirements-${getRuntimeKey(runtime)}` - ); - if (cached !== undefined) { - if (cached !== null) { - chunkGraph.addModuleRuntimeRequirements( - module, - runtime, - cached, - false - ); - } - continue; - } - } - let set; - const runtimeRequirements = - codeGenerationResults.getRuntimeRequirements(module, runtime); - if (runtimeRequirements && runtimeRequirements.size > 0) { - set = new Set(runtimeRequirements); - } else if (additionalModuleRuntimeRequirements.isUsed()) { - set = new Set(); - } else { - if (memCache) { - memCache.set( - `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, - null - ); - } - continue; - } - additionalModuleRuntimeRequirements.call(module, set, context); + sentinel = {}; - for (const r of set) { - const hook = runtimeRequirementInModule.get(r); - if (hook !== undefined) hook.call(module, set, context); - } - if (set.size === 0) { - if (memCache) { - memCache.set( - `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, - null - ); - } - } else { - if (memCache) { - memCache.set( - `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, - set - ); - chunkGraph.addModuleRuntimeRequirements( - module, - runtime, - set, - false - ); - } else { - chunkGraph.addModuleRuntimeRequirements(module, runtime, set); - } - } - } - } - } - this.logger.timeEnd("runtime requirements.modules"); + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; - this.logger.time("runtime requirements.chunks"); - for (const chunk of chunks) { - const set = new Set(); - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( - module, - chunk.runtime - ); - for (const r of runtimeRequirements) set.add(r); - } - this.hooks.additionalChunkRuntimeRequirements.call(chunk, set, context); + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); - for (const r of set) { - this.hooks.runtimeRequirementInChunk.for(r).call(chunk, set, context); - } + while (worklist.length) { + element = worklist.pop(); - chunkGraph.addChunkRuntimeRequirements(chunk, set); - } - this.logger.timeEnd("runtime requirements.chunks"); + if (element === sentinel) { + element = leavelist.pop(); - this.logger.time("runtime requirements.entries"); - for (const treeEntry of chunkGraphEntries) { - const set = new Set(); - for (const chunk of treeEntry.getAllReferencedChunks()) { - const runtimeRequirements = - chunkGraph.getChunkRuntimeRequirements(chunk); - for (const r of runtimeRequirements) set.add(r); - } + ret = this.__execute(visitor.leave, element); - this.hooks.additionalTreeRuntimeRequirements.call( - treeEntry, - set, - context - ); + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } - for (const r of set) { - this.hooks.runtimeRequirementInTree - .for(r) - .call(treeEntry, set, context); - } + if (element.node) { - chunkGraph.addTreeRuntimeRequirements(treeEntry, set); - } - this.logger.timeEnd("runtime requirements.entries"); - } + ret = this.__execute(visitor.enter, element); - // TODO webpack 6 make chunkGraph argument non-optional - /** - * @param {Chunk} chunk target chunk - * @param {RuntimeModule} module runtime module - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {void} - */ - addRuntimeModule(chunk, module, chunkGraph = this.chunkGraph) { - // Deprecated ModuleGraph association - if (this._backCompat) - ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); + if (this.__state === BREAK || ret === BREAK) { + return; + } - // add it to the list - this.modules.add(module); - this._modules.set(module.identifier(), module); + worklist.push(sentinel); + leavelist.push(element); - // connect to the chunk graph - chunkGraph.connectChunkAndModule(chunk, module); - chunkGraph.connectChunkAndRuntimeModule(chunk, module); - if (module.fullHash) { - chunkGraph.addFullHashModuleToChunk(chunk, module); - } else if (module.dependentHash) { - chunkGraph.addDependentHashModuleToChunk(chunk, module); - } + if (this.__state === SKIP || ret === SKIP) { + continue; + } - // attach runtime module - module.attach(this, chunk, chunkGraph); + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } - // Setup internals - const exportsInfo = this.moduleGraph.getExportsInfo(module); - exportsInfo.setHasProvideInfo(); - if (typeof chunk.runtime === "string") { - exportsInfo.setUsedForSideEffectsOnly(chunk.runtime); - } else if (chunk.runtime === undefined) { - exportsInfo.setUsedForSideEffectsOnly(undefined); - } else { - for (const runtime of chunk.runtime) { - exportsInfo.setUsedForSideEffectsOnly(runtime); - } - } - chunkGraph.addModuleRuntimeRequirements( - module, - chunk.runtime, - new Set([RuntimeGlobals.requireScope]) - ); + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } - // runtime modules don't need ids - chunkGraph.setModuleId(module, ""); + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; - // Call hook - this.hooks.runtimeModule.call(module, chunk); - } + Controller.prototype.replace = function replace(root, visitor) { + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; - /** - * If `module` is passed, `loc` and `request` must also be passed. - * @param {string | ChunkGroupOptions} groupOptions options for the chunk group - * @param {Module=} module the module the references the chunk group - * @param {DependencyLocation=} loc the location from with the chunk group is referenced (inside of module) - * @param {string=} request the request from which the the chunk group is referenced - * @returns {ChunkGroup} the new or existing chunk group - */ - addChunkInGroup(groupOptions, module, loc, request) { - if (typeof groupOptions === "string") { - groupOptions = { name: groupOptions }; - } - const name = groupOptions.name; + function removeElem(element) { + var i, + key, + nextElem, + parent; - if (name) { - const chunkGroup = this.namedChunkGroups.get(name); - if (chunkGroup !== undefined) { - chunkGroup.addOptions(groupOptions); - if (module) { - chunkGroup.addOrigin(module, loc, request); - } - return chunkGroup; - } - } - const chunkGroup = new ChunkGroup(groupOptions); - if (module) chunkGroup.addOrigin(module, loc, request); - const chunk = this.addChunk(name); + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; - connectChunkGroupAndChunk(chunkGroup, chunk); + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } - this.chunkGroups.push(chunkGroup); - if (name) { - this.namedChunkGroups.set(name, chunkGroup); - } - return chunkGroup; - } + this.__initialize(root, visitor); - /** - * @param {EntryOptions} options options for the entrypoint - * @param {Module} module the module the references the chunk group - * @param {DependencyLocation} loc the location from with the chunk group is referenced (inside of module) - * @param {string} request the request from which the the chunk group is referenced - * @returns {Entrypoint} the new or existing entrypoint - */ - addAsyncEntrypoint(options, module, loc, request) { - const name = options.name; - if (name) { - const entrypoint = this.namedChunkGroups.get(name); - if (entrypoint instanceof Entrypoint) { - if (entrypoint !== undefined) { - if (module) { - entrypoint.addOrigin(module, loc, request); - } - return entrypoint; - } - } else if (entrypoint) { - throw new Error( - `Cannot add an async entrypoint with the name '${name}', because there is already an chunk group with this name` - ); - } - } - const chunk = this.addChunk(name); - if (options.filename) { - chunk.filenameTemplate = options.filename; - } - const entrypoint = new Entrypoint(options, false); - entrypoint.setRuntimeChunk(chunk); - entrypoint.setEntrypointChunk(chunk); - if (name) { - this.namedChunkGroups.set(name, entrypoint); - } - this.chunkGroups.push(entrypoint); - this.asyncEntrypoints.push(entrypoint); - connectChunkGroupAndChunk(entrypoint, chunk); - if (module) { - entrypoint.addOrigin(module, loc, request); - } - return entrypoint; - } + sentinel = {}; - /** - * This method first looks to see if a name is provided for a new chunk, - * and first looks to see if any named chunks already exist and reuse that chunk instead. - * - * @param {string=} name optional chunk name to be provided - * @returns {Chunk} create a chunk (invoked during seal event) - */ - addChunk(name) { - if (name) { - const chunk = this.namedChunks.get(name); - if (chunk !== undefined) { - return chunk; - } - } - const chunk = new Chunk(name, this._backCompat); - this.chunks.add(chunk); - if (this._backCompat) - ChunkGraph.setChunkGraphForChunk(chunk, this.chunkGraph); - if (name) { - this.namedChunks.set(name, chunk); - } - return chunk; - } + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; - /** - * @deprecated - * @param {Module} module module to assign depth - * @returns {void} - */ - assignDepth(module) { - const moduleGraph = this.moduleGraph; + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); - const queue = new Set([module]); - let depth; + while (worklist.length) { + element = worklist.pop(); - moduleGraph.setDepth(module, 0); + if (element === sentinel) { + element = leavelist.pop(); - /** - * @param {Module} module module for processing - * @returns {void} - */ - const processModule = module => { - if (!moduleGraph.setDepthIfLower(module, depth)) return; - queue.add(module); - }; + target = this.__execute(visitor.leave, element); - for (module of queue) { - queue.delete(module); - depth = moduleGraph.getDepth(module) + 1; + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } - for (const connection of moduleGraph.getOutgoingConnections(module)) { - const refModule = connection.module; - if (refModule) { - processModule(refModule); - } - } - } - } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } - /** - * @param {Set} modules module to assign depth - * @returns {void} - */ - assignDepths(modules) { - const moduleGraph = this.moduleGraph; + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } - /** @type {Set} */ - const queue = new Set(modules); - queue.add(1); - let depth = 0; + target = this.__execute(visitor.enter, element); - let i = 0; - for (const module of queue) { - i++; - if (typeof module === "number") { - depth = module; - if (queue.size === i) return; - queue.add(depth + 1); - } else { - moduleGraph.setDepth(module, depth); - for (const { module: refModule } of moduleGraph.getOutgoingConnections( - module - )) { - if (refModule) { - queue.add(refModule); - } - } - } - } - } + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } - /** - * @param {Dependency} dependency the dependency - * @param {RuntimeSpec} runtime the runtime - * @returns {(string[] | ReferencedExport)[]} referenced exports - */ - getDependencyReferencedExports(dependency, runtime) { - const referencedExports = dependency.getReferencedExports( - this.moduleGraph, - runtime - ); - return this.hooks.dependencyReferencedExports.call( - referencedExports, - dependency, - runtime - ); - } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } - /** - * - * @param {Module} module module relationship for removal - * @param {DependenciesBlockLike} block //TODO: good description - * @returns {void} - */ - removeReasonsOfDependencyBlock(module, block) { - if (block.blocks) { - for (const b of block.blocks) { - this.removeReasonsOfDependencyBlock(module, b); - } - } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } - if (block.dependencies) { - for (const dep of block.dependencies) { - const originalModule = this.moduleGraph.getModule(dep); - if (originalModule) { - this.moduleGraph.removeConnection(dep); + // node may be null + node = element.node; + if (!node) { + continue; + } - if (this.chunkGraph) { - for (const chunk of this.chunkGraph.getModuleChunks( - originalModule - )) { - this.patchChunksAfterReasonRemoval(originalModule, chunk); - } - } - } - } - } - } + worklist.push(sentinel); + leavelist.push(element); - /** - * @param {Module} module module to patch tie - * @param {Chunk} chunk chunk to patch tie - * @returns {void} - */ - patchChunksAfterReasonRemoval(module, chunk) { - if (!module.hasReasons(this.moduleGraph, chunk.runtime)) { - this.removeReasonsOfDependencyBlock(module, module); - } - if (!module.hasReasonForChunk(chunk, this.moduleGraph, this.chunkGraph)) { - if (this.chunkGraph.isModuleInChunk(module, chunk)) { - this.chunkGraph.disconnectChunkAndModule(chunk, module); - this.removeChunkFromDependencies(module, chunk); - } - } - } + if (this.__state === SKIP || target === SKIP) { + continue; + } - /** - * - * @param {DependenciesBlock} block block tie for Chunk - * @param {Chunk} chunk chunk to remove from dep - * @returns {void} - */ - removeChunkFromDependencies(block, chunk) { - /** - * @param {Dependency} d dependency to (maybe) patch up - */ - const iteratorDependency = d => { - const depModule = this.moduleGraph.getModule(d); - if (!depModule) { - return; - } - this.patchChunksAfterReasonRemoval(depModule, chunk); - }; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } - const blocks = block.blocks; - for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { - const asyncBlock = blocks[indexBlock]; - const chunkGroup = this.chunkGraph.getBlockChunkGroup(asyncBlock); - // Grab all chunks from the first Block's AsyncDepBlock - const chunks = chunkGroup.chunks; - // For each chunk in chunkGroup - for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { - const iteratedChunk = chunks[indexChunk]; - chunkGroup.removeChunk(iteratedChunk); - // Recurse - this.removeChunkFromDependencies(block, iteratedChunk); - } - } + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } - if (block.dependencies) { - for (const dep of block.dependencies) iteratorDependency(dep); - } - } + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } - assignRuntimeIds() { - const { chunkGraph } = this; - const processEntrypoint = ep => { - const runtime = ep.options.runtime || ep.name; - const chunk = ep.getRuntimeChunk(); - chunkGraph.setRuntimeId(runtime, chunk.id); - }; - for (const ep of this.entrypoints.values()) { - processEntrypoint(ep); - } - for (const ep of this.asyncEntrypoints) { - processEntrypoint(ep); - } - } + return outer.root; + }; - sortItemsWithChunkIds() { - for (const chunkGroup of this.chunkGroups) { - chunkGroup.sortItems(); - } + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } - this.errors.sort(compareErrors); - this.warnings.sort(compareErrors); - this.children.sort(byNameOrHash); - } + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } - summarizeDependencies() { - for ( - let indexChildren = 0; - indexChildren < this.children.length; - indexChildren++ - ) { - const child = this.children[indexChildren]; + function extendCommentRange(comment, tokens) { + var target; - this.fileDependencies.addAll(child.fileDependencies); - this.contextDependencies.addAll(child.contextDependencies); - this.missingDependencies.addAll(child.missingDependencies); - this.buildDependencies.addAll(child.buildDependencies); - } + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); - for (const module of this.modules) { - module.addCacheDependencies( - this.fileDependencies, - this.contextDependencies, - this.missingDependencies, - this.buildDependencies - ); - } - } + comment.extendedRange = [comment.range[0], comment.range[1]]; - createModuleHashes() { - let statModulesHashed = 0; - let statModulesFromCache = 0; - const { chunkGraph, runtimeTemplate, moduleMemCaches2 } = this; - const { hashFunction, hashDigest, hashDigestLength } = this.outputOptions; - for (const module of this.modules) { - const memCache = moduleMemCaches2 && moduleMemCaches2.get(module); - for (const runtime of chunkGraph.getModuleRuntimes(module)) { - if (memCache) { - const digest = memCache.get(`moduleHash-${getRuntimeKey(runtime)}`); - if (digest !== undefined) { - chunkGraph.setModuleHashes( - module, - runtime, - digest, - digest.substr(0, hashDigestLength) - ); - statModulesFromCache++; - continue; - } - } - statModulesHashed++; - const digest = this._createModuleHash( - module, - chunkGraph, - runtime, - hashFunction, - runtimeTemplate, - hashDigest, - hashDigestLength - ); - if (memCache) { - memCache.set(`moduleHash-${getRuntimeKey(runtime)}`, digest); - } - } - } - this.logger.log( - `${statModulesHashed} modules hashed, ${statModulesFromCache} from cache (${ - Math.round( - (100 * (statModulesHashed + statModulesFromCache)) / this.modules.size - ) / 100 - } variants per module in average)` - ); - } + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } - _createModuleHash( - module, - chunkGraph, - runtime, - hashFunction, - runtimeTemplate, - hashDigest, - hashDigestLength - ) { - const moduleHash = createHash(hashFunction); - module.updateHash(moduleHash, { - chunkGraph, - runtime, - runtimeTemplate - }); - const moduleHashDigest = /** @type {string} */ ( - moduleHash.digest(hashDigest) - ); - chunkGraph.setModuleHashes( - module, - runtime, - moduleHashDigest, - moduleHashDigest.substr(0, hashDigestLength) - ); - return moduleHashDigest; - } + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } - createHash() { - this.logger.time("hashing: initialize hash"); - const chunkGraph = this.chunkGraph; - const runtimeTemplate = this.runtimeTemplate; - const outputOptions = this.outputOptions; - const hashFunction = outputOptions.hashFunction; - const hashDigest = outputOptions.hashDigest; - const hashDigestLength = outputOptions.hashDigestLength; - const hash = createHash(hashFunction); - if (outputOptions.hashSalt) { - hash.update(outputOptions.hashSalt); - } - this.logger.timeEnd("hashing: initialize hash"); - if (this.children.length > 0) { - this.logger.time("hashing: hash child compilations"); - for (const child of this.children) { - hash.update(child.hash); - } - this.logger.timeEnd("hashing: hash child compilations"); - } - if (this.warnings.length > 0) { - this.logger.time("hashing: hash warnings"); - for (const warning of this.warnings) { - hash.update(`${warning.message}`); - } - this.logger.timeEnd("hashing: hash warnings"); - } - if (this.errors.length > 0) { - this.logger.time("hashing: hash errors"); - for (const error of this.errors) { - hash.update(`${error.message}`); - } - this.logger.timeEnd("hashing: hash errors"); - } + return comment; + } - this.logger.time("hashing: sort chunks"); - /* - * all non-runtime chunks need to be hashes first, - * since runtime chunk might use their hashes. - * runtime chunks need to be hashed in the correct order - * since they may depend on each other (for async entrypoints). - * So we put all non-runtime chunks first and hash them in any order. - * And order runtime chunks according to referenced between each other. - * Chunks need to be in deterministic order since we add hashes to full chunk - * during these hashing. - */ - /** @type {Chunk[]} */ - const unorderedRuntimeChunks = []; - /** @type {Chunk[]} */ - const otherChunks = []; - for (const c of this.chunks) { - if (c.hasRuntime()) { - unorderedRuntimeChunks.push(c); - } else { - otherChunks.push(c); - } - } - unorderedRuntimeChunks.sort(byId); - otherChunks.sort(byId); + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; - /** @typedef {{ chunk: Chunk, referencedBy: RuntimeChunkInfo[], remaining: number }} RuntimeChunkInfo */ - /** @type {Map} */ - const runtimeChunksMap = new Map(); - for (const chunk of unorderedRuntimeChunks) { - runtimeChunksMap.set(chunk, { - chunk, - referencedBy: [], - remaining: 0 - }); - } - let remaining = 0; - for (const info of runtimeChunksMap.values()) { - for (const other of new Set( - Array.from(info.chunk.getAllReferencedAsyncEntrypoints()).map( - e => e.chunks[e.chunks.length - 1] - ) - )) { - const otherInfo = runtimeChunksMap.get(other); - otherInfo.referencedBy.push(info); - info.remaining++; - remaining++; - } - } - /** @type {Chunk[]} */ - const runtimeChunks = []; - for (const info of runtimeChunksMap.values()) { - if (info.remaining === 0) { - runtimeChunks.push(info.chunk); - } - } - // If there are any references between chunks - // make sure to follow these chains - if (remaining > 0) { - const readyChunks = []; - for (const chunk of runtimeChunks) { - const hasFullHashModules = - chunkGraph.getNumberOfChunkFullHashModules(chunk) !== 0; - const info = runtimeChunksMap.get(chunk); - for (const otherInfo of info.referencedBy) { - if (hasFullHashModules) { - chunkGraph.upgradeDependentToFullHashModules(otherInfo.chunk); - } - remaining--; - if (--otherInfo.remaining === 0) { - readyChunks.push(otherInfo.chunk); - } - } - if (readyChunks.length > 0) { - // This ensures deterministic ordering, since referencedBy is non-deterministic - readyChunks.sort(byId); - for (const c of readyChunks) runtimeChunks.push(c); - readyChunks.length = 0; - } - } - } - // If there are still remaining references we have cycles and want to create a warning - if (remaining > 0) { - let circularRuntimeChunkInfo = []; - for (const info of runtimeChunksMap.values()) { - if (info.remaining !== 0) { - circularRuntimeChunkInfo.push(info); - } - } - circularRuntimeChunkInfo.sort(compareSelect(i => i.chunk, byId)); - const err = - new WebpackError(`Circular dependency between chunks with runtime (${Array.from( - circularRuntimeChunkInfo, - c => c.chunk.name || c.chunk.id - ).join(", ")}) -This prevents using hashes of each other and should be avoided.`); - err.chunk = circularRuntimeChunkInfo[0].chunk; - this.warnings.push(err); - for (const i of circularRuntimeChunkInfo) runtimeChunks.push(i.chunk); - } - this.logger.timeEnd("hashing: sort chunks"); + if (!tree.range) { + throw new Error('attachComments needs range information'); + } - const fullHashChunks = new Set(); - /** @type {{module: Module, hash: string, runtime: RuntimeSpec, runtimes: RuntimeSpec[]}[]} */ - const codeGenerationJobs = []; - /** @type {Map>} */ - const codeGenerationJobsMap = new Map(); + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } - const processChunk = chunk => { - // Last minute module hash generation for modules that depend on chunk hashes - this.logger.time("hashing: hash runtime modules"); - const runtime = chunk.runtime; - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - if (!chunkGraph.hasModuleHashes(module, runtime)) { - const hash = this._createModuleHash( - module, - chunkGraph, - runtime, - hashFunction, - runtimeTemplate, - hashDigest, - hashDigestLength - ); - let hashMap = codeGenerationJobsMap.get(hash); - if (hashMap) { - const moduleJob = hashMap.get(module); - if (moduleJob) { - moduleJob.runtimes.push(runtime); - continue; - } - } else { - hashMap = new Map(); - codeGenerationJobsMap.set(hash, hashMap); - } - const job = { - module, - hash, - runtime, - runtimes: [runtime] - }; - hashMap.set(module, job); - codeGenerationJobs.push(job); - } - } - this.logger.timeAggregate("hashing: hash runtime modules"); - this.logger.time("hashing: hash chunks"); - const chunkHash = createHash(hashFunction); - try { - if (outputOptions.hashSalt) { - chunkHash.update(outputOptions.hashSalt); - } - chunk.updateHash(chunkHash, chunkGraph); - this.hooks.chunkHash.call(chunk, chunkHash, { - chunkGraph, - moduleGraph: this.moduleGraph, - runtimeTemplate: this.runtimeTemplate - }); - const chunkHashDigest = /** @type {string} */ ( - chunkHash.digest(hashDigest) - ); - hash.update(chunkHashDigest); - chunk.hash = chunkHashDigest; - chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); - const fullHashModules = - chunkGraph.getChunkFullHashModulesIterable(chunk); - if (fullHashModules) { - fullHashChunks.add(chunk); - } else { - this.hooks.contentHash.call(chunk); - } - } catch (err) { - this.errors.push(new ChunkRenderError(chunk, "", err)); - } - this.logger.timeAggregate("hashing: hash chunks"); - }; - otherChunks.forEach(processChunk); - for (const chunk of runtimeChunks) processChunk(chunk); + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } - this.logger.timeAggregateEnd("hashing: hash runtime modules"); - this.logger.timeAggregateEnd("hashing: hash chunks"); - this.logger.time("hashing: hash digest"); - this.hooks.fullHash.call(hash); - this.fullHash = /** @type {string} */ (hash.digest(hashDigest)); - this.hash = this.fullHash.substr(0, hashDigestLength); - this.logger.timeEnd("hashing: hash digest"); + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; - this.logger.time("hashing: process full hash modules"); - for (const chunk of fullHashChunks) { - for (const module of chunkGraph.getChunkFullHashModulesIterable(chunk)) { - const moduleHash = createHash(hashFunction); - module.updateHash(moduleHash, { - chunkGraph, - runtime: chunk.runtime, - runtimeTemplate - }); - const moduleHashDigest = /** @type {string} */ ( - moduleHash.digest(hashDigest) - ); - const oldHash = chunkGraph.getModuleHash(module, chunk.runtime); - chunkGraph.setModuleHashes( - module, - chunk.runtime, - moduleHashDigest, - moduleHashDigest.substr(0, hashDigestLength) - ); - codeGenerationJobsMap.get(oldHash).get(module).hash = moduleHashDigest; - } - const chunkHash = createHash(hashFunction); - chunkHash.update(chunk.hash); - chunkHash.update(this.hash); - const chunkHashDigest = /** @type {string} */ ( - chunkHash.digest(hashDigest) - ); - chunk.hash = chunkHashDigest; - chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); - this.hooks.contentHash.call(chunk); - } - this.logger.timeEnd("hashing: process full hash modules"); - return codeGenerationJobs; - } + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } - /** - * @param {string} file file name - * @param {Source} source asset source - * @param {AssetInfo} assetInfo extra asset information - * @returns {void} - */ - emitAsset(file, source, assetInfo = {}) { - if (this.assets[file]) { - if (!isSourceEqual(this.assets[file], source)) { - this.errors.push( - new WebpackError( - `Conflict: Multiple assets emit different content to the same filename ${file}` - ) - ); - this.assets[file] = source; - this._setAssetInfo(file, assetInfo); - return; - } - const oldInfo = this.assetsInfo.get(file); - const newInfo = Object.assign({}, oldInfo, assetInfo); - this._setAssetInfo(file, newInfo, oldInfo); - return; - } - this.assets[file] = source; - this._setAssetInfo(file, assetInfo, undefined); - } + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } - _setAssetInfo(file, newInfo, oldInfo = this.assetsInfo.get(file)) { - if (newInfo === undefined) { - this.assetsInfo.delete(file); - } else { - this.assetsInfo.set(file, newInfo); - } - const oldRelated = oldInfo && oldInfo.related; - const newRelated = newInfo && newInfo.related; - if (oldRelated) { - for (const key of Object.keys(oldRelated)) { - const remove = name => { - const relatedIn = this._assetsRelatedIn.get(name); - if (relatedIn === undefined) return; - const entry = relatedIn.get(key); - if (entry === undefined) return; - entry.delete(file); - if (entry.size !== 0) return; - relatedIn.delete(key); - if (relatedIn.size === 0) this._assetsRelatedIn.delete(name); - }; - const entry = oldRelated[key]; - if (Array.isArray(entry)) { - entry.forEach(remove); - } else if (entry) { - remove(entry); - } - } - } - if (newRelated) { - for (const key of Object.keys(newRelated)) { - const add = name => { - let relatedIn = this._assetsRelatedIn.get(name); - if (relatedIn === undefined) { - this._assetsRelatedIn.set(name, (relatedIn = new Map())); - } - let entry = relatedIn.get(key); - if (entry === undefined) { - relatedIn.set(key, (entry = new Set())); - } - entry.add(file); - }; - const entry = newRelated[key]; - if (Array.isArray(entry)) { - entry.forEach(add); - } else if (entry) { - add(entry); - } - } - } - } + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } - /** - * @param {string} file file name - * @param {Source | function(Source): Source} newSourceOrFunction new asset source or function converting old to new - * @param {AssetInfo | function(AssetInfo | undefined): AssetInfo} assetInfoUpdateOrFunction new asset info or function converting old to new - */ - updateAsset( - file, - newSourceOrFunction, - assetInfoUpdateOrFunction = undefined - ) { - if (!this.assets[file]) { - throw new Error( - `Called Compilation.updateAsset for not existing filename ${file}` - ); - } - if (typeof newSourceOrFunction === "function") { - this.assets[file] = newSourceOrFunction(this.assets[file]); - } else { - this.assets[file] = newSourceOrFunction; - } - if (assetInfoUpdateOrFunction !== undefined) { - const oldInfo = this.assetsInfo.get(file) || EMPTY_ASSET_INFO; - if (typeof assetInfoUpdateOrFunction === "function") { - this._setAssetInfo(file, assetInfoUpdateOrFunction(oldInfo), oldInfo); - } else { - this._setAssetInfo( - file, - cachedCleverMerge(oldInfo, assetInfoUpdateOrFunction), - oldInfo - ); - } - } - } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); - renameAsset(file, newFile) { - const source = this.assets[file]; - if (!source) { - throw new Error( - `Called Compilation.renameAsset for not existing filename ${file}` - ); - } - if (this.assets[newFile]) { - if (!isSourceEqual(this.assets[file], source)) { - this.errors.push( - new WebpackError( - `Conflict: Called Compilation.renameAsset for already existing filename ${newFile} with different content` - ) - ); - } - } - const assetInfo = this.assetsInfo.get(file); - // Update related in all other assets - const relatedInInfo = this._assetsRelatedIn.get(file); - if (relatedInInfo) { - for (const [key, assets] of relatedInInfo) { - for (const name of assets) { - const info = this.assetsInfo.get(name); - if (!info) continue; - const related = info.related; - if (!related) continue; - const entry = related[key]; - let newEntry; - if (Array.isArray(entry)) { - newEntry = entry.map(x => (x === file ? newFile : x)); - } else if (entry === file) { - newEntry = newFile; - } else continue; - this.assetsInfo.set(name, { - ...info, - related: { - ...related, - [key]: newEntry - } - }); - } - } - } - this._setAssetInfo(file, undefined, assetInfo); - this._setAssetInfo(newFile, assetInfo); - delete this.assets[file]; - this.assets[newFile] = source; - for (const chunk of this.chunks) { - { - const size = chunk.files.size; - chunk.files.delete(file); - if (size !== chunk.files.size) { - chunk.files.add(newFile); - } - } - { - const size = chunk.auxiliaryFiles.size; - chunk.auxiliaryFiles.delete(file); - if (size !== chunk.auxiliaryFiles.size) { - chunk.auxiliaryFiles.add(newFile); - } - } - } - } + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; - /** - * @param {string} file file name - */ - deleteAsset(file) { - if (!this.assets[file]) { - return; - } - delete this.assets[file]; - const assetInfo = this.assetsInfo.get(file); - this._setAssetInfo(file, undefined, assetInfo); - const related = assetInfo && assetInfo.related; - if (related) { - for (const key of Object.keys(related)) { - const checkUsedAndDelete = file => { - if (!this._assetsRelatedIn.has(file)) { - this.deleteAsset(file); - } - }; - const items = related[key]; - if (Array.isArray(items)) { - items.forEach(checkUsedAndDelete); - } else if (items) { - checkUsedAndDelete(items); - } - } - } - // TODO If this becomes a performance problem - // store a reverse mapping from asset to chunk - for (const chunk of this.chunks) { - chunk.files.delete(file); - chunk.auxiliaryFiles.delete(file); - } - } + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } - getAssets() { - /** @type {Readonly[]} */ - const array = []; - for (const assetName of Object.keys(this.assets)) { - if (Object.prototype.hasOwnProperty.call(this.assets, assetName)) { - array.push({ - name: assetName, - source: this.assets[assetName], - info: this.assetsInfo.get(assetName) || EMPTY_ASSET_INFO - }); - } - } - return array; - } + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } - /** - * @param {string} name the name of the asset - * @returns {Readonly | undefined} the asset or undefined when not found - */ - getAsset(name) { - if (!Object.prototype.hasOwnProperty.call(this.assets, name)) - return undefined; - return { - name, - source: this.assets[name], - info: this.assetsInfo.get(name) || EMPTY_ASSET_INFO - }; - } + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } - clearAssets() { - for (const chunk of this.chunks) { - chunk.files.clear(); - chunk.auxiliaryFiles.clear(); - } - } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); - createModuleAssets() { - const { chunkGraph } = this; - for (const module of this.modules) { - if (module.buildInfo.assets) { - const assetsInfo = module.buildInfo.assetsInfo; - for (const assetName of Object.keys(module.buildInfo.assets)) { - const fileName = this.getPath(assetName, { - chunkGraph: this.chunkGraph, - module - }); - for (const chunk of chunkGraph.getModuleChunksIterable(module)) { - chunk.auxiliaryFiles.add(fileName); - } - this.emitAsset( - fileName, - module.buildInfo.assets[assetName], - assetsInfo ? assetsInfo.get(assetName) : undefined - ); - this.hooks.moduleAsset.call(module, fileName); - } - } - } - } + return tree; + } - /** - * @param {RenderManifestOptions} options options object - * @returns {RenderManifestEntry[]} manifest entries - */ - getRenderManifest(options) { - return this.hooks.renderManifest.call([], options); - } + exports.version = (__webpack_require__(15535)/* .version */ .i8); + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { return clone({}); }; - /** - * @param {Callback} callback signals when the call finishes - * @returns {void} - */ - createChunkAssets(callback) { - const outputOptions = this.outputOptions; - const cachedSourceMap = new WeakMap(); - /** @type {Map} */ - const alreadyWrittenFiles = new Map(); + return exports; +}(exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ - asyncLib.forEachLimit( - this.chunks, - 15, - (chunk, callback) => { - /** @type {RenderManifestEntry[]} */ - let manifest; - try { - manifest = this.getRenderManifest({ - chunk, - hash: this.hash, - fullHash: this.fullHash, - outputOptions, - codeGenerationResults: this.codeGenerationResults, - moduleTemplates: this.moduleTemplates, - dependencyTemplates: this.dependencyTemplates, - chunkGraph: this.chunkGraph, - moduleGraph: this.moduleGraph, - runtimeTemplate: this.runtimeTemplate - }); - } catch (err) { - this.errors.push(new ChunkRenderError(chunk, "", err)); - return callback(); - } - asyncLib.forEach( - manifest, - (fileManifest, callback) => { - const ident = fileManifest.identifier; - const usedHash = fileManifest.hash; - const assetCacheItem = this._assetsCache.getItemCache( - ident, - usedHash - ); +/***/ }), - assetCacheItem.get((err, sourceFromCache) => { - /** @type {string | function(PathData, AssetInfo=): string} */ - let filenameTemplate; - /** @type {string} */ - let file; - /** @type {AssetInfo} */ - let assetInfo; +/***/ 86140: +/***/ (function(module) { - let inTry = true; - const errorAndCallback = err => { - const filename = - file || - (typeof file === "string" - ? file - : typeof filenameTemplate === "string" - ? filenameTemplate - : ""); +module.exports = function (glob, opts) { + if (typeof glob !== 'string') { + throw new TypeError('Expected a string'); + } - this.errors.push(new ChunkRenderError(chunk, filename, err)); - inTry = false; - return callback(); - }; + var str = String(glob); - try { - if ("filename" in fileManifest) { - file = fileManifest.filename; - assetInfo = fileManifest.info; - } else { - filenameTemplate = fileManifest.filenameTemplate; - const pathAndInfo = this.getPathWithInfo( - filenameTemplate, - fileManifest.pathOptions - ); - file = pathAndInfo.path; - assetInfo = fileManifest.info - ? { - ...pathAndInfo.info, - ...fileManifest.info - } - : pathAndInfo.info; - } + // The regexp we are building, as a string. + var reStr = ""; - if (err) { - return errorAndCallback(err); - } + // Whether we are matching so called "extended" globs (like bash) and should + // support single character matching, matching ranges of characters, group + // matching, etc. + var extended = opts ? !!opts.extended : false; - let source = sourceFromCache; + // When globstar is _false_ (default), '/foo/*' is translated a regexp like + // '^\/foo\/.*$' which will match any string beginning with '/foo/' + // When globstar is _true_, '/foo/*' is translated to regexp like + // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT + // which does not have a '/' to the right of it. + // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but + // these will not '/foo/bar/baz', '/foo/bar/baz.txt' + // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when + // globstar is _false_ + var globstar = opts ? !!opts.globstar : false; - // check if the same filename was already written by another chunk - const alreadyWritten = alreadyWrittenFiles.get(file); - if (alreadyWritten !== undefined) { - if (alreadyWritten.hash !== usedHash) { - inTry = false; - return callback( - new WebpackError( - `Conflict: Multiple chunks emit assets to the same filename ${file}` + - ` (chunks ${alreadyWritten.chunk.id} and ${chunk.id})` - ) - ); - } else { - source = alreadyWritten.source; - } - } else if (!source) { - // render the asset - source = fileManifest.render(); + // If we are doing extended matching, this boolean is true when we are inside + // a group (eg {*.html,*.js}), and false otherwise. + var inGroup = false; - // Ensure that source is a cached source to avoid additional cost because of repeated access - if (!(source instanceof CachedSource)) { - const cacheEntry = cachedSourceMap.get(source); - if (cacheEntry) { - source = cacheEntry; - } else { - const cachedSource = new CachedSource(source); - cachedSourceMap.set(source, cachedSource); - source = cachedSource; - } - } - } - this.emitAsset(file, source, assetInfo); - if (fileManifest.auxiliary) { - chunk.auxiliaryFiles.add(file); - } else { - chunk.files.add(file); - } - this.hooks.chunkAsset.call(chunk, file); - alreadyWrittenFiles.set(file, { - hash: usedHash, - source, - chunk - }); - if (source !== sourceFromCache) { - assetCacheItem.store(source, err => { - if (err) return errorAndCallback(err); - inTry = false; - return callback(); - }); - } else { - inTry = false; - callback(); - } - } catch (err) { - if (!inTry) throw err; - errorAndCallback(err); - } - }); - }, - callback - ); - }, - callback - ); - } + // RegExp flags (eg "i" ) to pass in to RegExp constructor. + var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; - /** - * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash - * @param {PathData} data context data - * @returns {string} interpolated path - */ - getPath(filename, data = {}) { - if (!data.hash) { - data = { - hash: this.hash, - ...data - }; - } - return this.getAssetPath(filename, data); - } + var c; + for (var i = 0, len = str.length; i < len; i++) { + c = str[i]; - /** - * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash - * @param {PathData} data context data - * @returns {{ path: string, info: AssetInfo }} interpolated path and asset info - */ - getPathWithInfo(filename, data = {}) { - if (!data.hash) { - data = { - hash: this.hash, - ...data - }; - } - return this.getAssetPathWithInfo(filename, data); - } + switch (c) { + case "/": + case "$": + case "^": + case "+": + case ".": + case "(": + case ")": + case "=": + case "!": + case "|": + reStr += "\\" + c; + break; - /** - * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash - * @param {PathData} data context data - * @returns {string} interpolated path - */ - getAssetPath(filename, data) { - return this.hooks.assetPath.call( - typeof filename === "function" ? filename(data) : filename, - data, - undefined - ); - } + case "?": + if (extended) { + reStr += "."; + break; + } - /** - * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash - * @param {PathData} data context data - * @returns {{ path: string, info: AssetInfo }} interpolated path and asset info - */ - getAssetPathWithInfo(filename, data) { - const assetInfo = {}; - // TODO webpack 5: refactor assetPath hook to receive { path, info } object - const newPath = this.hooks.assetPath.call( - typeof filename === "function" ? filename(data, assetInfo) : filename, - data, - assetInfo - ); - return { path: newPath, info: assetInfo }; - } + case "[": + case "]": + if (extended) { + reStr += c; + break; + } - getWarnings() { - return this.hooks.processWarnings.call(this.warnings); - } + case "{": + if (extended) { + inGroup = true; + reStr += "("; + break; + } - getErrors() { - return this.hooks.processErrors.call(this.errors); - } + case "}": + if (extended) { + inGroup = false; + reStr += ")"; + break; + } - /** - * This function allows you to run another instance of webpack inside of webpack however as - * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins - * from parent (or top level compiler) and creates a child Compilation - * - * @param {string} name name of the child compiler - * @param {OutputOptions=} outputOptions // Need to convert config schema to types for this - * @param {Array=} plugins webpack plugins that will be applied - * @returns {Compiler} creates a child Compiler instance - */ - createChildCompiler(name, outputOptions, plugins) { - const idx = this.childrenCounters[name] || 0; - this.childrenCounters[name] = idx + 1; - return this.compiler.createChildCompiler( - this, - name, - idx, - outputOptions, - plugins - ); - } + case ",": + if (inGroup) { + reStr += "|"; + break; + } + reStr += "\\" + c; + break; - /** - * @param {Module} module the module - * @param {ExecuteModuleOptions} options options - * @param {ExecuteModuleCallback} callback callback - */ - executeModule(module, options, callback) { - // Aggregate all referenced modules and ensure they are ready - const modules = new Set([module]); - processAsyncTree( - modules, - 10, - /** - * @param {Module} module the module - * @param {function(Module): void} push push more jobs - * @param {Callback} callback callback - * @returns {void} - */ - (module, push, callback) => { - this.buildQueue.waitFor(module, err => { - if (err) return callback(err); - this.processDependenciesQueue.waitFor(module, err => { - if (err) return callback(err); - for (const { module: m } of this.moduleGraph.getOutgoingConnections( - module - )) { - const size = modules.size; - modules.add(m); - if (modules.size !== size) push(m); - } - callback(); - }); - }); - }, - err => { - if (err) return callback(err); + case "*": + // Move over all consecutive "*"'s. + // Also store the previous and next characters + var prevChar = str[i - 1]; + var starCount = 1; + while(str[i + 1] === "*") { + starCount++; + i++; + } + var nextChar = str[i + 1]; - // Create new chunk graph, chunk and entrypoint for the build time execution - const chunkGraph = new ChunkGraph( - this.moduleGraph, - this.outputOptions.hashFunction - ); - const runtime = "build time"; - const { hashFunction, hashDigest, hashDigestLength } = - this.outputOptions; - const runtimeTemplate = this.runtimeTemplate; + if (!globstar) { + // globstar is disabled, so treat any number of "*" as one + reStr += ".*"; + } else { + // globstar is enabled, so determine if this is a globstar segment + var isGlobstar = starCount > 1 // multiple "*"'s + && (prevChar === "/" || prevChar === undefined) // from the start of the segment + && (nextChar === "/" || nextChar === undefined) // to the end of the segment - const chunk = new Chunk("build time chunk", this._backCompat); - chunk.id = chunk.name; - chunk.ids = [chunk.id]; - chunk.runtime = runtime; + if (isGlobstar) { + // it's a globstar, so match zero or more path segments + reStr += "((?:[^/]*(?:\/|$))*)"; + i++; // move over the "/" + } else { + // it's not a globstar, so only match one path segment + reStr += "([^/]*)"; + } + } + break; - const entrypoint = new Entrypoint({ - runtime, - chunkLoading: false, - ...options.entryOptions - }); - chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint); - connectChunkGroupAndChunk(entrypoint, chunk); - entrypoint.setRuntimeChunk(chunk); - entrypoint.setEntrypointChunk(chunk); + default: + reStr += c; + } + } - const chunks = new Set([chunk]); + // When regexp 'g' flag is specified don't + // constrain the regular expression with ^ & $ + if (!flags || !~flags.indexOf('g')) { + reStr = "^" + reStr + "$"; + } - // Assign ids to modules and modules to the chunk - for (const module of modules) { - const id = module.identifier(); - chunkGraph.setModuleId(module, id); - chunkGraph.connectChunkAndModule(chunk, module); - } + return new RegExp(reStr, flags); +}; - // Hash modules - for (const module of modules) { - this._createModuleHash( - module, - chunkGraph, - runtime, - hashFunction, - runtimeTemplate, - hashDigest, - hashDigestLength - ); - } - const codeGenerationResults = new CodeGenerationResults( - this.outputOptions.hashFunction - ); - /** @type {WebpackError[]} */ - const errors = []; - /** - * @param {Module} module the module - * @param {Callback} callback callback - * @returns {void} - */ - const codeGen = (module, callback) => { - this._codeGenerationModule( - module, - runtime, - [runtime], - chunkGraph.getModuleHash(module, runtime), - this.dependencyTemplates, - chunkGraph, - this.moduleGraph, - runtimeTemplate, - errors, - codeGenerationResults, - (err, codeGenerated) => { - callback(err); - } - ); - }; +/***/ }), - const reportErrors = () => { - if (errors.length > 0) { - errors.sort( - compareSelect(err => err.module, compareModulesByIdentifier) - ); - for (const error of errors) { - this.errors.push(error); - } - errors.length = 0; - } - }; +/***/ 89132: +/***/ (function(module) { - // Generate code for all aggregated modules - asyncLib.eachLimit(modules, 10, codeGen, err => { - if (err) return callback(err); - reportErrors(); +"use strict"; - // for backward-compat temporary set the chunk graph - // TODO webpack 6 - const old = this.chunkGraph; - this.chunkGraph = chunkGraph; - this.processRuntimeRequirements({ - chunkGraph, - modules, - chunks, - codeGenerationResults, - chunkGraphEntries: chunks - }); - this.chunkGraph = old; - const runtimeModules = - chunkGraph.getChunkRuntimeModulesIterable(chunk); +module.exports = clone - // Hash runtime modules - for (const module of runtimeModules) { - modules.add(module); - this._createModuleHash( - module, - chunkGraph, - runtime, - hashFunction, - runtimeTemplate, - hashDigest, - hashDigestLength - ); - } - - // Generate code for all runtime modules - asyncLib.eachLimit(runtimeModules, 10, codeGen, err => { - if (err) return callback(err); - reportErrors(); +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +} - /** @type {Map} */ - const moduleArgumentsMap = new Map(); - /** @type {Map} */ - const moduleArgumentsById = new Map(); +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj - /** @type {ExecuteModuleResult["fileDependencies"]} */ - const fileDependencies = new LazySet(); - /** @type {ExecuteModuleResult["contextDependencies"]} */ - const contextDependencies = new LazySet(); - /** @type {ExecuteModuleResult["missingDependencies"]} */ - const missingDependencies = new LazySet(); - /** @type {ExecuteModuleResult["buildDependencies"]} */ - const buildDependencies = new LazySet(); + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) - /** @type {ExecuteModuleResult["assets"]} */ - const assets = new Map(); + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) - let cacheable = true; + return copy +} - /** @type {ExecuteModuleContext} */ - const context = { - assets, - __webpack_require__: undefined, - chunk, - chunkGraph - }; - // Prepare execution - asyncLib.eachLimit( - modules, - 10, - (module, callback) => { - const codeGenerationResult = codeGenerationResults.get( - module, - runtime - ); - /** @type {ExecuteModuleArgument} */ - const moduleArgument = { - module, - codeGenerationResult, - preparedInfo: undefined, - moduleObject: undefined - }; - moduleArgumentsMap.set(module, moduleArgument); - moduleArgumentsById.set(module.identifier(), moduleArgument); - module.addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ); - if (module.buildInfo.cacheable === false) { - cacheable = false; - } - if (module.buildInfo && module.buildInfo.assets) { - const { assets: moduleAssets, assetsInfo } = module.buildInfo; - for (const assetName of Object.keys(moduleAssets)) { - assets.set(assetName, { - source: moduleAssets[assetName], - info: assetsInfo ? assetsInfo.get(assetName) : undefined - }); - } - } - this.hooks.prepareModuleExecution.callAsync( - moduleArgument, - context, - callback - ); - }, - err => { - if (err) return callback(err); +/***/ }), - let exports; - try { - const { - strictModuleErrorHandling, - strictModuleExceptionHandling - } = this.outputOptions; - const __nested_webpack_require_152290__ = id => { - const cached = moduleCache[id]; - if (cached !== undefined) { - if (cached.error) throw cached.error; - return cached.exports; - } - const moduleArgument = moduleArgumentsById.get(id); - return __webpack_require_module__(moduleArgument, id); - }; - const interceptModuleExecution = (__nested_webpack_require_152290__[ - RuntimeGlobals.interceptModuleExecution.replace( - "__webpack_require__.", - "" - ) - ] = []); - const moduleCache = (__nested_webpack_require_152290__[ - RuntimeGlobals.moduleCache.replace( - "__webpack_require__.", - "" - ) - ] = {}); +/***/ 90552: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - context.__webpack_require__ = __nested_webpack_require_152290__; +var fs = __webpack_require__(57147) +var polyfills = __webpack_require__(11290) +var legacy = __webpack_require__(54410) +var clone = __webpack_require__(89132) - /** - * @param {ExecuteModuleArgument} moduleArgument the module argument - * @param {string=} id id - * @returns {any} exports - */ - const __webpack_require_module__ = (moduleArgument, id) => { - var execOptions = { - id, - module: { - id, - exports: {}, - loaded: false, - error: undefined - }, - require: __nested_webpack_require_152290__ - }; - interceptModuleExecution.forEach(handler => - handler(execOptions) - ); - const module = moduleArgument.module; - this.buildTimeExecutedModules.add(module); - const moduleObject = execOptions.module; - moduleArgument.moduleObject = moduleObject; - try { - if (id) moduleCache[id] = moduleObject; +var util = __webpack_require__(73837) - tryRunOrWebpackError( - () => - this.hooks.executeModule.call( - moduleArgument, - context - ), - "Compilation.hooks.executeModule" - ); - moduleObject.loaded = true; - return moduleObject.exports; - } catch (e) { - if (strictModuleExceptionHandling) { - if (id) delete moduleCache[id]; - } else if (strictModuleErrorHandling) { - moduleObject.error = e; - } - if (!e.module) e.module = module; - throw e; - } - }; +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol - for (const runtimeModule of chunkGraph.getChunkRuntimeModulesInOrder( - chunk - )) { - __webpack_require_module__( - moduleArgumentsMap.get(runtimeModule) - ); - } - exports = __nested_webpack_require_152290__(module.identifier()); - } catch (e) { - const err = new WebpackError( - `Execution of module code from module graph (${module.readableIdentifier( - this.requestShortener - )}) failed: ${e.message}` - ); - err.stack = e.stack; - err.module = e.module; - return callback(err); - } +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} - callback(null, { - exports, - assets, - cacheable, - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - }); - } - ); - }); - }); - } - ); - } +function noop () {} - checkConstraints() { - const chunkGraph = this.chunkGraph; +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} - /** @type {Set} */ - const usedIds = new Set(); +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } - for (const module of this.modules) { - if (module.type === "runtime") continue; - const moduleId = chunkGraph.getModuleId(module); - if (moduleId === null) continue; - if (usedIds.has(moduleId)) { - throw new Error(`checkConstraints: duplicate module id ${moduleId}`); - } - usedIds.add(moduleId); - } +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) - for (const chunk of this.chunks) { - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - if (!this.modules.has(module)) { - throw new Error( - "checkConstraints: module in chunk but not in compilation " + - ` ${chunk.debugId} ${module.debugId}` - ); - } - } - for (const module of chunkGraph.getChunkEntryModulesIterable(chunk)) { - if (!this.modules.has(module)) { - throw new Error( - "checkConstraints: entry module in chunk but not in compilation " + - ` ${chunk.debugId} ${module.debugId}` - ); - } - } - } + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } - for (const chunkGroup of this.chunkGroups) { - chunkGroup.checkConstraints(); - } - } -} + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } -/** - * @typedef {Object} FactorizeModuleOptions - * @property {ModuleProfile} currentProfile - * @property {ModuleFactory} factory - * @property {Dependency[]} dependencies - * @property {boolean=} factoryResult return full ModuleFactoryResult instead of only module - * @property {Module | null} originModule - * @property {Partial=} contextInfo - * @property {string=} context - */ + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) -/** - * @param {FactorizeModuleOptions} options options object - * @param {ModuleCallback | ModuleFactoryResultCallback} callback callback - * @returns {void} - */ + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() + } -// Workaround for typescript as it doesn't support function overloading in jsdoc within a class -Compilation.prototype.factorizeModule = /** @type {{ - (options: FactorizeModuleOptions & { factoryResult?: false }, callback: ModuleCallback): void; - (options: FactorizeModuleOptions & { factoryResult: true }, callback: ModuleFactoryResultCallback): void; -}} */ ( - function (options, callback) { - this.factorizeQueue.add(options, callback); - } -); + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) -// Hide from typescript -const compilationPrototype = Compilation.prototype; + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + __webpack_require__(39491).equal(fs[gracefulQueue].length, 0) + }) + } +} -// TODO webpack 6 remove -Object.defineProperty(compilationPrototype, "modifyHash", { - writable: false, - enumerable: false, - configurable: false, - value: () => { - throw new Error( - "Compilation.modifyHash was removed in favor of Compilation.hooks.fullHash" - ); - } -}); +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} -// TODO webpack 6 remove -Object.defineProperty(compilationPrototype, "cache", { - enumerable: false, - configurable: false, - get: util.deprecate( - /** - * @this {Compilation} the compilation - * @returns {Cache} the cache - */ - function () { - return this.compiler.cache; - }, - "Compilation.cache was removed in favor of Compilation.getCache()", - "DEP_WEBPACK_COMPILATION_CACHE" - ), - set: util.deprecate( - v => {}, - "Compilation.cache was removed in favor of Compilation.getCache()", - "DEP_WEBPACK_COMPILATION_CACHE" - ) -}); +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} -/** - * Add additional assets to the compilation. - */ -Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL = -2000; +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch -/** - * Basic preprocessing of assets. - */ -Compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS = -1000; + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null -/** - * Derive new assets from existing assets. - * Existing assets should not be treated as complete. - */ -Compilation.PROCESS_ASSETS_STAGE_DERIVED = -200; + return go$readFile(path, options, cb) -/** - * Add additional sections to existing assets, like a banner or initialization code. - */ -Compilation.PROCESS_ASSETS_STAGE_ADDITIONS = -100; + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } -/** - * Optimize existing assets in a general way. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE = 100; + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null -/** - * Optimize the count of existing assets, e. g. by merging them. - * Only assets of the same type should be merged. - * For assets of different types see PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT = 200; + return go$writeFile(path, data, options, cb) -/** - * Optimize the compatibility of existing assets, e. g. add polyfills or vendor-prefixes. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY = 300; + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } -/** - * Optimize the size of existing assets, e. g. by minimizing or omitting whitespace. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE = 400; + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null -/** - * Add development tooling to assets, e. g. by extracting a SourceMap. - */ -Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING = 500; + return go$appendFile(path, data, options, cb) -/** - * Optimize the count of existing assets, e. g. by inlining assets of into other assets. - * Only assets of different types should be inlined. - * For assets of the same type see PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE = 700; + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } -/** - * Summarize the list of existing assets - * e. g. creating an assets manifest of Service Workers. - */ -Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE = 1000; + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 + } + return go$copyFile(src, dest, flags, cb) -/** - * Optimize the hashes of the assets, e. g. by generating real hashes of the asset content. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH = 2500; + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } -/** - * Optimize the transfer of existing assets, e. g. by preparing a compressed (gzip) file as separate asset. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER = 3000; + var fs$readdir = fs.readdir + fs.readdir = readdir + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null -/** - * Analyse existing assets. - */ -Compilation.PROCESS_ASSETS_STAGE_ANALYSE = 4000; + return go$readdir(path, options, cb) -/** - * Creating assets for reporting purposes. - */ -Compilation.PROCESS_ASSETS_STAGE_REPORT = 5000; + function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (files && files.sort) + files.sort() -module.exports = Compilation; + if (typeof cb === 'function') + cb.call(this, err, files) + } + }) + } + } + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } -/***/ }), + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } -/***/ 70845: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } -const parseJson = __webpack_require__(15235); -const asyncLib = __webpack_require__(78175); -const { - SyncHook, - SyncBailHook, - AsyncParallelHook, - AsyncSeriesHook -} = __webpack_require__(6967); -const { SizeOnlySource } = __webpack_require__(51255); -const webpack = __webpack_require__(91919); -const Cache = __webpack_require__(7592); -const CacheFacade = __webpack_require__(55392); -const ChunkGraph = __webpack_require__(64971); -const Compilation = __webpack_require__(85720); -const ConcurrentCompilationError = __webpack_require__(95735); -const ContextModuleFactory = __webpack_require__(62471); -const ModuleGraph = __webpack_require__(99988); -const NormalModuleFactory = __webpack_require__(68860); -const RequestShortener = __webpack_require__(73406); -const ResolverFactory = __webpack_require__(30217); -const Stats = __webpack_require__(31743); -const Watching = __webpack_require__(84275); -const WebpackError = __webpack_require__(53799); -const { Logger } = __webpack_require__(32597); -const { join, dirname, mkdirp } = __webpack_require__(17139); -const { makePathsRelative } = __webpack_require__(82186); -const { isSourceEqual } = __webpack_require__(41245); + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} Entry */ -/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ -/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./util/WeakTupleMap")} WeakTupleMap */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */ -/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ -/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */ + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } -/** - * @typedef {Object} CompilationParams - * @property {NormalModuleFactory} normalModuleFactory - * @property {ContextModuleFactory} contextModuleFactory - */ + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } -/** - * @template T - * @callback Callback - * @param {(Error | null)=} err - * @param {T=} result - */ + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } -/** - * @callback RunAsChildCallback - * @param {(Error | null)=} err - * @param {Chunk[]=} entries - * @param {Compilation=} compilation - */ + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } -/** - * @typedef {Object} AssetEmittedInfo - * @property {Buffer} content - * @property {Source} source - * @property {Compilation} compilation - * @property {string} outputPath - * @property {string} targetPath - */ + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } -/** - * @param {string[]} array an array - * @returns {boolean} true, if the array is sorted - */ -const isSorted = array => { - for (let i = 1; i < array.length; i++) { - if (array[i - 1] > array[i]) return false; - } - return true; -}; + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null -/** - * @param {Object} obj an object - * @param {string[]} keys the keys of the object - * @returns {Object} the object with properties sorted by property name - */ -const sortObject = (obj, keys) => { - const o = {}; - for (const k of keys.sort()) { - o[k] = obj[k]; - } - return o; -}; + return go$open(path, flags, mode, cb) -/** - * @param {string} filename filename - * @param {string | string[] | undefined} hashes list of hashes - * @returns {boolean} true, if the filename contains any hash - */ -const includesHash = (filename, hashes) => { - if (!hashes) return false; - if (Array.isArray(hashes)) { - return hashes.some(hash => filename.includes(hash)); - } else { - return filename.includes(hashes); - } -}; + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } -class Compiler { - /** - * @param {string} context the compilation path - * @param {WebpackOptions} options options - */ - constructor(context, options = /** @type {WebpackOptions} */ ({})) { - this.hooks = Object.freeze({ - /** @type {SyncHook<[]>} */ - initialize: new SyncHook([]), + return fs +} - /** @type {SyncBailHook<[Compilation], boolean>} */ - shouldEmit: new SyncBailHook(["compilation"]), - /** @type {AsyncSeriesHook<[Stats]>} */ - done: new AsyncSeriesHook(["stats"]), - /** @type {SyncHook<[Stats]>} */ - afterDone: new SyncHook(["stats"]), - /** @type {AsyncSeriesHook<[]>} */ - additionalPass: new AsyncSeriesHook([]), - /** @type {AsyncSeriesHook<[Compiler]>} */ - beforeRun: new AsyncSeriesHook(["compiler"]), - /** @type {AsyncSeriesHook<[Compiler]>} */ - run: new AsyncSeriesHook(["compiler"]), - /** @type {AsyncSeriesHook<[Compilation]>} */ - emit: new AsyncSeriesHook(["compilation"]), - /** @type {AsyncSeriesHook<[string, AssetEmittedInfo]>} */ - assetEmitted: new AsyncSeriesHook(["file", "info"]), - /** @type {AsyncSeriesHook<[Compilation]>} */ - afterEmit: new AsyncSeriesHook(["compilation"]), +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() +} - /** @type {SyncHook<[Compilation, CompilationParams]>} */ - thisCompilation: new SyncHook(["compilation", "params"]), - /** @type {SyncHook<[Compilation, CompilationParams]>} */ - compilation: new SyncHook(["compilation", "params"]), - /** @type {SyncHook<[NormalModuleFactory]>} */ - normalModuleFactory: new SyncHook(["normalModuleFactory"]), - /** @type {SyncHook<[ContextModuleFactory]>} */ - contextModuleFactory: new SyncHook(["contextModuleFactory"]), +// keep track of the timeout between retry() calls +var retryTimer - /** @type {AsyncSeriesHook<[CompilationParams]>} */ - beforeCompile: new AsyncSeriesHook(["params"]), - /** @type {SyncHook<[CompilationParams]>} */ - compile: new SyncHook(["params"]), - /** @type {AsyncParallelHook<[Compilation]>} */ - make: new AsyncParallelHook(["compilation"]), - /** @type {AsyncParallelHook<[Compilation]>} */ - finishMake: new AsyncSeriesHook(["compilation"]), - /** @type {AsyncSeriesHook<[Compilation]>} */ - afterCompile: new AsyncSeriesHook(["compilation"]), +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime + } + } + // call retry to make sure we're actively processing the queue + retry() +} - /** @type {AsyncSeriesHook<[]>} */ - readRecords: new AsyncSeriesHook([]), - /** @type {AsyncSeriesHook<[]>} */ - emitRecords: new AsyncSeriesHook([]), +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined - /** @type {AsyncSeriesHook<[Compiler]>} */ - watchRun: new AsyncSeriesHook(["compiler"]), - /** @type {SyncHook<[Error]>} */ - failed: new SyncHook(["error"]), - /** @type {SyncHook<[string | null, number]>} */ - invalid: new SyncHook(["filename", "changeTime"]), - /** @type {SyncHook<[]>} */ - watchClose: new SyncHook([]), - /** @type {AsyncSeriesHook<[]>} */ - shutdown: new AsyncSeriesHook([]), + if (fs[gracefulQueue].length === 0) + return - /** @type {SyncBailHook<[string, string, any[]], true>} */ - infrastructureLog: new SyncBailHook(["origin", "type", "args"]), + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] - // TODO the following hooks are weirdly located here - // TODO move them for webpack 5 - /** @type {SyncHook<[]>} */ - environment: new SyncHook([]), - /** @type {SyncHook<[]>} */ - afterEnvironment: new SyncHook([]), - /** @type {SyncHook<[Compiler]>} */ - afterPlugins: new SyncHook(["compiler"]), - /** @type {SyncHook<[Compiler]>} */ - afterResolvers: new SyncHook(["compiler"]), - /** @type {SyncBailHook<[string, Entry], boolean>} */ - entryOption: new SyncBailHook(["context", "entry"]) - }); + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) + } + } - this.webpack = webpack; + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) + } +} - /** @type {string=} */ - this.name = undefined; - /** @type {Compilation=} */ - this.parentCompilation = undefined; - /** @type {Compiler} */ - this.root = this; - /** @type {string} */ - this.outputPath = ""; - /** @type {Watching} */ - this.watching = undefined; - /** @type {OutputFileSystem} */ - this.outputFileSystem = null; - /** @type {IntermediateFileSystem} */ - this.intermediateFileSystem = null; - /** @type {InputFileSystem} */ - this.inputFileSystem = null; - /** @type {WatchFileSystem} */ - this.watchFileSystem = null; +/***/ }), - /** @type {string|null} */ - this.recordsInputPath = null; - /** @type {string|null} */ - this.recordsOutputPath = null; - this.records = {}; - /** @type {Set} */ - this.managedPaths = new Set(); - /** @type {Set} */ - this.immutablePaths = new Set(); +/***/ 54410: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {ReadonlySet} */ - this.modifiedFiles = undefined; - /** @type {ReadonlySet} */ - this.removedFiles = undefined; - /** @type {ReadonlyMap} */ - this.fileTimestamps = undefined; - /** @type {ReadonlyMap} */ - this.contextTimestamps = undefined; - /** @type {number} */ - this.fsStartTime = undefined; +var Stream = (__webpack_require__(12781).Stream) - /** @type {ResolverFactory} */ - this.resolverFactory = new ResolverFactory(); +module.exports = legacy - this.infrastructureLogger = undefined; +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } - this.options = options; + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); - this.context = context; + Stream.call(this); - this.requestShortener = new RequestShortener(context, this.root); + var self = this; - this.cache = new Cache(); + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; - /** @type {Map, memCache: WeakTupleMap }> | undefined} */ - this.moduleMemCaches = undefined; + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; - this.compilerPath = ""; + options = options || {}; - /** @type {boolean} */ - this.running = false; + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } - /** @type {boolean} */ - this.idle = false; + if (this.encoding) this.setEncoding(this.encoding); - /** @type {boolean} */ - this.watchMode = false; + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } - this._backCompat = this.options.experiments.backCompat !== false; + if (this.start > this.end) { + throw new Error('start must be <= end'); + } - /** @type {Compilation} */ - this._lastCompilation = undefined; - /** @type {NormalModuleFactory} */ - this._lastNormalModuleFactory = undefined; + this.pos = this.start; + } - /** @private @type {WeakMap }>} */ - this._assetEmittingSourceCache = new WeakMap(); - /** @private @type {Map} */ - this._assetEmittingWrittenFiles = new Map(); - /** @private @type {Set} */ - this._assetEmittingPreviousFiles = new Set(); - } + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } - /** - * @param {string} name cache name - * @returns {CacheFacade} the cache facade instance - */ - getCache(name) { - return new CacheFacade( - this.cache, - `${this.compilerPath}${name}`, - this.options.output.hashFunction - ); - } + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } - /** - * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name - * @returns {Logger} a logger with that name - */ - getInfrastructureLogger(name) { - if (!name) { - throw new TypeError( - "Compiler.getInfrastructureLogger(name) called without a name" - ); - } - return new Logger( - (type, args) => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compiler.getInfrastructureLogger(name) called with a function not returning a name" - ); - } - } - if (this.hooks.infrastructureLog.call(name, type, args) === undefined) { - if (this.infrastructureLogger !== undefined) { - this.infrastructureLogger(name, type, args); - } - } - }, - childName => { - if (typeof name === "function") { - if (typeof childName === "function") { - return this.getInfrastructureLogger(() => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compiler.getInfrastructureLogger(name) called with a function not returning a name" - ); - } - } - if (typeof childName === "function") { - childName = childName(); - if (!childName) { - throw new TypeError( - "Logger.getChildLogger(name) called with a function not returning a name" - ); - } - } - return `${name}/${childName}`; - }); - } else { - return this.getInfrastructureLogger(() => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compiler.getInfrastructureLogger(name) called with a function not returning a name" - ); - } - } - return `${name}/${childName}`; - }); - } - } else { - if (typeof childName === "function") { - return this.getInfrastructureLogger(() => { - if (typeof childName === "function") { - childName = childName(); - if (!childName) { - throw new TypeError( - "Logger.getChildLogger(name) called with a function not returning a name" - ); - } - } - return `${name}/${childName}`; - }); - } else { - return this.getInfrastructureLogger(`${name}/${childName}`); - } - } - } - ); - } + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } - // TODO webpack 6: solve this in a better way - // e.g. move compilation specific info from Modules into ModuleGraph - _cleanupLastCompilation() { - if (this._lastCompilation !== undefined) { - for (const module of this._lastCompilation.modules) { - ChunkGraph.clearChunkGraphForModule(module); - ModuleGraph.clearModuleGraphForModule(module); - module.cleanupForCache(); - } - for (const chunk of this._lastCompilation.chunks) { - ChunkGraph.clearChunkGraphForChunk(chunk); - } - this._lastCompilation = undefined; - } - } + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); - // TODO webpack 6: solve this in a better way - _cleanupLastNormalModuleFactory() { - if (this._lastNormalModuleFactory !== undefined) { - this._lastNormalModuleFactory.cleanupForCache(); - this._lastNormalModuleFactory = undefined; - } - } + Stream.call(this); - /** - * @param {WatchOptions} watchOptions the watcher's options - * @param {Callback} handler signals when the call finishes - * @returns {Watching} a compiler watcher - */ - watch(watchOptions, handler) { - if (this.running) { - return handler(new ConcurrentCompilationError()); - } + this.path = path; + this.fd = null; + this.writable = true; - this.running = true; - this.watchMode = true; - this.watching = new Watching(this, watchOptions, handler); - return this.watching; - } + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; - /** - * @param {Callback} callback signals when the call finishes - * @returns {void} - */ - run(callback) { - if (this.running) { - return callback(new ConcurrentCompilationError()); - } + options = options || {}; - let logger; + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } - const finalCallback = (err, stats) => { - if (logger) logger.time("beginIdle"); - this.idle = true; - this.cache.beginIdle(); - this.idle = true; - if (logger) logger.timeEnd("beginIdle"); - this.running = false; - if (err) { - this.hooks.failed.call(err); - } - if (callback !== undefined) callback(err, stats); - this.hooks.afterDone.call(stats); - }; + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } - const startTime = Date.now(); + this.pos = this.start; + } - this.running = true; + this.busy = false; + this._queue = []; - const onCompiled = (err, compilation) => { - if (err) return finalCallback(err); + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} - if (this.hooks.shouldEmit.call(compilation) === false) { - compilation.startTime = startTime; - compilation.endTime = Date.now(); - const stats = new Stats(compilation); - this.hooks.done.callAsync(stats, err => { - if (err) return finalCallback(err); - return finalCallback(null, stats); - }); - return; - } - process.nextTick(() => { - logger = compilation.getLogger("webpack.Compiler"); - logger.time("emitAssets"); - this.emitAssets(compilation, err => { - logger.timeEnd("emitAssets"); - if (err) return finalCallback(err); +/***/ }), - if (compilation.hooks.needAdditionalPass.call()) { - compilation.needAdditionalPass = true; +/***/ 11290: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - compilation.startTime = startTime; - compilation.endTime = Date.now(); - logger.time("done hook"); - const stats = new Stats(compilation); - this.hooks.done.callAsync(stats, err => { - logger.timeEnd("done hook"); - if (err) return finalCallback(err); +var constants = __webpack_require__(22057) - this.hooks.additionalPass.callAsync(err => { - if (err) return finalCallback(err); - this.compile(onCompiled); - }); - }); - return; - } +var origCwd = process.cwd +var cwd = null - logger.time("emitRecords"); - this.emitRecords(err => { - logger.timeEnd("emitRecords"); - if (err) return finalCallback(err); +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - compilation.startTime = startTime; - compilation.endTime = Date.now(); - logger.time("done hook"); - const stats = new Stats(compilation); - this.hooks.done.callAsync(stats, err => { - logger.timeEnd("done hook"); - if (err) return finalCallback(err); - this.cache.storeBuildDependencies( - compilation.buildDependencies, - err => { - if (err) return finalCallback(err); - return finalCallback(null, stats); - } - ); - }); - }); - }); - }); - }; +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} - const run = () => { - this.hooks.beforeRun.callAsync(this, err => { - if (err) return finalCallback(err); +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) +} - this.hooks.run.callAsync(this, err => { - if (err) return finalCallback(err); +module.exports = patch - this.readRecords(err => { - if (err) return finalCallback(err); +function patch (fs) { + // (re-)implement some things that are known busted or missing. - this.compile(onCompiled); - }); - }); - }); - }; + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } - if (this.idle) { - this.cache.endIdle(err => { - if (err) return finalCallback(err); + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } - this.idle = false; - run(); - }); - } else { - run(); - } - } + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. - /** - * @param {RunAsChildCallback} callback signals when the call finishes - * @returns {void} - */ - runAsChild(callback) { - const startTime = Date.now(); - this.compile((err, compilation) => { - if (err) return callback(err); + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) - this.parentCompilation.children.push(compilation); - for (const { name, source, info } of compilation.getAssets()) { - this.parentCompilation.emitAsset(name, source, info); - } + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) - const entries = []; - for (const ep of compilation.entrypoints.values()) { - entries.push(...ep.chunks); - } + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) - compilation.startTime = startTime; - compilation.endTime = Date.now(); + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) - return callback(null, entries, compilation); - }); - } + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) - purgeInputFileSystem() { - if (this.inputFileSystem && this.inputFileSystem.purge) { - this.inputFileSystem.purge(); - } - } + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) - /** - * @param {Compilation} compilation the compilation - * @param {Callback} callback signals when the assets are emitted - * @returns {void} - */ - emitAssets(compilation, callback) { - let outputPath; + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } - const emitFiles = err => { - if (err) return callback(err); + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. - const assets = compilation.getAssets(); - compilation.assets = { ...compilation.assets }; - /** @type {Map} */ - const caseInsensitiveMap = new Map(); - /** @type {Set} */ - const allTargetPaths = new Set(); - asyncLib.forEachLimit( - assets, - 15, - ({ name: file, source, info }, callback) => { - let targetFile = file; - let immutable = info.immutable; - const queryStringIdx = targetFile.indexOf("?"); - if (queryStringIdx >= 0) { - targetFile = targetFile.substr(0, queryStringIdx); - // We may remove the hash, which is in the query string - // So we recheck if the file is immutable - // This doesn't cover all cases, but immutable is only a performance optimization anyway - immutable = - immutable && - (includesHash(targetFile, info.contenthash) || - includesHash(targetFile, info.chunkhash) || - includesHash(targetFile, info.modulehash) || - includesHash(targetFile, info.fullhash)); - } + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + }})(fs.rename) + } - const writeOut = err => { - if (err) return callback(err); - const targetPath = join( - this.outputFileSystem, - outputPath, - targetFile - ); - allTargetPaths.add(targetPath); + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } - // check if the target file has already been written by this Compiler - const targetFileGeneration = - this._assetEmittingWrittenFiles.get(targetPath); + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) - // create an cache entry for this Source if not already existing - let cacheEntry = this._assetEmittingSourceCache.get(source); - if (cacheEntry === undefined) { - cacheEntry = { - sizeOnlySource: undefined, - writtenTo: new Map() - }; - this._assetEmittingSourceCache.set(source, cacheEntry); - } + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) - let similarEntry; + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } - const checkSimilarFile = () => { - const caseInsensitiveTargetPath = targetPath.toLowerCase(); - similarEntry = caseInsensitiveMap.get(caseInsensitiveTargetPath); - if (similarEntry !== undefined) { - const { path: other, source: otherSource } = similarEntry; - if (isSourceEqual(otherSource, source)) { - // Size may or may not be available at this point. - // If it's not available add to "waiting" list and it will be updated once available - if (similarEntry.size !== undefined) { - updateWithReplacementSource(similarEntry.size); - } else { - if (!similarEntry.waiting) similarEntry.waiting = []; - similarEntry.waiting.push({ file, cacheEntry }); - } - alreadyWritten(); - } else { - const err = - new WebpackError(`Prevent writing to file that only differs in casing or query string from already written file. -This will lead to a race-condition and corrupted files on case-insensitive file systems. -${targetPath} -${other}`); - err.file = file; - callback(err); - } - return true; - } else { - caseInsensitiveMap.set( - caseInsensitiveTargetPath, - (similarEntry = { - path: targetPath, - source, - size: undefined, - waiting: undefined - }) - ); - return false; - } - }; + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - /** - * get the binary (Buffer) content from the Source - * @returns {Buffer} content for the source - */ - const getContent = () => { - if (typeof source.buffer === "function") { - return source.buffer(); - } else { - const bufferOrString = source.source(); - if (Buffer.isBuffer(bufferOrString)) { - return bufferOrString; - } else { - return Buffer.from(bufferOrString, "utf8"); - } - } - }; + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } - const alreadyWritten = () => { - // cache the information that the Source has been already been written to that location - if (targetFileGeneration === undefined) { - const newGeneration = 1; - this._assetEmittingWrittenFiles.set(targetPath, newGeneration); - cacheEntry.writtenTo.set(targetPath, newGeneration); - } else { - cacheEntry.writtenTo.set(targetPath, targetFileGeneration); - } - callback(); - }; + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } - /** - * Write the file to output file system - * @param {Buffer} content content to be written - * @returns {void} - */ - const doWrite = content => { - this.outputFileSystem.writeFile(targetPath, content, err => { - if (err) return callback(err); + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } - // information marker that the asset has been emitted - compilation.emittedAssets.add(file); + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } + } - // cache the information that the Source has been written to that location - const newGeneration = - targetFileGeneration === undefined - ? 1 - : targetFileGeneration + 1; - cacheEntry.writtenTo.set(targetPath, newGeneration); - this._assetEmittingWrittenFiles.set(targetPath, newGeneration); - this.hooks.assetEmitted.callAsync( - file, - { - content, - source, - outputPath, - compilation, - targetPath - }, - callback - ); - }); - }; + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } - const updateWithReplacementSource = size => { - updateFileWithReplacementSource(file, cacheEntry, size); - similarEntry.size = size; - if (similarEntry.waiting !== undefined) { - for (const { file, cacheEntry } of similarEntry.waiting) { - updateFileWithReplacementSource(file, cacheEntry, size); - } - } - }; + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } - const updateFileWithReplacementSource = ( - file, - cacheEntry, - size - ) => { - // Create a replacement resource which only allows to ask for size - // This allows to GC all memory allocated by the Source - // (expect when the Source is stored in any other cache) - if (!cacheEntry.sizeOnlySource) { - cacheEntry.sizeOnlySource = new SizeOnlySource(size); - } - compilation.updateAsset(file, cacheEntry.sizeOnlySource, { - size - }); - }; - const processExistingFile = stats => { - // skip emitting if it's already there and an immutable file - if (immutable) { - updateWithReplacementSource(stats.size); - return alreadyWritten(); - } + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } - const content = getContent(); + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } - updateWithReplacementSource(content.length); + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } - // if it exists and content on disk matches content - // skip writing the same content again - // (to keep mtime and don't trigger watchers) - // for a fast negative match file size is compared first - if (content.length === stats.size) { - compilation.comparedForEmitAssets.add(file); - return this.outputFileSystem.readFile( - targetPath, - (err, existingContent) => { - if ( - err || - !content.equals(/** @type {Buffer} */ (existingContent)) - ) { - return doWrite(content); - } else { - return alreadyWritten(); - } - } - ); - } + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; + } + } - return doWrite(content); - }; + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true - const processMissingFile = () => { - const content = getContent(); + if (er.code === "ENOSYS") + return true - updateWithReplacementSource(content.length); + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } - return doWrite(content); - }; + return false + } +} - // if the target file has already been written - if (targetFileGeneration !== undefined) { - // check if the Source has been written to this target file - const writtenGeneration = cacheEntry.writtenTo.get(targetPath); - if (writtenGeneration === targetFileGeneration) { - // if yes, we may skip writing the file - // if it's already there - // (we assume one doesn't modify files while the Compiler is running, other then removing them) - if (this._assetEmittingPreviousFiles.has(targetPath)) { - // We assume that assets from the last compilation say intact on disk (they are not removed) - compilation.updateAsset(file, cacheEntry.sizeOnlySource, { - size: cacheEntry.sizeOnlySource.size() - }); +/***/ }), - return callback(); - } else { - // Settings immutable will make it accept file content without comparing when file exist - immutable = true; - } - } else if (!immutable) { - if (checkSimilarFile()) return; - // We wrote to this file before which has very likely a different content - // skip comparing and assume content is different for performance - // This case happens often during watch mode. - return processMissingFile(); - } - } +/***/ 15235: +/***/ (function(module) { - if (checkSimilarFile()) return; - if (this.options.output.compareBeforeEmit) { - this.outputFileSystem.stat(targetPath, (err, stats) => { - const exists = !err && stats.isFile(); +"use strict"; - if (exists) { - processExistingFile(stats); - } else { - processMissingFile(); - } - }); - } else { - processMissingFile(); - } - }; - if (targetFile.match(/\/|\\/)) { - const fs = this.outputFileSystem; - const dir = dirname(fs, join(fs, outputPath, targetFile)); - mkdirp(fs, dir, writeOut); - } else { - writeOut(); - } - }, - err => { - // Clear map to free up memory - caseInsensitiveMap.clear(); - if (err) { - this._assetEmittingPreviousFiles.clear(); - return callback(err); - } +module.exports = parseJson +function parseJson (txt, reviver, context) { + context = context || 20 + try { + return JSON.parse(txt, reviver) + } catch (e) { + if (typeof txt !== 'string') { + const isEmptyArray = Array.isArray(txt) && txt.length === 0 + const errorMessage = 'Cannot parse ' + + (isEmptyArray ? 'an empty array' : String(txt)) + throw new TypeError(errorMessage) + } + const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) + const errIdx = syntaxErr + ? +syntaxErr[1] + : e.message.match(/^Unexpected end of JSON.*/i) + ? txt.length - 1 + : null + if (errIdx != null) { + const start = errIdx <= context + ? 0 + : errIdx - context + const end = errIdx + context >= txt.length + ? txt.length + : errIdx + context + e.message += ` while parsing near '${ + start === 0 ? '' : '...' + }${txt.slice(start, end)}${ + end === txt.length ? '' : '...' + }'` + } else { + e.message += ` while parsing '${txt.slice(0, context * 2)}'` + } + throw e + } +} - this._assetEmittingPreviousFiles = allTargetPaths; - this.hooks.afterEmit.callAsync(compilation, err => { - if (err) return callback(err); +/***/ }), - return callback(); - }); - } - ); - }; +/***/ 49448: +/***/ (function(module) { - this.hooks.emit.callAsync(compilation, err => { - if (err) return callback(err); - outputPath = compilation.getPath(this.outputPath, {}); - mkdirp(this.outputFileSystem, outputPath, emitFiles); - }); - } +"use strict"; - /** - * @param {Callback} callback signals when the call finishes - * @returns {void} - */ - emitRecords(callback) { - if (this.hooks.emitRecords.isUsed()) { - if (this.recordsOutputPath) { - asyncLib.parallel( - [ - cb => this.hooks.emitRecords.callAsync(cb), - this._emitRecords.bind(this) - ], - err => callback(err) - ); - } else { - this.hooks.emitRecords.callAsync(callback); - } - } else { - if (this.recordsOutputPath) { - this._emitRecords(callback); - } else { - callback(); - } - } + +class LoadingLoaderError extends Error { + constructor(message) { + super(message); + this.name = "LoaderRunnerError"; + Error.captureStackTrace(this, this.constructor); } +} - /** - * @param {Callback} callback signals when the call finishes - * @returns {void} - */ - _emitRecords(callback) { - const writeFile = () => { - this.outputFileSystem.writeFile( - this.recordsOutputPath, - JSON.stringify( - this.records, - (n, value) => { - if ( - typeof value === "object" && - value !== null && - !Array.isArray(value) - ) { - const keys = Object.keys(value); - if (!isSorted(keys)) { - return sortObject(value, keys); - } - } - return value; - }, - 2 - ), - callback - ); - }; +module.exports = LoadingLoaderError; - const recordsOutputPathDirectory = dirname( - this.outputFileSystem, - this.recordsOutputPath - ); - if (!recordsOutputPathDirectory) { - return writeFile(); - } - mkdirp(this.outputFileSystem, recordsOutputPathDirectory, err => { - if (err) return callback(err); - writeFile(); - }); - } - /** - * @param {Callback} callback signals when the call finishes - * @returns {void} - */ - readRecords(callback) { - if (this.hooks.readRecords.isUsed()) { - if (this.recordsInputPath) { - asyncLib.parallel([ - cb => this.hooks.readRecords.callAsync(cb), - this._readRecords.bind(this) - ]); - } else { - this.records = {}; - this.hooks.readRecords.callAsync(callback); - } - } else { - if (this.recordsInputPath) { - this._readRecords(callback); +/***/ }), + +/***/ 68318: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +var fs = __webpack_require__(57147); +var readFile = fs.readFile.bind(fs); +var loadLoader = __webpack_require__(55102); + +function utf8BufferToString(buf) { + var str = buf.toString("utf-8"); + if(str.charCodeAt(0) === 0xFEFF) { + return str.substr(1); + } else { + return str; + } +} + +const PATH_QUERY_FRAGMENT_REGEXP = /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; + +/** + * @param {string} str the path with query and fragment + * @returns {{ path: string, query: string, fragment: string }} parsed parts + */ +function parsePathQueryFragment(str) { + var match = PATH_QUERY_FRAGMENT_REGEXP.exec(str); + return { + path: match[1].replace(/\0(.)/g, "$1"), + query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "", + fragment: match[3] || "" + }; +} + +function dirname(path) { + if(path === "/") return "/"; + var i = path.lastIndexOf("/"); + var j = path.lastIndexOf("\\"); + var i2 = path.indexOf("/"); + var j2 = path.indexOf("\\"); + var idx = i > j ? i : j; + var idx2 = i > j ? i2 : j2; + if(idx < 0) return path; + if(idx === idx2) return path.substr(0, idx + 1); + return path.substr(0, idx); +} + +function createLoaderObject(loader) { + var obj = { + path: null, + query: null, + fragment: null, + options: null, + ident: null, + normal: null, + pitch: null, + raw: null, + data: null, + pitchExecuted: false, + normalExecuted: false + }; + Object.defineProperty(obj, "request", { + enumerable: true, + get: function() { + return obj.path.replace(/#/g, "\0#") + obj.query.replace(/#/g, "\0#") + obj.fragment; + }, + set: function(value) { + if(typeof value === "string") { + var splittedRequest = parsePathQueryFragment(value); + obj.path = splittedRequest.path; + obj.query = splittedRequest.query; + obj.fragment = splittedRequest.fragment; + obj.options = undefined; + obj.ident = undefined; } else { - this.records = {}; - callback(); + if(!value.loader) + throw new Error("request should be a string or object with loader and options (" + JSON.stringify(value) + ")"); + obj.path = value.loader; + obj.fragment = value.fragment || ""; + obj.type = value.type; + obj.options = value.options; + obj.ident = value.ident; + if(obj.options === null) + obj.query = ""; + else if(obj.options === undefined) + obj.query = ""; + else if(typeof obj.options === "string") + obj.query = "?" + obj.options; + else if(obj.ident) + obj.query = "??" + obj.ident; + else if(typeof obj.options === "object" && obj.options.ident) + obj.query = "??" + obj.options.ident; + else + obj.query = "?" + JSON.stringify(obj.options); } } + }); + obj.request = loader; + if(Object.preventExtensions) { + Object.preventExtensions(obj); } + return obj; +} - /** - * @param {Callback} callback signals when the call finishes - * @returns {void} - */ - _readRecords(callback) { - if (!this.recordsInputPath) { - this.records = {}; - return callback(); +function runSyncOrAsync(fn, context, args, callback) { + var isSync = true; + var isDone = false; + var isError = false; // internal error + var reportedError = false; + context.async = function async() { + if(isDone) { + if(reportedError) return; // ignore + throw new Error("async(): The callback was already called."); } - this.inputFileSystem.stat(this.recordsInputPath, err => { - // It doesn't exist - // We can ignore this. - if (err) return callback(); + isSync = false; + return innerCallback; + }; + var innerCallback = context.callback = function() { + if(isDone) { + if(reportedError) return; // ignore + throw new Error("callback(): The callback was already called."); + } + isDone = true; + isSync = false; + try { + callback.apply(null, arguments); + } catch(e) { + isError = true; + throw e; + } + }; + try { + var result = (function LOADER_EXECUTION() { + return fn.apply(context, args); + }()); + if(isSync) { + isDone = true; + if(result === undefined) + return callback(); + if(result && typeof result === "object" && typeof result.then === "function") { + return result.then(function(r) { + callback(null, r); + }, callback); + } + return callback(null, result); + } + } catch(e) { + if(isError) throw e; + if(isDone) { + // loader is already "done", so we cannot use the callback function + // for better debugging we print the error on the console + if(typeof e === "object" && e.stack) console.error(e.stack); + else console.error(e); + return; + } + isDone = true; + reportedError = true; + callback(e); + } - this.inputFileSystem.readFile(this.recordsInputPath, (err, content) => { - if (err) return callback(err); +} - try { - this.records = parseJson(content.toString("utf-8")); - } catch (e) { - e.message = "Cannot parse records: " + e.message; - return callback(e); - } +function convertArgs(args, raw) { + if(!raw && Buffer.isBuffer(args[0])) + args[0] = utf8BufferToString(args[0]); + else if(raw && typeof args[0] === "string") + args[0] = Buffer.from(args[0], "utf-8"); +} - return callback(); - }); - }); - } +function iteratePitchingLoaders(options, loaderContext, callback) { + // abort after last loader + if(loaderContext.loaderIndex >= loaderContext.loaders.length) + return processResource(options, loaderContext, callback); - /** - * @param {Compilation} compilation the compilation - * @param {string} compilerName the compiler's name - * @param {number} compilerIndex the compiler's index - * @param {OutputOptions=} outputOptions the output options - * @param {WebpackPluginInstance[]=} plugins the plugins to apply - * @returns {Compiler} a child compiler - */ - createChildCompiler( - compilation, - compilerName, - compilerIndex, - outputOptions, - plugins - ) { - const childCompiler = new Compiler(this.context, { - ...this.options, - output: { - ...this.options.output, - ...outputOptions - } - }); - childCompiler.name = compilerName; - childCompiler.outputPath = this.outputPath; - childCompiler.inputFileSystem = this.inputFileSystem; - childCompiler.outputFileSystem = null; - childCompiler.resolverFactory = this.resolverFactory; - childCompiler.modifiedFiles = this.modifiedFiles; - childCompiler.removedFiles = this.removedFiles; - childCompiler.fileTimestamps = this.fileTimestamps; - childCompiler.contextTimestamps = this.contextTimestamps; - childCompiler.fsStartTime = this.fsStartTime; - childCompiler.cache = this.cache; - childCompiler.compilerPath = `${this.compilerPath}${compilerName}|${compilerIndex}|`; - childCompiler._backCompat = this._backCompat; + var currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex]; - const relativeCompilerName = makePathsRelative( - this.context, - compilerName, - this.root - ); - if (!this.records[relativeCompilerName]) { - this.records[relativeCompilerName] = []; - } - if (this.records[relativeCompilerName][compilerIndex]) { - childCompiler.records = this.records[relativeCompilerName][compilerIndex]; - } else { - this.records[relativeCompilerName].push((childCompiler.records = {})); - } + // iterate + if(currentLoaderObject.pitchExecuted) { + loaderContext.loaderIndex++; + return iteratePitchingLoaders(options, loaderContext, callback); + } - childCompiler.parentCompilation = compilation; - childCompiler.root = this.root; - if (Array.isArray(plugins)) { - for (const plugin of plugins) { - plugin.apply(childCompiler); - } + // load loader module + loadLoader(currentLoaderObject, function(err) { + if(err) { + loaderContext.cacheable(false); + return callback(err); } - for (const name in this.hooks) { - if ( - ![ - "make", - "compile", - "emit", - "afterEmit", - "invalid", - "done", - "thisCompilation" - ].includes(name) - ) { - if (childCompiler.hooks[name]) { - childCompiler.hooks[name].taps = this.hooks[name].taps.slice(); + var fn = currentLoaderObject.pitch; + currentLoaderObject.pitchExecuted = true; + if(!fn) return iteratePitchingLoaders(options, loaderContext, callback); + + runSyncOrAsync( + fn, + loaderContext, [loaderContext.remainingRequest, loaderContext.previousRequest, currentLoaderObject.data = {}], + function(err) { + if(err) return callback(err); + var args = Array.prototype.slice.call(arguments, 1); + // Determine whether to continue the pitching process based on + // argument values (as opposed to argument presence) in order + // to support synchronous and asynchronous usages. + var hasArg = args.some(function(value) { + return value !== undefined; + }); + if(hasArg) { + loaderContext.loaderIndex--; + iterateNormalLoaders(options, loaderContext, args, callback); + } else { + iteratePitchingLoaders(options, loaderContext, callback); } } - } - - compilation.hooks.childCompiler.call( - childCompiler, - compilerName, - compilerIndex ); + }); +} - return childCompiler; - } +function processResource(options, loaderContext, callback) { + // set loader index to last loader + loaderContext.loaderIndex = loaderContext.loaders.length - 1; - isChild() { - return !!this.parentCompilation; + var resourcePath = loaderContext.resourcePath; + if(resourcePath) { + options.processResource(loaderContext, resourcePath, function(err, buffer) { + if(err) return callback(err); + options.resourceBuffer = buffer; + iterateNormalLoaders(options, loaderContext, [buffer], callback); + }); + } else { + iterateNormalLoaders(options, loaderContext, [null], callback); } +} - createCompilation(params) { - this._cleanupLastCompilation(); - return (this._lastCompilation = new Compilation(this, params)); - } +function iterateNormalLoaders(options, loaderContext, args, callback) { + if(loaderContext.loaderIndex < 0) + return callback(null, args); - /** - * @param {CompilationParams} params the compilation parameters - * @returns {Compilation} the created compilation - */ - newCompilation(params) { - const compilation = this.createCompilation(params); - compilation.name = this.name; - compilation.records = this.records; - this.hooks.thisCompilation.call(compilation, params); - this.hooks.compilation.call(compilation, params); - return compilation; - } + var currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex]; - createNormalModuleFactory() { - this._cleanupLastNormalModuleFactory(); - const normalModuleFactory = new NormalModuleFactory({ - context: this.options.context, - fs: this.inputFileSystem, - resolverFactory: this.resolverFactory, - options: this.options.module, - associatedObjectForCache: this.root, - layers: this.options.experiments.layers - }); - this._lastNormalModuleFactory = normalModuleFactory; - this.hooks.normalModuleFactory.call(normalModuleFactory); - return normalModuleFactory; + // iterate + if(currentLoaderObject.normalExecuted) { + loaderContext.loaderIndex--; + return iterateNormalLoaders(options, loaderContext, args, callback); } - createContextModuleFactory() { - const contextModuleFactory = new ContextModuleFactory(this.resolverFactory); - this.hooks.contextModuleFactory.call(contextModuleFactory); - return contextModuleFactory; + var fn = currentLoaderObject.normal; + currentLoaderObject.normalExecuted = true; + if(!fn) { + return iterateNormalLoaders(options, loaderContext, args, callback); } - newCompilationParams() { - const params = { - normalModuleFactory: this.createNormalModuleFactory(), - contextModuleFactory: this.createContextModuleFactory() - }; - return params; - } + convertArgs(args, currentLoaderObject.raw); - /** - * @param {Callback} callback signals when the compilation finishes - * @returns {void} - */ - compile(callback) { - const params = this.newCompilationParams(); - this.hooks.beforeCompile.callAsync(params, err => { - if (err) return callback(err); + runSyncOrAsync(fn, loaderContext, args, function(err) { + if(err) return callback(err); - this.hooks.compile.call(params); + var args = Array.prototype.slice.call(arguments, 1); + iterateNormalLoaders(options, loaderContext, args, callback); + }); +} - const compilation = this.newCompilation(params); +exports.getContext = function getContext(resource) { + var path = parsePathQueryFragment(resource).path; + return dirname(path); +}; - const logger = compilation.getLogger("webpack.Compiler"); +exports.runLoaders = function runLoaders(options, callback) { + // read options + var resource = options.resource || ""; + var loaders = options.loaders || []; + var loaderContext = options.context || {}; + var processResource = options.processResource || ((readResource, context, resource, callback) => { + context.addDependency(resource); + readResource(resource, callback); + }).bind(null, options.readResource || readFile); - logger.time("make hook"); - this.hooks.make.callAsync(compilation, err => { - logger.timeEnd("make hook"); - if (err) return callback(err); + // + var splittedResource = resource && parsePathQueryFragment(resource); + var resourcePath = splittedResource ? splittedResource.path : undefined; + var resourceQuery = splittedResource ? splittedResource.query : undefined; + var resourceFragment = splittedResource ? splittedResource.fragment : undefined; + var contextDirectory = resourcePath ? dirname(resourcePath) : null; - logger.time("finish make hook"); - this.hooks.finishMake.callAsync(compilation, err => { - logger.timeEnd("finish make hook"); - if (err) return callback(err); + // execution state + var requestCacheable = true; + var fileDependencies = []; + var contextDependencies = []; + var missingDependencies = []; - process.nextTick(() => { - logger.time("finish compilation"); - compilation.finish(err => { - logger.timeEnd("finish compilation"); - if (err) return callback(err); + // prepare loader objects + loaders = loaders.map(createLoaderObject); - logger.time("seal compilation"); - compilation.seal(err => { - logger.timeEnd("seal compilation"); - if (err) return callback(err); + loaderContext.context = contextDirectory; + loaderContext.loaderIndex = 0; + loaderContext.loaders = loaders; + loaderContext.resourcePath = resourcePath; + loaderContext.resourceQuery = resourceQuery; + loaderContext.resourceFragment = resourceFragment; + loaderContext.async = null; + loaderContext.callback = null; + loaderContext.cacheable = function cacheable(flag) { + if(flag === false) { + requestCacheable = false; + } + }; + loaderContext.dependency = loaderContext.addDependency = function addDependency(file) { + fileDependencies.push(file); + }; + loaderContext.addContextDependency = function addContextDependency(context) { + contextDependencies.push(context); + }; + loaderContext.addMissingDependency = function addMissingDependency(context) { + missingDependencies.push(context); + }; + loaderContext.getDependencies = function getDependencies() { + return fileDependencies.slice(); + }; + loaderContext.getContextDependencies = function getContextDependencies() { + return contextDependencies.slice(); + }; + loaderContext.getMissingDependencies = function getMissingDependencies() { + return missingDependencies.slice(); + }; + loaderContext.clearDependencies = function clearDependencies() { + fileDependencies.length = 0; + contextDependencies.length = 0; + missingDependencies.length = 0; + requestCacheable = true; + }; + Object.defineProperty(loaderContext, "resource", { + enumerable: true, + get: function() { + if(loaderContext.resourcePath === undefined) + return undefined; + return loaderContext.resourcePath.replace(/#/g, "\0#") + loaderContext.resourceQuery.replace(/#/g, "\0#") + loaderContext.resourceFragment; + }, + set: function(value) { + var splittedResource = value && parsePathQueryFragment(value); + loaderContext.resourcePath = splittedResource ? splittedResource.path : undefined; + loaderContext.resourceQuery = splittedResource ? splittedResource.query : undefined; + loaderContext.resourceFragment = splittedResource ? splittedResource.fragment : undefined; + } + }); + Object.defineProperty(loaderContext, "request", { + enumerable: true, + get: function() { + return loaderContext.loaders.map(function(o) { + return o.request; + }).concat(loaderContext.resource || "").join("!"); + } + }); + Object.defineProperty(loaderContext, "remainingRequest", { + enumerable: true, + get: function() { + if(loaderContext.loaderIndex >= loaderContext.loaders.length - 1 && !loaderContext.resource) + return ""; + return loaderContext.loaders.slice(loaderContext.loaderIndex + 1).map(function(o) { + return o.request; + }).concat(loaderContext.resource || "").join("!"); + } + }); + Object.defineProperty(loaderContext, "currentRequest", { + enumerable: true, + get: function() { + return loaderContext.loaders.slice(loaderContext.loaderIndex).map(function(o) { + return o.request; + }).concat(loaderContext.resource || "").join("!"); + } + }); + Object.defineProperty(loaderContext, "previousRequest", { + enumerable: true, + get: function() { + return loaderContext.loaders.slice(0, loaderContext.loaderIndex).map(function(o) { + return o.request; + }).join("!"); + } + }); + Object.defineProperty(loaderContext, "query", { + enumerable: true, + get: function() { + var entry = loaderContext.loaders[loaderContext.loaderIndex]; + return entry.options && typeof entry.options === "object" ? entry.options : entry.query; + } + }); + Object.defineProperty(loaderContext, "data", { + enumerable: true, + get: function() { + return loaderContext.loaders[loaderContext.loaderIndex].data; + } + }); - logger.time("afterCompile hook"); - this.hooks.afterCompile.callAsync(compilation, err => { - logger.timeEnd("afterCompile hook"); - if (err) return callback(err); + // finish loader context + if(Object.preventExtensions) { + Object.preventExtensions(loaderContext); + } - return callback(null, compilation); - }); - }); - }); - }); - }); + var processOptions = { + resourceBuffer: null, + processResource: processResource + }; + iteratePitchingLoaders(processOptions, loaderContext, function(err, result) { + if(err) { + return callback(err, { + cacheable: requestCacheable, + fileDependencies: fileDependencies, + contextDependencies: contextDependencies, + missingDependencies: missingDependencies }); + } + callback(null, { + result: result, + resourceBuffer: processOptions.resourceBuffer, + cacheable: requestCacheable, + fileDependencies: fileDependencies, + contextDependencies: contextDependencies, + missingDependencies: missingDependencies }); - } + }); +}; - /** - * @param {Callback} callback signals when the compiler closes - * @returns {void} - */ - close(callback) { - if (this.watching) { - // When there is still an active watching, close this first - this.watching.close(err => { - this.close(callback); - }); + +/***/ }), + +/***/ 55102: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +var LoaderLoadingError = __webpack_require__(49448); +var url; + +module.exports = function loadLoader(loader, callback) { + if(loader.type === "module") { + try { + if(url === undefined) url = __webpack_require__(57310); + var loaderUrl = url.pathToFileURL(loader.path); + var modulePromise = eval("import(" + JSON.stringify(loaderUrl.toString()) + ")"); + modulePromise.then(function(module) { + handleResult(loader, module, callback); + }, callback); return; + } catch(e) { + callback(e); } - this.hooks.shutdown.callAsync(err => { - if (err) return callback(err); - // Get rid of reference to last compilation to avoid leaking memory - // We can't run this._cleanupLastCompilation() as the Stats to this compilation - // might be still in use. We try to get rid of the reference to the cache instead. - this._lastCompilation = undefined; - this._lastNormalModuleFactory = undefined; - this.cache.shutdown(callback); - }); + } else { + try { + var module = require(loader.path); + } catch(e) { + // it is possible for node to choke on a require if the FD descriptor + // limit has been reached. give it a chance to recover. + if(e instanceof Error && e.code === "EMFILE") { + var retry = loadLoader.bind(null, loader, callback); + if(typeof setImmediate === "function") { + // node >= 0.9.0 + return setImmediate(retry); + } else { + // node < 0.9.0 + return process.nextTick(retry); + } + } + return callback(e); + } + return handleResult(loader, module, callback); } -} +}; -module.exports = Compiler; +function handleResult(loader, module, callback) { + if(typeof module !== "function" && typeof module !== "object") { + return callback(new LoaderLoadingError( + "Module '" + loader.path + "' is not a loader (export function or es6 module)" + )); + } + loader.normal = typeof module === "function" ? module : module.default; + loader.pitch = module.pitch; + loader.raw = module.raw; + if(typeof loader.normal !== "function" && typeof loader.pitch !== "function") { + return callback(new LoaderLoadingError( + "Module '" + loader.path + "' is not a loader (must have normal or pitch function)" + )); + } + callback(); +} /***/ }), -/***/ 98229: -/***/ (function(module) { +/***/ 54983: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +var __webpack_unused_export__; +__webpack_unused_export__ = ({ + value: true +}); +exports.Z = void 0; -/** @typedef {import("./Module")} Module */ +const { + stringHints, + numberHints +} = __webpack_require__(79926); +/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */ -const MODULE_REFERENCE_REGEXP = - /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(?:_asiSafe(\d))?__$/; +/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */ + +/** @typedef {import("./validate").Schema} Schema */ + +/** @typedef {import("./validate").ValidationErrorConfiguration} ValidationErrorConfiguration */ + +/** @typedef {import("./validate").PostFormatter} PostFormatter */ + +/** @typedef {import("./validate").SchemaUtilErrorObject} SchemaUtilErrorObject */ + +/** @enum {number} */ -const DEFAULT_EXPORT = "__WEBPACK_DEFAULT_EXPORT__"; -const NAMESPACE_OBJECT_EXPORT = "__WEBPACK_NAMESPACE_OBJECT__"; +const SPECIFICITY = { + type: 1, + not: 1, + oneOf: 1, + anyOf: 1, + if: 1, + enum: 1, + const: 1, + instanceof: 1, + required: 2, + pattern: 2, + patternRequired: 2, + format: 2, + formatMinimum: 2, + formatMaximum: 2, + minimum: 2, + exclusiveMinimum: 2, + maximum: 2, + exclusiveMaximum: 2, + multipleOf: 2, + uniqueItems: 2, + contains: 2, + minLength: 2, + maxLength: 2, + minItems: 2, + maxItems: 2, + minProperties: 2, + maxProperties: 2, + dependencies: 2, + propertyNames: 2, + additionalItems: 2, + additionalProperties: 2, + absolutePath: 2 +}; /** - * @typedef {Object} ExternalModuleInfo - * @property {number} index - * @property {Module} module + * + * @param {Array} array + * @param {(item: SchemaUtilErrorObject) => number} fn + * @returns {Array} */ +function filterMax(array, fn) { + const evaluatedMax = array.reduce((max, item) => Math.max(max, fn(item)), 0); + return array.filter(item => fn(item) === evaluatedMax); +} /** - * @typedef {Object} ConcatenatedModuleInfo - * @property {number} index - * @property {Module} module - * @property {Map} exportMap mapping from export name to symbol - * @property {Map} rawExportMap mapping from export name to symbol - * @property {string=} namespaceExportSymbol + * + * @param {Array} children + * @returns {Array} */ -/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo} ModuleInfo */ +function filterChildren(children) { + let newChildren = children; + newChildren = filterMax(newChildren, + /** + * + * @param {SchemaUtilErrorObject} error + * @returns {number} + */ + error => error.dataPath ? error.dataPath.length : 0); + newChildren = filterMax(newChildren, + /** + * @param {SchemaUtilErrorObject} error + * @returns {number} + */ + error => SPECIFICITY[ + /** @type {keyof typeof SPECIFICITY} */ + error.keyword] || 2); + return newChildren; +} /** - * @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 + * Find all children errors + * @param {Array} children + * @param {Array} schemaPaths + * @return {number} returns index of first child */ -class ConcatenationScope { - /** - * @param {ModuleInfo[] | Map} 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); - } +function findAllChildren(children, schemaPaths) { + let i = children.length - 1; - /** - * - * @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); - } - } + const predicate = + /** + * @param {string} schemaPath + * @returns {boolean} + */ + schemaPath => children[i].schemaPath.indexOf(schemaPath) !== 0; - /** - * - * @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); - } - } + while (i > -1 && !schemaPaths.every(predicate)) { + if (children[i].keyword === "anyOf" || children[i].keyword === "oneOf") { + const refs = extractRefs(children[i]); + const childrenStart = findAllChildren(children.slice(0, i), refs.concat(children[i].schemaPath)); + i = childrenStart - 1; + } else { + i -= 1; + } + } - /** - * @param {string} symbol identifier of the export in source code - */ - registerNamespaceExport(symbol) { - this._currentModule.namespaceExportSymbol = symbol; - } + return i + 1; +} +/** + * Extracts all refs from schema + * @param {SchemaUtilErrorObject} error + * @return {Array} + */ - /** - * - * @param {Module} module the referenced module - * @param {Partial} 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); - } +function extractRefs(error) { + const { + schema + } = error; - /** - * @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 - }; - } + if (!Array.isArray(schema)) { + return []; + } + + return schema.map(({ + $ref + }) => $ref).filter(s => s); } +/** + * Groups children by their first level parent (assuming that error is root) + * @param {Array} children + * @return {Array} + */ -ConcatenationScope.DEFAULT_EXPORT = DEFAULT_EXPORT; -ConcatenationScope.NAMESPACE_OBJECT_EXPORT = NAMESPACE_OBJECT_EXPORT; -module.exports = ConcatenationScope; +function groupChildrenByFirstChild(children) { + const result = []; + let i = children.length - 1; + while (i > 0) { + const child = children[i]; -/***/ }), + if (child.keyword === "anyOf" || child.keyword === "oneOf") { + const refs = extractRefs(child); + const childrenStart = findAllChildren(children.slice(0, i), refs.concat(child.schemaPath)); -/***/ 95735: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (childrenStart !== i) { + result.push(Object.assign({}, child, { + children: children.slice(childrenStart, i) + })); + i = childrenStart; + } else { + result.push(child); + } + } else { + result.push(child); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Maksim Nazarjev @acupofspirt -*/ + i -= 1; + } + if (i === 0) { + result.push(children[i]); + } + return result.reverse(); +} +/** + * @param {string} str + * @param {string} prefix + * @returns {string} + */ -const WebpackError = __webpack_require__(53799); -module.exports = class ConcurrentCompilationError extends WebpackError { - constructor() { - super(); +function indent(str, prefix) { + return str.replace(/\n(?!$)/g, `\n${prefix}`); +} +/** + * @param {Schema} schema + * @returns {schema is (Schema & {not: Schema})} + */ - this.name = "ConcurrentCompilationError"; - this.message = - "You ran Webpack twice. Each instance only supports a single concurrent compilation at a time."; - } -}; +function hasNotInSchema(schema) { + return !!schema.not; +} +/** + * @param {Schema} schema + * @return {Schema} + */ -/***/ }), -/***/ 61333: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +function findFirstTypedSchema(schema) { + if (hasNotInSchema(schema)) { + return findFirstTypedSchema(schema.not); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return schema; +} +/** + * @param {Schema} schema + * @return {boolean} + */ +function canApplyNot(schema) { + const typedSchema = findFirstTypedSchema(schema); + return likeNumber(typedSchema) || likeInteger(typedSchema) || likeString(typedSchema) || likeNull(typedSchema) || likeBoolean(typedSchema); +} +/** + * @param {any} maybeObj + * @returns {boolean} + */ -const { ConcatSource, PrefixSource } = __webpack_require__(51255); -const InitFragment = __webpack_require__(55870); -const Template = __webpack_require__(1626); -const { mergeRuntime } = __webpack_require__(17156); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./Generator").GenerateContext} GenerateContext */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +function isObject(maybeObj) { + return typeof maybeObj === "object" && maybeObj !== null; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ -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" - ); - } -}; +function likeNumber(schema) { + return schema.type === "number" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; +} /** - * @typedef {GenerateContext} Context + * @param {Schema} schema + * @returns {boolean} */ -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 {Context} context context - * @returns {string|Source} the source code that will be included as initialization code - */ - getContent(context) { - if (this.runtimeCondition === false || !this.content) return ""; - if (this.runtimeCondition === true) return this.content; - const expr = context.runtimeTemplate.runtimeConditionExpression({ - chunkGraph: context.chunkGraph, - runtimeRequirements: context.runtimeRequirements, - runtime: context.runtime, - runtimeCondition: this.runtimeCondition - }); - if (expr === "true") return this.content; - return wrapInCondition(expr, this.content); - } - /** - * @param {Context} context context - * @returns {string|Source=} the source code that will be included at the end of the module - */ - getEndContent(context) { - if (this.runtimeCondition === false || !this.endContent) return ""; - if (this.runtimeCondition === true) return this.endContent; - const expr = context.runtimeTemplate.runtimeConditionExpression({ - chunkGraph: context.chunkGraph, - runtimeRequirements: context.runtimeRequirements, - runtime: context.runtime, - runtimeCondition: this.runtimeCondition - }); - if (expr === "true") return this.endContent; - return wrapInCondition(expr, this.endContent); - } +function likeInteger(schema) { + return schema.type === "integer" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ - 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 - ); - } + +function likeString(schema) { + return schema.type === "string" || typeof schema.minLength !== "undefined" || typeof schema.maxLength !== "undefined" || typeof schema.pattern !== "undefined" || typeof schema.format !== "undefined" || typeof schema.formatMinimum !== "undefined" || typeof schema.formatMaximum !== "undefined"; } +/** + * @param {Schema} schema + * @returns {boolean} + */ -module.exports = ConditionalInitFragment; +function likeBoolean(schema) { + return schema.type === "boolean"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ -/***/ }), -/***/ 11146: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +function likeArray(schema) { + return schema.type === "array" || typeof schema.minItems === "number" || typeof schema.maxItems === "number" || typeof schema.uniqueItems !== "undefined" || typeof schema.items !== "undefined" || typeof schema.additionalItems !== "undefined" || typeof schema.contains !== "undefined"; +} +/** + * @param {Schema & {patternRequired?: Array}} schema + * @returns {boolean} + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +function likeObject(schema) { + return schema.type === "object" || typeof schema.minProperties !== "undefined" || typeof schema.maxProperties !== "undefined" || typeof schema.required !== "undefined" || typeof schema.properties !== "undefined" || typeof schema.patternProperties !== "undefined" || typeof schema.additionalProperties !== "undefined" || typeof schema.dependencies !== "undefined" || typeof schema.propertyNames !== "undefined" || typeof schema.patternRequired !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ -const CachedConstDependency = __webpack_require__(57403); -const ConstDependency = __webpack_require__(76911); -const { evaluateToString } = __webpack_require__(93998); -const { parseResource } = __webpack_require__(82186); +function likeNull(schema) { + return schema.type === "null"; +} +/** + * @param {string} type + * @returns {string} + */ -/** @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; - } - } -}; +function getArticle(type) { + if (/^[aeiou]/i.test(type)) { + return "an"; + } -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); -}; + return "a"; +} +/** + * @param {Schema=} schema + * @returns {string} + */ -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() - ); +function getSchemaNonTypes(schema) { + if (!schema) { + return ""; + } - 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 (!schema.type) { + if (likeNumber(schema) || likeInteger(schema)) { + return " | should be any non-number"; + } - 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); - } + if (likeString(schema)) { + return " | should be any non-string"; + } - return keepRight; - } - } - } - ); - parser.hooks.optionalChaining.tap("ConstPlugin", expr => { - /** @type {ExpressionNode[]} */ - const optionalExpressionsStack = []; - /** @type {ExpressionNode|SuperNode} */ - let next = expr.expression; + if (likeArray(schema)) { + return " | should be any non-array"; + } - 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; - } - } + if (likeObject(schema)) { + return " | should be any non-object"; + } + } - while (optionalExpressionsStack.length) { - const expression = optionalExpressionsStack.pop(); - const evaluated = parser.evaluateExpression(expression); + return ""; +} +/** + * @param {Array} hints + * @returns {string} + */ - 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; - }); - }; +function formatHints(hints) { + return hints.length > 0 ? `(${hints.join(", ")})` : ""; +} +/** + * @param {Schema} schema + * @param {boolean} logic + * @returns {string[]} + */ - 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); - } - ); - } + +function getHints(schema, logic) { + if (likeNumber(schema) || likeInteger(schema)) { + return numberHints(schema, logic); + } else if (likeString(schema)) { + return stringHints(schema, logic); + } + + return []; } -module.exports = ConstPlugin; +class ValidationError extends Error { + /** + * @param {Array} errors + * @param {Schema} schema + * @param {ValidationErrorConfiguration} configuration + */ + constructor(errors, schema, configuration = {}) { + super(); + /** @type {string} */ + this.name = "ValidationError"; + /** @type {Array} */ -/***/ }), + this.errors = errors; + /** @type {Schema} */ -/***/ 21411: -/***/ (function(module) { + this.schema = schema; + let headerNameFromSchema; + let baseDataPathFromSchema; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + if (schema.title && (!configuration.name || !configuration.baseDataPath)) { + const splittedTitleFromSchema = schema.title.match(/^(.+) (.+)$/); + if (splittedTitleFromSchema) { + if (!configuration.name) { + [, headerNameFromSchema] = splittedTitleFromSchema; + } + if (!configuration.baseDataPath) { + [,, baseDataPathFromSchema] = splittedTitleFromSchema; + } + } + } + /** @type {string} */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./ContextModuleFactory")} ContextModuleFactory */ -class ContextExclusionPlugin { - /** - * @param {RegExp} negativeMatcher Matcher regular expression - */ - constructor(negativeMatcher) { - this.negativeMatcher = negativeMatcher; - } + this.headerName = configuration.name || headerNameFromSchema || "Object"; + /** @type {string} */ - /** - * 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)); - }); - }); - } -} + this.baseDataPath = configuration.baseDataPath || baseDataPathFromSchema || "configuration"; + /** @type {PostFormatter | null} */ -module.exports = ContextExclusionPlugin; + this.postFormatter = configuration.postFormatter || null; + const header = `Invalid ${this.baseDataPath} object. ${this.headerName} has been initialized using ${getArticle(this.baseDataPath)} ${this.baseDataPath} object that does not match the API schema.\n`; + /** @type {string} */ + this.message = `${header}${this.formatValidationErrors(errors)}`; + Error.captureStackTrace(this, this.constructor); + } + /** + * @param {string} path + * @returns {Schema} + */ -/***/ }), -/***/ 76729: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + getSchemaPart(path) { + const newPath = path.split("/"); + let schemaPart = this.schema; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + for (let i = 1; i < newPath.length; i++) { + const inner = schemaPart[ + /** @type {keyof Schema} */ + newPath[i]]; + if (!inner) { + break; + } + schemaPart = inner; + } -const { OriginalSource, RawSource } = __webpack_require__(51255); -const AsyncDependenciesBlock = __webpack_require__(47736); -const { makeWebpackError } = __webpack_require__(11351); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const WebpackError = __webpack_require__(53799); -const { - compareLocations, - concatComparators, - compareSelect, - keepOriginalOrder, - compareModulesById -} = __webpack_require__(29579); -const { contextify, parseResource } = __webpack_require__(82186); -const makeSerializable = __webpack_require__(33032); + return schemaPart; + } + /** + * @param {Schema} schema + * @param {boolean} logic + * @param {Array} prevSchemas + * @returns {string} + */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./Module").BuildMeta} BuildMeta */ -/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */ -/** @template T @typedef {import("./util/LazySet")} LazySet */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */ + formatSchema(schema, logic = true, prevSchemas = []) { + let newLogic = logic; -/** - * @typedef {Object} ContextOptions - * @property {ContextMode} mode - * @property {boolean} recursive - * @property {RegExp} regExp - * @property {"strict"|boolean=} namespaceObject - * @property {string=} addon - * @property {string=} chunkName - * @property {RegExp=} include - * @property {RegExp=} exclude - * @property {RawChunkGroupOptions=} groupOptions - * @property {string=} typePrefix - * @property {string=} category - * @property {string[][]=} referencedExports exports referenced from modules (won't be mangled) - */ + const formatInnerSchema = + /** + * + * @param {Object} innerSchema + * @param {boolean=} addSelf + * @returns {string} + */ + (innerSchema, addSelf) => { + if (!addSelf) { + return this.formatSchema(innerSchema, newLogic, prevSchemas); + } -/** - * @typedef {Object} ContextModuleOptionsExtras - * @property {string} resource - * @property {string=} resourceQuery - * @property {string=} resourceFragment - * @property {TODO} resolveOptions - */ + if (prevSchemas.includes(innerSchema)) { + return "(recursive)"; + } -/** @typedef {ContextOptions & ContextModuleOptionsExtras} ContextModuleOptions */ + return this.formatSchema(innerSchema, newLogic, prevSchemas.concat(schema)); + }; -/** - * @callback ResolveDependenciesCallback - * @param {(Error | null)=} err - * @param {ContextElementDependency[]=} dependencies - */ + if (hasNotInSchema(schema) && !likeObject(schema)) { + if (canApplyNot(schema.not)) { + newLogic = !logic; + return formatInnerSchema(schema.not); + } -/** - * @callback ResolveDependencies - * @param {InputFileSystem} fs - * @param {ContextModuleOptions} options - * @param {ResolveDependenciesCallback} callback - */ + const needApplyLogicHere = !schema.not.not; + const prefix = logic ? "" : "non "; + newLogic = !logic; + return needApplyLogicHere ? prefix + formatInnerSchema(schema.not) : formatInnerSchema(schema.not); + } -const SNAPSHOT_OPTIONS = { timestamp: true }; + if ( + /** @type {Schema & {instanceof: string | Array}} */ + schema.instanceof) { + const { + instanceof: value + } = + /** @type {Schema & {instanceof: string | Array}} */ + schema; + const values = !Array.isArray(value) ? [value] : value; + return values.map( + /** + * @param {string} item + * @returns {string} + */ + item => item === "Function" ? "function" : item).join(" | "); + } -const TYPES = new Set(["javascript"]); + if (schema.enum) { + return ( + /** @type {Array} */ + schema.enum.map(item => JSON.stringify(item)).join(" | ") + ); + } -class ContextModule extends Module { - /** - * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context - * @param {ContextModuleOptions} options options object - */ - constructor(resolveDependencies, options) { - const parsed = parseResource(options ? options.resource : ""); - const resource = parsed.path; - const resourceQuery = (options && options.resourceQuery) || parsed.query; - const resourceFragment = - (options && options.resourceFragment) || parsed.fragment; + if (typeof schema.const !== "undefined") { + return JSON.stringify(schema.const); + } - super("javascript/dynamic", resource); + if (schema.oneOf) { + return ( + /** @type {Array} */ + schema.oneOf.map(item => formatInnerSchema(item, true)).join(" | ") + ); + } - // Info from Factory - this.resolveDependencies = resolveDependencies; - /** @type {ContextModuleOptions} */ - this.options = { - ...options, - resource, - resourceQuery, - resourceFragment - }; - if (options && options.resolveOptions !== undefined) { - this.resolveOptions = options.resolveOptions; - } + if (schema.anyOf) { + return ( + /** @type {Array} */ + schema.anyOf.map(item => formatInnerSchema(item, true)).join(" | ") + ); + } - if (options && typeof options.mode !== "string") { - throw new Error("options.mode is a required option"); - } + if (schema.allOf) { + return ( + /** @type {Array} */ + schema.allOf.map(item => formatInnerSchema(item, true)).join(" & ") + ); + } - this._identifier = this._createIdentifier(); - this._forceBuild = true; - } + if ( + /** @type {JSONSchema7} */ + schema.if) { + const { + if: ifValue, + then: thenValue, + else: elseValue + } = + /** @type {JSONSchema7} */ + schema; + return `${ifValue ? `if ${formatInnerSchema(ifValue)}` : ""}${thenValue ? ` then ${formatInnerSchema(thenValue)}` : ""}${elseValue ? ` else ${formatInnerSchema(elseValue)}` : ""}`; + } - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; - } + if (schema.$ref) { + return formatInnerSchema(this.getSchemaPart(schema.$ref), true); + } - /** - * 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) { - const m = /** @type {ContextModule} */ (module); - this.resolveDependencies = m.resolveDependencies; - this.options = m.options; - } + if (likeNumber(schema) || likeInteger(schema)) { + const [type, ...hints] = getHints(schema, logic); + const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; + return logic ? str : hints.length > 0 ? `non-${type} | ${str}` : `non-${type}`; + } - /** - * Assuming this module is in the cache. Remove internal references to allow freeing some memory. - */ - cleanupForCache() { - super.cleanupForCache(); - this.resolveDependencies = undefined; - } + if (likeString(schema)) { + const [type, ...hints] = getHints(schema, logic); + const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; + return logic ? str : str === "string" ? "non-string" : `non-string | ${str}`; + } - _prettyRegExp(regexString, stripSlash = true) { - const str = (regexString + "").replace(/!/g, "%21").replace(/\|/g, "%7C"); - return stripSlash ? str.substring(1, str.length - 1) : str; - } + if (likeBoolean(schema)) { + return `${logic ? "" : "non-"}boolean`; + } - _createIdentifier() { - let identifier = this.context; - if (this.options.resourceQuery) { - identifier += `|${this.options.resourceQuery}`; - } - if (this.options.resourceFragment) { - identifier += `|${this.options.resourceFragment}`; - } - if (this.options.mode) { - identifier += `|${this.options.mode}`; - } - if (!this.options.recursive) { - identifier += "|nonrecursive"; - } - if (this.options.addon) { - identifier += `|${this.options.addon}`; - } - if (this.options.regExp) { - identifier += `|${this._prettyRegExp(this.options.regExp, false)}`; - } - if (this.options.include) { - identifier += `|include: ${this._prettyRegExp( - this.options.include, - false - )}`; - } - if (this.options.exclude) { - identifier += `|exclude: ${this._prettyRegExp( - this.options.exclude, - false - )}`; - } - if (this.options.referencedExports) { - identifier += `|referencedExports: ${JSON.stringify( - this.options.referencedExports - )}`; - } - if (this.options.chunkName) { - identifier += `|chunkName: ${this.options.chunkName}`; - } - if (this.options.groupOptions) { - identifier += `|groupOptions: ${JSON.stringify( - this.options.groupOptions - )}`; - } - if (this.options.namespaceObject === "strict") { - identifier += "|strict namespace object"; - } else if (this.options.namespaceObject) { - identifier += "|namespace object"; - } + if (likeArray(schema)) { + // not logic already applied in formatValidationError + newLogic = true; + const hints = []; - return identifier; - } + if (typeof schema.minItems === "number") { + hints.push(`should not have fewer than ${schema.minItems} item${schema.minItems > 1 ? "s" : ""}`); + } - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return this._identifier; - } + if (typeof schema.maxItems === "number") { + hints.push(`should not have more than ${schema.maxItems} item${schema.maxItems > 1 ? "s" : ""}`); + } - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - let identifier = requestShortener.shorten(this.context) + "/"; - if (this.options.resourceQuery) { - identifier += ` ${this.options.resourceQuery}`; - } - if (this.options.mode) { - identifier += ` ${this.options.mode}`; - } - if (!this.options.recursive) { - identifier += " nonrecursive"; - } - if (this.options.addon) { - identifier += ` ${requestShortener.shorten(this.options.addon)}`; - } - if (this.options.regExp) { - identifier += ` ${this._prettyRegExp(this.options.regExp)}`; - } - if (this.options.include) { - identifier += ` include: ${this._prettyRegExp(this.options.include)}`; - } - if (this.options.exclude) { - identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`; - } - if (this.options.referencedExports) { - identifier += ` referencedExports: ${this.options.referencedExports - .map(e => e.join(".")) - .join(", ")}`; - } - if (this.options.chunkName) { - identifier += ` chunkName: ${this.options.chunkName}`; - } - if (this.options.groupOptions) { - const groupOptions = this.options.groupOptions; - for (const key of Object.keys(groupOptions)) { - identifier += ` ${key}: ${groupOptions[key]}`; - } - } - if (this.options.namespaceObject === "strict") { - identifier += " strict namespace object"; - } else if (this.options.namespaceObject) { - identifier += " namespace object"; - } + if (schema.uniqueItems) { + hints.push("should not have duplicate items"); + } - return identifier; - } + const hasAdditionalItems = typeof schema.additionalItems === "undefined" || Boolean(schema.additionalItems); + let items = ""; - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - let identifier = contextify( - options.context, - this.context, - options.associatedObjectForCache - ); - if (this.layer) identifier = `(${this.layer})/${identifier}`; - if (this.options.mode) { - identifier += ` ${this.options.mode}`; - } - if (this.options.recursive) { - identifier += " recursive"; - } - if (this.options.addon) { - identifier += ` ${contextify( - options.context, - this.options.addon, - options.associatedObjectForCache - )}`; - } - if (this.options.regExp) { - identifier += ` ${this._prettyRegExp(this.options.regExp)}`; - } - if (this.options.include) { - identifier += ` include: ${this._prettyRegExp(this.options.include)}`; - } - if (this.options.exclude) { - identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`; - } - if (this.options.referencedExports) { - identifier += ` referencedExports: ${this.options.referencedExports - .map(e => e.join(".")) - .join(", ")}`; - } + if (schema.items) { + if (Array.isArray(schema.items) && schema.items.length > 0) { + items = `${ + /** @type {Array} */ + schema.items.map(item => formatInnerSchema(item)).join(", ")}`; - return identifier; - } + if (hasAdditionalItems) { + if (schema.additionalItems && isObject(schema.additionalItems) && Object.keys(schema.additionalItems).length > 0) { + hints.push(`additional items should be ${formatInnerSchema(schema.additionalItems)}`); + } + } + } else if (schema.items && Object.keys(schema.items).length > 0) { + // "additionalItems" is ignored + items = `${formatInnerSchema(schema.items)}`; + } else { + // Fallback for empty `items` value + items = "any"; + } + } else { + // "additionalItems" is ignored + items = "any"; + } - /** - * @returns {void} - */ - invalidateBuild() { - this._forceBuild = true; - } + if (schema.contains && Object.keys(schema.contains).length > 0) { + hints.push(`should contains at least one ${this.formatSchema(schema.contains)} item`); + } - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild({ fileSystemInfo }, callback) { - // build if enforced - if (this._forceBuild) return callback(null, true); + return `[${items}${hasAdditionalItems ? ", ..." : ""}]${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; + } - // always build when we have no snapshot - if (!this.buildInfo.snapshot) return callback(null, true); + if (likeObject(schema)) { + // not logic already applied in formatValidationError + newLogic = true; + const hints = []; - fileSystemInfo.checkSnapshotValid(this.buildInfo.snapshot, (err, valid) => { - callback(err, !valid); - }); - } + if (typeof schema.minProperties === "number") { + hints.push(`should not have fewer than ${schema.minProperties} ${schema.minProperties > 1 ? "properties" : "property"}`); + } - /** - * @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._forceBuild = false; - /** @type {BuildMeta} */ - this.buildMeta = { - exportsType: "default", - defaultObject: "redirect-warn" - }; - this.buildInfo = { - snapshot: undefined - }; - this.dependencies.length = 0; - this.blocks.length = 0; - const startTime = Date.now(); - this.resolveDependencies(fs, this.options, (err, dependencies) => { - if (err) { - return callback( - makeWebpackError(err, "ContextModule.resolveDependencies") - ); - } + if (typeof schema.maxProperties === "number") { + hints.push(`should not have more than ${schema.maxProperties} ${schema.minProperties && schema.minProperties > 1 ? "properties" : "property"}`); + } - // abort if something failed - // this will create an empty context - if (!dependencies) { - callback(); - return; - } + if (schema.patternProperties && Object.keys(schema.patternProperties).length > 0) { + const patternProperties = Object.keys(schema.patternProperties); + hints.push(`additional property names should match pattern${patternProperties.length > 1 ? "s" : ""} ${patternProperties.map(pattern => JSON.stringify(pattern)).join(" | ")}`); + } - // enhance dependencies with meta info - for (const dep of dependencies) { - dep.loc = { - name: dep.userRequest - }; - dep.request = this.options.addon + dep.request; - } - dependencies.sort( - concatComparators( - compareSelect(a => a.loc, compareLocations), - keepOriginalOrder(this.dependencies) - ) - ); + const properties = schema.properties ? Object.keys(schema.properties) : []; + const required = schema.required ? schema.required : []; + const allProperties = [...new Set( + /** @type {Array} */ + [].concat(required).concat(properties))]; + const objectStructure = allProperties.map(property => { + const isRequired = required.includes(property); // Some properties need quotes, maybe we should add check + // Maybe we should output type of property (`foo: string`), but it is looks very unreadable - if (this.options.mode === "sync" || this.options.mode === "eager") { - // if we have an sync or eager context - // just add all dependencies and continue - this.dependencies = dependencies; - } else if (this.options.mode === "lazy-once") { - // for the lazy-once mode create a new async dependency block - // and add that block to this context - if (dependencies.length > 0) { - const block = new AsyncDependenciesBlock({ - ...this.options.groupOptions, - name: this.options.chunkName - }); - for (const dep of dependencies) { - block.addDependency(dep); - } - this.addBlock(block); - } - } else if ( - this.options.mode === "weak" || - this.options.mode === "async-weak" - ) { - // we mark all dependencies as weak - for (const dep of dependencies) { - dep.weak = true; - } - this.dependencies = dependencies; - } else if (this.options.mode === "lazy") { - // if we are lazy create a new async dependency block per dependency - // and add all blocks to this context - let index = 0; - for (const dep of dependencies) { - let chunkName = this.options.chunkName; - if (chunkName) { - if (!/\[(index|request)\]/.test(chunkName)) { - chunkName += "[index]"; - } - chunkName = chunkName.replace(/\[index\]/g, `${index++}`); - chunkName = chunkName.replace( - /\[request\]/g, - Template.toPath(dep.userRequest) - ); - } - const block = new AsyncDependenciesBlock( - { - ...this.options.groupOptions, - name: chunkName - }, - dep.loc, - dep.userRequest - ); - block.addDependency(dep); - this.addBlock(block); - } - } else { - callback( - new WebpackError(`Unsupported mode "${this.options.mode}" in context`) - ); - return; - } - compilation.fileSystemInfo.createSnapshot( - startTime, - null, - [this.context], - null, - SNAPSHOT_OPTIONS, - (err, snapshot) => { - if (err) return callback(err); - this.buildInfo.snapshot = snapshot; - callback(); - } - ); - }); - } + return `${property}${isRequired ? "" : "?"}`; + }).concat(typeof schema.additionalProperties === "undefined" || Boolean(schema.additionalProperties) ? schema.additionalProperties && isObject(schema.additionalProperties) ? [`: ${formatInnerSchema(schema.additionalProperties)}`] : ["…"] : []).join(", "); + const { + dependencies, + propertyNames, + patternRequired + } = + /** @type {Schema & {patternRequired?: Array;}} */ + schema; - /** - * @param {LazySet} fileDependencies set where file dependencies are added to - * @param {LazySet} contextDependencies set where context dependencies are added to - * @param {LazySet} missingDependencies set where missing dependencies are added to - * @param {LazySet} buildDependencies set where build dependencies are added to - */ - addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ) { - contextDependencies.add(this.context); - } + if (dependencies) { + Object.keys(dependencies).forEach(dependencyName => { + const dependency = dependencies[dependencyName]; - /** - * @param {ContextElementDependency[]} dependencies all dependencies - * @param {ChunkGraph} chunkGraph chunk graph - * @returns {TODO} TODO - */ - getUserRequestMap(dependencies, chunkGraph) { - const moduleGraph = chunkGraph.moduleGraph; - // if we filter first we get a new array - // therefore we don't need to create a clone of dependencies explicitly - // therefore the order of this is !important! - const sortedDependencies = dependencies - .filter(dependency => moduleGraph.getModule(dependency)) - .sort((a, b) => { - if (a.userRequest === b.userRequest) { - return 0; - } - return a.userRequest < b.userRequest ? -1 : 1; - }); - const map = Object.create(null); - for (const dep of sortedDependencies) { - const module = moduleGraph.getModule(dep); - map[dep.userRequest] = chunkGraph.getModuleId(module); - } - return map; - } + if (Array.isArray(dependency)) { + hints.push(`should have ${dependency.length > 1 ? "properties" : "property"} ${dependency.map(dep => `'${dep}'`).join(", ")} when property '${dependencyName}' is present`); + } else { + hints.push(`should be valid according to the schema ${formatInnerSchema(dependency)} when property '${dependencyName}' is present`); + } + }); + } - /** - * @param {ContextElementDependency[]} dependencies all dependencies - * @param {ChunkGraph} chunkGraph chunk graph - * @returns {TODO} TODO - */ - getFakeMap(dependencies, chunkGraph) { - if (!this.options.namespaceObject) { - return 9; - } - const moduleGraph = chunkGraph.moduleGraph; - // bitfield - let hasType = 0; - const comparator = compareModulesById(chunkGraph); - // if we filter first we get a new array - // therefore we don't need to create a clone of dependencies explicitly - // therefore the order of this is !important! - const sortedModules = dependencies - .map(dependency => moduleGraph.getModule(dependency)) - .filter(Boolean) - .sort(comparator); - const fakeMap = Object.create(null); - for (const module of sortedModules) { - const exportsType = module.getExportsType( - moduleGraph, - this.options.namespaceObject === "strict" - ); - const id = chunkGraph.getModuleId(module); - switch (exportsType) { - case "namespace": - fakeMap[id] = 9; - hasType |= 1; - break; - case "dynamic": - fakeMap[id] = 7; - hasType |= 2; - break; - case "default-only": - fakeMap[id] = 1; - hasType |= 4; - break; - case "default-with-named": - fakeMap[id] = 3; - hasType |= 8; - break; - default: - throw new Error(`Unexpected exports type ${exportsType}`); - } - } - if (hasType === 1) { - return 9; - } - if (hasType === 2) { - return 7; - } - if (hasType === 4) { - return 1; - } - if (hasType === 8) { - return 3; - } - if (hasType === 0) { - return 9; - } - return fakeMap; - } + if (propertyNames && Object.keys(propertyNames).length > 0) { + hints.push(`each property name should match format ${JSON.stringify(schema.propertyNames.format)}`); + } - getFakeMapInitStatement(fakeMap) { - return typeof fakeMap === "object" - ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` - : ""; - } + if (patternRequired && patternRequired.length > 0) { + hints.push(`should have property matching pattern ${patternRequired.map( + /** + * @param {string} item + * @returns {string} + */ + item => JSON.stringify(item))}`); + } - getReturn(type, asyncModule) { - if (type === 9) { - return "__webpack_require__(id)"; - } - return `${RuntimeGlobals.createFakeNamespaceObject}(id, ${type}${ - asyncModule ? " | 16" : "" - })`; - } + return `object {${objectStructure ? ` ${objectStructure} ` : ""}}${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; + } - getReturnModuleObjectSource( - fakeMap, - asyncModule, - fakeMapDataExpression = "fakeMap[id]" - ) { - if (typeof fakeMap === "number") { - return `return ${this.getReturn(fakeMap, asyncModule)};`; - } - return `return ${ - RuntimeGlobals.createFakeNamespaceObject - }(id, ${fakeMapDataExpression}${asyncModule ? " | 16" : ""})`; - } + if (likeNull(schema)) { + return `${logic ? "" : "non-"}null`; + } - /** - * @param {TODO} dependencies TODO - * @param {TODO} id TODO - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {string} source code - */ - getSyncSource(dependencies, id, chunkGraph) { - const map = this.getUserRequestMap(dependencies, chunkGraph); - const fakeMap = this.getFakeMap(dependencies, chunkGraph); - const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); + if (Array.isArray(schema.type)) { + // not logic already applied in formatValidationError + return `${schema.type.join(" | ")}`; + } // Fallback for unknown keywords + // not logic already applied in formatValidationError - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} + /* istanbul ignore next */ -function webpackContext(req) { - var id = webpackContextResolve(req); - ${returnModuleObject} -} -function webpackContextResolve(req) { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; -} -webpackContext.keys = function webpackContextKeys() { - return Object.keys(map); -}; -webpackContext.resolve = webpackContextResolve; -module.exports = webpackContext; -webpackContext.id = ${JSON.stringify(id)};`; - } - /** - * @param {TODO} dependencies TODO - * @param {TODO} id TODO - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {string} source code - */ - getWeakSyncSource(dependencies, id, chunkGraph) { - const map = this.getUserRequestMap(dependencies, chunkGraph); - const fakeMap = this.getFakeMap(dependencies, chunkGraph); - const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); + return JSON.stringify(schema, null, 2); + } + /** + * @param {Schema=} schemaPart + * @param {(boolean | Array)=} additionalPath + * @param {boolean=} needDot + * @param {boolean=} logic + * @returns {string} + */ - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} -function webpackContext(req) { - var id = webpackContextResolve(req); - if(!${RuntimeGlobals.moduleFactories}[id]) { - var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - ${returnModuleObject} -} -function webpackContextResolve(req) { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; -} -webpackContext.keys = function webpackContextKeys() { - return Object.keys(map); -}; -webpackContext.resolve = webpackContextResolve; -webpackContext.id = ${JSON.stringify(id)}; -module.exports = webpackContext;`; - } + getSchemaPartText(schemaPart, additionalPath, needDot = false, logic = true) { + if (!schemaPart) { + return ""; + } - /** - * @param {TODO} dependencies TODO - * @param {TODO} id TODO - * @param {Object} context context - * @param {ChunkGraph} context.chunkGraph the chunk graph - * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph - * @returns {string} source code - */ - getAsyncWeakSource(dependencies, id, { chunkGraph, runtimeTemplate }) { - const arrow = runtimeTemplate.supportsArrowFunction(); - const map = this.getUserRequestMap(dependencies, chunkGraph); - const fakeMap = this.getFakeMap(dependencies, chunkGraph); - const returnModuleObject = this.getReturnModuleObjectSource(fakeMap, true); + if (Array.isArray(additionalPath)) { + for (let i = 0; i < additionalPath.length; i++) { + /** @type {Schema | undefined} */ + const inner = schemaPart[ + /** @type {keyof Schema} */ + additionalPath[i]]; - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} + if (inner) { + // eslint-disable-next-line no-param-reassign + schemaPart = inner; + } else { + break; + } + } + } -function webpackAsyncContext(req) { - return webpackAsyncContextResolve(req).then(${ - arrow ? "id =>" : "function(id)" - } { - if(!${RuntimeGlobals.moduleFactories}[id]) { - var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - ${returnModuleObject} - }); -} -function webpackAsyncContextResolve(req) { - // Here Promise.resolve().then() is used instead of new Promise() to prevent - // uncaught exception popping up in devtools - return Promise.resolve().then(${arrow ? "() =>" : "function()"} { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; - }); -} -webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( - "Object.keys(map)" - )}; -webpackAsyncContext.resolve = webpackAsyncContextResolve; -webpackAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackAsyncContext;`; - } + while (schemaPart.$ref) { + // eslint-disable-next-line no-param-reassign + schemaPart = this.getSchemaPart(schemaPart.$ref); + } - /** - * @param {TODO} dependencies TODO - * @param {TODO} id TODO - * @param {Object} context context - * @param {ChunkGraph} context.chunkGraph the chunk graph - * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph - * @returns {string} source code - */ - getEagerSource(dependencies, id, { chunkGraph, runtimeTemplate }) { - const arrow = runtimeTemplate.supportsArrowFunction(); - const map = this.getUserRequestMap(dependencies, chunkGraph); - const fakeMap = this.getFakeMap(dependencies, chunkGraph); - const thenFunction = - fakeMap !== 9 - ? `${arrow ? "id =>" : "function(id)"} { - ${this.getReturnModuleObjectSource(fakeMap)} - }` - : "__webpack_require__"; - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} + let schemaText = `${this.formatSchema(schemaPart, logic)}${needDot ? "." : ""}`; -function webpackAsyncContext(req) { - return webpackAsyncContextResolve(req).then(${thenFunction}); -} -function webpackAsyncContextResolve(req) { - // Here Promise.resolve().then() is used instead of new Promise() to prevent - // uncaught exception popping up in devtools - return Promise.resolve().then(${arrow ? "() =>" : "function()"} { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; - }); -} -webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( - "Object.keys(map)" - )}; -webpackAsyncContext.resolve = webpackAsyncContextResolve; -webpackAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackAsyncContext;`; - } + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } - /** - * @param {TODO} block TODO - * @param {TODO} dependencies TODO - * @param {TODO} id TODO - * @param {Object} options options object - * @param {RuntimeTemplate} options.runtimeTemplate the runtime template - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @returns {string} source code - */ - getLazyOnceSource(block, dependencies, id, { runtimeTemplate, chunkGraph }) { - const promise = runtimeTemplate.blockPromise({ - chunkGraph, - block, - message: "lazy-once context", - runtimeRequirements: new Set() - }); - const arrow = runtimeTemplate.supportsArrowFunction(); - const map = this.getUserRequestMap(dependencies, chunkGraph); - const fakeMap = this.getFakeMap(dependencies, chunkGraph); - const thenFunction = - fakeMap !== 9 - ? `${arrow ? "id =>" : "function(id)"} { - ${this.getReturnModuleObjectSource(fakeMap, true)}; - }` - : "__webpack_require__"; + if (schemaPart.link) { + schemaText += `\n-> Read more at ${schemaPart.link}`; + } - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} + return schemaText; + } + /** + * @param {Schema=} schemaPart + * @returns {string} + */ -function webpackAsyncContext(req) { - return webpackAsyncContextResolve(req).then(${thenFunction}); -} -function webpackAsyncContextResolve(req) { - return ${promise}.then(${arrow ? "() =>" : "function()"} { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; - }); -} -webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( - "Object.keys(map)" - )}; -webpackAsyncContext.resolve = webpackAsyncContextResolve; -webpackAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackAsyncContext;`; - } - /** - * @param {TODO} blocks TODO - * @param {TODO} id TODO - * @param {Object} context context - * @param {ChunkGraph} context.chunkGraph the chunk graph - * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph - * @returns {string} source code - */ - getLazySource(blocks, id, { chunkGraph, runtimeTemplate }) { - const moduleGraph = chunkGraph.moduleGraph; - const arrow = runtimeTemplate.supportsArrowFunction(); - let hasMultipleOrNoChunks = false; - let hasNoChunk = true; - const fakeMap = this.getFakeMap( - blocks.map(b => b.dependencies[0]), - chunkGraph - ); - const hasFakeMap = typeof fakeMap === "object"; - const items = blocks - .map(block => { - const dependency = block.dependencies[0]; - return { - dependency: dependency, - module: moduleGraph.getModule(dependency), - block: block, - userRequest: dependency.userRequest, - chunks: undefined - }; - }) - .filter(item => item.module); - for (const item of items) { - const chunkGroup = chunkGraph.getBlockChunkGroup(item.block); - const chunks = (chunkGroup && chunkGroup.chunks) || []; - item.chunks = chunks; - if (chunks.length > 0) { - hasNoChunk = false; - } - if (chunks.length !== 1) { - hasMultipleOrNoChunks = true; - } - } - const shortMode = hasNoChunk && !hasFakeMap; - const sortedItems = items.sort((a, b) => { - if (a.userRequest === b.userRequest) return 0; - return a.userRequest < b.userRequest ? -1 : 1; - }); - const map = Object.create(null); - for (const item of sortedItems) { - const moduleId = chunkGraph.getModuleId(item.module); - if (shortMode) { - map[item.userRequest] = moduleId; - } else { - const arrayStart = [moduleId]; - if (hasFakeMap) { - arrayStart.push(fakeMap[moduleId]); - } - map[item.userRequest] = arrayStart.concat( - item.chunks.map(chunk => chunk.id) - ); - } - } + getSchemaPartDescription(schemaPart) { + if (!schemaPart) { + return ""; + } - const chunksStartPosition = hasFakeMap ? 2 : 1; - const requestPrefix = hasNoChunk - ? "Promise.resolve()" - : hasMultipleOrNoChunks - ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))` - : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`; - const returnModuleObject = this.getReturnModuleObjectSource( - fakeMap, - true, - shortMode ? "invalid" : "ids[1]" - ); + while (schemaPart.$ref) { + // eslint-disable-next-line no-param-reassign + schemaPart = this.getSchemaPart(schemaPart.$ref); + } - const webpackAsyncContext = - requestPrefix === "Promise.resolve()" - ? ` -function webpackAsyncContext(req) { - return Promise.resolve().then(${arrow ? "() =>" : "function()"} { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } + let schemaText = ""; - ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"} - ${returnModuleObject} - }); -}` - : `function webpackAsyncContext(req) { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - return Promise.resolve().then(${arrow ? "() =>" : "function()"} { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - }); - } + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } - var ids = map[req], id = ids[0]; - return ${requestPrefix}.then(${arrow ? "() =>" : "function()"} { - ${returnModuleObject} - }); -}`; + if (schemaPart.link) { + schemaText += `\n-> Read more at ${schemaPart.link}`; + } - return `var map = ${JSON.stringify(map, null, "\t")}; -${webpackAsyncContext} -webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( - "Object.keys(map)" - )}; -webpackAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackAsyncContext;`; - } + return schemaText; + } + /** + * @param {SchemaUtilErrorObject} error + * @returns {string} + */ - getSourceForEmptyContext(id, runtimeTemplate) { - return `function webpackEmptyContext(req) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; -} -webpackEmptyContext.keys = ${runtimeTemplate.returningFunction("[]")}; -webpackEmptyContext.resolve = webpackEmptyContext; -webpackEmptyContext.id = ${JSON.stringify(id)}; -module.exports = webpackEmptyContext;`; - } - getSourceForEmptyAsyncContext(id, runtimeTemplate) { - const arrow = runtimeTemplate.supportsArrowFunction(); - return `function webpackEmptyAsyncContext(req) { - // Here Promise.resolve().then() is used instead of new Promise() to prevent - // uncaught exception popping up in devtools - return Promise.resolve().then(${arrow ? "() =>" : "function()"} { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - }); -} -webpackEmptyAsyncContext.keys = ${runtimeTemplate.returningFunction("[]")}; -webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; -webpackEmptyAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackEmptyAsyncContext;`; - } + formatValidationError(error) { + const { + keyword, + dataPath: errorDataPath + } = error; + const dataPath = `${this.baseDataPath}${errorDataPath}`; - /** - * @param {string} asyncMode module mode - * @param {CodeGenerationContext} context context info - * @returns {string} the source code - */ - getSourceString(asyncMode, { runtimeTemplate, chunkGraph }) { - const id = chunkGraph.getModuleId(this); - if (asyncMode === "lazy") { - if (this.blocks && this.blocks.length > 0) { - return this.getLazySource(this.blocks, id, { - runtimeTemplate, - chunkGraph - }); - } - return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); - } - if (asyncMode === "eager") { - if (this.dependencies && this.dependencies.length > 0) { - return this.getEagerSource(this.dependencies, id, { - chunkGraph, - runtimeTemplate - }); - } - return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); - } - if (asyncMode === "lazy-once") { - const block = this.blocks[0]; - if (block) { - return this.getLazyOnceSource(block, block.dependencies, id, { - runtimeTemplate, - chunkGraph - }); - } - return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); - } - if (asyncMode === "async-weak") { - if (this.dependencies && this.dependencies.length > 0) { - return this.getAsyncWeakSource(this.dependencies, id, { - chunkGraph, - runtimeTemplate - }); - } - return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); - } - if (asyncMode === "weak") { - if (this.dependencies && this.dependencies.length > 0) { - return this.getWeakSyncSource(this.dependencies, id, chunkGraph); - } - } - if (this.dependencies && this.dependencies.length > 0) { - return this.getSyncSource(this.dependencies, id, chunkGraph); - } - return this.getSourceForEmptyContext(id, runtimeTemplate); - } + switch (keyword) { + case "type": + { + const { + parentSchema, + params + } = error; // eslint-disable-next-line default-case - getSource(sourceString) { - if (this.useSourceMap || this.useSimpleSourceMap) { - return new OriginalSource(sourceString, this.identifier()); - } - return new RawSource(sourceString); - } + switch ( + /** @type {import("ajv").TypeParams} */ + params.type) { + case "number": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration(context) { - const { chunkGraph } = context; - const sources = new Map(); - sources.set( - "javascript", - this.getSource(this.getSourceString(this.options.mode, context)) - ); - const set = new Set(); - const allDeps = /** @type {ContextElementDependency[]} */ ( - this.dependencies.concat(this.blocks.map(b => b.dependencies[0])) - ); - set.add(RuntimeGlobals.module); - set.add(RuntimeGlobals.hasOwnProperty); - if (allDeps.length > 0) { - const asyncMode = this.options.mode; - set.add(RuntimeGlobals.require); - if (asyncMode === "weak") { - set.add(RuntimeGlobals.moduleFactories); - } else if (asyncMode === "async-weak") { - set.add(RuntimeGlobals.moduleFactories); - set.add(RuntimeGlobals.ensureChunk); - } else if (asyncMode === "lazy" || asyncMode === "lazy-once") { - set.add(RuntimeGlobals.ensureChunk); - } - if (this.getFakeMap(allDeps, chunkGraph) !== 9) { - set.add(RuntimeGlobals.createFakeNamespaceObject); - } - } - return { - sources, - runtimeRequirements: set - }; - } + case "integer": + return `${dataPath} should be an ${this.getSchemaPartText(parentSchema, false, true)}`; - /** - * @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) { - // base penalty - let size = 160; + case "string": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; - // if we don't have dependencies we stop here. - for (const dependency of this.dependencies) { - const element = /** @type {ContextElementDependency} */ (dependency); - size += 5 + element.userRequest.length; - } - return size; - } + case "boolean": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; - serialize(context) { - const { write } = context; - write(this._identifier); - write(this._forceBuild); - super.serialize(context); - } + case "array": + return `${dataPath} should be an array:\n${this.getSchemaPartText(parentSchema)}`; - deserialize(context) { - const { read } = context; - this._identifier = read(); - this._forceBuild = read(); - super.deserialize(context); - } -} + case "object": + return `${dataPath} should be an object:\n${this.getSchemaPartText(parentSchema)}`; -makeSerializable(ContextModule, "webpack/lib/ContextModule"); + case "null": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; -module.exports = ContextModule; + default: + return `${dataPath} should be:\n${this.getSchemaPartText(parentSchema)}`; + } + } + case "instanceof": + { + const { + parentSchema + } = error; + return `${dataPath} should be an instance of ${this.getSchemaPartText(parentSchema, false, true)}`; + } -/***/ }), + case "pattern": + { + const { + params, + parentSchema + } = error; + const { + pattern + } = + /** @type {import("ajv").PatternParams} */ + params; + return `${dataPath} should match pattern ${JSON.stringify(pattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } -/***/ 62471: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + case "format": + { + const { + params, + parentSchema + } = error; + const { + format + } = + /** @type {import("ajv").FormatParams} */ + params; + return `${dataPath} should match format ${JSON.stringify(format)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + case "formatMinimum": + case "formatMaximum": + { + const { + params, + parentSchema + } = error; + const { + comparison, + limit + } = + /** @type {import("ajv").ComparisonParams} */ + params; + return `${dataPath} should be ${comparison} ${JSON.stringify(limit)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "minimum": + case "maximum": + case "exclusiveMinimum": + case "exclusiveMaximum": + { + const { + parentSchema, + params + } = error; + const { + comparison, + limit + } = + /** @type {import("ajv").ComparisonParams} */ + params; + const [, ...hints] = getHints( + /** @type {Schema} */ + parentSchema, true); + if (hints.length === 0) { + hints.push(`should be ${comparison} ${limit}`); + } -const asyncLib = __webpack_require__(78175); -const { AsyncSeriesWaterfallHook, SyncWaterfallHook } = __webpack_require__(6967); -const ContextModule = __webpack_require__(76729); -const ModuleFactory = __webpack_require__(51010); -const ContextElementDependency = __webpack_require__(58477); -const LazySet = __webpack_require__(38938); -const { cachedSetProperty } = __webpack_require__(60839); -const { createFakeHook } = __webpack_require__(64518); -const { join } = __webpack_require__(17139); + return `${dataPath} ${hints.join(" ")}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } -/** @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} FakeHook */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + case "multipleOf": + { + const { + params, + parentSchema + } = error; + const { + multipleOf + } = + /** @type {import("ajv").MultipleOfParams} */ + params; + return `${dataPath} should be multiple of ${multipleOf}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } -const EMPTY_RESOLVE_OPTIONS = {}; + case "patternRequired": + { + const { + params, + parentSchema + } = error; + const { + missingPattern + } = + /** @type {import("ajv").PatternRequiredParams} */ + params; + return `${dataPath} should have property matching pattern ${JSON.stringify(missingPattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } -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, "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; - } + case "minLength": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; - /** - * @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 LazySet(); - const missingDependencies = new LazySet(); - const contextDependencies = new LazySet(); - this.hooks.beforeResolve.callAsync( - { - context: context, - dependencies: dependencies, - resolveOptions, - fileDependencies, - missingDependencies, - contextDependencies, - ...dependency.options - }, - (err, beforeResolveResult) => { - if (err) { - return callback(err, { - fileDependencies, - missingDependencies, - contextDependencies - }); - } + if (limit === 1) { + return `${dataPath} should be a non-empty string${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - // Ignored - if (!beforeResolveResult) { - return callback(null, { - fileDependencies, - missingDependencies, - contextDependencies - }); - } + const length = limit - 1; + return `${dataPath} should be longer than ${length} character${length > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - const context = beforeResolveResult.context; - const request = beforeResolveResult.request; - const resolveOptions = beforeResolveResult.resolveOptions; + case "minItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; - 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; - } + if (limit === 1) { + return `${dataPath} should be a non-empty array${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - 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"); + return `${dataPath} should not have fewer than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - 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 - }); - } + case "minProperties": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; - 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 - }); - } + if (limit === 1) { + return `${dataPath} should be a non-empty object${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - // Ignored - if (!result) { - return callback(null, { - fileDependencies, - missingDependencies, - contextDependencies - }); - } + return `${dataPath} should not have fewer than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - return callback(null, { - module: new ContextModule(result.resolveDependencies, result), - fileDependencies, - missingDependencies, - contextDependencies - }); - } - ); - } - ); - } - ); - } + case "maxLength": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + const max = limit + 1; + return `${dataPath} should be shorter than ${max} character${max > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - /** - * @param {InputFileSystem} fs file system - * @param {ContextModuleOptions} options options - * @param {ResolveDependenciesCallback} callback callback function - * @returns {void} - */ - resolveDependencies(fs, options, callback) { - const cmf = this; - const { - resource, - resourceQuery, - resourceFragment, - recursive, - regExp, - include, - exclude, - referencedExports, - category, - typePrefix - } = options; - if (!regExp || !resource) return callback(null, []); + case "maxItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - 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 - ); - }); - }; + case "maxProperties": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + return `${dataPath} should not have more than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - 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); + case "uniqueItems": + { + const { + params, + parentSchema + } = error; + const { + i + } = + /** @type {import("ajv").UniqueItemsParams} */ + params; + return `${dataPath} should not contain the item '${error.data[i]}' twice${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - 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); - } - } + case "additionalItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}. These items are valid:\n${this.getSchemaPartText(parentSchema)}`; + } - 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, "/") - }; + case "contains": + { + const { + parentSchema + } = error; + return `${dataPath} should contains at least one ${this.getSchemaPartText(parentSchema, ["contains"])} item${getSchemaNonTypes(parentSchema)}.`; + } - 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, - typePrefix, - category, - referencedExports - ); - dep.optional = true; - return dep; - }); - callback(null, alternatives); - } - ); - } else { - callback(); - } - }); - } else { - callback(); - } - }, - (err, result) => { - if (err) return callback(err); + case "required": + { + const { + parentSchema, + params + } = error; + const missingProperty = + /** @type {import("ajv").DependenciesParams} */ + params.missingProperty.replace(/^\./, ""); + const hasProperty = parentSchema && Boolean( + /** @type {Schema} */ + parentSchema.properties && + /** @type {Schema} */ + parentSchema.properties[missingProperty]); + return `${dataPath} misses the property '${missingProperty}'${getSchemaNonTypes(parentSchema)}.${hasProperty ? ` Should be:\n${this.getSchemaPartText(parentSchema, ["properties", missingProperty])}` : this.getSchemaPartDescription(parentSchema)}`; + } - if (!result) return callback(null, []); + case "additionalProperties": + { + const { + params, + parentSchema + } = error; + const { + additionalProperty + } = + /** @type {import("ajv").AdditionalPropertiesParams} */ + params; + return `${dataPath} has an unknown property '${additionalProperty}'${getSchemaNonTypes(parentSchema)}. These properties are valid:\n${this.getSchemaPartText(parentSchema)}`; + } - const flattenedResult = []; + case "dependencies": + { + const { + params, + parentSchema + } = error; + const { + property, + deps + } = + /** @type {import("ajv").DependenciesParams} */ + params; + const dependencies = deps.split(",").map( + /** + * @param {string} dep + * @returns {string} + */ + dep => `'${dep.trim()}'`).join(", "); + return `${dataPath} should have properties ${dependencies} when property '${property}' is present${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - for (const item of result) { - if (item) flattenedResult.push(...item); - } + case "propertyNames": + { + const { + params, + parentSchema, + schema + } = error; + const { + propertyName + } = + /** @type {import("ajv").PropertyNamesParams} */ + params; + return `${dataPath} property name '${propertyName}' is invalid${getSchemaNonTypes(parentSchema)}. Property names should be match format ${JSON.stringify(schema.format)}.${this.getSchemaPartDescription(parentSchema)}`; + } - callback(null, flattenedResult); - } - ); - }); - }; + case "enum": + { + const { + parentSchema + } = error; - if (typeof fs.realpath === "function") { - addDirectoryChecked(resource, new Set(), callback); - } else { - const addSubDirectory = (dir, callback) => - addDirectory(dir, addSubDirectory, callback); - addDirectory(resource, addSubDirectory, callback); - } - } -}; + if (parentSchema && + /** @type {Schema} */ + parentSchema.enum && + /** @type {Schema} */ + parentSchema.enum.length === 1) { + return `${dataPath} should be ${this.getSchemaPartText(parentSchema, false, true)}`; + } + return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; + } -/***/ }), + case "const": + { + const { + parentSchema + } = error; + return `${dataPath} should be equal to constant ${this.getSchemaPartText(parentSchema, false, true)}`; + } -/***/ 12206: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + case "not": + { + const postfix = likeObject( + /** @type {Schema} */ + error.parentSchema) ? `\n${this.getSchemaPartText(error.parentSchema)}` : ""; + const schemaOutput = this.getSchemaPartText(error.schema, false, false, false); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (canApplyNot(error.schema)) { + return `${dataPath} should be any ${schemaOutput}${postfix}.`; + } + const { + schema, + parentSchema + } = error; + return `${dataPath} should not be ${this.getSchemaPartText(schema, false, true)}${parentSchema && likeObject(parentSchema) ? `\n${this.getSchemaPartText(parentSchema)}` : ""}`; + } + case "oneOf": + case "anyOf": + { + const { + parentSchema, + children + } = error; -const ContextElementDependency = __webpack_require__(58477); -const { join } = __webpack_require__(17139); + if (children && children.length > 0) { + if (error.schema.length === 1) { + const lastChild = children[children.length - 1]; + const remainingChildren = children.slice(0, children.length - 1); + return this.formatValidationError(Object.assign({}, lastChild, { + children: remainingChildren, + parentSchema: Object.assign({}, parentSchema, lastChild.parentSchema) + })); + } -class ContextReplacementPlugin { - constructor( - resourceRegExp, - newContentResource, - newContentRecursive, - newContentRegExp - ) { - this.resourceRegExp = resourceRegExp; + let filteredChildren = filterChildren(children); - 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; - } - } + if (filteredChildren.length === 1) { + return this.formatValidationError(filteredChildren[0]); + } - 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; + filteredChildren = groupChildrenByFirstChild(filteredChildren); + return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}\nDetails:\n${filteredChildren.map( + /** + * @param {SchemaUtilErrorObject} nestedError + * @returns {string} + */ + nestedError => ` * ${indent(this.formatValidationError(nestedError), " ")}`).join("\n")}`; + } - 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; - }); - }); - } -} + return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; + } -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; -}; + case "if": + { + const { + params, + parentSchema + } = error; + const { + failingKeyword + } = + /** @type {import("ajv").IfParams} */ + params; + return `${dataPath} should match "${failingKeyword}" schema:\n${this.getSchemaPartText(parentSchema, [failingKeyword])}`; + } -module.exports = ContextReplacementPlugin; + case "absolutePath": + { + const { + message, + parentSchema + } = error; + return `${dataPath}: ${message}${this.getSchemaPartDescription(parentSchema)}`; + } + /* istanbul ignore next */ -/***/ }), + default: + { + const { + message, + parentSchema + } = error; + const ErrorInJSON = JSON.stringify(error, null, 2); // For `custom`, `false schema`, `$ref` keywords + // Fallback for unknown keywords -/***/ 79065: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + return `${dataPath} ${message} (${ErrorInJSON}).\n${this.getSchemaPartText(parentSchema, false)}`; + } + } + } + /** + * @param {Array} errors + * @returns {string} + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + formatValidationErrors(errors) { + return errors.map(error => { + let formattedError = this.formatValidationError(error); + if (this.postFormatter) { + formattedError = this.postFormatter(formattedError, error); + } -const RuntimeGlobals = __webpack_require__(16475); -const WebpackError = __webpack_require__(53799); -const ConstDependency = __webpack_require__(76911); -const BasicEvaluatedExpression = __webpack_require__(950); -const { - evaluateToString, - toConstantDependency -} = __webpack_require__(93998); -const createHash = __webpack_require__(49835); + return ` - ${indent(formattedError, " ")}`; + }).join("\n"); + } -/** @typedef {import("estree").Expression} Expression */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./NormalModule")} NormalModule */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +} + +var _default = ValidationError; +exports.Z = _default; + +/***/ }), + +/***/ 81184: +/***/ (function(module) { + +"use strict"; -/** @typedef {null|undefined|RegExp|Function|string|number|boolean|bigint|undefined} CodeValuePrimitive */ -/** @typedef {RecursiveArrayOrRecord} CodeValue */ /** - * @typedef {Object} RuntimeValueOptions - * @property {string[]=} fileDependencies - * @property {string[]=} contextDependencies - * @property {string[]=} missingDependencies - * @property {string[]=} buildDependencies - * @property {string|function(): string=} version + * @typedef {[number, boolean]} RangeValue */ -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 || {}; - } +/** + * @callback RangeValueCallback + * @param {RangeValue} rangeValue + * @returns {boolean} + */ +class Range { + /** + * @param {"left" | "right"} side + * @param {boolean} exclusive + * @returns {">" | ">=" | "<" | "<="} + */ + static getOperator(side, exclusive) { + if (side === "left") { + return exclusive ? ">" : ">="; + } - get fileDependencies() { - return this.options === true ? true : this.options.fileDependencies; - } + return exclusive ? "<" : "<="; + } + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ - /** - * @param {JavascriptParser} parser the parser - * @param {Map>} 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 /** @type {string} */ ( - valueCacheVersions.get(VALUE_DEP_PREFIX + key) - ); - } - }); - } + static formatRight(value, logic, exclusive) { + if (logic === false) { + return Range.formatLeft(value, !logic, !exclusive); + } - getCacheVersion() { - return this.options === true - ? undefined - : (typeof this.options.version === "function" - ? this.options.version() - : this.options.version) || "unset"; - } -} + return `should be ${Range.getOperator("right", exclusive)} ${value}`; + } + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ -/** - * @param {any[]|{[k: string]: any}} obj obj - * @param {JavascriptParser} parser Parser - * @param {Map>} 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 `/*#__PURE__*/Object(${code})`; - } -}; + static formatLeft(value, logic, exclusive) { + if (logic === false) { + return Range.formatRight(value, !logic, !exclusive); + } -/** - * Convert code to a string that evaluates - * @param {CodeValue} code Code to evaluate - * @param {JavascriptParser} parser Parser - * @param {Map>} 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 + ""; -}; + return `should be ${Range.getOperator("left", exclusive)} ${value}`; + } + /** + * @param {number} start left side value + * @param {number} end right side value + * @param {boolean} startExclusive is range exclusive from left side + * @param {boolean} endExclusive is range exclusive from right side + * @param {boolean} logic is not logic applied + * @returns {string} + */ -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 "; -const VALUE_DEP_MAIN = "webpack/DefinePlugin_hash"; + static formatRange(start, end, startExclusive, endExclusive, logic) { + let result = "should be"; + result += ` ${Range.getOperator(logic ? "left" : "right", logic ? startExclusive : !startExclusive)} ${start} `; + result += logic ? "and" : "or"; + result += ` ${Range.getOperator(logic ? "right" : "left", logic ? endExclusive : !endExclusive)} ${end}`; + return result; + } + /** + * @param {Array} values + * @param {boolean} logic is not logic applied + * @return {RangeValue} computed value and it's exclusive flag + */ -class DefinePlugin { - /** - * Create a new define plugin - * @param {Record} 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); - } + static getRangeValue(values, logic) { + let minMax = logic ? Infinity : -Infinity; + let j = -1; + const predicate = logic ? + /** @type {RangeValueCallback} */ + ([value]) => value <= minMax : + /** @type {RangeValueCallback} */ + ([value]) => value >= minMax; - /** - * 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; + for (let i = 0; i < values.length; i++) { + if (predicate(values[i])) { + [minMax] = values[i]; + j = i; + } + } - const mainHash = createHash(compilation.outputOptions.hashFunction); - mainHash.update( - /** @type {string} */ ( - compilation.valueCacheVersions.get(VALUE_DEP_MAIN) - ) || "" - ); + if (j > -1) { + return values[j]; + } - /** - * Handler - * @param {JavascriptParser} parser Parser - * @returns {void} - */ - const handler = parser => { - const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN); - parser.hooks.program.tap("DefinePlugin", () => { - const { buildInfo } = parser.state.module; - if (!buildInfo.valueDependencies) - buildInfo.valueDependencies = new Map(); - buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue); - }); + return [Infinity, true]; + } - const addValueDependency = key => { - const { buildInfo } = parser.state.module; - buildInfo.valueDependencies.set( - VALUE_DEP_PREFIX + key, - compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key) - ); - }; + constructor() { + /** @type {Array} */ + this._left = []; + /** @type {Array} */ - const withValueDependency = - (key, fn) => - (...args) => { - addValueDependency(key); - return fn(...args); - }; + this._right = []; + } + /** + * @param {number} value + * @param {boolean=} exclusive + */ - /** - * 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; - }); - }); - }; + left(value, exclusive = false) { + this._left.push([value, exclusive]); + } + /** + * @param {number} value + * @param {boolean=} exclusive + */ - /** - * 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]) - ); + right(value, exclusive = false) { + this._right.push([value, exclusive]); + } + /** + * @param {boolean} logic is not logic applied + * @return {string} "smart" range string representation + */ - 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, ""); - }; + format(logic = true) { + const [start, leftExclusive] = Range.getRangeValue(this._left, logic); + const [end, rightExclusive] = Range.getRangeValue(this._right, !logic); - 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); + if (!Number.isFinite(start) && !Number.isFinite(end)) { + return ""; + } - /** - * 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; - mainHash.update("|" + prefix + key); - const oldVersion = compilation.valueCacheVersions.get(name); - if (oldVersion === undefined) { - compilation.valueCacheVersions.set(name, version); - } else if (oldVersion !== version) { - const warning = new WebpackError( - `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 + "."); - } - }); - }; + const realStart = leftExclusive ? start + 1 : start; + const realEnd = rightExclusive ? end - 1 : end; // e.g. 5 < x < 7, 5 < x <= 6, 6 <= x <= 6 - walkDefinitionsForValues(definitions, ""); + if (realStart === realEnd) { + return `should be ${logic ? "" : "!"}= ${realStart}`; + } // e.g. 4 < x < ∞ + + + if (Number.isFinite(start) && !Number.isFinite(end)) { + return Range.formatLeft(start, logic, leftExclusive); + } // e.g. ∞ < x < 4 + + + if (!Number.isFinite(start) && Number.isFinite(end)) { + return Range.formatRight(end, logic, rightExclusive); + } + + return Range.formatRange(start, end, leftExclusive, rightExclusive, logic); + } - compilation.valueCacheVersions.set( - VALUE_DEP_MAIN, - /** @type {string} */ (mainHash.digest("hex").slice(0, 8)) - ); - } - ); - } } -module.exports = DefinePlugin; +module.exports = Range; /***/ }), -/***/ 28623: +/***/ 79926: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const Range = __webpack_require__(81184); +/** @typedef {import("../validate").Schema} Schema */ -const { OriginalSource, RawSource } = __webpack_require__(51255); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const DelegatedSourceDependency = __webpack_require__(22914); -const StaticExportsDependency = __webpack_require__(91418); -const makeSerializable = __webpack_require__(33032); +/** + * @param {Schema} schema + * @param {boolean} logic + * @return {string[]} + */ -/** @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 -]); +module.exports.stringHints = function stringHints(schema, logic) { + const hints = []; + let type = "string"; + const currentSchema = { ...schema + }; -class DelegatedModule extends Module { - constructor(sourceRequest, data, type, userRequest, originalRequest) { - super("javascript/dynamic", null); + if (!logic) { + const tmpLength = currentSchema.minLength; + const tmpFormat = currentSchema.formatMinimum; + const tmpExclusive = currentSchema.formatExclusiveMaximum; + currentSchema.minLength = currentSchema.maxLength; + currentSchema.maxLength = tmpLength; + currentSchema.formatMinimum = currentSchema.formatMaximum; + currentSchema.formatMaximum = tmpFormat; + currentSchema.formatExclusiveMaximum = !currentSchema.formatExclusiveMinimum; + currentSchema.formatExclusiveMinimum = !tmpExclusive; + } - // Info from Factory - this.sourceRequest = sourceRequest; - this.request = data.id; - this.delegationType = type; - this.userRequest = userRequest; - this.originalRequest = originalRequest; - /** @type {ManifestModuleData} */ - this.delegateData = data; + if (typeof currentSchema.minLength === "number") { + if (currentSchema.minLength === 1) { + type = "non-empty string"; + } else { + const length = Math.max(currentSchema.minLength - 1, 0); + hints.push(`should be longer than ${length} character${length > 1 ? "s" : ""}`); + } + } - // Build info - this.delegatedSourceDependency = undefined; - } + if (typeof currentSchema.maxLength === "number") { + if (currentSchema.maxLength === 0) { + type = "empty string"; + } else { + const length = currentSchema.maxLength + 1; + hints.push(`should be shorter than ${length} character${length > 1 ? "s" : ""}`); + } + } - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; - } + if (currentSchema.pattern) { + hints.push(`should${logic ? "" : " not"} match pattern ${JSON.stringify(currentSchema.pattern)}`); + } - /** - * @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); - } + if (currentSchema.format) { + hints.push(`should${logic ? "" : " not"} match format ${JSON.stringify(currentSchema.format)}`); + } - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return `delegated ${JSON.stringify(this.request)} from ${ - this.sourceRequest - }`; - } + if (currentSchema.formatMinimum) { + hints.push(`should be ${currentSchema.formatExclusiveMinimum ? ">" : ">="} ${JSON.stringify(currentSchema.formatMinimum)}`); + } - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return `delegated ${this.userRequest} from ${this.sourceRequest}`; - } + if (currentSchema.formatMaximum) { + hints.push(`should be ${currentSchema.formatExclusiveMaximum ? "<" : "<="} ${JSON.stringify(currentSchema.formatMaximum)}`); + } - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - return callback(null, !this.buildMeta); - } + return [type].concat(hints); +}; +/** + * @param {Schema} schema + * @param {boolean} logic + * @return {string[]} + */ - /** - * @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; +module.exports.numberHints = function numberHints(schema, logic) { + const hints = [schema.type === "integer" ? "integer" : "number"]; + const range = new Range(); - if (!sourceModule) { - str = runtimeTemplate.throwMissingModuleErrorBlock({ - request: this.sourceRequest - }); - } else { - str = `module.exports = (${runtimeTemplate.moduleExports({ - module: sourceModule, - chunkGraph, - request: dep.request, - runtimeRequirements: new Set() - })})`; + if (typeof schema.minimum === "number") { + range.left(schema.minimum); + } - switch (this.delegationType) { - case "require": - str += `(${JSON.stringify(this.request)})`; - break; - case "object": - str += `[${JSON.stringify(this.request)}]`; - break; - } + if (typeof schema.exclusiveMinimum === "number") { + range.left(schema.exclusiveMinimum, true); + } - str += ";"; - } + if (typeof schema.maximum === "number") { + range.right(schema.maximum); + } - const sources = new Map(); - if (this.useSourceMap || this.useSimpleSourceMap) { - sources.set("javascript", new OriginalSource(str, this.identifier())); - } else { - sources.set("javascript", new RawSource(str)); - } + if (typeof schema.exclusiveMaximum === "number") { + range.right(schema.exclusiveMaximum, true); + } - return { - sources, - runtimeRequirements: RUNTIME_REQUIREMENTS - }; - } + const rangeFormat = range.format(logic); - /** - * @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; - } + if (rangeFormat) { + hints.push(rangeFormat); + } - /** - * @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); - } + if (typeof schema.multipleOf === "number") { + hints.push(`should${logic ? "" : " not"} be multiple of ${schema.multipleOf}`); + } - serialize(context) { - const { write } = context; - // constructor - write(this.sourceRequest); - write(this.delegateData); - write(this.delegationType); - write(this.userRequest); - write(this.originalRequest); - super.serialize(context); - } + return hints; +}; - 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; - } +/***/ 18151: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * Assuming this module is in the cache. Remove internal references to allow freeing some memory. - */ - cleanupForCache() { - super.cleanupForCache(); - this.delegateData = undefined; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Hook = __webpack_require__(21468); +const HookCodeFactory = __webpack_require__(66443); + +class AsyncParallelBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, onDone }) { + let code = ""; + code += `var _results = new Array(${this.options.taps.length});\n`; + code += "var _checkDone = function() {\n"; + code += "for(var i = 0; i < _results.length; i++) {\n"; + code += "var item = _results[i];\n"; + code += "if(item === undefined) return false;\n"; + code += "if(item.result !== undefined) {\n"; + code += onResult("item.result"); + code += "return true;\n"; + code += "}\n"; + code += "if(item.error) {\n"; + code += onError("item.error"); + code += "return true;\n"; + code += "}\n"; + code += "}\n"; + code += "return false;\n"; + code += "}\n"; + code += this.callTapsParallel({ + onError: (i, err, done, doneBreak) => { + let code = ""; + code += `if(${i} < _results.length && ((_results.length = ${i + + 1}), (_results[${i}] = { error: ${err} }), _checkDone())) {\n`; + code += doneBreak(true); + code += "} else {\n"; + code += done(); + code += "}\n"; + return code; + }, + onResult: (i, result, done, doneBreak) => { + let code = ""; + code += `if(${i} < _results.length && (${result} !== undefined && (_results.length = ${i + + 1}), (_results[${i}] = { result: ${result} }), _checkDone())) {\n`; + code += doneBreak(true); + code += "} else {\n"; + code += done(); + code += "}\n"; + return code; + }, + onTap: (i, run, done, doneBreak) => { + let code = ""; + if (i > 0) { + code += `if(${i} >= _results.length) {\n`; + code += done(); + code += "} else {\n"; + } + code += run(); + if (i > 0) code += "}\n"; + return code; + }, + onDone + }); + return code; } } -makeSerializable(DelegatedModule, "webpack/lib/DelegatedModule"); +const factory = new AsyncParallelBailHookCodeFactory(); -module.exports = DelegatedModule; +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncParallelBailHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncParallelBailHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncParallelBailHook.prototype = null; + +module.exports = AsyncParallelBailHook; /***/ }), -/***/ 51387: +/***/ 31684: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -32138,96 +28389,42 @@ module.exports = DelegatedModule; */ +const Hook = __webpack_require__(21468); +const HookCodeFactory = __webpack_require__(66443); -const DelegatedModule = __webpack_require__(28623); - -// 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"]; +class AsyncParallelHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsParallel({ + onError: (i, err, done, doneBreak) => onError(err) + doneBreak(true), + onDone + }); } +} - 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; - } - ); - } - } +const factory = new AsyncParallelHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncParallelHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncParallelHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; } -module.exports = DelegatedModuleFactoryPlugin; + +AsyncParallelHook.prototype = null; + +module.exports = AsyncParallelHook; /***/ }), -/***/ 80632: +/***/ 95734: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -32237,48 +28434,47 @@ module.exports = DelegatedModuleFactoryPlugin; */ +const Hook = __webpack_require__(21468); +const HookCodeFactory = __webpack_require__(66443); -const DelegatedModuleFactoryPlugin = __webpack_require__(51387); -const DelegatedSourceDependency = __webpack_require__(22914); - -/** @typedef {import("./Compiler")} Compiler */ - -class DelegatedPlugin { - constructor(options) { - this.options = options; +class AsyncSeriesBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, resultReturns, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onResult: (i, result, next) => + `if(${result} !== undefined) {\n${onResult( + result + )}\n} else {\n${next()}}\n`, + resultReturns, + onDone + }); } +} - /** - * 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 - ); - } - ); +const factory = new AsyncSeriesBailHookCodeFactory(); - compiler.hooks.compile.tap("DelegatedPlugin", ({ normalModuleFactory }) => { - new DelegatedModuleFactoryPlugin({ - associatedObjectForCache: compiler.root, - ...this.options - }).apply(normalModuleFactory); - }); - } +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncSeriesBailHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesBailHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; } -module.exports = DelegatedPlugin; +AsyncSeriesBailHook.prototype = null; + +module.exports = AsyncSeriesBailHook; /***/ }), -/***/ 71040: +/***/ 96496: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -32288,112 +28484,42 @@ module.exports = DelegatedPlugin; */ +const Hook = __webpack_require__(21468); +const HookCodeFactory = __webpack_require__(66443); -const makeSerializable = __webpack_require__(33032); - -/** @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 = []; - /** @type {DependenciesBlock} */ - this.parent = undefined; - } - - getRootBlock() { - /** @type {DependenciesBlock} */ - let current = this; - while (current.parent) current = current.parent; - return current; - } - - /** - * Adds a DependencyBlock to DependencyBlock relationship. - * This is used for when a Module has a AsyncDependencyBlock tie (for code-splitting) - * - * @param {AsyncDependenciesBlock} block block being added - * @returns {void} - */ - addBlock(block) { - this.blocks.push(block); - block.parent = this; - } - - /** - * @param {Dependency} dependency dependency being tied to block. - * This is an "edge" pointing to another "node" on module graph. - * @returns {void} - */ - addDependency(dependency) { - this.dependencies.push(dependency); - } - - /** - * @param {Dependency} dependency dependency being removed - * @returns {void} - */ - removeDependency(dependency) { - const idx = this.dependencies.indexOf(dependency); - if (idx >= 0) { - this.dependencies.splice(idx, 1); - } - } - - /** - * Removes all dependencies and blocks - * @returns {void} - */ - clearDependenciesAndBlocks() { - this.dependencies.length = 0; - this.blocks.length = 0; +class AsyncSeriesHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); } +} - /** - * @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); - } - } +const factory = new AsyncSeriesHookCodeFactory(); - serialize({ write }) { - write(this.dependencies); - write(this.blocks); - } +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; - deserialize({ read }) { - this.dependencies = read(); - this.blocks = read(); - for (const block of this.blocks) { - block.parent = this; - } - } +function AsyncSeriesHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; } -makeSerializable(DependenciesBlock, "webpack/lib/DependenciesBlock"); +AsyncSeriesHook.prototype = null; -module.exports = DependenciesBlock; +module.exports = AsyncSeriesHook; /***/ }), -/***/ 54912: +/***/ 95999: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -32403,353 +28529,42 @@ module.exports = DependenciesBlock; */ +const Hook = __webpack_require__(21468); +const HookCodeFactory = __webpack_require__(66443); -const memoize = __webpack_require__(78676); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./util/Hash")} Hash */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ - -/** - * @typedef {Object} UpdateHashContext - * @property {ChunkGraph} chunkGraph - * @property {RuntimeSpec} runtime - * @property {RuntimeTemplate=} runtimeTemplate - */ - -/** - * @typedef {Object} SourcePosition - * @property {number} line - * @property {number=} column - */ - -/** - * @typedef {Object} RealDependencyLocation - * @property {SourcePosition} start - * @property {SourcePosition=} end - * @property {number=} index - */ - -/** - * @typedef {Object} SyntheticDependencyLocation - * @property {string} name - * @property {number=} index - */ - -/** @typedef {SyntheticDependencyLocation|RealDependencyLocation} DependencyLocation */ - -/** - * @typedef {Object} ExportSpec - * @property {string} name the name of the export - * @property {boolean=} canMangle can the export be renamed (defaults to true) - * @property {boolean=} terminalBinding is the export a terminal binding that should be checked for export star conflicts - * @property {(string | ExportSpec)[]=} exports nested exports - * @property {ModuleGraphConnection=} from when reexported: from which module - * @property {string[] | null=} export when reexported: from which export - * @property {number=} priority when reexported: with which priority - * @property {boolean=} hidden export is not visible, because another export blends over it - */ - -/** - * @typedef {Object} ExportsSpec - * @property {(string | ExportSpec)[] | true | null} exports exported names, true for unknown exports or null for no exports - * @property {Set=} excludeExports when exports = true, list of unaffected exports - * @property {Set=} hideExports list of maybe prior exposed, but now hidden exports - * @property {ModuleGraphConnection=} from when reexported: from which module - * @property {number=} priority when reexported: with which priority - * @property {boolean=} canMangle can the export be renamed (defaults to true) - * @property {boolean=} terminalBinding are the exports terminal bindings that should be checked for export star conflicts - * @property {Module[]=} dependencies module on which the result depends on - */ - -/** - * @typedef {Object} ReferencedExport - * @property {string[]} name name of the referenced export - * @property {boolean=} canMangle when false, referenced export can not be mangled, defaults to true - */ - -const TRANSITIVE = Symbol("transitive"); - -const getIgnoredModule = memoize(() => { - const RawModule = __webpack_require__(84929); - return new RawModule("/* (ignored) */", `ignored`, `(ignored)`); -}); - -class Dependency { - constructor() { - /** @type {Module} */ - this._parentModule = undefined; - /** @type {DependenciesBlock} */ - this._parentDependenciesBlock = undefined; - /** @type {number} */ - this._parentDependenciesBlockIndex = -1; - // TODO check if this can be moved into ModuleDependency - /** @type {boolean} */ - this.weak = false; - // TODO check if this can be moved into ModuleDependency - /** @type {boolean} */ - this.optional = false; - this._locSL = 0; - this._locSC = 0; - this._locEL = 0; - this._locEC = 0; - this._locI = undefined; - this._locN = undefined; - this._loc = undefined; - } - - /** - * @returns {string} a display name for the type of dependency - */ - get type() { - return "unknown"; - } - - /** - * @returns {string} a dependency category, typical categories are "commonjs", "amd", "esm" - */ - get category() { - return "unknown"; - } - - /** - * @returns {DependencyLocation} location - */ - get loc() { - if (this._loc !== undefined) return this._loc; - /** @type {SyntheticDependencyLocation & RealDependencyLocation} */ - const loc = {}; - if (this._locSL > 0) { - loc.start = { line: this._locSL, column: this._locSC }; - } - if (this._locEL > 0) { - loc.end = { line: this._locEL, column: this._locEC }; - } - if (this._locN !== undefined) { - loc.name = this._locN; - } - if (this._locI !== undefined) { - loc.index = this._locI; - } - return (this._loc = loc); - } - - set loc(loc) { - if ("start" in loc && typeof loc.start === "object") { - this._locSL = loc.start.line || 0; - this._locSC = loc.start.column || 0; - } else { - this._locSL = 0; - this._locSC = 0; - } - if ("end" in loc && typeof loc.end === "object") { - this._locEL = loc.end.line || 0; - this._locEC = loc.end.column || 0; - } else { - this._locEL = 0; - this._locEC = 0; - } - if ("index" in loc) { - this._locI = loc.index; - } else { - this._locI = undefined; - } - if ("name" in loc) { - this._locN = loc.name; - } else { - this._locN = undefined; - } - this._loc = loc; - } - - setLoc(startLine, startColumn, endLine, endColumn) { - this._locSL = startLine; - this._locSC = startColumn; - this._locEL = endLine; - this._locEC = endColumn; - this._locI = undefined; - this._locN = undefined; - this._loc = undefined; - } - - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - return null; - } - - /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module - */ - couldAffectReferencingModule() { - return TRANSITIVE; - } - - /** - * Returns the referenced module and export - * @deprecated - * @param {ModuleGraph} moduleGraph module graph - * @returns {never} throws error - */ - getReference(moduleGraph) { - throw new Error( - "Dependency.getReference was removed in favor of Dependency.getReferencedExports, ModuleGraph.getModule and ModuleGraph.getConnection().active" - ); - } - - /** - * Returns list of exports referenced by this dependency - * @param {ModuleGraph} moduleGraph module graph - * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports - */ - getReferencedExports(moduleGraph, runtime) { - return Dependency.EXPORTS_OBJECT_REFERENCED; - } - - /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {null | false | 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._locSL); - write(this._locSC); - write(this._locEL); - write(this._locEC); - write(this._locI); - write(this._locN); - } - - deserialize({ read }) { - this.weak = read(); - this.optional = read(); - this._locSL = read(); - this._locSC = read(); - this._locEL = read(); - this._locEC = read(); - this._locI = read(); - this._locN = read(); +class AsyncSeriesLoopHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsLooping({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); } } -/** @type {string[][]} */ -Dependency.NO_EXPORTS_REFERENCED = []; -/** @type {string[][]} */ -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)" - ); - }, +const factory = new AsyncSeriesLoopHookCodeFactory(); - /** - * @deprecated - * @returns {never} throws - */ - set() { - throw new Error( - "module property was removed from Dependency (use compilation.moduleGraph.updateModule(dependency, module) instead)" - ); - } -}); +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; -Object.defineProperty(Dependency.prototype, "disconnect", { - get() { - throw new Error( - "disconnect was removed from Dependency (Dependency no longer carries graph specific information)" - ); - } -}); +function AsyncSeriesLoopHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesLoopHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} -Dependency.TRANSITIVE = TRANSITIVE; +AsyncSeriesLoopHook.prototype = null; -module.exports = Dependency; +module.exports = AsyncSeriesLoopHook; /***/ }), -/***/ 5160: +/***/ 58118: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -32759,62 +28574,52 @@ module.exports = Dependency; */ +const Hook = __webpack_require__(21468); +const HookCodeFactory = __webpack_require__(66443); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./Generator").GenerateContext} GenerateContext */ -/** @template T @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} 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 - * @property {CodeGenerationResults} codeGenerationResults the code generation results - */ +class AsyncSeriesWaterfallHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onResult: (i, result, next) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += `${this._args[0]} = ${result};\n`; + code += `}\n`; + code += next(); + return code; + }, + onDone: () => onResult(this._args[0]) + }); + } +} -/** - * @typedef {Object} CssDependencyTemplateContextExtras - * @property {Map} cssExports the css exports - */ +const factory = new AsyncSeriesWaterfallHookCodeFactory(); -/** @typedef {DependencyTemplateContext & CssDependencyTemplateContextExtras} CssDependencyTemplateContext */ +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; -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 = __webpack_require__(77198); - throw new AbstractMethodError(); - } +function AsyncSeriesWaterfallHook(args = [], name = undefined) { + if (args.length < 1) + throw new Error("Waterfall hooks must have at least one argument"); + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesWaterfallHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; } -module.exports = DependencyTemplate; +AsyncSeriesWaterfallHook.prototype = null; + +module.exports = AsyncSeriesWaterfallHook; /***/ }), -/***/ 9163: +/***/ 21468: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -32824,136 +28629,181 @@ module.exports = DependencyTemplate; */ +const util = __webpack_require__(73837); -const createHash = __webpack_require__(49835); +const deprecateContext = util.deprecate(() => {}, +"Hook.context is deprecated and will be removed"); -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ -/** @typedef {typeof import("./util/Hash")} Hash */ +const CALL_DELEGATE = function(...args) { + this.call = this._createCall("sync"); + return this.call(...args); +}; +const CALL_ASYNC_DELEGATE = function(...args) { + this.callAsync = this._createCall("async"); + return this.callAsync(...args); +}; +const PROMISE_DELEGATE = function(...args) { + this.promise = this._createCall("promise"); + return this.promise(...args); +}; -/** @typedef {new (...args: any[]) => Dependency} DependencyConstructor */ +class Hook { + constructor(args = [], name = undefined) { + this._args = args; + this.name = name; + this.taps = []; + this.interceptors = []; + this._call = CALL_DELEGATE; + this.call = CALL_DELEGATE; + this._callAsync = CALL_ASYNC_DELEGATE; + this.callAsync = CALL_ASYNC_DELEGATE; + this._promise = PROMISE_DELEGATE; + this.promise = PROMISE_DELEGATE; + this._x = undefined; -class DependencyTemplates { - /** - * @param {string | Hash} hashFunction the hash function to use - */ - constructor(hashFunction = "md4") { - /** @type {Map} */ - this._map = new Map(); - /** @type {string} */ - this._hash = "31d6cfe0d16ae931b73c59d7e0c089c0"; - this._hashFunction = hashFunction; + this.compile = this.compile; + this.tap = this.tap; + this.tapAsync = this.tapAsync; + this.tapPromise = this.tapPromise; } - /** - * @param {DependencyConstructor} dependency Constructor of Dependency - * @returns {DependencyTemplate} template for this dependency - */ - get(dependency) { - return this._map.get(dependency); + compile(options) { + throw new Error("Abstract: should be overridden"); } - /** - * @param {DependencyConstructor} dependency Constructor of Dependency - * @param {DependencyTemplate} dependencyTemplate template for this dependency - * @returns {void} - */ - set(dependency, dependencyTemplate) { - this._map.set(dependency, dependencyTemplate); + _createCall(type) { + return this.compile({ + taps: this.taps, + interceptors: this.interceptors, + args: this._args, + type: type + }); } - /** - * @param {string} part additional hash contributor - * @returns {void} - */ - updateHash(part) { - const hash = createHash(this._hashFunction); - hash.update(`${this._hash}${part}`); - this._hash = /** @type {string} */ (hash.digest("hex")); + _tap(type, options, fn) { + if (typeof options === "string") { + options = { + name: options.trim() + }; + } else if (typeof options !== "object" || options === null) { + throw new Error("Invalid tap options"); + } + if (typeof options.name !== "string" || options.name === "") { + throw new Error("Missing name for tap"); + } + if (typeof options.context !== "undefined") { + deprecateContext(); + } + options = Object.assign({ type, fn }, options); + options = this._runRegisterInterceptors(options); + this._insert(options); } - getHash() { - return this._hash; + tap(options, fn) { + this._tap("sync", options, fn); } - clone() { - const newInstance = new DependencyTemplates(this._hashFunction); - newInstance._map = new Map(this._map); - newInstance._hash = this._hash; - return newInstance; + tapAsync(options, fn) { + this._tap("async", options, fn); } -} - -module.exports = DependencyTemplates; - -/***/ }), + tapPromise(options, fn) { + this._tap("promise", options, fn); + } -/***/ 62790: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + _runRegisterInterceptors(options) { + for (const interceptor of this.interceptors) { + if (interceptor.register) { + const newOptions = interceptor.register(options); + if (newOptions !== undefined) { + options = newOptions; + } + } + } + return options; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + withOptions(options) { + const mergeOptions = opt => + Object.assign({}, options, typeof opt === "string" ? { name: opt } : opt); + return { + name: this.name, + tap: (opt, fn) => this.tap(mergeOptions(opt), fn), + tapAsync: (opt, fn) => this.tapAsync(mergeOptions(opt), fn), + tapPromise: (opt, fn) => this.tapPromise(mergeOptions(opt), fn), + intercept: interceptor => this.intercept(interceptor), + isUsed: () => this.isUsed(), + withOptions: opt => this.withOptions(mergeOptions(opt)) + }; + } + isUsed() { + return this.taps.length > 0 || this.interceptors.length > 0; + } -const DllModuleFactory = __webpack_require__(68703); -const DllEntryDependency = __webpack_require__(95666); -const EntryDependency = __webpack_require__(3979); + intercept(interceptor) { + this._resetCompilation(); + this.interceptors.push(Object.assign({}, interceptor)); + if (interceptor.register) { + for (let i = 0; i < this.taps.length; i++) { + this.taps[i] = interceptor.register(this.taps[i]); + } + } + } -class DllEntryPlugin { - constructor(context, entries, options) { - this.context = context; - this.entries = entries; - this.options = options; + _resetCompilation() { + this.call = this._call; + this.callAsync = this._callAsync; + this.promise = this._promise; } - apply(compiler) { - compiler.hooks.compilation.tap( - "DllEntryPlugin", - (compilation, { normalModuleFactory }) => { - const dllModuleFactory = new DllModuleFactory(); - compilation.dependencyFactories.set( - DllEntryDependency, - dllModuleFactory - ); - compilation.dependencyFactories.set( - EntryDependency, - normalModuleFactory - ); + _insert(item) { + this._resetCompilation(); + let before; + if (typeof item.before === "string") { + before = new Set([item.before]); + } else if (Array.isArray(item.before)) { + before = new Set(item.before); + } + let stage = 0; + if (typeof item.stage === "number") { + stage = item.stage; + } + let i = this.taps.length; + while (i > 0) { + i--; + const x = this.taps[i]; + this.taps[i + 1] = x; + const xStage = x.stage || 0; + if (before) { + if (before.has(x.name)) { + before.delete(x.name); + continue; + } + if (before.size > 0) { + continue; + } } - ); - 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 - ); - }); + if (xStage > stage) { + continue; + } + i++; + break; + } + this.taps[i] = item; } } -module.exports = DllEntryPlugin; +Object.setPrototypeOf(Hook.prototype, null); + +module.exports = Hook; /***/ }), -/***/ 28280: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 66443: +/***/ (function(module) { "use strict"; /* @@ -32962,207 +28812,473 @@ module.exports = DllEntryPlugin; */ - -const { RawSource } = __webpack_require__(51255); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); - -/** @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} 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(); +class HookCodeFactory { + constructor(config) { + this.config = config; + this.options = undefined; + this._args = undefined; } - /** - * @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 - }; + create(options) { + this.init(options); + let fn; + switch (this.options.type) { + case "sync": + fn = new Function( + this.args(), + '"use strict";\n' + + this.header() + + this.contentWithInterceptors({ + onError: err => `throw ${err};\n`, + onResult: result => `return ${result};\n`, + resultReturns: true, + onDone: () => "", + rethrowIfPossible: true + }) + ); + break; + case "async": + fn = new Function( + this.args({ + after: "_callback" + }), + '"use strict";\n' + + this.header() + + this.contentWithInterceptors({ + onError: err => `_callback(${err});\n`, + onResult: result => `_callback(null, ${result});\n`, + onDone: () => "_callback();\n" + }) + ); + break; + case "promise": + let errorHelperUsed = false; + const content = this.contentWithInterceptors({ + onError: err => { + errorHelperUsed = true; + return `_error(${err});\n`; + }, + onResult: result => `_resolve(${result});\n`, + onDone: () => "_resolve();\n" + }); + let code = ""; + code += '"use strict";\n'; + code += this.header(); + code += "return new Promise((function(_resolve, _reject) {\n"; + if (errorHelperUsed) { + code += "var _sync = true;\n"; + code += "function _error(_err) {\n"; + code += "if(_sync)\n"; + code += + "_resolve(Promise.resolve().then((function() { throw _err; })));\n"; + code += "else\n"; + code += "_reject(_err);\n"; + code += "};\n"; + } + code += content; + if (errorHelperUsed) { + code += "_sync = false;\n"; + } + code += "}));\n"; + fn = new Function(this.args(), code); + break; + } + this.deinit(); + return fn; } - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - return callback(null, !this.buildMeta); + setup(instance, options) { + instance._x = options.taps.map(t => t.fn); } /** - * @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) + * @param {{ type: "sync" | "promise" | "async", taps: Array, interceptors: Array }} options */ - size(type) { - return 12; + init(options) { + this.options = options; + this._args = options.args.slice(); } - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - hash.update(`dll module${this.name || ""}`); - super.updateHash(hash, context); + deinit() { + this.options = undefined; + this._args = undefined; } - serialize(context) { - context.write(this.name); - super.serialize(context); + contentWithInterceptors(options) { + if (this.options.interceptors.length > 0) { + const onError = options.onError; + const onResult = options.onResult; + const onDone = options.onDone; + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.call) { + code += `${this.getInterceptor(i)}.call(${this.args({ + before: interceptor.context ? "_context" : undefined + })});\n`; + } + } + code += this.content( + Object.assign(options, { + onError: + onError && + (err => { + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.error) { + code += `${this.getInterceptor(i)}.error(${err});\n`; + } + } + code += onError(err); + return code; + }), + onResult: + onResult && + (result => { + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.result) { + code += `${this.getInterceptor(i)}.result(${result});\n`; + } + } + code += onResult(result); + return code; + }), + onDone: + onDone && + (() => { + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.done) { + code += `${this.getInterceptor(i)}.done();\n`; + } + } + code += onDone(); + return code; + }) + }) + ); + return code; + } else { + return this.content(options); + } } - deserialize(context) { - this.name = context.read(); - super.deserialize(context); + header() { + let code = ""; + if (this.needContext()) { + code += "var _context = {};\n"; + } else { + code += "var _context;\n"; + } + code += "var _x = this._x;\n"; + if (this.options.interceptors.length > 0) { + code += "var _taps = this.taps;\n"; + code += "var _interceptors = this.interceptors;\n"; + } + return code; } - /** - * 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; + needContext() { + for (const tap of this.options.taps) if (tap.context) return true; + return false; } - /** - * Assuming this module is in the cache. Remove internal references to allow freeing some memory. - */ - cleanupForCache() { - super.cleanupForCache(); - this.dependencies = undefined; + callTap(tapIndex, { onError, onResult, onDone, rethrowIfPossible }) { + let code = ""; + let hasTapCached = false; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.tap) { + if (!hasTapCached) { + code += `var _tap${tapIndex} = ${this.getTap(tapIndex)};\n`; + hasTapCached = true; + } + code += `${this.getInterceptor(i)}.tap(${ + interceptor.context ? "_context, " : "" + }_tap${tapIndex});\n`; + } + } + code += `var _fn${tapIndex} = ${this.getTapFn(tapIndex)};\n`; + const tap = this.options.taps[tapIndex]; + switch (tap.type) { + case "sync": + if (!rethrowIfPossible) { + code += `var _hasError${tapIndex} = false;\n`; + code += "try {\n"; + } + if (onResult) { + code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + } else { + code += `_fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + } + if (!rethrowIfPossible) { + code += "} catch(_err) {\n"; + code += `_hasError${tapIndex} = true;\n`; + code += onError("_err"); + code += "}\n"; + code += `if(!_hasError${tapIndex}) {\n`; + } + if (onResult) { + code += onResult(`_result${tapIndex}`); + } + if (onDone) { + code += onDone(); + } + if (!rethrowIfPossible) { + code += "}\n"; + } + break; + case "async": + let cbCode = ""; + if (onResult) + cbCode += `(function(_err${tapIndex}, _result${tapIndex}) {\n`; + else cbCode += `(function(_err${tapIndex}) {\n`; + cbCode += `if(_err${tapIndex}) {\n`; + cbCode += onError(`_err${tapIndex}`); + cbCode += "} else {\n"; + if (onResult) { + cbCode += onResult(`_result${tapIndex}`); + } + if (onDone) { + cbCode += onDone(); + } + cbCode += "}\n"; + cbCode += "})"; + code += `_fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined, + after: cbCode + })});\n`; + break; + case "promise": + code += `var _hasResult${tapIndex} = false;\n`; + code += `var _promise${tapIndex} = _fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + code += `if (!_promise${tapIndex} || !_promise${tapIndex}.then)\n`; + code += ` throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise${tapIndex} + ')');\n`; + code += `_promise${tapIndex}.then((function(_result${tapIndex}) {\n`; + code += `_hasResult${tapIndex} = true;\n`; + if (onResult) { + code += onResult(`_result${tapIndex}`); + } + if (onDone) { + code += onDone(); + } + code += `}), function(_err${tapIndex}) {\n`; + code += `if(_hasResult${tapIndex}) throw _err${tapIndex};\n`; + code += onError(`_err${tapIndex}`); + code += "});\n"; + break; + } + return code; } -} -makeSerializable(DllModule, "webpack/lib/DllModule"); - -module.exports = DllModule; - - -/***/ }), - -/***/ 68703: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + callTapsSeries({ + onError, + onResult, + resultReturns, + onDone, + doneReturns, + rethrowIfPossible + }) { + if (this.options.taps.length === 0) return onDone(); + const firstAsync = this.options.taps.findIndex(t => t.type !== "sync"); + const somethingReturns = resultReturns || doneReturns; + let code = ""; + let current = onDone; + let unrollCounter = 0; + for (let j = this.options.taps.length - 1; j >= 0; j--) { + const i = j; + const unroll = + current !== onDone && + (this.options.taps[i].type !== "sync" || unrollCounter++ > 20); + if (unroll) { + unrollCounter = 0; + code += `function _next${i}() {\n`; + code += current(); + code += `}\n`; + current = () => `${somethingReturns ? "return " : ""}_next${i}();\n`; + } + const done = current; + const doneBreak = skipDone => { + if (skipDone) return ""; + return onDone(); + }; + const content = this.callTap(i, { + onError: error => onError(i, error, done, doneBreak), + onResult: + onResult && + (result => { + return onResult(i, result, done, doneBreak); + }), + onDone: !onResult && done, + rethrowIfPossible: + rethrowIfPossible && (firstAsync < 0 || i < firstAsync) + }); + current = () => content; + } + code += current(); + return code; + } + callTapsLooping({ onError, onDone, rethrowIfPossible }) { + if (this.options.taps.length === 0) return onDone(); + const syncOnly = this.options.taps.every(t => t.type === "sync"); + let code = ""; + if (!syncOnly) { + code += "var _looper = (function() {\n"; + code += "var _loopAsync = false;\n"; + } + code += "var _loop;\n"; + code += "do {\n"; + code += "_loop = false;\n"; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.loop) { + code += `${this.getInterceptor(i)}.loop(${this.args({ + before: interceptor.context ? "_context" : undefined + })});\n`; + } + } + code += this.callTapsSeries({ + onError, + onResult: (i, result, next, doneBreak) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += "_loop = true;\n"; + if (!syncOnly) code += "if(_loopAsync) _looper();\n"; + code += doneBreak(true); + code += `} else {\n`; + code += next(); + code += `}\n`; + return code; + }, + onDone: + onDone && + (() => { + let code = ""; + code += "if(!_loop) {\n"; + code += onDone(); + code += "}\n"; + return code; + }), + rethrowIfPossible: rethrowIfPossible && syncOnly + }); + code += "} while(_loop);\n"; + if (!syncOnly) { + code += "_loopAsync = true;\n"; + code += "});\n"; + code += "_looper();\n"; + } + return code; + } + callTapsParallel({ + onError, + onResult, + onDone, + rethrowIfPossible, + onTap = (i, run) => run() + }) { + if (this.options.taps.length <= 1) { + return this.callTapsSeries({ + onError, + onResult, + onDone, + rethrowIfPossible + }); + } + let code = ""; + code += "do {\n"; + code += `var _counter = ${this.options.taps.length};\n`; + if (onDone) { + code += "var _done = (function() {\n"; + code += onDone(); + code += "});\n"; + } + for (let i = 0; i < this.options.taps.length; i++) { + const done = () => { + if (onDone) return "if(--_counter === 0) _done();\n"; + else return "--_counter;"; + }; + const doneBreak = skipDone => { + if (skipDone || !onDone) return "_counter = 0;\n"; + else return "_counter = 0;\n_done();\n"; + }; + code += "if(_counter <= 0) break;\n"; + code += onTap( + i, + () => + this.callTap(i, { + onError: error => { + let code = ""; + code += "if(_counter > 0) {\n"; + code += onError(i, error, done, doneBreak); + code += "}\n"; + return code; + }, + onResult: + onResult && + (result => { + let code = ""; + code += "if(_counter > 0) {\n"; + code += onResult(i, result, done, doneBreak); + code += "}\n"; + return code; + }), + onDone: + !onResult && + (() => { + return done(); + }), + rethrowIfPossible + }), + done, + doneBreak + ); + } + code += "} while(false);\n"; + return code; + } -const DllModule = __webpack_require__(28280); -const ModuleFactory = __webpack_require__(51010); + args({ before, after } = {}) { + let allArgs = this._args; + if (before) allArgs = [before].concat(allArgs); + if (after) allArgs = allArgs.concat(after); + if (allArgs.length === 0) { + return ""; + } else { + return allArgs.join(", "); + } + } -/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("./dependencies/DllEntryDependency")} DllEntryDependency */ + getTapFn(idx) { + return `_x[${idx}]`; + } -class DllModuleFactory extends ModuleFactory { - constructor() { - super(); - this.hooks = Object.freeze({}); + getTap(idx) { + return `_taps[${idx}]`; } - /** - * @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 - ) - }); + + getInterceptor(idx) { + return `_interceptors[${idx}]`; } } -module.exports = DllModuleFactory; +module.exports = HookCodeFactory; /***/ }), -/***/ 40038: +/***/ 77079: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -33172,73 +29288,66 @@ module.exports = DllModuleFactory; */ +const util = __webpack_require__(73837); -const DllEntryPlugin = __webpack_require__(62790); -const FlagAllModulesAsUsedPlugin = __webpack_require__(58727); -const LibManifestPlugin = __webpack_require__(93837); -const createSchemaValidation = __webpack_require__(32540); - -/** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */ -/** @typedef {import("./Compiler")} Compiler */ +const defaultFactory = (key, hook) => hook; -const validate = createSchemaValidation( - __webpack_require__(9667), - () => __webpack_require__(99926), - { - name: "Dll Plugin", - baseDataPath: "options" +class HookMap { + constructor(factory, name = undefined) { + this._map = new Map(); + this.name = name; + this._factory = factory; + this._interceptors = []; } -); -class DllPlugin { - /** - * @param {DllPluginOptions} options options object - */ - constructor(options) { - validate(options); - this.options = { - ...options, - entryOnly: options.entryOnly !== false - }; + get(key) { + return this._map.get(key); } - /** - * 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); + for(key) { + const hook = this.get(key); + if (hook !== undefined) { + return hook; + } + let newHook = this._factory(key); + const interceptors = this._interceptors; + for (let i = 0; i < interceptors.length; i++) { + newHook = interceptors[i].factory(key, newHook); } + this._map.set(key, newHook); + return newHook; + } + + intercept(interceptor) { + this._interceptors.push( + Object.assign( + { + factory: defaultFactory + }, + interceptor + ) + ); } } -module.exports = DllPlugin; +HookMap.prototype.tap = util.deprecate(function(key, options, fn) { + return this.for(key).tap(options, fn); +}, "HookMap#tap(key,…) is deprecated. Use HookMap#for(key).tap(…) instead."); + +HookMap.prototype.tapAsync = util.deprecate(function(key, options, fn) { + return this.for(key).tapAsync(options, fn); +}, "HookMap#tapAsync(key,…) is deprecated. Use HookMap#for(key).tapAsync(…) instead."); + +HookMap.prototype.tapPromise = util.deprecate(function(key, options, fn) { + return this.for(key).tapPromise(options, fn); +}, "HookMap#tapPromise(key,…) is deprecated. Use HookMap#for(key).tapPromise(…) instead."); + +module.exports = HookMap; /***/ }), -/***/ 90999: +/***/ 13103: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -33248,254 +29357,118 @@ module.exports = DllPlugin; */ +const Hook = __webpack_require__(21468); -const parseJson = __webpack_require__(15235); -const DelegatedModuleFactoryPlugin = __webpack_require__(51387); -const ExternalModuleFactoryPlugin = __webpack_require__(62153); -const WebpackError = __webpack_require__(53799); -const DelegatedSourceDependency = __webpack_require__(22914); -const createSchemaValidation = __webpack_require__(32540); -const makePathsRelative = (__webpack_require__(82186).makePathsRelative); - -/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ -/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ -/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ - -const validate = createSchemaValidation( - __webpack_require__(28534), - () => __webpack_require__(46552), - { - name: "Dll Reference Plugin", - baseDataPath: "options" +class MultiHook { + constructor(hooks, name = undefined) { + this.hooks = hooks; + this.name = name; } -); -class DllReferencePlugin { - /** - * @param {DllReferencePluginOptions} options options object - */ - constructor(options) { - validate(options); - this.options = options; - /** @type {WeakMap} */ - this._compilationData = new WeakMap(); + tap(options, fn) { + for (const hook of this.hooks) { + hook.tap(options, fn); + } } - 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(); - } - ); + tapAsync(options, fn) { + for (const hook of this.hooks) { + hook.tapAsync(options, fn); + } + } - 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); - }); + tapPromise(options, fn) { + for (const hook of this.hooks) { + hook.tapPromise(options, fn); + } + } - 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); - } - } - } - ); + isUsed() { + for (const hook of this.hooks) { + if (hook.isUsed()) return true; + } + return false; } -} -class DllManifestError extends WebpackError { - constructor(filename, message) { - super(); + intercept(interceptor) { + for (const hook of this.hooks) { + hook.intercept(interceptor); + } + } - this.name = "DllManifestError"; - this.message = `Dll manifest ${filename}\n${message}`; + withOptions(options) { + return new MultiHook( + this.hooks.map(h => h.withOptions(options)), + this.name + ); } } -module.exports = DllReferencePlugin; +module.exports = MultiHook; /***/ }), -/***/ 96475: +/***/ 1626: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Naoyuki Kanezawa @nkzawa + Author Tobias Koppers @sokra */ +const Hook = __webpack_require__(21468); +const HookCodeFactory = __webpack_require__(66443); -const EntryOptionPlugin = __webpack_require__(9909); -const EntryPlugin = __webpack_require__(96953); -const EntryDependency = __webpack_require__(3979); +class SyncBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, resultReturns, onDone, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onResult: (i, result, next) => + `if(${result} !== undefined) {\n${onResult( + result + )};\n} else {\n${next()}}\n`, + resultReturns, + onDone, + rethrowIfPossible + }); + } +} -/** @typedef {import("../declarations/WebpackOptions").EntryDynamicNormalized} EntryDynamic */ -/** @typedef {import("../declarations/WebpackOptions").EntryItem} EntryItem */ -/** @typedef {import("../declarations/WebpackOptions").EntryStaticNormalized} EntryStatic */ -/** @typedef {import("./Compiler")} Compiler */ +const factory = new SyncBailHookCodeFactory(); -class DynamicEntryPlugin { - /** - * @param {string} context the context path - * @param {EntryDynamic} entry the entry value - */ - constructor(context, entry) { - this.context = context; - this.entry = entry; - } +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncBailHook"); +}; - /** - * 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 - ); - } - ); +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncBailHook"); +}; - 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 => {}) - ); - } +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function SyncBailHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = SyncBailHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; } -module.exports = DynamicEntryPlugin; +SyncBailHook.prototype = null; + +module.exports = SyncBailHook; /***/ }), -/***/ 9909: +/***/ 69689: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -33505,97 +29478,51 @@ module.exports = DynamicEntryPlugin; */ +const Hook = __webpack_require__(21468); +const HookCodeFactory = __webpack_require__(66443); -/** @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; +class SyncHookCodeFactory extends HookCodeFactory { + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible }); } +} - /** - * @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 = __webpack_require__(96475); - new DynamicEntryPlugin(context, entry).apply(compiler); - } else { - const EntryPlugin = __webpack_require__(96953); - 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); - } - } - } - } +const factory = new SyncHookCodeFactory(); - /** - * @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, - publicPath: desc.publicPath, - chunkLoading: desc.chunkLoading, - asyncChunks: desc.asyncChunks, - wasmLoading: desc.wasmLoading, - library: desc.library - }; - if (desc.layer !== undefined && !compiler.options.experiments.layers) { - throw new Error( - "'entryOptions.layer' is only allowed when 'experiments.layers' is enabled" - ); - } - if (desc.chunkLoading) { - const EnableChunkLoadingPlugin = __webpack_require__(61291); - EnableChunkLoadingPlugin.checkEnabled(compiler, desc.chunkLoading); - } - if (desc.wasmLoading) { - const EnableWasmLoadingPlugin = __webpack_require__(78613); - EnableWasmLoadingPlugin.checkEnabled(compiler, desc.wasmLoading); - } - if (desc.library) { - const EnableLibraryPlugin = __webpack_require__(91452); - EnableLibraryPlugin.checkEnabled(compiler, desc.library.type); - } - return options; - } +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncHook"); +}; + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function SyncHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = SyncHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; } -module.exports = EntryOptionPlugin; +SyncHook.prototype = null; + +module.exports = SyncHook; /***/ }), -/***/ 96953: +/***/ 50179: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -33605,72 +29532,51 @@ module.exports = EntryOptionPlugin; */ +const Hook = __webpack_require__(21468); +const HookCodeFactory = __webpack_require__(66443); -const EntryDependency = __webpack_require__(3979); +class SyncLoopHookCodeFactory extends HookCodeFactory { + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsLooping({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); + } +} -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ +const factory = new SyncLoopHookCodeFactory(); -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 - ); - } - ); +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncLoopHook"); +}; - const { entry, options, context } = this; - const dep = EntryPlugin.createDependency(entry, options); +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncLoopHook"); +}; - compiler.hooks.make.tapAsync("EntryPlugin", (compilation, callback) => { - compilation.addEntry(context, dep, options, err => { - callback(err); - }); - }); - } +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; - /** - * @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; - } +function SyncLoopHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = SyncLoopHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; } -module.exports = EntryPlugin; +SyncLoopHook.prototype = null; + +module.exports = SyncLoopHook; /***/ }), -/***/ 13795: +/***/ 36093: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -33680,178 +29586,375 @@ module.exports = EntryPlugin; */ +const Hook = __webpack_require__(21468); +const HookCodeFactory = __webpack_require__(66443); -const ChunkGroup = __webpack_require__(15626); +class SyncWaterfallHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, resultReturns, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onResult: (i, result, next) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += `${this._args[0]} = ${result};\n`; + code += `}\n`; + code += next(); + return code; + }, + onDone: () => onResult(this._args[0]), + doneReturns: resultReturns, + rethrowIfPossible + }); + } +} -/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ -/** @typedef {import("./Chunk")} Chunk */ +const factory = new SyncWaterfallHookCodeFactory(); -/** @typedef {{ name?: string } & Omit} EntryOptions */ +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncWaterfallHook"); +}; -/** - * 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; - } +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncWaterfallHook"); +}; - /** - * @returns {boolean} true, when this chunk group will be loaded on initial page load - */ - isInitial() { - return this._initial; - } +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; - /** - * Sets the runtimeChunk for an entrypoint. - * @param {Chunk} chunk the chunk being set as the runtime chunk. - * @returns {void} - */ - setRuntimeChunk(chunk) { - this._runtimeChunk = chunk; - } +function SyncWaterfallHook(args = [], name = undefined) { + if (args.length < 1) + throw new Error("Waterfall hooks must have at least one argument"); + const hook = new Hook(args, name); + hook.constructor = SyncWaterfallHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; +} - /** - * 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; - } +SyncWaterfallHook.prototype = 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; - } +module.exports = SyncWaterfallHook; - /** - * 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; +/***/ 41242: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +exports.__esModule = true; +exports.SyncHook = __webpack_require__(69689); +exports.SyncBailHook = __webpack_require__(1626); +exports.SyncWaterfallHook = __webpack_require__(36093); +exports.SyncLoopHook = __webpack_require__(50179); +exports.AsyncParallelHook = __webpack_require__(31684); +exports.AsyncParallelBailHook = __webpack_require__(18151); +exports.AsyncSeriesHook = __webpack_require__(96496); +exports.AsyncSeriesBailHook = __webpack_require__(95734); +exports.AsyncSeriesLoopHook = __webpack_require__(95999); +exports.AsyncSeriesWaterfallHook = __webpack_require__(58118); +exports.HookMap = __webpack_require__(77079); +exports.MultiHook = __webpack_require__(13103); /***/ }), -/***/ 22070: +/***/ 74315: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Authors Simen Brekken @simenbrekken, Einar Löve @einarlove + Author Tobias Koppers @sokra */ -const DefinePlugin = __webpack_require__(79065); +const RuntimeGlobals = __webpack_require__(16475); const WebpackError = __webpack_require__(53799); +const ConstDependency = __webpack_require__(76911); +const BasicEvaluatedExpression = __webpack_require__(950); +const { + toConstantDependency, + evaluateToString +} = __webpack_require__(93998); +const ChunkNameRuntimeModule = __webpack_require__(84519); +const GetFullHashRuntimeModule = __webpack_require__(88732); /** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./DefinePlugin").CodeValue} CodeValue */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ -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 = {}; - } +/* 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) { - /** @type {Record} */ - const definitions = {}; - for (const key of this.keys) { - const value = - process.env[key] !== undefined - ? process.env[key] - : this.defaultValues[key]; + compiler.hooks.compilation.tap( + "APIPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); - 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." - ); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.chunkName) + .tap("APIPlugin", chunk => { + compilation.addRuntimeModule( + chunk, + new ChunkNameRuntimeModule(chunk.name) + ); + return true; + }); - error.name = "EnvVariableNotDefinedError"; - compilation.errors.push(error); - }); + 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); } + ); + } +} - definitions[`process.env.${key}`] = - value === undefined ? "undefined" : JSON.stringify(value); - } +module.exports = APIPlugin; - new DefinePlugin(definitions).apply(compiler); + +/***/ }), + +/***/ 77198: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +const WebpackError = __webpack_require__(53799); +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 = EnvironmentPlugin; +module.exports = AbstractMethodError; /***/ }), -/***/ 59985: -/***/ (function(__unused_webpack_module, exports) { +/***/ 47736: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -33861,190 +29964,149 @@ module.exports = EnvironmentPlugin; -const loaderFlag = "LOADER_EXECUTION"; +const DependenciesBlock = __webpack_require__(71040); +const makeSerializable = __webpack_require__(33032); -const webpackOptionsFlag = "WEBPACK_OPTIONS"; +/** @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 */ -exports.cutOffByFlag = (stack, flag) => { - stack = stack.split("\n"); - for (let i = 0; i < stack.length; i++) { - if (stack[i].includes(flag)) { - stack.length = i; +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; + this._stringifiedGroupOptions = undefined; } - return stack.join("\n"); -}; -exports.cutOffLoaderExecution = stack => - exports.cutOffByFlag(stack, loaderFlag); + /** + * @returns {string} The name of the chunk + */ + get chunkName() { + return this.groupOptions.name; + } -exports.cutOffWebpackOptions = stack => - exports.cutOffByFlag(stack, webpackOptionsFlag); + /** + * @param {string} value The new chunk name + * @returns {void} + */ + set chunkName(value) { + if (this.groupOptions.name !== value) { + this.groupOptions.name = value; + this._stringifiedGroupOptions = undefined; + } + } -exports.cutOffMultilineMessage = (stack, message) => { - stack = stack.split("\n"); - message = message.split("\n"); + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + const { chunkGraph } = context; + if (this._stringifiedGroupOptions === undefined) { + this._stringifiedGroupOptions = JSON.stringify(this.groupOptions); + } + const chunkGroup = chunkGraph.getBlockChunkGroup(this); + hash.update( + `${this._stringifiedGroupOptions}${chunkGroup ? chunkGroup.id : ""}` + ); + super.updateHash(hash, context); + } - const result = []; + serialize(context) { + const { write } = context; + write(this.groupOptions); + write(this.loc); + write(this.request); + super.serialize(context); + } - stack.forEach((line, idx) => { - if (!line.includes(message[idx])) result.push(line); - }); + deserialize(context) { + const { read } = context; + this.groupOptions = read(); + this.loc = read(); + this.request = read(); + super.deserialize(context); + } +} - return result.join("\n"); -}; +makeSerializable(AsyncDependenciesBlock, "webpack/lib/AsyncDependenciesBlock"); -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; +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)" + ); } -}; - -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; -}; +module.exports = AsyncDependenciesBlock; /***/ }), -/***/ 65218: +/***/ 30111: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sean Larkin @thelarkinn */ -const { ConcatSource, RawSource } = __webpack_require__(51255); -const ExternalModule = __webpack_require__(73071); -const ModuleFilenameHelpers = __webpack_require__(88821); -const RuntimeGlobals = __webpack_require__(16475); -const JavascriptModulesPlugin = __webpack_require__(89464); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./Compiler")} Compiler */ - -/** @type {WeakMap} */ -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/). - */ -`); +const WebpackError = __webpack_require__(53799); -class EvalDevToolModulePlugin { - constructor(options) { - this.namespace = options.namespace || ""; - this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]"; - this.moduleFilenameTemplate = - options.moduleFilenameTemplate || - "webpack://[namespace]/[resourcePath]?[loaders]"; - } +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ +class AsyncDependencyToInitialChunkError extends WebpackError { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * Creates an instance of AsyncDependencyToInitialChunkError. + * @param {string} chunkName Name of Chunk + * @param {Module} module module tied to dependency + * @param {DependencyLocation} loc location of dependency */ - apply(compiler) { - compiler.hooks.compilation.tap("EvalDevToolModulePlugin", compilation => { - const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); - hooks.renderModuleContent.tap( - "EvalDevToolModulePlugin", - (source, module, { runtimeTemplate, chunkGraph }) => { - const cacheEntry = cache.get(source); - if (cacheEntry !== undefined) return cacheEntry; - if (module instanceof ExternalModule) { - cache.set(source, source); - return source; - } - const content = source.source(); - const str = ModuleFilenameHelpers.createFilename( - module, - { - moduleFilenameTemplate: this.moduleFilenameTemplate, - namespace: this.namespace - }, - { - requestShortener: runtimeTemplate.requestShortener, - chunkGraph, - hashFunction: compilation.outputOptions.hashFunction - } - ); - const footer = - "\n" + - this.sourceUrlComment.replace( - /\[url\]/g, - encodeURI(str) - .replace(/%2F/g, "/") - .replace(/%20/g, "_") - .replace(/%5E/g, "^") - .replace(/%5C/g, "\\") - .replace(/^\//, "") - ); - const result = new RawSource( - `eval(${ - compilation.outputOptions.trustedTypes - ? `${RuntimeGlobals.createScript}(${JSON.stringify( - content + footer - )})` - : JSON.stringify(content + footer) - });` - ); - cache.set(source, result); - return result; - } - ); - hooks.inlineInRuntimeBailout.tap( - "EvalDevToolModulePlugin", - () => "the eval devtool is used." - ); - hooks.render.tap( - "EvalDevToolModulePlugin", - source => new ConcatSource(devtoolWarning, source) - ); - hooks.chunkHash.tap("EvalDevToolModulePlugin", (chunk, hash) => { - hash.update("EvalDevToolModulePlugin"); - hash.update("2"); - }); - if (compilation.outputOptions.trustedTypes) { - compilation.hooks.additionalModuleRuntimeRequirements.tap( - "EvalDevToolModulePlugin", - (module, set, context) => { - set.add(RuntimeGlobals.createScript); - } - ); - } - }); + constructor(chunkName, module, loc) { + super( + `It's not allowed to load an initial chunk on demand. The chunk name "${chunkName}" is already used by an entrypoint.` + ); + + this.name = "AsyncDependencyToInitialChunkError"; + this.module = module; + this.loc = loc; } } -module.exports = EvalDevToolModulePlugin; +module.exports = AsyncDependencyToInitialChunkError; /***/ }), -/***/ 14790: +/***/ 17714: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -34055,210 +30117,69 @@ module.exports = EvalDevToolModulePlugin; -const { ConcatSource, RawSource } = __webpack_require__(51255); -const ModuleFilenameHelpers = __webpack_require__(88821); +const asyncLib = __webpack_require__(78175); const NormalModule = __webpack_require__(39); -const RuntimeGlobals = __webpack_require__(16475); -const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(97513); -const JavascriptModulesPlugin = __webpack_require__(89464); -const ConcatenatedModule = __webpack_require__(97198); -const { makePathsAbsolute } = __webpack_require__(82186); +const PrefetchDependency = __webpack_require__(31618); -/** @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} */ -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; - } - +class AutomaticPrefetchPlugin { /** * 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 + "AutomaticPrefetchPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + PrefetchDependency, + normalModuleFactory ); - 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 = makePathsAbsolute(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, - hashFunction: compilation.outputOptions.hashFunction - } - ); - }); - 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 + } + ); + let lastModules = null; + compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => { + lastModules = []; - return result( - new RawSource( - `eval(${ - compilation.outputOptions.trustedTypes - ? `${RuntimeGlobals.createScript}(${JSON.stringify( - content + footer - )})` - : JSON.stringify(content + footer) - });` - ) + 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); } ); - hooks.inlineInRuntimeBailout.tap( - "EvalDevToolModulePlugin", - () => "the eval-source-map devtool is used." - ); - hooks.render.tap( - "EvalSourceMapDevToolPlugin", - source => new ConcatSource(devtoolWarning, source) - ); - hooks.chunkHash.tap("EvalSourceMapDevToolPlugin", (chunk, hash) => { - hash.update("EvalSourceMapDevToolPlugin"); - hash.update("2"); - }); - if (compilation.outputOptions.trustedTypes) { - compilation.hooks.additionalModuleRuntimeRequirements.tap( - "EvalSourceMapDevToolPlugin", - (module, set, context) => { - set.add(RuntimeGlobals.createScript); - } - ); - } } ); } } - -module.exports = EvalSourceMapDevToolPlugin; +module.exports = AutomaticPrefetchPlugin; /***/ }), -/***/ 63686: +/***/ 21242: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -34269,1606 +30190,1550 @@ module.exports = EvalSourceMapDevToolPlugin; -const { equals } = __webpack_require__(84953); -const SortableSet = __webpack_require__(13098); -const makeSerializable = __webpack_require__(33032); -const { forEachRuntime } = __webpack_require__(17156); +const { ConcatSource } = __webpack_require__(51255); +const Compilation = __webpack_require__(85720); +const ModuleFilenameHelpers = __webpack_require__(88821); +const Template = __webpack_require__(39722); +const createSchemaValidation = __webpack_require__(32540); -/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */ +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {typeof UsageState.OnlyPropertiesUsed | typeof UsageState.NoInfo | typeof UsageState.Unknown | typeof UsageState.Used} RuntimeUsageStateType */ -/** @typedef {typeof UsageState.Unused | RuntimeUsageStateType} UsageStateType */ +const validate = createSchemaValidation( + __webpack_require__(42173), + () => __webpack_require__(49052), + { + name: "Banner Plugin", + baseDataPath: "options" + } +); -const UsageState = Object.freeze({ - Unused: /** @type {0} */ (0), - OnlyPropertiesUsed: /** @type {1} */ (1), - NoInfo: /** @type {2} */ (2), - Unknown: /** @type {3} */ (3), - Used: /** @type {4} */ (4) -}); +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 */`; +}; -const RETURNS_TRUE = () => true; +class BannerPlugin { + /** + * @param {BannerPluginArgument} options options object + */ + constructor(options) { + if (typeof options === "string" || typeof options === "function") { + options = { + banner: options + }; + } -const CIRCULAR = Symbol("circular target"); + validate(options); -class RestoreProvidedData { - constructor( - exports, - otherProvided, - otherCanMangleProvide, - otherTerminalBinding - ) { - this.exports = exports; - this.otherProvided = otherProvided; - this.otherCanMangleProvide = otherCanMangleProvide; - this.otherTerminalBinding = otherTerminalBinding; - } + this.options = options; - serialize({ write }) { - write(this.exports); - write(this.otherProvided); - write(this.otherCanMangleProvide); - write(this.otherTerminalBinding); + 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; + } } - static deserialize({ read }) { - return new RestoreProvidedData(read(), read(), read(), read()); + /** + * 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) + ); + } + } + } + ); + }); } } -makeSerializable( - RestoreProvidedData, - "webpack/lib/ModuleGraph", - "RestoreProvidedData" -); +module.exports = BannerPlugin; -class ExportsInfo { + +/***/ }), + +/***/ 7592: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { AsyncParallelHook, AsyncSeriesBailHook, SyncHook } = __webpack_require__(41242); +const { + makeWebpackError, + makeWebpackErrorCallback +} = __webpack_require__(11351); + +/** @typedef {import("./WebpackError")} WebpackError */ + +/** + * @typedef {Object} Etag + * @property {function(): string} toString + */ + +/** + * @template T + * @callback CallbackCache + * @param {(WebpackError | null)=} 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() { - /** @type {Map} */ - this._exports = new Map(); - this._otherExportsInfo = new ExportInfo(null); - this._sideEffectsOnlyInfo = new ExportInfo("*side effects only*"); - this._exportsAreOrdered = false; - /** @type {ExportsInfo=} */ - this._redirectTo = undefined; + 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]>} */ + storeBuildDependencies: new AsyncParallelHook(["dependencies"]), + /** @type {SyncHook<[]>} */ + beginIdle: new SyncHook([]), + /** @type {AsyncParallelHook<[]>} */ + endIdle: new AsyncParallelHook([]), + /** @type {AsyncParallelHook<[]>} */ + shutdown: new AsyncParallelHook([]) + }; } /** - * @returns {Iterable} all owned exports in any order + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {CallbackCache} callback signals when the value is retrieved + * @returns {void} */ - get ownedExports() { - return this._exports.values(); + 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); + } + }); } /** - * @returns {Iterable} all owned exports in order + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {T} data the value to store + * @param {CallbackCache} callback signals when the value is stored + * @returns {void} */ - get orderedOwnedExports() { - if (!this._exportsAreOrdered) { - this._sortExports(); - } - return this._exports.values(); + store(identifier, etag, data, callback) { + this.hooks.store.callAsync( + identifier, + etag, + data, + makeWebpackErrorCallback(callback, "Cache.hooks.store") + ); } /** - * @returns {Iterable} all exports in any order + * After this method has succeeded the cache can only be restored when build dependencies are + * @param {Iterable} dependencies list of all build dependencies + * @param {CallbackCache} callback signals when the dependencies are stored + * @returns {void} */ - get exports() { - if (this._redirectTo !== undefined) { - const map = new Map(this._redirectTo._exports); - for (const [key, value] of this._exports) { - map.set(key, value); - } - return map.values(); - } - return this._exports.values(); + storeBuildDependencies(dependencies, callback) { + this.hooks.storeBuildDependencies.callAsync( + dependencies, + makeWebpackErrorCallback(callback, "Cache.hooks.storeBuildDependencies") + ); } /** - * @returns {Iterable} all exports in order + * @returns {void} */ - get orderedExports() { - if (!this._exportsAreOrdered) { - this._sortExports(); - } - if (this._redirectTo !== undefined) { - const map = new Map( - Array.from(this._redirectTo.orderedExports, item => [item.name, item]) - ); - for (const [key, value] of this._exports) { - map.set(key, value); - } - // sorting should be pretty fast as map contains - // a lot of presorted items - this._sortExportsMap(map); - return map.values(); - } - return this._exports.values(); + beginIdle() { + this.hooks.beginIdle.call(); } /** - * @returns {ExportInfo} the export info of unlisted exports + * @param {CallbackCache} callback signals when the call finishes + * @returns {void} */ - get otherExportsInfo() { - if (this._redirectTo !== undefined) - return this._redirectTo.otherExportsInfo; - return this._otherExportsInfo; + endIdle(callback) { + this.hooks.endIdle.callAsync( + makeWebpackErrorCallback(callback, "Cache.hooks.endIdle") + ); } - _sortExportsMap(exports) { - if (exports.size > 1) { - const namesInOrder = []; - for (const entry of exports.values()) { - namesInOrder.push(entry.name); - } - namesInOrder.sort(); - let i = 0; - for (const entry of exports.values()) { - const name = namesInOrder[i]; - if (entry.name !== name) break; - i++; - } - for (; i < namesInOrder.length; i++) { - const name = namesInOrder[i]; - const correctEntry = exports.get(name); - exports.delete(name); - exports.set(name, correctEntry); - } - } + /** + * @param {CallbackCache} callback signals when the call finishes + * @returns {void} + */ + shutdown(callback) { + this.hooks.shutdown.callAsync( + makeWebpackErrorCallback(callback, "Cache.hooks.shutdown") + ); } +} - _sortExports() { - this._sortExportsMap(this._exports); - this._exportsAreOrdered = true; - } +Cache.STAGE_MEMORY = -10; +Cache.STAGE_DEFAULT = 0; +Cache.STAGE_DISK = 10; +Cache.STAGE_NETWORK = 20; - setRedirectNamedTo(exportsInfo) { - if (this._redirectTo === exportsInfo) return false; - this._redirectTo = exportsInfo; - return true; - } +module.exports = Cache; - setHasProvideInfo() { - for (const exportInfo of this._exports.values()) { - if (exportInfo.provided === undefined) { - exportInfo.provided = false; - } - if (exportInfo.canMangleProvide === undefined) { - exportInfo.canMangleProvide = true; - } - } - if (this._redirectTo !== undefined) { - this._redirectTo.setHasProvideInfo(); - } else { - if (this._otherExportsInfo.provided === undefined) { - this._otherExportsInfo.provided = false; - } - if (this._otherExportsInfo.canMangleProvide === undefined) { - this._otherExportsInfo.canMangleProvide = true; - } - } - } - setHasUseInfo() { - for (const exportInfo of this._exports.values()) { - exportInfo.setHasUseInfo(); - } - this._sideEffectsOnlyInfo.setHasUseInfo(); - if (this._redirectTo !== undefined) { - this._redirectTo.setHasUseInfo(); - } else { - this._otherExportsInfo.setHasUseInfo(); - if (this._otherExportsInfo.canMangleUse === undefined) { - this._otherExportsInfo.canMangleUse = true; - } - } +/***/ }), + +/***/ 55392: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { forEachBail } = __webpack_require__(30662); +const asyncLib = __webpack_require__(78175); +const getLazyHashedEtag = __webpack_require__(94075); +const mergeEtags = __webpack_require__(54980); + +/** @typedef {import("./Cache")} Cache */ +/** @typedef {import("./Cache").Etag} Etag */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./cache/getLazyHashedEtag").HashableObject} HashableObject */ +/** @typedef {typeof import("./util/Hash")} HashConstructor */ + +/** + * @template T + * @callback CallbackCache + * @param {(WebpackError | null)=} err + * @param {T=} result + * @returns {void} + */ + +/** + * @template T + * @callback CallbackNormalErrorCache + * @param {(Error | null)=} 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]); } /** - * @param {string} name export name - * @returns {ExportInfo} export info for this name + * @template T + * @param {CallbackCache} callback signals when the value is retrieved + * @returns {void} */ - getOwnExportInfo(name) { - const info = this._exports.get(name); - if (info !== undefined) return info; - const newInfo = new ExportInfo(name, this._otherExportsInfo); - this._exports.set(name, newInfo); - this._exportsAreOrdered = false; - return newInfo; + get(callback) { + forEachBail(this._items, (item, callback) => item.get(callback), callback); } /** - * @param {string} name export name - * @returns {ExportInfo} export info for this name + * @template T + * @returns {Promise} promise with the data */ - getExportInfo(name) { - const info = this._exports.get(name); - if (info !== undefined) return info; - if (this._redirectTo !== undefined) - return this._redirectTo.getExportInfo(name); - const newInfo = new ExportInfo(name, this._otherExportsInfo); - this._exports.set(name, newInfo); - this._exportsAreOrdered = false; - return newInfo; + 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); } /** - * @param {string} name export name - * @returns {ExportInfo} export info for this name + * @template T + * @param {T} data the value to store + * @param {CallbackCache} callback signals when the value is stored + * @returns {void} */ - getReadOnlyExportInfo(name) { - const info = this._exports.get(name); - if (info !== undefined) return info; - if (this._redirectTo !== undefined) - return this._redirectTo.getReadOnlyExportInfo(name); - return this._otherExportsInfo; + store(data, callback) { + asyncLib.each( + this._items, + (item, callback) => item.store(data, callback), + callback + ); } /** - * @param {string[]} name export name - * @returns {ExportInfo | undefined} export info for this name + * @template T + * @param {T} data the value to store + * @returns {Promise} promise signals when the value is stored */ - getReadOnlyExportInfoRecursive(name) { - const exportInfo = this.getReadOnlyExportInfo(name[0]); - if (name.length === 1) return exportInfo; - if (!exportInfo.exportsInfo) return undefined; - return exportInfo.exportsInfo.getReadOnlyExportInfoRecursive(name.slice(1)); + storePromise(data) { + return Promise.all(this._items.map(item => item.storePromise(data))).then( + () => {} + ); } +} +class ItemCacheFacade { /** - * @param {string[]=} name the export name - * @returns {ExportsInfo | undefined} the nested exports info + * @param {Cache} cache the root cache + * @param {string} name the child cache item name + * @param {Etag | null} etag the etag */ - getNestedExportsInfo(name) { - if (Array.isArray(name) && name.length > 0) { - const info = this.getReadOnlyExportInfo(name[0]); - if (!info.exportsInfo) return undefined; - return info.exportsInfo.getNestedExportsInfo(name.slice(1)); - } - return this; + constructor(cache, name, etag) { + this._cache = cache; + this._name = name; + this._etag = etag; } /** - * @param {boolean=} canMangle true, if exports can still be mangled (defaults to false) - * @param {Set=} excludeExports list of unaffected exports - * @param {any=} targetKey use this as key for the target - * @param {ModuleGraphConnection=} targetModule set this module as target - * @param {number=} priority priority - * @returns {boolean} true, if this call changed something + * @template T + * @param {CallbackCache} callback signals when the value is retrieved + * @returns {void} */ - setUnknownExportsProvided( - canMangle, - excludeExports, - targetKey, - targetModule, - priority - ) { - let changed = false; - if (excludeExports) { - for (const name of excludeExports) { - // Make sure these entries exist, so they can get different info - this.getExportInfo(name); - } - } - for (const exportInfo of this._exports.values()) { - if (excludeExports && excludeExports.has(exportInfo.name)) continue; - if (exportInfo.provided !== true && exportInfo.provided !== null) { - exportInfo.provided = null; - changed = true; - } - if (!canMangle && exportInfo.canMangleProvide !== false) { - exportInfo.canMangleProvide = false; - changed = true; - } - if (targetKey) { - exportInfo.setTarget(targetKey, targetModule, [exportInfo.name], -1); - } - } - if (this._redirectTo !== undefined) { - if ( - this._redirectTo.setUnknownExportsProvided( - canMangle, - excludeExports, - targetKey, - targetModule, - priority - ) - ) { - changed = true; - } - } else { - if ( - this._otherExportsInfo.provided !== true && - this._otherExportsInfo.provided !== null - ) { - this._otherExportsInfo.provided = null; - changed = true; - } - if (!canMangle && this._otherExportsInfo.canMangleProvide !== false) { - this._otherExportsInfo.canMangleProvide = false; - changed = true; - } - if (targetKey) { - this._otherExportsInfo.setTarget( - targetKey, - targetModule, - undefined, - priority - ); - } - } - return changed; + get(callback) { + this._cache.get(this._name, this._etag, callback); } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, when something changed + * @template T + * @returns {Promise} promise with the data */ - setUsedInUnknownWay(runtime) { - let changed = false; - for (const exportInfo of this._exports.values()) { - if (exportInfo.setUsedInUnknownWay(runtime)) { - changed = true; - } - } - if (this._redirectTo !== undefined) { - if (this._redirectTo.setUsedInUnknownWay(runtime)) { - changed = true; - } - } else { - if ( - this._otherExportsInfo.setUsedConditionally( - used => used < UsageState.Unknown, - UsageState.Unknown, - runtime - ) - ) { - changed = true; - } - if (this._otherExportsInfo.canMangleUse !== false) { - this._otherExportsInfo.canMangleUse = false; - changed = true; - } - } - return changed; + getPromise() { + return new Promise((resolve, reject) => { + this._cache.get(this._name, this._etag, (err, data) => { + if (err) { + reject(err); + } else { + resolve(data); + } + }); + }); } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, when something changed + * @template T + * @param {T} data the value to store + * @param {CallbackCache} callback signals when the value is stored + * @returns {void} */ - setUsedWithoutInfo(runtime) { - let changed = false; - for (const exportInfo of this._exports.values()) { - if (exportInfo.setUsedWithoutInfo(runtime)) { - changed = true; - } - } - if (this._redirectTo !== undefined) { - if (this._redirectTo.setUsedWithoutInfo(runtime)) { - changed = true; - } - } else { - if (this._otherExportsInfo.setUsed(UsageState.NoInfo, runtime)) { - changed = true; - } - if (this._otherExportsInfo.canMangleUse !== false) { - this._otherExportsInfo.canMangleUse = false; - changed = true; - } - } - return changed; + store(data, callback) { + this._cache.store(this._name, this._etag, data, callback); } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, when something changed + * @template T + * @param {T} data the value to store + * @returns {Promise} promise signals when the value is stored */ - setAllKnownExportsUsed(runtime) { - let changed = false; - for (const exportInfo of this._exports.values()) { - if (!exportInfo.provided) continue; - if (exportInfo.setUsed(UsageState.Used, runtime)) { - changed = true; - } - } - return changed; + storePromise(data) { + return new Promise((resolve, reject) => { + this._cache.store(this._name, this._etag, data, err => { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, when something changed + * @template T + * @param {function(CallbackNormalErrorCache): void} computer function to compute the value if not cached + * @param {CallbackNormalErrorCache} callback signals when the value is retrieved + * @returns {void} */ - setUsedForSideEffectsOnly(runtime) { - return this._sideEffectsOnlyInfo.setUsedConditionally( - used => used === UsageState.Unused, - UsageState.Used, - runtime - ); + 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); + }); + }); + }); } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, when the module exports are used in any way + * @template T + * @param {function(): Promise | T} computer function to compute the value if not cached + * @returns {Promise} promise with the data */ - isUsed(runtime) { - if (this._redirectTo !== undefined) { - if (this._redirectTo.isUsed(runtime)) { - return true; - } - } else { - if (this._otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { - return true; - } - } - for (const exportInfo of this._exports.values()) { - if (exportInfo.getUsed(runtime) !== UsageState.Unused) { - return true; - } - } - return false; + 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 {RuntimeSpec} runtime the runtime - * @returns {boolean} true, when the module is used in any way + * @param {Cache} cache the root cache + * @param {string} name the child cache name + * @param {string | HashConstructor} hashFunction the hash function to use */ - isModuleUsed(runtime) { - if (this.isUsed(runtime)) return true; - if (this._sideEffectsOnlyInfo.getUsed(runtime) !== UsageState.Unused) - return true; - return false; + constructor(cache, name, hashFunction) { + this._cache = cache; + this._name = name; + this._hashFunction = hashFunction; } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {SortableSet | boolean | null} set of used exports, or true (when namespace object is used), or false (when unused), or null (when unknown) + * @param {string} name the child cache name# + * @returns {CacheFacade} child cache */ - getUsedExports(runtime) { - if (!this._redirectTo !== undefined) { - switch (this._otherExportsInfo.getUsed(runtime)) { - case UsageState.NoInfo: - return null; - case UsageState.Unknown: - case UsageState.OnlyPropertiesUsed: - case UsageState.Used: - return true; - } - } - const array = []; - if (!this._exportsAreOrdered) this._sortExports(); - for (const exportInfo of this._exports.values()) { - switch (exportInfo.getUsed(runtime)) { - case UsageState.NoInfo: - return null; - case UsageState.Unknown: - return true; - case UsageState.OnlyPropertiesUsed: - case UsageState.Used: - array.push(exportInfo.name); - } - } - if (this._redirectTo !== undefined) { - const inner = this._redirectTo.getUsedExports(runtime); - if (inner === null) return null; - if (inner === true) return true; - if (inner !== false) { - for (const item of inner) { - array.push(item); - } - } - } - if (array.length === 0) { - switch (this._sideEffectsOnlyInfo.getUsed(runtime)) { - case UsageState.NoInfo: - return null; - case UsageState.Unused: - return false; - } - } - return new SortableSet(array); + getChildCache(name) { + return new CacheFacade( + this._cache, + `${this._name}|${name}`, + this._hashFunction + ); } /** - * @returns {null | true | string[]} list of exports when known + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @returns {ItemCacheFacade} item cache */ - getProvidedExports() { - if (!this._redirectTo !== undefined) { - switch (this._otherExportsInfo.provided) { - case undefined: - return null; - case null: - return true; - case true: - return true; - } - } - const array = []; - if (!this._exportsAreOrdered) this._sortExports(); - for (const exportInfo of this._exports.values()) { - switch (exportInfo.provided) { - case undefined: - return null; - case null: - return true; - case true: - array.push(exportInfo.name); - } - } - if (this._redirectTo !== undefined) { - const inner = this._redirectTo.getProvidedExports(); - if (inner === null) return null; - if (inner === true) return true; - for (const item of inner) { - if (!array.includes(item)) { - array.push(item); - } - } - } - return array; + getItemCache(identifier, etag) { + return new ItemCacheFacade( + this._cache, + `${this._name}|${identifier}`, + etag + ); } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {ExportInfo[]} exports that are relevant (not unused and potential provided) + * @param {HashableObject} obj an hashable object + * @returns {Etag} an etag that is lazy hashed */ - getRelevantExports(runtime) { - const list = []; - for (const exportInfo of this._exports.values()) { - const used = exportInfo.getUsed(runtime); - if (used === UsageState.Unused) continue; - if (exportInfo.provided === false) continue; - list.push(exportInfo); - } - if (this._redirectTo !== undefined) { - for (const exportInfo of this._redirectTo.getRelevantExports(runtime)) { - if (!this._exports.has(exportInfo.name)) list.push(exportInfo); - } - } - if ( - this._otherExportsInfo.provided !== false && - this._otherExportsInfo.getUsed(runtime) !== UsageState.Unused - ) { - list.push(this._otherExportsInfo); - } - return list; + getLazyHashedEtag(obj) { + return getLazyHashedEtag(obj, this._hashFunction); } /** - * @param {string | string[]} name the name of the export - * @returns {boolean | undefined | null} if the export is provided + * @param {Etag} a an etag + * @param {Etag} b another etag + * @returns {Etag} an etag that represents both */ - isExportProvided(name) { - if (Array.isArray(name)) { - const info = this.getReadOnlyExportInfo(name[0]); - if (info.exportsInfo && name.length > 1) { - return info.exportsInfo.isExportProvided(name.slice(1)); - } - return info.provided; - } - const info = this.getReadOnlyExportInfo(name); - return info.provided; + mergeEtags(a, b) { + return mergeEtags(a, b); } /** - * @param {RuntimeSpec} runtime runtime - * @returns {string} key representing the usage + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {CallbackCache} callback signals when the value is retrieved + * @returns {void} */ - getUsageKey(runtime) { - const key = []; - if (this._redirectTo !== undefined) { - key.push(this._redirectTo.getUsageKey(runtime)); - } else { - key.push(this._otherExportsInfo.getUsed(runtime)); - } - key.push(this._sideEffectsOnlyInfo.getUsed(runtime)); - for (const exportInfo of this.orderedOwnedExports) { - key.push(exportInfo.getUsed(runtime)); - } - return key.join("|"); + get(identifier, etag, callback) { + this._cache.get(`${this._name}|${identifier}`, etag, callback); } /** - * @param {RuntimeSpec} runtimeA first runtime - * @param {RuntimeSpec} runtimeB second runtime - * @returns {boolean} true, when equally used + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @returns {Promise} promise with the data */ - isEquallyUsed(runtimeA, runtimeB) { - if (this._redirectTo !== undefined) { - if (!this._redirectTo.isEquallyUsed(runtimeA, runtimeB)) return false; - } else { - if ( - this._otherExportsInfo.getUsed(runtimeA) !== - this._otherExportsInfo.getUsed(runtimeB) - ) { - return false; - } - } - if ( - this._sideEffectsOnlyInfo.getUsed(runtimeA) !== - this._sideEffectsOnlyInfo.getUsed(runtimeB) - ) { - return false; - } - for (const exportInfo of this.ownedExports) { - if (exportInfo.getUsed(runtimeA) !== exportInfo.getUsed(runtimeB)) - return false; - } - return true; + getPromise(identifier, etag) { + return new Promise((resolve, reject) => { + this._cache.get(`${this._name}|${identifier}`, etag, (err, data) => { + if (err) { + reject(err); + } else { + resolve(data); + } + }); + }); } /** - * @param {string | string[]} name export name - * @param {RuntimeSpec} runtime check usage for this runtime only - * @returns {UsageStateType} usage status + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {T} data the value to store + * @param {CallbackCache} callback signals when the value is stored + * @returns {void} */ - getUsed(name, runtime) { - if (Array.isArray(name)) { - if (name.length === 0) return this.otherExportsInfo.getUsed(runtime); - let info = this.getReadOnlyExportInfo(name[0]); - if (info.exportsInfo && name.length > 1) { - return info.exportsInfo.getUsed(name.slice(1), runtime); - } - return info.getUsed(runtime); - } - let info = this.getReadOnlyExportInfo(name); - return info.getUsed(runtime); + store(identifier, etag, data, callback) { + this._cache.store(`${this._name}|${identifier}`, etag, data, callback); } /** - * @param {string | string[]} name the export name - * @param {RuntimeSpec} runtime check usage for this runtime only - * @returns {string | string[] | false} the used name + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {T} data the value to store + * @returns {Promise} promise signals when the value is stored */ - getUsedName(name, runtime) { - if (Array.isArray(name)) { - // TODO improve this - if (name.length === 0) { - if (!this.isUsed(runtime)) return false; - return name; - } - let info = this.getReadOnlyExportInfo(name[0]); - const x = info.getUsedName(name[0], runtime); - if (x === false) return false; - const arr = x === name[0] && name.length === 1 ? name : [x]; - if (name.length === 1) { - return arr; - } - if ( - info.exportsInfo && - info.getUsed(runtime) === UsageState.OnlyPropertiesUsed - ) { - const nested = info.exportsInfo.getUsedName(name.slice(1), runtime); - if (!nested) return false; - return arr.concat(nested); - } else { - return arr.concat(name.slice(1)); - } - } else { - let info = this.getReadOnlyExportInfo(name); - const usedName = info.getUsedName(name, runtime); - return usedName; - } + storePromise(identifier, etag, data) { + return new Promise((resolve, reject) => { + this._cache.store(`${this._name}|${identifier}`, etag, data, err => { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); } /** - * @param {Hash} hash the hash - * @param {RuntimeSpec} runtime the runtime + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {function(CallbackNormalErrorCache): void} computer function to compute the value if not cached + * @param {CallbackNormalErrorCache} callback signals when the value is retrieved * @returns {void} */ - updateHash(hash, runtime) { - this._updateHash(hash, runtime, new Set()); + 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); + }); + }); + }); } /** - * @param {Hash} hash the hash - * @param {RuntimeSpec} runtime the runtime - * @param {Set} alreadyVisitedExportsInfo for circular references - * @returns {void} + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {function(): Promise | T} computer function to compute the value if not cached + * @returns {Promise} promise with the data */ - _updateHash(hash, runtime, alreadyVisitedExportsInfo) { - const set = new Set(alreadyVisitedExportsInfo); - set.add(this); - for (const exportInfo of this.orderedExports) { - if (exportInfo.hasInfo(this._otherExportsInfo, runtime)) { - exportInfo._updateHash(hash, runtime, set); - } - } - this._sideEffectsOnlyInfo._updateHash(hash, runtime, set); - this._otherExportsInfo._updateHash(hash, runtime, set); - if (this._redirectTo !== undefined) { - this._redirectTo._updateHash(hash, runtime, set); - } + 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; } +} - getRestoreProvidedData() { - const otherProvided = this._otherExportsInfo.provided; - const otherCanMangleProvide = this._otherExportsInfo.canMangleProvide; - const otherTerminalBinding = this._otherExportsInfo.terminalBinding; - const exports = []; - for (const exportInfo of this.orderedExports) { - if ( - exportInfo.provided !== otherProvided || - exportInfo.canMangleProvide !== otherCanMangleProvide || - exportInfo.terminalBinding !== otherTerminalBinding || - exportInfo.exportsInfoOwned - ) { - exports.push({ - name: exportInfo.name, - provided: exportInfo.provided, - canMangleProvide: exportInfo.canMangleProvide, - terminalBinding: exportInfo.terminalBinding, - exportsInfo: exportInfo.exportsInfoOwned - ? exportInfo.exportsInfo.getRestoreProvidedData() - : undefined - }); - } - } - return new RestoreProvidedData( - exports, - otherProvided, - otherCanMangleProvide, - otherTerminalBinding - ); - } +module.exports = CacheFacade; +module.exports.ItemCacheFacade = ItemCacheFacade; +module.exports.MultiItemCache = MultiItemCache; - restoreProvided({ - otherProvided, - otherCanMangleProvide, - otherTerminalBinding, - exports - }) { - let wasEmpty = true; - for (const exportInfo of this._exports.values()) { - wasEmpty = false; - exportInfo.provided = otherProvided; - exportInfo.canMangleProvide = otherCanMangleProvide; - exportInfo.terminalBinding = otherTerminalBinding; - } - this._otherExportsInfo.provided = otherProvided; - this._otherExportsInfo.canMangleProvide = otherCanMangleProvide; - this._otherExportsInfo.terminalBinding = otherTerminalBinding; - for (const exp of exports) { - const exportInfo = this.getExportInfo(exp.name); - exportInfo.provided = exp.provided; - exportInfo.canMangleProvide = exp.canMangleProvide; - exportInfo.terminalBinding = exp.terminalBinding; - if (exp.exportsInfo) { - const exportsInfo = exportInfo.createNestedExportsInfo(); - exportsInfo.restoreProvided(exp.exportsInfo); + +/***/ }), + +/***/ 77975: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const WebpackError = __webpack_require__(53799); + +/** @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.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()}`; } - } - if (wasEmpty) this._exportsAreOrdered = true; + return message; + }) + .join("\n"); +}; + +class CaseSensitiveModulesWarning extends WebpackError { + /** + * Creates an instance of CaseSensitiveModulesWarning. + * @param {Iterable} modules modules that were detected + * @param {ModuleGraph} moduleGraph the module graph + */ + constructor(modules, moduleGraph) { + const sortedModules = sortModules(Array.from(modules)); + const modulesList = createModulesListMessage(sortedModules, moduleGraph); + super(`There are multiple modules with names that only differ in casing. +This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. +Use equal casing. Compare these module identifiers: +${modulesList}`); + + this.name = "CaseSensitiveModulesWarning"; + this.module = sortedModules[0]; } } -class ExportInfo { +module.exports = CaseSensitiveModulesWarning; + + +/***/ }), + +/***/ 39385: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const ChunkGraph = __webpack_require__(64971); +const Entrypoint = __webpack_require__(13795); +const { intersect } = __webpack_require__(93347); +const SortableSet = __webpack_require__(13098); +const StringXor = __webpack_require__(40293); +const { + compareModulesByIdentifier, + compareChunkGroupsByIndex, + compareModulesById +} = __webpack_require__(29579); +const { createArrayToSetDeprecationSet } = __webpack_require__(64518); +const { mergeRuntime } = __webpack_require__(17156); + +/** @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} hash + * @property {Record>} contentHash + * @property {Record} name + */ + +/** + * @deprecated + * @typedef {Object} ChunkModuleMaps + * @property {Record} id + * @property {Record} 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 the original name of the export - * @param {ExportInfo=} initFrom init values from this ExportInfo + * @param {string=} name of chunk being created, is optional (for subclasses) + * @param {boolean} backCompat enable backward-compatibility */ - constructor(name, initFrom) { + constructor(name, backCompat = true) { + /** @type {number | string | null} */ + this.id = null; + /** @type {(number|string)[] | null} */ + this.ids = null; + /** @type {number} */ + this.debugId = debugId++; /** @type {string} */ this.name = name; - /** @private @type {string | null} */ - this._usedName = initFrom ? initFrom._usedName : null; - /** @private @type {UsageStateType} */ - this._globalUsed = initFrom ? initFrom._globalUsed : undefined; - /** @private @type {Map} */ - this._usedInRuntime = - initFrom && initFrom._usedInRuntime - ? new Map(initFrom._usedInRuntime) - : undefined; - /** @private @type {boolean} */ - this._hasUseInRuntimeInfo = initFrom - ? initFrom._hasUseInRuntimeInfo - : false; - /** - * true: it is provided - * false: it is not provided - * null: only the runtime knows if it is provided - * undefined: it was not determined if it is provided - * @type {boolean | null | undefined} - */ - this.provided = initFrom ? initFrom.provided : undefined; - /** - * is the export a terminal binding that should be checked for export star conflicts - * @type {boolean} - */ - this.terminalBinding = initFrom ? initFrom.terminalBinding : false; - /** - * true: it can be mangled - * false: is can not be mangled - * undefined: it was not determined if it can be mangled - * @type {boolean | undefined} - */ - this.canMangleProvide = initFrom ? initFrom.canMangleProvide : undefined; - /** - * true: it can be mangled - * false: is can not be mangled - * undefined: it was not determined if it can be mangled - * @type {boolean | undefined} - */ - this.canMangleUse = initFrom ? initFrom.canMangleUse : undefined; + /** @type {SortableSet} */ + this.idNameHints = new SortableSet(); /** @type {boolean} */ - this.exportsInfoOwned = false; - /** @type {ExportsInfo=} */ - this.exportsInfo = undefined; - /** @type {Map=} */ - this._target = undefined; - if (initFrom && initFrom._target) { - this._target = new Map(); - for (const [key, value] of initFrom._target) { - this._target.set(key, { - connection: value.connection, - export: value.export || [name], - priority: value.priority - }); - } + this.preventIntegration = false; + /** @type {(string | function(PathData, AssetInfo=): string)?} */ + this.filenameTemplate = undefined; + /** @type {(string | function(PathData, AssetInfo=): string)?} */ + this.cssFilenameTemplate = undefined; + /** @private @type {SortableSet} */ + this._groups = new SortableSet(undefined, compareChunkGroupsByIndex); + /** @type {RuntimeSpec} */ + this.runtime = undefined; + /** @type {Set} */ + this.files = backCompat ? new ChunkFilesSet() : new Set(); + /** @type {Set} */ + this.auxiliaryFiles = new Set(); + /** @type {boolean} */ + this.rendered = false; + /** @type {string=} */ + this.hash = undefined; + /** @type {Record} */ + 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)" + ); } - /** @type {Map=} */ - this._maxTarget = undefined; } - // TODO webpack 5 remove - /** @private */ - get used() { - throw new Error("REMOVED"); + /** + * @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 + ); } - /** @private */ - get usedName() { - throw new Error("REMOVED"); + + /** + * @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; } + /** - * @private - * @param {*} v v + * @param {Module} module the module + * @returns {void} */ - set used(v) { - throw new Error("REMOVED"); + removeModule(module) { + ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.removeModule", + "DEP_WEBPACK_CHUNK_REMOVE_MODULE" + ).disconnectChunkAndModule(this, module); } + /** - * @private - * @param {*} v v + * @returns {number} the number of module which are contained in this chunk */ - set usedName(v) { - throw new Error("REMOVED"); + getNumberOfModules() { + return ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.getNumberOfModules", + "DEP_WEBPACK_CHUNK_GET_NUMBER_OF_MODULES" + ).getNumberOfChunkModules(this); } - get canMangle() { - switch (this.canMangleProvide) { - case undefined: - return this.canMangleUse === false ? false : undefined; - case false: - return false; - case true: - switch (this.canMangleUse) { - case undefined: - return undefined; - case false: - return false; - case true: - return true; - } - } - throw new Error( - `Unexpected flags for canMangle ${this.canMangleProvide} ${this.canMangleUse}` + get modulesIterable() { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.modulesIterable", + "DEP_WEBPACK_CHUNK_MODULES_ITERABLE" + ); + return chunkGraph.getOrderedChunkModulesIterable( + this, + compareModulesByIdentifier ); } /** - * @param {RuntimeSpec} runtime only apply to this runtime - * @returns {boolean} true, when something changed + * @param {Chunk} otherChunk the chunk to compare with + * @returns {-1|0|1} the comparison result */ - setUsedInUnknownWay(runtime) { - let changed = false; - if ( - this.setUsedConditionally( - used => used < UsageState.Unknown, - UsageState.Unknown, - runtime - ) - ) { - changed = true; - } - if (this.canMangleUse !== false) { - this.canMangleUse = false; - changed = true; - } - return changed; + compareTo(otherChunk) { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.compareTo", + "DEP_WEBPACK_CHUNK_COMPARE_TO" + ); + return chunkGraph.compareChunks(this, otherChunk); } /** - * @param {RuntimeSpec} runtime only apply to this runtime - * @returns {boolean} true, when something changed + * @param {Module} module the module + * @returns {boolean} true, if the chunk contains the module */ - setUsedWithoutInfo(runtime) { - let changed = false; - if (this.setUsed(UsageState.NoInfo, runtime)) { - changed = true; - } - if (this.canMangleUse !== false) { - this.canMangleUse = false; - changed = true; - } - return changed; + containsModule(module) { + return ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.containsModule", + "DEP_WEBPACK_CHUNK_CONTAINS_MODULE" + ).isModuleInChunk(module, this); } - setHasUseInfo() { - if (!this._hasUseInRuntimeInfo) { - this._hasUseInRuntimeInfo = true; - } - if (this.canMangleUse === undefined) { - this.canMangleUse = true; - } - if (this.exportsInfoOwned) { - this.exportsInfo.setHasUseInfo(); - } + /** + * @returns {Module[]} the modules for this chunk + */ + getModules() { + return ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.getModules", + "DEP_WEBPACK_CHUNK_GET_MODULES" + ).getChunkModules(this); } /** - * @param {function(UsageStateType): boolean} condition compare with old value - * @param {UsageStateType} newValue set when condition is true - * @param {RuntimeSpec} runtime only apply to this runtime - * @returns {boolean} true when something has changed + * @returns {void} */ - setUsedConditionally(condition, newValue, runtime) { - if (runtime === undefined) { - if (this._globalUsed === undefined) { - this._globalUsed = newValue; - return true; - } else { - if (this._globalUsed !== newValue && condition(this._globalUsed)) { - this._globalUsed = newValue; - return true; - } - } - } else if (this._usedInRuntime === undefined) { - if (newValue !== UsageState.Unused && condition(UsageState.Unused)) { - this._usedInRuntime = new Map(); - forEachRuntime(runtime, runtime => - this._usedInRuntime.set(runtime, newValue) - ); - return true; - } + 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 { - let changed = false; - forEachRuntime(runtime, runtime => { - /** @type {UsageStateType} */ - let oldValue = this._usedInRuntime.get(runtime); - if (oldValue === undefined) oldValue = UsageState.Unused; - if (newValue !== oldValue && condition(oldValue)) { - if (newValue === UsageState.Unused) { - this._usedInRuntime.delete(runtime); - } else { - this._usedInRuntime.set(runtime, newValue); + 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} */ + const chunkModuleIdMap = Object.create(null); + /** @type {Record} */ + 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; } - changed = true; + const moduleId = chunkGraph.getModuleId(module); + array.push(moduleId); + chunkModuleHashMap[moduleId] = chunkGraph.getRenderedModuleHash( + module, + undefined + ); } - }); - if (changed) { - if (this._usedInRuntime.size === 0) this._usedInRuntime = undefined; - return true; } } - return false; + + return { + id: chunkModuleIdMap, + hash: chunkModuleHashMap + }; } /** - * @param {UsageStateType} newValue new value of the used state - * @param {RuntimeSpec} runtime only apply to this runtime - * @returns {boolean} true when something has changed + * @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 */ - setUsed(newValue, runtime) { - if (runtime === undefined) { - if (this._globalUsed !== newValue) { - this._globalUsed = newValue; - return true; - } - } else if (this._usedInRuntime === undefined) { - if (newValue !== UsageState.Unused) { - this._usedInRuntime = new Map(); - forEachRuntime(runtime, runtime => - this._usedInRuntime.set(runtime, newValue) - ); - return true; - } - } else { - let changed = false; - forEachRuntime(runtime, runtime => { - /** @type {UsageStateType} */ - let oldValue = this._usedInRuntime.get(runtime); - if (oldValue === undefined) oldValue = UsageState.Unused; - if (newValue !== oldValue) { - if (newValue === UsageState.Unused) { - this._usedInRuntime.delete(runtime); - } else { - this._usedInRuntime.set(runtime, newValue); - } - changed = true; + 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} */ + const chunkHashMap = Object.create(null); + /** @type {Record>} */ + const chunkContentHashMap = Object.create(null); + /** @type {Record} */ + 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); } - }); - if (changed) { - if (this._usedInRuntime.size === 0) this._usedInRuntime = undefined; - return true; + chunkContentHashMap[key][chunk.id] = chunk.contentHash[key]; + } + if (chunk.name) { + chunkNameMap[chunk.id] = chunk.name; } } - return false; + + return { + hash: chunkHashMap, + contentHash: chunkContentHashMap, + name: chunkNameMap + }; } + // BACKWARD-COMPAT END /** - * @param {any} key the key - * @returns {boolean} true, if something has changed + * @returns {boolean} whether or not the Chunk will have a runtime */ - unsetTarget(key) { - if (!this._target) return false; - if (this._target.delete(key)) { - this._maxTarget = undefined; - return true; + hasRuntime() { + for (const chunkGroup of this._groups) { + if ( + chunkGroup instanceof Entrypoint && + chunkGroup.getRuntimeChunk() === this + ) { + return true; + } } return false; } /** - * @param {any} key the key - * @param {ModuleGraphConnection} connection the target module if a single one - * @param {string[]=} exportName the exported name - * @param {number=} priority priority - * @returns {boolean} true, if something has changed + * @returns {boolean} whether or not this chunk can be an initial chunk */ - setTarget(key, connection, exportName, priority = 0) { - if (exportName) exportName = [...exportName]; - if (!this._target) { - this._target = new Map(); - this._target.set(key, { connection, export: exportName, priority }); - return true; - } - const oldTarget = this._target.get(key); - if (!oldTarget) { - if (oldTarget === null && !connection) return false; - this._target.set(key, { connection, export: exportName, priority }); - this._maxTarget = undefined; - return true; - } - if ( - oldTarget.connection !== connection || - oldTarget.priority !== priority || - (exportName - ? !oldTarget.export || !equals(oldTarget.export, exportName) - : oldTarget.export) - ) { - oldTarget.connection = connection; - oldTarget.export = exportName; - oldTarget.priority = priority; - this._maxTarget = undefined; - return true; + canBeInitial() { + for (const chunkGroup of this._groups) { + if (chunkGroup.isInitial()) return true; } return false; } /** - * @param {RuntimeSpec} runtime for this runtime - * @returns {UsageStateType} usage state + * @returns {boolean} whether this chunk can only be an initial chunk */ - getUsed(runtime) { - if (!this._hasUseInRuntimeInfo) return UsageState.NoInfo; - if (this._globalUsed !== undefined) return this._globalUsed; - if (this._usedInRuntime === undefined) { - return UsageState.Unused; - } else if (typeof runtime === "string") { - const value = this._usedInRuntime.get(runtime); - return value === undefined ? UsageState.Unused : value; - } else if (runtime === undefined) { - /** @type {UsageStateType} */ - let max = UsageState.Unused; - for (const value of this._usedInRuntime.values()) { - if (value === UsageState.Used) { - return UsageState.Used; - } - if (max < value) max = value; - } - return max; - } else { - /** @type {UsageStateType} */ - let max = UsageState.Unused; - for (const item of runtime) { - const value = this._usedInRuntime.get(item); - if (value !== undefined) { - if (value === UsageState.Used) { - return UsageState.Used; - } - if (max < value) max = value; - } - } - return max; + isOnlyInitial() { + if (this._groups.size <= 0) return false; + for (const chunkGroup of this._groups) { + if (!chunkGroup.isInitial()) return false; } + return true; } /** - * get used name - * @param {string | undefined} fallbackName fallback name for used exports with no name - * @param {RuntimeSpec} runtime check usage for this runtime only - * @returns {string | false} used name + * @returns {EntryOptions | undefined} the entry options for this chunk */ - getUsedName(fallbackName, runtime) { - if (this._hasUseInRuntimeInfo) { - if (this._globalUsed !== undefined) { - if (this._globalUsed === UsageState.Unused) return false; - } else { - if (this._usedInRuntime === undefined) return false; - if (typeof runtime === "string") { - if (!this._usedInRuntime.has(runtime)) { - return false; - } - } else if (runtime !== undefined) { - if ( - Array.from(runtime).every( - runtime => !this._usedInRuntime.has(runtime) - ) - ) { - return false; - } - } + getEntryOptions() { + for (const chunkGroup of this._groups) { + if (chunkGroup instanceof Entrypoint) { + return chunkGroup.options; } } - if (this._usedName !== null) return this._usedName; - return this.name || fallbackName; + return undefined; } /** - * @returns {boolean} true, when a mangled name of this export is set + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being added + * @returns {void} */ - hasUsedName() { - return this._usedName !== null; + addGroup(chunkGroup) { + this._groups.add(chunkGroup); } /** - * Sets the mangled name of this export - * @param {string} name the new name + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being removed from * @returns {void} */ - setUsedName(name) { - this._usedName = name; + removeGroup(chunkGroup) { + this._groups.delete(chunkGroup); } /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target - * @returns {ExportInfo | ExportsInfo | undefined} the terminal binding export(s) info if known + * @param {ChunkGroup} chunkGroup the chunkGroup to check + * @returns {boolean} returns true if chunk has chunkGroup reference and exists in chunkGroup */ - getTerminalBinding(moduleGraph, resolveTargetFilter = RETURNS_TRUE) { - if (this.terminalBinding) return this; - const target = this.getTarget(moduleGraph, resolveTargetFilter); - if (!target) return undefined; - const exportsInfo = moduleGraph.getExportsInfo(target.module); - if (!target.export) return exportsInfo; - return exportsInfo.getReadOnlyExportInfoRecursive(target.export); + isInGroup(chunkGroup) { + return this._groups.has(chunkGroup); } - isReexport() { - return !this.terminalBinding && this._target && this._target.size > 0; + /** + * @returns {number} the amount of groups that the said chunk is in + */ + getNumberOfGroups() { + return this._groups.size; } - _getMaxTarget() { - if (this._maxTarget !== undefined) return this._maxTarget; - if (this._target.size <= 1) return (this._maxTarget = this._target); - let maxPriority = -Infinity; - let minPriority = Infinity; - for (const { priority } of this._target.values()) { - if (maxPriority < priority) maxPriority = priority; - if (minPriority > priority) minPriority = priority; - } - // This should be very common - if (maxPriority === minPriority) return (this._maxTarget = this._target); - - // This is an edge case - const map = new Map(); - for (const [key, value] of this._target) { - if (maxPriority === value.priority) { - map.set(key, value); - } - } - this._maxTarget = map; - return map; + /** + * @returns {Iterable} the chunkGroups that the said chunk is referenced in + */ + get groupsIterable() { + this._groups.sort(); + return this._groups; } /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {function(Module): boolean} validTargetModuleFilter a valid target module - * @returns {{ module: Module, export: string[] | undefined } | undefined | false} the target, undefined when there is no target, false when no target is valid + * @returns {void} */ - findTarget(moduleGraph, validTargetModuleFilter) { - return this._findTarget(moduleGraph, validTargetModuleFilter, new Set()); + disconnectFromGroups() { + for (const chunkGroup of this._groups) { + chunkGroup.removeChunk(this); + } } /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {function(Module): boolean} validTargetModuleFilter a valid target module - * @param {Set | undefined} alreadyVisited set of already visited export info to avoid circular references - * @returns {{ module: Module, export: string[] | undefined } | undefined | false} the target, undefined when there is no target, false when no target is valid + * @param {Chunk} newChunk the new chunk that will be split out of + * @returns {void} */ - _findTarget(moduleGraph, validTargetModuleFilter, alreadyVisited) { - if (!this._target || this._target.size === 0) return undefined; - let rawTarget = this._getMaxTarget().values().next().value; - if (!rawTarget) return undefined; - /** @type {{ module: Module, export: string[] | undefined }} */ - let target = { - module: rawTarget.connection.module, - export: rawTarget.export - }; - for (;;) { - if (validTargetModuleFilter(target.module)) return target; - const exportsInfo = moduleGraph.getExportsInfo(target.module); - const exportInfo = exportsInfo.getExportInfo(target.export[0]); - if (alreadyVisited.has(exportInfo)) return null; - const newTarget = exportInfo._findTarget( - moduleGraph, - validTargetModuleFilter, - alreadyVisited - ); - if (!newTarget) return false; - if (target.export.length === 1) { - target = newTarget; - } else { - target = { - module: newTarget.module, - export: newTarget.export - ? newTarget.export.concat(target.export.slice(1)) - : target.export.slice(1) - }; - } + 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 {ModuleGraph} moduleGraph the module graph - * @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target - * @returns {{ module: Module, export: string[] | undefined } | undefined} the target + * @param {Hash} hash hash (will be modified) + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} */ - getTarget(moduleGraph, resolveTargetFilter = RETURNS_TRUE) { - const result = this._getTarget(moduleGraph, resolveTargetFilter, undefined); - if (result === CIRCULAR) return undefined; - return result; + updateHash(hash, chunkGraph) { + hash.update( + `${this.id} ${this.ids ? this.ids.join() : ""} ${this.name || ""} ` + ); + const xor = new StringXor(); + for (const m of chunkGraph.getChunkModulesIterable(this)) { + xor.add(chunkGraph.getModuleHash(m, this.runtime)); + } + xor.updateHash(hash); + const entryModules = + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(this); + for (const [m, chunkGroup] of entryModules) { + hash.update(`entry${chunkGraph.getModuleId(m)}${chunkGroup.id}`); + } } /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {function({ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target - * @param {Set | undefined} alreadyVisited set of already visited export info to avoid circular references - * @returns {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined } | CIRCULAR | undefined} the target + * @returns {Set} a set of all the async chunks */ - _getTarget(moduleGraph, resolveTargetFilter, alreadyVisited) { - /** - * @param {{ connection: ModuleGraphConnection, export: string[] | undefined } | null} inputTarget unresolved target - * @param {Set} alreadyVisited set of already visited export info to avoid circular references - * @returns {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined } | CIRCULAR | null} resolved target - */ - const resolveTarget = (inputTarget, alreadyVisited) => { - if (!inputTarget) return null; - if (!inputTarget.export) { - return { - module: inputTarget.connection.module, - connection: inputTarget.connection, - export: undefined - }; + getAllAsyncChunks() { + const queue = new Set(); + const chunks = new Set(); + + const initialChunks = intersect( + Array.from(this.groupsIterable, g => new Set(g.chunks)) + ); + + const initialQueue = new Set(this.groupsIterable); + + for (const chunkGroup of initialQueue) { + for (const child of chunkGroup.childrenIterable) { + if (child instanceof Entrypoint) { + initialQueue.add(child); + } else { + queue.add(child); + } } - /** @type {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }} */ - let target = { - module: inputTarget.connection.module, - connection: inputTarget.connection, - export: inputTarget.export - }; - if (!resolveTargetFilter(target)) return target; - let alreadyVisitedOwned = false; - for (;;) { - const exportsInfo = moduleGraph.getExportsInfo(target.module); - const exportInfo = exportsInfo.getExportInfo(target.export[0]); - if (!exportInfo) return target; - if (alreadyVisited.has(exportInfo)) return CIRCULAR; - const newTarget = exportInfo._getTarget( - moduleGraph, - resolveTargetFilter, - alreadyVisited - ); - if (newTarget === CIRCULAR) return CIRCULAR; - if (!newTarget) return target; - if (target.export.length === 1) { - target = newTarget; - if (!target.export) return target; - } else { - target = { - module: newTarget.module, - connection: newTarget.connection, - export: newTarget.export - ? newTarget.export.concat(target.export.slice(1)) - : target.export.slice(1) - }; - } - if (!resolveTargetFilter(target)) return target; - if (!alreadyVisitedOwned) { - alreadyVisited = new Set(alreadyVisited); - alreadyVisitedOwned = true; + } + + for (const chunkGroup of queue) { + for (const chunk of chunkGroup.chunks) { + if (!initialChunks.has(chunk)) { + chunks.add(chunk); } - alreadyVisited.add(exportInfo); } - }; - - if (!this._target || this._target.size === 0) return undefined; - if (alreadyVisited && alreadyVisited.has(this)) return CIRCULAR; - const newAlreadyVisited = new Set(alreadyVisited); - newAlreadyVisited.add(this); - const values = this._getMaxTarget().values(); - const target = resolveTarget(values.next().value, newAlreadyVisited); - if (target === CIRCULAR) return CIRCULAR; - if (target === null) return undefined; - let result = values.next(); - while (!result.done) { - const t = resolveTarget(result.value, newAlreadyVisited); - if (t === CIRCULAR) return CIRCULAR; - if (t === null) return undefined; - if (t.module !== target.module) return undefined; - if (!t.export !== !target.export) return undefined; - if (target.export && !equals(t.export, target.export)) return undefined; - result = values.next(); + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } } - return target; + + return chunks; } /** - * Move the target forward as long resolveTargetFilter is fulfilled - * @param {ModuleGraph} moduleGraph the module graph - * @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target - * @param {function({ module: Module, export: string[] | undefined }): ModuleGraphConnection=} updateOriginalConnection updates the original connection instead of using the target connection - * @returns {{ module: Module, export: string[] | undefined } | undefined} the resolved target when moved + * @returns {Set} a set of all the initial chunks (including itself) */ - moveTarget(moduleGraph, resolveTargetFilter, updateOriginalConnection) { - const target = this._getTarget(moduleGraph, resolveTargetFilter, undefined); - if (target === CIRCULAR) return undefined; - if (!target) return undefined; - const originalTarget = this._getMaxTarget().values().next().value; - if ( - originalTarget.connection === target.connection && - originalTarget.export === target.export - ) { - return undefined; + getAllInitialChunks() { + const chunks = new Set(); + const queue = new Set(this.groupsIterable); + for (const group of queue) { + if (group.isInitial()) { + for (const c of group.chunks) chunks.add(c); + for (const g of group.childrenIterable) queue.add(g); + } } - this._target.clear(); - this._target.set(undefined, { - connection: updateOriginalConnection - ? updateOriginalConnection(target) - : target.connection, - export: target.export, - priority: 0 - }); - return target; + return chunks; } - createNestedExportsInfo() { - if (this.exportsInfoOwned) return this.exportsInfo; - this.exportsInfoOwned = true; - const oldExportsInfo = this.exportsInfo; - this.exportsInfo = new ExportsInfo(); - this.exportsInfo.setHasProvideInfo(); - if (oldExportsInfo) { - this.exportsInfo.setRedirectNamedTo(oldExportsInfo); + /** + * @returns {Set} 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 this.exportsInfo; - } - getNestedExportsInfo() { - return this.exportsInfo; + return chunks; } - hasInfo(baseInfo, runtime) { - return ( - (this._usedName && this._usedName !== this.name) || - this.provided || - this.terminalBinding || - this.getUsed(runtime) !== baseInfo.getUsed(runtime) - ); - } + /** + * @returns {Set} a set of all the referenced entrypoints + */ + getAllReferencedAsyncEntrypoints() { + const queue = new Set(this.groupsIterable); + const entrypoints = new Set(); - updateHash(hash, runtime) { - this._updateHash(hash, runtime, 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; } - _updateHash(hash, runtime, alreadyVisitedExportsInfo) { - hash.update( - `${this._usedName || this.name}${this.getUsed(runtime)}${this.provided}${ - this.terminalBinding - }` + /** + * @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)) ); - if (this.exportsInfo && !alreadyVisitedExportsInfo.has(this.exportsInfo)) { - this.exportsInfo._updateHash(hash, runtime, alreadyVisitedExportsInfo); - } - } - getUsedInfo() { - if (this._globalUsed !== undefined) { - switch (this._globalUsed) { - case UsageState.Unused: - return "unused"; - case UsageState.NoInfo: - return "no usage info"; - case UsageState.Unknown: - return "maybe used (runtime-defined)"; - case UsageState.Used: - return "used"; - case UsageState.OnlyPropertiesUsed: - return "only properties used"; - } - } else if (this._usedInRuntime !== undefined) { - /** @type {Map} */ - const map = new Map(); - for (const [runtime, used] of this._usedInRuntime) { - const list = map.get(used); - if (list !== undefined) list.push(runtime); - else map.set(used, [runtime]); + for (const chunkGroup of this.groupsIterable) { + for (const child of chunkGroup.childrenIterable) { + queue.add(child); } - const specificInfo = Array.from(map, ([used, runtimes]) => { - switch (used) { - case UsageState.NoInfo: - return `no usage info in ${runtimes.join(", ")}`; - case UsageState.Unknown: - return `maybe used in ${runtimes.join(", ")} (runtime-defined)`; - case UsageState.Used: - return `used in ${runtimes.join(", ")}`; - case UsageState.OnlyPropertiesUsed: - return `only properties used in ${runtimes.join(", ")}`; + } + + for (const chunkGroup of queue) { + for (const chunk of chunkGroup.chunks) { + if (!initialChunks.has(chunk)) { + return true; } - }); - if (specificInfo.length > 0) { - return specificInfo.join("; "); + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); } } - return this._hasUseInRuntimeInfo ? "unused" : "no usage info"; + + return false; } - getProvidedInfo() { - switch (this.provided) { - case undefined: - return "no provided info"; - case null: - return "maybe provided (runtime-defined)"; - case true: - return "provided"; - case false: - return "not provided"; + /** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {ChunkFilterPredicate=} filterFn function used to filter chunks + * @returns {Record} a record object of names to lists of child ids(?) + */ + getChildIdsByOrders(chunkGraph, filterFn) { + /** @type {Map} */ + 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} */ + 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} */ + 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; } - getRenameInfo() { - if (this._usedName !== null && this._usedName !== this.name) { - return `renamed to ${JSON.stringify(this._usedName).slice(1, -1)}`; + /** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} type option name + * @returns {{ onChunks: Chunk[], chunks: Set }[]} 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 + }); + } } - switch (this.canMangleProvide) { - case undefined: - switch (this.canMangleUse) { - case undefined: - return "missing provision and use info prevents renaming"; - case false: - return "usage prevents renaming (no provision info)"; - case true: - return "missing provision info prevents renaming"; - } - break; - case true: - switch (this.canMangleUse) { - case undefined: - return "missing usage info prevents renaming"; - case false: - return "usage prevents renaming"; - case true: - return "could be renamed"; - } - break; - case false: - switch (this.canMangleUse) { - case undefined: - return "provision prevents renaming (no use info)"; - case false: - return "usage and provision prevents renaming"; - case true: - return "provision prevents renaming"; + 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); } - break; + } else { + result.push( + (lastEntry = { + onChunks: group.chunks, + chunks: new Set(childGroup.chunks) + }) + ); + } } - throw new Error( - `Unexpected flags for getRenameInfo ${this.canMangleProvide} ${this.canMangleUse}` - ); + return result; } -} - -module.exports = ExportsInfo; -module.exports.ExportInfo = ExportInfo; -module.exports.UsageState = UsageState; - - -/***/ }), - -/***/ 7145: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @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>} a record object of names to lists of child ids(?) by chunk id + */ + getChildIdsByOrdersMap(chunkGraph, includeDirectChildren, filterFn) { + /** @type {Record>} */ + 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]; + } + }; -const ConstDependency = __webpack_require__(76911); -const ExportsInfoDependency = __webpack_require__(78988); + if (includeDirectChildren) { + /** @type {Set} */ + 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); + } + } -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ + for (const chunk of this.getAllAsyncChunks()) { + addChildIdsByOrdersToMap(chunk); + } -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); - } - ); + return chunkMaps; } } -module.exports = ExportsInfoApiPlugin; +module.exports = Chunk; /***/ }), -/***/ 73071: +/***/ 64971: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -35879,4636 +31744,3292 @@ module.exports = ExportsInfoApiPlugin; -const { OriginalSource, RawSource } = __webpack_require__(51255); -const ConcatenationScope = __webpack_require__(98229); -const { UsageState } = __webpack_require__(63686); -const InitFragment = __webpack_require__(55870); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const StaticExportsDependency = __webpack_require__(91418); +const util = __webpack_require__(73837); +const Entrypoint = __webpack_require__(13795); +const ModuleGraphConnection = __webpack_require__(40639); +const { first } = __webpack_require__(93347); +const SortableSet = __webpack_require__(13098); +const { + compareModulesById, + compareIterables, + compareModulesByIdentifier, + concatComparators, + compareSelect, + compareIds +} = __webpack_require__(29579); const createHash = __webpack_require__(49835); -const extractUrlAndGlobal = __webpack_require__(11850); -const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const { register } = __webpack_require__(8282); +const findGraphRoots = __webpack_require__(6261); +const { + RuntimeSpecMap, + RuntimeSpecSet, + runtimeToString, + mergeRuntime, + forEachRuntime +} = __webpack_require__(17156); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ /** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./ExportsInfo")} ExportsInfo */ -/** @typedef {import("./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("./NormalModuleFactory")} NormalModuleFactory */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ -/** @typedef {import("./util/Hash")} Hash */ -/** @typedef {typeof import("./util/Hash")} HashConstructor */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./RuntimeModule")} RuntimeModule */ +/** @typedef {typeof import("./util/Hash")} Hash */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ -/** - * @typedef {Object} SourceData - * @property {boolean=} iife - * @property {string=} init - * @property {string} expression - * @property {InitFragment[]=} chunkInitFragments - * @property {ReadonlySet=} runtimeRequirements - */ +/** @type {ReadonlySet} */ +const EMPTY_SET = new Set(); -const TYPES = new Set(["javascript"]); -const CSS_TYPES = new Set(["css-import"]); -const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); -const RUNTIME_REQUIREMENTS_FOR_SCRIPT = new Set([RuntimeGlobals.loadScript]); -const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([ - RuntimeGlobals.definePropertyGetters -]); -const EMPTY_RUNTIME_REQUIREMENTS = new Set([]); +const ZERO_BIG_INT = BigInt(0); + +const compareModuleIterables = compareIterables(compareModulesByIdentifier); + +/** @typedef {(c: Chunk, chunkGraph: ChunkGraph) => boolean} ChunkFilterPredicate */ +/** @typedef {(m: Module) => boolean} ModuleFilterPredicate */ /** - * @param {string|string[]} variableName the variable name or path - * @param {string} type the module system - * @returns {SourceData} the generated source + * @typedef {Object} ChunkSizeOptions + * @property {number=} chunkOverhead constant overhead for a chunk + * @property {number=} entryChunkMultiplicator multiplicator for initial chunks */ -const getSourceForGlobalVariableExternal = (variableName, type) => { - if (!Array.isArray(variableName)) { - // make it an array as the look up works the same basically - variableName = [variableName]; + +class ModuleHashInfo { + constructor(hash, renderedHash) { + this.hash = hash; + this.renderedHash = renderedHash; } +} - // needed for e.g. window["some"]["thing"] - const objectLookup = variableName.map(r => `[${JSON.stringify(r)}]`).join(""); - return { - iife: type === "this", - expression: `${type}${objectLookup}` - }; -}; +/** @template T @typedef {(set: SortableSet) => T[]} SetToArrayFunction */ /** - * @param {string|string[]} moduleAndSpecifiers the module request - * @returns {SourceData} the generated source + * @template T + * @param {SortableSet} set the set + * @returns {T[]} set as array */ -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 - )}` - }; +const getArray = set => { + return Array.from(set); }; /** - * @param {string|string[]} moduleAndSpecifiers the module request - * @returns {SourceData} the generated source + * @param {SortableSet} chunks the chunks + * @returns {RuntimeSpecSet} runtimes */ -const getSourceForCommonJsExternalInNodeModule = moduleAndSpecifiers => { - const chunkInitFragments = [ - new InitFragment( - 'import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module";\n', - InitFragment.STAGE_HARMONY_IMPORTS, - 0, - "external module node-commonjs" - ) - ]; - if (!Array.isArray(moduleAndSpecifiers)) { - return { - expression: `__WEBPACK_EXTERNAL_createRequire(import.meta.url)(${JSON.stringify( - moduleAndSpecifiers - )})`, - chunkInitFragments - }; +const getModuleRuntimes = chunks => { + const runtimes = new RuntimeSpecSet(); + for (const chunk of chunks) { + runtimes.add(chunk.runtime); } - const moduleName = moduleAndSpecifiers[0]; - return { - expression: `__WEBPACK_EXTERNAL_createRequire(import.meta.url)(${JSON.stringify( - moduleName - )})${propertyAccess(moduleAndSpecifiers, 1)}`, - chunkInitFragments - }; + return runtimes; }; /** - * @param {string|string[]} moduleAndSpecifiers the module request - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @returns {SourceData} the generated source + * @param {SortableSet} set the set + * @returns {Map>} modules by source type */ -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" - )});` - }; -}; - -class ModuleExternalInitFragment extends InitFragment { - /** - * @param {string} request import source - * @param {string=} ident recomputed ident - * @param {string | HashConstructor=} hashFunction the hash function to use - */ - constructor(request, ident, hashFunction = "md4") { - if (ident === undefined) { - ident = Template.toIdentifier(request); - if (ident !== request) { - ident += `_${createHash(hashFunction) - .update(request) - .digest("hex") - .slice(0, 8)}`; +const modulesBySourceType = set => { + /** @type {Map>} */ + const map = new Map(); + for (const module of set) { + for (const sourceType of module.getSourceTypes()) { + let innerSet = map.get(sourceType); + if (innerSet === undefined) { + innerSet = new SortableSet(); + map.set(sourceType, innerSet); } - } - const identifier = `__WEBPACK_EXTERNAL_MODULE_${ident}__`; - super( - `import * as ${identifier} from ${JSON.stringify(request)};\n`, - InitFragment.STAGE_HARMONY_IMPORTS, - 0, - `external module import ${ident}` - ); - this._ident = ident; - this._identifier = identifier; - this._request = request; - } - - getNamespaceIdentifier() { - return this._identifier; - } -} - -register( - ModuleExternalInitFragment, - "webpack/lib/ExternalModule", - "ModuleExternalInitFragment", - { - serialize(obj, { write }) { - write(obj._request); - write(obj._ident); - }, - deserialize({ read }) { - return new ModuleExternalInitFragment(read(), read()); + innerSet.add(module); } } -); - -const generateModuleRemapping = (input, exportsInfo, runtime) => { - if (exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused) { - const properties = []; - for (const exportInfo of exportsInfo.orderedExports) { - const used = exportInfo.getUsedName(exportInfo.name, runtime); - if (!used) continue; - const nestedInfo = exportInfo.getNestedExportsInfo(); - if (nestedInfo) { - const nestedExpr = generateModuleRemapping( - `${input}${propertyAccess([exportInfo.name])}`, - nestedInfo - ); - if (nestedExpr) { - properties.push(`[${JSON.stringify(used)}]: y(${nestedExpr})`); - continue; - } - } - properties.push( - `[${JSON.stringify(used)}]: () => ${input}${propertyAccess([ - exportInfo.name - ])}` - ); + for (const [key, innerSet] of map) { + // When all modules have the source type, we reuse the original SortableSet + // to benefit from the shared cache (especially for sorting) + if (innerSet.size === set.size) { + map.set(key, set); } - return `x({ ${properties.join(", ")} })`; } + return map; }; -/** - * @param {string|string[]} moduleAndSpecifiers the module request - * @param {ExportsInfo} exportsInfo exports info of this module - * @param {RuntimeSpec} runtime the runtime - * @param {string | HashConstructor=} hashFunction the hash function to use - * @returns {SourceData} the generated source - */ -const getSourceForModuleExternal = ( - moduleAndSpecifiers, - exportsInfo, - runtime, - hashFunction -) => { - if (!Array.isArray(moduleAndSpecifiers)) - moduleAndSpecifiers = [moduleAndSpecifiers]; - const initFragment = new ModuleExternalInitFragment( - moduleAndSpecifiers[0], - undefined, - hashFunction - ); - const baseAccess = `${initFragment.getNamespaceIdentifier()}${propertyAccess( - moduleAndSpecifiers, - 1 - )}`; - const moduleRemapping = generateModuleRemapping( - baseAccess, - exportsInfo, - runtime - ); - let expression = moduleRemapping || baseAccess; - return { - expression, - init: `var x = y => { var x = {}; ${RuntimeGlobals.definePropertyGetters}(x, y); return x; }\nvar y = x => () => x`, - runtimeRequirements: moduleRemapping - ? RUNTIME_REQUIREMENTS_FOR_MODULE - : undefined, - chunkInitFragments: [initFragment] - }; -}; +/** @type {WeakMap} */ +const createOrderedArrayFunctionMap = new WeakMap(); /** - * @param {string|string[]} urlAndGlobal the script request - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @returns {SourceData} the generated source + * @template T + * @param {function(T, T): -1|0|1} comparator comparator function + * @returns {SetToArrayFunction} set as ordered array */ -const getSourceForScriptExternal = (urlAndGlobal, runtimeTemplate) => { - if (typeof urlAndGlobal === "string") { - urlAndGlobal = extractUrlAndGlobal(urlAndGlobal); - } - const url = urlAndGlobal[0]; - const globalName = urlAndGlobal[1]; - return { - init: "var __webpack_error__ = new Error();", - expression: `new Promise(${runtimeTemplate.basicFunction( - "resolve, reject", - [ - `if(typeof ${globalName} !== "undefined") return resolve();`, - `${RuntimeGlobals.loadScript}(${JSON.stringify( - url - )}, ${runtimeTemplate.basicFunction("event", [ - `if(typeof ${globalName} !== "undefined") return resolve();`, - "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", - "var realSrc = event && event.target && event.target.src;", - "__webpack_error__.message = 'Loading script failed.\\n(' + errorType + ': ' + realSrc + ')';", - "__webpack_error__.name = 'ScriptExternalLoadError';", - "__webpack_error__.type = errorType;", - "__webpack_error__.request = realSrc;", - "reject(__webpack_error__);" - ])}, ${JSON.stringify(globalName)});` - ] - )}).then(${runtimeTemplate.returningFunction( - `${globalName}${propertyAccess(urlAndGlobal, 2)}` - )})`, - runtimeRequirements: RUNTIME_REQUIREMENTS_FOR_SCRIPT +const createOrderedArrayFunction = comparator => { + /** @type {SetToArrayFunction} */ + let fn = createOrderedArrayFunctionMap.get(comparator); + if (fn !== undefined) return fn; + fn = set => { + set.sortWith(comparator); + return Array.from(set); }; + createOrderedArrayFunctionMap.set(comparator, fn); + return fn; }; /** - * @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 + * @param {Iterable} modules the modules to get the count/size of + * @returns {number} the size of the modules */ -const checkExternalVariable = (variableName, request, runtimeTemplate) => { - return `if(typeof ${variableName} === 'undefined') { ${runtimeTemplate.throwMissingModuleErrorBlock( - { request } - )} }\n`; +const getModulesSize = modules => { + let size = 0; + for (const module of modules) { + for (const type of module.getSourceTypes()) { + size += module.size(type); + } + } + return size; }; /** - * @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 + * @param {Iterable} modules the sortable Set to get the size of + * @returns {Record} the sizes of the modules */ -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 - }; +const getModulesSizes = modules => { + let sizes = Object.create(null); + for (const module of modules) { + for (const type of module.getSourceTypes()) { + sizes[type] = (sizes[type] || 0) + module.size(type); + } + } + return sizes; }; /** - * @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 + * @param {Chunk} a chunk + * @param {Chunk} b chunk + * @returns {boolean} true, if a is always a parent of b */ -const getSourceForDefaultCase = (optional, request, runtimeTemplate) => { - if (!Array.isArray(request)) { - // make it an array as the look up works the same basically - request = [request]; +const isAvailableChunk = (a, b) => { + const queue = new Set(b.groupsIterable); + for (const chunkGroup of queue) { + if (a.isInGroup(chunkGroup)) continue; + if (chunkGroup.isInitial()) return false; + for (const parent of chunkGroup.parentsIterable) { + queue.add(parent); + } } - - const variableName = request[0]; - const objectLookup = propertyAccess(request, 1); - return { - init: optional - ? checkExternalVariable(variableName, request.join("."), runtimeTemplate) - : undefined, - expression: `${variableName}${objectLookup}` - }; + return true; }; -class ExternalModule extends Module { - constructor(request, type, userRequest) { - super("javascript/dynamic", null); - - // Info from Factory - /** @type {string | string[] | Record} */ - this.request = request; - /** @type {string} */ - this.externalType = type; - /** @type {string} */ - this.userRequest = userRequest; +class ChunkGraphModule { + constructor() { + /** @type {SortableSet} */ + this.chunks = new SortableSet(); + /** @type {Set | undefined} */ + this.entryInChunks = undefined; + /** @type {Set | undefined} */ + this.runtimeInChunks = undefined; + /** @type {RuntimeSpecMap} */ + this.hashes = undefined; + /** @type {string | number} */ + this.id = null; + /** @type {RuntimeSpecMap> | undefined} */ + this.runtimeRequirements = undefined; + /** @type {RuntimeSpecMap} */ + this.graphHashes = undefined; + /** @type {RuntimeSpecMap} */ + this.graphHashesWithConnections = undefined; } +} - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return this.externalType === "css-import" ? CSS_TYPES : TYPES; +class ChunkGraphChunk { + constructor() { + /** @type {SortableSet} */ + this.modules = new SortableSet(); + /** @type {Map} */ + this.entryModules = new Map(); + /** @type {SortableSet} */ + this.runtimeModules = new SortableSet(); + /** @type {Set | undefined} */ + this.fullHashModules = undefined; + /** @type {Set | undefined} */ + this.dependentHashModules = undefined; + /** @type {Set | undefined} */ + this.runtimeRequirements = undefined; + /** @type {Set} */ + this.runtimeRequirementsInTree = new Set(); } +} +class ChunkGraph { /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @param {ModuleGraph} moduleGraph the module graph + * @param {string | Hash} hashFunction the hash function to use */ - libIdent(options) { - return this.userRequest; - } + constructor(moduleGraph, hashFunction = "md4") { + /** @private @type {WeakMap} */ + this._modules = new WeakMap(); + /** @private @type {WeakMap} */ + this._chunks = new WeakMap(); + /** @private @type {WeakMap} */ + this._blockChunkGroups = new WeakMap(); + /** @private @type {Map} */ + this._runtimeIds = new Map(); + /** @type {ModuleGraph} */ + this.moduleGraph = moduleGraph; - /** - * @param {Chunk} chunk the chunk which condition should be checked - * @param {Compilation} compilation the compilation - * @returns {boolean} true, if the chunk is ok for the module - */ - chunkCondition(chunk, { chunkGraph }) { - return this.externalType === "css-import" - ? true - : chunkGraph.getNumberOfEntryModules(chunk) > 0; + this._hashFunction = hashFunction; + + this._getGraphRoots = this._getGraphRoots.bind(this); } /** - * @returns {string} a unique identifier of the module + * @private + * @param {Module} module the module + * @returns {ChunkGraphModule} internal module */ - identifier() { - return `external ${this.externalType} ${JSON.stringify(this.request)}`; + _getChunkGraphModule(module) { + let cgm = this._modules.get(module); + if (cgm === undefined) { + cgm = new ChunkGraphModule(); + this._modules.set(module, cgm); + } + return cgm; } /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module + * @private + * @param {Chunk} chunk the chunk + * @returns {ChunkGraphChunk} internal chunk */ - readableIdentifier(requestShortener) { - return "external " + JSON.stringify(this.request); + _getChunkGraphChunk(chunk) { + let cgc = this._chunks.get(chunk); + if (cgc === undefined) { + cgc = new ChunkGraphChunk(); + this._chunks.set(chunk, cgc); + } + return cgc; } /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} + * @param {SortableSet} set the sortable Set to get the roots of + * @returns {Module[]} the graph roots */ - needBuild(context, callback) { - return callback(null, !this.buildMeta); + _getGraphRoots(set) { + const { moduleGraph } = this; + return Array.from( + findGraphRoots(set, module => { + /** @type {Set} */ + const set = new Set(); + const addDependencies = module => { + for (const connection of moduleGraph.getOutgoingConnections(module)) { + if (!connection.module) continue; + const activeState = connection.getActiveState(undefined); + if (activeState === false) continue; + if (activeState === ModuleGraphConnection.TRANSITIVE_ONLY) { + addDependencies(connection.module); + continue; + } + set.add(connection.module); + } + }; + addDependencies(module); + return set; + }) + ).sort(compareModulesByIdentifier); } /** - * @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 + * @param {Chunk} chunk the new chunk + * @param {Module} module the module * @returns {void} */ - build(options, compilation, resolver, fs, callback) { - this.buildMeta = { - async: false, - exportsType: undefined - }; - this.buildInfo = { - strict: true, - topLevelDeclarations: new Set(), - module: compilation.outputOptions.module - }; - const { request, externalType } = this._getRequestAndExternalType(); - this.buildMeta.exportsType = "dynamic"; - let canMangle = false; - this.clearDependenciesAndBlocks(); - switch (externalType) { - case "this": - this.buildInfo.strict = false; - break; - case "system": - if (!Array.isArray(request) || request.length === 1) { - this.buildMeta.exportsType = "namespace"; - canMangle = true; - } - break; - case "module": - if (this.buildInfo.module) { - if (!Array.isArray(request) || request.length === 1) { - this.buildMeta.exportsType = "namespace"; - canMangle = true; - } - } else { - this.buildMeta.async = true; - if (!Array.isArray(request) || request.length === 1) { - this.buildMeta.exportsType = "namespace"; - canMangle = false; - } - } - break; - case "script": - case "promise": - this.buildMeta.async = true; - break; - case "import": - this.buildMeta.async = true; - if (!Array.isArray(request) || request.length === 1) { - this.buildMeta.exportsType = "namespace"; - canMangle = false; - } - break; - } - this.addDependency(new StaticExportsDependency(true, canMangle)); - callback(); + connectChunkAndModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + cgm.chunks.add(chunk); + cgc.modules.add(module); } - restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { - this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); + /** + * @param {Chunk} chunk the chunk + * @param {Module} module the module + * @returns {void} + */ + disconnectChunkAndModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + cgc.modules.delete(module); + cgm.chunks.delete(chunk); } /** - * @param {ConcatenationBailoutReasonContext} context context - * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + * @param {Chunk} chunk the chunk which will be disconnected + * @returns {void} */ - 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`; + disconnectChunk(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + for (const module of cgc.modules) { + const cgm = this._getChunkGraphModule(module); + cgm.chunks.delete(chunk); } - return undefined; + cgc.modules.clear(); + chunk.disconnectFromGroups(); + ChunkGraph.clearChunkGraphForChunk(chunk); } - _getRequestAndExternalType() { - let { request, externalType } = this; - if (typeof request === "object" && !Array.isArray(request)) - request = request[externalType]; - return { request, externalType }; + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} modules the modules + * @returns {void} + */ + attachModules(chunk, modules) { + const cgc = this._getChunkGraphChunk(chunk); + for (const module of modules) { + cgc.modules.add(module); + } } - _getSourceData( - request, - externalType, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime - ) { - switch (externalType) { - case "this": - case "window": - case "self": - return getSourceForGlobalVariableExternal(request, this.externalType); - case "global": - return getSourceForGlobalVariableExternal( - request, - runtimeTemplate.globalObject - ); - case "commonjs": - case "commonjs2": - case "commonjs-module": - case "commonjs-static": - return getSourceForCommonJsExternal(request); - case "node-commonjs": - return this.buildInfo.module - ? getSourceForCommonJsExternalInNodeModule(request) - : getSourceForCommonJsExternal(request); - case "amd": - case "amd-require": - case "umd": - case "umd2": - case "system": - case "jsonp": { - const id = chunkGraph.getModuleId(this); - return getSourceForAmdOrUmdExternal( - id !== null ? id : this.identifier(), - this.isOptional(moduleGraph), - request, - runtimeTemplate - ); - } - case "import": - return getSourceForImportExternal(request, runtimeTemplate); - case "script": - return getSourceForScriptExternal(request, runtimeTemplate); - case "module": { - if (!this.buildInfo.module) { - if (!runtimeTemplate.supportsDynamicImport()) { - throw new Error( - "The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script" + - (runtimeTemplate.supportsEcmaScriptModuleSyntax() - ? "\nDid you mean to build a EcmaScript Module ('output.module: true')?" - : "") - ); - } - return getSourceForImportExternal(request, runtimeTemplate); - } - if (!runtimeTemplate.supportsEcmaScriptModuleSyntax()) { - throw new Error( - "The target environment doesn't support EcmaScriptModule syntax so it's not possible to use external type 'module'" - ); - } - return getSourceForModuleExternal( - request, - moduleGraph.getExportsInfo(this), - runtime, - runtimeTemplate.outputOptions.hashFunction - ); - } - case "var": - case "promise": - case "const": - case "let": - case "assign": - default: - return getSourceForDefaultCase( - this.isOptional(moduleGraph), - request, - runtimeTemplate - ); + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} modules the runtime modules + * @returns {void} + */ + attachRuntimeModules(chunk, modules) { + const cgc = this._getChunkGraphChunk(chunk); + for (const module of modules) { + cgc.runtimeModules.add(module); } } /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result + * @param {Chunk} chunk the chunk + * @param {Iterable} modules the modules that require a full hash + * @returns {void} */ - codeGeneration({ - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime, - concatenationScope - }) { - const { request, externalType } = this._getRequestAndExternalType(); - switch (externalType) { - case "asset": { - const sources = new Map(); - sources.set( - "javascript", - new RawSource(`module.exports = ${JSON.stringify(request)};`) - ); - const data = new Map(); - data.set("url", request); - return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS, data }; - } - case "css-import": { - const sources = new Map(); - sources.set( - "css-import", - new RawSource(`@import url(${JSON.stringify(request)});`) - ); - return { - sources, - runtimeRequirements: EMPTY_RUNTIME_REQUIREMENTS - }; - } - default: { - const sourceData = this._getSourceData( - request, - externalType, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime - ); + attachFullHashModules(chunk, modules) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.fullHashModules === undefined) cgc.fullHashModules = new Set(); + for (const module of modules) { + cgc.fullHashModules.add(module); + } + } - 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}`; + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} modules the modules that require a full hash + * @returns {void} + */ + attachDependentHashModules(chunk, modules) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.dependentHashModules === undefined) + cgc.dependentHashModules = new Set(); + for (const module of modules) { + cgc.dependentHashModules.add(module); + } + } - let data = undefined; - if (sourceData.chunkInitFragments) { - data = new Map(); - data.set("chunkInitFragments", sourceData.chunkInitFragments); - } + /** + * @param {Module} oldModule the replaced module + * @param {Module} newModule the replacing module + * @returns {void} + */ + replaceModule(oldModule, newModule) { + const oldCgm = this._getChunkGraphModule(oldModule); + const newCgm = this._getChunkGraphModule(newModule); - const sources = new Map(); - if (this.useSourceMap || this.useSimpleSourceMap) { - sources.set( - "javascript", - new OriginalSource(sourceString, this.identifier()) - ); - } else { - sources.set("javascript", new RawSource(sourceString)); - } + for (const chunk of oldCgm.chunks) { + const cgc = this._getChunkGraphChunk(chunk); + cgc.modules.delete(oldModule); + cgc.modules.add(newModule); + newCgm.chunks.add(chunk); + } + oldCgm.chunks.clear(); - let runtimeRequirements = sourceData.runtimeRequirements; - if (!concatenationScope) { - if (!runtimeRequirements) { - runtimeRequirements = RUNTIME_REQUIREMENTS; + if (oldCgm.entryInChunks !== undefined) { + if (newCgm.entryInChunks === undefined) { + newCgm.entryInChunks = new Set(); + } + for (const chunk of oldCgm.entryInChunks) { + const cgc = this._getChunkGraphChunk(chunk); + const old = cgc.entryModules.get(oldModule); + /** @type {Map} */ + const newEntryModules = new Map(); + for (const [m, cg] of cgc.entryModules) { + if (m === oldModule) { + newEntryModules.set(newModule, old); } else { - const set = new Set(runtimeRequirements); - set.add(RuntimeGlobals.module); - runtimeRequirements = set; + newEntryModules.set(m, cg); } } + cgc.entryModules = newEntryModules; + newCgm.entryInChunks.add(chunk); + } + oldCgm.entryInChunks = undefined; + } - return { - sources, - runtimeRequirements: - runtimeRequirements || EMPTY_RUNTIME_REQUIREMENTS, - data - }; + if (oldCgm.runtimeInChunks !== undefined) { + if (newCgm.runtimeInChunks === undefined) { + newCgm.runtimeInChunks = new Set(); + } + for (const chunk of oldCgm.runtimeInChunks) { + const cgc = this._getChunkGraphChunk(chunk); + cgc.runtimeModules.delete(/** @type {RuntimeModule} */ (oldModule)); + cgc.runtimeModules.add(/** @type {RuntimeModule} */ (newModule)); + newCgm.runtimeInChunks.add(chunk); + if ( + cgc.fullHashModules !== undefined && + cgc.fullHashModules.has(/** @type {RuntimeModule} */ (oldModule)) + ) { + cgc.fullHashModules.delete(/** @type {RuntimeModule} */ (oldModule)); + cgc.fullHashModules.add(/** @type {RuntimeModule} */ (newModule)); + } + if ( + cgc.dependentHashModules !== undefined && + cgc.dependentHashModules.has(/** @type {RuntimeModule} */ (oldModule)) + ) { + cgc.dependentHashModules.delete( + /** @type {RuntimeModule} */ (oldModule) + ); + cgc.dependentHashModules.add( + /** @type {RuntimeModule} */ (newModule) + ); + } } + oldCgm.runtimeInChunks = undefined; } } /** - * @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) + * @param {Module} module the checked module + * @param {Chunk} chunk the checked chunk + * @returns {boolean} true, if the chunk contains the module */ - size(type) { - return 42; + isModuleInChunk(module, chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.has(module); } /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} + * @param {Module} module the checked module + * @param {ChunkGroup} chunkGroup the checked chunk group + * @returns {boolean} true, if the chunk contains the module */ - updateHash(hash, context) { - const { chunkGraph } = context; - hash.update( - `${this.externalType}${JSON.stringify(this.request)}${this.isOptional( - chunkGraph.moduleGraph - )}` - ); - super.updateHash(hash, context); + isModuleInChunkGroup(module, chunkGroup) { + for (const chunk of chunkGroup.chunks) { + if (this.isModuleInChunk(module, chunk)) return true; + } + return false; } - serialize(context) { - const { write } = context; + /** + * @param {Module} module the checked module + * @returns {boolean} true, if the module is entry of any chunk + */ + isEntryModule(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.entryInChunks !== undefined; + } - write(this.request); - write(this.externalType); - write(this.userRequest); + /** + * @param {Module} module the module + * @returns {Iterable} iterable of chunks (do not modify) + */ + getModuleChunksIterable(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.chunks; + } - super.serialize(context); + /** + * @param {Module} module the module + * @param {function(Chunk, Chunk): -1|0|1} sortFn sort function + * @returns {Iterable} iterable of chunks (do not modify) + */ + getOrderedModuleChunksIterable(module, sortFn) { + const cgm = this._getChunkGraphModule(module); + cgm.chunks.sortWith(sortFn); + return cgm.chunks; } - deserialize(context) { - const { read } = context; + /** + * @param {Module} module the module + * @returns {Chunk[]} array of chunks (cached, do not modify) + */ + getModuleChunks(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.chunks.getFromCache(getArray); + } - this.request = read(); - this.externalType = read(); - this.userRequest = read(); + /** + * @param {Module} module the module + * @returns {number} the number of chunk which contain the module + */ + getNumberOfModuleChunks(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.chunks.size; + } - super.deserialize(context); + /** + * @param {Module} module the module + * @returns {RuntimeSpecSet} runtimes + */ + getModuleRuntimes(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.chunks.getFromUnorderedCache(getModuleRuntimes); } -} -makeSerializable(ExternalModule, "webpack/lib/ExternalModule"); + /** + * @param {Chunk} chunk the chunk + * @returns {number} the number of modules which are contained in this chunk + */ + getNumberOfChunkModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.size; + } -module.exports = ExternalModule; + /** + * @param {Chunk} chunk the chunk + * @returns {number} the number of full hash modules which are contained in this chunk + */ + getNumberOfChunkFullHashModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.fullHashModules === undefined ? 0 : cgc.fullHashModules.size; + } + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} return the modules for this chunk + */ + getChunkModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules; + } -/***/ }), + /** + * @param {Chunk} chunk the chunk + * @param {string} sourceType source type + * @returns {Iterable | undefined} return the modules for this chunk + */ + getChunkModulesIterableBySourceType(chunk, sourceType) { + const cgc = this._getChunkGraphChunk(chunk); + const modulesWithSourceType = cgc.modules + .getFromUnorderedCache(modulesBySourceType) + .get(sourceType); + return modulesWithSourceType; + } -/***/ 62153: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {Chunk} chunk the chunk + * @param {function(Module, Module): -1|0|1} comparator comparator function + * @returns {Iterable} return the modules for this chunk + */ + getOrderedChunkModulesIterable(chunk, comparator) { + const cgc = this._getChunkGraphChunk(chunk); + cgc.modules.sortWith(comparator); + return cgc.modules; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {Chunk} chunk the chunk + * @param {string} sourceType source type + * @param {function(Module, Module): -1|0|1} comparator comparator function + * @returns {Iterable | undefined} return the modules for this chunk + */ + getOrderedChunkModulesIterableBySourceType(chunk, sourceType, comparator) { + const cgc = this._getChunkGraphChunk(chunk); + const modulesWithSourceType = cgc.modules + .getFromUnorderedCache(modulesBySourceType) + .get(sourceType); + if (modulesWithSourceType === undefined) return undefined; + modulesWithSourceType.sortWith(comparator); + return modulesWithSourceType; + } + /** + * @param {Chunk} chunk the chunk + * @returns {Module[]} return the modules for this chunk (cached, do not modify) + */ + getChunkModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.getFromUnorderedCache(getArray); + } + /** + * @param {Chunk} chunk the chunk + * @param {function(Module, Module): -1|0|1} comparator comparator function + * @returns {Module[]} return the modules for this chunk (cached, do not modify) + */ + getOrderedChunkModules(chunk, comparator) { + const cgc = this._getChunkGraphChunk(chunk); + const arrayFunction = createOrderedArrayFunction(comparator); + return cgc.modules.getFromUnorderedCache(arrayFunction); + } -const util = __webpack_require__(73837); -const ExternalModule = __webpack_require__(73071); -const { resolveByProperty, cachedSetProperty } = __webpack_require__(60839); + /** + * @param {Chunk} chunk the chunk + * @param {ModuleFilterPredicate} filterFn function used to filter modules + * @param {boolean} includeAllChunks all chunks or only async chunks + * @returns {Record} chunk to module ids object + */ + getChunkModuleIdMap(chunk, filterFn, includeAllChunks = false) { + /** @type {Record} */ + const chunkModuleIdMap = Object.create(null); -/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ -/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ + for (const asyncChunk of includeAllChunks + ? chunk.getAllReferencedChunks() + : chunk.getAllAsyncChunks()) { + /** @type {(string|number)[]} */ + let array; + for (const module of this.getOrderedChunkModulesIterable( + asyncChunk, + compareModulesById(this) + )) { + if (filterFn(module)) { + if (array === undefined) { + array = []; + chunkModuleIdMap[asyncChunk.id] = array; + } + const moduleId = this.getModuleId(module); + array.push(moduleId); + } + } + } -const UNSPECIFIED_EXTERNAL_TYPE_REGEXP = /^[a-z0-9-]+ /; -const EMPTY_RESOLVE_OPTIONS = {}; + return chunkModuleIdMap; + } -// 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" -); + /** + * @param {Chunk} chunk the chunk + * @param {ModuleFilterPredicate} filterFn function used to filter modules + * @param {number} hashLength length of the hash + * @param {boolean} includeAllChunks all chunks or only async chunks + * @returns {Record>} chunk to module id to module hash object + */ + getChunkModuleRenderedHashMap( + chunk, + filterFn, + hashLength = 0, + includeAllChunks = false + ) { + /** @type {Record>} */ + const chunkModuleHashMap = Object.create(null); -const cache = new WeakMap(); + for (const asyncChunk of includeAllChunks + ? chunk.getAllReferencedChunks() + : chunk.getAllAsyncChunks()) { + /** @type {Record} */ + let idToHashMap; + for (const module of this.getOrderedChunkModulesIterable( + asyncChunk, + compareModulesById(this) + )) { + if (filterFn(module)) { + if (idToHashMap === undefined) { + idToHashMap = Object.create(null); + chunkModuleHashMap[asyncChunk.id] = idToHashMap; + } + const moduleId = this.getModuleId(module); + const hash = this.getRenderedModuleHash(module, asyncChunk.runtime); + idToHashMap[moduleId] = hashLength ? hash.slice(0, hashLength) : hash; + } + } + } -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; + return chunkModuleHashMap; } - 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 + * @param {Chunk} chunk the chunk + * @param {ChunkFilterPredicate} filterFn function used to filter chunks + * @returns {Record} chunk map */ - constructor(type, externals) { - this.type = type; - this.externals = externals; + getChunkConditionMap(chunk, filterFn) { + const map = Object.create(null); + for (const c of chunk.getAllReferencedChunks()) { + map[c.id] = filterFn(c, this); + } + return map; } /** - * @param {NormalModuleFactory} normalModuleFactory the normal module factory - * @returns {void} + * @param {Chunk} chunk the chunk + * @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 */ - apply(normalModuleFactory) { - const globalType = this.type; - normalModuleFactory.hooks.factorize.tapAsync( - "ExternalModuleFactoryPlugin", - (data, callback) => { - const context = data.context; - const contextInfo = data.contextInfo; - const dependency = data.dependencies[0]; - const dependencyType = data.dependencyType; - - /** - * @param {string|string[]|boolean|Record} 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} */ - 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 | null)=, ExternalModule=): void} callback callback - * @returns {void} - */ - const handleExternals = (externals, callback) => { - if (typeof externals === "string") { - if (externals === dependency.request) { - return handleExternal(dependency.request, undefined, callback); - } - } else if (Array.isArray(externals)) { - let i = 0; - const next = () => { - 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; - }; + hasModuleInGraph(chunk, filterFn, filterChunkFn) { + const queue = new Set(chunk.groupsIterable); + const chunksProcessed = new Set(); - 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(); + for (const chunkGroup of queue) { + for (const innerChunk of chunkGroup.chunks) { + if (!chunksProcessed.has(innerChunk)) { + chunksProcessed.add(innerChunk); + if (!filterChunkFn || filterChunkFn(innerChunk, this)) { + for (const module of this.getChunkModulesIterable(innerChunk)) { + if (filterFn(module)) { + return true; } - }; - if (externals.length === 3) { - // TODO webpack 6 remove this - callDeprecatedExternals( - externals, - context, - dependency.request, - cb - ); - } else { - const promise = externals( - { - context, - request: dependency.request, - dependencyType, - contextInfo, - getResolve: options => (context, request, callback) => { - const resolveContext = { - fileDependencies: data.fileDependencies, - missingDependencies: data.missingDependencies, - contextDependencies: data.contextDependencies - }; - let resolver = normalModuleFactory.getResolver( - "normal", - dependencyType - ? cachedSetProperty( - data.resolveOptions || EMPTY_RESOLVE_OPTIONS, - "dependencyType", - dependencyType - ) - : data.resolveOptions - ); - if (options) resolver = resolver.withOptions(options); - if (callback) { - resolver.resolve( - {}, - context, - request, - resolveContext, - callback - ); - } else { - return new Promise((resolve, reject) => { - resolver.resolve( - {}, - context, - request, - resolveContext, - (err, result) => { - if (err) reject(err); - else resolve(result); - } - ); - }); - } - } - }, - cb - ); - if (promise && promise.then) promise.then(r => cb(null, r), cb); - } - return; - } else if (typeof externals === "object") { - const resolvedExternals = resolveLayer( - externals, - contextInfo.issuerLayer - ); - if ( - Object.prototype.hasOwnProperty.call( - resolvedExternals, - dependency.request - ) - ) { - return handleExternal( - resolvedExternals[dependency.request], - undefined, - callback - ); } } - callback(); - }; - - handleExternals(this.externals, callback); + } } - ); + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + return false; } -} -module.exports = ExternalModuleFactoryPlugin; - - -/***/ }), - -/***/ 6652: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + /** + * @param {Chunk} chunkA first chunk + * @param {Chunk} chunkB second chunk + * @returns {-1|0|1} this is a comparator function like sort and returns -1, 0, or 1 based on sort order + */ + compareChunks(chunkA, chunkB) { + const cgcA = this._getChunkGraphChunk(chunkA); + const cgcB = this._getChunkGraphChunk(chunkB); + if (cgcA.modules.size > cgcB.modules.size) return -1; + if (cgcA.modules.size < cgcB.modules.size) return 1; + cgcA.modules.sortWith(compareModulesByIdentifier); + cgcB.modules.sortWith(compareModulesByIdentifier); + return compareModuleIterables(cgcA.modules, cgcB.modules); + } -const ExternalModuleFactoryPlugin = __webpack_require__(62153); - -/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ -/** @typedef {import("./Compiler")} Compiler */ + /** + * @param {Chunk} chunk the chunk + * @returns {number} total size of all modules in the chunk + */ + getChunkModulesSize(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.getFromUnorderedCache(getModulesSize); + } -class ExternalsPlugin { /** - * @param {string | undefined} type default external type - * @param {Externals} externals externals config + * @param {Chunk} chunk the chunk + * @returns {Record} total sizes of all modules in the chunk by source type */ - constructor(type, externals) { - this.type = type; - this.externals = externals; + getChunkModulesSizes(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.getFromUnorderedCache(getModulesSizes); } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {Chunk} chunk the chunk + * @returns {Module[]} root modules of the chunks (ordered by identifier) */ - apply(compiler) { - compiler.hooks.compile.tap("ExternalsPlugin", ({ normalModuleFactory }) => { - new ExternalModuleFactoryPlugin(this.type, this.externals).apply( - normalModuleFactory - ); - }); + getChunkRootModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.getFromUnorderedCache(this._getGraphRoots); } -} -module.exports = ExternalsPlugin; + /** + * @param {Chunk} chunk the chunk + * @param {ChunkSizeOptions} options options object + * @returns {number} total size of the chunk + */ + getChunkSize(chunk, options = {}) { + const cgc = this._getChunkGraphChunk(chunk); + const modulesSize = cgc.modules.getFromUnorderedCache(getModulesSize); + const chunkOverhead = + typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; + const entryChunkMultiplicator = + typeof options.entryChunkMultiplicator === "number" + ? options.entryChunkMultiplicator + : 10; + return ( + chunkOverhead + + modulesSize * (chunk.canBeInitial() ? entryChunkMultiplicator : 1) + ); + } + /** + * @param {Chunk} chunkA chunk + * @param {Chunk} chunkB chunk + * @param {ChunkSizeOptions} options options object + * @returns {number} total size of the chunk or false if chunks can't be integrated + */ + getIntegratedChunksSize(chunkA, chunkB, options = {}) { + const cgcA = this._getChunkGraphChunk(chunkA); + const cgcB = this._getChunkGraphChunk(chunkB); + const allModules = new Set(cgcA.modules); + for (const m of cgcB.modules) allModules.add(m); + let modulesSize = getModulesSize(allModules); + const chunkOverhead = + typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; + const entryChunkMultiplicator = + typeof options.entryChunkMultiplicator === "number" + ? options.entryChunkMultiplicator + : 10; + return ( + chunkOverhead + + modulesSize * + (chunkA.canBeInitial() || chunkB.canBeInitial() + ? entryChunkMultiplicator + : 1) + ); + } -/***/ }), + /** + * @param {Chunk} chunkA chunk + * @param {Chunk} chunkB chunk + * @returns {boolean} true, if chunks could be integrated + */ + canChunksBeIntegrated(chunkA, chunkB) { + if (chunkA.preventIntegration || chunkB.preventIntegration) { + return false; + } -/***/ 79453: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const hasRuntimeA = chunkA.hasRuntime(); + const hasRuntimeB = chunkB.hasRuntime(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { create: createResolver } = __webpack_require__(9256); -const asyncLib = __webpack_require__(78175); -const AsyncQueue = __webpack_require__(12260); -const StackedCacheMap = __webpack_require__(64985); -const createHash = __webpack_require__(49835); -const { join, dirname, relative, lstatReadlinkAbsolute } = __webpack_require__(17139); -const makeSerializable = __webpack_require__(33032); -const processAsyncTree = __webpack_require__(42791); - -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./logging/Logger").Logger} Logger */ -/** @typedef {typeof import("./util/Hash")} Hash */ -/** @typedef {import("./util/fs").IStats} IStats */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ - -const supportsEsm = +process.versions.modules >= 83; - -let FS_ACCURACY = 2000; - -const EMPTY_SET = new Set(); - -const RBDT_RESOLVE_CJS = 0; -const RBDT_RESOLVE_ESM = 1; -const RBDT_RESOLVE_DIRECTORY = 2; -const RBDT_RESOLVE_CJS_FILE = 3; -const RBDT_RESOLVE_CJS_FILE_AS_CHILD = 4; -const RBDT_RESOLVE_ESM_FILE = 5; -const RBDT_DIRECTORY = 6; -const RBDT_FILE = 7; -const RBDT_DIRECTORY_DEPENDENCIES = 8; -const RBDT_FILE_DEPENDENCIES = 9; - -const INVALID = Symbol("invalid"); + if (hasRuntimeA !== hasRuntimeB) { + if (hasRuntimeA) { + return isAvailableChunk(chunkA, chunkB); + } else if (hasRuntimeB) { + return isAvailableChunk(chunkB, chunkA); + } else { + return false; + } + } -/** - * @typedef {Object} FileSystemInfoEntry - * @property {number} safeTime - * @property {number=} timestamp - */ + if ( + this.getNumberOfEntryModules(chunkA) > 0 || + this.getNumberOfEntryModules(chunkB) > 0 + ) { + return false; + } -/** - * @typedef {Object} ResolvedContextFileSystemInfoEntry - * @property {number} safeTime - * @property {string=} timestampHash - */ + return true; + } -/** - * @typedef {Object} ContextFileSystemInfoEntry - * @property {number} safeTime - * @property {string=} timestampHash - * @property {ResolvedContextFileSystemInfoEntry=} resolved - * @property {Set=} symlinks - */ + /** + * @param {Chunk} chunkA the target chunk + * @param {Chunk} chunkB the chunk to integrate + * @returns {void} + */ + integrateChunks(chunkA, chunkB) { + // Decide for one name (deterministic) + if (chunkA.name && chunkB.name) { + if ( + this.getNumberOfEntryModules(chunkA) > 0 === + this.getNumberOfEntryModules(chunkB) > 0 + ) { + // When both chunks have entry modules or none have one, use + // shortest name + if (chunkA.name.length !== chunkB.name.length) { + chunkA.name = + chunkA.name.length < chunkB.name.length ? chunkA.name : chunkB.name; + } else { + chunkA.name = chunkA.name < chunkB.name ? chunkA.name : chunkB.name; + } + } else if (this.getNumberOfEntryModules(chunkB) > 0) { + // Pick the name of the chunk with the entry module + chunkA.name = chunkB.name; + } + } else if (chunkB.name) { + chunkA.name = chunkB.name; + } -/** - * @typedef {Object} TimestampAndHash - * @property {number} safeTime - * @property {number=} timestamp - * @property {string} hash - */ + // Merge id name hints + for (const hint of chunkB.idNameHints) { + chunkA.idNameHints.add(hint); + } -/** - * @typedef {Object} ResolvedContextTimestampAndHash - * @property {number} safeTime - * @property {string=} timestampHash - * @property {string} hash - */ + // Merge runtime + chunkA.runtime = mergeRuntime(chunkA.runtime, chunkB.runtime); -/** - * @typedef {Object} ContextTimestampAndHash - * @property {number} safeTime - * @property {string=} timestampHash - * @property {string} hash - * @property {ResolvedContextTimestampAndHash=} resolved - * @property {Set=} symlinks - */ + // getChunkModules is used here to create a clone, because disconnectChunkAndModule modifies + for (const module of this.getChunkModules(chunkB)) { + this.disconnectChunkAndModule(chunkB, module); + this.connectChunkAndModule(chunkA, module); + } -/** - * @typedef {Object} ContextHash - * @property {string} hash - * @property {string=} resolved - * @property {Set=} symlinks - */ + for (const [module, chunkGroup] of Array.from( + this.getChunkEntryModulesWithChunkGroupIterable(chunkB) + )) { + this.disconnectChunkAndEntryModule(chunkB, module); + this.connectChunkAndEntryModule(chunkA, module, chunkGroup); + } -/** - * @typedef {Object} SnapshotOptimizationEntry - * @property {Snapshot} snapshot - * @property {number} shared - * @property {Set} snapshotContent - * @property {Set} children - */ + for (const chunkGroup of chunkB.groupsIterable) { + chunkGroup.replaceChunk(chunkB, chunkA); + chunkA.addGroup(chunkGroup); + chunkB.removeGroup(chunkGroup); + } + ChunkGraph.clearChunkGraphForChunk(chunkB); + } -/** - * @typedef {Object} ResolveBuildDependenciesResult - * @property {Set} files list of files - * @property {Set} directories list of directories - * @property {Set} missing list of missing entries - * @property {Map} resolveResults stored resolve results - * @property {Object} resolveDependencies dependencies of the resolving - * @property {Set} resolveDependencies.files list of files - * @property {Set} resolveDependencies.directories list of directories - * @property {Set} resolveDependencies.missing list of missing entries - */ + /** + * @param {Chunk} chunk the chunk to upgrade + * @returns {void} + */ + upgradeDependentToFullHashModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.dependentHashModules === undefined) return; + if (cgc.fullHashModules === undefined) { + cgc.fullHashModules = cgc.dependentHashModules; + } else { + for (const m of cgc.dependentHashModules) { + cgc.fullHashModules.add(m); + } + cgc.dependentHashModules = undefined; + } + } -const DONE_ITERATOR_RESULT = new Set().keys().next(); + /** + * @param {Module} module the checked module + * @param {Chunk} chunk the checked chunk + * @returns {boolean} true, if the chunk contains the module as entry + */ + isEntryModuleInChunk(module, chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.entryModules.has(module); + } -// cspell:word tshs -// Tsh = Timestamp + Hash -// Tshs = Timestamp + Hash combinations + /** + * @param {Chunk} chunk the new chunk + * @param {Module} module the entry module + * @param {Entrypoint=} entrypoint the chunk group which must be loaded before the module is executed + * @returns {void} + */ + connectChunkAndEntryModule(chunk, module, entrypoint) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + if (cgm.entryInChunks === undefined) { + cgm.entryInChunks = new Set(); + } + cgm.entryInChunks.add(chunk); + cgc.entryModules.set(module, entrypoint); + } -class SnapshotIterator { - constructor(next) { - this.next = next; + /** + * @param {Chunk} chunk the new chunk + * @param {RuntimeModule} module the runtime module + * @returns {void} + */ + connectChunkAndRuntimeModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + if (cgm.runtimeInChunks === undefined) { + cgm.runtimeInChunks = new Set(); + } + cgm.runtimeInChunks.add(chunk); + cgc.runtimeModules.add(module); } -} -class SnapshotIterable { - constructor(snapshot, getMaps) { - this.snapshot = snapshot; - this.getMaps = getMaps; + /** + * @param {Chunk} chunk the new chunk + * @param {RuntimeModule} module the module that require a full hash + * @returns {void} + */ + addFullHashModuleToChunk(chunk, module) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.fullHashModules === undefined) cgc.fullHashModules = new Set(); + cgc.fullHashModules.add(module); } - [Symbol.iterator]() { - let state = 0; - /** @type {IterableIterator} */ - let it; - /** @type {(Snapshot) => (Map | Set)[]} */ - let getMaps; - /** @type {(Map | Set)[]} */ - let maps; - /** @type {Snapshot} */ - let snapshot; - let queue; - return new SnapshotIterator(() => { - for (;;) { - switch (state) { - case 0: - snapshot = this.snapshot; - getMaps = this.getMaps; - maps = getMaps(snapshot); - state = 1; - /* falls through */ - case 1: - if (maps.length > 0) { - const map = maps.pop(); - if (map !== undefined) { - it = map.keys(); - state = 2; - } else { - break; - } - } else { - state = 3; - break; - } - /* falls through */ - case 2: { - const result = it.next(); - if (!result.done) return result; - state = 1; - break; - } - case 3: { - const children = snapshot.children; - if (children !== undefined) { - if (children.size === 1) { - // shortcut for a single child - // avoids allocation of queue - for (const child of children) snapshot = child; - maps = getMaps(snapshot); - state = 1; - break; - } - if (queue === undefined) queue = []; - for (const child of children) { - queue.push(child); - } - } - if (queue !== undefined && queue.length > 0) { - snapshot = queue.pop(); - maps = getMaps(snapshot); - state = 1; - break; - } else { - state = 4; - } - } - /* falls through */ - case 4: - return DONE_ITERATOR_RESULT; - } - } - }); + /** + * @param {Chunk} chunk the new chunk + * @param {RuntimeModule} module the module that require a full hash + * @returns {void} + */ + addDependentHashModuleToChunk(chunk, module) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.dependentHashModules === undefined) + cgc.dependentHashModules = new Set(); + cgc.dependentHashModules.add(module); } -} -class Snapshot { - constructor() { - this._flags = 0; - /** @type {number | undefined} */ - this.startTime = undefined; - /** @type {Map | undefined} */ - this.fileTimestamps = undefined; - /** @type {Map | undefined} */ - this.fileHashes = undefined; - /** @type {Map | undefined} */ - this.fileTshs = undefined; - /** @type {Map | undefined} */ - this.contextTimestamps = undefined; - /** @type {Map | undefined} */ - this.contextHashes = undefined; - /** @type {Map | undefined} */ - this.contextTshs = undefined; - /** @type {Map | undefined} */ - this.missingExistence = undefined; - /** @type {Map | undefined} */ - this.managedItemInfo = undefined; - /** @type {Set | undefined} */ - this.managedFiles = undefined; - /** @type {Set | undefined} */ - this.managedContexts = undefined; - /** @type {Set | undefined} */ - this.managedMissing = undefined; - /** @type {Set | undefined} */ - this.children = undefined; + /** + * @param {Chunk} chunk the new chunk + * @param {Module} module the entry module + * @returns {void} + */ + disconnectChunkAndEntryModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + cgm.entryInChunks.delete(chunk); + if (cgm.entryInChunks.size === 0) { + cgm.entryInChunks = undefined; + } + cgc.entryModules.delete(module); } - hasStartTime() { - return (this._flags & 1) !== 0; + /** + * @param {Chunk} chunk the new chunk + * @param {RuntimeModule} module the runtime module + * @returns {void} + */ + disconnectChunkAndRuntimeModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + cgm.runtimeInChunks.delete(chunk); + if (cgm.runtimeInChunks.size === 0) { + cgm.runtimeInChunks = undefined; + } + cgc.runtimeModules.delete(module); } - setStartTime(value) { - this._flags = this._flags | 1; - this.startTime = value; + /** + * @param {Module} module the entry module, it will no longer be entry + * @returns {void} + */ + disconnectEntryModule(module) { + const cgm = this._getChunkGraphModule(module); + for (const chunk of cgm.entryInChunks) { + const cgc = this._getChunkGraphChunk(chunk); + cgc.entryModules.delete(module); + } + cgm.entryInChunks = undefined; } - setMergedStartTime(value, snapshot) { - if (value) { - if (snapshot.hasStartTime()) { - this.setStartTime(Math.min(value, snapshot.startTime)); - } else { - this.setStartTime(value); + /** + * @param {Chunk} chunk the chunk, for which all entries will be removed + * @returns {void} + */ + disconnectEntries(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + for (const module of cgc.entryModules.keys()) { + const cgm = this._getChunkGraphModule(module); + cgm.entryInChunks.delete(chunk); + if (cgm.entryInChunks.size === 0) { + cgm.entryInChunks = undefined; } - } else { - if (snapshot.hasStartTime()) this.setStartTime(snapshot.startTime); } + cgc.entryModules.clear(); } - hasFileTimestamps() { - return (this._flags & 2) !== 0; + /** + * @param {Chunk} chunk the chunk + * @returns {number} the amount of entry modules in chunk + */ + getNumberOfEntryModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.entryModules.size; } - setFileTimestamps(value) { - this._flags = this._flags | 2; - this.fileTimestamps = value; + /** + * @param {Chunk} chunk the chunk + * @returns {number} the amount of entry modules in chunk + */ + getNumberOfRuntimeModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.runtimeModules.size; } - hasFileHashes() { - return (this._flags & 4) !== 0; + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of modules (do not modify) + */ + getChunkEntryModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.entryModules.keys(); } - setFileHashes(value) { - this._flags = this._flags | 4; - this.fileHashes = value; - } + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of chunks + */ + getChunkEntryDependentChunksIterable(chunk) { + /** @type {Set} */ + const set = new Set(); + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup instanceof Entrypoint) { + const entrypointChunk = chunkGroup.getEntrypointChunk(); + const cgc = this._getChunkGraphChunk(entrypointChunk); + for (const chunkGroup of cgc.entryModules.values()) { + for (const c of chunkGroup.chunks) { + if (c !== chunk && c !== entrypointChunk && !c.hasRuntime()) { + set.add(c); + } + } + } + } + } - hasFileTshs() { - return (this._flags & 8) !== 0; + return set; } - setFileTshs(value) { - this._flags = this._flags | 8; - this.fileTshs = value; + /** + * @param {Chunk} chunk the chunk + * @returns {boolean} true, when it has dependent chunks + */ + hasChunkEntryDependentChunks(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + for (const chunkGroup of cgc.entryModules.values()) { + for (const c of chunkGroup.chunks) { + if (c !== chunk) { + return true; + } + } + } + return false; } - hasContextTimestamps() { - return (this._flags & 0x10) !== 0; + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of modules (do not modify) + */ + getChunkRuntimeModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.runtimeModules; } - setContextTimestamps(value) { - this._flags = this._flags | 0x10; - this.contextTimestamps = value; + /** + * @param {Chunk} chunk the chunk + * @returns {RuntimeModule[]} array of modules in order of execution + */ + getChunkRuntimeModulesInOrder(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + const array = Array.from(cgc.runtimeModules); + array.sort( + concatComparators( + compareSelect( + /** + * @param {RuntimeModule} r runtime module + * @returns {number=} stage + */ + r => r.stage, + compareIds + ), + compareModulesByIdentifier + ) + ); + return array; } - hasContextHashes() { - return (this._flags & 0x20) !== 0; + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable | undefined} iterable of modules (do not modify) + */ + getChunkFullHashModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.fullHashModules; } - setContextHashes(value) { - this._flags = this._flags | 0x20; - this.contextHashes = value; + /** + * @param {Chunk} chunk the chunk + * @returns {ReadonlySet | undefined} set of modules (do not modify) + */ + getChunkFullHashModulesSet(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.fullHashModules; } - hasContextTshs() { - return (this._flags & 0x40) !== 0; + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable | undefined} iterable of modules (do not modify) + */ + getChunkDependentHashModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.dependentHashModules; } - setContextTshs(value) { - this._flags = this._flags | 0x40; - this.contextTshs = value; - } + /** @typedef {[Module, Entrypoint | undefined]} EntryModuleWithChunkGroup */ - hasMissingExistence() { - return (this._flags & 0x80) !== 0; + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of modules (do not modify) + */ + getChunkEntryModulesWithChunkGroupIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.entryModules; } - setMissingExistence(value) { - this._flags = this._flags | 0x80; - this.missingExistence = value; + /** + * @param {AsyncDependenciesBlock} depBlock the async block + * @returns {ChunkGroup} the chunk group + */ + getBlockChunkGroup(depBlock) { + return this._blockChunkGroups.get(depBlock); } - hasManagedItemInfo() { - return (this._flags & 0x100) !== 0; + /** + * @param {AsyncDependenciesBlock} depBlock the async block + * @param {ChunkGroup} chunkGroup the chunk group + * @returns {void} + */ + connectBlockAndChunkGroup(depBlock, chunkGroup) { + this._blockChunkGroups.set(depBlock, chunkGroup); + chunkGroup.addBlock(depBlock); } - setManagedItemInfo(value) { - this._flags = this._flags | 0x100; - this.managedItemInfo = value; + /** + * @param {ChunkGroup} chunkGroup the chunk group + * @returns {void} + */ + disconnectChunkGroup(chunkGroup) { + for (const block of chunkGroup.blocksIterable) { + this._blockChunkGroups.delete(block); + } + // TODO refactor by moving blocks list into ChunkGraph + chunkGroup._blocks.clear(); } - hasManagedFiles() { - return (this._flags & 0x200) !== 0; + /** + * @param {Module} module the module + * @returns {string | number} the id of the module + */ + getModuleId(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.id; } - setManagedFiles(value) { - this._flags = this._flags | 0x200; - this.managedFiles = value; + /** + * @param {Module} module the module + * @param {string | number} id the id of the module + * @returns {void} + */ + setModuleId(module, id) { + const cgm = this._getChunkGraphModule(module); + cgm.id = id; } - hasManagedContexts() { - return (this._flags & 0x400) !== 0; + /** + * @param {string} runtime runtime + * @returns {string | number} the id of the runtime + */ + getRuntimeId(runtime) { + return this._runtimeIds.get(runtime); } - setManagedContexts(value) { - this._flags = this._flags | 0x400; - this.managedContexts = value; + /** + * @param {string} runtime runtime + * @param {string | number} id the id of the runtime + * @returns {void} + */ + setRuntimeId(runtime, id) { + this._runtimeIds.set(runtime, id); } - hasManagedMissing() { - return (this._flags & 0x800) !== 0; + /** + * @template T + * @param {Module} module the module + * @param {RuntimeSpecMap} hashes hashes data + * @param {RuntimeSpec} runtime the runtime + * @returns {T} hash + */ + _getModuleHashInfo(module, hashes, runtime) { + if (!hashes) { + throw new Error( + `Module ${module.identifier()} has no hash info for runtime ${runtimeToString( + runtime + )} (hashes not set at all)` + ); + } else if (runtime === undefined) { + const hashInfoItems = new Set(hashes.values()); + if (hashInfoItems.size !== 1) { + throw new Error( + `No unique hash info entry for unspecified runtime for ${module.identifier()} (existing runtimes: ${Array.from( + hashes.keys(), + r => runtimeToString(r) + ).join(", ")}). +Caller might not support runtime-dependent code generation (opt-out via optimization.usedExports: "global").` + ); + } + return first(hashInfoItems); + } else { + const hashInfo = hashes.get(runtime); + if (!hashInfo) { + throw new Error( + `Module ${module.identifier()} has no hash info for runtime ${runtimeToString( + runtime + )} (available runtimes ${Array.from( + hashes.keys(), + runtimeToString + ).join(", ")})` + ); + } + return hashInfo; + } } - setManagedMissing(value) { - this._flags = this._flags | 0x800; - this.managedMissing = value; + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, if the module has hashes for this runtime + */ + hasModuleHashes(module, runtime) { + const cgm = this._getChunkGraphModule(module); + const hashes = cgm.hashes; + return hashes && hashes.has(runtime); } - hasChildren() { - return (this._flags & 0x1000) !== 0; + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {string} hash + */ + getModuleHash(module, runtime) { + const cgm = this._getChunkGraphModule(module); + const hashes = cgm.hashes; + return this._getModuleHashInfo(module, hashes, runtime).hash; } - setChildren(value) { - this._flags = this._flags | 0x1000; - this.children = value; + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {string} hash + */ + getRenderedModuleHash(module, runtime) { + const cgm = this._getChunkGraphModule(module); + const hashes = cgm.hashes; + return this._getModuleHashInfo(module, hashes, runtime).renderedHash; } - addChild(child) { - if (!this.hasChildren()) { - this.setChildren(new Set()); + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @param {string} hash the full hash + * @param {string} renderedHash the shortened hash for rendering + * @returns {void} + */ + setModuleHashes(module, runtime, hash, renderedHash) { + const cgm = this._getChunkGraphModule(module); + if (cgm.hashes === undefined) { + cgm.hashes = new RuntimeSpecMap(); } - this.children.add(child); - } - - serialize({ write }) { - write(this._flags); - if (this.hasStartTime()) write(this.startTime); - if (this.hasFileTimestamps()) write(this.fileTimestamps); - if (this.hasFileHashes()) write(this.fileHashes); - if (this.hasFileTshs()) write(this.fileTshs); - if (this.hasContextTimestamps()) write(this.contextTimestamps); - if (this.hasContextHashes()) write(this.contextHashes); - if (this.hasContextTshs()) write(this.contextTshs); - if (this.hasMissingExistence()) write(this.missingExistence); - if (this.hasManagedItemInfo()) write(this.managedItemInfo); - if (this.hasManagedFiles()) write(this.managedFiles); - if (this.hasManagedContexts()) write(this.managedContexts); - if (this.hasManagedMissing()) write(this.managedMissing); - if (this.hasChildren()) write(this.children); + cgm.hashes.set(runtime, new ModuleHashInfo(hash, renderedHash)); } - deserialize({ read }) { - this._flags = read(); - if (this.hasStartTime()) this.startTime = read(); - if (this.hasFileTimestamps()) this.fileTimestamps = read(); - if (this.hasFileHashes()) this.fileHashes = read(); - if (this.hasFileTshs()) this.fileTshs = read(); - if (this.hasContextTimestamps()) this.contextTimestamps = read(); - if (this.hasContextHashes()) this.contextHashes = read(); - if (this.hasContextTshs()) this.contextTshs = read(); - if (this.hasMissingExistence()) this.missingExistence = read(); - if (this.hasManagedItemInfo()) this.managedItemInfo = read(); - if (this.hasManagedFiles()) this.managedFiles = read(); - if (this.hasManagedContexts()) this.managedContexts = read(); - if (this.hasManagedMissing()) this.managedMissing = read(); - if (this.hasChildren()) this.children = read(); + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @param {Set} items runtime requirements to be added (ownership of this Set is given to ChunkGraph when transferOwnership not false) + * @param {boolean} transferOwnership true: transfer ownership of the items object, false: items is immutable and shared and won't be modified + * @returns {void} + */ + addModuleRuntimeRequirements( + module, + runtime, + items, + transferOwnership = true + ) { + const cgm = this._getChunkGraphModule(module); + const runtimeRequirementsMap = cgm.runtimeRequirements; + if (runtimeRequirementsMap === undefined) { + const map = new RuntimeSpecMap(); + // TODO avoid cloning item and track ownership instead + map.set(runtime, transferOwnership ? items : new Set(items)); + cgm.runtimeRequirements = map; + return; + } + runtimeRequirementsMap.update(runtime, runtimeRequirements => { + if (runtimeRequirements === undefined) { + return transferOwnership ? items : new Set(items); + } else if (!transferOwnership || runtimeRequirements.size >= items.size) { + for (const item of items) runtimeRequirements.add(item); + return runtimeRequirements; + } else { + for (const item of runtimeRequirements) items.add(item); + return items; + } + }); } /** - * @param {function(Snapshot): (ReadonlyMap | ReadonlySet)[]} getMaps first - * @returns {Iterable} iterable + * @param {Chunk} chunk the chunk + * @param {Set} items runtime requirements to be added (ownership of this Set is given to ChunkGraph) + * @returns {void} */ - _createIterable(getMaps) { - return new SnapshotIterable(this, getMaps); + addChunkRuntimeRequirements(chunk, items) { + const cgc = this._getChunkGraphChunk(chunk); + const runtimeRequirements = cgc.runtimeRequirements; + if (runtimeRequirements === undefined) { + cgc.runtimeRequirements = items; + } else if (runtimeRequirements.size >= items.size) { + for (const item of items) runtimeRequirements.add(item); + } else { + for (const item of runtimeRequirements) items.add(item); + cgc.runtimeRequirements = items; + } } /** - * @returns {Iterable} iterable + * @param {Chunk} chunk the chunk + * @param {Iterable} items runtime requirements to be added + * @returns {void} */ - getFileIterable() { - return this._createIterable(s => [ - s.fileTimestamps, - s.fileHashes, - s.fileTshs, - s.managedFiles - ]); + addTreeRuntimeRequirements(chunk, items) { + const cgc = this._getChunkGraphChunk(chunk); + const runtimeRequirements = cgc.runtimeRequirementsInTree; + for (const item of items) runtimeRequirements.add(item); } /** - * @returns {Iterable} iterable + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {ReadonlySet} runtime requirements */ - getContextIterable() { - return this._createIterable(s => [ - s.contextTimestamps, - s.contextHashes, - s.contextTshs, - s.managedContexts - ]); + getModuleRuntimeRequirements(module, runtime) { + const cgm = this._getChunkGraphModule(module); + const runtimeRequirements = + cgm.runtimeRequirements && cgm.runtimeRequirements.get(runtime); + return runtimeRequirements === undefined ? EMPTY_SET : runtimeRequirements; } /** - * @returns {Iterable} iterable + * @param {Chunk} chunk the chunk + * @returns {ReadonlySet} runtime requirements */ - getMissingIterable() { - return this._createIterable(s => [s.missingExistence, s.managedMissing]); + getChunkRuntimeRequirements(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + const runtimeRequirements = cgc.runtimeRequirements; + return runtimeRequirements === undefined ? EMPTY_SET : runtimeRequirements; } -} - -makeSerializable(Snapshot, "webpack/lib/FileSystemInfo", "Snapshot"); -const MIN_COMMON_SNAPSHOT_SIZE = 3; - -/** - * @template T - */ -class SnapshotOptimization { /** - * @param {function(Snapshot): boolean} has has value - * @param {function(Snapshot): Map | Set} get get value - * @param {function(Snapshot, Map | Set): void} set set value - * @param {boolean=} useStartTime use the start time of snapshots - * @param {boolean=} isSet value is an Set instead of a Map + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @param {boolean} withConnections include connections + * @returns {string} hash */ - constructor(has, get, set, useStartTime = true, isSet = false) { - this._has = has; - this._get = get; - this._set = set; - this._useStartTime = useStartTime; - this._isSet = isSet; - /** @type {Map} */ - this._map = new Map(); - this._statItemsShared = 0; - this._statItemsUnshared = 0; - this._statSharedSnapshots = 0; - this._statReusedSharedSnapshots = 0; + getModuleGraphHash(module, runtime, withConnections = true) { + const cgm = this._getChunkGraphModule(module); + return withConnections + ? this._getModuleGraphHashWithConnections(cgm, module, runtime) + : this._getModuleGraphHashBigInt(cgm, module, runtime).toString(16); } - getStatisticMessage() { - const total = this._statItemsShared + this._statItemsUnshared; - if (total === 0) return undefined; - return `${ - this._statItemsShared && Math.round((this._statItemsShared * 100) / total) - }% (${this._statItemsShared}/${total}) entries shared via ${ - this._statSharedSnapshots - } shared snapshots (${ - this._statReusedSharedSnapshots + this._statSharedSnapshots - } times referenced)`; + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @param {boolean} withConnections include connections + * @returns {bigint} hash + */ + getModuleGraphHashBigInt(module, runtime, withConnections = true) { + const cgm = this._getChunkGraphModule(module); + return withConnections + ? BigInt( + `0x${this._getModuleGraphHashWithConnections(cgm, module, runtime)}` + ) + : this._getModuleGraphHashBigInt(cgm, module, runtime); } - clear() { - this._map.clear(); - this._statItemsShared = 0; - this._statItemsUnshared = 0; - this._statSharedSnapshots = 0; - this._statReusedSharedSnapshots = 0; + /** + * @param {ChunkGraphModule} cgm the ChunkGraphModule + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {bigint} hash as big int + */ + _getModuleGraphHashBigInt(cgm, module, runtime) { + if (cgm.graphHashes === undefined) { + cgm.graphHashes = new RuntimeSpecMap(); + } + const graphHash = cgm.graphHashes.provide(runtime, () => { + const hash = createHash(this._hashFunction); + hash.update(`${cgm.id}${this.moduleGraph.isAsync(module)}`); + this.moduleGraph.getExportsInfo(module).updateHash(hash, runtime); + return BigInt(`0x${/** @type {string} */ (hash.digest("hex"))}`); + }); + return graphHash; } /** - * @param {Snapshot} newSnapshot snapshot - * @param {Set} capturedFiles files to snapshot/share - * @returns {void} + * @param {ChunkGraphModule} cgm the ChunkGraphModule + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {string} hash */ - optimize(newSnapshot, capturedFiles) { - /** - * @param {SnapshotOptimizationEntry} entry optimization entry - * @returns {void} - */ - const increaseSharedAndStoreOptimizationEntry = entry => { - if (entry.children !== undefined) { - entry.children.forEach(increaseSharedAndStoreOptimizationEntry); - } - entry.shared++; - storeOptimizationEntry(entry); + _getModuleGraphHashWithConnections(cgm, module, runtime) { + if (cgm.graphHashesWithConnections === undefined) { + cgm.graphHashesWithConnections = new RuntimeSpecMap(); + } + const activeStateToString = state => { + if (state === false) return "F"; + if (state === true) return "T"; + if (state === ModuleGraphConnection.TRANSITIVE_ONLY) return "O"; + throw new Error("Not implemented active state"); }; - /** - * @param {SnapshotOptimizationEntry} entry optimization entry - * @returns {void} - */ - const storeOptimizationEntry = entry => { - for (const path of entry.snapshotContent) { - const old = this._map.get(path); - if (old.shared < entry.shared) { - this._map.set(path, entry); + const strict = module.buildMeta && module.buildMeta.strictHarmonyModule; + return cgm.graphHashesWithConnections.provide(runtime, () => { + const graphHash = this._getModuleGraphHashBigInt( + cgm, + module, + runtime + ).toString(16); + const connections = this.moduleGraph.getOutgoingConnections(module); + /** @type {Set} */ + const activeNamespaceModules = new Set(); + /** @type {Map>} */ + const connectedModules = new Map(); + const processConnection = (connection, stateInfo) => { + const module = connection.module; + stateInfo += module.getExportsType(this.moduleGraph, strict); + // cspell:word Tnamespace + if (stateInfo === "Tnamespace") activeNamespaceModules.add(module); + else { + const oldModule = connectedModules.get(stateInfo); + if (oldModule === undefined) { + connectedModules.set(stateInfo, module); + } else if (oldModule instanceof Set) { + oldModule.add(module); + } else if (oldModule !== module) { + connectedModules.set(stateInfo, new Set([oldModule, module])); + } } - capturedFiles.delete(path); - } - }; - - /** @type {SnapshotOptimizationEntry} */ - let newOptimizationEntry = undefined; - - const capturedFilesSize = capturedFiles.size; - - /** @type {Set | undefined} */ - const optimizationEntries = new Set(); - - for (const path of capturedFiles) { - const optimizationEntry = this._map.get(path); - if (optimizationEntry === undefined) { - if (newOptimizationEntry === undefined) { - newOptimizationEntry = { - snapshot: newSnapshot, - shared: 0, - snapshotContent: undefined, - children: undefined - }; + }; + if (runtime === undefined || typeof runtime === "string") { + for (const connection of connections) { + const state = connection.getActiveState(runtime); + if (state === false) continue; + processConnection(connection, state === true ? "T" : "O"); } - this._map.set(path, newOptimizationEntry); - continue; } else { - optimizationEntries.add(optimizationEntry); - } - } - - optimizationEntries: for (const optimizationEntry of optimizationEntries) { - const snapshot = optimizationEntry.snapshot; - if (optimizationEntry.shared > 0) { - // It's a shared snapshot - // We can't change it, so we can only use it when all files match - // and startTime is compatible - if ( - this._useStartTime && - newSnapshot.startTime && - (!snapshot.startTime || snapshot.startTime > newSnapshot.startTime) - ) { - continue; - } - const nonSharedFiles = new Set(); - const snapshotContent = optimizationEntry.snapshotContent; - const snapshotEntries = this._get(snapshot); - for (const path of snapshotContent) { - if (!capturedFiles.has(path)) { - if (!snapshotEntries.has(path)) { - // File is not shared and can't be removed from the snapshot - // because it's in a child of the snapshot - continue optimizationEntries; - } - nonSharedFiles.add(path); - continue; - } - } - if (nonSharedFiles.size === 0) { - // The complete snapshot is shared - // add it as child - newSnapshot.addChild(snapshot); - increaseSharedAndStoreOptimizationEntry(optimizationEntry); - this._statReusedSharedSnapshots++; - } else { - // Only a part of the snapshot is shared - const sharedCount = snapshotContent.size - nonSharedFiles.size; - if (sharedCount < MIN_COMMON_SNAPSHOT_SIZE) { - // Common part it too small - continue optimizationEntries; - } - // Extract common timestamps from both snapshots - let commonMap; - if (this._isSet) { - commonMap = new Set(); - for (const path of /** @type {Set} */ (snapshotEntries)) { - if (nonSharedFiles.has(path)) continue; - commonMap.add(path); - snapshotEntries.delete(path); - } - } else { - commonMap = new Map(); - const map = /** @type {Map} */ (snapshotEntries); - for (const [path, value] of map) { - if (nonSharedFiles.has(path)) continue; - commonMap.set(path, value); - snapshotEntries.delete(path); - } - } - // Create and attach snapshot - const commonSnapshot = new Snapshot(); - if (this._useStartTime) { - commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot); + // cspell:word Tnamespace + for (const connection of connections) { + const states = new Set(); + let stateInfo = ""; + forEachRuntime( + runtime, + runtime => { + const state = connection.getActiveState(runtime); + states.add(state); + stateInfo += activeStateToString(state) + runtime; + }, + true + ); + if (states.size === 1) { + const state = first(states); + if (state === false) continue; + stateInfo = activeStateToString(state); } - this._set(commonSnapshot, commonMap); - newSnapshot.addChild(commonSnapshot); - snapshot.addChild(commonSnapshot); - // Create optimization entry - const newEntry = { - snapshot: commonSnapshot, - shared: optimizationEntry.shared + 1, - snapshotContent: new Set(commonMap.keys()), - children: undefined - }; - if (optimizationEntry.children === undefined) - optimizationEntry.children = new Set(); - optimizationEntry.children.add(newEntry); - storeOptimizationEntry(newEntry); - this._statSharedSnapshots++; + processConnection(connection, stateInfo); } - } else { - // It's a unshared snapshot - // We can extract a common shared snapshot - // with all common files - const snapshotEntries = this._get(snapshot); - if (snapshotEntries === undefined) { - // Incomplete snapshot, that can't be used - continue optimizationEntries; + } + // cspell:word Tnamespace + if (activeNamespaceModules.size === 0 && connectedModules.size === 0) + return graphHash; + const connectedModulesInOrder = + connectedModules.size > 1 + ? Array.from(connectedModules).sort(([a], [b]) => (a < b ? -1 : 1)) + : connectedModules; + const hash = createHash(this._hashFunction); + const addModuleToHash = module => { + hash.update( + this._getModuleGraphHashBigInt( + this._getChunkGraphModule(module), + module, + runtime + ).toString(16) + ); + }; + const addModulesToHash = modules => { + let xor = ZERO_BIG_INT; + for (const m of modules) { + xor = + xor ^ + this._getModuleGraphHashBigInt( + this._getChunkGraphModule(m), + m, + runtime + ); } - let commonMap; - if (this._isSet) { - commonMap = new Set(); - const set = /** @type {Set} */ (snapshotEntries); - if (capturedFiles.size < set.size) { - for (const path of capturedFiles) { - if (set.has(path)) commonMap.add(path); - } - } else { - for (const path of set) { - if (capturedFiles.has(path)) commonMap.add(path); - } - } + hash.update(xor.toString(16)); + }; + if (activeNamespaceModules.size === 1) + addModuleToHash(activeNamespaceModules.values().next().value); + else if (activeNamespaceModules.size > 1) + addModulesToHash(activeNamespaceModules); + for (const [stateInfo, modules] of connectedModulesInOrder) { + hash.update(stateInfo); + if (modules instanceof Set) { + addModulesToHash(modules); } else { - commonMap = new Map(); - const map = /** @type {Map} */ (snapshotEntries); - for (const path of capturedFiles) { - const ts = map.get(path); - if (ts === undefined) continue; - commonMap.set(path, ts); - } - } - - if (commonMap.size < MIN_COMMON_SNAPSHOT_SIZE) { - // Common part it too small - continue optimizationEntries; - } - // Create and attach snapshot - const commonSnapshot = new Snapshot(); - if (this._useStartTime) { - commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot); + addModuleToHash(modules); } - this._set(commonSnapshot, commonMap); - newSnapshot.addChild(commonSnapshot); - snapshot.addChild(commonSnapshot); - // Remove files from snapshot - for (const path of commonMap.keys()) snapshotEntries.delete(path); - const sharedCount = commonMap.size; - this._statItemsUnshared -= sharedCount; - this._statItemsShared += sharedCount; - // Create optimization entry - storeOptimizationEntry({ - snapshot: commonSnapshot, - shared: 2, - snapshotContent: new Set(commonMap.keys()), - children: undefined - }); - this._statSharedSnapshots++; } - } - const unshared = capturedFiles.size; - this._statItemsUnshared += unshared; - this._statItemsShared += capturedFilesSize - unshared; + hash.update(graphHash); + return /** @type {string} */ (hash.digest("hex")); + }); } -} -const parseString = str => { - if (str[0] === "'") str = `"${str.slice(1, -1).replace(/"/g, '\\"')}"`; - return JSON.parse(str); -}; + /** + * @param {Chunk} chunk the chunk + * @returns {ReadonlySet} runtime requirements + */ + getTreeRuntimeRequirements(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.runtimeRequirementsInTree; + } -/* istanbul ignore next */ -/** - * @param {number} mtime mtime - */ -const applyMtime = mtime => { - if (FS_ACCURACY > 1 && mtime % 2 !== 0) FS_ACCURACY = 1; - else if (FS_ACCURACY > 10 && mtime % 20 !== 0) FS_ACCURACY = 10; - else if (FS_ACCURACY > 100 && mtime % 200 !== 0) FS_ACCURACY = 100; - else if (FS_ACCURACY > 1000 && mtime % 2000 !== 0) FS_ACCURACY = 1000; -}; + // 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 {ChunkGraph} the chunk graph + */ + static getChunkGraphForModule(module, deprecateMessage, deprecationCode) { + const fn = deprecateGetChunkGraphForModuleMap.get(deprecateMessage); + if (fn) return fn(module); + const newFn = util.deprecate( + /** + * @param {Module} module the module + * @returns {ChunkGraph} the chunk graph + */ + module => { + const chunkGraph = chunkGraphForModuleMap.get(module); + if (!chunkGraph) + throw new Error( + deprecateMessage + + ": There was no ChunkGraph assigned to the Module for backward-compat (Use the new API)" + ); + return chunkGraph; + }, + deprecateMessage + ": Use new ChunkGraph API", + deprecationCode + ); + deprecateGetChunkGraphForModuleMap.set(deprecateMessage, newFn); + return newFn(module); + } -/** - * @template T - * @template K - * @param {Map} a source map - * @param {Map} b joining map - * @returns {Map} joined map - */ -const mergeMaps = (a, b) => { - if (!b || b.size === 0) return a; - if (!a || a.size === 0) return b; - const map = new Map(a); - for (const [key, value] of b) { - map.set(key, value); + // TODO remove in webpack 6 + /** + * @param {Module} module the module + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} + */ + static setChunkGraphForModule(module, chunkGraph) { + chunkGraphForModuleMap.set(module, chunkGraph); } - return map; -}; -/** - * @template T - * @template K - * @param {Set} a source map - * @param {Set} b joining map - * @returns {Set} joined map - */ -const mergeSets = (a, b) => { - if (!b || b.size === 0) return a; - if (!a || a.size === 0) return b; - const map = new Set(a); - for (const item of b) { - map.add(item); + // TODO remove in webpack 6 + /** + * @param {Module} module the module + * @returns {void} + */ + static clearChunkGraphForModule(module) { + chunkGraphForModuleMap.delete(module); } - return map; -}; -/** - * Finding file or directory to manage - * @param {string} managedPath path that is managing by {@link FileSystemInfo} - * @param {string} path path to file or directory - * @returns {string|null} managed item - * @example - * getManagedItem( - * '/Users/user/my-project/node_modules/', - * '/Users/user/my-project/node_modules/package/index.js' - * ) === '/Users/user/my-project/node_modules/package' - * getManagedItem( - * '/Users/user/my-project/node_modules/', - * '/Users/user/my-project/node_modules/package1/node_modules/package2' - * ) === '/Users/user/my-project/node_modules/package1/node_modules/package2' - * getManagedItem( - * '/Users/user/my-project/node_modules/', - * '/Users/user/my-project/node_modules/.bin/script.js' - * ) === null // hidden files are disallowed as managed items - * getManagedItem( - * '/Users/user/my-project/node_modules/', - * '/Users/user/my-project/node_modules/package' - * ) === '/Users/user/my-project/node_modules/package' - */ -const getManagedItem = (managedPath, path) => { - let i = managedPath.length; - let slashes = 1; - let startingPosition = true; - loop: while (i < path.length) { - switch (path.charCodeAt(i)) { - case 47: // slash - case 92: // backslash - if (--slashes === 0) break loop; - startingPosition = true; - break; - case 46: // . - // hidden files are disallowed as managed items - // it's probably .yarn-integrity or .cache - if (startingPosition) return null; - break; - case 64: // @ - if (!startingPosition) return null; - slashes++; - break; - default: - startingPosition = false; - break; - } - i++; + // TODO remove in webpack 6 + /** + * @param {Chunk} chunk the chunk + * @param {string} deprecateMessage message for the deprecation message + * @param {string} deprecationCode code for the deprecation + * @returns {ChunkGraph} the chunk graph + */ + static getChunkGraphForChunk(chunk, deprecateMessage, deprecationCode) { + const fn = deprecateGetChunkGraphForChunkMap.get(deprecateMessage); + if (fn) return fn(chunk); + const newFn = util.deprecate( + /** + * @param {Chunk} chunk the chunk + * @returns {ChunkGraph} the chunk graph + */ + chunk => { + const chunkGraph = chunkGraphForChunkMap.get(chunk); + if (!chunkGraph) + throw new Error( + deprecateMessage + + "There was no ChunkGraph assigned to the Chunk for backward-compat (Use the new API)" + ); + return chunkGraph; + }, + deprecateMessage + ": Use new ChunkGraph API", + deprecationCode + ); + deprecateGetChunkGraphForChunkMap.set(deprecateMessage, newFn); + return newFn(chunk); } - if (i === path.length) slashes--; - // return null when path is incomplete - if (slashes !== 0) return null; - // if (path.slice(i + 1, i + 13) === "node_modules") - if ( - path.length >= i + 13 && - path.charCodeAt(i + 1) === 110 && - path.charCodeAt(i + 2) === 111 && - path.charCodeAt(i + 3) === 100 && - path.charCodeAt(i + 4) === 101 && - path.charCodeAt(i + 5) === 95 && - path.charCodeAt(i + 6) === 109 && - path.charCodeAt(i + 7) === 111 && - path.charCodeAt(i + 8) === 100 && - path.charCodeAt(i + 9) === 117 && - path.charCodeAt(i + 10) === 108 && - path.charCodeAt(i + 11) === 101 && - path.charCodeAt(i + 12) === 115 - ) { - // if this is the end of the path - if (path.length === i + 13) { - // return the node_modules directory - // it's special - return path; - } - const c = path.charCodeAt(i + 13); - // if next symbol is slash or backslash - if (c === 47 || c === 92) { - // Managed subpath - return getManagedItem(path.slice(0, i + 14), path); - } + + // TODO remove in webpack 6 + /** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} + */ + static setChunkGraphForChunk(chunk, chunkGraph) { + chunkGraphForChunkMap.set(chunk, chunkGraph); } - return path.slice(0, i); -}; -/** - * @template {ContextFileSystemInfoEntry | ContextTimestampAndHash} T - * @param {T} entry entry - * @returns {T["resolved"] | undefined} the resolved entry - */ -const getResolvedTimestamp = entry => { - if (entry === null) return null; - if (entry.resolved !== undefined) return entry.resolved; - return entry.symlinks === undefined ? entry : undefined; -}; + // TODO remove in webpack 6 + /** + * @param {Chunk} chunk the chunk + * @returns {void} + */ + static clearChunkGraphForChunk(chunk) { + chunkGraphForChunkMap.delete(chunk); + } +} -/** - * @param {ContextHash} entry entry - * @returns {string | undefined} the resolved entry - */ -const getResolvedHash = entry => { - if (entry === null) return null; - if (entry.resolved !== undefined) return entry.resolved; - return entry.symlinks === undefined ? entry.hash : undefined; -}; +// TODO remove in webpack 6 +/** @type {WeakMap} */ +const chunkGraphForModuleMap = new WeakMap(); -const addAll = (source, target) => { - for (const key of source) target.add(key); -}; +// TODO remove in webpack 6 +/** @type {WeakMap} */ +const chunkGraphForChunkMap = new WeakMap(); -/** - * Used to access information about the filesystem in a cached way - */ -class FileSystemInfo { - /** - * @param {InputFileSystem} fs file system - * @param {Object} options options - * @param {Iterable=} options.managedPaths paths that are only managed by a package manager - * @param {Iterable=} options.immutablePaths paths that are immutable - * @param {Logger=} options.logger logger used to log invalid snapshots - * @param {string | Hash=} options.hashFunction the hash function to use - */ - constructor( - fs, - { - managedPaths = [], - immutablePaths = [], - logger, - hashFunction = "md4" - } = {} - ) { - this.fs = fs; - this.logger = logger; - this._remainingLogs = logger ? 40 : 0; - this._loggedPaths = logger ? new Set() : undefined; - this._hashFunction = hashFunction; - /** @type {WeakMap} */ - this._snapshotCache = new WeakMap(); - this._fileTimestampsOptimization = new SnapshotOptimization( - s => s.hasFileTimestamps(), - s => s.fileTimestamps, - (s, v) => s.setFileTimestamps(v) - ); - this._fileHashesOptimization = new SnapshotOptimization( - s => s.hasFileHashes(), - s => s.fileHashes, - (s, v) => s.setFileHashes(v), - false - ); - this._fileTshsOptimization = new SnapshotOptimization( - s => s.hasFileTshs(), - s => s.fileTshs, - (s, v) => s.setFileTshs(v) - ); - this._contextTimestampsOptimization = new SnapshotOptimization( - s => s.hasContextTimestamps(), - s => s.contextTimestamps, - (s, v) => s.setContextTimestamps(v) - ); - this._contextHashesOptimization = new SnapshotOptimization( - s => s.hasContextHashes(), - s => s.contextHashes, - (s, v) => s.setContextHashes(v), - false - ); - this._contextTshsOptimization = new SnapshotOptimization( - s => s.hasContextTshs(), - s => s.contextTshs, - (s, v) => s.setContextTshs(v) - ); - this._missingExistenceOptimization = new SnapshotOptimization( - s => s.hasMissingExistence(), - s => s.missingExistence, - (s, v) => s.setMissingExistence(v), - false - ); - this._managedItemInfoOptimization = new SnapshotOptimization( - s => s.hasManagedItemInfo(), - s => s.managedItemInfo, - (s, v) => s.setManagedItemInfo(v), - false - ); - this._managedFilesOptimization = new SnapshotOptimization( - s => s.hasManagedFiles(), - s => s.managedFiles, - (s, v) => s.setManagedFiles(v), - false, - true - ); - this._managedContextsOptimization = new SnapshotOptimization( - s => s.hasManagedContexts(), - s => s.managedContexts, - (s, v) => s.setManagedContexts(v), - false, - true - ); - this._managedMissingOptimization = new SnapshotOptimization( - s => s.hasManagedMissing(), - s => s.managedMissing, - (s, v) => s.setManagedMissing(v), - false, - true - ); - /** @type {StackedCacheMap} */ - this._fileTimestamps = new StackedCacheMap(); - /** @type {Map} */ - this._fileHashes = new Map(); - /** @type {Map} */ - this._fileTshs = new Map(); - /** @type {StackedCacheMap} */ - this._contextTimestamps = new StackedCacheMap(); - /** @type {Map} */ - this._contextHashes = new Map(); - /** @type {Map} */ - this._contextTshs = new Map(); - /** @type {Map} */ - this._managedItems = new Map(); - /** @type {AsyncQueue} */ - this.fileTimestampQueue = new AsyncQueue({ - name: "file timestamp", - parallelism: 30, - processor: this._readFileTimestamp.bind(this) - }); - /** @type {AsyncQueue} */ - this.fileHashQueue = new AsyncQueue({ - name: "file hash", - parallelism: 10, - processor: this._readFileHash.bind(this) - }); - /** @type {AsyncQueue} */ - this.contextTimestampQueue = new AsyncQueue({ - name: "context timestamp", - parallelism: 2, - processor: this._readContextTimestamp.bind(this) - }); - /** @type {AsyncQueue} */ - this.contextHashQueue = new AsyncQueue({ - name: "context hash", - parallelism: 2, - processor: this._readContextHash.bind(this) - }); - /** @type {AsyncQueue} */ - this.contextTshQueue = new AsyncQueue({ - name: "context hash and timestamp", - parallelism: 2, - processor: this._readContextTimestampAndHash.bind(this) - }); - /** @type {AsyncQueue} */ - this.managedItemQueue = new AsyncQueue({ - name: "managed item info", - parallelism: 10, - processor: this._getManagedItemInfo.bind(this) - }); - /** @type {AsyncQueue>} */ - this.managedItemDirectoryQueue = new AsyncQueue({ - name: "managed item directory info", - parallelism: 10, - processor: this._getManagedItemDirectoryInfo.bind(this) - }); - this.managedPaths = Array.from(managedPaths); - this.managedPathsWithSlash = /** @type {string[]} */ ( - this.managedPaths.filter(p => typeof p === "string") - ).map(p => join(fs, p, "_").slice(0, -1)); +// TODO remove in webpack 6 +/** @type {Map ChunkGraph>} */ +const deprecateGetChunkGraphForModuleMap = new Map(); - this.managedPathsRegExps = /** @type {RegExp[]} */ ( - this.managedPaths.filter(p => typeof p !== "string") - ); - this.immutablePaths = Array.from(immutablePaths); - this.immutablePathsWithSlash = /** @type {string[]} */ ( - this.immutablePaths.filter(p => typeof p === "string") - ).map(p => join(fs, p, "_").slice(0, -1)); - this.immutablePathsRegExps = /** @type {RegExp[]} */ ( - this.immutablePaths.filter(p => typeof p !== "string") - ); +// TODO remove in webpack 6 +/** @type {Map ChunkGraph>} */ +const deprecateGetChunkGraphForChunkMap = new Map(); - this._cachedDeprecatedFileTimestamps = undefined; - this._cachedDeprecatedContextTimestamps = undefined; +module.exports = ChunkGraph; - this._warnAboutExperimentalEsmTracking = false; - this._statCreatedSnapshots = 0; - this._statTestedSnapshotsCached = 0; - this._statTestedSnapshotsNotCached = 0; - this._statTestedChildrenCached = 0; - this._statTestedChildrenNotCached = 0; - this._statTestedEntries = 0; - } +/***/ }), - logStatistics() { - const logWhenMessage = (header, message) => { - if (message) { - this.logger.log(`${header}: ${message}`); - } - }; - this.logger.log(`${this._statCreatedSnapshots} new snapshots created`); - this.logger.log( - `${ - this._statTestedSnapshotsNotCached && - Math.round( - (this._statTestedSnapshotsNotCached * 100) / - (this._statTestedSnapshotsCached + - this._statTestedSnapshotsNotCached) - ) - }% root snapshot uncached (${this._statTestedSnapshotsNotCached} / ${ - this._statTestedSnapshotsCached + this._statTestedSnapshotsNotCached - })` - ); - this.logger.log( - `${ - this._statTestedChildrenNotCached && - Math.round( - (this._statTestedChildrenNotCached * 100) / - (this._statTestedChildrenCached + this._statTestedChildrenNotCached) - ) - }% children snapshot uncached (${this._statTestedChildrenNotCached} / ${ - this._statTestedChildrenCached + this._statTestedChildrenNotCached - })` - ); - this.logger.log(`${this._statTestedEntries} entries tested`); - this.logger.log( - `File info in cache: ${this._fileTimestamps.size} timestamps ${this._fileHashes.size} hashes ${this._fileTshs.size} timestamp hash combinations` - ); - logWhenMessage( - `File timestamp snapshot optimization`, - this._fileTimestampsOptimization.getStatisticMessage() - ); - logWhenMessage( - `File hash snapshot optimization`, - this._fileHashesOptimization.getStatisticMessage() - ); - logWhenMessage( - `File timestamp hash combination snapshot optimization`, - this._fileTshsOptimization.getStatisticMessage() - ); - this.logger.log( - `Directory info in cache: ${this._contextTimestamps.size} timestamps ${this._contextHashes.size} hashes ${this._contextTshs.size} timestamp hash combinations` - ); - logWhenMessage( - `Directory timestamp snapshot optimization`, - this._contextTimestampsOptimization.getStatisticMessage() - ); - logWhenMessage( - `Directory hash snapshot optimization`, - this._contextHashesOptimization.getStatisticMessage() - ); - logWhenMessage( - `Directory timestamp hash combination snapshot optimization`, - this._contextTshsOptimization.getStatisticMessage() - ); - logWhenMessage( - `Missing items snapshot optimization`, - this._missingExistenceOptimization.getStatisticMessage() - ); - this.logger.log( - `Managed items info in cache: ${this._managedItems.size} items` - ); - logWhenMessage( - `Managed items snapshot optimization`, - this._managedItemInfoOptimization.getStatisticMessage() - ); - logWhenMessage( - `Managed files snapshot optimization`, - this._managedFilesOptimization.getStatisticMessage() - ); - logWhenMessage( - `Managed contexts snapshot optimization`, - this._managedContextsOptimization.getStatisticMessage() - ); - logWhenMessage( - `Managed missing snapshot optimization`, - this._managedMissingOptimization.getStatisticMessage() - ); - } +/***/ 15626: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - _log(path, reason, ...args) { - const key = path + reason; - if (this._loggedPaths.has(key)) return; - this._loggedPaths.add(key); - this.logger.debug(`${path} invalidated because ${reason}`, ...args); - if (--this._remainingLogs === 0) { - this.logger.debug( - "Logging limit has been reached and no further logging will be emitted by FileSystemInfo" - ); - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - clear() { - this._remainingLogs = this.logger ? 40 : 0; - if (this._loggedPaths !== undefined) this._loggedPaths.clear(); - this._snapshotCache = new WeakMap(); - this._fileTimestampsOptimization.clear(); - this._fileHashesOptimization.clear(); - this._fileTshsOptimization.clear(); - this._contextTimestampsOptimization.clear(); - this._contextHashesOptimization.clear(); - this._contextTshsOptimization.clear(); - this._missingExistenceOptimization.clear(); - this._managedItemInfoOptimization.clear(); - this._managedFilesOptimization.clear(); - this._managedContextsOptimization.clear(); - this._managedMissingOptimization.clear(); - this._fileTimestamps.clear(); - this._fileHashes.clear(); - this._fileTshs.clear(); - this._contextTimestamps.clear(); - this._contextHashes.clear(); - this._contextTshs.clear(); - this._managedItems.clear(); - this._managedItems.clear(); - this._cachedDeprecatedFileTimestamps = undefined; - this._cachedDeprecatedContextTimestamps = undefined; +const util = __webpack_require__(73837); +const SortableSet = __webpack_require__(13098); +const { + compareLocations, + compareChunks, + compareIterables +} = __webpack_require__(29579); - this._statCreatedSnapshots = 0; - this._statTestedSnapshotsCached = 0; - this._statTestedSnapshotsNotCached = 0; - this._statTestedChildrenCached = 0; - this._statTestedChildrenNotCached = 0; - this._statTestedEntries = 0; - } +/** @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} 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 { /** - * @param {ReadonlyMap} map timestamps - * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it - * @returns {void} + * Creates an instance of ChunkGroup. + * @param {string|ChunkGroupOptions=} options chunk group options passed to chunkGroup */ - addFileTimestamps(map, immutable) { - this._fileTimestamps.addAll(map, immutable); - this._cachedDeprecatedFileTimestamps = undefined; + 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} */ + this._children = new SortableSet(undefined, sortById); + /** @type {SortableSet} */ + this._parents = new SortableSet(undefined, sortById); + /** @type {SortableSet} */ + 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} */ + this._modulePreOrderIndices = new Map(); + /** Indices in bottom-up order */ + /** @private @type {Map} */ + this._modulePostOrderIndices = new Map(); + /** @type {number} */ + this.index = undefined; } /** - * @param {ReadonlyMap} map timestamps - * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it + * when a new chunk is added to a chunkGroup, addingOptions will occur. + * @param {ChunkGroupOptions} options the chunkGroup options passed to addOptions * @returns {void} */ - addContextTimestamps(map, immutable) { - this._contextTimestamps.addAll(map, immutable); - this._cachedDeprecatedContextTimestamps = undefined; + 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}` + ); + } + } + } } /** - * @param {string} path file path - * @param {function((WebpackError | null)=, (FileSystemInfoEntry | "ignore" | null)=): void} callback callback function - * @returns {void} + * returns the name of current ChunkGroup + * @returns {string|undefined} returns the ChunkGroup name */ - getFileTimestamp(path, callback) { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) return callback(null, cache); - this.fileTimestampQueue.add(path, callback); + get name() { + return this.options.name; } /** - * @param {string} path context path - * @param {function((WebpackError | null)=, (ResolvedContextFileSystemInfoEntry | "ignore" | null)=): void} callback callback function + * sets a new name for current ChunkGroup + * @param {string} value the new name for ChunkGroup * @returns {void} */ - getContextTimestamp(path, callback) { - const cache = this._contextTimestamps.get(path); - if (cache !== undefined) { - if (cache === "ignore") return callback(null, "ignore"); - const resolved = getResolvedTimestamp(cache); - if (resolved !== undefined) return callback(null, resolved); - return this._resolveContextTimestamp(cache, callback); - } - this.contextTimestampQueue.add(path, (err, entry) => { - if (err) return callback(err); - const resolved = getResolvedTimestamp(entry); - if (resolved !== undefined) return callback(null, resolved); - this._resolveContextTimestamp(entry, callback); - }); + set name(value) { + this.options.name = value; } + /* istanbul ignore next */ /** - * @param {string} path context path - * @param {function((WebpackError | null)=, (ContextFileSystemInfoEntry | "ignore" | null)=): void} callback callback function - * @returns {void} + * get a uniqueId for ChunkGroup, made up of its member Chunk debugId's + * @returns {string} a unique concatenation of chunk debugId's */ - _getUnresolvedContextTimestamp(path, callback) { - const cache = this._contextTimestamps.get(path); - if (cache !== undefined) return callback(null, cache); - this.contextTimestampQueue.add(path, callback); + get debugId() { + return Array.from(this.chunks, x => x.debugId).join("+"); } /** - * @param {string} path file path - * @param {function((WebpackError | null)=, string=): void} callback callback function - * @returns {void} + * get a unique id for ChunkGroup, made up of its member Chunk id's + * @returns {string} a unique concatenation of chunk ids */ - getFileHash(path, callback) { - const cache = this._fileHashes.get(path); - if (cache !== undefined) return callback(null, cache); - this.fileHashQueue.add(path, callback); + get id() { + return Array.from(this.chunks, x => x.id).join("+"); } /** - * @param {string} path context path - * @param {function((WebpackError | null)=, string=): void} callback callback function - * @returns {void} + * Performs an unshift of a specific chunk + * @param {Chunk} chunk chunk being unshifted + * @returns {boolean} returns true if attempted chunk shift is accepted */ - getContextHash(path, callback) { - const cache = this._contextHashes.get(path); - if (cache !== undefined) { - const resolved = getResolvedHash(cache); - if (resolved !== undefined) return callback(null, resolved); - return this._resolveContextHash(cache, callback); + 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; } - this.contextHashQueue.add(path, (err, entry) => { - if (err) return callback(err); - const resolved = getResolvedHash(entry); - if (resolved !== undefined) return callback(null, resolved); - this._resolveContextHash(entry, callback); - }); + return false; } /** - * @param {string} path context path - * @param {function((WebpackError | null)=, ContextHash=): void} callback callback function - * @returns {void} + * 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 */ - _getUnresolvedContextHash(path, callback) { - const cache = this._contextHashes.get(path); - if (cache !== undefined) return callback(null, cache); - this.contextHashQueue.add(path, callback); + 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; } /** - * @param {string} path context path - * @param {function((WebpackError | null)=, ResolvedContextTimestampAndHash=): void} callback callback function - * @returns {void} + * 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. */ - getContextTsh(path, callback) { - const cache = this._contextTshs.get(path); - if (cache !== undefined) { - const resolved = getResolvedTimestamp(cache); - if (resolved !== undefined) return callback(null, resolved); - return this._resolveContextTsh(cache, callback); + pushChunk(chunk) { + const oldIdx = this.chunks.indexOf(chunk); + if (oldIdx >= 0) { + return false; } - this.contextTshQueue.add(path, (err, entry) => { - if (err) return callback(err); - const resolved = getResolvedTimestamp(entry); - if (resolved !== undefined) return callback(null, resolved); - this._resolveContextTsh(entry, callback); - }); + this.chunks.push(chunk); + return true; } /** - * @param {string} path context path - * @param {function((WebpackError | null)=, ContextTimestampAndHash=): void} callback callback function - * @returns {void} + * @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 */ - _getUnresolvedContextTsh(path, callback) { - const cache = this._contextTshs.get(path); - if (cache !== undefined) return callback(null, cache); - this.contextTshQueue.add(path, callback); + 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; + } } - _createBuildDependenciesResolvers() { - const resolveContext = createResolver({ - resolveToContext: true, - exportsFields: [], - fileSystem: this.fs - }); - const resolveCjs = createResolver({ - extensions: [".js", ".json", ".node"], - conditionNames: ["require", "node"], - exportsFields: ["exports"], - fileSystem: this.fs - }); - const resolveCjsAsChild = createResolver({ - extensions: [".js", ".json", ".node"], - conditionNames: ["require", "node"], - exportsFields: [], - fileSystem: this.fs - }); - const resolveEsm = createResolver({ - extensions: [".js", ".json", ".node"], - fullySpecified: true, - conditionNames: ["import", "node"], - exportsFields: ["exports"], - fileSystem: this.fs - }); - return { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild }; + /** + * @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; } /** - * @param {string} context context directory - * @param {Iterable} deps dependencies - * @param {function((Error | null)=, ResolveBuildDependenciesResult=): void} callback callback function + * @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} 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} */ - resolveBuildDependencies(context, deps, callback) { - const { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild } = - this._createBuildDependenciesResolvers(); + addOrigin(module, loc, request) { + this.origins.push({ + module, + loc, + request + }); + } - /** @type {Set} */ + /** + * @returns {string[]} the files contained this chunk group + */ + getFiles() { const files = new Set(); - /** @type {Set} */ - const fileSymlinks = new Set(); - /** @type {Set} */ - const directories = new Set(); - /** @type {Set} */ - const directorySymlinks = new Set(); - /** @type {Set} */ - const missing = new Set(); - /** @type {Set} */ - const resolveFiles = new Set(); - /** @type {Set} */ - const resolveDirectories = new Set(); - /** @type {Set} */ - const resolveMissing = new Set(); - /** @type {Map} */ - const resolveResults = new Map(); - const invalidResolveResults = new Set(); - const resolverContext = { - fileDependencies: resolveFiles, - contextDependencies: resolveDirectories, - missingDependencies: resolveMissing - }; - const expectedToString = expected => { - return expected ? ` (expected ${expected})` : ""; - }; - const jobToString = job => { - switch (job.type) { - case RBDT_RESOLVE_CJS: - return `resolve commonjs ${job.path}${expectedToString( - job.expected - )}`; - case RBDT_RESOLVE_ESM: - return `resolve esm ${job.path}${expectedToString(job.expected)}`; - case RBDT_RESOLVE_DIRECTORY: - return `resolve directory ${job.path}`; - case RBDT_RESOLVE_CJS_FILE: - return `resolve commonjs file ${job.path}${expectedToString( - job.expected - )}`; - case RBDT_RESOLVE_ESM_FILE: - return `resolve esm file ${job.path}${expectedToString( - job.expected - )}`; - case RBDT_DIRECTORY: - return `directory ${job.path}`; - case RBDT_FILE: - return `file ${job.path}`; - case RBDT_DIRECTORY_DEPENDENCIES: - return `directory dependencies ${job.path}`; - case RBDT_FILE_DEPENDENCIES: - return `file dependencies ${job.path}`; + + for (const chunk of this.chunks) { + for (const file of chunk.files) { + files.add(file); } - return `unknown ${job.type} ${job.path}`; - }; - const pathToString = job => { - let result = ` at ${jobToString(job)}`; - job = job.issuer; - while (job !== undefined) { - result += `\n at ${jobToString(job)}`; - job = job.issuer; + } + + 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); } - return result; - }; - processAsyncTree( - Array.from(deps, dep => ({ - type: RBDT_RESOLVE_CJS, - context, - path: dep, - expected: undefined, - issuer: undefined - })), - 20, - (job, push, callback) => { - const { type, context, path, expected } = job; - const resolveDirectory = path => { - const key = `d\n${context}\n${path}`; - if (resolveResults.has(key)) { - return callback(); - } - resolveResults.set(key, undefined); - resolveContext(context, path, resolverContext, (err, _, result) => { - if (err) { - if (expected === false) { - resolveResults.set(key, false); - return callback(); - } - invalidResolveResults.add(key); - err.message += `\nwhile resolving '${path}' in ${context} to a directory`; - return callback(err); - } - const resultPath = result.path; - resolveResults.set(key, resultPath); - push({ - type: RBDT_DIRECTORY, - context: undefined, - path: resultPath, - expected: undefined, - issuer: job - }); - callback(); - }); - }; - const resolveFile = (path, symbol, resolve) => { - const key = `${symbol}\n${context}\n${path}`; - if (resolveResults.has(key)) { - return callback(); + } + + /** + * 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} mapping from children type to ordered list of ChunkGroups + */ + getChildrenByOrders(moduleGraph, chunkGraph) { + /** @type {Map} */ + 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 = [])); } - resolveResults.set(key, undefined); - resolve(context, path, resolverContext, (err, _, result) => { - if (typeof expected === "string") { - if (!err && result && result.path === expected) { - resolveResults.set(key, result.path); - } else { - invalidResolveResults.add(key); - this.logger.warn( - `Resolving '${path}' in ${context} for build dependencies doesn't lead to expected result '${expected}', but to '${ - err || (result && result.path) - }' instead. Resolving dependencies are ignored for this path.\n${pathToString( - job - )}` - ); - } - } else { - if (err) { - if (expected === false) { - resolveResults.set(key, false); - return callback(); - } - invalidResolveResults.add(key); - err.message += `\nwhile resolving '${path}' in ${context} as file\n${pathToString( - job - )}`; - return callback(err); - } - const resultPath = result.path; - resolveResults.set(key, resultPath); - push({ - type: RBDT_FILE, - context: undefined, - path: resultPath, - expected: undefined, - issuer: job - }); - } - callback(); + list.push({ + order: childGroup.options[key], + group: childGroup }); - }; - switch (type) { - case RBDT_RESOLVE_CJS: { - const isDirectory = /[\\/]$/.test(path); - if (isDirectory) { - resolveDirectory(path.slice(0, path.length - 1)); - } else { - resolveFile(path, "f", resolveCjs); - } - break; - } - case RBDT_RESOLVE_ESM: { - const isDirectory = /[\\/]$/.test(path); - if (isDirectory) { - resolveDirectory(path.slice(0, path.length - 1)); - } else { - resolveFile(path); - } - break; - } - case RBDT_RESOLVE_DIRECTORY: { - resolveDirectory(path); - break; - } - case RBDT_RESOLVE_CJS_FILE: { - resolveFile(path, "f", resolveCjs); - break; - } - case RBDT_RESOLVE_CJS_FILE_AS_CHILD: { - resolveFile(path, "c", resolveCjsAsChild); - break; - } - case RBDT_RESOLVE_ESM_FILE: { - resolveFile(path, "e", resolveEsm); - break; - } - case RBDT_FILE: { - if (files.has(path)) { - callback(); - break; - } - files.add(path); - this.fs.realpath(path, (err, _realPath) => { - if (err) return callback(err); - const realPath = /** @type {string} */ (_realPath); - if (realPath !== path) { - fileSymlinks.add(path); - resolveFiles.add(path); - if (files.has(realPath)) return callback(); - files.add(realPath); - } - push({ - type: RBDT_FILE_DEPENDENCIES, - context: undefined, - path: realPath, - expected: undefined, - issuer: job - }); - callback(); - }); - break; - } - case RBDT_DIRECTORY: { - if (directories.has(path)) { - callback(); - break; - } - directories.add(path); - this.fs.realpath(path, (err, _realPath) => { - if (err) return callback(err); - const realPath = /** @type {string} */ (_realPath); - if (realPath !== path) { - directorySymlinks.add(path); - resolveFiles.add(path); - if (directories.has(realPath)) return callback(); - directories.add(realPath); - } - push({ - type: RBDT_DIRECTORY_DEPENDENCIES, - context: undefined, - path: realPath, - expected: undefined, - issuer: job - }); - callback(); - }); - break; - } - case RBDT_FILE_DEPENDENCIES: { - // Check for known files without dependencies - if (/\.json5?$|\.yarn-integrity$|yarn\.lock$|\.ya?ml/.test(path)) { - process.nextTick(callback); - break; - } - // Check commonjs cache for the module - /** @type {NodeModule} */ - const module = require.cache[path]; - if (module && Array.isArray(module.children)) { - children: for (const child of module.children) { - let childPath = child.filename; - if (childPath) { - push({ - type: RBDT_FILE, - context: undefined, - path: childPath, - expected: undefined, - issuer: job - }); - const context = dirname(this.fs, path); - for (const modulePath of module.paths) { - if (childPath.startsWith(modulePath)) { - let subPath = childPath.slice(modulePath.length + 1); - const packageMatch = /^(@[^\\/]+[\\/])[^\\/]+/.exec( - subPath - ); - if (packageMatch) { - push({ - type: RBDT_FILE, - context: undefined, - path: - modulePath + - childPath[modulePath.length] + - packageMatch[0] + - childPath[modulePath.length] + - "package.json", - expected: false, - issuer: job - }); - } - let request = subPath.replace(/\\/g, "/"); - if (request.endsWith(".js")) - request = request.slice(0, -3); - push({ - type: RBDT_RESOLVE_CJS_FILE_AS_CHILD, - context, - path: request, - expected: child.filename, - issuer: job - }); - continue children; - } - } - let request = relative(this.fs, context, childPath); - if (request.endsWith(".js")) request = request.slice(0, -3); - request = request.replace(/\\/g, "/"); - if (!request.startsWith("../")) request = `./${request}`; - push({ - type: RBDT_RESOLVE_CJS_FILE, - context, - path: request, - expected: child.filename, - issuer: job - }); - } - } - } else if (supportsEsm && /\.m?js$/.test(path)) { - if (!this._warnAboutExperimentalEsmTracking) { - this.logger.log( - "Node.js doesn't offer a (nice) way to introspect the ESM dependency graph yet.\n" + - "Until a full solution is available webpack uses an experimental ESM tracking based on parsing.\n" + - "As best effort webpack parses the ESM files to guess dependencies. But this can lead to expensive and incorrect tracking." - ); - this._warnAboutExperimentalEsmTracking = true; - } - const lexer = __webpack_require__(54392); - lexer.init.then(() => { - this.fs.readFile(path, (err, content) => { - if (err) return callback(err); - try { - const context = dirname(this.fs, path); - const source = content.toString(); - const [imports] = lexer.parse(source); - for (const imp of imports) { - try { - let dependency; - if (imp.d === -1) { - // import ... from "..." - dependency = parseString( - source.substring(imp.s - 1, imp.e + 1) - ); - } else if (imp.d > -1) { - // import() - let expr = source.substring(imp.s, imp.e).trim(); - dependency = parseString(expr); - } else { - // e.g. import.meta - continue; - } - push({ - type: RBDT_RESOLVE_ESM_FILE, - context, - path: dependency, - expected: undefined, - issuer: job - }); - } catch (e) { - this.logger.warn( - `Parsing of ${path} for build dependencies failed at 'import(${source.substring( - imp.s, - imp.e - )})'.\n` + - "Build dependencies behind this expression are ignored and might cause incorrect cache invalidation." - ); - this.logger.debug(pathToString(job)); - this.logger.debug(e.stack); - } - } - } catch (e) { - this.logger.warn( - `Parsing of ${path} for build dependencies failed and all dependencies of this file are ignored, which might cause incorrect cache invalidation..` - ); - this.logger.debug(pathToString(job)); - this.logger.debug(e.stack); - } - process.nextTick(callback); - }); - }, callback); - break; - } else { - this.logger.log( - `Assuming ${path} has no dependencies as we were unable to assign it to any module system.` - ); - this.logger.debug(pathToString(job)); - } - process.nextTick(callback); - break; - } - case RBDT_DIRECTORY_DEPENDENCIES: { - const match = - /(^.+[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+)/.exec(path); - const packagePath = match ? match[1] : path; - const packageJson = join(this.fs, packagePath, "package.json"); - this.fs.readFile(packageJson, (err, content) => { - if (err) { - if (err.code === "ENOENT") { - resolveMissing.add(packageJson); - const parent = dirname(this.fs, packagePath); - if (parent !== packagePath) { - push({ - type: RBDT_DIRECTORY_DEPENDENCIES, - context: undefined, - path: parent, - expected: undefined, - issuer: job - }); - } - callback(); - return; - } - return callback(err); - } - resolveFiles.add(packageJson); - let packageData; - try { - packageData = JSON.parse(content.toString("utf-8")); - } catch (e) { - return callback(e); - } - const depsObject = packageData.dependencies; - const optionalDepsObject = packageData.optionalDependencies; - const allDeps = new Set(); - const optionalDeps = new Set(); - if (typeof depsObject === "object" && depsObject) { - for (const dep of Object.keys(depsObject)) { - allDeps.add(dep); - } - } - if ( - typeof optionalDepsObject === "object" && - optionalDepsObject - ) { - for (const dep of Object.keys(optionalDepsObject)) { - allDeps.add(dep); - optionalDeps.add(dep); - } - } - for (const dep of allDeps) { - push({ - type: RBDT_RESOLVE_DIRECTORY, - context: packagePath, - path: dep, - expected: !optionalDeps.has(dep), - issuer: job - }); - } - callback(); - }); - break; - } } - }, - err => { - if (err) return callback(err); - for (const l of fileSymlinks) files.delete(l); - for (const l of directorySymlinks) directories.delete(l); - for (const k of invalidResolveResults) resolveResults.delete(k); - callback(null, { - files, - directories, - missing, - resolveResults, - resolveDependencies: { - files: resolveFiles, - directories: resolveDirectories, - missing: resolveMissing - } - }); } - ); + } + /** @type {Record} */ + 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; } /** - * @param {Map} resolveResults results from resolving - * @param {function((Error | null)=, boolean=): void} callback callback with true when resolveResults resolve the same way + * 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} */ - checkResolveResultsValid(resolveResults, callback) { - const { resolveCjs, resolveCjsAsChild, resolveEsm, resolveContext } = - this._createBuildDependenciesResolvers(); - asyncLib.eachLimit( - resolveResults, - 20, - ([key, expectedResult], callback) => { - const [type, context, path] = key.split("\n"); - switch (type) { - case "d": - resolveContext(context, path, {}, (err, _, result) => { - if (expectedResult === false) - return callback(err ? undefined : INVALID); - if (err) return callback(err); - const resultPath = result.path; - if (resultPath !== expectedResult) return callback(INVALID); - callback(); - }); - break; - case "f": - resolveCjs(context, path, {}, (err, _, result) => { - if (expectedResult === false) - return callback(err ? undefined : INVALID); - if (err) return callback(err); - const resultPath = result.path; - if (resultPath !== expectedResult) return callback(INVALID); - callback(); - }); - break; - case "c": - resolveCjsAsChild(context, path, {}, (err, _, result) => { - if (expectedResult === false) - return callback(err ? undefined : INVALID); - if (err) return callback(err); - const resultPath = result.path; - if (resultPath !== expectedResult) return callback(INVALID); - callback(); - }); - break; - case "e": - resolveEsm(context, path, {}, (err, _, result) => { - if (expectedResult === false) - return callback(err ? undefined : INVALID); - if (err) return callback(err); - const resultPath = result.path; - if (resultPath !== expectedResult) return callback(INVALID); - callback(); - }); - break; - default: - callback(new Error("Unexpected type in resolve result key")); - break; - } - }, - /** - * @param {Error | typeof INVALID=} err error or invalid flag - * @returns {void} - */ - err => { - if (err === INVALID) { - return callback(null, false); - } - if (err) { - return callback(err); - } - return callback(null, true); - } - ); + setModulePreOrderIndex(module, index) { + this._modulePreOrderIndices.set(module, index); } /** - * - * @param {number} startTime when processing the files has started - * @param {Iterable} files all files - * @param {Iterable} directories all directories - * @param {Iterable} missing all missing files or directories - * @param {Object} options options object (for future extensions) - * @param {boolean=} options.hash should use hash to snapshot - * @param {boolean=} options.timestamp should use timestamp to snapshot - * @param {function((WebpackError | null)=, (Snapshot | null)=): void} callback callback function + * 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} */ - createSnapshot(startTime, files, directories, missing, options, callback) { - /** @type {Map} */ - const fileTimestamps = new Map(); - /** @type {Map} */ - const fileHashes = new Map(); - /** @type {Map} */ - const fileTshs = new Map(); - /** @type {Map} */ - const contextTimestamps = new Map(); - /** @type {Map} */ - const contextHashes = new Map(); - /** @type {Map} */ - const contextTshs = new Map(); - /** @type {Map} */ - const missingExistence = new Map(); - /** @type {Map} */ - const managedItemInfo = new Map(); - /** @type {Set} */ - const managedFiles = new Set(); - /** @type {Set} */ - const managedContexts = new Set(); - /** @type {Set} */ - const managedMissing = new Set(); - /** @type {Set} */ - const children = new Set(); + setModulePostOrderIndex(module, index) { + this._modulePostOrderIndices.set(module, index); + } - const snapshot = new Snapshot(); - if (startTime) snapshot.setStartTime(startTime); + /** + * 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); + } - /** @type {Set} */ - const managedItems = new Set(); + /* 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}` + ); + } + } + } +} - /** 1 = timestamp, 2 = hash, 3 = timestamp + hash */ - const mode = options && options.hash ? (options.timestamp ? 3 : 2) : 1; +ChunkGroup.prototype.getModuleIndex = util.deprecate( + ChunkGroup.prototype.getModulePreOrderIndex, + "ChunkGroup.getModuleIndex was renamed to getModulePreOrderIndex", + "DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX" +); - let jobs = 1; - const jobDone = () => { - if (--jobs === 0) { - if (fileTimestamps.size !== 0) { - snapshot.setFileTimestamps(fileTimestamps); - } - if (fileHashes.size !== 0) { - snapshot.setFileHashes(fileHashes); - } - if (fileTshs.size !== 0) { - snapshot.setFileTshs(fileTshs); - } - if (contextTimestamps.size !== 0) { - snapshot.setContextTimestamps(contextTimestamps); - } - if (contextHashes.size !== 0) { - snapshot.setContextHashes(contextHashes); - } - if (contextTshs.size !== 0) { - snapshot.setContextTshs(contextTshs); - } - if (missingExistence.size !== 0) { - snapshot.setMissingExistence(missingExistence); - } - if (managedItemInfo.size !== 0) { - snapshot.setManagedItemInfo(managedItemInfo); - } - this._managedFilesOptimization.optimize(snapshot, managedFiles); - if (managedFiles.size !== 0) { - snapshot.setManagedFiles(managedFiles); - } - this._managedContextsOptimization.optimize(snapshot, managedContexts); - if (managedContexts.size !== 0) { - snapshot.setManagedContexts(managedContexts); - } - this._managedMissingOptimization.optimize(snapshot, managedMissing); - if (managedMissing.size !== 0) { - snapshot.setManagedMissing(managedMissing); - } - if (children.size !== 0) { - snapshot.setChildren(children); - } - this._snapshotCache.set(snapshot, true); - this._statCreatedSnapshots++; +ChunkGroup.prototype.getModuleIndex2 = util.deprecate( + ChunkGroup.prototype.getModulePostOrderIndex, + "ChunkGroup.getModuleIndex2 was renamed to getModulePostOrderIndex", + "DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX_2" +); - callback(null, snapshot); - } - }; - const jobError = () => { - if (jobs > 0) { - // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8) - jobs = -100000000; - callback(null, null); - } - }; - const checkManaged = (path, managedSet) => { - for (const immutablePath of this.immutablePathsRegExps) { - if (immutablePath.test(path)) { - managedSet.add(path); - return true; - } - } - for (const immutablePath of this.immutablePathsWithSlash) { - if (path.startsWith(immutablePath)) { - managedSet.add(path); - return true; - } - } - for (const managedPath of this.managedPathsRegExps) { - const match = managedPath.exec(path); - if (match) { - const managedItem = getManagedItem(match[1], path); - if (managedItem) { - managedItems.add(managedItem); - managedSet.add(path); - return true; - } - } - } - for (const managedPath of this.managedPathsWithSlash) { - if (path.startsWith(managedPath)) { - const managedItem = getManagedItem(managedPath, path); - if (managedItem) { - managedItems.add(managedItem); - managedSet.add(path); - return true; - } - } - } - return false; - }; - const captureNonManaged = (items, managedSet) => { - const capturedItems = new Set(); - for (const path of items) { - if (!checkManaged(path, managedSet)) capturedItems.add(path); - } - return capturedItems; - }; - const processCapturedFiles = capturedFiles => { - switch (mode) { - case 3: - this._fileTshsOptimization.optimize(snapshot, capturedFiles); - for (const path of capturedFiles) { - const cache = this._fileTshs.get(path); - if (cache !== undefined) { - fileTshs.set(path, cache); - } else { - jobs++; - this._getFileTimestampAndHash(path, (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting file timestamp hash combination of ${path}: ${err.stack}` - ); - } - jobError(); - } else { - fileTshs.set(path, entry); - jobDone(); - } - }); - } - } - break; - case 2: - this._fileHashesOptimization.optimize(snapshot, capturedFiles); - for (const path of capturedFiles) { - const cache = this._fileHashes.get(path); - if (cache !== undefined) { - fileHashes.set(path, cache); - } else { - jobs++; - this.fileHashQueue.add(path, (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting file hash of ${path}: ${err.stack}` - ); - } - jobError(); - } else { - fileHashes.set(path, entry); - jobDone(); - } - }); - } - } - break; - case 1: - this._fileTimestampsOptimization.optimize(snapshot, capturedFiles); - for (const path of capturedFiles) { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) { - if (cache !== "ignore") { - fileTimestamps.set(path, cache); +module.exports = ChunkGroup; + + +/***/ }), + +/***/ 918: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const WebpackError = __webpack_require__(53799); + +/** @typedef {import("./Chunk")} Chunk */ + +class ChunkRenderError extends WebpackError { + /** + * Create a new ChunkRenderError + * @param {Chunk} chunk A chunk + * @param {string} file Related file + * @param {Error} error Original error + */ + constructor(chunk, file, error) { + super(); + + this.name = "ChunkRenderError"; + this.error = error; + this.message = error.message; + this.details = error.stack; + this.file = file; + this.chunk = chunk; + } +} + +module.exports = ChunkRenderError; + + +/***/ }), + +/***/ 46341: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const util = __webpack_require__(73837); +const memoize = __webpack_require__(78676); + +/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */ +/** @typedef {import("./Compilation")} Compilation */ + +const getJavascriptModulesPlugin = memoize(() => + __webpack_require__(89464) +); + +// 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); } - } else { - jobs++; - this.fileTimestampQueue.add(path, (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting file timestamp of ${path}: ${err.stack}` - ); - } - jobError(); - } else { - fileTimestamps.set(path, entry); - jobDone(); + ); + }, + "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); }); - } - } - break; + }, + "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; + + +/***/ }), + +/***/ 31085: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + + + +const asyncLib = __webpack_require__(78175); +const { SyncBailHook } = __webpack_require__(41242); +const Compilation = __webpack_require__(85720); +const createSchemaValidation = __webpack_require__(32540); +const { join } = __webpack_require__(17139); +const processAsyncTree = __webpack_require__(42791); + +/** @typedef {import("../declarations/WebpackOptions").CleanOptions} CleanOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./logging/Logger").Logger} Logger */ +/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ +/** @typedef {import("./util/fs").StatsCallback} StatsCallback */ + +/** @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 validate = createSchemaValidation( + undefined, + () => { + const { definitions } = __webpack_require__(73342); + return { + definitions, + oneOf: [{ $ref: "#/definitions/CleanOptions" }] }; - if (files) { - processCapturedFiles(captureNonManaged(files, managedFiles)); + }, + { + name: "Clean Plugin", + baseDataPath: "options" + } +); + +/** + * @param {OutputFileSystem} fs filesystem + * @param {string} outputPath output path + * @param {Set} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator) + * @param {function((Error | null)=, Set=): 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); } - const processCapturedDirectories = capturedDirectories => { - switch (mode) { - case 3: - this._contextTshsOptimization.optimize(snapshot, capturedDirectories); - for (const path of capturedDirectories) { - const cache = this._contextTshs.get(path); - /** @type {ResolvedContextTimestampAndHash} */ - let resolved; - if ( - cache !== undefined && - (resolved = getResolvedTimestamp(cache)) !== undefined - ) { - contextTshs.set(path, resolved); - } else { - jobs++; - /** - * @param {Error=} err error - * @param {ResolvedContextTimestampAndHash=} entry entry - * @returns {void} - */ - const callback = (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting context timestamp hash combination of ${path}: ${err.stack}` - ); - } - jobError(); - } else { - contextTshs.set(path, entry); - jobDone(); - } + ); +}; + +/** + * @param {Set} currentAssets assets list + * @param {Set} oldAssets old assets list + * @returns {Set} 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} filename path to file + * @param {StatsCallback} callback callback for provided filename + * @returns {void} + */ +const doStat = (fs, filename, callback) => { + if ("lstat" in fs) { + fs.lstat(filename, callback); + } else { + fs.stat(filename, callback); + } +}; + +/** + * @param {OutputFileSystem} fs filesystem + * @param {string} outputPath output path + * @param {boolean} dry only log instead of fs modification + * @param {Logger} logger logger + * @param {Set} 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); + } + doStat(fs, 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 (cache !== undefined) { - this._resolveContextTsh(cache, callback); + if (entries.length === 0) { + push(deleteJob); } else { - this.getContextTsh(path, callback); - } - } - } - break; - case 2: - this._contextHashesOptimization.optimize( - snapshot, - capturedDirectories - ); - for (const path of capturedDirectories) { - const cache = this._contextHashes.get(path); - let resolved; - if ( - cache !== undefined && - (resolved = getResolvedHash(cache)) !== undefined - ) { - contextHashes.set(path, resolved); - } else { - jobs++; - const callback = (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting context hash of ${path}: ${err.stack}` + 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; } - jobError(); - } else { - contextHashes.set(path, entry); - jobDone(); + push({ + type: "check", + filename: `${filename}/${file}`, + parent: parentToken + }); } - }; - if (cache !== undefined) { - this._resolveContextHash(cache, callback); - } else { - this.getContextHash(path, callback); } - } + 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 1: - this._contextTimestampsOptimization.optimize( - snapshot, - capturedDirectories - ); - for (const path of capturedDirectories) { - const cache = this._contextTimestamps.get(path); - if (cache === "ignore") continue; - let resolved; - if ( - cache !== undefined && - (resolved = getResolvedTimestamp(cache)) !== undefined - ) { - contextTimestamps.set(path, resolved); - } else { - jobs++; - /** - * @param {Error=} err error - * @param {ResolvedContextFileSystemInfoEntry=} entry entry - * @returns {void} - */ - const callback = (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting context timestamp of ${path}: ${err.stack}` - ); - } - jobError(); - } else { - contextTimestamps.set(path, entry); - jobDone(); - } - }; - if (cache !== undefined) { - this._resolveContextTimestamp(cache, callback); - } else { - this.getContextTimestamp(path, callback); - } - } + 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; } - }; - if (directories) { - processCapturedDirectories( - captureNonManaged(directories, managedContexts) + }, + callback + ); +}; + +/** @type {WeakMap} */ +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" ); } - const processCapturedMissing = capturedMissing => { - this._missingExistenceOptimization.optimize(snapshot, capturedMissing); - for (const path of capturedMissing) { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) { - if (cache !== "ignore") { - missingExistence.set(path, Boolean(cache)); + 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(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); } - } else { - jobs++; - this.fileTimestampQueue.add(path, (err, entry) => { + applyDiff(fs, outputPath, dry, logger, diff, isKept, err => { if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting missing timestamp of ${path}: ${err.stack}` - ); - } - jobError(); + oldAssets = undefined; } else { - missingExistence.set(path, Boolean(entry)); - jobDone(); + oldAssets = currentAssets; } + callback(err); }); + }; + + if (oldAssets) { + diffCallback(null, getDiffToOldAssets(currentAssets, oldAssets)); + } else { + getDiffToFs(fs, outputPath, currentAssets, diffCallback); } } - }; - if (missing) { - processCapturedMissing(captureNonManaged(missing, managedMissing)); - } - this._managedItemInfoOptimization.optimize(snapshot, managedItems); - for (const path of managedItems) { - const cache = this._managedItems.get(path); - if (cache !== undefined) { - if (!cache.startsWith("*")) { - managedFiles.add(join(this.fs, path, "package.json")); - } else if (cache === "*nested") { - managedMissing.add(join(this.fs, path, "package.json")); - } - managedItemInfo.set(path, cache); - } else { - jobs++; - this.managedItemQueue.add(path, (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting managed item ${path}: ${err.stack}` - ); - } - jobError(); - } else if (entry) { - if (!entry.startsWith("*")) { - managedFiles.add(join(this.fs, path, "package.json")); - } else if (cache === "*nested") { - managedMissing.add(join(this.fs, path, "package.json")); - } - managedItemInfo.set(path, entry); - jobDone(); - } else { - // Fallback to normal snapshotting - const process = (set, fn) => { - if (set.size === 0) return; - const captured = new Set(); - for (const file of set) { - if (file.startsWith(path)) captured.add(file); - } - if (captured.size > 0) fn(captured); - }; - process(managedFiles, processCapturedFiles); - process(managedContexts, processCapturedDirectories); - process(managedMissing, processCapturedMissing); - jobDone(); - } - }); - } - } - jobDone(); + ); } +} + +module.exports = CleanPlugin; + +/***/ }), + +/***/ 2102: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const WebpackError = __webpack_require__(53799); + +/** @typedef {import("./Module")} Module */ + +class CodeGenerationError extends WebpackError { /** - * @param {Snapshot} snapshot1 a snapshot - * @param {Snapshot} snapshot2 a snapshot - * @returns {Snapshot} merged snapshot + * Create a new CodeGenerationError + * @param {Module} module related module + * @param {Error} error Original error */ - mergeSnapshots(snapshot1, snapshot2) { - const snapshot = new Snapshot(); - if (snapshot1.hasStartTime() && snapshot2.hasStartTime()) - snapshot.setStartTime(Math.min(snapshot1.startTime, snapshot2.startTime)); - else if (snapshot2.hasStartTime()) snapshot.startTime = snapshot2.startTime; - else if (snapshot1.hasStartTime()) snapshot.startTime = snapshot1.startTime; - if (snapshot1.hasFileTimestamps() || snapshot2.hasFileTimestamps()) { - snapshot.setFileTimestamps( - mergeMaps(snapshot1.fileTimestamps, snapshot2.fileTimestamps) - ); - } - if (snapshot1.hasFileHashes() || snapshot2.hasFileHashes()) { - snapshot.setFileHashes( - mergeMaps(snapshot1.fileHashes, snapshot2.fileHashes) - ); - } - if (snapshot1.hasFileTshs() || snapshot2.hasFileTshs()) { - snapshot.setFileTshs(mergeMaps(snapshot1.fileTshs, snapshot2.fileTshs)); - } - if (snapshot1.hasContextTimestamps() || snapshot2.hasContextTimestamps()) { - snapshot.setContextTimestamps( - mergeMaps(snapshot1.contextTimestamps, snapshot2.contextTimestamps) - ); - } - if (snapshot1.hasContextHashes() || snapshot2.hasContextHashes()) { - snapshot.setContextHashes( - mergeMaps(snapshot1.contextHashes, snapshot2.contextHashes) - ); - } - if (snapshot1.hasContextTshs() || snapshot2.hasContextTshs()) { - snapshot.setContextTshs( - mergeMaps(snapshot1.contextTshs, snapshot2.contextTshs) - ); - } - if (snapshot1.hasMissingExistence() || snapshot2.hasMissingExistence()) { - snapshot.setMissingExistence( - mergeMaps(snapshot1.missingExistence, snapshot2.missingExistence) - ); - } - if (snapshot1.hasManagedItemInfo() || snapshot2.hasManagedItemInfo()) { - snapshot.setManagedItemInfo( - mergeMaps(snapshot1.managedItemInfo, snapshot2.managedItemInfo) - ); - } - if (snapshot1.hasManagedFiles() || snapshot2.hasManagedFiles()) { - snapshot.setManagedFiles( - mergeSets(snapshot1.managedFiles, snapshot2.managedFiles) + constructor(module, error) { + super(); + + this.name = "CodeGenerationError"; + this.error = error; + this.message = error.message; + this.details = error.stack; + this.module = module; + } +} + +module.exports = CodeGenerationError; + + +/***/ }), + +/***/ 71426: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { provide } = __webpack_require__(82482); +const { first } = __webpack_require__(93347); +const createHash = __webpack_require__(49835); +const { runtimeToString, RuntimeSpecMap } = __webpack_require__(17156); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {typeof import("./util/Hash")} Hash */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +class CodeGenerationResults { + /** + * @param {string | Hash} hashFunction the hash function to use + */ + constructor(hashFunction = "md4") { + /** @type {Map>} */ + this.map = new Map(); + this._hashFunction = hashFunction; + } + + /** + * @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 (snapshot1.hasManagedContexts() || snapshot2.hasManagedContexts()) { - snapshot.setManagedContexts( - mergeSets(snapshot1.managedContexts, snapshot2.managedContexts) - ); + 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; } - if (snapshot1.hasManagedMissing() || snapshot2.hasManagedMissing()) { - snapshot.setManagedMissing( - mergeSets(snapshot1.managedMissing, snapshot2.managedMissing) + 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(", ")})` ); } - if (snapshot1.hasChildren() || snapshot2.hasChildren()) { - snapshot.setChildren(mergeSets(snapshot1.children, snapshot2.children)); + 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 ( - this._snapshotCache.get(snapshot1) === true && - this._snapshotCache.get(snapshot2) === true - ) { - this._snapshotCache.set(snapshot, true); + 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; } - return snapshot; } /** - * @param {Snapshot} snapshot the snapshot made - * @param {function((WebpackError | null)=, boolean=): void} callback callback function - * @returns {void} + * @param {Module} module the module + * @param {RuntimeSpec} runtime runtime(s) + * @param {string} sourceType the source type + * @returns {Source} a source */ - checkSnapshotValid(snapshot, callback) { - const cachedResult = this._snapshotCache.get(snapshot); - if (cachedResult !== undefined) { - this._statTestedSnapshotsCached++; - if (typeof cachedResult === "boolean") { - callback(null, cachedResult); - } else { - cachedResult.push(callback); - } - return; - } - this._statTestedSnapshotsNotCached++; - this._checkSnapshotValidNoCache(snapshot, callback); + getSource(module, runtime, sourceType) { + return this.get(module, runtime).sources.get(sourceType); } /** - * @param {Snapshot} snapshot the snapshot made - * @param {function((WebpackError | null)=, boolean=): void} callback callback function - * @returns {void} + * @param {Module} module the module + * @param {RuntimeSpec} runtime runtime(s) + * @returns {ReadonlySet} runtime requirements */ - _checkSnapshotValidNoCache(snapshot, callback) { - /** @type {number | undefined} */ - let startTime = undefined; - if (snapshot.hasStartTime()) { - startTime = snapshot.startTime; - } - let jobs = 1; - const jobDone = () => { - if (--jobs === 0) { - this._snapshotCache.set(snapshot, true); - callback(null, true); - } - }; - const invalid = () => { - if (jobs > 0) { - // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8) - jobs = -100000000; - this._snapshotCache.set(snapshot, false); - callback(null, false); - } - }; - const invalidWithError = (path, err) => { - if (this._remainingLogs > 0) { - this._log(path, `error occurred: %s`, err); - } - invalid(); - }; - /** - * @param {string} path file path - * @param {string} current current hash - * @param {string} snap snapshot hash - * @returns {boolean} true, if ok - */ - const checkHash = (path, current, snap) => { - if (current !== snap) { - // If hash differ it's invalid - if (this._remainingLogs > 0) { - this._log(path, `hashes differ (%s != %s)`, current, snap); - } - return false; - } - return true; - }; - /** - * @param {string} path file path - * @param {boolean} current current entry - * @param {boolean} snap entry from snapshot - * @returns {boolean} true, if ok - */ - const checkExistence = (path, current, snap) => { - if (!current !== !snap) { - // If existence of item differs - // it's invalid - if (this._remainingLogs > 0) { - this._log( - path, - current ? "it didn't exist before" : "it does no longer exist" - ); - } - return false; - } - return true; - }; - /** - * @param {string} path file path - * @param {FileSystemInfoEntry} current current entry - * @param {FileSystemInfoEntry} snap entry from snapshot - * @param {boolean} log log reason - * @returns {boolean} true, if ok - */ - const checkFile = (path, current, snap, log = true) => { - if (current === snap) return true; - if (!checkExistence(path, Boolean(current), Boolean(snap))) return false; - if (current) { - // For existing items only - if (typeof startTime === "number" && current.safeTime > startTime) { - // If a change happened after starting reading the item - // this may no longer be valid - if (log && this._remainingLogs > 0) { - this._log( - path, - `it may have changed (%d) after the start time of the snapshot (%d)`, - current.safeTime, - startTime - ); - } - return false; - } - if ( - snap.timestamp !== undefined && - current.timestamp !== snap.timestamp - ) { - // If we have a timestamp (it was a file or symlink) and it differs from current timestamp - // it's invalid - if (log && this._remainingLogs > 0) { - this._log( - path, - `timestamps differ (%d != %d)`, - current.timestamp, - snap.timestamp - ); - } - return false; - } - } - return true; - }; - /** - * @param {string} path file path - * @param {ResolvedContextFileSystemInfoEntry} current current entry - * @param {ResolvedContextFileSystemInfoEntry} snap entry from snapshot - * @param {boolean} log log reason - * @returns {boolean} true, if ok - */ - const checkContext = (path, current, snap, log = true) => { - if (current === snap) return true; - if (!checkExistence(path, Boolean(current), Boolean(snap))) return false; - if (current) { - // For existing items only - if (typeof startTime === "number" && current.safeTime > startTime) { - // If a change happened after starting reading the item - // this may no longer be valid - if (log && this._remainingLogs > 0) { - this._log( - path, - `it may have changed (%d) after the start time of the snapshot (%d)`, - current.safeTime, - startTime - ); - } - return false; - } - if ( - snap.timestampHash !== undefined && - current.timestampHash !== snap.timestampHash - ) { - // If we have a timestampHash (it was a directory) and it differs from current timestampHash - // it's invalid - if (log && this._remainingLogs > 0) { - this._log( - path, - `timestamps hashes differ (%s != %s)`, - current.timestampHash, - snap.timestampHash - ); - } - return false; - } - } - return true; - }; - if (snapshot.hasChildren()) { - const childCallback = (err, result) => { - if (err || !result) return invalid(); - else jobDone(); - }; - for (const child of snapshot.children) { - const cache = this._snapshotCache.get(child); - if (cache !== undefined) { - this._statTestedChildrenCached++; - /* istanbul ignore else */ - if (typeof cache === "boolean") { - if (cache === false) { - invalid(); - return; - } - } else { - jobs++; - cache.push(childCallback); - } - } else { - this._statTestedChildrenNotCached++; - jobs++; - this._checkSnapshotValidNoCache(child, childCallback); - } - } - } - if (snapshot.hasFileTimestamps()) { - const { fileTimestamps } = snapshot; - this._statTestedEntries += fileTimestamps.size; - for (const [path, ts] of fileTimestamps) { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) { - if (cache !== "ignore" && !checkFile(path, cache, ts)) { - invalid(); - return; - } - } else { - jobs++; - this.fileTimestampQueue.add(path, (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkFile(path, entry, ts)) { - invalid(); - } else { - jobDone(); - } - }); - } - } - } - const processFileHashSnapshot = (path, hash) => { - const cache = this._fileHashes.get(path); - if (cache !== undefined) { - if (cache !== "ignore" && !checkHash(path, cache, hash)) { - invalid(); - return; - } - } else { - jobs++; - this.fileHashQueue.add(path, (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkHash(path, entry, hash)) { - invalid(); - } else { - jobDone(); - } - }); - } - }; - if (snapshot.hasFileHashes()) { - const { fileHashes } = snapshot; - this._statTestedEntries += fileHashes.size; - for (const [path, hash] of fileHashes) { - processFileHashSnapshot(path, hash); - } - } - if (snapshot.hasFileTshs()) { - const { fileTshs } = snapshot; - this._statTestedEntries += fileTshs.size; - for (const [path, tsh] of fileTshs) { - if (typeof tsh === "string") { - processFileHashSnapshot(path, tsh); - } else { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) { - if (cache === "ignore" || !checkFile(path, cache, tsh, false)) { - processFileHashSnapshot(path, tsh && tsh.hash); - } - } else { - jobs++; - this.fileTimestampQueue.add(path, (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkFile(path, entry, tsh, false)) { - processFileHashSnapshot(path, tsh && tsh.hash); - } - jobDone(); - }); - } - } - } - } - if (snapshot.hasContextTimestamps()) { - const { contextTimestamps } = snapshot; - this._statTestedEntries += contextTimestamps.size; - for (const [path, ts] of contextTimestamps) { - const cache = this._contextTimestamps.get(path); - if (cache === "ignore") continue; - let resolved; - if ( - cache !== undefined && - (resolved = getResolvedTimestamp(cache)) !== undefined - ) { - if (!checkContext(path, resolved, ts)) { - invalid(); - return; - } - } else { - jobs++; - /** - * @param {Error=} err error - * @param {ResolvedContextFileSystemInfoEntry=} entry entry - * @returns {void} - */ - const callback = (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkContext(path, entry, ts)) { - invalid(); - } else { - jobDone(); - } - }; - if (cache !== undefined) { - this._resolveContextTimestamp(cache, callback); - } else { - this.getContextTimestamp(path, callback); - } - } - } - } - const processContextHashSnapshot = (path, hash) => { - const cache = this._contextHashes.get(path); - let resolved; - if ( - cache !== undefined && - (resolved = getResolvedHash(cache)) !== undefined - ) { - if (!checkHash(path, resolved, hash)) { - invalid(); - return; - } - } else { - jobs++; - const callback = (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkHash(path, entry, hash)) { - invalid(); - } else { - jobDone(); - } - }; - if (cache !== undefined) { - this._resolveContextHash(cache, callback); - } else { - this.getContextHash(path, callback); - } - } - }; - if (snapshot.hasContextHashes()) { - const { contextHashes } = snapshot; - this._statTestedEntries += contextHashes.size; - for (const [path, hash] of contextHashes) { - processContextHashSnapshot(path, hash); - } - } - if (snapshot.hasContextTshs()) { - const { contextTshs } = snapshot; - this._statTestedEntries += contextTshs.size; - for (const [path, tsh] of contextTshs) { - if (typeof tsh === "string") { - processContextHashSnapshot(path, tsh); - } else { - const cache = this._contextTimestamps.get(path); - if (cache === "ignore") continue; - let resolved; - if ( - cache !== undefined && - (resolved = getResolvedTimestamp(cache)) !== undefined - ) { - if (!checkContext(path, resolved, tsh, false)) { - processContextHashSnapshot(path, tsh && tsh.hash); - } - } else { - jobs++; - /** - * @param {Error=} err error - * @param {ResolvedContextFileSystemInfoEntry=} entry entry - * @returns {void} - */ - const callback = (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkContext(path, entry, tsh, false)) { - processContextHashSnapshot(path, tsh && tsh.hash); - } - jobDone(); - }; - if (cache !== undefined) { - this._resolveContextTimestamp(cache, callback); - } else { - this.getContextTimestamp(path, callback); - } - } - } - } - } - if (snapshot.hasMissingExistence()) { - const { missingExistence } = snapshot; - this._statTestedEntries += missingExistence.size; - for (const [path, existence] of missingExistence) { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) { - if ( - cache !== "ignore" && - !checkExistence(path, Boolean(cache), Boolean(existence)) - ) { - invalid(); - return; - } - } else { - jobs++; - this.fileTimestampQueue.add(path, (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkExistence(path, Boolean(entry), Boolean(existence))) { - invalid(); - } else { - jobDone(); - } - }); - } - } - } - if (snapshot.hasManagedItemInfo()) { - const { managedItemInfo } = snapshot; - this._statTestedEntries += managedItemInfo.size; - for (const [path, info] of managedItemInfo) { - const cache = this._managedItems.get(path); - if (cache !== undefined) { - if (!checkHash(path, cache, info)) { - invalid(); - return; - } - } else { - jobs++; - this.managedItemQueue.add(path, (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkHash(path, entry, info)) { - invalid(); - } else { - jobDone(); - } - }); - } - } - } - jobDone(); - - // if there was an async action - // try to join multiple concurrent request for this snapshot - if (jobs > 0) { - const callbacks = [callback]; - callback = (err, result) => { - for (const callback of callbacks) callback(err, result); - }; - this._snapshotCache.set(snapshot, callbacks); - } + getRuntimeRequirements(module, runtime) { + return this.get(module, runtime).runtimeRequirements; } - _readFileTimestamp(path, callback) { - this.fs.stat(path, (err, stat) => { - if (err) { - if (err.code === "ENOENT") { - this._fileTimestamps.set(path, null); - this._cachedDeprecatedFileTimestamps = undefined; - return callback(null, null); - } - return callback(err); - } - - let ts; - if (stat.isDirectory()) { - ts = { - safeTime: 0, - timestamp: undefined - }; - } else { - const mtime = +stat.mtime; - - if (mtime) applyMtime(mtime); - - ts = { - safeTime: mtime ? mtime + FS_ACCURACY : Infinity, - timestamp: mtime - }; - } + /** + * @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); + } - this._fileTimestamps.set(path, ts); - this._cachedDeprecatedFileTimestamps = undefined; + /** + * @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(this._hashFunction); + 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"))); + } - callback(null, ts); - }); + /** + * @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); } +} - _readFileHash(path, callback) { - this.fs.readFile(path, (err, content) => { - if (err) { - if (err.code === "EISDIR") { - this._fileHashes.set(path, "directory"); - return callback(null, "directory"); - } - if (err.code === "ENOENT") { - this._fileHashes.set(path, null); - return callback(null, null); - } - if (err.code === "ERR_FS_FILE_TOO_LARGE") { - this.logger.warn(`Ignoring ${path} for hashing as it's very large`); - this._fileHashes.set(path, "too large"); - return callback(null, "too large"); - } - return callback(err); - } +module.exports = CodeGenerationResults; - const hash = createHash(this._hashFunction); - hash.update(content); +/***/ }), - const digest = /** @type {string} */ (hash.digest("hex")); +/***/ 98427: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - this._fileHashes.set(path, digest); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - callback(null, digest); - }); - } - _getFileTimestampAndHash(path, callback) { - const continueWithHash = hash => { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) { - if (cache !== "ignore") { - const result = { - ...cache, - hash - }; - this._fileTshs.set(path, result); - return callback(null, result); - } else { - this._fileTshs.set(path, hash); - return callback(null, hash); - } - } else { - this.fileTimestampQueue.add(path, (err, entry) => { - if (err) { - return callback(err); - } - const result = { - ...entry, - hash - }; - this._fileTshs.set(path, result); - return callback(null, result); - }); - } - }; - const cache = this._fileHashes.get(path); - if (cache !== undefined) { - continueWithHash(cache); - } else { - this.fileHashQueue.add(path, (err, entry) => { - if (err) { - return callback(err); - } - continueWithHash(entry); - }); - } - } +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +class CommentCompilationWarning extends WebpackError { /** - * @template T - * @template ItemType - * @param {Object} options options - * @param {string} options.path path - * @param {function(string): ItemType} options.fromImmutablePath called when context item is an immutable path - * @param {function(string): ItemType} options.fromManagedItem called when context item is a managed path - * @param {function(string, string, function(Error=, ItemType=): void): void} options.fromSymlink called when context item is a symlink - * @param {function(string, IStats, function(Error=, ItemType=): void): void} options.fromFile called when context item is a file - * @param {function(string, IStats, function(Error=, ItemType=): void): void} options.fromDirectory called when context item is a directory - * @param {function(string[], ItemType[]): T} options.reduce called from all context items - * @param {function((Error | null)=, (T)=): void} callback callback + * + * @param {string} message warning message + * @param {DependencyLocation} loc affected lines of code */ - _readContext( - { - path, - fromImmutablePath, - fromManagedItem, - fromSymlink, - fromFile, - fromDirectory, - reduce - }, - callback - ) { - this.fs.readdir(path, (err, _files) => { - if (err) { - if (err.code === "ENOENT") { - return callback(null, null); - } - return callback(err); - } - const files = /** @type {string[]} */ (_files) - .map(file => file.normalize("NFC")) - .filter(file => !/^\./.test(file)) - .sort(); - asyncLib.map( - files, - (file, callback) => { - const child = join(this.fs, path, file); - for (const immutablePath of this.immutablePathsRegExps) { - if (immutablePath.test(path)) { - // ignore any immutable path for timestamping - return callback(null, fromImmutablePath(path)); - } - } - for (const immutablePath of this.immutablePathsWithSlash) { - if (path.startsWith(immutablePath)) { - // ignore any immutable path for timestamping - return callback(null, fromImmutablePath(path)); - } - } - for (const managedPath of this.managedPathsRegExps) { - const match = managedPath.exec(path); - if (match) { - const managedItem = getManagedItem(match[1], path); - if (managedItem) { - // construct timestampHash from managed info - return this.managedItemQueue.add(managedItem, (err, info) => { - if (err) return callback(err); - return callback(null, fromManagedItem(info)); - }); - } - } - } - for (const managedPath of this.managedPathsWithSlash) { - if (path.startsWith(managedPath)) { - const managedItem = getManagedItem(managedPath, child); - if (managedItem) { - // construct timestampHash from managed info - return this.managedItemQueue.add(managedItem, (err, info) => { - if (err) return callback(err); - return callback(null, fromManagedItem(info)); - }); - } - } - } - - lstatReadlinkAbsolute(this.fs, child, (err, stat) => { - if (err) return callback(err); + constructor(message, loc) { + super(message); - if (typeof stat === "string") { - return fromSymlink(child, stat, callback); - } + this.name = "CommentCompilationWarning"; - if (stat.isFile()) { - return fromFile(child, stat, callback); - } - if (stat.isDirectory()) { - return fromDirectory(child, stat, callback); - } - callback(null, null); - }); - }, - (err, results) => { - if (err) return callback(err); - const result = reduce(files, results); - callback(null, result); - } - ); - }); + this.loc = loc; } +} - _readContextTimestamp(path, callback) { - this._readContext( - { - path, - fromImmutablePath: () => null, - fromManagedItem: info => ({ - safeTime: 0, - timestampHash: info - }), - fromSymlink: (file, target, callback) => { - callback(null, { - timestampHash: target, - symlinks: new Set([target]) - }); - }, - fromFile: (file, stat, callback) => { - // Prefer the cached value over our new stat to report consistent results - const cache = this._fileTimestamps.get(file); - if (cache !== undefined) - return callback(null, cache === "ignore" ? null : cache); +makeSerializable( + CommentCompilationWarning, + "webpack/lib/CommentCompilationWarning" +); - const mtime = +stat.mtime; +module.exports = CommentCompilationWarning; - if (mtime) applyMtime(mtime); - const ts = { - safeTime: mtime ? mtime + FS_ACCURACY : Infinity, - timestamp: mtime - }; +/***/ }), - this._fileTimestamps.set(file, ts); - this._cachedDeprecatedFileTimestamps = undefined; - callback(null, ts); - }, - fromDirectory: (directory, stat, callback) => { - this.contextTimestampQueue.increaseParallelism(); - this._getUnresolvedContextTimestamp(directory, (err, tsEntry) => { - this.contextTimestampQueue.decreaseParallelism(); - callback(err, tsEntry); - }); - }, - reduce: (files, tsEntries) => { - let symlinks = undefined; +/***/ 94258: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const hash = createHash(this._hashFunction); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - for (const file of files) hash.update(file); - let safeTime = 0; - for (const entry of tsEntries) { - if (!entry) { - hash.update("n"); - continue; - } - if (entry.timestamp) { - hash.update("f"); - hash.update(`${entry.timestamp}`); - } else if (entry.timestampHash) { - hash.update("d"); - hash.update(`${entry.timestampHash}`); - } - if (entry.symlinks !== undefined) { - if (symlinks === undefined) symlinks = new Set(); - addAll(entry.symlinks, symlinks); - } - if (entry.safeTime) { - safeTime = Math.max(safeTime, entry.safeTime); - } - } - const digest = /** @type {string} */ (hash.digest("hex")); - const result = { - safeTime, - timestampHash: digest - }; - if (symlinks) result.symlinks = symlinks; - return result; - } - }, - (err, result) => { - if (err) return callback(err); - this._contextTimestamps.set(path, result); - this._cachedDeprecatedContextTimestamps = undefined; +const ConstDependency = __webpack_require__(76911); - callback(null, result); - } - ); - } +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ + +const nestedWebpackRequireTag = Symbol("nested __webpack_require__"); +class CompatibilityPlugin { /** - * @param {ContextFileSystemInfoEntry} entry entry - * @param {function((Error | null)=, ResolvedContextFileSystemInfoEntry=): void} callback callback + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - _resolveContextTimestamp(entry, callback) { - const hashes = []; - let safeTime = 0; - processAsyncTree( - entry.symlinks, - 10, - (target, push, callback) => { - this._getUnresolvedContextTimestamp(target, (err, entry) => { - if (err) return callback(err); - if (entry && entry !== "ignore") { - hashes.push(entry.timestampHash); - if (entry.safeTime) { - safeTime = Math.max(safeTime, entry.safeTime); - } - if (entry.symlinks !== undefined) { - for (const target of entry.symlinks) push(target); - } - } - callback(); - }); - }, - err => { - if (err) return callback(err); - const hash = createHash(this._hashFunction); - hash.update(entry.timestampHash); - if (entry.safeTime) { - safeTime = Math.max(safeTime, entry.safeTime); - } - hashes.sort(); - for (const h of hashes) { - hash.update(h); - } - callback( - null, - (entry.resolved = { - safeTime, - timestampHash: /** @type {string} */ (hash.digest("hex")) - }) + apply(compiler) { + compiler.hooks.compilation.tap( + "CompatibilityPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() ); - } - ); - } - _readContextHash(path, callback) { - this._readContext( - { - path, - fromImmutablePath: () => "", - fromManagedItem: info => info || "", - fromSymlink: (file, target, callback) => { - callback(null, { - hash: target, - symlinks: new Set([target]) - }); - }, - fromFile: (file, stat, callback) => - this.getFileHash(file, (err, hash) => { - callback(err, hash || ""); - }), - fromDirectory: (directory, stat, callback) => { - this.contextHashQueue.increaseParallelism(); - this._getUnresolvedContextHash(directory, (err, hash) => { - this.contextHashQueue.decreaseParallelism(); - callback(err, hash || ""); + 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 {string[]} files files - * @param {(string | ContextHash)[]} fileHashes hashes - * @returns {ContextHash} reduced hash + * @param {JavascriptParser} parser the parser + * @returns {void} */ - reduce: (files, fileHashes) => { - let symlinks = undefined; - const hash = createHash(this._hashFunction); + const handler = parser => { + // Handle nested requires + 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; + }); - for (const file of files) hash.update(file); - for (const entry of fileHashes) { - if (typeof entry === "string") { - hash.update(entry); - } else { - hash.update(entry.hash); - if (entry.symlinks) { - if (symlinks === undefined) symlinks = new Set(); - addAll(entry.symlinks, symlinks); + // Handle hashbang + parser.hooks.program.tap( + "CompatibilityPlugin", + (program, comments) => { + if (comments.length === 0) return; + const c = comments[0]; + if (c.type === "Line" && c.range[0] === 0) { + if (parser.state.source.slice(0, 2).toString() !== "#!") return; + // this is a hashbang comment + const dep = new ConstDependency("//", 0); + dep.loc = c.loc; + parser.state.module.addPresentationalDependency(dep); } } - } + ); + }; - const result = { - hash: /** @type {string} */ (hash.digest("hex")) - }; - if (symlinks) result.symlinks = symlinks; - return result; - } - }, - (err, result) => { - if (err) return callback(err); - this._contextHashes.set(path, result); - return callback(null, result); + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CompatibilityPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("CompatibilityPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("CompatibilityPlugin", handler); } ); } - - /** - * @param {ContextHash} entry context hash - * @param {function((Error | null)=, string=): void} callback callback - * @returns {void} - */ - _resolveContextHash(entry, callback) { - const hashes = []; - processAsyncTree( - entry.symlinks, - 10, - (target, push, callback) => { - this._getUnresolvedContextHash(target, (err, hash) => { - if (err) return callback(err); - if (hash) { - hashes.push(hash.hash); - if (hash.symlinks !== undefined) { - for (const target of hash.symlinks) push(target); - } - } - callback(); - }); - }, - err => { - if (err) return callback(err); - const hash = createHash(this._hashFunction); - hash.update(entry.hash); - hashes.sort(); - for (const h of hashes) { - hash.update(h); - } - callback( - null, - (entry.resolved = /** @type {string} */ (hash.digest("hex"))) - ); - } - ); - } - - _readContextTimestampAndHash(path, callback) { - const finalize = (timestamp, hash) => { - const result = - timestamp === "ignore" - ? hash - : { - ...timestamp, - ...hash - }; - this._contextTshs.set(path, result); - callback(null, result); - }; - const cachedHash = this._contextHashes.get(path); - const cachedTimestamp = this._contextTimestamps.get(path); - if (cachedHash !== undefined) { - if (cachedTimestamp !== undefined) { - finalize(cachedTimestamp, cachedHash); - } else { - this.contextTimestampQueue.add(path, (err, entry) => { - if (err) return callback(err); - finalize(entry, cachedHash); - }); - } - } else { - if (cachedTimestamp !== undefined) { - this.contextHashQueue.add(path, (err, entry) => { - if (err) return callback(err); - finalize(cachedTimestamp, entry); - }); - } else { - this._readContext( - { - path, - fromImmutablePath: () => null, - fromManagedItem: info => ({ - safeTime: 0, - timestampHash: info, - hash: info || "" - }), - fromSymlink: (fle, target, callback) => { - callback(null, { - timestampHash: target, - hash: target, - symlinks: new Set([target]) - }); - }, - fromFile: (file, stat, callback) => { - this._getFileTimestampAndHash(file, callback); - }, - fromDirectory: (directory, stat, callback) => { - this.contextTshQueue.increaseParallelism(); - this.contextTshQueue.add(directory, (err, result) => { - this.contextTshQueue.decreaseParallelism(); - callback(err, result); - }); - }, - /** - * @param {string[]} files files - * @param {(Partial & Partial | string | null)[]} results results - * @returns {ContextTimestampAndHash} tsh - */ - reduce: (files, results) => { - let symlinks = undefined; - - const tsHash = createHash(this._hashFunction); - const hash = createHash(this._hashFunction); - - for (const file of files) { - tsHash.update(file); - hash.update(file); - } - let safeTime = 0; - for (const entry of results) { - if (!entry) { - tsHash.update("n"); - continue; - } - if (typeof entry === "string") { - tsHash.update("n"); - hash.update(entry); - continue; - } - if (entry.timestamp) { - tsHash.update("f"); - tsHash.update(`${entry.timestamp}`); - } else if (entry.timestampHash) { - tsHash.update("d"); - tsHash.update(`${entry.timestampHash}`); - } - if (entry.symlinks !== undefined) { - if (symlinks === undefined) symlinks = new Set(); - addAll(entry.symlinks, symlinks); - } - if (entry.safeTime) { - safeTime = Math.max(safeTime, entry.safeTime); - } - hash.update(entry.hash); - } - - const result = { - safeTime, - timestampHash: /** @type {string} */ (tsHash.digest("hex")), - hash: /** @type {string} */ (hash.digest("hex")) - }; - if (symlinks) result.symlinks = symlinks; - return result; - } - }, - (err, result) => { - if (err) return callback(err); - this._contextTshs.set(path, result); - return callback(null, result); - } - ); - } - } - } - - /** - * @param {ContextTimestampAndHash} entry entry - * @param {function((Error | null)=, ResolvedContextTimestampAndHash=): void} callback callback - * @returns {void} - */ - _resolveContextTsh(entry, callback) { - const hashes = []; - const tsHashes = []; - let safeTime = 0; - processAsyncTree( - entry.symlinks, - 10, - (target, push, callback) => { - this._getUnresolvedContextTsh(target, (err, entry) => { - if (err) return callback(err); - if (entry) { - hashes.push(entry.hash); - if (entry.timestampHash) tsHashes.push(entry.timestampHash); - if (entry.safeTime) { - safeTime = Math.max(safeTime, entry.safeTime); - } - if (entry.symlinks !== undefined) { - for (const target of entry.symlinks) push(target); - } - } - callback(); - }); - }, - err => { - if (err) return callback(err); - const hash = createHash(this._hashFunction); - const tsHash = createHash(this._hashFunction); - hash.update(entry.hash); - if (entry.timestampHash) tsHash.update(entry.timestampHash); - if (entry.safeTime) { - safeTime = Math.max(safeTime, entry.safeTime); - } - hashes.sort(); - for (const h of hashes) { - hash.update(h); - } - tsHashes.sort(); - for (const h of tsHashes) { - tsHash.update(h); - } - callback( - null, - (entry.resolved = { - safeTime, - timestampHash: /** @type {string} */ (tsHash.digest("hex")), - hash: /** @type {string} */ (hash.digest("hex")) - }) - ); - } - ); - } - - _getManagedItemDirectoryInfo(path, callback) { - this.fs.readdir(path, (err, elements) => { - if (err) { - if (err.code === "ENOENT" || err.code === "ENOTDIR") { - return callback(null, EMPTY_SET); - } - return callback(err); - } - const set = new Set( - /** @type {string[]} */ (elements).map(element => - join(this.fs, path, element) - ) - ); - callback(null, set); - }); - } - - _getManagedItemInfo(path, callback) { - const dir = dirname(this.fs, path); - this.managedItemDirectoryQueue.add(dir, (err, elements) => { - if (err) { - return callback(err); - } - if (!elements.has(path)) { - // file or directory doesn't exist - this._managedItems.set(path, "*missing"); - return callback(null, "*missing"); - } - // something exists - // it may be a file or directory - if ( - path.endsWith("node_modules") && - (path.endsWith("/node_modules") || path.endsWith("\\node_modules")) - ) { - // we are only interested in existence of this special directory - this._managedItems.set(path, "*node_modules"); - return callback(null, "*node_modules"); - } - - // we assume it's a directory, as files shouldn't occur in managed paths - const packageJsonPath = join(this.fs, path, "package.json"); - this.fs.readFile(packageJsonPath, (err, content) => { - if (err) { - if (err.code === "ENOENT" || err.code === "ENOTDIR") { - // no package.json or path is not a directory - this.fs.readdir(path, (err, elements) => { - if ( - !err && - elements.length === 1 && - elements[0] === "node_modules" - ) { - // This is only a grouping folder e. g. used by yarn - // we are only interested in existence of this special directory - this._managedItems.set(path, "*nested"); - return callback(null, "*nested"); - } - this.logger.warn( - `Managed item ${path} isn't a directory or doesn't contain a package.json (see snapshot.managedPaths option)` - ); - return callback(); - }); - return; - } - return callback(err); - } - let data; - try { - data = JSON.parse(content.toString("utf-8")); - } catch (e) { - return callback(e); - } - if (!data.name) { - this.logger.warn( - `${packageJsonPath} doesn't contain a "name" property (see snapshot.managedPaths option)` - ); - return callback(); - } - const info = `${data.name || ""}@${data.version || ""}`; - this._managedItems.set(path, info); - callback(null, info); - }); - }); - } - - getDeprecatedFileTimestamps() { - if (this._cachedDeprecatedFileTimestamps !== undefined) - return this._cachedDeprecatedFileTimestamps; - const map = new Map(); - for (const [path, info] of this._fileTimestamps) { - if (info) map.set(path, typeof info === "object" ? info.safeTime : null); - } - return (this._cachedDeprecatedFileTimestamps = map); - } - - getDeprecatedContextTimestamps() { - if (this._cachedDeprecatedContextTimestamps !== undefined) - return this._cachedDeprecatedContextTimestamps; - const map = new Map(); - for (const [path, info] of this._contextTimestamps) { - if (info) map.set(path, typeof info === "object" ? info.safeTime : null); - } - return (this._cachedDeprecatedContextTimestamps = map); - } -} - -module.exports = FileSystemInfo; -module.exports.Snapshot = Snapshot; +} +module.exports = CompatibilityPlugin; /***/ }), -/***/ 58727: +/***/ 85720: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -40519,4334 +35040,5270 @@ module.exports.Snapshot = Snapshot; -const { getEntryRuntime, mergeRuntimeOwned } = __webpack_require__(17156); +const asyncLib = __webpack_require__(78175); +const { + HookMap, + SyncHook, + SyncBailHook, + SyncWaterfallHook, + AsyncSeriesHook, + AsyncSeriesBailHook, + AsyncParallelHook +} = __webpack_require__(41242); +const util = __webpack_require__(73837); +const { CachedSource } = __webpack_require__(51255); +const { MultiItemCache } = __webpack_require__(55392); +const Chunk = __webpack_require__(39385); +const ChunkGraph = __webpack_require__(64971); +const ChunkGroup = __webpack_require__(15626); +const ChunkRenderError = __webpack_require__(918); +const ChunkTemplate = __webpack_require__(46341); +const CodeGenerationError = __webpack_require__(2102); +const CodeGenerationResults = __webpack_require__(71426); +const Dependency = __webpack_require__(54912); +const DependencyTemplates = __webpack_require__(9163); +const Entrypoint = __webpack_require__(13795); +const ErrorHelpers = __webpack_require__(59985); +const FileSystemInfo = __webpack_require__(79453); +const { + connectChunkGroupAndChunk, + connectChunkGroupParentAndChild +} = __webpack_require__(37234); +const { + makeWebpackError, + tryRunOrWebpackError +} = __webpack_require__(11351); +const MainTemplate = __webpack_require__(12856); +const Module = __webpack_require__(73208); +const ModuleDependencyError = __webpack_require__(67409); +const ModuleDependencyWarning = __webpack_require__(29656); +const ModuleGraph = __webpack_require__(99988); +const ModuleNotFoundError = __webpack_require__(32882); +const ModuleProfile = __webpack_require__(36418); +const ModuleRestoreError = __webpack_require__(94560); +const ModuleStoreError = __webpack_require__(59001); +const ModuleTemplate = __webpack_require__(62677); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeTemplate = __webpack_require__(18777); +const Stats = __webpack_require__(31743); +const WebpackError = __webpack_require__(53799); +const buildChunkGraph = __webpack_require__(79233); +const BuildCycleError = __webpack_require__(22273); +const { Logger, LogType } = __webpack_require__(32597); +const StatsFactory = __webpack_require__(92629); +const StatsPrinter = __webpack_require__(30198); +const { equals: arrayEquals } = __webpack_require__(84953); +const AsyncQueue = __webpack_require__(12260); +const LazySet = __webpack_require__(38938); +const { provide } = __webpack_require__(82482); +const WeakTupleMap = __webpack_require__(28745); +const { cachedCleverMerge } = __webpack_require__(60839); +const { + compareLocations, + concatComparators, + compareSelect, + compareIds, + compareStringsNumeric, + compareModulesByIdentifier +} = __webpack_require__(29579); +const createHash = __webpack_require__(49835); +const { + arrayToSetDeprecation, + soonFrozenObjectDeprecation, + createFakeHook +} = __webpack_require__(64518); +const processAsyncTree = __webpack_require__(42791); +const { getRuntimeKey } = __webpack_require__(17156); +const { isSourceEqual } = __webpack_require__(41245); +/** @template T @typedef {import("tapable").AsArray} AsArray */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ +/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Cache")} Cache */ +/** @typedef {import("./CacheFacade")} CacheFacade */ +/** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */ /** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Compiler").CompilationParams} CompilationParams */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ +/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./ModuleFactory")} ModuleFactory */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */ +/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./RuntimeModule")} RuntimeModule */ +/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry */ +/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */ +/** @typedef {import("./util/Hash")} Hash */ +/** @template T @typedef {import("./util/deprecation").FakeHook} FakeHook */ /** @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; - } - } - ); - } - ); - } -} +/** + * @callback Callback + * @param {(WebpackError | null)=} err + * @returns {void} + */ -module.exports = FlagAllModulesAsUsedPlugin; +/** + * @callback ModuleCallback + * @param {(WebpackError | null)=} err + * @param {Module=} result + * @returns {void} + */ +/** + * @callback ModuleFactoryResultCallback + * @param {(WebpackError | null)=} err + * @param {ModuleFactoryResult=} result + * @returns {void} + */ -/***/ }), +/** + * @callback ModuleOrFactoryResultCallback + * @param {(WebpackError | null)=} err + * @param {Module | ModuleFactoryResult=} result + * @returns {void} + */ -/***/ 84506: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @callback ExecuteModuleCallback + * @param {(WebpackError | null)=} err + * @param {ExecuteModuleResult=} result + * @returns {void} + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @callback DepBlockVarDependenciesCallback + * @param {Dependency} dependency + * @returns {any} + */ +/** @typedef {new (...args: any[]) => Dependency} DepConstructor */ +/** @typedef {Record} CompilationAssets */ +/** + * @typedef {Object} AvailableModulesChunkGroupMapping + * @property {ChunkGroup} chunkGroup + * @property {Set} availableModules + * @property {boolean} needCopy + */ -const asyncLib = __webpack_require__(78175); -const Queue = __webpack_require__(65930); +/** + * @typedef {Object} DependenciesBlockLike + * @property {Dependency[]} dependencies + * @property {AsyncDependenciesBlock[]} blocks + */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Dependency").ExportSpec} ExportSpec */ -/** @typedef {import("./Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("./ExportsInfo")} ExportsInfo */ -/** @typedef {import("./Module")} Module */ +/** + * @typedef {Object} ChunkPathData + * @property {string|number} id + * @property {string=} name + * @property {string} hash + * @property {function(number): string=} hashWithLength + * @property {(Record)=} contentHash + * @property {(Record string>)=} contentHashWithLength + */ -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 statRestoredFromMemCache = 0; - let statRestoredFromCache = 0; - let statNoExports = 0; - let statFlaggedUncached = 0; - let statNotCached = 0; - let statQueueItemsProcessed = 0; +/** + * @typedef {Object} ChunkHashContext + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + */ - const { moduleMemCaches } = compilation; +/** + * @typedef {Object} RuntimeRequirementsContext + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {CodeGenerationResults} codeGenerationResults the code generation results + */ - /** @type {Queue} */ - const queue = new Queue(); +/** + * @typedef {Object} ExecuteModuleOptions + * @property {EntryOptions=} entryOptions + */ - // Step 1: Try to restore cached provided export info from cache - logger.time("restore cached provided exports"); - asyncLib.each( - modules, - (module, callback) => { - const exportsInfo = moduleGraph.getExportsInfo(module); - if (!module.buildMeta || !module.buildMeta.exportsType) { - if (exportsInfo.otherExportsInfo.provided !== null) { - // It's a module without declared exports - statNoExports++; - exportsInfo.setHasProvideInfo(); - exportsInfo.setUnknownExportsProvided(); - return callback(); - } - } - if (typeof module.buildInfo.hash !== "string") { - statFlaggedUncached++; - // Enqueue uncacheable module for determining the exports - queue.enqueue(module); - exportsInfo.setHasProvideInfo(); - return callback(); - } - const memCache = moduleMemCaches && moduleMemCaches.get(module); - const memCacheValue = memCache && memCache.get(this); - if (memCacheValue !== undefined) { - statRestoredFromMemCache++; - exportsInfo.restoreProvided(memCacheValue); - return callback(); - } - cache.get( - module.identifier(), - module.buildInfo.hash, - (err, result) => { - if (err) return callback(err); +/** + * @typedef {Object} ExecuteModuleResult + * @property {any} exports + * @property {boolean} cacheable + * @property {Map} assets + * @property {LazySet} fileDependencies + * @property {LazySet} contextDependencies + * @property {LazySet} missingDependencies + * @property {LazySet} buildDependencies + */ - if (result !== undefined) { - statRestoredFromCache++; - exportsInfo.restoreProvided(result); - } else { - statNotCached++; - // Without cached info enqueue module for determining the exports - queue.enqueue(module); - exportsInfo.setHasProvideInfo(); - } - callback(); - } - ); - }, - err => { - logger.timeEnd("restore cached provided exports"); - if (err) return callback(err); +/** + * @typedef {Object} ExecuteModuleArgument + * @property {Module} module + * @property {{ id: string, exports: any, loaded: boolean }=} moduleObject + * @property {any} preparedInfo + * @property {CodeGenerationResult} codeGenerationResult + */ - /** @type {Set} */ - const modulesToStore = new Set(); +/** + * @typedef {Object} ExecuteModuleContext + * @property {Map} assets + * @property {Chunk} chunk + * @property {ChunkGraph} chunkGraph + * @property {function(string): any=} __webpack_require__ + */ - /** @type {Map>} */ - const dependencies = new Map(); +/** + * @typedef {Object} EntryData + * @property {Dependency[]} dependencies dependencies of the entrypoint that should be evaluated at startup + * @property {Dependency[]} includeDependencies dependencies of the entrypoint that should be included but not evaluated + * @property {EntryOptions} options options of the entrypoint + */ - /** @type {Module} */ - let module; +/** + * @typedef {Object} LogEntry + * @property {string} type + * @property {any[]} args + * @property {number} time + * @property {string[]=} trace + */ - /** @type {ExportsInfo} */ - let exportsInfo; +/** + * @typedef {Object} KnownAssetInfo + * @property {boolean=} immutable true, if the asset can be long term cached forever (contains a hash) + * @property {boolean=} minimized whether the asset is minimized + * @property {string | string[]=} fullhash the value(s) of the full hash used for this asset + * @property {string | string[]=} chunkhash the value(s) of the chunk hash used for this asset + * @property {string | string[]=} modulehash the value(s) of the module hash used for this asset + * @property {string | string[]=} contenthash the value(s) of the content hash used for this asset + * @property {string=} sourceFilename when asset was created from a source file (potentially transformed), the original filename relative to compilation context + * @property {number=} size size in bytes, only set after asset has been emitted + * @property {boolean=} development true, when asset is only used for development and doesn't count towards user-facing assets + * @property {boolean=} hotModuleReplacement true, when asset ships data for updating an existing application (HMR) + * @property {boolean=} javascriptModule true, when asset is javascript and an ESM + * @property {Record=} related object of pointers to other assets, keyed by type of relation (only points from parent to child) + */ - /** @type {Map} */ - const exportsSpecsFromDependencies = new Map(); +/** @typedef {KnownAssetInfo & Record} AssetInfo */ - let cacheable = true; - let changed = false; +/** + * @typedef {Object} Asset + * @property {string} name the filename of the asset + * @property {Source} source source of the asset + * @property {AssetInfo} info info about the asset + */ - /** - * @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); - } - }; +/** + * @typedef {Object} ModulePathData + * @property {string|number} id + * @property {string} hash + * @property {function(number): string=} hashWithLength + */ - /** - * @param {Dependency} dep the dependency - * @returns {void} - */ - const processDependency = dep => { - const exportDesc = dep.getExports(moduleGraph); - if (!exportDesc) return; - exportsSpecsFromDependencies.set(dep, exportDesc); - }; +/** + * @typedef {Object} PathData + * @property {ChunkGraph=} chunkGraph + * @property {string=} hash + * @property {function(number): string=} hashWithLength + * @property {(Chunk|ChunkPathData)=} chunk + * @property {(Module|ModulePathData)=} module + * @property {RuntimeSpec=} runtime + * @property {string=} filename + * @property {string=} basename + * @property {string=} query + * @property {string=} contentHashType + * @property {string=} contentHash + * @property {function(number): string=} contentHashWithLength + * @property {boolean=} noChunkHash + * @property {string=} url + */ - /** - * @param {Dependency} dep dependency - * @param {ExportsSpec} exportDesc info - * @returns {void} - */ - const processExportsSpec = (dep, exportDesc) => { - const exports = exportDesc.exports; - const globalCanMangle = exportDesc.canMangle; - const globalFrom = exportDesc.from; - const globalPriority = exportDesc.priority; - const globalTerminalBinding = - exportDesc.terminalBinding || false; - const exportDeps = exportDesc.dependencies; - if (exportDesc.hideExports) { - for (const name of exportDesc.hideExports) { - const exportInfo = exportsInfo.getExportInfo(name); - exportInfo.unsetTarget(dep); - } - } - if (exports === true) { - // unknown exports - if ( - exportsInfo.setUnknownExportsProvided( - globalCanMangle, - exportDesc.excludeExports, - globalFrom && dep, - globalFrom, - globalPriority - ) - ) { - changed = true; - } - } else if (Array.isArray(exports)) { - /** - * merge in new exports - * @param {ExportsInfo} exportsInfo own exports info - * @param {(ExportSpec | string)[]} exports list of exports - */ - const mergeExports = (exportsInfo, exports) => { - for (const exportNameOrSpec of exports) { - let name; - let canMangle = globalCanMangle; - let terminalBinding = globalTerminalBinding; - let exports = undefined; - let from = globalFrom; - let fromExport = undefined; - let priority = globalPriority; - let hidden = false; - if (typeof exportNameOrSpec === "string") { - name = exportNameOrSpec; - } else { - name = exportNameOrSpec.name; - if (exportNameOrSpec.canMangle !== undefined) - canMangle = exportNameOrSpec.canMangle; - if (exportNameOrSpec.export !== undefined) - fromExport = exportNameOrSpec.export; - if (exportNameOrSpec.exports !== undefined) - exports = exportNameOrSpec.exports; - if (exportNameOrSpec.from !== undefined) - from = exportNameOrSpec.from; - if (exportNameOrSpec.priority !== undefined) - priority = exportNameOrSpec.priority; - if (exportNameOrSpec.terminalBinding !== undefined) - terminalBinding = exportNameOrSpec.terminalBinding; - if (exportNameOrSpec.hidden !== undefined) - hidden = exportNameOrSpec.hidden; - } - const exportInfo = exportsInfo.getExportInfo(name); +/** + * @typedef {Object} KnownNormalizedStatsOptions + * @property {string} context + * @property {RequestShortener} requestShortener + * @property {string} chunksSort + * @property {string} modulesSort + * @property {string} chunkModulesSort + * @property {string} nestedModulesSort + * @property {string} assetsSort + * @property {boolean} ids + * @property {boolean} cachedAssets + * @property {boolean} groupAssetsByEmitStatus + * @property {boolean} groupAssetsByPath + * @property {boolean} groupAssetsByExtension + * @property {number} assetsSpace + * @property {((value: string, asset: StatsAsset) => boolean)[]} excludeAssets + * @property {((name: string, module: StatsModule, type: "module" | "chunk" | "root-of-chunk" | "nested") => boolean)[]} excludeModules + * @property {((warning: StatsError, textValue: string) => boolean)[]} warningsFilter + * @property {boolean} cachedModules + * @property {boolean} orphanModules + * @property {boolean} dependentModules + * @property {boolean} runtimeModules + * @property {boolean} groupModulesByCacheStatus + * @property {boolean} groupModulesByLayer + * @property {boolean} groupModulesByAttributes + * @property {boolean} groupModulesByPath + * @property {boolean} groupModulesByExtension + * @property {boolean} groupModulesByType + * @property {boolean | "auto"} entrypoints + * @property {boolean} chunkGroups + * @property {boolean} chunkGroupAuxiliary + * @property {boolean} chunkGroupChildren + * @property {number} chunkGroupMaxAssets + * @property {number} modulesSpace + * @property {number} chunkModulesSpace + * @property {number} nestedModulesSpace + * @property {false|"none"|"error"|"warn"|"info"|"log"|"verbose"} logging + * @property {((value: string) => boolean)[]} loggingDebug + * @property {boolean} loggingTrace + * @property {any} _env + */ - if ( - exportInfo.provided === false || - exportInfo.provided === null - ) { - exportInfo.provided = true; - changed = true; - } +/** @typedef {KnownNormalizedStatsOptions & Omit & Record} NormalizedStatsOptions */ - if ( - exportInfo.canMangleProvide !== false && - canMangle === false - ) { - exportInfo.canMangleProvide = false; - changed = true; - } +/** + * @typedef {Object} KnownCreateStatsOptionsContext + * @property {boolean=} forToString + */ - if (terminalBinding && !exportInfo.terminalBinding) { - exportInfo.terminalBinding = true; - changed = true; - } +/** @typedef {KnownCreateStatsOptionsContext & Record} CreateStatsOptionsContext */ - if (exports) { - const nestedExportsInfo = - exportInfo.createNestedExportsInfo(); - mergeExports(nestedExportsInfo, exports); - } +/** @type {AssetInfo} */ +const EMPTY_ASSET_INFO = Object.freeze({}); - if ( - from && - (hidden - ? exportInfo.unsetTarget(dep) - : exportInfo.setTarget( - dep, - from, - fromExport === undefined ? [name] : fromExport, - priority - )) - ) { - changed = true; - } +const esmDependencyCategory = "esm"; +// TODO webpack 6: remove +const deprecatedNormalModuleLoaderHook = util.deprecate( + compilation => { + return (__webpack_require__(39).getCompilationHooks)(compilation).loader; + }, + "Compilation.hooks.normalModuleLoader was moved to NormalModule.getCompilationHooks(compilation).loader", + "DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK" +); - // 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); - } - } +// TODO webpack 6: remove +const defineRemovedModuleTemplates = moduleTemplates => { + Object.defineProperties(moduleTemplates, { + asset: { + enumerable: false, + configurable: false, + get: () => { + throw new WebpackError( + "Compilation.moduleTemplates.asset has been removed" + ); + } + }, + webassembly: { + enumerable: false, + configurable: false, + get: () => { + throw new WebpackError( + "Compilation.moduleTemplates.webassembly has been removed" + ); + } + } + }); + moduleTemplates = undefined; +}; - 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 byId = compareSelect( + /** + * @param {Chunk} c chunk + * @returns {number | string} id + */ c => c.id, + compareIds +); - const notifyDependencies = () => { - const deps = dependencies.get(module); - if (deps !== undefined) { - for (const dep of deps) { - queue.enqueue(dep); - } - } - }; +const byNameOrHash = concatComparators( + compareSelect( + /** + * @param {Compilation} c compilation + * @returns {string} name + */ + c => c.name, + compareIds + ), + compareSelect( + /** + * @param {Compilation} c compilation + * @returns {string} hash + */ c => c.fullHash, + compareIds + ) +); - logger.time("figure out provided exports"); - while (queue.length > 0) { - module = queue.dequeue(); +const byMessage = compareSelect(err => `${err.message}`, compareStringsNumeric); - statQueueItemsProcessed++; +const byModule = compareSelect( + err => (err.module && err.module.identifier()) || "", + compareStringsNumeric +); - exportsInfo = moduleGraph.getExportsInfo(module); +const byLocation = compareSelect(err => err.loc, compareLocations); - cacheable = true; - changed = false; +const compareErrors = concatComparators(byModule, byLocation, byMessage); - exportsSpecsFromDependencies.clear(); - moduleGraph.freeze(); - processDependenciesBlock(module); - moduleGraph.unfreeze(); - for (const [ - dep, - exportsSpec - ] of exportsSpecsFromDependencies) { - processExportsSpec(dep, exportsSpec); - } +/** @type {WeakMap} */ +const unsafeCacheDependencies = new WeakMap(); - if (cacheable) { - modulesToStore.add(module); - } +/** @type {WeakMap} */ +const unsafeCacheData = new WeakMap(); - if (changed) { - notifyDependencies(); - } - } - logger.timeEnd("figure out provided exports"); +class Compilation { + /** + * Creates an instance of Compilation. + * @param {Compiler} compiler the compiler which created the compilation + * @param {CompilationParams} params the compilation parameters + */ + constructor(compiler, params) { + this._backCompat = compiler._backCompat; - logger.log( - `${Math.round( - (100 * (statFlaggedUncached + statNotCached)) / - (statRestoredFromMemCache + - statRestoredFromCache + - statNotCached + - statFlaggedUncached + - statNoExports) - )}% of exports of modules have been determined (${statNoExports} no declared exports, ${statNotCached} not cached, ${statFlaggedUncached} flagged uncacheable, ${statRestoredFromCache} from cache, ${statRestoredFromMemCache} from mem cache, ${ - statQueueItemsProcessed - - statNotCached - - statFlaggedUncached - } additional calculations due to dependencies)` - ); - - logger.time("store provided exports into cache"); - asyncLib.each( - modulesToStore, - (module, callback) => { - if (typeof module.buildInfo.hash !== "string") { - // not cacheable - return callback(); - } - const cachedData = moduleGraph - .getExportsInfo(module) - .getRestoreProvidedData(); - const memCache = - moduleMemCaches && moduleMemCaches.get(module); - if (memCache) { - memCache.set(this, cachedData); - } - cache.store( - module.identifier(), - module.buildInfo.hash, - cachedData, - callback - ); - }, - err => { - logger.timeEnd("store provided exports into cache"); - callback(err); - } - ); - } - ); - } - ); + const getNormalModuleLoader = () => deprecatedNormalModuleLoaderHook(this); + /** @typedef {{ additionalAssets?: true | Function }} ProcessAssetsAdditionalOptions */ + /** @type {AsyncSeriesHook<[CompilationAssets], ProcessAssetsAdditionalOptions>} */ + const processAssetsHook = new AsyncSeriesHook(["assets"]); - /** @type {WeakMap} */ - 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)); - } - ); + let savedAssets = new Set(); + const popNewAssets = assets => { + let newAssets = undefined; + for (const file of Object.keys(assets)) { + if (savedAssets.has(file)) continue; + if (newAssets === undefined) { + newAssets = Object.create(null); + } + newAssets[file] = assets[file]; + savedAssets.add(file); } - ); - } -} - -module.exports = FlagDependencyExportsPlugin; - - -/***/ }), - -/***/ 58812: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Dependency = __webpack_require__(54912); -const { UsageState } = __webpack_require__(63686); -const ModuleGraphConnection = __webpack_require__(40639); -const { STAGE_DEFAULT } = __webpack_require__(80057); -const ArrayQueue = __webpack_require__(41792); -const TupleQueue = __webpack_require__(38415); -const { getEntryRuntime, mergeRuntimeOwned } = __webpack_require__(17156); - -/** @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 => { - if (compilation.moduleMemCaches) { - throw new Error( - "optimization.usedExports can't be used with cacheUnaffected as export usage is a global effect" - ); - } - - const logger = compilation.getLogger( - "webpack.FlagDependencyUsagePlugin" - ); - /** @type {Map} */ - 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); - } + return newAssets; + }; + processAssetsHook.intercept({ + name: "Compilation", + call: () => { + savedAssets = new Set(Object.keys(this.assets)); + }, + register: tap => { + const { type, name } = tap; + const { fn, additionalAssets, ...remainingTap } = tap; + const additionalAssetsFn = + additionalAssets === true ? fn : additionalAssets; + const processedAssets = additionalAssetsFn ? new WeakSet() : undefined; + switch (type) { + case "sync": + if (additionalAssetsFn) { + this.hooks.processAdditionalAssets.tap(name, assets => { + if (processedAssets.has(this.assets)) + additionalAssetsFn(assets); + }); } - }; - - /** - * @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>} */ - const map = new Map(); - - /** @type {ArrayQueue} */ - const queue = new ArrayQueue(); - queue.enqueue(module); - for (;;) { - const block = queue.dequeue(); - if (block === undefined) break; - for (const b of block.blocks) { - if ( - !this.global && - b.groupOptions && - b.groupOptions.entryOptions - ) { - processModule( - b, - b.groupOptions.entryOptions.runtime || undefined, - true + return { + ...remainingTap, + type: "async", + fn: (assets, callback) => { + try { + fn(assets); + } catch (e) { + return callback(e); + } + if (processedAssets !== undefined) + processedAssets.add(this.assets); + const newAssets = popNewAssets(assets); + if (newAssets !== undefined) { + this.hooks.processAdditionalAssets.callAsync( + newAssets, + callback ); - } else { - queue.enqueue(b); + return; } + callback(); } - 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; + }; + case "async": + if (additionalAssetsFn) { + this.hooks.processAdditionalAssets.tapAsync( + name, + (assets, callback) => { + if (processedAssets.has(this.assets)) + return additionalAssetsFn(assets, callback); + callback(); } - 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 - }); - } - } + ); + } + return { + ...remainingTap, + fn: (assets, callback) => { + fn(assets, err => { + if (err) return callback(err); + if (processedAssets !== undefined) + processedAssets.add(this.assets); + const newAssets = popNewAssets(assets); + if (newAssets !== undefined) { + this.hooks.processAdditionalAssets.callAsync( + newAssets, + callback + ); + return; } - } + callback(); + }); } + }; + case "promise": + if (additionalAssetsFn) { + this.hooks.processAdditionalAssets.tapPromise(name, assets => { + if (processedAssets.has(this.assets)) + return additionalAssetsFn(assets); + return Promise.resolve(); + }); } - - for (const [module, referencedExports] of map) { - if (Array.isArray(referencedExports)) { - processReferencedModule( - module, - referencedExports, - runtime, - forceSideEffects - ); - } else { - processReferencedModule( - module, - Array.from(referencedExports.values()), - runtime, - forceSideEffects - ); + return { + ...remainingTap, + fn: assets => { + const p = fn(assets); + if (!p || !p.then) return p; + return p.then(() => { + if (processedAssets !== undefined) + processedAssets.add(this.assets); + const newAssets = popNewAssets(assets); + if (newAssets !== undefined) { + return this.hooks.processAdditionalAssets.promise( + newAssets + ); + } + }); } - } - }; - - 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; + /** @type {SyncHook<[CompilationAssets]>} */ + const afterProcessAssetsHook = new SyncHook(["assets"]); + /** + * @template T + * @param {string} name name of the hook + * @param {number} stage new stage + * @param {function(): AsArray} getArgs get old hook function args + * @param {string=} code deprecation code (not deprecated when unset) + * @returns {FakeHook, "tap" | "tapAsync" | "tapPromise" | "name">>} fake hook which redirects + */ + const createProcessAssetsHook = (name, stage, getArgs, code) => { + if (!this._backCompat && code) return undefined; + const errorMessage = + reason => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}. +BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a single Compilation.hooks.processAssets hook.`; + const getOptions = options => { + if (typeof options === "string") options = { name: options }; + if (options.stage) { + throw new Error(errorMessage("it's using the 'stage' option")); + } + return { ...options, stage: stage }; + }; + return createFakeHook( + { + name, + /** @type {AsyncSeriesHook["intercept"]} */ + intercept(interceptor) { + throw new Error(errorMessage("it's using 'intercept'")); + }, + /** @type {AsyncSeriesHook["tap"]} */ + tap: (options, fn) => { + processAssetsHook.tap(getOptions(options), () => fn(...getArgs())); + }, + /** @type {AsyncSeriesHook["tapAsync"]} */ + tapAsync: (options, fn) => { + processAssetsHook.tapAsync( + getOptions(options), + (assets, callback) => + /** @type {any} */ (fn)(...getArgs(), callback) + ); + }, + /** @type {AsyncSeriesHook["tapPromise"]} */ + tapPromise: (options, fn) => { + processAssetsHook.tapPromise(getOptions(options), () => + fn(...getArgs()) + ); + } + }, + `${name} is deprecated (use Compilation.hooks.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)`, + code + ); + }; + this.hooks = Object.freeze({ + /** @type {SyncHook<[Module]>} */ + buildModule: new SyncHook(["module"]), + /** @type {SyncHook<[Module]>} */ + rebuildModule: new SyncHook(["module"]), + /** @type {SyncHook<[Module, WebpackError]>} */ + failedModule: new SyncHook(["module", "error"]), + /** @type {SyncHook<[Module]>} */ + succeedModule: new SyncHook(["module"]), + /** @type {SyncHook<[Module]>} */ + stillValidModule: new SyncHook(["module"]), -/***/ }), + /** @type {SyncHook<[Dependency, EntryOptions]>} */ + addEntry: new SyncHook(["entry", "options"]), + /** @type {SyncHook<[Dependency, EntryOptions, Error]>} */ + failedEntry: new SyncHook(["entry", "options", "error"]), + /** @type {SyncHook<[Dependency, EntryOptions, Module]>} */ + succeedEntry: new SyncHook(["entry", "options", "module"]), -/***/ 93401: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {SyncWaterfallHook<[(string[] | ReferencedExport)[], Dependency, RuntimeSpec]>} */ + dependencyReferencedExports: new SyncWaterfallHook([ + "referencedExports", + "dependency", + "runtime" + ]), -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** @type {SyncHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */ + executeModule: new SyncHook(["options", "context"]), + /** @type {AsyncParallelHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */ + prepareModuleExecution: new AsyncParallelHook(["options", "context"]), + /** @type {AsyncSeriesHook<[Iterable]>} */ + finishModules: new AsyncSeriesHook(["modules"]), + /** @type {AsyncSeriesHook<[Module]>} */ + finishRebuildingModule: new AsyncSeriesHook(["module"]), + /** @type {SyncHook<[]>} */ + unseal: new SyncHook([]), + /** @type {SyncHook<[]>} */ + seal: new SyncHook([]), + /** @type {SyncHook<[]>} */ + beforeChunks: new SyncHook([]), + /** @type {SyncHook<[Iterable]>} */ + afterChunks: new SyncHook(["chunks"]), -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ -/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./NormalModule")} NormalModule */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./util/Hash")} Hash */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + /** @type {SyncBailHook<[Iterable]>} */ + optimizeDependencies: new SyncBailHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + afterOptimizeDependencies: new SyncHook(["modules"]), -/** - * @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} runtimeRequirements the requirements for runtime - * @property {RuntimeSpec} runtime the runtime - * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules - * @property {CodeGenerationResults=} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that) - * @property {string} type which kind of code should be generated - * @property {function(): Map=} getData get access to the code generation data - */ + /** @type {SyncHook<[]>} */ + optimize: new SyncHook([]), + /** @type {SyncBailHook<[Iterable]>} */ + optimizeModules: new SyncBailHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + afterOptimizeModules: new SyncHook(["modules"]), -/** - * @typedef {Object} UpdateHashContext - * @property {NormalModule} module the module - * @property {ChunkGraph} chunkGraph - * @property {RuntimeSpec} runtime - */ + /** @type {SyncBailHook<[Iterable, ChunkGroup[]]>} */ + optimizeChunks: new SyncBailHook(["chunks", "chunkGroups"]), + /** @type {SyncHook<[Iterable, ChunkGroup[]]>} */ + afterOptimizeChunks: new SyncHook(["chunks", "chunkGroups"]), -/** - * - */ -class Generator { - static byType(map) { - return new ByTypeGenerator(map); - } + /** @type {AsyncSeriesHook<[Iterable, Iterable]>} */ + optimizeTree: new AsyncSeriesHook(["chunks", "modules"]), + /** @type {SyncHook<[Iterable, Iterable]>} */ + afterOptimizeTree: new SyncHook(["chunks", "modules"]), - /* istanbul ignore next */ - /** - * @abstract - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); - } + /** @type {AsyncSeriesBailHook<[Iterable, Iterable]>} */ + optimizeChunkModules: new AsyncSeriesBailHook(["chunks", "modules"]), + /** @type {SyncHook<[Iterable, Iterable]>} */ + afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]), + /** @type {SyncBailHook<[], boolean>} */ + shouldRecord: new SyncBailHook([]), - /* 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 = __webpack_require__(77198); - throw new AbstractMethodError(); - } + /** @type {SyncHook<[Chunk, Set, RuntimeRequirementsContext]>} */ + additionalChunkRuntimeRequirements: new SyncHook([ + "chunk", + "runtimeRequirements", + "context" + ]), + /** @type {HookMap, RuntimeRequirementsContext]>>} */ + runtimeRequirementInChunk: new HookMap( + () => new SyncBailHook(["chunk", "runtimeRequirements", "context"]) + ), + /** @type {SyncHook<[Module, Set, RuntimeRequirementsContext]>} */ + additionalModuleRuntimeRequirements: new SyncHook([ + "module", + "runtimeRequirements", + "context" + ]), + /** @type {HookMap, RuntimeRequirementsContext]>>} */ + runtimeRequirementInModule: new HookMap( + () => new SyncBailHook(["module", "runtimeRequirements", "context"]) + ), + /** @type {SyncHook<[Chunk, Set, RuntimeRequirementsContext]>} */ + additionalTreeRuntimeRequirements: new SyncHook([ + "chunk", + "runtimeRequirements", + "context" + ]), + /** @type {HookMap, RuntimeRequirementsContext]>>} */ + runtimeRequirementInTree: new HookMap( + () => new SyncBailHook(["chunk", "runtimeRequirements", "context"]) + ), - /* 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 = __webpack_require__(77198); - throw new AbstractMethodError(); - } + /** @type {SyncHook<[RuntimeModule, Chunk]>} */ + runtimeModule: new SyncHook(["module", "chunk"]), - /** - * @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}`; - } + /** @type {SyncHook<[Iterable, any]>} */ + reviveModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook<[Iterable]>} */ + beforeModuleIds: new SyncHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + moduleIds: new SyncHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + optimizeModuleIds: new SyncHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + afterOptimizeModuleIds: new SyncHook(["modules"]), - /** - * @param {Hash} hash hash that will be modified - * @param {UpdateHashContext} updateHashContext context for updating hash - */ - updateHash(hash, { module, runtime }) { - // no nothing - } -} + /** @type {SyncHook<[Iterable, any]>} */ + reviveChunks: new SyncHook(["chunks", "records"]), + /** @type {SyncHook<[Iterable]>} */ + beforeChunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook<[Iterable]>} */ + chunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook<[Iterable]>} */ + optimizeChunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook<[Iterable]>} */ + afterOptimizeChunkIds: new SyncHook(["chunks"]), -class ByTypeGenerator extends Generator { - constructor(map) { - super(); - this.map = map; - this._types = new Set(Object.keys(map)); - } + /** @type {SyncHook<[Iterable, any]>} */ + recordModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook<[Iterable, any]>} */ + recordChunks: new SyncHook(["chunks", "records"]), - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return this._types; - } + /** @type {SyncHook<[Iterable]>} */ + optimizeCodeGeneration: new SyncHook(["modules"]), - /** - * @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; - } + /** @type {SyncHook<[]>} */ + beforeModuleHash: new SyncHook([]), + /** @type {SyncHook<[]>} */ + afterModuleHash: new SyncHook([]), - /** - * @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); - } -} + /** @type {SyncHook<[]>} */ + beforeCodeGeneration: new SyncHook([]), + /** @type {SyncHook<[]>} */ + afterCodeGeneration: new SyncHook([]), -module.exports = Generator; + /** @type {SyncHook<[]>} */ + beforeRuntimeRequirements: new SyncHook([]), + /** @type {SyncHook<[]>} */ + afterRuntimeRequirements: new SyncHook([]), + /** @type {SyncHook<[]>} */ + beforeHash: new SyncHook([]), + /** @type {SyncHook<[Chunk]>} */ + contentHash: new SyncHook(["chunk"]), + /** @type {SyncHook<[]>} */ + afterHash: new SyncHook([]), + /** @type {SyncHook<[any]>} */ + recordHash: new SyncHook(["records"]), + /** @type {SyncHook<[Compilation, any]>} */ + record: new SyncHook(["compilation", "records"]), -/***/ }), + /** @type {SyncHook<[]>} */ + beforeModuleAssets: new SyncHook([]), + /** @type {SyncBailHook<[], boolean>} */ + shouldGenerateChunkAssets: new SyncBailHook([]), + /** @type {SyncHook<[]>} */ + beforeChunkAssets: new SyncHook([]), + // TODO webpack 6 remove + /** @deprecated */ + additionalChunkAssets: createProcessAssetsHook( + "additionalChunkAssets", + Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, + () => [this.chunks], + "DEP_WEBPACK_COMPILATION_ADDITIONAL_CHUNK_ASSETS" + ), -/***/ 37234: -/***/ (function(__unused_webpack_module, exports) { + // TODO webpack 6 deprecate + /** @deprecated */ + additionalAssets: createProcessAssetsHook( + "additionalAssets", + Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, + () => [] + ), + // TODO webpack 6 remove + /** @deprecated */ + optimizeChunkAssets: createProcessAssetsHook( + "optimizeChunkAssets", + Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE, + () => [this.chunks], + "DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS" + ), + // TODO webpack 6 remove + /** @deprecated */ + afterOptimizeChunkAssets: createProcessAssetsHook( + "afterOptimizeChunkAssets", + Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE + 1, + () => [this.chunks], + "DEP_WEBPACK_COMPILATION_AFTER_OPTIMIZE_CHUNK_ASSETS" + ), + // TODO webpack 6 deprecate + /** @deprecated */ + optimizeAssets: processAssetsHook, + // TODO webpack 6 deprecate + /** @deprecated */ + afterOptimizeAssets: afterProcessAssetsHook, -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + processAssets: processAssetsHook, + afterProcessAssets: afterProcessAssetsHook, + /** @type {AsyncSeriesHook<[CompilationAssets]>} */ + processAdditionalAssets: new AsyncSeriesHook(["assets"]), + /** @type {SyncBailHook<[], boolean>} */ + needAdditionalSeal: new SyncBailHook([]), + /** @type {AsyncSeriesHook<[]>} */ + afterSeal: new AsyncSeriesHook([]), + /** @type {SyncWaterfallHook<[RenderManifestEntry[], RenderManifestOptions]>} */ + renderManifest: new SyncWaterfallHook(["result", "options"]), -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./Module")} Module */ + /** @type {SyncHook<[Hash]>} */ + fullHash: new SyncHook(["hash"]), + /** @type {SyncHook<[Chunk, Hash, ChunkHashContext]>} */ + chunkHash: new SyncHook(["chunk", "chunkHash", "ChunkHashContext"]), -/** - * @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); - } -}; + /** @type {SyncHook<[Module, string]>} */ + moduleAsset: new SyncHook(["module", "filename"]), + /** @type {SyncHook<[Chunk, string]>} */ + chunkAsset: new SyncHook(["chunk", "filename"]), -/** - * @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); - } -}; + /** @type {SyncWaterfallHook<[string, object, AssetInfo]>} */ + assetPath: new SyncWaterfallHook(["path", "options", "assetInfo"]), -exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk; -exports.connectChunkGroupParentAndChild = connectChunkGroupParentAndChild; + /** @type {SyncBailHook<[], boolean>} */ + needAdditionalPass: new SyncBailHook([]), + /** @type {SyncHook<[Compiler, string, number]>} */ + childCompiler: new SyncHook([ + "childCompiler", + "compilerName", + "compilerIndex" + ]), -/***/ }), + /** @type {SyncBailHook<[string, LogEntry], true>} */ + log: new SyncBailHook(["origin", "logEntry"]), -/***/ 97511: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {SyncWaterfallHook<[WebpackError[]]>} */ + processWarnings: new SyncWaterfallHook(["warnings"]), + /** @type {SyncWaterfallHook<[WebpackError[]]>} */ + processErrors: new SyncWaterfallHook(["errors"]), -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + /** @type {HookMap, CreateStatsOptionsContext]>>} */ + statsPreset: new HookMap(() => new SyncHook(["options", "context"])), + /** @type {SyncHook<[Partial, CreateStatsOptionsContext]>} */ + statsNormalize: new SyncHook(["options", "context"]), + /** @type {SyncHook<[StatsFactory, NormalizedStatsOptions]>} */ + statsFactory: new SyncHook(["statsFactory", "options"]), + /** @type {SyncHook<[StatsPrinter, NormalizedStatsOptions]>} */ + statsPrinter: new SyncHook(["statsPrinter", "options"]), + get normalModuleLoader() { + return getNormalModuleLoader(); + } + }); + /** @type {string=} */ + this.name = undefined; + this.startTime = undefined; + this.endTime = undefined; + /** @type {Compiler} */ + this.compiler = compiler; + this.resolverFactory = compiler.resolverFactory; + this.inputFileSystem = compiler.inputFileSystem; + this.fileSystemInfo = new FileSystemInfo(this.inputFileSystem, { + managedPaths: compiler.managedPaths, + immutablePaths: compiler.immutablePaths, + logger: this.getLogger("webpack.FileSystemInfo"), + hashFunction: compiler.options.output.hashFunction + }); + if (compiler.fileTimestamps) { + this.fileSystemInfo.addFileTimestamps(compiler.fileTimestamps, true); + } + if (compiler.contextTimestamps) { + this.fileSystemInfo.addContextTimestamps( + compiler.contextTimestamps, + true + ); + } + /** @type {Map>} */ + this.valueCacheVersions = new Map(); + this.requestShortener = compiler.requestShortener; + this.compilerPath = compiler.compilerPath; + this.logger = this.getLogger("webpack.Compilation"); -const WebpackError = __webpack_require__(53799); + const options = compiler.options; + this.options = options; + this.outputOptions = options && options.output; + /** @type {boolean} */ + this.bail = (options && options.bail) || false; + /** @type {boolean} */ + this.profile = (options && options.profile) || false; -module.exports = class HarmonyLinkingError extends WebpackError { - /** @param {string} message Error message */ - constructor(message) { - super(message); - this.name = "HarmonyLinkingError"; - this.hideStack = true; - } -}; - - -/***/ }), + this.params = params; + this.mainTemplate = new MainTemplate(this.outputOptions, this); + this.chunkTemplate = new ChunkTemplate(this.outputOptions, this); + this.runtimeTemplate = new RuntimeTemplate( + this, + this.outputOptions, + this.requestShortener + ); + /** @type {{javascript: ModuleTemplate}} */ + this.moduleTemplates = { + javascript: new ModuleTemplate(this.runtimeTemplate, this) + }; + defineRemovedModuleTemplates(this.moduleTemplates); -/***/ 11351: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {Map> | undefined} */ + this.moduleMemCaches = undefined; + /** @type {Map> | undefined} */ + this.moduleMemCaches2 = undefined; + this.moduleGraph = new ModuleGraph(); + /** @type {ChunkGraph} */ + this.chunkGraph = undefined; + /** @type {CodeGenerationResults} */ + this.codeGenerationResults = undefined; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ + /** @type {AsyncQueue} */ + this.processDependenciesQueue = new AsyncQueue({ + name: "processDependencies", + parallelism: options.parallelism || 100, + processor: this._processModuleDependencies.bind(this) + }); + /** @type {AsyncQueue} */ + this.addModuleQueue = new AsyncQueue({ + name: "addModule", + parent: this.processDependenciesQueue, + getKey: module => module.identifier(), + processor: this._addModule.bind(this) + }); + /** @type {AsyncQueue} */ + this.factorizeQueue = new AsyncQueue({ + name: "factorize", + parent: this.addModuleQueue, + processor: this._factorizeModule.bind(this) + }); + /** @type {AsyncQueue} */ + this.buildQueue = new AsyncQueue({ + name: "build", + parent: this.factorizeQueue, + processor: this._buildModule.bind(this) + }); + /** @type {AsyncQueue} */ + this.rebuildQueue = new AsyncQueue({ + name: "rebuild", + parallelism: options.parallelism || 100, + processor: this._rebuildModule.bind(this) + }); + /** + * Modules in value are building during the build of Module in key. + * Means value blocking key from finishing. + * Needed to detect build cycles. + * @type {WeakMap>} + */ + this.creatingModuleDuringBuild = new WeakMap(); + /** @type {Map} */ + this.entries = new Map(); + /** @type {EntryData} */ + this.globalEntry = { + dependencies: [], + includeDependencies: [], + options: { + name: undefined + } + }; + /** @type {Map} */ + this.entrypoints = new Map(); + /** @type {Entrypoint[]} */ + this.asyncEntrypoints = []; + /** @type {Set} */ + this.chunks = new Set(); + /** @type {ChunkGroup[]} */ + this.chunkGroups = []; + /** @type {Map} */ + this.namedChunkGroups = new Map(); + /** @type {Map} */ + this.namedChunks = new Map(); + /** @type {Set} */ + this.modules = new Set(); + if (this._backCompat) { + arrayToSetDeprecation(this.chunks, "Compilation.chunks"); + arrayToSetDeprecation(this.modules, "Compilation.modules"); + } + /** @private @type {Map} */ + this._modules = new Map(); + this.records = null; + /** @type {string[]} */ + this.additionalChunkAssets = []; + /** @type {CompilationAssets} */ + this.assets = {}; + /** @type {Map} */ + this.assetsInfo = new Map(); + /** @type {Map>>} */ + this._assetsRelatedIn = new Map(); + /** @type {WebpackError[]} */ + this.errors = []; + /** @type {WebpackError[]} */ + this.warnings = []; + /** @type {Compilation[]} */ + this.children = []; + /** @type {Map} */ + this.logging = new Map(); + /** @type {Map} */ + this.dependencyFactories = new Map(); + /** @type {DependencyTemplates} */ + this.dependencyTemplates = new DependencyTemplates( + this.outputOptions.hashFunction + ); + this.childrenCounters = {}; + /** @type {Set} */ + this.usedChunkIds = null; + /** @type {Set} */ + this.usedModuleIds = null; + /** @type {boolean} */ + this.needAdditionalPass = false; + /** @type {Set} */ + this._restoredUnsafeCacheModuleEntries = new Set(); + /** @type {Map} */ + this._restoredUnsafeCacheEntries = new Map(); + /** @type {WeakSet} */ + this.builtModules = new WeakSet(); + /** @type {WeakSet} */ + this.codeGeneratedModules = new WeakSet(); + /** @type {WeakSet} */ + this.buildTimeExecutedModules = new WeakSet(); + /** @private @type {Map} */ + this._rebuildingModules = new Map(); + /** @type {Set} */ + this.emittedAssets = new Set(); + /** @type {Set} */ + this.comparedForEmitAssets = new Set(); + /** @type {LazySet} */ + this.fileDependencies = new LazySet(); + /** @type {LazySet} */ + this.contextDependencies = new LazySet(); + /** @type {LazySet} */ + this.missingDependencies = new LazySet(); + /** @type {LazySet} */ + this.buildDependencies = new LazySet(); + // TODO webpack 6 remove + this.compilationDependencies = { + add: util.deprecate( + item => this.fileDependencies.add(item), + "Compilation.compilationDependencies is deprecated (used Compilation.fileDependencies instead)", + "DEP_WEBPACK_COMPILATION_COMPILATION_DEPENDENCIES" + ) + }; -const WebpackError = __webpack_require__(53799); + this._modulesCache = this.getCache("Compilation/modules"); + this._assetsCache = this.getCache("Compilation/assets"); + this._codeGenerationCache = this.getCache("Compilation/codeGeneration"); -/** @typedef {import("./Module")} Module */ + const unsafeCache = options.module.unsafeCache; + this._unsafeCache = !!unsafeCache; + this._unsafeCachePredicate = + typeof unsafeCache === "function" ? unsafeCache : () => true; + } -/** - * @template T - * @callback Callback - * @param {Error=} err - * @param {T=} stats - * @returns {void} - */ + getStats() { + return new Stats(this); + } -class HookWebpackError extends WebpackError { /** - * Creates an instance of HookWebpackError. - * @param {Error} error inner error - * @param {string} hook name of hook + * @param {StatsOptions | string} optionsOrPreset stats option value + * @param {CreateStatsOptionsContext} context context + * @returns {NormalizedStatsOptions} normalized options */ - 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}`; - - 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 | null)=, T=): void} callback webpack error callback - * @param {string} hook name of hook - * @returns {Callback} generic callback - */ -const makeWebpackErrorCallback = (callback, hook) => { - return (err, result) => { - if (err) { - if (err instanceof WebpackError) { - callback(err); - return; + createStatsOptions(optionsOrPreset, context = {}) { + if ( + typeof optionsOrPreset === "boolean" || + typeof optionsOrPreset === "string" + ) { + optionsOrPreset = { preset: optionsOrPreset }; + } + if (typeof optionsOrPreset === "object" && optionsOrPreset !== null) { + // We use this method of shallow cloning this object to include + // properties in the prototype chain + /** @type {Partial} */ + const options = {}; + for (const key in optionsOrPreset) { + options[key] = optionsOrPreset[key]; } - callback(new HookWebpackError(err, hook)); - return; + if (options.preset !== undefined) { + this.hooks.statsPreset.for(options.preset).call(options, context); + } + this.hooks.statsNormalize.call(options, context); + return /** @type {NormalizedStatsOptions} */ (options); + } else { + /** @type {Partial} */ + const options = {}; + this.hooks.statsNormalize.call(options, context); + return /** @type {NormalizedStatsOptions} */ (options); } - 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); + createStatsFactory(options) { + const statsFactory = new StatsFactory(); + this.hooks.statsFactory.call(statsFactory, options); + return statsFactory; } - return r; -}; -module.exports.tryRunOrWebpackError = tryRunOrWebpackError; + createStatsPrinter(options) { + const statsPrinter = new StatsPrinter(); + this.hooks.statsPrinter.call(statsPrinter, options); + return statsPrinter; + } + /** + * @param {string} name cache name + * @returns {CacheFacade} the cache facade instance + */ + getCache(name) { + return this.compiler.getCache(name); + } -/***/ }), + /** + * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name + * @returns {Logger} a logger with that name + */ + getLogger(name) { + if (!name) { + throw new TypeError("Compilation.getLogger(name) called without a name"); + } + /** @type {LogEntry[] | undefined} */ + let logEntries; + return new Logger( + (type, args) => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compilation.getLogger(name) called with a function not returning a name" + ); + } + } + let trace; + switch (type) { + case LogType.warn: + case LogType.error: + case LogType.trace: + trace = ErrorHelpers.cutOffLoaderExecution(new Error("Trace").stack) + .split("\n") + .slice(3); + break; + } + /** @type {LogEntry} */ + const logEntry = { + time: Date.now(), + type, + args, + trace + }; + if (this.hooks.log.call(name, logEntry) === undefined) { + if (logEntry.type === LogType.profileEnd) { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.profileEnd === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.profileEnd(`[${name}] ${logEntry.args[0]}`); + } + } + if (logEntries === undefined) { + logEntries = this.logging.get(name); + if (logEntries === undefined) { + logEntries = []; + this.logging.set(name, logEntries); + } + } + logEntries.push(logEntry); + if (logEntry.type === LogType.profile) { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.profile === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.profile(`[${name}] ${logEntry.args[0]}`); + } + } + } + }, + childName => { + if (typeof name === "function") { + if (typeof childName === "function") { + return this.getLogger(() => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compilation.getLogger(name) called with a function not returning a name" + ); + } + } + if (typeof childName === "function") { + childName = childName(); + if (!childName) { + throw new TypeError( + "Logger.getChildLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } else { + return this.getLogger(() => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compilation.getLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } + } else { + if (typeof childName === "function") { + return this.getLogger(() => { + if (typeof childName === "function") { + childName = childName(); + if (!childName) { + throw new TypeError( + "Logger.getChildLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } else { + return this.getLogger(`${name}/${childName}`); + } + } + } + ); + } -/***/ 6404: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {Module} module module to be added that was created + * @param {ModuleCallback} callback returns the module in the compilation, + * it could be the passed one (if new), or an already existing in the compilation + * @returns {void} + */ + addModule(module, callback) { + this.addModuleQueue.add(module, callback); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {Module} module module to be added that was created + * @param {ModuleCallback} callback returns the module in the compilation, + * it could be the passed one (if new), or an already existing in the compilation + * @returns {void} + */ + _addModule(module, callback) { + const identifier = module.identifier(); + const alreadyAddedModule = this._modules.get(identifier); + if (alreadyAddedModule) { + return callback(null, alreadyAddedModule); + } + const currentProfile = this.profile + ? this.moduleGraph.getProfile(module) + : undefined; + if (currentProfile !== undefined) { + currentProfile.markRestoringStart(); + } + this._modulesCache.get(identifier, null, (err, cacheModule) => { + if (err) return callback(new ModuleRestoreError(module, err)); -const { SyncBailHook } = __webpack_require__(6967); -const { RawSource } = __webpack_require__(51255); -const ChunkGraph = __webpack_require__(64971); -const Compilation = __webpack_require__(85720); -const HotUpdateChunk = __webpack_require__(9597); -const NormalModule = __webpack_require__(39); -const RuntimeGlobals = __webpack_require__(16475); -const WebpackError = __webpack_require__(53799); -const ConstDependency = __webpack_require__(76911); -const ImportMetaHotAcceptDependency = __webpack_require__(51274); -const ImportMetaHotDeclineDependency = __webpack_require__(53141); -const ModuleHotAcceptDependency = __webpack_require__(47511); -const ModuleHotDeclineDependency = __webpack_require__(86301); -const HotModuleReplacementRuntimeModule = __webpack_require__(27899); -const JavascriptParser = __webpack_require__(29050); -const { - evaluateToIdentifier -} = __webpack_require__(93998); -const { find, isSubset } = __webpack_require__(93347); -const TupleSet = __webpack_require__(76455); -const { compareModulesById } = __webpack_require__(29579); -const { - getRuntimeKey, - keyToRuntime, - forEachRuntime, - mergeRuntimeOwned, - subtractRuntime, - intersectRuntime -} = __webpack_require__(17156); + if (currentProfile !== undefined) { + currentProfile.markRestoringEnd(); + currentProfile.markIntegrationStart(); + } -/** @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 */ + if (cacheModule) { + cacheModule.updateCacheModule(module); -/** - * @typedef {Object} HMRJavascriptParserHooks - * @property {SyncBailHook<[TODO, string[]], void>} hotAcceptCallback - * @property {SyncBailHook<[TODO, string[]], void>} hotAcceptWithoutCallback - */ + module = cacheModule; + } + this._modules.set(identifier, module); + this.modules.add(module); + if (this._backCompat) + ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); + if (currentProfile !== undefined) { + currentProfile.markIntegrationEnd(); + } + callback(null, module); + }); + } -/** @type {WeakMap} */ -const parserHooksMap = new WeakMap(); + /** + * Fetches a module from a compilation by its identifier + * @param {Module} module the module provided + * @returns {Module} the module requested + */ + getModule(module) { + const identifier = module.identifier(); + return this._modules.get(identifier); + } -class HotModuleReplacementPlugin { /** - * @param {JavascriptParser} parser the parser - * @returns {HMRJavascriptParserHooks} the attached hooks + * Attempts to search for a module by its identifier + * @param {string} identifier identifier (usually path) for module + * @returns {Module|undefined} attempt to search for module and return it, else undefined */ - 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; + findModule(identifier) { + return this._modules.get(identifier); } - constructor(options) { - this.options = options || {}; + /** + * Schedules a build of the module object + * + * @param {Module} module module to be built + * @param {ModuleCallback} callback the callback + * @returns {void} + */ + buildModule(module, callback) { + this.buildQueue.add(module, callback); } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * Builds the module object + * + * @param {Module} module module to be built + * @param {ModuleCallback} callback the callback * @returns {void} */ - apply(compiler) { - const { _backCompat: backCompat } = compiler; - if (compiler.options.output.strictModuleErrorHandling === undefined) - compiler.options.output.strictModuleErrorHandling = true; - const runtimeRequirements = [RuntimeGlobals.module]; + _buildModule(module, callback) { + const currentProfile = this.profile + ? this.moduleGraph.getProfile(module) + : undefined; + if (currentProfile !== undefined) { + currentProfile.markBuildingStart(); + } - const createAcceptHandler = (parser, ParamDependency) => { - const { hotAcceptCallback, hotAcceptWithoutCallback } = - HotModuleReplacementPlugin.getParserHooks(parser); + module.needBuild( + { + compilation: this, + fileSystemInfo: this.fileSystemInfo, + valueCacheVersions: this.valueCacheVersions + }, + (err, needBuild) => { + if (err) return callback(err); - 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 (!needBuild) { + if (currentProfile !== undefined) { + currentProfile.markBuildingEnd(); } - 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; + this.hooks.stillValidModule.call(module); + return callback(); + } + + this.hooks.buildModule.call(module); + this.builtModules.add(module); + module.build( + this.options, + this, + this.resolverFactory.get("normal", module.resolveOptions), + this.inputFileSystem, + err => { + if (currentProfile !== undefined) { + currentProfile.markBuildingEnd(); } + if (err) { + this.hooks.failedModule.call(module, err); + return callback(err); + } + if (currentProfile !== undefined) { + currentProfile.markStoringStart(); + } + this._modulesCache.store(module.identifier(), null, module, err => { + if (currentProfile !== undefined) { + currentProfile.markStoringEnd(); + } + if (err) { + this.hooks.failedModule.call(module, err); + return callback(new ModuleStoreError(module, err)); + } + this.hooks.succeedModule.call(module); + return callback(); + }); } - } - 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()); + /** + * @param {Module} module to be processed for deps + * @param {ModuleCallback} callback callback to be triggered + * @returns {void} + */ + processModuleDependencies(module, callback) { + this.processDependenciesQueue.add(module, callback); + } + + /** + * @param {Module} module to be processed for deps + * @returns {void} + */ + processModuleDependenciesNonRecursive(module) { + const processDependenciesBlock = block => { + if (block.dependencies) { + let i = 0; + for (const dep of block.dependencies) { + this.moduleGraph.setParents(dep, block, module, i++); } - 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; + if (block.blocks) { + for (const b of block.blocks) processDependenciesBlock(b); + } }; - 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; - }; + processDependenciesBlock(module); + } - 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)); - }; + /** + * @param {Module} module to be processed for deps + * @param {ModuleCallback} callback callback to be triggered + * @returns {void} + */ + _processModuleDependencies(module, callback) { + /** @type {Array<{factory: ModuleFactory, dependencies: Dependency[], originModule: Module|null}>} */ + const sortedDependencies = []; - 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)); - }; + /** @type {DependenciesBlock} */ + let currentBlock; - 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; + /** @type {Map>} */ + let dependencies; + /** @type {DepConstructor} */ + let factoryCacheKey; + /** @type {ModuleFactory} */ + let factoryCacheKey2; + /** @type {Map} */ + let factoryCacheValue; + /** @type {string} */ + let listCacheKey1; + /** @type {string} */ + let listCacheKey2; + /** @type {Dependency[]} */ + let listCacheValue; - //#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 + let inProgressSorting = 1; + let inProgressTransitive = 1; - //#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 + const onDependenciesSorted = err => { + if (err) return callback(err); - let hotIndex = 0; - const fullHashChunkModuleHashes = {}; - const chunkModuleHashes = {}; + // early exit without changing parallelism back and forth + if (sortedDependencies.length === 0 && inProgressTransitive === 1) { + return callback(); + } - 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.chunkHashes = {}; - records.chunkRuntime = {}; - for (const chunk of compilation.chunks) { - records.chunkHashes[chunk.id] = chunk.hash; - records.chunkRuntime[chunk.id] = getRuntimeKey(chunk.runtime); + // This is nested so we need to allow one additional task + this.processDependenciesQueue.increaseParallelism(); + + for (const item of sortedDependencies) { + inProgressTransitive++; + this.handleModuleCreation(item, err => { + // In V8, the Error objects keep a reference to the functions on the stack. These warnings & + // errors are created inside closures that keep a reference to the Compilation, so errors are + // leaking the Compilation object. + if (err && this.bail) { + if (inProgressTransitive <= 0) return; + inProgressTransitive = -1; + // eslint-disable-next-line no-self-assign + err.stack = err.stack; + onTransitiveTasksFinished(err); + return; + } + if (--inProgressTransitive === 0) onTransitiveTasksFinished(); + }); + } + if (--inProgressTransitive === 0) onTransitiveTasksFinished(); + }; + + const onTransitiveTasksFinished = err => { + if (err) return callback(err); + this.processDependenciesQueue.decreaseParallelism(); + + return callback(); + }; + + /** + * @param {Dependency} dep dependency + * @param {number} index index in block + * @returns {void} + */ + const processDependency = (dep, index) => { + this.moduleGraph.setParents(dep, currentBlock, module, index); + if (this._unsafeCache) { + try { + const unsafeCachedModule = unsafeCacheDependencies.get(dep); + if (unsafeCachedModule === null) return; + if (unsafeCachedModule !== undefined) { + if ( + this._restoredUnsafeCacheModuleEntries.has(unsafeCachedModule) + ) { + this._handleExistingModuleFromUnsafeCache( + module, + dep, + unsafeCachedModule + ); + return; } - records.chunkModuleIds = {}; - for (const chunk of compilation.chunks) { - records.chunkModuleIds[chunk.id] = Array.from( - chunkGraph.getOrderedChunkModulesIterable( - chunk, - compareModulesById(chunkGraph) - ), - m => chunkGraph.getModuleId(m) + const identifier = unsafeCachedModule.identifier(); + const cachedModule = + this._restoredUnsafeCacheEntries.get(identifier); + if (cachedModule !== undefined) { + // update unsafe cache to new module + unsafeCacheDependencies.set(dep, cachedModule); + this._handleExistingModuleFromUnsafeCache( + module, + dep, + cachedModule ); + return; } - } - ); - /** @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); + inProgressSorting++; + this._modulesCache.get(identifier, null, (err, cachedModule) => { + if (err) { + if (inProgressSorting <= 0) return; + inProgressSorting = -1; + onDependenciesSorted(err); + return; } - } - 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; - } + try { + if (!this._restoredUnsafeCacheEntries.has(identifier)) { + const data = unsafeCacheData.get(cachedModule); + if (data === undefined) { + processDependencyForResolving(dep); + if (--inProgressSorting === 0) onDependenciesSorted(); + return; } - } 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; + if (cachedModule !== unsafeCachedModule) { + unsafeCacheDependencies.set(dep, cachedModule); } - } - } 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.chunkHashes || - !records.chunkModuleIds - ) { - return; - } - for (const [module, chunk] of fullHashModules) { - const key = `${chunk.id}|${module.identifier()}`; - const hash = nonCodeGeneratedModules.has(module, chunk.runtime) - ? chunkGraph.getModuleHash(module, chunk.runtime) - : compilation.codeGenerationResults.getHash( - module, - chunk.runtime - ); - if (records.chunkModuleHashes[key] !== hash) { - updatedModules.add(module, chunk); - } - chunkModuleHashes[key] = hash; - } - - /** @type {Map, removedChunkIds: Set, removedModules: Set, 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} */ - 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} */ - const completelyRemovedModules = new Set(); - - for (const key of Object.keys(records.chunkHashes)) { - const oldRuntime = keyToRuntime(records.chunkRuntime[key]); - /** @type {Module[]} */ - const remainingModules = []; - // Check which modules are removed - for (const id of records.chunkModuleIds[key]) { - const module = allModules.get(id); - if (module === undefined) { - completelyRemovedModules.add(id); - } else { - remainingModules.push(module); - } - } - - let chunkId; - let newModules; - let newRuntimeModules; - let newFullHashModules; - let newDependentHashModules; - let newRuntime; - let removedFromRuntime; - const currentChunk = find( - compilation.chunks, - chunk => `${chunk.id}` === key - ); - if (currentChunk) { - chunkId = currentChunk.id; - newRuntime = intersectRuntime( - currentChunk.runtime, - allOldRuntime - ); - if (newRuntime === undefined) continue; - newModules = chunkGraph - .getChunkModules(currentChunk) - .filter(module => updatedModules.has(module, currentChunk)); - newRuntimeModules = Array.from( - chunkGraph.getChunkRuntimeModulesIterable(currentChunk) - ).filter(module => updatedModules.has(module, currentChunk)); - const fullHashModules = - chunkGraph.getChunkFullHashModulesIterable(currentChunk); - newFullHashModules = - fullHashModules && - Array.from(fullHashModules).filter(module => - updatedModules.has(module, currentChunk) + cachedModule.restoreFromUnsafeCache( + data, + this.params.normalModuleFactory, + this.params ); - const dependentHashModules = - chunkGraph.getChunkDependentHashModulesIterable(currentChunk); - newDependentHashModules = - dependentHashModules && - Array.from(dependentHashModules).filter(module => - updatedModules.has(module, currentChunk) + this._restoredUnsafeCacheEntries.set( + identifier, + cachedModule ); - 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; + this._restoredUnsafeCacheModuleEntries.add(cachedModule); + if (!this.modules.has(cachedModule)) { + inProgressTransitive++; + this._handleNewModuleFromUnsafeCache( + module, + dep, + cachedModule, + err => { + if (err) { + if (inProgressTransitive <= 0) return; + inProgressTransitive = -1; + onTransitiveTasksFinished(err); } + if (--inProgressTransitive === 0) + return onTransitiveTasksFinished(); } - hotUpdateMainContentByRuntime - .get(runtime) - .removedModules.add(module); - }); + ); + if (--inProgressSorting === 0) onDependenciesSorted(); + return; } } - } - if ( - (newModules && newModules.length > 0) || - (newRuntimeModules && newRuntimeModules.length > 0) - ) { - const hotUpdateChunk = new HotUpdateChunk(); - if (backCompat) - ChunkGraph.setChunkGraphForChunk(hotUpdateChunk, chunkGraph); - hotUpdateChunk.id = chunkId; - hotUpdateChunk.runtime = newRuntime; - if (currentChunk) { - for (const group of currentChunk.groupsIterable) - hotUpdateChunk.addGroup(group); - } - chunkGraph.attachModules(hotUpdateChunk, newModules || []); - chunkGraph.attachRuntimeModules( - hotUpdateChunk, - newRuntimeModules || [] - ); - if (newFullHashModules) { - chunkGraph.attachFullHashModules( - hotUpdateChunk, - newFullHashModules - ); - } - if (newDependentHashModules) { - chunkGraph.attachDependentHashModules( - hotUpdateChunk, - newDependentHashModules - ); - } - const renderManifest = compilation.getRenderManifest({ - chunk: hotUpdateChunk, - hash: records.hash, - fullHash: records.hash, - outputOptions: compilation.outputOptions, - moduleTemplates: compilation.moduleTemplates, - dependencyTemplates: compilation.dependencyTemplates, - codeGenerationResults: compilation.codeGenerationResults, - runtimeTemplate: compilation.runtimeTemplate, - moduleGraph: compilation.moduleGraph, - chunkGraph - }); - for (const entry of renderManifest) { - /** @type {string} */ - let filename; - /** @type {AssetInfo} */ - let assetInfo; - if ("filename" in entry) { - filename = entry.filename; - assetInfo = entry.info; - } else { - ({ path: filename, info: assetInfo } = - compilation.getPathWithInfo( - entry.filenameTemplate, - entry.pathOptions - )); - } - const source = entry.render(); - compilation.additionalChunkAssets.push(filename); - compilation.emitAsset(filename, source, { - hotModuleReplacement: true, - ...assetInfo - }); - if (currentChunk) { - currentChunk.files.add(filename); - compilation.hooks.chunkAsset.call(currentChunk, filename); - } + if (unsafeCachedModule !== cachedModule) { + unsafeCacheDependencies.set(dep, cachedModule); } - 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; + this._handleExistingModuleFromUnsafeCache( + module, + dep, + cachedModule + ); // a3 + } catch (err) { + if (inProgressSorting <= 0) return; + inProgressSorting = -1; + onDependenciesSorted(err); + return; } - 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 - }); - } + if (--inProgressSorting === 0) onDependenciesSorted(); + }); + return; } - ); + } catch (e) { + console.error(e); + } + } + processDependencyForResolving(dep); + }; - 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() + /** + * @param {Dependency} dep dependency + * @returns {void} + */ + const processDependencyForResolving = dep => { + const resourceIdent = dep.getResourceIdentifier(); + if (resourceIdent !== undefined && resourceIdent !== null) { + const category = dep.category; + const constructor = /** @type {DepConstructor} */ (dep.constructor); + if (factoryCacheKey === constructor) { + // Fast path 1: same constructor as prev item + if (listCacheKey1 === category && listCacheKey2 === resourceIdent) { + // Super fast path 1: also same resource + listCacheValue.push(dep); + return; + } + } else { + const factory = this.dependencyFactories.get(constructor); + if (factory === undefined) { + throw new Error( + `No module factory available for dependency type: ${constructor.name}` ); } - ); - - 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; + if (factoryCacheKey2 === factory) { + // Fast path 2: same factory as prev item + factoryCacheKey = constructor; + if (listCacheKey1 === category && listCacheKey2 === resourceIdent) { + // Super fast path 2: also same resource + listCacheValue.push(dep); + return; + } + } else { + // Slow path + if (factoryCacheKey2 !== undefined) { + // Archive last cache entry + if (dependencies === undefined) dependencies = new Map(); + dependencies.set(factoryCacheKey2, factoryCacheValue); + factoryCacheValue = dependencies.get(factory); + if (factoryCacheValue === undefined) { + factoryCacheValue = new Map(); + } + } else { + factoryCacheValue = new Map(); + } + factoryCacheKey = constructor; + factoryCacheKey2 = factory; } - ); + } + // Here webpack is using heuristic that assumes + // mostly esm dependencies would be used + // so we don't allocate extra string for them + const cacheKey = + category === esmDependencyCategory + ? resourceIdent + : `${category}${resourceIdent}`; + let list = factoryCacheValue.get(cacheKey); + if (list === undefined) { + factoryCacheValue.set(cacheKey, (list = [])); + sortedDependencies.push({ + factory: factoryCacheKey2, + dependencies: list, + originModule: module + }); + } + list.push(dep); + listCacheKey1 = category; + listCacheKey2 = resourceIdent; + listCacheValue = list; } - ); - } -} - -module.exports = HotModuleReplacementPlugin; + }; + try { + /** @type {DependenciesBlock[]} */ + const queue = [module]; + do { + const block = queue.pop(); + if (block.dependencies) { + currentBlock = block; + let i = 0; + for (const dep of block.dependencies) processDependency(dep, i++); + } + if (block.blocks) { + for (const b of block.blocks) queue.push(b); + } + } while (queue.length !== 0); + } catch (e) { + return callback(e); + } -/***/ }), + if (--inProgressSorting === 0) onDependenciesSorted(); + } -/***/ 9597: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + _handleNewModuleFromUnsafeCache(originModule, dependency, module, callback) { + const moduleGraph = this.moduleGraph; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + moduleGraph.setResolvedModule(originModule, dependency, module); + moduleGraph.setIssuerIfUnset( + module, + originModule !== undefined ? originModule : null + ); + this._modules.set(module.identifier(), module); + this.modules.add(module); + if (this._backCompat) + ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); -const Chunk = __webpack_require__(39385); + this._handleModuleBuildAndDependencies( + originModule, + module, + true, + callback + ); + } -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./util/Hash")} Hash */ + _handleExistingModuleFromUnsafeCache(originModule, dependency, module) { + const moduleGraph = this.moduleGraph; -class HotUpdateChunk extends Chunk { - constructor() { - super(); + moduleGraph.setResolvedModule(originModule, dependency, module); } -} -module.exports = HotUpdateChunk; + /** + * @typedef {Object} HandleModuleCreationOptions + * @property {ModuleFactory} factory + * @property {Dependency[]} dependencies + * @property {Module | null} originModule + * @property {Partial=} contextInfo + * @property {string=} context + * @property {boolean=} recursive recurse into dependencies of the created module + * @property {boolean=} connectOrigin connect the resolved module with the origin module + */ + /** + * @param {HandleModuleCreationOptions} options options object + * @param {ModuleCallback} callback callback + * @returns {void} + */ + handleModuleCreation( + { + factory, + dependencies, + originModule, + contextInfo, + context, + recursive = true, + connectOrigin = recursive + }, + callback + ) { + const moduleGraph = this.moduleGraph; -/***/ }), + const currentProfile = this.profile ? new ModuleProfile() : undefined; -/***/ 3: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.factorizeModule( + { + currentProfile, + factory, + dependencies, + factoryResult: true, + originModule, + contextInfo, + context + }, + (err, factoryResult) => { + const applyFactoryResultDependencies = () => { + const { fileDependencies, contextDependencies, missingDependencies } = + factoryResult; + if (fileDependencies) { + this.fileDependencies.addAll(fileDependencies); + } + if (contextDependencies) { + this.contextDependencies.addAll(contextDependencies); + } + if (missingDependencies) { + this.missingDependencies.addAll(missingDependencies); + } + }; + if (err) { + if (factoryResult) applyFactoryResultDependencies(); + if (dependencies.every(d => d.optional)) { + this.warnings.push(err); + return callback(); + } else { + this.errors.push(err); + return callback(err); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ + const newModule = factoryResult.module; + if (!newModule) { + applyFactoryResultDependencies(); + return callback(); + } + if (currentProfile !== undefined) { + moduleGraph.setProfile(newModule, currentProfile); + } -const ModuleFactory = __webpack_require__(51010); + this.addModule(newModule, (err, module) => { + if (err) { + applyFactoryResultDependencies(); + if (!err.module) { + err.module = module; + } + this.errors.push(err); -/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ + return callback(err); + } -/** - * Ignores error when module is unresolved - */ -class IgnoreErrorModuleFactory extends ModuleFactory { - /** - * @param {NormalModuleFactory} normalModuleFactory normalModuleFactory instance - */ - constructor(normalModuleFactory) { - super(); + if ( + this._unsafeCache && + factoryResult.cacheable !== false && + /** @type {any} */ (module).restoreFromUnsafeCache && + this._unsafeCachePredicate(module) + ) { + const unsafeCacheableModule = + /** @type {Module & { restoreFromUnsafeCache: Function }} */ ( + module + ); + for (let i = 0; i < dependencies.length; i++) { + const dependency = dependencies[i]; + moduleGraph.setResolvedModule( + connectOrigin ? originModule : null, + dependency, + unsafeCacheableModule + ); + unsafeCacheDependencies.set(dependency, unsafeCacheableModule); + } + if (!unsafeCacheData.has(unsafeCacheableModule)) { + unsafeCacheData.set( + unsafeCacheableModule, + unsafeCacheableModule.getUnsafeCacheData() + ); + } + } else { + applyFactoryResultDependencies(); + for (let i = 0; i < dependencies.length; i++) { + const dependency = dependencies[i]; + moduleGraph.setResolvedModule( + connectOrigin ? originModule : null, + dependency, + module + ); + } + } - this.normalModuleFactory = normalModuleFactory; - } + moduleGraph.setIssuerIfUnset( + module, + originModule !== undefined ? originModule : null + ); + if (module !== newModule) { + if (currentProfile !== undefined) { + const otherProfile = moduleGraph.getProfile(module); + if (otherProfile !== undefined) { + currentProfile.mergeInto(otherProfile); + } else { + moduleGraph.setProfile(module, currentProfile); + } + } + } - /** - * @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); - }); + this._handleModuleBuildAndDependencies( + originModule, + module, + recursive, + callback + ); + }); + } + ); } -} -module.exports = IgnoreErrorModuleFactory; + _handleModuleBuildAndDependencies(originModule, module, recursive, callback) { + // Check for cycles when build is trigger inside another build + let creatingModuleDuringBuildSet = undefined; + if (!recursive && this.buildQueue.isProcessing(originModule)) { + // Track build dependency + creatingModuleDuringBuildSet = + this.creatingModuleDuringBuild.get(originModule); + if (creatingModuleDuringBuildSet === undefined) { + creatingModuleDuringBuildSet = new Set(); + this.creatingModuleDuringBuild.set( + originModule, + creatingModuleDuringBuildSet + ); + } + creatingModuleDuringBuildSet.add(module); + // When building is blocked by another module + // search for a cycle, cancel the cycle by throwing + // an error (otherwise this would deadlock) + const blockReasons = this.creatingModuleDuringBuild.get(module); + if (blockReasons !== undefined) { + const set = new Set(blockReasons); + for (const item of set) { + const blockReasons = this.creatingModuleDuringBuild.get(item); + if (blockReasons !== undefined) { + for (const m of blockReasons) { + if (m === module) { + return callback(new BuildCycleError(module)); + } + set.add(m); + } + } + } + } + } -/***/ }), + this.buildModule(module, err => { + if (creatingModuleDuringBuildSet !== undefined) { + creatingModuleDuringBuildSet.delete(module); + } + if (err) { + if (!err.module) { + err.module = module; + } + this.errors.push(err); -/***/ 84808: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + return callback(err); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (!recursive) { + this.processModuleDependenciesNonRecursive(module); + callback(null, module); + return; + } + // This avoids deadlocks for circular dependencies + if (this.processDependenciesQueue.isProcessing(module)) { + return callback(); + } + this.processModuleDependencies(module, err => { + if (err) { + return callback(err); + } + callback(null, module); + }); + }); + } -const createSchemaValidation = __webpack_require__(32540); + /** + * @param {FactorizeModuleOptions} options options object + * @param {ModuleOrFactoryResultCallback} callback callback + * @returns {void} + */ + _factorizeModule( + { + currentProfile, + factory, + dependencies, + originModule, + factoryResult, + contextInfo, + context + }, + callback + ) { + if (currentProfile !== undefined) { + currentProfile.markFactoryStart(); + } + factory.create( + { + contextInfo: { + issuer: originModule ? originModule.nameForCondition() : "", + issuerLayer: originModule ? originModule.layer : null, + compiler: this.compiler.name, + ...contextInfo + }, + resolveOptions: originModule ? originModule.resolveOptions : undefined, + context: context + ? context + : originModule + ? originModule.context + : this.compiler.context, + dependencies: dependencies + }, + (err, result) => { + if (result) { + // TODO webpack 6: remove + // For backward-compat + if (result.module === undefined && result instanceof Module) { + result = { + module: result + }; + } + if (!factoryResult) { + const { + fileDependencies, + contextDependencies, + missingDependencies + } = result; + if (fileDependencies) { + this.fileDependencies.addAll(fileDependencies); + } + if (contextDependencies) { + this.contextDependencies.addAll(contextDependencies); + } + if (missingDependencies) { + this.missingDependencies.addAll(missingDependencies); + } + } + } + if (err) { + const notFoundError = new ModuleNotFoundError( + originModule, + err, + dependencies.map(d => d.loc).filter(Boolean)[0] + ); + return callback(notFoundError, factoryResult ? result : undefined); + } + if (!result) { + return callback(); + } -/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./NormalModuleFactory").ResolveData} ResolveData */ + if (currentProfile !== undefined) { + currentProfile.markFactoryEnd(); + } -const validate = createSchemaValidation( - __webpack_require__(20858), - () => __webpack_require__(3098), - { - name: "Ignore Plugin", - baseDataPath: "options" + callback(null, factoryResult ? result : result.module); + } + ); } -); -class IgnorePlugin { /** - * @param {IgnorePluginOptions} options IgnorePlugin options + * @param {string} context context string path + * @param {Dependency} dependency dependency used to create Module chain + * @param {ModuleCallback} callback callback for when module chain is complete + * @returns {void} will throw if dependency instance is not a valid Dependency */ - constructor(options) { - validate(options); - this.options = options; - - /** @private @type {Function} */ - this.checkIgnore = this.checkIgnore.bind(this); + addModuleChain(context, dependency, callback) { + return this.addModuleTree({ context, dependency }, callback); } /** - * Note that if "contextRegExp" is given, both the "resourceRegExp" - * and "contextRegExp" have to match. - * - * @param {ResolveData} resolveData resolve data - * @returns {false|undefined} returns false when the request should be ignored, otherwise undefined + * @param {Object} options options + * @param {string} options.context context string path + * @param {Dependency} options.dependency dependency used to create Module chain + * @param {Partial=} options.contextInfo additional context info for the root module + * @param {ModuleCallback} callback callback for when module chain is complete + * @returns {void} will throw if dependency instance is not a valid Dependency */ - checkIgnore(resolveData) { + addModuleTree({ context, dependency, contextInfo }, callback) { if ( - "checkResource" in this.options && - this.options.checkResource && - this.options.checkResource(resolveData.request, resolveData.context) + typeof dependency !== "object" || + dependency === null || + !dependency.constructor ) { - return false; + return callback( + new WebpackError("Parameter 'dependency' must be a Dependency") + ); + } + const Dep = /** @type {DepConstructor} */ (dependency.constructor); + const moduleFactory = this.dependencyFactories.get(Dep); + if (!moduleFactory) { + return callback( + new WebpackError( + `No dependency factory available for this dependency type: ${dependency.constructor.name}` + ) + ); } - 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; + this.handleModuleCreation( + { + factory: moduleFactory, + dependencies: [dependency], + originModule: null, + contextInfo, + context + }, + (err, result) => { + if (err && this.bail) { + callback(err); + this.buildQueue.stop(); + this.rebuildQueue.stop(); + this.processDependenciesQueue.stop(); + this.factorizeQueue.stop(); + } else if (!err && result) { + callback(null, result); + } else { + callback(); } - } else { - return false; } - } + ); } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {string} context context path for entry + * @param {Dependency} entry entry dependency that should be followed + * @param {string | EntryOptions} optionsOrName options or deprecated name of entry + * @param {ModuleCallback} callback callback function + * @returns {void} returns */ - 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; - - -/***/ }), - -/***/ 7373: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - + addEntry(context, entry, optionsOrName, callback) { + // TODO webpack 6 remove + const options = + typeof optionsOrName === "object" + ? optionsOrName + : { name: optionsOrName }; -/** @typedef {import("../declarations/WebpackOptions").IgnoreWarningsNormalized} IgnoreWarningsNormalized */ -/** @typedef {import("./Compiler")} Compiler */ + this._addEntryItem(context, entry, "dependencies", options, callback); + } -class IgnoreWarningsPlugin { /** - * @param {IgnoreWarningsNormalized} ignoreWarnings conditions to ignore warnings + * @param {string} context context path for entry + * @param {Dependency} dependency dependency that should be followed + * @param {EntryOptions} options options + * @param {ModuleCallback} callback callback function + * @returns {void} returns */ - constructor(ignoreWarnings) { - this._ignoreWarnings = ignoreWarnings; + addInclude(context, dependency, options, callback) { + this._addEntryItem( + context, + dependency, + "includeDependencies", + options, + callback + ); } + /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {string} context context path for entry + * @param {Dependency} entry entry dependency that should be followed + * @param {"dependencies" | "includeDependencies"} target type of entry + * @param {EntryOptions} options options + * @param {ModuleCallback} callback callback function + * @returns {void} returns */ - 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) - ); - }); + _addEntryItem(context, entry, target, options, callback) { + const { name } = options; + let entryData = + name !== undefined ? this.entries.get(name) : this.globalEntry; + if (entryData === undefined) { + entryData = { + dependencies: [], + includeDependencies: [], + options: { + name: undefined, + ...options } - ); - }); - } -} - -module.exports = IgnoreWarningsPlugin; - - -/***/ }), - -/***/ 55870: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ - - - -const { ConcatSource } = __webpack_require__(51255); -const makeSerializable = __webpack_require__(33032); - -/** @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]; + }; + entryData[target].push(entry); + this.entries.set(name, entryData); + } else { + entryData[target].push(entry); + for (const key of Object.keys(options)) { + if (options[key] === undefined) continue; + if (entryData.options[key] === options[key]) continue; + if ( + Array.isArray(entryData.options[key]) && + Array.isArray(options[key]) && + arrayEquals(entryData.options[key], options[key]) + ) { + continue; + } + if (entryData.options[key] === undefined) { + entryData.options[key] = options[key]; + } else { + return callback( + new WebpackError( + `Conflicting entry option ${key} = ${entryData.options[key]} vs ${options[key]}` + ) + ); + } + } + } -/** - * @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; -}; + this.hooks.addEntry.call(entry, options); -/** - * @template Context - */ -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; + this.addModuleTree( + { + context, + dependency: entry, + contextInfo: entryData.options.layer + ? { issuerLayer: entryData.options.layer } + : undefined + }, + (err, module) => { + if (err) { + this.hooks.failedEntry.call(entry, options, err); + return callback(err); + } + this.hooks.succeedEntry.call(entry, options, module); + return callback(null, module); + } + ); } /** - * @param {Context} context context - * @returns {string|Source} the source code that will be included as initialization code + * @param {Module} module module to be rebuilt + * @param {ModuleCallback} callback callback when module finishes rebuilding + * @returns {void} */ - getContent(context) { - return this.content; + rebuildModule(module, callback) { + this.rebuildQueue.add(module, callback); } /** - * @param {Context} context context - * @returns {string|Source=} the source code that will be included at the end of the module + * @param {Module} module module to be rebuilt + * @param {ModuleCallback} callback callback when module finishes rebuilding + * @returns {void} */ - getEndContent(context) { - return this.endContent; - } - - static addToSource(source, initFragments, context) { - 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); + _rebuildModule(module, callback) { + this.hooks.rebuildModule.call(module); + const oldDependencies = module.dependencies.slice(); + const oldBlocks = module.blocks.slice(); + module.invalidateBuild(); + this.buildQueue.invalidate(module); + this.buildModule(module, err => { + if (err) { + return this.hooks.finishRebuildingModule.callAsync(module, err2 => { + if (err2) { + callback( + makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule") + ); + return; + } + callback(err); + }); + } - // Deduplicate fragments. If a fragment has no key, it is always included. - const keyedFragments = new Map(); - for (const [fragment] of sortedFragments) { - if (typeof fragment.mergeAll === "function") { - if (!fragment.key) { - throw new Error( - `InitFragment with mergeAll function must have a valid key: ${fragment.constructor.name}` + this.processDependenciesQueue.invalidate(module); + this.moduleGraph.unfreeze(); + this.processModuleDependencies(module, err => { + if (err) return callback(err); + this.removeReasonsOfDependencyBlock(module, { + dependencies: oldDependencies, + blocks: oldBlocks + }); + this.hooks.finishRebuildingModule.callAsync(module, err2 => { + if (err2) { + callback( + makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule") ); + return; } - const oldValue = keyedFragments.get(fragment.key); - if (oldValue === undefined) { - keyedFragments.set(fragment.key, fragment); - } else if (Array.isArray(oldValue)) { - oldValue.push(fragment); + callback(null, module); + }); + }); + }); + } + + _computeAffectedModules(modules) { + const moduleMemCacheCache = this.compiler.moduleMemCaches; + if (!moduleMemCacheCache) return; + if (!this.moduleMemCaches) { + this.moduleMemCaches = new Map(); + this.moduleGraph.setModuleMemCaches(this.moduleMemCaches); + } + const { moduleGraph, moduleMemCaches } = this; + const affectedModules = new Set(); + const infectedModules = new Set(); + let statNew = 0; + let statChanged = 0; + let statUnchanged = 0; + let statReferencesChanged = 0; + let statWithoutBuild = 0; + + const computeReferences = module => { + /** @type {WeakMap} */ + let references = undefined; + for (const connection of moduleGraph.getOutgoingConnections(module)) { + const d = connection.dependency; + const m = connection.module; + if (!d || !m || unsafeCacheDependencies.has(d)) continue; + if (references === undefined) references = new WeakMap(); + references.set(d, m); + } + return references; + }; + + /** + * @param {Module} module the module + * @param {WeakMap} references references + * @returns {boolean} true, when the references differ + */ + const compareReferences = (module, references) => { + if (references === undefined) return true; + for (const connection of moduleGraph.getOutgoingConnections(module)) { + const d = connection.dependency; + if (!d) continue; + const entry = references.get(d); + if (entry === undefined) continue; + if (entry !== connection.module) return false; + } + return true; + }; + + const modulesWithoutCache = new Set(modules); + for (const [module, cachedMemCache] of moduleMemCacheCache) { + if (modulesWithoutCache.has(module)) { + const buildInfo = module.buildInfo; + if (buildInfo) { + if (cachedMemCache.buildInfo !== buildInfo) { + // use a new one + const memCache = new WeakTupleMap(); + moduleMemCaches.set(module, memCache); + affectedModules.add(module); + cachedMemCache.buildInfo = buildInfo; + cachedMemCache.references = computeReferences(module); + cachedMemCache.memCache = memCache; + statChanged++; + } else if (!compareReferences(module, cachedMemCache.references)) { + // use a new one + const memCache = new WeakTupleMap(); + moduleMemCaches.set(module, memCache); + affectedModules.add(module); + cachedMemCache.references = computeReferences(module); + cachedMemCache.memCache = memCache; + statReferencesChanged++; } else { - keyedFragments.set(fragment.key, [oldValue, fragment]); - } - continue; - } else if (typeof fragment.merge === "function") { - const oldValue = keyedFragments.get(fragment.key); - if (oldValue !== undefined) { - keyedFragments.set(fragment.key, fragment.merge(oldValue)); - continue; + // keep the old mem cache + moduleMemCaches.set(module, cachedMemCache.memCache); + statUnchanged++; } + } else { + infectedModules.add(module); + moduleMemCacheCache.delete(module); + statWithoutBuild++; } - keyedFragments.set(fragment.key || Symbol(), fragment); + modulesWithoutCache.delete(module); + } else { + moduleMemCacheCache.delete(module); } + } - const concatSource = new ConcatSource(); - const endContents = []; - for (let fragment of keyedFragments.values()) { - if (Array.isArray(fragment)) { - fragment = fragment[0].mergeAll(fragment); + for (const module of modulesWithoutCache) { + const buildInfo = module.buildInfo; + if (buildInfo) { + // create a new entry + const memCache = new WeakTupleMap(); + moduleMemCacheCache.set(module, { + buildInfo, + references: computeReferences(module), + memCache + }); + moduleMemCaches.set(module, memCache); + affectedModules.add(module); + statNew++; + } else { + infectedModules.add(module); + statWithoutBuild++; + } + } + + const reduceAffectType = connections => { + let affected = false; + for (const { dependency } of connections) { + if (!dependency) continue; + const type = dependency.couldAffectReferencingModule(); + if (type === Dependency.TRANSITIVE) return Dependency.TRANSITIVE; + if (type === false) continue; + affected = true; + } + return affected; + }; + const directOnlyInfectedModules = new Set(); + for (const module of infectedModules) { + for (const [ + referencingModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if (!referencingModule) continue; + if (infectedModules.has(referencingModule)) continue; + const type = reduceAffectType(connections); + if (!type) continue; + if (type === true) { + directOnlyInfectedModules.add(referencingModule); + } else { + infectedModules.add(referencingModule); } - concatSource.add(fragment.getContent(context)); - const endContent = fragment.getEndContent(context); - if (endContent) { - endContents.push(endContent); + } + } + for (const module of directOnlyInfectedModules) infectedModules.add(module); + const directOnlyAffectModules = new Set(); + for (const module of affectedModules) { + for (const [ + referencingModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if (!referencingModule) continue; + if (infectedModules.has(referencingModule)) continue; + if (affectedModules.has(referencingModule)) continue; + const type = reduceAffectType(connections); + if (!type) continue; + if (type === true) { + directOnlyAffectModules.add(referencingModule); + } else { + affectedModules.add(referencingModule); } + const memCache = new WeakTupleMap(); + const cache = moduleMemCacheCache.get(referencingModule); + cache.memCache = memCache; + moduleMemCaches.set(referencingModule, memCache); } + } + for (const module of directOnlyAffectModules) affectedModules.add(module); + this.logger.log( + `${Math.round( + (100 * (affectedModules.size + infectedModules.size)) / + this.modules.size + )}% (${affectedModules.size} affected + ${ + infectedModules.size + } infected of ${ + this.modules.size + }) modules flagged as affected (${statNew} new modules, ${statChanged} changed, ${statReferencesChanged} references changed, ${statUnchanged} unchanged, ${statWithoutBuild} were not built)` + ); + } - concatSource.add(source); - for (const content of endContents.reverse()) { - concatSource.add(content); + _computeAffectedModulesWithChunkGraph() { + const { moduleMemCaches } = this; + if (!moduleMemCaches) return; + const moduleMemCaches2 = (this.moduleMemCaches2 = new Map()); + const { moduleGraph, chunkGraph } = this; + const key = "memCache2"; + let statUnchanged = 0; + let statChanged = 0; + let statNew = 0; + /** + * @param {Module} module module + * @returns {{ id: string | number, modules?: Map, blocks?: (string | number)[] }} references + */ + const computeReferences = module => { + const id = chunkGraph.getModuleId(module); + /** @type {Map} */ + let modules = undefined; + /** @type {(string | number)[] | undefined} */ + let blocks = undefined; + const outgoing = moduleGraph.getOutgoingConnectionsByModule(module); + if (outgoing !== undefined) { + for (const m of outgoing.keys()) { + if (!m) continue; + if (modules === undefined) modules = new Map(); + modules.set(m, chunkGraph.getModuleId(m)); + } + } + if (module.blocks.length > 0) { + blocks = []; + const queue = Array.from(module.blocks); + for (const block of queue) { + const chunkGroup = chunkGraph.getBlockChunkGroup(block); + if (chunkGroup) { + for (const chunk of chunkGroup.chunks) { + blocks.push(chunk.id); + } + } else { + blocks.push(null); + } + queue.push.apply(queue, block.blocks); + } + } + return { id, modules, blocks }; + }; + /** + * @param {Module} module module + * @param {Object} references references + * @param {string | number} references.id id + * @param {Map=} references.modules modules + * @param {(string | number)[]=} references.blocks blocks + * @returns {boolean} ok? + */ + const compareReferences = (module, { id, modules, blocks }) => { + if (id !== chunkGraph.getModuleId(module)) return false; + if (modules !== undefined) { + for (const [module, id] of modules) { + if (chunkGraph.getModuleId(module) !== id) return false; + } + } + if (blocks !== undefined) { + const queue = Array.from(module.blocks); + let i = 0; + for (const block of queue) { + const chunkGroup = chunkGraph.getBlockChunkGroup(block); + if (chunkGroup) { + for (const chunk of chunkGroup.chunks) { + if (i >= blocks.length || blocks[i++] !== chunk.id) return false; + } + } else { + if (i >= blocks.length || blocks[i++] !== null) return false; + } + queue.push.apply(queue, block.blocks); + } + if (i !== blocks.length) return false; + } + return true; + }; + + for (const [module, memCache] of moduleMemCaches) { + /** @type {{ references: { id: string | number, modules?: Map, blocks?: (string | number)[]}, memCache: WeakTupleMap }} */ + const cache = memCache.get(key); + if (cache === undefined) { + const memCache2 = new WeakTupleMap(); + memCache.set(key, { + references: computeReferences(module), + memCache: memCache2 + }); + moduleMemCaches2.set(module, memCache2); + statNew++; + } else if (!compareReferences(module, cache.references)) { + const memCache = new WeakTupleMap(); + cache.references = computeReferences(module); + cache.memCache = memCache; + moduleMemCaches2.set(module, memCache); + statChanged++; + } else { + moduleMemCaches2.set(module, cache.memCache); + statUnchanged++; } - return concatSource; - } else { - return source; } + + this.logger.log( + `${Math.round( + (100 * statChanged) / (statNew + statChanged + statUnchanged) + )}% modules flagged as affected by chunk graph (${statNew} new modules, ${statChanged} changed, ${statUnchanged} unchanged)` + ); } - serialize(context) { - const { write } = context; + finish(callback) { + this.factorizeQueue.clear(); + if (this.profile) { + this.logger.time("finish module profiles"); + const ParallelismFactorCalculator = __webpack_require__(50780); + const p = new ParallelismFactorCalculator(); + const moduleGraph = this.moduleGraph; + const modulesWithProfiles = new Map(); + for (const module of this.modules) { + const profile = moduleGraph.getProfile(module); + if (!profile) continue; + modulesWithProfiles.set(module, profile); + p.range( + profile.buildingStartTime, + profile.buildingEndTime, + f => (profile.buildingParallelismFactor = f) + ); + p.range( + profile.factoryStartTime, + profile.factoryEndTime, + f => (profile.factoryParallelismFactor = f) + ); + p.range( + profile.integrationStartTime, + profile.integrationEndTime, + f => (profile.integrationParallelismFactor = f) + ); + p.range( + profile.storingStartTime, + profile.storingEndTime, + f => (profile.storingParallelismFactor = f) + ); + p.range( + profile.restoringStartTime, + profile.restoringEndTime, + f => (profile.restoringParallelismFactor = f) + ); + if (profile.additionalFactoryTimes) { + for (const { start, end } of profile.additionalFactoryTimes) { + const influence = (end - start) / profile.additionalFactories; + p.range( + start, + end, + f => + (profile.additionalFactoriesParallelismFactor += f * influence) + ); + } + } + } + p.calculate(); - write(this.content); - write(this.stage); - write(this.position); - write(this.key); - write(this.endContent); - } + const logger = this.getLogger("webpack.Compilation.ModuleProfile"); + const logByValue = (value, msg) => { + if (value > 1000) { + logger.error(msg); + } else if (value > 500) { + logger.warn(msg); + } else if (value > 200) { + logger.info(msg); + } else if (value > 30) { + logger.log(msg); + } else { + logger.debug(msg); + } + }; + const logNormalSummary = (category, getDuration, getParallelism) => { + let sum = 0; + let max = 0; + for (const [module, profile] of modulesWithProfiles) { + const p = getParallelism(profile); + const d = getDuration(profile); + if (d === 0 || p === 0) continue; + const t = d / p; + sum += t; + if (t <= 10) continue; + logByValue( + t, + ` | ${Math.round(t)} ms${ + p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : "" + } ${category} > ${module.readableIdentifier(this.requestShortener)}` + ); + max = Math.max(max, t); + } + if (sum <= 10) return; + logByValue( + Math.max(sum / 10, max), + `${Math.round(sum)} ms ${category}` + ); + }; + const logByLoadersSummary = (category, getDuration, getParallelism) => { + const map = new Map(); + for (const [module, profile] of modulesWithProfiles) { + const list = provide( + map, + module.type + "!" + module.identifier().replace(/(!|^)[^!]*$/, ""), + () => [] + ); + list.push({ module, profile }); + } - deserialize(context) { - const { read } = context; + let sum = 0; + let max = 0; + for (const [key, modules] of map) { + let innerSum = 0; + let innerMax = 0; + for (const { module, profile } of modules) { + const p = getParallelism(profile); + const d = getDuration(profile); + if (d === 0 || p === 0) continue; + const t = d / p; + innerSum += t; + if (t <= 10) continue; + logByValue( + t, + ` | | ${Math.round(t)} ms${ + p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : "" + } ${category} > ${module.readableIdentifier( + this.requestShortener + )}` + ); + innerMax = Math.max(innerMax, t); + } + sum += innerSum; + if (innerSum <= 10) continue; + const idx = key.indexOf("!"); + const loaders = key.slice(idx + 1); + const moduleType = key.slice(0, idx); + const t = Math.max(innerSum / 10, innerMax); + logByValue( + t, + ` | ${Math.round(innerSum)} ms ${category} > ${ + loaders + ? `${ + modules.length + } x ${moduleType} with ${this.requestShortener.shorten( + loaders + )}` + : `${modules.length} x ${moduleType}` + }` + ); + max = Math.max(max, t); + } + if (sum <= 10) return; + logByValue( + Math.max(sum / 10, max), + `${Math.round(sum)} ms ${category}` + ); + }; + logNormalSummary( + "resolve to new modules", + p => p.factory, + p => p.factoryParallelismFactor + ); + logNormalSummary( + "resolve to existing modules", + p => p.additionalFactories, + p => p.additionalFactoriesParallelismFactor + ); + logNormalSummary( + "integrate modules", + p => p.restoring, + p => p.restoringParallelismFactor + ); + logByLoadersSummary( + "build modules", + p => p.building, + p => p.buildingParallelismFactor + ); + logNormalSummary( + "store modules", + p => p.storing, + p => p.storingParallelismFactor + ); + logNormalSummary( + "restore modules", + p => p.restoring, + p => p.restoringParallelismFactor + ); + this.logger.timeEnd("finish module profiles"); + } + this.logger.time("compute affected modules"); + this._computeAffectedModules(this.modules); + this.logger.timeEnd("compute affected modules"); + this.logger.time("finish modules"); + const { modules, moduleMemCaches } = this; + this.hooks.finishModules.callAsync(modules, err => { + this.logger.timeEnd("finish modules"); + if (err) return callback(err); - this.content = read(); - this.stage = read(); - this.position = read(); - this.key = read(); - this.endContent = read(); + // extract warnings and errors from modules + this.moduleGraph.freeze("dependency errors"); + // TODO keep a cacheToken (= {}) for each module in the graph + // create a new one per compilation and flag all updated files + // and parents with it + this.logger.time("report dependency errors and warnings"); + for (const module of modules) { + // TODO only run for modules with changed cacheToken + // global WeakMap> to keep modules without errors/warnings + const memCache = moduleMemCaches && moduleMemCaches.get(module); + if (memCache && memCache.get("noWarningsOrErrors")) continue; + let hasProblems = this.reportDependencyErrorsAndWarnings(module, [ + module + ]); + const errors = module.getErrors(); + if (errors !== undefined) { + for (const error of errors) { + if (!error.module) { + error.module = module; + } + this.errors.push(error); + hasProblems = true; + } + } + const warnings = module.getWarnings(); + if (warnings !== undefined) { + for (const warning of warnings) { + if (!warning.module) { + warning.module = module; + } + this.warnings.push(warning); + hasProblems = true; + } + } + if (!hasProblems && memCache) memCache.set("noWarningsOrErrors", true); + } + this.moduleGraph.unfreeze(); + this.logger.timeEnd("report dependency errors and warnings"); + + callback(); + }); } -} -makeSerializable(InitFragment, "webpack/lib/InitFragment"); + unseal() { + this.hooks.unseal.call(); + this.chunks.clear(); + this.chunkGroups.length = 0; + this.namedChunks.clear(); + this.namedChunkGroups.clear(); + this.entrypoints.clear(); + this.additionalChunkAssets.length = 0; + this.assets = {}; + this.assetsInfo.clear(); + this.moduleGraph.removeAllModuleAttributes(); + this.moduleGraph.unfreeze(); + this.moduleMemCaches2 = undefined; + } -InitFragment.prototype.merge = undefined; + /** + * @param {Callback} callback signals when the call finishes + * @returns {void} + */ + seal(callback) { + const finalCallback = err => { + this.factorizeQueue.clear(); + this.buildQueue.clear(); + this.rebuildQueue.clear(); + this.processDependenciesQueue.clear(); + this.addModuleQueue.clear(); + return callback(err); + }; + const chunkGraph = new ChunkGraph( + this.moduleGraph, + this.outputOptions.hashFunction + ); + this.chunkGraph = chunkGraph; -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; + if (this._backCompat) { + for (const module of this.modules) { + ChunkGraph.setChunkGraphForModule(module, chunkGraph); + } + } -module.exports = InitFragment; + this.hooks.seal.call(); + this.logger.time("optimize dependencies"); + while (this.hooks.optimizeDependencies.call(this.modules)) { + /* empty */ + } + this.hooks.afterOptimizeDependencies.call(this.modules); + this.logger.timeEnd("optimize dependencies"); -/***/ }), + this.logger.time("create chunks"); + this.hooks.beforeChunks.call(); + this.moduleGraph.freeze("seal"); + /** @type {Map} */ + const chunkGraphInit = new Map(); + for (const [name, { dependencies, includeDependencies, options }] of this + .entries) { + const chunk = this.addChunk(name); + if (options.filename) { + chunk.filenameTemplate = options.filename; + } + const entrypoint = new Entrypoint(options); + if (!options.dependOn && !options.runtime) { + entrypoint.setRuntimeChunk(chunk); + } + entrypoint.setEntrypointChunk(chunk); + this.namedChunkGroups.set(name, entrypoint); + this.entrypoints.set(name, entrypoint); + this.chunkGroups.push(entrypoint); + connectChunkGroupAndChunk(entrypoint, chunk); -/***/ 68257: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const entryModules = new Set(); + for (const dep of [...this.globalEntry.dependencies, ...dependencies]) { + entrypoint.addOrigin(null, { name }, /** @type {any} */ (dep).request); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const module = this.moduleGraph.getModule(dep); + if (module) { + chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint); + entryModules.add(module); + const modulesList = chunkGraphInit.get(entrypoint); + if (modulesList === undefined) { + chunkGraphInit.set(entrypoint, [module]); + } else { + modulesList.push(module); + } + } + } + this.assignDepths(entryModules); + const mapAndSort = deps => + deps + .map(dep => this.moduleGraph.getModule(dep)) + .filter(Boolean) + .sort(compareModulesByIdentifier); + const includedModules = [ + ...mapAndSort(this.globalEntry.includeDependencies), + ...mapAndSort(includeDependencies) + ]; -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); + let modulesList = chunkGraphInit.get(entrypoint); + if (modulesList === undefined) { + chunkGraphInit.set(entrypoint, (modulesList = [])); + } + for (const module of includedModules) { + this.assignDepth(module); + modulesList.push(module); + } + } + const runtimeChunks = new Set(); + outer: for (const [ + name, + { + options: { dependOn, runtime } + } + ] of this.entries) { + if (dependOn && runtime) { + const err = + new WebpackError(`Entrypoint '${name}' has 'dependOn' and 'runtime' specified. This is not valid. +Entrypoints that depend on other entrypoints do not have their own runtime. +They will use the runtime(s) from referenced entrypoints instead. +Remove the 'runtime' option from the entrypoint.`); + const entry = this.entrypoints.get(name); + err.chunk = entry.getEntrypointChunk(); + this.errors.push(err); + } + if (dependOn) { + const entry = this.entrypoints.get(name); + const referencedChunks = entry + .getEntrypointChunk() + .getAllReferencedChunks(); + const dependOnEntries = []; + for (const dep of dependOn) { + const dependency = this.entrypoints.get(dep); + if (!dependency) { + throw new Error( + `Entry ${name} depends on ${dep}, but this entry was not found` + ); + } + if (referencedChunks.has(dependency.getEntrypointChunk())) { + const err = new WebpackError( + `Entrypoints '${name}' and '${dep}' use 'dependOn' to depend on each other in a circular way.` + ); + const entryChunk = entry.getEntrypointChunk(); + err.chunk = entryChunk; + this.errors.push(err); + entry.setRuntimeChunk(entryChunk); + continue outer; + } + dependOnEntries.push(dependency); + } + for (const dependency of dependOnEntries) { + connectChunkGroupParentAndChild(dependency, entry); + } + } else if (runtime) { + const entry = this.entrypoints.get(name); + let chunk = this.namedChunks.get(runtime); + if (chunk) { + if (!runtimeChunks.has(chunk)) { + const err = + new WebpackError(`Entrypoint '${name}' has a 'runtime' option which points to another entrypoint named '${runtime}'. +It's not valid to use other entrypoints as runtime chunk. +Did you mean to use 'dependOn: ${JSON.stringify( + runtime + )}' instead to allow using entrypoint '${name}' within the runtime of entrypoint '${runtime}'? For this '${runtime}' must always be loaded when '${name}' is used. +Or do you want to use the entrypoints '${name}' and '${runtime}' independently on the same page with a shared runtime? In this case give them both the same value for the 'runtime' option. It must be a name not already used by an entrypoint.`); + const entryChunk = entry.getEntrypointChunk(); + err.chunk = entryChunk; + this.errors.push(err); + entry.setRuntimeChunk(entryChunk); + continue; + } + } else { + chunk = this.addChunk(runtime); + chunk.preventIntegration = true; + runtimeChunks.add(chunk); + } + entry.unshiftChunk(chunk); + chunk.addGroup(entry); + entry.setRuntimeChunk(chunk); + } + } + buildChunkGraph(this, chunkGraphInit); + this.hooks.afterChunks.call(this.chunks); + this.logger.timeEnd("create chunks"); -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Module")} Module */ + this.logger.time("optimize"); + this.hooks.optimize.call(); -class InvalidDependenciesModuleWarning extends WebpackError { - /** - * @param {Module} module module tied to dependency - * @param {Iterable} 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 ..." : "" - }`); + while (this.hooks.optimizeModules.call(this.modules)) { + /* empty */ + } + this.hooks.afterOptimizeModules.call(this.modules); - this.name = "InvalidDependenciesModuleWarning"; - this.details = depsList.slice(3).join("\n"); - this.module = module; - } -} + while (this.hooks.optimizeChunks.call(this.chunks, this.chunkGroups)) { + /* empty */ + } + this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups); -makeSerializable( - InvalidDependenciesModuleWarning, - "webpack/lib/InvalidDependenciesModuleWarning" -); + this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => { + if (err) { + return finalCallback( + makeWebpackError(err, "Compilation.hooks.optimizeTree") + ); + } -module.exports = InvalidDependenciesModuleWarning; + this.hooks.afterOptimizeTree.call(this.chunks, this.modules); + this.hooks.optimizeChunkModules.callAsync( + this.chunks, + this.modules, + err => { + if (err) { + return finalCallback( + makeWebpackError(err, "Compilation.hooks.optimizeChunkModules") + ); + } -/***/ }), + this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules); -/***/ 52329: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const shouldRecord = this.hooks.shouldRecord.call() !== false; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov -*/ + this.hooks.reviveModules.call(this.modules, this.records); + this.hooks.beforeModuleIds.call(this.modules); + this.hooks.moduleIds.call(this.modules); + this.hooks.optimizeModuleIds.call(this.modules); + this.hooks.afterOptimizeModuleIds.call(this.modules); + this.hooks.reviveChunks.call(this.chunks, this.records); + this.hooks.beforeChunkIds.call(this.chunks); + this.hooks.chunkIds.call(this.chunks); + this.hooks.optimizeChunkIds.call(this.chunks); + this.hooks.afterOptimizeChunkIds.call(this.chunks); + this.assignRuntimeIds(); -const InnerGraph = __webpack_require__(38988); + this.logger.time("compute affected modules with chunk graph"); + this._computeAffectedModulesWithChunkGraph(); + this.logger.timeEnd("compute affected modules with chunk graph"); -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ + this.sortItemsWithChunkIds(); -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; - const currentSymbol = InnerGraph.getTopLevelSymbol(parser.state); - if (currentSymbol) { - InnerGraph.addUsage(parser.state, null, currentSymbol); - } else { - 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); - } - } - }); - }; + if (shouldRecord) { + this.hooks.recordModules.call(this.modules, this.records); + this.hooks.recordChunks.call(this.chunks, this.records); + } - 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); - } - ); - } -} + this.hooks.optimizeCodeGeneration.call(this.modules); + this.logger.timeEnd("optimize"); -module.exports = JavascriptMetaInfoPlugin; + this.logger.time("module hashing"); + this.hooks.beforeModuleHash.call(); + this.createModuleHashes(); + this.hooks.afterModuleHash.call(); + this.logger.timeEnd("module hashing"); + this.logger.time("code generation"); + this.hooks.beforeCodeGeneration.call(); + this.codeGeneration(err => { + if (err) { + return finalCallback(err); + } + this.hooks.afterCodeGeneration.call(); + this.logger.timeEnd("code generation"); -/***/ }), + this.logger.time("runtime requirements"); + this.hooks.beforeRuntimeRequirements.call(); + this.processRuntimeRequirements(); + this.hooks.afterRuntimeRequirements.call(); + this.logger.timeEnd("runtime requirements"); -/***/ 93837: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.logger.time("hashing"); + this.hooks.beforeHash.call(); + const codeGenerationJobs = this.createHash(); + this.hooks.afterHash.call(); + this.logger.timeEnd("hashing"); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this._runCodeGenerationJobs(codeGenerationJobs, err => { + if (err) { + return finalCallback(err); + } + if (shouldRecord) { + this.logger.time("record hash"); + this.hooks.recordHash.call(this.records); + this.logger.timeEnd("record hash"); + } + this.logger.time("module assets"); + this.clearAssets(); -const asyncLib = __webpack_require__(78175); -const EntryDependency = __webpack_require__(3979); -const { someInIterable } = __webpack_require__(39104); -const { compareModulesById } = __webpack_require__(29579); -const { dirname, mkdirp } = __webpack_require__(17139); + this.hooks.beforeModuleAssets.call(); + this.createModuleAssets(); + this.logger.timeEnd("module assets"); -/** @typedef {import("./Compiler")} Compiler */ + const cont = () => { + this.logger.time("process assets"); + this.hooks.processAssets.callAsync(this.assets, err => { + if (err) { + return finalCallback( + makeWebpackError(err, "Compilation.hooks.processAssets") + ); + } + this.hooks.afterProcessAssets.call(this.assets); + this.logger.timeEnd("process assets"); + this.assets = this._backCompat + ? soonFrozenObjectDeprecation( + this.assets, + "Compilation.assets", + "DEP_WEBPACK_COMPILATION_ASSETS", + `BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation. + Do changes to assets earlier, e. g. in Compilation.hooks.processAssets. + Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.` + ) + : Object.freeze(this.assets); -/** - * @typedef {Object} ManifestModuleData - * @property {string | number} id - * @property {Object} buildMeta - * @property {boolean | string[]} exports - */ + this.summarizeDependencies(); + if (shouldRecord) { + this.hooks.record.call(this, this.records); + } -class LibManifestPlugin { - constructor(options) { - this.options = options; + if (this.hooks.needAdditionalSeal.call()) { + this.unseal(); + return this.seal(callback); + } + return this.hooks.afterSeal.callAsync(err => { + if (err) { + return finalCallback( + makeWebpackError(err, "Compilation.hooks.afterSeal") + ); + } + this.fileSystemInfo.logStatistics(); + finalCallback(); + }); + }); + }; + + this.logger.time("create chunk assets"); + if (this.hooks.shouldGenerateChunkAssets.call() !== false) { + this.hooks.beforeChunkAssets.call(); + this.createChunkAssets(err => { + this.logger.timeEnd("create chunk assets"); + if (err) { + return finalCallback(err); + } + cont(); + }); + } else { + this.logger.timeEnd("create chunk assets"); + cont(); + } + }); + }); + } + ); + }); } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {Module} module module to report from + * @param {DependenciesBlock[]} blocks blocks to report from + * @returns {boolean} true, when it has warnings or errors */ - 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; + reportDependencyErrorsAndWarnings(module, blocks) { + let hasProblems = false; + for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { + const block = blocks[indexBlock]; + const dependencies = block.dependencies; + + for (let indexDep = 0; indexDep < dependencies.length; indexDep++) { + const d = dependencies[indexDep]; + + const warnings = d.getWarnings(this.moduleGraph); + if (warnings) { + for (let indexWar = 0; indexWar < warnings.length; indexWar++) { + const w = warnings[indexWar]; + + const warning = new ModuleDependencyWarning(module, w, d.loc); + this.warnings.push(warning); + hasProblems = true; + } + } + const errors = d.getErrors(this.moduleGraph); + if (errors) { + for (let indexErr = 0; indexErr < errors.length; indexErr++) { + const e = errors[indexErr]; + + const error = new ModuleDependencyError(module, e, d.loc); + this.errors.push(error); + hasProblems = true; + } + } + } + + if (this.reportDependencyErrorsAndWarnings(module, block.blocks)) + hasProblems = true; + } + return hasProblems; + } + + codeGeneration(callback) { + const { chunkGraph } = this; + this.codeGenerationResults = new CodeGenerationResults( + this.outputOptions.hashFunction + ); + /** @type {{module: Module, hash: string, runtime: RuntimeSpec, runtimes: RuntimeSpec[]}[]} */ + const jobs = []; + for (const module of this.modules) { + const runtimes = chunkGraph.getModuleRuntimes(module); + if (runtimes.size === 1) { + for (const runtime of runtimes) { + const hash = chunkGraph.getModuleHash(module, runtime); + jobs.push({ module, hash, runtime, runtimes: [runtime] }); + } + } else if (runtimes.size > 1) { + /** @type {Map} */ + const map = new Map(); + for (const runtime of runtimes) { + const hash = chunkGraph.getModuleHash(module, runtime); + const job = map.get(hash); + if (job === undefined) { + const newJob = { module, hash, runtime, runtimes: [runtime] }; + jobs.push(newJob); + map.set(hash, newJob); + } else { + job.runtimes.push(runtime); + } + } + } + } + + this._runCodeGenerationJobs(jobs, callback); + } + + _runCodeGenerationJobs(jobs, callback) { + let statModulesFromCache = 0; + let statModulesGenerated = 0; + const { chunkGraph, moduleGraph, dependencyTemplates, runtimeTemplate } = + this; + const results = this.codeGenerationResults; + const errors = []; + /** @type {Set | undefined} */ + let notCodeGeneratedModules = undefined; + const runIteration = () => { + let delayedJobs = []; + let delayedModules = new Set(); + asyncLib.eachLimit( + jobs, + this.options.parallelism, + (job, callback) => { + const { module } = job; + const { codeGenerationDependencies } = module; + if (codeGenerationDependencies !== undefined) { + if ( + notCodeGeneratedModules === undefined || + codeGenerationDependencies.some(dep => { + const referencedModule = moduleGraph.getModule(dep); + return notCodeGeneratedModules.has(referencedModule); + }) + ) { + delayedJobs.push(job); + delayedModules.add(module); + return callback(); } - 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 + } + const { hash, runtime, runtimes } = job; + this._codeGenerationModule( + module, + runtime, + runtimes, + hash, + dependencyTemplates, + chunkGraph, + moduleGraph, + runtimeTemplate, + errors, + results, + (err, codeGenerated) => { + if (codeGenerated) statModulesGenerated++; + else statModulesFromCache++; + callback(err); + } + ); + }, + err => { + if (err) return callback(err); + if (delayedJobs.length > 0) { + if (delayedJobs.length === jobs.length) { + return callback( + new Error( + `Unable to make progress during code generation because of circular code generation dependency: ${Array.from( + delayedModules, + m => m.identifier() + ).join(", ")}` ) - ) { - 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 - ); - } + jobs = delayedJobs; + delayedJobs = []; + notCodeGeneratedModules = delayedModules; + delayedModules = new Set(); + return runIteration(); + } + if (errors.length > 0) { + errors.sort( + compareSelect(err => err.module, compareModulesByIdentifier) ); - }, - callback - ); - } + for (const error of errors) { + this.errors.push(error); + } + } + this.logger.log( + `${Math.round( + (100 * statModulesGenerated) / + (statModulesGenerated + statModulesFromCache) + )}% code generated (${statModulesGenerated} generated, ${statModulesFromCache} from cache)` + ); + callback(); + } + ); + }; + runIteration(); + } + + /** + * @param {Module} module module + * @param {RuntimeSpec} runtime runtime + * @param {RuntimeSpec[]} runtimes runtimes + * @param {string} hash hash + * @param {DependencyTemplates} dependencyTemplates dependencyTemplates + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate + * @param {WebpackError[]} errors errors + * @param {CodeGenerationResults} results results + * @param {function(WebpackError=, boolean=): void} callback callback + */ + _codeGenerationModule( + module, + runtime, + runtimes, + hash, + dependencyTemplates, + chunkGraph, + moduleGraph, + runtimeTemplate, + errors, + results, + callback + ) { + let codeGenerated = false; + const cache = new MultiItemCache( + runtimes.map(runtime => + this._codeGenerationCache.getItemCache( + `${module.identifier()}|${getRuntimeKey(runtime)}`, + `${hash}|${dependencyTemplates.getHash()}` + ) + ) ); + cache.get((err, cachedResult) => { + if (err) return callback(err); + let result; + if (!cachedResult) { + try { + codeGenerated = true; + this.codeGeneratedModules.add(module); + result = module.codeGeneration({ + chunkGraph, + moduleGraph, + dependencyTemplates, + runtimeTemplate, + runtime, + codeGenerationResults: results + }); + } catch (err) { + errors.push(new CodeGenerationError(module, err)); + result = cachedResult = { + sources: new Map(), + runtimeRequirements: null + }; + } + } else { + result = cachedResult; + } + for (const runtime of runtimes) { + results.add(module, runtime, result); + } + if (!cachedResult) { + cache.store(result, err => callback(err, codeGenerated)); + } else { + callback(null, codeGenerated); + } + }); } -} -module.exports = LibManifestPlugin; + _getChunkGraphEntries() { + /** @type {Set} */ + const treeEntries = new Set(); + for (const ep of this.entrypoints.values()) { + const chunk = ep.getRuntimeChunk(); + if (chunk) treeEntries.add(chunk); + } + for (const ep of this.asyncEntrypoints) { + const chunk = ep.getRuntimeChunk(); + if (chunk) treeEntries.add(chunk); + } + return treeEntries; + } -/***/ }), + /** + * @param {Object} options options + * @param {ChunkGraph=} options.chunkGraph the chunk graph + * @param {Iterable=} options.modules modules + * @param {Iterable=} options.chunks chunks + * @param {CodeGenerationResults=} options.codeGenerationResults codeGenerationResults + * @param {Iterable=} options.chunkGraphEntries chunkGraphEntries + * @returns {void} + */ + processRuntimeRequirements({ + chunkGraph = this.chunkGraph, + modules = this.modules, + chunks = this.chunks, + codeGenerationResults = this.codeGenerationResults, + chunkGraphEntries = this._getChunkGraphEntries() + } = {}) { + const context = { chunkGraph, codeGenerationResults }; + const { moduleMemCaches2 } = this; + this.logger.time("runtime requirements.modules"); + const additionalModuleRuntimeRequirements = + this.hooks.additionalModuleRuntimeRequirements; + const runtimeRequirementInModule = this.hooks.runtimeRequirementInModule; + for (const module of modules) { + if (chunkGraph.getNumberOfModuleChunks(module) > 0) { + const memCache = moduleMemCaches2 && moduleMemCaches2.get(module); + for (const runtime of chunkGraph.getModuleRuntimes(module)) { + if (memCache) { + const cached = memCache.get( + `moduleRuntimeRequirements-${getRuntimeKey(runtime)}` + ); + if (cached !== undefined) { + if (cached !== null) { + chunkGraph.addModuleRuntimeRequirements( + module, + runtime, + cached, + false + ); + } + continue; + } + } + let set; + const runtimeRequirements = + codeGenerationResults.getRuntimeRequirements(module, runtime); + if (runtimeRequirements && runtimeRequirements.size > 0) { + set = new Set(runtimeRequirements); + } else if (additionalModuleRuntimeRequirements.isUsed()) { + set = new Set(); + } else { + if (memCache) { + memCache.set( + `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, + null + ); + } + continue; + } + additionalModuleRuntimeRequirements.call(module, set, context); -/***/ 14157: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + for (const r of set) { + const hook = runtimeRequirementInModule.get(r); + if (hook !== undefined) hook.call(module, set, context); + } + if (set.size === 0) { + if (memCache) { + memCache.set( + `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, + null + ); + } + } else { + if (memCache) { + memCache.set( + `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, + set + ); + chunkGraph.addModuleRuntimeRequirements( + module, + runtime, + set, + false + ); + } else { + chunkGraph.addModuleRuntimeRequirements(module, runtime, set); + } + } + } + } + } + this.logger.timeEnd("runtime requirements.modules"); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.logger.time("runtime requirements.chunks"); + for (const chunk of chunks) { + const set = new Set(); + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( + module, + chunk.runtime + ); + for (const r of runtimeRequirements) set.add(r); + } + this.hooks.additionalChunkRuntimeRequirements.call(chunk, set, context); + for (const r of set) { + this.hooks.runtimeRequirementInChunk.for(r).call(chunk, set, context); + } + chunkGraph.addChunkRuntimeRequirements(chunk, set); + } + this.logger.timeEnd("runtime requirements.chunks"); -const EnableLibraryPlugin = __webpack_require__(91452); + this.logger.time("runtime requirements.entries"); + for (const treeEntry of chunkGraphEntries) { + const set = new Set(); + for (const chunk of treeEntry.getAllReferencedChunks()) { + const runtimeRequirements = + chunkGraph.getChunkRuntimeRequirements(chunk); + for (const r of runtimeRequirements) set.add(r); + } -/** @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 */ + this.hooks.additionalTreeRuntimeRequirements.call( + treeEntry, + set, + context + ); -// 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 - }; + for (const r of set) { + this.hooks.runtimeRequirementInTree + .for(r) + .call(treeEntry, set, context); + } + + chunkGraph.addTreeRuntimeRequirements(treeEntry, set); + } + this.logger.timeEnd("runtime requirements.entries"); } + // TODO webpack 6 make chunkGraph argument non-optional /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {Chunk} chunk target chunk + * @param {RuntimeModule} module runtime module + * @param {ChunkGraph} chunkGraph the chunk graph * @returns {void} */ - apply(compiler) { - const { output } = compiler.options; - output.library = this.library; - new EnableLibraryPlugin(this.library.type).apply(compiler); - } -} + addRuntimeModule(chunk, module, chunkGraph = this.chunkGraph) { + // Deprecated ModuleGraph association + if (this._backCompat) + ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); -module.exports = LibraryTemplatePlugin; + // add it to the list + this.modules.add(module); + this._modules.set(module.identifier(), module); + // connect to the chunk graph + chunkGraph.connectChunkAndModule(chunk, module); + chunkGraph.connectChunkAndRuntimeModule(chunk, module); + if (module.fullHash) { + chunkGraph.addFullHashModuleToChunk(chunk, module); + } else if (module.dependentHash) { + chunkGraph.addDependentHashModuleToChunk(chunk, module); + } -/***/ }), + // attach runtime module + module.attach(this, chunk, chunkGraph); -/***/ 22078: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Setup internals + const exportsInfo = this.moduleGraph.getExportsInfo(module); + exportsInfo.setHasProvideInfo(); + if (typeof chunk.runtime === "string") { + exportsInfo.setUsedForSideEffectsOnly(chunk.runtime); + } else if (chunk.runtime === undefined) { + exportsInfo.setUsedForSideEffectsOnly(undefined); + } else { + for (const runtime of chunk.runtime) { + exportsInfo.setUsedForSideEffectsOnly(runtime); + } + } + chunkGraph.addModuleRuntimeRequirements( + module, + chunk.runtime, + new Set([RuntimeGlobals.requireScope]) + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // runtime modules don't need ids + chunkGraph.setModuleId(module, ""); + // Call hook + this.hooks.runtimeModule.call(module, chunk); + } + /** + * If `module` is passed, `loc` and `request` must also be passed. + * @param {string | ChunkGroupOptions} groupOptions options for the chunk group + * @param {Module=} module the module the references the chunk group + * @param {DependencyLocation=} loc the location from with the chunk group is referenced (inside of module) + * @param {string=} request the request from which the the chunk group is referenced + * @returns {ChunkGroup} the new or existing chunk group + */ + addChunkInGroup(groupOptions, module, loc, request) { + if (typeof groupOptions === "string") { + groupOptions = { name: groupOptions }; + } + const name = groupOptions.name; -const ModuleFilenameHelpers = __webpack_require__(88821); -const NormalModule = __webpack_require__(39); -const createSchemaValidation = __webpack_require__(32540); + if (name) { + const chunkGroup = this.namedChunkGroups.get(name); + if (chunkGroup !== undefined) { + chunkGroup.addOptions(groupOptions); + if (module) { + chunkGroup.addOrigin(module, loc, request); + } + return chunkGroup; + } + } + const chunkGroup = new ChunkGroup(groupOptions); + if (module) chunkGroup.addOrigin(module, loc, request); + const chunk = this.addChunk(name); -/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */ -/** @typedef {import("./Compiler")} Compiler */ + connectChunkGroupAndChunk(chunkGroup, chunk); -const validate = createSchemaValidation( - __webpack_require__(24160), - () => __webpack_require__(15965), - { - name: "Loader Options Plugin", - baseDataPath: "options" + this.chunkGroups.push(chunkGroup); + if (name) { + this.namedChunkGroups.set(name, chunkGroup); + } + return chunkGroup; } -); -class LoaderOptionsPlugin { + /** - * @param {LoaderOptionsPluginOptions} options options object + * @param {EntryOptions} options options for the entrypoint + * @param {Module} module the module the references the chunk group + * @param {DependencyLocation} loc the location from with the chunk group is referenced (inside of module) + * @param {string} request the request from which the the chunk group is referenced + * @returns {Entrypoint} the new or existing entrypoint */ - constructor(options = {}) { - validate(options); - if (typeof options !== "object") options = {}; - if (!options.test) { - options.test = { - test: () => true - }; + addAsyncEntrypoint(options, module, loc, request) { + const name = options.name; + if (name) { + const entrypoint = this.namedChunkGroups.get(name); + if (entrypoint instanceof Entrypoint) { + if (entrypoint !== undefined) { + if (module) { + entrypoint.addOrigin(module, loc, request); + } + return entrypoint; + } + } else if (entrypoint) { + throw new Error( + `Cannot add an async entrypoint with the name '${name}', because there is already an chunk group with this name` + ); + } } - this.options = options; + const chunk = this.addChunk(name); + if (options.filename) { + chunk.filenameTemplate = options.filename; + } + const entrypoint = new Entrypoint(options, false); + entrypoint.setRuntimeChunk(chunk); + entrypoint.setEntrypointChunk(chunk); + if (name) { + this.namedChunkGroups.set(name, entrypoint); + } + this.chunkGroups.push(entrypoint); + this.asyncEntrypoints.push(entrypoint); + connectChunkGroupAndChunk(entrypoint, chunk); + if (module) { + entrypoint.addOrigin(module, loc, request); + } + return entrypoint; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * This method first looks to see if a name is provided for a new chunk, + * and first looks to see if any named chunks already exist and reuse that chunk instead. + * + * @param {string=} name optional chunk name to be provided + * @returns {Chunk} create a chunk (invoked during seal event) */ - 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]; - } - } - } - ); - }); + addChunk(name) { + if (name) { + const chunk = this.namedChunks.get(name); + if (chunk !== undefined) { + return chunk; + } + } + const chunk = new Chunk(name, this._backCompat); + this.chunks.add(chunk); + if (this._backCompat) + ChunkGraph.setChunkGraphForChunk(chunk, this.chunkGraph); + if (name) { + this.namedChunks.set(name, chunk); + } + return chunk; } -} -module.exports = LoaderOptionsPlugin; + /** + * @deprecated + * @param {Module} module module to assign depth + * @returns {void} + */ + assignDepth(module) { + const moduleGraph = this.moduleGraph; + const queue = new Set([module]); + let depth; -/***/ }), + moduleGraph.setDepth(module, 0); -/***/ 86738: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {Module} module module for processing + * @returns {void} + */ + const processModule = module => { + if (!moduleGraph.setDepthIfLower(module, depth)) return; + queue.add(module); + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + for (module of queue) { + queue.delete(module); + depth = moduleGraph.getDepth(module) + 1; + for (const connection of moduleGraph.getOutgoingConnections(module)) { + const refModule = connection.module; + if (refModule) { + processModule(refModule); + } + } + } + } + /** + * @param {Set} modules module to assign depth + * @returns {void} + */ + assignDepths(modules) { + const moduleGraph = this.moduleGraph; -const NormalModule = __webpack_require__(39); + /** @type {Set} */ + const queue = new Set(modules); + queue.add(1); + let depth = 0; -/** @typedef {import("./Compiler")} Compiler */ + let i = 0; + for (const module of queue) { + i++; + if (typeof module === "number") { + depth = module; + if (queue.size === i) return; + queue.add(depth + 1); + } else { + moduleGraph.setDepth(module, depth); + for (const { module: refModule } of moduleGraph.getOutgoingConnections( + module + )) { + if (refModule) { + queue.add(refModule); + } + } + } + } + } -class LoaderTargetPlugin { /** - * @param {string} target the target + * @param {Dependency} dependency the dependency + * @param {RuntimeSpec} runtime the runtime + * @returns {(string[] | ReferencedExport)[]} referenced exports */ - constructor(target) { - this.target = target; + getDependencyReferencedExports(dependency, runtime) { + const referencedExports = dependency.getReferencedExports( + this.moduleGraph, + runtime + ); + return this.hooks.dependencyReferencedExports.call( + referencedExports, + dependency, + runtime + ); } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * + * @param {Module} module module relationship for removal + * @param {DependenciesBlockLike} block //TODO: good description * @returns {void} */ - apply(compiler) { - compiler.hooks.compilation.tap("LoaderTargetPlugin", compilation => { - NormalModule.getCompilationHooks(compilation).loader.tap( - "LoaderTargetPlugin", - loaderContext => { - loaderContext.target = this.target; + removeReasonsOfDependencyBlock(module, block) { + if (block.blocks) { + for (const b of block.blocks) { + this.removeReasonsOfDependencyBlock(module, b); + } + } + + if (block.dependencies) { + for (const dep of block.dependencies) { + const originalModule = this.moduleGraph.getModule(dep); + if (originalModule) { + this.moduleGraph.removeConnection(dep); + + if (this.chunkGraph) { + for (const chunk of this.chunkGraph.getModuleChunks( + originalModule + )) { + this.patchChunksAfterReasonRemoval(originalModule, chunk); + } + } } - ); - }); + } + } } -} -module.exports = LoaderTargetPlugin; + /** + * @param {Module} module module to patch tie + * @param {Chunk} chunk chunk to patch tie + * @returns {void} + */ + patchChunksAfterReasonRemoval(module, chunk) { + if (!module.hasReasons(this.moduleGraph, chunk.runtime)) { + this.removeReasonsOfDependencyBlock(module, module); + } + if (!module.hasReasonForChunk(chunk, this.moduleGraph, this.chunkGraph)) { + if (this.chunkGraph.isModuleInChunk(module, chunk)) { + this.chunkGraph.disconnectChunkAndModule(chunk, module); + this.removeChunkFromDependencies(module, chunk); + } + } + } + /** + * + * @param {DependenciesBlock} block block tie for Chunk + * @param {Chunk} chunk chunk to remove from dep + * @returns {void} + */ + removeChunkFromDependencies(block, chunk) { + /** + * @param {Dependency} d dependency to (maybe) patch up + */ + const iteratorDependency = d => { + const depModule = this.moduleGraph.getModule(d); + if (!depModule) { + return; + } + this.patchChunksAfterReasonRemoval(depModule, chunk); + }; -/***/ }), + const blocks = block.blocks; + for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { + const asyncBlock = blocks[indexBlock]; + const chunkGroup = this.chunkGraph.getBlockChunkGroup(asyncBlock); + // Grab all chunks from the first Block's AsyncDepBlock + const chunks = chunkGroup.chunks; + // For each chunk in chunkGroup + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const iteratedChunk = chunks[indexChunk]; + chunkGroup.removeChunk(iteratedChunk); + // Recurse + this.removeChunkFromDependencies(block, iteratedChunk); + } + } -/***/ 12856: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (block.dependencies) { + for (const dep of block.dependencies) iteratorDependency(dep); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + assignRuntimeIds() { + const { chunkGraph } = this; + const processEntrypoint = ep => { + const runtime = ep.options.runtime || ep.name; + const chunk = ep.getRuntimeChunk(); + chunkGraph.setRuntimeId(runtime, chunk.id); + }; + for (const ep of this.entrypoints.values()) { + processEntrypoint(ep); + } + for (const ep of this.asyncEntrypoints) { + processEntrypoint(ep); + } + } + sortItemsWithChunkIds() { + for (const chunkGroup of this.chunkGroups) { + chunkGroup.sortItems(); + } + this.errors.sort(compareErrors); + this.warnings.sort(compareErrors); + this.children.sort(byNameOrHash); + } -const { SyncWaterfallHook } = __webpack_require__(6967); -const util = __webpack_require__(73837); -const RuntimeGlobals = __webpack_require__(16475); -const memoize = __webpack_require__(78676); + summarizeDependencies() { + for ( + let indexChildren = 0; + indexChildren < this.children.length; + indexChildren++ + ) { + const child = this.children[indexChildren]; -/** @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("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext} */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate} */ -/** @typedef {import("./ModuleGraph")} ModuleGraph} */ -/** @typedef {import("./ChunkGraph")} ChunkGraph} */ -/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions} */ -/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry} */ + this.fileDependencies.addAll(child.fileDependencies); + this.contextDependencies.addAll(child.contextDependencies); + this.missingDependencies.addAll(child.missingDependencies); + this.buildDependencies.addAll(child.buildDependencies); + } -const getJavascriptModulesPlugin = memoize(() => - __webpack_require__(89464) -); -const getJsonpTemplatePlugin = memoize(() => - __webpack_require__(4607) -); -const getLoadScriptRuntimeModule = memoize(() => - __webpack_require__(19942) -); + for (const module of this.modules) { + module.addCacheDependencies( + this.fileDependencies, + this.contextDependencies, + this.missingDependencies, + this.buildDependencies + ); + } + } -// 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); - } + createModuleHashes() { + let statModulesHashed = 0; + let statModulesFromCache = 0; + const { chunkGraph, runtimeTemplate, moduleMemCaches2 } = this; + const { hashFunction, hashDigest, hashDigestLength } = this.outputOptions; + for (const module of this.modules) { + const memCache = moduleMemCaches2 && moduleMemCaches2.get(module); + for (const runtime of chunkGraph.getModuleRuntimes(module)) { + if (memCache) { + const digest = memCache.get(`moduleHash-${getRuntimeKey(runtime)}`); + if (digest !== undefined) { + chunkGraph.setModuleHashes( + module, + runtime, + digest, + digest.substr(0, hashDigestLength) ); - }, - "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)" - ); + statModulesFromCache++; + continue; + } } - }, - 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)" - ); + statModulesHashed++; + const digest = this._createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength + ); + if (memCache) { + memCache.set(`moduleHash-${getRuntimeKey(runtime)}`, digest); } - }, - - // 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.logger.log( + `${statModulesHashed} modules hashed, ${statModulesFromCache} from cache (${ + Math.round( + (100 * (statModulesHashed + statModulesFromCache)) / this.modules.size + ) / 100 + } variants per module in average)` ); + } - 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" + _createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength + ) { + const moduleHash = createHash(hashFunction); + module.updateHash(moduleHash, { + chunkGraph, + runtime, + runtimeTemplate + }); + const moduleHashDigest = /** @type {string} */ ( + moduleHash.digest(hashDigest) ); - - 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" + chunkGraph.setModuleHashes( + module, + runtime, + moduleHashDigest, + moduleHashDigest.substr(0, hashDigestLength) ); + return moduleHashDigest; } -} -Object.defineProperty(MainTemplate.prototype, "requireFn", { - get: util.deprecate( - () => "__webpack_require__", - 'MainTemplate.requireFn is deprecated (use "__webpack_require__")', - "DEP_WEBPACK_MAIN_TEMPLATE_REQUIRE_FN" - ) -}); + createHash() { + this.logger.time("hashing: initialize hash"); + const chunkGraph = this.chunkGraph; + const runtimeTemplate = this.runtimeTemplate; + const outputOptions = this.outputOptions; + const hashFunction = outputOptions.hashFunction; + const hashDigest = outputOptions.hashDigest; + const hashDigestLength = outputOptions.hashDigestLength; + const hash = createHash(hashFunction); + if (outputOptions.hashSalt) { + hash.update(outputOptions.hashSalt); + } + this.logger.timeEnd("hashing: initialize hash"); + if (this.children.length > 0) { + this.logger.time("hashing: hash child compilations"); + for (const child of this.children) { + hash.update(child.hash); + } + this.logger.timeEnd("hashing: hash child compilations"); + } + if (this.warnings.length > 0) { + this.logger.time("hashing: hash warnings"); + for (const warning of this.warnings) { + hash.update(`${warning.message}`); + } + this.logger.timeEnd("hashing: hash warnings"); + } + if (this.errors.length > 0) { + this.logger.time("hashing: hash errors"); + for (const error of this.errors) { + hash.update(`${error.message}`); + } + this.logger.timeEnd("hashing: hash errors"); + } -Object.defineProperty(MainTemplate.prototype, "outputOptions", { - get: util.deprecate( - /** - * @this {MainTemplate} - * @returns {OutputOptions} output options + this.logger.time("hashing: sort chunks"); + /* + * all non-runtime chunks need to be hashes first, + * since runtime chunk might use their hashes. + * runtime chunks need to be hashed in the correct order + * since they may depend on each other (for async entrypoints). + * So we put all non-runtime chunks first and hash them in any order. + * And order runtime chunks according to referenced between each other. + * Chunks need to be in deterministic order since we add hashes to full chunk + * during these hashing. */ - function () { - return this._outputOptions; - }, - "MainTemplate.outputOptions is deprecated (use Compilation.outputOptions instead)", - "DEP_WEBPACK_MAIN_TEMPLATE_OUTPUT_OPTIONS" - ) -}); - -module.exports = MainTemplate; - - -/***/ }), - -/***/ 73208: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const util = __webpack_require__(73837); -const ChunkGraph = __webpack_require__(64971); -const DependenciesBlock = __webpack_require__(71040); -const ModuleGraph = __webpack_require__(99988); -const RuntimeGlobals = __webpack_require__(16475); -const { first } = __webpack_require__(93347); -const { compareChunksById } = __webpack_require__(29579); -const makeSerializable = __webpack_require__(33032); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./ExportsInfo").UsageStateType} UsageStateType */ -/** @typedef {import("./FileSystemInfo")} FileSystemInfo */ -/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./util/Hash")} Hash */ -/** @template T @typedef {import("./util/LazySet")} LazySet */ -/** @template T @typedef {import("./util/SortableSet")} SortableSet */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ - -/** - * @typedef {Object} SourceContext - * @property {DependencyTemplates} dependencyTemplates the dependency templates - * @property {RuntimeTemplate} runtimeTemplate the runtime template - * @property {ModuleGraph} moduleGraph the module graph - * @property {ChunkGraph} chunkGraph the chunk graph - * @property {RuntimeSpec} runtime the runtimes code should be generated for - * @property {string=} type the type of source that should be generated - */ - -/** - * @typedef {Object} CodeGenerationContext - * @property {DependencyTemplates} dependencyTemplates the dependency templates - * @property {RuntimeTemplate} runtimeTemplate the runtime template - * @property {ModuleGraph} moduleGraph the module graph - * @property {ChunkGraph} chunkGraph the chunk graph - * @property {RuntimeSpec} runtime the runtimes code should be generated for - * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules - * @property {CodeGenerationResults} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that) - */ - -/** - * @typedef {Object} ConcatenationBailoutReasonContext - * @property {ModuleGraph} moduleGraph the module graph - * @property {ChunkGraph} chunkGraph the chunk graph - */ - -/** - * @typedef {Object} CodeGenerationResult - * @property {Map} sources the resulting sources for all source types - * @property {Map=} data the resulting data for all source types - * @property {ReadonlySet} runtimeRequirements the runtime requirements - * @property {string=} hash a hash of the code generation result (will be automatically calculated from sources and runtimeRequirements if not provided) - */ - -/** - * @typedef {Object} LibIdentOptions - * @property {string} context absolute context path to which lib ident is relative to - * @property {Object=} associatedObjectForCache object for caching - */ - -/** - * @typedef {Object} KnownBuildMeta - * @property {string=} moduleArgument - * @property {string=} exportsArgument - * @property {boolean=} strict - * @property {string=} moduleConcatenationBailout - * @property {("default" | "namespace" | "flagged" | "dynamic")=} exportsType - * @property {(false | "redirect" | "redirect-warn")=} defaultObject - * @property {boolean=} strictHarmonyModule - * @property {boolean=} async - * @property {boolean=} sideEffectFree - */ - -/** - * @typedef {Object} NeedBuildContext - * @property {Compilation} compilation - * @property {FileSystemInfo} fileSystemInfo - * @property {Map>} valueCacheVersions - */ - -/** @typedef {KnownBuildMeta & Record} BuildMeta */ + /** @type {Chunk[]} */ + const unorderedRuntimeChunks = []; + /** @type {Chunk[]} */ + const otherChunks = []; + for (const c of this.chunks) { + if (c.hasRuntime()) { + unorderedRuntimeChunks.push(c); + } else { + otherChunks.push(c); + } + } + unorderedRuntimeChunks.sort(byId); + otherChunks.sort(byId); -const EMPTY_RESOLVE_OPTIONS = {}; + /** @typedef {{ chunk: Chunk, referencedBy: RuntimeChunkInfo[], remaining: number }} RuntimeChunkInfo */ + /** @type {Map} */ + const runtimeChunksMap = new Map(); + for (const chunk of unorderedRuntimeChunks) { + runtimeChunksMap.set(chunk, { + chunk, + referencedBy: [], + remaining: 0 + }); + } + let remaining = 0; + for (const info of runtimeChunksMap.values()) { + for (const other of new Set( + Array.from(info.chunk.getAllReferencedAsyncEntrypoints()).map( + e => e.chunks[e.chunks.length - 1] + ) + )) { + const otherInfo = runtimeChunksMap.get(other); + otherInfo.referencedBy.push(info); + info.remaining++; + remaining++; + } + } + /** @type {Chunk[]} */ + const runtimeChunks = []; + for (const info of runtimeChunksMap.values()) { + if (info.remaining === 0) { + runtimeChunks.push(info.chunk); + } + } + // If there are any references between chunks + // make sure to follow these chains + if (remaining > 0) { + const readyChunks = []; + for (const chunk of runtimeChunks) { + const hasFullHashModules = + chunkGraph.getNumberOfChunkFullHashModules(chunk) !== 0; + const info = runtimeChunksMap.get(chunk); + for (const otherInfo of info.referencedBy) { + if (hasFullHashModules) { + chunkGraph.upgradeDependentToFullHashModules(otherInfo.chunk); + } + remaining--; + if (--otherInfo.remaining === 0) { + readyChunks.push(otherInfo.chunk); + } + } + if (readyChunks.length > 0) { + // This ensures deterministic ordering, since referencedBy is non-deterministic + readyChunks.sort(byId); + for (const c of readyChunks) runtimeChunks.push(c); + readyChunks.length = 0; + } + } + } + // If there are still remaining references we have cycles and want to create a warning + if (remaining > 0) { + let circularRuntimeChunkInfo = []; + for (const info of runtimeChunksMap.values()) { + if (info.remaining !== 0) { + circularRuntimeChunkInfo.push(info); + } + } + circularRuntimeChunkInfo.sort(compareSelect(i => i.chunk, byId)); + const err = + new WebpackError(`Circular dependency between chunks with runtime (${Array.from( + circularRuntimeChunkInfo, + c => c.chunk.name || c.chunk.id + ).join(", ")}) +This prevents using hashes of each other and should be avoided.`); + err.chunk = circularRuntimeChunkInfo[0].chunk; + this.warnings.push(err); + for (const i of circularRuntimeChunkInfo) runtimeChunks.push(i.chunk); + } + this.logger.timeEnd("hashing: sort chunks"); -let debugId = 1000; + const fullHashChunks = new Set(); + /** @type {{module: Module, hash: string, runtime: RuntimeSpec, runtimes: RuntimeSpec[]}[]} */ + const codeGenerationJobs = []; + /** @type {Map>} */ + const codeGenerationJobsMap = new Map(); -const DEFAULT_TYPES_UNKNOWN = new Set(["unknown"]); -const DEFAULT_TYPES_JS = new Set(["javascript"]); + const processChunk = chunk => { + // Last minute module hash generation for modules that depend on chunk hashes + this.logger.time("hashing: hash runtime modules"); + const runtime = chunk.runtime; + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (!chunkGraph.hasModuleHashes(module, runtime)) { + const hash = this._createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength + ); + let hashMap = codeGenerationJobsMap.get(hash); + if (hashMap) { + const moduleJob = hashMap.get(module); + if (moduleJob) { + moduleJob.runtimes.push(runtime); + continue; + } + } else { + hashMap = new Map(); + codeGenerationJobsMap.set(hash, hashMap); + } + const job = { + module, + hash, + runtime, + runtimes: [runtime] + }; + hashMap.set(module, job); + codeGenerationJobs.push(job); + } + } + this.logger.timeAggregate("hashing: hash runtime modules"); + this.logger.time("hashing: hash chunks"); + const chunkHash = createHash(hashFunction); + try { + if (outputOptions.hashSalt) { + chunkHash.update(outputOptions.hashSalt); + } + chunk.updateHash(chunkHash, chunkGraph); + this.hooks.chunkHash.call(chunk, chunkHash, { + chunkGraph, + moduleGraph: this.moduleGraph, + runtimeTemplate: this.runtimeTemplate + }); + const chunkHashDigest = /** @type {string} */ ( + chunkHash.digest(hashDigest) + ); + hash.update(chunkHashDigest); + chunk.hash = chunkHashDigest; + chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); + const fullHashModules = + chunkGraph.getChunkFullHashModulesIterable(chunk); + if (fullHashModules) { + fullHashChunks.add(chunk); + } else { + this.hooks.contentHash.call(chunk); + } + } catch (err) { + this.errors.push(new ChunkRenderError(chunk, "", err)); + } + this.logger.timeAggregate("hashing: hash chunks"); + }; + otherChunks.forEach(processChunk); + for (const chunk of runtimeChunks) processChunk(chunk); -const deprecatedNeedRebuild = util.deprecate( - (module, context) => { - return module.needRebuild( - context.fileSystemInfo.getDeprecatedFileTimestamps(), - context.fileSystemInfo.getDeprecatedContextTimestamps() - ); - }, - "Module.needRebuild is deprecated in favor of Module.needBuild", - "DEP_WEBPACK_MODULE_NEED_REBUILD" -); + this.logger.timeAggregateEnd("hashing: hash runtime modules"); + this.logger.timeAggregateEnd("hashing: hash chunks"); + this.logger.time("hashing: hash digest"); + this.hooks.fullHash.call(hash); + this.fullHash = /** @type {string} */ (hash.digest(hashDigest)); + this.hash = this.fullHash.substr(0, hashDigestLength); + this.logger.timeEnd("hashing: hash digest"); -/** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ + this.logger.time("hashing: process full hash modules"); + for (const chunk of fullHashChunks) { + for (const module of chunkGraph.getChunkFullHashModulesIterable(chunk)) { + const moduleHash = createHash(hashFunction); + module.updateHash(moduleHash, { + chunkGraph, + runtime: chunk.runtime, + runtimeTemplate + }); + const moduleHashDigest = /** @type {string} */ ( + moduleHash.digest(hashDigest) + ); + const oldHash = chunkGraph.getModuleHash(module, chunk.runtime); + chunkGraph.setModuleHashes( + module, + chunk.runtime, + moduleHashDigest, + moduleHashDigest.substr(0, hashDigestLength) + ); + codeGenerationJobsMap.get(oldHash).get(module).hash = moduleHashDigest; + } + const chunkHash = createHash(hashFunction); + chunkHash.update(chunk.hash); + chunkHash.update(this.hash); + const chunkHashDigest = /** @type {string} */ ( + chunkHash.digest(hashDigest) + ); + chunk.hash = chunkHashDigest; + chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); + this.hooks.contentHash.call(chunk); + } + this.logger.timeEnd("hashing: process full hash modules"); + return codeGenerationJobs; + } -class Module extends DependenciesBlock { /** - * @param {string} type the module type - * @param {string=} context an optional context - * @param {string=} layer an optional layer in which the module is + * @param {string} file file name + * @param {Source} source asset source + * @param {AssetInfo} assetInfo extra asset information + * @returns {void} */ - constructor(type, context = null, layer = null) { - super(); - - /** @type {string} */ - this.type = type; - /** @type {string | null} */ - this.context = context; - /** @type {string | null} */ - this.layer = layer; - /** @type {boolean} */ - this.needId = true; - - // Unique Id - /** @type {number} */ - this.debugId = debugId++; - - // Info from Factory - /** @type {ResolveOptions} */ - this.resolveOptions = EMPTY_RESOLVE_OPTIONS; - /** @type {object | undefined} */ - this.factoryMeta = undefined; - // TODO refactor this -> options object filled from Factory - // TODO webpack 6: use an enum - /** @type {boolean} */ - this.useSourceMap = false; - /** @type {boolean} */ - this.useSimpleSourceMap = false; - - // Info from Build - /** @type {WebpackError[] | undefined} */ - this._warnings = undefined; - /** @type {WebpackError[] | undefined} */ - this._errors = undefined; - /** @type {BuildMeta} */ - this.buildMeta = undefined; - /** @type {Record} */ - this.buildInfo = undefined; - /** @type {Dependency[] | undefined} */ - this.presentationalDependencies = undefined; - /** @type {Dependency[] | undefined} */ - this.codeGenerationDependencies = undefined; - } - - // TODO remove in webpack 6 - // BACKWARD-COMPAT START - get id() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.id", - "DEP_WEBPACK_MODULE_ID" - ).getModuleId(this); - } - - set id(value) { - if (value === "") { - this.needId = false; + emitAsset(file, source, assetInfo = {}) { + if (this.assets[file]) { + if (!isSourceEqual(this.assets[file], source)) { + this.errors.push( + new WebpackError( + `Conflict: Multiple assets emit different content to the same filename ${file}` + ) + ); + this.assets[file] = source; + this._setAssetInfo(file, assetInfo); + return; + } + const oldInfo = this.assetsInfo.get(file); + const newInfo = Object.assign({}, oldInfo, assetInfo); + this._setAssetInfo(file, newInfo, oldInfo); return; } - ChunkGraph.getChunkGraphForModule( - this, - "Module.id", - "DEP_WEBPACK_MODULE_ID" - ).setModuleId(this, value); + this.assets[file] = source; + this._setAssetInfo(file, assetInfo, undefined); } - /** - * @returns {string} the hash of the module - */ - get hash() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.hash", - "DEP_WEBPACK_MODULE_HASH" - ).getModuleHash(this, undefined); + _setAssetInfo(file, newInfo, oldInfo = this.assetsInfo.get(file)) { + if (newInfo === undefined) { + this.assetsInfo.delete(file); + } else { + this.assetsInfo.set(file, newInfo); + } + const oldRelated = oldInfo && oldInfo.related; + const newRelated = newInfo && newInfo.related; + if (oldRelated) { + for (const key of Object.keys(oldRelated)) { + const remove = name => { + const relatedIn = this._assetsRelatedIn.get(name); + if (relatedIn === undefined) return; + const entry = relatedIn.get(key); + if (entry === undefined) return; + entry.delete(file); + if (entry.size !== 0) return; + relatedIn.delete(key); + if (relatedIn.size === 0) this._assetsRelatedIn.delete(name); + }; + const entry = oldRelated[key]; + if (Array.isArray(entry)) { + entry.forEach(remove); + } else if (entry) { + remove(entry); + } + } + } + if (newRelated) { + for (const key of Object.keys(newRelated)) { + const add = name => { + let relatedIn = this._assetsRelatedIn.get(name); + if (relatedIn === undefined) { + this._assetsRelatedIn.set(name, (relatedIn = new Map())); + } + let entry = relatedIn.get(key); + if (entry === undefined) { + relatedIn.set(key, (entry = new Set())); + } + entry.add(file); + }; + const entry = newRelated[key]; + if (Array.isArray(entry)) { + entry.forEach(add); + } else if (entry) { + add(entry); + } + } + } } /** - * @returns {string} the shortened hash of the module + * @param {string} file file name + * @param {Source | function(Source): Source} newSourceOrFunction new asset source or function converting old to new + * @param {AssetInfo | function(AssetInfo | undefined): AssetInfo} assetInfoUpdateOrFunction new asset info or function converting old to new */ - get renderedHash() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.renderedHash", - "DEP_WEBPACK_MODULE_RENDERED_HASH" - ).getRenderedModuleHash(this, undefined); - } - - get profile() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.profile", - "DEP_WEBPACK_MODULE_PROFILE" - ).getProfile(this); - } - - set profile(value) { - ModuleGraph.getModuleGraphForModule( - this, - "Module.profile", - "DEP_WEBPACK_MODULE_PROFILE" - ).setProfile(this, value); - } - - get index() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.index", - "DEP_WEBPACK_MODULE_INDEX" - ).getPreOrderIndex(this); - } - - set index(value) { - ModuleGraph.getModuleGraphForModule( - this, - "Module.index", - "DEP_WEBPACK_MODULE_INDEX" - ).setPreOrderIndex(this, value); - } - - get index2() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.index2", - "DEP_WEBPACK_MODULE_INDEX2" - ).getPostOrderIndex(this); - } - - set index2(value) { - ModuleGraph.getModuleGraphForModule( - this, - "Module.index2", - "DEP_WEBPACK_MODULE_INDEX2" - ).setPostOrderIndex(this, value); + updateAsset( + file, + newSourceOrFunction, + assetInfoUpdateOrFunction = undefined + ) { + if (!this.assets[file]) { + throw new Error( + `Called Compilation.updateAsset for not existing filename ${file}` + ); + } + if (typeof newSourceOrFunction === "function") { + this.assets[file] = newSourceOrFunction(this.assets[file]); + } else { + this.assets[file] = newSourceOrFunction; + } + if (assetInfoUpdateOrFunction !== undefined) { + const oldInfo = this.assetsInfo.get(file) || EMPTY_ASSET_INFO; + if (typeof assetInfoUpdateOrFunction === "function") { + this._setAssetInfo(file, assetInfoUpdateOrFunction(oldInfo), oldInfo); + } else { + this._setAssetInfo( + file, + cachedCleverMerge(oldInfo, assetInfoUpdateOrFunction), + oldInfo + ); + } + } } - get depth() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.depth", - "DEP_WEBPACK_MODULE_DEPTH" - ).getDepth(this); - } - - set depth(value) { - ModuleGraph.getModuleGraphForModule( - this, - "Module.depth", - "DEP_WEBPACK_MODULE_DEPTH" - ).setDepth(this, value); - } - - get issuer() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.issuer", - "DEP_WEBPACK_MODULE_ISSUER" - ).getIssuer(this); - } - - set issuer(value) { - ModuleGraph.getModuleGraphForModule( - this, - "Module.issuer", - "DEP_WEBPACK_MODULE_ISSUER" - ).setIssuer(this, value); - } - - get usedExports() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.usedExports", - "DEP_WEBPACK_MODULE_USED_EXPORTS" - ).getUsedExports(this, undefined); - } - - /** - * @deprecated - * @returns {(string | OptimizationBailoutFunction)[]} list - */ - get optimizationBailout() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.optimizationBailout", - "DEP_WEBPACK_MODULE_OPTIMIZATION_BAILOUT" - ).getOptimizationBailout(this); - } - - get optional() { - return this.isOptional( - ModuleGraph.getModuleGraphForModule( - this, - "Module.optional", - "DEP_WEBPACK_MODULE_OPTIONAL" - ) - ); - } - - addChunk(chunk) { - const chunkGraph = ChunkGraph.getChunkGraphForModule( - this, - "Module.addChunk", - "DEP_WEBPACK_MODULE_ADD_CHUNK" - ); - if (chunkGraph.isModuleInChunk(this, chunk)) return false; - chunkGraph.connectChunkAndModule(chunk, this); - return true; - } - - removeChunk(chunk) { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.removeChunk", - "DEP_WEBPACK_MODULE_REMOVE_CHUNK" - ).disconnectChunkAndModule(chunk, this); - } - - isInChunk(chunk) { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.isInChunk", - "DEP_WEBPACK_MODULE_IS_IN_CHUNK" - ).isModuleInChunk(this, chunk); - } - - isEntryModule() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.isEntryModule", - "DEP_WEBPACK_MODULE_IS_ENTRY_MODULE" - ).isEntryModule(this); - } - - getChunks() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.getChunks", - "DEP_WEBPACK_MODULE_GET_CHUNKS" - ).getModuleChunks(this); - } - - getNumberOfChunks() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.getNumberOfChunks", - "DEP_WEBPACK_MODULE_GET_NUMBER_OF_CHUNKS" - ).getNumberOfModuleChunks(this); - } - - get chunksIterable() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.chunksIterable", - "DEP_WEBPACK_MODULE_CHUNKS_ITERABLE" - ).getOrderedModuleChunksIterable(this, compareChunksById); - } - - /** - * @param {string} exportName a name of an export - * @returns {boolean | null} true, if the export is provided why the module. - * null, if it's unknown. - * false, if it's not provided. - */ - isProvided(exportName) { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.usedExports", - "DEP_WEBPACK_MODULE_USED_EXPORTS" - ).isExportProvided(this, exportName); - } - // BACKWARD-COMPAT END - - /** - * @deprecated moved to .buildInfo.exportsArgument - * @returns {string} name of the exports argument - */ - get exportsArgument() { - return (this.buildInfo && this.buildInfo.exportsArgument) || "exports"; - } - - /** - * @deprecated moved to .buildInfo.moduleArgument - * @returns {string} name of the module argument - */ - get moduleArgument() { - return (this.buildInfo && this.buildInfo.moduleArgument) || "module"; - } - - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {boolean} strict the importing module is strict - * @returns {"namespace" | "default-only" | "default-with-named" | "dynamic"} export type - * "namespace": Exports is already a namespace object. namespace = exports. - * "dynamic": Check at runtime if __esModule is set. When set: namespace = { ...exports, default: exports }. When not set: namespace = { default: exports }. - * "default-only": Provide a namespace object with only default export. namespace = { default: exports } - * "default-with-named": Provide a namespace object with named and default export. namespace = { ...exports, default: exports } - */ - getExportsType(moduleGraph, strict) { - switch (this.buildMeta && this.buildMeta.exportsType) { - case "flagged": - return strict ? "default-with-named" : "namespace"; - case "namespace": - return "namespace"; - case "default": - switch (this.buildMeta.defaultObject) { - case "redirect": - return "default-with-named"; - case "redirect-warn": - return strict ? "default-only" : "default-with-named"; - default: - return "default-only"; - } - case "dynamic": { - if (strict) return "default-with-named"; - // Try to figure out value of __esModule by following reexports - const handleDefault = () => { - switch (this.buildMeta.defaultObject) { - case "redirect": - case "redirect-warn": - return "default-with-named"; - default: - return "default-only"; - } - }; - const exportInfo = moduleGraph.getReadOnlyExportInfo( - this, - "__esModule" + renameAsset(file, newFile) { + const source = this.assets[file]; + if (!source) { + throw new Error( + `Called Compilation.renameAsset for not existing filename ${file}` + ); + } + if (this.assets[newFile]) { + if (!isSourceEqual(this.assets[file], source)) { + this.errors.push( + new WebpackError( + `Conflict: Called Compilation.renameAsset for already existing filename ${newFile} with different content` + ) ); - if (exportInfo.provided === false) { - return handleDefault(); + } + } + const assetInfo = this.assetsInfo.get(file); + // Update related in all other assets + const relatedInInfo = this._assetsRelatedIn.get(file); + if (relatedInInfo) { + for (const [key, assets] of relatedInInfo) { + for (const name of assets) { + const info = this.assetsInfo.get(name); + if (!info) continue; + const related = info.related; + if (!related) continue; + const entry = related[key]; + let newEntry; + if (Array.isArray(entry)) { + newEntry = entry.map(x => (x === file ? newFile : x)); + } else if (entry === file) { + newEntry = newFile; + } else continue; + this.assetsInfo.set(name, { + ...info, + related: { + ...related, + [key]: newEntry + } + }); } - const target = exportInfo.getTarget(moduleGraph); - if ( - !target || - !target.export || - target.export.length !== 1 || - target.export[0] !== "__esModule" - ) { - return "dynamic"; + } + } + this._setAssetInfo(file, undefined, assetInfo); + this._setAssetInfo(newFile, assetInfo); + delete this.assets[file]; + this.assets[newFile] = source; + for (const chunk of this.chunks) { + { + const size = chunk.files.size; + chunk.files.delete(file); + if (size !== chunk.files.size) { + chunk.files.add(newFile); } - switch ( - target.module.buildMeta && - target.module.buildMeta.exportsType - ) { - case "flagged": - case "namespace": - return "namespace"; - case "default": - return handleDefault(); - default: - return "dynamic"; + } + { + const size = chunk.auxiliaryFiles.size; + chunk.auxiliaryFiles.delete(file); + if (size !== chunk.auxiliaryFiles.size) { + chunk.auxiliaryFiles.add(newFile); } } - default: - return strict ? "default-with-named" : "dynamic"; - } - } - - /** - * @param {Dependency} presentationalDependency dependency being tied to module. - * This is a Dependency without edge in the module graph. It's only for presentation. - * @returns {void} - */ - addPresentationalDependency(presentationalDependency) { - if (this.presentationalDependencies === undefined) { - this.presentationalDependencies = []; - } - this.presentationalDependencies.push(presentationalDependency); - } - - /** - * @param {Dependency} codeGenerationDependency dependency being tied to module. - * This is a Dependency where the code generation result of the referenced module is needed during code generation. - * The Dependency should also be added to normal dependencies via addDependency. - * @returns {void} - */ - addCodeGenerationDependency(codeGenerationDependency) { - if (this.codeGenerationDependencies === undefined) { - this.codeGenerationDependencies = []; } - this.codeGenerationDependencies.push(codeGenerationDependency); } /** - * Removes all dependencies and blocks - * @returns {void} + * @param {string} file file name */ - clearDependenciesAndBlocks() { - if (this.presentationalDependencies !== undefined) { - this.presentationalDependencies.length = 0; + deleteAsset(file) { + if (!this.assets[file]) { + return; } - if (this.codeGenerationDependencies !== undefined) { - this.codeGenerationDependencies.length = 0; + delete this.assets[file]; + const assetInfo = this.assetsInfo.get(file); + this._setAssetInfo(file, undefined, assetInfo); + const related = assetInfo && assetInfo.related; + if (related) { + for (const key of Object.keys(related)) { + const checkUsedAndDelete = file => { + if (!this._assetsRelatedIn.has(file)) { + this.deleteAsset(file); + } + }; + const items = related[key]; + if (Array.isArray(items)) { + items.forEach(checkUsedAndDelete); + } else if (items) { + checkUsedAndDelete(items); + } + } } - super.clearDependenciesAndBlocks(); - } - - /** - * @param {WebpackError} warning the warning - * @returns {void} - */ - addWarning(warning) { - if (this._warnings === undefined) { - this._warnings = []; + // TODO If this becomes a performance problem + // store a reverse mapping from asset to chunk + for (const chunk of this.chunks) { + chunk.files.delete(file); + chunk.auxiliaryFiles.delete(file); } - this._warnings.push(warning); - } - - /** - * @returns {Iterable | undefined} list of warnings if any - */ - getWarnings() { - return this._warnings; - } - - /** - * @returns {number} number of warnings - */ - getNumberOfWarnings() { - return this._warnings !== undefined ? this._warnings.length : 0; } - /** - * @param {WebpackError} error the error - * @returns {void} - */ - addError(error) { - if (this._errors === undefined) { - this._errors = []; + getAssets() { + /** @type {Readonly[]} */ + const array = []; + for (const assetName of Object.keys(this.assets)) { + if (Object.prototype.hasOwnProperty.call(this.assets, assetName)) { + array.push({ + name: assetName, + source: this.assets[assetName], + info: this.assetsInfo.get(assetName) || EMPTY_ASSET_INFO + }); + } } - this._errors.push(error); - } - - /** - * @returns {Iterable | undefined} list of errors if any - */ - getErrors() { - return this._errors; + return array; } /** - * @returns {number} number of errors + * @param {string} name the name of the asset + * @returns {Readonly | undefined} the asset or undefined when not found */ - getNumberOfErrors() { - return this._errors !== undefined ? this._errors.length : 0; + getAsset(name) { + if (!Object.prototype.hasOwnProperty.call(this.assets, name)) + return undefined; + return { + name, + source: this.assets[name], + info: this.assetsInfo.get(name) || EMPTY_ASSET_INFO + }; } - /** - * removes all warnings and errors - * @returns {void} - */ - clearWarningsAndErrors() { - if (this._warnings !== undefined) { - this._warnings.length = 0; - } - if (this._errors !== undefined) { - this._errors.length = 0; + clearAssets() { + for (const chunk of this.chunks) { + chunk.files.clear(); + chunk.auxiliaryFiles.clear(); } } - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {boolean} true, if the module is optional - */ - isOptional(moduleGraph) { - let hasConnections = false; - for (const r of moduleGraph.getIncomingConnections(this)) { - if ( - !r.dependency || - !r.dependency.optional || - !r.isTargetActive(undefined) - ) { - return false; + createModuleAssets() { + const { chunkGraph } = this; + for (const module of this.modules) { + if (module.buildInfo.assets) { + const assetsInfo = module.buildInfo.assetsInfo; + for (const assetName of Object.keys(module.buildInfo.assets)) { + const fileName = this.getPath(assetName, { + chunkGraph: this.chunkGraph, + module + }); + for (const chunk of chunkGraph.getModuleChunksIterable(module)) { + chunk.auxiliaryFiles.add(fileName); + } + this.emitAsset( + fileName, + module.buildInfo.assets[assetName], + assetsInfo ? assetsInfo.get(assetName) : undefined + ); + this.hooks.moduleAsset.call(module, fileName); + } } - hasConnections = true; } - return hasConnections; } /** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {Chunk} chunk a chunk - * @param {Chunk=} ignoreChunk chunk to be ignored - * @returns {boolean} true, if the module is accessible from "chunk" when ignoring "ignoreChunk" + * @param {RenderManifestOptions} options options object + * @returns {RenderManifestEntry[]} manifest entries */ - isAccessibleInChunk(chunkGraph, chunk, ignoreChunk) { - // Check if module is accessible in ALL chunk groups - for (const chunkGroup of chunk.groupsIterable) { - if (!this.isAccessibleInChunkGroup(chunkGraph, chunkGroup)) return false; - } - return true; + getRenderManifest(options) { + return this.hooks.renderManifest.call([], options); } /** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {ChunkGroup} chunkGroup a chunk group - * @param {Chunk=} ignoreChunk chunk to be ignored - * @returns {boolean} true, if the module is accessible from "chunkGroup" when ignoring "ignoreChunk" + * @param {Callback} callback signals when the call finishes + * @returns {void} */ - isAccessibleInChunkGroup(chunkGraph, chunkGroup, ignoreChunk) { - const queue = new Set([chunkGroup]); + createChunkAssets(callback) { + const outputOptions = this.outputOptions; + const cachedSourceMap = new WeakMap(); + /** @type {Map} */ + const alreadyWrittenFiles = new Map(); - // Check if module is accessible from all items of the queue - queueFor: for (const cg of queue) { - // 1. If module is in one of the chunks of the group we can continue checking the next items - // because it's accessible. - for (const chunk of cg.chunks) { - if (chunk !== ignoreChunk && chunkGraph.isModuleInChunk(this, chunk)) - continue queueFor; - } - // 2. If the chunk group is initial, we can break here because it's not accessible. - if (chunkGroup.isInitial()) return false; - // 3. Enqueue all parents because it must be accessible from ALL parents - for (const parent of chunkGroup.parentsIterable) queue.add(parent); - } - // When we processed through the whole list and we didn't bailout, the module is accessible - return true; - } + asyncLib.forEachLimit( + this.chunks, + 15, + (chunk, callback) => { + /** @type {RenderManifestEntry[]} */ + let manifest; + try { + manifest = this.getRenderManifest({ + chunk, + hash: this.hash, + fullHash: this.fullHash, + outputOptions, + codeGenerationResults: this.codeGenerationResults, + moduleTemplates: this.moduleTemplates, + dependencyTemplates: this.dependencyTemplates, + chunkGraph: this.chunkGraph, + moduleGraph: this.moduleGraph, + runtimeTemplate: this.runtimeTemplate + }); + } catch (err) { + this.errors.push(new ChunkRenderError(chunk, "", err)); + return callback(); + } + asyncLib.forEach( + manifest, + (fileManifest, callback) => { + const ident = fileManifest.identifier; + const usedHash = fileManifest.hash; - /** - * @param {Chunk} chunk a chunk - * @param {ModuleGraph} moduleGraph the module graph - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {boolean} true, if the module has any reason why "chunk" should be included - */ - hasReasonForChunk(chunk, moduleGraph, chunkGraph) { - // check for each reason if we need the chunk - for (const [ - fromModule, - connections - ] of moduleGraph.getIncomingConnectionsByOriginModule(this)) { - if (!connections.some(c => c.isTargetActive(chunk.runtime))) continue; - for (const originChunk of chunkGraph.getModuleChunksIterable( - fromModule - )) { - // return true if module this is not reachable from originChunk when ignoring chunk - if (!this.isAccessibleInChunk(chunkGraph, originChunk, chunk)) - return true; - } - } - return false; - } + const assetCacheItem = this._assetsCache.getItemCache( + ident, + usedHash + ); - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true if at least one other module depends on this module - */ - hasReasons(moduleGraph, runtime) { - for (const c of moduleGraph.getIncomingConnections(this)) { - if (c.isTargetActive(runtime)) return true; - } - return false; - } + assetCacheItem.get((err, sourceFromCache) => { + /** @type {string | function(PathData, AssetInfo=): string} */ + let filenameTemplate; + /** @type {string} */ + let file; + /** @type {AssetInfo} */ + let assetInfo; - /** - * @returns {string} for debugging - */ - toString() { - return `Module[${this.debugId}: ${this.identifier()}]`; - } + let inTry = true; + const errorAndCallback = err => { + const filename = + file || + (typeof file === "string" + ? file + : typeof filenameTemplate === "string" + ? filenameTemplate + : ""); - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - callback( - null, - !this.buildMeta || - this.needRebuild === Module.prototype.needRebuild || - deprecatedNeedRebuild(this, context) - ); - } + this.errors.push(new ChunkRenderError(chunk, filename, err)); + inTry = false; + return callback(); + }; - /** - * @deprecated Use needBuild instead - * @param {Map} fileTimestamps timestamps of files - * @param {Map} contextTimestamps timestamps of directories - * @returns {boolean} true, if the module needs a rebuild - */ - needRebuild(fileTimestamps, contextTimestamps) { - return true; - } + try { + if ("filename" in fileManifest) { + file = fileManifest.filename; + assetInfo = fileManifest.info; + } else { + filenameTemplate = fileManifest.filenameTemplate; + const pathAndInfo = this.getPathWithInfo( + filenameTemplate, + fileManifest.pathOptions + ); + file = pathAndInfo.path; + assetInfo = fileManifest.info + ? { + ...pathAndInfo.info, + ...fileManifest.info + } + : pathAndInfo.info; + } - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash( - hash, - context = { - chunkGraph: ChunkGraph.getChunkGraphForModule( - this, - "Module.updateHash", - "DEP_WEBPACK_MODULE_UPDATE_HASH" - ), - runtime: undefined - } - ) { - const { chunkGraph, runtime } = context; - hash.update(chunkGraph.getModuleGraphHash(this, runtime)); - if (this.presentationalDependencies !== undefined) { - for (const dep of this.presentationalDependencies) { - dep.updateHash(hash, context); - } - } - super.updateHash(hash, context); - } + if (err) { + return errorAndCallback(err); + } - /** - * @returns {void} - */ - invalidateBuild() { - // should be overridden to support this feature - } + let source = sourceFromCache; - /* istanbul ignore next */ - /** - * @abstract - * @returns {string} a unique identifier of the module - */ - identifier() { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); - } + // check if the same filename was already written by another chunk + const alreadyWritten = alreadyWrittenFiles.get(file); + if (alreadyWritten !== undefined) { + if (alreadyWritten.hash !== usedHash) { + inTry = false; + return callback( + new WebpackError( + `Conflict: Multiple chunks emit assets to the same filename ${file}` + + ` (chunks ${alreadyWritten.chunk.id} and ${chunk.id})` + ) + ); + } else { + source = alreadyWritten.source; + } + } else if (!source) { + // render the asset + source = fileManifest.render(); - /* istanbul ignore next */ - /** - * @abstract - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + // Ensure that source is a cached source to avoid additional cost because of repeated access + if (!(source instanceof CachedSource)) { + const cacheEntry = cachedSourceMap.get(source); + if (cacheEntry) { + source = cacheEntry; + } else { + const cachedSource = new CachedSource(source); + cachedSourceMap.set(source, cachedSource); + source = cachedSource; + } + } + } + this.emitAsset(file, source, assetInfo); + if (fileManifest.auxiliary) { + chunk.auxiliaryFiles.add(file); + } else { + chunk.files.add(file); + } + this.hooks.chunkAsset.call(chunk, file); + alreadyWrittenFiles.set(file, { + hash: usedHash, + source, + chunk + }); + if (source !== sourceFromCache) { + assetCacheItem.store(source, err => { + if (err) return errorAndCallback(err); + inTry = false; + return callback(); + }); + } else { + inTry = false; + callback(); + } + } catch (err) { + if (!inTry) throw err; + errorAndCallback(err); + } + }); + }, + callback + ); + }, + callback + ); } - /* istanbul ignore next */ /** - * @abstract - * @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} + * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash + * @param {PathData} data context data + * @returns {string} interpolated path */ - build(options, compilation, resolver, fs, callback) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + getPath(filename, data = {}) { + if (!data.hash) { + data = { + hash: this.hash, + ...data + }; + } + return this.getAssetPath(filename, data); } /** - * @abstract - * @returns {Set} types available (do not mutate) + * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash + * @param {PathData} data context data + * @returns {{ path: string, info: AssetInfo }} interpolated path and asset info */ - getSourceTypes() { - // Better override this method to return the correct types - if (this.source === Module.prototype.source) { - return DEFAULT_TYPES_UNKNOWN; - } else { - return DEFAULT_TYPES_JS; + getPathWithInfo(filename, data = {}) { + if (!data.hash) { + data = { + hash: this.hash, + ...data + }; } + return this.getAssetPathWithInfo(filename, data); } /** - * @abstract - * @deprecated Use codeGeneration() instead - * @param {DependencyTemplates} dependencyTemplates the dependency templates - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {string=} type the type of source that should be generated - * @returns {Source} generated source + * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash + * @param {PathData} data context data + * @returns {string} interpolated path */ - source(dependencyTemplates, runtimeTemplate, type = "javascript") { - if (this.codeGeneration === Module.prototype.codeGeneration) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); - } - const chunkGraph = ChunkGraph.getChunkGraphForModule( - this, - "Module.source() is deprecated. Use Compilation.codeGenerationResults.getSource(module, runtime, type) instead", - "DEP_WEBPACK_MODULE_SOURCE" + getAssetPath(filename, data) { + return this.hooks.assetPath.call( + typeof filename === "function" ? filename(data) : filename, + data, + undefined ); - /** @type {CodeGenerationContext} */ - const codeGenContext = { - dependencyTemplates, - runtimeTemplate, - moduleGraph: chunkGraph.moduleGraph, - chunkGraph, - runtime: undefined, - codeGenerationResults: undefined - }; - const sources = this.codeGeneration(codeGenContext).sources; - return type ? sources.get(type) : sources.get(first(this.getSourceTypes())); } - /* istanbul ignore next */ /** - * @abstract - * @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) + * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash + * @param {PathData} data context data + * @returns {{ path: string, info: AssetInfo }} interpolated path and asset info */ - size(type) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + getAssetPathWithInfo(filename, data) { + const assetInfo = {}; + // TODO webpack 5: refactor assetPath hook to receive { path, info } object + const newPath = this.hooks.assetPath.call( + typeof filename === "function" ? filename(data, assetInfo) : filename, + data, + assetInfo + ); + return { path: newPath, info: assetInfo }; } - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - return null; + getWarnings() { + return this.hooks.processWarnings.call(this.warnings); } - /** - * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) - */ - nameForCondition() { - return null; + getErrors() { + return this.hooks.processErrors.call(this.errors); } /** - * @param {ConcatenationBailoutReasonContext} context context - * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + * This function allows you to run another instance of webpack inside of webpack however as + * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins + * from parent (or top level compiler) and creates a child Compilation + * + * @param {string} name name of the child compiler + * @param {OutputOptions=} outputOptions // Need to convert config schema to types for this + * @param {Array=} plugins webpack plugins that will be applied + * @returns {Compiler} creates a child Compiler instance */ - getConcatenationBailoutReason(context) { - return `Module Concatenation is not implemented for ${this.constructor.name}`; + createChildCompiler(name, outputOptions, plugins) { + const idx = this.childrenCounters[name] || 0; + this.childrenCounters[name] = idx + 1; + return this.compiler.createChildCompiler( + this, + name, + idx, + outputOptions, + plugins + ); } /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only + * @param {Module} module the module + * @param {ExecuteModuleOptions} options options + * @param {ExecuteModuleCallback} callback callback */ - getSideEffectsConnectionState(moduleGraph) { - return true; - } + executeModule(module, options, callback) { + // Aggregate all referenced modules and ensure they are ready + const modules = new Set([module]); + processAsyncTree( + modules, + 10, + /** + * @param {Module} module the module + * @param {function(Module): void} push push more jobs + * @param {Callback} callback callback + * @returns {void} + */ + (module, push, callback) => { + this.buildQueue.waitFor(module, err => { + if (err) return callback(err); + this.processDependenciesQueue.waitFor(module, err => { + if (err) return callback(err); + for (const { module: m } of this.moduleGraph.getOutgoingConnections( + module + )) { + const size = modules.size; + modules.add(m); + if (modules.size !== size) push(m); + } + callback(); + }); + }); + }, + err => { + if (err) return callback(err); - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration(context) { - // Best override this method - const sources = new Map(); - for (const type of this.getSourceTypes()) { - if (type !== "unknown") { - sources.set( - type, - this.source( - context.dependencyTemplates, - context.runtimeTemplate, - type - ) + // Create new chunk graph, chunk and entrypoint for the build time execution + const chunkGraph = new ChunkGraph( + this.moduleGraph, + this.outputOptions.hashFunction ); - } - } - return { - sources, - runtimeRequirements: new Set([ - RuntimeGlobals.module, - RuntimeGlobals.exports, - RuntimeGlobals.require - ]) - }; - } - - /** - * @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, compilation) { - return true; - } - - hasChunkCondition() { - return this.chunkCondition !== Module.prototype.chunkCondition; - } + const runtime = "build time"; + const { hashFunction, hashDigest, hashDigestLength } = + this.outputOptions; + const runtimeTemplate = this.runtimeTemplate; - /** - * 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) { - this.type = module.type; - this.layer = module.layer; - this.context = module.context; - this.factoryMeta = module.factoryMeta; - this.resolveOptions = module.resolveOptions; - } + const chunk = new Chunk("build time chunk", this._backCompat); + chunk.id = chunk.name; + chunk.ids = [chunk.id]; + chunk.runtime = runtime; - /** - * Module should be unsafe cached. Get data that's needed for that. - * This data will be passed to restoreFromUnsafeCache later. - * @returns {object} cached data - */ - getUnsafeCacheData() { - return { - factoryMeta: this.factoryMeta, - resolveOptions: this.resolveOptions - }; - } + const entrypoint = new Entrypoint({ + runtime, + chunkLoading: false, + ...options.entryOptions + }); + chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint); + connectChunkGroupAndChunk(entrypoint, chunk); + entrypoint.setRuntimeChunk(chunk); + entrypoint.setEntrypointChunk(chunk); - /** - * restore unsafe cache data - * @param {object} unsafeCacheData data from getUnsafeCacheData - * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching - */ - _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { - this.factoryMeta = unsafeCacheData.factoryMeta; - this.resolveOptions = unsafeCacheData.resolveOptions; - } + const chunks = new Set([chunk]); - /** - * Assuming this module is in the cache. Remove internal references to allow freeing some memory. - */ - cleanupForCache() { - this.factoryMeta = undefined; - this.resolveOptions = undefined; - } + // Assign ids to modules and modules to the chunk + for (const module of modules) { + const id = module.identifier(); + chunkGraph.setModuleId(module, id); + chunkGraph.connectChunkAndModule(chunk, module); + } - /** - * @returns {Source | null} the original source for the module before webpack transformation - */ - originalSource() { - return null; - } + // Hash modules + for (const module of modules) { + this._createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength + ); + } - /** - * @param {LazySet} fileDependencies set where file dependencies are added to - * @param {LazySet} contextDependencies set where context dependencies are added to - * @param {LazySet} missingDependencies set where missing dependencies are added to - * @param {LazySet} buildDependencies set where build dependencies are added to - */ - addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ) {} + const codeGenerationResults = new CodeGenerationResults( + this.outputOptions.hashFunction + ); + /** @type {WebpackError[]} */ + const errors = []; + /** + * @param {Module} module the module + * @param {Callback} callback callback + * @returns {void} + */ + const codeGen = (module, callback) => { + this._codeGenerationModule( + module, + runtime, + [runtime], + chunkGraph.getModuleHash(module, runtime), + this.dependencyTemplates, + chunkGraph, + this.moduleGraph, + runtimeTemplate, + errors, + codeGenerationResults, + (err, codeGenerated) => { + callback(err); + } + ); + }; - serialize(context) { - const { write } = context; - write(this.type); - write(this.layer); - write(this.context); - write(this.resolveOptions); - write(this.factoryMeta); - write(this.useSourceMap); - write(this.useSimpleSourceMap); - write( - this._warnings !== undefined && this._warnings.length === 0 - ? undefined - : this._warnings - ); - write( - this._errors !== undefined && this._errors.length === 0 - ? undefined - : this._errors - ); - write(this.buildMeta); - write(this.buildInfo); - write(this.presentationalDependencies); - write(this.codeGenerationDependencies); - super.serialize(context); - } + const reportErrors = () => { + if (errors.length > 0) { + errors.sort( + compareSelect(err => err.module, compareModulesByIdentifier) + ); + for (const error of errors) { + this.errors.push(error); + } + errors.length = 0; + } + }; - deserialize(context) { - const { read } = context; - this.type = read(); - this.layer = read(); - this.context = read(); - this.resolveOptions = read(); - this.factoryMeta = read(); - this.useSourceMap = read(); - this.useSimpleSourceMap = read(); - this._warnings = read(); - this._errors = read(); - this.buildMeta = read(); - this.buildInfo = read(); - this.presentationalDependencies = read(); - this.codeGenerationDependencies = read(); - super.deserialize(context); - } -} + // Generate code for all aggregated modules + asyncLib.eachLimit(modules, 10, codeGen, err => { + if (err) return callback(err); + reportErrors(); -makeSerializable(Module, "webpack/lib/Module"); + // for backward-compat temporary set the chunk graph + // TODO webpack 6 + const old = this.chunkGraph; + this.chunkGraph = chunkGraph; + this.processRuntimeRequirements({ + chunkGraph, + modules, + chunks, + codeGenerationResults, + chunkGraphEntries: chunks + }); + this.chunkGraph = old; -// TODO remove in webpack 6 -Object.defineProperty(Module.prototype, "hasEqualsChunks", { - get() { - throw new Error( - "Module.hasEqualsChunks was renamed (use hasEqualChunks instead)" - ); - } -}); + const runtimeModules = + chunkGraph.getChunkRuntimeModulesIterable(chunk); -// TODO remove in webpack 6 -Object.defineProperty(Module.prototype, "isUsed", { - get() { - throw new Error( - "Module.isUsed was renamed (use getUsedName, isExportUsed or isModuleUsed instead)" - ); - } -}); + // Hash runtime modules + for (const module of runtimeModules) { + modules.add(module); + this._createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength + ); + } -// TODO remove in webpack 6 -Object.defineProperty(Module.prototype, "errors", { - get: util.deprecate( - /** - * @this {Module} - * @returns {WebpackError[]} array - */ - function () { - if (this._errors === undefined) { - this._errors = []; - } - return this._errors; - }, - "Module.errors was removed (use getErrors instead)", - "DEP_WEBPACK_MODULE_ERRORS" - ) -}); + // Generate code for all runtime modules + asyncLib.eachLimit(runtimeModules, 10, codeGen, err => { + if (err) return callback(err); + reportErrors(); -// TODO remove in webpack 6 -Object.defineProperty(Module.prototype, "warnings", { - get: util.deprecate( - /** - * @this {Module} - * @returns {WebpackError[]} array - */ - function () { - if (this._warnings === undefined) { - this._warnings = []; - } - return this._warnings; - }, - "Module.warnings was removed (use getWarnings instead)", - "DEP_WEBPACK_MODULE_WARNINGS" - ) -}); + /** @type {Map} */ + const moduleArgumentsMap = new Map(); + /** @type {Map} */ + const moduleArgumentsById = new Map(); -// TODO remove in webpack 6 -Object.defineProperty(Module.prototype, "used", { - get() { - throw new Error( - "Module.used was refactored (use ModuleGraph.getUsedExports instead)" - ); - }, - set(value) { - throw new Error( - "Module.used was refactored (use ModuleGraph.setUsedExports instead)" - ); - } -}); + /** @type {ExecuteModuleResult["fileDependencies"]} */ + const fileDependencies = new LazySet(); + /** @type {ExecuteModuleResult["contextDependencies"]} */ + const contextDependencies = new LazySet(); + /** @type {ExecuteModuleResult["missingDependencies"]} */ + const missingDependencies = new LazySet(); + /** @type {ExecuteModuleResult["buildDependencies"]} */ + const buildDependencies = new LazySet(); -module.exports = Module; + /** @type {ExecuteModuleResult["assets"]} */ + const assets = new Map(); + let cacheable = true; -/***/ }), + /** @type {ExecuteModuleContext} */ + const context = { + assets, + __webpack_require__: undefined, + chunk, + chunkGraph + }; -/***/ 21305: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Prepare execution + asyncLib.eachLimit( + modules, + 10, + (module, callback) => { + const codeGenerationResult = codeGenerationResults.get( + module, + runtime + ); + /** @type {ExecuteModuleArgument} */ + const moduleArgument = { + module, + codeGenerationResult, + preparedInfo: undefined, + moduleObject: undefined + }; + moduleArgumentsMap.set(module, moduleArgument); + moduleArgumentsById.set(module.identifier(), moduleArgument); + module.addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ); + if (module.buildInfo.cacheable === false) { + cacheable = false; + } + if (module.buildInfo && module.buildInfo.assets) { + const { assets: moduleAssets, assetsInfo } = module.buildInfo; + for (const assetName of Object.keys(moduleAssets)) { + assets.set(assetName, { + source: moduleAssets[assetName], + info: assetsInfo ? assetsInfo.get(assetName) : undefined + }); + } + } + this.hooks.prepareModuleExecution.callAsync( + moduleArgument, + context, + callback + ); + }, + err => { + if (err) return callback(err); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + let exports; + try { + const { + strictModuleErrorHandling, + strictModuleExceptionHandling + } = this.outputOptions; + const __nested_webpack_require_152290__ = id => { + const cached = moduleCache[id]; + if (cached !== undefined) { + if (cached.error) throw cached.error; + return cached.exports; + } + const moduleArgument = moduleArgumentsById.get(id); + return __webpack_require_module__(moduleArgument, id); + }; + const interceptModuleExecution = (__nested_webpack_require_152290__[ + RuntimeGlobals.interceptModuleExecution.replace( + "__webpack_require__.", + "" + ) + ] = []); + const moduleCache = (__nested_webpack_require_152290__[ + RuntimeGlobals.moduleCache.replace( + "__webpack_require__.", + "" + ) + ] = {}); + context.__webpack_require__ = __nested_webpack_require_152290__; + /** + * @param {ExecuteModuleArgument} moduleArgument the module argument + * @param {string=} id id + * @returns {any} exports + */ + const __webpack_require_module__ = (moduleArgument, id) => { + var execOptions = { + id, + module: { + id, + exports: {}, + loaded: false, + error: undefined + }, + require: __nested_webpack_require_152290__ + }; + interceptModuleExecution.forEach(handler => + handler(execOptions) + ); + const module = moduleArgument.module; + this.buildTimeExecutedModules.add(module); + const moduleObject = execOptions.module; + moduleArgument.moduleObject = moduleObject; + try { + if (id) moduleCache[id] = moduleObject; -const { cutOffLoaderExecution } = __webpack_require__(59985); -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); + tryRunOrWebpackError( + () => + this.hooks.executeModule.call( + moduleArgument, + context + ), + "Compilation.hooks.executeModule" + ); + moduleObject.loaded = true; + return moduleObject.exports; + } catch (e) { + if (strictModuleExceptionHandling) { + if (id) delete moduleCache[id]; + } else if (strictModuleErrorHandling) { + moduleObject.error = e; + } + if (!e.module) e.module = module; + throw e; + } + }; -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; + for (const runtimeModule of chunkGraph.getChunkRuntimeModulesInOrder( + chunk + )) { + __webpack_require_module__( + moduleArgumentsMap.get(runtimeModule) + ); + } + exports = __nested_webpack_require_152290__(module.identifier()); + } catch (e) { + const err = new WebpackError( + `Execution of module code from module graph (${module.readableIdentifier( + this.requestShortener + )}) failed: ${e.message}` + ); + err.stack = e.stack; + err.module = e.module; + return callback(err); + } - if (from) { - message += ` (from ${from}):\n`; - } else { - message += ": "; - } + callback(null, { + exports, + assets, + cacheable, + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + }); + } + ); + }); + }); + } + ); + } - if (err !== null && typeof err === "object") { - if (typeof err.stack === "string" && err.stack) { - const stack = cutOffLoaderExecution(err.stack); + checkConstraints() { + const chunkGraph = this.chunkGraph; - if (!err.hideStack) { - message += stack; - } else { - details = stack; + /** @type {Set} */ + const usedIds = new Set(); - 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); + for (const module of this.modules) { + if (module.type === "runtime") continue; + const moduleId = chunkGraph.getModuleId(module); + if (moduleId === null) continue; + if (usedIds.has(moduleId)) { + throw new Error(`checkConstraints: duplicate module id ${moduleId}`); } - } else { - message += String(err); + usedIds.add(moduleId); } - super(message); + for (const chunk of this.chunks) { + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (!this.modules.has(module)) { + throw new Error( + "checkConstraints: module in chunk but not in compilation " + + ` ${chunk.debugId} ${module.debugId}` + ); + } + } + for (const module of chunkGraph.getChunkEntryModulesIterable(chunk)) { + if (!this.modules.has(module)) { + throw new Error( + "checkConstraints: entry module in chunk but not in compilation " + + ` ${chunk.debugId} ${module.debugId}` + ); + } + } + } - this.name = "ModuleBuildError"; - this.details = details; - this.error = err; + for (const chunkGroup of this.chunkGroups) { + chunkGroup.checkConstraints(); + } } +} - serialize(context) { - const { write } = context; +/** + * @typedef {Object} FactorizeModuleOptions + * @property {ModuleProfile} currentProfile + * @property {ModuleFactory} factory + * @property {Dependency[]} dependencies + * @property {boolean=} factoryResult return full ModuleFactoryResult instead of only module + * @property {Module | null} originModule + * @property {Partial=} contextInfo + * @property {string=} context + */ - write(this.error); +/** + * @param {FactorizeModuleOptions} options options object + * @param {ModuleCallback | ModuleFactoryResultCallback} callback callback + * @returns {void} + */ - super.serialize(context); +// Workaround for typescript as it doesn't support function overloading in jsdoc within a class +Compilation.prototype.factorizeModule = /** @type {{ + (options: FactorizeModuleOptions & { factoryResult?: false }, callback: ModuleCallback): void; + (options: FactorizeModuleOptions & { factoryResult: true }, callback: ModuleFactoryResultCallback): void; +}} */ ( + function (options, callback) { + this.factorizeQueue.add(options, callback); } +); - deserialize(context) { - const { read } = context; - - this.error = read(); +// Hide from typescript +const compilationPrototype = Compilation.prototype; - super.deserialize(context); +// TODO webpack 6 remove +Object.defineProperty(compilationPrototype, "modifyHash", { + writable: false, + enumerable: false, + configurable: false, + value: () => { + throw new Error( + "Compilation.modifyHash was removed in favor of Compilation.hooks.fullHash" + ); } -} +}); -makeSerializable(ModuleBuildError, "webpack/lib/ModuleBuildError"); +// TODO webpack 6 remove +Object.defineProperty(compilationPrototype, "cache", { + enumerable: false, + configurable: false, + get: util.deprecate( + /** + * @this {Compilation} the compilation + * @returns {Cache} the cache + */ + function () { + return this.compiler.cache; + }, + "Compilation.cache was removed in favor of Compilation.getCache()", + "DEP_WEBPACK_COMPILATION_CACHE" + ), + set: util.deprecate( + v => {}, + "Compilation.cache was removed in favor of Compilation.getCache()", + "DEP_WEBPACK_COMPILATION_CACHE" + ) +}); -module.exports = ModuleBuildError; +/** + * Add additional assets to the compilation. + */ +Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL = -2000; +/** + * Basic preprocessing of assets. + */ +Compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS = -1000; -/***/ }), +/** + * Derive new assets from existing assets. + * Existing assets should not be treated as complete. + */ +Compilation.PROCESS_ASSETS_STAGE_DERIVED = -200; -/***/ 67409: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * Add additional sections to existing assets, like a banner or initialization code. + */ +Compilation.PROCESS_ASSETS_STAGE_ADDITIONS = -100; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * Optimize existing assets in a general way. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE = 100; +/** + * Optimize the count of existing assets, e. g. by merging them. + * Only assets of the same type should be merged. + * For assets of different types see PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT = 200; +/** + * Optimize the compatibility of existing assets, e. g. add polyfills or vendor-prefixes. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY = 300; -const WebpackError = __webpack_require__(53799); +/** + * Optimize the size of existing assets, e. g. by minimizing or omitting whitespace. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE = 400; -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Module")} Module */ +/** + * Add development tooling to assets, e. g. by extracting a SourceMap. + */ +Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING = 500; -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); +/** + * Optimize the count of existing assets, e. g. by inlining assets of into other assets. + * Only assets of different types should be inlined. + * For assets of the same type see PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE = 700; - 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; +/** + * Summarize the list of existing assets + * e. g. creating an assets manifest of Service Workers. + */ +Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE = 1000; - if (err && /** @type {any} */ (err).hideStack) { - this.stack = - err.stack.split("\n").slice(1).join("\n") + "\n\n" + this.stack; - } - } -} +/** + * Optimize the hashes of the assets, e. g. by generating real hashes of the asset content. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH = 2500; -module.exports = ModuleDependencyError; +/** + * Optimize the transfer of existing assets, e. g. by preparing a compressed (gzip) file as separate asset. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER = 3000; + +/** + * Analyse existing assets. + */ +Compilation.PROCESS_ASSETS_STAGE_ANALYSE = 4000; + +/** + * Creating assets for reporting purposes. + */ +Compilation.PROCESS_ASSETS_STAGE_REPORT = 5000; + +module.exports = Compilation; /***/ }), -/***/ 29656: +/***/ 70845: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -44857,1325 +40314,1221 @@ module.exports = ModuleDependencyError; +const parseJson = __webpack_require__(15235); +const asyncLib = __webpack_require__(78175); +const { + SyncHook, + SyncBailHook, + AsyncParallelHook, + AsyncSeriesHook +} = __webpack_require__(41242); +const { SizeOnlySource } = __webpack_require__(51255); +const webpack = __webpack_require__(91919); +const Cache = __webpack_require__(7592); +const CacheFacade = __webpack_require__(55392); +const ChunkGraph = __webpack_require__(64971); +const Compilation = __webpack_require__(85720); +const ConcurrentCompilationError = __webpack_require__(95735); +const ContextModuleFactory = __webpack_require__(62471); +const ModuleGraph = __webpack_require__(99988); +const NormalModuleFactory = __webpack_require__(68860); +const RequestShortener = __webpack_require__(73406); +const ResolverFactory = __webpack_require__(30217); +const Stats = __webpack_require__(31743); +const Watching = __webpack_require__(84275); const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); +const { Logger } = __webpack_require__(32597); +const { join, dirname, mkdirp } = __webpack_require__(17139); +const { makePathsRelative } = __webpack_require__(82186); +const { isSourceEqual } = __webpack_require__(41245); -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} Entry */ +/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ /** @typedef {import("./Module")} Module */ +/** @typedef {import("./util/WeakTupleMap")} WeakTupleMap */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */ +/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ +/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */ -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; +/** + * @typedef {Object} CompilationParams + * @property {NormalModuleFactory} normalModuleFactory + * @property {ContextModuleFactory} contextModuleFactory + */ - if (err && /** @type {any} */ (err).hideStack) { - this.stack = - err.stack.split("\n").slice(1).join("\n") + "\n\n" + this.stack; - } - } -} +/** + * @template T + * @callback Callback + * @param {(Error | null)=} err + * @param {T=} result + */ -makeSerializable( - ModuleDependencyWarning, - "webpack/lib/ModuleDependencyWarning" -); +/** + * @callback RunAsChildCallback + * @param {(Error | null)=} err + * @param {Chunk[]=} entries + * @param {Compilation=} compilation + */ -module.exports = ModuleDependencyWarning; +/** + * @typedef {Object} AssetEmittedInfo + * @property {Buffer} content + * @property {Source} source + * @property {Compilation} compilation + * @property {string} outputPath + * @property {string} targetPath + */ +/** + * @param {string[]} array an array + * @returns {boolean} true, if the array is sorted + */ +const isSorted = array => { + for (let i = 1; i < array.length; i++) { + if (array[i - 1] > array[i]) return false; + } + return true; +}; -/***/ }), +/** + * @param {Object} obj an object + * @param {string[]} keys the keys of the object + * @returns {Object} the object with properties sorted by property name + */ +const sortObject = (obj, keys) => { + const o = {}; + for (const k of keys.sort()) { + o[k] = obj[k]; + } + return o; +}; -/***/ 23744: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @param {string} filename filename + * @param {string | string[] | undefined} hashes list of hashes + * @returns {boolean} true, if the filename contains any hash + */ +const includesHash = (filename, hashes) => { + if (!hashes) return false; + if (Array.isArray(hashes)) { + return hashes.some(hash => filename.includes(hash)); + } else { + return filename.includes(hashes); + } +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +class Compiler { + /** + * @param {string} context the compilation path + * @param {WebpackOptions} options options + */ + constructor(context, options = /** @type {WebpackOptions} */ ({})) { + this.hooks = Object.freeze({ + /** @type {SyncHook<[]>} */ + initialize: new SyncHook([]), + /** @type {SyncBailHook<[Compilation], boolean>} */ + shouldEmit: new SyncBailHook(["compilation"]), + /** @type {AsyncSeriesHook<[Stats]>} */ + done: new AsyncSeriesHook(["stats"]), + /** @type {SyncHook<[Stats]>} */ + afterDone: new SyncHook(["stats"]), + /** @type {AsyncSeriesHook<[]>} */ + additionalPass: new AsyncSeriesHook([]), + /** @type {AsyncSeriesHook<[Compiler]>} */ + beforeRun: new AsyncSeriesHook(["compiler"]), + /** @type {AsyncSeriesHook<[Compiler]>} */ + run: new AsyncSeriesHook(["compiler"]), + /** @type {AsyncSeriesHook<[Compilation]>} */ + emit: new AsyncSeriesHook(["compilation"]), + /** @type {AsyncSeriesHook<[string, AssetEmittedInfo]>} */ + assetEmitted: new AsyncSeriesHook(["file", "info"]), + /** @type {AsyncSeriesHook<[Compilation]>} */ + afterEmit: new AsyncSeriesHook(["compilation"]), + /** @type {SyncHook<[Compilation, CompilationParams]>} */ + thisCompilation: new SyncHook(["compilation", "params"]), + /** @type {SyncHook<[Compilation, CompilationParams]>} */ + compilation: new SyncHook(["compilation", "params"]), + /** @type {SyncHook<[NormalModuleFactory]>} */ + normalModuleFactory: new SyncHook(["normalModuleFactory"]), + /** @type {SyncHook<[ContextModuleFactory]>} */ + contextModuleFactory: new SyncHook(["contextModuleFactory"]), -const { cleanUp } = __webpack_require__(59985); -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); + /** @type {AsyncSeriesHook<[CompilationParams]>} */ + beforeCompile: new AsyncSeriesHook(["params"]), + /** @type {SyncHook<[CompilationParams]>} */ + compile: new SyncHook(["params"]), + /** @type {AsyncParallelHook<[Compilation]>} */ + make: new AsyncParallelHook(["compilation"]), + /** @type {AsyncParallelHook<[Compilation]>} */ + finishMake: new AsyncSeriesHook(["compilation"]), + /** @type {AsyncSeriesHook<[Compilation]>} */ + afterCompile: new AsyncSeriesHook(["compilation"]), -class ModuleError extends WebpackError { - /** - * @param {Error} err error thrown - * @param {{from?: string|null}} info additional info - */ - constructor(err, { from = null } = {}) { - let message = "Module Error"; + /** @type {AsyncSeriesHook<[]>} */ + readRecords: new AsyncSeriesHook([]), + /** @type {AsyncSeriesHook<[]>} */ + emitRecords: new AsyncSeriesHook([]), - if (from) { - message += ` (from ${from}):\n`; - } else { - message += ": "; - } + /** @type {AsyncSeriesHook<[Compiler]>} */ + watchRun: new AsyncSeriesHook(["compiler"]), + /** @type {SyncHook<[Error]>} */ + failed: new SyncHook(["error"]), + /** @type {SyncHook<[string | null, number]>} */ + invalid: new SyncHook(["filename", "changeTime"]), + /** @type {SyncHook<[]>} */ + watchClose: new SyncHook([]), + /** @type {AsyncSeriesHook<[]>} */ + shutdown: new AsyncSeriesHook([]), - if (err && typeof err === "object" && err.message) { - message += err.message; - } else if (err) { - message += err; - } + /** @type {SyncBailHook<[string, string, any[]], true>} */ + infrastructureLog: new SyncBailHook(["origin", "type", "args"]), - super(message); + // TODO the following hooks are weirdly located here + // TODO move them for webpack 5 + /** @type {SyncHook<[]>} */ + environment: new SyncHook([]), + /** @type {SyncHook<[]>} */ + afterEnvironment: new SyncHook([]), + /** @type {SyncHook<[Compiler]>} */ + afterPlugins: new SyncHook(["compiler"]), + /** @type {SyncHook<[Compiler]>} */ + afterResolvers: new SyncHook(["compiler"]), + /** @type {SyncBailHook<[string, Entry], boolean>} */ + entryOption: new SyncBailHook(["context", "entry"]) + }); - this.name = "ModuleError"; - this.error = err; - this.details = - err && typeof err === "object" && err.stack - ? cleanUp(err.stack, this.message) - : undefined; - } + this.webpack = webpack; - serialize(context) { - const { write } = context; + /** @type {string=} */ + this.name = undefined; + /** @type {Compilation=} */ + this.parentCompilation = undefined; + /** @type {Compiler} */ + this.root = this; + /** @type {string} */ + this.outputPath = ""; + /** @type {Watching} */ + this.watching = undefined; - write(this.error); + /** @type {OutputFileSystem} */ + this.outputFileSystem = null; + /** @type {IntermediateFileSystem} */ + this.intermediateFileSystem = null; + /** @type {InputFileSystem} */ + this.inputFileSystem = null; + /** @type {WatchFileSystem} */ + this.watchFileSystem = null; - super.serialize(context); - } + /** @type {string|null} */ + this.recordsInputPath = null; + /** @type {string|null} */ + this.recordsOutputPath = null; + this.records = {}; + /** @type {Set} */ + this.managedPaths = new Set(); + /** @type {Set} */ + this.immutablePaths = new Set(); - deserialize(context) { - const { read } = context; + /** @type {ReadonlySet} */ + this.modifiedFiles = undefined; + /** @type {ReadonlySet} */ + this.removedFiles = undefined; + /** @type {ReadonlyMap} */ + this.fileTimestamps = undefined; + /** @type {ReadonlyMap} */ + this.contextTimestamps = undefined; + /** @type {number} */ + this.fsStartTime = undefined; - this.error = read(); + /** @type {ResolverFactory} */ + this.resolverFactory = new ResolverFactory(); - super.deserialize(context); - } -} + this.infrastructureLogger = undefined; -makeSerializable(ModuleError, "webpack/lib/ModuleError"); + this.options = options; -module.exports = ModuleError; + this.context = context; + this.requestShortener = new RequestShortener(context, this.root); -/***/ }), + this.cache = new Cache(); -/***/ 51010: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {Map, memCache: WeakTupleMap }> | undefined} */ + this.moduleMemCaches = undefined; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.compilerPath = ""; + /** @type {boolean} */ + this.running = false; + /** @type {boolean} */ + this.idle = false; -/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Module")} Module */ + /** @type {boolean} */ + this.watchMode = false; -/** - * @typedef {Object} ModuleFactoryResult - * @property {Module=} module the created module or unset if no module was created - * @property {Set=} fileDependencies - * @property {Set=} contextDependencies - * @property {Set=} missingDependencies - * @property {boolean=} cacheable allow to use the unsafe cache - */ + this._backCompat = this.options.experiments.backCompat !== false; -/** - * @typedef {Object} ModuleFactoryCreateDataContextInfo - * @property {string} issuer - * @property {string | null=} issuerLayer - * @property {string} compiler - */ + /** @type {Compilation} */ + this._lastCompilation = undefined; + /** @type {NormalModuleFactory} */ + this._lastNormalModuleFactory = undefined; -/** - * @typedef {Object} ModuleFactoryCreateData - * @property {ModuleFactoryCreateDataContextInfo} contextInfo - * @property {ResolveOptions=} resolveOptions - * @property {string} context - * @property {Dependency[]} dependencies - */ + /** @private @type {WeakMap }>} */ + this._assetEmittingSourceCache = new WeakMap(); + /** @private @type {Map} */ + this._assetEmittingWrittenFiles = new Map(); + /** @private @type {Set} */ + this._assetEmittingPreviousFiles = new Set(); + } -class ModuleFactory { - /* istanbul ignore next */ /** - * @abstract - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback - * @returns {void} + * @param {string} name cache name + * @returns {CacheFacade} the cache facade instance */ - create(data, callback) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + getCache(name) { + return new CacheFacade( + this.cache, + `${this.compilerPath}${name}`, + this.options.output.hashFunction + ); } -} - -module.exports = ModuleFactory; - -/***/ }), - -/***/ 88821: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const NormalModule = __webpack_require__(39); -const createHash = __webpack_require__(49835); -const memoize = __webpack_require__(78676); - -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {typeof import("./util/Hash")} Hash */ - -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, hashFunction) => { - return () => { - const hash = createHash(hashFunction); - 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 - }); + /** + * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name + * @returns {Logger} a logger with that name + */ + getInfrastructureLogger(name) { + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called without a name" + ); + } + return new Logger( + (type, args) => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called with a function not returning a name" + ); + } + } + if (this.hooks.infrastructureLog.call(name, type, args) === undefined) { + if (this.infrastructureLogger !== undefined) { + this.infrastructureLogger(name, type, args); + } + } }, - enumerable: true, - configurable: true - }); - } - return newObj; -}; - -const REGEXP = /\[\\*([\w-]+)\\*\]/gi; - -/** - * - * @param {Module | string} module the module - * @param {TODO} options options - * @param {Object} contextInfo context info - * @param {RequestShortener} contextInfo.requestShortener requestShortener - * @param {ChunkGraph} contextInfo.chunkGraph chunk graph - * @param {string | Hash} contextInfo.hashFunction the hash function to use - * @returns {string} the filename - */ -ModuleFilenameHelpers.createFilename = ( - module = "", - options, - { requestShortener, chunkGraph, hashFunction = "md4" } -) => { - const opts = { - namespace: "", - moduleFilenameTemplate: "", - ...(typeof options === "object" - ? options - : { - moduleFilenameTemplate: options - }) - }; - - let absoluteResourcePath; - let hash; - let identifier; - let moduleId; - let shortIdentifier; - if (typeof module === "string") { - shortIdentifier = memoize(() => requestShortener.shorten(module)); - identifier = shortIdentifier; - moduleId = () => ""; - absoluteResourcePath = () => module.split("!").pop(); - hash = getHash(identifier, hashFunction); - } else { - shortIdentifier = memoize(() => - module.readableIdentifier(requestShortener) - ); - identifier = memoize(() => requestShortener.shorten(module.identifier())); - moduleId = () => chunkGraph.getModuleId(module); - absoluteResourcePath = () => - module instanceof NormalModule - ? module.resource - : module.identifier().split("!").pop(); - hash = getHash(identifier, hashFunction); - } - 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 - }) + childName => { + if (typeof name === "function") { + if (typeof childName === "function") { + return this.getInfrastructureLogger(() => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called with a function not returning a name" + ); + } + } + if (typeof childName === "function") { + childName = childName(); + if (!childName) { + throw new TypeError( + "Logger.getChildLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } else { + return this.getInfrastructureLogger(() => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } + } else { + if (typeof childName === "function") { + return this.getInfrastructureLogger(() => { + if (typeof childName === "function") { + childName = childName(); + if (!childName) { + throw new TypeError( + "Logger.getChildLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } else { + return this.getInfrastructureLogger(`${name}/${childName}`); + } + } + } ); } - // TODO webpack 6: consider removing alternatives without dashes - /** @type {Map} */ - 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)}]`; + // TODO webpack 6: solve this in a better way + // e.g. move compilation specific info from Modules into ModuleGraph + _cleanupLastCompilation() { + if (this._lastCompilation !== undefined) { + for (const module of this._lastCompilation.modules) { + ChunkGraph.clearChunkGraphForModule(module); + ModuleGraph.clearModuleGraphForModule(module); + module.cleanupForCache(); } - 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; + for (const chunk of this._lastCompilation.chunks) { + ChunkGraph.clearChunkGraphForChunk(chunk); + } + this._lastCompilation = undefined; } - }); -}; - -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; + // TODO webpack 6: solve this in a better way + _cleanupLastNormalModuleFactory() { + if (this._lastNormalModuleFactory !== undefined) { + this._lastNormalModuleFactory.cleanupForCache(); + this._lastNormalModuleFactory = undefined; } } - return true; -}; - - -/***/ }), -/***/ 99988: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {WatchOptions} watchOptions the watcher's options + * @param {Callback} handler signals when the call finishes + * @returns {Watching} a compiler watcher + */ + watch(watchOptions, handler) { + if (this.running) { + return handler(new ConcurrentCompilationError()); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.running = true; + this.watchMode = true; + this.watching = new Watching(this, watchOptions, handler); + return this.watching; + } + /** + * @param {Callback} callback signals when the call finishes + * @returns {void} + */ + run(callback) { + if (this.running) { + return callback(new ConcurrentCompilationError()); + } + let logger; -const util = __webpack_require__(73837); -const ExportsInfo = __webpack_require__(63686); -const ModuleGraphConnection = __webpack_require__(40639); -const SortableSet = __webpack_require__(13098); -const WeakTupleMap = __webpack_require__(28745); + const finalCallback = (err, stats) => { + if (logger) logger.time("beginIdle"); + this.idle = true; + this.cache.beginIdle(); + this.idle = true; + if (logger) logger.timeEnd("beginIdle"); + this.running = false; + if (err) { + this.hooks.failed.call(err); + } + if (callback !== undefined) callback(err, stats); + this.hooks.afterDone.call(stats); + }; -/** @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 */ + const startTime = Date.now(); -/** - * @callback OptimizationBailoutFunction - * @param {RequestShortener} requestShortener - * @returns {string} - */ + this.running = true; -const EMPTY_SET = new Set(); + const onCompiled = (err, compilation) => { + if (err) return finalCallback(err); -/** - * @param {SortableSet} set input - * @returns {readonly Map} 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); + if (this.hooks.shouldEmit.call(compilation) === false) { + compilation.startTime = startTime; + compilation.endTime = Date.now(); + const stats = new Stats(compilation); + this.hooks.done.callAsync(stats, err => { + if (err) return finalCallback(err); + return finalCallback(null, stats); + }); + return; } - } - } - return map; -}; -/** - * @param {SortableSet} set input - * @returns {readonly Map} mapped by module - */ -const getConnectionsByModule = set => { - const map = new Map(); - /** @type {Module | 0} */ - let lastModule = 0; - /** @type {ModuleGraphConnection[]} */ - let lastList = undefined; - for (const connection of set) { - const { module } = connection; - if (lastModule === module) { - lastList.push(connection); - } else { - lastModule = module; - const list = map.get(module); - if (list !== undefined) { - lastList = list; - list.push(connection); - } else { - const list = [connection]; - lastList = list; - map.set(module, list); - } - } - } - return map; -}; + process.nextTick(() => { + logger = compilation.getLogger("webpack.Compiler"); + logger.time("emitAssets"); + this.emitAssets(compilation, err => { + logger.timeEnd("emitAssets"); + if (err) return finalCallback(err); -class ModuleGraphModule { - constructor() { - /** @type {SortableSet} */ - this.incomingConnections = new SortableSet(); - /** @type {SortableSet | 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; - /** @type {ModuleGraphConnection[]} */ - this._unassignedConnections = undefined; - } -} + if (compilation.hooks.needAdditionalPass.call()) { + compilation.needAdditionalPass = true; -class ModuleGraph { - constructor() { - /** @type {WeakMap} */ - this._dependencyMap = new WeakMap(); - /** @type {Map} */ - this._moduleMap = new Map(); - /** @type {WeakMap} */ - this._metaMap = new WeakMap(); + compilation.startTime = startTime; + compilation.endTime = Date.now(); + logger.time("done hook"); + const stats = new Stats(compilation); + this.hooks.done.callAsync(stats, err => { + logger.timeEnd("done hook"); + if (err) return finalCallback(err); - /** @type {WeakTupleMap} */ - this._cache = undefined; + this.hooks.additionalPass.callAsync(err => { + if (err) return finalCallback(err); + this.compile(onCompiled); + }); + }); + return; + } - /** @type {Map>} */ - this._moduleMemCaches = undefined; - } + logger.time("emitRecords"); + this.emitRecords(err => { + logger.timeEnd("emitRecords"); + if (err) return finalCallback(err); - /** - * @param {Module} module the module - * @returns {ModuleGraphModule} the internal module - */ - _getModuleGraphModule(module) { - let mgm = this._moduleMap.get(module); - if (mgm === undefined) { - mgm = new ModuleGraphModule(); - this._moduleMap.set(module, mgm); - } - return mgm; - } + compilation.startTime = startTime; + compilation.endTime = Date.now(); + logger.time("done hook"); + const stats = new Stats(compilation); + this.hooks.done.callAsync(stats, err => { + logger.timeEnd("done hook"); + if (err) return finalCallback(err); + this.cache.storeBuildDependencies( + compilation.buildDependencies, + err => { + if (err) return finalCallback(err); + return finalCallback(null, stats); + } + ); + }); + }); + }); + }); + }; - /** - * @param {Dependency} dependency the dependency - * @param {DependenciesBlock} block parent block - * @param {Module} module parent module - * @param {number=} indexInBlock position in block - * @returns {void} - */ - setParents(dependency, block, module, indexInBlock = -1) { - dependency._parentDependenciesBlockIndex = indexInBlock; - dependency._parentDependenciesBlock = block; - dependency._parentModule = module; - } + const run = () => { + this.hooks.beforeRun.callAsync(this, err => { + if (err) return finalCallback(err); - /** - * @param {Dependency} dependency the dependency - * @returns {Module} parent module - */ - getParentModule(dependency) { - return dependency._parentModule; - } + this.hooks.run.callAsync(this, err => { + if (err) return finalCallback(err); - /** - * @param {Dependency} dependency the dependency - * @returns {DependenciesBlock} parent block - */ - getParentBlock(dependency) { - return dependency._parentDependenciesBlock; - } + this.readRecords(err => { + if (err) return finalCallback(err); - /** - * @param {Dependency} dependency the dependency - * @returns {number} index - */ - getParentBlockIndex(dependency) { - return dependency._parentDependenciesBlockIndex; - } + this.compile(onCompiled); + }); + }); + }); + }; - /** - * @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 connections = this._getModuleGraphModule(module).incomingConnections; - connections.add(connection); - if (originModule) { - const mgm = this._getModuleGraphModule(originModule); - if (mgm._unassignedConnections === undefined) { - mgm._unassignedConnections = []; - } - mgm._unassignedConnections.push(connection); - if (mgm.outgoingConnections === undefined) { - mgm.outgoingConnections = new SortableSet(); - } - mgm.outgoingConnections.add(connection); + if (this.idle) { + this.cache.endIdle(err => { + if (err) return finalCallback(err); + + this.idle = false; + run(); + }); } else { - this._dependencyMap.set(dependency, connection); + run(); } } /** - * @param {Dependency} dependency the referencing dependency - * @param {Module} module the referenced module + * @param {RunAsChildCallback} callback signals when the call finishes * @returns {void} */ - updateModule(dependency, module) { - const connection = this.getConnection(dependency); - if (connection.module === module) return; - const newConnection = connection.clone(); - newConnection.module = module; - this._dependencyMap.set(dependency, newConnection); - connection.setActive(false); - const originMgm = this._getModuleGraphModule(connection.originModule); - originMgm.outgoingConnections.add(newConnection); - const targetMgm = this._getModuleGraphModule(module); - targetMgm.incomingConnections.add(newConnection); - } + runAsChild(callback) { + const startTime = Date.now(); + this.compile((err, compilation) => { + if (err) return callback(err); - /** - * @param {Dependency} dependency the referencing dependency - * @returns {void} - */ - removeConnection(dependency) { - const connection = this.getConnection(dependency); - const targetMgm = this._getModuleGraphModule(connection.module); - targetMgm.incomingConnections.delete(connection); - const originMgm = this._getModuleGraphModule(connection.originModule); - originMgm.outgoingConnections.delete(connection); - this._dependencyMap.set(dependency, null); - } + this.parentCompilation.children.push(compilation); + for (const { name, source, info } of compilation.getAssets()) { + this.parentCompilation.emitAsset(name, source, info); + } - /** - * @param {Dependency} dependency the referencing dependency - * @param {string} explanation an explanation - * @returns {void} - */ - addExplanation(dependency, explanation) { - const connection = this.getConnection(dependency); - connection.addExplanation(explanation); - } + const entries = []; + for (const ep of compilation.entrypoints.values()) { + entries.push(...ep.chunks); + } - /** - * @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; - } + compilation.startTime = startTime; + compilation.endTime = Date.now(); - /** - * @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; + return callback(null, entries, compilation); + }); } - /** - * @returns {void} - */ - removeAllModuleAttributes() { - for (const mgm of this._moduleMap.values()) { - mgm.postOrderIndex = null; - mgm.preOrderIndex = null; - mgm.depth = null; - mgm.async = false; + purgeInputFileSystem() { + if (this.inputFileSystem && this.inputFileSystem.purge) { + this.inputFileSystem.purge(); } } /** - * @param {Module} oldModule the old referencing module - * @param {Module} newModule the new referencing module - * @param {function(ModuleGraphConnection): boolean} filterConnection filter predicate for replacement + * @param {Compilation} compilation the compilation + * @param {Callback} callback signals when the assets are emitted * @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 SortableSet(); - } - 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); - } - } - } + emitAssets(compilation, callback) { + let outputPath; - /** - * @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 SortableSet(); - } - 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); + const emitFiles = err => { + if (err) return callback(err); + + const assets = compilation.getAssets(); + compilation.assets = { ...compilation.assets }; + /** @type {Map} */ + const caseInsensitiveMap = new Map(); + /** @type {Set} */ + const allTargetPaths = new Set(); + asyncLib.forEachLimit( + assets, + 15, + ({ name: file, source, info }, callback) => { + let targetFile = file; + let immutable = info.immutable; + const queryStringIdx = targetFile.indexOf("?"); + if (queryStringIdx >= 0) { + targetFile = targetFile.substr(0, queryStringIdx); + // We may remove the hash, which is in the query string + // So we recheck if the file is immutable + // This doesn't cover all cases, but immutable is only a performance optimization anyway + immutable = + immutable && + (includesHash(targetFile, info.contenthash) || + includesHash(targetFile, info.chunkhash) || + includesHash(targetFile, info.modulehash) || + includesHash(targetFile, info.fullhash)); } - } - } - } - } - /** - * @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)); - } + const writeOut = err => { + if (err) return callback(err); + const targetPath = join( + this.outputFileSystem, + outputPath, + targetFile + ); + allTargetPaths.add(targetPath); - /** - * @param {Dependency} dependency the dependency to look for a referenced module - * @returns {Module} the referenced module - */ - getResolvedModule(dependency) { - const connection = this.getConnection(dependency); - return connection !== undefined ? connection.resolvedModule : null; - } + // check if the target file has already been written by this Compiler + const targetFileGeneration = + this._assetEmittingWrittenFiles.get(targetPath); - /** - * @param {Dependency} dependency the dependency to look for a referenced module - * @returns {ModuleGraphConnection | undefined} the connection - */ - getConnection(dependency) { - const connection = this._dependencyMap.get(dependency); - if (connection === undefined) { - const module = this.getParentModule(dependency); - if (module !== undefined) { - const mgm = this._getModuleGraphModule(module); - if ( - mgm._unassignedConnections && - mgm._unassignedConnections.length !== 0 - ) { - let foundConnection; - for (const connection of mgm._unassignedConnections) { - this._dependencyMap.set(connection.dependency, connection); - if (connection.dependency === dependency) - foundConnection = connection; - } - mgm._unassignedConnections.length = 0; - if (foundConnection !== undefined) { - return foundConnection; - } - } - } - this._dependencyMap.set(dependency, null); - return undefined; - } - return connection === null ? undefined : connection; - } + // create an cache entry for this Source if not already existing + let cacheEntry = this._assetEmittingSourceCache.get(source); + if (cacheEntry === undefined) { + cacheEntry = { + sizeOnlySource: undefined, + writtenTo: new Map() + }; + this._assetEmittingSourceCache.set(source, cacheEntry); + } - /** - * @param {Dependency} dependency the dependency to look for a referenced module - * @returns {Module} the referenced module - */ - getModule(dependency) { - const connection = this.getConnection(dependency); - return connection !== undefined ? connection.module : null; - } + let similarEntry; - /** - * @param {Dependency} dependency the dependency to look for a referencing module - * @returns {Module} the referencing module - */ - getOrigin(dependency) { - const connection = this.getConnection(dependency); - return connection !== undefined ? connection.originModule : null; - } + const checkSimilarFile = () => { + const caseInsensitiveTargetPath = targetPath.toLowerCase(); + similarEntry = caseInsensitiveMap.get(caseInsensitiveTargetPath); + if (similarEntry !== undefined) { + const { path: other, source: otherSource } = similarEntry; + if (isSourceEqual(otherSource, source)) { + // Size may or may not be available at this point. + // If it's not available add to "waiting" list and it will be updated once available + if (similarEntry.size !== undefined) { + updateWithReplacementSource(similarEntry.size); + } else { + if (!similarEntry.waiting) similarEntry.waiting = []; + similarEntry.waiting.push({ file, cacheEntry }); + } + alreadyWritten(); + } else { + const err = + new WebpackError(`Prevent writing to file that only differs in casing or query string from already written file. +This will lead to a race-condition and corrupted files on case-insensitive file systems. +${targetPath} +${other}`); + err.file = file; + callback(err); + } + return true; + } else { + caseInsensitiveMap.set( + caseInsensitiveTargetPath, + (similarEntry = { + path: targetPath, + source, + size: undefined, + waiting: undefined + }) + ); + return false; + } + }; - /** - * @param {Dependency} dependency the dependency to look for a referencing module - * @returns {Module} the original referencing module - */ - getResolvedOrigin(dependency) { - const connection = this.getConnection(dependency); - return connection !== undefined ? connection.resolvedOriginModule : null; - } + /** + * get the binary (Buffer) content from the Source + * @returns {Buffer} content for the source + */ + const getContent = () => { + if (typeof source.buffer === "function") { + return source.buffer(); + } else { + const bufferOrString = source.source(); + if (Buffer.isBuffer(bufferOrString)) { + return bufferOrString; + } else { + return Buffer.from(bufferOrString, "utf8"); + } + } + }; - /** - * @param {Module} module the module - * @returns {Iterable} reasons why a module is included - */ - getIncomingConnections(module) { - const connections = this._getModuleGraphModule(module).incomingConnections; - return connections; - } + const alreadyWritten = () => { + // cache the information that the Source has been already been written to that location + if (targetFileGeneration === undefined) { + const newGeneration = 1; + this._assetEmittingWrittenFiles.set(targetPath, newGeneration); + cacheEntry.writtenTo.set(targetPath, newGeneration); + } else { + cacheEntry.writtenTo.set(targetPath, targetFileGeneration); + } + callback(); + }; - /** - * @param {Module} module the module - * @returns {Iterable} list of outgoing connections - */ - getOutgoingConnections(module) { - const connections = this._getModuleGraphModule(module).outgoingConnections; - return connections === undefined ? EMPTY_SET : connections; - } + /** + * Write the file to output file system + * @param {Buffer} content content to be written + * @returns {void} + */ + const doWrite = content => { + this.outputFileSystem.writeFile(targetPath, content, err => { + if (err) return callback(err); - /** - * @param {Module} module the module - * @returns {readonly Map} reasons why a module is included, in a map by source module - */ - getIncomingConnectionsByOriginModule(module) { - const connections = this._getModuleGraphModule(module).incomingConnections; - return connections.getFromUnorderedCache(getConnectionsByOriginModule); - } + // information marker that the asset has been emitted + compilation.emittedAssets.add(file); - /** - * @param {Module} module the module - * @returns {readonly Map | undefined} connections to modules, in a map by module - */ - getOutgoingConnectionsByModule(module) { - const connections = this._getModuleGraphModule(module).outgoingConnections; - return connections === undefined - ? undefined - : connections.getFromUnorderedCache(getConnectionsByModule); - } + // cache the information that the Source has been written to that location + const newGeneration = + targetFileGeneration === undefined + ? 1 + : targetFileGeneration + 1; + cacheEntry.writtenTo.set(targetPath, newGeneration); + this._assetEmittingWrittenFiles.set(targetPath, newGeneration); + this.hooks.assetEmitted.callAsync( + file, + { + content, + source, + outputPath, + compilation, + targetPath + }, + callback + ); + }); + }; - /** - * @param {Module} module the module - * @returns {ModuleProfile | null} the module profile - */ - getProfile(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.profile; - } + const updateWithReplacementSource = size => { + updateFileWithReplacementSource(file, cacheEntry, size); + similarEntry.size = size; + if (similarEntry.waiting !== undefined) { + for (const { file, cacheEntry } of similarEntry.waiting) { + updateFileWithReplacementSource(file, cacheEntry, size); + } + } + }; - /** - * @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; - } + const updateFileWithReplacementSource = ( + file, + cacheEntry, + size + ) => { + // Create a replacement resource which only allows to ask for size + // This allows to GC all memory allocated by the Source + // (expect when the Source is stored in any other cache) + if (!cacheEntry.sizeOnlySource) { + cacheEntry.sizeOnlySource = new SizeOnlySource(size); + } + compilation.updateAsset(file, cacheEntry.sizeOnlySource, { + size + }); + }; - /** - * @param {Module} module the module - * @returns {Module | null} the issuer module - */ - getIssuer(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.issuer; - } + const processExistingFile = stats => { + // skip emitting if it's already there and an immutable file + if (immutable) { + updateWithReplacementSource(stats.size); + return alreadyWritten(); + } - /** - * @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; - } + const content = getContent(); - /** - * @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; - } + updateWithReplacementSource(content.length); - /** - * @param {Module} module the module - * @returns {(string | OptimizationBailoutFunction)[]} optimization bailouts - */ - getOptimizationBailout(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.optimizationBailout; - } + // if it exists and content on disk matches content + // skip writing the same content again + // (to keep mtime and don't trigger watchers) + // for a fast negative match file size is compared first + if (content.length === stats.size) { + compilation.comparedForEmitAssets.add(file); + return this.outputFileSystem.readFile( + targetPath, + (err, existingContent) => { + if ( + err || + !content.equals(/** @type {Buffer} */ (existingContent)) + ) { + return doWrite(content); + } else { + return alreadyWritten(); + } + } + ); + } - /** - * @param {Module} module the module - * @returns {true | string[] | null} the provided exports - */ - getProvidedExports(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.exports.getProvidedExports(); - } + return doWrite(content); + }; - /** - * @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; - } + const processMissingFile = () => { + const content = getContent(); - /** - * @param {Module} module the module - * @returns {ExportsInfo} info about the exports - */ - getExportsInfo(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.exports; - } + updateWithReplacementSource(content.length); - /** - * @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); - } + return doWrite(content); + }; - /** - * @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); - } + // if the target file has already been written + if (targetFileGeneration !== undefined) { + // check if the Source has been written to this target file + const writtenGeneration = cacheEntry.writtenTo.get(targetPath); + if (writtenGeneration === targetFileGeneration) { + // if yes, we may skip writing the file + // if it's already there + // (we assume one doesn't modify files while the Compiler is running, other then removing them) - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {false | true | SortableSet | null} the used exports - * false: module is not used at all. - * true: the module namespace/object export is used. - * SortableSet: these export names are used. - * empty SortableSet: 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); - } + if (this._assetEmittingPreviousFiles.has(targetPath)) { + // We assume that assets from the last compilation say intact on disk (they are not removed) + compilation.updateAsset(file, cacheEntry.sizeOnlySource, { + size: cacheEntry.sizeOnlySource.size() + }); - /** - * @param {Module} module the module - * @returns {number} the index of the module - */ - getPreOrderIndex(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.preOrderIndex; - } + return callback(); + } else { + // Settings immutable will make it accept file content without comparing when file exist + immutable = true; + } + } else if (!immutable) { + if (checkSimilarFile()) return; + // We wrote to this file before which has very likely a different content + // skip comparing and assume content is different for performance + // This case happens often during watch mode. + return processMissingFile(); + } + } - /** - * @param {Module} module the module - * @returns {number} the index of the module - */ - getPostOrderIndex(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.postOrderIndex; - } + if (checkSimilarFile()) return; + if (this.options.output.compareBeforeEmit) { + this.outputFileSystem.stat(targetPath, (err, stats) => { + const exists = !err && stats.isFile(); - /** - * @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; + if (exists) { + processExistingFile(stats); + } else { + processMissingFile(); + } + }); + } else { + processMissingFile(); + } + }; + + if (targetFile.match(/\/|\\/)) { + const fs = this.outputFileSystem; + const dir = dirname(fs, join(fs, outputPath, targetFile)); + mkdirp(fs, dir, writeOut); + } else { + writeOut(); + } + }, + err => { + // Clear map to free up memory + caseInsensitiveMap.clear(); + if (err) { + this._assetEmittingPreviousFiles.clear(); + return callback(err); + } + + this._assetEmittingPreviousFiles = allTargetPaths; + + this.hooks.afterEmit.callAsync(compilation, err => { + if (err) return callback(err); + + return callback(); + }); + } + ); + }; + + this.hooks.emit.callAsync(compilation, err => { + if (err) return callback(err); + outputPath = compilation.getPath(this.outputPath, {}); + mkdirp(this.outputFileSystem, outputPath, emitFiles); + }); } /** - * @param {Module} module the module - * @param {number} index the index of the module - * @returns {boolean} true, if the index was set + * @param {Callback} callback signals when the call finishes + * @returns {void} */ - setPreOrderIndexIfUnset(module, index) { - const mgm = this._getModuleGraphModule(module); - if (mgm.preOrderIndex === null) { - mgm.preOrderIndex = index; - return true; + emitRecords(callback) { + if (this.hooks.emitRecords.isUsed()) { + if (this.recordsOutputPath) { + asyncLib.parallel( + [ + cb => this.hooks.emitRecords.callAsync(cb), + this._emitRecords.bind(this) + ], + err => callback(err) + ); + } else { + this.hooks.emitRecords.callAsync(callback); + } + } else { + if (this.recordsOutputPath) { + this._emitRecords(callback); + } else { + callback(); + } } - return false; } /** - * @param {Module} module the module - * @param {number} index the index of the module + * @param {Callback} callback signals when the call finishes * @returns {void} */ - setPostOrderIndex(module, index) { - const mgm = this._getModuleGraphModule(module); - mgm.postOrderIndex = index; - } + _emitRecords(callback) { + const writeFile = () => { + this.outputFileSystem.writeFile( + this.recordsOutputPath, + JSON.stringify( + this.records, + (n, value) => { + if ( + typeof value === "object" && + value !== null && + !Array.isArray(value) + ) { + const keys = Object.keys(value); + if (!isSorted(keys)) { + return sortObject(value, keys); + } + } + return value; + }, + 2 + ), + callback + ); + }; - /** - * @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; + const recordsOutputPathDirectory = dirname( + this.outputFileSystem, + this.recordsOutputPath + ); + if (!recordsOutputPathDirectory) { + return writeFile(); } - return false; - } - - /** - * @param {Module} module the module - * @returns {number} the depth of the module - */ - getDepth(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.depth; + mkdirp(this.outputFileSystem, recordsOutputPathDirectory, err => { + if (err) return callback(err); + writeFile(); + }); } /** - * @param {Module} module the module - * @param {number} depth the depth of the module + * @param {Callback} callback signals when the call finishes * @returns {void} */ - setDepth(module, depth) { - const mgm = this._getModuleGraphModule(module); - mgm.depth = depth; + readRecords(callback) { + if (this.hooks.readRecords.isUsed()) { + if (this.recordsInputPath) { + asyncLib.parallel([ + cb => this.hooks.readRecords.callAsync(cb), + this._readRecords.bind(this) + ]); + } else { + this.records = {}; + this.hooks.readRecords.callAsync(callback); + } + } else { + if (this.recordsInputPath) { + this._readRecords(callback); + } else { + this.records = {}; + callback(); + } + } } /** - * @param {Module} module the module - * @param {number} depth the depth of the module - * @returns {boolean} true, if the depth was set + * @param {Callback} callback signals when the call finishes + * @returns {void} */ - setDepthIfLower(module, depth) { - const mgm = this._getModuleGraphModule(module); - if (mgm.depth === null || mgm.depth > depth) { - mgm.depth = depth; - return true; + _readRecords(callback) { + if (!this.recordsInputPath) { + this.records = {}; + return callback(); } - return false; - } + this.inputFileSystem.stat(this.recordsInputPath, err => { + // It doesn't exist + // We can ignore this. + if (err) return callback(); - /** - * @param {Module} module the module - * @returns {boolean} true, if the module is async - */ - isAsync(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.async; - } + this.inputFileSystem.readFile(this.recordsInputPath, (err, content) => { + if (err) return callback(err); - /** - * @param {Module} module the module - * @returns {void} - */ - setAsync(module) { - const mgm = this._getModuleGraphModule(module); - mgm.async = true; + try { + this.records = parseJson(content.toString("utf-8")); + } catch (e) { + e.message = "Cannot parse records: " + e.message; + return callback(e); + } + + return callback(); + }); + }); } /** - * @param {any} thing any thing - * @returns {Object} metadata + * @param {Compilation} compilation the compilation + * @param {string} compilerName the compiler's name + * @param {number} compilerIndex the compiler's index + * @param {OutputOptions=} outputOptions the output options + * @param {WebpackPluginInstance[]=} plugins the plugins to apply + * @returns {Compiler} a child compiler */ - getMeta(thing) { - let meta = this._metaMap.get(thing); - if (meta === undefined) { - meta = Object.create(null); - this._metaMap.set(thing, meta); + createChildCompiler( + compilation, + compilerName, + compilerIndex, + outputOptions, + plugins + ) { + const childCompiler = new Compiler(this.context, { + ...this.options, + output: { + ...this.options.output, + ...outputOptions + } + }); + childCompiler.name = compilerName; + childCompiler.outputPath = this.outputPath; + childCompiler.inputFileSystem = this.inputFileSystem; + childCompiler.outputFileSystem = null; + childCompiler.resolverFactory = this.resolverFactory; + childCompiler.modifiedFiles = this.modifiedFiles; + childCompiler.removedFiles = this.removedFiles; + childCompiler.fileTimestamps = this.fileTimestamps; + childCompiler.contextTimestamps = this.contextTimestamps; + childCompiler.fsStartTime = this.fsStartTime; + childCompiler.cache = this.cache; + childCompiler.compilerPath = `${this.compilerPath}${compilerName}|${compilerIndex}|`; + childCompiler._backCompat = this._backCompat; + + const relativeCompilerName = makePathsRelative( + this.context, + compilerName, + this.root + ); + if (!this.records[relativeCompilerName]) { + this.records[relativeCompilerName] = []; + } + if (this.records[relativeCompilerName][compilerIndex]) { + childCompiler.records = this.records[relativeCompilerName][compilerIndex]; + } else { + this.records[relativeCompilerName].push((childCompiler.records = {})); } - return meta; - } - /** - * @param {any} thing any thing - * @returns {Object} metadata - */ - getMetaIfExisting(thing) { - return this._metaMap.get(thing); + childCompiler.parentCompilation = compilation; + childCompiler.root = this.root; + if (Array.isArray(plugins)) { + for (const plugin of plugins) { + plugin.apply(childCompiler); + } + } + for (const name in this.hooks) { + if ( + ![ + "make", + "compile", + "emit", + "afterEmit", + "invalid", + "done", + "thisCompilation" + ].includes(name) + ) { + if (childCompiler.hooks[name]) { + childCompiler.hooks[name].taps = this.hooks[name].taps.slice(); + } + } + } + + compilation.hooks.childCompiler.call( + childCompiler, + compilerName, + compilerIndex + ); + + return childCompiler; } - /** - * @param {string=} cacheStage a persistent stage name for caching - */ - freeze(cacheStage) { - this._cache = new WeakTupleMap(); - this._cacheStage = cacheStage; + isChild() { + return !!this.parentCompilation; } - unfreeze() { - this._cache = undefined; - this._cacheStage = undefined; + createCompilation(params) { + this._cleanupLastCompilation(); + return (this._lastCompilation = new Compilation(this, params)); } /** - * @template {any[]} T - * @template V - * @param {(moduleGraph: ModuleGraph, ...args: T) => V} fn computer - * @param {T} args arguments - * @returns {V} computed value or cached + * @param {CompilationParams} params the compilation parameters + * @returns {Compilation} the created compilation */ - cached(fn, ...args) { - if (this._cache === undefined) return fn(this, ...args); - return this._cache.provide(fn, ...args, () => fn(this, ...args)); + newCompilation(params) { + const compilation = this.createCompilation(params); + compilation.name = this.name; + compilation.records = this.records; + this.hooks.thisCompilation.call(compilation, params); + this.hooks.compilation.call(compilation, params); + return compilation; } - /** - * @param {Map>} moduleMemCaches mem caches for modules for better caching - */ - setModuleMemCaches(moduleMemCaches) { - this._moduleMemCaches = moduleMemCaches; + createNormalModuleFactory() { + this._cleanupLastNormalModuleFactory(); + const normalModuleFactory = new NormalModuleFactory({ + context: this.options.context, + fs: this.inputFileSystem, + resolverFactory: this.resolverFactory, + options: this.options.module, + associatedObjectForCache: this.root, + layers: this.options.experiments.layers + }); + this._lastNormalModuleFactory = normalModuleFactory; + this.hooks.normalModuleFactory.call(normalModuleFactory); + return normalModuleFactory; } - /** - * @param {Dependency} dependency dependency - * @param {...any} args arguments, last argument is a function called with moduleGraph, dependency, ...args - * @returns {any} computed value or cached - */ - dependencyCacheProvide(dependency, ...args) { - /** @type {(moduleGraph: ModuleGraph, dependency: Dependency, ...args: any[]) => any} */ - const fn = args.pop(); - if (this._moduleMemCaches && this._cacheStage) { - const memCache = this._moduleMemCaches.get( - this.getParentModule(dependency) - ); - if (memCache !== undefined) { - return memCache.provide(dependency, this._cacheStage, ...args, () => - fn(this, dependency, ...args) - ); - } - } - if (this._cache === undefined) return fn(this, dependency, ...args); - return this._cache.provide(dependency, ...args, () => - fn(this, dependency, ...args) - ); + createContextModuleFactory() { + const contextModuleFactory = new ContextModuleFactory(this.resolverFactory); + this.hooks.contextModuleFactory.call(contextModuleFactory); + return contextModuleFactory; } - // 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); + newCompilationParams() { + const params = { + normalModuleFactory: this.createNormalModuleFactory(), + contextModuleFactory: this.createContextModuleFactory() + }; + return params; } - // TODO remove in webpack 6 /** - * @param {Module} module the module - * @param {ModuleGraph} moduleGraph the module graph + * @param {Callback} callback signals when the compilation finishes * @returns {void} */ - static setModuleGraphForModule(module, moduleGraph) { - moduleGraphForModuleMap.set(module, moduleGraph); + compile(callback) { + const params = this.newCompilationParams(); + this.hooks.beforeCompile.callAsync(params, err => { + if (err) return callback(err); + + this.hooks.compile.call(params); + + const compilation = this.newCompilation(params); + + const logger = compilation.getLogger("webpack.Compiler"); + + logger.time("make hook"); + this.hooks.make.callAsync(compilation, err => { + logger.timeEnd("make hook"); + if (err) return callback(err); + + logger.time("finish make hook"); + this.hooks.finishMake.callAsync(compilation, err => { + logger.timeEnd("finish make hook"); + if (err) return callback(err); + + process.nextTick(() => { + logger.time("finish compilation"); + compilation.finish(err => { + logger.timeEnd("finish compilation"); + if (err) return callback(err); + + logger.time("seal compilation"); + compilation.seal(err => { + logger.timeEnd("seal compilation"); + if (err) return callback(err); + + logger.time("afterCompile hook"); + this.hooks.afterCompile.callAsync(compilation, err => { + logger.timeEnd("afterCompile hook"); + if (err) return callback(err); + + return callback(null, compilation); + }); + }); + }); + }); + }); + }); + }); } - // TODO remove in webpack 6 /** - * @param {Module} module the module + * @param {Callback} callback signals when the compiler closes * @returns {void} */ - static clearModuleGraphForModule(module) { - moduleGraphForModuleMap.delete(module); + close(callback) { + if (this.watching) { + // When there is still an active watching, close this first + this.watching.close(err => { + this.close(callback); + }); + return; + } + this.hooks.shutdown.callAsync(err => { + if (err) return callback(err); + // Get rid of reference to last compilation to avoid leaking memory + // We can't run this._cleanupLastCompilation() as the Stats to this compilation + // might be still in use. We try to get rid of the reference to the cache instead. + this._lastCompilation = undefined; + this._lastNormalModuleFactory = undefined; + this.cache.shutdown(callback); + }); } } -// TODO remove in webpack 6 -/** @type {WeakMap} */ -const moduleGraphForModuleMap = new WeakMap(); - -// TODO remove in webpack 6 -/** @type {Map ModuleGraph>} */ -const deprecateMap = new Map(); - -module.exports = ModuleGraph; -module.exports.ModuleGraphConnection = ModuleGraphConnection; +module.exports = Compiler; /***/ }), -/***/ 40639: +/***/ 98229: /***/ (function(module) { "use strict"; @@ -46186,458 +41539,189 @@ module.exports.ModuleGraphConnection = ModuleGraphConnection; -/** @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"); +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__"; /** - * While determining the active state, this flag is used to signal a circular connection. + * @typedef {Object} ExternalModuleInfo + * @property {number} index + * @property {Module} module */ -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 + * @typedef {Object} ConcatenatedModuleInfo + * @property {number} index + * @property {Module} module + * @property {Map} exportMap mapping from export name to symbol + * @property {Map} rawExportMap mapping from export name to symbol + * @property {string=} namespaceExportSymbol */ -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; -}; + +/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo} ModuleInfo */ /** - * @param {ConnectionState} a first - * @param {ConnectionState} b second - * @returns {ConnectionState} intersected + * @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 */ -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 { +class ConcatenationScope { /** - * @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 + * @param {ModuleInfo[] | Map} modulesMap all module info by module + * @param {ConcatenatedModuleInfo} currentModule the current module info */ - 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} */ - this.explanations = undefined; - if (explanation) { - this.explanations = new Set(); - this.explanations.add(explanation); + 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; } - 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 {Module} module the referenced module + * @returns {boolean} true, when it's in the scope + */ + isModuleInScope(module) { + return this._modulesMap.has(module); } /** - * @param {function(ModuleGraphConnection, RuntimeSpec): ConnectionState} condition condition for the connection - * @returns {void} + * + * @param {string} exportName name of the export + * @param {string} symbol identifier of the export in source code */ - 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; + 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} explanation the explanation to add - * @returns {void} + * + * @param {string} exportName name of the export + * @param {string} expression expression to be used */ - addExplanation(explanation) { - if (this.explanations === undefined) { - this.explanations = new Set(); + registerRawExport(exportName, expression) { + if (!this._currentModule.rawExportMap) { + this._currentModule.rawExportMap = new Map(); + } + if (!this._currentModule.rawExportMap.has(exportName)) { + this._currentModule.rawExportMap.set(exportName, expression); } - 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 + * @param {string} symbol identifier of the export in source code */ - isActive(runtime) { - if (!this.conditional) return this._active; - return this.condition(this, runtime) !== false; + registerNamespaceExport(symbol) { + this._currentModule.namespaceExportSymbol = symbol; } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, if the connection is active + * + * @param {Module} module the referenced module + * @param {Partial} options options + * @returns {string} the reference as identifier */ - isTargetActive(runtime) { - if (!this.conditional) return this._active; - return this.condition(this, runtime) === true; + 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 {RuntimeSpec} runtime the runtime - * @returns {ConnectionState} true: fully active, false: inactive, TRANSITIVE: direct module inactive, but transitive connection maybe active + * @param {string} name the identifier + * @returns {boolean} true, when it's an module reference */ - getActiveState(runtime) { - if (!this.conditional) return this._active; - return this.condition(this, runtime); + static isModuleReference(name) { + return MODULE_REFERENCE_REGEXP.test(name); } /** - * @param {boolean} value active or not - * @returns {void} + * @param {string} name the identifier + * @returns {ModuleReferenceOptions & { index: number }} parsed options and index */ - setActive(value) { - this.conditional = false; - this._active = value; - } - - set active(value) { - throw new Error("Use setActive instead"); + 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 + }; } } -/** @typedef {typeof TRANSITIVE_ONLY} TRANSITIVE_ONLY */ -/** @typedef {typeof CIRCULAR_CONNECTION} CIRCULAR_CONNECTION */ +ConcatenationScope.DEFAULT_EXPORT = DEFAULT_EXPORT; +ConcatenationScope.NAMESPACE_OBJECT_EXPORT = NAMESPACE_OBJECT_EXPORT; -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 -); +module.exports = ConcatenationScope; /***/ }), -/***/ 3454: +/***/ 95735: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Maksim Nazarjev @acupofspirt */ -const { ConcatSource, RawSource, CachedSource } = __webpack_require__(51255); -const { UsageState } = __webpack_require__(63686); -const Template = __webpack_require__(1626); -const JavascriptModulesPlugin = __webpack_require__(89464); +const WebpackError = __webpack_require__(53799); -/** @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 */ +module.exports = class ConcurrentCompilationError extends WebpackError { + constructor() { + super(); -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; + this.name = "ConcurrentCompilationError"; + this.message = + "You ran Webpack twice. Each instance only supports a single concurrent compilation at a time."; } - return str; }; -/** - * @param {ConcatSource} source output - * @param {string} indent spacing - * @param {ExportsInfo} exportsInfo data - * @param {ModuleGraph} moduleGraph moduleGraph - * @param {RequestShortener} requestShortener requestShortener - * @param {Set} 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 }>>} */ -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; - /***/ }), -/***/ 32882: +/***/ 61333: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -46648,90 +41732,116 @@ module.exports = ModuleInfoHeaderPlugin; -const WebpackError = __webpack_require__(53799); +const { ConcatSource, PrefixSource } = __webpack_require__(51255); +const InitFragment = __webpack_require__(55870); +const Template = __webpack_require__(39722); +const { mergeRuntime } = __webpack_require__(17156); -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Module")} Module */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Generator").GenerateContext} GenerateContext */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ -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" +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 ModuleNotFoundError extends WebpackError { +/** + * @typedef {GenerateContext} Context + */ +class ConditionalInitFragment extends InitFragment { /** - * @param {Module} module module tied to dependency - * @param {Error&any} err error thrown - * @param {DependencyLocation} loc location of dependency + * @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(module, err, loc) { - let message = `Module not found: ${err.toString()}`; + constructor( + content, + stage, + position, + key, + runtimeCondition = true, + endContent + ) { + super(content, stage, position, key, endContent); + this.runtimeCondition = runtimeCondition; + } - // 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 }`; - } - } + /** + * @param {Context} context context + * @returns {string|Source} the source code that will be included as initialization code + */ + getContent(context) { + if (this.runtimeCondition === false || !this.content) return ""; + if (this.runtimeCondition === true) return this.content; + const expr = context.runtimeTemplate.runtimeConditionExpression({ + chunkGraph: context.chunkGraph, + runtimeRequirements: context.runtimeRequirements, + runtime: context.runtime, + runtimeCondition: this.runtimeCondition + }); + if (expr === "true") return this.content; + return wrapInCondition(expr, this.content); + } - super(message); + /** + * @param {Context} context context + * @returns {string|Source=} the source code that will be included at the end of the module + */ + getEndContent(context) { + if (this.runtimeCondition === false || !this.endContent) return ""; + if (this.runtimeCondition === true) return this.endContent; + const expr = context.runtimeTemplate.runtimeConditionExpression({ + chunkGraph: context.chunkGraph, + runtimeRequirements: context.runtimeRequirements, + runtime: context.runtime, + runtimeCondition: this.runtimeCondition + }); + if (expr === "true") return this.endContent; + return wrapInCondition(expr, this.endContent); + } - this.name = "ModuleNotFoundError"; - this.details = err.details; - this.module = module; - this.error = err; - this.loc = loc; + 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 = ModuleNotFoundError; +module.exports = ConditionalInitFragment; /***/ }), -/***/ 58443: +/***/ 11146: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -46742,1432 +41852,1632 @@ module.exports = ModuleNotFoundError; -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); - -const WASM_HEADER = Buffer.from([0x00, 0x61, 0x73, 0x6d]); +const CachedConstDependency = __webpack_require__(57403); +const ConstDependency = __webpack_require__(76911); +const { evaluateToString } = __webpack_require__(93998); +const { parseResource } = __webpack_require__(82186); -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; +/** @typedef {import("estree").Expression} ExpressionNode */ +/** @typedef {import("estree").Super} SuperNode */ +/** @typedef {import("./Compiler")} Compiler */ - 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"; +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; } + } +}; - 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); +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); +}; - message += - linesBefore.map(l => `\n| ${l}`).join("") + - `\n> ${theLine}` + - linesAfter.map(l => `\n| ${l}`).join(""); - } +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() + ); - loc = { start: err.loc }; - } else if (err && err.stack) { - message += "\n" + err.stack; - } + compilation.dependencyTemplates.set( + CachedConstDependency, + new CachedConstDependency.Template() + ); - super(message); + 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); - this.name = "ModuleParseError"; - this.loc = loc; - this.error = err; - } + 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); + } - serialize(context) { - const { write } = context; + return keepRight; + } + } + } + ); + parser.hooks.optionalChaining.tap("ConstPlugin", expr => { + /** @type {ExpressionNode[]} */ + const optionalExpressionsStack = []; + /** @type {ExpressionNode|SuperNode} */ + let next = expr.expression; - write(this.error); + 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; + } + } - super.serialize(context); - } + while (optionalExpressionsStack.length) { + const expression = optionalExpressionsStack.pop(); + const evaluated = parser.evaluateExpression(expression); - deserialize(context) { - const { read } = context; + 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; + }); - this.error = read(); + 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; + }); + }; - super.deserialize(context); + 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); + } + ); } } -makeSerializable(ModuleParseError, "webpack/lib/ModuleParseError"); - -module.exports = ModuleParseError; +module.exports = ConstPlugin; /***/ }), -/***/ 36418: +/***/ 21411: /***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -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; +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./ContextModuleFactory")} ContextModuleFactory */ - this.buildingStartTime = 0; - this.buildingEndTime = 0; - this.building = 0; - this.buildingParallelismFactor = 0; +class ContextExclusionPlugin { + /** + * @param {RegExp} negativeMatcher Matcher regular expression + */ + constructor(negativeMatcher) { + this.negativeMatcher = negativeMatcher; + } - this.storingStartTime = 0; - this.storingEndTime = 0; - this.storing = 0; - this.storingParallelismFactor = 0; + /** + * 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)); + }); + }); + } +} - this.additionalFactoryTimes = undefined; - this.additionalFactories = 0; - this.additionalFactoriesParallelismFactor = 0; +module.exports = ContextExclusionPlugin; - /** @deprecated */ - this.additionalIntegration = 0; - } - markFactoryStart() { - this.factoryStartTime = Date.now(); - } +/***/ }), - markFactoryEnd() { - this.factoryEndTime = Date.now(); - this.factory = this.factoryEndTime - this.factoryStartTime; - } +/***/ 76729: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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; - - -/***/ }), - -/***/ 94560: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const WebpackError = __webpack_require__(53799); - -/** @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; - } -} - -module.exports = ModuleRestoreError; - - -/***/ }), - -/***/ 59001: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +const { OriginalSource, RawSource } = __webpack_require__(51255); +const AsyncDependenciesBlock = __webpack_require__(47736); +const { makeWebpackError } = __webpack_require__(11351); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); const WebpackError = __webpack_require__(53799); - -/** @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; - } -} - -module.exports = ModuleStoreError; - - -/***/ }), - -/***/ 62677: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const util = __webpack_require__(73837); -const memoize = __webpack_require__(78676); +const { + compareLocations, + concatComparators, + compareSelect, + keepOriginalOrder, + compareModulesById +} = __webpack_require__(29579); +const { contextify, parseResource } = __webpack_require__(82186); +const makeSerializable = __webpack_require__(33032); /** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ /** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ /** @typedef {import("./Compilation")} Compilation */ /** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Module").BuildMeta} BuildMeta */ +/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./util/Hash")} Hash */ - -const getJavascriptModulesPlugin = memoize(() => - __webpack_require__(89464) -); - -// 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; - - -/***/ }), - -/***/ 11234: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { cleanUp } = __webpack_require__(59985); -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); - -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; - } - - 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; - - -/***/ }), - -/***/ 33370: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - +/** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */ +/** @template T @typedef {import("./util/LazySet")} LazySet */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */ -const asyncLib = __webpack_require__(78175); -const { SyncHook, MultiHook } = __webpack_require__(6967); +/** + * @typedef {Object} ContextOptions + * @property {ContextMode} mode + * @property {boolean} recursive + * @property {RegExp} regExp + * @property {"strict"|boolean=} namespaceObject + * @property {string=} addon + * @property {string=} chunkName + * @property {RegExp=} include + * @property {RegExp=} exclude + * @property {RawChunkGroupOptions=} groupOptions + * @property {string=} typePrefix + * @property {string=} category + * @property {string[][]=} referencedExports exports referenced from modules (won't be mangled) + */ -const ConcurrentCompilationError = __webpack_require__(95735); -const MultiStats = __webpack_require__(24170); -const MultiWatching = __webpack_require__(81128); -const ArrayQueue = __webpack_require__(41792); +/** + * @typedef {Object} ContextModuleOptionsExtras + * @property {string} resource + * @property {string=} resourceQuery + * @property {string=} resourceFragment + * @property {TODO} resolveOptions + */ -/** @template T @typedef {import("tapable").AsyncSeriesHook} AsyncSeriesHook */ -/** @template T @template R @typedef {import("tapable").SyncBailHook} SyncBailHook */ -/** @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 */ +/** @typedef {ContextOptions & ContextModuleOptionsExtras} ContextModuleOptions */ /** - * @template T - * @callback Callback + * @callback ResolveDependenciesCallback * @param {(Error | null)=} err - * @param {T=} result + * @param {ContextElementDependency[]=} dependencies */ /** - * @callback RunWithDependenciesHandler - * @param {Compiler} compiler - * @param {Callback} callback + * @callback ResolveDependencies + * @param {InputFileSystem} fs + * @param {ContextModuleOptions} options + * @param {ResolveDependenciesCallback} callback */ -/** - * @typedef {Object} MultiCompilerOptions - * @property {number=} parallelism how many Compilers are allows to run at the same time in parallel - */ +const SNAPSHOT_OPTIONS = { timestamp: true }; -module.exports = class MultiCompiler { +const TYPES = new Set(["javascript"]); + +class ContextModule extends Module { /** - * @param {Compiler[] | Record} compilers child compilers - * @param {MultiCompilerOptions} options options + * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context + * @param {ContextModuleOptions} options options object */ - constructor(compilers, options) { - if (!Array.isArray(compilers)) { - compilers = Object.keys(compilers).map(name => { - compilers[name].name = name; - return compilers[name]; - }); - } + constructor(resolveDependencies, options) { + const parsed = parseResource(options ? options.resource : ""); + const resource = parsed.path; + const resourceQuery = (options && options.resourceQuery) || parsed.query; + const resourceFragment = + (options && options.resourceFragment) || parsed.fragment; - this.hooks = Object.freeze({ - /** @type {SyncHook<[MultiStats]>} */ - done: new SyncHook(["stats"]), - /** @type {MultiHook>} */ - invalid: new MultiHook(compilers.map(c => c.hooks.invalid)), - /** @type {MultiHook>} */ - run: new MultiHook(compilers.map(c => c.hooks.run)), - /** @type {SyncHook<[]>} */ - watchClose: new SyncHook([]), - /** @type {MultiHook>} */ - watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)), - /** @type {MultiHook>} */ - infrastructureLog: new MultiHook( - compilers.map(c => c.hooks.infrastructureLog) - ) - }); - this.compilers = compilers; - /** @type {MultiCompilerOptions} */ - this._options = { - parallelism: options.parallelism || Infinity - }; - /** @type {WeakMap} */ - this.dependencies = new WeakMap(); - this.running = false; + super("javascript/dynamic", resource); - /** @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; - 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)); - } - }); - compiler.hooks.invalid.tap("MultiCompiler", () => { - if (compilerDone) { - compilerDone = false; - doneCompilers--; - } - }); + // Info from Factory + this.resolveDependencies = resolveDependencies; + /** @type {ContextModuleOptions} */ + this.options = { + ...options, + resource, + resourceQuery, + resourceFragment + }; + if (options && options.resolveOptions !== undefined) { + this.resolveOptions = options.resolveOptions; } - } - - 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 (options && typeof options.mode !== "string") { + throw new Error("options.mode is a required option"); } - if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/"; - return commonPath; + this._identifier = this._createIdentifier(); + this._forceBuild = true; } - get inputFileSystem() { - throw new Error("Cannot read inputFileSystem of a MultiCompiler"); + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; } - get outputFileSystem() { - throw new Error("Cannot read outputFileSystem of a MultiCompiler"); + /** + * 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) { + const m = /** @type {ContextModule} */ (module); + this.resolveDependencies = m.resolveDependencies; + this.options = m.options; } - get watchFileSystem() { - throw new Error("Cannot read watchFileSystem of a MultiCompiler"); + /** + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. + */ + cleanupForCache() { + super.cleanupForCache(); + this.resolveDependencies = undefined; } - get intermediateFileSystem() { - throw new Error("Cannot read outputFileSystem of a MultiCompiler"); + _prettyRegExp(regexString, stripSlash = true) { + const str = (regexString + "").replace(/!/g, "%21").replace(/\|/g, "%7C"); + return stripSlash ? str.substring(1, str.length - 1) : str; } - /** - * @param {InputFileSystem} value the new input file system - */ - set inputFileSystem(value) { - for (const compiler of this.compilers) { - compiler.inputFileSystem = value; + _createIdentifier() { + let identifier = this.context; + if (this.options.resourceQuery) { + identifier += `|${this.options.resourceQuery}`; + } + if (this.options.resourceFragment) { + identifier += `|${this.options.resourceFragment}`; + } + if (this.options.mode) { + identifier += `|${this.options.mode}`; + } + if (!this.options.recursive) { + identifier += "|nonrecursive"; + } + if (this.options.addon) { + identifier += `|${this.options.addon}`; + } + if (this.options.regExp) { + identifier += `|${this._prettyRegExp(this.options.regExp, false)}`; + } + if (this.options.include) { + identifier += `|include: ${this._prettyRegExp( + this.options.include, + false + )}`; + } + if (this.options.exclude) { + identifier += `|exclude: ${this._prettyRegExp( + this.options.exclude, + false + )}`; + } + if (this.options.referencedExports) { + identifier += `|referencedExports: ${JSON.stringify( + this.options.referencedExports + )}`; + } + if (this.options.chunkName) { + identifier += `|chunkName: ${this.options.chunkName}`; + } + if (this.options.groupOptions) { + identifier += `|groupOptions: ${JSON.stringify( + this.options.groupOptions + )}`; + } + if (this.options.namespaceObject === "strict") { + identifier += "|strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += "|namespace object"; } + + return identifier; } /** - * @param {OutputFileSystem} value the new output file system + * @returns {string} a unique identifier of the module */ - set outputFileSystem(value) { - for (const compiler of this.compilers) { - compiler.outputFileSystem = value; - } + identifier() { + return this._identifier; } /** - * @param {WatchFileSystem} value the new watch file system + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module */ - set watchFileSystem(value) { - for (const compiler of this.compilers) { - compiler.watchFileSystem = value; + readableIdentifier(requestShortener) { + let identifier = requestShortener.shorten(this.context) + "/"; + if (this.options.resourceQuery) { + identifier += ` ${this.options.resourceQuery}`; + } + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (!this.options.recursive) { + identifier += " nonrecursive"; + } + if (this.options.addon) { + identifier += ` ${requestShortener.shorten(this.options.addon)}`; + } + if (this.options.regExp) { + identifier += ` ${this._prettyRegExp(this.options.regExp)}`; + } + if (this.options.include) { + identifier += ` include: ${this._prettyRegExp(this.options.include)}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`; + } + if (this.options.referencedExports) { + identifier += ` referencedExports: ${this.options.referencedExports + .map(e => e.join(".")) + .join(", ")}`; + } + if (this.options.chunkName) { + identifier += ` chunkName: ${this.options.chunkName}`; + } + if (this.options.groupOptions) { + const groupOptions = this.options.groupOptions; + for (const key of Object.keys(groupOptions)) { + identifier += ` ${key}: ${groupOptions[key]}`; + } } + if (this.options.namespaceObject === "strict") { + identifier += " strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += " namespace object"; + } + + return identifier; } /** - * @param {IntermediateFileSystem} value the new intermediate file system + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion */ - set intermediateFileSystem(value) { - for (const compiler of this.compilers) { - compiler.intermediateFileSystem = value; + libIdent(options) { + let identifier = contextify( + options.context, + this.context, + options.associatedObjectForCache + ); + if (this.layer) identifier = `(${this.layer})/${identifier}`; + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (this.options.recursive) { + identifier += " recursive"; + } + if (this.options.addon) { + identifier += ` ${contextify( + options.context, + this.options.addon, + options.associatedObjectForCache + )}`; } + if (this.options.regExp) { + identifier += ` ${this._prettyRegExp(this.options.regExp)}`; + } + if (this.options.include) { + identifier += ` include: ${this._prettyRegExp(this.options.include)}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`; + } + if (this.options.referencedExports) { + identifier += ` referencedExports: ${this.options.referencedExports + .map(e => e.join(".")) + .join(", ")}`; + } + + return identifier; } - getInfrastructureLogger(name) { - return this.compilers[0].getInfrastructureLogger(name); + /** + * @returns {void} + */ + invalidateBuild() { + this._forceBuild = true; } /** - * @param {Compiler} compiler the child compiler - * @param {string[]} dependencies its dependencies + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild * @returns {void} */ - setDependencies(compiler, dependencies) { - this.dependencies.set(compiler, dependencies); + needBuild({ fileSystemInfo }, callback) { + // build if enforced + if (this._forceBuild) return callback(null, true); + + // always build when we have no snapshot + if (!this.buildInfo.snapshot) return callback(null, true); + + fileSystemInfo.checkSnapshotValid(this.buildInfo.snapshot, (err, valid) => { + callback(err, !valid); + }); } /** - * @param {Callback} callback signals when the validation is complete - * @returns {boolean} true if the dependencies are valid + * @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} */ - 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; + build(options, compilation, resolver, fs, callback) { + this._forceBuild = false; + /** @type {BuildMeta} */ + this.buildMeta = { + exportsType: "default", + defaultObject: "redirect-warn" }; - const sortEdges = (e1, e2) => { - return ( - e1.source.name.localeCompare(e2.source.name) || - e1.target.name.localeCompare(e2.target.name) - ); + this.buildInfo = { + snapshot: undefined }; - 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 - }); + this.dependencies.length = 0; + this.blocks.length = 0; + const startTime = Date.now(); + this.resolveDependencies(fs, this.options, (err, dependencies) => { + if (err) { + return callback( + makeWebpackError(err, "ContextModule.resolveDependencies") + ); + } + + // abort if something failed + // this will create an empty context + if (!dependencies) { + callback(); + return; + } + + // enhance dependencies with meta info + for (const dep of dependencies) { + dep.loc = { + name: dep.userRequest + }; + dep.request = this.options.addon + dep.request; + } + dependencies.sort( + concatComparators( + compareSelect(a => a.loc, compareLocations), + keepOriginalOrder(this.dependencies) + ) + ); + + if (this.options.mode === "sync" || this.options.mode === "eager") { + // if we have an sync or eager context + // just add all dependencies and continue + this.dependencies = dependencies; + } else if (this.options.mode === "lazy-once") { + // for the lazy-once mode create a new async dependency block + // and add that block to this context + if (dependencies.length > 0) { + const block = new AsyncDependenciesBlock({ + ...this.options.groupOptions, + name: this.options.chunkName + }); + for (const dep of dependencies) { + block.addDependency(dep); } + this.addBlock(block); } - } - } - /** @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); + } else if ( + this.options.mode === "weak" || + this.options.mode === "async-weak" + ) { + // we mark all dependencies as weak + for (const dep of dependencies) { + dep.weak = true; + } + this.dependencies = dependencies; + } else if (this.options.mode === "lazy") { + // if we are lazy create a new async dependency block per dependency + // and add all blocks to this context + let index = 0; + for (const dep of dependencies) { + let chunkName = this.options.chunkName; + if (chunkName) { + if (!/\[(index|request)\]/.test(chunkName)) { + chunkName += "[index]"; + } + chunkName = chunkName.replace(/\[index\]/g, `${index++}`); + chunkName = chunkName.replace( + /\[request\]/g, + Template.toPath(dep.userRequest) + ); } + const block = new AsyncDependenciesBlock( + { + ...this.options.groupOptions, + name: chunkName + }, + dep.loc, + dep.userRequest + ); + block.addDependency(dep); + this.addBlock(block); } + } else { + callback( + new WebpackError(`Unsupported mode "${this.options.mode}" in context`) + ); + return; } - } - 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; + compilation.fileSystemInfo.createSnapshot( + startTime, + null, + [this.context], + null, + SNAPSHOT_OPTIONS, + (err, snapshot) => { + if (err) return callback(err); + this.buildInfo.snapshot = snapshot; + callback(); + } + ); + }); } - // 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} callback the compiler's handler - * @returns {void} + * @param {LazySet} fileDependencies set where file dependencies are added to + * @param {LazySet} contextDependencies set where context dependencies are added to + * @param {LazySet} missingDependencies set where missing dependencies are added to + * @param {LazySet} buildDependencies set where build dependencies are added to */ - 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); + addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ) { + contextDependencies.add(this.context); } /** - * @template SetupResult - * @param {function(Compiler, number, Callback, function(): boolean, function(): void, function(): void): SetupResult} setup setup a single compiler - * @param {function(Compiler, SetupResult, Callback): void} run run/continue a single compiler - * @param {Callback} callback callback when all compilers are done, result includes Stats of all changed compilers - * @returns {SetupResult[]} result of setup + * @param {ContextElementDependency[]} dependencies all dependencies + * @param {ChunkGraph} chunkGraph chunk graph + * @returns {TODO} TODO */ - _runGraph(setup, run, callback) { - /** @typedef {{ compiler: Compiler, setupResult: SetupResult, result: Stats, state: "pending" | "blocked" | "queued" | "starting" | "running" | "running-outdated" | "done", children: Node[], parents: Node[] }} Node */ - - // State transitions for nodes: - // -> blocked (initial) - // blocked -> starting [running++] (when all parents done) - // queued -> starting [running++] (when processing the queue) - // starting -> running (when run has been called) - // running -> done [running--] (when compilation is done) - // done -> pending (when invalidated from file change) - // pending -> blocked [add to queue] (when invalidated from aggregated changes) - // done -> blocked [add to queue] (when invalidated, from parent invalidation) - // running -> running-outdated (when invalidated, either from change or parent invalidation) - // running-outdated -> blocked [running--] (when compilation is done) + getUserRequestMap(dependencies, chunkGraph) { + const moduleGraph = chunkGraph.moduleGraph; + // if we filter first we get a new array + // therefore we don't need to create a clone of dependencies explicitly + // therefore the order of this is !important! + const sortedDependencies = dependencies + .filter(dependency => moduleGraph.getModule(dependency)) + .sort((a, b) => { + if (a.userRequest === b.userRequest) { + return 0; + } + return a.userRequest < b.userRequest ? -1 : 1; + }); + const map = Object.create(null); + for (const dep of sortedDependencies) { + const module = moduleGraph.getModule(dep); + map[dep.userRequest] = chunkGraph.getModuleId(module); + } + return map; + } - /** @type {Node[]} */ - const nodes = this.compilers.map(compiler => ({ - compiler, - setupResult: undefined, - result: undefined, - state: "blocked", - children: [], - parents: [] - })); - /** @type {Map} */ - 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); - } + /** + * @param {ContextElementDependency[]} dependencies all dependencies + * @param {ChunkGraph} chunkGraph chunk graph + * @returns {TODO} TODO + */ + getFakeMap(dependencies, chunkGraph) { + if (!this.options.namespaceObject) { + return 9; } - /** @type {ArrayQueue} */ - const queue = new ArrayQueue(); - for (const node of nodes) { - if (node.parents.length === 0) { - node.state = "queued"; - queue.enqueue(node); + const moduleGraph = chunkGraph.moduleGraph; + // bitfield + let hasType = 0; + const comparator = compareModulesById(chunkGraph); + // if we filter first we get a new array + // therefore we don't need to create a clone of dependencies explicitly + // therefore the order of this is !important! + const sortedModules = dependencies + .map(dependency => moduleGraph.getModule(dependency)) + .filter(Boolean) + .sort(comparator); + const fakeMap = Object.create(null); + for (const module of sortedModules) { + const exportsType = module.getExportsType( + moduleGraph, + this.options.namespaceObject === "strict" + ); + const id = chunkGraph.getModuleId(module); + switch (exportsType) { + case "namespace": + fakeMap[id] = 9; + hasType |= 1; + break; + case "dynamic": + fakeMap[id] = 7; + hasType |= 2; + break; + case "default-only": + fakeMap[id] = 1; + hasType |= 4; + break; + case "default-with-named": + fakeMap[id] = 3; + hasType |= 8; + break; + default: + throw new Error(`Unexpected exports type ${exportsType}`); } } - 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) { - if (child.state === "blocked") queue.enqueue(child); - } - } else if (node.state === "running-outdated") { - node.state = "blocked"; - queue.enqueue(node); - } - processQueue(); - }; - /** - * @param {Node} node node - * @returns {void} - */ - const nodeInvalidFromParent = node => { - if (node.state === "done") { - node.state = "blocked"; - } else if (node.state === "running") { - node.state = "running-outdated"; - } - for (const child of node.children) { - nodeInvalidFromParent(child); - } - }; - /** - * @param {Node} node node - * @returns {void} - */ - const nodeInvalid = node => { - if (node.state === "done") { - node.state = "pending"; - } else if (node.state === "running") { - node.state = "running-outdated"; - } - for (const child of node.children) { - nodeInvalidFromParent(child); - } - }; - /** - * @param {Node} node node - * @returns {void} - */ - const nodeChange = node => { - nodeInvalid(node); - if (node.state === "pending") { - node.state = "blocked"; - } - if (node.state === "blocked") { - queue.enqueue(node); - processQueue(); - } - }; + if (hasType === 1) { + return 9; + } + if (hasType === 2) { + return 7; + } + if (hasType === 4) { + return 1; + } + if (hasType === 8) { + return 3; + } + if (hasType === 0) { + return 9; + } + return fakeMap; + } - const setupResults = []; - nodes.forEach((node, i) => { - setupResults.push( - (node.setupResult = setup( - node.compiler, - i, - nodeDone.bind(null, node), - () => node.state !== "starting" && node.state !== "running", - () => nodeChange(node), - () => nodeInvalid(node) - )) - ); - }); - let processing = true; - const processQueue = () => { - if (processing) return; - processing = true; - process.nextTick(processQueueWorker); - }; - const processQueueWorker = () => { - while (running < parallelism && queue.length > 0 && !errored) { - const node = queue.dequeue(); - if ( - node.state === "queued" || - (node.state === "blocked" && - node.parents.every(p => p.state === "done")) - ) { - running++; - node.state = "starting"; - run(node.compiler, node.setupResult, nodeDone.bind(null, node)); - node.state = "running"; - } - } - processing = false; - if ( - !errored && - running === 0 && - nodes.every(node => node.state === "done") - ) { - const stats = []; - for (const node of nodes) { - const result = node.result; - if (result) { - node.result = undefined; - stats.push(result); - } - } - if (stats.length > 0) { - callback(null, new MultiStats(stats)); - } - } - }; - processQueueWorker(); - return setupResults; + getFakeMapInitStatement(fakeMap) { + return typeof fakeMap === "object" + ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` + : ""; } - /** - * @param {WatchOptions|WatchOptions[]} watchOptions the watcher's options - * @param {Callback} handler signals when the call finishes - * @returns {MultiWatching} a compiler watcher - */ - watch(watchOptions, handler) { - if (this.running) { - return handler(new ConcurrentCompilationError()); + getReturn(type, asyncModule) { + if (type === 9) { + return "__webpack_require__(id)"; } - this.running = true; + return `${RuntimeGlobals.createFakeNamespaceObject}(id, ${type}${ + asyncModule ? " | 16" : "" + })`; + } - if (this.validateDependencies(handler)) { - const watchings = this._runGraph( - (compiler, idx, callback, isBlocked, setChanged, setInvalid) => { - const watching = compiler.watch( - Array.isArray(watchOptions) ? watchOptions[idx] : watchOptions, - callback - ); - if (watching) { - watching._onInvalid = setInvalid; - watching._onChange = setChanged; - watching._isBlocked = isBlocked; - } - return watching; - }, - (compiler, watching, callback) => { - if (compiler.watching !== watching) return; - if (!watching.running) watching.invalidate(); - }, - handler - ); - return new MultiWatching(watchings, this); + getReturnModuleObjectSource( + fakeMap, + asyncModule, + fakeMapDataExpression = "fakeMap[id]" + ) { + if (typeof fakeMap === "number") { + return `return ${this.getReturn(fakeMap, asyncModule)};`; } - - return new MultiWatching([], this); + return `return ${ + RuntimeGlobals.createFakeNamespaceObject + }(id, ${fakeMapDataExpression}${asyncModule ? " | 16" : ""})`; } /** - * @param {Callback} callback signals when the call finishes - * @returns {void} + * @param {TODO} dependencies TODO + * @param {TODO} id TODO + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {string} source code */ - run(callback) { - if (this.running) { - return callback(new ConcurrentCompilationError()); - } - this.running = true; + getSyncSource(dependencies, id, chunkGraph) { + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); - if (this.validateDependencies(callback)) { - this._runGraph( - () => {}, - (compiler, setupResult, callback) => compiler.run(callback), - (err, stats) => { - this.running = false; + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} - if (callback !== undefined) { - return callback(err, stats); - } - } - ); - } +function webpackContext(req) { + var id = webpackContextResolve(req); + ${returnModuleObject} +} +function webpackContextResolve(req) { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; } - - purgeInputFileSystem() { - for (const compiler of this.compilers) { - if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { - compiler.inputFileSystem.purge(); - } - } + return map[req]; +} +webpackContext.keys = function webpackContextKeys() { + return Object.keys(map); +}; +webpackContext.resolve = webpackContextResolve; +module.exports = webpackContext; +webpackContext.id = ${JSON.stringify(id)};`; } /** - * @param {Callback} callback signals when the compiler closes - * @returns {void} + * @param {TODO} dependencies TODO + * @param {TODO} id TODO + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {string} source code */ - close(callback) { - asyncLib.each( - this.compilers, - (compiler, callback) => { - compiler.close(callback); - }, - callback - ); - } -}; - - -/***/ }), - -/***/ 24170: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const identifierUtils = __webpack_require__(82186); + getWeakSyncSource(dependencies, id, chunkGraph) { + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); -/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ -/** @typedef {import("./Stats")} Stats */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").KnownStatsCompilation} KnownStatsCompilation */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} -const indent = (str, prefix) => { - const rem = str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); - return prefix + rem; +function webpackContext(req) { + var id = webpackContextResolve(req); + if(!${RuntimeGlobals.moduleFactories}[id]) { + var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + ${returnModuleObject} +} +function webpackContextResolve(req) { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; +} +webpackContext.keys = function webpackContextKeys() { + return Object.keys(map); }; +webpackContext.resolve = webpackContextResolve; +webpackContext.id = ${JSON.stringify(id)}; +module.exports = webpackContext;`; + } -class MultiStats { /** - * @param {Stats[]} stats the child stats + * @param {TODO} dependencies TODO + * @param {TODO} id TODO + * @param {Object} context context + * @param {ChunkGraph} context.chunkGraph the chunk graph + * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph + * @returns {string} source code */ - constructor(stats) { - this.stats = stats; - } + getAsyncWeakSource(dependencies, id, { chunkGraph, runtimeTemplate }) { + const arrow = runtimeTemplate.supportsArrowFunction(); + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap, true); - get hash() { - return this.stats.map(stat => stat.hash).join(""); + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${ + arrow ? "id =>" : "function(id)" + } { + if(!${RuntimeGlobals.moduleFactories}[id]) { + var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + ${returnModuleObject} + }); +} +function webpackAsyncContextResolve(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; + }); +} +webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( + "Object.keys(map)" + )}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; } /** - * @returns {boolean} true if a child compilation encountered an error + * @param {TODO} dependencies TODO + * @param {TODO} id TODO + * @param {Object} context context + * @param {ChunkGraph} context.chunkGraph the chunk graph + * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph + * @returns {string} source code */ - hasErrors() { - return this.stats.some(stat => stat.hasErrors()); + getEagerSource(dependencies, id, { chunkGraph, runtimeTemplate }) { + const arrow = runtimeTemplate.supportsArrowFunction(); + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const thenFunction = + fakeMap !== 9 + ? `${arrow ? "id =>" : "function(id)"} { + ${this.getReturnModuleObjectSource(fakeMap)} + }` + : "__webpack_require__"; + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${thenFunction}); +} +function webpackAsyncContextResolve(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; + }); +} +webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( + "Object.keys(map)" + )}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; } /** - * @returns {boolean} true if a child compilation had a warning + * @param {TODO} block TODO + * @param {TODO} dependencies TODO + * @param {TODO} id TODO + * @param {Object} options options object + * @param {RuntimeTemplate} options.runtimeTemplate the runtime template + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @returns {string} source code */ - hasWarnings() { - return this.stats.some(stat => stat.hasWarnings()); - } + getLazyOnceSource(block, dependencies, id, { runtimeTemplate, chunkGraph }) { + const promise = runtimeTemplate.blockPromise({ + chunkGraph, + block, + message: "lazy-once context", + runtimeRequirements: new Set() + }); + const arrow = runtimeTemplate.supportsArrowFunction(); + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const thenFunction = + fakeMap !== 9 + ? `${arrow ? "id =>" : "function(id)"} { + ${this.getReturnModuleObjectSource(fakeMap, true)}; + }` + : "__webpack_require__"; - _createChildOptions(options, context) { - if (!options) { - options = {}; + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} + +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${thenFunction}); +} +function webpackAsyncContextResolve(req) { + return ${promise}.then(${arrow ? "() =>" : "function()"} { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; } - 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 - }; + return map[req]; + }); +} +webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( + "Object.keys(map)" + )}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; } /** - * @param {any} options stats options - * @returns {StatsCompilation} json output + * @param {TODO} blocks TODO + * @param {TODO} id TODO + * @param {Object} context context + * @param {ChunkGraph} context.chunkGraph the chunk graph + * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph + * @returns {string} source code */ - 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)); - } + getLazySource(blocks, id, { chunkGraph, runtimeTemplate }) { + const moduleGraph = chunkGraph.moduleGraph; + const arrow = runtimeTemplate.supportsArrowFunction(); + let hasMultipleOrNoChunks = false; + let hasNoChunk = true; + const fakeMap = this.getFakeMap( + blocks.map(b => b.dependencies[0]), + chunkGraph + ); + const hasFakeMap = typeof fakeMap === "object"; + const items = blocks + .map(block => { + const dependency = block.dependencies[0]; + return { + dependency: dependency, + module: moduleGraph.getModule(dependency), + block: block, + userRequest: dependency.userRequest, + chunks: undefined + }; + }) + .filter(item => item.module); + for (const item of items) { + const chunkGroup = chunkGraph.getBlockChunkGroup(item.block); + const chunks = (chunkGroup && chunkGroup.chunks) || []; + item.chunks = chunks; + if (chunks.length > 0) { + hasNoChunk = false; } - } - if (options.warnings) { - obj.warnings = []; - for (const j of obj.children) { - for (const i of j.warnings) { - obj.warnings.push(mapError(j, i)); - } + if (chunks.length !== 1) { + hasMultipleOrNoChunks = true; } } - if (options.errorsCount) { - obj.errorsCount = 0; - for (const j of obj.children) { - obj.errorsCount += j.errorsCount; + const shortMode = hasNoChunk && !hasFakeMap; + const sortedItems = items.sort((a, b) => { + if (a.userRequest === b.userRequest) return 0; + return a.userRequest < b.userRequest ? -1 : 1; + }); + const map = Object.create(null); + for (const item of sortedItems) { + const moduleId = chunkGraph.getModuleId(item.module); + if (shortMode) { + map[item.userRequest] = moduleId; + } else { + const arrayStart = [moduleId]; + if (hasFakeMap) { + arrayStart.push(fakeMap[moduleId]); + } + map[item.userRequest] = arrayStart.concat( + item.chunks.map(chunk => chunk.id) + ); } } - if (options.warningsCount) { - obj.warningsCount = 0; - for (const j of obj.children) { - obj.warningsCount += j.warningsCount; - } + + const chunksStartPosition = hasFakeMap ? 2 : 1; + const requestPrefix = hasNoChunk + ? "Promise.resolve()" + : hasMultipleOrNoChunks + ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))` + : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`; + const returnModuleObject = this.getReturnModuleObjectSource( + fakeMap, + true, + shortMode ? "invalid" : "ids[1]" + ); + + const webpackAsyncContext = + requestPrefix === "Promise.resolve()" + ? ` +function webpackAsyncContext(req) { + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; } - 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; + ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"} + ${returnModuleObject} + }); +}` + : `function webpackAsyncContext(req) { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; }); - return results.filter(Boolean).join("\n\n"); } -} - -module.exports = MultiStats; - - -/***/ }), - -/***/ 81128: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + var ids = map[req], id = ids[0]; + return ${requestPrefix}.then(${arrow ? "() =>" : "function()"} { + ${returnModuleObject} + }); +}`; -const asyncLib = __webpack_require__(78175); + return `var map = ${JSON.stringify(map, null, "\t")}; +${webpackAsyncContext} +webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( + "Object.keys(map)" + )}; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } -/** @typedef {import("./MultiCompiler")} MultiCompiler */ -/** @typedef {import("./Watching")} Watching */ + getSourceForEmptyContext(id, runtimeTemplate) { + return `function webpackEmptyContext(req) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; +} +webpackEmptyContext.keys = ${runtimeTemplate.returningFunction("[]")}; +webpackEmptyContext.resolve = webpackEmptyContext; +webpackEmptyContext.id = ${JSON.stringify(id)}; +module.exports = webpackEmptyContext;`; + } -/** - * @template T - * @callback Callback - * @param {(Error | null)=} err - * @param {T=} result - */ + getSourceForEmptyAsyncContext(id, runtimeTemplate) { + const arrow = runtimeTemplate.supportsArrowFunction(); + return `function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); +} +webpackEmptyAsyncContext.keys = ${runtimeTemplate.returningFunction("[]")}; +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackEmptyAsyncContext;`; + } -class MultiWatching { /** - * @param {Watching[]} watchings child compilers' watchers - * @param {MultiCompiler} compiler the compiler + * @param {string} asyncMode module mode + * @param {CodeGenerationContext} context context info + * @returns {string} the source code */ - 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(); + getSourceString(asyncMode, { runtimeTemplate, chunkGraph }) { + const id = chunkGraph.getModuleId(this); + if (asyncMode === "lazy") { + if (this.blocks && this.blocks.length > 0) { + return this.getLazySource(this.blocks, id, { + runtimeTemplate, + chunkGraph + }); } + return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); } - } - - suspend() { - for (const watching of this.watchings) { - watching.suspend(); + if (asyncMode === "eager") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getEagerSource(this.dependencies, id, { + chunkGraph, + runtimeTemplate + }); + } + return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); + } + if (asyncMode === "lazy-once") { + const block = this.blocks[0]; + if (block) { + return this.getLazyOnceSource(block, block.dependencies, id, { + runtimeTemplate, + chunkGraph + }); + } + return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); + } + if (asyncMode === "async-weak") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getAsyncWeakSource(this.dependencies, id, { + chunkGraph, + runtimeTemplate + }); + } + return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); + } + if (asyncMode === "weak") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getWeakSyncSource(this.dependencies, id, chunkGraph); + } } + if (this.dependencies && this.dependencies.length > 0) { + return this.getSyncSource(this.dependencies, id, chunkGraph); + } + return this.getSourceForEmptyContext(id, runtimeTemplate); } - resume() { - for (const watching of this.watchings) { - watching.resume(); + getSource(sourceString) { + if (this.useSourceMap || this.useSimpleSourceMap) { + return new OriginalSource(sourceString, this.identifier()); } + return new RawSource(sourceString); } /** - * @param {Callback} callback signals when the watcher is closed - * @returns {void} + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - 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); - } - } + codeGeneration(context) { + const { chunkGraph } = context; + const sources = new Map(); + sources.set( + "javascript", + this.getSource(this.getSourceString(this.options.mode, context)) + ); + const set = new Set(); + const allDeps = /** @type {ContextElementDependency[]} */ ( + this.dependencies.concat(this.blocks.map(b => b.dependencies[0])) ); + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.hasOwnProperty); + if (allDeps.length > 0) { + const asyncMode = this.options.mode; + set.add(RuntimeGlobals.require); + if (asyncMode === "weak") { + set.add(RuntimeGlobals.moduleFactories); + } else if (asyncMode === "async-weak") { + set.add(RuntimeGlobals.moduleFactories); + set.add(RuntimeGlobals.ensureChunk); + } else if (asyncMode === "lazy" || asyncMode === "lazy-once") { + set.add(RuntimeGlobals.ensureChunk); + } + if (this.getFakeMap(allDeps, chunkGraph) !== 9) { + set.add(RuntimeGlobals.createFakeNamespaceObject); + } + } + return { + sources, + runtimeRequirements: set + }; } -} - -module.exports = MultiWatching; - - -/***/ }), - -/***/ 50169: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @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) { + // base penalty + let size = 160; + // if we don't have dependencies we stop here. + for (const dependency of this.dependencies) { + const element = /** @type {ContextElementDependency} */ (dependency); + size += 5 + element.userRequest.length; + } + return size; + } -/** @typedef {import("./Compiler")} Compiler */ + serialize(context) { + const { write } = context; + write(this._identifier); + write(this._forceBuild); + super.serialize(context); + } -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; - }); - }); + deserialize(context) { + const { read } = context; + this._identifier = read(); + this._forceBuild = read(); + super.deserialize(context); } } -module.exports = NoEmitOnErrorsPlugin; +makeSerializable(ContextModule, "webpack/lib/ContextModule"); + +module.exports = ContextModule; /***/ }), -/***/ 80832: +/***/ 62471: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -48178,68 +43488,397 @@ module.exports = NoEmitOnErrorsPlugin; -const WebpackError = __webpack_require__(53799); - -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/"; - } -}; - - -/***/ }), +const asyncLib = __webpack_require__(78175); +const { AsyncSeriesWaterfallHook, SyncWaterfallHook } = __webpack_require__(41242); +const ContextModule = __webpack_require__(76729); +const ModuleFactory = __webpack_require__(51010); +const ContextElementDependency = __webpack_require__(58477); +const LazySet = __webpack_require__(38938); +const { cachedSetProperty } = __webpack_require__(60839); +const { createFakeHook } = __webpack_require__(64518); +const { join } = __webpack_require__(17139); -/***/ 6325: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** @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} FakeHook */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ +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, "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 LazySet(); + const missingDependencies = new LazySet(); + const contextDependencies = new LazySet(); + 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 WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); + const context = beforeResolveResult.context; + const request = beforeResolveResult.request; + const resolveOptions = beforeResolveResult.resolveOptions; -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + 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 + }); + } + ); + } + ); + } + ); + } -class NodeStuffInWebError extends WebpackError { /** - * @param {DependencyLocation} loc loc - * @param {string} expression expression - * @param {string} description description + * @param {InputFileSystem} fs file system + * @param {ContextModuleOptions} options options + * @param {ResolveDependenciesCallback} callback callback function + * @returns {void} */ - constructor(loc, expression, description) { - super( - `${JSON.stringify( - expression - )} has been used, it will be undefined in next major version. -${description}` - ); + resolveDependencies(fs, options, callback) { + const cmf = this; + const { + resource, + resourceQuery, + resourceFragment, + recursive, + regExp, + include, + exclude, + referencedExports, + category, + typePrefix + } = options; + if (!regExp || !resource) return callback(null, []); - this.name = "NodeStuffInWebError"; - this.loc = loc; - } -} + 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 + ); + }); + }; -makeSerializable(NodeStuffInWebError, "webpack/lib/NodeStuffInWebError"); + 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); -module.exports = NodeStuffInWebError; + 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, + typePrefix, + 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); + } + } +}; /***/ }), -/***/ 95287: +/***/ 12206: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -48250,180 +43889,161 @@ module.exports = NodeStuffInWebError; -const NodeStuffInWebError = __webpack_require__(6325); -const RuntimeGlobals = __webpack_require__(16475); -const CachedConstDependency = __webpack_require__(57403); -const ConstDependency = __webpack_require__(76911); -const { - evaluateToString, - expressionIsUnsupported -} = __webpack_require__(93998); -const { relative } = __webpack_require__(17139); -const { parseResource } = __webpack_require__(82186); +const ContextElementDependency = __webpack_require__(58477); +const { join } = __webpack_require__(17139); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +class ContextReplacementPlugin { + constructor( + resourceRegExp, + newContentResource, + newContentRecursive, + newContentRegExp + ) { + this.resourceRegExp = resourceRegExp; -class NodeStuffPlugin { - constructor(options) { - this.options = options; + if (typeof newContentResource === "function") { + this.newContentCallback = newContentResource; + } else if ( + typeof newContentResource === "string" && + typeof newContentRecursive === "object" + ) { + this.newContentResource = newContentResource; + this.newContentCreateContextMap = (fs, callback) => { + callback(null, newContentRecursive); + }; + } else if ( + typeof newContentResource === "string" && + typeof newContentRecursive === "function" + ) { + this.newContentResource = newContentResource; + this.newContentCreateContextMap = newContentRecursive; + } else { + if (typeof newContentResource !== "string") { + newContentRegExp = newContentRecursive; + newContentRecursive = newContentResource; + newContentResource = undefined; + } + if (typeof newContentRecursive !== "boolean") { + newContentRegExp = newContentRecursive; + newContentRecursive = undefined; + } + this.newContentResource = newContentResource; + this.newContentRecursive = newContentRecursive; + this.newContentRegExp = newContentRegExp; + } } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap( - "NodeStuffPlugin", - (compilation, { normalModuleFactory }) => { - const handler = (parser, parserOptions) => { - if (parserOptions.node === false) return; + const resourceRegExp = this.resourceRegExp; + const newContentCallback = this.newContentCallback; + const newContentResource = this.newContentResource; + const newContentRecursive = this.newContentRecursive; + const newContentRegExp = this.newContentRegExp; + const newContentCreateContextMap = this.newContentCreateContextMap; - let localOptions = options; - if (parserOptions.node) { - localOptions = { ...localOptions, ...parserOptions.node }; + 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 (localOptions.global !== false) { - const withWarning = localOptions.global === "warn"; - 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); - - // TODO webpack 6 remove - if (withWarning) { - parser.state.module.addWarning( - new NodeStuffInWebError( - dep.loc, - "global", - "The global namespace object is Node.js feature and doesn't present in browser." - ) - ); - } - }); + if (newContentRecursive !== undefined) { + result.recursive = newContentRecursive; } - - const setModuleConstant = (expressionName, fn, warning) => { - 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); - - // TODO webpack 6 remove - if (warning) { - parser.state.module.addWarning( - new NodeStuffInWebError(dep.loc, expressionName, warning) - ); - } - - return true; - }); - }; - - const setConstant = (expressionName, value, warning) => - setModuleConstant(expressionName, () => value, warning); - - const context = compiler.context; - if (localOptions.__filename) { - switch (localOptions.__filename) { - case "mock": - setConstant("__filename", "/index.js"); - break; - case "warn-mock": - setConstant( - "__filename", - "/index.js", - "The __filename is Node.js feature and doesn't present in browser." - ); - break; - case true: - setModuleConstant("__filename", module => - relative(compiler.inputFileSystem, context, module.resource) - ); - break; + 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; } - - 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) { - switch (localOptions.__dirname) { - case "mock": - setConstant("__dirname", "/"); - break; - case "warn-mock": - setConstant( - "__dirname", - "/", - "The __dirname is Node.js feature and doesn't present in browser." - ); - break; - case true: - setModuleConstant("__dirname", module => - relative(compiler.inputFileSystem, context, module.context) - ); - break; + } + 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 + ); } - - 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); - } - ); + 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; + }); + }); } } -module.exports = NodeStuffPlugin; +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; /***/ }), -/***/ 39: +/***/ 79065: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -48434,341 +44054,689 @@ module.exports = NodeStuffPlugin; -const parseJson = __webpack_require__(15235); -const { getContext, runLoaders } = __webpack_require__(8255); -const querystring = __webpack_require__(63477); -const { HookMap, SyncHook, AsyncSeriesBailHook } = __webpack_require__(6967); -const { - CachedSource, - OriginalSource, - RawSource, - SourceMapSource -} = __webpack_require__(51255); -const Compilation = __webpack_require__(85720); -const HookWebpackError = __webpack_require__(11351); -const Module = __webpack_require__(73208); -const ModuleBuildError = __webpack_require__(21305); -const ModuleError = __webpack_require__(23744); -const ModuleGraphConnection = __webpack_require__(40639); -const ModuleParseError = __webpack_require__(58443); -const ModuleWarning = __webpack_require__(11234); const RuntimeGlobals = __webpack_require__(16475); -const UnhandledSchemeError = __webpack_require__(68099); const WebpackError = __webpack_require__(53799); -const formatLocation = __webpack_require__(16734); -const LazySet = __webpack_require__(38938); -const { isSubset } = __webpack_require__(93347); -const { getScheme } = __webpack_require__(54500); +const ConstDependency = __webpack_require__(76911); +const BasicEvaluatedExpression = __webpack_require__(950); const { - compareLocations, - concatComparators, - compareSelect, - keepOriginalOrder -} = __webpack_require__(29579); + evaluateToString, + toConstantDependency +} = __webpack_require__(93998); const createHash = __webpack_require__(49835); -const { createFakeHook } = __webpack_require__(64518); -const { join } = __webpack_require__(17139); -const { - contextify, - absolutify, - makePathsRelative -} = __webpack_require__(82186); -const makeSerializable = __webpack_require__(33032); -const memoize = __webpack_require__(78676); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/LoaderContext").NormalModuleLoaderContext} NormalModuleLoaderContext */ -/** @typedef {import("../declarations/WebpackOptions").Mode} Mode */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("estree").Expression} Expression */ /** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./Generator")} Generator */ -/** @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("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ -/** @typedef {import("./Parser")} Parser */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./NormalModule")} NormalModule */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./logging/Logger").Logger} WebpackLogger */ -/** @typedef {import("./util/Hash")} Hash */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ + +/** @typedef {null|undefined|RegExp|Function|string|number|boolean|bigint|undefined} CodeValuePrimitive */ +/** @typedef {RecursiveArrayOrRecord} CodeValue */ /** - * @typedef {Object} SourceMap - * @property {number} version - * @property {string[]} sources - * @property {string} mappings - * @property {string=} file - * @property {string=} sourceRoot - * @property {string[]=} sourcesContent - * @property {string[]=} names + * @typedef {Object} RuntimeValueOptions + * @property {string[]=} fileDependencies + * @property {string[]=} contextDependencies + * @property {string[]=} missingDependencies + * @property {string[]=} buildDependencies + * @property {string|function(): string=} version */ -const getInvalidDependenciesModuleWarning = memoize(() => - __webpack_require__(68257) -); -const getValidate = memoize(() => (__webpack_require__(38476).validate)); +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 || {}; + } -const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/; + get fileDependencies() { + return this.options === true ? true : this.options.fileDependencies; + } -/** - * @typedef {Object} LoaderItem - * @property {string} loader - * @property {any} options - * @property {string?} ident - * @property {string?} type - */ + /** + * @param {JavascriptParser} parser the parser + * @param {Map>} 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); + } + } + } -/** - * @param {string} context absolute context path - * @param {string} source a source path - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} new source path - */ -const contextifySourceUrl = (context, source, associatedObjectForCache) => { - if (source.startsWith("webpack://")) return source; - return `webpack://${makePathsRelative( - context, - source, - associatedObjectForCache - )}`; -}; + return this.fn({ + module: parser.state.module, + key, + get version() { + return /** @type {string} */ ( + 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 {string} context absolute context path - * @param {SourceMap} sourceMap a source map - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {SourceMap} new source map + * @param {any[]|{[k: string]: any}} obj obj + * @param {JavascriptParser} parser Parser + * @param {Map>} 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 contextifySourceMap = (context, sourceMap, associatedObjectForCache) => { - if (!Array.isArray(sourceMap.sources)) return sourceMap; - const { sourceRoot } = sourceMap; - /** @type {function(string): string} */ - const mapper = !sourceRoot - ? source => source - : sourceRoot.endsWith("/") - ? source => - source.startsWith("/") - ? `${sourceRoot.slice(0, -1)}${source}` - : `${sourceRoot}${source}` - : source => - source.startsWith("/") - ? `${sourceRoot}${source}` - : `${sourceRoot}/${source}`; - const newSources = sourceMap.sources.map(source => - contextifySourceUrl(context, mapper(source), associatedObjectForCache) - ); - return { - ...sourceMap, - file: "x", - sourceRoot: undefined, - sources: newSources - }; +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 `/*#__PURE__*/Object(${code})`; + } }; /** - * @param {string | Buffer} input the input - * @returns {string} the converted string + * Convert code to a string that evaluates + * @param {CodeValue} code Code to evaluate + * @param {JavascriptParser} parser Parser + * @param {Map>} 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 asString = input => { - if (Buffer.isBuffer(input)) { - return input.toString("utf-8"); +const toCode = ( + code, + parser, + valueCacheVersions, + key, + runtimeTemplate, + asiSafe +) => { + if (code === null) { + return "null"; } - return input; + 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 + ""; }; -/** - * @param {string | Buffer} input the input - * @returns {Buffer} the converted buffer - */ -const asBuffer = input => { - if (!Buffer.isBuffer(input)) { - return Buffer.from(input, "utf-8"); +const toCacheVersion = code => { + if (code === null) { + return "null"; } - return input; + 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 + ""; }; -class NonErrorEmittedError extends WebpackError { - constructor(error) { - super(); +const VALUE_DEP_PREFIX = "webpack/DefinePlugin "; +const VALUE_DEP_MAIN = "webpack/DefinePlugin_hash"; - this.name = "NonErrorEmittedError"; - this.message = "(Emitted value instead of an instance of Error) " + error; +class DefinePlugin { + /** + * Create a new define plugin + * @param {Record} definitions A map of global object definitions + */ + constructor(definitions) { + this.definitions = definitions; } -} - -makeSerializable( - NonErrorEmittedError, - "webpack/lib/NormalModule", - "NonErrorEmittedError" -); -/** - * @typedef {Object} NormalModuleCompilationHooks - * @property {SyncHook<[object, NormalModule]>} loader - * @property {SyncHook<[LoaderItem[], NormalModule, object]>} beforeLoaders - * @property {SyncHook<[NormalModule]>} beforeParse - * @property {SyncHook<[NormalModule]>} beforeSnapshot - * @property {HookMap>} readResourceForScheme - * @property {HookMap>} readResource - * @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild - */ - -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); - -class NormalModule extends Module { /** - * @param {Compilation} compilation the compilation - * @returns {NormalModuleCompilationHooks} the attached hooks + * @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 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 = { - loader: new SyncHook(["loaderContext", "module"]), - beforeLoaders: new SyncHook(["loaders", "module", "loaderContext"]), - beforeParse: new SyncHook(["module"]), - beforeSnapshot: new SyncHook(["module"]), - // TODO webpack 6 deprecate - readResourceForScheme: new HookMap(scheme => { - const hook = hooks.readResource.for(scheme); - return createFakeHook( - /** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer>} */ ({ - tap: (options, fn) => - hook.tap(options, loaderContext => - fn(loaderContext.resource, loaderContext._module) - ), - tapAsync: (options, fn) => - hook.tapAsync(options, (loaderContext, callback) => - fn(loaderContext.resource, loaderContext._module, callback) - ), - tapPromise: (options, fn) => - hook.tapPromise(options, loaderContext => - fn(loaderContext.resource, loaderContext._module) - ) - }) - ); - }), - readResource: new HookMap( - () => new AsyncSeriesBailHook(["loaderContext"]) - ), - needBuild: new AsyncSeriesBailHook(["module", "context"]) - }; - compilationHooksMap.set(compilation, hooks); - } - return hooks; + static runtimeValue(fn, options) { + return new RuntimeValue(fn, options); } /** - * @param {Object} options options object - * @param {string=} options.layer an optional layer in which the module is - * @param {string} options.type module type - * @param {string} options.request request string - * @param {string} options.userRequest request intended by user (without loaders from config) - * @param {string} options.rawRequest request without resolving - * @param {LoaderItem[]} options.loaders list of loaders - * @param {string} options.resource path + query of the real resource - * @param {Record=} options.resourceResolveData resource resolve data - * @param {string} options.context context directory for resolving - * @param {string | undefined} options.matchResource path + query of the matched resource (virtual) - * @param {Parser} options.parser the parser used - * @param {object} options.parserOptions the options of the parser used - * @param {Generator} options.generator the generator used - * @param {object} options.generatorOptions the options of the generator used - * @param {Object} options.resolveOptions options used for resolving requests from this module + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - constructor({ - layer, - type, - request, - userRequest, - rawRequest, - loaders, - resource, - resourceResolveData, - context, - matchResource, - parser, - parserOptions, - generator, - generatorOptions, - resolveOptions - }) { - super(type, context || getContext(resource), layer); + apply(compiler) { + const definitions = this.definitions; + compiler.hooks.compilation.tap( + "DefinePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + const { runtimeTemplate } = compilation; + + const mainHash = createHash(compilation.outputOptions.hashFunction); + mainHash.update( + /** @type {string} */ ( + compilation.valueCacheVersions.get(VALUE_DEP_MAIN) + ) || "" + ); + + /** + * Handler + * @param {JavascriptParser} parser Parser + * @returns {void} + */ + const handler = parser => { + const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN); + parser.hooks.program.tap("DefinePlugin", () => { + const { buildInfo } = parser.state.module; + if (!buildInfo.valueDependencies) + buildInfo.valueDependencies = new Map(); + buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue); + }); + + const addValueDependency = key => { + const { buildInfo } = parser.state.module; + 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; + mainHash.update("|" + prefix + key); + const oldVersion = compilation.valueCacheVersions.get(name); + if (oldVersion === undefined) { + compilation.valueCacheVersions.set(name, version); + } else if (oldVersion !== version) { + const warning = new WebpackError( + `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, ""); + + compilation.valueCacheVersions.set( + VALUE_DEP_MAIN, + /** @type {string} */ (mainHash.digest("hex").slice(0, 8)) + ); + } + ); + } +} +module.exports = DefinePlugin; + + +/***/ }), + +/***/ 28623: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { OriginalSource, RawSource } = __webpack_require__(51255); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const DelegatedSourceDependency = __webpack_require__(22914); +const StaticExportsDependency = __webpack_require__(91418); +const makeSerializable = __webpack_require__(33032); + +/** @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 - /** @type {string} */ - this.request = request; - /** @type {string} */ + this.sourceRequest = sourceRequest; + this.request = data.id; + this.delegationType = type; this.userRequest = userRequest; - /** @type {string} */ - this.rawRequest = rawRequest; - /** @type {boolean} */ - this.binary = /^(asset|webassembly)\b/.test(type); - /** @type {Parser} */ - this.parser = parser; - this.parserOptions = parserOptions; - /** @type {Generator} */ - this.generator = generator; - this.generatorOptions = generatorOptions; - /** @type {string} */ - this.resource = resource; - this.resourceResolveData = resourceResolveData; - /** @type {string | undefined} */ - this.matchResource = matchResource; - /** @type {LoaderItem[]} */ - this.loaders = loaders; - if (resolveOptions !== undefined) { - // already declared in super class - this.resolveOptions = resolveOptions; - } + this.originalRequest = originalRequest; + /** @type {ManifestModuleData} */ + this.delegateData = data; - // Info from Build - /** @type {(WebpackError | null)=} */ - this.error = null; - /** @private @type {Source=} */ - this._source = null; - /** @private @type {Map | undefined} **/ - this._sourceSizes = undefined; - /** @private @type {Set} */ - this._sourceTypes = undefined; + // Build info + this.delegatedSourceDependency = undefined; + } - // Cache - this._lastSuccessfulBuildMeta = {}; - this._forceBuild = true; - this._isEvaluatingSideEffects = false; - /** @type {WeakSet | undefined} */ - this._addedSideEffectsBailout = undefined; + /** + * @returns {Set} 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() { - if (this.layer === null) { - if (this.type === "javascript/auto") { - return this.request; - } else { - return `${this.type}|${this.request}`; - } - } else { - return `${this.type}|${this.request}|${this.layer}`; - } + return `delegated ${JSON.stringify(this.request)} from ${ + this.sourceRequest + }`; } /** @@ -48776,31 +44744,127 @@ class NormalModule extends Module { * @returns {string} a user readable identifier of the module */ readableIdentifier(requestShortener) { - return requestShortener.shorten(this.userRequest); + return `delegated ${this.userRequest} from ${this.sourceRequest}`; } /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} */ - libIdent(options) { - let ident = contextify( - options.context, - this.userRequest, - options.associatedObjectForCache + 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 ); - if (this.layer) ident = `(${this.layer})/${ident}`; - return ident; + this.addDependency(this.delegatedSourceDependency); + this.addDependency( + new StaticExportsDependency(this.delegateData.exports || true, false) + ); + callback(); } /** - * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - nameForCondition() { - const resource = this.matchResource || this.resource; - const idx = resource.indexOf("?"); - if (idx >= 0) return resource.substr(0, idx); - return resource; + 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; } /** @@ -48812,1032 +44876,651 @@ class NormalModule extends Module { */ updateCacheModule(module) { super.updateCacheModule(module); - const m = /** @type {NormalModule} */ (module); - this.binary = m.binary; - this.request = m.request; + const m = /** @type {DelegatedModule} */ (module); + this.delegationType = m.delegationType; this.userRequest = m.userRequest; - this.rawRequest = m.rawRequest; - this.parser = m.parser; - this.parserOptions = m.parserOptions; - this.generator = m.generator; - this.generatorOptions = m.generatorOptions; - this.resource = m.resource; - this.resourceResolveData = m.resourceResolveData; - this.context = m.context; - this.matchResource = m.matchResource; - this.loaders = m.loaders; + this.originalRequest = m.originalRequest; + this.delegateData = m.delegateData; } /** * Assuming this module is in the cache. Remove internal references to allow freeing some memory. */ cleanupForCache() { - // Make sure to cache types and sizes before cleanup when this module has been built - // They are accessed by the stats and we don't want them to crash after cleanup - // TODO reconsider this for webpack 6 - if (this.buildInfo) { - if (this._sourceTypes === undefined) this.getSourceTypes(); - for (const type of this._sourceTypes) { - this.size(type); - } - } super.cleanupForCache(); - this.parser = undefined; - this.parserOptions = undefined; - this.generator = undefined; - this.generatorOptions = undefined; + this.delegateData = undefined; + } +} + +makeSerializable(DelegatedModule, "webpack/lib/DelegatedModule"); + +module.exports = DelegatedModule; + + +/***/ }), + +/***/ 51387: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const DelegatedModule = __webpack_require__(28623); + +// 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; + + +/***/ }), + +/***/ 80632: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const DelegatedModuleFactoryPlugin = __webpack_require__(51387); +const DelegatedSourceDependency = __webpack_require__(22914); + +/** @typedef {import("./Compiler")} Compiler */ + +class DelegatedPlugin { + constructor(options) { + this.options = options; } /** - * Module should be unsafe cached. Get data that's needed for that. - * This data will be passed to restoreFromUnsafeCache later. - * @returns {object} cached data + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - getUnsafeCacheData() { - const data = super.getUnsafeCacheData(); - data.parserOptions = this.parserOptions; - data.generatorOptions = this.generatorOptions; - return data; + 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); + }); } +} - restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { - this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); +module.exports = DelegatedPlugin; + + +/***/ }), + +/***/ 71040: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); + +/** @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 = []; + /** @type {DependenciesBlock} */ + this.parent = undefined; + } + + getRootBlock() { + /** @type {DependenciesBlock} */ + let current = this; + while (current.parent) current = current.parent; + return current; } /** - * restore unsafe cache data - * @param {object} unsafeCacheData data from getUnsafeCacheData - * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching + * 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} */ - _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { - super._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); - this.parserOptions = unsafeCacheData.parserOptions; - this.parser = normalModuleFactory.getParser(this.type, this.parserOptions); - this.generatorOptions = unsafeCacheData.generatorOptions; - this.generator = normalModuleFactory.getGenerator( - this.type, - this.generatorOptions - ); - // we assume the generator behaves identically and keep cached sourceTypes/Sizes + addBlock(block) { + this.blocks.push(block); + block.parent = this; } /** - * @param {string} context the compilation context - * @param {string} name the asset name - * @param {string} content the content - * @param {string | TODO} sourceMap an optional source map - * @param {Object=} associatedObjectForCache object for caching - * @returns {Source} the created source + * @param {Dependency} dependency dependency being tied to block. + * This is an "edge" pointing to another "node" on module graph. + * @returns {void} */ - createSourceForAsset( - context, - name, - content, - sourceMap, - associatedObjectForCache - ) { - if (sourceMap) { - if ( - typeof sourceMap === "string" && - (this.useSourceMap || this.useSimpleSourceMap) - ) { - return new OriginalSource( - content, - contextifySourceUrl(context, sourceMap, associatedObjectForCache) - ); - } + addDependency(dependency) { + this.dependencies.push(dependency); + } - if (this.useSourceMap) { - return new SourceMapSource( - content, - name, - contextifySourceMap(context, sourceMap, associatedObjectForCache) - ); - } + /** + * @param {Dependency} dependency dependency being removed + * @returns {void} + */ + removeDependency(dependency) { + const idx = this.dependencies.indexOf(dependency); + if (idx >= 0) { + this.dependencies.splice(idx, 1); } + } - return new RawSource(content); + /** + * Removes all dependencies and blocks + * @returns {void} + */ + clearDependenciesAndBlocks() { + this.dependencies.length = 0; + this.blocks.length = 0; } /** - * @param {ResolverWithOptions} resolver a resolver - * @param {WebpackOptions} options webpack options - * @param {Compilation} compilation the compilation - * @param {InputFileSystem} fs file system from reading - * @param {NormalModuleCompilationHooks} hooks the hooks - * @returns {NormalModuleLoaderContext} loader context + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} */ - _createLoaderContext(resolver, options, compilation, fs, hooks) { - const { requestShortener } = compilation.runtimeTemplate; - const getCurrentLoaderName = () => { - const currentLoader = this.getCurrentLoader(loaderContext); - if (!currentLoader) return "(not in loader scope)"; - return requestShortener.shorten(currentLoader.loader); - }; - const getResolveContext = () => { - return { - fileDependencies: { - add: d => loaderContext.addDependency(d) - }, - contextDependencies: { - add: d => loaderContext.addContextDependency(d) - }, - missingDependencies: { - add: d => loaderContext.addMissingDependency(d) - } - }; - }; - const getAbsolutify = memoize(() => - absolutify.bindCache(compilation.compiler.root) - ); - const getAbsolutifyInContext = memoize(() => - absolutify.bindContextCache(this.context, compilation.compiler.root) - ); - const getContextify = memoize(() => - contextify.bindCache(compilation.compiler.root) - ); - const getContextifyInContext = memoize(() => - contextify.bindContextCache(this.context, compilation.compiler.root) - ); - const utils = { - absolutify: (context, request) => { - return context === this.context - ? getAbsolutifyInContext()(request) - : getAbsolutify()(context, request); - }, - contextify: (context, request) => { - return context === this.context - ? getContextifyInContext()(request) - : getContextify()(context, request); - }, - createHash: type => { - return createHash(type || compilation.outputOptions.hashFunction); - } - }; - const loaderContext = { - version: 2, - getOptions: schema => { - const loader = this.getCurrentLoader(loaderContext); - - let { options } = loader; + updateHash(hash, context) { + for (const dep of this.dependencies) { + dep.updateHash(hash, context); + } + for (const block of this.blocks) { + block.updateHash(hash, context); + } + } - if (typeof options === "string") { - if (options.substr(0, 1) === "{" && options.substr(-1) === "}") { - try { - options = parseJson(options); - } catch (e) { - throw new Error(`Cannot parse string options: ${e.message}`); - } - } else { - options = querystring.parse(options, "&", "=", { - maxKeys: 0 - }); - } - } + serialize({ write }) { + write(this.dependencies); + write(this.blocks); + } - if (options === null || options === undefined) { - options = {}; - } + deserialize({ read }) { + this.dependencies = read(); + this.blocks = read(); + for (const block of this.blocks) { + block.parent = this; + } + } +} - if (schema) { - let name = "Loader"; - let baseDataPath = "options"; - let match; - if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) { - [, name, baseDataPath] = match; - } - getValidate()(schema, options, { - name, - baseDataPath - }); - } +makeSerializable(DependenciesBlock, "webpack/lib/DependenciesBlock"); - return options; - }, - emitWarning: warning => { - if (!(warning instanceof Error)) { - warning = new NonErrorEmittedError(warning); - } - this.addWarning( - new ModuleWarning(warning, { - from: getCurrentLoaderName() - }) - ); - }, - emitError: error => { - if (!(error instanceof Error)) { - error = new NonErrorEmittedError(error); - } - this.addError( - new ModuleError(error, { - from: getCurrentLoaderName() - }) - ); - }, - getLogger: name => { - const currentLoader = this.getCurrentLoader(loaderContext); - return compilation.getLogger(() => - [currentLoader && currentLoader.loader, name, this.identifier()] - .filter(Boolean) - .join("|") - ); - }, - resolve(context, request, callback) { - resolver.resolve({}, context, request, getResolveContext(), callback); - }, - getResolve(options) { - const child = options ? resolver.withOptions(options) : resolver; - return (context, request, callback) => { - if (callback) { - child.resolve({}, context, request, getResolveContext(), callback); - } else { - return new Promise((resolve, reject) => { - child.resolve( - {}, - context, - request, - getResolveContext(), - (err, result) => { - if (err) reject(err); - else resolve(result); - } - ); - }); - } - }; - }, - emitFile: (name, content, sourceMap, assetInfo) => { - if (!this.buildInfo.assets) { - this.buildInfo.assets = Object.create(null); - this.buildInfo.assetsInfo = new Map(); - } - this.buildInfo.assets[name] = this.createSourceForAsset( - options.context, - name, - content, - sourceMap, - compilation.compiler.root - ); - this.buildInfo.assetsInfo.set(name, assetInfo); - }, - addBuildDependency: dep => { - if (this.buildInfo.buildDependencies === undefined) { - this.buildInfo.buildDependencies = new LazySet(); - } - this.buildInfo.buildDependencies.add(dep); - }, - utils, - rootContext: options.context, - webpack: true, - sourceMap: !!this.useSourceMap, - mode: options.mode || "production", - _module: this, - _compilation: compilation, - _compiler: compilation.compiler, - fs: fs - }; +module.exports = DependenciesBlock; - Object.assign(loaderContext, options.loader); - hooks.loader.call(loaderContext, this); +/***/ }), - return loaderContext; - } +/***/ 54912: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) { - if ( - this.loaders && - this.loaders.length && - index < this.loaders.length && - index >= 0 && - this.loaders[index] - ) { - return this.loaders[index]; - } - return null; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @param {string} context the compilation context - * @param {string | Buffer} content the content - * @param {string | TODO} sourceMap an optional source map - * @param {Object=} associatedObjectForCache object for caching - * @returns {Source} the created source - */ - createSource(context, content, sourceMap, associatedObjectForCache) { - if (Buffer.isBuffer(content)) { - return new RawSource(content); - } - // if there is no identifier return raw source - if (!this.identifier) { - return new RawSource(content); - } - // from here on we assume we have an identifier - const identifier = this.identifier(); +const memoize = __webpack_require__(78676); - if (this.useSourceMap && sourceMap) { - return new SourceMapSource( - content, - contextifySourceUrl(context, identifier, associatedObjectForCache), - contextifySourceMap(context, sourceMap, associatedObjectForCache) - ); - } +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ - if (this.useSourceMap || this.useSimpleSourceMap) { - return new OriginalSource( - content, - contextifySourceUrl(context, identifier, associatedObjectForCache) - ); - } +/** + * @typedef {Object} UpdateHashContext + * @property {ChunkGraph} chunkGraph + * @property {RuntimeSpec} runtime + * @property {RuntimeTemplate=} runtimeTemplate + */ - return new RawSource(content); - } +/** + * @typedef {Object} SourcePosition + * @property {number} line + * @property {number=} column + */ - /** - * @param {WebpackOptions} options webpack options - * @param {Compilation} compilation the compilation - * @param {ResolverWithOptions} resolver the resolver - * @param {InputFileSystem} fs the file system - * @param {NormalModuleCompilationHooks} hooks the hooks - * @param {function((WebpackError | null)=): void} callback callback function - * @returns {void} - */ - _doBuild(options, compilation, resolver, fs, hooks, callback) { - const loaderContext = this._createLoaderContext( - resolver, - options, - compilation, - fs, - hooks - ); +/** + * @typedef {Object} RealDependencyLocation + * @property {SourcePosition} start + * @property {SourcePosition=} end + * @property {number=} index + */ - const processResult = (err, result) => { - if (err) { - if (!(err instanceof Error)) { - err = new NonErrorEmittedError(err); - } - const currentLoader = this.getCurrentLoader(loaderContext); - const error = new ModuleBuildError(err, { - from: - currentLoader && - compilation.runtimeTemplate.requestShortener.shorten( - currentLoader.loader - ) - }); - return callback(error); - } +/** + * @typedef {Object} SyntheticDependencyLocation + * @property {string} name + * @property {number=} index + */ - const source = result[0]; - const sourceMap = result.length >= 1 ? result[1] : null; - const extraInfo = result.length >= 2 ? result[2] : null; +/** @typedef {SyntheticDependencyLocation|RealDependencyLocation} DependencyLocation */ - if (!Buffer.isBuffer(source) && typeof source !== "string") { - const currentLoader = this.getCurrentLoader(loaderContext, 0); - const err = new Error( - `Final loader (${ - currentLoader - ? compilation.runtimeTemplate.requestShortener.shorten( - currentLoader.loader - ) - : "unknown" - }) didn't return a Buffer or String` - ); - const error = new ModuleBuildError(err); - return callback(error); - } +/** + * @typedef {Object} ExportSpec + * @property {string} name the name of the export + * @property {boolean=} canMangle can the export be renamed (defaults to true) + * @property {boolean=} terminalBinding is the export a terminal binding that should be checked for export star conflicts + * @property {(string | ExportSpec)[]=} exports nested exports + * @property {ModuleGraphConnection=} from when reexported: from which module + * @property {string[] | null=} export when reexported: from which export + * @property {number=} priority when reexported: with which priority + * @property {boolean=} hidden export is not visible, because another export blends over it + */ - this._source = this.createSource( - options.context, - this.binary ? asBuffer(source) : asString(source), - sourceMap, - compilation.compiler.root - ); - if (this._sourceSizes !== undefined) this._sourceSizes.clear(); - this._ast = - typeof extraInfo === "object" && - extraInfo !== null && - extraInfo.webpackAST !== undefined - ? extraInfo.webpackAST - : null; - return callback(); - }; +/** + * @typedef {Object} ExportsSpec + * @property {(string | ExportSpec)[] | true | null} exports exported names, true for unknown exports or null for no exports + * @property {Set=} excludeExports when exports = true, list of unaffected exports + * @property {Set=} hideExports list of maybe prior exposed, but now hidden exports + * @property {ModuleGraphConnection=} from when reexported: from which module + * @property {number=} priority when reexported: with which priority + * @property {boolean=} canMangle can the export be renamed (defaults to true) + * @property {boolean=} terminalBinding are the exports terminal bindings that should be checked for export star conflicts + * @property {Module[]=} dependencies module on which the result depends on + */ - this.buildInfo.fileDependencies = new LazySet(); - this.buildInfo.contextDependencies = new LazySet(); - this.buildInfo.missingDependencies = new LazySet(); - this.buildInfo.cacheable = true; +/** + * @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 + */ - try { - hooks.beforeLoaders.call(this.loaders, this, loaderContext); - } catch (err) { - processResult(err); - return; - } +const TRANSITIVE = Symbol("transitive"); - if (this.loaders.length > 0) { - this.buildInfo.buildDependencies = new LazySet(); - } +const getIgnoredModule = memoize(() => { + const RawModule = __webpack_require__(84929); + return new RawModule("/* (ignored) */", `ignored`, `(ignored)`); +}); - runLoaders( - { - resource: this.resource, - loaders: this.loaders, - context: loaderContext, - processResource: (loaderContext, resourcePath, callback) => { - const resource = loaderContext.resource; - const scheme = getScheme(resource); - hooks.readResource - .for(scheme) - .callAsync(loaderContext, (err, result) => { - if (err) return callback(err); - if (typeof result !== "string" && !result) { - return callback(new UnhandledSchemeError(scheme, resource)); - } - return callback(null, result); - }); - } - }, - (err, result) => { - // Cleanup loaderContext to avoid leaking memory in ICs - loaderContext._compilation = - loaderContext._compiler = - loaderContext._module = - loaderContext.fs = - undefined; +class Dependency { + constructor() { + /** @type {Module} */ + this._parentModule = undefined; + /** @type {DependenciesBlock} */ + this._parentDependenciesBlock = undefined; + /** @type {number} */ + this._parentDependenciesBlockIndex = -1; + // TODO check if this can be moved into ModuleDependency + /** @type {boolean} */ + this.weak = false; + // TODO check if this can be moved into ModuleDependency + /** @type {boolean} */ + this.optional = false; + this._locSL = 0; + this._locSC = 0; + this._locEL = 0; + this._locEC = 0; + this._locI = undefined; + this._locN = undefined; + this._loc = undefined; + } - if (!result) { - this.buildInfo.cacheable = false; - return processResult( - err || new Error("No result from loader-runner processing"), - null - ); - } - this.buildInfo.fileDependencies.addAll(result.fileDependencies); - this.buildInfo.contextDependencies.addAll(result.contextDependencies); - this.buildInfo.missingDependencies.addAll(result.missingDependencies); - for (const loader of this.loaders) { - this.buildInfo.buildDependencies.add(loader.loader); - } - this.buildInfo.cacheable = this.buildInfo.cacheable && result.cacheable; - processResult(err, result.result); - } - ); + /** + * @returns {string} a display name for the type of dependency + */ + get type() { + return "unknown"; } /** - * @param {WebpackError} error the error - * @returns {void} + * @returns {string} a dependency category, typical categories are "commonjs", "amd", "esm" */ - markModuleAsErrored(error) { - // Restore build meta from successful build to keep importing state - this.buildMeta = { ...this._lastSuccessfulBuildMeta }; - this.error = error; - this.addError(error); + get category() { + return "unknown"; } - applyNoParseRule(rule, content) { - // must start with "rule" if rule is a string - if (typeof rule === "string") { - return content.startsWith(rule); + /** + * @returns {DependencyLocation} location + */ + get loc() { + if (this._loc !== undefined) return this._loc; + /** @type {SyntheticDependencyLocation & RealDependencyLocation} */ + const loc = {}; + if (this._locSL > 0) { + loc.start = { line: this._locSL, column: this._locSC }; } - - if (typeof rule === "function") { - return rule(content); + if (this._locEL > 0) { + loc.end = { line: this._locEL, column: this._locEC }; } - // we assume rule is a regexp - return rule.test(content); + if (this._locN !== undefined) { + loc.name = this._locN; + } + if (this._locI !== undefined) { + loc.index = this._locI; + } + return (this._loc = loc); } - // check if module should not be parsed - // returns "true" if the module should !not! be parsed - // returns "false" if the module !must! be parsed - shouldPreventParsing(noParseRule, request) { - // if no noParseRule exists, return false - // the module !must! be parsed. - if (!noParseRule) { - return false; + set loc(loc) { + if ("start" in loc && typeof loc.start === "object") { + this._locSL = loc.start.line || 0; + this._locSC = loc.start.column || 0; + } else { + this._locSL = 0; + this._locSC = 0; } - - // we only have one rule to check - if (!Array.isArray(noParseRule)) { - // returns "true" if the module is !not! to be parsed - return this.applyNoParseRule(noParseRule, request); + if ("end" in loc && typeof loc.end === "object") { + this._locEL = loc.end.line || 0; + this._locEC = loc.end.column || 0; + } else { + this._locEL = 0; + this._locEC = 0; } - - for (let i = 0; i < noParseRule.length; i++) { - const rule = noParseRule[i]; - // early exit on first truthy match - // this module is !not! to be parsed - if (this.applyNoParseRule(rule, request)) { - return true; - } + if ("index" in loc) { + this._locI = loc.index; + } else { + this._locI = undefined; } - // no match found, so this module !should! be parsed - return false; + if ("name" in loc) { + this._locN = loc.name; + } else { + this._locN = undefined; + } + this._loc = loc; } - _initBuildHash(compilation) { - const hash = createHash(compilation.outputOptions.hashFunction); - if (this._source) { - hash.update("source"); - this._source.updateHash(hash); - } - hash.update("meta"); - hash.update(JSON.stringify(this.buildMeta)); - this.buildInfo.hash = /** @type {string} */ (hash.digest("hex")); + setLoc(startLine, startColumn, endLine, endColumn) { + this._locSL = startLine; + this._locSC = startColumn; + this._locEL = endLine; + this._locEC = endColumn; + this._locI = undefined; + this._locN = undefined; + this._loc = undefined; } /** - * @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} + * @returns {string | null} an identifier to merge equal requests */ - build(options, compilation, resolver, fs, callback) { - this._forceBuild = false; - this._source = null; - if (this._sourceSizes !== undefined) this._sourceSizes.clear(); - this._sourceTypes = undefined; - this._ast = null; - this.error = null; - this.clearWarningsAndErrors(); - this.clearDependenciesAndBlocks(); - this.buildMeta = {}; - this.buildInfo = { - cacheable: false, - parsed: true, - fileDependencies: undefined, - contextDependencies: undefined, - missingDependencies: undefined, - buildDependencies: undefined, - valueDependencies: undefined, - hash: undefined, - assets: undefined, - assetsInfo: undefined - }; - - const startTime = compilation.compiler.fsStartTime || Date.now(); - - const hooks = NormalModule.getCompilationHooks(compilation); - - return this._doBuild(options, compilation, resolver, fs, hooks, err => { - // if we have an error mark module as failed and exit - if (err) { - this.markModuleAsErrored(err); - this._initBuildHash(compilation); - return callback(); - } - - const handleParseError = e => { - const source = this._source.source(); - const loaders = this.loaders.map(item => - contextify(options.context, item.loader, compilation.compiler.root) - ); - const error = new ModuleParseError(source, e, loaders, this.type); - this.markModuleAsErrored(error); - this._initBuildHash(compilation); - return callback(); - }; - - const handleParseResult = result => { - this.dependencies.sort( - concatComparators( - compareSelect(a => a.loc, compareLocations), - keepOriginalOrder(this.dependencies) - ) - ); - this._initBuildHash(compilation); - this._lastSuccessfulBuildMeta = this.buildMeta; - return handleBuildDone(); - }; - - const handleBuildDone = () => { - try { - hooks.beforeSnapshot.call(this); - } catch (err) { - this.markModuleAsErrored(err); - return callback(); - } - - const snapshotOptions = compilation.options.snapshot.module; - if (!this.buildInfo.cacheable || !snapshotOptions) { - return callback(); - } - // add warning for all non-absolute paths in fileDependencies, etc - // This makes it easier to find problems with watching and/or caching - let nonAbsoluteDependencies = undefined; - const checkDependencies = deps => { - for (const dep of deps) { - if (!ABSOLUTE_PATH_REGEX.test(dep)) { - if (nonAbsoluteDependencies === undefined) - nonAbsoluteDependencies = new Set(); - nonAbsoluteDependencies.add(dep); - deps.delete(dep); - try { - const depWithoutGlob = dep.replace(/[\\/]?\*.*$/, ""); - const absolute = join( - compilation.fileSystemInfo.fs, - this.context, - depWithoutGlob - ); - if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) { - (depWithoutGlob !== dep - ? this.buildInfo.contextDependencies - : deps - ).add(absolute); - } - } catch (e) { - // ignore - } - } - } - }; - checkDependencies(this.buildInfo.fileDependencies); - checkDependencies(this.buildInfo.missingDependencies); - checkDependencies(this.buildInfo.contextDependencies); - if (nonAbsoluteDependencies !== undefined) { - const InvalidDependenciesModuleWarning = - getInvalidDependenciesModuleWarning(); - this.addWarning( - new InvalidDependenciesModuleWarning(this, nonAbsoluteDependencies) - ); - } - // convert file/context/missingDependencies into filesystem snapshot - compilation.fileSystemInfo.createSnapshot( - startTime, - this.buildInfo.fileDependencies, - this.buildInfo.contextDependencies, - this.buildInfo.missingDependencies, - snapshotOptions, - (err, snapshot) => { - if (err) { - this.markModuleAsErrored(err); - return; - } - this.buildInfo.fileDependencies = undefined; - this.buildInfo.contextDependencies = undefined; - this.buildInfo.missingDependencies = undefined; - this.buildInfo.snapshot = snapshot; - return callback(); - } - ); - }; - - try { - hooks.beforeParse.call(this); - } catch (err) { - this.markModuleAsErrored(err); - this._initBuildHash(compilation); - return callback(); - } - - // check if this module should !not! be parsed. - // if so, exit here; - const noParseRule = options.module && options.module.noParse; - if (this.shouldPreventParsing(noParseRule, this.request)) { - // We assume that we need module and exports - this.buildInfo.parsed = false; - this._initBuildHash(compilation); - return handleBuildDone(); - } - - let result; - try { - const source = this._source.source(); - result = this.parser.parse(this._ast || source, { - source, - current: this, - module: this, - compilation: compilation, - options: options - }); - } catch (e) { - handleParseError(e); - return; - } - handleParseResult(result); - }); + getResourceIdentifier() { + return null; } /** - * @param {ConcatenationBailoutReasonContext} context context - * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module */ - getConcatenationBailoutReason(context) { - return this.generator.getConcatenationBailoutReason(this, context); + couldAffectReferencingModule() { + return TRANSITIVE; } /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only + * Returns the referenced module and export + * @deprecated + * @param {ModuleGraph} moduleGraph module graph + * @returns {never} throws error */ - getSideEffectsConnectionState(moduleGraph) { - if (this.factoryMeta !== undefined) { - if (this.factoryMeta.sideEffectFree) return false; - if (this.factoryMeta.sideEffectFree === false) return true; - } - if (this.buildMeta !== undefined && this.buildMeta.sideEffectFree) { - if (this._isEvaluatingSideEffects) - return ModuleGraphConnection.CIRCULAR_CONNECTION; - this._isEvaluatingSideEffects = true; - /** @type {ConnectionState} */ - let current = false; - for (const dep of this.dependencies) { - const state = dep.getModuleEvaluationSideEffectsState(moduleGraph); - if (state === true) { - if ( - this._addedSideEffectsBailout === undefined - ? ((this._addedSideEffectsBailout = new WeakSet()), true) - : !this._addedSideEffectsBailout.has(moduleGraph) - ) { - this._addedSideEffectsBailout.add(moduleGraph); - moduleGraph - .getOptimizationBailout(this) - .push( - () => - `Dependency (${ - dep.type - }) with side effects at ${formatLocation(dep.loc)}` - ); - } - this._isEvaluatingSideEffects = false; - return true; - } else if (state !== ModuleGraphConnection.CIRCULAR_CONNECTION) { - current = ModuleGraphConnection.addConnectionStates(current, state); - } - } - this._isEvaluatingSideEffects = false; - // When caching is implemented here, make sure to not cache when - // at least one circular connection was in the loop above - return current; - } else { - return true; - } + getReference(moduleGraph) { + throw new Error( + "Dependency.getReference was removed in favor of Dependency.getReferencedExports, ModuleGraph.getModule and ModuleGraph.getConnection().active" + ); } /** - * @returns {Set} types available (do not mutate) + * 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 */ - getSourceTypes() { - if (this._sourceTypes === undefined) { - this._sourceTypes = this.generator.getTypes(this); - } - return this._sourceTypes; + getReferencedExports(moduleGraph, runtime) { + return Dependency.EXPORTS_OBJECT_REFERENCED; } /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active */ - codeGeneration({ - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime, - concatenationScope, - codeGenerationResults - }) { - /** @type {Set} */ - const runtimeRequirements = new Set(); - - if (!this.buildInfo.parsed) { - runtimeRequirements.add(RuntimeGlobals.module); - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.thisAsExports); - } - - /** @type {Map} */ - let data; - const getData = () => { - if (data === undefined) data = new Map(); - return data; - }; - - const sources = new Map(); - for (const type of this.generator.getTypes(this)) { - const source = this.error - ? new RawSource( - "throw new Error(" + JSON.stringify(this.error.message) + ");" - ) - : this.generator.generate(this, { - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtimeRequirements, - runtime, - concatenationScope, - codeGenerationResults, - getData, - type - }); - - if (source) { - sources.set(type, new CachedSource(source)); - } - } + getCondition(moduleGraph) { + return null; + } - /** @type {CodeGenerationResult} */ - const resultEntry = { - sources, - runtimeRequirements, - data - }; - return resultEntry; + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + return undefined; } /** - * @returns {Source | null} the original source for the module before webpack transformation + * Returns warnings + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} warnings */ - originalSource() { - return this._source; + getWarnings(moduleGraph) { + return null; } /** - * @returns {void} + * Returns errors + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} errors */ - invalidateBuild() { - this._forceBuild = true; + getErrors(moduleGraph) { + return null; } /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context * @returns {void} */ - needBuild(context, callback) { - const { fileSystemInfo, compilation, valueCacheVersions } = context; - // build if enforced - if (this._forceBuild) return callback(null, true); - - // always try to build in case of an error - if (this.error) return callback(null, true); - - // always build when module is not cacheable - if (!this.buildInfo.cacheable) return callback(null, true); - - // build when there is no snapshot to check - if (!this.buildInfo.snapshot) return callback(null, true); - - // build when valueDependencies have changed - /** @type {Map>} */ - const valueDependencies = this.buildInfo.valueDependencies; - if (valueDependencies) { - if (!valueCacheVersions) return callback(null, true); - for (const [key, value] of valueDependencies) { - if (value === undefined) return callback(null, true); - const current = valueCacheVersions.get(key); - if ( - value !== current && - (typeof value === "string" || - typeof current === "string" || - current === undefined || - !isSubset(value, current)) - ) { - return callback(null, true); - } - } - } - - // check snapshot for validity - fileSystemInfo.checkSnapshotValid(this.buildInfo.snapshot, (err, valid) => { - if (err) return callback(err); - if (!valid) return callback(null, true); - const hooks = NormalModule.getCompilationHooks(compilation); - hooks.needBuild.callAsync(this, context, (err, needBuild) => { - if (err) { - return callback( - HookWebpackError.makeWebpackError( - err, - "NormalModule.getCompilationHooks().needBuild" - ) - ); - } - callback(null, !!needBuild); - }); - }); - } + updateHash(hash, context) {} /** - * @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) + * implement this method to allow the occurrence order plugin to count correctly + * @returns {number} count how often the id is used in this dependency */ - size(type) { - const cachedSize = - this._sourceSizes === undefined ? undefined : this._sourceSizes.get(type); - if (cachedSize !== undefined) { - return cachedSize; - } - const size = Math.max(1, this.generator.getSize(this, type)); - if (this._sourceSizes === undefined) { - this._sourceSizes = new Map(); - } - this._sourceSizes.set(type, size); - return size; + getNumberOfIdOccurrences() { + return 1; } /** - * @param {LazySet} fileDependencies set where file dependencies are added to - * @param {LazySet} contextDependencies set where context dependencies are added to - * @param {LazySet} missingDependencies set where missing dependencies are added to - * @param {LazySet} buildDependencies set where build dependencies are added to + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules */ - addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ) { - const { snapshot, buildDependencies: buildDeps } = this.buildInfo; - if (snapshot) { - fileDependencies.addAll(snapshot.getFileIterable()); - contextDependencies.addAll(snapshot.getContextIterable()); - missingDependencies.addAll(snapshot.getMissingIterable()); - } else { - const { - fileDependencies: fileDeps, - contextDependencies: contextDeps, - missingDependencies: missingDeps - } = this.buildInfo; - if (fileDeps !== undefined) fileDependencies.addAll(fileDeps); - if (contextDeps !== undefined) contextDependencies.addAll(contextDeps); - if (missingDeps !== undefined) missingDependencies.addAll(missingDeps); - } - if (buildDeps !== undefined) { - buildDependencies.addAll(buildDeps); - } + getModuleEvaluationSideEffectsState(moduleGraph) { + return true; } /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} + * @param {string} context context directory + * @returns {Module} a module */ - updateHash(hash, context) { - hash.update(this.buildInfo.hash); - this.generator.updateHash(hash, { - module: this, - ...context - }); - super.updateHash(hash, context); + createIgnoredModule(context) { + return getIgnoredModule(); } - serialize(context) { - const { write } = context; - // deserialize - write(this._source); - write(this.error); - write(this._lastSuccessfulBuildMeta); - write(this._forceBuild); - super.serialize(context); + serialize({ write }) { + write(this.weak); + write(this.optional); + write(this._locSL); + write(this._locSC); + write(this._locEL); + write(this._locEC); + write(this._locI); + write(this._locN); } - static deserialize(context) { - const obj = new NormalModule({ - // will be deserialized by Module - layer: null, - type: "", - // will be filled by updateCacheModule - resource: "", - context: "", - request: null, - userRequest: null, - rawRequest: null, - loaders: null, - matchResource: null, - parser: null, - parserOptions: null, - generator: null, - generatorOptions: null, - resolveOptions: null - }); - obj.deserialize(context); - return obj; + deserialize({ read }) { + this.weak = read(); + this.optional = read(); + this._locSL = read(); + this._locSC = read(); + this._locEL = read(); + this._locEC = read(); + this._locI = read(); + this._locN = read(); } +} - deserialize(context) { - const { read } = context; - this._source = read(); - this.error = read(); - this._lastSuccessfulBuildMeta = read(); - this._forceBuild = read(); - super.deserialize(context); +/** @type {string[][]} */ +Dependency.NO_EXPORTS_REFERENCED = []; +/** @type {string[][]} */ +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)" + ); } -} +}); -makeSerializable(NormalModule, "webpack/lib/NormalModule"); +Object.defineProperty(Dependency.prototype, "disconnect", { + get() { + throw new Error( + "disconnect was removed from Dependency (Dependency no longer carries graph specific information)" + ); + } +}); -module.exports = NormalModule; +Dependency.TRANSITIVE = TRANSITIVE; + +module.exports = Dependency; /***/ }), -/***/ 68860: +/***/ 5160: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -49848,1117 +45531,485 @@ module.exports = NormalModule; -const { getContext } = __webpack_require__(8255); -const asyncLib = __webpack_require__(78175); -const { - AsyncSeriesBailHook, - SyncWaterfallHook, - SyncBailHook, - SyncHook, - HookMap -} = __webpack_require__(6967); -const ChunkGraph = __webpack_require__(64971); -const Module = __webpack_require__(73208); -const ModuleFactory = __webpack_require__(51010); -const ModuleGraph = __webpack_require__(99988); -const NormalModule = __webpack_require__(39); -const BasicEffectRulePlugin = __webpack_require__(30318); -const BasicMatcherRulePlugin = __webpack_require__(94215); -const ObjectMatcherRulePlugin = __webpack_require__(72021); -const RuleSetCompiler = __webpack_require__(83349); -const UseEffectRulePlugin = __webpack_require__(84977); -const LazySet = __webpack_require__(38938); -const { getScheme } = __webpack_require__(54500); -const { cachedCleverMerge, cachedSetProperty } = __webpack_require__(60839); -const { join } = __webpack_require__(17139); -const { parseResource } = __webpack_require__(82186); - -/** @typedef {import("../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ -/** @typedef {import("./Generator")} Generator */ -/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("./Parser")} Parser */ -/** @typedef {import("./ResolverFactory")} ResolverFactory */ -/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Generator").GenerateContext} GenerateContext */ +/** @template T @typedef {import("./InitFragment")} InitFragment */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ /** - * @typedef {Object} ResolveData - * @property {ModuleFactoryCreateData["contextInfo"]} contextInfo - * @property {ModuleFactoryCreateData["resolveOptions"]} resolveOptions - * @property {string} context - * @property {string} request - * @property {Record | undefined} assertions - * @property {ModuleDependency[]} dependencies - * @property {string} dependencyType - * @property {Object} createData - * @property {LazySet} fileDependencies - * @property {LazySet} missingDependencies - * @property {LazySet} contextDependencies - * @property {boolean} cacheable allow to use the unsafe cache + * @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} 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 + * @property {CodeGenerationResults} codeGenerationResults the code generation results */ /** - * @typedef {Object} ResourceData - * @property {string} resource - * @property {string} path - * @property {string} query - * @property {string} fragment - * @property {string=} context + * @typedef {Object} CssDependencyTemplateContextExtras + * @property {Map} cssExports the css exports */ -/** @typedef {ResourceData & { data: Record }} ResourceDataWithData */ +/** @typedef {DependencyTemplateContext & CssDependencyTemplateContextExtras} CssDependencyTemplateContext */ -const EMPTY_RESOLVE_OPTIONS = {}; -const EMPTY_PARSER_OPTIONS = {}; -const EMPTY_GENERATOR_OPTIONS = {}; -const EMPTY_ELEMENTS = []; +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 = __webpack_require__(77198); + throw new AbstractMethodError(); + } +} -const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; +module.exports = DependencyTemplate; -const loaderToIdent = data => { - if (!data.options) { - return data.loader; - } - if (typeof data.options === "string") { - return data.loader + "?" + data.options; - } - if (typeof data.options !== "object") { - throw new Error("loader options must be string or object"); - } - if (data.ident) { - return data.loader + "??" + data.ident; - } - return data.loader + "?" + JSON.stringify(data.options); -}; -const stringifyLoadersAndResource = (loaders, resource) => { - let str = ""; - for (const loader of loaders) { - str += loaderToIdent(loader) + "!"; - } - return str + resource; -}; +/***/ }), -/** - * @param {string} resultString resultString - * @returns {{loader: string, options: string|undefined}} parsed loader request - */ -const identToLoaderRequest = resultString => { - const idx = resultString.indexOf("?"); - if (idx >= 0) { - const loader = resultString.substr(0, idx); - const options = resultString.substr(idx + 1); - return { - loader, - options - }; - } else { - return { - loader: resultString, - options: undefined - }; - } -}; +/***/ 9163: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const needCalls = (times, callback) => { - return err => { - if (--times === 0) { - return callback(err); - } - if (err && times > 0) { - times = NaN; - return callback(err); - } - }; -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -const mergeGlobalOptions = (globalOptions, type, localOptions) => { - const parts = type.split("/"); - let result; - let current = ""; - for (const part of parts) { - current = current ? `${current}/${part}` : part; - const options = globalOptions[current]; - if (typeof options === "object") { - if (result === undefined) { - result = options; - } else { - result = cachedCleverMerge(result, options); - } - } - } - if (result === undefined) { - return localOptions; - } else { - return cachedCleverMerge(result, localOptions); - } -}; -// TODO webpack 6 remove -const deprecationChangedHookMessage = (name, hook) => { - const names = hook.taps - .map(tapped => { - return tapped.name; - }) - .join(", "); - return ( - `NormalModuleFactory.${name} (${names}) is no longer a waterfall hook, but a bailing hook instead. ` + - "Do not return the passed object, but modify it instead. " + - "Returning false will ignore the request and results in no module created." - ); -}; +const createHash = __webpack_require__(49835); -const ruleSetCompiler = new RuleSetCompiler([ - new BasicMatcherRulePlugin("test", "resource"), - new BasicMatcherRulePlugin("scheme"), - new BasicMatcherRulePlugin("mimetype"), - new BasicMatcherRulePlugin("dependency"), - new BasicMatcherRulePlugin("include", "resource"), - new BasicMatcherRulePlugin("exclude", "resource", true), - new BasicMatcherRulePlugin("resource"), - new BasicMatcherRulePlugin("resourceQuery"), - new BasicMatcherRulePlugin("resourceFragment"), - new BasicMatcherRulePlugin("realResource"), - new BasicMatcherRulePlugin("issuer"), - new BasicMatcherRulePlugin("compiler"), - new BasicMatcherRulePlugin("issuerLayer"), - new ObjectMatcherRulePlugin("assert", "assertions"), - new ObjectMatcherRulePlugin("descriptionData"), - new BasicEffectRulePlugin("type"), - new BasicEffectRulePlugin("sideEffects"), - new BasicEffectRulePlugin("parser"), - new BasicEffectRulePlugin("resolve"), - new BasicEffectRulePlugin("generator"), - new BasicEffectRulePlugin("layer"), - new UseEffectRulePlugin() -]); +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ +/** @typedef {typeof import("./util/Hash")} Hash */ -class NormalModuleFactory extends ModuleFactory { +/** @typedef {new (...args: any[]) => Dependency} DependencyConstructor */ + +class DependencyTemplates { /** - * @param {Object} param params - * @param {string=} param.context context - * @param {InputFileSystem} param.fs file system - * @param {ResolverFactory} param.resolverFactory resolverFactory - * @param {ModuleOptions} param.options options - * @param {Object=} param.associatedObjectForCache an object to which the cache will be attached - * @param {boolean=} param.layers enable layers + * @param {string | Hash} hashFunction the hash function to use */ - constructor({ - context, - fs, - resolverFactory, - options, - associatedObjectForCache, - layers = false - }) { - super(); - this.hooks = Object.freeze({ - /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ - resolve: new AsyncSeriesBailHook(["resolveData"]), - /** @type {HookMap>} */ - resolveForScheme: new HookMap( - () => new AsyncSeriesBailHook(["resourceData", "resolveData"]) - ), - /** @type {HookMap>} */ - resolveInScheme: new HookMap( - () => new AsyncSeriesBailHook(["resourceData", "resolveData"]) - ), - /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ - factorize: new AsyncSeriesBailHook(["resolveData"]), - /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ - beforeResolve: new AsyncSeriesBailHook(["resolveData"]), - /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ - afterResolve: new AsyncSeriesBailHook(["resolveData"]), - /** @type {AsyncSeriesBailHook<[ResolveData["createData"], ResolveData], TODO>} */ - createModule: new AsyncSeriesBailHook(["createData", "resolveData"]), - /** @type {SyncWaterfallHook<[Module, ResolveData["createData"], ResolveData], TODO>} */ - module: new SyncWaterfallHook(["module", "createData", "resolveData"]), - createParser: new HookMap(() => new SyncBailHook(["parserOptions"])), - parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])), - createGenerator: new HookMap( - () => new SyncBailHook(["generatorOptions"]) - ), - generator: new HookMap( - () => new SyncHook(["generator", "generatorOptions"]) - ) - }); - this.resolverFactory = resolverFactory; - this.ruleSet = ruleSetCompiler.compile([ - { - rules: options.defaultRules - }, - { - rules: options.rules - } - ]); - this.context = context || ""; - this.fs = fs; - this._globalParserOptions = options.parser; - this._globalGeneratorOptions = options.generator; - /** @type {Map>} */ - this.parserCache = new Map(); - /** @type {Map>} */ - this.generatorCache = new Map(); - /** @type {Set} */ - this._restoredUnsafeCacheEntries = new Set(); + constructor(hashFunction = "md4") { + /** @type {Map} */ + this._map = new Map(); + /** @type {string} */ + this._hash = "31d6cfe0d16ae931b73c59d7e0c089c0"; + this._hashFunction = hashFunction; + } - const cacheParseResource = parseResource.bindCache( - associatedObjectForCache - ); + /** + * @param {DependencyConstructor} dependency Constructor of Dependency + * @returns {DependencyTemplate} template for this dependency + */ + get(dependency) { + return this._map.get(dependency); + } - this.hooks.factorize.tapAsync( - { - name: "NormalModuleFactory", - stage: 100 - }, - (resolveData, callback) => { - this.hooks.resolve.callAsync(resolveData, (err, result) => { - if (err) return callback(err); + /** + * @param {DependencyConstructor} dependency Constructor of Dependency + * @param {DependencyTemplate} dependencyTemplate template for this dependency + * @returns {void} + */ + set(dependency, dependencyTemplate) { + this._map.set(dependency, dependencyTemplate); + } - // Ignored - if (result === false) return callback(); + /** + * @param {string} part additional hash contributor + * @returns {void} + */ + updateHash(part) { + const hash = createHash(this._hashFunction); + hash.update(`${this._hash}${part}`); + this._hash = /** @type {string} */ (hash.digest("hex")); + } - // direct module - if (result instanceof Module) return callback(null, result); + getHash() { + return this._hash; + } - if (typeof result === "object") - throw new Error( - deprecationChangedHookMessage("resolve", this.hooks.resolve) + - " Returning a Module object will result in this module used as result." - ); + clone() { + const newInstance = new DependencyTemplates(this._hashFunction); + newInstance._map = new Map(this._map); + newInstance._hash = this._hash; + return newInstance; + } +} - this.hooks.afterResolve.callAsync(resolveData, (err, result) => { - if (err) return callback(err); +module.exports = DependencyTemplates; - if (typeof result === "object") - throw new Error( - deprecationChangedHookMessage( - "afterResolve", - this.hooks.afterResolve - ) - ); - // Ignored - if (result === false) return callback(); +/***/ }), - const createData = resolveData.createData; +/***/ 62790: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - this.hooks.createModule.callAsync( - createData, - resolveData, - (err, createdModule) => { - if (!createdModule) { - if (!resolveData.request) { - return callback(new Error("Empty dependency (no request)")); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - createdModule = new NormalModule(createData); - } - createdModule = this.hooks.module.call( - createdModule, - createData, - resolveData - ); - return callback(null, createdModule); - } - ); - }); - }); +const DllModuleFactory = __webpack_require__(68703); +const DllEntryDependency = __webpack_require__(95666); +const EntryDependency = __webpack_require__(3979); + +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 + ); } ); - this.hooks.resolve.tapAsync( - { - name: "NormalModuleFactory", - stage: 100 - }, - (data, callback) => { - const { - contextInfo, - context, - dependencies, - dependencyType, - request, - assertions, - resolveOptions, - fileDependencies, - missingDependencies, - contextDependencies - } = data; - const loaderResolver = this.getResolver("loader"); - - /** @type {ResourceData | undefined} */ - let matchResourceData = undefined; - /** @type {string} */ - let unresolvedResource; - /** @type {{loader: string, options: string|undefined}[]} */ - let elements; - let noPreAutoLoaders = false; - let noAutoLoaders = false; - let noPrePostAutoLoaders = false; + 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 + ); + }); + } +} - const contextScheme = getScheme(context); - /** @type {string | undefined} */ - let scheme = getScheme(request); +module.exports = DllEntryPlugin; - if (!scheme) { - /** @type {string} */ - let requestWithoutMatchResource = request; - const matchResourceMatch = MATCH_RESOURCE_REGEX.exec(request); - if (matchResourceMatch) { - let matchResource = matchResourceMatch[1]; - if (matchResource.charCodeAt(0) === 46) { - // 46 === ".", 47 === "/" - const secondChar = matchResource.charCodeAt(1); - if ( - secondChar === 47 || - (secondChar === 46 && matchResource.charCodeAt(2) === 47) - ) { - // if matchResources startsWith ../ or ./ - matchResource = join(this.fs, context, matchResource); - } - } - matchResourceData = { - resource: matchResource, - ...cacheParseResource(matchResource) - }; - requestWithoutMatchResource = request.substr( - matchResourceMatch[0].length - ); - } - scheme = getScheme(requestWithoutMatchResource); +/***/ }), - if (!scheme && !contextScheme) { - const firstChar = requestWithoutMatchResource.charCodeAt(0); - const secondChar = requestWithoutMatchResource.charCodeAt(1); - noPreAutoLoaders = firstChar === 45 && secondChar === 33; // startsWith "-!" - noAutoLoaders = noPreAutoLoaders || firstChar === 33; // startsWith "!" - noPrePostAutoLoaders = firstChar === 33 && secondChar === 33; // startsWith "!!"; - const rawElements = requestWithoutMatchResource - .slice( - noPreAutoLoaders || noPrePostAutoLoaders - ? 2 - : noAutoLoaders - ? 1 - : 0 - ) - .split(/!+/); - unresolvedResource = rawElements.pop(); - elements = rawElements.map(identToLoaderRequest); - scheme = getScheme(unresolvedResource); - } else { - unresolvedResource = requestWithoutMatchResource; - elements = EMPTY_ELEMENTS; - } - } else { - unresolvedResource = request; - elements = EMPTY_ELEMENTS; - } +/***/ 28280: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const resolveContext = { - fileDependencies, - missingDependencies, - contextDependencies - }; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {ResourceDataWithData} */ - let resourceData; - let loaders; - const continueCallback = needCalls(2, err => { - if (err) return callback(err); +const { RawSource } = __webpack_require__(51255); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); - // translate option idents - try { - for (const item of loaders) { - if (typeof item.options === "string" && item.options[0] === "?") { - const ident = item.options.substr(1); - if (ident === "[[missing ident]]") { - throw new Error( - "No ident is provided by referenced loader. " + - "When using a function for Rule.use in config you need to " + - "provide an 'ident' property for referenced loader options." - ); - } - item.options = this.ruleSet.references.get(ident); - if (item.options === undefined) { - throw new Error( - "Invalid ident is provided by referenced loader" - ); - } - item.ident = ident; - } - } - } catch (e) { - return callback(e); - } +/** @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 */ - if (!resourceData) { - // ignored - return callback(null, dependencies[0].createIgnoredModule(context)); - } +const TYPES = new Set(["javascript"]); +const RUNTIME_REQUIREMENTS = new Set([ + RuntimeGlobals.require, + RuntimeGlobals.module +]); - const userRequest = - (matchResourceData !== undefined - ? `${matchResourceData.resource}!=!` - : "") + - stringifyLoadersAndResource(loaders, resourceData.resource); +class DllModule extends Module { + constructor(context, dependencies, name) { + super("javascript/dynamic", context); - const settings = {}; - const useLoadersPost = []; - const useLoaders = []; - const useLoadersPre = []; + // Info from Factory + this.dependencies = dependencies; + this.name = name; + } - // handle .webpack[] suffix - let resource; - let match; - if ( - matchResourceData && - typeof (resource = matchResourceData.resource) === "string" && - (match = /\.webpack\[([^\]]+)\]$/.exec(resource)) - ) { - settings.type = match[1]; - matchResourceData.resource = matchResourceData.resource.slice( - 0, - -settings.type.length - 10 - ); - } else { - settings.type = "javascript/auto"; - const resourceDataForRules = matchResourceData || resourceData; - const result = this.ruleSet.exec({ - resource: resourceDataForRules.path, - realResource: resourceData.path, - resourceQuery: resourceDataForRules.query, - resourceFragment: resourceDataForRules.fragment, - scheme, - assertions, - mimetype: matchResourceData - ? "" - : resourceData.data.mimetype || "", - dependency: dependencyType, - descriptionData: matchResourceData - ? undefined - : resourceData.data.descriptionFileData, - issuer: contextInfo.issuer, - compiler: contextInfo.compiler, - issuerLayer: contextInfo.issuerLayer || "" - }); - for (const r of result) { - if (r.type === "use") { - if (!noAutoLoaders && !noPrePostAutoLoaders) { - useLoaders.push(r.value); - } - } else if (r.type === "use-post") { - if (!noPrePostAutoLoaders) { - useLoadersPost.push(r.value); - } - } else if (r.type === "use-pre") { - if (!noPreAutoLoaders && !noPrePostAutoLoaders) { - useLoadersPre.push(r.value); - } - } else if ( - typeof r.value === "object" && - r.value !== null && - typeof settings[r.type] === "object" && - settings[r.type] !== null - ) { - settings[r.type] = cachedCleverMerge(settings[r.type], r.value); - } else { - settings[r.type] = r.value; - } - } - } + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; + } - let postLoaders, normalLoaders, preLoaders; + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `dll ${this.name}`; + } - const continueCallback = needCalls(3, err => { - if (err) { - return callback(err); - } - const allLoaders = postLoaders; - if (matchResourceData === undefined) { - for (const loader of loaders) allLoaders.push(loader); - for (const loader of normalLoaders) allLoaders.push(loader); - } else { - for (const loader of normalLoaders) allLoaders.push(loader); - for (const loader of loaders) allLoaders.push(loader); - } - for (const loader of preLoaders) allLoaders.push(loader); - let type = settings.type; - const resolveOptions = settings.resolve; - const layer = settings.layer; - if (layer !== undefined && !layers) { - return callback( - new Error( - "'Rule.layer' is only allowed when 'experiments.layers' is enabled" - ) - ); - } - try { - Object.assign(data.createData, { - layer: - layer === undefined ? contextInfo.issuerLayer || null : layer, - request: stringifyLoadersAndResource( - allLoaders, - resourceData.resource - ), - userRequest, - rawRequest: request, - loaders: allLoaders, - resource: resourceData.resource, - context: - resourceData.context || getContext(resourceData.resource), - matchResource: matchResourceData - ? matchResourceData.resource - : undefined, - resourceResolveData: resourceData.data, - settings, - type, - parser: this.getParser(type, settings.parser), - parserOptions: settings.parser, - generator: this.getGenerator(type, settings.generator), - generatorOptions: settings.generator, - resolveOptions - }); - } catch (e) { - return callback(e); - } - callback(); - }); - this.resolveRequestArray( - contextInfo, - this.context, - useLoadersPost, - loaderResolver, - resolveContext, - (err, result) => { - postLoaders = result; - continueCallback(err); - } - ); - this.resolveRequestArray( - contextInfo, - this.context, - useLoaders, - loaderResolver, - resolveContext, - (err, result) => { - normalLoaders = result; - continueCallback(err); - } - ); - this.resolveRequestArray( - contextInfo, - this.context, - useLoadersPre, - loaderResolver, - resolveContext, - (err, result) => { - preLoaders = result; - continueCallback(err); - } - ); - }); + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `dll ${this.name}`; + } - this.resolveRequestArray( - contextInfo, - contextScheme ? this.context : context, - elements, - loaderResolver, - resolveContext, - (err, result) => { - if (err) return continueCallback(err); - loaders = result; - continueCallback(); - } - ); + /** + * @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(); + } - const defaultResolve = context => { - if (/^($|\?)/.test(unresolvedResource)) { - resourceData = { - resource: unresolvedResource, - data: {}, - ...cacheParseResource(unresolvedResource) - }; - continueCallback(); - } + /** + * @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 + }; + } - // resource without scheme and with path - else { - const normalResolver = this.getResolver( - "normal", - dependencyType - ? cachedSetProperty( - resolveOptions || EMPTY_RESOLVE_OPTIONS, - "dependencyType", - dependencyType - ) - : resolveOptions - ); - this.resolveResource( - contextInfo, - context, - unresolvedResource, - normalResolver, - resolveContext, - (err, resolvedResource, resolvedResourceResolveData) => { - if (err) return continueCallback(err); - if (resolvedResource !== false) { - resourceData = { - resource: resolvedResource, - data: resolvedResourceResolveData, - ...cacheParseResource(resolvedResource) - }; - } - continueCallback(); - } - ); - } - }; + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, !this.buildMeta); + } - // resource with scheme - if (scheme) { - resourceData = { - resource: unresolvedResource, - data: {}, - path: undefined, - query: undefined, - fragment: undefined, - context: undefined - }; - this.hooks.resolveForScheme - .for(scheme) - .callAsync(resourceData, data, err => { - if (err) return continueCallback(err); - continueCallback(); - }); - } + /** + * @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; + } - // resource within scheme - else if (contextScheme) { - resourceData = { - resource: unresolvedResource, - data: {}, - path: undefined, - query: undefined, - fragment: undefined, - context: undefined - }; - this.hooks.resolveInScheme - .for(contextScheme) - .callAsync(resourceData, data, (err, handled) => { - if (err) return continueCallback(err); - if (!handled) return defaultResolve(this.context); - continueCallback(); - }); - } + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + hash.update(`dll module${this.name || ""}`); + super.updateHash(hash, context); + } - // resource without scheme and without path - else defaultResolve(context); - } - ); + serialize(context) { + context.write(this.name); + super.serialize(context); } - cleanupForCache() { - for (const module of this._restoredUnsafeCacheEntries) { - ChunkGraph.clearChunkGraphForModule(module); - ModuleGraph.clearModuleGraphForModule(module); - module.cleanupForCache(); - } + deserialize(context) { + this.name = context.read(); + super.deserialize(context); } /** - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * 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} */ - create(data, callback) { - const dependencies = /** @type {ModuleDependency[]} */ (data.dependencies); - const context = data.context || this.context; - const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS; - const dependency = dependencies[0]; - const request = dependency.request; - const assertions = dependency.assertions; - const contextInfo = data.contextInfo; - const fileDependencies = new LazySet(); - const missingDependencies = new LazySet(); - const contextDependencies = new LazySet(); - const dependencyType = - (dependencies.length > 0 && dependencies[0].category) || ""; - /** @type {ResolveData} */ - const resolveData = { - contextInfo, - resolveOptions, - context, - request, - assertions, - dependencies, - dependencyType, - fileDependencies, - missingDependencies, - contextDependencies, - createData: {}, - cacheable: true - }; - this.hooks.beforeResolve.callAsync(resolveData, (err, result) => { - if (err) { - return callback(err, { - fileDependencies, - missingDependencies, - contextDependencies, - cacheable: false - }); - } - - // Ignored - if (result === false) { - return callback(null, { - fileDependencies, - missingDependencies, - contextDependencies, - cacheable: resolveData.cacheable - }); - } - - if (typeof result === "object") - throw new Error( - deprecationChangedHookMessage( - "beforeResolve", - this.hooks.beforeResolve - ) - ); - - this.hooks.factorize.callAsync(resolveData, (err, module) => { - if (err) { - return callback(err, { - fileDependencies, - missingDependencies, - contextDependencies, - cacheable: false - }); - } - - const factoryResult = { - module, - fileDependencies, - missingDependencies, - contextDependencies, - cacheable: resolveData.cacheable - }; + updateCacheModule(module) { + super.updateCacheModule(module); + this.dependencies = module.dependencies; + } - callback(null, factoryResult); - }); - }); + /** + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. + */ + cleanupForCache() { + super.cleanupForCache(); + this.dependencies = undefined; } +} - resolveResource( - contextInfo, - context, - unresolvedResource, - resolver, - resolveContext, - callback - ) { - resolver.resolve( - contextInfo, - context, - unresolvedResource, - resolveContext, - (err, resolvedResource, resolvedResourceResolveData) => { - if (err) { - return this._resolveResourceErrorHints( - err, - contextInfo, - context, - unresolvedResource, - resolver, - resolveContext, - (err2, hints) => { - if (err2) { - err.message += ` -An fatal error happened during resolving additional hints for this error: ${err2.message}`; - err.stack += ` +makeSerializable(DllModule, "webpack/lib/DllModule"); -An fatal error happened during resolving additional hints for this error: -${err2.stack}`; - return callback(err); - } - if (hints && hints.length > 0) { - err.message += ` -${hints.join("\n\n")}`; - } - callback(err); - } - ); - } - callback(err, resolvedResource, resolvedResourceResolveData); - } - ); - } +module.exports = DllModule; - _resolveResourceErrorHints( - error, - contextInfo, - context, - unresolvedResource, - resolver, - resolveContext, - callback - ) { - asyncLib.parallel( - [ - callback => { - if (!resolver.options.fullySpecified) return callback(); - resolver - .withOptions({ - fullySpecified: false - }) - .resolve( - contextInfo, - context, - unresolvedResource, - resolveContext, - (err, resolvedResource) => { - if (!err && resolvedResource) { - const resource = parseResource(resolvedResource).path.replace( - /^.*[\\/]/, - "" - ); - return callback( - null, - `Did you mean '${resource}'? -BREAKING CHANGE: The request '${unresolvedResource}' failed to resolve only because it was resolved as fully specified -(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"'). -The extension in the request is mandatory for it to be fully specified. -Add the extension to the request.` - ); - } - callback(); - } - ); - }, - callback => { - if (!resolver.options.enforceExtension) return callback(); - resolver - .withOptions({ - enforceExtension: false, - extensions: [] - }) - .resolve( - contextInfo, - context, - unresolvedResource, - resolveContext, - (err, resolvedResource) => { - if (!err && resolvedResource) { - let hint = ""; - const match = /(\.[^.]+)(\?|$)/.exec(unresolvedResource); - if (match) { - const fixedRequest = unresolvedResource.replace( - /(\.[^.]+)(\?|$)/, - "$2" - ); - if (resolver.options.extensions.has(match[1])) { - hint = `Did you mean '${fixedRequest}'?`; - } else { - hint = `Did you mean '${fixedRequest}'? Also note that '${match[1]}' is not in 'resolve.extensions' yet and need to be added for this to work?`; - } - } else { - hint = `Did you mean to omit the extension or to remove 'resolve.enforceExtension'?`; - } - return callback( - null, - `The request '${unresolvedResource}' failed to resolve only because 'resolve.enforceExtension' was specified. -${hint} -Including the extension in the request is no longer possible. Did you mean to enforce including the extension in requests with 'resolve.extensions: []' instead?` - ); - } - callback(); - } - ); - }, - callback => { - if ( - /^\.\.?\//.test(unresolvedResource) || - resolver.options.preferRelative - ) { - return callback(); - } - resolver.resolve( - contextInfo, - context, - `./${unresolvedResource}`, - resolveContext, - (err, resolvedResource) => { - if (err || !resolvedResource) return callback(); - const moduleDirectories = resolver.options.modules - .map(m => (Array.isArray(m) ? m.join(", ") : m)) - .join(", "); - callback( - null, - `Did you mean './${unresolvedResource}'? -Requests that should resolve in the current directory need to start with './'. -Requests that start with a name are treated as module requests and resolve within module directories (${moduleDirectories}). -If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.` - ); - } - ); - } - ], - (err, hints) => { - if (err) return callback(err); - callback(null, hints.filter(Boolean)); - } - ); - } - resolveRequestArray( - contextInfo, - context, - array, - resolver, - resolveContext, - callback - ) { - if (array.length === 0) return callback(null, array); - asyncLib.map( - array, - (item, callback) => { - resolver.resolve( - contextInfo, - context, - item.loader, - resolveContext, - (err, result) => { - if ( - err && - /^[^/]*$/.test(item.loader) && - !/-loader$/.test(item.loader) - ) { - return resolver.resolve( - contextInfo, - context, - item.loader + "-loader", - resolveContext, - err2 => { - if (!err2) { - err.message = - err.message + - "\n" + - "BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" + - ` You need to specify '${item.loader}-loader' instead of '${item.loader}',\n` + - " see https://webpack.js.org/migrate/3/#automatic-loader-module-name-extension-removed"; - } - callback(err); - } - ); - } - if (err) return callback(err); +/***/ }), - const parsedResult = identToLoaderRequest(result); - const resolved = { - loader: parsedResult.loader, - options: - item.options === undefined - ? parsedResult.options - : item.options, - ident: item.options === undefined ? undefined : item.ident - }; - return callback(null, resolved); - } - ); - }, - callback - ); - } +/***/ 68703: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - getParser(type, parserOptions = EMPTY_PARSER_OPTIONS) { - let cache = this.parserCache.get(type); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (cache === undefined) { - cache = new WeakMap(); - this.parserCache.set(type, cache); - } - let parser = cache.get(parserOptions); - if (parser === undefined) { - parser = this.createParser(type, parserOptions); - cache.set(parserOptions, parser); - } +const DllModule = __webpack_require__(28280); +const ModuleFactory = __webpack_require__(51010); - return parser; - } +/** @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 {string} type type - * @param {{[k: string]: any}} parserOptions parser options - * @returns {Parser} parser + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * @returns {void} */ - createParser(type, parserOptions = {}) { - parserOptions = mergeGlobalOptions( - this._globalParserOptions, - type, - parserOptions - ); - const parser = this.hooks.createParser.for(type).call(parserOptions); - if (!parser) { - throw new Error(`No parser registered for ${type}`); - } - this.hooks.parser.for(type).call(parser, parserOptions); - return parser; + create(data, callback) { + const dependency = /** @type {DllEntryDependency} */ (data.dependencies[0]); + callback(null, { + module: new DllModule( + data.context, + dependency.dependencies, + dependency.name + ) + }); } +} - getGenerator(type, generatorOptions = EMPTY_GENERATOR_OPTIONS) { - let cache = this.generatorCache.get(type); +module.exports = DllModuleFactory; - if (cache === undefined) { - cache = new WeakMap(); - this.generatorCache.set(type, cache); - } - let generator = cache.get(generatorOptions); +/***/ }), - if (generator === undefined) { - generator = this.createGenerator(type, generatorOptions); - cache.set(generatorOptions, generator); - } +/***/ 40038: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return generator; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const DllEntryPlugin = __webpack_require__(62790); +const FlagAllModulesAsUsedPlugin = __webpack_require__(58727); +const LibManifestPlugin = __webpack_require__(93837); +const createSchemaValidation = __webpack_require__(32540); + +/** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ + +const validate = createSchemaValidation( + __webpack_require__(9667), + () => __webpack_require__(99926), + { + name: "Dll Plugin", + baseDataPath: "options" } +); - createGenerator(type, generatorOptions = {}) { - generatorOptions = mergeGlobalOptions( - this._globalGeneratorOptions, - type, - generatorOptions - ); - const generator = this.hooks.createGenerator - .for(type) - .call(generatorOptions); - if (!generator) { - throw new Error(`No generator registered for ${type}`); - } - this.hooks.generator.for(type).call(generator, generatorOptions); - return generator; +class DllPlugin { + /** + * @param {DllPluginOptions} options options object + */ + constructor(options) { + validate(options); + this.options = { + ...options, + entryOnly: options.entryOnly !== false + }; } - getResolver(type, resolveOptions) { - return this.resolverFactory.get(type, resolveOptions); + /** + * 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 = NormalModuleFactory; +module.exports = DllPlugin; /***/ }), -/***/ 30633: +/***/ 90999: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -50969,112 +46020,253 @@ module.exports = NormalModuleFactory; -const { join, dirname } = __webpack_require__(17139); +const parseJson = __webpack_require__(15235); +const DelegatedModuleFactoryPlugin = __webpack_require__(51387); +const ExternalModuleFactoryPlugin = __webpack_require__(62153); +const WebpackError = __webpack_require__(53799); +const DelegatedSourceDependency = __webpack_require__(22914); +const createSchemaValidation = __webpack_require__(32540); +const makePathsRelative = (__webpack_require__(82186).makePathsRelative); -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {function(TODO): void} ModuleReplacer */ +/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ -class NormalModuleReplacementPlugin { - /** - * Create an instance of the plugin - * @param {RegExp} resourceRegExp the resource matcher - * @param {string|ModuleReplacer} newResource the resource replacement - */ - constructor(resourceRegExp, newResource) { - this.resourceRegExp = resourceRegExp; - this.newResource = newResource; +const validate = createSchemaValidation( + __webpack_require__(28534), + () => __webpack_require__(46552), + { + name: "Dll Reference Plugin", + baseDataPath: "options" } +); +class DllReferencePlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {DllReferencePluginOptions} options options object */ + constructor(options) { + validate(options); + this.options = options; + /** @type {WeakMap} */ + this._compilationData = new WeakMap(); + } + apply(compiler) { - const resourceRegExp = this.resourceRegExp; - const newResource = this.newResource; - compiler.hooks.normalModuleFactory.tap( - "NormalModuleReplacementPlugin", - nmf => { - nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => { - if (resourceRegExp.test(result.request)) { - if (typeof newResource === "function") { - newResource(result); - } else { - result.request = newResource; - } - } - }); - nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => { - const createData = result.createData; - if (resourceRegExp.test(createData.resource)) { - if (typeof newResource === "function") { - newResource(result); - } else { - const fs = compiler.inputFileSystem; - if ( - newResource.startsWith("/") || - (newResource.length > 1 && newResource[1] === ":") - ) { - createData.resource = newResource; - } else { - createData.resource = join( - fs, - dirname(fs, createData.resource), - newResource + 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); } - }); + } } ); } } -module.exports = NormalModuleReplacementPlugin; +class DllManifestError extends WebpackError { + constructor(filename, message) { + super(); + + this.name = "DllManifestError"; + this.message = `Dll manifest ${filename}\n${message}`; + } +} + +module.exports = DllReferencePlugin; /***/ }), -/***/ 80057: -/***/ (function(__unused_webpack_module, exports) { +/***/ 96475: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent + Author Naoyuki Kanezawa @nkzawa */ -exports.STAGE_BASIC = -10; -exports.STAGE_DEFAULT = 0; -exports.STAGE_ADVANCED = 10; - - -/***/ }), - -/***/ 81426: -/***/ (function(module) { +const EntryOptionPlugin = __webpack_require__(9909); +const EntryPlugin = __webpack_require__(96953); +const EntryDependency = __webpack_require__(3979); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** @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 + ); + } + ); -class OptionsApply { - process(options, compiler) {} + 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 = OptionsApply; + +module.exports = DynamicEntryPlugin; /***/ }), -/***/ 11715: +/***/ 9909: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -51085,42 +46277,96 @@ module.exports = OptionsApply; -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./NormalModule")} NormalModule */ - -/** @typedef {Record} PreparsedAst */ +/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ +/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} Entry */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ -/** - * @typedef {Object} ParserStateBase - * @property {string | Buffer} source - * @property {NormalModule} current - * @property {NormalModule} module - * @property {Compilation} compilation - * @property {{[k: string]: any}} options - */ +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; + }); + } -/** @typedef {Record & ParserStateBase} ParserState */ + /** + * @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 = __webpack_require__(96475); + new DynamicEntryPlugin(context, entry).apply(compiler); + } else { + const EntryPlugin = __webpack_require__(96953); + 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); + } + } + } + } -class Parser { - /* istanbul ignore next */ /** - * @abstract - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state + * @param {Compiler} compiler the compiler + * @param {string} name entry name + * @param {EntryDescription} desc entry description + * @returns {EntryOptions} options for the entry */ - parse(source, state) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + static entryDescriptionToOptions(compiler, name, desc) { + /** @type {EntryOptions} */ + const options = { + name, + filename: desc.filename, + runtime: desc.runtime, + layer: desc.layer, + dependOn: desc.dependOn, + publicPath: desc.publicPath, + chunkLoading: desc.chunkLoading, + asyncChunks: desc.asyncChunks, + wasmLoading: desc.wasmLoading, + library: desc.library + }; + if (desc.layer !== undefined && !compiler.options.experiments.layers) { + throw new Error( + "'entryOptions.layer' is only allowed when 'experiments.layers' is enabled" + ); + } + if (desc.chunkLoading) { + const EnableChunkLoadingPlugin = __webpack_require__(61291); + EnableChunkLoadingPlugin.checkEnabled(compiler, desc.chunkLoading); + } + if (desc.wasmLoading) { + const EnableWasmLoadingPlugin = __webpack_require__(78613); + EnableWasmLoadingPlugin.checkEnabled(compiler, desc.wasmLoading); + } + if (desc.library) { + const EnableLibraryPlugin = __webpack_require__(91452); + EnableLibraryPlugin.checkEnabled(compiler, desc.library.type); + } + return options; } } -module.exports = Parser; +module.exports = EntryOptionPlugin; /***/ }), -/***/ 73850: +/***/ 96953: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -51131,19 +46377,24 @@ module.exports = Parser; -const PrefetchDependency = __webpack_require__(31618); +const EntryDependency = __webpack_require__(3979); /** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ -class PrefetchPlugin { - constructor(context, request) { - if (request) { - this.context = context; - this.request = request; - } else { - this.context = null; - this.request = context; - } +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 || ""; } /** @@ -51153,32 +46404,44 @@ class PrefetchPlugin { */ apply(compiler) { compiler.hooks.compilation.tap( - "PrefetchPlugin", + "EntryPlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( - PrefetchDependency, + EntryDependency, normalModuleFactory ); } ); - compiler.hooks.make.tapAsync("PrefetchPlugin", (compilation, callback) => { - compilation.addModuleChain( - this.context || compiler.context, - new PrefetchDependency(this.request), - err => { - callback(err); - } - ); + + const { entry, options, context } = this; + const dep = EntryPlugin.createDependency(entry, options); + + compiler.hooks.make.tapAsync("EntryPlugin", (compilation, callback) => { + 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 = PrefetchPlugin; +module.exports = EntryPlugin; /***/ }), -/***/ 13216: +/***/ 13795: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -51189,597 +46452,177 @@ module.exports = PrefetchPlugin; -const Compiler = __webpack_require__(70845); -const MultiCompiler = __webpack_require__(33370); -const NormalModule = __webpack_require__(39); -const createSchemaValidation = __webpack_require__(32540); -const { contextify } = __webpack_require__(82186); - -/** @typedef {import("../declarations/plugins/ProgressPlugin").HandlerFunction} HandlerFunction */ -/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */ -/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */ - -const validate = createSchemaValidation( - __webpack_require__(57647), - () => __webpack_require__(75202), - { - name: "Progress Plugin", - baseDataPath: "options" - } -); -const median3 = (a, b, c) => { - return a + b + c - Math.max(a, b, c) - Math.min(a, b, c); -}; - -const createDefaultHandler = (profile, logger) => { - /** @type {{ value: string, time: number }[]} */ - const lastStateInfo = []; +const ChunkGroup = __webpack_require__(15626); - const defaultHandler = (percentage, msg, ...args) => { - if (profile) { - if (percentage === 0) { - lastStateInfo.length = 0; - } - const fullState = [msg, ...args]; - const state = fullState.map(s => s.replace(/\d+\/\d+ /g, "")); - const now = Date.now(); - const len = Math.max(state.length, lastStateInfo.length); - for (let i = len; i >= 0; i--) { - const stateItem = i < state.length ? state[i] : undefined; - const lastStateItem = - i < lastStateInfo.length ? lastStateInfo[i] : undefined; - if (lastStateItem) { - if (stateItem !== lastStateItem.value) { - const diff = now - lastStateItem.time; - if (lastStateItem.value) { - let reportState = lastStateItem.value; - if (i > 0) { - reportState = lastStateInfo[i - 1].value + " > " + reportState; - } - const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`; - const d = diff; - // This depends on timing so we ignore it for coverage - /* istanbul ignore next */ - { - if (d > 10000) { - logger.error(stateMsg); - } else if (d > 1000) { - logger.warn(stateMsg); - } else if (d > 10) { - logger.info(stateMsg); - } else if (d > 5) { - logger.log(stateMsg); - } else { - logger.debug(stateMsg); - } - } - } - if (stateItem === undefined) { - lastStateInfo.length = i; - } else { - lastStateItem.value = stateItem; - lastStateItem.time = now; - lastStateInfo.length = i + 1; - } - } - } else { - lastStateInfo[i] = { - value: stateItem, - time: now - }; - } - } - } - logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args); - if (percentage === 1 || (!msg && args.length === 0)) logger.status(); - }; +/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ +/** @typedef {import("./Chunk")} Chunk */ - return defaultHandler; -}; +/** @typedef {{ name?: string } & Omit} EntryOptions */ /** - * @callback ReportProgress - * @param {number} p - * @param {...string[]} [args] - * @returns {void} + * 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; + } -/** @type {WeakMap} */ -const progressReporters = new WeakMap(); - -class ProgressPlugin { /** - * @param {Compiler} compiler the current compiler - * @returns {ReportProgress} a progress reporter, if any + * @returns {boolean} true, when this chunk group will be loaded on initial page load */ - static getReporter(compiler) { - return progressReporters.get(compiler); + isInitial() { + return this._initial; } /** - * @param {ProgressPluginArgument} options options + * Sets the runtimeChunk for an entrypoint. + * @param {Chunk} chunk the chunk being set as the runtime chunk. + * @returns {void} */ - constructor(options = {}) { - if (typeof options === "function") { - options = { - handler: options - }; - } - - validate(options); - options = { ...ProgressPlugin.defaultOptions, ...options }; - - this.profile = options.profile; - this.handler = options.handler; - this.modulesCount = options.modulesCount; - this.dependenciesCount = options.dependenciesCount; - this.showEntries = options.entries; - this.showModules = options.modules; - this.showDependencies = options.dependencies; - this.showActiveModules = options.activeModules; - this.percentBy = options.percentBy; - } + setRuntimeChunk(chunk) { + this._runtimeChunk = chunk; + } /** - * @param {Compiler | MultiCompiler} compiler webpack compiler - * @returns {void} + * Fetches the chunk reference containing the webpack bootstrap code + * @returns {Chunk | null} returns the runtime chunk or null if there is none */ - apply(compiler) { - const handler = - this.handler || - createDefaultHandler( - this.profile, - compiler.getInfrastructureLogger("webpack.Progress") - ); - if (compiler instanceof MultiCompiler) { - this._applyOnMultiCompiler(compiler, handler); - } else if (compiler instanceof Compiler) { - this._applyOnCompiler(compiler, handler); + getRuntimeChunk() { + if (this._runtimeChunk) return this._runtimeChunk; + for (const parent of this.parentsIterable) { + if (parent instanceof Entrypoint) return parent.getRuntimeChunk(); } + return null; } /** - * @param {MultiCompiler} compiler webpack multi-compiler - * @param {HandlerFunction} handler function that executes for every progress step + * Sets the chunk with the entrypoint modules for an entrypoint. + * @param {Chunk} chunk the chunk being set as the entrypoint chunk. * @returns {void} */ - _applyOnMultiCompiler(compiler, handler) { - const states = compiler.compilers.map( - () => /** @type {[number, ...string[]]} */ ([0]) - ); - compiler.compilers.forEach((compiler, idx) => { - new ProgressPlugin((p, msg, ...args) => { - states[idx] = [p, msg, ...args]; - let sum = 0; - for (const [p] of states) sum += p; - handler(sum / states.length, `[${idx}] ${msg}`, ...args); - }).apply(compiler); - }); + setEntrypointChunk(chunk) { + this._entrypointChunk = chunk; } /** - * @param {Compiler} compiler webpack compiler - * @param {HandlerFunction} handler function that executes for every progress step - * @returns {void} + * Returns the chunk which contains the entrypoint modules + * (or at least the execution of them) + * @returns {Chunk} chunk */ - _applyOnCompiler(compiler, handler) { - const showEntries = this.showEntries; - const showModules = this.showModules; - const showDependencies = this.showDependencies; - const showActiveModules = this.showActiveModules; - let lastActiveModule = ""; - let currentLoader = ""; - let lastModulesCount = 0; - let lastDependenciesCount = 0; - let lastEntriesCount = 0; - let modulesCount = 0; - let dependenciesCount = 0; - let entriesCount = 1; - let doneModules = 0; - let doneDependencies = 0; - let doneEntries = 0; - const activeModules = new Set(); - let lastUpdate = 0; - - const updateThrottled = () => { - if (lastUpdate + 500 < Date.now()) update(); - }; - - const update = () => { - /** @type {string[]} */ - const items = []; - const percentByModules = - doneModules / - Math.max(lastModulesCount || this.modulesCount || 1, modulesCount); - const percentByEntries = - doneEntries / - Math.max(lastEntriesCount || this.dependenciesCount || 1, entriesCount); - const percentByDependencies = - doneDependencies / - Math.max(lastDependenciesCount || 1, dependenciesCount); - let percentageFactor; - - switch (this.percentBy) { - case "entries": - percentageFactor = percentByEntries; - break; - case "dependencies": - percentageFactor = percentByDependencies; - break; - case "modules": - percentageFactor = percentByModules; - break; - default: - percentageFactor = median3( - percentByModules, - percentByEntries, - percentByDependencies - ); - } - - const percentage = 0.1 + percentageFactor * 0.55; - - if (currentLoader) { - items.push( - `import loader ${contextify( - compiler.context, - currentLoader, - compiler.root - )}` - ); - } else { - const statItems = []; - if (showEntries) { - statItems.push(`${doneEntries}/${entriesCount} entries`); - } - if (showDependencies) { - statItems.push( - `${doneDependencies}/${dependenciesCount} dependencies` - ); - } - if (showModules) { - statItems.push(`${doneModules}/${modulesCount} modules`); - } - if (showActiveModules) { - statItems.push(`${activeModules.size} active`); - } - if (statItems.length > 0) { - items.push(statItems.join(" ")); - } - if (showActiveModules) { - items.push(lastActiveModule); - } - } - handler(percentage, "building", ...items); - lastUpdate = Date.now(); - }; - - const factorizeAdd = () => { - dependenciesCount++; - if (dependenciesCount < 50 || dependenciesCount % 100 === 0) - updateThrottled(); - }; + getEntrypointChunk() { + return this._entrypointChunk; + } - const factorizeDone = () => { - doneDependencies++; - if (doneDependencies < 50 || doneDependencies % 100 === 0) - updateThrottled(); - }; + /** + * @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); + } +} - const moduleAdd = () => { - modulesCount++; - if (modulesCount < 50 || modulesCount % 100 === 0) updateThrottled(); - }; +module.exports = Entrypoint; - // only used when showActiveModules is set - const moduleBuild = module => { - const ident = module.identifier(); - if (ident) { - activeModules.add(ident); - lastActiveModule = ident; - update(); - } - }; - const entryAdd = (entry, options) => { - entriesCount++; - if (entriesCount < 5 || entriesCount % 10 === 0) updateThrottled(); - }; +/***/ }), - const moduleDone = module => { - doneModules++; - if (showActiveModules) { - const ident = module.identifier(); - if (ident) { - activeModules.delete(ident); - if (lastActiveModule === ident) { - lastActiveModule = ""; - for (const m of activeModules) { - lastActiveModule = m; - } - update(); - return; - } - } - } - if (doneModules < 50 || doneModules % 100 === 0) updateThrottled(); - }; +/***/ 22070: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const entryDone = (entry, options) => { - doneEntries++; - update(); - }; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Authors Simen Brekken @simenbrekken, Einar Löve @einarlove +*/ - const cache = compiler - .getCache("ProgressPlugin") - .getItemCache("counts", null); - let cacheGetPromise; - compiler.hooks.beforeCompile.tap("ProgressPlugin", () => { - if (!cacheGetPromise) { - cacheGetPromise = cache.getPromise().then( - data => { - if (data) { - lastModulesCount = lastModulesCount || data.modulesCount; - lastDependenciesCount = - lastDependenciesCount || data.dependenciesCount; - } - return data; - }, - err => { - // Ignore error - } - ); - } - }); +const DefinePlugin = __webpack_require__(79065); +const WebpackError = __webpack_require__(53799); - compiler.hooks.afterCompile.tapPromise("ProgressPlugin", compilation => { - if (compilation.compiler.isChild()) return Promise.resolve(); - return cacheGetPromise.then(async oldData => { - if ( - !oldData || - oldData.modulesCount !== modulesCount || - oldData.dependenciesCount !== dependenciesCount - ) { - await cache.storePromise({ modulesCount, dependenciesCount }); - } - }); - }); +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./DefinePlugin").CodeValue} CodeValue */ - compiler.hooks.compilation.tap("ProgressPlugin", compilation => { - if (compilation.compiler.isChild()) return; - lastModulesCount = modulesCount; - lastEntriesCount = entriesCount; - lastDependenciesCount = dependenciesCount; - modulesCount = dependenciesCount = entriesCount = 0; - doneModules = doneDependencies = doneEntries = 0; +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 = {}; + } + } - compilation.factorizeQueue.hooks.added.tap( - "ProgressPlugin", - factorizeAdd - ); - compilation.factorizeQueue.hooks.result.tap( - "ProgressPlugin", - factorizeDone - ); + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + /** @type {Record} */ + const definitions = {}; + for (const key of this.keys) { + const value = + process.env[key] !== undefined + ? process.env[key] + : this.defaultValues[key]; - compilation.addModuleQueue.hooks.added.tap("ProgressPlugin", moduleAdd); - compilation.processDependenciesQueue.hooks.result.tap( - "ProgressPlugin", - moduleDone - ); + 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." + ); - if (showActiveModules) { - compilation.hooks.buildModule.tap("ProgressPlugin", moduleBuild); + error.name = "EnvVariableNotDefinedError"; + compilation.errors.push(error); + }); } - compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd); - compilation.hooks.failedEntry.tap("ProgressPlugin", entryDone); - compilation.hooks.succeedEntry.tap("ProgressPlugin", entryDone); - - // avoid dynamic require if bundled with webpack - // @ts-expect-error - if (false) {} + definitions[`process.env.${key}`] = + value === undefined ? "undefined" : JSON.stringify(value); + } - const hooks = { - finishModules: "finish module graph", - seal: "plugins", - optimizeDependencies: "dependencies optimization", - afterOptimizeDependencies: "after dependencies optimization", - beforeChunks: "chunk graph", - afterChunks: "after chunk graph", - optimize: "optimizing", - optimizeModules: "module optimization", - afterOptimizeModules: "after module optimization", - optimizeChunks: "chunk optimization", - afterOptimizeChunks: "after chunk optimization", - optimizeTree: "module and chunk tree optimization", - afterOptimizeTree: "after module and chunk tree optimization", - optimizeChunkModules: "chunk modules optimization", - afterOptimizeChunkModules: "after chunk modules optimization", - reviveModules: "module reviving", - beforeModuleIds: "before module ids", - moduleIds: "module ids", - optimizeModuleIds: "module id optimization", - afterOptimizeModuleIds: "module id optimization", - reviveChunks: "chunk reviving", - beforeChunkIds: "before chunk ids", - chunkIds: "chunk ids", - optimizeChunkIds: "chunk id optimization", - afterOptimizeChunkIds: "after chunk id optimization", - recordModules: "record modules", - recordChunks: "record chunks", - beforeModuleHash: "module hashing", - beforeCodeGeneration: "code generation", - beforeRuntimeRequirements: "runtime requirements", - beforeHash: "hashing", - afterHash: "after hashing", - recordHash: "record hash", - beforeModuleAssets: "module assets processing", - beforeChunkAssets: "chunk assets processing", - processAssets: "asset processing", - afterProcessAssets: "after asset optimization", - record: "recording", - afterSeal: "after seal" - }; - const numberOfHooks = Object.keys(hooks).length; - Object.keys(hooks).forEach((name, idx) => { - const title = hooks[name]; - const percentage = (idx / numberOfHooks) * 0.25 + 0.7; - compilation.hooks[name].intercept({ - name: "ProgressPlugin", - call() { - handler(percentage, "sealing", title); - }, - done() { - progressReporters.set(compiler, undefined); - handler(percentage, "sealing", title); - }, - result() { - handler(percentage, "sealing", title); - }, - error() { - handler(percentage, "sealing", title); - }, - tap(tap) { - // p is percentage from 0 to 1 - // args is any number of messages in a hierarchical matter - progressReporters.set(compilation.compiler, (p, ...args) => { - handler(percentage, "sealing", title, tap.name, ...args); - }); - handler(percentage, "sealing", title, tap.name); - } - }); - }); - }); - compiler.hooks.make.intercept({ - name: "ProgressPlugin", - call() { - handler(0.1, "building"); - }, - done() { - handler(0.65, "building"); - } - }); - const interceptHook = (hook, progress, category, name) => { - hook.intercept({ - name: "ProgressPlugin", - call() { - handler(progress, category, name); - }, - done() { - progressReporters.set(compiler, undefined); - handler(progress, category, name); - }, - result() { - handler(progress, category, name); - }, - error() { - handler(progress, category, name); - }, - tap(tap) { - progressReporters.set(compiler, (p, ...args) => { - handler(progress, category, name, tap.name, ...args); - }); - handler(progress, category, name, tap.name); - } - }); - }; - compiler.cache.hooks.endIdle.intercept({ - name: "ProgressPlugin", - call() { - handler(0, ""); - } - }); - interceptHook(compiler.cache.hooks.endIdle, 0.01, "cache", "end idle"); - compiler.hooks.initialize.intercept({ - name: "ProgressPlugin", - call() { - handler(0, ""); - } - }); - interceptHook(compiler.hooks.initialize, 0.01, "setup", "initialize"); - interceptHook(compiler.hooks.beforeRun, 0.02, "setup", "before run"); - interceptHook(compiler.hooks.run, 0.03, "setup", "run"); - interceptHook(compiler.hooks.watchRun, 0.03, "setup", "watch run"); - interceptHook( - compiler.hooks.normalModuleFactory, - 0.04, - "setup", - "normal module factory" - ); - interceptHook( - compiler.hooks.contextModuleFactory, - 0.05, - "setup", - "context module factory" - ); - interceptHook( - compiler.hooks.beforeCompile, - 0.06, - "setup", - "before compile" - ); - interceptHook(compiler.hooks.compile, 0.07, "setup", "compile"); - interceptHook(compiler.hooks.thisCompilation, 0.08, "setup", "compilation"); - interceptHook(compiler.hooks.compilation, 0.09, "setup", "compilation"); - interceptHook(compiler.hooks.finishMake, 0.69, "building", "finish"); - interceptHook(compiler.hooks.emit, 0.95, "emitting", "emit"); - interceptHook(compiler.hooks.afterEmit, 0.98, "emitting", "after emit"); - interceptHook(compiler.hooks.done, 0.99, "done", "plugins"); - compiler.hooks.done.intercept({ - name: "ProgressPlugin", - done() { - handler(0.99, ""); - } - }); - interceptHook( - compiler.cache.hooks.storeBuildDependencies, - 0.99, - "cache", - "store build dependencies" - ); - interceptHook(compiler.cache.hooks.shutdown, 0.99, "cache", "shutdown"); - interceptHook(compiler.cache.hooks.beginIdle, 0.99, "cache", "begin idle"); - interceptHook( - compiler.hooks.watchClose, - 0.99, - "end", - "closing watch compilation" - ); - compiler.cache.hooks.beginIdle.intercept({ - name: "ProgressPlugin", - done() { - handler(1, ""); - } - }); - compiler.cache.hooks.shutdown.intercept({ - name: "ProgressPlugin", - done() { - handler(1, ""); - } - }); + new DefinePlugin(definitions).apply(compiler); } } -ProgressPlugin.defaultOptions = { - profile: false, - modulesCount: 5000, - dependenciesCount: 10000, - modules: true, - dependencies: true, - activeModules: false, - entries: true -}; - -module.exports = ProgressPlugin; +module.exports = EnvironmentPlugin; /***/ }), -/***/ 38309: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 59985: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -51789,105 +46632,65 @@ module.exports = ProgressPlugin; -const ConstDependency = __webpack_require__(76911); -const ProvidedDependency = __webpack_require__(95770); -const { approve } = __webpack_require__(93998); +const loaderFlag = "LOADER_EXECUTION"; -/** @typedef {import("./Compiler")} Compiler */ +const webpackOptionsFlag = "WEBPACK_OPTIONS"; -class ProvidePlugin { - /** - * @param {Record} definitions the provided identifiers - */ - constructor(definitions) { - this.definitions = definitions; +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"); +}; - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const definitions = this.definitions; - compiler.hooks.compilation.tap( - "ProvidePlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); - compilation.dependencyFactories.set( - ProvidedDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ProvidedDependency, - new ProvidedDependency.Template() - ); - const handler = (parser, parserOptions) => { - Object.keys(definitions).forEach(name => { - const request = [].concat(definitions[name]); - const splittedName = name.split("."); - if (splittedName.length > 0) { - splittedName.slice(1).forEach((_, i) => { - const name = splittedName.slice(0, i + 1).join("."); - parser.hooks.canRename.for(name).tap("ProvidePlugin", approve); - }); - } +exports.cutOffLoaderExecution = stack => + exports.cutOffByFlag(stack, loaderFlag); - parser.hooks.expression.for(name).tap("ProvidePlugin", expr => { - const nameIdentifier = name.includes(".") - ? `__webpack_provided_${name.replace(/\./g, "_dot_")}` - : name; - const dep = new ProvidedDependency( - request[0], - nameIdentifier, - request.slice(1), - expr.range - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return true; - }); +exports.cutOffWebpackOptions = stack => + exports.cutOffByFlag(stack, webpackOptionsFlag); - parser.hooks.call.for(name).tap("ProvidePlugin", expr => { - const nameIdentifier = name.includes(".") - ? `__webpack_provided_${name.replace(/\./g, "_dot_")}` - : name; - const dep = new ProvidedDependency( - request[0], - nameIdentifier, - request.slice(1), - expr.callee.range - ); - dep.loc = expr.callee.loc; - parser.state.module.addDependency(dep); - parser.walkExpressions(expr.arguments); - return true; - }); - }); - }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("ProvidePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("ProvidePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("ProvidePlugin", handler); - } - ); +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; } -} +}; -module.exports = ProvidePlugin; +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; +}; /***/ }), -/***/ 84929: +/***/ 65218: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -51898,156 +46701,121 @@ module.exports = ProvidePlugin; -const { OriginalSource, RawSource } = __webpack_require__(51255); -const Module = __webpack_require__(73208); -const makeSerializable = __webpack_require__(33032); +const { ConcatSource, RawSource } = __webpack_require__(51255); +const ExternalModule = __webpack_require__(73071); +const ModuleFilenameHelpers = __webpack_require__(88821); +const RuntimeGlobals = __webpack_require__(16475); +const JavascriptModulesPlugin = __webpack_require__(89464); /** @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("./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"]); - -class RawModule extends Module { - /** - * @param {string} source source code - * @param {string} identifier unique identifier - * @param {string=} readableIdentifier readable identifier - * @param {ReadonlySet=} runtimeRequirements runtime requirements needed for the source code - */ - constructor(source, identifier, readableIdentifier, runtimeRequirements) { - super("javascript/dynamic", null); - this.sourceStr = source; - this.identifierStr = identifier || this.sourceStr; - this.readableIdentifierStr = readableIdentifier || this.identifierStr; - this.runtimeRequirements = runtimeRequirements || null; - } - - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; - } - - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return this.identifierStr; - } +/** @typedef {import("./Compiler")} Compiler */ - /** - * @param {string=} type the source type for which the size should be estimated - * @returns {number} the estimated size of the module (must be non-zero) - */ - size(type) { - return Math.max(1, this.sourceStr.length); - } +/** @type {WeakMap} */ +const cache = new WeakMap(); - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return requestShortener.shorten(this.readableIdentifierStr); - } +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/). + */ +`); - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - return callback(null, !this.buildMeta); +class EvalDevToolModulePlugin { + constructor(options) { + this.namespace = options.namespace || ""; + this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]"; + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || + "webpack://[namespace]/[resourcePath]?[loaders]"; } /** - * @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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - build(options, compilation, resolver, fs, callback) { - this.buildMeta = {}; - this.buildInfo = { - cacheable: true - }; - callback(); - } - - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration(context) { - const sources = new Map(); - if (this.useSourceMap || this.useSimpleSourceMap) { - sources.set( - "javascript", - new OriginalSource(this.sourceStr, this.identifier()) + apply(compiler) { + compiler.hooks.compilation.tap("EvalDevToolModulePlugin", compilation => { + const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); + hooks.renderModuleContent.tap( + "EvalDevToolModulePlugin", + (source, module, { runtimeTemplate, chunkGraph }) => { + const cacheEntry = cache.get(source); + if (cacheEntry !== undefined) return cacheEntry; + if (module instanceof ExternalModule) { + cache.set(source, source); + return source; + } + const content = source.source(); + const str = ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: this.moduleFilenameTemplate, + namespace: this.namespace + }, + { + requestShortener: runtimeTemplate.requestShortener, + chunkGraph, + hashFunction: compilation.outputOptions.hashFunction + } + ); + const footer = + "\n" + + this.sourceUrlComment.replace( + /\[url\]/g, + encodeURI(str) + .replace(/%2F/g, "/") + .replace(/%20/g, "_") + .replace(/%5E/g, "^") + .replace(/%5C/g, "\\") + .replace(/^\//, "") + ); + const result = new RawSource( + `eval(${ + compilation.outputOptions.trustedTypes + ? `${RuntimeGlobals.createScript}(${JSON.stringify( + content + footer + )})` + : JSON.stringify(content + footer) + });` + ); + cache.set(source, result); + return result; + } ); - } else { - sources.set("javascript", new RawSource(this.sourceStr)); - } - return { sources, runtimeRequirements: this.runtimeRequirements }; - } - - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - hash.update(this.sourceStr); - super.updateHash(hash, context); - } - - serialize(context) { - const { write } = context; - - write(this.sourceStr); - write(this.identifierStr); - write(this.readableIdentifierStr); - write(this.runtimeRequirements); - - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - - this.sourceStr = read(); - this.identifierStr = read(); - this.readableIdentifierStr = read(); - this.runtimeRequirements = read(); - - super.deserialize(context); + hooks.inlineInRuntimeBailout.tap( + "EvalDevToolModulePlugin", + () => "the eval devtool is used." + ); + hooks.render.tap( + "EvalDevToolModulePlugin", + source => new ConcatSource(devtoolWarning, source) + ); + hooks.chunkHash.tap("EvalDevToolModulePlugin", (chunk, hash) => { + hash.update("EvalDevToolModulePlugin"); + hash.update("2"); + }); + if (compilation.outputOptions.trustedTypes) { + compilation.hooks.additionalModuleRuntimeRequirements.tap( + "EvalDevToolModulePlugin", + (module, set, context) => { + set.add(RuntimeGlobals.createScript); + } + ); + } + }); } } -makeSerializable(RawModule, "webpack/lib/RawModule"); - -module.exports = RawModule; +module.exports = EvalDevToolModulePlugin; /***/ }), -/***/ 11094: +/***/ 14790: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -52058,242 +46826,210 @@ module.exports = RawModule; -const { compareNumbers } = __webpack_require__(29579); -const identifierUtils = __webpack_require__(82186); +const { ConcatSource, RawSource } = __webpack_require__(51255); +const ModuleFilenameHelpers = __webpack_require__(88821); +const NormalModule = __webpack_require__(39); +const RuntimeGlobals = __webpack_require__(16475); +const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(97513); +const JavascriptModulesPlugin = __webpack_require__(89464); +const ConcatenatedModule = __webpack_require__(97198); +const { makePathsAbsolute } = __webpack_require__(82186); -/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").DevTool} DevToolOptions */ +/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ /** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Module")} Module */ - -/** - * @typedef {Object} RecordsChunks - * @property {Record=} byName - * @property {Record=} bySource - * @property {number[]=} usedIds - */ -/** - * @typedef {Object} RecordsModules - * @property {Record=} byIdentifier - * @property {Record=} bySource - * @property {number[]=} usedIds - */ +/** @type {WeakMap} */ +const cache = new WeakMap(); -/** - * @typedef {Object} Records - * @property {RecordsChunks=} chunks - * @property {RecordsModules=} modules +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 RecordIdsPlugin { +class EvalSourceMapDevToolPlugin { /** - * @param {Object} options Options object - * @param {boolean=} options.portableIds true, when ids need to be portable + * @param {SourceMapDevToolPluginOptions|string} inputOptions Options object */ - constructor(options) { - this.options = options || {}; + 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; } /** - * @param {Compiler} compiler the Compiler + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - const portableIds = this.options.portableIds; + 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 makePathsRelative = - identifierUtils.makePathsRelative.bindContextCache( - compiler.context, - compiler.root - ); + const result = r => { + cache.set(source, r); + return r; + }; - /** - * @param {Module} module the module - * @returns {string} the (portable) identifier - */ - const getModuleIdentifier = module => { - if (portableIds) { - return makePathsRelative(module.identifier()); - } - return module.identifier(); - }; + 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); + } - compiler.hooks.compilation.tap("RecordIdsPlugin", compilation => { - compilation.hooks.recordModules.tap( - "RecordIdsPlugin", - /** - * @param {Module[]} modules the modules array - * @param {Records} records the records object - * @returns {void} - */ - (modules, records) => { - const chunkGraph = compilation.chunkGraph; - if (!records.modules) records.modules = {}; - if (!records.modules.byIdentifier) records.modules.byIdentifier = {}; - /** @type {Set} */ - const usedIds = new Set(); - for (const module of modules) { - const moduleId = chunkGraph.getModuleId(module); - if (typeof moduleId !== "number") continue; - const identifier = getModuleIdentifier(module); - records.modules.byIdentifier[identifier] = moduleId; - usedIds.add(moduleId); - } - records.modules.usedIds = Array.from(usedIds).sort(compareNumbers); - } - ); - compilation.hooks.reviveModules.tap( - "RecordIdsPlugin", - /** - * @param {Module[]} modules the modules array - * @param {Records} records the records object - * @returns {void} - */ - (modules, records) => { - if (!records.modules) return; - if (records.modules.byIdentifier) { - const chunkGraph = compilation.chunkGraph; - /** @type {Set} */ - const usedIds = new Set(); - for (const module of modules) { - const moduleId = chunkGraph.getModuleId(module); - if (moduleId !== null) continue; - const identifier = getModuleIdentifier(module); - const id = records.modules.byIdentifier[identifier]; - if (id === undefined) continue; - if (usedIds.has(id)) continue; - usedIds.add(id); - chunkGraph.setModuleId(module, id); + /** @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); } - } - if (Array.isArray(records.modules.usedIds)) { - compilation.usedModuleIds = new Set(records.modules.usedIds); - } - } - ); - /** - * @param {Chunk} chunk the chunk - * @returns {string[]} sources of the chunk - */ - const getChunkSources = chunk => { - /** @type {string[]} */ - const sources = []; - for (const chunkGroup of chunk.groupsIterable) { - const index = chunkGroup.chunks.indexOf(chunk); - if (chunkGroup.name) { - sources.push(`${index} ${chunkGroup.name}`); - } else { - for (const origin of chunkGroup.origins) { - if (origin.module) { - if (origin.request) { - sources.push( - `${index} ${getModuleIdentifier(origin.module)} ${ - origin.request - }` - ); - } else if (typeof origin.loc === "string") { - sources.push( - `${index} ${getModuleIdentifier(origin.module)} ${ - origin.loc - }` - ); - } else if ( - origin.loc && - typeof origin.loc === "object" && - "start" in origin.loc - ) { - sources.push( - `${index} ${getModuleIdentifier( - origin.module - )} ${JSON.stringify(origin.loc.start)}` - ); + // 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 = makePathsAbsolute(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, + hashFunction: compilation.outputOptions.hashFunction } + ); + }); + moduleFilenames = ModuleFilenameHelpers.replaceDuplicates( + moduleFilenames, + (filename, i, n) => { + for (let j = 0; j < n; j++) filename += "*"; + return filename; } - } - } - } - return sources; - }; + ); + sourceMap.sources = moduleFilenames; + sourceMap.sourceRoot = options.sourceRoot || ""; + const moduleId = chunkGraph.getModuleId(m); + sourceMap.file = `${moduleId}.js`; - compilation.hooks.recordChunks.tap( - "RecordIdsPlugin", - /** - * @param {Chunk[]} chunks the chunks array - * @param {Records} records the records object - * @returns {void} - */ - (chunks, records) => { - if (!records.chunks) records.chunks = {}; - if (!records.chunks.byName) records.chunks.byName = {}; - if (!records.chunks.bySource) records.chunks.bySource = {}; - /** @type {Set} */ - const usedIds = new Set(); - for (const chunk of chunks) { - if (typeof chunk.id !== "number") continue; - const name = chunk.name; - if (name) records.chunks.byName[name] = chunk.id; - const sources = getChunkSources(chunk); - for (const source of sources) { - records.chunks.bySource[source] = chunk.id; - } - usedIds.add(chunk.id); - } - records.chunks.usedIds = Array.from(usedIds).sort(compareNumbers); - } - ); - compilation.hooks.reviveChunks.tap( - "RecordIdsPlugin", - /** - * @param {Chunk[]} chunks the chunks array - * @param {Records} records the records object - * @returns {void} - */ - (chunks, records) => { - if (!records.chunks) return; - /** @type {Set} */ - const usedIds = new Set(); - if (records.chunks.byName) { - for (const chunk of chunks) { - if (chunk.id !== null) continue; - if (!chunk.name) continue; - const id = records.chunks.byName[chunk.name]; - if (id === undefined) continue; - if (usedIds.has(id)) continue; - usedIds.add(id); - chunk.id = id; - chunk.ids = [id]; - } + const footer = + this.sourceMapComment.replace( + /\[url\]/g, + `data:application/json;charset=utf-8;base64,${Buffer.from( + JSON.stringify(sourceMap), + "utf8" + ).toString("base64")}` + ) + `\n//# sourceURL=webpack-internal:///${moduleId}\n`; // workaround for chrome bug + + return result( + new RawSource( + `eval(${ + compilation.outputOptions.trustedTypes + ? `${RuntimeGlobals.createScript}(${JSON.stringify( + content + footer + )})` + : JSON.stringify(content + footer) + });` + ) + ); } - if (records.chunks.bySource) { - for (const chunk of chunks) { - if (chunk.id !== null) continue; - const sources = getChunkSources(chunk); - for (const source of sources) { - const id = records.chunks.bySource[source]; - if (id === undefined) continue; - if (usedIds.has(id)) continue; - usedIds.add(id); - chunk.id = id; - chunk.ids = [id]; - break; - } + ); + hooks.inlineInRuntimeBailout.tap( + "EvalDevToolModulePlugin", + () => "the eval-source-map devtool is used." + ); + hooks.render.tap( + "EvalSourceMapDevToolPlugin", + source => new ConcatSource(devtoolWarning, source) + ); + hooks.chunkHash.tap("EvalSourceMapDevToolPlugin", (chunk, hash) => { + hash.update("EvalSourceMapDevToolPlugin"); + hash.update("2"); + }); + if (compilation.outputOptions.trustedTypes) { + compilation.hooks.additionalModuleRuntimeRequirements.tap( + "EvalSourceMapDevToolPlugin", + (module, set, context) => { + set.add(RuntimeGlobals.createScript); } - } - if (Array.isArray(records.chunks.usedIds)) { - compilation.usedChunkIds = new Set(records.chunks.usedIds); - } + ); } - ); - }); + } + ); } } -module.exports = RecordIdsPlugin; + +module.exports = EvalSourceMapDevToolPlugin; /***/ }), -/***/ 73406: +/***/ 63686: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -52304,892 +47040,1527 @@ module.exports = RecordIdsPlugin; -const { contextify } = __webpack_require__(82186); - -class RequestShortener { - /** - * @param {string} dir the directory - * @param {object=} associatedObjectForCache an object to which the cache will be attached - */ - constructor(dir, associatedObjectForCache) { - this.contextify = contextify.bindContextCache( - dir, - associatedObjectForCache - ); - } +const { equals } = __webpack_require__(84953); +const SortableSet = __webpack_require__(13098); +const makeSerializable = __webpack_require__(33032); +const { forEachRuntime } = __webpack_require__(17156); - /** - * @param {string | undefined | null} request the request to shorten - * @returns {string | undefined | null} the shortened request - */ - shorten(request) { - if (!request) { - return request; - } - return this.contextify(request); - } -} +/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("./util/Hash")} Hash */ -module.exports = RequestShortener; +/** @typedef {typeof UsageState.OnlyPropertiesUsed | typeof UsageState.NoInfo | typeof UsageState.Unknown | typeof UsageState.Used} RuntimeUsageStateType */ +/** @typedef {typeof UsageState.Unused | RuntimeUsageStateType} UsageStateType */ +const UsageState = Object.freeze({ + Unused: /** @type {0} */ (0), + OnlyPropertiesUsed: /** @type {1} */ (1), + NoInfo: /** @type {2} */ (2), + Unknown: /** @type {3} */ (3), + Used: /** @type {4} */ (4) +}); -/***/ }), +const RETURNS_TRUE = () => true; -/***/ 88846: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const CIRCULAR = Symbol("circular target"); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +class RestoreProvidedData { + constructor( + exports, + otherProvided, + otherCanMangleProvide, + otherTerminalBinding + ) { + this.exports = exports; + this.otherProvided = otherProvided; + this.otherCanMangleProvide = otherCanMangleProvide; + this.otherTerminalBinding = otherTerminalBinding; + } + serialize({ write }) { + write(this.exports); + write(this.otherProvided); + write(this.otherCanMangleProvide); + write(this.otherTerminalBinding); + } + static deserialize({ read }) { + return new RestoreProvidedData(read(), read(), read(), read()); + } +} -const RuntimeGlobals = __webpack_require__(16475); -const ConstDependency = __webpack_require__(76911); -const { - toConstantDependency -} = __webpack_require__(93998); +makeSerializable( + RestoreProvidedData, + "webpack/lib/ModuleGraph", + "RestoreProvidedData" +); -/** @typedef {import("./Compiler")} Compiler */ +class ExportsInfo { + constructor() { + /** @type {Map} */ + this._exports = new Map(); + this._otherExportsInfo = new ExportInfo(null); + this._sideEffectsOnlyInfo = new ExportInfo("*side effects only*"); + this._exportsAreOrdered = false; + /** @type {ExportsInfo=} */ + this._redirectTo = undefined; + } -module.exports = class RequireJsStuffPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @returns {Iterable} all owned exports in any order */ - apply(compiler) { - compiler.hooks.compilation.tap( - "RequireJsStuffPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); - const handler = (parser, parserOptions) => { - if ( - parserOptions.requireJs === undefined || - !parserOptions.requireJs - ) { - return; - } + get ownedExports() { + return this._exports.values(); + } - parser.hooks.call - .for("require.config") - .tap( - "RequireJsStuffPlugin", - toConstantDependency(parser, "undefined") - ); - parser.hooks.call - .for("requirejs.config") - .tap( - "RequireJsStuffPlugin", - toConstantDependency(parser, "undefined") - ); + /** + * @returns {Iterable} all owned exports in order + */ + get orderedOwnedExports() { + if (!this._exportsAreOrdered) { + this._sortExports(); + } + return this._exports.values(); + } - parser.hooks.expression - .for("require.version") - .tap( - "RequireJsStuffPlugin", - toConstantDependency(parser, JSON.stringify("0.0.0")) - ); - parser.hooks.expression - .for("requirejs.onError") - .tap( - "RequireJsStuffPlugin", - toConstantDependency( - parser, - RuntimeGlobals.uncaughtErrorHandler, - [RuntimeGlobals.uncaughtErrorHandler] - ) - ); - }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireJsStuffPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireJsStuffPlugin", handler); + /** + * @returns {Iterable} all exports in any order + */ + get exports() { + if (this._redirectTo !== undefined) { + const map = new Map(this._redirectTo._exports); + for (const [key, value] of this._exports) { + map.set(key, value); } - ); + return map.values(); + } + return this._exports.values(); } -}; - - -/***/ }), - -/***/ 30217: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + /** + * @returns {Iterable} all exports in order + */ + get orderedExports() { + if (!this._exportsAreOrdered) { + this._sortExports(); + } + if (this._redirectTo !== undefined) { + const map = new Map( + Array.from(this._redirectTo.orderedExports, item => [item.name, item]) + ); + for (const [key, value] of this._exports) { + map.set(key, value); + } + // sorting should be pretty fast as map contains + // a lot of presorted items + this._sortExportsMap(map); + return map.values(); + } + return this._exports.values(); + } -const Factory = (__webpack_require__(9256).ResolverFactory); -const { HookMap, SyncHook, SyncWaterfallHook } = __webpack_require__(6967); -const { - cachedCleverMerge, - removeOperations, - resolveByProperty -} = __webpack_require__(60839); + /** + * @returns {ExportInfo} the export info of unlisted exports + */ + get otherExportsInfo() { + if (this._redirectTo !== undefined) + return this._redirectTo.otherExportsInfo; + return this._otherExportsInfo; + } -/** @typedef {import("enhanced-resolve").ResolveOptions} ResolveOptions */ -/** @typedef {import("enhanced-resolve").Resolver} Resolver */ -/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */ -/** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */ + _sortExportsMap(exports) { + if (exports.size > 1) { + const namesInOrder = []; + for (const entry of exports.values()) { + namesInOrder.push(entry.name); + } + namesInOrder.sort(); + let i = 0; + for (const entry of exports.values()) { + const name = namesInOrder[i]; + if (entry.name !== name) break; + i++; + } + for (; i < namesInOrder.length; i++) { + const name = namesInOrder[i]; + const correctEntry = exports.get(name); + exports.delete(name); + exports.set(name, correctEntry); + } + } + } -/** @typedef {WebpackResolveOptions & {dependencyType?: string, resolveToContext?: boolean }} ResolveOptionsWithDependencyType */ -/** - * @typedef {Object} WithOptions - * @property {function(Partial): ResolverWithOptions} withOptions create a resolver with additional/different options - */ + _sortExports() { + this._sortExportsMap(this._exports); + this._exportsAreOrdered = true; + } -/** @typedef {Resolver & WithOptions} ResolverWithOptions */ + setRedirectNamedTo(exportsInfo) { + if (this._redirectTo === exportsInfo) return false; + this._redirectTo = exportsInfo; + return true; + } -// need to be hoisted on module level for caching identity -const EMPTY_RESOLVE_OPTIONS = {}; + setHasProvideInfo() { + for (const exportInfo of this._exports.values()) { + if (exportInfo.provided === undefined) { + exportInfo.provided = false; + } + if (exportInfo.canMangleProvide === undefined) { + exportInfo.canMangleProvide = true; + } + } + if (this._redirectTo !== undefined) { + this._redirectTo.setHasProvideInfo(); + } else { + if (this._otherExportsInfo.provided === undefined) { + this._otherExportsInfo.provided = false; + } + if (this._otherExportsInfo.canMangleProvide === undefined) { + this._otherExportsInfo.canMangleProvide = true; + } + } + } -/** - * @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType enhanced options - * @returns {ResolveOptions} merged options - */ -const convertToResolveOptions = resolveOptionsWithDepType => { - const { dependencyType, plugins, ...remaining } = resolveOptionsWithDepType; + setHasUseInfo() { + for (const exportInfo of this._exports.values()) { + exportInfo.setHasUseInfo(); + } + this._sideEffectsOnlyInfo.setHasUseInfo(); + if (this._redirectTo !== undefined) { + this._redirectTo.setHasUseInfo(); + } else { + this._otherExportsInfo.setHasUseInfo(); + if (this._otherExportsInfo.canMangleUse === undefined) { + this._otherExportsInfo.canMangleUse = true; + } + } + } - // check type compat - /** @type {Partial} */ - const partialOptions = { - ...remaining, - plugins: - plugins && - /** @type {ResolvePluginInstance[]} */ ( - plugins.filter(item => item !== "...") - ) - }; + /** + * @param {string} name export name + * @returns {ExportInfo} export info for this name + */ + getOwnExportInfo(name) { + const info = this._exports.get(name); + if (info !== undefined) return info; + const newInfo = new ExportInfo(name, this._otherExportsInfo); + this._exports.set(name, newInfo); + this._exportsAreOrdered = false; + return newInfo; + } - if (!partialOptions.fileSystem) { - throw new Error( - "fileSystem is missing in resolveOptions, but it's required for enhanced-resolve" - ); + /** + * @param {string} name export name + * @returns {ExportInfo} export info for this name + */ + getExportInfo(name) { + const info = this._exports.get(name); + if (info !== undefined) return info; + if (this._redirectTo !== undefined) + return this._redirectTo.getExportInfo(name); + const newInfo = new ExportInfo(name, this._otherExportsInfo); + this._exports.set(name, newInfo); + this._exportsAreOrdered = false; + return newInfo; } - // These weird types validate that we checked all non-optional properties - const options = - /** @type {Partial & Pick} */ ( - partialOptions - ); - return removeOperations( - resolveByProperty(options, "byDependency", dependencyType) - ); -}; + /** + * @param {string} name export name + * @returns {ExportInfo} export info for this name + */ + getReadOnlyExportInfo(name) { + const info = this._exports.get(name); + if (info !== undefined) return info; + if (this._redirectTo !== undefined) + return this._redirectTo.getReadOnlyExportInfo(name); + return this._otherExportsInfo; + } -/** - * @typedef {Object} ResolverCache - * @property {WeakMap} direct - * @property {Map} stringified - */ + /** + * @param {string[]} name export name + * @returns {ExportInfo | undefined} export info for this name + */ + getReadOnlyExportInfoRecursive(name) { + const exportInfo = this.getReadOnlyExportInfo(name[0]); + if (name.length === 1) return exportInfo; + if (!exportInfo.exportsInfo) return undefined; + return exportInfo.exportsInfo.getReadOnlyExportInfoRecursive(name.slice(1)); + } -module.exports = class ResolverFactory { - constructor() { - this.hooks = Object.freeze({ - /** @type {HookMap>} */ - resolveOptions: new HookMap( - () => new SyncWaterfallHook(["resolveOptions"]) - ), - /** @type {HookMap>} */ - resolver: new HookMap( - () => new SyncHook(["resolver", "resolveOptions", "userResolveOptions"]) - ) - }); - /** @type {Map} */ - this.cache = new Map(); + /** + * @param {string[]=} name the export name + * @returns {ExportsInfo | undefined} the nested exports info + */ + getNestedExportsInfo(name) { + if (Array.isArray(name) && name.length > 0) { + const info = this.getReadOnlyExportInfo(name[0]); + if (!info.exportsInfo) return undefined; + return info.exportsInfo.getNestedExportsInfo(name.slice(1)); + } + return this; } /** - * @param {string} type type of resolver - * @param {ResolveOptionsWithDependencyType=} resolveOptions options - * @returns {ResolverWithOptions} the resolver + * @param {boolean=} canMangle true, if exports can still be mangled (defaults to false) + * @param {Set=} excludeExports list of unaffected exports + * @param {any=} targetKey use this as key for the target + * @param {ModuleGraphConnection=} targetModule set this module as target + * @param {number=} priority priority + * @returns {boolean} true, if this call changed something */ - get(type, resolveOptions = EMPTY_RESOLVE_OPTIONS) { - let typedCaches = this.cache.get(type); - if (!typedCaches) { - typedCaches = { - direct: new WeakMap(), - stringified: new Map() - }; - this.cache.set(type, typedCaches); + setUnknownExportsProvided( + canMangle, + excludeExports, + targetKey, + targetModule, + priority + ) { + let changed = false; + if (excludeExports) { + for (const name of excludeExports) { + // Make sure these entries exist, so they can get different info + this.getExportInfo(name); + } } - const cachedResolver = typedCaches.direct.get(resolveOptions); - if (cachedResolver) { - return cachedResolver; + for (const exportInfo of this._exports.values()) { + if (excludeExports && excludeExports.has(exportInfo.name)) continue; + if (exportInfo.provided !== true && exportInfo.provided !== null) { + exportInfo.provided = null; + changed = true; + } + if (!canMangle && exportInfo.canMangleProvide !== false) { + exportInfo.canMangleProvide = false; + changed = true; + } + if (targetKey) { + exportInfo.setTarget(targetKey, targetModule, [exportInfo.name], -1); + } } - const ident = JSON.stringify(resolveOptions); - const resolver = typedCaches.stringified.get(ident); - if (resolver) { - typedCaches.direct.set(resolveOptions, resolver); - return resolver; + if (this._redirectTo !== undefined) { + if ( + this._redirectTo.setUnknownExportsProvided( + canMangle, + excludeExports, + targetKey, + targetModule, + priority + ) + ) { + changed = true; + } + } else { + if ( + this._otherExportsInfo.provided !== true && + this._otherExportsInfo.provided !== null + ) { + this._otherExportsInfo.provided = null; + changed = true; + } + if (!canMangle && this._otherExportsInfo.canMangleProvide !== false) { + this._otherExportsInfo.canMangleProvide = false; + changed = true; + } + if (targetKey) { + this._otherExportsInfo.setTarget( + targetKey, + targetModule, + undefined, + priority + ); + } } - const newResolver = this._create(type, resolveOptions); - typedCaches.direct.set(resolveOptions, newResolver); - typedCaches.stringified.set(ident, newResolver); - return newResolver; + return changed; } /** - * @param {string} type type of resolver - * @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType options - * @returns {ResolverWithOptions} the resolver + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when something changed */ - _create(type, resolveOptionsWithDepType) { - /** @type {ResolveOptionsWithDependencyType} */ - const originalResolveOptions = { ...resolveOptionsWithDepType }; - - const resolveOptions = convertToResolveOptions( - this.hooks.resolveOptions.for(type).call(resolveOptionsWithDepType) - ); - const resolver = /** @type {ResolverWithOptions} */ ( - Factory.createResolver(resolveOptions) - ); - if (!resolver) { - throw new Error("No resolver created"); + setUsedInUnknownWay(runtime) { + let changed = false; + for (const exportInfo of this._exports.values()) { + if (exportInfo.setUsedInUnknownWay(runtime)) { + changed = true; + } } - /** @type {WeakMap, ResolverWithOptions>} */ - const childCache = new WeakMap(); - resolver.withOptions = options => { - const cacheEntry = childCache.get(options); - if (cacheEntry !== undefined) return cacheEntry; - const mergedOptions = cachedCleverMerge(originalResolveOptions, options); - const resolver = this.get(type, mergedOptions); - childCache.set(options, resolver); - return resolver; - }; - this.hooks.resolver - .for(type) - .call(resolver, resolveOptions, originalResolveOptions); - return resolver; + if (this._redirectTo !== undefined) { + if (this._redirectTo.setUsedInUnknownWay(runtime)) { + changed = true; + } + } else { + if ( + this._otherExportsInfo.setUsedConditionally( + used => used < UsageState.Unknown, + UsageState.Unknown, + runtime + ) + ) { + changed = true; + } + if (this._otherExportsInfo.canMangleUse !== false) { + this._otherExportsInfo.canMangleUse = false; + changed = true; + } + } + return changed; } -}; + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when something changed + */ + setUsedWithoutInfo(runtime) { + let changed = false; + for (const exportInfo of this._exports.values()) { + if (exportInfo.setUsedWithoutInfo(runtime)) { + changed = true; + } + } + if (this._redirectTo !== undefined) { + if (this._redirectTo.setUsedWithoutInfo(runtime)) { + changed = true; + } + } else { + if (this._otherExportsInfo.setUsed(UsageState.NoInfo, runtime)) { + changed = true; + } + if (this._otherExportsInfo.canMangleUse !== false) { + this._otherExportsInfo.canMangleUse = false; + changed = true; + } + } + return changed; + } -/***/ }), - -/***/ 16475: -/***/ (function(__unused_webpack_module, exports) { + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when something changed + */ + setAllKnownExportsUsed(runtime) { + let changed = false; + for (const exportInfo of this._exports.values()) { + if (!exportInfo.provided) continue; + if (exportInfo.setUsed(UsageState.Used, runtime)) { + changed = true; + } + } + return changed; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when something changed + */ + setUsedForSideEffectsOnly(runtime) { + return this._sideEffectsOnlyInfo.setUsedConditionally( + used => used === UsageState.Unused, + UsageState.Used, + runtime + ); + } + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when the module exports are used in any way + */ + isUsed(runtime) { + if (this._redirectTo !== undefined) { + if (this._redirectTo.isUsed(runtime)) { + return true; + } + } else { + if (this._otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { + return true; + } + } + for (const exportInfo of this._exports.values()) { + if (exportInfo.getUsed(runtime) !== UsageState.Unused) { + return true; + } + } + return false; + } + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when the module is used in any way + */ + isModuleUsed(runtime) { + if (this.isUsed(runtime)) return true; + if (this._sideEffectsOnlyInfo.getUsed(runtime) !== UsageState.Unused) + return true; + return false; + } -/** - * the internal require function - */ -exports.require = "__webpack_require__"; + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {SortableSet | boolean | null} set of used exports, or true (when namespace object is used), or false (when unused), or null (when unknown) + */ + getUsedExports(runtime) { + if (!this._redirectTo !== undefined) { + switch (this._otherExportsInfo.getUsed(runtime)) { + case UsageState.NoInfo: + return null; + case UsageState.Unknown: + case UsageState.OnlyPropertiesUsed: + case UsageState.Used: + return true; + } + } + const array = []; + if (!this._exportsAreOrdered) this._sortExports(); + for (const exportInfo of this._exports.values()) { + switch (exportInfo.getUsed(runtime)) { + case UsageState.NoInfo: + return null; + case UsageState.Unknown: + return true; + case UsageState.OnlyPropertiesUsed: + case UsageState.Used: + array.push(exportInfo.name); + } + } + if (this._redirectTo !== undefined) { + const inner = this._redirectTo.getUsedExports(runtime); + if (inner === null) return null; + if (inner === true) return true; + if (inner !== false) { + for (const item of inner) { + array.push(item); + } + } + } + if (array.length === 0) { + switch (this._sideEffectsOnlyInfo.getUsed(runtime)) { + case UsageState.NoInfo: + return null; + case UsageState.Unused: + return false; + } + } + return new SortableSet(array); + } -/** - * access to properties of the internal require function/object - */ -exports.requireScope = "__webpack_require__.*"; + /** + * @returns {null | true | string[]} list of exports when known + */ + getProvidedExports() { + if (!this._redirectTo !== undefined) { + switch (this._otherExportsInfo.provided) { + case undefined: + return null; + case null: + return true; + case true: + return true; + } + } + const array = []; + if (!this._exportsAreOrdered) this._sortExports(); + for (const exportInfo of this._exports.values()) { + switch (exportInfo.provided) { + case undefined: + return null; + case null: + return true; + case true: + array.push(exportInfo.name); + } + } + if (this._redirectTo !== undefined) { + const inner = this._redirectTo.getProvidedExports(); + if (inner === null) return null; + if (inner === true) return true; + for (const item of inner) { + if (!array.includes(item)) { + array.push(item); + } + } + } + return array; + } -/** - * the internal exports object - */ -exports.exports = "__webpack_exports__"; + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {ExportInfo[]} exports that are relevant (not unused and potential provided) + */ + getRelevantExports(runtime) { + const list = []; + for (const exportInfo of this._exports.values()) { + const used = exportInfo.getUsed(runtime); + if (used === UsageState.Unused) continue; + if (exportInfo.provided === false) continue; + list.push(exportInfo); + } + if (this._redirectTo !== undefined) { + for (const exportInfo of this._redirectTo.getRelevantExports(runtime)) { + if (!this._exports.has(exportInfo.name)) list.push(exportInfo); + } + } + if ( + this._otherExportsInfo.provided !== false && + this._otherExportsInfo.getUsed(runtime) !== UsageState.Unused + ) { + list.push(this._otherExportsInfo); + } + return list; + } -/** - * top-level this need to be the exports object - */ -exports.thisAsExports = "top-level-this-exports"; + /** + * @param {string | string[]} name the name of the export + * @returns {boolean | undefined | null} if the export is provided + */ + isExportProvided(name) { + if (Array.isArray(name)) { + const info = this.getReadOnlyExportInfo(name[0]); + if (info.exportsInfo && name.length > 1) { + return info.exportsInfo.isExportProvided(name.slice(1)); + } + return info.provided; + } + const info = this.getReadOnlyExportInfo(name); + return info.provided; + } -/** - * runtime need to return the exports of the last entry module - */ -exports.returnExportsFromRuntime = "return-exports-from-runtime"; - -/** - * the internal module object - */ -exports.module = "module"; - -/** - * the internal module object - */ -exports.moduleId = "module.id"; - -/** - * the internal module object - */ -exports.moduleLoaded = "module.loaded"; - -/** - * the bundle public path - */ -exports.publicPath = "__webpack_require__.p"; - -/** - * the module id of the entry point - */ -exports.entryModuleId = "__webpack_require__.s"; - -/** - * the module cache - */ -exports.moduleCache = "__webpack_require__.c"; - -/** - * the module functions - */ -exports.moduleFactories = "__webpack_require__.m"; - -/** - * the module functions, with only write access - */ -exports.moduleFactoriesAddOnly = "__webpack_require__.m (add only)"; - -/** - * the chunk ensure function - */ -exports.ensureChunk = "__webpack_require__.e"; - -/** - * an object with handlers to ensure a chunk - */ -exports.ensureChunkHandlers = "__webpack_require__.f"; - -/** - * a runtime requirement if ensureChunkHandlers should include loading of chunk needed for entries - */ -exports.ensureChunkIncludeEntries = "__webpack_require__.f (include entries)"; - -/** - * the chunk prefetch function - */ -exports.prefetchChunk = "__webpack_require__.E"; - -/** - * an object with handlers to prefetch a chunk - */ -exports.prefetchChunkHandlers = "__webpack_require__.F"; - -/** - * the chunk preload function - */ -exports.preloadChunk = "__webpack_require__.G"; - -/** - * an object with handlers to preload a chunk - */ -exports.preloadChunkHandlers = "__webpack_require__.H"; - -/** - * the exported property define getters function - */ -exports.definePropertyGetters = "__webpack_require__.d"; - -/** - * define compatibility on export - */ -exports.makeNamespaceObject = "__webpack_require__.r"; - -/** - * create a fake namespace object - */ -exports.createFakeNamespaceObject = "__webpack_require__.t"; - -/** - * compatibility get default export - */ -exports.compatGetDefaultExport = "__webpack_require__.n"; - -/** - * harmony module decorator - */ -exports.harmonyModuleDecorator = "__webpack_require__.hmd"; - -/** - * node.js module decorator - */ -exports.nodeModuleDecorator = "__webpack_require__.nmd"; - -/** - * the webpack hash - */ -exports.getFullHash = "__webpack_require__.h"; - -/** - * an object containing all installed WebAssembly.Instance export objects keyed by module id - */ -exports.wasmInstances = "__webpack_require__.w"; - -/** - * instantiate a wasm instance from module exports object, id, hash and importsObject - */ -exports.instantiateWasm = "__webpack_require__.v"; - -/** - * the uncaught error handler for the webpack runtime - */ -exports.uncaughtErrorHandler = "__webpack_require__.oe"; - -/** - * the script nonce - */ -exports.scriptNonce = "__webpack_require__.nc"; - -/** - * function to load a script tag. - * Arguments: (url: string, done: (event) => void), key?: string | number, chunkId?: string | number) => void - * done function is called when loading has finished or timeout occurred. - * It will attach to existing script tags with data-webpack == uniqueName + ":" + key or src == url. - */ -exports.loadScript = "__webpack_require__.l"; - -/** - * function to promote a string to a TrustedScript using webpack's Trusted - * Types policy - * Arguments: (script: string) => TrustedScript - */ -exports.createScript = "__webpack_require__.ts"; - -/** - * function to promote a string to a TrustedScriptURL using webpack's Trusted - * Types policy - * Arguments: (url: string) => TrustedScriptURL - */ -exports.createScriptUrl = "__webpack_require__.tu"; - -/** - * function to return webpack's Trusted Types policy - * Arguments: () => TrustedTypePolicy - */ -exports.getTrustedTypesPolicy = "__webpack_require__.tt"; - -/** - * the chunk name of the chunk with the runtime - */ -exports.chunkName = "__webpack_require__.cn"; - -/** - * the runtime id of the current runtime - */ -exports.runtimeId = "__webpack_require__.j"; - -/** - * the filename of the script part of the chunk - */ -exports.getChunkScriptFilename = "__webpack_require__.u"; - -/** - * the filename of the css part of the chunk - */ -exports.getChunkCssFilename = "__webpack_require__.k"; - -/** - * a flag when a module/chunk/tree has css modules - */ -exports.hasCssModules = "has css modules"; - -/** - * the filename of the script part of the hot update chunk - */ -exports.getChunkUpdateScriptFilename = "__webpack_require__.hu"; - -/** - * the filename of the css part of the hot update chunk - */ -exports.getChunkUpdateCssFilename = "__webpack_require__.hk"; - -/** - * startup signal from runtime - * This will be called when the runtime chunk has been loaded. - */ -exports.startup = "__webpack_require__.x"; - -/** - * @deprecated - * creating a default startup function with the entry modules - */ -exports.startupNoDefault = "__webpack_require__.x (no default handler)"; - -/** - * startup signal from runtime but only used to add logic after the startup - */ -exports.startupOnlyAfter = "__webpack_require__.x (only after)"; - -/** - * startup signal from runtime but only used to add sync logic before the startup - */ -exports.startupOnlyBefore = "__webpack_require__.x (only before)"; - -/** - * global callback functions for installing chunks - */ -exports.chunkCallback = "webpackChunk"; - -/** - * method to startup an entrypoint with needed chunks. - * Signature: (moduleId: Id, chunkIds: Id[]) => any. - * Returns the exports of the module or a Promise - */ -exports.startupEntrypoint = "__webpack_require__.X"; - -/** - * register deferred code, which will run when certain - * chunks are loaded. - * Signature: (chunkIds: Id[], fn: () => any, priority: int >= 0 = 0) => any - * Returned value will be returned directly when all chunks are already loaded - * When (priority & 1) it will wait for all other handlers with lower priority to - * be executed before itself is executed - */ -exports.onChunksLoaded = "__webpack_require__.O"; - -/** - * method to install a chunk that was loaded somehow - * Signature: ({ id, ids, modules, runtime }) => void - */ -exports.externalInstallChunk = "__webpack_require__.C"; - -/** - * interceptor for module executions - */ -exports.interceptModuleExecution = "__webpack_require__.i"; - -/** - * the global object - */ -exports.global = "__webpack_require__.g"; - -/** - * an object with all share scopes - */ -exports.shareScopeMap = "__webpack_require__.S"; - -/** - * The sharing init sequence function (only runs once per share scope). - * Has one argument, the name of the share scope. - * Creates a share scope if not existing - */ -exports.initializeSharing = "__webpack_require__.I"; - -/** - * The current scope when getting a module from a remote - */ -exports.currentRemoteGetScope = "__webpack_require__.R"; - -/** - * the filename of the HMR manifest - */ -exports.getUpdateManifestFilename = "__webpack_require__.hmrF"; - -/** - * function downloading the update manifest - */ -exports.hmrDownloadManifest = "__webpack_require__.hmrM"; - -/** - * array with handler functions to download chunk updates - */ -exports.hmrDownloadUpdateHandlers = "__webpack_require__.hmrC"; - -/** - * object with all hmr module data for all modules - */ -exports.hmrModuleData = "__webpack_require__.hmrD"; - -/** - * array with handler functions when a module should be invalidated - */ -exports.hmrInvalidateModuleHandlers = "__webpack_require__.hmrI"; - -/** - * the prefix for storing state of runtime modules when hmr is enabled - */ -exports.hmrRuntimeStatePrefix = "__webpack_require__.hmrS"; - -/** - * the AMD define function - */ -exports.amdDefine = "__webpack_require__.amdD"; - -/** - * the AMD options - */ -exports.amdOptions = "__webpack_require__.amdO"; - -/** - * the System polyfill object - */ -exports.system = "__webpack_require__.System"; - -/** - * the shorthand for Object.prototype.hasOwnProperty - * using of it decreases the compiled bundle size - */ -exports.hasOwnProperty = "__webpack_require__.o"; - -/** - * the System.register context object - */ -exports.systemContext = "__webpack_require__.y"; - -/** - * the baseURI of current document - */ -exports.baseURI = "__webpack_require__.b"; - -/** - * a RelativeURL class when relative URLs are used - */ -exports.relativeUrl = "__webpack_require__.U"; - -/** - * Creates an async module. The body function must be a async function. - * "module.exports" will be decorated with an AsyncModulePromise. - * The body function will be called. - * To handle async dependencies correctly do this: "([a, b, c] = await handleDependencies([a, b, c]));". - * If "hasAwaitAfterDependencies" is truthy, "handleDependencies()" must be called at the end of the body function. - * Signature: function( - * module: Module, - * body: (handleDependencies: (deps: AsyncModulePromise[]) => Promise & () => void, - * hasAwaitAfterDependencies?: boolean - * ) => void - */ -exports.asyncModule = "__webpack_require__.a"; - - -/***/ }), + /** + * @param {RuntimeSpec} runtime runtime + * @returns {string} key representing the usage + */ + getUsageKey(runtime) { + const key = []; + if (this._redirectTo !== undefined) { + key.push(this._redirectTo.getUsageKey(runtime)); + } else { + key.push(this._otherExportsInfo.getUsed(runtime)); + } + key.push(this._sideEffectsOnlyInfo.getUsed(runtime)); + for (const exportInfo of this.orderedOwnedExports) { + key.push(exportInfo.getUsed(runtime)); + } + return key.join("|"); + } -/***/ 16963: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {RuntimeSpec} runtimeA first runtime + * @param {RuntimeSpec} runtimeB second runtime + * @returns {boolean} true, when equally used + */ + isEquallyUsed(runtimeA, runtimeB) { + if (this._redirectTo !== undefined) { + if (!this._redirectTo.isEquallyUsed(runtimeA, runtimeB)) return false; + } else { + if ( + this._otherExportsInfo.getUsed(runtimeA) !== + this._otherExportsInfo.getUsed(runtimeB) + ) { + return false; + } + } + if ( + this._sideEffectsOnlyInfo.getUsed(runtimeA) !== + this._sideEffectsOnlyInfo.getUsed(runtimeB) + ) { + return false; + } + for (const exportInfo of this.ownedExports) { + if (exportInfo.getUsed(runtimeA) !== exportInfo.getUsed(runtimeB)) + return false; + } + return true; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {string | string[]} name export name + * @param {RuntimeSpec} runtime check usage for this runtime only + * @returns {UsageStateType} usage status + */ + getUsed(name, runtime) { + if (Array.isArray(name)) { + if (name.length === 0) return this.otherExportsInfo.getUsed(runtime); + let info = this.getReadOnlyExportInfo(name[0]); + if (info.exportsInfo && name.length > 1) { + return info.exportsInfo.getUsed(name.slice(1), runtime); + } + return info.getUsed(runtime); + } + let info = this.getReadOnlyExportInfo(name); + return info.getUsed(runtime); + } + /** + * @param {string | string[]} name the export name + * @param {RuntimeSpec} runtime check usage for this runtime only + * @returns {string | string[] | false} the used name + */ + getUsedName(name, runtime) { + if (Array.isArray(name)) { + // TODO improve this + if (name.length === 0) { + if (!this.isUsed(runtime)) return false; + return name; + } + let info = this.getReadOnlyExportInfo(name[0]); + const x = info.getUsedName(name[0], runtime); + if (x === false) return false; + const arr = x === name[0] && name.length === 1 ? name : [x]; + if (name.length === 1) { + return arr; + } + if ( + info.exportsInfo && + info.getUsed(runtime) === UsageState.OnlyPropertiesUsed + ) { + const nested = info.exportsInfo.getUsedName(name.slice(1), runtime); + if (!nested) return false; + return arr.concat(nested); + } else { + return arr.concat(name.slice(1)); + } + } else { + let info = this.getReadOnlyExportInfo(name); + const usedName = info.getUsedName(name, runtime); + return usedName; + } + } + /** + * @param {Hash} hash the hash + * @param {RuntimeSpec} runtime the runtime + * @returns {void} + */ + updateHash(hash, runtime) { + this._updateHash(hash, runtime, new Set()); + } -const { RawSource } = __webpack_require__(51255); -const OriginalSource = (__webpack_require__(51255).OriginalSource); -const Module = __webpack_require__(73208); + /** + * @param {Hash} hash the hash + * @param {RuntimeSpec} runtime the runtime + * @param {Set} alreadyVisitedExportsInfo for circular references + * @returns {void} + */ + _updateHash(hash, runtime, alreadyVisitedExportsInfo) { + const set = new Set(alreadyVisitedExportsInfo); + set.add(this); + for (const exportInfo of this.orderedExports) { + if (exportInfo.hasInfo(this._otherExportsInfo, runtime)) { + exportInfo._updateHash(hash, runtime, set); + } + } + this._sideEffectsOnlyInfo._updateHash(hash, runtime, set); + this._otherExportsInfo._updateHash(hash, runtime, set); + if (this._redirectTo !== undefined) { + this._redirectTo._updateHash(hash, runtime, set); + } + } -/** @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("./Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./util/Hash")} Hash */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + getRestoreProvidedData() { + const otherProvided = this._otherExportsInfo.provided; + const otherCanMangleProvide = this._otherExportsInfo.canMangleProvide; + const otherTerminalBinding = this._otherExportsInfo.terminalBinding; + const exports = []; + for (const exportInfo of this.orderedExports) { + if ( + exportInfo.provided !== otherProvided || + exportInfo.canMangleProvide !== otherCanMangleProvide || + exportInfo.terminalBinding !== otherTerminalBinding || + exportInfo.exportsInfoOwned + ) { + exports.push({ + name: exportInfo.name, + provided: exportInfo.provided, + canMangleProvide: exportInfo.canMangleProvide, + terminalBinding: exportInfo.terminalBinding, + exportsInfo: exportInfo.exportsInfoOwned + ? exportInfo.exportsInfo.getRestoreProvidedData() + : undefined + }); + } + } + return new RestoreProvidedData( + exports, + otherProvided, + otherCanMangleProvide, + otherTerminalBinding + ); + } -const TYPES = new Set(["runtime"]); + restoreProvided({ + otherProvided, + otherCanMangleProvide, + otherTerminalBinding, + exports + }) { + let wasEmpty = true; + for (const exportInfo of this._exports.values()) { + wasEmpty = false; + exportInfo.provided = otherProvided; + exportInfo.canMangleProvide = otherCanMangleProvide; + exportInfo.terminalBinding = otherTerminalBinding; + } + this._otherExportsInfo.provided = otherProvided; + this._otherExportsInfo.canMangleProvide = otherCanMangleProvide; + this._otherExportsInfo.terminalBinding = otherTerminalBinding; + for (const exp of exports) { + const exportInfo = this.getExportInfo(exp.name); + exportInfo.provided = exp.provided; + exportInfo.canMangleProvide = exp.canMangleProvide; + exportInfo.terminalBinding = exp.terminalBinding; + if (exp.exportsInfo) { + const exportsInfo = exportInfo.createNestedExportsInfo(); + exportsInfo.restoreProvided(exp.exportsInfo); + } + } + if (wasEmpty) this._exportsAreOrdered = true; + } +} -class RuntimeModule extends Module { +class ExportInfo { /** - * @param {string} name a readable name - * @param {number=} stage an optional stage + * @param {string} name the original name of the export + * @param {ExportInfo=} initFrom init values from this ExportInfo */ - constructor(name, stage = 0) { - super("runtime"); - this.name = name; - this.stage = stage; - this.buildMeta = {}; - this.buildInfo = {}; - /** @type {Compilation} */ - this.compilation = undefined; - /** @type {Chunk} */ - this.chunk = undefined; - /** @type {ChunkGraph} */ - this.chunkGraph = undefined; - this.fullHash = false; - this.dependentHash = false; + constructor(name, initFrom) { /** @type {string} */ - this._cachedGeneratedCode = undefined; + this.name = name; + /** @private @type {string | null} */ + this._usedName = initFrom ? initFrom._usedName : null; + /** @private @type {UsageStateType} */ + this._globalUsed = initFrom ? initFrom._globalUsed : undefined; + /** @private @type {Map} */ + this._usedInRuntime = + initFrom && initFrom._usedInRuntime + ? new Map(initFrom._usedInRuntime) + : undefined; + /** @private @type {boolean} */ + this._hasUseInRuntimeInfo = initFrom + ? initFrom._hasUseInRuntimeInfo + : false; + /** + * true: it is provided + * false: it is not provided + * null: only the runtime knows if it is provided + * undefined: it was not determined if it is provided + * @type {boolean | null | undefined} + */ + this.provided = initFrom ? initFrom.provided : undefined; + /** + * is the export a terminal binding that should be checked for export star conflicts + * @type {boolean} + */ + this.terminalBinding = initFrom ? initFrom.terminalBinding : false; + /** + * true: it can be mangled + * false: is can not be mangled + * undefined: it was not determined if it can be mangled + * @type {boolean | undefined} + */ + this.canMangleProvide = initFrom ? initFrom.canMangleProvide : undefined; + /** + * true: it can be mangled + * false: is can not be mangled + * undefined: it was not determined if it can be mangled + * @type {boolean | undefined} + */ + this.canMangleUse = initFrom ? initFrom.canMangleUse : undefined; + /** @type {boolean} */ + this.exportsInfoOwned = false; + /** @type {ExportsInfo=} */ + this.exportsInfo = undefined; + /** @type {Map=} */ + this._target = undefined; + if (initFrom && initFrom._target) { + this._target = new Map(); + for (const [key, value] of initFrom._target) { + this._target.set(key, { + connection: value.connection, + export: value.export || [name], + priority: value.priority + }); + } + } + /** @type {Map=} */ + this._maxTarget = undefined; } + // TODO webpack 5 remove + /** @private */ + get used() { + throw new Error("REMOVED"); + } + /** @private */ + get usedName() { + throw new Error("REMOVED"); + } /** - * @param {Compilation} compilation the compilation - * @param {Chunk} chunk the chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {void} + * @private + * @param {*} v v */ - attach(compilation, chunk, chunkGraph = compilation.chunkGraph) { - this.compilation = compilation; - this.chunk = chunk; - this.chunkGraph = chunkGraph; + set used(v) { + throw new Error("REMOVED"); } - /** - * @returns {string} a unique identifier of the module + * @private + * @param {*} v v */ - identifier() { - return `webpack/runtime/${this.name}`; + set usedName(v) { + throw new Error("REMOVED"); } - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return `webpack/runtime/${this.name}`; + get canMangle() { + switch (this.canMangleProvide) { + case undefined: + return this.canMangleUse === false ? false : undefined; + case false: + return false; + case true: + switch (this.canMangleUse) { + case undefined: + return undefined; + case false: + return false; + case true: + return true; + } + } + throw new Error( + `Unexpected flags for canMangle ${this.canMangleProvide} ${this.canMangleUse}` + ); } /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} + * @param {RuntimeSpec} runtime only apply to this runtime + * @returns {boolean} true, when something changed */ - needBuild(context, callback) { - return callback(null, false); + setUsedInUnknownWay(runtime) { + let changed = false; + if ( + this.setUsedConditionally( + used => used < UsageState.Unknown, + UsageState.Unknown, + runtime + ) + ) { + changed = true; + } + if (this.canMangleUse !== false) { + this.canMangleUse = false; + changed = true; + } + return changed; } /** - * @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} + * @param {RuntimeSpec} runtime only apply to this runtime + * @returns {boolean} true, when something changed */ - build(options, compilation, resolver, fs, callback) { - // do nothing - // should not be called as runtime modules are added later to the compilation - callback(); + setUsedWithoutInfo(runtime) { + let changed = false; + if (this.setUsed(UsageState.NoInfo, runtime)) { + changed = true; + } + if (this.canMangleUse !== false) { + this.canMangleUse = false; + changed = true; + } + return changed; + } + + setHasUseInfo() { + if (!this._hasUseInRuntimeInfo) { + this._hasUseInRuntimeInfo = true; + } + if (this.canMangleUse === undefined) { + this.canMangleUse = true; + } + if (this.exportsInfoOwned) { + this.exportsInfo.setHasUseInfo(); + } } /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} + * @param {function(UsageStateType): boolean} condition compare with old value + * @param {UsageStateType} newValue set when condition is true + * @param {RuntimeSpec} runtime only apply to this runtime + * @returns {boolean} true when something has changed */ - updateHash(hash, context) { - hash.update(this.name); - hash.update(`${this.stage}`); - try { - if (this.fullHash || this.dependentHash) { - // Do not use getGeneratedCode here, because i. e. compilation hash might be not - // ready at this point. We will cache it later instead. - hash.update(this.generate()); + setUsedConditionally(condition, newValue, runtime) { + if (runtime === undefined) { + if (this._globalUsed === undefined) { + this._globalUsed = newValue; + return true; } else { - hash.update(this.getGeneratedCode()); + if (this._globalUsed !== newValue && condition(this._globalUsed)) { + this._globalUsed = newValue; + return true; + } + } + } else if (this._usedInRuntime === undefined) { + if (newValue !== UsageState.Unused && condition(UsageState.Unused)) { + this._usedInRuntime = new Map(); + forEachRuntime(runtime, runtime => + this._usedInRuntime.set(runtime, newValue) + ); + return true; + } + } else { + let changed = false; + forEachRuntime(runtime, runtime => { + /** @type {UsageStateType} */ + let oldValue = this._usedInRuntime.get(runtime); + if (oldValue === undefined) oldValue = UsageState.Unused; + if (newValue !== oldValue && condition(oldValue)) { + if (newValue === UsageState.Unused) { + this._usedInRuntime.delete(runtime); + } else { + this._usedInRuntime.set(runtime, newValue); + } + changed = true; + } + }); + if (changed) { + if (this._usedInRuntime.size === 0) this._usedInRuntime = undefined; + return true; } - } catch (err) { - hash.update(err.message); } - super.updateHash(hash, context); + return false; } /** - * @returns {Set} types available (do not mutate) + * @param {UsageStateType} newValue new value of the used state + * @param {RuntimeSpec} runtime only apply to this runtime + * @returns {boolean} true when something has changed */ - getSourceTypes() { - return TYPES; + setUsed(newValue, runtime) { + if (runtime === undefined) { + if (this._globalUsed !== newValue) { + this._globalUsed = newValue; + return true; + } + } else if (this._usedInRuntime === undefined) { + if (newValue !== UsageState.Unused) { + this._usedInRuntime = new Map(); + forEachRuntime(runtime, runtime => + this._usedInRuntime.set(runtime, newValue) + ); + return true; + } + } else { + let changed = false; + forEachRuntime(runtime, runtime => { + /** @type {UsageStateType} */ + let oldValue = this._usedInRuntime.get(runtime); + if (oldValue === undefined) oldValue = UsageState.Unused; + if (newValue !== oldValue) { + if (newValue === UsageState.Unused) { + this._usedInRuntime.delete(runtime); + } else { + this._usedInRuntime.set(runtime, newValue); + } + changed = true; + } + }); + if (changed) { + if (this._usedInRuntime.size === 0) this._usedInRuntime = undefined; + return true; + } + } + return false; } /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result + * @param {any} key the key + * @returns {boolean} true, if something has changed */ - codeGeneration(context) { - const sources = new Map(); - const generatedCode = this.getGeneratedCode(); - if (generatedCode) { - sources.set( - "runtime", - this.useSourceMap || this.useSimpleSourceMap - ? new OriginalSource(generatedCode, this.identifier()) - : new RawSource(generatedCode) - ); + unsetTarget(key) { + if (!this._target) return false; + if (this._target.delete(key)) { + this._maxTarget = undefined; + return true; } - return { - sources, - runtimeRequirements: null - }; + return false; } /** - * @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) + * @param {any} key the key + * @param {ModuleGraphConnection} connection the target module if a single one + * @param {string[]=} exportName the exported name + * @param {number=} priority priority + * @returns {boolean} true, if something has changed */ - size(type) { - try { - const source = this.getGeneratedCode(); - return source ? source.length : 0; - } catch (e) { - return 0; + setTarget(key, connection, exportName, priority = 0) { + if (exportName) exportName = [...exportName]; + if (!this._target) { + this._target = new Map(); + this._target.set(key, { connection, export: exportName, priority }); + return true; + } + const oldTarget = this._target.get(key); + if (!oldTarget) { + if (oldTarget === null && !connection) return false; + this._target.set(key, { connection, export: exportName, priority }); + this._maxTarget = undefined; + return true; + } + if ( + oldTarget.connection !== connection || + oldTarget.priority !== priority || + (exportName + ? !oldTarget.export || !equals(oldTarget.export, exportName) + : oldTarget.export) + ) { + oldTarget.connection = connection; + oldTarget.export = exportName; + oldTarget.priority = priority; + this._maxTarget = undefined; + return true; } + return false; } - /* istanbul ignore next */ /** - * @abstract - * @returns {string} runtime code + * @param {RuntimeSpec} runtime for this runtime + * @returns {UsageStateType} usage state */ - generate() { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + getUsed(runtime) { + if (!this._hasUseInRuntimeInfo) return UsageState.NoInfo; + if (this._globalUsed !== undefined) return this._globalUsed; + if (this._usedInRuntime === undefined) { + return UsageState.Unused; + } else if (typeof runtime === "string") { + const value = this._usedInRuntime.get(runtime); + return value === undefined ? UsageState.Unused : value; + } else if (runtime === undefined) { + /** @type {UsageStateType} */ + let max = UsageState.Unused; + for (const value of this._usedInRuntime.values()) { + if (value === UsageState.Used) { + return UsageState.Used; + } + if (max < value) max = value; + } + return max; + } else { + /** @type {UsageStateType} */ + let max = UsageState.Unused; + for (const item of runtime) { + const value = this._usedInRuntime.get(item); + if (value !== undefined) { + if (value === UsageState.Used) { + return UsageState.Used; + } + if (max < value) max = value; + } + } + return max; + } } /** - * @returns {string} runtime code + * get used name + * @param {string | undefined} fallbackName fallback name for used exports with no name + * @param {RuntimeSpec} runtime check usage for this runtime only + * @returns {string | false} used name */ - getGeneratedCode() { - if (this._cachedGeneratedCode) { - return this._cachedGeneratedCode; + getUsedName(fallbackName, runtime) { + if (this._hasUseInRuntimeInfo) { + if (this._globalUsed !== undefined) { + if (this._globalUsed === UsageState.Unused) return false; + } else { + if (this._usedInRuntime === undefined) return false; + if (typeof runtime === "string") { + if (!this._usedInRuntime.has(runtime)) { + return false; + } + } else if (runtime !== undefined) { + if ( + Array.from(runtime).every( + runtime => !this._usedInRuntime.has(runtime) + ) + ) { + return false; + } + } + } } - return (this._cachedGeneratedCode = this.generate()); + if (this._usedName !== null) return this._usedName; + return this.name || fallbackName; } /** - * @returns {boolean} true, if the runtime module should get it's own scope + * @returns {boolean} true, when a mangled name of this export is set */ - shouldIsolate() { - return true; + hasUsedName() { + return this._usedName !== null; } -} -/** - * Runtime modules without any dependencies to other runtime modules - */ -RuntimeModule.STAGE_NORMAL = 0; + /** + * Sets the mangled name of this export + * @param {string} name the new name + * @returns {void} + */ + setUsedName(name) { + this._usedName = name; + } -/** - * Runtime modules with simple dependencies on other runtime modules - */ -RuntimeModule.STAGE_BASIC = 5; + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target + * @returns {ExportInfo | ExportsInfo | undefined} the terminal binding export(s) info if known + */ + getTerminalBinding(moduleGraph, resolveTargetFilter = RETURNS_TRUE) { + if (this.terminalBinding) return this; + const target = this.getTarget(moduleGraph, resolveTargetFilter); + if (!target) return undefined; + const exportsInfo = moduleGraph.getExportsInfo(target.module); + if (!target.export) return exportsInfo; + return exportsInfo.getReadOnlyExportInfoRecursive(target.export); + } -/** - * Runtime modules which attach to handlers of other runtime modules - */ -RuntimeModule.STAGE_ATTACH = 10; + isReexport() { + return !this.terminalBinding && this._target && this._target.size > 0; + } -/** - * Runtime modules which trigger actions on bootstrap - */ -RuntimeModule.STAGE_TRIGGER = 20; + _getMaxTarget() { + if (this._maxTarget !== undefined) return this._maxTarget; + if (this._target.size <= 1) return (this._maxTarget = this._target); + let maxPriority = -Infinity; + let minPriority = Infinity; + for (const { priority } of this._target.values()) { + if (maxPriority < priority) maxPriority = priority; + if (minPriority > priority) minPriority = priority; + } + // This should be very common + if (maxPriority === minPriority) return (this._maxTarget = this._target); -module.exports = RuntimeModule; + // This is an edge case + const map = new Map(); + for (const [key, value] of this._target) { + if (maxPriority === value.priority) { + map.set(key, value); + } + } + this._maxTarget = map; + return map; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {function(Module): boolean} validTargetModuleFilter a valid target module + * @returns {{ module: Module, export: string[] | undefined } | undefined | false} the target, undefined when there is no target, false when no target is valid + */ + findTarget(moduleGraph, validTargetModuleFilter) { + return this._findTarget(moduleGraph, validTargetModuleFilter, new Set()); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {function(Module): boolean} validTargetModuleFilter a valid target module + * @param {Set | undefined} alreadyVisited set of already visited export info to avoid circular references + * @returns {{ module: Module, export: string[] | undefined } | undefined | false} the target, undefined when there is no target, false when no target is valid + */ + _findTarget(moduleGraph, validTargetModuleFilter, alreadyVisited) { + if (!this._target || this._target.size === 0) return undefined; + let rawTarget = this._getMaxTarget().values().next().value; + if (!rawTarget) return undefined; + /** @type {{ module: Module, export: string[] | undefined }} */ + let target = { + module: rawTarget.connection.module, + export: rawTarget.export + }; + for (;;) { + if (validTargetModuleFilter(target.module)) return target; + const exportsInfo = moduleGraph.getExportsInfo(target.module); + const exportInfo = exportsInfo.getExportInfo(target.export[0]); + if (alreadyVisited.has(exportInfo)) return null; + const newTarget = exportInfo._findTarget( + moduleGraph, + validTargetModuleFilter, + alreadyVisited + ); + if (!newTarget) return false; + if (target.export.length === 1) { + target = newTarget; + } else { + target = { + module: newTarget.module, + export: newTarget.export + ? newTarget.export.concat(target.export.slice(1)) + : target.export.slice(1) + }; + } + } + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target + * @returns {{ module: Module, export: string[] | undefined } | undefined} the target + */ + getTarget(moduleGraph, resolveTargetFilter = RETURNS_TRUE) { + const result = this._getTarget(moduleGraph, resolveTargetFilter, undefined); + if (result === CIRCULAR) return undefined; + return result; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {function({ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target + * @param {Set | undefined} alreadyVisited set of already visited export info to avoid circular references + * @returns {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined } | CIRCULAR | undefined} the target + */ + _getTarget(moduleGraph, resolveTargetFilter, alreadyVisited) { + /** + * @param {{ connection: ModuleGraphConnection, export: string[] | undefined } | null} inputTarget unresolved target + * @param {Set} alreadyVisited set of already visited export info to avoid circular references + * @returns {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined } | CIRCULAR | null} resolved target + */ + const resolveTarget = (inputTarget, alreadyVisited) => { + if (!inputTarget) return null; + if (!inputTarget.export) { + return { + module: inputTarget.connection.module, + connection: inputTarget.connection, + export: undefined + }; + } + /** @type {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }} */ + let target = { + module: inputTarget.connection.module, + connection: inputTarget.connection, + export: inputTarget.export + }; + if (!resolveTargetFilter(target)) return target; + let alreadyVisitedOwned = false; + for (;;) { + const exportsInfo = moduleGraph.getExportsInfo(target.module); + const exportInfo = exportsInfo.getExportInfo(target.export[0]); + if (!exportInfo) return target; + if (alreadyVisited.has(exportInfo)) return CIRCULAR; + const newTarget = exportInfo._getTarget( + moduleGraph, + resolveTargetFilter, + alreadyVisited + ); + if (newTarget === CIRCULAR) return CIRCULAR; + if (!newTarget) return target; + if (target.export.length === 1) { + target = newTarget; + if (!target.export) return target; + } else { + target = { + module: newTarget.module, + connection: newTarget.connection, + export: newTarget.export + ? newTarget.export.concat(target.export.slice(1)) + : target.export.slice(1) + }; + } + if (!resolveTargetFilter(target)) return target; + if (!alreadyVisitedOwned) { + alreadyVisited = new Set(alreadyVisited); + alreadyVisitedOwned = true; + } + alreadyVisited.add(exportInfo); + } + }; + + if (!this._target || this._target.size === 0) return undefined; + if (alreadyVisited && alreadyVisited.has(this)) return CIRCULAR; + const newAlreadyVisited = new Set(alreadyVisited); + newAlreadyVisited.add(this); + const values = this._getMaxTarget().values(); + const target = resolveTarget(values.next().value, newAlreadyVisited); + if (target === CIRCULAR) return CIRCULAR; + if (target === null) return undefined; + let result = values.next(); + while (!result.done) { + const t = resolveTarget(result.value, newAlreadyVisited); + if (t === CIRCULAR) return CIRCULAR; + if (t === null) return undefined; + if (t.module !== target.module) return undefined; + if (!t.export !== !target.export) return undefined; + if (target.export && !equals(t.export, target.export)) return undefined; + result = values.next(); + } + return target; + } + + /** + * Move the target forward as long resolveTargetFilter is fulfilled + * @param {ModuleGraph} moduleGraph the module graph + * @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target + * @param {function({ module: Module, export: string[] | undefined }): ModuleGraphConnection=} updateOriginalConnection updates the original connection instead of using the target connection + * @returns {{ module: Module, export: string[] | undefined } | undefined} the resolved target when moved + */ + moveTarget(moduleGraph, resolveTargetFilter, updateOriginalConnection) { + const target = this._getTarget(moduleGraph, resolveTargetFilter, undefined); + if (target === CIRCULAR) return undefined; + if (!target) return undefined; + const originalTarget = this._getMaxTarget().values().next().value; + if ( + originalTarget.connection === target.connection && + originalTarget.export === target.export + ) { + return undefined; + } + this._target.clear(); + this._target.set(undefined, { + connection: updateOriginalConnection + ? updateOriginalConnection(target) + : target.connection, + export: target.export, + priority: 0 + }); + return target; + } + + createNestedExportsInfo() { + if (this.exportsInfoOwned) return this.exportsInfo; + this.exportsInfoOwned = true; + const oldExportsInfo = this.exportsInfo; + this.exportsInfo = new ExportsInfo(); + this.exportsInfo.setHasProvideInfo(); + if (oldExportsInfo) { + this.exportsInfo.setRedirectNamedTo(oldExportsInfo); + } + return this.exportsInfo; + } + + getNestedExportsInfo() { + return this.exportsInfo; + } + + hasInfo(baseInfo, runtime) { + return ( + (this._usedName && this._usedName !== this.name) || + this.provided || + this.terminalBinding || + this.getUsed(runtime) !== baseInfo.getUsed(runtime) + ); + } + + updateHash(hash, runtime) { + this._updateHash(hash, runtime, new Set()); + } + + _updateHash(hash, runtime, alreadyVisitedExportsInfo) { + hash.update( + `${this._usedName || this.name}${this.getUsed(runtime)}${this.provided}${ + this.terminalBinding + }` + ); + if (this.exportsInfo && !alreadyVisitedExportsInfo.has(this.exportsInfo)) { + this.exportsInfo._updateHash(hash, runtime, alreadyVisitedExportsInfo); + } + } + + getUsedInfo() { + if (this._globalUsed !== undefined) { + switch (this._globalUsed) { + case UsageState.Unused: + return "unused"; + case UsageState.NoInfo: + return "no usage info"; + case UsageState.Unknown: + return "maybe used (runtime-defined)"; + case UsageState.Used: + return "used"; + case UsageState.OnlyPropertiesUsed: + return "only properties used"; + } + } else if (this._usedInRuntime !== undefined) { + /** @type {Map} */ + const map = new Map(); + for (const [runtime, used] of this._usedInRuntime) { + const list = map.get(used); + if (list !== undefined) list.push(runtime); + else map.set(used, [runtime]); + } + const specificInfo = Array.from(map, ([used, runtimes]) => { + switch (used) { + case UsageState.NoInfo: + return `no usage info in ${runtimes.join(", ")}`; + case UsageState.Unknown: + return `maybe used in ${runtimes.join(", ")} (runtime-defined)`; + case UsageState.Used: + return `used in ${runtimes.join(", ")}`; + case UsageState.OnlyPropertiesUsed: + return `only properties used in ${runtimes.join(", ")}`; + } + }); + if (specificInfo.length > 0) { + return specificInfo.join("; "); + } + } + return this._hasUseInRuntimeInfo ? "unused" : "no usage info"; + } + + getProvidedInfo() { + switch (this.provided) { + case undefined: + return "no provided info"; + case null: + return "maybe provided (runtime-defined)"; + case true: + return "provided"; + case false: + return "not provided"; + } + } + + getRenameInfo() { + if (this._usedName !== null && this._usedName !== this.name) { + return `renamed to ${JSON.stringify(this._usedName).slice(1, -1)}`; + } + switch (this.canMangleProvide) { + case undefined: + switch (this.canMangleUse) { + case undefined: + return "missing provision and use info prevents renaming"; + case false: + return "usage prevents renaming (no provision info)"; + case true: + return "missing provision info prevents renaming"; + } + break; + case true: + switch (this.canMangleUse) { + case undefined: + return "missing usage info prevents renaming"; + case false: + return "usage prevents renaming"; + case true: + return "could be renamed"; + } + break; + case false: + switch (this.canMangleUse) { + case undefined: + return "provision prevents renaming (no use info)"; + case false: + return "usage and provision prevents renaming"; + case true: + return "provision prevents renaming"; + } + break; + } + throw new Error( + `Unexpected flags for getRenameInfo ${this.canMangleProvide} ${this.canMangleUse}` + ); + } +} + +module.exports = ExportsInfo; +module.exports.ExportInfo = ExportInfo; +module.exports.UsageState = UsageState; /***/ }), -/***/ 2307: +/***/ 7145: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -53200,448 +48571,75 @@ module.exports = RuntimeModule; -const RuntimeGlobals = __webpack_require__(16475); -const { getChunkFilenameTemplate } = __webpack_require__(47283); -const RuntimeRequirementsDependency = __webpack_require__(24187); -const JavascriptModulesPlugin = __webpack_require__(89464); -const AsyncModuleRuntimeModule = __webpack_require__(63672); -const AutoPublicPathRuntimeModule = __webpack_require__(66532); -const CompatGetDefaultExportRuntimeModule = __webpack_require__(44793); -const CompatRuntimeModule = __webpack_require__(88234); -const CreateFakeNamespaceObjectRuntimeModule = __webpack_require__(94669); -const CreateScriptRuntimeModule = __webpack_require__(2759); -const CreateScriptUrlRuntimeModule = __webpack_require__(21213); -const DefinePropertyGettersRuntimeModule = __webpack_require__(75481); -const EnsureChunkRuntimeModule = __webpack_require__(71519); -const GetChunkFilenameRuntimeModule = __webpack_require__(34277); -const GetMainFilenameRuntimeModule = __webpack_require__(10029); -const GetTrustedTypesPolicyRuntimeModule = __webpack_require__(38713); -const GlobalRuntimeModule = __webpack_require__(23255); -const HasOwnPropertyRuntimeModule = __webpack_require__(8011); -const LoadScriptRuntimeModule = __webpack_require__(19942); -const MakeNamespaceObjectRuntimeModule = __webpack_require__(65714); -const OnChunksLoadedRuntimeModule = __webpack_require__(44518); -const PublicPathRuntimeModule = __webpack_require__(56030); -const RelativeUrlRuntimeModule = __webpack_require__(4537); -const RuntimeIdRuntimeModule = __webpack_require__(97115); -const SystemContextRuntimeModule = __webpack_require__(80655); -const ShareRuntimeModule = __webpack_require__(96066); -const StringXor = __webpack_require__(40293); +const ConstDependency = __webpack_require__(76911); +const ExportsInfoDependency = __webpack_require__(78988); -/** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Module")} Module */ - -const GLOBALS_ON_REQUIRE = [ - RuntimeGlobals.chunkName, - RuntimeGlobals.runtimeId, - RuntimeGlobals.compatGetDefaultExport, - RuntimeGlobals.createFakeNamespaceObject, - RuntimeGlobals.createScript, - RuntimeGlobals.createScriptUrl, - RuntimeGlobals.getTrustedTypesPolicy, - RuntimeGlobals.definePropertyGetters, - RuntimeGlobals.ensureChunk, - RuntimeGlobals.entryModuleId, - RuntimeGlobals.getFullHash, - RuntimeGlobals.global, - RuntimeGlobals.makeNamespaceObject, - RuntimeGlobals.moduleCache, - RuntimeGlobals.moduleFactories, - RuntimeGlobals.moduleFactoriesAddOnly, - RuntimeGlobals.interceptModuleExecution, - RuntimeGlobals.publicPath, - RuntimeGlobals.baseURI, - RuntimeGlobals.relativeUrl, - RuntimeGlobals.scriptNonce, - RuntimeGlobals.uncaughtErrorHandler, - RuntimeGlobals.asyncModule, - RuntimeGlobals.wasmInstances, - RuntimeGlobals.instantiateWasm, - RuntimeGlobals.shareScopeMap, - RuntimeGlobals.initializeSharing, - RuntimeGlobals.loadScript, - RuntimeGlobals.systemContext, - RuntimeGlobals.onChunksLoaded -]; - -const MODULE_DEPENDENCIES = { - [RuntimeGlobals.moduleLoaded]: [RuntimeGlobals.module], - [RuntimeGlobals.moduleId]: [RuntimeGlobals.module] -}; - -const TREE_DEPENDENCIES = { - [RuntimeGlobals.definePropertyGetters]: [RuntimeGlobals.hasOwnProperty], - [RuntimeGlobals.compatGetDefaultExport]: [ - RuntimeGlobals.definePropertyGetters - ], - [RuntimeGlobals.createFakeNamespaceObject]: [ - RuntimeGlobals.definePropertyGetters, - RuntimeGlobals.makeNamespaceObject, - RuntimeGlobals.require - ], - [RuntimeGlobals.initializeSharing]: [RuntimeGlobals.shareScopeMap], - [RuntimeGlobals.shareScopeMap]: [RuntimeGlobals.hasOwnProperty] -}; +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ -class RuntimePlugin { +class ExportsInfoApiPlugin { /** - * @param {Compiler} compiler the Compiler + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap("RuntimePlugin", compilation => { - compilation.dependencyTemplates.set( - RuntimeRequirementsDependency, - new RuntimeRequirementsDependency.Template() - ); - for (const req of GLOBALS_ON_REQUIRE) { - compilation.hooks.runtimeRequirementInModule - .for(req) - .tap("RuntimePlugin", (module, set) => { - set.add(RuntimeGlobals.requireScope); - }); - compilation.hooks.runtimeRequirementInTree - .for(req) - .tap("RuntimePlugin", (module, set) => { - set.add(RuntimeGlobals.requireScope); - }); - } - for (const req of Object.keys(TREE_DEPENDENCIES)) { - const deps = TREE_DEPENDENCIES[req]; - compilation.hooks.runtimeRequirementInTree - .for(req) - .tap("RuntimePlugin", (chunk, set) => { - for (const dep of deps) set.add(dep); - }); - } - for (const req of Object.keys(MODULE_DEPENDENCIES)) { - const deps = MODULE_DEPENDENCIES[req]; - compilation.hooks.runtimeRequirementInModule - .for(req) - .tap("RuntimePlugin", (chunk, set) => { - for (const dep of deps) set.add(dep); - }); + 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); } - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.definePropertyGetters) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule( - chunk, - new DefinePropertyGettersRuntimeModule() - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.makeNamespaceObject) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule( - chunk, - new MakeNamespaceObjectRuntimeModule() - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.createFakeNamespaceObject) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule( - chunk, - new CreateFakeNamespaceObjectRuntimeModule() - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hasOwnProperty) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule( - chunk, - new HasOwnPropertyRuntimeModule() - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.compatGetDefaultExport) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule( - chunk, - new CompatGetDefaultExportRuntimeModule() - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.runtimeId) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule(chunk, new RuntimeIdRuntimeModule()); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.publicPath) - .tap("RuntimePlugin", (chunk, set) => { - const { outputOptions } = compilation; - const { publicPath: globalPublicPath, scriptType } = outputOptions; - const entryOptions = chunk.getEntryOptions(); - const publicPath = - entryOptions && entryOptions.publicPath !== undefined - ? entryOptions.publicPath - : globalPublicPath; - - if (publicPath === "auto") { - const module = new AutoPublicPathRuntimeModule(); - if (scriptType !== "module") set.add(RuntimeGlobals.global); - compilation.addRuntimeModule(chunk, module); - } else { - const module = new PublicPathRuntimeModule(publicPath); - - if ( - typeof publicPath !== "string" || - /\[(full)?hash\]/.test(publicPath) - ) { - module.fullHash = true; - } - - compilation.addRuntimeModule(chunk, module); - } - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.global) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule(chunk, new GlobalRuntimeModule()); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.asyncModule) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule(chunk, new AsyncModuleRuntimeModule()); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.systemContext) - .tap("RuntimePlugin", chunk => { - const { outputOptions } = compilation; - const { library: globalLibrary } = outputOptions; - const entryOptions = chunk.getEntryOptions(); - const libraryType = - entryOptions && entryOptions.library !== undefined - ? entryOptions.library.type - : globalLibrary.type; - - if (libraryType === "system") { - compilation.addRuntimeModule( - chunk, - new SystemContextRuntimeModule() - ); - } - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.getChunkScriptFilename) - .tap("RuntimePlugin", (chunk, set) => { - if ( - typeof compilation.outputOptions.chunkFilename === "string" && - /\[(full)?hash(:\d+)?\]/.test( - compilation.outputOptions.chunkFilename - ) - ) { - set.add(RuntimeGlobals.getFullHash); - } - compilation.addRuntimeModule( - chunk, - new GetChunkFilenameRuntimeModule( - "javascript", - "javascript", - RuntimeGlobals.getChunkScriptFilename, - chunk => - chunk.filenameTemplate || - (chunk.canBeInitial() - ? compilation.outputOptions.filename - : compilation.outputOptions.chunkFilename), - false - ) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.getChunkCssFilename) - .tap("RuntimePlugin", (chunk, set) => { - if ( - typeof compilation.outputOptions.cssChunkFilename === "string" && - /\[(full)?hash(:\d+)?\]/.test( - compilation.outputOptions.cssChunkFilename - ) - ) { - set.add(RuntimeGlobals.getFullHash); - } - compilation.addRuntimeModule( - chunk, - new GetChunkFilenameRuntimeModule( - "css", - "css", - RuntimeGlobals.getChunkCssFilename, - chunk => - getChunkFilenameTemplate(chunk, compilation.outputOptions), - set.has(RuntimeGlobals.hmrDownloadUpdateHandlers) - ) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.getChunkUpdateScriptFilename) - .tap("RuntimePlugin", (chunk, set) => { - if ( - /\[(full)?hash(:\d+)?\]/.test( - compilation.outputOptions.hotUpdateChunkFilename - ) - ) - set.add(RuntimeGlobals.getFullHash); - compilation.addRuntimeModule( - chunk, - new GetChunkFilenameRuntimeModule( - "javascript", - "javascript update", - RuntimeGlobals.getChunkUpdateScriptFilename, - c => compilation.outputOptions.hotUpdateChunkFilename, - true - ) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.getUpdateManifestFilename) - .tap("RuntimePlugin", (chunk, set) => { - if ( - /\[(full)?hash(:\d+)?\]/.test( - compilation.outputOptions.hotUpdateMainFilename - ) - ) { - set.add(RuntimeGlobals.getFullHash); - } - compilation.addRuntimeModule( - chunk, - new GetMainFilenameRuntimeModule( - "update manifest", - RuntimeGlobals.getUpdateManifestFilename, - compilation.outputOptions.hotUpdateMainFilename - ) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunk) - .tap("RuntimePlugin", (chunk, set) => { - const hasAsyncChunks = chunk.hasAsyncChunks(); - if (hasAsyncChunks) { - set.add(RuntimeGlobals.ensureChunkHandlers); - } - compilation.addRuntimeModule( - chunk, - new EnsureChunkRuntimeModule(set) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkIncludeEntries) - .tap("RuntimePlugin", (chunk, set) => { - set.add(RuntimeGlobals.ensureChunkHandlers); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.shareScopeMap) - .tap("RuntimePlugin", (chunk, set) => { - compilation.addRuntimeModule(chunk, new ShareRuntimeModule()); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.loadScript) - .tap("RuntimePlugin", (chunk, set) => { - const withCreateScriptUrl = !!compilation.outputOptions.trustedTypes; - if (withCreateScriptUrl) { - set.add(RuntimeGlobals.createScriptUrl); - } - compilation.addRuntimeModule( - chunk, - new LoadScriptRuntimeModule(withCreateScriptUrl) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.createScript) - .tap("RuntimePlugin", (chunk, set) => { - if (compilation.outputOptions.trustedTypes) { - set.add(RuntimeGlobals.getTrustedTypesPolicy); - } - compilation.addRuntimeModule(chunk, new CreateScriptRuntimeModule()); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.createScriptUrl) - .tap("RuntimePlugin", (chunk, set) => { - if (compilation.outputOptions.trustedTypes) { - set.add(RuntimeGlobals.getTrustedTypesPolicy); - } - compilation.addRuntimeModule( - chunk, - new CreateScriptUrlRuntimeModule() - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.getTrustedTypesPolicy) - .tap("RuntimePlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new GetTrustedTypesPolicyRuntimeModule(set) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.relativeUrl) - .tap("RuntimePlugin", (chunk, set) => { - compilation.addRuntimeModule(chunk, new RelativeUrlRuntimeModule()); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.onChunksLoaded) - .tap("RuntimePlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new OnChunksLoadedRuntimeModule() - ); - return true; - }); - // TODO webpack 6: remove CompatRuntimeModule - compilation.hooks.additionalTreeRuntimeRequirements.tap( - "RuntimePlugin", - (chunk, set) => { - const { mainTemplate } = compilation; - if ( - mainTemplate.hooks.bootstrap.isUsed() || - mainTemplate.hooks.localVars.isUsed() || - mainTemplate.hooks.requireEnsure.isUsed() || - mainTemplate.hooks.requireExtensions.isUsed() - ) { - compilation.addRuntimeModule(chunk, new CompatRuntimeModule()); - } - } - ); - JavascriptModulesPlugin.getCompilationHooks(compilation).chunkHash.tap( - "RuntimePlugin", - (chunk, hash, { chunkGraph }) => { - const xor = new StringXor(); - for (const m of chunkGraph.getChunkRuntimeModulesIterable(chunk)) { - xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); - } - xor.updateHash(hash); - } - ); - }); + ); } } -module.exports = RuntimePlugin; + +module.exports = ExportsInfoApiPlugin; /***/ }), -/***/ 18777: +/***/ 73071: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -53652,1045 +48650,763 @@ module.exports = RuntimePlugin; +const { OriginalSource, RawSource } = __webpack_require__(51255); +const ConcatenationScope = __webpack_require__(98229); +const { UsageState } = __webpack_require__(63686); const InitFragment = __webpack_require__(55870); +const Module = __webpack_require__(73208); const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const { equals } = __webpack_require__(84953); -const compileBooleanMatcher = __webpack_require__(29404); +const Template = __webpack_require__(39722); +const StaticExportsDependency = __webpack_require__(91418); +const createHash = __webpack_require__(49835); +const extractUrlAndGlobal = __webpack_require__(11850); +const makeSerializable = __webpack_require__(33032); const propertyAccess = __webpack_require__(54190); -const { forEachRuntime, subtractRuntime } = __webpack_require__(17156); +const { register } = __webpack_require__(8282); -/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./Chunk")} Chunk */ /** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ /** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./ExportsInfo")} ExportsInfo */ +/** @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("./NormalModuleFactory")} NormalModuleFactory */ /** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {typeof import("./util/Hash")} HashConstructor */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** - * @param {Module} module the module - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {string} error message + * @typedef {Object} SourceData + * @property {boolean=} iife + * @property {string=} init + * @property {string} expression + * @property {InitFragment[]=} chunkInitFragments + * @property {ReadonlySet=} runtimeRequirements */ -const noModuleIdErrorMessage = (module, chunkGraph) => { - return `Module ${module.identifier()} has no id assigned. -This should not happen. -It's in these chunks: ${ - Array.from( - chunkGraph.getModuleChunksIterable(module), - c => c.name || c.id || c.debugId - ).join(", ") || "none" - } (If module is in no chunk this indicates a bug in some chunk/module optimization logic) -Module has these incoming connections: ${Array.from( - chunkGraph.moduleGraph.getIncomingConnections(module), - connection => - `\n - ${ - connection.originModule && connection.originModule.identifier() - } ${connection.dependency && connection.dependency.type} ${ - (connection.explanations && - Array.from(connection.explanations).join(", ")) || - "" - }` - ).join("")}`; -}; + +const TYPES = new Set(["javascript"]); +const CSS_TYPES = new Set(["css-import"]); +const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); +const RUNTIME_REQUIREMENTS_FOR_SCRIPT = new Set([RuntimeGlobals.loadScript]); +const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([ + RuntimeGlobals.definePropertyGetters +]); +const EMPTY_RUNTIME_REQUIREMENTS = new Set([]); /** - * @param {string|undefined} definition global object definition - * @returns {string} save to use global object + * @param {string|string[]} variableName the variable name or path + * @param {string} type the module system + * @returns {SourceData} the generated source */ -function getGlobalObject(definition) { - if (!definition) return definition; - const trimmed = definition.trim(); - - if ( - // identifier, we do not need real identifier regarding ECMAScript/Unicode - trimmed.match(/^[_\p{L}][_0-9\p{L}]*$/iu) || - // iife - // call expression - // expression in parentheses - trimmed.match(/^([_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu) - ) - return trimmed; - - return `Object(${trimmed})`; -} - -class RuntimeTemplate { - /** - * @param {Compilation} compilation the compilation - * @param {OutputOptions} outputOptions the compilation output options - * @param {RequestShortener} requestShortener the request shortener - */ - constructor(compilation, outputOptions, requestShortener) { - this.compilation = compilation; - this.outputOptions = outputOptions || {}; - this.requestShortener = requestShortener; - this.globalObject = getGlobalObject(outputOptions.globalObject); - } - - isIIFE() { - return this.outputOptions.iife; +const getSourceForGlobalVariableExternal = (variableName, type) => { + if (!Array.isArray(variableName)) { + // make it an array as the look up works the same basically + variableName = [variableName]; } - isModule() { - return this.outputOptions.module; - } + // needed for e.g. window["some"]["thing"] + const objectLookup = variableName.map(r => `[${JSON.stringify(r)}]`).join(""); + return { + iife: type === "this", + expression: `${type}${objectLookup}` + }; +}; - supportsConst() { - return this.outputOptions.environment.const; +/** + * @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 + )}` + }; +}; - supportsArrowFunction() { - return this.outputOptions.environment.arrowFunction; +/** + * @param {string|string[]} moduleAndSpecifiers the module request + * @returns {SourceData} the generated source + */ +const getSourceForCommonJsExternalInNodeModule = moduleAndSpecifiers => { + const chunkInitFragments = [ + new InitFragment( + 'import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module";\n', + InitFragment.STAGE_HARMONY_IMPORTS, + 0, + "external module node-commonjs" + ) + ]; + if (!Array.isArray(moduleAndSpecifiers)) { + return { + expression: `__WEBPACK_EXTERNAL_createRequire(import.meta.url)(${JSON.stringify( + moduleAndSpecifiers + )})`, + chunkInitFragments + }; } + const moduleName = moduleAndSpecifiers[0]; + return { + expression: `__WEBPACK_EXTERNAL_createRequire(import.meta.url)(${JSON.stringify( + moduleName + )})${propertyAccess(moduleAndSpecifiers, 1)}`, + chunkInitFragments + }; +}; - supportsOptionalChaining() { - return this.outputOptions.environment.optionalChaining; +/** + * @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'" + ); } - - supportsForOf() { - return this.outputOptions.environment.forOf; + if (!Array.isArray(moduleAndSpecifiers)) { + return { + expression: `${importName}(${JSON.stringify(moduleAndSpecifiers)});` + }; } - - supportsDestructuring() { - return this.outputOptions.environment.destructuring; - } - - supportsBigIntLiteral() { - return this.outputOptions.environment.bigIntLiteral; - } - - supportsDynamicImport() { - return this.outputOptions.environment.dynamicImport; - } - - supportsEcmaScriptModuleSyntax() { - return this.outputOptions.environment.module; - } - - supportTemplateLiteral() { - return this.outputOptions.environment.templateLiteral; - } - - returningFunction(returnValue, args = "") { - return this.supportsArrowFunction() - ? `(${args}) => (${returnValue})` - : `function(${args}) { return ${returnValue}; }`; - } - - basicFunction(args, body) { - return this.supportsArrowFunction() - ? `(${args}) => {\n${Template.indent(body)}\n}` - : `function(${args}) {\n${Template.indent(body)}\n}`; + 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" + )});` + }; +}; +class ModuleExternalInitFragment extends InitFragment { /** - * @param {Array} args args - * @returns {string} result expression + * @param {string} request import source + * @param {string=} ident recomputed ident + * @param {string | HashConstructor=} hashFunction the hash function to use */ - concatenation(...args) { - const len = args.length; - - if (len === 2) return this._es5Concatenation(args); - if (len === 0) return '""'; - if (len === 1) { - return typeof args[0] === "string" - ? JSON.stringify(args[0]) - : `"" + ${args[0].expr}`; + constructor(request, ident, hashFunction = "md4") { + if (ident === undefined) { + ident = Template.toIdentifier(request); + if (ident !== request) { + ident += `_${createHash(hashFunction) + .update(request) + .digest("hex") + .slice(0, 8)}`; + } } - if (!this.supportTemplateLiteral()) return this._es5Concatenation(args); + const identifier = `__WEBPACK_EXTERNAL_MODULE_${ident}__`; + super( + `import * as ${identifier} from ${JSON.stringify(request)};\n`, + InitFragment.STAGE_HARMONY_IMPORTS, + 0, + `external module import ${ident}` + ); + this._ident = ident; + this._identifier = identifier; + this._request = request; + } - // cost comparison between template literal and concatenation: - // both need equal surroundings: `xxx` vs "xxx" - // template literal has constant cost of 3 chars for each expression - // es5 concatenation has cost of 3 + n chars for n expressions in row - // when a es5 concatenation ends with an expression it reduces cost by 3 - // when a es5 concatenation starts with an single expression it reduces cost by 3 - // e. g. `${a}${b}${c}` (3*3 = 9) is longer than ""+a+b+c ((3+3)-3 = 3) - // e. g. `x${a}x${b}x${c}x` (3*3 = 9) is shorter than "x"+a+"x"+b+"x"+c+"x" (4+4+4 = 12) + getNamespaceIdentifier() { + return this._identifier; + } +} - let templateCost = 0; - let concatenationCost = 0; +register( + ModuleExternalInitFragment, + "webpack/lib/ExternalModule", + "ModuleExternalInitFragment", + { + serialize(obj, { write }) { + write(obj._request); + write(obj._ident); + }, + deserialize({ read }) { + return new ModuleExternalInitFragment(read(), read()); + } + } +); - let lastWasExpr = false; - for (const arg of args) { - const isExpr = typeof arg !== "string"; - if (isExpr) { - templateCost += 3; - concatenationCost += lastWasExpr ? 1 : 4; +const generateModuleRemapping = (input, exportsInfo, runtime) => { + if (exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused) { + const properties = []; + for (const exportInfo of exportsInfo.orderedExports) { + const used = exportInfo.getUsedName(exportInfo.name, runtime); + if (!used) continue; + const nestedInfo = exportInfo.getNestedExportsInfo(); + if (nestedInfo) { + const nestedExpr = generateModuleRemapping( + `${input}${propertyAccess([exportInfo.name])}`, + nestedInfo + ); + if (nestedExpr) { + properties.push(`[${JSON.stringify(used)}]: y(${nestedExpr})`); + continue; + } } - lastWasExpr = isExpr; + properties.push( + `[${JSON.stringify(used)}]: () => ${input}${propertyAccess([ + exportInfo.name + ])}` + ); } - if (lastWasExpr) concatenationCost -= 3; - if (typeof args[0] !== "string" && typeof args[1] === "string") - concatenationCost -= 3; - - if (concatenationCost <= templateCost) return this._es5Concatenation(args); - - return `\`${args - .map(arg => (typeof arg === "string" ? arg : `\${${arg.expr}}`)) - .join("")}\``; + return `x({ ${properties.join(", ")} })`; } +}; - /** - * @param {Array} args args (len >= 2) - * @returns {string} result expression - * @private - */ - _es5Concatenation(args) { - const str = args - .map(arg => (typeof arg === "string" ? JSON.stringify(arg) : arg.expr)) - .join(" + "); +/** + * @param {string|string[]} moduleAndSpecifiers the module request + * @param {ExportsInfo} exportsInfo exports info of this module + * @param {RuntimeSpec} runtime the runtime + * @param {string | HashConstructor=} hashFunction the hash function to use + * @returns {SourceData} the generated source + */ +const getSourceForModuleExternal = ( + moduleAndSpecifiers, + exportsInfo, + runtime, + hashFunction +) => { + if (!Array.isArray(moduleAndSpecifiers)) + moduleAndSpecifiers = [moduleAndSpecifiers]; + const initFragment = new ModuleExternalInitFragment( + moduleAndSpecifiers[0], + undefined, + hashFunction + ); + const baseAccess = `${initFragment.getNamespaceIdentifier()}${propertyAccess( + moduleAndSpecifiers, + 1 + )}`; + const moduleRemapping = generateModuleRemapping( + baseAccess, + exportsInfo, + runtime + ); + let expression = moduleRemapping || baseAccess; + return { + expression, + init: `var x = y => { var x = {}; ${RuntimeGlobals.definePropertyGetters}(x, y); return x; }\nvar y = x => () => x`, + runtimeRequirements: moduleRemapping + ? RUNTIME_REQUIREMENTS_FOR_MODULE + : undefined, + chunkInitFragments: [initFragment] + }; +}; - // when the first two args are expression, we need to prepend "" + to force string - // concatenation instead of number addition. - return typeof args[0] !== "string" && typeof args[1] !== "string" - ? `"" + ${str}` - : str; +/** + * @param {string|string[]} urlAndGlobal the script request + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @returns {SourceData} the generated source + */ +const getSourceForScriptExternal = (urlAndGlobal, runtimeTemplate) => { + if (typeof urlAndGlobal === "string") { + urlAndGlobal = extractUrlAndGlobal(urlAndGlobal); } + const url = urlAndGlobal[0]; + const globalName = urlAndGlobal[1]; + return { + init: "var __webpack_error__ = new Error();", + expression: `new Promise(${runtimeTemplate.basicFunction( + "resolve, reject", + [ + `if(typeof ${globalName} !== "undefined") return resolve();`, + `${RuntimeGlobals.loadScript}(${JSON.stringify( + url + )}, ${runtimeTemplate.basicFunction("event", [ + `if(typeof ${globalName} !== "undefined") return resolve();`, + "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", + "var realSrc = event && event.target && event.target.src;", + "__webpack_error__.message = 'Loading script failed.\\n(' + errorType + ': ' + realSrc + ')';", + "__webpack_error__.name = 'ScriptExternalLoadError';", + "__webpack_error__.type = errorType;", + "__webpack_error__.request = realSrc;", + "reject(__webpack_error__);" + ])}, ${JSON.stringify(globalName)});` + ] + )}).then(${runtimeTemplate.returningFunction( + `${globalName}${propertyAccess(urlAndGlobal, 2)}` + )})`, + runtimeRequirements: RUNTIME_REQUIREMENTS_FOR_SCRIPT + }; +}; - expressionFunction(expression, args = "") { - return this.supportsArrowFunction() - ? `(${args}) => (${expression})` - : `function(${args}) { ${expression}; }`; - } +/** + * @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`; +}; - emptyFunction() { - return this.supportsArrowFunction() ? "x => {}" : "function() {}"; - } +/** + * @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 + }; +}; - destructureArray(items, value) { - return this.supportsDestructuring() - ? `var [${items.join(", ")}] = ${value};` - : Template.asString( - items.map((item, i) => `var ${item} = ${value}[${i}];`) - ); +/** + * @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]; } - destructureObject(items, value) { - return this.supportsDestructuring() - ? `var {${items.join(", ")}} = ${value};` - : Template.asString( - items.map(item => `var ${item} = ${value}${propertyAccess([item])};`) - ); - } + const variableName = request[0]; + const objectLookup = propertyAccess(request, 1); + return { + init: optional + ? checkExternalVariable(variableName, request.join("."), runtimeTemplate) + : undefined, + expression: `${variableName}${objectLookup}` + }; +}; - iife(args, body) { - return `(${this.basicFunction(args, body)})()`; - } +class ExternalModule extends Module { + constructor(request, type, userRequest) { + super("javascript/dynamic", null); - forEach(variable, array, body) { - return this.supportsForOf() - ? `for(const ${variable} of ${array}) {\n${Template.indent(body)}\n}` - : `${array}.forEach(function(${variable}) {\n${Template.indent( - body - )}\n});`; + // Info from Factory + /** @type {string | string[] | Record} */ + this.request = request; + /** @type {string} */ + this.externalType = type; + /** @type {string} */ + this.userRequest = userRequest; } /** - * Add a comment - * @param {object} options Information content of the comment - * @param {string=} options.request request string used originally - * @param {string=} options.chunkName name of the chunk referenced - * @param {string=} options.chunkReason reason information of the chunk - * @param {string=} options.message additional message - * @param {string=} options.exportName name of the export - * @returns {string} comment + * @returns {Set} types available (do not mutate) */ - comment({ request, chunkName, chunkReason, message, exportName }) { - let content; - if (this.outputOptions.pathinfo) { - content = [message, request, chunkName, chunkReason] - .filter(Boolean) - .map(item => this.requestShortener.shorten(item)) - .join(" | "); - } else { - content = [message, chunkName, chunkReason] - .filter(Boolean) - .map(item => this.requestShortener.shorten(item)) - .join(" | "); - } - if (!content) return ""; - if (this.outputOptions.pathinfo) { - return Template.toComment(content) + " "; - } else { - return Template.toNormalComment(content) + " "; - } + getSourceTypes() { + return this.externalType === "css-import" ? CSS_TYPES : TYPES; } /** - * @param {object} options generation options - * @param {string=} options.request request string used originally - * @returns {string} generated error block + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion */ - throwMissingModuleErrorBlock({ request }) { - const err = `Cannot find module '${request}'`; - return `var e = new Error(${JSON.stringify( - err - )}); e.code = 'MODULE_NOT_FOUND'; throw e;`; + libIdent(options) { + return this.userRequest; } /** - * @param {object} options generation options - * @param {string=} options.request request string used originally - * @returns {string} generated error function + * @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 */ - throwMissingModuleErrorFunction({ request }) { - return `function webpackMissingModule() { ${this.throwMissingModuleErrorBlock( - { request } - )} }`; + chunkCondition(chunk, { chunkGraph }) { + return this.externalType === "css-import" + ? true + : chunkGraph.getNumberOfEntryModules(chunk) > 0; } /** - * @param {object} options generation options - * @param {string=} options.request request string used originally - * @returns {string} generated error IIFE + * @returns {string} a unique identifier of the module */ - missingModule({ request }) { - return `Object(${this.throwMissingModuleErrorFunction({ request })}())`; + identifier() { + return `external ${this.externalType} ${JSON.stringify(this.request)}`; } /** - * @param {object} options generation options - * @param {string=} options.request request string used originally - * @returns {string} generated error statement + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module */ - missingModuleStatement({ request }) { - return `${this.missingModule({ request })};\n`; + readableIdentifier(requestShortener) { + return "external " + JSON.stringify(this.request); } /** - * @param {object} options generation options - * @param {string=} options.request request string used originally - * @returns {string} generated error code + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} */ - missingModulePromise({ request }) { - return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({ - request - })})`; + needBuild(context, callback) { + return callback(null, !this.buildMeta); } /** - * @param {Object} options options object - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {Module} options.module the module - * @param {string} options.request the request that should be printed as comment - * @param {string=} options.idExpr expression to use as id expression - * @param {"expression" | "promise" | "statements"} options.type which kind of code should be returned - * @returns {string} the code + * @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} */ - weakError({ module, chunkGraph, request, idExpr, type }) { - const moduleId = chunkGraph.getModuleId(module); - const errorMessage = - moduleId === null - ? JSON.stringify("Module is not available (weak dependency)") - : idExpr - ? `"Module '" + ${idExpr} + "' is not available (weak dependency)"` - : JSON.stringify( - `Module '${moduleId}' is not available (weak dependency)` - ); - const comment = request ? Template.toNormalComment(request) + " " : ""; - const errorStatements = - `var e = new Error(${errorMessage}); ` + - comment + - "e.code = 'MODULE_NOT_FOUND'; throw e;"; - switch (type) { - case "statements": - return errorStatements; + build(options, compilation, resolver, fs, callback) { + this.buildMeta = { + async: false, + exportsType: undefined + }; + this.buildInfo = { + strict: true, + topLevelDeclarations: new Set(), + module: compilation.outputOptions.module + }; + const { request, externalType } = this._getRequestAndExternalType(); + this.buildMeta.exportsType = "dynamic"; + let canMangle = false; + this.clearDependenciesAndBlocks(); + switch (externalType) { + case "this": + this.buildInfo.strict = false; + break; + case "system": + if (!Array.isArray(request) || request.length === 1) { + this.buildMeta.exportsType = "namespace"; + canMangle = true; + } + break; + case "module": + if (this.buildInfo.module) { + if (!Array.isArray(request) || request.length === 1) { + this.buildMeta.exportsType = "namespace"; + canMangle = true; + } + } else { + this.buildMeta.async = true; + if (!Array.isArray(request) || request.length === 1) { + this.buildMeta.exportsType = "namespace"; + canMangle = false; + } + } + break; + case "script": case "promise": - return `Promise.resolve().then(${this.basicFunction( - "", - errorStatements - )})`; - case "expression": - return this.iife("", errorStatements); + this.buildMeta.async = true; + break; + case "import": + this.buildMeta.async = true; + if (!Array.isArray(request) || request.length === 1) { + this.buildMeta.exportsType = "namespace"; + canMangle = false; + } + break; } + this.addDependency(new StaticExportsDependency(true, canMangle)); + callback(); } - /** - * @param {Object} options options object - * @param {Module} options.module the module - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {string} options.request the request that should be printed as comment - * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) - * @returns {string} the expression - */ - moduleId({ module, chunkGraph, request, weak }) { - if (!module) { - return this.missingModule({ - request - }); - } - const moduleId = chunkGraph.getModuleId(module); - if (moduleId === null) { - if (weak) { - return "null /* weak dependency, without id */"; - } - throw new Error( - `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage( - module, - chunkGraph - )}` - ); - } - return `${this.comment({ request })}${JSON.stringify(moduleId)}`; + restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { + this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); } /** - * @param {Object} options options object - * @param {Module} options.module the module - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {string} options.request the request that should be printed as comment - * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} the expression + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated */ - moduleRaw({ module, chunkGraph, request, weak, runtimeRequirements }) { - if (!module) { - return this.missingModule({ - request - }); - } - const moduleId = chunkGraph.getModuleId(module); - if (moduleId === null) { - if (weak) { - // only weak referenced modules don't get an id - // we can always emit an error emitting code here - return this.weakError({ - module, - chunkGraph, - request, - type: "expression" - }); - } - throw new Error( - `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage( - module, - chunkGraph - )}` - ); + 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`; } - runtimeRequirements.add(RuntimeGlobals.require); - return `__webpack_require__(${this.moduleId({ - module, - chunkGraph, - request, - weak - })})`; + return undefined; } - /** - * @param {Object} options options object - * @param {Module} options.module the module - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {string} options.request the request that should be printed as comment - * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} the expression - */ - moduleExports({ module, chunkGraph, request, weak, runtimeRequirements }) { - return this.moduleRaw({ - module, - chunkGraph, - request, - weak, - runtimeRequirements - }); + _getRequestAndExternalType() { + let { request, externalType } = this; + if (typeof request === "object" && !Array.isArray(request)) + request = request[externalType]; + return { request, externalType }; } - /** - * @param {Object} options options object - * @param {Module} options.module the module - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {string} options.request the request that should be printed as comment - * @param {boolean=} options.strict if the current module is in strict esm mode - * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} the expression - */ - moduleNamespace({ - module, - chunkGraph, + _getSourceData( request, - strict, - weak, - runtimeRequirements - }) { - if (!module) { - return this.missingModule({ - request - }); - } - if (chunkGraph.getModuleId(module) === null) { - if (weak) { - // only weak referenced modules don't get an id - // we can always emit an error emitting code here - return this.weakError({ - module, - chunkGraph, + externalType, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime + ) { + switch (externalType) { + case "this": + case "window": + case "self": + return getSourceForGlobalVariableExternal(request, this.externalType); + case "global": + return getSourceForGlobalVariableExternal( request, - type: "expression" - }); + runtimeTemplate.globalObject + ); + case "commonjs": + case "commonjs2": + case "commonjs-module": + case "commonjs-static": + return getSourceForCommonJsExternal(request); + case "node-commonjs": + return this.buildInfo.module + ? getSourceForCommonJsExternalInNodeModule(request) + : getSourceForCommonJsExternal(request); + case "amd": + case "amd-require": + case "umd": + case "umd2": + case "system": + case "jsonp": { + const id = chunkGraph.getModuleId(this); + return getSourceForAmdOrUmdExternal( + id !== null ? id : this.identifier(), + this.isOptional(moduleGraph), + request, + runtimeTemplate + ); } - throw new Error( - `RuntimeTemplate.moduleNamespace(): ${noModuleIdErrorMessage( - module, - chunkGraph - )}` - ); - } - const moduleId = this.moduleId({ - module, - chunkGraph, - request, - weak - }); - const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict); - switch (exportsType) { - case "namespace": - return this.moduleRaw({ - module, - chunkGraph, + case "import": + return getSourceForImportExternal(request, runtimeTemplate); + case "script": + return getSourceForScriptExternal(request, runtimeTemplate); + case "module": { + if (!this.buildInfo.module) { + if (!runtimeTemplate.supportsDynamicImport()) { + throw new Error( + "The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script" + + (runtimeTemplate.supportsEcmaScriptModuleSyntax() + ? "\nDid you mean to build a EcmaScript Module ('output.module: true')?" + : "") + ); + } + return getSourceForImportExternal(request, runtimeTemplate); + } + if (!runtimeTemplate.supportsEcmaScriptModuleSyntax()) { + throw new Error( + "The target environment doesn't support EcmaScriptModule syntax so it's not possible to use external type 'module'" + ); + } + return getSourceForModuleExternal( request, - weak, - runtimeRequirements - }); - case "default-with-named": - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 3)`; - case "default-only": - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 1)`; - case "dynamic": - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 7)`; + moduleGraph.getExportsInfo(this), + runtime, + runtimeTemplate.outputOptions.hashFunction + ); + } + case "var": + case "promise": + case "const": + case "let": + case "assign": + default: + return getSourceForDefaultCase( + this.isOptional(moduleGraph), + request, + runtimeTemplate + ); } } /** - * @param {Object} options options object - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {AsyncDependenciesBlock=} options.block the current dependencies block - * @param {Module} options.module the module - * @param {string} options.request the request that should be printed as comment - * @param {string} options.message a message for the comment - * @param {boolean=} options.strict if the current module is in strict esm mode - * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} the promise expression + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - moduleNamespacePromise({ + codeGeneration({ + runtimeTemplate, + moduleGraph, chunkGraph, - block, - module, - request, - message, - strict, - weak, - runtimeRequirements + runtime, + concatenationScope }) { - if (!module) { - return this.missingModulePromise({ - request - }); - } - const moduleId = chunkGraph.getModuleId(module); - if (moduleId === null) { - if (weak) { - // only weak referenced modules don't get an id - // we can always emit an error emitting code here - return this.weakError({ - module, - chunkGraph, - request, - type: "promise" - }); + const { request, externalType } = this._getRequestAndExternalType(); + switch (externalType) { + case "asset": { + const sources = new Map(); + sources.set( + "javascript", + new RawSource(`module.exports = ${JSON.stringify(request)};`) + ); + const data = new Map(); + data.set("url", request); + return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS, data }; } - throw new Error( - `RuntimeTemplate.moduleNamespacePromise(): ${noModuleIdErrorMessage( - module, - chunkGraph - )}` - ); - } - const promise = this.blockPromise({ - chunkGraph, - block, - message, - runtimeRequirements - }); - - let appending; - let idExpr = JSON.stringify(chunkGraph.getModuleId(module)); - const comment = this.comment({ - request - }); - let header = ""; - if (weak) { - if (idExpr.length > 8) { - // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"' - header += `var id = ${idExpr}; `; - idExpr = "id"; + case "css-import": { + const sources = new Map(); + sources.set( + "css-import", + new RawSource(`@import url(${JSON.stringify(request)});`) + ); + return { + sources, + runtimeRequirements: EMPTY_RUNTIME_REQUIREMENTS + }; } - runtimeRequirements.add(RuntimeGlobals.moduleFactories); - header += `if(!${ - RuntimeGlobals.moduleFactories - }[${idExpr}]) { ${this.weakError({ - module, - chunkGraph, - request, - idExpr, - type: "statements" - })} } `; - } - const moduleIdExpr = this.moduleId({ - module, - chunkGraph, - request, - weak - }); - const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict); - let fakeType = 16; - switch (exportsType) { - case "namespace": - if (header) { - const rawModule = this.moduleRaw({ - module, - chunkGraph, - request, - weak, - runtimeRequirements - }); - appending = `.then(${this.basicFunction( - "", - `${header}return ${rawModule};` - )})`; + default: { + const sourceData = this._getSourceData( + request, + externalType, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime + ); + + 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 { - runtimeRequirements.add(RuntimeGlobals.require); - appending = `.then(__webpack_require__.bind(__webpack_require__, ${comment}${idExpr}))`; + sourceString = `module.exports = ${sourceString};`; } - break; - case "dynamic": - fakeType |= 4; - /* fall through */ - case "default-with-named": - fakeType |= 2; - /* fall through */ - case "default-only": - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - if (chunkGraph.moduleGraph.isAsync(module)) { - if (header) { - const rawModule = this.moduleRaw({ - module, - chunkGraph, - request, - weak, - runtimeRequirements - }); - appending = `.then(${this.basicFunction( - "", - `${header}return ${rawModule};` - )})`; - } else { - runtimeRequirements.add(RuntimeGlobals.require); - appending = `.then(__webpack_require__.bind(__webpack_require__, ${comment}${idExpr}))`; - } - appending += `.then(${this.returningFunction( - `${RuntimeGlobals.createFakeNamespaceObject}(m, ${fakeType})`, - "m" - )})`; + if (sourceData.init) + sourceString = `${sourceData.init}\n${sourceString}`; + + let data = undefined; + if (sourceData.chunkInitFragments) { + data = new Map(); + data.set("chunkInitFragments", sourceData.chunkInitFragments); + } + + const sources = new Map(); + if (this.useSourceMap || this.useSimpleSourceMap) { + sources.set( + "javascript", + new OriginalSource(sourceString, this.identifier()) + ); } else { - fakeType |= 1; - if (header) { - const returnExpression = `${RuntimeGlobals.createFakeNamespaceObject}(${moduleIdExpr}, ${fakeType})`; - appending = `.then(${this.basicFunction( - "", - `${header}return ${returnExpression};` - )})`; + sources.set("javascript", new RawSource(sourceString)); + } + + let runtimeRequirements = sourceData.runtimeRequirements; + if (!concatenationScope) { + if (!runtimeRequirements) { + runtimeRequirements = RUNTIME_REQUIREMENTS; } else { - appending = `.then(${RuntimeGlobals.createFakeNamespaceObject}.bind(__webpack_require__, ${comment}${idExpr}, ${fakeType}))`; + const set = new Set(runtimeRequirements); + set.add(RuntimeGlobals.module); + runtimeRequirements = set; } } - break; - } - return `${promise || "Promise.resolve()"}${appending}`; + return { + sources, + runtimeRequirements: + runtimeRequirements || EMPTY_RUNTIME_REQUIREMENTS, + data + }; + } + } } /** - * @param {Object} options options object - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {RuntimeSpec=} options.runtime runtime for which this code will be generated - * @param {RuntimeSpec | boolean=} options.runtimeCondition only execute the statement in some runtimes - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} expression + * @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) */ - runtimeConditionExpression({ - chunkGraph, - runtimeCondition, - runtime, - runtimeRequirements - }) { - if (runtimeCondition === undefined) return "true"; - if (typeof runtimeCondition === "boolean") return `${runtimeCondition}`; - /** @type {Set} */ - const positiveRuntimeIds = new Set(); - forEachRuntime(runtimeCondition, runtime => - positiveRuntimeIds.add(`${chunkGraph.getRuntimeId(runtime)}`) - ); - /** @type {Set} */ - const negativeRuntimeIds = new Set(); - forEachRuntime(subtractRuntime(runtime, runtimeCondition), runtime => - negativeRuntimeIds.add(`${chunkGraph.getRuntimeId(runtime)}`) - ); - runtimeRequirements.add(RuntimeGlobals.runtimeId); - return compileBooleanMatcher.fromLists( - Array.from(positiveRuntimeIds), - Array.from(negativeRuntimeIds) - )(RuntimeGlobals.runtimeId); + size(type) { + return 42; } /** - * - * @param {Object} options options object - * @param {boolean=} options.update whether a new variable should be created or the existing one updated - * @param {Module} options.module the module - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {string} options.request the request that should be printed as comment - * @param {string} options.importVar name of the import variable - * @param {Module} options.originModule module in which the statement is emitted - * @param {boolean=} options.weak true, if this is a weak dependency - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {[string, string]} the import statement and the compat statement + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} */ - importStatement({ - update, - module, - chunkGraph, - request, - importVar, - originModule, - weak, - runtimeRequirements - }) { - if (!module) { - return [ - this.missingModuleStatement({ - request - }), - "" - ]; - } - if (chunkGraph.getModuleId(module) === null) { - if (weak) { - // only weak referenced modules don't get an id - // we can always emit an error emitting code here - return [ - this.weakError({ - module, - chunkGraph, - request, - type: "statements" - }), - "" - ]; - } - throw new Error( - `RuntimeTemplate.importStatement(): ${noModuleIdErrorMessage( - module, - chunkGraph - )}` - ); - } - const moduleId = this.moduleId({ - module, - chunkGraph, - request, - weak - }); - const optDeclaration = update ? "" : "var "; - - const exportsType = module.getExportsType( - chunkGraph.moduleGraph, - originModule.buildMeta.strictHarmonyModule + updateHash(hash, context) { + const { chunkGraph } = context; + hash.update( + `${this.externalType}${JSON.stringify(this.request)}${this.isOptional( + chunkGraph.moduleGraph + )}` ); - runtimeRequirements.add(RuntimeGlobals.require); - const importContent = `/* harmony import */ ${optDeclaration}${importVar} = __webpack_require__(${moduleId});\n`; - - if (exportsType === "dynamic") { - runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport); - return [ - importContent, - `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${importVar});\n` - ]; - } - return [importContent, ""]; + super.updateHash(hash, context); } - /** - * @param {Object} options options - * @param {ModuleGraph} options.moduleGraph the module graph - * @param {Module} options.module the module - * @param {string} options.request the request - * @param {string | string[]} options.exportName the export name - * @param {Module} options.originModule the origin module - * @param {boolean|undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted - * @param {boolean} options.isCall true, if expression will be called - * @param {boolean} options.callContext when false, call context will not be preserved - * @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated - * @param {string} options.importVar the identifier name of the import variable - * @param {InitFragment[]} options.initFragments init fragments will be added here - * @param {RuntimeSpec} options.runtime runtime for which this code will be generated - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} expression - */ - exportFromImport({ - moduleGraph, - module, - request, - exportName, - originModule, - asiSafe, - isCall, - callContext, - defaultInterop, - importVar, - initFragments, - runtime, - runtimeRequirements - }) { - if (!module) { - return this.missingModule({ - request - }); - } - if (!Array.isArray(exportName)) { - exportName = exportName ? [exportName] : []; - } - const exportsType = module.getExportsType( - moduleGraph, - originModule.buildMeta.strictHarmonyModule - ); - - if (defaultInterop) { - if (exportName.length > 0 && exportName[0] === "default") { - switch (exportsType) { - case "dynamic": - if (isCall) { - return `${importVar}_default()${propertyAccess(exportName, 1)}`; - } else { - return asiSafe - ? `(${importVar}_default()${propertyAccess(exportName, 1)})` - : asiSafe === false - ? `;(${importVar}_default()${propertyAccess(exportName, 1)})` - : `${importVar}_default.a${propertyAccess(exportName, 1)}`; - } - case "default-only": - case "default-with-named": - exportName = exportName.slice(1); - break; - } - } else if (exportName.length > 0) { - if (exportsType === "default-only") { - return ( - "/* non-default import from non-esm module */undefined" + - propertyAccess(exportName, 1) - ); - } else if ( - exportsType !== "namespace" && - exportName[0] === "__esModule" - ) { - return "/* __esModule */true"; - } - } else if ( - exportsType === "default-only" || - exportsType === "default-with-named" - ) { - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - initFragments.push( - new InitFragment( - `var ${importVar}_namespace_cache;\n`, - InitFragment.STAGE_CONSTANTS, - -1, - `${importVar}_namespace_cache` - ) - ); - return `/*#__PURE__*/ ${ - asiSafe ? "" : asiSafe === false ? ";" : "Object" - }(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${ - RuntimeGlobals.createFakeNamespaceObject - }(${importVar}${exportsType === "default-only" ? "" : ", 2"})))`; - } - } - - if (exportName.length > 0) { - const exportsInfo = moduleGraph.getExportsInfo(module); - const used = exportsInfo.getUsedName(exportName, runtime); - if (!used) { - const comment = Template.toNormalComment( - `unused export ${propertyAccess(exportName)}` - ); - return `${comment} undefined`; - } - const comment = equals(used, exportName) - ? "" - : Template.toNormalComment(propertyAccess(exportName)) + " "; - const access = `${importVar}${comment}${propertyAccess(used)}`; - if (isCall && callContext === false) { - return asiSafe - ? `(0,${access})` - : asiSafe === false - ? `;(0,${access})` - : `/*#__PURE__*/Object(${access})`; - } - return access; - } else { - return importVar; - } - } + serialize(context) { + const { write } = context; - /** - * @param {Object} options options - * @param {AsyncDependenciesBlock} options.block the async block - * @param {string} options.message the message - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} expression - */ - blockPromise({ block, message, chunkGraph, runtimeRequirements }) { - if (!block) { - const comment = this.comment({ - message - }); - return `Promise.resolve(${comment.trim()})`; - } - const chunkGroup = chunkGraph.getBlockChunkGroup(block); - if (!chunkGroup || chunkGroup.chunks.length === 0) { - const comment = this.comment({ - message - }); - return `Promise.resolve(${comment.trim()})`; - } - const chunks = chunkGroup.chunks.filter( - chunk => !chunk.hasRuntime() && chunk.id !== null - ); - const comment = this.comment({ - message, - chunkName: block.chunkName - }); - if (chunks.length === 1) { - const chunkId = JSON.stringify(chunks[0].id); - runtimeRequirements.add(RuntimeGlobals.ensureChunk); - return `${RuntimeGlobals.ensureChunk}(${comment}${chunkId})`; - } else if (chunks.length > 0) { - runtimeRequirements.add(RuntimeGlobals.ensureChunk); - const requireChunkId = chunk => - `${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)})`; - return `Promise.all(${comment.trim()}[${chunks - .map(requireChunkId) - .join(", ")}])`; - } else { - return `Promise.resolve(${comment.trim()})`; - } - } + write(this.request); + write(this.externalType); + write(this.userRequest); - /** - * @param {Object} options options - * @param {AsyncDependenciesBlock} options.block the async block - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @param {string=} options.request request string used originally - * @returns {string} expression - */ - asyncModuleFactory({ block, chunkGraph, runtimeRequirements, request }) { - const dep = block.dependencies[0]; - const module = chunkGraph.moduleGraph.getModule(dep); - const ensureChunk = this.blockPromise({ - block, - message: "", - chunkGraph, - runtimeRequirements - }); - const factory = this.returningFunction( - this.moduleRaw({ - module, - chunkGraph, - request, - runtimeRequirements - }) - ); - return this.returningFunction( - ensureChunk.startsWith("Promise.resolve(") - ? `${factory}` - : `${ensureChunk}.then(${this.returningFunction(factory)})` - ); + super.serialize(context); } - /** - * @param {Object} options options - * @param {Dependency} options.dependency the dependency - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @param {string=} options.request request string used originally - * @returns {string} expression - */ - syncModuleFactory({ dependency, chunkGraph, runtimeRequirements, request }) { - const module = chunkGraph.moduleGraph.getModule(dependency); - const factory = this.returningFunction( - this.moduleRaw({ - module, - chunkGraph, - request, - runtimeRequirements - }) - ); - return this.returningFunction(factory); - } + deserialize(context) { + const { read } = context; - /** - * @param {Object} options options - * @param {string} options.exportsArgument the name of the exports object - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} statement - */ - defineEsModuleFlagStatement({ exportsArgument, runtimeRequirements }) { - runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); - runtimeRequirements.add(RuntimeGlobals.exports); - return `${RuntimeGlobals.makeNamespaceObject}(${exportsArgument});\n`; - } + this.request = read(); + this.externalType = read(); + this.userRequest = read(); - /** - * @param {Object} options options object - * @param {Module} options.module the module - * @param {string} options.publicPath the public path - * @param {RuntimeSpec=} options.runtime runtime - * @param {CodeGenerationResults} options.codeGenerationResults the code generation results - * @returns {string} the url of the asset - */ - assetUrl({ publicPath, runtime, module, codeGenerationResults }) { - if (!module) { - return "data:,"; - } - const codeGen = codeGenerationResults.get(module, runtime); - const { data } = codeGen; - const url = data.get("url"); - if (url) return url.toString(); - const filename = data.get("filename"); - return publicPath + filename; + super.deserialize(context); } } -module.exports = RuntimeTemplate; +makeSerializable(ExternalModule, "webpack/lib/ExternalModule"); + +module.exports = ExternalModule; /***/ }), -/***/ 63560: -/***/ (function(module) { +/***/ 62153: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -54700,76 +49416,258 @@ module.exports = RuntimeTemplate; -class SelfModuleFactory { - constructor(moduleGraph) { - this.moduleGraph = moduleGraph; - } - - create(data, callback) { - const module = this.moduleGraph.getParentModule(data.dependencies[0]); - callback(null, { - module - }); - } -} - -module.exports = SelfModuleFactory; - - -/***/ }), - -/***/ 48076: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const util = __webpack_require__(73837); +const ExternalModule = __webpack_require__(73071); +const { resolveByProperty, cachedSetProperty } = __webpack_require__(60839); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ +/** @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" +); -module.exports = __webpack_require__(96953); +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; + } -/***/ 71070: -/***/ (function(__unused_webpack_module, exports) { + /** + * @param {NormalModuleFactory} normalModuleFactory the normal module factory + * @returns {void} + */ + apply(normalModuleFactory) { + const globalType = this.type; + normalModuleFactory.hooks.factorize.tapAsync( + "ExternalModuleFactoryPlugin", + (data, callback) => { + const context = data.context; + const contextInfo = data.contextInfo; + const dependency = data.dependencies[0]; + const dependencyType = data.dependencyType; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ + /** + * @param {string|string[]|boolean|Record} 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} */ + 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 | null)=, ExternalModule=): void} callback callback + * @returns {void} + */ + const handleExternals = (externals, callback) => { + if (typeof externals === "string") { + if (externals === dependency.request) { + return handleExternal(dependency.request, undefined, callback); + } + } else if (Array.isArray(externals)) { + let i = 0; + const next = () => { + 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; + }; -/** - * @param {number} size the size in bytes - * @returns {string} the formatted size - */ -exports.formatSize = size => { - if (typeof size !== "number" || Number.isNaN(size) === true) { - return "unknown size"; - } + next(); + return; + } else if (externals instanceof RegExp) { + if (externals.test(dependency.request)) { + return handleExternal(dependency.request, undefined, callback); + } + } else if (typeof externals === "function") { + const cb = (err, value, type) => { + if (err) return callback(err); + if (value !== undefined) { + handleExternal(value, type, callback); + } else { + callback(); + } + }; + if (externals.length === 3) { + // TODO webpack 6 remove this + callDeprecatedExternals( + externals, + context, + dependency.request, + cb + ); + } else { + const promise = externals( + { + context, + request: dependency.request, + dependencyType, + contextInfo, + getResolve: options => (context, request, callback) => { + const resolveContext = { + fileDependencies: data.fileDependencies, + missingDependencies: data.missingDependencies, + contextDependencies: data.contextDependencies + }; + let resolver = normalModuleFactory.getResolver( + "normal", + dependencyType + ? cachedSetProperty( + data.resolveOptions || EMPTY_RESOLVE_OPTIONS, + "dependencyType", + dependencyType + ) + : data.resolveOptions + ); + if (options) resolver = resolver.withOptions(options); + if (callback) { + resolver.resolve( + {}, + context, + request, + resolveContext, + callback + ); + } else { + return new Promise((resolve, reject) => { + resolver.resolve( + {}, + context, + request, + resolveContext, + (err, result) => { + if (err) reject(err); + else resolve(result); + } + ); + }); + } + } + }, + cb + ); + if (promise && promise.then) promise.then(r => cb(null, r), cb); + } + return; + } else if (typeof externals === "object") { + const resolvedExternals = resolveLayer( + externals, + contextInfo.issuerLayer + ); + if ( + Object.prototype.hasOwnProperty.call( + resolvedExternals, + dependency.request + ) + ) { + return handleExternal( + resolvedExternals[dependency.request], + undefined, + callback + ); + } + } + callback(); + }; - if (size <= 0) { - return "0 bytes"; + handleExternals(this.externals, callback); + } + ); } - - const abbreviations = ["bytes", "KiB", "MiB", "GiB"]; - const index = Math.floor(Math.log(size) / Math.log(1024)); - - return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${ - abbreviations[index] - }`; -}; +} +module.exports = ExternalModuleFactoryPlugin; /***/ }), -/***/ 97513: +/***/ 6652: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -54780,61 +49678,41 @@ exports.formatSize = size => { -const JavascriptModulesPlugin = __webpack_require__(89464); +const ExternalModuleFactoryPlugin = __webpack_require__(62153); -/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ +/** @typedef {import("./Compiler")} Compiler */ -class SourceMapDevToolModuleOptionsPlugin { - constructor(options) { - this.options = options; +class ExternalsPlugin { + /** + * @param {string | undefined} type default external type + * @param {Externals} externals externals config + */ + constructor(type, externals) { + this.type = type; + this.externals = externals; } /** - * @param {Compilation} compilation the compiler instance + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply(compilation) { - const options = this.options; - if (options.module !== false) { - compilation.hooks.buildModule.tap( - "SourceMapDevToolModuleOptionsPlugin", - module => { - module.useSourceMap = true; - } - ); - compilation.hooks.runtimeModule.tap( - "SourceMapDevToolModuleOptionsPlugin", - module => { - module.useSourceMap = true; - } - ); - } else { - compilation.hooks.buildModule.tap( - "SourceMapDevToolModuleOptionsPlugin", - module => { - module.useSimpleSourceMap = true; - } - ); - compilation.hooks.runtimeModule.tap( - "SourceMapDevToolModuleOptionsPlugin", - module => { - module.useSimpleSourceMap = true; - } + apply(compiler) { + compiler.hooks.compile.tap("ExternalsPlugin", ({ normalModuleFactory }) => { + new ExternalModuleFactoryPlugin(this.type, this.externals).apply( + normalModuleFactory ); - } - JavascriptModulesPlugin.getCompilationHooks(compilation).useSourceMap.tap( - "SourceMapDevToolModuleOptionsPlugin", - () => true - ); + }); } } -module.exports = SourceMapDevToolModuleOptionsPlugin; +module.exports = ExternalsPlugin; /***/ }), -/***/ 63872: +/***/ 79453: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -54845,3684 +49723,3583 @@ module.exports = SourceMapDevToolModuleOptionsPlugin; +const { create: createResolver } = __webpack_require__(30662); const asyncLib = __webpack_require__(78175); -const { ConcatSource, RawSource } = __webpack_require__(51255); -const Compilation = __webpack_require__(85720); -const ModuleFilenameHelpers = __webpack_require__(88821); -const ProgressPlugin = __webpack_require__(13216); -const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(97513); -const createSchemaValidation = __webpack_require__(32540); +const AsyncQueue = __webpack_require__(12260); +const StackedCacheMap = __webpack_require__(64985); const createHash = __webpack_require__(49835); -const { relative, dirname } = __webpack_require__(17139); -const { makePathsAbsolute } = __webpack_require__(82186); +const { join, dirname, relative, lstatReadlinkAbsolute } = __webpack_require__(17139); +const makeSerializable = __webpack_require__(33032); +const processAsyncTree = __webpack_require__(42791); -/** @typedef {import("webpack-sources").MapOptions} MapOptions */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ -/** @typedef {import("./Cache").Etag} Etag */ -/** @typedef {import("./CacheFacade").ItemCacheFacade} ItemCacheFacade */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./NormalModule").SourceMap} SourceMap */ -/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./logging/Logger").Logger} Logger */ +/** @typedef {typeof import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").IStats} IStats */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + +const supportsEsm = +process.versions.modules >= 83; + +let FS_ACCURACY = 2000; + +const EMPTY_SET = new Set(); + +const RBDT_RESOLVE_CJS = 0; +const RBDT_RESOLVE_ESM = 1; +const RBDT_RESOLVE_DIRECTORY = 2; +const RBDT_RESOLVE_CJS_FILE = 3; +const RBDT_RESOLVE_CJS_FILE_AS_CHILD = 4; +const RBDT_RESOLVE_ESM_FILE = 5; +const RBDT_DIRECTORY = 6; +const RBDT_FILE = 7; +const RBDT_DIRECTORY_DEPENDENCIES = 8; +const RBDT_FILE_DEPENDENCIES = 9; + +const INVALID = Symbol("invalid"); -const validate = createSchemaValidation( - __webpack_require__(2885), - () => __webpack_require__(30501), - { - name: "SourceMap DevTool Plugin", - baseDataPath: "options" - } -); /** - * @typedef {object} SourceMapTask - * @property {Source} asset - * @property {AssetInfo} assetInfo - * @property {(string | Module)[]} modules - * @property {string} source - * @property {string} file - * @property {SourceMap} sourceMap - * @property {ItemCacheFacade} cacheItem cache item + * @typedef {Object} FileSystemInfoEntry + * @property {number} safeTime + * @property {number=} timestamp */ /** - * Escapes regular expression metacharacters - * @param {string} str String to quote - * @returns {string} Escaped string + * @typedef {Object} ResolvedContextFileSystemInfoEntry + * @property {number} safeTime + * @property {string=} timestampHash */ -const quoteMeta = str => { - return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); -}; /** - * Creating {@link SourceMapTask} for given file - * @param {string} file current compiled file - * @param {Source} asset the asset - * @param {AssetInfo} assetInfo the asset info - * @param {MapOptions} options source map options - * @param {Compilation} compilation compilation instance - * @param {ItemCacheFacade} cacheItem cache item - * @returns {SourceMapTask | undefined} created task instance or `undefined` + * @typedef {Object} ContextFileSystemInfoEntry + * @property {number} safeTime + * @property {string=} timestampHash + * @property {ResolvedContextFileSystemInfoEntry=} resolved + * @property {Set=} symlinks */ -const getTaskForFile = ( - file, - asset, - assetInfo, - options, - compilation, - cacheItem -) => { - let source; - /** @type {SourceMap} */ - let sourceMap; - /** - * Check if asset can build source map - */ - if (asset.sourceAndMap) { - const sourceAndMap = asset.sourceAndMap(options); - sourceMap = /** @type {SourceMap} */ (sourceAndMap.map); - source = sourceAndMap.source; - } else { - sourceMap = /** @type {SourceMap} */ (asset.map(options)); - source = asset.source(); - } - if (!sourceMap || typeof source !== "string") return; - const context = compilation.options.context; - const root = compilation.compiler.root; - const cachedAbsolutify = makePathsAbsolute.bindContextCache(context, root); - const modules = sourceMap.sources.map(source => { - if (!source.startsWith("webpack://")) return source; - source = cachedAbsolutify(source.slice(10)); - const module = compilation.findModule(source); - return module || source; - }); - return { - file, - asset, - source, - assetInfo, - sourceMap, - modules, - cacheItem - }; -}; +/** + * @typedef {Object} TimestampAndHash + * @property {number} safeTime + * @property {number=} timestamp + * @property {string} hash + */ -class SourceMapDevToolPlugin { - /** - * @param {SourceMapDevToolPluginOptions} [options] options object - * @throws {Error} throws error, if got more than 1 arguments - */ - constructor(options = {}) { - validate(options); +/** + * @typedef {Object} ResolvedContextTimestampAndHash + * @property {number} safeTime + * @property {string=} timestampHash + * @property {string} hash + */ - /** @type {string | false} */ - this.sourceMapFilename = options.filename; - /** @type {string | false} */ - this.sourceMappingURLComment = - options.append === false - ? false - : options.append || "\n//# source" + "MappingURL=[url]"; - /** @type {string | Function} */ - this.moduleFilenameTemplate = - options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]"; - /** @type {string | Function} */ - this.fallbackModuleFilenameTemplate = - options.fallbackModuleFilenameTemplate || - "webpack://[namespace]/[resourcePath]?[hash]"; - /** @type {string} */ - this.namespace = options.namespace || ""; - /** @type {SourceMapDevToolPluginOptions} */ - this.options = options; - } +/** + * @typedef {Object} ContextTimestampAndHash + * @property {number} safeTime + * @property {string=} timestampHash + * @property {string} hash + * @property {ResolvedContextTimestampAndHash=} resolved + * @property {Set=} symlinks + */ - /** - * Apply the plugin - * @param {Compiler} compiler compiler instance - * @returns {void} - */ - apply(compiler) { - const outputFs = compiler.outputFileSystem; - const sourceMapFilename = this.sourceMapFilename; - const sourceMappingURLComment = this.sourceMappingURLComment; - const moduleFilenameTemplate = this.moduleFilenameTemplate; - const namespace = this.namespace; - const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate; - const requestShortener = compiler.requestShortener; - const options = this.options; - options.test = options.test || /\.((c|m)?js|css)($|\?)/i; +/** + * @typedef {Object} ContextHash + * @property {string} hash + * @property {string=} resolved + * @property {Set=} symlinks + */ - const matchObject = ModuleFilenameHelpers.matchObject.bind( - undefined, - options - ); +/** + * @typedef {Object} SnapshotOptimizationEntry + * @property {Snapshot} snapshot + * @property {number} shared + * @property {Set} snapshotContent + * @property {Set} children + */ - compiler.hooks.compilation.tap("SourceMapDevToolPlugin", compilation => { - new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); +/** + * @typedef {Object} ResolveBuildDependenciesResult + * @property {Set} files list of files + * @property {Set} directories list of directories + * @property {Set} missing list of missing entries + * @property {Map} resolveResults stored resolve results + * @property {Object} resolveDependencies dependencies of the resolving + * @property {Set} resolveDependencies.files list of files + * @property {Set} resolveDependencies.directories list of directories + * @property {Set} resolveDependencies.missing list of missing entries + */ - compilation.hooks.processAssets.tapAsync( - { - name: "SourceMapDevToolPlugin", - stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING, - additionalAssets: true - }, - (assets, callback) => { - const chunkGraph = compilation.chunkGraph; - const cache = compilation.getCache("SourceMapDevToolPlugin"); - /** @type {Map} */ - const moduleToSourceNameMapping = new Map(); - /** - * @type {Function} - * @returns {void} - */ - const reportProgress = - ProgressPlugin.getReporter(compilation.compiler) || (() => {}); +const DONE_ITERATOR_RESULT = new Set().keys().next(); - /** @type {Map} */ - const fileToChunk = new Map(); - for (const chunk of compilation.chunks) { - for (const file of chunk.files) { - fileToChunk.set(file, chunk); - } - for (const file of chunk.auxiliaryFiles) { - fileToChunk.set(file, chunk); - } - } +// cspell:word tshs +// Tsh = Timestamp + Hash +// Tshs = Timestamp + Hash combinations - /** @type {string[]} */ - const files = []; - for (const file of Object.keys(assets)) { - if (matchObject(file)) { - files.push(file); - } - } +class SnapshotIterator { + constructor(next) { + this.next = next; + } +} - reportProgress(0.0); - /** @type {SourceMapTask[]} */ - const tasks = []; - let fileIndex = 0; +class SnapshotIterable { + constructor(snapshot, getMaps) { + this.snapshot = snapshot; + this.getMaps = getMaps; + } - asyncLib.each( - files, - (file, callback) => { - const asset = compilation.getAsset(file); - if (asset.info.related && asset.info.related.sourceMap) { - fileIndex++; - return callback(); + [Symbol.iterator]() { + let state = 0; + /** @type {IterableIterator} */ + let it; + /** @type {(Snapshot) => (Map | Set)[]} */ + let getMaps; + /** @type {(Map | Set)[]} */ + let maps; + /** @type {Snapshot} */ + let snapshot; + let queue; + return new SnapshotIterator(() => { + for (;;) { + switch (state) { + case 0: + snapshot = this.snapshot; + getMaps = this.getMaps; + maps = getMaps(snapshot); + state = 1; + /* falls through */ + case 1: + if (maps.length > 0) { + const map = maps.pop(); + if (map !== undefined) { + it = map.keys(); + state = 2; + } else { + break; } - const cacheItem = cache.getItemCache( - file, - cache.mergeEtags( - cache.getLazyHashedEtag(asset.source), - namespace - ) - ); + } else { + state = 3; + break; + } + /* falls through */ + case 2: { + const result = it.next(); + if (!result.done) return result; + state = 1; + break; + } + case 3: { + const children = snapshot.children; + if (children !== undefined) { + if (children.size === 1) { + // shortcut for a single child + // avoids allocation of queue + for (const child of children) snapshot = child; + maps = getMaps(snapshot); + state = 1; + break; + } + if (queue === undefined) queue = []; + for (const child of children) { + queue.push(child); + } + } + if (queue !== undefined && queue.length > 0) { + snapshot = queue.pop(); + maps = getMaps(snapshot); + state = 1; + break; + } else { + state = 4; + } + } + /* falls through */ + case 4: + return DONE_ITERATOR_RESULT; + } + } + }); + } +} - cacheItem.get((err, cacheEntry) => { - if (err) { - return callback(err); - } - /** - * If presented in cache, reassigns assets. Cache assets already have source maps. - */ - if (cacheEntry) { - const { assets, assetsInfo } = cacheEntry; - for (const cachedFile of Object.keys(assets)) { - if (cachedFile === file) { - compilation.updateAsset( - cachedFile, - assets[cachedFile], - assetsInfo[cachedFile] - ); - } else { - compilation.emitAsset( - cachedFile, - assets[cachedFile], - assetsInfo[cachedFile] - ); - } - /** - * Add file to chunk, if not presented there - */ - if (cachedFile !== file) { - const chunk = fileToChunk.get(file); - if (chunk !== undefined) - chunk.auxiliaryFiles.add(cachedFile); - } - } - - reportProgress( - (0.5 * ++fileIndex) / files.length, - file, - "restored cached SourceMap" - ); - - return callback(); - } - - reportProgress( - (0.5 * fileIndex) / files.length, - file, - "generate SourceMap" - ); - - /** @type {SourceMapTask | undefined} */ - const task = getTaskForFile( - file, - asset.source, - asset.info, - { - module: options.module, - columns: options.columns - }, - compilation, - cacheItem - ); +class Snapshot { + constructor() { + this._flags = 0; + /** @type {number | undefined} */ + this.startTime = undefined; + /** @type {Map | undefined} */ + this.fileTimestamps = undefined; + /** @type {Map | undefined} */ + this.fileHashes = undefined; + /** @type {Map | undefined} */ + this.fileTshs = undefined; + /** @type {Map | undefined} */ + this.contextTimestamps = undefined; + /** @type {Map | undefined} */ + this.contextHashes = undefined; + /** @type {Map | undefined} */ + this.contextTshs = undefined; + /** @type {Map | undefined} */ + this.missingExistence = undefined; + /** @type {Map | undefined} */ + this.managedItemInfo = undefined; + /** @type {Set | undefined} */ + this.managedFiles = undefined; + /** @type {Set | undefined} */ + this.managedContexts = undefined; + /** @type {Set | undefined} */ + this.managedMissing = undefined; + /** @type {Set | undefined} */ + this.children = undefined; + } - if (task) { - const modules = task.modules; + hasStartTime() { + return (this._flags & 1) !== 0; + } - for (let idx = 0; idx < modules.length; idx++) { - const module = modules[idx]; - if (!moduleToSourceNameMapping.get(module)) { - moduleToSourceNameMapping.set( - module, - ModuleFilenameHelpers.createFilename( - module, - { - moduleFilenameTemplate: moduleFilenameTemplate, - namespace: namespace - }, - { - requestShortener, - chunkGraph, - hashFunction: compilation.outputOptions.hashFunction - } - ) - ); - } - } + setStartTime(value) { + this._flags = this._flags | 1; + this.startTime = value; + } - tasks.push(task); - } + setMergedStartTime(value, snapshot) { + if (value) { + if (snapshot.hasStartTime()) { + this.setStartTime(Math.min(value, snapshot.startTime)); + } else { + this.setStartTime(value); + } + } else { + if (snapshot.hasStartTime()) this.setStartTime(snapshot.startTime); + } + } - reportProgress( - (0.5 * ++fileIndex) / files.length, - file, - "generated SourceMap" - ); + hasFileTimestamps() { + return (this._flags & 2) !== 0; + } - callback(); - }); - }, - err => { - if (err) { - return callback(err); - } + setFileTimestamps(value) { + this._flags = this._flags | 2; + this.fileTimestamps = value; + } - reportProgress(0.5, "resolve sources"); - /** @type {Set} */ - const usedNamesSet = new Set(moduleToSourceNameMapping.values()); - /** @type {Set} */ - const conflictDetectionSet = new Set(); + hasFileHashes() { + return (this._flags & 4) !== 0; + } - /** - * all modules in defined order (longest identifier first) - * @type {Array} - */ - const allModules = Array.from( - moduleToSourceNameMapping.keys() - ).sort((a, b) => { - const ai = typeof a === "string" ? a : a.identifier(); - const bi = typeof b === "string" ? b : b.identifier(); - return ai.length - bi.length; - }); + setFileHashes(value) { + this._flags = this._flags | 4; + this.fileHashes = value; + } - // find modules with conflicting source names - for (let idx = 0; idx < allModules.length; idx++) { - const module = allModules[idx]; - let sourceName = moduleToSourceNameMapping.get(module); - let hasName = conflictDetectionSet.has(sourceName); - if (!hasName) { - conflictDetectionSet.add(sourceName); - continue; - } + hasFileTshs() { + return (this._flags & 8) !== 0; + } - // try the fallback name first - sourceName = ModuleFilenameHelpers.createFilename( - module, - { - moduleFilenameTemplate: fallbackModuleFilenameTemplate, - namespace: namespace - }, - { - requestShortener, - chunkGraph, - hashFunction: compilation.outputOptions.hashFunction - } - ); - hasName = usedNamesSet.has(sourceName); - if (!hasName) { - moduleToSourceNameMapping.set(module, sourceName); - usedNamesSet.add(sourceName); - continue; - } + setFileTshs(value) { + this._flags = this._flags | 8; + this.fileTshs = value; + } - // otherwise just append stars until we have a valid name - while (hasName) { - sourceName += "*"; - hasName = usedNamesSet.has(sourceName); - } - moduleToSourceNameMapping.set(module, sourceName); - usedNamesSet.add(sourceName); - } + hasContextTimestamps() { + return (this._flags & 0x10) !== 0; + } - let taskIndex = 0; + setContextTimestamps(value) { + this._flags = this._flags | 0x10; + this.contextTimestamps = value; + } - asyncLib.each( - tasks, - (task, callback) => { - const assets = Object.create(null); - const assetsInfo = Object.create(null); - const file = task.file; - const chunk = fileToChunk.get(file); - const sourceMap = task.sourceMap; - const source = task.source; - const modules = task.modules; + hasContextHashes() { + return (this._flags & 0x20) !== 0; + } - reportProgress( - 0.5 + (0.5 * taskIndex) / tasks.length, - file, - "attach SourceMap" - ); + setContextHashes(value) { + this._flags = this._flags | 0x20; + this.contextHashes = value; + } - const moduleFilenames = modules.map(m => - moduleToSourceNameMapping.get(m) - ); - sourceMap.sources = moduleFilenames; - if (options.noSources) { - sourceMap.sourcesContent = undefined; - } - sourceMap.sourceRoot = options.sourceRoot || ""; - sourceMap.file = file; - const usesContentHash = - sourceMapFilename && - /\[contenthash(:\w+)?\]/.test(sourceMapFilename); + hasContextTshs() { + return (this._flags & 0x40) !== 0; + } - // If SourceMap and asset uses contenthash, avoid a circular dependency by hiding hash in `file` - if (usesContentHash && task.assetInfo.contenthash) { - const contenthash = task.assetInfo.contenthash; - let pattern; - if (Array.isArray(contenthash)) { - pattern = contenthash.map(quoteMeta).join("|"); - } else { - pattern = quoteMeta(contenthash); - } - sourceMap.file = sourceMap.file.replace( - new RegExp(pattern, "g"), - m => "x".repeat(m.length) - ); - } + setContextTshs(value) { + this._flags = this._flags | 0x40; + this.contextTshs = value; + } - /** @type {string | false} */ - let currentSourceMappingURLComment = sourceMappingURLComment; - if ( - currentSourceMappingURLComment !== false && - /\.css($|\?)/i.test(file) - ) { - currentSourceMappingURLComment = - currentSourceMappingURLComment.replace( - /^\n\/\/(.*)$/, - "\n/*$1*/" - ); - } - const sourceMapString = JSON.stringify(sourceMap); - if (sourceMapFilename) { - let filename = file; - const sourceMapContentHash = - usesContentHash && - /** @type {string} */ ( - createHash(compilation.outputOptions.hashFunction) - .update(sourceMapString) - .digest("hex") - ); - const pathParams = { - chunk, - filename: options.fileContext - ? relative( - outputFs, - `/${options.fileContext}`, - `/${filename}` - ) - : filename, - contentHash: sourceMapContentHash - }; - const { path: sourceMapFile, info: sourceMapInfo } = - compilation.getPathWithInfo( - sourceMapFilename, - pathParams - ); - const sourceMapUrl = options.publicPath - ? options.publicPath + sourceMapFile - : relative( - outputFs, - dirname(outputFs, `/${file}`), - `/${sourceMapFile}` - ); - /** @type {Source} */ - let asset = new RawSource(source); - if (currentSourceMappingURLComment !== false) { - // Add source map url to compilation asset, if currentSourceMappingURLComment is set - asset = new ConcatSource( - asset, - compilation.getPath( - currentSourceMappingURLComment, - Object.assign({ url: sourceMapUrl }, pathParams) - ) - ); - } - const assetInfo = { - related: { sourceMap: sourceMapFile } - }; - assets[file] = asset; - assetsInfo[file] = assetInfo; - compilation.updateAsset(file, asset, assetInfo); - // Add source map file to compilation assets and chunk files - const sourceMapAsset = new RawSource(sourceMapString); - const sourceMapAssetInfo = { - ...sourceMapInfo, - development: true - }; - assets[sourceMapFile] = sourceMapAsset; - assetsInfo[sourceMapFile] = sourceMapAssetInfo; - compilation.emitAsset( - sourceMapFile, - sourceMapAsset, - sourceMapAssetInfo - ); - if (chunk !== undefined) - chunk.auxiliaryFiles.add(sourceMapFile); - } else { - if (currentSourceMappingURLComment === false) { - throw new Error( - "SourceMapDevToolPlugin: append can't be false when no filename is provided" - ); - } - /** - * Add source map as data url to asset - */ - const asset = new ConcatSource( - new RawSource(source), - currentSourceMappingURLComment - .replace(/\[map\]/g, () => sourceMapString) - .replace( - /\[url\]/g, - () => - `data:application/json;charset=utf-8;base64,${Buffer.from( - sourceMapString, - "utf-8" - ).toString("base64")}` - ) - ); - assets[file] = asset; - assetsInfo[file] = undefined; - compilation.updateAsset(file, asset); - } + hasMissingExistence() { + return (this._flags & 0x80) !== 0; + } - task.cacheItem.store({ assets, assetsInfo }, err => { - reportProgress( - 0.5 + (0.5 * ++taskIndex) / tasks.length, - task.file, - "attached SourceMap" - ); + setMissingExistence(value) { + this._flags = this._flags | 0x80; + this.missingExistence = value; + } - if (err) { - return callback(err); - } - callback(); - }); - }, - err => { - reportProgress(1.0); - callback(err); - } - ); - } - ); - } - ); - }); + hasManagedItemInfo() { + return (this._flags & 0x100) !== 0; } -} -module.exports = SourceMapDevToolPlugin; + setManagedItemInfo(value) { + this._flags = this._flags | 0x100; + this.managedItemInfo = value; + } + hasManagedFiles() { + return (this._flags & 0x200) !== 0; + } -/***/ }), + setManagedFiles(value) { + this._flags = this._flags | 0x200; + this.managedFiles = value; + } -/***/ 31743: -/***/ (function(module) { + hasManagedContexts() { + return (this._flags & 0x400) !== 0; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + setManagedContexts(value) { + this._flags = this._flags | 0x400; + this.managedContexts = value; + } + hasManagedMissing() { + return (this._flags & 0x800) !== 0; + } + setManagedMissing(value) { + this._flags = this._flags | 0x800; + this.managedMissing = value; + } -/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ + hasChildren() { + return (this._flags & 0x1000) !== 0; + } -class Stats { - /** - * @param {Compilation} compilation webpack compilation - */ - constructor(compilation) { - this.compilation = compilation; + setChildren(value) { + this._flags = this._flags | 0x1000; + this.children = value; } - get hash() { - return this.compilation.hash; + addChild(child) { + if (!this.hasChildren()) { + this.setChildren(new Set()); + } + this.children.add(child); } - get startTime() { - return this.compilation.startTime; + serialize({ write }) { + write(this._flags); + if (this.hasStartTime()) write(this.startTime); + if (this.hasFileTimestamps()) write(this.fileTimestamps); + if (this.hasFileHashes()) write(this.fileHashes); + if (this.hasFileTshs()) write(this.fileTshs); + if (this.hasContextTimestamps()) write(this.contextTimestamps); + if (this.hasContextHashes()) write(this.contextHashes); + if (this.hasContextTshs()) write(this.contextTshs); + if (this.hasMissingExistence()) write(this.missingExistence); + if (this.hasManagedItemInfo()) write(this.managedItemInfo); + if (this.hasManagedFiles()) write(this.managedFiles); + if (this.hasManagedContexts()) write(this.managedContexts); + if (this.hasManagedMissing()) write(this.managedMissing); + if (this.hasChildren()) write(this.children); } - get endTime() { - return this.compilation.endTime; + deserialize({ read }) { + this._flags = read(); + if (this.hasStartTime()) this.startTime = read(); + if (this.hasFileTimestamps()) this.fileTimestamps = read(); + if (this.hasFileHashes()) this.fileHashes = read(); + if (this.hasFileTshs()) this.fileTshs = read(); + if (this.hasContextTimestamps()) this.contextTimestamps = read(); + if (this.hasContextHashes()) this.contextHashes = read(); + if (this.hasContextTshs()) this.contextTshs = read(); + if (this.hasMissingExistence()) this.missingExistence = read(); + if (this.hasManagedItemInfo()) this.managedItemInfo = read(); + if (this.hasManagedFiles()) this.managedFiles = read(); + if (this.hasManagedContexts()) this.managedContexts = read(); + if (this.hasManagedMissing()) this.managedMissing = read(); + if (this.hasChildren()) this.children = read(); } /** - * @returns {boolean} true if the compilation had a warning + * @param {function(Snapshot): (ReadonlyMap | ReadonlySet)[]} getMaps first + * @returns {Iterable} iterable */ - hasWarnings() { - return ( - this.compilation.warnings.length > 0 || - this.compilation.children.some(child => child.getStats().hasWarnings()) - ); + _createIterable(getMaps) { + return new SnapshotIterable(this, getMaps); } /** - * @returns {boolean} true if the compilation encountered an error + * @returns {Iterable} iterable */ - hasErrors() { - return ( - this.compilation.errors.length > 0 || - this.compilation.children.some(child => child.getStats().hasErrors()) - ); + getFileIterable() { + return this._createIterable(s => [ + s.fileTimestamps, + s.fileHashes, + s.fileTshs, + s.managedFiles + ]); } /** - * @param {(string|StatsOptions)=} options stats options - * @returns {StatsCompilation} json output + * @returns {Iterable} iterable */ - toJson(options) { - options = this.compilation.createStatsOptions(options, { - forToString: false - }); - - const statsFactory = this.compilation.createStatsFactory(options); + getContextIterable() { + return this._createIterable(s => [ + s.contextTimestamps, + s.contextHashes, + s.contextTshs, + s.managedContexts + ]); + } - return statsFactory.create("compilation", this.compilation, { - compilation: this.compilation - }); + /** + * @returns {Iterable} iterable + */ + getMissingIterable() { + return this._createIterable(s => [s.missingExistence, s.managedMissing]); } +} - toString(options) { - options = this.compilation.createStatsOptions(options, { - forToString: true - }); +makeSerializable(Snapshot, "webpack/lib/FileSystemInfo", "Snapshot"); - const statsFactory = this.compilation.createStatsFactory(options); - const statsPrinter = this.compilation.createStatsPrinter(options); +const MIN_COMMON_SNAPSHOT_SIZE = 3; - const data = statsFactory.create("compilation", this.compilation, { - compilation: this.compilation - }); - const result = statsPrinter.print("compilation", data); - return result === undefined ? "" : result; +/** + * @template T + */ +class SnapshotOptimization { + /** + * @param {function(Snapshot): boolean} has has value + * @param {function(Snapshot): Map | Set} get get value + * @param {function(Snapshot, Map | Set): void} set set value + * @param {boolean=} useStartTime use the start time of snapshots + * @param {boolean=} isSet value is an Set instead of a Map + */ + constructor(has, get, set, useStartTime = true, isSet = false) { + this._has = has; + this._get = get; + this._set = set; + this._useStartTime = useStartTime; + this._isSet = isSet; + /** @type {Map} */ + this._map = new Map(); + this._statItemsShared = 0; + this._statItemsUnshared = 0; + this._statSharedSnapshots = 0; + this._statReusedSharedSnapshots = 0; } -} -module.exports = Stats; + getStatisticMessage() { + const total = this._statItemsShared + this._statItemsUnshared; + if (total === 0) return undefined; + return `${ + this._statItemsShared && Math.round((this._statItemsShared * 100) / total) + }% (${this._statItemsShared}/${total}) entries shared via ${ + this._statSharedSnapshots + } shared snapshots (${ + this._statReusedSharedSnapshots + this._statSharedSnapshots + } times referenced)`; + } + clear() { + this._map.clear(); + this._statItemsShared = 0; + this._statItemsUnshared = 0; + this._statSharedSnapshots = 0; + this._statReusedSharedSnapshots = 0; + } -/***/ }), + /** + * @param {Snapshot} newSnapshot snapshot + * @param {Set} capturedFiles files to snapshot/share + * @returns {void} + */ + optimize(newSnapshot, capturedFiles) { + /** + * @param {SnapshotOptimizationEntry} entry optimization entry + * @returns {void} + */ + const increaseSharedAndStoreOptimizationEntry = entry => { + if (entry.children !== undefined) { + entry.children.forEach(increaseSharedAndStoreOptimizationEntry); + } + entry.shared++; + storeOptimizationEntry(entry); + }; + /** + * @param {SnapshotOptimizationEntry} entry optimization entry + * @returns {void} + */ + const storeOptimizationEntry = entry => { + for (const path of entry.snapshotContent) { + const old = this._map.get(path); + if (old.shared < entry.shared) { + this._map.set(path, entry); + } + capturedFiles.delete(path); + } + }; -/***/ 1626: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {SnapshotOptimizationEntry} */ + let newOptimizationEntry = undefined; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const capturedFilesSize = capturedFiles.size; + /** @type {Set | undefined} */ + const optimizationEntries = new Set(); + for (const path of capturedFiles) { + const optimizationEntry = this._map.get(path); + if (optimizationEntry === undefined) { + if (newOptimizationEntry === undefined) { + newOptimizationEntry = { + snapshot: newSnapshot, + shared: 0, + snapshotContent: undefined, + children: undefined + }; + } + this._map.set(path, newOptimizationEntry); + continue; + } else { + optimizationEntries.add(optimizationEntry); + } + } -const { ConcatSource, PrefixSource } = __webpack_require__(51255); + optimizationEntries: for (const optimizationEntry of optimizationEntries) { + const snapshot = optimizationEntry.snapshot; + if (optimizationEntry.shared > 0) { + // It's a shared snapshot + // We can't change it, so we can only use it when all files match + // and startTime is compatible + if ( + this._useStartTime && + newSnapshot.startTime && + (!snapshot.startTime || snapshot.startTime > newSnapshot.startTime) + ) { + continue; + } + const nonSharedFiles = new Set(); + const snapshotContent = optimizationEntry.snapshotContent; + const snapshotEntries = this._get(snapshot); + for (const path of snapshotContent) { + if (!capturedFiles.has(path)) { + if (!snapshotEntries.has(path)) { + // File is not shared and can't be removed from the snapshot + // because it's in a child of the snapshot + continue optimizationEntries; + } + nonSharedFiles.add(path); + continue; + } + } + if (nonSharedFiles.size === 0) { + // The complete snapshot is shared + // add it as child + newSnapshot.addChild(snapshot); + increaseSharedAndStoreOptimizationEntry(optimizationEntry); + this._statReusedSharedSnapshots++; + } else { + // Only a part of the snapshot is shared + const sharedCount = snapshotContent.size - nonSharedFiles.size; + if (sharedCount < MIN_COMMON_SNAPSHOT_SIZE) { + // Common part it too small + continue optimizationEntries; + } + // Extract common timestamps from both snapshots + let commonMap; + if (this._isSet) { + commonMap = new Set(); + for (const path of /** @type {Set} */ (snapshotEntries)) { + if (nonSharedFiles.has(path)) continue; + commonMap.add(path); + snapshotEntries.delete(path); + } + } else { + commonMap = new Map(); + const map = /** @type {Map} */ (snapshotEntries); + for (const [path, value] of map) { + if (nonSharedFiles.has(path)) continue; + commonMap.set(path, value); + snapshotEntries.delete(path); + } + } + // Create and attach snapshot + const commonSnapshot = new Snapshot(); + if (this._useStartTime) { + commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot); + } + this._set(commonSnapshot, commonMap); + newSnapshot.addChild(commonSnapshot); + snapshot.addChild(commonSnapshot); + // Create optimization entry + const newEntry = { + snapshot: commonSnapshot, + shared: optimizationEntry.shared + 1, + snapshotContent: new Set(commonMap.keys()), + children: undefined + }; + if (optimizationEntry.children === undefined) + optimizationEntry.children = new Set(); + optimizationEntry.children.add(newEntry); + storeOptimizationEntry(newEntry); + this._statSharedSnapshots++; + } + } else { + // It's a unshared snapshot + // We can extract a common shared snapshot + // with all common files + const snapshotEntries = this._get(snapshot); + if (snapshotEntries === undefined) { + // Incomplete snapshot, that can't be used + continue optimizationEntries; + } + let commonMap; + if (this._isSet) { + commonMap = new Set(); + const set = /** @type {Set} */ (snapshotEntries); + if (capturedFiles.size < set.size) { + for (const path of capturedFiles) { + if (set.has(path)) commonMap.add(path); + } + } else { + for (const path of set) { + if (capturedFiles.has(path)) commonMap.add(path); + } + } + } else { + commonMap = new Map(); + const map = /** @type {Map} */ (snapshotEntries); + for (const path of capturedFiles) { + const ts = map.get(path); + if (ts === undefined) continue; + commonMap.set(path, ts); + } + } -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("./Compilation").PathData} PathData */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ -/** @typedef {import("./RuntimeModule")} RuntimeModule */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ -/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ + if (commonMap.size < MIN_COMMON_SNAPSHOT_SIZE) { + // Common part it too small + continue optimizationEntries; + } + // Create and attach snapshot + const commonSnapshot = new Snapshot(); + if (this._useStartTime) { + commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot); + } + this._set(commonSnapshot, commonMap); + newSnapshot.addChild(commonSnapshot); + snapshot.addChild(commonSnapshot); + // Remove files from snapshot + for (const path of commonMap.keys()) snapshotEntries.delete(path); + const sharedCount = commonMap.size; + this._statItemsUnshared -= sharedCount; + this._statItemsShared += sharedCount; + // Create optimization entry + storeOptimizationEntry({ + snapshot: commonSnapshot, + shared: 2, + snapshotContent: new Set(commonMap.keys()), + children: undefined + }); + this._statSharedSnapshots++; + } + } + const unshared = capturedFiles.size; + this._statItemsUnshared += unshared; + this._statItemsShared += capturedFilesSize - unshared; + } +} -const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0); -const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0); -const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1; -const NUMBER_OF_IDENTIFIER_START_CHARS = DELTA_A_TO_Z * 2 + 2; // a-z A-Z _ $ -const NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS = - NUMBER_OF_IDENTIFIER_START_CHARS + 10; // a-z A-Z _ $ 0-9 -const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g; -const INDENT_MULTILINE_REGEX = /^\t/gm; -const LINE_SEPARATOR_REGEX = /\r?\n/g; -const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/; -const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g; -const COMMENT_END_REGEX = /\*\//g; -const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g; -const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; +const parseString = str => { + if (str[0] === "'") str = `"${str.slice(1, -1).replace(/"/g, '\\"')}"`; + return JSON.parse(str); +}; +/* istanbul ignore next */ /** - * @typedef {Object} RenderManifestOptions - * @property {Chunk} chunk the chunk used to render - * @property {string} hash - * @property {string} fullHash - * @property {OutputOptions} outputOptions - * @property {CodeGenerationResults} codeGenerationResults - * @property {{javascript: ModuleTemplate}} moduleTemplates - * @property {DependencyTemplates} dependencyTemplates - * @property {RuntimeTemplate} runtimeTemplate - * @property {ModuleGraph} moduleGraph - * @property {ChunkGraph} chunkGraph + * @param {number} mtime mtime */ +const applyMtime = mtime => { + if (FS_ACCURACY > 1 && mtime % 2 !== 0) FS_ACCURACY = 1; + else if (FS_ACCURACY > 10 && mtime % 20 !== 0) FS_ACCURACY = 10; + else if (FS_ACCURACY > 100 && mtime % 200 !== 0) FS_ACCURACY = 100; + else if (FS_ACCURACY > 1000 && mtime % 2000 !== 0) FS_ACCURACY = 1000; +}; -/** @typedef {RenderManifestEntryTemplated | RenderManifestEntryStatic} RenderManifestEntry */ +/** + * @template T + * @template K + * @param {Map} a source map + * @param {Map} b joining map + * @returns {Map} joined map + */ +const mergeMaps = (a, b) => { + if (!b || b.size === 0) return a; + if (!a || a.size === 0) return b; + const map = new Map(a); + for (const [key, value] of b) { + map.set(key, value); + } + return map; +}; /** - * @typedef {Object} RenderManifestEntryTemplated - * @property {function(): Source} render - * @property {string | function(PathData, AssetInfo=): string} filenameTemplate - * @property {PathData=} pathOptions - * @property {AssetInfo=} info - * @property {string} identifier - * @property {string=} hash - * @property {boolean=} auxiliary + * @template T + * @template K + * @param {Set} a source map + * @param {Set} b joining map + * @returns {Set} joined map */ +const mergeSets = (a, b) => { + if (!b || b.size === 0) return a; + if (!a || a.size === 0) return b; + const map = new Set(a); + for (const item of b) { + map.add(item); + } + return map; +}; /** - * @typedef {Object} RenderManifestEntryStatic - * @property {function(): Source} render - * @property {string} filename - * @property {AssetInfo} info - * @property {string} identifier - * @property {string=} hash - * @property {boolean=} auxiliary + * Finding file or directory to manage + * @param {string} managedPath path that is managing by {@link FileSystemInfo} + * @param {string} path path to file or directory + * @returns {string|null} managed item + * @example + * getManagedItem( + * '/Users/user/my-project/node_modules/', + * '/Users/user/my-project/node_modules/package/index.js' + * ) === '/Users/user/my-project/node_modules/package' + * getManagedItem( + * '/Users/user/my-project/node_modules/', + * '/Users/user/my-project/node_modules/package1/node_modules/package2' + * ) === '/Users/user/my-project/node_modules/package1/node_modules/package2' + * getManagedItem( + * '/Users/user/my-project/node_modules/', + * '/Users/user/my-project/node_modules/.bin/script.js' + * ) === null // hidden files are disallowed as managed items + * getManagedItem( + * '/Users/user/my-project/node_modules/', + * '/Users/user/my-project/node_modules/package' + * ) === '/Users/user/my-project/node_modules/package' */ +const getManagedItem = (managedPath, path) => { + let i = managedPath.length; + let slashes = 1; + let startingPosition = true; + loop: while (i < path.length) { + switch (path.charCodeAt(i)) { + case 47: // slash + case 92: // backslash + if (--slashes === 0) break loop; + startingPosition = true; + break; + case 46: // . + // hidden files are disallowed as managed items + // it's probably .yarn-integrity or .cache + if (startingPosition) return null; + break; + case 64: // @ + if (!startingPosition) return null; + slashes++; + break; + default: + startingPosition = false; + break; + } + i++; + } + if (i === path.length) slashes--; + // return null when path is incomplete + if (slashes !== 0) return null; + // if (path.slice(i + 1, i + 13) === "node_modules") + if ( + path.length >= i + 13 && + path.charCodeAt(i + 1) === 110 && + path.charCodeAt(i + 2) === 111 && + path.charCodeAt(i + 3) === 100 && + path.charCodeAt(i + 4) === 101 && + path.charCodeAt(i + 5) === 95 && + path.charCodeAt(i + 6) === 109 && + path.charCodeAt(i + 7) === 111 && + path.charCodeAt(i + 8) === 100 && + path.charCodeAt(i + 9) === 117 && + path.charCodeAt(i + 10) === 108 && + path.charCodeAt(i + 11) === 101 && + path.charCodeAt(i + 12) === 115 + ) { + // if this is the end of the path + if (path.length === i + 13) { + // return the node_modules directory + // it's special + return path; + } + const c = path.charCodeAt(i + 13); + // if next symbol is slash or backslash + if (c === 47 || c === 92) { + // Managed subpath + return getManagedItem(path.slice(0, i + 14), path); + } + } + return path.slice(0, i); +}; /** - * @typedef {Object} HasId - * @property {number | string} id + * @template {ContextFileSystemInfoEntry | ContextTimestampAndHash} T + * @param {T} entry entry + * @returns {T["resolved"] | undefined} the resolved entry */ +const getResolvedTimestamp = entry => { + if (entry === null) return null; + if (entry.resolved !== undefined) return entry.resolved; + return entry.symlinks === undefined ? entry : undefined; +}; /** - * @typedef {function(Module, number): boolean} ModuleFilterPredicate + * @param {ContextHash} entry entry + * @returns {string | undefined} the resolved entry */ +const getResolvedHash = entry => { + if (entry === null) return null; + if (entry.resolved !== undefined) return entry.resolved; + return entry.symlinks === undefined ? entry.hash : undefined; +}; -class Template { +const addAll = (source, target) => { + for (const key of source) target.add(key); +}; + +/** + * Used to access information about the filesystem in a cached way + */ +class FileSystemInfo { /** - * - * @param {Function} fn a runtime function (.runtime.js) "template" - * @returns {string} the updated and normalized function string + * @param {InputFileSystem} fs file system + * @param {Object} options options + * @param {Iterable=} options.managedPaths paths that are only managed by a package manager + * @param {Iterable=} options.immutablePaths paths that are immutable + * @param {Logger=} options.logger logger used to log invalid snapshots + * @param {string | Hash=} options.hashFunction the hash function to use */ - static getFunctionContent(fn) { - return fn - .toString() - .replace(FUNCTION_CONTENT_REGEX, "") - .replace(INDENT_MULTILINE_REGEX, "") - .replace(LINE_SEPARATOR_REGEX, "\n"); - } + constructor( + fs, + { + managedPaths = [], + immutablePaths = [], + logger, + hashFunction = "md4" + } = {} + ) { + this.fs = fs; + this.logger = logger; + this._remainingLogs = logger ? 40 : 0; + this._loggedPaths = logger ? new Set() : undefined; + this._hashFunction = hashFunction; + /** @type {WeakMap} */ + this._snapshotCache = new WeakMap(); + this._fileTimestampsOptimization = new SnapshotOptimization( + s => s.hasFileTimestamps(), + s => s.fileTimestamps, + (s, v) => s.setFileTimestamps(v) + ); + this._fileHashesOptimization = new SnapshotOptimization( + s => s.hasFileHashes(), + s => s.fileHashes, + (s, v) => s.setFileHashes(v), + false + ); + this._fileTshsOptimization = new SnapshotOptimization( + s => s.hasFileTshs(), + s => s.fileTshs, + (s, v) => s.setFileTshs(v) + ); + this._contextTimestampsOptimization = new SnapshotOptimization( + s => s.hasContextTimestamps(), + s => s.contextTimestamps, + (s, v) => s.setContextTimestamps(v) + ); + this._contextHashesOptimization = new SnapshotOptimization( + s => s.hasContextHashes(), + s => s.contextHashes, + (s, v) => s.setContextHashes(v), + false + ); + this._contextTshsOptimization = new SnapshotOptimization( + s => s.hasContextTshs(), + s => s.contextTshs, + (s, v) => s.setContextTshs(v) + ); + this._missingExistenceOptimization = new SnapshotOptimization( + s => s.hasMissingExistence(), + s => s.missingExistence, + (s, v) => s.setMissingExistence(v), + false + ); + this._managedItemInfoOptimization = new SnapshotOptimization( + s => s.hasManagedItemInfo(), + s => s.managedItemInfo, + (s, v) => s.setManagedItemInfo(v), + false + ); + this._managedFilesOptimization = new SnapshotOptimization( + s => s.hasManagedFiles(), + s => s.managedFiles, + (s, v) => s.setManagedFiles(v), + false, + true + ); + this._managedContextsOptimization = new SnapshotOptimization( + s => s.hasManagedContexts(), + s => s.managedContexts, + (s, v) => s.setManagedContexts(v), + false, + true + ); + this._managedMissingOptimization = new SnapshotOptimization( + s => s.hasManagedMissing(), + s => s.managedMissing, + (s, v) => s.setManagedMissing(v), + false, + true + ); + /** @type {StackedCacheMap} */ + this._fileTimestamps = new StackedCacheMap(); + /** @type {Map} */ + this._fileHashes = new Map(); + /** @type {Map} */ + this._fileTshs = new Map(); + /** @type {StackedCacheMap} */ + this._contextTimestamps = new StackedCacheMap(); + /** @type {Map} */ + this._contextHashes = new Map(); + /** @type {Map} */ + this._contextTshs = new Map(); + /** @type {Map} */ + this._managedItems = new Map(); + /** @type {AsyncQueue} */ + this.fileTimestampQueue = new AsyncQueue({ + name: "file timestamp", + parallelism: 30, + processor: this._readFileTimestamp.bind(this) + }); + /** @type {AsyncQueue} */ + this.fileHashQueue = new AsyncQueue({ + name: "file hash", + parallelism: 10, + processor: this._readFileHash.bind(this) + }); + /** @type {AsyncQueue} */ + this.contextTimestampQueue = new AsyncQueue({ + name: "context timestamp", + parallelism: 2, + processor: this._readContextTimestamp.bind(this) + }); + /** @type {AsyncQueue} */ + this.contextHashQueue = new AsyncQueue({ + name: "context hash", + parallelism: 2, + processor: this._readContextHash.bind(this) + }); + /** @type {AsyncQueue} */ + this.contextTshQueue = new AsyncQueue({ + name: "context hash and timestamp", + parallelism: 2, + processor: this._readContextTimestampAndHash.bind(this) + }); + /** @type {AsyncQueue} */ + this.managedItemQueue = new AsyncQueue({ + name: "managed item info", + parallelism: 10, + processor: this._getManagedItemInfo.bind(this) + }); + /** @type {AsyncQueue>} */ + this.managedItemDirectoryQueue = new AsyncQueue({ + name: "managed item directory info", + parallelism: 10, + processor: this._getManagedItemDirectoryInfo.bind(this) + }); + this.managedPaths = Array.from(managedPaths); + this.managedPathsWithSlash = /** @type {string[]} */ ( + this.managedPaths.filter(p => typeof p === "string") + ).map(p => join(fs, p, "_").slice(0, -1)); - /** - * @param {string} str the string converted to identifier - * @returns {string} created identifier - */ - static toIdentifier(str) { - if (typeof str !== "string") return ""; - return str - .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1") - .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_"); - } - /** - * - * @param {string} str string to be converted to commented in bundle code - * @returns {string} returns a commented version of string - */ - static toComment(str) { - if (!str) return ""; - return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`; - } + this.managedPathsRegExps = /** @type {RegExp[]} */ ( + this.managedPaths.filter(p => typeof p !== "string") + ); + this.immutablePaths = Array.from(immutablePaths); + this.immutablePathsWithSlash = /** @type {string[]} */ ( + this.immutablePaths.filter(p => typeof p === "string") + ).map(p => join(fs, p, "_").slice(0, -1)); + this.immutablePathsRegExps = /** @type {RegExp[]} */ ( + this.immutablePaths.filter(p => typeof p !== "string") + ); - /** - * - * @param {string} str string to be converted to "normal comment" - * @returns {string} returns a commented version of string - */ - static toNormalComment(str) { - if (!str) return ""; - return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`; - } + this._cachedDeprecatedFileTimestamps = undefined; + this._cachedDeprecatedContextTimestamps = undefined; - /** - * @param {string} str string path to be normalized - * @returns {string} normalized bundle-safe path - */ - static toPath(str) { - if (typeof str !== "string") return ""; - return str - .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-") - .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, ""); + this._warnAboutExperimentalEsmTracking = false; + + this._statCreatedSnapshots = 0; + this._statTestedSnapshotsCached = 0; + this._statTestedSnapshotsNotCached = 0; + this._statTestedChildrenCached = 0; + this._statTestedChildrenNotCached = 0; + this._statTestedEntries = 0; } - // map number to a single character a-z, A-Z or multiple characters if number is too big - /** - * @param {number} n number to convert to ident - * @returns {string} returns single character ident - */ - static numberToIdentifier(n) { - if (n >= NUMBER_OF_IDENTIFIER_START_CHARS) { - // use multiple letters - return ( - Template.numberToIdentifier(n % NUMBER_OF_IDENTIFIER_START_CHARS) + - Template.numberToIdentifierContinuation( - Math.floor(n / NUMBER_OF_IDENTIFIER_START_CHARS) + logStatistics() { + const logWhenMessage = (header, message) => { + if (message) { + this.logger.log(`${header}: ${message}`); + } + }; + this.logger.log(`${this._statCreatedSnapshots} new snapshots created`); + this.logger.log( + `${ + this._statTestedSnapshotsNotCached && + Math.round( + (this._statTestedSnapshotsNotCached * 100) / + (this._statTestedSnapshotsCached + + this._statTestedSnapshotsNotCached) + ) + }% root snapshot uncached (${this._statTestedSnapshotsNotCached} / ${ + this._statTestedSnapshotsCached + this._statTestedSnapshotsNotCached + })` + ); + this.logger.log( + `${ + this._statTestedChildrenNotCached && + Math.round( + (this._statTestedChildrenNotCached * 100) / + (this._statTestedChildrenCached + this._statTestedChildrenNotCached) ) + }% children snapshot uncached (${this._statTestedChildrenNotCached} / ${ + this._statTestedChildrenCached + this._statTestedChildrenNotCached + })` + ); + this.logger.log(`${this._statTestedEntries} entries tested`); + this.logger.log( + `File info in cache: ${this._fileTimestamps.size} timestamps ${this._fileHashes.size} hashes ${this._fileTshs.size} timestamp hash combinations` + ); + logWhenMessage( + `File timestamp snapshot optimization`, + this._fileTimestampsOptimization.getStatisticMessage() + ); + logWhenMessage( + `File hash snapshot optimization`, + this._fileHashesOptimization.getStatisticMessage() + ); + logWhenMessage( + `File timestamp hash combination snapshot optimization`, + this._fileTshsOptimization.getStatisticMessage() + ); + this.logger.log( + `Directory info in cache: ${this._contextTimestamps.size} timestamps ${this._contextHashes.size} hashes ${this._contextTshs.size} timestamp hash combinations` + ); + logWhenMessage( + `Directory timestamp snapshot optimization`, + this._contextTimestampsOptimization.getStatisticMessage() + ); + logWhenMessage( + `Directory hash snapshot optimization`, + this._contextHashesOptimization.getStatisticMessage() + ); + logWhenMessage( + `Directory timestamp hash combination snapshot optimization`, + this._contextTshsOptimization.getStatisticMessage() + ); + logWhenMessage( + `Missing items snapshot optimization`, + this._missingExistenceOptimization.getStatisticMessage() + ); + this.logger.log( + `Managed items info in cache: ${this._managedItems.size} items` + ); + logWhenMessage( + `Managed items snapshot optimization`, + this._managedItemInfoOptimization.getStatisticMessage() + ); + logWhenMessage( + `Managed files snapshot optimization`, + this._managedFilesOptimization.getStatisticMessage() + ); + logWhenMessage( + `Managed contexts snapshot optimization`, + this._managedContextsOptimization.getStatisticMessage() + ); + logWhenMessage( + `Managed missing snapshot optimization`, + this._managedMissingOptimization.getStatisticMessage() + ); + } + + _log(path, reason, ...args) { + const key = path + reason; + if (this._loggedPaths.has(key)) return; + this._loggedPaths.add(key); + this.logger.debug(`${path} invalidated because ${reason}`, ...args); + if (--this._remainingLogs === 0) { + this.logger.debug( + "Logging limit has been reached and no further logging will be emitted by FileSystemInfo" ); } + } - // lower case - if (n < DELTA_A_TO_Z) { - return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); - } - n -= DELTA_A_TO_Z; + clear() { + this._remainingLogs = this.logger ? 40 : 0; + if (this._loggedPaths !== undefined) this._loggedPaths.clear(); - // upper case - if (n < DELTA_A_TO_Z) { - return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); - } + this._snapshotCache = new WeakMap(); + this._fileTimestampsOptimization.clear(); + this._fileHashesOptimization.clear(); + this._fileTshsOptimization.clear(); + this._contextTimestampsOptimization.clear(); + this._contextHashesOptimization.clear(); + this._contextTshsOptimization.clear(); + this._missingExistenceOptimization.clear(); + this._managedItemInfoOptimization.clear(); + this._managedFilesOptimization.clear(); + this._managedContextsOptimization.clear(); + this._managedMissingOptimization.clear(); + this._fileTimestamps.clear(); + this._fileHashes.clear(); + this._fileTshs.clear(); + this._contextTimestamps.clear(); + this._contextHashes.clear(); + this._contextTshs.clear(); + this._managedItems.clear(); + this._managedItems.clear(); - if (n === DELTA_A_TO_Z) return "_"; - return "$"; + this._cachedDeprecatedFileTimestamps = undefined; + this._cachedDeprecatedContextTimestamps = undefined; + + this._statCreatedSnapshots = 0; + this._statTestedSnapshotsCached = 0; + this._statTestedSnapshotsNotCached = 0; + this._statTestedChildrenCached = 0; + this._statTestedChildrenNotCached = 0; + this._statTestedEntries = 0; } /** - * @param {number} n number to convert to ident - * @returns {string} returns single character ident + * @param {ReadonlyMap} map timestamps + * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it + * @returns {void} */ - static numberToIdentifierContinuation(n) { - if (n >= NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) { - // use multiple letters - return ( - Template.numberToIdentifierContinuation( - n % NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS - ) + - Template.numberToIdentifierContinuation( - Math.floor(n / NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) - ) - ); - } - - // lower case - if (n < DELTA_A_TO_Z) { - return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); - } - n -= DELTA_A_TO_Z; - - // upper case - if (n < DELTA_A_TO_Z) { - return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); - } - n -= DELTA_A_TO_Z; - - // numbers - if (n < 10) { - return `${n}`; - } - - if (n === 10) return "_"; - return "$"; + addFileTimestamps(map, immutable) { + this._fileTimestamps.addAll(map, immutable); + this._cachedDeprecatedFileTimestamps = undefined; } /** - * - * @param {string | string[]} s string to convert to identity - * @returns {string} converted identity + * @param {ReadonlyMap} map timestamps + * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it + * @returns {void} */ - static indent(s) { - if (Array.isArray(s)) { - return s.map(Template.indent).join("\n"); - } else { - const str = s.trimRight(); - if (!str) return ""; - const ind = str[0] === "\n" ? "" : "\t"; - return ind + str.replace(/\n([^\n])/g, "\n\t$1"); - } + addContextTimestamps(map, immutable) { + this._contextTimestamps.addAll(map, immutable); + this._cachedDeprecatedContextTimestamps = undefined; } /** - * - * @param {string|string[]} s string to create prefix for - * @param {string} prefix prefix to compose - * @returns {string} returns new prefix string + * @param {string} path file path + * @param {function((WebpackError | null)=, (FileSystemInfoEntry | "ignore" | null)=): void} callback callback function + * @returns {void} */ - static prefix(s, prefix) { - const str = Template.asString(s).trim(); - if (!str) return ""; - const ind = str[0] === "\n" ? "" : prefix; - return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); + getFileTimestamp(path, callback) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) return callback(null, cache); + this.fileTimestampQueue.add(path, callback); } /** - * - * @param {string|string[]} str string or string collection - * @returns {string} returns a single string from array + * @param {string} path context path + * @param {function((WebpackError | null)=, (ResolvedContextFileSystemInfoEntry | "ignore" | null)=): void} callback callback function + * @returns {void} */ - static asString(str) { - if (Array.isArray(str)) { - return str.join("\n"); + getContextTimestamp(path, callback) { + const cache = this._contextTimestamps.get(path); + if (cache !== undefined) { + if (cache === "ignore") return callback(null, "ignore"); + const resolved = getResolvedTimestamp(cache); + if (resolved !== undefined) return callback(null, resolved); + return this._resolveContextTimestamp(cache, callback); } - return str; + this.contextTimestampQueue.add(path, (err, entry) => { + if (err) return callback(err); + const resolved = getResolvedTimestamp(entry); + if (resolved !== undefined) return callback(null, resolved); + this._resolveContextTimestamp(entry, callback); + }); } /** - * @typedef {Object} WithId - * @property {string|number} id + * @param {string} path context path + * @param {function((WebpackError | null)=, (ContextFileSystemInfoEntry | "ignore" | null)=): void} callback callback function + * @returns {void} */ + _getUnresolvedContextTimestamp(path, callback) { + const cache = this._contextTimestamps.get(path); + if (cache !== undefined) return callback(null, cache); + this.contextTimestampQueue.add(path, callback); + } /** - * @param {WithId[]} modules a collection of modules to get array bounds for - * @returns {[number, number] | false} returns the upper and lower array bounds - * or false if not every module has a number based id + * @param {string} path file path + * @param {function((WebpackError | null)=, string=): void} callback callback function + * @returns {void} */ - static getModulesArrayBounds(modules) { - let maxId = -Infinity; - let minId = Infinity; - for (const module of modules) { - const moduleId = module.id; - if (typeof moduleId !== "number") return false; - if (maxId < moduleId) maxId = moduleId; - if (minId > moduleId) minId = moduleId; - } - if (minId < 16 + ("" + minId).length) { - // add minId x ',' instead of 'Array(minId).concat(…)' - minId = 0; - } - // start with -1 because the first module needs no comma - let objectOverhead = -1; - for (const module of modules) { - // module id + colon + comma - objectOverhead += `${module.id}`.length + 2; - } - // number of commas, or when starting non-zero the length of Array(minId).concat() - const arrayOverhead = minId === 0 ? maxId : 16 + `${minId}`.length + maxId; - return arrayOverhead < objectOverhead ? [minId, maxId] : false; + getFileHash(path, callback) { + const cache = this._fileHashes.get(path); + if (cache !== undefined) return callback(null, cache); + this.fileHashQueue.add(path, callback); } /** - * @param {ChunkRenderContext} renderContext render context - * @param {Module[]} modules modules to render (should be ordered by identifier) - * @param {function(Module): Source} renderModule function to render a module - * @param {string=} prefix applying prefix strings - * @returns {Source} rendered chunk modules in a Source object + * @param {string} path context path + * @param {function((WebpackError | null)=, string=): void} callback callback function + * @returns {void} */ - static renderChunkModules(renderContext, modules, renderModule, prefix = "") { - const { chunkGraph } = renderContext; - var source = new ConcatSource(); - if (modules.length === 0) { - return null; + getContextHash(path, callback) { + const cache = this._contextHashes.get(path); + if (cache !== undefined) { + const resolved = getResolvedHash(cache); + if (resolved !== undefined) return callback(null, resolved); + return this._resolveContextHash(cache, callback); } - /** @type {{id: string|number, source: Source|string}[]} */ - const allModules = modules.map(module => { - return { - id: chunkGraph.getModuleId(module), - source: renderModule(module) || "false" - }; + this.contextHashQueue.add(path, (err, entry) => { + if (err) return callback(err); + const resolved = getResolvedHash(entry); + if (resolved !== undefined) return callback(null, resolved); + this._resolveContextHash(entry, callback); }); - const bounds = Template.getModulesArrayBounds(allModules); - if (bounds) { - // Render a spare array - const minId = bounds[0]; - const maxId = bounds[1]; - if (minId !== 0) { - source.add(`Array(${minId}).concat(`); - } - source.add("[\n"); - /** @type {Map} */ - const modules = new Map(); - for (const module of allModules) { - modules.set(module.id, module); - } - for (let idx = minId; idx <= maxId; idx++) { - const module = modules.get(idx); - if (idx !== minId) { - source.add(",\n"); - } - source.add(`/* ${idx} */`); - if (module) { - source.add("\n"); - source.add(module.source); - } - } - source.add("\n" + prefix + "]"); - if (minId !== 0) { - source.add(")"); - } - } else { - // Render an object - source.add("{\n"); - for (let i = 0; i < allModules.length; i++) { - const module = allModules[i]; - if (i !== 0) { - source.add(",\n"); - } - source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`); - source.add(module.source); - } - source.add(`\n\n${prefix}}`); - } - return source; } /** - * @param {RuntimeModule[]} runtimeModules array of runtime modules in order - * @param {RenderContext & { codeGenerationResults?: CodeGenerationResults }} renderContext render context - * @returns {Source} rendered runtime modules in a Source object + * @param {string} path context path + * @param {function((WebpackError | null)=, ContextHash=): void} callback callback function + * @returns {void} */ - static renderRuntimeModules(runtimeModules, renderContext) { - const source = new ConcatSource(); - for (const module of runtimeModules) { - const codeGenerationResults = renderContext.codeGenerationResults; - let runtimeSource; - if (codeGenerationResults) { - runtimeSource = codeGenerationResults.getSource( - module, - renderContext.chunk.runtime, - "runtime" - ); - } else { - const codeGenResult = module.codeGeneration({ - chunkGraph: renderContext.chunkGraph, - dependencyTemplates: renderContext.dependencyTemplates, - moduleGraph: renderContext.moduleGraph, - runtimeTemplate: renderContext.runtimeTemplate, - runtime: renderContext.chunk.runtime, - codeGenerationResults - }); - if (!codeGenResult) continue; - runtimeSource = codeGenResult.sources.get("runtime"); - } - if (runtimeSource) { - source.add(Template.toNormalComment(module.identifier()) + "\n"); - if (!module.shouldIsolate()) { - source.add(runtimeSource); - source.add("\n\n"); - } else if (renderContext.runtimeTemplate.supportsArrowFunction()) { - source.add("(() => {\n"); - source.add(new PrefixSource("\t", runtimeSource)); - source.add("\n})();\n\n"); - } else { - source.add("!function() {\n"); - source.add(new PrefixSource("\t", runtimeSource)); - source.add("\n}();\n\n"); - } - } - } - return source; + _getUnresolvedContextHash(path, callback) { + const cache = this._contextHashes.get(path); + if (cache !== undefined) return callback(null, cache); + this.contextHashQueue.add(path, callback); } /** - * @param {RuntimeModule[]} runtimeModules array of runtime modules in order - * @param {RenderContext} renderContext render context - * @returns {Source} rendered chunk runtime modules in a Source object + * @param {string} path context path + * @param {function((WebpackError | null)=, ResolvedContextTimestampAndHash=): void} callback callback function + * @returns {void} */ - static renderChunkRuntimeModules(runtimeModules, renderContext) { - return new PrefixSource( - "/******/ ", - new ConcatSource( - "function(__webpack_require__) { // webpackRuntimeModules\n", - this.renderRuntimeModules(runtimeModules, renderContext), - "}\n" - ) - ); - } -} - -module.exports = Template; -module.exports.NUMBER_OF_IDENTIFIER_START_CHARS = - NUMBER_OF_IDENTIFIER_START_CHARS; -module.exports.NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS = - NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS; - - -/***/ }), - -/***/ 80734: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Jason Anderson @diurnalist -*/ - - - -const { basename, extname } = __webpack_require__(71017); -const util = __webpack_require__(73837); -const Chunk = __webpack_require__(39385); -const Module = __webpack_require__(73208); -const { parseResource } = __webpack_require__(82186); - -/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("./Compilation").PathData} PathData */ -/** @typedef {import("./Compiler")} Compiler */ - -const REGEXP = /\[\\*([\w:]+)\\*\]/gi; - -const prepareId = id => { - if (typeof id !== "string") return id; - - if (/^"\s\+*.*\+\s*"$/.test(id)) { - const match = /^"\s\+*\s*(.*)\s*\+\s*"$/.exec(id); - - return `" + (${match[1]} + "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_") + "`; - } - - return id.replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_"); -}; - -const hashLength = (replacer, handler, assetInfo, hashName) => { - const fn = (match, arg, input) => { - let result; - const length = arg && parseInt(arg, 10); - - if (length && handler) { - result = handler(length); - } else { - const hash = replacer(match, arg, input); - - result = length ? hash.slice(0, length) : hash; - } - if (assetInfo) { - assetInfo.immutable = true; - if (Array.isArray(assetInfo[hashName])) { - assetInfo[hashName] = [...assetInfo[hashName], result]; - } else if (assetInfo[hashName]) { - assetInfo[hashName] = [assetInfo[hashName], result]; - } else { - assetInfo[hashName] = result; - } - } - return result; - }; - - return fn; -}; - -const replacer = (value, allowEmpty) => { - const fn = (match, arg, input) => { - if (typeof value === "function") { - value = value(); - } - if (value === null || value === undefined) { - if (!allowEmpty) { - throw new Error( - `Path variable ${match} not implemented in this context: ${input}` - ); - } - - return ""; - } else { - return `${value}`; + getContextTsh(path, callback) { + const cache = this._contextTshs.get(path); + if (cache !== undefined) { + const resolved = getResolvedTimestamp(cache); + if (resolved !== undefined) return callback(null, resolved); + return this._resolveContextTsh(cache, callback); } - }; - - return fn; -}; - -const deprecationCache = new Map(); -const deprecatedFunction = (() => () => {})(); -const deprecated = (fn, message, code) => { - let d = deprecationCache.get(message); - if (d === undefined) { - d = util.deprecate(deprecatedFunction, message, code); - deprecationCache.set(message, d); - } - return (...args) => { - d(); - return fn(...args); - }; -}; - -/** - * @param {string | function(PathData, AssetInfo=): string} path the raw path - * @param {PathData} data context data - * @param {AssetInfo} assetInfo extra info about the asset (will be written to) - * @returns {string} the interpolated path - */ -const replacePathVariables = (path, data, assetInfo) => { - const chunkGraph = data.chunkGraph; - - /** @type {Map} */ - const replacements = new Map(); - - // Filename context - // - // Placeholders - // - // for /some/path/file.js?query#fragment: - // [file] - /some/path/file.js - // [query] - ?query - // [fragment] - #fragment - // [base] - file.js - // [path] - /some/path/ - // [name] - file - // [ext] - .js - if (typeof data.filename === "string") { - const { path: file, query, fragment } = parseResource(data.filename); - - const ext = extname(file); - const base = basename(file); - const name = base.slice(0, base.length - ext.length); - const path = file.slice(0, file.length - base.length); - - replacements.set("file", replacer(file)); - replacements.set("query", replacer(query, true)); - replacements.set("fragment", replacer(fragment, true)); - replacements.set("path", replacer(path, true)); - replacements.set("base", replacer(base)); - replacements.set("name", replacer(name)); - replacements.set("ext", replacer(ext, true)); - // Legacy - replacements.set( - "filebase", - deprecated( - replacer(base), - "[filebase] is now [base]", - "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME" - ) - ); - } - - // Compilation context - // - // Placeholders - // - // [fullhash] - data.hash (3a4b5c6e7f) - // - // Legacy Placeholders - // - // [hash] - data.hash (3a4b5c6e7f) - if (data.hash) { - const hashReplacer = hashLength( - replacer(data.hash), - data.hashWithLength, - assetInfo, - "fullhash" - ); - - replacements.set("fullhash", hashReplacer); - - // Legacy - replacements.set( - "hash", - deprecated( - hashReplacer, - "[hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)", - "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH" - ) - ); - } - - // Chunk Context - // - // Placeholders - // - // [id] - chunk.id (0.js) - // [name] - chunk.name (app.js) - // [chunkhash] - chunk.hash (7823t4t4.js) - // [contenthash] - chunk.contentHash[type] (3256u3zg.js) - if (data.chunk) { - const chunk = data.chunk; - - const contentHashType = data.contentHashType; - - const idReplacer = replacer(chunk.id); - const nameReplacer = replacer(chunk.name || chunk.id); - const chunkhashReplacer = hashLength( - replacer(chunk instanceof Chunk ? chunk.renderedHash : chunk.hash), - "hashWithLength" in chunk ? chunk.hashWithLength : undefined, - assetInfo, - "chunkhash" - ); - const contenthashReplacer = hashLength( - replacer( - data.contentHash || - (contentHashType && - chunk.contentHash && - chunk.contentHash[contentHashType]) - ), - data.contentHashWithLength || - ("contentHashWithLength" in chunk && chunk.contentHashWithLength - ? chunk.contentHashWithLength[contentHashType] - : undefined), - assetInfo, - "contenthash" - ); - - replacements.set("id", idReplacer); - replacements.set("name", nameReplacer); - replacements.set("chunkhash", chunkhashReplacer); - replacements.set("contenthash", contenthashReplacer); - } - - // Module Context - // - // Placeholders - // - // [id] - module.id (2.png) - // [hash] - module.hash (6237543873.png) - // - // Legacy Placeholders - // - // [moduleid] - module.id (2.png) - // [modulehash] - module.hash (6237543873.png) - if (data.module) { - const module = data.module; - - const idReplacer = replacer(() => - prepareId( - module instanceof Module ? chunkGraph.getModuleId(module) : module.id - ) - ); - const moduleHashReplacer = hashLength( - replacer(() => - module instanceof Module - ? chunkGraph.getRenderedModuleHash(module, data.runtime) - : module.hash - ), - "hashWithLength" in module ? module.hashWithLength : undefined, - assetInfo, - "modulehash" - ); - const contentHashReplacer = hashLength( - replacer(data.contentHash), - undefined, - assetInfo, - "contenthash" - ); - - replacements.set("id", idReplacer); - replacements.set("modulehash", moduleHashReplacer); - replacements.set("contenthash", contentHashReplacer); - replacements.set( - "hash", - data.contentHash ? contentHashReplacer : moduleHashReplacer - ); - // Legacy - replacements.set( - "moduleid", - deprecated( - idReplacer, - "[moduleid] is now [id]", - "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_MODULE_ID" - ) - ); + this.contextTshQueue.add(path, (err, entry) => { + if (err) return callback(err); + const resolved = getResolvedTimestamp(entry); + if (resolved !== undefined) return callback(null, resolved); + this._resolveContextTsh(entry, callback); + }); } - // Other things - if (data.url) { - replacements.set("url", replacer(data.url)); - } - if (typeof data.runtime === "string") { - replacements.set( - "runtime", - replacer(() => prepareId(data.runtime)) - ); - } else { - replacements.set("runtime", replacer("_")); + /** + * @param {string} path context path + * @param {function((WebpackError | null)=, ContextTimestampAndHash=): void} callback callback function + * @returns {void} + */ + _getUnresolvedContextTsh(path, callback) { + const cache = this._contextTshs.get(path); + if (cache !== undefined) return callback(null, cache); + this.contextTshQueue.add(path, callback); } - if (typeof path === "function") { - path = path(data, assetInfo); + _createBuildDependenciesResolvers() { + const resolveContext = createResolver({ + resolveToContext: true, + exportsFields: [], + fileSystem: this.fs + }); + const resolveCjs = createResolver({ + extensions: [".js", ".json", ".node"], + conditionNames: ["require", "node"], + exportsFields: ["exports"], + fileSystem: this.fs + }); + const resolveCjsAsChild = createResolver({ + extensions: [".js", ".json", ".node"], + conditionNames: ["require", "node"], + exportsFields: [], + fileSystem: this.fs + }); + const resolveEsm = createResolver({ + extensions: [".js", ".json", ".node"], + fullySpecified: true, + conditionNames: ["import", "node"], + exportsFields: ["exports"], + fileSystem: this.fs + }); + return { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild }; } - path = path.replace(REGEXP, (match, content) => { - if (content.length + 2 === match.length) { - const contentMatch = /^(\w+)(?::(\w+))?$/.exec(content); - if (!contentMatch) return match; - const [, kind, arg] = contentMatch; - const replacer = replacements.get(kind); - if (replacer !== undefined) { - return replacer(match, arg, path); - } - } else if (match.startsWith("[\\") && match.endsWith("\\]")) { - return `[${match.slice(2, -2)}]`; - } - return match; - }); - - return path; -}; - -const plugin = "TemplatedPathPlugin"; - -class TemplatedPathPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {string} context context directory + * @param {Iterable} deps dependencies + * @param {function((Error | null)=, ResolveBuildDependenciesResult=): void} callback callback function * @returns {void} */ - apply(compiler) { - compiler.hooks.compilation.tap(plugin, compilation => { - compilation.hooks.assetPath.tap(plugin, replacePathVariables); - }); - } -} - -module.exports = TemplatedPathPlugin; - - -/***/ }), - -/***/ 68099: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + resolveBuildDependencies(context, deps, callback) { + const { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild } = + this._createBuildDependenciesResolvers(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - - - -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); - -class UnhandledSchemeError extends WebpackError { - /** - * @param {string} scheme scheme - * @param {string} resource resource - */ - constructor(scheme, resource) { - super( - `Reading from "${resource}" is not handled by plugins (Unhandled scheme).` + - '\nWebpack supports "data:" and "file:" URIs by default.' + - `\nYou may need an additional plugin to handle "${scheme}:" URIs.` - ); - this.file = resource; - this.name = "UnhandledSchemeError"; - } -} - -makeSerializable( - UnhandledSchemeError, - "webpack/lib/UnhandledSchemeError", - "UnhandledSchemeError" -); - -module.exports = UnhandledSchemeError; - - -/***/ }), - -/***/ 42495: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); - -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ - -class UnsupportedFeatureWarning extends WebpackError { - /** - * @param {string} message description of warning - * @param {DependencyLocation} loc location start and end positions of the module - */ - constructor(message, loc) { - super(message); - - this.name = "UnsupportedFeatureWarning"; - this.loc = loc; - this.hideStack = true; - } -} - -makeSerializable( - UnsupportedFeatureWarning, - "webpack/lib/UnsupportedFeatureWarning" -); - -module.exports = UnsupportedFeatureWarning; - - -/***/ }), - -/***/ 36803: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const ConstDependency = __webpack_require__(76911); - -/** @typedef {import("./Compiler")} Compiler */ - -class UseStrictPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "UseStrictPlugin", - (compilation, { normalModuleFactory }) => { - const handler = parser => { - parser.hooks.program.tap("UseStrictPlugin", ast => { - const firstNode = ast.body[0]; - if ( - firstNode && - firstNode.type === "ExpressionStatement" && - firstNode.expression.type === "Literal" && - firstNode.expression.value === "use strict" - ) { - // Remove "use strict" expression. It will be added later by the renderer again. - // This is necessary in order to not break the strict mode when webpack prepends code. - // @see https://github.com/webpack/webpack/issues/1970 - const dep = new ConstDependency("", firstNode.range); - dep.loc = firstNode.loc; - parser.state.module.addPresentationalDependency(dep); - parser.state.module.buildInfo.strict = true; + /** @type {Set} */ + const files = new Set(); + /** @type {Set} */ + const fileSymlinks = new Set(); + /** @type {Set} */ + const directories = new Set(); + /** @type {Set} */ + const directorySymlinks = new Set(); + /** @type {Set} */ + const missing = new Set(); + /** @type {Set} */ + const resolveFiles = new Set(); + /** @type {Set} */ + const resolveDirectories = new Set(); + /** @type {Set} */ + const resolveMissing = new Set(); + /** @type {Map} */ + const resolveResults = new Map(); + const invalidResolveResults = new Set(); + const resolverContext = { + fileDependencies: resolveFiles, + contextDependencies: resolveDirectories, + missingDependencies: resolveMissing + }; + const expectedToString = expected => { + return expected ? ` (expected ${expected})` : ""; + }; + const jobToString = job => { + switch (job.type) { + case RBDT_RESOLVE_CJS: + return `resolve commonjs ${job.path}${expectedToString( + job.expected + )}`; + case RBDT_RESOLVE_ESM: + return `resolve esm ${job.path}${expectedToString(job.expected)}`; + case RBDT_RESOLVE_DIRECTORY: + return `resolve directory ${job.path}`; + case RBDT_RESOLVE_CJS_FILE: + return `resolve commonjs file ${job.path}${expectedToString( + job.expected + )}`; + case RBDT_RESOLVE_ESM_FILE: + return `resolve esm file ${job.path}${expectedToString( + job.expected + )}`; + case RBDT_DIRECTORY: + return `directory ${job.path}`; + case RBDT_FILE: + return `file ${job.path}`; + case RBDT_DIRECTORY_DEPENDENCIES: + return `directory dependencies ${job.path}`; + case RBDT_FILE_DEPENDENCIES: + return `file dependencies ${job.path}`; + } + return `unknown ${job.type} ${job.path}`; + }; + const pathToString = job => { + let result = ` at ${jobToString(job)}`; + job = job.issuer; + while (job !== undefined) { + result += `\n at ${jobToString(job)}`; + job = job.issuer; + } + return result; + }; + processAsyncTree( + Array.from(deps, dep => ({ + type: RBDT_RESOLVE_CJS, + context, + path: dep, + expected: undefined, + issuer: undefined + })), + 20, + (job, push, callback) => { + const { type, context, path, expected } = job; + const resolveDirectory = path => { + const key = `d\n${context}\n${path}`; + if (resolveResults.has(key)) { + return callback(); + } + resolveResults.set(key, undefined); + resolveContext(context, path, resolverContext, (err, _, result) => { + if (err) { + if (expected === false) { + resolveResults.set(key, false); + return callback(); + } + invalidResolveResults.add(key); + err.message += `\nwhile resolving '${path}' in ${context} to a directory`; + return callback(err); } + const resultPath = result.path; + resolveResults.set(key, resultPath); + push({ + type: RBDT_DIRECTORY, + context: undefined, + path: resultPath, + expected: undefined, + issuer: job + }); + callback(); }); }; - - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("UseStrictPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("UseStrictPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("UseStrictPlugin", handler); - } - ); - } -} - -module.exports = UseStrictPlugin; - - -/***/ }), - -/***/ 56504: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const CaseSensitiveModulesWarning = __webpack_require__(77975); - -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Module")} Module */ - -class WarnCaseSensitiveModulesPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "WarnCaseSensitiveModulesPlugin", - compilation => { - compilation.hooks.seal.tap("WarnCaseSensitiveModulesPlugin", () => { - /** @type {Map>} */ - const moduleWithoutCase = new Map(); - for (const module of compilation.modules) { - const identifier = module.identifier(); - const lowerIdentifier = identifier.toLowerCase(); - let map = moduleWithoutCase.get(lowerIdentifier); - if (map === undefined) { - map = new Map(); - moduleWithoutCase.set(lowerIdentifier, map); + const resolveFile = (path, symbol, resolve) => { + const key = `${symbol}\n${context}\n${path}`; + if (resolveResults.has(key)) { + return callback(); + } + resolveResults.set(key, undefined); + resolve(context, path, resolverContext, (err, _, result) => { + if (typeof expected === "string") { + if (!err && result && result.path === expected) { + resolveResults.set(key, result.path); + } else { + invalidResolveResults.add(key); + this.logger.warn( + `Resolving '${path}' in ${context} for build dependencies doesn't lead to expected result '${expected}', but to '${ + err || (result && result.path) + }' instead. Resolving dependencies are ignored for this path.\n${pathToString( + job + )}` + ); + } + } else { + if (err) { + if (expected === false) { + resolveResults.set(key, false); + return callback(); + } + invalidResolveResults.add(key); + err.message += `\nwhile resolving '${path}' in ${context} as file\n${pathToString( + job + )}`; + return callback(err); + } + const resultPath = result.path; + resolveResults.set(key, resultPath); + push({ + type: RBDT_FILE, + context: undefined, + path: resultPath, + expected: undefined, + issuer: job + }); } - map.set(identifier, module); + callback(); + }); + }; + switch (type) { + case RBDT_RESOLVE_CJS: { + const isDirectory = /[\\/]$/.test(path); + if (isDirectory) { + resolveDirectory(path.slice(0, path.length - 1)); + } else { + resolveFile(path, "f", resolveCjs); + } + break; } - for (const pair of moduleWithoutCase) { - const map = pair[1]; - if (map.size > 1) { - compilation.warnings.push( - new CaseSensitiveModulesWarning( - map.values(), - compilation.moduleGraph - ) + case RBDT_RESOLVE_ESM: { + const isDirectory = /[\\/]$/.test(path); + if (isDirectory) { + resolveDirectory(path.slice(0, path.length - 1)); + } else { + resolveFile(path); + } + break; + } + case RBDT_RESOLVE_DIRECTORY: { + resolveDirectory(path); + break; + } + case RBDT_RESOLVE_CJS_FILE: { + resolveFile(path, "f", resolveCjs); + break; + } + case RBDT_RESOLVE_CJS_FILE_AS_CHILD: { + resolveFile(path, "c", resolveCjsAsChild); + break; + } + case RBDT_RESOLVE_ESM_FILE: { + resolveFile(path, "e", resolveEsm); + break; + } + case RBDT_FILE: { + if (files.has(path)) { + callback(); + break; + } + files.add(path); + this.fs.realpath(path, (err, _realPath) => { + if (err) return callback(err); + const realPath = /** @type {string} */ (_realPath); + if (realPath !== path) { + fileSymlinks.add(path); + resolveFiles.add(path); + if (files.has(realPath)) return callback(); + files.add(realPath); + } + push({ + type: RBDT_FILE_DEPENDENCIES, + context: undefined, + path: realPath, + expected: undefined, + issuer: job + }); + callback(); + }); + break; + } + case RBDT_DIRECTORY: { + if (directories.has(path)) { + callback(); + break; + } + directories.add(path); + this.fs.realpath(path, (err, _realPath) => { + if (err) return callback(err); + const realPath = /** @type {string} */ (_realPath); + if (realPath !== path) { + directorySymlinks.add(path); + resolveFiles.add(path); + if (directories.has(realPath)) return callback(); + directories.add(realPath); + } + push({ + type: RBDT_DIRECTORY_DEPENDENCIES, + context: undefined, + path: realPath, + expected: undefined, + issuer: job + }); + callback(); + }); + break; + } + case RBDT_FILE_DEPENDENCIES: { + // Check for known files without dependencies + if (/\.json5?$|\.yarn-integrity$|yarn\.lock$|\.ya?ml/.test(path)) { + process.nextTick(callback); + break; + } + // Check commonjs cache for the module + /** @type {NodeModule} */ + const module = require.cache[path]; + if (module && Array.isArray(module.children)) { + children: for (const child of module.children) { + let childPath = child.filename; + if (childPath) { + push({ + type: RBDT_FILE, + context: undefined, + path: childPath, + expected: undefined, + issuer: job + }); + const context = dirname(this.fs, path); + for (const modulePath of module.paths) { + if (childPath.startsWith(modulePath)) { + let subPath = childPath.slice(modulePath.length + 1); + const packageMatch = /^(@[^\\/]+[\\/])[^\\/]+/.exec( + subPath + ); + if (packageMatch) { + push({ + type: RBDT_FILE, + context: undefined, + path: + modulePath + + childPath[modulePath.length] + + packageMatch[0] + + childPath[modulePath.length] + + "package.json", + expected: false, + issuer: job + }); + } + let request = subPath.replace(/\\/g, "/"); + if (request.endsWith(".js")) + request = request.slice(0, -3); + push({ + type: RBDT_RESOLVE_CJS_FILE_AS_CHILD, + context, + path: request, + expected: child.filename, + issuer: job + }); + continue children; + } + } + let request = relative(this.fs, context, childPath); + if (request.endsWith(".js")) request = request.slice(0, -3); + request = request.replace(/\\/g, "/"); + if (!request.startsWith("../")) request = `./${request}`; + push({ + type: RBDT_RESOLVE_CJS_FILE, + context, + path: request, + expected: child.filename, + issuer: job + }); + } + } + } else if (supportsEsm && /\.m?js$/.test(path)) { + if (!this._warnAboutExperimentalEsmTracking) { + this.logger.log( + "Node.js doesn't offer a (nice) way to introspect the ESM dependency graph yet.\n" + + "Until a full solution is available webpack uses an experimental ESM tracking based on parsing.\n" + + "As best effort webpack parses the ESM files to guess dependencies. But this can lead to expensive and incorrect tracking." + ); + this._warnAboutExperimentalEsmTracking = true; + } + const lexer = __webpack_require__(54392); + lexer.init.then(() => { + this.fs.readFile(path, (err, content) => { + if (err) return callback(err); + try { + const context = dirname(this.fs, path); + const source = content.toString(); + const [imports] = lexer.parse(source); + for (const imp of imports) { + try { + let dependency; + if (imp.d === -1) { + // import ... from "..." + dependency = parseString( + source.substring(imp.s - 1, imp.e + 1) + ); + } else if (imp.d > -1) { + // import() + let expr = source.substring(imp.s, imp.e).trim(); + dependency = parseString(expr); + } else { + // e.g. import.meta + continue; + } + push({ + type: RBDT_RESOLVE_ESM_FILE, + context, + path: dependency, + expected: undefined, + issuer: job + }); + } catch (e) { + this.logger.warn( + `Parsing of ${path} for build dependencies failed at 'import(${source.substring( + imp.s, + imp.e + )})'.\n` + + "Build dependencies behind this expression are ignored and might cause incorrect cache invalidation." + ); + this.logger.debug(pathToString(job)); + this.logger.debug(e.stack); + } + } + } catch (e) { + this.logger.warn( + `Parsing of ${path} for build dependencies failed and all dependencies of this file are ignored, which might cause incorrect cache invalidation..` + ); + this.logger.debug(pathToString(job)); + this.logger.debug(e.stack); + } + process.nextTick(callback); + }); + }, callback); + break; + } else { + this.logger.log( + `Assuming ${path} has no dependencies as we were unable to assign it to any module system.` ); + this.logger.debug(pathToString(job)); } + process.nextTick(callback); + break; + } + case RBDT_DIRECTORY_DEPENDENCIES: { + const match = + /(^.+[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+)/.exec(path); + const packagePath = match ? match[1] : path; + const packageJson = join(this.fs, packagePath, "package.json"); + this.fs.readFile(packageJson, (err, content) => { + if (err) { + if (err.code === "ENOENT") { + resolveMissing.add(packageJson); + const parent = dirname(this.fs, packagePath); + if (parent !== packagePath) { + push({ + type: RBDT_DIRECTORY_DEPENDENCIES, + context: undefined, + path: parent, + expected: undefined, + issuer: job + }); + } + callback(); + return; + } + return callback(err); + } + resolveFiles.add(packageJson); + let packageData; + try { + packageData = JSON.parse(content.toString("utf-8")); + } catch (e) { + return callback(e); + } + const depsObject = packageData.dependencies; + const optionalDepsObject = packageData.optionalDependencies; + const allDeps = new Set(); + const optionalDeps = new Set(); + if (typeof depsObject === "object" && depsObject) { + for (const dep of Object.keys(depsObject)) { + allDeps.add(dep); + } + } + if ( + typeof optionalDepsObject === "object" && + optionalDepsObject + ) { + for (const dep of Object.keys(optionalDepsObject)) { + allDeps.add(dep); + optionalDeps.add(dep); + } + } + for (const dep of allDeps) { + push({ + type: RBDT_RESOLVE_DIRECTORY, + context: packagePath, + path: dep, + expected: !optionalDeps.has(dep), + issuer: job + }); + } + callback(); + }); + break; + } + } + }, + err => { + if (err) return callback(err); + for (const l of fileSymlinks) files.delete(l); + for (const l of directorySymlinks) directories.delete(l); + for (const k of invalidResolveResults) resolveResults.delete(k); + callback(null, { + files, + directories, + missing, + resolveResults, + resolveDependencies: { + files: resolveFiles, + directories: resolveDirectories, + missing: resolveMissing } }); } ); } -} - -module.exports = WarnCaseSensitiveModulesPlugin; - - -/***/ }), - -/***/ 76537: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ - - - -const WebpackError = __webpack_require__(53799); - -/** @typedef {import("./Compiler")} Compiler */ - -class WarnDeprecatedOptionPlugin { - /** - * Create an instance of the plugin - * @param {string} option the target option - * @param {string | number} value the deprecated option value - * @param {string} suggestion the suggestion replacement - */ - constructor(option, value, suggestion) { - this.option = option; - this.value = value; - this.suggestion = suggestion; - } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {Map} resolveResults results from resolving + * @param {function((Error | null)=, boolean=): void} callback callback with true when resolveResults resolve the same way * @returns {void} */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "WarnDeprecatedOptionPlugin", - compilation => { - compilation.warnings.push( - new DeprecatedOptionWarning(this.option, this.value, this.suggestion) - ); + checkResolveResultsValid(resolveResults, callback) { + const { resolveCjs, resolveCjsAsChild, resolveEsm, resolveContext } = + this._createBuildDependenciesResolvers(); + asyncLib.eachLimit( + resolveResults, + 20, + ([key, expectedResult], callback) => { + const [type, context, path] = key.split("\n"); + switch (type) { + case "d": + resolveContext(context, path, {}, (err, _, result) => { + if (expectedResult === false) + return callback(err ? undefined : INVALID); + if (err) return callback(err); + const resultPath = result.path; + if (resultPath !== expectedResult) return callback(INVALID); + callback(); + }); + break; + case "f": + resolveCjs(context, path, {}, (err, _, result) => { + if (expectedResult === false) + return callback(err ? undefined : INVALID); + if (err) return callback(err); + const resultPath = result.path; + if (resultPath !== expectedResult) return callback(INVALID); + callback(); + }); + break; + case "c": + resolveCjsAsChild(context, path, {}, (err, _, result) => { + if (expectedResult === false) + return callback(err ? undefined : INVALID); + if (err) return callback(err); + const resultPath = result.path; + if (resultPath !== expectedResult) return callback(INVALID); + callback(); + }); + break; + case "e": + resolveEsm(context, path, {}, (err, _, result) => { + if (expectedResult === false) + return callback(err ? undefined : INVALID); + if (err) return callback(err); + const resultPath = result.path; + if (resultPath !== expectedResult) return callback(INVALID); + callback(); + }); + break; + default: + callback(new Error("Unexpected type in resolve result key")); + break; + } + }, + /** + * @param {Error | typeof INVALID=} err error or invalid flag + * @returns {void} + */ + err => { + if (err === INVALID) { + return callback(null, false); + } + if (err) { + return callback(err); + } + return callback(null, true); } ); } -} - -class DeprecatedOptionWarning extends WebpackError { - constructor(option, value, suggestion) { - super(); - - this.name = "DeprecatedOptionWarning"; - this.message = - "configuration\n" + - `The value '${value}' for option '${option}' is deprecated. ` + - `Use '${suggestion}' instead.`; - } -} - -module.exports = WarnDeprecatedOptionPlugin; - - -/***/ }), - -/***/ 25295: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const NoModeWarning = __webpack_require__(80832); - -/** @typedef {import("./Compiler")} Compiler */ - -class WarnNoModeSetPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * + * @param {number} startTime when processing the files has started + * @param {Iterable} files all files + * @param {Iterable} directories all directories + * @param {Iterable} missing all missing files or directories + * @param {Object} options options object (for future extensions) + * @param {boolean=} options.hash should use hash to snapshot + * @param {boolean=} options.timestamp should use timestamp to snapshot + * @param {function((WebpackError | null)=, (Snapshot | null)=): void} callback callback function * @returns {void} */ - apply(compiler) { - compiler.hooks.thisCompilation.tap("WarnNoModeSetPlugin", compilation => { - compilation.warnings.push(new NoModeWarning()); - }); - } -} - -module.exports = WarnNoModeSetPlugin; - - -/***/ }), - -/***/ 65193: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { groupBy } = __webpack_require__(84953); -const createSchemaValidation = __webpack_require__(32540); - -/** @typedef {import("../declarations/plugins/WatchIgnorePlugin").WatchIgnorePluginOptions} WatchIgnorePluginOptions */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */ - -const validate = createSchemaValidation( - __webpack_require__(16711), - () => __webpack_require__(44246), - { - name: "Watch Ignore Plugin", - baseDataPath: "options" - } -); - -const IGNORE_TIME_ENTRY = "ignore"; + createSnapshot(startTime, files, directories, missing, options, callback) { + /** @type {Map} */ + const fileTimestamps = new Map(); + /** @type {Map} */ + const fileHashes = new Map(); + /** @type {Map} */ + const fileTshs = new Map(); + /** @type {Map} */ + const contextTimestamps = new Map(); + /** @type {Map} */ + const contextHashes = new Map(); + /** @type {Map} */ + const contextTshs = new Map(); + /** @type {Map} */ + const missingExistence = new Map(); + /** @type {Map} */ + const managedItemInfo = new Map(); + /** @type {Set} */ + const managedFiles = new Set(); + /** @type {Set} */ + const managedContexts = new Set(); + /** @type {Set} */ + const managedMissing = new Set(); + /** @type {Set} */ + const children = new Set(); -class IgnoringWatchFileSystem { - /** - * @param {WatchFileSystem} wfs original file system - * @param {(string|RegExp)[]} paths ignored paths - */ - constructor(wfs, paths) { - this.wfs = wfs; - this.paths = paths; - } + const snapshot = new Snapshot(); + if (startTime) snapshot.setStartTime(startTime); - watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { - files = Array.from(files); - dirs = Array.from(dirs); - const ignored = path => - this.paths.some(p => - p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0 - ); + /** @type {Set} */ + const managedItems = new Set(); - const [ignoredFiles, notIgnoredFiles] = groupBy(files, ignored); - const [ignoredDirs, notIgnoredDirs] = groupBy(dirs, ignored); + /** 1 = timestamp, 2 = hash, 3 = timestamp + hash */ + const mode = options && options.hash ? (options.timestamp ? 3 : 2) : 1; - const watcher = this.wfs.watch( - notIgnoredFiles, - notIgnoredDirs, - missing, - startTime, - options, - (err, fileTimestamps, dirTimestamps, changedFiles, removedFiles) => { - if (err) return callback(err); - for (const path of ignoredFiles) { - fileTimestamps.set(path, IGNORE_TIME_ENTRY); + let jobs = 1; + const jobDone = () => { + if (--jobs === 0) { + if (fileTimestamps.size !== 0) { + snapshot.setFileTimestamps(fileTimestamps); } - - for (const path of ignoredDirs) { - dirTimestamps.set(path, IGNORE_TIME_ENTRY); + if (fileHashes.size !== 0) { + snapshot.setFileHashes(fileHashes); } + if (fileTshs.size !== 0) { + snapshot.setFileTshs(fileTshs); + } + if (contextTimestamps.size !== 0) { + snapshot.setContextTimestamps(contextTimestamps); + } + if (contextHashes.size !== 0) { + snapshot.setContextHashes(contextHashes); + } + if (contextTshs.size !== 0) { + snapshot.setContextTshs(contextTshs); + } + if (missingExistence.size !== 0) { + snapshot.setMissingExistence(missingExistence); + } + if (managedItemInfo.size !== 0) { + snapshot.setManagedItemInfo(managedItemInfo); + } + this._managedFilesOptimization.optimize(snapshot, managedFiles); + if (managedFiles.size !== 0) { + snapshot.setManagedFiles(managedFiles); + } + this._managedContextsOptimization.optimize(snapshot, managedContexts); + if (managedContexts.size !== 0) { + snapshot.setManagedContexts(managedContexts); + } + this._managedMissingOptimization.optimize(snapshot, managedMissing); + if (managedMissing.size !== 0) { + snapshot.setManagedMissing(managedMissing); + } + if (children.size !== 0) { + snapshot.setChildren(children); + } + this._snapshotCache.set(snapshot, true); + this._statCreatedSnapshots++; - callback( - err, - fileTimestamps, - dirTimestamps, - changedFiles, - removedFiles - ); - }, - callbackUndelayed - ); - - return { - close: () => watcher.close(), - pause: () => watcher.pause(), - getContextTimeInfoEntries: () => { - const dirTimestamps = watcher.getContextTimeInfoEntries(); - for (const path of ignoredDirs) { - dirTimestamps.set(path, IGNORE_TIME_ENTRY); + callback(null, snapshot); + } + }; + const jobError = () => { + if (jobs > 0) { + // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8) + jobs = -100000000; + callback(null, null); + } + }; + const checkManaged = (path, managedSet) => { + for (const immutablePath of this.immutablePathsRegExps) { + if (immutablePath.test(path)) { + managedSet.add(path); + return true; } - return dirTimestamps; - }, - getFileTimeInfoEntries: () => { - const fileTimestamps = watcher.getFileTimeInfoEntries(); - for (const path of ignoredFiles) { - fileTimestamps.set(path, IGNORE_TIME_ENTRY); + } + for (const immutablePath of this.immutablePathsWithSlash) { + if (path.startsWith(immutablePath)) { + managedSet.add(path); + return true; } - return fileTimestamps; - }, - getInfo: - watcher.getInfo && - (() => { - const info = watcher.getInfo(); - const { fileTimeInfoEntries, contextTimeInfoEntries } = info; - for (const path of ignoredFiles) { - fileTimeInfoEntries.set(path, IGNORE_TIME_ENTRY); + } + for (const managedPath of this.managedPathsRegExps) { + const match = managedPath.exec(path); + if (match) { + const managedItem = getManagedItem(match[1], path); + if (managedItem) { + managedItems.add(managedItem); + managedSet.add(path); + return true; } - for (const path of ignoredDirs) { - contextTimeInfoEntries.set(path, IGNORE_TIME_ENTRY); + } + } + for (const managedPath of this.managedPathsWithSlash) { + if (path.startsWith(managedPath)) { + const managedItem = getManagedItem(managedPath, path); + if (managedItem) { + managedItems.add(managedItem); + managedSet.add(path); + return true; } - return info; - }) + } + } + return false; }; - } -} - -class WatchIgnorePlugin { - /** - * @param {WatchIgnorePluginOptions} options options - */ - constructor(options) { - validate(options); - this.paths = options.paths; - } - - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.afterEnvironment.tap("WatchIgnorePlugin", () => { - compiler.watchFileSystem = new IgnoringWatchFileSystem( - compiler.watchFileSystem, - this.paths - ); - }); - } -} - -module.exports = WatchIgnorePlugin; - - -/***/ }), - -/***/ 84275: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Stats = __webpack_require__(31743); - -/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ - -/** - * @template T - * @callback Callback - * @param {(Error | null)=} err - * @param {T=} result - */ - -class Watching { - /** - * @param {Compiler} compiler the compiler - * @param {WatchOptions} watchOptions options - * @param {Callback} handler completion handler - */ - constructor(compiler, watchOptions, handler) { - this.startTime = null; - this.invalid = false; - this.handler = handler; - /** @type {Callback[]} */ - this.callbacks = []; - /** @type {Callback[] | undefined} */ - this._closeCallbacks = undefined; - this.closed = false; - this.suspended = false; - this.blocked = false; - this._isBlocked = () => false; - this._onChange = () => {}; - this._onInvalid = () => {}; - if (typeof watchOptions === "number") { - this.watchOptions = { - aggregateTimeout: watchOptions - }; - } else if (watchOptions && typeof watchOptions === "object") { - this.watchOptions = { ...watchOptions }; - } else { - this.watchOptions = {}; - } - if (typeof this.watchOptions.aggregateTimeout !== "number") { - this.watchOptions.aggregateTimeout = 20; - } - this.compiler = compiler; - this.running = false; - this._initial = true; - this._invalidReported = true; - this._needRecords = true; - this.watcher = undefined; - this.pausedWatcher = undefined; - /** @type {Set} */ - this._collectedChangedFiles = undefined; - /** @type {Set} */ - this._collectedRemovedFiles = undefined; - this._done = this._done.bind(this); - process.nextTick(() => { - if (this._initial) this._invalidate(); - }); - } - - /** - * @param {ReadonlySet} changedFiles changed files - * @param {ReadonlySet} removedFiles removed files - */ - _mergeWithCollected(changedFiles, removedFiles) { - if (!changedFiles) return; - if (!this._collectedChangedFiles) { - this._collectedChangedFiles = new Set(changedFiles); - this._collectedRemovedFiles = new Set(removedFiles); - } else { - for (const file of changedFiles) { - this._collectedChangedFiles.add(file); - this._collectedRemovedFiles.delete(file); - } - for (const file of removedFiles) { - this._collectedChangedFiles.delete(file); - this._collectedRemovedFiles.add(file); - } - } - } - - /** - * @param {ReadonlyMap=} fileTimeInfoEntries info for files - * @param {ReadonlyMap=} contextTimeInfoEntries info for directories - * @param {ReadonlySet=} changedFiles changed files - * @param {ReadonlySet=} removedFiles removed files - * @returns {void} - */ - _go(fileTimeInfoEntries, contextTimeInfoEntries, changedFiles, removedFiles) { - this._initial = false; - if (this.startTime === null) this.startTime = Date.now(); - this.running = true; - if (this.watcher) { - this.pausedWatcher = this.watcher; - this.lastWatcherStartTime = Date.now(); - this.watcher.pause(); - this.watcher = null; - } else if (!this.lastWatcherStartTime) { - this.lastWatcherStartTime = Date.now(); - } - this.compiler.fsStartTime = Date.now(); - if ( - changedFiles && - removedFiles && - fileTimeInfoEntries && - contextTimeInfoEntries - ) { - this._mergeWithCollected(changedFiles, removedFiles); - this.compiler.fileTimestamps = fileTimeInfoEntries; - this.compiler.contextTimestamps = contextTimeInfoEntries; - } else if (this.pausedWatcher) { - if (this.pausedWatcher.getInfo) { - const { - changes, - removals, - fileTimeInfoEntries, - contextTimeInfoEntries - } = this.pausedWatcher.getInfo(); - this._mergeWithCollected(changes, removals); - this.compiler.fileTimestamps = fileTimeInfoEntries; - this.compiler.contextTimestamps = contextTimeInfoEntries; - } else { - this._mergeWithCollected( - this.pausedWatcher.getAggregatedChanges && - this.pausedWatcher.getAggregatedChanges(), - this.pausedWatcher.getAggregatedRemovals && - this.pausedWatcher.getAggregatedRemovals() - ); - this.compiler.fileTimestamps = - this.pausedWatcher.getFileTimeInfoEntries(); - this.compiler.contextTimestamps = - this.pausedWatcher.getContextTimeInfoEntries(); - } - } - this.compiler.modifiedFiles = this._collectedChangedFiles; - this._collectedChangedFiles = undefined; - this.compiler.removedFiles = this._collectedRemovedFiles; - this._collectedRemovedFiles = undefined; - - const run = () => { - if (this.compiler.idle) { - return this.compiler.cache.endIdle(err => { - if (err) return this._done(err); - this.compiler.idle = false; - run(); - }); - } - if (this._needRecords) { - return this.compiler.readRecords(err => { - if (err) return this._done(err); - - this._needRecords = false; - run(); - }); + const captureNonManaged = (items, managedSet) => { + const capturedItems = new Set(); + for (const path of items) { + if (!checkManaged(path, managedSet)) capturedItems.add(path); } - this.invalid = false; - this._invalidReported = false; - this.compiler.hooks.watchRun.callAsync(this.compiler, err => { - if (err) return this._done(err); - const onCompiled = (err, compilation) => { - if (err) return this._done(err, compilation); - if (this.invalid) return this._done(null, compilation); - - if (this.compiler.hooks.shouldEmit.call(compilation) === false) { - return this._done(null, compilation); + return capturedItems; + }; + const processCapturedFiles = capturedFiles => { + switch (mode) { + case 3: + this._fileTshsOptimization.optimize(snapshot, capturedFiles); + for (const path of capturedFiles) { + const cache = this._fileTshs.get(path); + if (cache !== undefined) { + fileTshs.set(path, cache); + } else { + jobs++; + this._getFileTimestampAndHash(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting file timestamp hash combination of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + fileTshs.set(path, entry); + jobDone(); + } + }); + } } - - process.nextTick(() => { - const logger = compilation.getLogger("webpack.Compiler"); - logger.time("emitAssets"); - this.compiler.emitAssets(compilation, err => { - logger.timeEnd("emitAssets"); - if (err) return this._done(err, compilation); - if (this.invalid) return this._done(null, compilation); - - logger.time("emitRecords"); - this.compiler.emitRecords(err => { - logger.timeEnd("emitRecords"); - if (err) return this._done(err, compilation); - - if (compilation.hooks.needAdditionalPass.call()) { - compilation.needAdditionalPass = true; - - compilation.startTime = this.startTime; - compilation.endTime = Date.now(); - logger.time("done hook"); - const stats = new Stats(compilation); - this.compiler.hooks.done.callAsync(stats, err => { - logger.timeEnd("done hook"); - if (err) return this._done(err, compilation); - - this.compiler.hooks.additionalPass.callAsync(err => { - if (err) return this._done(err, compilation); - this.compiler.compile(onCompiled); - }); - }); - return; + break; + case 2: + this._fileHashesOptimization.optimize(snapshot, capturedFiles); + for (const path of capturedFiles) { + const cache = this._fileHashes.get(path); + if (cache !== undefined) { + fileHashes.set(path, cache); + } else { + jobs++; + this.fileHashQueue.add(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting file hash of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + fileHashes.set(path, entry); + jobDone(); } - return this._done(null, compilation); }); - }); - }); - }; - this.compiler.compile(onCompiled); - }); - }; - - run(); - } - - /** - * @param {Compilation} compilation the compilation - * @returns {Stats} the compilation stats - */ - _getStats(compilation) { - const stats = new Stats(compilation); - return stats; - } - - /** - * @param {Error=} err an optional error - * @param {Compilation=} compilation the compilation - * @returns {void} - */ - _done(err, compilation) { - this.running = false; - - const logger = compilation && compilation.getLogger("webpack.Watching"); - - let stats = null; - - const handleError = (err, cbs) => { - this.compiler.hooks.failed.call(err); - this.compiler.cache.beginIdle(); - this.compiler.idle = true; - this.handler(err, stats); - if (!cbs) { - cbs = this.callbacks; - this.callbacks = []; + } + } + break; + case 1: + this._fileTimestampsOptimization.optimize(snapshot, capturedFiles); + for (const path of capturedFiles) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache !== "ignore") { + fileTimestamps.set(path, cache); + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting file timestamp of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + fileTimestamps.set(path, entry); + jobDone(); + } + }); + } + } + break; } - for (const cb of cbs) cb(err); }; - - if ( - this.invalid && - !this.suspended && - !this.blocked && - !(this._isBlocked() && (this.blocked = true)) - ) { - if (compilation) { - logger.time("storeBuildDependencies"); - this.compiler.cache.storeBuildDependencies( - compilation.buildDependencies, - err => { - logger.timeEnd("storeBuildDependencies"); - if (err) return handleError(err); - this._go(); + if (files) { + processCapturedFiles(captureNonManaged(files, managedFiles)); + } + const processCapturedDirectories = capturedDirectories => { + switch (mode) { + case 3: + this._contextTshsOptimization.optimize(snapshot, capturedDirectories); + for (const path of capturedDirectories) { + const cache = this._contextTshs.get(path); + /** @type {ResolvedContextTimestampAndHash} */ + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedTimestamp(cache)) !== undefined + ) { + contextTshs.set(path, resolved); + } else { + jobs++; + /** + * @param {Error=} err error + * @param {ResolvedContextTimestampAndHash=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting context timestamp hash combination of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + contextTshs.set(path, entry); + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextTsh(cache, callback); + } else { + this.getContextTsh(path, callback); + } + } } - ); - } else { - this._go(); + break; + case 2: + this._contextHashesOptimization.optimize( + snapshot, + capturedDirectories + ); + for (const path of capturedDirectories) { + const cache = this._contextHashes.get(path); + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedHash(cache)) !== undefined + ) { + contextHashes.set(path, resolved); + } else { + jobs++; + const callback = (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting context hash of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + contextHashes.set(path, entry); + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextHash(cache, callback); + } else { + this.getContextHash(path, callback); + } + } + } + break; + case 1: + this._contextTimestampsOptimization.optimize( + snapshot, + capturedDirectories + ); + for (const path of capturedDirectories) { + const cache = this._contextTimestamps.get(path); + if (cache === "ignore") continue; + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedTimestamp(cache)) !== undefined + ) { + contextTimestamps.set(path, resolved); + } else { + jobs++; + /** + * @param {Error=} err error + * @param {ResolvedContextFileSystemInfoEntry=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting context timestamp of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + contextTimestamps.set(path, entry); + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextTimestamp(cache, callback); + } else { + this.getContextTimestamp(path, callback); + } + } + } + break; } - return; - } - - if (compilation) { - compilation.startTime = this.startTime; - compilation.endTime = Date.now(); - stats = new Stats(compilation); + }; + if (directories) { + processCapturedDirectories( + captureNonManaged(directories, managedContexts) + ); } - this.startTime = null; - if (err) return handleError(err); - - const cbs = this.callbacks; - this.callbacks = []; - logger.time("done hook"); - this.compiler.hooks.done.callAsync(stats, err => { - logger.timeEnd("done hook"); - if (err) return handleError(err, cbs); - this.handler(null, stats); - logger.time("storeBuildDependencies"); - this.compiler.cache.storeBuildDependencies( - compilation.buildDependencies, - err => { - logger.timeEnd("storeBuildDependencies"); - if (err) return handleError(err, cbs); - logger.time("beginIdle"); - this.compiler.cache.beginIdle(); - this.compiler.idle = true; - logger.timeEnd("beginIdle"); - process.nextTick(() => { - if (!this.closed) { - this.watch( - compilation.fileDependencies, - compilation.contextDependencies, - compilation.missingDependencies - ); + const processCapturedMissing = capturedMissing => { + this._missingExistenceOptimization.optimize(snapshot, capturedMissing); + for (const path of capturedMissing) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache !== "ignore") { + missingExistence.set(path, Boolean(cache)); + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting missing timestamp of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + missingExistence.set(path, Boolean(entry)); + jobDone(); } }); - for (const cb of cbs) cb(null); - this.compiler.hooks.afterDone.call(stats); - } - ); - }); - } - - /** - * @param {Iterable} files watched files - * @param {Iterable} dirs watched directories - * @param {Iterable} missing watched existence entries - * @returns {void} - */ - watch(files, dirs, missing) { - this.pausedWatcher = null; - this.watcher = this.compiler.watchFileSystem.watch( - files, - dirs, - missing, - this.lastWatcherStartTime, - this.watchOptions, - ( - err, - fileTimeInfoEntries, - contextTimeInfoEntries, - changedFiles, - removedFiles - ) => { - if (err) { - this.compiler.modifiedFiles = undefined; - this.compiler.removedFiles = undefined; - this.compiler.fileTimestamps = undefined; - this.compiler.contextTimestamps = undefined; - this.compiler.fsStartTime = undefined; - return this.handler(err); } - this._invalidate( - fileTimeInfoEntries, - contextTimeInfoEntries, - changedFiles, - removedFiles - ); - this._onChange(); - }, - (fileName, changeTime) => { - if (!this._invalidReported) { - this._invalidReported = true; - this.compiler.hooks.invalid.call(fileName, changeTime); + } + }; + if (missing) { + processCapturedMissing(captureNonManaged(missing, managedMissing)); + } + this._managedItemInfoOptimization.optimize(snapshot, managedItems); + for (const path of managedItems) { + const cache = this._managedItems.get(path); + if (cache !== undefined) { + if (!cache.startsWith("*")) { + managedFiles.add(join(this.fs, path, "package.json")); + } else if (cache === "*nested") { + managedMissing.add(join(this.fs, path, "package.json")); } - this._onInvalid(); + managedItemInfo.set(path, cache); + } else { + jobs++; + this.managedItemQueue.add(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting managed item ${path}: ${err.stack}` + ); + } + jobError(); + } else if (entry) { + if (!entry.startsWith("*")) { + managedFiles.add(join(this.fs, path, "package.json")); + } else if (cache === "*nested") { + managedMissing.add(join(this.fs, path, "package.json")); + } + managedItemInfo.set(path, entry); + jobDone(); + } else { + // Fallback to normal snapshotting + const process = (set, fn) => { + if (set.size === 0) return; + const captured = new Set(); + for (const file of set) { + if (file.startsWith(path)) captured.add(file); + } + if (captured.size > 0) fn(captured); + }; + process(managedFiles, processCapturedFiles); + process(managedContexts, processCapturedDirectories); + process(managedMissing, processCapturedMissing); + jobDone(); + } + }); } - ); + } + jobDone(); } /** - * @param {Callback=} callback signals when the build has completed again - * @returns {void} + * @param {Snapshot} snapshot1 a snapshot + * @param {Snapshot} snapshot2 a snapshot + * @returns {Snapshot} merged snapshot */ - invalidate(callback) { - if (callback) { - this.callbacks.push(callback); + mergeSnapshots(snapshot1, snapshot2) { + const snapshot = new Snapshot(); + if (snapshot1.hasStartTime() && snapshot2.hasStartTime()) + snapshot.setStartTime(Math.min(snapshot1.startTime, snapshot2.startTime)); + else if (snapshot2.hasStartTime()) snapshot.startTime = snapshot2.startTime; + else if (snapshot1.hasStartTime()) snapshot.startTime = snapshot1.startTime; + if (snapshot1.hasFileTimestamps() || snapshot2.hasFileTimestamps()) { + snapshot.setFileTimestamps( + mergeMaps(snapshot1.fileTimestamps, snapshot2.fileTimestamps) + ); } - if (!this._invalidReported) { - this._invalidReported = true; - this.compiler.hooks.invalid.call(null, Date.now()); + if (snapshot1.hasFileHashes() || snapshot2.hasFileHashes()) { + snapshot.setFileHashes( + mergeMaps(snapshot1.fileHashes, snapshot2.fileHashes) + ); } - this._onChange(); - this._invalidate(); - } - - _invalidate( - fileTimeInfoEntries, - contextTimeInfoEntries, - changedFiles, - removedFiles - ) { - if (this.suspended || (this._isBlocked() && (this.blocked = true))) { - this._mergeWithCollected(changedFiles, removedFiles); - return; + if (snapshot1.hasFileTshs() || snapshot2.hasFileTshs()) { + snapshot.setFileTshs(mergeMaps(snapshot1.fileTshs, snapshot2.fileTshs)); } - - if (this.running) { - this._mergeWithCollected(changedFiles, removedFiles); - this.invalid = true; - } else { - this._go( - fileTimeInfoEntries, - contextTimeInfoEntries, - changedFiles, - removedFiles + if (snapshot1.hasContextTimestamps() || snapshot2.hasContextTimestamps()) { + snapshot.setContextTimestamps( + mergeMaps(snapshot1.contextTimestamps, snapshot2.contextTimestamps) ); } - } - - suspend() { - this.suspended = true; - } - - resume() { - if (this.suspended) { - this.suspended = false; - this._invalidate(); + if (snapshot1.hasContextHashes() || snapshot2.hasContextHashes()) { + snapshot.setContextHashes( + mergeMaps(snapshot1.contextHashes, snapshot2.contextHashes) + ); } - } - - /** - * @param {Callback} callback signals when the watcher is closed - * @returns {void} - */ - close(callback) { - if (this._closeCallbacks) { - if (callback) { - this._closeCallbacks.push(callback); - } - return; + if (snapshot1.hasContextTshs() || snapshot2.hasContextTshs()) { + snapshot.setContextTshs( + mergeMaps(snapshot1.contextTshs, snapshot2.contextTshs) + ); } - const finalCallback = (err, compilation) => { - this.running = false; - this.compiler.running = false; - this.compiler.watching = undefined; - this.compiler.watchMode = false; - this.compiler.modifiedFiles = undefined; - this.compiler.removedFiles = undefined; - this.compiler.fileTimestamps = undefined; - this.compiler.contextTimestamps = undefined; - this.compiler.fsStartTime = undefined; - const shutdown = err => { - this.compiler.hooks.watchClose.call(); - const closeCallbacks = this._closeCallbacks; - this._closeCallbacks = undefined; - for (const cb of closeCallbacks) cb(err); - }; - if (compilation) { - const logger = compilation.getLogger("webpack.Watching"); - logger.time("storeBuildDependencies"); - this.compiler.cache.storeBuildDependencies( - compilation.buildDependencies, - err2 => { - logger.timeEnd("storeBuildDependencies"); - shutdown(err || err2); - } - ); - } else { - shutdown(err); - } - }; - - this.closed = true; - if (this.watcher) { - this.watcher.close(); - this.watcher = null; + if (snapshot1.hasMissingExistence() || snapshot2.hasMissingExistence()) { + snapshot.setMissingExistence( + mergeMaps(snapshot1.missingExistence, snapshot2.missingExistence) + ); } - if (this.pausedWatcher) { - this.pausedWatcher.close(); - this.pausedWatcher = null; + if (snapshot1.hasManagedItemInfo() || snapshot2.hasManagedItemInfo()) { + snapshot.setManagedItemInfo( + mergeMaps(snapshot1.managedItemInfo, snapshot2.managedItemInfo) + ); } - this._closeCallbacks = []; - if (callback) { - this._closeCallbacks.push(callback); + if (snapshot1.hasManagedFiles() || snapshot2.hasManagedFiles()) { + snapshot.setManagedFiles( + mergeSets(snapshot1.managedFiles, snapshot2.managedFiles) + ); } - if (this.running) { - this.invalid = true; - this._done = finalCallback; - } else { - finalCallback(); + if (snapshot1.hasManagedContexts() || snapshot2.hasManagedContexts()) { + snapshot.setManagedContexts( + mergeSets(snapshot1.managedContexts, snapshot2.managedContexts) + ); + } + if (snapshot1.hasManagedMissing() || snapshot2.hasManagedMissing()) { + snapshot.setManagedMissing( + mergeSets(snapshot1.managedMissing, snapshot2.managedMissing) + ); + } + if (snapshot1.hasChildren() || snapshot2.hasChildren()) { + snapshot.setChildren(mergeSets(snapshot1.children, snapshot2.children)); + } + if ( + this._snapshotCache.get(snapshot1) === true && + this._snapshotCache.get(snapshot2) === true + ) { + this._snapshotCache.set(snapshot, true); } + return snapshot; } -} - -module.exports = Watching; - - -/***/ }), - -/***/ 53799: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Jarid Margolin @jaridmargolin -*/ - - - -const inspect = (__webpack_require__(73837).inspect.custom); -const makeSerializable = __webpack_require__(33032); - -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Module")} Module */ -class WebpackError extends Error { /** - * Creates an instance of WebpackError. - * @param {string=} message error message + * @param {Snapshot} snapshot the snapshot made + * @param {function((WebpackError | null)=, boolean=): void} callback callback function + * @returns {void} */ - constructor(message) { - super(message); - - this.details = undefined; - /** @type {Module} */ - this.module = undefined; - /** @type {DependencyLocation} */ - this.loc = undefined; - /** @type {boolean} */ - this.hideStack = undefined; - /** @type {Chunk} */ - this.chunk = undefined; - /** @type {string} */ - this.file = undefined; - } - - [inspect]() { - return this.stack + (this.details ? `\n${this.details}` : ""); - } - - serialize({ write }) { - write(this.name); - write(this.message); - write(this.stack); - write(this.details); - write(this.loc); - write(this.hideStack); - } - - deserialize({ read }) { - this.name = read(); - this.message = read(); - this.stack = read(); - this.details = read(); - this.loc = read(); - this.hideStack = read(); + checkSnapshotValid(snapshot, callback) { + const cachedResult = this._snapshotCache.get(snapshot); + if (cachedResult !== undefined) { + this._statTestedSnapshotsCached++; + if (typeof cachedResult === "boolean") { + callback(null, cachedResult); + } else { + cachedResult.push(callback); + } + return; + } + this._statTestedSnapshotsNotCached++; + this._checkSnapshotValidNoCache(snapshot, callback); } -} - -makeSerializable(WebpackError, "webpack/lib/WebpackError"); - -module.exports = WebpackError; - - -/***/ }), - -/***/ 97017: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - - - -const IgnoreErrorModuleFactory = __webpack_require__(3); -const WebpackIsIncludedDependency = __webpack_require__(26505); -const { - toConstantDependency -} = __webpack_require__(93998); - -/** @typedef {import("enhanced-resolve/lib/Resolver")} Resolver */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ -class WebpackIsIncludedPlugin { /** - * @param {Compiler} compiler the compiler instance + * @param {Snapshot} snapshot the snapshot made + * @param {function((WebpackError | null)=, boolean=): void} callback callback function * @returns {void} */ - apply(compiler) { - compiler.hooks.compilation.tap( - "WebpackIsIncludedPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - WebpackIsIncludedDependency, - new IgnoreErrorModuleFactory(normalModuleFactory) - ); - compilation.dependencyTemplates.set( - WebpackIsIncludedDependency, - new WebpackIsIncludedDependency.Template() - ); - - /** - * @param {JavascriptParser} parser the parser - * @returns {void} - */ - const handler = parser => { - parser.hooks.call - .for("__webpack_is_included__") - .tap("WebpackIsIncludedPlugin", expr => { - if ( - expr.type !== "CallExpression" || - expr.arguments.length !== 1 || - expr.arguments[0].type === "SpreadElement" - ) - return; - - const request = parser.evaluateExpression(expr.arguments[0]); - - if (!request.isString()) return; - - const dep = new WebpackIsIncludedDependency( - request.string, - expr.range - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return true; - }); - parser.hooks.typeof - .for("__webpack_is_included__") - .tap( - "WebpackIsIncludedPlugin", - toConstantDependency(parser, JSON.stringify("function")) - ); - }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("WebpackIsIncludedPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("WebpackIsIncludedPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("WebpackIsIncludedPlugin", handler); + _checkSnapshotValidNoCache(snapshot, callback) { + /** @type {number | undefined} */ + let startTime = undefined; + if (snapshot.hasStartTime()) { + startTime = snapshot.startTime; + } + let jobs = 1; + const jobDone = () => { + if (--jobs === 0) { + this._snapshotCache.set(snapshot, true); + callback(null, true); } - ); - } -} - -module.exports = WebpackIsIncludedPlugin; - - -/***/ }), - -/***/ 88422: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const OptionsApply = __webpack_require__(81426); - -const AssetModulesPlugin = __webpack_require__(16109); -const JavascriptModulesPlugin = __webpack_require__(89464); -const JsonModulesPlugin = __webpack_require__(86770); - -const ChunkPrefetchPreloadPlugin = __webpack_require__(33895); - -const EntryOptionPlugin = __webpack_require__(9909); -const RecordIdsPlugin = __webpack_require__(11094); - -const RuntimePlugin = __webpack_require__(2307); - -const APIPlugin = __webpack_require__(74315); -const CompatibilityPlugin = __webpack_require__(94258); -const ConstPlugin = __webpack_require__(11146); -const ExportsInfoApiPlugin = __webpack_require__(7145); -const WebpackIsIncludedPlugin = __webpack_require__(97017); - -const TemplatedPathPlugin = __webpack_require__(80734); -const UseStrictPlugin = __webpack_require__(36803); -const WarnCaseSensitiveModulesPlugin = __webpack_require__(56504); - -const DataUriPlugin = __webpack_require__(64820); -const FileUriPlugin = __webpack_require__(57637); - -const ResolverCachePlugin = __webpack_require__(97347); - -const CommonJsPlugin = __webpack_require__(32406); -const HarmonyModulesPlugin = __webpack_require__(39029); -const ImportMetaPlugin = __webpack_require__(17228); -const ImportPlugin = __webpack_require__(41293); -const LoaderPlugin = __webpack_require__(24721); -const RequireContextPlugin = __webpack_require__(2928); -const RequireEnsurePlugin = __webpack_require__(8434); -const RequireIncludePlugin = __webpack_require__(37378); -const SystemPlugin = __webpack_require__(97981); -const URLPlugin = __webpack_require__(14412); -const WorkerPlugin = __webpack_require__(82509); - -const InferAsyncModulesPlugin = __webpack_require__(59498); - -const JavascriptMetaInfoPlugin = __webpack_require__(52329); -const DefaultStatsFactoryPlugin = __webpack_require__(71760); -const DefaultStatsPresetPlugin = __webpack_require__(55442); -const DefaultStatsPrinterPlugin = __webpack_require__(58692); - -const { cleverMerge } = __webpack_require__(60839); - -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("./Compiler")} Compiler */ - -class WebpackOptionsApply extends OptionsApply { - constructor() { - super(); - } - - /** - * @param {WebpackOptions} options options object - * @param {Compiler} compiler compiler object - * @returns {WebpackOptions} options object - */ - process(options, compiler) { - compiler.outputPath = options.output.path; - compiler.recordsInputPath = options.recordsInputPath || null; - compiler.recordsOutputPath = options.recordsOutputPath || null; - compiler.name = options.name; - - if (options.externals) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ExternalsPlugin = __webpack_require__(6652); - new ExternalsPlugin(options.externalsType, options.externals).apply( - compiler - ); - } - - if (options.externalsPresets.node) { - const NodeTargetPlugin = __webpack_require__(17916); - new NodeTargetPlugin().apply(compiler); - } - if (options.externalsPresets.electronMain) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ElectronTargetPlugin = __webpack_require__(32277); - new ElectronTargetPlugin("main").apply(compiler); - } - if (options.externalsPresets.electronPreload) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ElectronTargetPlugin = __webpack_require__(32277); - new ElectronTargetPlugin("preload").apply(compiler); - } - if (options.externalsPresets.electronRenderer) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ElectronTargetPlugin = __webpack_require__(32277); - new ElectronTargetPlugin("renderer").apply(compiler); - } - if ( - options.externalsPresets.electron && - !options.externalsPresets.electronMain && - !options.externalsPresets.electronPreload && - !options.externalsPresets.electronRenderer - ) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ElectronTargetPlugin = __webpack_require__(32277); - new ElectronTargetPlugin().apply(compiler); - } - if (options.externalsPresets.nwjs) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ExternalsPlugin = __webpack_require__(6652); - new ExternalsPlugin("node-commonjs", "nw.gui").apply(compiler); - } - if (options.externalsPresets.webAsync) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ExternalsPlugin = __webpack_require__(6652); - new ExternalsPlugin( - "import", - options.experiments.css - ? ({ request, dependencyType }, callback) => { - if (dependencyType === "url") { - if (/^(\/\/|https?:\/\/)/.test(request)) - return callback(null, `asset ${request}`); - } else if (dependencyType === "css-import") { - if (/^(\/\/|https?:\/\/)/.test(request)) - return callback(null, `css-import ${request}`); - } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) { - if (/^\.css(\?|$)/.test(request)) - return callback(null, `css-import ${request}`); - return callback(null, `import ${request}`); - } - callback(); - } - : /^(\/\/|https?:\/\/|std:)/ - ).apply(compiler); - } else if (options.externalsPresets.web) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ExternalsPlugin = __webpack_require__(6652); - new ExternalsPlugin( - "module", - options.experiments.css - ? ({ request, dependencyType }, callback) => { - if (dependencyType === "url") { - if (/^(\/\/|https?:\/\/)/.test(request)) - return callback(null, `asset ${request}`); - } else if (dependencyType === "css-import") { - if (/^(\/\/|https?:\/\/)/.test(request)) - return callback(null, `css-import ${request}`); - } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) { - if (/^\.css(\?|$)/.test(request)) - return callback(null, `css-import ${request}`); - return callback(null, `module ${request}`); - } - callback(); - } - : /^(\/\/|https?:\/\/|std:)/ - ).apply(compiler); - } - - new ChunkPrefetchPreloadPlugin().apply(compiler); - - if (typeof options.output.chunkFormat === "string") { - switch (options.output.chunkFormat) { - case "array-push": { - const ArrayPushCallbackChunkFormatPlugin = __webpack_require__(18535); - new ArrayPushCallbackChunkFormatPlugin().apply(compiler); - break; + }; + const invalid = () => { + if (jobs > 0) { + // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8) + jobs = -100000000; + this._snapshotCache.set(snapshot, false); + callback(null, false); + } + }; + const invalidWithError = (path, err) => { + if (this._remainingLogs > 0) { + this._log(path, `error occurred: %s`, err); + } + invalid(); + }; + /** + * @param {string} path file path + * @param {string} current current hash + * @param {string} snap snapshot hash + * @returns {boolean} true, if ok + */ + const checkHash = (path, current, snap) => { + if (current !== snap) { + // If hash differ it's invalid + if (this._remainingLogs > 0) { + this._log(path, `hashes differ (%s != %s)`, current, snap); } - case "commonjs": { - const CommonJsChunkFormatPlugin = __webpack_require__(84508); - new CommonJsChunkFormatPlugin().apply(compiler); - break; + return false; + } + return true; + }; + /** + * @param {string} path file path + * @param {boolean} current current entry + * @param {boolean} snap entry from snapshot + * @returns {boolean} true, if ok + */ + const checkExistence = (path, current, snap) => { + if (!current !== !snap) { + // If existence of item differs + // it's invalid + if (this._remainingLogs > 0) { + this._log( + path, + current ? "it didn't exist before" : "it does no longer exist" + ); } - case "module": { - const ModuleChunkFormatPlugin = __webpack_require__(68927); - new ModuleChunkFormatPlugin().apply(compiler); - break; + return false; + } + return true; + }; + /** + * @param {string} path file path + * @param {FileSystemInfoEntry} current current entry + * @param {FileSystemInfoEntry} snap entry from snapshot + * @param {boolean} log log reason + * @returns {boolean} true, if ok + */ + const checkFile = (path, current, snap, log = true) => { + if (current === snap) return true; + if (!checkExistence(path, Boolean(current), Boolean(snap))) return false; + if (current) { + // For existing items only + if (typeof startTime === "number" && current.safeTime > startTime) { + // If a change happened after starting reading the item + // this may no longer be valid + if (log && this._remainingLogs > 0) { + this._log( + path, + `it may have changed (%d) after the start time of the snapshot (%d)`, + current.safeTime, + startTime + ); + } + return false; + } + if ( + snap.timestamp !== undefined && + current.timestamp !== snap.timestamp + ) { + // If we have a timestamp (it was a file or symlink) and it differs from current timestamp + // it's invalid + if (log && this._remainingLogs > 0) { + this._log( + path, + `timestamps differ (%d != %d)`, + current.timestamp, + snap.timestamp + ); + } + return false; } - default: - throw new Error( - "Unsupported chunk format '" + options.output.chunkFormat + "'." - ); } - } - - if (options.output.enabledChunkLoadingTypes.length > 0) { - for (const type of options.output.enabledChunkLoadingTypes) { - const EnableChunkLoadingPlugin = __webpack_require__(61291); - new EnableChunkLoadingPlugin(type).apply(compiler); + return true; + }; + /** + * @param {string} path file path + * @param {ResolvedContextFileSystemInfoEntry} current current entry + * @param {ResolvedContextFileSystemInfoEntry} snap entry from snapshot + * @param {boolean} log log reason + * @returns {boolean} true, if ok + */ + const checkContext = (path, current, snap, log = true) => { + if (current === snap) return true; + if (!checkExistence(path, Boolean(current), Boolean(snap))) return false; + if (current) { + // For existing items only + if (typeof startTime === "number" && current.safeTime > startTime) { + // If a change happened after starting reading the item + // this may no longer be valid + if (log && this._remainingLogs > 0) { + this._log( + path, + `it may have changed (%d) after the start time of the snapshot (%d)`, + current.safeTime, + startTime + ); + } + return false; + } + if ( + snap.timestampHash !== undefined && + current.timestampHash !== snap.timestampHash + ) { + // If we have a timestampHash (it was a directory) and it differs from current timestampHash + // it's invalid + if (log && this._remainingLogs > 0) { + this._log( + path, + `timestamps hashes differ (%s != %s)`, + current.timestampHash, + snap.timestampHash + ); + } + return false; + } } - } - - if (options.output.enabledWasmLoadingTypes.length > 0) { - for (const type of options.output.enabledWasmLoadingTypes) { - const EnableWasmLoadingPlugin = __webpack_require__(78613); - new EnableWasmLoadingPlugin(type).apply(compiler); + return true; + }; + if (snapshot.hasChildren()) { + const childCallback = (err, result) => { + if (err || !result) return invalid(); + else jobDone(); + }; + for (const child of snapshot.children) { + const cache = this._snapshotCache.get(child); + if (cache !== undefined) { + this._statTestedChildrenCached++; + /* istanbul ignore else */ + if (typeof cache === "boolean") { + if (cache === false) { + invalid(); + return; + } + } else { + jobs++; + cache.push(childCallback); + } + } else { + this._statTestedChildrenNotCached++; + jobs++; + this._checkSnapshotValidNoCache(child, childCallback); + } } } - - if (options.output.enabledLibraryTypes.length > 0) { - for (const type of options.output.enabledLibraryTypes) { - const EnableLibraryPlugin = __webpack_require__(91452); - new EnableLibraryPlugin(type).apply(compiler); + if (snapshot.hasFileTimestamps()) { + const { fileTimestamps } = snapshot; + this._statTestedEntries += fileTimestamps.size; + for (const [path, ts] of fileTimestamps) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache !== "ignore" && !checkFile(path, cache, ts)) { + invalid(); + return; + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkFile(path, entry, ts)) { + invalid(); + } else { + jobDone(); + } + }); + } } } - - if (options.output.pathinfo) { - const ModuleInfoHeaderPlugin = __webpack_require__(3454); - new ModuleInfoHeaderPlugin(options.output.pathinfo !== true).apply( - compiler - ); - } - - if (options.output.clean) { - const CleanPlugin = __webpack_require__(31085); - new CleanPlugin( - options.output.clean === true ? {} : options.output.clean - ).apply(compiler); + const processFileHashSnapshot = (path, hash) => { + const cache = this._fileHashes.get(path); + if (cache !== undefined) { + if (cache !== "ignore" && !checkHash(path, cache, hash)) { + invalid(); + return; + } + } else { + jobs++; + this.fileHashQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkHash(path, entry, hash)) { + invalid(); + } else { + jobDone(); + } + }); + } + }; + if (snapshot.hasFileHashes()) { + const { fileHashes } = snapshot; + this._statTestedEntries += fileHashes.size; + for (const [path, hash] of fileHashes) { + processFileHashSnapshot(path, hash); + } } - - if (options.devtool) { - if (options.devtool.includes("source-map")) { - const hidden = options.devtool.includes("hidden"); - const inline = options.devtool.includes("inline"); - const evalWrapped = options.devtool.includes("eval"); - const cheap = options.devtool.includes("cheap"); - const moduleMaps = options.devtool.includes("module"); - const noSources = options.devtool.includes("nosources"); - const Plugin = evalWrapped - ? __webpack_require__(14790) - : __webpack_require__(63872); - new Plugin({ - filename: inline ? null : options.output.sourceMapFilename, - moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, - fallbackModuleFilenameTemplate: - options.output.devtoolFallbackModuleFilenameTemplate, - append: hidden ? false : undefined, - module: moduleMaps ? true : cheap ? false : true, - columns: cheap ? false : true, - noSources: noSources, - namespace: options.output.devtoolNamespace - }).apply(compiler); - } else if (options.devtool.includes("eval")) { - const EvalDevToolModulePlugin = __webpack_require__(65218); - new EvalDevToolModulePlugin({ - moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, - namespace: options.output.devtoolNamespace - }).apply(compiler); + if (snapshot.hasFileTshs()) { + const { fileTshs } = snapshot; + this._statTestedEntries += fileTshs.size; + for (const [path, tsh] of fileTshs) { + if (typeof tsh === "string") { + processFileHashSnapshot(path, tsh); + } else { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache === "ignore" || !checkFile(path, cache, tsh, false)) { + processFileHashSnapshot(path, tsh && tsh.hash); + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkFile(path, entry, tsh, false)) { + processFileHashSnapshot(path, tsh && tsh.hash); + } + jobDone(); + }); + } + } } } - - new JavascriptModulesPlugin().apply(compiler); - new JsonModulesPlugin().apply(compiler); - new AssetModulesPlugin().apply(compiler); - - if (!options.experiments.outputModule) { - if (options.output.module) { - throw new Error( - "'output.module: true' is only allowed when 'experiments.outputModule' is enabled" - ); + if (snapshot.hasContextTimestamps()) { + const { contextTimestamps } = snapshot; + this._statTestedEntries += contextTimestamps.size; + for (const [path, ts] of contextTimestamps) { + const cache = this._contextTimestamps.get(path); + if (cache === "ignore") continue; + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedTimestamp(cache)) !== undefined + ) { + if (!checkContext(path, resolved, ts)) { + invalid(); + return; + } + } else { + jobs++; + /** + * @param {Error=} err error + * @param {ResolvedContextFileSystemInfoEntry=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkContext(path, entry, ts)) { + invalid(); + } else { + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextTimestamp(cache, callback); + } else { + this.getContextTimestamp(path, callback); + } + } } - if (options.output.enabledLibraryTypes.includes("module")) { - throw new Error( - "library type \"module\" is only allowed when 'experiments.outputModule' is enabled" - ); + } + const processContextHashSnapshot = (path, hash) => { + const cache = this._contextHashes.get(path); + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedHash(cache)) !== undefined + ) { + if (!checkHash(path, resolved, hash)) { + invalid(); + return; + } + } else { + jobs++; + const callback = (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkHash(path, entry, hash)) { + invalid(); + } else { + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextHash(cache, callback); + } else { + this.getContextHash(path, callback); + } } - if (options.externalsType === "module") { - throw new Error( - "'externalsType: \"module\"' is only allowed when 'experiments.outputModule' is enabled" - ); + }; + if (snapshot.hasContextHashes()) { + const { contextHashes } = snapshot; + this._statTestedEntries += contextHashes.size; + for (const [path, hash] of contextHashes) { + processContextHashSnapshot(path, hash); } } - - if (options.experiments.syncWebAssembly) { - const WebAssemblyModulesPlugin = __webpack_require__(53639); - new WebAssemblyModulesPlugin({ - mangleImports: options.optimization.mangleWasmImports - }).apply(compiler); - } - - if (options.experiments.asyncWebAssembly) { - const AsyncWebAssemblyModulesPlugin = __webpack_require__(7538); - new AsyncWebAssemblyModulesPlugin({ - mangleImports: options.optimization.mangleWasmImports - }).apply(compiler); + if (snapshot.hasContextTshs()) { + const { contextTshs } = snapshot; + this._statTestedEntries += contextTshs.size; + for (const [path, tsh] of contextTshs) { + if (typeof tsh === "string") { + processContextHashSnapshot(path, tsh); + } else { + const cache = this._contextTimestamps.get(path); + if (cache === "ignore") continue; + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedTimestamp(cache)) !== undefined + ) { + if (!checkContext(path, resolved, tsh, false)) { + processContextHashSnapshot(path, tsh && tsh.hash); + } + } else { + jobs++; + /** + * @param {Error=} err error + * @param {ResolvedContextFileSystemInfoEntry=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkContext(path, entry, tsh, false)) { + processContextHashSnapshot(path, tsh && tsh.hash); + } + jobDone(); + }; + if (cache !== undefined) { + this._resolveContextTimestamp(cache, callback); + } else { + this.getContextTimestamp(path, callback); + } + } + } + } } - - if (options.experiments.css) { - const CssModulesPlugin = __webpack_require__(47283); - new CssModulesPlugin(options.experiments.css).apply(compiler); + if (snapshot.hasMissingExistence()) { + const { missingExistence } = snapshot; + this._statTestedEntries += missingExistence.size; + for (const [path, existence] of missingExistence) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if ( + cache !== "ignore" && + !checkExistence(path, Boolean(cache), Boolean(existence)) + ) { + invalid(); + return; + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkExistence(path, Boolean(entry), Boolean(existence))) { + invalid(); + } else { + jobDone(); + } + }); + } + } } - - if (options.experiments.lazyCompilation) { - const LazyCompilationPlugin = __webpack_require__(79040); - const lazyOptions = - typeof options.experiments.lazyCompilation === "object" - ? options.experiments.lazyCompilation - : null; - new LazyCompilationPlugin({ - backend: - typeof lazyOptions.backend === "function" - ? lazyOptions.backend - : __webpack_require__(17781)({ - ...lazyOptions.backend, - client: - (lazyOptions.backend && lazyOptions.backend.client) || - options.externalsPresets.node ? __webpack_require__.ab + "lazy-compilation-node.js" : __webpack_require__.ab + "lazy-compilation-web.js" - }), - entries: !lazyOptions || lazyOptions.entries !== false, - imports: !lazyOptions || lazyOptions.imports !== false, - test: (lazyOptions && lazyOptions.test) || undefined - }).apply(compiler); + if (snapshot.hasManagedItemInfo()) { + const { managedItemInfo } = snapshot; + this._statTestedEntries += managedItemInfo.size; + for (const [path, info] of managedItemInfo) { + const cache = this._managedItems.get(path); + if (cache !== undefined) { + if (!checkHash(path, cache, info)) { + invalid(); + return; + } + } else { + jobs++; + this.managedItemQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkHash(path, entry, info)) { + invalid(); + } else { + jobDone(); + } + }); + } + } } + jobDone(); - if (options.experiments.buildHttp) { - const HttpUriPlugin = __webpack_require__(42110); - const httpOptions = options.experiments.buildHttp; - new HttpUriPlugin(httpOptions).apply(compiler); + // if there was an async action + // try to join multiple concurrent request for this snapshot + if (jobs > 0) { + const callbacks = [callback]; + callback = (err, result) => { + for (const callback of callbacks) callback(err, result); + }; + this._snapshotCache.set(snapshot, callbacks); } + } - new EntryOptionPlugin().apply(compiler); - compiler.hooks.entryOption.call(options.context, options.entry); - - new RuntimePlugin().apply(compiler); - - new InferAsyncModulesPlugin().apply(compiler); + _readFileTimestamp(path, callback) { + this.fs.stat(path, (err, stat) => { + if (err) { + if (err.code === "ENOENT") { + this._fileTimestamps.set(path, null); + this._cachedDeprecatedFileTimestamps = undefined; + return callback(null, null); + } + return callback(err); + } - new DataUriPlugin().apply(compiler); - new FileUriPlugin().apply(compiler); + let ts; + if (stat.isDirectory()) { + ts = { + safeTime: 0, + timestamp: undefined + }; + } else { + const mtime = +stat.mtime; - new CompatibilityPlugin().apply(compiler); - new HarmonyModulesPlugin({ - topLevelAwait: options.experiments.topLevelAwait - }).apply(compiler); - if (options.amd !== false) { - const AMDPlugin = __webpack_require__(50067); - const RequireJsStuffPlugin = __webpack_require__(88846); - new AMDPlugin(options.amd || {}).apply(compiler); - new RequireJsStuffPlugin().apply(compiler); - } - new CommonJsPlugin().apply(compiler); - new LoaderPlugin({}).apply(compiler); - if (options.node !== false) { - const NodeStuffPlugin = __webpack_require__(95287); - new NodeStuffPlugin(options.node).apply(compiler); - } - new APIPlugin().apply(compiler); - new ExportsInfoApiPlugin().apply(compiler); - new WebpackIsIncludedPlugin().apply(compiler); - new ConstPlugin().apply(compiler); - new UseStrictPlugin().apply(compiler); - new RequireIncludePlugin().apply(compiler); - new RequireEnsurePlugin().apply(compiler); - new RequireContextPlugin().apply(compiler); - new ImportPlugin().apply(compiler); - new SystemPlugin().apply(compiler); - new ImportMetaPlugin().apply(compiler); - new URLPlugin().apply(compiler); - new WorkerPlugin( - options.output.workerChunkLoading, - options.output.workerWasmLoading, - options.output.module - ).apply(compiler); + if (mtime) applyMtime(mtime); - new DefaultStatsFactoryPlugin().apply(compiler); - new DefaultStatsPresetPlugin().apply(compiler); - new DefaultStatsPrinterPlugin().apply(compiler); + ts = { + safeTime: mtime ? mtime + FS_ACCURACY : Infinity, + timestamp: mtime + }; + } - new JavascriptMetaInfoPlugin().apply(compiler); + this._fileTimestamps.set(path, ts); + this._cachedDeprecatedFileTimestamps = undefined; - if (typeof options.mode !== "string") { - const WarnNoModeSetPlugin = __webpack_require__(25295); - new WarnNoModeSetPlugin().apply(compiler); - } + callback(null, ts); + }); + } - const EnsureChunkConditionsPlugin = __webpack_require__(96260); - new EnsureChunkConditionsPlugin().apply(compiler); - if (options.optimization.removeAvailableModules) { - const RemoveParentModulesPlugin = __webpack_require__(7081); - new RemoveParentModulesPlugin().apply(compiler); - } - if (options.optimization.removeEmptyChunks) { - const RemoveEmptyChunksPlugin = __webpack_require__(84760); - new RemoveEmptyChunksPlugin().apply(compiler); - } - if (options.optimization.mergeDuplicateChunks) { - const MergeDuplicateChunksPlugin = __webpack_require__(85067); - new MergeDuplicateChunksPlugin().apply(compiler); - } - if (options.optimization.flagIncludedChunks) { - const FlagIncludedChunksPlugin = __webpack_require__(50089); - new FlagIncludedChunksPlugin().apply(compiler); - } - if (options.optimization.sideEffects) { - const SideEffectsFlagPlugin = __webpack_require__(84800); - new SideEffectsFlagPlugin( - options.optimization.sideEffects === true - ).apply(compiler); - } - if (options.optimization.providedExports) { - const FlagDependencyExportsPlugin = __webpack_require__(84506); - new FlagDependencyExportsPlugin().apply(compiler); - } - if (options.optimization.usedExports) { - const FlagDependencyUsagePlugin = __webpack_require__(58812); - new FlagDependencyUsagePlugin( - options.optimization.usedExports === "global" - ).apply(compiler); - } - if (options.optimization.innerGraph) { - const InnerGraphPlugin = __webpack_require__(28758); - new InnerGraphPlugin().apply(compiler); - } - if (options.optimization.mangleExports) { - const MangleExportsPlugin = __webpack_require__(27868); - new MangleExportsPlugin( - options.optimization.mangleExports !== "size" - ).apply(compiler); - } - if (options.optimization.concatenateModules) { - const ModuleConcatenationPlugin = __webpack_require__(74844); - new ModuleConcatenationPlugin().apply(compiler); - } - if (options.optimization.splitChunks) { - const SplitChunksPlugin = __webpack_require__(21478); - new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler); - } - if (options.optimization.runtimeChunk) { - const RuntimeChunkPlugin = __webpack_require__(2837); - new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler); - } - if (!options.optimization.emitOnErrors) { - const NoEmitOnErrorsPlugin = __webpack_require__(50169); - new NoEmitOnErrorsPlugin().apply(compiler); - } - if (options.optimization.realContentHash) { - const RealContentHashPlugin = __webpack_require__(46043); - new RealContentHashPlugin({ - hashFunction: options.output.hashFunction, - hashDigest: options.output.hashDigest - }).apply(compiler); - } - if (options.optimization.checkWasmTypes) { - const WasmFinalizeExportsPlugin = __webpack_require__(19810); - new WasmFinalizeExportsPlugin().apply(compiler); - } - const moduleIds = options.optimization.moduleIds; - if (moduleIds) { - switch (moduleIds) { - case "natural": { - const NaturalModuleIdsPlugin = __webpack_require__(83366); - new NaturalModuleIdsPlugin().apply(compiler); - break; - } - case "named": { - const NamedModuleIdsPlugin = __webpack_require__(24339); - new NamedModuleIdsPlugin().apply(compiler); - break; - } - case "hashed": { - const WarnDeprecatedOptionPlugin = __webpack_require__(76537); - const HashedModuleIdsPlugin = __webpack_require__(21825); - new WarnDeprecatedOptionPlugin( - "optimization.moduleIds", - "hashed", - "deterministic" - ).apply(compiler); - new HashedModuleIdsPlugin({ - hashFunction: options.output.hashFunction - }).apply(compiler); - break; - } - case "deterministic": { - const DeterministicModuleIdsPlugin = __webpack_require__(76692); - new DeterministicModuleIdsPlugin().apply(compiler); - break; - } - case "size": { - const OccurrenceModuleIdsPlugin = __webpack_require__(35371); - new OccurrenceModuleIdsPlugin({ - prioritiseInitial: true - }).apply(compiler); - break; - } - default: - throw new Error( - `webpack bug: moduleIds: ${moduleIds} is not implemented` - ); - } - } - const chunkIds = options.optimization.chunkIds; - if (chunkIds) { - switch (chunkIds) { - case "natural": { - const NaturalChunkIdsPlugin = __webpack_require__(86221); - new NaturalChunkIdsPlugin().apply(compiler); - break; - } - case "named": { - const NamedChunkIdsPlugin = __webpack_require__(6454); - new NamedChunkIdsPlugin().apply(compiler); - break; - } - case "deterministic": { - const DeterministicChunkIdsPlugin = __webpack_require__(8747); - new DeterministicChunkIdsPlugin().apply(compiler); - break; - } - case "size": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const OccurrenceChunkIdsPlugin = __webpack_require__(51020); - new OccurrenceChunkIdsPlugin({ - prioritiseInitial: true - }).apply(compiler); - break; + _readFileHash(path, callback) { + this.fs.readFile(path, (err, content) => { + if (err) { + if (err.code === "EISDIR") { + this._fileHashes.set(path, "directory"); + return callback(null, "directory"); } - case "total-size": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const OccurrenceChunkIdsPlugin = __webpack_require__(51020); - new OccurrenceChunkIdsPlugin({ - prioritiseInitial: false - }).apply(compiler); - break; + if (err.code === "ENOENT") { + this._fileHashes.set(path, null); + return callback(null, null); } - default: - throw new Error( - `webpack bug: chunkIds: ${chunkIds} is not implemented` - ); - } - } - if (options.optimization.nodeEnv) { - const DefinePlugin = __webpack_require__(79065); - new DefinePlugin({ - "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv) - }).apply(compiler); - } - if (options.optimization.minimize) { - for (const minimizer of options.optimization.minimizer) { - if (typeof minimizer === "function") { - minimizer.call(compiler, compiler); - } else if (minimizer !== "...") { - minimizer.apply(compiler); + if (err.code === "ERR_FS_FILE_TOO_LARGE") { + this.logger.warn(`Ignoring ${path} for hashing as it's very large`); + this._fileHashes.set(path, "too large"); + return callback(null, "too large"); } + return callback(err); } - } - if (options.performance) { - const SizeLimitsPlugin = __webpack_require__(32557); - new SizeLimitsPlugin(options.performance).apply(compiler); - } + const hash = createHash(this._hashFunction); - new TemplatedPathPlugin().apply(compiler); + hash.update(content); - new RecordIdsPlugin({ - portableIds: options.optimization.portableRecords - }).apply(compiler); + const digest = /** @type {string} */ (hash.digest("hex")); - new WarnCaseSensitiveModulesPlugin().apply(compiler); + this._fileHashes.set(path, digest); - const AddManagedPathsPlugin = __webpack_require__(47942); - new AddManagedPathsPlugin( - options.snapshot.managedPaths, - options.snapshot.immutablePaths - ).apply(compiler); + callback(null, digest); + }); + } - if (options.cache && typeof options.cache === "object") { - const cacheOptions = options.cache; - switch (cacheOptions.type) { - case "memory": { - if (isFinite(cacheOptions.maxGenerations)) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const MemoryWithGcCachePlugin = __webpack_require__(99334); - new MemoryWithGcCachePlugin({ - maxGenerations: cacheOptions.maxGenerations - }).apply(compiler); - } else { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const MemoryCachePlugin = __webpack_require__(52539); - new MemoryCachePlugin().apply(compiler); - } - if (cacheOptions.cacheUnaffected) { - if (!options.experiments.cacheUnaffected) { - throw new Error( - "'cache.cacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled" - ); - } - compiler.moduleMemCaches = new Map(); - } - break; + _getFileTimestampAndHash(path, callback) { + const continueWithHash = hash => { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache !== "ignore") { + const result = { + ...cache, + hash + }; + this._fileTshs.set(path, result); + return callback(null, result); + } else { + this._fileTshs.set(path, hash); + return callback(null, hash); } - case "filesystem": { - const AddBuildDependenciesPlugin = __webpack_require__(28034); - for (const key in cacheOptions.buildDependencies) { - const list = cacheOptions.buildDependencies[key]; - new AddBuildDependenciesPlugin(list).apply(compiler); - } - if (!isFinite(cacheOptions.maxMemoryGenerations)) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const MemoryCachePlugin = __webpack_require__(52539); - new MemoryCachePlugin().apply(compiler); - } else if (cacheOptions.maxMemoryGenerations !== 0) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const MemoryWithGcCachePlugin = __webpack_require__(99334); - new MemoryWithGcCachePlugin({ - maxGenerations: cacheOptions.maxMemoryGenerations - }).apply(compiler); - } - if (cacheOptions.memoryCacheUnaffected) { - if (!options.experiments.cacheUnaffected) { - throw new Error( - "'cache.memoryCacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled" - ); - } - compiler.moduleMemCaches = new Map(); + } else { + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) { + return callback(err); } - switch (cacheOptions.store) { - case "pack": { - const IdleFileCachePlugin = __webpack_require__(71985); - const PackFileCacheStrategy = __webpack_require__(86180); - new IdleFileCachePlugin( - new PackFileCacheStrategy({ - compiler, - fs: compiler.intermediateFileSystem, - context: options.context, - cacheLocation: cacheOptions.cacheLocation, - version: cacheOptions.version, - logger: compiler.getInfrastructureLogger( - "webpack.cache.PackFileCacheStrategy" - ), - snapshot: options.snapshot, - maxAge: cacheOptions.maxAge, - profile: cacheOptions.profile, - allowCollectingMemory: cacheOptions.allowCollectingMemory, - compression: cacheOptions.compression - }), - cacheOptions.idleTimeout, - cacheOptions.idleTimeoutForInitialStore, - cacheOptions.idleTimeoutAfterLargeChanges - ).apply(compiler); - break; - } - default: - throw new Error("Unhandled value for cache.store"); - } - break; - } - default: - // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339) - throw new Error(`Unknown cache type ${cacheOptions.type}`); + const result = { + ...entry, + hash + }; + this._fileTshs.set(path, result); + return callback(null, result); + }); } - } - new ResolverCachePlugin().apply(compiler); - - if (options.ignoreWarnings && options.ignoreWarnings.length > 0) { - const IgnoreWarningsPlugin = __webpack_require__(7373); - new IgnoreWarningsPlugin(options.ignoreWarnings).apply(compiler); - } + }; - compiler.hooks.afterPlugins.call(compiler); - if (!compiler.inputFileSystem) { - throw new Error("No input filesystem provided"); - } - compiler.resolverFactory.hooks.resolveOptions - .for("normal") - .tap("WebpackOptionsApply", resolveOptions => { - resolveOptions = cleverMerge(options.resolve, resolveOptions); - resolveOptions.fileSystem = compiler.inputFileSystem; - return resolveOptions; - }); - compiler.resolverFactory.hooks.resolveOptions - .for("context") - .tap("WebpackOptionsApply", resolveOptions => { - resolveOptions = cleverMerge(options.resolve, resolveOptions); - resolveOptions.fileSystem = compiler.inputFileSystem; - resolveOptions.resolveToContext = true; - return resolveOptions; - }); - compiler.resolverFactory.hooks.resolveOptions - .for("loader") - .tap("WebpackOptionsApply", resolveOptions => { - resolveOptions = cleverMerge(options.resolveLoader, resolveOptions); - resolveOptions.fileSystem = compiler.inputFileSystem; - return resolveOptions; + const cache = this._fileHashes.get(path); + if (cache !== undefined) { + continueWithHash(cache); + } else { + this.fileHashQueue.add(path, (err, entry) => { + if (err) { + return callback(err); + } + continueWithHash(entry); }); - compiler.hooks.afterResolvers.call(compiler); - return options; + } } -} - -module.exports = WebpackOptionsApply; - - -/***/ }), - -/***/ 14452: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @template T + * @template ItemType + * @param {Object} options options + * @param {string} options.path path + * @param {function(string): ItemType} options.fromImmutablePath called when context item is an immutable path + * @param {function(string): ItemType} options.fromManagedItem called when context item is a managed path + * @param {function(string, string, function(Error=, ItemType=): void): void} options.fromSymlink called when context item is a symlink + * @param {function(string, IStats, function(Error=, ItemType=): void): void} options.fromFile called when context item is a file + * @param {function(string, IStats, function(Error=, ItemType=): void): void} options.fromDirectory called when context item is a directory + * @param {function(string[], ItemType[]): T} options.reduce called from all context items + * @param {function((Error | null)=, (T)=): void} callback callback + */ + _readContext( + { + path, + fromImmutablePath, + fromManagedItem, + fromSymlink, + fromFile, + fromDirectory, + reduce + }, + callback + ) { + this.fs.readdir(path, (err, _files) => { + if (err) { + if (err.code === "ENOENT") { + return callback(null, null); + } + return callback(err); + } + const files = /** @type {string[]} */ (_files) + .map(file => file.normalize("NFC")) + .filter(file => !/^\./.test(file)) + .sort(); + asyncLib.map( + files, + (file, callback) => { + const child = join(this.fs, path, file); + for (const immutablePath of this.immutablePathsRegExps) { + if (immutablePath.test(path)) { + // ignore any immutable path for timestamping + return callback(null, fromImmutablePath(path)); + } + } + for (const immutablePath of this.immutablePathsWithSlash) { + if (path.startsWith(immutablePath)) { + // ignore any immutable path for timestamping + return callback(null, fromImmutablePath(path)); + } + } + for (const managedPath of this.managedPathsRegExps) { + const match = managedPath.exec(path); + if (match) { + const managedItem = getManagedItem(match[1], path); + if (managedItem) { + // construct timestampHash from managed info + return this.managedItemQueue.add(managedItem, (err, info) => { + if (err) return callback(err); + return callback(null, fromManagedItem(info)); + }); + } + } + } + for (const managedPath of this.managedPathsWithSlash) { + if (path.startsWith(managedPath)) { + const managedItem = getManagedItem(managedPath, child); + if (managedItem) { + // construct timestampHash from managed info + return this.managedItemQueue.add(managedItem, (err, info) => { + if (err) return callback(err); + return callback(null, fromManagedItem(info)); + }); + } + } + } + lstatReadlinkAbsolute(this.fs, child, (err, stat) => { + if (err) return callback(err); -const { applyWebpackOptionsDefaults } = __webpack_require__(92988); -const { getNormalizedWebpackOptions } = __webpack_require__(26693); + if (typeof stat === "string") { + return fromSymlink(child, stat, callback); + } -class WebpackOptionsDefaulter { - process(options) { - options = getNormalizedWebpackOptions(options); - applyWebpackOptionsDefaults(options); - return options; + if (stat.isFile()) { + return fromFile(child, stat, callback); + } + if (stat.isDirectory()) { + return fromDirectory(child, stat, callback); + } + callback(null, null); + }); + }, + (err, results) => { + if (err) return callback(err); + const result = reduce(files, results); + callback(null, result); + } + ); + }); } -} - -module.exports = WebpackOptionsDefaulter; + _readContextTimestamp(path, callback) { + this._readContext( + { + path, + fromImmutablePath: () => null, + fromManagedItem: info => ({ + safeTime: 0, + timestampHash: info + }), + fromSymlink: (file, target, callback) => { + callback(null, { + timestampHash: target, + symlinks: new Set([target]) + }); + }, + fromFile: (file, stat, callback) => { + // Prefer the cached value over our new stat to report consistent results + const cache = this._fileTimestamps.get(file); + if (cache !== undefined) + return callback(null, cache === "ignore" ? null : cache); -/***/ }), + const mtime = +stat.mtime; -/***/ 98421: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (mtime) applyMtime(mtime); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov -*/ + const ts = { + safeTime: mtime ? mtime + FS_ACCURACY : Infinity, + timestamp: mtime + }; + this._fileTimestamps.set(file, ts); + this._cachedDeprecatedFileTimestamps = undefined; + callback(null, ts); + }, + fromDirectory: (directory, stat, callback) => { + this.contextTimestampQueue.increaseParallelism(); + this._getUnresolvedContextTimestamp(directory, (err, tsEntry) => { + this.contextTimestampQueue.decreaseParallelism(); + callback(err, tsEntry); + }); + }, + reduce: (files, tsEntries) => { + let symlinks = undefined; + const hash = createHash(this._hashFunction); -const mimeTypes = __webpack_require__(78585); -const path = __webpack_require__(71017); -const { RawSource } = __webpack_require__(51255); -const Generator = __webpack_require__(93401); -const RuntimeGlobals = __webpack_require__(16475); -const createHash = __webpack_require__(49835); -const { makePathsRelative } = __webpack_require__(82186); + for (const file of files) hash.update(file); + let safeTime = 0; + for (const entry of tsEntries) { + if (!entry) { + hash.update("n"); + continue; + } + if (entry.timestamp) { + hash.update("f"); + hash.update(`${entry.timestamp}`); + } else if (entry.timestampHash) { + hash.update("d"); + hash.update(`${entry.timestampHash}`); + } + if (entry.symlinks !== undefined) { + if (symlinks === undefined) symlinks = new Set(); + addAll(entry.symlinks, symlinks); + } + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + } -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").AssetGeneratorOptions} AssetGeneratorOptions */ -/** @typedef {import("../../declarations/WebpackOptions").AssetModuleOutputPath} AssetModuleOutputPath */ -/** @typedef {import("../../declarations/WebpackOptions").RawPublicPath} RawPublicPath */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../util/Hash")} Hash */ + const digest = /** @type {string} */ (hash.digest("hex")); -const mergeMaybeArrays = (a, b) => { - const set = new Set(); - if (Array.isArray(a)) for (const item of a) set.add(item); - else set.add(a); - if (Array.isArray(b)) for (const item of b) set.add(item); - else set.add(b); - return Array.from(set); -}; + const result = { + safeTime, + timestampHash: digest + }; + if (symlinks) result.symlinks = symlinks; + return result; + } + }, + (err, result) => { + if (err) return callback(err); + this._contextTimestamps.set(path, result); + this._cachedDeprecatedContextTimestamps = undefined; -const mergeAssetInfo = (a, b) => { - const result = { ...a, ...b }; - for (const key of Object.keys(a)) { - if (key in b) { - if (a[key] === b[key]) continue; - switch (key) { - case "fullhash": - case "chunkhash": - case "modulehash": - case "contenthash": - result[key] = mergeMaybeArrays(a[key], b[key]); - break; - case "immutable": - case "development": - case "hotModuleReplacement": - case "javascriptModule": - result[key] = a[key] || b[key]; - break; - case "related": - result[key] = mergeRelatedInfo(a[key], b[key]); - break; - default: - throw new Error(`Can't handle conflicting asset info for ${key}`); + callback(null, result); } - } - } - return result; -}; - -const mergeRelatedInfo = (a, b) => { - const result = { ...a, ...b }; - for (const key of Object.keys(a)) { - if (key in b) { - if (a[key] === b[key]) continue; - result[key] = mergeMaybeArrays(a[key], b[key]); - } + ); } - return result; -}; - -const encodeDataUri = (encoding, source) => { - let encodedContent; - - switch (encoding) { - case "base64": { - encodedContent = source.buffer().toString("base64"); - break; - } - case false: { - const content = source.source(); - if (typeof content !== "string") { - encodedContent = content.toString("utf-8"); + /** + * @param {ContextFileSystemInfoEntry} entry entry + * @param {function((Error | null)=, ResolvedContextFileSystemInfoEntry=): void} callback callback + * @returns {void} + */ + _resolveContextTimestamp(entry, callback) { + const hashes = []; + let safeTime = 0; + processAsyncTree( + entry.symlinks, + 10, + (target, push, callback) => { + this._getUnresolvedContextTimestamp(target, (err, entry) => { + if (err) return callback(err); + if (entry && entry !== "ignore") { + hashes.push(entry.timestampHash); + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + if (entry.symlinks !== undefined) { + for (const target of entry.symlinks) push(target); + } + } + callback(); + }); + }, + err => { + if (err) return callback(err); + const hash = createHash(this._hashFunction); + hash.update(entry.timestampHash); + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + hashes.sort(); + for (const h of hashes) { + hash.update(h); + } + callback( + null, + (entry.resolved = { + safeTime, + timestampHash: /** @type {string} */ (hash.digest("hex")) + }) + ); } - - encodedContent = encodeURIComponent(encodedContent).replace( - /[!'()*]/g, - character => "%" + character.codePointAt(0).toString(16) - ); - break; - } - default: - throw new Error(`Unsupported encoding '${encoding}'`); + ); } - return encodedContent; -}; - -const decodeDataUriContent = (encoding, content) => { - const isBase64 = encoding === "base64"; - return isBase64 - ? Buffer.from(content, "base64") - : Buffer.from(decodeURIComponent(content), "ascii"); -}; + _readContextHash(path, callback) { + this._readContext( + { + path, + fromImmutablePath: () => "", + fromManagedItem: info => info || "", + fromSymlink: (file, target, callback) => { + callback(null, { + hash: target, + symlinks: new Set([target]) + }); + }, + fromFile: (file, stat, callback) => + this.getFileHash(file, (err, hash) => { + callback(err, hash || ""); + }), + fromDirectory: (directory, stat, callback) => { + this.contextHashQueue.increaseParallelism(); + this._getUnresolvedContextHash(directory, (err, hash) => { + this.contextHashQueue.decreaseParallelism(); + callback(err, hash || ""); + }); + }, + /** + * @param {string[]} files files + * @param {(string | ContextHash)[]} fileHashes hashes + * @returns {ContextHash} reduced hash + */ + reduce: (files, fileHashes) => { + let symlinks = undefined; + const hash = createHash(this._hashFunction); -const JS_TYPES = new Set(["javascript"]); -const JS_AND_ASSET_TYPES = new Set(["javascript", "asset"]); + for (const file of files) hash.update(file); + for (const entry of fileHashes) { + if (typeof entry === "string") { + hash.update(entry); + } else { + hash.update(entry.hash); + if (entry.symlinks) { + if (symlinks === undefined) symlinks = new Set(); + addAll(entry.symlinks, symlinks); + } + } + } -class AssetGenerator extends Generator { - /** - * @param {AssetGeneratorOptions["dataUrl"]=} dataUrlOptions the options for the data url - * @param {string=} filename override for output.assetModuleFilename - * @param {RawPublicPath=} publicPath override for output.assetModulePublicPath - * @param {AssetModuleOutputPath=} outputPath the output path for the emitted file which is not included in the runtime import - * @param {boolean=} emit generate output asset - */ - constructor(dataUrlOptions, filename, publicPath, outputPath, emit) { - super(); - this.dataUrlOptions = dataUrlOptions; - this.filename = filename; - this.publicPath = publicPath; - this.outputPath = outputPath; - this.emit = emit; + const result = { + hash: /** @type {string} */ (hash.digest("hex")) + }; + if (symlinks) result.symlinks = symlinks; + return result; + } + }, + (err, result) => { + if (err) return callback(err); + this._contextHashes.set(path, result); + return callback(null, result); + } + ); } /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code + * @param {ContextHash} entry context hash + * @param {function((Error | null)=, string=): void} callback callback + * @returns {void} */ - generate( - module, - { runtime, chunkGraph, runtimeTemplate, runtimeRequirements, type, getData } - ) { - switch (type) { - case "asset": - return module.originalSource(); - default: { - runtimeRequirements.add(RuntimeGlobals.module); - - const originalSource = module.originalSource(); - if (module.buildInfo.dataUrl) { - let encodedSource; - if (typeof this.dataUrlOptions === "function") { - encodedSource = this.dataUrlOptions.call( - null, - originalSource.source(), - { - filename: module.matchResource || module.resource, - module - } - ); - } else { - /** @type {string | false | undefined} */ - let encoding = this.dataUrlOptions.encoding; - if (encoding === undefined) { - if ( - module.resourceResolveData && - module.resourceResolveData.encoding !== undefined - ) { - encoding = module.resourceResolveData.encoding; - } - } - if (encoding === undefined) { - encoding = "base64"; - } - let ext; - let mimeType = this.dataUrlOptions.mimetype; - if (mimeType === undefined) { - ext = path.extname(module.nameForCondition()); - if ( - module.resourceResolveData && - module.resourceResolveData.mimetype !== undefined - ) { - mimeType = - module.resourceResolveData.mimetype + - module.resourceResolveData.parameters; - } else if (ext) { - mimeType = mimeTypes.lookup(ext); - } - } - if (typeof mimeType !== "string") { - throw new Error( - "DataUrl can't be generated automatically, " + - `because there is no mimetype for "${ext}" in mimetype database. ` + - 'Either pass a mimetype via "generator.mimetype" or ' + - 'use type: "asset/resource" to create a resource file instead of a DataUrl' - ); + _resolveContextHash(entry, callback) { + const hashes = []; + processAsyncTree( + entry.symlinks, + 10, + (target, push, callback) => { + this._getUnresolvedContextHash(target, (err, hash) => { + if (err) return callback(err); + if (hash) { + hashes.push(hash.hash); + if (hash.symlinks !== undefined) { + for (const target of hash.symlinks) push(target); } + } + callback(); + }); + }, + err => { + if (err) return callback(err); + const hash = createHash(this._hashFunction); + hash.update(entry.hash); + hashes.sort(); + for (const h of hashes) { + hash.update(h); + } + callback( + null, + (entry.resolved = /** @type {string} */ (hash.digest("hex"))) + ); + } + ); + } - let encodedContent; + _readContextTimestampAndHash(path, callback) { + const finalize = (timestamp, hash) => { + const result = + timestamp === "ignore" + ? hash + : { + ...timestamp, + ...hash + }; + this._contextTshs.set(path, result); + callback(null, result); + }; + const cachedHash = this._contextHashes.get(path); + const cachedTimestamp = this._contextTimestamps.get(path); + if (cachedHash !== undefined) { + if (cachedTimestamp !== undefined) { + finalize(cachedTimestamp, cachedHash); + } else { + this.contextTimestampQueue.add(path, (err, entry) => { + if (err) return callback(err); + finalize(entry, cachedHash); + }); + } + } else { + if (cachedTimestamp !== undefined) { + this.contextHashQueue.add(path, (err, entry) => { + if (err) return callback(err); + finalize(cachedTimestamp, entry); + }); + } else { + this._readContext( + { + path, + fromImmutablePath: () => null, + fromManagedItem: info => ({ + safeTime: 0, + timestampHash: info, + hash: info || "" + }), + fromSymlink: (fle, target, callback) => { + callback(null, { + timestampHash: target, + hash: target, + symlinks: new Set([target]) + }); + }, + fromFile: (file, stat, callback) => { + this._getFileTimestampAndHash(file, callback); + }, + fromDirectory: (directory, stat, callback) => { + this.contextTshQueue.increaseParallelism(); + this.contextTshQueue.add(directory, (err, result) => { + this.contextTshQueue.decreaseParallelism(); + callback(err, result); + }); + }, + /** + * @param {string[]} files files + * @param {(Partial & Partial | string | null)[]} results results + * @returns {ContextTimestampAndHash} tsh + */ + reduce: (files, results) => { + let symlinks = undefined; - if ( - module.resourceResolveData && - module.resourceResolveData.encoding === encoding && - decodeDataUriContent( - module.resourceResolveData.encoding, - module.resourceResolveData.encodedContent - ).equals(originalSource.buffer()) - ) { - encodedContent = module.resourceResolveData.encodedContent; - } else { - encodedContent = encodeDataUri(encoding, originalSource); - } + const tsHash = createHash(this._hashFunction); + const hash = createHash(this._hashFunction); - encodedSource = `data:${mimeType}${ - encoding ? `;${encoding}` : "" - },${encodedContent}`; - } - const data = getData(); - data.set("url", Buffer.from(encodedSource)); - return new RawSource( - `${RuntimeGlobals.module}.exports = ${JSON.stringify( - encodedSource - )};` - ); - } else { - const assetModuleFilename = - this.filename || runtimeTemplate.outputOptions.assetModuleFilename; - const hash = createHash(runtimeTemplate.outputOptions.hashFunction); - if (runtimeTemplate.outputOptions.hashSalt) { - hash.update(runtimeTemplate.outputOptions.hashSalt); - } - hash.update(originalSource.buffer()); - const fullHash = /** @type {string} */ ( - hash.digest(runtimeTemplate.outputOptions.hashDigest) - ); - const contentHash = fullHash.slice( - 0, - runtimeTemplate.outputOptions.hashDigestLength - ); - module.buildInfo.fullContentHash = fullHash; - const sourceFilename = makePathsRelative( - runtimeTemplate.compilation.compiler.context, - module.matchResource || module.resource, - runtimeTemplate.compilation.compiler.root - ).replace(/^\.\//, ""); - let { path: filename, info: assetInfo } = - runtimeTemplate.compilation.getAssetPathWithInfo( - assetModuleFilename, - { - module, - runtime, - filename: sourceFilename, - chunkGraph, - contentHash + for (const file of files) { + tsHash.update(file); + hash.update(file); } - ); - let assetPath; - if (this.publicPath !== undefined) { - const { path, info } = - runtimeTemplate.compilation.getAssetPathWithInfo( - this.publicPath, - { - module, - runtime, - filename: sourceFilename, - chunkGraph, - contentHash + let safeTime = 0; + for (const entry of results) { + if (!entry) { + tsHash.update("n"); + continue; } - ); - assetInfo = mergeAssetInfo(assetInfo, info); - assetPath = JSON.stringify(path + filename); - } else { - runtimeRequirements.add(RuntimeGlobals.publicPath); // add __webpack_require__.p - assetPath = runtimeTemplate.concatenation( - { expr: RuntimeGlobals.publicPath }, - filename - ); - } - assetInfo = { - sourceFilename, - ...assetInfo - }; - if (this.outputPath) { - const { path: outputPath, info } = - runtimeTemplate.compilation.getAssetPathWithInfo( - this.outputPath, - { - module, - runtime, - filename: sourceFilename, - chunkGraph, - contentHash + if (typeof entry === "string") { + tsHash.update("n"); + hash.update(entry); + continue; } - ); - assetInfo = mergeAssetInfo(assetInfo, info); - filename = path.posix.join(outputPath, filename); - } - module.buildInfo.filename = filename; - module.buildInfo.assetInfo = assetInfo; - if (getData) { - // Due to code generation caching module.buildInfo.XXX can't used to store such information - // It need to be stored in the code generation results instead, where it's cached too - // TODO webpack 6 For back-compat reasons we also store in on module.buildInfo - const data = getData(); - data.set("fullContentHash", fullHash); - data.set("filename", filename); - data.set("assetInfo", assetInfo); - } + if (entry.timestamp) { + tsHash.update("f"); + tsHash.update(`${entry.timestamp}`); + } else if (entry.timestampHash) { + tsHash.update("d"); + tsHash.update(`${entry.timestampHash}`); + } + if (entry.symlinks !== undefined) { + if (symlinks === undefined) symlinks = new Set(); + addAll(entry.symlinks, symlinks); + } + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + hash.update(entry.hash); + } - return new RawSource( - `${RuntimeGlobals.module}.exports = ${assetPath};` - ); - } + const result = { + safeTime, + timestampHash: /** @type {string} */ (tsHash.digest("hex")), + hash: /** @type {string} */ (hash.digest("hex")) + }; + if (symlinks) result.symlinks = symlinks; + return result; + } + }, + (err, result) => { + if (err) return callback(err); + this._contextTshs.set(path, result); + return callback(null, result); + } + ); } } } /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) + * @param {ContextTimestampAndHash} entry entry + * @param {function((Error | null)=, ResolvedContextTimestampAndHash=): void} callback callback + * @returns {void} */ - getTypes(module) { - if ((module.buildInfo && module.buildInfo.dataUrl) || this.emit === false) { - return JS_TYPES; - } else { - return JS_AND_ASSET_TYPES; - } + _resolveContextTsh(entry, callback) { + const hashes = []; + const tsHashes = []; + let safeTime = 0; + processAsyncTree( + entry.symlinks, + 10, + (target, push, callback) => { + this._getUnresolvedContextTsh(target, (err, entry) => { + if (err) return callback(err); + if (entry) { + hashes.push(entry.hash); + if (entry.timestampHash) tsHashes.push(entry.timestampHash); + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + if (entry.symlinks !== undefined) { + for (const target of entry.symlinks) push(target); + } + } + callback(); + }); + }, + err => { + if (err) return callback(err); + const hash = createHash(this._hashFunction); + const tsHash = createHash(this._hashFunction); + hash.update(entry.hash); + if (entry.timestampHash) tsHash.update(entry.timestampHash); + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + hashes.sort(); + for (const h of hashes) { + hash.update(h); + } + tsHashes.sort(); + for (const h of tsHashes) { + tsHash.update(h); + } + callback( + null, + (entry.resolved = { + safeTime, + timestampHash: /** @type {string} */ (tsHash.digest("hex")), + hash: /** @type {string} */ (hash.digest("hex")) + }) + ); + } + ); } - /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module - */ - getSize(module, type) { - switch (type) { - case "asset": { - const originalSource = module.originalSource(); - - if (!originalSource) { - return 0; + _getManagedItemDirectoryInfo(path, callback) { + this.fs.readdir(path, (err, elements) => { + if (err) { + if (err.code === "ENOENT" || err.code === "ENOTDIR") { + return callback(null, EMPTY_SET); } + return callback(err); + } + const set = new Set( + /** @type {string[]} */ (elements).map(element => + join(this.fs, path, element) + ) + ); + callback(null, set); + }); + } - return originalSource.size(); + _getManagedItemInfo(path, callback) { + const dir = dirname(this.fs, path); + this.managedItemDirectoryQueue.add(dir, (err, elements) => { + if (err) { + return callback(err); + } + if (!elements.has(path)) { + // file or directory doesn't exist + this._managedItems.set(path, "*missing"); + return callback(null, "*missing"); + } + // something exists + // it may be a file or directory + if ( + path.endsWith("node_modules") && + (path.endsWith("/node_modules") || path.endsWith("\\node_modules")) + ) { + // we are only interested in existence of this special directory + this._managedItems.set(path, "*node_modules"); + return callback(null, "*node_modules"); } - default: - if (module.buildInfo && module.buildInfo.dataUrl) { - const originalSource = module.originalSource(); - if (!originalSource) { - return 0; + // we assume it's a directory, as files shouldn't occur in managed paths + const packageJsonPath = join(this.fs, path, "package.json"); + this.fs.readFile(packageJsonPath, (err, content) => { + if (err) { + if (err.code === "ENOENT" || err.code === "ENOTDIR") { + // no package.json or path is not a directory + this.fs.readdir(path, (err, elements) => { + if ( + !err && + elements.length === 1 && + elements[0] === "node_modules" + ) { + // This is only a grouping folder e. g. used by yarn + // we are only interested in existence of this special directory + this._managedItems.set(path, "*nested"); + return callback(null, "*nested"); + } + this.logger.warn( + `Managed item ${path} isn't a directory or doesn't contain a package.json (see snapshot.managedPaths option)` + ); + return callback(); + }); + return; } - - // roughly for data url - // Example: m.exports="data:image/png;base64,ag82/f+2==" - // 4/3 = base64 encoding - // 34 = ~ data url header + footer + rounding - return originalSource.size() * 1.34 + 36; - } else { - // it's only estimated so this number is probably fine - // Example: m.exports=r.p+"0123456789012345678901.ext" - return 42; + return callback(err); + } + let data; + try { + data = JSON.parse(content.toString("utf-8")); + } catch (e) { + return callback(e); + } + if (!data.name) { + this.logger.warn( + `${packageJsonPath} doesn't contain a "name" property (see snapshot.managedPaths option)` + ); + return callback(); } + const info = `${data.name || ""}@${data.version || ""}`; + this._managedItems.set(path, info); + callback(null, info); + }); + }); + } + + getDeprecatedFileTimestamps() { + if (this._cachedDeprecatedFileTimestamps !== undefined) + return this._cachedDeprecatedFileTimestamps; + const map = new Map(); + for (const [path, info] of this._fileTimestamps) { + if (info) map.set(path, typeof info === "object" ? info.safeTime : null); } + return (this._cachedDeprecatedFileTimestamps = map); } - /** - * @param {Hash} hash hash that will be modified - * @param {UpdateHashContext} updateHashContext context for updating hash - */ - updateHash(hash, { module }) { - hash.update(module.buildInfo.dataUrl ? "data-url" : "resource"); + getDeprecatedContextTimestamps() { + if (this._cachedDeprecatedContextTimestamps !== undefined) + return this._cachedDeprecatedContextTimestamps; + const map = new Map(); + for (const [path, info] of this._contextTimestamps) { + if (info) map.set(path, typeof info === "object" ? info.safeTime : null); + } + return (this._cachedDeprecatedContextTimestamps = map); } } -module.exports = AssetGenerator; +module.exports = FileSystemInfo; +module.exports.Snapshot = Snapshot; /***/ }), -/***/ 16109: +/***/ 58727: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Yuta Hiroto @hiroppy + Author Tobias Koppers @sokra */ -const { cleverMerge } = __webpack_require__(60839); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const createSchemaValidation = __webpack_require__(32540); -const memoize = __webpack_require__(78676); +const { getEntryRuntime, mergeRuntimeOwned } = __webpack_require__(17156); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ -const getSchema = name => { - const { definitions } = __webpack_require__(73342); - return { - definitions, - oneOf: [{ $ref: `#/definitions/${name}` }] - }; -}; +class FlagAllModulesAsUsedPlugin { + constructor(explanation) { + this.explanation = explanation; + } -const generatorValidationOptions = { - name: "Asset Modules Plugin", - baseDataPath: "generator" -}; -const validateGeneratorOptions = { - asset: createSchemaValidation( - __webpack_require__(55125), - () => getSchema("AssetGeneratorOptions"), - generatorValidationOptions - ), - "asset/resource": createSchemaValidation( - __webpack_require__(4405), - () => getSchema("AssetResourceGeneratorOptions"), - generatorValidationOptions - ), - "asset/inline": createSchemaValidation( - __webpack_require__(62368), - () => getSchema("AssetInlineGeneratorOptions"), - generatorValidationOptions - ) -}; - -const validateParserOptions = createSchemaValidation( - __webpack_require__(45020), - () => getSchema("AssetParserOptions"), - { - name: "Asset Modules Plugin", - baseDataPath: "parser" - } -); - -const getAssetGenerator = memoize(() => __webpack_require__(98421)); -const getAssetParser = memoize(() => __webpack_require__(91112)); -const getAssetSourceParser = memoize(() => __webpack_require__(30953)); -const getAssetSourceGenerator = memoize(() => - __webpack_require__(18749) -); - -const type = "asset"; -const plugin = "AssetModulesPlugin"; - -class AssetModulesPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance @@ -58530,498 +53307,467 @@ class AssetModulesPlugin { */ apply(compiler) { compiler.hooks.compilation.tap( - plugin, - (compilation, { normalModuleFactory }) => { - normalModuleFactory.hooks.createParser - .for("asset") - .tap(plugin, parserOptions => { - validateParserOptions(parserOptions); - parserOptions = cleverMerge( - compiler.options.module.parser.asset, - parserOptions - ); - - let dataUrlCondition = parserOptions.dataUrlCondition; - if (!dataUrlCondition || typeof dataUrlCondition === "object") { - dataUrlCondition = { - maxSize: 8096, - ...dataUrlCondition - }; - } - - const AssetParser = getAssetParser(); - - return new AssetParser(dataUrlCondition); - }); - normalModuleFactory.hooks.createParser - .for("asset/inline") - .tap(plugin, parserOptions => { - const AssetParser = getAssetParser(); - - return new AssetParser(true); - }); - normalModuleFactory.hooks.createParser - .for("asset/resource") - .tap(plugin, parserOptions => { - const AssetParser = getAssetParser(); - - return new AssetParser(false); - }); - normalModuleFactory.hooks.createParser - .for("asset/source") - .tap(plugin, parserOptions => { - const AssetSourceParser = getAssetSourceParser(); - - return new AssetSourceParser(); - }); - - for (const type of ["asset", "asset/inline", "asset/resource"]) { - normalModuleFactory.hooks.createGenerator - .for(type) - .tap(plugin, generatorOptions => { - validateGeneratorOptions[type](generatorOptions); - - let dataUrl = undefined; - if (type !== "asset/resource") { - dataUrl = generatorOptions.dataUrl; - if (!dataUrl || typeof dataUrl === "object") { - dataUrl = { - encoding: undefined, - mimetype: undefined, - ...dataUrl - }; - } - } - - let filename = undefined; - let publicPath = undefined; - let outputPath = undefined; - if (type !== "asset/inline") { - filename = generatorOptions.filename; - publicPath = generatorOptions.publicPath; - outputPath = generatorOptions.outputPath; - } - - const AssetGenerator = getAssetGenerator(); - - return new AssetGenerator( - dataUrl, - filename, - publicPath, - outputPath, - generatorOptions.emit !== false + "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) ); - }); - } - normalModuleFactory.hooks.createGenerator - .for("asset/source") - .tap(plugin, () => { - const AssetSourceGenerator = getAssetSourceGenerator(); - - return new AssetSourceGenerator(); - }); - - compilation.hooks.renderManifest.tap(plugin, (result, options) => { - const { chunkGraph } = compilation; - const { chunk, codeGenerationResults } = options; - - const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( - chunk, - "asset", - compareModulesByIdentifier - ); - if (modules) { + } for (const module of modules) { - try { - const codeGenResult = codeGenerationResults.get( - module, - chunk.runtime - ); - result.push({ - render: () => codeGenResult.sources.get(type), - filename: - module.buildInfo.filename || - codeGenResult.data.get("filename"), - info: - module.buildInfo.assetInfo || - codeGenResult.data.get("assetInfo"), - auxiliary: true, - identifier: `assetModule${chunkGraph.getModuleId(module)}`, - hash: - module.buildInfo.fullContentHash || - codeGenResult.data.get("fullContentHash") - }); - } catch (e) { - e.message += `\nduring rendering of asset ${module.identifier()}`; - throw e; + const exportsInfo = moduleGraph.getExportsInfo(module); + exportsInfo.setUsedInUnknownWay(runtime); + moduleGraph.addExtraReason(module, this.explanation); + if (module.factoryMeta === undefined) { + module.factoryMeta = {}; } + module.factoryMeta.sideEffectFree = false; } } - - return result; - }); - - compilation.hooks.prepareModuleExecution.tap( - "AssetModulesPlugin", - (options, context) => { - const { codeGenerationResult } = options; - const source = codeGenerationResult.sources.get("asset"); - if (source === undefined) return; - context.assets.set(codeGenerationResult.data.get("filename"), { - source, - info: codeGenerationResult.data.get("assetInfo") - }); - } ); } ); } } -module.exports = AssetModulesPlugin; - - -/***/ }), - -/***/ 91112: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Yuta Hiroto @hiroppy -*/ - - - -const Parser = __webpack_require__(11715); - -/** @typedef {import("../../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */ -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ - -class AssetParser extends Parser { - /** - * @param {AssetParserOptions["dataUrlCondition"] | boolean} dataUrlCondition condition for inlining as DataUrl - */ - constructor(dataUrlCondition) { - super(); - this.dataUrlCondition = dataUrlCondition; - } - - /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state - */ - parse(source, state) { - if (typeof source === "object" && !Buffer.isBuffer(source)) { - throw new Error("AssetParser doesn't accept preparsed AST"); - } - state.module.buildInfo.strict = true; - state.module.buildMeta.exportsType = "default"; - - if (typeof this.dataUrlCondition === "function") { - state.module.buildInfo.dataUrl = this.dataUrlCondition(source, { - filename: state.module.matchResource || state.module.resource, - module: state.module - }); - } else if (typeof this.dataUrlCondition === "boolean") { - state.module.buildInfo.dataUrl = this.dataUrlCondition; - } else if ( - this.dataUrlCondition && - typeof this.dataUrlCondition === "object" - ) { - state.module.buildInfo.dataUrl = - Buffer.byteLength(source) <= this.dataUrlCondition.maxSize; - } else { - throw new Error("Unexpected dataUrlCondition type"); - } - - return state; - } -} - -module.exports = AssetParser; +module.exports = FlagAllModulesAsUsedPlugin; /***/ }), -/***/ 18749: +/***/ 84506: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov + Author Tobias Koppers @sokra */ -const { RawSource } = __webpack_require__(51255); -const Generator = __webpack_require__(93401); -const RuntimeGlobals = __webpack_require__(16475); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../NormalModule")} NormalModule */ - -const TYPES = new Set(["javascript"]); - -class AssetSourceGenerator extends Generator { - /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code - */ - generate(module, { chunkGraph, runtimeTemplate, runtimeRequirements }) { - runtimeRequirements.add(RuntimeGlobals.module); - - const originalSource = module.originalSource(); - - if (!originalSource) { - return new RawSource(""); - } - - const content = originalSource.source(); - - let encodedSource; - if (typeof content === "string") { - encodedSource = content; - } else { - encodedSource = content.toString("utf-8"); - } - return new RawSource( - `${RuntimeGlobals.module}.exports = ${JSON.stringify(encodedSource)};` - ); - } +const asyncLib = __webpack_require__(78175); +const Queue = __webpack_require__(65930); - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; - } +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").ExportSpec} ExportSpec */ +/** @typedef {import("./Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("./ExportsInfo")} ExportsInfo */ +/** @typedef {import("./Module")} Module */ +class FlagDependencyExportsPlugin { /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - getSize(module, type) { - const originalSource = module.originalSource(); + 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 statRestoredFromMemCache = 0; + let statRestoredFromCache = 0; + let statNoExports = 0; + let statFlaggedUncached = 0; + let statNotCached = 0; + let statQueueItemsProcessed = 0; - if (!originalSource) { - return 0; - } + const { moduleMemCaches } = compilation; - // Example: m.exports="abcd" - return originalSource.size() + 12; - } -} + /** @type {Queue} */ + const queue = new Queue(); -module.exports = AssetSourceGenerator; + // Step 1: Try to restore cached provided export info from cache + logger.time("restore cached provided exports"); + asyncLib.each( + modules, + (module, callback) => { + const exportsInfo = moduleGraph.getExportsInfo(module); + if (!module.buildMeta || !module.buildMeta.exportsType) { + if (exportsInfo.otherExportsInfo.provided !== null) { + // It's a module without declared exports + statNoExports++; + exportsInfo.setHasProvideInfo(); + exportsInfo.setUnknownExportsProvided(); + return callback(); + } + } + if (typeof module.buildInfo.hash !== "string") { + statFlaggedUncached++; + // Enqueue uncacheable module for determining the exports + queue.enqueue(module); + exportsInfo.setHasProvideInfo(); + return callback(); + } + const memCache = moduleMemCaches && moduleMemCaches.get(module); + const memCacheValue = memCache && memCache.get(this); + if (memCacheValue !== undefined) { + statRestoredFromMemCache++; + exportsInfo.restoreProvided(memCacheValue); + return callback(); + } + cache.get( + module.identifier(), + module.buildInfo.hash, + (err, result) => { + if (err) return callback(err); + if (result !== undefined) { + statRestoredFromCache++; + exportsInfo.restoreProvided(result); + } else { + statNotCached++; + // Without cached info enqueue module for determining the exports + queue.enqueue(module); + exportsInfo.setHasProvideInfo(); + } + callback(); + } + ); + }, + err => { + logger.timeEnd("restore cached provided exports"); + if (err) return callback(err); -/***/ }), + /** @type {Set} */ + const modulesToStore = new Set(); -/***/ 30953: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {Map>} */ + const dependencies = new Map(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Yuta Hiroto @hiroppy -*/ + /** @type {Module} */ + let module; + /** @type {ExportsInfo} */ + let exportsInfo; + /** @type {Map} */ + const exportsSpecsFromDependencies = new Map(); -const Parser = __webpack_require__(11715); + let cacheable = true; + let changed = false; -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ + /** + * @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); + } + }; -class AssetSourceParser extends Parser { - /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state - */ - parse(source, state) { - if (typeof source === "object" && !Buffer.isBuffer(source)) { - throw new Error("AssetSourceParser doesn't accept preparsed AST"); - } - const { module } = state; - module.buildInfo.strict = true; - module.buildMeta.exportsType = "default"; + /** + * @param {Dependency} dep the dependency + * @returns {void} + */ + const processDependency = dep => { + const exportDesc = dep.getExports(moduleGraph); + if (!exportDesc) return; + exportsSpecsFromDependencies.set(dep, exportDesc); + }; - return state; - } -} + /** + * @param {Dependency} dep dependency + * @param {ExportsSpec} exportDesc info + * @returns {void} + */ + const processExportsSpec = (dep, exportDesc) => { + const exports = exportDesc.exports; + const globalCanMangle = exportDesc.canMangle; + const globalFrom = exportDesc.from; + const globalPriority = exportDesc.priority; + const globalTerminalBinding = + exportDesc.terminalBinding || false; + const exportDeps = exportDesc.dependencies; + if (exportDesc.hideExports) { + for (const name of exportDesc.hideExports) { + const exportInfo = exportsInfo.getExportInfo(name); + exportInfo.unsetTarget(dep); + } + } + if (exports === true) { + // unknown exports + if ( + exportsInfo.setUnknownExportsProvided( + globalCanMangle, + exportDesc.excludeExports, + globalFrom && dep, + globalFrom, + globalPriority + ) + ) { + changed = true; + } + } else if (Array.isArray(exports)) { + /** + * merge in new exports + * @param {ExportsInfo} exportsInfo own exports info + * @param {(ExportSpec | string)[]} exports list of exports + */ + const mergeExports = (exportsInfo, exports) => { + for (const exportNameOrSpec of exports) { + let name; + let canMangle = globalCanMangle; + let terminalBinding = globalTerminalBinding; + let exports = undefined; + let from = globalFrom; + let fromExport = undefined; + let priority = globalPriority; + let hidden = false; + if (typeof exportNameOrSpec === "string") { + name = exportNameOrSpec; + } else { + name = exportNameOrSpec.name; + if (exportNameOrSpec.canMangle !== undefined) + canMangle = exportNameOrSpec.canMangle; + if (exportNameOrSpec.export !== undefined) + fromExport = exportNameOrSpec.export; + if (exportNameOrSpec.exports !== undefined) + exports = exportNameOrSpec.exports; + if (exportNameOrSpec.from !== undefined) + from = exportNameOrSpec.from; + if (exportNameOrSpec.priority !== undefined) + priority = exportNameOrSpec.priority; + if (exportNameOrSpec.terminalBinding !== undefined) + terminalBinding = exportNameOrSpec.terminalBinding; + if (exportNameOrSpec.hidden !== undefined) + hidden = exportNameOrSpec.hidden; + } + const exportInfo = exportsInfo.getExportInfo(name); -module.exports = AssetSourceParser; + if ( + exportInfo.provided === false || + exportInfo.provided === null + ) { + exportInfo.provided = true; + changed = true; + } + if ( + exportInfo.canMangleProvide !== false && + canMangle === false + ) { + exportInfo.canMangleProvide = false; + changed = true; + } -/***/ }), + if (terminalBinding && !exportInfo.terminalBinding) { + exportInfo.terminalBinding = true; + changed = true; + } -/***/ 19684: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (exports) { + const nestedExportsInfo = + exportInfo.createNestedExportsInfo(); + mergeExports(nestedExportsInfo, exports); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if ( + from && + (hidden + ? exportInfo.unsetTarget(dep) + : exportInfo.setTarget( + dep, + from, + fromExport === undefined ? [name] : fromExport, + priority + )) + ) { + changed = true; + } + // Recalculate target exportsInfo + const target = exportInfo.getTarget(moduleGraph); + let targetExportsInfo = 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 { RawSource } = __webpack_require__(51255); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); + const notifyDependencies = () => { + const deps = dependencies.get(module); + if (deps !== undefined) { + for (const dep of deps) { + queue.enqueue(dep); + } + } + }; -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ + logger.time("figure out provided exports"); + while (queue.length > 0) { + module = queue.dequeue(); -const TYPES = new Set(["javascript"]); + statQueueItemsProcessed++; -class RawDataUrlModule extends Module { - /** - * @param {string} url raw url - * @param {string} identifier unique identifier - * @param {string=} readableIdentifier readable identifier - */ - constructor(url, identifier, readableIdentifier) { - super("asset/raw-data-url", null); - this.url = url; - this.urlBuffer = url ? Buffer.from(url) : undefined; - this.identifierStr = identifier || this.url; - this.readableIdentifierStr = readableIdentifier || this.identifierStr; - } + exportsInfo = moduleGraph.getExportsInfo(module); - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; - } + cacheable = true; + changed = false; - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return this.identifierStr; - } + exportsSpecsFromDependencies.clear(); + moduleGraph.freeze(); + processDependenciesBlock(module); + moduleGraph.unfreeze(); + for (const [ + dep, + exportsSpec + ] of exportsSpecsFromDependencies) { + processExportsSpec(dep, exportsSpec); + } - /** - * @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) { - if (this.url === undefined) this.url = this.urlBuffer.toString(); - return Math.max(1, this.url.length); - } + if (cacheable) { + modulesToStore.add(module); + } - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return requestShortener.shorten(this.readableIdentifierStr); - } + if (changed) { + notifyDependencies(); + } + } + logger.timeEnd("figure out provided exports"); - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - return callback(null, !this.buildMeta); - } + logger.log( + `${Math.round( + (100 * (statFlaggedUncached + statNotCached)) / + (statRestoredFromMemCache + + statRestoredFromCache + + statNotCached + + statFlaggedUncached + + statNoExports) + )}% of exports of modules have been determined (${statNoExports} no declared exports, ${statNotCached} not cached, ${statFlaggedUncached} flagged uncacheable, ${statRestoredFromCache} from cache, ${statRestoredFromMemCache} from mem cache, ${ + statQueueItemsProcessed - + statNotCached - + statFlaggedUncached + } additional calculations due to dependencies)` + ); - /** - * @param {WebpackOptions} options webpack options - * @param {Compilation} compilation the compilation - * @param {ResolverWithOptions} resolver the resolver - * @param {InputFileSystem} fs the file system - * @param {function(WebpackError=): void} callback callback function - * @returns {void} - */ - build(options, compilation, resolver, fs, callback) { - this.buildMeta = {}; - this.buildInfo = { - cacheable: true - }; - callback(); - } + logger.time("store provided exports into cache"); + asyncLib.each( + modulesToStore, + (module, callback) => { + if (typeof module.buildInfo.hash !== "string") { + // not cacheable + return callback(); + } + const cachedData = moduleGraph + .getExportsInfo(module) + .getRestoreProvidedData(); + const memCache = + moduleMemCaches && moduleMemCaches.get(module); + if (memCache) { + memCache.set(this, cachedData); + } + cache.store( + module.identifier(), + module.buildInfo.hash, + cachedData, + callback + ); + }, + err => { + logger.timeEnd("store provided exports into cache"); + callback(err); + } + ); + } + ); + } + ); - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration(context) { - if (this.url === undefined) this.url = this.urlBuffer.toString(); - const sources = new Map(); - sources.set( - "javascript", - new RawSource(`module.exports = ${JSON.stringify(this.url)};`) + /** @type {WeakMap} */ + 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)); + } + ); + } ); - const data = new Map(); - data.set("url", this.urlBuffer); - const runtimeRequirements = new Set(); - runtimeRequirements.add(RuntimeGlobals.module); - return { sources, runtimeRequirements, data }; - } - - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - hash.update(this.urlBuffer); - super.updateHash(hash, context); - } - - serialize(context) { - const { write } = context; - - write(this.urlBuffer); - write(this.identifierStr); - write(this.readableIdentifierStr); - - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - - this.urlBuffer = read(); - this.identifierStr = read(); - this.readableIdentifierStr = read(); - - super.deserialize(context); } } -makeSerializable(RawDataUrlModule, "webpack/lib/asset/RawDataUrlModule"); - -module.exports = RawDataUrlModule; +module.exports = FlagDependencyExportsPlugin; /***/ }), -/***/ 41153: +/***/ 58812: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -59032,1546 +53778,1538 @@ module.exports = RawDataUrlModule; -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +const Dependency = __webpack_require__(54912); +const { UsageState } = __webpack_require__(63686); +const ModuleGraphConnection = __webpack_require__(40639); +const { STAGE_DEFAULT } = __webpack_require__(80057); +const ArrayQueue = __webpack_require__(41792); +const TupleQueue = __webpack_require__(38415); +const { getEntryRuntime, mergeRuntimeOwned } = __webpack_require__(17156); -/** - * @typedef {GenerateContext} Context - */ -class AwaitDependenciesInitFragment extends InitFragment { - /** - * @param {Set} promises the promises that should be awaited - */ - constructor(promises) { - super( - undefined, - InitFragment.STAGE_ASYNC_DEPENDENCIES, - 0, - "await-dependencies" - ); - this.promises = promises; - } +/** @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 */ - merge(other) { - const promises = new Set(this.promises); - for (const p of other.promises) { - promises.add(p); - } - return new AwaitDependenciesInitFragment(promises); - } +const { NO_EXPORTS_REFERENCED, EXPORTS_OBJECT_REFERENCED } = Dependency; +class FlagDependencyUsagePlugin { /** - * @param {Context} context context - * @returns {string|Source} the source code that will be included as initialization code + * @param {boolean} global do a global analysis instead of per runtime */ - getContent({ runtimeRequirements }) { - runtimeRequirements.add(RuntimeGlobals.module); - const promises = this.promises; - if (promises.size === 0) { - return ""; - } - if (promises.size === 1) { - for (const p of promises) { - return Template.asString([ - `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${p}]);`, - `${p} = (__webpack_async_dependencies__.then ? await __webpack_async_dependencies__ : __webpack_async_dependencies__)[0];`, - "" - ]); - } - } - const sepPromises = Array.from(promises).join(", "); - // TODO check if destructuring is supported - return Template.asString([ - `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${sepPromises}]);`, - `([${sepPromises}] = __webpack_async_dependencies__.then ? await __webpack_async_dependencies__ : __webpack_async_dependencies__);`, - "" - ]); + constructor(global) { + this.global = global; } -} - -module.exports = AwaitDependenciesInitFragment; - - -/***/ }), - -/***/ 59498: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const HarmonyImportDependency = __webpack_require__(57154); - -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -class InferAsyncModulesPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap("InferAsyncModulesPlugin", compilation => { - const { moduleGraph } = compilation; - compilation.hooks.finishModules.tap( - "InferAsyncModulesPlugin", + compiler.hooks.compilation.tap("FlagDependencyUsagePlugin", compilation => { + const moduleGraph = compilation.moduleGraph; + compilation.hooks.optimizeDependencies.tap( + { + name: "FlagDependencyUsagePlugin", + stage: STAGE_DEFAULT + }, modules => { - /** @type {Set} */ - const queue = new Set(); - for (const module of modules) { - if (module.buildMeta && module.buildMeta.async) { - queue.add(module); - } - } - for (const module of queue) { - moduleGraph.setAsync(module); - for (const [ - originModule, - connections - ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { - if ( - connections.some( - c => - c.dependency instanceof HarmonyImportDependency && - c.isTargetActive(undefined) - ) - ) { - queue.add(originModule); - } - } + if (compilation.moduleMemCaches) { + throw new Error( + "optimization.usedExports can't be used with cacheUnaffected as export usage is a global effect" + ); } - } - ); - }); - } -} - -module.exports = InferAsyncModulesPlugin; - - -/***/ }), - -/***/ 79233: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + const logger = compilation.getLogger( + "webpack.FlagDependencyUsagePlugin" + ); + /** @type {Map} */ + const exportInfoToModuleMap = new Map(); -const AsyncDependencyToInitialChunkError = __webpack_require__(30111); -const { connectChunkGroupParentAndChild } = __webpack_require__(37234); -const ModuleGraphConnection = __webpack_require__(40639); -const { getEntryRuntime, mergeRuntime } = __webpack_require__(17156); + /** @type {TupleQueue<[Module, RuntimeSpec]>} */ + const queue = new TupleQueue(); -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ + /** + * @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>} */ + const map = new Map(); + + /** @type {ArrayQueue} */ + const queue = new ArrayQueue(); + queue.enqueue(module); + for (;;) { + const block = queue.dequeue(); + if (block === undefined) break; + for (const b of block.blocks) { + if ( + !this.global && + b.groupOptions && + b.groupOptions.entryOptions + ) { + processModule( + b, + b.groupOptions.entryOptions.runtime || undefined, + true + ); + } else { + queue.enqueue(b); + } + } + for (const dep of block.dependencies) { + const connection = moduleGraph.getConnection(dep); + if (!connection || !connection.module) { + continue; + } + const activeState = connection.getActiveState(runtime); + if (activeState === false) continue; + const { module } = connection; + if (activeState === ModuleGraphConnection.TRANSITIVE_ONLY) { + processModule(module, runtime, false); + continue; + } + const oldReferencedExports = map.get(module); + if (oldReferencedExports === EXPORTS_OBJECT_REFERENCED) { + continue; + } + const referencedExports = + compilation.getDependencyReferencedExports(dep, runtime); + if ( + oldReferencedExports === undefined || + oldReferencedExports === NO_EXPORTS_REFERENCED || + referencedExports === EXPORTS_OBJECT_REFERENCED + ) { + map.set(module, referencedExports); + } else if ( + oldReferencedExports !== undefined && + referencedExports === NO_EXPORTS_REFERENCED + ) { + continue; + } else { + let exportsMap; + if (Array.isArray(oldReferencedExports)) { + exportsMap = new Map(); + for (const item of oldReferencedExports) { + if (Array.isArray(item)) { + exportsMap.set(item.join("\n"), item); + } else { + exportsMap.set(item.name.join("\n"), item); + } + } + map.set(module, exportsMap); + } else { + exportsMap = oldReferencedExports; + } + for (const item of referencedExports) { + if (Array.isArray(item)) { + const key = item.join("\n"); + const oldItem = exportsMap.get(key); + if (oldItem === undefined) { + exportsMap.set(key, item); + } + // if oldItem is already an array we have to do nothing + // if oldItem is an ReferencedExport object, we don't have to do anything + // as canMangle defaults to true for arrays + } else { + const key = item.name.join("\n"); + const oldItem = exportsMap.get(key); + if (oldItem === undefined || Array.isArray(oldItem)) { + exportsMap.set(key, item); + } else { + exportsMap.set(key, { + name: item.name, + canMangle: item.canMangle && oldItem.canMangle + }); + } + } + } + } + } + } + + for (const [module, referencedExports] of map) { + if (Array.isArray(referencedExports)) { + processReferencedModule( + module, + referencedExports, + runtime, + forceSideEffects + ); + } else { + processReferencedModule( + module, + Array.from(referencedExports.values()), + runtime, + forceSideEffects + ); + } + } + }; + + logger.time("initialize exports usage"); + for (const module of modules) { + const exportsInfo = moduleGraph.getExportsInfo(module); + exportInfoToModuleMap.set(exportsInfo, module); + exportsInfo.setHasUseInfo(); + } + logger.timeEnd("initialize exports usage"); + + logger.time("trace exports usage in graph"); + + /** + * @param {Dependency} dep dependency + * @param {RuntimeSpec} runtime runtime + */ + const processEntryDependency = (dep, runtime) => { + const module = moduleGraph.getModule(dep); + if (module) { + processReferencedModule( + module, + NO_EXPORTS_REFERENCED, + runtime, + true + ); + } + }; + /** @type {RuntimeSpec} */ + let globalRuntime = 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; + + +/***/ }), + +/***/ 93401: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ /** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Entrypoint")} Entrypoint */ -/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ +/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ /** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("./logging/Logger").Logger} Logger */ +/** @typedef {import("./NormalModule")} NormalModule */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./util/Hash")} Hash */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** - * @typedef {Object} QueueItem - * @property {number} action - * @property {DependenciesBlock} block - * @property {Module} module - * @property {Chunk} chunk - * @property {ChunkGroup} chunkGroup - * @property {ChunkGroupInfo} chunkGroupInfo + * @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} runtimeRequirements the requirements for runtime + * @property {RuntimeSpec} runtime the runtime + * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules + * @property {CodeGenerationResults=} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that) + * @property {string} type which kind of code should be generated + * @property {function(): Map=} getData get access to the code generation data */ -/** @typedef {Set & { plus: Set }} ModuleSetPlus */ - /** - * @typedef {Object} ChunkGroupInfo - * @property {ChunkGroup} chunkGroup the chunk group - * @property {RuntimeSpec} runtime the runtimes - * @property {ModuleSetPlus} minAvailableModules current minimal set of modules available at this point - * @property {boolean} minAvailableModulesOwned true, if minAvailableModules is owned and can be modified - * @property {ModuleSetPlus[]} availableModulesToBeMerged enqueued updates to the minimal set of available modules - * @property {Set=} skippedItems modules that were skipped because module is already available in parent chunks (need to reconsider when minAvailableModules is shrinking) - * @property {Set<[Module, ConnectionState]>=} skippedModuleConnections referenced modules that where skipped because they were not active in this runtime - * @property {ModuleSetPlus} resultingAvailableModules set of modules available including modules from this chunk group - * @property {Set} children set of children chunk groups, that will be revisited when availableModules shrink - * @property {Set} availableSources set of chunk groups that are the source for minAvailableModules - * @property {Set} availableChildren set of chunk groups which depend on the this chunk group as availableSource - * @property {number} preOrderIndex next pre order index - * @property {number} postOrderIndex next post order index - * @property {boolean} chunkLoading has a chunk loading mechanism - * @property {boolean} asyncChunks create async chunks + * @typedef {Object} UpdateHashContext + * @property {NormalModule} module the module + * @property {ChunkGraph} chunkGraph + * @property {RuntimeSpec} runtime */ /** - * @typedef {Object} BlockChunkGroupConnection - * @property {ChunkGroupInfo} originChunkGroupInfo origin chunk group - * @property {ChunkGroup} chunkGroup referenced chunk group + * */ +class Generator { + static byType(map) { + return new ByTypeGenerator(map); + } -const EMPTY_SET = /** @type {ModuleSetPlus} */ (new Set()); -EMPTY_SET.plus = EMPTY_SET; + /* istanbul ignore next */ + /** + * @abstract + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) + */ + getTypes(module) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); + } -/** - * @param {ModuleSetPlus} a first set - * @param {ModuleSetPlus} b second set - * @returns {number} cmp - */ -const bySetSize = (a, b) => { - return b.size + b.plus.size - a.size - a.plus.size; -}; + /* 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 = __webpack_require__(77198); + throw new AbstractMethodError(); + } -const extractBlockModules = (module, moduleGraph, runtime, blockModulesMap) => { - let blockCache; - let modules; + /* 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 = __webpack_require__(77198); + throw new AbstractMethodError(); + } - const arrays = []; + /** + * @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}`; + } - const queue = [module]; - while (queue.length > 0) { - const block = queue.pop(); - const arr = []; - arrays.push(arr); - blockModulesMap.set(block, arr); - for (const b of block.blocks) { - queue.push(b); - } + /** + * @param {Hash} hash hash that will be modified + * @param {UpdateHashContext} updateHashContext context for updating hash + */ + updateHash(hash, { module, runtime }) { + // no nothing } +} - for (const connection of moduleGraph.getOutgoingConnections(module)) { - const d = connection.dependency; - // We skip connections without dependency - if (!d) continue; - const m = connection.module; - // We skip connections without Module pointer - if (!m) continue; - // We skip weak connections - if (connection.weak) continue; - const state = connection.getActiveState(runtime); - // We skip inactive connections - if (state === false) continue; +class ByTypeGenerator extends Generator { + constructor(map) { + super(); + this.map = map; + this._types = new Set(Object.keys(map)); + } - const block = moduleGraph.getParentBlock(d); - let index = moduleGraph.getParentBlockIndex(d); + /** + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) + */ + getTypes(module) { + return this._types; + } - // deprecated fallback - if (index < 0) { - index = block.dependencies.indexOf(d); - } + /** + * @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; + } - if (blockCache !== block) { - modules = blockModulesMap.get((blockCache = block)); + /** + * @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}`); } - - const i = index << 2; - modules[i] = m; - modules[i + 1] = state; + return generator.generate(module, generateContext); } +} - for (const modules of arrays) { - if (modules.length === 0) continue; - let indexMap; - let length = 0; - outer: for (let j = 0; j < modules.length; j += 2) { - const m = modules[j]; - if (m === undefined) continue; - const state = modules[j + 1]; - if (indexMap === undefined) { - let i = 0; - for (; i < length; i += 2) { - if (modules[i] === m) { - const merged = modules[i + 1]; - if (merged === true) continue outer; - modules[i + 1] = ModuleGraphConnection.addConnectionStates( - merged, - state - ); - } - } - modules[length] = m; - length++; - modules[length] = state; - length++; - if (length > 30) { - // To avoid worse case performance, we will use an index map for - // linear cost access, which allows to maintain O(n) complexity - // while keeping allocations down to a minimum - indexMap = new Map(); - for (let i = 0; i < length; i += 2) { - indexMap.set(modules[i], i + 1); - } - } - } else { - const idx = indexMap.get(m); - if (idx !== undefined) { - const merged = modules[idx]; - if (merged === true) continue outer; - modules[idx] = ModuleGraphConnection.addConnectionStates( - merged, - state - ); - } else { - modules[length] = m; - length++; - modules[length] = state; - indexMap.set(m, length); - length++; - } - } - } - modules.length = length; +module.exports = Generator; + + +/***/ }), + +/***/ 37234: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @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 {Logger} logger a logger - * @param {Compilation} compilation the compilation - * @param {Map} inputEntrypointsAndModules chunk groups which are processed with the modules - * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules - * @param {Map} blockConnections connection for blocks - * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks - * @param {Set} allCreatedChunkGroups filled with all chunk groups that are created here + * @param {ChunkGroup} parent parent ChunkGroup to connect + * @param {ChunkGroup} child child ChunkGroup to connect + * @returns {void} */ -const visitModules = ( - logger, - compilation, - inputEntrypointsAndModules, - chunkGroupInfoMap, - blockConnections, - blocksWithNestedBlocks, - allCreatedChunkGroups -) => { - const { moduleGraph, chunkGraph, moduleMemCaches } = compilation; +const connectChunkGroupParentAndChild = (parent, child) => { + if (parent.addChild(child)) { + child.addParent(parent); + } +}; - const blockModulesRuntimeMap = new Map(); +exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk; +exports.connectChunkGroupParentAndChild = connectChunkGroupParentAndChild; - /** @type {RuntimeSpec | false} */ - let blockModulesMapRuntime = false; - let blockModulesMap; - /** - * - * @param {DependenciesBlock} block block - * @param {RuntimeSpec} runtime runtime - * @returns {(Module | ConnectionState)[]} block modules in flatten tuples - */ - const getBlockModules = (block, runtime) => { - if (blockModulesMapRuntime !== runtime) { - blockModulesMap = blockModulesRuntimeMap.get(runtime); - if (blockModulesMap === undefined) { - blockModulesMap = new Map(); - blockModulesRuntimeMap.set(runtime, blockModulesMap); - } - } - let blockModules = blockModulesMap.get(block); - if (blockModules !== undefined) return blockModules; - const module = /** @type {Module} */ (block.getRootBlock()); - const memCache = moduleMemCaches && moduleMemCaches.get(module); - if (memCache !== undefined) { - const map = memCache.provide( - "bundleChunkGraph.blockModules", - runtime, - () => { - logger.time("visitModules: prepare"); - const map = new Map(); - extractBlockModules(module, moduleGraph, runtime, map); - logger.timeAggregate("visitModules: prepare"); - return map; - } - ); - for (const [block, blockModules] of map) - blockModulesMap.set(block, blockModules); - return map.get(block); - } else { - logger.time("visitModules: prepare"); - extractBlockModules(module, moduleGraph, runtime, blockModulesMap); - blockModules = blockModulesMap.get(block); - logger.timeAggregate("visitModules: prepare"); - return blockModules; - } - }; +/***/ }), - let statProcessedQueueItems = 0; - let statProcessedBlocks = 0; - let statConnectedChunkGroups = 0; - let statProcessedChunkGroupsForMerging = 0; - let statMergedAvailableModuleSets = 0; - let statForkedAvailableModules = 0; - let statForkedAvailableModulesCount = 0; - let statForkedAvailableModulesCountPlus = 0; - let statForkedMergedModulesCount = 0; - let statForkedMergedModulesCountPlus = 0; - let statForkedResultModulesCount = 0; - let statChunkGroupInfoUpdated = 0; - let statChildChunkGroupsReconnected = 0; +/***/ 97511: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - let nextChunkGroupIndex = 0; - let nextFreeModulePreOrderIndex = 0; - let nextFreeModulePostOrderIndex = 0; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - /** @type {Map} */ - const blockChunkGroups = new Map(); - /** @type {Map} */ - const namedChunkGroups = new Map(); - /** @type {Map} */ - const namedAsyncEntrypoints = new Map(); +const WebpackError = __webpack_require__(53799); - const ADD_AND_ENTER_ENTRY_MODULE = 0; - const ADD_AND_ENTER_MODULE = 1; - const ENTER_MODULE = 2; - const PROCESS_BLOCK = 3; - const PROCESS_ENTRY_BLOCK = 4; - const LEAVE_MODULE = 5; +module.exports = class HarmonyLinkingError extends WebpackError { + /** @param {string} message Error message */ + constructor(message) { + super(message); + this.name = "HarmonyLinkingError"; + this.hideStack = true; + } +}; - /** @type {QueueItem[]} */ - let queue = []; - /** @type {Map>} */ - const queueConnect = new Map(); - /** @type {Set} */ - const chunkGroupsForCombining = new Set(); +/***/ }), - // Fill queue with entrypoint modules - // Create ChunkGroupInfo for entrypoints - for (const [chunkGroup, modules] of inputEntrypointsAndModules) { - const runtime = getEntryRuntime( - compilation, - chunkGroup.name, - chunkGroup.options - ); - /** @type {ChunkGroupInfo} */ - const chunkGroupInfo = { - chunkGroup, - runtime, - minAvailableModules: undefined, - minAvailableModulesOwned: false, - availableModulesToBeMerged: [], - skippedItems: undefined, - resultingAvailableModules: undefined, - children: undefined, - availableSources: undefined, - availableChildren: undefined, - preOrderIndex: 0, - postOrderIndex: 0, - chunkLoading: - chunkGroup.options.chunkLoading !== undefined - ? chunkGroup.options.chunkLoading !== false - : compilation.outputOptions.chunkLoading !== false, - asyncChunks: - chunkGroup.options.asyncChunks !== undefined - ? chunkGroup.options.asyncChunks - : compilation.outputOptions.asyncChunks !== false - }; - chunkGroup.index = nextChunkGroupIndex++; - if (chunkGroup.getNumberOfParents() > 0) { - // minAvailableModules for child entrypoints are unknown yet, set to undefined. - // This means no module is added until other sets are merged into - // this minAvailableModules (by the parent entrypoints) - const skippedItems = new Set(); - for (const module of modules) { - skippedItems.add(module); - } - chunkGroupInfo.skippedItems = skippedItems; - chunkGroupsForCombining.add(chunkGroupInfo); - } else { - // The application may start here: We start with an empty list of available modules - chunkGroupInfo.minAvailableModules = EMPTY_SET; - const chunk = chunkGroup.getEntrypointChunk(); - for (const module of modules) { - queue.push({ - action: ADD_AND_ENTER_MODULE, - block: module, - module, - chunk, - chunkGroup, - chunkGroupInfo - }); - } - } - chunkGroupInfoMap.set(chunkGroup, chunkGroupInfo); - if (chunkGroup.name) { - namedChunkGroups.set(chunkGroup.name, chunkGroupInfo); - } - } - // Fill availableSources with parent-child dependencies between entrypoints - for (const chunkGroupInfo of chunkGroupsForCombining) { - const { chunkGroup } = chunkGroupInfo; - chunkGroupInfo.availableSources = new Set(); - for (const parent of chunkGroup.parentsIterable) { - const parentChunkGroupInfo = chunkGroupInfoMap.get(parent); - chunkGroupInfo.availableSources.add(parentChunkGroupInfo); - if (parentChunkGroupInfo.availableChildren === undefined) { - parentChunkGroupInfo.availableChildren = new Set(); - } - parentChunkGroupInfo.availableChildren.add(chunkGroupInfo); - } - } - // pop() is used to read from the queue - // so it need to be reversed to be iterated in - // correct order - queue.reverse(); +/***/ 11351: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {Set} */ - const outdatedChunkGroupInfo = new Set(); - /** @type {Set} */ - const chunkGroupsForMerging = new Set(); - /** @type {QueueItem[]} */ - let queueDelayed = []; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ - /** @type {[Module, ConnectionState][]} */ - const skipConnectionBuffer = []; - /** @type {Module[]} */ - const skipBuffer = []; - /** @type {QueueItem[]} */ - const queueBuffer = []; - /** @type {Module} */ - let module; - /** @type {Chunk} */ - let chunk; - /** @type {ChunkGroup} */ - let chunkGroup; - /** @type {DependenciesBlock} */ - let block; - /** @type {ChunkGroupInfo} */ - let chunkGroupInfo; - // For each async Block in graph +const WebpackError = __webpack_require__(53799); + +/** @typedef {import("./Module")} Module */ + +/** + * @template T + * @callback Callback + * @param {Error=} err + * @param {T=} stats + * @returns {void} + */ + +class HookWebpackError extends WebpackError { /** - * @param {AsyncDependenciesBlock} b iterating over each Async DepBlock - * @returns {void} + * Creates an instance of HookWebpackError. + * @param {Error} error inner error + * @param {string} hook name of hook */ - const iteratorBlock = b => { - // 1. We create a chunk group with single chunk in it for this Block - // but only once (blockChunkGroups map) - let cgi = blockChunkGroups.get(b); - /** @type {ChunkGroup} */ - let c; - /** @type {Entrypoint} */ - let entrypoint; - const entryOptions = b.groupOptions && b.groupOptions.entryOptions; - if (cgi === undefined) { - const chunkName = (b.groupOptions && b.groupOptions.name) || b.chunkName; - if (entryOptions) { - cgi = namedAsyncEntrypoints.get(chunkName); - if (!cgi) { - entrypoint = compilation.addAsyncEntrypoint( - entryOptions, - module, - b.loc, - b.request - ); - entrypoint.index = nextChunkGroupIndex++; - cgi = { - chunkGroup: entrypoint, - runtime: entrypoint.options.runtime || entrypoint.name, - minAvailableModules: EMPTY_SET, - minAvailableModulesOwned: false, - availableModulesToBeMerged: [], - skippedItems: undefined, - resultingAvailableModules: undefined, - children: undefined, - availableSources: undefined, - availableChildren: undefined, - preOrderIndex: 0, - postOrderIndex: 0, - chunkLoading: - entryOptions.chunkLoading !== undefined - ? entryOptions.chunkLoading !== false - : chunkGroupInfo.chunkLoading, - asyncChunks: - entryOptions.asyncChunks !== undefined - ? entryOptions.asyncChunks - : chunkGroupInfo.asyncChunks - }; - chunkGroupInfoMap.set(entrypoint, cgi); + constructor(error, hook) { + super(error.message); - chunkGraph.connectBlockAndChunkGroup(b, entrypoint); - if (chunkName) { - namedAsyncEntrypoints.set(chunkName, cgi); - } - } else { - entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup); - // TODO merge entryOptions - entrypoint.addOrigin(module, b.loc, b.request); - chunkGraph.connectBlockAndChunkGroup(b, entrypoint); - } + this.name = "HookWebpackError"; + this.hook = hook; + this.error = error; + this.hideStack = true; + this.details = `caused by plugins in ${hook}\n${error.stack}`; - // 2. We enqueue the DependenciesBlock for traversal - queueDelayed.push({ - action: PROCESS_ENTRY_BLOCK, - block: b, - module: module, - chunk: entrypoint.chunks[0], - chunkGroup: entrypoint, - chunkGroupInfo: cgi - }); - } else if (!chunkGroupInfo.asyncChunks || !chunkGroupInfo.chunkLoading) { - // Just queue the block into the current chunk group - queue.push({ - action: PROCESS_BLOCK, - block: b, - module: module, - chunk, - chunkGroup, - chunkGroupInfo - }); - } else { - cgi = chunkName && namedChunkGroups.get(chunkName); - if (!cgi) { - c = compilation.addChunkInGroup( - b.groupOptions || b.chunkName, - module, - b.loc, - b.request - ); - c.index = nextChunkGroupIndex++; - cgi = { - chunkGroup: c, - runtime: chunkGroupInfo.runtime, - minAvailableModules: undefined, - minAvailableModulesOwned: undefined, - availableModulesToBeMerged: [], - skippedItems: undefined, - resultingAvailableModules: undefined, - children: undefined, - availableSources: undefined, - availableChildren: undefined, - preOrderIndex: 0, - postOrderIndex: 0, - chunkLoading: chunkGroupInfo.chunkLoading, - asyncChunks: chunkGroupInfo.asyncChunks - }; - allCreatedChunkGroups.add(c); - chunkGroupInfoMap.set(c, cgi); - if (chunkName) { - namedChunkGroups.set(chunkName, cgi); - } - } else { - c = cgi.chunkGroup; - if (c.isInitial()) { - compilation.errors.push( - new AsyncDependencyToInitialChunkError(chunkName, module, b.loc) - ); - c = chunkGroup; - } - c.addOptions(b.groupOptions); - c.addOrigin(module, b.loc, b.request); - } - blockConnections.set(b, []); - } - blockChunkGroups.set(b, cgi); - } else if (entryOptions) { - entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup); - } else { - c = cgi.chunkGroup; - } + this.stack += `\n-- inner error --\n${error.stack}`; + } +} - if (c !== undefined) { - // 2. We store the connection for the block - // to connect it later if needed - blockConnections.get(b).push({ - originChunkGroupInfo: chunkGroupInfo, - chunkGroup: c - }); +module.exports = HookWebpackError; - // 3. We enqueue the chunk group info creation/updating - let connectList = queueConnect.get(chunkGroupInfo); - if (connectList === undefined) { - connectList = new Set(); - queueConnect.set(chunkGroupInfo, connectList); - } - connectList.add(cgi); +/** + * @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; - // TODO check if this really need to be done for each traversal - // or if it is enough when it's queued when created - // 4. We enqueue the DependenciesBlock for traversal - queueDelayed.push({ - action: PROCESS_BLOCK, - block: b, - module: module, - chunk: c.chunks[0], - chunkGroup: c, - chunkGroupInfo: cgi - }); - } else if (entrypoint !== undefined) { - chunkGroupInfo.chunkGroup.addAsyncEntrypoint(entrypoint); +/** + * @template T + * @param {function((WebpackError | null)=, T=): void} callback webpack error callback + * @param {string} hook name of hook + * @returns {Callback} 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); }; +}; - /** - * @param {DependenciesBlock} block the block - * @returns {void} - */ - const processBlock = block => { - statProcessedBlocks++; - // get prepared block info - const blockModules = getBlockModules(block, chunkGroupInfo.runtime); +module.exports.makeWebpackErrorCallback = makeWebpackErrorCallback; - if (blockModules !== undefined) { - const { minAvailableModules } = chunkGroupInfo; - // Buffer items because order need to be reversed to get indices correct - // Traverse all referenced modules - for (let i = 0; i < blockModules.length; i += 2) { - const refModule = /** @type {Module} */ (blockModules[i]); - if (chunkGraph.isModuleInChunk(refModule, chunk)) { - // skip early if already connected - continue; - } - const activeState = /** @type {ConnectionState} */ ( - blockModules[i + 1] - ); - if (activeState !== true) { - skipConnectionBuffer.push([refModule, activeState]); - if (activeState === false) continue; - } - if ( - activeState === true && - (minAvailableModules.has(refModule) || - minAvailableModules.plus.has(refModule)) - ) { - // already in parent chunks, skip it for now - skipBuffer.push(refModule); - continue; - } - // enqueue, then add and enter to be in the correct order - // this is relevant with circular dependencies - queueBuffer.push({ - action: activeState === true ? ADD_AND_ENTER_MODULE : PROCESS_BLOCK, - block: refModule, - module: refModule, - chunk, - chunkGroup, - chunkGroupInfo - }); - } - // Add buffered items in reverse order - if (skipConnectionBuffer.length > 0) { - let { skippedModuleConnections } = chunkGroupInfo; - if (skippedModuleConnections === undefined) { - chunkGroupInfo.skippedModuleConnections = skippedModuleConnections = - new Set(); - } - for (let i = skipConnectionBuffer.length - 1; i >= 0; i--) { - skippedModuleConnections.add(skipConnectionBuffer[i]); - } - skipConnectionBuffer.length = 0; - } - if (skipBuffer.length > 0) { - let { skippedItems } = chunkGroupInfo; - if (skippedItems === undefined) { - chunkGroupInfo.skippedItems = skippedItems = new Set(); - } - for (let i = skipBuffer.length - 1; i >= 0; i--) { - skippedItems.add(skipBuffer[i]); - } - skipBuffer.length = 0; - } - if (queueBuffer.length > 0) { - for (let i = queueBuffer.length - 1; i >= 0; i--) { - queue.push(queueBuffer[i]); - } - queueBuffer.length = 0; - } +/** + * @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; +}; - // Traverse all Blocks - for (const b of block.blocks) { - iteratorBlock(b); - } +module.exports.tryRunOrWebpackError = tryRunOrWebpackError; - if (block.blocks.length > 0 && module !== block) { - blocksWithNestedBlocks.add(block); - } - }; - /** - * @param {DependenciesBlock} block the block - * @returns {void} - */ - const processEntryBlock = block => { - statProcessedBlocks++; - // get prepared block info - const blockModules = getBlockModules(block, chunkGroupInfo.runtime); +/***/ }), - if (blockModules !== undefined) { - // Traverse all referenced modules - for (let i = 0; i < blockModules.length; i += 2) { - const refModule = /** @type {Module} */ (blockModules[i]); - const activeState = /** @type {ConnectionState} */ ( - blockModules[i + 1] - ); - // enqueue, then add and enter to be in the correct order - // this is relevant with circular dependencies - queueBuffer.push({ - action: - activeState === true ? ADD_AND_ENTER_ENTRY_MODULE : PROCESS_BLOCK, - block: refModule, - module: refModule, - chunk, - chunkGroup, - chunkGroupInfo - }); - } - // Add buffered items in reverse order - if (queueBuffer.length > 0) { - for (let i = queueBuffer.length - 1; i >= 0; i--) { - queue.push(queueBuffer[i]); - } - queueBuffer.length = 0; - } - } +/***/ 6404: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Traverse all Blocks - for (const b of block.blocks) { - iteratorBlock(b); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (block.blocks.length > 0 && module !== block) { - blocksWithNestedBlocks.add(block); - } - }; - const processQueue = () => { - while (queue.length) { - statProcessedQueueItems++; - const queueItem = queue.pop(); - module = queueItem.module; - block = queueItem.block; - chunk = queueItem.chunk; - chunkGroup = queueItem.chunkGroup; - chunkGroupInfo = queueItem.chunkGroupInfo; - switch (queueItem.action) { - case ADD_AND_ENTER_ENTRY_MODULE: - chunkGraph.connectChunkAndEntryModule( - chunk, - module, - /** @type {Entrypoint} */ (chunkGroup) - ); - // fallthrough - case ADD_AND_ENTER_MODULE: { - if (chunkGraph.isModuleInChunk(module, chunk)) { - // already connected, skip it - break; - } - // We connect Module and Chunk - chunkGraph.connectChunkAndModule(chunk, module); - } - // fallthrough - case ENTER_MODULE: { - const index = chunkGroup.getModulePreOrderIndex(module); - if (index === undefined) { - chunkGroup.setModulePreOrderIndex( - module, - chunkGroupInfo.preOrderIndex++ - ); - } +const { SyncBailHook } = __webpack_require__(41242); +const { RawSource } = __webpack_require__(51255); +const ChunkGraph = __webpack_require__(64971); +const Compilation = __webpack_require__(85720); +const HotUpdateChunk = __webpack_require__(9597); +const NormalModule = __webpack_require__(39); +const RuntimeGlobals = __webpack_require__(16475); +const WebpackError = __webpack_require__(53799); +const ConstDependency = __webpack_require__(76911); +const ImportMetaHotAcceptDependency = __webpack_require__(51274); +const ImportMetaHotDeclineDependency = __webpack_require__(53141); +const ModuleHotAcceptDependency = __webpack_require__(47511); +const ModuleHotDeclineDependency = __webpack_require__(86301); +const HotModuleReplacementRuntimeModule = __webpack_require__(27899); +const JavascriptParser = __webpack_require__(29050); +const { + evaluateToIdentifier +} = __webpack_require__(93998); +const { find, isSubset } = __webpack_require__(93347); +const TupleSet = __webpack_require__(76455); +const { compareModulesById } = __webpack_require__(29579); +const { + getRuntimeKey, + keyToRuntime, + forEachRuntime, + mergeRuntimeOwned, + subtractRuntime, + intersectRuntime +} = __webpack_require__(17156); - if ( - moduleGraph.setPreOrderIndexIfUnset( - module, - nextFreeModulePreOrderIndex - ) - ) { - nextFreeModulePreOrderIndex++; - } +/** @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 */ - // reuse queueItem - queueItem.action = LEAVE_MODULE; - queue.push(queueItem); - } - // fallthrough - case PROCESS_BLOCK: { - processBlock(block); - break; - } - case PROCESS_ENTRY_BLOCK: { - processEntryBlock(block); - break; - } - case LEAVE_MODULE: { - const index = chunkGroup.getModulePostOrderIndex(module); - if (index === undefined) { - chunkGroup.setModulePostOrderIndex( - module, - chunkGroupInfo.postOrderIndex++ - ); - } +/** + * @typedef {Object} HMRJavascriptParserHooks + * @property {SyncBailHook<[TODO, string[]], void>} hotAcceptCallback + * @property {SyncBailHook<[TODO, string[]], void>} hotAcceptWithoutCallback + */ - if ( - moduleGraph.setPostOrderIndexIfUnset( - module, - nextFreeModulePostOrderIndex - ) - ) { - nextFreeModulePostOrderIndex++; - } - break; - } - } +/** @type {WeakMap} */ +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; + } - const calculateResultingAvailableModules = chunkGroupInfo => { - if (chunkGroupInfo.resultingAvailableModules) - return chunkGroupInfo.resultingAvailableModules; + constructor(options) { + this.options = options || {}; + } - const minAvailableModules = chunkGroupInfo.minAvailableModules; + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { _backCompat: backCompat } = compiler; + if (compiler.options.output.strictModuleErrorHandling === undefined) + compiler.options.output.strictModuleErrorHandling = true; + const runtimeRequirements = [RuntimeGlobals.module]; - // Create a new Set of available modules at this point - // We want to be as lazy as possible. There are multiple ways doing this: - // Note that resultingAvailableModules is stored as "(a) + (b)" as it's a ModuleSetPlus - // - resultingAvailableModules = (modules of chunk) + (minAvailableModules + minAvailableModules.plus) - // - resultingAvailableModules = (minAvailableModules + modules of chunk) + (minAvailableModules.plus) - // We choose one depending on the size of minAvailableModules vs minAvailableModules.plus + const createAcceptHandler = (parser, ParamDependency) => { + const { hotAcceptCallback, hotAcceptWithoutCallback } = + HotModuleReplacementPlugin.getParserHooks(parser); - let resultingAvailableModules; - if (minAvailableModules.size > minAvailableModules.plus.size) { - // resultingAvailableModules = (modules of chunk) + (minAvailableModules + minAvailableModules.plus) - resultingAvailableModules = - /** @type {Set & {plus: Set}} */ (new Set()); - for (const module of minAvailableModules.plus) - minAvailableModules.add(module); - minAvailableModules.plus = EMPTY_SET; - resultingAvailableModules.plus = minAvailableModules; - chunkGroupInfo.minAvailableModulesOwned = false; - } else { - // resultingAvailableModules = (minAvailableModules + modules of chunk) + (minAvailableModules.plus) - resultingAvailableModules = - /** @type {Set & {plus: Set}} */ ( - new Set(minAvailableModules) + return expr => { + const module = parser.state.module; + const dep = new ConstDependency( + `${module.moduleArgument}.hot.accept`, + expr.callee.range, + runtimeRequirements ); - resultingAvailableModules.plus = minAvailableModules.plus; - } - - // add the modules from the chunk group to the set - for (const chunk of chunkGroupInfo.chunkGroup.chunks) { - for (const m of chunkGraph.getChunkModulesIterable(chunk)) { - resultingAvailableModules.add(m); - } - } - return (chunkGroupInfo.resultingAvailableModules = - resultingAvailableModules); - }; + 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 processConnectQueue = () => { - // Figure out new parents for chunk groups - // to get new available modules for these children - for (const [chunkGroupInfo, targets] of queueConnect) { - // 1. Add new targets to the list of children - if (chunkGroupInfo.children === undefined) { - chunkGroupInfo.children = targets; - } else { - for (const target of targets) { - chunkGroupInfo.children.add(target); + 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; + }; - // 2. Calculate resulting available modules - const resultingAvailableModules = - calculateResultingAvailableModules(chunkGroupInfo); - - const runtime = chunkGroupInfo.runtime; + 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; + }; - // 3. Update chunk group info - for (const target of targets) { - target.availableModulesToBeMerged.push(resultingAvailableModules); - chunkGroupsForMerging.add(target); - const oldRuntime = target.runtime; - const newRuntime = mergeRuntime(oldRuntime, runtime); - if (oldRuntime !== newRuntime) { - target.runtime = newRuntime; - outdatedChunkGroupInfo.add(target); + 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)); + }; - statConnectedChunkGroups += targets.size; - } - queueConnect.clear(); - }; + 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)); + }; - const processChunkGroupsForMerging = () => { - statProcessedChunkGroupsForMerging += chunkGroupsForMerging.size; + 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; - // Execute the merge - for (const info of chunkGroupsForMerging) { - const availableModulesToBeMerged = info.availableModulesToBeMerged; - let cachedMinAvailableModules = info.minAvailableModules; + //#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 - statMergedAvailableModuleSets += availableModulesToBeMerged.length; + //#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 - // 1. Get minimal available modules - // It doesn't make sense to traverse a chunk again with more available modules. - // This step calculates the minimal available modules and skips traversal when - // the list didn't shrink. - if (availableModulesToBeMerged.length > 1) { - availableModulesToBeMerged.sort(bySetSize); - } - let changed = false; - merge: for (const availableModules of availableModulesToBeMerged) { - if (cachedMinAvailableModules === undefined) { - cachedMinAvailableModules = availableModules; - info.minAvailableModules = cachedMinAvailableModules; - info.minAvailableModulesOwned = false; - changed = true; - } else { - if (info.minAvailableModulesOwned) { - // We own it and can modify it - if (cachedMinAvailableModules.plus === availableModules.plus) { - for (const m of cachedMinAvailableModules) { - if (!availableModules.has(m)) { - cachedMinAvailableModules.delete(m); - changed = true; - } + 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.chunkHashes = {}; + records.chunkRuntime = {}; + for (const chunk of compilation.chunks) { + records.chunkHashes[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); } - } else { - for (const m of cachedMinAvailableModules) { - if (!availableModules.has(m) && !availableModules.plus.has(m)) { - cachedMinAvailableModules.delete(m); - changed = true; - } + }; + const fullHashModulesInThisChunk = + chunkGraph.getChunkFullHashModulesSet(chunk); + if (fullHashModulesInThisChunk !== undefined) { + for (const module of fullHashModulesInThisChunk) { + fullHashModules.add(module, chunk); } - for (const m of cachedMinAvailableModules.plus) { - if (!availableModules.has(m) && !availableModules.plus.has(m)) { - // We can't remove modules from the plus part - // so we need to merge plus into the normal part to allow modifying it - const iterator = - cachedMinAvailableModules.plus[Symbol.iterator](); - // fast forward add all modules until m - /** @type {IteratorResult} */ - let it; - while (!(it = iterator.next()).done) { - const module = it.value; - if (module === m) break; - cachedMinAvailableModules.add(module); - } - // check the remaining modules before adding - while (!(it = iterator.next()).done) { - const module = it.value; + } + 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 ( - availableModules.has(module) || - availableModules.plus.has(m) + fullHashModulesInThisChunk.has( + /** @type {RuntimeModule} */ (module) + ) ) { - cachedMinAvailableModules.add(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; } } - cachedMinAvailableModules.plus = EMPTY_SET; - changed = true; - continue merge; - } - } - } - } else if (cachedMinAvailableModules.plus === availableModules.plus) { - // Common and fast case when the plus part is shared - // We only need to care about the normal part - if (availableModules.size < cachedMinAvailableModules.size) { - // the new availableModules is smaller so it's faster to - // fork from the new availableModules - statForkedAvailableModules++; - statForkedAvailableModulesCount += availableModules.size; - statForkedMergedModulesCount += cachedMinAvailableModules.size; - // construct a new Set as intersection of cachedMinAvailableModules and availableModules - const newSet = /** @type {ModuleSetPlus} */ (new Set()); - newSet.plus = availableModules.plus; - for (const m of availableModules) { - if (cachedMinAvailableModules.has(m)) { - newSet.add(m); - } - } - statForkedResultModulesCount += newSet.size; - cachedMinAvailableModules = newSet; - info.minAvailableModulesOwned = true; - info.minAvailableModules = newSet; - changed = true; - continue merge; - } - for (const m of cachedMinAvailableModules) { - if (!availableModules.has(m)) { - // cachedMinAvailableModules need to be modified - // but we don't own it - statForkedAvailableModules++; - statForkedAvailableModulesCount += - cachedMinAvailableModules.size; - statForkedMergedModulesCount += availableModules.size; - // construct a new Set as intersection of cachedMinAvailableModules and availableModules - // as the plus part is equal we can just take over this one - const newSet = /** @type {ModuleSetPlus} */ (new Set()); - newSet.plus = availableModules.plus; - const iterator = cachedMinAvailableModules[Symbol.iterator](); - // fast forward add all modules until m - /** @type {IteratorResult} */ - let it; - while (!(it = iterator.next()).done) { - const module = it.value; - if (module === m) break; - newSet.add(module); - } - // check the remaining modules before adding - while (!(it = iterator.next()).done) { - const module = it.value; - if (availableModules.has(module)) { - newSet.add(module); - } - } - statForkedResultModulesCount += newSet.size; - cachedMinAvailableModules = newSet; - info.minAvailableModulesOwned = true; - info.minAvailableModules = newSet; - changed = true; - continue merge; - } - } - } else { - for (const m of cachedMinAvailableModules) { - if (!availableModules.has(m) && !availableModules.plus.has(m)) { - // cachedMinAvailableModules need to be modified - // but we don't own it - statForkedAvailableModules++; - statForkedAvailableModulesCount += - cachedMinAvailableModules.size; - statForkedAvailableModulesCountPlus += - cachedMinAvailableModules.plus.size; - statForkedMergedModulesCount += availableModules.size; - statForkedMergedModulesCountPlus += availableModules.plus.size; - // construct a new Set as intersection of cachedMinAvailableModules and availableModules - const newSet = /** @type {ModuleSetPlus} */ (new Set()); - newSet.plus = EMPTY_SET; - const iterator = cachedMinAvailableModules[Symbol.iterator](); - // fast forward add all modules until m - /** @type {IteratorResult} */ - let it; - while (!(it = iterator.next()).done) { - const module = it.value; - if (module === m) break; - newSet.add(module); - } - // check the remaining modules before adding - while (!(it = iterator.next()).done) { - const module = it.value; - if ( - availableModules.has(module) || - availableModules.plus.has(module) - ) { - newSet.add(module); + } 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; } } - // also check all modules in cachedMinAvailableModules.plus - for (const module of cachedMinAvailableModules.plus) { - if ( - availableModules.has(module) || - availableModules.plus.has(module) - ) { - newSet.add(module); + } 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; + } } - } - statForkedResultModulesCount += newSet.size; - cachedMinAvailableModules = newSet; - info.minAvailableModulesOwned = true; - info.minAvailableModules = newSet; - changed = true; - continue merge; - } - } - for (const m of cachedMinAvailableModules.plus) { - if (!availableModules.has(m) && !availableModules.plus.has(m)) { - // cachedMinAvailableModules need to be modified - // but we don't own it - statForkedAvailableModules++; - statForkedAvailableModulesCount += - cachedMinAvailableModules.size; - statForkedAvailableModulesCountPlus += - cachedMinAvailableModules.plus.size; - statForkedMergedModulesCount += availableModules.size; - statForkedMergedModulesCountPlus += availableModules.plus.size; - // construct a new Set as intersection of cachedMinAvailableModules and availableModules - // we already know that all modules directly from cachedMinAvailableModules are in availableModules too - const newSet = /** @type {ModuleSetPlus} */ ( - new Set(cachedMinAvailableModules) - ); - newSet.plus = EMPTY_SET; - const iterator = - cachedMinAvailableModules.plus[Symbol.iterator](); - // fast forward add all modules until m - /** @type {IteratorResult} */ - let it; - while (!(it = iterator.next()).done) { - const module = it.value; - if (module === m) break; - newSet.add(module); - } - // check the remaining modules before adding - while (!(it = iterator.next()).done) { - const module = it.value; - if ( - availableModules.has(module) || - availableModules.plus.has(module) - ) { - newSet.add(module); + } else { + for (const module of modules) { + const key = `${chunk.id}|${module.identifier()}`; + const hash = getModuleHash(module); + chunkModuleHashes[key] = hash; } } - statForkedResultModulesCount += newSet.size; - cachedMinAvailableModules = newSet; - info.minAvailableModulesOwned = true; - info.minAvailableModules = newSet; - changed = true; - continue merge; } } } - } - } - availableModulesToBeMerged.length = 0; - if (changed) { - info.resultingAvailableModules = undefined; - outdatedChunkGroupInfo.add(info); - } - } - chunkGroupsForMerging.clear(); - }; - const processChunkGroupsForCombining = () => { - for (const info of chunkGroupsForCombining) { - for (const source of info.availableSources) { - if (!source.minAvailableModules) { - chunkGroupsForCombining.delete(info); - break; - } - } - } - for (const info of chunkGroupsForCombining) { - const availableModules = /** @type {ModuleSetPlus} */ (new Set()); - availableModules.plus = EMPTY_SET; - const mergeSet = set => { - if (set.size > availableModules.plus.size) { - for (const item of availableModules.plus) availableModules.add(item); - availableModules.plus = set; - } else { - for (const item of set) availableModules.add(item); - } - }; - // combine minAvailableModules from all resultingAvailableModules - for (const source of info.availableSources) { - const resultingAvailableModules = - calculateResultingAvailableModules(source); - mergeSet(resultingAvailableModules); - mergeSet(resultingAvailableModules.plus); - } - info.minAvailableModules = availableModules; - info.minAvailableModulesOwned = false; - info.resultingAvailableModules = undefined; - outdatedChunkGroupInfo.add(info); - } - chunkGroupsForCombining.clear(); - }; + hotIndex = records.hotIndex || 0; + if (updatedModules.size > 0) hotIndex++; - const processOutdatedChunkGroupInfo = () => { - statChunkGroupInfoUpdated += outdatedChunkGroupInfo.size; - // Revisit skipped elements - for (const info of outdatedChunkGroupInfo) { - // 1. Reconsider skipped items - if (info.skippedItems !== undefined) { - const { minAvailableModules } = info; - for (const module of info.skippedItems) { - if ( - !minAvailableModules.has(module) && - !minAvailableModules.plus.has(module) - ) { - queue.push({ - action: ADD_AND_ENTER_MODULE, - block: module, - module, - chunk: info.chunkGroup.chunks[0], - chunkGroup: info.chunkGroup, - chunkGroupInfo: info + 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.chunkHashes || + !records.chunkModuleIds + ) { + return; + } + for (const [module, chunk] of fullHashModules) { + const key = `${chunk.id}|${module.identifier()}`; + const hash = nonCodeGeneratedModules.has(module, chunk.runtime) + ? chunkGraph.getModuleHash(module, chunk.runtime) + : compilation.codeGenerationResults.getHash( + module, + chunk.runtime + ); + if (records.chunkModuleHashes[key] !== hash) { + updatedModules.add(module, chunk); + } + chunkModuleHashes[key] = hash; + } + + /** @type {Map, removedChunkIds: Set, removedModules: Set, 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 + }); }); - info.skippedItems.delete(module); - } - } - } + if (hotUpdateMainContentByRuntime.size === 0) return; - // 2. Reconsider skipped connections - if (info.skippedModuleConnections !== undefined) { - const { minAvailableModules } = info; - for (const entry of info.skippedModuleConnections) { - const [module, activeState] = entry; - if (activeState === false) continue; - if (activeState === true) { - info.skippedModuleConnections.delete(entry); - } - if ( - activeState === true && - (minAvailableModules.has(module) || - minAvailableModules.plus.has(module)) - ) { - info.skippedItems.add(module); - continue; - } - queue.push({ - action: activeState === true ? ADD_AND_ENTER_MODULE : PROCESS_BLOCK, - block: module, - module, - chunk: info.chunkGroup.chunks[0], - chunkGroup: info.chunkGroup, - chunkGroupInfo: info - }); - } - } + // Create a list of all active modules to verify which modules are removed completely + /** @type {Map} */ + const allModules = new Map(); + for (const module of compilation.modules) { + const id = chunkGraph.getModuleId(module); + allModules.set(id, module); + } - // 2. Reconsider children chunk groups - if (info.children !== undefined) { - statChildChunkGroupsReconnected += info.children.size; - for (const cgi of info.children) { - let connectList = queueConnect.get(info); - if (connectList === undefined) { - connectList = new Set(); - queueConnect.set(info, connectList); - } - connectList.add(cgi); - } - } - - // 3. Reconsider chunk groups for combining - if (info.availableChildren !== undefined) { - for (const cgi of info.availableChildren) { - chunkGroupsForCombining.add(cgi); - } - } - } - outdatedChunkGroupInfo.clear(); - }; + // List of completely removed modules + /** @type {Set} */ + const completelyRemovedModules = new Set(); - // Iterative traversal of the Module graph - // Recursive would be simpler to write but could result in Stack Overflows - while (queue.length || queueConnect.size) { - logger.time("visitModules: visiting"); - processQueue(); - logger.timeAggregateEnd("visitModules: prepare"); - logger.timeEnd("visitModules: visiting"); + for (const key of Object.keys(records.chunkHashes)) { + const oldRuntime = keyToRuntime(records.chunkRuntime[key]); + /** @type {Module[]} */ + const remainingModules = []; + // Check which modules are removed + for (const id of records.chunkModuleIds[key]) { + const module = allModules.get(id); + if (module === undefined) { + completelyRemovedModules.add(id); + } else { + remainingModules.push(module); + } + } - if (chunkGroupsForCombining.size > 0) { - logger.time("visitModules: combine available modules"); - processChunkGroupsForCombining(); - logger.timeEnd("visitModules: combine available modules"); - } + let chunkId; + let newModules; + let newRuntimeModules; + let newFullHashModules; + let newDependentHashModules; + let newRuntime; + let removedFromRuntime; + const currentChunk = find( + compilation.chunks, + chunk => `${chunk.id}` === key + ); + if (currentChunk) { + chunkId = currentChunk.id; + newRuntime = intersectRuntime( + currentChunk.runtime, + allOldRuntime + ); + if (newRuntime === undefined) continue; + newModules = chunkGraph + .getChunkModules(currentChunk) + .filter(module => updatedModules.has(module, currentChunk)); + newRuntimeModules = Array.from( + chunkGraph.getChunkRuntimeModulesIterable(currentChunk) + ).filter(module => updatedModules.has(module, currentChunk)); + const fullHashModules = + chunkGraph.getChunkFullHashModulesIterable(currentChunk); + newFullHashModules = + fullHashModules && + Array.from(fullHashModules).filter(module => + updatedModules.has(module, currentChunk) + ); + const dependentHashModules = + chunkGraph.getChunkDependentHashModulesIterable(currentChunk); + newDependentHashModules = + dependentHashModules && + Array.from(dependentHashModules).filter(module => + updatedModules.has(module, currentChunk) + ); + removedFromRuntime = subtractRuntime(oldRuntime, newRuntime); + } else { + // chunk has completely removed + chunkId = `${+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(); + if (backCompat) + ChunkGraph.setChunkGraphForChunk(hotUpdateChunk, chunkGraph); + hotUpdateChunk.id = chunkId; + hotUpdateChunk.runtime = newRuntime; + if (currentChunk) { + for (const group of currentChunk.groupsIterable) + hotUpdateChunk.addGroup(group); + } + chunkGraph.attachModules(hotUpdateChunk, newModules || []); + chunkGraph.attachRuntimeModules( + hotUpdateChunk, + newRuntimeModules || [] + ); + if (newFullHashModules) { + chunkGraph.attachFullHashModules( + hotUpdateChunk, + newFullHashModules + ); + } + if (newDependentHashModules) { + chunkGraph.attachDependentHashModules( + hotUpdateChunk, + newDependentHashModules + ); + } + const renderManifest = compilation.getRenderManifest({ + chunk: hotUpdateChunk, + hash: records.hash, + fullHash: records.hash, + outputOptions: compilation.outputOptions, + moduleTemplates: compilation.moduleTemplates, + dependencyTemplates: compilation.dependencyTemplates, + codeGenerationResults: compilation.codeGenerationResults, + runtimeTemplate: compilation.runtimeTemplate, + moduleGraph: compilation.moduleGraph, + chunkGraph + }); + for (const entry of renderManifest) { + /** @type {string} */ + let filename; + /** @type {AssetInfo} */ + let assetInfo; + if ("filename" in entry) { + filename = entry.filename; + assetInfo = entry.info; + } else { + ({ path: filename, info: assetInfo } = + compilation.getPathWithInfo( + entry.filenameTemplate, + entry.pathOptions + )); + } + const source = entry.render(); + compilation.additionalChunkAssets.push(filename); + compilation.emitAsset(filename, source, { + hotModuleReplacement: true, + ...assetInfo + }); + if (currentChunk) { + currentChunk.files.add(filename); + compilation.hooks.chunkAsset.call(currentChunk, filename); + } + } + forEachRuntime(newRuntime, runtime => { + 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) + ) + ) + }; - if (queueConnect.size > 0) { - logger.time("visitModules: calculating available modules"); - processConnectQueue(); - logger.timeEnd("visitModules: calculating available modules"); + const source = new RawSource(JSON.stringify(hotUpdateMainJson)); + compilation.emitAsset(filename, source, { + hotModuleReplacement: true, + ...assetInfo + }); + } + } + ); - if (chunkGroupsForMerging.size > 0) { - logger.time("visitModules: merging available modules"); - processChunkGroupsForMerging(); - logger.timeEnd("visitModules: merging available modules"); - } - } + 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() + ); + } + ); - if (outdatedChunkGroupInfo.size > 0) { - logger.time("visitModules: check modules for revisit"); - processOutdatedChunkGroupInfo(); - logger.timeEnd("visitModules: check modules for revisit"); - } + 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); + }); - // Run queueDelayed when all items of the queue are processed - // This is important to get the global indexing correct - // Async blocks should be processed after all sync blocks are processed - if (queue.length === 0) { - const tempQueue = queue; - queue = queueDelayed.reverse(); - queueDelayed = tempQueue; - } + NormalModule.getCompilationHooks(compilation).loader.tap( + "HotModuleReplacementPlugin", + context => { + context.hot = true; + } + ); + } + ); } +} - logger.log( - `${statProcessedQueueItems} queue items processed (${statProcessedBlocks} blocks)` - ); - logger.log(`${statConnectedChunkGroups} chunk groups connected`); - logger.log( - `${statProcessedChunkGroupsForMerging} chunk groups processed for merging (${statMergedAvailableModuleSets} module sets, ${statForkedAvailableModules} forked, ${statForkedAvailableModulesCount} + ${statForkedAvailableModulesCountPlus} modules forked, ${statForkedMergedModulesCount} + ${statForkedMergedModulesCountPlus} modules merged into fork, ${statForkedResultModulesCount} resulting modules)` - ); - logger.log( - `${statChunkGroupInfoUpdated} chunk group info updated (${statChildChunkGroupsReconnected} already connected chunk groups reconnected)` - ); -}; +module.exports = HotModuleReplacementPlugin; -/** - * - * @param {Compilation} compilation the compilation - * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks - * @param {Map} blockConnections connection for blocks - * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules - */ -const connectChunkGroups = ( - compilation, - blocksWithNestedBlocks, - blockConnections, - chunkGroupInfoMap -) => { - const { chunkGraph } = compilation; - /** - * Helper function to check if all modules of a chunk are available - * - * @param {ChunkGroup} chunkGroup the chunkGroup to scan - * @param {ModuleSetPlus} availableModules the comparator set - * @returns {boolean} return true if all modules of a chunk are available - */ - const areModulesAvailable = (chunkGroup, availableModules) => { - for (const chunk of chunkGroup.chunks) { - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - if (!availableModules.has(module) && !availableModules.plus.has(module)) - return false; - } - } - return true; - }; +/***/ }), - // For each edge in the basic chunk graph - for (const [block, connections] of blockConnections) { - // 1. Check if connection is needed - // When none of the dependencies need to be connected - // we can skip all of them - // It's not possible to filter each item so it doesn't create inconsistent - // connections and modules can only create one version - // TODO maybe decide this per runtime - if ( - // TODO is this needed? - !blocksWithNestedBlocks.has(block) && - connections.every(({ chunkGroup, originChunkGroupInfo }) => - areModulesAvailable( - chunkGroup, - originChunkGroupInfo.resultingAvailableModules - ) - ) - ) { - continue; - } +/***/ 9597: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // 2. Foreach edge - for (let i = 0; i < connections.length; i++) { - const { chunkGroup, originChunkGroupInfo } = connections[i]; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // 3. Connect block with chunk - chunkGraph.connectBlockAndChunkGroup(block, chunkGroup); - // 4. Connect chunk with parent - connectChunkGroupParentAndChild( - originChunkGroupInfo.chunkGroup, - chunkGroup - ); - } - } -}; -/** - * Remove all unconnected chunk groups - * @param {Compilation} compilation the compilation - * @param {Iterable} allCreatedChunkGroups all chunk groups that where created before - */ -const cleanupUnconnectedGroups = (compilation, allCreatedChunkGroups) => { - const { chunkGraph } = compilation; +const Chunk = __webpack_require__(39385); - for (const chunkGroup of allCreatedChunkGroups) { - if (chunkGroup.getNumberOfParents() === 0) { - for (const chunk of chunkGroup.chunks) { - compilation.chunks.delete(chunk); - chunkGraph.disconnectChunk(chunk); - } - chunkGraph.disconnectChunkGroup(chunkGroup); - chunkGroup.remove(); - } +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./util/Hash")} Hash */ + +class HotUpdateChunk extends Chunk { + constructor() { + super(); } -}; +} -/** - * This method creates the Chunk graph from the Module graph - * @param {Compilation} compilation the compilation - * @param {Map} inputEntrypointsAndModules chunk groups which are processed with the modules - * @returns {void} - */ -const buildChunkGraph = (compilation, inputEntrypointsAndModules) => { - const logger = compilation.getLogger("webpack.buildChunkGraph"); +module.exports = HotUpdateChunk; - // SHARED STATE - /** @type {Map} */ - const blockConnections = new Map(); +/***/ }), - /** @type {Set} */ - const allCreatedChunkGroups = new Set(); +/***/ 3: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {Map} */ - const chunkGroupInfoMap = new Map(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - /** @type {Set} */ - const blocksWithNestedBlocks = new Set(); - // PART ONE - logger.time("visitModules"); - visitModules( - logger, - compilation, - inputEntrypointsAndModules, - chunkGroupInfoMap, - blockConnections, - blocksWithNestedBlocks, - allCreatedChunkGroups - ); - logger.timeEnd("visitModules"); +const ModuleFactory = __webpack_require__(51010); - // PART TWO +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ - logger.time("connectChunkGroups"); - connectChunkGroups( - compilation, - blocksWithNestedBlocks, - blockConnections, - chunkGroupInfoMap - ); - logger.timeEnd("connectChunkGroups"); +/** + * Ignores error when module is unresolved + */ +class IgnoreErrorModuleFactory extends ModuleFactory { + /** + * @param {NormalModuleFactory} normalModuleFactory normalModuleFactory instance + */ + constructor(normalModuleFactory) { + super(); - for (const [chunkGroup, chunkGroupInfo] of chunkGroupInfoMap) { - for (const chunk of chunkGroup.chunks) - chunk.runtime = mergeRuntime(chunk.runtime, chunkGroupInfo.runtime); + this.normalModuleFactory = normalModuleFactory; } - // Cleanup work - - logger.time("cleanup"); - cleanupUnconnectedGroups(compilation, allCreatedChunkGroups); - logger.timeEnd("cleanup"); -}; + /** + * @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 = buildChunkGraph; +module.exports = IgnoreErrorModuleFactory; /***/ }), -/***/ 28034: -/***/ (function(module) { +/***/ 84808: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -60581,14 +55319,64 @@ module.exports = buildChunkGraph; -/** @typedef {import("../Compiler")} Compiler */ +const createSchemaValidation = __webpack_require__(32540); -class AddBuildDependenciesPlugin { +/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./NormalModuleFactory").ResolveData} ResolveData */ + +const validate = createSchemaValidation( + __webpack_require__(20858), + () => __webpack_require__(3098), + { + name: "Ignore Plugin", + baseDataPath: "options" + } +); + +class IgnorePlugin { /** - * @param {Iterable} buildDependencies list of build dependencies + * @param {IgnorePluginOptions} options IgnorePlugin options */ - constructor(buildDependencies) { - this.buildDependencies = new Set(buildDependencies); + constructor(options) { + validate(options); + this.options = options; + + /** @private @type {Function} */ + this.checkIgnore = this.checkIgnore.bind(this); + } + + /** + * Note that if "contextRegExp" is given, both the "resourceRegExp" + * and "contextRegExp" have to match. + * + * @param {ResolveData} resolveData resolve data + * @returns {false|undefined} returns false when the request should be ignored, otherwise undefined + */ + checkIgnore(resolveData) { + if ( + "checkResource" in this.options && + this.options.checkResource && + this.options.checkResource(resolveData.request, resolveData.context) + ) { + return false; + } + + if ( + "resourceRegExp" in this.options && + this.options.resourceRegExp && + this.options.resourceRegExp.test(resolveData.request) + ) { + if ("contextRegExp" in this.options && this.options.contextRegExp) { + // if "contextRegExp" is given, + // both the "resourceRegExp" and "contextRegExp" have to match. + if (this.options.contextRegExp.test(resolveData.context)) { + return false; + } + } else { + return false; + } + } } /** @@ -60597,21 +55385,21 @@ class AddBuildDependenciesPlugin { * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap( - "AddBuildDependenciesPlugin", - compilation => { - compilation.buildDependencies.addAll(this.buildDependencies); - } - ); + 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 = AddBuildDependenciesPlugin; +module.exports = IgnorePlugin; /***/ }), -/***/ 47942: +/***/ 41606: /***/ (function(module) { "use strict"; @@ -60622,274 +55410,212 @@ module.exports = AddBuildDependenciesPlugin; -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../declarations/WebpackOptions").IgnoreWarningsNormalized} IgnoreWarningsNormalized */ +/** @typedef {import("./Compiler")} Compiler */ -class AddManagedPathsPlugin { +class IgnoreWarningsPlugin { /** - * @param {Iterable} managedPaths list of managed paths - * @param {Iterable} immutablePaths list of immutable paths + * @param {IgnoreWarningsNormalized} ignoreWarnings conditions to ignore warnings */ - constructor(managedPaths, immutablePaths) { - this.managedPaths = new Set(managedPaths); - this.immutablePaths = new Set(immutablePaths); + constructor(ignoreWarnings) { + this._ignoreWarnings = ignoreWarnings; } - /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - for (const managedPath of this.managedPaths) { - compiler.managedPaths.add(managedPath); - } - for (const immutablePath of this.immutablePaths) { - compiler.immutablePaths.add(immutablePath); - } + 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 = AddManagedPathsPlugin; +module.exports = IgnoreWarningsPlugin; /***/ }), -/***/ 71985: +/***/ 55870: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Florent Cailhol @ooflorent */ -const Cache = __webpack_require__(7592); -const ProgressPlugin = __webpack_require__(13216); +const { ConcatSource } = __webpack_require__(51255); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Generator").GenerateContext} GenerateContext */ -const BUILD_DEPENDENCIES_KEY = Symbol(); +/** + * @param {InitFragment} fragment the init fragment + * @param {number} index index + * @returns {[InitFragment, number]} tuple with both + */ +const extractFragmentIndex = (fragment, index) => [fragment, index]; -class IdleFileCachePlugin { +/** + * @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; +}; + +/** + * @template Context + */ +class InitFragment { /** - * @param {TODO} strategy cache strategy - * @param {number} idleTimeout timeout - * @param {number} idleTimeoutForInitialStore initial timeout - * @param {number} idleTimeoutAfterLargeChanges timeout after changes + * @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( - strategy, - idleTimeout, - idleTimeoutForInitialStore, - idleTimeoutAfterLargeChanges - ) { - this.strategy = strategy; - this.idleTimeout = idleTimeout; - this.idleTimeoutForInitialStore = idleTimeoutForInitialStore; - this.idleTimeoutAfterLargeChanges = idleTimeoutAfterLargeChanges; + constructor(content, stage, position, key, endContent) { + this.content = content; + this.stage = stage; + this.position = position; + this.key = key; + this.endContent = endContent; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {Context} context context + * @returns {string|Source} the source code that will be included as initialization code */ - apply(compiler) { - let strategy = this.strategy; - const idleTimeout = this.idleTimeout; - const idleTimeoutForInitialStore = Math.min( - idleTimeout, - this.idleTimeoutForInitialStore - ); - const idleTimeoutAfterLargeChanges = this.idleTimeoutAfterLargeChanges; - const resolvedPromise = Promise.resolve(); - - let timeSpendInBuild = 0; - let timeSpendInStore = 0; - let avgTimeSpendInStore = 0; + getContent(context) { + return this.content; + } - /** @type {Map Promise>} */ - const pendingIdleTasks = new Map(); + /** + * @param {Context} context context + * @returns {string|Source=} the source code that will be included at the end of the module + */ + getEndContent(context) { + return this.endContent; + } - compiler.cache.hooks.store.tap( - { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, - (identifier, etag, data) => { - pendingIdleTasks.set(identifier, () => - strategy.store(identifier, etag, data) - ); - } - ); + static addToSource(source, initFragments, context) { + 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); - compiler.cache.hooks.get.tapPromise( - { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, - (identifier, etag, gotHandlers) => { - const restore = () => - strategy.restore(identifier, etag).then(cacheEntry => { - if (cacheEntry === undefined) { - gotHandlers.push((result, callback) => { - if (result !== undefined) { - pendingIdleTasks.set(identifier, () => - strategy.store(identifier, etag, result) - ); - } - callback(); - }); - } else { - return cacheEntry; - } - }); - const pendingTask = pendingIdleTasks.get(identifier); - if (pendingTask !== undefined) { - pendingIdleTasks.delete(identifier); - return pendingTask().then(restore); + // Deduplicate fragments. If a fragment has no key, it is always included. + const keyedFragments = new Map(); + for (const [fragment] of sortedFragments) { + if (typeof fragment.mergeAll === "function") { + if (!fragment.key) { + throw new Error( + `InitFragment with mergeAll function must have a valid key: ${fragment.constructor.name}` + ); + } + const oldValue = keyedFragments.get(fragment.key); + if (oldValue === undefined) { + keyedFragments.set(fragment.key, fragment); + } else if (Array.isArray(oldValue)) { + oldValue.push(fragment); + } else { + keyedFragments.set(fragment.key, [oldValue, fragment]); + } + continue; + } else if (typeof fragment.merge === "function") { + const oldValue = keyedFragments.get(fragment.key); + if (oldValue !== undefined) { + keyedFragments.set(fragment.key, fragment.merge(oldValue)); + continue; + } } - return restore(); - } - ); - - compiler.cache.hooks.storeBuildDependencies.tap( - { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, - dependencies => { - pendingIdleTasks.set(BUILD_DEPENDENCIES_KEY, () => - strategy.storeBuildDependencies(dependencies) - ); + keyedFragments.set(fragment.key || Symbol(), fragment); } - ); - compiler.cache.hooks.shutdown.tapPromise( - { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, - () => { - if (idleTimer) { - clearTimeout(idleTimer); - idleTimer = undefined; + const concatSource = new ConcatSource(); + const endContents = []; + for (let fragment of keyedFragments.values()) { + if (Array.isArray(fragment)) { + fragment = fragment[0].mergeAll(fragment); } - isIdle = false; - const reportProgress = ProgressPlugin.getReporter(compiler); - const jobs = Array.from(pendingIdleTasks.values()); - if (reportProgress) reportProgress(0, "process pending cache items"); - const promises = jobs.map(fn => fn()); - pendingIdleTasks.clear(); - promises.push(currentIdlePromise); - const promise = Promise.all(promises); - currentIdlePromise = promise.then(() => strategy.afterAllStored()); - if (reportProgress) { - currentIdlePromise = currentIdlePromise.then(() => { - reportProgress(1, `stored`); - }); + concatSource.add(fragment.getContent(context)); + const endContent = fragment.getEndContent(context); + if (endContent) { + endContents.push(endContent); } - return currentIdlePromise.then(() => { - // Reset strategy - if (strategy.clear) strategy.clear(); - }); } - ); - /** @type {Promise} */ - let currentIdlePromise = resolvedPromise; - let isIdle = false; - let isInitialStore = true; - const processIdleTasks = () => { - if (isIdle) { - const startTime = Date.now(); - if (pendingIdleTasks.size > 0) { - const promises = [currentIdlePromise]; - const maxTime = startTime + 100; - let maxCount = 100; - for (const [filename, factory] of pendingIdleTasks) { - pendingIdleTasks.delete(filename); - promises.push(factory()); - if (maxCount-- <= 0 || Date.now() > maxTime) break; - } - currentIdlePromise = Promise.all(promises); - currentIdlePromise.then(() => { - timeSpendInStore += Date.now() - startTime; - // Allow to exit the process between - idleTimer = setTimeout(processIdleTasks, 0); - idleTimer.unref(); - }); - return; - } - currentIdlePromise = currentIdlePromise - .then(async () => { - await strategy.afterAllStored(); - timeSpendInStore += Date.now() - startTime; - avgTimeSpendInStore = - Math.max(avgTimeSpendInStore, timeSpendInStore) * 0.9 + - timeSpendInStore * 0.1; - timeSpendInStore = 0; - timeSpendInBuild = 0; - }) - .catch(err => { - const logger = compiler.getInfrastructureLogger( - "IdleFileCachePlugin" - ); - logger.warn(`Background tasks during idle failed: ${err.message}`); - logger.debug(err.stack); - }); - isInitialStore = false; - } - }; - let idleTimer = undefined; - compiler.cache.hooks.beginIdle.tap( - { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, - () => { - const isLargeChange = timeSpendInBuild > avgTimeSpendInStore * 2; - if (isInitialStore && idleTimeoutForInitialStore < idleTimeout) { - compiler - .getInfrastructureLogger("IdleFileCachePlugin") - .log( - `Initial cache was generated and cache will be persisted in ${ - idleTimeoutForInitialStore / 1000 - }s.` - ); - } else if ( - isLargeChange && - idleTimeoutAfterLargeChanges < idleTimeout - ) { - compiler - .getInfrastructureLogger("IdleFileCachePlugin") - .log( - `Spend ${Math.round(timeSpendInBuild) / 1000}s in build and ${ - Math.round(avgTimeSpendInStore) / 1000 - }s in average in cache store. This is considered as large change and cache will be persisted in ${ - idleTimeoutAfterLargeChanges / 1000 - }s.` - ); - } - idleTimer = setTimeout(() => { - idleTimer = undefined; - isIdle = true; - resolvedPromise.then(processIdleTasks); - }, Math.min(isInitialStore ? idleTimeoutForInitialStore : Infinity, isLargeChange ? idleTimeoutAfterLargeChanges : Infinity, idleTimeout)); - idleTimer.unref(); - } - ); - compiler.cache.hooks.endIdle.tap( - { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, - () => { - if (idleTimer) { - clearTimeout(idleTimer); - idleTimer = undefined; - } - isIdle = false; + concatSource.add(source); + for (const content of endContents.reverse()) { + concatSource.add(content); } - ); - compiler.hooks.done.tap("IdleFileCachePlugin", stats => { - // 10% build overhead is ignored, as it's not cacheable - timeSpendInBuild *= 0.9; - timeSpendInBuild += stats.endTime - stats.startTime; - }); + return concatSource; + } else { + return source; + } + } + + serialize(context) { + const { write } = context; + + write(this.content); + write(this.stage); + write(this.position); + write(this.key); + write(this.endContent); + } + + deserialize(context) { + const { read } = context; + + this.content = read(); + this.stage = read(); + this.position = read(); + this.key = read(); + this.endContent = read(); } } -module.exports = IdleFileCachePlugin; +makeSerializable(InitFragment, "webpack/lib/InitFragment"); + +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; /***/ }), -/***/ 52539: +/***/ 68257: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -60900,198 +55626,124 @@ module.exports = IdleFileCachePlugin; -const Cache = __webpack_require__(7592); +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Cache").Etag} Etag */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ -class MemoryCachePlugin { +class InvalidDependenciesModuleWarning extends WebpackError { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {Module} module module tied to dependency + * @param {Iterable} deps invalid dependencies */ - apply(compiler) { - /** @type {Map} */ - const cache = new Map(); - compiler.cache.hooks.store.tap( - { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, - (identifier, etag, data) => { - cache.set(identifier, { etag, data }); - } - ); - compiler.cache.hooks.get.tap( - { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, - (identifier, etag, gotHandlers) => { - const cacheEntry = cache.get(identifier); - if (cacheEntry === null) { - return null; - } else if (cacheEntry !== undefined) { - return cacheEntry.etag === etag ? cacheEntry.data : null; - } - gotHandlers.push((result, callback) => { - if (result === undefined) { - cache.set(identifier, null); - } else { - cache.set(identifier, { etag, data: result }); - } - return callback(); - }); - } - ); - compiler.cache.hooks.shutdown.tap( - { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, - () => { - cache.clear(); - } - ); + 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; } } -module.exports = MemoryCachePlugin; + +makeSerializable( + InvalidDependenciesModuleWarning, + "webpack/lib/InvalidDependenciesModuleWarning" +); + +module.exports = InvalidDependenciesModuleWarning; /***/ }), -/***/ 99334: +/***/ 52329: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sergey Melyukov @smelukov */ -const Cache = __webpack_require__(7592); +const InnerGraph = __webpack_require__(38988); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Cache").Etag} Etag */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ -class MemoryWithGcCachePlugin { - constructor({ maxGenerations }) { - this._maxGenerations = maxGenerations; - } +class JavascriptMetaInfoPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - const maxGenerations = this._maxGenerations; - /** @type {Map} */ - const cache = new Map(); - /** @type {Map} */ - const oldCache = new Map(); - let generation = 0; - let cachePosition = 0; - const logger = compiler.getInfrastructureLogger("MemoryWithGcCachePlugin"); - compiler.hooks.afterDone.tap("MemoryWithGcCachePlugin", () => { - generation++; - let clearedEntries = 0; - let lastClearedIdentifier; - for (const [identifier, entry] of oldCache) { - if (entry.until > generation) break; - - oldCache.delete(identifier); - if (cache.get(identifier) === undefined) { - cache.delete(identifier); - clearedEntries++; - lastClearedIdentifier = identifier; - } - } - if (clearedEntries > 0 || oldCache.size > 0) { - logger.log( - `${cache.size - oldCache.size} active entries, ${ - oldCache.size - } recently unused cached entries${ - clearedEntries > 0 - ? `, ${clearedEntries} old unused cache entries removed e. g. ${lastClearedIdentifier}` - : "" - }` - ); - } - let i = (cache.size / maxGenerations) | 0; - let j = cachePosition >= cache.size ? 0 : cachePosition; - cachePosition = j + i; - for (const [identifier, entry] of cache) { - if (j !== 0) { - j--; - continue; - } - if (entry !== undefined) { - // We don't delete the cache entry, but set it to undefined instead - // This reserves the location in the data table and avoids rehashing - // when constantly adding and removing entries. - // It will be deleted when removed from oldCache. - cache.set(identifier, undefined); - oldCache.delete(identifier); - oldCache.set(identifier, { - entry, - until: generation + maxGenerations + 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; + const currentSymbol = InnerGraph.getTopLevelSymbol(parser.state); + if (currentSymbol) { + InnerGraph.addUsage(parser.state, null, currentSymbol); + } else { + InnerGraph.bailout(parser.state); + } }); - if (i-- === 0) break; - } - } - }); - compiler.cache.hooks.store.tap( - { name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY }, - (identifier, etag, data) => { - cache.set(identifier, { etag, data }); - } - ); - compiler.cache.hooks.get.tap( - { name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY }, - (identifier, etag, gotHandlers) => { - const cacheEntry = cache.get(identifier); - if (cacheEntry === null) { - return null; - } else if (cacheEntry !== undefined) { - return cacheEntry.etag === etag ? cacheEntry.data : null; - } - const oldCacheEntry = oldCache.get(identifier); - if (oldCacheEntry !== undefined) { - const cacheEntry = oldCacheEntry.entry; - if (cacheEntry === null) { - oldCache.delete(identifier); - cache.set(identifier, cacheEntry); - return null; - } else { - if (cacheEntry.etag !== etag) return null; - oldCache.delete(identifier); - cache.set(identifier, cacheEntry); - return cacheEntry.data; - } - } - gotHandlers.push((result, callback) => { - if (result === undefined) { - cache.set(identifier, null); - } else { - cache.set(identifier, { etag, data: result }); - } - return callback(); - }); - } - ); - compiler.cache.hooks.shutdown.tap( - { name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY }, - () => { - cache.clear(); - oldCache.clear(); + 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 = MemoryWithGcCachePlugin; + +module.exports = JavascriptMetaInfoPlugin; /***/ }), -/***/ 86180: +/***/ 93837: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -61102,2909 +55754,1924 @@ module.exports = MemoryWithGcCachePlugin; -const FileSystemInfo = __webpack_require__(79453); -const ProgressPlugin = __webpack_require__(13216); -const { formatSize } = __webpack_require__(71070); -const SerializerMiddleware = __webpack_require__(83137); -const LazySet = __webpack_require__(38938); -const makeSerializable = __webpack_require__(33032); -const memoize = __webpack_require__(78676); -const { - createFileSerializer, - NOT_SERIALIZABLE -} = __webpack_require__(8282); +const asyncLib = __webpack_require__(78175); +const EntryDependency = __webpack_require__(3979); +const { someInIterable } = __webpack_require__(39104); +const { compareModulesById } = __webpack_require__(29579); +const { dirname, mkdirp } = __webpack_require__(17139); -/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */ -/** @typedef {import("../Cache").Etag} Etag */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */ -/** @typedef {import("../logging/Logger").Logger} Logger */ -/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ +/** @typedef {import("./Compiler")} Compiler */ -class PackContainer { - /** - * @param {Object} data stored data - * @param {string} version version identifier - * @param {Snapshot} buildSnapshot snapshot of all build dependencies - * @param {Set} buildDependencies list of all unresolved build dependencies captured - * @param {Map} resolveResults result of the resolved build dependencies - * @param {Snapshot} resolveBuildDependenciesSnapshot snapshot of the dependencies of the build dependencies resolving - */ - constructor( - data, - version, - buildSnapshot, - buildDependencies, - resolveResults, - resolveBuildDependenciesSnapshot - ) { - this.data = data; - this.version = version; - this.buildSnapshot = buildSnapshot; - this.buildDependencies = buildDependencies; - this.resolveResults = resolveResults; - this.resolveBuildDependenciesSnapshot = resolveBuildDependenciesSnapshot; - } +/** + * @typedef {Object} ManifestModuleData + * @property {string | number} id + * @property {Object} buildMeta + * @property {boolean | string[]} exports + */ - serialize({ write, writeLazy }) { - write(this.version); - write(this.buildSnapshot); - write(this.buildDependencies); - write(this.resolveResults); - write(this.resolveBuildDependenciesSnapshot); - writeLazy(this.data); +class LibManifestPlugin { + constructor(options) { + this.options = options; } - deserialize({ read }) { - this.version = read(); - this.buildSnapshot = read(); - this.buildDependencies = read(); - this.resolveResults = read(); - this.resolveBuildDependenciesSnapshot = read(); - this.data = read(); + /** + * 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; -makeSerializable( - PackContainer, - "webpack/lib/cache/PackFileCacheStrategy", - "PackContainer" -); -const MIN_CONTENT_SIZE = 1024 * 1024; // 1 MB -const CONTENT_COUNT_TO_MERGE = 10; -const MIN_ITEMS_IN_FRESH_PACK = 100; -const MAX_ITEMS_IN_FRESH_PACK = 50000; -const MAX_TIME_IN_FRESH_PACK = 1 * 60 * 1000; // 1 min +/***/ }), -class PackItemInfo { - /** - * @param {string} identifier identifier of item - * @param {string | null} etag etag of item - * @param {any} value fresh value of item - */ - constructor(identifier, etag, value) { - this.identifier = identifier; - this.etag = etag; - this.location = -1; - this.lastAccess = Date.now(); - this.freshValue = value; - } -} +/***/ 14157: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -class Pack { - constructor(logger, maxAge) { - /** @type {Map} */ - this.itemInfo = new Map(); - /** @type {string[]} */ - this.requests = []; - this.requestsTimeout = undefined; - /** @type {Map} */ - this.freshContent = new Map(); - /** @type {(undefined | PackContent)[]} */ - this.content = []; - this.invalid = false; - this.logger = logger; - this.maxAge = maxAge; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - _addRequest(identifier) { - this.requests.push(identifier); - if (this.requestsTimeout === undefined) { - this.requestsTimeout = setTimeout(() => { - this.requests.push(undefined); - this.requestsTimeout = undefined; - }, MAX_TIME_IN_FRESH_PACK); - if (this.requestsTimeout.unref) this.requestsTimeout.unref(); - } - } - stopCapturingRequests() { - if (this.requestsTimeout !== undefined) { - clearTimeout(this.requestsTimeout); - this.requestsTimeout = undefined; - } - } +const EnableLibraryPlugin = __webpack_require__(91452); + +/** @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 {string} identifier unique name for the resource - * @param {string | null} etag etag of the resource - * @returns {any} cached content + * @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 */ - get(identifier, etag) { - const info = this.itemInfo.get(identifier); - this._addRequest(identifier); - if (info === undefined) { - return undefined; - } - if (info.etag !== etag) return null; - info.lastAccess = Date.now(); - const loc = info.location; - if (loc === -1) { - return info.freshValue; - } else { - if (!this.content[loc]) { - return undefined; - } - return this.content[loc].get(identifier); - } + constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) { + this.library = { + type: target || "var", + name, + umdNamedDefine, + auxiliaryComment, + export: exportProperty + }; } /** - * @param {string} identifier unique name for the resource - * @param {string | null} etag etag of the resource - * @param {any} data cached content + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - set(identifier, etag, data) { - if (!this.invalid) { - this.invalid = true; - this.logger.log(`Pack got invalid because of write to: ${identifier}`); - } - const info = this.itemInfo.get(identifier); - if (info === undefined) { - const newInfo = new PackItemInfo(identifier, etag, data); - this.itemInfo.set(identifier, newInfo); - this._addRequest(identifier); - this.freshContent.set(identifier, newInfo); - } else { - const loc = info.location; - if (loc >= 0) { - this._addRequest(identifier); - this.freshContent.set(identifier, info); - const content = this.content[loc]; - content.delete(identifier); - if (content.items.size === 0) { - this.content[loc] = undefined; - this.logger.debug("Pack %d got empty and is removed", loc); - } - } - info.freshValue = data; - info.lastAccess = Date.now(); - info.etag = etag; - info.location = -1; - } - } - - getContentStats() { - let count = 0; - let size = 0; - for (const content of this.content) { - if (content !== undefined) { - count++; - const s = content.getSize(); - if (s > 0) { - size += s; - } - } - } - return { count, size }; + apply(compiler) { + const { output } = compiler.options; + output.library = this.library; + new EnableLibraryPlugin(this.library.type).apply(compiler); } +} - /** - * @returns {number} new location of data entries - */ - _findLocation() { - let i; - for (i = 0; i < this.content.length && this.content[i] !== undefined; i++); - return i; - } +module.exports = LibraryTemplatePlugin; - _gcAndUpdateLocation(items, usedItems, newLoc) { - let count = 0; - let lastGC; - const now = Date.now(); - for (const identifier of items) { - const info = this.itemInfo.get(identifier); - if (now - info.lastAccess > this.maxAge) { - this.itemInfo.delete(identifier); - items.delete(identifier); - usedItems.delete(identifier); - count++; - lastGC = identifier; - } else { - info.location = newLoc; - } - } - if (count > 0) { - this.logger.log( - "Garbage Collected %d old items at pack %d (%d items remaining) e. g. %s", - count, - newLoc, - items.size, - lastGC - ); - } - } - _persistFreshContent() { - const itemsCount = this.freshContent.size; - if (itemsCount > 0) { - const packCount = Math.ceil(itemsCount / MAX_ITEMS_IN_FRESH_PACK); - const itemsPerPack = Math.ceil(itemsCount / packCount); - const packs = []; - let i = 0; - let ignoreNextTimeTick = false; - const createNextPack = () => { - const loc = this._findLocation(); - this.content[loc] = null; // reserve - const pack = { - /** @type {Set} */ - items: new Set(), - /** @type {Map} */ - map: new Map(), - loc - }; - packs.push(pack); - return pack; - }; - let pack = createNextPack(); - if (this.requestsTimeout !== undefined) - clearTimeout(this.requestsTimeout); - for (const identifier of this.requests) { - if (identifier === undefined) { - if (ignoreNextTimeTick) { - ignoreNextTimeTick = false; - } else if (pack.items.size >= MIN_ITEMS_IN_FRESH_PACK) { - i = 0; - pack = createNextPack(); - } - continue; - } - const info = this.freshContent.get(identifier); - if (info === undefined) continue; - pack.items.add(identifier); - pack.map.set(identifier, info.freshValue); - info.location = pack.loc; - info.freshValue = undefined; - this.freshContent.delete(identifier); - if (++i > itemsPerPack) { - i = 0; - pack = createNextPack(); - ignoreNextTimeTick = true; - } - } - this.requests.length = 0; - for (const pack of packs) { - this.content[pack.loc] = new PackContent( - pack.items, - new Set(pack.items), - new PackContentItems(pack.map) - ); - } - this.logger.log( - `${itemsCount} fresh items in cache put into pack ${ - packs.length > 1 - ? packs - .map(pack => `${pack.loc} (${pack.items.size} items)`) - .join(", ") - : packs[0].loc - }` - ); - } - } +/***/ }), - /** - * Merges small content files to a single content file - */ - _optimizeSmallContent() { - // 1. Find all small content files - // Treat unused content files separately to avoid - // a merge-split cycle - /** @type {number[]} */ - const smallUsedContents = []; - /** @type {number} */ - let smallUsedContentSize = 0; - /** @type {number[]} */ - const smallUnusedContents = []; - /** @type {number} */ - let smallUnusedContentSize = 0; - for (let i = 0; i < this.content.length; i++) { - const content = this.content[i]; - if (content === undefined) continue; - if (content.outdated) continue; - const size = content.getSize(); - if (size < 0 || size > MIN_CONTENT_SIZE) continue; - if (content.used.size > 0) { - smallUsedContents.push(i); - smallUsedContentSize += size; - } else { - smallUnusedContents.push(i); - smallUnusedContentSize += size; - } - } +/***/ 22078: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // 2. Check if minimum number is reached - let mergedIndices; - if ( - smallUsedContents.length >= CONTENT_COUNT_TO_MERGE || - smallUsedContentSize > MIN_CONTENT_SIZE - ) { - mergedIndices = smallUsedContents; - } else if ( - smallUnusedContents.length >= CONTENT_COUNT_TO_MERGE || - smallUnusedContentSize > MIN_CONTENT_SIZE - ) { - mergedIndices = smallUnusedContents; - } else return; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const mergedContent = []; - // 3. Remove old content entries - for (const i of mergedIndices) { - mergedContent.push(this.content[i]); - this.content[i] = undefined; - } - // 4. Determine merged items - /** @type {Set} */ - const mergedItems = new Set(); - /** @type {Set} */ - const mergedUsedItems = new Set(); - /** @type {(function(Map): Promise)[]} */ - const addToMergedMap = []; - for (const content of mergedContent) { - for (const identifier of content.items) { - mergedItems.add(identifier); - } - for (const identifier of content.used) { - mergedUsedItems.add(identifier); - } - addToMergedMap.push(async map => { - // unpack existing content - // after that values are accessible in .content - await content.unpack( - "it should be merged with other small pack contents" - ); - for (const [identifier, value] of content.content) { - map.set(identifier, value); - } - }); - } +const ModuleFilenameHelpers = __webpack_require__(88821); +const NormalModule = __webpack_require__(39); +const createSchemaValidation = __webpack_require__(32540); - // 5. GC and update location of merged items - const newLoc = this._findLocation(); - this._gcAndUpdateLocation(mergedItems, mergedUsedItems, newLoc); +/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ - // 6. If not empty, store content somewhere - if (mergedItems.size > 0) { - this.content[newLoc] = new PackContent( - mergedItems, - mergedUsedItems, - memoize(async () => { - /** @type {Map} */ - const map = new Map(); - await Promise.all(addToMergedMap.map(fn => fn(map))); - return new PackContentItems(map); - }) - ); - this.logger.log( - "Merged %d small files with %d cache items into pack %d", - mergedContent.length, - mergedItems.size, - newLoc - ); +const validate = createSchemaValidation( + __webpack_require__(24160), + () => __webpack_require__(15965), + { + name: "Loader Options Plugin", + baseDataPath: "options" + } +); +class LoaderOptionsPlugin { + /** + * @param {LoaderOptionsPluginOptions} options options object + */ + constructor(options = {}) { + validate(options); + if (typeof options !== "object") options = {}; + if (!options.test) { + options.test = { + test: () => true + }; } + this.options = options; } /** - * Split large content files with used and unused items - * into two parts to separate used from unused items + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - _optimizeUnusedContent() { - // 1. Find a large content file with used and unused items - for (let i = 0; i < this.content.length; i++) { - const content = this.content[i]; - if (content === undefined) continue; - const size = content.getSize(); - if (size < MIN_CONTENT_SIZE) continue; - const used = content.used.size; - const total = content.items.size; - if (used > 0 && used < total) { - // 2. Remove this content - this.content[i] = undefined; - - // 3. Determine items for the used content file - const usedItems = new Set(content.used); - const newLoc = this._findLocation(); - this._gcAndUpdateLocation(usedItems, usedItems, newLoc); - - // 4. Create content file for used items - if (usedItems.size > 0) { - this.content[newLoc] = new PackContent( - usedItems, - new Set(usedItems), - async () => { - await content.unpack( - "it should be splitted into used and unused items" - ); - const map = new Map(); - for (const identifier of usedItems) { - map.set(identifier, content.content.get(identifier)); + 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; } - return new PackContentItems(map); + context[key] = options[key]; } - ); + } } + ); + }); + } +} - // 5. Determine items for the unused content file - const unusedItems = new Set(content.items); - const usedOfUnusedItems = new Set(); - for (const identifier of usedItems) { - unusedItems.delete(identifier); - } - const newUnusedLoc = this._findLocation(); - this._gcAndUpdateLocation(unusedItems, usedOfUnusedItems, newUnusedLoc); +module.exports = LoaderOptionsPlugin; - // 6. Create content file for unused items - if (unusedItems.size > 0) { - this.content[newUnusedLoc] = new PackContent( - unusedItems, - usedOfUnusedItems, - async () => { - await content.unpack( - "it should be splitted into used and unused items" - ); - const map = new Map(); - for (const identifier of unusedItems) { - map.set(identifier, content.content.get(identifier)); - } - return new PackContentItems(map); - } - ); - } - this.logger.log( - "Split pack %d into pack %d with %d used items and pack %d with %d unused items", - i, - newLoc, - usedItems.size, - newUnusedLoc, - unusedItems.size - ); +/***/ }), - // optimizing only one of them is good enough and - // reduces the amount of serialization needed - return; - } - } - } +/***/ 86738: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * Find the content with the oldest item and run GC on that. - * Only runs for one content to avoid large invalidation. - */ - _gcOldestContent() { - /** @type {PackItemInfo} */ - let oldest = undefined; - for (const info of this.itemInfo.values()) { - if (oldest === undefined || info.lastAccess < oldest.lastAccess) { - oldest = info; - } - } - if (Date.now() - oldest.lastAccess > this.maxAge) { - const loc = oldest.location; - if (loc < 0) return; - const content = this.content[loc]; - const items = new Set(content.items); - const usedItems = new Set(content.used); - this._gcAndUpdateLocation(items, usedItems, loc); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - this.content[loc] = - items.size > 0 - ? new PackContent(items, usedItems, async () => { - await content.unpack( - "it contains old items that should be garbage collected" - ); - const map = new Map(); - for (const identifier of items) { - map.set(identifier, content.content.get(identifier)); - } - return new PackContentItems(map); - }) - : undefined; - } - } - serialize({ write, writeSeparate }) { - this._persistFreshContent(); - this._optimizeSmallContent(); - this._optimizeUnusedContent(); - this._gcOldestContent(); - for (const identifier of this.itemInfo.keys()) { - write(identifier); - } - write(null); // null as marker of the end of keys - for (const info of this.itemInfo.values()) { - write(info.etag); - } - for (const info of this.itemInfo.values()) { - write(info.lastAccess); - } - for (let i = 0; i < this.content.length; i++) { - const content = this.content[i]; - if (content !== undefined) { - write(content.items); - content.writeLazy(lazy => writeSeparate(lazy, { name: `${i}` })); - } else { - write(undefined); // undefined marks an empty content slot - } - } - write(null); // null as marker of the end of items - } - deserialize({ read, logger }) { - this.logger = logger; - { - const items = []; - let item = read(); - while (item !== null) { - items.push(item); - item = read(); - } - this.itemInfo.clear(); - const infoItems = items.map(identifier => { - const info = new PackItemInfo(identifier, undefined, undefined); - this.itemInfo.set(identifier, info); - return info; - }); - for (const info of infoItems) { - info.etag = read(); - } - for (const info of infoItems) { - info.lastAccess = read(); - } - } - this.content.length = 0; - let items = read(); - while (items !== null) { - if (items === undefined) { - this.content.push(items); - } else { - const idx = this.content.length; - const lazy = read(); - this.content.push( - new PackContent( - items, - new Set(), - lazy, - logger, - `${this.content.length}` - ) - ); - for (const identifier of items) { - this.itemInfo.get(identifier).location = idx; - } - } - items = read(); - } - } -} +const NormalModule = __webpack_require__(39); -makeSerializable(Pack, "webpack/lib/cache/PackFileCacheStrategy", "Pack"); +/** @typedef {import("./Compiler")} Compiler */ -class PackContentItems { +class LoaderTargetPlugin { /** - * @param {Map} map items + * @param {string} target the target */ - constructor(map) { - this.map = map; + constructor(target) { + this.target = target; } - serialize({ write, snapshot, rollback, logger, profile }) { - if (profile) { - write(false); - for (const [key, value] of this.map) { - const s = snapshot(); - try { - write(key); - const start = process.hrtime(); - write(value); - const durationHr = process.hrtime(start); - const duration = durationHr[0] * 1000 + durationHr[1] / 1e6; - if (duration > 1) { - if (duration > 500) - logger.error(`Serialization of '${key}': ${duration} ms`); - else if (duration > 50) - logger.warn(`Serialization of '${key}': ${duration} ms`); - else if (duration > 10) - logger.info(`Serialization of '${key}': ${duration} ms`); - else if (duration > 5) - logger.log(`Serialization of '${key}': ${duration} ms`); - else logger.debug(`Serialization of '${key}': ${duration} ms`); - } - } catch (e) { - rollback(s); - if (e === NOT_SERIALIZABLE) continue; - logger.warn( - `Skipped not serializable cache item '${key}': ${e.message}` - ); - logger.debug(e.stack); + /** + * 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; } - } - write(null); - return; - } - // Try to serialize all at once - const s = snapshot(); - try { - write(true); - write(this.map); - } catch (e) { - rollback(s); + ); + }); + } +} - // Try to serialize each item on it's own - write(false); - for (const [key, value] of this.map) { - const s = snapshot(); - try { - write(key); - write(value); - } catch (e) { - rollback(s); - if (e === NOT_SERIALIZABLE) continue; - logger.warn( - `Skipped not serializable cache item '${key}': ${e.message}` +module.exports = LoaderTargetPlugin; + + +/***/ }), + +/***/ 12856: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { SyncWaterfallHook } = __webpack_require__(41242); +const util = __webpack_require__(73837); +const RuntimeGlobals = __webpack_require__(16475); +const memoize = __webpack_require__(78676); + +/** @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("./javascript/JavascriptModulesPlugin").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(() => + __webpack_require__(89464) +); +const getJsonpTemplatePlugin = memoize(() => + __webpack_require__(4607) +); +const getLoadScriptRuntimeModule = memoize(() => + __webpack_require__(19942) +); + +// 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)" ); - logger.debug(e.stack); } + }, + + // 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; } - write(null); - } - } + }); - deserialize({ read, logger, profile }) { - if (read()) { - this.map = read(); - } else if (profile) { - const map = new Map(); - let key = read(); - while (key !== null) { - const start = process.hrtime(); - const value = read(); - const durationHr = process.hrtime(start); - const duration = durationHr[0] * 1000 + durationHr[1] / 1e6; - if (duration > 1) { - if (duration > 100) - logger.error(`Deserialization of '${key}': ${duration} ms`); - else if (duration > 20) - logger.warn(`Deserialization of '${key}': ${duration} ms`); - else if (duration > 5) - logger.info(`Deserialization of '${key}': ${duration} ms`); - else if (duration > 2) - logger.log(`Deserialization of '${key}': ${duration} ms`); - else logger.debug(`Deserialization of '${key}': ${duration} ms`); + 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)}`; } - map.set(key, value); - key = read(); - } - this.map = map; - } else { - const map = new Map(); - let key = read(); - while (key !== null) { - map.set(key, read()); - key = read(); - } - this.map = map; - } + 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" + ); } } -makeSerializable( - PackContentItems, - "webpack/lib/cache/PackFileCacheStrategy", - "PackContentItems" -); +Object.defineProperty(MainTemplate.prototype, "requireFn", { + get: util.deprecate( + () => "__webpack_require__", + 'MainTemplate.requireFn is deprecated (use "__webpack_require__")', + "DEP_WEBPACK_MAIN_TEMPLATE_REQUIRE_FN" + ) +}); -class PackContent { - /* - This class can be in these states: - | this.lazy | this.content | this.outdated | state - A1 | undefined | Map | false | fresh content - A2 | undefined | Map | true | (will not happen) - B1 | lazy () => {} | undefined | false | not deserialized - B2 | lazy () => {} | undefined | true | not deserialized, but some items has been removed - C1 | lazy* () => {} | Map | false | deserialized - C2 | lazy* () => {} | Map | true | deserialized, and some items has been removed +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" + ) +}); - this.used is a subset of this.items. - this.items is a subset of this.content.keys() resp. this.lazy().map.keys() - When this.outdated === false, this.items === this.content.keys() resp. this.lazy().map.keys() - When this.outdated === true, this.items should be used to recreated this.lazy/this.content. - When this.lazy and this.content is set, they contain the same data. - this.get must only be called with a valid item from this.items. - In state C this.lazy is unMemoized - */ +module.exports = MainTemplate; + + +/***/ }), + +/***/ 73208: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const util = __webpack_require__(73837); +const ChunkGraph = __webpack_require__(64971); +const DependenciesBlock = __webpack_require__(71040); +const ModuleGraph = __webpack_require__(99988); +const RuntimeGlobals = __webpack_require__(16475); +const { first } = __webpack_require__(93347); +const { compareChunksById } = __webpack_require__(29579); +const makeSerializable = __webpack_require__(33032); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./ExportsInfo").UsageStateType} UsageStateType */ +/** @typedef {import("./FileSystemInfo")} FileSystemInfo */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./util/Hash")} Hash */ +/** @template T @typedef {import("./util/LazySet")} LazySet */ +/** @template T @typedef {import("./util/SortableSet")} SortableSet */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @typedef {Object} SourceContext + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {RuntimeSpec} runtime the runtimes code should be generated for + * @property {string=} type the type of source that should be generated + */ + +/** + * @typedef {Object} CodeGenerationContext + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {RuntimeSpec} runtime the runtimes code should be generated for + * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules + * @property {CodeGenerationResults} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that) + */ + +/** + * @typedef {Object} ConcatenationBailoutReasonContext + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + */ + +/** + * @typedef {Object} CodeGenerationResult + * @property {Map} sources the resulting sources for all source types + * @property {Map=} data the resulting data for all source types + * @property {ReadonlySet} runtimeRequirements the runtime requirements + * @property {string=} hash a hash of the code generation result (will be automatically calculated from sources and runtimeRequirements if not provided) + */ + +/** + * @typedef {Object} LibIdentOptions + * @property {string} context absolute context path to which lib ident is relative to + * @property {Object=} associatedObjectForCache object for caching + */ + +/** + * @typedef {Object} KnownBuildMeta + * @property {string=} moduleArgument + * @property {string=} exportsArgument + * @property {boolean=} strict + * @property {string=} moduleConcatenationBailout + * @property {("default" | "namespace" | "flagged" | "dynamic")=} exportsType + * @property {(false | "redirect" | "redirect-warn")=} defaultObject + * @property {boolean=} strictHarmonyModule + * @property {boolean=} async + * @property {boolean=} sideEffectFree + */ + +/** + * @typedef {Object} NeedBuildContext + * @property {Compilation} compilation + * @property {FileSystemInfo} fileSystemInfo + * @property {Map>} valueCacheVersions + */ + +/** @typedef {KnownBuildMeta & Record} BuildMeta */ + +const EMPTY_RESOLVE_OPTIONS = {}; + +let debugId = 1000; + +const DEFAULT_TYPES_UNKNOWN = new Set(["unknown"]); +const DEFAULT_TYPES_JS = new Set(["javascript"]); + +const deprecatedNeedRebuild = util.deprecate( + (module, context) => { + return module.needRebuild( + context.fileSystemInfo.getDeprecatedFileTimestamps(), + context.fileSystemInfo.getDeprecatedContextTimestamps() + ); + }, + "Module.needRebuild is deprecated in favor of Module.needBuild", + "DEP_WEBPACK_MODULE_NEED_REBUILD" +); + +/** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ +class Module extends DependenciesBlock { /** - * @param {Set} items keys - * @param {Set} usedItems used keys - * @param {PackContentItems | function(): Promise} dataOrFn sync or async content - * @param {Logger=} logger logger for logging - * @param {string=} lazyName name of dataOrFn for logging + * @param {string} type the module type + * @param {string=} context an optional context + * @param {string=} layer an optional layer in which the module is */ - constructor(items, usedItems, dataOrFn, logger, lazyName) { - this.items = items; - /** @type {function(): Promise | PackContentItems} */ - this.lazy = typeof dataOrFn === "function" ? dataOrFn : undefined; - /** @type {Map} */ - this.content = typeof dataOrFn === "function" ? undefined : dataOrFn.map; - this.outdated = false; - this.used = usedItems; - this.logger = logger; - this.lazyName = lazyName; + constructor(type, context = null, layer = null) { + super(); + + /** @type {string} */ + this.type = type; + /** @type {string | null} */ + this.context = context; + /** @type {string | null} */ + this.layer = layer; + /** @type {boolean} */ + this.needId = true; + + // Unique Id + /** @type {number} */ + this.debugId = debugId++; + + // Info from Factory + /** @type {ResolveOptions} */ + this.resolveOptions = EMPTY_RESOLVE_OPTIONS; + /** @type {object | undefined} */ + this.factoryMeta = undefined; + // TODO refactor this -> options object filled from Factory + // TODO webpack 6: use an enum + /** @type {boolean} */ + this.useSourceMap = false; + /** @type {boolean} */ + this.useSimpleSourceMap = false; + + // Info from Build + /** @type {WebpackError[] | undefined} */ + this._warnings = undefined; + /** @type {WebpackError[] | undefined} */ + this._errors = undefined; + /** @type {BuildMeta} */ + this.buildMeta = undefined; + /** @type {Record} */ + this.buildInfo = undefined; + /** @type {Dependency[] | undefined} */ + this.presentationalDependencies = undefined; + /** @type {Dependency[] | undefined} */ + this.codeGenerationDependencies = undefined; } - get(identifier) { - this.used.add(identifier); - if (this.content) { - return this.content.get(identifier); - } + // TODO remove in webpack 6 + // BACKWARD-COMPAT START + get id() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.id", + "DEP_WEBPACK_MODULE_ID" + ).getModuleId(this); + } - // We are in state B - const { lazyName } = this; - let timeMessage; - if (lazyName) { - // only log once - this.lazyName = undefined; - timeMessage = `restore cache content ${lazyName} (${formatSize( - this.getSize() - )})`; - this.logger.log( - `starting to restore cache content ${lazyName} (${formatSize( - this.getSize() - )}) because of request to: ${identifier}` - ); - this.logger.time(timeMessage); - } - const value = this.lazy(); - if ("then" in value) { - return value.then(data => { - const map = data.map; - if (timeMessage) { - this.logger.timeEnd(timeMessage); - } - // Move to state C - this.content = map; - this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); - return map.get(identifier); - }); - } else { - const map = value.map; - if (timeMessage) { - this.logger.timeEnd(timeMessage); - } - // Move to state C - this.content = map; - this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); - return map.get(identifier); + set id(value) { + if (value === "") { + this.needId = false; + return; } + ChunkGraph.getChunkGraphForModule( + this, + "Module.id", + "DEP_WEBPACK_MODULE_ID" + ).setModuleId(this, value); } /** - * @param {string} reason explanation why unpack is necessary - * @returns {void | Promise} maybe a promise if lazy + * @returns {string} the hash of the module */ - unpack(reason) { - if (this.content) return; - - // Move from state B to C - if (this.lazy) { - const { lazyName } = this; - let timeMessage; - if (lazyName) { - // only log once - this.lazyName = undefined; - timeMessage = `unpack cache content ${lazyName} (${formatSize( - this.getSize() - )})`; - this.logger.log( - `starting to unpack cache content ${lazyName} (${formatSize( - this.getSize() - )}) because ${reason}` - ); - this.logger.time(timeMessage); - } - const value = this.lazy(); - if ("then" in value) { - return value.then(data => { - if (timeMessage) { - this.logger.timeEnd(timeMessage); - } - this.content = data.map; - }); - } else { - if (timeMessage) { - this.logger.timeEnd(timeMessage); - } - this.content = value.map; - } - } + get hash() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.hash", + "DEP_WEBPACK_MODULE_HASH" + ).getModuleHash(this, undefined); } /** - * @returns {number} size of the content or -1 if not known + * @returns {string} the shortened hash of the module */ - getSize() { - if (!this.lazy) return -1; - const options = /** @type {any} */ (this.lazy).options; - if (!options) return -1; - const size = options.size; - if (typeof size !== "number") return -1; - return size; + get renderedHash() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.renderedHash", + "DEP_WEBPACK_MODULE_RENDERED_HASH" + ).getRenderedModuleHash(this, undefined); } - delete(identifier) { - this.items.delete(identifier); - this.used.delete(identifier); - this.outdated = true; + get profile() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.profile", + "DEP_WEBPACK_MODULE_PROFILE" + ).getProfile(this); } - /** - * @template T - * @param {function(any): function(): Promise | PackContentItems} write write function - * @returns {void} - */ - writeLazy(write) { - if (!this.outdated && this.lazy) { - // State B1 or C1 - // this.lazy is still the valid deserialized version - write(this.lazy); - return; - } - if (!this.outdated && this.content) { - // State A1 - const map = new Map(this.content); - // Move to state C1 - this.lazy = SerializerMiddleware.unMemoizeLazy( - write(() => new PackContentItems(map)) - ); - return; - } - if (this.content) { - // State A2 or C2 - /** @type {Map} */ - const map = new Map(); - for (const item of this.items) { - map.set(item, this.content.get(item)); - } - // Move to state C1 - this.outdated = false; - this.content = map; - this.lazy = SerializerMiddleware.unMemoizeLazy( - write(() => new PackContentItems(map)) - ); - return; - } - // State B2 - const { lazyName } = this; - let timeMessage; - if (lazyName) { - // only log once - this.lazyName = undefined; - timeMessage = `unpack cache content ${lazyName} (${formatSize( - this.getSize() - )})`; - this.logger.log( - `starting to unpack cache content ${lazyName} (${formatSize( - this.getSize() - )}) because it's outdated and need to be serialized` - ); - this.logger.time(timeMessage); - } - const value = this.lazy(); - this.outdated = false; - if ("then" in value) { - // Move to state B1 - this.lazy = write(() => - value.then(data => { - if (timeMessage) { - this.logger.timeEnd(timeMessage); - } - const oldMap = data.map; - /** @type {Map} */ - const map = new Map(); - for (const item of this.items) { - map.set(item, oldMap.get(item)); - } - // Move to state C1 (or maybe C2) - this.content = map; - this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + set profile(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.profile", + "DEP_WEBPACK_MODULE_PROFILE" + ).setProfile(this, value); + } - return new PackContentItems(map); - }) - ); - } else { - // Move to state C1 - if (timeMessage) { - this.logger.timeEnd(timeMessage); - } - const oldMap = value.map; - /** @type {Map} */ - const map = new Map(); - for (const item of this.items) { - map.set(item, oldMap.get(item)); - } - this.content = map; - this.lazy = write(() => new PackContentItems(map)); - } + get index() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.index", + "DEP_WEBPACK_MODULE_INDEX" + ).getPreOrderIndex(this); } -} -const allowCollectingMemory = buf => { - const wasted = buf.buffer.byteLength - buf.byteLength; - if (wasted > 8192 && (wasted > 1048576 || wasted > buf.byteLength)) { - return Buffer.from(buf); + set index(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.index", + "DEP_WEBPACK_MODULE_INDEX" + ).setPreOrderIndex(this, value); + } + + get index2() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.index2", + "DEP_WEBPACK_MODULE_INDEX2" + ).getPostOrderIndex(this); + } + + set index2(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.index2", + "DEP_WEBPACK_MODULE_INDEX2" + ).setPostOrderIndex(this, value); + } + + get depth() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.depth", + "DEP_WEBPACK_MODULE_DEPTH" + ).getDepth(this); + } + + set depth(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.depth", + "DEP_WEBPACK_MODULE_DEPTH" + ).setDepth(this, value); + } + + get issuer() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.issuer", + "DEP_WEBPACK_MODULE_ISSUER" + ).getIssuer(this); + } + + set issuer(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.issuer", + "DEP_WEBPACK_MODULE_ISSUER" + ).setIssuer(this, value); + } + + get usedExports() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.usedExports", + "DEP_WEBPACK_MODULE_USED_EXPORTS" + ).getUsedExports(this, undefined); } - return buf; -}; -class PackFileCacheStrategy { /** - * @param {Object} options options - * @param {Compiler} options.compiler the compiler - * @param {IntermediateFileSystem} options.fs the filesystem - * @param {string} options.context the context directory - * @param {string} options.cacheLocation the location of the cache data - * @param {string} options.version version identifier - * @param {Logger} options.logger a logger - * @param {SnapshotOptions} options.snapshot options regarding snapshotting - * @param {number} options.maxAge max age of cache items - * @param {boolean} options.profile track and log detailed timing information for individual cache items - * @param {boolean} options.allowCollectingMemory allow to collect unused memory created during deserialization - * @param {false | "gzip" | "brotli"} options.compression compression used + * @deprecated + * @returns {(string | OptimizationBailoutFunction)[]} list */ - constructor({ - compiler, - fs, - context, - cacheLocation, - version, - logger, - snapshot, - maxAge, - profile, - allowCollectingMemory, - compression - }) { - this.fileSerializer = createFileSerializer( - fs, - compiler.options.output.hashFunction + get optimizationBailout() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.optimizationBailout", + "DEP_WEBPACK_MODULE_OPTIMIZATION_BAILOUT" + ).getOptimizationBailout(this); + } + + get optional() { + return this.isOptional( + ModuleGraph.getModuleGraphForModule( + this, + "Module.optional", + "DEP_WEBPACK_MODULE_OPTIONAL" + ) ); - this.fileSystemInfo = new FileSystemInfo(fs, { - managedPaths: snapshot.managedPaths, - immutablePaths: snapshot.immutablePaths, - logger: logger.getChildLogger("webpack.FileSystemInfo"), - hashFunction: compiler.options.output.hashFunction - }); - this.compiler = compiler; - this.context = context; - this.cacheLocation = cacheLocation; - this.version = version; - this.logger = logger; - this.maxAge = maxAge; - this.profile = profile; - this.allowCollectingMemory = allowCollectingMemory; - this.compression = compression; - this._extension = - compression === "brotli" - ? ".pack.br" - : compression === "gzip" - ? ".pack.gz" - : ".pack"; - this.snapshot = snapshot; - /** @type {Set} */ - this.buildDependencies = new Set(); - /** @type {LazySet} */ - this.newBuildDependencies = new LazySet(); - /** @type {Snapshot} */ - this.resolveBuildDependenciesSnapshot = undefined; - /** @type {Map} */ - this.resolveResults = undefined; - /** @type {Snapshot} */ - this.buildSnapshot = undefined; - /** @type {Promise} */ - this.packPromise = this._openPack(); - this.storePromise = Promise.resolve(); } - _getPack() { - if (this.packPromise === undefined) { - this.packPromise = this.storePromise.then(() => this._openPack()); - } - return this.packPromise; + addChunk(chunk) { + const chunkGraph = ChunkGraph.getChunkGraphForModule( + this, + "Module.addChunk", + "DEP_WEBPACK_MODULE_ADD_CHUNK" + ); + if (chunkGraph.isModuleInChunk(this, chunk)) return false; + chunkGraph.connectChunkAndModule(chunk, this); + return true; } - /** - * @returns {Promise} the pack - */ - _openPack() { - const { logger, profile, cacheLocation, version } = this; - /** @type {Snapshot} */ - let buildSnapshot; - /** @type {Set} */ - let buildDependencies; - /** @type {Set} */ - let newBuildDependencies; - /** @type {Snapshot} */ - let resolveBuildDependenciesSnapshot; - /** @type {Map} */ - let resolveResults; - logger.time("restore cache container"); - return this.fileSerializer - .deserialize(null, { - filename: `${cacheLocation}/index${this._extension}`, - extension: `${this._extension}`, - logger, - profile, - retainedBuffer: this.allowCollectingMemory - ? allowCollectingMemory - : undefined - }) - .catch(err => { - if (err.code !== "ENOENT") { - logger.warn( - `Restoring pack failed from ${cacheLocation}${this._extension}: ${err}` - ); - logger.debug(err.stack); - } else { - logger.debug( - `No pack exists at ${cacheLocation}${this._extension}: ${err}` - ); - } - return undefined; - }) - .then(packContainer => { - logger.timeEnd("restore cache container"); - if (!packContainer) return undefined; - if (!(packContainer instanceof PackContainer)) { - logger.warn( - `Restored pack from ${cacheLocation}${this._extension}, but contained content is unexpected.`, - packContainer - ); - return undefined; - } - if (packContainer.version !== version) { - logger.log( - `Restored pack from ${cacheLocation}${this._extension}, but version doesn't match.` - ); - return undefined; - } - logger.time("check build dependencies"); - return Promise.all([ - new Promise((resolve, reject) => { - this.fileSystemInfo.checkSnapshotValid( - packContainer.buildSnapshot, - (err, valid) => { - if (err) { - logger.log( - `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of build dependencies errored: ${err}.` - ); - logger.debug(err.stack); - return resolve(false); - } - if (!valid) { - logger.log( - `Restored pack from ${cacheLocation}${this._extension}, but build dependencies have changed.` - ); - return resolve(false); - } - buildSnapshot = packContainer.buildSnapshot; - return resolve(true); - } - ); - }), - new Promise((resolve, reject) => { - this.fileSystemInfo.checkSnapshotValid( - packContainer.resolveBuildDependenciesSnapshot, - (err, valid) => { - if (err) { - logger.log( - `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of resolving of build dependencies errored: ${err}.` - ); - logger.debug(err.stack); - return resolve(false); - } - if (valid) { - resolveBuildDependenciesSnapshot = - packContainer.resolveBuildDependenciesSnapshot; - buildDependencies = packContainer.buildDependencies; - resolveResults = packContainer.resolveResults; - return resolve(true); - } - logger.log( - "resolving of build dependencies is invalid, will re-resolve build dependencies" - ); - this.fileSystemInfo.checkResolveResultsValid( - packContainer.resolveResults, - (err, valid) => { - if (err) { - logger.log( - `Restored pack from ${cacheLocation}${this._extension}, but resolving of build dependencies errored: ${err}.` - ); - logger.debug(err.stack); - return resolve(false); - } - if (valid) { - newBuildDependencies = packContainer.buildDependencies; - resolveResults = packContainer.resolveResults; - return resolve(true); - } - logger.log( - `Restored pack from ${cacheLocation}${this._extension}, but build dependencies resolve to different locations.` - ); - return resolve(false); - } - ); - } - ); - }) - ]) - .catch(err => { - logger.timeEnd("check build dependencies"); - throw err; - }) - .then(([buildSnapshotValid, resolveValid]) => { - logger.timeEnd("check build dependencies"); - if (buildSnapshotValid && resolveValid) { - logger.time("restore cache content metadata"); - const d = packContainer.data(); - logger.timeEnd("restore cache content metadata"); - return d; - } - return undefined; - }); - }) - .then(pack => { - if (pack) { - pack.maxAge = this.maxAge; - this.buildSnapshot = buildSnapshot; - if (buildDependencies) this.buildDependencies = buildDependencies; - if (newBuildDependencies) - this.newBuildDependencies.addAll(newBuildDependencies); - this.resolveResults = resolveResults; - this.resolveBuildDependenciesSnapshot = - resolveBuildDependenciesSnapshot; - return pack; - } - return new Pack(logger, this.maxAge); - }) - .catch(err => { - this.logger.warn( - `Restoring pack from ${cacheLocation}${this._extension} failed: ${err}` - ); - this.logger.debug(err.stack); - return new Pack(logger, this.maxAge); - }); + removeChunk(chunk) { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.removeChunk", + "DEP_WEBPACK_MODULE_REMOVE_CHUNK" + ).disconnectChunkAndModule(chunk, this); } - /** - * @param {string} identifier unique name for the resource - * @param {Etag | null} etag etag of the resource - * @param {any} data cached content - * @returns {Promise} promise - */ - store(identifier, etag, data) { - return this._getPack().then(pack => { - pack.set(identifier, etag === null ? null : etag.toString(), data); - }); + isInChunk(chunk) { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.isInChunk", + "DEP_WEBPACK_MODULE_IS_IN_CHUNK" + ).isModuleInChunk(this, chunk); } - /** - * @param {string} identifier unique name for the resource - * @param {Etag | null} etag etag of the resource - * @returns {Promise} promise to the cached content - */ - restore(identifier, etag) { - return this._getPack() - .then(pack => - pack.get(identifier, etag === null ? null : etag.toString()) - ) - .catch(err => { - if (err && err.code !== "ENOENT") { - this.logger.warn( - `Restoring failed for ${identifier} from pack: ${err}` - ); - this.logger.debug(err.stack); - } - }); + isEntryModule() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.isEntryModule", + "DEP_WEBPACK_MODULE_IS_ENTRY_MODULE" + ).isEntryModule(this); } - storeBuildDependencies(dependencies) { - this.newBuildDependencies.addAll(dependencies); + getChunks() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.getChunks", + "DEP_WEBPACK_MODULE_GET_CHUNKS" + ).getModuleChunks(this); } - afterAllStored() { - const packPromise = this.packPromise; - if (packPromise === undefined) return Promise.resolve(); - const reportProgress = ProgressPlugin.getReporter(this.compiler); - return (this.storePromise = packPromise - .then(pack => { - pack.stopCapturingRequests(); - if (!pack.invalid) return; - this.packPromise = undefined; - this.logger.log(`Storing pack...`); - let promise; - const newBuildDependencies = new Set(); - for (const dep of this.newBuildDependencies) { - if (!this.buildDependencies.has(dep)) { - newBuildDependencies.add(dep); - } - } - if (newBuildDependencies.size > 0 || !this.buildSnapshot) { - if (reportProgress) reportProgress(0.5, "resolve build dependencies"); - this.logger.debug( - `Capturing build dependencies... (${Array.from( - newBuildDependencies - ).join(", ")})` - ); - promise = new Promise((resolve, reject) => { - this.logger.time("resolve build dependencies"); - this.fileSystemInfo.resolveBuildDependencies( - this.context, - newBuildDependencies, - (err, result) => { - this.logger.timeEnd("resolve build dependencies"); - if (err) return reject(err); - - this.logger.time("snapshot build dependencies"); - const { - files, - directories, - missing, - resolveResults, - resolveDependencies - } = result; - if (this.resolveResults) { - for (const [key, value] of resolveResults) { - this.resolveResults.set(key, value); - } - } else { - this.resolveResults = resolveResults; - } - if (reportProgress) { - reportProgress( - 0.6, - "snapshot build dependencies", - "resolving" - ); - } - this.fileSystemInfo.createSnapshot( - undefined, - resolveDependencies.files, - resolveDependencies.directories, - resolveDependencies.missing, - this.snapshot.resolveBuildDependencies, - (err, snapshot) => { - if (err) { - this.logger.timeEnd("snapshot build dependencies"); - return reject(err); - } - if (!snapshot) { - this.logger.timeEnd("snapshot build dependencies"); - return reject( - new Error("Unable to snapshot resolve dependencies") - ); - } - if (this.resolveBuildDependenciesSnapshot) { - this.resolveBuildDependenciesSnapshot = - this.fileSystemInfo.mergeSnapshots( - this.resolveBuildDependenciesSnapshot, - snapshot - ); - } else { - this.resolveBuildDependenciesSnapshot = snapshot; - } - if (reportProgress) { - reportProgress( - 0.7, - "snapshot build dependencies", - "modules" - ); - } - this.fileSystemInfo.createSnapshot( - undefined, - files, - directories, - missing, - this.snapshot.buildDependencies, - (err, snapshot) => { - this.logger.timeEnd("snapshot build dependencies"); - if (err) return reject(err); - if (!snapshot) { - return reject( - new Error("Unable to snapshot build dependencies") - ); - } - this.logger.debug("Captured build dependencies"); - - if (this.buildSnapshot) { - this.buildSnapshot = - this.fileSystemInfo.mergeSnapshots( - this.buildSnapshot, - snapshot - ); - } else { - this.buildSnapshot = snapshot; - } - - resolve(); - } - ); - } - ); - } - ); - }); - } else { - promise = Promise.resolve(); - } - return promise.then(() => { - if (reportProgress) reportProgress(0.8, "serialize pack"); - this.logger.time(`store pack`); - const updatedBuildDependencies = new Set(this.buildDependencies); - for (const dep of newBuildDependencies) { - updatedBuildDependencies.add(dep); - } - const content = new PackContainer( - pack, - this.version, - this.buildSnapshot, - updatedBuildDependencies, - this.resolveResults, - this.resolveBuildDependenciesSnapshot - ); - return this.fileSerializer - .serialize(content, { - filename: `${this.cacheLocation}/index${this._extension}`, - extension: `${this._extension}`, - logger: this.logger, - profile: this.profile - }) - .then(() => { - for (const dep of newBuildDependencies) { - this.buildDependencies.add(dep); - } - this.newBuildDependencies.clear(); - this.logger.timeEnd(`store pack`); - const stats = pack.getContentStats(); - this.logger.log( - "Stored pack (%d items, %d files, %d MiB)", - pack.itemInfo.size, - stats.count, - Math.round(stats.size / 1024 / 1024) - ); - }) - .catch(err => { - this.logger.timeEnd(`store pack`); - this.logger.warn(`Caching failed for pack: ${err}`); - this.logger.debug(err.stack); - }); - }); - }) - .catch(err => { - this.logger.warn(`Caching failed for pack: ${err}`); - this.logger.debug(err.stack); - })); + getNumberOfChunks() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.getNumberOfChunks", + "DEP_WEBPACK_MODULE_GET_NUMBER_OF_CHUNKS" + ).getNumberOfModuleChunks(this); } - clear() { - this.fileSystemInfo.clear(); - this.buildDependencies.clear(); - this.newBuildDependencies.clear(); - this.resolveBuildDependenciesSnapshot = undefined; - this.resolveResults = undefined; - this.buildSnapshot = undefined; - this.packPromise = undefined; + get chunksIterable() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.chunksIterable", + "DEP_WEBPACK_MODULE_CHUNKS_ITERABLE" + ).getOrderedModuleChunksIterable(this, compareChunksById); } -} - -module.exports = PackFileCacheStrategy; - - -/***/ }), - -/***/ 97347: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const LazySet = __webpack_require__(38938); -const makeSerializable = __webpack_require__(33032); - -/** @typedef {import("enhanced-resolve/lib/Resolver")} Resolver */ -/** @typedef {import("../CacheFacade").ItemCacheFacade} ItemCacheFacade */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../FileSystemInfo")} FileSystemInfo */ -/** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */ - -class CacheEntry { - constructor(result, snapshot) { - this.result = result; - this.snapshot = snapshot; + /** + * @param {string} exportName a name of an export + * @returns {boolean | null} true, if the export is provided why the module. + * null, if it's unknown. + * false, if it's not provided. + */ + isProvided(exportName) { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.usedExports", + "DEP_WEBPACK_MODULE_USED_EXPORTS" + ).isExportProvided(this, exportName); } + // BACKWARD-COMPAT END - serialize({ write }) { - write(this.result); - write(this.snapshot); + /** + * @deprecated moved to .buildInfo.exportsArgument + * @returns {string} name of the exports argument + */ + get exportsArgument() { + return (this.buildInfo && this.buildInfo.exportsArgument) || "exports"; } - deserialize({ read }) { - this.result = read(); - this.snapshot = read(); + /** + * @deprecated moved to .buildInfo.moduleArgument + * @returns {string} name of the module argument + */ + get moduleArgument() { + return (this.buildInfo && this.buildInfo.moduleArgument) || "module"; } -} - -makeSerializable(CacheEntry, "webpack/lib/cache/ResolverCachePlugin"); -/** - * @template T - * @param {Set | LazySet} set set to add items to - * @param {Set | LazySet} otherSet set to add items from - * @returns {void} - */ -const addAllToSet = (set, otherSet) => { - if (set instanceof LazySet) { - set.addAll(otherSet); - } else { - for (const item of otherSet) { - set.add(item); + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {boolean} strict the importing module is strict + * @returns {"namespace" | "default-only" | "default-with-named" | "dynamic"} export type + * "namespace": Exports is already a namespace object. namespace = exports. + * "dynamic": Check at runtime if __esModule is set. When set: namespace = { ...exports, default: exports }. When not set: namespace = { default: exports }. + * "default-only": Provide a namespace object with only default export. namespace = { default: exports } + * "default-with-named": Provide a namespace object with named and default export. namespace = { ...exports, default: exports } + */ + getExportsType(moduleGraph, strict) { + switch (this.buildMeta && this.buildMeta.exportsType) { + case "flagged": + return strict ? "default-with-named" : "namespace"; + case "namespace": + return "namespace"; + case "default": + switch (this.buildMeta.defaultObject) { + case "redirect": + return "default-with-named"; + case "redirect-warn": + return strict ? "default-only" : "default-with-named"; + default: + return "default-only"; + } + case "dynamic": { + if (strict) return "default-with-named"; + // Try to figure out value of __esModule by following reexports + const handleDefault = () => { + switch (this.buildMeta.defaultObject) { + case "redirect": + case "redirect-warn": + return "default-with-named"; + default: + return "default-only"; + } + }; + const exportInfo = moduleGraph.getReadOnlyExportInfo( + this, + "__esModule" + ); + if (exportInfo.provided === false) { + return handleDefault(); + } + const target = exportInfo.getTarget(moduleGraph); + if ( + !target || + !target.export || + target.export.length !== 1 || + target.export[0] !== "__esModule" + ) { + return "dynamic"; + } + switch ( + target.module.buildMeta && + target.module.buildMeta.exportsType + ) { + case "flagged": + case "namespace": + return "namespace"; + case "default": + return handleDefault(); + default: + return "dynamic"; + } + } + default: + return strict ? "default-with-named" : "dynamic"; } } -}; -/** - * @param {Object} object an object - * @param {boolean} excludeContext if true, context is not included in string - * @returns {string} stringified version - */ -const objectToString = (object, excludeContext) => { - let str = ""; - for (const key in object) { - if (excludeContext && key === "context") continue; - const value = object[key]; - if (typeof value === "object" && value !== null) { - str += `|${key}=[${objectToString(value, false)}|]`; - } else { - str += `|${key}=|${value}`; + /** + * @param {Dependency} presentationalDependency dependency being tied to module. + * This is a Dependency without edge in the module graph. It's only for presentation. + * @returns {void} + */ + addPresentationalDependency(presentationalDependency) { + if (this.presentationalDependencies === undefined) { + this.presentationalDependencies = []; } + this.presentationalDependencies.push(presentationalDependency); } - return str; -}; -class ResolverCachePlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {Dependency} codeGenerationDependency dependency being tied to module. + * This is a Dependency where the code generation result of the referenced module is needed during code generation. + * The Dependency should also be added to normal dependencies via addDependency. * @returns {void} */ - apply(compiler) { - const cache = compiler.getCache("ResolverCachePlugin"); - /** @type {FileSystemInfo} */ - let fileSystemInfo; - let snapshotOptions; - let realResolves = 0; - let cachedResolves = 0; - let cacheInvalidResolves = 0; - let concurrentResolves = 0; - compiler.hooks.thisCompilation.tap("ResolverCachePlugin", compilation => { - snapshotOptions = compilation.options.snapshot.resolve; - fileSystemInfo = compilation.fileSystemInfo; - compilation.hooks.finishModules.tap("ResolverCachePlugin", () => { - if (realResolves + cachedResolves > 0) { - const logger = compilation.getLogger("webpack.ResolverCachePlugin"); - logger.log( - `${Math.round( - (100 * realResolves) / (realResolves + cachedResolves) - )}% really resolved (${realResolves} real resolves with ${cacheInvalidResolves} cached but invalid, ${cachedResolves} cached valid, ${concurrentResolves} concurrent)` - ); - realResolves = 0; - cachedResolves = 0; - cacheInvalidResolves = 0; - concurrentResolves = 0; - } - }); - }); - /** - * @param {ItemCacheFacade} itemCache cache - * @param {Resolver} resolver the resolver - * @param {Object} resolveContext context for resolving meta info - * @param {Object} request the request info object - * @param {function((Error | null)=, Object=): void} callback callback function - * @returns {void} - */ - const doRealResolve = ( - itemCache, - resolver, - resolveContext, - request, - callback - ) => { - realResolves++; - const newRequest = { - _ResolverCachePluginCacheMiss: true, - ...request - }; - const newResolveContext = { - ...resolveContext, - stack: new Set(), - missingDependencies: new LazySet(), - fileDependencies: new LazySet(), - contextDependencies: new LazySet() - }; - const propagate = key => { - if (resolveContext[key]) { - addAllToSet(resolveContext[key], newResolveContext[key]); - } - }; - const resolveTime = Date.now(); - resolver.doResolve( - resolver.hooks.resolve, - newRequest, - "Cache miss", - newResolveContext, - (err, result) => { - propagate("fileDependencies"); - propagate("contextDependencies"); - propagate("missingDependencies"); - if (err) return callback(err); - const fileDependencies = newResolveContext.fileDependencies; - const contextDependencies = newResolveContext.contextDependencies; - const missingDependencies = newResolveContext.missingDependencies; - fileSystemInfo.createSnapshot( - resolveTime, - fileDependencies, - contextDependencies, - missingDependencies, - snapshotOptions, - (err, snapshot) => { - if (err) return callback(err); - if (!snapshot) { - if (result) return callback(null, result); - return callback(); - } - itemCache.store(new CacheEntry(result, snapshot), storeErr => { - if (storeErr) return callback(storeErr); - if (result) return callback(null, result); - callback(); - }); - } - ); - } - ); - }; - compiler.resolverFactory.hooks.resolver.intercept({ - factory(type, hook) { - /** @type {Map} */ - const activeRequests = new Map(); - hook.tap( - "ResolverCachePlugin", - /** - * @param {Resolver} resolver the resolver - * @param {Object} options resolve options - * @param {Object} userOptions resolve options passed by the user - * @returns {void} - */ - (resolver, options, userOptions) => { - if (options.cache !== true) return; - const optionsIdent = objectToString(userOptions, false); - const cacheWithContext = - options.cacheWithContext !== undefined - ? options.cacheWithContext - : false; - resolver.hooks.resolve.tapAsync( - { - name: "ResolverCachePlugin", - stage: -100 - }, - (request, resolveContext, callback) => { - if (request._ResolverCachePluginCacheMiss || !fileSystemInfo) { - return callback(); - } - const identifier = `${type}${optionsIdent}${objectToString( - request, - !cacheWithContext - )}`; - const activeRequest = activeRequests.get(identifier); - if (activeRequest) { - activeRequest.push(callback); - return; - } - const itemCache = cache.getItemCache(identifier, null); - let callbacks; - const done = (err, result) => { - if (callbacks === undefined) { - callback(err, result); - callbacks = false; - } else { - for (const callback of callbacks) { - callback(err, result); - } - activeRequests.delete(identifier); - callbacks = false; - } - }; - /** - * @param {Error=} err error if any - * @param {CacheEntry=} cacheEntry cache entry - * @returns {void} - */ - const processCacheResult = (err, cacheEntry) => { - if (err) return done(err); - - if (cacheEntry) { - const { snapshot, result } = cacheEntry; - fileSystemInfo.checkSnapshotValid( - snapshot, - (err, valid) => { - if (err || !valid) { - cacheInvalidResolves++; - return doRealResolve( - itemCache, - resolver, - resolveContext, - request, - done - ); - } - cachedResolves++; - if (resolveContext.missingDependencies) { - addAllToSet( - resolveContext.missingDependencies, - snapshot.getMissingIterable() - ); - } - if (resolveContext.fileDependencies) { - addAllToSet( - resolveContext.fileDependencies, - snapshot.getFileIterable() - ); - } - if (resolveContext.contextDependencies) { - addAllToSet( - resolveContext.contextDependencies, - snapshot.getContextIterable() - ); - } - done(null, result); - } - ); - } else { - doRealResolve( - itemCache, - resolver, - resolveContext, - request, - done - ); - } - }; - itemCache.get(processCacheResult); - if (callbacks === undefined) { - callbacks = [callback]; - activeRequests.set(identifier, callbacks); - } - } - ); - } - ); - return hook; - } - }); + addCodeGenerationDependency(codeGenerationDependency) { + if (this.codeGenerationDependencies === undefined) { + this.codeGenerationDependencies = []; + } + this.codeGenerationDependencies.push(codeGenerationDependency); } -} - -module.exports = ResolverCachePlugin; - - -/***/ }), - -/***/ 94075: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + /** + * Removes all dependencies and blocks + * @returns {void} + */ + clearDependenciesAndBlocks() { + if (this.presentationalDependencies !== undefined) { + this.presentationalDependencies.length = 0; + } + if (this.codeGenerationDependencies !== undefined) { + this.codeGenerationDependencies.length = 0; + } + super.clearDependenciesAndBlocks(); + } -const createHash = __webpack_require__(49835); - -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {typeof import("../util/Hash")} HashConstructor */ + /** + * @param {WebpackError} warning the warning + * @returns {void} + */ + addWarning(warning) { + if (this._warnings === undefined) { + this._warnings = []; + } + this._warnings.push(warning); + } -/** - * @typedef {Object} HashableObject - * @property {function(Hash): void} updateHash - */ + /** + * @returns {Iterable | undefined} list of warnings if any + */ + getWarnings() { + return this._warnings; + } -class LazyHashedEtag { /** - * @param {HashableObject} obj object with updateHash method - * @param {string | HashConstructor} hashFunction the hash function to use + * @returns {number} number of warnings */ - constructor(obj, hashFunction = "md4") { - this._obj = obj; - this._hash = undefined; - this._hashFunction = hashFunction; + getNumberOfWarnings() { + return this._warnings !== undefined ? this._warnings.length : 0; } /** - * @returns {string} hash of object + * @param {WebpackError} error the error + * @returns {void} */ - toString() { - if (this._hash === undefined) { - const hash = createHash(this._hashFunction); - this._obj.updateHash(hash); - this._hash = /** @type {string} */ (hash.digest("base64")); + addError(error) { + if (this._errors === undefined) { + this._errors = []; } - return this._hash; + this._errors.push(error); } -} -/** @type {Map>} */ -const mapStrings = new Map(); + /** + * @returns {Iterable | undefined} list of errors if any + */ + getErrors() { + return this._errors; + } -/** @type {WeakMap>} */ -const mapObjects = new WeakMap(); + /** + * @returns {number} number of errors + */ + getNumberOfErrors() { + return this._errors !== undefined ? this._errors.length : 0; + } -/** - * @param {HashableObject} obj object with updateHash method - * @param {string | HashConstructor} hashFunction the hash function to use - * @returns {LazyHashedEtag} etag - */ -const getter = (obj, hashFunction = "md4") => { - let innerMap; - if (typeof hashFunction === "string") { - innerMap = mapStrings.get(hashFunction); - if (innerMap === undefined) { - const newHash = new LazyHashedEtag(obj, hashFunction); - innerMap = new WeakMap(); - innerMap.set(obj, newHash); - mapStrings.set(hashFunction, innerMap); - return newHash; + /** + * removes all warnings and errors + * @returns {void} + */ + clearWarningsAndErrors() { + if (this._warnings !== undefined) { + this._warnings.length = 0; } - } else { - innerMap = mapObjects.get(hashFunction); - if (innerMap === undefined) { - const newHash = new LazyHashedEtag(obj, hashFunction); - innerMap = new WeakMap(); - innerMap.set(obj, newHash); - mapObjects.set(hashFunction, innerMap); - return newHash; + if (this._errors !== undefined) { + this._errors.length = 0; } } - const hash = innerMap.get(obj); - if (hash !== undefined) return hash; - const newHash = new LazyHashedEtag(obj, hashFunction); - innerMap.set(obj, newHash); - return newHash; -}; - -module.exports = getter; - - -/***/ }), -/***/ 54980: -/***/ (function(module) { + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {boolean} true, if the module is optional + */ + isOptional(moduleGraph) { + let hasConnections = false; + for (const r of moduleGraph.getIncomingConnections(this)) { + if ( + !r.dependency || + !r.dependency.optional || + !r.isTargetActive(undefined) + ) { + return false; + } + hasConnections = true; + } + return hasConnections; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk} chunk a chunk + * @param {Chunk=} ignoreChunk chunk to be ignored + * @returns {boolean} true, if the module is accessible from "chunk" when ignoring "ignoreChunk" + */ + isAccessibleInChunk(chunkGraph, chunk, ignoreChunk) { + // Check if module is accessible in ALL chunk groups + for (const chunkGroup of chunk.groupsIterable) { + if (!this.isAccessibleInChunkGroup(chunkGraph, chunkGroup)) return false; + } + return true; + } + /** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {ChunkGroup} chunkGroup a chunk group + * @param {Chunk=} ignoreChunk chunk to be ignored + * @returns {boolean} true, if the module is accessible from "chunkGroup" when ignoring "ignoreChunk" + */ + isAccessibleInChunkGroup(chunkGraph, chunkGroup, ignoreChunk) { + const queue = new Set([chunkGroup]); + // Check if module is accessible from all items of the queue + queueFor: for (const cg of queue) { + // 1. If module is in one of the chunks of the group we can continue checking the next items + // because it's accessible. + for (const chunk of cg.chunks) { + if (chunk !== ignoreChunk && chunkGraph.isModuleInChunk(this, chunk)) + continue queueFor; + } + // 2. If the chunk group is initial, we can break here because it's not accessible. + if (chunkGroup.isInitial()) return false; + // 3. Enqueue all parents because it must be accessible from ALL parents + for (const parent of chunkGroup.parentsIterable) queue.add(parent); + } + // When we processed through the whole list and we didn't bailout, the module is accessible + return true; + } -/** @typedef {import("../Cache").Etag} Etag */ + /** + * @param {Chunk} chunk a chunk + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {boolean} true, if the module has any reason why "chunk" should be included + */ + hasReasonForChunk(chunk, moduleGraph, chunkGraph) { + // check for each reason if we need the chunk + for (const [ + fromModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(this)) { + if (!connections.some(c => c.isTargetActive(chunk.runtime))) continue; + for (const originChunk of chunkGraph.getModuleChunksIterable( + fromModule + )) { + // return true if module this is not reachable from originChunk when ignoring chunk + if (!this.isAccessibleInChunk(chunkGraph, originChunk, chunk)) + return true; + } + } + return false; + } -class MergedEtag { /** - * @param {Etag} a first - * @param {Etag} b second + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true if at least one other module depends on this module */ - constructor(a, b) { - this.a = a; - this.b = b; + hasReasons(moduleGraph, runtime) { + for (const c of moduleGraph.getIncomingConnections(this)) { + if (c.isTargetActive(runtime)) return true; + } + return false; } + /** + * @returns {string} for debugging + */ toString() { - return `${this.a.toString()}|${this.b.toString()}`; + return `Module[${this.debugId}: ${this.identifier()}]`; } -} -const dualObjectMap = new WeakMap(); -const objectStringMap = new WeakMap(); + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + callback( + null, + !this.buildMeta || + this.needRebuild === Module.prototype.needRebuild || + deprecatedNeedRebuild(this, context) + ); + } -/** - * @param {Etag} a first - * @param {Etag} b second - * @returns {Etag} result - */ -const mergeEtags = (a, b) => { - if (typeof a === "string") { - if (typeof b === "string") { - return `${a}|${b}`; - } else { - const temp = b; - b = a; - a = temp; + /** + * @deprecated Use needBuild instead + * @param {Map} fileTimestamps timestamps of files + * @param {Map} contextTimestamps timestamps of directories + * @returns {boolean} true, if the module needs a rebuild + */ + needRebuild(fileTimestamps, contextTimestamps) { + return true; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash( + hash, + context = { + chunkGraph: ChunkGraph.getChunkGraphForModule( + this, + "Module.updateHash", + "DEP_WEBPACK_MODULE_UPDATE_HASH" + ), + runtime: undefined } - } else { - if (typeof b !== "string") { - // both a and b are objects - let map = dualObjectMap.get(a); - if (map === undefined) { - dualObjectMap.set(a, (map = new WeakMap())); - } - const mergedEtag = map.get(b); - if (mergedEtag === undefined) { - const newMergedEtag = new MergedEtag(a, b); - map.set(b, newMergedEtag); - return newMergedEtag; - } else { - return mergedEtag; + ) { + const { chunkGraph, runtime } = context; + hash.update(chunkGraph.getModuleGraphHash(this, runtime)); + if (this.presentationalDependencies !== undefined) { + for (const dep of this.presentationalDependencies) { + dep.updateHash(hash, context); } } + super.updateHash(hash, context); } - // a is object, b is string - let map = objectStringMap.get(a); - if (map === undefined) { - objectStringMap.set(a, (map = new Map())); - } - const mergedEtag = map.get(b); - if (mergedEtag === undefined) { - const newMergedEtag = new MergedEtag(a, b); - map.set(b, newMergedEtag); - return newMergedEtag; - } else { - return mergedEtag; - } -}; - -module.exports = mergeEtags; - - -/***/ }), - -/***/ 13462: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const path = __webpack_require__(71017); -const webpackSchema = __webpack_require__(73342); - -// TODO add originPath to PathItem for better errors -/** - * @typedef {Object} PathItem - * @property {any} schema the part of the schema - * @property {string} path the path in the config - */ - -/** @typedef {"unknown-argument" | "unexpected-non-array-in-path" | "unexpected-non-object-in-path" | "multiple-values-unexpected" | "invalid-value"} ProblemType */ - -/** - * @typedef {Object} Problem - * @property {ProblemType} type - * @property {string} path - * @property {string} argument - * @property {any=} value - * @property {number=} index - * @property {string=} expected - */ - -/** - * @typedef {Object} LocalProblem - * @property {ProblemType} type - * @property {string} path - * @property {string=} expected - */ - -/** - * @typedef {Object} ArgumentConfig - * @property {string} description - * @property {string} [negatedDescription] - * @property {string} path - * @property {boolean} multiple - * @property {"enum"|"string"|"path"|"number"|"boolean"|"RegExp"|"reset"} type - * @property {any[]=} values - */ -/** - * @typedef {Object} Argument - * @property {string} description - * @property {"string"|"number"|"boolean"} simpleType - * @property {boolean} multiple - * @property {ArgumentConfig[]} configs - */ + /** + * @returns {void} + */ + invalidateBuild() { + // should be overridden to support this feature + } -/** - * @param {any=} schema a json schema to create arguments for (by default webpack schema is used) - * @returns {Record} object of arguments - */ -const getArguments = (schema = webpackSchema) => { - /** @type {Record} */ - const flags = {}; + /* istanbul ignore next */ + /** + * @abstract + * @returns {string} a unique identifier of the module + */ + identifier() { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); + } - const pathToArgumentName = input => { - return input - .replace(/\./g, "-") - .replace(/\[\]/g, "") - .replace( - /(\p{Uppercase_Letter}+|\p{Lowercase_Letter}|\d)(\p{Uppercase_Letter}+)/gu, - "$1-$2" - ) - .replace(/-?[^\p{Uppercase_Letter}\p{Lowercase_Letter}\d]+/gu, "-") - .toLowerCase(); - }; + /* istanbul ignore next */ + /** + * @abstract + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); + } - const getSchemaPart = path => { - const newPath = path.split("/"); + /* istanbul ignore next */ + /** + * @abstract + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {function(WebpackError=): void} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); + } - let schemaPart = schema; + /** + * @abstract + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + // Better override this method to return the correct types + if (this.source === Module.prototype.source) { + return DEFAULT_TYPES_UNKNOWN; + } else { + return DEFAULT_TYPES_JS; + } + } - for (let i = 1; i < newPath.length; i++) { - const inner = schemaPart[newPath[i]]; + /** + * @abstract + * @deprecated Use codeGeneration() instead + * @param {DependencyTemplates} dependencyTemplates the dependency templates + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {string=} type the type of source that should be generated + * @returns {Source} generated source + */ + source(dependencyTemplates, runtimeTemplate, type = "javascript") { + if (this.codeGeneration === Module.prototype.codeGeneration) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); + } + const chunkGraph = ChunkGraph.getChunkGraphForModule( + this, + "Module.source() is deprecated. Use Compilation.codeGenerationResults.getSource(module, runtime, type) instead", + "DEP_WEBPACK_MODULE_SOURCE" + ); + /** @type {CodeGenerationContext} */ + const codeGenContext = { + dependencyTemplates, + runtimeTemplate, + moduleGraph: chunkGraph.moduleGraph, + chunkGraph, + runtime: undefined, + codeGenerationResults: undefined + }; + const sources = this.codeGeneration(codeGenContext).sources; + return type ? sources.get(type) : sources.get(first(this.getSourceTypes())); + } - if (!inner) { - break; - } + /* istanbul ignore next */ + /** + * @abstract + * @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) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); + } - schemaPart = inner; - } + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return null; + } - return schemaPart; - }; + /** + * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + */ + nameForCondition() { + return null; + } /** - * - * @param {PathItem[]} path path in the schema - * @returns {string | undefined} description + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated */ - const getDescription = path => { - for (const { schema } of path) { - if (schema.cli) { - if (schema.cli.helper) continue; - if (schema.cli.description) return schema.cli.description; - } - if (schema.description) return schema.description; - } - }; + getConcatenationBailoutReason(context) { + return `Module Concatenation is not implemented for ${this.constructor.name}`; + } /** - * - * @param {PathItem[]} path path in the schema - * @returns {string | undefined} negative description + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only */ - const getNegatedDescription = path => { - for (const { schema } of path) { - if (schema.cli) { - if (schema.cli.helper) continue; - if (schema.cli.negatedDescription) return schema.cli.negatedDescription; - } - } - }; + getSideEffectsConnectionState(moduleGraph) { + return true; + } /** - * - * @param {PathItem[]} path path in the schema - * @returns {string | undefined} reset description + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - const getResetDescription = path => { - for (const { schema } of path) { - if (schema.cli) { - if (schema.cli.helper) continue; - if (schema.cli.resetDescription) return schema.cli.resetDescription; + codeGeneration(context) { + // Best override this method + const sources = new Map(); + for (const type of this.getSourceTypes()) { + if (type !== "unknown") { + sources.set( + type, + this.source( + context.dependencyTemplates, + context.runtimeTemplate, + type + ) + ); } } - }; + return { + sources, + runtimeRequirements: new Set([ + RuntimeGlobals.module, + RuntimeGlobals.exports, + RuntimeGlobals.require + ]) + }; + } /** - * - * @param {any} schemaPart schema - * @returns {Pick} partial argument config + * @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 */ - const schemaToArgumentConfig = schemaPart => { - if (schemaPart.enum) { - return { - type: "enum", - values: schemaPart.enum - }; - } - switch (schemaPart.type) { - case "number": - return { - type: "number" - }; - case "string": - return { - type: schemaPart.absolutePath ? "path" : "string" - }; - case "boolean": - return { - type: "boolean" - }; - } - if (schemaPart.instanceof === "RegExp") { - return { - type: "RegExp" - }; - } - return undefined; - }; + chunkCondition(chunk, compilation) { + return true; + } + + hasChunkCondition() { + return this.chunkCondition !== Module.prototype.chunkCondition; + } /** - * @param {PathItem[]} path path in the schema + * 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} */ - const addResetFlag = path => { - const schemaPath = path[0].path; - const name = pathToArgumentName(`${schemaPath}.reset`); - const description = - getResetDescription(path) || - `Clear all items provided in '${schemaPath}' configuration. ${getDescription( - path - )}`; - flags[name] = { - configs: [ - { - type: "reset", - multiple: false, - description, - path: schemaPath - } - ], - description: undefined, - simpleType: undefined, - multiple: undefined - }; - }; + updateCacheModule(module) { + this.type = module.type; + this.layer = module.layer; + this.context = module.context; + this.factoryMeta = module.factoryMeta; + this.resolveOptions = module.resolveOptions; + } /** - * @param {PathItem[]} path full path in schema - * @param {boolean} multiple inside of an array - * @returns {number} number of arguments added + * Module should be unsafe cached. Get data that's needed for that. + * This data will be passed to restoreFromUnsafeCache later. + * @returns {object} cached data */ - const addFlag = (path, multiple) => { - const argConfigBase = schemaToArgumentConfig(path[0].schema); - if (!argConfigBase) return 0; - - const negatedDescription = getNegatedDescription(path); - const name = pathToArgumentName(path[0].path); - /** @type {ArgumentConfig} */ - const argConfig = { - ...argConfigBase, - multiple, - description: getDescription(path), - path: path[0].path + getUnsafeCacheData() { + return { + factoryMeta: this.factoryMeta, + resolveOptions: this.resolveOptions }; + } - if (negatedDescription) { - argConfig.negatedDescription = negatedDescription; - } - - if (!flags[name]) { - flags[name] = { - configs: [], - description: undefined, - simpleType: undefined, - multiple: undefined - }; - } - - if ( - flags[name].configs.some( - item => JSON.stringify(item) === JSON.stringify(argConfig) - ) - ) { - return 0; - } - - if ( - flags[name].configs.some( - item => item.type === argConfig.type && item.multiple !== multiple - ) - ) { - if (multiple) { - throw new Error( - `Conflicting schema for ${path[0].path} with ${argConfig.type} type (array type must be before single item type)` - ); - } - return 0; - } + /** + * restore unsafe cache data + * @param {object} unsafeCacheData data from getUnsafeCacheData + * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching + */ + _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { + this.factoryMeta = unsafeCacheData.factoryMeta; + this.resolveOptions = unsafeCacheData.resolveOptions; + } - flags[name].configs.push(argConfig); + /** + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. + */ + cleanupForCache() { + this.factoryMeta = undefined; + this.resolveOptions = undefined; + } - return 1; - }; + /** + * @returns {Source | null} the original source for the module before webpack transformation + */ + originalSource() { + return null; + } - // TODO support `not` and `if/then/else` - // TODO support `const`, but we don't use it on our schema /** - * - * @param {object} schemaPart the current schema - * @param {string} schemaPath the current path in the schema - * @param {{schema: object, path: string}[]} path all previous visited schemaParts - * @param {string | null} inArray if inside of an array, the path to the array - * @returns {number} added arguments + * @param {LazySet} fileDependencies set where file dependencies are added to + * @param {LazySet} contextDependencies set where context dependencies are added to + * @param {LazySet} missingDependencies set where missing dependencies are added to + * @param {LazySet} buildDependencies set where build dependencies are added to */ - const traverse = (schemaPart, schemaPath = "", path = [], inArray = null) => { - while (schemaPart.$ref) { - schemaPart = getSchemaPart(schemaPart.$ref); - } + addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ) {} - const repetitions = path.filter(({ schema }) => schema === schemaPart); - if ( - repetitions.length >= 2 || - repetitions.some(({ path }) => path === schemaPath) - ) { - return 0; - } + serialize(context) { + const { write } = context; + write(this.type); + write(this.layer); + write(this.context); + write(this.resolveOptions); + write(this.factoryMeta); + write(this.useSourceMap); + write(this.useSimpleSourceMap); + write( + this._warnings !== undefined && this._warnings.length === 0 + ? undefined + : this._warnings + ); + write( + this._errors !== undefined && this._errors.length === 0 + ? undefined + : this._errors + ); + write(this.buildMeta); + write(this.buildInfo); + write(this.presentationalDependencies); + write(this.codeGenerationDependencies); + super.serialize(context); + } - if (schemaPart.cli && schemaPart.cli.exclude) return 0; + deserialize(context) { + const { read } = context; + this.type = read(); + this.layer = read(); + this.context = read(); + this.resolveOptions = read(); + this.factoryMeta = read(); + this.useSourceMap = read(); + this.useSimpleSourceMap = read(); + this._warnings = read(); + this._errors = read(); + this.buildMeta = read(); + this.buildInfo = read(); + this.presentationalDependencies = read(); + this.codeGenerationDependencies = read(); + super.deserialize(context); + } +} - const fullPath = [{ schema: schemaPart, path: schemaPath }, ...path]; +makeSerializable(Module, "webpack/lib/Module"); - let addedArguments = 0; +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "hasEqualsChunks", { + get() { + throw new Error( + "Module.hasEqualsChunks was renamed (use hasEqualChunks instead)" + ); + } +}); - addedArguments += addFlag(fullPath, !!inArray); +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "isUsed", { + get() { + throw new Error( + "Module.isUsed was renamed (use getUsedName, isExportUsed or isModuleUsed instead)" + ); + } +}); - if (schemaPart.type === "object") { - if (schemaPart.properties) { - for (const property of Object.keys(schemaPart.properties)) { - addedArguments += traverse( - schemaPart.properties[property], - schemaPath ? `${schemaPath}.${property}` : property, - fullPath, - inArray - ); - } +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "errors", { + get: util.deprecate( + /** + * @this {Module} + * @returns {WebpackError[]} array + */ + function () { + if (this._errors === undefined) { + this._errors = []; } + return this._errors; + }, + "Module.errors was removed (use getErrors instead)", + "DEP_WEBPACK_MODULE_ERRORS" + ) +}); - return addedArguments; - } - - if (schemaPart.type === "array") { - if (inArray) { - return 0; +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "warnings", { + get: util.deprecate( + /** + * @this {Module} + * @returns {WebpackError[]} array + */ + function () { + if (this._warnings === undefined) { + this._warnings = []; } - if (Array.isArray(schemaPart.items)) { - let i = 0; - for (const item of schemaPart.items) { - addedArguments += traverse( - item, - `${schemaPath}.${i}`, - fullPath, - schemaPath - ); - } + return this._warnings; + }, + "Module.warnings was removed (use getWarnings instead)", + "DEP_WEBPACK_MODULE_WARNINGS" + ) +}); - return addedArguments; - } +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "used", { + get() { + throw new Error( + "Module.used was refactored (use ModuleGraph.getUsedExports instead)" + ); + }, + set(value) { + throw new Error( + "Module.used was refactored (use ModuleGraph.setUsedExports instead)" + ); + } +}); - addedArguments += traverse( - schemaPart.items, - `${schemaPath}[]`, - fullPath, - schemaPath - ); +module.exports = Module; - if (addedArguments > 0) { - addResetFlag(fullPath); - addedArguments++; - } - return addedArguments; - } +/***/ }), - const maybeOf = schemaPart.oneOf || schemaPart.anyOf || schemaPart.allOf; +/***/ 21305: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (maybeOf) { - const items = maybeOf; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - for (let i = 0; i < items.length; i++) { - addedArguments += traverse(items[i], schemaPath, fullPath, inArray); - } - return addedArguments; - } - return addedArguments; - }; +const { cutOffLoaderExecution } = __webpack_require__(59985); +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); - traverse(schema); +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; - // Summarize flags - for (const name of Object.keys(flags)) { - const argument = flags[name]; - argument.description = argument.configs.reduce((desc, { description }) => { - if (!desc) return description; - if (!description) return desc; - if (desc.includes(description)) return desc; - return `${desc} ${description}`; - }, /** @type {string | undefined} */ (undefined)); - argument.simpleType = argument.configs.reduce((t, argConfig) => { - /** @type {"string" | "number" | "boolean"} */ - let type = "string"; - switch (argConfig.type) { - case "number": - type = "number"; - break; - case "reset": - case "boolean": - type = "boolean"; - break; - case "enum": - if (argConfig.values.every(v => typeof v === "boolean")) - type = "boolean"; - if (argConfig.values.every(v => typeof v === "number")) - type = "number"; - break; - } - if (t === undefined) return type; - return t === type ? t : "string"; - }, /** @type {"string" | "number" | "boolean" | undefined} */ (undefined)); - argument.multiple = argument.configs.some(c => c.multiple); - } + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } - return flags; -}; + if (err !== null && typeof err === "object") { + if (typeof err.stack === "string" && err.stack) { + const stack = cutOffLoaderExecution(err.stack); -const cliAddedItems = new WeakMap(); + if (!err.hideStack) { + message += stack; + } else { + details = stack; -/** - * @param {any} config configuration - * @param {string} schemaPath path in the config - * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined - * @returns {{ problem?: LocalProblem, object?: any, property?: string | number, value?: any }} problem or object with property and value - */ -const getObjectAndProperty = (config, schemaPath, index = 0) => { - if (!schemaPath) return { value: config }; - const parts = schemaPath.split("."); - let property = parts.pop(); - let current = config; - let i = 0; - for (const part of parts) { - const isArray = part.endsWith("[]"); - const name = isArray ? part.slice(0, -2) : part; - let value = current[name]; - if (isArray) { - if (value === undefined) { - value = {}; - current[name] = [...Array.from({ length: index }), value]; - cliAddedItems.set(current[name], index + 1); - } else if (!Array.isArray(value)) { - return { - problem: { - type: "unexpected-non-array-in-path", - path: parts.slice(0, i).join(".") + if (typeof err.message === "string" && err.message) { + message += err.message; + } else { + message += err; } - }; - } else { - let addedItems = cliAddedItems.get(value) || 0; - while (addedItems <= index) { - value.push(undefined); - addedItems++; - } - cliAddedItems.set(value, addedItems); - const x = value.length - addedItems + index; - if (value[x] === undefined) { - value[x] = {}; - } else if (value[x] === null || typeof value[x] !== "object") { - return { - problem: { - type: "unexpected-non-object-in-path", - path: parts.slice(0, i).join(".") - } - }; } - value = value[x]; - } - } else { - if (value === undefined) { - value = current[name] = {}; - } else if (value === null || typeof value !== "object") { - return { - problem: { - type: "unexpected-non-object-in-path", - path: parts.slice(0, i).join(".") - } - }; + } else if (typeof err.message === "string" && err.message) { + message += err.message; + } else { + message += String(err); } - } - current = value; - i++; - } - let value = current[property]; - if (property.endsWith("[]")) { - const name = property.slice(0, -2); - const value = current[name]; - if (value === undefined) { - current[name] = [...Array.from({ length: index }), undefined]; - cliAddedItems.set(current[name], index + 1); - return { object: current[name], property: index, value: undefined }; - } else if (!Array.isArray(value)) { - current[name] = [value, ...Array.from({ length: index }), undefined]; - cliAddedItems.set(current[name], index + 1); - return { object: current[name], property: index + 1, value: undefined }; } else { - let addedItems = cliAddedItems.get(value) || 0; - while (addedItems <= index) { - value.push(undefined); - addedItems++; - } - cliAddedItems.set(value, addedItems); - const x = value.length - addedItems + index; - if (value[x] === undefined) { - value[x] = {}; - } else if (value[x] === null || typeof value[x] !== "object") { - return { - problem: { - type: "unexpected-non-object-in-path", - path: schemaPath - } - }; - } - return { - object: value, - property: x, - value: value[x] - }; + message += String(err); } - } - return { object: current, property, value }; -}; -/** - * @param {any} config configuration - * @param {string} schemaPath path in the config - * @param {any} value parsed value - * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined - * @returns {LocalProblem | null} problem or null for success - */ -const setValue = (config, schemaPath, value, index) => { - const { problem, object, property } = getObjectAndProperty( - config, - schemaPath, - index - ); - if (problem) return problem; - object[property] = value; - return null; -}; + super(message); -/** - * @param {ArgumentConfig} argConfig processing instructions - * @param {any} config configuration - * @param {any} value the value - * @param {number | undefined} index the index if multiple values provided - * @returns {LocalProblem | null} a problem if any - */ -const processArgumentConfig = (argConfig, config, value, index) => { - if (index !== undefined && !argConfig.multiple) { - return { - type: "multiple-values-unexpected", - path: argConfig.path - }; - } - const parsed = parseValueForArgumentConfig(argConfig, value); - if (parsed === undefined) { - return { - type: "invalid-value", - path: argConfig.path, - expected: getExpectedValue(argConfig) - }; + this.name = "ModuleBuildError"; + this.details = details; + this.error = err; } - const problem = setValue(config, argConfig.path, parsed, index); - if (problem) return problem; - return null; -}; -/** - * @param {ArgumentConfig} argConfig processing instructions - * @returns {string | undefined} expected message - */ -const getExpectedValue = argConfig => { - switch (argConfig.type) { - default: - return argConfig.type; - case "boolean": - return "true | false"; - case "RegExp": - return "regular expression (example: /ab?c*/)"; - case "enum": - return argConfig.values.map(v => `${v}`).join(" | "); - case "reset": - return "true (will reset the previous value to an empty array)"; - } -}; + serialize(context) { + const { write } = context; -/** - * @param {ArgumentConfig} argConfig processing instructions - * @param {any} value the value - * @returns {any | undefined} parsed value - */ -const parseValueForArgumentConfig = (argConfig, value) => { - switch (argConfig.type) { - case "string": - if (typeof value === "string") { - return value; - } - break; - case "path": - if (typeof value === "string") { - return path.resolve(value); - } - break; - case "number": - if (typeof value === "number") return value; - if (typeof value === "string" && /^[+-]?\d*(\.\d*)[eE]\d+$/) { - const n = +value; - if (!isNaN(n)) return n; - } - break; - case "boolean": - if (typeof value === "boolean") return value; - if (value === "true") return true; - if (value === "false") return false; - break; - case "RegExp": - if (value instanceof RegExp) return value; - if (typeof value === "string") { - // cspell:word yugi - const match = /^\/(.*)\/([yugi]*)$/.exec(value); - if (match && !/[^\\]\//.test(match[1])) - return new RegExp(match[1], match[2]); - } - break; - case "enum": - if (argConfig.values.includes(value)) return value; - for (const item of argConfig.values) { - if (`${item}` === value) return item; - } - break; - case "reset": - if (value === true) return []; - break; + write(this.error); + + super.serialize(context); } -}; -/** - * @param {Record} args object of arguments - * @param {any} config configuration - * @param {Record} values object with values - * @returns {Problem[] | null} problems or null for success - */ -const processArguments = (args, config, values) => { - /** @type {Problem[]} */ - const problems = []; - for (const key of Object.keys(values)) { - const arg = args[key]; - if (!arg) { - problems.push({ - type: "unknown-argument", - path: "", - argument: key - }); - continue; - } - const processValue = (value, i) => { - const currentProblems = []; - for (const argConfig of arg.configs) { - const problem = processArgumentConfig(argConfig, config, value, i); - if (!problem) { - return; - } - currentProblems.push({ - ...problem, - argument: key, - value: value, - index: i - }); - } - problems.push(...currentProblems); - }; - let value = values[key]; - if (Array.isArray(value)) { - for (let i = 0; i < value.length; i++) { - processValue(value[i], i); - } - } else { - processValue(value, undefined); - } + deserialize(context) { + const { read } = context; + + this.error = read(); + + super.deserialize(context); } - if (problems.length === 0) return null; - return problems; -}; +} -exports.getArguments = getArguments; -exports.processArguments = processArguments; +makeSerializable(ModuleBuildError, "webpack/lib/ModuleBuildError"); + +module.exports = ModuleBuildError; /***/ }), -/***/ 43950: +/***/ 67409: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov + Author Tobias Koppers @sokra */ -const browserslist = __webpack_require__(14907); -const path = __webpack_require__(71017); +const WebpackError = __webpack_require__(53799); -/** @typedef {import("./target").ApiTargetProperties} ApiTargetProperties */ -/** @typedef {import("./target").EcmaTargetProperties} EcmaTargetProperties */ -/** @typedef {import("./target").PlatformTargetProperties} PlatformTargetProperties */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ -// [[C:]/path/to/config][:env] -const inputRx = /^(?:((?:[A-Z]:)?[/\\].*?))?(?::(.+?))?$/i; +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); -/** - * @typedef {Object} BrowserslistHandlerConfig - * @property {string=} configPath - * @property {string=} env - * @property {string=} query - */ + 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; -/** - * @param {string} input input string - * @param {string} context the context directory - * @returns {BrowserslistHandlerConfig} config - */ -const parse = (input, context) => { - if (!input) { - return {}; + if (err && /** @type {any} */ (err).hideStack) { + this.stack = + err.stack.split("\n").slice(1).join("\n") + "\n\n" + this.stack; + } } +} - if (path.isAbsolute(input)) { - const [, configPath, env] = inputRx.exec(input) || []; - return { configPath, env }; - } +module.exports = ModuleDependencyError; - const config = browserslist.findConfig(context); - if (config && Object.keys(config).includes(input)) { - return { env: input }; - } +/***/ }), - return { query: input }; -}; +/***/ 29656: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * @param {string} input input string - * @param {string} context the context directory - * @returns {string[] | undefined} selected browsers - */ -const load = (input, context) => { - const { configPath, env, query } = parse(input, context); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // if a query is specified, then use it, else - // if a path to a config is specified then load it, else - // find a nearest config - const config = query - ? query - : configPath - ? browserslist.loadConfig({ - config: configPath, - env - }) - : browserslist.loadConfig({ path: context, env }); - if (!config) return null; - return browserslist(config); -}; -/** - * @param {string[]} browsers supported browsers list - * @returns {EcmaTargetProperties & PlatformTargetProperties & ApiTargetProperties} target properties - */ -const resolve = browsers => { +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ + +class ModuleDependencyWarning extends WebpackError { /** - * Checks all against a version number - * @param {Record} versions first supported version - * @returns {boolean} true if supports + * @param {Module} module module tied to dependency + * @param {Error} err error thrown + * @param {DependencyLocation} loc location of dependency */ - const rawChecker = versions => { - return browsers.every(v => { - const [name, parsedVersion] = v.split(" "); - if (!name) return false; - const requiredVersion = versions[name]; - if (!requiredVersion) return false; - const [parsedMajor, parserMinor] = - // safari TP supports all features for normal safari - parsedVersion === "TP" - ? [Infinity, Infinity] - : parsedVersion.split("."); - if (typeof requiredVersion === "number") { - return +parsedMajor >= requiredVersion; - } - return requiredVersion[0] === +parsedMajor - ? +parserMinor >= requiredVersion[1] - : +parsedMajor > requiredVersion[0]; - }); - }; - const anyNode = browsers.some(b => /^node /.test(b)); - const anyBrowser = browsers.some(b => /^(?!node)/.test(b)); - const browserProperty = !anyBrowser ? false : anyNode ? null : true; - const nodeProperty = !anyNode ? false : anyBrowser ? null : true; - // Internet Explorer Mobile, Blackberry browser and Opera Mini are very old browsers, they do not support new features - const es6DynamicImport = rawChecker({ - chrome: 63, - and_chr: 63, - edge: 79, - firefox: 67, - and_ff: 67, - // ie: Not supported - opera: 50, - op_mob: 46, - safari: [11, 1], - ios_saf: [11, 3], - samsung: [8, 2], - android: 63, - and_qq: [10, 4], - // baidu: Not supported - // and_uc: Not supported - // kaios: Not supported - // Since Node.js 13.14.0 no warning about usage, but it was added 8.5.0 with some limitations and it was improved in 12.0.0 and 13.2.0 - node: [13, 14] - }); + constructor(module, err, loc) { + super(err ? err.message : ""); - return { - const: rawChecker({ - chrome: 49, - and_chr: 49, - edge: 12, - // Prior to Firefox 13, const is implemented, but re-assignment is not failing. - // Prior to Firefox 46, a TypeError was thrown on redeclaration instead of a SyntaxError. - firefox: 36, - and_ff: 36, - // Not supported in for-in and for-of loops - // ie: Not supported - opera: 36, - op_mob: 36, - safari: [10, 0], - ios_saf: [10, 0], - // Before 5.0 supported correctly in strict mode, otherwise supported without block scope - samsung: [5, 0], - android: 37, - and_qq: [10, 4], - // Supported correctly in strict mode, otherwise supported without block scope - // baidu: Not supported - and_uc: [12, 12], - kaios: [2, 5], - node: [6, 0] - }), - arrowFunction: rawChecker({ - chrome: 45, - and_chr: 45, - edge: 12, - // The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of 'use strict'; is now required. - // Prior to Firefox 39, a line terminator (\\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \\n => {} will now throw a SyntaxError in this and later versions. - firefox: 39, - and_ff: 39, - // ie: Not supported, - opera: 32, - op_mob: 32, - safari: 10, - ios_saf: 10, - samsung: [5, 0], - android: 45, - and_qq: [10, 4], - baidu: [7, 12], - and_uc: [12, 12], - kaios: [2, 5], - node: [6, 0] - }), - forOf: rawChecker({ - chrome: 38, - and_chr: 38, - edge: 12, - // Prior to Firefox 51, using the for...of loop construct with the const keyword threw a SyntaxError ("missing = in const declaration"). - firefox: 51, - and_ff: 51, - // ie: Not supported, - opera: 25, - op_mob: 25, - safari: 7, - ios_saf: 7, - samsung: [3, 0], - android: 38, - // and_qq: Unknown support - // baidu: Unknown support - // and_uc: Unknown support - // kaios: Unknown support - node: [0, 12] - }), - destructuring: rawChecker({ - chrome: 49, - and_chr: 49, - edge: 14, - firefox: 41, - and_ff: 41, - // ie: Not supported, - opera: 36, - op_mob: 36, - safari: 8, - ios_saf: 8, - samsung: [5, 0], - android: 49, - // and_qq: Unknown support - // baidu: Unknown support - // and_uc: Unknown support - // kaios: Unknown support - node: [6, 0] - }), - bigIntLiteral: rawChecker({ - chrome: 67, - and_chr: 67, - edge: 79, - firefox: 68, - and_ff: 68, - // ie: Not supported, - opera: 54, - op_mob: 48, - safari: 14, - ios_saf: 14, - samsung: [9, 2], - android: 67, - // and_qq: Not supported - // baidu: Not supported - // and_uc: Not supported - // kaios: Not supported - node: [10, 4] - }), - // Support syntax `import` and `export` and no limitations and bugs on Node.js - // Not include `export * as namespace` - module: rawChecker({ - chrome: 61, - and_chr: 61, - edge: 16, - firefox: 60, - and_ff: 60, - // ie: Not supported, - opera: 48, - op_mob: 45, - safari: [10, 1], - ios_saf: [10, 3], - samsung: [8, 0], - android: 61, - and_qq: [10, 4], - // baidu: Not supported - // and_uc: Not supported - // kaios: Not supported - // Since Node.js 13.14.0 no warning about usage, but it was added 8.5.0 with some limitations and it was improved in 12.0.0 and 13.2.0 - node: [13, 14] - }), - dynamicImport: es6DynamicImport, - dynamicImportInWorker: es6DynamicImport && !anyNode, - // browserslist does not have info about globalThis - // so this is based on mdn-browser-compat-data - globalThis: rawChecker({ - chrome: 71, - and_chr: 71, - edge: 79, - firefox: 65, - and_ff: 65, - // ie: Not supported, - opera: 58, - op_mob: 50, - safari: [12, 1], - ios_saf: [12, 2], - samsung: [10, 1], - android: 71, - // and_qq: Unknown support - // baidu: Unknown support - // and_uc: Unknown support - // kaios: Unknown support - node: [12, 0] - }), - optionalChaining: rawChecker({ - chrome: 80, - and_chr: 80, - edge: 80, - firefox: 74, - and_ff: 79, - // ie: Not supported, - opera: 67, - op_mob: 64, - safari: [13, 1], - ios_saf: [13, 4], - samsung: 13, - android: 80, - // and_qq: Not supported - // baidu: Not supported - // and_uc: Not supported - // kaios: Not supported - node: 14 - }), - templateLiteral: rawChecker({ - chrome: 41, - and_chr: 41, - edge: 13, - firefox: 34, - and_ff: 34, - // ie: Not supported, - opera: 29, - op_mob: 64, - safari: [9, 1], - ios_saf: 9, - samsung: 4, - android: 41, - and_qq: [10, 4], - baidu: [7, 12], - and_uc: [12, 12], - kaios: [2, 5], - node: 4 - }), - browser: browserProperty, - electron: false, - node: nodeProperty, - nwjs: false, - web: browserProperty, - webworker: false, + 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; - document: browserProperty, - fetchWasm: browserProperty, - global: nodeProperty, - importScripts: false, - importScriptsInWorker: true, - nodeBuiltins: nodeProperty, - require: nodeProperty - }; -}; + if (err && /** @type {any} */ (err).hideStack) { + this.stack = + err.stack.split("\n").slice(1).join("\n") + "\n\n" + this.stack; + } + } +} -module.exports = { - resolve, - load -}; +makeSerializable( + ModuleDependencyWarning, + "webpack/lib/ModuleDependencyWarning" +); + +module.exports = ModuleDependencyWarning; /***/ }), -/***/ 92988: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 23744: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -64014,1307 +57681,1273 @@ module.exports = { -const fs = __webpack_require__(57147); -const path = __webpack_require__(71017); -const Template = __webpack_require__(1626); -const { cleverMerge } = __webpack_require__(60839); -const { - getTargetsProperties, - getTargetProperties, - getDefaultTarget -} = __webpack_require__(52801); +const { cleanUp } = __webpack_require__(59985); +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("../../declarations/WebpackOptions").CacheOptionsNormalized} CacheOptions */ -/** @typedef {import("../../declarations/WebpackOptions").CssExperimentOptions} CssExperimentOptions */ -/** @typedef {import("../../declarations/WebpackOptions").EntryDescription} EntryDescription */ -/** @typedef {import("../../declarations/WebpackOptions").EntryNormalized} Entry */ -/** @typedef {import("../../declarations/WebpackOptions").Experiments} Experiments */ -/** @typedef {import("../../declarations/WebpackOptions").ExperimentsNormalized} ExperimentsNormalized */ -/** @typedef {import("../../declarations/WebpackOptions").ExternalsPresets} ExternalsPresets */ -/** @typedef {import("../../declarations/WebpackOptions").ExternalsType} ExternalsType */ -/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */ -/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ -/** @typedef {import("../../declarations/WebpackOptions").Library} Library */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").Loader} Loader */ -/** @typedef {import("../../declarations/WebpackOptions").Mode} Mode */ -/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ -/** @typedef {import("../../declarations/WebpackOptions").Node} WebpackNode */ -/** @typedef {import("../../declarations/WebpackOptions").Optimization} Optimization */ -/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */ -/** @typedef {import("../../declarations/WebpackOptions").Performance} Performance */ -/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ -/** @typedef {import("../../declarations/WebpackOptions").RuleSetRules} RuleSetRules */ -/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */ -/** @typedef {import("../../declarations/WebpackOptions").Target} Target */ -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("./target").TargetProperties} TargetProperties */ +class ModuleError extends WebpackError { + /** + * @param {Error} err error thrown + * @param {{from?: string|null}} info additional info + */ + constructor(err, { from = null } = {}) { + let message = "Module Error"; -const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i; + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } -/** - * Sets a constant default value when undefined - * @template T - * @template {keyof T} P - * @param {T} obj an object - * @param {P} prop a property of this object - * @param {T[P]} value a default value of the property - * @returns {void} - */ -const D = (obj, prop, value) => { - if (obj[prop] === undefined) { - obj[prop] = value; + 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; } -}; -/** - * Sets a dynamic default value when undefined, by calling the factory function - * @template T - * @template {keyof T} P - * @param {T} obj an object - * @param {P} prop a property of this object - * @param {function(): T[P]} factory a default value factory for the property - * @returns {void} - */ -const F = (obj, prop, factory) => { - if (obj[prop] === undefined) { - obj[prop] = factory(); + serialize(context) { + const { write } = context; + + write(this.error); + + super.serialize(context); } -}; -/** - * Sets a dynamic default value when undefined, by calling the factory function. - * factory must return an array or undefined - * When the current value is already an array an contains "..." it's replaced with - * the result of the factory function - * @template T - * @template {keyof T} P - * @param {T} obj an object - * @param {P} prop a property of this object - * @param {function(): T[P]} factory a default value factory for the property - * @returns {void} - */ -const A = (obj, prop, factory) => { - const value = obj[prop]; - if (value === undefined) { - obj[prop] = factory(); - } else if (Array.isArray(value)) { - /** @type {any[]} */ - let newArray = undefined; - for (let i = 0; i < value.length; i++) { - const item = value[i]; - if (item === "...") { - if (newArray === undefined) { - newArray = value.slice(0, i); - obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray)); - } - const items = /** @type {any[]} */ (/** @type {unknown} */ (factory())); - if (items !== undefined) { - for (const item of items) { - newArray.push(item); - } - } - } else if (newArray !== undefined) { - newArray.push(item); - } - } + deserialize(context) { + const { read } = context; + + this.error = read(); + + super.deserialize(context); } -}; +} + +makeSerializable(ModuleError, "webpack/lib/ModuleError"); + +module.exports = ModuleError; + + +/***/ }), + +/***/ 51010: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Module")} Module */ /** - * @param {WebpackOptions} options options to be modified - * @returns {void} + * @typedef {Object} ModuleFactoryResult + * @property {Module=} module the created module or unset if no module was created + * @property {Set=} fileDependencies + * @property {Set=} contextDependencies + * @property {Set=} missingDependencies + * @property {boolean=} cacheable allow to use the unsafe cache */ -const applyWebpackOptionsBaseDefaults = options => { - F(options, "context", () => process.cwd()); - applyInfrastructureLoggingDefaults(options.infrastructureLogging); -}; /** - * @param {WebpackOptions} options options to be modified - * @returns {void} + * @typedef {Object} ModuleFactoryCreateDataContextInfo + * @property {string} issuer + * @property {string | null=} issuerLayer + * @property {string} compiler */ -const applyWebpackOptionsDefaults = options => { - F(options, "context", () => process.cwd()); - F(options, "target", () => { - return getDefaultTarget(options.context); - }); - - const { mode, name, target } = options; - - let targetProperties = - target === false - ? /** @type {false} */ (false) - : typeof target === "string" - ? getTargetProperties(target, options.context) - : getTargetsProperties(target, options.context); - const development = mode === "development"; - const production = mode === "production" || !mode; +/** + * @typedef {Object} ModuleFactoryCreateData + * @property {ModuleFactoryCreateDataContextInfo} contextInfo + * @property {ResolveOptions=} resolveOptions + * @property {string} context + * @property {Dependency[]} dependencies + */ - if (typeof options.entry !== "function") { - for (const key of Object.keys(options.entry)) { - F( - options.entry[key], - "import", - () => /** @type {[string]} */ (["./src"]) - ); - } +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 = __webpack_require__(77198); + throw new AbstractMethodError(); } +} - F(options, "devtool", () => (development ? "eval" : false)); - D(options, "watch", false); - D(options, "profile", false); - D(options, "parallelism", 100); - D(options, "recordsInputPath", false); - D(options, "recordsOutputPath", false); +module.exports = ModuleFactory; - applyExperimentsDefaults(options.experiments, { - production, - development, - targetProperties - }); - const futureDefaults = options.experiments.futureDefaults; +/***/ }), - F(options, "cache", () => - development ? { type: /** @type {"memory"} */ ("memory") } : false - ); - applyCacheDefaults(options.cache, { - name: name || "default", - mode: mode || "production", - development, - cacheUnaffected: options.experiments.cacheUnaffected - }); - const cache = !!options.cache; +/***/ 88821: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - applySnapshotDefaults(options.snapshot, { - production, - futureDefaults - }); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - applyModuleDefaults(options.module, { - cache, - syncWebAssembly: options.experiments.syncWebAssembly, - asyncWebAssembly: options.experiments.asyncWebAssembly, - css: options.experiments.css, - futureDefaults - }); - applyOutputDefaults(options.output, { - context: options.context, - targetProperties, - isAffectedByBrowserslist: - target === undefined || - (typeof target === "string" && target.startsWith("browserslist")) || - (Array.isArray(target) && - target.some(target => target.startsWith("browserslist"))), - outputModule: options.experiments.outputModule, - development, - entry: options.entry, - module: options.module, - futureDefaults - }); - applyExternalsPresetsDefaults(options.externalsPresets, { - targetProperties, - buildHttp: !!options.experiments.buildHttp - }); +const NormalModule = __webpack_require__(39); +const createHash = __webpack_require__(49835); +const memoize = __webpack_require__(78676); - applyLoaderDefaults(options.loader, { targetProperties }); +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {typeof import("./util/Hash")} Hash */ - F(options, "externalsType", () => { - const validExternalTypes = (__webpack_require__(73342).definitions.ExternalsType["enum"]); - return options.output.library && - validExternalTypes.includes(options.output.library.type) - ? /** @type {ExternalsType} */ (options.output.library.type) - : options.output.module - ? "module" - : "var"; - }); +const ModuleFilenameHelpers = exports; - applyNodeDefaults(options.node, { - futureDefaults: options.experiments.futureDefaults, - targetProperties - }); +// 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; - F(options, "performance", () => - production && - targetProperties && - (targetProperties.browser || targetProperties.browser === null) - ? {} - : false - ); - applyPerformanceDefaults(options.performance, { - production - }); +const getAfter = (strFn, token) => { + return () => { + const str = strFn(); + const idx = str.indexOf(token); + return idx < 0 ? "" : str.substr(idx); + }; +}; - applyOptimizationDefaults(options.optimization, { - development, - production, - css: options.experiments.css, - records: !!(options.recordsInputPath || options.recordsOutputPath) - }); +const getBefore = (strFn, token) => { + return () => { + const str = strFn(); + const idx = str.lastIndexOf(token); + return idx < 0 ? "" : str.substr(0, idx); + }; +}; - options.resolve = cleverMerge( - getResolveDefaults({ - cache, - context: options.context, - targetProperties, - mode: options.mode - }), - options.resolve - ); +const getHash = (strFn, hashFunction) => { + return () => { + const hash = createHash(hashFunction); + hash.update(strFn()); + const digest = /** @type {string} */ (hash.digest("hex")); + return digest.substr(0, 4); + }; +}; - options.resolveLoader = cleverMerge( - getResolveLoaderDefaults({ cache }), - options.resolveLoader - ); +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; + /** - * @param {ExperimentsNormalized} experiments options - * @param {Object} options options - * @param {boolean} options.production is production - * @param {boolean} options.development is development mode - * @param {TargetProperties | false} options.targetProperties target properties - * @returns {void} + * + * @param {Module | string} module the module + * @param {TODO} options options + * @param {Object} contextInfo context info + * @param {RequestShortener} contextInfo.requestShortener requestShortener + * @param {ChunkGraph} contextInfo.chunkGraph chunk graph + * @param {string | Hash} contextInfo.hashFunction the hash function to use + * @returns {string} the filename */ -const applyExperimentsDefaults = ( - experiments, - { production, development, targetProperties } +ModuleFilenameHelpers.createFilename = ( + module = "", + options, + { requestShortener, chunkGraph, hashFunction = "md4" } ) => { - D(experiments, "futureDefaults", false); - D(experiments, "backCompat", !experiments.futureDefaults); - D(experiments, "topLevelAwait", experiments.futureDefaults); - D(experiments, "syncWebAssembly", false); - D(experiments, "asyncWebAssembly", experiments.futureDefaults); - D(experiments, "outputModule", false); - D(experiments, "layers", false); - D(experiments, "lazyCompilation", undefined); - D(experiments, "buildHttp", undefined); - D(experiments, "cacheUnaffected", experiments.futureDefaults); - F(experiments, "css", () => (experiments.futureDefaults ? {} : undefined)); + const opts = { + namespace: "", + moduleFilenameTemplate: "", + ...(typeof options === "object" + ? options + : { + moduleFilenameTemplate: options + }) + }; - if (typeof experiments.buildHttp === "object") { - D(experiments.buildHttp, "frozen", production); - D(experiments.buildHttp, "upgrade", false); + let absoluteResourcePath; + let hash; + let identifier; + let moduleId; + let shortIdentifier; + if (typeof module === "string") { + shortIdentifier = memoize(() => requestShortener.shorten(module)); + identifier = shortIdentifier; + moduleId = () => ""; + absoluteResourcePath = () => module.split("!").pop(); + hash = getHash(identifier, hashFunction); + } else { + shortIdentifier = memoize(() => + module.readableIdentifier(requestShortener) + ); + identifier = memoize(() => requestShortener.shorten(module.identifier())); + moduleId = () => chunkGraph.getModuleId(module); + absoluteResourcePath = () => + module instanceof NormalModule + ? module.resource + : module.identifier().split("!").pop(); + hash = getHash(identifier, hashFunction); } + const resource = memoize(() => shortIdentifier().split("!").pop()); - if (typeof experiments.css === "object") { - D( - experiments.css, - "exportsOnly", - !targetProperties || !targetProperties.document + 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 + }) ); } -}; -/** - * @param {CacheOptions} cache options - * @param {Object} options options - * @param {string} options.name name - * @param {string} options.mode mode - * @param {boolean} options.development is development mode - * @param {boolean} options.cacheUnaffected the cacheUnaffected experiment is enabled - * @returns {void} - */ -const applyCacheDefaults = ( - cache, - { name, mode, development, cacheUnaffected } -) => { - if (cache === false) return; - switch (cache.type) { - case "filesystem": - F(cache, "name", () => name + "-" + mode); - D(cache, "version", ""); - F(cache, "cacheDirectory", () => { - const cwd = process.cwd(); - let dir = cwd; - for (;;) { - try { - if (fs.statSync(path.join(dir, "package.json")).isFile()) break; - // eslint-disable-next-line no-empty - } catch (e) {} - const parent = path.dirname(dir); - if (dir === parent) { - dir = undefined; - break; - } - dir = parent; - } - if (!dir) { - return path.resolve(cwd, ".cache/webpack"); - } else if (process.versions.pnp === "1") { - return path.resolve(dir, ".pnp/.cache/webpack"); - } else if (process.versions.pnp === "3") { - return path.resolve(dir, ".yarn/.cache/webpack"); - } else { - return path.resolve(dir, "node_modules/.cache/webpack"); + // TODO webpack 6: consider removing alternatives without dashes + /** @type {Map} */ + 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(); } - }); - F(cache, "cacheLocation", () => - path.resolve(cache.cacheDirectory, cache.name) - ); - D(cache, "hashAlgorithm", "md4"); - D(cache, "store", "pack"); - D(cache, "compression", false); - D(cache, "profile", false); - D(cache, "idleTimeout", 60000); - D(cache, "idleTimeoutForInitialStore", 5000); - D(cache, "idleTimeoutAfterLargeChanges", 1000); - D(cache, "maxMemoryGenerations", development ? 5 : Infinity); - D(cache, "maxAge", 1000 * 60 * 60 * 24 * 60); // 1 month - D(cache, "allowCollectingMemory", development); - D(cache, "memoryCacheUnaffected", development && cacheUnaffected); - D(cache.buildDependencies, "defaultWebpack", [ - path.resolve(__dirname, "..") + path.sep - ]); - break; - case "memory": - D(cache, "maxGenerations", Infinity); - D(cache, "cacheUnaffected", development && cacheUnaffected); - break; + } 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; + } + }); }; -/** - * @param {SnapshotOptions} snapshot options - * @param {Object} options options - * @param {boolean} options.production is production - * @param {boolean} options.futureDefaults is future defaults enabled - * @returns {void} - */ -const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => { - if (futureDefaults) { - F(snapshot, "managedPaths", () => - process.versions.pnp === "3" - ? [ - /^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/ - ] - : [/^(.+?[\\/]node_modules[\\/])/] - ); - F(snapshot, "immutablePaths", () => - process.versions.pnp === "3" - ? [/^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/] - : [] - ); +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 { - A(snapshot, "managedPaths", () => { - if (process.versions.pnp === "3") { - const match = - /^(.+?)[\\/]cache[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec( - /*require.resolve*/(36871) - ); - if (match) { - return [path.resolve(match[1], "unplugged")]; - } - } else { - const match = /^(.+?[\\/]node_modules[\\/])/.exec( - // eslint-disable-next-line node/no-extraneous-require - /*require.resolve*/(36871) - ); - if (match) { - return [match[1]]; - } - } - return []; - }); - A(snapshot, "immutablePaths", () => { - if (process.versions.pnp === "1") { - const match = - /^(.+?[\\/]v4)[\\/]npm-watchpack-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec( - /*require.resolve*/(36871) - ); - if (match) { - return [match[1]]; - } - } else if (process.versions.pnp === "3") { - const match = - /^(.+?)[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec( - /*require.resolve*/(36871) - ); - if (match) { - return [match[1]]; - } - } - return []; - }); + return test.test(str); } - F(snapshot, "resolveBuildDependencies", () => ({ - timestamp: true, - hash: true - })); - F(snapshot, "buildDependencies", () => ({ timestamp: true, hash: true })); - F(snapshot, "module", () => - production ? { timestamp: true, hash: true } : { timestamp: true } - ); - F(snapshot, "resolve", () => - production ? { timestamp: true, hash: true } : { timestamp: true } - ); }; -/** - * @param {JavascriptParserOptions} parserOptions parser options - * @param {Object} options options - * @param {boolean} options.futureDefaults is future defaults enabled - * @returns {void} - */ -const applyJavascriptParserOptionsDefaults = ( - parserOptions, - { futureDefaults } -) => { - D(parserOptions, "unknownContextRequest", "."); - D(parserOptions, "unknownContextRegExp", false); - D(parserOptions, "unknownContextRecursive", true); - D(parserOptions, "unknownContextCritical", true); - D(parserOptions, "exprContextRequest", "."); - D(parserOptions, "exprContextRegExp", false); - D(parserOptions, "exprContextRecursive", true); - D(parserOptions, "exprContextCritical", true); - D(parserOptions, "wrappedContextRegExp", /.*/); - D(parserOptions, "wrappedContextRecursive", true); - D(parserOptions, "wrappedContextCritical", false); - D(parserOptions, "strictThisContextOnImports", false); - if (futureDefaults) D(parserOptions, "exportsPresence", "error"); +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; }; + +/***/ }), + +/***/ 99988: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const util = __webpack_require__(73837); +const ExportsInfo = __webpack_require__(63686); +const ModuleGraphConnection = __webpack_require__(40639); +const SortableSet = __webpack_require__(13098); +const WeakTupleMap = __webpack_require__(28745); + +/** @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 */ + /** - * @param {ModuleOptions} module options - * @param {Object} options options - * @param {boolean} options.cache is caching enabled - * @param {boolean} options.syncWebAssembly is syncWebAssembly enabled - * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled - * @param {CssExperimentOptions} options.css is css enabled - * @param {boolean} options.futureDefaults is future defaults enabled - * @returns {void} + * @callback OptimizationBailoutFunction + * @param {RequestShortener} requestShortener + * @returns {string} */ -const applyModuleDefaults = ( - module, - { cache, syncWebAssembly, asyncWebAssembly, css, futureDefaults } -) => { - if (cache) { - D(module, "unsafeCache", module => { - const name = module.nameForCondition(); - return name && NODE_MODULES_REGEXP.test(name); - }); - } else { - D(module, "unsafeCache", false); - } - - F(module.parser, "asset", () => ({})); - F(module.parser.asset, "dataUrlCondition", () => ({})); - if (typeof module.parser.asset.dataUrlCondition === "object") { - D(module.parser.asset.dataUrlCondition, "maxSize", 8096); - } - F(module.parser, "javascript", () => ({})); - applyJavascriptParserOptionsDefaults(module.parser.javascript, { - futureDefaults - }); +const EMPTY_SET = new Set(); - A(module, "defaultRules", () => { - const esm = { - type: "javascript/esm", - resolve: { - byDependency: { - esm: { - fullySpecified: true - } - } - } - }; - const commonjs = { - type: "javascript/dynamic" - }; - /** @type {RuleSetRules} */ - const rules = [ - { - mimetype: "application/node", - type: "javascript/auto" - }, - { - test: /\.json$/i, - type: "json" - }, - { - mimetype: "application/json", - type: "json" - }, - { - test: /\.mjs$/i, - ...esm - }, - { - test: /\.js$/i, - descriptionData: { - type: "module" - }, - ...esm - }, - { - test: /\.cjs$/i, - ...commonjs - }, - { - test: /\.js$/i, - descriptionData: { - type: "commonjs" - }, - ...commonjs - }, - { - mimetype: { - or: ["text/javascript", "application/javascript"] - }, - ...esm +/** + * @param {SortableSet} set input + * @returns {readonly Map} 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); } - ]; - if (asyncWebAssembly) { - const wasm = { - type: "webassembly/async", - rules: [ - { - descriptionData: { - type: "module" - }, - resolve: { - fullySpecified: true - } - } - ] - }; - rules.push({ - test: /\.wasm$/i, - ...wasm - }); - rules.push({ - mimetype: "application/wasm", - ...wasm - }); - } else if (syncWebAssembly) { - const wasm = { - type: "webassembly/sync", - rules: [ - { - descriptionData: { - type: "module" - }, - resolve: { - fullySpecified: true - } - } - ] - }; - rules.push({ - test: /\.wasm$/i, - ...wasm - }); - rules.push({ - mimetype: "application/wasm", - ...wasm - }); - } - if (css) { - const cssRule = { - type: "css", - resolve: { - fullySpecified: true, - preferRelative: true - } - }; - const cssModulesRule = { - type: "css/module", - resolve: { - fullySpecified: true - } - }; - rules.push({ - test: /\.css$/i, - oneOf: [ - { - test: /\.module\.css$/i, - ...cssModulesRule - }, - { - ...cssRule - } - ] - }); - rules.push({ - mimetype: "text/css+module", - ...cssModulesRule - }); - rules.push({ - mimetype: "text/css", - ...cssRule - }); } - rules.push( - { - dependency: "url", - oneOf: [ - { - scheme: /^data$/, - type: "asset/inline" - }, - { - type: "asset/resource" - } - ] - }, - { - assert: { type: "json" }, - type: "json" - } - ); - return rules; - }); + } + return map; }; /** - * @param {Output} output options - * @param {Object} options options - * @param {string} options.context context - * @param {TargetProperties | false} options.targetProperties target properties - * @param {boolean} options.isAffectedByBrowserslist is affected by browserslist - * @param {boolean} options.outputModule is outputModule experiment enabled - * @param {boolean} options.development is development mode - * @param {Entry} options.entry entry option - * @param {ModuleOptions} options.module module option - * @param {boolean} options.futureDefaults is future defaults enabled - * @returns {void} + * @param {SortableSet} set input + * @returns {readonly Map} mapped by module */ -const applyOutputDefaults = ( - output, - { - context, - targetProperties: tp, - isAffectedByBrowserslist, - outputModule, - development, - entry, - module, - futureDefaults +const getConnectionsByModule = set => { + const map = new Map(); + /** @type {Module | 0} */ + let lastModule = 0; + /** @type {ModuleGraphConnection[]} */ + let lastList = undefined; + for (const connection of set) { + const { module } = connection; + if (lastModule === module) { + lastList.push(connection); + } else { + lastModule = module; + const list = map.get(module); + if (list !== undefined) { + lastList = list; + list.push(connection); + } else { + const list = [connection]; + lastList = list; + map.set(module, list); + } + } } -) => { + return map; +}; + +class ModuleGraphModule { + constructor() { + /** @type {SortableSet} */ + this.incomingConnections = new SortableSet(); + /** @type {SortableSet | 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; + /** @type {ModuleGraphConnection[]} */ + this._unassignedConnections = undefined; + } +} + +class ModuleGraph { + constructor() { + /** @type {WeakMap} */ + this._dependencyMap = new WeakMap(); + /** @type {Map} */ + this._moduleMap = new Map(); + /** @type {WeakMap} */ + this._metaMap = new WeakMap(); + + /** @type {WeakTupleMap} */ + this._cache = undefined; + + /** @type {Map>} */ + this._moduleMemCaches = undefined; + } + /** - * @param {Library=} library the library option - * @returns {string} a readable library name + * @param {Module} module the module + * @returns {ModuleGraphModule} the internal module */ - const getLibraryName = library => { - const libraryName = - typeof library === "object" && - library && - !Array.isArray(library) && - "type" in library - ? library.name - : /** @type {LibraryName=} */ (library); - if (Array.isArray(libraryName)) { - return libraryName.join("."); - } else if (typeof libraryName === "object") { - return getLibraryName(libraryName.root); - } else if (typeof libraryName === "string") { - return libraryName; + _getModuleGraphModule(module) { + let mgm = this._moduleMap.get(module); + if (mgm === undefined) { + mgm = new ModuleGraphModule(); + this._moduleMap.set(module, mgm); } - return ""; - }; + return mgm; + } - F(output, "uniqueName", () => { - const libraryName = getLibraryName(output.library); - if (libraryName) return libraryName; - const pkgPath = path.resolve(context, "package.json"); - try { - const packageInfo = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); - return packageInfo.name || ""; - } catch (e) { - if (e.code !== "ENOENT") { - e.message += `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`; - throw e; - } - return ""; - } - }); + /** + * @param {Dependency} dependency the dependency + * @param {DependenciesBlock} block parent block + * @param {Module} module parent module + * @param {number=} indexInBlock position in block + * @returns {void} + */ + setParents(dependency, block, module, indexInBlock = -1) { + dependency._parentDependenciesBlockIndex = indexInBlock; + dependency._parentDependenciesBlock = block; + dependency._parentModule = module; + } - F(output, "module", () => !!outputModule); - D(output, "filename", output.module ? "[name].mjs" : "[name].js"); - F(output, "iife", () => !output.module); - D(output, "importFunctionName", "import"); - D(output, "importMetaName", "import.meta"); - F(output, "chunkFilename", () => { - const filename = output.filename; - if (typeof filename !== "function") { - const hasName = filename.includes("[name]"); - const hasId = filename.includes("[id]"); - const hasChunkHash = filename.includes("[chunkhash]"); - const hasContentHash = filename.includes("[contenthash]"); - // Anything changing depending on chunk is fine - if (hasChunkHash || hasContentHash || hasName || hasId) return filename; - // Otherwise prefix "[id]." in front of the basename to make it changing - return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2"); - } - return output.module ? "[id].mjs" : "[id].js"; - }); - F(output, "cssFilename", () => { - const filename = output.filename; - if (typeof filename !== "function") { - return filename.replace(/\.[mc]?js(\?|$)/, ".css$1"); - } - return "[id].css"; - }); - F(output, "cssChunkFilename", () => { - const chunkFilename = output.chunkFilename; - if (typeof chunkFilename !== "function") { - return chunkFilename.replace(/\.[mc]?js(\?|$)/, ".css$1"); - } - return "[id].css"; - }); - D(output, "assetModuleFilename", "[hash][ext][query]"); - D(output, "webassemblyModuleFilename", "[hash].module.wasm"); - D(output, "compareBeforeEmit", true); - D(output, "charset", true); - F(output, "hotUpdateGlobal", () => - Template.toIdentifier( - "webpackHotUpdate" + Template.toIdentifier(output.uniqueName) - ) - ); - F(output, "chunkLoadingGlobal", () => - Template.toIdentifier( - "webpackChunk" + Template.toIdentifier(output.uniqueName) - ) - ); - F(output, "globalObject", () => { - if (tp) { - if (tp.global) return "global"; - if (tp.globalThis) return "globalThis"; - } - return "self"; - }); - F(output, "chunkFormat", () => { - if (tp) { - const helpMessage = isAffectedByBrowserslist - ? "Make sure that your 'browserslist' includes only platforms that support these features or select an appropriate 'target' to allow selecting a chunk format by default. Alternatively specify the 'output.chunkFormat' directly." - : "Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly."; - if (output.module) { - if (tp.dynamicImport) return "module"; - if (tp.document) return "array-push"; - throw new Error( - "For the selected environment is no default ESM chunk format available:\n" + - "ESM exports can be chosen when 'import()' is available.\n" + - "JSONP Array push can be chosen when 'document' is available.\n" + - helpMessage - ); - } else { - if (tp.document) return "array-push"; - if (tp.require) return "commonjs"; - if (tp.nodeBuiltins) return "commonjs"; - if (tp.importScripts) return "array-push"; - throw new Error( - "For the selected environment is no default script chunk format available:\n" + - "JSONP Array push can be chosen when 'document' or 'importScripts' is available.\n" + - "CommonJs exports can be chosen when 'require' or node builtins are available.\n" + - helpMessage - ); - } - } - throw new Error( - "Chunk format can't be selected by default when no target is specified" + /** + * @param {Dependency} dependency the dependency + * @returns {Module} parent module + */ + getParentModule(dependency) { + return dependency._parentModule; + } + + /** + * @param {Dependency} dependency the dependency + * @returns {DependenciesBlock} parent block + */ + getParentBlock(dependency) { + return dependency._parentDependenciesBlock; + } + + /** + * @param {Dependency} dependency the dependency + * @returns {number} index + */ + getParentBlockIndex(dependency) { + return dependency._parentDependenciesBlockIndex; + } + + /** + * @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) ); - }); - D(output, "asyncChunks", true); - F(output, "chunkLoading", () => { - if (tp) { - switch (output.chunkFormat) { - case "array-push": - if (tp.document) return "jsonp"; - if (tp.importScripts) return "import-scripts"; - break; - case "commonjs": - if (tp.require) return "require"; - if (tp.nodeBuiltins) return "async-node"; - break; - case "module": - if (tp.dynamicImport) return "import"; - break; - } - if ( - tp.require === null || - tp.nodeBuiltins === null || - tp.document === null || - tp.importScripts === null - ) { - return "universal"; - } - } - return false; - }); - F(output, "workerChunkLoading", () => { - if (tp) { - switch (output.chunkFormat) { - case "array-push": - if (tp.importScriptsInWorker) return "import-scripts"; - break; - case "commonjs": - if (tp.require) return "require"; - if (tp.nodeBuiltins) return "async-node"; - break; - case "module": - if (tp.dynamicImportInWorker) return "import"; - break; - } - if ( - tp.require === null || - tp.nodeBuiltins === null || - tp.importScriptsInWorker === null - ) { - return "universal"; + const connections = this._getModuleGraphModule(module).incomingConnections; + connections.add(connection); + if (originModule) { + const mgm = this._getModuleGraphModule(originModule); + if (mgm._unassignedConnections === undefined) { + mgm._unassignedConnections = []; } - } - return false; - }); - F(output, "wasmLoading", () => { - if (tp) { - if (tp.fetchWasm) return "fetch"; - if (tp.nodeBuiltins) - return output.module ? "async-node-module" : "async-node"; - if (tp.nodeBuiltins === null || tp.fetchWasm === null) { - return "universal"; + mgm._unassignedConnections.push(connection); + if (mgm.outgoingConnections === undefined) { + mgm.outgoingConnections = new SortableSet(); } + mgm.outgoingConnections.add(connection); + } else { + this._dependencyMap.set(dependency, connection); } - return false; - }); - F(output, "workerWasmLoading", () => output.wasmLoading); - F(output, "devtoolNamespace", () => output.uniqueName); - if (output.library) { - F(output.library, "type", () => (output.module ? "module" : "var")); } - F(output, "path", () => path.join(process.cwd(), "dist")); - F(output, "pathinfo", () => development); - D(output, "sourceMapFilename", "[file].map[query]"); - D( - output, - "hotUpdateChunkFilename", - `[id].[fullhash].hot-update.${output.module ? "mjs" : "js"}` - ); - D(output, "hotUpdateMainFilename", "[runtime].[fullhash].hot-update.json"); - D(output, "crossOriginLoading", false); - F(output, "scriptType", () => (output.module ? "module" : false)); - D( - output, - "publicPath", - (tp && (tp.document || tp.importScripts)) || output.scriptType === "module" - ? "auto" - : "" - ); - D(output, "chunkLoadTimeout", 120000); - D(output, "hashFunction", futureDefaults ? "xxhash64" : "md4"); - D(output, "hashDigest", "hex"); - D(output, "hashDigestLength", futureDefaults ? 16 : 20); - D(output, "strictModuleExceptionHandling", false); - const optimistic = v => v || v === undefined; - F( - output.environment, - "arrowFunction", - () => tp && optimistic(tp.arrowFunction) - ); - F(output.environment, "const", () => tp && optimistic(tp.const)); - F( - output.environment, - "destructuring", - () => tp && optimistic(tp.destructuring) - ); - F(output.environment, "forOf", () => tp && optimistic(tp.forOf)); - F(output.environment, "bigIntLiteral", () => tp && tp.bigIntLiteral); - F(output.environment, "dynamicImport", () => tp && tp.dynamicImport); - F(output.environment, "module", () => tp && tp.module); + /** + * @param {Dependency} dependency the referencing dependency + * @param {Module} module the referenced module + * @returns {void} + */ + updateModule(dependency, module) { + const connection = this.getConnection(dependency); + if (connection.module === module) return; + const newConnection = connection.clone(); + newConnection.module = module; + this._dependencyMap.set(dependency, newConnection); + connection.setActive(false); + const originMgm = this._getModuleGraphModule(connection.originModule); + originMgm.outgoingConnections.add(newConnection); + const targetMgm = this._getModuleGraphModule(module); + targetMgm.incomingConnections.add(newConnection); + } - const { trustedTypes } = output; - if (trustedTypes) { - F( - trustedTypes, - "policyName", - () => - output.uniqueName.replace(/[^a-zA-Z0-9\-#=_/@.%]+/g, "_") || "webpack" - ); + /** + * @param {Dependency} dependency the referencing dependency + * @returns {void} + */ + removeConnection(dependency) { + const connection = this.getConnection(dependency); + const targetMgm = this._getModuleGraphModule(connection.module); + targetMgm.incomingConnections.delete(connection); + const originMgm = this._getModuleGraphModule(connection.originModule); + originMgm.outgoingConnections.delete(connection); + this._dependencyMap.set(dependency, null); } /** - * @param {function(EntryDescription): void} fn iterator + * @param {Dependency} dependency the referencing dependency + * @param {string} explanation an explanation * @returns {void} */ - const forEachEntry = fn => { - for (const name of Object.keys(entry)) { - fn(entry[name]); - } - }; - A(output, "enabledLibraryTypes", () => { - const enabledLibraryTypes = []; - if (output.library) { - enabledLibraryTypes.push(output.library.type); - } - forEachEntry(desc => { - if (desc.library) { - enabledLibraryTypes.push(desc.library.type); - } - }); - return enabledLibraryTypes; - }); + addExplanation(dependency, explanation) { + const connection = this.getConnection(dependency); + connection.addExplanation(explanation); + } - A(output, "enabledChunkLoadingTypes", () => { - const enabledChunkLoadingTypes = new Set(); - if (output.chunkLoading) { - enabledChunkLoadingTypes.add(output.chunkLoading); - } - if (output.workerChunkLoading) { - enabledChunkLoadingTypes.add(output.workerChunkLoading); - } - forEachEntry(desc => { - if (desc.chunkLoading) { - enabledChunkLoadingTypes.add(desc.chunkLoading); - } - }); - return Array.from(enabledChunkLoadingTypes); - }); + /** + * @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; + } - A(output, "enabledWasmLoadingTypes", () => { - const enabledWasmLoadingTypes = new Set(); - if (output.wasmLoading) { - enabledWasmLoadingTypes.add(output.wasmLoading); + /** + * @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; } - if (output.workerWasmLoading) { - enabledWasmLoadingTypes.add(output.workerWasmLoading); + } + + /** + * @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 SortableSet(); + } + const newConnections = newMgm.outgoingConnections; + for (const connection of oldConnections) { + if (filterConnection(connection)) { + connection.originModule = newModule; + newConnections.add(connection); + oldConnections.delete(connection); + } + } } - forEachEntry(desc => { - if (desc.wasmLoading) { - enabledWasmLoadingTypes.add(desc.wasmLoading); + // 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); } - }); - return Array.from(enabledWasmLoadingTypes); - }); -}; - -/** - * @param {ExternalsPresets} externalsPresets options - * @param {Object} options options - * @param {TargetProperties | false} options.targetProperties target properties - * @param {boolean} options.buildHttp buildHttp experiment enabled - * @returns {void} - */ -const applyExternalsPresetsDefaults = ( - externalsPresets, - { targetProperties, buildHttp } -) => { - D( - externalsPresets, - "web", - !buildHttp && targetProperties && targetProperties.web - ); - D(externalsPresets, "node", targetProperties && targetProperties.node); - D(externalsPresets, "nwjs", targetProperties && targetProperties.nwjs); - D( - externalsPresets, - "electron", - targetProperties && targetProperties.electron - ); - D( - externalsPresets, - "electronMain", - targetProperties && - targetProperties.electron && - targetProperties.electronMain - ); - D( - externalsPresets, - "electronPreload", - targetProperties && - targetProperties.electron && - targetProperties.electronPreload - ); - D( - externalsPresets, - "electronRenderer", - targetProperties && - targetProperties.electron && - targetProperties.electronRenderer - ); -}; + } + } -/** - * @param {Loader} loader options - * @param {Object} options options - * @param {TargetProperties | false} options.targetProperties target properties - * @returns {void} - */ -const applyLoaderDefaults = (loader, { targetProperties }) => { - F(loader, "target", () => { - if (targetProperties) { - if (targetProperties.electron) { - if (targetProperties.electronMain) return "electron-main"; - if (targetProperties.electronPreload) return "electron-preload"; - if (targetProperties.electronRenderer) return "electron-renderer"; - return "electron"; + /** + * @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 SortableSet(); + } + 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); + } + } } - if (targetProperties.nwjs) return "nwjs"; - if (targetProperties.node) return "node"; - if (targetProperties.web) return "web"; } - }); -}; + } -/** - * @param {WebpackNode} node options - * @param {Object} options options - * @param {TargetProperties | false} options.targetProperties target properties - * @param {boolean} options.futureDefaults is future defaults enabled - * @returns {void} - */ -const applyNodeDefaults = (node, { futureDefaults, targetProperties }) => { - if (node === false) return; + /** + * @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)); + } - F(node, "global", () => { - if (targetProperties && targetProperties.global) return false; - // TODO webpack 6 should always default to false - return futureDefaults ? "warn" : true; - }); - F(node, "__filename", () => { - if (targetProperties && targetProperties.node) return "eval-only"; - // TODO webpack 6 should always default to false - return futureDefaults ? "warn-mock" : "mock"; - }); - F(node, "__dirname", () => { - if (targetProperties && targetProperties.node) return "eval-only"; - // TODO webpack 6 should always default to false - return futureDefaults ? "warn-mock" : "mock"; - }); -}; - -/** - * @param {Performance} performance options - * @param {Object} options options - * @param {boolean} options.production is production - * @returns {void} - */ -const applyPerformanceDefaults = (performance, { production }) => { - if (performance === false) return; - D(performance, "maxAssetSize", 250000); - D(performance, "maxEntrypointSize", 250000); - F(performance, "hints", () => (production ? "warning" : false)); -}; + /** + * @param {Dependency} dependency the dependency to look for a referenced module + * @returns {Module} the referenced module + */ + getResolvedModule(dependency) { + const connection = this.getConnection(dependency); + return connection !== undefined ? connection.resolvedModule : null; + } -/** - * @param {Optimization} optimization options - * @param {Object} options options - * @param {boolean} options.production is production - * @param {boolean} options.development is development - * @param {CssExperimentOptions} options.css is css enabled - * @param {boolean} options.records using records - * @returns {void} - */ -const applyOptimizationDefaults = ( - optimization, - { production, development, css, records } -) => { - D(optimization, "removeAvailableModules", false); - D(optimization, "removeEmptyChunks", true); - D(optimization, "mergeDuplicateChunks", true); - D(optimization, "flagIncludedChunks", production); - F(optimization, "moduleIds", () => { - if (production) return "deterministic"; - if (development) return "named"; - return "natural"; - }); - F(optimization, "chunkIds", () => { - if (production) return "deterministic"; - if (development) return "named"; - return "natural"; - }); - F(optimization, "sideEffects", () => (production ? true : "flag")); - D(optimization, "providedExports", true); - D(optimization, "usedExports", production); - D(optimization, "innerGraph", production); - D(optimization, "mangleExports", production); - D(optimization, "concatenateModules", production); - D(optimization, "runtimeChunk", false); - D(optimization, "emitOnErrors", !production); - D(optimization, "checkWasmTypes", production); - D(optimization, "mangleWasmImports", false); - D(optimization, "portableRecords", records); - D(optimization, "realContentHash", production); - D(optimization, "minimize", production); - A(optimization, "minimizer", () => [ - { - apply: compiler => { - // Lazy load the Terser plugin - const TerserPlugin = __webpack_require__(55302); - new TerserPlugin({ - terserOptions: { - compress: { - passes: 2 - } + /** + * @param {Dependency} dependency the dependency to look for a referenced module + * @returns {ModuleGraphConnection | undefined} the connection + */ + getConnection(dependency) { + const connection = this._dependencyMap.get(dependency); + if (connection === undefined) { + const module = this.getParentModule(dependency); + if (module !== undefined) { + const mgm = this._getModuleGraphModule(module); + if ( + mgm._unassignedConnections && + mgm._unassignedConnections.length !== 0 + ) { + let foundConnection; + for (const connection of mgm._unassignedConnections) { + this._dependencyMap.set(connection.dependency, connection); + if (connection.dependency === dependency) + foundConnection = connection; } - }).apply(compiler); + mgm._unassignedConnections.length = 0; + if (foundConnection !== undefined) { + return foundConnection; + } + } } + this._dependencyMap.set(dependency, null); + return undefined; + } + return connection === null ? undefined : connection; + } + + /** + * @param {Dependency} dependency the dependency to look for a referenced module + * @returns {Module} the referenced module + */ + getModule(dependency) { + const connection = this.getConnection(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.getConnection(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.getConnection(dependency); + return connection !== undefined ? connection.resolvedOriginModule : null; + } + + /** + * @param {Module} module the module + * @returns {Iterable} reasons why a module is included + */ + getIncomingConnections(module) { + const connections = this._getModuleGraphModule(module).incomingConnections; + return connections; + } + + /** + * @param {Module} module the module + * @returns {Iterable} list of outgoing connections + */ + getOutgoingConnections(module) { + const connections = this._getModuleGraphModule(module).outgoingConnections; + return connections === undefined ? EMPTY_SET : connections; + } + + /** + * @param {Module} module the module + * @returns {readonly Map} 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 {readonly Map | undefined} connections to modules, in a map by module + */ + getOutgoingConnectionsByModule(module) { + const connections = this._getModuleGraphModule(module).outgoingConnections; + return connections === undefined + ? undefined + : connections.getFromUnorderedCache(getConnectionsByModule); + } + + /** + * @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 | null} the used exports + * false: module is not used at all. + * true: the module namespace/object export is used. + * SortableSet: these export names are used. + * empty SortableSet: 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; } - ]); - F(optimization, "nodeEnv", () => { - if (production) return "production"; - if (development) return "development"; return false; - }); - const { splitChunks } = optimization; - if (splitChunks) { - A(splitChunks, "defaultSizeTypes", () => - css ? ["javascript", "css", "unknown"] : ["javascript", "unknown"] - ); - D(splitChunks, "hidePathInfo", production); - D(splitChunks, "chunks", "async"); - D(splitChunks, "usedExports", optimization.usedExports === true); - D(splitChunks, "minChunks", 1); - F(splitChunks, "minSize", () => (production ? 20000 : 10000)); - F(splitChunks, "minRemainingSize", () => (development ? 0 : undefined)); - F(splitChunks, "enforceSizeThreshold", () => (production ? 50000 : 30000)); - F(splitChunks, "maxAsyncRequests", () => (production ? 30 : Infinity)); - F(splitChunks, "maxInitialRequests", () => (production ? 30 : Infinity)); - D(splitChunks, "automaticNameDelimiter", "-"); - const { cacheGroups } = splitChunks; - F(cacheGroups, "default", () => ({ - idHint: "", - reuseExistingChunk: true, - minChunks: 2, - priority: -20 - })); - F(cacheGroups, "defaultVendors", () => ({ - idHint: "vendors", - reuseExistingChunk: true, - test: NODE_MODULES_REGEXP, - priority: -10 - })); } -}; -/** - * @param {Object} options options - * @param {boolean} options.cache is cache enable - * @param {string} options.context build context - * @param {TargetProperties | false} options.targetProperties target properties - * @param {Mode} options.mode mode - * @returns {ResolveOptions} resolve options - */ -const getResolveDefaults = ({ cache, context, targetProperties, mode }) => { - /** @type {string[]} */ - const conditions = ["webpack"]; + /** + * @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; + } - conditions.push(mode === "development" ? "development" : "production"); + /** + * @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; + } - if (targetProperties) { - if (targetProperties.webworker) conditions.push("worker"); - if (targetProperties.node) conditions.push("node"); - if (targetProperties.web) conditions.push("browser"); - if (targetProperties.electron) conditions.push("electron"); - if (targetProperties.nwjs) conditions.push("nwjs"); + /** + * @param {Module} module the module + * @returns {number} the depth of the module + */ + getDepth(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.depth; } - const jsExtensions = [".js", ".json", ".wasm"]; + /** + * @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; + } - const tp = targetProperties; - const browserField = - tp && tp.web && (!tp.node || (tp.electron && tp.electronRenderer)); + /** + * @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; + } - /** @type {function(): ResolveOptions} */ - const cjsDeps = () => ({ - aliasFields: browserField ? ["browser"] : [], - mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."], - conditionNames: ["require", "module", "..."], - extensions: [...jsExtensions] - }); - /** @type {function(): ResolveOptions} */ - const esmDeps = () => ({ - aliasFields: browserField ? ["browser"] : [], - mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."], - conditionNames: ["import", "module", "..."], - extensions: [...jsExtensions] - }); + /** + * @param {Module} module the module + * @returns {boolean} true, if the module is async + */ + isAsync(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.async; + } - /** @type {ResolveOptions} */ - const resolveOptions = { - cache, - modules: ["node_modules"], - conditionNames: conditions, - mainFiles: ["index"], - extensions: [], - aliasFields: [], - exportsFields: ["exports"], - roots: [context], - mainFields: ["main"], - byDependency: { - wasm: esmDeps(), - esm: esmDeps(), - loaderImport: esmDeps(), - url: { - preferRelative: true - }, - worker: { - ...esmDeps(), - preferRelative: true - }, - commonjs: cjsDeps(), - amd: cjsDeps(), - // for backward-compat: loadModule - loader: cjsDeps(), - // for backward-compat: Custom Dependency - unknown: cjsDeps(), - // for backward-compat: getResolve without dependencyType - undefined: cjsDeps() + /** + * @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; + } - return resolveOptions; -}; + /** + * @param {any} thing any thing + * @returns {Object} metadata + */ + getMetaIfExisting(thing) { + return this._metaMap.get(thing); + } -/** - * @param {Object} options options - * @param {boolean} options.cache is cache enable - * @returns {ResolveOptions} resolve options - */ -const getResolveLoaderDefaults = ({ cache }) => { - /** @type {ResolveOptions} */ - const resolveOptions = { - cache, - conditionNames: ["loader", "require", "node"], - exportsFields: ["exports"], - mainFields: ["loader", "main"], - extensions: [".js"], - mainFiles: ["index"] - }; + /** + * @param {string=} cacheStage a persistent stage name for caching + */ + freeze(cacheStage) { + this._cache = new WeakTupleMap(); + this._cacheStage = cacheStage; + } - return resolveOptions; -}; + unfreeze() { + this._cache = undefined; + this._cacheStage = undefined; + } -/** - * @param {InfrastructureLogging} infrastructureLogging options - * @returns {void} - */ -const applyInfrastructureLoggingDefaults = infrastructureLogging => { - F(infrastructureLogging, "stream", () => process.stderr); - const tty = - /** @type {any} */ (infrastructureLogging.stream).isTTY && - process.env.TERM !== "dumb"; - D(infrastructureLogging, "level", "info"); - D(infrastructureLogging, "debug", false); - D(infrastructureLogging, "colors", tty); - D(infrastructureLogging, "appendOnly", !tty); -}; + /** + * @template {any[]} T + * @template V + * @param {(moduleGraph: ModuleGraph, ...args: T) => V} fn computer + * @param {T} args arguments + * @returns {V} computed value or cached + */ + cached(fn, ...args) { + if (this._cache === undefined) return fn(this, ...args); + return this._cache.provide(fn, ...args, () => fn(this, ...args)); + } -exports.applyWebpackOptionsBaseDefaults = applyWebpackOptionsBaseDefaults; -exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults; + /** + * @param {Map>} moduleMemCaches mem caches for modules for better caching + */ + setModuleMemCaches(moduleMemCaches) { + this._moduleMemCaches = moduleMemCaches; + } + + /** + * @param {Dependency} dependency dependency + * @param {...any} args arguments, last argument is a function called with moduleGraph, dependency, ...args + * @returns {any} computed value or cached + */ + dependencyCacheProvide(dependency, ...args) { + /** @type {(moduleGraph: ModuleGraph, dependency: Dependency, ...args: any[]) => any} */ + const fn = args.pop(); + if (this._moduleMemCaches && this._cacheStage) { + const memCache = this._moduleMemCaches.get( + this.getParentModule(dependency) + ); + if (memCache !== undefined) { + return memCache.provide(dependency, this._cacheStage, ...args, () => + fn(this, dependency, ...args) + ); + } + } + if (this._cache === undefined) return fn(this, dependency, ...args); + return this._cache.provide(dependency, ...args, () => + fn(this, dependency, ...args) + ); + } + + // 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} */ +const moduleGraphForModuleMap = new WeakMap(); + +// TODO remove in webpack 6 +/** @type {Map ModuleGraph>} */ +const deprecateMap = new Map(); + +module.exports = ModuleGraph; +module.exports.ModuleGraphConnection = ModuleGraphConnection; /***/ }), -/***/ 26693: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 40639: +/***/ (function(module) { "use strict"; /* @@ -65324,533 +58957,459 @@ exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults; -const util = __webpack_require__(73837); - -/** @typedef {import("../../declarations/WebpackOptions").EntryStatic} EntryStatic */ -/** @typedef {import("../../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunk} OptimizationRuntimeChunk */ -/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunkNormalized} OptimizationRuntimeChunkNormalized */ -/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputNormalized */ -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */ - -const handledDeprecatedNoEmitOnErrors = util.deprecate( - (noEmitOnErrors, emitOnErrors) => { - if (emitOnErrors !== undefined && !noEmitOnErrors === !emitOnErrors) { - throw new Error( - "Conflicting use of 'optimization.noEmitOnErrors' and 'optimization.emitOnErrors'. Remove deprecated 'optimization.noEmitOnErrors' from config." - ); - } - return !noEmitOnErrors; - }, - "optimization.noEmitOnErrors is deprecated in favor of optimization.emitOnErrors", - "DEP_WEBPACK_CONFIGURATION_OPTIMIZATION_NO_EMIT_ON_ERRORS" -); +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** - * @template T - * @template R - * @param {T|undefined} value value or not - * @param {function(T): R} fn nested handler - * @returns {R} result value + * Module itself is not connected, but transitive modules are connected transitively. */ -const nestedConfig = (value, fn) => - value === undefined ? fn(/** @type {T} */ ({})) : fn(value); +const TRANSITIVE_ONLY = Symbol("transitive only"); /** - * @template T - * @param {T|undefined} value value or not - * @returns {T} result value + * While determining the active state, this flag is used to signal a circular connection. */ -const cloneObject = value => { - return /** @type {T} */ ({ ...value }); -}; +const CIRCULAR_CONNECTION = Symbol("circular connection"); -/** - * @template T - * @template R - * @param {T|undefined} value value or not - * @param {function(T): R} fn nested handler - * @returns {R|undefined} result value - */ -const optionalNestedConfig = (value, fn) => - value === undefined ? undefined : fn(value); +/** @typedef {boolean | typeof TRANSITIVE_ONLY | typeof CIRCULAR_CONNECTION} ConnectionState */ /** - * @template T - * @template R - * @param {T[]|undefined} value array or not - * @param {function(T[]): R[]} fn nested handler - * @returns {R[]|undefined} cloned value + * @param {ConnectionState} a first + * @param {ConnectionState} b second + * @returns {ConnectionState} merged */ -const nestedArray = (value, fn) => (Array.isArray(value) ? fn(value) : fn([])); +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; +}; /** - * @template T - * @template R - * @param {T[]|undefined} value array or not - * @param {function(T[]): R[]} fn nested handler - * @returns {R[]|undefined} cloned value + * @param {ConnectionState} a first + * @param {ConnectionState} b second + * @returns {ConnectionState} intersected */ -const optionalNestedArray = (value, fn) => - Array.isArray(value) ? fn(value) : undefined; +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; +}; -/** - * @template T - * @template R - * @param {Record|undefined} value value or not - * @param {function(T): R} fn nested handler - * @param {Record=} customKeys custom nested handler for some keys - * @returns {Record} result value - */ -const keyedNestedConfig = (value, fn, customKeys) => { - const result = - value === undefined - ? {} - : Object.keys(value).reduce( - (obj, key) => ( - (obj[key] = ( - customKeys && key in customKeys ? customKeys[key] : fn - )(value[key])), - obj - ), - /** @type {Record} */ ({}) - ); - if (customKeys) { - for (const key of Object.keys(customKeys)) { - if (!(key in result)) { - result[key] = customKeys[key](/** @type {T} */ ({})); - } +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} */ + this.explanations = undefined; + if (explanation) { + this.explanations = new Set(); + this.explanations.add(explanation); } } - return result; + + 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 +); + + +/***/ }), + +/***/ 3454: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { ConcatSource, RawSource, CachedSource } = __webpack_require__(51255); +const { UsageState } = __webpack_require__(63686); +const Template = __webpack_require__(39722); +const JavascriptModulesPlugin = __webpack_require__(89464); + +/** @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 {WebpackOptions} config input config - * @returns {WebpackOptionsNormalized} normalized options + * @param {ConcatSource} source output + * @param {string} indent spacing + * @param {ExportsInfo} exportsInfo data + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {RequestShortener} requestShortener requestShortener + * @param {Set} alreadyPrinted deduplication set + * @returns {void} */ -const getNormalizedWebpackOptions = config => { - return { - amd: config.amd, - bail: config.bail, - cache: optionalNestedConfig(config.cache, cache => { - if (cache === false) return false; - if (cache === true) { - return { - type: "memory", - maxGenerations: undefined - }; - } - switch (cache.type) { - case "filesystem": - return { - type: "filesystem", - allowCollectingMemory: cache.allowCollectingMemory, - maxMemoryGenerations: cache.maxMemoryGenerations, - maxAge: cache.maxAge, - profile: cache.profile, - buildDependencies: cloneObject(cache.buildDependencies), - cacheDirectory: cache.cacheDirectory, - cacheLocation: cache.cacheLocation, - hashAlgorithm: cache.hashAlgorithm, - compression: cache.compression, - idleTimeout: cache.idleTimeout, - idleTimeoutForInitialStore: cache.idleTimeoutForInitialStore, - idleTimeoutAfterLargeChanges: cache.idleTimeoutAfterLargeChanges, - name: cache.name, - store: cache.store, - version: cache.version - }; - case undefined: - case "memory": - return { - type: "memory", - maxGenerations: cache.maxGenerations - }; - default: - // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339) - throw new Error(`Not implemented cache.type ${cache.type}`); - } - }), - context: config.context, - dependencies: config.dependencies, - devServer: optionalNestedConfig(config.devServer, devServer => ({ - ...devServer - })), - devtool: config.devtool, - entry: - config.entry === undefined - ? { main: {} } - : typeof config.entry === "function" - ? ( - fn => () => - Promise.resolve().then(fn).then(getNormalizedEntryStatic) - )(config.entry) - : getNormalizedEntryStatic(config.entry), - experiments: nestedConfig(config.experiments, experiments => ({ - ...experiments, - buildHttp: optionalNestedConfig(experiments.buildHttp, options => - Array.isArray(options) ? { allowedUris: options } : options - ), - lazyCompilation: optionalNestedConfig( - experiments.lazyCompilation, - options => - options === true ? {} : options === false ? undefined : options - ), - css: optionalNestedConfig(experiments.css, options => - options === true ? {} : options === false ? undefined : options - ) - })), - externals: config.externals, - externalsPresets: cloneObject(config.externalsPresets), - externalsType: config.externalsType, - ignoreWarnings: config.ignoreWarnings - ? config.ignoreWarnings.map(ignore => { - if (typeof ignore === "function") return ignore; - const i = ignore instanceof RegExp ? { message: ignore } : ignore; - return (warning, { requestShortener }) => { - if (!i.message && !i.module && !i.file) return false; - if (i.message && !i.message.test(warning.message)) { - return false; - } - if ( - i.module && - (!warning.module || - !i.module.test( - warning.module.readableIdentifier(requestShortener) - )) - ) { - return false; - } - if (i.file && (!warning.file || !i.file.test(warning.file))) { - return false; - } - return true; - }; - }) - : undefined, - infrastructureLogging: cloneObject(config.infrastructureLogging), - loader: cloneObject(config.loader), - mode: config.mode, - module: nestedConfig(config.module, module => ({ - noParse: module.noParse, - unsafeCache: module.unsafeCache, - parser: keyedNestedConfig(module.parser, cloneObject, { - javascript: parserOptions => ({ - unknownContextRequest: module.unknownContextRequest, - unknownContextRegExp: module.unknownContextRegExp, - unknownContextRecursive: module.unknownContextRecursive, - unknownContextCritical: module.unknownContextCritical, - exprContextRequest: module.exprContextRequest, - exprContextRegExp: module.exprContextRegExp, - exprContextRecursive: module.exprContextRecursive, - exprContextCritical: module.exprContextCritical, - wrappedContextRegExp: module.wrappedContextRegExp, - wrappedContextRecursive: module.wrappedContextRecursive, - wrappedContextCritical: module.wrappedContextCritical, - // TODO webpack 6 remove - strictExportPresence: module.strictExportPresence, - strictThisContextOnImports: module.strictThisContextOnImports, - ...parserOptions - }) - }), - generator: cloneObject(module.generator), - defaultRules: optionalNestedArray(module.defaultRules, r => [...r]), - rules: nestedArray(module.rules, r => [...r]) - })), - name: config.name, - node: nestedConfig( - config.node, - node => - node && { - ...node - } - ), - optimization: nestedConfig(config.optimization, optimization => { - return { - ...optimization, - runtimeChunk: getNormalizedOptimizationRuntimeChunk( - optimization.runtimeChunk - ), - splitChunks: nestedConfig( - optimization.splitChunks, - splitChunks => - splitChunks && { - ...splitChunks, - defaultSizeTypes: splitChunks.defaultSizeTypes - ? [...splitChunks.defaultSizeTypes] - : ["..."], - cacheGroups: cloneObject(splitChunks.cacheGroups) - } - ), - emitOnErrors: - optimization.noEmitOnErrors !== undefined - ? handledDeprecatedNoEmitOnErrors( - optimization.noEmitOnErrors, - optimization.emitOnErrors - ) - : optimization.emitOnErrors - }; - }), - output: nestedConfig(config.output, output => { - const { library } = output; - const libraryAsName = /** @type {LibraryName} */ (library); - const libraryBase = - typeof library === "object" && - library && - !Array.isArray(library) && - "type" in library - ? library - : libraryAsName || output.libraryTarget - ? /** @type {LibraryOptions} */ ({ - name: libraryAsName - }) - : undefined; - /** @type {OutputNormalized} */ - const result = { - assetModuleFilename: output.assetModuleFilename, - asyncChunks: output.asyncChunks, - charset: output.charset, - chunkFilename: output.chunkFilename, - chunkFormat: output.chunkFormat, - chunkLoading: output.chunkLoading, - chunkLoadingGlobal: output.chunkLoadingGlobal, - chunkLoadTimeout: output.chunkLoadTimeout, - cssFilename: output.cssFilename, - cssChunkFilename: output.cssChunkFilename, - clean: output.clean, - compareBeforeEmit: output.compareBeforeEmit, - crossOriginLoading: output.crossOriginLoading, - devtoolFallbackModuleFilenameTemplate: - output.devtoolFallbackModuleFilenameTemplate, - devtoolModuleFilenameTemplate: output.devtoolModuleFilenameTemplate, - devtoolNamespace: output.devtoolNamespace, - environment: cloneObject(output.environment), - enabledChunkLoadingTypes: output.enabledChunkLoadingTypes - ? [...output.enabledChunkLoadingTypes] - : ["..."], - enabledLibraryTypes: output.enabledLibraryTypes - ? [...output.enabledLibraryTypes] - : ["..."], - enabledWasmLoadingTypes: output.enabledWasmLoadingTypes - ? [...output.enabledWasmLoadingTypes] - : ["..."], - filename: output.filename, - globalObject: output.globalObject, - hashDigest: output.hashDigest, - hashDigestLength: output.hashDigestLength, - hashFunction: output.hashFunction, - hashSalt: output.hashSalt, - hotUpdateChunkFilename: output.hotUpdateChunkFilename, - hotUpdateGlobal: output.hotUpdateGlobal, - hotUpdateMainFilename: output.hotUpdateMainFilename, - iife: output.iife, - importFunctionName: output.importFunctionName, - importMetaName: output.importMetaName, - scriptType: output.scriptType, - library: libraryBase && { - type: - output.libraryTarget !== undefined - ? output.libraryTarget - : libraryBase.type, - auxiliaryComment: - output.auxiliaryComment !== undefined - ? output.auxiliaryComment - : libraryBase.auxiliaryComment, - export: - output.libraryExport !== undefined - ? output.libraryExport - : libraryBase.export, - name: libraryBase.name, - umdNamedDefine: - output.umdNamedDefine !== undefined - ? output.umdNamedDefine - : libraryBase.umdNamedDefine - }, - module: output.module, - path: output.path, - pathinfo: output.pathinfo, - publicPath: output.publicPath, - sourceMapFilename: output.sourceMapFilename, - sourcePrefix: output.sourcePrefix, - strictModuleExceptionHandling: output.strictModuleExceptionHandling, - trustedTypes: optionalNestedConfig( - output.trustedTypes, - trustedTypes => { - if (trustedTypes === true) return {}; - if (typeof trustedTypes === "string") - return { policyName: trustedTypes }; - return { ...trustedTypes }; - } - ), - uniqueName: output.uniqueName, - wasmLoading: output.wasmLoading, - webassemblyModuleFilename: output.webassemblyModuleFilename, - workerChunkLoading: output.workerChunkLoading, - workerWasmLoading: output.workerWasmLoading - }; - return result; - }), - parallelism: config.parallelism, - performance: optionalNestedConfig(config.performance, performance => { - if (performance === false) return false; - return { - ...performance - }; - }), - plugins: nestedArray(config.plugins, p => [...p]), - profile: config.profile, - recordsInputPath: - config.recordsInputPath !== undefined - ? config.recordsInputPath - : config.recordsPath, - recordsOutputPath: - config.recordsOutputPath !== undefined - ? config.recordsOutputPath - : config.recordsPath, - resolve: nestedConfig(config.resolve, resolve => ({ - ...resolve, - byDependency: keyedNestedConfig(resolve.byDependency, cloneObject) - })), - resolveLoader: cloneObject(config.resolveLoader), - snapshot: nestedConfig(config.snapshot, snapshot => ({ - resolveBuildDependencies: optionalNestedConfig( - snapshot.resolveBuildDependencies, - resolveBuildDependencies => ({ - timestamp: resolveBuildDependencies.timestamp, - hash: resolveBuildDependencies.hash - }) - ), - buildDependencies: optionalNestedConfig( - snapshot.buildDependencies, - buildDependencies => ({ - timestamp: buildDependencies.timestamp, - hash: buildDependencies.hash - }) - ), - resolve: optionalNestedConfig(snapshot.resolve, resolve => ({ - timestamp: resolve.timestamp, - hash: resolve.hash - })), - module: optionalNestedConfig(snapshot.module, module => ({ - timestamp: module.timestamp, - hash: module.hash - })), - immutablePaths: optionalNestedArray(snapshot.immutablePaths, p => [...p]), - managedPaths: optionalNestedArray(snapshot.managedPaths, p => [...p]) - })), - stats: nestedConfig(config.stats, stats => { - if (stats === false) { - return { - preset: "none" - }; - } - if (stats === true) { - return { - preset: "normal" - }; - } - if (typeof stats === "string") { - return { - preset: stats - }; - } - return { - ...stats - }; - }), - target: config.target, - watch: config.watch, - watchOptions: cloneObject(config.watchOptions) - }; -}; +const printExportsInfoToSource = ( + source, + indent, + exportsInfo, + moduleGraph, + requestShortener, + alreadyPrinted = new Set() +) => { + const otherExportsInfo = exportsInfo.otherExportsInfo; -/** - * @param {EntryStatic} entry static entry options - * @returns {EntryStaticNormalized} normalized static entry options - */ -const getNormalizedEntryStatic = entry => { - if (typeof entry === "string") { - return { - main: { - import: [entry] - } - }; + 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++; + } } - if (Array.isArray(entry)) { - return { - main: { - import: entry - } - }; + let showOtherExports = false; + if (!alreadyPrinted.has(otherExportsInfo)) { + alreadyPrinted.add(otherExportsInfo); + showOtherExports = true; + } else { + alreadyPrintedExports++; } - /** @type {EntryStaticNormalized} */ - const result = {}; - for (const key of Object.keys(entry)) { - const value = entry[key]; - if (typeof value === "string") { - result[key] = { - import: [value] - }; - } else if (Array.isArray(value)) { - result[key] = { - import: value - }; - } else { - result[key] = { - import: - value.import && - (Array.isArray(value.import) ? value.import : [value.import]), - filename: value.filename, - layer: value.layer, - runtime: value.runtime, - publicPath: value.publicPath, - chunkLoading: value.chunkLoading, - asyncChunks: value.asyncChunks, - wasmLoading: value.wasmLoading, - dependOn: - value.dependOn && - (Array.isArray(value.dependOn) ? value.dependOn : [value.dependOn]), - library: value.library - }; + + // 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 + ); } } - return result; -}; -/** - * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option - * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option - */ -const getNormalizedOptimizationRuntimeChunk = runtimeChunk => { - if (runtimeChunk === undefined) return undefined; - if (runtimeChunk === false) return false; - if (runtimeChunk === "single") { - return { - name: () => "runtime" - }; + if (alreadyPrintedExports) { + source.add( + Template.toComment( + `${indent}... (${alreadyPrintedExports} already listed exports)` + ) + "\n" + ); } - if (runtimeChunk === true || runtimeChunk === "multiple") { - return { - name: entrypoint => `runtime~${entrypoint.name}` - }; + + 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" + ); + } } - const { name } = runtimeChunk; - return { - name: typeof name === "function" ? name : () => name - }; }; -exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions; +/** @type {WeakMap }>>} */ +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; /***/ }), -/***/ 52801: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 32882: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -65860,1056 +59419,572 @@ exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions; -const memoize = __webpack_require__(78676); +const WebpackError = __webpack_require__(53799); -const getBrowserslistTargetHandler = memoize(() => - __webpack_require__(43950) -); +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ -/** - * @param {string} context the context directory - * @returns {string} default target - */ -const getDefaultTarget = context => { - const browsers = getBrowserslistTargetHandler().load(null, context); - return browsers ? "browserslist" : "web"; +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" }; -/** - * @typedef {Object} PlatformTargetProperties - * @property {boolean | null} web web platform, importing of http(s) and std: is available - * @property {boolean | null} browser browser platform, running in a normal web browser - * @property {boolean | null} webworker (Web)Worker platform, running in a web/shared/service worker - * @property {boolean | null} node node platform, require of node built-in modules is available - * @property {boolean | null} nwjs nwjs platform, require of legacy nw.gui is available - * @property {boolean | null} electron electron platform, require of some electron built-in modules is available - */ - -/** - * @typedef {Object} ElectronContextTargetProperties - * @property {boolean | null} electronMain in main context - * @property {boolean | null} electronPreload in preload context - * @property {boolean | null} electronRenderer in renderer context with node integration - */ - -/** - * @typedef {Object} ApiTargetProperties - * @property {boolean | null} require has require function available - * @property {boolean | null} nodeBuiltins has node.js built-in modules available - * @property {boolean | null} document has document available (allows script tags) - * @property {boolean | null} importScripts has importScripts available - * @property {boolean | null} importScriptsInWorker has importScripts available when creating a worker - * @property {boolean | null} fetchWasm has fetch function available for WebAssembly - * @property {boolean | null} global has global variable available - */ - -/** - * @typedef {Object} EcmaTargetProperties - * @property {boolean | null} globalThis has globalThis variable available - * @property {boolean | null} bigIntLiteral big int literal syntax is available - * @property {boolean | null} const const and let variable declarations are available - * @property {boolean | null} arrowFunction arrow functions are available - * @property {boolean | null} forOf for of iteration is available - * @property {boolean | null} destructuring destructuring is available - * @property {boolean | null} dynamicImport async import() is available - * @property {boolean | null} dynamicImportInWorker async import() is available when creating a worker - * @property {boolean | null} module ESM syntax is available (when in module) - * @property {boolean | null} optionalChaining optional chaining is available - * @property {boolean | null} templateLiteral template literal is available - */ - -///** @typedef {PlatformTargetProperties | ApiTargetProperties | EcmaTargetProperties | PlatformTargetProperties & ApiTargetProperties | PlatformTargetProperties & EcmaTargetProperties | ApiTargetProperties & EcmaTargetProperties} TargetProperties */ -/** @template T @typedef {{ [P in keyof T]?: never }} Never */ -/** @template A @template B @typedef {(A & Never) | (Never & B) | (A & B)} Mix */ -/** @typedef {Mix, Mix>} TargetProperties */ - -const versionDependent = (major, minor) => { - if (!major) return () => /** @type {undefined} */ (undefined); - major = +major; - minor = minor ? +minor : 0; - return (vMajor, vMinor = 0) => { - return major > vMajor || (major === vMajor && minor >= vMinor); - }; -}; +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()}`; -/** @type {[string, string, RegExp, (...args: string[]) => TargetProperties | false][]} */ -const TARGETS = [ - [ - "browserslist / browserslist:env / browserslist:query / browserslist:path-to-config / browserslist:path-to-config:env", - "Resolve features from browserslist. Will resolve browserslist config automatically. Only browser or node queries are supported (electron is not supported). Examples: 'browserslist:modern' to use 'modern' environment from browserslist config", - /^browserslist(?::(.+))?$/, - (rest, context) => { - const browserslistTargetHandler = getBrowserslistTargetHandler(); - const browsers = browserslistTargetHandler.load( - rest ? rest.trim() : null, - context - ); - if (!browsers) { - throw new Error(`No browserslist config found to handle the 'browserslist' target. -See https://github.com/browserslist/browserslist#queries for possible ways to provide a config. -The recommended way is to add a 'browserslist' key to your package.json and list supported browsers (resp. node.js versions). -You can also more options via the 'target' option: 'browserslist' / 'browserslist:env' / 'browserslist:query' / 'browserslist:path-to-config' / 'browserslist:path-to-config:env'`); + // 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 }`; } - return browserslistTargetHandler.resolve(browsers); - } - ], - [ - "web", - "Web browser.", - /^web$/, - () => { - return { - web: true, - browser: true, - webworker: null, - node: false, - electron: false, - nwjs: false, - - document: true, - importScriptsInWorker: true, - fetchWasm: true, - nodeBuiltins: false, - importScripts: false, - require: false, - global: false - }; - } - ], - [ - "webworker", - "Web Worker, SharedWorker or Service Worker.", - /^webworker$/, - () => { - return { - web: true, - browser: true, - webworker: true, - node: false, - electron: false, - nwjs: false, - - importScripts: true, - importScriptsInWorker: true, - fetchWasm: true, - nodeBuiltins: false, - require: false, - document: false, - global: false - }; - } - ], - [ - "[async-]node[X[.Y]]", - "Node.js in version X.Y. The 'async-' prefix will load chunks asynchronously via 'fs' and 'vm' instead of 'require()'. Examples: node14.5, async-node10.", - /^(async-)?node(\d+(?:\.(\d+))?)?$/, - (asyncFlag, major, minor) => { - const v = versionDependent(major, minor); - // see https://node.green/ - return { - node: true, - electron: false, - nwjs: false, - web: false, - webworker: false, - browser: false, - - require: !asyncFlag, - nodeBuiltins: true, - global: true, - document: false, - fetchWasm: false, - importScripts: false, - importScriptsInWorker: false, - - globalThis: v(12), - const: v(6), - templateLiteral: v(4), - optionalChaining: v(14), - arrowFunction: v(6), - forOf: v(5), - destructuring: v(6), - bigIntLiteral: v(10, 4), - dynamicImport: v(12, 17), - dynamicImportInWorker: major ? false : undefined, - module: v(12, 17) - }; - } - ], - [ - "electron[X[.Y]]-main/preload/renderer", - "Electron in version X.Y. Script is running in main, preload resp. renderer context.", - /^electron(\d+(?:\.(\d+))?)?-(main|preload|renderer)$/, - (major, minor, context) => { - const v = versionDependent(major, minor); - // see https://node.green/ + https://github.com/electron/releases - return { - node: true, - electron: true, - web: context !== "main", - webworker: false, - browser: false, - nwjs: false, - - electronMain: context === "main", - electronPreload: context === "preload", - electronRenderer: context === "renderer", - - global: true, - nodeBuiltins: true, - require: true, - document: context === "renderer", - fetchWasm: context === "renderer", - importScripts: false, - importScriptsInWorker: true, - - globalThis: v(5), - const: v(1, 1), - templateLiteral: v(1, 1), - optionalChaining: v(8), - arrowFunction: v(1, 1), - forOf: v(0, 36), - destructuring: v(1, 1), - bigIntLiteral: v(4), - dynamicImport: v(11), - dynamicImportInWorker: major ? false : undefined, - module: v(11) - }; - } - ], - [ - "nwjs[X[.Y]] / node-webkit[X[.Y]]", - "NW.js in version X.Y.", - /^(?:nwjs|node-webkit)(\d+(?:\.(\d+))?)?$/, - (major, minor) => { - const v = versionDependent(major, minor); - // see https://node.green/ + https://github.com/nwjs/nw.js/blob/nw48/CHANGELOG.md - return { - node: true, - web: true, - nwjs: true, - webworker: null, - browser: false, - electron: false, - - global: true, - nodeBuiltins: true, - document: false, - importScriptsInWorker: false, - fetchWasm: false, - importScripts: false, - require: false, - - globalThis: v(0, 43), - const: v(0, 15), - templateLiteral: v(0, 13), - optionalChaining: v(0, 44), - arrowFunction: v(0, 15), - forOf: v(0, 13), - destructuring: v(0, 15), - bigIntLiteral: v(0, 32), - dynamicImport: v(0, 43), - dynamicImportInWorker: major ? false : undefined, - module: v(0, 43) - }; } - ], - [ - "esX", - "EcmaScript in this version. Examples: es2020, es5.", - /^es(\d+)$/, - version => { - let v = +version; - if (v < 1000) v = v + 2009; - return { - const: v >= 2015, - templateLiteral: v >= 2015, - optionalChaining: v >= 2020, - arrowFunction: v >= 2015, - forOf: v >= 2015, - destructuring: v >= 2015, - module: v >= 2015, - globalThis: v >= 2020, - bigIntLiteral: v >= 2020, - dynamicImport: v >= 2020, - dynamicImportInWorker: v >= 2020 - }; - } - ] -]; -/** - * @param {string} target the target - * @param {string} context the context directory - * @returns {TargetProperties} target properties - */ -const getTargetProperties = (target, context) => { - for (const [, , regExp, handler] of TARGETS) { - const match = regExp.exec(target); - if (match) { - const [, ...args] = match; - const result = handler(...args, context); - if (result) return result; - } - } - throw new Error( - `Unknown target '${target}'. The following targets are supported:\n${TARGETS.map( - ([name, description]) => `* ${name}: ${description}` - ).join("\n")}` - ); -}; + super(message); -const mergeTargetProperties = targetProperties => { - const keys = new Set(); - for (const tp of targetProperties) { - for (const key of Object.keys(tp)) { - keys.add(key); - } - } - const result = {}; - for (const key of keys) { - let hasTrue = false; - let hasFalse = false; - for (const tp of targetProperties) { - const value = tp[key]; - switch (value) { - case true: - hasTrue = true; - break; - case false: - hasFalse = true; - break; - } - } - if (hasTrue || hasFalse) - result[key] = hasFalse && hasTrue ? null : hasTrue ? true : false; + this.name = "ModuleNotFoundError"; + this.details = err.details; + this.module = module; + this.error = err; + this.loc = loc; } - return /** @type {TargetProperties} */ (result); -}; - -/** - * @param {string[]} targets the targets - * @param {string} context the context directory - * @returns {TargetProperties} target properties - */ -const getTargetsProperties = (targets, context) => { - return mergeTargetProperties( - targets.map(t => getTargetProperties(t, context)) - ); -}; +} -exports.getDefaultTarget = getDefaultTarget; -exports.getTargetProperties = getTargetProperties; -exports.getTargetsProperties = getTargetsProperties; +module.exports = ModuleNotFoundError; /***/ }), -/***/ 64813: +/***/ 58443: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr + Author Tobias Koppers @sokra */ -const Dependency = __webpack_require__(54912); +const WebpackError = __webpack_require__(53799); const makeSerializable = __webpack_require__(33032); -/** @typedef {import("./ContainerEntryModule").ExposeOptions} ExposeOptions */ +const WASM_HEADER = Buffer.from([0x00, 0x61, 0x73, 0x6d]); -class ContainerEntryDependency extends Dependency { +class ModuleParseError extends WebpackError { /** - * @param {string} name entry name - * @param {[string, ExposeOptions][]} exposes list of exposed modules - * @param {string} shareScope name of the share scope + * @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(name, exposes, shareScope) { - super(); - this.name = name; - this.exposes = exposes; - this.shareScope = shareScope; - } + constructor(source, err, loaders, type) { + let message = "Module parse failed: " + (err && err.message); + let loc = undefined; - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - return `container-entry-${this.name}`; - } + 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"; + } - get type() { - return "container entry"; - } + if ( + err && + err.loc && + typeof err.loc === "object" && + typeof err.loc.line === "number" + ) { + var lineNumber = err.loc.line; - get category() { - return "esm"; - } -} - -makeSerializable( - ContainerEntryDependency, - "webpack/lib/container/ContainerEntryDependency" -); - -module.exports = ContainerEntryDependency; - - -/***/ }), - -/***/ 80580: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr -*/ + 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; + } -const { OriginalSource, RawSource } = __webpack_require__(51255); -const AsyncDependenciesBlock = __webpack_require__(47736); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const StaticExportsDependency = __webpack_require__(91418); -const makeSerializable = __webpack_require__(33032); -const ContainerExposedDependency = __webpack_require__(72374); + super(message); -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */ + this.name = "ModuleParseError"; + this.loc = loc; + this.error = err; + } -/** - * @typedef {Object} ExposeOptions - * @property {string[]} import requests to exposed modules (last one is exported) - * @property {string} name custom chunk name for the exposed module - */ + serialize(context) { + const { write } = context; -const SOURCE_TYPES = new Set(["javascript"]); + write(this.error); -class ContainerEntryModule extends Module { - /** - * @param {string} name container entry name - * @param {[string, ExposeOptions][]} exposes list of exposed modules - * @param {string} shareScope name of the share scope - */ - constructor(name, exposes, shareScope) { - super("javascript/dynamic", null); - this._name = name; - this._exposes = exposes; - this._shareScope = shareScope; + super.serialize(context); } - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return SOURCE_TYPES; - } + deserialize(context) { + const { read } = context; - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return `container entry (${this._shareScope}) ${JSON.stringify( - this._exposes - )}`; - } + this.error = read(); - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return `container entry`; + super.deserialize(context); } +} - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - return `${this.layer ? `(${this.layer})/` : ""}webpack/container/entry/${ - this._name - }`; - } +makeSerializable(ModuleParseError, "webpack/lib/ModuleParseError"); - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - return callback(null, !this.buildMeta); - } +module.exports = ModuleParseError; - /** - * @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 = { - strict: true, - topLevelDeclarations: new Set(["moduleMap", "get", "init"]) - }; - this.buildMeta.exportsType = "namespace"; - this.clearDependenciesAndBlocks(); +/***/ }), - for (const [name, options] of this._exposes) { - const block = new AsyncDependenciesBlock( - { - name: options.name - }, - { name }, - options.import[options.import.length - 1] - ); - let idx = 0; - for (const request of options.import) { - const dep = new ContainerExposedDependency(name, request); - dep.loc = { - name, - index: idx++ - }; +/***/ 36418: +/***/ (function(module) { - block.addDependency(dep); - } - this.addBlock(block); - } - this.addDependency(new StaticExportsDependency(["get", "init"], false)); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - callback(); - } - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration({ moduleGraph, chunkGraph, runtimeTemplate }) { - const sources = new Map(); - const runtimeRequirements = new Set([ - RuntimeGlobals.definePropertyGetters, - RuntimeGlobals.hasOwnProperty, - RuntimeGlobals.exports - ]); - const getters = []; - for (const block of this.blocks) { - const { dependencies } = block; +class ModuleProfile { + constructor() { + this.startTime = Date.now(); - const modules = dependencies.map(dependency => { - const dep = /** @type {ContainerExposedDependency} */ (dependency); - return { - name: dep.exposedName, - module: moduleGraph.getModule(dep), - request: dep.userRequest - }; - }); + this.factoryStartTime = 0; + this.factoryEndTime = 0; + this.factory = 0; + this.factoryParallelismFactor = 0; - let str; + this.restoringStartTime = 0; + this.restoringEndTime = 0; + this.restoring = 0; + this.restoringParallelismFactor = 0; - if (modules.some(m => !m.module)) { - str = runtimeTemplate.throwMissingModuleErrorBlock({ - request: modules.map(m => m.request).join(", ") - }); - } else { - str = `return ${runtimeTemplate.blockPromise({ - block, - message: "", - chunkGraph, - runtimeRequirements - })}.then(${runtimeTemplate.returningFunction( - runtimeTemplate.returningFunction( - `(${modules - .map(({ module, request }) => - runtimeTemplate.moduleRaw({ - module, - chunkGraph, - request, - weak: false, - runtimeRequirements - }) - ) - .join(", ")})` - ) - )});`; - } + this.integrationStartTime = 0; + this.integrationEndTime = 0; + this.integration = 0; + this.integrationParallelismFactor = 0; - getters.push( - `${JSON.stringify(modules[0].name)}: ${runtimeTemplate.basicFunction( - "", - str - )}` - ); - } + this.buildingStartTime = 0; + this.buildingEndTime = 0; + this.building = 0; + this.buildingParallelismFactor = 0; - const source = Template.asString([ - `var moduleMap = {`, - Template.indent(getters.join(",\n")), - "};", - `var get = ${runtimeTemplate.basicFunction("module, getScope", [ - `${RuntimeGlobals.currentRemoteGetScope} = getScope;`, - // reusing the getScope variable to avoid creating a new var (and module is also used later) - "getScope = (", - Template.indent([ - `${RuntimeGlobals.hasOwnProperty}(moduleMap, module)`, - Template.indent([ - "? moduleMap[module]()", - `: Promise.resolve().then(${runtimeTemplate.basicFunction( - "", - "throw new Error('Module \"' + module + '\" does not exist in container.');" - )})` - ]) - ]), - ");", - `${RuntimeGlobals.currentRemoteGetScope} = undefined;`, - "return getScope;" - ])};`, - `var init = ${runtimeTemplate.basicFunction("shareScope, initScope", [ - `if (!${RuntimeGlobals.shareScopeMap}) return;`, - `var name = ${JSON.stringify(this._shareScope)}`, - `var oldScope = ${RuntimeGlobals.shareScopeMap}[name];`, - `if(oldScope && oldScope !== shareScope) throw new Error("Container initialization failed as it has already been initialized with a different share scope");`, - `${RuntimeGlobals.shareScopeMap}[name] = shareScope;`, - `return ${RuntimeGlobals.initializeSharing}(name, initScope);` - ])};`, - "", - "// This exports getters to disallow modifications", - `${RuntimeGlobals.definePropertyGetters}(exports, {`, - Template.indent([ - `get: ${runtimeTemplate.returningFunction("get")},`, - `init: ${runtimeTemplate.returningFunction("init")}` - ]), - "});" - ]); + this.storingStartTime = 0; + this.storingEndTime = 0; + this.storing = 0; + this.storingParallelismFactor = 0; - sources.set( - "javascript", - this.useSourceMap || this.useSimpleSourceMap - ? new OriginalSource(source, "webpack/container-entry") - : new RawSource(source) - ); + this.additionalFactoryTimes = undefined; + this.additionalFactories = 0; + this.additionalFactoriesParallelismFactor = 0; - return { - sources, - runtimeRequirements - }; + /** @deprecated */ + this.additionalIntegration = 0; } - /** - * @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; + markFactoryStart() { + this.factoryStartTime = Date.now(); } - serialize(context) { - const { write } = context; - write(this._name); - write(this._exposes); - write(this._shareScope); - super.serialize(context); + markFactoryEnd() { + this.factoryEndTime = Date.now(); + this.factory = this.factoryEndTime - this.factoryStartTime; } - static deserialize(context) { - const { read } = context; - const obj = new ContainerEntryModule(read(), read(), read()); - obj.deserialize(context); - return obj; + markRestoringStart() { + this.restoringStartTime = Date.now(); } -} - -makeSerializable( - ContainerEntryModule, - "webpack/lib/container/ContainerEntryModule" -); -module.exports = ContainerEntryModule; - - -/***/ }), + markRestoringEnd() { + this.restoringEndTime = Date.now(); + this.restoring = this.restoringEndTime - this.restoringStartTime; + } -/***/ 76398: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + markIntegrationStart() { + this.integrationStartTime = Date.now(); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr -*/ + 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; + } -const ModuleFactory = __webpack_require__(51010); -const ContainerEntryModule = __webpack_require__(80580); + markStoringStart() { + this.storingStartTime = Date.now(); + } -/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */ + markStoringEnd() { + this.storingEndTime = Date.now(); + this.storing = this.storingEndTime - this.storingStartTime; + } -module.exports = class ContainerEntryModuleFactory extends ModuleFactory { + // This depends on timing so we ignore it for coverage + /* istanbul ignore next */ /** - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * Merge this profile into another one + * @param {ModuleProfile} realProfile the profile to merge into * @returns {void} */ - create({ dependencies: [dependency] }, callback) { - const dep = /** @type {ContainerEntryDependency} */ (dependency); - callback(null, { - module: new ContainerEntryModule(dep.name, dep.exposes, dep.shareScope) + mergeInto(realProfile) { + realProfile.additionalFactories = this.factory; + (realProfile.additionalFactoryTimes = + realProfile.additionalFactoryTimes || []).push({ + start: this.factoryStartTime, + end: this.factoryEndTime }); } -}; +} + +module.exports = ModuleProfile; /***/ }), -/***/ 72374: +/***/ 94560: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr + Author Tobias Koppers @sokra */ -const ModuleDependency = __webpack_require__(80321); -const makeSerializable = __webpack_require__(33032); - -class ContainerExposedDependency extends ModuleDependency { - /** - * @param {string} exposedName public name - * @param {string} request request to module - */ - constructor(exposedName, request) { - super(request); - this.exposedName = exposedName; - } - - get type() { - return "container exposed"; - } +const WebpackError = __webpack_require__(53799); - get category() { - return "esm"; - } +/** @typedef {import("./Module")} Module */ +class ModuleRestoreError extends WebpackError { /** - * @returns {string | null} an identifier to merge equal requests + * @param {Module} module module tied to dependency + * @param {string | Error} err error thrown */ - getResourceIdentifier() { - return `exposed dependency ${this.exposedName}=${this.request}`; - } + 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); + } - serialize(context) { - context.write(this.exposedName); - super.serialize(context); - } + super(message); - deserialize(context) { - this.exposedName = context.read(); - super.deserialize(context); + this.name = "ModuleRestoreError"; + this.details = details; + this.module = module; + this.error = err; } } -makeSerializable( - ContainerExposedDependency, - "webpack/lib/container/ContainerExposedDependency" -); - -module.exports = ContainerExposedDependency; +module.exports = ModuleRestoreError; /***/ }), -/***/ 9244: +/***/ 59001: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr + Author Tobias Koppers @sokra */ -const createSchemaValidation = __webpack_require__(32540); -const ContainerEntryDependency = __webpack_require__(64813); -const ContainerEntryModuleFactory = __webpack_require__(76398); -const ContainerExposedDependency = __webpack_require__(72374); -const { parseOptions } = __webpack_require__(3083); - -/** @typedef {import("../../declarations/plugins/container/ContainerPlugin").ContainerPluginOptions} ContainerPluginOptions */ -/** @typedef {import("../Compiler")} Compiler */ - -const validate = createSchemaValidation( - __webpack_require__(9504), - () => __webpack_require__(84899), - { - name: "Container Plugin", - baseDataPath: "options" - } -); - -const PLUGIN_NAME = "ContainerPlugin"; - -class ContainerPlugin { - /** - * @param {ContainerPluginOptions} options options - */ - constructor(options) { - validate(options); +const WebpackError = __webpack_require__(53799); - this._options = { - name: options.name, - shareScope: options.shareScope || "default", - library: options.library || { - type: "var", - name: options.name - }, - runtime: options.runtime, - filename: options.filename || undefined, - exposes: parseOptions( - options.exposes, - item => ({ - import: Array.isArray(item) ? item : [item], - name: undefined - }), - item => ({ - import: Array.isArray(item.import) ? item.import : [item.import], - name: item.name || undefined - }) - ) - }; - } +/** @typedef {import("./Module")} Module */ +class ModuleStoreError extends WebpackError { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {Module} module module tied to dependency + * @param {string | Error} err error thrown */ - apply(compiler) { - const { name, exposes, shareScope, filename, library, runtime } = - this._options; - - compiler.options.output.enabledLibraryTypes.push(library.type); - - compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => { - const dep = new ContainerEntryDependency(name, exposes, shareScope); - dep.loc = { name }; - compilation.addEntry( - compilation.options.context, - dep, - { - name, - filename, - runtime, - library - }, - error => { - if (error) return callback(error); - callback(); - } - ); - }); + 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); + } - compiler.hooks.thisCompilation.tap( - PLUGIN_NAME, - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - ContainerEntryDependency, - new ContainerEntryModuleFactory() - ); + super(message); - compilation.dependencyFactories.set( - ContainerExposedDependency, - normalModuleFactory - ); - } - ); + this.name = "ModuleStoreError"; + this.details = details; + this.module = module; + this.error = err; } } -module.exports = ContainerPlugin; +module.exports = ModuleStoreError; /***/ }), -/***/ 95757: +/***/ 62677: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy + Author Tobias Koppers @sokra */ -const ExternalsPlugin = __webpack_require__(6652); -const RuntimeGlobals = __webpack_require__(16475); -const createSchemaValidation = __webpack_require__(32540); -const FallbackDependency = __webpack_require__(57764); -const FallbackItemDependency = __webpack_require__(29593); -const FallbackModuleFactory = __webpack_require__(4112); -const RemoteModule = __webpack_require__(62916); -const RemoteRuntimeModule = __webpack_require__(88288); -const RemoteToExternalDependency = __webpack_require__(14389); -const { parseOptions } = __webpack_require__(3083); +const util = __webpack_require__(73837); +const memoize = __webpack_require__(78676); -/** @typedef {import("../../declarations/plugins/container/ContainerReferencePlugin").ContainerReferencePluginOptions} ContainerReferencePluginOptions */ -/** @typedef {import("../../declarations/plugins/container/ContainerReferencePlugin").RemotesConfig} RemotesConfig */ -/** @typedef {import("../Compiler")} Compiler */ +/** @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 validate = createSchemaValidation( - __webpack_require__(95122), - () => - __webpack_require__(66681), - { - name: "Container Reference Plugin", - baseDataPath: "options" - } +const getJavascriptModulesPlugin = memoize(() => + __webpack_require__(89464) ); -const slashCode = "/".charCodeAt(0); - -class ContainerReferencePlugin { - /** - * @param {ContainerReferencePluginOptions} options options - */ - constructor(options) { - validate(options); - - this._remoteType = options.remoteType; - this._remotes = parseOptions( - options.remotes, - item => ({ - external: Array.isArray(item) ? item : [item], - shareScope: options.shareScope || "default" - }), - item => ({ - external: Array.isArray(item.external) - ? item.external - : [item.external], - shareScope: item.shareScope || options.shareScope || "default" - }) - ); - } - +// TODO webpack 6: remove this class +class ModuleTemplate { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {Compilation} compilation the compilation */ - apply(compiler) { - const { _remotes: remotes, _remoteType: remoteType } = this; - - /** @type {Record} */ - const remoteExternals = {}; - for (const [key, config] of remotes) { - let i = 0; - for (const external of config.external) { - if (external.startsWith("internal ")) continue; - remoteExternals[ - `webpack/container/reference/${key}${i ? `/fallback-${i}` : ""}` - ] = external; - i++; - } - } - - new ExternalsPlugin(remoteType, remoteExternals).apply(compiler); - - compiler.hooks.compilation.tap( - "ContainerReferencePlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - RemoteToExternalDependency, - normalModuleFactory - ); - - compilation.dependencyFactories.set( - FallbackItemDependency, - normalModuleFactory - ); - - compilation.dependencyFactories.set( - FallbackDependency, - new FallbackModuleFactory() - ); - - normalModuleFactory.hooks.factorize.tap( - "ContainerReferencePlugin", - data => { - if (!data.request.includes("!")) { - for (const [key, config] of remotes) { - if ( - data.request.startsWith(`${key}`) && - (data.request.length === key.length || - data.request.charCodeAt(key.length) === slashCode) - ) { - return new RemoteModule( - data.request, - config.external.map((external, i) => - external.startsWith("internal ") - ? external.slice(9) - : `webpack/container/reference/${key}${ - i ? `/fallback-${i}` : "" - }` - ), - `.${data.request.slice(key.length)}`, - config.shareScope - ); - } - } - } - } - ); - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("ContainerReferencePlugin", (chunk, set) => { - set.add(RuntimeGlobals.module); - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.hasOwnProperty); - set.add(RuntimeGlobals.initializeSharing); - set.add(RuntimeGlobals.shareScopeMap); - compilation.addRuntimeModule(chunk, new RemoteRuntimeModule()); - }); + 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" + ) } - ); + }); } } -module.exports = ContainerReferencePlugin; +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; /***/ }), -/***/ 57764: +/***/ 11234: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -66920,55 +59995,65 @@ module.exports = ContainerReferencePlugin; -const Dependency = __webpack_require__(54912); +const { cleanUp } = __webpack_require__(59985); +const WebpackError = __webpack_require__(53799); const makeSerializable = __webpack_require__(33032); -class FallbackDependency extends Dependency { - constructor(requests) { - super(); - this.requests = requests; - } - +class ModuleWarning extends WebpackError { /** - * @returns {string | null} an identifier to merge equal requests + * @param {Error} warning error thrown + * @param {{from?: string|null}} info additional info */ - getResourceIdentifier() { - return `fallback ${this.requests.join(" ")}`; - } + constructor(warning, { from = null } = {}) { + let message = "Module Warning"; - get type() { - return "fallback"; - } + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } - get category() { - return "esm"; + 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; } serialize(context) { const { write } = context; - write(this.requests); + + write(this.warning); + super.serialize(context); } - static deserialize(context) { + deserialize(context) { const { read } = context; - const obj = new FallbackDependency(read()); - obj.deserialize(context); - return obj; + + this.warning = read(); + + super.deserialize(context); } } -makeSerializable( - FallbackDependency, - "webpack/lib/container/FallbackDependency" -); +makeSerializable(ModuleWarning, "webpack/lib/ModuleWarning"); -module.exports = FallbackDependency; +module.exports = ModuleWarning; /***/ }), -/***/ 29593: +/***/ 33370: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -66979,529 +60064,881 @@ module.exports = FallbackDependency; -const ModuleDependency = __webpack_require__(80321); -const makeSerializable = __webpack_require__(33032); - -class FallbackItemDependency extends ModuleDependency { - constructor(request) { - super(request); - } - - get type() { - return "fallback item"; - } - - get category() { - return "esm"; - } -} - -makeSerializable( - FallbackItemDependency, - "webpack/lib/container/FallbackItemDependency" -); - -module.exports = FallbackItemDependency; - - -/***/ }), - -/***/ 82886: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy -*/ - +const asyncLib = __webpack_require__(78175); +const { SyncHook, MultiHook } = __webpack_require__(41242); +const ConcurrentCompilationError = __webpack_require__(95735); +const MultiStats = __webpack_require__(24170); +const MultiWatching = __webpack_require__(81128); +const ArrayQueue = __webpack_require__(41792); -const { RawSource } = __webpack_require__(51255); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const makeSerializable = __webpack_require__(33032); -const FallbackItemDependency = __webpack_require__(29593); +/** @template T @typedef {import("tapable").AsyncSeriesHook} AsyncSeriesHook */ +/** @template T @template R @typedef {import("tapable").SyncBailHook} SyncBailHook */ +/** @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 */ -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** + * @template T + * @callback Callback + * @param {(Error | null)=} err + * @param {T=} result + */ -const TYPES = new Set(["javascript"]); -const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); +/** + * @callback RunWithDependenciesHandler + * @param {Compiler} compiler + * @param {Callback} callback + */ -class FallbackModule extends Module { - /** - * @param {string[]} requests list of requests to choose one - */ - constructor(requests) { - super("fallback-module"); - this.requests = requests; - this._identifier = `fallback ${this.requests.join(" ")}`; - } +/** + * @typedef {Object} MultiCompilerOptions + * @property {number=} parallelism how many Compilers are allows to run at the same time in parallel + */ +module.exports = class MultiCompiler { /** - * @returns {string} a unique identifier of the module + * @param {Compiler[] | Record} compilers child compilers + * @param {MultiCompilerOptions} options options */ - identifier() { - return this._identifier; - } + constructor(compilers, options) { + if (!Array.isArray(compilers)) { + compilers = Object.keys(compilers).map(name => { + compilers[name].name = name; + return compilers[name]; + }); + } - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return this._identifier; + this.hooks = Object.freeze({ + /** @type {SyncHook<[MultiStats]>} */ + done: new SyncHook(["stats"]), + /** @type {MultiHook>} */ + invalid: new MultiHook(compilers.map(c => c.hooks.invalid)), + /** @type {MultiHook>} */ + run: new MultiHook(compilers.map(c => c.hooks.run)), + /** @type {SyncHook<[]>} */ + watchClose: new SyncHook([]), + /** @type {MultiHook>} */ + watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)), + /** @type {MultiHook>} */ + infrastructureLog: new MultiHook( + compilers.map(c => c.hooks.infrastructureLog) + ) + }); + this.compilers = compilers; + /** @type {MultiCompilerOptions} */ + this._options = { + parallelism: options.parallelism || Infinity + }; + /** @type {WeakMap} */ + 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; + 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)); + } + }); + 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 {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @param {InputFileSystem} value the new input file system */ - libIdent(options) { - return `${this.layer ? `(${this.layer})/` : ""}webpack/container/fallback/${ - this.requests[0] - }/and ${this.requests.length - 1} more`; + set inputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.inputFileSystem = value; + } } /** - * @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 + * @param {OutputFileSystem} value the new output file system */ - chunkCondition(chunk, { chunkGraph }) { - return chunkGraph.getNumberOfEntryModules(chunk) > 0; + set outputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.outputFileSystem = value; + } } /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} + * @param {WatchFileSystem} value the new watch file system */ - needBuild(context, callback) { - callback(null, !this.buildInfo); + set watchFileSystem(value) { + for (const compiler of this.compilers) { + compiler.watchFileSystem = value; + } } /** - * @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} + * @param {IntermediateFileSystem} value the new intermediate file system */ - build(options, compilation, resolver, fs, callback) { - this.buildMeta = {}; - this.buildInfo = { - strict: true - }; - - this.clearDependenciesAndBlocks(); - for (const request of this.requests) - this.addDependency(new FallbackItemDependency(request)); + set intermediateFileSystem(value) { + for (const compiler of this.compilers) { + compiler.intermediateFileSystem = value; + } + } - callback(); + getInfrastructureLogger(name) { + return this.compilers[0].getInfrastructureLogger(name); } /** - * @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) + * @param {Compiler} compiler the child compiler + * @param {string[]} dependencies its dependencies + * @returns {void} */ - size(type) { - return this.requests.length * 5 + 42; + setDependencies(compiler, dependencies) { + this.dependencies.set(compiler, dependencies); } /** - * @returns {Set} types available (do not mutate) + * @param {Callback} callback signals when the validation is complete + * @returns {boolean} true if the dependencies are valid */ - getSourceTypes() { - return TYPES; + 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 /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result + * @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} callback the compiler's handler + * @returns {void} */ - codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { - const ids = this.dependencies.map(dep => - chunkGraph.getModuleId(moduleGraph.getModule(dep)) - ); - const code = Template.asString([ - `var ids = ${JSON.stringify(ids)};`, - "var error, result, i = 0;", - `var loop = ${runtimeTemplate.basicFunction("next", [ - "while(i < ids.length) {", - Template.indent([ - "try { next = __webpack_require__(ids[i++]); } catch(e) { return handleError(e); }", - "if(next) return next.then ? next.then(handleResult, handleError) : handleResult(next);" - ]), - "}", - "if(error) throw error;" - ])}`, - `var handleResult = ${runtimeTemplate.basicFunction("result", [ - "if(result) return result;", - "return loop();" - ])};`, - `var handleError = ${runtimeTemplate.basicFunction("e", [ - "error = e;", - "return loop();" - ])};`, - "module.exports = loop();" - ]); - const sources = new Map(); - sources.set("javascript", new RawSource(code)); - return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS }; - } - - serialize(context) { - const { write } = context; - write(this.requests); - super.serialize(context); + 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); } - static deserialize(context) { - const { read } = context; - const obj = new FallbackModule(read()); - obj.deserialize(context); - return obj; - } -} + /** + * @template SetupResult + * @param {function(Compiler, number, Callback, function(): boolean, function(): void, function(): void): SetupResult} setup setup a single compiler + * @param {function(Compiler, SetupResult, Callback): void} run run/continue a single compiler + * @param {Callback} callback callback when all compilers are done, result includes Stats of all changed compilers + * @returns {SetupResult[]} result of setup + */ + _runGraph(setup, run, callback) { + /** @typedef {{ compiler: Compiler, setupResult: SetupResult, result: Stats, state: "pending" | "blocked" | "queued" | "starting" | "running" | "running-outdated" | "done", children: Node[], parents: Node[] }} Node */ -makeSerializable(FallbackModule, "webpack/lib/container/FallbackModule"); + // State transitions for nodes: + // -> blocked (initial) + // blocked -> starting [running++] (when all parents done) + // queued -> starting [running++] (when processing the queue) + // starting -> running (when run has been called) + // running -> done [running--] (when compilation is done) + // done -> pending (when invalidated from file change) + // pending -> blocked [add to queue] (when invalidated from aggregated changes) + // done -> blocked [add to queue] (when invalidated, from parent invalidation) + // running -> running-outdated (when invalidated, either from change or parent invalidation) + // running-outdated -> blocked [running--] (when compilation is done) -module.exports = FallbackModule; + /** @type {Node[]} */ + const nodes = this.compilers.map(compiler => ({ + compiler, + setupResult: undefined, + result: undefined, + state: "blocked", + children: [], + parents: [] + })); + /** @type {Map} */ + 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); + } + } + /** @type {ArrayQueue} */ + 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) { + if (child.state === "blocked") queue.enqueue(child); + } + } else if (node.state === "running-outdated") { + node.state = "blocked"; + queue.enqueue(node); + } + processQueue(); + }; + /** + * @param {Node} node node + * @returns {void} + */ + const nodeInvalidFromParent = node => { + if (node.state === "done") { + node.state = "blocked"; + } else if (node.state === "running") { + node.state = "running-outdated"; + } + for (const child of node.children) { + nodeInvalidFromParent(child); + } + }; + /** + * @param {Node} node node + * @returns {void} + */ + const nodeInvalid = node => { + if (node.state === "done") { + node.state = "pending"; + } else if (node.state === "running") { + node.state = "running-outdated"; + } + for (const child of node.children) { + nodeInvalidFromParent(child); + } + }; + /** + * @param {Node} node node + * @returns {void} + */ + const nodeChange = node => { + nodeInvalid(node); + if (node.state === "pending") { + node.state = "blocked"; + } + if (node.state === "blocked") { + queue.enqueue(node); + processQueue(); + } + }; + const setupResults = []; + nodes.forEach((node, i) => { + setupResults.push( + (node.setupResult = setup( + node.compiler, + i, + nodeDone.bind(null, node), + () => node.state !== "starting" && node.state !== "running", + () => nodeChange(node), + () => nodeInvalid(node) + )) + ); + }); + let processing = true; + const processQueue = () => { + if (processing) return; + processing = true; + process.nextTick(processQueueWorker); + }; + const processQueueWorker = () => { + while (running < parallelism && queue.length > 0 && !errored) { + const node = queue.dequeue(); + if ( + node.state === "queued" || + (node.state === "blocked" && + node.parents.every(p => p.state === "done")) + ) { + running++; + node.state = "starting"; + run(node.compiler, node.setupResult, nodeDone.bind(null, node)); + node.state = "running"; + } + } + processing = false; + if ( + !errored && + running === 0 && + nodes.every(node => node.state === "done") + ) { + const stats = []; + for (const node of nodes) { + const result = node.result; + if (result) { + node.result = undefined; + stats.push(result); + } + } + if (stats.length > 0) { + callback(null, new MultiStats(stats)); + } + } + }; + processQueueWorker(); + return setupResults; + } -/***/ }), + /** + * @param {WatchOptions|WatchOptions[]} watchOptions the watcher's options + * @param {Callback} handler signals when the call finishes + * @returns {MultiWatching} a compiler watcher + */ + watch(watchOptions, handler) { + if (this.running) { + return handler(new ConcurrentCompilationError()); + } + this.running = true; -/***/ 4112: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (this.validateDependencies(handler)) { + const watchings = this._runGraph( + (compiler, idx, callback, isBlocked, setChanged, setInvalid) => { + const watching = compiler.watch( + Array.isArray(watchOptions) ? watchOptions[idx] : watchOptions, + callback + ); + if (watching) { + watching._onInvalid = setInvalid; + watching._onChange = setChanged; + watching._isBlocked = isBlocked; + } + return watching; + }, + (compiler, watching, callback) => { + if (compiler.watching !== watching) return; + if (!watching.running) watching.invalidate(); + }, + handler + ); + return new MultiWatching(watchings, this); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr -*/ + return new MultiWatching([], this); + } + /** + * @param {Callback} callback signals when the call finishes + * @returns {void} + */ + run(callback) { + if (this.running) { + return callback(new ConcurrentCompilationError()); + } + this.running = true; + if (this.validateDependencies(callback)) { + this._runGraph( + () => {}, + (compiler, setupResult, callback) => compiler.run(callback), + (err, stats) => { + this.running = false; -const ModuleFactory = __webpack_require__(51010); -const FallbackModule = __webpack_require__(82886); + if (callback !== undefined) { + return callback(err, stats); + } + } + ); + } + } -/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("./FallbackDependency")} FallbackDependency */ + purgeInputFileSystem() { + for (const compiler of this.compilers) { + if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { + compiler.inputFileSystem.purge(); + } + } + } -module.exports = class FallbackModuleFactory extends ModuleFactory { /** - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * @param {Callback} callback signals when the compiler closes * @returns {void} */ - create({ dependencies: [dependency] }, callback) { - const dep = /** @type {FallbackDependency} */ (dependency); - callback(null, { - module: new FallbackModule(dep.requests) - }); + close(callback) { + asyncLib.each( + this.compilers, + (compiler, callback) => { + compiler.close(callback); + }, + callback + ); } }; /***/ }), -/***/ 30569: +/***/ 24170: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy + Author Tobias Koppers @sokra */ -const isValidExternalsType = __webpack_require__(62142); -const SharePlugin = __webpack_require__(26335); -const createSchemaValidation = __webpack_require__(32540); -const ContainerPlugin = __webpack_require__(9244); -const ContainerReferencePlugin = __webpack_require__(95757); +const identifierUtils = __webpack_require__(82186); -/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ExternalsType} ExternalsType */ -/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ModuleFederationPluginOptions} ModuleFederationPluginOptions */ -/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").Shared} Shared */ -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("./Stats")} Stats */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").KnownStatsCompilation} KnownStatsCompilation */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ -const validate = createSchemaValidation( - __webpack_require__(7467), - () => __webpack_require__(82601), - { - name: "Module Federation Plugin", - baseDataPath: "options" +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; } -); -class ModuleFederationPlugin { + + get hash() { + return this.stats.map(stat => stat.hash).join(""); + } + /** - * @param {ModuleFederationPluginOptions} options options + * @returns {boolean} true if a child compilation encountered an error */ - constructor(options) { - validate(options); + hasErrors() { + return this.stats.some(stat => stat.hasErrors()); + } - this._options = options; + /** + * @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 + }; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {any} options stats options + * @returns {StatsCompilation} json output */ - apply(compiler) { - const { _options: options } = this; - const library = options.library || { type: "var", name: options.name }; - const remoteType = - options.remoteType || - (options.library && isValidExternalsType(options.library.type) - ? /** @type {ExternalsType} */ (options.library.type) - : "script"); - if ( - library && - !compiler.options.output.enabledLibraryTypes.includes(library.type) - ) { - compiler.options.output.enabledLibraryTypes.push(library.type); + 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; } - compiler.hooks.afterPlugins.tap("ModuleFederationPlugin", () => { - if ( - options.exposes && - (Array.isArray(options.exposes) - ? options.exposes.length > 0 - : Object.keys(options.exposes).length > 0) - ) { - new ContainerPlugin({ - name: options.name, - library, - filename: options.filename, - runtime: options.runtime, - exposes: options.exposes - }).apply(compiler); + 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.remotes && - (Array.isArray(options.remotes) - ? options.remotes.length > 0 - : Object.keys(options.remotes).length > 0) - ) { - new ContainerReferencePlugin({ - remoteType, - remotes: options.remotes - }).apply(compiler); + } + 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.shared) { - new SharePlugin({ - shared: options.shared, - shareScope: options.shareScope - }).apply(compiler); + } + 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 = ModuleFederationPlugin; +module.exports = MultiStats; /***/ }), -/***/ 62916: +/***/ 81128: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy + Author Tobias Koppers @sokra */ -const { RawSource } = __webpack_require__(51255); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const FallbackDependency = __webpack_require__(57764); -const RemoteToExternalDependency = __webpack_require__(14389); +const asyncLib = __webpack_require__(78175); -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./MultiCompiler")} MultiCompiler */ +/** @typedef {import("./Watching")} Watching */ -const TYPES = new Set(["remote", "share-init"]); -const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); +/** + * @template T + * @callback Callback + * @param {(Error | null)=} err + * @param {T=} result + */ -class RemoteModule extends Module { +class MultiWatching { /** - * @param {string} request request string - * @param {string[]} externalRequests list of external requests to containers - * @param {string} internalRequest name of exposed module in container - * @param {string} shareScope the used share scope name + * @param {Watching[]} watchings child compilers' watchers + * @param {MultiCompiler} compiler the compiler */ - constructor(request, externalRequests, internalRequest, shareScope) { - super("remote-module"); - this.request = request; - this.externalRequests = externalRequests; - this.internalRequest = internalRequest; - this.shareScope = shareScope; - this._identifier = `remote (${shareScope}) ${this.externalRequests.join( - " " - )} ${this.internalRequest}`; + constructor(watchings, compiler) { + this.watchings = watchings; + this.compiler = compiler; } - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return this._identifier; + invalidate(callback) { + if (callback) { + asyncLib.each( + this.watchings, + (watching, callback) => watching.invalidate(callback), + callback + ); + } else { + for (const watching of this.watchings) { + watching.invalidate(); + } + } } - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return `remote ${this.request}`; + suspend() { + for (const watching of this.watchings) { + watching.suspend(); + } } - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - return `${this.layer ? `(${this.layer})/` : ""}webpack/container/remote/${ - this.request - }`; + resume() { + for (const watching of this.watchings) { + watching.resume(); + } } /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @param {Callback} callback signals when the watcher is closed * @returns {void} */ - needBuild(context, callback) { - callback(null, !this.buildInfo); + 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); + } + } + ); } +} - /** - * @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 = { - strict: true - }; +module.exports = MultiWatching; - this.clearDependenciesAndBlocks(); - if (this.externalRequests.length === 1) { - this.addDependency( - new RemoteToExternalDependency(this.externalRequests[0]) - ); - } else { - this.addDependency(new FallbackDependency(this.externalRequests)); - } - callback(); - } +/***/ }), - /** - * @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 6; - } +/***/ 50169: +/***/ (function(module) { - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) - */ - nameForCondition() { - return this.request; - } - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { - const module = moduleGraph.getModule(this.dependencies[0]); - const id = module && chunkGraph.getModuleId(module); - const sources = new Map(); - sources.set("remote", new RawSource("")); - const data = new Map(); - data.set("share-init", [ - { - shareScope: this.shareScope, - initStage: 20, - init: id === undefined ? "" : `initExternal(${JSON.stringify(id)});` - } - ]); - return { sources, data, runtimeRequirements: RUNTIME_REQUIREMENTS }; - } - serialize(context) { - const { write } = context; - write(this.request); - write(this.externalRequests); - write(this.internalRequest); - write(this.shareScope); - super.serialize(context); - } +/** @typedef {import("./Compiler")} Compiler */ - static deserialize(context) { - const { read } = context; - const obj = new RemoteModule(read(), read(), read(), read()); - obj.deserialize(context); - return obj; +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; + }); + }); } } -makeSerializable(RemoteModule, "webpack/lib/container/RemoteModule"); - -module.exports = RemoteModule; +module.exports = NoEmitOnErrorsPlugin; /***/ }), -/***/ 88288: +/***/ 80832: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -67512,565 +60949,458 @@ module.exports = RemoteModule; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); - -/** @typedef {import("./RemoteModule")} RemoteModule */ +const WebpackError = __webpack_require__(53799); -class RemoteRuntimeModule extends RuntimeModule { +module.exports = class NoModeWarning extends WebpackError { constructor() { - super("remotes loading"); - } + super(); - /** - * @returns {string} runtime code - */ - generate() { - const { compilation, chunkGraph } = this; - const { runtimeTemplate, moduleGraph } = compilation; - const chunkToRemotesMapping = {}; - const idToExternalAndNameMapping = {}; - for (const chunk of this.chunk.getAllAsyncChunks()) { - const modules = chunkGraph.getChunkModulesIterableBySourceType( - chunk, - "remote" - ); - if (!modules) continue; - const remotes = (chunkToRemotesMapping[chunk.id] = []); - for (const m of modules) { - const module = /** @type {RemoteModule} */ (m); - const name = module.internalRequest; - const id = chunkGraph.getModuleId(module); - const shareScope = module.shareScope; - const dep = module.dependencies[0]; - const externalModule = moduleGraph.getModule(dep); - const externalModuleId = - externalModule && chunkGraph.getModuleId(externalModule); - remotes.push(id); - idToExternalAndNameMapping[id] = [shareScope, name, externalModuleId]; - } - } - return Template.asString([ - `var chunkMapping = ${JSON.stringify( - chunkToRemotesMapping, - null, - "\t" - )};`, - `var idToExternalAndNameMapping = ${JSON.stringify( - idToExternalAndNameMapping, - null, - "\t" - )};`, - `${ - RuntimeGlobals.ensureChunkHandlers - }.remotes = ${runtimeTemplate.basicFunction("chunkId, promises", [ - `if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`, - Template.indent([ - `chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction("id", [ - `var getScope = ${RuntimeGlobals.currentRemoteGetScope};`, - "if(!getScope) getScope = [];", - "var data = idToExternalAndNameMapping[id];", - "if(getScope.indexOf(data) >= 0) return;", - "getScope.push(data);", - `if(data.p) return promises.push(data.p);`, - `var onError = ${runtimeTemplate.basicFunction("error", [ - 'if(!error) error = new Error("Container missing");', - 'if(typeof error.message === "string")', - Template.indent( - `error.message += '\\nwhile loading "' + data[1] + '" from ' + data[2];` - ), - `__webpack_modules__[id] = ${runtimeTemplate.basicFunction("", [ - "throw error;" - ])}`, - "data.p = 0;" - ])};`, - `var handleFunction = ${runtimeTemplate.basicFunction( - "fn, arg1, arg2, d, next, first", - [ - "try {", - Template.indent([ - "var promise = fn(arg1, arg2);", - "if(promise && promise.then) {", - Template.indent([ - `var p = promise.then(${runtimeTemplate.returningFunction( - "next(result, d)", - "result" - )}, onError);`, - `if(first) promises.push(data.p = p); else return p;` - ]), - "} else {", - Template.indent(["return next(promise, d, first);"]), - "}" - ]), - "} catch(error) {", - Template.indent(["onError(error);"]), - "}" - ] - )}`, - `var onExternal = ${runtimeTemplate.returningFunction( - `external ? handleFunction(${RuntimeGlobals.initializeSharing}, data[0], 0, external, onInitialized, first) : onError()`, - "external, _, first" - )};`, - `var onInitialized = ${runtimeTemplate.returningFunction( - `handleFunction(external.get, data[1], getScope, 0, onFactory, first)`, - "_, external, first" - )};`, - `var onFactory = ${runtimeTemplate.basicFunction("factory", [ - "data.p = 1;", - `__webpack_modules__[id] = ${runtimeTemplate.basicFunction( - "module", - ["module.exports = factory();"] - )}` - ])};`, - "handleFunction(__webpack_require__, data[2], 0, 0, onExternal, 1);" - ])});` - ]), - "}" - ])}` - ]); + 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/"; } -} - -module.exports = RemoteRuntimeModule; +}; /***/ }), -/***/ 14389: +/***/ 6325: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const ModuleDependency = __webpack_require__(80321); +const WebpackError = __webpack_require__(53799); const makeSerializable = __webpack_require__(33032); -class RemoteToExternalDependency extends ModuleDependency { - constructor(request) { - super(request); - } +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ - get type() { - return "remote to external"; - } +class NodeStuffInWebError extends WebpackError { + /** + * @param {DependencyLocation} loc loc + * @param {string} expression expression + * @param {string} description description + */ + constructor(loc, expression, description) { + super( + `${JSON.stringify( + expression + )} has been used, it will be undefined in next major version. +${description}` + ); - get category() { - return "esm"; + this.name = "NodeStuffInWebError"; + this.loc = loc; } } -makeSerializable( - RemoteToExternalDependency, - "webpack/lib/container/RemoteToExternalDependency" -); - -module.exports = RemoteToExternalDependency; - - -/***/ }), - -/***/ 3083: -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @template T @typedef {(string | Record)[] | Record} ContainerOptionsFormat */ - -/** - * @template T - * @template N - * @param {ContainerOptionsFormat} options options passed by the user - * @param {function(string | string[], string) : N} normalizeSimple normalize a simple item - * @param {function(T, string) : N} normalizeOptions normalize a complex item - * @param {function(string, N): void} fn processing function - * @returns {void} - */ -const process = (options, normalizeSimple, normalizeOptions, fn) => { - const array = items => { - for (const item of items) { - if (typeof item === "string") { - fn(item, normalizeSimple(item, item)); - } else if (item && typeof item === "object") { - object(item); - } else { - throw new Error("Unexpected options format"); - } - } - }; - const object = obj => { - for (const [key, value] of Object.entries(obj)) { - if (typeof value === "string" || Array.isArray(value)) { - fn(key, normalizeSimple(value, key)); - } else { - fn(key, normalizeOptions(value, key)); - } - } - }; - if (!options) { - return; - } else if (Array.isArray(options)) { - array(options); - } else if (typeof options === "object") { - object(options); - } else { - throw new Error("Unexpected options format"); - } -}; - -/** - * @template T - * @template R - * @param {ContainerOptionsFormat} options options passed by the user - * @param {function(string | string[], string) : R} normalizeSimple normalize a simple item - * @param {function(T, string) : R} normalizeOptions normalize a complex item - * @returns {[string, R][]} parsed options - */ -const parseOptions = (options, normalizeSimple, normalizeOptions) => { - /** @type {[string, R][]} */ - const items = []; - process(options, normalizeSimple, normalizeOptions, (key, value) => { - items.push([key, value]); - }); - return items; -}; - -/** - * @template T - * @param {string} scope scope name - * @param {ContainerOptionsFormat} options options passed by the user - * @returns {Record} options to spread or pass - */ -const scope = (scope, options) => { - /** @type {Record} */ - const obj = {}; - process( - options, - item => /** @type {string | string[] | T} */ (item), - item => /** @type {string | string[] | T} */ (item), - (key, value) => { - obj[ - key.startsWith("./") ? `${scope}${key.slice(1)}` : `${scope}/${key}` - ] = value; - } - ); - return obj; -}; +makeSerializable(NodeStuffInWebError, "webpack/lib/NodeStuffInWebError"); -exports.parseOptions = parseOptions; -exports.scope = scope; +module.exports = NodeStuffInWebError; /***/ }), -/***/ 91254: +/***/ 95287: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov + Author Tobias Koppers @sokra */ -const { ReplaceSource, RawSource, ConcatSource } = __webpack_require__(51255); -const { UsageState } = __webpack_require__(63686); -const Generator = __webpack_require__(93401); +const NodeStuffInWebError = __webpack_require__(6325); const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../util/Hash")} Hash */ +const CachedConstDependency = __webpack_require__(57403); +const ConstDependency = __webpack_require__(76911); +const { + evaluateToString, + expressionIsUnsupported +} = __webpack_require__(93998); +const { relative } = __webpack_require__(17139); +const { parseResource } = __webpack_require__(82186); -const TYPES = new Set(["javascript"]); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -class CssExportsGenerator extends Generator { - constructor() { - super(); +class NodeStuffPlugin { + constructor(options) { + this.options = options; } - // TODO add getConcatenationBailoutReason to allow concatenation - // but how to make it have a module id - /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate(module, generateContext) { - const source = new ReplaceSource(new RawSource("")); - const initFragments = []; - const cssExports = new Map(); + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "NodeStuffPlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + if (parserOptions.node === false) return; - generateContext.runtimeRequirements.add(RuntimeGlobals.module); + let localOptions = options; + if (parserOptions.node) { + localOptions = { ...localOptions, ...parserOptions.node }; + } - const runtimeRequirements = new Set(); + if (localOptions.global !== false) { + const withWarning = localOptions.global === "warn"; + 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 templateContext = { - runtimeTemplate: generateContext.runtimeTemplate, - dependencyTemplates: generateContext.dependencyTemplates, - moduleGraph: generateContext.moduleGraph, - chunkGraph: generateContext.chunkGraph, - module, - runtime: generateContext.runtime, - runtimeRequirements: runtimeRequirements, - concatenationScope: generateContext.concatenationScope, - codeGenerationResults: generateContext.codeGenerationResults, - initFragments, - cssExports - }; + // TODO webpack 6 remove + if (withWarning) { + parser.state.module.addWarning( + new NodeStuffInWebError( + dep.loc, + "global", + "The global namespace object is Node.js feature and doesn't present in browser." + ) + ); + } + }); + } - const handleDependency = dependency => { - const constructor = /** @type {new (...args: any[]) => Dependency} */ ( - dependency.constructor - ); - const template = generateContext.dependencyTemplates.get(constructor); - if (!template) { - throw new Error( - "No template for dependency: " + dependency.constructor.name - ); - } + const setModuleConstant = (expressionName, fn, warning) => { + 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); - template.apply(dependency, source, templateContext); - }; - module.dependencies.forEach(handleDependency); + // TODO webpack 6 remove + if (warning) { + parser.state.module.addWarning( + new NodeStuffInWebError(dep.loc, expressionName, warning) + ); + } - if (generateContext.concatenationScope) { - const source = new ConcatSource(); - const usedIdentifiers = new Set(); - for (const [k, v] of cssExports) { - let identifier = Template.toIdentifier(k); - let i = 0; - while (usedIdentifiers.has(identifier)) { - identifier = Template.toIdentifier(k + i); - } - usedIdentifiers.add(identifier); - generateContext.concatenationScope.registerExport(k, identifier); - source.add( - `${ - generateContext.runtimeTemplate.supportsConst ? "const" : "var" - } ${identifier} = ${JSON.stringify(v)};\n` - ); - } - return source; - } else { - const otherUsed = - generateContext.moduleGraph - .getExportsInfo(module) - .otherExportsInfo.getUsed(generateContext.runtime) !== - UsageState.Unused; - if (otherUsed) { - generateContext.runtimeRequirements.add( - RuntimeGlobals.makeNamespaceObject - ); - } - return new RawSource( - `${otherUsed ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${ - module.moduleArgument - }.exports = {\n${Array.from( - cssExports, - ([k, v]) => `\t${JSON.stringify(k)}: ${JSON.stringify(v)}` - ).join(",\n")}\n}${otherUsed ? ")" : ""};` - ); - } - } + return true; + }); + }; - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; - } + const setConstant = (expressionName, value, warning) => + setModuleConstant(expressionName, () => value, warning); - /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module - */ - getSize(module, type) { - return 42; - } + const context = compiler.context; + if (localOptions.__filename) { + switch (localOptions.__filename) { + case "mock": + setConstant("__filename", "/index.js"); + break; + case "warn-mock": + setConstant( + "__filename", + "/index.js", + "The __filename is Node.js feature and doesn't present in browser." + ); + break; + case true: + setModuleConstant("__filename", module => + relative(compiler.inputFileSystem, context, module.resource) + ); + break; + } - /** - * @param {Hash} hash hash that will be modified - * @param {UpdateHashContext} updateHashContext context for updating hash - */ - updateHash(hash, { module }) {} + 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) { + switch (localOptions.__dirname) { + case "mock": + setConstant("__dirname", "/"); + break; + case "warn-mock": + setConstant( + "__dirname", + "/", + "The __dirname is Node.js feature and doesn't present in browser." + ); + break; + case true: + setModuleConstant("__dirname", module => + relative(compiler.inputFileSystem, context, module.context) + ); + break; + } + + 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 = CssExportsGenerator; +module.exports = NodeStuffPlugin; /***/ }), -/***/ 46061: +/***/ 39: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov + Author Tobias Koppers @sokra */ -const { ReplaceSource } = __webpack_require__(51255); -const Generator = __webpack_require__(93401); -const InitFragment = __webpack_require__(55870); +const parseJson = __webpack_require__(15235); +const { getContext, runLoaders } = __webpack_require__(68318); +const querystring = __webpack_require__(63477); +const { HookMap, SyncHook, AsyncSeriesBailHook } = __webpack_require__(41242); +const { + CachedSource, + OriginalSource, + RawSource, + SourceMapSource +} = __webpack_require__(51255); +const Compilation = __webpack_require__(85720); +const HookWebpackError = __webpack_require__(11351); +const Module = __webpack_require__(73208); +const ModuleBuildError = __webpack_require__(21305); +const ModuleError = __webpack_require__(23744); +const ModuleGraphConnection = __webpack_require__(40639); +const ModuleParseError = __webpack_require__(58443); +const ModuleWarning = __webpack_require__(11234); const RuntimeGlobals = __webpack_require__(16475); +const UnhandledSchemeError = __webpack_require__(68099); +const WebpackError = __webpack_require__(53799); +const formatLocation = __webpack_require__(16734); +const LazySet = __webpack_require__(38938); +const { isSubset } = __webpack_require__(93347); +const { getScheme } = __webpack_require__(54500); +const { + compareLocations, + concatComparators, + compareSelect, + keepOriginalOrder +} = __webpack_require__(29579); +const createHash = __webpack_require__(49835); +const { createFakeHook } = __webpack_require__(64518); +const { join } = __webpack_require__(17139); +const { + contextify, + absolutify, + makePathsRelative +} = __webpack_require__(82186); +const makeSerializable = __webpack_require__(33032); +const memoize = __webpack_require__(78676); /** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../util/Hash")} Hash */ - -const TYPES = new Set(["css"]); - -class CssGenerator extends Generator { - constructor() { - super(); - } +/** @typedef {import("../declarations/LoaderContext").NormalModuleLoaderContext} NormalModuleLoaderContext */ +/** @typedef {import("../declarations/WebpackOptions").Mode} Mode */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Generator")} Generator */ +/** @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("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ +/** @typedef {import("./Parser")} Parser */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./logging/Logger").Logger} WebpackLogger */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ - /** - * @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 originalSource = module.originalSource(); - const source = new ReplaceSource(originalSource); - const initFragments = []; - const cssExports = new Map(); +/** + * @typedef {Object} SourceMap + * @property {number} version + * @property {string[]} sources + * @property {string} mappings + * @property {string=} file + * @property {string=} sourceRoot + * @property {string[]=} sourcesContent + * @property {string[]=} names + */ - generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules); +const getInvalidDependenciesModuleWarning = memoize(() => + __webpack_require__(68257) +); +const getValidate = memoize(() => (__webpack_require__(38476).validate)); - const templateContext = { - runtimeTemplate: generateContext.runtimeTemplate, - dependencyTemplates: generateContext.dependencyTemplates, - moduleGraph: generateContext.moduleGraph, - chunkGraph: generateContext.chunkGraph, - module, - runtime: generateContext.runtime, - runtimeRequirements: generateContext.runtimeRequirements, - concatenationScope: generateContext.concatenationScope, - codeGenerationResults: generateContext.codeGenerationResults, - initFragments, - cssExports - }; +const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/; - const handleDependency = dependency => { - const constructor = /** @type {new (...args: any[]) => Dependency} */ ( - dependency.constructor - ); - const template = generateContext.dependencyTemplates.get(constructor); - if (!template) { - throw new Error( - "No template for dependency: " + dependency.constructor.name - ); - } +/** + * @typedef {Object} LoaderItem + * @property {string} loader + * @property {any} options + * @property {string?} ident + * @property {string?} type + */ - template.apply(dependency, source, templateContext); - }; - module.dependencies.forEach(handleDependency); - if (module.presentationalDependencies !== undefined) - module.presentationalDependencies.forEach(handleDependency); +/** + * @param {string} context absolute context path + * @param {string} source a source path + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} new source path + */ +const contextifySourceUrl = (context, source, associatedObjectForCache) => { + if (source.startsWith("webpack://")) return source; + return `webpack://${makePathsRelative( + context, + source, + associatedObjectForCache + )}`; +}; - if (cssExports.size > 0) { - const data = generateContext.getData(); - data.set("css-exports", cssExports); - } +/** + * @param {string} context absolute context path + * @param {SourceMap} sourceMap a source map + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {SourceMap} new source map + */ +const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => { + if (!Array.isArray(sourceMap.sources)) return sourceMap; + const { sourceRoot } = sourceMap; + /** @type {function(string): string} */ + const mapper = !sourceRoot + ? source => source + : sourceRoot.endsWith("/") + ? source => + source.startsWith("/") + ? `${sourceRoot.slice(0, -1)}${source}` + : `${sourceRoot}${source}` + : source => + source.startsWith("/") + ? `${sourceRoot}${source}` + : `${sourceRoot}/${source}`; + const newSources = sourceMap.sources.map(source => + contextifySourceUrl(context, mapper(source), associatedObjectForCache) + ); + return { + ...sourceMap, + file: "x", + sourceRoot: undefined, + sources: newSources + }; +}; - return InitFragment.addToSource(source, initFragments, generateContext); +/** + * @param {string | Buffer} input the input + * @returns {string} the converted string + */ +const asString = input => { + if (Buffer.isBuffer(input)) { + return input.toString("utf-8"); } + return input; +}; - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; +/** + * @param {string | Buffer} input the input + * @returns {Buffer} the converted buffer + */ +const asBuffer = input => { + if (!Buffer.isBuffer(input)) { + return Buffer.from(input, "utf-8"); } + return input; +}; - /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module - */ - getSize(module, type) { - const originalSource = module.originalSource(); - - if (!originalSource) { - return 0; - } +class NonErrorEmittedError extends WebpackError { + constructor(error) { + super(); - return originalSource.size(); + this.name = "NonErrorEmittedError"; + this.message = "(Emitted value instead of an instance of Error) " + error; } - - /** - * @param {Hash} hash hash that will be modified - * @param {UpdateHashContext} updateHashContext context for updating hash - */ - updateHash(hash, { module }) {} } -module.exports = CssGenerator; - - -/***/ }), - -/***/ 80806: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { SyncWaterfallHook } = __webpack_require__(6967); -const Compilation = __webpack_require__(85720); -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); -const compileBooleanMatcher = __webpack_require__(29404); -const { chunkHasCss } = __webpack_require__(47283); - -/** @typedef {import("../Chunk")} Chunk */ +makeSerializable( + NonErrorEmittedError, + "webpack/lib/NormalModule", + "NonErrorEmittedError" +); /** - * @typedef {Object} JsonpCompilationPluginHooks - * @property {SyncWaterfallHook<[string, Chunk]>} createStylesheet + * @typedef {Object} NormalModuleCompilationHooks + * @property {SyncHook<[object, NormalModule]>} loader + * @property {SyncHook<[LoaderItem[], NormalModule, object]>} beforeLoaders + * @property {SyncHook<[NormalModule]>} beforeParse + * @property {SyncHook<[NormalModule]>} beforeSnapshot + * @property {HookMap>} readResourceForScheme + * @property {HookMap>} readResource + * @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild */ -/** @type {WeakMap} */ +/** @type {WeakMap} */ const compilationHooksMap = new WeakMap(); -class CssLoadingRuntimeModule extends RuntimeModule { +class NormalModule extends Module { /** * @param {Compilation} compilation the compilation - * @returns {JsonpCompilationPluginHooks} hooks + * @returns {NormalModuleCompilationHooks} the attached hooks */ static getCompilationHooks(compilation) { if (!(compilation instanceof Compilation)) { @@ -68081,888 +61411,1204 @@ class CssLoadingRuntimeModule extends RuntimeModule { let hooks = compilationHooksMap.get(compilation); if (hooks === undefined) { hooks = { - createStylesheet: new SyncWaterfallHook(["source", "chunk"]) + loader: new SyncHook(["loaderContext", "module"]), + beforeLoaders: new SyncHook(["loaders", "module", "loaderContext"]), + beforeParse: new SyncHook(["module"]), + beforeSnapshot: new SyncHook(["module"]), + // TODO webpack 6 deprecate + readResourceForScheme: new HookMap(scheme => { + const hook = hooks.readResource.for(scheme); + return createFakeHook( + /** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer>} */ ({ + tap: (options, fn) => + hook.tap(options, loaderContext => + fn(loaderContext.resource, loaderContext._module) + ), + tapAsync: (options, fn) => + hook.tapAsync(options, (loaderContext, callback) => + fn(loaderContext.resource, loaderContext._module, callback) + ), + tapPromise: (options, fn) => + hook.tapPromise(options, loaderContext => + fn(loaderContext.resource, loaderContext._module) + ) + }) + ); + }), + readResource: new HookMap( + () => new AsyncSeriesBailHook(["loaderContext"]) + ), + needBuild: new AsyncSeriesBailHook(["module", "context"]) }; compilationHooksMap.set(compilation, hooks); } return hooks; } - constructor(runtimeRequirements, runtimeOptions) { - super("css loading", 10); + /** + * @param {Object} options options object + * @param {string=} options.layer an optional layer in which the module is + * @param {string} options.type module type + * @param {string} options.request request string + * @param {string} options.userRequest request intended by user (without loaders from config) + * @param {string} options.rawRequest request without resolving + * @param {LoaderItem[]} options.loaders list of loaders + * @param {string} options.resource path + query of the real resource + * @param {Record=} options.resourceResolveData resource resolve data + * @param {string} options.context context directory for resolving + * @param {string | undefined} options.matchResource path + query of the matched resource (virtual) + * @param {Parser} options.parser the parser used + * @param {object} options.parserOptions the options of the parser used + * @param {Generator} options.generator the generator used + * @param {object} options.generatorOptions the options of the generator used + * @param {Object} options.resolveOptions options used for resolving requests from this module + */ + constructor({ + layer, + type, + request, + userRequest, + rawRequest, + loaders, + resource, + resourceResolveData, + context, + matchResource, + parser, + parserOptions, + generator, + generatorOptions, + resolveOptions + }) { + super(type, context || getContext(resource), layer); - this._runtimeRequirements = runtimeRequirements; - this.runtimeOptions = runtimeOptions; + // Info from Factory + /** @type {string} */ + this.request = request; + /** @type {string} */ + this.userRequest = userRequest; + /** @type {string} */ + this.rawRequest = rawRequest; + /** @type {boolean} */ + this.binary = /^(asset|webassembly)\b/.test(type); + /** @type {Parser} */ + this.parser = parser; + this.parserOptions = parserOptions; + /** @type {Generator} */ + this.generator = generator; + this.generatorOptions = generatorOptions; + /** @type {string} */ + this.resource = resource; + this.resourceResolveData = resourceResolveData; + /** @type {string | undefined} */ + this.matchResource = matchResource; + /** @type {LoaderItem[]} */ + this.loaders = loaders; + if (resolveOptions !== undefined) { + // already declared in super class + this.resolveOptions = resolveOptions; + } + + // Info from Build + /** @type {(WebpackError | null)=} */ + this.error = null; + /** @private @type {Source=} */ + this._source = null; + /** @private @type {Map | undefined} **/ + this._sourceSizes = undefined; + /** @private @type {Set} */ + this._sourceTypes = undefined; + + // Cache + this._lastSuccessfulBuildMeta = {}; + this._forceBuild = true; + this._isEvaluatingSideEffects = false; + /** @type {WeakSet | undefined} */ + this._addedSideEffectsBailout = undefined; } /** - * @returns {string} runtime code + * @returns {string} a unique identifier of the module */ - generate() { - const { compilation, chunk, _runtimeRequirements } = this; - const { - chunkGraph, - runtimeTemplate, - outputOptions: { - crossOriginLoading, - uniqueName, - chunkLoadTimeout: loadTimeout + identifier() { + if (this.layer === null) { + if (this.type === "javascript/auto") { + return this.request; + } else { + return `${this.type}|${this.request}`; } - } = compilation; - const fn = RuntimeGlobals.ensureChunkHandlers; - const conditionMap = chunkGraph.getChunkConditionMap( - chunk, - (chunk, chunkGraph) => - !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css") - ); - const hasCssMatcher = compileBooleanMatcher(conditionMap); - - const withLoading = - _runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) && - hasCssMatcher !== false; - const withHmr = _runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const initialChunkIdsWithCss = new Set(); - const initialChunkIdsWithoutCss = new Set(); - for (const c of chunk.getAllInitialChunks()) { - (chunkHasCss(c, chunkGraph) - ? initialChunkIdsWithCss - : initialChunkIdsWithoutCss - ).add(c.id); - } - - if (!withLoading && !withHmr && initialChunkIdsWithCss.size === 0) { - return null; + } else { + return `${this.type}|${this.request}|${this.layer}`; } + } - const { createStylesheet } = - CssLoadingRuntimeModule.getCompilationHooks(compilation); - - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_css` - : undefined; + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.userRequest); + } - const code = Template.asString([ - "link = document.createElement('link');", - uniqueName - ? 'link.setAttribute("data-webpack", uniqueName + ":" + key);' - : "", - "link.setAttribute(loadingAttribute, 1);", - 'link.rel = "stylesheet";', - "link.href = url;", - crossOriginLoading - ? Template.asString([ - "if (link.src.indexOf(window.location.origin + '/') !== 0) {", - Template.indent( - `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` - ), - "}" - ]) - : "" - ]); + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + let ident = contextify( + options.context, + this.userRequest, + options.associatedObjectForCache + ); + if (this.layer) ident = `(${this.layer})/${ident}`; + return ident; + } - const cc = str => str.charCodeAt(0); + /** + * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + */ + nameForCondition() { + const resource = this.matchResource || this.resource; + const idx = resource.indexOf("?"); + if (idx >= 0) return resource.substr(0, idx); + return resource; + } - return Template.asString([ - "// object to store loaded and loading chunks", - "// undefined = chunk not loaded, null = chunk preloaded/prefetched", - "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", - `var installedChunks = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{${Array.from( - initialChunkIdsWithoutCss, - id => `${JSON.stringify(id)}:0` - ).join(",")}};`, - "", - uniqueName - ? `var uniqueName = ${JSON.stringify( - runtimeTemplate.outputOptions.uniqueName - )};` - : "// data-webpack is not used as build has no uniqueName", - `var loadCssChunkData = ${runtimeTemplate.basicFunction( - "target, link, chunkId", - [ - `var data, token = "", token2, exports = {}, exportsWithId = [], exportsWithDashes = [], ${ - withHmr ? "moduleIds = [], " : "" - }i = 0, cc = 1;`, - "try { if(!link) link = loadStylesheet(chunkId); data = link.sheet.cssRules; data = data[data.length - 1].style; } catch(e) { data = getComputedStyle(document.head); }", - `data = data.getPropertyValue(${ - uniqueName - ? runtimeTemplate.concatenation( - "--webpack-", - { expr: "uniqueName" }, - "-", - { expr: "chunkId" } - ) - : runtimeTemplate.concatenation("--webpack-", { expr: "chunkId" }) - });`, - "if(!data) return [];", - "for(; cc; i++) {", - Template.indent([ - "cc = data.charCodeAt(i);", - `if(cc == ${cc("(")}) { token2 = token; token = ""; }`, - `else if(cc == ${cc( - ")" - )}) { exports[token2.replace(/^_/, "")] = token.replace(/^_/, ""); token = ""; }`, - `else if(cc == ${cc("/")} || cc == ${cc( - "%" - )}) { token = token.replace(/^_/, ""); exports[token] = token; exportsWithId.push(token); if(cc == ${cc( - "%" - )}) exportsWithDashes.push(token); token = ""; }`, - `else if(!cc || cc == ${cc( - "," - )}) { token = token.replace(/^_/, ""); exportsWithId.forEach(${runtimeTemplate.expressionFunction( - `exports[x] = ${ - uniqueName - ? runtimeTemplate.concatenation( - { expr: "uniqueName" }, - "-", - { expr: "token" }, - "-", - { expr: "exports[x]" } - ) - : runtimeTemplate.concatenation({ expr: "token" }, "-", { - expr: "exports[x]" - }) - }`, - "x" - )}); exportsWithDashes.forEach(${runtimeTemplate.expressionFunction( - `exports[x] = "--" + exports[x]`, - "x" - )}); ${ - RuntimeGlobals.makeNamespaceObject - }(exports); target[token] = (${runtimeTemplate.basicFunction( - "exports, module", - `module.exports = exports;` - )}).bind(null, exports); ${ - withHmr ? "moduleIds.push(token); " : "" - }token = ""; exports = {}; exportsWithId.length = 0; }`, - `else if(cc == ${cc("\\")}) { token += data[++i] }`, - `else { token += data[i]; }` - ]), - "}", - `${ - withHmr ? `if(target == ${RuntimeGlobals.moduleFactories}) ` : "" - }installedChunks[chunkId] = 0;`, - withHmr ? "return moduleIds;" : "" - ] - )}`, - 'var loadingAttribute = "data-webpack-loading";', - `var loadStylesheet = ${runtimeTemplate.basicFunction( - "chunkId, url, done" + (withHmr ? ", hmr" : ""), - [ - 'var link, needAttach, key = "chunk-" + chunkId;', - withHmr ? "if(!hmr) {" : "", - 'var links = document.getElementsByTagName("link");', - "for(var i = 0; i < links.length; i++) {", - Template.indent([ - "var l = links[i];", - `if(l.rel == "stylesheet" && (${ - withHmr - ? 'l.href.startsWith(url) || l.getAttribute("href").startsWith(url)' - : 'l.href == url || l.getAttribute("href") == url' - }${ - uniqueName - ? ' || l.getAttribute("data-webpack") == uniqueName + ":" + key' - : "" - })) { link = l; break; }` - ]), - "}", - "if(!done) return link;", - withHmr ? "}" : "", - "if(!link) {", - Template.indent([ - "needAttach = true;", - createStylesheet.call(code, this.chunk) - ]), - "}", - `var onLinkComplete = ${runtimeTemplate.basicFunction( - "prev, event", - Template.asString([ - "link.onerror = link.onload = null;", - "link.removeAttribute(loadingAttribute);", - "clearTimeout(timeout);", - 'if(event && event.type != "load") link.parentNode.removeChild(link)', - "done(event);", - "if(prev) return prev(event);" - ]) - )};`, - "if(link.getAttribute(loadingAttribute)) {", - Template.indent([ - `var timeout = setTimeout(onLinkComplete.bind(null, undefined, { type: 'timeout', target: link }), ${loadTimeout});`, - "link.onerror = onLinkComplete.bind(null, link.onerror);", - "link.onload = onLinkComplete.bind(null, link.onload);" - ]), - "} else onLinkComplete(undefined, { type: 'load', target: link });", // We assume any existing stylesheet is render blocking - withHmr ? "hmr ? document.head.insertBefore(link, hmr) :" : "", - "needAttach && document.head.appendChild(link);", - "return link;" - ] - )};`, - initialChunkIdsWithCss.size > 2 - ? `${JSON.stringify( - Array.from(initialChunkIdsWithCss) - )}.forEach(loadCssChunkData.bind(null, ${ - RuntimeGlobals.moduleFactories - }, 0));` - : initialChunkIdsWithCss.size > 0 - ? `${Array.from( - initialChunkIdsWithCss, - id => - `loadCssChunkData(${ - RuntimeGlobals.moduleFactories - }, 0, ${JSON.stringify(id)});` - ).join("")}` - : "// no initial css", - "", - withLoading - ? Template.asString([ - `${fn}.css = ${runtimeTemplate.basicFunction( - "chunkId, promises", - hasCssMatcher !== false - ? [ - "// css chunk loading", - `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, - 'if(installedChunkData !== 0) { // 0 means "already installed".', - Template.indent([ - "", - '// a Promise means "currently loading".', - "if(installedChunkData) {", - Template.indent([ - "promises.push(installedChunkData[2]);" - ]), - "} else {", - Template.indent([ - hasCssMatcher === true - ? "if(true) { // all chunks have CSS" - : `if(${hasCssMatcher("chunkId")}) {`, - Template.indent([ - "// setup Promise in chunk cache", - `var promise = new Promise(${runtimeTemplate.expressionFunction( - `installedChunkData = installedChunks[chunkId] = [resolve, reject]`, - "resolve, reject" - )});`, - "promises.push(installedChunkData[2] = promise);", - "", - "// start chunk loading", - `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, - "// create error before stack unwound to get useful stacktrace later", - "var error = new Error();", - `var loadingEnded = ${runtimeTemplate.basicFunction( - "event", - [ - `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`, - Template.indent([ - "installedChunkData = installedChunks[chunkId];", - "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;", - "if(installedChunkData) {", - Template.indent([ - 'if(event.type !== "load") {', - Template.indent([ - "var errorType = event && event.type;", - "var realSrc = event && event.target && event.target.src;", - "error.message = 'Loading css chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", - "error.name = 'ChunkLoadError';", - "error.type = errorType;", - "error.request = realSrc;", - "installedChunkData[1](error);" - ]), - "} else {", - Template.indent([ - `loadCssChunkData(${RuntimeGlobals.moduleFactories}, link, chunkId);`, - "installedChunkData[0]();" - ]), - "}" - ]), - "}" - ]), - "}" - ] - )};`, - "var link = loadStylesheet(chunkId, url, loadingEnded);" - ]), - "} else installedChunks[chunkId] = 0;" - ]), - "}" - ]), - "}" - ] - : "installedChunks[chunkId] = 0;" - )};` - ]) - : "// no chunk loading", - "", - withHmr - ? Template.asString([ - "var oldTags = [];", - "var newTags = [];", - `var applyHandler = ${runtimeTemplate.basicFunction("options", [ - `return { dispose: ${runtimeTemplate.basicFunction( - "", - [] - )}, apply: ${runtimeTemplate.basicFunction("", [ - "var moduleIds = [];", - `newTags.forEach(${runtimeTemplate.expressionFunction( - "info[1].sheet.disabled = false", - "info" - )});`, - "while(oldTags.length) {", - Template.indent([ - "var oldTag = oldTags.pop();", - "if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);" - ]), - "}", - "while(newTags.length) {", - Template.indent([ - `var info = newTags.pop();`, - `var chunkModuleIds = loadCssChunkData(${RuntimeGlobals.moduleFactories}, info[1], info[0]);`, - `chunkModuleIds.forEach(${runtimeTemplate.expressionFunction( - "moduleIds.push(id)", - "id" - )});` - ]), - "}", - "return moduleIds;" - ])} };` - ])}`, - `var cssTextKey = ${runtimeTemplate.returningFunction( - `Array.from(link.sheet.cssRules, ${runtimeTemplate.returningFunction( - "r.cssText", - "r" - )}).join()`, - "link" - )}`, - `${ - RuntimeGlobals.hmrDownloadUpdateHandlers - }.css = ${runtimeTemplate.basicFunction( - "chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList", - [ - "applyHandlers.push(applyHandler);", - `chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [ - `var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, - `var url = ${RuntimeGlobals.publicPath} + filename;`, - "var oldTag = loadStylesheet(chunkId, url);", - "if(!oldTag) return;", - `promises.push(new Promise(${runtimeTemplate.basicFunction( - "resolve, reject", - [ - `var link = loadStylesheet(chunkId, url + (url.indexOf("?") < 0 ? "?" : "&") + "hmr=" + Date.now(), ${runtimeTemplate.basicFunction( - "event", - [ - 'if(event.type !== "load") {', - Template.indent([ - "var errorType = event && event.type;", - "var realSrc = event && event.target && event.target.src;", - "error.message = 'Loading css hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", - "error.name = 'ChunkLoadError';", - "error.type = errorType;", - "error.request = realSrc;", - "reject(error);" - ]), - "} else {", - Template.indent([ - "try { if(cssTextKey(oldTag) == cssTextKey(link)) { if(link.parentNode) link.parentNode.removeChild(link); return resolve(); } } catch(e) {}", - "var factories = {};", - "loadCssChunkData(factories, link, chunkId);", - `Object.keys(factories).forEach(${runtimeTemplate.expressionFunction( - "updatedModulesList.push(id)", - "id" - )})`, - "link.sheet.disabled = true;", - "oldTags.push(oldTag);", - "newTags.push([chunkId, link]);", - "resolve();" - ]), - "}" - ] - )}, oldTag);` - ] - )}));` - ])});` - ] - )}` - ]) - : "// no hmr" - ]); + /** + * 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 {NormalModule} */ (module); + this.binary = m.binary; + this.request = m.request; + this.userRequest = m.userRequest; + this.rawRequest = m.rawRequest; + this.parser = m.parser; + this.parserOptions = m.parserOptions; + this.generator = m.generator; + this.generatorOptions = m.generatorOptions; + this.resource = m.resource; + this.resourceResolveData = m.resourceResolveData; + this.context = m.context; + this.matchResource = m.matchResource; + this.loaders = m.loaders; } -} - -module.exports = CssLoadingRuntimeModule; - -/***/ }), + /** + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. + */ + cleanupForCache() { + // Make sure to cache types and sizes before cleanup when this module has been built + // They are accessed by the stats and we don't want them to crash after cleanup + // TODO reconsider this for webpack 6 + if (this.buildInfo) { + if (this._sourceTypes === undefined) this.getSourceTypes(); + for (const type of this._sourceTypes) { + this.size(type); + } + } + super.cleanupForCache(); + this.parser = undefined; + this.parserOptions = undefined; + this.generator = undefined; + this.generatorOptions = undefined; + } -/***/ 47283: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * Module should be unsafe cached. Get data that's needed for that. + * This data will be passed to restoreFromUnsafeCache later. + * @returns {object} cached data + */ + getUnsafeCacheData() { + const data = super.getUnsafeCacheData(); + data.parserOptions = this.parserOptions; + data.generatorOptions = this.generatorOptions; + return data; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { + this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); + } + /** + * restore unsafe cache data + * @param {object} unsafeCacheData data from getUnsafeCacheData + * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching + */ + _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { + super._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); + this.parserOptions = unsafeCacheData.parserOptions; + this.parser = normalModuleFactory.getParser(this.type, this.parserOptions); + this.generatorOptions = unsafeCacheData.generatorOptions; + this.generator = normalModuleFactory.getGenerator( + this.type, + this.generatorOptions + ); + // we assume the generator behaves identically and keep cached sourceTypes/Sizes + } + /** + * @param {string} context the compilation context + * @param {string} name the asset name + * @param {string} content the content + * @param {string | TODO} sourceMap an optional source map + * @param {Object=} associatedObjectForCache object for caching + * @returns {Source} the created source + */ + createSourceForAsset( + context, + name, + content, + sourceMap, + associatedObjectForCache + ) { + if (sourceMap) { + if ( + typeof sourceMap === "string" && + (this.useSourceMap || this.useSimpleSourceMap) + ) { + return new OriginalSource( + content, + contextifySourceUrl(context, sourceMap, associatedObjectForCache) + ); + } -const { ConcatSource } = __webpack_require__(51255); -const HotUpdateChunk = __webpack_require__(9597); -const RuntimeGlobals = __webpack_require__(16475); -const SelfModuleFactory = __webpack_require__(63560); -const CssExportDependency = __webpack_require__(76760); -const CssImportDependency = __webpack_require__(90542); -const CssLocalIdentifierDependency = __webpack_require__(92328); -const CssSelfLocalIdentifierDependency = __webpack_require__(29094); -const CssUrlDependency = __webpack_require__(70749); -const StaticExportsDependency = __webpack_require__(91418); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const createSchemaValidation = __webpack_require__(32540); -const createHash = __webpack_require__(49835); -const memoize = __webpack_require__(78676); -const CssExportsGenerator = __webpack_require__(91254); -const CssGenerator = __webpack_require__(46061); -const CssParser = __webpack_require__(98305); + if (this.useSourceMap) { + return new SourceMapSource( + content, + name, + contextifySourceMap(context, sourceMap, associatedObjectForCache) + ); + } + } -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").CssExperimentOptions} CssExperimentOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ + return new RawSource(content); + } -const getCssLoadingRuntimeModule = memoize(() => - __webpack_require__(80806) -); + /** + * @param {ResolverWithOptions} resolver a resolver + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {InputFileSystem} fs file system from reading + * @param {NormalModuleCompilationHooks} hooks the hooks + * @returns {NormalModuleLoaderContext} loader context + */ + _createLoaderContext(resolver, options, compilation, fs, hooks) { + const { requestShortener } = compilation.runtimeTemplate; + const getCurrentLoaderName = () => { + const currentLoader = this.getCurrentLoader(loaderContext); + if (!currentLoader) return "(not in loader scope)"; + return requestShortener.shorten(currentLoader.loader); + }; + const getResolveContext = () => { + return { + fileDependencies: { + add: d => loaderContext.addDependency(d) + }, + contextDependencies: { + add: d => loaderContext.addContextDependency(d) + }, + missingDependencies: { + add: d => loaderContext.addMissingDependency(d) + } + }; + }; + const getAbsolutify = memoize(() => + absolutify.bindCache(compilation.compiler.root) + ); + const getAbsolutifyInContext = memoize(() => + absolutify.bindContextCache(this.context, compilation.compiler.root) + ); + const getContextify = memoize(() => + contextify.bindCache(compilation.compiler.root) + ); + const getContextifyInContext = memoize(() => + contextify.bindContextCache(this.context, compilation.compiler.root) + ); + const utils = { + absolutify: (context, request) => { + return context === this.context + ? getAbsolutifyInContext()(request) + : getAbsolutify()(context, request); + }, + contextify: (context, request) => { + return context === this.context + ? getContextifyInContext()(request) + : getContextify()(context, request); + }, + createHash: type => { + return createHash(type || compilation.outputOptions.hashFunction); + } + }; + const loaderContext = { + version: 2, + getOptions: schema => { + const loader = this.getCurrentLoader(loaderContext); -const getSchema = name => { - const { definitions } = __webpack_require__(73342); - return { - definitions, - oneOf: [{ $ref: `#/definitions/${name}` }] - }; -}; + let { options } = loader; -const validateGeneratorOptions = createSchemaValidation( - __webpack_require__(59170), - () => getSchema("CssGeneratorOptions"), - { - name: "Css Modules Plugin", - baseDataPath: "parser" - } -); -const validateParserOptions = createSchemaValidation( - __webpack_require__(38542), - () => getSchema("CssParserOptions"), - { - name: "Css Modules Plugin", - baseDataPath: "parser" - } -); + if (typeof options === "string") { + if (options.substr(0, 1) === "{" && options.substr(-1) === "}") { + try { + options = parseJson(options); + } catch (e) { + throw new Error(`Cannot parse string options: ${e.message}`); + } + } else { + options = querystring.parse(options, "&", "=", { + maxKeys: 0 + }); + } + } -const escapeCss = (str, omitOptionalUnderscore) => { - const escaped = `${str}`.replace( - // cspell:word uffff - /[^a-zA-Z0-9_\u0081-\uffff-]/g, - s => `\\${s}` - ); - return !omitOptionalUnderscore && /^(?!--)[0-9_-]/.test(escaped) - ? `_${escaped}` - : escaped; -}; + if (options === null || options === undefined) { + options = {}; + } -const plugin = "CssModulesPlugin"; + if (schema) { + let name = "Loader"; + let baseDataPath = "options"; + let match; + if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) { + [, name, baseDataPath] = match; + } + getValidate()(schema, options, { + name, + baseDataPath + }); + } -class CssModulesPlugin { - /** - * @param {CssExperimentOptions} options options - */ - constructor({ exportsOnly = false }) { - this._exportsOnly = exportsOnly; - } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - plugin, - (compilation, { normalModuleFactory }) => { - const selfFactory = new SelfModuleFactory(compilation.moduleGraph); - compilation.dependencyFactories.set( - CssUrlDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - CssUrlDependency, - new CssUrlDependency.Template() - ); - compilation.dependencyTemplates.set( - CssLocalIdentifierDependency, - new CssLocalIdentifierDependency.Template() - ); - compilation.dependencyFactories.set( - CssSelfLocalIdentifierDependency, - selfFactory - ); - compilation.dependencyTemplates.set( - CssSelfLocalIdentifierDependency, - new CssSelfLocalIdentifierDependency.Template() - ); - compilation.dependencyTemplates.set( - CssExportDependency, - new CssExportDependency.Template() - ); - compilation.dependencyFactories.set( - CssImportDependency, - normalModuleFactory + return options; + }, + emitWarning: warning => { + if (!(warning instanceof Error)) { + warning = new NonErrorEmittedError(warning); + } + this.addWarning( + new ModuleWarning(warning, { + from: getCurrentLoaderName() + }) ); - compilation.dependencyTemplates.set( - CssImportDependency, - new CssImportDependency.Template() + }, + emitError: error => { + if (!(error instanceof Error)) { + error = new NonErrorEmittedError(error); + } + this.addError( + new ModuleError(error, { + from: getCurrentLoaderName() + }) ); - compilation.dependencyTemplates.set( - StaticExportsDependency, - new StaticExportsDependency.Template() + }, + getLogger: name => { + const currentLoader = this.getCurrentLoader(loaderContext); + return compilation.getLogger(() => + [currentLoader && currentLoader.loader, name, this.identifier()] + .filter(Boolean) + .join("|") ); - normalModuleFactory.hooks.createParser - .for("css") - .tap(plugin, parserOptions => { - validateParserOptions(parserOptions); - return new CssParser(); - }); - normalModuleFactory.hooks.createParser - .for("css/global") - .tap(plugin, parserOptions => { - validateParserOptions(parserOptions); - return new CssParser({ - allowPseudoBlocks: false, - allowModeSwitch: false - }); - }); - normalModuleFactory.hooks.createParser - .for("css/module") - .tap(plugin, parserOptions => { - validateParserOptions(parserOptions); - return new CssParser({ - defaultMode: "local" - }); - }); - normalModuleFactory.hooks.createGenerator - .for("css") - .tap(plugin, generatorOptions => { - validateGeneratorOptions(generatorOptions); - return this._exportsOnly - ? new CssExportsGenerator() - : new CssGenerator(); - }); - normalModuleFactory.hooks.createGenerator - .for("css/global") - .tap(plugin, generatorOptions => { - validateGeneratorOptions(generatorOptions); - return this._exportsOnly - ? new CssExportsGenerator() - : new CssGenerator(); - }); - normalModuleFactory.hooks.createGenerator - .for("css/module") - .tap(plugin, generatorOptions => { - validateGeneratorOptions(generatorOptions); - return this._exportsOnly - ? new CssExportsGenerator() - : new CssGenerator(); - }); - const orderedCssModulesPerChunk = new WeakMap(); - compilation.hooks.afterCodeGeneration.tap("CssModulesPlugin", () => { - const { chunkGraph } = compilation; - for (const chunk of compilation.chunks) { - if (CssModulesPlugin.chunkHasCss(chunk, chunkGraph)) { - orderedCssModulesPerChunk.set( - chunk, - this.getOrderedChunkCssModules(chunk, chunkGraph, compilation) + }, + resolve(context, request, callback) { + resolver.resolve({}, context, request, getResolveContext(), callback); + }, + getResolve(options) { + const child = options ? resolver.withOptions(options) : resolver; + return (context, request, callback) => { + if (callback) { + child.resolve({}, context, request, getResolveContext(), callback); + } else { + return new Promise((resolve, reject) => { + child.resolve( + {}, + context, + request, + getResolveContext(), + (err, result) => { + if (err) reject(err); + else resolve(result); + } ); - } - } - }); - compilation.hooks.contentHash.tap("CssModulesPlugin", chunk => { - const { - chunkGraph, - outputOptions: { - hashSalt, - hashDigest, - hashDigestLength, - hashFunction - } - } = compilation; - const modules = orderedCssModulesPerChunk.get(chunk); - if (modules === undefined) return; - const hash = createHash(hashFunction); - if (hashSalt) hash.update(hashSalt); - for (const module of modules) { - hash.update(chunkGraph.getModuleHash(module, chunk.runtime)); - } - const digest = /** @type {string} */ (hash.digest(hashDigest)); - chunk.contentHash.css = digest.substr(0, hashDigestLength); - }); - compilation.hooks.renderManifest.tap(plugin, (result, options) => { - const { chunkGraph } = compilation; - const { hash, chunk, codeGenerationResults } = options; - - if (chunk instanceof HotUpdateChunk) return result; - - const modules = orderedCssModulesPerChunk.get(chunk); - if (modules !== undefined) { - result.push({ - render: () => - this.renderChunk({ - chunk, - chunkGraph, - codeGenerationResults, - uniqueName: compilation.outputOptions.uniqueName, - modules - }), - filenameTemplate: CssModulesPlugin.getChunkFilenameTemplate( - chunk, - compilation.outputOptions - ), - pathOptions: { - hash, - runtime: chunk.runtime, - chunk, - contentHashType: "css" - }, - identifier: `css${chunk.id}`, - hash: chunk.contentHash.css }); } - return result; - }); - const enabledChunks = new WeakSet(); - const handler = (chunk, set) => { - if (enabledChunks.has(chunk)) { - return; - } - enabledChunks.add(chunk); + }; + }, + emitFile: (name, content, sourceMap, assetInfo) => { + if (!this.buildInfo.assets) { + this.buildInfo.assets = Object.create(null); + this.buildInfo.assetsInfo = new Map(); + } + this.buildInfo.assets[name] = this.createSourceForAsset( + options.context, + name, + content, + sourceMap, + compilation.compiler.root + ); + this.buildInfo.assetsInfo.set(name, assetInfo); + }, + addBuildDependency: dep => { + if (this.buildInfo.buildDependencies === undefined) { + this.buildInfo.buildDependencies = new LazySet(); + } + this.buildInfo.buildDependencies.add(dep); + }, + utils, + rootContext: options.context, + webpack: true, + sourceMap: !!this.useSourceMap, + mode: options.mode || "production", + _module: this, + _compilation: compilation, + _compiler: compilation.compiler, + fs: fs + }; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.getChunkCssFilename); - set.add(RuntimeGlobals.hasOwnProperty); - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.makeNamespaceObject); + Object.assign(loaderContext, options.loader); - const CssLoadingRuntimeModule = getCssLoadingRuntimeModule(); - compilation.addRuntimeModule(chunk, new CssLoadingRuntimeModule(set)); - }; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hasCssModules) - .tap(plugin, handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap(plugin, handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap(plugin, handler); - } - ); + hooks.loader.call(loaderContext, this); + + return loaderContext; } - getModulesInOrder(chunk, modules, compilation) { - if (!modules) return []; + getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) { + if ( + this.loaders && + this.loaders.length && + index < this.loaders.length && + index >= 0 && + this.loaders[index] + ) { + return this.loaders[index]; + } + return null; + } - const modulesList = [...modules]; + /** + * @param {string} context the compilation context + * @param {string | Buffer} content the content + * @param {string | TODO} sourceMap an optional source map + * @param {Object=} associatedObjectForCache object for caching + * @returns {Source} the created source + */ + createSource(context, content, sourceMap, associatedObjectForCache) { + if (Buffer.isBuffer(content)) { + return new RawSource(content); + } - // Get ordered list of modules per chunk group - // Lists are in reverse order to allow to use Array.pop() - const modulesByChunkGroup = Array.from(chunk.groupsIterable, chunkGroup => { - const sortedModules = modulesList - .map(module => { - return { - module, - index: chunkGroup.getModulePostOrderIndex(module) - }; - }) - .filter(item => item.index !== undefined) - .sort((a, b) => b.index - a.index) - .map(item => item.module); + // if there is no identifier return raw source + if (!this.identifier) { + return new RawSource(content); + } - return { list: sortedModules, set: new Set(sortedModules) }; - }); + // from here on we assume we have an identifier + const identifier = this.identifier(); - if (modulesByChunkGroup.length === 1) - return modulesByChunkGroup[0].list.reverse(); + if (this.useSourceMap && sourceMap) { + return new SourceMapSource( + content, + contextifySourceUrl(context, identifier, associatedObjectForCache), + contextifySourceMap(context, sourceMap, associatedObjectForCache) + ); + } - const compareModuleLists = ({ list: a }, { list: b }) => { - if (a.length === 0) { - return b.length === 0 ? 0 : 1; - } else { - if (b.length === 0) return -1; - return compareModulesByIdentifier(a[a.length - 1], b[b.length - 1]); - } - }; + if (this.useSourceMap || this.useSimpleSourceMap) { + return new OriginalSource( + content, + contextifySourceUrl(context, identifier, associatedObjectForCache) + ); + } - modulesByChunkGroup.sort(compareModuleLists); + return new RawSource(content); + } - const finalModules = []; + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {NormalModuleCompilationHooks} hooks the hooks + * @param {function((WebpackError | null)=): void} callback callback function + * @returns {void} + */ + _doBuild(options, compilation, resolver, fs, hooks, callback) { + const loaderContext = this._createLoaderContext( + resolver, + options, + compilation, + fs, + hooks + ); - for (;;) { - const failedModules = new Set(); - const list = modulesByChunkGroup[0].list; - if (list.length === 0) { - // done, everything empty - break; - } - let selectedModule = list[list.length - 1]; - let hasFailed = undefined; - outer: for (;;) { - for (const { list, set } of modulesByChunkGroup) { - if (list.length === 0) continue; - const lastModule = list[list.length - 1]; - if (lastModule === selectedModule) continue; - if (!set.has(selectedModule)) continue; - failedModules.add(selectedModule); - if (failedModules.has(lastModule)) { - // There is a conflict, try other alternatives - hasFailed = lastModule; - continue; - } - selectedModule = lastModule; - hasFailed = false; - continue outer; // restart + const processResult = (err, result) => { + if (err) { + if (!(err instanceof Error)) { + err = new NonErrorEmittedError(err); } - break; - } - if (hasFailed) { - // There is a not resolve-able conflict with the selectedModule - if (compilation) { - // TODO print better warning - compilation.warnings.push( - new Error( - `chunk ${ - chunk.name || chunk.id - }\nConflicting order between ${hasFailed.readableIdentifier( - compilation.requestShortener - )} and ${selectedModule.readableIdentifier( - compilation.requestShortener - )}` + const currentLoader = this.getCurrentLoader(loaderContext); + const error = new ModuleBuildError(err, { + from: + currentLoader && + compilation.runtimeTemplate.requestShortener.shorten( + currentLoader.loader ) - ); - } - selectedModule = hasFailed; - } - // Insert the selected module into the final modules list - finalModules.push(selectedModule); - // Remove the selected module from all lists - for (const { list, set } of modulesByChunkGroup) { - const lastModule = list[list.length - 1]; - if (lastModule === selectedModule) list.pop(); - else if (hasFailed && set.has(selectedModule)) { - const idx = list.indexOf(selectedModule); - if (idx >= 0) list.splice(idx, 1); - } + }); + return callback(error); } - modulesByChunkGroup.sort(compareModuleLists); - } - return finalModules; - } - getOrderedChunkCssModules(chunk, chunkGraph, compilation) { - return [ - ...this.getModulesInOrder( - chunk, - chunkGraph.getOrderedChunkModulesIterableBySourceType( - chunk, - "css-import", - compareModulesByIdentifier - ), - compilation - ), - ...this.getModulesInOrder( - chunk, - chunkGraph.getOrderedChunkModulesIterableBySourceType( - chunk, - "css", - compareModulesByIdentifier - ), - compilation - ) - ]; + const source = result[0]; + const sourceMap = result.length >= 1 ? result[1] : null; + const extraInfo = result.length >= 2 ? result[2] : null; + + if (!Buffer.isBuffer(source) && typeof source !== "string") { + const currentLoader = this.getCurrentLoader(loaderContext, 0); + const err = new Error( + `Final loader (${ + currentLoader + ? compilation.runtimeTemplate.requestShortener.shorten( + currentLoader.loader + ) + : "unknown" + }) didn't return a Buffer or String` + ); + const error = new ModuleBuildError(err); + return callback(error); + } + + this._source = this.createSource( + options.context, + this.binary ? asBuffer(source) : asString(source), + sourceMap, + compilation.compiler.root + ); + if (this._sourceSizes !== undefined) this._sourceSizes.clear(); + this._ast = + typeof extraInfo === "object" && + extraInfo !== null && + extraInfo.webpackAST !== undefined + ? extraInfo.webpackAST + : null; + return callback(); + }; + + this.buildInfo.fileDependencies = new LazySet(); + this.buildInfo.contextDependencies = new LazySet(); + this.buildInfo.missingDependencies = new LazySet(); + this.buildInfo.cacheable = true; + + try { + hooks.beforeLoaders.call(this.loaders, this, loaderContext); + } catch (err) { + processResult(err); + return; + } + + if (this.loaders.length > 0) { + this.buildInfo.buildDependencies = new LazySet(); + } + + runLoaders( + { + resource: this.resource, + loaders: this.loaders, + context: loaderContext, + processResource: (loaderContext, resourcePath, callback) => { + const resource = loaderContext.resource; + const scheme = getScheme(resource); + hooks.readResource + .for(scheme) + .callAsync(loaderContext, (err, result) => { + if (err) return callback(err); + if (typeof result !== "string" && !result) { + return callback(new UnhandledSchemeError(scheme, resource)); + } + return callback(null, result); + }); + } + }, + (err, result) => { + // Cleanup loaderContext to avoid leaking memory in ICs + loaderContext._compilation = + loaderContext._compiler = + loaderContext._module = + loaderContext.fs = + undefined; + + if (!result) { + this.buildInfo.cacheable = false; + return processResult( + err || new Error("No result from loader-runner processing"), + null + ); + } + this.buildInfo.fileDependencies.addAll(result.fileDependencies); + this.buildInfo.contextDependencies.addAll(result.contextDependencies); + this.buildInfo.missingDependencies.addAll(result.missingDependencies); + for (const loader of this.loaders) { + this.buildInfo.buildDependencies.add(loader.loader); + } + this.buildInfo.cacheable = this.buildInfo.cacheable && result.cacheable; + processResult(err, result.result); + } + ); } - renderChunk({ - uniqueName, - chunk, - chunkGraph, - codeGenerationResults, - modules - }) { - const source = new ConcatSource(); - const metaData = []; - for (const module of modules) { - try { - const codeGenResult = codeGenerationResults.get(module, chunk.runtime); + /** + * @param {WebpackError} error the error + * @returns {void} + */ + markModuleAsErrored(error) { + // Restore build meta from successful build to keep importing state + this.buildMeta = { ...this._lastSuccessfulBuildMeta }; + this.error = error; + this.addError(error); + } - const s = - codeGenResult.sources.get("css") || - codeGenResult.sources.get("css-import"); - if (s) { - source.add(s); - source.add("\n"); + applyNoParseRule(rule, content) { + // must start with "rule" if rule is a string + if (typeof rule === "string") { + return content.startsWith(rule); + } + + if (typeof rule === "function") { + return rule(content); + } + // we assume rule is a regexp + return rule.test(content); + } + + // check if module should not be parsed + // returns "true" if the module should !not! be parsed + // returns "false" if the module !must! be parsed + shouldPreventParsing(noParseRule, request) { + // if no noParseRule exists, return false + // the module !must! be parsed. + if (!noParseRule) { + return false; + } + + // we only have one rule to check + if (!Array.isArray(noParseRule)) { + // returns "true" if the module is !not! to be parsed + return this.applyNoParseRule(noParseRule, request); + } + + for (let i = 0; i < noParseRule.length; i++) { + const rule = noParseRule[i]; + // early exit on first truthy match + // this module is !not! to be parsed + if (this.applyNoParseRule(rule, request)) { + return true; + } + } + // no match found, so this module !should! be parsed + return false; + } + + _initBuildHash(compilation) { + const hash = createHash(compilation.outputOptions.hashFunction); + if (this._source) { + hash.update("source"); + this._source.updateHash(hash); + } + hash.update("meta"); + hash.update(JSON.stringify(this.buildMeta)); + this.buildInfo.hash = /** @type {string} */ (hash.digest("hex")); + } + + /** + * @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._forceBuild = false; + this._source = null; + if (this._sourceSizes !== undefined) this._sourceSizes.clear(); + this._sourceTypes = undefined; + this._ast = null; + this.error = null; + this.clearWarningsAndErrors(); + this.clearDependenciesAndBlocks(); + this.buildMeta = {}; + this.buildInfo = { + cacheable: false, + parsed: true, + fileDependencies: undefined, + contextDependencies: undefined, + missingDependencies: undefined, + buildDependencies: undefined, + valueDependencies: undefined, + hash: undefined, + assets: undefined, + assetsInfo: undefined + }; + + const startTime = compilation.compiler.fsStartTime || Date.now(); + + const hooks = NormalModule.getCompilationHooks(compilation); + + return this._doBuild(options, compilation, resolver, fs, hooks, err => { + // if we have an error mark module as failed and exit + if (err) { + this.markModuleAsErrored(err); + this._initBuildHash(compilation); + return callback(); + } + + const handleParseError = e => { + const source = this._source.source(); + const loaders = this.loaders.map(item => + contextify(options.context, item.loader, compilation.compiler.root) + ); + const error = new ModuleParseError(source, e, loaders, this.type); + this.markModuleAsErrored(error); + this._initBuildHash(compilation); + return callback(); + }; + + const handleParseResult = result => { + this.dependencies.sort( + concatComparators( + compareSelect(a => a.loc, compareLocations), + keepOriginalOrder(this.dependencies) + ) + ); + this._initBuildHash(compilation); + this._lastSuccessfulBuildMeta = this.buildMeta; + return handleBuildDone(); + }; + + const handleBuildDone = () => { + try { + hooks.beforeSnapshot.call(this); + } catch (err) { + this.markModuleAsErrored(err); + return callback(); } - const exports = - codeGenResult.data && codeGenResult.data.get("css-exports"); - const moduleId = chunkGraph.getModuleId(module) + ""; - metaData.push( - `${ - exports - ? Array.from(exports, ([n, v]) => { - const shortcutValue = `${ - uniqueName ? uniqueName + "-" : "" - }${moduleId}-${n}`; - return v === shortcutValue - ? `${escapeCss(n)}/` - : v === "--" + shortcutValue - ? `${escapeCss(n)}%` - : `${escapeCss(n)}(${escapeCss(v)})`; - }).join("") - : "" - }${escapeCss(moduleId)}` + + const snapshotOptions = compilation.options.snapshot.module; + if (!this.buildInfo.cacheable || !snapshotOptions) { + return callback(); + } + // add warning for all non-absolute paths in fileDependencies, etc + // This makes it easier to find problems with watching and/or caching + let nonAbsoluteDependencies = undefined; + const checkDependencies = deps => { + for (const dep of deps) { + if (!ABSOLUTE_PATH_REGEX.test(dep)) { + if (nonAbsoluteDependencies === undefined) + nonAbsoluteDependencies = new Set(); + nonAbsoluteDependencies.add(dep); + deps.delete(dep); + try { + const depWithoutGlob = dep.replace(/[\\/]?\*.*$/, ""); + const absolute = join( + compilation.fileSystemInfo.fs, + this.context, + depWithoutGlob + ); + if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) { + (depWithoutGlob !== dep + ? this.buildInfo.contextDependencies + : deps + ).add(absolute); + } + } catch (e) { + // ignore + } + } + } + }; + checkDependencies(this.buildInfo.fileDependencies); + checkDependencies(this.buildInfo.missingDependencies); + checkDependencies(this.buildInfo.contextDependencies); + if (nonAbsoluteDependencies !== undefined) { + const InvalidDependenciesModuleWarning = + getInvalidDependenciesModuleWarning(); + this.addWarning( + new InvalidDependenciesModuleWarning(this, nonAbsoluteDependencies) + ); + } + // convert file/context/missingDependencies into filesystem snapshot + compilation.fileSystemInfo.createSnapshot( + startTime, + this.buildInfo.fileDependencies, + this.buildInfo.contextDependencies, + this.buildInfo.missingDependencies, + snapshotOptions, + (err, snapshot) => { + if (err) { + this.markModuleAsErrored(err); + return; + } + this.buildInfo.fileDependencies = undefined; + this.buildInfo.contextDependencies = undefined; + this.buildInfo.missingDependencies = undefined; + this.buildInfo.snapshot = snapshot; + return callback(); + } ); + }; + + try { + hooks.beforeParse.call(this); + } catch (err) { + this.markModuleAsErrored(err); + this._initBuildHash(compilation); + return callback(); + } + + // check if this module should !not! be parsed. + // if so, exit here; + const noParseRule = options.module && options.module.noParse; + if (this.shouldPreventParsing(noParseRule, this.request)) { + // We assume that we need module and exports + this.buildInfo.parsed = false; + this._initBuildHash(compilation); + return handleBuildDone(); + } + + let result; + try { + const source = this._source.source(); + result = this.parser.parse(this._ast || source, { + source, + current: this, + module: this, + compilation: compilation, + options: options + }); } catch (e) { - e.message += `\nduring rendering of css ${module.identifier()}`; - throw e; + handleParseError(e); + return; + } + handleParseResult(result); + }); + } + + /** + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + */ + getConcatenationBailoutReason(context) { + return this.generator.getConcatenationBailoutReason(this, context); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only + */ + getSideEffectsConnectionState(moduleGraph) { + if (this.factoryMeta !== undefined) { + if (this.factoryMeta.sideEffectFree) return false; + if (this.factoryMeta.sideEffectFree === false) return true; + } + if (this.buildMeta !== undefined && this.buildMeta.sideEffectFree) { + if (this._isEvaluatingSideEffects) + return ModuleGraphConnection.CIRCULAR_CONNECTION; + this._isEvaluatingSideEffects = true; + /** @type {ConnectionState} */ + let current = false; + for (const dep of this.dependencies) { + const state = dep.getModuleEvaluationSideEffectsState(moduleGraph); + if (state === true) { + if ( + this._addedSideEffectsBailout === undefined + ? ((this._addedSideEffectsBailout = new WeakSet()), true) + : !this._addedSideEffectsBailout.has(moduleGraph) + ) { + this._addedSideEffectsBailout.add(moduleGraph); + moduleGraph + .getOptimizationBailout(this) + .push( + () => + `Dependency (${ + dep.type + }) with side effects at ${formatLocation(dep.loc)}` + ); + } + this._isEvaluatingSideEffects = false; + return true; + } else if (state !== ModuleGraphConnection.CIRCULAR_CONNECTION) { + current = ModuleGraphConnection.addConnectionStates(current, state); + } } + this._isEvaluatingSideEffects = false; + // When caching is implemented here, make sure to not cache when + // at least one circular connection was in the loop above + return current; + } else { + return true; } - source.add( - `head{--webpack-${escapeCss( - (uniqueName ? uniqueName + "-" : "") + chunk.id, - true - )}:${metaData.join(",")};}` - ); - return source; } - static getChunkFilenameTemplate(chunk, outputOptions) { - if (chunk.cssFilenameTemplate) { - return chunk.cssFilenameTemplate; - } else if (chunk.canBeInitial()) { - return outputOptions.cssFilename; + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + if (this._sourceTypes === undefined) { + this._sourceTypes = this.generator.getTypes(this); + } + return this._sourceTypes; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + concatenationScope, + codeGenerationResults + }) { + /** @type {Set} */ + const runtimeRequirements = new Set(); + + if (!this.buildInfo.parsed) { + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.thisAsExports); + } + + /** @type {Map} */ + let data; + const getData = () => { + if (data === undefined) data = new Map(); + return data; + }; + + const sources = new Map(); + for (const type of this.generator.getTypes(this)) { + const source = this.error + ? new RawSource( + "throw new Error(" + JSON.stringify(this.error.message) + ");" + ) + : this.generator.generate(this, { + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtimeRequirements, + runtime, + concatenationScope, + codeGenerationResults, + getData, + type + }); + + if (source) { + sources.set(type, new CachedSource(source)); + } + } + + /** @type {CodeGenerationResult} */ + const resultEntry = { + sources, + runtimeRequirements, + data + }; + return resultEntry; + } + + /** + * @returns {Source | null} the original source for the module before webpack transformation + */ + originalSource() { + return this._source; + } + + /** + * @returns {void} + */ + invalidateBuild() { + this._forceBuild = true; + } + + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + const { fileSystemInfo, compilation, valueCacheVersions } = context; + // build if enforced + if (this._forceBuild) return callback(null, true); + + // always try to build in case of an error + if (this.error) return callback(null, true); + + // always build when module is not cacheable + if (!this.buildInfo.cacheable) return callback(null, true); + + // build when there is no snapshot to check + if (!this.buildInfo.snapshot) return callback(null, true); + + // build when valueDependencies have changed + /** @type {Map>} */ + const valueDependencies = this.buildInfo.valueDependencies; + if (valueDependencies) { + if (!valueCacheVersions) return callback(null, true); + for (const [key, value] of valueDependencies) { + if (value === undefined) return callback(null, true); + const current = valueCacheVersions.get(key); + if ( + value !== current && + (typeof value === "string" || + typeof current === "string" || + current === undefined || + !isSubset(value, current)) + ) { + return callback(null, true); + } + } + } + + // check snapshot for validity + fileSystemInfo.checkSnapshotValid(this.buildInfo.snapshot, (err, valid) => { + if (err) return callback(err); + if (!valid) return callback(null, true); + const hooks = NormalModule.getCompilationHooks(compilation); + hooks.needBuild.callAsync(this, context, (err, needBuild) => { + if (err) { + return callback( + HookWebpackError.makeWebpackError( + err, + "NormalModule.getCompilationHooks().needBuild" + ) + ); + } + callback(null, !!needBuild); + }); + }); + } + + /** + * @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) { + const cachedSize = + this._sourceSizes === undefined ? undefined : this._sourceSizes.get(type); + if (cachedSize !== undefined) { + return cachedSize; + } + const size = Math.max(1, this.generator.getSize(this, type)); + if (this._sourceSizes === undefined) { + this._sourceSizes = new Map(); + } + this._sourceSizes.set(type, size); + return size; + } + + /** + * @param {LazySet} fileDependencies set where file dependencies are added to + * @param {LazySet} contextDependencies set where context dependencies are added to + * @param {LazySet} missingDependencies set where missing dependencies are added to + * @param {LazySet} buildDependencies set where build dependencies are added to + */ + addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ) { + const { snapshot, buildDependencies: buildDeps } = this.buildInfo; + if (snapshot) { + fileDependencies.addAll(snapshot.getFileIterable()); + contextDependencies.addAll(snapshot.getContextIterable()); + missingDependencies.addAll(snapshot.getMissingIterable()); } else { - return outputOptions.cssChunkFilename; + const { + fileDependencies: fileDeps, + contextDependencies: contextDeps, + missingDependencies: missingDeps + } = this.buildInfo; + if (fileDeps !== undefined) fileDependencies.addAll(fileDeps); + if (contextDeps !== undefined) contextDependencies.addAll(contextDeps); + if (missingDeps !== undefined) missingDependencies.addAll(missingDeps); + } + if (buildDeps !== undefined) { + buildDependencies.addAll(buildDeps); } } - static chunkHasCss(chunk, chunkGraph) { - return ( - !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css") || - !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css-import") - ); + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + hash.update(this.buildInfo.hash); + this.generator.updateHash(hash, { + module: this, + ...context + }); + super.updateHash(hash, context); + } + + serialize(context) { + const { write } = context; + // deserialize + write(this._source); + write(this.error); + write(this._lastSuccessfulBuildMeta); + write(this._forceBuild); + super.serialize(context); + } + + static deserialize(context) { + const obj = new NormalModule({ + // will be deserialized by Module + layer: null, + type: "", + // will be filled by updateCacheModule + resource: "", + context: "", + request: null, + userRequest: null, + rawRequest: null, + loaders: null, + matchResource: null, + parser: null, + parserOptions: null, + generator: null, + generatorOptions: null, + resolveOptions: null + }); + obj.deserialize(context); + return obj; + } + + deserialize(context) { + const { read } = context; + this._source = read(); + this.error = read(); + this._lastSuccessfulBuildMeta = read(); + this._forceBuild = read(); + super.deserialize(context); } } -module.exports = CssModulesPlugin; +makeSerializable(NormalModule, "webpack/lib/NormalModule"); + +module.exports = NormalModule; /***/ }), -/***/ 98305: +/***/ 68860: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -68973,1752 +62619,1337 @@ module.exports = CssModulesPlugin; -const Parser = __webpack_require__(11715); -const ConstDependency = __webpack_require__(76911); -const CssExportDependency = __webpack_require__(76760); -const CssImportDependency = __webpack_require__(90542); -const CssLocalIdentifierDependency = __webpack_require__(92328); -const CssSelfLocalIdentifierDependency = __webpack_require__(29094); -const CssUrlDependency = __webpack_require__(70749); -const StaticExportsDependency = __webpack_require__(91418); -const walkCssTokens = __webpack_require__(44124); +const { getContext } = __webpack_require__(68318); +const asyncLib = __webpack_require__(78175); +const { + AsyncSeriesBailHook, + SyncWaterfallHook, + SyncBailHook, + SyncHook, + HookMap +} = __webpack_require__(41242); +const ChunkGraph = __webpack_require__(64971); +const Module = __webpack_require__(73208); +const ModuleFactory = __webpack_require__(51010); +const ModuleGraph = __webpack_require__(99988); +const NormalModule = __webpack_require__(39); +const BasicEffectRulePlugin = __webpack_require__(30318); +const BasicMatcherRulePlugin = __webpack_require__(94215); +const ObjectMatcherRulePlugin = __webpack_require__(72021); +const RuleSetCompiler = __webpack_require__(83349); +const UseEffectRulePlugin = __webpack_require__(84977); +const LazySet = __webpack_require__(38938); +const { getScheme } = __webpack_require__(54500); +const { cachedCleverMerge, cachedSetProperty } = __webpack_require__(60839); +const { join } = __webpack_require__(17139); +const { parseResource } = __webpack_require__(82186); -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ +/** @typedef {import("../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ +/** @typedef {import("./Generator")} Generator */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./Parser")} Parser */ +/** @typedef {import("./ResolverFactory")} ResolverFactory */ +/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -const CC_LEFT_CURLY = "{".charCodeAt(0); -const CC_RIGHT_CURLY = "}".charCodeAt(0); -const CC_COLON = ":".charCodeAt(0); -const CC_SLASH = "/".charCodeAt(0); -const CC_SEMICOLON = ";".charCodeAt(0); +/** + * @typedef {Object} ResolveData + * @property {ModuleFactoryCreateData["contextInfo"]} contextInfo + * @property {ModuleFactoryCreateData["resolveOptions"]} resolveOptions + * @property {string} context + * @property {string} request + * @property {Record | undefined} assertions + * @property {ModuleDependency[]} dependencies + * @property {string} dependencyType + * @property {Object} createData + * @property {LazySet} fileDependencies + * @property {LazySet} missingDependencies + * @property {LazySet} contextDependencies + * @property {boolean} cacheable allow to use the unsafe cache + */ -const cssUnescape = str => { - return str.replace(/\\([0-9a-fA-F]{1,6}[ \t\n\r\f]?|[\s\S])/g, match => { - if (match.length > 2) { - return String.fromCharCode(parseInt(match.slice(1).trim(), 16)); - } else { - return match[1]; - } - }); +/** + * @typedef {Object} ResourceData + * @property {string} resource + * @property {string} path + * @property {string} query + * @property {string} fragment + * @property {string=} context + */ + +/** @typedef {ResourceData & { data: Record }} ResourceDataWithData */ + +const EMPTY_RESOLVE_OPTIONS = {}; +const EMPTY_PARSER_OPTIONS = {}; +const EMPTY_GENERATOR_OPTIONS = {}; +const EMPTY_ELEMENTS = []; + +const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; + +const loaderToIdent = data => { + if (!data.options) { + return data.loader; + } + if (typeof data.options === "string") { + return data.loader + "?" + data.options; + } + if (typeof data.options !== "object") { + throw new Error("loader options must be string or object"); + } + if (data.ident) { + return data.loader + "??" + data.ident; + } + return data.loader + "?" + JSON.stringify(data.options); }; -class LocConverter { - constructor(input) { - this._input = input; - this.line = 1; - this.column = 0; - this.pos = 0; +const stringifyLoadersAndResource = (loaders, resource) => { + let str = ""; + for (const loader of loaders) { + str += loaderToIdent(loader) + "!"; } + return str + resource; +}; - get(pos) { - if (this.pos !== pos) { - if (this.pos < pos) { - const str = this._input.slice(this.pos, pos); - let i = str.lastIndexOf("\n"); - if (i === -1) { - this.column += str.length; - } else { - this.column = str.length - i - 1; - this.line++; - while (i > 0 && (i = str.lastIndexOf("\n", i - 1)) !== -1) - this.line++; - } +/** + * @param {string} resultString resultString + * @returns {{loader: string, options: string|undefined}} parsed loader request + */ +const identToLoaderRequest = resultString => { + const idx = resultString.indexOf("?"); + if (idx >= 0) { + const loader = resultString.substr(0, idx); + const options = resultString.substr(idx + 1); + return { + loader, + options + }; + } else { + return { + loader: resultString, + options: undefined + }; + } +}; + +const needCalls = (times, callback) => { + return err => { + if (--times === 0) { + return callback(err); + } + if (err && times > 0) { + times = NaN; + return callback(err); + } + }; +}; + +const mergeGlobalOptions = (globalOptions, type, localOptions) => { + const parts = type.split("/"); + let result; + let current = ""; + for (const part of parts) { + current = current ? `${current}/${part}` : part; + const options = globalOptions[current]; + if (typeof options === "object") { + if (result === undefined) { + result = options; } else { - let i = this._input.lastIndexOf("\n", this.pos); - while (i >= pos) { - this.line--; - i = i > 0 ? this._input.lastIndexOf("\n", i - 1) : -1; - } - this.column = pos - i; + result = cachedCleverMerge(result, options); } - this.pos = pos; } - return this; } -} + if (result === undefined) { + return localOptions; + } else { + return cachedCleverMerge(result, localOptions); + } +}; -const CSS_MODE_TOP_LEVEL = 0; -const CSS_MODE_IN_RULE = 1; -const CSS_MODE_IN_LOCAL_RULE = 2; -const CSS_MODE_AT_IMPORT_EXPECT_URL = 3; -// TODO implement layer and supports for @import -const CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS = 4; -const CSS_MODE_AT_IMPORT_EXPECT_MEDIA = 5; -const CSS_MODE_AT_OTHER = 6; +// TODO webpack 6 remove +const deprecationChangedHookMessage = (name, hook) => { + const names = hook.taps + .map(tapped => { + return tapped.name; + }) + .join(", "); -const explainMode = mode => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: - return "parsing top level css"; - case CSS_MODE_IN_RULE: - return "parsing css rule content (global)"; - case CSS_MODE_IN_LOCAL_RULE: - return "parsing css rule content (local)"; - case CSS_MODE_AT_IMPORT_EXPECT_URL: - return "parsing @import (expecting url)"; - case CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS: - return "parsing @import (expecting optionally supports or media query)"; - case CSS_MODE_AT_IMPORT_EXPECT_MEDIA: - return "parsing @import (expecting optionally media query)"; - case CSS_MODE_AT_OTHER: - return "parsing at-rule"; - default: - return mode; - } + return ( + `NormalModuleFactory.${name} (${names}) is no longer a waterfall hook, but a bailing hook instead. ` + + "Do not return the passed object, but modify it instead. " + + "Returning false will ignore the request and results in no module created." + ); }; -class CssParser extends Parser { - constructor({ - allowPseudoBlocks = true, - allowModeSwitch = true, - defaultMode = "global" - } = {}) { - super(); - this.allowPseudoBlocks = allowPseudoBlocks; - this.allowModeSwitch = allowModeSwitch; - this.defaultMode = defaultMode; - } +const ruleSetCompiler = new RuleSetCompiler([ + new BasicMatcherRulePlugin("test", "resource"), + new BasicMatcherRulePlugin("scheme"), + new BasicMatcherRulePlugin("mimetype"), + new BasicMatcherRulePlugin("dependency"), + new BasicMatcherRulePlugin("include", "resource"), + new BasicMatcherRulePlugin("exclude", "resource", true), + new BasicMatcherRulePlugin("resource"), + new BasicMatcherRulePlugin("resourceQuery"), + new BasicMatcherRulePlugin("resourceFragment"), + new BasicMatcherRulePlugin("realResource"), + new BasicMatcherRulePlugin("issuer"), + new BasicMatcherRulePlugin("compiler"), + new BasicMatcherRulePlugin("issuerLayer"), + new ObjectMatcherRulePlugin("assert", "assertions"), + new ObjectMatcherRulePlugin("descriptionData"), + new BasicEffectRulePlugin("type"), + new BasicEffectRulePlugin("sideEffects"), + new BasicEffectRulePlugin("parser"), + new BasicEffectRulePlugin("resolve"), + new BasicEffectRulePlugin("generator"), + new BasicEffectRulePlugin("layer"), + new UseEffectRulePlugin() +]); +class NormalModuleFactory extends ModuleFactory { /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state + * @param {Object} param params + * @param {string=} param.context context + * @param {InputFileSystem} param.fs file system + * @param {ResolverFactory} param.resolverFactory resolverFactory + * @param {ModuleOptions} param.options options + * @param {Object=} param.associatedObjectForCache an object to which the cache will be attached + * @param {boolean=} param.layers enable layers */ - parse(source, state) { - if (Buffer.isBuffer(source)) { - source = source.toString("utf-8"); - } else if (typeof source === "object") { - throw new Error("webpackAst is unexpected for the CssParser"); - } - if (source[0] === "\ufeff") { - source = source.slice(1); - } - - const module = state.module; - - const declaredCssVariables = new Set(); - - const locConverter = new LocConverter(source); - let mode = CSS_MODE_TOP_LEVEL; - let modePos = 0; - let modeNestingLevel = 0; - let modeData = undefined; - let singleClassSelector = undefined; - let lastIdentifier = undefined; - const modeStack = []; - const isTopLevelLocal = () => - modeData === "local" || - (this.defaultMode === "local" && modeData === undefined); - const eatWhiteLine = (input, pos) => { - for (;;) { - const cc = input.charCodeAt(pos); - if (cc === 32 || cc === 9) { - pos++; - continue; - } - if (cc === 10) pos++; - break; - } - return pos; - }; - const eatUntil = chars => { - const charCodes = Array.from({ length: chars.length }, (_, i) => - chars.charCodeAt(i) - ); - const arr = Array.from( - { length: charCodes.reduce((a, b) => Math.max(a, b), 0) + 1 }, - () => false - ); - charCodes.forEach(cc => (arr[cc] = true)); - return (input, pos) => { - for (;;) { - const cc = input.charCodeAt(pos); - if (cc < arr.length && arr[cc]) { - return pos; - } - pos++; - if (pos === input.length) return pos; - } - }; - }; - const eatText = (input, pos, eater) => { - let text = ""; - for (;;) { - if (input.charCodeAt(pos) === CC_SLASH) { - const newPos = walkCssTokens.eatComments(input, pos); - if (pos !== newPos) { - pos = newPos; - if (pos === input.length) break; - } else { - text += "/"; - pos++; - if (pos === input.length) break; - } - } - const newPos = eater(input, pos); - if (pos !== newPos) { - text += input.slice(pos, newPos); - pos = newPos; - } else { - break; - } - if (pos === input.length) break; - } - return [pos, text.trimRight()]; - }; - const eatExportName = eatUntil(":};/"); - const eatExportValue = eatUntil("};/"); - const parseExports = (input, pos) => { - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - const cc = input.charCodeAt(pos); - if (cc !== CC_LEFT_CURLY) - throw new Error( - `Unexpected ${input[pos]} at ${pos} during parsing of ':export' (expected '{')` - ); - pos++; - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - for (;;) { - if (input.charCodeAt(pos) === CC_RIGHT_CURLY) break; - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - if (pos === input.length) return pos; - let start = pos; - let name; - [pos, name] = eatText(input, pos, eatExportName); - if (pos === input.length) return pos; - if (input.charCodeAt(pos) !== CC_COLON) { - throw new Error( - `Unexpected ${input[pos]} at ${pos} during parsing of export name in ':export' (expected ':')` - ); - } - pos++; - if (pos === input.length) return pos; - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - if (pos === input.length) return pos; - let value; - [pos, value] = eatText(input, pos, eatExportValue); - if (pos === input.length) return pos; - const cc = input.charCodeAt(pos); - if (cc === CC_SEMICOLON) { - pos++; - if (pos === input.length) return pos; - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - if (pos === input.length) return pos; - } else if (cc !== CC_RIGHT_CURLY) { - throw new Error( - `Unexpected ${input[pos]} at ${pos} during parsing of export value in ':export' (expected ';' or '}')` - ); - } - const dep = new CssExportDependency(name, value); - const { line: sl, column: sc } = locConverter.get(start); - const { line: el, column: ec } = locConverter.get(pos); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - } - pos++; - if (pos === input.length) return pos; - pos = eatWhiteLine(input, pos); - return pos; - }; - const eatPropertyName = eatUntil(":{};"); - const processLocalDeclaration = (input, pos) => { - modeData = undefined; - const start = pos; - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - const propertyNameStart = pos; - const [propertyNameEnd, propertyName] = eatText( - input, - pos, - eatPropertyName - ); - if (input.charCodeAt(propertyNameEnd) !== CC_COLON) return start; - pos = propertyNameEnd + 1; - if (propertyName.startsWith("--")) { - // CSS Variable - const { line: sl, column: sc } = locConverter.get(propertyNameStart); - const { line: el, column: ec } = locConverter.get(propertyNameEnd); - const name = propertyName.slice(2); - const dep = new CssLocalIdentifierDependency( - name, - [propertyNameStart, propertyNameEnd], - "--" - ); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - declaredCssVariables.add(name); - } else if ( - propertyName === "animation-name" || - propertyName === "animation" - ) { - modeData = "animation"; - lastIdentifier = undefined; - } - return pos; - }; - const processDeclarationValueDone = (input, pos) => { - if (modeData === "animation" && lastIdentifier) { - const { line: sl, column: sc } = locConverter.get(lastIdentifier[0]); - const { line: el, column: ec } = locConverter.get(lastIdentifier[1]); - const name = input.slice(lastIdentifier[0], lastIdentifier[1]); - const dep = new CssSelfLocalIdentifierDependency(name, lastIdentifier); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - } - }; - const eatKeyframes = eatUntil("{};/"); - const eatNameInVar = eatUntil(",)};/"); - walkCssTokens(source, { - isSelector: () => { - return mode !== CSS_MODE_IN_RULE && mode !== CSS_MODE_IN_LOCAL_RULE; - }, - url: (input, start, end, contentStart, contentEnd) => { - const value = cssUnescape(input.slice(contentStart, contentEnd)); - switch (mode) { - case CSS_MODE_AT_IMPORT_EXPECT_URL: { - modeData.url = value; - mode = CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS; - break; - } - case CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS: - case CSS_MODE_AT_IMPORT_EXPECT_MEDIA: - throw new Error( - `Unexpected ${input.slice( - start, - end - )} at ${start} during ${explainMode(mode)}` - ); - default: { - const dep = new CssUrlDependency(value, [start, end], "url"); - const { line: sl, column: sc } = locConverter.get(start); - const { line: el, column: ec } = locConverter.get(end); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - module.addCodeGenerationDependency(dep); - break; - } - } - return end; - }, - string: (input, start, end) => { - switch (mode) { - case CSS_MODE_AT_IMPORT_EXPECT_URL: { - modeData.url = cssUnescape(input.slice(start + 1, end - 1)); - mode = CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS; - break; - } - } - return end; - }, - atKeyword: (input, start, end) => { - const name = input.slice(start, end); - if (name === "@namespace") { - throw new Error("@namespace is not supported in bundled CSS"); - } - if (name === "@import") { - if (mode !== CSS_MODE_TOP_LEVEL) { - throw new Error( - `Unexpected @import at ${start} during ${explainMode(mode)}` - ); - } - mode = CSS_MODE_AT_IMPORT_EXPECT_URL; - modePos = end; - modeData = { - start: start, - url: undefined, - supports: undefined - }; - } - if (name === "@keyframes") { - let pos = end; - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - if (pos === input.length) return pos; - const [newPos, name] = eatText(input, pos, eatKeyframes); - const { line: sl, column: sc } = locConverter.get(pos); - const { line: el, column: ec } = locConverter.get(newPos); - const dep = new CssLocalIdentifierDependency(name, [pos, newPos]); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - pos = newPos; - if (pos === input.length) return pos; - if (input.charCodeAt(pos) !== CC_LEFT_CURLY) { - throw new Error( - `Unexpected ${input[pos]} at ${pos} during parsing of @keyframes (expected '{')` - ); - } - mode = CSS_MODE_IN_LOCAL_RULE; - modeNestingLevel = 1; - return pos + 1; - } - return end; - }, - semicolon: (input, start, end) => { - switch (mode) { - case CSS_MODE_AT_IMPORT_EXPECT_URL: - throw new Error(`Expected URL for @import at ${start}`); - case CSS_MODE_AT_IMPORT_EXPECT_MEDIA: - case CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS: { - const { line: sl, column: sc } = locConverter.get(modeData.start); - const { line: el, column: ec } = locConverter.get(end); - end = eatWhiteLine(input, end); - const media = input.slice(modePos, start).trim(); - const dep = new CssImportDependency( - modeData.url, - [modeData.start, end], - modeData.supports, - media - ); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - break; - } - case CSS_MODE_IN_LOCAL_RULE: { - processDeclarationValueDone(input, start); - return processLocalDeclaration(input, end); - } - case CSS_MODE_IN_RULE: { - return end; - } - } - mode = CSS_MODE_TOP_LEVEL; - modeData = undefined; - singleClassSelector = undefined; - return end; - }, - leftCurlyBracket: (input, start, end) => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: - mode = isTopLevelLocal() - ? CSS_MODE_IN_LOCAL_RULE - : CSS_MODE_IN_RULE; - modeNestingLevel = 1; - if (mode === CSS_MODE_IN_LOCAL_RULE) - return processLocalDeclaration(input, end); - break; - case CSS_MODE_IN_RULE: - case CSS_MODE_IN_LOCAL_RULE: - modeNestingLevel++; - break; - } - return end; - }, - rightCurlyBracket: (input, start, end) => { - switch (mode) { - case CSS_MODE_IN_LOCAL_RULE: - processDeclarationValueDone(input, start); - /* falls through */ - case CSS_MODE_IN_RULE: - if (--modeNestingLevel === 0) { - mode = CSS_MODE_TOP_LEVEL; - modeData = undefined; - singleClassSelector = undefined; - } - break; - } - return end; - }, - id: (input, start, end) => { - singleClassSelector = false; - switch (mode) { - case CSS_MODE_TOP_LEVEL: - if (isTopLevelLocal()) { - const name = input.slice(start + 1, end); - const dep = new CssLocalIdentifierDependency(name, [ - start + 1, - end - ]); - const { line: sl, column: sc } = locConverter.get(start); - const { line: el, column: ec } = locConverter.get(end); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - } - break; - } - return end; - }, - identifier: (input, start, end) => { - singleClassSelector = false; - switch (mode) { - case CSS_MODE_IN_LOCAL_RULE: - if (modeData === "animation") { - lastIdentifier = [start, end]; - } - break; - } - return end; - }, - class: (input, start, end) => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: { - if (isTopLevelLocal()) { - const name = input.slice(start + 1, end); - const dep = new CssLocalIdentifierDependency(name, [ - start + 1, - end - ]); - const { line: sl, column: sc } = locConverter.get(start); - const { line: el, column: ec } = locConverter.get(end); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - if (singleClassSelector === undefined) singleClassSelector = name; - } else { - singleClassSelector = false; - } - break; - } - } - return end; - }, - leftParenthesis: (input, start, end) => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: { - modeStack.push(false); - break; - } - } - return end; - }, - rightParenthesis: (input, start, end) => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: { - const newModeData = modeStack.pop(); - if (newModeData !== false) { - modeData = newModeData; - const dep = new ConstDependency("", [start, end]); - module.addPresentationalDependency(dep); - } - break; - } - } - return end; - }, - pseudoClass: (input, start, end) => { - singleClassSelector = false; - switch (mode) { - case CSS_MODE_TOP_LEVEL: { - const name = input.slice(start, end); - if (this.allowModeSwitch && name === ":global") { - modeData = "global"; - const dep = new ConstDependency("", [start, end]); - module.addPresentationalDependency(dep); - } else if (this.allowModeSwitch && name === ":local") { - modeData = "local"; - const dep = new ConstDependency("", [start, end]); - module.addPresentationalDependency(dep); - } else if (this.allowPseudoBlocks && name === ":export") { - const pos = parseExports(input, end); - const dep = new ConstDependency("", [start, pos]); - module.addPresentationalDependency(dep); - return pos; - } - break; - } - } - return end; - }, - pseudoFunction: (input, start, end) => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: { - const name = input.slice(start, end - 1); - if (this.allowModeSwitch && name === ":global") { - modeStack.push(modeData); - modeData = "global"; - const dep = new ConstDependency("", [start, end]); - module.addPresentationalDependency(dep); - } else if (this.allowModeSwitch && name === ":local") { - modeStack.push(modeData); - modeData = "local"; - const dep = new ConstDependency("", [start, end]); - module.addPresentationalDependency(dep); - } else { - modeStack.push(false); - } - break; - } - } - return end; - }, - function: (input, start, end) => { - switch (mode) { - case CSS_MODE_IN_LOCAL_RULE: { - const name = input.slice(start, end - 1); - if (name === "var") { - let pos = walkCssTokens.eatWhitespaceAndComments(input, end); - if (pos === input.length) return pos; - const [newPos, name] = eatText(input, pos, eatNameInVar); - if (!name.startsWith("--")) return end; - const { line: sl, column: sc } = locConverter.get(pos); - const { line: el, column: ec } = locConverter.get(newPos); - const dep = new CssSelfLocalIdentifierDependency( - name.slice(2), - [pos, newPos], - "--", - declaredCssVariables - ); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - return newPos; - } - break; - } - } - return end; + constructor({ + context, + fs, + resolverFactory, + options, + associatedObjectForCache, + layers = false + }) { + super(); + this.hooks = Object.freeze({ + /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ + resolve: new AsyncSeriesBailHook(["resolveData"]), + /** @type {HookMap>} */ + resolveForScheme: new HookMap( + () => new AsyncSeriesBailHook(["resourceData", "resolveData"]) + ), + /** @type {HookMap>} */ + resolveInScheme: new HookMap( + () => new AsyncSeriesBailHook(["resourceData", "resolveData"]) + ), + /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ + factorize: new AsyncSeriesBailHook(["resolveData"]), + /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ + beforeResolve: new AsyncSeriesBailHook(["resolveData"]), + /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ + afterResolve: new AsyncSeriesBailHook(["resolveData"]), + /** @type {AsyncSeriesBailHook<[ResolveData["createData"], ResolveData], TODO>} */ + createModule: new AsyncSeriesBailHook(["createData", "resolveData"]), + /** @type {SyncWaterfallHook<[Module, ResolveData["createData"], ResolveData], TODO>} */ + module: new SyncWaterfallHook(["module", "createData", "resolveData"]), + createParser: new HookMap(() => new SyncBailHook(["parserOptions"])), + parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])), + createGenerator: new HookMap( + () => new SyncBailHook(["generatorOptions"]) + ), + generator: new HookMap( + () => new SyncHook(["generator", "generatorOptions"]) + ) + }); + this.resolverFactory = resolverFactory; + this.ruleSet = ruleSetCompiler.compile([ + { + rules: options.defaultRules }, - comma: (input, start, end) => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: - modeData = undefined; - modeStack.length = 0; - break; - case CSS_MODE_IN_LOCAL_RULE: - processDeclarationValueDone(input, start); - break; - } - return end; + { + rules: options.rules } - }); + ]); + this.context = context || ""; + this.fs = fs; + this._globalParserOptions = options.parser; + this._globalGeneratorOptions = options.generator; + /** @type {Map>} */ + this.parserCache = new Map(); + /** @type {Map>} */ + this.generatorCache = new Map(); + /** @type {Set} */ + this._restoredUnsafeCacheEntries = new Set(); - module.buildInfo.strict = true; - module.buildMeta.exportsType = "namespace"; - module.addDependency(new StaticExportsDependency([], true)); - return state; - } -} + const cacheParseResource = parseResource.bindCache( + associatedObjectForCache + ); -module.exports = CssParser; + this.hooks.factorize.tapAsync( + { + name: "NormalModuleFactory", + stage: 100 + }, + (resolveData, callback) => { + this.hooks.resolve.callAsync(resolveData, (err, result) => { + if (err) return callback(err); + // Ignored + if (result === false) return callback(); -/***/ }), + // direct module + if (result instanceof Module) return callback(null, result); -/***/ 44124: -/***/ (function(module) { + if (typeof result === "object") + throw new Error( + deprecationChangedHookMessage("resolve", this.hooks.resolve) + + " Returning a Module object will result in this module used as result." + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.hooks.afterResolve.callAsync(resolveData, (err, result) => { + if (err) return callback(err); + if (typeof result === "object") + throw new Error( + deprecationChangedHookMessage( + "afterResolve", + this.hooks.afterResolve + ) + ); + // Ignored + if (result === false) return callback(); -/** - * @typedef {Object} CssTokenCallbacks - * @property {function(string, number): boolean} isSelector - * @property {function(string, number, number, number, number): number=} url - * @property {function(string, number, number): number=} string - * @property {function(string, number, number): number=} leftParenthesis - * @property {function(string, number, number): number=} rightParenthesis - * @property {function(string, number, number): number=} pseudoFunction - * @property {function(string, number, number): number=} function - * @property {function(string, number, number): number=} pseudoClass - * @property {function(string, number, number): number=} atKeyword - * @property {function(string, number, number): number=} class - * @property {function(string, number, number): number=} identifier - * @property {function(string, number, number): number=} id - * @property {function(string, number, number): number=} leftCurlyBracket - * @property {function(string, number, number): number=} rightCurlyBracket - * @property {function(string, number, number): number=} semicolon - * @property {function(string, number, number): number=} comma - */ + const createData = resolveData.createData; -/** @typedef {function(string, number, CssTokenCallbacks): number} CharHandler */ + this.hooks.createModule.callAsync( + createData, + resolveData, + (err, createdModule) => { + if (!createdModule) { + if (!resolveData.request) { + return callback(new Error("Empty dependency (no request)")); + } -// spec: https://drafts.csswg.org/css-syntax/ + createdModule = new NormalModule(createData); + } -const CC_LINE_FEED = "\n".charCodeAt(0); -const CC_CARRIAGE_RETURN = "\r".charCodeAt(0); -const CC_FORM_FEED = "\f".charCodeAt(0); + createdModule = this.hooks.module.call( + createdModule, + createData, + resolveData + ); -const CC_TAB = "\t".charCodeAt(0); -const CC_SPACE = " ".charCodeAt(0); + return callback(null, createdModule); + } + ); + }); + }); + } + ); + this.hooks.resolve.tapAsync( + { + name: "NormalModuleFactory", + stage: 100 + }, + (data, callback) => { + const { + contextInfo, + context, + dependencies, + dependencyType, + request, + assertions, + resolveOptions, + fileDependencies, + missingDependencies, + contextDependencies + } = data; + const loaderResolver = this.getResolver("loader"); -const CC_SLASH = "/".charCodeAt(0); -const CC_BACK_SLASH = "\\".charCodeAt(0); -const CC_ASTERISK = "*".charCodeAt(0); + /** @type {ResourceData | undefined} */ + let matchResourceData = undefined; + /** @type {string} */ + let unresolvedResource; + /** @type {{loader: string, options: string|undefined}[]} */ + let elements; + let noPreAutoLoaders = false; + let noAutoLoaders = false; + let noPrePostAutoLoaders = false; -const CC_LEFT_PARENTHESIS = "(".charCodeAt(0); -const CC_RIGHT_PARENTHESIS = ")".charCodeAt(0); -const CC_LEFT_CURLY = "{".charCodeAt(0); -const CC_RIGHT_CURLY = "}".charCodeAt(0); + const contextScheme = getScheme(context); + /** @type {string | undefined} */ + let scheme = getScheme(request); -const CC_QUOTATION_MARK = '"'.charCodeAt(0); -const CC_APOSTROPHE = "'".charCodeAt(0); + if (!scheme) { + /** @type {string} */ + let requestWithoutMatchResource = request; + const matchResourceMatch = MATCH_RESOURCE_REGEX.exec(request); + if (matchResourceMatch) { + let matchResource = matchResourceMatch[1]; + if (matchResource.charCodeAt(0) === 46) { + // 46 === ".", 47 === "/" + const secondChar = matchResource.charCodeAt(1); + if ( + secondChar === 47 || + (secondChar === 46 && matchResource.charCodeAt(2) === 47) + ) { + // if matchResources startsWith ../ or ./ + matchResource = join(this.fs, context, matchResource); + } + } + matchResourceData = { + resource: matchResource, + ...cacheParseResource(matchResource) + }; + requestWithoutMatchResource = request.substr( + matchResourceMatch[0].length + ); + } -const CC_FULL_STOP = ".".charCodeAt(0); -const CC_COLON = ":".charCodeAt(0); -const CC_SEMICOLON = ";".charCodeAt(0); -const CC_COMMA = ",".charCodeAt(0); -const CC_PERCENTAGE = "%".charCodeAt(0); -const CC_AT_SIGN = "@".charCodeAt(0); + scheme = getScheme(requestWithoutMatchResource); -const CC_LOW_LINE = "_".charCodeAt(0); -const CC_LOWER_A = "a".charCodeAt(0); -const CC_LOWER_U = "u".charCodeAt(0); -const CC_LOWER_E = "e".charCodeAt(0); -const CC_LOWER_Z = "z".charCodeAt(0); -const CC_UPPER_A = "A".charCodeAt(0); -const CC_UPPER_E = "E".charCodeAt(0); -const CC_UPPER_Z = "Z".charCodeAt(0); -const CC_0 = "0".charCodeAt(0); -const CC_9 = "9".charCodeAt(0); + if (!scheme && !contextScheme) { + const firstChar = requestWithoutMatchResource.charCodeAt(0); + const secondChar = requestWithoutMatchResource.charCodeAt(1); + noPreAutoLoaders = firstChar === 45 && secondChar === 33; // startsWith "-!" + noAutoLoaders = noPreAutoLoaders || firstChar === 33; // startsWith "!" + noPrePostAutoLoaders = firstChar === 33 && secondChar === 33; // startsWith "!!"; + const rawElements = requestWithoutMatchResource + .slice( + noPreAutoLoaders || noPrePostAutoLoaders + ? 2 + : noAutoLoaders + ? 1 + : 0 + ) + .split(/!+/); + unresolvedResource = rawElements.pop(); + elements = rawElements.map(identToLoaderRequest); + scheme = getScheme(unresolvedResource); + } else { + unresolvedResource = requestWithoutMatchResource; + elements = EMPTY_ELEMENTS; + } + } else { + unresolvedResource = request; + elements = EMPTY_ELEMENTS; + } -const CC_NUMBER_SIGN = "#".charCodeAt(0); -const CC_PLUS_SIGN = "+".charCodeAt(0); -const CC_HYPHEN_MINUS = "-".charCodeAt(0); + const resolveContext = { + fileDependencies, + missingDependencies, + contextDependencies + }; -const CC_LESS_THAN_SIGN = "<".charCodeAt(0); -const CC_GREATER_THAN_SIGN = ">".charCodeAt(0); + /** @type {ResourceDataWithData} */ + let resourceData; -const _isNewLine = cc => { - return ( - cc === CC_LINE_FEED || cc === CC_CARRIAGE_RETURN || cc === CC_FORM_FEED - ); -}; + let loaders; -/** @type {CharHandler} */ -const consumeSpace = (input, pos, callbacks) => { - let cc; - do { - pos++; - cc = input.charCodeAt(pos); - } while (_isWhiteSpace(cc)); - return pos; -}; + const continueCallback = needCalls(2, err => { + if (err) return callback(err); -const _isWhiteSpace = cc => { - return ( - cc === CC_LINE_FEED || - cc === CC_CARRIAGE_RETURN || - cc === CC_FORM_FEED || - cc === CC_TAB || - cc === CC_SPACE - ); -}; + // translate option idents + try { + for (const item of loaders) { + if (typeof item.options === "string" && item.options[0] === "?") { + const ident = item.options.substr(1); + if (ident === "[[missing ident]]") { + throw new Error( + "No ident is provided by referenced loader. " + + "When using a function for Rule.use in config you need to " + + "provide an 'ident' property for referenced loader options." + ); + } + item.options = this.ruleSet.references.get(ident); + if (item.options === undefined) { + throw new Error( + "Invalid ident is provided by referenced loader" + ); + } + item.ident = ident; + } + } + } catch (e) { + return callback(e); + } -/** @type {CharHandler} */ -const consumeSingleCharToken = (input, pos, callbacks) => { - return pos + 1; -}; + if (!resourceData) { + // ignored + return callback(null, dependencies[0].createIgnoredModule(context)); + } -/** @type {CharHandler} */ -const consumePotentialComment = (input, pos, callbacks) => { - pos++; - if (pos === input.length) return pos; - let cc = input.charCodeAt(pos); - if (cc !== CC_ASTERISK) return pos; - for (;;) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - while (cc === CC_ASTERISK) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - if (cc === CC_SLASH) return pos + 1; - } - } -}; + const userRequest = + (matchResourceData !== undefined + ? `${matchResourceData.resource}!=!` + : "") + + stringifyLoadersAndResource(loaders, resourceData.resource); -/** @type {function(number): CharHandler} */ -const consumeString = end => (input, pos, callbacks) => { - const start = pos; - pos = _consumeString(input, pos, end); - if (callbacks.string !== undefined) { - pos = callbacks.string(input, start, pos); - } - return pos; -}; + const settings = {}; + const useLoadersPost = []; + const useLoaders = []; + const useLoadersPre = []; -const _consumeString = (input, pos, end) => { - pos++; - for (;;) { - if (pos === input.length) return pos; - const cc = input.charCodeAt(pos); - if (cc === end) return pos + 1; - if (_isNewLine(cc)) { - // bad string - return pos; - } - if (cc === CC_BACK_SLASH) { - // we don't need to fully parse the escaped code point - // just skip over a potential new line - pos++; - if (pos === input.length) return pos; - pos++; - } else { - pos++; - } - } -}; + // handle .webpack[] suffix + let resource; + let match; + if ( + matchResourceData && + typeof (resource = matchResourceData.resource) === "string" && + (match = /\.webpack\[([^\]]+)\]$/.exec(resource)) + ) { + settings.type = match[1]; + matchResourceData.resource = matchResourceData.resource.slice( + 0, + -settings.type.length - 10 + ); + } else { + settings.type = "javascript/auto"; + const resourceDataForRules = matchResourceData || resourceData; + const result = this.ruleSet.exec({ + resource: resourceDataForRules.path, + realResource: resourceData.path, + resourceQuery: resourceDataForRules.query, + resourceFragment: resourceDataForRules.fragment, + scheme, + assertions, + mimetype: matchResourceData + ? "" + : resourceData.data.mimetype || "", + dependency: dependencyType, + descriptionData: matchResourceData + ? undefined + : resourceData.data.descriptionFileData, + issuer: contextInfo.issuer, + compiler: contextInfo.compiler, + issuerLayer: contextInfo.issuerLayer || "" + }); + for (const r of result) { + if (r.type === "use") { + if (!noAutoLoaders && !noPrePostAutoLoaders) { + useLoaders.push(r.value); + } + } else if (r.type === "use-post") { + if (!noPrePostAutoLoaders) { + useLoadersPost.push(r.value); + } + } else if (r.type === "use-pre") { + if (!noPreAutoLoaders && !noPrePostAutoLoaders) { + useLoadersPre.push(r.value); + } + } else if ( + typeof r.value === "object" && + r.value !== null && + typeof settings[r.type] === "object" && + settings[r.type] !== null + ) { + settings[r.type] = cachedCleverMerge(settings[r.type], r.value); + } else { + settings[r.type] = r.value; + } + } + } -const _isIdentifierStartCode = cc => { - return ( - cc === CC_LOW_LINE || - (cc >= CC_LOWER_A && cc <= CC_LOWER_Z) || - (cc >= CC_UPPER_A && cc <= CC_UPPER_Z) || - cc > 0x80 - ); -}; + let postLoaders, normalLoaders, preLoaders; -const _isDigit = cc => { - return cc >= CC_0 && cc <= CC_9; -}; + const continueCallback = needCalls(3, err => { + if (err) { + return callback(err); + } + const allLoaders = postLoaders; + if (matchResourceData === undefined) { + for (const loader of loaders) allLoaders.push(loader); + for (const loader of normalLoaders) allLoaders.push(loader); + } else { + for (const loader of normalLoaders) allLoaders.push(loader); + for (const loader of loaders) allLoaders.push(loader); + } + for (const loader of preLoaders) allLoaders.push(loader); + let type = settings.type; + const resolveOptions = settings.resolve; + const layer = settings.layer; + if (layer !== undefined && !layers) { + return callback( + new Error( + "'Rule.layer' is only allowed when 'experiments.layers' is enabled" + ) + ); + } + try { + Object.assign(data.createData, { + layer: + layer === undefined ? contextInfo.issuerLayer || null : layer, + request: stringifyLoadersAndResource( + allLoaders, + resourceData.resource + ), + userRequest, + rawRequest: request, + loaders: allLoaders, + resource: resourceData.resource, + context: + resourceData.context || getContext(resourceData.resource), + matchResource: matchResourceData + ? matchResourceData.resource + : undefined, + resourceResolveData: resourceData.data, + settings, + type, + parser: this.getParser(type, settings.parser), + parserOptions: settings.parser, + generator: this.getGenerator(type, settings.generator), + generatorOptions: settings.generator, + resolveOptions + }); + } catch (e) { + return callback(e); + } + callback(); + }); + this.resolveRequestArray( + contextInfo, + this.context, + useLoadersPost, + loaderResolver, + resolveContext, + (err, result) => { + postLoaders = result; + continueCallback(err); + } + ); + this.resolveRequestArray( + contextInfo, + this.context, + useLoaders, + loaderResolver, + resolveContext, + (err, result) => { + normalLoaders = result; + continueCallback(err); + } + ); + this.resolveRequestArray( + contextInfo, + this.context, + useLoadersPre, + loaderResolver, + resolveContext, + (err, result) => { + preLoaders = result; + continueCallback(err); + } + ); + }); -const _startsIdentifier = (input, pos) => { - const cc = input.charCodeAt(pos); - if (cc === CC_HYPHEN_MINUS) { - if (pos === input.length) return false; - const cc = input.charCodeAt(pos + 1); - if (cc === CC_HYPHEN_MINUS) return true; - if (cc === CC_BACK_SLASH) { - const cc = input.charCodeAt(pos + 2); - return !_isNewLine(cc); - } - return _isIdentifierStartCode(cc); - } - if (cc === CC_BACK_SLASH) { - const cc = input.charCodeAt(pos + 1); - return !_isNewLine(cc); - } - return _isIdentifierStartCode(cc); -}; + this.resolveRequestArray( + contextInfo, + contextScheme ? this.context : context, + elements, + loaderResolver, + resolveContext, + (err, result) => { + if (err) return continueCallback(err); + loaders = result; + continueCallback(); + } + ); -/** @type {CharHandler} */ -const consumeNumberSign = (input, pos, callbacks) => { - const start = pos; - pos++; - if (pos === input.length) return pos; - if (callbacks.isSelector(input, pos) && _startsIdentifier(input, pos)) { - pos = _consumeIdentifier(input, pos); - if (callbacks.id !== undefined) { - return callbacks.id(input, start, pos); - } - } - return pos; -}; + const defaultResolve = context => { + if (/^($|\?)/.test(unresolvedResource)) { + resourceData = { + resource: unresolvedResource, + data: {}, + ...cacheParseResource(unresolvedResource) + }; + continueCallback(); + } -/** @type {CharHandler} */ -const consumeMinus = (input, pos, callbacks) => { - const start = pos; - pos++; - if (pos === input.length) return pos; - const cc = input.charCodeAt(pos); - if (cc === CC_FULL_STOP || _isDigit(cc)) { - return consumeNumericToken(input, pos, callbacks); - } else if (cc === CC_HYPHEN_MINUS) { - pos++; - if (pos === input.length) return pos; - const cc = input.charCodeAt(pos); - if (cc === CC_GREATER_THAN_SIGN) { - return pos + 1; - } else { - pos = _consumeIdentifier(input, pos); - if (callbacks.identifier !== undefined) { - return callbacks.identifier(input, start, pos); - } - } - } else if (cc === CC_BACK_SLASH) { - if (pos + 1 === input.length) return pos; - const cc = input.charCodeAt(pos + 1); - if (_isNewLine(cc)) return pos; - pos = _consumeIdentifier(input, pos); - if (callbacks.identifier !== undefined) { - return callbacks.identifier(input, start, pos); - } - } else if (_isIdentifierStartCode(cc)) { - pos++; - pos = _consumeIdentifier(input, pos); - if (callbacks.identifier !== undefined) { - return callbacks.identifier(input, start, pos); - } - } - return pos; -}; + // resource without scheme and with path + else { + const normalResolver = this.getResolver( + "normal", + dependencyType + ? cachedSetProperty( + resolveOptions || EMPTY_RESOLVE_OPTIONS, + "dependencyType", + dependencyType + ) + : resolveOptions + ); + this.resolveResource( + contextInfo, + context, + unresolvedResource, + normalResolver, + resolveContext, + (err, resolvedResource, resolvedResourceResolveData) => { + if (err) return continueCallback(err); + if (resolvedResource !== false) { + resourceData = { + resource: resolvedResource, + data: resolvedResourceResolveData, + ...cacheParseResource(resolvedResource) + }; + } + continueCallback(); + } + ); + } + }; -/** @type {CharHandler} */ -const consumeDot = (input, pos, callbacks) => { - const start = pos; - pos++; - if (pos === input.length) return pos; - const cc = input.charCodeAt(pos); - if (_isDigit(cc)) return consumeNumericToken(input, pos - 2, callbacks); - if (!callbacks.isSelector(input, pos) || !_startsIdentifier(input, pos)) - return pos; - pos = _consumeIdentifier(input, pos); - if (callbacks.class !== undefined) return callbacks.class(input, start, pos); - return pos; -}; + // resource with scheme + if (scheme) { + resourceData = { + resource: unresolvedResource, + data: {}, + path: undefined, + query: undefined, + fragment: undefined, + context: undefined + }; + this.hooks.resolveForScheme + .for(scheme) + .callAsync(resourceData, data, err => { + if (err) return continueCallback(err); + continueCallback(); + }); + } -/** @type {CharHandler} */ -const consumeNumericToken = (input, pos, callbacks) => { - pos = _consumeNumber(input, pos); - if (pos === input.length) return pos; - if (_startsIdentifier(input, pos)) return _consumeIdentifier(input, pos); - const cc = input.charCodeAt(pos); - if (cc === CC_PERCENTAGE) return pos + 1; - return pos; -}; + // resource within scheme + else if (contextScheme) { + resourceData = { + resource: unresolvedResource, + data: {}, + path: undefined, + query: undefined, + fragment: undefined, + context: undefined + }; + this.hooks.resolveInScheme + .for(contextScheme) + .callAsync(resourceData, data, (err, handled) => { + if (err) return continueCallback(err); + if (!handled) return defaultResolve(this.context); + continueCallback(); + }); + } -/** @type {CharHandler} */ -const consumeOtherIdentifier = (input, pos, callbacks) => { - const start = pos; - pos = _consumeIdentifier(input, pos); - if ( - pos !== input.length && - !callbacks.isSelector(input, pos) && - input.charCodeAt(pos) === CC_LEFT_PARENTHESIS - ) { - pos++; - if (callbacks.function !== undefined) { - return callbacks.function(input, start, pos); - } - } else { - if (callbacks.identifier !== undefined) { - return callbacks.identifier(input, start, pos); - } + // resource without scheme and without path + else defaultResolve(context); + } + ); } - return pos; -}; -/** @type {CharHandler} */ -const consumePotentialUrl = (input, pos, callbacks) => { - const start = pos; - pos = _consumeIdentifier(input, pos); - if (pos === start + 3 && input.slice(start, pos + 1) === "url(") { - pos++; - let cc = input.charCodeAt(pos); - while (_isWhiteSpace(cc)) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); + cleanupForCache() { + for (const module of this._restoredUnsafeCacheEntries) { + ChunkGraph.clearChunkGraphForModule(module); + ModuleGraph.clearModuleGraphForModule(module); + module.cleanupForCache(); } - if (cc === CC_QUOTATION_MARK || cc === CC_APOSTROPHE) { - pos++; - const contentStart = pos; - pos = _consumeString(input, pos, cc); - const contentEnd = pos - 1; - cc = input.charCodeAt(pos); - while (_isWhiteSpace(cc)) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); + } + + /** + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * @returns {void} + */ + create(data, callback) { + const dependencies = /** @type {ModuleDependency[]} */ (data.dependencies); + const context = data.context || this.context; + const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS; + const dependency = dependencies[0]; + const request = dependency.request; + const assertions = dependency.assertions; + const contextInfo = data.contextInfo; + const fileDependencies = new LazySet(); + const missingDependencies = new LazySet(); + const contextDependencies = new LazySet(); + const dependencyType = + (dependencies.length > 0 && dependencies[0].category) || ""; + /** @type {ResolveData} */ + const resolveData = { + contextInfo, + resolveOptions, + context, + request, + assertions, + dependencies, + dependencyType, + fileDependencies, + missingDependencies, + contextDependencies, + createData: {}, + cacheable: true + }; + this.hooks.beforeResolve.callAsync(resolveData, (err, result) => { + if (err) { + return callback(err, { + fileDependencies, + missingDependencies, + contextDependencies, + cacheable: false + }); } - if (cc !== CC_RIGHT_PARENTHESIS) return pos; - pos++; - if (callbacks.url !== undefined) - return callbacks.url(input, start, pos, contentStart, contentEnd); - return pos; - } else { - const contentStart = pos; - let contentEnd; - for (;;) { - if (cc === CC_BACK_SLASH) { - pos++; - if (pos === input.length) return pos; - pos++; - } else if (_isWhiteSpace(cc)) { - contentEnd = pos; - do { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - } while (_isWhiteSpace(cc)); - if (cc !== CC_RIGHT_PARENTHESIS) return pos; - pos++; - if (callbacks.url !== undefined) { - return callbacks.url(input, start, pos, contentStart, contentEnd); - } - return pos; - } else if (cc === CC_RIGHT_PARENTHESIS) { - contentEnd = pos; - pos++; - if (callbacks.url !== undefined) { - return callbacks.url(input, start, pos, contentStart, contentEnd); - } - return pos; - } else if (cc === CC_LEFT_PARENTHESIS) { - return pos; - } else { - pos++; - } - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); + + // Ignored + if (result === false) { + return callback(null, { + fileDependencies, + missingDependencies, + contextDependencies, + cacheable: resolveData.cacheable + }); } - } - } else { - if (callbacks.identifier !== undefined) { - return callbacks.identifier(input, start, pos); - } - return pos; - } -}; -/** @type {CharHandler} */ -const consumePotentialPseudo = (input, pos, callbacks) => { - const start = pos; - pos++; - if (!callbacks.isSelector(input, pos) || !_startsIdentifier(input, pos)) - return pos; - pos = _consumeIdentifier(input, pos); - let cc = input.charCodeAt(pos); - if (cc === CC_LEFT_PARENTHESIS) { - pos++; - if (callbacks.pseudoFunction !== undefined) { - return callbacks.pseudoFunction(input, start, pos); - } - return pos; - } - if (callbacks.pseudoClass !== undefined) { - return callbacks.pseudoClass(input, start, pos); - } - return pos; -}; + if (typeof result === "object") + throw new Error( + deprecationChangedHookMessage( + "beforeResolve", + this.hooks.beforeResolve + ) + ); -/** @type {CharHandler} */ -const consumeLeftParenthesis = (input, pos, callbacks) => { - pos++; - if (callbacks.leftParenthesis !== undefined) { - return callbacks.leftParenthesis(input, pos - 1, pos); - } - return pos; -}; + this.hooks.factorize.callAsync(resolveData, (err, module) => { + if (err) { + return callback(err, { + fileDependencies, + missingDependencies, + contextDependencies, + cacheable: false + }); + } -/** @type {CharHandler} */ -const consumeRightParenthesis = (input, pos, callbacks) => { - pos++; - if (callbacks.rightParenthesis !== undefined) { - return callbacks.rightParenthesis(input, pos - 1, pos); - } - return pos; -}; + const factoryResult = { + module, + fileDependencies, + missingDependencies, + contextDependencies, + cacheable: resolveData.cacheable + }; -/** @type {CharHandler} */ -const consumeLeftCurlyBracket = (input, pos, callbacks) => { - pos++; - if (callbacks.leftCurlyBracket !== undefined) { - return callbacks.leftCurlyBracket(input, pos - 1, pos); + callback(null, factoryResult); + }); + }); } - return pos; -}; -/** @type {CharHandler} */ -const consumeRightCurlyBracket = (input, pos, callbacks) => { - pos++; - if (callbacks.rightCurlyBracket !== undefined) { - return callbacks.rightCurlyBracket(input, pos - 1, pos); + resolveResource( + contextInfo, + context, + unresolvedResource, + resolver, + resolveContext, + callback + ) { + resolver.resolve( + contextInfo, + context, + unresolvedResource, + resolveContext, + (err, resolvedResource, resolvedResourceResolveData) => { + if (err) { + return this._resolveResourceErrorHints( + err, + contextInfo, + context, + unresolvedResource, + resolver, + resolveContext, + (err2, hints) => { + if (err2) { + err.message += ` +An fatal error happened during resolving additional hints for this error: ${err2.message}`; + err.stack += ` + +An fatal error happened during resolving additional hints for this error: +${err2.stack}`; + return callback(err); + } + if (hints && hints.length > 0) { + err.message += ` +${hints.join("\n\n")}`; + } + callback(err); + } + ); + } + callback(err, resolvedResource, resolvedResourceResolveData); + } + ); } - return pos; -}; -/** @type {CharHandler} */ -const consumeSemicolon = (input, pos, callbacks) => { - pos++; - if (callbacks.semicolon !== undefined) { - return callbacks.semicolon(input, pos - 1, pos); + _resolveResourceErrorHints( + error, + contextInfo, + context, + unresolvedResource, + resolver, + resolveContext, + callback + ) { + asyncLib.parallel( + [ + callback => { + if (!resolver.options.fullySpecified) return callback(); + resolver + .withOptions({ + fullySpecified: false + }) + .resolve( + contextInfo, + context, + unresolvedResource, + resolveContext, + (err, resolvedResource) => { + if (!err && resolvedResource) { + const resource = parseResource(resolvedResource).path.replace( + /^.*[\\/]/, + "" + ); + return callback( + null, + `Did you mean '${resource}'? +BREAKING CHANGE: The request '${unresolvedResource}' failed to resolve only because it was resolved as fully specified +(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"'). +The extension in the request is mandatory for it to be fully specified. +Add the extension to the request.` + ); + } + callback(); + } + ); + }, + callback => { + if (!resolver.options.enforceExtension) return callback(); + resolver + .withOptions({ + enforceExtension: false, + extensions: [] + }) + .resolve( + contextInfo, + context, + unresolvedResource, + resolveContext, + (err, resolvedResource) => { + if (!err && resolvedResource) { + let hint = ""; + const match = /(\.[^.]+)(\?|$)/.exec(unresolvedResource); + if (match) { + const fixedRequest = unresolvedResource.replace( + /(\.[^.]+)(\?|$)/, + "$2" + ); + if (resolver.options.extensions.has(match[1])) { + hint = `Did you mean '${fixedRequest}'?`; + } else { + hint = `Did you mean '${fixedRequest}'? Also note that '${match[1]}' is not in 'resolve.extensions' yet and need to be added for this to work?`; + } + } else { + hint = `Did you mean to omit the extension or to remove 'resolve.enforceExtension'?`; + } + return callback( + null, + `The request '${unresolvedResource}' failed to resolve only because 'resolve.enforceExtension' was specified. +${hint} +Including the extension in the request is no longer possible. Did you mean to enforce including the extension in requests with 'resolve.extensions: []' instead?` + ); + } + callback(); + } + ); + }, + callback => { + if ( + /^\.\.?\//.test(unresolvedResource) || + resolver.options.preferRelative + ) { + return callback(); + } + resolver.resolve( + contextInfo, + context, + `./${unresolvedResource}`, + resolveContext, + (err, resolvedResource) => { + if (err || !resolvedResource) return callback(); + const moduleDirectories = resolver.options.modules + .map(m => (Array.isArray(m) ? m.join(", ") : m)) + .join(", "); + callback( + null, + `Did you mean './${unresolvedResource}'? +Requests that should resolve in the current directory need to start with './'. +Requests that start with a name are treated as module requests and resolve within module directories (${moduleDirectories}). +If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.` + ); + } + ); + } + ], + (err, hints) => { + if (err) return callback(err); + callback(null, hints.filter(Boolean)); + } + ); } - return pos; -}; -/** @type {CharHandler} */ -const consumeComma = (input, pos, callbacks) => { - pos++; - if (callbacks.comma !== undefined) { - return callbacks.comma(input, pos - 1, pos); + resolveRequestArray( + contextInfo, + context, + array, + resolver, + resolveContext, + callback + ) { + if (array.length === 0) return callback(null, array); + asyncLib.map( + array, + (item, callback) => { + resolver.resolve( + contextInfo, + context, + item.loader, + resolveContext, + (err, result) => { + if ( + err && + /^[^/]*$/.test(item.loader) && + !/-loader$/.test(item.loader) + ) { + return resolver.resolve( + contextInfo, + context, + item.loader + "-loader", + resolveContext, + err2 => { + if (!err2) { + err.message = + err.message + + "\n" + + "BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" + + ` You need to specify '${item.loader}-loader' instead of '${item.loader}',\n` + + " see https://webpack.js.org/migrate/3/#automatic-loader-module-name-extension-removed"; + } + callback(err); + } + ); + } + if (err) return callback(err); + + const parsedResult = identToLoaderRequest(result); + const resolved = { + loader: parsedResult.loader, + options: + item.options === undefined + ? parsedResult.options + : item.options, + ident: item.options === undefined ? undefined : item.ident + }; + return callback(null, resolved); + } + ); + }, + callback + ); } - return pos; -}; -const _consumeIdentifier = (input, pos) => { - for (;;) { - const cc = input.charCodeAt(pos); - if (cc === CC_BACK_SLASH) { - pos++; - if (pos === input.length) return pos; - pos++; - } else if ( - _isIdentifierStartCode(cc) || - _isDigit(cc) || - cc === CC_HYPHEN_MINUS - ) { - pos++; - } else { - return pos; + getParser(type, parserOptions = EMPTY_PARSER_OPTIONS) { + let cache = this.parserCache.get(type); + + if (cache === undefined) { + cache = new WeakMap(); + this.parserCache.set(type, cache); } - } -}; -const _consumeNumber = (input, pos) => { - pos++; - if (pos === input.length) return pos; - let cc = input.charCodeAt(pos); - while (_isDigit(cc)) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - } - if (cc === CC_FULL_STOP && pos + 1 !== input.length) { - const next = input.charCodeAt(pos + 1); - if (_isDigit(next)) { - pos += 2; - cc = input.charCodeAt(pos); - while (_isDigit(cc)) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - } + let parser = cache.get(parserOptions); + + if (parser === undefined) { + parser = this.createParser(type, parserOptions); + cache.set(parserOptions, parser); } + + return parser; } - if (cc === CC_LOWER_E || cc === CC_UPPER_E) { - if (pos + 1 !== input.length) { - const next = input.charCodeAt(pos + 2); - if (_isDigit(next)) { - pos += 2; - } else if ( - (next === CC_HYPHEN_MINUS || next === CC_PLUS_SIGN) && - pos + 2 !== input.length - ) { - const next = input.charCodeAt(pos + 2); - if (_isDigit(next)) { - pos += 3; - } else { - return pos; - } - } else { - return pos; - } + + /** + * @param {string} type type + * @param {{[k: string]: any}} parserOptions parser options + * @returns {Parser} parser + */ + createParser(type, parserOptions = {}) { + parserOptions = mergeGlobalOptions( + this._globalParserOptions, + type, + parserOptions + ); + const parser = this.hooks.createParser.for(type).call(parserOptions); + if (!parser) { + throw new Error(`No parser registered for ${type}`); } - } else { - return pos; - } - cc = input.charCodeAt(pos); - while (_isDigit(cc)) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); + this.hooks.parser.for(type).call(parser, parserOptions); + return parser; } - return pos; -}; -/** @type {CharHandler} */ -const consumeLessThan = (input, pos, callbacks) => { - if (input.slice(pos + 1, pos + 4) === "!--") return pos + 4; - return pos + 1; -}; + getGenerator(type, generatorOptions = EMPTY_GENERATOR_OPTIONS) { + let cache = this.generatorCache.get(type); -/** @type {CharHandler} */ -const consumeAt = (input, pos, callbacks) => { - const start = pos; - pos++; - if (pos === input.length) return pos; - if (_startsIdentifier(input, pos)) { - pos = _consumeIdentifier(input, pos); - if (callbacks.atKeyword !== undefined) { - pos = callbacks.atKeyword(input, start, pos); + if (cache === undefined) { + cache = new WeakMap(); + this.generatorCache.set(type, cache); } - } - return pos; -}; -const CHAR_MAP = Array.from({ length: 0x80 }, (_, cc) => { - // https://drafts.csswg.org/css-syntax/#consume-token - switch (cc) { - case CC_LINE_FEED: - case CC_CARRIAGE_RETURN: - case CC_FORM_FEED: - case CC_TAB: - case CC_SPACE: - return consumeSpace; - case CC_QUOTATION_MARK: - case CC_APOSTROPHE: - return consumeString(cc); - case CC_NUMBER_SIGN: - return consumeNumberSign; - case CC_SLASH: - return consumePotentialComment; - // case CC_LEFT_SQUARE: - // case CC_RIGHT_SQUARE: - // case CC_COMMA: - // case CC_COLON: - // return consumeSingleCharToken; - case CC_COMMA: - return consumeComma; - case CC_SEMICOLON: - return consumeSemicolon; - case CC_LEFT_PARENTHESIS: - return consumeLeftParenthesis; - case CC_RIGHT_PARENTHESIS: - return consumeRightParenthesis; - case CC_LEFT_CURLY: - return consumeLeftCurlyBracket; - case CC_RIGHT_CURLY: - return consumeRightCurlyBracket; - case CC_COLON: - return consumePotentialPseudo; - case CC_PLUS_SIGN: - return consumeNumericToken; - case CC_FULL_STOP: - return consumeDot; - case CC_HYPHEN_MINUS: - return consumeMinus; - case CC_LESS_THAN_SIGN: - return consumeLessThan; - case CC_AT_SIGN: - return consumeAt; - case CC_LOWER_U: - return consumePotentialUrl; - case CC_LOW_LINE: - return consumeOtherIdentifier; - default: - if (_isDigit(cc)) return consumeNumericToken; - if ( - (cc >= CC_LOWER_A && cc <= CC_LOWER_Z) || - (cc >= CC_UPPER_A && cc <= CC_UPPER_Z) - ) { - return consumeOtherIdentifier; - } - return consumeSingleCharToken; - } -}); + let generator = cache.get(generatorOptions); -/** - * @param {string} input input css - * @param {CssTokenCallbacks} callbacks callbacks - * @returns {void} - */ -module.exports = (input, callbacks) => { - let pos = 0; - while (pos < input.length) { - const cc = input.charCodeAt(pos); - if (cc < 0x80) { - pos = CHAR_MAP[cc](input, pos, callbacks); - } else { - pos++; + if (generator === undefined) { + generator = this.createGenerator(type, generatorOptions); + cache.set(generatorOptions, generator); } + + return generator; } -}; -module.exports.eatComments = (input, pos) => { - loop: for (;;) { - const cc = input.charCodeAt(pos); - if (cc === CC_SLASH) { - if (pos === input.length) return pos; - let cc = input.charCodeAt(pos + 1); - if (cc !== CC_ASTERISK) return pos; - pos++; - for (;;) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - while (cc === CC_ASTERISK) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - if (cc === CC_SLASH) { - pos++; - continue loop; - } - } - } + createGenerator(type, generatorOptions = {}) { + generatorOptions = mergeGlobalOptions( + this._globalGeneratorOptions, + type, + generatorOptions + ); + const generator = this.hooks.createGenerator + .for(type) + .call(generatorOptions); + if (!generator) { + throw new Error(`No generator registered for ${type}`); } - return pos; + this.hooks.generator.for(type).call(generator, generatorOptions); + return generator; } -}; -module.exports.eatWhitespaceAndComments = (input, pos) => { - loop: for (;;) { - const cc = input.charCodeAt(pos); - if (cc === CC_SLASH) { - if (pos === input.length) return pos; - let cc = input.charCodeAt(pos + 1); - if (cc !== CC_ASTERISK) return pos; - pos++; - for (;;) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - while (cc === CC_ASTERISK) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - if (cc === CC_SLASH) { - pos++; - continue loop; - } - } - } - } else if (_isWhiteSpace(cc)) { - pos++; - continue; - } - return pos; + getResolver(type, resolveOptions) { + return this.resolverFactory.get(type, resolveOptions); } -}; +} + +module.exports = NormalModuleFactory; /***/ }), -/***/ 2757: +/***/ 30633: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const { Tracer } = __webpack_require__(5787); -const createSchemaValidation = __webpack_require__(32540); -const { dirname, mkdirpSync } = __webpack_require__(17139); +const { join, dirname } = __webpack_require__(17139); -/** @typedef {import("../../declarations/plugins/debug/ProfilingPlugin").ProfilingPluginOptions} ProfilingPluginOptions */ -/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {function(TODO): void} ModuleReplacer */ -const validate = createSchemaValidation( - __webpack_require__(37134), - () => __webpack_require__(50686), - { - name: "Profiling Plugin", - baseDataPath: "options" +class NormalModuleReplacementPlugin { + /** + * Create an instance of the plugin + * @param {RegExp} resourceRegExp the resource matcher + * @param {string|ModuleReplacer} newResource the resource replacement + */ + constructor(resourceRegExp, newResource) { + this.resourceRegExp = resourceRegExp; + this.newResource = newResource; } -); -let inspector = undefined; -try { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - inspector = __webpack_require__(31405); -} catch (e) { - console.log("Unable to CPU profile in < node 8.0"); + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const resourceRegExp = this.resourceRegExp; + const newResource = this.newResource; + compiler.hooks.normalModuleFactory.tap( + "NormalModuleReplacementPlugin", + nmf => { + nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => { + if (resourceRegExp.test(result.request)) { + if (typeof newResource === "function") { + newResource(result); + } else { + result.request = newResource; + } + } + }); + nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => { + const createData = result.createData; + if (resourceRegExp.test(createData.resource)) { + if (typeof newResource === "function") { + newResource(result); + } else { + const fs = compiler.inputFileSystem; + if ( + newResource.startsWith("/") || + (newResource.length > 1 && newResource[1] === ":") + ) { + createData.resource = newResource; + } else { + createData.resource = join( + fs, + dirname(fs, createData.resource), + newResource + ); + } + } + } + }); + } + ); + } } -class Profiler { - constructor(inspector) { - this.session = undefined; - this.inspector = inspector; - this._startTime = 0; - } +module.exports = NormalModuleReplacementPlugin; - hasSession() { - return this.session !== undefined; - } - startProfiling() { - if (this.inspector === undefined) { - return Promise.resolve(); - } +/***/ }), - try { - this.session = new inspector.Session(); - this.session.connect(); - } catch (_) { - this.session = undefined; - return Promise.resolve(); - } +/***/ 80057: +/***/ (function(__unused_webpack_module, exports) { - const hrtime = process.hrtime(); - this._startTime = hrtime[0] * 1000000 + Math.round(hrtime[1] / 1000); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ - return Promise.all([ - this.sendCommand("Profiler.setSamplingInterval", { - interval: 100 - }), - this.sendCommand("Profiler.enable"), - this.sendCommand("Profiler.start") - ]); - } - sendCommand(method, params) { - if (this.hasSession()) { - return new Promise((res, rej) => { - return this.session.post(method, params, (err, params) => { - if (err !== null) { - rej(err); - } else { - res(params); - } - }); - }); - } else { - return Promise.resolve(); - } - } - destroy() { - if (this.hasSession()) { - this.session.disconnect(); - } +exports.STAGE_BASIC = -10; +exports.STAGE_DEFAULT = 0; +exports.STAGE_ADVANCED = 10; - return Promise.resolve(); - } - stopProfiling() { - return this.sendCommand("Profiler.stop").then(({ profile }) => { - const hrtime = process.hrtime(); - const endTime = hrtime[0] * 1000000 + Math.round(hrtime[1] / 1000); - if (profile.startTime < this._startTime || profile.endTime > endTime) { - // In some cases timestamps mismatch and we need to adjust them - // Both process.hrtime and the inspector timestamps claim to be relative - // to a unknown point in time. But they do not guarantee that this is the - // same point in time. - const duration = profile.endTime - profile.startTime; - const ownDuration = endTime - this._startTime; - const untracked = Math.max(0, ownDuration - duration); - profile.startTime = this._startTime + untracked / 2; - profile.endTime = endTime - untracked / 2; - } - return { profile }; - }); - } -} +/***/ }), -/** - * an object that wraps Tracer and Profiler with a counter - * @typedef {Object} Trace - * @property {Tracer} trace instance of Tracer - * @property {number} counter Counter - * @property {Profiler} profiler instance of Profiler - * @property {Function} end the end function - */ +/***/ 81426: +/***/ (function(module) { -/** - * @param {IntermediateFileSystem} fs filesystem used for output - * @param {string} outputPath The location where to write the log. - * @returns {Trace} The trace object - */ -const createTrace = (fs, outputPath) => { - const trace = new Tracer(); - const profiler = new Profiler(inspector); - if (/\/|\\/.test(outputPath)) { - const dirPath = dirname(fs, outputPath); - mkdirpSync(fs, dirPath); - } - const fsStream = fs.createWriteStream(outputPath); - - let counter = 0; - - trace.pipe(fsStream); - // These are critical events that need to be inserted so that tools like - // chrome dev tools can load the profile. - trace.instantEvent({ - name: "TracingStartedInPage", - id: ++counter, - cat: ["disabled-by-default-devtools.timeline"], - args: { - data: { - sessionId: "-1", - page: "0xfff", - frames: [ - { - frame: "0xfff", - url: "webpack", - name: "" - } - ] - } - } - }); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - trace.instantEvent({ - name: "TracingStartedInBrowser", - id: ++counter, - cat: ["disabled-by-default-devtools.timeline"], - args: { - data: { - sessionId: "-1" - } - } - }); - return { - trace, - counter, - profiler, - end: callback => { - trace.push("]"); - // Wait until the write stream finishes. - fsStream.on("close", () => { - callback(); - }); - // Tear down the readable trace stream. - trace.push(null); - } - }; -}; -const pluginName = "ProfilingPlugin"; +class OptionsApply { + process(options, compiler) {} +} +module.exports = OptionsApply; -class ProfilingPlugin { - /** - * @param {ProfilingPluginOptions=} options options object - */ - constructor(options = {}) { - validate(options); - this.outputPath = options.outputPath || "events.json"; - } - apply(compiler) { - const tracer = createTrace( - compiler.intermediateFileSystem, - this.outputPath - ); - tracer.profiler.startProfiling(); +/***/ }), - // Compiler Hooks - Object.keys(compiler.hooks).forEach(hookName => { - const hook = compiler.hooks[hookName]; - if (hook) { - hook.intercept(makeInterceptorFor("Compiler", tracer)(hookName)); - } - }); +/***/ 11715: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - Object.keys(compiler.resolverFactory.hooks).forEach(hookName => { - const hook = compiler.resolverFactory.hooks[hookName]; - if (hook) { - hook.intercept(makeInterceptorFor("Resolver", tracer)(hookName)); - } - }); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - compiler.hooks.compilation.tap( - pluginName, - (compilation, { normalModuleFactory, contextModuleFactory }) => { - interceptAllHooksFor(compilation, tracer, "Compilation"); - interceptAllHooksFor( - normalModuleFactory, - tracer, - "Normal Module Factory" - ); - interceptAllHooksFor( - contextModuleFactory, - tracer, - "Context Module Factory" - ); - interceptAllParserHooks(normalModuleFactory, tracer); - interceptAllJavascriptModulesPluginHooks(compilation, tracer); - } - ); - // We need to write out the CPU profile when we are all done. - compiler.hooks.done.tapAsync( - { - name: pluginName, - stage: Infinity - }, - (stats, callback) => { - if (compiler.watchMode) return callback(); - tracer.profiler.stopProfiling().then(parsedResults => { - if (parsedResults === undefined) { - tracer.profiler.destroy(); - tracer.end(callback); - return; - } - const cpuStartTime = parsedResults.profile.startTime; - const cpuEndTime = parsedResults.profile.endTime; +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./NormalModule")} NormalModule */ - tracer.trace.completeEvent({ - name: "TaskQueueManager::ProcessTaskFromWorkQueue", - id: ++tracer.counter, - cat: ["toplevel"], - ts: cpuStartTime, - args: { - src_file: "../../ipc/ipc_moji_bootstrap.cc", - src_func: "Accept" - } - }); +/** @typedef {Record} PreparsedAst */ - tracer.trace.completeEvent({ - name: "EvaluateScript", - id: ++tracer.counter, - cat: ["devtools.timeline"], - ts: cpuStartTime, - dur: cpuEndTime - cpuStartTime, - args: { - data: { - url: "webpack", - lineNumber: 1, - columnNumber: 1, - frame: "0xFFF" - } - } - }); +/** + * @typedef {Object} ParserStateBase + * @property {string | Buffer} source + * @property {NormalModule} current + * @property {NormalModule} module + * @property {Compilation} compilation + * @property {{[k: string]: any}} options + */ - tracer.trace.instantEvent({ - name: "CpuProfile", - id: ++tracer.counter, - cat: ["disabled-by-default-devtools.timeline"], - ts: cpuEndTime, - args: { - data: { - cpuProfile: parsedResults.profile - } - } - }); +/** @typedef {Record & ParserStateBase} ParserState */ - tracer.profiler.destroy(); - tracer.end(callback); - }); - } - ); +class Parser { + /* istanbul ignore next */ + /** + * @abstract + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } } -const interceptAllHooksFor = (instance, tracer, logLabel) => { - if (Reflect.has(instance, "hooks")) { - Object.keys(instance.hooks).forEach(hookName => { - const hook = instance.hooks[hookName]; - if (hook && !hook._fakeHook) { - hook.intercept(makeInterceptorFor(logLabel, tracer)(hookName)); - } - }); - } -}; +module.exports = Parser; -const interceptAllParserHooks = (moduleFactory, tracer) => { - const moduleTypes = [ - "javascript/auto", - "javascript/dynamic", - "javascript/esm", - "json", - "webassembly/async", - "webassembly/sync" - ]; - moduleTypes.forEach(moduleType => { - moduleFactory.hooks.parser - .for(moduleType) - .tap("ProfilingPlugin", (parser, parserOpts) => { - interceptAllHooksFor(parser, tracer, "Parser"); - }); - }); -}; +/***/ }), -const interceptAllJavascriptModulesPluginHooks = (compilation, tracer) => { - interceptAllHooksFor( - { - hooks: - (__webpack_require__(89464).getCompilationHooks)( - compilation - ) - }, - tracer, - "JavascriptModulesPlugin" - ); -}; +/***/ 73850: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const makeInterceptorFor = (instance, tracer) => hookName => ({ - register: ({ name, type, context, fn }) => { - const newFn = - // Don't tap our own hooks to ensure stream can close cleanly - name === pluginName - ? fn - : makeNewProfiledTapFn(hookName, tracer, { - name, - type, - fn - }); - return { - name, - type, - context, - fn: newFn - }; - } -}); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -// TODO improve typing -/** @typedef {(...args: TODO[]) => void | Promise} PluginFunction */ -/** - * @param {string} hookName Name of the hook to profile. - * @param {Trace} tracer The trace object. - * @param {object} options Options for the profiled fn. - * @param {string} options.name Plugin name - * @param {string} options.type Plugin type (sync | async | promise) - * @param {PluginFunction} options.fn Plugin function - * @returns {PluginFunction} Chainable hooked function. - */ -const makeNewProfiledTapFn = (hookName, tracer, { name, type, fn }) => { - const defaultCategory = ["blink.user_timing"]; - switch (type) { - case "promise": - return (...args) => { - const id = ++tracer.counter; - tracer.trace.begin({ - name, - id, - cat: defaultCategory - }); - const promise = /** @type {Promise<*>} */ (fn(...args)); - return promise.then(r => { - tracer.trace.end({ - name, - id, - cat: defaultCategory - }); - return r; - }); - }; - case "async": - return (...args) => { - const id = ++tracer.counter; - tracer.trace.begin({ - name, - id, - cat: defaultCategory - }); - const callback = args.pop(); - fn(...args, (...r) => { - tracer.trace.end({ - name, - id, - cat: defaultCategory - }); - callback(...r); - }); - }; - case "sync": - return (...args) => { - const id = ++tracer.counter; - // Do not instrument ourself due to the CPU - // profile needing to be the last event in the trace. - if (name === pluginName) { - return fn(...args); - } +const PrefetchDependency = __webpack_require__(31618); - tracer.trace.begin({ - name, - id, - cat: defaultCategory - }); - let r; - try { - r = fn(...args); - } catch (error) { - tracer.trace.end({ - name, - id, - cat: defaultCategory - }); - throw error; +/** @typedef {import("./Compiler")} Compiler */ + +class PrefetchPlugin { + constructor(context, request) { + if (request) { + this.context = context; + this.request = request; + } else { + this.context = null; + this.request = context; + } + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "PrefetchPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + PrefetchDependency, + normalModuleFactory + ); + } + ); + compiler.hooks.make.tapAsync("PrefetchPlugin", (compilation, callback) => { + compilation.addModuleChain( + this.context || compiler.context, + new PrefetchDependency(this.request), + err => { + callback(err); } - tracer.trace.end({ - name, - id, - cat: defaultCategory - }); - return r; - }; - default: - break; + ); + }); } -}; +} -module.exports = ProfilingPlugin; -module.exports.Profiler = Profiler; +module.exports = PrefetchPlugin; /***/ }), -/***/ 96816: +/***/ 13216: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -70729,587 +63960,596 @@ module.exports.Profiler = Profiler; -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +const Compiler = __webpack_require__(70845); +const MultiCompiler = __webpack_require__(33370); +const NormalModule = __webpack_require__(39); +const createSchemaValidation = __webpack_require__(32540); +const { contextify } = __webpack_require__(82186); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../declarations/plugins/ProgressPlugin").HandlerFunction} HandlerFunction */ +/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */ +/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */ -/** @type {Record} */ -const DEFINITIONS = { - f: { - definition: "var __WEBPACK_AMD_DEFINE_RESULT__;", - content: `!(__WEBPACK_AMD_DEFINE_RESULT__ = (#).call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, - requests: [ - RuntimeGlobals.require, - RuntimeGlobals.exports, - RuntimeGlobals.module - ] - }, - o: { - definition: "", - content: "!(module.exports = #)", - requests: [RuntimeGlobals.module] - }, - of: { - definition: - "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;", - content: `!(__WEBPACK_AMD_DEFINE_FACTORY__ = (#), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : - __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, - requests: [ - RuntimeGlobals.require, - RuntimeGlobals.exports, - RuntimeGlobals.module - ] - }, - af: { - definition: - "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", - content: `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = (#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, - requests: [RuntimeGlobals.exports, RuntimeGlobals.module] - }, - ao: { - definition: "", - content: "!(#, module.exports = #)", - requests: [RuntimeGlobals.module] - }, - aof: { - definition: - "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", - content: `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, - requests: [RuntimeGlobals.exports, RuntimeGlobals.module] - }, - lf: { - definition: "var XXX, XXXmodule;", - content: - "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = (#).call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))", - requests: [RuntimeGlobals.require, RuntimeGlobals.module] - }, - lo: { - definition: "var XXX;", - content: "!(XXX = #)", - requests: [] - }, - lof: { - definition: "var XXX, XXXfactory, XXXmodule;", - content: - "!(XXXfactory = (#), (typeof XXXfactory === 'function' ? ((XXXmodule = { id: YYY, exports: {}, loaded: false }), (XXX = XXXfactory.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule)), (XXXmodule.loaded = true), XXX === undefined && (XXX = XXXmodule.exports)) : XXX = XXXfactory))", - requests: [RuntimeGlobals.require, RuntimeGlobals.module] - }, - laf: { - definition: "var __WEBPACK_AMD_DEFINE_ARRAY__, XXX, XXXexports;", - content: - "!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = (#).apply(XXXexports = {}, __WEBPACK_AMD_DEFINE_ARRAY__), XXX === undefined && (XXX = XXXexports))", - requests: [] - }, - lao: { - definition: "var XXX;", - content: "!(#, XXX = #)", - requests: [] - }, - laof: { - definition: "var XXXarray, XXXfactory, XXXexports, XXX;", - content: `!(XXXarray = #, XXXfactory = (#), - (typeof XXXfactory === 'function' ? - ((XXX = XXXfactory.apply(XXXexports = {}, XXXarray)), XXX === undefined && (XXX = XXXexports)) : - (XXX = XXXfactory) - ))`, - requests: [] +const validate = createSchemaValidation( + __webpack_require__(57647), + () => __webpack_require__(75202), + { + name: "Progress Plugin", + baseDataPath: "options" } +); +const median3 = (a, b, c) => { + return a + b + c - Math.max(a, b, c) - Math.min(a, b, c); }; -class AMDDefineDependency extends NullDependency { - constructor(range, arrayRange, functionRange, objectRange, namedModule) { - super(); - this.range = range; - this.arrayRange = arrayRange; - this.functionRange = functionRange; - this.objectRange = objectRange; - this.namedModule = namedModule; - this.localModule = null; - } +const createDefaultHandler = (profile, logger) => { + /** @type {{ value: string, time: number }[]} */ + const lastStateInfo = []; - get type() { - return "amd define"; - } + const defaultHandler = (percentage, msg, ...args) => { + if (profile) { + if (percentage === 0) { + lastStateInfo.length = 0; + } + const fullState = [msg, ...args]; + const state = fullState.map(s => s.replace(/\d+\/\d+ /g, "")); + const now = Date.now(); + const len = Math.max(state.length, lastStateInfo.length); + for (let i = len; i >= 0; i--) { + const stateItem = i < state.length ? state[i] : undefined; + const lastStateItem = + i < lastStateInfo.length ? lastStateInfo[i] : undefined; + if (lastStateItem) { + if (stateItem !== lastStateItem.value) { + const diff = now - lastStateItem.time; + if (lastStateItem.value) { + let reportState = lastStateItem.value; + if (i > 0) { + reportState = lastStateInfo[i - 1].value + " > " + reportState; + } + const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`; + const d = diff; + // This depends on timing so we ignore it for coverage + /* istanbul ignore next */ + { + if (d > 10000) { + logger.error(stateMsg); + } else if (d > 1000) { + logger.warn(stateMsg); + } else if (d > 10) { + logger.info(stateMsg); + } else if (d > 5) { + logger.log(stateMsg); + } else { + logger.debug(stateMsg); + } + } + } + if (stateItem === undefined) { + lastStateInfo.length = i; + } else { + lastStateItem.value = stateItem; + lastStateItem.time = now; + lastStateInfo.length = i + 1; + } + } + } else { + lastStateInfo[i] = { + value: stateItem, + time: now + }; + } + } + } + logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args); + if (percentage === 1 || (!msg && args.length === 0)) logger.status(); + }; - serialize(context) { - const { write } = context; - write(this.range); - write(this.arrayRange); - write(this.functionRange); - write(this.objectRange); - write(this.namedModule); - write(this.localModule); - super.serialize(context); - } + return defaultHandler; +}; - deserialize(context) { - const { read } = context; - this.range = read(); - this.arrayRange = read(); - this.functionRange = read(); - this.objectRange = read(); - this.namedModule = read(); - this.localModule = read(); - super.deserialize(context); +/** + * @callback ReportProgress + * @param {number} p + * @param {...string[]} [args] + * @returns {void} + */ + +/** @type {WeakMap} */ +const progressReporters = new WeakMap(); + +class ProgressPlugin { + /** + * @param {Compiler} compiler the current compiler + * @returns {ReportProgress} a progress reporter, if any + */ + static getReporter(compiler) { + return progressReporters.get(compiler); } -} -makeSerializable( - AMDDefineDependency, - "webpack/lib/dependencies/AMDDefineDependency" -); + /** + * @param {ProgressPluginArgument} options options + */ + constructor(options = {}) { + if (typeof options === "function") { + options = { + handler: options + }; + } + + validate(options); + options = { ...ProgressPlugin.defaultOptions, ...options }; + + this.profile = options.profile; + this.handler = options.handler; + this.modulesCount = options.modulesCount; + this.dependenciesCount = options.dependenciesCount; + this.showEntries = options.entries; + this.showModules = options.modules; + this.showDependencies = options.dependencies; + this.showActiveModules = options.activeModules; + this.percentBy = options.percentBy; + } -AMDDefineDependency.Template = class AMDDefineDependencyTemplate extends ( - NullDependency.Template -) { /** - * @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 + * @param {Compiler | MultiCompiler} compiler webpack compiler * @returns {void} */ - apply(dependency, source, { runtimeRequirements }) { - const dep = /** @type {AMDDefineDependency} */ (dependency); - const branch = this.branch(dep); - const { definition, content, requests } = DEFINITIONS[branch]; - for (const req of requests) { - runtimeRequirements.add(req); + apply(compiler) { + const handler = + this.handler || + createDefaultHandler( + this.profile, + compiler.getInfrastructureLogger("webpack.Progress") + ); + if (compiler instanceof MultiCompiler) { + this._applyOnMultiCompiler(compiler, handler); + } else if (compiler instanceof Compiler) { + this._applyOnCompiler(compiler, handler); } - this.replace(dep, source, definition, content); } - localModuleVar(dependency) { - return ( - dependency.localModule && - dependency.localModule.used && - dependency.localModule.variableName() + /** + * @param {MultiCompiler} compiler webpack multi-compiler + * @param {HandlerFunction} handler function that executes for every progress step + * @returns {void} + */ + _applyOnMultiCompiler(compiler, handler) { + const states = compiler.compilers.map( + () => /** @type {[number, ...string[]]} */ ([0]) ); + compiler.compilers.forEach((compiler, idx) => { + new ProgressPlugin((p, msg, ...args) => { + states[idx] = [p, msg, ...args]; + let sum = 0; + for (const [p] of states) sum += p; + handler(sum / states.length, `[${idx}] ${msg}`, ...args); + }).apply(compiler); + }); } - branch(dependency) { - const localModuleVar = this.localModuleVar(dependency) ? "l" : ""; - const arrayRange = dependency.arrayRange ? "a" : ""; - const objectRange = dependency.objectRange ? "o" : ""; - const functionRange = dependency.functionRange ? "f" : ""; - return localModuleVar + arrayRange + objectRange + functionRange; - } + /** + * @param {Compiler} compiler webpack compiler + * @param {HandlerFunction} handler function that executes for every progress step + * @returns {void} + */ + _applyOnCompiler(compiler, handler) { + const showEntries = this.showEntries; + const showModules = this.showModules; + const showDependencies = this.showDependencies; + const showActiveModules = this.showActiveModules; + let lastActiveModule = ""; + let currentLoader = ""; + let lastModulesCount = 0; + let lastDependenciesCount = 0; + let lastEntriesCount = 0; + let modulesCount = 0; + let dependenciesCount = 0; + let entriesCount = 1; + let doneModules = 0; + let doneDependencies = 0; + let doneEntries = 0; + const activeModules = new Set(); + let lastUpdate = 0; - replace(dependency, source, definition, text) { - const localModuleVar = this.localModuleVar(dependency); - if (localModuleVar) { - text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); - definition = definition.replace( - /XXX/g, - localModuleVar.replace(/\$/g, "$$$$") - ); - } + const updateThrottled = () => { + if (lastUpdate + 500 < Date.now()) update(); + }; - if (dependency.namedModule) { - text = text.replace(/YYY/g, JSON.stringify(dependency.namedModule)); - } + const update = () => { + /** @type {string[]} */ + const items = []; + const percentByModules = + doneModules / + Math.max(lastModulesCount || this.modulesCount || 1, modulesCount); + const percentByEntries = + doneEntries / + Math.max(lastEntriesCount || this.dependenciesCount || 1, entriesCount); + const percentByDependencies = + doneDependencies / + Math.max(lastDependenciesCount || 1, dependenciesCount); + let percentageFactor; - const texts = text.split("#"); + switch (this.percentBy) { + case "entries": + percentageFactor = percentByEntries; + break; + case "dependencies": + percentageFactor = percentByDependencies; + break; + case "modules": + percentageFactor = percentByModules; + break; + default: + percentageFactor = median3( + percentByModules, + percentByEntries, + percentByDependencies + ); + } - if (definition) source.insert(0, definition); + const percentage = 0.1 + percentageFactor * 0.55; - let current = dependency.range[0]; - if (dependency.arrayRange) { - source.replace(current, dependency.arrayRange[0] - 1, texts.shift()); - current = dependency.arrayRange[1]; - } + if (currentLoader) { + items.push( + `import loader ${contextify( + compiler.context, + currentLoader, + compiler.root + )}` + ); + } else { + const statItems = []; + if (showEntries) { + statItems.push(`${doneEntries}/${entriesCount} entries`); + } + if (showDependencies) { + statItems.push( + `${doneDependencies}/${dependenciesCount} dependencies` + ); + } + if (showModules) { + statItems.push(`${doneModules}/${modulesCount} modules`); + } + if (showActiveModules) { + statItems.push(`${activeModules.size} active`); + } + if (statItems.length > 0) { + items.push(statItems.join(" ")); + } + if (showActiveModules) { + items.push(lastActiveModule); + } + } + handler(percentage, "building", ...items); + lastUpdate = Date.now(); + }; - if (dependency.objectRange) { - source.replace(current, dependency.objectRange[0] - 1, texts.shift()); - current = dependency.objectRange[1]; - } else if (dependency.functionRange) { - source.replace(current, dependency.functionRange[0] - 1, texts.shift()); - current = dependency.functionRange[1]; - } - source.replace(current, dependency.range[1] - 1, texts.shift()); - if (texts.length > 0) throw new Error("Implementation error"); - } -}; + const factorizeAdd = () => { + dependenciesCount++; + if (dependenciesCount < 50 || dependenciesCount % 100 === 0) + updateThrottled(); + }; -module.exports = AMDDefineDependency; + const factorizeDone = () => { + doneDependencies++; + if (doneDependencies < 50 || doneDependencies % 100 === 0) + updateThrottled(); + }; + const moduleAdd = () => { + modulesCount++; + if (modulesCount < 50 || modulesCount % 100 === 0) updateThrottled(); + }; -/***/ }), + // only used when showActiveModules is set + const moduleBuild = module => { + const ident = module.identifier(); + if (ident) { + activeModules.add(ident); + lastActiveModule = ident; + update(); + } + }; -/***/ 48519: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const entryAdd = (entry, options) => { + entriesCount++; + if (entriesCount < 5 || entriesCount % 10 === 0) updateThrottled(); + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const moduleDone = module => { + doneModules++; + if (showActiveModules) { + const ident = module.identifier(); + if (ident) { + activeModules.delete(ident); + if (lastActiveModule === ident) { + lastActiveModule = ""; + for (const m of activeModules) { + lastActiveModule = m; + } + update(); + return; + } + } + } + if (doneModules < 50 || doneModules % 100 === 0) updateThrottled(); + }; + const entryDone = (entry, options) => { + doneEntries++; + update(); + }; + const cache = compiler + .getCache("ProgressPlugin") + .getItemCache("counts", null); -const RuntimeGlobals = __webpack_require__(16475); -const AMDDefineDependency = __webpack_require__(96816); -const AMDRequireArrayDependency = __webpack_require__(33516); -const AMDRequireContextDependency = __webpack_require__(96123); -const AMDRequireItemDependency = __webpack_require__(71806); -const ConstDependency = __webpack_require__(76911); -const ContextDependencyHelpers = __webpack_require__(99630); -const DynamicExports = __webpack_require__(32006); -const LocalModuleDependency = __webpack_require__(52805); -const { addLocalModule, getLocalModule } = __webpack_require__(75827); + let cacheGetPromise; -const isBoundFunctionExpression = expr => { - if (expr.type !== "CallExpression") return false; - if (expr.callee.type !== "MemberExpression") return false; - if (expr.callee.computed) return false; - if (expr.callee.object.type !== "FunctionExpression") return false; - if (expr.callee.property.type !== "Identifier") return false; - if (expr.callee.property.name !== "bind") return false; - return true; -}; + compiler.hooks.beforeCompile.tap("ProgressPlugin", () => { + if (!cacheGetPromise) { + cacheGetPromise = cache.getPromise().then( + data => { + if (data) { + lastModulesCount = lastModulesCount || data.modulesCount; + lastDependenciesCount = + lastDependenciesCount || data.dependenciesCount; + } + return data; + }, + err => { + // Ignore error + } + ); + } + }); -const isUnboundFunctionExpression = expr => { - if (expr.type === "FunctionExpression") return true; - if (expr.type === "ArrowFunctionExpression") return true; - return false; -}; + compiler.hooks.afterCompile.tapPromise("ProgressPlugin", compilation => { + if (compilation.compiler.isChild()) return Promise.resolve(); + return cacheGetPromise.then(async oldData => { + if ( + !oldData || + oldData.modulesCount !== modulesCount || + oldData.dependenciesCount !== dependenciesCount + ) { + await cache.storePromise({ modulesCount, dependenciesCount }); + } + }); + }); -const isCallable = expr => { - if (isUnboundFunctionExpression(expr)) return true; - if (isBoundFunctionExpression(expr)) return true; - return false; -}; + compiler.hooks.compilation.tap("ProgressPlugin", compilation => { + if (compilation.compiler.isChild()) return; + lastModulesCount = modulesCount; + lastEntriesCount = entriesCount; + lastDependenciesCount = dependenciesCount; + modulesCount = dependenciesCount = entriesCount = 0; + doneModules = doneDependencies = doneEntries = 0; -class AMDDefineDependencyParserPlugin { - constructor(options) { - this.options = options; - } + compilation.factorizeQueue.hooks.added.tap( + "ProgressPlugin", + factorizeAdd + ); + compilation.factorizeQueue.hooks.result.tap( + "ProgressPlugin", + factorizeDone + ); - apply(parser) { - parser.hooks.call - .for("define") - .tap( - "AMDDefineDependencyParserPlugin", - this.processCallDefine.bind(this, parser) + compilation.addModuleQueue.hooks.added.tap("ProgressPlugin", moduleAdd); + compilation.processDependenciesQueue.hooks.result.tap( + "ProgressPlugin", + moduleDone ); - } - processArray(parser, expr, param, identifiers, namedModule) { - if (param.isArray()) { - param.items.forEach((param, idx) => { - if ( - param.isString() && - ["require", "module", "exports"].includes(param.string) - ) - identifiers[idx] = param.string; - const result = this.processItem(parser, expr, param, namedModule); - if (result === undefined) { - this.processContext(parser, expr, param); - } - }); - return true; - } else if (param.isConstArray()) { - const deps = []; - param.array.forEach((request, idx) => { - let dep; - let localModule; - if (request === "require") { - identifiers[idx] = request; - dep = "__webpack_require__"; - } else if (["exports", "module"].includes(request)) { - identifiers[idx] = request; - dep = request; - } else if ((localModule = getLocalModule(parser.state, request))) { - localModule.flagUsed(); - dep = new LocalModuleDependency(localModule, undefined, false); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - } else { - dep = this.newRequireItemDependency(request); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - } - deps.push(dep); - }); - const dep = this.newRequireArrayDependency(deps, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.module.addPresentationalDependency(dep); - return true; - } - } - processItem(parser, expr, param, namedModule) { - if (param.isConditional()) { - param.options.forEach(param => { - const result = this.processItem(parser, expr, param); - if (result === undefined) { - this.processContext(parser, expr, param); - } - }); - return true; - } else if (param.isString()) { - let dep, localModule; - if (param.string === "require") { - dep = new ConstDependency("__webpack_require__", param.range, [ - RuntimeGlobals.require - ]); - } else if (param.string === "exports") { - dep = new ConstDependency("exports", param.range, [ - RuntimeGlobals.exports - ]); - } else if (param.string === "module") { - dep = new ConstDependency("module", param.range, [ - RuntimeGlobals.module - ]); - } else if ( - (localModule = getLocalModule(parser.state, param.string, namedModule)) - ) { - localModule.flagUsed(); - dep = new LocalModuleDependency(localModule, param.range, false); - } else { - dep = this.newRequireItemDependency(param.string, param.range); - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; + if (showActiveModules) { + compilation.hooks.buildModule.tap("ProgressPlugin", moduleBuild); } - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - } - } - processContext(parser, expr, param) { - const dep = ContextDependencyHelpers.create( - AMDRequireContextDependency, - param.range, - param, - expr, - this.options, - { - category: "amd" - }, - parser - ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - processCallDefine(parser, expr) { - let array, fn, obj, namedModule; - switch (expr.arguments.length) { - case 1: - if (isCallable(expr.arguments[0])) { - // define(f() {…}) - fn = expr.arguments[0]; - } else if (expr.arguments[0].type === "ObjectExpression") { - // define({…}) - obj = expr.arguments[0]; - } else { - // define(expr) - // unclear if function or object - obj = fn = expr.arguments[0]; - } - break; - case 2: - if (expr.arguments[0].type === "Literal") { - namedModule = expr.arguments[0].value; - // define("…", …) - if (isCallable(expr.arguments[1])) { - // define("…", f() {…}) - fn = expr.arguments[1]; - } else if (expr.arguments[1].type === "ObjectExpression") { - // define("…", {…}) - obj = expr.arguments[1]; - } else { - // define("…", expr) - // unclear if function or object - obj = fn = expr.arguments[1]; - } - } else { - array = expr.arguments[0]; - if (isCallable(expr.arguments[1])) { - // define([…], f() {}) - fn = expr.arguments[1]; - } else if (expr.arguments[1].type === "ObjectExpression") { - // define([…], {…}) - obj = expr.arguments[1]; - } else { - // define([…], expr) - // unclear if function or object - obj = fn = expr.arguments[1]; - } - } - break; - case 3: - // define("…", […], f() {…}) - namedModule = expr.arguments[0].value; - array = expr.arguments[1]; - if (isCallable(expr.arguments[2])) { - // define("…", […], f() {}) - fn = expr.arguments[2]; - } else if (expr.arguments[2].type === "ObjectExpression") { - // define("…", […], {…}) - obj = expr.arguments[2]; - } else { - // define("…", […], expr) - // unclear if function or object - obj = fn = expr.arguments[2]; - } - break; - default: - return; - } - DynamicExports.bailout(parser.state); - let fnParams = null; - let fnParamsOffset = 0; - if (fn) { - if (isUnboundFunctionExpression(fn)) { - fnParams = fn.params; - } else if (isBoundFunctionExpression(fn)) { - fnParams = fn.callee.object.params; - fnParamsOffset = fn.arguments.length - 1; - if (fnParamsOffset < 0) { - fnParamsOffset = 0; - } - } - } - let fnRenames = new Map(); - if (array) { - const identifiers = {}; - const param = parser.evaluateExpression(array); - const result = this.processArray( - parser, - expr, - param, - identifiers, - namedModule - ); - if (!result) return; - if (fnParams) { - fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { - if (identifiers[idx]) { - fnRenames.set(param.name, parser.getVariableInfo(identifiers[idx])); - return false; - } - return true; - }); - } - } else { - const identifiers = ["require", "exports", "module"]; - if (fnParams) { - fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { - if (identifiers[idx]) { - fnRenames.set(param.name, parser.getVariableInfo(identifiers[idx])); - return false; + compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd); + compilation.hooks.failedEntry.tap("ProgressPlugin", entryDone); + compilation.hooks.succeedEntry.tap("ProgressPlugin", entryDone); + + // avoid dynamic require if bundled with webpack + // @ts-expect-error + if (false) {} + + const hooks = { + finishModules: "finish module graph", + seal: "plugins", + optimizeDependencies: "dependencies optimization", + afterOptimizeDependencies: "after dependencies optimization", + beforeChunks: "chunk graph", + afterChunks: "after chunk graph", + optimize: "optimizing", + optimizeModules: "module optimization", + afterOptimizeModules: "after module optimization", + optimizeChunks: "chunk optimization", + afterOptimizeChunks: "after chunk optimization", + optimizeTree: "module and chunk tree optimization", + afterOptimizeTree: "after module and chunk tree optimization", + optimizeChunkModules: "chunk modules optimization", + afterOptimizeChunkModules: "after chunk modules optimization", + reviveModules: "module reviving", + beforeModuleIds: "before module ids", + moduleIds: "module ids", + optimizeModuleIds: "module id optimization", + afterOptimizeModuleIds: "module id optimization", + reviveChunks: "chunk reviving", + beforeChunkIds: "before chunk ids", + chunkIds: "chunk ids", + optimizeChunkIds: "chunk id optimization", + afterOptimizeChunkIds: "after chunk id optimization", + recordModules: "record modules", + recordChunks: "record chunks", + beforeModuleHash: "module hashing", + beforeCodeGeneration: "code generation", + beforeRuntimeRequirements: "runtime requirements", + beforeHash: "hashing", + afterHash: "after hashing", + recordHash: "record hash", + beforeModuleAssets: "module assets processing", + beforeChunkAssets: "chunk assets processing", + processAssets: "asset processing", + afterProcessAssets: "after asset optimization", + record: "recording", + afterSeal: "after seal" + }; + const numberOfHooks = Object.keys(hooks).length; + Object.keys(hooks).forEach((name, idx) => { + const title = hooks[name]; + const percentage = (idx / numberOfHooks) * 0.25 + 0.7; + compilation.hooks[name].intercept({ + name: "ProgressPlugin", + call() { + handler(percentage, "sealing", title); + }, + done() { + progressReporters.set(compiler, undefined); + handler(percentage, "sealing", title); + }, + result() { + handler(percentage, "sealing", title); + }, + error() { + handler(percentage, "sealing", title); + }, + tap(tap) { + // p is percentage from 0 to 1 + // args is any number of messages in a hierarchical matter + progressReporters.set(compilation.compiler, (p, ...args) => { + handler(percentage, "sealing", title, tap.name, ...args); + }); + handler(percentage, "sealing", title, tap.name); } - return true; }); + }); + }); + compiler.hooks.make.intercept({ + name: "ProgressPlugin", + call() { + handler(0.1, "building"); + }, + done() { + handler(0.65, "building"); } - } - let inTry; - if (fn && isUnboundFunctionExpression(fn)) { - inTry = parser.scope.inTry; - parser.inScope(fnParams, () => { - for (const [name, varInfo] of fnRenames) { - parser.setVariable(name, varInfo); - } - parser.scope.inTry = inTry; - if (fn.body.type === "BlockStatement") { - parser.detectMode(fn.body.body); - const prev = parser.prevStatement; - parser.preWalkStatement(fn.body); - parser.prevStatement = prev; - parser.walkStatement(fn.body); - } else { - parser.walkExpression(fn.body); + }); + const interceptHook = (hook, progress, category, name) => { + hook.intercept({ + name: "ProgressPlugin", + call() { + handler(progress, category, name); + }, + done() { + progressReporters.set(compiler, undefined); + handler(progress, category, name); + }, + result() { + handler(progress, category, name); + }, + error() { + handler(progress, category, name); + }, + tap(tap) { + progressReporters.set(compiler, (p, ...args) => { + handler(progress, category, name, tap.name, ...args); + }); + handler(progress, category, name, tap.name); } }); - } else if (fn && isBoundFunctionExpression(fn)) { - inTry = parser.scope.inTry; - parser.inScope( - fn.callee.object.params.filter( - i => !["require", "module", "exports"].includes(i.name) - ), - () => { - for (const [name, varInfo] of fnRenames) { - parser.setVariable(name, varInfo); - } - parser.scope.inTry = inTry; - if (fn.callee.object.body.type === "BlockStatement") { - parser.detectMode(fn.callee.object.body.body); - const prev = parser.prevStatement; - parser.preWalkStatement(fn.callee.object.body); - parser.prevStatement = prev; - parser.walkStatement(fn.callee.object.body); - } else { - parser.walkExpression(fn.callee.object.body); - } - } - ); - if (fn.arguments) { - parser.walkExpressions(fn.arguments); + }; + compiler.cache.hooks.endIdle.intercept({ + name: "ProgressPlugin", + call() { + handler(0, ""); } - } else if (fn || obj) { - parser.walkExpression(fn || obj); - } - - const dep = this.newDefineDependency( - expr.range, - array ? array.range : null, - fn ? fn.range : null, - obj ? obj.range : null, - namedModule ? namedModule : null + }); + interceptHook(compiler.cache.hooks.endIdle, 0.01, "cache", "end idle"); + compiler.hooks.initialize.intercept({ + name: "ProgressPlugin", + call() { + handler(0, ""); + } + }); + interceptHook(compiler.hooks.initialize, 0.01, "setup", "initialize"); + interceptHook(compiler.hooks.beforeRun, 0.02, "setup", "before run"); + interceptHook(compiler.hooks.run, 0.03, "setup", "run"); + interceptHook(compiler.hooks.watchRun, 0.03, "setup", "watch run"); + interceptHook( + compiler.hooks.normalModuleFactory, + 0.04, + "setup", + "normal module factory" ); - dep.loc = expr.loc; - if (namedModule) { - dep.localModule = addLocalModule(parser.state, namedModule); - } - parser.state.module.addPresentationalDependency(dep); - return true; - } - - newDefineDependency( - range, - arrayRange, - functionRange, - objectRange, - namedModule - ) { - return new AMDDefineDependency( - range, - arrayRange, - functionRange, - objectRange, - namedModule + interceptHook( + compiler.hooks.contextModuleFactory, + 0.05, + "setup", + "context module factory" ); - } - newRequireArrayDependency(depsArray, range) { - return new AMDRequireArrayDependency(depsArray, range); - } - newRequireItemDependency(request, range) { - return new AMDRequireItemDependency(request, range); + interceptHook( + compiler.hooks.beforeCompile, + 0.06, + "setup", + "before compile" + ); + interceptHook(compiler.hooks.compile, 0.07, "setup", "compile"); + interceptHook(compiler.hooks.thisCompilation, 0.08, "setup", "compilation"); + interceptHook(compiler.hooks.compilation, 0.09, "setup", "compilation"); + interceptHook(compiler.hooks.finishMake, 0.69, "building", "finish"); + interceptHook(compiler.hooks.emit, 0.95, "emitting", "emit"); + interceptHook(compiler.hooks.afterEmit, 0.98, "emitting", "after emit"); + interceptHook(compiler.hooks.done, 0.99, "done", "plugins"); + compiler.hooks.done.intercept({ + name: "ProgressPlugin", + done() { + handler(0.99, ""); + } + }); + interceptHook( + compiler.cache.hooks.storeBuildDependencies, + 0.99, + "cache", + "store build dependencies" + ); + interceptHook(compiler.cache.hooks.shutdown, 0.99, "cache", "shutdown"); + interceptHook(compiler.cache.hooks.beginIdle, 0.99, "cache", "begin idle"); + interceptHook( + compiler.hooks.watchClose, + 0.99, + "end", + "closing watch compilation" + ); + compiler.cache.hooks.beginIdle.intercept({ + name: "ProgressPlugin", + done() { + handler(1, ""); + } + }); + compiler.cache.hooks.shutdown.intercept({ + name: "ProgressPlugin", + done() { + handler(1, ""); + } + }); } } -module.exports = AMDDefineDependencyParserPlugin; + +ProgressPlugin.defaultOptions = { + profile: false, + modulesCount: 5000, + dependenciesCount: 10000, + modules: true, + dependencies: true, + activeModules: false, + entries: true +}; + +module.exports = ProgressPlugin; /***/ }), -/***/ 50067: +/***/ 38309: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -71320,38 +64560,18 @@ module.exports = AMDDefineDependencyParserPlugin; -const RuntimeGlobals = __webpack_require__(16475); -const { - approve, - evaluateToIdentifier, - evaluateToString, - toConstantDependency -} = __webpack_require__(93998); - -const AMDDefineDependency = __webpack_require__(96816); -const AMDDefineDependencyParserPlugin = __webpack_require__(48519); -const AMDRequireArrayDependency = __webpack_require__(33516); -const AMDRequireContextDependency = __webpack_require__(96123); -const AMDRequireDependenciesBlockParserPlugin = __webpack_require__(66866); -const AMDRequireDependency = __webpack_require__(43911); -const AMDRequireItemDependency = __webpack_require__(71806); -const { - AMDDefineRuntimeModule, - AMDOptionsRuntimeModule -} = __webpack_require__(45242); const ConstDependency = __webpack_require__(76911); -const LocalModuleDependency = __webpack_require__(52805); -const UnsupportedDependency = __webpack_require__(51669); +const ProvidedDependency = __webpack_require__(95770); +const { approve } = __webpack_require__(93998); -/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("./Compiler")} Compiler */ -class AMDPlugin { +class ProvidePlugin { /** - * @param {Record} amdOptions the AMD options + * @param {Record} definitions the provided identifiers */ - constructor(amdOptions) { - this.amdOptions = amdOptions; + constructor(definitions) { + this.definitions = definitions; } /** @@ -71360,180 +64580,85 @@ class AMDPlugin { * @returns {void} */ apply(compiler) { - const amdOptions = this.amdOptions; + const definitions = this.definitions; compiler.hooks.compilation.tap( - "AMDPlugin", - (compilation, { contextModuleFactory, normalModuleFactory }) => { + "ProvidePlugin", + (compilation, { normalModuleFactory }) => { compilation.dependencyTemplates.set( - AMDRequireDependency, - new AMDRequireDependency.Template() + ConstDependency, + new ConstDependency.Template() ); - compilation.dependencyFactories.set( - AMDRequireItemDependency, + ProvidedDependency, normalModuleFactory ); compilation.dependencyTemplates.set( - AMDRequireItemDependency, - new AMDRequireItemDependency.Template() - ); - - compilation.dependencyTemplates.set( - AMDRequireArrayDependency, - new AMDRequireArrayDependency.Template() - ); - - compilation.dependencyFactories.set( - AMDRequireContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - AMDRequireContextDependency, - new AMDRequireContextDependency.Template() - ); - - compilation.dependencyTemplates.set( - AMDDefineDependency, - new AMDDefineDependency.Template() - ); - - compilation.dependencyTemplates.set( - UnsupportedDependency, - new UnsupportedDependency.Template() - ); - - compilation.dependencyTemplates.set( - LocalModuleDependency, - new LocalModuleDependency.Template() + ProvidedDependency, + new ProvidedDependency.Template() ); - - compilation.hooks.runtimeRequirementInModule - .for(RuntimeGlobals.amdDefine) - .tap("AMDPlugin", (module, set) => { - set.add(RuntimeGlobals.require); - }); - - compilation.hooks.runtimeRequirementInModule - .for(RuntimeGlobals.amdOptions) - .tap("AMDPlugin", (module, set) => { - set.add(RuntimeGlobals.requireScope); - }); - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.amdDefine) - .tap("AMDPlugin", (chunk, set) => { - compilation.addRuntimeModule(chunk, new AMDDefineRuntimeModule()); - }); - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.amdOptions) - .tap("AMDPlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new AMDOptionsRuntimeModule(amdOptions) - ); - }); - const handler = (parser, parserOptions) => { - if (parserOptions.amd !== undefined && !parserOptions.amd) return; + Object.keys(definitions).forEach(name => { + const request = [].concat(definitions[name]); + const splittedName = name.split("."); + if (splittedName.length > 0) { + splittedName.slice(1).forEach((_, i) => { + const name = splittedName.slice(0, i + 1).join("."); + parser.hooks.canRename.for(name).tap("ProvidePlugin", approve); + }); + } - const tapOptionsHooks = (optionExpr, rootName, getMembers) => { - parser.hooks.expression - .for(optionExpr) - .tap( - "AMDPlugin", - toConstantDependency(parser, RuntimeGlobals.amdOptions, [ - RuntimeGlobals.amdOptions - ]) - ); - parser.hooks.evaluateIdentifier - .for(optionExpr) - .tap( - "AMDPlugin", - evaluateToIdentifier(optionExpr, rootName, getMembers, true) - ); - parser.hooks.evaluateTypeof - .for(optionExpr) - .tap("AMDPlugin", evaluateToString("object")); - parser.hooks.typeof - .for(optionExpr) - .tap( - "AMDPlugin", - toConstantDependency(parser, JSON.stringify("object")) + parser.hooks.expression.for(name).tap("ProvidePlugin", expr => { + const nameIdentifier = name.includes(".") + ? `__webpack_provided_${name.replace(/\./g, "_dot_")}` + : name; + const dep = new ProvidedDependency( + request[0], + nameIdentifier, + request.slice(1), + expr.range ); - }; - - new AMDRequireDependenciesBlockParserPlugin(parserOptions).apply( - parser - ); - new AMDDefineDependencyParserPlugin(parserOptions).apply(parser); - - tapOptionsHooks("define.amd", "define", () => "amd"); - tapOptionsHooks("require.amd", "require", () => ["amd"]); - tapOptionsHooks( - "__webpack_amd_options__", - "__webpack_amd_options__", - () => [] - ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return true; + }); - parser.hooks.expression.for("define").tap("AMDPlugin", expr => { - const dep = new ConstDependency( - RuntimeGlobals.amdDefine, - expr.range, - [RuntimeGlobals.amdDefine] - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); - parser.hooks.typeof - .for("define") - .tap( - "AMDPlugin", - toConstantDependency(parser, JSON.stringify("function")) - ); - parser.hooks.evaluateTypeof - .for("define") - .tap("AMDPlugin", evaluateToString("function")); - parser.hooks.canRename.for("define").tap("AMDPlugin", approve); - parser.hooks.rename.for("define").tap("AMDPlugin", expr => { - const dep = new ConstDependency( - RuntimeGlobals.amdDefine, - expr.range, - [RuntimeGlobals.amdDefine] - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return false; + parser.hooks.call.for(name).tap("ProvidePlugin", expr => { + const nameIdentifier = name.includes(".") + ? `__webpack_provided_${name.replace(/\./g, "_dot_")}` + : name; + const dep = new ProvidedDependency( + request[0], + nameIdentifier, + request.slice(1), + expr.callee.range + ); + dep.loc = expr.callee.loc; + parser.state.module.addDependency(dep); + parser.walkExpressions(expr.arguments); + return true; + }); }); - parser.hooks.typeof - .for("require") - .tap( - "AMDPlugin", - toConstantDependency(parser, JSON.stringify("function")) - ); - parser.hooks.evaluateTypeof - .for("require") - .tap("AMDPlugin", evaluateToString("function")); }; - normalModuleFactory.hooks.parser .for("javascript/auto") - .tap("AMDPlugin", handler); + .tap("ProvidePlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") - .tap("AMDPlugin", handler); + .tap("ProvidePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ProvidePlugin", handler); } ); } } -module.exports = AMDPlugin; +module.exports = ProvidePlugin; /***/ }), -/***/ 33516: +/***/ 84929: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -71544,137 +64669,132 @@ module.exports = AMDPlugin; -const DependencyTemplate = __webpack_require__(5160); +const { OriginalSource, RawSource } = __webpack_require__(51255); +const Module = __webpack_require__(73208); const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @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("./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 */ -class AMDRequireArrayDependency extends NullDependency { - constructor(depsArray, range) { - super(); +const TYPES = new Set(["javascript"]); - this.depsArray = depsArray; - this.range = range; +class RawModule extends Module { + /** + * @param {string} source source code + * @param {string} identifier unique identifier + * @param {string=} readableIdentifier readable identifier + * @param {ReadonlySet=} runtimeRequirements runtime requirements needed for the source code + */ + constructor(source, identifier, readableIdentifier, runtimeRequirements) { + super("javascript/dynamic", null); + this.sourceStr = source; + this.identifierStr = identifier || this.sourceStr; + this.readableIdentifierStr = readableIdentifier || this.identifierStr; + this.runtimeRequirements = runtimeRequirements || null; } - get type() { - return "amd require array"; + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; } - get category() { - return "amd"; + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this.identifierStr; } - serialize(context) { - const { write } = context; - - write(this.depsArray); - write(this.range); - - super.serialize(context); + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + return Math.max(1, this.sourceStr.length); } - deserialize(context) { - const { read } = context; - - this.depsArray = read(); - this.range = read(); - - super.deserialize(context); + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.readableIdentifierStr); } -} - -makeSerializable( - AMDRequireArrayDependency, - "webpack/lib/dependencies/AMDRequireArrayDependency" -); -AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate extends ( - DependencyTemplate -) { /** - * @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 + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild * @returns {void} */ - apply(dependency, source, templateContext) { - const dep = /** @type {AMDRequireArrayDependency} */ (dependency); - const content = this.getContent(dep, templateContext); - source.replace(dep.range[0], dep.range[1] - 1, content); + needBuild(context, callback) { + return callback(null, !this.buildMeta); } - getContent(dep, templateContext) { - const requires = dep.depsArray.map(dependency => { - return this.contentForDependency(dependency, templateContext); - }); - return `[${requires.join(", ")}]`; + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {function(WebpackError=): void} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = { + cacheable: true + }; + callback(); } - contentForDependency( - dep, - { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } - ) { - if (typeof dep === "string") { - return dep; - } - - if (dep.localModule) { - return dep.localModule.variableName(); + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration(context) { + const sources = new Map(); + if (this.useSourceMap || this.useSimpleSourceMap) { + sources.set( + "javascript", + new OriginalSource(this.sourceStr, this.identifier()) + ); } else { - return runtimeTemplate.moduleExports({ - module: moduleGraph.getModule(dep), - chunkGraph, - request: dep.request, - runtimeRequirements - }); + sources.set("javascript", new RawSource(this.sourceStr)); } - } -}; - -module.exports = AMDRequireArrayDependency; - - -/***/ }), - -/***/ 96123: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const ContextDependency = __webpack_require__(88101); - -class AMDRequireContextDependency extends ContextDependency { - constructor(options, range, valueRange) { - super(options); - - this.range = range; - this.valueRange = valueRange; - } - - get type() { - return "amd require context"; + return { sources, runtimeRequirements: this.runtimeRequirements }; } - get category() { - return "amd"; + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + hash.update(this.sourceStr); + super.updateHash(hash, context); } serialize(context) { const { write } = context; - write(this.range); - write(this.valueRange); + write(this.sourceStr); + write(this.identifierStr); + write(this.readableIdentifierStr); + write(this.runtimeRequirements); super.serialize(context); } @@ -71682,26 +64802,23 @@ class AMDRequireContextDependency extends ContextDependency { deserialize(context) { const { read } = context; - this.range = read(); - this.valueRange = read(); + this.sourceStr = read(); + this.identifierStr = read(); + this.readableIdentifierStr = read(); + this.runtimeRequirements = read(); super.deserialize(context); } } -makeSerializable( - AMDRequireContextDependency, - "webpack/lib/dependencies/AMDRequireContextDependency" -); - -AMDRequireContextDependency.Template = __webpack_require__(75815); +makeSerializable(RawModule, "webpack/lib/RawModule"); -module.exports = AMDRequireContextDependency; +module.exports = RawModule; /***/ }), -/***/ 76932: +/***/ 11094: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -71712,313 +64829,242 @@ module.exports = AMDRequireContextDependency; -const AsyncDependenciesBlock = __webpack_require__(47736); -const makeSerializable = __webpack_require__(33032); - -class AMDRequireDependenciesBlock extends AsyncDependenciesBlock { - constructor(loc, request) { - super(null, loc, request); - } -} - -makeSerializable( - AMDRequireDependenciesBlock, - "webpack/lib/dependencies/AMDRequireDependenciesBlock" -); - -module.exports = AMDRequireDependenciesBlock; - - -/***/ }), - -/***/ 66866: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const { compareNumbers } = __webpack_require__(29579); +const identifierUtils = __webpack_require__(82186); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ +/** + * @typedef {Object} RecordsChunks + * @property {Record=} byName + * @property {Record=} bySource + * @property {number[]=} usedIds + */ +/** + * @typedef {Object} RecordsModules + * @property {Record=} byIdentifier + * @property {Record=} bySource + * @property {number[]=} usedIds + */ -const RuntimeGlobals = __webpack_require__(16475); -const UnsupportedFeatureWarning = __webpack_require__(42495); -const AMDRequireArrayDependency = __webpack_require__(33516); -const AMDRequireContextDependency = __webpack_require__(96123); -const AMDRequireDependenciesBlock = __webpack_require__(76932); -const AMDRequireDependency = __webpack_require__(43911); -const AMDRequireItemDependency = __webpack_require__(71806); -const ConstDependency = __webpack_require__(76911); -const ContextDependencyHelpers = __webpack_require__(99630); -const LocalModuleDependency = __webpack_require__(52805); -const { getLocalModule } = __webpack_require__(75827); -const UnsupportedDependency = __webpack_require__(51669); -const getFunctionExpression = __webpack_require__(50396); +/** + * @typedef {Object} Records + * @property {RecordsChunks=} chunks + * @property {RecordsModules=} modules + */ -class AMDRequireDependenciesBlockParserPlugin { +class RecordIdsPlugin { + /** + * @param {Object} options Options object + * @param {boolean=} options.portableIds true, when ids need to be portable + */ constructor(options) { - this.options = options; + this.options = options || {}; } - processFunctionArgument(parser, expression) { - let bindThis = true; - const fnData = getFunctionExpression(expression); - if (fnData) { - parser.inScope( - fnData.fn.params.filter(i => { - return !["require", "module", "exports"].includes(i.name); - }), - () => { - if (fnData.fn.body.type === "BlockStatement") { - parser.walkStatement(fnData.fn.body); - } else { - parser.walkExpression(fnData.fn.body); - } - } - ); - parser.walkExpressions(fnData.expressions); - if (fnData.needThis === false) { - bindThis = false; - } - } else { - parser.walkExpression(expression); - } - return bindThis; - } + /** + * @param {Compiler} compiler the Compiler + * @returns {void} + */ + apply(compiler) { + const portableIds = this.options.portableIds; - apply(parser) { - parser.hooks.call - .for("require") - .tap( - "AMDRequireDependenciesBlockParserPlugin", - this.processCallRequire.bind(this, parser) + const makePathsRelative = + identifierUtils.makePathsRelative.bindContextCache( + compiler.context, + compiler.root ); - } - processArray(parser, expr, param) { - if (param.isArray()) { - for (const p of param.items) { - const result = this.processItem(parser, expr, p); - if (result === undefined) { - this.processContext(parser, expr, p); - } - } - return true; - } else if (param.isConstArray()) { - const deps = []; - for (const request of param.array) { - let dep, localModule; - if (request === "require") { - dep = "__webpack_require__"; - } else if (["exports", "module"].includes(request)) { - dep = request; - } else if ((localModule = getLocalModule(parser.state, request))) { - localModule.flagUsed(); - dep = new LocalModuleDependency(localModule, undefined, false); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - } else { - dep = this.newRequireItemDependency(request); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - } - deps.push(dep); + /** + * @param {Module} module the module + * @returns {string} the (portable) identifier + */ + const getModuleIdentifier = module => { + if (portableIds) { + return makePathsRelative(module.identifier()); } - const dep = this.newRequireArrayDependency(deps, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.module.addPresentationalDependency(dep); - return true; - } - } - processItem(parser, expr, param) { - if (param.isConditional()) { - for (const p of param.options) { - const result = this.processItem(parser, expr, p); - if (result === undefined) { - this.processContext(parser, expr, p); - } - } - return true; - } else if (param.isString()) { - let dep, localModule; - if (param.string === "require") { - dep = new ConstDependency("__webpack_require__", param.string, [ - RuntimeGlobals.require - ]); - } else if (param.string === "module") { - dep = new ConstDependency( - parser.state.module.buildInfo.moduleArgument, - param.range, - [RuntimeGlobals.module] - ); - } else if (param.string === "exports") { - dep = new ConstDependency( - parser.state.module.buildInfo.exportsArgument, - param.range, - [RuntimeGlobals.exports] - ); - } else if ((localModule = getLocalModule(parser.state, param.string))) { - localModule.flagUsed(); - dep = new LocalModuleDependency(localModule, param.range, false); - } else { - dep = this.newRequireItemDependency(param.string, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - } - } - processContext(parser, expr, param) { - const dep = ContextDependencyHelpers.create( - AMDRequireContextDependency, - param.range, - param, - expr, - this.options, - { - category: "amd" - }, - parser - ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - - processArrayForRequestString(param) { - if (param.isArray()) { - const result = param.items.map(item => - this.processItemForRequestString(item) - ); - if (result.every(Boolean)) return result.join(" "); - } else if (param.isConstArray()) { - return param.array.join(" "); - } - } - - processItemForRequestString(param) { - if (param.isConditional()) { - const result = param.options.map(item => - this.processItemForRequestString(item) - ); - if (result.every(Boolean)) return result.join("|"); - } else if (param.isString()) { - return param.string; - } - } - - processCallRequire(parser, expr) { - let param; - let depBlock; - let dep; - let result; - - const old = parser.state.current; + return module.identifier(); + }; - if (expr.arguments.length >= 1) { - param = parser.evaluateExpression(expr.arguments[0]); - depBlock = this.newRequireDependenciesBlock( - expr.loc, - this.processArrayForRequestString(param) + compiler.hooks.compilation.tap("RecordIdsPlugin", compilation => { + compilation.hooks.recordModules.tap( + "RecordIdsPlugin", + /** + * @param {Module[]} modules the modules array + * @param {Records} records the records object + * @returns {void} + */ + (modules, records) => { + const chunkGraph = compilation.chunkGraph; + if (!records.modules) records.modules = {}; + if (!records.modules.byIdentifier) records.modules.byIdentifier = {}; + /** @type {Set} */ + const usedIds = new Set(); + for (const module of modules) { + const moduleId = chunkGraph.getModuleId(module); + if (typeof moduleId !== "number") continue; + const identifier = getModuleIdentifier(module); + records.modules.byIdentifier[identifier] = moduleId; + usedIds.add(moduleId); + } + records.modules.usedIds = Array.from(usedIds).sort(compareNumbers); + } ); - dep = this.newRequireDependency( - expr.range, - param.range, - expr.arguments.length > 1 ? expr.arguments[1].range : null, - expr.arguments.length > 2 ? expr.arguments[2].range : null + compilation.hooks.reviveModules.tap( + "RecordIdsPlugin", + /** + * @param {Module[]} modules the modules array + * @param {Records} records the records object + * @returns {void} + */ + (modules, records) => { + if (!records.modules) return; + if (records.modules.byIdentifier) { + const chunkGraph = compilation.chunkGraph; + /** @type {Set} */ + const usedIds = new Set(); + for (const module of modules) { + const moduleId = chunkGraph.getModuleId(module); + if (moduleId !== null) continue; + const identifier = getModuleIdentifier(module); + const id = records.modules.byIdentifier[identifier]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunkGraph.setModuleId(module, id); + } + } + if (Array.isArray(records.modules.usedIds)) { + compilation.usedModuleIds = new Set(records.modules.usedIds); + } + } ); - dep.loc = expr.loc; - depBlock.addDependency(dep); - parser.state.current = depBlock; - } - - if (expr.arguments.length === 1) { - parser.inScope([], () => { - result = this.processArray(parser, expr, param); - }); - parser.state.current = old; - if (!result) return; - parser.state.current.addBlock(depBlock); - return true; - } + /** + * @param {Chunk} chunk the chunk + * @returns {string[]} sources of the chunk + */ + const getChunkSources = chunk => { + /** @type {string[]} */ + const sources = []; + for (const chunkGroup of chunk.groupsIterable) { + const index = chunkGroup.chunks.indexOf(chunk); + if (chunkGroup.name) { + sources.push(`${index} ${chunkGroup.name}`); + } else { + for (const origin of chunkGroup.origins) { + if (origin.module) { + if (origin.request) { + sources.push( + `${index} ${getModuleIdentifier(origin.module)} ${ + origin.request + }` + ); + } else if (typeof origin.loc === "string") { + sources.push( + `${index} ${getModuleIdentifier(origin.module)} ${ + origin.loc + }` + ); + } else if ( + origin.loc && + typeof origin.loc === "object" && + "start" in origin.loc + ) { + sources.push( + `${index} ${getModuleIdentifier( + origin.module + )} ${JSON.stringify(origin.loc.start)}` + ); + } + } + } + } + } + return sources; + }; - if (expr.arguments.length === 2 || expr.arguments.length === 3) { - try { - parser.inScope([], () => { - result = this.processArray(parser, expr, param); - }); - if (!result) { - const dep = new UnsupportedDependency("unsupported", expr.range); - old.addPresentationalDependency(dep); - if (parser.state.module) { - parser.state.module.addError( - new UnsupportedFeatureWarning( - "Cannot statically analyse 'require(…, …)' in line " + - expr.loc.start.line, - expr.loc - ) - ); + compilation.hooks.recordChunks.tap( + "RecordIdsPlugin", + /** + * @param {Chunk[]} chunks the chunks array + * @param {Records} records the records object + * @returns {void} + */ + (chunks, records) => { + if (!records.chunks) records.chunks = {}; + if (!records.chunks.byName) records.chunks.byName = {}; + if (!records.chunks.bySource) records.chunks.bySource = {}; + /** @type {Set} */ + const usedIds = new Set(); + for (const chunk of chunks) { + if (typeof chunk.id !== "number") continue; + const name = chunk.name; + if (name) records.chunks.byName[name] = chunk.id; + const sources = getChunkSources(chunk); + for (const source of sources) { + records.chunks.bySource[source] = chunk.id; + } + usedIds.add(chunk.id); } - depBlock = null; - return true; + records.chunks.usedIds = Array.from(usedIds).sort(compareNumbers); } - dep.functionBindThis = this.processFunctionArgument( - parser, - expr.arguments[1] - ); - if (expr.arguments.length === 3) { - dep.errorCallbackBindThis = this.processFunctionArgument( - parser, - expr.arguments[2] - ); + ); + compilation.hooks.reviveChunks.tap( + "RecordIdsPlugin", + /** + * @param {Chunk[]} chunks the chunks array + * @param {Records} records the records object + * @returns {void} + */ + (chunks, records) => { + if (!records.chunks) return; + /** @type {Set} */ + const usedIds = new Set(); + if (records.chunks.byName) { + for (const chunk of chunks) { + if (chunk.id !== null) continue; + if (!chunk.name) continue; + const id = records.chunks.byName[chunk.name]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunk.id = id; + chunk.ids = [id]; + } + } + if (records.chunks.bySource) { + for (const chunk of chunks) { + if (chunk.id !== null) continue; + const sources = getChunkSources(chunk); + for (const source of sources) { + const id = records.chunks.bySource[source]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunk.id = id; + chunk.ids = [id]; + break; + } + } + } + if (Array.isArray(records.chunks.usedIds)) { + compilation.usedChunkIds = new Set(records.chunks.usedIds); + } } - } finally { - parser.state.current = old; - if (depBlock) parser.state.current.addBlock(depBlock); - } - return true; - } - } - - newRequireDependenciesBlock(loc, request) { - return new AMDRequireDependenciesBlock(loc, request); - } - newRequireDependency( - outerRange, - arrayRange, - functionRange, - errorCallbackRange - ) { - return new AMDRequireDependency( - outerRange, - arrayRange, - functionRange, - errorCallbackRange - ); - } - newRequireItemDependency(request, range) { - return new AMDRequireItemDependency(request, range); - } - newRequireArrayDependency(depsArray, range) { - return new AMDRequireArrayDependency(depsArray, range); + ); + }); } } -module.exports = AMDRequireDependenciesBlockParserPlugin; +module.exports = RecordIdsPlugin; /***/ }), -/***/ 43911: +/***/ 73406: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -72029,178 +65075,123 @@ module.exports = AMDRequireDependenciesBlockParserPlugin; -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - -class AMDRequireDependency extends NullDependency { - constructor(outerRange, arrayRange, functionRange, errorCallbackRange) { - super(); - - this.outerRange = outerRange; - this.arrayRange = arrayRange; - this.functionRange = functionRange; - this.errorCallbackRange = errorCallbackRange; - this.functionBindThis = false; - this.errorCallbackBindThis = false; - } - - get category() { - return "amd"; - } - - serialize(context) { - const { write } = context; - - write(this.outerRange); - write(this.arrayRange); - write(this.functionRange); - write(this.errorCallbackRange); - write(this.functionBindThis); - write(this.errorCallbackBindThis); - - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - - this.outerRange = read(); - this.arrayRange = read(); - this.functionRange = read(); - this.errorCallbackRange = read(); - this.functionBindThis = read(); - this.errorCallbackBindThis = read(); - - super.deserialize(context); - } -} - -makeSerializable( - AMDRequireDependency, - "webpack/lib/dependencies/AMDRequireDependency" -); +const { contextify } = __webpack_require__(82186); -AMDRequireDependency.Template = class AMDRequireDependencyTemplate extends ( - NullDependency.Template -) { +class RequestShortener { /** - * @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} + * @param {string} dir the directory + * @param {object=} associatedObjectForCache an object to which the cache will be attached */ - apply( - dependency, - source, - { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {AMDRequireDependency} */ (dependency); - const depBlock = /** @type {AsyncDependenciesBlock} */ ( - moduleGraph.getParentBlock(dep) + constructor(dir, associatedObjectForCache) { + this.contextify = contextify.bindContextCache( + dir, + associatedObjectForCache ); - const promise = runtimeTemplate.blockPromise({ - chunkGraph, - block: depBlock, - message: "AMD require", - runtimeRequirements - }); - - // has array range but no function range - if (dep.arrayRange && !dep.functionRange) { - const startBlock = `${promise}.then(function() {`; - const endBlock = `;})['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; - runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); - - source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); - - source.replace(dep.arrayRange[1], dep.outerRange[1] - 1, endBlock); - - return; - } - - // has function range but no array range - if (dep.functionRange && !dep.arrayRange) { - const startBlock = `${promise}.then((`; - const endBlock = `).bind(exports, __webpack_require__, exports, module))['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; - runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); - - source.replace(dep.outerRange[0], dep.functionRange[0] - 1, startBlock); - - source.replace(dep.functionRange[1], dep.outerRange[1] - 1, endBlock); + } - return; + /** + * @param {string | undefined | null} request the request to shorten + * @returns {string | undefined | null} the shortened request + */ + shorten(request) { + if (!request) { + return request; } + return this.contextify(request); + } +} - // has array range, function range, and errorCallbackRange - if (dep.arrayRange && dep.functionRange && dep.errorCallbackRange) { - const startBlock = `${promise}.then(function() { `; - const errorRangeBlock = `}${ - dep.functionBindThis ? ".bind(this)" : "" - })['catch'](`; - const endBlock = `${dep.errorCallbackBindThis ? ".bind(this)" : ""})`; - - source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); - - source.insert(dep.arrayRange[0], "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); +module.exports = RequestShortener; - source.replace(dep.arrayRange[1], dep.functionRange[0] - 1, "; ("); - source.insert( - dep.functionRange[1], - ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" - ); +/***/ }), - source.replace( - dep.functionRange[1], - dep.errorCallbackRange[0] - 1, - errorRangeBlock - ); +/***/ 88846: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - source.replace( - dep.errorCallbackRange[1], - dep.outerRange[1] - 1, - endBlock - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - return; - } - // has array range, function range, but no errorCallbackRange - if (dep.arrayRange && dep.functionRange) { - const startBlock = `${promise}.then(function() { `; - const endBlock = `}${ - dep.functionBindThis ? ".bind(this)" : "" - })['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; - runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); - source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); +const RuntimeGlobals = __webpack_require__(16475); +const ConstDependency = __webpack_require__(76911); +const { + toConstantDependency +} = __webpack_require__(93998); - source.insert(dep.arrayRange[0], "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); +/** @typedef {import("./Compiler")} Compiler */ - source.replace(dep.arrayRange[1], dep.functionRange[0] - 1, "; ("); +module.exports = class RequireJsStuffPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireJsStuffPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireJs === undefined || + !parserOptions.requireJs + ) { + return; + } - source.insert( - dep.functionRange[1], - ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" - ); + parser.hooks.call + .for("require.config") + .tap( + "RequireJsStuffPlugin", + toConstantDependency(parser, "undefined") + ); + parser.hooks.call + .for("requirejs.config") + .tap( + "RequireJsStuffPlugin", + toConstantDependency(parser, "undefined") + ); - source.replace(dep.functionRange[1], dep.outerRange[1] - 1, endBlock); - } + parser.hooks.expression + .for("require.version") + .tap( + "RequireJsStuffPlugin", + toConstantDependency(parser, JSON.stringify("0.0.0")) + ); + parser.hooks.expression + .for("requirejs.onError") + .tap( + "RequireJsStuffPlugin", + toConstantDependency( + parser, + RuntimeGlobals.uncaughtErrorHandler, + [RuntimeGlobals.uncaughtErrorHandler] + ) + ); + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireJsStuffPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireJsStuffPlugin", handler); + } + ); } }; -module.exports = AMDRequireDependency; - /***/ }), -/***/ 71806: +/***/ 30217: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -72211,648 +65202,544 @@ module.exports = AMDRequireDependency; -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyTemplateAsRequireId = __webpack_require__(36873); - -class AMDRequireItemDependency extends ModuleDependency { - constructor(request, range) { - super(request); - - this.range = range; - } - - get type() { - return "amd require"; - } - - get category() { - return "amd"; - } -} - -makeSerializable( - AMDRequireItemDependency, - "webpack/lib/dependencies/AMDRequireItemDependency" -); +const Factory = (__webpack_require__(30662).ResolverFactory); +const { HookMap, SyncHook, SyncWaterfallHook } = __webpack_require__(41242); +const { + cachedCleverMerge, + removeOperations, + resolveByProperty +} = __webpack_require__(60839); -AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; +/** @typedef {import("enhanced-resolve").ResolveOptions} ResolveOptions */ +/** @typedef {import("enhanced-resolve").Resolver} Resolver */ +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */ +/** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */ -module.exports = AMDRequireItemDependency; +/** @typedef {WebpackResolveOptions & {dependencyType?: string, resolveToContext?: boolean }} ResolveOptionsWithDependencyType */ +/** + * @typedef {Object} WithOptions + * @property {function(Partial): ResolverWithOptions} withOptions create a resolver with additional/different options + */ +/** @typedef {Resolver & WithOptions} ResolverWithOptions */ -/***/ }), +// need to be hoisted on module level for caching identity +const EMPTY_RESOLVE_OPTIONS = {}; -/***/ 45242: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/** + * @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType enhanced options + * @returns {ResolveOptions} merged options + */ +const convertToResolveOptions = resolveOptionsWithDepType => { + const { dependencyType, plugins, ...remaining } = resolveOptionsWithDepType; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + // check type compat + /** @type {Partial} */ + const partialOptions = { + ...remaining, + plugins: + plugins && + /** @type {ResolvePluginInstance[]} */ ( + plugins.filter(item => item !== "...") + ) + }; + if (!partialOptions.fileSystem) { + throw new Error( + "fileSystem is missing in resolveOptions, but it's required for enhanced-resolve" + ); + } + // These weird types validate that we checked all non-optional properties + const options = + /** @type {Partial & Pick} */ ( + partialOptions + ); + return removeOperations( + resolveByProperty(options, "byDependency", dependencyType) + ); +}; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); +/** + * @typedef {Object} ResolverCache + * @property {WeakMap} direct + * @property {Map} stringified + */ -class AMDDefineRuntimeModule extends RuntimeModule { +module.exports = class ResolverFactory { constructor() { - super("amd define"); + this.hooks = Object.freeze({ + /** @type {HookMap>} */ + resolveOptions: new HookMap( + () => new SyncWaterfallHook(["resolveOptions"]) + ), + /** @type {HookMap>} */ + resolver: new HookMap( + () => new SyncHook(["resolver", "resolveOptions", "userResolveOptions"]) + ) + }); + /** @type {Map} */ + this.cache = new Map(); } /** - * @returns {string} runtime code + * @param {string} type type of resolver + * @param {ResolveOptionsWithDependencyType=} resolveOptions options + * @returns {ResolverWithOptions} the resolver */ - generate() { - return Template.asString([ - `${RuntimeGlobals.amdDefine} = function () {`, - Template.indent("throw new Error('define cannot be used indirect');"), - "};" - ]); + get(type, resolveOptions = EMPTY_RESOLVE_OPTIONS) { + let typedCaches = this.cache.get(type); + if (!typedCaches) { + typedCaches = { + direct: new WeakMap(), + stringified: new Map() + }; + this.cache.set(type, typedCaches); + } + const cachedResolver = typedCaches.direct.get(resolveOptions); + if (cachedResolver) { + return cachedResolver; + } + const ident = JSON.stringify(resolveOptions); + const resolver = typedCaches.stringified.get(ident); + if (resolver) { + typedCaches.direct.set(resolveOptions, resolver); + return resolver; + } + const newResolver = this._create(type, resolveOptions); + typedCaches.direct.set(resolveOptions, newResolver); + typedCaches.stringified.set(ident, newResolver); + return newResolver; } -} -class AMDOptionsRuntimeModule extends RuntimeModule { /** - * @param {Record} options the AMD options + * @param {string} type type of resolver + * @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType options + * @returns {ResolverWithOptions} the resolver */ - constructor(options) { - super("amd options"); - this.options = options; - } + _create(type, resolveOptionsWithDepType) { + /** @type {ResolveOptionsWithDependencyType} */ + const originalResolveOptions = { ...resolveOptionsWithDepType }; - /** - * @returns {string} runtime code - */ - generate() { - return Template.asString([ - `${RuntimeGlobals.amdOptions} = ${JSON.stringify(this.options)};` - ]); + const resolveOptions = convertToResolveOptions( + this.hooks.resolveOptions.for(type).call(resolveOptionsWithDepType) + ); + const resolver = /** @type {ResolverWithOptions} */ ( + Factory.createResolver(resolveOptions) + ); + if (!resolver) { + throw new Error("No resolver created"); + } + /** @type {WeakMap, ResolverWithOptions>} */ + const childCache = new WeakMap(); + resolver.withOptions = options => { + const cacheEntry = childCache.get(options); + if (cacheEntry !== undefined) return cacheEntry; + const mergedOptions = cachedCleverMerge(originalResolveOptions, options); + const resolver = this.get(type, mergedOptions); + childCache.set(options, resolver); + return resolver; + }; + this.hooks.resolver + .for(type) + .call(resolver, resolveOptions, originalResolveOptions); + return resolver; } -} - -exports.AMDDefineRuntimeModule = AMDDefineRuntimeModule; -exports.AMDOptionsRuntimeModule = AMDOptionsRuntimeModule; +}; /***/ }), -/***/ 57403: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 16475: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent + Author Tobias Koppers @sokra */ -const DependencyTemplate = __webpack_require__(5160); -const InitFragment = __webpack_require__(55870); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +/** + * the internal require function + */ +exports.require = "__webpack_require__"; -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../util/Hash")} Hash */ +/** + * access to properties of the internal require function/object + */ +exports.requireScope = "__webpack_require__.*"; -class CachedConstDependency extends NullDependency { - constructor(expression, range, identifier) { - super(); +/** + * the internal exports object + */ +exports.exports = "__webpack_exports__"; - this.expression = expression; - this.range = range; - this.identifier = identifier; - this._hashUpdate = undefined; - } +/** + * top-level this need to be the exports object + */ +exports.thisAsExports = "top-level-this-exports"; - /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) - this._hashUpdate = "" + this.identifier + this.range + this.expression; - hash.update(this._hashUpdate); - } +/** + * runtime need to return the exports of the last entry module + */ +exports.returnExportsFromRuntime = "return-exports-from-runtime"; - serialize(context) { - const { write } = context; +/** + * the internal module object + */ +exports.module = "module"; - write(this.expression); - write(this.range); - write(this.identifier); +/** + * the internal module object + */ +exports.moduleId = "module.id"; - super.serialize(context); - } +/** + * the internal module object + */ +exports.moduleLoaded = "module.loaded"; - deserialize(context) { - const { read } = context; +/** + * the bundle public path + */ +exports.publicPath = "__webpack_require__.p"; - this.expression = read(); - this.range = read(); - this.identifier = read(); +/** + * the module id of the entry point + */ +exports.entryModuleId = "__webpack_require__.s"; - super.deserialize(context); - } -} +/** + * the module cache + */ +exports.moduleCache = "__webpack_require__.c"; -makeSerializable( - CachedConstDependency, - "webpack/lib/dependencies/CachedConstDependency" -); +/** + * the module functions + */ +exports.moduleFactories = "__webpack_require__.m"; -CachedConstDependency.Template = class CachedConstDependencyTemplate extends ( - DependencyTemplate -) { - /** - * @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, - { runtimeTemplate, dependencyTemplates, initFragments } - ) { - const dep = /** @type {CachedConstDependency} */ (dependency); +/** + * the module functions, with only write access + */ +exports.moduleFactoriesAddOnly = "__webpack_require__.m (add only)"; - initFragments.push( - new InitFragment( - `var ${dep.identifier} = ${dep.expression};\n`, - InitFragment.STAGE_CONSTANTS, - 0, - `const ${dep.identifier}` - ) - ); +/** + * the chunk ensure function + */ +exports.ensureChunk = "__webpack_require__.e"; - if (typeof dep.range === "number") { - source.insert(dep.range, dep.identifier); +/** + * an object with handlers to ensure a chunk + */ +exports.ensureChunkHandlers = "__webpack_require__.f"; - return; - } +/** + * a runtime requirement if ensureChunkHandlers should include loading of chunk needed for entries + */ +exports.ensureChunkIncludeEntries = "__webpack_require__.f (include entries)"; - source.replace(dep.range[0], dep.range[1] - 1, dep.identifier); - } -}; +/** + * the chunk prefetch function + */ +exports.prefetchChunk = "__webpack_require__.E"; -module.exports = CachedConstDependency; +/** + * an object with handlers to prefetch a chunk + */ +exports.prefetchChunkHandlers = "__webpack_require__.F"; +/** + * the chunk preload function + */ +exports.preloadChunk = "__webpack_require__.G"; -/***/ }), +/** + * an object with handlers to preload a chunk + */ +exports.preloadChunkHandlers = "__webpack_require__.H"; -/***/ 59643: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/** + * the exported property define getters function + */ +exports.definePropertyGetters = "__webpack_require__.d"; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * define compatibility on export + */ +exports.makeNamespaceObject = "__webpack_require__.r"; +/** + * create a fake namespace object + */ +exports.createFakeNamespaceObject = "__webpack_require__.t"; +/** + * compatibility get default export + */ +exports.compatGetDefaultExport = "__webpack_require__.n"; -const RuntimeGlobals = __webpack_require__(16475); +/** + * harmony module decorator + */ +exports.harmonyModuleDecorator = "__webpack_require__.hmd"; -exports.handleDependencyBase = (depBase, module, runtimeRequirements) => { - let base = undefined; - let type; - switch (depBase) { - case "exports": - runtimeRequirements.add(RuntimeGlobals.exports); - base = module.exportsArgument; - type = "expression"; - break; - case "module.exports": - runtimeRequirements.add(RuntimeGlobals.module); - base = `${module.moduleArgument}.exports`; - type = "expression"; - break; - case "this": - runtimeRequirements.add(RuntimeGlobals.thisAsExports); - base = "this"; - type = "expression"; - break; - case "Object.defineProperty(exports)": - runtimeRequirements.add(RuntimeGlobals.exports); - base = module.exportsArgument; - type = "Object.defineProperty"; - break; - case "Object.defineProperty(module.exports)": - runtimeRequirements.add(RuntimeGlobals.module); - base = `${module.moduleArgument}.exports`; - type = "Object.defineProperty"; - break; - case "Object.defineProperty(this)": - runtimeRequirements.add(RuntimeGlobals.thisAsExports); - base = "this"; - type = "Object.defineProperty"; - break; - default: - throw new Error(`Unsupported base ${depBase}`); - } +/** + * node.js module decorator + */ +exports.nodeModuleDecorator = "__webpack_require__.nmd"; - return [type, base]; -}; +/** + * the webpack hash + */ +exports.getFullHash = "__webpack_require__.h"; +/** + * an object containing all installed WebAssembly.Instance export objects keyed by module id + */ +exports.wasmInstances = "__webpack_require__.w"; -/***/ }), +/** + * instantiate a wasm instance from module exports object, id, hash and importsObject + */ +exports.instantiateWasm = "__webpack_require__.v"; -/***/ 62892: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * the uncaught error handler for the webpack runtime + */ +exports.uncaughtErrorHandler = "__webpack_require__.oe"; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * the script nonce + */ +exports.scriptNonce = "__webpack_require__.nc"; +/** + * function to load a script tag. + * Arguments: (url: string, done: (event) => void), key?: string | number, chunkId?: string | number) => void + * done function is called when loading has finished or timeout occurred. + * It will attach to existing script tags with data-webpack == uniqueName + ":" + key or src == url. + */ +exports.loadScript = "__webpack_require__.l"; +/** + * function to promote a string to a TrustedScript using webpack's Trusted + * Types policy + * Arguments: (script: string) => TrustedScript + */ +exports.createScript = "__webpack_require__.ts"; -const Dependency = __webpack_require__(54912); -const { UsageState } = __webpack_require__(63686); -const Template = __webpack_require__(1626); -const { equals } = __webpack_require__(84953); -const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const { handleDependencyBase } = __webpack_require__(59643); -const ModuleDependency = __webpack_require__(80321); -const processExportInfo = __webpack_require__(55207); +/** + * function to promote a string to a TrustedScriptURL using webpack's Trusted + * Types policy + * Arguments: (url: string) => TrustedScriptURL + */ +exports.createScriptUrl = "__webpack_require__.tu"; -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** + * function to return webpack's Trusted Types policy + * Arguments: () => TrustedTypePolicy + */ +exports.getTrustedTypesPolicy = "__webpack_require__.tt"; -const idsSymbol = Symbol("CommonJsExportRequireDependency.ids"); +/** + * the chunk name of the chunk with the runtime + */ +exports.chunkName = "__webpack_require__.cn"; -const EMPTY_OBJECT = {}; +/** + * the runtime id of the current runtime + */ +exports.runtimeId = "__webpack_require__.j"; -class CommonJsExportRequireDependency extends ModuleDependency { - constructor(range, valueRange, base, names, request, ids, resultUsed) { - super(request); - this.range = range; - this.valueRange = valueRange; - this.base = base; - this.names = names; - this.ids = ids; - this.resultUsed = resultUsed; - this.asiSafe = undefined; - } +/** + * the filename of the script part of the chunk + */ +exports.getChunkScriptFilename = "__webpack_require__.u"; - get type() { - return "cjs export require"; - } +/** + * the filename of the css part of the chunk + */ +exports.getChunkCssFilename = "__webpack_require__.k"; - /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module - */ - couldAffectReferencingModule() { - return Dependency.TRANSITIVE; - } +/** + * a flag when a module/chunk/tree has css modules + */ +exports.hasCssModules = "has css modules"; - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {string[]} the imported id - */ - getIds(moduleGraph) { - return moduleGraph.getMeta(this)[idsSymbol] || this.ids; - } +/** + * the filename of the script part of the hot update chunk + */ +exports.getChunkUpdateScriptFilename = "__webpack_require__.hu"; - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {string[]} ids the imported ids - * @returns {void} - */ - setIds(moduleGraph, ids) { - moduleGraph.getMeta(this)[idsSymbol] = ids; - } +/** + * the filename of the css part of the hot update chunk + */ +exports.getChunkUpdateCssFilename = "__webpack_require__.hk"; - /** - * 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) { - const ids = this.getIds(moduleGraph); - const getFullResult = () => { - if (ids.length === 0) { - return Dependency.EXPORTS_OBJECT_REFERENCED; - } else { - return [ - { - name: ids, - canMangle: false - } - ]; - } - }; - if (this.resultUsed) return getFullResult(); - let exportsInfo = moduleGraph.getExportsInfo( - moduleGraph.getParentModule(this) - ); - for (const name of this.names) { - const exportInfo = exportsInfo.getReadOnlyExportInfo(name); - const used = exportInfo.getUsed(runtime); - if (used === UsageState.Unused) return Dependency.NO_EXPORTS_REFERENCED; - if (used !== UsageState.OnlyPropertiesUsed) return getFullResult(); - exportsInfo = exportInfo.exportsInfo; - if (!exportsInfo) return getFullResult(); - } - if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { - return getFullResult(); - } - /** @type {string[][]} */ - const referencedExports = []; - for (const exportInfo of exportsInfo.orderedExports) { - processExportInfo( - runtime, - referencedExports, - ids.concat(exportInfo.name), - exportInfo, - false - ); - } - return referencedExports.map(name => ({ - name, - canMangle: false - })); - } +/** + * startup signal from runtime + * This will be called when the runtime chunk has been loaded. + */ +exports.startup = "__webpack_require__.x"; - /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names - */ - getExports(moduleGraph) { - const ids = this.getIds(moduleGraph); - if (this.names.length === 1) { - const name = this.names[0]; - const from = moduleGraph.getConnection(this); - if (!from) return; - return { - exports: [ - { - name, - from, - export: ids.length === 0 ? null : ids, - // we can't mangle names that are in an empty object - // because one could access the prototype property - // when export isn't set yet - canMangle: !(name in EMPTY_OBJECT) && false - } - ], - dependencies: [from.module] - }; - } else if (this.names.length > 0) { - const name = this.names[0]; - return { - exports: [ - { - name, - // we can't mangle names that are in an empty object - // because one could access the prototype property - // when export isn't set yet - canMangle: !(name in EMPTY_OBJECT) && false - } - ], - dependencies: undefined - }; - } else { - const from = moduleGraph.getConnection(this); - if (!from) return; - const reexportInfo = this.getStarReexports( - moduleGraph, - undefined, - from.module - ); - if (reexportInfo) { - return { - exports: Array.from(reexportInfo.exports, name => { - return { - name, - from, - export: ids.concat(name), - canMangle: !(name in EMPTY_OBJECT) && false - }; - }), - // TODO handle deep reexports - dependencies: [from.module] - }; - } else { - return { - exports: true, - from: ids.length === 0 ? from : undefined, - canMangle: false, - dependencies: [from.module] - }; - } - } - } +/** + * @deprecated + * creating a default startup function with the entry modules + */ +exports.startupNoDefault = "__webpack_require__.x (no default handler)"; - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {RuntimeSpec} runtime the runtime - * @param {Module} importedModule the imported module (optional) - * @returns {{exports?: Set, checked?: Set}} information - */ - getStarReexports( - moduleGraph, - runtime, - importedModule = moduleGraph.getModule(this) - ) { - let importedExportsInfo = moduleGraph.getExportsInfo(importedModule); - const ids = this.getIds(moduleGraph); - if (ids.length > 0) - importedExportsInfo = importedExportsInfo.getNestedExportsInfo(ids); - let exportsInfo = moduleGraph.getExportsInfo( - moduleGraph.getParentModule(this) - ); - if (this.names.length > 0) - exportsInfo = exportsInfo.getNestedExportsInfo(this.names); +/** + * startup signal from runtime but only used to add logic after the startup + */ +exports.startupOnlyAfter = "__webpack_require__.x (only after)"; - const noExtraExports = - importedExportsInfo && - importedExportsInfo.otherExportsInfo.provided === false; - const noExtraImports = - exportsInfo && - exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused; +/** + * startup signal from runtime but only used to add sync logic before the startup + */ +exports.startupOnlyBefore = "__webpack_require__.x (only before)"; - if (!noExtraExports && !noExtraImports) { - return; - } +/** + * global callback functions for installing chunks + */ +exports.chunkCallback = "webpackChunk"; - const isNamespaceImport = - importedModule.getExportsType(moduleGraph, false) === "namespace"; +/** + * method to startup an entrypoint with needed chunks. + * Signature: (moduleId: Id, chunkIds: Id[]) => any. + * Returns the exports of the module or a Promise + */ +exports.startupEntrypoint = "__webpack_require__.X"; - /** @type {Set} */ - const exports = new Set(); - /** @type {Set} */ - const checked = new Set(); +/** + * register deferred code, which will run when certain + * chunks are loaded. + * Signature: (chunkIds: Id[], fn: () => any, priority: int >= 0 = 0) => any + * Returned value will be returned directly when all chunks are already loaded + * When (priority & 1) it will wait for all other handlers with lower priority to + * be executed before itself is executed + */ +exports.onChunksLoaded = "__webpack_require__.O"; - if (noExtraImports) { - for (const exportInfo of exportsInfo.orderedExports) { - const name = exportInfo.name; - if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; - if (name === "__esModule" && isNamespaceImport) { - exports.add(name); - } else if (importedExportsInfo) { - const importedExportInfo = - importedExportsInfo.getReadOnlyExportInfo(name); - if (importedExportInfo.provided === false) continue; - exports.add(name); - if (importedExportInfo.provided === true) continue; - checked.add(name); - } else { - exports.add(name); - checked.add(name); - } - } - } else if (noExtraExports) { - for (const importedExportInfo of importedExportsInfo.orderedExports) { - const name = importedExportInfo.name; - if (importedExportInfo.provided === false) continue; - if (exportsInfo) { - const exportInfo = exportsInfo.getReadOnlyExportInfo(name); - if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; - } - exports.add(name); - if (importedExportInfo.provided === true) continue; - checked.add(name); - } - if (isNamespaceImport) { - exports.add("__esModule"); - checked.delete("__esModule"); - } - } +/** + * method to install a chunk that was loaded somehow + * Signature: ({ id, ids, modules, runtime }) => void + */ +exports.externalInstallChunk = "__webpack_require__.C"; - return { exports, checked }; - } +/** + * interceptor for module executions + */ +exports.interceptModuleExecution = "__webpack_require__.i"; - serialize(context) { - const { write } = context; - write(this.asiSafe); - write(this.range); - write(this.valueRange); - write(this.base); - write(this.names); - write(this.ids); - write(this.resultUsed); - super.serialize(context); - } +/** + * the global object + */ +exports.global = "__webpack_require__.g"; - deserialize(context) { - const { read } = context; - this.asiSafe = read(); - this.range = read(); - this.valueRange = read(); - this.base = read(); - this.names = read(); - this.ids = read(); - this.resultUsed = read(); - super.deserialize(context); - } -} +/** + * an object with all share scopes + */ +exports.shareScopeMap = "__webpack_require__.S"; -makeSerializable( - CommonJsExportRequireDependency, - "webpack/lib/dependencies/CommonJsExportRequireDependency" -); +/** + * The sharing init sequence function (only runs once per share scope). + * Has one argument, the name of the share scope. + * Creates a share scope if not existing + */ +exports.initializeSharing = "__webpack_require__.I"; -CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependencyTemplate extends ( - ModuleDependency.Template -) { - /** - * @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, - { - module, - runtimeTemplate, - chunkGraph, - moduleGraph, - runtimeRequirements, - runtime - } - ) { - const dep = /** @type {CommonJsExportRequireDependency} */ (dependency); - const used = moduleGraph - .getExportsInfo(module) - .getUsedName(dep.names, runtime); +/** + * The current scope when getting a module from a remote + */ +exports.currentRemoteGetScope = "__webpack_require__.R"; - const [type, base] = handleDependencyBase( - dep.base, - module, - runtimeRequirements - ); +/** + * the filename of the HMR manifest + */ +exports.getUpdateManifestFilename = "__webpack_require__.hmrF"; - const importedModule = moduleGraph.getModule(dep); - let requireExpr = runtimeTemplate.moduleExports({ - module: importedModule, - chunkGraph, - request: dep.request, - weak: dep.weak, - runtimeRequirements - }); - if (importedModule) { - const ids = dep.getIds(moduleGraph); - const usedImported = moduleGraph - .getExportsInfo(importedModule) - .getUsedName(ids, runtime); - if (usedImported) { - const comment = equals(usedImported, ids) - ? "" - : Template.toNormalComment(propertyAccess(ids)) + " "; - requireExpr += `${comment}${propertyAccess(usedImported)}`; - } - } +/** + * function downloading the update manifest + */ +exports.hmrDownloadManifest = "__webpack_require__.hmrM"; - switch (type) { - case "expression": - source.replace( - dep.range[0], - dep.range[1] - 1, - used - ? `${base}${propertyAccess(used)} = ${requireExpr}` - : `/* unused reexport */ ${requireExpr}` - ); - return; - case "Object.defineProperty": - throw new Error("TODO"); - default: - throw new Error("Unexpected type"); - } - } -}; +/** + * array with handler functions to download chunk updates + */ +exports.hmrDownloadUpdateHandlers = "__webpack_require__.hmrC"; -module.exports = CommonJsExportRequireDependency; +/** + * object with all hmr module data for all modules + */ +exports.hmrModuleData = "__webpack_require__.hmrD"; + +/** + * array with handler functions when a module should be invalidated + */ +exports.hmrInvalidateModuleHandlers = "__webpack_require__.hmrI"; + +/** + * the prefix for storing state of runtime modules when hmr is enabled + */ +exports.hmrRuntimeStatePrefix = "__webpack_require__.hmrS"; + +/** + * the AMD define function + */ +exports.amdDefine = "__webpack_require__.amdD"; + +/** + * the AMD options + */ +exports.amdOptions = "__webpack_require__.amdO"; + +/** + * the System polyfill object + */ +exports.system = "__webpack_require__.System"; + +/** + * the shorthand for Object.prototype.hasOwnProperty + * using of it decreases the compiled bundle size + */ +exports.hasOwnProperty = "__webpack_require__.o"; + +/** + * the System.register context object + */ +exports.systemContext = "__webpack_require__.y"; + +/** + * the baseURI of current document + */ +exports.baseURI = "__webpack_require__.b"; + +/** + * a RelativeURL class when relative URLs are used + */ +exports.relativeUrl = "__webpack_require__.U"; + +/** + * Creates an async module. The body function must be a async function. + * "module.exports" will be decorated with an AsyncModulePromise. + * The body function will be called. + * To handle async dependencies correctly do this: "([a, b, c] = await handleDependencies([a, b, c]));". + * If "hasAwaitAfterDependencies" is truthy, "handleDependencies()" must be called at the end of the body function. + * Signature: function( + * module: Module, + * body: (handleDependencies: (deps: AsyncModulePromise[]) => Promise & () => void, + * hasAwaitAfterDependencies?: boolean + * ) => void + */ +exports.asyncModule = "__webpack_require__.a"; /***/ }), -/***/ 45598: +/***/ 16963: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -72863,164 +65750,217 @@ module.exports = CommonJsExportRequireDependency; -const InitFragment = __webpack_require__(55870); -const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const { handleDependencyBase } = __webpack_require__(59643); -const NullDependency = __webpack_require__(31830); +const { RawSource } = __webpack_require__(51255); +const OriginalSource = (__webpack_require__(51255).OriginalSource); +const Module = __webpack_require__(73208); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @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("./Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -const EMPTY_OBJECT = {}; +const TYPES = new Set(["runtime"]); -class CommonJsExportsDependency extends NullDependency { - constructor(range, valueRange, base, names) { - super(); - this.range = range; - this.valueRange = valueRange; - this.base = base; - this.names = names; +class RuntimeModule extends Module { + /** + * @param {string} name a readable name + * @param {number=} stage an optional stage + */ + constructor(name, stage = 0) { + super("runtime"); + this.name = name; + this.stage = stage; + this.buildMeta = {}; + this.buildInfo = {}; + /** @type {Compilation} */ + this.compilation = undefined; + /** @type {Chunk} */ + this.chunk = undefined; + /** @type {ChunkGraph} */ + this.chunkGraph = undefined; + this.fullHash = false; + this.dependentHash = false; + /** @type {string} */ + this._cachedGeneratedCode = undefined; } - get type() { - return "cjs exports"; + /** + * @param {Compilation} compilation the compilation + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} + */ + attach(compilation, chunk, chunkGraph = compilation.chunkGraph) { + this.compilation = compilation; + this.chunk = chunk; + this.chunkGraph = chunkGraph; } /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names + * @returns {string} a unique identifier of the module */ - getExports(moduleGraph) { - const name = this.names[0]; - return { - exports: [ - { - name, - // we can't mangle names that are in an empty object - // because one could access the prototype property - // when export isn't set yet - canMangle: !(name in EMPTY_OBJECT) - } - ], - dependencies: undefined - }; + identifier() { + return `webpack/runtime/${this.name}`; } - serialize(context) { - const { write } = context; - write(this.range); - write(this.valueRange); - write(this.base); - write(this.names); - super.serialize(context); + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `webpack/runtime/${this.name}`; } - deserialize(context) { - const { read } = context; - this.range = read(); - this.valueRange = read(); - this.base = read(); - this.names = read(); - super.deserialize(context); + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, false); } -} -makeSerializable( - CommonJsExportsDependency, - "webpack/lib/dependencies/CommonJsExportsDependency" -); + /** + * @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) { + // do nothing + // should not be called as runtime modules are added later to the compilation + callback(); + } -CommonJsExportsDependency.Template = class CommonJsExportsDependencyTemplate extends ( - NullDependency.Template -) { /** - * @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 + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context * @returns {void} */ - apply( - dependency, - source, - { module, moduleGraph, initFragments, runtimeRequirements, runtime } - ) { - const dep = /** @type {CommonJsExportsDependency} */ (dependency); - const used = moduleGraph - .getExportsInfo(module) - .getUsedName(dep.names, runtime); + updateHash(hash, context) { + hash.update(this.name); + hash.update(`${this.stage}`); + try { + if (this.fullHash || this.dependentHash) { + // Do not use getGeneratedCode here, because i. e. compilation hash might be not + // ready at this point. We will cache it later instead. + hash.update(this.generate()); + } else { + hash.update(this.getGeneratedCode()); + } + } catch (err) { + hash.update(err.message); + } + super.updateHash(hash, context); + } - const [type, base] = handleDependencyBase( - dep.base, - module, - runtimeRequirements - ); + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; + } - switch (type) { - case "expression": - if (!used) { - initFragments.push( - new InitFragment( - "var __webpack_unused_export__;\n", - InitFragment.STAGE_CONSTANTS, - 0, - "__webpack_unused_export__" - ) - ); - source.replace( - dep.range[0], - dep.range[1] - 1, - "__webpack_unused_export__" - ); - return; - } - source.replace( - dep.range[0], - dep.range[1] - 1, - `${base}${propertyAccess(used)}` - ); - return; - case "Object.defineProperty": - if (!used) { - initFragments.push( - new InitFragment( - "var __webpack_unused_export__;\n", - InitFragment.STAGE_CONSTANTS, - 0, - "__webpack_unused_export__" - ) - ); - source.replace( - dep.range[0], - dep.valueRange[0] - 1, - "__webpack_unused_export__ = (" - ); - source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); - return; - } - source.replace( - dep.range[0], - dep.valueRange[0] - 1, - `Object.defineProperty(${base}${propertyAccess( - used.slice(0, -1) - )}, ${JSON.stringify(used[used.length - 1])}, (` - ); - source.replace(dep.valueRange[1], dep.range[1] - 1, "))"); - return; + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration(context) { + const sources = new Map(); + const generatedCode = this.getGeneratedCode(); + if (generatedCode) { + sources.set( + "runtime", + this.useSourceMap || this.useSimpleSourceMap + ? new OriginalSource(generatedCode, this.identifier()) + : new RawSource(generatedCode) + ); } + return { + sources, + runtimeRequirements: null + }; } -}; -module.exports = CommonJsExportsDependency; + /** + * @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) { + try { + const source = this.getGeneratedCode(); + return source ? source.length : 0; + } catch (e) { + return 0; + } + } + + /* istanbul ignore next */ + /** + * @abstract + * @returns {string} runtime code + */ + generate() { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); + } + + /** + * @returns {string} runtime code + */ + getGeneratedCode() { + if (this._cachedGeneratedCode) { + return this._cachedGeneratedCode; + } + return (this._cachedGeneratedCode = this.generate()); + } + + /** + * @returns {boolean} true, if the runtime module should get it's own scope + */ + shouldIsolate() { + return true; + } +} + +/** + * Runtime modules without any dependencies to other runtime modules + */ +RuntimeModule.STAGE_NORMAL = 0; + +/** + * Runtime modules with simple dependencies on other runtime modules + */ +RuntimeModule.STAGE_BASIC = 5; + +/** + * Runtime modules which attach to handlers of other runtime modules + */ +RuntimeModule.STAGE_ATTACH = 10; + +/** + * Runtime modules which trigger actions on bootstrap + */ +RuntimeModule.STAGE_TRIGGER = 20; + +module.exports = RuntimeModule; /***/ }), -/***/ 97107: +/***/ 2307: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -73032,339 +65972,447 @@ module.exports = CommonJsExportsDependency; const RuntimeGlobals = __webpack_require__(16475); -const formatLocation = __webpack_require__(16734); -const { evaluateToString } = __webpack_require__(93998); -const propertyAccess = __webpack_require__(54190); -const CommonJsExportRequireDependency = __webpack_require__(62892); -const CommonJsExportsDependency = __webpack_require__(45598); -const CommonJsSelfReferenceDependency = __webpack_require__(52225); -const DynamicExports = __webpack_require__(32006); -const HarmonyExports = __webpack_require__(39211); -const ModuleDecoratorDependency = __webpack_require__(88488); - -/** @typedef {import("estree").Expression} ExpressionNode */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +const { getChunkFilenameTemplate } = __webpack_require__(47283); +const RuntimeRequirementsDependency = __webpack_require__(24187); +const JavascriptModulesPlugin = __webpack_require__(89464); +const AsyncModuleRuntimeModule = __webpack_require__(63672); +const AutoPublicPathRuntimeModule = __webpack_require__(66532); +const CompatGetDefaultExportRuntimeModule = __webpack_require__(44793); +const CompatRuntimeModule = __webpack_require__(88234); +const CreateFakeNamespaceObjectRuntimeModule = __webpack_require__(94669); +const CreateScriptRuntimeModule = __webpack_require__(2759); +const CreateScriptUrlRuntimeModule = __webpack_require__(21213); +const DefinePropertyGettersRuntimeModule = __webpack_require__(75481); +const EnsureChunkRuntimeModule = __webpack_require__(71519); +const GetChunkFilenameRuntimeModule = __webpack_require__(34277); +const GetMainFilenameRuntimeModule = __webpack_require__(10029); +const GetTrustedTypesPolicyRuntimeModule = __webpack_require__(38713); +const GlobalRuntimeModule = __webpack_require__(23255); +const HasOwnPropertyRuntimeModule = __webpack_require__(8011); +const LoadScriptRuntimeModule = __webpack_require__(19942); +const MakeNamespaceObjectRuntimeModule = __webpack_require__(65714); +const OnChunksLoadedRuntimeModule = __webpack_require__(44518); +const PublicPathRuntimeModule = __webpack_require__(56030); +const RelativeUrlRuntimeModule = __webpack_require__(4537); +const RuntimeIdRuntimeModule = __webpack_require__(97115); +const SystemContextRuntimeModule = __webpack_require__(80655); +const ShareRuntimeModule = __webpack_require__(96066); +const StringXor = __webpack_require__(40293); -const getValueOfPropertyDescription = expr => { - if (expr.type !== "ObjectExpression") return; - for (const property of expr.properties) { - if (property.computed) continue; - const key = property.key; - if (key.type !== "Identifier" || key.name !== "value") continue; - return property.value; - } -}; +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ -const isTruthyLiteral = expr => { - switch (expr.type) { - case "Literal": - return !!expr.value; - case "UnaryExpression": - if (expr.operator === "!") return isFalsyLiteral(expr.argument); - } - return false; -}; +const GLOBALS_ON_REQUIRE = [ + RuntimeGlobals.chunkName, + RuntimeGlobals.runtimeId, + RuntimeGlobals.compatGetDefaultExport, + RuntimeGlobals.createFakeNamespaceObject, + RuntimeGlobals.createScript, + RuntimeGlobals.createScriptUrl, + RuntimeGlobals.getTrustedTypesPolicy, + RuntimeGlobals.definePropertyGetters, + RuntimeGlobals.ensureChunk, + RuntimeGlobals.entryModuleId, + RuntimeGlobals.getFullHash, + RuntimeGlobals.global, + RuntimeGlobals.makeNamespaceObject, + RuntimeGlobals.moduleCache, + RuntimeGlobals.moduleFactories, + RuntimeGlobals.moduleFactoriesAddOnly, + RuntimeGlobals.interceptModuleExecution, + RuntimeGlobals.publicPath, + RuntimeGlobals.baseURI, + RuntimeGlobals.relativeUrl, + RuntimeGlobals.scriptNonce, + RuntimeGlobals.uncaughtErrorHandler, + RuntimeGlobals.asyncModule, + RuntimeGlobals.wasmInstances, + RuntimeGlobals.instantiateWasm, + RuntimeGlobals.shareScopeMap, + RuntimeGlobals.initializeSharing, + RuntimeGlobals.loadScript, + RuntimeGlobals.systemContext, + RuntimeGlobals.onChunksLoaded +]; -const isFalsyLiteral = expr => { - switch (expr.type) { - case "Literal": - return !expr.value; - case "UnaryExpression": - if (expr.operator === "!") return isTruthyLiteral(expr.argument); - } - return false; +const MODULE_DEPENDENCIES = { + [RuntimeGlobals.moduleLoaded]: [RuntimeGlobals.module], + [RuntimeGlobals.moduleId]: [RuntimeGlobals.module] }; -/** - * @param {JavascriptParser} parser the parser - * @param {ExpressionNode} expr expression - * @returns {{ argument: BasicEvaluatedExpression, ids: string[] } | undefined} parsed call - */ -const parseRequireCall = (parser, expr) => { - const ids = []; - while (expr.type === "MemberExpression") { - if (expr.object.type === "Super") return; - if (!expr.property) return; - const prop = expr.property; - if (expr.computed) { - if (prop.type !== "Literal") return; - ids.push(`${prop.value}`); - } else { - if (prop.type !== "Identifier") return; - ids.push(prop.name); - } - expr = expr.object; - } - if (expr.type !== "CallExpression" || expr.arguments.length !== 1) return; - const callee = expr.callee; - if ( - callee.type !== "Identifier" || - parser.getVariableInfo(callee.name) !== "require" - ) { - return; - } - const arg = expr.arguments[0]; - if (arg.type === "SpreadElement") return; - const argValue = parser.evaluateExpression(arg); - return { argument: argValue, ids: ids.reverse() }; +const TREE_DEPENDENCIES = { + [RuntimeGlobals.definePropertyGetters]: [RuntimeGlobals.hasOwnProperty], + [RuntimeGlobals.compatGetDefaultExport]: [ + RuntimeGlobals.definePropertyGetters + ], + [RuntimeGlobals.createFakeNamespaceObject]: [ + RuntimeGlobals.definePropertyGetters, + RuntimeGlobals.makeNamespaceObject, + RuntimeGlobals.require + ], + [RuntimeGlobals.initializeSharing]: [RuntimeGlobals.shareScopeMap], + [RuntimeGlobals.shareScopeMap]: [RuntimeGlobals.hasOwnProperty] }; -class CommonJsExportsParserPlugin { - constructor(moduleGraph) { - this.moduleGraph = moduleGraph; - } - +class RuntimePlugin { /** - * @param {JavascriptParser} parser the parser + * @param {Compiler} compiler the Compiler + * @returns {void} */ - apply(parser) { - const enableStructuredExports = () => { - DynamicExports.enable(parser.state); - }; - const checkNamespace = (topLevel, members, valueExpr) => { - if (!DynamicExports.isEnabled(parser.state)) return; - if (members.length > 0 && members[0] === "__esModule") { - if (valueExpr && isTruthyLiteral(valueExpr) && topLevel) { - DynamicExports.setFlagged(parser.state); - } else { - DynamicExports.setDynamic(parser.state); - } - } - }; - const bailout = reason => { - DynamicExports.bailout(parser.state); - if (reason) bailoutHint(reason); - }; - const bailoutHint = reason => { - this.moduleGraph - .getOptimizationBailout(parser.state.module) - .push(`CommonJS bailout: ${reason}`); - }; - - // metadata // - parser.hooks.evaluateTypeof - .for("module") - .tap("CommonJsExportsParserPlugin", evaluateToString("object")); - parser.hooks.evaluateTypeof - .for("exports") - .tap("CommonJsPlugin", evaluateToString("object")); - - // exporting // - const handleAssignExport = (expr, base, members) => { - if (HarmonyExports.isEnabled(parser.state)) return; - // Handle reexporting - const requireCall = parseRequireCall(parser, expr.right); - if ( - requireCall && - requireCall.argument.isString() && - (members.length === 0 || members[0] !== "__esModule") - ) { - enableStructuredExports(); - // It's possible to reexport __esModule, so we must convert to a dynamic module - if (members.length === 0) DynamicExports.setDynamic(parser.state); - const dep = new CommonJsExportRequireDependency( - expr.range, - null, - base, - members, - requireCall.argument.string, - requireCall.ids, - !parser.isStatementLevelExpression(expr) - ); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.module.addDependency(dep); - return true; - } - if (members.length === 0) return; - enableStructuredExports(); - const remainingMembers = members; - checkNamespace( - parser.statementPath.length === 1 && - parser.isStatementLevelExpression(expr), - remainingMembers, - expr.right - ); - const dep = new CommonJsExportsDependency( - expr.left.range, - null, - base, - remainingMembers + apply(compiler) { + compiler.hooks.compilation.tap("RuntimePlugin", compilation => { + compilation.dependencyTemplates.set( + RuntimeRequirementsDependency, + new RuntimeRequirementsDependency.Template() ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - parser.walkExpression(expr.right); - return true; - }; - parser.hooks.assignMemberChain - .for("exports") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - return handleAssignExport(expr, "exports", members); - }); - parser.hooks.assignMemberChain - .for("this") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - if (!parser.scope.topLevelScope) return; - return handleAssignExport(expr, "this", members); - }); - parser.hooks.assignMemberChain - .for("module") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - if (members[0] !== "exports") return; - return handleAssignExport(expr, "module.exports", members.slice(1)); - }); - parser.hooks.call - .for("Object.defineProperty") - .tap("CommonJsExportsParserPlugin", expression => { - const expr = /** @type {import("estree").CallExpression} */ ( - expression - ); - if (!parser.isStatementLevelExpression(expr)) return; - if (expr.arguments.length !== 3) return; - if (expr.arguments[0].type === "SpreadElement") return; - if (expr.arguments[1].type === "SpreadElement") return; - if (expr.arguments[2].type === "SpreadElement") return; - const exportsArg = parser.evaluateExpression(expr.arguments[0]); - if (!exportsArg || !exportsArg.isIdentifier()) return; - if ( - exportsArg.identifier !== "exports" && - exportsArg.identifier !== "module.exports" && - (exportsArg.identifier !== "this" || !parser.scope.topLevelScope) - ) { - return; - } - const propertyArg = parser.evaluateExpression(expr.arguments[1]); - if (!propertyArg) return; - const property = propertyArg.asString(); - if (typeof property !== "string") return; - enableStructuredExports(); - const descArg = expr.arguments[2]; - checkNamespace( - parser.statementPath.length === 1, - [property], - getValueOfPropertyDescription(descArg) - ); - const dep = new CommonJsExportsDependency( - expr.range, - expr.arguments[2].range, - `Object.defineProperty(${exportsArg.identifier})`, - [property] - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - - parser.walkExpression(expr.arguments[2]); - return true; - }); - - // Self reference // - const handleAccessExport = (expr, base, members, call = undefined) => { - if (HarmonyExports.isEnabled(parser.state)) return; - if (members.length === 0) { - bailout(`${base} is used directly at ${formatLocation(expr.loc)}`); + for (const req of GLOBALS_ON_REQUIRE) { + compilation.hooks.runtimeRequirementInModule + .for(req) + .tap("RuntimePlugin", (module, set) => { + set.add(RuntimeGlobals.requireScope); + }); + compilation.hooks.runtimeRequirementInTree + .for(req) + .tap("RuntimePlugin", (module, set) => { + set.add(RuntimeGlobals.requireScope); + }); } - if (call && members.length === 1) { - bailoutHint( - `${base}${propertyAccess( - members - )}(...) prevents optimization as ${base} is passed as call context at ${formatLocation( - expr.loc - )}` - ); + for (const req of Object.keys(TREE_DEPENDENCIES)) { + const deps = TREE_DEPENDENCIES[req]; + compilation.hooks.runtimeRequirementInTree + .for(req) + .tap("RuntimePlugin", (chunk, set) => { + for (const dep of deps) set.add(dep); + }); } - const dep = new CommonJsSelfReferenceDependency( - expr.range, - base, - members, - !!call - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - if (call) { - parser.walkExpressions(call.arguments); + for (const req of Object.keys(MODULE_DEPENDENCIES)) { + const deps = MODULE_DEPENDENCIES[req]; + compilation.hooks.runtimeRequirementInModule + .for(req) + .tap("RuntimePlugin", (chunk, set) => { + for (const dep of deps) set.add(dep); + }); } - return true; - }; - parser.hooks.callMemberChain - .for("exports") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - return handleAccessExport(expr.callee, "exports", members, expr); - }); - parser.hooks.expressionMemberChain - .for("exports") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - return handleAccessExport(expr, "exports", members); - }); - parser.hooks.expression - .for("exports") - .tap("CommonJsExportsParserPlugin", expr => { - return handleAccessExport(expr, "exports", []); - }); - parser.hooks.callMemberChain - .for("module") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - if (members[0] !== "exports") return; - return handleAccessExport( - expr.callee, - "module.exports", - members.slice(1), - expr - ); - }); - parser.hooks.expressionMemberChain - .for("module") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - if (members[0] !== "exports") return; - return handleAccessExport(expr, "module.exports", members.slice(1)); - }); - parser.hooks.expression - .for("module.exports") - .tap("CommonJsExportsParserPlugin", expr => { - return handleAccessExport(expr, "module.exports", []); - }); - parser.hooks.callMemberChain - .for("this") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - if (!parser.scope.topLevelScope) return; - return handleAccessExport(expr.callee, "this", members, expr); - }); - parser.hooks.expressionMemberChain - .for("this") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - if (!parser.scope.topLevelScope) return; - return handleAccessExport(expr, "this", members); - }); - parser.hooks.expression - .for("this") - .tap("CommonJsExportsParserPlugin", expr => { - if (!parser.scope.topLevelScope) return; - return handleAccessExport(expr, "this", []); - }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.definePropertyGetters) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule( + chunk, + new DefinePropertyGettersRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.makeNamespaceObject) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule( + chunk, + new MakeNamespaceObjectRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.createFakeNamespaceObject) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule( + chunk, + new CreateFakeNamespaceObjectRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hasOwnProperty) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule( + chunk, + new HasOwnPropertyRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.compatGetDefaultExport) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule( + chunk, + new CompatGetDefaultExportRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.runtimeId) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule(chunk, new RuntimeIdRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.publicPath) + .tap("RuntimePlugin", (chunk, set) => { + const { outputOptions } = compilation; + const { publicPath: globalPublicPath, scriptType } = outputOptions; + const entryOptions = chunk.getEntryOptions(); + const publicPath = + entryOptions && entryOptions.publicPath !== undefined + ? entryOptions.publicPath + : globalPublicPath; - // Bailouts // - parser.hooks.expression.for("module").tap("CommonJsPlugin", expr => { - bailout(); - const isHarmony = HarmonyExports.isEnabled(parser.state); - const dep = new ModuleDecoratorDependency( - isHarmony - ? RuntimeGlobals.harmonyModuleDecorator - : RuntimeGlobals.nodeModuleDecorator, - !isHarmony + if (publicPath === "auto") { + const module = new AutoPublicPathRuntimeModule(); + if (scriptType !== "module") set.add(RuntimeGlobals.global); + compilation.addRuntimeModule(chunk, module); + } else { + const module = new PublicPathRuntimeModule(publicPath); + + if ( + typeof publicPath !== "string" || + /\[(full)?hash\]/.test(publicPath) + ) { + module.fullHash = true; + } + + compilation.addRuntimeModule(chunk, module); + } + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.global) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule(chunk, new GlobalRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.asyncModule) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule(chunk, new AsyncModuleRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.systemContext) + .tap("RuntimePlugin", chunk => { + const { outputOptions } = compilation; + const { library: globalLibrary } = outputOptions; + const entryOptions = chunk.getEntryOptions(); + const libraryType = + entryOptions && entryOptions.library !== undefined + ? entryOptions.library.type + : globalLibrary.type; + + if (libraryType === "system") { + compilation.addRuntimeModule( + chunk, + new SystemContextRuntimeModule() + ); + } + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getChunkScriptFilename) + .tap("RuntimePlugin", (chunk, set) => { + if ( + typeof compilation.outputOptions.chunkFilename === "string" && + /\[(full)?hash(:\d+)?\]/.test( + compilation.outputOptions.chunkFilename + ) + ) { + set.add(RuntimeGlobals.getFullHash); + } + compilation.addRuntimeModule( + chunk, + new GetChunkFilenameRuntimeModule( + "javascript", + "javascript", + RuntimeGlobals.getChunkScriptFilename, + chunk => + chunk.filenameTemplate || + (chunk.canBeInitial() + ? compilation.outputOptions.filename + : compilation.outputOptions.chunkFilename), + false + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getChunkCssFilename) + .tap("RuntimePlugin", (chunk, set) => { + if ( + typeof compilation.outputOptions.cssChunkFilename === "string" && + /\[(full)?hash(:\d+)?\]/.test( + compilation.outputOptions.cssChunkFilename + ) + ) { + set.add(RuntimeGlobals.getFullHash); + } + compilation.addRuntimeModule( + chunk, + new GetChunkFilenameRuntimeModule( + "css", + "css", + RuntimeGlobals.getChunkCssFilename, + chunk => + getChunkFilenameTemplate(chunk, compilation.outputOptions), + set.has(RuntimeGlobals.hmrDownloadUpdateHandlers) + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getChunkUpdateScriptFilename) + .tap("RuntimePlugin", (chunk, set) => { + if ( + /\[(full)?hash(:\d+)?\]/.test( + compilation.outputOptions.hotUpdateChunkFilename + ) + ) + set.add(RuntimeGlobals.getFullHash); + compilation.addRuntimeModule( + chunk, + new GetChunkFilenameRuntimeModule( + "javascript", + "javascript update", + RuntimeGlobals.getChunkUpdateScriptFilename, + c => compilation.outputOptions.hotUpdateChunkFilename, + true + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getUpdateManifestFilename) + .tap("RuntimePlugin", (chunk, set) => { + if ( + /\[(full)?hash(:\d+)?\]/.test( + compilation.outputOptions.hotUpdateMainFilename + ) + ) { + set.add(RuntimeGlobals.getFullHash); + } + compilation.addRuntimeModule( + chunk, + new GetMainFilenameRuntimeModule( + "update manifest", + RuntimeGlobals.getUpdateManifestFilename, + compilation.outputOptions.hotUpdateMainFilename + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunk) + .tap("RuntimePlugin", (chunk, set) => { + const hasAsyncChunks = chunk.hasAsyncChunks(); + if (hasAsyncChunks) { + set.add(RuntimeGlobals.ensureChunkHandlers); + } + compilation.addRuntimeModule( + chunk, + new EnsureChunkRuntimeModule(set) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkIncludeEntries) + .tap("RuntimePlugin", (chunk, set) => { + set.add(RuntimeGlobals.ensureChunkHandlers); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.shareScopeMap) + .tap("RuntimePlugin", (chunk, set) => { + compilation.addRuntimeModule(chunk, new ShareRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.loadScript) + .tap("RuntimePlugin", (chunk, set) => { + const withCreateScriptUrl = !!compilation.outputOptions.trustedTypes; + if (withCreateScriptUrl) { + set.add(RuntimeGlobals.createScriptUrl); + } + compilation.addRuntimeModule( + chunk, + new LoadScriptRuntimeModule(withCreateScriptUrl) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.createScript) + .tap("RuntimePlugin", (chunk, set) => { + if (compilation.outputOptions.trustedTypes) { + set.add(RuntimeGlobals.getTrustedTypesPolicy); + } + compilation.addRuntimeModule(chunk, new CreateScriptRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.createScriptUrl) + .tap("RuntimePlugin", (chunk, set) => { + if (compilation.outputOptions.trustedTypes) { + set.add(RuntimeGlobals.getTrustedTypesPolicy); + } + compilation.addRuntimeModule( + chunk, + new CreateScriptUrlRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getTrustedTypesPolicy) + .tap("RuntimePlugin", (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new GetTrustedTypesPolicyRuntimeModule(set) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.relativeUrl) + .tap("RuntimePlugin", (chunk, set) => { + compilation.addRuntimeModule(chunk, new RelativeUrlRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap("RuntimePlugin", (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new OnChunksLoadedRuntimeModule() + ); + return true; + }); + // TODO webpack 6: remove CompatRuntimeModule + compilation.hooks.additionalTreeRuntimeRequirements.tap( + "RuntimePlugin", + (chunk, set) => { + const { mainTemplate } = compilation; + if ( + mainTemplate.hooks.bootstrap.isUsed() || + mainTemplate.hooks.localVars.isUsed() || + mainTemplate.hooks.requireEnsure.isUsed() || + mainTemplate.hooks.requireExtensions.isUsed() + ) { + compilation.addRuntimeModule(chunk, new CompatRuntimeModule()); + } + } + ); + JavascriptModulesPlugin.getCompilationHooks(compilation).chunkHash.tap( + "RuntimePlugin", + (chunk, hash, { chunkGraph }) => { + const xor = new StringXor(); + for (const m of chunkGraph.getChunkRuntimeModulesIterable(chunk)) { + xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); + } + xor.updateHash(hash); + } ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return true; }); } } -module.exports = CommonJsExportsParserPlugin; +module.exports = RuntimePlugin; /***/ }), -/***/ 59440: +/***/ 18777: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -73375,537 +66423,1045 @@ module.exports = CommonJsExportsParserPlugin; -const Template = __webpack_require__(1626); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); const { equals } = __webpack_require__(84953); -const makeSerializable = __webpack_require__(33032); +const compileBooleanMatcher = __webpack_require__(29404); const propertyAccess = __webpack_require__(54190); -const ModuleDependency = __webpack_require__(80321); +const { forEachRuntime, subtractRuntime } = __webpack_require__(17156); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ -class CommonJsFullRequireDependency extends ModuleDependency { +/** + * @param {Module} module the module + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {string} error message + */ +const noModuleIdErrorMessage = (module, chunkGraph) => { + return `Module ${module.identifier()} has no id assigned. +This should not happen. +It's in these chunks: ${ + Array.from( + chunkGraph.getModuleChunksIterable(module), + c => c.name || c.id || c.debugId + ).join(", ") || "none" + } (If module is in no chunk this indicates a bug in some chunk/module optimization logic) +Module has these incoming connections: ${Array.from( + chunkGraph.moduleGraph.getIncomingConnections(module), + connection => + `\n - ${ + connection.originModule && connection.originModule.identifier() + } ${connection.dependency && connection.dependency.type} ${ + (connection.explanations && + Array.from(connection.explanations).join(", ")) || + "" + }` + ).join("")}`; +}; + +/** + * @param {string|undefined} definition global object definition + * @returns {string} save to use global object + */ +function getGlobalObject(definition) { + if (!definition) return definition; + const trimmed = definition.trim(); + + if ( + // identifier, we do not need real identifier regarding ECMAScript/Unicode + trimmed.match(/^[_\p{L}][_0-9\p{L}]*$/iu) || + // iife + // call expression + // expression in parentheses + trimmed.match(/^([_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu) + ) + return trimmed; + + return `Object(${trimmed})`; +} + +class RuntimeTemplate { /** - * @param {string} request the request string - * @param {[number, number]} range location in source code - * @param {string[]} names accessed properties on module + * @param {Compilation} compilation the compilation + * @param {OutputOptions} outputOptions the compilation output options + * @param {RequestShortener} requestShortener the request shortener */ - constructor(request, range, names) { - super(request); - this.range = range; - this.names = names; - this.call = false; - this.asiSafe = undefined; + constructor(compilation, outputOptions, requestShortener) { + this.compilation = compilation; + this.outputOptions = outputOptions || {}; + this.requestShortener = requestShortener; + this.globalObject = getGlobalObject(outputOptions.globalObject); } - /** - * 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) { - if (this.call) { - const importedModule = moduleGraph.getModule(this); - if ( - !importedModule || - importedModule.getExportsType(moduleGraph, false) !== "namespace" - ) { - return [this.names.slice(0, -1)]; - } - } - return [this.names]; + isIIFE() { + return this.outputOptions.iife; } - serialize(context) { - const { write } = context; - write(this.names); - write(this.call); - write(this.asiSafe); - super.serialize(context); + isModule() { + return this.outputOptions.module; } - deserialize(context) { - const { read } = context; - this.names = read(); - this.call = read(); - this.asiSafe = read(); - super.deserialize(context); + supportsConst() { + return this.outputOptions.environment.const; } - get type() { - return "cjs full require"; + supportsArrowFunction() { + return this.outputOptions.environment.arrowFunction; } - get category() { - return "commonjs"; + supportsOptionalChaining() { + return this.outputOptions.environment.optionalChaining; + } + + supportsForOf() { + return this.outputOptions.environment.forOf; + } + + supportsDestructuring() { + return this.outputOptions.environment.destructuring; + } + + supportsBigIntLiteral() { + return this.outputOptions.environment.bigIntLiteral; + } + + supportsDynamicImport() { + return this.outputOptions.environment.dynamicImport; + } + + supportsEcmaScriptModuleSyntax() { + return this.outputOptions.environment.module; + } + + supportTemplateLiteral() { + return this.outputOptions.environment.templateLiteral; + } + + returningFunction(returnValue, args = "") { + return this.supportsArrowFunction() + ? `(${args}) => (${returnValue})` + : `function(${args}) { return ${returnValue}; }`; + } + + basicFunction(args, body) { + return this.supportsArrowFunction() + ? `(${args}) => {\n${Template.indent(body)}\n}` + : `function(${args}) {\n${Template.indent(body)}\n}`; } -} -CommonJsFullRequireDependency.Template = class CommonJsFullRequireDependencyTemplate extends ( - ModuleDependency.Template -) { /** - * @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} + * @param {Array} args args + * @returns {string} result expression */ - apply( - dependency, - source, - { - module, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtimeRequirements, - runtime, - initFragments + concatenation(...args) { + const len = args.length; + + if (len === 2) return this._es5Concatenation(args); + if (len === 0) return '""'; + if (len === 1) { + return typeof args[0] === "string" + ? JSON.stringify(args[0]) + : `"" + ${args[0].expr}`; } - ) { - const dep = /** @type {CommonJsFullRequireDependency} */ (dependency); - if (!dep.range) return; - const importedModule = moduleGraph.getModule(dep); - let requireExpr = runtimeTemplate.moduleExports({ - module: importedModule, - chunkGraph, - request: dep.request, - weak: dep.weak, - runtimeRequirements - }); - if (importedModule) { - const ids = dep.names; - const usedImported = moduleGraph - .getExportsInfo(importedModule) - .getUsedName(ids, runtime); - if (usedImported) { - const comment = equals(usedImported, ids) - ? "" - : Template.toNormalComment(propertyAccess(ids)) + " "; - const access = `${comment}${propertyAccess(usedImported)}`; - requireExpr = - dep.asiSafe === true - ? `(${requireExpr}${access})` - : `${requireExpr}${access}`; + if (!this.supportTemplateLiteral()) return this._es5Concatenation(args); + + // cost comparison between template literal and concatenation: + // both need equal surroundings: `xxx` vs "xxx" + // template literal has constant cost of 3 chars for each expression + // es5 concatenation has cost of 3 + n chars for n expressions in row + // when a es5 concatenation ends with an expression it reduces cost by 3 + // when a es5 concatenation starts with an single expression it reduces cost by 3 + // e. g. `${a}${b}${c}` (3*3 = 9) is longer than ""+a+b+c ((3+3)-3 = 3) + // e. g. `x${a}x${b}x${c}x` (3*3 = 9) is shorter than "x"+a+"x"+b+"x"+c+"x" (4+4+4 = 12) + + let templateCost = 0; + let concatenationCost = 0; + + let lastWasExpr = false; + for (const arg of args) { + const isExpr = typeof arg !== "string"; + if (isExpr) { + templateCost += 3; + concatenationCost += lastWasExpr ? 1 : 4; } + lastWasExpr = isExpr; } - source.replace(dep.range[0], dep.range[1] - 1, requireExpr); + if (lastWasExpr) concatenationCost -= 3; + if (typeof args[0] !== "string" && typeof args[1] === "string") + concatenationCost -= 3; + + if (concatenationCost <= templateCost) return this._es5Concatenation(args); + + return `\`${args + .map(arg => (typeof arg === "string" ? arg : `\${${arg.expr}}`)) + .join("")}\``; } -}; -makeSerializable( - CommonJsFullRequireDependency, - "webpack/lib/dependencies/CommonJsFullRequireDependency" -); + /** + * @param {Array} args args (len >= 2) + * @returns {string} result expression + * @private + */ + _es5Concatenation(args) { + const str = args + .map(arg => (typeof arg === "string" ? JSON.stringify(arg) : arg.expr)) + .join(" + "); -module.exports = CommonJsFullRequireDependency; + // when the first two args are expression, we need to prepend "" + to force string + // concatenation instead of number addition. + return typeof args[0] !== "string" && typeof args[1] !== "string" + ? `"" + ${str}` + : str; + } + expressionFunction(expression, args = "") { + return this.supportsArrowFunction() + ? `(${args}) => (${expression})` + : `function(${args}) { ${expression}; }`; + } -/***/ }), + emptyFunction() { + return this.supportsArrowFunction() ? "x => {}" : "function() {}"; + } -/***/ 36013: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + destructureArray(items, value) { + return this.supportsDestructuring() + ? `var [${items.join(", ")}] = ${value};` + : Template.asString( + items.map((item, i) => `var ${item} = ${value}[${i}];`) + ); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + destructureObject(items, value) { + return this.supportsDestructuring() + ? `var {${items.join(", ")}} = ${value};` + : Template.asString( + items.map(item => `var ${item} = ${value}${propertyAccess([item])};`) + ); + } + iife(args, body) { + return `(${this.basicFunction(args, body)})()`; + } + forEach(variable, array, body) { + return this.supportsForOf() + ? `for(const ${variable} of ${array}) {\n${Template.indent(body)}\n}` + : `${array}.forEach(function(${variable}) {\n${Template.indent( + body + )}\n});`; + } -const CommentCompilationWarning = __webpack_require__(98427); -const RuntimeGlobals = __webpack_require__(16475); -const UnsupportedFeatureWarning = __webpack_require__(42495); -const { - evaluateToIdentifier, - evaluateToString, - expressionIsUnsupported, - toConstantDependency -} = __webpack_require__(93998); -const CommonJsFullRequireDependency = __webpack_require__(59440); -const CommonJsRequireContextDependency = __webpack_require__(23962); -const CommonJsRequireDependency = __webpack_require__(21264); -const ConstDependency = __webpack_require__(76911); -const ContextDependencyHelpers = __webpack_require__(99630); -const LocalModuleDependency = __webpack_require__(52805); -const { getLocalModule } = __webpack_require__(75827); -const RequireHeaderDependency = __webpack_require__(89183); -const RequireResolveContextDependency = __webpack_require__(55627); -const RequireResolveDependency = __webpack_require__(68582); -const RequireResolveHeaderDependency = __webpack_require__(9880); + /** + * Add a comment + * @param {object} options Information content of the comment + * @param {string=} options.request request string used originally + * @param {string=} options.chunkName name of the chunk referenced + * @param {string=} options.chunkReason reason information of the chunk + * @param {string=} options.message additional message + * @param {string=} options.exportName name of the export + * @returns {string} comment + */ + comment({ request, chunkName, chunkReason, message, exportName }) { + let content; + if (this.outputOptions.pathinfo) { + content = [message, request, chunkName, chunkReason] + .filter(Boolean) + .map(item => this.requestShortener.shorten(item)) + .join(" | "); + } else { + content = [message, chunkName, chunkReason] + .filter(Boolean) + .map(item => this.requestShortener.shorten(item)) + .join(" | "); + } + if (!content) return ""; + if (this.outputOptions.pathinfo) { + return Template.toComment(content) + " "; + } else { + return Template.toNormalComment(content) + " "; + } + } -/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ + /** + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error block + */ + throwMissingModuleErrorBlock({ request }) { + const err = `Cannot find module '${request}'`; + return `var e = new Error(${JSON.stringify( + err + )}); e.code = 'MODULE_NOT_FOUND'; throw e;`; + } -class CommonJsImportsParserPlugin { /** - * @param {JavascriptParserOptions} options parser options + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error function */ - constructor(options) { - this.options = options; + throwMissingModuleErrorFunction({ request }) { + return `function webpackMissingModule() { ${this.throwMissingModuleErrorBlock( + { request } + )} }`; } - apply(parser) { - const options = this.options; + /** + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error IIFE + */ + missingModule({ request }) { + return `Object(${this.throwMissingModuleErrorFunction({ request })}())`; + } - // metadata // - const tapRequireExpression = (expression, getMembers) => { - parser.hooks.typeof - .for(expression) - .tap( - "CommonJsPlugin", - toConstantDependency(parser, JSON.stringify("function")) - ); - parser.hooks.evaluateTypeof - .for(expression) - .tap("CommonJsPlugin", evaluateToString("function")); - parser.hooks.evaluateIdentifier - .for(expression) - .tap( - "CommonJsPlugin", - evaluateToIdentifier(expression, "require", getMembers, true) - ); - }; - tapRequireExpression("require", () => []); - tapRequireExpression("require.resolve", () => ["resolve"]); - tapRequireExpression("require.resolveWeak", () => ["resolveWeak"]); + /** + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error statement + */ + missingModuleStatement({ request }) { + return `${this.missingModule({ request })};\n`; + } - // Weird stuff // - parser.hooks.assign.for("require").tap("CommonJsPlugin", expr => { - // to not leak to global "require", we need to define a local require here. - const dep = new ConstDependency("var require;", 0); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); + /** + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error code + */ + missingModulePromise({ request }) { + return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({ + request + })})`; + } - // Unsupported // - parser.hooks.expression - .for("require.main.require") - .tap( - "CommonJsPlugin", - expressionIsUnsupported( - parser, - "require.main.require is not supported by webpack." - ) - ); - parser.hooks.call - .for("require.main.require") - .tap( - "CommonJsPlugin", - expressionIsUnsupported( - parser, - "require.main.require is not supported by webpack." - ) - ); - parser.hooks.expression - .for("module.parent.require") - .tap( - "CommonJsPlugin", - expressionIsUnsupported( - parser, - "module.parent.require is not supported by webpack." - ) + /** + * @param {Object} options options object + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {Module} options.module the module + * @param {string} options.request the request that should be printed as comment + * @param {string=} options.idExpr expression to use as id expression + * @param {"expression" | "promise" | "statements"} options.type which kind of code should be returned + * @returns {string} the code + */ + weakError({ module, chunkGraph, request, idExpr, type }) { + const moduleId = chunkGraph.getModuleId(module); + const errorMessage = + moduleId === null + ? JSON.stringify("Module is not available (weak dependency)") + : idExpr + ? `"Module '" + ${idExpr} + "' is not available (weak dependency)"` + : JSON.stringify( + `Module '${moduleId}' is not available (weak dependency)` + ); + const comment = request ? Template.toNormalComment(request) + " " : ""; + const errorStatements = + `var e = new Error(${errorMessage}); ` + + comment + + "e.code = 'MODULE_NOT_FOUND'; throw e;"; + switch (type) { + case "statements": + return errorStatements; + case "promise": + return `Promise.resolve().then(${this.basicFunction( + "", + errorStatements + )})`; + case "expression": + return this.iife("", errorStatements); + } + } + + /** + * @param {Object} options options object + * @param {Module} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @returns {string} the expression + */ + moduleId({ module, chunkGraph, request, weak }) { + if (!module) { + return this.missingModule({ + request + }); + } + const moduleId = chunkGraph.getModuleId(module); + if (moduleId === null) { + if (weak) { + return "null /* weak dependency, without id */"; + } + throw new Error( + `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` ); - parser.hooks.call - .for("module.parent.require") - .tap( - "CommonJsPlugin", - expressionIsUnsupported( - parser, - "module.parent.require is not supported by webpack." - ) + } + return `${this.comment({ request })}${JSON.stringify(moduleId)}`; + } + + /** + * @param {Object} options options object + * @param {Module} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} the expression + */ + moduleRaw({ module, chunkGraph, request, weak, runtimeRequirements }) { + if (!module) { + return this.missingModule({ + request + }); + } + const moduleId = chunkGraph.getModuleId(module); + if (moduleId === null) { + if (weak) { + // only weak referenced modules don't get an id + // we can always emit an error emitting code here + return this.weakError({ + module, + chunkGraph, + request, + type: "expression" + }); + } + throw new Error( + `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` ); + } + runtimeRequirements.add(RuntimeGlobals.require); + return `__webpack_require__(${this.moduleId({ + module, + chunkGraph, + request, + weak + })})`; + } - // renaming // - parser.hooks.canRename.for("require").tap("CommonJsPlugin", () => true); - parser.hooks.rename.for("require").tap("CommonJsPlugin", expr => { - // To avoid "not defined" error, replace the value with undefined - const dep = new ConstDependency("undefined", expr.range); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return false; + /** + * @param {Object} options options object + * @param {Module} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} the expression + */ + moduleExports({ module, chunkGraph, request, weak, runtimeRequirements }) { + return this.moduleRaw({ + module, + chunkGraph, + request, + weak, + runtimeRequirements }); + } - // inspection // - parser.hooks.expression - .for("require.cache") - .tap( - "CommonJsImportsParserPlugin", - toConstantDependency(parser, RuntimeGlobals.moduleCache, [ - RuntimeGlobals.moduleCache, - RuntimeGlobals.moduleId, - RuntimeGlobals.moduleLoaded - ]) + /** + * @param {Object} options options object + * @param {Module} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {boolean=} options.strict if the current module is in strict esm mode + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} the expression + */ + moduleNamespace({ + module, + chunkGraph, + request, + strict, + weak, + runtimeRequirements + }) { + if (!module) { + return this.missingModule({ + request + }); + } + if (chunkGraph.getModuleId(module) === null) { + if (weak) { + // only weak referenced modules don't get an id + // we can always emit an error emitting code here + return this.weakError({ + module, + chunkGraph, + request, + type: "expression" + }); + } + throw new Error( + `RuntimeTemplate.moduleNamespace(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` ); + } + const moduleId = this.moduleId({ + module, + chunkGraph, + request, + weak + }); + const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict); + switch (exportsType) { + case "namespace": + return this.moduleRaw({ + module, + chunkGraph, + request, + weak, + runtimeRequirements + }); + case "default-with-named": + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 3)`; + case "default-only": + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 1)`; + case "dynamic": + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 7)`; + } + } - // require as expression // - parser.hooks.expression - .for("require") - .tap("CommonJsImportsParserPlugin", expr => { - const dep = new CommonJsRequireContextDependency( - { - request: options.unknownContextRequest, - recursive: options.unknownContextRecursive, - regExp: options.unknownContextRegExp, - mode: "sync" - }, - expr.range, - undefined, - parser.scope.inShorthand - ); - dep.critical = - options.unknownContextCritical && - "require function is used in a way in which dependencies cannot be statically extracted"; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; + /** + * @param {Object} options options object + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {AsyncDependenciesBlock=} options.block the current dependencies block + * @param {Module} options.module the module + * @param {string} options.request the request that should be printed as comment + * @param {string} options.message a message for the comment + * @param {boolean=} options.strict if the current module is in strict esm mode + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} the promise expression + */ + moduleNamespacePromise({ + chunkGraph, + block, + module, + request, + message, + strict, + weak, + runtimeRequirements + }) { + if (!module) { + return this.missingModulePromise({ + request }); - - // require // - const processRequireItem = (expr, param) => { - if (param.isString()) { - const dep = new CommonJsRequireDependency(param.string, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; + } + const moduleId = chunkGraph.getModuleId(module); + if (moduleId === null) { + if (weak) { + // only weak referenced modules don't get an id + // we can always emit an error emitting code here + return this.weakError({ + module, + chunkGraph, + request, + type: "promise" + }); } - }; - const processRequireContext = (expr, param) => { - const dep = ContextDependencyHelpers.create( - CommonJsRequireContextDependency, - expr.range, - param, - expr, - options, - { - category: "commonjs" - }, - parser + throw new Error( + `RuntimeTemplate.moduleNamespacePromise(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - }; - const createRequireHandler = callNew => expr => { - if (options.commonjsMagicComments) { - const { options: requireOptions, errors: commentErrors } = - parser.parseCommentOptions(expr.range); + } + const promise = this.blockPromise({ + chunkGraph, + block, + message, + runtimeRequirements + }); - if (commentErrors) { - for (const e of commentErrors) { - const { comment } = e; - parser.state.module.addWarning( - new CommentCompilationWarning( - `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, - comment.loc - ) - ); - } + let appending; + let idExpr = JSON.stringify(chunkGraph.getModuleId(module)); + const comment = this.comment({ + request + }); + let header = ""; + if (weak) { + if (idExpr.length > 8) { + // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"' + header += `var id = ${idExpr}; `; + idExpr = "id"; + } + runtimeRequirements.add(RuntimeGlobals.moduleFactories); + header += `if(!${ + RuntimeGlobals.moduleFactories + }[${idExpr}]) { ${this.weakError({ + module, + chunkGraph, + request, + idExpr, + type: "statements" + })} } `; + } + const moduleIdExpr = this.moduleId({ + module, + chunkGraph, + request, + weak + }); + const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict); + let fakeType = 16; + switch (exportsType) { + case "namespace": + if (header) { + const rawModule = this.moduleRaw({ + module, + chunkGraph, + request, + weak, + runtimeRequirements + }); + appending = `.then(${this.basicFunction( + "", + `${header}return ${rawModule};` + )})`; + } else { + runtimeRequirements.add(RuntimeGlobals.require); + appending = `.then(__webpack_require__.bind(__webpack_require__, ${comment}${idExpr}))`; } - if (requireOptions) { - if (requireOptions.webpackIgnore !== undefined) { - if (typeof requireOptions.webpackIgnore !== "boolean") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackIgnore\` expected a boolean, but received: ${requireOptions.webpackIgnore}.`, - expr.loc - ) - ); - } else { - // Do not instrument `require()` if `webpackIgnore` is `true` - if (requireOptions.webpackIgnore) { - return true; - } - } + break; + case "dynamic": + fakeType |= 4; + /* fall through */ + case "default-with-named": + fakeType |= 2; + /* fall through */ + case "default-only": + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + if (chunkGraph.moduleGraph.isAsync(module)) { + if (header) { + const rawModule = this.moduleRaw({ + module, + chunkGraph, + request, + weak, + runtimeRequirements + }); + appending = `.then(${this.basicFunction( + "", + `${header}return ${rawModule};` + )})`; + } else { + runtimeRequirements.add(RuntimeGlobals.require); + appending = `.then(__webpack_require__.bind(__webpack_require__, ${comment}${idExpr}))`; + } + appending += `.then(${this.returningFunction( + `${RuntimeGlobals.createFakeNamespaceObject}(m, ${fakeType})`, + "m" + )})`; + } else { + fakeType |= 1; + if (header) { + const returnExpression = `${RuntimeGlobals.createFakeNamespaceObject}(${moduleIdExpr}, ${fakeType})`; + appending = `.then(${this.basicFunction( + "", + `${header}return ${returnExpression};` + )})`; + } else { + appending = `.then(${RuntimeGlobals.createFakeNamespaceObject}.bind(__webpack_require__, ${comment}${idExpr}, ${fakeType}))`; } } + break; + } + + return `${promise || "Promise.resolve()"}${appending}`; + } + + /** + * @param {Object} options options object + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {RuntimeSpec=} options.runtime runtime for which this code will be generated + * @param {RuntimeSpec | boolean=} options.runtimeCondition only execute the statement in some runtimes + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} expression + */ + runtimeConditionExpression({ + chunkGraph, + runtimeCondition, + runtime, + runtimeRequirements + }) { + if (runtimeCondition === undefined) return "true"; + if (typeof runtimeCondition === "boolean") return `${runtimeCondition}`; + /** @type {Set} */ + const positiveRuntimeIds = new Set(); + forEachRuntime(runtimeCondition, runtime => + positiveRuntimeIds.add(`${chunkGraph.getRuntimeId(runtime)}`) + ); + /** @type {Set} */ + const negativeRuntimeIds = new Set(); + forEachRuntime(subtractRuntime(runtime, runtimeCondition), runtime => + negativeRuntimeIds.add(`${chunkGraph.getRuntimeId(runtime)}`) + ); + runtimeRequirements.add(RuntimeGlobals.runtimeId); + return compileBooleanMatcher.fromLists( + Array.from(positiveRuntimeIds), + Array.from(negativeRuntimeIds) + )(RuntimeGlobals.runtimeId); + } + + /** + * + * @param {Object} options options object + * @param {boolean=} options.update whether a new variable should be created or the existing one updated + * @param {Module} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {string} options.importVar name of the import variable + * @param {Module} options.originModule module in which the statement is emitted + * @param {boolean=} options.weak true, if this is a weak dependency + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {[string, string]} the import statement and the compat statement + */ + importStatement({ + update, + module, + chunkGraph, + request, + importVar, + originModule, + weak, + runtimeRequirements + }) { + if (!module) { + return [ + this.missingModuleStatement({ + request + }), + "" + ]; + } + if (chunkGraph.getModuleId(module) === null) { + if (weak) { + // only weak referenced modules don't get an id + // we can always emit an error emitting code here + return [ + this.weakError({ + module, + chunkGraph, + request, + type: "statements" + }), + "" + ]; } + throw new Error( + `RuntimeTemplate.importStatement(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` + ); + } + const moduleId = this.moduleId({ + module, + chunkGraph, + request, + weak + }); + const optDeclaration = update ? "" : "var "; - if (expr.arguments.length !== 1) return; - let localModule; - const param = parser.evaluateExpression(expr.arguments[0]); - if (param.isConditional()) { - let isExpression = false; - for (const p of param.options) { - const result = processRequireItem(expr, p); - if (result === undefined) { - isExpression = true; - } + const exportsType = module.getExportsType( + chunkGraph.moduleGraph, + originModule.buildMeta.strictHarmonyModule + ); + runtimeRequirements.add(RuntimeGlobals.require); + const importContent = `/* harmony import */ ${optDeclaration}${importVar} = __webpack_require__(${moduleId});\n`; + + if (exportsType === "dynamic") { + runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport); + return [ + importContent, + `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${importVar});\n` + ]; + } + return [importContent, ""]; + } + + /** + * @param {Object} options options + * @param {ModuleGraph} options.moduleGraph the module graph + * @param {Module} options.module the module + * @param {string} options.request the request + * @param {string | string[]} options.exportName the export name + * @param {Module} options.originModule the origin module + * @param {boolean|undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted + * @param {boolean} options.isCall true, if expression will be called + * @param {boolean} options.callContext when false, call context will not be preserved + * @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated + * @param {string} options.importVar the identifier name of the import variable + * @param {InitFragment[]} options.initFragments init fragments will be added here + * @param {RuntimeSpec} options.runtime runtime for which this code will be generated + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} expression + */ + exportFromImport({ + moduleGraph, + module, + request, + exportName, + originModule, + asiSafe, + isCall, + callContext, + defaultInterop, + importVar, + initFragments, + runtime, + runtimeRequirements + }) { + if (!module) { + return this.missingModule({ + request + }); + } + if (!Array.isArray(exportName)) { + exportName = exportName ? [exportName] : []; + } + const exportsType = module.getExportsType( + moduleGraph, + originModule.buildMeta.strictHarmonyModule + ); + + if (defaultInterop) { + if (exportName.length > 0 && exportName[0] === "default") { + switch (exportsType) { + case "dynamic": + if (isCall) { + return `${importVar}_default()${propertyAccess(exportName, 1)}`; + } else { + return asiSafe + ? `(${importVar}_default()${propertyAccess(exportName, 1)})` + : asiSafe === false + ? `;(${importVar}_default()${propertyAccess(exportName, 1)})` + : `${importVar}_default.a${propertyAccess(exportName, 1)}`; + } + case "default-only": + case "default-with-named": + exportName = exportName.slice(1); + break; } - if (!isExpression) { - const dep = new RequireHeaderDependency(expr.callee.range); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; + } else if (exportName.length > 0) { + if (exportsType === "default-only") { + return ( + "/* non-default import from non-esm module */undefined" + + propertyAccess(exportName, 1) + ); + } else if ( + exportsType !== "namespace" && + exportName[0] === "__esModule" + ) { + return "/* __esModule */true"; } - } - if ( - param.isString() && - (localModule = getLocalModule(parser.state, param.string)) + } else if ( + exportsType === "default-only" || + exportsType === "default-with-named" ) { - localModule.flagUsed(); - const dep = new LocalModuleDependency(localModule, expr.range, callNew); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - } else { - const result = processRequireItem(expr, param); - if (result === undefined) { - processRequireContext(expr, param); - } else { - const dep = new RequireHeaderDependency(expr.callee.range); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - } - return true; - } - }; - parser.hooks.call - .for("require") - .tap("CommonJsImportsParserPlugin", createRequireHandler(false)); - parser.hooks.new - .for("require") - .tap("CommonJsImportsParserPlugin", createRequireHandler(true)); - parser.hooks.call - .for("module.require") - .tap("CommonJsImportsParserPlugin", createRequireHandler(false)); - parser.hooks.new - .for("module.require") - .tap("CommonJsImportsParserPlugin", createRequireHandler(true)); - - // require with property access // - const chainHandler = (expr, calleeMembers, callExpr, members) => { - if (callExpr.arguments.length !== 1) return; - const param = parser.evaluateExpression(callExpr.arguments[0]); - if (param.isString() && !getLocalModule(parser.state, param.string)) { - const dep = new CommonJsFullRequireDependency( - param.string, - expr.range, - members - ); - dep.asiSafe = !parser.isAsiPosition(expr.range[0]); - dep.optional = !!parser.scope.inTry; - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return true; - } - }; - const callChainHandler = (expr, calleeMembers, callExpr, members) => { - if (callExpr.arguments.length !== 1) return; - const param = parser.evaluateExpression(callExpr.arguments[0]); - if (param.isString() && !getLocalModule(parser.state, param.string)) { - const dep = new CommonJsFullRequireDependency( - param.string, - expr.callee.range, - members + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + initFragments.push( + new InitFragment( + `var ${importVar}_namespace_cache;\n`, + InitFragment.STAGE_CONSTANTS, + -1, + `${importVar}_namespace_cache` + ) ); - dep.call = true; - dep.asiSafe = !parser.isAsiPosition(expr.range[0]); - dep.optional = !!parser.scope.inTry; - dep.loc = expr.callee.loc; - parser.state.current.addDependency(dep); - parser.walkExpressions(expr.arguments); - return true; + return `/*#__PURE__*/ ${ + asiSafe ? "" : asiSafe === false ? ";" : "Object" + }(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${ + RuntimeGlobals.createFakeNamespaceObject + }(${importVar}${exportsType === "default-only" ? "" : ", 2"})))`; } - }; - parser.hooks.memberChainOfCallMemberChain - .for("require") - .tap("CommonJsImportsParserPlugin", chainHandler); - parser.hooks.memberChainOfCallMemberChain - .for("module.require") - .tap("CommonJsImportsParserPlugin", chainHandler); - parser.hooks.callMemberChainOfCallMemberChain - .for("require") - .tap("CommonJsImportsParserPlugin", callChainHandler); - parser.hooks.callMemberChainOfCallMemberChain - .for("module.require") - .tap("CommonJsImportsParserPlugin", callChainHandler); + } - // require.resolve // - const processResolve = (expr, weak) => { - if (expr.arguments.length !== 1) return; - const param = parser.evaluateExpression(expr.arguments[0]); - if (param.isConditional()) { - for (const option of param.options) { - const result = processResolveItem(expr, option, weak); - if (result === undefined) { - processResolveContext(expr, option, weak); - } - } - const dep = new RequireResolveHeaderDependency(expr.callee.range); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - } else { - const result = processResolveItem(expr, param, weak); - if (result === undefined) { - processResolveContext(expr, param, weak); - } - const dep = new RequireResolveHeaderDependency(expr.callee.range); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; + if (exportName.length > 0) { + const exportsInfo = moduleGraph.getExportsInfo(module); + const used = exportsInfo.getUsedName(exportName, runtime); + if (!used) { + const comment = Template.toNormalComment( + `unused export ${propertyAccess(exportName)}` + ); + return `${comment} undefined`; } - }; - const processResolveItem = (expr, param, weak) => { - if (param.isString()) { - const dep = new RequireResolveDependency(param.string, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - dep.weak = weak; - parser.state.current.addDependency(dep); - return true; + const comment = equals(used, exportName) + ? "" + : Template.toNormalComment(propertyAccess(exportName)) + " "; + const access = `${importVar}${comment}${propertyAccess(used)}`; + if (isCall && callContext === false) { + return asiSafe + ? `(0,${access})` + : asiSafe === false + ? `;(0,${access})` + : `/*#__PURE__*/Object(${access})`; } - }; - const processResolveContext = (expr, param, weak) => { - const dep = ContextDependencyHelpers.create( - RequireResolveContextDependency, - param.range, - param, - expr, - options, - { - category: "commonjs", - mode: weak ? "weak" : "sync" - }, - parser - ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - }; + return access; + } else { + return importVar; + } + } - parser.hooks.call - .for("require.resolve") - .tap("RequireResolveDependencyParserPlugin", expr => { - return processResolve(expr, false); + /** + * @param {Object} options options + * @param {AsyncDependenciesBlock} options.block the async block + * @param {string} options.message the message + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} expression + */ + blockPromise({ block, message, chunkGraph, runtimeRequirements }) { + if (!block) { + const comment = this.comment({ + message }); - parser.hooks.call - .for("require.resolveWeak") - .tap("RequireResolveDependencyParserPlugin", expr => { - return processResolve(expr, true); + return `Promise.resolve(${comment.trim()})`; + } + const chunkGroup = chunkGraph.getBlockChunkGroup(block); + if (!chunkGroup || chunkGroup.chunks.length === 0) { + const comment = this.comment({ + message }); + return `Promise.resolve(${comment.trim()})`; + } + const chunks = chunkGroup.chunks.filter( + chunk => !chunk.hasRuntime() && chunk.id !== null + ); + const comment = this.comment({ + message, + chunkName: block.chunkName + }); + if (chunks.length === 1) { + const chunkId = JSON.stringify(chunks[0].id); + runtimeRequirements.add(RuntimeGlobals.ensureChunk); + return `${RuntimeGlobals.ensureChunk}(${comment}${chunkId})`; + } else if (chunks.length > 0) { + runtimeRequirements.add(RuntimeGlobals.ensureChunk); + const requireChunkId = chunk => + `${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)})`; + return `Promise.all(${comment.trim()}[${chunks + .map(requireChunkId) + .join(", ")}])`; + } else { + return `Promise.resolve(${comment.trim()})`; + } + } + + /** + * @param {Object} options options + * @param {AsyncDependenciesBlock} options.block the async block + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @param {string=} options.request request string used originally + * @returns {string} expression + */ + asyncModuleFactory({ block, chunkGraph, runtimeRequirements, request }) { + const dep = block.dependencies[0]; + const module = chunkGraph.moduleGraph.getModule(dep); + const ensureChunk = this.blockPromise({ + block, + message: "", + chunkGraph, + runtimeRequirements + }); + const factory = this.returningFunction( + this.moduleRaw({ + module, + chunkGraph, + request, + runtimeRequirements + }) + ); + return this.returningFunction( + ensureChunk.startsWith("Promise.resolve(") + ? `${factory}` + : `${ensureChunk}.then(${this.returningFunction(factory)})` + ); + } + + /** + * @param {Object} options options + * @param {Dependency} options.dependency the dependency + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @param {string=} options.request request string used originally + * @returns {string} expression + */ + syncModuleFactory({ dependency, chunkGraph, runtimeRequirements, request }) { + const module = chunkGraph.moduleGraph.getModule(dependency); + const factory = this.returningFunction( + this.moduleRaw({ + module, + chunkGraph, + request, + runtimeRequirements + }) + ); + return this.returningFunction(factory); + } + + /** + * @param {Object} options options + * @param {string} options.exportsArgument the name of the exports object + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} statement + */ + defineEsModuleFlagStatement({ exportsArgument, runtimeRequirements }) { + runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); + runtimeRequirements.add(RuntimeGlobals.exports); + return `${RuntimeGlobals.makeNamespaceObject}(${exportsArgument});\n`; + } + + /** + * @param {Object} options options object + * @param {Module} options.module the module + * @param {string} options.publicPath the public path + * @param {RuntimeSpec=} options.runtime runtime + * @param {CodeGenerationResults} options.codeGenerationResults the code generation results + * @returns {string} the url of the asset + */ + assetUrl({ publicPath, runtime, module, codeGenerationResults }) { + if (!module) { + return "data:,"; + } + const codeGen = codeGenerationResults.get(module, runtime); + const { data } = codeGen; + const url = data.get("url"); + if (url) return url.toString(); + const filename = data.get("filename"); + return publicPath + filename; } } -module.exports = CommonJsImportsParserPlugin; + +module.exports = RuntimeTemplate; /***/ }), -/***/ 32406: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 63560: +/***/ (function(module) { "use strict"; /* @@ -73915,284 +67471,141 @@ module.exports = CommonJsImportsParserPlugin; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const SelfModuleFactory = __webpack_require__(63560); -const Template = __webpack_require__(1626); -const CommonJsExportsDependency = __webpack_require__(45598); -const CommonJsFullRequireDependency = __webpack_require__(59440); -const CommonJsRequireContextDependency = __webpack_require__(23962); -const CommonJsRequireDependency = __webpack_require__(21264); -const CommonJsSelfReferenceDependency = __webpack_require__(52225); -const ModuleDecoratorDependency = __webpack_require__(88488); -const RequireHeaderDependency = __webpack_require__(89183); -const RequireResolveContextDependency = __webpack_require__(55627); -const RequireResolveDependency = __webpack_require__(68582); -const RequireResolveHeaderDependency = __webpack_require__(9880); -const RuntimeRequirementsDependency = __webpack_require__(24187); +class SelfModuleFactory { + constructor(moduleGraph) { + this.moduleGraph = moduleGraph; + } -const CommonJsExportsParserPlugin = __webpack_require__(97107); -const CommonJsImportsParserPlugin = __webpack_require__(36013); + create(data, callback) { + const module = this.moduleGraph.getParentModule(data.dependencies[0]); + callback(null, { + module + }); + } +} -const { - evaluateToIdentifier, - toConstantDependency -} = __webpack_require__(93998); -const CommonJsExportRequireDependency = __webpack_require__(62892); +module.exports = SelfModuleFactory; -class CommonJsPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "CommonJsPlugin", - (compilation, { contextModuleFactory, normalModuleFactory }) => { - compilation.dependencyFactories.set( - CommonJsRequireDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - CommonJsRequireDependency, - new CommonJsRequireDependency.Template() - ); - compilation.dependencyFactories.set( - CommonJsFullRequireDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - CommonJsFullRequireDependency, - new CommonJsFullRequireDependency.Template() - ); +/***/ }), - compilation.dependencyFactories.set( - CommonJsRequireContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - CommonJsRequireContextDependency, - new CommonJsRequireContextDependency.Template() - ); +/***/ 48076: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - compilation.dependencyFactories.set( - RequireResolveDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - RequireResolveDependency, - new RequireResolveDependency.Template() - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ - compilation.dependencyFactories.set( - RequireResolveContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - RequireResolveContextDependency, - new RequireResolveContextDependency.Template() - ); - compilation.dependencyTemplates.set( - RequireResolveHeaderDependency, - new RequireResolveHeaderDependency.Template() - ); - compilation.dependencyTemplates.set( - RequireHeaderDependency, - new RequireHeaderDependency.Template() - ); +module.exports = __webpack_require__(96953); - compilation.dependencyTemplates.set( - CommonJsExportsDependency, - new CommonJsExportsDependency.Template() - ); - compilation.dependencyFactories.set( - CommonJsExportRequireDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - CommonJsExportRequireDependency, - new CommonJsExportRequireDependency.Template() - ); +/***/ }), - const selfFactory = new SelfModuleFactory(compilation.moduleGraph); +/***/ 71070: +/***/ (function(__unused_webpack_module, exports) { - compilation.dependencyFactories.set( - CommonJsSelfReferenceDependency, - selfFactory - ); - compilation.dependencyTemplates.set( - CommonJsSelfReferenceDependency, - new CommonJsSelfReferenceDependency.Template() - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ - compilation.dependencyFactories.set( - ModuleDecoratorDependency, - selfFactory - ); - compilation.dependencyTemplates.set( - ModuleDecoratorDependency, - new ModuleDecoratorDependency.Template() - ); - compilation.hooks.runtimeRequirementInModule - .for(RuntimeGlobals.harmonyModuleDecorator) - .tap("CommonJsPlugin", (module, set) => { - set.add(RuntimeGlobals.module); - set.add(RuntimeGlobals.requireScope); - }); - compilation.hooks.runtimeRequirementInModule - .for(RuntimeGlobals.nodeModuleDecorator) - .tap("CommonJsPlugin", (module, set) => { - set.add(RuntimeGlobals.module); - set.add(RuntimeGlobals.requireScope); - }); +/** + * @param {number} size the size in bytes + * @returns {string} the formatted size + */ +exports.formatSize = size => { + if (typeof size !== "number" || Number.isNaN(size) === true) { + return "unknown size"; + } - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.harmonyModuleDecorator) - .tap("CommonJsPlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new HarmonyModuleDecoratorRuntimeModule() - ); - }); + if (size <= 0) { + return "0 bytes"; + } - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.nodeModuleDecorator) - .tap("CommonJsPlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new NodeModuleDecoratorRuntimeModule() - ); - }); + const abbreviations = ["bytes", "KiB", "MiB", "GiB"]; + const index = Math.floor(Math.log(size) / Math.log(1024)); - const handler = (parser, parserOptions) => { - if (parserOptions.commonjs !== undefined && !parserOptions.commonjs) - return; - parser.hooks.typeof - .for("module") - .tap( - "CommonJsPlugin", - toConstantDependency(parser, JSON.stringify("object")) - ); + return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${ + abbreviations[index] + }`; +}; - parser.hooks.expression - .for("require.main") - .tap( - "CommonJsPlugin", - toConstantDependency( - parser, - `${RuntimeGlobals.moduleCache}[${RuntimeGlobals.entryModuleId}]`, - [RuntimeGlobals.moduleCache, RuntimeGlobals.entryModuleId] - ) - ); - parser.hooks.expression - .for("module.loaded") - .tap("CommonJsPlugin", expr => { - parser.state.module.buildInfo.moduleConcatenationBailout = - "module.loaded"; - const dep = new RuntimeRequirementsDependency([ - RuntimeGlobals.moduleLoaded - ]); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); - parser.hooks.expression - .for("module.id") - .tap("CommonJsPlugin", expr => { - parser.state.module.buildInfo.moduleConcatenationBailout = - "module.id"; - const dep = new RuntimeRequirementsDependency([ - RuntimeGlobals.moduleId - ]); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); +/***/ }), - parser.hooks.evaluateIdentifier.for("module.hot").tap( - "CommonJsPlugin", - evaluateToIdentifier("module.hot", "module", () => ["hot"], null) - ); +/***/ 97513: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - new CommonJsImportsParserPlugin(parserOptions).apply(parser); - new CommonJsExportsParserPlugin(compilation.moduleGraph).apply( - parser - ); - }; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("CommonJsPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("CommonJsPlugin", handler); - } - ); - } -} -class HarmonyModuleDecoratorRuntimeModule extends RuntimeModule { - constructor() { - super("harmony module decorator"); - } - /** - * @returns {string} runtime code - */ - generate() { - const { runtimeTemplate } = this.compilation; - return Template.asString([ - `${ - RuntimeGlobals.harmonyModuleDecorator - } = ${runtimeTemplate.basicFunction("module", [ - "module = Object.create(module);", - "if (!module.children) module.children = [];", - "Object.defineProperty(module, 'exports', {", - Template.indent([ - "enumerable: true,", - `set: ${runtimeTemplate.basicFunction("", [ - "throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);" - ])}` - ]), - "});", - "return module;" - ])};` - ]); - } -} +const JavascriptModulesPlugin = __webpack_require__(89464); -class NodeModuleDecoratorRuntimeModule extends RuntimeModule { - constructor() { - super("node module decorator"); +/** @typedef {import("./Compilation")} Compilation */ + +class SourceMapDevToolModuleOptionsPlugin { + constructor(options) { + this.options = options; } /** - * @returns {string} runtime code + * @param {Compilation} compilation the compiler instance + * @returns {void} */ - generate() { - const { runtimeTemplate } = this.compilation; - return Template.asString([ - `${RuntimeGlobals.nodeModuleDecorator} = ${runtimeTemplate.basicFunction( - "module", - [ - "module.paths = [];", - "if (!module.children) module.children = [];", - "return module;" - ] - )};` - ]); + apply(compilation) { + const options = this.options; + if (options.module !== false) { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.useSourceMap = true; + } + ); + compilation.hooks.runtimeModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.useSourceMap = true; + } + ); + } else { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.useSimpleSourceMap = true; + } + ); + compilation.hooks.runtimeModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.useSimpleSourceMap = true; + } + ); + } + JavascriptModulesPlugin.getCompilationHooks(compilation).useSourceMap.tap( + "SourceMapDevToolModuleOptionsPlugin", + () => true + ); } } -module.exports = CommonJsPlugin; +module.exports = SourceMapDevToolModuleOptionsPlugin; /***/ }), -/***/ 23962: +/***/ 63872: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -74203,102 +67616,565 @@ module.exports = CommonJsPlugin; -const makeSerializable = __webpack_require__(33032); -const ContextDependency = __webpack_require__(88101); -const ContextDependencyTemplateAsRequireCall = __webpack_require__(75815); +const asyncLib = __webpack_require__(78175); +const { ConcatSource, RawSource } = __webpack_require__(51255); +const Compilation = __webpack_require__(85720); +const ModuleFilenameHelpers = __webpack_require__(88821); +const ProgressPlugin = __webpack_require__(13216); +const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(97513); +const createSchemaValidation = __webpack_require__(32540); +const createHash = __webpack_require__(49835); +const { relative, dirname } = __webpack_require__(17139); +const { makePathsAbsolute } = __webpack_require__(82186); -class CommonJsRequireContextDependency extends ContextDependency { - constructor(options, range, valueRange, inShorthand) { - super(options); +/** @typedef {import("webpack-sources").MapOptions} MapOptions */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ +/** @typedef {import("./Cache").Etag} Etag */ +/** @typedef {import("./CacheFacade").ItemCacheFacade} ItemCacheFacade */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./NormalModule").SourceMap} SourceMap */ +/** @typedef {import("./util/Hash")} Hash */ - this.range = range; - this.valueRange = valueRange; - // inShorthand must be serialized by subclasses that use it - this.inShorthand = inShorthand; +const validate = createSchemaValidation( + __webpack_require__(2885), + () => __webpack_require__(30501), + { + name: "SourceMap DevTool Plugin", + baseDataPath: "options" } +); +/** + * @typedef {object} SourceMapTask + * @property {Source} asset + * @property {AssetInfo} assetInfo + * @property {(string | Module)[]} modules + * @property {string} source + * @property {string} file + * @property {SourceMap} sourceMap + * @property {ItemCacheFacade} cacheItem cache item + */ - get type() { - return "cjs require context"; +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string + */ +const quoteMeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); +}; + +/** + * Creating {@link SourceMapTask} for given file + * @param {string} file current compiled file + * @param {Source} asset the asset + * @param {AssetInfo} assetInfo the asset info + * @param {MapOptions} options source map options + * @param {Compilation} compilation compilation instance + * @param {ItemCacheFacade} cacheItem cache item + * @returns {SourceMapTask | undefined} created task instance or `undefined` + */ +const getTaskForFile = ( + file, + asset, + assetInfo, + options, + compilation, + cacheItem +) => { + let source; + /** @type {SourceMap} */ + let sourceMap; + /** + * Check if asset can build source map + */ + if (asset.sourceAndMap) { + const sourceAndMap = asset.sourceAndMap(options); + sourceMap = /** @type {SourceMap} */ (sourceAndMap.map); + source = sourceAndMap.source; + } else { + sourceMap = /** @type {SourceMap} */ (asset.map(options)); + source = asset.source(); } + if (!sourceMap || typeof source !== "string") return; + const context = compilation.options.context; + const root = compilation.compiler.root; + const cachedAbsolutify = makePathsAbsolute.bindContextCache(context, root); + const modules = sourceMap.sources.map(source => { + if (!source.startsWith("webpack://")) return source; + source = cachedAbsolutify(source.slice(10)); + const module = compilation.findModule(source); + return module || source; + }); - serialize(context) { - const { write } = context; + return { + file, + asset, + source, + assetInfo, + sourceMap, + modules, + cacheItem + }; +}; - write(this.range); - write(this.valueRange); - write(this.inShorthand); +class SourceMapDevToolPlugin { + /** + * @param {SourceMapDevToolPluginOptions} [options] options object + * @throws {Error} throws error, if got more than 1 arguments + */ + constructor(options = {}) { + validate(options); - super.serialize(context); + /** @type {string | false} */ + this.sourceMapFilename = options.filename; + /** @type {string | false} */ + this.sourceMappingURLComment = + options.append === false + ? false + : options.append || "\n//# source" + "MappingURL=[url]"; + /** @type {string | Function} */ + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]"; + /** @type {string | Function} */ + this.fallbackModuleFilenameTemplate = + options.fallbackModuleFilenameTemplate || + "webpack://[namespace]/[resourcePath]?[hash]"; + /** @type {string} */ + this.namespace = options.namespace || ""; + /** @type {SourceMapDevToolPluginOptions} */ + this.options = options; } - deserialize(context) { - const { read } = context; + /** + * Apply the plugin + * @param {Compiler} compiler compiler instance + * @returns {void} + */ + apply(compiler) { + const outputFs = compiler.outputFileSystem; + const sourceMapFilename = this.sourceMapFilename; + const sourceMappingURLComment = this.sourceMappingURLComment; + const moduleFilenameTemplate = this.moduleFilenameTemplate; + const namespace = this.namespace; + const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate; + const requestShortener = compiler.requestShortener; + const options = this.options; + options.test = options.test || /\.((c|m)?js|css)($|\?)/i; - this.range = read(); - this.valueRange = read(); - this.inShorthand = read(); + const matchObject = ModuleFilenameHelpers.matchObject.bind( + undefined, + options + ); - super.deserialize(context); - } -} + compiler.hooks.compilation.tap("SourceMapDevToolPlugin", compilation => { + new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); -makeSerializable( - CommonJsRequireContextDependency, - "webpack/lib/dependencies/CommonJsRequireContextDependency" -); + compilation.hooks.processAssets.tapAsync( + { + name: "SourceMapDevToolPlugin", + stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING, + additionalAssets: true + }, + (assets, callback) => { + const chunkGraph = compilation.chunkGraph; + const cache = compilation.getCache("SourceMapDevToolPlugin"); + /** @type {Map} */ + const moduleToSourceNameMapping = new Map(); + /** + * @type {Function} + * @returns {void} + */ + const reportProgress = + ProgressPlugin.getReporter(compilation.compiler) || (() => {}); -CommonJsRequireContextDependency.Template = - ContextDependencyTemplateAsRequireCall; + /** @type {Map} */ + const fileToChunk = new Map(); + for (const chunk of compilation.chunks) { + for (const file of chunk.files) { + fileToChunk.set(file, chunk); + } + for (const file of chunk.auxiliaryFiles) { + fileToChunk.set(file, chunk); + } + } -module.exports = CommonJsRequireContextDependency; + /** @type {string[]} */ + const files = []; + for (const file of Object.keys(assets)) { + if (matchObject(file)) { + files.push(file); + } + } + reportProgress(0.0); + /** @type {SourceMapTask[]} */ + const tasks = []; + let fileIndex = 0; -/***/ }), + asyncLib.each( + files, + (file, callback) => { + const asset = compilation.getAsset(file); + if (asset.info.related && asset.info.related.sourceMap) { + fileIndex++; + return callback(); + } + const cacheItem = cache.getItemCache( + file, + cache.mergeEtags( + cache.getLazyHashedEtag(asset.source), + namespace + ) + ); -/***/ 21264: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + cacheItem.get((err, cacheEntry) => { + if (err) { + return callback(err); + } + /** + * If presented in cache, reassigns assets. Cache assets already have source maps. + */ + if (cacheEntry) { + const { assets, assetsInfo } = cacheEntry; + for (const cachedFile of Object.keys(assets)) { + if (cachedFile === file) { + compilation.updateAsset( + cachedFile, + assets[cachedFile], + assetsInfo[cachedFile] + ); + } else { + compilation.emitAsset( + cachedFile, + assets[cachedFile], + assetsInfo[cachedFile] + ); + } + /** + * Add file to chunk, if not presented there + */ + if (cachedFile !== file) { + const chunk = fileToChunk.get(file); + if (chunk !== undefined) + chunk.auxiliaryFiles.add(cachedFile); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + reportProgress( + (0.5 * ++fileIndex) / files.length, + file, + "restored cached SourceMap" + ); + return callback(); + } + reportProgress( + (0.5 * fileIndex) / files.length, + file, + "generate SourceMap" + ); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyTemplateAsId = __webpack_require__(80825); + /** @type {SourceMapTask | undefined} */ + const task = getTaskForFile( + file, + asset.source, + asset.info, + { + module: options.module, + columns: options.columns + }, + compilation, + cacheItem + ); -class CommonJsRequireDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; - } + if (task) { + const modules = task.modules; - get type() { - return "cjs require"; - } + for (let idx = 0; idx < modules.length; idx++) { + const module = modules[idx]; + if (!moduleToSourceNameMapping.get(module)) { + moduleToSourceNameMapping.set( + module, + ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: moduleFilenameTemplate, + namespace: namespace + }, + { + requestShortener, + chunkGraph, + hashFunction: compilation.outputOptions.hashFunction + } + ) + ); + } + } - get category() { - return "commonjs"; - } -} + tasks.push(task); + } -CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; + reportProgress( + (0.5 * ++fileIndex) / files.length, + file, + "generated SourceMap" + ); -makeSerializable( - CommonJsRequireDependency, - "webpack/lib/dependencies/CommonJsRequireDependency" -); + callback(); + }); + }, + err => { + if (err) { + return callback(err); + } -module.exports = CommonJsRequireDependency; + reportProgress(0.5, "resolve sources"); + /** @type {Set} */ + const usedNamesSet = new Set(moduleToSourceNameMapping.values()); + /** @type {Set} */ + const conflictDetectionSet = new Set(); + + /** + * all modules in defined order (longest identifier first) + * @type {Array} + */ + const allModules = Array.from( + moduleToSourceNameMapping.keys() + ).sort((a, b) => { + const ai = typeof a === "string" ? a : a.identifier(); + const bi = typeof b === "string" ? b : b.identifier(); + return ai.length - bi.length; + }); + + // find modules with conflicting source names + for (let idx = 0; idx < allModules.length; idx++) { + const module = allModules[idx]; + let sourceName = moduleToSourceNameMapping.get(module); + let hasName = conflictDetectionSet.has(sourceName); + if (!hasName) { + conflictDetectionSet.add(sourceName); + continue; + } + + // try the fallback name first + sourceName = ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: fallbackModuleFilenameTemplate, + namespace: namespace + }, + { + requestShortener, + chunkGraph, + hashFunction: compilation.outputOptions.hashFunction + } + ); + hasName = usedNamesSet.has(sourceName); + if (!hasName) { + moduleToSourceNameMapping.set(module, sourceName); + usedNamesSet.add(sourceName); + continue; + } + + // otherwise just append stars until we have a valid name + while (hasName) { + sourceName += "*"; + hasName = usedNamesSet.has(sourceName); + } + moduleToSourceNameMapping.set(module, sourceName); + usedNamesSet.add(sourceName); + } + + let taskIndex = 0; + + asyncLib.each( + tasks, + (task, callback) => { + const assets = Object.create(null); + const assetsInfo = Object.create(null); + const file = task.file; + const chunk = fileToChunk.get(file); + const sourceMap = task.sourceMap; + const source = task.source; + const modules = task.modules; + + reportProgress( + 0.5 + (0.5 * taskIndex) / tasks.length, + file, + "attach SourceMap" + ); + + const moduleFilenames = modules.map(m => + moduleToSourceNameMapping.get(m) + ); + sourceMap.sources = moduleFilenames; + if (options.noSources) { + sourceMap.sourcesContent = undefined; + } + sourceMap.sourceRoot = options.sourceRoot || ""; + sourceMap.file = file; + const usesContentHash = + sourceMapFilename && + /\[contenthash(:\w+)?\]/.test(sourceMapFilename); + + // If SourceMap and asset uses contenthash, avoid a circular dependency by hiding hash in `file` + if (usesContentHash && task.assetInfo.contenthash) { + const contenthash = task.assetInfo.contenthash; + let pattern; + if (Array.isArray(contenthash)) { + pattern = contenthash.map(quoteMeta).join("|"); + } else { + pattern = quoteMeta(contenthash); + } + sourceMap.file = sourceMap.file.replace( + new RegExp(pattern, "g"), + m => "x".repeat(m.length) + ); + } + + /** @type {string | false} */ + let currentSourceMappingURLComment = sourceMappingURLComment; + if ( + currentSourceMappingURLComment !== false && + /\.css($|\?)/i.test(file) + ) { + currentSourceMappingURLComment = + currentSourceMappingURLComment.replace( + /^\n\/\/(.*)$/, + "\n/*$1*/" + ); + } + const sourceMapString = JSON.stringify(sourceMap); + if (sourceMapFilename) { + let filename = file; + const sourceMapContentHash = + usesContentHash && + /** @type {string} */ ( + createHash(compilation.outputOptions.hashFunction) + .update(sourceMapString) + .digest("hex") + ); + const pathParams = { + chunk, + filename: options.fileContext + ? relative( + outputFs, + `/${options.fileContext}`, + `/${filename}` + ) + : filename, + contentHash: sourceMapContentHash + }; + const { path: sourceMapFile, info: sourceMapInfo } = + compilation.getPathWithInfo( + sourceMapFilename, + pathParams + ); + const sourceMapUrl = options.publicPath + ? options.publicPath + sourceMapFile + : relative( + outputFs, + dirname(outputFs, `/${file}`), + `/${sourceMapFile}` + ); + /** @type {Source} */ + let asset = new RawSource(source); + if (currentSourceMappingURLComment !== false) { + // Add source map url to compilation asset, if currentSourceMappingURLComment is set + asset = new ConcatSource( + asset, + compilation.getPath( + currentSourceMappingURLComment, + Object.assign({ url: sourceMapUrl }, pathParams) + ) + ); + } + const assetInfo = { + related: { sourceMap: sourceMapFile } + }; + assets[file] = asset; + assetsInfo[file] = assetInfo; + compilation.updateAsset(file, asset, assetInfo); + // Add source map file to compilation assets and chunk files + const sourceMapAsset = new RawSource(sourceMapString); + const sourceMapAssetInfo = { + ...sourceMapInfo, + development: true + }; + assets[sourceMapFile] = sourceMapAsset; + assetsInfo[sourceMapFile] = sourceMapAssetInfo; + compilation.emitAsset( + sourceMapFile, + sourceMapAsset, + sourceMapAssetInfo + ); + if (chunk !== undefined) + chunk.auxiliaryFiles.add(sourceMapFile); + } else { + if (currentSourceMappingURLComment === false) { + throw new Error( + "SourceMapDevToolPlugin: append can't be false when no filename is provided" + ); + } + /** + * Add source map as data url to asset + */ + const asset = new ConcatSource( + new RawSource(source), + currentSourceMappingURLComment + .replace(/\[map\]/g, () => sourceMapString) + .replace( + /\[url\]/g, + () => + `data:application/json;charset=utf-8;base64,${Buffer.from( + sourceMapString, + "utf-8" + ).toString("base64")}` + ) + ); + assets[file] = asset; + assetsInfo[file] = undefined; + compilation.updateAsset(file, asset); + } + + task.cacheItem.store({ assets, assetsInfo }, err => { + reportProgress( + 0.5 + (0.5 * ++taskIndex) / tasks.length, + task.file, + "attached SourceMap" + ); + + if (err) { + return callback(err); + } + callback(); + }); + }, + err => { + reportProgress(1.0); + callback(err); + } + ); + } + ); + } + ); + }); + } +} + +module.exports = SourceMapDevToolPlugin; /***/ }), -/***/ 52225: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 31743: +/***/ (function(module) { "use strict"; /* @@ -74308,145 +68184,88 @@ module.exports = CommonJsRequireDependency; -const RuntimeGlobals = __webpack_require__(16475); -const { equals } = __webpack_require__(84953); -const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const NullDependency = __webpack_require__(31830); +/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +class Stats { + /** + * @param {Compilation} compilation webpack compilation + */ + constructor(compilation) { + this.compilation = compilation; + } -class CommonJsSelfReferenceDependency extends NullDependency { - constructor(range, base, names, call) { - super(); - this.range = range; - this.base = base; - this.names = names; - this.call = call; + get hash() { + return this.compilation.hash; } - get type() { - return "cjs self exports reference"; + get startTime() { + return this.compilation.startTime; } - get category() { - return "self"; + get endTime() { + return this.compilation.endTime; } /** - * @returns {string | null} an identifier to merge equal requests + * @returns {boolean} true if the compilation had a warning */ - getResourceIdentifier() { - return `self`; + hasWarnings() { + return ( + this.compilation.warnings.length > 0 || + this.compilation.children.some(child => child.getStats().hasWarnings()) + ); } /** - * Returns list of exports referenced by this dependency - * @param {ModuleGraph} moduleGraph module graph - * @param {RuntimeSpec} runtime the runtime for which the module is analysed - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {boolean} true if the compilation encountered an error */ - getReferencedExports(moduleGraph, runtime) { - return [this.call ? this.names.slice(0, -1) : this.names]; - } - - serialize(context) { - const { write } = context; - write(this.range); - write(this.base); - write(this.names); - write(this.call); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.range = read(); - this.base = read(); - this.names = read(); - this.call = read(); - super.deserialize(context); + hasErrors() { + return ( + this.compilation.errors.length > 0 || + this.compilation.children.some(child => child.getStats().hasErrors()) + ); } -} -makeSerializable( - CommonJsSelfReferenceDependency, - "webpack/lib/dependencies/CommonJsSelfReferenceDependency" -); - -CommonJsSelfReferenceDependency.Template = class CommonJsSelfReferenceDependencyTemplate extends ( - NullDependency.Template -) { /** - * @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} + * @param {(string|StatsOptions)=} options stats options + * @returns {StatsCompilation} json output */ - apply( - dependency, - source, - { module, moduleGraph, runtime, runtimeRequirements } - ) { - const dep = /** @type {CommonJsSelfReferenceDependency} */ (dependency); - let used; - if (dep.names.length === 0) { - used = dep.names; - } else { - used = moduleGraph.getExportsInfo(module).getUsedName(dep.names, runtime); - } - if (!used) { - throw new Error( - "Self-reference dependency has unused export name: This should not happen" - ); - } + toJson(options) { + options = this.compilation.createStatsOptions(options, { + forToString: false + }); - let base = undefined; - switch (dep.base) { - case "exports": - runtimeRequirements.add(RuntimeGlobals.exports); - base = module.exportsArgument; - break; - case "module.exports": - runtimeRequirements.add(RuntimeGlobals.module); - base = `${module.moduleArgument}.exports`; - break; - case "this": - runtimeRequirements.add(RuntimeGlobals.thisAsExports); - base = "this"; - break; - default: - throw new Error(`Unsupported base ${dep.base}`); - } + const statsFactory = this.compilation.createStatsFactory(options); - if (base === dep.base && equals(used, dep.names)) { - // Nothing has to be changed - // We don't use a replacement for compat reasons - // for plugins that update `module._source` which they - // shouldn't do! - return; - } + return statsFactory.create("compilation", this.compilation, { + compilation: this.compilation + }); + } - source.replace( - dep.range[0], - dep.range[1] - 1, - `${base}${propertyAccess(used)}` - ); + toString(options) { + options = this.compilation.createStatsOptions(options, { + forToString: true + }); + + const statsFactory = this.compilation.createStatsFactory(options); + const statsPrinter = this.compilation.createStatsPrinter(options); + + const data = statsFactory.create("compilation", this.compilation, { + compilation: this.compilation + }); + const result = statsPrinter.print("compilation", data); + return result === undefined ? "" : result; } -}; +} -module.exports = CommonJsSelfReferenceDependency; +module.exports = Stats; /***/ }), -/***/ 76911: +/***/ 39722: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -74457,722 +68276,793 @@ module.exports = CommonJsSelfReferenceDependency; -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +const { ConcatSource, PrefixSource } = __webpack_require__(51255); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compilation").PathData} PathData */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("./RuntimeModule")} RuntimeModule */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -class ConstDependency extends NullDependency { +const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0); +const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0); +const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1; +const NUMBER_OF_IDENTIFIER_START_CHARS = DELTA_A_TO_Z * 2 + 2; // a-z A-Z _ $ +const NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS = + NUMBER_OF_IDENTIFIER_START_CHARS + 10; // a-z A-Z _ $ 0-9 +const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g; +const INDENT_MULTILINE_REGEX = /^\t/gm; +const LINE_SEPARATOR_REGEX = /\r?\n/g; +const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/; +const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g; +const COMMENT_END_REGEX = /\*\//g; +const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g; +const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; + +/** + * @typedef {Object} RenderManifestOptions + * @property {Chunk} chunk the chunk used to render + * @property {string} hash + * @property {string} fullHash + * @property {OutputOptions} outputOptions + * @property {CodeGenerationResults} codeGenerationResults + * @property {{javascript: ModuleTemplate}} moduleTemplates + * @property {DependencyTemplates} dependencyTemplates + * @property {RuntimeTemplate} runtimeTemplate + * @property {ModuleGraph} moduleGraph + * @property {ChunkGraph} chunkGraph + */ + +/** @typedef {RenderManifestEntryTemplated | RenderManifestEntryStatic} RenderManifestEntry */ + +/** + * @typedef {Object} RenderManifestEntryTemplated + * @property {function(): Source} render + * @property {string | function(PathData, AssetInfo=): string} filenameTemplate + * @property {PathData=} pathOptions + * @property {AssetInfo=} info + * @property {string} identifier + * @property {string=} hash + * @property {boolean=} auxiliary + */ + +/** + * @typedef {Object} RenderManifestEntryStatic + * @property {function(): Source} render + * @property {string} filename + * @property {AssetInfo} info + * @property {string} identifier + * @property {string=} hash + * @property {boolean=} auxiliary + */ + +/** + * @typedef {Object} HasId + * @property {number | string} id + */ + +/** + * @typedef {function(Module, number): boolean} ModuleFilterPredicate + */ + +class Template { /** - * @param {string} expression the expression - * @param {number|[number, number]} range the source range - * @param {string[]=} runtimeRequirements runtime requirements + * + * @param {Function} fn a runtime function (.runtime.js) "template" + * @returns {string} the updated and normalized function string */ - constructor(expression, range, runtimeRequirements) { - super(); - this.expression = expression; - this.range = range; - this.runtimeRequirements = runtimeRequirements - ? new Set(runtimeRequirements) - : null; - this._hashUpdate = undefined; + static getFunctionContent(fn) { + return fn + .toString() + .replace(FUNCTION_CONTENT_REGEX, "") + .replace(INDENT_MULTILINE_REGEX, "") + .replace(LINE_SEPARATOR_REGEX, "\n"); } /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context - * @returns {void} + * @param {string} str the string converted to identifier + * @returns {string} created identifier */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) { - let hashUpdate = "" + this.range + "|" + this.expression; - if (this.runtimeRequirements) { - for (const item of this.runtimeRequirements) { - hashUpdate += "|"; - hashUpdate += item; - } - } - this._hashUpdate = hashUpdate; - } - hash.update(this._hashUpdate); + static toIdentifier(str) { + if (typeof str !== "string") return ""; + return str + .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1") + .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_"); } - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules + * + * @param {string} str string to be converted to commented in bundle code + * @returns {string} returns a commented version of string */ - getModuleEvaluationSideEffectsState(moduleGraph) { - return false; + static toComment(str) { + if (!str) return ""; + return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`; } - serialize(context) { - const { write } = context; - write(this.expression); - write(this.range); - write(this.runtimeRequirements); - super.serialize(context); + /** + * + * @param {string} str string to be converted to "normal comment" + * @returns {string} returns a commented version of string + */ + static toNormalComment(str) { + if (!str) return ""; + return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`; } - deserialize(context) { - const { read } = context; - this.expression = read(); - this.range = read(); - this.runtimeRequirements = read(); - super.deserialize(context); + /** + * @param {string} str string path to be normalized + * @returns {string} normalized bundle-safe path + */ + static toPath(str) { + if (typeof str !== "string") return ""; + return str + .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-") + .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, ""); } -} -makeSerializable(ConstDependency, "webpack/lib/dependencies/ConstDependency"); - -ConstDependency.Template = class ConstDependencyTemplate extends ( - NullDependency.Template -) { + // map number to a single character a-z, A-Z or multiple characters if number is too big /** - * @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} + * @param {number} n number to convert to ident + * @returns {string} returns single character ident */ - apply(dependency, source, templateContext) { - const dep = /** @type {ConstDependency} */ (dependency); - if (dep.runtimeRequirements) { - for (const req of dep.runtimeRequirements) { - templateContext.runtimeRequirements.add(req); - } - } - if (typeof dep.range === "number") { - source.insert(dep.range, dep.expression); - return; + static numberToIdentifier(n) { + if (n >= NUMBER_OF_IDENTIFIER_START_CHARS) { + // use multiple letters + return ( + Template.numberToIdentifier(n % NUMBER_OF_IDENTIFIER_START_CHARS) + + Template.numberToIdentifierContinuation( + Math.floor(n / NUMBER_OF_IDENTIFIER_START_CHARS) + ) + ); } - source.replace(dep.range[0], dep.range[1] - 1, dep.expression); - } -}; - -module.exports = ConstDependency; - - -/***/ }), - -/***/ 88101: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Dependency = __webpack_require__(54912); -const DependencyTemplate = __webpack_require__(5160); -const makeSerializable = __webpack_require__(33032); -const memoize = __webpack_require__(78676); - -/** @typedef {import("../ContextModule").ContextOptions} ContextOptions */ -/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../WebpackError")} WebpackError */ - -const getCriticalDependencyWarning = memoize(() => - __webpack_require__(15427) -); + // lower case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); + } + n -= DELTA_A_TO_Z; -/** @typedef {ContextOptions & { request: string }} ContextDependencyOptions */ + // upper case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); + } -const regExpToString = r => (r ? r + "" : ""); + if (n === DELTA_A_TO_Z) return "_"; + return "$"; + } -class ContextDependency extends Dependency { /** - * @param {ContextDependencyOptions} options options for the context module + * @param {number} n number to convert to ident + * @returns {string} returns single character ident */ - constructor(options) { - super(); + static numberToIdentifierContinuation(n) { + if (n >= NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) { + // use multiple letters + return ( + Template.numberToIdentifierContinuation( + n % NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS + ) + + Template.numberToIdentifierContinuation( + Math.floor(n / NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) + ) + ); + } - this.options = options; - this.userRequest = this.options && this.options.request; - /** @type {false | string} */ - this.critical = false; - this.hadGlobalOrStickyRegExp = false; + // lower case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); + } + n -= DELTA_A_TO_Z; - if ( - this.options && - (this.options.regExp.global || this.options.regExp.sticky) - ) { - this.options = { ...this.options, regExp: null }; - this.hadGlobalOrStickyRegExp = true; + // upper case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); + } + n -= DELTA_A_TO_Z; + + // numbers + if (n < 10) { + return `${n}`; } - this.request = undefined; - this.range = undefined; - this.valueRange = undefined; - this.inShorthand = undefined; - // TODO refactor this - this.replaces = undefined; + if (n === 10) return "_"; + return "$"; } - get category() { - return "commonjs"; + /** + * + * @param {string | string[]} s string to convert to identity + * @returns {string} converted identity + */ + static indent(s) { + if (Array.isArray(s)) { + return s.map(Template.indent).join("\n"); + } else { + const str = s.trimRight(); + if (!str) return ""; + const ind = str[0] === "\n" ? "" : "\t"; + return ind + str.replace(/\n([^\n])/g, "\n\t$1"); + } } /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + * + * @param {string|string[]} s string to create prefix for + * @param {string} prefix prefix to compose + * @returns {string} returns new prefix string */ - couldAffectReferencingModule() { - return true; + static prefix(s, prefix) { + const str = Template.asString(s).trim(); + if (!str) return ""; + const ind = str[0] === "\n" ? "" : prefix; + return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); } /** - * @returns {string | null} an identifier to merge equal requests + * + * @param {string|string[]} str string or string collection + * @returns {string} returns a single string from array */ - getResourceIdentifier() { - return ( - `context${this.options.request} ${this.options.recursive} ` + - `${regExpToString(this.options.regExp)} ${regExpToString( - this.options.include - )} ${regExpToString(this.options.exclude)} ` + - `${this.options.mode} ${this.options.chunkName} ` + - `${JSON.stringify(this.options.groupOptions)}` - ); + static asString(str) { + if (Array.isArray(str)) { + return str.join("\n"); + } + return str; } /** - * Returns warnings - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} warnings + * @typedef {Object} WithId + * @property {string|number} id */ - getWarnings(moduleGraph) { - let warnings = super.getWarnings(moduleGraph); - if (this.critical) { - if (!warnings) warnings = []; - const CriticalDependencyWarning = getCriticalDependencyWarning(); - warnings.push(new CriticalDependencyWarning(this.critical)); + /** + * @param {WithId[]} modules a collection of modules to get array bounds for + * @returns {[number, number] | false} returns the upper and lower array bounds + * or false if not every module has a number based id + */ + static getModulesArrayBounds(modules) { + let maxId = -Infinity; + let minId = Infinity; + for (const module of modules) { + const moduleId = module.id; + if (typeof moduleId !== "number") return false; + if (maxId < moduleId) maxId = moduleId; + if (minId > moduleId) minId = moduleId; } - - if (this.hadGlobalOrStickyRegExp) { - if (!warnings) warnings = []; - const CriticalDependencyWarning = getCriticalDependencyWarning(); - warnings.push( - new CriticalDependencyWarning( - "Contexts can't use RegExps with the 'g' or 'y' flags." - ) - ); + if (minId < 16 + ("" + minId).length) { + // add minId x ',' instead of 'Array(minId).concat(…)' + minId = 0; } - - return warnings; + // start with -1 because the first module needs no comma + let objectOverhead = -1; + for (const module of modules) { + // module id + colon + comma + objectOverhead += `${module.id}`.length + 2; + } + // number of commas, or when starting non-zero the length of Array(minId).concat() + const arrayOverhead = minId === 0 ? maxId : 16 + `${minId}`.length + maxId; + return arrayOverhead < objectOverhead ? [minId, maxId] : false; } - serialize(context) { - const { write } = context; - - write(this.options); - write(this.userRequest); - write(this.critical); - write(this.hadGlobalOrStickyRegExp); - write(this.request); - write(this.range); - write(this.valueRange); - write(this.prepend); - write(this.replaces); - - super.serialize(context); + /** + * @param {ChunkRenderContext} renderContext render context + * @param {Module[]} modules modules to render (should be ordered by identifier) + * @param {function(Module): Source} renderModule function to render a module + * @param {string=} prefix applying prefix strings + * @returns {Source} rendered chunk modules in a Source object + */ + static renderChunkModules(renderContext, modules, renderModule, prefix = "") { + const { chunkGraph } = renderContext; + var source = new ConcatSource(); + if (modules.length === 0) { + return null; + } + /** @type {{id: string|number, source: Source|string}[]} */ + const allModules = modules.map(module => { + return { + id: chunkGraph.getModuleId(module), + source: renderModule(module) || "false" + }; + }); + const bounds = Template.getModulesArrayBounds(allModules); + if (bounds) { + // Render a spare array + const minId = bounds[0]; + const maxId = bounds[1]; + if (minId !== 0) { + source.add(`Array(${minId}).concat(`); + } + source.add("[\n"); + /** @type {Map} */ + const modules = new Map(); + for (const module of allModules) { + modules.set(module.id, module); + } + for (let idx = minId; idx <= maxId; idx++) { + const module = modules.get(idx); + if (idx !== minId) { + source.add(",\n"); + } + source.add(`/* ${idx} */`); + if (module) { + source.add("\n"); + source.add(module.source); + } + } + source.add("\n" + prefix + "]"); + if (minId !== 0) { + source.add(")"); + } + } else { + // Render an object + source.add("{\n"); + for (let i = 0; i < allModules.length; i++) { + const module = allModules[i]; + if (i !== 0) { + source.add(",\n"); + } + source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`); + source.add(module.source); + } + source.add(`\n\n${prefix}}`); + } + return source; } - deserialize(context) { - const { read } = context; - - this.options = read(); - this.userRequest = read(); - this.critical = read(); - this.hadGlobalOrStickyRegExp = read(); - this.request = read(); - this.range = read(); - this.valueRange = read(); - this.prepend = read(); - this.replaces = read(); + /** + * @param {RuntimeModule[]} runtimeModules array of runtime modules in order + * @param {RenderContext & { codeGenerationResults?: CodeGenerationResults }} renderContext render context + * @returns {Source} rendered runtime modules in a Source object + */ + static renderRuntimeModules(runtimeModules, renderContext) { + const source = new ConcatSource(); + for (const module of runtimeModules) { + const codeGenerationResults = renderContext.codeGenerationResults; + let runtimeSource; + if (codeGenerationResults) { + runtimeSource = codeGenerationResults.getSource( + module, + renderContext.chunk.runtime, + "runtime" + ); + } else { + const codeGenResult = module.codeGeneration({ + chunkGraph: renderContext.chunkGraph, + dependencyTemplates: renderContext.dependencyTemplates, + moduleGraph: renderContext.moduleGraph, + runtimeTemplate: renderContext.runtimeTemplate, + runtime: renderContext.chunk.runtime, + codeGenerationResults + }); + if (!codeGenResult) continue; + runtimeSource = codeGenResult.sources.get("runtime"); + } + if (runtimeSource) { + source.add(Template.toNormalComment(module.identifier()) + "\n"); + if (!module.shouldIsolate()) { + source.add(runtimeSource); + source.add("\n\n"); + } else if (renderContext.runtimeTemplate.supportsArrowFunction()) { + source.add("(() => {\n"); + source.add(new PrefixSource("\t", runtimeSource)); + source.add("\n})();\n\n"); + } else { + source.add("!function() {\n"); + source.add(new PrefixSource("\t", runtimeSource)); + source.add("\n}();\n\n"); + } + } + } + return source; + } - super.deserialize(context); + /** + * @param {RuntimeModule[]} runtimeModules array of runtime modules in order + * @param {RenderContext} renderContext render context + * @returns {Source} rendered chunk runtime modules in a Source object + */ + static renderChunkRuntimeModules(runtimeModules, renderContext) { + return new PrefixSource( + "/******/ ", + new ConcatSource( + "function(__webpack_require__) { // webpackRuntimeModules\n", + this.renderRuntimeModules(runtimeModules, renderContext), + "}\n" + ) + ); } } -makeSerializable( - ContextDependency, - "webpack/lib/dependencies/ContextDependency" -); - -ContextDependency.Template = DependencyTemplate; - -module.exports = ContextDependency; +module.exports = Template; +module.exports.NUMBER_OF_IDENTIFIER_START_CHARS = + NUMBER_OF_IDENTIFIER_START_CHARS; +module.exports.NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS = + NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS; /***/ }), -/***/ 99630: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 80734: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Jason Anderson @diurnalist */ +const { basename, extname } = __webpack_require__(71017); +const util = __webpack_require__(73837); +const Chunk = __webpack_require__(39385); +const Module = __webpack_require__(73208); const { parseResource } = __webpack_require__(82186); -/** @typedef {import("estree").Node} EsTreeNode */ -/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ -/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ -/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ -/** @typedef {import("./ContextDependency")} ContextDependency */ -/** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */ - -/** - * Escapes regular expression metacharacters - * @param {string} str String to quote - * @returns {string} Escaped string - */ -const quoteMeta = str => { - return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); -}; +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compilation").PathData} PathData */ +/** @typedef {import("./Compiler")} Compiler */ -const splitContextFromPrefix = prefix => { - const idx = prefix.lastIndexOf("/"); - let context = "."; - if (idx >= 0) { - context = prefix.substr(0, idx); - prefix = `.${prefix.substr(idx)}`; - } - return { - context, - prefix - }; -}; +const REGEXP = /\[\\*([\w:]+)\\*\]/gi; -/** @typedef {Partial>} PartialContextDependencyOptions */ +const prepareId = id => { + if (typeof id !== "string") return id; -/** @typedef {{ new(options: ContextDependencyOptions, range: [number, number], valueRange: [number, number]): ContextDependency }} ContextDependencyConstructor */ + if (/^"\s\+*.*\+\s*"$/.test(id)) { + const match = /^"\s\+*\s*(.*)\s*\+\s*"$/.exec(id); -/** - * @param {ContextDependencyConstructor} Dep the Dependency class - * @param {[number, number]} range source range - * @param {BasicEvaluatedExpression} param context param - * @param {EsTreeNode} expr expr - * @param {Pick} options options for context creation - * @param {PartialContextDependencyOptions} contextOptions options for the ContextModule - * @param {JavascriptParser} parser the parser - * @returns {ContextDependency} the created Dependency - */ -exports.create = (Dep, range, param, expr, options, contextOptions, parser) => { - if (param.isTemplateString()) { - let prefixRaw = param.quasis[0].string; - let postfixRaw = - param.quasis.length > 1 - ? param.quasis[param.quasis.length - 1].string - : ""; + return `" + (${match[1]} + "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_") + "`; + } - const valueRange = param.range; - const { context, prefix } = splitContextFromPrefix(prefixRaw); - const { - path: postfix, - query, - fragment - } = parseResource(postfixRaw, parser); + return id.replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_"); +}; - // When there are more than two quasis, the generated RegExp can be more precise - // We join the quasis with the expression regexp - const innerQuasis = param.quasis.slice(1, param.quasis.length - 1); - const innerRegExp = - options.wrappedContextRegExp.source + - innerQuasis - .map(q => quoteMeta(q.string) + options.wrappedContextRegExp.source) - .join(""); +const hashLength = (replacer, handler, assetInfo, hashName) => { + const fn = (match, arg, input) => { + let result; + const length = arg && parseInt(arg, 10); - // Example: `./context/pre${e}inner${e}inner2${e}post?query#frag` - // context: "./context" - // prefix: "./pre" - // innerQuasis: [BEE("inner"), BEE("inner2")] - // (BEE = BasicEvaluatedExpression) - // postfix: "post" - // query: "?query" - // fragment: "#frag" - // regExp: /^\.\/pre.*inner.*inner2.*post$/ - const regExp = new RegExp( - `^${quoteMeta(prefix)}${innerRegExp}${quoteMeta(postfix)}$` - ); - const dep = new Dep( - { - request: context + query + fragment, - recursive: options.wrappedContextRecursive, - regExp, - mode: "sync", - ...contextOptions - }, - range, - valueRange - ); - dep.loc = expr.loc; - const replaces = []; + if (length && handler) { + result = handler(length); + } else { + const hash = replacer(match, arg, input); - param.parts.forEach((part, i) => { - if (i % 2 === 0) { - // Quasis or merged quasi - let range = part.range; - let value = part.string; - if (param.templateStringKind === "cooked") { - value = JSON.stringify(value); - value = value.slice(1, value.length - 1); - } - if (i === 0) { - // prefix - value = prefix; - range = [param.range[0], part.range[1]]; - value = - (param.templateStringKind === "cooked" ? "`" : "String.raw`") + - value; - } else if (i === param.parts.length - 1) { - // postfix - value = postfix; - range = [part.range[0], param.range[1]]; - value = value + "`"; - } else if ( - part.expression && - part.expression.type === "TemplateElement" && - part.expression.value.raw === value - ) { - // Shortcut when it's a single quasi and doesn't need to be replaced - return; - } - replaces.push({ - range, - value - }); + result = length ? hash.slice(0, length) : hash; + } + if (assetInfo) { + assetInfo.immutable = true; + if (Array.isArray(assetInfo[hashName])) { + assetInfo[hashName] = [...assetInfo[hashName], result]; + } else if (assetInfo[hashName]) { + assetInfo[hashName] = [assetInfo[hashName], result]; } else { - // Expression - parser.walkExpression(part.expression); + assetInfo[hashName] = result; } - }); - - dep.replaces = replaces; - dep.critical = - options.wrappedContextCritical && - "a part of the request of a dependency is an expression"; - return dep; - } else if ( - param.isWrapped() && - ((param.prefix && param.prefix.isString()) || - (param.postfix && param.postfix.isString())) - ) { - let prefixRaw = - param.prefix && param.prefix.isString() ? param.prefix.string : ""; - let postfixRaw = - param.postfix && param.postfix.isString() ? param.postfix.string : ""; - const prefixRange = - param.prefix && param.prefix.isString() ? param.prefix.range : null; - const postfixRange = - param.postfix && param.postfix.isString() ? param.postfix.range : null; - const valueRange = param.range; - const { context, prefix } = splitContextFromPrefix(prefixRaw); - const { - path: postfix, - query, - fragment - } = parseResource(postfixRaw, parser); - const regExp = new RegExp( - `^${quoteMeta(prefix)}${options.wrappedContextRegExp.source}${quoteMeta( - postfix - )}$` - ); - const dep = new Dep( - { - request: context + query + fragment, - recursive: options.wrappedContextRecursive, - regExp, - mode: "sync", - ...contextOptions - }, - range, - valueRange - ); - dep.loc = expr.loc; - const replaces = []; - if (prefixRange) { - replaces.push({ - range: prefixRange, - value: JSON.stringify(prefix) - }); } - if (postfixRange) { - replaces.push({ - range: postfixRange, - value: JSON.stringify(postfix) - }); - } - dep.replaces = replaces; - dep.critical = - options.wrappedContextCritical && - "a part of the request of a dependency is an expression"; + return result; + }; - if (parser && param.wrappedInnerExpressions) { - for (const part of param.wrappedInnerExpressions) { - if (part.expression) parser.walkExpression(part.expression); - } + return fn; +}; + +const replacer = (value, allowEmpty) => { + const fn = (match, arg, input) => { + if (typeof value === "function") { + value = value(); } + if (value === null || value === undefined) { + if (!allowEmpty) { + throw new Error( + `Path variable ${match} not implemented in this context: ${input}` + ); + } - return dep; - } else { - const dep = new Dep( - { - request: options.exprContextRequest, - recursive: options.exprContextRecursive, - regExp: /** @type {RegExp} */ (options.exprContextRegExp), - mode: "sync", - ...contextOptions - }, - range, - param.range - ); - dep.loc = expr.loc; - dep.critical = - options.exprContextCritical && - "the request of a dependency is an expression"; + return ""; + } else { + return `${value}`; + } + }; - parser.walkExpression(param.expression); + return fn; +}; - return dep; +const deprecationCache = new Map(); +const deprecatedFunction = (() => () => {})(); +const deprecated = (fn, message, code) => { + let d = deprecationCache.get(message); + if (d === undefined) { + d = util.deprecate(deprecatedFunction, message, code); + deprecationCache.set(message, d); } + return (...args) => { + d(); + return fn(...args); + }; }; +/** + * @param {string | function(PathData, AssetInfo=): string} path the raw path + * @param {PathData} data context data + * @param {AssetInfo} assetInfo extra info about the asset (will be written to) + * @returns {string} the interpolated path + */ +const replacePathVariables = (path, data, assetInfo) => { + const chunkGraph = data.chunkGraph; -/***/ }), - -/***/ 76081: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** @type {Map} */ + const replacements = new Map(); + // Filename context + // + // Placeholders + // + // for /some/path/file.js?query#fragment: + // [file] - /some/path/file.js + // [query] - ?query + // [fragment] - #fragment + // [base] - file.js + // [path] - /some/path/ + // [name] - file + // [ext] - .js + if (typeof data.filename === "string") { + const { path: file, query, fragment } = parseResource(data.filename); + const ext = extname(file); + const base = basename(file); + const name = base.slice(0, base.length - ext.length); + const path = file.slice(0, file.length - base.length); -const ContextDependency = __webpack_require__(88101); + replacements.set("file", replacer(file)); + replacements.set("query", replacer(query, true)); + replacements.set("fragment", replacer(fragment, true)); + replacements.set("path", replacer(path, true)); + replacements.set("base", replacer(base)); + replacements.set("name", replacer(name)); + replacements.set("ext", replacer(ext, true)); + // Legacy + replacements.set( + "filebase", + deprecated( + replacer(base), + "[filebase] is now [base]", + "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME" + ) + ); + } -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + // Compilation context + // + // Placeholders + // + // [fullhash] - data.hash (3a4b5c6e7f) + // + // Legacy Placeholders + // + // [hash] - data.hash (3a4b5c6e7f) + if (data.hash) { + const hashReplacer = hashLength( + replacer(data.hash), + data.hashWithLength, + assetInfo, + "fullhash" + ); -class ContextDependencyTemplateAsId extends ContextDependency.Template { - /** - * @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, - { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {ContextDependency} */ (dependency); - const moduleExports = runtimeTemplate.moduleExports({ - module: moduleGraph.getModule(dep), - chunkGraph, - request: dep.request, - weak: dep.weak, - runtimeRequirements - }); + replacements.set("fullhash", hashReplacer); - if (moduleGraph.getModule(dep)) { - if (dep.valueRange) { - if (Array.isArray(dep.replaces)) { - for (let i = 0; i < dep.replaces.length; i++) { - const rep = dep.replaces[i]; - source.replace(rep.range[0], rep.range[1] - 1, rep.value); - } - } - source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); - source.replace( - dep.range[0], - dep.valueRange[0] - 1, - `${moduleExports}.resolve(` - ); - } else { - source.replace( - dep.range[0], - dep.range[1] - 1, - `${moduleExports}.resolve` - ); - } - } else { - source.replace(dep.range[0], dep.range[1] - 1, moduleExports); - } + // Legacy + replacements.set( + "hash", + deprecated( + hashReplacer, + "[hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)", + "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH" + ) + ); } -} -module.exports = ContextDependencyTemplateAsId; + // Chunk Context + // + // Placeholders + // + // [id] - chunk.id (0.js) + // [name] - chunk.name (app.js) + // [chunkhash] - chunk.hash (7823t4t4.js) + // [contenthash] - chunk.contentHash[type] (3256u3zg.js) + if (data.chunk) { + const chunk = data.chunk; -/***/ }), + const contentHashType = data.contentHashType; -/***/ 75815: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const idReplacer = replacer(chunk.id); + const nameReplacer = replacer(chunk.name || chunk.id); + const chunkhashReplacer = hashLength( + replacer(chunk instanceof Chunk ? chunk.renderedHash : chunk.hash), + "hashWithLength" in chunk ? chunk.hashWithLength : undefined, + assetInfo, + "chunkhash" + ); + const contenthashReplacer = hashLength( + replacer( + data.contentHash || + (contentHashType && + chunk.contentHash && + chunk.contentHash[contentHashType]) + ), + data.contentHashWithLength || + ("contentHashWithLength" in chunk && chunk.contentHashWithLength + ? chunk.contentHashWithLength[contentHashType] + : undefined), + assetInfo, + "contenthash" + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + replacements.set("id", idReplacer); + replacements.set("name", nameReplacer); + replacements.set("chunkhash", chunkhashReplacer); + replacements.set("contenthash", contenthashReplacer); + } + // Module Context + // + // Placeholders + // + // [id] - module.id (2.png) + // [hash] - module.hash (6237543873.png) + // + // Legacy Placeholders + // + // [moduleid] - module.id (2.png) + // [modulehash] - module.hash (6237543873.png) + if (data.module) { + const module = data.module; + const idReplacer = replacer(() => + prepareId( + module instanceof Module ? chunkGraph.getModuleId(module) : module.id + ) + ); + const moduleHashReplacer = hashLength( + replacer(() => + module instanceof Module + ? chunkGraph.getRenderedModuleHash(module, data.runtime) + : module.hash + ), + "hashWithLength" in module ? module.hashWithLength : undefined, + assetInfo, + "modulehash" + ); + const contentHashReplacer = hashLength( + replacer(data.contentHash), + undefined, + assetInfo, + "contenthash" + ); -const ContextDependency = __webpack_require__(88101); + replacements.set("id", idReplacer); + replacements.set("modulehash", moduleHashReplacer); + replacements.set("contenthash", contentHashReplacer); + replacements.set( + "hash", + data.contentHash ? contentHashReplacer : moduleHashReplacer + ); + // Legacy + replacements.set( + "moduleid", + deprecated( + idReplacer, + "[moduleid] is now [id]", + "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_MODULE_ID" + ) + ); + } -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + // Other things + if (data.url) { + replacements.set("url", replacer(data.url)); + } + if (typeof data.runtime === "string") { + replacements.set( + "runtime", + replacer(() => prepareId(data.runtime)) + ); + } else { + replacements.set("runtime", replacer("_")); + } -class ContextDependencyTemplateAsRequireCall extends ContextDependency.Template { + if (typeof path === "function") { + path = path(data, assetInfo); + } + + path = path.replace(REGEXP, (match, content) => { + if (content.length + 2 === match.length) { + const contentMatch = /^(\w+)(?::(\w+))?$/.exec(content); + if (!contentMatch) return match; + const [, kind, arg] = contentMatch; + const replacer = replacements.get(kind); + if (replacer !== undefined) { + return replacer(match, arg, path); + } + } else if (match.startsWith("[\\") && match.endsWith("\\]")) { + return `[${match.slice(2, -2)}]`; + } + return match; + }); + + return path; +}; + +const plugin = "TemplatedPathPlugin"; + +class TemplatedPathPlugin { /** - * @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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply( - dependency, - source, - { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {ContextDependency} */ (dependency); - let moduleExports = runtimeTemplate.moduleExports({ - module: moduleGraph.getModule(dep), - chunkGraph, - request: dep.request, - runtimeRequirements + apply(compiler) { + compiler.hooks.compilation.tap(plugin, compilation => { + compilation.hooks.assetPath.tap(plugin, replacePathVariables); }); - - if (dep.inShorthand) { - moduleExports = `${dep.inShorthand}: ${moduleExports}`; - } - if (moduleGraph.getModule(dep)) { - if (dep.valueRange) { - if (Array.isArray(dep.replaces)) { - for (let i = 0; i < dep.replaces.length; i++) { - const rep = dep.replaces[i]; - source.replace(rep.range[0], rep.range[1] - 1, rep.value); - } - } - source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); - source.replace( - dep.range[0], - dep.valueRange[0] - 1, - `${moduleExports}(` - ); - } else { - source.replace(dep.range[0], dep.range[1] - 1, moduleExports); - } - } else { - source.replace(dep.range[0], dep.range[1] - 1, moduleExports); - } } } -module.exports = ContextDependencyTemplateAsRequireCall; + +module.exports = TemplatedPathPlugin; /***/ }), -/***/ 58477: +/***/ 68099: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const Dependency = __webpack_require__(54912); +const WebpackError = __webpack_require__(53799); const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); - -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -class ContextElementDependency extends ModuleDependency { - constructor(request, userRequest, typePrefix, category, referencedExports) { - super(request); - this.referencedExports = referencedExports; - this._typePrefix = typePrefix; - this._category = category; - - if (userRequest) { - this.userRequest = userRequest; - } - } - - get type() { - if (this._typePrefix) { - return `${this._typePrefix} context element`; - } - - return "context element"; - } - - get category() { - return this._category; - } +class UnhandledSchemeError extends WebpackError { /** - * 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 + * @param {string} scheme scheme + * @param {string} resource resource */ - getReferencedExports(moduleGraph, runtime) { - return this.referencedExports - ? this.referencedExports.map(e => ({ - name: e, - canMangle: false - })) - : Dependency.EXPORTS_OBJECT_REFERENCED; - } - - serialize(context) { - context.write(this.referencedExports); - super.serialize(context); - } - - deserialize(context) { - this.referencedExports = context.read(); - super.deserialize(context); + constructor(scheme, resource) { + super( + `Reading from "${resource}" is not handled by plugins (Unhandled scheme).` + + '\nWebpack supports "data:" and "file:" URIs by default.' + + `\nYou may need an additional plugin to handle "${scheme}:" URIs.` + ); + this.file = resource; + this.name = "UnhandledSchemeError"; } } makeSerializable( - ContextElementDependency, - "webpack/lib/dependencies/ContextElementDependency" + UnhandledSchemeError, + "webpack/lib/UnhandledSchemeError", + "UnhandledSchemeError" ); -module.exports = ContextElementDependency; +module.exports = UnhandledSchemeError; /***/ }), -/***/ 79062: +/***/ 42495: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -75183,70 +69073,36 @@ module.exports = ContextElementDependency; -const RuntimeGlobals = __webpack_require__(16475); +const WebpackError = __webpack_require__(53799); const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -class CreateScriptUrlDependency extends NullDependency { +class UnsupportedFeatureWarning extends WebpackError { /** - * @param {[number, number]} range range + * @param {string} message description of warning + * @param {DependencyLocation} loc location start and end positions of the module */ - constructor(range) { - super(); - this.range = range; - } - - get type() { - return "create script url"; - } - - serialize(context) { - const { write } = context; - write(this.range); - super.serialize(context); - } + constructor(message, loc) { + super(message); - deserialize(context) { - const { read } = context; - this.range = read(); - super.deserialize(context); + this.name = "UnsupportedFeatureWarning"; + this.loc = loc; + this.hideStack = true; } } -CreateScriptUrlDependency.Template = class CreateScriptUrlDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, { runtimeRequirements }) { - const dep = /** @type {CreateScriptUrlDependency} */ (dependency); - - runtimeRequirements.add(RuntimeGlobals.createScriptUrl); - - source.insert(dep.range[0], `${RuntimeGlobals.createScriptUrl}(`); - source.insert(dep.range[1], ")"); - } -}; - makeSerializable( - CreateScriptUrlDependency, - "webpack/lib/dependencies/CreateScriptUrlDependency" + UnsupportedFeatureWarning, + "webpack/lib/UnsupportedFeatureWarning" ); -module.exports = CreateScriptUrlDependency; +module.exports = UnsupportedFeatureWarning; /***/ }), -/***/ 15427: +/***/ 36803: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -75257,1076 +69113,1005 @@ module.exports = CreateScriptUrlDependency; -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); +const ConstDependency = __webpack_require__(76911); -class CriticalDependencyWarning extends WebpackError { - constructor(message) { - super(); +/** @typedef {import("./Compiler")} Compiler */ - this.name = "CriticalDependencyWarning"; - this.message = "Critical dependency: " + message; +class UseStrictPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "UseStrictPlugin", + (compilation, { normalModuleFactory }) => { + const handler = parser => { + parser.hooks.program.tap("UseStrictPlugin", ast => { + const firstNode = ast.body[0]; + if ( + firstNode && + firstNode.type === "ExpressionStatement" && + firstNode.expression.type === "Literal" && + firstNode.expression.value === "use strict" + ) { + // Remove "use strict" expression. It will be added later by the renderer again. + // This is necessary in order to not break the strict mode when webpack prepends code. + // @see https://github.com/webpack/webpack/issues/1970 + const dep = new ConstDependency("", firstNode.range); + dep.loc = firstNode.loc; + parser.state.module.addPresentationalDependency(dep); + parser.state.module.buildInfo.strict = true; + } + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("UseStrictPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("UseStrictPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("UseStrictPlugin", handler); + } + ); } } -makeSerializable( - CriticalDependencyWarning, - "webpack/lib/dependencies/CriticalDependencyWarning" -); - -module.exports = CriticalDependencyWarning; +module.exports = UseStrictPlugin; /***/ }), -/***/ 76760: +/***/ 56504: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ - -class CssExportDependency extends NullDependency { - /** - * @param {string} name name - * @param {string} value value - */ - constructor(name, value) { - super(); - this.name = name; - this.value = value; - } - - get type() { - return "css :export"; - } - - /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names - */ - getExports(moduleGraph) { - const name = this.name; - return { - exports: [ - { - name, - canMangle: true - } - ], - dependencies: undefined - }; - } - - serialize(context) { - const { write } = context; - write(this.name); - write(this.value); - super.serialize(context); - } +const CaseSensitiveModulesWarning = __webpack_require__(77975); - deserialize(context) { - const { read } = context; - this.name = read(); - this.value = read(); - super.deserialize(context); - } -} +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ -CssExportDependency.Template = class CssExportDependencyTemplate extends ( - NullDependency.Template -) { +class WarnCaseSensitiveModulesPlugin { /** - * @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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply(dependency, source, { cssExports }) { - const dep = /** @type {CssExportDependency} */ (dependency); - cssExports.set(dep.name, dep.value); + apply(compiler) { + compiler.hooks.compilation.tap( + "WarnCaseSensitiveModulesPlugin", + compilation => { + compilation.hooks.seal.tap("WarnCaseSensitiveModulesPlugin", () => { + /** @type {Map>} */ + const moduleWithoutCase = new Map(); + for (const module of compilation.modules) { + const identifier = module.identifier(); + const lowerIdentifier = identifier.toLowerCase(); + let map = moduleWithoutCase.get(lowerIdentifier); + if (map === undefined) { + map = new Map(); + moduleWithoutCase.set(lowerIdentifier, map); + } + map.set(identifier, module); + } + for (const pair of moduleWithoutCase) { + const map = pair[1]; + if (map.size > 1) { + compilation.warnings.push( + new CaseSensitiveModulesWarning( + map.values(), + compilation.moduleGraph + ) + ); + } + } + }); + } + ); } -}; - -makeSerializable( - CssExportDependency, - "webpack/lib/dependencies/CssExportDependency" -); +} -module.exports = CssExportDependency; +module.exports = WarnCaseSensitiveModulesPlugin; /***/ }), -/***/ 90542: +/***/ 76537: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Florent Cailhol @ooflorent */ -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); +const WebpackError = __webpack_require__(53799); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./Compiler")} Compiler */ -class CssImportDependency extends ModuleDependency { +class WarnDeprecatedOptionPlugin { /** - * @param {string} request request - * @param {[number, number]} range range of the argument - * @param {string | undefined} supports list of supports conditions - * @param {string | undefined} media list of media conditions + * Create an instance of the plugin + * @param {string} option the target option + * @param {string | number} value the deprecated option value + * @param {string} suggestion the suggestion replacement */ - constructor(request, range, supports, media) { - super(request); - this.range = range; - this.supports = supports; - this.media = media; - } - - get type() { - return "css @import"; - } - - get category() { - return "css-import"; + constructor(option, value, suggestion) { + this.option = option; + this.value = value; + this.suggestion = suggestion; } /** - * @param {string} context context directory - * @returns {Module} a module + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - createIgnoredModule(context) { - return null; + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "WarnDeprecatedOptionPlugin", + compilation => { + compilation.warnings.push( + new DeprecatedOptionWarning(this.option, this.value, this.suggestion) + ); + } + ); } } -CssImportDependency.Template = class CssImportDependencyTemplate extends ( - ModuleDependency.Template -) { - /** - * @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 dep = /** @type {CssImportDependency} */ (dependency); +class DeprecatedOptionWarning extends WebpackError { + constructor(option, value, suggestion) { + super(); - source.replace(dep.range[0], dep.range[1] - 1, ""); + this.name = "DeprecatedOptionWarning"; + this.message = + "configuration\n" + + `The value '${value}' for option '${option}' is deprecated. ` + + `Use '${suggestion}' instead.`; } -}; - -makeSerializable( - CssImportDependency, - "webpack/lib/dependencies/CssImportDependency" -); +} -module.exports = CssImportDependency; +module.exports = WarnDeprecatedOptionPlugin; /***/ }), -/***/ 92328: +/***/ 25295: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ - -class CssLocalIdentifierDependency extends NullDependency { - /** - * @param {string} name name - * @param {[number, number]} range range - * @param {string=} prefix prefix - */ - constructor(name, range, prefix = "") { - super(); - this.name = name; - this.range = range; - this.prefix = prefix; - } - - get type() { - return "css local identifier"; - } - - /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names - */ - getExports(moduleGraph) { - const name = this.name; - return { - exports: [ - { - name, - canMangle: true - } - ], - dependencies: undefined - }; - } - - serialize(context) { - const { write } = context; - write(this.name); - write(this.range); - write(this.prefix); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.name = read(); - this.range = read(); - this.prefix = read(); - super.deserialize(context); - } -} +const NoModeWarning = __webpack_require__(80832); -const escapeCssIdentifier = (str, omitUnderscore) => { - const escaped = `${str}`.replace( - // cspell:word uffff - /[^a-zA-Z0-9_\u0081-\uffff-]/g, - s => `\\${s}` - ); - return !omitUnderscore && /^(?!--)[0-9-]/.test(escaped) - ? `_${escaped}` - : escaped; -}; +/** @typedef {import("./Compiler")} Compiler */ -CssLocalIdentifierDependency.Template = class CssLocalIdentifierDependencyTemplate extends ( - NullDependency.Template -) { +class WarnNoModeSetPlugin { /** - * @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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply( - dependency, - source, - { module, moduleGraph, chunkGraph, runtime, runtimeTemplate, cssExports } - ) { - const dep = /** @type {CssLocalIdentifierDependency} */ (dependency); - const used = moduleGraph - .getExportInfo(module, dep.name) - .getUsedName(dep.name, runtime); - const moduleId = chunkGraph.getModuleId(module); - const identifier = - dep.prefix + - (runtimeTemplate.outputOptions.uniqueName - ? runtimeTemplate.outputOptions.uniqueName + "-" - : "") + - (used ? moduleId + "-" + used : "-"); - source.replace( - dep.range[0], - dep.range[1] - 1, - escapeCssIdentifier(identifier, dep.prefix) - ); - if (used) cssExports.set(used, identifier); + apply(compiler) { + compiler.hooks.thisCompilation.tap("WarnNoModeSetPlugin", compilation => { + compilation.warnings.push(new NoModeWarning()); + }); } -}; - -makeSerializable( - CssLocalIdentifierDependency, - "webpack/lib/dependencies/CssLocalIdentifierDependency" -); +} -module.exports = CssLocalIdentifierDependency; +module.exports = WarnNoModeSetPlugin; /***/ }), -/***/ 29094: +/***/ 65193: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const Dependency = __webpack_require__(54912); -const makeSerializable = __webpack_require__(33032); -const CssLocalIdentifierDependency = __webpack_require__(92328); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +const { groupBy } = __webpack_require__(84953); +const createSchemaValidation = __webpack_require__(32540); -class CssSelfLocalIdentifierDependency extends CssLocalIdentifierDependency { - /** - * @param {string} name name - * @param {[number, number]} range range - * @param {string=} prefix prefix - * @param {Set=} declaredSet set of declared names (will only be active when in declared set) - */ - constructor(name, range, prefix = "", declaredSet = undefined) { - super(name, range, prefix); - this.declaredSet = declaredSet; - } +/** @typedef {import("../declarations/plugins/WatchIgnorePlugin").WatchIgnorePluginOptions} WatchIgnorePluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */ - get type() { - return "css self local identifier"; +const validate = createSchemaValidation( + __webpack_require__(16711), + () => __webpack_require__(44246), + { + name: "Watch Ignore Plugin", + baseDataPath: "options" } +); - get category() { - return "self"; - } +const IGNORE_TIME_ENTRY = "ignore"; +class IgnoringWatchFileSystem { /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - return `self`; - } - /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names + * @param {WatchFileSystem} wfs original file system + * @param {(string|RegExp)[]} paths ignored paths */ - getExports(moduleGraph) { - if (this.declaredSet && !this.declaredSet.has(this.name)) return; - return super.getExports(moduleGraph); + constructor(wfs, paths) { + this.wfs = wfs; + this.paths = paths; } - /** - * 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) { - if (this.declaredSet && !this.declaredSet.has(this.name)) - return Dependency.NO_EXPORTS_REFERENCED; - return [[this.name]]; - } + watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { + files = Array.from(files); + dirs = Array.from(dirs); + const ignored = path => + this.paths.some(p => + p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0 + ); - serialize(context) { - const { write } = context; - write(this.declaredSet); - super.serialize(context); - } + const [ignoredFiles, notIgnoredFiles] = groupBy(files, ignored); + const [ignoredDirs, notIgnoredDirs] = groupBy(dirs, ignored); - deserialize(context) { - const { read } = context; - this.declaredSet = read(); - super.deserialize(context); + const watcher = this.wfs.watch( + notIgnoredFiles, + notIgnoredDirs, + missing, + startTime, + options, + (err, fileTimestamps, dirTimestamps, changedFiles, removedFiles) => { + if (err) return callback(err); + for (const path of ignoredFiles) { + fileTimestamps.set(path, IGNORE_TIME_ENTRY); + } + + for (const path of ignoredDirs) { + dirTimestamps.set(path, IGNORE_TIME_ENTRY); + } + + callback( + err, + fileTimestamps, + dirTimestamps, + changedFiles, + removedFiles + ); + }, + callbackUndelayed + ); + + return { + close: () => watcher.close(), + pause: () => watcher.pause(), + getContextTimeInfoEntries: () => { + const dirTimestamps = watcher.getContextTimeInfoEntries(); + for (const path of ignoredDirs) { + dirTimestamps.set(path, IGNORE_TIME_ENTRY); + } + return dirTimestamps; + }, + getFileTimeInfoEntries: () => { + const fileTimestamps = watcher.getFileTimeInfoEntries(); + for (const path of ignoredFiles) { + fileTimestamps.set(path, IGNORE_TIME_ENTRY); + } + return fileTimestamps; + }, + getInfo: + watcher.getInfo && + (() => { + const info = watcher.getInfo(); + const { fileTimeInfoEntries, contextTimeInfoEntries } = info; + for (const path of ignoredFiles) { + fileTimeInfoEntries.set(path, IGNORE_TIME_ENTRY); + } + for (const path of ignoredDirs) { + contextTimeInfoEntries.set(path, IGNORE_TIME_ENTRY); + } + return info; + }) + }; } } -CssSelfLocalIdentifierDependency.Template = class CssSelfLocalIdentifierDependencyTemplate extends ( - CssLocalIdentifierDependency.Template -) { +class WatchIgnorePlugin { /** - * @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} + * @param {WatchIgnorePluginOptions} options options */ - apply(dependency, source, templateContext) { - const dep = /** @type {CssSelfLocalIdentifierDependency} */ (dependency); - if (dep.declaredSet && !dep.declaredSet.has(dep.name)) return; - super.apply(dependency, source, templateContext); + constructor(options) { + validate(options); + this.paths = options.paths; } -}; -makeSerializable( - CssSelfLocalIdentifierDependency, - "webpack/lib/dependencies/CssSelfLocalIdentifierDependency" -); + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.afterEnvironment.tap("WatchIgnorePlugin", () => { + compiler.watchFileSystem = new IgnoringWatchFileSystem( + compiler.watchFileSystem, + this.paths + ); + }); + } +} -module.exports = CssSelfLocalIdentifierDependency; +module.exports = WatchIgnorePlugin; /***/ }), -/***/ 70749: +/***/ 84275: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const makeSerializable = __webpack_require__(33032); -const memoize = __webpack_require__(78676); -const ModuleDependency = __webpack_require__(80321); +const Stats = __webpack_require__(31743); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ -const getRawDataUrlModule = memoize(() => __webpack_require__(19684)); +/** + * @template T + * @callback Callback + * @param {(Error | null)=} err + * @param {T=} result + */ -class CssUrlDependency extends ModuleDependency { +class Watching { /** - * @param {string} request request - * @param {[number, number]} range range of the argument - * @param {string} cssFunctionKind kind of css function, e. g. url(), image() + * @param {Compiler} compiler the compiler + * @param {WatchOptions} watchOptions options + * @param {Callback} handler completion handler */ - constructor(request, range, cssFunctionKind) { - super(request); - this.range = range; - this.cssFunctionKind = cssFunctionKind; - } - - get type() { - return "css url()"; - } - - get category() { - return "url"; + constructor(compiler, watchOptions, handler) { + this.startTime = null; + this.invalid = false; + this.handler = handler; + /** @type {Callback[]} */ + this.callbacks = []; + /** @type {Callback[] | undefined} */ + this._closeCallbacks = undefined; + this.closed = false; + this.suspended = false; + this.blocked = false; + this._isBlocked = () => false; + this._onChange = () => {}; + this._onInvalid = () => {}; + if (typeof watchOptions === "number") { + this.watchOptions = { + aggregateTimeout: watchOptions + }; + } else if (watchOptions && typeof watchOptions === "object") { + this.watchOptions = { ...watchOptions }; + } else { + this.watchOptions = {}; + } + if (typeof this.watchOptions.aggregateTimeout !== "number") { + this.watchOptions.aggregateTimeout = 20; + } + this.compiler = compiler; + this.running = false; + this._initial = true; + this._invalidReported = true; + this._needRecords = true; + this.watcher = undefined; + this.pausedWatcher = undefined; + /** @type {Set} */ + this._collectedChangedFiles = undefined; + /** @type {Set} */ + this._collectedRemovedFiles = undefined; + this._done = this._done.bind(this); + process.nextTick(() => { + if (this._initial) this._invalidate(); + }); } /** - * @param {string} context context directory - * @returns {Module} a module + * @param {ReadonlySet} changedFiles changed files + * @param {ReadonlySet} removedFiles removed files */ - createIgnoredModule(context) { - const RawDataUrlModule = getRawDataUrlModule(); - return new RawDataUrlModule("data:,", `ignored-asset`, `(ignored asset)`); - } - - serialize(context) { - const { write } = context; - write(this.cssFunctionKind); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.cssFunctionKind = read(); - super.deserialize(context); - } -} - -const cssEscapeString = str => { - let countWhiteOrBracket = 0; - let countQuotation = 0; - let countApostrophe = 0; - for (let i = 0; i < str.length; i++) { - const cc = str.charCodeAt(i); - switch (cc) { - case 9: // tab - case 10: // nl - case 32: // space - case 40: // ( - case 41: // ) - countWhiteOrBracket++; - break; - case 34: - countQuotation++; - break; - case 39: - countApostrophe++; - break; + _mergeWithCollected(changedFiles, removedFiles) { + if (!changedFiles) return; + if (!this._collectedChangedFiles) { + this._collectedChangedFiles = new Set(changedFiles); + this._collectedRemovedFiles = new Set(removedFiles); + } else { + for (const file of changedFiles) { + this._collectedChangedFiles.add(file); + this._collectedRemovedFiles.delete(file); + } + for (const file of removedFiles) { + this._collectedChangedFiles.delete(file); + this._collectedRemovedFiles.add(file); + } } } - if (countWhiteOrBracket < 2) { - return str.replace(/[\n\t ()'"\\]/g, m => `\\${m}`); - } else if (countQuotation <= countApostrophe) { - return `"${str.replace(/[\n"\\]/g, m => `\\${m}`)}"`; - } else { - return `'${str.replace(/[\n'\\]/g, m => `\\${m}`)}'`; - } -}; -CssUrlDependency.Template = class CssUrlDependencyTemplate extends ( - ModuleDependency.Template -) { /** - * @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 + * @param {ReadonlyMap=} fileTimeInfoEntries info for files + * @param {ReadonlyMap=} contextTimeInfoEntries info for directories + * @param {ReadonlySet=} changedFiles changed files + * @param {ReadonlySet=} removedFiles removed files * @returns {void} */ - apply( - dependency, - source, - { runtime, moduleGraph, runtimeTemplate, codeGenerationResults } - ) { - const dep = /** @type {CssUrlDependency} */ (dependency); - - source.replace( - dep.range[0], - dep.range[1] - 1, - `${dep.cssFunctionKind}(${cssEscapeString( - runtimeTemplate.assetUrl({ - publicPath: "", - runtime, - module: moduleGraph.getModule(dep), - codeGenerationResults - }) - )})` - ); - } -}; - -makeSerializable(CssUrlDependency, "webpack/lib/dependencies/CssUrlDependency"); - -module.exports = CssUrlDependency; - - -/***/ }), - -/***/ 22914: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + _go(fileTimeInfoEntries, contextTimeInfoEntries, changedFiles, removedFiles) { + this._initial = false; + if (this.startTime === null) this.startTime = Date.now(); + this.running = true; + if (this.watcher) { + this.pausedWatcher = this.watcher; + this.lastWatcherStartTime = Date.now(); + this.watcher.pause(); + this.watcher = null; + } else if (!this.lastWatcherStartTime) { + this.lastWatcherStartTime = Date.now(); + } + this.compiler.fsStartTime = Date.now(); + if ( + changedFiles && + removedFiles && + fileTimeInfoEntries && + contextTimeInfoEntries + ) { + this._mergeWithCollected(changedFiles, removedFiles); + this.compiler.fileTimestamps = fileTimeInfoEntries; + this.compiler.contextTimestamps = contextTimeInfoEntries; + } else if (this.pausedWatcher) { + if (this.pausedWatcher.getInfo) { + const { + changes, + removals, + fileTimeInfoEntries, + contextTimeInfoEntries + } = this.pausedWatcher.getInfo(); + this._mergeWithCollected(changes, removals); + this.compiler.fileTimestamps = fileTimeInfoEntries; + this.compiler.contextTimestamps = contextTimeInfoEntries; + } else { + this._mergeWithCollected( + this.pausedWatcher.getAggregatedChanges && + this.pausedWatcher.getAggregatedChanges(), + this.pausedWatcher.getAggregatedRemovals && + this.pausedWatcher.getAggregatedRemovals() + ); + this.compiler.fileTimestamps = + this.pausedWatcher.getFileTimeInfoEntries(); + this.compiler.contextTimestamps = + this.pausedWatcher.getContextTimeInfoEntries(); + } + } + this.compiler.modifiedFiles = this._collectedChangedFiles; + this._collectedChangedFiles = undefined; + this.compiler.removedFiles = this._collectedRemovedFiles; + this._collectedRemovedFiles = undefined; + const run = () => { + if (this.compiler.idle) { + return this.compiler.cache.endIdle(err => { + if (err) return this._done(err); + this.compiler.idle = false; + run(); + }); + } + if (this._needRecords) { + return this.compiler.readRecords(err => { + if (err) return this._done(err); + this._needRecords = false; + run(); + }); + } + this.invalid = false; + this._invalidReported = false; + this.compiler.hooks.watchRun.callAsync(this.compiler, err => { + if (err) return this._done(err); + const onCompiled = (err, compilation) => { + if (err) return this._done(err, compilation); + if (this.invalid) return this._done(null, compilation); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); + if (this.compiler.hooks.shouldEmit.call(compilation) === false) { + return this._done(null, compilation); + } -class DelegatedSourceDependency extends ModuleDependency { - constructor(request) { - super(request); - } + process.nextTick(() => { + const logger = compilation.getLogger("webpack.Compiler"); + logger.time("emitAssets"); + this.compiler.emitAssets(compilation, err => { + logger.timeEnd("emitAssets"); + if (err) return this._done(err, compilation); + if (this.invalid) return this._done(null, compilation); - get type() { - return "delegated source"; - } + logger.time("emitRecords"); + this.compiler.emitRecords(err => { + logger.timeEnd("emitRecords"); + if (err) return this._done(err, compilation); - get category() { - return "esm"; - } -} + if (compilation.hooks.needAdditionalPass.call()) { + compilation.needAdditionalPass = true; -makeSerializable( - DelegatedSourceDependency, - "webpack/lib/dependencies/DelegatedSourceDependency" -); + compilation.startTime = this.startTime; + compilation.endTime = Date.now(); + logger.time("done hook"); + const stats = new Stats(compilation); + this.compiler.hooks.done.callAsync(stats, err => { + logger.timeEnd("done hook"); + if (err) return this._done(err, compilation); -module.exports = DelegatedSourceDependency; + this.compiler.hooks.additionalPass.callAsync(err => { + if (err) return this._done(err, compilation); + this.compiler.compile(onCompiled); + }); + }); + return; + } + return this._done(null, compilation); + }); + }); + }); + }; + this.compiler.compile(onCompiled); + }); + }; + run(); + } -/***/ }), + /** + * @param {Compilation} compilation the compilation + * @returns {Stats} the compilation stats + */ + _getStats(compilation) { + const stats = new Stats(compilation); + return stats; + } -/***/ 95666: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {Error=} err an optional error + * @param {Compilation=} compilation the compilation + * @returns {void} + */ + _done(err, compilation) { + this.running = false; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const logger = compilation && compilation.getLogger("webpack.Watching"); + let stats = null; + const handleError = (err, cbs) => { + this.compiler.hooks.failed.call(err); + this.compiler.cache.beginIdle(); + this.compiler.idle = true; + this.handler(err, stats); + if (!cbs) { + cbs = this.callbacks; + this.callbacks = []; + } + for (const cb of cbs) cb(err); + }; -const Dependency = __webpack_require__(54912); -const makeSerializable = __webpack_require__(33032); + if ( + this.invalid && + !this.suspended && + !this.blocked && + !(this._isBlocked() && (this.blocked = true)) + ) { + if (compilation) { + logger.time("storeBuildDependencies"); + this.compiler.cache.storeBuildDependencies( + compilation.buildDependencies, + err => { + logger.timeEnd("storeBuildDependencies"); + if (err) return handleError(err); + this._go(); + } + ); + } else { + this._go(); + } + return; + } -class DllEntryDependency extends Dependency { - constructor(dependencies, name) { - super(); + if (compilation) { + compilation.startTime = this.startTime; + compilation.endTime = Date.now(); + stats = new Stats(compilation); + } + this.startTime = null; + if (err) return handleError(err); - this.dependencies = dependencies; - this.name = name; + const cbs = this.callbacks; + this.callbacks = []; + logger.time("done hook"); + this.compiler.hooks.done.callAsync(stats, err => { + logger.timeEnd("done hook"); + if (err) return handleError(err, cbs); + this.handler(null, stats); + logger.time("storeBuildDependencies"); + this.compiler.cache.storeBuildDependencies( + compilation.buildDependencies, + err => { + logger.timeEnd("storeBuildDependencies"); + if (err) return handleError(err, cbs); + logger.time("beginIdle"); + this.compiler.cache.beginIdle(); + this.compiler.idle = true; + logger.timeEnd("beginIdle"); + process.nextTick(() => { + if (!this.closed) { + this.watch( + compilation.fileDependencies, + compilation.contextDependencies, + compilation.missingDependencies + ); + } + }); + for (const cb of cbs) cb(null); + this.compiler.hooks.afterDone.call(stats); + } + ); + }); } - get type() { - return "dll entry"; + /** + * @param {Iterable} files watched files + * @param {Iterable} dirs watched directories + * @param {Iterable} missing watched existence entries + * @returns {void} + */ + watch(files, dirs, missing) { + this.pausedWatcher = null; + this.watcher = this.compiler.watchFileSystem.watch( + files, + dirs, + missing, + this.lastWatcherStartTime, + this.watchOptions, + ( + err, + fileTimeInfoEntries, + contextTimeInfoEntries, + changedFiles, + removedFiles + ) => { + if (err) { + this.compiler.modifiedFiles = undefined; + this.compiler.removedFiles = undefined; + this.compiler.fileTimestamps = undefined; + this.compiler.contextTimestamps = undefined; + this.compiler.fsStartTime = undefined; + return this.handler(err); + } + this._invalidate( + fileTimeInfoEntries, + contextTimeInfoEntries, + changedFiles, + removedFiles + ); + this._onChange(); + }, + (fileName, changeTime) => { + if (!this._invalidReported) { + this._invalidReported = true; + this.compiler.hooks.invalid.call(fileName, changeTime); + } + this._onInvalid(); + } + ); } - serialize(context) { - const { write } = context; - - write(this.dependencies); - write(this.name); - - super.serialize(context); + /** + * @param {Callback=} callback signals when the build has completed again + * @returns {void} + */ + invalidate(callback) { + if (callback) { + this.callbacks.push(callback); + } + if (!this._invalidReported) { + this._invalidReported = true; + this.compiler.hooks.invalid.call(null, Date.now()); + } + this._onChange(); + this._invalidate(); } - deserialize(context) { - const { read } = context; - - this.dependencies = read(); - this.name = read(); + _invalidate( + fileTimeInfoEntries, + contextTimeInfoEntries, + changedFiles, + removedFiles + ) { + if (this.suspended || (this._isBlocked() && (this.blocked = true))) { + this._mergeWithCollected(changedFiles, removedFiles); + return; + } - super.deserialize(context); + if (this.running) { + this._mergeWithCollected(changedFiles, removedFiles); + this.invalid = true; + } else { + this._go( + fileTimeInfoEntries, + contextTimeInfoEntries, + changedFiles, + removedFiles + ); + } } -} - -makeSerializable( - DllEntryDependency, - "webpack/lib/dependencies/DllEntryDependency" -); - -module.exports = DllEntryDependency; - - -/***/ }), - -/***/ 32006: -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @type {WeakMap} */ -const parserStateExportsState = new WeakMap(); - -/** - * @param {ParserState} parserState parser state - * @returns {void} - */ -exports.bailout = parserState => { - const value = parserStateExportsState.get(parserState); - parserStateExportsState.set(parserState, false); - if (value === true) { - parserState.module.buildMeta.exportsType = undefined; - parserState.module.buildMeta.defaultObject = false; + suspend() { + this.suspended = true; } -}; -/** - * @param {ParserState} parserState parser state - * @returns {void} - */ -exports.enable = parserState => { - const value = parserStateExportsState.get(parserState); - if (value === false) return; - parserStateExportsState.set(parserState, true); - if (value !== true) { - parserState.module.buildMeta.exportsType = "default"; - parserState.module.buildMeta.defaultObject = "redirect"; + resume() { + if (this.suspended) { + this.suspended = false; + this._invalidate(); + } } -}; - -/** - * @param {ParserState} parserState parser state - * @returns {void} - */ -exports.setFlagged = parserState => { - const value = parserStateExportsState.get(parserState); - if (value !== true) return; - const buildMeta = parserState.module.buildMeta; - if (buildMeta.exportsType === "dynamic") return; - buildMeta.exportsType = "flagged"; -}; - -/** - * @param {ParserState} parserState parser state - * @returns {void} - */ -exports.setDynamic = parserState => { - const value = parserStateExportsState.get(parserState); - if (value !== true) return; - parserState.module.buildMeta.exportsType = "dynamic"; -}; - -/** - * @param {ParserState} parserState parser state - * @returns {boolean} true, when enabled - */ -exports.isEnabled = parserState => { - const value = parserStateExportsState.get(parserState); - return value === true; -}; - - -/***/ }), - -/***/ 3979: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -class EntryDependency extends ModuleDependency { /** - * @param {string} request request path for entry + * @param {Callback} callback signals when the watcher is closed + * @returns {void} */ - constructor(request) { - super(request); - } - - get type() { - return "entry"; - } + close(callback) { + if (this._closeCallbacks) { + if (callback) { + this._closeCallbacks.push(callback); + } + return; + } + const finalCallback = (err, compilation) => { + this.running = false; + this.compiler.running = false; + this.compiler.watching = undefined; + this.compiler.watchMode = false; + this.compiler.modifiedFiles = undefined; + this.compiler.removedFiles = undefined; + this.compiler.fileTimestamps = undefined; + this.compiler.contextTimestamps = undefined; + this.compiler.fsStartTime = undefined; + const shutdown = err => { + this.compiler.hooks.watchClose.call(); + const closeCallbacks = this._closeCallbacks; + this._closeCallbacks = undefined; + for (const cb of closeCallbacks) cb(err); + }; + if (compilation) { + const logger = compilation.getLogger("webpack.Watching"); + logger.time("storeBuildDependencies"); + this.compiler.cache.storeBuildDependencies( + compilation.buildDependencies, + err2 => { + logger.timeEnd("storeBuildDependencies"); + shutdown(err || err2); + } + ); + } else { + shutdown(err); + } + }; - get category() { - return "esm"; + this.closed = true; + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + if (this.pausedWatcher) { + this.pausedWatcher.close(); + this.pausedWatcher = null; + } + this._closeCallbacks = []; + if (callback) { + this._closeCallbacks.push(callback); + } + if (this.running) { + this.invalid = true; + this._done = finalCallback; + } else { + finalCallback(); + } } } -makeSerializable(EntryDependency, "webpack/lib/dependencies/EntryDependency"); - -module.exports = EntryDependency; +module.exports = Watching; /***/ }), -/***/ 78988: +/***/ 53799: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Jarid Margolin @jaridmargolin */ -const { UsageState } = __webpack_require__(63686); +const inspect = (__webpack_require__(73837).inspect.custom); const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ -/** - * @param {ModuleGraph} moduleGraph the module graph - * @param {Module} module the module - * @param {string | null} exportName name of the export if any - * @param {string | null} property name of the requested property - * @param {RuntimeSpec} runtime for which runtime - * @returns {any} value of the property - */ -const getProperty = (moduleGraph, module, exportName, property, runtime) => { - if (!exportName) { - switch (property) { - case "usedExports": { - const usedExports = moduleGraph - .getExportsInfo(module) - .getUsedExports(runtime); - if ( - typeof usedExports === "boolean" || - usedExports === undefined || - usedExports === null - ) { - return usedExports; - } - return Array.from(usedExports).sort(); - } - } - } - switch (property) { - case "used": - return ( - moduleGraph.getExportsInfo(module).getUsed(exportName, runtime) !== - UsageState.Unused - ); - case "useInfo": { - const state = moduleGraph - .getExportsInfo(module) - .getUsed(exportName, runtime); - switch (state) { - case UsageState.Used: - case UsageState.OnlyPropertiesUsed: - return true; - case UsageState.Unused: - return false; - case UsageState.NoInfo: - return undefined; - case UsageState.Unknown: - return null; - default: - throw new Error(`Unexpected UsageState ${state}`); - } - } - case "provideInfo": - return moduleGraph.getExportsInfo(module).isExportProvided(exportName); +class WebpackError extends Error { + /** + * Creates an instance of WebpackError. + * @param {string=} message error message + */ + constructor(message) { + super(message); + + this.details = undefined; + /** @type {Module} */ + this.module = undefined; + /** @type {DependencyLocation} */ + this.loc = undefined; + /** @type {boolean} */ + this.hideStack = undefined; + /** @type {Chunk} */ + this.chunk = undefined; + /** @type {string} */ + this.file = undefined; } - return undefined; -}; -class ExportsInfoDependency extends NullDependency { - constructor(range, exportName, property) { - super(); - this.range = range; - this.exportName = exportName; - this.property = property; + [inspect]() { + return this.stack + (this.details ? `\n${this.details}` : ""); } - serialize(context) { - const { write } = context; - write(this.range); - write(this.exportName); - write(this.property); - super.serialize(context); + serialize({ write }) { + write(this.name); + write(this.message); + write(this.stack); + write(this.details); + write(this.loc); + write(this.hideStack); } - static deserialize(context) { - const obj = new ExportsInfoDependency( - context.read(), - context.read(), - context.read() - ); - obj.deserialize(context); - return obj; + deserialize({ read }) { + this.name = read(); + this.message = read(); + this.stack = read(); + this.details = read(); + this.loc = read(); + this.hideStack = read(); } } -makeSerializable( - ExportsInfoDependency, - "webpack/lib/dependencies/ExportsInfoDependency" -); - -ExportsInfoDependency.Template = class ExportsInfoDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, { module, moduleGraph, runtime }) { - const dep = /** @type {ExportsInfoDependency} */ (dependency); - - const value = getProperty( - moduleGraph, - module, - dep.exportName, - dep.property, - runtime - ); - source.replace( - dep.range[0], - dep.range[1] - 1, - value === undefined ? "undefined" : JSON.stringify(value) - ); - } -}; +makeSerializable(WebpackError, "webpack/lib/WebpackError"); -module.exports = ExportsInfoDependency; +module.exports = WebpackError; /***/ }), -/***/ 23624: +/***/ 97017: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const Template = __webpack_require__(1626); -const makeSerializable = __webpack_require__(33032); -const HarmonyImportDependency = __webpack_require__(57154); -const NullDependency = __webpack_require__(31830); +const IgnoreErrorModuleFactory = __webpack_require__(3); +const WebpackIsIncludedDependency = __webpack_require__(26505); +const { + toConstantDependency +} = __webpack_require__(93998); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("./HarmonyAcceptImportDependency")} HarmonyAcceptImportDependency */ +/** @typedef {import("enhanced-resolve/lib/Resolver")} Resolver */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ -class HarmonyAcceptDependency extends NullDependency { +class WebpackIsIncludedPlugin { /** - * @param {[number, number]} range expression range - * @param {HarmonyAcceptImportDependency[]} dependencies import dependencies - * @param {boolean} hasCallback true, if the range wraps an existing callback + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - constructor(range, dependencies, hasCallback) { - super(); - this.range = range; - this.dependencies = dependencies; - this.hasCallback = hasCallback; - } - - get type() { - return "accepted harmony modules"; - } + apply(compiler) { + compiler.hooks.compilation.tap( + "WebpackIsIncludedPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + WebpackIsIncludedDependency, + new IgnoreErrorModuleFactory(normalModuleFactory) + ); + compilation.dependencyTemplates.set( + WebpackIsIncludedDependency, + new WebpackIsIncludedDependency.Template() + ); - serialize(context) { - const { write } = context; - write(this.range); - write(this.dependencies); - write(this.hasCallback); - super.serialize(context); - } + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + const handler = parser => { + parser.hooks.call + .for("__webpack_is_included__") + .tap("WebpackIsIncludedPlugin", expr => { + if ( + expr.type !== "CallExpression" || + expr.arguments.length !== 1 || + expr.arguments[0].type === "SpreadElement" + ) + return; - deserialize(context) { - const { read } = context; - this.range = read(); - this.dependencies = read(); - this.hasCallback = read(); - super.deserialize(context); - } -} + const request = parser.evaluateExpression(expr.arguments[0]); -makeSerializable( - HarmonyAcceptDependency, - "webpack/lib/dependencies/HarmonyAcceptDependency" -); + if (!request.isString()) return; -HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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 dep = /** @type {HarmonyAcceptDependency} */ (dependency); - const { - module, - runtime, - runtimeRequirements, - runtimeTemplate, - moduleGraph, - chunkGraph - } = templateContext; - const content = dep.dependencies - .map(dependency => { - const referencedModule = moduleGraph.getModule(dependency); - return { - dependency, - runtimeCondition: referencedModule - ? HarmonyImportDependency.Template.getImportEmittedRuntime( - module, - referencedModule - ) - : false + const dep = new WebpackIsIncludedDependency( + request.string, + expr.range + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return true; + }); + parser.hooks.typeof + .for("__webpack_is_included__") + .tap( + "WebpackIsIncludedPlugin", + toConstantDependency(parser, JSON.stringify("function")) + ); }; - }) - .filter(({ runtimeCondition }) => runtimeCondition !== false) - .map(({ dependency, runtimeCondition }) => { - const condition = runtimeTemplate.runtimeConditionExpression({ - chunkGraph, - runtime, - runtimeCondition, - runtimeRequirements - }); - const s = dependency.getImportStatement(true, templateContext); - const code = s[0] + s[1]; - if (condition !== "true") { - return `if (${condition}) {\n${Template.indent(code)}\n}\n`; - } - return code; - }) - .join(""); - - if (dep.hasCallback) { - if (runtimeTemplate.supportsArrowFunction()) { - source.insert( - dep.range[0], - `__WEBPACK_OUTDATED_DEPENDENCIES__ => { ${content}(` - ); - source.insert(dep.range[1], ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }"); - } else { - source.insert( - dep.range[0], - `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(` - ); - source.insert( - dep.range[1], - ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }.bind(this)" - ); + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("WebpackIsIncludedPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("WebpackIsIncludedPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("WebpackIsIncludedPlugin", handler); } - return; - } - - const arrow = runtimeTemplate.supportsArrowFunction(); - source.insert( - dep.range[1] - 0.5, - `, ${arrow ? "() =>" : "function()"} { ${content} }` ); } -}; +} -module.exports = HarmonyAcceptDependency; +module.exports = WebpackIsIncludedPlugin; /***/ }), -/***/ 99843: +/***/ 88422: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -76337,436 +70122,698 @@ module.exports = HarmonyAcceptDependency; -const makeSerializable = __webpack_require__(33032); -const HarmonyImportDependency = __webpack_require__(57154); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +const OptionsApply = __webpack_require__(81426); -class HarmonyAcceptImportDependency extends HarmonyImportDependency { - constructor(request) { - super(request, NaN); - this.weak = true; - } +const AssetModulesPlugin = __webpack_require__(16109); +const JavascriptModulesPlugin = __webpack_require__(89464); +const JsonModulesPlugin = __webpack_require__(86770); - get type() { - return "harmony accept"; - } -} +const ChunkPrefetchPreloadPlugin = __webpack_require__(33895); -makeSerializable( - HarmonyAcceptImportDependency, - "webpack/lib/dependencies/HarmonyAcceptImportDependency" -); +const EntryOptionPlugin = __webpack_require__(9909); +const RecordIdsPlugin = __webpack_require__(11094); -HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate extends ( - HarmonyImportDependency.Template -) {}; +const RuntimePlugin = __webpack_require__(2307); -module.exports = HarmonyAcceptImportDependency; +const APIPlugin = __webpack_require__(74315); +const CompatibilityPlugin = __webpack_require__(94258); +const ConstPlugin = __webpack_require__(11146); +const ExportsInfoApiPlugin = __webpack_require__(7145); +const WebpackIsIncludedPlugin = __webpack_require__(97017); +const TemplatedPathPlugin = __webpack_require__(80734); +const UseStrictPlugin = __webpack_require__(36803); +const WarnCaseSensitiveModulesPlugin = __webpack_require__(56504); -/***/ }), +const DataUriPlugin = __webpack_require__(64820); +const FileUriPlugin = __webpack_require__(57637); -/***/ 72906: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const ResolverCachePlugin = __webpack_require__(97347); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const CommonJsPlugin = __webpack_require__(32406); +const HarmonyModulesPlugin = __webpack_require__(39029); +const ImportMetaPlugin = __webpack_require__(17228); +const ImportPlugin = __webpack_require__(41293); +const LoaderPlugin = __webpack_require__(24721); +const RequireContextPlugin = __webpack_require__(2928); +const RequireEnsurePlugin = __webpack_require__(8434); +const RequireIncludePlugin = __webpack_require__(37378); +const SystemPlugin = __webpack_require__(97981); +const URLPlugin = __webpack_require__(14412); +const WorkerPlugin = __webpack_require__(82509); +const InferAsyncModulesPlugin = __webpack_require__(59498); +const JavascriptMetaInfoPlugin = __webpack_require__(52329); +const DefaultStatsFactoryPlugin = __webpack_require__(71760); +const DefaultStatsPresetPlugin = __webpack_require__(55442); +const DefaultStatsPrinterPlugin = __webpack_require__(58692); -const { UsageState } = __webpack_require__(63686); -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +const { cleverMerge } = __webpack_require__(60839); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./Compiler")} Compiler */ -class HarmonyCompatibilityDependency extends NullDependency { - get type() { - return "harmony export header"; +class WebpackOptionsApply extends OptionsApply { + constructor() { + super(); } -} - -makeSerializable( - HarmonyCompatibilityDependency, - "webpack/lib/dependencies/HarmonyCompatibilityDependency" -); -HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate extends ( - NullDependency.Template -) { /** - * @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} + * @param {WebpackOptions} options options object + * @param {Compiler} compiler compiler object + * @returns {WebpackOptions} options object */ - apply( - dependency, - source, - { - module, - runtimeTemplate, - moduleGraph, - initFragments, - runtimeRequirements, - runtime, - concatenationScope - } - ) { - if (concatenationScope) return; - const exportsInfo = moduleGraph.getExportsInfo(module); - if ( - exportsInfo.getReadOnlyExportInfo("__esModule").getUsed(runtime) !== - UsageState.Unused - ) { - const content = runtimeTemplate.defineEsModuleFlagStatement({ - exportsArgument: module.exportsArgument, - runtimeRequirements - }); - initFragments.push( - new InitFragment( - content, - InitFragment.STAGE_HARMONY_EXPORTS, - 0, - "harmony compatibility" - ) - ); - } - if (moduleGraph.isAsync(module)) { - runtimeRequirements.add(RuntimeGlobals.module); - runtimeRequirements.add(RuntimeGlobals.asyncModule); - initFragments.push( - new InitFragment( - runtimeTemplate.supportsArrowFunction() - ? `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async (__webpack_handle_async_dependencies__) => {\n` - : `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async function (__webpack_handle_async_dependencies__) {\n`, - InitFragment.STAGE_ASYNC_BOUNDARY, - 0, - undefined, - module.buildMeta.async - ? `\n__webpack_handle_async_dependencies__();\n}, 1);` - : "\n});" - ) + process(options, compiler) { + compiler.outputPath = options.output.path; + compiler.recordsInputPath = options.recordsInputPath || null; + compiler.recordsOutputPath = options.recordsOutputPath || null; + compiler.name = options.name; + + if (options.externals) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = __webpack_require__(6652); + new ExternalsPlugin(options.externalsType, options.externals).apply( + compiler ); } - } -}; -module.exports = HarmonyCompatibilityDependency; - - -/***/ }), + if (options.externalsPresets.node) { + const NodeTargetPlugin = __webpack_require__(17916); + new NodeTargetPlugin().apply(compiler); + } + if (options.externalsPresets.electronMain) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ElectronTargetPlugin = __webpack_require__(32277); + new ElectronTargetPlugin("main").apply(compiler); + } + if (options.externalsPresets.electronPreload) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ElectronTargetPlugin = __webpack_require__(32277); + new ElectronTargetPlugin("preload").apply(compiler); + } + if (options.externalsPresets.electronRenderer) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ElectronTargetPlugin = __webpack_require__(32277); + new ElectronTargetPlugin("renderer").apply(compiler); + } + if ( + options.externalsPresets.electron && + !options.externalsPresets.electronMain && + !options.externalsPresets.electronPreload && + !options.externalsPresets.electronRenderer + ) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ElectronTargetPlugin = __webpack_require__(32277); + new ElectronTargetPlugin().apply(compiler); + } + if (options.externalsPresets.nwjs) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = __webpack_require__(6652); + new ExternalsPlugin("node-commonjs", "nw.gui").apply(compiler); + } + if (options.externalsPresets.webAsync) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = __webpack_require__(6652); + new ExternalsPlugin( + "import", + options.experiments.css + ? ({ request, dependencyType }, callback) => { + if (dependencyType === "url") { + if (/^(\/\/|https?:\/\/)/.test(request)) + return callback(null, `asset ${request}`); + } else if (dependencyType === "css-import") { + if (/^(\/\/|https?:\/\/)/.test(request)) + return callback(null, `css-import ${request}`); + } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) { + if (/^\.css(\?|$)/.test(request)) + return callback(null, `css-import ${request}`); + return callback(null, `import ${request}`); + } + callback(); + } + : /^(\/\/|https?:\/\/|std:)/ + ).apply(compiler); + } else if (options.externalsPresets.web) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = __webpack_require__(6652); + new ExternalsPlugin( + "module", + options.experiments.css + ? ({ request, dependencyType }, callback) => { + if (dependencyType === "url") { + if (/^(\/\/|https?:\/\/)/.test(request)) + return callback(null, `asset ${request}`); + } else if (dependencyType === "css-import") { + if (/^(\/\/|https?:\/\/)/.test(request)) + return callback(null, `css-import ${request}`); + } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) { + if (/^\.css(\?|$)/.test(request)) + return callback(null, `css-import ${request}`); + return callback(null, `module ${request}`); + } + callback(); + } + : /^(\/\/|https?:\/\/|std:)/ + ).apply(compiler); + } -/***/ 17223: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + new ChunkPrefetchPreloadPlugin().apply(compiler); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (typeof options.output.chunkFormat === "string") { + switch (options.output.chunkFormat) { + case "array-push": { + const ArrayPushCallbackChunkFormatPlugin = __webpack_require__(18535); + new ArrayPushCallbackChunkFormatPlugin().apply(compiler); + break; + } + case "commonjs": { + const CommonJsChunkFormatPlugin = __webpack_require__(84508); + new CommonJsChunkFormatPlugin().apply(compiler); + break; + } + case "module": { + const ModuleChunkFormatPlugin = __webpack_require__(68927); + new ModuleChunkFormatPlugin().apply(compiler); + break; + } + default: + throw new Error( + "Unsupported chunk format '" + options.output.chunkFormat + "'." + ); + } + } + if (options.output.enabledChunkLoadingTypes.length > 0) { + for (const type of options.output.enabledChunkLoadingTypes) { + const EnableChunkLoadingPlugin = __webpack_require__(61291); + new EnableChunkLoadingPlugin(type).apply(compiler); + } + } + if (options.output.enabledWasmLoadingTypes.length > 0) { + for (const type of options.output.enabledWasmLoadingTypes) { + const EnableWasmLoadingPlugin = __webpack_require__(78613); + new EnableWasmLoadingPlugin(type).apply(compiler); + } + } -const DynamicExports = __webpack_require__(32006); -const HarmonyCompatibilityDependency = __webpack_require__(72906); -const HarmonyExports = __webpack_require__(39211); + if (options.output.enabledLibraryTypes.length > 0) { + for (const type of options.output.enabledLibraryTypes) { + const EnableLibraryPlugin = __webpack_require__(91452); + new EnableLibraryPlugin(type).apply(compiler); + } + } -module.exports = class HarmonyDetectionParserPlugin { - constructor(options) { - const { topLevelAwait = false } = options || {}; - this.topLevelAwait = topLevelAwait; - } + if (options.output.pathinfo) { + const ModuleInfoHeaderPlugin = __webpack_require__(3454); + new ModuleInfoHeaderPlugin(options.output.pathinfo !== true).apply( + compiler + ); + } - apply(parser) { - parser.hooks.program.tap("HarmonyDetectionParserPlugin", ast => { - const isStrictHarmony = parser.state.module.type === "javascript/esm"; - const isHarmony = - isStrictHarmony || - ast.body.some( - statement => - statement.type === "ImportDeclaration" || - statement.type === "ExportDefaultDeclaration" || - statement.type === "ExportNamedDeclaration" || - statement.type === "ExportAllDeclaration" - ); - if (isHarmony) { - const module = parser.state.module; - const compatDep = new HarmonyCompatibilityDependency(); - compatDep.loc = { - start: { - line: -1, - column: 0 - }, - end: { - line: -1, - column: 0 - }, - index: -3 - }; - module.addPresentationalDependency(compatDep); - DynamicExports.bailout(parser.state); - HarmonyExports.enable(parser.state, isStrictHarmony); - parser.scope.isStrict = true; + if (options.output.clean) { + const CleanPlugin = __webpack_require__(31085); + new CleanPlugin( + options.output.clean === true ? {} : options.output.clean + ).apply(compiler); + } + + if (options.devtool) { + if (options.devtool.includes("source-map")) { + const hidden = options.devtool.includes("hidden"); + const inline = options.devtool.includes("inline"); + const evalWrapped = options.devtool.includes("eval"); + const cheap = options.devtool.includes("cheap"); + const moduleMaps = options.devtool.includes("module"); + const noSources = options.devtool.includes("nosources"); + const Plugin = evalWrapped + ? __webpack_require__(14790) + : __webpack_require__(63872); + new Plugin({ + filename: inline ? null : options.output.sourceMapFilename, + moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, + fallbackModuleFilenameTemplate: + options.output.devtoolFallbackModuleFilenameTemplate, + append: hidden ? false : undefined, + module: moduleMaps ? true : cheap ? false : true, + columns: cheap ? false : true, + noSources: noSources, + namespace: options.output.devtoolNamespace + }).apply(compiler); + } else if (options.devtool.includes("eval")) { + const EvalDevToolModulePlugin = __webpack_require__(65218); + new EvalDevToolModulePlugin({ + moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, + namespace: options.output.devtoolNamespace + }).apply(compiler); } - }); + } - parser.hooks.topLevelAwait.tap("HarmonyDetectionParserPlugin", () => { - const module = parser.state.module; - if (!this.topLevelAwait) { + new JavascriptModulesPlugin().apply(compiler); + new JsonModulesPlugin().apply(compiler); + new AssetModulesPlugin().apply(compiler); + + if (!options.experiments.outputModule) { + if (options.output.module) { throw new Error( - "The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)" + "'output.module: true' is only allowed when 'experiments.outputModule' is enabled" ); } - if (!HarmonyExports.isEnabled(parser.state)) { + if (options.output.enabledLibraryTypes.includes("module")) { throw new Error( - "Top-level-await is only supported in EcmaScript Modules" + "library type \"module\" is only allowed when 'experiments.outputModule' is enabled" ); } - module.buildMeta.async = true; - }); - - const skipInHarmony = () => { - if (HarmonyExports.isEnabled(parser.state)) { - return true; + if (options.externalsType === "module") { + throw new Error( + "'externalsType: \"module\"' is only allowed when 'experiments.outputModule' is enabled" + ); } - }; + } - const nullInHarmony = () => { - if (HarmonyExports.isEnabled(parser.state)) { - return null; - } - }; + if (options.experiments.syncWebAssembly) { + const WebAssemblyModulesPlugin = __webpack_require__(53639); + new WebAssemblyModulesPlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + } - const nonHarmonyIdentifiers = ["define", "exports"]; - for (const identifier of nonHarmonyIdentifiers) { - parser.hooks.evaluateTypeof - .for(identifier) - .tap("HarmonyDetectionParserPlugin", nullInHarmony); - parser.hooks.typeof - .for(identifier) - .tap("HarmonyDetectionParserPlugin", skipInHarmony); - parser.hooks.evaluate - .for(identifier) - .tap("HarmonyDetectionParserPlugin", nullInHarmony); - parser.hooks.expression - .for(identifier) - .tap("HarmonyDetectionParserPlugin", skipInHarmony); - parser.hooks.call - .for(identifier) - .tap("HarmonyDetectionParserPlugin", skipInHarmony); + if (options.experiments.asyncWebAssembly) { + const AsyncWebAssemblyModulesPlugin = __webpack_require__(7538); + new AsyncWebAssemblyModulesPlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); } - } -}; + if (options.experiments.css) { + const CssModulesPlugin = __webpack_require__(47283); + new CssModulesPlugin(options.experiments.css).apply(compiler); + } -/***/ }), + if (options.experiments.lazyCompilation) { + const LazyCompilationPlugin = __webpack_require__(79040); + const lazyOptions = + typeof options.experiments.lazyCompilation === "object" + ? options.experiments.lazyCompilation + : null; + new LazyCompilationPlugin({ + backend: + typeof lazyOptions.backend === "function" + ? lazyOptions.backend + : __webpack_require__(17781)({ + ...lazyOptions.backend, + client: + (lazyOptions.backend && lazyOptions.backend.client) || + options.externalsPresets.node ? __webpack_require__.ab + "lazy-compilation-node.js" : __webpack_require__.ab + "lazy-compilation-web.js" + }), + entries: !lazyOptions || lazyOptions.entries !== false, + imports: !lazyOptions || lazyOptions.imports !== false, + test: (lazyOptions && lazyOptions.test) || undefined + }).apply(compiler); + } -/***/ 93466: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (options.experiments.buildHttp) { + const HttpUriPlugin = __webpack_require__(42110); + const httpOptions = options.experiments.buildHttp; + new HttpUriPlugin(httpOptions).apply(compiler); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + new EntryOptionPlugin().apply(compiler); + compiler.hooks.entryOption.call(options.context, options.entry); + new RuntimePlugin().apply(compiler); + new InferAsyncModulesPlugin().apply(compiler); -const InnerGraph = __webpack_require__(38988); -const ConstDependency = __webpack_require__(76911); -const HarmonyExportExpressionDependency = __webpack_require__(51340); -const HarmonyExportHeaderDependency = __webpack_require__(38873); -const HarmonyExportImportedSpecifierDependency = __webpack_require__(67157); -const HarmonyExportSpecifierDependency = __webpack_require__(48567); -const { ExportPresenceModes } = __webpack_require__(57154); -const { - harmonySpecifierTag, - getAssertions -} = __webpack_require__(20862); -const HarmonyImportSideEffectDependency = __webpack_require__(73132); + new DataUriPlugin().apply(compiler); + new FileUriPlugin().apply(compiler); -const { HarmonyStarExportsList } = HarmonyExportImportedSpecifierDependency; + new CompatibilityPlugin().apply(compiler); + new HarmonyModulesPlugin({ + topLevelAwait: options.experiments.topLevelAwait + }).apply(compiler); + if (options.amd !== false) { + const AMDPlugin = __webpack_require__(50067); + const RequireJsStuffPlugin = __webpack_require__(88846); + new AMDPlugin(options.amd || {}).apply(compiler); + new RequireJsStuffPlugin().apply(compiler); + } + new CommonJsPlugin().apply(compiler); + new LoaderPlugin({}).apply(compiler); + if (options.node !== false) { + const NodeStuffPlugin = __webpack_require__(95287); + new NodeStuffPlugin(options.node).apply(compiler); + } + new APIPlugin().apply(compiler); + new ExportsInfoApiPlugin().apply(compiler); + new WebpackIsIncludedPlugin().apply(compiler); + new ConstPlugin().apply(compiler); + new UseStrictPlugin().apply(compiler); + new RequireIncludePlugin().apply(compiler); + new RequireEnsurePlugin().apply(compiler); + new RequireContextPlugin().apply(compiler); + new ImportPlugin().apply(compiler); + new SystemPlugin().apply(compiler); + new ImportMetaPlugin().apply(compiler); + new URLPlugin().apply(compiler); + new WorkerPlugin( + options.output.workerChunkLoading, + options.output.workerWasmLoading, + options.output.module + ).apply(compiler); -module.exports = class HarmonyExportDependencyParserPlugin { - constructor(options) { - this.exportPresenceMode = - options.reexportExportsPresence !== undefined - ? ExportPresenceModes.fromUserOption(options.reexportExportsPresence) - : options.exportsPresence !== undefined - ? ExportPresenceModes.fromUserOption(options.exportsPresence) - : options.strictExportPresence - ? ExportPresenceModes.ERROR - : ExportPresenceModes.AUTO; - } + new DefaultStatsFactoryPlugin().apply(compiler); + new DefaultStatsPresetPlugin().apply(compiler); + new DefaultStatsPrinterPlugin().apply(compiler); - apply(parser) { - const { exportPresenceMode } = this; - parser.hooks.export.tap( - "HarmonyExportDependencyParserPlugin", - statement => { - const dep = new HarmonyExportHeaderDependency( - statement.declaration && statement.declaration.range, - statement.range - ); - dep.loc = Object.create(statement.loc); - dep.loc.index = -1; - parser.state.module.addPresentationalDependency(dep); - return true; - } - ); - parser.hooks.exportImport.tap( - "HarmonyExportDependencyParserPlugin", - (statement, source) => { - parser.state.lastHarmonyImportOrder = - (parser.state.lastHarmonyImportOrder || 0) + 1; - const clearDep = new ConstDependency("", statement.range); - clearDep.loc = Object.create(statement.loc); - clearDep.loc.index = -1; - parser.state.module.addPresentationalDependency(clearDep); - const sideEffectDep = new HarmonyImportSideEffectDependency( - source, - parser.state.lastHarmonyImportOrder, - getAssertions(statement) - ); - sideEffectDep.loc = Object.create(statement.loc); - sideEffectDep.loc.index = -1; - parser.state.current.addDependency(sideEffectDep); - return true; - } - ); - parser.hooks.exportExpression.tap( - "HarmonyExportDependencyParserPlugin", - (statement, expr) => { - const isFunctionDeclaration = expr.type === "FunctionDeclaration"; - const comments = parser.getComments([ - statement.range[0], - expr.range[0] - ]); - const dep = new HarmonyExportExpressionDependency( - expr.range, - statement.range, - comments - .map(c => { - switch (c.type) { - case "Block": - return `/*${c.value}*/`; - case "Line": - return `//${c.value}\n`; - } - return ""; - }) - .join(""), - expr.type.endsWith("Declaration") && expr.id - ? expr.id.name - : isFunctionDeclaration - ? { - id: expr.id ? expr.id.name : undefined, - range: [ - expr.range[0], - expr.params.length > 0 - ? expr.params[0].range[0] - : expr.body.range[0] - ], - prefix: `${expr.async ? "async " : ""}function${ - expr.generator ? "*" : "" - } `, - suffix: `(${expr.params.length > 0 ? "" : ") "}` - } - : undefined - ); - dep.loc = Object.create(statement.loc); - dep.loc.index = -1; - parser.state.current.addDependency(dep); - InnerGraph.addVariableUsage( - parser, - expr.type.endsWith("Declaration") && expr.id - ? expr.id.name - : "*default*", - "default" - ); - return true; + new JavascriptMetaInfoPlugin().apply(compiler); + + if (typeof options.mode !== "string") { + const WarnNoModeSetPlugin = __webpack_require__(25295); + new WarnNoModeSetPlugin().apply(compiler); + } + + const EnsureChunkConditionsPlugin = __webpack_require__(96260); + new EnsureChunkConditionsPlugin().apply(compiler); + if (options.optimization.removeAvailableModules) { + const RemoveParentModulesPlugin = __webpack_require__(7081); + new RemoveParentModulesPlugin().apply(compiler); + } + if (options.optimization.removeEmptyChunks) { + const RemoveEmptyChunksPlugin = __webpack_require__(84760); + new RemoveEmptyChunksPlugin().apply(compiler); + } + if (options.optimization.mergeDuplicateChunks) { + const MergeDuplicateChunksPlugin = __webpack_require__(85067); + new MergeDuplicateChunksPlugin().apply(compiler); + } + if (options.optimization.flagIncludedChunks) { + const FlagIncludedChunksPlugin = __webpack_require__(50089); + new FlagIncludedChunksPlugin().apply(compiler); + } + if (options.optimization.sideEffects) { + const SideEffectsFlagPlugin = __webpack_require__(84800); + new SideEffectsFlagPlugin( + options.optimization.sideEffects === true + ).apply(compiler); + } + if (options.optimization.providedExports) { + const FlagDependencyExportsPlugin = __webpack_require__(84506); + new FlagDependencyExportsPlugin().apply(compiler); + } + if (options.optimization.usedExports) { + const FlagDependencyUsagePlugin = __webpack_require__(58812); + new FlagDependencyUsagePlugin( + options.optimization.usedExports === "global" + ).apply(compiler); + } + if (options.optimization.innerGraph) { + const InnerGraphPlugin = __webpack_require__(28758); + new InnerGraphPlugin().apply(compiler); + } + if (options.optimization.mangleExports) { + const MangleExportsPlugin = __webpack_require__(27868); + new MangleExportsPlugin( + options.optimization.mangleExports !== "size" + ).apply(compiler); + } + if (options.optimization.concatenateModules) { + const ModuleConcatenationPlugin = __webpack_require__(74844); + new ModuleConcatenationPlugin().apply(compiler); + } + if (options.optimization.splitChunks) { + const SplitChunksPlugin = __webpack_require__(21478); + new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler); + } + if (options.optimization.runtimeChunk) { + const RuntimeChunkPlugin = __webpack_require__(2837); + new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler); + } + if (!options.optimization.emitOnErrors) { + const NoEmitOnErrorsPlugin = __webpack_require__(50169); + new NoEmitOnErrorsPlugin().apply(compiler); + } + if (options.optimization.realContentHash) { + const RealContentHashPlugin = __webpack_require__(46043); + new RealContentHashPlugin({ + hashFunction: options.output.hashFunction, + hashDigest: options.output.hashDigest + }).apply(compiler); + } + if (options.optimization.checkWasmTypes) { + const WasmFinalizeExportsPlugin = __webpack_require__(19810); + new WasmFinalizeExportsPlugin().apply(compiler); + } + const moduleIds = options.optimization.moduleIds; + if (moduleIds) { + switch (moduleIds) { + case "natural": { + const NaturalModuleIdsPlugin = __webpack_require__(83366); + new NaturalModuleIdsPlugin().apply(compiler); + break; + } + case "named": { + const NamedModuleIdsPlugin = __webpack_require__(24339); + new NamedModuleIdsPlugin().apply(compiler); + break; + } + case "hashed": { + const WarnDeprecatedOptionPlugin = __webpack_require__(76537); + const HashedModuleIdsPlugin = __webpack_require__(21825); + new WarnDeprecatedOptionPlugin( + "optimization.moduleIds", + "hashed", + "deterministic" + ).apply(compiler); + new HashedModuleIdsPlugin({ + hashFunction: options.output.hashFunction + }).apply(compiler); + break; + } + case "deterministic": { + const DeterministicModuleIdsPlugin = __webpack_require__(76692); + new DeterministicModuleIdsPlugin().apply(compiler); + break; + } + case "size": { + const OccurrenceModuleIdsPlugin = __webpack_require__(35371); + new OccurrenceModuleIdsPlugin({ + prioritiseInitial: true + }).apply(compiler); + break; + } + default: + throw new Error( + `webpack bug: moduleIds: ${moduleIds} is not implemented` + ); } - ); - parser.hooks.exportSpecifier.tap( - "HarmonyExportDependencyParserPlugin", - (statement, id, name, idx) => { - const settings = parser.getTagData(id, harmonySpecifierTag); - let dep; - const harmonyNamedExports = (parser.state.harmonyNamedExports = - parser.state.harmonyNamedExports || new Set()); - harmonyNamedExports.add(name); - InnerGraph.addVariableUsage(parser, id, name); - if (settings) { - dep = new HarmonyExportImportedSpecifierDependency( - settings.source, - settings.sourceOrder, - settings.ids, - name, - harmonyNamedExports, - null, - exportPresenceMode, - null, - settings.assertions + } + const chunkIds = options.optimization.chunkIds; + if (chunkIds) { + switch (chunkIds) { + case "natural": { + const NaturalChunkIdsPlugin = __webpack_require__(86221); + new NaturalChunkIdsPlugin().apply(compiler); + break; + } + case "named": { + const NamedChunkIdsPlugin = __webpack_require__(6454); + new NamedChunkIdsPlugin().apply(compiler); + break; + } + case "deterministic": { + const DeterministicChunkIdsPlugin = __webpack_require__(8747); + new DeterministicChunkIdsPlugin().apply(compiler); + break; + } + case "size": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const OccurrenceChunkIdsPlugin = __webpack_require__(51020); + new OccurrenceChunkIdsPlugin({ + prioritiseInitial: true + }).apply(compiler); + break; + } + case "total-size": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const OccurrenceChunkIdsPlugin = __webpack_require__(51020); + new OccurrenceChunkIdsPlugin({ + prioritiseInitial: false + }).apply(compiler); + break; + } + default: + throw new Error( + `webpack bug: chunkIds: ${chunkIds} is not implemented` ); - } else { - dep = new HarmonyExportSpecifierDependency(id, name); + } + } + if (options.optimization.nodeEnv) { + const DefinePlugin = __webpack_require__(79065); + new DefinePlugin({ + "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv) + }).apply(compiler); + } + if (options.optimization.minimize) { + for (const minimizer of options.optimization.minimizer) { + if (typeof minimizer === "function") { + minimizer.call(compiler, compiler); + } else if (minimizer !== "...") { + minimizer.apply(compiler); } - dep.loc = Object.create(statement.loc); - dep.loc.index = idx; - parser.state.current.addDependency(dep); - return true; } - ); - parser.hooks.exportImportSpecifier.tap( - "HarmonyExportDependencyParserPlugin", - (statement, source, id, name, idx) => { - const harmonyNamedExports = (parser.state.harmonyNamedExports = - parser.state.harmonyNamedExports || new Set()); - let harmonyStarExports = null; - if (name) { - harmonyNamedExports.add(name); - } else { - harmonyStarExports = parser.state.harmonyStarExports = - parser.state.harmonyStarExports || new HarmonyStarExportsList(); + } + + if (options.performance) { + const SizeLimitsPlugin = __webpack_require__(32557); + new SizeLimitsPlugin(options.performance).apply(compiler); + } + + new TemplatedPathPlugin().apply(compiler); + + new RecordIdsPlugin({ + portableIds: options.optimization.portableRecords + }).apply(compiler); + + new WarnCaseSensitiveModulesPlugin().apply(compiler); + + const AddManagedPathsPlugin = __webpack_require__(47942); + new AddManagedPathsPlugin( + options.snapshot.managedPaths, + options.snapshot.immutablePaths + ).apply(compiler); + + if (options.cache && typeof options.cache === "object") { + const cacheOptions = options.cache; + switch (cacheOptions.type) { + case "memory": { + if (isFinite(cacheOptions.maxGenerations)) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const MemoryWithGcCachePlugin = __webpack_require__(99334); + new MemoryWithGcCachePlugin({ + maxGenerations: cacheOptions.maxGenerations + }).apply(compiler); + } else { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const MemoryCachePlugin = __webpack_require__(52539); + new MemoryCachePlugin().apply(compiler); + } + if (cacheOptions.cacheUnaffected) { + if (!options.experiments.cacheUnaffected) { + throw new Error( + "'cache.cacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled" + ); + } + compiler.moduleMemCaches = new Map(); + } + break; } - const dep = new HarmonyExportImportedSpecifierDependency( - source, - parser.state.lastHarmonyImportOrder, - id ? [id] : [], - name, - harmonyNamedExports, - harmonyStarExports && harmonyStarExports.slice(), - exportPresenceMode, - harmonyStarExports - ); - if (harmonyStarExports) { - harmonyStarExports.push(dep); + case "filesystem": { + const AddBuildDependenciesPlugin = __webpack_require__(28034); + for (const key in cacheOptions.buildDependencies) { + const list = cacheOptions.buildDependencies[key]; + new AddBuildDependenciesPlugin(list).apply(compiler); + } + if (!isFinite(cacheOptions.maxMemoryGenerations)) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const MemoryCachePlugin = __webpack_require__(52539); + new MemoryCachePlugin().apply(compiler); + } else if (cacheOptions.maxMemoryGenerations !== 0) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const MemoryWithGcCachePlugin = __webpack_require__(99334); + new MemoryWithGcCachePlugin({ + maxGenerations: cacheOptions.maxMemoryGenerations + }).apply(compiler); + } + if (cacheOptions.memoryCacheUnaffected) { + if (!options.experiments.cacheUnaffected) { + throw new Error( + "'cache.memoryCacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled" + ); + } + compiler.moduleMemCaches = new Map(); + } + switch (cacheOptions.store) { + case "pack": { + const IdleFileCachePlugin = __webpack_require__(71985); + const PackFileCacheStrategy = __webpack_require__(86180); + new IdleFileCachePlugin( + new PackFileCacheStrategy({ + compiler, + fs: compiler.intermediateFileSystem, + context: options.context, + cacheLocation: cacheOptions.cacheLocation, + version: cacheOptions.version, + logger: compiler.getInfrastructureLogger( + "webpack.cache.PackFileCacheStrategy" + ), + snapshot: options.snapshot, + maxAge: cacheOptions.maxAge, + profile: cacheOptions.profile, + allowCollectingMemory: cacheOptions.allowCollectingMemory, + compression: cacheOptions.compression + }), + cacheOptions.idleTimeout, + cacheOptions.idleTimeoutForInitialStore, + cacheOptions.idleTimeoutAfterLargeChanges + ).apply(compiler); + break; + } + default: + throw new Error("Unhandled value for cache.store"); + } + break; } - dep.loc = Object.create(statement.loc); - dep.loc.index = idx; - parser.state.current.addDependency(dep); - return true; + default: + // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339) + throw new Error(`Unknown cache type ${cacheOptions.type}`); } - ); + } + new ResolverCachePlugin().apply(compiler); + + if (options.ignoreWarnings && options.ignoreWarnings.length > 0) { + const IgnoreWarningsPlugin = __webpack_require__(41606); + new IgnoreWarningsPlugin(options.ignoreWarnings).apply(compiler); + } + + compiler.hooks.afterPlugins.call(compiler); + if (!compiler.inputFileSystem) { + throw new Error("No input filesystem provided"); + } + compiler.resolverFactory.hooks.resolveOptions + .for("normal") + .tap("WebpackOptionsApply", resolveOptions => { + resolveOptions = cleverMerge(options.resolve, resolveOptions); + resolveOptions.fileSystem = compiler.inputFileSystem; + return resolveOptions; + }); + compiler.resolverFactory.hooks.resolveOptions + .for("context") + .tap("WebpackOptionsApply", resolveOptions => { + resolveOptions = cleverMerge(options.resolve, resolveOptions); + resolveOptions.fileSystem = compiler.inputFileSystem; + resolveOptions.resolveToContext = true; + return resolveOptions; + }); + compiler.resolverFactory.hooks.resolveOptions + .for("loader") + .tap("WebpackOptionsApply", resolveOptions => { + resolveOptions = cleverMerge(options.resolveLoader, resolveOptions); + resolveOptions.fileSystem = compiler.inputFileSystem; + return resolveOptions; + }); + compiler.hooks.afterResolvers.call(compiler); + return options; } -}; +} + +module.exports = WebpackOptionsApply; /***/ }), -/***/ 51340: +/***/ 14452: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -76777,1546 +70824,1115 @@ module.exports = class HarmonyExportDependencyParserPlugin { -const ConcatenationScope = __webpack_require__(98229); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const HarmonyExportInitFragment = __webpack_require__(89500); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ - -class HarmonyExportExpressionDependency extends NullDependency { - constructor(range, rangeStatement, prefix, declarationId) { - super(); - this.range = range; - this.rangeStatement = rangeStatement; - this.prefix = prefix; - this.declarationId = declarationId; - } - - get type() { - return "harmony export expression"; - } - - /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names - */ - getExports(moduleGraph) { - return { - exports: ["default"], - priority: 1, - terminalBinding: true, - dependencies: undefined - }; - } - - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules - */ - getModuleEvaluationSideEffectsState(moduleGraph) { - // The expression/declaration is already covered by SideEffectsFlagPlugin - return false; - } - - serialize(context) { - const { write } = context; - write(this.range); - write(this.rangeStatement); - write(this.prefix); - write(this.declarationId); - super.serialize(context); - } +const { applyWebpackOptionsDefaults } = __webpack_require__(92988); +const { getNormalizedWebpackOptions } = __webpack_require__(26693); - deserialize(context) { - const { read } = context; - this.range = read(); - this.rangeStatement = read(); - this.prefix = read(); - this.declarationId = read(); - super.deserialize(context); +class WebpackOptionsDefaulter { + process(options) { + options = getNormalizedWebpackOptions(options); + applyWebpackOptionsDefaults(options); + return options; } } -makeSerializable( - HarmonyExportExpressionDependency, - "webpack/lib/dependencies/HarmonyExportExpressionDependency" -); - -HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, - { - module, - moduleGraph, - runtimeTemplate, - runtimeRequirements, - initFragments, - runtime, - concatenationScope - } - ) { - const dep = /** @type {HarmonyExportExpressionDependency} */ (dependency); - const { declarationId } = dep; - const exportsName = module.exportsArgument; - if (declarationId) { - let name; - if (typeof declarationId === "string") { - name = declarationId; - } else { - name = ConcatenationScope.DEFAULT_EXPORT; - source.replace( - declarationId.range[0], - declarationId.range[1] - 1, - `${declarationId.prefix}${name}${declarationId.suffix}` - ); - } - - if (concatenationScope) { - concatenationScope.registerExport("default", name); - } else { - const used = moduleGraph - .getExportsInfo(module) - .getUsedName("default", runtime); - if (used) { - const map = new Map(); - map.set(used, `/* export default binding */ ${name}`); - initFragments.push(new HarmonyExportInitFragment(exportsName, map)); - } - } - - source.replace( - dep.rangeStatement[0], - dep.range[0] - 1, - `/* harmony default export */ ${dep.prefix}` - ); - } else { - let content; - const name = ConcatenationScope.DEFAULT_EXPORT; - if (runtimeTemplate.supportsConst()) { - content = `/* harmony default export */ const ${name} = `; - if (concatenationScope) { - concatenationScope.registerExport("default", name); - } else { - const used = moduleGraph - .getExportsInfo(module) - .getUsedName("default", runtime); - if (used) { - runtimeRequirements.add(RuntimeGlobals.exports); - const map = new Map(); - map.set(used, name); - initFragments.push(new HarmonyExportInitFragment(exportsName, map)); - } else { - content = `/* unused harmony default export */ var ${name} = `; - } - } - } else if (concatenationScope) { - content = `/* harmony default export */ var ${name} = `; - concatenationScope.registerExport("default", name); - } else { - const used = moduleGraph - .getExportsInfo(module) - .getUsedName("default", runtime); - if (used) { - runtimeRequirements.add(RuntimeGlobals.exports); - // This is a little bit incorrect as TDZ is not correct, but we can't use const. - content = `/* harmony default export */ ${exportsName}[${JSON.stringify( - used - )}] = `; - } else { - content = `/* unused harmony default export */ var ${name} = `; - } - } - - if (dep.range) { - source.replace( - dep.rangeStatement[0], - dep.range[0] - 1, - content + "(" + dep.prefix - ); - source.replace(dep.range[1], dep.rangeStatement[1] - 0.5, ");"); - return; - } - - source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); - } - } -}; - -module.exports = HarmonyExportExpressionDependency; +module.exports = WebpackOptionsDefaulter; /***/ }), -/***/ 38873: +/***/ 98421: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sergey Melyukov @smelukov */ -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +const mimeTypes = __webpack_require__(78585); +const path = __webpack_require__(71017); +const { RawSource } = __webpack_require__(51255); +const Generator = __webpack_require__(93401); +const RuntimeGlobals = __webpack_require__(16475); +const createHash = __webpack_require__(49835); +const { makePathsRelative } = __webpack_require__(82186); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").AssetGeneratorOptions} AssetGeneratorOptions */ +/** @typedef {import("../../declarations/WebpackOptions").AssetModuleOutputPath} AssetModuleOutputPath */ +/** @typedef {import("../../declarations/WebpackOptions").RawPublicPath} RawPublicPath */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../util/Hash")} Hash */ -class HarmonyExportHeaderDependency extends NullDependency { - constructor(range, rangeStatement) { - super(); - this.range = range; - this.rangeStatement = rangeStatement; +const mergeMaybeArrays = (a, b) => { + const set = new Set(); + if (Array.isArray(a)) for (const item of a) set.add(item); + else set.add(a); + if (Array.isArray(b)) for (const item of b) set.add(item); + else set.add(b); + return Array.from(set); +}; + +const mergeAssetInfo = (a, b) => { + const result = { ...a, ...b }; + for (const key of Object.keys(a)) { + if (key in b) { + if (a[key] === b[key]) continue; + switch (key) { + case "fullhash": + case "chunkhash": + case "modulehash": + case "contenthash": + result[key] = mergeMaybeArrays(a[key], b[key]); + break; + case "immutable": + case "development": + case "hotModuleReplacement": + case "javascriptModule": + result[key] = a[key] || b[key]; + break; + case "related": + result[key] = mergeRelatedInfo(a[key], b[key]); + break; + default: + throw new Error(`Can't handle conflicting asset info for ${key}`); + } + } } + return result; +}; - get type() { - return "harmony export header"; +const mergeRelatedInfo = (a, b) => { + const result = { ...a, ...b }; + for (const key of Object.keys(a)) { + if (key in b) { + if (a[key] === b[key]) continue; + result[key] = mergeMaybeArrays(a[key], b[key]); + } } + return result; +}; - serialize(context) { - const { write } = context; - write(this.range); - write(this.rangeStatement); - super.serialize(context); +const encodeDataUri = (encoding, source) => { + let encodedContent; + + switch (encoding) { + case "base64": { + encodedContent = source.buffer().toString("base64"); + break; + } + case false: { + const content = source.source(); + + if (typeof content !== "string") { + encodedContent = content.toString("utf-8"); + } + + encodedContent = encodeURIComponent(encodedContent).replace( + /[!'()*]/g, + character => "%" + character.codePointAt(0).toString(16) + ); + break; + } + default: + throw new Error(`Unsupported encoding '${encoding}'`); } - deserialize(context) { - const { read } = context; - this.range = read(); - this.rangeStatement = read(); - super.deserialize(context); + return encodedContent; +}; + +const decodeDataUriContent = (encoding, content) => { + const isBase64 = encoding === "base64"; + return isBase64 + ? Buffer.from(content, "base64") + : Buffer.from(decodeURIComponent(content), "ascii"); +}; + +const JS_TYPES = new Set(["javascript"]); +const JS_AND_ASSET_TYPES = new Set(["javascript", "asset"]); + +class AssetGenerator extends Generator { + /** + * @param {AssetGeneratorOptions["dataUrl"]=} dataUrlOptions the options for the data url + * @param {string=} filename override for output.assetModuleFilename + * @param {RawPublicPath=} publicPath override for output.assetModulePublicPath + * @param {AssetModuleOutputPath=} outputPath the output path for the emitted file which is not included in the runtime import + * @param {boolean=} emit generate output asset + */ + constructor(dataUrlOptions, filename, publicPath, outputPath, emit) { + super(); + this.dataUrlOptions = dataUrlOptions; + this.filename = filename; + this.publicPath = publicPath; + this.outputPath = outputPath; + this.emit = emit; } -} -makeSerializable( - HarmonyExportHeaderDependency, - "webpack/lib/dependencies/HarmonyExportHeaderDependency" -); + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code + */ + generate( + module, + { runtime, chunkGraph, runtimeTemplate, runtimeRequirements, type, getData } + ) { + switch (type) { + case "asset": + return module.originalSource(); + default: { + runtimeRequirements.add(RuntimeGlobals.module); + + const originalSource = module.originalSource(); + if (module.buildInfo.dataUrl) { + let encodedSource; + if (typeof this.dataUrlOptions === "function") { + encodedSource = this.dataUrlOptions.call( + null, + originalSource.source(), + { + filename: module.matchResource || module.resource, + module + } + ); + } else { + /** @type {string | false | undefined} */ + let encoding = this.dataUrlOptions.encoding; + if (encoding === undefined) { + if ( + module.resourceResolveData && + module.resourceResolveData.encoding !== undefined + ) { + encoding = module.resourceResolveData.encoding; + } + } + if (encoding === undefined) { + encoding = "base64"; + } + let ext; + let mimeType = this.dataUrlOptions.mimetype; + if (mimeType === undefined) { + ext = path.extname(module.nameForCondition()); + if ( + module.resourceResolveData && + module.resourceResolveData.mimetype !== undefined + ) { + mimeType = + module.resourceResolveData.mimetype + + module.resourceResolveData.parameters; + } else if (ext) { + mimeType = mimeTypes.lookup(ext); + } + } + if (typeof mimeType !== "string") { + throw new Error( + "DataUrl can't be generated automatically, " + + `because there is no mimetype for "${ext}" in mimetype database. ` + + 'Either pass a mimetype via "generator.mimetype" or ' + + 'use type: "asset/resource" to create a resource file instead of a DataUrl' + ); + } + + let encodedContent; + + if ( + module.resourceResolveData && + module.resourceResolveData.encoding === encoding && + decodeDataUriContent( + module.resourceResolveData.encoding, + module.resourceResolveData.encodedContent + ).equals(originalSource.buffer()) + ) { + encodedContent = module.resourceResolveData.encodedContent; + } else { + encodedContent = encodeDataUri(encoding, originalSource); + } + + encodedSource = `data:${mimeType}${ + encoding ? `;${encoding}` : "" + },${encodedContent}`; + } + const data = getData(); + data.set("url", Buffer.from(encodedSource)); + return new RawSource( + `${RuntimeGlobals.module}.exports = ${JSON.stringify( + encodedSource + )};` + ); + } else { + const assetModuleFilename = + this.filename || runtimeTemplate.outputOptions.assetModuleFilename; + const hash = createHash(runtimeTemplate.outputOptions.hashFunction); + if (runtimeTemplate.outputOptions.hashSalt) { + hash.update(runtimeTemplate.outputOptions.hashSalt); + } + hash.update(originalSource.buffer()); + const fullHash = /** @type {string} */ ( + hash.digest(runtimeTemplate.outputOptions.hashDigest) + ); + const contentHash = fullHash.slice( + 0, + runtimeTemplate.outputOptions.hashDigestLength + ); + module.buildInfo.fullContentHash = fullHash; + const sourceFilename = makePathsRelative( + runtimeTemplate.compilation.compiler.context, + module.matchResource || module.resource, + runtimeTemplate.compilation.compiler.root + ).replace(/^\.\//, ""); + let { path: filename, info: assetInfo } = + runtimeTemplate.compilation.getAssetPathWithInfo( + assetModuleFilename, + { + module, + runtime, + filename: sourceFilename, + chunkGraph, + contentHash + } + ); + let assetPath; + if (this.publicPath !== undefined) { + const { path, info } = + runtimeTemplate.compilation.getAssetPathWithInfo( + this.publicPath, + { + module, + runtime, + filename: sourceFilename, + chunkGraph, + contentHash + } + ); + assetInfo = mergeAssetInfo(assetInfo, info); + assetPath = JSON.stringify(path + filename); + } else { + runtimeRequirements.add(RuntimeGlobals.publicPath); // add __webpack_require__.p + assetPath = runtimeTemplate.concatenation( + { expr: RuntimeGlobals.publicPath }, + filename + ); + } + assetInfo = { + sourceFilename, + ...assetInfo + }; + if (this.outputPath) { + const { path: outputPath, info } = + runtimeTemplate.compilation.getAssetPathWithInfo( + this.outputPath, + { + module, + runtime, + filename: sourceFilename, + chunkGraph, + contentHash + } + ); + assetInfo = mergeAssetInfo(assetInfo, info); + filename = path.posix.join(outputPath, filename); + } + module.buildInfo.filename = filename; + module.buildInfo.assetInfo = assetInfo; + if (getData) { + // Due to code generation caching module.buildInfo.XXX can't used to store such information + // It need to be stored in the code generation results instead, where it's cached too + // TODO webpack 6 For back-compat reasons we also store in on module.buildInfo + const data = getData(); + data.set("fullContentHash", fullHash); + data.set("filename", filename); + data.set("assetInfo", assetInfo); + } + + return new RawSource( + `${RuntimeGlobals.module}.exports = ${assetPath};` + ); + } + } + } + } -HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate extends ( - NullDependency.Template -) { /** - * @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} + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - apply(dependency, source, templateContext) { - const dep = /** @type {HarmonyExportHeaderDependency} */ (dependency); - const content = ""; - const replaceUntil = dep.range - ? dep.range[0] - 1 - : dep.rangeStatement[1] - 1; - source.replace(dep.rangeStatement[0], replaceUntil, content); + getTypes(module) { + if ((module.buildInfo && module.buildInfo.dataUrl) || this.emit === false) { + return JS_TYPES; + } else { + return JS_AND_ASSET_TYPES; + } } -}; -module.exports = HarmonyExportHeaderDependency; + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + switch (type) { + case "asset": { + const originalSource = module.originalSource(); + + if (!originalSource) { + return 0; + } + + return originalSource.size(); + } + default: + if (module.buildInfo && module.buildInfo.dataUrl) { + const originalSource = module.originalSource(); + + if (!originalSource) { + return 0; + } + + // roughly for data url + // Example: m.exports="data:image/png;base64,ag82/f+2==" + // 4/3 = base64 encoding + // 34 = ~ data url header + footer + rounding + return originalSource.size() * 1.34 + 36; + } else { + // it's only estimated so this number is probably fine + // Example: m.exports=r.p+"0123456789012345678901.ext" + return 42; + } + } + } + + /** + * @param {Hash} hash hash that will be modified + * @param {UpdateHashContext} updateHashContext context for updating hash + */ + updateHash(hash, { module }) { + hash.update(module.buildInfo.dataUrl ? "data-url" : "resource"); + } +} + +module.exports = AssetGenerator; /***/ }), -/***/ 67157: +/***/ 16109: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Yuta Hiroto @hiroppy */ -const Dependency = __webpack_require__(54912); -const { UsageState } = __webpack_require__(63686); -const HarmonyLinkingError = __webpack_require__(97511); -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const { countIterable } = __webpack_require__(39104); -const { first, combine } = __webpack_require__(93347); -const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const { getRuntimeKey, keyToRuntime } = __webpack_require__(17156); -const HarmonyExportInitFragment = __webpack_require__(89500); -const HarmonyImportDependency = __webpack_require__(57154); -const processExportInfo = __webpack_require__(55207); +const { cleverMerge } = __webpack_require__(60839); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); +const memoize = __webpack_require__(78676); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ExportsInfo")} ExportsInfo */ -/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ /** @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 {"missing"|"unused"|"empty-star"|"reexport-dynamic-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-fake-namespace-object"|"reexport-undefined"|"normal-reexport"|"dynamic-reexport"} ExportModeType */ - -const { ExportPresenceModes } = HarmonyImportDependency; +const getSchema = name => { + const { definitions } = __webpack_require__(73342); + return { + definitions, + oneOf: [{ $ref: `#/definitions/${name}` }] + }; +}; -const idsSymbol = Symbol("HarmonyExportImportedSpecifierDependency.ids"); +const generatorValidationOptions = { + name: "Asset Modules Plugin", + baseDataPath: "generator" +}; +const validateGeneratorOptions = { + asset: createSchemaValidation( + __webpack_require__(55125), + () => getSchema("AssetGeneratorOptions"), + generatorValidationOptions + ), + "asset/resource": createSchemaValidation( + __webpack_require__(4405), + () => getSchema("AssetResourceGeneratorOptions"), + generatorValidationOptions + ), + "asset/inline": createSchemaValidation( + __webpack_require__(62368), + () => getSchema("AssetInlineGeneratorOptions"), + generatorValidationOptions + ) +}; -class NormalReexportItem { - /** - * @param {string} name export name - * @param {string[]} ids reexported ids from other module - * @param {ExportInfo} exportInfo export info from other module - * @param {boolean} checked true, if it should be checked at runtime if this export exists - * @param {boolean} hidden true, if it is hidden behind another active export in the same module - */ - constructor(name, ids, exportInfo, checked, hidden) { - this.name = name; - this.ids = ids; - this.exportInfo = exportInfo; - this.checked = checked; - this.hidden = hidden; +const validateParserOptions = createSchemaValidation( + __webpack_require__(45020), + () => getSchema("AssetParserOptions"), + { + name: "Asset Modules Plugin", + baseDataPath: "parser" } -} +); -class ExportMode { +const getAssetGenerator = memoize(() => __webpack_require__(98421)); +const getAssetParser = memoize(() => __webpack_require__(91112)); +const getAssetSourceParser = memoize(() => __webpack_require__(30953)); +const getAssetSourceGenerator = memoize(() => + __webpack_require__(18749) +); + +const type = "asset"; +const plugin = "AssetModulesPlugin"; + +class AssetModulesPlugin { /** - * @param {ExportModeType} type type of the mode + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - constructor(type) { - /** @type {ExportModeType} */ - this.type = type; + apply(compiler) { + compiler.hooks.compilation.tap( + plugin, + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.createParser + .for("asset") + .tap(plugin, parserOptions => { + validateParserOptions(parserOptions); + parserOptions = cleverMerge( + compiler.options.module.parser.asset, + parserOptions + ); - // for "normal-reexport": - /** @type {NormalReexportItem[] | null} */ - this.items = null; + let dataUrlCondition = parserOptions.dataUrlCondition; + if (!dataUrlCondition || typeof dataUrlCondition === "object") { + dataUrlCondition = { + maxSize: 8096, + ...dataUrlCondition + }; + } - // for "reexport-named-default" | "reexport-fake-namespace-object" | "reexport-namespace-object" - /** @type {string|null} */ - this.name = null; - /** @type {ExportInfo | null} */ - this.partialNamespaceExportInfo = null; + const AssetParser = getAssetParser(); - // for "dynamic-reexport": - /** @type {Set | null} */ - this.ignored = null; + return new AssetParser(dataUrlCondition); + }); + normalModuleFactory.hooks.createParser + .for("asset/inline") + .tap(plugin, parserOptions => { + const AssetParser = getAssetParser(); - // for "dynamic-reexport" | "empty-star": - /** @type {Set | null} */ - this.hidden = null; + return new AssetParser(true); + }); + normalModuleFactory.hooks.createParser + .for("asset/resource") + .tap(plugin, parserOptions => { + const AssetParser = getAssetParser(); - // for "missing": - /** @type {string | null} */ - this.userRequest = null; + return new AssetParser(false); + }); + normalModuleFactory.hooks.createParser + .for("asset/source") + .tap(plugin, parserOptions => { + const AssetSourceParser = getAssetSourceParser(); - // for "reexport-fake-namespace-object": - /** @type {number} */ - this.fakeType = 0; - } -} + return new AssetSourceParser(); + }); -const determineExportAssignments = ( - moduleGraph, - dependencies, - additionalDependency -) => { - const names = new Set(); - const dependencyIndices = []; + for (const type of ["asset", "asset/inline", "asset/resource"]) { + normalModuleFactory.hooks.createGenerator + .for(type) + .tap(plugin, generatorOptions => { + validateGeneratorOptions[type](generatorOptions); - if (additionalDependency) { - dependencies = dependencies.concat(additionalDependency); - } + let dataUrl = undefined; + if (type !== "asset/resource") { + dataUrl = generatorOptions.dataUrl; + if (!dataUrl || typeof dataUrl === "object") { + dataUrl = { + encoding: undefined, + mimetype: undefined, + ...dataUrl + }; + } + } - for (const dep of dependencies) { - const i = dependencyIndices.length; - dependencyIndices[i] = names.size; - const otherImportedModule = moduleGraph.getModule(dep); - if (otherImportedModule) { - const exportsInfo = moduleGraph.getExportsInfo(otherImportedModule); - for (const exportInfo of exportsInfo.exports) { - if ( - exportInfo.provided === true && - exportInfo.name !== "default" && - !names.has(exportInfo.name) - ) { - names.add(exportInfo.name); - dependencyIndices[i] = names.size; - } - } - } - } - dependencyIndices.push(names.size); + let filename = undefined; + let publicPath = undefined; + let outputPath = undefined; + if (type !== "asset/inline") { + filename = generatorOptions.filename; + publicPath = generatorOptions.publicPath; + outputPath = generatorOptions.outputPath; + } - return { names: Array.from(names), dependencyIndices }; -}; + const AssetGenerator = getAssetGenerator(); -const findDependencyForName = ( - { names, dependencyIndices }, - name, - dependencies -) => { - const dependenciesIt = dependencies[Symbol.iterator](); - const dependencyIndicesIt = dependencyIndices[Symbol.iterator](); - let dependenciesItResult = dependenciesIt.next(); - let dependencyIndicesItResult = dependencyIndicesIt.next(); - if (dependencyIndicesItResult.done) return; - for (let i = 0; i < names.length; i++) { - while (i >= dependencyIndicesItResult.value) { - dependenciesItResult = dependenciesIt.next(); - dependencyIndicesItResult = dependencyIndicesIt.next(); - if (dependencyIndicesItResult.done) return; - } - if (names[i] === name) return dependenciesItResult.value; - } - return undefined; -}; + return new AssetGenerator( + dataUrl, + filename, + publicPath, + outputPath, + generatorOptions.emit !== false + ); + }); + } + normalModuleFactory.hooks.createGenerator + .for("asset/source") + .tap(plugin, () => { + const AssetSourceGenerator = getAssetSourceGenerator(); -/** - * @param {ModuleGraph} moduleGraph the module graph - * @param {HarmonyExportImportedSpecifierDependency} dep the dependency - * @param {string} runtimeKey the runtime key - * @returns {ExportMode} the export mode - */ -const getMode = (moduleGraph, dep, runtimeKey) => { - const importedModule = moduleGraph.getModule(dep); + return new AssetSourceGenerator(); + }); - if (!importedModule) { - const mode = new ExportMode("missing"); + compilation.hooks.renderManifest.tap(plugin, (result, options) => { + const { chunkGraph } = compilation; + const { chunk, codeGenerationResults } = options; - mode.userRequest = dep.userRequest; + const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "asset", + compareModulesByIdentifier + ); + if (modules) { + for (const module of modules) { + try { + const codeGenResult = codeGenerationResults.get( + module, + chunk.runtime + ); + result.push({ + render: () => codeGenResult.sources.get(type), + filename: + module.buildInfo.filename || + codeGenResult.data.get("filename"), + info: + module.buildInfo.assetInfo || + codeGenResult.data.get("assetInfo"), + auxiliary: true, + identifier: `assetModule${chunkGraph.getModuleId(module)}`, + hash: + module.buildInfo.fullContentHash || + codeGenResult.data.get("fullContentHash") + }); + } catch (e) { + e.message += `\nduring rendering of asset ${module.identifier()}`; + throw e; + } + } + } - return mode; - } + return result; + }); - const name = dep.name; - const runtime = keyToRuntime(runtimeKey); - const parentModule = moduleGraph.getParentModule(dep); - const exportsInfo = moduleGraph.getExportsInfo(parentModule); + compilation.hooks.prepareModuleExecution.tap( + "AssetModulesPlugin", + (options, context) => { + const { codeGenerationResult } = options; + const source = codeGenerationResult.sources.get("asset"); + if (source === undefined) return; + context.assets.set(codeGenerationResult.data.get("filename"), { + source, + info: codeGenerationResult.data.get("assetInfo") + }); + } + ); + } + ); + } +} - if ( - name - ? exportsInfo.getUsed(name, runtime) === UsageState.Unused - : exportsInfo.isUsed(runtime) === false - ) { - const mode = new ExportMode("unused"); +module.exports = AssetModulesPlugin; - mode.name = name || "*"; - return mode; - } +/***/ }), - const importedExportsType = importedModule.getExportsType( - moduleGraph, - parentModule.buildMeta.strictHarmonyModule - ); +/***/ 91112: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const ids = dep.getIds(moduleGraph); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Yuta Hiroto @hiroppy +*/ - // Special handling for reexporting the default export - // from non-namespace modules - if (name && ids.length > 0 && ids[0] === "default") { - switch (importedExportsType) { - case "dynamic": { - const mode = new ExportMode("reexport-dynamic-default"); - mode.name = name; - return mode; - } - case "default-only": - case "default-with-named": { - const exportInfo = exportsInfo.getReadOnlyExportInfo(name); - const mode = new ExportMode("reexport-named-default"); +const Parser = __webpack_require__(11715); - mode.name = name; - mode.partialNamespaceExportInfo = exportInfo; +/** @typedef {import("../../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ - return mode; - } - } +class AssetParser extends Parser { + /** + * @param {AssetParserOptions["dataUrlCondition"] | boolean} dataUrlCondition condition for inlining as DataUrl + */ + constructor(dataUrlCondition) { + super(); + this.dataUrlCondition = dataUrlCondition; } - // reexporting with a fixed name - if (name) { - let mode; - const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (typeof source === "object" && !Buffer.isBuffer(source)) { + throw new Error("AssetParser doesn't accept preparsed AST"); + } + state.module.buildInfo.strict = true; + state.module.buildMeta.exportsType = "default"; - if (ids.length > 0) { - // export { name as name } - switch (importedExportsType) { - case "default-only": - mode = new ExportMode("reexport-undefined"); - mode.name = name; - break; - default: - mode = new ExportMode("normal-reexport"); - mode.items = [ - new NormalReexportItem(name, ids, exportInfo, false, false) - ]; - break; - } + if (typeof this.dataUrlCondition === "function") { + state.module.buildInfo.dataUrl = this.dataUrlCondition(source, { + filename: state.module.matchResource || state.module.resource, + module: state.module + }); + } else if (typeof this.dataUrlCondition === "boolean") { + state.module.buildInfo.dataUrl = this.dataUrlCondition; + } else if ( + this.dataUrlCondition && + typeof this.dataUrlCondition === "object" + ) { + state.module.buildInfo.dataUrl = + Buffer.byteLength(source) <= this.dataUrlCondition.maxSize; } else { - // export * as name - switch (importedExportsType) { - case "default-only": - mode = new ExportMode("reexport-fake-namespace-object"); - mode.name = name; - mode.partialNamespaceExportInfo = exportInfo; - mode.fakeType = 0; - break; - case "default-with-named": - mode = new ExportMode("reexport-fake-namespace-object"); - mode.name = name; - mode.partialNamespaceExportInfo = exportInfo; - mode.fakeType = 2; - break; - case "dynamic": - default: - mode = new ExportMode("reexport-namespace-object"); - mode.name = name; - mode.partialNamespaceExportInfo = exportInfo; - } + throw new Error("Unexpected dataUrlCondition type"); } - return mode; + return state; } +} - // Star reexporting - - const { ignoredExports, exports, checked, hidden } = dep.getStarReexports( - moduleGraph, - runtime, - exportsInfo, - importedModule - ); - if (!exports) { - // We have too few info about the modules - // Delegate the logic to the runtime code +module.exports = AssetParser; - const mode = new ExportMode("dynamic-reexport"); - mode.ignored = ignoredExports; - mode.hidden = hidden; - return mode; - } +/***/ }), - if (exports.size === 0) { - const mode = new ExportMode("empty-star"); - mode.hidden = hidden; +/***/ 18749: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return mode; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ - const mode = new ExportMode("normal-reexport"); - mode.items = Array.from( - exports, - exportName => - new NormalReexportItem( - exportName, - [exportName], - exportsInfo.getReadOnlyExportInfo(exportName), - checked.has(exportName), - false - ) - ); - if (hidden !== undefined) { - for (const exportName of hidden) { - mode.items.push( - new NormalReexportItem( - exportName, - [exportName], - exportsInfo.getReadOnlyExportInfo(exportName), - false, - true - ) - ); - } - } - return mode; -}; +const { RawSource } = __webpack_require__(51255); +const Generator = __webpack_require__(93401); +const RuntimeGlobals = __webpack_require__(16475); -class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { - /** - * @param {string} request the request string - * @param {number} sourceOrder the order in the original source file - * @param {string[]} ids the requested export name of the imported module - * @param {string | null} name the export name of for this module - * @param {Set} activeExports other named exports in the module - * @param {ReadonlyArray | Iterable} otherStarExports other star exports in the module before this import - * @param {number} exportPresenceMode mode of checking export names - * @param {HarmonyStarExportsList} allStarExports all star exports in the module - * @param {Record=} assertions import assertions - */ - constructor( - request, - sourceOrder, - ids, - name, - activeExports, - otherStarExports, - exportPresenceMode, - allStarExports, - assertions - ) { - super(request, sourceOrder, assertions); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../NormalModule")} NormalModule */ - this.ids = ids; - this.name = name; - this.activeExports = activeExports; - this.otherStarExports = otherStarExports; - this.exportPresenceMode = exportPresenceMode; - this.allStarExports = allStarExports; - } +const TYPES = new Set(["javascript"]); +class AssetSourceGenerator extends Generator { /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code */ - couldAffectReferencingModule() { - return Dependency.TRANSITIVE; - } + generate(module, { chunkGraph, runtimeTemplate, runtimeRequirements }) { + runtimeRequirements.add(RuntimeGlobals.module); - // TODO webpack 6 remove - get id() { - throw new Error("id was renamed to ids and type changed to string[]"); - } + const originalSource = module.originalSource(); - // TODO webpack 6 remove - getId() { - throw new Error("id was renamed to ids and type changed to string[]"); - } + if (!originalSource) { + return new RawSource(""); + } - // TODO webpack 6 remove - setId() { - throw new Error("id was renamed to ids and type changed to string[]"); - } + const content = originalSource.source(); - get type() { - return "harmony export imported specifier"; + let encodedSource; + if (typeof content === "string") { + encodedSource = content; + } else { + encodedSource = content.toString("utf-8"); + } + return new RawSource( + `${RuntimeGlobals.module}.exports = ${JSON.stringify(encodedSource)};` + ); } /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {string[]} the imported id + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - getIds(moduleGraph) { - return moduleGraph.getMeta(this)[idsSymbol] || this.ids; + getTypes(module) { + return TYPES; } /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {string[]} ids the imported ids - * @returns {void} + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - setIds(moduleGraph, ids) { - moduleGraph.getMeta(this)[idsSymbol] = ids; - } + getSize(module, type) { + const originalSource = module.originalSource(); - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {RuntimeSpec} runtime the runtime - * @returns {ExportMode} the export mode - */ - getMode(moduleGraph, runtime) { - return moduleGraph.dependencyCacheProvide( - this, - getRuntimeKey(runtime), - getMode - ); + if (!originalSource) { + return 0; + } + + // Example: m.exports="abcd" + return originalSource.size() + 12; } +} - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {RuntimeSpec} runtime the runtime - * @param {ExportsInfo} exportsInfo exports info about the current module (optional) - * @param {Module} importedModule the imported module (optional) - * @returns {{exports?: Set, checked?: Set, ignoredExports: Set, hidden?: Set}} information - */ - getStarReexports( - moduleGraph, - runtime, - exportsInfo = moduleGraph.getExportsInfo(moduleGraph.getParentModule(this)), - importedModule = moduleGraph.getModule(this) - ) { - const importedExportsInfo = moduleGraph.getExportsInfo(importedModule); - - const noExtraExports = - importedExportsInfo.otherExportsInfo.provided === false; - const noExtraImports = - exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused; +module.exports = AssetSourceGenerator; - const ignoredExports = new Set(["default", ...this.activeExports]); - let hiddenExports = undefined; - const otherStarExports = - this._discoverActiveExportsFromOtherStarExports(moduleGraph); - if (otherStarExports !== undefined) { - hiddenExports = new Set(); - for (let i = 0; i < otherStarExports.namesSlice; i++) { - hiddenExports.add(otherStarExports.names[i]); - } - for (const e of ignoredExports) hiddenExports.delete(e); - } +/***/ }), - if (!noExtraExports && !noExtraImports) { - return { - ignoredExports, - hidden: hiddenExports - }; - } +/***/ 30953: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {Set} */ - const exports = new Set(); - /** @type {Set} */ - const checked = new Set(); - /** @type {Set} */ - const hidden = hiddenExports !== undefined ? new Set() : undefined; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Yuta Hiroto @hiroppy +*/ - if (noExtraImports) { - for (const exportInfo of exportsInfo.orderedExports) { - const name = exportInfo.name; - if (ignoredExports.has(name)) continue; - if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; - const importedExportInfo = - importedExportsInfo.getReadOnlyExportInfo(name); - if (importedExportInfo.provided === false) continue; - if (hiddenExports !== undefined && hiddenExports.has(name)) { - hidden.add(name); - continue; - } - exports.add(name); - if (importedExportInfo.provided === true) continue; - checked.add(name); - } - } else if (noExtraExports) { - for (const importedExportInfo of importedExportsInfo.orderedExports) { - const name = importedExportInfo.name; - if (ignoredExports.has(name)) continue; - if (importedExportInfo.provided === false) continue; - const exportInfo = exportsInfo.getReadOnlyExportInfo(name); - if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; - if (hiddenExports !== undefined && hiddenExports.has(name)) { - hidden.add(name); - continue; - } - exports.add(name); - if (importedExportInfo.provided === true) continue; - checked.add(name); - } - } - return { ignoredExports, exports, checked, hidden }; - } - /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active - */ - getCondition(moduleGraph) { - return (connection, runtime) => { - const mode = this.getMode(moduleGraph, runtime); - return mode.type !== "unused" && mode.type !== "empty-star"; - }; - } +const Parser = __webpack_require__(11715); - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules - */ - getModuleEvaluationSideEffectsState(moduleGraph) { - return false; - } +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ +class AssetSourceParser extends Parser { /** - * 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 + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state */ - getReferencedExports(moduleGraph, runtime) { - const mode = this.getMode(moduleGraph, runtime); - - switch (mode.type) { - case "missing": - case "unused": - case "empty-star": - case "reexport-undefined": - return Dependency.NO_EXPORTS_REFERENCED; - - case "reexport-dynamic-default": - return Dependency.EXPORTS_OBJECT_REFERENCED; + parse(source, state) { + if (typeof source === "object" && !Buffer.isBuffer(source)) { + throw new Error("AssetSourceParser doesn't accept preparsed AST"); + } + const { module } = state; + module.buildInfo.strict = true; + module.buildMeta.exportsType = "default"; - case "reexport-named-default": { - if (!mode.partialNamespaceExportInfo) - return Dependency.EXPORTS_OBJECT_REFERENCED; - /** @type {string[][]} */ - const referencedExports = []; - processExportInfo( - runtime, - referencedExports, - [], - /** @type {ExportInfo} */ (mode.partialNamespaceExportInfo) - ); - return referencedExports; - } + return state; + } +} - case "reexport-namespace-object": - case "reexport-fake-namespace-object": { - if (!mode.partialNamespaceExportInfo) - return Dependency.EXPORTS_OBJECT_REFERENCED; - /** @type {string[][]} */ - const referencedExports = []; - processExportInfo( - runtime, - referencedExports, - [], - /** @type {ExportInfo} */ (mode.partialNamespaceExportInfo), - mode.type === "reexport-fake-namespace-object" - ); - return referencedExports; - } +module.exports = AssetSourceParser; - case "dynamic-reexport": - return Dependency.EXPORTS_OBJECT_REFERENCED; - case "normal-reexport": { - const referencedExports = []; - for (const { ids, exportInfo, hidden } of mode.items) { - if (hidden) continue; - processExportInfo(runtime, referencedExports, ids, exportInfo, false); - } - return referencedExports; - } +/***/ }), - default: - throw new Error(`Unknown mode ${mode.type}`); - } - } +/***/ 19684: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {{ names: string[], namesSlice: number, dependencyIndices: number[], dependencyIndex: number } | undefined} exported names and their origin dependency - */ - _discoverActiveExportsFromOtherStarExports(moduleGraph) { - if (!this.otherStarExports) return undefined; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const i = - "length" in this.otherStarExports - ? this.otherStarExports.length - : countIterable(this.otherStarExports); - if (i === 0) return undefined; - if (this.allStarExports) { - const { names, dependencyIndices } = moduleGraph.cached( - determineExportAssignments, - this.allStarExports.dependencies - ); - return { - names, - namesSlice: dependencyIndices[i - 1], - dependencyIndices, - dependencyIndex: i - }; - } +const { RawSource } = __webpack_require__(51255); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); - const { names, dependencyIndices } = moduleGraph.cached( - determineExportAssignments, - this.otherStarExports, - this - ); +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ - return { - names, - namesSlice: dependencyIndices[i - 1], - dependencyIndices, - dependencyIndex: i - }; - } +const TYPES = new Set(["javascript"]); +class RawDataUrlModule extends Module { /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names + * @param {string} url raw url + * @param {string} identifier unique identifier + * @param {string=} readableIdentifier readable identifier */ - getExports(moduleGraph) { - const mode = this.getMode(moduleGraph, undefined); - - switch (mode.type) { - case "missing": - return undefined; - case "dynamic-reexport": { - const from = moduleGraph.getConnection(this); - return { - exports: true, - from, - canMangle: false, - excludeExports: mode.hidden - ? combine(mode.ignored, mode.hidden) - : mode.ignored, - hideExports: mode.hidden, - dependencies: [from.module] - }; - } - case "empty-star": - return { - exports: [], - hideExports: mode.hidden, - dependencies: [moduleGraph.getModule(this)] - }; - // falls through - case "normal-reexport": { - const from = moduleGraph.getConnection(this); - return { - exports: Array.from(mode.items, item => ({ - name: item.name, - from, - export: item.ids, - hidden: item.hidden - })), - priority: 1, - dependencies: [from.module] - }; - } - case "reexport-dynamic-default": { - { - const from = moduleGraph.getConnection(this); - return { - exports: [ - { - name: mode.name, - from, - export: ["default"] - } - ], - priority: 1, - dependencies: [from.module] - }; - } - } - case "reexport-undefined": - return { - exports: [mode.name], - dependencies: [moduleGraph.getModule(this)] - }; - case "reexport-fake-namespace-object": { - const from = moduleGraph.getConnection(this); - return { - exports: [ - { - name: mode.name, - from, - export: null, - exports: [ - { - name: "default", - canMangle: false, - from, - export: null - } - ] - } - ], - priority: 1, - dependencies: [from.module] - }; - } - case "reexport-namespace-object": { - const from = moduleGraph.getConnection(this); - return { - exports: [ - { - name: mode.name, - from, - export: null - } - ], - priority: 1, - dependencies: [from.module] - }; - } - case "reexport-named-default": { - const from = moduleGraph.getConnection(this); - return { - exports: [ - { - name: mode.name, - from, - export: ["default"] - } - ], - priority: 1, - dependencies: [from.module] - }; - } - default: - throw new Error(`Unknown mode ${mode.type}`); - } + constructor(url, identifier, readableIdentifier) { + super("asset/raw-data-url", null); + this.url = url; + this.urlBuffer = url ? Buffer.from(url) : undefined; + this.identifierStr = identifier || this.url; + this.readableIdentifierStr = readableIdentifier || this.identifierStr; } /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {number} effective mode + * @returns {Set} types available (do not mutate) */ - _getEffectiveExportPresenceLevel(moduleGraph) { - if (this.exportPresenceMode !== ExportPresenceModes.AUTO) - return this.exportPresenceMode; - return moduleGraph.getParentModule(this).buildMeta.strictHarmonyModule - ? ExportPresenceModes.ERROR - : ExportPresenceModes.WARN; + getSourceTypes() { + return TYPES; } /** - * Returns warnings - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} warnings + * @returns {string} a unique identifier of the module */ - getWarnings(moduleGraph) { - const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); - if (exportsPresence === ExportPresenceModes.WARN) { - return this._getErrors(moduleGraph); - } - return null; + identifier() { + return this.identifierStr; } /** - * Returns errors - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} errors + * @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) */ - getErrors(moduleGraph) { - const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); - if (exportsPresence === ExportPresenceModes.ERROR) { - return this._getErrors(moduleGraph); - } - return null; + size(type) { + if (this.url === undefined) this.url = this.urlBuffer.toString(); + return Math.max(1, this.url.length); } /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[] | undefined} errors + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module */ - _getErrors(moduleGraph) { - const ids = this.getIds(moduleGraph); - let errors = this.getLinkingErrors( - moduleGraph, - ids, - `(reexported as '${this.name}')` - ); - if (ids.length === 0 && this.name === null) { - const potentialConflicts = - this._discoverActiveExportsFromOtherStarExports(moduleGraph); - if (potentialConflicts && potentialConflicts.namesSlice > 0) { - const ownNames = new Set( - potentialConflicts.names.slice( - potentialConflicts.namesSlice, - potentialConflicts.dependencyIndices[ - potentialConflicts.dependencyIndex - ] - ) - ); - const importedModule = moduleGraph.getModule(this); - if (importedModule) { - const exportsInfo = moduleGraph.getExportsInfo(importedModule); - const conflicts = new Map(); - for (const exportInfo of exportsInfo.orderedExports) { - if (exportInfo.provided !== true) continue; - if (exportInfo.name === "default") continue; - if (this.activeExports.has(exportInfo.name)) continue; - if (ownNames.has(exportInfo.name)) continue; - const conflictingDependency = findDependencyForName( - potentialConflicts, - exportInfo.name, - this.allStarExports - ? this.allStarExports.dependencies - : [...this.otherStarExports, this] - ); - if (!conflictingDependency) continue; - const target = exportInfo.getTerminalBinding(moduleGraph); - if (!target) continue; - const conflictingModule = moduleGraph.getModule( - conflictingDependency - ); - if (conflictingModule === importedModule) continue; - const conflictingExportInfo = moduleGraph.getExportInfo( - conflictingModule, - exportInfo.name - ); - const conflictingTarget = - conflictingExportInfo.getTerminalBinding(moduleGraph); - if (!conflictingTarget) continue; - if (target === conflictingTarget) continue; - const list = conflicts.get(conflictingDependency.request); - if (list === undefined) { - conflicts.set(conflictingDependency.request, [exportInfo.name]); - } else { - list.push(exportInfo.name); - } - } - for (const [request, exports] of conflicts) { - if (!errors) errors = []; - errors.push( - new HarmonyLinkingError( - `The requested module '${ - this.request - }' contains conflicting star exports for the ${ - exports.length > 1 ? "names" : "name" - } ${exports - .map(e => `'${e}'`) - .join(", ")} with the previous requested module '${request}'` - ) - ); - } - } - } - } - return errors; - } - - serialize(context) { - const { write, setCircularReference } = context; - - setCircularReference(this); - write(this.ids); - write(this.name); - write(this.activeExports); - write(this.otherStarExports); - write(this.exportPresenceMode); - write(this.allStarExports); - - super.serialize(context); + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.readableIdentifierStr); } - deserialize(context) { - const { read, setCircularReference } = context; - - setCircularReference(this); - this.ids = read(); - this.name = read(); - this.activeExports = read(); - this.otherStarExports = read(); - this.exportPresenceMode = read(); - this.allStarExports = read(); - - super.deserialize(context); + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, !this.buildMeta); } -} - -makeSerializable( - HarmonyExportImportedSpecifierDependency, - "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency" -); -module.exports = HarmonyExportImportedSpecifierDependency; - -HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate extends ( - HarmonyImportDependency.Template -) { /** - * @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 + * @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} */ - apply(dependency, source, templateContext) { - const { moduleGraph, runtime, concatenationScope } = templateContext; + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = { + cacheable: true + }; + callback(); + } - const dep = /** @type {HarmonyExportImportedSpecifierDependency} */ ( - dependency + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration(context) { + if (this.url === undefined) this.url = this.urlBuffer.toString(); + const sources = new Map(); + sources.set( + "javascript", + new RawSource(`module.exports = ${JSON.stringify(this.url)};`) ); - - const mode = dep.getMode(moduleGraph, runtime); - - if (concatenationScope) { - switch (mode.type) { - case "reexport-undefined": - concatenationScope.registerRawExport( - mode.name, - "/* reexport non-default export from non-harmony */ undefined" - ); - } - return; - } - - if (mode.type !== "unused" && mode.type !== "empty-star") { - super.apply(dependency, source, templateContext); - - this._addExportFragments( - templateContext.initFragments, - dep, - mode, - templateContext.module, - moduleGraph, - runtime, - templateContext.runtimeTemplate, - templateContext.runtimeRequirements - ); - } + const data = new Map(); + data.set("url", this.urlBuffer); + const runtimeRequirements = new Set(); + runtimeRequirements.add(RuntimeGlobals.module); + return { sources, runtimeRequirements, data }; } /** - * @param {InitFragment[]} initFragments target array for init fragments - * @param {HarmonyExportImportedSpecifierDependency} dep dependency - * @param {ExportMode} mode the export mode - * @param {Module} module the current module - * @param {ModuleGraph} moduleGraph the module graph - * @param {RuntimeSpec} runtime the runtime - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {Set} runtimeRequirements runtime requirements + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context * @returns {void} */ - _addExportFragments( - initFragments, - dep, - mode, - module, - moduleGraph, - runtime, - runtimeTemplate, - runtimeRequirements - ) { - const importedModule = moduleGraph.getModule(dep); - const importVar = dep.getImportVar(moduleGraph); - - switch (mode.type) { - case "missing": - case "empty-star": - initFragments.push( - new InitFragment( - "/* empty/unused harmony star reexport */\n", - InitFragment.STAGE_HARMONY_EXPORTS, - 1 - ) - ); - break; - - case "unused": - initFragments.push( - new InitFragment( - `${Template.toNormalComment( - `unused harmony reexport ${mode.name}` - )}\n`, - InitFragment.STAGE_HARMONY_EXPORTS, - 1 - ) - ); - break; - - case "reexport-dynamic-default": - initFragments.push( - this.getReexportFragment( - module, - "reexport default from dynamic", - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), - importVar, - null, - runtimeRequirements - ) - ); - break; + updateHash(hash, context) { + hash.update(this.urlBuffer); + super.updateHash(hash, context); + } - case "reexport-fake-namespace-object": - initFragments.push( - ...this.getReexportFakeNamespaceObjectFragments( - module, - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), - importVar, - mode.fakeType, - runtimeRequirements - ) - ); - break; + serialize(context) { + const { write } = context; - case "reexport-undefined": - initFragments.push( - this.getReexportFragment( - module, - "reexport non-default export from non-harmony", - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), - "undefined", - "", - runtimeRequirements - ) - ); - break; + write(this.urlBuffer); + write(this.identifierStr); + write(this.readableIdentifierStr); - case "reexport-named-default": - initFragments.push( - this.getReexportFragment( - module, - "reexport default export from named module", - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), - importVar, - "", - runtimeRequirements - ) - ); - break; + super.serialize(context); + } - case "reexport-namespace-object": - initFragments.push( - this.getReexportFragment( - module, - "reexport module object", - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), - importVar, - "", - runtimeRequirements - ) - ); - break; + deserialize(context) { + const { read } = context; - case "normal-reexport": - for (const { name, ids, checked, hidden } of mode.items) { - if (hidden) continue; - if (checked) { - initFragments.push( - new InitFragment( - "/* harmony reexport (checked) */ " + - this.getConditionalReexportStatement( - module, - name, - importVar, - ids, - runtimeRequirements - ), - moduleGraph.isAsync(importedModule) - ? InitFragment.STAGE_ASYNC_HARMONY_IMPORTS - : InitFragment.STAGE_HARMONY_IMPORTS, - dep.sourceOrder - ) - ); - } else { - initFragments.push( - this.getReexportFragment( - module, - "reexport safe", - moduleGraph.getExportsInfo(module).getUsedName(name, runtime), - importVar, - moduleGraph - .getExportsInfo(importedModule) - .getUsedName(ids, runtime), - runtimeRequirements - ) - ); - } - } - break; + this.urlBuffer = read(); + this.identifierStr = read(); + this.readableIdentifierStr = read(); - case "dynamic-reexport": { - const ignored = mode.hidden - ? combine(mode.ignored, mode.hidden) - : mode.ignored; - const modern = - runtimeTemplate.supportsConst() && - runtimeTemplate.supportsArrowFunction(); - let content = - "/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {};\n" + - `/* harmony reexport (unknown) */ for(${ - modern ? "const" : "var" - } __WEBPACK_IMPORT_KEY__ in ${importVar}) `; + super.deserialize(context); + } +} - // Filter out exports which are defined by other exports - // and filter out default export because it cannot be reexported with * - if (ignored.size > 1) { - content += - "if(" + - JSON.stringify(Array.from(ignored)) + - ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) "; - } else if (ignored.size === 1) { - content += `if(__WEBPACK_IMPORT_KEY__ !== ${JSON.stringify( - first(ignored) - )}) `; - } +makeSerializable(RawDataUrlModule, "webpack/lib/asset/RawDataUrlModule"); - content += `__WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = `; - if (modern) { - content += `() => ${importVar}[__WEBPACK_IMPORT_KEY__]`; - } else { - content += `function(key) { return ${importVar}[key]; }.bind(0, __WEBPACK_IMPORT_KEY__)`; - } +module.exports = RawDataUrlModule; - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - const exportsName = module.exportsArgument; - initFragments.push( - new InitFragment( - `${content}\n/* harmony reexport (unknown) */ ${RuntimeGlobals.definePropertyGetters}(${exportsName}, __WEBPACK_REEXPORT_OBJECT__);\n`, - moduleGraph.isAsync(importedModule) - ? InitFragment.STAGE_ASYNC_HARMONY_IMPORTS - : InitFragment.STAGE_HARMONY_IMPORTS, - dep.sourceOrder - ) - ); - break; - } +/***/ }), - default: - throw new Error(`Unknown mode ${mode.type}`); - } - } +/***/ 41153: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - getReexportFragment( - module, - comment, - key, - name, - valueKey, - runtimeRequirements - ) { - const returnValue = this.getReturnValue(name, valueKey); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - const map = new Map(); - map.set(key, `/* ${comment} */ ${returnValue}`); - return new HarmonyExportInitFragment(module.exportsArgument, map); - } +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); - getReexportFakeNamespaceObjectFragments( - module, - key, - name, - fakeType, - runtimeRequirements - ) { - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ - const map = new Map(); - map.set( - key, - `/* reexport fake namespace object from non-harmony */ ${name}_namespace_cache || (${name}_namespace_cache = ${ - RuntimeGlobals.createFakeNamespaceObject - }(${name}${fakeType ? `, ${fakeType}` : ""}))` +/** + * @typedef {GenerateContext} Context + */ +class AwaitDependenciesInitFragment extends InitFragment { + /** + * @param {Set} promises the promises that should be awaited + */ + constructor(promises) { + super( + undefined, + InitFragment.STAGE_ASYNC_DEPENDENCIES, + 0, + "await-dependencies" ); + this.promises = promises; + } - return [ - new InitFragment( - `var ${name}_namespace_cache;\n`, - InitFragment.STAGE_CONSTANTS, - -1, - `${name}_namespace_cache` - ), - new HarmonyExportInitFragment(module.exportsArgument, map) - ]; + merge(other) { + const promises = new Set(this.promises); + for (const p of other.promises) { + promises.add(p); + } + return new AwaitDependenciesInitFragment(promises); } - getConditionalReexportStatement( - module, - key, - name, - valueKey, - runtimeRequirements - ) { - if (valueKey === false) { - return "/* unused export */\n"; + /** + * @param {Context} context context + * @returns {string|Source} the source code that will be included as initialization code + */ + getContent({ runtimeRequirements }) { + runtimeRequirements.add(RuntimeGlobals.module); + const promises = this.promises; + if (promises.size === 0) { + return ""; + } + if (promises.size === 1) { + for (const p of promises) { + return Template.asString([ + `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${p}]);`, + `${p} = (__webpack_async_dependencies__.then ? await __webpack_async_dependencies__ : __webpack_async_dependencies__)[0];`, + "" + ]); + } } + const sepPromises = Array.from(promises).join(", "); + // TODO check if destructuring is supported + return Template.asString([ + `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${sepPromises}]);`, + `([${sepPromises}] = __webpack_async_dependencies__.then ? await __webpack_async_dependencies__ : __webpack_async_dependencies__);`, + "" + ]); + } +} - const exportsName = module.exportsArgument; - const returnValue = this.getReturnValue(name, valueKey); +module.exports = AwaitDependenciesInitFragment; - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - runtimeRequirements.add(RuntimeGlobals.hasOwnProperty); - return `if(${RuntimeGlobals.hasOwnProperty}(${name}, ${JSON.stringify( - valueKey[0] - )})) ${ - RuntimeGlobals.definePropertyGetters - }(${exportsName}, { ${JSON.stringify( - key - )}: function() { return ${returnValue}; } });\n`; - } +/***/ }), - getReturnValue(name, valueKey) { - if (valueKey === null) { - return `${name}_default.a`; - } +/***/ 59498: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (valueKey === "") { - return name; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (valueKey === false) { - return "/* unused export */ undefined"; - } - return `${name}${propertyAccess(valueKey)}`; - } -}; -class HarmonyStarExportsList { - constructor() { - /** @type {HarmonyExportImportedSpecifierDependency[]} */ - this.dependencies = []; - } +const HarmonyImportDependency = __webpack_require__(57154); +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +class InferAsyncModulesPlugin { /** - * @param {HarmonyExportImportedSpecifierDependency} dep dependency + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - push(dep) { - this.dependencies.push(dep); - } - - slice() { - return this.dependencies.slice(); - } - - serialize({ write, setCircularReference }) { - setCircularReference(this); - write(this.dependencies); - } - - deserialize({ read, setCircularReference }) { - setCircularReference(this); - this.dependencies = read(); + apply(compiler) { + compiler.hooks.compilation.tap("InferAsyncModulesPlugin", compilation => { + const { moduleGraph } = compilation; + compilation.hooks.finishModules.tap( + "InferAsyncModulesPlugin", + modules => { + /** @type {Set} */ + const queue = new Set(); + for (const module of modules) { + if (module.buildMeta && module.buildMeta.async) { + queue.add(module); + } + } + for (const module of queue) { + moduleGraph.setAsync(module); + for (const [ + originModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if ( + connections.some( + c => + c.dependency instanceof HarmonyImportDependency && + c.isTargetActive(undefined) + ) + ) { + queue.add(originModule); + } + } + } + } + ); + }); } } -makeSerializable( - HarmonyStarExportsList, - "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency", - "HarmonyStarExportsList" -); - -module.exports.HarmonyStarExportsList = HarmonyStarExportsList; +module.exports = InferAsyncModulesPlugin; /***/ }), -/***/ 89500: +/***/ 79233: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -78327,704 +71943,1406 @@ module.exports.HarmonyStarExportsList = HarmonyStarExportsList; -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const { first } = __webpack_require__(93347); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +const AsyncDependencyToInitialChunkError = __webpack_require__(30111); +const { connectChunkGroupParentAndChild } = __webpack_require__(37234); +const ModuleGraphConnection = __webpack_require__(40639); +const { getEntryRuntime, mergeRuntime } = __webpack_require__(17156); -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; -}; +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Entrypoint")} Entrypoint */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./logging/Logger").Logger} Logger */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ -const EMPTY_MAP = new Map(); -const EMPTY_SET = new Set(); +/** + * @typedef {Object} QueueItem + * @property {number} action + * @property {DependenciesBlock} block + * @property {Module} module + * @property {Chunk} chunk + * @property {ChunkGroup} chunkGroup + * @property {ChunkGroupInfo} chunkGroupInfo + */ + +/** @typedef {Set & { plus: Set }} ModuleSetPlus */ /** - * @typedef {GenerateContext} Context + * @typedef {Object} ChunkGroupInfo + * @property {ChunkGroup} chunkGroup the chunk group + * @property {RuntimeSpec} runtime the runtimes + * @property {ModuleSetPlus} minAvailableModules current minimal set of modules available at this point + * @property {boolean} minAvailableModulesOwned true, if minAvailableModules is owned and can be modified + * @property {ModuleSetPlus[]} availableModulesToBeMerged enqueued updates to the minimal set of available modules + * @property {Set=} skippedItems modules that were skipped because module is already available in parent chunks (need to reconsider when minAvailableModules is shrinking) + * @property {Set<[Module, ConnectionState]>=} skippedModuleConnections referenced modules that where skipped because they were not active in this runtime + * @property {ModuleSetPlus} resultingAvailableModules set of modules available including modules from this chunk group + * @property {Set} children set of children chunk groups, that will be revisited when availableModules shrink + * @property {Set} availableSources set of chunk groups that are the source for minAvailableModules + * @property {Set} availableChildren set of chunk groups which depend on the this chunk group as availableSource + * @property {number} preOrderIndex next pre order index + * @property {number} postOrderIndex next post order index + * @property {boolean} chunkLoading has a chunk loading mechanism + * @property {boolean} asyncChunks create async chunks */ -class HarmonyExportInitFragment extends InitFragment { - /** - * @param {string} exportsArgument the exports identifier - * @param {Map} exportMap mapping from used name to exposed variable name - * @param {Set} unusedExports list of unused export names - */ - constructor( - exportsArgument, - exportMap = EMPTY_MAP, - unusedExports = EMPTY_SET - ) { - super(undefined, InitFragment.STAGE_HARMONY_EXPORTS, 1, "harmony-exports"); - this.exportsArgument = exportsArgument; - this.exportMap = exportMap; - this.unusedExports = unusedExports; + +/** + * @typedef {Object} BlockChunkGroupConnection + * @property {ChunkGroupInfo} originChunkGroupInfo origin chunk group + * @property {ChunkGroup} chunkGroup referenced chunk group + */ + +const EMPTY_SET = /** @type {ModuleSetPlus} */ (new Set()); +EMPTY_SET.plus = EMPTY_SET; + +/** + * @param {ModuleSetPlus} a first set + * @param {ModuleSetPlus} b second set + * @returns {number} cmp + */ +const bySetSize = (a, b) => { + return b.size + b.plus.size - a.size - a.plus.size; +}; + +const extractBlockModules = (module, moduleGraph, runtime, blockModulesMap) => { + let blockCache; + let modules; + + const arrays = []; + + const queue = [module]; + while (queue.length > 0) { + const block = queue.pop(); + const arr = []; + arrays.push(arr); + blockModulesMap.set(block, arr); + for (const b of block.blocks) { + queue.push(b); + } } - /** - * @param {HarmonyExportInitFragment[]} fragments all fragments to merge - * @returns {HarmonyExportInitFragment} merged fragment - */ - mergeAll(fragments) { - let exportMap; - let exportMapOwned = false; - let unusedExports; - let unusedExportsOwned = false; + for (const connection of moduleGraph.getOutgoingConnections(module)) { + const d = connection.dependency; + // We skip connections without dependency + if (!d) continue; + const m = connection.module; + // We skip connections without Module pointer + if (!m) continue; + // We skip weak connections + if (connection.weak) continue; + const state = connection.getActiveState(runtime); + // We skip inactive connections + if (state === false) continue; - for (const fragment of fragments) { - if (fragment.exportMap.size !== 0) { - if (exportMap === undefined) { - exportMap = fragment.exportMap; - exportMapOwned = false; - } else { - if (!exportMapOwned) { - exportMap = new Map(exportMap); - exportMapOwned = true; + const block = moduleGraph.getParentBlock(d); + let index = moduleGraph.getParentBlockIndex(d); + + // deprecated fallback + if (index < 0) { + index = block.dependencies.indexOf(d); + } + + if (blockCache !== block) { + modules = blockModulesMap.get((blockCache = block)); + } + + const i = index << 2; + modules[i] = m; + modules[i + 1] = state; + } + + for (const modules of arrays) { + if (modules.length === 0) continue; + let indexMap; + let length = 0; + outer: for (let j = 0; j < modules.length; j += 2) { + const m = modules[j]; + if (m === undefined) continue; + const state = modules[j + 1]; + if (indexMap === undefined) { + let i = 0; + for (; i < length; i += 2) { + if (modules[i] === m) { + const merged = modules[i + 1]; + if (merged === true) continue outer; + modules[i + 1] = ModuleGraphConnection.addConnectionStates( + merged, + state + ); } - for (const [key, value] of fragment.exportMap) { - if (!exportMap.has(key)) exportMap.set(key, value); + } + modules[length] = m; + length++; + modules[length] = state; + length++; + if (length > 30) { + // To avoid worse case performance, we will use an index map for + // linear cost access, which allows to maintain O(n) complexity + // while keeping allocations down to a minimum + indexMap = new Map(); + for (let i = 0; i < length; i += 2) { + indexMap.set(modules[i], i + 1); } } - } - if (fragment.unusedExports.size !== 0) { - if (unusedExports === undefined) { - unusedExports = fragment.unusedExports; - unusedExportsOwned = false; + } else { + const idx = indexMap.get(m); + if (idx !== undefined) { + const merged = modules[idx]; + if (merged === true) continue outer; + modules[idx] = ModuleGraphConnection.addConnectionStates( + merged, + state + ); } else { - if (!unusedExportsOwned) { - unusedExports = new Set(unusedExports); - unusedExportsOwned = true; - } - for (const value of fragment.unusedExports) { - unusedExports.add(value); - } + modules[length] = m; + length++; + modules[length] = state; + indexMap.set(m, length); + length++; } } } - return new HarmonyExportInitFragment( - this.exportsArgument, - exportMap, - unusedExports - ); + modules.length = length; } +}; - merge(other) { - let exportMap; - if (this.exportMap.size === 0) { - exportMap = other.exportMap; - } else if (other.exportMap.size === 0) { - exportMap = this.exportMap; - } else { - exportMap = new Map(other.exportMap); - for (const [key, value] of this.exportMap) { - if (!exportMap.has(key)) exportMap.set(key, value); - } - } - let unusedExports; - if (this.unusedExports.size === 0) { - unusedExports = other.unusedExports; - } else if (other.unusedExports.size === 0) { - unusedExports = this.unusedExports; - } else { - unusedExports = new Set(other.unusedExports); - for (const value of this.unusedExports) { - unusedExports.add(value); - } - } - return new HarmonyExportInitFragment( - this.exportsArgument, - exportMap, - unusedExports - ); - } +/** + * + * @param {Logger} logger a logger + * @param {Compilation} compilation the compilation + * @param {Map} inputEntrypointsAndModules chunk groups which are processed with the modules + * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules + * @param {Map} blockConnections connection for blocks + * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks + * @param {Set} allCreatedChunkGroups filled with all chunk groups that are created here + */ +const visitModules = ( + logger, + compilation, + inputEntrypointsAndModules, + chunkGroupInfoMap, + blockConnections, + blocksWithNestedBlocks, + allCreatedChunkGroups +) => { + const { moduleGraph, chunkGraph, moduleMemCaches } = compilation; + + const blockModulesRuntimeMap = new Map(); + + /** @type {RuntimeSpec | false} */ + let blockModulesMapRuntime = false; + let blockModulesMap; /** - * @param {Context} context context - * @returns {string|Source} the source code that will be included as initialization code + * + * @param {DependenciesBlock} block block + * @param {RuntimeSpec} runtime runtime + * @returns {(Module | ConnectionState)[]} block modules in flatten tuples */ - getContent({ runtimeTemplate, runtimeRequirements }) { - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - - const unusedPart = - this.unusedExports.size > 1 - ? `/* unused harmony exports ${joinIterableWithComma( - this.unusedExports - )} */\n` - : this.unusedExports.size > 0 - ? `/* unused harmony export ${first(this.unusedExports)} */\n` - : ""; - const definitions = []; - for (const [key, value] of this.exportMap) { - definitions.push( - `\n/* harmony export */ ${JSON.stringify( - key - )}: ${runtimeTemplate.returningFunction(value)}` + const getBlockModules = (block, runtime) => { + if (blockModulesMapRuntime !== runtime) { + blockModulesMap = blockModulesRuntimeMap.get(runtime); + if (blockModulesMap === undefined) { + blockModulesMap = new Map(); + blockModulesRuntimeMap.set(runtime, blockModulesMap); + } + } + let blockModules = blockModulesMap.get(block); + if (blockModules !== undefined) return blockModules; + const module = /** @type {Module} */ (block.getRootBlock()); + const memCache = moduleMemCaches && moduleMemCaches.get(module); + if (memCache !== undefined) { + const map = memCache.provide( + "bundleChunkGraph.blockModules", + runtime, + () => { + logger.time("visitModules: prepare"); + const map = new Map(); + extractBlockModules(module, moduleGraph, runtime, map); + logger.timeAggregate("visitModules: prepare"); + return map; + } ); + for (const [block, blockModules] of map) + blockModulesMap.set(block, blockModules); + return map.get(block); + } else { + logger.time("visitModules: prepare"); + extractBlockModules(module, moduleGraph, runtime, blockModulesMap); + blockModules = blockModulesMap.get(block); + logger.timeAggregate("visitModules: prepare"); + return blockModules; } - const definePart = - this.exportMap.size > 0 - ? `/* harmony export */ ${RuntimeGlobals.definePropertyGetters}(${ - this.exportsArgument - }, {${definitions.join(",")}\n/* harmony export */ });\n` - : ""; - return `${definePart}${unusedPart}`; - } -} - -module.exports = HarmonyExportInitFragment; + }; + let statProcessedQueueItems = 0; + let statProcessedBlocks = 0; + let statConnectedChunkGroups = 0; + let statProcessedChunkGroupsForMerging = 0; + let statMergedAvailableModuleSets = 0; + let statForkedAvailableModules = 0; + let statForkedAvailableModulesCount = 0; + let statForkedAvailableModulesCountPlus = 0; + let statForkedMergedModulesCount = 0; + let statForkedMergedModulesCountPlus = 0; + let statForkedResultModulesCount = 0; + let statChunkGroupInfoUpdated = 0; + let statChildChunkGroupsReconnected = 0; -/***/ }), + let nextChunkGroupIndex = 0; + let nextFreeModulePreOrderIndex = 0; + let nextFreeModulePostOrderIndex = 0; -/***/ 48567: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {Map} */ + const blockChunkGroups = new Map(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** @type {Map} */ + const namedChunkGroups = new Map(); + /** @type {Map} */ + const namedAsyncEntrypoints = new Map(); + const ADD_AND_ENTER_ENTRY_MODULE = 0; + const ADD_AND_ENTER_MODULE = 1; + const ENTER_MODULE = 2; + const PROCESS_BLOCK = 3; + const PROCESS_ENTRY_BLOCK = 4; + const LEAVE_MODULE = 5; -const makeSerializable = __webpack_require__(33032); -const HarmonyExportInitFragment = __webpack_require__(89500); -const NullDependency = __webpack_require__(31830); + /** @type {QueueItem[]} */ + let queue = []; -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ + /** @type {Map>} */ + const queueConnect = new Map(); + /** @type {Set} */ + const chunkGroupsForCombining = new Set(); -class HarmonyExportSpecifierDependency extends NullDependency { - constructor(id, name) { - super(); - this.id = id; - this.name = name; + // Fill queue with entrypoint modules + // Create ChunkGroupInfo for entrypoints + for (const [chunkGroup, modules] of inputEntrypointsAndModules) { + const runtime = getEntryRuntime( + compilation, + chunkGroup.name, + chunkGroup.options + ); + /** @type {ChunkGroupInfo} */ + const chunkGroupInfo = { + chunkGroup, + runtime, + minAvailableModules: undefined, + minAvailableModulesOwned: false, + availableModulesToBeMerged: [], + skippedItems: undefined, + resultingAvailableModules: undefined, + children: undefined, + availableSources: undefined, + availableChildren: undefined, + preOrderIndex: 0, + postOrderIndex: 0, + chunkLoading: + chunkGroup.options.chunkLoading !== undefined + ? chunkGroup.options.chunkLoading !== false + : compilation.outputOptions.chunkLoading !== false, + asyncChunks: + chunkGroup.options.asyncChunks !== undefined + ? chunkGroup.options.asyncChunks + : compilation.outputOptions.asyncChunks !== false + }; + chunkGroup.index = nextChunkGroupIndex++; + if (chunkGroup.getNumberOfParents() > 0) { + // minAvailableModules for child entrypoints are unknown yet, set to undefined. + // This means no module is added until other sets are merged into + // this minAvailableModules (by the parent entrypoints) + const skippedItems = new Set(); + for (const module of modules) { + skippedItems.add(module); + } + chunkGroupInfo.skippedItems = skippedItems; + chunkGroupsForCombining.add(chunkGroupInfo); + } else { + // The application may start here: We start with an empty list of available modules + chunkGroupInfo.minAvailableModules = EMPTY_SET; + const chunk = chunkGroup.getEntrypointChunk(); + for (const module of modules) { + queue.push({ + action: ADD_AND_ENTER_MODULE, + block: module, + module, + chunk, + chunkGroup, + chunkGroupInfo + }); + } + } + chunkGroupInfoMap.set(chunkGroup, chunkGroupInfo); + if (chunkGroup.name) { + namedChunkGroups.set(chunkGroup.name, chunkGroupInfo); + } } - - get type() { - return "harmony export specifier"; + // Fill availableSources with parent-child dependencies between entrypoints + for (const chunkGroupInfo of chunkGroupsForCombining) { + const { chunkGroup } = chunkGroupInfo; + chunkGroupInfo.availableSources = new Set(); + for (const parent of chunkGroup.parentsIterable) { + const parentChunkGroupInfo = chunkGroupInfoMap.get(parent); + chunkGroupInfo.availableSources.add(parentChunkGroupInfo); + if (parentChunkGroupInfo.availableChildren === undefined) { + parentChunkGroupInfo.availableChildren = new Set(); + } + parentChunkGroupInfo.availableChildren.add(chunkGroupInfo); + } } + // pop() is used to read from the queue + // so it need to be reversed to be iterated in + // correct order + queue.reverse(); - /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names - */ - getExports(moduleGraph) { - return { - exports: [this.name], - priority: 1, - terminalBinding: true, - dependencies: undefined - }; - } + /** @type {Set} */ + const outdatedChunkGroupInfo = new Set(); + /** @type {Set} */ + const chunkGroupsForMerging = new Set(); + /** @type {QueueItem[]} */ + let queueDelayed = []; + + /** @type {[Module, ConnectionState][]} */ + const skipConnectionBuffer = []; + /** @type {Module[]} */ + const skipBuffer = []; + /** @type {QueueItem[]} */ + const queueBuffer = []; + + /** @type {Module} */ + let module; + /** @type {Chunk} */ + let chunk; + /** @type {ChunkGroup} */ + let chunkGroup; + /** @type {DependenciesBlock} */ + let block; + /** @type {ChunkGroupInfo} */ + let chunkGroupInfo; + // For each async Block in graph /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules + * @param {AsyncDependenciesBlock} b iterating over each Async DepBlock + * @returns {void} */ - getModuleEvaluationSideEffectsState(moduleGraph) { - return false; - } + const iteratorBlock = b => { + // 1. We create a chunk group with single chunk in it for this Block + // but only once (blockChunkGroups map) + let cgi = blockChunkGroups.get(b); + /** @type {ChunkGroup} */ + let c; + /** @type {Entrypoint} */ + let entrypoint; + const entryOptions = b.groupOptions && b.groupOptions.entryOptions; + if (cgi === undefined) { + const chunkName = (b.groupOptions && b.groupOptions.name) || b.chunkName; + if (entryOptions) { + cgi = namedAsyncEntrypoints.get(chunkName); + if (!cgi) { + entrypoint = compilation.addAsyncEntrypoint( + entryOptions, + module, + b.loc, + b.request + ); + entrypoint.index = nextChunkGroupIndex++; + cgi = { + chunkGroup: entrypoint, + runtime: entrypoint.options.runtime || entrypoint.name, + minAvailableModules: EMPTY_SET, + minAvailableModulesOwned: false, + availableModulesToBeMerged: [], + skippedItems: undefined, + resultingAvailableModules: undefined, + children: undefined, + availableSources: undefined, + availableChildren: undefined, + preOrderIndex: 0, + postOrderIndex: 0, + chunkLoading: + entryOptions.chunkLoading !== undefined + ? entryOptions.chunkLoading !== false + : chunkGroupInfo.chunkLoading, + asyncChunks: + entryOptions.asyncChunks !== undefined + ? entryOptions.asyncChunks + : chunkGroupInfo.asyncChunks + }; + chunkGroupInfoMap.set(entrypoint, cgi); - serialize(context) { - const { write } = context; - write(this.id); - write(this.name); - super.serialize(context); - } + chunkGraph.connectBlockAndChunkGroup(b, entrypoint); + if (chunkName) { + namedAsyncEntrypoints.set(chunkName, cgi); + } + } else { + entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup); + // TODO merge entryOptions + entrypoint.addOrigin(module, b.loc, b.request); + chunkGraph.connectBlockAndChunkGroup(b, entrypoint); + } - deserialize(context) { - const { read } = context; - this.id = read(); - this.name = read(); - super.deserialize(context); - } -} + // 2. We enqueue the DependenciesBlock for traversal + queueDelayed.push({ + action: PROCESS_ENTRY_BLOCK, + block: b, + module: module, + chunk: entrypoint.chunks[0], + chunkGroup: entrypoint, + chunkGroupInfo: cgi + }); + } else if (!chunkGroupInfo.asyncChunks || !chunkGroupInfo.chunkLoading) { + // Just queue the block into the current chunk group + queue.push({ + action: PROCESS_BLOCK, + block: b, + module: module, + chunk, + chunkGroup, + chunkGroupInfo + }); + } else { + cgi = chunkName && namedChunkGroups.get(chunkName); + if (!cgi) { + c = compilation.addChunkInGroup( + b.groupOptions || b.chunkName, + module, + b.loc, + b.request + ); + c.index = nextChunkGroupIndex++; + cgi = { + chunkGroup: c, + runtime: chunkGroupInfo.runtime, + minAvailableModules: undefined, + minAvailableModulesOwned: undefined, + availableModulesToBeMerged: [], + skippedItems: undefined, + resultingAvailableModules: undefined, + children: undefined, + availableSources: undefined, + availableChildren: undefined, + preOrderIndex: 0, + postOrderIndex: 0, + chunkLoading: chunkGroupInfo.chunkLoading, + asyncChunks: chunkGroupInfo.asyncChunks + }; + allCreatedChunkGroups.add(c); + chunkGroupInfoMap.set(c, cgi); + if (chunkName) { + namedChunkGroups.set(chunkName, cgi); + } + } else { + c = cgi.chunkGroup; + if (c.isInitial()) { + compilation.errors.push( + new AsyncDependencyToInitialChunkError(chunkName, module, b.loc) + ); + c = chunkGroup; + } + c.addOptions(b.groupOptions); + c.addOrigin(module, b.loc, b.request); + } + blockConnections.set(b, []); + } + blockChunkGroups.set(b, cgi); + } else if (entryOptions) { + entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup); + } else { + c = cgi.chunkGroup; + } -makeSerializable( - HarmonyExportSpecifierDependency, - "webpack/lib/dependencies/HarmonyExportSpecifierDependency" -); + if (c !== undefined) { + // 2. We store the connection for the block + // to connect it later if needed + blockConnections.get(b).push({ + originChunkGroupInfo: chunkGroupInfo, + chunkGroup: c + }); + + // 3. We enqueue the chunk group info creation/updating + let connectList = queueConnect.get(chunkGroupInfo); + if (connectList === undefined) { + connectList = new Set(); + queueConnect.set(chunkGroupInfo, connectList); + } + connectList.add(cgi); + + // TODO check if this really need to be done for each traversal + // or if it is enough when it's queued when created + // 4. We enqueue the DependenciesBlock for traversal + queueDelayed.push({ + action: PROCESS_BLOCK, + block: b, + module: module, + chunk: c.chunks[0], + chunkGroup: c, + chunkGroupInfo: cgi + }); + } else if (entrypoint !== undefined) { + chunkGroupInfo.chunkGroup.addAsyncEntrypoint(entrypoint); + } + }; -HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate extends ( - NullDependency.Template -) { /** - * @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 + * @param {DependenciesBlock} block the block * @returns {void} */ - apply( - dependency, - source, - { module, moduleGraph, initFragments, runtime, concatenationScope } - ) { - const dep = /** @type {HarmonyExportSpecifierDependency} */ (dependency); - if (concatenationScope) { - concatenationScope.registerExport(dep.name, dep.id); - return; - } - const used = moduleGraph - .getExportsInfo(module) - .getUsedName(dep.name, runtime); - if (!used) { - const set = new Set(); - set.add(dep.name || "namespace"); - initFragments.push( - new HarmonyExportInitFragment(module.exportsArgument, undefined, set) - ); - return; + const processBlock = block => { + statProcessedBlocks++; + // get prepared block info + const blockModules = getBlockModules(block, chunkGroupInfo.runtime); + + if (blockModules !== undefined) { + const { minAvailableModules } = chunkGroupInfo; + // Buffer items because order need to be reversed to get indices correct + // Traverse all referenced modules + for (let i = 0; i < blockModules.length; i += 2) { + const refModule = /** @type {Module} */ (blockModules[i]); + if (chunkGraph.isModuleInChunk(refModule, chunk)) { + // skip early if already connected + continue; + } + const activeState = /** @type {ConnectionState} */ ( + blockModules[i + 1] + ); + if (activeState !== true) { + skipConnectionBuffer.push([refModule, activeState]); + if (activeState === false) continue; + } + if ( + activeState === true && + (minAvailableModules.has(refModule) || + minAvailableModules.plus.has(refModule)) + ) { + // already in parent chunks, skip it for now + skipBuffer.push(refModule); + continue; + } + // enqueue, then add and enter to be in the correct order + // this is relevant with circular dependencies + queueBuffer.push({ + action: activeState === true ? ADD_AND_ENTER_MODULE : PROCESS_BLOCK, + block: refModule, + module: refModule, + chunk, + chunkGroup, + chunkGroupInfo + }); + } + // Add buffered items in reverse order + if (skipConnectionBuffer.length > 0) { + let { skippedModuleConnections } = chunkGroupInfo; + if (skippedModuleConnections === undefined) { + chunkGroupInfo.skippedModuleConnections = skippedModuleConnections = + new Set(); + } + for (let i = skipConnectionBuffer.length - 1; i >= 0; i--) { + skippedModuleConnections.add(skipConnectionBuffer[i]); + } + skipConnectionBuffer.length = 0; + } + if (skipBuffer.length > 0) { + let { skippedItems } = chunkGroupInfo; + if (skippedItems === undefined) { + chunkGroupInfo.skippedItems = skippedItems = new Set(); + } + for (let i = skipBuffer.length - 1; i >= 0; i--) { + skippedItems.add(skipBuffer[i]); + } + skipBuffer.length = 0; + } + if (queueBuffer.length > 0) { + for (let i = queueBuffer.length - 1; i >= 0; i--) { + queue.push(queueBuffer[i]); + } + queueBuffer.length = 0; + } } - const map = new Map(); - map.set(used, `/* binding */ ${dep.id}`); - initFragments.push( - new HarmonyExportInitFragment(module.exportsArgument, map, undefined) - ); - } -}; + // Traverse all Blocks + for (const b of block.blocks) { + iteratorBlock(b); + } -module.exports = HarmonyExportSpecifierDependency; + if (block.blocks.length > 0 && module !== block) { + blocksWithNestedBlocks.add(block); + } + }; + /** + * @param {DependenciesBlock} block the block + * @returns {void} + */ + const processEntryBlock = block => { + statProcessedBlocks++; + // get prepared block info + const blockModules = getBlockModules(block, chunkGroupInfo.runtime); -/***/ }), + if (blockModules !== undefined) { + // Traverse all referenced modules + for (let i = 0; i < blockModules.length; i += 2) { + const refModule = /** @type {Module} */ (blockModules[i]); + const activeState = /** @type {ConnectionState} */ ( + blockModules[i + 1] + ); + // enqueue, then add and enter to be in the correct order + // this is relevant with circular dependencies + queueBuffer.push({ + action: + activeState === true ? ADD_AND_ENTER_ENTRY_MODULE : PROCESS_BLOCK, + block: refModule, + module: refModule, + chunk, + chunkGroup, + chunkGroupInfo + }); + } + // Add buffered items in reverse order + if (queueBuffer.length > 0) { + for (let i = queueBuffer.length - 1; i >= 0; i--) { + queue.push(queueBuffer[i]); + } + queueBuffer.length = 0; + } + } -/***/ 39211: -/***/ (function(__unused_webpack_module, exports) { + // Traverse all Blocks + for (const b of block.blocks) { + iteratorBlock(b); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (block.blocks.length > 0 && module !== block) { + blocksWithNestedBlocks.add(block); + } + }; + const processQueue = () => { + while (queue.length) { + statProcessedQueueItems++; + const queueItem = queue.pop(); + module = queueItem.module; + block = queueItem.block; + chunk = queueItem.chunk; + chunkGroup = queueItem.chunkGroup; + chunkGroupInfo = queueItem.chunkGroupInfo; + switch (queueItem.action) { + case ADD_AND_ENTER_ENTRY_MODULE: + chunkGraph.connectChunkAndEntryModule( + chunk, + module, + /** @type {Entrypoint} */ (chunkGroup) + ); + // fallthrough + case ADD_AND_ENTER_MODULE: { + if (chunkGraph.isModuleInChunk(module, chunk)) { + // already connected, skip it + break; + } + // We connect Module and Chunk + chunkGraph.connectChunkAndModule(chunk, module); + } + // fallthrough + case ENTER_MODULE: { + const index = chunkGroup.getModulePreOrderIndex(module); + if (index === undefined) { + chunkGroup.setModulePreOrderIndex( + module, + chunkGroupInfo.preOrderIndex++ + ); + } -/** @typedef {import("../Parser").ParserState} ParserState */ + if ( + moduleGraph.setPreOrderIndexIfUnset( + module, + nextFreeModulePreOrderIndex + ) + ) { + nextFreeModulePreOrderIndex++; + } -/** @type {WeakMap} */ -const parserStateExportsState = new WeakMap(); + // reuse queueItem + queueItem.action = LEAVE_MODULE; + queue.push(queueItem); + } + // fallthrough + case PROCESS_BLOCK: { + processBlock(block); + break; + } + case PROCESS_ENTRY_BLOCK: { + processEntryBlock(block); + break; + } + case LEAVE_MODULE: { + const index = chunkGroup.getModulePostOrderIndex(module); + if (index === undefined) { + chunkGroup.setModulePostOrderIndex( + module, + chunkGroupInfo.postOrderIndex++ + ); + } -/** - * @param {ParserState} parserState parser state - * @param {boolean} isStrictHarmony strict harmony mode should be enabled - * @returns {void} - */ -exports.enable = (parserState, isStrictHarmony) => { - const value = parserStateExportsState.get(parserState); - if (value === false) return; - parserStateExportsState.set(parserState, true); - if (value !== true) { - parserState.module.buildMeta.exportsType = "namespace"; - parserState.module.buildInfo.strict = true; - parserState.module.buildInfo.exportsArgument = "__webpack_exports__"; - if (isStrictHarmony) { - parserState.module.buildMeta.strictHarmonyModule = true; - parserState.module.buildInfo.moduleArgument = "__webpack_module__"; + if ( + moduleGraph.setPostOrderIndexIfUnset( + module, + nextFreeModulePostOrderIndex + ) + ) { + nextFreeModulePostOrderIndex++; + } + break; + } + } } - } -}; + }; -/** - * @param {ParserState} parserState parser state - * @returns {boolean} true, when enabled - */ -exports.isEnabled = parserState => { - const value = parserStateExportsState.get(parserState); - return value === true; -}; + const calculateResultingAvailableModules = chunkGroupInfo => { + if (chunkGroupInfo.resultingAvailableModules) + return chunkGroupInfo.resultingAvailableModules; + const minAvailableModules = chunkGroupInfo.minAvailableModules; -/***/ }), + // Create a new Set of available modules at this point + // We want to be as lazy as possible. There are multiple ways doing this: + // Note that resultingAvailableModules is stored as "(a) + (b)" as it's a ModuleSetPlus + // - resultingAvailableModules = (modules of chunk) + (minAvailableModules + minAvailableModules.plus) + // - resultingAvailableModules = (minAvailableModules + modules of chunk) + (minAvailableModules.plus) + // We choose one depending on the size of minAvailableModules vs minAvailableModules.plus -/***/ 57154: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + let resultingAvailableModules; + if (minAvailableModules.size > minAvailableModules.plus.size) { + // resultingAvailableModules = (modules of chunk) + (minAvailableModules + minAvailableModules.plus) + resultingAvailableModules = + /** @type {Set & {plus: Set}} */ (new Set()); + for (const module of minAvailableModules.plus) + minAvailableModules.add(module); + minAvailableModules.plus = EMPTY_SET; + resultingAvailableModules.plus = minAvailableModules; + chunkGroupInfo.minAvailableModulesOwned = false; + } else { + // resultingAvailableModules = (minAvailableModules + modules of chunk) + (minAvailableModules.plus) + resultingAvailableModules = + /** @type {Set & {plus: Set}} */ ( + new Set(minAvailableModules) + ); + resultingAvailableModules.plus = minAvailableModules.plus; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // add the modules from the chunk group to the set + for (const chunk of chunkGroupInfo.chunkGroup.chunks) { + for (const m of chunkGraph.getChunkModulesIterable(chunk)) { + resultingAvailableModules.add(m); + } + } + return (chunkGroupInfo.resultingAvailableModules = + resultingAvailableModules); + }; + const processConnectQueue = () => { + // Figure out new parents for chunk groups + // to get new available modules for these children + for (const [chunkGroupInfo, targets] of queueConnect) { + // 1. Add new targets to the list of children + if (chunkGroupInfo.children === undefined) { + chunkGroupInfo.children = targets; + } else { + for (const target of targets) { + chunkGroupInfo.children.add(target); + } + } + // 2. Calculate resulting available modules + const resultingAvailableModules = + calculateResultingAvailableModules(chunkGroupInfo); -const ConditionalInitFragment = __webpack_require__(61333); -const Dependency = __webpack_require__(54912); -const HarmonyLinkingError = __webpack_require__(97511); -const InitFragment = __webpack_require__(55870); -const Template = __webpack_require__(1626); -const AwaitDependenciesInitFragment = __webpack_require__(41153); -const { filterRuntime, mergeRuntime } = __webpack_require__(17156); -const ModuleDependency = __webpack_require__(80321); + const runtime = chunkGroupInfo.runtime; -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + // 3. Update chunk group info + for (const target of targets) { + target.availableModulesToBeMerged.push(resultingAvailableModules); + chunkGroupsForMerging.add(target); + const oldRuntime = target.runtime; + const newRuntime = mergeRuntime(oldRuntime, runtime); + if (oldRuntime !== newRuntime) { + target.runtime = newRuntime; + outdatedChunkGroupInfo.add(target); + } + } -const ExportPresenceModes = { - NONE: /** @type {0} */ (0), - WARN: /** @type {1} */ (1), - AUTO: /** @type {2} */ (2), - ERROR: /** @type {3} */ (3), - fromUserOption(str) { - switch (str) { - case "error": - return ExportPresenceModes.ERROR; - case "warn": - return ExportPresenceModes.WARN; - case "auto": - return ExportPresenceModes.AUTO; - case false: - return ExportPresenceModes.NONE; - default: - throw new Error(`Invalid export presence value ${str}`); + statConnectedChunkGroups += targets.size; } - } -}; - -class HarmonyImportDependency extends ModuleDependency { - /** - * - * @param {string} request request string - * @param {number} sourceOrder source order - * @param {Record=} assertions import assertions - */ - constructor(request, sourceOrder, assertions) { - super(request); - this.sourceOrder = sourceOrder; - this.assertions = assertions; - } + queueConnect.clear(); + }; - get category() { - return "esm"; - } + const processChunkGroupsForMerging = () => { + statProcessedChunkGroupsForMerging += chunkGroupsForMerging.size; - /** - * 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.NO_EXPORTS_REFERENCED; - } + // Execute the merge + for (const info of chunkGroupsForMerging) { + const availableModulesToBeMerged = info.availableModulesToBeMerged; + let cachedMinAvailableModules = info.minAvailableModules; - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {string} name of the variable for the import - */ - getImportVar(moduleGraph) { - const module = moduleGraph.getParentModule(this); - const meta = moduleGraph.getMeta(module); - let importVarMap = meta.importVarMap; - if (!importVarMap) meta.importVarMap = importVarMap = new Map(); - let importVar = importVarMap.get(moduleGraph.getModule(this)); - if (importVar) return importVar; - importVar = `${Template.toIdentifier( - `${this.userRequest}` - )}__WEBPACK_IMPORTED_MODULE_${importVarMap.size}__`; - importVarMap.set(moduleGraph.getModule(this), importVar); - return importVar; - } + statMergedAvailableModuleSets += availableModulesToBeMerged.length; - /** - * @param {boolean} update create new variables or update existing one - * @param {DependencyTemplateContext} templateContext the template context - * @returns {[string, string]} the import statement and the compat statement - */ - getImportStatement( - update, - { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } - ) { - return runtimeTemplate.importStatement({ - update, - module: moduleGraph.getModule(this), - chunkGraph, - importVar: this.getImportVar(moduleGraph), - request: this.request, - originModule: module, - runtimeRequirements - }); - } + // 1. Get minimal available modules + // It doesn't make sense to traverse a chunk again with more available modules. + // This step calculates the minimal available modules and skips traversal when + // the list didn't shrink. + if (availableModulesToBeMerged.length > 1) { + availableModulesToBeMerged.sort(bySetSize); + } + let changed = false; + merge: for (const availableModules of availableModulesToBeMerged) { + if (cachedMinAvailableModules === undefined) { + cachedMinAvailableModules = availableModules; + info.minAvailableModules = cachedMinAvailableModules; + info.minAvailableModulesOwned = false; + changed = true; + } else { + if (info.minAvailableModulesOwned) { + // We own it and can modify it + if (cachedMinAvailableModules.plus === availableModules.plus) { + for (const m of cachedMinAvailableModules) { + if (!availableModules.has(m)) { + cachedMinAvailableModules.delete(m); + changed = true; + } + } + } else { + for (const m of cachedMinAvailableModules) { + if (!availableModules.has(m) && !availableModules.plus.has(m)) { + cachedMinAvailableModules.delete(m); + changed = true; + } + } + for (const m of cachedMinAvailableModules.plus) { + if (!availableModules.has(m) && !availableModules.plus.has(m)) { + // We can't remove modules from the plus part + // so we need to merge plus into the normal part to allow modifying it + const iterator = + cachedMinAvailableModules.plus[Symbol.iterator](); + // fast forward add all modules until m + /** @type {IteratorResult} */ + let it; + while (!(it = iterator.next()).done) { + const module = it.value; + if (module === m) break; + cachedMinAvailableModules.add(module); + } + // check the remaining modules before adding + while (!(it = iterator.next()).done) { + const module = it.value; + if ( + availableModules.has(module) || + availableModules.plus.has(m) + ) { + cachedMinAvailableModules.add(module); + } + } + cachedMinAvailableModules.plus = EMPTY_SET; + changed = true; + continue merge; + } + } + } + } else if (cachedMinAvailableModules.plus === availableModules.plus) { + // Common and fast case when the plus part is shared + // We only need to care about the normal part + if (availableModules.size < cachedMinAvailableModules.size) { + // the new availableModules is smaller so it's faster to + // fork from the new availableModules + statForkedAvailableModules++; + statForkedAvailableModulesCount += availableModules.size; + statForkedMergedModulesCount += cachedMinAvailableModules.size; + // construct a new Set as intersection of cachedMinAvailableModules and availableModules + const newSet = /** @type {ModuleSetPlus} */ (new Set()); + newSet.plus = availableModules.plus; + for (const m of availableModules) { + if (cachedMinAvailableModules.has(m)) { + newSet.add(m); + } + } + statForkedResultModulesCount += newSet.size; + cachedMinAvailableModules = newSet; + info.minAvailableModulesOwned = true; + info.minAvailableModules = newSet; + changed = true; + continue merge; + } + for (const m of cachedMinAvailableModules) { + if (!availableModules.has(m)) { + // cachedMinAvailableModules need to be modified + // but we don't own it + statForkedAvailableModules++; + statForkedAvailableModulesCount += + cachedMinAvailableModules.size; + statForkedMergedModulesCount += availableModules.size; + // construct a new Set as intersection of cachedMinAvailableModules and availableModules + // as the plus part is equal we can just take over this one + const newSet = /** @type {ModuleSetPlus} */ (new Set()); + newSet.plus = availableModules.plus; + const iterator = cachedMinAvailableModules[Symbol.iterator](); + // fast forward add all modules until m + /** @type {IteratorResult} */ + let it; + while (!(it = iterator.next()).done) { + const module = it.value; + if (module === m) break; + newSet.add(module); + } + // check the remaining modules before adding + while (!(it = iterator.next()).done) { + const module = it.value; + if (availableModules.has(module)) { + newSet.add(module); + } + } + statForkedResultModulesCount += newSet.size; + cachedMinAvailableModules = newSet; + info.minAvailableModulesOwned = true; + info.minAvailableModules = newSet; + changed = true; + continue merge; + } + } + } else { + for (const m of cachedMinAvailableModules) { + if (!availableModules.has(m) && !availableModules.plus.has(m)) { + // cachedMinAvailableModules need to be modified + // but we don't own it + statForkedAvailableModules++; + statForkedAvailableModulesCount += + cachedMinAvailableModules.size; + statForkedAvailableModulesCountPlus += + cachedMinAvailableModules.plus.size; + statForkedMergedModulesCount += availableModules.size; + statForkedMergedModulesCountPlus += availableModules.plus.size; + // construct a new Set as intersection of cachedMinAvailableModules and availableModules + const newSet = /** @type {ModuleSetPlus} */ (new Set()); + newSet.plus = EMPTY_SET; + const iterator = cachedMinAvailableModules[Symbol.iterator](); + // fast forward add all modules until m + /** @type {IteratorResult} */ + let it; + while (!(it = iterator.next()).done) { + const module = it.value; + if (module === m) break; + newSet.add(module); + } + // check the remaining modules before adding + while (!(it = iterator.next()).done) { + const module = it.value; + if ( + availableModules.has(module) || + availableModules.plus.has(module) + ) { + newSet.add(module); + } + } + // also check all modules in cachedMinAvailableModules.plus + for (const module of cachedMinAvailableModules.plus) { + if ( + availableModules.has(module) || + availableModules.plus.has(module) + ) { + newSet.add(module); + } + } + statForkedResultModulesCount += newSet.size; + cachedMinAvailableModules = newSet; + info.minAvailableModulesOwned = true; + info.minAvailableModules = newSet; + changed = true; + continue merge; + } + } + for (const m of cachedMinAvailableModules.plus) { + if (!availableModules.has(m) && !availableModules.plus.has(m)) { + // cachedMinAvailableModules need to be modified + // but we don't own it + statForkedAvailableModules++; + statForkedAvailableModulesCount += + cachedMinAvailableModules.size; + statForkedAvailableModulesCountPlus += + cachedMinAvailableModules.plus.size; + statForkedMergedModulesCount += availableModules.size; + statForkedMergedModulesCountPlus += availableModules.plus.size; + // construct a new Set as intersection of cachedMinAvailableModules and availableModules + // we already know that all modules directly from cachedMinAvailableModules are in availableModules too + const newSet = /** @type {ModuleSetPlus} */ ( + new Set(cachedMinAvailableModules) + ); + newSet.plus = EMPTY_SET; + const iterator = + cachedMinAvailableModules.plus[Symbol.iterator](); + // fast forward add all modules until m + /** @type {IteratorResult} */ + let it; + while (!(it = iterator.next()).done) { + const module = it.value; + if (module === m) break; + newSet.add(module); + } + // check the remaining modules before adding + while (!(it = iterator.next()).done) { + const module = it.value; + if ( + availableModules.has(module) || + availableModules.plus.has(module) + ) { + newSet.add(module); + } + } + statForkedResultModulesCount += newSet.size; + cachedMinAvailableModules = newSet; + info.minAvailableModulesOwned = true; + info.minAvailableModules = newSet; + changed = true; + continue merge; + } + } + } + } + } + availableModulesToBeMerged.length = 0; + if (changed) { + info.resultingAvailableModules = undefined; + outdatedChunkGroupInfo.add(info); + } + } + chunkGroupsForMerging.clear(); + }; - /** - * @param {ModuleGraph} moduleGraph module graph - * @param {string[]} ids imported ids - * @param {string} additionalMessage extra info included in the error message - * @returns {WebpackError[] | undefined} errors - */ - getLinkingErrors(moduleGraph, ids, additionalMessage) { - const importedModule = moduleGraph.getModule(this); - // ignore errors for missing or failed modules - if (!importedModule || importedModule.getNumberOfErrors() > 0) { - return; + const processChunkGroupsForCombining = () => { + for (const info of chunkGroupsForCombining) { + for (const source of info.availableSources) { + if (!source.minAvailableModules) { + chunkGroupsForCombining.delete(info); + break; + } + } + } + for (const info of chunkGroupsForCombining) { + const availableModules = /** @type {ModuleSetPlus} */ (new Set()); + availableModules.plus = EMPTY_SET; + const mergeSet = set => { + if (set.size > availableModules.plus.size) { + for (const item of availableModules.plus) availableModules.add(item); + availableModules.plus = set; + } else { + for (const item of set) availableModules.add(item); + } + }; + // combine minAvailableModules from all resultingAvailableModules + for (const source of info.availableSources) { + const resultingAvailableModules = + calculateResultingAvailableModules(source); + mergeSet(resultingAvailableModules); + mergeSet(resultingAvailableModules.plus); + } + info.minAvailableModules = availableModules; + info.minAvailableModulesOwned = false; + info.resultingAvailableModules = undefined; + outdatedChunkGroupInfo.add(info); } + chunkGroupsForCombining.clear(); + }; - const parentModule = moduleGraph.getParentModule(this); - const exportsType = importedModule.getExportsType( - moduleGraph, - parentModule.buildMeta.strictHarmonyModule - ); - if (exportsType === "namespace" || exportsType === "default-with-named") { - if (ids.length === 0) { - return; + const processOutdatedChunkGroupInfo = () => { + statChunkGroupInfoUpdated += outdatedChunkGroupInfo.size; + // Revisit skipped elements + for (const info of outdatedChunkGroupInfo) { + // 1. Reconsider skipped items + if (info.skippedItems !== undefined) { + const { minAvailableModules } = info; + for (const module of info.skippedItems) { + if ( + !minAvailableModules.has(module) && + !minAvailableModules.plus.has(module) + ) { + queue.push({ + action: ADD_AND_ENTER_MODULE, + block: module, + module, + chunk: info.chunkGroup.chunks[0], + chunkGroup: info.chunkGroup, + chunkGroupInfo: info + }); + info.skippedItems.delete(module); + } + } } - if ( - (exportsType !== "default-with-named" || ids[0] !== "default") && - moduleGraph.isExportProvided(importedModule, ids) === false - ) { - // We are sure that it's not provided + // 2. Reconsider skipped connections + if (info.skippedModuleConnections !== undefined) { + const { minAvailableModules } = info; + for (const entry of info.skippedModuleConnections) { + const [module, activeState] = entry; + if (activeState === false) continue; + if (activeState === true) { + info.skippedModuleConnections.delete(entry); + } + if ( + activeState === true && + (minAvailableModules.has(module) || + minAvailableModules.plus.has(module)) + ) { + info.skippedItems.add(module); + continue; + } + queue.push({ + action: activeState === true ? ADD_AND_ENTER_MODULE : PROCESS_BLOCK, + block: module, + module, + chunk: info.chunkGroup.chunks[0], + chunkGroup: info.chunkGroup, + chunkGroupInfo: info + }); + } + } - // Try to provide detailed info in the error message - let pos = 0; - let exportsInfo = moduleGraph.getExportsInfo(importedModule); - while (pos < ids.length && exportsInfo) { - const id = ids[pos++]; - const exportInfo = exportsInfo.getReadOnlyExportInfo(id); - if (exportInfo.provided === false) { - // We are sure that it's not provided - const providedExports = exportsInfo.getProvidedExports(); - const moreInfo = !Array.isArray(providedExports) - ? " (possible exports unknown)" - : providedExports.length === 0 - ? " (module has no exports)" - : ` (possible exports: ${providedExports.join(", ")})`; - return [ - new HarmonyLinkingError( - `export ${ids - .slice(0, pos) - .map(id => `'${id}'`) - .join(".")} ${additionalMessage} was not found in '${ - this.userRequest - }'${moreInfo}` - ) - ]; + // 2. Reconsider children chunk groups + if (info.children !== undefined) { + statChildChunkGroupsReconnected += info.children.size; + for (const cgi of info.children) { + let connectList = queueConnect.get(info); + if (connectList === undefined) { + connectList = new Set(); + queueConnect.set(info, connectList); } - exportsInfo = exportInfo.getNestedExportsInfo(); + connectList.add(cgi); } + } - // General error message - return [ - new HarmonyLinkingError( - `export ${ids - .map(id => `'${id}'`) - .join(".")} ${additionalMessage} was not found in '${ - this.userRequest - }'` - ) - ]; + // 3. Reconsider chunk groups for combining + if (info.availableChildren !== undefined) { + for (const cgi of info.availableChildren) { + chunkGroupsForCombining.add(cgi); + } } } - switch (exportsType) { - case "default-only": - // It's has only a default export - if (ids.length > 0 && ids[0] !== "default") { - // In strict harmony modules we only support the default export - return [ - new HarmonyLinkingError( - `Can't import the named export ${ids - .map(id => `'${id}'`) - .join( - "." - )} ${additionalMessage} from default-exporting module (only default export is available)` - ) - ]; - } - break; - case "default-with-named": - // It has a default export and named properties redirect - // In some cases we still want to warn here - if ( - ids.length > 0 && - ids[0] !== "default" && - importedModule.buildMeta.defaultObject === "redirect-warn" - ) { - // For these modules only the default export is supported - return [ - new HarmonyLinkingError( - `Should not import the named export ${ids - .map(id => `'${id}'`) - .join( - "." - )} ${additionalMessage} from default-exporting module (only default export is available soon)` - ) - ]; - } - break; + outdatedChunkGroupInfo.clear(); + }; + + // Iterative traversal of the Module graph + // Recursive would be simpler to write but could result in Stack Overflows + while (queue.length || queueConnect.size) { + logger.time("visitModules: visiting"); + processQueue(); + logger.timeAggregateEnd("visitModules: prepare"); + logger.timeEnd("visitModules: visiting"); + + if (chunkGroupsForCombining.size > 0) { + logger.time("visitModules: combine available modules"); + processChunkGroupsForCombining(); + logger.timeEnd("visitModules: combine available modules"); } - } - serialize(context) { - const { write } = context; - write(this.sourceOrder); - write(this.assertions); - super.serialize(context); - } + if (queueConnect.size > 0) { + logger.time("visitModules: calculating available modules"); + processConnectQueue(); + logger.timeEnd("visitModules: calculating available modules"); - deserialize(context) { - const { read } = context; - this.sourceOrder = read(); - this.assertions = read(); - super.deserialize(context); + if (chunkGroupsForMerging.size > 0) { + logger.time("visitModules: merging available modules"); + processChunkGroupsForMerging(); + logger.timeEnd("visitModules: merging available modules"); + } + } + + if (outdatedChunkGroupInfo.size > 0) { + logger.time("visitModules: check modules for revisit"); + processOutdatedChunkGroupInfo(); + logger.timeEnd("visitModules: check modules for revisit"); + } + + // Run queueDelayed when all items of the queue are processed + // This is important to get the global indexing correct + // Async blocks should be processed after all sync blocks are processed + if (queue.length === 0) { + const tempQueue = queue; + queue = queueDelayed.reverse(); + queueDelayed = tempQueue; + } } -} -module.exports = HarmonyImportDependency; + logger.log( + `${statProcessedQueueItems} queue items processed (${statProcessedBlocks} blocks)` + ); + logger.log(`${statConnectedChunkGroups} chunk groups connected`); + logger.log( + `${statProcessedChunkGroupsForMerging} chunk groups processed for merging (${statMergedAvailableModuleSets} module sets, ${statForkedAvailableModules} forked, ${statForkedAvailableModulesCount} + ${statForkedAvailableModulesCountPlus} modules forked, ${statForkedMergedModulesCount} + ${statForkedMergedModulesCountPlus} modules merged into fork, ${statForkedResultModulesCount} resulting modules)` + ); + logger.log( + `${statChunkGroupInfoUpdated} chunk group info updated (${statChildChunkGroupsReconnected} already connected chunk groups reconnected)` + ); +}; -/** @type {WeakMap>} */ -const importEmittedMap = new WeakMap(); +/** + * + * @param {Compilation} compilation the compilation + * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks + * @param {Map} blockConnections connection for blocks + * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules + */ +const connectChunkGroups = ( + compilation, + blocksWithNestedBlocks, + blockConnections, + chunkGroupInfoMap +) => { + const { chunkGraph } = compilation; -HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends ( - ModuleDependency.Template -) { /** - * @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} + * Helper function to check if all modules of a chunk are available + * + * @param {ChunkGroup} chunkGroup the chunkGroup to scan + * @param {ModuleSetPlus} availableModules the comparator set + * @returns {boolean} return true if all modules of a chunk are available */ - apply(dependency, source, templateContext) { - const dep = /** @type {HarmonyImportDependency} */ (dependency); - const { module, chunkGraph, moduleGraph, runtime } = templateContext; - - const connection = moduleGraph.getConnection(dep); - if (connection && !connection.isTargetActive(runtime)) return; - - const referencedModule = connection && connection.module; + const areModulesAvailable = (chunkGroup, availableModules) => { + for (const chunk of chunkGroup.chunks) { + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (!availableModules.has(module) && !availableModules.plus.has(module)) + return false; + } + } + return true; + }; + // For each edge in the basic chunk graph + for (const [block, connections] of blockConnections) { + // 1. Check if connection is needed + // When none of the dependencies need to be connected + // we can skip all of them + // It's not possible to filter each item so it doesn't create inconsistent + // connections and modules can only create one version + // TODO maybe decide this per runtime if ( - connection && - connection.weak && - referencedModule && - chunkGraph.getModuleId(referencedModule) === null + // TODO is this needed? + !blocksWithNestedBlocks.has(block) && + connections.every(({ chunkGroup, originChunkGroupInfo }) => + areModulesAvailable( + chunkGroup, + originChunkGroupInfo.resultingAvailableModules + ) + ) ) { - // in weak references, module might not be in any chunk - // but that's ok, we don't need that logic in this case - return; + continue; } - const moduleKey = referencedModule - ? referencedModule.identifier() - : dep.request; - const key = `harmony import ${moduleKey}`; + // 2. Foreach edge + for (let i = 0; i < connections.length; i++) { + const { chunkGroup, originChunkGroupInfo } = connections[i]; - const runtimeCondition = dep.weak - ? false - : connection - ? filterRuntime(runtime, r => connection.isTargetActive(r)) - : true; + // 3. Connect block with chunk + chunkGraph.connectBlockAndChunkGroup(block, chunkGroup); - if (module && referencedModule) { - let emittedModules = importEmittedMap.get(module); - if (emittedModules === undefined) { - emittedModules = new WeakMap(); - importEmittedMap.set(module, emittedModules); - } - let mergedRuntimeCondition = runtimeCondition; - const oldRuntimeCondition = emittedModules.get(referencedModule) || false; - if (oldRuntimeCondition !== false && mergedRuntimeCondition !== true) { - if (mergedRuntimeCondition === false || oldRuntimeCondition === true) { - mergedRuntimeCondition = oldRuntimeCondition; - } else { - mergedRuntimeCondition = mergeRuntime( - oldRuntimeCondition, - mergedRuntimeCondition - ); - } - } - emittedModules.set(referencedModule, mergedRuntimeCondition); + // 4. Connect chunk with parent + connectChunkGroupParentAndChild( + originChunkGroupInfo.chunkGroup, + chunkGroup + ); } + } +}; - const importStatement = dep.getImportStatement(false, templateContext); - if ( - referencedModule && - templateContext.moduleGraph.isAsync(referencedModule) - ) { - templateContext.initFragments.push( - new ConditionalInitFragment( - importStatement[0], - InitFragment.STAGE_HARMONY_IMPORTS, - dep.sourceOrder, - key, - runtimeCondition - ) - ); - templateContext.initFragments.push( - new AwaitDependenciesInitFragment( - new Set([dep.getImportVar(templateContext.moduleGraph)]) - ) - ); - templateContext.initFragments.push( - new ConditionalInitFragment( - importStatement[1], - InitFragment.STAGE_ASYNC_HARMONY_IMPORTS, - dep.sourceOrder, - key + " compat", - runtimeCondition - ) - ); - } else { - templateContext.initFragments.push( - new ConditionalInitFragment( - importStatement[0] + importStatement[1], - InitFragment.STAGE_HARMONY_IMPORTS, - dep.sourceOrder, - key, - runtimeCondition - ) - ); +/** + * Remove all unconnected chunk groups + * @param {Compilation} compilation the compilation + * @param {Iterable} allCreatedChunkGroups all chunk groups that where created before + */ +const cleanupUnconnectedGroups = (compilation, allCreatedChunkGroups) => { + const { chunkGraph } = compilation; + + for (const chunkGroup of allCreatedChunkGroups) { + if (chunkGroup.getNumberOfParents() === 0) { + for (const chunk of chunkGroup.chunks) { + compilation.chunks.delete(chunk); + chunkGraph.disconnectChunk(chunk); + } + chunkGraph.disconnectChunkGroup(chunkGroup); + chunkGroup.remove(); } } +}; - /** - * - * @param {Module} module the module - * @param {Module} referencedModule the referenced module - * @returns {RuntimeSpec | boolean} runtimeCondition in which this import has been emitted - */ - static getImportEmittedRuntime(module, referencedModule) { - const emittedModules = importEmittedMap.get(module); - if (emittedModules === undefined) return false; - return emittedModules.get(referencedModule) || false; +/** + * This method creates the Chunk graph from the Module graph + * @param {Compilation} compilation the compilation + * @param {Map} inputEntrypointsAndModules chunk groups which are processed with the modules + * @returns {void} + */ +const buildChunkGraph = (compilation, inputEntrypointsAndModules) => { + const logger = compilation.getLogger("webpack.buildChunkGraph"); + + // SHARED STATE + + /** @type {Map} */ + const blockConnections = new Map(); + + /** @type {Set} */ + const allCreatedChunkGroups = new Set(); + + /** @type {Map} */ + const chunkGroupInfoMap = new Map(); + + /** @type {Set} */ + const blocksWithNestedBlocks = new Set(); + + // PART ONE + + logger.time("visitModules"); + visitModules( + logger, + compilation, + inputEntrypointsAndModules, + chunkGroupInfoMap, + blockConnections, + blocksWithNestedBlocks, + allCreatedChunkGroups + ); + logger.timeEnd("visitModules"); + + // PART TWO + + logger.time("connectChunkGroups"); + connectChunkGroups( + compilation, + blocksWithNestedBlocks, + blockConnections, + chunkGroupInfoMap + ); + logger.timeEnd("connectChunkGroups"); + + for (const [chunkGroup, chunkGroupInfo] of chunkGroupInfoMap) { + for (const chunk of chunkGroup.chunks) + chunk.runtime = mergeRuntime(chunk.runtime, chunkGroupInfo.runtime); } + + // Cleanup work + + logger.time("cleanup"); + cleanupUnconnectedGroups(compilation, allCreatedChunkGroups); + logger.timeEnd("cleanup"); }; -module.exports.ExportPresenceModes = ExportPresenceModes; +module.exports = buildChunkGraph; /***/ }), -/***/ 20862: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 28034: +/***/ (function(module) { "use strict"; /* @@ -79034,260 +73352,315 @@ module.exports.ExportPresenceModes = ExportPresenceModes; -const HotModuleReplacementPlugin = __webpack_require__(6404); -const InnerGraph = __webpack_require__(38988); -const ConstDependency = __webpack_require__(76911); -const HarmonyAcceptDependency = __webpack_require__(23624); -const HarmonyAcceptImportDependency = __webpack_require__(99843); -const HarmonyExports = __webpack_require__(39211); -const { ExportPresenceModes } = __webpack_require__(57154); -const HarmonyImportSideEffectDependency = __webpack_require__(73132); -const HarmonyImportSpecifierDependency = __webpack_require__(14077); +/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */ -/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */ -/** @typedef {import("estree").Identifier} Identifier */ -/** @typedef {import("estree").ImportDeclaration} ImportDeclaration */ -/** @typedef {import("estree").ImportExpression} ImportExpression */ -/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ -/** @typedef {import("../optimize/InnerGraph").InnerGraph} InnerGraph */ -/** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */ -/** @typedef {import("./HarmonyImportDependency")} HarmonyImportDependency */ +class AddBuildDependenciesPlugin { + /** + * @param {Iterable} buildDependencies list of build dependencies + */ + constructor(buildDependencies) { + this.buildDependencies = new Set(buildDependencies); + } -const harmonySpecifierTag = Symbol("harmony import"); + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "AddBuildDependenciesPlugin", + compilation => { + compilation.buildDependencies.addAll(this.buildDependencies); + } + ); + } +} -/** - * @typedef {Object} HarmonySettings - * @property {string[]} ids - * @property {string} source - * @property {number} sourceOrder - * @property {string} name - * @property {boolean} await - * @property {Record | undefined} assertions - */ +module.exports = AddBuildDependenciesPlugin; -/** - * @param {ImportDeclaration | ExportNamedDeclaration | ExportAllDeclaration | ImportExpression} node node with assertions - * @returns {Record | undefined} assertions - */ -function getAssertions(node) { - // TODO remove cast when @types/estree has been updated to import assertions - const assertions = /** @type {{ assertions?: ImportAttributeNode[] }} */ ( - node - ).assertions; - if (assertions === undefined) { - return undefined; + +/***/ }), + +/***/ 47942: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("../Compiler")} Compiler */ + +class AddManagedPathsPlugin { + /** + * @param {Iterable} managedPaths list of managed paths + * @param {Iterable} immutablePaths list of immutable paths + */ + constructor(managedPaths, immutablePaths) { + this.managedPaths = new Set(managedPaths); + this.immutablePaths = new Set(immutablePaths); } - const result = {}; - for (const assertion of assertions) { - const key = - assertion.key.type === "Identifier" - ? assertion.key.name - : assertion.key.value; - result[key] = assertion.value.value; + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + for (const managedPath of this.managedPaths) { + compiler.managedPaths.add(managedPath); + } + for (const immutablePath of this.immutablePaths) { + compiler.immutablePaths.add(immutablePath); + } } - return result; } -module.exports = class HarmonyImportDependencyParserPlugin { +module.exports = AddManagedPathsPlugin; + + +/***/ }), + +/***/ 71985: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const Cache = __webpack_require__(7592); +const ProgressPlugin = __webpack_require__(13216); + +/** @typedef {import("../Compiler")} Compiler */ + +const BUILD_DEPENDENCIES_KEY = Symbol(); + +class IdleFileCachePlugin { /** - * @param {JavascriptParserOptions} options options + * @param {TODO} strategy cache strategy + * @param {number} idleTimeout timeout + * @param {number} idleTimeoutForInitialStore initial timeout + * @param {number} idleTimeoutAfterLargeChanges timeout after changes */ - constructor(options) { - this.exportPresenceMode = - options.importExportsPresence !== undefined - ? ExportPresenceModes.fromUserOption(options.importExportsPresence) - : options.exportsPresence !== undefined - ? ExportPresenceModes.fromUserOption(options.exportsPresence) - : options.strictExportPresence - ? ExportPresenceModes.ERROR - : ExportPresenceModes.AUTO; - this.strictThisContextOnImports = options.strictThisContextOnImports; + constructor( + strategy, + idleTimeout, + idleTimeoutForInitialStore, + idleTimeoutAfterLargeChanges + ) { + this.strategy = strategy; + this.idleTimeout = idleTimeout; + this.idleTimeoutForInitialStore = idleTimeoutForInitialStore; + this.idleTimeoutAfterLargeChanges = idleTimeoutAfterLargeChanges; } /** - * @param {JavascriptParser} parser the parser + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply(parser) { - const { exportPresenceMode } = this; - parser.hooks.isPure - .for("Identifier") - .tap("HarmonyImportDependencyParserPlugin", expression => { - const expr = /** @type {Identifier} */ (expression); - if ( - parser.isVariableDefined(expr.name) || - parser.getTagData(expr.name, harmonySpecifierTag) - ) { - return true; - } - }); - parser.hooks.import.tap( - "HarmonyImportDependencyParserPlugin", - (statement, source) => { - parser.state.lastHarmonyImportOrder = - (parser.state.lastHarmonyImportOrder || 0) + 1; - const clearDep = new ConstDependency( - parser.isAsiPosition(statement.range[0]) ? ";" : "", - statement.range - ); - clearDep.loc = statement.loc; - parser.state.module.addPresentationalDependency(clearDep); - parser.unsetAsiPosition(statement.range[1]); - const assertions = getAssertions(statement); - const sideEffectDep = new HarmonyImportSideEffectDependency( - source, - parser.state.lastHarmonyImportOrder, - assertions + apply(compiler) { + let strategy = this.strategy; + const idleTimeout = this.idleTimeout; + const idleTimeoutForInitialStore = Math.min( + idleTimeout, + this.idleTimeoutForInitialStore + ); + const idleTimeoutAfterLargeChanges = this.idleTimeoutAfterLargeChanges; + const resolvedPromise = Promise.resolve(); + + let timeSpendInBuild = 0; + let timeSpendInStore = 0; + let avgTimeSpendInStore = 0; + + /** @type {Map Promise>} */ + const pendingIdleTasks = new Map(); + + compiler.cache.hooks.store.tap( + { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, + (identifier, etag, data) => { + pendingIdleTasks.set(identifier, () => + strategy.store(identifier, etag, data) ); - sideEffectDep.loc = statement.loc; - parser.state.module.addDependency(sideEffectDep); - return true; } ); - parser.hooks.importSpecifier.tap( - "HarmonyImportDependencyParserPlugin", - (statement, source, id, name) => { - const ids = id === null ? [] : [id]; - parser.tagVariable(name, harmonySpecifierTag, { - name, - source, - ids, - sourceOrder: parser.state.lastHarmonyImportOrder, - assertions: getAssertions(statement) - }); - return true; + + compiler.cache.hooks.get.tapPromise( + { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, + (identifier, etag, gotHandlers) => { + const restore = () => + strategy.restore(identifier, etag).then(cacheEntry => { + if (cacheEntry === undefined) { + gotHandlers.push((result, callback) => { + if (result !== undefined) { + pendingIdleTasks.set(identifier, () => + strategy.store(identifier, etag, result) + ); + } + callback(); + }); + } else { + return cacheEntry; + } + }); + const pendingTask = pendingIdleTasks.get(identifier); + if (pendingTask !== undefined) { + pendingIdleTasks.delete(identifier); + return pendingTask().then(restore); + } + return restore(); } ); - parser.hooks.expression - .for(harmonySpecifierTag) - .tap("HarmonyImportDependencyParserPlugin", expr => { - const settings = /** @type {HarmonySettings} */ (parser.currentTagData); - const dep = new HarmonyImportSpecifierDependency( - settings.source, - settings.sourceOrder, - settings.ids, - settings.name, - expr.range, - exportPresenceMode, - settings.assertions - ); - dep.shorthand = parser.scope.inShorthand; - dep.directImport = true; - dep.asiSafe = !parser.isAsiPosition(expr.range[0]); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); - return true; - }); - parser.hooks.expressionMemberChain - .for(harmonySpecifierTag) - .tap("HarmonyImportDependencyParserPlugin", (expr, members) => { - const settings = /** @type {HarmonySettings} */ (parser.currentTagData); - const ids = settings.ids.concat(members); - const dep = new HarmonyImportSpecifierDependency( - settings.source, - settings.sourceOrder, - ids, - settings.name, - expr.range, - exportPresenceMode, - settings.assertions - ); - dep.asiSafe = !parser.isAsiPosition(expr.range[0]); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); - return true; - }); - parser.hooks.callMemberChain - .for(harmonySpecifierTag) - .tap("HarmonyImportDependencyParserPlugin", (expr, members) => { - const { arguments: args, callee } = expr; - const settings = /** @type {HarmonySettings} */ (parser.currentTagData); - const ids = settings.ids.concat(members); - const dep = new HarmonyImportSpecifierDependency( - settings.source, - settings.sourceOrder, - ids, - settings.name, - callee.range, - exportPresenceMode, - settings.assertions + + compiler.cache.hooks.storeBuildDependencies.tap( + { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, + dependencies => { + pendingIdleTasks.set(BUILD_DEPENDENCIES_KEY, () => + strategy.storeBuildDependencies(dependencies) ); - dep.directImport = members.length === 0; - dep.call = true; - dep.asiSafe = !parser.isAsiPosition(callee.range[0]); - // only in case when we strictly follow the spec we need a special case here - dep.namespaceObjectAsContext = - members.length > 0 && this.strictThisContextOnImports; - dep.loc = callee.loc; - parser.state.module.addDependency(dep); - if (args) parser.walkExpressions(args); - InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); - return true; - }); - const { hotAcceptCallback, hotAcceptWithoutCallback } = - HotModuleReplacementPlugin.getParserHooks(parser); - hotAcceptCallback.tap( - "HarmonyImportDependencyParserPlugin", - (expr, requests) => { - if (!HarmonyExports.isEnabled(parser.state)) { - // This is not a harmony module, skip it - return; + } + ); + + compiler.cache.hooks.shutdown.tapPromise( + { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, + () => { + if (idleTimer) { + clearTimeout(idleTimer); + idleTimer = undefined; } - const dependencies = requests.map(request => { - const dep = new HarmonyAcceptImportDependency(request); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return dep; - }); - if (dependencies.length > 0) { - const dep = new HarmonyAcceptDependency( - expr.range, - dependencies, - true - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); + isIdle = false; + const reportProgress = ProgressPlugin.getReporter(compiler); + const jobs = Array.from(pendingIdleTasks.values()); + if (reportProgress) reportProgress(0, "process pending cache items"); + const promises = jobs.map(fn => fn()); + pendingIdleTasks.clear(); + promises.push(currentIdlePromise); + const promise = Promise.all(promises); + currentIdlePromise = promise.then(() => strategy.afterAllStored()); + if (reportProgress) { + currentIdlePromise = currentIdlePromise.then(() => { + reportProgress(1, `stored`); + }); } + return currentIdlePromise.then(() => { + // Reset strategy + if (strategy.clear) strategy.clear(); + }); } ); - hotAcceptWithoutCallback.tap( - "HarmonyImportDependencyParserPlugin", - (expr, requests) => { - if (!HarmonyExports.isEnabled(parser.state)) { - // This is not a harmony module, skip it + + /** @type {Promise} */ + let currentIdlePromise = resolvedPromise; + let isIdle = false; + let isInitialStore = true; + const processIdleTasks = () => { + if (isIdle) { + const startTime = Date.now(); + if (pendingIdleTasks.size > 0) { + const promises = [currentIdlePromise]; + const maxTime = startTime + 100; + let maxCount = 100; + for (const [filename, factory] of pendingIdleTasks) { + pendingIdleTasks.delete(filename); + promises.push(factory()); + if (maxCount-- <= 0 || Date.now() > maxTime) break; + } + currentIdlePromise = Promise.all(promises); + currentIdlePromise.then(() => { + timeSpendInStore += Date.now() - startTime; + // Allow to exit the process between + idleTimer = setTimeout(processIdleTasks, 0); + idleTimer.unref(); + }); return; } - const dependencies = requests.map(request => { - const dep = new HarmonyAcceptImportDependency(request); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return dep; - }); - if (dependencies.length > 0) { - const dep = new HarmonyAcceptDependency( - expr.range, - dependencies, - false - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); + currentIdlePromise = currentIdlePromise + .then(async () => { + await strategy.afterAllStored(); + timeSpendInStore += Date.now() - startTime; + avgTimeSpendInStore = + Math.max(avgTimeSpendInStore, timeSpendInStore) * 0.9 + + timeSpendInStore * 0.1; + timeSpendInStore = 0; + timeSpendInBuild = 0; + }) + .catch(err => { + const logger = compiler.getInfrastructureLogger( + "IdleFileCachePlugin" + ); + logger.warn(`Background tasks during idle failed: ${err.message}`); + logger.debug(err.stack); + }); + isInitialStore = false; + } + }; + let idleTimer = undefined; + compiler.cache.hooks.beginIdle.tap( + { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, + () => { + const isLargeChange = timeSpendInBuild > avgTimeSpendInStore * 2; + if (isInitialStore && idleTimeoutForInitialStore < idleTimeout) { + compiler + .getInfrastructureLogger("IdleFileCachePlugin") + .log( + `Initial cache was generated and cache will be persisted in ${ + idleTimeoutForInitialStore / 1000 + }s.` + ); + } else if ( + isLargeChange && + idleTimeoutAfterLargeChanges < idleTimeout + ) { + compiler + .getInfrastructureLogger("IdleFileCachePlugin") + .log( + `Spend ${Math.round(timeSpendInBuild) / 1000}s in build and ${ + Math.round(avgTimeSpendInStore) / 1000 + }s in average in cache store. This is considered as large change and cache will be persisted in ${ + idleTimeoutAfterLargeChanges / 1000 + }s.` + ); + } + idleTimer = setTimeout(() => { + idleTimer = undefined; + isIdle = true; + resolvedPromise.then(processIdleTasks); + }, Math.min(isInitialStore ? idleTimeoutForInitialStore : Infinity, isLargeChange ? idleTimeoutAfterLargeChanges : Infinity, idleTimeout)); + idleTimer.unref(); + } + ); + compiler.cache.hooks.endIdle.tap( + { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, + () => { + if (idleTimer) { + clearTimeout(idleTimer); + idleTimer = undefined; } + isIdle = false; } ); + compiler.hooks.done.tap("IdleFileCachePlugin", stats => { + // 10% build overhead is ignored, as it's not cacheable + timeSpendInBuild *= 0.9; + timeSpendInBuild += stats.endTime - stats.startTime; + }); } -}; +} -module.exports.harmonySpecifierTag = harmonySpecifierTag; -module.exports.getAssertions = getAssertions; +module.exports = IdleFileCachePlugin; /***/ }), -/***/ 73132: +/***/ 52539: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -79298,84 +73671,198 @@ module.exports.getAssertions = getAssertions; -const makeSerializable = __webpack_require__(33032); -const HarmonyImportDependency = __webpack_require__(57154); +const Cache = __webpack_require__(7592); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../InitFragment")} InitFragment */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Cache").Etag} Etag */ +/** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -class HarmonyImportSideEffectDependency extends HarmonyImportDependency { - constructor(request, sourceOrder, assertions) { - super(request, sourceOrder, assertions); - } - - get type() { - return "harmony side effect evaluation"; - } - - /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active - */ - getCondition(moduleGraph) { - return connection => { - const refModule = connection.resolvedModule; - if (!refModule) return true; - return refModule.getSideEffectsConnectionState(moduleGraph); - }; - } +class MemoryCachePlugin { /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - getModuleEvaluationSideEffectsState(moduleGraph) { - const refModule = moduleGraph.getModule(this); - if (!refModule) return true; - return refModule.getSideEffectsConnectionState(moduleGraph); + apply(compiler) { + /** @type {Map} */ + const cache = new Map(); + compiler.cache.hooks.store.tap( + { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, + (identifier, etag, data) => { + cache.set(identifier, { etag, data }); + } + ); + compiler.cache.hooks.get.tap( + { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, + (identifier, etag, gotHandlers) => { + const cacheEntry = cache.get(identifier); + if (cacheEntry === null) { + return null; + } else if (cacheEntry !== undefined) { + return cacheEntry.etag === etag ? cacheEntry.data : null; + } + gotHandlers.push((result, callback) => { + if (result === undefined) { + cache.set(identifier, null); + } else { + cache.set(identifier, { etag, data: result }); + } + return callback(); + }); + } + ); + compiler.cache.hooks.shutdown.tap( + { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, + () => { + cache.clear(); + } + ); } } +module.exports = MemoryCachePlugin; -makeSerializable( - HarmonyImportSideEffectDependency, - "webpack/lib/dependencies/HarmonyImportSideEffectDependency" -); -HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends ( - HarmonyImportDependency.Template -) { +/***/ }), + +/***/ 99334: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const Cache = __webpack_require__(7592); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Cache").Etag} Etag */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +class MemoryWithGcCachePlugin { + constructor({ maxGenerations }) { + this._maxGenerations = maxGenerations; + } /** - * @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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply(dependency, source, templateContext) { - const { moduleGraph, concatenationScope } = templateContext; - if (concatenationScope) { - const module = moduleGraph.getModule(dependency); - if (concatenationScope.isModuleInScope(module)) { - return; + apply(compiler) { + const maxGenerations = this._maxGenerations; + /** @type {Map} */ + const cache = new Map(); + /** @type {Map} */ + const oldCache = new Map(); + let generation = 0; + let cachePosition = 0; + const logger = compiler.getInfrastructureLogger("MemoryWithGcCachePlugin"); + compiler.hooks.afterDone.tap("MemoryWithGcCachePlugin", () => { + generation++; + let clearedEntries = 0; + let lastClearedIdentifier; + for (const [identifier, entry] of oldCache) { + if (entry.until > generation) break; + + oldCache.delete(identifier); + if (cache.get(identifier) === undefined) { + cache.delete(identifier); + clearedEntries++; + lastClearedIdentifier = identifier; + } } - } - super.apply(dependency, source, templateContext); + if (clearedEntries > 0 || oldCache.size > 0) { + logger.log( + `${cache.size - oldCache.size} active entries, ${ + oldCache.size + } recently unused cached entries${ + clearedEntries > 0 + ? `, ${clearedEntries} old unused cache entries removed e. g. ${lastClearedIdentifier}` + : "" + }` + ); + } + let i = (cache.size / maxGenerations) | 0; + let j = cachePosition >= cache.size ? 0 : cachePosition; + cachePosition = j + i; + for (const [identifier, entry] of cache) { + if (j !== 0) { + j--; + continue; + } + if (entry !== undefined) { + // We don't delete the cache entry, but set it to undefined instead + // This reserves the location in the data table and avoids rehashing + // when constantly adding and removing entries. + // It will be deleted when removed from oldCache. + cache.set(identifier, undefined); + oldCache.delete(identifier); + oldCache.set(identifier, { + entry, + until: generation + maxGenerations + }); + if (i-- === 0) break; + } + } + }); + compiler.cache.hooks.store.tap( + { name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY }, + (identifier, etag, data) => { + cache.set(identifier, { etag, data }); + } + ); + compiler.cache.hooks.get.tap( + { name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY }, + (identifier, etag, gotHandlers) => { + const cacheEntry = cache.get(identifier); + if (cacheEntry === null) { + return null; + } else if (cacheEntry !== undefined) { + return cacheEntry.etag === etag ? cacheEntry.data : null; + } + const oldCacheEntry = oldCache.get(identifier); + if (oldCacheEntry !== undefined) { + const cacheEntry = oldCacheEntry.entry; + if (cacheEntry === null) { + oldCache.delete(identifier); + cache.set(identifier, cacheEntry); + return null; + } else { + if (cacheEntry.etag !== etag) return null; + oldCache.delete(identifier); + cache.set(identifier, cacheEntry); + return cacheEntry.data; + } + } + gotHandlers.push((result, callback) => { + if (result === undefined) { + cache.set(identifier, null); + } else { + cache.set(identifier, { etag, data: result }); + } + return callback(); + }); + } + ); + compiler.cache.hooks.shutdown.tap( + { name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY }, + () => { + cache.clear(); + oldCache.clear(); + } + ); } -}; - -module.exports = HarmonyImportSideEffectDependency; +} +module.exports = MemoryWithGcCachePlugin; /***/ }), -/***/ 14077: +/***/ 86180: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -79386,1027 +73873,1903 @@ module.exports = HarmonyImportSideEffectDependency; -const Dependency = __webpack_require__(54912); -const { - getDependencyUsedByExportsCondition -} = __webpack_require__(38988); +const FileSystemInfo = __webpack_require__(79453); +const ProgressPlugin = __webpack_require__(13216); +const { formatSize } = __webpack_require__(71070); +const SerializerMiddleware = __webpack_require__(83137); +const LazySet = __webpack_require__(38938); const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const HarmonyImportDependency = __webpack_require__(57154); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -const idsSymbol = Symbol("HarmonyImportSpecifierDependency.ids"); +const memoize = __webpack_require__(78676); +const { + createFileSerializer, + NOT_SERIALIZABLE +} = __webpack_require__(8282); -const { ExportPresenceModes } = HarmonyImportDependency; +/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */ +/** @typedef {import("../Cache").Etag} Etag */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */ +/** @typedef {import("../logging/Logger").Logger} Logger */ +/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ -class HarmonyImportSpecifierDependency extends HarmonyImportDependency { +class PackContainer { + /** + * @param {Object} data stored data + * @param {string} version version identifier + * @param {Snapshot} buildSnapshot snapshot of all build dependencies + * @param {Set} buildDependencies list of all unresolved build dependencies captured + * @param {Map} resolveResults result of the resolved build dependencies + * @param {Snapshot} resolveBuildDependenciesSnapshot snapshot of the dependencies of the build dependencies resolving + */ constructor( - request, - sourceOrder, - ids, - name, - range, - exportPresenceMode, - assertions + data, + version, + buildSnapshot, + buildDependencies, + resolveResults, + resolveBuildDependenciesSnapshot ) { - super(request, sourceOrder, assertions); - this.ids = ids; - this.name = name; - this.range = range; - this.exportPresenceMode = exportPresenceMode; - this.namespaceObjectAsContext = false; - this.call = undefined; - this.directImport = undefined; - this.shorthand = undefined; - this.asiSafe = undefined; - /** @type {Set | boolean} */ - this.usedByExports = undefined; + this.data = data; + this.version = version; + this.buildSnapshot = buildSnapshot; + this.buildDependencies = buildDependencies; + this.resolveResults = resolveResults; + this.resolveBuildDependenciesSnapshot = resolveBuildDependenciesSnapshot; } - // TODO webpack 6 remove - get id() { - throw new Error("id was renamed to ids and type changed to string[]"); + serialize({ write, writeLazy }) { + write(this.version); + write(this.buildSnapshot); + write(this.buildDependencies); + write(this.resolveResults); + write(this.resolveBuildDependenciesSnapshot); + writeLazy(this.data); } - // TODO webpack 6 remove - getId() { - throw new Error("id was renamed to ids and type changed to string[]"); + deserialize({ read }) { + this.version = read(); + this.buildSnapshot = read(); + this.buildDependencies = read(); + this.resolveResults = read(); + this.resolveBuildDependenciesSnapshot = read(); + this.data = read(); } +} - // TODO webpack 6 remove - setId() { - throw new Error("id was renamed to ids and type changed to string[]"); - } +makeSerializable( + PackContainer, + "webpack/lib/cache/PackFileCacheStrategy", + "PackContainer" +); - get type() { - return "harmony import specifier"; - } +const MIN_CONTENT_SIZE = 1024 * 1024; // 1 MB +const CONTENT_COUNT_TO_MERGE = 10; +const MIN_ITEMS_IN_FRESH_PACK = 100; +const MAX_ITEMS_IN_FRESH_PACK = 50000; +const MAX_TIME_IN_FRESH_PACK = 1 * 60 * 1000; // 1 min +class PackItemInfo { /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {string[]} the imported ids + * @param {string} identifier identifier of item + * @param {string | null} etag etag of item + * @param {any} value fresh value of item */ - getIds(moduleGraph) { - const meta = moduleGraph.getMetaIfExisting(this); - if (meta === undefined) return this.ids; - const ids = meta[idsSymbol]; - return ids !== undefined ? ids : this.ids; + constructor(identifier, etag, value) { + this.identifier = identifier; + this.etag = etag; + this.location = -1; + this.lastAccess = Date.now(); + this.freshValue = value; } +} - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {string[]} ids the imported ids - * @returns {void} - */ - setIds(moduleGraph, ids) { - moduleGraph.getMeta(this)[idsSymbol] = ids; +class Pack { + constructor(logger, maxAge) { + /** @type {Map} */ + this.itemInfo = new Map(); + /** @type {string[]} */ + this.requests = []; + this.requestsTimeout = undefined; + /** @type {Map} */ + this.freshContent = new Map(); + /** @type {(undefined | PackContent)[]} */ + this.content = []; + this.invalid = false; + this.logger = logger; + this.maxAge = maxAge; } - /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active - */ - getCondition(moduleGraph) { - return getDependencyUsedByExportsCondition( - this, - this.usedByExports, - moduleGraph - ); + _addRequest(identifier) { + this.requests.push(identifier); + if (this.requestsTimeout === undefined) { + this.requestsTimeout = setTimeout(() => { + this.requests.push(undefined); + this.requestsTimeout = undefined; + }, MAX_TIME_IN_FRESH_PACK); + if (this.requestsTimeout.unref) this.requestsTimeout.unref(); + } + } + + stopCapturingRequests() { + if (this.requestsTimeout !== undefined) { + clearTimeout(this.requestsTimeout); + this.requestsTimeout = undefined; + } } /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules + * @param {string} identifier unique name for the resource + * @param {string | null} etag etag of the resource + * @returns {any} cached content */ - getModuleEvaluationSideEffectsState(moduleGraph) { - return false; + get(identifier, etag) { + const info = this.itemInfo.get(identifier); + this._addRequest(identifier); + if (info === undefined) { + return undefined; + } + if (info.etag !== etag) return null; + info.lastAccess = Date.now(); + const loc = info.location; + if (loc === -1) { + return info.freshValue; + } else { + if (!this.content[loc]) { + return undefined; + } + return this.content[loc].get(identifier); + } } /** - * 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 + * @param {string} identifier unique name for the resource + * @param {string | null} etag etag of the resource + * @param {any} data cached content + * @returns {void} */ - getReferencedExports(moduleGraph, runtime) { - let ids = this.getIds(moduleGraph); - if (ids.length === 0) return Dependency.EXPORTS_OBJECT_REFERENCED; - let namespaceObjectAsContext = this.namespaceObjectAsContext; - if (ids[0] === "default") { - const selfModule = moduleGraph.getParentModule(this); - const importedModule = moduleGraph.getModule(this); - switch ( - importedModule.getExportsType( - moduleGraph, - selfModule.buildMeta.strictHarmonyModule - ) - ) { - case "default-only": - case "default-with-named": - if (ids.length === 1) return Dependency.EXPORTS_OBJECT_REFERENCED; - ids = ids.slice(1); - namespaceObjectAsContext = true; - break; - case "dynamic": - return Dependency.EXPORTS_OBJECT_REFERENCED; + set(identifier, etag, data) { + if (!this.invalid) { + this.invalid = true; + this.logger.log(`Pack got invalid because of write to: ${identifier}`); + } + const info = this.itemInfo.get(identifier); + if (info === undefined) { + const newInfo = new PackItemInfo(identifier, etag, data); + this.itemInfo.set(identifier, newInfo); + this._addRequest(identifier); + this.freshContent.set(identifier, newInfo); + } else { + const loc = info.location; + if (loc >= 0) { + this._addRequest(identifier); + this.freshContent.set(identifier, info); + const content = this.content[loc]; + content.delete(identifier); + if (content.items.size === 0) { + this.content[loc] = undefined; + this.logger.debug("Pack %d got empty and is removed", loc); + } } + info.freshValue = data; + info.lastAccess = Date.now(); + info.etag = etag; + info.location = -1; } + } - if ( - this.call && - !this.directImport && - (namespaceObjectAsContext || ids.length > 1) - ) { - if (ids.length === 1) return Dependency.EXPORTS_OBJECT_REFERENCED; - ids = ids.slice(0, -1); + getContentStats() { + let count = 0; + let size = 0; + for (const content of this.content) { + if (content !== undefined) { + count++; + const s = content.getSize(); + if (s > 0) { + size += s; + } + } } - - return [ids]; + return { count, size }; } /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {number} effective mode + * @returns {number} new location of data entries */ - _getEffectiveExportPresenceLevel(moduleGraph) { - if (this.exportPresenceMode !== ExportPresenceModes.AUTO) - return this.exportPresenceMode; - return moduleGraph.getParentModule(this).buildMeta.strictHarmonyModule - ? ExportPresenceModes.ERROR - : ExportPresenceModes.WARN; + _findLocation() { + let i; + for (i = 0; i < this.content.length && this.content[i] !== undefined; i++); + return i; } - /** - * Returns warnings - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} warnings - */ - getWarnings(moduleGraph) { - const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); - if (exportsPresence === ExportPresenceModes.WARN) { - return this._getErrors(moduleGraph); + _gcAndUpdateLocation(items, usedItems, newLoc) { + let count = 0; + let lastGC; + const now = Date.now(); + for (const identifier of items) { + const info = this.itemInfo.get(identifier); + if (now - info.lastAccess > this.maxAge) { + this.itemInfo.delete(identifier); + items.delete(identifier); + usedItems.delete(identifier); + count++; + lastGC = identifier; + } else { + info.location = newLoc; + } + } + if (count > 0) { + this.logger.log( + "Garbage Collected %d old items at pack %d (%d items remaining) e. g. %s", + count, + newLoc, + items.size, + lastGC + ); } - return null; } - /** - * Returns errors - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} errors - */ - getErrors(moduleGraph) { - const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); - if (exportsPresence === ExportPresenceModes.ERROR) { - return this._getErrors(moduleGraph); + _persistFreshContent() { + const itemsCount = this.freshContent.size; + if (itemsCount > 0) { + const packCount = Math.ceil(itemsCount / MAX_ITEMS_IN_FRESH_PACK); + const itemsPerPack = Math.ceil(itemsCount / packCount); + const packs = []; + let i = 0; + let ignoreNextTimeTick = false; + const createNextPack = () => { + const loc = this._findLocation(); + this.content[loc] = null; // reserve + const pack = { + /** @type {Set} */ + items: new Set(), + /** @type {Map} */ + map: new Map(), + loc + }; + packs.push(pack); + return pack; + }; + let pack = createNextPack(); + if (this.requestsTimeout !== undefined) + clearTimeout(this.requestsTimeout); + for (const identifier of this.requests) { + if (identifier === undefined) { + if (ignoreNextTimeTick) { + ignoreNextTimeTick = false; + } else if (pack.items.size >= MIN_ITEMS_IN_FRESH_PACK) { + i = 0; + pack = createNextPack(); + } + continue; + } + const info = this.freshContent.get(identifier); + if (info === undefined) continue; + pack.items.add(identifier); + pack.map.set(identifier, info.freshValue); + info.location = pack.loc; + info.freshValue = undefined; + this.freshContent.delete(identifier); + if (++i > itemsPerPack) { + i = 0; + pack = createNextPack(); + ignoreNextTimeTick = true; + } + } + this.requests.length = 0; + for (const pack of packs) { + this.content[pack.loc] = new PackContent( + pack.items, + new Set(pack.items), + new PackContentItems(pack.map) + ); + } + this.logger.log( + `${itemsCount} fresh items in cache put into pack ${ + packs.length > 1 + ? packs + .map(pack => `${pack.loc} (${pack.items.size} items)`) + .join(", ") + : packs[0].loc + }` + ); } - return null; } /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[] | undefined} errors + * Merges small content files to a single content file */ - _getErrors(moduleGraph) { - const ids = this.getIds(moduleGraph); - return this.getLinkingErrors( - moduleGraph, - ids, - `(imported as '${this.name}')` - ); - } + _optimizeSmallContent() { + // 1. Find all small content files + // Treat unused content files separately to avoid + // a merge-split cycle + /** @type {number[]} */ + const smallUsedContents = []; + /** @type {number} */ + let smallUsedContentSize = 0; + /** @type {number[]} */ + const smallUnusedContents = []; + /** @type {number} */ + let smallUnusedContentSize = 0; + for (let i = 0; i < this.content.length; i++) { + const content = this.content[i]; + if (content === undefined) continue; + if (content.outdated) continue; + const size = content.getSize(); + if (size < 0 || size > MIN_CONTENT_SIZE) continue; + if (content.used.size > 0) { + smallUsedContents.push(i); + smallUsedContentSize += size; + } else { + smallUnusedContents.push(i); + smallUnusedContentSize += size; + } + } - /** - * 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 0; - } + // 2. Check if minimum number is reached + let mergedIndices; + if ( + smallUsedContents.length >= CONTENT_COUNT_TO_MERGE || + smallUsedContentSize > MIN_CONTENT_SIZE + ) { + mergedIndices = smallUsedContents; + } else if ( + smallUnusedContents.length >= CONTENT_COUNT_TO_MERGE || + smallUnusedContentSize > MIN_CONTENT_SIZE + ) { + mergedIndices = smallUnusedContents; + } else return; - serialize(context) { - const { write } = context; - write(this.ids); - write(this.name); - write(this.range); - write(this.exportPresenceMode); - write(this.namespaceObjectAsContext); - write(this.call); - write(this.directImport); - write(this.shorthand); - write(this.asiSafe); - write(this.usedByExports); - super.serialize(context); - } + const mergedContent = []; - deserialize(context) { - const { read } = context; - this.ids = read(); - this.name = read(); - this.range = read(); - this.exportPresenceMode = read(); - this.namespaceObjectAsContext = read(); - this.call = read(); - this.directImport = read(); - this.shorthand = read(); - this.asiSafe = read(); - this.usedByExports = read(); - super.deserialize(context); - } -} - -makeSerializable( - HarmonyImportSpecifierDependency, - "webpack/lib/dependencies/HarmonyImportSpecifierDependency" -); - -HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate extends ( - HarmonyImportDependency.Template -) { - /** - * @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 dep = /** @type {HarmonyImportSpecifierDependency} */ (dependency); - const { moduleGraph, module, runtime, concatenationScope } = - templateContext; - const connection = moduleGraph.getConnection(dep); - // Skip rendering depending when dependency is conditional - if (connection && !connection.isTargetActive(runtime)) return; - - const ids = dep.getIds(moduleGraph); + // 3. Remove old content entries + for (const i of mergedIndices) { + mergedContent.push(this.content[i]); + this.content[i] = undefined; + } - let exportExpr; - if ( - connection && - concatenationScope && - concatenationScope.isModuleInScope(connection.module) - ) { - if (ids.length === 0) { - exportExpr = concatenationScope.createModuleReference( - connection.module, - { - asiSafe: dep.asiSafe - } - ); - } else if (dep.namespaceObjectAsContext && ids.length === 1) { - exportExpr = - concatenationScope.createModuleReference(connection.module, { - asiSafe: dep.asiSafe - }) + propertyAccess(ids); - } else { - exportExpr = concatenationScope.createModuleReference( - connection.module, - { - ids, - call: dep.call, - directImport: dep.directImport, - asiSafe: dep.asiSafe - } - ); + // 4. Determine merged items + /** @type {Set} */ + const mergedItems = new Set(); + /** @type {Set} */ + const mergedUsedItems = new Set(); + /** @type {(function(Map): Promise)[]} */ + const addToMergedMap = []; + for (const content of mergedContent) { + for (const identifier of content.items) { + mergedItems.add(identifier); } - } else { - super.apply(dependency, source, templateContext); - - const { runtimeTemplate, initFragments, runtimeRequirements } = - templateContext; - - exportExpr = runtimeTemplate.exportFromImport({ - moduleGraph, - module: moduleGraph.getModule(dep), - request: dep.request, - exportName: ids, - originModule: module, - asiSafe: dep.shorthand ? true : dep.asiSafe, - isCall: dep.call, - callContext: !dep.directImport, - defaultInterop: true, - importVar: dep.getImportVar(moduleGraph), - initFragments, - runtime, - runtimeRequirements + for (const identifier of content.used) { + mergedUsedItems.add(identifier); + } + addToMergedMap.push(async map => { + // unpack existing content + // after that values are accessible in .content + await content.unpack( + "it should be merged with other small pack contents" + ); + for (const [identifier, value] of content.content) { + map.set(identifier, value); + } }); } - if (dep.shorthand) { - source.insert(dep.range[1], `: ${exportExpr}`); - } else { - source.replace(dep.range[0], dep.range[1] - 1, exportExpr); - } - } -}; - -module.exports = HarmonyImportSpecifierDependency; - - -/***/ }), - -/***/ 39029: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const HarmonyAcceptDependency = __webpack_require__(23624); -const HarmonyAcceptImportDependency = __webpack_require__(99843); -const HarmonyCompatibilityDependency = __webpack_require__(72906); -const HarmonyExportExpressionDependency = __webpack_require__(51340); -const HarmonyExportHeaderDependency = __webpack_require__(38873); -const HarmonyExportImportedSpecifierDependency = __webpack_require__(67157); -const HarmonyExportSpecifierDependency = __webpack_require__(48567); -const HarmonyImportSideEffectDependency = __webpack_require__(73132); -const HarmonyImportSpecifierDependency = __webpack_require__(14077); - -const HarmonyDetectionParserPlugin = __webpack_require__(17223); -const HarmonyExportDependencyParserPlugin = __webpack_require__(93466); -const HarmonyImportDependencyParserPlugin = __webpack_require__(20862); -const HarmonyTopLevelThisParserPlugin = __webpack_require__(63232); -/** @typedef {import("../Compiler")} Compiler */ + // 5. GC and update location of merged items + const newLoc = this._findLocation(); + this._gcAndUpdateLocation(mergedItems, mergedUsedItems, newLoc); -class HarmonyModulesPlugin { - constructor(options) { - this.options = options; + // 6. If not empty, store content somewhere + if (mergedItems.size > 0) { + this.content[newLoc] = new PackContent( + mergedItems, + mergedUsedItems, + memoize(async () => { + /** @type {Map} */ + const map = new Map(); + await Promise.all(addToMergedMap.map(fn => fn(map))); + return new PackContentItems(map); + }) + ); + this.logger.log( + "Merged %d small files with %d cache items into pack %d", + mergedContent.length, + mergedItems.size, + newLoc + ); + } } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * Split large content files with used and unused items + * into two parts to separate used from unused items */ - apply(compiler) { - compiler.hooks.compilation.tap( - "HarmonyModulesPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyTemplates.set( - HarmonyCompatibilityDependency, - new HarmonyCompatibilityDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyImportSideEffectDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - HarmonyImportSideEffectDependency, - new HarmonyImportSideEffectDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyImportSpecifierDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - HarmonyImportSpecifierDependency, - new HarmonyImportSpecifierDependency.Template() - ); - - compilation.dependencyTemplates.set( - HarmonyExportHeaderDependency, - new HarmonyExportHeaderDependency.Template() - ); + _optimizeUnusedContent() { + // 1. Find a large content file with used and unused items + for (let i = 0; i < this.content.length; i++) { + const content = this.content[i]; + if (content === undefined) continue; + const size = content.getSize(); + if (size < MIN_CONTENT_SIZE) continue; + const used = content.used.size; + const total = content.items.size; + if (used > 0 && used < total) { + // 2. Remove this content + this.content[i] = undefined; - compilation.dependencyTemplates.set( - HarmonyExportExpressionDependency, - new HarmonyExportExpressionDependency.Template() - ); + // 3. Determine items for the used content file + const usedItems = new Set(content.used); + const newLoc = this._findLocation(); + this._gcAndUpdateLocation(usedItems, usedItems, newLoc); - compilation.dependencyTemplates.set( - HarmonyExportSpecifierDependency, - new HarmonyExportSpecifierDependency.Template() - ); + // 4. Create content file for used items + if (usedItems.size > 0) { + this.content[newLoc] = new PackContent( + usedItems, + new Set(usedItems), + async () => { + await content.unpack( + "it should be splitted into used and unused items" + ); + const map = new Map(); + for (const identifier of usedItems) { + map.set(identifier, content.content.get(identifier)); + } + return new PackContentItems(map); + } + ); + } - compilation.dependencyFactories.set( - HarmonyExportImportedSpecifierDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - HarmonyExportImportedSpecifierDependency, - new HarmonyExportImportedSpecifierDependency.Template() - ); + // 5. Determine items for the unused content file + const unusedItems = new Set(content.items); + const usedOfUnusedItems = new Set(); + for (const identifier of usedItems) { + unusedItems.delete(identifier); + } + const newUnusedLoc = this._findLocation(); + this._gcAndUpdateLocation(unusedItems, usedOfUnusedItems, newUnusedLoc); - compilation.dependencyTemplates.set( - HarmonyAcceptDependency, - new HarmonyAcceptDependency.Template() - ); + // 6. Create content file for unused items + if (unusedItems.size > 0) { + this.content[newUnusedLoc] = new PackContent( + unusedItems, + usedOfUnusedItems, + async () => { + await content.unpack( + "it should be splitted into used and unused items" + ); + const map = new Map(); + for (const identifier of unusedItems) { + map.set(identifier, content.content.get(identifier)); + } + return new PackContentItems(map); + } + ); + } - compilation.dependencyFactories.set( - HarmonyAcceptImportDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - HarmonyAcceptImportDependency, - new HarmonyAcceptImportDependency.Template() + this.logger.log( + "Split pack %d into pack %d with %d used items and pack %d with %d unused items", + i, + newLoc, + usedItems.size, + newUnusedLoc, + unusedItems.size ); - const handler = (parser, parserOptions) => { - // TODO webpack 6: rename harmony to esm or module - if (parserOptions.harmony !== undefined && !parserOptions.harmony) - return; - - new HarmonyDetectionParserPlugin(this.options).apply(parser); - new HarmonyImportDependencyParserPlugin(parserOptions).apply(parser); - new HarmonyExportDependencyParserPlugin(parserOptions).apply(parser); - new HarmonyTopLevelThisParserPlugin().apply(parser); - }; - - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("HarmonyModulesPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("HarmonyModulesPlugin", handler); + // optimizing only one of them is good enough and + // reduces the amount of serialization needed + return; } - ); + } } -} -module.exports = HarmonyModulesPlugin; - - -/***/ }), - -/***/ 63232: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ + /** + * Find the content with the oldest item and run GC on that. + * Only runs for one content to avoid large invalidation. + */ + _gcOldestContent() { + /** @type {PackItemInfo} */ + let oldest = undefined; + for (const info of this.itemInfo.values()) { + if (oldest === undefined || info.lastAccess < oldest.lastAccess) { + oldest = info; + } + } + if (Date.now() - oldest.lastAccess > this.maxAge) { + const loc = oldest.location; + if (loc < 0) return; + const content = this.content[loc]; + const items = new Set(content.items); + const usedItems = new Set(content.used); + this._gcAndUpdateLocation(items, usedItems, loc); + this.content[loc] = + items.size > 0 + ? new PackContent(items, usedItems, async () => { + await content.unpack( + "it contains old items that should be garbage collected" + ); + const map = new Map(); + for (const identifier of items) { + map.set(identifier, content.content.get(identifier)); + } + return new PackContentItems(map); + }) + : undefined; + } + } -const ConstDependency = __webpack_require__(76911); -const HarmonyExports = __webpack_require__(39211); + serialize({ write, writeSeparate }) { + this._persistFreshContent(); + this._optimizeSmallContent(); + this._optimizeUnusedContent(); + this._gcOldestContent(); + for (const identifier of this.itemInfo.keys()) { + write(identifier); + } + write(null); // null as marker of the end of keys + for (const info of this.itemInfo.values()) { + write(info.etag); + } + for (const info of this.itemInfo.values()) { + write(info.lastAccess); + } + for (let i = 0; i < this.content.length; i++) { + const content = this.content[i]; + if (content !== undefined) { + write(content.items); + content.writeLazy(lazy => writeSeparate(lazy, { name: `${i}` })); + } else { + write(undefined); // undefined marks an empty content slot + } + } + write(null); // null as marker of the end of items + } -class HarmonyTopLevelThisParserPlugin { - apply(parser) { - parser.hooks.expression - .for("this") - .tap("HarmonyTopLevelThisParserPlugin", node => { - if (!parser.scope.topLevelScope) return; - if (HarmonyExports.isEnabled(parser.state)) { - const dep = new ConstDependency("undefined", node.range, null); - dep.loc = node.loc; - parser.state.module.addPresentationalDependency(dep); - return this; - } + deserialize({ read, logger }) { + this.logger = logger; + { + const items = []; + let item = read(); + while (item !== null) { + items.push(item); + item = read(); + } + this.itemInfo.clear(); + const infoItems = items.map(identifier => { + const info = new PackItemInfo(identifier, undefined, undefined); + this.itemInfo.set(identifier, info); + return info; }); + for (const info of infoItems) { + info.etag = read(); + } + for (const info of infoItems) { + info.lastAccess = read(); + } + } + this.content.length = 0; + let items = read(); + while (items !== null) { + if (items === undefined) { + this.content.push(items); + } else { + const idx = this.content.length; + const lazy = read(); + this.content.push( + new PackContent( + items, + new Set(), + lazy, + logger, + `${this.content.length}` + ) + ); + for (const identifier of items) { + this.itemInfo.get(identifier).location = idx; + } + } + items = read(); + } } } -module.exports = HarmonyTopLevelThisParserPlugin; - - -/***/ }), - -/***/ 1902: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const ContextDependency = __webpack_require__(88101); -const ContextDependencyTemplateAsRequireCall = __webpack_require__(75815); - -class ImportContextDependency extends ContextDependency { - constructor(options, range, valueRange) { - super(options); - - this.range = range; - this.valueRange = valueRange; - } - - get type() { - return `import() context ${this.options.mode}`; - } +makeSerializable(Pack, "webpack/lib/cache/PackFileCacheStrategy", "Pack"); - get category() { - return "esm"; +class PackContentItems { + /** + * @param {Map} map items + */ + constructor(map) { + this.map = map; } - serialize(context) { - const { write } = context; - - write(this.range); - write(this.valueRange); + serialize({ write, snapshot, rollback, logger, profile }) { + if (profile) { + write(false); + for (const [key, value] of this.map) { + const s = snapshot(); + try { + write(key); + const start = process.hrtime(); + write(value); + const durationHr = process.hrtime(start); + const duration = durationHr[0] * 1000 + durationHr[1] / 1e6; + if (duration > 1) { + if (duration > 500) + logger.error(`Serialization of '${key}': ${duration} ms`); + else if (duration > 50) + logger.warn(`Serialization of '${key}': ${duration} ms`); + else if (duration > 10) + logger.info(`Serialization of '${key}': ${duration} ms`); + else if (duration > 5) + logger.log(`Serialization of '${key}': ${duration} ms`); + else logger.debug(`Serialization of '${key}': ${duration} ms`); + } + } catch (e) { + rollback(s); + if (e === NOT_SERIALIZABLE) continue; + logger.warn( + `Skipped not serializable cache item '${key}': ${e.message}` + ); + logger.debug(e.stack); + } + } + write(null); + return; + } + // Try to serialize all at once + const s = snapshot(); + try { + write(true); + write(this.map); + } catch (e) { + rollback(s); - super.serialize(context); + // Try to serialize each item on it's own + write(false); + for (const [key, value] of this.map) { + const s = snapshot(); + try { + write(key); + write(value); + } catch (e) { + rollback(s); + if (e === NOT_SERIALIZABLE) continue; + logger.warn( + `Skipped not serializable cache item '${key}': ${e.message}` + ); + logger.debug(e.stack); + } + } + write(null); + } } - deserialize(context) { - const { read } = context; - - this.range = read(); - this.valueRange = read(); - - super.deserialize(context); + deserialize({ read, logger, profile }) { + if (read()) { + this.map = read(); + } else if (profile) { + const map = new Map(); + let key = read(); + while (key !== null) { + const start = process.hrtime(); + const value = read(); + const durationHr = process.hrtime(start); + const duration = durationHr[0] * 1000 + durationHr[1] / 1e6; + if (duration > 1) { + if (duration > 100) + logger.error(`Deserialization of '${key}': ${duration} ms`); + else if (duration > 20) + logger.warn(`Deserialization of '${key}': ${duration} ms`); + else if (duration > 5) + logger.info(`Deserialization of '${key}': ${duration} ms`); + else if (duration > 2) + logger.log(`Deserialization of '${key}': ${duration} ms`); + else logger.debug(`Deserialization of '${key}': ${duration} ms`); + } + map.set(key, value); + key = read(); + } + this.map = map; + } else { + const map = new Map(); + let key = read(); + while (key !== null) { + map.set(key, read()); + key = read(); + } + this.map = map; + } } } makeSerializable( - ImportContextDependency, - "webpack/lib/dependencies/ImportContextDependency" + PackContentItems, + "webpack/lib/cache/PackFileCacheStrategy", + "PackContentItems" ); -ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; - -module.exports = ImportContextDependency; - - -/***/ }), - -/***/ 89376: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Dependency = __webpack_require__(54912); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); +class PackContent { + /* + This class can be in these states: + | this.lazy | this.content | this.outdated | state + A1 | undefined | Map | false | fresh content + A2 | undefined | Map | true | (will not happen) + B1 | lazy () => {} | undefined | false | not deserialized + B2 | lazy () => {} | undefined | true | not deserialized, but some items has been removed + C1 | lazy* () => {} | Map | false | deserialized + C2 | lazy* () => {} | Map | true | deserialized, and some items has been removed -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + this.used is a subset of this.items. + this.items is a subset of this.content.keys() resp. this.lazy().map.keys() + When this.outdated === false, this.items === this.content.keys() resp. this.lazy().map.keys() + When this.outdated === true, this.items should be used to recreated this.lazy/this.content. + When this.lazy and this.content is set, they contain the same data. + this.get must only be called with a valid item from this.items. + In state C this.lazy is unMemoized + */ -class ImportDependency extends ModuleDependency { /** - * @param {string} request the request - * @param {[number, number]} range expression range - * @param {string[][]=} referencedExports list of referenced exports + * @param {Set} items keys + * @param {Set} usedItems used keys + * @param {PackContentItems | function(): Promise} dataOrFn sync or async content + * @param {Logger=} logger logger for logging + * @param {string=} lazyName name of dataOrFn for logging */ - constructor(request, range, referencedExports) { - super(request); - this.range = range; - this.referencedExports = referencedExports; + constructor(items, usedItems, dataOrFn, logger, lazyName) { + this.items = items; + /** @type {function(): Promise | PackContentItems} */ + this.lazy = typeof dataOrFn === "function" ? dataOrFn : undefined; + /** @type {Map} */ + this.content = typeof dataOrFn === "function" ? undefined : dataOrFn.map; + this.outdated = false; + this.used = usedItems; + this.logger = logger; + this.lazyName = lazyName; } - get type() { - return "import()"; - } + get(identifier) { + this.used.add(identifier); + if (this.content) { + return this.content.get(identifier); + } - get category() { - return "esm"; + // We are in state B + const { lazyName } = this; + let timeMessage; + if (lazyName) { + // only log once + this.lazyName = undefined; + timeMessage = `restore cache content ${lazyName} (${formatSize( + this.getSize() + )})`; + this.logger.log( + `starting to restore cache content ${lazyName} (${formatSize( + this.getSize() + )}) because of request to: ${identifier}` + ); + this.logger.time(timeMessage); + } + const value = this.lazy(); + if ("then" in value) { + return value.then(data => { + const map = data.map; + if (timeMessage) { + this.logger.timeEnd(timeMessage); + } + // Move to state C + this.content = map; + this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + return map.get(identifier); + }); + } else { + const map = value.map; + if (timeMessage) { + this.logger.timeEnd(timeMessage); + } + // Move to state C + this.content = map; + this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + return map.get(identifier); + } } /** - * 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 + * @param {string} reason explanation why unpack is necessary + * @returns {void | Promise} maybe a promise if lazy */ - getReferencedExports(moduleGraph, runtime) { - return this.referencedExports - ? this.referencedExports.map(e => ({ - name: e, - canMangle: false - })) - : Dependency.EXPORTS_OBJECT_REFERENCED; - } + unpack(reason) { + if (this.content) return; - serialize(context) { - context.write(this.range); - context.write(this.referencedExports); - super.serialize(context); + // Move from state B to C + if (this.lazy) { + const { lazyName } = this; + let timeMessage; + if (lazyName) { + // only log once + this.lazyName = undefined; + timeMessage = `unpack cache content ${lazyName} (${formatSize( + this.getSize() + )})`; + this.logger.log( + `starting to unpack cache content ${lazyName} (${formatSize( + this.getSize() + )}) because ${reason}` + ); + this.logger.time(timeMessage); + } + const value = this.lazy(); + if ("then" in value) { + return value.then(data => { + if (timeMessage) { + this.logger.timeEnd(timeMessage); + } + this.content = data.map; + }); + } else { + if (timeMessage) { + this.logger.timeEnd(timeMessage); + } + this.content = value.map; + } + } } - deserialize(context) { - this.range = context.read(); - this.referencedExports = context.read(); - super.deserialize(context); + /** + * @returns {number} size of the content or -1 if not known + */ + getSize() { + if (!this.lazy) return -1; + const options = /** @type {any} */ (this.lazy).options; + if (!options) return -1; + const size = options.size; + if (typeof size !== "number") return -1; + return size; } -} -makeSerializable(ImportDependency, "webpack/lib/dependencies/ImportDependency"); + delete(identifier) { + this.items.delete(identifier); + this.used.delete(identifier); + this.outdated = true; + } -ImportDependency.Template = class ImportDependencyTemplate extends ( - ModuleDependency.Template -) { /** - * @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 + * @template T + * @param {function(any): function(): Promise | PackContentItems} write write function * @returns {void} */ - apply( - dependency, - source, - { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {ImportDependency} */ (dependency); - const block = /** @type {AsyncDependenciesBlock} */ ( - moduleGraph.getParentBlock(dep) - ); - const content = runtimeTemplate.moduleNamespacePromise({ - chunkGraph, - block: block, - module: moduleGraph.getModule(dep), - request: dep.request, - strict: module.buildMeta.strictHarmonyModule, - message: "import()", - runtimeRequirements - }); + writeLazy(write) { + if (!this.outdated && this.lazy) { + // State B1 or C1 + // this.lazy is still the valid deserialized version + write(this.lazy); + return; + } + if (!this.outdated && this.content) { + // State A1 + const map = new Map(this.content); + // Move to state C1 + this.lazy = SerializerMiddleware.unMemoizeLazy( + write(() => new PackContentItems(map)) + ); + return; + } + if (this.content) { + // State A2 or C2 + /** @type {Map} */ + const map = new Map(); + for (const item of this.items) { + map.set(item, this.content.get(item)); + } + // Move to state C1 + this.outdated = false; + this.content = map; + this.lazy = SerializerMiddleware.unMemoizeLazy( + write(() => new PackContentItems(map)) + ); + return; + } + // State B2 + const { lazyName } = this; + let timeMessage; + if (lazyName) { + // only log once + this.lazyName = undefined; + timeMessage = `unpack cache content ${lazyName} (${formatSize( + this.getSize() + )})`; + this.logger.log( + `starting to unpack cache content ${lazyName} (${formatSize( + this.getSize() + )}) because it's outdated and need to be serialized` + ); + this.logger.time(timeMessage); + } + const value = this.lazy(); + this.outdated = false; + if ("then" in value) { + // Move to state B1 + this.lazy = write(() => + value.then(data => { + if (timeMessage) { + this.logger.timeEnd(timeMessage); + } + const oldMap = data.map; + /** @type {Map} */ + const map = new Map(); + for (const item of this.items) { + map.set(item, oldMap.get(item)); + } + // Move to state C1 (or maybe C2) + this.content = map; + this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); - source.replace(dep.range[0], dep.range[1] - 1, content); + return new PackContentItems(map); + }) + ); + } else { + // Move to state C1 + if (timeMessage) { + this.logger.timeEnd(timeMessage); + } + const oldMap = value.map; + /** @type {Map} */ + const map = new Map(); + for (const item of this.items) { + map.set(item, oldMap.get(item)); + } + this.content = map; + this.lazy = write(() => new PackContentItems(map)); + } } -}; - -module.exports = ImportDependency; - - -/***/ }), - -/***/ 50718: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const ImportDependency = __webpack_require__(89376); +} -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ +const allowCollectingMemory = buf => { + const wasted = buf.buffer.byteLength - buf.byteLength; + if (wasted > 8192 && (wasted > 1048576 || wasted > buf.byteLength)) { + return Buffer.from(buf); + } + return buf; +}; -class ImportEagerDependency extends ImportDependency { +class PackFileCacheStrategy { /** - * @param {string} request the request - * @param {[number, number]} range expression range - * @param {string[][]=} referencedExports list of referenced exports + * @param {Object} options options + * @param {Compiler} options.compiler the compiler + * @param {IntermediateFileSystem} options.fs the filesystem + * @param {string} options.context the context directory + * @param {string} options.cacheLocation the location of the cache data + * @param {string} options.version version identifier + * @param {Logger} options.logger a logger + * @param {SnapshotOptions} options.snapshot options regarding snapshotting + * @param {number} options.maxAge max age of cache items + * @param {boolean} options.profile track and log detailed timing information for individual cache items + * @param {boolean} options.allowCollectingMemory allow to collect unused memory created during deserialization + * @param {false | "gzip" | "brotli"} options.compression compression used */ - constructor(request, range, referencedExports) { - super(request, range, referencedExports); - } - - get type() { - return "import() eager"; + constructor({ + compiler, + fs, + context, + cacheLocation, + version, + logger, + snapshot, + maxAge, + profile, + allowCollectingMemory, + compression + }) { + this.fileSerializer = createFileSerializer( + fs, + compiler.options.output.hashFunction + ); + this.fileSystemInfo = new FileSystemInfo(fs, { + managedPaths: snapshot.managedPaths, + immutablePaths: snapshot.immutablePaths, + logger: logger.getChildLogger("webpack.FileSystemInfo"), + hashFunction: compiler.options.output.hashFunction + }); + this.compiler = compiler; + this.context = context; + this.cacheLocation = cacheLocation; + this.version = version; + this.logger = logger; + this.maxAge = maxAge; + this.profile = profile; + this.allowCollectingMemory = allowCollectingMemory; + this.compression = compression; + this._extension = + compression === "brotli" + ? ".pack.br" + : compression === "gzip" + ? ".pack.gz" + : ".pack"; + this.snapshot = snapshot; + /** @type {Set} */ + this.buildDependencies = new Set(); + /** @type {LazySet} */ + this.newBuildDependencies = new LazySet(); + /** @type {Snapshot} */ + this.resolveBuildDependenciesSnapshot = undefined; + /** @type {Map} */ + this.resolveResults = undefined; + /** @type {Snapshot} */ + this.buildSnapshot = undefined; + /** @type {Promise} */ + this.packPromise = this._openPack(); + this.storePromise = Promise.resolve(); } - get category() { - return "esm"; + _getPack() { + if (this.packPromise === undefined) { + this.packPromise = this.storePromise.then(() => this._openPack()); + } + return this.packPromise; } -} -makeSerializable( - ImportEagerDependency, - "webpack/lib/dependencies/ImportEagerDependency" -); - -ImportEagerDependency.Template = class ImportEagerDependencyTemplate extends ( - ImportDependency.Template -) { /** - * @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} + * @returns {Promise} the pack */ - apply( - dependency, - source, - { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {ImportEagerDependency} */ (dependency); - const content = runtimeTemplate.moduleNamespacePromise({ - chunkGraph, - module: moduleGraph.getModule(dep), - request: dep.request, - strict: module.buildMeta.strictHarmonyModule, - message: "import() eager", - runtimeRequirements + _openPack() { + const { logger, profile, cacheLocation, version } = this; + /** @type {Snapshot} */ + let buildSnapshot; + /** @type {Set} */ + let buildDependencies; + /** @type {Set} */ + let newBuildDependencies; + /** @type {Snapshot} */ + let resolveBuildDependenciesSnapshot; + /** @type {Map} */ + let resolveResults; + logger.time("restore cache container"); + return this.fileSerializer + .deserialize(null, { + filename: `${cacheLocation}/index${this._extension}`, + extension: `${this._extension}`, + logger, + profile, + retainedBuffer: this.allowCollectingMemory + ? allowCollectingMemory + : undefined + }) + .catch(err => { + if (err.code !== "ENOENT") { + logger.warn( + `Restoring pack failed from ${cacheLocation}${this._extension}: ${err}` + ); + logger.debug(err.stack); + } else { + logger.debug( + `No pack exists at ${cacheLocation}${this._extension}: ${err}` + ); + } + return undefined; + }) + .then(packContainer => { + logger.timeEnd("restore cache container"); + if (!packContainer) return undefined; + if (!(packContainer instanceof PackContainer)) { + logger.warn( + `Restored pack from ${cacheLocation}${this._extension}, but contained content is unexpected.`, + packContainer + ); + return undefined; + } + if (packContainer.version !== version) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but version doesn't match.` + ); + return undefined; + } + logger.time("check build dependencies"); + return Promise.all([ + new Promise((resolve, reject) => { + this.fileSystemInfo.checkSnapshotValid( + packContainer.buildSnapshot, + (err, valid) => { + if (err) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of build dependencies errored: ${err}.` + ); + logger.debug(err.stack); + return resolve(false); + } + if (!valid) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but build dependencies have changed.` + ); + return resolve(false); + } + buildSnapshot = packContainer.buildSnapshot; + return resolve(true); + } + ); + }), + new Promise((resolve, reject) => { + this.fileSystemInfo.checkSnapshotValid( + packContainer.resolveBuildDependenciesSnapshot, + (err, valid) => { + if (err) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of resolving of build dependencies errored: ${err}.` + ); + logger.debug(err.stack); + return resolve(false); + } + if (valid) { + resolveBuildDependenciesSnapshot = + packContainer.resolveBuildDependenciesSnapshot; + buildDependencies = packContainer.buildDependencies; + resolveResults = packContainer.resolveResults; + return resolve(true); + } + logger.log( + "resolving of build dependencies is invalid, will re-resolve build dependencies" + ); + this.fileSystemInfo.checkResolveResultsValid( + packContainer.resolveResults, + (err, valid) => { + if (err) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but resolving of build dependencies errored: ${err}.` + ); + logger.debug(err.stack); + return resolve(false); + } + if (valid) { + newBuildDependencies = packContainer.buildDependencies; + resolveResults = packContainer.resolveResults; + return resolve(true); + } + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but build dependencies resolve to different locations.` + ); + return resolve(false); + } + ); + } + ); + }) + ]) + .catch(err => { + logger.timeEnd("check build dependencies"); + throw err; + }) + .then(([buildSnapshotValid, resolveValid]) => { + logger.timeEnd("check build dependencies"); + if (buildSnapshotValid && resolveValid) { + logger.time("restore cache content metadata"); + const d = packContainer.data(); + logger.timeEnd("restore cache content metadata"); + return d; + } + return undefined; + }); + }) + .then(pack => { + if (pack) { + pack.maxAge = this.maxAge; + this.buildSnapshot = buildSnapshot; + if (buildDependencies) this.buildDependencies = buildDependencies; + if (newBuildDependencies) + this.newBuildDependencies.addAll(newBuildDependencies); + this.resolveResults = resolveResults; + this.resolveBuildDependenciesSnapshot = + resolveBuildDependenciesSnapshot; + return pack; + } + return new Pack(logger, this.maxAge); + }) + .catch(err => { + this.logger.warn( + `Restoring pack from ${cacheLocation}${this._extension} failed: ${err}` + ); + this.logger.debug(err.stack); + return new Pack(logger, this.maxAge); + }); + } + + /** + * @param {string} identifier unique name for the resource + * @param {Etag | null} etag etag of the resource + * @param {any} data cached content + * @returns {Promise} promise + */ + store(identifier, etag, data) { + return this._getPack().then(pack => { + pack.set(identifier, etag === null ? null : etag.toString(), data); }); + } - source.replace(dep.range[0], dep.range[1] - 1, content); + /** + * @param {string} identifier unique name for the resource + * @param {Etag | null} etag etag of the resource + * @returns {Promise} promise to the cached content + */ + restore(identifier, etag) { + return this._getPack() + .then(pack => + pack.get(identifier, etag === null ? null : etag.toString()) + ) + .catch(err => { + if (err && err.code !== "ENOENT") { + this.logger.warn( + `Restoring failed for ${identifier} from pack: ${err}` + ); + this.logger.debug(err.stack); + } + }); } -}; -module.exports = ImportEagerDependency; + storeBuildDependencies(dependencies) { + this.newBuildDependencies.addAll(dependencies); + } + + afterAllStored() { + const packPromise = this.packPromise; + if (packPromise === undefined) return Promise.resolve(); + const reportProgress = ProgressPlugin.getReporter(this.compiler); + return (this.storePromise = packPromise + .then(pack => { + pack.stopCapturingRequests(); + if (!pack.invalid) return; + this.packPromise = undefined; + this.logger.log(`Storing pack...`); + let promise; + const newBuildDependencies = new Set(); + for (const dep of this.newBuildDependencies) { + if (!this.buildDependencies.has(dep)) { + newBuildDependencies.add(dep); + } + } + if (newBuildDependencies.size > 0 || !this.buildSnapshot) { + if (reportProgress) reportProgress(0.5, "resolve build dependencies"); + this.logger.debug( + `Capturing build dependencies... (${Array.from( + newBuildDependencies + ).join(", ")})` + ); + promise = new Promise((resolve, reject) => { + this.logger.time("resolve build dependencies"); + this.fileSystemInfo.resolveBuildDependencies( + this.context, + newBuildDependencies, + (err, result) => { + this.logger.timeEnd("resolve build dependencies"); + if (err) return reject(err); + + this.logger.time("snapshot build dependencies"); + const { + files, + directories, + missing, + resolveResults, + resolveDependencies + } = result; + if (this.resolveResults) { + for (const [key, value] of resolveResults) { + this.resolveResults.set(key, value); + } + } else { + this.resolveResults = resolveResults; + } + if (reportProgress) { + reportProgress( + 0.6, + "snapshot build dependencies", + "resolving" + ); + } + this.fileSystemInfo.createSnapshot( + undefined, + resolveDependencies.files, + resolveDependencies.directories, + resolveDependencies.missing, + this.snapshot.resolveBuildDependencies, + (err, snapshot) => { + if (err) { + this.logger.timeEnd("snapshot build dependencies"); + return reject(err); + } + if (!snapshot) { + this.logger.timeEnd("snapshot build dependencies"); + return reject( + new Error("Unable to snapshot resolve dependencies") + ); + } + if (this.resolveBuildDependenciesSnapshot) { + this.resolveBuildDependenciesSnapshot = + this.fileSystemInfo.mergeSnapshots( + this.resolveBuildDependenciesSnapshot, + snapshot + ); + } else { + this.resolveBuildDependenciesSnapshot = snapshot; + } + if (reportProgress) { + reportProgress( + 0.7, + "snapshot build dependencies", + "modules" + ); + } + this.fileSystemInfo.createSnapshot( + undefined, + files, + directories, + missing, + this.snapshot.buildDependencies, + (err, snapshot) => { + this.logger.timeEnd("snapshot build dependencies"); + if (err) return reject(err); + if (!snapshot) { + return reject( + new Error("Unable to snapshot build dependencies") + ); + } + this.logger.debug("Captured build dependencies"); + + if (this.buildSnapshot) { + this.buildSnapshot = + this.fileSystemInfo.mergeSnapshots( + this.buildSnapshot, + snapshot + ); + } else { + this.buildSnapshot = snapshot; + } + + resolve(); + } + ); + } + ); + } + ); + }); + } else { + promise = Promise.resolve(); + } + return promise.then(() => { + if (reportProgress) reportProgress(0.8, "serialize pack"); + this.logger.time(`store pack`); + const updatedBuildDependencies = new Set(this.buildDependencies); + for (const dep of newBuildDependencies) { + updatedBuildDependencies.add(dep); + } + const content = new PackContainer( + pack, + this.version, + this.buildSnapshot, + updatedBuildDependencies, + this.resolveResults, + this.resolveBuildDependenciesSnapshot + ); + return this.fileSerializer + .serialize(content, { + filename: `${this.cacheLocation}/index${this._extension}`, + extension: `${this._extension}`, + logger: this.logger, + profile: this.profile + }) + .then(() => { + for (const dep of newBuildDependencies) { + this.buildDependencies.add(dep); + } + this.newBuildDependencies.clear(); + this.logger.timeEnd(`store pack`); + const stats = pack.getContentStats(); + this.logger.log( + "Stored pack (%d items, %d files, %d MiB)", + pack.itemInfo.size, + stats.count, + Math.round(stats.size / 1024 / 1024) + ); + }) + .catch(err => { + this.logger.timeEnd(`store pack`); + this.logger.warn(`Caching failed for pack: ${err}`); + this.logger.debug(err.stack); + }); + }); + }) + .catch(err => { + this.logger.warn(`Caching failed for pack: ${err}`); + this.logger.debug(err.stack); + })); + } + + clear() { + this.fileSystemInfo.clear(); + this.buildDependencies.clear(); + this.newBuildDependencies.clear(); + this.resolveBuildDependenciesSnapshot = undefined; + this.resolveResults = undefined; + this.buildSnapshot = undefined; + this.packPromise = undefined; + } +} + +module.exports = PackFileCacheStrategy; /***/ }), -/***/ 51274: +/***/ 97347: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ +const LazySet = __webpack_require__(38938); const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyTemplateAsId = __webpack_require__(80825); -class ImportMetaHotAcceptDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; - this.weak = true; +/** @typedef {import("enhanced-resolve/lib/Resolver")} Resolver */ +/** @typedef {import("../CacheFacade").ItemCacheFacade} ItemCacheFacade */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../FileSystemInfo")} FileSystemInfo */ +/** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */ + +class CacheEntry { + constructor(result, snapshot) { + this.result = result; + this.snapshot = snapshot; } - get type() { - return "import.meta.webpackHot.accept"; + serialize({ write }) { + write(this.result); + write(this.snapshot); } - get category() { - return "esm"; + deserialize({ read }) { + this.result = read(); + this.snapshot = read(); } } -makeSerializable( - ImportMetaHotAcceptDependency, - "webpack/lib/dependencies/ImportMetaHotAcceptDependency" -); +makeSerializable(CacheEntry, "webpack/lib/cache/ResolverCachePlugin"); -ImportMetaHotAcceptDependency.Template = ModuleDependencyTemplateAsId; +/** + * @template T + * @param {Set | LazySet} set set to add items to + * @param {Set | LazySet} otherSet set to add items from + * @returns {void} + */ +const addAllToSet = (set, otherSet) => { + if (set instanceof LazySet) { + set.addAll(otherSet); + } else { + for (const item of otherSet) { + set.add(item); + } + } +}; -module.exports = ImportMetaHotAcceptDependency; +/** + * @param {Object} object an object + * @param {boolean} excludeContext if true, context is not included in string + * @returns {string} stringified version + */ +const objectToString = (object, excludeContext) => { + let str = ""; + for (const key in object) { + if (excludeContext && key === "context") continue; + const value = object[key]; + if (typeof value === "object" && value !== null) { + str += `|${key}=[${objectToString(value, false)}|]`; + } else { + str += `|${key}=|${value}`; + } + } + return str; +}; + +class ResolverCachePlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const cache = compiler.getCache("ResolverCachePlugin"); + /** @type {FileSystemInfo} */ + let fileSystemInfo; + let snapshotOptions; + let realResolves = 0; + let cachedResolves = 0; + let cacheInvalidResolves = 0; + let concurrentResolves = 0; + compiler.hooks.thisCompilation.tap("ResolverCachePlugin", compilation => { + snapshotOptions = compilation.options.snapshot.resolve; + fileSystemInfo = compilation.fileSystemInfo; + compilation.hooks.finishModules.tap("ResolverCachePlugin", () => { + if (realResolves + cachedResolves > 0) { + const logger = compilation.getLogger("webpack.ResolverCachePlugin"); + logger.log( + `${Math.round( + (100 * realResolves) / (realResolves + cachedResolves) + )}% really resolved (${realResolves} real resolves with ${cacheInvalidResolves} cached but invalid, ${cachedResolves} cached valid, ${concurrentResolves} concurrent)` + ); + realResolves = 0; + cachedResolves = 0; + cacheInvalidResolves = 0; + concurrentResolves = 0; + } + }); + }); + /** + * @param {ItemCacheFacade} itemCache cache + * @param {Resolver} resolver the resolver + * @param {Object} resolveContext context for resolving meta info + * @param {Object} request the request info object + * @param {function((Error | null)=, Object=): void} callback callback function + * @returns {void} + */ + const doRealResolve = ( + itemCache, + resolver, + resolveContext, + request, + callback + ) => { + realResolves++; + const newRequest = { + _ResolverCachePluginCacheMiss: true, + ...request + }; + const newResolveContext = { + ...resolveContext, + stack: new Set(), + missingDependencies: new LazySet(), + fileDependencies: new LazySet(), + contextDependencies: new LazySet() + }; + const propagate = key => { + if (resolveContext[key]) { + addAllToSet(resolveContext[key], newResolveContext[key]); + } + }; + const resolveTime = Date.now(); + resolver.doResolve( + resolver.hooks.resolve, + newRequest, + "Cache miss", + newResolveContext, + (err, result) => { + propagate("fileDependencies"); + propagate("contextDependencies"); + propagate("missingDependencies"); + if (err) return callback(err); + const fileDependencies = newResolveContext.fileDependencies; + const contextDependencies = newResolveContext.contextDependencies; + const missingDependencies = newResolveContext.missingDependencies; + fileSystemInfo.createSnapshot( + resolveTime, + fileDependencies, + contextDependencies, + missingDependencies, + snapshotOptions, + (err, snapshot) => { + if (err) return callback(err); + if (!snapshot) { + if (result) return callback(null, result); + return callback(); + } + itemCache.store(new CacheEntry(result, snapshot), storeErr => { + if (storeErr) return callback(storeErr); + if (result) return callback(null, result); + callback(); + }); + } + ); + } + ); + }; + compiler.resolverFactory.hooks.resolver.intercept({ + factory(type, hook) { + /** @type {Map} */ + const activeRequests = new Map(); + hook.tap( + "ResolverCachePlugin", + /** + * @param {Resolver} resolver the resolver + * @param {Object} options resolve options + * @param {Object} userOptions resolve options passed by the user + * @returns {void} + */ + (resolver, options, userOptions) => { + if (options.cache !== true) return; + const optionsIdent = objectToString(userOptions, false); + const cacheWithContext = + options.cacheWithContext !== undefined + ? options.cacheWithContext + : false; + resolver.hooks.resolve.tapAsync( + { + name: "ResolverCachePlugin", + stage: -100 + }, + (request, resolveContext, callback) => { + if (request._ResolverCachePluginCacheMiss || !fileSystemInfo) { + return callback(); + } + const identifier = `${type}${optionsIdent}${objectToString( + request, + !cacheWithContext + )}`; + const activeRequest = activeRequests.get(identifier); + if (activeRequest) { + activeRequest.push(callback); + return; + } + const itemCache = cache.getItemCache(identifier, null); + let callbacks; + const done = (err, result) => { + if (callbacks === undefined) { + callback(err, result); + callbacks = false; + } else { + for (const callback of callbacks) { + callback(err, result); + } + activeRequests.delete(identifier); + callbacks = false; + } + }; + /** + * @param {Error=} err error if any + * @param {CacheEntry=} cacheEntry cache entry + * @returns {void} + */ + const processCacheResult = (err, cacheEntry) => { + if (err) return done(err); + + if (cacheEntry) { + const { snapshot, result } = cacheEntry; + fileSystemInfo.checkSnapshotValid( + snapshot, + (err, valid) => { + if (err || !valid) { + cacheInvalidResolves++; + return doRealResolve( + itemCache, + resolver, + resolveContext, + request, + done + ); + } + cachedResolves++; + if (resolveContext.missingDependencies) { + addAllToSet( + resolveContext.missingDependencies, + snapshot.getMissingIterable() + ); + } + if (resolveContext.fileDependencies) { + addAllToSet( + resolveContext.fileDependencies, + snapshot.getFileIterable() + ); + } + if (resolveContext.contextDependencies) { + addAllToSet( + resolveContext.contextDependencies, + snapshot.getContextIterable() + ); + } + done(null, result); + } + ); + } else { + doRealResolve( + itemCache, + resolver, + resolveContext, + request, + done + ); + } + }; + itemCache.get(processCacheResult); + if (callbacks === undefined) { + callbacks = [callback]; + activeRequests.set(identifier, callbacks); + } + } + ); + } + ); + return hook; + } + }); + } +} + +module.exports = ResolverCachePlugin; /***/ }), -/***/ 53141: +/***/ 94075: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyTemplateAsId = __webpack_require__(80825); +const createHash = __webpack_require__(49835); -class ImportMetaHotDeclineDependency extends ModuleDependency { - constructor(request, range) { - super(request); +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {typeof import("../util/Hash")} HashConstructor */ - this.range = range; - this.weak = true; - } +/** + * @typedef {Object} HashableObject + * @property {function(Hash): void} updateHash + */ - get type() { - return "import.meta.webpackHot.decline"; +class LazyHashedEtag { + /** + * @param {HashableObject} obj object with updateHash method + * @param {string | HashConstructor} hashFunction the hash function to use + */ + constructor(obj, hashFunction = "md4") { + this._obj = obj; + this._hash = undefined; + this._hashFunction = hashFunction; } - get category() { - return "esm"; + /** + * @returns {string} hash of object + */ + toString() { + if (this._hash === undefined) { + const hash = createHash(this._hashFunction); + this._obj.updateHash(hash); + this._hash = /** @type {string} */ (hash.digest("base64")); + } + return this._hash; } } -makeSerializable( - ImportMetaHotDeclineDependency, - "webpack/lib/dependencies/ImportMetaHotDeclineDependency" -); +/** @type {Map>} */ +const mapStrings = new Map(); -ImportMetaHotDeclineDependency.Template = ModuleDependencyTemplateAsId; +/** @type {WeakMap>} */ +const mapObjects = new WeakMap(); -module.exports = ImportMetaHotDeclineDependency; +/** + * @param {HashableObject} obj object with updateHash method + * @param {string | HashConstructor} hashFunction the hash function to use + * @returns {LazyHashedEtag} etag + */ +const getter = (obj, hashFunction = "md4") => { + let innerMap; + if (typeof hashFunction === "string") { + innerMap = mapStrings.get(hashFunction); + if (innerMap === undefined) { + const newHash = new LazyHashedEtag(obj, hashFunction); + innerMap = new WeakMap(); + innerMap.set(obj, newHash); + mapStrings.set(hashFunction, innerMap); + return newHash; + } + } else { + innerMap = mapObjects.get(hashFunction); + if (innerMap === undefined) { + const newHash = new LazyHashedEtag(obj, hashFunction); + innerMap = new WeakMap(); + innerMap.set(obj, newHash); + mapObjects.set(hashFunction, innerMap); + return newHash; + } + } + const hash = innerMap.get(obj); + if (hash !== undefined) return hash; + const newHash = new LazyHashedEtag(obj, hashFunction); + innerMap.set(obj, newHash); + return newHash; +}; + +module.exports = getter; /***/ }), -/***/ 17228: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 54980: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const { pathToFileURL } = __webpack_require__(57310); -const ModuleDependencyWarning = __webpack_require__(29656); -const Template = __webpack_require__(1626); -const BasicEvaluatedExpression = __webpack_require__(950); -const { - evaluateToIdentifier, - toConstantDependency, - evaluateToString, - evaluateToNumber -} = __webpack_require__(93998); -const memoize = __webpack_require__(78676); -const propertyAccess = __webpack_require__(54190); -const ConstDependency = __webpack_require__(76911); - -/** @typedef {import("estree").MemberExpression} MemberExpression */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../javascript/JavascriptParser")} Parser */ - -const getCriticalDependencyWarning = memoize(() => - __webpack_require__(15427) -); +/** @typedef {import("../Cache").Etag} Etag */ -class ImportMetaPlugin { +class MergedEtag { /** - * @param {Compiler} compiler compiler + * @param {Etag} a first + * @param {Etag} b second */ - apply(compiler) { - compiler.hooks.compilation.tap( - "ImportMetaPlugin", - (compilation, { normalModuleFactory }) => { - /** - * @param {NormalModule} module module - * @returns {string} file url - */ - const getUrl = module => { - return pathToFileURL(module.resource).toString(); - }; - /** - * @param {Parser} parser parser - * @param {Object} parserOptions parserOptions - * @returns {void} - */ - const parserHandler = (parser, parserOptions) => { - /// import.meta direct /// - parser.hooks.typeof - .for("import.meta") - .tap( - "ImportMetaPlugin", - toConstantDependency(parser, JSON.stringify("object")) - ); - parser.hooks.expression - .for("import.meta") - .tap("ImportMetaPlugin", metaProperty => { - const CriticalDependencyWarning = getCriticalDependencyWarning(); - parser.state.module.addWarning( - new ModuleDependencyWarning( - parser.state.module, - new CriticalDependencyWarning( - "Accessing import.meta directly is unsupported (only property access is supported)" - ), - metaProperty.loc - ) - ); - const dep = new ConstDependency( - `${parser.isAsiPosition(metaProperty.range[0]) ? ";" : ""}({})`, - metaProperty.range - ); - dep.loc = metaProperty.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); - parser.hooks.evaluateTypeof - .for("import.meta") - .tap("ImportMetaPlugin", evaluateToString("object")); - parser.hooks.evaluateIdentifier.for("import.meta").tap( - "ImportMetaPlugin", - evaluateToIdentifier("import.meta", "import.meta", () => [], true) - ); - - /// import.meta.url /// - parser.hooks.typeof - .for("import.meta.url") - .tap( - "ImportMetaPlugin", - toConstantDependency(parser, JSON.stringify("string")) - ); - parser.hooks.expression - .for("import.meta.url") - .tap("ImportMetaPlugin", expr => { - const dep = new ConstDependency( - JSON.stringify(getUrl(parser.state.module)), - expr.range - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); - parser.hooks.evaluateTypeof - .for("import.meta.url") - .tap("ImportMetaPlugin", evaluateToString("string")); - parser.hooks.evaluateIdentifier - .for("import.meta.url") - .tap("ImportMetaPlugin", expr => { - return new BasicEvaluatedExpression() - .setString(getUrl(parser.state.module)) - .setRange(expr.range); - }); + constructor(a, b) { + this.a = a; + this.b = b; + } - /// import.meta.webpack /// - const webpackVersion = parseInt( - (__webpack_require__(32702)/* .version */ .i8), - 10 - ); - parser.hooks.typeof - .for("import.meta.webpack") - .tap( - "ImportMetaPlugin", - toConstantDependency(parser, JSON.stringify("number")) - ); - parser.hooks.expression - .for("import.meta.webpack") - .tap( - "ImportMetaPlugin", - toConstantDependency(parser, JSON.stringify(webpackVersion)) - ); - parser.hooks.evaluateTypeof - .for("import.meta.webpack") - .tap("ImportMetaPlugin", evaluateToString("number")); - parser.hooks.evaluateIdentifier - .for("import.meta.webpack") - .tap("ImportMetaPlugin", evaluateToNumber(webpackVersion)); + toString() { + return `${this.a.toString()}|${this.b.toString()}`; + } +} - /// Unknown properties /// - parser.hooks.unhandledExpressionMemberChain - .for("import.meta") - .tap("ImportMetaPlugin", (expr, members) => { - const dep = new ConstDependency( - `${Template.toNormalComment( - "unsupported import.meta." + members.join(".") - )} undefined${propertyAccess(members, 1)}`, - expr.range - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); - parser.hooks.evaluate - .for("MemberExpression") - .tap("ImportMetaPlugin", expression => { - const expr = /** @type {MemberExpression} */ (expression); - if ( - expr.object.type === "MetaProperty" && - expr.object.meta.name === "import" && - expr.object.property.name === "meta" && - expr.property.type === - (expr.computed ? "Literal" : "Identifier") - ) { - return new BasicEvaluatedExpression() - .setUndefined() - .setRange(expr.range); - } - }); - }; +const dualObjectMap = new WeakMap(); +const objectStringMap = new WeakMap(); - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("ImportMetaPlugin", parserHandler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("ImportMetaPlugin", parserHandler); +/** + * @param {Etag} a first + * @param {Etag} b second + * @returns {Etag} result + */ +const mergeEtags = (a, b) => { + if (typeof a === "string") { + if (typeof b === "string") { + return `${a}|${b}`; + } else { + const temp = b; + b = a; + a = temp; + } + } else { + if (typeof b !== "string") { + // both a and b are objects + let map = dualObjectMap.get(a); + if (map === undefined) { + dualObjectMap.set(a, (map = new WeakMap())); } - ); + const mergedEtag = map.get(b); + if (mergedEtag === undefined) { + const newMergedEtag = new MergedEtag(a, b); + map.set(b, newMergedEtag); + return newMergedEtag; + } else { + return mergedEtag; + } + } } -} + // a is object, b is string + let map = objectStringMap.get(a); + if (map === undefined) { + objectStringMap.set(a, (map = new Map())); + } + const mergedEtag = map.get(b); + if (mergedEtag === undefined) { + const newMergedEtag = new MergedEtag(a, b); + map.set(b, newMergedEtag); + return newMergedEtag; + } else { + return mergedEtag; + } +}; -module.exports = ImportMetaPlugin; +module.exports = mergeEtags; /***/ }), -/***/ 88130: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 13462: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -80416,1014 +75779,1002 @@ module.exports = ImportMetaPlugin; -const AsyncDependenciesBlock = __webpack_require__(47736); -const CommentCompilationWarning = __webpack_require__(98427); -const UnsupportedFeatureWarning = __webpack_require__(42495); -const ContextDependencyHelpers = __webpack_require__(99630); -const ImportContextDependency = __webpack_require__(1902); -const ImportDependency = __webpack_require__(89376); -const ImportEagerDependency = __webpack_require__(50718); -const ImportWeakDependency = __webpack_require__(82483); - -/** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ -/** @typedef {import("../ContextModule").ContextMode} ContextMode */ - -class ImportParserPlugin { - constructor(options) { - this.options = options; - } - - apply(parser) { - parser.hooks.importCall.tap("ImportParserPlugin", expr => { - const param = parser.evaluateExpression(expr.source); - - let chunkName = null; - /** @type {ContextMode} */ - let mode = "lazy"; - let include = null; - let exclude = null; - /** @type {string[][] | null} */ - let exports = null; - /** @type {RawChunkGroupOptions} */ - const groupOptions = {}; - - const { options: importOptions, errors: commentErrors } = - parser.parseCommentOptions(expr.range); +const path = __webpack_require__(71017); +const webpackSchema = __webpack_require__(73342); - if (commentErrors) { - for (const e of commentErrors) { - const { comment } = e; - parser.state.module.addWarning( - new CommentCompilationWarning( - `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, - comment.loc - ) - ); - } - } +// TODO add originPath to PathItem for better errors +/** + * @typedef {Object} PathItem + * @property {any} schema the part of the schema + * @property {string} path the path in the config + */ - if (importOptions) { - if (importOptions.webpackIgnore !== undefined) { - if (typeof importOptions.webpackIgnore !== "boolean") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, - expr.loc - ) - ); - } else { - // Do not instrument `import()` if `webpackIgnore` is `true` - if (importOptions.webpackIgnore) { - return false; - } - } - } - if (importOptions.webpackChunkName !== undefined) { - if (typeof importOptions.webpackChunkName !== "string") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, - expr.loc - ) - ); - } else { - chunkName = importOptions.webpackChunkName; - } - } - if (importOptions.webpackMode !== undefined) { - if (typeof importOptions.webpackMode !== "string") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackMode\` expected a string, but received: ${importOptions.webpackMode}.`, - expr.loc - ) - ); - } else { - mode = importOptions.webpackMode; - } - } - if (importOptions.webpackPrefetch !== undefined) { - if (importOptions.webpackPrefetch === true) { - groupOptions.prefetchOrder = 0; - } else if (typeof importOptions.webpackPrefetch === "number") { - groupOptions.prefetchOrder = importOptions.webpackPrefetch; - } else { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackPrefetch\` expected true or a number, but received: ${importOptions.webpackPrefetch}.`, - expr.loc - ) - ); - } - } - if (importOptions.webpackPreload !== undefined) { - if (importOptions.webpackPreload === true) { - groupOptions.preloadOrder = 0; - } else if (typeof importOptions.webpackPreload === "number") { - groupOptions.preloadOrder = importOptions.webpackPreload; - } else { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackPreload\` expected true or a number, but received: ${importOptions.webpackPreload}.`, - expr.loc - ) - ); - } - } - if (importOptions.webpackInclude !== undefined) { - if ( - !importOptions.webpackInclude || - importOptions.webpackInclude.constructor.name !== "RegExp" - ) { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackInclude\` expected a regular expression, but received: ${importOptions.webpackInclude}.`, - expr.loc - ) - ); - } else { - include = new RegExp(importOptions.webpackInclude); - } - } - if (importOptions.webpackExclude !== undefined) { - if ( - !importOptions.webpackExclude || - importOptions.webpackExclude.constructor.name !== "RegExp" - ) { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackExclude\` expected a regular expression, but received: ${importOptions.webpackExclude}.`, - expr.loc - ) - ); - } else { - exclude = new RegExp(importOptions.webpackExclude); - } - } - if (importOptions.webpackExports !== undefined) { - if ( - !( - typeof importOptions.webpackExports === "string" || - (Array.isArray(importOptions.webpackExports) && - importOptions.webpackExports.every( - item => typeof item === "string" - )) - ) - ) { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackExports\` expected a string or an array of strings, but received: ${importOptions.webpackExports}.`, - expr.loc - ) - ); - } else { - if (typeof importOptions.webpackExports === "string") { - exports = [[importOptions.webpackExports]]; - } else { - exports = Array.from(importOptions.webpackExports, e => [e]); - } - } - } - } +/** @typedef {"unknown-argument" | "unexpected-non-array-in-path" | "unexpected-non-object-in-path" | "multiple-values-unexpected" | "invalid-value"} ProblemType */ - if (param.isString()) { - if (mode !== "lazy" && mode !== "eager" && mode !== "weak") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackMode\` expected 'lazy', 'eager' or 'weak', but received: ${mode}.`, - expr.loc - ) - ); - } +/** + * @typedef {Object} Problem + * @property {ProblemType} type + * @property {string} path + * @property {string} argument + * @property {any=} value + * @property {number=} index + * @property {string=} expected + */ - if (mode === "eager") { - const dep = new ImportEagerDependency( - param.string, - expr.range, - exports - ); - parser.state.current.addDependency(dep); - } else if (mode === "weak") { - const dep = new ImportWeakDependency( - param.string, - expr.range, - exports - ); - parser.state.current.addDependency(dep); - } else { - const depBlock = new AsyncDependenciesBlock( - { - ...groupOptions, - name: chunkName - }, - expr.loc, - param.string - ); - const dep = new ImportDependency(param.string, expr.range, exports); - dep.loc = expr.loc; - depBlock.addDependency(dep); - parser.state.current.addBlock(depBlock); - } - return true; - } else { - if ( - mode !== "lazy" && - mode !== "lazy-once" && - mode !== "eager" && - mode !== "weak" - ) { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`, - expr.loc - ) - ); - mode = "lazy"; - } +/** + * @typedef {Object} LocalProblem + * @property {ProblemType} type + * @property {string} path + * @property {string=} expected + */ - if (mode === "weak") { - mode = "async-weak"; - } - const dep = ContextDependencyHelpers.create( - ImportContextDependency, - expr.range, - param, - expr, - this.options, - { - chunkName, - groupOptions, - include, - exclude, - mode, - namespaceObject: parser.state.module.buildMeta.strictHarmonyModule - ? "strict" - : true, - typePrefix: "import()", - category: "esm", - referencedExports: exports - }, - parser - ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - }); - } -} +/** + * @typedef {Object} ArgumentConfig + * @property {string} description + * @property {string} [negatedDescription] + * @property {string} path + * @property {boolean} multiple + * @property {"enum"|"string"|"path"|"number"|"boolean"|"RegExp"|"reset"} type + * @property {any[]=} values + */ -module.exports = ImportParserPlugin; +/** + * @typedef {Object} Argument + * @property {string} description + * @property {"string"|"number"|"boolean"} simpleType + * @property {boolean} multiple + * @property {ArgumentConfig[]} configs + */ +/** + * @param {any=} schema a json schema to create arguments for (by default webpack schema is used) + * @returns {Record} object of arguments + */ +const getArguments = (schema = webpackSchema) => { + /** @type {Record} */ + const flags = {}; -/***/ }), + const pathToArgumentName = input => { + return input + .replace(/\./g, "-") + .replace(/\[\]/g, "") + .replace( + /(\p{Uppercase_Letter}+|\p{Lowercase_Letter}|\d)(\p{Uppercase_Letter}+)/gu, + "$1-$2" + ) + .replace(/-?[^\p{Uppercase_Letter}\p{Lowercase_Letter}\d]+/gu, "-") + .toLowerCase(); + }; -/***/ 41293: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const getSchemaPart = path => { + const newPath = path.split("/"); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + let schemaPart = schema; + for (let i = 1; i < newPath.length; i++) { + const inner = schemaPart[newPath[i]]; + if (!inner) { + break; + } -const ImportContextDependency = __webpack_require__(1902); -const ImportDependency = __webpack_require__(89376); -const ImportEagerDependency = __webpack_require__(50718); -const ImportParserPlugin = __webpack_require__(88130); -const ImportWeakDependency = __webpack_require__(82483); + schemaPart = inner; + } -/** @typedef {import("../Compiler")} Compiler */ + return schemaPart; + }; -class ImportPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * + * @param {PathItem[]} path path in the schema + * @returns {string | undefined} description */ - apply(compiler) { - compiler.hooks.compilation.tap( - "ImportPlugin", - (compilation, { contextModuleFactory, normalModuleFactory }) => { - compilation.dependencyFactories.set( - ImportDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ImportDependency, - new ImportDependency.Template() - ); - - compilation.dependencyFactories.set( - ImportEagerDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ImportEagerDependency, - new ImportEagerDependency.Template() - ); - - compilation.dependencyFactories.set( - ImportWeakDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ImportWeakDependency, - new ImportWeakDependency.Template() - ); - - compilation.dependencyFactories.set( - ImportContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - ImportContextDependency, - new ImportContextDependency.Template() - ); - - const handler = (parser, parserOptions) => { - if (parserOptions.import !== undefined && !parserOptions.import) - return; - - new ImportParserPlugin(parserOptions).apply(parser); - }; - - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("ImportPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("ImportPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("ImportPlugin", handler); + const getDescription = path => { + for (const { schema } of path) { + if (schema.cli) { + if (schema.cli.helper) continue; + if (schema.cli.description) return schema.cli.description; } - ); - } -} -module.exports = ImportPlugin; - - -/***/ }), - -/***/ 82483: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const ImportDependency = __webpack_require__(89376); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ + if (schema.description) return schema.description; + } + }; -class ImportWeakDependency extends ImportDependency { /** - * @param {string} request the request - * @param {[number, number]} range expression range - * @param {string[][]=} referencedExports list of referenced exports + * + * @param {PathItem[]} path path in the schema + * @returns {string | undefined} negative description */ - constructor(request, range, referencedExports) { - super(request, range, referencedExports); - this.weak = true; - } - - get type() { - return "import() weak"; - } -} - -makeSerializable( - ImportWeakDependency, - "webpack/lib/dependencies/ImportWeakDependency" -); + const getNegatedDescription = path => { + for (const { schema } of path) { + if (schema.cli) { + if (schema.cli.helper) continue; + if (schema.cli.negatedDescription) return schema.cli.negatedDescription; + } + } + }; -ImportWeakDependency.Template = class ImportDependencyTemplate extends ( - ImportDependency.Template -) { /** - * @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} + * + * @param {PathItem[]} path path in the schema + * @returns {string | undefined} reset description */ - apply( - dependency, - source, - { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {ImportWeakDependency} */ (dependency); - const content = runtimeTemplate.moduleNamespacePromise({ - chunkGraph, - module: moduleGraph.getModule(dep), - request: dep.request, - strict: module.buildMeta.strictHarmonyModule, - message: "import() weak", - weak: true, - runtimeRequirements - }); - - source.replace(dep.range[0], dep.range[1] - 1, content); - } -}; - -module.exports = ImportWeakDependency; - - -/***/ }), - -/***/ 750: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ExportSpec} ExportSpec */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/Hash")} Hash */ - -const getExportsFromData = data => { - if (data && typeof data === "object") { - if (Array.isArray(data)) { - return data.map((item, idx) => { - return { - name: `${idx}`, - canMangle: true, - exports: getExportsFromData(item) - }; - }); - } else { - const exports = []; - for (const key of Object.keys(data)) { - exports.push({ - name: key, - canMangle: true, - exports: getExportsFromData(data[key]) - }); + const getResetDescription = path => { + for (const { schema } of path) { + if (schema.cli) { + if (schema.cli.helper) continue; + if (schema.cli.resetDescription) return schema.cli.resetDescription; } - return exports; } - } - return undefined; -}; + }; -class JsonExportsDependency extends NullDependency { /** - * @param {(string | ExportSpec)[]} exports json exports + * + * @param {any} schemaPart schema + * @returns {Pick} partial argument config */ - constructor(exports) { - super(); - this.exports = exports; - this._hashUpdate = undefined; - } - - get type() { - return "json exports"; - } + const schemaToArgumentConfig = schemaPart => { + if (schemaPart.enum) { + return { + type: "enum", + values: schemaPart.enum + }; + } + switch (schemaPart.type) { + case "number": + return { + type: "number" + }; + case "string": + return { + type: schemaPart.absolutePath ? "path" : "string" + }; + case "boolean": + return { + type: "boolean" + }; + } + if (schemaPart.instanceof === "RegExp") { + return { + type: "RegExp" + }; + } + return undefined; + }; /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names + * @param {PathItem[]} path path in the schema + * @returns {void} */ - getExports(moduleGraph) { - return { - exports: this.exports, - dependencies: undefined + const addResetFlag = path => { + const schemaPath = path[0].path; + const name = pathToArgumentName(`${schemaPath}.reset`); + const description = + getResetDescription(path) || + `Clear all items provided in '${schemaPath}' configuration. ${getDescription( + path + )}`; + flags[name] = { + configs: [ + { + type: "reset", + multiple: false, + description, + path: schemaPath + } + ], + description: undefined, + simpleType: undefined, + multiple: undefined }; - } + }; /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context - * @returns {void} + * @param {PathItem[]} path full path in schema + * @param {boolean} multiple inside of an array + * @returns {number} number of arguments added */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) { - this._hashUpdate = this.exports - ? JSON.stringify(this.exports) - : "undefined"; - } - hash.update(this._hashUpdate); - } - - serialize(context) { - const { write } = context; - write(this.exports); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.exports = read(); - super.deserialize(context); - } -} - -makeSerializable( - JsonExportsDependency, - "webpack/lib/dependencies/JsonExportsDependency" -); - -module.exports = JsonExportsDependency; -module.exports.getExportsFromData = getExportsFromData; + const addFlag = (path, multiple) => { + const argConfigBase = schemaToArgumentConfig(path[0].schema); + if (!argConfigBase) return 0; + const negatedDescription = getNegatedDescription(path); + const name = pathToArgumentName(path[0].path); + /** @type {ArgumentConfig} */ + const argConfig = { + ...argConfigBase, + multiple, + description: getDescription(path), + path: path[0].path + }; -/***/ }), + if (negatedDescription) { + argConfig.negatedDescription = negatedDescription; + } -/***/ 71693: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (!flags[name]) { + flags[name] = { + configs: [], + description: undefined, + simpleType: undefined, + multiple: undefined + }; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if ( + flags[name].configs.some( + item => JSON.stringify(item) === JSON.stringify(argConfig) + ) + ) { + return 0; + } + if ( + flags[name].configs.some( + item => item.type === argConfig.type && item.multiple !== multiple + ) + ) { + if (multiple) { + throw new Error( + `Conflicting schema for ${path[0].path} with ${argConfig.type} type (array type must be before single item type)` + ); + } + return 0; + } + flags[name].configs.push(argConfig); -const ModuleDependency = __webpack_require__(80321); + return 1; + }; -class LoaderDependency extends ModuleDependency { + // TODO support `not` and `if/then/else` + // TODO support `const`, but we don't use it on our schema /** - * @param {string} request request string + * + * @param {object} schemaPart the current schema + * @param {string} schemaPath the current path in the schema + * @param {{schema: object, path: string}[]} path all previous visited schemaParts + * @param {string | null} inArray if inside of an array, the path to the array + * @returns {number} added arguments */ - constructor(request) { - super(request); - } - - get type() { - return "loader"; - } + const traverse = (schemaPart, schemaPath = "", path = [], inArray = null) => { + while (schemaPart.$ref) { + schemaPart = getSchemaPart(schemaPart.$ref); + } - get category() { - return "loader"; - } -} + const repetitions = path.filter(({ schema }) => schema === schemaPart); + if ( + repetitions.length >= 2 || + repetitions.some(({ path }) => path === schemaPath) + ) { + return 0; + } -module.exports = LoaderDependency; + if (schemaPart.cli && schemaPart.cli.exclude) return 0; + const fullPath = [{ schema: schemaPart, path: schemaPath }, ...path]; -/***/ }), + let addedArguments = 0; -/***/ 223: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + addedArguments += addFlag(fullPath, !!inArray); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (schemaPart.type === "object") { + if (schemaPart.properties) { + for (const property of Object.keys(schemaPart.properties)) { + addedArguments += traverse( + schemaPart.properties[property], + schemaPath ? `${schemaPath}.${property}` : property, + fullPath, + inArray + ); + } + } + return addedArguments; + } + if (schemaPart.type === "array") { + if (inArray) { + return 0; + } + if (Array.isArray(schemaPart.items)) { + let i = 0; + for (const item of schemaPart.items) { + addedArguments += traverse( + item, + `${schemaPath}.${i}`, + fullPath, + schemaPath + ); + } -const ModuleDependency = __webpack_require__(80321); + return addedArguments; + } -class LoaderImportDependency extends ModuleDependency { - /** - * @param {string} request request string - */ - constructor(request) { - super(request); - this.weak = true; - } + addedArguments += traverse( + schemaPart.items, + `${schemaPath}[]`, + fullPath, + schemaPath + ); - get type() { - return "loader import"; - } + if (addedArguments > 0) { + addResetFlag(fullPath); + addedArguments++; + } - get category() { - return "loaderImport"; - } -} + return addedArguments; + } -module.exports = LoaderImportDependency; + const maybeOf = schemaPart.oneOf || schemaPart.anyOf || schemaPart.allOf; + if (maybeOf) { + const items = maybeOf; -/***/ }), + for (let i = 0; i < items.length; i++) { + addedArguments += traverse(items[i], schemaPath, fullPath, inArray); + } -/***/ 24721: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + return addedArguments; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return addedArguments; + }; + traverse(schema); + // Summarize flags + for (const name of Object.keys(flags)) { + const argument = flags[name]; + argument.description = argument.configs.reduce((desc, { description }) => { + if (!desc) return description; + if (!description) return desc; + if (desc.includes(description)) return desc; + return `${desc} ${description}`; + }, /** @type {string | undefined} */ (undefined)); + argument.simpleType = argument.configs.reduce((t, argConfig) => { + /** @type {"string" | "number" | "boolean"} */ + let type = "string"; + switch (argConfig.type) { + case "number": + type = "number"; + break; + case "reset": + case "boolean": + type = "boolean"; + break; + case "enum": + if (argConfig.values.every(v => typeof v === "boolean")) + type = "boolean"; + if (argConfig.values.every(v => typeof v === "number")) + type = "number"; + break; + } + if (t === undefined) return type; + return t === type ? t : "string"; + }, /** @type {"string" | "number" | "boolean" | undefined} */ (undefined)); + argument.multiple = argument.configs.some(c => c.multiple); + } -const NormalModule = __webpack_require__(39); -const LazySet = __webpack_require__(38938); -const LoaderDependency = __webpack_require__(71693); -const LoaderImportDependency = __webpack_require__(223); + return flags; +}; -/** @typedef {import("../Compilation").DepConstructor} DepConstructor */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +const cliAddedItems = new WeakMap(); /** - * @callback LoadModuleCallback - * @param {(Error | null)=} err error object - * @param {string | Buffer=} source source code - * @param {object=} map source map - * @param {Module=} module loaded module if successful + * @param {any} config configuration + * @param {string} schemaPath path in the config + * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined + * @returns {{ problem?: LocalProblem, object?: any, property?: string | number, value?: any }} problem or object with property and value */ +const getObjectAndProperty = (config, schemaPath, index = 0) => { + if (!schemaPath) return { value: config }; + const parts = schemaPath.split("."); + let property = parts.pop(); + let current = config; + let i = 0; + for (const part of parts) { + const isArray = part.endsWith("[]"); + const name = isArray ? part.slice(0, -2) : part; + let value = current[name]; + if (isArray) { + if (value === undefined) { + value = {}; + current[name] = [...Array.from({ length: index }), value]; + cliAddedItems.set(current[name], index + 1); + } else if (!Array.isArray(value)) { + return { + problem: { + type: "unexpected-non-array-in-path", + path: parts.slice(0, i).join(".") + } + }; + } else { + let addedItems = cliAddedItems.get(value) || 0; + while (addedItems <= index) { + value.push(undefined); + addedItems++; + } + cliAddedItems.set(value, addedItems); + const x = value.length - addedItems + index; + if (value[x] === undefined) { + value[x] = {}; + } else if (value[x] === null || typeof value[x] !== "object") { + return { + problem: { + type: "unexpected-non-object-in-path", + path: parts.slice(0, i).join(".") + } + }; + } + value = value[x]; + } + } else { + if (value === undefined) { + value = current[name] = {}; + } else if (value === null || typeof value !== "object") { + return { + problem: { + type: "unexpected-non-object-in-path", + path: parts.slice(0, i).join(".") + } + }; + } + } + current = value; + i++; + } + let value = current[property]; + if (property.endsWith("[]")) { + const name = property.slice(0, -2); + const value = current[name]; + if (value === undefined) { + current[name] = [...Array.from({ length: index }), undefined]; + cliAddedItems.set(current[name], index + 1); + return { object: current[name], property: index, value: undefined }; + } else if (!Array.isArray(value)) { + current[name] = [value, ...Array.from({ length: index }), undefined]; + cliAddedItems.set(current[name], index + 1); + return { object: current[name], property: index + 1, value: undefined }; + } else { + let addedItems = cliAddedItems.get(value) || 0; + while (addedItems <= index) { + value.push(undefined); + addedItems++; + } + cliAddedItems.set(value, addedItems); + const x = value.length - addedItems + index; + if (value[x] === undefined) { + value[x] = {}; + } else if (value[x] === null || typeof value[x] !== "object") { + return { + problem: { + type: "unexpected-non-object-in-path", + path: schemaPath + } + }; + } + return { + object: value, + property: x, + value: value[x] + }; + } + } + return { object: current, property, value }; +}; /** - * @callback ImportModuleCallback - * @param {(Error | null)=} err error object - * @param {any=} exports exports of the evaluated module + * @param {any} config configuration + * @param {string} schemaPath path in the config + * @param {any} value parsed value + * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined + * @returns {LocalProblem | null} problem or null for success */ +const setValue = (config, schemaPath, value, index) => { + const { problem, object, property } = getObjectAndProperty( + config, + schemaPath, + index + ); + if (problem) return problem; + object[property] = value; + return null; +}; /** - * @typedef {Object} ImportModuleOptions - * @property {string=} layer the target layer - * @property {string=} publicPath the target public path + * @param {ArgumentConfig} argConfig processing instructions + * @param {any} config configuration + * @param {any} value the value + * @param {number | undefined} index the index if multiple values provided + * @returns {LocalProblem | null} a problem if any */ +const processArgumentConfig = (argConfig, config, value, index) => { + if (index !== undefined && !argConfig.multiple) { + return { + type: "multiple-values-unexpected", + path: argConfig.path + }; + } + const parsed = parseValueForArgumentConfig(argConfig, value); + if (parsed === undefined) { + return { + type: "invalid-value", + path: argConfig.path, + expected: getExpectedValue(argConfig) + }; + } + const problem = setValue(config, argConfig.path, parsed, index); + if (problem) return problem; + return null; +}; -class LoaderPlugin { - /** - * @param {Object} options options - */ - constructor(options = {}) {} +/** + * @param {ArgumentConfig} argConfig processing instructions + * @returns {string | undefined} expected message + */ +const getExpectedValue = argConfig => { + switch (argConfig.type) { + default: + return argConfig.type; + case "boolean": + return "true | false"; + case "RegExp": + return "regular expression (example: /ab?c*/)"; + case "enum": + return argConfig.values.map(v => `${v}`).join(" | "); + case "reset": + return "true (will reset the previous value to an empty array)"; + } +}; - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "LoaderPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - LoaderDependency, - normalModuleFactory - ); - compilation.dependencyFactories.set( - LoaderImportDependency, - normalModuleFactory - ); +/** + * @param {ArgumentConfig} argConfig processing instructions + * @param {any} value the value + * @returns {any | undefined} parsed value + */ +const parseValueForArgumentConfig = (argConfig, value) => { + switch (argConfig.type) { + case "string": + if (typeof value === "string") { + return value; } - ); - - compiler.hooks.compilation.tap("LoaderPlugin", compilation => { - const moduleGraph = compilation.moduleGraph; - NormalModule.getCompilationHooks(compilation).loader.tap( - "LoaderPlugin", - loaderContext => { - /** - * @param {string} request the request string to load the module from - * @param {LoadModuleCallback} callback callback returning the loaded module or error - * @returns {void} - */ - loaderContext.loadModule = (request, callback) => { - const dep = new LoaderDependency(request); - dep.loc = { - name: request - }; - const factory = compilation.dependencyFactories.get( - /** @type {DepConstructor} */ (dep.constructor) - ); - if (factory === undefined) { - return callback( - new Error( - `No module factory available for dependency type: ${dep.constructor.name}` - ) - ); - } - compilation.buildQueue.increaseParallelism(); - compilation.handleModuleCreation( - { - factory, - dependencies: [dep], - originModule: loaderContext._module, - context: loaderContext.context, - recursive: false - }, - err => { - compilation.buildQueue.decreaseParallelism(); - if (err) { - return callback(err); - } - const referencedModule = moduleGraph.getModule(dep); - if (!referencedModule) { - return callback(new Error("Cannot load the module")); - } - if (referencedModule.getNumberOfErrors() > 0) { - return callback( - new Error("The loaded module contains errors") - ); - } - const moduleSource = referencedModule.originalSource(); - if (!moduleSource) { - return callback( - new Error( - "The module created for a LoaderDependency must have an original source" - ) - ); - } - let source, map; - if (moduleSource.sourceAndMap) { - const sourceAndMap = moduleSource.sourceAndMap(); - map = sourceAndMap.map; - source = sourceAndMap.source; - } else { - map = moduleSource.map(); - source = moduleSource.source(); - } - const fileDependencies = new LazySet(); - const contextDependencies = new LazySet(); - const missingDependencies = new LazySet(); - const buildDependencies = new LazySet(); - referencedModule.addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ); - - for (const d of fileDependencies) { - loaderContext.addDependency(d); - } - for (const d of contextDependencies) { - loaderContext.addContextDependency(d); - } - for (const d of missingDependencies) { - loaderContext.addMissingDependency(d); - } - for (const d of buildDependencies) { - loaderContext.addBuildDependency(d); - } - return callback(null, source, map, referencedModule); - } - ); - }; - - /** - * @param {string} request the request string to load the module from - * @param {ImportModuleOptions=} options options - * @param {ImportModuleCallback=} callback callback returning the exports - * @returns {void} - */ - const importModule = (request, options, callback) => { - const dep = new LoaderImportDependency(request); - dep.loc = { - name: request - }; - const factory = compilation.dependencyFactories.get( - /** @type {DepConstructor} */ (dep.constructor) - ); - if (factory === undefined) { - return callback( - new Error( - `No module factory available for dependency type: ${dep.constructor.name}` - ) - ); - } - compilation.buildQueue.increaseParallelism(); - compilation.handleModuleCreation( - { - factory, - dependencies: [dep], - originModule: loaderContext._module, - contextInfo: { - issuerLayer: options.layer - }, - context: loaderContext.context, - connectOrigin: false - }, - err => { - compilation.buildQueue.decreaseParallelism(); - if (err) { - return callback(err); - } - const referencedModule = moduleGraph.getModule(dep); - if (!referencedModule) { - return callback(new Error("Cannot load the module")); - } - compilation.executeModule( - referencedModule, - { - entryOptions: { - publicPath: options.publicPath - } - }, - (err, result) => { - if (err) return callback(err); - for (const d of result.fileDependencies) { - loaderContext.addDependency(d); - } - for (const d of result.contextDependencies) { - loaderContext.addContextDependency(d); - } - for (const d of result.missingDependencies) { - loaderContext.addMissingDependency(d); - } - for (const d of result.buildDependencies) { - loaderContext.addBuildDependency(d); - } - if (result.cacheable === false) - loaderContext.cacheable(false); - for (const [name, { source, info }] of result.assets) { - const { buildInfo } = loaderContext._module; - if (!buildInfo.assets) { - buildInfo.assets = Object.create(null); - buildInfo.assetsInfo = new Map(); - } - buildInfo.assets[name] = source; - buildInfo.assetsInfo.set(name, info); - } - callback(null, result.exports); - } - ); - } - ); - }; + break; + case "path": + if (typeof value === "string") { + return path.resolve(value); + } + break; + case "number": + if (typeof value === "number") return value; + if (typeof value === "string" && /^[+-]?\d*(\.\d*)[eE]\d+$/) { + const n = +value; + if (!isNaN(n)) return n; + } + break; + case "boolean": + if (typeof value === "boolean") return value; + if (value === "true") return true; + if (value === "false") return false; + break; + case "RegExp": + if (value instanceof RegExp) return value; + if (typeof value === "string") { + // cspell:word yugi + const match = /^\/(.*)\/([yugi]*)$/.exec(value); + if (match && !/[^\\]\//.test(match[1])) + return new RegExp(match[1], match[2]); + } + break; + case "enum": + if (argConfig.values.includes(value)) return value; + for (const item of argConfig.values) { + if (`${item}` === value) return item; + } + break; + case "reset": + if (value === true) return []; + break; + } +}; - /** - * @param {string} request the request string to load the module from - * @param {ImportModuleOptions} options options - * @param {ImportModuleCallback=} callback callback returning the exports - * @returns {Promise | void} exports - */ - loaderContext.importModule = (request, options, callback) => { - if (!callback) { - return new Promise((resolve, reject) => { - importModule(request, options || {}, (err, result) => { - if (err) reject(err); - else resolve(result); - }); - }); - } - return importModule(request, options || {}, callback); - }; +/** + * @param {Record} args object of arguments + * @param {any} config configuration + * @param {Record} values object with values + * @returns {Problem[] | null} problems or null for success + */ +const processArguments = (args, config, values) => { + /** @type {Problem[]} */ + const problems = []; + for (const key of Object.keys(values)) { + const arg = args[key]; + if (!arg) { + problems.push({ + type: "unknown-argument", + path: "", + argument: key + }); + continue; + } + const processValue = (value, i) => { + const currentProblems = []; + for (const argConfig of arg.configs) { + const problem = processArgumentConfig(argConfig, config, value, i); + if (!problem) { + return; } - ); - }); + currentProblems.push({ + ...problem, + argument: key, + value: value, + index: i + }); + } + problems.push(...currentProblems); + }; + let value = values[key]; + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + processValue(value[i], i); + } + } else { + processValue(value, undefined); + } } -} -module.exports = LoaderPlugin; + if (problems.length === 0) return null; + return problems; +}; + +exports.getArguments = getArguments; +exports.processArguments = processArguments; /***/ }), -/***/ 5826: +/***/ 43950: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sergey Melyukov @smelukov */ -const makeSerializable = __webpack_require__(33032); - -class LocalModule { - constructor(name, idx) { - this.name = name; - this.idx = idx; - this.used = false; - } - - flagUsed() { - this.used = true; - } - - variableName() { - return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__"; - } +const browserslist = __webpack_require__(14907); +const path = __webpack_require__(71017); - serialize(context) { - const { write } = context; +/** @typedef {import("./target").ApiTargetProperties} ApiTargetProperties */ +/** @typedef {import("./target").EcmaTargetProperties} EcmaTargetProperties */ +/** @typedef {import("./target").PlatformTargetProperties} PlatformTargetProperties */ - write(this.name); - write(this.idx); - write(this.used); - } +// [[C:]/path/to/config][:env] +const inputRx = /^(?:((?:[A-Z]:)?[/\\].*?))?(?::(.+?))?$/i; - deserialize(context) { - const { read } = context; +/** + * @typedef {Object} BrowserslistHandlerConfig + * @property {string=} configPath + * @property {string=} env + * @property {string=} query + */ - this.name = read(); - this.idx = read(); - this.used = read(); +/** + * @param {string} input input string + * @param {string} context the context directory + * @returns {BrowserslistHandlerConfig} config + */ +const parse = (input, context) => { + if (!input) { + return {}; } -} - -makeSerializable(LocalModule, "webpack/lib/dependencies/LocalModule"); - -module.exports = LocalModule; - -/***/ }), - -/***/ 52805: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - -class LocalModuleDependency extends NullDependency { - constructor(localModule, range, callNew) { - super(); - - this.localModule = localModule; - this.range = range; - this.callNew = callNew; + if (path.isAbsolute(input)) { + const [, configPath, env] = inputRx.exec(input) || []; + return { configPath, env }; } - serialize(context) { - const { write } = context; - - write(this.localModule); - write(this.range); - write(this.callNew); + const config = browserslist.findConfig(context); - super.serialize(context); + if (config && Object.keys(config).includes(input)) { + return { env: input }; } - deserialize(context) { - const { read } = context; + return { query: input }; +}; - this.localModule = read(); - this.range = read(); - this.callNew = read(); +/** + * @param {string} input input string + * @param {string} context the context directory + * @returns {string[] | undefined} selected browsers + */ +const load = (input, context) => { + const { configPath, env, query } = parse(input, context); - super.deserialize(context); - } -} + // if a query is specified, then use it, else + // if a path to a config is specified then load it, else + // find a nearest config + const config = query + ? query + : configPath + ? browserslist.loadConfig({ + config: configPath, + env + }) + : browserslist.loadConfig({ path: context, env }); -makeSerializable( - LocalModuleDependency, - "webpack/lib/dependencies/LocalModuleDependency" -); + if (!config) return null; + return browserslist(config); +}; -LocalModuleDependency.Template = class LocalModuleDependencyTemplate extends ( - NullDependency.Template -) { +/** + * @param {string[]} browsers supported browsers list + * @returns {EcmaTargetProperties & PlatformTargetProperties & ApiTargetProperties} target properties + */ +const resolve = browsers => { /** - * @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} + * Checks all against a version number + * @param {Record} versions first supported version + * @returns {boolean} true if supports */ - apply(dependency, source, templateContext) { - const dep = /** @type {LocalModuleDependency} */ (dependency); - if (!dep.range) return; - const moduleInstance = dep.callNew - ? `new (function () { return ${dep.localModule.variableName()}; })()` - : dep.localModule.variableName(); - source.replace(dep.range[0], dep.range[1] - 1, moduleInstance); - } + const rawChecker = versions => { + return browsers.every(v => { + const [name, parsedVersion] = v.split(" "); + if (!name) return false; + const requiredVersion = versions[name]; + if (!requiredVersion) return false; + const [parsedMajor, parserMinor] = + // safari TP supports all features for normal safari + parsedVersion === "TP" + ? [Infinity, Infinity] + : parsedVersion.split("."); + if (typeof requiredVersion === "number") { + return +parsedMajor >= requiredVersion; + } + return requiredVersion[0] === +parsedMajor + ? +parserMinor >= requiredVersion[1] + : +parsedMajor > requiredVersion[0]; + }); + }; + const anyNode = browsers.some(b => /^node /.test(b)); + const anyBrowser = browsers.some(b => /^(?!node)/.test(b)); + const browserProperty = !anyBrowser ? false : anyNode ? null : true; + const nodeProperty = !anyNode ? false : anyBrowser ? null : true; + // Internet Explorer Mobile, Blackberry browser and Opera Mini are very old browsers, they do not support new features + const es6DynamicImport = rawChecker({ + chrome: 63, + and_chr: 63, + edge: 79, + firefox: 67, + and_ff: 67, + // ie: Not supported + opera: 50, + op_mob: 46, + safari: [11, 1], + ios_saf: [11, 3], + samsung: [8, 2], + android: 63, + and_qq: [10, 4], + // baidu: Not supported + // and_uc: Not supported + // kaios: Not supported + // Since Node.js 13.14.0 no warning about usage, but it was added 8.5.0 with some limitations and it was improved in 12.0.0 and 13.2.0 + node: [13, 14] + }); + + return { + const: rawChecker({ + chrome: 49, + and_chr: 49, + edge: 12, + // Prior to Firefox 13, const is implemented, but re-assignment is not failing. + // Prior to Firefox 46, a TypeError was thrown on redeclaration instead of a SyntaxError. + firefox: 36, + and_ff: 36, + // Not supported in for-in and for-of loops + // ie: Not supported + opera: 36, + op_mob: 36, + safari: [10, 0], + ios_saf: [10, 0], + // Before 5.0 supported correctly in strict mode, otherwise supported without block scope + samsung: [5, 0], + android: 37, + and_qq: [10, 4], + // Supported correctly in strict mode, otherwise supported without block scope + // baidu: Not supported + and_uc: [12, 12], + kaios: [2, 5], + node: [6, 0] + }), + arrowFunction: rawChecker({ + chrome: 45, + and_chr: 45, + edge: 12, + // The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of 'use strict'; is now required. + // Prior to Firefox 39, a line terminator (\\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \\n => {} will now throw a SyntaxError in this and later versions. + firefox: 39, + and_ff: 39, + // ie: Not supported, + opera: 32, + op_mob: 32, + safari: 10, + ios_saf: 10, + samsung: [5, 0], + android: 45, + and_qq: [10, 4], + baidu: [7, 12], + and_uc: [12, 12], + kaios: [2, 5], + node: [6, 0] + }), + forOf: rawChecker({ + chrome: 38, + and_chr: 38, + edge: 12, + // Prior to Firefox 51, using the for...of loop construct with the const keyword threw a SyntaxError ("missing = in const declaration"). + firefox: 51, + and_ff: 51, + // ie: Not supported, + opera: 25, + op_mob: 25, + safari: 7, + ios_saf: 7, + samsung: [3, 0], + android: 38, + // and_qq: Unknown support + // baidu: Unknown support + // and_uc: Unknown support + // kaios: Unknown support + node: [0, 12] + }), + destructuring: rawChecker({ + chrome: 49, + and_chr: 49, + edge: 14, + firefox: 41, + and_ff: 41, + // ie: Not supported, + opera: 36, + op_mob: 36, + safari: 8, + ios_saf: 8, + samsung: [5, 0], + android: 49, + // and_qq: Unknown support + // baidu: Unknown support + // and_uc: Unknown support + // kaios: Unknown support + node: [6, 0] + }), + bigIntLiteral: rawChecker({ + chrome: 67, + and_chr: 67, + edge: 79, + firefox: 68, + and_ff: 68, + // ie: Not supported, + opera: 54, + op_mob: 48, + safari: 14, + ios_saf: 14, + samsung: [9, 2], + android: 67, + // and_qq: Not supported + // baidu: Not supported + // and_uc: Not supported + // kaios: Not supported + node: [10, 4] + }), + // Support syntax `import` and `export` and no limitations and bugs on Node.js + // Not include `export * as namespace` + module: rawChecker({ + chrome: 61, + and_chr: 61, + edge: 16, + firefox: 60, + and_ff: 60, + // ie: Not supported, + opera: 48, + op_mob: 45, + safari: [10, 1], + ios_saf: [10, 3], + samsung: [8, 0], + android: 61, + and_qq: [10, 4], + // baidu: Not supported + // and_uc: Not supported + // kaios: Not supported + // Since Node.js 13.14.0 no warning about usage, but it was added 8.5.0 with some limitations and it was improved in 12.0.0 and 13.2.0 + node: [13, 14] + }), + dynamicImport: es6DynamicImport, + dynamicImportInWorker: es6DynamicImport && !anyNode, + // browserslist does not have info about globalThis + // so this is based on mdn-browser-compat-data + globalThis: rawChecker({ + chrome: 71, + and_chr: 71, + edge: 79, + firefox: 65, + and_ff: 65, + // ie: Not supported, + opera: 58, + op_mob: 50, + safari: [12, 1], + ios_saf: [12, 2], + samsung: [10, 1], + android: 71, + // and_qq: Unknown support + // baidu: Unknown support + // and_uc: Unknown support + // kaios: Unknown support + node: [12, 0] + }), + optionalChaining: rawChecker({ + chrome: 80, + and_chr: 80, + edge: 80, + firefox: 74, + and_ff: 79, + // ie: Not supported, + opera: 67, + op_mob: 64, + safari: [13, 1], + ios_saf: [13, 4], + samsung: 13, + android: 80, + // and_qq: Not supported + // baidu: Not supported + // and_uc: Not supported + // kaios: Not supported + node: 14 + }), + templateLiteral: rawChecker({ + chrome: 41, + and_chr: 41, + edge: 13, + firefox: 34, + and_ff: 34, + // ie: Not supported, + opera: 29, + op_mob: 64, + safari: [9, 1], + ios_saf: 9, + samsung: 4, + android: 41, + and_qq: [10, 4], + baidu: [7, 12], + and_uc: [12, 12], + kaios: [2, 5], + node: 4 + }), + browser: browserProperty, + electron: false, + node: nodeProperty, + nwjs: false, + web: browserProperty, + webworker: false, + + document: browserProperty, + fetchWasm: browserProperty, + global: nodeProperty, + importScripts: false, + importScriptsInWorker: true, + nodeBuiltins: nodeProperty, + require: nodeProperty + }; }; -module.exports = LocalModuleDependency; +module.exports = { + resolve, + load +}; /***/ }), -/***/ 75827: +/***/ 92988: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; @@ -81434,456 +76785,1307 @@ module.exports = LocalModuleDependency; -const LocalModule = __webpack_require__(5826); +const fs = __webpack_require__(57147); +const path = __webpack_require__(71017); +const Template = __webpack_require__(39722); +const { cleverMerge } = __webpack_require__(60839); +const { + getTargetsProperties, + getTargetProperties, + getDefaultTarget +} = __webpack_require__(52801); -const lookup = (parent, mod) => { - if (mod.charAt(0) !== ".") return mod; +/** @typedef {import("../../declarations/WebpackOptions").CacheOptionsNormalized} CacheOptions */ +/** @typedef {import("../../declarations/WebpackOptions").CssExperimentOptions} CssExperimentOptions */ +/** @typedef {import("../../declarations/WebpackOptions").EntryDescription} EntryDescription */ +/** @typedef {import("../../declarations/WebpackOptions").EntryNormalized} Entry */ +/** @typedef {import("../../declarations/WebpackOptions").Experiments} Experiments */ +/** @typedef {import("../../declarations/WebpackOptions").ExperimentsNormalized} ExperimentsNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").ExternalsPresets} ExternalsPresets */ +/** @typedef {import("../../declarations/WebpackOptions").ExternalsType} ExternalsType */ +/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../../declarations/WebpackOptions").Library} Library */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").Loader} Loader */ +/** @typedef {import("../../declarations/WebpackOptions").Mode} Mode */ +/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ +/** @typedef {import("../../declarations/WebpackOptions").Node} WebpackNode */ +/** @typedef {import("../../declarations/WebpackOptions").Optimization} Optimization */ +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */ +/** @typedef {import("../../declarations/WebpackOptions").Performance} Performance */ +/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetRules} RuleSetRules */ +/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */ +/** @typedef {import("../../declarations/WebpackOptions").Target} Target */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./target").TargetProperties} TargetProperties */ - var path = parent.split("/"); - var segments = mod.split("/"); - path.pop(); +const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i; - for (let i = 0; i < segments.length; i++) { - const seg = segments[i]; - if (seg === "..") { - path.pop(); - } else if (seg !== ".") { - path.push(seg); - } +/** + * Sets a constant default value when undefined + * @template T + * @template {keyof T} P + * @param {T} obj an object + * @param {P} prop a property of this object + * @param {T[P]} value a default value of the property + * @returns {void} + */ +const D = (obj, prop, value) => { + if (obj[prop] === undefined) { + obj[prop] = value; } - - return path.join("/"); }; -exports.addLocalModule = (state, name) => { - if (!state.localModules) { - state.localModules = []; +/** + * Sets a dynamic default value when undefined, by calling the factory function + * @template T + * @template {keyof T} P + * @param {T} obj an object + * @param {P} prop a property of this object + * @param {function(): T[P]} factory a default value factory for the property + * @returns {void} + */ +const F = (obj, prop, factory) => { + if (obj[prop] === undefined) { + obj[prop] = factory(); } - const m = new LocalModule(name, state.localModules.length); - state.localModules.push(m); - return m; }; -exports.getLocalModule = (state, name, namedModule) => { - if (!state.localModules) return null; - if (namedModule) { - // resolve dependency name relative to the defining named module - name = lookup(namedModule, name); - } - for (let i = 0; i < state.localModules.length; i++) { - if (state.localModules[i].name === name) { - return state.localModules[i]; +/** + * Sets a dynamic default value when undefined, by calling the factory function. + * factory must return an array or undefined + * When the current value is already an array an contains "..." it's replaced with + * the result of the factory function + * @template T + * @template {keyof T} P + * @param {T} obj an object + * @param {P} prop a property of this object + * @param {function(): T[P]} factory a default value factory for the property + * @returns {void} + */ +const A = (obj, prop, factory) => { + const value = obj[prop]; + if (value === undefined) { + obj[prop] = factory(); + } else if (Array.isArray(value)) { + /** @type {any[]} */ + let newArray = undefined; + for (let i = 0; i < value.length; i++) { + const item = value[i]; + if (item === "...") { + if (newArray === undefined) { + newArray = value.slice(0, i); + obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray)); + } + const items = /** @type {any[]} */ (/** @type {unknown} */ (factory())); + if (items !== undefined) { + for (const item of items) { + newArray.push(item); + } + } + } else if (newArray !== undefined) { + newArray.push(item); + } } } - return null; }; +/** + * @param {WebpackOptions} options options to be modified + * @returns {void} + */ +const applyWebpackOptionsBaseDefaults = options => { + F(options, "context", () => process.cwd()); + applyInfrastructureLoggingDefaults(options.infrastructureLogging); +}; -/***/ }), +/** + * @param {WebpackOptions} options options to be modified + * @returns {void} + */ +const applyWebpackOptionsDefaults = options => { + F(options, "context", () => process.cwd()); + F(options, "target", () => { + return getDefaultTarget(options.context); + }); -/***/ 88488: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const { mode, name, target } = options; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + let targetProperties = + target === false + ? /** @type {false} */ (false) + : typeof target === "string" + ? getTargetProperties(target, options.context) + : getTargetsProperties(target, options.context); + const development = mode === "development"; + const production = mode === "production" || !mode; + if (typeof options.entry !== "function") { + for (const key of Object.keys(options.entry)) { + F( + options.entry[key], + "import", + () => /** @type {[string]} */ (["./src"]) + ); + } + } -const Dependency = __webpack_require__(54912); -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); + F(options, "devtool", () => (development ? "eval" : false)); + D(options, "watch", false); + D(options, "profile", false); + D(options, "parallelism", 100); + D(options, "recordsInputPath", false); + D(options, "recordsOutputPath", false); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + applyExperimentsDefaults(options.experiments, { + production, + development, + targetProperties + }); -class ModuleDecoratorDependency extends NullDependency { - /** - * @param {string} decorator the decorator requirement - * @param {boolean} allowExportsAccess allow to access exports from module - */ - constructor(decorator, allowExportsAccess) { - super(); - this.decorator = decorator; - this.allowExportsAccess = allowExportsAccess; - this._hashUpdate = undefined; - } + const futureDefaults = options.experiments.futureDefaults; - /** - * @returns {string} a display name for the type of dependency - */ - get type() { - return "module decorator"; - } + F(options, "cache", () => + development ? { type: /** @type {"memory"} */ ("memory") } : false + ); + applyCacheDefaults(options.cache, { + name: name || "default", + mode: mode || "production", + development, + cacheUnaffected: options.experiments.cacheUnaffected + }); + const cache = !!options.cache; - get category() { - return "self"; - } + applySnapshotDefaults(options.snapshot, { + production, + futureDefaults + }); - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - return `self`; - } + applyModuleDefaults(options.module, { + cache, + syncWebAssembly: options.experiments.syncWebAssembly, + asyncWebAssembly: options.experiments.asyncWebAssembly, + css: options.experiments.css, + futureDefaults + }); - /** - * 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 this.allowExportsAccess - ? Dependency.EXPORTS_OBJECT_REFERENCED - : Dependency.NO_EXPORTS_REFERENCED; - } + applyOutputDefaults(options.output, { + context: options.context, + targetProperties, + isAffectedByBrowserslist: + target === undefined || + (typeof target === "string" && target.startsWith("browserslist")) || + (Array.isArray(target) && + target.some(target => target.startsWith("browserslist"))), + outputModule: options.experiments.outputModule, + development, + entry: options.entry, + module: options.module, + futureDefaults + }); - /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) { - this._hashUpdate = `${this.decorator}${this.allowExportsAccess}`; - } - hash.update(this._hashUpdate); - } + applyExternalsPresetsDefaults(options.externalsPresets, { + targetProperties, + buildHttp: !!options.experiments.buildHttp + }); - serialize(context) { - const { write } = context; - write(this.decorator); - write(this.allowExportsAccess); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.decorator = read(); - this.allowExportsAccess = read(); - super.deserialize(context); - } -} - -makeSerializable( - ModuleDecoratorDependency, - "webpack/lib/dependencies/ModuleDecoratorDependency" -); - -ModuleDecoratorDependency.Template = class ModuleDecoratorDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, - { module, chunkGraph, initFragments, runtimeRequirements } - ) { - const dep = /** @type {ModuleDecoratorDependency} */ (dependency); - runtimeRequirements.add(RuntimeGlobals.moduleLoaded); - runtimeRequirements.add(RuntimeGlobals.moduleId); - runtimeRequirements.add(RuntimeGlobals.module); - runtimeRequirements.add(dep.decorator); - initFragments.push( - new InitFragment( - `/* module decorator */ ${module.moduleArgument} = ${dep.decorator}(${module.moduleArgument});\n`, - InitFragment.STAGE_PROVIDES, - 0, - `module decorator ${chunkGraph.getModuleId(module)}` - ) - ); - } -}; - -module.exports = ModuleDecoratorDependency; - - -/***/ }), + applyLoaderDefaults(options.loader, { targetProperties }); -/***/ 80321: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + F(options, "externalsType", () => { + const validExternalTypes = (__webpack_require__(73342).definitions.ExternalsType["enum"]); + return options.output.library && + validExternalTypes.includes(options.output.library.type) + ? /** @type {ExternalsType} */ (options.output.library.type) + : options.output.module + ? "module" + : "var"; + }); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + applyNodeDefaults(options.node, { + futureDefaults: options.experiments.futureDefaults, + targetProperties + }); + F(options, "performance", () => + production && + targetProperties && + (targetProperties.browser || targetProperties.browser === null) + ? {} + : false + ); + applyPerformanceDefaults(options.performance, { + production + }); + applyOptimizationDefaults(options.optimization, { + development, + production, + css: options.experiments.css, + records: !!(options.recordsInputPath || options.recordsOutputPath) + }); -const Dependency = __webpack_require__(54912); -const DependencyTemplate = __webpack_require__(5160); -const memoize = __webpack_require__(78676); + options.resolve = cleverMerge( + getResolveDefaults({ + cache, + context: options.context, + targetProperties, + mode: options.mode + }), + options.resolve + ); -/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ -/** @typedef {import("../Module")} Module */ + options.resolveLoader = cleverMerge( + getResolveLoaderDefaults({ cache }), + options.resolveLoader + ); +}; -const getRawModule = memoize(() => __webpack_require__(84929)); +/** + * @param {ExperimentsNormalized} experiments options + * @param {Object} options options + * @param {boolean} options.production is production + * @param {boolean} options.development is development mode + * @param {TargetProperties | false} options.targetProperties target properties + * @returns {void} + */ +const applyExperimentsDefaults = ( + experiments, + { production, development, targetProperties } +) => { + D(experiments, "futureDefaults", false); + D(experiments, "backCompat", !experiments.futureDefaults); + D(experiments, "topLevelAwait", experiments.futureDefaults); + D(experiments, "syncWebAssembly", false); + D(experiments, "asyncWebAssembly", experiments.futureDefaults); + D(experiments, "outputModule", false); + D(experiments, "layers", false); + D(experiments, "lazyCompilation", undefined); + D(experiments, "buildHttp", undefined); + D(experiments, "cacheUnaffected", experiments.futureDefaults); + F(experiments, "css", () => (experiments.futureDefaults ? {} : undefined)); -class ModuleDependency extends Dependency { - /** - * @param {string} request request path which needs resolving - */ - constructor(request) { - super(); - this.request = request; - this.userRequest = request; - this.range = undefined; - // assertions must be serialized by subclasses that use it - /** @type {Record | undefined} */ - this.assertions = undefined; + if (typeof experiments.buildHttp === "object") { + D(experiments.buildHttp, "frozen", production); + D(experiments.buildHttp, "upgrade", false); } - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - let str = `module${this.request}`; - if (this.assertions !== undefined) { - str += JSON.stringify(this.assertions); - } - return str; + if (typeof experiments.css === "object") { + D( + experiments.css, + "exportsOnly", + !targetProperties || !targetProperties.document + ); } +}; - /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module - */ - couldAffectReferencingModule() { - return true; +/** + * @param {CacheOptions} cache options + * @param {Object} options options + * @param {string} options.name name + * @param {string} options.mode mode + * @param {boolean} options.development is development mode + * @param {boolean} options.cacheUnaffected the cacheUnaffected experiment is enabled + * @returns {void} + */ +const applyCacheDefaults = ( + cache, + { name, mode, development, cacheUnaffected } +) => { + if (cache === false) return; + switch (cache.type) { + case "filesystem": + F(cache, "name", () => name + "-" + mode); + D(cache, "version", ""); + F(cache, "cacheDirectory", () => { + const cwd = process.cwd(); + let dir = cwd; + for (;;) { + try { + if (fs.statSync(path.join(dir, "package.json")).isFile()) break; + // eslint-disable-next-line no-empty + } catch (e) {} + const parent = path.dirname(dir); + if (dir === parent) { + dir = undefined; + break; + } + dir = parent; + } + if (!dir) { + return path.resolve(cwd, ".cache/webpack"); + } else if (process.versions.pnp === "1") { + return path.resolve(dir, ".pnp/.cache/webpack"); + } else if (process.versions.pnp === "3") { + return path.resolve(dir, ".yarn/.cache/webpack"); + } else { + return path.resolve(dir, "node_modules/.cache/webpack"); + } + }); + F(cache, "cacheLocation", () => + path.resolve(cache.cacheDirectory, cache.name) + ); + D(cache, "hashAlgorithm", "md4"); + D(cache, "store", "pack"); + D(cache, "compression", false); + D(cache, "profile", false); + D(cache, "idleTimeout", 60000); + D(cache, "idleTimeoutForInitialStore", 5000); + D(cache, "idleTimeoutAfterLargeChanges", 1000); + D(cache, "maxMemoryGenerations", development ? 5 : Infinity); + D(cache, "maxAge", 1000 * 60 * 60 * 24 * 60); // 1 month + D(cache, "allowCollectingMemory", development); + D(cache, "memoryCacheUnaffected", development && cacheUnaffected); + D(cache.buildDependencies, "defaultWebpack", [ + path.resolve(__dirname, "..") + path.sep + ]); + break; + case "memory": + D(cache, "maxGenerations", Infinity); + D(cache, "cacheUnaffected", development && cacheUnaffected); + break; } +}; - /** - * @param {string} context context directory - * @returns {Module} a module - */ - createIgnoredModule(context) { - const RawModule = getRawModule(); - return new RawModule( - "/* (ignored) */", - `ignored|${context}|${this.request}`, - `${this.request} (ignored)` +/** + * @param {SnapshotOptions} snapshot options + * @param {Object} options options + * @param {boolean} options.production is production + * @param {boolean} options.futureDefaults is future defaults enabled + * @returns {void} + */ +const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => { + if (futureDefaults) { + F(snapshot, "managedPaths", () => + process.versions.pnp === "3" + ? [ + /^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/ + ] + : [/^(.+?[\\/]node_modules[\\/])/] ); + F(snapshot, "immutablePaths", () => + process.versions.pnp === "3" + ? [/^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/] + : [] + ); + } else { + A(snapshot, "managedPaths", () => { + if (process.versions.pnp === "3") { + const match = + /^(.+?)[\\/]cache[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec( + /*require.resolve*/(36871) + ); + if (match) { + return [path.resolve(match[1], "unplugged")]; + } + } else { + const match = /^(.+?[\\/]node_modules[\\/])/.exec( + // eslint-disable-next-line node/no-extraneous-require + /*require.resolve*/(36871) + ); + if (match) { + return [match[1]]; + } + } + return []; + }); + A(snapshot, "immutablePaths", () => { + if (process.versions.pnp === "1") { + const match = + /^(.+?[\\/]v4)[\\/]npm-watchpack-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec( + /*require.resolve*/(36871) + ); + if (match) { + return [match[1]]; + } + } else if (process.versions.pnp === "3") { + const match = + /^(.+?)[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec( + /*require.resolve*/(36871) + ); + if (match) { + return [match[1]]; + } + } + return []; + }); } + F(snapshot, "resolveBuildDependencies", () => ({ + timestamp: true, + hash: true + })); + F(snapshot, "buildDependencies", () => ({ timestamp: true, hash: true })); + F(snapshot, "module", () => + production ? { timestamp: true, hash: true } : { timestamp: true } + ); + F(snapshot, "resolve", () => + production ? { timestamp: true, hash: true } : { timestamp: true } + ); +}; - serialize(context) { - const { write } = context; - write(this.request); - write(this.userRequest); - write(this.range); - super.serialize(context); - } +/** + * @param {JavascriptParserOptions} parserOptions parser options + * @param {Object} options options + * @param {boolean} options.futureDefaults is future defaults enabled + * @returns {void} + */ +const applyJavascriptParserOptionsDefaults = ( + parserOptions, + { futureDefaults } +) => { + D(parserOptions, "unknownContextRequest", "."); + D(parserOptions, "unknownContextRegExp", false); + D(parserOptions, "unknownContextRecursive", true); + D(parserOptions, "unknownContextCritical", true); + D(parserOptions, "exprContextRequest", "."); + D(parserOptions, "exprContextRegExp", false); + D(parserOptions, "exprContextRecursive", true); + D(parserOptions, "exprContextCritical", true); + D(parserOptions, "wrappedContextRegExp", /.*/); + D(parserOptions, "wrappedContextRecursive", true); + D(parserOptions, "wrappedContextCritical", false); + D(parserOptions, "strictThisContextOnImports", false); + if (futureDefaults) D(parserOptions, "exportsPresence", "error"); +}; - deserialize(context) { - const { read } = context; - this.request = read(); - this.userRequest = read(); - this.range = read(); - super.deserialize(context); +/** + * @param {ModuleOptions} module options + * @param {Object} options options + * @param {boolean} options.cache is caching enabled + * @param {boolean} options.syncWebAssembly is syncWebAssembly enabled + * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled + * @param {CssExperimentOptions} options.css is css enabled + * @param {boolean} options.futureDefaults is future defaults enabled + * @returns {void} + */ +const applyModuleDefaults = ( + module, + { cache, syncWebAssembly, asyncWebAssembly, css, futureDefaults } +) => { + if (cache) { + D(module, "unsafeCache", module => { + const name = module.nameForCondition(); + return name && NODE_MODULES_REGEXP.test(name); + }); + } else { + D(module, "unsafeCache", false); } -} - -ModuleDependency.Template = DependencyTemplate; - -module.exports = ModuleDependency; - - -/***/ }), - -/***/ 80825: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + F(module.parser, "asset", () => ({})); + F(module.parser.asset, "dataUrlCondition", () => ({})); + if (typeof module.parser.asset.dataUrlCondition === "object") { + D(module.parser.asset.dataUrlCondition, "maxSize", 8096); + } -const ModuleDependency = __webpack_require__(80321); + F(module.parser, "javascript", () => ({})); + applyJavascriptParserOptionsDefaults(module.parser.javascript, { + futureDefaults + }); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + A(module, "defaultRules", () => { + const esm = { + type: "javascript/esm", + resolve: { + byDependency: { + esm: { + fullySpecified: true + } + } + } + }; + const commonjs = { + type: "javascript/dynamic" + }; + /** @type {RuleSetRules} */ + const rules = [ + { + mimetype: "application/node", + type: "javascript/auto" + }, + { + test: /\.json$/i, + type: "json" + }, + { + mimetype: "application/json", + type: "json" + }, + { + test: /\.mjs$/i, + ...esm + }, + { + test: /\.js$/i, + descriptionData: { + type: "module" + }, + ...esm + }, + { + test: /\.cjs$/i, + ...commonjs + }, + { + test: /\.js$/i, + descriptionData: { + type: "commonjs" + }, + ...commonjs + }, + { + mimetype: { + or: ["text/javascript", "application/javascript"] + }, + ...esm + } + ]; + if (asyncWebAssembly) { + const wasm = { + type: "webassembly/async", + rules: [ + { + descriptionData: { + type: "module" + }, + resolve: { + fullySpecified: true + } + } + ] + }; + rules.push({ + test: /\.wasm$/i, + ...wasm + }); + rules.push({ + mimetype: "application/wasm", + ...wasm + }); + } else if (syncWebAssembly) { + const wasm = { + type: "webassembly/sync", + rules: [ + { + descriptionData: { + type: "module" + }, + resolve: { + fullySpecified: true + } + } + ] + }; + rules.push({ + test: /\.wasm$/i, + ...wasm + }); + rules.push({ + mimetype: "application/wasm", + ...wasm + }); + } + if (css) { + const cssRule = { + type: "css", + resolve: { + fullySpecified: true, + preferRelative: true + } + }; + const cssModulesRule = { + type: "css/module", + resolve: { + fullySpecified: true + } + }; + rules.push({ + test: /\.css$/i, + oneOf: [ + { + test: /\.module\.css$/i, + ...cssModulesRule + }, + { + ...cssRule + } + ] + }); + rules.push({ + mimetype: "text/css+module", + ...cssModulesRule + }); + rules.push({ + mimetype: "text/css", + ...cssRule + }); + } + rules.push( + { + dependency: "url", + oneOf: [ + { + scheme: /^data$/, + type: "asset/inline" + }, + { + type: "asset/resource" + } + ] + }, + { + assert: { type: "json" }, + type: "json" + } + ); + return rules; + }); +}; -class ModuleDependencyTemplateAsId extends ModuleDependency.Template { +/** + * @param {Output} output options + * @param {Object} options options + * @param {string} options.context context + * @param {TargetProperties | false} options.targetProperties target properties + * @param {boolean} options.isAffectedByBrowserslist is affected by browserslist + * @param {boolean} options.outputModule is outputModule experiment enabled + * @param {boolean} options.development is development mode + * @param {Entry} options.entry entry option + * @param {ModuleOptions} options.module module option + * @param {boolean} options.futureDefaults is future defaults enabled + * @returns {void} + */ +const applyOutputDefaults = ( + output, + { + context, + targetProperties: tp, + isAffectedByBrowserslist, + outputModule, + development, + entry, + module, + futureDefaults + } +) => { /** - * @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} + * @param {Library=} library the library option + * @returns {string} a readable library name */ - apply(dependency, source, { runtimeTemplate, moduleGraph, chunkGraph }) { - const dep = /** @type {ModuleDependency} */ (dependency); - if (!dep.range) return; - const content = runtimeTemplate.moduleId({ - module: moduleGraph.getModule(dep), - chunkGraph, - request: dep.request, - weak: dep.weak - }); - source.replace(dep.range[0], dep.range[1] - 1, content); - } -} - -module.exports = ModuleDependencyTemplateAsId; - - -/***/ }), - -/***/ 36873: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const getLibraryName = library => { + const libraryName = + typeof library === "object" && + library && + !Array.isArray(library) && + "type" in library + ? library.name + : /** @type {LibraryName=} */ (library); + if (Array.isArray(libraryName)) { + return libraryName.join("."); + } else if (typeof libraryName === "object") { + return getLibraryName(libraryName.root); + } else if (typeof libraryName === "string") { + return libraryName; + } + return ""; + }; + F(output, "uniqueName", () => { + const libraryName = getLibraryName(output.library); + if (libraryName) return libraryName; + const pkgPath = path.resolve(context, "package.json"); + try { + const packageInfo = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); + return packageInfo.name || ""; + } catch (e) { + if (e.code !== "ENOENT") { + e.message += `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`; + throw e; + } + return ""; + } + }); + F(output, "module", () => !!outputModule); + D(output, "filename", output.module ? "[name].mjs" : "[name].js"); + F(output, "iife", () => !output.module); + D(output, "importFunctionName", "import"); + D(output, "importMetaName", "import.meta"); + F(output, "chunkFilename", () => { + const filename = output.filename; + if (typeof filename !== "function") { + const hasName = filename.includes("[name]"); + const hasId = filename.includes("[id]"); + const hasChunkHash = filename.includes("[chunkhash]"); + const hasContentHash = filename.includes("[contenthash]"); + // Anything changing depending on chunk is fine + if (hasChunkHash || hasContentHash || hasName || hasId) return filename; + // Otherwise prefix "[id]." in front of the basename to make it changing + return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2"); + } + return output.module ? "[id].mjs" : "[id].js"; + }); + F(output, "cssFilename", () => { + const filename = output.filename; + if (typeof filename !== "function") { + return filename.replace(/\.[mc]?js(\?|$)/, ".css$1"); + } + return "[id].css"; + }); + F(output, "cssChunkFilename", () => { + const chunkFilename = output.chunkFilename; + if (typeof chunkFilename !== "function") { + return chunkFilename.replace(/\.[mc]?js(\?|$)/, ".css$1"); + } + return "[id].css"; + }); + D(output, "assetModuleFilename", "[hash][ext][query]"); + D(output, "webassemblyModuleFilename", "[hash].module.wasm"); + D(output, "compareBeforeEmit", true); + D(output, "charset", true); + F(output, "hotUpdateGlobal", () => + Template.toIdentifier( + "webpackHotUpdate" + Template.toIdentifier(output.uniqueName) + ) + ); + F(output, "chunkLoadingGlobal", () => + Template.toIdentifier( + "webpackChunk" + Template.toIdentifier(output.uniqueName) + ) + ); + F(output, "globalObject", () => { + if (tp) { + if (tp.global) return "global"; + if (tp.globalThis) return "globalThis"; + } + return "self"; + }); + F(output, "chunkFormat", () => { + if (tp) { + const helpMessage = isAffectedByBrowserslist + ? "Make sure that your 'browserslist' includes only platforms that support these features or select an appropriate 'target' to allow selecting a chunk format by default. Alternatively specify the 'output.chunkFormat' directly." + : "Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly."; + if (output.module) { + if (tp.dynamicImport) return "module"; + if (tp.document) return "array-push"; + throw new Error( + "For the selected environment is no default ESM chunk format available:\n" + + "ESM exports can be chosen when 'import()' is available.\n" + + "JSONP Array push can be chosen when 'document' is available.\n" + + helpMessage + ); + } else { + if (tp.document) return "array-push"; + if (tp.require) return "commonjs"; + if (tp.nodeBuiltins) return "commonjs"; + if (tp.importScripts) return "array-push"; + throw new Error( + "For the selected environment is no default script chunk format available:\n" + + "JSONP Array push can be chosen when 'document' or 'importScripts' is available.\n" + + "CommonJs exports can be chosen when 'require' or node builtins are available.\n" + + helpMessage + ); + } + } + throw new Error( + "Chunk format can't be selected by default when no target is specified" + ); + }); + D(output, "asyncChunks", true); + F(output, "chunkLoading", () => { + if (tp) { + switch (output.chunkFormat) { + case "array-push": + if (tp.document) return "jsonp"; + if (tp.importScripts) return "import-scripts"; + break; + case "commonjs": + if (tp.require) return "require"; + if (tp.nodeBuiltins) return "async-node"; + break; + case "module": + if (tp.dynamicImport) return "import"; + break; + } + if ( + tp.require === null || + tp.nodeBuiltins === null || + tp.document === null || + tp.importScripts === null + ) { + return "universal"; + } + } + return false; + }); + F(output, "workerChunkLoading", () => { + if (tp) { + switch (output.chunkFormat) { + case "array-push": + if (tp.importScriptsInWorker) return "import-scripts"; + break; + case "commonjs": + if (tp.require) return "require"; + if (tp.nodeBuiltins) return "async-node"; + break; + case "module": + if (tp.dynamicImportInWorker) return "import"; + break; + } + if ( + tp.require === null || + tp.nodeBuiltins === null || + tp.importScriptsInWorker === null + ) { + return "universal"; + } + } + return false; + }); + F(output, "wasmLoading", () => { + if (tp) { + if (tp.fetchWasm) return "fetch"; + if (tp.nodeBuiltins) + return output.module ? "async-node-module" : "async-node"; + if (tp.nodeBuiltins === null || tp.fetchWasm === null) { + return "universal"; + } + } + return false; + }); + F(output, "workerWasmLoading", () => output.wasmLoading); + F(output, "devtoolNamespace", () => output.uniqueName); + if (output.library) { + F(output.library, "type", () => (output.module ? "module" : "var")); + } + F(output, "path", () => path.join(process.cwd(), "dist")); + F(output, "pathinfo", () => development); + D(output, "sourceMapFilename", "[file].map[query]"); + D( + output, + "hotUpdateChunkFilename", + `[id].[fullhash].hot-update.${output.module ? "mjs" : "js"}` + ); + D(output, "hotUpdateMainFilename", "[runtime].[fullhash].hot-update.json"); + D(output, "crossOriginLoading", false); + F(output, "scriptType", () => (output.module ? "module" : false)); + D( + output, + "publicPath", + (tp && (tp.document || tp.importScripts)) || output.scriptType === "module" + ? "auto" + : "" + ); + D(output, "chunkLoadTimeout", 120000); + D(output, "hashFunction", futureDefaults ? "xxhash64" : "md4"); + D(output, "hashDigest", "hex"); + D(output, "hashDigestLength", futureDefaults ? 16 : 20); + D(output, "strictModuleExceptionHandling", false); -const ModuleDependency = __webpack_require__(80321); + const optimistic = v => v || v === undefined; + F( + output.environment, + "arrowFunction", + () => tp && optimistic(tp.arrowFunction) + ); + F(output.environment, "const", () => tp && optimistic(tp.const)); + F( + output.environment, + "destructuring", + () => tp && optimistic(tp.destructuring) + ); + F(output.environment, "forOf", () => tp && optimistic(tp.forOf)); + F(output.environment, "bigIntLiteral", () => tp && tp.bigIntLiteral); + F(output.environment, "dynamicImport", () => tp && tp.dynamicImport); + F(output.environment, "module", () => tp && tp.module); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + const { trustedTypes } = output; + if (trustedTypes) { + F( + trustedTypes, + "policyName", + () => + output.uniqueName.replace(/[^a-zA-Z0-9\-#=_/@.%]+/g, "_") || "webpack" + ); + } -class ModuleDependencyTemplateAsRequireId extends ModuleDependency.Template { /** - * @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 + * @param {function(EntryDescription): void} fn iterator * @returns {void} */ - apply( - dependency, - source, - { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {ModuleDependency} */ (dependency); - if (!dep.range) return; - const content = runtimeTemplate.moduleExports({ - module: moduleGraph.getModule(dep), - chunkGraph, - request: dep.request, - weak: dep.weak, - runtimeRequirements + const forEachEntry = fn => { + for (const name of Object.keys(entry)) { + fn(entry[name]); + } + }; + A(output, "enabledLibraryTypes", () => { + const enabledLibraryTypes = []; + if (output.library) { + enabledLibraryTypes.push(output.library.type); + } + forEachEntry(desc => { + if (desc.library) { + enabledLibraryTypes.push(desc.library.type); + } }); - source.replace(dep.range[0], dep.range[1] - 1, content); - } -} -module.exports = ModuleDependencyTemplateAsRequireId; + return enabledLibraryTypes; + }); + A(output, "enabledChunkLoadingTypes", () => { + const enabledChunkLoadingTypes = new Set(); + if (output.chunkLoading) { + enabledChunkLoadingTypes.add(output.chunkLoading); + } + if (output.workerChunkLoading) { + enabledChunkLoadingTypes.add(output.workerChunkLoading); + } + forEachEntry(desc => { + if (desc.chunkLoading) { + enabledChunkLoadingTypes.add(desc.chunkLoading); + } + }); + return Array.from(enabledChunkLoadingTypes); + }); -/***/ }), + A(output, "enabledWasmLoadingTypes", () => { + const enabledWasmLoadingTypes = new Set(); + if (output.wasmLoading) { + enabledWasmLoadingTypes.add(output.wasmLoading); + } + if (output.workerWasmLoading) { + enabledWasmLoadingTypes.add(output.workerWasmLoading); + } + forEachEntry(desc => { + if (desc.wasmLoading) { + enabledWasmLoadingTypes.add(desc.wasmLoading); + } + }); + return Array.from(enabledWasmLoadingTypes); + }); +}; -/***/ 47511: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @param {ExternalsPresets} externalsPresets options + * @param {Object} options options + * @param {TargetProperties | false} options.targetProperties target properties + * @param {boolean} options.buildHttp buildHttp experiment enabled + * @returns {void} + */ +const applyExternalsPresetsDefaults = ( + externalsPresets, + { targetProperties, buildHttp } +) => { + D( + externalsPresets, + "web", + !buildHttp && targetProperties && targetProperties.web + ); + D(externalsPresets, "node", targetProperties && targetProperties.node); + D(externalsPresets, "nwjs", targetProperties && targetProperties.nwjs); + D( + externalsPresets, + "electron", + targetProperties && targetProperties.electron + ); + D( + externalsPresets, + "electronMain", + targetProperties && + targetProperties.electron && + targetProperties.electronMain + ); + D( + externalsPresets, + "electronPreload", + targetProperties && + targetProperties.electron && + targetProperties.electronPreload + ); + D( + externalsPresets, + "electronRenderer", + targetProperties && + targetProperties.electron && + targetProperties.electronRenderer + ); +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @param {Loader} loader options + * @param {Object} options options + * @param {TargetProperties | false} options.targetProperties target properties + * @returns {void} + */ +const applyLoaderDefaults = (loader, { targetProperties }) => { + F(loader, "target", () => { + if (targetProperties) { + if (targetProperties.electron) { + if (targetProperties.electronMain) return "electron-main"; + if (targetProperties.electronPreload) return "electron-preload"; + if (targetProperties.electronRenderer) return "electron-renderer"; + return "electron"; + } + if (targetProperties.nwjs) return "nwjs"; + if (targetProperties.node) return "node"; + if (targetProperties.web) return "web"; + } + }); +}; +/** + * @param {WebpackNode} node options + * @param {Object} options options + * @param {TargetProperties | false} options.targetProperties target properties + * @param {boolean} options.futureDefaults is future defaults enabled + * @returns {void} + */ +const applyNodeDefaults = (node, { futureDefaults, targetProperties }) => { + if (node === false) return; + F(node, "global", () => { + if (targetProperties && targetProperties.global) return false; + // TODO webpack 6 should always default to false + return futureDefaults ? "warn" : true; + }); + F(node, "__filename", () => { + if (targetProperties && targetProperties.node) return "eval-only"; + // TODO webpack 6 should always default to false + return futureDefaults ? "warn-mock" : "mock"; + }); + F(node, "__dirname", () => { + if (targetProperties && targetProperties.node) return "eval-only"; + // TODO webpack 6 should always default to false + return futureDefaults ? "warn-mock" : "mock"; + }); +}; -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyTemplateAsId = __webpack_require__(80825); - -class ModuleHotAcceptDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; - this.weak = true; - } - - get type() { - return "module.hot.accept"; - } +/** + * @param {Performance} performance options + * @param {Object} options options + * @param {boolean} options.production is production + * @returns {void} + */ +const applyPerformanceDefaults = (performance, { production }) => { + if (performance === false) return; + D(performance, "maxAssetSize", 250000); + D(performance, "maxEntrypointSize", 250000); + F(performance, "hints", () => (production ? "warning" : false)); +}; - get category() { - return "commonjs"; +/** + * @param {Optimization} optimization options + * @param {Object} options options + * @param {boolean} options.production is production + * @param {boolean} options.development is development + * @param {CssExperimentOptions} options.css is css enabled + * @param {boolean} options.records using records + * @returns {void} + */ +const applyOptimizationDefaults = ( + optimization, + { production, development, css, records } +) => { + D(optimization, "removeAvailableModules", false); + D(optimization, "removeEmptyChunks", true); + D(optimization, "mergeDuplicateChunks", true); + D(optimization, "flagIncludedChunks", production); + F(optimization, "moduleIds", () => { + if (production) return "deterministic"; + if (development) return "named"; + return "natural"; + }); + F(optimization, "chunkIds", () => { + if (production) return "deterministic"; + if (development) return "named"; + return "natural"; + }); + F(optimization, "sideEffects", () => (production ? true : "flag")); + D(optimization, "providedExports", true); + D(optimization, "usedExports", production); + D(optimization, "innerGraph", production); + D(optimization, "mangleExports", production); + D(optimization, "concatenateModules", production); + D(optimization, "runtimeChunk", false); + D(optimization, "emitOnErrors", !production); + D(optimization, "checkWasmTypes", production); + D(optimization, "mangleWasmImports", false); + D(optimization, "portableRecords", records); + D(optimization, "realContentHash", production); + D(optimization, "minimize", production); + A(optimization, "minimizer", () => [ + { + apply: compiler => { + // Lazy load the Terser plugin + const TerserPlugin = __webpack_require__(55302); + new TerserPlugin({ + terserOptions: { + compress: { + passes: 2 + } + } + }).apply(compiler); + } + } + ]); + F(optimization, "nodeEnv", () => { + if (production) return "production"; + if (development) return "development"; + return false; + }); + const { splitChunks } = optimization; + if (splitChunks) { + A(splitChunks, "defaultSizeTypes", () => + css ? ["javascript", "css", "unknown"] : ["javascript", "unknown"] + ); + D(splitChunks, "hidePathInfo", production); + D(splitChunks, "chunks", "async"); + D(splitChunks, "usedExports", optimization.usedExports === true); + D(splitChunks, "minChunks", 1); + F(splitChunks, "minSize", () => (production ? 20000 : 10000)); + F(splitChunks, "minRemainingSize", () => (development ? 0 : undefined)); + F(splitChunks, "enforceSizeThreshold", () => (production ? 50000 : 30000)); + F(splitChunks, "maxAsyncRequests", () => (production ? 30 : Infinity)); + F(splitChunks, "maxInitialRequests", () => (production ? 30 : Infinity)); + D(splitChunks, "automaticNameDelimiter", "-"); + const { cacheGroups } = splitChunks; + F(cacheGroups, "default", () => ({ + idHint: "", + reuseExistingChunk: true, + minChunks: 2, + priority: -20 + })); + F(cacheGroups, "defaultVendors", () => ({ + idHint: "vendors", + reuseExistingChunk: true, + test: NODE_MODULES_REGEXP, + priority: -10 + })); } -} - -makeSerializable( - ModuleHotAcceptDependency, - "webpack/lib/dependencies/ModuleHotAcceptDependency" -); - -ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId; - -module.exports = ModuleHotAcceptDependency; - - -/***/ }), +}; -/***/ 86301: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @param {Object} options options + * @param {boolean} options.cache is cache enable + * @param {string} options.context build context + * @param {TargetProperties | false} options.targetProperties target properties + * @param {Mode} options.mode mode + * @returns {ResolveOptions} resolve options + */ +const getResolveDefaults = ({ cache, context, targetProperties, mode }) => { + /** @type {string[]} */ + const conditions = ["webpack"]; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + conditions.push(mode === "development" ? "development" : "production"); + if (targetProperties) { + if (targetProperties.webworker) conditions.push("worker"); + if (targetProperties.node) conditions.push("node"); + if (targetProperties.web) conditions.push("browser"); + if (targetProperties.electron) conditions.push("electron"); + if (targetProperties.nwjs) conditions.push("nwjs"); + } + const jsExtensions = [".js", ".json", ".wasm"]; -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyTemplateAsId = __webpack_require__(80825); + const tp = targetProperties; + const browserField = + tp && tp.web && (!tp.node || (tp.electron && tp.electronRenderer)); -class ModuleHotDeclineDependency extends ModuleDependency { - constructor(request, range) { - super(request); + /** @type {function(): ResolveOptions} */ + const cjsDeps = () => ({ + aliasFields: browserField ? ["browser"] : [], + mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."], + conditionNames: ["require", "module", "..."], + extensions: [...jsExtensions] + }); + /** @type {function(): ResolveOptions} */ + const esmDeps = () => ({ + aliasFields: browserField ? ["browser"] : [], + mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."], + conditionNames: ["import", "module", "..."], + extensions: [...jsExtensions] + }); - this.range = range; - this.weak = true; - } + /** @type {ResolveOptions} */ + const resolveOptions = { + cache, + modules: ["node_modules"], + conditionNames: conditions, + mainFiles: ["index"], + extensions: [], + aliasFields: [], + exportsFields: ["exports"], + roots: [context], + mainFields: ["main"], + byDependency: { + wasm: esmDeps(), + esm: esmDeps(), + loaderImport: esmDeps(), + url: { + preferRelative: true + }, + worker: { + ...esmDeps(), + preferRelative: true + }, + commonjs: cjsDeps(), + amd: cjsDeps(), + // for backward-compat: loadModule + loader: cjsDeps(), + // for backward-compat: Custom Dependency + unknown: cjsDeps(), + // for backward-compat: getResolve without dependencyType + undefined: cjsDeps() + } + }; - get type() { - return "module.hot.decline"; - } + return resolveOptions; +}; - get category() { - return "commonjs"; - } -} +/** + * @param {Object} options options + * @param {boolean} options.cache is cache enable + * @returns {ResolveOptions} resolve options + */ +const getResolveLoaderDefaults = ({ cache }) => { + /** @type {ResolveOptions} */ + const resolveOptions = { + cache, + conditionNames: ["loader", "require", "node"], + exportsFields: ["exports"], + mainFields: ["loader", "main"], + extensions: [".js"], + mainFiles: ["index"] + }; -makeSerializable( - ModuleHotDeclineDependency, - "webpack/lib/dependencies/ModuleHotDeclineDependency" -); + return resolveOptions; +}; -ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId; +/** + * @param {InfrastructureLogging} infrastructureLogging options + * @returns {void} + */ +const applyInfrastructureLoggingDefaults = infrastructureLogging => { + F(infrastructureLogging, "stream", () => process.stderr); + const tty = + /** @type {any} */ (infrastructureLogging.stream).isTTY && + process.env.TERM !== "dumb"; + D(infrastructureLogging, "level", "info"); + D(infrastructureLogging, "debug", false); + D(infrastructureLogging, "colors", tty); + D(infrastructureLogging, "appendOnly", !tty); +}; -module.exports = ModuleHotDeclineDependency; +exports.applyWebpackOptionsBaseDefaults = applyWebpackOptionsBaseDefaults; +exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults; /***/ }), -/***/ 31830: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 26693: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -81893,1286 +78095,1592 @@ module.exports = ModuleHotDeclineDependency; -const Dependency = __webpack_require__(54912); -const DependencyTemplate = __webpack_require__(5160); +const util = __webpack_require__(73837); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../../declarations/WebpackOptions").EntryStatic} EntryStatic */ +/** @typedef {import("../../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunk} OptimizationRuntimeChunk */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunkNormalized} OptimizationRuntimeChunkNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */ -class NullDependency extends Dependency { - get type() { - return "null"; - } +const handledDeprecatedNoEmitOnErrors = util.deprecate( + (noEmitOnErrors, emitOnErrors) => { + if (emitOnErrors !== undefined && !noEmitOnErrors === !emitOnErrors) { + throw new Error( + "Conflicting use of 'optimization.noEmitOnErrors' and 'optimization.emitOnErrors'. Remove deprecated 'optimization.noEmitOnErrors' from config." + ); + } + return !noEmitOnErrors; + }, + "optimization.noEmitOnErrors is deprecated in favor of optimization.emitOnErrors", + "DEP_WEBPACK_CONFIGURATION_OPTIMIZATION_NO_EMIT_ON_ERRORS" +); - /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module - */ - couldAffectReferencingModule() { - return false; - } -} +/** + * @template T + * @template R + * @param {T|undefined} value value or not + * @param {function(T): R} fn nested handler + * @returns {R} result value + */ +const nestedConfig = (value, fn) => + value === undefined ? fn(/** @type {T} */ ({})) : fn(value); -NullDependency.Template = class NullDependencyTemplate extends ( - DependencyTemplate -) { - /** - * @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) {} +/** + * @template T + * @param {T|undefined} value value or not + * @returns {T} result value + */ +const cloneObject = value => { + return /** @type {T} */ ({ ...value }); }; -module.exports = NullDependency; - - -/***/ }), - -/***/ 31618: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @template T + * @template R + * @param {T|undefined} value value or not + * @param {function(T): R} fn nested handler + * @returns {R|undefined} result value + */ +const optionalNestedConfig = (value, fn) => + value === undefined ? undefined : fn(value); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @template T + * @template R + * @param {T[]|undefined} value array or not + * @param {function(T[]): R[]} fn nested handler + * @returns {R[]|undefined} cloned value + */ +const nestedArray = (value, fn) => (Array.isArray(value) ? fn(value) : fn([])); +/** + * @template T + * @template R + * @param {T[]|undefined} value array or not + * @param {function(T[]): R[]} fn nested handler + * @returns {R[]|undefined} cloned value + */ +const optionalNestedArray = (value, fn) => + Array.isArray(value) ? fn(value) : undefined; +/** + * @template T + * @template R + * @param {Record|undefined} value value or not + * @param {function(T): R} fn nested handler + * @param {Record=} customKeys custom nested handler for some keys + * @returns {Record} result value + */ +const keyedNestedConfig = (value, fn, customKeys) => { + const result = + value === undefined + ? {} + : Object.keys(value).reduce( + (obj, key) => ( + (obj[key] = ( + customKeys && key in customKeys ? customKeys[key] : fn + )(value[key])), + obj + ), + /** @type {Record} */ ({}) + ); + if (customKeys) { + for (const key of Object.keys(customKeys)) { + if (!(key in result)) { + result[key] = customKeys[key](/** @type {T} */ ({})); + } + } + } + return result; +}; -const ModuleDependency = __webpack_require__(80321); +/** + * @param {WebpackOptions} config input config + * @returns {WebpackOptionsNormalized} normalized options + */ +const getNormalizedWebpackOptions = config => { + return { + amd: config.amd, + bail: config.bail, + cache: optionalNestedConfig(config.cache, cache => { + if (cache === false) return false; + if (cache === true) { + return { + type: "memory", + maxGenerations: undefined + }; + } + switch (cache.type) { + case "filesystem": + return { + type: "filesystem", + allowCollectingMemory: cache.allowCollectingMemory, + maxMemoryGenerations: cache.maxMemoryGenerations, + maxAge: cache.maxAge, + profile: cache.profile, + buildDependencies: cloneObject(cache.buildDependencies), + cacheDirectory: cache.cacheDirectory, + cacheLocation: cache.cacheLocation, + hashAlgorithm: cache.hashAlgorithm, + compression: cache.compression, + idleTimeout: cache.idleTimeout, + idleTimeoutForInitialStore: cache.idleTimeoutForInitialStore, + idleTimeoutAfterLargeChanges: cache.idleTimeoutAfterLargeChanges, + name: cache.name, + store: cache.store, + version: cache.version + }; + case undefined: + case "memory": + return { + type: "memory", + maxGenerations: cache.maxGenerations + }; + default: + // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339) + throw new Error(`Not implemented cache.type ${cache.type}`); + } + }), + context: config.context, + dependencies: config.dependencies, + devServer: optionalNestedConfig(config.devServer, devServer => ({ + ...devServer + })), + devtool: config.devtool, + entry: + config.entry === undefined + ? { main: {} } + : typeof config.entry === "function" + ? ( + fn => () => + Promise.resolve().then(fn).then(getNormalizedEntryStatic) + )(config.entry) + : getNormalizedEntryStatic(config.entry), + experiments: nestedConfig(config.experiments, experiments => ({ + ...experiments, + buildHttp: optionalNestedConfig(experiments.buildHttp, options => + Array.isArray(options) ? { allowedUris: options } : options + ), + lazyCompilation: optionalNestedConfig( + experiments.lazyCompilation, + options => + options === true ? {} : options === false ? undefined : options + ), + css: optionalNestedConfig(experiments.css, options => + options === true ? {} : options === false ? undefined : options + ) + })), + externals: config.externals, + externalsPresets: cloneObject(config.externalsPresets), + externalsType: config.externalsType, + ignoreWarnings: config.ignoreWarnings + ? config.ignoreWarnings.map(ignore => { + if (typeof ignore === "function") return ignore; + const i = ignore instanceof RegExp ? { message: ignore } : ignore; + return (warning, { requestShortener }) => { + if (!i.message && !i.module && !i.file) return false; + if (i.message && !i.message.test(warning.message)) { + return false; + } + if ( + i.module && + (!warning.module || + !i.module.test( + warning.module.readableIdentifier(requestShortener) + )) + ) { + return false; + } + if (i.file && (!warning.file || !i.file.test(warning.file))) { + return false; + } + return true; + }; + }) + : undefined, + infrastructureLogging: cloneObject(config.infrastructureLogging), + loader: cloneObject(config.loader), + mode: config.mode, + module: nestedConfig(config.module, module => ({ + noParse: module.noParse, + unsafeCache: module.unsafeCache, + parser: keyedNestedConfig(module.parser, cloneObject, { + javascript: parserOptions => ({ + unknownContextRequest: module.unknownContextRequest, + unknownContextRegExp: module.unknownContextRegExp, + unknownContextRecursive: module.unknownContextRecursive, + unknownContextCritical: module.unknownContextCritical, + exprContextRequest: module.exprContextRequest, + exprContextRegExp: module.exprContextRegExp, + exprContextRecursive: module.exprContextRecursive, + exprContextCritical: module.exprContextCritical, + wrappedContextRegExp: module.wrappedContextRegExp, + wrappedContextRecursive: module.wrappedContextRecursive, + wrappedContextCritical: module.wrappedContextCritical, + // TODO webpack 6 remove + strictExportPresence: module.strictExportPresence, + strictThisContextOnImports: module.strictThisContextOnImports, + ...parserOptions + }) + }), + generator: cloneObject(module.generator), + defaultRules: optionalNestedArray(module.defaultRules, r => [...r]), + rules: nestedArray(module.rules, r => [...r]) + })), + name: config.name, + node: nestedConfig( + config.node, + node => + node && { + ...node + } + ), + optimization: nestedConfig(config.optimization, optimization => { + return { + ...optimization, + runtimeChunk: getNormalizedOptimizationRuntimeChunk( + optimization.runtimeChunk + ), + splitChunks: nestedConfig( + optimization.splitChunks, + splitChunks => + splitChunks && { + ...splitChunks, + defaultSizeTypes: splitChunks.defaultSizeTypes + ? [...splitChunks.defaultSizeTypes] + : ["..."], + cacheGroups: cloneObject(splitChunks.cacheGroups) + } + ), + emitOnErrors: + optimization.noEmitOnErrors !== undefined + ? handledDeprecatedNoEmitOnErrors( + optimization.noEmitOnErrors, + optimization.emitOnErrors + ) + : optimization.emitOnErrors + }; + }), + output: nestedConfig(config.output, output => { + const { library } = output; + const libraryAsName = /** @type {LibraryName} */ (library); + const libraryBase = + typeof library === "object" && + library && + !Array.isArray(library) && + "type" in library + ? library + : libraryAsName || output.libraryTarget + ? /** @type {LibraryOptions} */ ({ + name: libraryAsName + }) + : undefined; + /** @type {OutputNormalized} */ + const result = { + assetModuleFilename: output.assetModuleFilename, + asyncChunks: output.asyncChunks, + charset: output.charset, + chunkFilename: output.chunkFilename, + chunkFormat: output.chunkFormat, + chunkLoading: output.chunkLoading, + chunkLoadingGlobal: output.chunkLoadingGlobal, + chunkLoadTimeout: output.chunkLoadTimeout, + cssFilename: output.cssFilename, + cssChunkFilename: output.cssChunkFilename, + clean: output.clean, + compareBeforeEmit: output.compareBeforeEmit, + crossOriginLoading: output.crossOriginLoading, + devtoolFallbackModuleFilenameTemplate: + output.devtoolFallbackModuleFilenameTemplate, + devtoolModuleFilenameTemplate: output.devtoolModuleFilenameTemplate, + devtoolNamespace: output.devtoolNamespace, + environment: cloneObject(output.environment), + enabledChunkLoadingTypes: output.enabledChunkLoadingTypes + ? [...output.enabledChunkLoadingTypes] + : ["..."], + enabledLibraryTypes: output.enabledLibraryTypes + ? [...output.enabledLibraryTypes] + : ["..."], + enabledWasmLoadingTypes: output.enabledWasmLoadingTypes + ? [...output.enabledWasmLoadingTypes] + : ["..."], + filename: output.filename, + globalObject: output.globalObject, + hashDigest: output.hashDigest, + hashDigestLength: output.hashDigestLength, + hashFunction: output.hashFunction, + hashSalt: output.hashSalt, + hotUpdateChunkFilename: output.hotUpdateChunkFilename, + hotUpdateGlobal: output.hotUpdateGlobal, + hotUpdateMainFilename: output.hotUpdateMainFilename, + iife: output.iife, + importFunctionName: output.importFunctionName, + importMetaName: output.importMetaName, + scriptType: output.scriptType, + library: libraryBase && { + type: + output.libraryTarget !== undefined + ? output.libraryTarget + : libraryBase.type, + auxiliaryComment: + output.auxiliaryComment !== undefined + ? output.auxiliaryComment + : libraryBase.auxiliaryComment, + export: + output.libraryExport !== undefined + ? output.libraryExport + : libraryBase.export, + name: libraryBase.name, + umdNamedDefine: + output.umdNamedDefine !== undefined + ? output.umdNamedDefine + : libraryBase.umdNamedDefine + }, + module: output.module, + path: output.path, + pathinfo: output.pathinfo, + publicPath: output.publicPath, + sourceMapFilename: output.sourceMapFilename, + sourcePrefix: output.sourcePrefix, + strictModuleExceptionHandling: output.strictModuleExceptionHandling, + trustedTypes: optionalNestedConfig( + output.trustedTypes, + trustedTypes => { + if (trustedTypes === true) return {}; + if (typeof trustedTypes === "string") + return { policyName: trustedTypes }; + return { ...trustedTypes }; + } + ), + uniqueName: output.uniqueName, + wasmLoading: output.wasmLoading, + webassemblyModuleFilename: output.webassemblyModuleFilename, + workerChunkLoading: output.workerChunkLoading, + workerWasmLoading: output.workerWasmLoading + }; + return result; + }), + parallelism: config.parallelism, + performance: optionalNestedConfig(config.performance, performance => { + if (performance === false) return false; + return { + ...performance + }; + }), + plugins: nestedArray(config.plugins, p => [...p]), + profile: config.profile, + recordsInputPath: + config.recordsInputPath !== undefined + ? config.recordsInputPath + : config.recordsPath, + recordsOutputPath: + config.recordsOutputPath !== undefined + ? config.recordsOutputPath + : config.recordsPath, + resolve: nestedConfig(config.resolve, resolve => ({ + ...resolve, + byDependency: keyedNestedConfig(resolve.byDependency, cloneObject) + })), + resolveLoader: cloneObject(config.resolveLoader), + snapshot: nestedConfig(config.snapshot, snapshot => ({ + resolveBuildDependencies: optionalNestedConfig( + snapshot.resolveBuildDependencies, + resolveBuildDependencies => ({ + timestamp: resolveBuildDependencies.timestamp, + hash: resolveBuildDependencies.hash + }) + ), + buildDependencies: optionalNestedConfig( + snapshot.buildDependencies, + buildDependencies => ({ + timestamp: buildDependencies.timestamp, + hash: buildDependencies.hash + }) + ), + resolve: optionalNestedConfig(snapshot.resolve, resolve => ({ + timestamp: resolve.timestamp, + hash: resolve.hash + })), + module: optionalNestedConfig(snapshot.module, module => ({ + timestamp: module.timestamp, + hash: module.hash + })), + immutablePaths: optionalNestedArray(snapshot.immutablePaths, p => [...p]), + managedPaths: optionalNestedArray(snapshot.managedPaths, p => [...p]) + })), + stats: nestedConfig(config.stats, stats => { + if (stats === false) { + return { + preset: "none" + }; + } + if (stats === true) { + return { + preset: "normal" + }; + } + if (typeof stats === "string") { + return { + preset: stats + }; + } + return { + ...stats + }; + }), + target: config.target, + watch: config.watch, + watchOptions: cloneObject(config.watchOptions) + }; +}; -class PrefetchDependency extends ModuleDependency { - constructor(request) { - super(request); +/** + * @param {EntryStatic} entry static entry options + * @returns {EntryStaticNormalized} normalized static entry options + */ +const getNormalizedEntryStatic = entry => { + if (typeof entry === "string") { + return { + main: { + import: [entry] + } + }; } - - get type() { - return "prefetch"; + if (Array.isArray(entry)) { + return { + main: { + import: entry + } + }; + } + /** @type {EntryStaticNormalized} */ + const result = {}; + for (const key of Object.keys(entry)) { + const value = entry[key]; + if (typeof value === "string") { + result[key] = { + import: [value] + }; + } else if (Array.isArray(value)) { + result[key] = { + import: value + }; + } else { + result[key] = { + import: + value.import && + (Array.isArray(value.import) ? value.import : [value.import]), + filename: value.filename, + layer: value.layer, + runtime: value.runtime, + publicPath: value.publicPath, + chunkLoading: value.chunkLoading, + asyncChunks: value.asyncChunks, + wasmLoading: value.wasmLoading, + dependOn: + value.dependOn && + (Array.isArray(value.dependOn) ? value.dependOn : [value.dependOn]), + library: value.library + }; + } } + return result; +}; - get category() { - return "esm"; +/** + * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option + * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option + */ +const getNormalizedOptimizationRuntimeChunk = runtimeChunk => { + if (runtimeChunk === undefined) return undefined; + if (runtimeChunk === false) return false; + if (runtimeChunk === "single") { + return { + name: () => "runtime" + }; } -} + if (runtimeChunk === true || runtimeChunk === "multiple") { + return { + name: entrypoint => `runtime~${entrypoint.name}` + }; + } + const { name } = runtimeChunk; + return { + name: typeof name === "function" ? name : () => name + }; +}; -module.exports = PrefetchDependency; +exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions; /***/ }), -/***/ 95770: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 52801: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent + Author Tobias Koppers @sokra */ -const InitFragment = __webpack_require__(55870); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); +const memoize = __webpack_require__(78676); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../util/Hash")} Hash */ +const getBrowserslistTargetHandler = memoize(() => + __webpack_require__(43950) +); /** - * @param {string[]|null} path the property path array - * @returns {string} the converted path + * @param {string} context the context directory + * @returns {string} default target */ -const pathToString = path => - path !== null && path.length > 0 - ? path.map(part => `[${JSON.stringify(part)}]`).join("") - : ""; - -class ProvidedDependency extends ModuleDependency { - constructor(request, identifier, path, range) { - super(request); - this.identifier = identifier; - this.path = path; - this.range = range; - this._hashUpdate = undefined; - } +const getDefaultTarget = context => { + const browsers = getBrowserslistTargetHandler().load(null, context); + return browsers ? "browserslist" : "web"; +}; - get type() { - return "provided"; - } +/** + * @typedef {Object} PlatformTargetProperties + * @property {boolean | null} web web platform, importing of http(s) and std: is available + * @property {boolean | null} browser browser platform, running in a normal web browser + * @property {boolean | null} webworker (Web)Worker platform, running in a web/shared/service worker + * @property {boolean | null} node node platform, require of node built-in modules is available + * @property {boolean | null} nwjs nwjs platform, require of legacy nw.gui is available + * @property {boolean | null} electron electron platform, require of some electron built-in modules is available + */ - get category() { - return "esm"; - } +/** + * @typedef {Object} ElectronContextTargetProperties + * @property {boolean | null} electronMain in main context + * @property {boolean | null} electronPreload in preload context + * @property {boolean | null} electronRenderer in renderer context with node integration + */ - /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) { - this._hashUpdate = - this.identifier + (this.path ? this.path.join(",") : "null"); - } - hash.update(this._hashUpdate); - } +/** + * @typedef {Object} ApiTargetProperties + * @property {boolean | null} require has require function available + * @property {boolean | null} nodeBuiltins has node.js built-in modules available + * @property {boolean | null} document has document available (allows script tags) + * @property {boolean | null} importScripts has importScripts available + * @property {boolean | null} importScriptsInWorker has importScripts available when creating a worker + * @property {boolean | null} fetchWasm has fetch function available for WebAssembly + * @property {boolean | null} global has global variable available + */ - serialize(context) { - const { write } = context; - write(this.identifier); - write(this.path); - super.serialize(context); - } +/** + * @typedef {Object} EcmaTargetProperties + * @property {boolean | null} globalThis has globalThis variable available + * @property {boolean | null} bigIntLiteral big int literal syntax is available + * @property {boolean | null} const const and let variable declarations are available + * @property {boolean | null} arrowFunction arrow functions are available + * @property {boolean | null} forOf for of iteration is available + * @property {boolean | null} destructuring destructuring is available + * @property {boolean | null} dynamicImport async import() is available + * @property {boolean | null} dynamicImportInWorker async import() is available when creating a worker + * @property {boolean | null} module ESM syntax is available (when in module) + * @property {boolean | null} optionalChaining optional chaining is available + * @property {boolean | null} templateLiteral template literal is available + */ - deserialize(context) { - const { read } = context; - this.identifier = read(); - this.path = read(); - super.deserialize(context); - } -} +///** @typedef {PlatformTargetProperties | ApiTargetProperties | EcmaTargetProperties | PlatformTargetProperties & ApiTargetProperties | PlatformTargetProperties & EcmaTargetProperties | ApiTargetProperties & EcmaTargetProperties} TargetProperties */ +/** @template T @typedef {{ [P in keyof T]?: never }} Never */ +/** @template A @template B @typedef {(A & Never) | (Never & B) | (A & B)} Mix */ +/** @typedef {Mix, Mix>} TargetProperties */ -makeSerializable( - ProvidedDependency, - "webpack/lib/dependencies/ProvidedDependency" -); +const versionDependent = (major, minor) => { + if (!major) return () => /** @type {undefined} */ (undefined); + major = +major; + minor = minor ? +minor : 0; + return (vMajor, vMinor = 0) => { + return major > vMajor || (major === vMajor && minor >= vMinor); + }; +}; -class ProvidedDependencyTemplate extends ModuleDependency.Template { - /** - * @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, - { - runtimeTemplate, - moduleGraph, - chunkGraph, - initFragments, - runtimeRequirements +/** @type {[string, string, RegExp, (...args: string[]) => TargetProperties | false][]} */ +const TARGETS = [ + [ + "browserslist / browserslist:env / browserslist:query / browserslist:path-to-config / browserslist:path-to-config:env", + "Resolve features from browserslist. Will resolve browserslist config automatically. Only browser or node queries are supported (electron is not supported). Examples: 'browserslist:modern' to use 'modern' environment from browserslist config", + /^browserslist(?::(.+))?$/, + (rest, context) => { + const browserslistTargetHandler = getBrowserslistTargetHandler(); + const browsers = browserslistTargetHandler.load( + rest ? rest.trim() : null, + context + ); + if (!browsers) { + throw new Error(`No browserslist config found to handle the 'browserslist' target. +See https://github.com/browserslist/browserslist#queries for possible ways to provide a config. +The recommended way is to add a 'browserslist' key to your package.json and list supported browsers (resp. node.js versions). +You can also more options via the 'target' option: 'browserslist' / 'browserslist:env' / 'browserslist:query' / 'browserslist:path-to-config' / 'browserslist:path-to-config:env'`); + } + return browserslistTargetHandler.resolve(browsers); } - ) { - const dep = /** @type {ProvidedDependency} */ (dependency); - initFragments.push( - new InitFragment( - `/* provided dependency */ var ${ - dep.identifier - } = ${runtimeTemplate.moduleExports({ - module: moduleGraph.getModule(dep), - chunkGraph, - request: dep.request, - runtimeRequirements - })}${pathToString(dep.path)};\n`, - InitFragment.STAGE_PROVIDES, - 1, - `provided ${dep.identifier}` - ) - ); - source.replace(dep.range[0], dep.range[1] - 1, dep.identifier); - } -} - -ProvidedDependency.Template = ProvidedDependencyTemplate; - -module.exports = ProvidedDependency; - + ], + [ + "web", + "Web browser.", + /^web$/, + () => { + return { + web: true, + browser: true, + webworker: null, + node: false, + electron: false, + nwjs: false, -/***/ }), + document: true, + importScriptsInWorker: true, + fetchWasm: true, + nodeBuiltins: false, + importScripts: false, + require: false, + global: false + }; + } + ], + [ + "webworker", + "Web Worker, SharedWorker or Service Worker.", + /^webworker$/, + () => { + return { + web: true, + browser: true, + webworker: true, + node: false, + electron: false, + nwjs: false, -/***/ 55799: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + importScripts: true, + importScriptsInWorker: true, + fetchWasm: true, + nodeBuiltins: false, + require: false, + document: false, + global: false + }; + } + ], + [ + "[async-]node[X[.Y]]", + "Node.js in version X.Y. The 'async-' prefix will load chunks asynchronously via 'fs' and 'vm' instead of 'require()'. Examples: node14.5, async-node10.", + /^(async-)?node(\d+(?:\.(\d+))?)?$/, + (asyncFlag, major, minor) => { + const v = versionDependent(major, minor); + // see https://node.green/ + return { + node: true, + electron: false, + nwjs: false, + web: false, + webworker: false, + browser: false, -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + require: !asyncFlag, + nodeBuiltins: true, + global: true, + document: false, + fetchWasm: false, + importScripts: false, + importScriptsInWorker: false, + globalThis: v(12), + const: v(6), + templateLiteral: v(4), + optionalChaining: v(14), + arrowFunction: v(6), + forOf: v(5), + destructuring: v(6), + bigIntLiteral: v(10, 4), + dynamicImport: v(12, 17), + dynamicImportInWorker: major ? false : undefined, + module: v(12, 17) + }; + } + ], + [ + "electron[X[.Y]]-main/preload/renderer", + "Electron in version X.Y. Script is running in main, preload resp. renderer context.", + /^electron(\d+(?:\.(\d+))?)?-(main|preload|renderer)$/, + (major, minor, context) => { + const v = versionDependent(major, minor); + // see https://node.green/ + https://github.com/electron/releases + return { + node: true, + electron: true, + web: context !== "main", + webworker: false, + browser: false, + nwjs: false, + electronMain: context === "main", + electronPreload: context === "preload", + electronRenderer: context === "renderer", -const { UsageState } = __webpack_require__(63686); -const makeSerializable = __webpack_require__(33032); -const { filterRuntime } = __webpack_require__(17156); -const NullDependency = __webpack_require__(31830); + global: true, + nodeBuiltins: true, + require: true, + document: context === "renderer", + fetchWasm: context === "renderer", + importScripts: false, + importScriptsInWorker: true, -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../util/Hash")} Hash */ + globalThis: v(5), + const: v(1, 1), + templateLiteral: v(1, 1), + optionalChaining: v(8), + arrowFunction: v(1, 1), + forOf: v(0, 36), + destructuring: v(1, 1), + bigIntLiteral: v(4), + dynamicImport: v(11), + dynamicImportInWorker: major ? false : undefined, + module: v(11) + }; + } + ], + [ + "nwjs[X[.Y]] / node-webkit[X[.Y]]", + "NW.js in version X.Y.", + /^(?:nwjs|node-webkit)(\d+(?:\.(\d+))?)?$/, + (major, minor) => { + const v = versionDependent(major, minor); + // see https://node.green/ + https://github.com/nwjs/nw.js/blob/nw48/CHANGELOG.md + return { + node: true, + web: true, + nwjs: true, + webworker: null, + browser: false, + electron: false, -class PureExpressionDependency extends NullDependency { - /** - * @param {[number, number]} range the source range - */ - constructor(range) { - super(); - this.range = range; - /** @type {Set | false} */ - this.usedByExports = false; - this._hashUpdate = undefined; - } + global: true, + nodeBuiltins: true, + document: false, + importScriptsInWorker: false, + fetchWasm: false, + importScripts: false, + require: false, - /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) { - this._hashUpdate = this.range + ""; + globalThis: v(0, 43), + const: v(0, 15), + templateLiteral: v(0, 13), + optionalChaining: v(0, 44), + arrowFunction: v(0, 15), + forOf: v(0, 13), + destructuring: v(0, 15), + bigIntLiteral: v(0, 32), + dynamicImport: v(0, 43), + dynamicImportInWorker: major ? false : undefined, + module: v(0, 43) + }; } - hash.update(this._hashUpdate); - } - - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules - */ - getModuleEvaluationSideEffectsState(moduleGraph) { - return false; - } + ], + [ + "esX", + "EcmaScript in this version. Examples: es2020, es5.", + /^es(\d+)$/, + version => { + let v = +version; + if (v < 1000) v = v + 2009; + return { + const: v >= 2015, + templateLiteral: v >= 2015, + optionalChaining: v >= 2020, + arrowFunction: v >= 2015, + forOf: v >= 2015, + destructuring: v >= 2015, + module: v >= 2015, + globalThis: v >= 2020, + bigIntLiteral: v >= 2020, + dynamicImport: v >= 2020, + dynamicImportInWorker: v >= 2020 + }; + } + ] +]; - serialize(context) { - const { write } = context; - write(this.range); - write(this.usedByExports); - super.serialize(context); +/** + * @param {string} target the target + * @param {string} context the context directory + * @returns {TargetProperties} target properties + */ +const getTargetProperties = (target, context) => { + for (const [, , regExp, handler] of TARGETS) { + const match = regExp.exec(target); + if (match) { + const [, ...args] = match; + const result = handler(...args, context); + if (result) return result; + } } + throw new Error( + `Unknown target '${target}'. The following targets are supported:\n${TARGETS.map( + ([name, description]) => `* ${name}: ${description}` + ).join("\n")}` + ); +}; - deserialize(context) { - const { read } = context; - this.range = read(); - this.usedByExports = read(); - super.deserialize(context); +const mergeTargetProperties = targetProperties => { + const keys = new Set(); + for (const tp of targetProperties) { + for (const key of Object.keys(tp)) { + keys.add(key); + } } -} - -makeSerializable( - PureExpressionDependency, - "webpack/lib/dependencies/PureExpressionDependency" -); - -PureExpressionDependency.Template = class PureExpressionDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, - { chunkGraph, moduleGraph, runtime, runtimeTemplate, runtimeRequirements } - ) { - const dep = /** @type {PureExpressionDependency} */ (dependency); - - const usedByExports = dep.usedByExports; - if (usedByExports !== false) { - const selfModule = moduleGraph.getParentModule(dep); - const exportsInfo = moduleGraph.getExportsInfo(selfModule); - const runtimeCondition = filterRuntime(runtime, runtime => { - for (const exportName of usedByExports) { - if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) { - return true; - } - } - return false; - }); - if (runtimeCondition === true) return; - if (runtimeCondition !== false) { - const condition = runtimeTemplate.runtimeConditionExpression({ - chunkGraph, - runtime, - runtimeCondition, - runtimeRequirements - }); - source.insert( - dep.range[0], - `(/* runtime-dependent pure expression or super */ ${condition} ? (` - ); - source.insert(dep.range[1], ") : null)"); - return; + const result = {}; + for (const key of keys) { + let hasTrue = false; + let hasFalse = false; + for (const tp of targetProperties) { + const value = tp[key]; + switch (value) { + case true: + hasTrue = true; + break; + case false: + hasFalse = true; + break; } } - - source.insert( - dep.range[0], - `(/* unused pure expression or super */ null && (` - ); - source.insert(dep.range[1], "))"); + if (hasTrue || hasFalse) + result[key] = hasFalse && hasTrue ? null : hasTrue ? true : false; } + return /** @type {TargetProperties} */ (result); }; -module.exports = PureExpressionDependency; +/** + * @param {string[]} targets the targets + * @param {string} context the context directory + * @returns {TargetProperties} target properties + */ +const getTargetsProperties = (targets, context) => { + return mergeTargetProperties( + targets.map(t => getTargetProperties(t, context)) + ); +}; + +exports.getDefaultTarget = getDefaultTarget; +exports.getTargetProperties = getTargetProperties; +exports.getTargetsProperties = getTargetsProperties; /***/ }), -/***/ 46917: +/***/ 64813: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr */ +const Dependency = __webpack_require__(54912); const makeSerializable = __webpack_require__(33032); -const ContextDependency = __webpack_require__(88101); -const ModuleDependencyTemplateAsRequireId = __webpack_require__(36873); -class RequireContextDependency extends ContextDependency { - constructor(options, range) { - super(options); +/** @typedef {import("./ContainerEntryModule").ExposeOptions} ExposeOptions */ - this.range = range; +class ContainerEntryDependency extends Dependency { + /** + * @param {string} name entry name + * @param {[string, ExposeOptions][]} exposes list of exposed modules + * @param {string} shareScope name of the share scope + */ + constructor(name, exposes, shareScope) { + super(); + this.name = name; + this.exposes = exposes; + this.shareScope = shareScope; } - get type() { - return "require.context"; + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return `container-entry-${this.name}`; } - serialize(context) { - const { write } = context; - - write(this.range); - - super.serialize(context); + get type() { + return "container entry"; } - deserialize(context) { - const { read } = context; - - this.range = read(); - - super.deserialize(context); + get category() { + return "esm"; } } makeSerializable( - RequireContextDependency, - "webpack/lib/dependencies/RequireContextDependency" + ContainerEntryDependency, + "webpack/lib/container/ContainerEntryDependency" ); -RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; - -module.exports = RequireContextDependency; +module.exports = ContainerEntryDependency; /***/ }), -/***/ 18851: +/***/ 80580: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr */ -const RequireContextDependency = __webpack_require__(46917); - -module.exports = class RequireContextDependencyParserPlugin { - apply(parser) { - parser.hooks.call - .for("require.context") - .tap("RequireContextDependencyParserPlugin", expr => { - let regExp = /^\.\/.*$/; - let recursive = true; - let mode = "sync"; - switch (expr.arguments.length) { - case 4: { - const modeExpr = parser.evaluateExpression(expr.arguments[3]); - if (!modeExpr.isString()) return; - mode = modeExpr.string; - } - // falls through - case 3: { - const regExpExpr = parser.evaluateExpression(expr.arguments[2]); - if (!regExpExpr.isRegExp()) return; - regExp = regExpExpr.regExp; - } - // falls through - case 2: { - const recursiveExpr = parser.evaluateExpression(expr.arguments[1]); - if (!recursiveExpr.isBoolean()) return; - recursive = recursiveExpr.bool; - } - // falls through - case 1: { - const requestExpr = parser.evaluateExpression(expr.arguments[0]); - if (!requestExpr.isString()) return; - const dep = new RequireContextDependency( - { - request: requestExpr.string, - recursive, - regExp, - mode, - category: "commonjs" - }, - expr.range - ); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - } - }); - } -}; - +const { OriginalSource, RawSource } = __webpack_require__(51255); +const AsyncDependenciesBlock = __webpack_require__(47736); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const StaticExportsDependency = __webpack_require__(91418); +const makeSerializable = __webpack_require__(33032); +const ContainerExposedDependency = __webpack_require__(72374); -/***/ }), +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */ -/***/ 2928: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @typedef {Object} ExposeOptions + * @property {string[]} import requests to exposed modules (last one is exported) + * @property {string} name custom chunk name for the exposed module + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const SOURCE_TYPES = new Set(["javascript"]); +class ContainerEntryModule extends Module { + /** + * @param {string} name container entry name + * @param {[string, ExposeOptions][]} exposes list of exposed modules + * @param {string} shareScope name of the share scope + */ + constructor(name, exposes, shareScope) { + super("javascript/dynamic", null); + this._name = name; + this._exposes = exposes; + this._shareScope = shareScope; + } + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return SOURCE_TYPES; + } -const { cachedSetProperty } = __webpack_require__(60839); -const ContextElementDependency = __webpack_require__(58477); -const RequireContextDependency = __webpack_require__(46917); -const RequireContextDependencyParserPlugin = __webpack_require__(18851); + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `container entry (${this._shareScope}) ${JSON.stringify( + this._exposes + )}`; + } -/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ -/** @typedef {import("../Compiler")} Compiler */ + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `container entry`; + } -/** @type {ResolveOptions} */ -const EMPTY_RESOLVE_OPTIONS = {}; + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `${this.layer ? `(${this.layer})/` : ""}webpack/container/entry/${ + this._name + }`; + } -class RequireContextPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild * @returns {void} */ - apply(compiler) { - compiler.hooks.compilation.tap( - "RequireContextPlugin", - (compilation, { contextModuleFactory, normalModuleFactory }) => { - compilation.dependencyFactories.set( - RequireContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - RequireContextDependency, - new RequireContextDependency.Template() - ); + needBuild(context, callback) { + return callback(null, !this.buildMeta); + } - compilation.dependencyFactories.set( - ContextElementDependency, - normalModuleFactory - ); + /** + * @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 = { + strict: true, + topLevelDeclarations: new Set(["moduleMap", "get", "init"]) + }; + this.buildMeta.exportsType = "namespace"; - const handler = (parser, parserOptions) => { - if ( - parserOptions.requireContext !== undefined && - !parserOptions.requireContext - ) - return; + this.clearDependenciesAndBlocks(); - new RequireContextDependencyParserPlugin().apply(parser); + for (const [name, options] of this._exposes) { + const block = new AsyncDependenciesBlock( + { + name: options.name + }, + { name }, + options.import[options.import.length - 1] + ); + let idx = 0; + for (const request of options.import) { + const dep = new ContainerExposedDependency(name, request); + dep.loc = { + name, + index: idx++ }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireContextPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireContextPlugin", handler); + block.addDependency(dep); + } + this.addBlock(block); + } + this.addDependency(new StaticExportsDependency(["get", "init"], false)); - contextModuleFactory.hooks.alternativeRequests.tap( - "RequireContextPlugin", - (items, options) => { - if (items.length === 0) return items; + callback(); + } - const finalResolveOptions = compiler.resolverFactory.get( - "normal", - cachedSetProperty( - options.resolveOptions || EMPTY_RESOLVE_OPTIONS, - "dependencyType", - options.category - ) - ).options; + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ moduleGraph, chunkGraph, runtimeTemplate }) { + const sources = new Map(); + const runtimeRequirements = new Set([ + RuntimeGlobals.definePropertyGetters, + RuntimeGlobals.hasOwnProperty, + RuntimeGlobals.exports + ]); + const getters = []; - let newItems; - if (!finalResolveOptions.fullySpecified) { - newItems = []; - for (const item of items) { - const { request, context } = item; - for (const ext of finalResolveOptions.extensions) { - if (request.endsWith(ext)) { - newItems.push({ - context, - request: request.slice(0, -ext.length) - }); - } - } - if (!finalResolveOptions.enforceExtension) { - newItems.push(item); - } - } - items = newItems; + for (const block of this.blocks) { + const { dependencies } = block; - newItems = []; - for (const obj of items) { - const { request, context } = obj; - for (const mainFile of finalResolveOptions.mainFiles) { - if (request.endsWith(`/${mainFile}`)) { - newItems.push({ - context, - request: request.slice(0, -mainFile.length) - }); - newItems.push({ - context, - request: request.slice(0, -mainFile.length - 1) - }); - } - } - newItems.push(obj); - } - items = newItems; - } + const modules = dependencies.map(dependency => { + const dep = /** @type {ContainerExposedDependency} */ (dependency); + return { + name: dep.exposedName, + module: moduleGraph.getModule(dep), + request: dep.userRequest + }; + }); - newItems = []; - for (const item of items) { - let hideOriginal = false; - for (const modulesItems of finalResolveOptions.modules) { - if (Array.isArray(modulesItems)) { - for (const dir of modulesItems) { - if (item.request.startsWith(`./${dir}/`)) { - newItems.push({ - context: item.context, - request: item.request.slice(dir.length + 3) - }); - hideOriginal = true; - } - } - } else { - const dir = modulesItems.replace(/\\/g, "/"); - const fullPath = - item.context.replace(/\\/g, "/") + item.request.slice(1); - if (fullPath.startsWith(dir)) { - newItems.push({ - context: item.context, - request: fullPath.slice(dir.length + 1) - }); - } - } - } - if (!hideOriginal) { - newItems.push(item); - } - } - return newItems; - } - ); - } - ); - } -} -module.exports = RequireContextPlugin; + let str; + if (modules.some(m => !m.module)) { + str = runtimeTemplate.throwMissingModuleErrorBlock({ + request: modules.map(m => m.request).join(", ") + }); + } else { + str = `return ${runtimeTemplate.blockPromise({ + block, + message: "", + chunkGraph, + runtimeRequirements + })}.then(${runtimeTemplate.returningFunction( + runtimeTemplate.returningFunction( + `(${modules + .map(({ module, request }) => + runtimeTemplate.moduleRaw({ + module, + chunkGraph, + request, + weak: false, + runtimeRequirements + }) + ) + .join(", ")})` + ) + )});`; + } -/***/ }), + getters.push( + `${JSON.stringify(modules[0].name)}: ${runtimeTemplate.basicFunction( + "", + str + )}` + ); + } -/***/ 27153: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const source = Template.asString([ + `var moduleMap = {`, + Template.indent(getters.join(",\n")), + "};", + `var get = ${runtimeTemplate.basicFunction("module, getScope", [ + `${RuntimeGlobals.currentRemoteGetScope} = getScope;`, + // reusing the getScope variable to avoid creating a new var (and module is also used later) + "getScope = (", + Template.indent([ + `${RuntimeGlobals.hasOwnProperty}(moduleMap, module)`, + Template.indent([ + "? moduleMap[module]()", + `: Promise.resolve().then(${runtimeTemplate.basicFunction( + "", + "throw new Error('Module \"' + module + '\" does not exist in container.');" + )})` + ]) + ]), + ");", + `${RuntimeGlobals.currentRemoteGetScope} = undefined;`, + "return getScope;" + ])};`, + `var init = ${runtimeTemplate.basicFunction("shareScope, initScope", [ + `if (!${RuntimeGlobals.shareScopeMap}) return;`, + `var name = ${JSON.stringify(this._shareScope)}`, + `var oldScope = ${RuntimeGlobals.shareScopeMap}[name];`, + `if(oldScope && oldScope !== shareScope) throw new Error("Container initialization failed as it has already been initialized with a different share scope");`, + `${RuntimeGlobals.shareScopeMap}[name] = shareScope;`, + `return ${RuntimeGlobals.initializeSharing}(name, initScope);` + ])};`, + "", + "// This exports getters to disallow modifications", + `${RuntimeGlobals.definePropertyGetters}(exports, {`, + Template.indent([ + `get: ${runtimeTemplate.returningFunction("get")},`, + `init: ${runtimeTemplate.returningFunction("init")}` + ]), + "});" + ]); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + sources.set( + "javascript", + this.useSourceMap || this.useSimpleSourceMap + ? new OriginalSource(source, "webpack/container-entry") + : new RawSource(source) + ); + return { + sources, + runtimeRequirements + }; + } + /** + * @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; + } -const AsyncDependenciesBlock = __webpack_require__(47736); -const makeSerializable = __webpack_require__(33032); + serialize(context) { + const { write } = context; + write(this._name); + write(this._exposes); + write(this._shareScope); + super.serialize(context); + } -class RequireEnsureDependenciesBlock extends AsyncDependenciesBlock { - constructor(chunkName, loc) { - super(chunkName, loc, null); + static deserialize(context) { + const { read } = context; + const obj = new ContainerEntryModule(read(), read(), read()); + obj.deserialize(context); + return obj; } } makeSerializable( - RequireEnsureDependenciesBlock, - "webpack/lib/dependencies/RequireEnsureDependenciesBlock" + ContainerEntryModule, + "webpack/lib/container/ContainerEntryModule" ); -module.exports = RequireEnsureDependenciesBlock; +module.exports = ContainerEntryModule; /***/ }), -/***/ 7235: +/***/ 76398: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr */ -const RequireEnsureDependenciesBlock = __webpack_require__(27153); -const RequireEnsureDependency = __webpack_require__(27223); -const RequireEnsureItemDependency = __webpack_require__(50329); -const getFunctionExpression = __webpack_require__(50396); - -module.exports = class RequireEnsureDependenciesBlockParserPlugin { - apply(parser) { - parser.hooks.call - .for("require.ensure") - .tap("RequireEnsureDependenciesBlockParserPlugin", expr => { - let chunkName = null; - let errorExpressionArg = null; - let errorExpression = null; - switch (expr.arguments.length) { - case 4: { - const chunkNameExpr = parser.evaluateExpression(expr.arguments[3]); - if (!chunkNameExpr.isString()) return; - chunkName = chunkNameExpr.string; - } - // falls through - case 3: { - errorExpressionArg = expr.arguments[2]; - errorExpression = getFunctionExpression(errorExpressionArg); - - if (!errorExpression && !chunkName) { - const chunkNameExpr = parser.evaluateExpression( - expr.arguments[2] - ); - if (!chunkNameExpr.isString()) return; - chunkName = chunkNameExpr.string; - } - } - // falls through - case 2: { - const dependenciesExpr = parser.evaluateExpression( - expr.arguments[0] - ); - const dependenciesItems = dependenciesExpr.isArray() - ? dependenciesExpr.items - : [dependenciesExpr]; - const successExpressionArg = expr.arguments[1]; - const successExpression = - getFunctionExpression(successExpressionArg); +const ModuleFactory = __webpack_require__(51010); +const ContainerEntryModule = __webpack_require__(80580); - if (successExpression) { - parser.walkExpressions(successExpression.expressions); - } - if (errorExpression) { - parser.walkExpressions(errorExpression.expressions); - } +/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */ - const depBlock = new RequireEnsureDependenciesBlock( - chunkName, - expr.loc - ); - const errorCallbackExists = - expr.arguments.length === 4 || - (!chunkName && expr.arguments.length === 3); - const dep = new RequireEnsureDependency( - expr.range, - expr.arguments[1].range, - errorCallbackExists && expr.arguments[2].range - ); - dep.loc = expr.loc; - depBlock.addDependency(dep); - const old = parser.state.current; - parser.state.current = depBlock; - try { - let failed = false; - parser.inScope([], () => { - for (const ee of dependenciesItems) { - if (ee.isString()) { - const ensureDependency = new RequireEnsureItemDependency( - ee.string - ); - ensureDependency.loc = ee.loc || expr.loc; - depBlock.addDependency(ensureDependency); - } else { - failed = true; - } - } - }); - if (failed) { - return; - } - if (successExpression) { - if (successExpression.fn.body.type === "BlockStatement") { - parser.walkStatement(successExpression.fn.body); - } else { - parser.walkExpression(successExpression.fn.body); - } - } - old.addBlock(depBlock); - } finally { - parser.state.current = old; - } - if (!successExpression) { - parser.walkExpression(successExpressionArg); - } - if (errorExpression) { - if (errorExpression.fn.body.type === "BlockStatement") { - parser.walkStatement(errorExpression.fn.body); - } else { - parser.walkExpression(errorExpression.fn.body); - } - } else if (errorExpressionArg) { - parser.walkExpression(errorExpressionArg); - } - return true; - } - } - }); +module.exports = class ContainerEntryModuleFactory extends ModuleFactory { + /** + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * @returns {void} + */ + create({ dependencies: [dependency] }, callback) { + const dep = /** @type {ContainerEntryDependency} */ (dependency); + callback(null, { + module: new ContainerEntryModule(dep.name, dep.exposes, dep.shareScope) + }); } }; /***/ }), -/***/ 27223: +/***/ 72374: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr */ -const RuntimeGlobals = __webpack_require__(16475); +const ModuleDependency = __webpack_require__(80321); const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - -class RequireEnsureDependency extends NullDependency { - constructor(range, contentRange, errorHandlerRange) { - super(); - this.range = range; - this.contentRange = contentRange; - this.errorHandlerRange = errorHandlerRange; +class ContainerExposedDependency extends ModuleDependency { + /** + * @param {string} exposedName public name + * @param {string} request request to module + */ + constructor(exposedName, request) { + super(request); + this.exposedName = exposedName; } get type() { - return "require.ensure"; + return "container exposed"; } - serialize(context) { - const { write } = context; + get category() { + return "esm"; + } - write(this.range); - write(this.contentRange); - write(this.errorHandlerRange); + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return `exposed dependency ${this.exposedName}=${this.request}`; + } + serialize(context) { + context.write(this.exposedName); super.serialize(context); } deserialize(context) { - const { read } = context; - - this.range = read(); - this.contentRange = read(); - this.errorHandlerRange = read(); - + this.exposedName = context.read(); super.deserialize(context); } } makeSerializable( - RequireEnsureDependency, - "webpack/lib/dependencies/RequireEnsureDependency" + ContainerExposedDependency, + "webpack/lib/container/ContainerExposedDependency" ); -RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, - { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {RequireEnsureDependency} */ (dependency); - const depBlock = /** @type {AsyncDependenciesBlock} */ ( - moduleGraph.getParentBlock(dep) - ); - const promise = runtimeTemplate.blockPromise({ - chunkGraph, - block: depBlock, - message: "require.ensure", - runtimeRequirements - }); - const range = dep.range; - const contentRange = dep.contentRange; - const errorHandlerRange = dep.errorHandlerRange; - source.replace(range[0], contentRange[0] - 1, `${promise}.then((`); - if (errorHandlerRange) { - source.replace( - contentRange[1], - errorHandlerRange[0] - 1, - ").bind(null, __webpack_require__))['catch'](" - ); - source.replace(errorHandlerRange[1], range[1] - 1, ")"); - } else { - source.replace( - contentRange[1], - range[1] - 1, - `).bind(null, __webpack_require__))['catch'](${RuntimeGlobals.uncaughtErrorHandler})` - ); - } - } -}; - -module.exports = RequireEnsureDependency; +module.exports = ContainerExposedDependency; /***/ }), -/***/ 50329: +/***/ 9244: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr */ -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const NullDependency = __webpack_require__(31830); - -class RequireEnsureItemDependency extends ModuleDependency { - constructor(request) { - super(request); - } +const createSchemaValidation = __webpack_require__(32540); +const ContainerEntryDependency = __webpack_require__(64813); +const ContainerEntryModuleFactory = __webpack_require__(76398); +const ContainerExposedDependency = __webpack_require__(72374); +const { parseOptions } = __webpack_require__(3083); - get type() { - return "require.ensure item"; - } +/** @typedef {import("../../declarations/plugins/container/ContainerPlugin").ContainerPluginOptions} ContainerPluginOptions */ +/** @typedef {import("../Compiler")} Compiler */ - get category() { - return "commonjs"; +const validate = createSchemaValidation( + __webpack_require__(9504), + () => __webpack_require__(84899), + { + name: "Container Plugin", + baseDataPath: "options" } -} - -makeSerializable( - RequireEnsureItemDependency, - "webpack/lib/dependencies/RequireEnsureItemDependency" ); -RequireEnsureItemDependency.Template = NullDependency.Template; - -module.exports = RequireEnsureItemDependency; - - -/***/ }), - -/***/ 8434: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const PLUGIN_NAME = "ContainerPlugin"; +class ContainerPlugin { + /** + * @param {ContainerPluginOptions} options options + */ + constructor(options) { + validate(options); + this._options = { + name: options.name, + shareScope: options.shareScope || "default", + library: options.library || { + type: "var", + name: options.name + }, + runtime: options.runtime, + filename: options.filename || undefined, + exposes: parseOptions( + options.exposes, + item => ({ + import: Array.isArray(item) ? item : [item], + name: undefined + }), + item => ({ + import: Array.isArray(item.import) ? item.import : [item.import], + name: item.name || undefined + }) + ) + }; + } -const RequireEnsureDependency = __webpack_require__(27223); -const RequireEnsureItemDependency = __webpack_require__(50329); + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { name, exposes, shareScope, filename, library, runtime } = + this._options; -const RequireEnsureDependenciesBlockParserPlugin = __webpack_require__(7235); + compiler.options.output.enabledLibraryTypes.push(library.type); -const { - evaluateToString, - toConstantDependency -} = __webpack_require__(93998); + compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => { + const dep = new ContainerEntryDependency(name, exposes, shareScope); + dep.loc = { name }; + compilation.addEntry( + compilation.options.context, + dep, + { + name, + filename, + runtime, + library + }, + error => { + if (error) return callback(error); + callback(); + } + ); + }); -class RequireEnsurePlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "RequireEnsurePlugin", + compiler.hooks.thisCompilation.tap( + PLUGIN_NAME, (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( - RequireEnsureItemDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - RequireEnsureItemDependency, - new RequireEnsureItemDependency.Template() + ContainerEntryDependency, + new ContainerEntryModuleFactory() ); - compilation.dependencyTemplates.set( - RequireEnsureDependency, - new RequireEnsureDependency.Template() + compilation.dependencyFactories.set( + ContainerExposedDependency, + normalModuleFactory ); - - const handler = (parser, parserOptions) => { - if ( - parserOptions.requireEnsure !== undefined && - !parserOptions.requireEnsure - ) - return; - - new RequireEnsureDependenciesBlockParserPlugin().apply(parser); - parser.hooks.evaluateTypeof - .for("require.ensure") - .tap("RequireEnsurePlugin", evaluateToString("function")); - parser.hooks.typeof - .for("require.ensure") - .tap( - "RequireEnsurePlugin", - toConstantDependency(parser, JSON.stringify("function")) - ); - }; - - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireEnsurePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireEnsurePlugin", handler); } ); } } -module.exports = RequireEnsurePlugin; + +module.exports = ContainerPlugin; /***/ }), -/***/ 89183: +/***/ 95757: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ +const ExternalsPlugin = __webpack_require__(6652); const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - -class RequireHeaderDependency extends NullDependency { - constructor(range) { - super(); - if (!Array.isArray(range)) throw new Error("range must be valid"); - this.range = range; - } +const createSchemaValidation = __webpack_require__(32540); +const FallbackDependency = __webpack_require__(57764); +const FallbackItemDependency = __webpack_require__(29593); +const FallbackModuleFactory = __webpack_require__(4112); +const RemoteModule = __webpack_require__(62916); +const RemoteRuntimeModule = __webpack_require__(88288); +const RemoteToExternalDependency = __webpack_require__(14389); +const { parseOptions } = __webpack_require__(3083); - serialize(context) { - const { write } = context; - write(this.range); - super.serialize(context); - } +/** @typedef {import("../../declarations/plugins/container/ContainerReferencePlugin").ContainerReferencePluginOptions} ContainerReferencePluginOptions */ +/** @typedef {import("../../declarations/plugins/container/ContainerReferencePlugin").RemotesConfig} RemotesConfig */ +/** @typedef {import("../Compiler")} Compiler */ - static deserialize(context) { - const obj = new RequireHeaderDependency(context.read()); - obj.deserialize(context); - return obj; +const validate = createSchemaValidation( + __webpack_require__(95122), + () => + __webpack_require__(66681), + { + name: "Container Reference Plugin", + baseDataPath: "options" } -} - -makeSerializable( - RequireHeaderDependency, - "webpack/lib/dependencies/RequireHeaderDependency" ); -RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, { runtimeRequirements }) { - const dep = /** @type {RequireHeaderDependency} */ (dependency); - runtimeRequirements.add(RuntimeGlobals.require); - source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__"); - } -}; - -module.exports = RequireHeaderDependency; - - -/***/ }), - -/***/ 71284: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Dependency = __webpack_require__(54912); -const Template = __webpack_require__(1626); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -class RequireIncludeDependency extends ModuleDependency { - constructor(request, range) { - super(request); - - this.range = range; - } +const slashCode = "/".charCodeAt(0); +class ContainerReferencePlugin { /** - * 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 + * @param {ContainerReferencePluginOptions} options options */ - getReferencedExports(moduleGraph, runtime) { - // This doesn't use any export - return Dependency.NO_EXPORTS_REFERENCED; - } - - get type() { - return "require.include"; - } + constructor(options) { + validate(options); - get category() { - return "commonjs"; + this._remoteType = options.remoteType; + this._remotes = parseOptions( + options.remotes, + item => ({ + external: Array.isArray(item) ? item : [item], + shareScope: options.shareScope || "default" + }), + item => ({ + external: Array.isArray(item.external) + ? item.external + : [item.external], + shareScope: item.shareScope || options.shareScope || "default" + }) + ); } -} -makeSerializable( - RequireIncludeDependency, - "webpack/lib/dependencies/RequireIncludeDependency" -); - -RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate extends ( - ModuleDependency.Template -) { /** - * @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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply(dependency, source, { runtimeTemplate }) { - const dep = /** @type {RequireIncludeDependency} */ (dependency); - const comment = runtimeTemplate.outputOptions.pathinfo - ? Template.toComment( - `require.include ${runtimeTemplate.requestShortener.shorten( - dep.request - )}` - ) - : ""; - - source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`); - } -}; - -module.exports = RequireIncludeDependency; - - -/***/ }), - -/***/ 35768: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const WebpackError = __webpack_require__(53799); -const { - evaluateToString, - toConstantDependency -} = __webpack_require__(93998); -const makeSerializable = __webpack_require__(33032); -const RequireIncludeDependency = __webpack_require__(71284); - -module.exports = class RequireIncludeDependencyParserPlugin { - constructor(warn) { - this.warn = warn; - } - apply(parser) { - const { warn } = this; - parser.hooks.call - .for("require.include") - .tap("RequireIncludeDependencyParserPlugin", expr => { - if (expr.arguments.length !== 1) return; - const param = parser.evaluateExpression(expr.arguments[0]); - if (!param.isString()) return; - - if (warn) { - parser.state.module.addWarning( - new RequireIncludeDeprecationWarning(expr.loc) - ); - } - - const dep = new RequireIncludeDependency(param.string, expr.range); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return true; - }); - parser.hooks.evaluateTypeof - .for("require.include") - .tap("RequireIncludePlugin", expr => { - if (warn) { - parser.state.module.addWarning( - new RequireIncludeDeprecationWarning(expr.loc) - ); - } - return evaluateToString("function")(expr); - }); - parser.hooks.typeof - .for("require.include") - .tap("RequireIncludePlugin", expr => { - if (warn) { - parser.state.module.addWarning( - new RequireIncludeDeprecationWarning(expr.loc) - ); - } - return toConstantDependency(parser, JSON.stringify("function"))(expr); - }); - } -}; - -class RequireIncludeDeprecationWarning extends WebpackError { - constructor(loc) { - super("require.include() is deprecated and will be removed soon."); - - this.name = "RequireIncludeDeprecationWarning"; - - this.loc = loc; - } -} - -makeSerializable( - RequireIncludeDeprecationWarning, - "webpack/lib/dependencies/RequireIncludeDependencyParserPlugin", - "RequireIncludeDeprecationWarning" -); - - -/***/ }), - -/***/ 37378: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + apply(compiler) { + const { _remotes: remotes, _remoteType: remoteType } = this; + /** @type {Record} */ + const remoteExternals = {}; + for (const [key, config] of remotes) { + let i = 0; + for (const external of config.external) { + if (external.startsWith("internal ")) continue; + remoteExternals[ + `webpack/container/reference/${key}${i ? `/fallback-${i}` : ""}` + ] = external; + i++; + } + } -const RequireIncludeDependency = __webpack_require__(71284); -const RequireIncludeDependencyParserPlugin = __webpack_require__(35768); + new ExternalsPlugin(remoteType, remoteExternals).apply(compiler); -class RequireIncludePlugin { - apply(compiler) { compiler.hooks.compilation.tap( - "RequireIncludePlugin", + "ContainerReferencePlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( - RequireIncludeDependency, + RemoteToExternalDependency, normalModuleFactory ); - compilation.dependencyTemplates.set( - RequireIncludeDependency, - new RequireIncludeDependency.Template() + + compilation.dependencyFactories.set( + FallbackItemDependency, + normalModuleFactory ); - const handler = (parser, parserOptions) => { - if (parserOptions.requireInclude === false) return; - const warn = parserOptions.requireInclude === undefined; + compilation.dependencyFactories.set( + FallbackDependency, + new FallbackModuleFactory() + ); - new RequireIncludeDependencyParserPlugin(warn).apply(parser); - }; + normalModuleFactory.hooks.factorize.tap( + "ContainerReferencePlugin", + data => { + if (!data.request.includes("!")) { + for (const [key, config] of remotes) { + if ( + data.request.startsWith(`${key}`) && + (data.request.length === key.length || + data.request.charCodeAt(key.length) === slashCode) + ) { + return new RemoteModule( + data.request, + config.external.map((external, i) => + external.startsWith("internal ") + ? external.slice(9) + : `webpack/container/reference/${key}${ + i ? `/fallback-${i}` : "" + }` + ), + `.${data.request.slice(key.length)}`, + config.shareScope + ); + } + } + } + } + ); - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireIncludePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireIncludePlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("ContainerReferencePlugin", (chunk, set) => { + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + set.add(RuntimeGlobals.initializeSharing); + set.add(RuntimeGlobals.shareScopeMap); + compilation.addRuntimeModule(chunk, new RemoteRuntimeModule()); + }); } ); } } -module.exports = RequireIncludePlugin; + +module.exports = ContainerReferencePlugin; /***/ }), -/***/ 55627: +/***/ 57764: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -83183,54 +79691,55 @@ module.exports = RequireIncludePlugin; +const Dependency = __webpack_require__(54912); const makeSerializable = __webpack_require__(33032); -const ContextDependency = __webpack_require__(88101); -const ContextDependencyTemplateAsId = __webpack_require__(76081); -class RequireResolveContextDependency extends ContextDependency { - constructor(options, range, valueRange) { - super(options); +class FallbackDependency extends Dependency { + constructor(requests) { + super(); + this.requests = requests; + } - this.range = range; - this.valueRange = valueRange; + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return `fallback ${this.requests.join(" ")}`; } get type() { - return "amd require context"; + return "fallback"; + } + + get category() { + return "esm"; } serialize(context) { const { write } = context; - - write(this.range); - write(this.valueRange); - + write(this.requests); super.serialize(context); } - deserialize(context) { + static deserialize(context) { const { read } = context; - - this.range = read(); - this.valueRange = read(); - - super.deserialize(context); + const obj = new FallbackDependency(read()); + obj.deserialize(context); + return obj; } } makeSerializable( - RequireResolveContextDependency, - "webpack/lib/dependencies/RequireResolveContextDependency" + FallbackDependency, + "webpack/lib/container/FallbackDependency" ); -RequireResolveContextDependency.Template = ContextDependencyTemplateAsId; - -module.exports = RequireResolveContextDependency; +module.exports = FallbackDependency; /***/ }), -/***/ 68582: +/***/ 29593: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -83241,928 +79750,1066 @@ module.exports = RequireResolveContextDependency; -const Dependency = __webpack_require__(54912); -const makeSerializable = __webpack_require__(33032); const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyAsId = __webpack_require__(80825); - -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +const makeSerializable = __webpack_require__(33032); -class RequireResolveDependency extends ModuleDependency { - constructor(request, range) { +class FallbackItemDependency extends ModuleDependency { + constructor(request) { super(request); - - this.range = range; } get type() { - return "require.resolve"; + return "fallback item"; } get category() { - return "commonjs"; - } - - /** - * 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) { - // This doesn't use any export - return Dependency.NO_EXPORTS_REFERENCED; + return "esm"; } } makeSerializable( - RequireResolveDependency, - "webpack/lib/dependencies/RequireResolveDependency" + FallbackItemDependency, + "webpack/lib/container/FallbackItemDependency" ); -RequireResolveDependency.Template = ModuleDependencyAsId; - -module.exports = RequireResolveDependency; +module.exports = FallbackItemDependency; /***/ }), -/***/ 9880: +/***/ 82886: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ +const { RawSource } = __webpack_require__(51255); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +const FallbackItemDependency = __webpack_require__(29593); -class RequireResolveHeaderDependency extends NullDependency { - constructor(range) { - super(); +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ - if (!Array.isArray(range)) throw new Error("range must be valid"); +const TYPES = new Set(["javascript"]); +const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); - this.range = range; +class FallbackModule extends Module { + /** + * @param {string[]} requests list of requests to choose one + */ + constructor(requests) { + super("fallback-module"); + this.requests = requests; + this._identifier = `fallback ${this.requests.join(" ")}`; } - serialize(context) { - const { write } = context; - - write(this.range); - - super.serialize(context); + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this._identifier; } - static deserialize(context) { - const obj = new RequireResolveHeaderDependency(context.read()); - obj.deserialize(context); - return obj; + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return this._identifier; } -} - -makeSerializable( - RequireResolveHeaderDependency, - "webpack/lib/dependencies/RequireResolveHeaderDependency" -); -RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTemplate extends ( - NullDependency.Template -) { /** - * @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} + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion */ - apply(dependency, source, templateContext) { - const dep = /** @type {RequireResolveHeaderDependency} */ (dependency); - source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + libIdent(options) { + return `${this.layer ? `(${this.layer})/` : ""}webpack/container/fallback/${ + this.requests[0] + }/and ${this.requests.length - 1} more`; } - applyAsTemplateArgument(name, dep, source) { - source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + /** + * @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; } -}; - -module.exports = RequireResolveHeaderDependency; - - -/***/ }), - -/***/ 24187: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + callback(null, !this.buildInfo); + } + /** + * @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 = { + strict: true + }; + this.clearDependenciesAndBlocks(); + for (const request of this.requests) + this.addDependency(new FallbackItemDependency(request)); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); + callback(); + } -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/Hash")} Hash */ + /** + * @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 this.requests.length * 5 + 42; + } -class RuntimeRequirementsDependency extends NullDependency { /** - * @param {string[]} runtimeRequirements runtime requirements + * @returns {Set} types available (do not mutate) */ - constructor(runtimeRequirements) { - super(); - this.runtimeRequirements = new Set(runtimeRequirements); - this._hashUpdate = undefined; + getSourceTypes() { + return TYPES; } /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context - * @returns {void} + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) { - this._hashUpdate = Array.from(this.runtimeRequirements).join() + ""; - } - hash.update(this._hashUpdate); + codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { + const ids = this.dependencies.map(dep => + chunkGraph.getModuleId(moduleGraph.getModule(dep)) + ); + const code = Template.asString([ + `var ids = ${JSON.stringify(ids)};`, + "var error, result, i = 0;", + `var loop = ${runtimeTemplate.basicFunction("next", [ + "while(i < ids.length) {", + Template.indent([ + "try { next = __webpack_require__(ids[i++]); } catch(e) { return handleError(e); }", + "if(next) return next.then ? next.then(handleResult, handleError) : handleResult(next);" + ]), + "}", + "if(error) throw error;" + ])}`, + `var handleResult = ${runtimeTemplate.basicFunction("result", [ + "if(result) return result;", + "return loop();" + ])};`, + `var handleError = ${runtimeTemplate.basicFunction("e", [ + "error = e;", + "return loop();" + ])};`, + "module.exports = loop();" + ]); + const sources = new Map(); + sources.set("javascript", new RawSource(code)); + return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS }; } serialize(context) { const { write } = context; - write(this.runtimeRequirements); + write(this.requests); super.serialize(context); } - deserialize(context) { + static deserialize(context) { const { read } = context; - this.runtimeRequirements = read(); - super.deserialize(context); + const obj = new FallbackModule(read()); + obj.deserialize(context); + return obj; } } -makeSerializable( - RuntimeRequirementsDependency, - "webpack/lib/dependencies/RuntimeRequirementsDependency" -); +makeSerializable(FallbackModule, "webpack/lib/container/FallbackModule"); -RuntimeRequirementsDependency.Template = class RuntimeRequirementsDependencyTemplate extends ( - NullDependency.Template -) { +module.exports = FallbackModule; + + +/***/ }), + +/***/ 4112: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr +*/ + + + +const ModuleFactory = __webpack_require__(51010); +const FallbackModule = __webpack_require__(82886); + +/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./FallbackDependency")} FallbackDependency */ + +module.exports = class FallbackModuleFactory extends ModuleFactory { /** - * @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 + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback * @returns {void} */ - apply(dependency, source, { runtimeRequirements }) { - const dep = /** @type {RuntimeRequirementsDependency} */ (dependency); - for (const req of dep.runtimeRequirements) { - runtimeRequirements.add(req); - } + create({ dependencies: [dependency] }, callback) { + const dep = /** @type {FallbackDependency} */ (dependency); + callback(null, { + module: new FallbackModule(dep.requests) + }); } }; -module.exports = RuntimeRequirementsDependency; - /***/ }), -/***/ 91418: +/***/ 30569: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +const isValidExternalsType = __webpack_require__(62142); +const SharePlugin = __webpack_require__(26335); +const createSchemaValidation = __webpack_require__(32540); +const ContainerPlugin = __webpack_require__(9244); +const ContainerReferencePlugin = __webpack_require__(95757); -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ExportSpec} ExportSpec */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ExternalsType} ExternalsType */ +/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ModuleFederationPluginOptions} ModuleFederationPluginOptions */ +/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").Shared} Shared */ +/** @typedef {import("../Compiler")} Compiler */ -class StaticExportsDependency extends NullDependency { +const validate = createSchemaValidation( + __webpack_require__(7467), + () => __webpack_require__(82601), + { + name: "Module Federation Plugin", + baseDataPath: "options" + } +); +class ModuleFederationPlugin { /** - * @param {string[] | true} exports export names - * @param {boolean} canMangle true, if mangling exports names is allowed + * @param {ModuleFederationPluginOptions} options options */ - constructor(exports, canMangle) { - super(); - this.exports = exports; - this.canMangle = canMangle; - } + constructor(options) { + validate(options); - get type() { - return "static exports"; + this._options = options; } /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - getExports(moduleGraph) { - return { - exports: this.exports, - canMangle: this.canMangle, - dependencies: undefined - }; - } - - serialize(context) { - const { write } = context; - write(this.exports); - write(this.canMangle); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.exports = read(); - this.canMangle = read(); - super.deserialize(context); + apply(compiler) { + const { _options: options } = this; + const library = options.library || { type: "var", name: options.name }; + const remoteType = + options.remoteType || + (options.library && isValidExternalsType(options.library.type) + ? /** @type {ExternalsType} */ (options.library.type) + : "script"); + if ( + library && + !compiler.options.output.enabledLibraryTypes.includes(library.type) + ) { + compiler.options.output.enabledLibraryTypes.push(library.type); + } + compiler.hooks.afterPlugins.tap("ModuleFederationPlugin", () => { + if ( + options.exposes && + (Array.isArray(options.exposes) + ? options.exposes.length > 0 + : Object.keys(options.exposes).length > 0) + ) { + new ContainerPlugin({ + name: options.name, + library, + filename: options.filename, + runtime: options.runtime, + exposes: options.exposes + }).apply(compiler); + } + if ( + options.remotes && + (Array.isArray(options.remotes) + ? options.remotes.length > 0 + : Object.keys(options.remotes).length > 0) + ) { + new ContainerReferencePlugin({ + remoteType, + remotes: options.remotes + }).apply(compiler); + } + if (options.shared) { + new SharePlugin({ + shared: options.shared, + shareScope: options.shareScope + }).apply(compiler); + } + }); } } -makeSerializable( - StaticExportsDependency, - "webpack/lib/dependencies/StaticExportsDependency" -); - -module.exports = StaticExportsDependency; +module.exports = ModuleFederationPlugin; /***/ }), -/***/ 97981: +/***/ 62916: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ +const { RawSource } = __webpack_require__(51255); +const Module = __webpack_require__(73208); const RuntimeGlobals = __webpack_require__(16475); -const WebpackError = __webpack_require__(53799); -const { - evaluateToString, - expressionIsUnsupported, - toConstantDependency -} = __webpack_require__(93998); const makeSerializable = __webpack_require__(33032); -const ConstDependency = __webpack_require__(76911); -const SystemRuntimeModule = __webpack_require__(85439); +const FallbackDependency = __webpack_require__(57764); +const RemoteToExternalDependency = __webpack_require__(14389); -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ -class SystemPlugin { +const TYPES = new Set(["remote", "share-init"]); +const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); + +class RemoteModule extends Module { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {string} request request string + * @param {string[]} externalRequests list of external requests to containers + * @param {string} internalRequest name of exposed module in container + * @param {string} shareScope the used share scope name */ - apply(compiler) { - compiler.hooks.compilation.tap( - "SystemPlugin", - (compilation, { normalModuleFactory }) => { - compilation.hooks.runtimeRequirementInModule - .for(RuntimeGlobals.system) - .tap("SystemPlugin", (module, set) => { - set.add(RuntimeGlobals.requireScope); - }); + constructor(request, externalRequests, internalRequest, shareScope) { + super("remote-module"); + this.request = request; + this.externalRequests = externalRequests; + this.internalRequest = internalRequest; + this.shareScope = shareScope; + this._identifier = `remote (${shareScope}) ${this.externalRequests.join( + " " + )} ${this.internalRequest}`; + } - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.system) - .tap("SystemPlugin", (chunk, set) => { - compilation.addRuntimeModule(chunk, new SystemRuntimeModule()); - }); + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this._identifier; + } - const handler = (parser, parserOptions) => { - if (parserOptions.system === undefined || !parserOptions.system) { - return; - } + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `remote ${this.request}`; + } - const setNotSupported = name => { - parser.hooks.evaluateTypeof - .for(name) - .tap("SystemPlugin", evaluateToString("undefined")); - parser.hooks.expression - .for(name) - .tap( - "SystemPlugin", - expressionIsUnsupported( - parser, - name + " is not supported by webpack." - ) - ); - }; + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `${this.layer ? `(${this.layer})/` : ""}webpack/container/remote/${ + this.request + }`; + } - parser.hooks.typeof - .for("System.import") - .tap( - "SystemPlugin", - toConstantDependency(parser, JSON.stringify("function")) - ); - parser.hooks.evaluateTypeof - .for("System.import") - .tap("SystemPlugin", evaluateToString("function")); - parser.hooks.typeof - .for("System") - .tap( - "SystemPlugin", - toConstantDependency(parser, JSON.stringify("object")) - ); - parser.hooks.evaluateTypeof - .for("System") - .tap("SystemPlugin", evaluateToString("object")); + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + callback(null, !this.buildInfo); + } - setNotSupported("System.set"); - setNotSupported("System.get"); - setNotSupported("System.register"); + /** + * @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 = { + strict: true + }; - parser.hooks.expression.for("System").tap("SystemPlugin", expr => { - const dep = new ConstDependency(RuntimeGlobals.system, expr.range, [ - RuntimeGlobals.system - ]); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); + this.clearDependenciesAndBlocks(); + if (this.externalRequests.length === 1) { + this.addDependency( + new RemoteToExternalDependency(this.externalRequests[0]) + ); + } else { + this.addDependency(new FallbackDependency(this.externalRequests)); + } - parser.hooks.call.for("System.import").tap("SystemPlugin", expr => { - parser.state.module.addWarning( - new SystemImportDeprecationWarning(expr.loc) - ); + callback(); + } - return parser.hooks.importCall.call({ - type: "ImportExpression", - source: expr.arguments[0], - loc: expr.loc, - range: expr.range - }); - }); - }; + /** + * @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 6; + } - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("SystemPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("SystemPlugin", handler); - } - ); + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; } -} -class SystemImportDeprecationWarning extends WebpackError { - constructor(loc) { - super( - "System.import() is deprecated and will be removed soon. Use import() instead.\n" + - "For more info visit https://webpack.js.org/guides/code-splitting/" - ); + /** + * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + */ + nameForCondition() { + return this.request; + } - this.name = "SystemImportDeprecationWarning"; + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { + const module = moduleGraph.getModule(this.dependencies[0]); + const id = module && chunkGraph.getModuleId(module); + const sources = new Map(); + sources.set("remote", new RawSource("")); + const data = new Map(); + data.set("share-init", [ + { + shareScope: this.shareScope, + initStage: 20, + init: id === undefined ? "" : `initExternal(${JSON.stringify(id)});` + } + ]); + return { sources, data, runtimeRequirements: RUNTIME_REQUIREMENTS }; + } - this.loc = loc; + serialize(context) { + const { write } = context; + write(this.request); + write(this.externalRequests); + write(this.internalRequest); + write(this.shareScope); + super.serialize(context); + } + + static deserialize(context) { + const { read } = context; + const obj = new RemoteModule(read(), read(), read(), read()); + obj.deserialize(context); + return obj; } } -makeSerializable( - SystemImportDeprecationWarning, - "webpack/lib/dependencies/SystemPlugin", - "SystemImportDeprecationWarning" -); +makeSerializable(RemoteModule, "webpack/lib/container/RemoteModule"); -module.exports = SystemPlugin; -module.exports.SystemImportDeprecationWarning = SystemImportDeprecationWarning; +module.exports = RemoteModule; /***/ }), -/***/ 85439: +/***/ 88288: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent + Author Tobias Koppers @sokra */ const RuntimeGlobals = __webpack_require__(16475); const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); +const Template = __webpack_require__(39722); -class SystemRuntimeModule extends RuntimeModule { +/** @typedef {import("./RemoteModule")} RemoteModule */ + +class RemoteRuntimeModule extends RuntimeModule { constructor() { - super("system"); + super("remotes loading"); } /** * @returns {string} runtime code */ generate() { + const { compilation, chunkGraph } = this; + const { runtimeTemplate, moduleGraph } = compilation; + const chunkToRemotesMapping = {}; + const idToExternalAndNameMapping = {}; + for (const chunk of this.chunk.getAllAsyncChunks()) { + const modules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "remote" + ); + if (!modules) continue; + const remotes = (chunkToRemotesMapping[chunk.id] = []); + for (const m of modules) { + const module = /** @type {RemoteModule} */ (m); + const name = module.internalRequest; + const id = chunkGraph.getModuleId(module); + const shareScope = module.shareScope; + const dep = module.dependencies[0]; + const externalModule = moduleGraph.getModule(dep); + const externalModuleId = + externalModule && chunkGraph.getModuleId(externalModule); + remotes.push(id); + idToExternalAndNameMapping[id] = [shareScope, name, externalModuleId]; + } + } return Template.asString([ - `${RuntimeGlobals.system} = {`, - Template.indent([ - "import: function () {", - Template.indent( - "throw new Error('System.import cannot be used indirectly');" - ), + `var chunkMapping = ${JSON.stringify( + chunkToRemotesMapping, + null, + "\t" + )};`, + `var idToExternalAndNameMapping = ${JSON.stringify( + idToExternalAndNameMapping, + null, + "\t" + )};`, + `${ + RuntimeGlobals.ensureChunkHandlers + }.remotes = ${runtimeTemplate.basicFunction("chunkId, promises", [ + `if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`, + Template.indent([ + `chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction("id", [ + `var getScope = ${RuntimeGlobals.currentRemoteGetScope};`, + "if(!getScope) getScope = [];", + "var data = idToExternalAndNameMapping[id];", + "if(getScope.indexOf(data) >= 0) return;", + "getScope.push(data);", + `if(data.p) return promises.push(data.p);`, + `var onError = ${runtimeTemplate.basicFunction("error", [ + 'if(!error) error = new Error("Container missing");', + 'if(typeof error.message === "string")', + Template.indent( + `error.message += '\\nwhile loading "' + data[1] + '" from ' + data[2];` + ), + `__webpack_modules__[id] = ${runtimeTemplate.basicFunction("", [ + "throw error;" + ])}`, + "data.p = 0;" + ])};`, + `var handleFunction = ${runtimeTemplate.basicFunction( + "fn, arg1, arg2, d, next, first", + [ + "try {", + Template.indent([ + "var promise = fn(arg1, arg2);", + "if(promise && promise.then) {", + Template.indent([ + `var p = promise.then(${runtimeTemplate.returningFunction( + "next(result, d)", + "result" + )}, onError);`, + `if(first) promises.push(data.p = p); else return p;` + ]), + "} else {", + Template.indent(["return next(promise, d, first);"]), + "}" + ]), + "} catch(error) {", + Template.indent(["onError(error);"]), + "}" + ] + )}`, + `var onExternal = ${runtimeTemplate.returningFunction( + `external ? handleFunction(${RuntimeGlobals.initializeSharing}, data[0], 0, external, onInitialized, first) : onError()`, + "external, _, first" + )};`, + `var onInitialized = ${runtimeTemplate.returningFunction( + `handleFunction(external.get, data[1], getScope, 0, onFactory, first)`, + "_, external, first" + )};`, + `var onFactory = ${runtimeTemplate.basicFunction("factory", [ + "data.p = 1;", + `__webpack_modules__[id] = ${runtimeTemplate.basicFunction( + "module", + ["module.exports = factory();"] + )}` + ])};`, + "handleFunction(__webpack_require__, data[2], 0, 0, onExternal, 1);" + ])});` + ]), "}" - ]), - "};" + ])}` ]); } } -module.exports = SystemRuntimeModule; +module.exports = RemoteRuntimeModule; /***/ }), -/***/ 58612: +/***/ 14389: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const { - getDependencyUsedByExportsCondition -} = __webpack_require__(38988); -const makeSerializable = __webpack_require__(33032); -const memoize = __webpack_require__(78676); const ModuleDependency = __webpack_require__(80321); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -const getRawDataUrlModule = memoize(() => __webpack_require__(19684)); - -class URLDependency extends ModuleDependency { - /** - * @param {string} request request - * @param {[number, number]} range range of the arguments of new URL( |> ... <| ) - * @param {[number, number]} outerRange range of the full |> new URL(...) <| - * @param {boolean=} relative use relative urls instead of absolute with base uri - */ - constructor(request, range, outerRange, relative) { +class RemoteToExternalDependency extends ModuleDependency { + constructor(request) { super(request); - this.range = range; - this.outerRange = outerRange; - this.relative = relative || false; - /** @type {Set | boolean} */ - this.usedByExports = undefined; } get type() { - return "new URL()"; + return "remote to external"; } get category() { - return "url"; + return "esm"; } +} - /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active - */ - getCondition(moduleGraph) { - return getDependencyUsedByExportsCondition( - this, - this.usedByExports, - moduleGraph - ); - } +makeSerializable( + RemoteToExternalDependency, + "webpack/lib/container/RemoteToExternalDependency" +); - /** - * @param {string} context context directory - * @returns {Module} a module - */ - createIgnoredModule(context) { - const RawDataUrlModule = getRawDataUrlModule(); - return new RawDataUrlModule("data:,", `ignored-asset`, `(ignored asset)`); - } +module.exports = RemoteToExternalDependency; - serialize(context) { - const { write } = context; - write(this.outerRange); - write(this.relative); - write(this.usedByExports); - super.serialize(context); - } - deserialize(context) { - const { read } = context; - this.outerRange = read(); - this.relative = read(); - this.usedByExports = read(); - super.deserialize(context); - } -} +/***/ }), -URLDependency.Template = class URLDependencyTemplate extends ( - ModuleDependency.Template -) { - /** - * @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 { - chunkGraph, - moduleGraph, - runtimeRequirements, - runtimeTemplate, - runtime - } = templateContext; - const dep = /** @type {URLDependency} */ (dependency); - const connection = moduleGraph.getConnection(dep); - // Skip rendering depending when dependency is conditional - if (connection && !connection.isTargetActive(runtime)) { - source.replace( - dep.outerRange[0], - dep.outerRange[1] - 1, - "/* unused asset import */ undefined" - ); - return; - } +/***/ 3083: +/***/ (function(__unused_webpack_module, exports) { - runtimeRequirements.add(RuntimeGlobals.require); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (dep.relative) { - runtimeRequirements.add(RuntimeGlobals.relativeUrl); - source.replace( - dep.outerRange[0], - dep.outerRange[1] - 1, - `/* asset import */ new ${ - RuntimeGlobals.relativeUrl - }(${runtimeTemplate.moduleRaw({ - chunkGraph, - module: moduleGraph.getModule(dep), - request: dep.request, - runtimeRequirements, - weak: false - })})` - ); - } else { - runtimeRequirements.add(RuntimeGlobals.baseURI); - source.replace( - dep.range[0], - dep.range[1] - 1, - `/* asset import */ ${runtimeTemplate.moduleRaw({ - chunkGraph, - module: moduleGraph.getModule(dep), - request: dep.request, - runtimeRequirements, - weak: false - })}, ${RuntimeGlobals.baseURI}` - ); + +/** @template T @typedef {(string | Record)[] | Record} ContainerOptionsFormat */ + +/** + * @template T + * @template N + * @param {ContainerOptionsFormat} options options passed by the user + * @param {function(string | string[], string) : N} normalizeSimple normalize a simple item + * @param {function(T, string) : N} normalizeOptions normalize a complex item + * @param {function(string, N): void} fn processing function + * @returns {void} + */ +const process = (options, normalizeSimple, normalizeOptions, fn) => { + const array = items => { + for (const item of items) { + if (typeof item === "string") { + fn(item, normalizeSimple(item, item)); + } else if (item && typeof item === "object") { + object(item); + } else { + throw new Error("Unexpected options format"); + } + } + }; + const object = obj => { + for (const [key, value] of Object.entries(obj)) { + if (typeof value === "string" || Array.isArray(value)) { + fn(key, normalizeSimple(value, key)); + } else { + fn(key, normalizeOptions(value, key)); + } } + }; + if (!options) { + return; + } else if (Array.isArray(options)) { + array(options); + } else if (typeof options === "object") { + object(options); + } else { + throw new Error("Unexpected options format"); } }; -makeSerializable(URLDependency, "webpack/lib/dependencies/URLDependency"); +/** + * @template T + * @template R + * @param {ContainerOptionsFormat} options options passed by the user + * @param {function(string | string[], string) : R} normalizeSimple normalize a simple item + * @param {function(T, string) : R} normalizeOptions normalize a complex item + * @returns {[string, R][]} parsed options + */ +const parseOptions = (options, normalizeSimple, normalizeOptions) => { + /** @type {[string, R][]} */ + const items = []; + process(options, normalizeSimple, normalizeOptions, (key, value) => { + items.push([key, value]); + }); + return items; +}; -module.exports = URLDependency; +/** + * @template T + * @param {string} scope scope name + * @param {ContainerOptionsFormat} options options passed by the user + * @returns {Record} options to spread or pass + */ +const scope = (scope, options) => { + /** @type {Record} */ + const obj = {}; + process( + options, + item => /** @type {string | string[] | T} */ (item), + item => /** @type {string | string[] | T} */ (item), + (key, value) => { + obj[ + key.startsWith("./") ? `${scope}${key.slice(1)}` : `${scope}/${key}` + ] = value; + } + ); + return obj; +}; + +exports.parseOptions = parseOptions; +exports.scope = scope; /***/ }), -/***/ 14412: +/***/ 91254: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Sergey Melyukov @smelukov */ -const { approve } = __webpack_require__(93998); -const InnerGraph = __webpack_require__(38988); -const URLDependency = __webpack_require__(58612); - -/** @typedef {import("estree").NewExpression} NewExpressionNode */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ - -class URLPlugin { - /** - * @param {Compiler} compiler compiler - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "URLPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set(URLDependency, normalModuleFactory); - compilation.dependencyTemplates.set( - URLDependency, - new URLDependency.Template() - ); - - /** - * @param {JavascriptParser} parser parser - * @param {object} parserOptions options - */ - const parserCallback = (parser, parserOptions) => { - if (parserOptions.url === false) return; - const relative = parserOptions.url === "relative"; - - /** - * @param {NewExpressionNode} expr expression - * @returns {undefined | string} request - */ - const getUrlRequest = expr => { - if (expr.arguments.length !== 2) return; - - const [arg1, arg2] = expr.arguments; +const { ReplaceSource, RawSource, ConcatSource } = __webpack_require__(51255); +const { UsageState } = __webpack_require__(63686); +const Generator = __webpack_require__(93401); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); - if ( - arg2.type !== "MemberExpression" || - arg1.type === "SpreadElement" - ) - return; +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../util/Hash")} Hash */ - const chain = parser.extractMemberExpressionChain(arg2); +const TYPES = new Set(["javascript"]); - if ( - chain.members.length !== 1 || - chain.object.type !== "MetaProperty" || - chain.object.meta.name !== "import" || - chain.object.property.name !== "meta" || - chain.members[0] !== "url" - ) - return; +class CssExportsGenerator extends Generator { + constructor() { + super(); + } - const request = parser.evaluateExpression(arg1).asString(); + // TODO add getConcatenationBailoutReason to allow concatenation + // but how to make it have a module id - return request; - }; + /** + * @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 source = new ReplaceSource(new RawSource("")); + const initFragments = []; + const cssExports = new Map(); - parser.hooks.canRename.for("URL").tap("URLPlugin", approve); - parser.hooks.new.for("URL").tap("URLPlugin", _expr => { - const expr = /** @type {NewExpressionNode} */ (_expr); + generateContext.runtimeRequirements.add(RuntimeGlobals.module); - const request = getUrlRequest(expr); + const runtimeRequirements = new Set(); - if (!request) return; + const templateContext = { + runtimeTemplate: generateContext.runtimeTemplate, + dependencyTemplates: generateContext.dependencyTemplates, + moduleGraph: generateContext.moduleGraph, + chunkGraph: generateContext.chunkGraph, + module, + runtime: generateContext.runtime, + runtimeRequirements: runtimeRequirements, + concatenationScope: generateContext.concatenationScope, + codeGenerationResults: generateContext.codeGenerationResults, + initFragments, + cssExports + }; - const [arg1, arg2] = expr.arguments; - const dep = new URLDependency( - request, - [arg1.range[0], arg2.range[1]], - expr.range, - relative - ); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); - return true; - }); - parser.hooks.isPure.for("NewExpression").tap("URLPlugin", _expr => { - const expr = /** @type {NewExpressionNode} */ (_expr); - const { callee } = expr; - if (callee.type !== "Identifier") return; - const calleeInfo = parser.getFreeInfoFromVariable(callee.name); - if (!calleeInfo || calleeInfo.name !== "URL") return; + const handleDependency = dependency => { + const constructor = /** @type {new (...args: any[]) => Dependency} */ ( + dependency.constructor + ); + const template = generateContext.dependencyTemplates.get(constructor); + if (!template) { + throw new Error( + "No template for dependency: " + dependency.constructor.name + ); + } - const request = getUrlRequest(expr); + template.apply(dependency, source, templateContext); + }; + module.dependencies.forEach(handleDependency); - if (request) return true; - }); - }; + if (generateContext.concatenationScope) { + const source = new ConcatSource(); + const usedIdentifiers = new Set(); + for (const [k, v] of cssExports) { + let identifier = Template.toIdentifier(k); + let i = 0; + while (usedIdentifiers.has(identifier)) { + identifier = Template.toIdentifier(k + i); + } + usedIdentifiers.add(identifier); + generateContext.concatenationScope.registerExport(k, identifier); + source.add( + `${ + generateContext.runtimeTemplate.supportsConst ? "const" : "var" + } ${identifier} = ${JSON.stringify(v)};\n` + ); + } + return source; + } else { + const otherUsed = + generateContext.moduleGraph + .getExportsInfo(module) + .otherExportsInfo.getUsed(generateContext.runtime) !== + UsageState.Unused; + if (otherUsed) { + generateContext.runtimeRequirements.add( + RuntimeGlobals.makeNamespaceObject + ); + } + return new RawSource( + `${otherUsed ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${ + module.moduleArgument + }.exports = {\n${Array.from( + cssExports, + ([k, v]) => `\t${JSON.stringify(k)}: ${JSON.stringify(v)}` + ).join(",\n")}\n}${otherUsed ? ")" : ""};` + ); + } + } - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("URLPlugin", parserCallback); + /** + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) + */ + getTypes(module) { + return TYPES; + } - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("URLPlugin", parserCallback); - } - ); + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + return 42; } + + /** + * @param {Hash} hash hash that will be modified + * @param {UpdateHashContext} updateHashContext context for updating hash + */ + updateHash(hash, { module }) {} } -module.exports = URLPlugin; +module.exports = CssExportsGenerator; /***/ }), -/***/ 51669: +/***/ 46061: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sergey Melyukov @smelukov */ -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +const { ReplaceSource } = __webpack_require__(51255); +const Generator = __webpack_require__(93401); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - -class UnsupportedDependency extends NullDependency { - constructor(request, range) { - super(); - - this.request = request; - this.range = range; - } - - serialize(context) { - const { write } = context; - - write(this.request); - write(this.range); - - super.serialize(context); - } - - deserialize(context) { - const { read } = context; +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../util/Hash")} Hash */ - this.request = read(); - this.range = read(); +const TYPES = new Set(["css"]); - super.deserialize(context); +class CssGenerator extends Generator { + constructor() { + super(); } -} - -makeSerializable( - UnsupportedDependency, - "webpack/lib/dependencies/UnsupportedDependency" -); -UnsupportedDependency.Template = class UnsupportedDependencyTemplate extends ( - NullDependency.Template -) { /** - * @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} + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code */ - apply(dependency, source, { runtimeTemplate }) { - const dep = /** @type {UnsupportedDependency} */ (dependency); - - source.replace( - dep.range[0], - dep.range[1], - runtimeTemplate.missingModule({ - request: dep.request - }) - ); - } -}; - -module.exports = UnsupportedDependency; - - -/***/ }), - -/***/ 52204: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + generate(module, generateContext) { + const originalSource = module.originalSource(); + const source = new ReplaceSource(originalSource); + const initFragments = []; + const cssExports = new Map(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules); + const templateContext = { + runtimeTemplate: generateContext.runtimeTemplate, + dependencyTemplates: generateContext.dependencyTemplates, + moduleGraph: generateContext.moduleGraph, + chunkGraph: generateContext.chunkGraph, + module, + runtime: generateContext.runtime, + runtimeRequirements: generateContext.runtimeRequirements, + concatenationScope: generateContext.concatenationScope, + codeGenerationResults: generateContext.codeGenerationResults, + initFragments, + cssExports + }; + const handleDependency = dependency => { + const constructor = /** @type {new (...args: any[]) => Dependency} */ ( + dependency.constructor + ); + const template = generateContext.dependencyTemplates.get(constructor); + if (!template) { + throw new Error( + "No template for dependency: " + dependency.constructor.name + ); + } -const Dependency = __webpack_require__(54912); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); + template.apply(dependency, source, templateContext); + }; + module.dependencies.forEach(handleDependency); + if (module.presentationalDependencies !== undefined) + module.presentationalDependencies.forEach(handleDependency); -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + if (cssExports.size > 0) { + const data = generateContext.getData(); + data.set("css-exports", cssExports); + } -class WebAssemblyExportImportedDependency extends ModuleDependency { - constructor(exportName, request, name, valueType) { - super(request); - /** @type {string} */ - this.exportName = exportName; - /** @type {string} */ - this.name = name; - /** @type {string} */ - this.valueType = valueType; + return InitFragment.addToSource(source, initFragments, generateContext); } /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - couldAffectReferencingModule() { - return Dependency.TRANSITIVE; + getTypes(module) { + return TYPES; } /** - * 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 + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - getReferencedExports(moduleGraph, runtime) { - return [[this.name]]; - } - - get type() { - return "wasm export import"; - } - - get category() { - return "wasm"; - } - - serialize(context) { - const { write } = context; + getSize(module, type) { + const originalSource = module.originalSource(); - write(this.exportName); - write(this.name); - write(this.valueType); + if (!originalSource) { + return 0; + } - super.serialize(context); + return originalSource.size(); } - deserialize(context) { - const { read } = context; - - this.exportName = read(); - this.name = read(); - this.valueType = read(); - - super.deserialize(context); - } + /** + * @param {Hash} hash hash that will be modified + * @param {UpdateHashContext} updateHashContext context for updating hash + */ + updateHash(hash, { module }) {} } -makeSerializable( - WebAssemblyExportImportedDependency, - "webpack/lib/dependencies/WebAssemblyExportImportedDependency" -); - -module.exports = WebAssemblyExportImportedDependency; +module.exports = CssGenerator; /***/ }), -/***/ 5239: +/***/ 80806: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -84173,289 +80820,451 @@ module.exports = WebAssemblyExportImportedDependency; -const makeSerializable = __webpack_require__(33032); -const UnsupportedWebAssemblyFeatureError = __webpack_require__(78455); -const ModuleDependency = __webpack_require__(80321); +const { SyncWaterfallHook } = __webpack_require__(41242); +const Compilation = __webpack_require__(85720); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); +const compileBooleanMatcher = __webpack_require__(29404); +const { chunkHasCss } = __webpack_require__(47283); -/** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("../Chunk")} Chunk */ -class WebAssemblyImportDependency extends ModuleDependency { - /** - * @param {string} request the request - * @param {string} name the imported name - * @param {ModuleImportDescription} description the WASM ast node - * @param {false | string} onlyDirectImport if only direct imports are allowed - */ - constructor(request, name, description, onlyDirectImport) { - super(request); - /** @type {string} */ - this.name = name; - /** @type {ModuleImportDescription} */ - this.description = description; - /** @type {false | string} */ - this.onlyDirectImport = onlyDirectImport; - } - - get type() { - return "wasm import"; - } - - get category() { - return "wasm"; - } +/** + * @typedef {Object} JsonpCompilationPluginHooks + * @property {SyncWaterfallHook<[string, Chunk]>} createStylesheet + */ - /** - * 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 [[this.name]]; - } +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); +class CssLoadingRuntimeModule extends RuntimeModule { /** - * Returns errors - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} errors + * @param {Compilation} compilation the compilation + * @returns {JsonpCompilationPluginHooks} hooks */ - getErrors(moduleGraph) { - const module = moduleGraph.getModule(this); - - if ( - this.onlyDirectImport && - module && - !module.type.startsWith("webassembly") - ) { - return [ - new UnsupportedWebAssemblyFeatureError( - `Import "${this.name}" from "${this.request}" with ${this.onlyDirectImport} can only be used for direct wasm to wasm dependencies` - ) - ]; + 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 = { + createStylesheet: new SyncWaterfallHook(["source", "chunk"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; } - serialize(context) { - const { write } = context; - - write(this.name); - write(this.description); - write(this.onlyDirectImport); - - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - - this.name = read(); - this.description = read(); - this.onlyDirectImport = read(); - - super.deserialize(context); - } -} - -makeSerializable( - WebAssemblyImportDependency, - "webpack/lib/dependencies/WebAssemblyImportDependency" -); - -module.exports = WebAssemblyImportDependency; - - -/***/ }), - -/***/ 26505: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - - - -const Dependency = __webpack_require__(54912); -const Template = __webpack_require__(1626); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -class WebpackIsIncludedDependency extends ModuleDependency { - constructor(request, range) { - super(request); - - this.weak = true; - this.range = range; - } - - /** - * 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) { - // This doesn't use any export - return Dependency.NO_EXPORTS_REFERENCED; - } + constructor(runtimeRequirements, runtimeOptions) { + super("css loading", 10); - get type() { - return "__webpack_is_included__"; + this._runtimeRequirements = runtimeRequirements; + this.runtimeOptions = runtimeOptions; } -} - -makeSerializable( - WebpackIsIncludedDependency, - "webpack/lib/dependencies/WebpackIsIncludedDependency" -); -WebpackIsIncludedDependency.Template = class WebpackIsIncludedDependencyTemplate extends ( - ModuleDependency.Template -) { /** - * @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} + * @returns {string} runtime code */ - apply(dependency, source, { runtimeTemplate, chunkGraph, moduleGraph }) { - const dep = /** @type {WebpackIsIncludedDependency} */ (dependency); - const connection = moduleGraph.getConnection(dep); - const included = connection - ? chunkGraph.getNumberOfModuleChunks(connection.module) > 0 - : false; - const comment = runtimeTemplate.outputOptions.pathinfo - ? Template.toComment( - `__webpack_is_included__ ${runtimeTemplate.requestShortener.shorten( - dep.request - )}` - ) - : ""; - - source.replace( - dep.range[0], - dep.range[1] - 1, - `${comment}${JSON.stringify(included)}` + generate() { + const { compilation, chunk, _runtimeRequirements } = this; + const { + chunkGraph, + runtimeTemplate, + outputOptions: { + crossOriginLoading, + uniqueName, + chunkLoadTimeout: loadTimeout + } + } = compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const conditionMap = chunkGraph.getChunkConditionMap( + chunk, + (chunk, chunkGraph) => + !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css") ); - } -}; - -module.exports = WebpackIsIncludedDependency; - - -/***/ }), - -/***/ 1466: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - + const hasCssMatcher = compileBooleanMatcher(conditionMap); + const withLoading = + _runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) && + hasCssMatcher !== false; + const withHmr = _runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const initialChunkIdsWithCss = new Set(); + const initialChunkIdsWithoutCss = new Set(); + for (const c of chunk.getAllInitialChunks()) { + (chunkHasCss(c, chunkGraph) + ? initialChunkIdsWithCss + : initialChunkIdsWithoutCss + ).add(c.id); + } -const Dependency = __webpack_require__(54912); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); + if (!withLoading && !withHmr && initialChunkIdsWithCss.size === 0) { + return null; + } -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Entrypoint")} Entrypoint */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + const { createStylesheet } = + CssLoadingRuntimeModule.getCompilationHooks(compilation); -class WorkerDependency extends ModuleDependency { - /** - * @param {string} request request - * @param {[number, number]} range range - */ - constructor(request, range) { - super(request); - this.range = range; - } + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_css` + : undefined; - /** - * 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.NO_EXPORTS_REFERENCED; - } + const code = Template.asString([ + "link = document.createElement('link');", + uniqueName + ? 'link.setAttribute("data-webpack", uniqueName + ":" + key);' + : "", + "link.setAttribute(loadingAttribute, 1);", + 'link.rel = "stylesheet";', + "link.href = url;", + crossOriginLoading + ? Template.asString([ + "if (link.src.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` + ), + "}" + ]) + : "" + ]); - get type() { - return "new Worker()"; - } + const cc = str => str.charCodeAt(0); - get category() { - return "worker"; + return Template.asString([ + "// object to store loaded and loading chunks", + "// undefined = chunk not loaded, null = chunk preloaded/prefetched", + "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{${Array.from( + initialChunkIdsWithoutCss, + id => `${JSON.stringify(id)}:0` + ).join(",")}};`, + "", + uniqueName + ? `var uniqueName = ${JSON.stringify( + runtimeTemplate.outputOptions.uniqueName + )};` + : "// data-webpack is not used as build has no uniqueName", + `var loadCssChunkData = ${runtimeTemplate.basicFunction( + "target, link, chunkId", + [ + `var data, token = "", token2, exports = {}, exportsWithId = [], exportsWithDashes = [], ${ + withHmr ? "moduleIds = [], " : "" + }i = 0, cc = 1;`, + "try { if(!link) link = loadStylesheet(chunkId); data = link.sheet.cssRules; data = data[data.length - 1].style; } catch(e) { data = getComputedStyle(document.head); }", + `data = data.getPropertyValue(${ + uniqueName + ? runtimeTemplate.concatenation( + "--webpack-", + { expr: "uniqueName" }, + "-", + { expr: "chunkId" } + ) + : runtimeTemplate.concatenation("--webpack-", { expr: "chunkId" }) + });`, + "if(!data) return [];", + "for(; cc; i++) {", + Template.indent([ + "cc = data.charCodeAt(i);", + `if(cc == ${cc("(")}) { token2 = token; token = ""; }`, + `else if(cc == ${cc( + ")" + )}) { exports[token2.replace(/^_/, "")] = token.replace(/^_/, ""); token = ""; }`, + `else if(cc == ${cc("/")} || cc == ${cc( + "%" + )}) { token = token.replace(/^_/, ""); exports[token] = token; exportsWithId.push(token); if(cc == ${cc( + "%" + )}) exportsWithDashes.push(token); token = ""; }`, + `else if(!cc || cc == ${cc( + "," + )}) { token = token.replace(/^_/, ""); exportsWithId.forEach(${runtimeTemplate.expressionFunction( + `exports[x] = ${ + uniqueName + ? runtimeTemplate.concatenation( + { expr: "uniqueName" }, + "-", + { expr: "token" }, + "-", + { expr: "exports[x]" } + ) + : runtimeTemplate.concatenation({ expr: "token" }, "-", { + expr: "exports[x]" + }) + }`, + "x" + )}); exportsWithDashes.forEach(${runtimeTemplate.expressionFunction( + `exports[x] = "--" + exports[x]`, + "x" + )}); ${ + RuntimeGlobals.makeNamespaceObject + }(exports); target[token] = (${runtimeTemplate.basicFunction( + "exports, module", + `module.exports = exports;` + )}).bind(null, exports); ${ + withHmr ? "moduleIds.push(token); " : "" + }token = ""; exports = {}; exportsWithId.length = 0; }`, + `else if(cc == ${cc("\\")}) { token += data[++i] }`, + `else { token += data[i]; }` + ]), + "}", + `${ + withHmr ? `if(target == ${RuntimeGlobals.moduleFactories}) ` : "" + }installedChunks[chunkId] = 0;`, + withHmr ? "return moduleIds;" : "" + ] + )}`, + 'var loadingAttribute = "data-webpack-loading";', + `var loadStylesheet = ${runtimeTemplate.basicFunction( + "chunkId, url, done" + (withHmr ? ", hmr" : ""), + [ + 'var link, needAttach, key = "chunk-" + chunkId;', + withHmr ? "if(!hmr) {" : "", + 'var links = document.getElementsByTagName("link");', + "for(var i = 0; i < links.length; i++) {", + Template.indent([ + "var l = links[i];", + `if(l.rel == "stylesheet" && (${ + withHmr + ? 'l.href.startsWith(url) || l.getAttribute("href").startsWith(url)' + : 'l.href == url || l.getAttribute("href") == url' + }${ + uniqueName + ? ' || l.getAttribute("data-webpack") == uniqueName + ":" + key' + : "" + })) { link = l; break; }` + ]), + "}", + "if(!done) return link;", + withHmr ? "}" : "", + "if(!link) {", + Template.indent([ + "needAttach = true;", + createStylesheet.call(code, this.chunk) + ]), + "}", + `var onLinkComplete = ${runtimeTemplate.basicFunction( + "prev, event", + Template.asString([ + "link.onerror = link.onload = null;", + "link.removeAttribute(loadingAttribute);", + "clearTimeout(timeout);", + 'if(event && event.type != "load") link.parentNode.removeChild(link)', + "done(event);", + "if(prev) return prev(event);" + ]) + )};`, + "if(link.getAttribute(loadingAttribute)) {", + Template.indent([ + `var timeout = setTimeout(onLinkComplete.bind(null, undefined, { type: 'timeout', target: link }), ${loadTimeout});`, + "link.onerror = onLinkComplete.bind(null, link.onerror);", + "link.onload = onLinkComplete.bind(null, link.onload);" + ]), + "} else onLinkComplete(undefined, { type: 'load', target: link });", // We assume any existing stylesheet is render blocking + withHmr ? "hmr ? document.head.insertBefore(link, hmr) :" : "", + "needAttach && document.head.appendChild(link);", + "return link;" + ] + )};`, + initialChunkIdsWithCss.size > 2 + ? `${JSON.stringify( + Array.from(initialChunkIdsWithCss) + )}.forEach(loadCssChunkData.bind(null, ${ + RuntimeGlobals.moduleFactories + }, 0));` + : initialChunkIdsWithCss.size > 0 + ? `${Array.from( + initialChunkIdsWithCss, + id => + `loadCssChunkData(${ + RuntimeGlobals.moduleFactories + }, 0, ${JSON.stringify(id)});` + ).join("")}` + : "// no initial css", + "", + withLoading + ? Template.asString([ + `${fn}.css = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasCssMatcher !== false + ? [ + "// css chunk loading", + `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + "", + '// a Promise means "currently loading".', + "if(installedChunkData) {", + Template.indent([ + "promises.push(installedChunkData[2]);" + ]), + "} else {", + Template.indent([ + hasCssMatcher === true + ? "if(true) { // all chunks have CSS" + : `if(${hasCssMatcher("chunkId")}) {`, + Template.indent([ + "// setup Promise in chunk cache", + `var promise = new Promise(${runtimeTemplate.expressionFunction( + `installedChunkData = installedChunks[chunkId] = [resolve, reject]`, + "resolve, reject" + )});`, + "promises.push(installedChunkData[2] = promise);", + "", + "// start chunk loading", + `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, + "// create error before stack unwound to get useful stacktrace later", + "var error = new Error();", + `var loadingEnded = ${runtimeTemplate.basicFunction( + "event", + [ + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`, + Template.indent([ + "installedChunkData = installedChunks[chunkId];", + "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;", + "if(installedChunkData) {", + Template.indent([ + 'if(event.type !== "load") {', + Template.indent([ + "var errorType = event && event.type;", + "var realSrc = event && event.target && event.target.src;", + "error.message = 'Loading css chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realSrc;", + "installedChunkData[1](error);" + ]), + "} else {", + Template.indent([ + `loadCssChunkData(${RuntimeGlobals.moduleFactories}, link, chunkId);`, + "installedChunkData[0]();" + ]), + "}" + ]), + "}" + ]), + "}" + ] + )};`, + "var link = loadStylesheet(chunkId, url, loadingEnded);" + ]), + "} else installedChunks[chunkId] = 0;" + ]), + "}" + ]), + "}" + ] + : "installedChunks[chunkId] = 0;" + )};` + ]) + : "// no chunk loading", + "", + withHmr + ? Template.asString([ + "var oldTags = [];", + "var newTags = [];", + `var applyHandler = ${runtimeTemplate.basicFunction("options", [ + `return { dispose: ${runtimeTemplate.basicFunction( + "", + [] + )}, apply: ${runtimeTemplate.basicFunction("", [ + "var moduleIds = [];", + `newTags.forEach(${runtimeTemplate.expressionFunction( + "info[1].sheet.disabled = false", + "info" + )});`, + "while(oldTags.length) {", + Template.indent([ + "var oldTag = oldTags.pop();", + "if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);" + ]), + "}", + "while(newTags.length) {", + Template.indent([ + `var info = newTags.pop();`, + `var chunkModuleIds = loadCssChunkData(${RuntimeGlobals.moduleFactories}, info[1], info[0]);`, + `chunkModuleIds.forEach(${runtimeTemplate.expressionFunction( + "moduleIds.push(id)", + "id" + )});` + ]), + "}", + "return moduleIds;" + ])} };` + ])}`, + `var cssTextKey = ${runtimeTemplate.returningFunction( + `Array.from(link.sheet.cssRules, ${runtimeTemplate.returningFunction( + "r.cssText", + "r" + )}).join()`, + "link" + )}`, + `${ + RuntimeGlobals.hmrDownloadUpdateHandlers + }.css = ${runtimeTemplate.basicFunction( + "chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList", + [ + "applyHandlers.push(applyHandler);", + `chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [ + `var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, + `var url = ${RuntimeGlobals.publicPath} + filename;`, + "var oldTag = loadStylesheet(chunkId, url);", + "if(!oldTag) return;", + `promises.push(new Promise(${runtimeTemplate.basicFunction( + "resolve, reject", + [ + `var link = loadStylesheet(chunkId, url + (url.indexOf("?") < 0 ? "?" : "&") + "hmr=" + Date.now(), ${runtimeTemplate.basicFunction( + "event", + [ + 'if(event.type !== "load") {', + Template.indent([ + "var errorType = event && event.type;", + "var realSrc = event && event.target && event.target.src;", + "error.message = 'Loading css hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realSrc;", + "reject(error);" + ]), + "} else {", + Template.indent([ + "try { if(cssTextKey(oldTag) == cssTextKey(link)) { if(link.parentNode) link.parentNode.removeChild(link); return resolve(); } } catch(e) {}", + "var factories = {};", + "loadCssChunkData(factories, link, chunkId);", + `Object.keys(factories).forEach(${runtimeTemplate.expressionFunction( + "updatedModulesList.push(id)", + "id" + )})`, + "link.sheet.disabled = true;", + "oldTags.push(oldTag);", + "newTags.push([chunkId, link]);", + "resolve();" + ]), + "}" + ] + )}, oldTag);` + ] + )}));` + ])});` + ] + )}` + ]) + : "// no hmr" + ]); } } -WorkerDependency.Template = class WorkerDependencyTemplate extends ( - ModuleDependency.Template -) { - /** - * @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 { chunkGraph, moduleGraph, runtimeRequirements } = templateContext; - const dep = /** @type {WorkerDependency} */ (dependency); - const block = /** @type {AsyncDependenciesBlock} */ ( - moduleGraph.getParentBlock(dependency) - ); - const entrypoint = /** @type {Entrypoint} */ ( - chunkGraph.getBlockChunkGroup(block) - ); - const chunk = entrypoint.getEntrypointChunk(); - - runtimeRequirements.add(RuntimeGlobals.publicPath); - runtimeRequirements.add(RuntimeGlobals.baseURI); - runtimeRequirements.add(RuntimeGlobals.getChunkScriptFilename); - - source.replace( - dep.range[0], - dep.range[1] - 1, - `/* worker import */ ${RuntimeGlobals.publicPath} + ${ - RuntimeGlobals.getChunkScriptFilename - }(${JSON.stringify(chunk.id)}), ${RuntimeGlobals.baseURI}` - ); - } -}; - -makeSerializable(WorkerDependency, "webpack/lib/dependencies/WorkerDependency"); - -module.exports = WorkerDependency; +module.exports = CssLoadingRuntimeModule; /***/ }), -/***/ 82509: +/***/ 47283: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -84466,53 +81275,78 @@ module.exports = WorkerDependency; -const { pathToFileURL } = __webpack_require__(57310); -const AsyncDependenciesBlock = __webpack_require__(47736); -const CommentCompilationWarning = __webpack_require__(98427); -const UnsupportedFeatureWarning = __webpack_require__(42495); -const EnableChunkLoadingPlugin = __webpack_require__(61291); -const { equals } = __webpack_require__(84953); +const { ConcatSource } = __webpack_require__(51255); +const HotUpdateChunk = __webpack_require__(9597); +const RuntimeGlobals = __webpack_require__(16475); +const SelfModuleFactory = __webpack_require__(63560); +const CssExportDependency = __webpack_require__(76760); +const CssImportDependency = __webpack_require__(90542); +const CssLocalIdentifierDependency = __webpack_require__(92328); +const CssSelfLocalIdentifierDependency = __webpack_require__(29094); +const CssUrlDependency = __webpack_require__(70749); +const StaticExportsDependency = __webpack_require__(91418); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); const createHash = __webpack_require__(49835); -const { contextify } = __webpack_require__(82186); -const EnableWasmLoadingPlugin = __webpack_require__(78613); -const ConstDependency = __webpack_require__(76911); -const CreateScriptUrlDependency = __webpack_require__(79062); -const { - harmonySpecifierTag -} = __webpack_require__(20862); -const WorkerDependency = __webpack_require__(1466); +const memoize = __webpack_require__(78676); +const CssExportsGenerator = __webpack_require__(91254); +const CssGenerator = __webpack_require__(46061); +const CssParser = __webpack_require__(98305); -/** @typedef {import("estree").Expression} Expression */ -/** @typedef {import("estree").ObjectExpression} ObjectExpression */ -/** @typedef {import("estree").Pattern} Pattern */ -/** @typedef {import("estree").Property} Property */ -/** @typedef {import("estree").SpreadElement} SpreadElement */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").CssExperimentOptions} CssExperimentOptions */ +/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */ -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ -/** @typedef {import("./HarmonyImportDependencyParserPlugin").HarmonySettings} HarmonySettings */ +/** @typedef {import("../Module")} Module */ -const getUrl = module => { - return pathToFileURL(module.resource).toString(); +const getCssLoadingRuntimeModule = memoize(() => + __webpack_require__(80806) +); + +const getSchema = name => { + const { definitions } = __webpack_require__(73342); + return { + definitions, + oneOf: [{ $ref: `#/definitions/${name}` }] + }; }; -const DEFAULT_SYNTAX = [ - "Worker", - "SharedWorker", - "navigator.serviceWorker.register()", - "Worker from worker_threads" -]; +const validateGeneratorOptions = createSchemaValidation( + __webpack_require__(59170), + () => getSchema("CssGeneratorOptions"), + { + name: "Css Modules Plugin", + baseDataPath: "parser" + } +); +const validateParserOptions = createSchemaValidation( + __webpack_require__(38542), + () => getSchema("CssParserOptions"), + { + name: "Css Modules Plugin", + baseDataPath: "parser" + } +); -/** @type {WeakMap} */ -const workerIndexMap = new WeakMap(); +const escapeCss = (str, omitOptionalUnderscore) => { + const escaped = `${str}`.replace( + // cspell:word uffff + /[^a-zA-Z0-9_\u0081-\uffff-]/g, + s => `\\${s}` + ); + return !omitOptionalUnderscore && /^(?!--)[0-9_-]/.test(escaped) + ? `_${escaped}` + : escaped; +}; -class WorkerPlugin { - constructor(chunkLoading, wasmLoading, module) { - this._chunkLoading = chunkLoading; - this._wasmLoading = wasmLoading; - this._module = module; +const plugin = "CssModulesPlugin"; + +class CssModulesPlugin { + /** + * @param {CssExperimentOptions} options options + */ + constructor({ exportsOnly = false }) { + this._exportsOnly = exportsOnly; } /** * Apply the plugin @@ -84520,2234 +81354,2143 @@ class WorkerPlugin { * @returns {void} */ apply(compiler) { - if (this._chunkLoading) { - new EnableChunkLoadingPlugin(this._chunkLoading).apply(compiler); - } - if (this._wasmLoading) { - new EnableWasmLoadingPlugin(this._wasmLoading).apply(compiler); - } - const cachedContextify = contextify.bindContextCache( - compiler.context, - compiler.root - ); - compiler.hooks.thisCompilation.tap( - "WorkerPlugin", + compiler.hooks.compilation.tap( + plugin, (compilation, { normalModuleFactory }) => { + const selfFactory = new SelfModuleFactory(compilation.moduleGraph); compilation.dependencyFactories.set( - WorkerDependency, + CssUrlDependency, normalModuleFactory ); compilation.dependencyTemplates.set( - WorkerDependency, - new WorkerDependency.Template() + CssUrlDependency, + new CssUrlDependency.Template() ); compilation.dependencyTemplates.set( - CreateScriptUrlDependency, - new CreateScriptUrlDependency.Template() + CssLocalIdentifierDependency, + new CssLocalIdentifierDependency.Template() + ); + compilation.dependencyFactories.set( + CssSelfLocalIdentifierDependency, + selfFactory + ); + compilation.dependencyTemplates.set( + CssSelfLocalIdentifierDependency, + new CssSelfLocalIdentifierDependency.Template() + ); + compilation.dependencyTemplates.set( + CssExportDependency, + new CssExportDependency.Template() + ); + compilation.dependencyFactories.set( + CssImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CssImportDependency, + new CssImportDependency.Template() + ); + compilation.dependencyTemplates.set( + StaticExportsDependency, + new StaticExportsDependency.Template() ); + normalModuleFactory.hooks.createParser + .for("css") + .tap(plugin, parserOptions => { + validateParserOptions(parserOptions); + return new CssParser(); + }); + normalModuleFactory.hooks.createParser + .for("css/global") + .tap(plugin, parserOptions => { + validateParserOptions(parserOptions); + return new CssParser({ + allowPseudoBlocks: false, + allowModeSwitch: false + }); + }); + normalModuleFactory.hooks.createParser + .for("css/module") + .tap(plugin, parserOptions => { + validateParserOptions(parserOptions); + return new CssParser({ + defaultMode: "local" + }); + }); + normalModuleFactory.hooks.createGenerator + .for("css") + .tap(plugin, generatorOptions => { + validateGeneratorOptions(generatorOptions); + return this._exportsOnly + ? new CssExportsGenerator() + : new CssGenerator(); + }); + normalModuleFactory.hooks.createGenerator + .for("css/global") + .tap(plugin, generatorOptions => { + validateGeneratorOptions(generatorOptions); + return this._exportsOnly + ? new CssExportsGenerator() + : new CssGenerator(); + }); + normalModuleFactory.hooks.createGenerator + .for("css/module") + .tap(plugin, generatorOptions => { + validateGeneratorOptions(generatorOptions); + return this._exportsOnly + ? new CssExportsGenerator() + : new CssGenerator(); + }); + const orderedCssModulesPerChunk = new WeakMap(); + compilation.hooks.afterCodeGeneration.tap("CssModulesPlugin", () => { + const { chunkGraph } = compilation; + for (const chunk of compilation.chunks) { + if (CssModulesPlugin.chunkHasCss(chunk, chunkGraph)) { + orderedCssModulesPerChunk.set( + chunk, + this.getOrderedChunkCssModules(chunk, chunkGraph, compilation) + ); + } + } + }); + compilation.hooks.contentHash.tap("CssModulesPlugin", chunk => { + const { + chunkGraph, + outputOptions: { + hashSalt, + hashDigest, + hashDigestLength, + hashFunction + } + } = compilation; + const modules = orderedCssModulesPerChunk.get(chunk); + if (modules === undefined) return; + const hash = createHash(hashFunction); + if (hashSalt) hash.update(hashSalt); + for (const module of modules) { + hash.update(chunkGraph.getModuleHash(module, chunk.runtime)); + } + const digest = /** @type {string} */ (hash.digest(hashDigest)); + chunk.contentHash.css = digest.substr(0, hashDigestLength); + }); + compilation.hooks.renderManifest.tap(plugin, (result, options) => { + const { chunkGraph } = compilation; + const { hash, chunk, codeGenerationResults } = options; - /** - * @param {JavascriptParser} parser the parser - * @param {Expression} expr expression - * @returns {[BasicEvaluatedExpression, [number, number]]} parsed - */ - const parseModuleUrl = (parser, expr) => { - if ( - expr.type !== "NewExpression" || - expr.callee.type === "Super" || - expr.arguments.length !== 2 - ) - return; - const [arg1, arg2] = expr.arguments; - if (arg1.type === "SpreadElement") return; - if (arg2.type === "SpreadElement") return; - const callee = parser.evaluateExpression(expr.callee); - if (!callee.isIdentifier() || callee.identifier !== "URL") return; - const arg2Value = parser.evaluateExpression(arg2); - if ( - !arg2Value.isString() || - !arg2Value.string.startsWith("file://") || - arg2Value.string !== getUrl(parser.state.module) - ) { + if (chunk instanceof HotUpdateChunk) return result; + + const modules = orderedCssModulesPerChunk.get(chunk); + if (modules !== undefined) { + result.push({ + render: () => + this.renderChunk({ + chunk, + chunkGraph, + codeGenerationResults, + uniqueName: compilation.outputOptions.uniqueName, + modules + }), + filenameTemplate: CssModulesPlugin.getChunkFilenameTemplate( + chunk, + compilation.outputOptions + ), + pathOptions: { + hash, + runtime: chunk.runtime, + chunk, + contentHashType: "css" + }, + identifier: `css${chunk.id}`, + hash: chunk.contentHash.css + }); + } + return result; + }); + const enabledChunks = new WeakSet(); + const handler = (chunk, set) => { + if (enabledChunks.has(chunk)) { return; } - const arg1Value = parser.evaluateExpression(arg1); - return [arg1Value, [arg1.range[0], arg2.range[1]]]; + enabledChunks.add(chunk); + + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getChunkCssFilename); + set.add(RuntimeGlobals.hasOwnProperty); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.makeNamespaceObject); + + const CssLoadingRuntimeModule = getCssLoadingRuntimeModule(); + compilation.addRuntimeModule(chunk, new CssLoadingRuntimeModule(set)); }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hasCssModules) + .tap(plugin, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(plugin, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap(plugin, handler); + } + ); + } - /** - * @param {JavascriptParser} parser the parser - * @param {ObjectExpression} expr expression - * @returns {{ expressions: Record, otherElements: (Property | SpreadElement)[], values: Record, spread: boolean, insertType: "comma" | "single", insertLocation: number }} parsed object - */ - const parseObjectExpression = (parser, expr) => { - /** @type {Record} */ - const values = {}; - /** @type {Record} */ - const expressions = {}; - /** @type {(Property | SpreadElement)[]} */ - const otherElements = []; - let spread = false; - for (const prop of expr.properties) { - if (prop.type === "SpreadElement") { - spread = true; - } else if ( - prop.type === "Property" && - !prop.method && - !prop.computed && - prop.key.type === "Identifier" - ) { - expressions[prop.key.name] = prop.value; - if (!prop.shorthand && !prop.value.type.endsWith("Pattern")) { - const value = parser.evaluateExpression( - /** @type {Expression} */ (prop.value) - ); - if (value.isCompileTimeValue()) - values[prop.key.name] = value.asCompileTimeValue(); - } - } else { - otherElements.push(prop); - } - } - const insertType = expr.properties.length > 0 ? "comma" : "single"; - const insertLocation = - expr.properties[expr.properties.length - 1].range[1]; + getModulesInOrder(chunk, modules, compilation) { + if (!modules) return []; + + const modulesList = [...modules]; + + // Get ordered list of modules per chunk group + // Lists are in reverse order to allow to use Array.pop() + const modulesByChunkGroup = Array.from(chunk.groupsIterable, chunkGroup => { + const sortedModules = modulesList + .map(module => { return { - expressions, - otherElements, - values, - spread, - insertType, - insertLocation + module, + index: chunkGroup.getModulePostOrderIndex(module) }; - }; + }) + .filter(item => item.index !== undefined) + .sort((a, b) => b.index - a.index) + .map(item => item.module); - /** - * @param {JavascriptParser} parser the parser - * @param {object} parserOptions options - */ - const parserPlugin = (parser, parserOptions) => { - if (parserOptions.worker === false) return; - const options = !Array.isArray(parserOptions.worker) - ? ["..."] - : parserOptions.worker; - const handleNewWorker = expr => { - if (expr.arguments.length === 0 || expr.arguments.length > 2) - return; - const [arg1, arg2] = expr.arguments; - if (arg1.type === "SpreadElement") return; - if (arg2 && arg2.type === "SpreadElement") return; - const parsedUrl = parseModuleUrl(parser, arg1); - if (!parsedUrl) return; - const [url, range] = parsedUrl; - if (!url.isString()) return; - const { - expressions, - otherElements, - values: options, - spread: hasSpreadInOptions, - insertType, - insertLocation - } = arg2 && arg2.type === "ObjectExpression" - ? parseObjectExpression(parser, arg2) - : { - expressions: {}, - otherElements: [], - values: {}, - spread: false, - insertType: arg2 ? "spread" : "argument", - insertLocation: arg2 ? arg2.range : arg1.range[1] - }; - const { options: importOptions, errors: commentErrors } = - parser.parseCommentOptions(expr.range); - - if (commentErrors) { - for (const e of commentErrors) { - const { comment } = e; - parser.state.module.addWarning( - new CommentCompilationWarning( - `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, - comment.loc - ) - ); - } - } - - /** @type {EntryOptions} */ - let entryOptions = {}; - - if (importOptions) { - if (importOptions.webpackIgnore !== undefined) { - if (typeof importOptions.webpackIgnore !== "boolean") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, - expr.loc - ) - ); - } else { - if (importOptions.webpackIgnore) { - return false; - } - } - } - if (importOptions.webpackEntryOptions !== undefined) { - if ( - typeof importOptions.webpackEntryOptions !== "object" || - importOptions.webpackEntryOptions === null - ) { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackEntryOptions\` expected a object, but received: ${importOptions.webpackEntryOptions}.`, - expr.loc - ) - ); - } else { - Object.assign( - entryOptions, - importOptions.webpackEntryOptions - ); - } - } - if (importOptions.webpackChunkName !== undefined) { - if (typeof importOptions.webpackChunkName !== "string") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, - expr.loc - ) - ); - } else { - entryOptions.name = importOptions.webpackChunkName; - } - } - } - - if ( - !Object.prototype.hasOwnProperty.call(entryOptions, "name") && - options && - typeof options.name === "string" - ) { - entryOptions.name = options.name; - } - - if (entryOptions.runtime === undefined) { - let i = workerIndexMap.get(parser.state) || 0; - workerIndexMap.set(parser.state, i + 1); - let name = `${cachedContextify( - parser.state.module.identifier() - )}|${i}`; - const hash = createHash(compilation.outputOptions.hashFunction); - hash.update(name); - const digest = /** @type {string} */ ( - hash.digest(compilation.outputOptions.hashDigest) - ); - entryOptions.runtime = digest.slice( - 0, - compilation.outputOptions.hashDigestLength - ); - } + return { list: sortedModules, set: new Set(sortedModules) }; + }); - const block = new AsyncDependenciesBlock({ - name: entryOptions.name, - entryOptions: { - chunkLoading: this._chunkLoading, - wasmLoading: this._wasmLoading, - ...entryOptions - } - }); - block.loc = expr.loc; - const dep = new WorkerDependency(url.string, range); - dep.loc = expr.loc; - block.addDependency(dep); - parser.state.module.addBlock(block); + if (modulesByChunkGroup.length === 1) + return modulesByChunkGroup[0].list.reverse(); - if (compilation.outputOptions.trustedTypes) { - const dep = new CreateScriptUrlDependency( - expr.arguments[0].range - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - } + const compareModuleLists = ({ list: a }, { list: b }) => { + if (a.length === 0) { + return b.length === 0 ? 0 : 1; + } else { + if (b.length === 0) return -1; + return compareModulesByIdentifier(a[a.length - 1], b[b.length - 1]); + } + }; - if (expressions.type) { - const expr = expressions.type; - if (options.type !== false) { - const dep = new ConstDependency( - this._module ? '"module"' : "undefined", - expr.range - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - expressions.type = undefined; - } - } else if (insertType === "comma") { - if (this._module || hasSpreadInOptions) { - const dep = new ConstDependency( - `, type: ${this._module ? '"module"' : "undefined"}`, - insertLocation - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - } - } else if (insertType === "spread") { - const dep1 = new ConstDependency( - "Object.assign({}, ", - insertLocation[0] - ); - const dep2 = new ConstDependency( - `, { type: ${this._module ? '"module"' : "undefined"} })`, - insertLocation[1] - ); - dep1.loc = expr.loc; - dep2.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep1); - parser.state.module.addPresentationalDependency(dep2); - } else if (insertType === "argument") { - if (this._module) { - const dep = new ConstDependency( - ', { type: "module" }', - insertLocation - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - } - } + modulesByChunkGroup.sort(compareModuleLists); - parser.walkExpression(expr.callee); - for (const key of Object.keys(expressions)) { - if (expressions[key]) parser.walkExpression(expressions[key]); - } - for (const prop of otherElements) { - parser.walkProperty(prop); - } - if (insertType === "spread") { - parser.walkExpression(arg2); - } + const finalModules = []; - return true; - }; - const processItem = item => { - if (item.endsWith("()")) { - parser.hooks.call - .for(item.slice(0, -2)) - .tap("WorkerPlugin", handleNewWorker); - } else { - const match = /^(.+?)(\(\))?\s+from\s+(.+)$/.exec(item); - if (match) { - const ids = match[1].split("."); - const call = match[2]; - const source = match[3]; - (call ? parser.hooks.call : parser.hooks.new) - .for(harmonySpecifierTag) - .tap("WorkerPlugin", expr => { - const settings = /** @type {HarmonySettings} */ ( - parser.currentTagData - ); - if ( - !settings || - settings.source !== source || - !equals(settings.ids, ids) - ) { - return; - } - return handleNewWorker(expr); - }); - } else { - parser.hooks.new.for(item).tap("WorkerPlugin", handleNewWorker); - } - } - }; - for (const item of options) { - if (item === "...") { - DEFAULT_SYNTAX.forEach(processItem); - } else processItem(item); + for (;;) { + const failedModules = new Set(); + const list = modulesByChunkGroup[0].list; + if (list.length === 0) { + // done, everything empty + break; + } + let selectedModule = list[list.length - 1]; + let hasFailed = undefined; + outer: for (;;) { + for (const { list, set } of modulesByChunkGroup) { + if (list.length === 0) continue; + const lastModule = list[list.length - 1]; + if (lastModule === selectedModule) continue; + if (!set.has(selectedModule)) continue; + failedModules.add(selectedModule); + if (failedModules.has(lastModule)) { + // There is a conflict, try other alternatives + hasFailed = lastModule; + continue; } - }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("WorkerPlugin", parserPlugin); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("WorkerPlugin", parserPlugin); + selectedModule = lastModule; + hasFailed = false; + continue outer; // restart + } + break; } - ); - } -} -module.exports = WorkerPlugin; - - -/***/ }), - -/***/ 50396: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -module.exports = expr => { - // - if ( - expr.type === "FunctionExpression" || - expr.type === "ArrowFunctionExpression" - ) { - return { - fn: expr, - expressions: [], - needThis: false - }; + if (hasFailed) { + // There is a not resolve-able conflict with the selectedModule + if (compilation) { + // TODO print better warning + compilation.warnings.push( + new Error( + `chunk ${ + chunk.name || chunk.id + }\nConflicting order between ${hasFailed.readableIdentifier( + compilation.requestShortener + )} and ${selectedModule.readableIdentifier( + compilation.requestShortener + )}` + ) + ); + } + selectedModule = hasFailed; + } + // Insert the selected module into the final modules list + finalModules.push(selectedModule); + // Remove the selected module from all lists + for (const { list, set } of modulesByChunkGroup) { + const lastModule = list[list.length - 1]; + if (lastModule === selectedModule) list.pop(); + else if (hasFailed && set.has(selectedModule)) { + const idx = list.indexOf(selectedModule); + if (idx >= 0) list.splice(idx, 1); + } + } + modulesByChunkGroup.sort(compareModuleLists); + } + return finalModules; } - // .bind() - if ( - expr.type === "CallExpression" && - expr.callee.type === "MemberExpression" && - expr.callee.object.type === "FunctionExpression" && - expr.callee.property.type === "Identifier" && - expr.callee.property.name === "bind" && - expr.arguments.length === 1 - ) { - return { - fn: expr.callee.object, - expressions: [expr.arguments[0]], - needThis: undefined - }; - } - // (function(_this) {return })(this) (Coffeescript) - if ( - expr.type === "CallExpression" && - expr.callee.type === "FunctionExpression" && - expr.callee.body.type === "BlockStatement" && - expr.arguments.length === 1 && - expr.arguments[0].type === "ThisExpression" && - expr.callee.body.body && - expr.callee.body.body.length === 1 && - expr.callee.body.body[0].type === "ReturnStatement" && - expr.callee.body.body[0].argument && - expr.callee.body.body[0].argument.type === "FunctionExpression" - ) { - return { - fn: expr.callee.body.body[0].argument, - expressions: [], - needThis: true - }; + getOrderedChunkCssModules(chunk, chunkGraph, compilation) { + return [ + ...this.getModulesInOrder( + chunk, + chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "css-import", + compareModulesByIdentifier + ), + compilation + ), + ...this.getModulesInOrder( + chunk, + chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "css", + compareModulesByIdentifier + ), + compilation + ) + ]; } -}; - - -/***/ }), - -/***/ 55207: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const { UsageState } = __webpack_require__(63686); - -/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + renderChunk({ + uniqueName, + chunk, + chunkGraph, + codeGenerationResults, + modules + }) { + const source = new ConcatSource(); + const metaData = []; + for (const module of modules) { + try { + const codeGenResult = codeGenerationResults.get(module, chunk.runtime); -/** - * @param {RuntimeSpec} runtime the runtime - * @param {string[][]} referencedExports list of referenced exports, will be added to - * @param {string[]} prefix export prefix - * @param {ExportInfo=} exportInfo the export info - * @param {boolean} defaultPointsToSelf when true, using default will reference itself - * @param {Set} alreadyVisited already visited export info (to handle circular reexports) - */ -const processExportInfo = ( - runtime, - referencedExports, - prefix, - exportInfo, - defaultPointsToSelf = false, - alreadyVisited = new Set() -) => { - if (!exportInfo) { - referencedExports.push(prefix); - return; - } - const used = exportInfo.getUsed(runtime); - if (used === UsageState.Unused) return; - if (alreadyVisited.has(exportInfo)) { - referencedExports.push(prefix); - return; - } - alreadyVisited.add(exportInfo); - if ( - used !== UsageState.OnlyPropertiesUsed || - !exportInfo.exportsInfo || - exportInfo.exportsInfo.otherExportsInfo.getUsed(runtime) !== - UsageState.Unused - ) { - alreadyVisited.delete(exportInfo); - referencedExports.push(prefix); - return; - } - const exportsInfo = exportInfo.exportsInfo; - for (const exportInfo of exportsInfo.orderedExports) { - processExportInfo( - runtime, - referencedExports, - defaultPointsToSelf && exportInfo.name === "default" - ? prefix - : prefix.concat(exportInfo.name), - exportInfo, - false, - alreadyVisited + const s = + codeGenResult.sources.get("css") || + codeGenResult.sources.get("css-import"); + if (s) { + source.add(s); + source.add("\n"); + } + const exports = + codeGenResult.data && codeGenResult.data.get("css-exports"); + const moduleId = chunkGraph.getModuleId(module) + ""; + metaData.push( + `${ + exports + ? Array.from(exports, ([n, v]) => { + const shortcutValue = `${ + uniqueName ? uniqueName + "-" : "" + }${moduleId}-${n}`; + return v === shortcutValue + ? `${escapeCss(n)}/` + : v === "--" + shortcutValue + ? `${escapeCss(n)}%` + : `${escapeCss(n)}(${escapeCss(v)})`; + }).join("") + : "" + }${escapeCss(moduleId)}` + ); + } catch (e) { + e.message += `\nduring rendering of css ${module.identifier()}`; + throw e; + } + } + source.add( + `head{--webpack-${escapeCss( + (uniqueName ? uniqueName + "-" : "") + chunk.id, + true + )}:${metaData.join(",")};}` ); + return source; } - alreadyVisited.delete(exportInfo); -}; -module.exports = processExportInfo; - - -/***/ }), - -/***/ 32277: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const ExternalsPlugin = __webpack_require__(6652); - -/** @typedef {import("../Compiler")} Compiler */ - -class ElectronTargetPlugin { - /** - * @param {"main" | "preload" | "renderer"=} context in main, preload or renderer context? - */ - constructor(context) { - this._context = context; - } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - new ExternalsPlugin("node-commonjs", [ - "clipboard", - "crash-reporter", - "electron", - "ipc", - "native-image", - "original-fs", - "screen", - "shell" - ]).apply(compiler); - switch (this._context) { - case "main": - new ExternalsPlugin("node-commonjs", [ - "app", - "auto-updater", - "browser-window", - "content-tracing", - "dialog", - "global-shortcut", - "ipc-main", - "menu", - "menu-item", - "power-monitor", - "power-save-blocker", - "protocol", - "session", - "tray", - "web-contents" - ]).apply(compiler); - break; - case "preload": - case "renderer": - new ExternalsPlugin("node-commonjs", [ - "desktop-capturer", - "ipc-renderer", - "remote", - "web-frame" - ]).apply(compiler); - break; + static getChunkFilenameTemplate(chunk, outputOptions) { + if (chunk.cssFilenameTemplate) { + return chunk.cssFilenameTemplate; + } else if (chunk.canBeInitial()) { + return outputOptions.cssFilename; + } else { + return outputOptions.cssChunkFilename; } } -} - -module.exports = ElectronTargetPlugin; - - -/***/ }), - -/***/ 22273: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const WebpackError = __webpack_require__(53799); - -/** @typedef {import("../Module")} Module */ - -class BuildCycleError extends WebpackError { - /** - * Creates an instance of ModuleDependencyError. - * @param {Module} module the module starting the cycle - */ - constructor(module) { - super( - "There is a circular build dependency, which makes it impossible to create this module" + static chunkHasCss(chunk, chunkGraph) { + return ( + !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css") || + !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css-import") ); - - this.name = "BuildCycleError"; - this.module = module; } } -module.exports = BuildCycleError; +module.exports = CssModulesPlugin; /***/ }), -/***/ 5294: +/***/ 98305: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeModule = __webpack_require__(16963); +const Parser = __webpack_require__(11715); +const ConstDependency = __webpack_require__(76911); +const CssExportDependency = __webpack_require__(76760); +const CssImportDependency = __webpack_require__(90542); +const CssLocalIdentifierDependency = __webpack_require__(92328); +const CssSelfLocalIdentifierDependency = __webpack_require__(29094); +const CssUrlDependency = __webpack_require__(70749); +const StaticExportsDependency = __webpack_require__(91418); +const walkCssTokens = __webpack_require__(44124); -class ExportWebpackRequireRuntimeModule extends RuntimeModule { - constructor() { - super("export webpack runtime", RuntimeModule.STAGE_ATTACH); - } +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ - /** - * @returns {boolean} true, if the runtime module should get it's own scope - */ - shouldIsolate() { - return false; +const CC_LEFT_CURLY = "{".charCodeAt(0); +const CC_RIGHT_CURLY = "}".charCodeAt(0); +const CC_COLON = ":".charCodeAt(0); +const CC_SLASH = "/".charCodeAt(0); +const CC_SEMICOLON = ";".charCodeAt(0); + +const cssUnescape = str => { + return str.replace(/\\([0-9a-fA-F]{1,6}[ \t\n\r\f]?|[\s\S])/g, match => { + if (match.length > 2) { + return String.fromCharCode(parseInt(match.slice(1).trim(), 16)); + } else { + return match[1]; + } + }); +}; + +class LocConverter { + constructor(input) { + this._input = input; + this.line = 1; + this.column = 0; + this.pos = 0; } - /** - * @returns {string} runtime code - */ - generate() { - return "export default __webpack_require__;"; + get(pos) { + if (this.pos !== pos) { + if (this.pos < pos) { + const str = this._input.slice(this.pos, pos); + let i = str.lastIndexOf("\n"); + if (i === -1) { + this.column += str.length; + } else { + this.column = str.length - i - 1; + this.line++; + while (i > 0 && (i = str.lastIndexOf("\n", i - 1)) !== -1) + this.line++; + } + } else { + let i = this._input.lastIndexOf("\n", this.pos); + while (i >= pos) { + this.line--; + i = i > 0 ? this._input.lastIndexOf("\n", i - 1) : -1; + } + this.column = pos - i; + } + this.pos = pos; + } + return this; } } -module.exports = ExportWebpackRequireRuntimeModule; - - -/***/ }), - -/***/ 68927: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - +const CSS_MODE_TOP_LEVEL = 0; +const CSS_MODE_IN_RULE = 1; +const CSS_MODE_IN_LOCAL_RULE = 2; +const CSS_MODE_AT_IMPORT_EXPECT_URL = 3; +// TODO implement layer and supports for @import +const CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS = 4; +const CSS_MODE_AT_IMPORT_EXPECT_MEDIA = 5; +const CSS_MODE_AT_OTHER = 6; -const { ConcatSource } = __webpack_require__(51255); -const { RuntimeGlobals } = __webpack_require__(91919); -const HotUpdateChunk = __webpack_require__(9597); -const Template = __webpack_require__(1626); -const { getAllChunks } = __webpack_require__(91145); -const { - getCompilationHooks, - getChunkFilenameTemplate -} = __webpack_require__(89464); -const { updateHashForEntryStartup } = __webpack_require__(98124); +const explainMode = mode => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: + return "parsing top level css"; + case CSS_MODE_IN_RULE: + return "parsing css rule content (global)"; + case CSS_MODE_IN_LOCAL_RULE: + return "parsing css rule content (local)"; + case CSS_MODE_AT_IMPORT_EXPECT_URL: + return "parsing @import (expecting url)"; + case CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS: + return "parsing @import (expecting optionally supports or media query)"; + case CSS_MODE_AT_IMPORT_EXPECT_MEDIA: + return "parsing @import (expecting optionally media query)"; + case CSS_MODE_AT_OTHER: + return "parsing at-rule"; + default: + return mode; + } +}; -/** @typedef {import("../Compiler")} Compiler */ +class CssParser extends Parser { + constructor({ + allowPseudoBlocks = true, + allowModeSwitch = true, + defaultMode = "global" + } = {}) { + super(); + this.allowPseudoBlocks = allowPseudoBlocks; + this.allowModeSwitch = allowModeSwitch; + this.defaultMode = defaultMode; + } -class ModuleChunkFormatPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "ModuleChunkFormatPlugin", - compilation => { - compilation.hooks.additionalChunkRuntimeRequirements.tap( - "ModuleChunkFormatPlugin", - (chunk, set) => { - if (chunk.hasRuntime()) return; - if (compilation.chunkGraph.getNumberOfEntryModules(chunk) > 0) { - set.add(RuntimeGlobals.require); - set.add(RuntimeGlobals.startupEntrypoint); - set.add(RuntimeGlobals.externalInstallChunk); - } - } - ); - const hooks = getCompilationHooks(compilation); - hooks.renderChunk.tap( - "ModuleChunkFormatPlugin", - (modules, renderContext) => { - const { chunk, chunkGraph, runtimeTemplate } = renderContext; - const hotUpdateChunk = - chunk instanceof HotUpdateChunk ? chunk : null; - const source = new ConcatSource(); - if (hotUpdateChunk) { - throw new Error( - "HMR is not implemented for module chunk format yet" - ); - } else { - source.add(`export const id = ${JSON.stringify(chunk.id)};\n`); - source.add(`export const ids = ${JSON.stringify(chunk.ids)};\n`); - source.add(`export const modules = `); - source.add(modules); - source.add(`;\n`); - const runtimeModules = - chunkGraph.getChunkRuntimeModulesInOrder(chunk); - if (runtimeModules.length > 0) { - source.add("export const runtime =\n"); - source.add( - Template.renderChunkRuntimeModules( - runtimeModules, - renderContext - ) - ); - } - const entries = Array.from( - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) - ); - if (entries.length > 0) { - const runtimeChunk = entries[0][1].getRuntimeChunk(); - const currentOutputName = compilation - .getPath( - getChunkFilenameTemplate(chunk, compilation.outputOptions), - { - chunk, - contentHashType: "javascript" - } - ) - .split("/"); - - // remove filename, we only need the directory - currentOutputName.pop(); - - const getRelativePath = chunk => { - const baseOutputName = currentOutputName.slice(); - const chunkOutputName = compilation - .getPath( - getChunkFilenameTemplate( - chunk, - compilation.outputOptions - ), - { - chunk: chunk, - contentHashType: "javascript" - } - ) - .split("/"); - - // remove common parts - while ( - baseOutputName.length > 0 && - chunkOutputName.length > 0 && - baseOutputName[0] === chunkOutputName[0] - ) { - baseOutputName.shift(); - chunkOutputName.shift(); - } - // create final path - return ( - (baseOutputName.length > 0 - ? "../".repeat(baseOutputName.length) - : "./") + chunkOutputName.join("/") - ); - }; - - const entrySource = new ConcatSource(); - entrySource.add(source); - entrySource.add(";\n\n// load runtime\n"); - entrySource.add( - `import __webpack_require__ from ${JSON.stringify( - getRelativePath(runtimeChunk) - )};\n` - ); + parse(source, state) { + if (Buffer.isBuffer(source)) { + source = source.toString("utf-8"); + } else if (typeof source === "object") { + throw new Error("webpackAst is unexpected for the CssParser"); + } + if (source[0] === "\ufeff") { + source = source.slice(1); + } - const startupSource = new ConcatSource(); - startupSource.add( - `var __webpack_exec__ = ${runtimeTemplate.returningFunction( - `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)`, - "moduleId" - )}\n` - ); + const module = state.module; - const loadedChunks = new Set(); - let index = 0; - for (let i = 0; i < entries.length; i++) { - const [module, entrypoint] = entries[i]; - const final = i + 1 === entries.length; - const moduleId = chunkGraph.getModuleId(module); - const chunks = getAllChunks( - entrypoint, - runtimeChunk, - undefined - ); - for (const chunk of chunks) { - if (loadedChunks.has(chunk)) continue; - loadedChunks.add(chunk); - startupSource.add( - `import * as __webpack_chunk_${index}__ from ${JSON.stringify( - getRelativePath(chunk) - )};\n` - ); - startupSource.add( - `${RuntimeGlobals.externalInstallChunk}(__webpack_chunk_${index}__);\n` - ); - index++; - } - startupSource.add( - `${ - final ? "var __webpack_exports__ = " : "" - }__webpack_exec__(${JSON.stringify(moduleId)});\n` - ); - } + const declaredCssVariables = new Set(); - entrySource.add( - hooks.renderStartup.call( - startupSource, - entries[entries.length - 1][0], - { - ...renderContext, - inlined: false - } - ) - ); - return entrySource; - } - } - return source; + const locConverter = new LocConverter(source); + let mode = CSS_MODE_TOP_LEVEL; + let modePos = 0; + let modeNestingLevel = 0; + let modeData = undefined; + let singleClassSelector = undefined; + let lastIdentifier = undefined; + const modeStack = []; + const isTopLevelLocal = () => + modeData === "local" || + (this.defaultMode === "local" && modeData === undefined); + const eatWhiteLine = (input, pos) => { + for (;;) { + const cc = input.charCodeAt(pos); + if (cc === 32 || cc === 9) { + pos++; + continue; + } + if (cc === 10) pos++; + break; + } + return pos; + }; + const eatUntil = chars => { + const charCodes = Array.from({ length: chars.length }, (_, i) => + chars.charCodeAt(i) + ); + const arr = Array.from( + { length: charCodes.reduce((a, b) => Math.max(a, b), 0) + 1 }, + () => false + ); + charCodes.forEach(cc => (arr[cc] = true)); + return (input, pos) => { + for (;;) { + const cc = input.charCodeAt(pos); + if (cc < arr.length && arr[cc]) { + return pos; } - ); - hooks.chunkHash.tap( - "ModuleChunkFormatPlugin", - (chunk, hash, { chunkGraph, runtimeTemplate }) => { - if (chunk.hasRuntime()) return; - hash.update("ModuleChunkFormatPlugin"); - hash.update("1"); - const entries = Array.from( - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) - ); - updateHashForEntryStartup(hash, chunkGraph, entries, chunk); + pos++; + if (pos === input.length) return pos; + } + }; + }; + const eatText = (input, pos, eater) => { + let text = ""; + for (;;) { + if (input.charCodeAt(pos) === CC_SLASH) { + const newPos = walkCssTokens.eatComments(input, pos); + if (pos !== newPos) { + pos = newPos; + if (pos === input.length) break; + } else { + text += "/"; + pos++; + if (pos === input.length) break; } - ); + } + const newPos = eater(input, pos); + if (pos !== newPos) { + text += input.slice(pos, newPos); + pos = newPos; + } else { + break; + } + if (pos === input.length) break; } - ); - } -} - -module.exports = ModuleChunkFormatPlugin; - - -/***/ }), - -/***/ 89831: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const ExportWebpackRequireRuntimeModule = __webpack_require__(5294); -const ModuleChunkLoadingRuntimeModule = __webpack_require__(64747); - -/** @typedef {import("../Compiler")} Compiler */ - -class ModuleChunkLoadingPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "ModuleChunkLoadingPlugin", - compilation => { - const globalChunkLoading = compilation.outputOptions.chunkLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const chunkLoading = - (options && options.chunkLoading) || globalChunkLoading; - return chunkLoading === "import"; - }; - const onceForChunkSet = new WeakSet(); - const handler = (chunk, set) => { - if (onceForChunkSet.has(chunk)) return; - onceForChunkSet.add(chunk); - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.hasOwnProperty); - compilation.addRuntimeModule( - chunk, - new ModuleChunkLoadingRuntimeModule(set) + return [pos, text.trimRight()]; + }; + const eatExportName = eatUntil(":};/"); + const eatExportValue = eatUntil("};/"); + const parseExports = (input, pos) => { + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + const cc = input.charCodeAt(pos); + if (cc !== CC_LEFT_CURLY) + throw new Error( + `Unexpected ${input[pos]} at ${pos} during parsing of ':export' (expected '{')` + ); + pos++; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + for (;;) { + if (input.charCodeAt(pos) === CC_RIGHT_CURLY) break; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + if (pos === input.length) return pos; + let start = pos; + let name; + [pos, name] = eatText(input, pos, eatExportName); + if (pos === input.length) return pos; + if (input.charCodeAt(pos) !== CC_COLON) { + throw new Error( + `Unexpected ${input[pos]} at ${pos} during parsing of export name in ':export' (expected ':')` ); - }; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("ModuleChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.baseURI) - .tap("ModuleChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.externalInstallChunk) - .tap("ModuleChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.onChunksLoaded) - .tap("ModuleChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.externalInstallChunk) - .tap("ModuleChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - compilation.addRuntimeModule( - chunk, - new ExportWebpackRequireRuntimeModule() + } + pos++; + if (pos === input.length) return pos; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + if (pos === input.length) return pos; + let value; + [pos, value] = eatText(input, pos, eatExportValue); + if (pos === input.length) return pos; + const cc = input.charCodeAt(pos); + if (cc === CC_SEMICOLON) { + pos++; + if (pos === input.length) return pos; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + if (pos === input.length) return pos; + } else if (cc !== CC_RIGHT_CURLY) { + throw new Error( + `Unexpected ${input[pos]} at ${pos} during parsing of export value in ':export' (expected ';' or '}')` + ); + } + const dep = new CssExportDependency(name, value); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(pos); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + } + pos++; + if (pos === input.length) return pos; + pos = eatWhiteLine(input, pos); + return pos; + }; + const eatPropertyName = eatUntil(":{};"); + const processLocalDeclaration = (input, pos) => { + modeData = undefined; + const start = pos; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + const propertyNameStart = pos; + const [propertyNameEnd, propertyName] = eatText( + input, + pos, + eatPropertyName + ); + if (input.charCodeAt(propertyNameEnd) !== CC_COLON) return start; + pos = propertyNameEnd + 1; + if (propertyName.startsWith("--")) { + // CSS Variable + const { line: sl, column: sc } = locConverter.get(propertyNameStart); + const { line: el, column: ec } = locConverter.get(propertyNameEnd); + const name = propertyName.slice(2); + const dep = new CssLocalIdentifierDependency( + name, + [propertyNameStart, propertyNameEnd], + "--" + ); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + declaredCssVariables.add(name); + } else if ( + propertyName === "animation-name" || + propertyName === "animation" + ) { + modeData = "animation"; + lastIdentifier = undefined; + } + return pos; + }; + const processDeclarationValueDone = (input, pos) => { + if (modeData === "animation" && lastIdentifier) { + const { line: sl, column: sc } = locConverter.get(lastIdentifier[0]); + const { line: el, column: ec } = locConverter.get(lastIdentifier[1]); + const name = input.slice(lastIdentifier[0], lastIdentifier[1]); + const dep = new CssSelfLocalIdentifierDependency(name, lastIdentifier); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + } + }; + const eatKeyframes = eatUntil("{};/"); + const eatNameInVar = eatUntil(",)};/"); + walkCssTokens(source, { + isSelector: () => { + return mode !== CSS_MODE_IN_RULE && mode !== CSS_MODE_IN_LOCAL_RULE; + }, + url: (input, start, end, contentStart, contentEnd) => { + const value = cssUnescape(input.slice(contentStart, contentEnd)); + switch (mode) { + case CSS_MODE_AT_IMPORT_EXPECT_URL: { + modeData.url = value; + mode = CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS; + break; + } + case CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS: + case CSS_MODE_AT_IMPORT_EXPECT_MEDIA: + throw new Error( + `Unexpected ${input.slice( + start, + end + )} at ${start} during ${explainMode(mode)}` ); - }); - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("ModuleChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.getChunkScriptFilename); - }); + default: { + const dep = new CssUrlDependency(value, [start, end], "url"); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + module.addCodeGenerationDependency(dep); + break; + } + } + return end; + }, + string: (input, start, end) => { + switch (mode) { + case CSS_MODE_AT_IMPORT_EXPECT_URL: { + modeData.url = cssUnescape(input.slice(start + 1, end - 1)); + mode = CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS; + break; + } + } + return end; + }, + atKeyword: (input, start, end) => { + const name = input.slice(start, end); + if (name === "@namespace") { + throw new Error("@namespace is not supported in bundled CSS"); + } + if (name === "@import") { + if (mode !== CSS_MODE_TOP_LEVEL) { + throw new Error( + `Unexpected @import at ${start} during ${explainMode(mode)}` + ); + } + mode = CSS_MODE_AT_IMPORT_EXPECT_URL; + modePos = end; + modeData = { + start: start, + url: undefined, + supports: undefined + }; + } + if (name === "@keyframes") { + let pos = end; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + if (pos === input.length) return pos; + const [newPos, name] = eatText(input, pos, eatKeyframes); + const { line: sl, column: sc } = locConverter.get(pos); + const { line: el, column: ec } = locConverter.get(newPos); + const dep = new CssLocalIdentifierDependency(name, [pos, newPos]); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + pos = newPos; + if (pos === input.length) return pos; + if (input.charCodeAt(pos) !== CC_LEFT_CURLY) { + throw new Error( + `Unexpected ${input[pos]} at ${pos} during parsing of @keyframes (expected '{')` + ); + } + mode = CSS_MODE_IN_LOCAL_RULE; + modeNestingLevel = 1; + return pos + 1; + } + return end; + }, + semicolon: (input, start, end) => { + switch (mode) { + case CSS_MODE_AT_IMPORT_EXPECT_URL: + throw new Error(`Expected URL for @import at ${start}`); + case CSS_MODE_AT_IMPORT_EXPECT_MEDIA: + case CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS: { + const { line: sl, column: sc } = locConverter.get(modeData.start); + const { line: el, column: ec } = locConverter.get(end); + end = eatWhiteLine(input, end); + const media = input.slice(modePos, start).trim(); + const dep = new CssImportDependency( + modeData.url, + [modeData.start, end], + modeData.supports, + media + ); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + break; + } + case CSS_MODE_IN_LOCAL_RULE: { + processDeclarationValueDone(input, start); + return processLocalDeclaration(input, end); + } + case CSS_MODE_IN_RULE: { + return end; + } + } + mode = CSS_MODE_TOP_LEVEL; + modeData = undefined; + singleClassSelector = undefined; + return end; + }, + leftCurlyBracket: (input, start, end) => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: + mode = isTopLevelLocal() + ? CSS_MODE_IN_LOCAL_RULE + : CSS_MODE_IN_RULE; + modeNestingLevel = 1; + if (mode === CSS_MODE_IN_LOCAL_RULE) + return processLocalDeclaration(input, end); + break; + case CSS_MODE_IN_RULE: + case CSS_MODE_IN_LOCAL_RULE: + modeNestingLevel++; + break; + } + return end; + }, + rightCurlyBracket: (input, start, end) => { + switch (mode) { + case CSS_MODE_IN_LOCAL_RULE: + processDeclarationValueDone(input, start); + /* falls through */ + case CSS_MODE_IN_RULE: + if (--modeNestingLevel === 0) { + mode = CSS_MODE_TOP_LEVEL; + modeData = undefined; + singleClassSelector = undefined; + } + break; + } + return end; + }, + id: (input, start, end) => { + singleClassSelector = false; + switch (mode) { + case CSS_MODE_TOP_LEVEL: + if (isTopLevelLocal()) { + const name = input.slice(start + 1, end); + const dep = new CssLocalIdentifierDependency(name, [ + start + 1, + end + ]); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + } + break; + } + return end; + }, + identifier: (input, start, end) => { + singleClassSelector = false; + switch (mode) { + case CSS_MODE_IN_LOCAL_RULE: + if (modeData === "animation") { + lastIdentifier = [start, end]; + } + break; + } + return end; + }, + class: (input, start, end) => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: { + if (isTopLevelLocal()) { + const name = input.slice(start + 1, end); + const dep = new CssLocalIdentifierDependency(name, [ + start + 1, + end + ]); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + if (singleClassSelector === undefined) singleClassSelector = name; + } else { + singleClassSelector = false; + } + break; + } + } + return end; + }, + leftParenthesis: (input, start, end) => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: { + modeStack.push(false); + break; + } + } + return end; + }, + rightParenthesis: (input, start, end) => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: { + const newModeData = modeStack.pop(); + if (newModeData !== false) { + modeData = newModeData; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + } + break; + } + } + return end; + }, + pseudoClass: (input, start, end) => { + singleClassSelector = false; + switch (mode) { + case CSS_MODE_TOP_LEVEL: { + const name = input.slice(start, end); + if (this.allowModeSwitch && name === ":global") { + modeData = "global"; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + } else if (this.allowModeSwitch && name === ":local") { + modeData = "local"; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + } else if (this.allowPseudoBlocks && name === ":export") { + const pos = parseExports(input, end); + const dep = new ConstDependency("", [start, pos]); + module.addPresentationalDependency(dep); + return pos; + } + break; + } + } + return end; + }, + pseudoFunction: (input, start, end) => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: { + const name = input.slice(start, end - 1); + if (this.allowModeSwitch && name === ":global") { + modeStack.push(modeData); + modeData = "global"; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + } else if (this.allowModeSwitch && name === ":local") { + modeStack.push(modeData); + modeData = "local"; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + } else { + modeStack.push(false); + } + break; + } + } + return end; + }, + function: (input, start, end) => { + switch (mode) { + case CSS_MODE_IN_LOCAL_RULE: { + const name = input.slice(start, end - 1); + if (name === "var") { + let pos = walkCssTokens.eatWhitespaceAndComments(input, end); + if (pos === input.length) return pos; + const [newPos, name] = eatText(input, pos, eatNameInVar); + if (!name.startsWith("--")) return end; + const { line: sl, column: sc } = locConverter.get(pos); + const { line: el, column: ec } = locConverter.get(newPos); + const dep = new CssSelfLocalIdentifierDependency( + name.slice(2), + [pos, newPos], + "--", + declaredCssVariables + ); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + return newPos; + } + break; + } + } + return end; + }, + comma: (input, start, end) => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: + modeData = undefined; + modeStack.length = 0; + break; + case CSS_MODE_IN_LOCAL_RULE: + processDeclarationValueDone(input, start); + break; + } + return end; } - ); + }); + + module.buildInfo.strict = true; + module.buildMeta.exportsType = "namespace"; + module.addDependency(new StaticExportsDependency([], true)); + return state; } } -module.exports = ModuleChunkLoadingPlugin; +module.exports = CssParser; /***/ }), -/***/ 64747: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 44124: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const { SyncWaterfallHook } = __webpack_require__(6967); -const Compilation = __webpack_require__(85720); -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); -const { - getChunkFilenameTemplate, - chunkHasJs -} = __webpack_require__(89464); -const { getInitialChunkIds } = __webpack_require__(98124); -const compileBooleanMatcher = __webpack_require__(29404); -const { getUndoPath } = __webpack_require__(82186); - -/** @typedef {import("../Chunk")} Chunk */ - /** - * @typedef {Object} JsonpCompilationPluginHooks - * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload - * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch + * @typedef {Object} CssTokenCallbacks + * @property {function(string, number): boolean} isSelector + * @property {function(string, number, number, number, number): number=} url + * @property {function(string, number, number): number=} string + * @property {function(string, number, number): number=} leftParenthesis + * @property {function(string, number, number): number=} rightParenthesis + * @property {function(string, number, number): number=} pseudoFunction + * @property {function(string, number, number): number=} function + * @property {function(string, number, number): number=} pseudoClass + * @property {function(string, number, number): number=} atKeyword + * @property {function(string, number, number): number=} class + * @property {function(string, number, number): number=} identifier + * @property {function(string, number, number): number=} id + * @property {function(string, number, number): number=} leftCurlyBracket + * @property {function(string, number, number): number=} rightCurlyBracket + * @property {function(string, number, number): number=} semicolon + * @property {function(string, number, number): number=} comma */ -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); +/** @typedef {function(string, number, CssTokenCallbacks): number} CharHandler */ -class ModuleChunkLoadingRuntimeModule extends RuntimeModule { - /** - * @param {Compilation} compilation the compilation - * @returns {JsonpCompilationPluginHooks} 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 = { - linkPreload: new SyncWaterfallHook(["source", "chunk"]), - linkPrefetch: new SyncWaterfallHook(["source", "chunk"]) - }; - compilationHooksMap.set(compilation, hooks); - } - return hooks; - } +// spec: https://drafts.csswg.org/css-syntax/ - constructor(runtimeRequirements) { - super("import chunk loading", RuntimeModule.STAGE_ATTACH); - this._runtimeRequirements = runtimeRequirements; - } +const CC_LINE_FEED = "\n".charCodeAt(0); +const CC_CARRIAGE_RETURN = "\r".charCodeAt(0); +const CC_FORM_FEED = "\f".charCodeAt(0); - /** - * @returns {string} runtime code - */ - generate() { - const { compilation, chunk } = this; - const { - runtimeTemplate, - chunkGraph, - outputOptions: { importFunctionName, importMetaName } - } = compilation; - const fn = RuntimeGlobals.ensureChunkHandlers; - const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI); - const withExternalInstallChunk = this._runtimeRequirements.has( - RuntimeGlobals.externalInstallChunk - ); - const withLoading = this._runtimeRequirements.has( - RuntimeGlobals.ensureChunkHandlers - ); - const withOnChunkLoad = this._runtimeRequirements.has( - RuntimeGlobals.onChunksLoaded - ); - const withHmr = this._runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); - const hasJsMatcher = compileBooleanMatcher(conditionMap); - const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); +const CC_TAB = "\t".charCodeAt(0); +const CC_SPACE = " ".charCodeAt(0); - const outputName = this.compilation.getPath( - getChunkFilenameTemplate(chunk, this.compilation.outputOptions), - { - chunk, - contentHashType: "javascript" - } - ); - const rootOutputDir = getUndoPath( - outputName, - this.compilation.outputOptions.path, - true - ); +const CC_SLASH = "/".charCodeAt(0); +const CC_BACK_SLASH = "\\".charCodeAt(0); +const CC_ASTERISK = "*".charCodeAt(0); - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_module` - : undefined; +const CC_LEFT_PARENTHESIS = "(".charCodeAt(0); +const CC_RIGHT_PARENTHESIS = ")".charCodeAt(0); +const CC_LEFT_CURLY = "{".charCodeAt(0); +const CC_RIGHT_CURLY = "}".charCodeAt(0); - return Template.asString([ - withBaseURI - ? Template.asString([ - `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify( - rootOutputDir - )}, ${importMetaName}.url);` - ]) - : "// no baseURI", - "", - "// object to store loaded and loading chunks", - "// undefined = chunk not loaded, null = chunk preloaded/prefetched", - "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", - `var installedChunks = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{`, - Template.indent( - Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join( - ",\n" - ) - ), - "};", - "", - withLoading || withExternalInstallChunk - ? `var installChunk = ${runtimeTemplate.basicFunction("data", [ - runtimeTemplate.destructureObject( - ["ids", "modules", "runtime"], - "data" - ), - '// add "modules" to the modules object,', - '// then flag all "ids" as loaded and fire callback', - "var moduleId, chunkId, i = 0;", - "for(moduleId in modules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(modules, moduleId)) {`, - Template.indent( - `${RuntimeGlobals.moduleFactories}[moduleId] = modules[moduleId];` - ), - "}" - ]), - "}", - "if(runtime) runtime(__webpack_require__);", - "for(;i < ids.length; i++) {", - Template.indent([ - "chunkId = ids[i];", - `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`, - Template.indent("installedChunks[chunkId][0]();"), - "}", - "installedChunks[ids[i]] = 0;" - ]), - "}", - withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" - ])}` - : "// no install chunk", - "", - withLoading - ? Template.asString([ - `${fn}.j = ${runtimeTemplate.basicFunction( - "chunkId, promises", - hasJsMatcher !== false - ? Template.indent([ - "// import() chunk loading for javascript", - `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, - 'if(installedChunkData !== 0) { // 0 means "already installed".', - Template.indent([ - "", - '// a Promise means "currently loading".', - "if(installedChunkData) {", - Template.indent([ - "promises.push(installedChunkData[1]);" - ]), - "} else {", - Template.indent([ - hasJsMatcher === true - ? "if(true) { // all chunks have JS" - : `if(${hasJsMatcher("chunkId")}) {`, - Template.indent([ - "// setup Promise in chunk cache", - `var promise = ${importFunctionName}(${JSON.stringify( - rootOutputDir - )} + ${ - RuntimeGlobals.getChunkScriptFilename - }(chunkId)).then(installChunk, ${runtimeTemplate.basicFunction( - "e", - [ - "if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;", - "throw e;" - ] - )});`, - `var promise = Promise.race([promise, new Promise(${runtimeTemplate.expressionFunction( - `installedChunkData = installedChunks[chunkId] = [resolve]`, - "resolve" - )})])`, - `promises.push(installedChunkData[1] = promise);` - ]), - "} else installedChunks[chunkId] = 0;" - ]), - "}" - ]), - "}" - ]) - : Template.indent(["installedChunks[chunkId] = 0;"]) - )};` - ]) - : "// no chunk on demand loading", - "", - withExternalInstallChunk - ? Template.asString([ - `${RuntimeGlobals.externalInstallChunk} = installChunk;` - ]) - : "// no external install chunk", - "", - withOnChunkLoad - ? `${ - RuntimeGlobals.onChunksLoaded - }.j = ${runtimeTemplate.returningFunction( - "installedChunks[chunkId] === 0", - "chunkId" - )};` - : "// no on chunks loaded" - ]); - } -} +const CC_QUOTATION_MARK = '"'.charCodeAt(0); +const CC_APOSTROPHE = "'".charCodeAt(0); -module.exports = ModuleChunkLoadingRuntimeModule; +const CC_FULL_STOP = ".".charCodeAt(0); +const CC_COLON = ":".charCodeAt(0); +const CC_SEMICOLON = ";".charCodeAt(0); +const CC_COMMA = ",".charCodeAt(0); +const CC_PERCENTAGE = "%".charCodeAt(0); +const CC_AT_SIGN = "@".charCodeAt(0); +const CC_LOW_LINE = "_".charCodeAt(0); +const CC_LOWER_A = "a".charCodeAt(0); +const CC_LOWER_U = "u".charCodeAt(0); +const CC_LOWER_E = "e".charCodeAt(0); +const CC_LOWER_Z = "z".charCodeAt(0); +const CC_UPPER_A = "A".charCodeAt(0); +const CC_UPPER_E = "E".charCodeAt(0); +const CC_UPPER_Z = "Z".charCodeAt(0); +const CC_0 = "0".charCodeAt(0); +const CC_9 = "9".charCodeAt(0); -/***/ }), +const CC_NUMBER_SIGN = "#".charCodeAt(0); +const CC_PLUS_SIGN = "+".charCodeAt(0); +const CC_HYPHEN_MINUS = "-".charCodeAt(0); -/***/ 16734: -/***/ (function(module) { +const CC_LESS_THAN_SIGN = "<".charCodeAt(0); +const CC_GREATER_THAN_SIGN = ">".charCodeAt(0); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const _isNewLine = cc => { + return ( + cc === CC_LINE_FEED || cc === CC_CARRIAGE_RETURN || cc === CC_FORM_FEED + ); +}; +/** @type {CharHandler} */ +const consumeSpace = (input, pos, callbacks) => { + let cc; + do { + pos++; + cc = input.charCodeAt(pos); + } while (_isWhiteSpace(cc)); + return pos; +}; +const _isWhiteSpace = cc => { + return ( + cc === CC_LINE_FEED || + cc === CC_CARRIAGE_RETURN || + cc === CC_FORM_FEED || + cc === CC_TAB || + cc === CC_SPACE + ); +}; -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Dependency").SourcePosition} SourcePosition */ +/** @type {CharHandler} */ +const consumeSingleCharToken = (input, pos, callbacks) => { + return pos + 1; +}; -/** - * @param {SourcePosition} pos position - * @returns {string} formatted position - */ -const formatPosition = pos => { - if (pos && typeof pos === "object") { - if ("line" in pos && "column" in pos) { - return `${pos.line}:${pos.column}`; - } else if ("line" in pos) { - return `${pos.line}:?`; +/** @type {CharHandler} */ +const consumePotentialComment = (input, pos, callbacks) => { + pos++; + if (pos === input.length) return pos; + let cc = input.charCodeAt(pos); + if (cc !== CC_ASTERISK) return pos; + for (;;) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + while (cc === CC_ASTERISK) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + if (cc === CC_SLASH) return pos + 1; } } - return ""; }; -/** - * @param {DependencyLocation} loc location - * @returns {string} formatted location - */ -const formatLocation = loc => { - if (loc && typeof loc === "object") { - if ("start" in loc && loc.start && "end" in loc && loc.end) { - if ( - typeof loc.start === "object" && - typeof loc.start.line === "number" && - typeof loc.end === "object" && - typeof loc.end.line === "number" && - typeof loc.end.column === "number" && - loc.start.line === loc.end.line - ) { - return `${formatPosition(loc.start)}-${loc.end.column}`; - } else if ( - typeof loc.start === "object" && - typeof loc.start.line === "number" && - typeof loc.start.column !== "number" && - typeof loc.end === "object" && - typeof loc.end.line === "number" && - typeof loc.end.column !== "number" - ) { - return `${loc.start.line}-${loc.end.line}`; - } else { - return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; - } - } - if ("start" in loc && loc.start) { - return formatPosition(loc.start); - } - if ("name" in loc && "index" in loc) { - return `${loc.name}[${loc.index}]`; +/** @type {function(number): CharHandler} */ +const consumeString = end => (input, pos, callbacks) => { + const start = pos; + pos = _consumeString(input, pos, end); + if (callbacks.string !== undefined) { + pos = callbacks.string(input, start, pos); + } + return pos; +}; + +const _consumeString = (input, pos, end) => { + pos++; + for (;;) { + if (pos === input.length) return pos; + const cc = input.charCodeAt(pos); + if (cc === end) return pos + 1; + if (_isNewLine(cc)) { + // bad string + return pos; } - if ("name" in loc) { - return loc.name; + if (cc === CC_BACK_SLASH) { + // we don't need to fully parse the escaped code point + // just skip over a potential new line + pos++; + if (pos === input.length) return pos; + pos++; + } else { + pos++; } } - return ""; }; -module.exports = formatLocation; - - -/***/ }), - -/***/ 27899: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - +const _isIdentifierStartCode = cc => { + return ( + cc === CC_LOW_LINE || + (cc >= CC_LOWER_A && cc <= CC_LOWER_Z) || + (cc >= CC_UPPER_A && cc <= CC_UPPER_Z) || + cc > 0x80 + ); +}; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); +const _isDigit = cc => { + return cc >= CC_0 && cc <= CC_9; +}; -class HotModuleReplacementRuntimeModule extends RuntimeModule { - constructor() { - super("hot module replacement", RuntimeModule.STAGE_BASIC); +const _startsIdentifier = (input, pos) => { + const cc = input.charCodeAt(pos); + if (cc === CC_HYPHEN_MINUS) { + if (pos === input.length) return false; + const cc = input.charCodeAt(pos + 1); + if (cc === CC_HYPHEN_MINUS) return true; + if (cc === CC_BACK_SLASH) { + const cc = input.charCodeAt(pos + 2); + return !_isNewLine(cc); + } + return _isIdentifierStartCode(cc); } - /** - * @returns {string} runtime code - */ - generate() { - return Template.getFunctionContent( - require('./HotModuleReplacement.runtime.js') - ) - .replace(/\$getFullHash\$/g, RuntimeGlobals.getFullHash) - .replace( - /\$interceptModuleExecution\$/g, - RuntimeGlobals.interceptModuleExecution - ) - .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) - .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) - .replace(/\$hmrDownloadManifest\$/g, RuntimeGlobals.hmrDownloadManifest) - .replace( - /\$hmrInvalidateModuleHandlers\$/g, - RuntimeGlobals.hmrInvalidateModuleHandlers - ) - .replace( - /\$hmrDownloadUpdateHandlers\$/g, - RuntimeGlobals.hmrDownloadUpdateHandlers - ); + if (cc === CC_BACK_SLASH) { + const cc = input.charCodeAt(pos + 1); + return !_isNewLine(cc); } -} - -module.exports = HotModuleReplacementRuntimeModule; + return _isIdentifierStartCode(cc); +}; +/** @type {CharHandler} */ +const consumeNumberSign = (input, pos, callbacks) => { + const start = pos; + pos++; + if (pos === input.length) return pos; + if (callbacks.isSelector(input, pos) && _startsIdentifier(input, pos)) { + pos = _consumeIdentifier(input, pos); + if (callbacks.id !== undefined) { + return callbacks.id(input, start, pos); + } + } + return pos; +}; -/***/ }), +/** @type {CharHandler} */ +const consumeMinus = (input, pos, callbacks) => { + const start = pos; + pos++; + if (pos === input.length) return pos; + const cc = input.charCodeAt(pos); + if (cc === CC_FULL_STOP || _isDigit(cc)) { + return consumeNumericToken(input, pos, callbacks); + } else if (cc === CC_HYPHEN_MINUS) { + pos++; + if (pos === input.length) return pos; + const cc = input.charCodeAt(pos); + if (cc === CC_GREATER_THAN_SIGN) { + return pos + 1; + } else { + pos = _consumeIdentifier(input, pos); + if (callbacks.identifier !== undefined) { + return callbacks.identifier(input, start, pos); + } + } + } else if (cc === CC_BACK_SLASH) { + if (pos + 1 === input.length) return pos; + const cc = input.charCodeAt(pos + 1); + if (_isNewLine(cc)) return pos; + pos = _consumeIdentifier(input, pos); + if (callbacks.identifier !== undefined) { + return callbacks.identifier(input, start, pos); + } + } else if (_isIdentifierStartCode(cc)) { + pos++; + pos = _consumeIdentifier(input, pos); + if (callbacks.identifier !== undefined) { + return callbacks.identifier(input, start, pos); + } + } + return pos; +}; -/***/ 79040: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** @type {CharHandler} */ +const consumeDot = (input, pos, callbacks) => { + const start = pos; + pos++; + if (pos === input.length) return pos; + const cc = input.charCodeAt(pos); + if (_isDigit(cc)) return consumeNumericToken(input, pos - 2, callbacks); + if (!callbacks.isSelector(input, pos) || !_startsIdentifier(input, pos)) + return pos; + pos = _consumeIdentifier(input, pos); + if (callbacks.class !== undefined) return callbacks.class(input, start, pos); + return pos; +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { RawSource } = __webpack_require__(51255); -const AsyncDependenciesBlock = __webpack_require__(47736); -const Dependency = __webpack_require__(54912); -const Module = __webpack_require__(73208); -const ModuleFactory = __webpack_require__(51010); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const CommonJsRequireDependency = __webpack_require__(21264); -const { registerNotSerializable } = __webpack_require__(8282); - -/** @typedef {import("../../declarations/WebpackOptions")} WebpackOptions */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../Module").BuildMeta} BuildMeta */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../dependencies/HarmonyImportDependency")} HarmonyImportDependency */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ - -/** - * @typedef {Object} BackendApi - * @property {function(Error=): void} dispose - * @property {function(Module): { client: string, data: string, active: boolean }} module - */ - -const HMR_DEPENDENCY_TYPES = new Set([ - "import.meta.webpackHot.accept", - "import.meta.webpackHot.decline", - "module.hot.accept", - "module.hot.decline" -]); - -/** - * @param {undefined|string|RegExp|Function} test test option - * @param {Module} module the module - * @returns {boolean} true, if the module should be selected - */ -const checkTest = (test, module) => { - if (test === undefined) return true; - if (typeof test === "function") { - return test(module); - } - if (typeof test === "string") { - const name = module.nameForCondition(); - return name && name.startsWith(test); - } - if (test instanceof RegExp) { - const name = module.nameForCondition(); - return name && test.test(name); - } - return false; +/** @type {CharHandler} */ +const consumeNumericToken = (input, pos, callbacks) => { + pos = _consumeNumber(input, pos); + if (pos === input.length) return pos; + if (_startsIdentifier(input, pos)) return _consumeIdentifier(input, pos); + const cc = input.charCodeAt(pos); + if (cc === CC_PERCENTAGE) return pos + 1; + return pos; }; -const TYPES = new Set(["javascript"]); - -class LazyCompilationDependency extends Dependency { - constructor(proxyModule) { - super(); - this.proxyModule = proxyModule; +/** @type {CharHandler} */ +const consumeOtherIdentifier = (input, pos, callbacks) => { + const start = pos; + pos = _consumeIdentifier(input, pos); + if ( + pos !== input.length && + !callbacks.isSelector(input, pos) && + input.charCodeAt(pos) === CC_LEFT_PARENTHESIS + ) { + pos++; + if (callbacks.function !== undefined) { + return callbacks.function(input, start, pos); + } + } else { + if (callbacks.identifier !== undefined) { + return callbacks.identifier(input, start, pos); + } } + return pos; +}; - get category() { - return "esm"; +/** @type {CharHandler} */ +const consumePotentialUrl = (input, pos, callbacks) => { + const start = pos; + pos = _consumeIdentifier(input, pos); + if (pos === start + 3 && input.slice(start, pos + 1) === "url(") { + pos++; + let cc = input.charCodeAt(pos); + while (_isWhiteSpace(cc)) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + } + if (cc === CC_QUOTATION_MARK || cc === CC_APOSTROPHE) { + pos++; + const contentStart = pos; + pos = _consumeString(input, pos, cc); + const contentEnd = pos - 1; + cc = input.charCodeAt(pos); + while (_isWhiteSpace(cc)) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + } + if (cc !== CC_RIGHT_PARENTHESIS) return pos; + pos++; + if (callbacks.url !== undefined) + return callbacks.url(input, start, pos, contentStart, contentEnd); + return pos; + } else { + const contentStart = pos; + let contentEnd; + for (;;) { + if (cc === CC_BACK_SLASH) { + pos++; + if (pos === input.length) return pos; + pos++; + } else if (_isWhiteSpace(cc)) { + contentEnd = pos; + do { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + } while (_isWhiteSpace(cc)); + if (cc !== CC_RIGHT_PARENTHESIS) return pos; + pos++; + if (callbacks.url !== undefined) { + return callbacks.url(input, start, pos, contentStart, contentEnd); + } + return pos; + } else if (cc === CC_RIGHT_PARENTHESIS) { + contentEnd = pos; + pos++; + if (callbacks.url !== undefined) { + return callbacks.url(input, start, pos, contentStart, contentEnd); + } + return pos; + } else if (cc === CC_LEFT_PARENTHESIS) { + return pos; + } else { + pos++; + } + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + } + } + } else { + if (callbacks.identifier !== undefined) { + return callbacks.identifier(input, start, pos); + } + return pos; } +}; - get type() { - return "lazy import()"; +/** @type {CharHandler} */ +const consumePotentialPseudo = (input, pos, callbacks) => { + const start = pos; + pos++; + if (!callbacks.isSelector(input, pos) || !_startsIdentifier(input, pos)) + return pos; + pos = _consumeIdentifier(input, pos); + let cc = input.charCodeAt(pos); + if (cc === CC_LEFT_PARENTHESIS) { + pos++; + if (callbacks.pseudoFunction !== undefined) { + return callbacks.pseudoFunction(input, start, pos); + } + return pos; } - - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - return this.proxyModule.originalModule.identifier(); + if (callbacks.pseudoClass !== undefined) { + return callbacks.pseudoClass(input, start, pos); } -} - -registerNotSerializable(LazyCompilationDependency); + return pos; +}; -class LazyCompilationProxyModule extends Module { - constructor(context, originalModule, request, client, data, active) { - super("lazy-compilation-proxy", context, originalModule.layer); - this.originalModule = originalModule; - this.request = request; - this.client = client; - this.data = data; - this.active = active; +/** @type {CharHandler} */ +const consumeLeftParenthesis = (input, pos, callbacks) => { + pos++; + if (callbacks.leftParenthesis !== undefined) { + return callbacks.leftParenthesis(input, pos - 1, pos); } + return pos; +}; - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return `lazy-compilation-proxy|${this.originalModule.identifier()}`; +/** @type {CharHandler} */ +const consumeRightParenthesis = (input, pos, callbacks) => { + pos++; + if (callbacks.rightParenthesis !== undefined) { + return callbacks.rightParenthesis(input, pos - 1, pos); } + return pos; +}; - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return `lazy-compilation-proxy ${this.originalModule.readableIdentifier( - requestShortener - )}`; +/** @type {CharHandler} */ +const consumeLeftCurlyBracket = (input, pos, callbacks) => { + pos++; + if (callbacks.leftCurlyBracket !== undefined) { + return callbacks.leftCurlyBracket(input, pos - 1, pos); } + return pos; +}; - /** - * 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 {LazyCompilationProxyModule} */ (module); - this.originalModule = m.originalModule; - this.request = m.request; - this.client = m.client; - this.data = m.data; - this.active = m.active; +/** @type {CharHandler} */ +const consumeRightCurlyBracket = (input, pos, callbacks) => { + pos++; + if (callbacks.rightCurlyBracket !== undefined) { + return callbacks.rightCurlyBracket(input, pos - 1, pos); } + return pos; +}; - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - return `${this.originalModule.libIdent(options)}!lazy-compilation-proxy`; +/** @type {CharHandler} */ +const consumeSemicolon = (input, pos, callbacks) => { + pos++; + if (callbacks.semicolon !== undefined) { + return callbacks.semicolon(input, pos - 1, pos); } + return pos; +}; - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - callback(null, !this.buildInfo || this.buildInfo.active !== this.active); +/** @type {CharHandler} */ +const consumeComma = (input, pos, callbacks) => { + pos++; + if (callbacks.comma !== undefined) { + return callbacks.comma(input, pos - 1, pos); } + return pos; +}; - /** - * @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.buildInfo = { - active: this.active - }; - /** @type {BuildMeta} */ - this.buildMeta = {}; - this.clearDependenciesAndBlocks(); - const dep = new CommonJsRequireDependency(this.client); - this.addDependency(dep); - if (this.active) { - const dep = new LazyCompilationDependency(this); - const block = new AsyncDependenciesBlock({}); - block.addDependency(dep); - this.addBlock(block); +const _consumeIdentifier = (input, pos) => { + for (;;) { + const cc = input.charCodeAt(pos); + if (cc === CC_BACK_SLASH) { + pos++; + if (pos === input.length) return pos; + pos++; + } else if ( + _isIdentifierStartCode(cc) || + _isDigit(cc) || + cc === CC_HYPHEN_MINUS + ) { + pos++; + } else { + return pos; } - callback(); - } - - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; } +}; - /** - * @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 200; +const _consumeNumber = (input, pos) => { + pos++; + if (pos === input.length) return pos; + let cc = input.charCodeAt(pos); + while (_isDigit(cc)) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); } - - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration({ runtimeTemplate, chunkGraph, moduleGraph }) { - const sources = new Map(); - const runtimeRequirements = new Set(); - runtimeRequirements.add(RuntimeGlobals.module); - const clientDep = /** @type {CommonJsRequireDependency} */ ( - this.dependencies[0] - ); - const clientModule = moduleGraph.getModule(clientDep); - const block = this.blocks[0]; - const client = Template.asString([ - `var client = ${runtimeTemplate.moduleExports({ - module: clientModule, - chunkGraph, - request: clientDep.userRequest, - runtimeRequirements - })}`, - `var data = ${JSON.stringify(this.data)};` - ]); - const keepActive = Template.asString([ - `var dispose = client.keepAlive({ data: data, active: ${JSON.stringify( - !!block - )}, module: module, onError: onError });` - ]); - let source; - if (block) { - const dep = block.dependencies[0]; - const module = moduleGraph.getModule(dep); - source = Template.asString([ - client, - `module.exports = ${runtimeTemplate.moduleNamespacePromise({ - chunkGraph, - block, - module, - request: this.request, - strict: false, // TODO this should be inherited from the original module - message: "import()", - runtimeRequirements - })};`, - "if (module.hot) {", - Template.indent([ - "module.hot.accept();", - `module.hot.accept(${JSON.stringify( - chunkGraph.getModuleId(module) - )}, function() { module.hot.invalidate(); });`, - "module.hot.dispose(function(data) { delete data.resolveSelf; dispose(data); });", - "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);" - ]), - "}", - "function onError() { /* ignore */ }", - keepActive - ]); - } else { - source = Template.asString([ - client, - "var resolveSelf, onError;", - `module.exports = new Promise(function(resolve, reject) { resolveSelf = resolve; onError = reject; });`, - "if (module.hot) {", - Template.indent([ - "module.hot.accept();", - "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);", - "module.hot.dispose(function(data) { data.resolveSelf = resolveSelf; dispose(data); });" - ]), - "}", - keepActive - ]); + if (cc === CC_FULL_STOP && pos + 1 !== input.length) { + const next = input.charCodeAt(pos + 1); + if (_isDigit(next)) { + pos += 2; + cc = input.charCodeAt(pos); + while (_isDigit(cc)) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + } } - sources.set("javascript", new RawSource(source)); - return { - sources, - runtimeRequirements - }; } - - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - super.updateHash(hash, context); - hash.update(this.active ? "active" : ""); - hash.update(JSON.stringify(this.data)); + if (cc === CC_LOWER_E || cc === CC_UPPER_E) { + if (pos + 1 !== input.length) { + const next = input.charCodeAt(pos + 2); + if (_isDigit(next)) { + pos += 2; + } else if ( + (next === CC_HYPHEN_MINUS || next === CC_PLUS_SIGN) && + pos + 2 !== input.length + ) { + const next = input.charCodeAt(pos + 2); + if (_isDigit(next)) { + pos += 3; + } else { + return pos; + } + } else { + return pos; + } + } + } else { + return pos; } -} - -registerNotSerializable(LazyCompilationProxyModule); - -class LazyCompilationDependencyFactory extends ModuleFactory { - constructor(factory) { - super(); - this._factory = factory; + cc = input.charCodeAt(pos); + while (_isDigit(cc)) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); } + return pos; +}; - /** - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback - * @returns {void} - */ - create(data, callback) { - const dependency = /** @type {LazyCompilationDependency} */ ( - data.dependencies[0] - ); - callback(null, { - module: dependency.proxyModule.originalModule - }); - } -} +/** @type {CharHandler} */ +const consumeLessThan = (input, pos, callbacks) => { + if (input.slice(pos + 1, pos + 4) === "!--") return pos + 4; + return pos + 1; +}; -class LazyCompilationPlugin { - /** - * @param {Object} options options - * @param {(function(Compiler, function(Error?, BackendApi?): void): void) | function(Compiler): Promise} options.backend the backend - * @param {boolean} options.entries true, when entries are lazy compiled - * @param {boolean} options.imports true, when import() modules are lazy compiled - * @param {RegExp | string | (function(Module): boolean)} options.test additional filter for lazy compiled entrypoint modules - */ - constructor({ backend, entries, imports, test }) { - this.backend = backend; - this.entries = entries; - this.imports = imports; - this.test = test; +/** @type {CharHandler} */ +const consumeAt = (input, pos, callbacks) => { + const start = pos; + pos++; + if (pos === input.length) return pos; + if (_startsIdentifier(input, pos)) { + pos = _consumeIdentifier(input, pos); + if (callbacks.atKeyword !== undefined) { + pos = callbacks.atKeyword(input, start, pos); + } } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - let backend; - compiler.hooks.beforeCompile.tapAsync( - "LazyCompilationPlugin", - (params, callback) => { - if (backend !== undefined) return callback(); - const promise = this.backend(compiler, (err, result) => { - if (err) return callback(err); - backend = result; - callback(); - }); - if (promise && promise.then) { - promise.then(b => { - backend = b; - callback(); - }, callback); - } - } - ); - compiler.hooks.thisCompilation.tap( - "LazyCompilationPlugin", - (compilation, { normalModuleFactory }) => { - normalModuleFactory.hooks.module.tap( - "LazyCompilationPlugin", - (originalModule, createData, resolveData) => { - if ( - resolveData.dependencies.every(dep => - HMR_DEPENDENCY_TYPES.has(dep.type) - ) - ) { - // for HMR only resolving, try to determine if the HMR accept/decline refers to - // an import() or not - const hmrDep = resolveData.dependencies[0]; - const originModule = - compilation.moduleGraph.getParentModule(hmrDep); - const isReferringToDynamicImport = originModule.blocks.some( - block => - block.dependencies.some( - dep => - dep.type === "import()" && - /** @type {HarmonyImportDependency} */ (dep).request === - hmrDep.request - ) - ); - if (!isReferringToDynamicImport) return; - } else if ( - !resolveData.dependencies.every( - dep => - HMR_DEPENDENCY_TYPES.has(dep.type) || - (this.imports && - (dep.type === "import()" || - dep.type === "import() context element")) || - (this.entries && dep.type === "entry") - ) - ) - return; - if ( - /webpack[/\\]hot[/\\]|webpack-dev-server[/\\]client|webpack-hot-middleware[/\\]client/.test( - resolveData.request - ) || - !checkTest(this.test, originalModule) - ) - return; - const moduleInfo = backend.module(originalModule); - if (!moduleInfo) return; - const { client, data, active } = moduleInfo; + return pos; +}; - return new LazyCompilationProxyModule( - compiler.context, - originalModule, - resolveData.request, - client, - data, - active - ); - } - ); - compilation.dependencyFactories.set( - LazyCompilationDependency, - new LazyCompilationDependencyFactory() - ); +const CHAR_MAP = Array.from({ length: 0x80 }, (_, cc) => { + // https://drafts.csswg.org/css-syntax/#consume-token + switch (cc) { + case CC_LINE_FEED: + case CC_CARRIAGE_RETURN: + case CC_FORM_FEED: + case CC_TAB: + case CC_SPACE: + return consumeSpace; + case CC_QUOTATION_MARK: + case CC_APOSTROPHE: + return consumeString(cc); + case CC_NUMBER_SIGN: + return consumeNumberSign; + case CC_SLASH: + return consumePotentialComment; + // case CC_LEFT_SQUARE: + // case CC_RIGHT_SQUARE: + // case CC_COMMA: + // case CC_COLON: + // return consumeSingleCharToken; + case CC_COMMA: + return consumeComma; + case CC_SEMICOLON: + return consumeSemicolon; + case CC_LEFT_PARENTHESIS: + return consumeLeftParenthesis; + case CC_RIGHT_PARENTHESIS: + return consumeRightParenthesis; + case CC_LEFT_CURLY: + return consumeLeftCurlyBracket; + case CC_RIGHT_CURLY: + return consumeRightCurlyBracket; + case CC_COLON: + return consumePotentialPseudo; + case CC_PLUS_SIGN: + return consumeNumericToken; + case CC_FULL_STOP: + return consumeDot; + case CC_HYPHEN_MINUS: + return consumeMinus; + case CC_LESS_THAN_SIGN: + return consumeLessThan; + case CC_AT_SIGN: + return consumeAt; + case CC_LOWER_U: + return consumePotentialUrl; + case CC_LOW_LINE: + return consumeOtherIdentifier; + default: + if (_isDigit(cc)) return consumeNumericToken; + if ( + (cc >= CC_LOWER_A && cc <= CC_LOWER_Z) || + (cc >= CC_UPPER_A && cc <= CC_UPPER_Z) + ) { + return consumeOtherIdentifier; } - ); - compiler.hooks.shutdown.tapAsync("LazyCompilationPlugin", callback => { - backend.dispose(callback); - }); + return consumeSingleCharToken; } -} - -module.exports = LazyCompilationPlugin; - - -/***/ }), - -/***/ 17781: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @typedef {import("http").ServerOptions} HttpServerOptions */ -/** @typedef {import("https").ServerOptions} HttpsServerOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LazyCompilationDefaultBackendOptions} LazyCompilationDefaultBackendOptions */ -/** @typedef {import("../Compiler")} Compiler */ +}); /** - * @callback BackendHandler - * @param {Compiler} compiler compiler - * @param {function((Error | null)=, any=): void} callback callback + * @param {string} input input css + * @param {CssTokenCallbacks} callbacks callbacks * @returns {void} */ +module.exports = (input, callbacks) => { + let pos = 0; + while (pos < input.length) { + const cc = input.charCodeAt(pos); + if (cc < 0x80) { + pos = CHAR_MAP[cc](input, pos, callbacks); + } else { + pos++; + } + } +}; -/** - * @param {Omit & { client: NonNullable}} options additional options for the backend - * @returns {BackendHandler} backend - */ -module.exports = options => (compiler, callback) => { - const logger = compiler.getInfrastructureLogger("LazyCompilationBackend"); - const activeModules = new Map(); - const prefix = "/lazy-compilation-using-"; - - const isHttps = - options.protocol === "https" || - (typeof options.server === "object" && - ("key" in options.server || "pfx" in options.server)); - - const createServer = - typeof options.server === "function" - ? options.server - : (() => { - const http = isHttps ? __webpack_require__(95687) : __webpack_require__(13685); - return http.createServer.bind(http, options.server); - })(); - const listen = - typeof options.listen === "function" - ? options.listen - : server => { - let listen = options.listen; - if (typeof listen === "object" && !("port" in listen)) - listen = { ...listen, port: undefined }; - server.listen(listen); - }; - - const protocol = options.protocol || (isHttps ? "https" : "http"); - - const requestListener = (req, res) => { - const keys = req.url.slice(prefix.length).split("@"); - req.socket.on("close", () => { - setTimeout(() => { - for (const key of keys) { - const oldValue = activeModules.get(key) || 0; - activeModules.set(key, oldValue - 1); - if (oldValue === 1) { - logger.log( - `${key} is no longer in use. Next compilation will skip this module.` - ); +module.exports.eatComments = (input, pos) => { + loop: for (;;) { + const cc = input.charCodeAt(pos); + if (cc === CC_SLASH) { + if (pos === input.length) return pos; + let cc = input.charCodeAt(pos + 1); + if (cc !== CC_ASTERISK) return pos; + pos++; + for (;;) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + while (cc === CC_ASTERISK) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + if (cc === CC_SLASH) { + pos++; + continue loop; } } - }, 120000); - }); - req.socket.setNoDelay(true); - res.writeHead(200, { - "content-type": "text/event-stream", - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Methods": "*", - "Access-Control-Allow-Headers": "*" - }); - res.write("\n"); - let moduleActivated = false; - for (const key of keys) { - const oldValue = activeModules.get(key) || 0; - activeModules.set(key, oldValue + 1); - if (oldValue === 0) { - logger.log(`${key} is now in use and will be compiled.`); - moduleActivated = true; } } - if (moduleActivated && compiler.watching) compiler.watching.invalidate(); - }; - - const server = /** @type {import("net").Server} */ (createServer()); - server.on("request", requestListener); + return pos; + } +}; - let isClosing = false; - /** @type {Set} */ - const sockets = new Set(); - server.on("connection", socket => { - sockets.add(socket); - socket.on("close", () => { - sockets.delete(socket); - }); - if (isClosing) socket.destroy(); - }); - server.on("clientError", e => { - if (e.message !== "Server is disposing") logger.warn(e); - }); - server.on("listening", err => { - if (err) return callback(err); - const addr = server.address(); - if (typeof addr === "string") throw new Error("addr must not be a string"); - const urlBase = - addr.address === "::" || addr.address === "0.0.0.0" - ? `${protocol}://localhost:${addr.port}` - : addr.family === "IPv6" - ? `${protocol}://[${addr.address}]:${addr.port}` - : `${protocol}://${addr.address}:${addr.port}`; - logger.log( - `Server-Sent-Events server for lazy compilation open at ${urlBase}.` - ); - callback(null, { - dispose(callback) { - isClosing = true; - // Removing the listener is a workaround for a memory leak in node.js - server.off("request", requestListener); - server.close(err => { - callback(err); - }); - for (const socket of sockets) { - socket.destroy(new Error("Server is disposing")); +module.exports.eatWhitespaceAndComments = (input, pos) => { + loop: for (;;) { + const cc = input.charCodeAt(pos); + if (cc === CC_SLASH) { + if (pos === input.length) return pos; + let cc = input.charCodeAt(pos + 1); + if (cc !== CC_ASTERISK) return pos; + pos++; + for (;;) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + while (cc === CC_ASTERISK) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + if (cc === CC_SLASH) { + pos++; + continue loop; + } } - }, - module(originalModule) { - const key = `${encodeURIComponent( - originalModule.identifier().replace(/\\/g, "/").replace(/@/g, "_") - ).replace(/%(2F|3A|24|26|2B|2C|3B|3D|3A)/g, decodeURIComponent)}`; - const active = activeModules.get(key) > 0; - return { - client: `${options.client}?${encodeURIComponent(urlBase + prefix)}`, - data: key, - active - }; } - }); - }); - listen(server); + } else if (_isWhiteSpace(cc)) { + pos++; + continue; + } + return pos; + } }; /***/ }), -/***/ 64618: +/***/ 2757: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const { find } = __webpack_require__(93347); -const { - compareModulesByPreOrderIndexOrIdentifier, - compareModulesByPostOrderIndexOrIdentifier -} = __webpack_require__(29579); +const { Tracer } = __webpack_require__(5787); +const createSchemaValidation = __webpack_require__(32540); +const { dirname, mkdirpSync } = __webpack_require__(17139); -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../../declarations/plugins/debug/ProfilingPlugin").ProfilingPluginOptions} ProfilingPluginOptions */ +/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ -class ChunkModuleIdRangePlugin { - constructor(options) { - this.options = options; +const validate = createSchemaValidation( + __webpack_require__(37134), + () => __webpack_require__(50686), + { + name: "Profiling Plugin", + baseDataPath: "options" } +); +let inspector = undefined; - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => { - const moduleGraph = compilation.moduleGraph; - compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => { - const chunkGraph = compilation.chunkGraph; - const chunk = find( - compilation.chunks, - chunk => chunk.name === options.name - ); - if (!chunk) { - throw new Error( - `ChunkModuleIdRangePlugin: Chunk with name '${options.name}"' was not found` - ); - } +try { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + inspector = __webpack_require__(31405); +} catch (e) { + console.log("Unable to CPU profile in < node 8.0"); +} - let chunkModules; - if (options.order) { - let cmpFn; - switch (options.order) { - case "index": - case "preOrderIndex": - cmpFn = compareModulesByPreOrderIndexOrIdentifier(moduleGraph); - break; - case "index2": - case "postOrderIndex": - cmpFn = compareModulesByPostOrderIndexOrIdentifier(moduleGraph); - break; - default: - throw new Error( - "ChunkModuleIdRangePlugin: unexpected value of order" - ); - } - chunkModules = chunkGraph.getOrderedChunkModules(chunk, cmpFn); - } else { - chunkModules = Array.from(modules) - .filter(m => { - return chunkGraph.isModuleInChunk(m, chunk); - }) - .sort(compareModulesByPreOrderIndexOrIdentifier(moduleGraph)); - } +class Profiler { + constructor(inspector) { + this.session = undefined; + this.inspector = inspector; + this._startTime = 0; + } - let currentId = options.start || 0; - for (let i = 0; i < chunkModules.length; i++) { - const m = chunkModules[i]; - if (m.needId && chunkGraph.getModuleId(m) === null) { - chunkGraph.setModuleId(m, currentId++); - } - if (options.end && currentId > options.end) break; - } - }); - }); + hasSession() { + return this.session !== undefined; } -} -module.exports = ChunkModuleIdRangePlugin; + startProfiling() { + if (this.inspector === undefined) { + return Promise.resolve(); + } -/***/ }), + try { + this.session = new inspector.Session(); + this.session.connect(); + } catch (_) { + this.session = undefined; + return Promise.resolve(); + } -/***/ 8747: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const hrtime = process.hrtime(); + this._startTime = hrtime[0] * 1000000 + Math.round(hrtime[1] / 1000); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ + return Promise.all([ + this.sendCommand("Profiler.setSamplingInterval", { + interval: 100 + }), + this.sendCommand("Profiler.enable"), + this.sendCommand("Profiler.start") + ]); + } + sendCommand(method, params) { + if (this.hasSession()) { + return new Promise((res, rej) => { + return this.session.post(method, params, (err, params) => { + if (err !== null) { + rej(err); + } else { + res(params); + } + }); + }); + } else { + return Promise.resolve(); + } + } + destroy() { + if (this.hasSession()) { + this.session.disconnect(); + } -const { compareChunksNatural } = __webpack_require__(29579); -const { - getFullChunkName, - getUsedChunkIds, - assignDeterministicIds -} = __webpack_require__(63290); - -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ - -class DeterministicChunkIdsPlugin { - constructor(options) { - this.options = options || {}; + return Promise.resolve(); } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "DeterministicChunkIdsPlugin", - compilation => { - compilation.hooks.chunkIds.tap( - "DeterministicChunkIdsPlugin", - chunks => { - const chunkGraph = compilation.chunkGraph; - const context = this.options.context - ? this.options.context - : compiler.context; - const maxLength = this.options.maxLength || 3; - - const compareNatural = compareChunksNatural(chunkGraph); - - const usedIds = getUsedChunkIds(compilation); - assignDeterministicIds( - Array.from(chunks).filter(chunk => { - return chunk.id === null; - }), - chunk => - getFullChunkName(chunk, chunkGraph, context, compiler.root), - compareNatural, - (chunk, id) => { - const size = usedIds.size; - usedIds.add(`${id}`); - if (size === usedIds.size) return false; - chunk.id = id; - chunk.ids = [id]; - return true; - }, - [Math.pow(10, maxLength)], - 10, - usedIds.size - ); - } - ); + stopProfiling() { + return this.sendCommand("Profiler.stop").then(({ profile }) => { + const hrtime = process.hrtime(); + const endTime = hrtime[0] * 1000000 + Math.round(hrtime[1] / 1000); + if (profile.startTime < this._startTime || profile.endTime > endTime) { + // In some cases timestamps mismatch and we need to adjust them + // Both process.hrtime and the inspector timestamps claim to be relative + // to a unknown point in time. But they do not guarantee that this is the + // same point in time. + const duration = profile.endTime - profile.startTime; + const ownDuration = endTime - this._startTime; + const untracked = Math.max(0, ownDuration - duration); + profile.startTime = this._startTime + untracked / 2; + profile.endTime = endTime - untracked / 2; } - ); + return { profile }; + }); } } -module.exports = DeterministicChunkIdsPlugin; - - -/***/ }), +/** + * an object that wraps Tracer and Profiler with a counter + * @typedef {Object} Trace + * @property {Tracer} trace instance of Tracer + * @property {number} counter Counter + * @property {Profiler} profiler instance of Profiler + * @property {Function} end the end function + */ -/***/ 76692: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @param {IntermediateFileSystem} fs filesystem used for output + * @param {string} outputPath The location where to write the log. + * @returns {Trace} The trace object + */ +const createTrace = (fs, outputPath) => { + const trace = new Tracer(); + const profiler = new Profiler(inspector); + if (/\/|\\/.test(outputPath)) { + const dirPath = dirname(fs, outputPath); + mkdirpSync(fs, dirPath); + } + const fsStream = fs.createWriteStream(outputPath); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ + let counter = 0; + trace.pipe(fsStream); + // These are critical events that need to be inserted so that tools like + // chrome dev tools can load the profile. + trace.instantEvent({ + name: "TracingStartedInPage", + id: ++counter, + cat: ["disabled-by-default-devtools.timeline"], + args: { + data: { + sessionId: "-1", + page: "0xfff", + frames: [ + { + frame: "0xfff", + url: "webpack", + name: "" + } + ] + } + } + }); + trace.instantEvent({ + name: "TracingStartedInBrowser", + id: ++counter, + cat: ["disabled-by-default-devtools.timeline"], + args: { + data: { + sessionId: "-1" + } + } + }); -const { - compareModulesByPreOrderIndexOrIdentifier -} = __webpack_require__(29579); -const { - getUsedModuleIdsAndModules, - getFullModuleName, - assignDeterministicIds -} = __webpack_require__(63290); + return { + trace, + counter, + profiler, + end: callback => { + trace.push("]"); + // Wait until the write stream finishes. + fsStream.on("close", () => { + callback(); + }); + // Tear down the readable trace stream. + trace.push(null); + } + }; +}; -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +const pluginName = "ProfilingPlugin"; -class DeterministicModuleIdsPlugin { +class ProfilingPlugin { /** - * @param {Object} options options - * @param {string=} options.context context relative to which module identifiers are computed - * @param {function(Module): boolean=} options.test selector function for modules - * @param {number=} options.maxLength maximum id length in digits (used as starting point) - * @param {number=} options.salt hash salt for ids - * @param {boolean=} options.fixedLength do not increase the maxLength to find an optimal id space size - * @param {boolean=} options.failOnConflict throw an error when id conflicts occur (instead of rehashing) + * @param {ProfilingPluginOptions=} options options object */ constructor(options = {}) { - this.options = options; + validate(options); + this.outputPath = options.outputPath || "events.json"; } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ apply(compiler) { - compiler.hooks.compilation.tap( - "DeterministicModuleIdsPlugin", - compilation => { - compilation.hooks.moduleIds.tap("DeterministicModuleIdsPlugin", () => { - const chunkGraph = compilation.chunkGraph; - const context = this.options.context - ? this.options.context - : compiler.context; - const maxLength = this.options.maxLength || 3; - const failOnConflict = this.options.failOnConflict || false; - const fixedLength = this.options.fixedLength || false; - const salt = this.options.salt || 0; - let conflicts = 0; - - const [usedIds, modules] = getUsedModuleIdsAndModules( - compilation, - this.options.test - ); - assignDeterministicIds( - modules, - module => getFullModuleName(module, context, compiler.root), - failOnConflict - ? () => 0 - : compareModulesByPreOrderIndexOrIdentifier( - compilation.moduleGraph - ), - (module, id) => { - const size = usedIds.size; - usedIds.add(`${id}`); - if (size === usedIds.size) { - conflicts++; - return false; - } - chunkGraph.setModuleId(module, id); - return true; - }, - [Math.pow(10, maxLength)], - fixedLength ? 0 : 10, - usedIds.size, - salt - ); - if (failOnConflict && conflicts) - throw new Error( - `Assigning deterministic module ids has lead to ${conflicts} conflict${ - conflicts > 1 ? "s" : "" - }.\nIncrease the 'maxLength' to increase the id space and make conflicts less likely (recommended when there are many conflicts or application is expected to grow), or add an 'salt' number to try another hash starting value in the same id space (recommended when there is only a single conflict).` - ); - }); - } + const tracer = createTrace( + compiler.intermediateFileSystem, + this.outputPath ); - } -} + tracer.profiler.startProfiling(); -module.exports = DeterministicModuleIdsPlugin; + // Compiler Hooks + Object.keys(compiler.hooks).forEach(hookName => { + const hook = compiler.hooks[hookName]; + if (hook) { + hook.intercept(makeInterceptorFor("Compiler", tracer)(hookName)); + } + }); + Object.keys(compiler.resolverFactory.hooks).forEach(hookName => { + const hook = compiler.resolverFactory.hooks[hookName]; + if (hook) { + hook.intercept(makeInterceptorFor("Resolver", tracer)(hookName)); + } + }); -/***/ }), + compiler.hooks.compilation.tap( + pluginName, + (compilation, { normalModuleFactory, contextModuleFactory }) => { + interceptAllHooksFor(compilation, tracer, "Compilation"); + interceptAllHooksFor( + normalModuleFactory, + tracer, + "Normal Module Factory" + ); + interceptAllHooksFor( + contextModuleFactory, + tracer, + "Context Module Factory" + ); + interceptAllParserHooks(normalModuleFactory, tracer); + interceptAllJavascriptModulesPluginHooks(compilation, tracer); + } + ); -/***/ 21825: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // We need to write out the CPU profile when we are all done. + compiler.hooks.done.tapAsync( + { + name: pluginName, + stage: Infinity + }, + (stats, callback) => { + if (compiler.watchMode) return callback(); + tracer.profiler.stopProfiling().then(parsedResults => { + if (parsedResults === undefined) { + tracer.profiler.destroy(); + tracer.end(callback); + return; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const cpuStartTime = parsedResults.profile.startTime; + const cpuEndTime = parsedResults.profile.endTime; + tracer.trace.completeEvent({ + name: "TaskQueueManager::ProcessTaskFromWorkQueue", + id: ++tracer.counter, + cat: ["toplevel"], + ts: cpuStartTime, + args: { + src_file: "../../ipc/ipc_moji_bootstrap.cc", + src_func: "Accept" + } + }); + tracer.trace.completeEvent({ + name: "EvaluateScript", + id: ++tracer.counter, + cat: ["devtools.timeline"], + ts: cpuStartTime, + dur: cpuEndTime - cpuStartTime, + args: { + data: { + url: "webpack", + lineNumber: 1, + columnNumber: 1, + frame: "0xFFF" + } + } + }); -const { - compareModulesByPreOrderIndexOrIdentifier -} = __webpack_require__(29579); -const createSchemaValidation = __webpack_require__(32540); -const createHash = __webpack_require__(49835); -const { - getUsedModuleIdsAndModules, - getFullModuleName -} = __webpack_require__(63290); + tracer.trace.instantEvent({ + name: "CpuProfile", + id: ++tracer.counter, + cat: ["disabled-by-default-devtools.timeline"], + ts: cpuEndTime, + args: { + data: { + cpuProfile: parsedResults.profile + } + } + }); -/** @typedef {import("../../declarations/plugins/HashedModuleIdsPlugin").HashedModuleIdsPluginOptions} HashedModuleIdsPluginOptions */ + tracer.profiler.destroy(); + tracer.end(callback); + }); + } + ); + } +} -const validate = createSchemaValidation( - __webpack_require__(52210), - () => __webpack_require__(59106), - { - name: "Hashed Module Ids Plugin", - baseDataPath: "options" +const interceptAllHooksFor = (instance, tracer, logLabel) => { + if (Reflect.has(instance, "hooks")) { + Object.keys(instance.hooks).forEach(hookName => { + const hook = instance.hooks[hookName]; + if (hook && !hook._fakeHook) { + hook.intercept(makeInterceptorFor(logLabel, tracer)(hookName)); + } + }); } -); +}; -class HashedModuleIdsPlugin { - /** - * @param {HashedModuleIdsPluginOptions=} options options object - */ - constructor(options = {}) { - validate(options); +const interceptAllParserHooks = (moduleFactory, tracer) => { + const moduleTypes = [ + "javascript/auto", + "javascript/dynamic", + "javascript/esm", + "json", + "webassembly/async", + "webassembly/sync" + ]; - /** @type {HashedModuleIdsPluginOptions} */ - this.options = { - context: null, - hashFunction: "md4", - hashDigest: "base64", - hashDigestLength: 4, - ...options + moduleTypes.forEach(moduleType => { + moduleFactory.hooks.parser + .for(moduleType) + .tap("ProfilingPlugin", (parser, parserOpts) => { + interceptAllHooksFor(parser, tracer, "Parser"); + }); + }); +}; + +const interceptAllJavascriptModulesPluginHooks = (compilation, tracer) => { + interceptAllHooksFor( + { + hooks: + (__webpack_require__(89464).getCompilationHooks)( + compilation + ) + }, + tracer, + "JavascriptModulesPlugin" + ); +}; + +const makeInterceptorFor = (instance, tracer) => hookName => ({ + register: ({ name, type, context, fn }) => { + const newFn = + // Don't tap our own hooks to ensure stream can close cleanly + name === pluginName + ? fn + : makeNewProfiledTapFn(hookName, tracer, { + name, + type, + fn + }); + return { + name, + type, + context, + fn: newFn }; } +}); - apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap("HashedModuleIdsPlugin", compilation => { - compilation.hooks.moduleIds.tap("HashedModuleIdsPlugin", () => { - const chunkGraph = compilation.chunkGraph; - const context = this.options.context - ? this.options.context - : compiler.context; +// TODO improve typing +/** @typedef {(...args: TODO[]) => void | Promise} PluginFunction */ - const [usedIds, modules] = getUsedModuleIdsAndModules(compilation); - const modulesInNaturalOrder = modules.sort( - compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph) - ); - for (const module of modulesInNaturalOrder) { - const ident = getFullModuleName(module, context, compiler.root); - const hash = createHash(options.hashFunction); - hash.update(ident || ""); - const hashId = /** @type {string} */ ( - hash.digest(options.hashDigest) - ); - let len = options.hashDigestLength; - while (usedIds.has(hashId.substr(0, len))) len++; - const moduleId = hashId.substr(0, len); - chunkGraph.setModuleId(module, moduleId); - usedIds.add(moduleId); +/** + * @param {string} hookName Name of the hook to profile. + * @param {Trace} tracer The trace object. + * @param {object} options Options for the profiled fn. + * @param {string} options.name Plugin name + * @param {string} options.type Plugin type (sync | async | promise) + * @param {PluginFunction} options.fn Plugin function + * @returns {PluginFunction} Chainable hooked function. + */ +const makeNewProfiledTapFn = (hookName, tracer, { name, type, fn }) => { + const defaultCategory = ["blink.user_timing"]; + + switch (type) { + case "promise": + return (...args) => { + const id = ++tracer.counter; + tracer.trace.begin({ + name, + id, + cat: defaultCategory + }); + const promise = /** @type {Promise<*>} */ (fn(...args)); + return promise.then(r => { + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + return r; + }); + }; + case "async": + return (...args) => { + const id = ++tracer.counter; + tracer.trace.begin({ + name, + id, + cat: defaultCategory + }); + const callback = args.pop(); + fn(...args, (...r) => { + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + callback(...r); + }); + }; + case "sync": + return (...args) => { + const id = ++tracer.counter; + // Do not instrument ourself due to the CPU + // profile needing to be the last event in the trace. + if (name === pluginName) { + return fn(...args); } - }); - }); + + tracer.trace.begin({ + name, + id, + cat: defaultCategory + }); + let r; + try { + r = fn(...args); + } catch (error) { + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + throw error; + } + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + return r; + }; + default: + break; } -} +}; -module.exports = HashedModuleIdsPlugin; +module.exports = ProfilingPlugin; +module.exports.Profiler = Profiler; /***/ }), -/***/ 63290: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 96816: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -86757,481 +83500,587 @@ module.exports = HashedModuleIdsPlugin; -const createHash = __webpack_require__(49835); -const { makePathsRelative } = __webpack_require__(82186); -const numberHash = __webpack_require__(70002); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module")} Module */ -/** @typedef {typeof import("../util/Hash")} Hash */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** - * @param {string} str string to hash - * @param {number} len max length of the hash - * @param {string | Hash} hashFunction hash function to use - * @returns {string} hash - */ -const getHash = (str, len, hashFunction) => { - const hash = createHash(hashFunction); - hash.update(str); - const digest = /** @type {string} */ (hash.digest("hex")); - return digest.substr(0, len); +/** @type {Record} */ +const DEFINITIONS = { + f: { + definition: "var __WEBPACK_AMD_DEFINE_RESULT__;", + content: `!(__WEBPACK_AMD_DEFINE_RESULT__ = (#).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, + requests: [ + RuntimeGlobals.require, + RuntimeGlobals.exports, + RuntimeGlobals.module + ] + }, + o: { + definition: "", + content: "!(module.exports = #)", + requests: [RuntimeGlobals.module] + }, + of: { + definition: + "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;", + content: `!(__WEBPACK_AMD_DEFINE_FACTORY__ = (#), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, + requests: [ + RuntimeGlobals.require, + RuntimeGlobals.exports, + RuntimeGlobals.module + ] + }, + af: { + definition: + "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", + content: `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = (#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, + requests: [RuntimeGlobals.exports, RuntimeGlobals.module] + }, + ao: { + definition: "", + content: "!(#, module.exports = #)", + requests: [RuntimeGlobals.module] + }, + aof: { + definition: + "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", + content: `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, + requests: [RuntimeGlobals.exports, RuntimeGlobals.module] + }, + lf: { + definition: "var XXX, XXXmodule;", + content: + "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = (#).call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))", + requests: [RuntimeGlobals.require, RuntimeGlobals.module] + }, + lo: { + definition: "var XXX;", + content: "!(XXX = #)", + requests: [] + }, + lof: { + definition: "var XXX, XXXfactory, XXXmodule;", + content: + "!(XXXfactory = (#), (typeof XXXfactory === 'function' ? ((XXXmodule = { id: YYY, exports: {}, loaded: false }), (XXX = XXXfactory.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule)), (XXXmodule.loaded = true), XXX === undefined && (XXX = XXXmodule.exports)) : XXX = XXXfactory))", + requests: [RuntimeGlobals.require, RuntimeGlobals.module] + }, + laf: { + definition: "var __WEBPACK_AMD_DEFINE_ARRAY__, XXX, XXXexports;", + content: + "!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = (#).apply(XXXexports = {}, __WEBPACK_AMD_DEFINE_ARRAY__), XXX === undefined && (XXX = XXXexports))", + requests: [] + }, + lao: { + definition: "var XXX;", + content: "!(#, XXX = #)", + requests: [] + }, + laof: { + definition: "var XXXarray, XXXfactory, XXXexports, XXX;", + content: `!(XXXarray = #, XXXfactory = (#), + (typeof XXXfactory === 'function' ? + ((XXX = XXXfactory.apply(XXXexports = {}, XXXarray)), XXX === undefined && (XXX = XXXexports)) : + (XXX = XXXfactory) + ))`, + requests: [] + } }; -/** - * @param {string} str the string - * @returns {string} string prefixed by an underscore if it is a number - */ -const avoidNumber = str => { - // max length of a number is 21 chars, bigger numbers a written as "...e+xx" - if (str.length > 21) return str; - const firstChar = str.charCodeAt(0); - // skip everything that doesn't look like a number - // charCodes: "-": 45, "1": 49, "9": 57 - if (firstChar < 49) { - if (firstChar !== 45) return str; - } else if (firstChar > 57) { - return str; - } - if (str === +str + "") { - return `_${str}`; +class AMDDefineDependency extends NullDependency { + constructor(range, arrayRange, functionRange, objectRange, namedModule) { + super(); + this.range = range; + this.arrayRange = arrayRange; + this.functionRange = functionRange; + this.objectRange = objectRange; + this.namedModule = namedModule; + this.localModule = null; } - return str; -}; -/** - * @param {string} request the request - * @returns {string} id representation - */ -const requestToId = request => { - return request - .replace(/^(\.\.?\/)+/, "") - .replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_"); -}; -exports.requestToId = requestToId; + get type() { + return "amd define"; + } -/** - * @param {string} string the string - * @param {string} delimiter separator for string and hash - * @param {string | Hash} hashFunction hash function to use - * @returns {string} string with limited max length to 100 chars - */ -const shortenLongString = (string, delimiter, hashFunction) => { - if (string.length < 100) return string; - return ( - string.slice(0, 100 - 6 - delimiter.length) + - delimiter + - getHash(string, 6, hashFunction) - ); -}; + serialize(context) { + const { write } = context; + write(this.range); + write(this.arrayRange); + write(this.functionRange); + write(this.objectRange); + write(this.namedModule); + write(this.localModule); + super.serialize(context); + } -/** - * @param {Module} module the module - * @param {string} context context directory - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} short module name - */ -const getShortModuleName = (module, context, associatedObjectForCache) => { - const libIdent = module.libIdent({ context, associatedObjectForCache }); - if (libIdent) return avoidNumber(libIdent); - const nameForCondition = module.nameForCondition(); - if (nameForCondition) - return avoidNumber( - makePathsRelative(context, nameForCondition, associatedObjectForCache) - ); - return ""; -}; -exports.getShortModuleName = getShortModuleName; + deserialize(context) { + const { read } = context; + this.range = read(); + this.arrayRange = read(); + this.functionRange = read(); + this.objectRange = read(); + this.namedModule = read(); + this.localModule = read(); + super.deserialize(context); + } +} -/** - * @param {string} shortName the short name - * @param {Module} module the module - * @param {string} context context directory - * @param {string | Hash} hashFunction hash function to use - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} long module name - */ -const getLongModuleName = ( - shortName, - module, - context, - hashFunction, - associatedObjectForCache -) => { - const fullName = getFullModuleName(module, context, associatedObjectForCache); - return `${shortName}?${getHash(fullName, 4, hashFunction)}`; -}; -exports.getLongModuleName = getLongModuleName; +makeSerializable( + AMDDefineDependency, + "webpack/lib/dependencies/AMDDefineDependency" +); -/** - * @param {Module} module the module - * @param {string} context context directory - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} full module name - */ -const getFullModuleName = (module, context, associatedObjectForCache) => { - return makePathsRelative( - context, - module.identifier(), - associatedObjectForCache - ); -}; -exports.getFullModuleName = getFullModuleName; +AMDDefineDependency.Template = class AMDDefineDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, { runtimeRequirements }) { + const dep = /** @type {AMDDefineDependency} */ (dependency); + const branch = this.branch(dep); + const { definition, content, requests } = DEFINITIONS[branch]; + for (const req of requests) { + runtimeRequirements.add(req); + } + this.replace(dep, source, definition, content); + } -/** - * @param {Chunk} chunk the chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {string} context context directory - * @param {string} delimiter delimiter for names - * @param {string | Hash} hashFunction hash function to use - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} short chunk name - */ -const getShortChunkName = ( - chunk, - chunkGraph, - context, - delimiter, - hashFunction, - associatedObjectForCache -) => { - const modules = chunkGraph.getChunkRootModules(chunk); - const shortModuleNames = modules.map(m => - requestToId(getShortModuleName(m, context, associatedObjectForCache)) - ); - chunk.idNameHints.sort(); - const chunkName = Array.from(chunk.idNameHints) - .concat(shortModuleNames) - .filter(Boolean) - .join(delimiter); - return shortenLongString(chunkName, delimiter, hashFunction); -}; -exports.getShortChunkName = getShortChunkName; + localModuleVar(dependency) { + return ( + dependency.localModule && + dependency.localModule.used && + dependency.localModule.variableName() + ); + } -/** - * @param {Chunk} chunk the chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {string} context context directory - * @param {string} delimiter delimiter for names - * @param {string | Hash} hashFunction hash function to use - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} short chunk name - */ -const getLongChunkName = ( - chunk, - chunkGraph, - context, - delimiter, - hashFunction, - associatedObjectForCache -) => { - const modules = chunkGraph.getChunkRootModules(chunk); - const shortModuleNames = modules.map(m => - requestToId(getShortModuleName(m, context, associatedObjectForCache)) - ); - const longModuleNames = modules.map(m => - requestToId( - getLongModuleName("", m, context, hashFunction, associatedObjectForCache) - ) - ); - chunk.idNameHints.sort(); - const chunkName = Array.from(chunk.idNameHints) - .concat(shortModuleNames, longModuleNames) - .filter(Boolean) - .join(delimiter); - return shortenLongString(chunkName, delimiter, hashFunction); -}; -exports.getLongChunkName = getLongChunkName; + branch(dependency) { + const localModuleVar = this.localModuleVar(dependency) ? "l" : ""; + const arrayRange = dependency.arrayRange ? "a" : ""; + const objectRange = dependency.objectRange ? "o" : ""; + const functionRange = dependency.functionRange ? "f" : ""; + return localModuleVar + arrayRange + objectRange + functionRange; + } -/** - * @param {Chunk} chunk the chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {string} context context directory - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} full chunk name - */ -const getFullChunkName = ( - chunk, - chunkGraph, - context, - associatedObjectForCache -) => { - if (chunk.name) return chunk.name; - const modules = chunkGraph.getChunkRootModules(chunk); - const fullModuleNames = modules.map(m => - makePathsRelative(context, m.identifier(), associatedObjectForCache) - ); - return fullModuleNames.join(); -}; -exports.getFullChunkName = getFullChunkName; + replace(dependency, source, definition, text) { + const localModuleVar = this.localModuleVar(dependency); + if (localModuleVar) { + text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); + definition = definition.replace( + /XXX/g, + localModuleVar.replace(/\$/g, "$$$$") + ); + } -/** - * @template K - * @template V - * @param {Map} map a map from key to values - * @param {K} key key - * @param {V} value value - * @returns {void} - */ -const addToMapOfItems = (map, key, value) => { - let array = map.get(key); - if (array === undefined) { - array = []; - map.set(key, array); - } - array.push(value); -}; + if (dependency.namedModule) { + text = text.replace(/YYY/g, JSON.stringify(dependency.namedModule)); + } -/** - * @param {Compilation} compilation the compilation - * @param {function(Module): boolean=} filter filter modules - * @returns {[Set, Module[]]} used module ids as strings and modules without id matching the filter - */ -const getUsedModuleIdsAndModules = (compilation, filter) => { - const chunkGraph = compilation.chunkGraph; + const texts = text.split("#"); - const modules = []; + if (definition) source.insert(0, definition); - /** @type {Set} */ - const usedIds = new Set(); - if (compilation.usedModuleIds) { - for (const id of compilation.usedModuleIds) { - usedIds.add(id + ""); + let current = dependency.range[0]; + if (dependency.arrayRange) { + source.replace(current, dependency.arrayRange[0] - 1, texts.shift()); + current = dependency.arrayRange[1]; } - } - for (const module of compilation.modules) { - if (!module.needId) continue; - const moduleId = chunkGraph.getModuleId(module); - if (moduleId !== null) { - usedIds.add(moduleId + ""); - } else { - if ( - (!filter || filter(module)) && - chunkGraph.getNumberOfModuleChunks(module) !== 0 - ) { - modules.push(module); - } + if (dependency.objectRange) { + source.replace(current, dependency.objectRange[0] - 1, texts.shift()); + current = dependency.objectRange[1]; + } else if (dependency.functionRange) { + source.replace(current, dependency.functionRange[0] - 1, texts.shift()); + current = dependency.functionRange[1]; } + source.replace(current, dependency.range[1] - 1, texts.shift()); + if (texts.length > 0) throw new Error("Implementation error"); } - - return [usedIds, modules]; }; -exports.getUsedModuleIdsAndModules = getUsedModuleIdsAndModules; -/** - * @param {Compilation} compilation the compilation - * @returns {Set} used chunk ids as strings - */ -const getUsedChunkIds = compilation => { - /** @type {Set} */ - const usedIds = new Set(); - if (compilation.usedChunkIds) { - for (const id of compilation.usedChunkIds) { - usedIds.add(id + ""); - } - } +module.exports = AMDDefineDependency; - for (const chunk of compilation.chunks) { - const chunkId = chunk.id; - if (chunkId !== null) { - usedIds.add(chunkId + ""); - } - } - return usedIds; -}; -exports.getUsedChunkIds = getUsedChunkIds; +/***/ }), -/** - * @template T - * @param {Iterable} items list of items to be named - * @param {function(T): string} getShortName get a short name for an item - * @param {function(T, string): string} getLongName get a long name for an item - * @param {function(T, T): -1|0|1} comparator order of items - * @param {Set} usedIds already used ids, will not be assigned - * @param {function(T, string): void} assignName assign a name to an item - * @returns {T[]} list of items without a name - */ -const assignNames = ( - items, - getShortName, - getLongName, - comparator, - usedIds, - assignName -) => { - /** @type {Map} */ - const nameToItems = new Map(); +/***/ 48519: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - for (const item of items) { - const name = getShortName(item); - addToMapOfItems(nameToItems, name, item); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {Map} */ - const nameToItems2 = new Map(); - for (const [name, items] of nameToItems) { - if (items.length > 1 || !name) { - for (const item of items) { - const longName = getLongName(item, name); - addToMapOfItems(nameToItems2, longName, item); - } - } else { - addToMapOfItems(nameToItems2, name, items[0]); - } - } - - /** @type {T[]} */ - const unnamedItems = []; - for (const [name, items] of nameToItems2) { - if (!name) { - for (const item of items) { - unnamedItems.push(item); - } - } else if (items.length === 1 && !usedIds.has(name)) { - assignName(items[0], name); - usedIds.add(name); - } else { - items.sort(comparator); - let i = 0; - for (const item of items) { - while (nameToItems2.has(name + i) && usedIds.has(name + i)) i++; - assignName(item, name + i); - usedIds.add(name + i); - i++; - } - } - } +const RuntimeGlobals = __webpack_require__(16475); +const AMDDefineDependency = __webpack_require__(96816); +const AMDRequireArrayDependency = __webpack_require__(33516); +const AMDRequireContextDependency = __webpack_require__(96123); +const AMDRequireItemDependency = __webpack_require__(71806); +const ConstDependency = __webpack_require__(76911); +const ContextDependencyHelpers = __webpack_require__(99630); +const DynamicExports = __webpack_require__(32006); +const LocalModuleDependency = __webpack_require__(52805); +const { addLocalModule, getLocalModule } = __webpack_require__(75827); - unnamedItems.sort(comparator); - return unnamedItems; +const isBoundFunctionExpression = expr => { + if (expr.type !== "CallExpression") return false; + if (expr.callee.type !== "MemberExpression") return false; + if (expr.callee.computed) return false; + if (expr.callee.object.type !== "FunctionExpression") return false; + if (expr.callee.property.type !== "Identifier") return false; + if (expr.callee.property.name !== "bind") return false; + return true; }; -exports.assignNames = assignNames; -/** - * @template T - * @param {T[]} items list of items to be named - * @param {function(T): string} getName get a name for an item - * @param {function(T, T): -1|0|1} comparator order of items - * @param {function(T, number): boolean} assignId assign an id to an item - * @param {number[]} ranges usable ranges for ids - * @param {number} expandFactor factor to create more ranges - * @param {number} extraSpace extra space to allocate, i. e. when some ids are already used - * @param {number} salt salting number to initialize hashing - * @returns {void} - */ -const assignDeterministicIds = ( - items, - getName, - comparator, - assignId, - ranges = [10], - expandFactor = 10, - extraSpace = 0, - salt = 0 -) => { - items.sort(comparator); +const isUnboundFunctionExpression = expr => { + if (expr.type === "FunctionExpression") return true; + if (expr.type === "ArrowFunctionExpression") return true; + return false; +}; - // max 5% fill rate - const optimalRange = Math.min( - Math.ceil(items.length * 20) + extraSpace, - Number.MAX_SAFE_INTEGER - ); +const isCallable = expr => { + if (isUnboundFunctionExpression(expr)) return true; + if (isBoundFunctionExpression(expr)) return true; + return false; +}; - let i = 0; - let range = ranges[i]; - while (range < optimalRange) { - i++; - if (i < ranges.length) { - range = Math.min(ranges[i], Number.MAX_SAFE_INTEGER); - } else if (expandFactor) { - range = Math.min(range * expandFactor, Number.MAX_SAFE_INTEGER); - } else { - break; - } +class AMDDefineDependencyParserPlugin { + constructor(options) { + this.options = options; } - for (const item of items) { - const ident = getName(item); - let id; - let i = salt; - do { - id = numberHash(ident + i++, range); - } while (!assignId(item, id)); + apply(parser) { + parser.hooks.call + .for("define") + .tap( + "AMDDefineDependencyParserPlugin", + this.processCallDefine.bind(this, parser) + ); } -}; -exports.assignDeterministicIds = assignDeterministicIds; - -/** - * @param {Set} usedIds used ids - * @param {Iterable} modules the modules - * @param {Compilation} compilation the compilation - * @returns {void} - */ -const assignAscendingModuleIds = (usedIds, modules, compilation) => { - const chunkGraph = compilation.chunkGraph; - let nextId = 0; - let assignId; - if (usedIds.size > 0) { - assignId = module => { - if (chunkGraph.getModuleId(module) === null) { - while (usedIds.has(nextId + "")) nextId++; - chunkGraph.setModuleId(module, nextId++); - } - }; - } else { - assignId = module => { - if (chunkGraph.getModuleId(module) === null) { - chunkGraph.setModuleId(module, nextId++); + processArray(parser, expr, param, identifiers, namedModule) { + if (param.isArray()) { + param.items.forEach((param, idx) => { + if ( + param.isString() && + ["require", "module", "exports"].includes(param.string) + ) + identifiers[idx] = param.string; + const result = this.processItem(parser, expr, param, namedModule); + if (result === undefined) { + this.processContext(parser, expr, param); + } + }); + return true; + } else if (param.isConstArray()) { + const deps = []; + param.array.forEach((request, idx) => { + let dep; + let localModule; + if (request === "require") { + identifiers[idx] = request; + dep = "__webpack_require__"; + } else if (["exports", "module"].includes(request)) { + identifiers[idx] = request; + dep = request; + } else if ((localModule = getLocalModule(parser.state, request))) { + localModule.flagUsed(); + dep = new LocalModuleDependency(localModule, undefined, false); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + } else { + dep = this.newRequireItemDependency(request); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + } + deps.push(dep); + }); + const dep = this.newRequireArrayDependency(deps, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.module.addPresentationalDependency(dep); + return true; + } + } + processItem(parser, expr, param, namedModule) { + if (param.isConditional()) { + param.options.forEach(param => { + const result = this.processItem(parser, expr, param); + if (result === undefined) { + this.processContext(parser, expr, param); + } + }); + return true; + } else if (param.isString()) { + let dep, localModule; + if (param.string === "require") { + dep = new ConstDependency("__webpack_require__", param.range, [ + RuntimeGlobals.require + ]); + } else if (param.string === "exports") { + dep = new ConstDependency("exports", param.range, [ + RuntimeGlobals.exports + ]); + } else if (param.string === "module") { + dep = new ConstDependency("module", param.range, [ + RuntimeGlobals.module + ]); + } else if ( + (localModule = getLocalModule(parser.state, param.string, namedModule)) + ) { + localModule.flagUsed(); + dep = new LocalModuleDependency(localModule, param.range, false); + } else { + dep = this.newRequireItemDependency(param.string, param.range); + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; } - }; + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + } } - for (const module of modules) { - assignId(module); + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + param.range, + param, + expr, + this.options, + { + category: "amd" + }, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; } -}; -exports.assignAscendingModuleIds = assignAscendingModuleIds; - -/** - * @param {Iterable} chunks the chunks - * @param {Compilation} compilation the compilation - * @returns {void} - */ -const assignAscendingChunkIds = (chunks, compilation) => { - const usedIds = getUsedChunkIds(compilation); - let nextId = 0; - if (usedIds.size > 0) { - for (const chunk of chunks) { - if (chunk.id === null) { - while (usedIds.has(nextId + "")) nextId++; - chunk.id = nextId; - chunk.ids = [nextId]; - nextId++; + processCallDefine(parser, expr) { + let array, fn, obj, namedModule; + switch (expr.arguments.length) { + case 1: + if (isCallable(expr.arguments[0])) { + // define(f() {…}) + fn = expr.arguments[0]; + } else if (expr.arguments[0].type === "ObjectExpression") { + // define({…}) + obj = expr.arguments[0]; + } else { + // define(expr) + // unclear if function or object + obj = fn = expr.arguments[0]; + } + break; + case 2: + if (expr.arguments[0].type === "Literal") { + namedModule = expr.arguments[0].value; + // define("…", …) + if (isCallable(expr.arguments[1])) { + // define("…", f() {…}) + fn = expr.arguments[1]; + } else if (expr.arguments[1].type === "ObjectExpression") { + // define("…", {…}) + obj = expr.arguments[1]; + } else { + // define("…", expr) + // unclear if function or object + obj = fn = expr.arguments[1]; + } + } else { + array = expr.arguments[0]; + if (isCallable(expr.arguments[1])) { + // define([…], f() {}) + fn = expr.arguments[1]; + } else if (expr.arguments[1].type === "ObjectExpression") { + // define([…], {…}) + obj = expr.arguments[1]; + } else { + // define([…], expr) + // unclear if function or object + obj = fn = expr.arguments[1]; + } + } + break; + case 3: + // define("…", […], f() {…}) + namedModule = expr.arguments[0].value; + array = expr.arguments[1]; + if (isCallable(expr.arguments[2])) { + // define("…", […], f() {}) + fn = expr.arguments[2]; + } else if (expr.arguments[2].type === "ObjectExpression") { + // define("…", […], {…}) + obj = expr.arguments[2]; + } else { + // define("…", […], expr) + // unclear if function or object + obj = fn = expr.arguments[2]; + } + break; + default: + return; + } + DynamicExports.bailout(parser.state); + let fnParams = null; + let fnParamsOffset = 0; + if (fn) { + if (isUnboundFunctionExpression(fn)) { + fnParams = fn.params; + } else if (isBoundFunctionExpression(fn)) { + fnParams = fn.callee.object.params; + fnParamsOffset = fn.arguments.length - 1; + if (fnParamsOffset < 0) { + fnParamsOffset = 0; + } } } - } else { - for (const chunk of chunks) { - if (chunk.id === null) { - chunk.id = nextId; - chunk.ids = [nextId]; - nextId++; + let fnRenames = new Map(); + if (array) { + const identifiers = {}; + const param = parser.evaluateExpression(array); + const result = this.processArray( + parser, + expr, + param, + identifiers, + namedModule + ); + if (!result) return; + if (fnParams) { + fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { + if (identifiers[idx]) { + fnRenames.set(param.name, parser.getVariableInfo(identifiers[idx])); + return false; + } + return true; + }); + } + } else { + const identifiers = ["require", "exports", "module"]; + if (fnParams) { + fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { + if (identifiers[idx]) { + fnRenames.set(param.name, parser.getVariableInfo(identifiers[idx])); + return false; + } + return true; + }); + } + } + let inTry; + if (fn && isUnboundFunctionExpression(fn)) { + inTry = parser.scope.inTry; + parser.inScope(fnParams, () => { + for (const [name, varInfo] of fnRenames) { + parser.setVariable(name, varInfo); + } + parser.scope.inTry = inTry; + if (fn.body.type === "BlockStatement") { + parser.detectMode(fn.body.body); + const prev = parser.prevStatement; + parser.preWalkStatement(fn.body); + parser.prevStatement = prev; + parser.walkStatement(fn.body); + } else { + parser.walkExpression(fn.body); + } + }); + } else if (fn && isBoundFunctionExpression(fn)) { + inTry = parser.scope.inTry; + parser.inScope( + fn.callee.object.params.filter( + i => !["require", "module", "exports"].includes(i.name) + ), + () => { + for (const [name, varInfo] of fnRenames) { + parser.setVariable(name, varInfo); + } + parser.scope.inTry = inTry; + if (fn.callee.object.body.type === "BlockStatement") { + parser.detectMode(fn.callee.object.body.body); + const prev = parser.prevStatement; + parser.preWalkStatement(fn.callee.object.body); + parser.prevStatement = prev; + parser.walkStatement(fn.callee.object.body); + } else { + parser.walkExpression(fn.callee.object.body); + } + } + ); + if (fn.arguments) { + parser.walkExpressions(fn.arguments); } + } else if (fn || obj) { + parser.walkExpression(fn || obj); + } + + const dep = this.newDefineDependency( + expr.range, + array ? array.range : null, + fn ? fn.range : null, + obj ? obj.range : null, + namedModule ? namedModule : null + ); + dep.loc = expr.loc; + if (namedModule) { + dep.localModule = addLocalModule(parser.state, namedModule); } + parser.state.module.addPresentationalDependency(dep); + return true; } -}; -exports.assignAscendingChunkIds = assignAscendingChunkIds; + + newDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ) { + return new AMDDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ); + } + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); + } + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); + } +} +module.exports = AMDDefineDependencyParserPlugin; /***/ }), -/***/ 6454: +/***/ 50067: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -87242,23 +84091,38 @@ exports.assignAscendingChunkIds = assignAscendingChunkIds; -const { compareChunksNatural } = __webpack_require__(29579); +const RuntimeGlobals = __webpack_require__(16475); const { - getShortChunkName, - getLongChunkName, - assignNames, - getUsedChunkIds, - assignAscendingChunkIds -} = __webpack_require__(63290); + approve, + evaluateToIdentifier, + evaluateToString, + toConstantDependency +} = __webpack_require__(93998); -/** @typedef {import("../Chunk")} Chunk */ +const AMDDefineDependency = __webpack_require__(96816); +const AMDDefineDependencyParserPlugin = __webpack_require__(48519); +const AMDRequireArrayDependency = __webpack_require__(33516); +const AMDRequireContextDependency = __webpack_require__(96123); +const AMDRequireDependenciesBlockParserPlugin = __webpack_require__(66866); +const AMDRequireDependency = __webpack_require__(43911); +const AMDRequireItemDependency = __webpack_require__(71806); +const { + AMDDefineRuntimeModule, + AMDOptionsRuntimeModule +} = __webpack_require__(45242); +const ConstDependency = __webpack_require__(76911); +const LocalModuleDependency = __webpack_require__(52805); +const UnsupportedDependency = __webpack_require__(51669); + +/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ /** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -class NamedChunkIdsPlugin { - constructor(options) { - this.delimiter = (options && options.delimiter) || "-"; - this.context = options && options.context; +class AMDPlugin { + /** + * @param {Record} amdOptions the AMD options + */ + constructor(amdOptions) { + this.amdOptions = amdOptions; } /** @@ -87267,126 +84131,180 @@ class NamedChunkIdsPlugin { * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap("NamedChunkIdsPlugin", compilation => { - const { hashFunction } = compilation.outputOptions; - compilation.hooks.chunkIds.tap("NamedChunkIdsPlugin", chunks => { - const chunkGraph = compilation.chunkGraph; - const context = this.context ? this.context : compiler.context; - const delimiter = this.delimiter; + const amdOptions = this.amdOptions; + compiler.hooks.compilation.tap( + "AMDPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyTemplates.set( + AMDRequireDependency, + new AMDRequireDependency.Template() + ); - const unnamedChunks = assignNames( - Array.from(chunks).filter(chunk => { - if (chunk.name) { - chunk.id = chunk.name; - chunk.ids = [chunk.name]; - } - return chunk.id === null; - }), - chunk => - getShortChunkName( - chunk, - chunkGraph, - context, - delimiter, - hashFunction, - compiler.root - ), - chunk => - getLongChunkName( - chunk, - chunkGraph, - context, - delimiter, - hashFunction, - compiler.root - ), - compareChunksNatural(chunkGraph), - getUsedChunkIds(compilation), - (chunk, name) => { - chunk.id = name; - chunk.ids = [name]; - } + compilation.dependencyFactories.set( + AMDRequireItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + AMDRequireItemDependency, + new AMDRequireItemDependency.Template() ); - if (unnamedChunks.length > 0) { - assignAscendingChunkIds(unnamedChunks, compilation); - } - }); - }); - } -} -module.exports = NamedChunkIdsPlugin; + compilation.dependencyTemplates.set( + AMDRequireArrayDependency, + new AMDRequireArrayDependency.Template() + ); + compilation.dependencyFactories.set( + AMDRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + AMDRequireContextDependency, + new AMDRequireContextDependency.Template() + ); -/***/ }), + compilation.dependencyTemplates.set( + AMDDefineDependency, + new AMDDefineDependency.Template() + ); -/***/ 24339: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + compilation.dependencyTemplates.set( + UnsupportedDependency, + new UnsupportedDependency.Template() + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + compilation.dependencyTemplates.set( + LocalModuleDependency, + new LocalModuleDependency.Template() + ); + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.amdDefine) + .tap("AMDPlugin", (module, set) => { + set.add(RuntimeGlobals.require); + }); + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.amdOptions) + .tap("AMDPlugin", (module, set) => { + set.add(RuntimeGlobals.requireScope); + }); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const { - getShortModuleName, - getLongModuleName, - assignNames, - getUsedModuleIdsAndModules, - assignAscendingModuleIds -} = __webpack_require__(63290); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.amdDefine) + .tap("AMDPlugin", (chunk, set) => { + compilation.addRuntimeModule(chunk, new AMDDefineRuntimeModule()); + }); -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.amdOptions) + .tap("AMDPlugin", (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new AMDOptionsRuntimeModule(amdOptions) + ); + }); -class NamedModuleIdsPlugin { - constructor(options) { - this.options = options || {}; - } + const handler = (parser, parserOptions) => { + if (parserOptions.amd !== undefined && !parserOptions.amd) return; - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const { root } = compiler; - compiler.hooks.compilation.tap("NamedModuleIdsPlugin", compilation => { - const { hashFunction } = compilation.outputOptions; - compilation.hooks.moduleIds.tap("NamedModuleIdsPlugin", () => { - const chunkGraph = compilation.chunkGraph; - const context = this.options.context - ? this.options.context - : compiler.context; + const tapOptionsHooks = (optionExpr, rootName, getMembers) => { + parser.hooks.expression + .for(optionExpr) + .tap( + "AMDPlugin", + toConstantDependency(parser, RuntimeGlobals.amdOptions, [ + RuntimeGlobals.amdOptions + ]) + ); + parser.hooks.evaluateIdentifier + .for(optionExpr) + .tap( + "AMDPlugin", + evaluateToIdentifier(optionExpr, rootName, getMembers, true) + ); + parser.hooks.evaluateTypeof + .for(optionExpr) + .tap("AMDPlugin", evaluateToString("object")); + parser.hooks.typeof + .for(optionExpr) + .tap( + "AMDPlugin", + toConstantDependency(parser, JSON.stringify("object")) + ); + }; - const [usedIds, modules] = getUsedModuleIdsAndModules(compilation); - const unnamedModules = assignNames( - modules, - m => getShortModuleName(m, context, root), - (m, shortName) => - getLongModuleName(shortName, m, context, hashFunction, root), - compareModulesByIdentifier, - usedIds, - (m, name) => chunkGraph.setModuleId(m, name) - ); - if (unnamedModules.length > 0) { - assignAscendingModuleIds(usedIds, unnamedModules, compilation); - } - }); - }); + new AMDRequireDependenciesBlockParserPlugin(parserOptions).apply( + parser + ); + new AMDDefineDependencyParserPlugin(parserOptions).apply(parser); + + tapOptionsHooks("define.amd", "define", () => "amd"); + tapOptionsHooks("require.amd", "require", () => ["amd"]); + tapOptionsHooks( + "__webpack_amd_options__", + "__webpack_amd_options__", + () => [] + ); + + parser.hooks.expression.for("define").tap("AMDPlugin", expr => { + const dep = new ConstDependency( + RuntimeGlobals.amdDefine, + expr.range, + [RuntimeGlobals.amdDefine] + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.typeof + .for("define") + .tap( + "AMDPlugin", + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for("define") + .tap("AMDPlugin", evaluateToString("function")); + parser.hooks.canRename.for("define").tap("AMDPlugin", approve); + parser.hooks.rename.for("define").tap("AMDPlugin", expr => { + const dep = new ConstDependency( + RuntimeGlobals.amdDefine, + expr.range, + [RuntimeGlobals.amdDefine] + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return false; + }); + parser.hooks.typeof + .for("require") + .tap( + "AMDPlugin", + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for("require") + .tap("AMDPlugin", evaluateToString("function")); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("AMDPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("AMDPlugin", handler); + } + ); } } -module.exports = NamedModuleIdsPlugin; +module.exports = AMDPlugin; /***/ }), -/***/ 86221: +/***/ 33516: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -87397,84 +84315,103 @@ module.exports = NamedModuleIdsPlugin; -const { compareChunksNatural } = __webpack_require__(29579); -const { assignAscendingChunkIds } = __webpack_require__(63290); +const DependencyTemplate = __webpack_require__(5160); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -class NaturalChunkIdsPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap("NaturalChunkIdsPlugin", compilation => { - compilation.hooks.chunkIds.tap("NaturalChunkIdsPlugin", chunks => { - const chunkGraph = compilation.chunkGraph; - const compareNatural = compareChunksNatural(chunkGraph); - const chunksInNaturalOrder = Array.from(chunks).sort(compareNatural); - assignAscendingChunkIds(chunksInNaturalOrder, compilation); - }); - }); +class AMDRequireArrayDependency extends NullDependency { + constructor(depsArray, range) { + super(); + + this.depsArray = depsArray; + this.range = range; } -} -module.exports = NaturalChunkIdsPlugin; + get type() { + return "amd require array"; + } + get category() { + return "amd"; + } -/***/ }), + serialize(context) { + const { write } = context; -/***/ 83366: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + write(this.depsArray); + write(this.range); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ + super.serialize(context); + } + deserialize(context) { + const { read } = context; + this.depsArray = read(); + this.range = read(); -const { - compareModulesByPreOrderIndexOrIdentifier -} = __webpack_require__(29579); -const { - assignAscendingModuleIds, - getUsedModuleIdsAndModules -} = __webpack_require__(63290); + super.deserialize(context); + } +} -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +makeSerializable( + AMDRequireArrayDependency, + "webpack/lib/dependencies/AMDRequireArrayDependency" +); -class NaturalModuleIdsPlugin { +AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate extends ( + DependencyTemplate +) { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - compiler.hooks.compilation.tap("NaturalModuleIdsPlugin", compilation => { - compilation.hooks.moduleIds.tap("NaturalModuleIdsPlugin", modules => { - const [usedIds, modulesInNaturalOrder] = - getUsedModuleIdsAndModules(compilation); - modulesInNaturalOrder.sort( - compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph) - ); - assignAscendingModuleIds(usedIds, modulesInNaturalOrder, compilation); - }); + apply(dependency, source, templateContext) { + const dep = /** @type {AMDRequireArrayDependency} */ (dependency); + const content = this.getContent(dep, templateContext); + source.replace(dep.range[0], dep.range[1] - 1, content); + } + + getContent(dep, templateContext) { + const requires = dep.depsArray.map(dependency => { + return this.contentForDependency(dependency, templateContext); }); + return `[${requires.join(", ")}]`; } -} -module.exports = NaturalModuleIdsPlugin; + contentForDependency( + dep, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + if (typeof dep === "string") { + return dep; + } + + if (dep.localModule) { + return dep.localModule.variableName(); + } else { + return runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + runtimeRequirements + }); + } + } +}; + +module.exports = AMDRequireArrayDependency; /***/ }), -/***/ 51020: +/***/ 96123: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -87485,84 +84422,57 @@ module.exports = NaturalModuleIdsPlugin; -const { compareChunksNatural } = __webpack_require__(29579); -const createSchemaValidation = __webpack_require__(32540); -const { assignAscendingChunkIds } = __webpack_require__(63290); +const makeSerializable = __webpack_require__(33032); +const ContextDependency = __webpack_require__(88101); -/** @typedef {import("../../declarations/plugins/ids/OccurrenceChunkIdsPlugin").OccurrenceChunkIdsPluginOptions} OccurrenceChunkIdsPluginOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +class AMDRequireContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); -const validate = createSchemaValidation( - __webpack_require__(24344), - () => __webpack_require__(53576), - { - name: "Occurrence Order Chunk Ids Plugin", - baseDataPath: "options" + this.range = range; + this.valueRange = valueRange; } -); -class OccurrenceChunkIdsPlugin { - /** - * @param {OccurrenceChunkIdsPluginOptions=} options options object - */ - constructor(options = {}) { - validate(options); - this.options = options; + get type() { + return "amd require context"; } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const prioritiseInitial = this.options.prioritiseInitial; - compiler.hooks.compilation.tap("OccurrenceChunkIdsPlugin", compilation => { - compilation.hooks.chunkIds.tap("OccurrenceChunkIdsPlugin", chunks => { - const chunkGraph = compilation.chunkGraph; + get category() { + return "amd"; + } - /** @type {Map} */ - const occursInInitialChunksMap = new Map(); + serialize(context) { + const { write } = context; - const compareNatural = compareChunksNatural(chunkGraph); + write(this.range); + write(this.valueRange); - for (const c of chunks) { - let occurs = 0; - for (const chunkGroup of c.groupsIterable) { - for (const parent of chunkGroup.parentsIterable) { - if (parent.isInitial()) occurs++; - } - } - occursInInitialChunksMap.set(c, occurs); - } + super.serialize(context); + } - const chunksInOccurrenceOrder = Array.from(chunks).sort((a, b) => { - if (prioritiseInitial) { - const aEntryOccurs = occursInInitialChunksMap.get(a); - const bEntryOccurs = occursInInitialChunksMap.get(b); - if (aEntryOccurs > bEntryOccurs) return -1; - if (aEntryOccurs < bEntryOccurs) return 1; - } - const aOccurs = a.getNumberOfGroups(); - const bOccurs = b.getNumberOfGroups(); - if (aOccurs > bOccurs) return -1; - if (aOccurs < bOccurs) return 1; - return compareNatural(a, b); - }); - assignAscendingChunkIds(chunksInOccurrenceOrder, compilation); - }); - }); + deserialize(context) { + const { read } = context; + + this.range = read(); + this.valueRange = read(); + + super.deserialize(context); } } -module.exports = OccurrenceChunkIdsPlugin; +makeSerializable( + AMDRequireContextDependency, + "webpack/lib/dependencies/AMDRequireContextDependency" +); + +AMDRequireContextDependency.Template = __webpack_require__(75815); + +module.exports = AMDRequireContextDependency; /***/ }), -/***/ 35371: +/***/ 76932: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -87573,163 +84483,313 @@ module.exports = OccurrenceChunkIdsPlugin; -const { - compareModulesByPreOrderIndexOrIdentifier -} = __webpack_require__(29579); -const createSchemaValidation = __webpack_require__(32540); -const { - assignAscendingModuleIds, - getUsedModuleIdsAndModules -} = __webpack_require__(63290); - -/** @typedef {import("../../declarations/plugins/ids/OccurrenceModuleIdsPlugin").OccurrenceModuleIdsPluginOptions} OccurrenceModuleIdsPluginOptions */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +const AsyncDependenciesBlock = __webpack_require__(47736); +const makeSerializable = __webpack_require__(33032); -const validate = createSchemaValidation( - __webpack_require__(14916), - () => __webpack_require__(19330), - { - name: "Occurrence Order Module Ids Plugin", - baseDataPath: "options" +class AMDRequireDependenciesBlock extends AsyncDependenciesBlock { + constructor(loc, request) { + super(null, loc, request); } +} + +makeSerializable( + AMDRequireDependenciesBlock, + "webpack/lib/dependencies/AMDRequireDependenciesBlock" ); -class OccurrenceModuleIdsPlugin { - /** - * @param {OccurrenceModuleIdsPluginOptions=} options options object - */ - constructor(options = {}) { - validate(options); - this.options = options; - } +module.exports = AMDRequireDependenciesBlock; - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const prioritiseInitial = this.options.prioritiseInitial; - compiler.hooks.compilation.tap("OccurrenceModuleIdsPlugin", compilation => { - const moduleGraph = compilation.moduleGraph; - compilation.hooks.moduleIds.tap("OccurrenceModuleIdsPlugin", () => { - const chunkGraph = compilation.chunkGraph; +/***/ }), - const [usedIds, modulesInOccurrenceOrder] = - getUsedModuleIdsAndModules(compilation); +/***/ 66866: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const occursInInitialChunksMap = new Map(); - const occursInAllChunksMap = new Map(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const initialChunkChunkMap = new Map(); - const entryCountMap = new Map(); - for (const m of modulesInOccurrenceOrder) { - let initial = 0; - let entry = 0; - for (const c of chunkGraph.getModuleChunksIterable(m)) { - if (c.canBeInitial()) initial++; - if (chunkGraph.isEntryModuleInChunk(m, c)) entry++; - } - initialChunkChunkMap.set(m, initial); - entryCountMap.set(m, entry); - } - /** - * @param {Module} module module - * @returns {number} count of occurs - */ - const countOccursInEntry = module => { - let sum = 0; - for (const [ - originModule, - connections - ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { - if (!originModule) continue; - if (!connections.some(c => c.isTargetActive(undefined))) continue; - sum += initialChunkChunkMap.get(originModule); - } - return sum; - }; - /** - * @param {Module} module module - * @returns {number} count of occurs - */ - const countOccurs = module => { - let sum = 0; - for (const [ - originModule, - connections - ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { - if (!originModule) continue; - const chunkModules = - chunkGraph.getNumberOfModuleChunks(originModule); - for (const c of connections) { - if (!c.isTargetActive(undefined)) continue; - if (!c.dependency) continue; - const factor = c.dependency.getNumberOfIdOccurrences(); - if (factor === 0) continue; - sum += factor * chunkModules; - } - } - return sum; - }; +const RuntimeGlobals = __webpack_require__(16475); +const UnsupportedFeatureWarning = __webpack_require__(42495); +const AMDRequireArrayDependency = __webpack_require__(33516); +const AMDRequireContextDependency = __webpack_require__(96123); +const AMDRequireDependenciesBlock = __webpack_require__(76932); +const AMDRequireDependency = __webpack_require__(43911); +const AMDRequireItemDependency = __webpack_require__(71806); +const ConstDependency = __webpack_require__(76911); +const ContextDependencyHelpers = __webpack_require__(99630); +const LocalModuleDependency = __webpack_require__(52805); +const { getLocalModule } = __webpack_require__(75827); +const UnsupportedDependency = __webpack_require__(51669); +const getFunctionExpression = __webpack_require__(50396); - if (prioritiseInitial) { - for (const m of modulesInOccurrenceOrder) { - const result = - countOccursInEntry(m) + - initialChunkChunkMap.get(m) + - entryCountMap.get(m); - occursInInitialChunksMap.set(m, result); +class AMDRequireDependenciesBlockParserPlugin { + constructor(options) { + this.options = options; + } + + processFunctionArgument(parser, expression) { + let bindThis = true; + const fnData = getFunctionExpression(expression); + if (fnData) { + parser.inScope( + fnData.fn.params.filter(i => { + return !["require", "module", "exports"].includes(i.name); + }), + () => { + if (fnData.fn.body.type === "BlockStatement") { + parser.walkStatement(fnData.fn.body); + } else { + parser.walkExpression(fnData.fn.body); } } + ); + parser.walkExpressions(fnData.expressions); + if (fnData.needThis === false) { + bindThis = false; + } + } else { + parser.walkExpression(expression); + } + return bindThis; + } - for (const m of modulesInOccurrenceOrder) { - const result = - countOccurs(m) + - chunkGraph.getNumberOfModuleChunks(m) + - entryCountMap.get(m); - occursInAllChunksMap.set(m, result); - } + apply(parser) { + parser.hooks.call + .for("require") + .tap( + "AMDRequireDependenciesBlockParserPlugin", + this.processCallRequire.bind(this, parser) + ); + } - const naturalCompare = compareModulesByPreOrderIndexOrIdentifier( - compilation.moduleGraph + processArray(parser, expr, param) { + if (param.isArray()) { + for (const p of param.items) { + const result = this.processItem(parser, expr, p); + if (result === undefined) { + this.processContext(parser, expr, p); + } + } + return true; + } else if (param.isConstArray()) { + const deps = []; + for (const request of param.array) { + let dep, localModule; + if (request === "require") { + dep = "__webpack_require__"; + } else if (["exports", "module"].includes(request)) { + dep = request; + } else if ((localModule = getLocalModule(parser.state, request))) { + localModule.flagUsed(); + dep = new LocalModuleDependency(localModule, undefined, false); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + } else { + dep = this.newRequireItemDependency(request); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + } + deps.push(dep); + } + const dep = this.newRequireArrayDependency(deps, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.module.addPresentationalDependency(dep); + return true; + } + } + processItem(parser, expr, param) { + if (param.isConditional()) { + for (const p of param.options) { + const result = this.processItem(parser, expr, p); + if (result === undefined) { + this.processContext(parser, expr, p); + } + } + return true; + } else if (param.isString()) { + let dep, localModule; + if (param.string === "require") { + dep = new ConstDependency("__webpack_require__", param.string, [ + RuntimeGlobals.require + ]); + } else if (param.string === "module") { + dep = new ConstDependency( + parser.state.module.buildInfo.moduleArgument, + param.range, + [RuntimeGlobals.module] + ); + } else if (param.string === "exports") { + dep = new ConstDependency( + parser.state.module.buildInfo.exportsArgument, + param.range, + [RuntimeGlobals.exports] ); + } else if ((localModule = getLocalModule(parser.state, param.string))) { + localModule.flagUsed(); + dep = new LocalModuleDependency(localModule, param.range, false); + } else { + dep = this.newRequireItemDependency(param.string, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + } + } + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + param.range, + param, + expr, + this.options, + { + category: "amd" + }, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } - modulesInOccurrenceOrder.sort((a, b) => { - if (prioritiseInitial) { - const aEntryOccurs = occursInInitialChunksMap.get(a); - const bEntryOccurs = occursInInitialChunksMap.get(b); - if (aEntryOccurs > bEntryOccurs) return -1; - if (aEntryOccurs < bEntryOccurs) return 1; - } - const aOccurs = occursInAllChunksMap.get(a); - const bOccurs = occursInAllChunksMap.get(b); - if (aOccurs > bOccurs) return -1; - if (aOccurs < bOccurs) return 1; - return naturalCompare(a, b); - }); + processArrayForRequestString(param) { + if (param.isArray()) { + const result = param.items.map(item => + this.processItemForRequestString(item) + ); + if (result.every(Boolean)) return result.join(" "); + } else if (param.isConstArray()) { + return param.array.join(" "); + } + } - assignAscendingModuleIds( - usedIds, - modulesInOccurrenceOrder, - compilation - ); + processItemForRequestString(param) { + if (param.isConditional()) { + const result = param.options.map(item => + this.processItemForRequestString(item) + ); + if (result.every(Boolean)) return result.join("|"); + } else if (param.isString()) { + return param.string; + } + } + + processCallRequire(parser, expr) { + let param; + let depBlock; + let dep; + let result; + + const old = parser.state.current; + + if (expr.arguments.length >= 1) { + param = parser.evaluateExpression(expr.arguments[0]); + depBlock = this.newRequireDependenciesBlock( + expr.loc, + this.processArrayForRequestString(param) + ); + dep = this.newRequireDependency( + expr.range, + param.range, + expr.arguments.length > 1 ? expr.arguments[1].range : null, + expr.arguments.length > 2 ? expr.arguments[2].range : null + ); + dep.loc = expr.loc; + depBlock.addDependency(dep); + + parser.state.current = depBlock; + } + + if (expr.arguments.length === 1) { + parser.inScope([], () => { + result = this.processArray(parser, expr, param); }); - }); + parser.state.current = old; + if (!result) return; + parser.state.current.addBlock(depBlock); + return true; + } + + if (expr.arguments.length === 2 || expr.arguments.length === 3) { + try { + parser.inScope([], () => { + result = this.processArray(parser, expr, param); + }); + if (!result) { + const dep = new UnsupportedDependency("unsupported", expr.range); + old.addPresentationalDependency(dep); + if (parser.state.module) { + parser.state.module.addError( + new UnsupportedFeatureWarning( + "Cannot statically analyse 'require(…, …)' in line " + + expr.loc.start.line, + expr.loc + ) + ); + } + depBlock = null; + return true; + } + dep.functionBindThis = this.processFunctionArgument( + parser, + expr.arguments[1] + ); + if (expr.arguments.length === 3) { + dep.errorCallbackBindThis = this.processFunctionArgument( + parser, + expr.arguments[2] + ); + } + } finally { + parser.state.current = old; + if (depBlock) parser.state.current.addBlock(depBlock); + } + return true; + } } -} -module.exports = OccurrenceModuleIdsPlugin; + newRequireDependenciesBlock(loc, request) { + return new AMDRequireDependenciesBlock(loc, request); + } + newRequireDependency( + outerRange, + arrayRange, + functionRange, + errorCallbackRange + ) { + return new AMDRequireDependency( + outerRange, + arrayRange, + functionRange, + errorCallbackRange + ); + } + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); + } + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); + } +} +module.exports = AMDRequireDependenciesBlockParserPlugin; /***/ }), -/***/ 8635: +/***/ 43911: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -87740,144 +84800,178 @@ module.exports = OccurrenceModuleIdsPlugin; -const { WebpackError } = __webpack_require__(91919); -const { getUsedModuleIdsAndModules } = __webpack_require__(63290); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -const plugin = "SyncModuleIdsPlugin"; +class AMDRequireDependency extends NullDependency { + constructor(outerRange, arrayRange, functionRange, errorCallbackRange) { + super(); -class SyncModuleIdsPlugin { - /** - * @param {Object} options options - * @param {string} options.path path to file - * @param {string=} options.context context for module names - * @param {function(Module): boolean} options.test selector for modules - * @param {"read" | "create" | "merge" | "update"=} options.mode operation mode (defaults to merge) - */ - constructor({ path, context, test, mode }) { - this._path = path; - this._context = context; - this._test = test || (() => true); - const readAndWrite = !mode || mode === "merge" || mode === "update"; - this._read = readAndWrite || mode === "read"; - this._write = readAndWrite || mode === "create"; - this._prune = mode === "update"; + this.outerRange = outerRange; + this.arrayRange = arrayRange; + this.functionRange = functionRange; + this.errorCallbackRange = errorCallbackRange; + this.functionBindThis = false; + this.errorCallbackBindThis = false; + } + + get category() { + return "amd"; + } + + serialize(context) { + const { write } = context; + + write(this.outerRange); + write(this.arrayRange); + write(this.functionRange); + write(this.errorCallbackRange); + write(this.functionBindThis); + write(this.errorCallbackBindThis); + + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + + this.outerRange = read(); + this.arrayRange = read(); + this.functionRange = read(); + this.errorCallbackRange = read(); + this.functionBindThis = read(); + this.errorCallbackBindThis = read(); + + super.deserialize(context); } +} + +makeSerializable( + AMDRequireDependency, + "webpack/lib/dependencies/AMDRequireDependency" +); +AMDRequireDependency.Template = class AMDRequireDependencyTemplate extends ( + NullDependency.Template +) { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - /** @type {Map} */ - let data; - let dataChanged = false; - if (this._read) { - compiler.hooks.readRecords.tapAsync(plugin, callback => { - const fs = compiler.intermediateFileSystem; - fs.readFile(this._path, (err, buffer) => { - if (err) { - if (err.code !== "ENOENT") { - return callback(err); - } - return callback(); - } - const json = JSON.parse(buffer.toString()); - data = new Map(); - for (const key of Object.keys(json)) { - data.set(key, json[key]); - } - dataChanged = false; - return callback(); - }); - }); + apply( + dependency, + source, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {AMDRequireDependency} */ (dependency); + const depBlock = /** @type {AsyncDependenciesBlock} */ ( + moduleGraph.getParentBlock(dep) + ); + const promise = runtimeTemplate.blockPromise({ + chunkGraph, + block: depBlock, + message: "AMD require", + runtimeRequirements + }); + + // has array range but no function range + if (dep.arrayRange && !dep.functionRange) { + const startBlock = `${promise}.then(function() {`; + const endBlock = `;})['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; + runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); + + source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); + + source.replace(dep.arrayRange[1], dep.outerRange[1] - 1, endBlock); + + return; } - if (this._write) { - compiler.hooks.emitRecords.tapAsync(plugin, callback => { - if (!data || !dataChanged) return callback(); - const json = {}; - const sorted = Array.from(data).sort(([a], [b]) => (a < b ? -1 : 1)); - for (const [key, value] of sorted) { - json[key] = value; - } - const fs = compiler.intermediateFileSystem; - fs.writeFile(this._path, JSON.stringify(json), callback); - }); + + // has function range but no array range + if (dep.functionRange && !dep.arrayRange) { + const startBlock = `${promise}.then((`; + const endBlock = `).bind(exports, __webpack_require__, exports, module))['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; + runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); + + source.replace(dep.outerRange[0], dep.functionRange[0] - 1, startBlock); + + source.replace(dep.functionRange[1], dep.outerRange[1] - 1, endBlock); + + return; + } + + // has array range, function range, and errorCallbackRange + if (dep.arrayRange && dep.functionRange && dep.errorCallbackRange) { + const startBlock = `${promise}.then(function() { `; + const errorRangeBlock = `}${ + dep.functionBindThis ? ".bind(this)" : "" + })['catch'](`; + const endBlock = `${dep.errorCallbackBindThis ? ".bind(this)" : ""})`; + + source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); + + source.insert(dep.arrayRange[0], "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); + + source.replace(dep.arrayRange[1], dep.functionRange[0] - 1, "; ("); + + source.insert( + dep.functionRange[1], + ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" + ); + + source.replace( + dep.functionRange[1], + dep.errorCallbackRange[0] - 1, + errorRangeBlock + ); + + source.replace( + dep.errorCallbackRange[1], + dep.outerRange[1] - 1, + endBlock + ); + + return; + } + + // has array range, function range, but no errorCallbackRange + if (dep.arrayRange && dep.functionRange) { + const startBlock = `${promise}.then(function() { `; + const endBlock = `}${ + dep.functionBindThis ? ".bind(this)" : "" + })['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; + runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); + + source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); + + source.insert(dep.arrayRange[0], "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); + + source.replace(dep.arrayRange[1], dep.functionRange[0] - 1, "; ("); + + source.insert( + dep.functionRange[1], + ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" + ); + + source.replace(dep.functionRange[1], dep.outerRange[1] - 1, endBlock); } - compiler.hooks.thisCompilation.tap(plugin, compilation => { - const associatedObjectForCache = compiler.root; - const context = this._context || compiler.context; - if (this._read) { - compilation.hooks.reviveModules.tap(plugin, (_1, _2) => { - if (!data) return; - const { chunkGraph } = compilation; - const [usedIds, modules] = getUsedModuleIdsAndModules( - compilation, - this._test - ); - for (const module of modules) { - const name = module.libIdent({ - context, - associatedObjectForCache - }); - if (!name) continue; - const id = data.get(name); - const idAsString = `${id}`; - if (usedIds.has(idAsString)) { - const err = new WebpackError( - `SyncModuleIdsPlugin: Unable to restore id '${id}' from '${this._path}' as it's already used.` - ); - err.module = module; - compilation.errors.push(err); - } - chunkGraph.setModuleId(module, id); - usedIds.add(idAsString); - } - }); - } - if (this._write) { - compilation.hooks.recordModules.tap(plugin, modules => { - const { chunkGraph } = compilation; - let oldData = data; - if (!oldData) { - oldData = data = new Map(); - } else if (this._prune) { - data = new Map(); - } - for (const module of modules) { - if (this._test(module)) { - const name = module.libIdent({ - context, - associatedObjectForCache - }); - if (!name) continue; - const id = chunkGraph.getModuleId(module); - if (id === null) continue; - const oldId = oldData.get(name); - if (oldId !== id) { - dataChanged = true; - } else if (data === oldData) { - continue; - } - data.set(name, id); - } - } - if (data.size !== oldData.size) dataChanged = true; - }); - } - }); } -} +}; -module.exports = SyncModuleIdsPlugin; +module.exports = AMDRequireDependency; /***/ }), -/***/ 91919: +/***/ 71806: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -87888,741 +84982,210 @@ module.exports = SyncModuleIdsPlugin; -const util = __webpack_require__(73837); -const memoize = __webpack_require__(78676); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyTemplateAsRequireId = __webpack_require__(36873); -/** @typedef {import("../declarations/WebpackOptions").Entry} Entry */ -/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} EntryNormalized */ -/** @typedef {import("../declarations/WebpackOptions").EntryObject} EntryObject */ -/** @typedef {import("../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../declarations/WebpackOptions").ModuleOptions} ModuleOptions */ -/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ -/** @typedef {import("../declarations/WebpackOptions").RuleSetCondition} RuleSetCondition */ -/** @typedef {import("../declarations/WebpackOptions").RuleSetConditionAbsolute} RuleSetConditionAbsolute */ -/** @typedef {import("../declarations/WebpackOptions").RuleSetRule} RuleSetRule */ -/** @typedef {import("../declarations/WebpackOptions").RuleSetUse} RuleSetUse */ -/** @typedef {import("../declarations/WebpackOptions").RuleSetUseItem} RuleSetUseItem */ -/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} Configuration */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */ -/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ -/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ -/** @typedef {import("./Compilation").Asset} Asset */ -/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("./MultiStats")} MultiStats */ -/** @typedef {import("./Parser").ParserState} ParserState */ -/** @typedef {import("./ResolverFactory").ResolvePluginInstance} ResolvePluginInstance */ -/** @typedef {import("./ResolverFactory").Resolver} Resolver */ -/** @typedef {import("./Watching")} Watching */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunk} StatsChunk */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunkGroup} StatsChunkGroup */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunkOrigin} StatsChunkOrigin */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsLogging} StatsLogging */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsLoggingEntry} StatsLoggingEntry */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleIssuer} StatsModuleIssuer */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleReason} StatsModuleReason */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleTraceDependency} StatsModuleTraceDependency */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleTraceItem} StatsModuleTraceItem */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsProfile} StatsProfile */ +class AMDRequireItemDependency extends ModuleDependency { + constructor(request, range) { + super(request); -/** - * @template {Function} T - * @param {function(): T} factory factory function - * @returns {T} function - */ -const lazyFunction = factory => { - const fac = memoize(factory); - const f = /** @type {any} */ ( - (...args) => { - return fac()(...args); - } - ); - return /** @type {T} */ (f); -}; + this.range = range; + } -/** - * @template A - * @template B - * @param {A} obj input a - * @param {B} exports input b - * @returns {A & B} merged - */ -const mergeExports = (obj, exports) => { - const descriptors = Object.getOwnPropertyDescriptors(exports); - for (const name of Object.keys(descriptors)) { - const descriptor = descriptors[name]; - if (descriptor.get) { - const fn = descriptor.get; - Object.defineProperty(obj, name, { - configurable: false, - enumerable: true, - get: memoize(fn) - }); - } else if (typeof descriptor.value === "object") { - Object.defineProperty(obj, name, { - configurable: false, - enumerable: true, - writable: false, - value: mergeExports({}, descriptor.value) - }); - } else { - throw new Error( - "Exposed values must be either a getter or an nested object" - ); - } + get type() { + return "amd require"; } - return /** @type {A & B} */ (Object.freeze(obj)); -}; -const fn = lazyFunction(() => __webpack_require__(36243)); -module.exports = mergeExports(fn, { - get webpack() { - return __webpack_require__(36243); - }, - get validate() { - const webpackOptionsSchemaCheck = __webpack_require__(10382); - const getRealValidate = memoize(() => { - const validateSchema = __webpack_require__(12047); - const webpackOptionsSchema = __webpack_require__(73342); - return options => validateSchema(webpackOptionsSchema, options); - }); - return options => { - if (!webpackOptionsSchemaCheck(options)) getRealValidate()(options); - }; - }, - get validateSchema() { - const validateSchema = __webpack_require__(12047); - return validateSchema; - }, - get version() { - return /** @type {string} */ ((__webpack_require__(32702)/* .version */ .i8)); - }, + get category() { + return "amd"; + } +} - get cli() { - return __webpack_require__(13462); - }, - get AutomaticPrefetchPlugin() { - return __webpack_require__(17714); - }, - get AsyncDependenciesBlock() { - return __webpack_require__(47736); - }, - get BannerPlugin() { - return __webpack_require__(21242); - }, - get Cache() { - return __webpack_require__(7592); - }, - get Chunk() { - return __webpack_require__(39385); - }, - get ChunkGraph() { - return __webpack_require__(64971); - }, - get CleanPlugin() { - return __webpack_require__(31085); - }, - get Compilation() { - return __webpack_require__(85720); - }, - get Compiler() { - return __webpack_require__(70845); - }, - get ConcatenationScope() { - return __webpack_require__(98229); - }, - get ContextExclusionPlugin() { - return __webpack_require__(21411); - }, - get ContextReplacementPlugin() { - return __webpack_require__(12206); - }, - get DefinePlugin() { - return __webpack_require__(79065); - }, - get DelegatedPlugin() { - return __webpack_require__(80632); - }, - get Dependency() { - return __webpack_require__(54912); - }, - get DllPlugin() { - return __webpack_require__(40038); - }, - get DllReferencePlugin() { - return __webpack_require__(90999); - }, - get DynamicEntryPlugin() { - return __webpack_require__(96475); - }, - get EntryOptionPlugin() { - return __webpack_require__(9909); - }, - get EntryPlugin() { - return __webpack_require__(96953); - }, - get EnvironmentPlugin() { - return __webpack_require__(22070); - }, - get EvalDevToolModulePlugin() { - return __webpack_require__(65218); - }, - get EvalSourceMapDevToolPlugin() { - return __webpack_require__(14790); - }, - get ExternalModule() { - return __webpack_require__(73071); - }, - get ExternalsPlugin() { - return __webpack_require__(6652); - }, - get Generator() { - return __webpack_require__(93401); - }, - get HotUpdateChunk() { - return __webpack_require__(9597); - }, - get HotModuleReplacementPlugin() { - return __webpack_require__(6404); - }, - get IgnorePlugin() { - return __webpack_require__(84808); - }, - get JavascriptModulesPlugin() { - return util.deprecate( - () => __webpack_require__(89464), - "webpack.JavascriptModulesPlugin has moved to webpack.javascript.JavascriptModulesPlugin", - "DEP_WEBPACK_JAVASCRIPT_MODULES_PLUGIN" - )(); - }, - get LibManifestPlugin() { - return __webpack_require__(93837); - }, - get LibraryTemplatePlugin() { - return util.deprecate( - () => __webpack_require__(14157), - "webpack.LibraryTemplatePlugin is deprecated and has been replaced by compilation.outputOptions.library or compilation.addEntry + passing a library option", - "DEP_WEBPACK_LIBRARY_TEMPLATE_PLUGIN" - )(); - }, - get LoaderOptionsPlugin() { - return __webpack_require__(22078); - }, - get LoaderTargetPlugin() { - return __webpack_require__(86738); - }, - get Module() { - return __webpack_require__(73208); - }, - get ModuleFilenameHelpers() { - return __webpack_require__(88821); - }, - get ModuleGraph() { - return __webpack_require__(99988); - }, - get ModuleGraphConnection() { - return __webpack_require__(40639); - }, - get NoEmitOnErrorsPlugin() { - return __webpack_require__(50169); - }, - get NormalModule() { - return __webpack_require__(39); - }, - get NormalModuleReplacementPlugin() { - return __webpack_require__(30633); - }, - get MultiCompiler() { - return __webpack_require__(33370); - }, - get Parser() { - return __webpack_require__(11715); - }, - get PrefetchPlugin() { - return __webpack_require__(73850); - }, - get ProgressPlugin() { - return __webpack_require__(13216); - }, - get ProvidePlugin() { - return __webpack_require__(38309); - }, - get RuntimeGlobals() { - return __webpack_require__(16475); - }, - get RuntimeModule() { - return __webpack_require__(16963); - }, - get SingleEntryPlugin() { - return util.deprecate( - () => __webpack_require__(96953), - "SingleEntryPlugin was renamed to EntryPlugin", - "DEP_WEBPACK_SINGLE_ENTRY_PLUGIN" - )(); - }, - get SourceMapDevToolPlugin() { - return __webpack_require__(63872); - }, - get Stats() { - return __webpack_require__(31743); - }, - get Template() { - return __webpack_require__(1626); - }, - get UsageState() { - return (__webpack_require__(63686).UsageState); - }, - get WatchIgnorePlugin() { - return __webpack_require__(65193); - }, - get WebpackError() { - return __webpack_require__(53799); - }, - get WebpackOptionsApply() { - return __webpack_require__(88422); - }, - get WebpackOptionsDefaulter() { - return util.deprecate( - () => __webpack_require__(14452), - "webpack.WebpackOptionsDefaulter is deprecated and has been replaced by webpack.config.getNormalizedWebpackOptions and webpack.config.applyWebpackOptionsDefaults", - "DEP_WEBPACK_OPTIONS_DEFAULTER" - )(); - }, - // TODO webpack 6 deprecate - get WebpackOptionsValidationError() { - return (__webpack_require__(38476).ValidationError); - }, - get ValidationError() { - return (__webpack_require__(38476).ValidationError); - }, +makeSerializable( + AMDRequireItemDependency, + "webpack/lib/dependencies/AMDRequireItemDependency" +); - cache: { - get MemoryCachePlugin() { - return __webpack_require__(52539); - } - }, +AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; - config: { - get getNormalizedWebpackOptions() { - return (__webpack_require__(26693).getNormalizedWebpackOptions); - }, - get applyWebpackOptionsDefaults() { - return (__webpack_require__(92988).applyWebpackOptionsDefaults); - } - }, +module.exports = AMDRequireItemDependency; - dependencies: { - get ModuleDependency() { - return __webpack_require__(80321); - }, - get ConstDependency() { - return __webpack_require__(76911); - }, - get NullDependency() { - return __webpack_require__(31830); - } - }, - ids: { - get ChunkModuleIdRangePlugin() { - return __webpack_require__(64618); - }, - get NaturalModuleIdsPlugin() { - return __webpack_require__(83366); - }, - get OccurrenceModuleIdsPlugin() { - return __webpack_require__(35371); - }, - get NamedModuleIdsPlugin() { - return __webpack_require__(24339); - }, - get DeterministicChunkIdsPlugin() { - return __webpack_require__(8747); - }, - get DeterministicModuleIdsPlugin() { - return __webpack_require__(76692); - }, - get NamedChunkIdsPlugin() { - return __webpack_require__(6454); - }, - get OccurrenceChunkIdsPlugin() { - return __webpack_require__(51020); - }, - get HashedModuleIdsPlugin() { - return __webpack_require__(21825); - } - }, +/***/ }), - javascript: { - get EnableChunkLoadingPlugin() { - return __webpack_require__(61291); - }, - get JavascriptModulesPlugin() { - return __webpack_require__(89464); - }, - get JavascriptParser() { - return __webpack_require__(29050); - } - }, +/***/ 45242: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - optimize: { - get AggressiveMergingPlugin() { - return __webpack_require__(64395); - }, - get AggressiveSplittingPlugin() { - return util.deprecate( - () => __webpack_require__(15543), - "AggressiveSplittingPlugin is deprecated in favor of SplitChunksPlugin", - "DEP_WEBPACK_AGGRESSIVE_SPLITTING_PLUGIN" - )(); - }, - get InnerGraph() { - return __webpack_require__(38988); - }, - get LimitChunkCountPlugin() { - return __webpack_require__(83608); - }, - get MinChunkSizePlugin() { - return __webpack_require__(53912); - }, - get ModuleConcatenationPlugin() { - return __webpack_require__(74844); - }, - get RealContentHashPlugin() { - return __webpack_require__(46043); - }, - get RuntimeChunkPlugin() { - return __webpack_require__(2837); - }, - get SideEffectsFlagPlugin() { - return __webpack_require__(84800); - }, - get SplitChunksPlugin() { - return __webpack_require__(21478); - } - }, +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - runtime: { - get GetChunkFilenameRuntimeModule() { - return __webpack_require__(34277); - }, - get LoadScriptRuntimeModule() { - return __webpack_require__(19942); - } - }, - prefetch: { - get ChunkPrefetchPreloadPlugin() { - return __webpack_require__(33895); - } - }, - web: { - get FetchCompileAsyncWasmPlugin() { - return __webpack_require__(8437); - }, - get FetchCompileWasmPlugin() { - return __webpack_require__(35537); - }, - get JsonpChunkLoadingRuntimeModule() { - return __webpack_require__(84154); - }, - get JsonpTemplatePlugin() { - return __webpack_require__(4607); - } - }, +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); - webworker: { - get WebWorkerTemplatePlugin() { - return __webpack_require__(68693); - } - }, +class AMDDefineRuntimeModule extends RuntimeModule { + constructor() { + super("amd define"); + } - node: { - get NodeEnvironmentPlugin() { - return __webpack_require__(7553); - }, - get NodeSourcePlugin() { - return __webpack_require__(7103); - }, - get NodeTargetPlugin() { - return __webpack_require__(17916); - }, - get NodeTemplatePlugin() { - return __webpack_require__(61052); - }, - get ReadFileCompileWasmPlugin() { - return __webpack_require__(98939); - } - }, + /** + * @returns {string} runtime code + */ + generate() { + return Template.asString([ + `${RuntimeGlobals.amdDefine} = function () {`, + Template.indent("throw new Error('define cannot be used indirect');"), + "};" + ]); + } +} - electron: { - get ElectronTargetPlugin() { - return __webpack_require__(32277); - } - }, +class AMDOptionsRuntimeModule extends RuntimeModule { + /** + * @param {Record} options the AMD options + */ + constructor(options) { + super("amd options"); + this.options = options; + } - wasm: { - get AsyncWebAssemblyModulesPlugin() { - return __webpack_require__(7538); - } - }, + /** + * @returns {string} runtime code + */ + generate() { + return Template.asString([ + `${RuntimeGlobals.amdOptions} = ${JSON.stringify(this.options)};` + ]); + } +} - library: { - get AbstractLibraryPlugin() { - return __webpack_require__(26030); - }, - get EnableLibraryPlugin() { - return __webpack_require__(91452); - } - }, +exports.AMDDefineRuntimeModule = AMDDefineRuntimeModule; +exports.AMDOptionsRuntimeModule = AMDOptionsRuntimeModule; - container: { - get ContainerPlugin() { - return __webpack_require__(9244); - }, - get ContainerReferencePlugin() { - return __webpack_require__(95757); - }, - get ModuleFederationPlugin() { - return __webpack_require__(30569); - }, - get scope() { - return (__webpack_require__(3083).scope); - } - }, - sharing: { - get ConsumeSharedPlugin() { - return __webpack_require__(15046); - }, - get ProvideSharedPlugin() { - return __webpack_require__(31225); - }, - get SharePlugin() { - return __webpack_require__(26335); - }, - get scope() { - return (__webpack_require__(3083).scope); - } - }, +/***/ }), - debug: { - get ProfilingPlugin() { - return __webpack_require__(2757); - } - }, +/***/ 57403: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - util: { - get createHash() { - return __webpack_require__(49835); - }, - get comparators() { - return __webpack_require__(29579); - }, - get runtime() { - return __webpack_require__(17156); - }, - get serialization() { - return __webpack_require__(8282); - }, - get cleverMerge() { - return (__webpack_require__(60839).cachedCleverMerge); - }, - get LazySet() { - return __webpack_require__(38938); - } - }, +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ - get sources() { - return __webpack_require__(51255); - }, - experiments: { - schemes: { - get HttpUriPlugin() { - return __webpack_require__(42110); - } - }, - ids: { - get SyncModuleIdsPlugin() { - return __webpack_require__(8635); - } - } + +const DependencyTemplate = __webpack_require__(5160); +const InitFragment = __webpack_require__(55870); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../util/Hash")} Hash */ + +class CachedConstDependency extends NullDependency { + constructor(expression, range, identifier) { + super(); + + this.expression = expression; + this.range = range; + this.identifier = identifier; + this._hashUpdate = undefined; } -}); + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) + this._hashUpdate = "" + this.identifier + this.range + this.expression; + hash.update(this._hashUpdate); + } -/***/ }), + serialize(context) { + const { write } = context; -/***/ 18535: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + write(this.expression); + write(this.range); + write(this.identifier); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + super.serialize(context); + } + deserialize(context) { + const { read } = context; + this.expression = read(); + this.range = read(); + this.identifier = read(); -const { ConcatSource, PrefixSource, RawSource } = __webpack_require__(51255); -const { RuntimeGlobals } = __webpack_require__(91919); -const HotUpdateChunk = __webpack_require__(9597); -const Template = __webpack_require__(1626); -const { getCompilationHooks } = __webpack_require__(89464); -const { - generateEntryStartup, - updateHashForEntryStartup -} = __webpack_require__(98124); + super.deserialize(context); + } +} -/** @typedef {import("../Compiler")} Compiler */ +makeSerializable( + CachedConstDependency, + "webpack/lib/dependencies/CachedConstDependency" +); -class ArrayPushCallbackChunkFormatPlugin { +CachedConstDependency.Template = class CachedConstDependencyTemplate extends ( + DependencyTemplate +) { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - compiler.hooks.thisCompilation.tap( - "ArrayPushCallbackChunkFormatPlugin", - compilation => { - compilation.hooks.additionalChunkRuntimeRequirements.tap( - "ArrayPushCallbackChunkFormatPlugin", - (chunk, set, { chunkGraph }) => { - if (chunk.hasRuntime()) return; - if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { - set.add(RuntimeGlobals.onChunksLoaded); - set.add(RuntimeGlobals.require); - } - set.add(RuntimeGlobals.chunkCallback); - } - ); - const hooks = getCompilationHooks(compilation); - hooks.renderChunk.tap( - "ArrayPushCallbackChunkFormatPlugin", - (modules, renderContext) => { - const { chunk, chunkGraph, runtimeTemplate } = renderContext; - const hotUpdateChunk = - chunk instanceof HotUpdateChunk ? chunk : null; - const globalObject = runtimeTemplate.globalObject; - const source = new ConcatSource(); - const runtimeModules = - chunkGraph.getChunkRuntimeModulesInOrder(chunk); - if (hotUpdateChunk) { - const hotUpdateGlobal = - runtimeTemplate.outputOptions.hotUpdateGlobal; - source.add( - `${globalObject}[${JSON.stringify(hotUpdateGlobal)}](` - ); - source.add(`${JSON.stringify(chunk.id)},`); - source.add(modules); - if (runtimeModules.length > 0) { - source.add(",\n"); - const runtimePart = Template.renderChunkRuntimeModules( - runtimeModules, - renderContext - ); - source.add(runtimePart); - } - source.add(")"); - } else { - const chunkLoadingGlobal = - runtimeTemplate.outputOptions.chunkLoadingGlobal; - source.add( - `(${globalObject}[${JSON.stringify( - chunkLoadingGlobal - )}] = ${globalObject}[${JSON.stringify( - chunkLoadingGlobal - )}] || []).push([` - ); - source.add(`${JSON.stringify(chunk.ids)},`); - source.add(modules); - const entries = Array.from( - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) - ); - if (runtimeModules.length > 0 || entries.length > 0) { - const runtime = new ConcatSource( - (runtimeTemplate.supportsArrowFunction() - ? "__webpack_require__ =>" - : "function(__webpack_require__)") + - " { // webpackRuntimeModules\n" - ); - if (runtimeModules.length > 0) { - runtime.add( - Template.renderRuntimeModules(runtimeModules, { - ...renderContext, - codeGenerationResults: compilation.codeGenerationResults - }) - ); - } - if (entries.length > 0) { - const startupSource = new RawSource( - generateEntryStartup( - chunkGraph, - runtimeTemplate, - entries, - chunk, - true - ) - ); - runtime.add( - hooks.renderStartup.call( - startupSource, - entries[entries.length - 1][0], - { - ...renderContext, - inlined: false - } - ) - ); - if ( - chunkGraph - .getChunkRuntimeRequirements(chunk) - .has(RuntimeGlobals.returnExportsFromRuntime) - ) { - runtime.add("return __webpack_exports__;\n"); - } - } - runtime.add("}\n"); - source.add(",\n"); - source.add(new PrefixSource("/******/ ", runtime)); - } - source.add("])"); - } - return source; - } - ); - hooks.chunkHash.tap( - "ArrayPushCallbackChunkFormatPlugin", - (chunk, hash, { chunkGraph, runtimeTemplate }) => { - if (chunk.hasRuntime()) return; - hash.update( - `ArrayPushCallbackChunkFormatPlugin1${runtimeTemplate.outputOptions.chunkLoadingGlobal}${runtimeTemplate.outputOptions.hotUpdateGlobal}${runtimeTemplate.globalObject}` - ); - const entries = Array.from( - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) - ); - updateHashForEntryStartup(hash, chunkGraph, entries, chunk); - } - ); - } + apply( + dependency, + source, + { runtimeTemplate, dependencyTemplates, initFragments } + ) { + const dep = /** @type {CachedConstDependency} */ (dependency); + + initFragments.push( + new InitFragment( + `var ${dep.identifier} = ${dep.expression};\n`, + InitFragment.STAGE_CONSTANTS, + 0, + `const ${dep.identifier}` + ) ); + + if (typeof dep.range === "number") { + source.insert(dep.range, dep.identifier); + + return; + } + + source.replace(dep.range[0], dep.range[1] - 1, dep.identifier); } -} +}; -module.exports = ArrayPushCallbackChunkFormatPlugin; +module.exports = CachedConstDependency; /***/ }), -/***/ 950: -/***/ (function(module) { +/***/ 59643: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -88632,485 +85195,436 @@ module.exports = ArrayPushCallbackChunkFormatPlugin; -/** @typedef {import("estree").Node} EsTreeNode */ -/** @typedef {import("./JavascriptParser").VariableInfoInterface} VariableInfoInterface */ - -const TypeUnknown = 0; -const TypeUndefined = 1; -const TypeNull = 2; -const TypeString = 3; -const TypeNumber = 4; -const TypeBoolean = 5; -const TypeRegExp = 6; -const TypeConditional = 7; -const TypeArray = 8; -const TypeConstArray = 9; -const TypeIdentifier = 10; -const TypeWrapped = 11; -const TypeTemplateString = 12; -const TypeBigInt = 13; +const RuntimeGlobals = __webpack_require__(16475); -class BasicEvaluatedExpression { - constructor() { - this.type = TypeUnknown; - /** @type {[number, number]} */ - this.range = undefined; - /** @type {boolean} */ - this.falsy = false; - /** @type {boolean} */ - this.truthy = false; - /** @type {boolean | undefined} */ - this.nullish = undefined; - /** @type {boolean} */ - this.sideEffects = true; - /** @type {boolean | undefined} */ - this.bool = undefined; - /** @type {number | undefined} */ - this.number = undefined; - /** @type {bigint | undefined} */ - this.bigint = undefined; - /** @type {RegExp | undefined} */ - this.regExp = undefined; - /** @type {string | undefined} */ - this.string = undefined; - /** @type {BasicEvaluatedExpression[] | undefined} */ - this.quasis = undefined; - /** @type {BasicEvaluatedExpression[] | undefined} */ - this.parts = undefined; - /** @type {any[] | undefined} */ - this.array = undefined; - /** @type {BasicEvaluatedExpression[] | undefined} */ - this.items = undefined; - /** @type {BasicEvaluatedExpression[] | undefined} */ - this.options = undefined; - /** @type {BasicEvaluatedExpression | undefined} */ - this.prefix = undefined; - /** @type {BasicEvaluatedExpression | undefined} */ - this.postfix = undefined; - this.wrappedInnerExpressions = undefined; - /** @type {string | undefined} */ - this.identifier = undefined; - /** @type {VariableInfoInterface} */ - this.rootInfo = undefined; - /** @type {() => string[]} */ - this.getMembers = undefined; - /** @type {EsTreeNode} */ - this.expression = undefined; +exports.handleDependencyBase = (depBase, module, runtimeRequirements) => { + let base = undefined; + let type; + switch (depBase) { + case "exports": + runtimeRequirements.add(RuntimeGlobals.exports); + base = module.exportsArgument; + type = "expression"; + break; + case "module.exports": + runtimeRequirements.add(RuntimeGlobals.module); + base = `${module.moduleArgument}.exports`; + type = "expression"; + break; + case "this": + runtimeRequirements.add(RuntimeGlobals.thisAsExports); + base = "this"; + type = "expression"; + break; + case "Object.defineProperty(exports)": + runtimeRequirements.add(RuntimeGlobals.exports); + base = module.exportsArgument; + type = "Object.defineProperty"; + break; + case "Object.defineProperty(module.exports)": + runtimeRequirements.add(RuntimeGlobals.module); + base = `${module.moduleArgument}.exports`; + type = "Object.defineProperty"; + break; + case "Object.defineProperty(this)": + runtimeRequirements.add(RuntimeGlobals.thisAsExports); + base = "this"; + type = "Object.defineProperty"; + break; + default: + throw new Error(`Unsupported base ${depBase}`); } - isUnknown() { - return this.type === TypeUnknown; - } + return [type, base]; +}; - isNull() { - return this.type === TypeNull; - } - isUndefined() { - return this.type === TypeUndefined; - } +/***/ }), - isString() { - return this.type === TypeString; - } +/***/ 62892: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - isNumber() { - return this.type === TypeNumber; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - isBigInt() { - return this.type === TypeBigInt; - } - isBoolean() { - return this.type === TypeBoolean; - } - isRegExp() { - return this.type === TypeRegExp; - } +const Dependency = __webpack_require__(54912); +const { UsageState } = __webpack_require__(63686); +const Template = __webpack_require__(39722); +const { equals } = __webpack_require__(84953); +const makeSerializable = __webpack_require__(33032); +const propertyAccess = __webpack_require__(54190); +const { handleDependencyBase } = __webpack_require__(59643); +const ModuleDependency = __webpack_require__(80321); +const processExportInfo = __webpack_require__(55207); - isConditional() { - return this.type === TypeConditional; - } +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - isArray() { - return this.type === TypeArray; - } +const idsSymbol = Symbol("CommonJsExportRequireDependency.ids"); - isConstArray() { - return this.type === TypeConstArray; - } +const EMPTY_OBJECT = {}; - isIdentifier() { - return this.type === TypeIdentifier; +class CommonJsExportRequireDependency extends ModuleDependency { + constructor(range, valueRange, base, names, request, ids, resultUsed) { + super(request); + this.range = range; + this.valueRange = valueRange; + this.base = base; + this.names = names; + this.ids = ids; + this.resultUsed = resultUsed; + this.asiSafe = undefined; } - isWrapped() { - return this.type === TypeWrapped; + get type() { + return "cjs export require"; } - isTemplateString() { - return this.type === TypeTemplateString; + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return Dependency.TRANSITIVE; } /** - * Is expression a primitive or an object type value? - * @returns {boolean | undefined} true: primitive type, false: object type, undefined: unknown/runtime-defined + * @param {ModuleGraph} moduleGraph the module graph + * @returns {string[]} the imported id */ - isPrimitiveType() { - switch (this.type) { - case TypeUndefined: - case TypeNull: - case TypeString: - case TypeNumber: - case TypeBoolean: - case TypeBigInt: - case TypeWrapped: - case TypeTemplateString: - return true; - case TypeRegExp: - case TypeArray: - case TypeConstArray: - return false; - default: - return undefined; - } + getIds(moduleGraph) { + return moduleGraph.getMeta(this)[idsSymbol] || this.ids; } /** - * Is expression a runtime or compile-time value? - * @returns {boolean} true: compile time value, false: runtime value + * @param {ModuleGraph} moduleGraph the module graph + * @param {string[]} ids the imported ids + * @returns {void} */ - isCompileTimeValue() { - switch (this.type) { - case TypeUndefined: - case TypeNull: - case TypeString: - case TypeNumber: - case TypeBoolean: - case TypeRegExp: - case TypeConstArray: - case TypeBigInt: - return true; - default: - return false; - } + setIds(moduleGraph, ids) { + moduleGraph.getMeta(this)[idsSymbol] = ids; } /** - * Gets the compile-time value of the expression - * @returns {any} the javascript value + * 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 */ - asCompileTimeValue() { - switch (this.type) { - case TypeUndefined: - return undefined; - case TypeNull: - return null; - case TypeString: - return this.string; - case TypeNumber: - return this.number; - case TypeBoolean: - return this.bool; - case TypeRegExp: - return this.regExp; - case TypeConstArray: - return this.array; - case TypeBigInt: - return this.bigint; - default: - throw new Error( - "asCompileTimeValue must only be called for compile-time values" - ); + getReferencedExports(moduleGraph, runtime) { + const ids = this.getIds(moduleGraph); + const getFullResult = () => { + if (ids.length === 0) { + return Dependency.EXPORTS_OBJECT_REFERENCED; + } else { + return [ + { + name: ids, + canMangle: false + } + ]; + } + }; + if (this.resultUsed) return getFullResult(); + let exportsInfo = moduleGraph.getExportsInfo( + moduleGraph.getParentModule(this) + ); + for (const name of this.names) { + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + const used = exportInfo.getUsed(runtime); + if (used === UsageState.Unused) return Dependency.NO_EXPORTS_REFERENCED; + if (used !== UsageState.OnlyPropertiesUsed) return getFullResult(); + exportsInfo = exportInfo.exportsInfo; + if (!exportsInfo) return getFullResult(); } - } - - isTruthy() { - return this.truthy; - } - - isFalsy() { - return this.falsy; - } - - isNullish() { - return this.nullish; + if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { + return getFullResult(); + } + /** @type {string[][]} */ + const referencedExports = []; + for (const exportInfo of exportsInfo.orderedExports) { + processExportInfo( + runtime, + referencedExports, + ids.concat(exportInfo.name), + exportInfo, + false + ); + } + return referencedExports.map(name => ({ + name, + canMangle: false + })); } /** - * Can this expression have side effects? - * @returns {boolean} false: never has side effects + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names */ - couldHaveSideEffects() { - return this.sideEffects; - } - - asBool() { - if (this.truthy) return true; - if (this.falsy || this.nullish) return false; - if (this.isBoolean()) return this.bool; - if (this.isNull()) return false; - if (this.isUndefined()) return false; - if (this.isString()) return this.string !== ""; - if (this.isNumber()) return this.number !== 0; - if (this.isBigInt()) return this.bigint !== BigInt(0); - if (this.isRegExp()) return true; - if (this.isArray()) return true; - if (this.isConstArray()) return true; - if (this.isWrapped()) { - return (this.prefix && this.prefix.asBool()) || - (this.postfix && this.postfix.asBool()) - ? true - : undefined; - } - if (this.isTemplateString()) { - const str = this.asString(); - if (typeof str === "string") return str !== ""; + getExports(moduleGraph) { + const ids = this.getIds(moduleGraph); + if (this.names.length === 1) { + const name = this.names[0]; + const from = moduleGraph.getConnection(this); + if (!from) return; + return { + exports: [ + { + name, + from, + export: ids.length === 0 ? null : ids, + // we can't mangle names that are in an empty object + // because one could access the prototype property + // when export isn't set yet + canMangle: !(name in EMPTY_OBJECT) && false + } + ], + dependencies: [from.module] + }; + } else if (this.names.length > 0) { + const name = this.names[0]; + return { + exports: [ + { + name, + // we can't mangle names that are in an empty object + // because one could access the prototype property + // when export isn't set yet + canMangle: !(name in EMPTY_OBJECT) && false + } + ], + dependencies: undefined + }; + } else { + const from = moduleGraph.getConnection(this); + if (!from) return; + const reexportInfo = this.getStarReexports( + moduleGraph, + undefined, + from.module + ); + if (reexportInfo) { + return { + exports: Array.from(reexportInfo.exports, name => { + return { + name, + from, + export: ids.concat(name), + canMangle: !(name in EMPTY_OBJECT) && false + }; + }), + // TODO handle deep reexports + dependencies: [from.module] + }; + } else { + return { + exports: true, + from: ids.length === 0 ? from : undefined, + canMangle: false, + dependencies: [from.module] + }; + } } - return undefined; } - asNullish() { - const nullish = this.isNullish(); + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @param {Module} importedModule the imported module (optional) + * @returns {{exports?: Set, checked?: Set}} information + */ + getStarReexports( + moduleGraph, + runtime, + importedModule = moduleGraph.getModule(this) + ) { + let importedExportsInfo = moduleGraph.getExportsInfo(importedModule); + const ids = this.getIds(moduleGraph); + if (ids.length > 0) + importedExportsInfo = importedExportsInfo.getNestedExportsInfo(ids); + let exportsInfo = moduleGraph.getExportsInfo( + moduleGraph.getParentModule(this) + ); + if (this.names.length > 0) + exportsInfo = exportsInfo.getNestedExportsInfo(this.names); - if (nullish === true || this.isNull() || this.isUndefined()) return true; + const noExtraExports = + importedExportsInfo && + importedExportsInfo.otherExportsInfo.provided === false; + const noExtraImports = + exportsInfo && + exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused; - if (nullish === false) return false; - if (this.isTruthy()) return false; - if (this.isBoolean()) return false; - if (this.isString()) return false; - if (this.isNumber()) return false; - if (this.isBigInt()) return false; - if (this.isRegExp()) return false; - if (this.isArray()) return false; - if (this.isConstArray()) return false; - if (this.isTemplateString()) return false; - if (this.isRegExp()) return false; + if (!noExtraExports && !noExtraImports) { + return; + } - return undefined; - } + const isNamespaceImport = + importedModule.getExportsType(moduleGraph, false) === "namespace"; - asString() { - if (this.isBoolean()) return `${this.bool}`; - if (this.isNull()) return "null"; - if (this.isUndefined()) return "undefined"; - if (this.isString()) return this.string; - if (this.isNumber()) return `${this.number}`; - if (this.isBigInt()) return `${this.bigint}`; - if (this.isRegExp()) return `${this.regExp}`; - if (this.isArray()) { - let array = []; - for (const item of this.items) { - const itemStr = item.asString(); - if (itemStr === undefined) return undefined; - array.push(itemStr); + /** @type {Set} */ + const exports = new Set(); + /** @type {Set} */ + const checked = new Set(); + + if (noExtraImports) { + for (const exportInfo of exportsInfo.orderedExports) { + const name = exportInfo.name; + if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; + if (name === "__esModule" && isNamespaceImport) { + exports.add(name); + } else if (importedExportsInfo) { + const importedExportInfo = + importedExportsInfo.getReadOnlyExportInfo(name); + if (importedExportInfo.provided === false) continue; + exports.add(name); + if (importedExportInfo.provided === true) continue; + checked.add(name); + } else { + exports.add(name); + checked.add(name); + } } - return `${array}`; - } - if (this.isConstArray()) return `${this.array}`; - if (this.isTemplateString()) { - let str = ""; - for (const part of this.parts) { - const partStr = part.asString(); - if (partStr === undefined) return undefined; - str += partStr; + } else if (noExtraExports) { + for (const importedExportInfo of importedExportsInfo.orderedExports) { + const name = importedExportInfo.name; + if (importedExportInfo.provided === false) continue; + if (exportsInfo) { + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; + } + exports.add(name); + if (importedExportInfo.provided === true) continue; + checked.add(name); + } + if (isNamespaceImport) { + exports.add("__esModule"); + checked.delete("__esModule"); } - return str; } - return undefined; - } - setString(string) { - this.type = TypeString; - this.string = string; - this.sideEffects = false; - return this; + return { exports, checked }; } - setUndefined() { - this.type = TypeUndefined; - this.sideEffects = false; - return this; + serialize(context) { + const { write } = context; + write(this.asiSafe); + write(this.range); + write(this.valueRange); + write(this.base); + write(this.names); + write(this.ids); + write(this.resultUsed); + super.serialize(context); } - setNull() { - this.type = TypeNull; - this.sideEffects = false; - return this; + deserialize(context) { + const { read } = context; + this.asiSafe = read(); + this.range = read(); + this.valueRange = read(); + this.base = read(); + this.names = read(); + this.ids = read(); + this.resultUsed = read(); + super.deserialize(context); } +} - setNumber(number) { - this.type = TypeNumber; - this.number = number; - this.sideEffects = false; - return this; - } - - setBigInt(bigint) { - this.type = TypeBigInt; - this.bigint = bigint; - this.sideEffects = false; - return this; - } - - setBoolean(bool) { - this.type = TypeBoolean; - this.bool = bool; - this.sideEffects = false; - return this; - } - - setRegExp(regExp) { - this.type = TypeRegExp; - this.regExp = regExp; - this.sideEffects = false; - return this; - } - - setIdentifier(identifier, rootInfo, getMembers) { - this.type = TypeIdentifier; - this.identifier = identifier; - this.rootInfo = rootInfo; - this.getMembers = getMembers; - this.sideEffects = true; - return this; - } - - setWrapped(prefix, postfix, innerExpressions) { - this.type = TypeWrapped; - this.prefix = prefix; - this.postfix = postfix; - this.wrappedInnerExpressions = innerExpressions; - this.sideEffects = true; - return this; - } - - setOptions(options) { - this.type = TypeConditional; - this.options = options; - this.sideEffects = true; - return this; - } +makeSerializable( + CommonJsExportRequireDependency, + "webpack/lib/dependencies/CommonJsExportRequireDependency" +); - addOptions(options) { - if (!this.options) { - this.type = TypeConditional; - this.options = []; - this.sideEffects = true; - } - for (const item of options) { - this.options.push(item); +CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @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, + { + module, + runtimeTemplate, + chunkGraph, + moduleGraph, + runtimeRequirements, + runtime } - return this; - } - - setItems(items) { - this.type = TypeArray; - this.items = items; - this.sideEffects = items.some(i => i.couldHaveSideEffects()); - return this; - } - - setArray(array) { - this.type = TypeConstArray; - this.array = array; - this.sideEffects = false; - return this; - } - - setTemplateString(quasis, parts, kind) { - this.type = TypeTemplateString; - this.quasis = quasis; - this.parts = parts; - this.templateStringKind = kind; - this.sideEffects = parts.some(p => p.sideEffects); - return this; - } - - setTruthy() { - this.falsy = false; - this.truthy = true; - this.nullish = false; - return this; - } - - setFalsy() { - this.falsy = true; - this.truthy = false; - return this; - } - - setNullish(value) { - this.nullish = value; - - if (value) return this.setFalsy(); - - return this; - } - - setRange(range) { - this.range = range; - return this; - } - - setSideEffects(sideEffects = true) { - this.sideEffects = sideEffects; - return this; - } - - setExpression(expression) { - this.expression = expression; - return this; - } -} - -/** - * @param {string} flags regexp flags - * @returns {boolean} is valid flags - */ -BasicEvaluatedExpression.isValidRegExpFlags = flags => { - const len = flags.length; + ) { + const dep = /** @type {CommonJsExportRequireDependency} */ (dependency); + const used = moduleGraph + .getExportsInfo(module) + .getUsedName(dep.names, runtime); - if (len === 0) return true; - if (len > 4) return false; + const [type, base] = handleDependencyBase( + dep.base, + module, + runtimeRequirements + ); - // cspell:word gimy - let remaining = 0b0000; // bit per RegExp flag: gimy + const importedModule = moduleGraph.getModule(dep); + let requireExpr = runtimeTemplate.moduleExports({ + module: importedModule, + chunkGraph, + request: dep.request, + weak: dep.weak, + runtimeRequirements + }); + if (importedModule) { + const ids = dep.getIds(moduleGraph); + const usedImported = moduleGraph + .getExportsInfo(importedModule) + .getUsedName(ids, runtime); + if (usedImported) { + const comment = equals(usedImported, ids) + ? "" + : Template.toNormalComment(propertyAccess(ids)) + " "; + requireExpr += `${comment}${propertyAccess(usedImported)}`; + } + } - for (let i = 0; i < len; i++) - switch (flags.charCodeAt(i)) { - case 103 /* g */: - if (remaining & 0b1000) return false; - remaining |= 0b1000; - break; - case 105 /* i */: - if (remaining & 0b0100) return false; - remaining |= 0b0100; - break; - case 109 /* m */: - if (remaining & 0b0010) return false; - remaining |= 0b0010; - break; - case 121 /* y */: - if (remaining & 0b0001) return false; - remaining |= 0b0001; - break; + switch (type) { + case "expression": + source.replace( + dep.range[0], + dep.range[1] - 1, + used + ? `${base}${propertyAccess(used)} = ${requireExpr}` + : `/* unused reexport */ ${requireExpr}` + ); + return; + case "Object.defineProperty": + throw new Error("TODO"); default: - return false; + throw new Error("Unexpected type"); } - - return true; + } }; -module.exports = BasicEvaluatedExpression; +module.exports = CommonJsExportRequireDependency; /***/ }), -/***/ 91145: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 45598: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -89120,217 +85634,164 @@ module.exports = BasicEvaluatedExpression; -const Entrypoint = __webpack_require__(13795); - -/** @typedef {import("../Chunk")} Chunk */ - -/** - * @param {Entrypoint} entrypoint a chunk group - * @param {Chunk} excludedChunk1 current chunk which is excluded - * @param {Chunk} excludedChunk2 runtime chunk which is excluded - * @returns {Set} chunks - */ -const getAllChunks = (entrypoint, excludedChunk1, excludedChunk2) => { - const queue = new Set([entrypoint]); - const chunks = new Set(); - for (const entrypoint of queue) { - for (const chunk of entrypoint.chunks) { - if (chunk === excludedChunk1) continue; - if (chunk === excludedChunk2) continue; - chunks.add(chunk); - } - for (const parent of entrypoint.parentsIterable) { - if (parent instanceof Entrypoint) queue.add(parent); - } - } - return chunks; -}; -exports.getAllChunks = getAllChunks; +const InitFragment = __webpack_require__(55870); +const makeSerializable = __webpack_require__(33032); +const propertyAccess = __webpack_require__(54190); +const { handleDependencyBase } = __webpack_require__(59643); +const NullDependency = __webpack_require__(31830); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/***/ }), +const EMPTY_OBJECT = {}; -/***/ 84508: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +class CommonJsExportsDependency extends NullDependency { + constructor(range, valueRange, base, names) { + super(); + this.range = range; + this.valueRange = valueRange; + this.base = base; + this.names = names; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + get type() { + return "cjs exports"; + } + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + const name = this.names[0]; + return { + exports: [ + { + name, + // we can't mangle names that are in an empty object + // because one could access the prototype property + // when export isn't set yet + canMangle: !(name in EMPTY_OBJECT) + } + ], + dependencies: undefined + }; + } + serialize(context) { + const { write } = context; + write(this.range); + write(this.valueRange); + write(this.base); + write(this.names); + super.serialize(context); + } -const { ConcatSource, RawSource } = __webpack_require__(51255); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const { - getChunkFilenameTemplate, - getCompilationHooks -} = __webpack_require__(89464); -const { - generateEntryStartup, - updateHashForEntryStartup -} = __webpack_require__(98124); + deserialize(context) { + const { read } = context; + this.range = read(); + this.valueRange = read(); + this.base = read(); + this.names = read(); + super.deserialize(context); + } +} -/** @typedef {import("../Compiler")} Compiler */ +makeSerializable( + CommonJsExportsDependency, + "webpack/lib/dependencies/CommonJsExportsDependency" +); -class CommonJsChunkFormatPlugin { +CommonJsExportsDependency.Template = class CommonJsExportsDependencyTemplate extends ( + NullDependency.Template +) { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - compiler.hooks.thisCompilation.tap( - "CommonJsChunkFormatPlugin", - compilation => { - compilation.hooks.additionalChunkRuntimeRequirements.tap( - "CommonJsChunkLoadingPlugin", - (chunk, set, { chunkGraph }) => { - if (chunk.hasRuntime()) return; - if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { - set.add(RuntimeGlobals.require); - set.add(RuntimeGlobals.startupEntrypoint); - set.add(RuntimeGlobals.externalInstallChunk); - } - } - ); - const hooks = getCompilationHooks(compilation); - hooks.renderChunk.tap( - "CommonJsChunkFormatPlugin", - (modules, renderContext) => { - const { chunk, chunkGraph, runtimeTemplate } = renderContext; - const source = new ConcatSource(); - source.add(`exports.id = ${JSON.stringify(chunk.id)};\n`); - source.add(`exports.ids = ${JSON.stringify(chunk.ids)};\n`); - source.add(`exports.modules = `); - source.add(modules); - source.add(";\n"); - const runtimeModules = - chunkGraph.getChunkRuntimeModulesInOrder(chunk); - if (runtimeModules.length > 0) { - source.add("exports.runtime =\n"); - source.add( - Template.renderChunkRuntimeModules( - runtimeModules, - renderContext - ) - ); - } - const entries = Array.from( - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) - ); - if (entries.length > 0) { - const runtimeChunk = entries[0][1].getRuntimeChunk(); - const currentOutputName = compilation - .getPath( - getChunkFilenameTemplate(chunk, compilation.outputOptions), - { - chunk, - contentHashType: "javascript" - } - ) - .split("/"); - const runtimeOutputName = compilation - .getPath( - getChunkFilenameTemplate( - runtimeChunk, - compilation.outputOptions - ), - { - chunk: runtimeChunk, - contentHashType: "javascript" - } - ) - .split("/"); - - // remove filename, we only need the directory - currentOutputName.pop(); - - // remove common parts - while ( - currentOutputName.length > 0 && - runtimeOutputName.length > 0 && - currentOutputName[0] === runtimeOutputName[0] - ) { - currentOutputName.shift(); - runtimeOutputName.shift(); - } + apply( + dependency, + source, + { module, moduleGraph, initFragments, runtimeRequirements, runtime } + ) { + const dep = /** @type {CommonJsExportsDependency} */ (dependency); + const used = moduleGraph + .getExportsInfo(module) + .getUsedName(dep.names, runtime); - // create final path - const runtimePath = - (currentOutputName.length > 0 - ? "../".repeat(currentOutputName.length) - : "./") + runtimeOutputName.join("/"); + const [type, base] = handleDependencyBase( + dep.base, + module, + runtimeRequirements + ); - const entrySource = new ConcatSource(); - entrySource.add( - `(${ - runtimeTemplate.supportsArrowFunction() - ? "() => " - : "function() " - }{\n` - ); - entrySource.add("var exports = {};\n"); - entrySource.add(source); - entrySource.add(";\n\n// load runtime\n"); - entrySource.add( - `var __webpack_require__ = require(${JSON.stringify( - runtimePath - )});\n` - ); - entrySource.add( - `${RuntimeGlobals.externalInstallChunk}(exports);\n` - ); - const startupSource = new RawSource( - generateEntryStartup( - chunkGraph, - runtimeTemplate, - entries, - chunk, - false - ) - ); - entrySource.add( - hooks.renderStartup.call( - startupSource, - entries[entries.length - 1][0], - { - ...renderContext, - inlined: false - } - ) - ); - entrySource.add("\n})()"); - return entrySource; - } - return source; - } + switch (type) { + case "expression": + if (!used) { + initFragments.push( + new InitFragment( + "var __webpack_unused_export__;\n", + InitFragment.STAGE_CONSTANTS, + 0, + "__webpack_unused_export__" + ) + ); + source.replace( + dep.range[0], + dep.range[1] - 1, + "__webpack_unused_export__" + ); + return; + } + source.replace( + dep.range[0], + dep.range[1] - 1, + `${base}${propertyAccess(used)}` ); - hooks.chunkHash.tap( - "CommonJsChunkFormatPlugin", - (chunk, hash, { chunkGraph }) => { - if (chunk.hasRuntime()) return; - hash.update("CommonJsChunkFormatPlugin"); - hash.update("1"); - const entries = Array.from( - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) - ); - updateHashForEntryStartup(hash, chunkGraph, entries, chunk); - } + return; + case "Object.defineProperty": + if (!used) { + initFragments.push( + new InitFragment( + "var __webpack_unused_export__;\n", + InitFragment.STAGE_CONSTANTS, + 0, + "__webpack_unused_export__" + ) + ); + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + "__webpack_unused_export__ = (" + ); + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + return; + } + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `Object.defineProperty(${base}${propertyAccess( + used.slice(0, -1) + )}, ${JSON.stringify(used[used.length - 1])}, (` ); - } - ); + source.replace(dep.valueRange[1], dep.range[1] - 1, "))"); + return; + } } -} +}; -module.exports = CommonJsChunkFormatPlugin; +module.exports = CommonJsExportsDependency; /***/ }), -/***/ 61291: +/***/ 97107: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -89341,122 +85802,340 @@ module.exports = CommonJsChunkFormatPlugin; -/** @typedef {import("../../declarations/WebpackOptions").ChunkLoadingType} ChunkLoadingType */ -/** @typedef {import("../Compiler")} Compiler */ +const RuntimeGlobals = __webpack_require__(16475); +const formatLocation = __webpack_require__(16734); +const { evaluateToString } = __webpack_require__(93998); +const propertyAccess = __webpack_require__(54190); +const CommonJsExportRequireDependency = __webpack_require__(62892); +const CommonJsExportsDependency = __webpack_require__(45598); +const CommonJsSelfReferenceDependency = __webpack_require__(52225); +const DynamicExports = __webpack_require__(32006); +const HarmonyExports = __webpack_require__(39211); +const ModuleDecoratorDependency = __webpack_require__(88488); -/** @type {WeakMap>} */ -const enabledTypes = new WeakMap(); +/** @typedef {import("estree").Expression} ExpressionNode */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ -const getEnabledTypes = compiler => { - let set = enabledTypes.get(compiler); - if (set === undefined) { - set = new Set(); - enabledTypes.set(compiler, set); +const getValueOfPropertyDescription = expr => { + if (expr.type !== "ObjectExpression") return; + for (const property of expr.properties) { + if (property.computed) continue; + const key = property.key; + if (key.type !== "Identifier" || key.name !== "value") continue; + return property.value; } - return set; }; -class EnableChunkLoadingPlugin { - /** - * @param {ChunkLoadingType} type library type that should be available - */ - constructor(type) { - this.type = type; +const isTruthyLiteral = expr => { + switch (expr.type) { + case "Literal": + return !!expr.value; + case "UnaryExpression": + if (expr.operator === "!") return isFalsyLiteral(expr.argument); } + return false; +}; - /** - * @param {Compiler} compiler the compiler instance - * @param {ChunkLoadingType} type type of library - * @returns {void} - */ - static setEnabled(compiler, type) { - getEnabledTypes(compiler).add(type); +const isFalsyLiteral = expr => { + switch (expr.type) { + case "Literal": + return !expr.value; + case "UnaryExpression": + if (expr.operator === "!") return isTruthyLiteral(expr.argument); } + return false; +}; - /** - * @param {Compiler} compiler the compiler instance - * @param {ChunkLoadingType} type type of library - * @returns {void} - */ - static checkEnabled(compiler, type) { - if (!getEnabledTypes(compiler).has(type)) { - throw new Error( - `Chunk loading type "${type}" is not enabled. ` + - "EnableChunkLoadingPlugin need to be used to enable this type of chunk loading. " + - 'This usually happens through the "output.enabledChunkLoadingTypes" option. ' + - 'If you are using a function as entry which sets "chunkLoading", you need to add all potential chunk loading types to "output.enabledChunkLoadingTypes". ' + - "These types are enabled: " + - Array.from(getEnabledTypes(compiler)).join(", ") - ); +/** + * @param {JavascriptParser} parser the parser + * @param {ExpressionNode} expr expression + * @returns {{ argument: BasicEvaluatedExpression, ids: string[] } | undefined} parsed call + */ +const parseRequireCall = (parser, expr) => { + const ids = []; + while (expr.type === "MemberExpression") { + if (expr.object.type === "Super") return; + if (!expr.property) return; + const prop = expr.property; + if (expr.computed) { + if (prop.type !== "Literal") return; + ids.push(`${prop.value}`); + } else { + if (prop.type !== "Identifier") return; + ids.push(prop.name); } + expr = expr.object; + } + if (expr.type !== "CallExpression" || expr.arguments.length !== 1) return; + const callee = expr.callee; + if ( + callee.type !== "Identifier" || + parser.getVariableInfo(callee.name) !== "require" + ) { + return; + } + const arg = expr.arguments[0]; + if (arg.type === "SpreadElement") return; + const argValue = parser.evaluateExpression(arg); + return { argument: argValue, ids: ids.reverse() }; +}; + +class CommonJsExportsParserPlugin { + constructor(moduleGraph) { + this.moduleGraph = moduleGraph; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {JavascriptParser} parser the parser */ - apply(compiler) { - const { type } = this; + apply(parser) { + const enableStructuredExports = () => { + DynamicExports.enable(parser.state); + }; + const checkNamespace = (topLevel, members, valueExpr) => { + if (!DynamicExports.isEnabled(parser.state)) return; + if (members.length > 0 && members[0] === "__esModule") { + if (valueExpr && isTruthyLiteral(valueExpr) && topLevel) { + DynamicExports.setFlagged(parser.state); + } else { + DynamicExports.setDynamic(parser.state); + } + } + }; + const bailout = reason => { + DynamicExports.bailout(parser.state); + if (reason) bailoutHint(reason); + }; + const bailoutHint = reason => { + this.moduleGraph + .getOptimizationBailout(parser.state.module) + .push(`CommonJS bailout: ${reason}`); + }; - // Only enable once - const enabled = getEnabledTypes(compiler); - if (enabled.has(type)) return; - enabled.add(type); + // metadata // + parser.hooks.evaluateTypeof + .for("module") + .tap("CommonJsExportsParserPlugin", evaluateToString("object")); + parser.hooks.evaluateTypeof + .for("exports") + .tap("CommonJsPlugin", evaluateToString("object")); - if (typeof type === "string") { - switch (type) { - case "jsonp": { - const JsonpChunkLoadingPlugin = __webpack_require__(83121); - new JsonpChunkLoadingPlugin().apply(compiler); - break; - } - case "import-scripts": { - const ImportScriptsChunkLoadingPlugin = __webpack_require__(54182); - new ImportScriptsChunkLoadingPlugin().apply(compiler); - break; - } - case "require": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const CommonJsChunkLoadingPlugin = __webpack_require__(1313); - new CommonJsChunkLoadingPlugin({ - asyncChunkLoading: false - }).apply(compiler); - break; - } - case "async-node": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const CommonJsChunkLoadingPlugin = __webpack_require__(1313); - new CommonJsChunkLoadingPlugin({ - asyncChunkLoading: true - }).apply(compiler); - break; - } - case "import": { - const ModuleChunkLoadingPlugin = __webpack_require__(89831); - new ModuleChunkLoadingPlugin().apply(compiler); - break; + // exporting // + const handleAssignExport = (expr, base, members) => { + if (HarmonyExports.isEnabled(parser.state)) return; + // Handle reexporting + const requireCall = parseRequireCall(parser, expr.right); + if ( + requireCall && + requireCall.argument.isString() && + (members.length === 0 || members[0] !== "__esModule") + ) { + enableStructuredExports(); + // It's possible to reexport __esModule, so we must convert to a dynamic module + if (members.length === 0) DynamicExports.setDynamic(parser.state); + const dep = new CommonJsExportRequireDependency( + expr.range, + null, + base, + members, + requireCall.argument.string, + requireCall.ids, + !parser.isStatementLevelExpression(expr) + ); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.module.addDependency(dep); + return true; + } + if (members.length === 0) return; + enableStructuredExports(); + const remainingMembers = members; + checkNamespace( + parser.statementPath.length === 1 && + parser.isStatementLevelExpression(expr), + remainingMembers, + expr.right + ); + const dep = new CommonJsExportsDependency( + expr.left.range, + null, + base, + remainingMembers + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + parser.walkExpression(expr.right); + return true; + }; + parser.hooks.assignMemberChain + .for("exports") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + return handleAssignExport(expr, "exports", members); + }); + parser.hooks.assignMemberChain + .for("this") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + if (!parser.scope.topLevelScope) return; + return handleAssignExport(expr, "this", members); + }); + parser.hooks.assignMemberChain + .for("module") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + if (members[0] !== "exports") return; + return handleAssignExport(expr, "module.exports", members.slice(1)); + }); + parser.hooks.call + .for("Object.defineProperty") + .tap("CommonJsExportsParserPlugin", expression => { + const expr = /** @type {import("estree").CallExpression} */ ( + expression + ); + if (!parser.isStatementLevelExpression(expr)) return; + if (expr.arguments.length !== 3) return; + if (expr.arguments[0].type === "SpreadElement") return; + if (expr.arguments[1].type === "SpreadElement") return; + if (expr.arguments[2].type === "SpreadElement") return; + const exportsArg = parser.evaluateExpression(expr.arguments[0]); + if (!exportsArg || !exportsArg.isIdentifier()) return; + if ( + exportsArg.identifier !== "exports" && + exportsArg.identifier !== "module.exports" && + (exportsArg.identifier !== "this" || !parser.scope.topLevelScope) + ) { + return; } - case "universal": - // TODO implement universal chunk loading - throw new Error("Universal Chunk Loading is not implemented yet"); - default: - throw new Error(`Unsupported chunk loading type ${type}. -Plugins which provide custom chunk loading types must call EnableChunkLoadingPlugin.setEnabled(compiler, type) to disable this error.`); + const propertyArg = parser.evaluateExpression(expr.arguments[1]); + if (!propertyArg) return; + const property = propertyArg.asString(); + if (typeof property !== "string") return; + enableStructuredExports(); + const descArg = expr.arguments[2]; + checkNamespace( + parser.statementPath.length === 1, + [property], + getValueOfPropertyDescription(descArg) + ); + const dep = new CommonJsExportsDependency( + expr.range, + expr.arguments[2].range, + `Object.defineProperty(${exportsArg.identifier})`, + [property] + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + + parser.walkExpression(expr.arguments[2]); + return true; + }); + + // Self reference // + const handleAccessExport = (expr, base, members, call = undefined) => { + if (HarmonyExports.isEnabled(parser.state)) return; + if (members.length === 0) { + bailout(`${base} is used directly at ${formatLocation(expr.loc)}`); } - } else { - // TODO support plugin instances here - // apply them to the compiler - } + if (call && members.length === 1) { + bailoutHint( + `${base}${propertyAccess( + members + )}(...) prevents optimization as ${base} is passed as call context at ${formatLocation( + expr.loc + )}` + ); + } + const dep = new CommonJsSelfReferenceDependency( + expr.range, + base, + members, + !!call + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + if (call) { + parser.walkExpressions(call.arguments); + } + return true; + }; + parser.hooks.callMemberChain + .for("exports") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + return handleAccessExport(expr.callee, "exports", members, expr); + }); + parser.hooks.expressionMemberChain + .for("exports") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + return handleAccessExport(expr, "exports", members); + }); + parser.hooks.expression + .for("exports") + .tap("CommonJsExportsParserPlugin", expr => { + return handleAccessExport(expr, "exports", []); + }); + parser.hooks.callMemberChain + .for("module") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + if (members[0] !== "exports") return; + return handleAccessExport( + expr.callee, + "module.exports", + members.slice(1), + expr + ); + }); + parser.hooks.expressionMemberChain + .for("module") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + if (members[0] !== "exports") return; + return handleAccessExport(expr, "module.exports", members.slice(1)); + }); + parser.hooks.expression + .for("module.exports") + .tap("CommonJsExportsParserPlugin", expr => { + return handleAccessExport(expr, "module.exports", []); + }); + parser.hooks.callMemberChain + .for("this") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + if (!parser.scope.topLevelScope) return; + return handleAccessExport(expr.callee, "this", members, expr); + }); + parser.hooks.expressionMemberChain + .for("this") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + if (!parser.scope.topLevelScope) return; + return handleAccessExport(expr, "this", members); + }); + parser.hooks.expression + .for("this") + .tap("CommonJsExportsParserPlugin", expr => { + if (!parser.scope.topLevelScope) return; + return handleAccessExport(expr, "this", []); + }); + + // Bailouts // + parser.hooks.expression.for("module").tap("CommonJsPlugin", expr => { + bailout(); + const isHarmony = HarmonyExports.isEnabled(parser.state); + const dep = new ModuleDecoratorDependency( + isHarmony + ? RuntimeGlobals.harmonyModuleDecorator + : RuntimeGlobals.nodeModuleDecorator, + !isHarmony + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return true; + }); } } - -module.exports = EnableChunkLoadingPlugin; +module.exports = CommonJsExportsParserPlugin; /***/ }), -/***/ 77106: +/***/ 59440: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -89467,229 +86146,536 @@ module.exports = EnableChunkLoadingPlugin; -const util = __webpack_require__(73837); -const { RawSource, ReplaceSource } = __webpack_require__(51255); -const Generator = __webpack_require__(93401); -const InitFragment = __webpack_require__(55870); -const HarmonyCompatibilityDependency = __webpack_require__(72906); +const Template = __webpack_require__(39722); +const { equals } = __webpack_require__(84953); +const makeSerializable = __webpack_require__(33032); +const propertyAccess = __webpack_require__(54190); +const ModuleDependency = __webpack_require__(80321); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ - -// TODO: clean up this file -// replace with newer constructs - -const deprecatedGetInitFragments = util.deprecate( - (template, dependency, templateContext) => - template.getInitFragments(dependency, templateContext), - "DependencyTemplate.getInitFragment is deprecated (use apply(dep, source, { initFragments }) instead)", - "DEP_WEBPACK_JAVASCRIPT_GENERATOR_GET_INIT_FRAGMENTS" -); - -const TYPES = new Set(["javascript"]); +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -class JavascriptGenerator extends Generator { +class CommonJsFullRequireDependency extends ModuleDependency { /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) + * @param {string} request the request string + * @param {[number, number]} range location in source code + * @param {string[]} names accessed properties on module */ - getTypes(module) { - return TYPES; + constructor(request, range, names) { + super(request); + this.range = range; + this.names = names; + this.call = false; + this.asiSafe = undefined; } /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module + * 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 */ - getSize(module, type) { - const originalSource = module.originalSource(); - if (!originalSource) { - return 39; + getReferencedExports(moduleGraph, runtime) { + if (this.call) { + const importedModule = moduleGraph.getModule(this); + if ( + !importedModule || + importedModule.getExportsType(moduleGraph, false) !== "namespace" + ) { + return [this.names.slice(0, -1)]; + } } - return originalSource.size(); + return [this.names]; } - /** - * @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) { - // Only harmony modules are valid for optimization - if ( - !module.buildMeta || - module.buildMeta.exportsType !== "namespace" || - module.presentationalDependencies === undefined || - !module.presentationalDependencies.some( - d => d instanceof HarmonyCompatibilityDependency - ) - ) { - return "Module is not an ECMAScript module"; - } - - // Some expressions are not compatible with module concatenation - // because they may produce unexpected results. The plugin bails out - // if some were detected upfront. - if (module.buildInfo && module.buildInfo.moduleConcatenationBailout) { - return `Module uses ${module.buildInfo.moduleConcatenationBailout}`; - } + serialize(context) { + const { write } = context; + write(this.names); + write(this.call); + write(this.asiSafe); + super.serialize(context); } - /** - * @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 originalSource = module.originalSource(); - if (!originalSource) { - return new RawSource("throw new Error('No source available');"); - } - - const source = new ReplaceSource(originalSource); - const initFragments = []; + deserialize(context) { + const { read } = context; + this.names = read(); + this.call = read(); + this.asiSafe = read(); + super.deserialize(context); + } - this.sourceModule(module, initFragments, source, generateContext); + get type() { + return "cjs full require"; + } - return InitFragment.addToSource(source, initFragments, generateContext); + get category() { + return "commonjs"; } +} +CommonJsFullRequireDependency.Template = class CommonJsFullRequireDependencyTemplate extends ( + ModuleDependency.Template +) { /** - * @param {Module} module the module to generate - * @param {InitFragment[]} initFragments mutable list of init fragments + * @param {Dependency} dependency the dependency for which the template should be applied * @param {ReplaceSource} source the current replace source which can be modified - * @param {GenerateContext} generateContext the generateContext + * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ - sourceModule(module, initFragments, source, generateContext) { - for (const dependency of module.dependencies) { - this.sourceDependency( - module, - dependency, - initFragments, - source, - generateContext - ); + apply( + dependency, + source, + { + module, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtimeRequirements, + runtime, + initFragments } - - if (module.presentationalDependencies !== undefined) { - for (const dependency of module.presentationalDependencies) { - this.sourceDependency( - module, - dependency, - initFragments, - source, - generateContext - ); + ) { + const dep = /** @type {CommonJsFullRequireDependency} */ (dependency); + if (!dep.range) return; + const importedModule = moduleGraph.getModule(dep); + let requireExpr = runtimeTemplate.moduleExports({ + module: importedModule, + chunkGraph, + request: dep.request, + weak: dep.weak, + runtimeRequirements + }); + if (importedModule) { + const ids = dep.names; + const usedImported = moduleGraph + .getExportsInfo(importedModule) + .getUsedName(ids, runtime); + if (usedImported) { + const comment = equals(usedImported, ids) + ? "" + : Template.toNormalComment(propertyAccess(ids)) + " "; + const access = `${comment}${propertyAccess(usedImported)}`; + requireExpr = + dep.asiSafe === true + ? `(${requireExpr}${access})` + : `${requireExpr}${access}`; } } - - for (const childBlock of module.blocks) { - this.sourceBlock( - module, - childBlock, - initFragments, - source, - generateContext - ); - } + source.replace(dep.range[0], dep.range[1] - 1, requireExpr); } +}; + +makeSerializable( + CommonJsFullRequireDependency, + "webpack/lib/dependencies/CommonJsFullRequireDependency" +); + +module.exports = CommonJsFullRequireDependency; + + +/***/ }), + +/***/ 36013: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const CommentCompilationWarning = __webpack_require__(98427); +const RuntimeGlobals = __webpack_require__(16475); +const UnsupportedFeatureWarning = __webpack_require__(42495); +const { + evaluateToIdentifier, + evaluateToString, + expressionIsUnsupported, + toConstantDependency +} = __webpack_require__(93998); +const CommonJsFullRequireDependency = __webpack_require__(59440); +const CommonJsRequireContextDependency = __webpack_require__(23962); +const CommonJsRequireDependency = __webpack_require__(21264); +const ConstDependency = __webpack_require__(76911); +const ContextDependencyHelpers = __webpack_require__(99630); +const LocalModuleDependency = __webpack_require__(52805); +const { getLocalModule } = __webpack_require__(75827); +const RequireHeaderDependency = __webpack_require__(89183); +const RequireResolveContextDependency = __webpack_require__(55627); +const RequireResolveDependency = __webpack_require__(68582); +const RequireResolveHeaderDependency = __webpack_require__(9880); + +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +class CommonJsImportsParserPlugin { /** - * @param {Module} module the module to generate - * @param {DependenciesBlock} block the dependencies block which will be processed - * @param {InitFragment[]} initFragments mutable list of init fragments - * @param {ReplaceSource} source the current replace source which can be modified - * @param {GenerateContext} generateContext the generateContext - * @returns {void} + * @param {JavascriptParserOptions} options parser options */ - sourceBlock(module, block, initFragments, source, generateContext) { - for (const dependency of block.dependencies) { - this.sourceDependency( - module, - dependency, - initFragments, - source, - generateContext - ); - } + constructor(options) { + this.options = options; + } - for (const childBlock of block.blocks) { - this.sourceBlock( - module, - childBlock, - initFragments, - source, - generateContext + apply(parser) { + const options = this.options; + + // metadata // + const tapRequireExpression = (expression, getMembers) => { + parser.hooks.typeof + .for(expression) + .tap( + "CommonJsPlugin", + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for(expression) + .tap("CommonJsPlugin", evaluateToString("function")); + parser.hooks.evaluateIdentifier + .for(expression) + .tap( + "CommonJsPlugin", + evaluateToIdentifier(expression, "require", getMembers, true) + ); + }; + tapRequireExpression("require", () => []); + tapRequireExpression("require.resolve", () => ["resolve"]); + tapRequireExpression("require.resolveWeak", () => ["resolveWeak"]); + + // Weird stuff // + parser.hooks.assign.for("require").tap("CommonJsPlugin", expr => { + // to not leak to global "require", we need to define a local require here. + const dep = new ConstDependency("var require;", 0); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + + // Unsupported // + parser.hooks.expression + .for("require.main.require") + .tap( + "CommonJsPlugin", + expressionIsUnsupported( + parser, + "require.main.require is not supported by webpack." + ) + ); + parser.hooks.call + .for("require.main.require") + .tap( + "CommonJsPlugin", + expressionIsUnsupported( + parser, + "require.main.require is not supported by webpack." + ) + ); + parser.hooks.expression + .for("module.parent.require") + .tap( + "CommonJsPlugin", + expressionIsUnsupported( + parser, + "module.parent.require is not supported by webpack." + ) + ); + parser.hooks.call + .for("module.parent.require") + .tap( + "CommonJsPlugin", + expressionIsUnsupported( + parser, + "module.parent.require is not supported by webpack." + ) ); - } - } - /** - * @param {Module} module the current module - * @param {Dependency} dependency the dependency to generate - * @param {InitFragment[]} initFragments mutable list of init fragments - * @param {ReplaceSource} source the current replace source which can be modified - * @param {GenerateContext} generateContext the render context - * @returns {void} - */ - sourceDependency(module, dependency, initFragments, source, generateContext) { - const constructor = /** @type {new (...args: any[]) => Dependency} */ ( - dependency.constructor - ); - const template = generateContext.dependencyTemplates.get(constructor); - if (!template) { - throw new Error( - "No template for dependency: " + dependency.constructor.name + // renaming // + parser.hooks.canRename.for("require").tap("CommonJsPlugin", () => true); + parser.hooks.rename.for("require").tap("CommonJsPlugin", expr => { + // To avoid "not defined" error, replace the value with undefined + const dep = new ConstDependency("undefined", expr.range); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return false; + }); + + // inspection // + parser.hooks.expression + .for("require.cache") + .tap( + "CommonJsImportsParserPlugin", + toConstantDependency(parser, RuntimeGlobals.moduleCache, [ + RuntimeGlobals.moduleCache, + RuntimeGlobals.moduleId, + RuntimeGlobals.moduleLoaded + ]) ); - } - const templateContext = { - runtimeTemplate: generateContext.runtimeTemplate, - dependencyTemplates: generateContext.dependencyTemplates, - moduleGraph: generateContext.moduleGraph, - chunkGraph: generateContext.chunkGraph, - module, - runtime: generateContext.runtime, - runtimeRequirements: generateContext.runtimeRequirements, - concatenationScope: generateContext.concatenationScope, - codeGenerationResults: generateContext.codeGenerationResults, - initFragments + // require as expression // + parser.hooks.expression + .for("require") + .tap("CommonJsImportsParserPlugin", expr => { + const dep = new CommonJsRequireContextDependency( + { + request: options.unknownContextRequest, + recursive: options.unknownContextRecursive, + regExp: options.unknownContextRegExp, + mode: "sync" + }, + expr.range, + undefined, + parser.scope.inShorthand + ); + dep.critical = + options.unknownContextCritical && + "require function is used in a way in which dependencies cannot be statically extracted"; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }); + + // require // + const processRequireItem = (expr, param) => { + if (param.isString()) { + const dep = new CommonJsRequireDependency(param.string, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } }; + const processRequireContext = (expr, param) => { + const dep = ContextDependencyHelpers.create( + CommonJsRequireContextDependency, + expr.range, + param, + expr, + options, + { + category: "commonjs" + }, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }; + const createRequireHandler = callNew => expr => { + if (options.commonjsMagicComments) { + const { options: requireOptions, errors: commentErrors } = + parser.parseCommentOptions(expr.range); - template.apply(dependency, source, templateContext); + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + comment.loc + ) + ); + } + } + if (requireOptions) { + if (requireOptions.webpackIgnore !== undefined) { + if (typeof requireOptions.webpackIgnore !== "boolean") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${requireOptions.webpackIgnore}.`, + expr.loc + ) + ); + } else { + // Do not instrument `require()` if `webpackIgnore` is `true` + if (requireOptions.webpackIgnore) { + return true; + } + } + } + } + } - // TODO remove in webpack 6 - if ("getInitFragments" in template) { - const fragments = deprecatedGetInitFragments( - template, - dependency, - templateContext - ); + if (expr.arguments.length !== 1) return; + let localModule; + const param = parser.evaluateExpression(expr.arguments[0]); + if (param.isConditional()) { + let isExpression = false; + for (const p of param.options) { + const result = processRequireItem(expr, p); + if (result === undefined) { + isExpression = true; + } + } + if (!isExpression) { + const dep = new RequireHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + } + } + if ( + param.isString() && + (localModule = getLocalModule(parser.state, param.string)) + ) { + localModule.flagUsed(); + const dep = new LocalModuleDependency(localModule, expr.range, callNew); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + } else { + const result = processRequireItem(expr, param); + if (result === undefined) { + processRequireContext(expr, param); + } else { + const dep = new RequireHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + } + return true; + } + }; + parser.hooks.call + .for("require") + .tap("CommonJsImportsParserPlugin", createRequireHandler(false)); + parser.hooks.new + .for("require") + .tap("CommonJsImportsParserPlugin", createRequireHandler(true)); + parser.hooks.call + .for("module.require") + .tap("CommonJsImportsParserPlugin", createRequireHandler(false)); + parser.hooks.new + .for("module.require") + .tap("CommonJsImportsParserPlugin", createRequireHandler(true)); - if (fragments) { - for (const fragment of fragments) { - initFragments.push(fragment); + // require with property access // + const chainHandler = (expr, calleeMembers, callExpr, members) => { + if (callExpr.arguments.length !== 1) return; + const param = parser.evaluateExpression(callExpr.arguments[0]); + if (param.isString() && !getLocalModule(parser.state, param.string)) { + const dep = new CommonJsFullRequireDependency( + param.string, + expr.range, + members + ); + dep.asiSafe = !parser.isAsiPosition(expr.range[0]); + dep.optional = !!parser.scope.inTry; + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + } + }; + const callChainHandler = (expr, calleeMembers, callExpr, members) => { + if (callExpr.arguments.length !== 1) return; + const param = parser.evaluateExpression(callExpr.arguments[0]); + if (param.isString() && !getLocalModule(parser.state, param.string)) { + const dep = new CommonJsFullRequireDependency( + param.string, + expr.callee.range, + members + ); + dep.call = true; + dep.asiSafe = !parser.isAsiPosition(expr.range[0]); + dep.optional = !!parser.scope.inTry; + dep.loc = expr.callee.loc; + parser.state.current.addDependency(dep); + parser.walkExpressions(expr.arguments); + return true; + } + }; + parser.hooks.memberChainOfCallMemberChain + .for("require") + .tap("CommonJsImportsParserPlugin", chainHandler); + parser.hooks.memberChainOfCallMemberChain + .for("module.require") + .tap("CommonJsImportsParserPlugin", chainHandler); + parser.hooks.callMemberChainOfCallMemberChain + .for("require") + .tap("CommonJsImportsParserPlugin", callChainHandler); + parser.hooks.callMemberChainOfCallMemberChain + .for("module.require") + .tap("CommonJsImportsParserPlugin", callChainHandler); + + // require.resolve // + const processResolve = (expr, weak) => { + if (expr.arguments.length !== 1) return; + const param = parser.evaluateExpression(expr.arguments[0]); + if (param.isConditional()) { + for (const option of param.options) { + const result = processResolveItem(expr, option, weak); + if (result === undefined) { + processResolveContext(expr, option, weak); + } + } + const dep = new RequireResolveHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + } else { + const result = processResolveItem(expr, param, weak); + if (result === undefined) { + processResolveContext(expr, param, weak); } + const dep = new RequireResolveHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; } - } + }; + const processResolveItem = (expr, param, weak) => { + if (param.isString()) { + const dep = new RequireResolveDependency(param.string, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + dep.weak = weak; + parser.state.current.addDependency(dep); + return true; + } + }; + const processResolveContext = (expr, param, weak) => { + const dep = ContextDependencyHelpers.create( + RequireResolveContextDependency, + param.range, + param, + expr, + options, + { + category: "commonjs", + mode: weak ? "weak" : "sync" + }, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }; + + parser.hooks.call + .for("require.resolve") + .tap("RequireResolveDependencyParserPlugin", expr => { + return processResolve(expr, false); + }); + parser.hooks.call + .for("require.resolveWeak") + .tap("RequireResolveDependencyParserPlugin", expr => { + return processResolve(expr, true); + }); } } - -module.exports = JavascriptGenerator; +module.exports = CommonJsImportsParserPlugin; /***/ }), -/***/ 89464: +/***/ 32406: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -89700,1349 +86686,654 @@ module.exports = JavascriptGenerator; -const { SyncWaterfallHook, SyncHook, SyncBailHook } = __webpack_require__(6967); -const vm = __webpack_require__(26144); -const { - ConcatSource, - OriginalSource, - PrefixSource, - RawSource, - CachedSource -} = __webpack_require__(51255); -const Compilation = __webpack_require__(85720); -const { tryRunOrWebpackError } = __webpack_require__(11351); -const HotUpdateChunk = __webpack_require__(9597); -const InitFragment = __webpack_require__(55870); const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const { last, someInIterable } = __webpack_require__(39104); -const StringXor = __webpack_require__(40293); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const createHash = __webpack_require__(49835); -const { intersectRuntime } = __webpack_require__(17156); -const JavascriptGenerator = __webpack_require__(77106); -const JavascriptParser = __webpack_require__(29050); +const RuntimeModule = __webpack_require__(16963); +const SelfModuleFactory = __webpack_require__(63560); +const Template = __webpack_require__(39722); +const CommonJsExportsDependency = __webpack_require__(45598); +const CommonJsFullRequireDependency = __webpack_require__(59440); +const CommonJsRequireContextDependency = __webpack_require__(23962); +const CommonJsRequireDependency = __webpack_require__(21264); +const CommonJsSelfReferenceDependency = __webpack_require__(52225); +const ModuleDecoratorDependency = __webpack_require__(88488); +const RequireHeaderDependency = __webpack_require__(89183); +const RequireResolveContextDependency = __webpack_require__(55627); +const RequireResolveDependency = __webpack_require__(68582); +const RequireResolveHeaderDependency = __webpack_require__(9880); +const RuntimeRequirementsDependency = __webpack_require__(24187); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../util/Hash")} Hash */ +const CommonJsExportsParserPlugin = __webpack_require__(97107); +const CommonJsImportsParserPlugin = __webpack_require__(36013); -/** - * @param {Chunk} chunk a chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {boolean} true, when a JS file is needed for this chunk - */ -const chunkHasJs = (chunk, chunkGraph) => { - if (chunkGraph.getNumberOfEntryModules(chunk) > 0) return true; +const { + evaluateToIdentifier, + toConstantDependency +} = __webpack_require__(93998); +const CommonJsExportRequireDependency = __webpack_require__(62892); - return chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript") - ? true - : false; -}; +class CommonJsPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "CommonJsPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + CommonJsRequireDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsRequireDependency, + new CommonJsRequireDependency.Template() + ); -const printGeneratedCodeForStack = (module, code) => { - const lines = code.split("\n"); - const n = `${lines.length}`.length; - return `\n\nGenerated code for ${module.identifier()}\n${lines - .map((line, i, lines) => { - const iStr = `${i + 1}`; - return `${" ".repeat(n - iStr.length)}${iStr} | ${line}`; - }) - .join("\n")}`; -}; + compilation.dependencyFactories.set( + CommonJsFullRequireDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsFullRequireDependency, + new CommonJsFullRequireDependency.Template() + ); -/** - * @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 - * @property {CodeGenerationResults} codeGenerationResults results of code generation - * @property {boolean} strictMode rendering in strict context - */ + compilation.dependencyFactories.set( + CommonJsRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsRequireContextDependency, + new CommonJsRequireContextDependency.Template() + ); -/** - * @typedef {Object} MainRenderContext - * @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 - * @property {CodeGenerationResults} codeGenerationResults results of code generation - * @property {string} hash hash to be used for render call - * @property {boolean} strictMode rendering in strict context - */ + compilation.dependencyFactories.set( + RequireResolveDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveDependency, + new RequireResolveDependency.Template() + ); -/** - * @typedef {Object} ChunkRenderContext - * @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 - * @property {CodeGenerationResults} codeGenerationResults results of code generation - * @property {InitFragment[]} chunkInitFragments init fragments for the chunk - * @property {boolean} strictMode rendering in strict context - */ + compilation.dependencyFactories.set( + RequireResolveContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveContextDependency, + new RequireResolveContextDependency.Template() + ); -/** - * @typedef {Object} RenderBootstrapContext - * @property {Chunk} chunk the chunk - * @property {RuntimeTemplate} runtimeTemplate the runtime template - * @property {ModuleGraph} moduleGraph the module graph - * @property {ChunkGraph} chunkGraph the chunk graph - * @property {string} hash hash to be used for render call - */ + compilation.dependencyTemplates.set( + RequireResolveHeaderDependency, + new RequireResolveHeaderDependency.Template() + ); -/** @typedef {RenderContext & { inlined: boolean }} StartupRenderContext */ + compilation.dependencyTemplates.set( + RequireHeaderDependency, + new RequireHeaderDependency.Template() + ); -/** - * @typedef {Object} CompilationHooks - * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModuleContent - * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModuleContainer - * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModulePackage - * @property {SyncWaterfallHook<[Source, RenderContext]>} renderChunk - * @property {SyncWaterfallHook<[Source, RenderContext]>} renderMain - * @property {SyncWaterfallHook<[Source, RenderContext]>} renderContent - * @property {SyncWaterfallHook<[Source, RenderContext]>} render - * @property {SyncWaterfallHook<[Source, Module, StartupRenderContext]>} renderStartup - * @property {SyncWaterfallHook<[string, RenderBootstrapContext]>} renderRequire - * @property {SyncBailHook<[Module, RenderBootstrapContext], string>} inlineInRuntimeBailout - * @property {SyncBailHook<[Module, RenderContext], string>} embedInRuntimeBailout - * @property {SyncBailHook<[RenderContext], string>} strictRuntimeBailout - * @property {SyncHook<[Chunk, Hash, ChunkHashContext]>} chunkHash - * @property {SyncBailHook<[Chunk, RenderContext], boolean>} useSourceMap - */ + compilation.dependencyTemplates.set( + CommonJsExportsDependency, + new CommonJsExportsDependency.Template() + ); -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); + compilation.dependencyFactories.set( + CommonJsExportRequireDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsExportRequireDependency, + new CommonJsExportRequireDependency.Template() + ); -class JavascriptModulesPlugin { - /** - * @param {Compilation} compilation the compilation - * @returns {CompilationHooks} 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 = { - renderModuleContent: new SyncWaterfallHook([ - "source", - "module", - "renderContext" - ]), - renderModuleContainer: new SyncWaterfallHook([ - "source", - "module", - "renderContext" - ]), - renderModulePackage: new SyncWaterfallHook([ - "source", - "module", - "renderContext" - ]), - render: new SyncWaterfallHook(["source", "renderContext"]), - renderContent: new SyncWaterfallHook(["source", "renderContext"]), - renderStartup: new SyncWaterfallHook([ - "source", - "module", - "startupRenderContext" - ]), - renderChunk: new SyncWaterfallHook(["source", "renderContext"]), - renderMain: new SyncWaterfallHook(["source", "renderContext"]), - renderRequire: new SyncWaterfallHook(["code", "renderContext"]), - inlineInRuntimeBailout: new SyncBailHook(["module", "renderContext"]), - embedInRuntimeBailout: new SyncBailHook(["module", "renderContext"]), - strictRuntimeBailout: new SyncBailHook(["renderContext"]), - chunkHash: new SyncHook(["chunk", "hash", "context"]), - useSourceMap: new SyncBailHook(["chunk", "renderContext"]) - }; - compilationHooksMap.set(compilation, hooks); - } - return hooks; - } + const selfFactory = new SelfModuleFactory(compilation.moduleGraph); - constructor(options = {}) { - this.options = options; - /** @type {WeakMap} */ - this._moduleFactoryCache = new WeakMap(); - } + compilation.dependencyFactories.set( + CommonJsSelfReferenceDependency, + selfFactory + ); + compilation.dependencyTemplates.set( + CommonJsSelfReferenceDependency, + new CommonJsSelfReferenceDependency.Template() + ); - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "JavascriptModulesPlugin", - (compilation, { normalModuleFactory }) => { - const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); - normalModuleFactory.hooks.createParser - .for("javascript/auto") - .tap("JavascriptModulesPlugin", options => { - return new JavascriptParser("auto"); - }); - normalModuleFactory.hooks.createParser - .for("javascript/dynamic") - .tap("JavascriptModulesPlugin", options => { - return new JavascriptParser("script"); - }); - normalModuleFactory.hooks.createParser - .for("javascript/esm") - .tap("JavascriptModulesPlugin", options => { - return new JavascriptParser("module"); - }); - normalModuleFactory.hooks.createGenerator - .for("javascript/auto") - .tap("JavascriptModulesPlugin", () => { - return new JavascriptGenerator(); - }); - normalModuleFactory.hooks.createGenerator - .for("javascript/dynamic") - .tap("JavascriptModulesPlugin", () => { - return new JavascriptGenerator(); + compilation.dependencyFactories.set( + ModuleDecoratorDependency, + selfFactory + ); + compilation.dependencyTemplates.set( + ModuleDecoratorDependency, + new ModuleDecoratorDependency.Template() + ); + + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.harmonyModuleDecorator) + .tap("CommonJsPlugin", (module, set) => { + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.requireScope); }); - normalModuleFactory.hooks.createGenerator - .for("javascript/esm") - .tap("JavascriptModulesPlugin", () => { - return new JavascriptGenerator(); + + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.nodeModuleDecorator) + .tap("CommonJsPlugin", (module, set) => { + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.requireScope); }); - compilation.hooks.renderManifest.tap( - "JavascriptModulesPlugin", - (result, options) => { - const { - hash, + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.harmonyModuleDecorator) + .tap("CommonJsPlugin", (chunk, set) => { + compilation.addRuntimeModule( chunk, - chunkGraph, - moduleGraph, - runtimeTemplate, - dependencyTemplates, - outputOptions, - codeGenerationResults - } = options; + new HarmonyModuleDecoratorRuntimeModule() + ); + }); - const hotUpdateChunk = - chunk instanceof HotUpdateChunk ? chunk : null; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.nodeModuleDecorator) + .tap("CommonJsPlugin", (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new NodeModuleDecoratorRuntimeModule() + ); + }); - let render; - const filenameTemplate = - JavascriptModulesPlugin.getChunkFilenameTemplate( - chunk, - outputOptions - ); - if (hotUpdateChunk) { - render = () => - this.renderChunk( - { - chunk, - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - codeGenerationResults, - strictMode: runtimeTemplate.isModule() - }, - hooks - ); - } else if (chunk.hasRuntime()) { - render = () => - this.renderMain( - { - hash, - chunk, - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - codeGenerationResults, - strictMode: runtimeTemplate.isModule() - }, - hooks, - compilation - ); - } else { - if (!chunkHasJs(chunk, chunkGraph)) { - return result; - } + const handler = (parser, parserOptions) => { + if (parserOptions.commonjs !== undefined && !parserOptions.commonjs) + return; + parser.hooks.typeof + .for("module") + .tap( + "CommonJsPlugin", + toConstantDependency(parser, JSON.stringify("object")) + ); - render = () => - this.renderChunk( - { - chunk, - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - codeGenerationResults, - strictMode: runtimeTemplate.isModule() - }, - hooks - ); - } + parser.hooks.expression + .for("require.main") + .tap( + "CommonJsPlugin", + toConstantDependency( + parser, + `${RuntimeGlobals.moduleCache}[${RuntimeGlobals.entryModuleId}]`, + [RuntimeGlobals.moduleCache, RuntimeGlobals.entryModuleId] + ) + ); + parser.hooks.expression + .for("module.loaded") + .tap("CommonJsPlugin", expr => { + parser.state.module.buildInfo.moduleConcatenationBailout = + "module.loaded"; + const dep = new RuntimeRequirementsDependency([ + RuntimeGlobals.moduleLoaded + ]); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); - result.push({ - render, - filenameTemplate, - pathOptions: { - hash, - runtime: chunk.runtime, - chunk, - contentHashType: "javascript" - }, - info: { - javascriptModule: compilation.runtimeTemplate.isModule() - }, - identifier: hotUpdateChunk - ? `hotupdatechunk${chunk.id}` - : `chunk${chunk.id}`, - hash: chunk.contentHash.javascript + parser.hooks.expression + .for("module.id") + .tap("CommonJsPlugin", expr => { + parser.state.module.buildInfo.moduleConcatenationBailout = + "module.id"; + const dep = new RuntimeRequirementsDependency([ + RuntimeGlobals.moduleId + ]); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; }); - return result; - } - ); - compilation.hooks.chunkHash.tap( - "JavascriptModulesPlugin", - (chunk, hash, context) => { - hooks.chunkHash.call(chunk, hash, context); - if (chunk.hasRuntime()) { - this.updateHashWithBootstrap( - hash, - { - hash: "0000", - chunk, - chunkGraph: context.chunkGraph, - moduleGraph: context.moduleGraph, - runtimeTemplate: context.runtimeTemplate - }, - hooks - ); - } - } - ); - compilation.hooks.contentHash.tap("JavascriptModulesPlugin", chunk => { - const { - chunkGraph, - moduleGraph, - runtimeTemplate, - outputOptions: { - hashSalt, - hashDigest, - hashDigestLength, - hashFunction - } - } = compilation; - const hash = createHash(hashFunction); - if (hashSalt) hash.update(hashSalt); - if (chunk.hasRuntime()) { - this.updateHashWithBootstrap( - hash, - { - hash: "0000", - chunk, - chunkGraph: compilation.chunkGraph, - moduleGraph: compilation.moduleGraph, - runtimeTemplate: compilation.runtimeTemplate - }, - hooks - ); - } else { - hash.update(`${chunk.id} `); - hash.update(chunk.ids ? chunk.ids.join(",") : ""); - } - hooks.chunkHash.call(chunk, hash, { - chunkGraph, - moduleGraph, - runtimeTemplate - }); - const modules = chunkGraph.getChunkModulesIterableBySourceType( - chunk, - "javascript" - ); - if (modules) { - const xor = new StringXor(); - for (const m of modules) { - xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); - } - xor.updateHash(hash); - } - const runtimeModules = chunkGraph.getChunkModulesIterableBySourceType( - chunk, - "runtime" + parser.hooks.evaluateIdentifier.for("module.hot").tap( + "CommonJsPlugin", + evaluateToIdentifier("module.hot", "module", () => ["hot"], null) ); - if (runtimeModules) { - const xor = new StringXor(); - for (const m of runtimeModules) { - xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); - } - xor.updateHash(hash); - } - const digest = /** @type {string} */ (hash.digest(hashDigest)); - chunk.contentHash.javascript = digest.substr(0, hashDigestLength); - }); - compilation.hooks.additionalTreeRuntimeRequirements.tap( - "JavascriptModulesPlugin", - (chunk, set, { chunkGraph }) => { - if ( - !set.has(RuntimeGlobals.startupNoDefault) && - chunkGraph.hasChunkEntryDependentChunks(chunk) - ) { - set.add(RuntimeGlobals.onChunksLoaded); - set.add(RuntimeGlobals.require); - } - } - ); - compilation.hooks.executeModule.tap( - "JavascriptModulesPlugin", - (options, context) => { - const source = - options.codeGenerationResult.sources.get("javascript"); - if (source === undefined) return; - const { module, moduleObject } = options; - const code = source.source(); - const fn = vm.runInThisContext( - `(function(${module.moduleArgument}, ${module.exportsArgument}, __webpack_require__) {\n${code}\n/**/})`, - { - filename: module.identifier(), - lineOffset: -1 - } - ); - try { - fn.call( - moduleObject.exports, - moduleObject, - moduleObject.exports, - context.__webpack_require__ - ); - } catch (e) { - e.stack += printGeneratedCodeForStack(options.module, code); - throw e; - } - } - ); - compilation.hooks.executeModule.tap( - "JavascriptModulesPlugin", - (options, context) => { - const source = options.codeGenerationResult.sources.get("runtime"); - if (source === undefined) return; - let code = source.source(); - if (typeof code !== "string") code = code.toString(); + new CommonJsImportsParserPlugin(parserOptions).apply(parser); + new CommonJsExportsParserPlugin(compilation.moduleGraph).apply( + parser + ); + }; - const fn = vm.runInThisContext( - `(function(__webpack_require__) {\n${code}\n/**/})`, - { - filename: options.module.identifier(), - lineOffset: -1 - } - ); - try { - fn.call(null, context.__webpack_require__); - } catch (e) { - e.stack += printGeneratedCodeForStack(options.module, code); - throw e; - } - } - ); + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CommonJsPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("CommonJsPlugin", handler); } ); } +} - static getChunkFilenameTemplate(chunk, outputOptions) { - if (chunk.filenameTemplate) { - return chunk.filenameTemplate; - } else if (chunk instanceof HotUpdateChunk) { - return outputOptions.hotUpdateChunkFilename; - } else if (chunk.canBeInitial()) { - return outputOptions.filename; - } else { - return outputOptions.chunkFilename; - } +class HarmonyModuleDecoratorRuntimeModule extends RuntimeModule { + constructor() { + super("harmony module decorator"); } /** - * @param {Module} module the rendered module - * @param {ChunkRenderContext} renderContext options object - * @param {CompilationHooks} hooks hooks - * @param {boolean} factory true: renders as factory method, false: pure module content - * @returns {Source} the newly generated source from rendering + * @returns {string} runtime code */ - renderModule(module, renderContext, hooks, factory) { - const { - chunk, - chunkGraph, - runtimeTemplate, - codeGenerationResults, - strictMode - } = renderContext; - try { - const codeGenResult = codeGenerationResults.get(module, chunk.runtime); - const moduleSource = codeGenResult.sources.get("javascript"); - if (!moduleSource) return null; - if (codeGenResult.data !== undefined) { - const chunkInitFragments = codeGenResult.data.get("chunkInitFragments"); - if (chunkInitFragments) { - for (const i of chunkInitFragments) - renderContext.chunkInitFragments.push(i); - } - } - const moduleSourcePostContent = tryRunOrWebpackError( - () => - hooks.renderModuleContent.call(moduleSource, module, renderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderModuleContent" - ); - let moduleSourcePostContainer; - if (factory) { - const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( - module, - chunk.runtime - ); - const needModule = runtimeRequirements.has(RuntimeGlobals.module); - const needExports = runtimeRequirements.has(RuntimeGlobals.exports); - const needRequire = - runtimeRequirements.has(RuntimeGlobals.require) || - runtimeRequirements.has(RuntimeGlobals.requireScope); - const needThisAsExports = runtimeRequirements.has( - RuntimeGlobals.thisAsExports - ); - const needStrict = module.buildInfo.strict && !strictMode; - const cacheEntry = this._moduleFactoryCache.get( - moduleSourcePostContent - ); - let source; - if ( - cacheEntry && - cacheEntry.needModule === needModule && - cacheEntry.needExports === needExports && - cacheEntry.needRequire === needRequire && - cacheEntry.needThisAsExports === needThisAsExports && - cacheEntry.needStrict === needStrict - ) { - source = cacheEntry.source; - } else { - const factorySource = new ConcatSource(); - const args = []; - if (needExports || needRequire || needModule) - args.push( - needModule - ? module.moduleArgument - : "__unused_webpack_" + module.moduleArgument - ); - if (needExports || needRequire) - args.push( - needExports - ? module.exportsArgument - : "__unused_webpack_" + module.exportsArgument - ); - if (needRequire) args.push("__webpack_require__"); - if (!needThisAsExports && runtimeTemplate.supportsArrowFunction()) { - factorySource.add("/***/ ((" + args.join(", ") + ") => {\n\n"); - } else { - factorySource.add("/***/ (function(" + args.join(", ") + ") {\n\n"); - } - if (needStrict) { - factorySource.add('"use strict";\n'); - } - factorySource.add(moduleSourcePostContent); - factorySource.add("\n\n/***/ })"); - source = new CachedSource(factorySource); - this._moduleFactoryCache.set(moduleSourcePostContent, { - source, - needModule, - needExports, - needRequire, - needThisAsExports, - needStrict - }); - } - moduleSourcePostContainer = tryRunOrWebpackError( - () => hooks.renderModuleContainer.call(source, module, renderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderModuleContainer" - ); - } else { - moduleSourcePostContainer = moduleSourcePostContent; - } - return tryRunOrWebpackError( - () => - hooks.renderModulePackage.call( - moduleSourcePostContainer, - module, - renderContext - ), - "JavascriptModulesPlugin.getCompilationHooks().renderModulePackage" - ); - } catch (e) { - e.module = module; - throw e; - } + generate() { + const { runtimeTemplate } = this.compilation; + return Template.asString([ + `${ + RuntimeGlobals.harmonyModuleDecorator + } = ${runtimeTemplate.basicFunction("module", [ + "module = Object.create(module);", + "if (!module.children) module.children = [];", + "Object.defineProperty(module, 'exports', {", + Template.indent([ + "enumerable: true,", + `set: ${runtimeTemplate.basicFunction("", [ + "throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);" + ])}` + ]), + "});", + "return module;" + ])};` + ]); } +} - /** - * @param {RenderContext} renderContext the render context - * @param {CompilationHooks} hooks hooks - * @returns {Source} the rendered source - */ - renderChunk(renderContext, hooks) { - const { chunk, chunkGraph } = renderContext; - const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( - chunk, - "javascript", - compareModulesByIdentifier - ); - const allModules = modules ? Array.from(modules) : []; - let strictHeader; - let allStrict = renderContext.strictMode; - if (!allStrict && allModules.every(m => m.buildInfo.strict)) { - const strictBailout = hooks.strictRuntimeBailout.call(renderContext); - strictHeader = strictBailout - ? `// runtime can't be in strict mode because ${strictBailout}.\n` - : '"use strict";\n'; - if (!strictBailout) allStrict = true; - } - /** @type {ChunkRenderContext} */ - const chunkRenderContext = { - ...renderContext, - chunkInitFragments: [], - strictMode: allStrict - }; - const moduleSources = - Template.renderChunkModules(chunkRenderContext, allModules, module => - this.renderModule(module, chunkRenderContext, hooks, true) - ) || new RawSource("{}"); - let source = tryRunOrWebpackError( - () => hooks.renderChunk.call(moduleSources, chunkRenderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderChunk" - ); - source = tryRunOrWebpackError( - () => hooks.renderContent.call(source, chunkRenderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderContent" - ); - if (!source) { - throw new Error( - "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something" - ); - } - source = InitFragment.addToSource( - source, - chunkRenderContext.chunkInitFragments, - chunkRenderContext - ); - source = tryRunOrWebpackError( - () => hooks.render.call(source, chunkRenderContext), - "JavascriptModulesPlugin.getCompilationHooks().render" - ); - if (!source) { - throw new Error( - "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something" - ); - } - chunk.rendered = true; - return strictHeader - ? new ConcatSource(strictHeader, source, ";") - : renderContext.runtimeTemplate.isModule() - ? source - : new ConcatSource(source, ";"); +class NodeModuleDecoratorRuntimeModule extends RuntimeModule { + constructor() { + super("node module decorator"); } /** - * @param {MainRenderContext} renderContext options object - * @param {CompilationHooks} hooks hooks - * @param {Compilation} compilation the compilation - * @returns {Source} the newly generated source from rendering + * @returns {string} runtime code */ - renderMain(renderContext, hooks, compilation) { - const { chunk, chunkGraph, runtimeTemplate } = renderContext; + generate() { + const { runtimeTemplate } = this.compilation; + return Template.asString([ + `${RuntimeGlobals.nodeModuleDecorator} = ${runtimeTemplate.basicFunction( + "module", + [ + "module.paths = [];", + "if (!module.children) module.children = [];", + "return module;" + ] + )};` + ]); + } +} - const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); - const iife = runtimeTemplate.isIIFE(); +module.exports = CommonJsPlugin; - const bootstrap = this.renderBootstrap(renderContext, hooks); - const useSourceMap = hooks.useSourceMap.call(chunk, renderContext); - const allModules = Array.from( - chunkGraph.getOrderedChunkModulesIterableBySourceType( - chunk, - "javascript", - compareModulesByIdentifier - ) || [] - ); +/***/ }), - const hasEntryModules = chunkGraph.getNumberOfEntryModules(chunk) > 0; - let inlinedModules; - if (bootstrap.allowInlineStartup && hasEntryModules) { - inlinedModules = new Set(chunkGraph.getChunkEntryModulesIterable(chunk)); - } +/***/ 23962: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - let source = new ConcatSource(); - let prefix; - if (iife) { - if (runtimeTemplate.supportsArrowFunction()) { - source.add("/******/ (() => { // webpackBootstrap\n"); - } else { - source.add("/******/ (function() { // webpackBootstrap\n"); - } - prefix = "/******/ \t"; - } else { - prefix = "/******/ "; - } - let allStrict = renderContext.strictMode; - if (!allStrict && allModules.every(m => m.buildInfo.strict)) { - const strictBailout = hooks.strictRuntimeBailout.call(renderContext); - if (strictBailout) { - source.add( - prefix + - `// runtime can't be in strict mode because ${strictBailout}.\n` - ); - } else { - allStrict = true; - source.add(prefix + '"use strict";\n'); - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {ChunkRenderContext} */ - const chunkRenderContext = { - ...renderContext, - chunkInitFragments: [], - strictMode: allStrict - }; - const chunkModules = Template.renderChunkModules( - chunkRenderContext, - inlinedModules - ? allModules.filter(m => !inlinedModules.has(m)) - : allModules, - module => this.renderModule(module, chunkRenderContext, hooks, true), - prefix - ); - if ( - chunkModules || - runtimeRequirements.has(RuntimeGlobals.moduleFactories) || - runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) || - runtimeRequirements.has(RuntimeGlobals.require) - ) { - source.add(prefix + "var __webpack_modules__ = ("); - source.add(chunkModules || "{}"); - source.add(");\n"); - source.add( - "/************************************************************************/\n" - ); - } - if (bootstrap.header.length > 0) { - const header = Template.asString(bootstrap.header) + "\n"; - source.add( - new PrefixSource( - prefix, - useSourceMap - ? new OriginalSource(header, "webpack/bootstrap") - : new RawSource(header) - ) - ); - source.add( - "/************************************************************************/\n" - ); - } +const makeSerializable = __webpack_require__(33032); +const ContextDependency = __webpack_require__(88101); +const ContextDependencyTemplateAsRequireCall = __webpack_require__(75815); - const runtimeModules = - renderContext.chunkGraph.getChunkRuntimeModulesInOrder(chunk); +class CommonJsRequireContextDependency extends ContextDependency { + constructor(options, range, valueRange, inShorthand) { + super(options); - if (runtimeModules.length > 0) { - source.add( - new PrefixSource( - prefix, - Template.renderRuntimeModules(runtimeModules, chunkRenderContext) - ) - ); - source.add( - "/************************************************************************/\n" - ); - // runtimeRuntimeModules calls codeGeneration - for (const module of runtimeModules) { - compilation.codeGeneratedModules.add(module); - } - } - if (inlinedModules) { - if (bootstrap.beforeStartup.length > 0) { - const beforeStartup = Template.asString(bootstrap.beforeStartup) + "\n"; - source.add( - new PrefixSource( - prefix, - useSourceMap - ? new OriginalSource(beforeStartup, "webpack/before-startup") - : new RawSource(beforeStartup) - ) - ); - } - const lastInlinedModule = last(inlinedModules); - const startupSource = new ConcatSource(); - startupSource.add(`var __webpack_exports__ = {};\n`); - for (const m of inlinedModules) { - const renderedModule = this.renderModule( - m, - chunkRenderContext, - hooks, - false - ); - if (renderedModule) { - const innerStrict = !allStrict && m.buildInfo.strict; - const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( - m, - chunk.runtime - ); - const exports = runtimeRequirements.has(RuntimeGlobals.exports); - const webpackExports = - exports && m.exportsArgument === "__webpack_exports__"; - let iife = innerStrict - ? "it need to be in strict mode." - : inlinedModules.size > 1 - ? // TODO check globals and top-level declarations of other entries and chunk modules - // to make a better decision - "it need to be isolated against other entry modules." - : chunkModules - ? "it need to be isolated against other modules in the chunk." - : exports && !webpackExports - ? `it uses a non-standard name for the exports (${m.exportsArgument}).` - : hooks.embedInRuntimeBailout.call(m, renderContext); - let footer; - if (iife !== undefined) { - startupSource.add( - `// This entry need to be wrapped in an IIFE because ${iife}\n` - ); - const arrow = runtimeTemplate.supportsArrowFunction(); - if (arrow) { - startupSource.add("(() => {\n"); - footer = "\n})();\n\n"; - } else { - startupSource.add("!function() {\n"); - footer = "\n}();\n"; - } - if (innerStrict) startupSource.add('"use strict";\n'); - } else { - footer = "\n"; - } - if (exports) { - if (m !== lastInlinedModule) - startupSource.add(`var ${m.exportsArgument} = {};\n`); - else if (m.exportsArgument !== "__webpack_exports__") - startupSource.add( - `var ${m.exportsArgument} = __webpack_exports__;\n` - ); - } - startupSource.add(renderedModule); - startupSource.add(footer); - } - } - if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) { - startupSource.add( - `__webpack_exports__ = ${RuntimeGlobals.onChunksLoaded}(__webpack_exports__);\n` - ); - } - source.add( - hooks.renderStartup.call(startupSource, lastInlinedModule, { - ...renderContext, - inlined: true - }) - ); - if (bootstrap.afterStartup.length > 0) { - const afterStartup = Template.asString(bootstrap.afterStartup) + "\n"; - source.add( - new PrefixSource( - prefix, - useSourceMap - ? new OriginalSource(afterStartup, "webpack/after-startup") - : new RawSource(afterStartup) - ) - ); - } - } else { - const lastEntryModule = last( - chunkGraph.getChunkEntryModulesIterable(chunk) - ); - const toSource = useSourceMap - ? (content, name) => - new OriginalSource(Template.asString(content), name) - : content => new RawSource(Template.asString(content)); - source.add( - new PrefixSource( - prefix, - new ConcatSource( - toSource(bootstrap.beforeStartup, "webpack/before-startup"), - "\n", - hooks.renderStartup.call( - toSource(bootstrap.startup.concat(""), "webpack/startup"), - lastEntryModule, - { - ...renderContext, - inlined: false - } - ), - toSource(bootstrap.afterStartup, "webpack/after-startup"), - "\n" - ) - ) - ); - } - if ( - hasEntryModules && - runtimeRequirements.has(RuntimeGlobals.returnExportsFromRuntime) - ) { - source.add(`${prefix}return __webpack_exports__;\n`); - } - if (iife) { - source.add("/******/ })()\n"); - } + this.range = range; + this.valueRange = valueRange; + // inShorthand must be serialized by subclasses that use it + this.inShorthand = inShorthand; + } - /** @type {Source} */ - let finalSource = tryRunOrWebpackError( - () => hooks.renderMain.call(source, renderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderMain" - ); - if (!finalSource) { - throw new Error( - "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderMain plugins should return something" - ); - } - finalSource = tryRunOrWebpackError( - () => hooks.renderContent.call(finalSource, renderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderContent" - ); - if (!finalSource) { - throw new Error( - "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something" - ); - } - finalSource = InitFragment.addToSource( - finalSource, - chunkRenderContext.chunkInitFragments, - chunkRenderContext - ); - finalSource = tryRunOrWebpackError( - () => hooks.render.call(finalSource, renderContext), - "JavascriptModulesPlugin.getCompilationHooks().render" - ); - if (!finalSource) { - throw new Error( - "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something" - ); - } - chunk.rendered = true; - return iife ? new ConcatSource(finalSource, ";") : finalSource; + get type() { + return "cjs require context"; + } + + serialize(context) { + const { write } = context; + + write(this.range); + write(this.valueRange); + write(this.inShorthand); + + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + + this.range = read(); + this.valueRange = read(); + this.inShorthand = read(); + + super.deserialize(context); + } +} + +makeSerializable( + CommonJsRequireContextDependency, + "webpack/lib/dependencies/CommonJsRequireContextDependency" +); + +CommonJsRequireContextDependency.Template = + ContextDependencyTemplateAsRequireCall; + +module.exports = CommonJsRequireContextDependency; + + +/***/ }), + +/***/ 21264: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyTemplateAsId = __webpack_require__(80825); + +class CommonJsRequireDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + } + + get type() { + return "cjs require"; + } + + get category() { + return "commonjs"; + } +} + +CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; + +makeSerializable( + CommonJsRequireDependency, + "webpack/lib/dependencies/CommonJsRequireDependency" +); + +module.exports = CommonJsRequireDependency; + + +/***/ }), + +/***/ 52225: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const { equals } = __webpack_require__(84953); +const makeSerializable = __webpack_require__(33032); +const propertyAccess = __webpack_require__(54190); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class CommonJsSelfReferenceDependency extends NullDependency { + constructor(range, base, names, call) { + super(); + this.range = range; + this.base = base; + this.names = names; + this.call = call; + } + + get type() { + return "cjs self exports reference"; + } + + get category() { + return "self"; } /** - * @param {Hash} hash the hash to be updated - * @param {RenderBootstrapContext} renderContext options object - * @param {CompilationHooks} hooks hooks + * @returns {string | null} an identifier to merge equal requests */ - updateHashWithBootstrap(hash, renderContext, hooks) { - const bootstrap = this.renderBootstrap(renderContext, hooks); - for (const key of Object.keys(bootstrap)) { - hash.update(key); - if (Array.isArray(bootstrap[key])) { - for (const line of bootstrap[key]) { - hash.update(line); - } - } else { - hash.update(JSON.stringify(bootstrap[key])); - } - } + getResourceIdentifier() { + return `self`; } /** - * @param {RenderBootstrapContext} renderContext options object - * @param {CompilationHooks} hooks hooks - * @returns {{ header: string[], beforeStartup: string[], startup: string[], afterStartup: string[], allowInlineStartup: boolean }} the generated source of the bootstrap code + * 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 */ - renderBootstrap(renderContext, hooks) { - const { chunkGraph, moduleGraph, chunk, runtimeTemplate } = renderContext; - - const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); - - const requireFunction = runtimeRequirements.has(RuntimeGlobals.require); - const moduleCache = runtimeRequirements.has(RuntimeGlobals.moduleCache); - const moduleFactories = runtimeRequirements.has( - RuntimeGlobals.moduleFactories - ); - const moduleUsed = runtimeRequirements.has(RuntimeGlobals.module); - const requireScopeUsed = runtimeRequirements.has( - RuntimeGlobals.requireScope - ); - const interceptModuleExecution = runtimeRequirements.has( - RuntimeGlobals.interceptModuleExecution - ); + getReferencedExports(moduleGraph, runtime) { + return [this.call ? this.names.slice(0, -1) : this.names]; + } - const useRequire = - requireFunction || interceptModuleExecution || moduleUsed; + serialize(context) { + const { write } = context; + write(this.range); + write(this.base); + write(this.names); + write(this.call); + super.serialize(context); + } - const result = { - header: [], - beforeStartup: [], - startup: [], - afterStartup: [], - allowInlineStartup: true - }; + deserialize(context) { + const { read } = context; + this.range = read(); + this.base = read(); + this.names = read(); + this.call = read(); + super.deserialize(context); + } +} - let { header: buf, startup, beforeStartup, afterStartup } = result; +makeSerializable( + CommonJsSelfReferenceDependency, + "webpack/lib/dependencies/CommonJsSelfReferenceDependency" +); - if (result.allowInlineStartup && moduleFactories) { - startup.push( - "// module factories are used so entry inlining is disabled" - ); - result.allowInlineStartup = false; - } - if (result.allowInlineStartup && moduleCache) { - startup.push("// module cache are used so entry inlining is disabled"); - result.allowInlineStartup = false; +CommonJsSelfReferenceDependency.Template = class CommonJsSelfReferenceDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, + { module, moduleGraph, runtime, runtimeRequirements } + ) { + const dep = /** @type {CommonJsSelfReferenceDependency} */ (dependency); + let used; + if (dep.names.length === 0) { + used = dep.names; + } else { + used = moduleGraph.getExportsInfo(module).getUsedName(dep.names, runtime); } - if (result.allowInlineStartup && interceptModuleExecution) { - startup.push( - "// module execution is intercepted so entry inlining is disabled" + if (!used) { + throw new Error( + "Self-reference dependency has unused export name: This should not happen" ); - result.allowInlineStartup = false; } - if (useRequire || moduleCache) { - buf.push("// The module cache"); - buf.push("var __webpack_module_cache__ = {};"); - buf.push(""); + let base = undefined; + switch (dep.base) { + case "exports": + runtimeRequirements.add(RuntimeGlobals.exports); + base = module.exportsArgument; + break; + case "module.exports": + runtimeRequirements.add(RuntimeGlobals.module); + base = `${module.moduleArgument}.exports`; + break; + case "this": + runtimeRequirements.add(RuntimeGlobals.thisAsExports); + base = "this"; + break; + default: + throw new Error(`Unsupported base ${dep.base}`); } - if (useRequire) { - buf.push("// The require function"); - buf.push(`function __webpack_require__(moduleId) {`); - buf.push(Template.indent(this.renderRequire(renderContext, hooks))); - buf.push("}"); - buf.push(""); - } else if (runtimeRequirements.has(RuntimeGlobals.requireScope)) { - buf.push("// The require scope"); - buf.push("var __webpack_require__ = {};"); - buf.push(""); + if (base === dep.base && equals(used, dep.names)) { + // Nothing has to be changed + // We don't use a replacement for compat reasons + // for plugins that update `module._source` which they + // shouldn't do! + return; } - if ( - moduleFactories || - runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) - ) { - buf.push("// expose the modules object (__webpack_modules__)"); - buf.push(`${RuntimeGlobals.moduleFactories} = __webpack_modules__;`); - buf.push(""); - } + source.replace( + dep.range[0], + dep.range[1] - 1, + `${base}${propertyAccess(used)}` + ); + } +}; - if (moduleCache) { - buf.push("// expose the module cache"); - buf.push(`${RuntimeGlobals.moduleCache} = __webpack_module_cache__;`); - buf.push(""); - } +module.exports = CommonJsSelfReferenceDependency; - if (interceptModuleExecution) { - buf.push("// expose the module execution interceptor"); - buf.push(`${RuntimeGlobals.interceptModuleExecution} = [];`); - buf.push(""); - } - if (!runtimeRequirements.has(RuntimeGlobals.startupNoDefault)) { - if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { - /** @type {string[]} */ - const buf2 = []; - const runtimeRequirements = - chunkGraph.getTreeRuntimeRequirements(chunk); - buf2.push("// Load entry module and return exports"); - let i = chunkGraph.getNumberOfEntryModules(chunk); - for (const [ - entryModule, - entrypoint - ] of chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)) { - const chunks = entrypoint.chunks.filter(c => c !== chunk); - if (result.allowInlineStartup && chunks.length > 0) { - buf2.push( - "// This entry module depends on other loaded chunks and execution need to be delayed" - ); - result.allowInlineStartup = false; - } - if ( - result.allowInlineStartup && - someInIterable( - moduleGraph.getIncomingConnectionsByOriginModule(entryModule), - ([originModule, connections]) => - originModule && - connections.some(c => c.isTargetActive(chunk.runtime)) && - someInIterable( - chunkGraph.getModuleRuntimes(originModule), - runtime => - intersectRuntime(runtime, chunk.runtime) !== undefined - ) - ) - ) { - buf2.push( - "// This entry module is referenced by other modules so it can't be inlined" - ); - result.allowInlineStartup = false; - } - if ( - result.allowInlineStartup && - (!entryModule.buildInfo || - !entryModule.buildInfo.topLevelDeclarations) - ) { - buf2.push( - "// This entry module doesn't tell about it's top-level declarations so it can't be inlined" - ); - result.allowInlineStartup = false; - } - if (result.allowInlineStartup) { - const bailout = hooks.inlineInRuntimeBailout.call( - entryModule, - renderContext - ); - if (bailout !== undefined) { - buf2.push( - `// This entry module can't be inlined because ${bailout}` - ); - result.allowInlineStartup = false; - } - } - i--; - const moduleId = chunkGraph.getModuleId(entryModule); - const entryRuntimeRequirements = - chunkGraph.getModuleRuntimeRequirements(entryModule, chunk.runtime); - let moduleIdExpr = JSON.stringify(moduleId); - if (runtimeRequirements.has(RuntimeGlobals.entryModuleId)) { - moduleIdExpr = `${RuntimeGlobals.entryModuleId} = ${moduleIdExpr}`; - } - if ( - result.allowInlineStartup && - entryRuntimeRequirements.has(RuntimeGlobals.module) - ) { - result.allowInlineStartup = false; - buf2.push( - "// This entry module used 'module' so it can't be inlined" - ); - } - if (chunks.length > 0) { - buf2.push( - `${i === 0 ? "var __webpack_exports__ = " : ""}${ - RuntimeGlobals.onChunksLoaded - }(undefined, ${JSON.stringify( - chunks.map(c => c.id) - )}, ${runtimeTemplate.returningFunction( - `__webpack_require__(${moduleIdExpr})` - )})` - ); - } else if (useRequire) { - buf2.push( - `${ - i === 0 ? "var __webpack_exports__ = " : "" - }__webpack_require__(${moduleIdExpr});` - ); - } else { - if (i === 0) buf2.push("var __webpack_exports__ = {};"); - if (requireScopeUsed) { - buf2.push( - `__webpack_modules__[${moduleIdExpr}](0, ${ - i === 0 ? "__webpack_exports__" : "{}" - }, __webpack_require__);` - ); - } else if (entryRuntimeRequirements.has(RuntimeGlobals.exports)) { - buf2.push( - `__webpack_modules__[${moduleIdExpr}](0, ${ - i === 0 ? "__webpack_exports__" : "{}" - });` - ); - } else { - buf2.push(`__webpack_modules__[${moduleIdExpr}]();`); - } - } - } - if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) { - buf2.push( - `__webpack_exports__ = ${RuntimeGlobals.onChunksLoaded}(__webpack_exports__);` - ); - } - if ( - runtimeRequirements.has(RuntimeGlobals.startup) || - (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) && - runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)) - ) { - result.allowInlineStartup = false; - buf.push("// the startup function"); - buf.push( - `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction("", [ - ...buf2, - "return __webpack_exports__;" - ])};` - ); - buf.push(""); - startup.push("// run startup"); - startup.push( - `var __webpack_exports__ = ${RuntimeGlobals.startup}();` - ); - } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore)) { - buf.push("// the startup function"); - buf.push( - `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` - ); - beforeStartup.push("// run runtime startup"); - beforeStartup.push(`${RuntimeGlobals.startup}();`); - startup.push("// startup"); - startup.push(Template.asString(buf2)); - } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)) { - buf.push("// the startup function"); - buf.push( - `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` - ); - startup.push("// startup"); - startup.push(Template.asString(buf2)); - afterStartup.push("// run runtime startup"); - afterStartup.push(`${RuntimeGlobals.startup}();`); - } else { - startup.push("// startup"); - startup.push(Template.asString(buf2)); +/***/ }), + +/***/ 76911: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/Hash")} Hash */ + +class ConstDependency extends NullDependency { + /** + * @param {string} expression the expression + * @param {number|[number, number]} range the source range + * @param {string[]=} runtimeRequirements runtime requirements + */ + constructor(expression, range, runtimeRequirements) { + super(); + this.expression = expression; + this.range = range; + this.runtimeRequirements = runtimeRequirements + ? new Set(runtimeRequirements) + : null; + this._hashUpdate = undefined; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + let hashUpdate = "" + this.range + "|" + this.expression; + if (this.runtimeRequirements) { + for (const item of this.runtimeRequirements) { + hashUpdate += "|"; + hashUpdate += item; } - } else if ( - runtimeRequirements.has(RuntimeGlobals.startup) || - runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) || - runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter) - ) { - buf.push( - "// the startup function", - "// It's empty as no entry modules are in this chunk", - `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};`, - "" - ); } - } else if ( - runtimeRequirements.has(RuntimeGlobals.startup) || - runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) || - runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter) - ) { - result.allowInlineStartup = false; - buf.push( - "// the startup function", - "// It's empty as some runtime module handles the default behavior", - `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` - ); - startup.push("// run startup"); - startup.push(`var __webpack_exports__ = ${RuntimeGlobals.startup}();`); + this._hashUpdate = hashUpdate; } - return result; + hash.update(this._hashUpdate); } /** - * @param {RenderBootstrapContext} renderContext options object - * @param {CompilationHooks} hooks hooks - * @returns {string} the generated source of the require function + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules */ - renderRequire(renderContext, hooks) { - const { - chunk, - chunkGraph, - runtimeTemplate: { outputOptions } - } = renderContext; - const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); - const moduleExecution = runtimeRequirements.has( - RuntimeGlobals.interceptModuleExecution - ) - ? Template.asString([ - "var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: __webpack_require__ };", - `${RuntimeGlobals.interceptModuleExecution}.forEach(function(handler) { handler(execOptions); });`, - "module = execOptions.module;", - "execOptions.factory.call(module.exports, module, module.exports, execOptions.require);" - ]) - : runtimeRequirements.has(RuntimeGlobals.thisAsExports) - ? Template.asString([ - "__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);" - ]) - : Template.asString([ - "__webpack_modules__[moduleId](module, module.exports, __webpack_require__);" - ]); - const needModuleId = runtimeRequirements.has(RuntimeGlobals.moduleId); - const needModuleLoaded = runtimeRequirements.has( - RuntimeGlobals.moduleLoaded - ); - const content = Template.asString([ - "// Check if module is in cache", - "var cachedModule = __webpack_module_cache__[moduleId];", - "if (cachedModule !== undefined) {", - outputOptions.strictModuleErrorHandling - ? Template.indent([ - "if (cachedModule.error !== undefined) throw cachedModule.error;", - "return cachedModule.exports;" - ]) - : Template.indent("return cachedModule.exports;"), - "}", - "// Create a new module (and put it into the cache)", - "var module = __webpack_module_cache__[moduleId] = {", - Template.indent([ - needModuleId ? "id: moduleId," : "// no module.id needed", - needModuleLoaded ? "loaded: false," : "// no module.loaded needed", - "exports: {}" - ]), - "};", - "", - outputOptions.strictModuleExceptionHandling - ? Template.asString([ - "// Execute the module function", - "var threw = true;", - "try {", - Template.indent([moduleExecution, "threw = false;"]), - "} finally {", - Template.indent([ - "if(threw) delete __webpack_module_cache__[moduleId];" - ]), - "}" - ]) - : outputOptions.strictModuleErrorHandling - ? Template.asString([ - "// Execute the module function", - "try {", - Template.indent(moduleExecution), - "} catch(e) {", - Template.indent(["module.error = e;", "throw e;"]), - "}" - ]) - : Template.asString([ - "// Execute the module function", - moduleExecution - ]), - needModuleLoaded - ? Template.asString([ - "", - "// Flag the module as loaded", - "module.loaded = true;", - "" - ]) - : "", - "// Return the exports of the module", - "return module.exports;" - ]); - return tryRunOrWebpackError( - () => hooks.renderRequire.call(content, renderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderRequire" - ); + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } + + serialize(context) { + const { write } = context; + write(this.expression); + write(this.range); + write(this.runtimeRequirements); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.expression = read(); + this.range = read(); + this.runtimeRequirements = read(); + super.deserialize(context); } } -module.exports = JavascriptModulesPlugin; -module.exports.chunkHasJs = chunkHasJs; +makeSerializable(ConstDependency, "webpack/lib/dependencies/ConstDependency"); + +ConstDependency.Template = class ConstDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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 dep = /** @type {ConstDependency} */ (dependency); + if (dep.runtimeRequirements) { + for (const req of dep.runtimeRequirements) { + templateContext.runtimeRequirements.add(req); + } + } + if (typeof dep.range === "number") { + source.insert(dep.range, dep.expression); + return; + } + + source.replace(dep.range[0], dep.range[1] - 1, dep.expression); + } +}; + +module.exports = ConstDependency; /***/ }), -/***/ 29050: +/***/ 88101: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -91053,3781 +87344,1359 @@ module.exports.chunkHasJs = chunkHasJs; -const { Parser: AcornParser } = __webpack_require__(31988); -const { importAssertions } = __webpack_require__(72617); -const { SyncBailHook, HookMap } = __webpack_require__(6967); -const vm = __webpack_require__(26144); -const Parser = __webpack_require__(11715); -const StackedMap = __webpack_require__(58845); -const binarySearchBounds = __webpack_require__(92229); +const Dependency = __webpack_require__(54912); +const DependencyTemplate = __webpack_require__(5160); +const makeSerializable = __webpack_require__(33032); const memoize = __webpack_require__(78676); -const BasicEvaluatedExpression = __webpack_require__(950); -/** @typedef {import("acorn").Options} AcornOptions */ -/** @typedef {import("estree").ArrayExpression} ArrayExpressionNode */ -/** @typedef {import("estree").BinaryExpression} BinaryExpressionNode */ -/** @typedef {import("estree").BlockStatement} BlockStatementNode */ -/** @typedef {import("estree").SequenceExpression} SequenceExpressionNode */ -/** @typedef {import("estree").CallExpression} CallExpressionNode */ -/** @typedef {import("estree").ClassDeclaration} ClassDeclarationNode */ -/** @typedef {import("estree").ClassExpression} ClassExpressionNode */ -/** @typedef {import("estree").Comment} CommentNode */ -/** @typedef {import("estree").ConditionalExpression} ConditionalExpressionNode */ -/** @typedef {import("estree").Declaration} DeclarationNode */ -/** @typedef {import("estree").PrivateIdentifier} PrivateIdentifierNode */ -/** @typedef {import("estree").PropertyDefinition} PropertyDefinitionNode */ -/** @typedef {import("estree").Expression} ExpressionNode */ -/** @typedef {import("estree").Identifier} IdentifierNode */ -/** @typedef {import("estree").IfStatement} IfStatementNode */ -/** @typedef {import("estree").LabeledStatement} LabeledStatementNode */ -/** @typedef {import("estree").Literal} LiteralNode */ -/** @typedef {import("estree").LogicalExpression} LogicalExpressionNode */ -/** @typedef {import("estree").ChainExpression} ChainExpressionNode */ -/** @typedef {import("estree").MemberExpression} MemberExpressionNode */ -/** @typedef {import("estree").MetaProperty} MetaPropertyNode */ -/** @typedef {import("estree").MethodDefinition} MethodDefinitionNode */ -/** @typedef {import("estree").ModuleDeclaration} ModuleDeclarationNode */ -/** @typedef {import("estree").NewExpression} NewExpressionNode */ -/** @typedef {import("estree").Node} AnyNode */ -/** @typedef {import("estree").Program} ProgramNode */ -/** @typedef {import("estree").Statement} StatementNode */ -/** @typedef {import("estree").ImportDeclaration} ImportDeclarationNode */ -/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclarationNode */ -/** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclarationNode */ -/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclarationNode */ -/** @typedef {import("estree").Super} SuperNode */ -/** @typedef {import("estree").TaggedTemplateExpression} TaggedTemplateExpressionNode */ -/** @typedef {import("estree").TemplateLiteral} TemplateLiteralNode */ -/** @typedef {import("estree").ThisExpression} ThisExpressionNode */ -/** @typedef {import("estree").UnaryExpression} UnaryExpressionNode */ -/** @typedef {import("estree").VariableDeclarator} VariableDeclaratorNode */ -/** @template T @typedef {import("tapable").AsArray} AsArray */ -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ -/** @typedef {{declaredScope: ScopeInfo, freeName: string | true, tagInfo: TagInfo | undefined}} VariableInfoInterface */ -/** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[] }} GetInfoResult */ +/** @typedef {import("../ContextModule").ContextOptions} ContextOptions */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../WebpackError")} WebpackError */ -const EMPTY_ARRAY = []; -const ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = 0b01; -const ALLOWED_MEMBER_TYPES_EXPRESSION = 0b10; -const ALLOWED_MEMBER_TYPES_ALL = 0b11; +const getCriticalDependencyWarning = memoize(() => + __webpack_require__(15427) +); -// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API +/** @typedef {ContextOptions & { request: string }} ContextDependencyOptions */ -const parser = AcornParser.extend(importAssertions); +const regExpToString = r => (r ? r + "" : ""); -class VariableInfo { +class ContextDependency extends Dependency { /** - * @param {ScopeInfo} declaredScope scope in which the variable is declared - * @param {string | true} freeName which free name the variable aliases, or true when none - * @param {TagInfo | undefined} tagInfo info about tags + * @param {ContextDependencyOptions} options options for the context module */ - constructor(declaredScope, freeName, tagInfo) { - this.declaredScope = declaredScope; - this.freeName = freeName; - this.tagInfo = tagInfo; - } -} - -/** @typedef {string | ScopeInfo | VariableInfo} ExportedVariableInfo */ -/** @typedef {LiteralNode | string | null | undefined} ImportSource */ -/** @typedef {Omit & { sourceType: "module" | "script" | "auto", ecmaVersion?: AcornOptions["ecmaVersion"] }} ParseOptions */ - -/** - * @typedef {Object} TagInfo - * @property {any} tag - * @property {any} data - * @property {TagInfo | undefined} next - */ + constructor(options) { + super(); -/** - * @typedef {Object} ScopeInfo - * @property {StackedMap} definitions - * @property {boolean | "arrow"} topLevelScope - * @property {boolean} inShorthand - * @property {boolean} isStrict - * @property {boolean} isAsmJs - * @property {boolean} inTry - */ + this.options = options; + this.userRequest = this.options && this.options.request; + /** @type {false | string} */ + this.critical = false; + this.hadGlobalOrStickyRegExp = false; -const joinRanges = (startRange, endRange) => { - if (!endRange) return startRange; - if (!startRange) return endRange; - return [startRange[0], endRange[1]]; -}; + if ( + this.options && + (this.options.regExp.global || this.options.regExp.sticky) + ) { + this.options = { ...this.options, regExp: null }; + this.hadGlobalOrStickyRegExp = true; + } -const objectAndMembersToName = (object, membersReversed) => { - let name = object; - for (let i = membersReversed.length - 1; i >= 0; i--) { - name = name + "." + membersReversed[i]; + this.request = undefined; + this.range = undefined; + this.valueRange = undefined; + this.inShorthand = undefined; + // TODO refactor this + this.replaces = undefined; } - return name; -}; -const getRootName = expression => { - switch (expression.type) { - case "Identifier": - return expression.name; - case "ThisExpression": - return "this"; - case "MetaProperty": - return `${expression.meta.name}.${expression.property.name}`; - default: - return undefined; + get category() { + return "commonjs"; } -}; - -/** @type {AcornOptions} */ -const defaultParserOptions = { - ranges: true, - locations: true, - ecmaVersion: "latest", - sourceType: "module", - // https://github.com/tc39/proposal-hashbang - allowHashBang: true, - onComment: null -}; - -// regexp to match at least one "magic comment" -const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/); - -const EMPTY_COMMENT_OPTIONS = { - options: null, - errors: null -}; -class JavascriptParser extends Parser { /** - * @param {"module" | "script" | "auto"} sourceType default source type + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module */ - constructor(sourceType = "auto") { - super(); - this.hooks = Object.freeze({ - /** @type {HookMap>} */ - evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ - evaluate: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ - evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ - evaluateDefinedIdentifier: new HookMap( - () => new SyncBailHook(["expression"]) - ), - /** @type {HookMap>} */ - evaluateCallExpressionMember: new HookMap( - () => new SyncBailHook(["expression", "param"]) - ), - /** @type {HookMap>} */ - isPure: new HookMap( - () => new SyncBailHook(["expression", "commentsStartPosition"]) - ), - /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ - preStatement: new SyncBailHook(["statement"]), + couldAffectReferencingModule() { + return true; + } - /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ - blockPreStatement: new SyncBailHook(["declaration"]), - /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ - statement: new SyncBailHook(["statement"]), - /** @type {SyncBailHook<[IfStatementNode], boolean | void>} */ - statementIf: new SyncBailHook(["statement"]), - /** @type {SyncBailHook<[ExpressionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ - classExtendsExpression: new SyncBailHook([ - "expression", - "classDefinition" - ]), - /** @type {SyncBailHook<[MethodDefinitionNode | PropertyDefinitionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ - classBodyElement: new SyncBailHook(["element", "classDefinition"]), - /** @type {SyncBailHook<[ExpressionNode, MethodDefinitionNode | PropertyDefinitionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ - classBodyValue: new SyncBailHook([ - "expression", - "element", - "classDefinition" - ]), - /** @type {HookMap>} */ - label: new HookMap(() => new SyncBailHook(["statement"])), - /** @type {SyncBailHook<[ImportDeclarationNode, ImportSource], boolean | void>} */ - import: new SyncBailHook(["statement", "source"]), - /** @type {SyncBailHook<[ImportDeclarationNode, ImportSource, string, string], boolean | void>} */ - importSpecifier: new SyncBailHook([ - "statement", - "source", - "exportName", - "identifierName" - ]), - /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode], boolean | void>} */ - export: new SyncBailHook(["statement"]), - /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, ImportSource], boolean | void>} */ - exportImport: new SyncBailHook(["statement", "source"]), - /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, DeclarationNode], boolean | void>} */ - exportDeclaration: new SyncBailHook(["statement", "declaration"]), - /** @type {SyncBailHook<[ExportDefaultDeclarationNode, DeclarationNode], boolean | void>} */ - exportExpression: new SyncBailHook(["statement", "declaration"]), - /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, string, string, number | undefined], boolean | void>} */ - exportSpecifier: new SyncBailHook([ - "statement", - "identifierName", - "exportName", - "index" - ]), - /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, ImportSource, string, string, number | undefined], boolean | void>} */ - exportImportSpecifier: new SyncBailHook([ - "statement", - "source", - "identifierName", - "exportName", - "index" - ]), - /** @type {SyncBailHook<[VariableDeclaratorNode, StatementNode], boolean | void>} */ - preDeclarator: new SyncBailHook(["declarator", "statement"]), - /** @type {SyncBailHook<[VariableDeclaratorNode, StatementNode], boolean | void>} */ - declarator: new SyncBailHook(["declarator", "statement"]), - /** @type {HookMap>} */ - varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])), - /** @type {HookMap>} */ - varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])), - /** @type {HookMap>} */ - varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])), - /** @type {HookMap>} */ - varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])), - /** @type {HookMap>} */ - pattern: new HookMap(() => new SyncBailHook(["pattern"])), - /** @type {HookMap>} */ - canRename: new HookMap(() => new SyncBailHook(["initExpression"])), - /** @type {HookMap>} */ - rename: new HookMap(() => new SyncBailHook(["initExpression"])), - /** @type {HookMap>} */ - assign: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ - assignMemberChain: new HookMap( - () => new SyncBailHook(["expression", "members"]) - ), - /** @type {HookMap>} */ - typeof: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ - importCall: new SyncBailHook(["expression"]), - /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ - topLevelAwait: new SyncBailHook(["expression"]), - /** @type {HookMap>} */ - call: new HookMap(() => new SyncBailHook(["expression"])), - /** Something like "a.b()" */ - /** @type {HookMap>} */ - callMemberChain: new HookMap( - () => new SyncBailHook(["expression", "members"]) - ), - /** Something like "a.b().c.d" */ - /** @type {HookMap>} */ - memberChainOfCallMemberChain: new HookMap( - () => - new SyncBailHook([ - "expression", - "calleeMembers", - "callExpression", - "members" - ]) - ), - /** Something like "a.b().c.d()"" */ - /** @type {HookMap>} */ - callMemberChainOfCallMemberChain: new HookMap( - () => - new SyncBailHook([ - "expression", - "calleeMembers", - "innerCallExpression", - "members" - ]) - ), - /** @type {SyncBailHook<[ChainExpressionNode], boolean | void>} */ - optionalChaining: new SyncBailHook(["optionalChaining"]), - /** @type {HookMap>} */ - new: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ - expression: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ - expressionMemberChain: new HookMap( - () => new SyncBailHook(["expression", "members"]) - ), - /** @type {HookMap>} */ - unhandledExpressionMemberChain: new HookMap( - () => new SyncBailHook(["expression", "members"]) - ), - /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ - expressionConditionalOperator: new SyncBailHook(["expression"]), - /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ - expressionLogicalOperator: new SyncBailHook(["expression"]), - /** @type {SyncBailHook<[ProgramNode, CommentNode[]], boolean | void>} */ - program: new SyncBailHook(["ast", "comments"]), - /** @type {SyncBailHook<[ProgramNode, CommentNode[]], boolean | void>} */ - finish: new SyncBailHook(["ast", "comments"]) - }); - this.sourceType = sourceType; - /** @type {ScopeInfo} */ - this.scope = undefined; - /** @type {ParserState} */ - this.state = undefined; - this.comments = undefined; - this.semicolons = undefined; - /** @type {(StatementNode|ExpressionNode)[]} */ - this.statementPath = undefined; - this.prevStatement = undefined; - this.currentTagData = undefined; - this._initializeEvaluating(); + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return ( + `context${this.options.request} ${this.options.recursive} ` + + `${regExpToString(this.options.regExp)} ${regExpToString( + this.options.include + )} ${regExpToString(this.options.exclude)} ` + + `${this.options.mode} ${this.options.chunkName} ` + + `${JSON.stringify(this.options.groupOptions)}` + ); } - _initializeEvaluating() { - this.hooks.evaluate.for("Literal").tap("JavascriptParser", _expr => { - const expr = /** @type {LiteralNode} */ (_expr); + /** + * Returns warnings + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} warnings + */ + getWarnings(moduleGraph) { + let warnings = super.getWarnings(moduleGraph); - switch (typeof expr.value) { - case "number": - return new BasicEvaluatedExpression() - .setNumber(expr.value) - .setRange(expr.range); - case "bigint": - return new BasicEvaluatedExpression() - .setBigInt(expr.value) - .setRange(expr.range); - case "string": - return new BasicEvaluatedExpression() - .setString(expr.value) - .setRange(expr.range); - case "boolean": - return new BasicEvaluatedExpression() - .setBoolean(expr.value) - .setRange(expr.range); - } - if (expr.value === null) { - return new BasicEvaluatedExpression().setNull().setRange(expr.range); - } - if (expr.value instanceof RegExp) { - return new BasicEvaluatedExpression() - .setRegExp(expr.value) - .setRange(expr.range); - } - }); - this.hooks.evaluate.for("NewExpression").tap("JavascriptParser", _expr => { - const expr = /** @type {NewExpressionNode} */ (_expr); - const callee = expr.callee; - if ( - callee.type !== "Identifier" || - callee.name !== "RegExp" || - expr.arguments.length > 2 || - this.getVariableInfo("RegExp") !== "RegExp" - ) - return; + if (this.critical) { + if (!warnings) warnings = []; + const CriticalDependencyWarning = getCriticalDependencyWarning(); + warnings.push(new CriticalDependencyWarning(this.critical)); + } - let regExp, flags; - const arg1 = expr.arguments[0]; + if (this.hadGlobalOrStickyRegExp) { + if (!warnings) warnings = []; + const CriticalDependencyWarning = getCriticalDependencyWarning(); + warnings.push( + new CriticalDependencyWarning( + "Contexts can't use RegExps with the 'g' or 'y' flags." + ) + ); + } - if (arg1) { - if (arg1.type === "SpreadElement") return; + return warnings; + } - const evaluatedRegExp = this.evaluateExpression(arg1); + serialize(context) { + const { write } = context; - if (!evaluatedRegExp) return; + write(this.options); + write(this.userRequest); + write(this.critical); + write(this.hadGlobalOrStickyRegExp); + write(this.request); + write(this.range); + write(this.valueRange); + write(this.prepend); + write(this.replaces); - regExp = evaluatedRegExp.asString(); + super.serialize(context); + } - if (!regExp) return; - } else { - return new BasicEvaluatedExpression() - .setRegExp(new RegExp("")) - .setRange(expr.range); - } + deserialize(context) { + const { read } = context; - const arg2 = expr.arguments[1]; + this.options = read(); + this.userRequest = read(); + this.critical = read(); + this.hadGlobalOrStickyRegExp = read(); + this.request = read(); + this.range = read(); + this.valueRange = read(); + this.prepend = read(); + this.replaces = read(); - if (arg2) { - if (arg2.type === "SpreadElement") return; + super.deserialize(context); + } +} - const evaluatedFlags = this.evaluateExpression(arg2); +makeSerializable( + ContextDependency, + "webpack/lib/dependencies/ContextDependency" +); - if (!evaluatedFlags) return; +ContextDependency.Template = DependencyTemplate; - if (!evaluatedFlags.isUndefined()) { - flags = evaluatedFlags.asString(); +module.exports = ContextDependency; - if ( - flags === undefined || - !BasicEvaluatedExpression.isValidRegExpFlags(flags) - ) - return; - } - } - return new BasicEvaluatedExpression() - .setRegExp(flags ? new RegExp(regExp, flags) : new RegExp(regExp)) - .setRange(expr.range); - }); - this.hooks.evaluate - .for("LogicalExpression") - .tap("JavascriptParser", _expr => { - const expr = /** @type {LogicalExpressionNode} */ (_expr); +/***/ }), - const left = this.evaluateExpression(expr.left); - if (!left) return; - let returnRight = false; - /** @type {boolean|undefined} */ - let allowedRight; - if (expr.operator === "&&") { - const leftAsBool = left.asBool(); - if (leftAsBool === false) return left.setRange(expr.range); - returnRight = leftAsBool === true; - allowedRight = false; - } else if (expr.operator === "||") { - const leftAsBool = left.asBool(); - if (leftAsBool === true) return left.setRange(expr.range); - returnRight = leftAsBool === false; - allowedRight = true; - } else if (expr.operator === "??") { - const leftAsNullish = left.asNullish(); - if (leftAsNullish === false) return left.setRange(expr.range); - if (leftAsNullish !== true) return; - returnRight = true; - } else return; - const right = this.evaluateExpression(expr.right); - if (!right) return; - if (returnRight) { - if (left.couldHaveSideEffects()) right.setSideEffects(); - return right.setRange(expr.range); - } +/***/ 99630: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - const asBool = right.asBool(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (allowedRight === true && asBool === true) { - return new BasicEvaluatedExpression() - .setRange(expr.range) - .setTruthy(); - } else if (allowedRight === false && asBool === false) { - return new BasicEvaluatedExpression().setRange(expr.range).setFalsy(); - } - }); - const valueAsExpression = (value, expr, sideEffects) => { - switch (typeof value) { - case "boolean": - return new BasicEvaluatedExpression() - .setBoolean(value) - .setSideEffects(sideEffects) - .setRange(expr.range); - case "number": - return new BasicEvaluatedExpression() - .setNumber(value) - .setSideEffects(sideEffects) - .setRange(expr.range); - case "bigint": - return new BasicEvaluatedExpression() - .setBigInt(value) - .setSideEffects(sideEffects) - .setRange(expr.range); - case "string": - return new BasicEvaluatedExpression() - .setString(value) - .setSideEffects(sideEffects) - .setRange(expr.range); - } - }; - this.hooks.evaluate - .for("BinaryExpression") - .tap("JavascriptParser", _expr => { - const expr = /** @type {BinaryExpressionNode} */ (_expr); +const { parseResource } = __webpack_require__(82186); - const handleConstOperation = fn => { - const left = this.evaluateExpression(expr.left); - if (!left || !left.isCompileTimeValue()) return; +/** @typedef {import("estree").Node} EsTreeNode */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./ContextDependency")} ContextDependency */ +/** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */ - const right = this.evaluateExpression(expr.right); - if (!right || !right.isCompileTimeValue()) return; +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string + */ +const quoteMeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); +}; - const result = fn( - left.asCompileTimeValue(), - right.asCompileTimeValue() - ); - return valueAsExpression( - result, - expr, - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - }; +const splitContextFromPrefix = prefix => { + const idx = prefix.lastIndexOf("/"); + let context = "."; + if (idx >= 0) { + context = prefix.substr(0, idx); + prefix = `.${prefix.substr(idx)}`; + } + return { + context, + prefix + }; +}; - const isAlwaysDifferent = (a, b) => - (a === true && b === false) || (a === false && b === true); +/** @typedef {Partial>} PartialContextDependencyOptions */ - const handleTemplateStringCompare = (left, right, res, eql) => { - const getPrefix = parts => { - let value = ""; - for (const p of parts) { - const v = p.asString(); - if (v !== undefined) value += v; - else break; - } - return value; - }; - const getSuffix = parts => { - let value = ""; - for (let i = parts.length - 1; i >= 0; i--) { - const v = parts[i].asString(); - if (v !== undefined) value = v + value; - else break; - } - return value; - }; - const leftPrefix = getPrefix(left.parts); - const rightPrefix = getPrefix(right.parts); - const leftSuffix = getSuffix(left.parts); - const rightSuffix = getSuffix(right.parts); - const lenPrefix = Math.min(leftPrefix.length, rightPrefix.length); - const lenSuffix = Math.min(leftSuffix.length, rightSuffix.length); - if ( - leftPrefix.slice(0, lenPrefix) !== - rightPrefix.slice(0, lenPrefix) || - leftSuffix.slice(-lenSuffix) !== rightSuffix.slice(-lenSuffix) - ) { - return res - .setBoolean(!eql) - .setSideEffects( - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - } - }; +/** @typedef {{ new(options: ContextDependencyOptions, range: [number, number], valueRange: [number, number]): ContextDependency }} ContextDependencyConstructor */ - const handleStrictEqualityComparison = eql => { - const left = this.evaluateExpression(expr.left); - if (!left) return; - const right = this.evaluateExpression(expr.right); - if (!right) return; - const res = new BasicEvaluatedExpression(); - res.setRange(expr.range); +/** + * @param {ContextDependencyConstructor} Dep the Dependency class + * @param {[number, number]} range source range + * @param {BasicEvaluatedExpression} param context param + * @param {EsTreeNode} expr expr + * @param {Pick} options options for context creation + * @param {PartialContextDependencyOptions} contextOptions options for the ContextModule + * @param {JavascriptParser} parser the parser + * @returns {ContextDependency} the created Dependency + */ +exports.create = (Dep, range, param, expr, options, contextOptions, parser) => { + if (param.isTemplateString()) { + let prefixRaw = param.quasis[0].string; + let postfixRaw = + param.quasis.length > 1 + ? param.quasis[param.quasis.length - 1].string + : ""; - const leftConst = left.isCompileTimeValue(); - const rightConst = right.isCompileTimeValue(); + const valueRange = param.range; + const { context, prefix } = splitContextFromPrefix(prefixRaw); + const { + path: postfix, + query, + fragment + } = parseResource(postfixRaw, parser); - if (leftConst && rightConst) { - return res - .setBoolean( - eql === - (left.asCompileTimeValue() === right.asCompileTimeValue()) - ) - .setSideEffects( - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - } - - if (left.isArray() && right.isArray()) { - return res - .setBoolean(!eql) - .setSideEffects( - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - } - if (left.isTemplateString() && right.isTemplateString()) { - return handleTemplateStringCompare(left, right, res, eql); - } - - const leftPrimitive = left.isPrimitiveType(); - const rightPrimitive = right.isPrimitiveType(); - - if ( - // Primitive !== Object or - // compile-time object types are never equal to something at runtime - (leftPrimitive === false && - (leftConst || rightPrimitive === true)) || - (rightPrimitive === false && - (rightConst || leftPrimitive === true)) || - // Different nullish or boolish status also means not equal - isAlwaysDifferent(left.asBool(), right.asBool()) || - isAlwaysDifferent(left.asNullish(), right.asNullish()) - ) { - return res - .setBoolean(!eql) - .setSideEffects( - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - } - }; - - const handleAbstractEqualityComparison = eql => { - const left = this.evaluateExpression(expr.left); - if (!left) return; - const right = this.evaluateExpression(expr.right); - if (!right) return; - const res = new BasicEvaluatedExpression(); - res.setRange(expr.range); - - const leftConst = left.isCompileTimeValue(); - const rightConst = right.isCompileTimeValue(); - - if (leftConst && rightConst) { - return res - .setBoolean( - eql === - // eslint-disable-next-line eqeqeq - (left.asCompileTimeValue() == right.asCompileTimeValue()) - ) - .setSideEffects( - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - } + // When there are more than two quasis, the generated RegExp can be more precise + // We join the quasis with the expression regexp + const innerQuasis = param.quasis.slice(1, param.quasis.length - 1); + const innerRegExp = + options.wrappedContextRegExp.source + + innerQuasis + .map(q => quoteMeta(q.string) + options.wrappedContextRegExp.source) + .join(""); - if (left.isArray() && right.isArray()) { - return res - .setBoolean(!eql) - .setSideEffects( - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - } - if (left.isTemplateString() && right.isTemplateString()) { - return handleTemplateStringCompare(left, right, res, eql); - } - }; + // Example: `./context/pre${e}inner${e}inner2${e}post?query#frag` + // context: "./context" + // prefix: "./pre" + // innerQuasis: [BEE("inner"), BEE("inner2")] + // (BEE = BasicEvaluatedExpression) + // postfix: "post" + // query: "?query" + // fragment: "#frag" + // regExp: /^\.\/pre.*inner.*inner2.*post$/ + const regExp = new RegExp( + `^${quoteMeta(prefix)}${innerRegExp}${quoteMeta(postfix)}$` + ); + const dep = new Dep( + { + request: context + query + fragment, + recursive: options.wrappedContextRecursive, + regExp, + mode: "sync", + ...contextOptions + }, + range, + valueRange + ); + dep.loc = expr.loc; + const replaces = []; - if (expr.operator === "+") { - const left = this.evaluateExpression(expr.left); - if (!left) return; - const right = this.evaluateExpression(expr.right); - if (!right) return; - const res = new BasicEvaluatedExpression(); - if (left.isString()) { - if (right.isString()) { - res.setString(left.string + right.string); - } else if (right.isNumber()) { - res.setString(left.string + right.number); - } else if ( - right.isWrapped() && - right.prefix && - right.prefix.isString() - ) { - // "left" + ("prefix" + inner + "postfix") - // => ("leftPrefix" + inner + "postfix") - res.setWrapped( - new BasicEvaluatedExpression() - .setString(left.string + right.prefix.string) - .setRange(joinRanges(left.range, right.prefix.range)), - right.postfix, - right.wrappedInnerExpressions - ); - } else if (right.isWrapped()) { - // "left" + ([null] + inner + "postfix") - // => ("left" + inner + "postfix") - res.setWrapped( - left, - right.postfix, - right.wrappedInnerExpressions - ); - } else { - // "left" + expr - // => ("left" + expr + "") - res.setWrapped(left, null, [right]); - } - } else if (left.isNumber()) { - if (right.isString()) { - res.setString(left.number + right.string); - } else if (right.isNumber()) { - res.setNumber(left.number + right.number); - } else { - return; - } - } else if (left.isBigInt()) { - if (right.isBigInt()) { - res.setBigInt(left.bigint + right.bigint); - } - } else if (left.isWrapped()) { - if (left.postfix && left.postfix.isString() && right.isString()) { - // ("prefix" + inner + "postfix") + "right" - // => ("prefix" + inner + "postfixRight") - res.setWrapped( - left.prefix, - new BasicEvaluatedExpression() - .setString(left.postfix.string + right.string) - .setRange(joinRanges(left.postfix.range, right.range)), - left.wrappedInnerExpressions - ); - } else if ( - left.postfix && - left.postfix.isString() && - right.isNumber() - ) { - // ("prefix" + inner + "postfix") + 123 - // => ("prefix" + inner + "postfix123") - res.setWrapped( - left.prefix, - new BasicEvaluatedExpression() - .setString(left.postfix.string + right.number) - .setRange(joinRanges(left.postfix.range, right.range)), - left.wrappedInnerExpressions - ); - } else if (right.isString()) { - // ("prefix" + inner + [null]) + "right" - // => ("prefix" + inner + "right") - res.setWrapped(left.prefix, right, left.wrappedInnerExpressions); - } else if (right.isNumber()) { - // ("prefix" + inner + [null]) + 123 - // => ("prefix" + inner + "123") - res.setWrapped( - left.prefix, - new BasicEvaluatedExpression() - .setString(right.number + "") - .setRange(right.range), - left.wrappedInnerExpressions - ); - } else if (right.isWrapped()) { - // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2") - // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2") - res.setWrapped( - left.prefix, - right.postfix, - left.wrappedInnerExpressions && - right.wrappedInnerExpressions && - left.wrappedInnerExpressions - .concat(left.postfix ? [left.postfix] : []) - .concat(right.prefix ? [right.prefix] : []) - .concat(right.wrappedInnerExpressions) - ); - } else { - // ("prefix" + inner + postfix) + expr - // => ("prefix" + inner + postfix + expr + [null]) - res.setWrapped( - left.prefix, - null, - left.wrappedInnerExpressions && - left.wrappedInnerExpressions.concat( - left.postfix ? [left.postfix, right] : [right] - ) - ); - } - } else { - if (right.isString()) { - // left + "right" - // => ([null] + left + "right") - res.setWrapped(null, right, [left]); - } else if (right.isWrapped()) { - // left + (prefix + inner + "postfix") - // => ([null] + left + prefix + inner + "postfix") - res.setWrapped( - null, - right.postfix, - right.wrappedInnerExpressions && - (right.prefix ? [left, right.prefix] : [left]).concat( - right.wrappedInnerExpressions - ) - ); - } else { - return; - } - } - if (left.couldHaveSideEffects() || right.couldHaveSideEffects()) - res.setSideEffects(); - res.setRange(expr.range); - return res; - } else if (expr.operator === "-") { - return handleConstOperation((l, r) => l - r); - } else if (expr.operator === "*") { - return handleConstOperation((l, r) => l * r); - } else if (expr.operator === "/") { - return handleConstOperation((l, r) => l / r); - } else if (expr.operator === "**") { - return handleConstOperation((l, r) => l ** r); - } else if (expr.operator === "===") { - return handleStrictEqualityComparison(true); - } else if (expr.operator === "==") { - return handleAbstractEqualityComparison(true); - } else if (expr.operator === "!==") { - return handleStrictEqualityComparison(false); - } else if (expr.operator === "!=") { - return handleAbstractEqualityComparison(false); - } else if (expr.operator === "&") { - return handleConstOperation((l, r) => l & r); - } else if (expr.operator === "|") { - return handleConstOperation((l, r) => l | r); - } else if (expr.operator === "^") { - return handleConstOperation((l, r) => l ^ r); - } else if (expr.operator === ">>>") { - return handleConstOperation((l, r) => l >>> r); - } else if (expr.operator === ">>") { - return handleConstOperation((l, r) => l >> r); - } else if (expr.operator === "<<") { - return handleConstOperation((l, r) => l << r); - } else if (expr.operator === "<") { - return handleConstOperation((l, r) => l < r); - } else if (expr.operator === ">") { - return handleConstOperation((l, r) => l > r); - } else if (expr.operator === "<=") { - return handleConstOperation((l, r) => l <= r); - } else if (expr.operator === ">=") { - return handleConstOperation((l, r) => l >= r); + param.parts.forEach((part, i) => { + if (i % 2 === 0) { + // Quasis or merged quasi + let range = part.range; + let value = part.string; + if (param.templateStringKind === "cooked") { + value = JSON.stringify(value); + value = value.slice(1, value.length - 1); } - }); - this.hooks.evaluate - .for("UnaryExpression") - .tap("JavascriptParser", _expr => { - const expr = /** @type {UnaryExpressionNode} */ (_expr); - - const handleConstOperation = fn => { - const argument = this.evaluateExpression(expr.argument); - if (!argument || !argument.isCompileTimeValue()) return; - const result = fn(argument.asCompileTimeValue()); - return valueAsExpression( - result, - expr, - argument.couldHaveSideEffects() - ); - }; - - if (expr.operator === "typeof") { - switch (expr.argument.type) { - case "Identifier": { - const res = this.callHooksForName( - this.hooks.evaluateTypeof, - expr.argument.name, - expr - ); - if (res !== undefined) return res; - break; - } - case "MetaProperty": { - const res = this.callHooksForName( - this.hooks.evaluateTypeof, - getRootName(expr.argument), - expr - ); - if (res !== undefined) return res; - break; - } - case "MemberExpression": { - const res = this.callHooksForExpression( - this.hooks.evaluateTypeof, - expr.argument, - expr - ); - if (res !== undefined) return res; - break; - } - case "ChainExpression": { - const res = this.callHooksForExpression( - this.hooks.evaluateTypeof, - expr.argument.expression, - expr - ); - if (res !== undefined) return res; - break; - } - case "FunctionExpression": { - return new BasicEvaluatedExpression() - .setString("function") - .setRange(expr.range); - } - } - const arg = this.evaluateExpression(expr.argument); - if (arg.isUnknown()) return; - if (arg.isString()) { - return new BasicEvaluatedExpression() - .setString("string") - .setRange(expr.range); - } - if (arg.isWrapped()) { - return new BasicEvaluatedExpression() - .setString("string") - .setSideEffects() - .setRange(expr.range); - } - if (arg.isUndefined()) { - return new BasicEvaluatedExpression() - .setString("undefined") - .setRange(expr.range); - } - if (arg.isNumber()) { - return new BasicEvaluatedExpression() - .setString("number") - .setRange(expr.range); - } - if (arg.isBigInt()) { - return new BasicEvaluatedExpression() - .setString("bigint") - .setRange(expr.range); - } - if (arg.isBoolean()) { - return new BasicEvaluatedExpression() - .setString("boolean") - .setRange(expr.range); - } - if (arg.isConstArray() || arg.isRegExp() || arg.isNull()) { - return new BasicEvaluatedExpression() - .setString("object") - .setRange(expr.range); - } - if (arg.isArray()) { - return new BasicEvaluatedExpression() - .setString("object") - .setSideEffects(arg.couldHaveSideEffects()) - .setRange(expr.range); - } - } else if (expr.operator === "!") { - const argument = this.evaluateExpression(expr.argument); - if (!argument) return; - const bool = argument.asBool(); - if (typeof bool !== "boolean") return; - return new BasicEvaluatedExpression() - .setBoolean(!bool) - .setSideEffects(argument.couldHaveSideEffects()) - .setRange(expr.range); - } else if (expr.operator === "~") { - return handleConstOperation(v => ~v); - } else if (expr.operator === "+") { - return handleConstOperation(v => +v); - } else if (expr.operator === "-") { - return handleConstOperation(v => -v); + if (i === 0) { + // prefix + value = prefix; + range = [param.range[0], part.range[1]]; + value = + (param.templateStringKind === "cooked" ? "`" : "String.raw`") + + value; + } else if (i === param.parts.length - 1) { + // postfix + value = postfix; + range = [part.range[0], param.range[1]]; + value = value + "`"; + } else if ( + part.expression && + part.expression.type === "TemplateElement" && + part.expression.value.raw === value + ) { + // Shortcut when it's a single quasi and doesn't need to be replaced + return; } - }); - this.hooks.evaluateTypeof.for("undefined").tap("JavascriptParser", expr => { - return new BasicEvaluatedExpression() - .setString("undefined") - .setRange(expr.range); - }); - this.hooks.evaluate.for("Identifier").tap("JavascriptParser", expr => { - if (/** @type {IdentifierNode} */ (expr).name === "undefined") { - return new BasicEvaluatedExpression() - .setUndefined() - .setRange(expr.range); + replaces.push({ + range, + value + }); + } else { + // Expression + parser.walkExpression(part.expression); } }); - /** - * @param {string} exprType expression type name - * @param {function(ExpressionNode): GetInfoResult | undefined} getInfo get info - * @returns {void} - */ - const tapEvaluateWithVariableInfo = (exprType, getInfo) => { - /** @type {ExpressionNode | undefined} */ - let cachedExpression = undefined; - /** @type {GetInfoResult | undefined} */ - let cachedInfo = undefined; - this.hooks.evaluate.for(exprType).tap("JavascriptParser", expr => { - const expression = /** @type {MemberExpressionNode} */ (expr); - const info = getInfo(expr); - if (info !== undefined) { - return this.callHooksForInfoWithFallback( - this.hooks.evaluateIdentifier, - info.name, - name => { - cachedExpression = expression; - cachedInfo = info; - }, - name => { - const hook = this.hooks.evaluateDefinedIdentifier.get(name); - if (hook !== undefined) { - return hook.call(expression); - } - }, - expression - ); - } + dep.replaces = replaces; + dep.critical = + options.wrappedContextCritical && + "a part of the request of a dependency is an expression"; + return dep; + } else if ( + param.isWrapped() && + ((param.prefix && param.prefix.isString()) || + (param.postfix && param.postfix.isString())) + ) { + let prefixRaw = + param.prefix && param.prefix.isString() ? param.prefix.string : ""; + let postfixRaw = + param.postfix && param.postfix.isString() ? param.postfix.string : ""; + const prefixRange = + param.prefix && param.prefix.isString() ? param.prefix.range : null; + const postfixRange = + param.postfix && param.postfix.isString() ? param.postfix.range : null; + const valueRange = param.range; + const { context, prefix } = splitContextFromPrefix(prefixRaw); + const { + path: postfix, + query, + fragment + } = parseResource(postfixRaw, parser); + const regExp = new RegExp( + `^${quoteMeta(prefix)}${options.wrappedContextRegExp.source}${quoteMeta( + postfix + )}$` + ); + const dep = new Dep( + { + request: context + query + fragment, + recursive: options.wrappedContextRecursive, + regExp, + mode: "sync", + ...contextOptions + }, + range, + valueRange + ); + dep.loc = expr.loc; + const replaces = []; + if (prefixRange) { + replaces.push({ + range: prefixRange, + value: JSON.stringify(prefix) }); - this.hooks.evaluate - .for(exprType) - .tap({ name: "JavascriptParser", stage: 100 }, expr => { - const info = cachedExpression === expr ? cachedInfo : getInfo(expr); - if (info !== undefined) { - return new BasicEvaluatedExpression() - .setIdentifier(info.name, info.rootInfo, info.getMembers) - .setRange(expr.range); - } - }); - this.hooks.finish.tap("JavascriptParser", () => { - // Cleanup for GC - cachedExpression = cachedInfo = undefined; + } + if (postfixRange) { + replaces.push({ + range: postfixRange, + value: JSON.stringify(postfix) }); - }; - tapEvaluateWithVariableInfo("Identifier", expr => { - const info = this.getVariableInfo( - /** @type {IdentifierNode} */ (expr).name - ); - if ( - typeof info === "string" || - (info instanceof VariableInfo && typeof info.freeName === "string") - ) { - return { name: info, rootInfo: info, getMembers: () => [] }; - } - }); - tapEvaluateWithVariableInfo("ThisExpression", expr => { - const info = this.getVariableInfo("this"); - if ( - typeof info === "string" || - (info instanceof VariableInfo && typeof info.freeName === "string") - ) { - return { name: info, rootInfo: info, getMembers: () => [] }; + } + dep.replaces = replaces; + dep.critical = + options.wrappedContextCritical && + "a part of the request of a dependency is an expression"; + + if (parser && param.wrappedInnerExpressions) { + for (const part of param.wrappedInnerExpressions) { + if (part.expression) parser.walkExpression(part.expression); } - }); - this.hooks.evaluate.for("MetaProperty").tap("JavascriptParser", expr => { - const metaProperty = /** @type {MetaPropertyNode} */ (expr); + } - return this.callHooksForName( - this.hooks.evaluateIdentifier, - getRootName(expr), - metaProperty - ); - }); - tapEvaluateWithVariableInfo("MemberExpression", expr => - this.getMemberExpressionInfo( - /** @type {MemberExpressionNode} */ (expr), - ALLOWED_MEMBER_TYPES_EXPRESSION - ) + return dep; + } else { + const dep = new Dep( + { + request: options.exprContextRequest, + recursive: options.exprContextRecursive, + regExp: /** @type {RegExp} */ (options.exprContextRegExp), + mode: "sync", + ...contextOptions + }, + range, + param.range ); + dep.loc = expr.loc; + dep.critical = + options.exprContextCritical && + "the request of a dependency is an expression"; - this.hooks.evaluate.for("CallExpression").tap("JavascriptParser", _expr => { - const expr = /** @type {CallExpressionNode} */ (_expr); - if ( - expr.callee.type !== "MemberExpression" || - expr.callee.property.type !== - (expr.callee.computed ? "Literal" : "Identifier") - ) { - return; - } - - // type Super also possible here - const param = this.evaluateExpression( - /** @type {ExpressionNode} */ (expr.callee.object) - ); - if (!param) return; - const property = - expr.callee.property.type === "Literal" - ? `${expr.callee.property.value}` - : expr.callee.property.name; - const hook = this.hooks.evaluateCallExpressionMember.get(property); - if (hook !== undefined) { - return hook.call(expr, param); - } - }); - this.hooks.evaluateCallExpressionMember - .for("indexOf") - .tap("JavascriptParser", (expr, param) => { - if (!param.isString()) return; - if (expr.arguments.length === 0) return; - const [arg1, arg2] = expr.arguments; - if (arg1.type === "SpreadElement") return; - const arg1Eval = this.evaluateExpression(arg1); - if (!arg1Eval.isString()) return; - const arg1Value = arg1Eval.string; + parser.walkExpression(param.expression); - let result; - if (arg2) { - if (arg2.type === "SpreadElement") return; - const arg2Eval = this.evaluateExpression(arg2); - if (!arg2Eval.isNumber()) return; - result = param.string.indexOf(arg1Value, arg2Eval.number); - } else { - result = param.string.indexOf(arg1Value); - } - return new BasicEvaluatedExpression() - .setNumber(result) - .setSideEffects(param.couldHaveSideEffects()) - .setRange(expr.range); - }); - this.hooks.evaluateCallExpressionMember - .for("replace") - .tap("JavascriptParser", (expr, param) => { - if (!param.isString()) return; - if (expr.arguments.length !== 2) return; - if (expr.arguments[0].type === "SpreadElement") return; - if (expr.arguments[1].type === "SpreadElement") return; - let arg1 = this.evaluateExpression(expr.arguments[0]); - let arg2 = this.evaluateExpression(expr.arguments[1]); - if (!arg1.isString() && !arg1.isRegExp()) return; - const arg1Value = arg1.regExp || arg1.string; - if (!arg2.isString()) return; - const arg2Value = arg2.string; - return new BasicEvaluatedExpression() - .setString(param.string.replace(arg1Value, arg2Value)) - .setSideEffects(param.couldHaveSideEffects()) - .setRange(expr.range); - }); - ["substr", "substring", "slice"].forEach(fn => { - this.hooks.evaluateCallExpressionMember - .for(fn) - .tap("JavascriptParser", (expr, param) => { - if (!param.isString()) return; - let arg1; - let result, - str = param.string; - switch (expr.arguments.length) { - case 1: - if (expr.arguments[0].type === "SpreadElement") return; - arg1 = this.evaluateExpression(expr.arguments[0]); - if (!arg1.isNumber()) return; - result = str[fn](arg1.number); - break; - case 2: { - if (expr.arguments[0].type === "SpreadElement") return; - if (expr.arguments[1].type === "SpreadElement") return; - arg1 = this.evaluateExpression(expr.arguments[0]); - const arg2 = this.evaluateExpression(expr.arguments[1]); - if (!arg1.isNumber()) return; - if (!arg2.isNumber()) return; - result = str[fn](arg1.number, arg2.number); - break; - } - default: - return; - } - return new BasicEvaluatedExpression() - .setString(result) - .setSideEffects(param.couldHaveSideEffects()) - .setRange(expr.range); - }); - }); + return dep; + } +}; - /** - * @param {"cooked" | "raw"} kind kind of values to get - * @param {TemplateLiteralNode} templateLiteralExpr TemplateLiteral expr - * @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template - */ - const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => { - /** @type {BasicEvaluatedExpression[]} */ - const quasis = []; - /** @type {BasicEvaluatedExpression[]} */ - const parts = []; - for (let i = 0; i < templateLiteralExpr.quasis.length; i++) { - const quasiExpr = templateLiteralExpr.quasis[i]; - const quasi = quasiExpr.value[kind]; +/***/ }), - if (i > 0) { - const prevExpr = parts[parts.length - 1]; - const expr = this.evaluateExpression( - templateLiteralExpr.expressions[i - 1] - ); - const exprAsString = expr.asString(); - if ( - typeof exprAsString === "string" && - !expr.couldHaveSideEffects() - ) { - // We can merge quasi + expr + quasi when expr - // is a const string +/***/ 76081: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - prevExpr.setString(prevExpr.string + exprAsString + quasi); - prevExpr.setRange([prevExpr.range[0], quasiExpr.range[1]]); - // We unset the expression as it doesn't match to a single expression - prevExpr.setExpression(undefined); - continue; - } - parts.push(expr); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const part = new BasicEvaluatedExpression() - .setString(quasi) - .setRange(quasiExpr.range) - .setExpression(quasiExpr); - quasis.push(part); - parts.push(part); - } - return { - quasis, - parts - }; - }; - this.hooks.evaluate - .for("TemplateLiteral") - .tap("JavascriptParser", _node => { - const node = /** @type {TemplateLiteralNode} */ (_node); - const { quasis, parts } = getSimplifiedTemplateResult("cooked", node); - if (parts.length === 1) { - return parts[0].setRange(node.range); - } - return new BasicEvaluatedExpression() - .setTemplateString(quasis, parts, "cooked") - .setRange(node.range); - }); - this.hooks.evaluate - .for("TaggedTemplateExpression") - .tap("JavascriptParser", _node => { - const node = /** @type {TaggedTemplateExpressionNode} */ (_node); - const tag = this.evaluateExpression(node.tag); +const ContextDependency = __webpack_require__(88101); - if (tag.isIdentifier() && tag.identifier === "String.raw") { - const { quasis, parts } = getSimplifiedTemplateResult( - "raw", - node.quasi - ); - return new BasicEvaluatedExpression() - .setTemplateString(quasis, parts, "raw") - .setRange(node.range); - } - }); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - this.hooks.evaluateCallExpressionMember - .for("concat") - .tap("JavascriptParser", (expr, param) => { - if (!param.isString() && !param.isWrapped()) return; +class ContextDependencyTemplateAsId extends ContextDependency.Template { + /** + * @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, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ContextDependency} */ (dependency); + const moduleExports = runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + weak: dep.weak, + runtimeRequirements + }); - let stringSuffix = null; - let hasUnknownParams = false; - const innerExpressions = []; - for (let i = expr.arguments.length - 1; i >= 0; i--) { - const arg = expr.arguments[i]; - if (arg.type === "SpreadElement") return; - const argExpr = this.evaluateExpression(arg); - if ( - hasUnknownParams || - (!argExpr.isString() && !argExpr.isNumber()) - ) { - hasUnknownParams = true; - innerExpressions.push(argExpr); - continue; + if (moduleGraph.getModule(dep)) { + if (dep.valueRange) { + if (Array.isArray(dep.replaces)) { + for (let i = 0; i < dep.replaces.length; i++) { + const rep = dep.replaces[i]; + source.replace(rep.range[0], rep.range[1] - 1, rep.value); } - - const value = argExpr.isString() - ? argExpr.string - : "" + argExpr.number; - - const newString = value + (stringSuffix ? stringSuffix.string : ""); - const newRange = [ - argExpr.range[0], - (stringSuffix || argExpr).range[1] - ]; - stringSuffix = new BasicEvaluatedExpression() - .setString(newString) - .setSideEffects( - (stringSuffix && stringSuffix.couldHaveSideEffects()) || - argExpr.couldHaveSideEffects() - ) - .setRange(newRange); } + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `${moduleExports}.resolve(` + ); + } else { + source.replace( + dep.range[0], + dep.range[1] - 1, + `${moduleExports}.resolve` + ); + } + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } +} +module.exports = ContextDependencyTemplateAsId; - if (hasUnknownParams) { - const prefix = param.isString() ? param : param.prefix; - const inner = - param.isWrapped() && param.wrappedInnerExpressions - ? param.wrappedInnerExpressions.concat(innerExpressions.reverse()) - : innerExpressions.reverse(); - return new BasicEvaluatedExpression() - .setWrapped(prefix, stringSuffix, inner) - .setRange(expr.range); - } else if (param.isWrapped()) { - const postfix = stringSuffix || param.postfix; - const inner = param.wrappedInnerExpressions - ? param.wrappedInnerExpressions.concat(innerExpressions.reverse()) - : innerExpressions.reverse(); - return new BasicEvaluatedExpression() - .setWrapped(param.prefix, postfix, inner) - .setRange(expr.range); - } else { - const newString = - param.string + (stringSuffix ? stringSuffix.string : ""); - return new BasicEvaluatedExpression() - .setString(newString) - .setSideEffects( - (stringSuffix && stringSuffix.couldHaveSideEffects()) || - param.couldHaveSideEffects() - ) - .setRange(expr.range); - } - }); - this.hooks.evaluateCallExpressionMember - .for("split") - .tap("JavascriptParser", (expr, param) => { - if (!param.isString()) return; - if (expr.arguments.length !== 1) return; - if (expr.arguments[0].type === "SpreadElement") return; - let result; - const arg = this.evaluateExpression(expr.arguments[0]); - if (arg.isString()) { - result = param.string.split(arg.string); - } else if (arg.isRegExp()) { - result = param.string.split(arg.regExp); - } else { - return; - } - return new BasicEvaluatedExpression() - .setArray(result) - .setSideEffects(param.couldHaveSideEffects()) - .setRange(expr.range); - }); - this.hooks.evaluate - .for("ConditionalExpression") - .tap("JavascriptParser", _expr => { - const expr = /** @type {ConditionalExpressionNode} */ (_expr); - const condition = this.evaluateExpression(expr.test); - const conditionValue = condition.asBool(); - let res; - if (conditionValue === undefined) { - const consequent = this.evaluateExpression(expr.consequent); - const alternate = this.evaluateExpression(expr.alternate); - if (!consequent || !alternate) return; - res = new BasicEvaluatedExpression(); - if (consequent.isConditional()) { - res.setOptions(consequent.options); - } else { - res.setOptions([consequent]); - } - if (alternate.isConditional()) { - res.addOptions(alternate.options); - } else { - res.addOptions([alternate]); - } - } else { - res = this.evaluateExpression( - conditionValue ? expr.consequent : expr.alternate - ); - if (condition.couldHaveSideEffects()) res.setSideEffects(); - } - res.setRange(expr.range); - return res; - }); - this.hooks.evaluate - .for("ArrayExpression") - .tap("JavascriptParser", _expr => { - const expr = /** @type {ArrayExpressionNode} */ (_expr); +/***/ }), - const items = expr.elements.map(element => { - return ( - element !== null && - element.type !== "SpreadElement" && - this.evaluateExpression(element) - ); - }); - if (!items.every(Boolean)) return; - return new BasicEvaluatedExpression() - .setItems(items) - .setRange(expr.range); - }); - this.hooks.evaluate - .for("ChainExpression") - .tap("JavascriptParser", _expr => { - const expr = /** @type {ChainExpressionNode} */ (_expr); - /** @type {ExpressionNode[]} */ - const optionalExpressionsStack = []; - /** @type {ExpressionNode|SuperNode} */ - let next = expr.expression; +/***/ 75815: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - 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; - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - while (optionalExpressionsStack.length > 0) { - const expression = optionalExpressionsStack.pop(); - const evaluated = this.evaluateExpression(expression); - if (evaluated && evaluated.asNullish()) { - return evaluated.setRange(_expr.range); - } - } - return this.evaluateExpression(expr.expression); - }); - } - getRenameIdentifier(expr) { - const result = this.evaluateExpression(expr); - if (result && result.isIdentifier()) { - return result.identifier; - } - } +const ContextDependency = __webpack_require__(88101); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +class ContextDependencyTemplateAsRequireCall extends ContextDependency.Template { /** - * @param {ClassExpressionNode | ClassDeclarationNode} classy a class node + * @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} */ - walkClass(classy) { - if (classy.superClass) { - if (!this.hooks.classExtendsExpression.call(classy.superClass, classy)) { - this.walkExpression(classy.superClass); - } + apply( + dependency, + source, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ContextDependency} */ (dependency); + let moduleExports = runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + runtimeRequirements + }); + + if (dep.inShorthand) { + moduleExports = `${dep.inShorthand}: ${moduleExports}`; } - if (classy.body && classy.body.type === "ClassBody") { - for (const classElement of /** @type {TODO} */ (classy.body.body)) { - if (!this.hooks.classBodyElement.call(classElement, classy)) { - if (classElement.computed && classElement.key) { - this.walkExpression(classElement.key); - } - if (classElement.value) { - if ( - !this.hooks.classBodyValue.call( - classElement.value, - classElement, - classy - ) - ) { - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = false; - this.walkExpression(classElement.value); - this.scope.topLevelScope = wasTopLevel; - } + if (moduleGraph.getModule(dep)) { + if (dep.valueRange) { + if (Array.isArray(dep.replaces)) { + for (let i = 0; i < dep.replaces.length; i++) { + const rep = dep.replaces[i]; + source.replace(rep.range[0], rep.range[1] - 1, rep.value); } } + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `${moduleExports}(` + ); + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); } + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); } } +} +module.exports = ContextDependencyTemplateAsRequireCall; - // Pre walking iterates the scope for variable declarations - preWalkStatements(statements) { - for (let index = 0, len = statements.length; index < len; index++) { - const statement = statements[index]; - this.preWalkStatement(statement); - } - } - // Block pre walking iterates the scope for block variable declarations - blockPreWalkStatements(statements) { - for (let index = 0, len = statements.length; index < len; index++) { - const statement = statements[index]; - this.blockPreWalkStatement(statement); - } - } +/***/ }), - // Walking iterates the statements and expressions and processes them - walkStatements(statements) { - for (let index = 0, len = statements.length; index < len; index++) { - const statement = statements[index]; - this.walkStatement(statement); - } - } +/***/ 58477: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - preWalkStatement(statement) { - this.statementPath.push(statement); - if (this.hooks.preStatement.call(statement)) { - this.prevStatement = this.statementPath.pop(); - return; - } - switch (statement.type) { - case "BlockStatement": - this.preWalkBlockStatement(statement); - break; - case "DoWhileStatement": - this.preWalkDoWhileStatement(statement); - break; - case "ForInStatement": - this.preWalkForInStatement(statement); - break; - case "ForOfStatement": - this.preWalkForOfStatement(statement); - break; - case "ForStatement": - this.preWalkForStatement(statement); - break; - case "FunctionDeclaration": - this.preWalkFunctionDeclaration(statement); - break; - case "IfStatement": - this.preWalkIfStatement(statement); - break; - case "LabeledStatement": - this.preWalkLabeledStatement(statement); - break; - case "SwitchStatement": - this.preWalkSwitchStatement(statement); - break; - case "TryStatement": - this.preWalkTryStatement(statement); - break; - case "VariableDeclaration": - this.preWalkVariableDeclaration(statement); - break; - case "WhileStatement": - this.preWalkWhileStatement(statement); - break; - case "WithStatement": - this.preWalkWithStatement(statement); - break; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const Dependency = __webpack_require__(54912); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); + +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class ContextElementDependency extends ModuleDependency { + constructor(request, userRequest, typePrefix, category, referencedExports) { + super(request); + this.referencedExports = referencedExports; + this._typePrefix = typePrefix; + this._category = category; + + if (userRequest) { + this.userRequest = userRequest; } - this.prevStatement = this.statementPath.pop(); } - blockPreWalkStatement(statement) { - this.statementPath.push(statement); - if (this.hooks.blockPreStatement.call(statement)) { - this.prevStatement = this.statementPath.pop(); - return; - } - switch (statement.type) { - case "ImportDeclaration": - this.blockPreWalkImportDeclaration(statement); - break; - case "ExportAllDeclaration": - this.blockPreWalkExportAllDeclaration(statement); - break; - case "ExportDefaultDeclaration": - this.blockPreWalkExportDefaultDeclaration(statement); - break; - case "ExportNamedDeclaration": - this.blockPreWalkExportNamedDeclaration(statement); - break; - case "VariableDeclaration": - this.blockPreWalkVariableDeclaration(statement); - break; - case "ClassDeclaration": - this.blockPreWalkClassDeclaration(statement); - break; + get type() { + if (this._typePrefix) { + return `${this._typePrefix} context element`; } - this.prevStatement = this.statementPath.pop(); + + return "context element"; } - walkStatement(statement) { - this.statementPath.push(statement); - if (this.hooks.statement.call(statement) !== undefined) { - this.prevStatement = this.statementPath.pop(); - return; - } - switch (statement.type) { - case "BlockStatement": - this.walkBlockStatement(statement); - break; - case "ClassDeclaration": - this.walkClassDeclaration(statement); - break; - case "DoWhileStatement": - this.walkDoWhileStatement(statement); - break; - case "ExportDefaultDeclaration": - this.walkExportDefaultDeclaration(statement); - break; - case "ExportNamedDeclaration": - this.walkExportNamedDeclaration(statement); - break; - case "ExpressionStatement": - this.walkExpressionStatement(statement); - break; - case "ForInStatement": - this.walkForInStatement(statement); - break; - case "ForOfStatement": - this.walkForOfStatement(statement); - break; - case "ForStatement": - this.walkForStatement(statement); - break; - case "FunctionDeclaration": - this.walkFunctionDeclaration(statement); - break; - case "IfStatement": - this.walkIfStatement(statement); - break; - case "LabeledStatement": - this.walkLabeledStatement(statement); - break; - case "ReturnStatement": - this.walkReturnStatement(statement); - break; - case "SwitchStatement": - this.walkSwitchStatement(statement); - break; - case "ThrowStatement": - this.walkThrowStatement(statement); - break; - case "TryStatement": - this.walkTryStatement(statement); - break; - case "VariableDeclaration": - this.walkVariableDeclaration(statement); - break; - case "WhileStatement": - this.walkWhileStatement(statement); - break; - case "WithStatement": - this.walkWithStatement(statement); - break; - } - this.prevStatement = this.statementPath.pop(); + get category() { + return this._category; } /** - * Walks a statements that is nested within a parent statement - * and can potentially be a non-block statement. - * This enforces the nested statement to never be in ASI position. - * @param {StatementNode} statement the nested statement - * @returns {void} + * 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 */ - walkNestedStatement(statement) { - this.prevStatement = undefined; - this.walkStatement(statement); + getReferencedExports(moduleGraph, runtime) { + return this.referencedExports + ? this.referencedExports.map(e => ({ + name: e, + canMangle: false + })) + : Dependency.EXPORTS_OBJECT_REFERENCED; } - // Real Statements - preWalkBlockStatement(statement) { - this.preWalkStatements(statement.body); + serialize(context) { + context.write(this.referencedExports); + super.serialize(context); } - walkBlockStatement(statement) { - this.inBlockScope(() => { - const body = statement.body; - const prev = this.prevStatement; - this.blockPreWalkStatements(body); - this.prevStatement = prev; - this.walkStatements(body); - }); + deserialize(context) { + this.referencedExports = context.read(); + super.deserialize(context); } +} - walkExpressionStatement(statement) { - this.walkExpression(statement.expression); - } +makeSerializable( + ContextElementDependency, + "webpack/lib/dependencies/ContextElementDependency" +); - preWalkIfStatement(statement) { - this.preWalkStatement(statement.consequent); - if (statement.alternate) { - this.preWalkStatement(statement.alternate); - } - } +module.exports = ContextElementDependency; - walkIfStatement(statement) { - const result = this.hooks.statementIf.call(statement); - if (result === undefined) { - this.walkExpression(statement.test); - this.walkNestedStatement(statement.consequent); - if (statement.alternate) { - this.walkNestedStatement(statement.alternate); - } - } else { - if (result) { - this.walkNestedStatement(statement.consequent); - } else if (statement.alternate) { - this.walkNestedStatement(statement.alternate); - } - } - } - preWalkLabeledStatement(statement) { - this.preWalkStatement(statement.body); - } +/***/ }), - walkLabeledStatement(statement) { - const hook = this.hooks.label.get(statement.label.name); - if (hook !== undefined) { - const result = hook.call(statement); - if (result === true) return; - } - this.walkNestedStatement(statement.body); - } +/***/ 79062: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - preWalkWithStatement(statement) { - this.preWalkStatement(statement.body); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - walkWithStatement(statement) { - this.walkExpression(statement.object); - this.walkNestedStatement(statement.body); - } - preWalkSwitchStatement(statement) { - this.preWalkSwitchCases(statement.cases); - } - walkSwitchStatement(statement) { - this.walkExpression(statement.discriminant); - this.walkSwitchCases(statement.cases); - } +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); - walkTerminatingStatement(statement) { - if (statement.argument) this.walkExpression(statement.argument); - } +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - walkReturnStatement(statement) { - this.walkTerminatingStatement(statement); +class CreateScriptUrlDependency extends NullDependency { + /** + * @param {[number, number]} range range + */ + constructor(range) { + super(); + this.range = range; } - walkThrowStatement(statement) { - this.walkTerminatingStatement(statement); + get type() { + return "create script url"; } - preWalkTryStatement(statement) { - this.preWalkStatement(statement.block); - if (statement.handler) this.preWalkCatchClause(statement.handler); - if (statement.finializer) this.preWalkStatement(statement.finializer); + serialize(context) { + const { write } = context; + write(this.range); + super.serialize(context); } - walkTryStatement(statement) { - if (this.scope.inTry) { - this.walkStatement(statement.block); - } else { - this.scope.inTry = true; - this.walkStatement(statement.block); - this.scope.inTry = false; - } - if (statement.handler) this.walkCatchClause(statement.handler); - if (statement.finalizer) this.walkStatement(statement.finalizer); + deserialize(context) { + const { read } = context; + this.range = read(); + super.deserialize(context); } +} - preWalkWhileStatement(statement) { - this.preWalkStatement(statement.body); - } +CreateScriptUrlDependency.Template = class CreateScriptUrlDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, { runtimeRequirements }) { + const dep = /** @type {CreateScriptUrlDependency} */ (dependency); - walkWhileStatement(statement) { - this.walkExpression(statement.test); - this.walkNestedStatement(statement.body); - } + runtimeRequirements.add(RuntimeGlobals.createScriptUrl); - preWalkDoWhileStatement(statement) { - this.preWalkStatement(statement.body); + source.insert(dep.range[0], `${RuntimeGlobals.createScriptUrl}(`); + source.insert(dep.range[1], ")"); } +}; - walkDoWhileStatement(statement) { - this.walkNestedStatement(statement.body); - this.walkExpression(statement.test); - } +makeSerializable( + CreateScriptUrlDependency, + "webpack/lib/dependencies/CreateScriptUrlDependency" +); - preWalkForStatement(statement) { - if (statement.init) { - if (statement.init.type === "VariableDeclaration") { - this.preWalkStatement(statement.init); - } - } - this.preWalkStatement(statement.body); - } +module.exports = CreateScriptUrlDependency; - walkForStatement(statement) { - this.inBlockScope(() => { - if (statement.init) { - if (statement.init.type === "VariableDeclaration") { - this.blockPreWalkVariableDeclaration(statement.init); - this.prevStatement = undefined; - this.walkStatement(statement.init); - } else { - this.walkExpression(statement.init); - } - } - if (statement.test) { - this.walkExpression(statement.test); - } - if (statement.update) { - this.walkExpression(statement.update); - } - const body = statement.body; - if (body.type === "BlockStatement") { - // no need to add additional scope - const prev = this.prevStatement; - this.blockPreWalkStatements(body.body); - this.prevStatement = prev; - this.walkStatements(body.body); - } else { - this.walkNestedStatement(body); - } - }); - } - preWalkForInStatement(statement) { - if (statement.left.type === "VariableDeclaration") { - this.preWalkVariableDeclaration(statement.left); - } - this.preWalkStatement(statement.body); - } +/***/ }), - walkForInStatement(statement) { - this.inBlockScope(() => { - if (statement.left.type === "VariableDeclaration") { - this.blockPreWalkVariableDeclaration(statement.left); - this.walkVariableDeclaration(statement.left); - } else { - this.walkPattern(statement.left); - } - this.walkExpression(statement.right); - const body = statement.body; - if (body.type === "BlockStatement") { - // no need to add additional scope - const prev = this.prevStatement; - this.blockPreWalkStatements(body.body); - this.prevStatement = prev; - this.walkStatements(body.body); - } else { - this.walkNestedStatement(body); - } - }); - } +/***/ 15427: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - preWalkForOfStatement(statement) { - if (statement.await && this.scope.topLevelScope === true) { - this.hooks.topLevelAwait.call(statement); - } - if (statement.left.type === "VariableDeclaration") { - this.preWalkVariableDeclaration(statement.left); - } - this.preWalkStatement(statement.body); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - walkForOfStatement(statement) { - this.inBlockScope(() => { - if (statement.left.type === "VariableDeclaration") { - this.blockPreWalkVariableDeclaration(statement.left); - this.walkVariableDeclaration(statement.left); - } else { - this.walkPattern(statement.left); - } - this.walkExpression(statement.right); - const body = statement.body; - if (body.type === "BlockStatement") { - // no need to add additional scope - const prev = this.prevStatement; - this.blockPreWalkStatements(body.body); - this.prevStatement = prev; - this.walkStatements(body.body); - } else { - this.walkNestedStatement(body); - } - }); - } - // Declarations - preWalkFunctionDeclaration(statement) { - if (statement.id) { - this.defineVariable(statement.id.name); - } - } - walkFunctionDeclaration(statement) { - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = false; - this.inFunctionScope(true, statement.params, () => { - for (const param of statement.params) { - this.walkPattern(param); - } - if (statement.body.type === "BlockStatement") { - this.detectMode(statement.body.body); - const prev = this.prevStatement; - this.preWalkStatement(statement.body); - this.prevStatement = prev; - this.walkStatement(statement.body); - } else { - this.walkExpression(statement.body); - } - }); - this.scope.topLevelScope = wasTopLevel; - } +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); - blockPreWalkImportDeclaration(statement) { - const source = statement.source.value; - this.hooks.import.call(statement, source); - for (const specifier of statement.specifiers) { - const name = specifier.local.name; - switch (specifier.type) { - case "ImportDefaultSpecifier": - if ( - !this.hooks.importSpecifier.call(statement, source, "default", name) - ) { - this.defineVariable(name); - } - break; - case "ImportSpecifier": - if ( - !this.hooks.importSpecifier.call( - statement, - source, - specifier.imported.name, - name - ) - ) { - this.defineVariable(name); - } - break; - case "ImportNamespaceSpecifier": - if (!this.hooks.importSpecifier.call(statement, source, null, name)) { - this.defineVariable(name); - } - break; - default: - this.defineVariable(name); - } - } - } +class CriticalDependencyWarning extends WebpackError { + constructor(message) { + super(); - enterDeclaration(declaration, onIdent) { - switch (declaration.type) { - case "VariableDeclaration": - for (const declarator of declaration.declarations) { - switch (declarator.type) { - case "VariableDeclarator": { - this.enterPattern(declarator.id, onIdent); - break; - } - } - } - break; - case "FunctionDeclaration": - this.enterPattern(declaration.id, onIdent); - break; - case "ClassDeclaration": - this.enterPattern(declaration.id, onIdent); - break; - } + this.name = "CriticalDependencyWarning"; + this.message = "Critical dependency: " + message; } +} - blockPreWalkExportNamedDeclaration(statement) { - let source; - if (statement.source) { - source = statement.source.value; - this.hooks.exportImport.call(statement, source); - } else { - this.hooks.export.call(statement); - } - if (statement.declaration) { - if ( - !this.hooks.exportDeclaration.call(statement, statement.declaration) - ) { - const prev = this.prevStatement; - this.preWalkStatement(statement.declaration); - this.prevStatement = prev; - this.blockPreWalkStatement(statement.declaration); - let index = 0; - this.enterDeclaration(statement.declaration, def => { - this.hooks.exportSpecifier.call(statement, def, def, index++); - }); - } - } - if (statement.specifiers) { - for ( - let specifierIndex = 0; - specifierIndex < statement.specifiers.length; - specifierIndex++ - ) { - const specifier = statement.specifiers[specifierIndex]; - switch (specifier.type) { - case "ExportSpecifier": { - const name = specifier.exported.name; - if (source) { - this.hooks.exportImportSpecifier.call( - statement, - source, - specifier.local.name, - name, - specifierIndex - ); - } else { - this.hooks.exportSpecifier.call( - statement, - specifier.local.name, - name, - specifierIndex - ); - } - break; - } - } - } - } - } +makeSerializable( + CriticalDependencyWarning, + "webpack/lib/dependencies/CriticalDependencyWarning" +); - walkExportNamedDeclaration(statement) { - if (statement.declaration) { - this.walkStatement(statement.declaration); - } - } +module.exports = CriticalDependencyWarning; - blockPreWalkExportDefaultDeclaration(statement) { - const prev = this.prevStatement; - this.preWalkStatement(statement.declaration); - this.prevStatement = prev; - this.blockPreWalkStatement(statement.declaration); - if ( - statement.declaration.id && - statement.declaration.type !== "FunctionExpression" && - statement.declaration.type !== "ClassExpression" - ) { - this.hooks.exportSpecifier.call( - statement, - statement.declaration.id.name, - "default", - undefined - ); - } - } - walkExportDefaultDeclaration(statement) { - this.hooks.export.call(statement); - if ( - statement.declaration.id && - statement.declaration.type !== "FunctionExpression" && - statement.declaration.type !== "ClassExpression" - ) { - if ( - !this.hooks.exportDeclaration.call(statement, statement.declaration) - ) { - this.walkStatement(statement.declaration); - } - } else { - // Acorn parses `export default function() {}` as `FunctionDeclaration` and - // `export default class {}` as `ClassDeclaration`, both with `id = null`. - // These nodes must be treated as expressions. - if ( - statement.declaration.type === "FunctionDeclaration" || - statement.declaration.type === "ClassDeclaration" - ) { - this.walkStatement(statement.declaration); - } else { - this.walkExpression(statement.declaration); - } - if (!this.hooks.exportExpression.call(statement, statement.declaration)) { - this.hooks.exportSpecifier.call( - statement, - statement.declaration, - "default", - undefined - ); - } - } - } +/***/ }), - blockPreWalkExportAllDeclaration(statement) { - const source = statement.source.value; - const name = statement.exported ? statement.exported.name : null; - this.hooks.exportImport.call(statement, source); - this.hooks.exportImportSpecifier.call(statement, source, null, name, 0); - } +/***/ 76760: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - preWalkVariableDeclaration(statement) { - if (statement.kind !== "var") return; - this._preWalkVariableDeclaration(statement, this.hooks.varDeclarationVar); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - blockPreWalkVariableDeclaration(statement) { - if (statement.kind === "var") return; - const hookMap = - statement.kind === "const" - ? this.hooks.varDeclarationConst - : this.hooks.varDeclarationLet; - this._preWalkVariableDeclaration(statement, hookMap); + + +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ + +class CssExportDependency extends NullDependency { + /** + * @param {string} name name + * @param {string} value value + */ + constructor(name, value) { + super(); + this.name = name; + this.value = value; } - _preWalkVariableDeclaration(statement, hookMap) { - for (const declarator of statement.declarations) { - switch (declarator.type) { - case "VariableDeclarator": { - if (!this.hooks.preDeclarator.call(declarator, statement)) { - this.enterPattern(declarator.id, (name, decl) => { - let hook = hookMap.get(name); - if (hook === undefined || !hook.call(decl)) { - hook = this.hooks.varDeclaration.get(name); - if (hook === undefined || !hook.call(decl)) { - this.defineVariable(name); - } - } - }); - } - break; - } - } - } + get type() { + return "css :export"; } - walkVariableDeclaration(statement) { - for (const declarator of statement.declarations) { - switch (declarator.type) { - case "VariableDeclarator": { - const renameIdentifier = - declarator.init && this.getRenameIdentifier(declarator.init); - if (renameIdentifier && declarator.id.type === "Identifier") { - const hook = this.hooks.canRename.get(renameIdentifier); - if (hook !== undefined && hook.call(declarator.init)) { - // renaming with "var a = b;" - const hook = this.hooks.rename.get(renameIdentifier); - if (hook === undefined || !hook.call(declarator.init)) { - this.setVariable(declarator.id.name, renameIdentifier); - } - break; - } - } - if (!this.hooks.declarator.call(declarator, statement)) { - this.walkPattern(declarator.id); - if (declarator.init) this.walkExpression(declarator.init); - } - break; + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + const name = this.name; + return { + exports: [ + { + name, + canMangle: true } - } - } + ], + dependencies: undefined + }; } - blockPreWalkClassDeclaration(statement) { - if (statement.id) { - this.defineVariable(statement.id.name); - } + serialize(context) { + const { write } = context; + write(this.name); + write(this.value); + super.serialize(context); } - walkClassDeclaration(statement) { - this.walkClass(statement); + deserialize(context) { + const { read } = context; + this.name = read(); + this.value = read(); + super.deserialize(context); } +} - preWalkSwitchCases(switchCases) { - for (let index = 0, len = switchCases.length; index < len; index++) { - const switchCase = switchCases[index]; - this.preWalkStatements(switchCase.consequent); - } +CssExportDependency.Template = class CssExportDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, { cssExports }) { + const dep = /** @type {CssExportDependency} */ (dependency); + cssExports.set(dep.name, dep.value); } +}; - walkSwitchCases(switchCases) { - this.inBlockScope(() => { - const len = switchCases.length; +makeSerializable( + CssExportDependency, + "webpack/lib/dependencies/CssExportDependency" +); - // we need to pre walk all statements first since we can have invalid code - // import A from "module"; - // switch(1) { - // case 1: - // console.log(A); // should fail at runtime - // case 2: - // const A = 1; - // } - for (let index = 0; index < len; index++) { - const switchCase = switchCases[index]; +module.exports = CssExportDependency; - if (switchCase.consequent.length > 0) { - const prev = this.prevStatement; - this.blockPreWalkStatements(switchCase.consequent); - this.prevStatement = prev; - } - } - for (let index = 0; index < len; index++) { - const switchCase = switchCases[index]; +/***/ }), - if (switchCase.test) { - this.walkExpression(switchCase.test); - } - if (switchCase.consequent.length > 0) { - this.walkStatements(switchCase.consequent); - } - } - }); - } +/***/ 90542: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - preWalkCatchClause(catchClause) { - this.preWalkStatement(catchClause.body); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - walkCatchClause(catchClause) { - this.inBlockScope(() => { - // Error binding is optional in catch clause since ECMAScript 2019 - if (catchClause.param !== null) { - this.enterPattern(catchClause.param, ident => { - this.defineVariable(ident); - }); - this.walkPattern(catchClause.param); - } - const prev = this.prevStatement; - this.blockPreWalkStatement(catchClause.body); - this.prevStatement = prev; - this.walkStatement(catchClause.body); - }); - } - walkPattern(pattern) { - switch (pattern.type) { - case "ArrayPattern": - this.walkArrayPattern(pattern); - break; - case "AssignmentPattern": - this.walkAssignmentPattern(pattern); - break; - case "MemberExpression": - this.walkMemberExpression(pattern); - break; - case "ObjectPattern": - this.walkObjectPattern(pattern); - break; - case "RestElement": - this.walkRestElement(pattern); - break; - } - } - walkAssignmentPattern(pattern) { - this.walkExpression(pattern.right); - this.walkPattern(pattern.left); - } +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); - walkObjectPattern(pattern) { - for (let i = 0, len = pattern.properties.length; i < len; i++) { - const prop = pattern.properties[i]; - if (prop) { - if (prop.computed) this.walkExpression(prop.key); - if (prop.value) this.walkPattern(prop.value); - } - } +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class CssImportDependency extends ModuleDependency { + /** + * @param {string} request request + * @param {[number, number]} range range of the argument + * @param {string | undefined} supports list of supports conditions + * @param {string | undefined} media list of media conditions + */ + constructor(request, range, supports, media) { + super(request); + this.range = range; + this.supports = supports; + this.media = media; } - walkArrayPattern(pattern) { - for (let i = 0, len = pattern.elements.length; i < len; i++) { - const element = pattern.elements[i]; - if (element) this.walkPattern(element); - } + get type() { + return "css @import"; } - walkRestElement(pattern) { - this.walkPattern(pattern.argument); + get category() { + return "css-import"; } - walkExpressions(expressions) { - for (const expression of expressions) { - if (expression) { - this.walkExpression(expression); - } - } + /** + * @param {string} context context directory + * @returns {Module} a module + */ + createIgnoredModule(context) { + return null; } +} - walkExpression(expression) { - switch (expression.type) { - case "ArrayExpression": - this.walkArrayExpression(expression); - break; - case "ArrowFunctionExpression": - this.walkArrowFunctionExpression(expression); - break; - case "AssignmentExpression": - this.walkAssignmentExpression(expression); - break; - case "AwaitExpression": - this.walkAwaitExpression(expression); - break; - case "BinaryExpression": - this.walkBinaryExpression(expression); - break; - case "CallExpression": - this.walkCallExpression(expression); - break; - case "ChainExpression": - this.walkChainExpression(expression); - break; - case "ClassExpression": - this.walkClassExpression(expression); - break; - case "ConditionalExpression": - this.walkConditionalExpression(expression); - break; - case "FunctionExpression": - this.walkFunctionExpression(expression); - break; - case "Identifier": - this.walkIdentifier(expression); - break; - case "ImportExpression": - this.walkImportExpression(expression); - break; - case "LogicalExpression": - this.walkLogicalExpression(expression); - break; - case "MetaProperty": - this.walkMetaProperty(expression); - break; - case "MemberExpression": - this.walkMemberExpression(expression); - break; - case "NewExpression": - this.walkNewExpression(expression); - break; - case "ObjectExpression": - this.walkObjectExpression(expression); - break; - case "SequenceExpression": - this.walkSequenceExpression(expression); - break; - case "SpreadElement": - this.walkSpreadElement(expression); - break; - case "TaggedTemplateExpression": - this.walkTaggedTemplateExpression(expression); - break; - case "TemplateLiteral": - this.walkTemplateLiteral(expression); - break; - case "ThisExpression": - this.walkThisExpression(expression); - break; - case "UnaryExpression": - this.walkUnaryExpression(expression); - break; - case "UpdateExpression": - this.walkUpdateExpression(expression); - break; - case "YieldExpression": - this.walkYieldExpression(expression); - break; - } - } - - walkAwaitExpression(expression) { - if (this.scope.topLevelScope === true) - this.hooks.topLevelAwait.call(expression); - this.walkExpression(expression.argument); - } - - walkArrayExpression(expression) { - if (expression.elements) { - this.walkExpressions(expression.elements); - } - } +CssImportDependency.Template = class CssImportDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @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 dep = /** @type {CssImportDependency} */ (dependency); - walkSpreadElement(expression) { - if (expression.argument) { - this.walkExpression(expression.argument); - } + source.replace(dep.range[0], dep.range[1] - 1, ""); } +}; - walkObjectExpression(expression) { - for ( - let propIndex = 0, len = expression.properties.length; - propIndex < len; - propIndex++ - ) { - const prop = expression.properties[propIndex]; - this.walkProperty(prop); - } - } +makeSerializable( + CssImportDependency, + "webpack/lib/dependencies/CssImportDependency" +); - walkProperty(prop) { - if (prop.type === "SpreadElement") { - this.walkExpression(prop.argument); - return; - } - if (prop.computed) { - this.walkExpression(prop.key); - } - if (prop.shorthand && prop.value && prop.value.type === "Identifier") { - this.scope.inShorthand = prop.value.name; - this.walkIdentifier(prop.value); - this.scope.inShorthand = false; - } else { - this.walkExpression(prop.value); - } - } +module.exports = CssImportDependency; - walkFunctionExpression(expression) { - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = false; - const scopeParams = expression.params; - // Add function name in scope for recursive calls - if (expression.id) { - scopeParams.push(expression.id.name); - } +/***/ }), - this.inFunctionScope(true, scopeParams, () => { - for (const param of expression.params) { - this.walkPattern(param); - } - if (expression.body.type === "BlockStatement") { - this.detectMode(expression.body.body); - const prev = this.prevStatement; - this.preWalkStatement(expression.body); - this.prevStatement = prev; - this.walkStatement(expression.body); - } else { - this.walkExpression(expression.body); - } - }); - this.scope.topLevelScope = wasTopLevel; - } +/***/ 92328: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - walkArrowFunctionExpression(expression) { - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = wasTopLevel ? "arrow" : false; - this.inFunctionScope(false, expression.params, () => { - for (const param of expression.params) { - this.walkPattern(param); - } - if (expression.body.type === "BlockStatement") { - this.detectMode(expression.body.body); - const prev = this.prevStatement; - this.preWalkStatement(expression.body); - this.prevStatement = prev; - this.walkStatement(expression.body); - } else { - this.walkExpression(expression.body); - } - }); - this.scope.topLevelScope = wasTopLevel; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - /** - * @param {SequenceExpressionNode} expression the sequence - */ - walkSequenceExpression(expression) { - if (!expression.expressions) return; - // We treat sequence expressions like statements when they are one statement level - // This has some benefits for optimizations that only work on statement level - const currentStatement = this.statementPath[this.statementPath.length - 1]; - if ( - currentStatement === expression || - (currentStatement.type === "ExpressionStatement" && - currentStatement.expression === expression) - ) { - const old = this.statementPath.pop(); - for (const expr of expression.expressions) { - this.statementPath.push(expr); - this.walkExpression(expr); - this.statementPath.pop(); - } - this.statementPath.push(old); - } else { - this.walkExpressions(expression.expressions); - } - } - walkUpdateExpression(expression) { - this.walkExpression(expression.argument); - } - walkUnaryExpression(expression) { - if (expression.operator === "typeof") { - const result = this.callHooksForExpression( - this.hooks.typeof, - expression.argument, - expression - ); - if (result === true) return; - if (expression.argument.type === "ChainExpression") { - const result = this.callHooksForExpression( - this.hooks.typeof, - expression.argument.expression, - expression - ); - if (result === true) return; - } - } - this.walkExpression(expression.argument); - } +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); - walkLeftRightExpression(expression) { - this.walkExpression(expression.left); - this.walkExpression(expression.right); - } +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ - walkBinaryExpression(expression) { - this.walkLeftRightExpression(expression); +class CssLocalIdentifierDependency extends NullDependency { + /** + * @param {string} name name + * @param {[number, number]} range range + * @param {string=} prefix prefix + */ + constructor(name, range, prefix = "") { + super(); + this.name = name; + this.range = range; + this.prefix = prefix; } - walkLogicalExpression(expression) { - const result = this.hooks.expressionLogicalOperator.call(expression); - if (result === undefined) { - this.walkLeftRightExpression(expression); - } else { - if (result) { - this.walkExpression(expression.right); - } - } + get type() { + return "css local identifier"; } - walkAssignmentExpression(expression) { - if (expression.left.type === "Identifier") { - const renameIdentifier = this.getRenameIdentifier(expression.right); - if (renameIdentifier) { - if ( - this.callHooksForInfo( - this.hooks.canRename, - renameIdentifier, - expression.right - ) - ) { - // renaming "a = b;" - if ( - !this.callHooksForInfo( - this.hooks.rename, - renameIdentifier, - expression.right - ) - ) { - this.setVariable( - expression.left.name, - this.getVariableInfo(renameIdentifier) - ); - } - return; - } - } - this.walkExpression(expression.right); - this.enterPattern(expression.left, (name, decl) => { - if (!this.callHooksForName(this.hooks.assign, name, expression)) { - this.walkExpression(expression.left); - } - }); - return; - } - if (expression.left.type.endsWith("Pattern")) { - this.walkExpression(expression.right); - this.enterPattern(expression.left, (name, decl) => { - if (!this.callHooksForName(this.hooks.assign, name, expression)) { - this.defineVariable(name); - } - }); - this.walkPattern(expression.left); - } else if (expression.left.type === "MemberExpression") { - const exprName = this.getMemberExpressionInfo( - expression.left, - ALLOWED_MEMBER_TYPES_EXPRESSION - ); - if (exprName) { - if ( - this.callHooksForInfo( - this.hooks.assignMemberChain, - exprName.rootInfo, - expression, - exprName.getMembers() - ) - ) { - return; + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + const name = this.name; + return { + exports: [ + { + name, + canMangle: true } - } - this.walkExpression(expression.right); - this.walkExpression(expression.left); - } else { - this.walkExpression(expression.right); - this.walkExpression(expression.left); - } - } - - walkConditionalExpression(expression) { - const result = this.hooks.expressionConditionalOperator.call(expression); - if (result === undefined) { - this.walkExpression(expression.test); - this.walkExpression(expression.consequent); - if (expression.alternate) { - this.walkExpression(expression.alternate); - } - } else { - if (result) { - this.walkExpression(expression.consequent); - } else if (expression.alternate) { - this.walkExpression(expression.alternate); - } - } - } - - walkNewExpression(expression) { - const result = this.callHooksForExpression( - this.hooks.new, - expression.callee, - expression - ); - if (result === true) return; - this.walkExpression(expression.callee); - if (expression.arguments) { - this.walkExpressions(expression.arguments); - } - } - - walkYieldExpression(expression) { - if (expression.argument) { - this.walkExpression(expression.argument); - } + ], + dependencies: undefined + }; } - walkTemplateLiteral(expression) { - if (expression.expressions) { - this.walkExpressions(expression.expressions); - } + serialize(context) { + const { write } = context; + write(this.name); + write(this.range); + write(this.prefix); + super.serialize(context); } - walkTaggedTemplateExpression(expression) { - if (expression.tag) { - this.walkExpression(expression.tag); - } - if (expression.quasi && expression.quasi.expressions) { - this.walkExpressions(expression.quasi.expressions); - } + deserialize(context) { + const { read } = context; + this.name = read(); + this.range = read(); + this.prefix = read(); + super.deserialize(context); } +} - walkClassExpression(expression) { - this.walkClass(expression); - } +const escapeCssIdentifier = (str, omitUnderscore) => { + const escaped = `${str}`.replace( + // cspell:word uffff + /[^a-zA-Z0-9_\u0081-\uffff-]/g, + s => `\\${s}` + ); + return !omitUnderscore && /^(?!--)[0-9-]/.test(escaped) + ? `_${escaped}` + : escaped; +}; +CssLocalIdentifierDependency.Template = class CssLocalIdentifierDependencyTemplate extends ( + NullDependency.Template +) { /** - * @param {ChainExpressionNode} expression expression + * @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} */ - walkChainExpression(expression) { - const result = this.hooks.optionalChaining.call(expression); - - if (result === undefined) { - if (expression.expression.type === "CallExpression") { - this.walkCallExpression(expression.expression); - } else { - this.walkMemberExpression(expression.expression); - } - } - } - - _walkIIFE(functionExpression, options, currentThis) { - const getVarInfo = argOrThis => { - const renameIdentifier = this.getRenameIdentifier(argOrThis); - if (renameIdentifier) { - if ( - this.callHooksForInfo( - this.hooks.canRename, - renameIdentifier, - argOrThis - ) - ) { - if ( - !this.callHooksForInfo( - this.hooks.rename, - renameIdentifier, - argOrThis - ) - ) { - return this.getVariableInfo(renameIdentifier); - } - } - } - this.walkExpression(argOrThis); - }; - const { params, type } = functionExpression; - const arrow = type === "ArrowFunctionExpression"; - const renameThis = currentThis ? getVarInfo(currentThis) : null; - const varInfoForArgs = options.map(getVarInfo); - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = wasTopLevel && arrow ? "arrow" : false; - const scopeParams = params.filter( - (identifier, idx) => !varInfoForArgs[idx] + apply( + dependency, + source, + { module, moduleGraph, chunkGraph, runtime, runtimeTemplate, cssExports } + ) { + const dep = /** @type {CssLocalIdentifierDependency} */ (dependency); + const used = moduleGraph + .getExportInfo(module, dep.name) + .getUsedName(dep.name, runtime); + const moduleId = chunkGraph.getModuleId(module); + const identifier = + dep.prefix + + (runtimeTemplate.outputOptions.uniqueName + ? runtimeTemplate.outputOptions.uniqueName + "-" + : "") + + (used ? moduleId + "-" + used : "-"); + source.replace( + dep.range[0], + dep.range[1] - 1, + escapeCssIdentifier(identifier, dep.prefix) ); + if (used) cssExports.set(used, identifier); + } +}; - // Add function name in scope for recursive calls - if (functionExpression.id) { - scopeParams.push(functionExpression.id.name); - } +makeSerializable( + CssLocalIdentifierDependency, + "webpack/lib/dependencies/CssLocalIdentifierDependency" +); - this.inFunctionScope(true, scopeParams, () => { - if (renameThis && !arrow) { - this.setVariable("this", renameThis); - } - for (let i = 0; i < varInfoForArgs.length; i++) { - const varInfo = varInfoForArgs[i]; - if (!varInfo) continue; - if (!params[i] || params[i].type !== "Identifier") continue; - this.setVariable(params[i].name, varInfo); - } - if (functionExpression.body.type === "BlockStatement") { - this.detectMode(functionExpression.body.body); - const prev = this.prevStatement; - this.preWalkStatement(functionExpression.body); - this.prevStatement = prev; - this.walkStatement(functionExpression.body); - } else { - this.walkExpression(functionExpression.body); - } - }); - this.scope.topLevelScope = wasTopLevel; - } +module.exports = CssLocalIdentifierDependency; - walkImportExpression(expression) { - let result = this.hooks.importCall.call(expression); - if (result === true) return; - this.walkExpression(expression.source); - } +/***/ }), - walkCallExpression(expression) { - const isSimpleFunction = fn => { - return fn.params.every(p => p.type === "Identifier"); - }; - if ( - expression.callee.type === "MemberExpression" && - expression.callee.object.type.endsWith("FunctionExpression") && - !expression.callee.computed && - (expression.callee.property.name === "call" || - expression.callee.property.name === "bind") && - expression.arguments.length > 0 && - isSimpleFunction(expression.callee.object) - ) { - // (function(…) { }.call/bind(?, …)) - this._walkIIFE( - expression.callee.object, - expression.arguments.slice(1), - expression.arguments[0] - ); - } else if ( - expression.callee.type.endsWith("FunctionExpression") && - isSimpleFunction(expression.callee) - ) { - // (function(…) { }(…)) - this._walkIIFE(expression.callee, expression.arguments, null); - } else { - if (expression.callee.type === "MemberExpression") { - const exprInfo = this.getMemberExpressionInfo( - expression.callee, - ALLOWED_MEMBER_TYPES_CALL_EXPRESSION - ); - if (exprInfo && exprInfo.type === "call") { - const result = this.callHooksForInfo( - this.hooks.callMemberChainOfCallMemberChain, - exprInfo.rootInfo, - expression, - exprInfo.getCalleeMembers(), - exprInfo.call, - exprInfo.getMembers() - ); - if (result === true) return; - } - } - const callee = this.evaluateExpression(expression.callee); - if (callee.isIdentifier()) { - const result1 = this.callHooksForInfo( - this.hooks.callMemberChain, - callee.rootInfo, - expression, - callee.getMembers() - ); - if (result1 === true) return; - const result2 = this.callHooksForInfo( - this.hooks.call, - callee.identifier, - expression - ); - if (result2 === true) return; - } +/***/ 29094: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (expression.callee) { - if (expression.callee.type === "MemberExpression") { - // because of call context we need to walk the call context as expression - this.walkExpression(expression.callee.object); - if (expression.callee.computed === true) - this.walkExpression(expression.callee.property); - } else { - this.walkExpression(expression.callee); - } - } - if (expression.arguments) this.walkExpressions(expression.arguments); - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - walkMemberExpression(expression) { - const exprInfo = this.getMemberExpressionInfo( - expression, - ALLOWED_MEMBER_TYPES_ALL - ); - if (exprInfo) { - switch (exprInfo.type) { - case "expression": { - const result1 = this.callHooksForInfo( - this.hooks.expression, - exprInfo.name, - expression - ); - if (result1 === true) return; - const members = exprInfo.getMembers(); - const result2 = this.callHooksForInfo( - this.hooks.expressionMemberChain, - exprInfo.rootInfo, - expression, - members - ); - if (result2 === true) return; - this.walkMemberExpressionWithExpressionName( - expression, - exprInfo.name, - exprInfo.rootInfo, - members.slice(), - () => - this.callHooksForInfo( - this.hooks.unhandledExpressionMemberChain, - exprInfo.rootInfo, - expression, - members - ) - ); - return; - } - case "call": { - const result = this.callHooksForInfo( - this.hooks.memberChainOfCallMemberChain, - exprInfo.rootInfo, - expression, - exprInfo.getCalleeMembers(), - exprInfo.call, - exprInfo.getMembers() - ); - if (result === true) return; - // Fast skip over the member chain as we already called memberChainOfCallMemberChain - // and call computed property are literals anyway - this.walkExpression(exprInfo.call); - return; - } - } - } - this.walkExpression(expression.object); - if (expression.computed === true) this.walkExpression(expression.property); - } - walkMemberExpressionWithExpressionName( - expression, - name, - rootInfo, - members, - onUnhandled - ) { - if (expression.object.type === "MemberExpression") { - // optimize the case where expression.object is a MemberExpression too. - // we can keep info here when calling walkMemberExpression directly - const property = - expression.property.name || `${expression.property.value}`; - name = name.slice(0, -property.length - 1); - members.pop(); - const result = this.callHooksForInfo( - this.hooks.expression, - name, - expression.object - ); - if (result === true) return; - this.walkMemberExpressionWithExpressionName( - expression.object, - name, - rootInfo, - members, - onUnhandled - ); - } else if (!onUnhandled || !onUnhandled()) { - this.walkExpression(expression.object); - } - if (expression.computed === true) this.walkExpression(expression.property); - } - walkThisExpression(expression) { - this.callHooksForName(this.hooks.expression, "this", expression); - } +const Dependency = __webpack_require__(54912); +const makeSerializable = __webpack_require__(33032); +const CssLocalIdentifierDependency = __webpack_require__(92328); - walkIdentifier(expression) { - this.callHooksForName(this.hooks.expression, expression.name, expression); - } +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +class CssSelfLocalIdentifierDependency extends CssLocalIdentifierDependency { /** - * @param {MetaPropertyNode} metaProperty meta property + * @param {string} name name + * @param {[number, number]} range range + * @param {string=} prefix prefix + * @param {Set=} declaredSet set of declared names (will only be active when in declared set) */ - walkMetaProperty(metaProperty) { - this.hooks.expression.for(getRootName(metaProperty)).call(metaProperty); + constructor(name, range, prefix = "", declaredSet = undefined) { + super(name, range, prefix); + this.declaredSet = declaredSet; } - callHooksForExpression(hookMap, expr, ...args) { - return this.callHooksForExpressionWithFallback( - hookMap, - expr, - undefined, - undefined, - ...args - ); + get type() { + return "css self local identifier"; } - /** - * @template T - * @template R - * @param {HookMap>} hookMap hooks the should be called - * @param {MemberExpressionNode} expr expression info - * @param {function(string, string | ScopeInfo | VariableInfo, function(): string[]): any} fallback callback when variable in not handled by hooks - * @param {function(string): any} defined callback when variable is defined - * @param {AsArray} args args for the hook - * @returns {R} result of hook - */ - callHooksForExpressionWithFallback( - hookMap, - expr, - fallback, - defined, - ...args - ) { - const exprName = this.getMemberExpressionInfo( - expr, - ALLOWED_MEMBER_TYPES_EXPRESSION - ); - if (exprName !== undefined) { - const members = exprName.getMembers(); - return this.callHooksForInfoWithFallback( - hookMap, - members.length === 0 ? exprName.rootInfo : exprName.name, - fallback && - (name => fallback(name, exprName.rootInfo, exprName.getMembers)), - defined && (() => defined(exprName.name)), - ...args - ); - } + get category() { + return "self"; } /** - * @template T - * @template R - * @param {HookMap>} hookMap hooks the should be called - * @param {string} name key in map - * @param {AsArray} args args for the hook - * @returns {R} result of hook + * @returns {string | null} an identifier to merge equal requests */ - callHooksForName(hookMap, name, ...args) { - return this.callHooksForNameWithFallback( - hookMap, - name, - undefined, - undefined, - ...args - ); + getResourceIdentifier() { + return `self`; } - /** - * @template T - * @template R - * @param {HookMap>} hookMap hooks that should be called - * @param {ExportedVariableInfo} info variable info - * @param {AsArray} args args for the hook - * @returns {R} result of hook + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names */ - callHooksForInfo(hookMap, info, ...args) { - return this.callHooksForInfoWithFallback( - hookMap, - info, - undefined, - undefined, - ...args - ); + getExports(moduleGraph) { + if (this.declaredSet && !this.declaredSet.has(this.name)) return; + return super.getExports(moduleGraph); } /** - * @template T - * @template R - * @param {HookMap>} hookMap hooks the should be called - * @param {ExportedVariableInfo} info variable info - * @param {function(string): any} fallback callback when variable in not handled by hooks - * @param {function(): any} defined callback when variable is defined - * @param {AsArray} args args for the hook - * @returns {R} result of hook + * 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 */ - callHooksForInfoWithFallback(hookMap, info, fallback, defined, ...args) { - let name; - if (typeof info === "string") { - name = info; - } else { - if (!(info instanceof VariableInfo)) { - if (defined !== undefined) { - return defined(); - } - return; - } - let tagInfo = info.tagInfo; - while (tagInfo !== undefined) { - const hook = hookMap.get(tagInfo.tag); - if (hook !== undefined) { - this.currentTagData = tagInfo.data; - const result = hook.call(...args); - this.currentTagData = undefined; - if (result !== undefined) return result; - } - tagInfo = tagInfo.next; - } - if (info.freeName === true) { - if (defined !== undefined) { - return defined(); - } - return; - } - name = info.freeName; - } - const hook = hookMap.get(name); - if (hook !== undefined) { - const result = hook.call(...args); - if (result !== undefined) return result; - } - if (fallback !== undefined) { - return fallback(name); - } + getReferencedExports(moduleGraph, runtime) { + if (this.declaredSet && !this.declaredSet.has(this.name)) + return Dependency.NO_EXPORTS_REFERENCED; + return [[this.name]]; } - /** - * @template T - * @template R - * @param {HookMap>} hookMap hooks the should be called - * @param {string} name key in map - * @param {function(string): any} fallback callback when variable in not handled by hooks - * @param {function(): any} defined callback when variable is defined - * @param {AsArray} args args for the hook - * @returns {R} result of hook - */ - callHooksForNameWithFallback(hookMap, name, fallback, defined, ...args) { - return this.callHooksForInfoWithFallback( - hookMap, - this.getVariableInfo(name), - fallback, - defined, - ...args - ); + serialize(context) { + const { write } = context; + write(this.declaredSet); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.declaredSet = read(); + super.deserialize(context); } +} +CssSelfLocalIdentifierDependency.Template = class CssSelfLocalIdentifierDependencyTemplate extends ( + CssLocalIdentifierDependency.Template +) { /** - * @deprecated - * @param {any} params scope params - * @param {function(): void} fn inner function + * @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} */ - inScope(params, fn) { - const oldScope = this.scope; - this.scope = { - topLevelScope: oldScope.topLevelScope, - inTry: false, - inShorthand: false, - isStrict: oldScope.isStrict, - isAsmJs: oldScope.isAsmJs, - definitions: oldScope.definitions.createChild() - }; + apply(dependency, source, templateContext) { + const dep = /** @type {CssSelfLocalIdentifierDependency} */ (dependency); + if (dep.declaredSet && !dep.declaredSet.has(dep.name)) return; + super.apply(dependency, source, templateContext); + } +}; - this.undefineVariable("this"); +makeSerializable( + CssSelfLocalIdentifierDependency, + "webpack/lib/dependencies/CssSelfLocalIdentifierDependency" +); - this.enterPatterns(params, (ident, pattern) => { - this.defineVariable(ident); - }); +module.exports = CssSelfLocalIdentifierDependency; - fn(); - this.scope = oldScope; - } +/***/ }), - inFunctionScope(hasThis, params, fn) { - const oldScope = this.scope; - this.scope = { - topLevelScope: oldScope.topLevelScope, - inTry: false, - inShorthand: false, - isStrict: oldScope.isStrict, - isAsmJs: oldScope.isAsmJs, - definitions: oldScope.definitions.createChild() - }; +/***/ 70749: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (hasThis) { - this.undefineVariable("this"); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - this.enterPatterns(params, (ident, pattern) => { - this.defineVariable(ident); - }); - fn(); - this.scope = oldScope; - } +const makeSerializable = __webpack_require__(33032); +const memoize = __webpack_require__(78676); +const ModuleDependency = __webpack_require__(80321); - inBlockScope(fn) { - const oldScope = this.scope; - this.scope = { - topLevelScope: oldScope.topLevelScope, - inTry: oldScope.inTry, - inShorthand: false, - isStrict: oldScope.isStrict, - isAsmJs: oldScope.isAsmJs, - definitions: oldScope.definitions.createChild() - }; +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - fn(); +const getRawDataUrlModule = memoize(() => __webpack_require__(19684)); - this.scope = oldScope; +class CssUrlDependency extends ModuleDependency { + /** + * @param {string} request request + * @param {[number, number]} range range of the argument + * @param {string} cssFunctionKind kind of css function, e. g. url(), image() + */ + constructor(request, range, cssFunctionKind) { + super(request); + this.range = range; + this.cssFunctionKind = cssFunctionKind; } - detectMode(statements) { - const isLiteral = - statements.length >= 1 && - statements[0].type === "ExpressionStatement" && - statements[0].expression.type === "Literal"; - if (isLiteral && statements[0].expression.value === "use strict") { - this.scope.isStrict = true; - } - if (isLiteral && statements[0].expression.value === "use asm") { - this.scope.isAsmJs = true; - } + get type() { + return "css url()"; } - enterPatterns(patterns, onIdent) { - for (const pattern of patterns) { - if (typeof pattern !== "string") { - this.enterPattern(pattern, onIdent); - } else if (pattern) { - onIdent(pattern); - } - } + get category() { + return "url"; } - enterPattern(pattern, onIdent) { - if (!pattern) return; - switch (pattern.type) { - case "ArrayPattern": - this.enterArrayPattern(pattern, onIdent); - break; - case "AssignmentPattern": - this.enterAssignmentPattern(pattern, onIdent); - break; - case "Identifier": - this.enterIdentifier(pattern, onIdent); - break; - case "ObjectPattern": - this.enterObjectPattern(pattern, onIdent); - break; - case "RestElement": - this.enterRestElement(pattern, onIdent); - break; - case "Property": - if (pattern.shorthand && pattern.value.type === "Identifier") { - this.scope.inShorthand = pattern.value.name; - this.enterIdentifier(pattern.value, onIdent); - this.scope.inShorthand = false; - } else { - this.enterPattern(pattern.value, onIdent); - } - break; - } + /** + * @param {string} context context directory + * @returns {Module} a module + */ + createIgnoredModule(context) { + const RawDataUrlModule = getRawDataUrlModule(); + return new RawDataUrlModule("data:,", `ignored-asset`, `(ignored asset)`); } - enterIdentifier(pattern, onIdent) { - if (!this.callHooksForName(this.hooks.pattern, pattern.name, pattern)) { - onIdent(pattern.name, pattern); - } + serialize(context) { + const { write } = context; + write(this.cssFunctionKind); + super.serialize(context); } - enterObjectPattern(pattern, onIdent) { - for ( - let propIndex = 0, len = pattern.properties.length; - propIndex < len; - propIndex++ - ) { - const prop = pattern.properties[propIndex]; - this.enterPattern(prop, onIdent); - } + deserialize(context) { + const { read } = context; + this.cssFunctionKind = read(); + super.deserialize(context); } +} - enterArrayPattern(pattern, onIdent) { - for ( - let elementIndex = 0, len = pattern.elements.length; - elementIndex < len; - elementIndex++ - ) { - const element = pattern.elements[elementIndex]; - this.enterPattern(element, onIdent); +const cssEscapeString = str => { + let countWhiteOrBracket = 0; + let countQuotation = 0; + let countApostrophe = 0; + for (let i = 0; i < str.length; i++) { + const cc = str.charCodeAt(i); + switch (cc) { + case 9: // tab + case 10: // nl + case 32: // space + case 40: // ( + case 41: // ) + countWhiteOrBracket++; + break; + case 34: + countQuotation++; + break; + case 39: + countApostrophe++; + break; } } - - enterRestElement(pattern, onIdent) { - this.enterPattern(pattern.argument, onIdent); - } - - enterAssignmentPattern(pattern, onIdent) { - this.enterPattern(pattern.left, onIdent); + if (countWhiteOrBracket < 2) { + return str.replace(/[\n\t ()'"\\]/g, m => `\\${m}`); + } else if (countQuotation <= countApostrophe) { + return `"${str.replace(/[\n"\\]/g, m => `\\${m}`)}"`; + } else { + return `'${str.replace(/[\n'\\]/g, m => `\\${m}`)}'`; } +}; +CssUrlDependency.Template = class CssUrlDependencyTemplate extends ( + ModuleDependency.Template +) { /** - * @param {ExpressionNode} expression expression node - * @returns {BasicEvaluatedExpression | undefined} evaluation result + * @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} */ - evaluateExpression(expression) { - try { - const hook = this.hooks.evaluate.get(expression.type); - if (hook !== undefined) { - const result = hook.call(expression); - if (result !== undefined) { - if (result) { - result.setExpression(expression); - } - return result; - } - } - } catch (e) { - console.warn(e); - // ignore error - } - return new BasicEvaluatedExpression() - .setRange(expression.range) - .setExpression(expression); - } + apply( + dependency, + source, + { runtime, moduleGraph, runtimeTemplate, codeGenerationResults } + ) { + const dep = /** @type {CssUrlDependency} */ (dependency); - parseString(expression) { - switch (expression.type) { - case "BinaryExpression": - if (expression.operator === "+") { - return ( - this.parseString(expression.left) + - this.parseString(expression.right) - ); - } - break; - case "Literal": - return expression.value + ""; - } - throw new Error( - expression.type + " is not supported as parameter for require" + source.replace( + dep.range[0], + dep.range[1] - 1, + `${dep.cssFunctionKind}(${cssEscapeString( + runtimeTemplate.assetUrl({ + publicPath: "", + runtime, + module: moduleGraph.getModule(dep), + codeGenerationResults + }) + )})` ); } +}; - parseCalculatedString(expression) { - switch (expression.type) { - case "BinaryExpression": - if (expression.operator === "+") { - const left = this.parseCalculatedString(expression.left); - const right = this.parseCalculatedString(expression.right); - if (left.code) { - return { - range: left.range, - value: left.value, - code: true, - conditional: false - }; - } else if (right.code) { - return { - range: [ - left.range[0], - right.range ? right.range[1] : left.range[1] - ], - value: left.value + right.value, - code: true, - conditional: false - }; - } else { - return { - range: [left.range[0], right.range[1]], - value: left.value + right.value, - code: false, - conditional: false - }; - } - } - break; - case "ConditionalExpression": { - const consequent = this.parseCalculatedString(expression.consequent); - const alternate = this.parseCalculatedString(expression.alternate); - const items = []; - if (consequent.conditional) { - items.push(...consequent.conditional); - } else if (!consequent.code) { - items.push(consequent); - } else { - break; - } - if (alternate.conditional) { - items.push(...alternate.conditional); - } else if (!alternate.code) { - items.push(alternate); - } else { - break; - } - return { - range: undefined, - value: "", - code: true, - conditional: items - }; - } - case "Literal": - return { - range: expression.range, - value: expression.value + "", - code: false, - conditional: false - }; - } - return { - range: undefined, - value: "", - code: true, - conditional: false - }; - } +makeSerializable(CssUrlDependency, "webpack/lib/dependencies/CssUrlDependency"); - /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state - */ - parse(source, state) { - let ast; - let comments; - const semicolons = new Set(); - if (source === null) { - throw new Error("source must not be null"); - } - if (Buffer.isBuffer(source)) { - source = source.toString("utf-8"); - } - if (typeof source === "object") { - ast = /** @type {ProgramNode} */ (source); - comments = source.comments; - } else { - comments = []; - ast = JavascriptParser._parse(source, { - sourceType: this.sourceType, - onComment: comments, - onInsertedSemicolon: pos => semicolons.add(pos) - }); - } +module.exports = CssUrlDependency; - const oldScope = this.scope; - const oldState = this.state; - const oldComments = this.comments; - const oldSemicolons = this.semicolons; - const oldStatementPath = this.statementPath; - const oldPrevStatement = this.prevStatement; - this.scope = { - topLevelScope: true, - inTry: false, - inShorthand: false, - isStrict: false, - isAsmJs: false, - definitions: new StackedMap() - }; - /** @type {ParserState} */ - this.state = state; - this.comments = comments; - this.semicolons = semicolons; - this.statementPath = []; - this.prevStatement = undefined; - if (this.hooks.program.call(ast, comments) === undefined) { - this.detectMode(ast.body); - this.preWalkStatements(ast.body); - this.prevStatement = undefined; - this.blockPreWalkStatements(ast.body); - this.prevStatement = undefined; - this.walkStatements(ast.body); - } - this.hooks.finish.call(ast, comments); - this.scope = oldScope; - /** @type {ParserState} */ - this.state = oldState; - this.comments = oldComments; - this.semicolons = oldSemicolons; - this.statementPath = oldStatementPath; - this.prevStatement = oldPrevStatement; - return state; - } - evaluate(source) { - const ast = JavascriptParser._parse("(" + source + ")", { - sourceType: this.sourceType, - locations: false - }); - if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") { - throw new Error("evaluate: Source is not a expression"); - } - return this.evaluateExpression(ast.body[0].expression); - } +/***/ }), - /** - * @param {ExpressionNode | DeclarationNode | PrivateIdentifierNode | null | undefined} expr an expression - * @param {number} commentsStartPos source position from which annotation comments are checked - * @returns {boolean} true, when the expression is pure - */ - isPure(expr, commentsStartPos) { - if (!expr) return true; - const result = this.hooks.isPure - .for(expr.type) - .call(expr, commentsStartPos); - if (typeof result === "boolean") return result; - switch (expr.type) { - case "ClassDeclaration": - case "ClassExpression": { - if (expr.body.type !== "ClassBody") return false; - if (expr.superClass && !this.isPure(expr.superClass, expr.range[0])) { - return false; - } - const items = - /** @type {(MethodDefinitionNode | PropertyDefinitionNode)[]} */ ( - expr.body.body - ); - return items.every( - item => - (!item.computed || - !item.key || - this.isPure(item.key, item.range[0])) && - (!item.static || - !item.value || - this.isPure( - item.value, - item.key ? item.key.range[1] : item.range[0] - )) - ); - } +/***/ 22914: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - case "FunctionDeclaration": - case "FunctionExpression": - case "ArrowFunctionExpression": - case "Literal": - case "PrivateIdentifier": - return true; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - case "VariableDeclaration": - return expr.declarations.every(decl => - this.isPure(decl.init, decl.range[0]) - ); - case "ConditionalExpression": - return ( - this.isPure(expr.test, commentsStartPos) && - this.isPure(expr.consequent, expr.test.range[1]) && - this.isPure(expr.alternate, expr.consequent.range[1]) - ); - case "SequenceExpression": - return expr.expressions.every(expr => { - const pureFlag = this.isPure(expr, commentsStartPos); - commentsStartPos = expr.range[1]; - return pureFlag; - }); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); - case "CallExpression": { - const pureFlag = - expr.range[0] - commentsStartPos > 12 && - this.getComments([commentsStartPos, expr.range[0]]).some( - comment => - comment.type === "Block" && - /^\s*(#|@)__PURE__\s*$/.test(comment.value) - ); - if (!pureFlag) return false; - commentsStartPos = expr.callee.range[1]; - return expr.arguments.every(arg => { - if (arg.type === "SpreadElement") return false; - const pureFlag = this.isPure(arg, commentsStartPos); - commentsStartPos = arg.range[1]; - return pureFlag; - }); - } - } - const evaluated = this.evaluateExpression(expr); - return !evaluated.couldHaveSideEffects(); +class DelegatedSourceDependency extends ModuleDependency { + constructor(request) { + super(request); } - getComments(range) { - const [rangeStart, rangeEnd] = range; - const compare = (comment, needle) => comment.range[0] - needle; - let idx = binarySearchBounds.ge(this.comments, rangeStart, compare); - let commentsInRange = []; - while (this.comments[idx] && this.comments[idx].range[1] <= rangeEnd) { - commentsInRange.push(this.comments[idx]); - idx++; - } - - return commentsInRange; + get type() { + return "delegated source"; } - /** - * @param {number} pos source code position - * @returns {boolean} true when a semicolon has been inserted before this position, false if not - */ - isAsiPosition(pos) { - const currentStatement = this.statementPath[this.statementPath.length - 1]; - if (currentStatement === undefined) throw new Error("Not in statement"); - return ( - // Either asking directly for the end position of the current statement - (currentStatement.range[1] === pos && this.semicolons.has(pos)) || - // Or asking for the start position of the current statement, - // here we have to check multiple things - (currentStatement.range[0] === pos && - // is there a previous statement which might be relevant? - this.prevStatement !== undefined && - // is the end position of the previous statement an ASI position? - this.semicolons.has(this.prevStatement.range[1])) - ); + get category() { + return "esm"; } +} - /** - * @param {number} pos source code position - * @returns {void} - */ - unsetAsiPosition(pos) { - this.semicolons.delete(pos); - } +makeSerializable( + DelegatedSourceDependency, + "webpack/lib/dependencies/DelegatedSourceDependency" +); - isStatementLevelExpression(expr) { - const currentStatement = this.statementPath[this.statementPath.length - 1]; - return ( - expr === currentStatement || - (currentStatement.type === "ExpressionStatement" && - currentStatement.expression === expr) - ); - } +module.exports = DelegatedSourceDependency; - getTagData(name, tag) { - const info = this.scope.definitions.get(name); - if (info instanceof VariableInfo) { - let tagInfo = info.tagInfo; - while (tagInfo !== undefined) { - if (tagInfo.tag === tag) return tagInfo.data; - tagInfo = tagInfo.next; - } - } - } - tagVariable(name, tag, data) { - const oldInfo = this.scope.definitions.get(name); - /** @type {VariableInfo} */ - let newInfo; - if (oldInfo === undefined) { - newInfo = new VariableInfo(this.scope, name, { - tag, - data, - next: undefined - }); - } else if (oldInfo instanceof VariableInfo) { - newInfo = new VariableInfo(oldInfo.declaredScope, oldInfo.freeName, { - tag, - data, - next: oldInfo.tagInfo - }); - } else { - newInfo = new VariableInfo(oldInfo, true, { - tag, - data, - next: undefined - }); - } - this.scope.definitions.set(name, newInfo); - } +/***/ }), - defineVariable(name) { - const oldInfo = this.scope.definitions.get(name); - // Don't redefine variable in same scope to keep existing tags - if (oldInfo instanceof VariableInfo && oldInfo.declaredScope === this.scope) - return; - this.scope.definitions.set(name, this.scope); - } +/***/ 95666: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - undefineVariable(name) { - this.scope.definitions.delete(name); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - isVariableDefined(name) { - const info = this.scope.definitions.get(name); - if (info === undefined) return false; - if (info instanceof VariableInfo) { - return info.freeName === true; - } - return true; - } - /** - * @param {string} name variable name - * @returns {ExportedVariableInfo} info for this variable - */ - getVariableInfo(name) { - const value = this.scope.definitions.get(name); - if (value === undefined) { - return name; - } else { - return value; - } - } - /** - * @param {string} name variable name - * @param {ExportedVariableInfo} variableInfo new info for this variable - * @returns {void} - */ - setVariable(name, variableInfo) { - if (typeof variableInfo === "string") { - if (variableInfo === name) { - this.scope.definitions.delete(name); - } else { - this.scope.definitions.set( - name, - new VariableInfo(this.scope, variableInfo, undefined) - ); - } - } else { - this.scope.definitions.set(name, variableInfo); - } - } +const Dependency = __webpack_require__(54912); +const makeSerializable = __webpack_require__(33032); - parseCommentOptions(range) { - const comments = this.getComments(range); - if (comments.length === 0) { - return EMPTY_COMMENT_OPTIONS; - } - let options = {}; - let errors = []; - for (const comment of comments) { - const { value } = comment; - if (value && webpackCommentRegExp.test(value)) { - // try compile only if webpack options comment is present - try { - const val = vm.runInNewContext(`(function(){return {${value}};})()`); - Object.assign(options, val); - } catch (e) { - e.comment = comment; - errors.push(e); - } - } - } - return { options, errors }; - } +class DllEntryDependency extends Dependency { + constructor(dependencies, name) { + super(); - /** - * @param {MemberExpressionNode} expression a member expression - * @returns {{ members: string[], object: ExpressionNode | SuperNode }} member names (reverse order) and remaining object - */ - extractMemberExpressionChain(expression) { - /** @type {AnyNode} */ - let expr = expression; - const members = []; - while (expr.type === "MemberExpression") { - if (expr.computed) { - if (expr.property.type !== "Literal") break; - members.push(`${expr.property.value}`); - } else { - if (expr.property.type !== "Identifier") break; - members.push(expr.property.name); - } - expr = expr.object; - } - return { - members, - object: expr - }; + this.dependencies = dependencies; + this.name = name; } - /** - * @param {string} varName variable name - * @returns {{name: string, info: VariableInfo | string}} name of the free variable and variable info for that - */ - getFreeInfoFromVariable(varName) { - const info = this.getVariableInfo(varName); - let name; - if (info instanceof VariableInfo) { - name = info.freeName; - if (typeof name !== "string") return undefined; - } else if (typeof info !== "string") { - return undefined; - } else { - name = info; - } - return { info, name }; + get type() { + return "dll entry"; } - /** @typedef {{ type: "call", call: CallExpressionNode, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => string[], name: string, getMembers: () => string[]}} CallExpressionInfo */ - /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[]}} ExpressionExpressionInfo */ - - /** - * @param {MemberExpressionNode} expression a member expression - * @param {number} allowedTypes which types should be returned, presented in bit mask - * @returns {CallExpressionInfo | ExpressionExpressionInfo | undefined} expression info - */ - getMemberExpressionInfo(expression, allowedTypes) { - const { object, members } = this.extractMemberExpressionChain(expression); - switch (object.type) { - case "CallExpression": { - if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0) - return undefined; - let callee = object.callee; - let rootMembers = EMPTY_ARRAY; - if (callee.type === "MemberExpression") { - ({ object: callee, members: rootMembers } = - this.extractMemberExpressionChain(callee)); - } - const rootName = getRootName(callee); - if (!rootName) return undefined; - const result = this.getFreeInfoFromVariable(rootName); - if (!result) return undefined; - const { info: rootInfo, name: resolvedRoot } = result; - const calleeName = objectAndMembersToName(resolvedRoot, rootMembers); - return { - type: "call", - call: object, - calleeName, - rootInfo, - getCalleeMembers: memoize(() => rootMembers.reverse()), - name: objectAndMembersToName(`${calleeName}()`, members), - getMembers: memoize(() => members.reverse()) - }; - } - case "Identifier": - case "MetaProperty": - case "ThisExpression": { - if ((allowedTypes & ALLOWED_MEMBER_TYPES_EXPRESSION) === 0) - return undefined; - const rootName = getRootName(object); - if (!rootName) return undefined; + serialize(context) { + const { write } = context; - const result = this.getFreeInfoFromVariable(rootName); - if (!result) return undefined; - const { info: rootInfo, name: resolvedRoot } = result; - return { - type: "expression", - name: objectAndMembersToName(resolvedRoot, members), - rootInfo, - getMembers: memoize(() => members.reverse()) - }; - } - } - } + write(this.dependencies); + write(this.name); - /** - * @param {MemberExpressionNode} expression an expression - * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => string[]}} name info - */ - getNameForExpression(expression) { - return this.getMemberExpressionInfo( - expression, - ALLOWED_MEMBER_TYPES_EXPRESSION - ); + super.serialize(context); } - /** - * @param {string} code source code - * @param {ParseOptions} options parsing options - * @returns {ProgramNode} parsed ast - */ - static _parse(code, options) { - const type = options ? options.sourceType : "module"; - /** @type {AcornOptions} */ - const parserOptions = { - ...defaultParserOptions, - allowReturnOutsideFunction: type === "script", - ...options, - sourceType: type === "auto" ? "module" : type - }; - - /** @type {AnyNode} */ - let ast; - let error; - let threw = false; - try { - ast = /** @type {AnyNode} */ (parser.parse(code, parserOptions)); - } catch (e) { - error = e; - threw = true; - } - - if (threw && type === "auto") { - parserOptions.sourceType = "script"; - if (!("allowReturnOutsideFunction" in options)) { - parserOptions.allowReturnOutsideFunction = true; - } - if (Array.isArray(parserOptions.onComment)) { - parserOptions.onComment.length = 0; - } - try { - ast = /** @type {AnyNode} */ (parser.parse(code, parserOptions)); - threw = false; - } catch (e) { - // we use the error from first parse try - // so nothing to do here - } - } + deserialize(context) { + const { read } = context; - if (threw) { - throw error; - } + this.dependencies = read(); + this.name = read(); - return /** @type {ProgramNode} */ (ast); + super.deserialize(context); } } -module.exports = JavascriptParser; -module.exports.ALLOWED_MEMBER_TYPES_ALL = ALLOWED_MEMBER_TYPES_ALL; -module.exports.ALLOWED_MEMBER_TYPES_EXPRESSION = - ALLOWED_MEMBER_TYPES_EXPRESSION; -module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = - ALLOWED_MEMBER_TYPES_CALL_EXPRESSION; +makeSerializable( + DllEntryDependency, + "webpack/lib/dependencies/DllEntryDependency" +); + +module.exports = DllEntryDependency; /***/ }), -/***/ 93998: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 32006: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -94837,112 +88706,74 @@ module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = -const UnsupportedFeatureWarning = __webpack_require__(42495); -const ConstDependency = __webpack_require__(76911); -const BasicEvaluatedExpression = __webpack_require__(950); +/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("estree").Expression} ExpressionNode */ -/** @typedef {import("estree").Node} Node */ -/** @typedef {import("./JavascriptParser")} JavascriptParser */ +/** @type {WeakMap} */ +const parserStateExportsState = new WeakMap(); /** - * @param {JavascriptParser} parser the parser - * @param {string} value the const value - * @param {string[]=} runtimeRequirements runtime requirements - * @returns {function(ExpressionNode): true} plugin function + * @param {ParserState} parserState parser state + * @returns {void} */ -exports.toConstantDependency = (parser, value, runtimeRequirements) => { - return function constDependency(expr) { - const dep = new ConstDependency(value, expr.range, runtimeRequirements); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }; +exports.bailout = parserState => { + const value = parserStateExportsState.get(parserState); + parserStateExportsState.set(parserState, false); + if (value === true) { + parserState.module.buildMeta.exportsType = undefined; + parserState.module.buildMeta.defaultObject = false; + } }; /** - * @param {string} value the string value - * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + * @param {ParserState} parserState parser state + * @returns {void} */ -exports.evaluateToString = value => { - return function stringExpression(expr) { - return new BasicEvaluatedExpression().setString(value).setRange(expr.range); - }; +exports.enable = parserState => { + const value = parserStateExportsState.get(parserState); + if (value === false) return; + parserStateExportsState.set(parserState, true); + if (value !== true) { + parserState.module.buildMeta.exportsType = "default"; + parserState.module.buildMeta.defaultObject = "redirect"; + } }; /** - * @param {number} value the number value - * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + * @param {ParserState} parserState parser state + * @returns {void} */ -exports.evaluateToNumber = value => { - return function stringExpression(expr) { - return new BasicEvaluatedExpression().setNumber(value).setRange(expr.range); - }; +exports.setFlagged = parserState => { + const value = parserStateExportsState.get(parserState); + if (value !== true) return; + const buildMeta = parserState.module.buildMeta; + if (buildMeta.exportsType === "dynamic") return; + buildMeta.exportsType = "flagged"; }; /** - * @param {boolean} value the boolean value - * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + * @param {ParserState} parserState parser state + * @returns {void} */ -exports.evaluateToBoolean = value => { - return function booleanExpression(expr) { - return new BasicEvaluatedExpression() - .setBoolean(value) - .setRange(expr.range); - }; +exports.setDynamic = parserState => { + const value = parserStateExportsState.get(parserState); + if (value !== true) return; + parserState.module.buildMeta.exportsType = "dynamic"; }; /** - * @param {string} identifier identifier - * @param {string} rootInfo rootInfo - * @param {function(): string[]} getMembers getMembers - * @param {boolean|null=} truthy is truthy, null if nullish - * @returns {function(ExpressionNode): BasicEvaluatedExpression} callback + * @param {ParserState} parserState parser state + * @returns {boolean} true, when enabled */ -exports.evaluateToIdentifier = (identifier, rootInfo, getMembers, truthy) => { - return function identifierExpression(expr) { - let evaluatedExpression = new BasicEvaluatedExpression() - .setIdentifier(identifier, rootInfo, getMembers) - .setSideEffects(false) - .setRange(expr.range); - switch (truthy) { - case true: - evaluatedExpression.setTruthy(); - break; - case null: - evaluatedExpression.setNullish(true); - break; - case false: - evaluatedExpression.setFalsy(); - break; - } - - return evaluatedExpression; - }; -}; - -exports.expressionIsUnsupported = (parser, message) => { - return function unsupportedExpression(expr) { - const dep = new ConstDependency("(void 0)", expr.range, null); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - if (!parser.state.module) return; - parser.state.module.addWarning( - new UnsupportedFeatureWarning(message, expr.loc) - ); - return true; - }; +exports.isEnabled = parserState => { + const value = parserStateExportsState.get(parserState); + return value === true; }; -exports.skipTraversal = () => true; - -exports.approve = () => true; - /***/ }), -/***/ 98124: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 3979: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -94952,135 +88783,34 @@ exports.approve = () => true; -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const { isSubset } = __webpack_require__(93347); -const { getAllChunks } = __webpack_require__(91145); - -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {(string|number)[]} EntryItem */ - -const EXPORT_PREFIX = "var __webpack_exports__ = "; - -/** - * @param {ChunkGraph} chunkGraph chunkGraph - * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate - * @param {import("../ChunkGraph").EntryModuleWithChunkGroup[]} entries entries - * @param {Chunk} chunk chunk - * @param {boolean} passive true: passive startup with on chunks loaded - * @returns {string} runtime code - */ -exports.generateEntryStartup = ( - chunkGraph, - runtimeTemplate, - entries, - chunk, - passive -) => { - /** @type {string[]} */ - const runtime = [ - `var __webpack_exec__ = ${runtimeTemplate.returningFunction( - `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)`, - "moduleId" - )}` - ]; - - const runModule = id => { - return `__webpack_exec__(${JSON.stringify(id)})`; - }; - const outputCombination = (chunks, moduleIds, final) => { - if (chunks.size === 0) { - runtime.push( - `${final ? EXPORT_PREFIX : ""}(${moduleIds.map(runModule).join(", ")});` - ); - } else { - const fn = runtimeTemplate.returningFunction( - moduleIds.map(runModule).join(", ") - ); - runtime.push( - `${final && !passive ? EXPORT_PREFIX : ""}${ - passive - ? RuntimeGlobals.onChunksLoaded - : RuntimeGlobals.startupEntrypoint - }(0, ${JSON.stringify(Array.from(chunks, c => c.id))}, ${fn});` - ); - if (final && passive) { - runtime.push(`${EXPORT_PREFIX}${RuntimeGlobals.onChunksLoaded}();`); - } - } - }; - - let currentChunks = undefined; - let currentModuleIds = undefined; +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); - for (const [module, entrypoint] of entries) { - const runtimeChunk = entrypoint.getRuntimeChunk(); - const moduleId = chunkGraph.getModuleId(module); - const chunks = getAllChunks(entrypoint, chunk, runtimeChunk); - if ( - currentChunks && - currentChunks.size === chunks.size && - isSubset(currentChunks, chunks) - ) { - currentModuleIds.push(moduleId); - } else { - if (currentChunks) { - outputCombination(currentChunks, currentModuleIds); - } - currentChunks = chunks; - currentModuleIds = [moduleId]; - } +class EntryDependency extends ModuleDependency { + /** + * @param {string} request request path for entry + */ + constructor(request) { + super(request); } - // output current modules with export prefix - if (currentChunks) { - outputCombination(currentChunks, currentModuleIds, true); + get type() { + return "entry"; } - runtime.push(""); - return Template.asString(runtime); -}; -/** - * @param {Hash} hash the hash to update - * @param {ChunkGraph} chunkGraph chunkGraph - * @param {import("../ChunkGraph").EntryModuleWithChunkGroup[]} entries entries - * @param {Chunk} chunk chunk - * @returns {void} - */ -exports.updateHashForEntryStartup = (hash, chunkGraph, entries, chunk) => { - for (const [module, entrypoint] of entries) { - const runtimeChunk = entrypoint.getRuntimeChunk(); - const moduleId = chunkGraph.getModuleId(module); - hash.update(`${moduleId}`); - for (const c of getAllChunks(entrypoint, chunk, runtimeChunk)) - hash.update(`${c.id}`); + get category() { + return "esm"; } -}; +} -/** - * @param {Chunk} chunk the chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {function(Chunk, ChunkGraph): boolean} filterFn filter function - * @returns {Set} initially fulfilled chunk ids - */ -exports.getInitialChunkIds = (chunk, chunkGraph, filterFn) => { - const initialChunkIds = new Set(chunk.ids); - for (const c of chunk.getAllInitialChunks()) { - if (c === chunk || filterFn(c, chunkGraph)) continue; - for (const id of c.ids) initialChunkIds.add(id); - } - return initialChunkIds; -}; +makeSerializable(EntryDependency, "webpack/lib/dependencies/EntryDependency"); + +module.exports = EntryDependency; /***/ }), -/***/ 90490: +/***/ 78988: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95091,244 +88821,141 @@ exports.getInitialChunkIds = (chunk, chunkGraph, filterFn) => { -const { register } = __webpack_require__(8282); +const { UsageState } = __webpack_require__(63686); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -class JsonData { - constructor(data) { - this._buffer = undefined; - this._data = undefined; - if (Buffer.isBuffer(data)) { - this._buffer = data; - } else { - this._data = data; - } - } - - get() { - if (this._data === undefined && this._buffer !== undefined) { - this._data = JSON.parse(this._buffer.toString()); - } - return this._data; - } -} - -register(JsonData, "webpack/lib/json/JsonData", null, { - serialize(obj, { write }) { - if (obj._buffer === undefined && obj._data !== undefined) { - obj._buffer = Buffer.from(JSON.stringify(obj._data)); - } - write(obj._buffer); - }, - deserialize({ read }) { - return new JsonData(read()); - } -}); - -module.exports = JsonData; - - -/***/ }), - -/***/ 70393: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { RawSource } = __webpack_require__(51255); -const ConcatenationScope = __webpack_require__(98229); -const { UsageState } = __webpack_require__(63686); -const Generator = __webpack_require__(93401); -const RuntimeGlobals = __webpack_require__(16475); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../ExportsInfo")} ExportsInfo */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -const stringifySafe = data => { - const stringified = JSON.stringify(data); - if (!stringified) { - return undefined; // Invalid JSON - } - - return stringified.replace(/\u2028|\u2029/g, str => - str === "\u2029" ? "\\u2029" : "\\u2028" - ); // invalid in JavaScript but valid JSON -}; +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** - * @param {Object} data data (always an object or array) - * @param {ExportsInfo} exportsInfo exports info - * @param {RuntimeSpec} runtime the runtime - * @returns {Object} reduced data + * @param {ModuleGraph} moduleGraph the module graph + * @param {Module} module the module + * @param {string | null} exportName name of the export if any + * @param {string | null} property name of the requested property + * @param {RuntimeSpec} runtime for which runtime + * @returns {any} value of the property */ -const createObjectForExportsInfo = (data, exportsInfo, runtime) => { - if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) - return data; - const isArray = Array.isArray(data); - const reducedData = isArray ? [] : {}; - for (const key of Object.keys(data)) { - const exportInfo = exportsInfo.getReadOnlyExportInfo(key); - const used = exportInfo.getUsed(runtime); - if (used === UsageState.Unused) continue; - - let value; - if (used === UsageState.OnlyPropertiesUsed && exportInfo.exportsInfo) { - value = createObjectForExportsInfo( - data[key], - exportInfo.exportsInfo, - runtime - ); - } else { - value = data[key]; - } - const name = exportInfo.getUsedName(key, runtime); - reducedData[name] = value; - } - if (isArray) { - let arrayLengthWhenUsed = - exportsInfo.getReadOnlyExportInfo("length").getUsed(runtime) !== - UsageState.Unused - ? data.length - : undefined; - - let sizeObjectMinusArray = 0; - for (let i = 0; i < reducedData.length; i++) { - if (reducedData[i] === undefined) { - sizeObjectMinusArray -= 2; - } else { - sizeObjectMinusArray += `${i}`.length + 3; +const getProperty = (moduleGraph, module, exportName, property, runtime) => { + if (!exportName) { + switch (property) { + case "usedExports": { + const usedExports = moduleGraph + .getExportsInfo(module) + .getUsedExports(runtime); + if ( + typeof usedExports === "boolean" || + usedExports === undefined || + usedExports === null + ) { + return usedExports; + } + return Array.from(usedExports).sort(); } } - if (arrayLengthWhenUsed !== undefined) { - sizeObjectMinusArray += - `${arrayLengthWhenUsed}`.length + - 8 - - (arrayLengthWhenUsed - reducedData.length) * 2; - } - if (sizeObjectMinusArray < 0) - return Object.assign( - arrayLengthWhenUsed === undefined - ? {} - : { length: arrayLengthWhenUsed }, - reducedData + } + switch (property) { + case "used": + return ( + moduleGraph.getExportsInfo(module).getUsed(exportName, runtime) !== + UsageState.Unused ); - const generatedLength = - arrayLengthWhenUsed !== undefined - ? Math.max(arrayLengthWhenUsed, reducedData.length) - : reducedData.length; - for (let i = 0; i < generatedLength; i++) { - if (reducedData[i] === undefined) { - reducedData[i] = 0; + case "useInfo": { + const state = moduleGraph + .getExportsInfo(module) + .getUsed(exportName, runtime); + switch (state) { + case UsageState.Used: + case UsageState.OnlyPropertiesUsed: + return true; + case UsageState.Unused: + return false; + case UsageState.NoInfo: + return undefined; + case UsageState.Unknown: + return null; + default: + throw new Error(`Unexpected UsageState ${state}`); } } + case "provideInfo": + return moduleGraph.getExportsInfo(module).isExportProvided(exportName); } - return reducedData; + return undefined; }; -const TYPES = new Set(["javascript"]); - -class JsonGenerator extends Generator { - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; +class ExportsInfoDependency extends NullDependency { + constructor(range, exportName, property) { + super(); + this.range = range; + this.exportName = exportName; + this.property = property; } - /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module - */ - getSize(module, type) { - let data = - module.buildInfo && - module.buildInfo.jsonData && - module.buildInfo.jsonData.get(); - if (!data) return 0; - return stringifySafe(data).length + 10; + serialize(context) { + const { write } = context; + write(this.range); + write(this.exportName); + write(this.property); + super.serialize(context); } - /** - * @param {NormalModule} module module for which the bailout reason should be determined - * @param {ConcatenationBailoutReasonContext} context context - * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated - */ - getConcatenationBailoutReason(module, context) { - return undefined; + static deserialize(context) { + const obj = new ExportsInfoDependency( + context.read(), + context.read(), + context.read() + ); + obj.deserialize(context); + return obj; } +} + +makeSerializable( + ExportsInfoDependency, + "webpack/lib/dependencies/ExportsInfoDependency" +); +ExportsInfoDependency.Template = class ExportsInfoDependencyTemplate extends ( + NullDependency.Template +) { /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code + * @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} */ - generate( - module, - { + apply(dependency, source, { module, moduleGraph, runtime }) { + const dep = /** @type {ExportsInfoDependency} */ (dependency); + + const value = getProperty( moduleGraph, - runtimeTemplate, - runtimeRequirements, - runtime, - concatenationScope - } - ) { - const data = - module.buildInfo && - module.buildInfo.jsonData && - module.buildInfo.jsonData.get(); - if (data === undefined) { - return new RawSource( - runtimeTemplate.missingModuleStatement({ - request: module.rawRequest - }) - ); - } - const exportsInfo = moduleGraph.getExportsInfo(module); - let finalJson = - typeof data === "object" && - data && - exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused - ? createObjectForExportsInfo(data, exportsInfo, runtime) - : data; - // Use JSON because JSON.parse() is much faster than JavaScript evaluation - const jsonStr = stringifySafe(finalJson); - const jsonExpr = - jsonStr.length > 20 && typeof finalJson === "object" - ? `JSON.parse('${jsonStr.replace(/[\\']/g, "\\$&")}')` - : jsonStr; - let content; - if (concatenationScope) { - content = `${runtimeTemplate.supportsConst() ? "const" : "var"} ${ - ConcatenationScope.NAMESPACE_OBJECT_EXPORT - } = ${jsonExpr};`; - concatenationScope.registerNamespaceExport( - ConcatenationScope.NAMESPACE_OBJECT_EXPORT - ); - } else { - runtimeRequirements.add(RuntimeGlobals.module); - content = `${module.moduleArgument}.exports = ${jsonExpr};`; - } - return new RawSource(content); + module, + dep.exportName, + dep.property, + runtime + ); + source.replace( + dep.range[0], + dep.range[1] - 1, + value === undefined ? "undefined" : JSON.stringify(value) + ); } -} +}; -module.exports = JsonGenerator; +module.exports = ExportsInfoDependency; /***/ }), -/***/ 86770: +/***/ 23624: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95339,54 +88966,138 @@ module.exports = JsonGenerator; -const createSchemaValidation = __webpack_require__(32540); -const JsonGenerator = __webpack_require__(70393); -const JsonParser = __webpack_require__(41090); +const Template = __webpack_require__(39722); +const makeSerializable = __webpack_require__(33032); +const HarmonyImportDependency = __webpack_require__(57154); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("./HarmonyAcceptImportDependency")} HarmonyAcceptImportDependency */ -const validate = createSchemaValidation( - __webpack_require__(54094), - () => __webpack_require__(50166), - { - name: "Json Modules Plugin", - baseDataPath: "parser" +class HarmonyAcceptDependency extends NullDependency { + /** + * @param {[number, number]} range expression range + * @param {HarmonyAcceptImportDependency[]} dependencies import dependencies + * @param {boolean} hasCallback true, if the range wraps an existing callback + */ + constructor(range, dependencies, hasCallback) { + super(); + this.range = range; + this.dependencies = dependencies; + this.hasCallback = hasCallback; + } + + get type() { + return "accepted harmony modules"; + } + + serialize(context) { + const { write } = context; + write(this.range); + write(this.dependencies); + write(this.hasCallback); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.range = read(); + this.dependencies = read(); + this.hasCallback = read(); + super.deserialize(context); } +} + +makeSerializable( + HarmonyAcceptDependency, + "webpack/lib/dependencies/HarmonyAcceptDependency" ); -class JsonModulesPlugin { +HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate extends ( + NullDependency.Template +) { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - compiler.hooks.compilation.tap( - "JsonModulesPlugin", - (compilation, { normalModuleFactory }) => { - normalModuleFactory.hooks.createParser - .for("json") - .tap("JsonModulesPlugin", parserOptions => { - validate(parserOptions); + apply(dependency, source, templateContext) { + const dep = /** @type {HarmonyAcceptDependency} */ (dependency); + const { + module, + runtime, + runtimeRequirements, + runtimeTemplate, + moduleGraph, + chunkGraph + } = templateContext; + const content = dep.dependencies + .map(dependency => { + const referencedModule = moduleGraph.getModule(dependency); + return { + dependency, + runtimeCondition: referencedModule + ? HarmonyImportDependency.Template.getImportEmittedRuntime( + module, + referencedModule + ) + : false + }; + }) + .filter(({ runtimeCondition }) => runtimeCondition !== false) + .map(({ dependency, runtimeCondition }) => { + const condition = runtimeTemplate.runtimeConditionExpression({ + chunkGraph, + runtime, + runtimeCondition, + runtimeRequirements + }); + const s = dependency.getImportStatement(true, templateContext); + const code = s[0] + s[1]; + if (condition !== "true") { + return `if (${condition}) {\n${Template.indent(code)}\n}\n`; + } + return code; + }) + .join(""); - return new JsonParser(parserOptions); - }); - normalModuleFactory.hooks.createGenerator - .for("json") - .tap("JsonModulesPlugin", () => { - return new JsonGenerator(); - }); + if (dep.hasCallback) { + if (runtimeTemplate.supportsArrowFunction()) { + source.insert( + dep.range[0], + `__WEBPACK_OUTDATED_DEPENDENCIES__ => { ${content}(` + ); + source.insert(dep.range[1], ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }"); + } else { + source.insert( + dep.range[0], + `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(` + ); + source.insert( + dep.range[1], + ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }.bind(this)" + ); } + return; + } + + const arrow = runtimeTemplate.supportsArrowFunction(); + source.insert( + dep.range[1] - 0.5, + `, ${arrow ? "() =>" : "function()"} { ${content} }` ); } -} +}; -module.exports = JsonModulesPlugin; +module.exports = HarmonyAcceptDependency; /***/ }), -/***/ 41090: +/***/ 99843: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95397,61 +89108,39 @@ module.exports = JsonModulesPlugin; -const parseJson = __webpack_require__(15235); -const Parser = __webpack_require__(11715); -const JsonExportsDependency = __webpack_require__(750); -const JsonData = __webpack_require__(90490); +const makeSerializable = __webpack_require__(33032); +const HarmonyImportDependency = __webpack_require__(57154); -/** @typedef {import("../../declarations/plugins/JsonModulesPluginParser").JsonModulesPluginParserOptions} JsonModulesPluginParserOptions */ -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -class JsonParser extends Parser { - /** - * @param {JsonModulesPluginParserOptions} options parser options - */ - constructor(options) { - super(); - this.options = options || {}; +class HarmonyAcceptImportDependency extends HarmonyImportDependency { + constructor(request) { + super(request, NaN); + this.weak = true; } - /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state - */ - parse(source, state) { - if (Buffer.isBuffer(source)) { - source = source.toString("utf-8"); - } - - /** @type {JsonModulesPluginParserOptions["parse"]} */ - const parseFn = - typeof this.options.parse === "function" ? this.options.parse : parseJson; - - const data = - typeof source === "object" - ? source - : parseFn(source[0] === "\ufeff" ? source.slice(1) : source); - - state.module.buildInfo.jsonData = new JsonData(data); - state.module.buildInfo.strict = true; - state.module.buildMeta.exportsType = "default"; - state.module.buildMeta.defaultObject = - typeof data === "object" ? "redirect-warn" : false; - state.module.addDependency( - new JsonExportsDependency(JsonExportsDependency.getExportsFromData(data)) - ); - return state; + get type() { + return "harmony accept"; } } -module.exports = JsonParser; +makeSerializable( + HarmonyAcceptImportDependency, + "webpack/lib/dependencies/HarmonyAcceptImportDependency" +); + +HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate extends ( + HarmonyImportDependency.Template +) {}; + +module.exports = HarmonyAcceptImportDependency; /***/ }), -/***/ 26030: +/***/ 72906: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95462,301 +89151,200 @@ module.exports = JsonParser; +const { UsageState } = __webpack_require__(63686); +const InitFragment = __webpack_require__(55870); const RuntimeGlobals = __webpack_require__(16475); -const JavascriptModulesPlugin = __webpack_require__(89464); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../Module")} Module */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ -/** @typedef {import("../util/Hash")} Hash */ - -const COMMON_LIBRARY_NAME_MESSAGE = - "Common configuration options that specific library names are 'output.library[.name]', 'entry.xyz.library[.name]', 'ModuleFederationPlugin.name' and 'ModuleFederationPlugin.library[.name]'."; - -/** - * @template T - * @typedef {Object} LibraryContext - * @property {Compilation} compilation - * @property {ChunkGraph} chunkGraph - * @property {T} options - */ -/** - * @template T - */ -class AbstractLibraryPlugin { - /** - * @param {Object} options options - * @param {string} options.pluginName name of the plugin - * @param {LibraryType} options.type used library type - */ - constructor({ pluginName, type }) { - this._pluginName = pluginName; - this._type = type; - this._parseCache = new WeakMap(); +class HarmonyCompatibilityDependency extends NullDependency { + get type() { + return "harmony export header"; } +} + +makeSerializable( + HarmonyCompatibilityDependency, + "webpack/lib/dependencies/HarmonyCompatibilityDependency" +); +HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate extends ( + NullDependency.Template +) { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - const { _pluginName } = this; - compiler.hooks.thisCompilation.tap(_pluginName, compilation => { - compilation.hooks.finishModules.tap( - { name: _pluginName, stage: 10 }, - () => { - for (const [ - name, - { - dependencies: deps, - options: { library } - } - ] of compilation.entries) { - const options = this._parseOptionsCached( - library !== undefined - ? library - : compilation.outputOptions.library - ); - if (options !== false) { - const dep = deps[deps.length - 1]; - if (dep) { - const module = compilation.moduleGraph.getModule(dep); - if (module) { - this.finishEntryModule(module, name, { - options, - compilation, - chunkGraph: compilation.chunkGraph - }); - } - } - } - } - } + apply( + dependency, + source, + { + module, + runtimeTemplate, + moduleGraph, + initFragments, + runtimeRequirements, + runtime, + concatenationScope + } + ) { + if (concatenationScope) return; + const exportsInfo = moduleGraph.getExportsInfo(module); + if ( + exportsInfo.getReadOnlyExportInfo("__esModule").getUsed(runtime) !== + UsageState.Unused + ) { + const content = runtimeTemplate.defineEsModuleFlagStatement({ + exportsArgument: module.exportsArgument, + runtimeRequirements + }); + initFragments.push( + new InitFragment( + content, + InitFragment.STAGE_HARMONY_EXPORTS, + 0, + "harmony compatibility" + ) ); + } + if (moduleGraph.isAsync(module)) { + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(RuntimeGlobals.asyncModule); + initFragments.push( + new InitFragment( + runtimeTemplate.supportsArrowFunction() + ? `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async (__webpack_handle_async_dependencies__) => {\n` + : `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async function (__webpack_handle_async_dependencies__) {\n`, + InitFragment.STAGE_ASYNC_BOUNDARY, + 0, + undefined, + module.buildMeta.async + ? `\n__webpack_handle_async_dependencies__();\n}, 1);` + : "\n});" + ) + ); + } + } +}; - const getOptionsForChunk = chunk => { - if (compilation.chunkGraph.getNumberOfEntryModules(chunk) === 0) - return false; - const options = chunk.getEntryOptions(); - const library = options && options.library; - return this._parseOptionsCached( - library !== undefined ? library : compilation.outputOptions.library - ); - }; - - if ( - this.render !== AbstractLibraryPlugin.prototype.render || - this.runtimeRequirements !== - AbstractLibraryPlugin.prototype.runtimeRequirements - ) { - compilation.hooks.additionalChunkRuntimeRequirements.tap( - _pluginName, - (chunk, set, { chunkGraph }) => { - const options = getOptionsForChunk(chunk); - if (options !== false) { - this.runtimeRequirements(chunk, set, { - options, - compilation, - chunkGraph - }); - } - } - ); - } - - const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); - - if (this.render !== AbstractLibraryPlugin.prototype.render) { - hooks.render.tap(_pluginName, (source, renderContext) => { - const options = getOptionsForChunk(renderContext.chunk); - if (options === false) return source; - return this.render(source, renderContext, { - options, - compilation, - chunkGraph: compilation.chunkGraph - }); - }); - } +module.exports = HarmonyCompatibilityDependency; - if ( - this.embedInRuntimeBailout !== - AbstractLibraryPlugin.prototype.embedInRuntimeBailout - ) { - hooks.embedInRuntimeBailout.tap( - _pluginName, - (module, renderContext) => { - const options = getOptionsForChunk(renderContext.chunk); - if (options === false) return; - return this.embedInRuntimeBailout(module, renderContext, { - options, - compilation, - chunkGraph: compilation.chunkGraph - }); - } - ); - } - if ( - this.strictRuntimeBailout !== - AbstractLibraryPlugin.prototype.strictRuntimeBailout - ) { - hooks.strictRuntimeBailout.tap(_pluginName, renderContext => { - const options = getOptionsForChunk(renderContext.chunk); - if (options === false) return; - return this.strictRuntimeBailout(renderContext, { - options, - compilation, - chunkGraph: compilation.chunkGraph - }); - }); - } +/***/ }), - if ( - this.renderStartup !== AbstractLibraryPlugin.prototype.renderStartup - ) { - hooks.renderStartup.tap( - _pluginName, - (source, module, renderContext) => { - const options = getOptionsForChunk(renderContext.chunk); - if (options === false) return source; - return this.renderStartup(source, module, renderContext, { - options, - compilation, - chunkGraph: compilation.chunkGraph - }); - } - ); - } +/***/ 17223: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - hooks.chunkHash.tap(_pluginName, (chunk, hash, context) => { - const options = getOptionsForChunk(chunk); - if (options === false) return; - this.chunkHash(chunk, hash, context, { - options, - compilation, - chunkGraph: compilation.chunkGraph - }); - }); - }); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @param {LibraryOptions=} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - _parseOptionsCached(library) { - if (!library) return false; - if (library.type !== this._type) return false; - const cacheEntry = this._parseCache.get(library); - if (cacheEntry !== undefined) return cacheEntry; - const result = this.parseOptions(library); - this._parseCache.set(library, result); - return result; - } - /* istanbul ignore next */ - /** - * @abstract - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - parseOptions(library) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); - } - /** - * @param {Module} module the exporting entry module - * @param {string} entryName the name of the entrypoint - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - finishEntryModule(module, entryName, libraryContext) {} +const DynamicExports = __webpack_require__(32006); +const HarmonyCompatibilityDependency = __webpack_require__(72906); +const HarmonyExports = __webpack_require__(39211); - /** - * @param {Module} module the exporting entry module - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {string | undefined} bailout reason - */ - embedInRuntimeBailout(module, renderContext, libraryContext) { - return undefined; +module.exports = class HarmonyDetectionParserPlugin { + constructor(options) { + const { topLevelAwait = false } = options || {}; + this.topLevelAwait = topLevelAwait; } - /** - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {string | undefined} bailout reason - */ - strictRuntimeBailout(renderContext, libraryContext) { - return undefined; - } + apply(parser) { + parser.hooks.program.tap("HarmonyDetectionParserPlugin", ast => { + const isStrictHarmony = parser.state.module.type === "javascript/esm"; + const isHarmony = + isStrictHarmony || + ast.body.some( + statement => + statement.type === "ImportDeclaration" || + statement.type === "ExportDefaultDeclaration" || + statement.type === "ExportNamedDeclaration" || + statement.type === "ExportAllDeclaration" + ); + if (isHarmony) { + const module = parser.state.module; + const compatDep = new HarmonyCompatibilityDependency(); + compatDep.loc = { + start: { + line: -1, + column: 0 + }, + end: { + line: -1, + column: 0 + }, + index: -3 + }; + module.addPresentationalDependency(compatDep); + DynamicExports.bailout(parser.state); + HarmonyExports.enable(parser.state, isStrictHarmony); + parser.scope.isStrict = true; + } + }); - /** - * @param {Chunk} chunk the chunk - * @param {Set} set runtime requirements - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - runtimeRequirements(chunk, set, libraryContext) { - if (this.render !== AbstractLibraryPlugin.prototype.render) - set.add(RuntimeGlobals.returnExportsFromRuntime); - } + parser.hooks.topLevelAwait.tap("HarmonyDetectionParserPlugin", () => { + const module = parser.state.module; + if (!this.topLevelAwait) { + throw new Error( + "The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)" + ); + } + if (!HarmonyExports.isEnabled(parser.state)) { + throw new Error( + "Top-level-await is only supported in EcmaScript Modules" + ); + } + module.buildMeta.async = true; + }); - /** - * @param {Source} source source - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - render(source, renderContext, libraryContext) { - return source; - } + const skipInHarmony = () => { + if (HarmonyExports.isEnabled(parser.state)) { + return true; + } + }; - /** - * @param {Source} source source - * @param {Module} module module - * @param {StartupRenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - renderStartup(source, module, renderContext, libraryContext) { - return source; - } + const nullInHarmony = () => { + if (HarmonyExports.isEnabled(parser.state)) { + return null; + } + }; - /** - * @param {Chunk} chunk the chunk - * @param {Hash} hash hash - * @param {ChunkHashContext} chunkHashContext chunk hash context - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - chunkHash(chunk, hash, chunkHashContext, libraryContext) { - const options = this._parseOptionsCached( - libraryContext.compilation.outputOptions.library - ); - hash.update(this._pluginName); - hash.update(JSON.stringify(options)); + const nonHarmonyIdentifiers = ["define", "exports"]; + for (const identifier of nonHarmonyIdentifiers) { + parser.hooks.evaluateTypeof + .for(identifier) + .tap("HarmonyDetectionParserPlugin", nullInHarmony); + parser.hooks.typeof + .for(identifier) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + parser.hooks.evaluate + .for(identifier) + .tap("HarmonyDetectionParserPlugin", nullInHarmony); + parser.hooks.expression + .for(identifier) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + parser.hooks.call + .for(identifier) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + } } -} - -AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE = COMMON_LIBRARY_NAME_MESSAGE; -module.exports = AbstractLibraryPlugin; +}; /***/ }), -/***/ 67416: +/***/ 93466: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95767,166 +89355,189 @@ module.exports = AbstractLibraryPlugin; -const { ConcatSource } = __webpack_require__(51255); -const ExternalModule = __webpack_require__(73071); -const Template = __webpack_require__(1626); -const AbstractLibraryPlugin = __webpack_require__(26030); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ - -/** - * @typedef {Object} AmdLibraryPluginOptions - * @property {LibraryType} type - * @property {boolean=} requireAsWrapper - */ +const InnerGraph = __webpack_require__(38988); +const ConstDependency = __webpack_require__(76911); +const HarmonyExportExpressionDependency = __webpack_require__(51340); +const HarmonyExportHeaderDependency = __webpack_require__(38873); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(67157); +const HarmonyExportSpecifierDependency = __webpack_require__(48567); +const { ExportPresenceModes } = __webpack_require__(57154); +const { + harmonySpecifierTag, + getAssertions +} = __webpack_require__(20862); +const HarmonyImportSideEffectDependency = __webpack_require__(73132); -/** - * @typedef {Object} AmdLibraryPluginParsed - * @property {string} name - */ +const { HarmonyStarExportsList } = HarmonyExportImportedSpecifierDependency; -/** - * @typedef {AmdLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} - */ -class AmdLibraryPlugin extends AbstractLibraryPlugin { - /** - * @param {AmdLibraryPluginOptions} options the plugin options - */ +module.exports = class HarmonyExportDependencyParserPlugin { constructor(options) { - super({ - pluginName: "AmdLibraryPlugin", - type: options.type - }); - this.requireAsWrapper = options.requireAsWrapper; + this.exportPresenceMode = + options.reexportExportsPresence !== undefined + ? ExportPresenceModes.fromUserOption(options.reexportExportsPresence) + : options.exportsPresence !== undefined + ? ExportPresenceModes.fromUserOption(options.exportsPresence) + : options.strictExportPresence + ? ExportPresenceModes.ERROR + : ExportPresenceModes.AUTO; } - /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - parseOptions(library) { - const { name } = library; - if (this.requireAsWrapper) { - if (name) { - throw new Error( - `AMD library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); - } - } else { - if (name && typeof name !== "string") { - throw new Error( - `AMD library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + apply(parser) { + const { exportPresenceMode } = this; + parser.hooks.export.tap( + "HarmonyExportDependencyParserPlugin", + statement => { + const dep = new HarmonyExportHeaderDependency( + statement.declaration && statement.declaration.range, + statement.range ); + dep.loc = Object.create(statement.loc); + dep.loc.index = -1; + parser.state.module.addPresentationalDependency(dep); + return true; + } + ); + parser.hooks.exportImport.tap( + "HarmonyExportDependencyParserPlugin", + (statement, source) => { + parser.state.lastHarmonyImportOrder = + (parser.state.lastHarmonyImportOrder || 0) + 1; + const clearDep = new ConstDependency("", statement.range); + clearDep.loc = Object.create(statement.loc); + clearDep.loc.index = -1; + parser.state.module.addPresentationalDependency(clearDep); + const sideEffectDep = new HarmonyImportSideEffectDependency( + source, + parser.state.lastHarmonyImportOrder, + getAssertions(statement) + ); + sideEffectDep.loc = Object.create(statement.loc); + sideEffectDep.loc.index = -1; + parser.state.current.addDependency(sideEffectDep); + return true; + } + ); + parser.hooks.exportExpression.tap( + "HarmonyExportDependencyParserPlugin", + (statement, expr) => { + const isFunctionDeclaration = expr.type === "FunctionDeclaration"; + const comments = parser.getComments([ + statement.range[0], + expr.range[0] + ]); + const dep = new HarmonyExportExpressionDependency( + expr.range, + statement.range, + comments + .map(c => { + switch (c.type) { + case "Block": + return `/*${c.value}*/`; + case "Line": + return `//${c.value}\n`; + } + return ""; + }) + .join(""), + expr.type.endsWith("Declaration") && expr.id + ? expr.id.name + : isFunctionDeclaration + ? { + id: expr.id ? expr.id.name : undefined, + range: [ + expr.range[0], + expr.params.length > 0 + ? expr.params[0].range[0] + : expr.body.range[0] + ], + prefix: `${expr.async ? "async " : ""}function${ + expr.generator ? "*" : "" + } `, + suffix: `(${expr.params.length > 0 ? "" : ") "}` + } + : undefined + ); + dep.loc = Object.create(statement.loc); + dep.loc.index = -1; + parser.state.current.addDependency(dep); + InnerGraph.addVariableUsage( + parser, + expr.type.endsWith("Declaration") && expr.id + ? expr.id.name + : "*default*", + "default" + ); + return true; + } + ); + parser.hooks.exportSpecifier.tap( + "HarmonyExportDependencyParserPlugin", + (statement, id, name, idx) => { + const settings = parser.getTagData(id, harmonySpecifierTag); + let dep; + const harmonyNamedExports = (parser.state.harmonyNamedExports = + parser.state.harmonyNamedExports || new Set()); + harmonyNamedExports.add(name); + InnerGraph.addVariableUsage(parser, id, name); + if (settings) { + dep = new HarmonyExportImportedSpecifierDependency( + settings.source, + settings.sourceOrder, + settings.ids, + name, + harmonyNamedExports, + null, + exportPresenceMode, + null, + settings.assertions + ); + } else { + dep = new HarmonyExportSpecifierDependency(id, name); + } + dep.loc = Object.create(statement.loc); + dep.loc.index = idx; + parser.state.current.addDependency(dep); + return true; + } + ); + parser.hooks.exportImportSpecifier.tap( + "HarmonyExportDependencyParserPlugin", + (statement, source, id, name, idx) => { + const harmonyNamedExports = (parser.state.harmonyNamedExports = + parser.state.harmonyNamedExports || new Set()); + let harmonyStarExports = null; + if (name) { + harmonyNamedExports.add(name); + } else { + harmonyStarExports = parser.state.harmonyStarExports = + parser.state.harmonyStarExports || new HarmonyStarExportsList(); + } + const dep = new HarmonyExportImportedSpecifierDependency( + source, + parser.state.lastHarmonyImportOrder, + id ? [id] : [], + name, + harmonyNamedExports, + harmonyStarExports && harmonyStarExports.slice(), + exportPresenceMode, + harmonyStarExports + ); + if (harmonyStarExports) { + harmonyStarExports.push(dep); + } + dep.loc = Object.create(statement.loc); + dep.loc.index = idx; + parser.state.current.addDependency(dep); + return true; } - } - return { - name: /** @type {string=} */ (name) - }; - } - - /** - * @param {Source} source source - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - render( - source, - { chunkGraph, chunk, runtimeTemplate }, - { options, compilation } - ) { - const modern = runtimeTemplate.supportsArrowFunction(); - const modules = chunkGraph - .getChunkModules(chunk) - .filter(m => m instanceof ExternalModule); - const externals = /** @type {ExternalModule[]} */ (modules); - const externalsDepsArray = JSON.stringify( - externals.map(m => - typeof m.request === "object" && !Array.isArray(m.request) - ? m.request.amd - : m.request - ) ); - const externalsArguments = externals - .map( - m => - `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( - `${chunkGraph.getModuleId(m)}` - )}__` - ) - .join(", "); - - const iife = runtimeTemplate.isIIFE(); - const fnStart = - (modern - ? `(${externalsArguments}) => {` - : `function(${externalsArguments}) {`) + - (iife || !chunk.hasRuntime() ? " return " : "\n"); - const fnEnd = iife ? ";\n}" : "\n}"; - - if (this.requireAsWrapper) { - return new ConcatSource( - `require(${externalsDepsArray}, ${fnStart}`, - source, - `${fnEnd});` - ); - } else if (options.name) { - const name = compilation.getPath(options.name, { - chunk - }); - - return new ConcatSource( - `define(${JSON.stringify(name)}, ${externalsDepsArray}, ${fnStart}`, - source, - `${fnEnd});` - ); - } else if (externalsArguments) { - return new ConcatSource( - `define(${externalsDepsArray}, ${fnStart}`, - source, - `${fnEnd});` - ); - } else { - return new ConcatSource(`define(${fnStart}`, source, `${fnEnd});`); - } - } - - /** - * @param {Chunk} chunk the chunk - * @param {Hash} hash hash - * @param {ChunkHashContext} chunkHashContext chunk hash context - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { - hash.update("AmdLibraryPlugin"); - if (this.requireAsWrapper) { - hash.update("requireAsWrapper"); - } else if (options.name) { - hash.update("named"); - const name = compilation.getPath(options.name, { - chunk - }); - hash.update(name); - } } -} - -module.exports = AmdLibraryPlugin; +}; /***/ }), -/***/ 40080: +/***/ 51340: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95937,373 +89548,194 @@ module.exports = AmdLibraryPlugin; -const { ConcatSource } = __webpack_require__(51255); -const { UsageState } = __webpack_require__(63686); -const Template = __webpack_require__(1626); -const propertyAccess = __webpack_require__(54190); -const { getEntryRuntime } = __webpack_require__(17156); -const AbstractLibraryPlugin = __webpack_require__(26030); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ - -const KEYWORD_REGEX = - /^(await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|super|switch|static|this|throw|try|true|typeof|var|void|while|with|yield)$/; -const IDENTIFIER_REGEX = - /^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/iu; - -/** - * Validates the library name by checking for keywords and valid characters - * @param {string} name name to be validated - * @returns {boolean} true, when valid - */ -const isNameValid = name => { - return !KEYWORD_REGEX.test(name) && IDENTIFIER_REGEX.test(name); -}; - -/** - * @param {string[]} accessor variable plus properties - * @param {number} existingLength items of accessor that are existing already - * @param {boolean=} initLast if the last property should also be initialized to an object - * @returns {string} code to access the accessor while initializing - */ -const accessWithInit = (accessor, existingLength, initLast = false) => { - // This generates for [a, b, c, d]: - // (((a = typeof a === "undefined" ? {} : a).b = a.b || {}).c = a.b.c || {}).d - const base = accessor[0]; - if (accessor.length === 1 && !initLast) return base; - let current = - existingLength > 0 - ? base - : `(${base} = typeof ${base} === "undefined" ? {} : ${base})`; - - // i is the current position in accessor that has been printed - let i = 1; - - // all properties printed so far (excluding base) - let propsSoFar; +const ConcatenationScope = __webpack_require__(98229); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const HarmonyExportInitFragment = __webpack_require__(89500); +const NullDependency = __webpack_require__(31830); - // if there is existingLength, print all properties until this position as property access - if (existingLength > i) { - propsSoFar = accessor.slice(1, existingLength); - i = existingLength; - current += propertyAccess(propsSoFar); - } else { - propsSoFar = []; - } +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ - // all remaining properties (except the last one when initLast is not set) - // should be printed as initializer - const initUntil = initLast ? accessor.length : accessor.length - 1; - for (; i < initUntil; i++) { - const prop = accessor[i]; - propsSoFar.push(prop); - current = `(${current}${propertyAccess([prop])} = ${base}${propertyAccess( - propsSoFar - )} || {})`; +class HarmonyExportExpressionDependency extends NullDependency { + constructor(range, rangeStatement, prefix, declarationId) { + super(); + this.range = range; + this.rangeStatement = rangeStatement; + this.prefix = prefix; + this.declarationId = declarationId; } - // print the last property as property access if not yet printed - if (i < accessor.length) - current = `${current}${propertyAccess([accessor[accessor.length - 1]])}`; - - return current; -}; - -/** - * @typedef {Object} AssignLibraryPluginOptions - * @property {LibraryType} type - * @property {string[] | "global"} prefix name prefix - * @property {string | false} declare declare name as variable - * @property {"error"|"static"|"copy"|"assign"} unnamed behavior for unnamed library name - * @property {"copy"|"assign"=} named behavior for named library name - */ - -/** - * @typedef {Object} AssignLibraryPluginParsed - * @property {string | string[]} name - * @property {string | string[] | undefined} export - */ - -/** - * @typedef {AssignLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} - */ -class AssignLibraryPlugin extends AbstractLibraryPlugin { - /** - * @param {AssignLibraryPluginOptions} options the plugin options - */ - constructor(options) { - super({ - pluginName: "AssignLibraryPlugin", - type: options.type - }); - this.prefix = options.prefix; - this.declare = options.declare; - this.unnamed = options.unnamed; - this.named = options.named || "assign"; + get type() { + return "harmony export expression"; } /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names */ - parseOptions(library) { - const { name } = library; - if (this.unnamed === "error") { - if (typeof name !== "string" && !Array.isArray(name)) { - throw new Error( - `Library name must be a string or string array. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); - } - } else { - if (name && typeof name !== "string" && !Array.isArray(name)) { - throw new Error( - `Library name must be a string, string array or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); - } - } + getExports(moduleGraph) { return { - name: /** @type {string|string[]=} */ (name), - export: library.export + exports: ["default"], + priority: 1, + terminalBinding: true, + dependencies: undefined }; } /** - * @param {Module} module the exporting entry module - * @param {string} entryName the name of the entrypoint - * @param {LibraryContext} libraryContext context - * @returns {void} + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules */ - finishEntryModule( - module, - entryName, - { options, compilation, compilation: { moduleGraph } } - ) { - const runtime = getEntryRuntime(compilation, entryName); - if (options.export) { - const exportsInfo = moduleGraph.getExportInfo( - module, - Array.isArray(options.export) ? options.export[0] : options.export - ); - exportsInfo.setUsed(UsageState.Used, runtime); - exportsInfo.canMangleUse = false; - } else { - const exportsInfo = moduleGraph.getExportsInfo(module); - exportsInfo.setUsedInUnknownWay(runtime); - } - moduleGraph.addExtraReason(module, "used as library export"); - } - - _getPrefix(compilation) { - return this.prefix === "global" - ? [compilation.runtimeTemplate.globalObject] - : this.prefix; - } - - _getResolvedFullName(options, chunk, compilation) { - const prefix = this._getPrefix(compilation); - const fullName = options.name ? prefix.concat(options.name) : prefix; - return fullName.map(n => - compilation.getPath(n, { - chunk - }) - ); + getModuleEvaluationSideEffectsState(moduleGraph) { + // The expression/declaration is already covered by SideEffectsFlagPlugin + return false; } - /** - * @param {Source} source source - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - render(source, { chunk }, { options, compilation }) { - const fullNameResolved = this._getResolvedFullName( - options, - chunk, - compilation - ); - if (this.declare) { - const base = fullNameResolved[0]; - if (!isNameValid(base)) { - throw new Error( - `Library name base (${base}) must be a valid identifier when using a var declaring library type. Either use a valid identifier (e. g. ${Template.toIdentifier( - base - )}) or use a different library type (e. g. 'type: "global"', which assign a property on the global scope instead of declaring a variable). ${ - AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE - }` - ); - } - source = new ConcatSource(`${this.declare} ${base};\n`, source); - } - return source; + serialize(context) { + const { write } = context; + write(this.range); + write(this.rangeStatement); + write(this.prefix); + write(this.declarationId); + super.serialize(context); } - /** - * @param {Module} module the exporting entry module - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {string | undefined} bailout reason - */ - embedInRuntimeBailout(module, { chunk }, { options, compilation }) { - const topLevelDeclarations = - module.buildInfo && module.buildInfo.topLevelDeclarations; - if (!topLevelDeclarations) - return "it doesn't tell about top level declarations."; - const fullNameResolved = this._getResolvedFullName( - options, - chunk, - compilation - ); - const base = fullNameResolved[0]; - if (topLevelDeclarations.has(base)) - return `it declares '${base}' on top-level, which conflicts with the current library output.`; + deserialize(context) { + const { read } = context; + this.range = read(); + this.rangeStatement = read(); + this.prefix = read(); + this.declarationId = read(); + super.deserialize(context); } +} - /** - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {string | undefined} bailout reason - */ - strictRuntimeBailout({ chunk }, { options, compilation }) { - if ( - this.declare || - this.prefix === "global" || - this.prefix.length > 0 || - !options.name - ) { - return; - } - return "a global variable is assign and maybe created"; - } +makeSerializable( + HarmonyExportExpressionDependency, + "webpack/lib/dependencies/HarmonyExportExpressionDependency" +); +HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTemplate extends ( + NullDependency.Template +) { /** - * @param {Source} source source - * @param {Module} module module - * @param {StartupRenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export + * @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} */ - renderStartup( + apply( + dependency, source, - module, - { moduleGraph, chunk }, - { options, compilation } + { + module, + moduleGraph, + runtimeTemplate, + runtimeRequirements, + initFragments, + runtime, + concatenationScope + } ) { - const fullNameResolved = this._getResolvedFullName( - options, - chunk, - compilation - ); - const staticExports = this.unnamed === "static"; - const exportAccess = options.export - ? propertyAccess( - Array.isArray(options.export) ? options.export : [options.export] - ) - : ""; - const result = new ConcatSource(source); - if (staticExports) { - const exportsInfo = moduleGraph.getExportsInfo(module); - const exportTarget = accessWithInit( - fullNameResolved, - this._getPrefix(compilation).length, - true - ); - for (const exportInfo of exportsInfo.orderedExports) { - if (!exportInfo.provided) continue; - const nameAccess = propertyAccess([exportInfo.name]); - result.add( - `${exportTarget}${nameAccess} = __webpack_exports__${exportAccess}${nameAccess};\n` + const dep = /** @type {HarmonyExportExpressionDependency} */ (dependency); + const { declarationId } = dep; + const exportsName = module.exportsArgument; + if (declarationId) { + let name; + if (typeof declarationId === "string") { + name = declarationId; + } else { + name = ConcatenationScope.DEFAULT_EXPORT; + source.replace( + declarationId.range[0], + declarationId.range[1] - 1, + `${declarationId.prefix}${name}${declarationId.suffix}` ); } - result.add( - `Object.defineProperty(${exportTarget}, "__esModule", { value: true });\n` - ); - } else if (options.name ? this.named === "copy" : this.unnamed === "copy") { - result.add( - `var __webpack_export_target__ = ${accessWithInit( - fullNameResolved, - this._getPrefix(compilation).length, - true - )};\n` - ); - let exports = "__webpack_exports__"; - if (exportAccess) { - result.add( - `var __webpack_exports_export__ = __webpack_exports__${exportAccess};\n` - ); - exports = "__webpack_exports_export__"; + + if (concatenationScope) { + concatenationScope.registerExport("default", name); + } else { + const used = moduleGraph + .getExportsInfo(module) + .getUsedName("default", runtime); + if (used) { + const map = new Map(); + map.set(used, `/* export default binding */ ${name}`); + initFragments.push(new HarmonyExportInitFragment(exportsName, map)); + } } - result.add( - `for(var i in ${exports}) __webpack_export_target__[i] = ${exports}[i];\n` - ); - result.add( - `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n` + + source.replace( + dep.rangeStatement[0], + dep.range[0] - 1, + `/* harmony default export */ ${dep.prefix}` ); } else { - result.add( - `${accessWithInit( - fullNameResolved, - this._getPrefix(compilation).length, - false - )} = __webpack_exports__${exportAccess};\n` - ); - } - return result; - } + let content; + const name = ConcatenationScope.DEFAULT_EXPORT; + if (runtimeTemplate.supportsConst()) { + content = `/* harmony default export */ const ${name} = `; + if (concatenationScope) { + concatenationScope.registerExport("default", name); + } else { + const used = moduleGraph + .getExportsInfo(module) + .getUsedName("default", runtime); + if (used) { + runtimeRequirements.add(RuntimeGlobals.exports); + const map = new Map(); + map.set(used, name); + initFragments.push(new HarmonyExportInitFragment(exportsName, map)); + } else { + content = `/* unused harmony default export */ var ${name} = `; + } + } + } else if (concatenationScope) { + content = `/* harmony default export */ var ${name} = `; + concatenationScope.registerExport("default", name); + } else { + const used = moduleGraph + .getExportsInfo(module) + .getUsedName("default", runtime); + if (used) { + runtimeRequirements.add(RuntimeGlobals.exports); + // This is a little bit incorrect as TDZ is not correct, but we can't use const. + content = `/* harmony default export */ ${exportsName}[${JSON.stringify( + used + )}] = `; + } else { + content = `/* unused harmony default export */ var ${name} = `; + } + } - /** - * @param {Chunk} chunk the chunk - * @param {Set} set runtime requirements - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - runtimeRequirements(chunk, set, libraryContext) { - // we don't need to return exports from runtime - } + if (dep.range) { + source.replace( + dep.rangeStatement[0], + dep.range[0] - 1, + content + "(" + dep.prefix + ); + source.replace(dep.range[1], dep.rangeStatement[1] - 0.5, ");"); + return; + } - /** - * @param {Chunk} chunk the chunk - * @param {Hash} hash hash - * @param {ChunkHashContext} chunkHashContext chunk hash context - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { - hash.update("AssignLibraryPlugin"); - const fullNameResolved = this._getResolvedFullName( - options, - chunk, - compilation - ); - if (options.name ? this.named === "copy" : this.unnamed === "copy") { - hash.update("copy"); - } - if (this.declare) { - hash.update(this.declare); - } - hash.update(fullNameResolved.join(".")); - if (options.export) { - hash.update(`${options.export}`); + source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); } } -} +}; -module.exports = AssignLibraryPlugin; +module.exports = HarmonyExportExpressionDependency; /***/ }), -/***/ 91452: +/***/ 38873: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -96314,252 +89746,69 @@ module.exports = AssignLibraryPlugin; -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Compiler")} Compiler */ +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @type {WeakMap>} */ -const enabledTypes = new WeakMap(); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -const getEnabledTypes = compiler => { - let set = enabledTypes.get(compiler); - if (set === undefined) { - set = new Set(); - enabledTypes.set(compiler, set); +class HarmonyExportHeaderDependency extends NullDependency { + constructor(range, rangeStatement) { + super(); + this.range = range; + this.rangeStatement = rangeStatement; } - return set; -}; -class EnableLibraryPlugin { - /** - * @param {LibraryType} type library type that should be available - */ - constructor(type) { - this.type = type; + get type() { + return "harmony export header"; } - /** - * @param {Compiler} compiler the compiler instance - * @param {LibraryType} type type of library - * @returns {void} - */ - static setEnabled(compiler, type) { - getEnabledTypes(compiler).add(type); + serialize(context) { + const { write } = context; + write(this.range); + write(this.rangeStatement); + super.serialize(context); } - /** - * @param {Compiler} compiler the compiler instance - * @param {LibraryType} type type of library - * @returns {void} - */ - static checkEnabled(compiler, type) { - if (!getEnabledTypes(compiler).has(type)) { - throw new Error( - `Library type "${type}" is not enabled. ` + - "EnableLibraryPlugin need to be used to enable this type of library. " + - 'This usually happens through the "output.enabledLibraryTypes" option. ' + - 'If you are using a function as entry which sets "library", you need to add all potential library types to "output.enabledLibraryTypes". ' + - "These types are enabled: " + - Array.from(getEnabledTypes(compiler)).join(", ") - ); - } + deserialize(context) { + const { read } = context; + this.range = read(); + this.rangeStatement = read(); + super.deserialize(context); } +} + +makeSerializable( + HarmonyExportHeaderDependency, + "webpack/lib/dependencies/HarmonyExportHeaderDependency" +); +HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate extends ( + NullDependency.Template +) { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - const { type } = this; - - // Only enable once - const enabled = getEnabledTypes(compiler); - if (enabled.has(type)) return; - enabled.add(type); - - if (typeof type === "string") { - const enableExportProperty = () => { - const ExportPropertyTemplatePlugin = __webpack_require__(5487); - new ExportPropertyTemplatePlugin({ - type, - nsObjectUsed: type !== "module" - }).apply(compiler); - }; - switch (type) { - case "var": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: [], - declare: "var", - unnamed: "error" - }).apply(compiler); - break; - } - case "assign-properties": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: [], - declare: false, - unnamed: "error", - named: "copy" - }).apply(compiler); - break; - } - case "assign": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: [], - declare: false, - unnamed: "error" - }).apply(compiler); - break; - } - case "this": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: ["this"], - declare: false, - unnamed: "copy" - }).apply(compiler); - break; - } - case "window": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: ["window"], - declare: false, - unnamed: "copy" - }).apply(compiler); - break; - } - case "self": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: ["self"], - declare: false, - unnamed: "copy" - }).apply(compiler); - break; - } - case "global": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: "global", - declare: false, - unnamed: "copy" - }).apply(compiler); - break; - } - case "commonjs": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: ["exports"], - declare: false, - unnamed: "copy" - }).apply(compiler); - break; - } - case "commonjs-static": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: ["exports"], - declare: false, - unnamed: "static" - }).apply(compiler); - break; - } - case "commonjs2": - case "commonjs-module": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: ["module", "exports"], - declare: false, - unnamed: "assign" - }).apply(compiler); - break; - } - case "amd": - case "amd-require": { - enableExportProperty(); - const AmdLibraryPlugin = __webpack_require__(67416); - new AmdLibraryPlugin({ - type, - requireAsWrapper: type === "amd-require" - }).apply(compiler); - break; - } - case "umd": - case "umd2": { - enableExportProperty(); - const UmdLibraryPlugin = __webpack_require__(54442); - new UmdLibraryPlugin({ - type, - optionalAmdExternalAsGlobal: type === "umd2" - }).apply(compiler); - break; - } - case "system": { - enableExportProperty(); - const SystemLibraryPlugin = __webpack_require__(11707); - new SystemLibraryPlugin({ - type - }).apply(compiler); - break; - } - case "jsonp": { - enableExportProperty(); - const JsonpLibraryPlugin = __webpack_require__(84415); - new JsonpLibraryPlugin({ - type - }).apply(compiler); - break; - } - case "module": { - enableExportProperty(); - const ModuleLibraryPlugin = __webpack_require__(59780); - new ModuleLibraryPlugin({ - type - }).apply(compiler); - break; - } - default: - throw new Error(`Unsupported library type ${type}. -Plugins which provide custom library types must call EnableLibraryPlugin.setEnabled(compiler, type) to disable this error.`); - } - } else { - // TODO support plugin instances here - // apply them to the compiler - } + apply(dependency, source, templateContext) { + const dep = /** @type {HarmonyExportHeaderDependency} */ (dependency); + const content = ""; + const replaceUntil = dep.range + ? dep.range[0] - 1 + : dep.rangeStatement[1] - 1; + source.replace(dep.rangeStatement[0], replaceUntil, content); } -} +}; -module.exports = EnableLibraryPlugin; +module.exports = HarmonyExportHeaderDependency; /***/ }), -/***/ 5487: +/***/ 67157: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -96570,1069 +89819,1275 @@ module.exports = EnableLibraryPlugin; -const { ConcatSource } = __webpack_require__(51255); +const Dependency = __webpack_require__(54912); const { UsageState } = __webpack_require__(63686); +const HarmonyLinkingError = __webpack_require__(97511); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const { countIterable } = __webpack_require__(39104); +const { first, combine } = __webpack_require__(93347); +const makeSerializable = __webpack_require__(33032); const propertyAccess = __webpack_require__(54190); -const { getEntryRuntime } = __webpack_require__(17156); -const AbstractLibraryPlugin = __webpack_require__(26030); +const { getRuntimeKey, keyToRuntime } = __webpack_require__(17156); +const HarmonyExportInitFragment = __webpack_require__(89500); +const HarmonyImportDependency = __webpack_require__(57154); +const processExportInfo = __webpack_require__(55207); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ExportsInfo")} ExportsInfo */ +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ /** @typedef {import("../Module")} Module */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ +/** @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} ExportPropertyLibraryPluginParsed - * @property {string | string[]} export - */ +/** @typedef {"missing"|"unused"|"empty-star"|"reexport-dynamic-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-fake-namespace-object"|"reexport-undefined"|"normal-reexport"|"dynamic-reexport"} ExportModeType */ -/** - * @typedef {Object} ExportPropertyLibraryPluginOptions - * @property {LibraryType} type - * @property {boolean} nsObjectUsed the namespace object is used - */ -/** - * @typedef {ExportPropertyLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} - */ -class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin { - /** - * @param {ExportPropertyLibraryPluginOptions} options options - */ - constructor({ type, nsObjectUsed }) { - super({ - pluginName: "ExportPropertyLibraryPlugin", - type - }); - this.nsObjectUsed = nsObjectUsed; - } +const { ExportPresenceModes } = HarmonyImportDependency; - /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - parseOptions(library) { - return { - export: library.export - }; - } +const idsSymbol = Symbol("HarmonyExportImportedSpecifierDependency.ids"); +class NormalReexportItem { /** - * @param {Module} module the exporting entry module - * @param {string} entryName the name of the entrypoint - * @param {LibraryContext} libraryContext context - * @returns {void} + * @param {string} name export name + * @param {string[]} ids reexported ids from other module + * @param {ExportInfo} exportInfo export info from other module + * @param {boolean} checked true, if it should be checked at runtime if this export exists + * @param {boolean} hidden true, if it is hidden behind another active export in the same module */ - finishEntryModule( - module, - entryName, - { options, compilation, compilation: { moduleGraph } } - ) { - const runtime = getEntryRuntime(compilation, entryName); - if (options.export) { - const exportsInfo = moduleGraph.getExportInfo( - module, - Array.isArray(options.export) ? options.export[0] : options.export - ); - exportsInfo.setUsed(UsageState.Used, runtime); - exportsInfo.canMangleUse = false; - } else { - const exportsInfo = moduleGraph.getExportsInfo(module); - if (this.nsObjectUsed) { - exportsInfo.setUsedInUnknownWay(runtime); - } else { - exportsInfo.setAllKnownExportsUsed(runtime); - } - } - moduleGraph.addExtraReason(module, "used as library export"); + constructor(name, ids, exportInfo, checked, hidden) { + this.name = name; + this.ids = ids; + this.exportInfo = exportInfo; + this.checked = checked; + this.hidden = hidden; } +} +class ExportMode { /** - * @param {Chunk} chunk the chunk - * @param {Set} set runtime requirements - * @param {LibraryContext} libraryContext context - * @returns {void} + * @param {ExportModeType} type type of the mode */ - runtimeRequirements(chunk, set, libraryContext) {} + constructor(type) { + /** @type {ExportModeType} */ + this.type = type; - /** - * @param {Source} source source - * @param {Module} module module - * @param {StartupRenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - renderStartup(source, module, renderContext, { options }) { - if (!options.export) return source; - const postfix = `__webpack_exports__ = __webpack_exports__${propertyAccess( - Array.isArray(options.export) ? options.export : [options.export] - )};\n`; - return new ConcatSource(source, postfix); - } -} + // for "normal-reexport": + /** @type {NormalReexportItem[] | null} */ + this.items = null; -module.exports = ExportPropertyLibraryPlugin; + // for "reexport-named-default" | "reexport-fake-namespace-object" | "reexport-namespace-object" + /** @type {string|null} */ + this.name = null; + /** @type {ExportInfo | null} */ + this.partialNamespaceExportInfo = null; + // for "dynamic-reexport": + /** @type {Set | null} */ + this.ignored = null; -/***/ }), + // for "dynamic-reexport" | "empty-star": + /** @type {Set | null} */ + this.hidden = null; -/***/ 84415: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // for "missing": + /** @type {string | null} */ + this.userRequest = null; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // for "reexport-fake-namespace-object": + /** @type {number} */ + this.fakeType = 0; + } +} +const determineExportAssignments = ( + moduleGraph, + dependencies, + additionalDependency +) => { + const names = new Set(); + const dependencyIndices = []; + if (additionalDependency) { + dependencies = dependencies.concat(additionalDependency); + } -const { ConcatSource } = __webpack_require__(51255); -const AbstractLibraryPlugin = __webpack_require__(26030); + for (const dep of dependencies) { + const i = dependencyIndices.length; + dependencyIndices[i] = names.size; + const otherImportedModule = moduleGraph.getModule(dep); + if (otherImportedModule) { + const exportsInfo = moduleGraph.getExportsInfo(otherImportedModule); + for (const exportInfo of exportsInfo.exports) { + if ( + exportInfo.provided === true && + exportInfo.name !== "default" && + !names.has(exportInfo.name) + ) { + names.add(exportInfo.name); + dependencyIndices[i] = names.size; + } + } + } + } + dependencyIndices.push(names.size); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + return { names: Array.from(names), dependencyIndices }; +}; -/** - * @typedef {Object} JsonpLibraryPluginOptions - * @property {LibraryType} type - */ +const findDependencyForName = ( + { names, dependencyIndices }, + name, + dependencies +) => { + const dependenciesIt = dependencies[Symbol.iterator](); + const dependencyIndicesIt = dependencyIndices[Symbol.iterator](); + let dependenciesItResult = dependenciesIt.next(); + let dependencyIndicesItResult = dependencyIndicesIt.next(); + if (dependencyIndicesItResult.done) return; + for (let i = 0; i < names.length; i++) { + while (i >= dependencyIndicesItResult.value) { + dependenciesItResult = dependenciesIt.next(); + dependencyIndicesItResult = dependencyIndicesIt.next(); + if (dependencyIndicesItResult.done) return; + } + if (names[i] === name) return dependenciesItResult.value; + } + return undefined; +}; /** - * @typedef {Object} JsonpLibraryPluginParsed - * @property {string} name + * @param {ModuleGraph} moduleGraph the module graph + * @param {HarmonyExportImportedSpecifierDependency} dep the dependency + * @param {string} runtimeKey the runtime key + * @returns {ExportMode} the export mode */ +const getMode = (moduleGraph, dep, runtimeKey) => { + const importedModule = moduleGraph.getModule(dep); -/** - * @typedef {JsonpLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} - */ -class JsonpLibraryPlugin extends AbstractLibraryPlugin { - /** - * @param {JsonpLibraryPluginOptions} options the plugin options - */ - constructor(options) { - super({ - pluginName: "JsonpLibraryPlugin", - type: options.type - }); - } + if (!importedModule) { + const mode = new ExportMode("missing"); - /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - parseOptions(library) { - const { name } = library; - if (typeof name !== "string") { - throw new Error( - `Jsonp library name must be a simple string. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); - } - return { - name: /** @type {string} */ (name) - }; - } + mode.userRequest = dep.userRequest; - /** - * @param {Source} source source - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - render(source, { chunk }, { options, compilation }) { - const name = compilation.getPath(options.name, { - chunk - }); - return new ConcatSource(`${name}(`, source, ")"); + return mode; } - /** - * @param {Chunk} chunk the chunk - * @param {Hash} hash hash - * @param {ChunkHashContext} chunkHashContext chunk hash context - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { - hash.update("JsonpLibraryPlugin"); - hash.update(compilation.getPath(options.name, { chunk })); + const name = dep.name; + const runtime = keyToRuntime(runtimeKey); + const parentModule = moduleGraph.getParentModule(dep); + const exportsInfo = moduleGraph.getExportsInfo(parentModule); + + if ( + name + ? exportsInfo.getUsed(name, runtime) === UsageState.Unused + : exportsInfo.isUsed(runtime) === false + ) { + const mode = new ExportMode("unused"); + + mode.name = name || "*"; + + return mode; } -} -module.exports = JsonpLibraryPlugin; + const importedExportsType = importedModule.getExportsType( + moduleGraph, + parentModule.buildMeta.strictHarmonyModule + ); + const ids = dep.getIds(moduleGraph); -/***/ }), + // Special handling for reexporting the default export + // from non-namespace modules + if (name && ids.length > 0 && ids[0] === "default") { + switch (importedExportsType) { + case "dynamic": { + const mode = new ExportMode("reexport-dynamic-default"); -/***/ 59780: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + mode.name = name; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return mode; + } + case "default-only": + case "default-with-named": { + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + const mode = new ExportMode("reexport-named-default"); + mode.name = name; + mode.partialNamespaceExportInfo = exportInfo; + return mode; + } + } + } -const { ConcatSource } = __webpack_require__(51255); -const Template = __webpack_require__(1626); -const propertyAccess = __webpack_require__(54190); -const AbstractLibraryPlugin = __webpack_require__(26030); + // reexporting with a fixed name + if (name) { + let mode; + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + if (ids.length > 0) { + // export { name as name } + switch (importedExportsType) { + case "default-only": + mode = new ExportMode("reexport-undefined"); + mode.name = name; + break; + default: + mode = new ExportMode("normal-reexport"); + mode.items = [ + new NormalReexportItem(name, ids, exportInfo, false, false) + ]; + break; + } + } else { + // export * as name + switch (importedExportsType) { + case "default-only": + mode = new ExportMode("reexport-fake-namespace-object"); + mode.name = name; + mode.partialNamespaceExportInfo = exportInfo; + mode.fakeType = 0; + break; + case "default-with-named": + mode = new ExportMode("reexport-fake-namespace-object"); + mode.name = name; + mode.partialNamespaceExportInfo = exportInfo; + mode.fakeType = 2; + break; + case "dynamic": + default: + mode = new ExportMode("reexport-namespace-object"); + mode.name = name; + mode.partialNamespaceExportInfo = exportInfo; + } + } -/** - * @typedef {Object} ModuleLibraryPluginOptions - * @property {LibraryType} type - */ + return mode; + } -/** - * @typedef {Object} ModuleLibraryPluginParsed - * @property {string} name - */ + // Star reexporting -/** - * @typedef {ModuleLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} - */ -class ModuleLibraryPlugin extends AbstractLibraryPlugin { - /** - * @param {ModuleLibraryPluginOptions} options the plugin options - */ - constructor(options) { - super({ - pluginName: "ModuleLibraryPlugin", - type: options.type - }); + const { ignoredExports, exports, checked, hidden } = dep.getStarReexports( + moduleGraph, + runtime, + exportsInfo, + importedModule + ); + if (!exports) { + // We have too few info about the modules + // Delegate the logic to the runtime code + + const mode = new ExportMode("dynamic-reexport"); + mode.ignored = ignoredExports; + mode.hidden = hidden; + + return mode; } - /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - parseOptions(library) { - const { name } = library; - if (name) { - throw new Error( - `Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); - } - return { - name: /** @type {string} */ (name) - }; + if (exports.size === 0) { + const mode = new ExportMode("empty-star"); + mode.hidden = hidden; + + return mode; } - /** - * @param {Source} source source - * @param {Module} module module - * @param {StartupRenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - renderStartup( - source, - module, - { moduleGraph, chunk }, - { options, compilation } - ) { - const result = new ConcatSource(source); - const exportsInfo = moduleGraph.getExportsInfo(module); - const exports = []; - const isAsync = moduleGraph.isAsync(module); - if (isAsync) { - result.add(`__webpack_exports__ = await __webpack_exports__;\n`); - } - for (const exportInfo of exportsInfo.orderedExports) { - if (!exportInfo.provided) continue; - const varName = `__webpack_exports__${Template.toIdentifier( - exportInfo.name - )}`; - result.add( - `var ${varName} = __webpack_exports__${propertyAccess([ - exportInfo.getUsedName(exportInfo.name, chunk.runtime) - ])};\n` + const mode = new ExportMode("normal-reexport"); + + mode.items = Array.from( + exports, + exportName => + new NormalReexportItem( + exportName, + [exportName], + exportsInfo.getReadOnlyExportInfo(exportName), + checked.has(exportName), + false + ) + ); + if (hidden !== undefined) { + for (const exportName of hidden) { + mode.items.push( + new NormalReexportItem( + exportName, + [exportName], + exportsInfo.getReadOnlyExportInfo(exportName), + false, + true + ) ); - exports.push(`${varName} as ${exportInfo.name}`); - } - if (exports.length > 0) { - result.add(`export { ${exports.join(", ")} };\n`); } - return result; } -} - -module.exports = ModuleLibraryPlugin; - - -/***/ }), -/***/ 11707: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + return mode; +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Joel Denning @joeldenning -*/ +class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { + /** + * @param {string} request the request string + * @param {number} sourceOrder the order in the original source file + * @param {string[]} ids the requested export name of the imported module + * @param {string | null} name the export name of for this module + * @param {Set} activeExports other named exports in the module + * @param {ReadonlyArray | Iterable} otherStarExports other star exports in the module before this import + * @param {number} exportPresenceMode mode of checking export names + * @param {HarmonyStarExportsList} allStarExports all star exports in the module + * @param {Record=} assertions import assertions + */ + constructor( + request, + sourceOrder, + ids, + name, + activeExports, + otherStarExports, + exportPresenceMode, + allStarExports, + assertions + ) { + super(request, sourceOrder, assertions); + this.ids = ids; + this.name = name; + this.activeExports = activeExports; + this.otherStarExports = otherStarExports; + this.exportPresenceMode = exportPresenceMode; + this.allStarExports = allStarExports; + } + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return Dependency.TRANSITIVE; + } -const { ConcatSource } = __webpack_require__(51255); -const { UsageState } = __webpack_require__(63686); -const ExternalModule = __webpack_require__(73071); -const Template = __webpack_require__(1626); -const propertyAccess = __webpack_require__(54190); -const AbstractLibraryPlugin = __webpack_require__(26030); + // TODO webpack 6 remove + get id() { + throw new Error("id was renamed to ids and type changed to string[]"); + } -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + // TODO webpack 6 remove + getId() { + throw new Error("id was renamed to ids and type changed to string[]"); + } -/** - * @typedef {Object} SystemLibraryPluginOptions - * @property {LibraryType} type - */ + // TODO webpack 6 remove + setId() { + throw new Error("id was renamed to ids and type changed to string[]"); + } -/** - * @typedef {Object} SystemLibraryPluginParsed - * @property {string} name - */ + get type() { + return "harmony export imported specifier"; + } -/** - * @typedef {SystemLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} - */ -class SystemLibraryPlugin extends AbstractLibraryPlugin { /** - * @param {SystemLibraryPluginOptions} options the plugin options + * @param {ModuleGraph} moduleGraph the module graph + * @returns {string[]} the imported id */ - constructor(options) { - super({ - pluginName: "SystemLibraryPlugin", - type: options.type - }); + getIds(moduleGraph) { + return moduleGraph.getMeta(this)[idsSymbol] || this.ids; } /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding + * @param {ModuleGraph} moduleGraph the module graph + * @param {string[]} ids the imported ids + * @returns {void} */ - parseOptions(library) { - const { name } = library; - if (name && typeof name !== "string") { - throw new Error( - `System.js library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); - } - return { - name: /** @type {string=} */ (name) - }; + setIds(moduleGraph, ids) { + moduleGraph.getMeta(this)[idsSymbol] = ids; } /** - * @param {Source} source source - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @returns {ExportMode} the export mode */ - render(source, { chunkGraph, moduleGraph, chunk }, { options, compilation }) { - const modules = chunkGraph - .getChunkModules(chunk) - .filter(m => m instanceof ExternalModule && m.externalType === "system"); - const externals = /** @type {ExternalModule[]} */ (modules); + getMode(moduleGraph, runtime) { + return moduleGraph.dependencyCacheProvide( + this, + getRuntimeKey(runtime), + getMode + ); + } - // The name this bundle should be registered as with System - const name = options.name - ? `${JSON.stringify(compilation.getPath(options.name, { chunk }))}, ` - : ""; + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @param {ExportsInfo} exportsInfo exports info about the current module (optional) + * @param {Module} importedModule the imported module (optional) + * @returns {{exports?: Set, checked?: Set, ignoredExports: Set, hidden?: Set}} information + */ + getStarReexports( + moduleGraph, + runtime, + exportsInfo = moduleGraph.getExportsInfo(moduleGraph.getParentModule(this)), + importedModule = moduleGraph.getModule(this) + ) { + const importedExportsInfo = moduleGraph.getExportsInfo(importedModule); - // The array of dependencies that are external to webpack and will be provided by System - const systemDependencies = JSON.stringify( - externals.map(m => - typeof m.request === "object" && !Array.isArray(m.request) - ? m.request.amd - : m.request - ) - ); + const noExtraExports = + importedExportsInfo.otherExportsInfo.provided === false; + const noExtraImports = + exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused; - // The name of the variable provided by System for exporting - const dynamicExport = "__WEBPACK_DYNAMIC_EXPORT__"; + const ignoredExports = new Set(["default", ...this.activeExports]); - // An array of the internal variable names for the webpack externals - const externalWebpackNames = externals.map( - m => - `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( - `${chunkGraph.getModuleId(m)}` - )}__` - ); + let hiddenExports = undefined; + const otherStarExports = + this._discoverActiveExportsFromOtherStarExports(moduleGraph); + if (otherStarExports !== undefined) { + hiddenExports = new Set(); + for (let i = 0; i < otherStarExports.namesSlice; i++) { + hiddenExports.add(otherStarExports.names[i]); + } + for (const e of ignoredExports) hiddenExports.delete(e); + } - // Declaring variables for the internal variable names for the webpack externals - const externalVarDeclarations = externalWebpackNames - .map(name => `var ${name} = {};`) - .join("\n"); + if (!noExtraExports && !noExtraImports) { + return { + ignoredExports, + hidden: hiddenExports + }; + } - // Define __esModule flag on all internal variables and helpers - const externalVarInitialization = []; + /** @type {Set} */ + const exports = new Set(); + /** @type {Set} */ + const checked = new Set(); + /** @type {Set} */ + const hidden = hiddenExports !== undefined ? new Set() : undefined; - // The system.register format requires an array of setter functions for externals. - const setters = - externalWebpackNames.length === 0 - ? "" - : Template.asString([ - "setters: [", - Template.indent( - externals - .map((module, i) => { - const external = externalWebpackNames[i]; - const exportsInfo = moduleGraph.getExportsInfo(module); - const otherUnused = - exportsInfo.otherExportsInfo.getUsed(chunk.runtime) === - UsageState.Unused; - const instructions = []; - const handledNames = []; - for (const exportInfo of exportsInfo.orderedExports) { - const used = exportInfo.getUsedName( - undefined, - chunk.runtime - ); - if (used) { - if (otherUnused || used !== exportInfo.name) { - instructions.push( - `${external}${propertyAccess([ - used - ])} = module${propertyAccess([exportInfo.name])};` - ); - handledNames.push(exportInfo.name); - } - } else { - handledNames.push(exportInfo.name); - } - } - if (!otherUnused) { - if ( - !Array.isArray(module.request) || - module.request.length === 1 - ) { - externalVarInitialization.push( - `Object.defineProperty(${external}, "__esModule", { value: true });` - ); - } - if (handledNames.length > 0) { - const name = `${external}handledNames`; - externalVarInitialization.push( - `var ${name} = ${JSON.stringify(handledNames)};` - ); - instructions.push( - Template.asString([ - "Object.keys(module).forEach(function(key) {", - Template.indent([ - `if(${name}.indexOf(key) >= 0)`, - Template.indent(`${external}[key] = module[key];`) - ]), - "});" - ]) - ); - } else { - instructions.push( - Template.asString([ - "Object.keys(module).forEach(function(key) {", - Template.indent([`${external}[key] = module[key];`]), - "});" - ]) - ); - } - } - if (instructions.length === 0) return "function() {}"; - return Template.asString([ - "function(module) {", - Template.indent(instructions), - "}" - ]); - }) - .join(",\n") - ), - "]," - ]); + if (noExtraImports) { + for (const exportInfo of exportsInfo.orderedExports) { + const name = exportInfo.name; + if (ignoredExports.has(name)) continue; + if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; + const importedExportInfo = + importedExportsInfo.getReadOnlyExportInfo(name); + if (importedExportInfo.provided === false) continue; + if (hiddenExports !== undefined && hiddenExports.has(name)) { + hidden.add(name); + continue; + } + exports.add(name); + if (importedExportInfo.provided === true) continue; + checked.add(name); + } + } else if (noExtraExports) { + for (const importedExportInfo of importedExportsInfo.orderedExports) { + const name = importedExportInfo.name; + if (ignoredExports.has(name)) continue; + if (importedExportInfo.provided === false) continue; + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; + if (hiddenExports !== undefined && hiddenExports.has(name)) { + hidden.add(name); + continue; + } + exports.add(name); + if (importedExportInfo.provided === true) continue; + checked.add(name); + } + } - return new ConcatSource( - Template.asString([ - `System.register(${name}${systemDependencies}, function(${dynamicExport}, __system_context__) {`, - Template.indent([ - externalVarDeclarations, - Template.asString(externalVarInitialization), - "return {", - Template.indent([ - setters, - "execute: function() {", - Template.indent(`${dynamicExport}(`) - ]) - ]), - "" - ]), - source, - Template.asString([ - "", - Template.indent([ - Template.indent([Template.indent([");"]), "}"]), - "};" - ]), - "})" - ]) - ); + return { ignoredExports, exports, checked, hidden }; } /** - * @param {Chunk} chunk the chunk - * @param {Hash} hash hash - * @param {ChunkHashContext} chunkHashContext chunk hash context - * @param {LibraryContext} libraryContext context - * @returns {void} + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active */ - chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { - hash.update("SystemLibraryPlugin"); - if (options.name) { - hash.update(compilation.getPath(options.name, { chunk })); - } + getCondition(moduleGraph) { + return (connection, runtime) => { + const mode = this.getMode(moduleGraph, runtime); + return mode.type !== "unused" && mode.type !== "empty-star"; + }; } -} - -module.exports = SystemLibraryPlugin; - - -/***/ }), - -/***/ 54442: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } + /** + * 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) { + const mode = this.getMode(moduleGraph, runtime); -const { ConcatSource, OriginalSource } = __webpack_require__(51255); -const ExternalModule = __webpack_require__(73071); -const Template = __webpack_require__(1626); -const AbstractLibraryPlugin = __webpack_require__(26030); + switch (mode.type) { + case "missing": + case "unused": + case "empty-star": + case "reexport-undefined": + return Dependency.NO_EXPORTS_REFERENCED; -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryCustomUmdCommentObject} LibraryCustomUmdCommentObject */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + case "reexport-dynamic-default": + return Dependency.EXPORTS_OBJECT_REFERENCED; -/** - * @param {string[]} accessor the accessor to convert to path - * @returns {string} the path - */ -const accessorToObjectAccess = accessor => { - return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); -}; + case "reexport-named-default": { + if (!mode.partialNamespaceExportInfo) + return Dependency.EXPORTS_OBJECT_REFERENCED; + /** @type {string[][]} */ + const referencedExports = []; + processExportInfo( + runtime, + referencedExports, + [], + /** @type {ExportInfo} */ (mode.partialNamespaceExportInfo) + ); + return referencedExports; + } -/** - * @param {string|undefined} base the path prefix - * @param {string|string[]} accessor the accessor - * @param {string=} joinWith the element separator - * @returns {string} the path - */ -const accessorAccess = (base, accessor, joinWith = ", ") => { - const accessors = Array.isArray(accessor) ? accessor : [accessor]; - return accessors - .map((_, idx) => { - const a = base - ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) - : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); - if (idx === accessors.length - 1) return a; - if (idx === 0 && base === undefined) - return `${a} = typeof ${a} === "object" ? ${a} : {}`; - return `${a} = ${a} || {}`; - }) - .join(joinWith); -}; + case "reexport-namespace-object": + case "reexport-fake-namespace-object": { + if (!mode.partialNamespaceExportInfo) + return Dependency.EXPORTS_OBJECT_REFERENCED; + /** @type {string[][]} */ + const referencedExports = []; + processExportInfo( + runtime, + referencedExports, + [], + /** @type {ExportInfo} */ (mode.partialNamespaceExportInfo), + mode.type === "reexport-fake-namespace-object" + ); + return referencedExports; + } -/** @typedef {string | string[] | LibraryCustomUmdObject} UmdLibraryPluginName */ + case "dynamic-reexport": + return Dependency.EXPORTS_OBJECT_REFERENCED; -/** - * @typedef {Object} UmdLibraryPluginOptions - * @property {LibraryType} type - * @property {boolean=} optionalAmdExternalAsGlobal - */ + case "normal-reexport": { + const referencedExports = []; + for (const { ids, exportInfo, hidden } of mode.items) { + if (hidden) continue; + processExportInfo(runtime, referencedExports, ids, exportInfo, false); + } + return referencedExports; + } -/** - * @typedef {Object} UmdLibraryPluginParsed - * @property {string | string[]} name - * @property {LibraryCustomUmdObject} names - * @property {string | LibraryCustomUmdCommentObject} auxiliaryComment - * @property {boolean} namedDefine - */ + default: + throw new Error(`Unknown mode ${mode.type}`); + } + } -/** - * @typedef {UmdLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} - */ -class UmdLibraryPlugin extends AbstractLibraryPlugin { /** - * @param {UmdLibraryPluginOptions} options the plugin option + * @param {ModuleGraph} moduleGraph the module graph + * @returns {{ names: string[], namesSlice: number, dependencyIndices: number[], dependencyIndex: number } | undefined} exported names and their origin dependency */ - constructor(options) { - super({ - pluginName: "UmdLibraryPlugin", - type: options.type - }); + _discoverActiveExportsFromOtherStarExports(moduleGraph) { + if (!this.otherStarExports) return undefined; - this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal; - } + const i = + "length" in this.otherStarExports + ? this.otherStarExports.length + : countIterable(this.otherStarExports); + if (i === 0) return undefined; - /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - parseOptions(library) { - /** @type {LibraryName} */ - let name; - /** @type {LibraryCustomUmdObject} */ - let names; - if (typeof library.name === "object" && !Array.isArray(library.name)) { - name = library.name.root || library.name.amd || library.name.commonjs; - names = library.name; - } else { - name = library.name; - const singleName = Array.isArray(name) ? name[0] : name; - names = { - commonjs: singleName, - root: library.name, - amd: singleName + if (this.allStarExports) { + const { names, dependencyIndices } = moduleGraph.cached( + determineExportAssignments, + this.allStarExports.dependencies + ); + + return { + names, + namesSlice: dependencyIndices[i - 1], + dependencyIndices, + dependencyIndex: i }; } + + const { names, dependencyIndices } = moduleGraph.cached( + determineExportAssignments, + this.otherStarExports, + this + ); + return { - name, names, - auxiliaryComment: library.auxiliaryComment, - namedDefine: library.umdNamedDefine + namesSlice: dependencyIndices[i - 1], + dependencyIndices, + dependencyIndex: i }; } /** - * @param {Source} source source - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - render( - source, - { chunkGraph, runtimeTemplate, chunk, moduleGraph }, - { options, compilation } - ) { - const modules = chunkGraph - .getChunkModules(chunk) - .filter( - m => - m instanceof ExternalModule && - (m.externalType === "umd" || m.externalType === "umd2") - ); - let externals = /** @type {ExternalModule[]} */ (modules); - /** @type {ExternalModule[]} */ - const optionalExternals = []; - /** @type {ExternalModule[]} */ - let requiredExternals = []; - if (this.optionalAmdExternalAsGlobal) { - for (const m of externals) { - if (m.isOptional(moduleGraph)) { - optionalExternals.push(m); - } else { - requiredExternals.push(m); + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + const mode = this.getMode(moduleGraph, undefined); + + switch (mode.type) { + case "missing": + return undefined; + case "dynamic-reexport": { + const from = moduleGraph.getConnection(this); + return { + exports: true, + from, + canMangle: false, + excludeExports: mode.hidden + ? combine(mode.ignored, mode.hidden) + : mode.ignored, + hideExports: mode.hidden, + dependencies: [from.module] + }; + } + case "empty-star": + return { + exports: [], + hideExports: mode.hidden, + dependencies: [moduleGraph.getModule(this)] + }; + // falls through + case "normal-reexport": { + const from = moduleGraph.getConnection(this); + return { + exports: Array.from(mode.items, item => ({ + name: item.name, + from, + export: item.ids, + hidden: item.hidden + })), + priority: 1, + dependencies: [from.module] + }; + } + case "reexport-dynamic-default": { + { + const from = moduleGraph.getConnection(this); + return { + exports: [ + { + name: mode.name, + from, + export: ["default"] + } + ], + priority: 1, + dependencies: [from.module] + }; } } - externals = requiredExternals.concat(optionalExternals); - } else { - requiredExternals = externals; + case "reexport-undefined": + return { + exports: [mode.name], + dependencies: [moduleGraph.getModule(this)] + }; + case "reexport-fake-namespace-object": { + const from = moduleGraph.getConnection(this); + return { + exports: [ + { + name: mode.name, + from, + export: null, + exports: [ + { + name: "default", + canMangle: false, + from, + export: null + } + ] + } + ], + priority: 1, + dependencies: [from.module] + }; + } + case "reexport-namespace-object": { + const from = moduleGraph.getConnection(this); + return { + exports: [ + { + name: mode.name, + from, + export: null + } + ], + priority: 1, + dependencies: [from.module] + }; + } + case "reexport-named-default": { + const from = moduleGraph.getConnection(this); + return { + exports: [ + { + name: mode.name, + from, + export: ["default"] + } + ], + priority: 1, + dependencies: [from.module] + }; + } + default: + throw new Error(`Unknown mode ${mode.type}`); } + } - const replaceKeys = str => { - return compilation.getPath(str, { - chunk - }); - }; + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {number} effective mode + */ + _getEffectiveExportPresenceLevel(moduleGraph) { + if (this.exportPresenceMode !== ExportPresenceModes.AUTO) + return this.exportPresenceMode; + return moduleGraph.getParentModule(this).buildMeta.strictHarmonyModule + ? ExportPresenceModes.ERROR + : ExportPresenceModes.WARN; + } - const externalsDepsArray = modules => { - return `[${replaceKeys( - modules - .map(m => - JSON.stringify( - typeof m.request === "object" ? m.request.amd : m.request - ) - ) - .join(", ") - )}]`; - }; + /** + * Returns warnings + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} warnings + */ + getWarnings(moduleGraph) { + const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); + if (exportsPresence === ExportPresenceModes.WARN) { + return this._getErrors(moduleGraph); + } + return null; + } - const externalsRootArray = modules => { - return replaceKeys( - modules - .map(m => { - let request = m.request; - if (typeof request === "object") request = request.root; - return `root${accessorToObjectAccess([].concat(request))}`; - }) - .join(", ") - ); - }; + /** + * Returns errors + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} errors + */ + getErrors(moduleGraph) { + const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); + if (exportsPresence === ExportPresenceModes.ERROR) { + return this._getErrors(moduleGraph); + } + return null; + } - const externalsRequireArray = type => { - return replaceKeys( - externals - .map(m => { - let expr; - let request = m.request; - if (typeof request === "object") { - request = request[type]; - } - if (request === undefined) { - throw new Error( - "Missing external configuration for type:" + type - ); - } - if (Array.isArray(request)) { - expr = `require(${JSON.stringify( - request[0] - )})${accessorToObjectAccess(request.slice(1))}`; + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | undefined} errors + */ + _getErrors(moduleGraph) { + const ids = this.getIds(moduleGraph); + let errors = this.getLinkingErrors( + moduleGraph, + ids, + `(reexported as '${this.name}')` + ); + if (ids.length === 0 && this.name === null) { + const potentialConflicts = + this._discoverActiveExportsFromOtherStarExports(moduleGraph); + if (potentialConflicts && potentialConflicts.namesSlice > 0) { + const ownNames = new Set( + potentialConflicts.names.slice( + potentialConflicts.namesSlice, + potentialConflicts.dependencyIndices[ + potentialConflicts.dependencyIndex + ] + ) + ); + const importedModule = moduleGraph.getModule(this); + if (importedModule) { + const exportsInfo = moduleGraph.getExportsInfo(importedModule); + const conflicts = new Map(); + for (const exportInfo of exportsInfo.orderedExports) { + if (exportInfo.provided !== true) continue; + if (exportInfo.name === "default") continue; + if (this.activeExports.has(exportInfo.name)) continue; + if (ownNames.has(exportInfo.name)) continue; + const conflictingDependency = findDependencyForName( + potentialConflicts, + exportInfo.name, + this.allStarExports + ? this.allStarExports.dependencies + : [...this.otherStarExports, this] + ); + if (!conflictingDependency) continue; + const target = exportInfo.getTerminalBinding(moduleGraph); + if (!target) continue; + const conflictingModule = moduleGraph.getModule( + conflictingDependency + ); + if (conflictingModule === importedModule) continue; + const conflictingExportInfo = moduleGraph.getExportInfo( + conflictingModule, + exportInfo.name + ); + const conflictingTarget = + conflictingExportInfo.getTerminalBinding(moduleGraph); + if (!conflictingTarget) continue; + if (target === conflictingTarget) continue; + const list = conflicts.get(conflictingDependency.request); + if (list === undefined) { + conflicts.set(conflictingDependency.request, [exportInfo.name]); } else { - expr = `require(${JSON.stringify(request)})`; - } - if (m.isOptional(moduleGraph)) { - expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; + list.push(exportInfo.name); } - return expr; - }) - .join(", ") - ); - }; + } + for (const [request, exports] of conflicts) { + if (!errors) errors = []; + errors.push( + new HarmonyLinkingError( + `The requested module '${ + this.request + }' contains conflicting star exports for the ${ + exports.length > 1 ? "names" : "name" + } ${exports + .map(e => `'${e}'`) + .join(", ")} with the previous requested module '${request}'` + ) + ); + } + } + } + } + return errors; + } - const externalsArguments = modules => { - return modules - .map( - m => - `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( - `${chunkGraph.getModuleId(m)}` - )}__` - ) - .join(", "); - }; + serialize(context) { + const { write, setCircularReference } = context; - const libraryName = library => { - return JSON.stringify(replaceKeys([].concat(library).pop())); - }; + setCircularReference(this); + write(this.ids); + write(this.name); + write(this.activeExports); + write(this.otherStarExports); + write(this.exportPresenceMode); + write(this.allStarExports); - let amdFactory; - if (optionalExternals.length > 0) { - const wrapperArguments = externalsArguments(requiredExternals); - const factoryArguments = - requiredExternals.length > 0 - ? externalsArguments(requiredExternals) + - ", " + - externalsRootArray(optionalExternals) - : externalsRootArray(optionalExternals); - amdFactory = - `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` + - ` return factory(${factoryArguments});\n` + - " }"; - } else { - amdFactory = "factory"; - } + super.serialize(context); + } - const { auxiliaryComment, namedDefine, names } = options; + deserialize(context) { + const { read, setCircularReference } = context; - const getAuxiliaryComment = type => { - if (auxiliaryComment) { - if (typeof auxiliaryComment === "string") - return "\t//" + auxiliaryComment + "\n"; - if (auxiliaryComment[type]) - return "\t//" + auxiliaryComment[type] + "\n"; - } - return ""; - }; + setCircularReference(this); + this.ids = read(); + this.name = read(); + this.activeExports = read(); + this.otherStarExports = read(); + this.exportPresenceMode = read(); + this.allStarExports = read(); - return new ConcatSource( - new OriginalSource( - "(function webpackUniversalModuleDefinition(root, factory) {\n" + - getAuxiliaryComment("commonjs2") + - " if(typeof exports === 'object' && typeof module === 'object')\n" + - " module.exports = factory(" + - externalsRequireArray("commonjs2") + - ");\n" + - getAuxiliaryComment("amd") + - " else if(typeof define === 'function' && define.amd)\n" + - (requiredExternals.length > 0 - ? names.amd && namedDefine === true - ? " define(" + - libraryName(names.amd) + - ", " + - externalsDepsArray(requiredExternals) + - ", " + - amdFactory + - ");\n" - : " define(" + - externalsDepsArray(requiredExternals) + - ", " + - amdFactory + - ");\n" - : names.amd && namedDefine === true - ? " define(" + - libraryName(names.amd) + - ", [], " + - amdFactory + - ");\n" - : " define([], " + amdFactory + ");\n") + - (names.root || names.commonjs - ? getAuxiliaryComment("commonjs") + - " else if(typeof exports === 'object')\n" + - " exports[" + - libraryName(names.commonjs || names.root) + - "] = factory(" + - externalsRequireArray("commonjs") + - ");\n" + - getAuxiliaryComment("root") + - " else\n" + - " " + - replaceKeys( - accessorAccess("root", names.root || names.commonjs) - ) + - " = factory(" + - externalsRootArray(externals) + - ");\n" - : " else {\n" + - (externals.length > 0 - ? " var a = typeof exports === 'object' ? factory(" + - externalsRequireArray("commonjs") + - ") : factory(" + - externalsRootArray(externals) + - ");\n" - : " var a = factory();\n") + - " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" + - " }\n") + - `})(${ - runtimeTemplate.outputOptions.globalObject - }, function(${externalsArguments(externals)}) {\nreturn `, - "webpack/universalModuleDefinition" - ), - source, - ";\n})" - ); + super.deserialize(context); } } -module.exports = UmdLibraryPlugin; +makeSerializable( + HarmonyExportImportedSpecifierDependency, + "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency" +); +module.exports = HarmonyExportImportedSpecifierDependency; -/***/ }), +HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate extends ( + HarmonyImportDependency.Template +) { + /** + * @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 { moduleGraph, runtime, concatenationScope } = templateContext; -/***/ 32597: -/***/ (function(__unused_webpack_module, exports) { + const dep = /** @type {HarmonyExportImportedSpecifierDependency} */ ( + dependency + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const mode = dep.getMode(moduleGraph, runtime); + if (concatenationScope) { + switch (mode.type) { + case "reexport-undefined": + concatenationScope.registerRawExport( + mode.name, + "/* reexport non-default export from non-harmony */ undefined" + ); + } + return; + } + if (mode.type !== "unused" && mode.type !== "empty-star") { + super.apply(dependency, source, templateContext); -const LogType = Object.freeze({ - error: /** @type {"error"} */ ("error"), // message, c style arguments - warn: /** @type {"warn"} */ ("warn"), // message, c style arguments - info: /** @type {"info"} */ ("info"), // message, c style arguments - log: /** @type {"log"} */ ("log"), // message, c style arguments - debug: /** @type {"debug"} */ ("debug"), // message, c style arguments + this._addExportFragments( + templateContext.initFragments, + dep, + mode, + templateContext.module, + moduleGraph, + runtime, + templateContext.runtimeTemplate, + templateContext.runtimeRequirements + ); + } + } - trace: /** @type {"trace"} */ ("trace"), // no arguments + /** + * @param {InitFragment[]} initFragments target array for init fragments + * @param {HarmonyExportImportedSpecifierDependency} dep dependency + * @param {ExportMode} mode the export mode + * @param {Module} module the current module + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {Set} runtimeRequirements runtime requirements + * @returns {void} + */ + _addExportFragments( + initFragments, + dep, + mode, + module, + moduleGraph, + runtime, + runtimeTemplate, + runtimeRequirements + ) { + const importedModule = moduleGraph.getModule(dep); + const importVar = dep.getImportVar(moduleGraph); - group: /** @type {"group"} */ ("group"), // [label] - groupCollapsed: /** @type {"groupCollapsed"} */ ("groupCollapsed"), // [label] - groupEnd: /** @type {"groupEnd"} */ ("groupEnd"), // [label] + switch (mode.type) { + case "missing": + case "empty-star": + initFragments.push( + new InitFragment( + "/* empty/unused harmony star reexport */\n", + InitFragment.STAGE_HARMONY_EXPORTS, + 1 + ) + ); + break; - profile: /** @type {"profile"} */ ("profile"), // [profileName] - profileEnd: /** @type {"profileEnd"} */ ("profileEnd"), // [profileName] + case "unused": + initFragments.push( + new InitFragment( + `${Template.toNormalComment( + `unused harmony reexport ${mode.name}` + )}\n`, + InitFragment.STAGE_HARMONY_EXPORTS, + 1 + ) + ); + break; - time: /** @type {"time"} */ ("time"), // name, time as [seconds, nanoseconds] + case "reexport-dynamic-default": + initFragments.push( + this.getReexportFragment( + module, + "reexport default from dynamic", + moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + importVar, + null, + runtimeRequirements + ) + ); + break; - clear: /** @type {"clear"} */ ("clear"), // no arguments - status: /** @type {"status"} */ ("status") // message, arguments -}); + case "reexport-fake-namespace-object": + initFragments.push( + ...this.getReexportFakeNamespaceObjectFragments( + module, + moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + importVar, + mode.fakeType, + runtimeRequirements + ) + ); + break; -exports.LogType = LogType; + case "reexport-undefined": + initFragments.push( + this.getReexportFragment( + module, + "reexport non-default export from non-harmony", + moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + "undefined", + "", + runtimeRequirements + ) + ); + break; -/** @typedef {typeof LogType[keyof typeof LogType]} LogTypeEnum */ + case "reexport-named-default": + initFragments.push( + this.getReexportFragment( + module, + "reexport default export from named module", + moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + importVar, + "", + runtimeRequirements + ) + ); + break; -const LOG_SYMBOL = Symbol("webpack logger raw log method"); -const TIMERS_SYMBOL = Symbol("webpack logger times"); -const TIMERS_AGGREGATES_SYMBOL = Symbol("webpack logger aggregated times"); + case "reexport-namespace-object": + initFragments.push( + this.getReexportFragment( + module, + "reexport module object", + moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + importVar, + "", + runtimeRequirements + ) + ); + break; -class WebpackLogger { - /** - * @param {function(LogTypeEnum, any[]=): void} log log function - * @param {function(string | function(): string): WebpackLogger} getChildLogger function to create child logger - */ - constructor(log, getChildLogger) { - this[LOG_SYMBOL] = log; - this.getChildLogger = getChildLogger; - } + case "normal-reexport": + for (const { name, ids, checked, hidden } of mode.items) { + if (hidden) continue; + if (checked) { + initFragments.push( + new InitFragment( + "/* harmony reexport (checked) */ " + + this.getConditionalReexportStatement( + module, + name, + importVar, + ids, + runtimeRequirements + ), + moduleGraph.isAsync(importedModule) + ? InitFragment.STAGE_ASYNC_HARMONY_IMPORTS + : InitFragment.STAGE_HARMONY_IMPORTS, + dep.sourceOrder + ) + ); + } else { + initFragments.push( + this.getReexportFragment( + module, + "reexport safe", + moduleGraph.getExportsInfo(module).getUsedName(name, runtime), + importVar, + moduleGraph + .getExportsInfo(importedModule) + .getUsedName(ids, runtime), + runtimeRequirements + ) + ); + } + } + break; - error(...args) { - this[LOG_SYMBOL](LogType.error, args); - } + case "dynamic-reexport": { + const ignored = mode.hidden + ? combine(mode.ignored, mode.hidden) + : mode.ignored; + const modern = + runtimeTemplate.supportsConst() && + runtimeTemplate.supportsArrowFunction(); + let content = + "/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {};\n" + + `/* harmony reexport (unknown) */ for(${ + modern ? "const" : "var" + } __WEBPACK_IMPORT_KEY__ in ${importVar}) `; - warn(...args) { - this[LOG_SYMBOL](LogType.warn, args); - } + // Filter out exports which are defined by other exports + // and filter out default export because it cannot be reexported with * + if (ignored.size > 1) { + content += + "if(" + + JSON.stringify(Array.from(ignored)) + + ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) "; + } else if (ignored.size === 1) { + content += `if(__WEBPACK_IMPORT_KEY__ !== ${JSON.stringify( + first(ignored) + )}) `; + } - info(...args) { - this[LOG_SYMBOL](LogType.info, args); - } + content += `__WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = `; + if (modern) { + content += `() => ${importVar}[__WEBPACK_IMPORT_KEY__]`; + } else { + content += `function(key) { return ${importVar}[key]; }.bind(0, __WEBPACK_IMPORT_KEY__)`; + } - log(...args) { - this[LOG_SYMBOL](LogType.log, args); - } + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - debug(...args) { - this[LOG_SYMBOL](LogType.debug, args); - } + const exportsName = module.exportsArgument; + initFragments.push( + new InitFragment( + `${content}\n/* harmony reexport (unknown) */ ${RuntimeGlobals.definePropertyGetters}(${exportsName}, __WEBPACK_REEXPORT_OBJECT__);\n`, + moduleGraph.isAsync(importedModule) + ? InitFragment.STAGE_ASYNC_HARMONY_IMPORTS + : InitFragment.STAGE_HARMONY_IMPORTS, + dep.sourceOrder + ) + ); + break; + } - assert(assertion, ...args) { - if (!assertion) { - this[LOG_SYMBOL](LogType.error, args); + default: + throw new Error(`Unknown mode ${mode.type}`); } } - trace() { - this[LOG_SYMBOL](LogType.trace, ["Trace"]); - } + getReexportFragment( + module, + comment, + key, + name, + valueKey, + runtimeRequirements + ) { + const returnValue = this.getReturnValue(name, valueKey); - clear() { - this[LOG_SYMBOL](LogType.clear); - } + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - status(...args) { - this[LOG_SYMBOL](LogType.status, args); - } + const map = new Map(); + map.set(key, `/* ${comment} */ ${returnValue}`); - group(...args) { - this[LOG_SYMBOL](LogType.group, args); + return new HarmonyExportInitFragment(module.exportsArgument, map); } - groupCollapsed(...args) { - this[LOG_SYMBOL](LogType.groupCollapsed, args); - } + getReexportFakeNamespaceObjectFragments( + module, + key, + name, + fakeType, + runtimeRequirements + ) { + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - groupEnd(...args) { - this[LOG_SYMBOL](LogType.groupEnd, args); + const map = new Map(); + map.set( + key, + `/* reexport fake namespace object from non-harmony */ ${name}_namespace_cache || (${name}_namespace_cache = ${ + RuntimeGlobals.createFakeNamespaceObject + }(${name}${fakeType ? `, ${fakeType}` : ""}))` + ); + + return [ + new InitFragment( + `var ${name}_namespace_cache;\n`, + InitFragment.STAGE_CONSTANTS, + -1, + `${name}_namespace_cache` + ), + new HarmonyExportInitFragment(module.exportsArgument, map) + ]; } - profile(label) { - this[LOG_SYMBOL](LogType.profile, [label]); + getConditionalReexportStatement( + module, + key, + name, + valueKey, + runtimeRequirements + ) { + if (valueKey === false) { + return "/* unused export */\n"; + } + + const exportsName = module.exportsArgument; + const returnValue = this.getReturnValue(name, valueKey); + + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + runtimeRequirements.add(RuntimeGlobals.hasOwnProperty); + + return `if(${RuntimeGlobals.hasOwnProperty}(${name}, ${JSON.stringify( + valueKey[0] + )})) ${ + RuntimeGlobals.definePropertyGetters + }(${exportsName}, { ${JSON.stringify( + key + )}: function() { return ${returnValue}; } });\n`; } - profileEnd(label) { - this[LOG_SYMBOL](LogType.profileEnd, [label]); + getReturnValue(name, valueKey) { + if (valueKey === null) { + return `${name}_default.a`; + } + + if (valueKey === "") { + return name; + } + + if (valueKey === false) { + return "/* unused export */ undefined"; + } + + return `${name}${propertyAccess(valueKey)}`; } +}; - time(label) { - this[TIMERS_SYMBOL] = this[TIMERS_SYMBOL] || new Map(); - this[TIMERS_SYMBOL].set(label, process.hrtime()); +class HarmonyStarExportsList { + constructor() { + /** @type {HarmonyExportImportedSpecifierDependency[]} */ + this.dependencies = []; } - timeLog(label) { - const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); - if (!prev) { - throw new Error(`No such label '${label}' for WebpackLogger.timeLog()`); - } - const time = process.hrtime(prev); - this[LOG_SYMBOL](LogType.time, [label, ...time]); + /** + * @param {HarmonyExportImportedSpecifierDependency} dep dependency + * @returns {void} + */ + push(dep) { + this.dependencies.push(dep); } - timeEnd(label) { - const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); - if (!prev) { - throw new Error(`No such label '${label}' for WebpackLogger.timeEnd()`); - } - const time = process.hrtime(prev); - this[TIMERS_SYMBOL].delete(label); - this[LOG_SYMBOL](LogType.time, [label, ...time]); + slice() { + return this.dependencies.slice(); } - timeAggregate(label) { - const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); - if (!prev) { - throw new Error( - `No such label '${label}' for WebpackLogger.timeAggregate()` - ); - } - const time = process.hrtime(prev); - this[TIMERS_SYMBOL].delete(label); - this[TIMERS_AGGREGATES_SYMBOL] = - this[TIMERS_AGGREGATES_SYMBOL] || new Map(); - const current = this[TIMERS_AGGREGATES_SYMBOL].get(label); - if (current !== undefined) { - if (time[1] + current[1] > 1e9) { - time[0] += current[0] + 1; - time[1] = time[1] - 1e9 + current[1]; - } else { - time[0] += current[0]; - time[1] += current[1]; - } - } - this[TIMERS_AGGREGATES_SYMBOL].set(label, time); + serialize({ write, setCircularReference }) { + setCircularReference(this); + write(this.dependencies); } - timeAggregateEnd(label) { - if (this[TIMERS_AGGREGATES_SYMBOL] === undefined) return; - const time = this[TIMERS_AGGREGATES_SYMBOL].get(label); - if (time === undefined) return; - this[TIMERS_AGGREGATES_SYMBOL].delete(label); - this[LOG_SYMBOL](LogType.time, [label, ...time]); + deserialize({ read, setCircularReference }) { + setCircularReference(this); + this.dependencies = read(); } } -exports.Logger = WebpackLogger; +makeSerializable( + HarmonyStarExportsList, + "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency", + "HarmonyStarExportsList" +); + +module.exports.HarmonyStarExportsList = HarmonyStarExportsList; /***/ }), -/***/ 54963: +/***/ 89500: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -97643,322 +91098,169 @@ exports.Logger = WebpackLogger; -const { LogType } = __webpack_require__(32597); - -/** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */ -/** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */ -/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ - -/** @typedef {function(string): boolean} FilterFunction */ - -/** - * @typedef {Object} LoggerConsole - * @property {function(): void} clear - * @property {function(): void} trace - * @property {(...args: any[]) => void} info - * @property {(...args: any[]) => void} log - * @property {(...args: any[]) => void} warn - * @property {(...args: any[]) => void} error - * @property {(...args: any[]) => void=} debug - * @property {(...args: any[]) => void=} group - * @property {(...args: any[]) => void=} groupCollapsed - * @property {(...args: any[]) => void=} groupEnd - * @property {(...args: any[]) => void=} status - * @property {(...args: any[]) => void=} profile - * @property {(...args: any[]) => void=} profileEnd - * @property {(...args: any[]) => void=} logTime - */ +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const { first } = __webpack_require__(93347); -/** - * @typedef {Object} LoggerOptions - * @property {false|true|"none"|"error"|"warn"|"info"|"log"|"verbose"} level loglevel - * @property {FilterTypes|boolean} debug filter for debug logging - * @property {LoggerConsole} console the console to log to - */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** - * @param {FilterItemTypes} item an input item - * @returns {FilterFunction} filter function - */ -const filterToFunction = item => { - if (typeof item === "string") { - const regExp = new RegExp( - `[\\\\/]${item.replace( - // eslint-disable-next-line no-useless-escape - /[-[\]{}()*+?.\\^$|]/g, - "\\$&" - )}([\\\\/]|$|!|\\?)` - ); - return ident => regExp.test(ident); - } - if (item && typeof item === "object" && typeof item.test === "function") { - return ident => item.test(ident); - } - if (typeof item === "function") { - return item; - } - if (typeof item === "boolean") { - return () => item; +const 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; }; -/** - * @enum {number} - */ -const LogLevel = { - none: 6, - false: 6, - error: 5, - warn: 4, - info: 3, - log: 2, - true: 2, - verbose: 1 -}; +const EMPTY_MAP = new Map(); +const EMPTY_SET = new Set(); /** - * @param {LoggerOptions} options options object - * @returns {function(string, LogTypeEnum, any[]): void} logging function + * @typedef {GenerateContext} Context */ -module.exports = ({ level = "info", debug = false, console }) => { - const debugFilters = - typeof debug === "boolean" - ? [() => debug] - : /** @type {FilterItemTypes[]} */ ([]) - .concat(debug) - .map(filterToFunction); - /** @type {number} */ - const loglevel = LogLevel[`${level}`] || 0; +class HarmonyExportInitFragment extends InitFragment { + /** + * @param {string} exportsArgument the exports identifier + * @param {Map} exportMap mapping from used name to exposed variable name + * @param {Set} unusedExports list of unused export names + */ + constructor( + exportsArgument, + exportMap = EMPTY_MAP, + unusedExports = EMPTY_SET + ) { + super(undefined, InitFragment.STAGE_HARMONY_EXPORTS, 1, "harmony-exports"); + this.exportsArgument = exportsArgument; + this.exportMap = exportMap; + this.unusedExports = unusedExports; + } /** - * @param {string} name name of the logger - * @param {LogTypeEnum} type type of the log entry - * @param {any[]} args arguments of the log entry - * @returns {void} + * @param {HarmonyExportInitFragment[]} fragments all fragments to merge + * @returns {HarmonyExportInitFragment} merged fragment */ - const logger = (name, type, args) => { - const labeledArgs = () => { - if (Array.isArray(args)) { - if (args.length > 0 && typeof args[0] === "string") { - return [`[${name}] ${args[0]}`, ...args.slice(1)]; - } else { - return [`[${name}]`, ...args]; - } - } else { - return []; - } - }; - const debug = debugFilters.some(f => f(name)); - switch (type) { - case LogType.debug: - if (!debug) return; - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.debug === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.debug(...labeledArgs()); + mergeAll(fragments) { + let exportMap; + let exportMapOwned = false; + let unusedExports; + let unusedExportsOwned = false; + + for (const fragment of fragments) { + if (fragment.exportMap.size !== 0) { + if (exportMap === undefined) { + exportMap = fragment.exportMap; + exportMapOwned = false; } else { - console.log(...labeledArgs()); - } - break; - case LogType.log: - if (!debug && loglevel > LogLevel.log) return; - console.log(...labeledArgs()); - break; - case LogType.info: - if (!debug && loglevel > LogLevel.info) return; - console.info(...labeledArgs()); - break; - case LogType.warn: - if (!debug && loglevel > LogLevel.warn) return; - console.warn(...labeledArgs()); - break; - case LogType.error: - if (!debug && loglevel > LogLevel.error) return; - console.error(...labeledArgs()); - break; - case LogType.trace: - if (!debug) return; - console.trace(); - break; - case LogType.groupCollapsed: - if (!debug && loglevel > LogLevel.log) return; - if (!debug && loglevel > LogLevel.verbose) { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.groupCollapsed === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.groupCollapsed(...labeledArgs()); - } else { - console.log(...labeledArgs()); + if (!exportMapOwned) { + exportMap = new Map(exportMap); + exportMapOwned = true; + } + for (const [key, value] of fragment.exportMap) { + if (!exportMap.has(key)) exportMap.set(key, value); } - break; - } - // falls through - case LogType.group: - if (!debug && loglevel > LogLevel.log) return; - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.group === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.group(...labeledArgs()); - } else { - console.log(...labeledArgs()); - } - break; - case LogType.groupEnd: - if (!debug && loglevel > LogLevel.log) return; - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.groupEnd === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.groupEnd(); - } - break; - case LogType.time: { - if (!debug && loglevel > LogLevel.log) return; - const ms = args[1] * 1000 + args[2] / 1000000; - const msg = `[${name}] ${args[0]}: ${ms} ms`; - if (typeof console.logTime === "function") { - console.logTime(msg); - } else { - console.log(msg); } - break; } - case LogType.profile: - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.profile === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.profile(...labeledArgs()); - } - break; - case LogType.profileEnd: - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.profileEnd === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.profileEnd(...labeledArgs()); - } - break; - case LogType.clear: - if (!debug && loglevel > LogLevel.log) return; - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.clear === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.clear(); - } - break; - case LogType.status: - if (!debug && loglevel > LogLevel.info) return; - if (typeof console.status === "function") { - if (args.length === 0) { - console.status(); - } else { - console.status(...labeledArgs()); - } + if (fragment.unusedExports.size !== 0) { + if (unusedExports === undefined) { + unusedExports = fragment.unusedExports; + unusedExportsOwned = false; } else { - if (args.length !== 0) { - console.info(...labeledArgs()); + if (!unusedExportsOwned) { + unusedExports = new Set(unusedExports); + unusedExportsOwned = true; + } + for (const value of fragment.unusedExports) { + unusedExports.add(value); } } - break; - default: - throw new Error(`Unexpected LogType ${type}`); + } } - }; - return logger; -}; - - -/***/ }), - -/***/ 62090: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const arraySum = array => { - let sum = 0; - for (const item of array) sum += item; - return sum; -}; - -/** - * @param {any[]} args items to be truncated - * @param {number} maxLength maximum length of args including spaces between - * @returns {string[]} truncated args - */ -const truncateArgs = (args, maxLength) => { - const lengths = args.map(a => `${a}`.length); - const availableLength = maxLength - lengths.length + 1; + return new HarmonyExportInitFragment( + this.exportsArgument, + exportMap, + unusedExports + ); + } - if (availableLength > 0 && args.length === 1) { - if (availableLength >= args[0].length) { - return args; - } else if (availableLength > 3) { - return ["..." + args[0].slice(-availableLength + 3)]; + merge(other) { + let exportMap; + if (this.exportMap.size === 0) { + exportMap = other.exportMap; + } else if (other.exportMap.size === 0) { + exportMap = this.exportMap; } else { - return [args[0].slice(-availableLength)]; + exportMap = new Map(other.exportMap); + for (const [key, value] of this.exportMap) { + if (!exportMap.has(key)) exportMap.set(key, value); + } } - } - - // Check if there is space for at least 4 chars per arg - if (availableLength < arraySum(lengths.map(i => Math.min(i, 6)))) { - // remove args - if (args.length > 1) - return truncateArgs(args.slice(0, args.length - 1), maxLength); - return []; - } - - let currentLength = arraySum(lengths); - - // Check if all fits into maxLength - if (currentLength <= availableLength) return args; - - // Try to remove chars from the longest items until it fits - while (currentLength > availableLength) { - const maxLength = Math.max(...lengths); - const shorterItems = lengths.filter(l => l !== maxLength); - const nextToMaxLength = - shorterItems.length > 0 ? Math.max(...shorterItems) : 0; - const maxReduce = maxLength - nextToMaxLength; - let maxItems = lengths.length - shorterItems.length; - let overrun = currentLength - availableLength; - for (let i = 0; i < lengths.length; i++) { - if (lengths[i] === maxLength) { - const reduce = Math.min(Math.floor(overrun / maxItems), maxReduce); - lengths[i] -= reduce; - currentLength -= reduce; - overrun -= reduce; - maxItems--; + let unusedExports; + if (this.unusedExports.size === 0) { + unusedExports = other.unusedExports; + } else if (other.unusedExports.size === 0) { + unusedExports = this.unusedExports; + } else { + unusedExports = new Set(other.unusedExports); + for (const value of this.unusedExports) { + unusedExports.add(value); } } + return new HarmonyExportInitFragment( + this.exportsArgument, + exportMap, + unusedExports + ); } - // Return args reduced to length in lengths - return args.map((a, i) => { - const str = `${a}`; - const length = lengths[i]; - if (str.length === length) { - return str; - } else if (length > 5) { - return "..." + str.slice(-length + 3); - } else if (length > 0) { - return str.slice(-length); - } else { - return ""; + /** + * @param {Context} context context + * @returns {string|Source} the source code that will be included as initialization code + */ + getContent({ runtimeTemplate, runtimeRequirements }) { + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + + const unusedPart = + this.unusedExports.size > 1 + ? `/* unused harmony exports ${joinIterableWithComma( + this.unusedExports + )} */\n` + : this.unusedExports.size > 0 + ? `/* unused harmony export ${first(this.unusedExports)} */\n` + : ""; + const definitions = []; + for (const [key, value] of this.exportMap) { + definitions.push( + `\n/* harmony export */ ${JSON.stringify( + key + )}: ${runtimeTemplate.returningFunction(value)}` + ); } - }); -}; + const definePart = + this.exportMap.size > 0 + ? `/* harmony export */ ${RuntimeGlobals.definePropertyGetters}(${ + this.exportsArgument + }, {${definitions.join(",")}\n/* harmony export */ });\n` + : ""; + return `${definePart}${unusedPart}`; + } +} -module.exports = truncateArgs; +module.exports = HarmonyExportInitFragment; /***/ }), -/***/ 1313: +/***/ 48567: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -97969,110 +91271,116 @@ module.exports = truncateArgs; -const RuntimeGlobals = __webpack_require__(16475); -const StartupChunkDependenciesPlugin = __webpack_require__(22339); +const makeSerializable = __webpack_require__(33032); +const HarmonyExportInitFragment = __webpack_require__(89500); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -class CommonJsChunkLoadingPlugin { - constructor(options) { - options = options || {}; - this._asyncChunkLoading = options.asyncChunkLoading; +class HarmonyExportSpecifierDependency extends NullDependency { + constructor(id, name) { + super(); + this.id = id; + this.name = name; + } + + get type() { + return "harmony export specifier"; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names */ - apply(compiler) { - const ChunkLoadingRuntimeModule = this._asyncChunkLoading - ? __webpack_require__(73369) - : __webpack_require__(94172); - const chunkLoadingValue = this._asyncChunkLoading - ? "async-node" - : "require"; - new StartupChunkDependenciesPlugin({ - chunkLoading: chunkLoadingValue, - asyncChunkLoading: this._asyncChunkLoading - }).apply(compiler); - compiler.hooks.thisCompilation.tap( - "CommonJsChunkLoadingPlugin", - compilation => { - const globalChunkLoading = compilation.outputOptions.chunkLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const chunkLoading = - options && options.chunkLoading !== undefined - ? options.chunkLoading - : globalChunkLoading; - return chunkLoading === chunkLoadingValue; - }; - const onceForChunkSet = new WeakSet(); - const handler = (chunk, set) => { - if (onceForChunkSet.has(chunk)) return; - onceForChunkSet.add(chunk); - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.hasOwnProperty); - compilation.addRuntimeModule( - chunk, - new ChunkLoadingRuntimeModule(set) - ); - }; + getExports(moduleGraph) { + return { + exports: [this.name], + priority: 1, + terminalBinding: true, + dependencies: undefined + }; + } - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("CommonJsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap("CommonJsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadManifest) - .tap("CommonJsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.baseURI) - .tap("CommonJsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.externalInstallChunk) - .tap("CommonJsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.onChunksLoaded) - .tap("CommonJsChunkLoadingPlugin", handler); + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.getChunkScriptFilename); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.getChunkUpdateScriptFilename); - set.add(RuntimeGlobals.moduleCache); - set.add(RuntimeGlobals.hmrModuleData); - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadManifest) - .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.getUpdateManifestFilename); - }); - } - ); + serialize(context) { + const { write } = context; + write(this.id); + write(this.name); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.id = read(); + this.name = read(); + super.deserialize(context); } } -module.exports = CommonJsChunkLoadingPlugin; +makeSerializable( + HarmonyExportSpecifierDependency, + "webpack/lib/dependencies/HarmonyExportSpecifierDependency" +); + +HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, + { module, moduleGraph, initFragments, runtime, concatenationScope } + ) { + const dep = /** @type {HarmonyExportSpecifierDependency} */ (dependency); + if (concatenationScope) { + concatenationScope.registerExport(dep.name, dep.id); + return; + } + const used = moduleGraph + .getExportsInfo(module) + .getUsedName(dep.name, runtime); + if (!used) { + const set = new Set(); + set.add(dep.name || "namespace"); + initFragments.push( + new HarmonyExportInitFragment(module.exportsArgument, undefined, set) + ); + return; + } + + const map = new Map(); + map.set(used, `/* binding */ ${dep.id}`); + initFragments.push( + new HarmonyExportInitFragment(module.exportsArgument, map, undefined) + ); + } +}; + +module.exports = HarmonyExportSpecifierDependency; /***/ }), -/***/ 7553: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 39211: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -98082,65 +91390,45 @@ module.exports = CommonJsChunkLoadingPlugin; -const CachedInputFileSystem = __webpack_require__(52788); -const fs = __webpack_require__(90552); -const createConsoleLogger = __webpack_require__(54963); -const NodeWatchFileSystem = __webpack_require__(98810); -const nodeConsole = __webpack_require__(91786); - -/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */ -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Parser").ParserState} ParserState */ -class NodeEnvironmentPlugin { - /** - * @param {Object} options options - * @param {InfrastructureLogging} options.infrastructureLogging infrastructure logging options - */ - constructor(options) { - this.options = options; - } +/** @type {WeakMap} */ +const parserStateExportsState = new WeakMap(); - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const { infrastructureLogging } = this.options; - compiler.infrastructureLogger = createConsoleLogger({ - level: infrastructureLogging.level || "info", - debug: infrastructureLogging.debug || false, - console: - infrastructureLogging.console || - nodeConsole({ - colors: infrastructureLogging.colors, - appendOnly: infrastructureLogging.appendOnly, - stream: infrastructureLogging.stream - }) - }); - compiler.inputFileSystem = new CachedInputFileSystem(fs, 60000); - const inputFileSystem = compiler.inputFileSystem; - compiler.outputFileSystem = fs; - compiler.intermediateFileSystem = fs; - compiler.watchFileSystem = new NodeWatchFileSystem( - compiler.inputFileSystem - ); - compiler.hooks.beforeRun.tap("NodeEnvironmentPlugin", compiler => { - if (compiler.inputFileSystem === inputFileSystem) { - compiler.fsStartTime = Date.now(); - inputFileSystem.purge(); - } - }); +/** + * @param {ParserState} parserState parser state + * @param {boolean} isStrictHarmony strict harmony mode should be enabled + * @returns {void} + */ +exports.enable = (parserState, isStrictHarmony) => { + const value = parserStateExportsState.get(parserState); + if (value === false) return; + parserStateExportsState.set(parserState, true); + if (value !== true) { + parserState.module.buildMeta.exportsType = "namespace"; + parserState.module.buildInfo.strict = true; + parserState.module.buildInfo.exportsArgument = "__webpack_exports__"; + if (isStrictHarmony) { + parserState.module.buildMeta.strictHarmonyModule = true; + parserState.module.buildInfo.moduleArgument = "__webpack_module__"; + } } -} +}; -module.exports = NodeEnvironmentPlugin; +/** + * @param {ParserState} parserState parser state + * @returns {boolean} true, when enabled + */ +exports.isEnabled = parserState => { + const value = parserStateExportsState.get(parserState); + return value === true; +}; /***/ }), -/***/ 7103: -/***/ (function(module) { +/***/ 57154: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -98150,152 +91438,363 @@ module.exports = NodeEnvironmentPlugin; -/** @typedef {import("../Compiler")} Compiler */ +const ConditionalInitFragment = __webpack_require__(61333); +const Dependency = __webpack_require__(54912); +const HarmonyLinkingError = __webpack_require__(97511); +const InitFragment = __webpack_require__(55870); +const Template = __webpack_require__(39722); +const AwaitDependenciesInitFragment = __webpack_require__(41153); +const { filterRuntime, mergeRuntime } = __webpack_require__(17156); +const ModuleDependency = __webpack_require__(80321); -class NodeSourcePlugin { +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +const ExportPresenceModes = { + NONE: /** @type {0} */ (0), + WARN: /** @type {1} */ (1), + AUTO: /** @type {2} */ (2), + ERROR: /** @type {3} */ (3), + fromUserOption(str) { + switch (str) { + case "error": + return ExportPresenceModes.ERROR; + case "warn": + return ExportPresenceModes.WARN; + case "auto": + return ExportPresenceModes.AUTO; + case false: + return ExportPresenceModes.NONE; + default: + throw new Error(`Invalid export presence value ${str}`); + } + } +}; + +class HarmonyImportDependency extends ModuleDependency { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * + * @param {string} request request string + * @param {number} sourceOrder source order + * @param {Record=} assertions import assertions */ - apply(compiler) {} -} - -module.exports = NodeSourcePlugin; + constructor(request, sourceOrder, assertions) { + super(request); + this.sourceOrder = sourceOrder; + this.assertions = assertions; + } + get category() { + return "esm"; + } -/***/ }), + /** + * 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.NO_EXPORTS_REFERENCED; + } -/***/ 17916: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {string} name of the variable for the import + */ + getImportVar(moduleGraph) { + const module = moduleGraph.getParentModule(this); + const meta = moduleGraph.getMeta(module); + let importVarMap = meta.importVarMap; + if (!importVarMap) meta.importVarMap = importVarMap = new Map(); + let importVar = importVarMap.get(moduleGraph.getModule(this)); + if (importVar) return importVar; + importVar = `${Template.toIdentifier( + `${this.userRequest}` + )}__WEBPACK_IMPORTED_MODULE_${importVarMap.size}__`; + importVarMap.set(moduleGraph.getModule(this), importVar); + return importVar; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {boolean} update create new variables or update existing one + * @param {DependencyTemplateContext} templateContext the template context + * @returns {[string, string]} the import statement and the compat statement + */ + getImportStatement( + update, + { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } + ) { + return runtimeTemplate.importStatement({ + update, + module: moduleGraph.getModule(this), + chunkGraph, + importVar: this.getImportVar(moduleGraph), + request: this.request, + originModule: module, + runtimeRequirements + }); + } + /** + * @param {ModuleGraph} moduleGraph module graph + * @param {string[]} ids imported ids + * @param {string} additionalMessage extra info included in the error message + * @returns {WebpackError[] | undefined} errors + */ + getLinkingErrors(moduleGraph, ids, additionalMessage) { + const importedModule = moduleGraph.getModule(this); + // ignore errors for missing or failed modules + if (!importedModule || importedModule.getNumberOfErrors() > 0) { + return; + } + const parentModule = moduleGraph.getParentModule(this); + const exportsType = importedModule.getExportsType( + moduleGraph, + parentModule.buildMeta.strictHarmonyModule + ); + if (exportsType === "namespace" || exportsType === "default-with-named") { + if (ids.length === 0) { + return; + } -const ExternalsPlugin = __webpack_require__(6652); + if ( + (exportsType !== "default-with-named" || ids[0] !== "default") && + moduleGraph.isExportProvided(importedModule, ids) === false + ) { + // We are sure that it's not provided -/** @typedef {import("../Compiler")} Compiler */ + // Try to provide detailed info in the error message + let pos = 0; + let exportsInfo = moduleGraph.getExportsInfo(importedModule); + while (pos < ids.length && exportsInfo) { + const id = ids[pos++]; + const exportInfo = exportsInfo.getReadOnlyExportInfo(id); + if (exportInfo.provided === false) { + // We are sure that it's not provided + const providedExports = exportsInfo.getProvidedExports(); + const moreInfo = !Array.isArray(providedExports) + ? " (possible exports unknown)" + : providedExports.length === 0 + ? " (module has no exports)" + : ` (possible exports: ${providedExports.join(", ")})`; + return [ + new HarmonyLinkingError( + `export ${ids + .slice(0, pos) + .map(id => `'${id}'`) + .join(".")} ${additionalMessage} was not found in '${ + this.userRequest + }'${moreInfo}` + ) + ]; + } + exportsInfo = exportInfo.getNestedExportsInfo(); + } -const builtins = [ - "assert", - "async_hooks", - "buffer", - "child_process", - "cluster", - "console", - "constants", - "crypto", - "dgram", - "diagnostics_channel", - "dns", - "dns/promises", - "domain", - "events", - "fs", - "fs/promises", - "http", - "http2", - "https", - "inspector", - "module", - "net", - "os", - "path", - "path/posix", - "path/win32", - "perf_hooks", - "process", - "punycode", - "querystring", - "readline", - "repl", - "stream", - "stream/promises", - "stream/web", - "string_decoder", - "sys", - "timers", - "timers/promises", - "tls", - "trace_events", - "tty", - "url", - "util", - "v8", - "vm", - "wasi", - "worker_threads", - "zlib", - /^node:/, + // General error message + return [ + new HarmonyLinkingError( + `export ${ids + .map(id => `'${id}'`) + .join(".")} ${additionalMessage} was not found in '${ + this.userRequest + }'` + ) + ]; + } + } + switch (exportsType) { + case "default-only": + // It's has only a default export + if (ids.length > 0 && ids[0] !== "default") { + // In strict harmony modules we only support the default export + return [ + new HarmonyLinkingError( + `Can't import the named export ${ids + .map(id => `'${id}'`) + .join( + "." + )} ${additionalMessage} from default-exporting module (only default export is available)` + ) + ]; + } + break; + case "default-with-named": + // It has a default export and named properties redirect + // In some cases we still want to warn here + if ( + ids.length > 0 && + ids[0] !== "default" && + importedModule.buildMeta.defaultObject === "redirect-warn" + ) { + // For these modules only the default export is supported + return [ + new HarmonyLinkingError( + `Should not import the named export ${ids + .map(id => `'${id}'`) + .join( + "." + )} ${additionalMessage} from default-exporting module (only default export is available soon)` + ) + ]; + } + break; + } + } - // cspell:word pnpapi - // Yarn PnP adds pnpapi as "builtin" - "pnpapi" -]; + serialize(context) { + const { write } = context; + write(this.sourceOrder); + write(this.assertions); + super.serialize(context); + } -class NodeTargetPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - new ExternalsPlugin("node-commonjs", builtins).apply(compiler); + deserialize(context) { + const { read } = context; + this.sourceOrder = read(); + this.assertions = read(); + super.deserialize(context); } } -module.exports = NodeTargetPlugin; +module.exports = HarmonyImportDependency; +/** @type {WeakMap>} */ +const importEmittedMap = new WeakMap(); -/***/ }), +HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @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 dep = /** @type {HarmonyImportDependency} */ (dependency); + const { module, chunkGraph, moduleGraph, runtime } = templateContext; -/***/ 61052: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const connection = moduleGraph.getConnection(dep); + if (connection && !connection.isTargetActive(runtime)) return; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const referencedModule = connection && connection.module; + if ( + connection && + connection.weak && + referencedModule && + chunkGraph.getModuleId(referencedModule) === null + ) { + // in weak references, module might not be in any chunk + // but that's ok, we don't need that logic in this case + return; + } + const moduleKey = referencedModule + ? referencedModule.identifier() + : dep.request; + const key = `harmony import ${moduleKey}`; -const CommonJsChunkFormatPlugin = __webpack_require__(84508); -const EnableChunkLoadingPlugin = __webpack_require__(61291); + const runtimeCondition = dep.weak + ? false + : connection + ? filterRuntime(runtime, r => connection.isTargetActive(r)) + : true; -/** @typedef {import("../Compiler")} Compiler */ + if (module && referencedModule) { + let emittedModules = importEmittedMap.get(module); + if (emittedModules === undefined) { + emittedModules = new WeakMap(); + importEmittedMap.set(module, emittedModules); + } + let mergedRuntimeCondition = runtimeCondition; + const oldRuntimeCondition = emittedModules.get(referencedModule) || false; + if (oldRuntimeCondition !== false && mergedRuntimeCondition !== true) { + if (mergedRuntimeCondition === false || oldRuntimeCondition === true) { + mergedRuntimeCondition = oldRuntimeCondition; + } else { + mergedRuntimeCondition = mergeRuntime( + oldRuntimeCondition, + mergedRuntimeCondition + ); + } + } + emittedModules.set(referencedModule, mergedRuntimeCondition); + } -class NodeTemplatePlugin { - constructor(options) { - this._options = options || {}; + const importStatement = dep.getImportStatement(false, templateContext); + if ( + referencedModule && + templateContext.moduleGraph.isAsync(referencedModule) + ) { + templateContext.initFragments.push( + new ConditionalInitFragment( + importStatement[0], + InitFragment.STAGE_HARMONY_IMPORTS, + dep.sourceOrder, + key, + runtimeCondition + ) + ); + templateContext.initFragments.push( + new AwaitDependenciesInitFragment( + new Set([dep.getImportVar(templateContext.moduleGraph)]) + ) + ); + templateContext.initFragments.push( + new ConditionalInitFragment( + importStatement[1], + InitFragment.STAGE_ASYNC_HARMONY_IMPORTS, + dep.sourceOrder, + key + " compat", + runtimeCondition + ) + ); + } else { + templateContext.initFragments.push( + new ConditionalInitFragment( + importStatement[0] + importStatement[1], + InitFragment.STAGE_HARMONY_IMPORTS, + dep.sourceOrder, + key, + runtimeCondition + ) + ); + } } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * + * @param {Module} module the module + * @param {Module} referencedModule the referenced module + * @returns {RuntimeSpec | boolean} runtimeCondition in which this import has been emitted */ - apply(compiler) { - const chunkLoading = this._options.asyncChunkLoading - ? "async-node" - : "require"; - compiler.options.output.chunkLoading = chunkLoading; - new CommonJsChunkFormatPlugin().apply(compiler); - new EnableChunkLoadingPlugin(chunkLoading).apply(compiler); + static getImportEmittedRuntime(module, referencedModule) { + const emittedModules = importEmittedMap.get(module); + if (emittedModules === undefined) return false; + return emittedModules.get(referencedModule) || false; } -} +}; -module.exports = NodeTemplatePlugin; +module.exports.ExportPresenceModes = ExportPresenceModes; /***/ }), -/***/ 98810: +/***/ 20862: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -98306,597 +91805,348 @@ module.exports = NodeTemplatePlugin; -const util = __webpack_require__(73837); -const Watchpack = __webpack_require__(36871); +const HotModuleReplacementPlugin = __webpack_require__(6404); +const InnerGraph = __webpack_require__(38988); +const ConstDependency = __webpack_require__(76911); +const HarmonyAcceptDependency = __webpack_require__(23624); +const HarmonyAcceptImportDependency = __webpack_require__(99843); +const HarmonyExports = __webpack_require__(39211); +const { ExportPresenceModes } = __webpack_require__(57154); +const HarmonyImportSideEffectDependency = __webpack_require__(73132); +const HarmonyImportSpecifierDependency = __webpack_require__(14077); -/** @typedef {import("../../declarations/WebpackOptions").WatchOptions} WatchOptions */ -/** @typedef {import("../FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ -/** @typedef {import("../util/fs").WatchFileSystem} WatchFileSystem */ -/** @typedef {import("../util/fs").WatchMethod} WatchMethod */ -/** @typedef {import("../util/fs").Watcher} Watcher */ +/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */ +/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").ImportDeclaration} ImportDeclaration */ +/** @typedef {import("estree").ImportExpression} ImportExpression */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../optimize/InnerGraph").InnerGraph} InnerGraph */ +/** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */ +/** @typedef {import("./HarmonyImportDependency")} HarmonyImportDependency */ -class NodeWatchFileSystem { - constructor(inputFileSystem) { - this.inputFileSystem = inputFileSystem; - this.watcherOptions = { - aggregateTimeout: 0 - }; - this.watcher = new Watchpack(this.watcherOptions); - } +const harmonySpecifierTag = Symbol("harmony import"); - /** - * @param {Iterable} files watched files - * @param {Iterable} directories watched directories - * @param {Iterable} missing watched exitance entries - * @param {number} startTime timestamp of start time - * @param {WatchOptions} options options object - * @param {function(Error=, Map, Map, Set, Set): void} callback aggregated callback - * @param {function(string, number): void} callbackUndelayed callback when the first change was detected - * @returns {Watcher} a watcher - */ - watch( - files, - directories, - missing, - startTime, - options, - callback, - callbackUndelayed - ) { - if (!files || typeof files[Symbol.iterator] !== "function") { - throw new Error("Invalid arguments: 'files'"); - } - if (!directories || typeof directories[Symbol.iterator] !== "function") { - throw new Error("Invalid arguments: 'directories'"); - } - if (!missing || typeof missing[Symbol.iterator] !== "function") { - throw new Error("Invalid arguments: 'missing'"); - } - if (typeof callback !== "function") { - throw new Error("Invalid arguments: 'callback'"); - } - if (typeof startTime !== "number" && startTime) { - throw new Error("Invalid arguments: 'startTime'"); - } - if (typeof options !== "object") { - throw new Error("Invalid arguments: 'options'"); - } - if (typeof callbackUndelayed !== "function" && callbackUndelayed) { - throw new Error("Invalid arguments: 'callbackUndelayed'"); - } - const oldWatcher = this.watcher; - this.watcher = new Watchpack(options); +/** + * @typedef {Object} HarmonySettings + * @property {string[]} ids + * @property {string} source + * @property {number} sourceOrder + * @property {string} name + * @property {boolean} await + * @property {Record | undefined} assertions + */ - if (callbackUndelayed) { - this.watcher.once("change", callbackUndelayed); - } +/** + * @param {ImportDeclaration | ExportNamedDeclaration | ExportAllDeclaration | ImportExpression} node node with assertions + * @returns {Record | undefined} assertions + */ +function getAssertions(node) { + // TODO remove cast when @types/estree has been updated to import assertions + const assertions = /** @type {{ assertions?: ImportAttributeNode[] }} */ ( + node + ).assertions; + if (assertions === undefined) { + return undefined; + } + const result = {}; + for (const assertion of assertions) { + const key = + assertion.key.type === "Identifier" + ? assertion.key.name + : assertion.key.value; + result[key] = assertion.value.value; + } + return result; +} - const fetchTimeInfo = () => { - const fileTimeInfoEntries = new Map(); - const contextTimeInfoEntries = new Map(); - if (this.watcher) { - this.watcher.collectTimeInfoEntries( - fileTimeInfoEntries, - contextTimeInfoEntries +module.exports = class HarmonyImportDependencyParserPlugin { + /** + * @param {JavascriptParserOptions} options options + */ + constructor(options) { + this.exportPresenceMode = + options.importExportsPresence !== undefined + ? ExportPresenceModes.fromUserOption(options.importExportsPresence) + : options.exportsPresence !== undefined + ? ExportPresenceModes.fromUserOption(options.exportsPresence) + : options.strictExportPresence + ? ExportPresenceModes.ERROR + : ExportPresenceModes.AUTO; + this.strictThisContextOnImports = options.strictThisContextOnImports; + } + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + const { exportPresenceMode } = this; + parser.hooks.isPure + .for("Identifier") + .tap("HarmonyImportDependencyParserPlugin", expression => { + const expr = /** @type {Identifier} */ (expression); + if ( + parser.isVariableDefined(expr.name) || + parser.getTagData(expr.name, harmonySpecifierTag) + ) { + return true; + } + }); + parser.hooks.import.tap( + "HarmonyImportDependencyParserPlugin", + (statement, source) => { + parser.state.lastHarmonyImportOrder = + (parser.state.lastHarmonyImportOrder || 0) + 1; + const clearDep = new ConstDependency( + parser.isAsiPosition(statement.range[0]) ? ";" : "", + statement.range + ); + clearDep.loc = statement.loc; + parser.state.module.addPresentationalDependency(clearDep); + parser.unsetAsiPosition(statement.range[1]); + const assertions = getAssertions(statement); + const sideEffectDep = new HarmonyImportSideEffectDependency( + source, + parser.state.lastHarmonyImportOrder, + assertions ); + sideEffectDep.loc = statement.loc; + parser.state.module.addDependency(sideEffectDep); + return true; } - return { fileTimeInfoEntries, contextTimeInfoEntries }; - }; - this.watcher.once("aggregated", (changes, removals) => { - // pause emitting events (avoids clearing aggregated changes and removals on timeout) - this.watcher.pause(); - - if (this.inputFileSystem && this.inputFileSystem.purge) { - const fs = this.inputFileSystem; - for (const item of changes) { - fs.purge(item); + ); + parser.hooks.importSpecifier.tap( + "HarmonyImportDependencyParserPlugin", + (statement, source, id, name) => { + const ids = id === null ? [] : [id]; + parser.tagVariable(name, harmonySpecifierTag, { + name, + source, + ids, + sourceOrder: parser.state.lastHarmonyImportOrder, + assertions: getAssertions(statement) + }); + return true; + } + ); + parser.hooks.expression + .for(harmonySpecifierTag) + .tap("HarmonyImportDependencyParserPlugin", expr => { + const settings = /** @type {HarmonySettings} */ (parser.currentTagData); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + settings.sourceOrder, + settings.ids, + settings.name, + expr.range, + exportPresenceMode, + settings.assertions + ); + dep.shorthand = parser.scope.inShorthand; + dep.directImport = true; + dep.asiSafe = !parser.isAsiPosition(expr.range[0]); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); + return true; + }); + parser.hooks.expressionMemberChain + .for(harmonySpecifierTag) + .tap("HarmonyImportDependencyParserPlugin", (expr, members) => { + const settings = /** @type {HarmonySettings} */ (parser.currentTagData); + const ids = settings.ids.concat(members); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + settings.sourceOrder, + ids, + settings.name, + expr.range, + exportPresenceMode, + settings.assertions + ); + dep.asiSafe = !parser.isAsiPosition(expr.range[0]); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); + return true; + }); + parser.hooks.callMemberChain + .for(harmonySpecifierTag) + .tap("HarmonyImportDependencyParserPlugin", (expr, members) => { + const { arguments: args, callee } = expr; + const settings = /** @type {HarmonySettings} */ (parser.currentTagData); + const ids = settings.ids.concat(members); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + settings.sourceOrder, + ids, + settings.name, + callee.range, + exportPresenceMode, + settings.assertions + ); + dep.directImport = members.length === 0; + dep.call = true; + dep.asiSafe = !parser.isAsiPosition(callee.range[0]); + // only in case when we strictly follow the spec we need a special case here + dep.namespaceObjectAsContext = + members.length > 0 && this.strictThisContextOnImports; + dep.loc = callee.loc; + parser.state.module.addDependency(dep); + if (args) parser.walkExpressions(args); + InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); + return true; + }); + const { hotAcceptCallback, hotAcceptWithoutCallback } = + HotModuleReplacementPlugin.getParserHooks(parser); + hotAcceptCallback.tap( + "HarmonyImportDependencyParserPlugin", + (expr, requests) => { + if (!HarmonyExports.isEnabled(parser.state)) { + // This is not a harmony module, skip it + return; } - for (const item of removals) { - fs.purge(item); + const dependencies = requests.map(request => { + const dep = new HarmonyAcceptImportDependency(request); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return dep; + }); + if (dependencies.length > 0) { + const dep = new HarmonyAcceptDependency( + expr.range, + dependencies, + true + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); } } - const { fileTimeInfoEntries, contextTimeInfoEntries } = fetchTimeInfo(); - callback( - null, - fileTimeInfoEntries, - contextTimeInfoEntries, - changes, - removals - ); - }); - - this.watcher.watch({ files, directories, missing, startTime }); - - if (oldWatcher) { - oldWatcher.close(); - } - return { - close: () => { - if (this.watcher) { - this.watcher.close(); - this.watcher = null; - } - }, - pause: () => { - if (this.watcher) { - this.watcher.pause(); + ); + hotAcceptWithoutCallback.tap( + "HarmonyImportDependencyParserPlugin", + (expr, requests) => { + if (!HarmonyExports.isEnabled(parser.state)) { + // This is not a harmony module, skip it + return; } - }, - getAggregatedRemovals: util.deprecate( - () => { - const items = this.watcher && this.watcher.aggregatedRemovals; - if (items && this.inputFileSystem && this.inputFileSystem.purge) { - const fs = this.inputFileSystem; - for (const item of items) { - fs.purge(item); - } - } - return items; - }, - "Watcher.getAggregatedRemovals is deprecated in favor of Watcher.getInfo since that's more performant.", - "DEP_WEBPACK_WATCHER_GET_AGGREGATED_REMOVALS" - ), - getAggregatedChanges: util.deprecate( - () => { - const items = this.watcher && this.watcher.aggregatedChanges; - if (items && this.inputFileSystem && this.inputFileSystem.purge) { - const fs = this.inputFileSystem; - for (const item of items) { - fs.purge(item); - } - } - return items; - }, - "Watcher.getAggregatedChanges is deprecated in favor of Watcher.getInfo since that's more performant.", - "DEP_WEBPACK_WATCHER_GET_AGGREGATED_CHANGES" - ), - getFileTimeInfoEntries: util.deprecate( - () => { - return fetchTimeInfo().fileTimeInfoEntries; - }, - "Watcher.getFileTimeInfoEntries is deprecated in favor of Watcher.getInfo since that's more performant.", - "DEP_WEBPACK_WATCHER_FILE_TIME_INFO_ENTRIES" - ), - getContextTimeInfoEntries: util.deprecate( - () => { - return fetchTimeInfo().contextTimeInfoEntries; - }, - "Watcher.getContextTimeInfoEntries is deprecated in favor of Watcher.getInfo since that's more performant.", - "DEP_WEBPACK_WATCHER_CONTEXT_TIME_INFO_ENTRIES" - ), - getInfo: () => { - const removals = this.watcher && this.watcher.aggregatedRemovals; - const changes = this.watcher && this.watcher.aggregatedChanges; - if (this.inputFileSystem && this.inputFileSystem.purge) { - const fs = this.inputFileSystem; - if (removals) { - for (const item of removals) { - fs.purge(item); - } - } - if (changes) { - for (const item of changes) { - fs.purge(item); - } - } + const dependencies = requests.map(request => { + const dep = new HarmonyAcceptImportDependency(request); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return dep; + }); + if (dependencies.length > 0) { + const dep = new HarmonyAcceptDependency( + expr.range, + dependencies, + false + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); } - const { fileTimeInfoEntries, contextTimeInfoEntries } = fetchTimeInfo(); - return { - changes, - removals, - fileTimeInfoEntries, - contextTimeInfoEntries - }; } - }; + ); } -} +}; -module.exports = NodeWatchFileSystem; +module.exports.harmonySpecifierTag = harmonySpecifierTag; +module.exports.getAssertions = getAssertions; /***/ }), -/***/ 73369: +/***/ 73132: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); -const { - chunkHasJs, - getChunkFilenameTemplate -} = __webpack_require__(89464); -const { getInitialChunkIds } = __webpack_require__(98124); -const compileBooleanMatcher = __webpack_require__(29404); -const { getUndoPath } = __webpack_require__(82186); +const makeSerializable = __webpack_require__(33032); +const HarmonyImportDependency = __webpack_require__(57154); -class ReadFileChunkLoadingRuntimeModule extends RuntimeModule { - constructor(runtimeRequirements) { - super("readFile chunk loading", RuntimeModule.STAGE_ATTACH); - this.runtimeRequirements = runtimeRequirements; +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../InitFragment")} InitFragment */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class HarmonyImportSideEffectDependency extends HarmonyImportDependency { + constructor(request, sourceOrder, assertions) { + super(request, sourceOrder, assertions); + } + + get type() { + return "harmony side effect evaluation"; } /** - * @returns {string} runtime code + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active */ - generate() { - const { chunkGraph, chunk } = this; - const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.ensureChunkHandlers; - const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); - const withExternalInstallChunk = this.runtimeRequirements.has( - RuntimeGlobals.externalInstallChunk - ); - const withOnChunkLoad = this.runtimeRequirements.has( - RuntimeGlobals.onChunksLoaded - ); - const withLoading = this.runtimeRequirements.has( - RuntimeGlobals.ensureChunkHandlers - ); - const withHmr = this.runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const withHmrManifest = this.runtimeRequirements.has( - RuntimeGlobals.hmrDownloadManifest - ); - const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); - const hasJsMatcher = compileBooleanMatcher(conditionMap); - const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); - - const outputName = this.compilation.getPath( - getChunkFilenameTemplate(chunk, this.compilation.outputOptions), - { - chunk, - contentHashType: "javascript" - } - ); - const rootOutputDir = getUndoPath( - outputName, - this.compilation.outputOptions.path, - false - ); - - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_readFileVm` - : undefined; + getCondition(moduleGraph) { + return connection => { + const refModule = connection.resolvedModule; + if (!refModule) return true; + return refModule.getSideEffectsConnectionState(moduleGraph); + }; + } - return Template.asString([ - withBaseURI - ? Template.asString([ - `${RuntimeGlobals.baseURI} = require("url").pathToFileURL(${ - rootOutputDir - ? `__dirname + ${JSON.stringify("/" + rootOutputDir)}` - : "__filename" - });` - ]) - : "// no baseURI", - "", - "// object to store loaded chunks", - '// "0" means "already loaded", Promise means loading', - `var installedChunks = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{`, - Template.indent( - Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join( - ",\n" - ) - ), - "};", - "", - withOnChunkLoad - ? `${ - RuntimeGlobals.onChunksLoaded - }.readFileVm = ${runtimeTemplate.returningFunction( - "installedChunks[chunkId] === 0", - "chunkId" - )};` - : "// no on chunks loaded", - "", - withLoading || withExternalInstallChunk - ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [ - "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", - "for(var moduleId in moreModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, - Template.indent([ - `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` - ]), - "}" - ]), - "}", - `if(runtime) runtime(__webpack_require__);`, - "for(var i = 0; i < chunkIds.length; i++) {", - Template.indent([ - "if(installedChunks[chunkIds[i]]) {", - Template.indent(["installedChunks[chunkIds[i]][0]();"]), - "}", - "installedChunks[chunkIds[i]] = 0;" - ]), - "}", - withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" - ])};` - : "// no chunk install function needed", - "", - withLoading - ? Template.asString([ - "// ReadFile + VM.run chunk loading for javascript", - `${fn}.readFileVm = function(chunkId, promises) {`, - hasJsMatcher !== false - ? Template.indent([ - "", - "var installedChunkData = installedChunks[chunkId];", - 'if(installedChunkData !== 0) { // 0 means "already installed".', - Template.indent([ - '// array of [resolve, reject, promise] means "currently loading"', - "if(installedChunkData) {", - Template.indent(["promises.push(installedChunkData[2]);"]), - "} else {", - Template.indent([ - hasJsMatcher === true - ? "if(true) { // all chunks have JS" - : `if(${hasJsMatcher("chunkId")}) {`, - Template.indent([ - "// load the chunk and return promise to it", - "var promise = new Promise(function(resolve, reject) {", - Template.indent([ - "installedChunkData = installedChunks[chunkId] = [resolve, reject];", - `var filename = require('path').join(__dirname, ${JSON.stringify( - rootOutputDir - )} + ${ - RuntimeGlobals.getChunkScriptFilename - }(chunkId));`, - "require('fs').readFile(filename, 'utf-8', function(err, content) {", - Template.indent([ - "if(err) return reject(err);", - "var chunk = {};", - "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + - "(chunk, require, require('path').dirname(filename), filename);", - "installChunk(chunk);" - ]), - "});" - ]), - "});", - "promises.push(installedChunkData[2] = promise);" - ]), - "} else installedChunks[chunkId] = 0;" - ]), - "}" - ]), - "}" - ]) - : Template.indent(["installedChunks[chunkId] = 0;"]), - "};" - ]) - : "// no chunk loading", - "", - withExternalInstallChunk - ? Template.asString([ - "module.exports = __webpack_require__;", - `${RuntimeGlobals.externalInstallChunk} = installChunk;` - ]) - : "// no external install chunk", - "", - withHmr - ? Template.asString([ - "function loadUpdateChunk(chunkId, updatedModulesList) {", - Template.indent([ - "return new Promise(function(resolve, reject) {", - Template.indent([ - `var filename = require('path').join(__dirname, ${JSON.stringify( - rootOutputDir - )} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`, - "require('fs').readFile(filename, 'utf-8', function(err, content) {", - Template.indent([ - "if(err) return reject(err);", - "var update = {};", - "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + - "(update, require, require('path').dirname(filename), filename);", - "var updatedModules = update.modules;", - "var runtime = update.runtime;", - "for(var moduleId in updatedModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, - Template.indent([ - `currentUpdate[moduleId] = updatedModules[moduleId];`, - "if(updatedModulesList) updatedModulesList.push(moduleId);" - ]), - "}" - ]), - "}", - "if(runtime) currentUpdateRuntime.push(runtime);", - "resolve();" - ]), - "});" - ]), - "});" - ]), - "}", - "", - Template.getFunctionContent( - require('./JavascriptHotModuleReplacement.runtime.js') - ) - .replace(/\$key\$/g, "readFileVm") - .replace(/\$installedChunks\$/g, "installedChunks") - .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") - .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) - .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) - .replace( - /\$ensureChunkHandlers\$/g, - RuntimeGlobals.ensureChunkHandlers - ) - .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) - .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) - .replace( - /\$hmrDownloadUpdateHandlers\$/g, - RuntimeGlobals.hmrDownloadUpdateHandlers - ) - .replace( - /\$hmrInvalidateModuleHandlers\$/g, - RuntimeGlobals.hmrInvalidateModuleHandlers - ) - ]) - : "// no HMR", - "", - withHmrManifest - ? Template.asString([ - `${RuntimeGlobals.hmrDownloadManifest} = function() {`, - Template.indent([ - "return new Promise(function(resolve, reject) {", - Template.indent([ - `var filename = require('path').join(__dirname, ${JSON.stringify( - rootOutputDir - )} + ${RuntimeGlobals.getUpdateManifestFilename}());`, - "require('fs').readFile(filename, 'utf-8', function(err, content) {", - Template.indent([ - "if(err) {", - Template.indent([ - 'if(err.code === "ENOENT") return resolve();', - "return reject(err);" - ]), - "}", - "try { resolve(JSON.parse(content)); }", - "catch(e) { reject(e); }" - ]), - "});" - ]), - "});" - ]), - "}" - ]) - : "// no HMR manifest" - ]); + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + const refModule = moduleGraph.getModule(this); + if (!refModule) return true; + return refModule.getSideEffectsConnectionState(moduleGraph); } } -module.exports = ReadFileChunkLoadingRuntimeModule; - - -/***/ }), - -/***/ 73163: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const AsyncWasmLoadingRuntimeModule = __webpack_require__(5434); - -/** @typedef {import("../Compiler")} Compiler */ +makeSerializable( + HarmonyImportSideEffectDependency, + "webpack/lib/dependencies/HarmonyImportSideEffectDependency" +); -class ReadFileCompileAsyncWasmPlugin { - constructor({ type = "async-node", import: useImport = false } = {}) { - this._type = type; - this._import = useImport; - } +HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends ( + HarmonyImportDependency.Template +) { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - compiler.hooks.thisCompilation.tap( - "ReadFileCompileAsyncWasmPlugin", - compilation => { - const globalWasmLoading = compilation.outputOptions.wasmLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const wasmLoading = - options && options.wasmLoading !== undefined - ? options.wasmLoading - : globalWasmLoading; - return wasmLoading === this._type; - }; - const generateLoadBinaryCode = this._import - ? path => - Template.asString([ - "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {", - Template.indent([ - `readFile(new URL(${path}, import.meta.url), (err, buffer) => {`, - Template.indent([ - "if (err) return reject(err);", - "", - "// Fake fetch response", - "resolve({", - Template.indent(["arrayBuffer() { return buffer; }"]), - "});" - ]), - "});" - ]), - "}))" - ]) - : path => - Template.asString([ - "new Promise(function (resolve, reject) {", - Template.indent([ - "try {", - Template.indent([ - "var { readFile } = require('fs');", - "var { join } = require('path');", - "", - `readFile(join(__dirname, ${path}), function(err, buffer){`, - Template.indent([ - "if (err) return reject(err);", - "", - "// Fake fetch response", - "resolve({", - Template.indent(["arrayBuffer() { return buffer; }"]), - "});" - ]), - "});" - ]), - "} catch (err) { reject(err); }" - ]), - "})" - ]); - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.instantiateWasm) - .tap("ReadFileCompileAsyncWasmPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - const chunkGraph = compilation.chunkGraph; - if ( - !chunkGraph.hasModuleInGraph( - chunk, - m => m.type === "webassembly/async" - ) - ) { - return; - } - set.add(RuntimeGlobals.publicPath); - compilation.addRuntimeModule( - chunk, - new AsyncWasmLoadingRuntimeModule({ - generateLoadBinaryCode, - supportsStreaming: false - }) - ); - }); + apply(dependency, source, templateContext) { + const { moduleGraph, concatenationScope } = templateContext; + if (concatenationScope) { + const module = moduleGraph.getModule(dependency); + if (concatenationScope.isModuleInScope(module)) { + return; } - ); + } + super.apply(dependency, source, templateContext); } -} +}; -module.exports = ReadFileCompileAsyncWasmPlugin; +module.exports = HarmonyImportSideEffectDependency; /***/ }), -/***/ 98939: +/***/ 14077: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -98907,479 +92157,335 @@ module.exports = ReadFileCompileAsyncWasmPlugin; -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const WasmChunkLoadingRuntimeModule = __webpack_require__(87394); +const Dependency = __webpack_require__(54912); +const { + getDependencyUsedByExportsCondition +} = __webpack_require__(38988); +const makeSerializable = __webpack_require__(33032); +const propertyAccess = __webpack_require__(54190); +const HarmonyImportDependency = __webpack_require__(57154); -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -// TODO webpack 6 remove +const idsSymbol = Symbol("HarmonyImportSpecifierDependency.ids"); -class ReadFileCompileWasmPlugin { - constructor(options) { - this.options = options || {}; +const { ExportPresenceModes } = HarmonyImportDependency; + +class HarmonyImportSpecifierDependency extends HarmonyImportDependency { + constructor( + request, + sourceOrder, + ids, + name, + range, + exportPresenceMode, + assertions + ) { + super(request, sourceOrder, assertions); + this.ids = ids; + this.name = name; + this.range = range; + this.exportPresenceMode = exportPresenceMode; + this.namespaceObjectAsContext = false; + this.call = undefined; + this.directImport = undefined; + this.shorthand = undefined; + this.asiSafe = undefined; + /** @type {Set | boolean} */ + this.usedByExports = undefined; } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "ReadFileCompileWasmPlugin", - compilation => { - const globalWasmLoading = compilation.outputOptions.wasmLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const wasmLoading = - options && options.wasmLoading !== undefined - ? options.wasmLoading - : globalWasmLoading; - return wasmLoading === "async-node"; - }; - const generateLoadBinaryCode = path => - Template.asString([ - "new Promise(function (resolve, reject) {", - Template.indent([ - "var { readFile } = require('fs');", - "var { join } = require('path');", - "", - "try {", - Template.indent([ - `readFile(join(__dirname, ${path}), function(err, buffer){`, - Template.indent([ - "if (err) return reject(err);", - "", - "// Fake fetch response", - "resolve({", - Template.indent(["arrayBuffer() { return buffer; }"]), - "});" - ]), - "});" - ]), - "} catch (err) { reject(err); }" - ]), - "})" - ]); + // TODO webpack 6 remove + get id() { + throw new Error("id was renamed to ids and type changed to string[]"); + } - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("ReadFileCompileWasmPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - const chunkGraph = compilation.chunkGraph; - if ( - !chunkGraph.hasModuleInGraph( - chunk, - m => m.type === "webassembly/sync" - ) - ) { - return; - } - set.add(RuntimeGlobals.moduleCache); - compilation.addRuntimeModule( - chunk, - new WasmChunkLoadingRuntimeModule({ - generateLoadBinaryCode, - supportsStreaming: false, - mangleImports: this.options.mangleImports, - runtimeRequirements: set - }) - ); - }); - } - ); + // TODO webpack 6 remove + getId() { + throw new Error("id was renamed to ids and type changed to string[]"); } -} -module.exports = ReadFileCompileWasmPlugin; + // TODO webpack 6 remove + setId() { + throw new Error("id was renamed to ids and type changed to string[]"); + } + get type() { + return "harmony import specifier"; + } -/***/ }), + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {string[]} the imported ids + */ + getIds(moduleGraph) { + const meta = moduleGraph.getMetaIfExisting(this); + if (meta === undefined) return this.ids; + const ids = meta[idsSymbol]; + return ids !== undefined ? ids : this.ids; + } -/***/ 94172: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {string[]} ids the imported ids + * @returns {void} + */ + setIds(moduleGraph, ids) { + moduleGraph.getMeta(this)[idsSymbol] = ids; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return getDependencyUsedByExportsCondition( + this, + this.usedByExports, + moduleGraph + ); + } + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } + /** + * 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) { + let ids = this.getIds(moduleGraph); + if (ids.length === 0) return Dependency.EXPORTS_OBJECT_REFERENCED; + let namespaceObjectAsContext = this.namespaceObjectAsContext; + if (ids[0] === "default") { + const selfModule = moduleGraph.getParentModule(this); + const importedModule = moduleGraph.getModule(this); + switch ( + importedModule.getExportsType( + moduleGraph, + selfModule.buildMeta.strictHarmonyModule + ) + ) { + case "default-only": + case "default-with-named": + if (ids.length === 1) return Dependency.EXPORTS_OBJECT_REFERENCED; + ids = ids.slice(1); + namespaceObjectAsContext = true; + break; + case "dynamic": + return Dependency.EXPORTS_OBJECT_REFERENCED; + } + } -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); -const { - chunkHasJs, - getChunkFilenameTemplate -} = __webpack_require__(89464); -const { getInitialChunkIds } = __webpack_require__(98124); -const compileBooleanMatcher = __webpack_require__(29404); -const { getUndoPath } = __webpack_require__(82186); + if ( + this.call && + !this.directImport && + (namespaceObjectAsContext || ids.length > 1) + ) { + if (ids.length === 1) return Dependency.EXPORTS_OBJECT_REFERENCED; + ids = ids.slice(0, -1); + } -class RequireChunkLoadingRuntimeModule extends RuntimeModule { - constructor(runtimeRequirements) { - super("require chunk loading", RuntimeModule.STAGE_ATTACH); - this.runtimeRequirements = runtimeRequirements; + return [ids]; } /** - * @returns {string} runtime code + * @param {ModuleGraph} moduleGraph module graph + * @returns {number} effective mode */ - generate() { - const { chunkGraph, chunk } = this; - const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.ensureChunkHandlers; - const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); - const withExternalInstallChunk = this.runtimeRequirements.has( - RuntimeGlobals.externalInstallChunk - ); - const withOnChunkLoad = this.runtimeRequirements.has( - RuntimeGlobals.onChunksLoaded - ); - const withLoading = this.runtimeRequirements.has( - RuntimeGlobals.ensureChunkHandlers - ); - const withHmr = this.runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const withHmrManifest = this.runtimeRequirements.has( - RuntimeGlobals.hmrDownloadManifest - ); - const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); - const hasJsMatcher = compileBooleanMatcher(conditionMap); - const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); - - const outputName = this.compilation.getPath( - getChunkFilenameTemplate(chunk, this.compilation.outputOptions), - { - chunk, - contentHashType: "javascript" - } - ); - const rootOutputDir = getUndoPath( - outputName, - this.compilation.outputOptions.path, - true - ); + _getEffectiveExportPresenceLevel(moduleGraph) { + if (this.exportPresenceMode !== ExportPresenceModes.AUTO) + return this.exportPresenceMode; + return moduleGraph.getParentModule(this).buildMeta.strictHarmonyModule + ? ExportPresenceModes.ERROR + : ExportPresenceModes.WARN; + } - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_require` - : undefined; + /** + * Returns warnings + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} warnings + */ + getWarnings(moduleGraph) { + const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); + if (exportsPresence === ExportPresenceModes.WARN) { + return this._getErrors(moduleGraph); + } + return null; + } - return Template.asString([ - withBaseURI - ? Template.asString([ - `${RuntimeGlobals.baseURI} = require("url").pathToFileURL(${ - rootOutputDir !== "./" - ? `__dirname + ${JSON.stringify("/" + rootOutputDir)}` - : "__filename" - });` - ]) - : "// no baseURI", - "", - "// object to store loaded chunks", - '// "1" means "loaded", otherwise not loaded yet', - `var installedChunks = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{`, - Template.indent( - Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 1`).join( - ",\n" - ) - ), - "};", - "", - withOnChunkLoad - ? `${ - RuntimeGlobals.onChunksLoaded - }.require = ${runtimeTemplate.returningFunction( - "installedChunks[chunkId]", - "chunkId" - )};` - : "// no on chunks loaded", - "", - withLoading || withExternalInstallChunk - ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [ - "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", - "for(var moduleId in moreModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, - Template.indent([ - `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` - ]), - "}" - ]), - "}", - `if(runtime) runtime(__webpack_require__);`, - "for(var i = 0; i < chunkIds.length; i++)", - Template.indent("installedChunks[chunkIds[i]] = 1;"), - withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" - ])};` - : "// no chunk install function needed", - "", - withLoading - ? Template.asString([ - "// require() chunk loading for javascript", - `${fn}.require = ${runtimeTemplate.basicFunction( - "chunkId, promises", - hasJsMatcher !== false - ? [ - '// "1" is the signal for "already loaded"', - "if(!installedChunks[chunkId]) {", - Template.indent([ - hasJsMatcher === true - ? "if(true) { // all chunks have JS" - : `if(${hasJsMatcher("chunkId")}) {`, - Template.indent([ - `installChunk(require(${JSON.stringify( - rootOutputDir - )} + ${ - RuntimeGlobals.getChunkScriptFilename - }(chunkId)));` - ]), - "} else installedChunks[chunkId] = 1;", - "" - ]), - "}" - ] - : "installedChunks[chunkId] = 1;" - )};` - ]) - : "// no chunk loading", - "", - withExternalInstallChunk - ? Template.asString([ - "module.exports = __webpack_require__;", - `${RuntimeGlobals.externalInstallChunk} = installChunk;` - ]) - : "// no external install chunk", - "", - withHmr - ? Template.asString([ - "function loadUpdateChunk(chunkId, updatedModulesList) {", - Template.indent([ - `var update = require(${JSON.stringify(rootOutputDir)} + ${ - RuntimeGlobals.getChunkUpdateScriptFilename - }(chunkId));`, - "var updatedModules = update.modules;", - "var runtime = update.runtime;", - "for(var moduleId in updatedModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, - Template.indent([ - `currentUpdate[moduleId] = updatedModules[moduleId];`, - "if(updatedModulesList) updatedModulesList.push(moduleId);" - ]), - "}" - ]), - "}", - "if(runtime) currentUpdateRuntime.push(runtime);" - ]), - "}", - "", - Template.getFunctionContent( - require('./JavascriptHotModuleReplacement.runtime.js') - ) - .replace(/\$key\$/g, "require") - .replace(/\$installedChunks\$/g, "installedChunks") - .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") - .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) - .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) - .replace( - /\$ensureChunkHandlers\$/g, - RuntimeGlobals.ensureChunkHandlers - ) - .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) - .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) - .replace( - /\$hmrDownloadUpdateHandlers\$/g, - RuntimeGlobals.hmrDownloadUpdateHandlers - ) - .replace( - /\$hmrInvalidateModuleHandlers\$/g, - RuntimeGlobals.hmrInvalidateModuleHandlers - ) - ]) - : "// no HMR", - "", - withHmrManifest - ? Template.asString([ - `${RuntimeGlobals.hmrDownloadManifest} = function() {`, - Template.indent([ - "return Promise.resolve().then(function() {", - Template.indent([ - `return require(${JSON.stringify(rootOutputDir)} + ${ - RuntimeGlobals.getUpdateManifestFilename - }());` - ]), - "})['catch'](function(err) { if(err.code !== 'MODULE_NOT_FOUND') throw err; });" - ]), - "}" - ]) - : "// no HMR manifest" - ]); + /** + * Returns errors + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} errors + */ + getErrors(moduleGraph) { + const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); + if (exportsPresence === ExportPresenceModes.ERROR) { + return this._getErrors(moduleGraph); + } + return null; } -} -module.exports = RequireChunkLoadingRuntimeModule; + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | undefined} errors + */ + _getErrors(moduleGraph) { + const ids = this.getIds(moduleGraph); + return this.getLinkingErrors( + moduleGraph, + ids, + `(imported as '${this.name}')` + ); + } + /** + * 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 0; + } -/***/ }), + serialize(context) { + const { write } = context; + write(this.ids); + write(this.name); + write(this.range); + write(this.exportPresenceMode); + write(this.namespaceObjectAsContext); + write(this.call); + write(this.directImport); + write(this.shorthand); + write(this.asiSafe); + write(this.usedByExports); + super.serialize(context); + } -/***/ 91786: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + deserialize(context) { + const { read } = context; + this.ids = read(); + this.name = read(); + this.range = read(); + this.exportPresenceMode = read(); + this.namespaceObjectAsContext = read(); + this.call = read(); + this.directImport = read(); + this.shorthand = read(); + this.asiSafe = read(); + this.usedByExports = read(); + super.deserialize(context); + } +} -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +makeSerializable( + HarmonyImportSpecifierDependency, + "webpack/lib/dependencies/HarmonyImportSpecifierDependency" +); +HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate extends ( + HarmonyImportDependency.Template +) { + /** + * @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 dep = /** @type {HarmonyImportSpecifierDependency} */ (dependency); + const { moduleGraph, module, runtime, concatenationScope } = + templateContext; + const connection = moduleGraph.getConnection(dep); + // Skip rendering depending when dependency is conditional + if (connection && !connection.isTargetActive(runtime)) return; + const ids = dep.getIds(moduleGraph); -const util = __webpack_require__(73837); -const truncateArgs = __webpack_require__(62090); + let exportExpr; + if ( + connection && + concatenationScope && + concatenationScope.isModuleInScope(connection.module) + ) { + if (ids.length === 0) { + exportExpr = concatenationScope.createModuleReference( + connection.module, + { + asiSafe: dep.asiSafe + } + ); + } else if (dep.namespaceObjectAsContext && ids.length === 1) { + exportExpr = + concatenationScope.createModuleReference(connection.module, { + asiSafe: dep.asiSafe + }) + propertyAccess(ids); + } else { + exportExpr = concatenationScope.createModuleReference( + connection.module, + { + ids, + call: dep.call, + directImport: dep.directImport, + asiSafe: dep.asiSafe + } + ); + } + } else { + super.apply(dependency, source, templateContext); -module.exports = ({ colors, appendOnly, stream }) => { - let currentStatusMessage = undefined; - let hasStatusMessage = false; - let currentIndent = ""; - let currentCollapsed = 0; + const { runtimeTemplate, initFragments, runtimeRequirements } = + templateContext; - const indent = (str, prefix, colorPrefix, colorSuffix) => { - if (str === "") return str; - prefix = currentIndent + prefix; - if (colors) { - return ( - prefix + - colorPrefix + - str.replace(/\n/g, colorSuffix + "\n" + prefix + colorPrefix) + - colorSuffix - ); - } else { - return prefix + str.replace(/\n/g, "\n" + prefix); + exportExpr = runtimeTemplate.exportFromImport({ + moduleGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + exportName: ids, + originModule: module, + asiSafe: dep.shorthand ? true : dep.asiSafe, + isCall: dep.call, + callContext: !dep.directImport, + defaultInterop: true, + importVar: dep.getImportVar(moduleGraph), + initFragments, + runtime, + runtimeRequirements + }); } - }; - - const clearStatusMessage = () => { - if (hasStatusMessage) { - stream.write("\x1b[2K\r"); - hasStatusMessage = false; + if (dep.shorthand) { + source.insert(dep.range[1], `: ${exportExpr}`); + } else { + source.replace(dep.range[0], dep.range[1] - 1, exportExpr); } - }; - - const writeStatusMessage = () => { - if (!currentStatusMessage) return; - const l = stream.columns; - const args = l - ? truncateArgs(currentStatusMessage, l - 1) - : currentStatusMessage; - const str = args.join(" "); - const coloredStr = `\u001b[1m${str}\u001b[39m\u001b[22m`; - stream.write(`\x1b[2K\r${coloredStr}`); - hasStatusMessage = true; - }; - - const writeColored = (prefix, colorPrefix, colorSuffix) => { - return (...args) => { - if (currentCollapsed > 0) return; - clearStatusMessage(); - const str = indent( - util.format(...args), - prefix, - colorPrefix, - colorSuffix - ); - stream.write(str + "\n"); - writeStatusMessage(); - }; - }; - - const writeGroupMessage = writeColored( - "<-> ", - "\u001b[1m\u001b[36m", - "\u001b[39m\u001b[22m" - ); - - const writeGroupCollapsedMessage = writeColored( - "<+> ", - "\u001b[1m\u001b[36m", - "\u001b[39m\u001b[22m" - ); - - return { - log: writeColored(" ", "\u001b[1m", "\u001b[22m"), - debug: writeColored(" ", "", ""), - trace: writeColored(" ", "", ""), - info: writeColored(" ", "\u001b[1m\u001b[32m", "\u001b[39m\u001b[22m"), - warn: writeColored(" ", "\u001b[1m\u001b[33m", "\u001b[39m\u001b[22m"), - error: writeColored(" ", "\u001b[1m\u001b[31m", "\u001b[39m\u001b[22m"), - logTime: writeColored( - " ", - "\u001b[1m\u001b[35m", - "\u001b[39m\u001b[22m" - ), - group: (...args) => { - writeGroupMessage(...args); - if (currentCollapsed > 0) { - currentCollapsed++; - } else { - currentIndent += " "; - } - }, - groupCollapsed: (...args) => { - writeGroupCollapsedMessage(...args); - currentCollapsed++; - }, - groupEnd: () => { - if (currentCollapsed > 0) currentCollapsed--; - else if (currentIndent.length >= 2) - currentIndent = currentIndent.slice(0, currentIndent.length - 2); - }, - // eslint-disable-next-line node/no-unsupported-features/node-builtins - profile: console.profile && (name => console.profile(name)), - // eslint-disable-next-line node/no-unsupported-features/node-builtins - profileEnd: console.profileEnd && (name => console.profileEnd(name)), - clear: - !appendOnly && - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.clear && - (() => { - clearStatusMessage(); - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.clear(); - writeStatusMessage(); - }), - status: appendOnly - ? writeColored(" ", "", "") - : (name, ...args) => { - args = args.filter(Boolean); - if (name === undefined && args.length === 0) { - clearStatusMessage(); - currentStatusMessage = undefined; - } else if ( - typeof name === "string" && - name.startsWith("[webpack.Progress] ") - ) { - currentStatusMessage = [name.slice(19), ...args]; - writeStatusMessage(); - } else if (name === "[webpack.Progress]") { - currentStatusMessage = [...args]; - writeStatusMessage(); - } else { - currentStatusMessage = [name, ...args]; - writeStatusMessage(); - } - } - }; + } }; +module.exports = HarmonyImportSpecifierDependency; + /***/ }), -/***/ 64395: +/***/ 39029: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99390,22 +92496,26 @@ module.exports = ({ colors, appendOnly, stream }) => { -const { STAGE_ADVANCED } = __webpack_require__(80057); +const HarmonyAcceptDependency = __webpack_require__(23624); +const HarmonyAcceptImportDependency = __webpack_require__(99843); +const HarmonyCompatibilityDependency = __webpack_require__(72906); +const HarmonyExportExpressionDependency = __webpack_require__(51340); +const HarmonyExportHeaderDependency = __webpack_require__(38873); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(67157); +const HarmonyExportSpecifierDependency = __webpack_require__(48567); +const HarmonyImportSideEffectDependency = __webpack_require__(73132); +const HarmonyImportSpecifierDependency = __webpack_require__(14077); + +const HarmonyDetectionParserPlugin = __webpack_require__(17223); +const HarmonyExportDependencyParserPlugin = __webpack_require__(93466); +const HarmonyImportDependencyParserPlugin = __webpack_require__(20862); +const HarmonyTopLevelThisParserPlugin = __webpack_require__(63232); -/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Compiler")} Compiler */ -class AggressiveMergingPlugin { +class HarmonyModulesPlugin { constructor(options) { - if ( - (options !== undefined && typeof options !== "object") || - Array.isArray(options) - ) { - throw new Error( - "Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see https://webpack.js.org/plugins/" - ); - } - this.options = options || {}; + this.options = options; } /** @@ -99414,409 +92524,194 @@ class AggressiveMergingPlugin { * @returns {void} */ apply(compiler) { - const options = this.options; - const minSizeReduce = options.minSizeReduce || 1.5; + compiler.hooks.compilation.tap( + "HarmonyModulesPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + HarmonyCompatibilityDependency, + new HarmonyCompatibilityDependency.Template() + ); - compiler.hooks.thisCompilation.tap( - "AggressiveMergingPlugin", - compilation => { - compilation.hooks.optimizeChunks.tap( - { - name: "AggressiveMergingPlugin", - stage: STAGE_ADVANCED - }, - chunks => { - const chunkGraph = compilation.chunkGraph; - /** @type {{a: Chunk, b: Chunk, improvement: number}[]} */ - let combinations = []; - for (const a of chunks) { - if (a.canBeInitial()) continue; - for (const b of chunks) { - if (b.canBeInitial()) continue; - if (b === a) break; - if (!chunkGraph.canChunksBeIntegrated(a, b)) { - continue; - } - const aSize = chunkGraph.getChunkSize(b, { - chunkOverhead: 0 - }); - const bSize = chunkGraph.getChunkSize(a, { - chunkOverhead: 0 - }); - const abSize = chunkGraph.getIntegratedChunksSize(b, a, { - chunkOverhead: 0 - }); - const improvement = (aSize + bSize) / abSize; - combinations.push({ - a, - b, - improvement - }); - } - } + compilation.dependencyFactories.set( + HarmonyImportSideEffectDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSideEffectDependency, + new HarmonyImportSideEffectDependency.Template() + ); - combinations.sort((a, b) => { - return b.improvement - a.improvement; - }); + compilation.dependencyFactories.set( + HarmonyImportSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSpecifierDependency, + new HarmonyImportSpecifierDependency.Template() + ); - const pair = combinations[0]; + compilation.dependencyTemplates.set( + HarmonyExportHeaderDependency, + new HarmonyExportHeaderDependency.Template() + ); - if (!pair) return; - if (pair.improvement < minSizeReduce) return; + compilation.dependencyTemplates.set( + HarmonyExportExpressionDependency, + new HarmonyExportExpressionDependency.Template() + ); - chunkGraph.integrateChunks(pair.b, pair.a); - compilation.chunks.delete(pair.a); - return true; - } + compilation.dependencyTemplates.set( + HarmonyExportSpecifierDependency, + new HarmonyExportSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportImportedSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyExportImportedSpecifierDependency, + new HarmonyExportImportedSpecifierDependency.Template() ); + + compilation.dependencyTemplates.set( + HarmonyAcceptDependency, + new HarmonyAcceptDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyAcceptImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyAcceptImportDependency, + new HarmonyAcceptImportDependency.Template() + ); + + const handler = (parser, parserOptions) => { + // TODO webpack 6: rename harmony to esm or module + if (parserOptions.harmony !== undefined && !parserOptions.harmony) + return; + + new HarmonyDetectionParserPlugin(this.options).apply(parser); + new HarmonyImportDependencyParserPlugin(parserOptions).apply(parser); + new HarmonyExportDependencyParserPlugin(parserOptions).apply(parser); + new HarmonyTopLevelThisParserPlugin().apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("HarmonyModulesPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("HarmonyModulesPlugin", handler); } ); } } - -module.exports = AggressiveMergingPlugin; +module.exports = HarmonyModulesPlugin; /***/ }), -/***/ 15543: +/***/ 63232: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Florent Cailhol @ooflorent */ -const { STAGE_ADVANCED } = __webpack_require__(80057); -const { intersect } = __webpack_require__(93347); -const { - compareModulesByIdentifier, - compareChunks -} = __webpack_require__(29579); -const createSchemaValidation = __webpack_require__(32540); -const identifierUtils = __webpack_require__(82186); - -/** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ - -const validate = createSchemaValidation( - __webpack_require__(32697), - () => - __webpack_require__(47995), - { - name: "Aggressive Splitting Plugin", - baseDataPath: "options" - } -); - -const moveModuleBetween = (chunkGraph, oldChunk, newChunk) => { - return module => { - chunkGraph.disconnectChunkAndModule(oldChunk, module); - chunkGraph.connectChunkAndModule(newChunk, module); - }; -}; - -/** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {Chunk} chunk the chunk - * @returns {function(Module): boolean} filter for entry module - */ -const isNotAEntryModule = (chunkGraph, chunk) => { - return module => { - return !chunkGraph.isEntryModuleInChunk(module, chunk); - }; -}; - -/** @type {WeakSet} */ -const recordedChunks = new WeakSet(); - -class AggressiveSplittingPlugin { - /** - * @param {AggressiveSplittingPluginOptions=} options options object - */ - constructor(options = {}) { - validate(options); - - this.options = options; - if (typeof this.options.minSize !== "number") { - this.options.minSize = 30 * 1024; - } - if (typeof this.options.maxSize !== "number") { - this.options.maxSize = 50 * 1024; - } - if (typeof this.options.chunkOverhead !== "number") { - this.options.chunkOverhead = 0; - } - if (typeof this.options.entryChunkMultiplicator !== "number") { - this.options.entryChunkMultiplicator = 1; - } - } +const ConstDependency = __webpack_require__(76911); +const HarmonyExports = __webpack_require__(39211); - /** - * @param {Chunk} chunk the chunk to test - * @returns {boolean} true if the chunk was recorded - */ - static wasChunkRecorded(chunk) { - return recordedChunks.has(chunk); +class HarmonyTopLevelThisParserPlugin { + apply(parser) { + parser.hooks.expression + .for("this") + .tap("HarmonyTopLevelThisParserPlugin", node => { + if (!parser.scope.topLevelScope) return; + if (HarmonyExports.isEnabled(parser.state)) { + const dep = new ConstDependency("undefined", node.range, null); + dep.loc = node.loc; + parser.state.module.addPresentationalDependency(dep); + return this; + } + }); } +} - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "AggressiveSplittingPlugin", - compilation => { - let needAdditionalSeal = false; - let newSplits; - let fromAggressiveSplittingSet; - let chunkSplitDataMap; - compilation.hooks.optimize.tap("AggressiveSplittingPlugin", () => { - newSplits = []; - fromAggressiveSplittingSet = new Set(); - chunkSplitDataMap = new Map(); - }); - compilation.hooks.optimizeChunks.tap( - { - name: "AggressiveSplittingPlugin", - stage: STAGE_ADVANCED - }, - chunks => { - const chunkGraph = compilation.chunkGraph; - // Precompute stuff - const nameToModuleMap = new Map(); - const moduleToNameMap = new Map(); - const makePathsRelative = - identifierUtils.makePathsRelative.bindContextCache( - compiler.context, - compiler.root - ); - for (const m of compilation.modules) { - const name = makePathsRelative(m.identifier()); - nameToModuleMap.set(name, m); - moduleToNameMap.set(m, name); - } +module.exports = HarmonyTopLevelThisParserPlugin; - // Check used chunk ids - const usedIds = new Set(); - for (const chunk of chunks) { - usedIds.add(chunk.id); - } - const recordedSplits = - (compilation.records && compilation.records.aggressiveSplits) || - []; - const usedSplits = newSplits - ? recordedSplits.concat(newSplits) - : recordedSplits; +/***/ }), - const minSize = this.options.minSize; - const maxSize = this.options.maxSize; +/***/ 1902: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const applySplit = splitData => { - // Cannot split if id is already taken - if (splitData.id !== undefined && usedIds.has(splitData.id)) { - return false; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Get module objects from names - const selectedModules = splitData.modules.map(name => - nameToModuleMap.get(name) - ); - // Does the modules exist at all? - if (!selectedModules.every(Boolean)) return false; - // Check if size matches (faster than waiting for hash) - let size = 0; - for (const m of selectedModules) size += m.size(); - if (size !== splitData.size) return false; +const makeSerializable = __webpack_require__(33032); +const ContextDependency = __webpack_require__(88101); +const ContextDependencyTemplateAsRequireCall = __webpack_require__(75815); - // get chunks with all modules - const selectedChunks = intersect( - selectedModules.map( - m => new Set(chunkGraph.getModuleChunksIterable(m)) - ) - ); +class ImportContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); - // No relevant chunks found - if (selectedChunks.size === 0) return false; + this.range = range; + this.valueRange = valueRange; + } - // The found chunk is already the split or similar - if ( - selectedChunks.size === 1 && - chunkGraph.getNumberOfChunkModules( - Array.from(selectedChunks)[0] - ) === selectedModules.length - ) { - const chunk = Array.from(selectedChunks)[0]; - if (fromAggressiveSplittingSet.has(chunk)) return false; - fromAggressiveSplittingSet.add(chunk); - chunkSplitDataMap.set(chunk, splitData); - return true; - } + get type() { + return `import() context ${this.options.mode}`; + } - // split the chunk into two parts - const newChunk = compilation.addChunk(); - newChunk.chunkReason = "aggressive splitted"; - for (const chunk of selectedChunks) { - selectedModules.forEach( - moveModuleBetween(chunkGraph, chunk, newChunk) - ); - chunk.split(newChunk); - chunk.name = null; - } - fromAggressiveSplittingSet.add(newChunk); - chunkSplitDataMap.set(newChunk, splitData); + get category() { + return "esm"; + } - if (splitData.id !== null && splitData.id !== undefined) { - newChunk.id = splitData.id; - newChunk.ids = [splitData.id]; - } - return true; - }; + serialize(context) { + const { write } = context; - // try to restore to recorded splitting - let changed = false; - for (let j = 0; j < usedSplits.length; j++) { - const splitData = usedSplits[j]; - if (applySplit(splitData)) changed = true; - } + write(this.range); + write(this.valueRange); - // for any chunk which isn't splitted yet, split it and create a new entry - // start with the biggest chunk - const cmpFn = compareChunks(chunkGraph); - const sortedChunks = Array.from(chunks).sort((a, b) => { - const diff1 = - chunkGraph.getChunkModulesSize(b) - - chunkGraph.getChunkModulesSize(a); - if (diff1) return diff1; - const diff2 = - chunkGraph.getNumberOfChunkModules(a) - - chunkGraph.getNumberOfChunkModules(b); - if (diff2) return diff2; - return cmpFn(a, b); - }); - for (const chunk of sortedChunks) { - if (fromAggressiveSplittingSet.has(chunk)) continue; - const size = chunkGraph.getChunkModulesSize(chunk); - if ( - size > maxSize && - chunkGraph.getNumberOfChunkModules(chunk) > 1 - ) { - const modules = chunkGraph - .getOrderedChunkModules(chunk, compareModulesByIdentifier) - .filter(isNotAEntryModule(chunkGraph, chunk)); - const selectedModules = []; - let selectedModulesSize = 0; - for (let k = 0; k < modules.length; k++) { - const module = modules[k]; - const newSize = selectedModulesSize + module.size(); - if (newSize > maxSize && selectedModulesSize >= minSize) { - break; - } - selectedModulesSize = newSize; - selectedModules.push(module); - } - if (selectedModules.length === 0) continue; - const splitData = { - modules: selectedModules - .map(m => moduleToNameMap.get(m)) - .sort(), - size: selectedModulesSize - }; + super.serialize(context); + } - if (applySplit(splitData)) { - newSplits = (newSplits || []).concat(splitData); - changed = true; - } - } - } - if (changed) return true; - } - ); - compilation.hooks.recordHash.tap( - "AggressiveSplittingPlugin", - records => { - // 4. save made splittings to records - const allSplits = new Set(); - const invalidSplits = new Set(); + deserialize(context) { + const { read } = context; - // Check if some splittings are invalid - // We remove invalid splittings and try again - for (const chunk of compilation.chunks) { - const splitData = chunkSplitDataMap.get(chunk); - if (splitData !== undefined) { - if (splitData.hash && chunk.hash !== splitData.hash) { - // Split was successful, but hash doesn't equal - // We can throw away the split since it's useless now - invalidSplits.add(splitData); - } - } - } + this.range = read(); + this.valueRange = read(); - if (invalidSplits.size > 0) { - records.aggressiveSplits = records.aggressiveSplits.filter( - splitData => !invalidSplits.has(splitData) - ); - needAdditionalSeal = true; - } else { - // set hash and id values on all (new) splittings - for (const chunk of compilation.chunks) { - const splitData = chunkSplitDataMap.get(chunk); - if (splitData !== undefined) { - splitData.hash = chunk.hash; - splitData.id = chunk.id; - allSplits.add(splitData); - // set flag for stats - recordedChunks.add(chunk); - } - } + super.deserialize(context); + } +} - // Also add all unused historical splits (after the used ones) - // They can still be used in some future compilation - const recordedSplits = - compilation.records && compilation.records.aggressiveSplits; - if (recordedSplits) { - for (const splitData of recordedSplits) { - if (!invalidSplits.has(splitData)) allSplits.add(splitData); - } - } +makeSerializable( + ImportContextDependency, + "webpack/lib/dependencies/ImportContextDependency" +); - // record all splits - records.aggressiveSplits = Array.from(allSplits); +ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; - needAdditionalSeal = false; - } - } - ); - compilation.hooks.needAdditionalSeal.tap( - "AggressiveSplittingPlugin", - () => { - if (needAdditionalSeal) { - needAdditionalSeal = false; - return true; - } - } - ); - } - ); - } -} -module.exports = AggressiveSplittingPlugin; +module.exports = ImportContextDependency; /***/ }), -/***/ 97198: +/***/ 89376: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99827,1877 +92722,1012 @@ module.exports = AggressiveSplittingPlugin; -const eslintScope = __webpack_require__(36007); -const Referencer = __webpack_require__(44585); -const { - CachedSource, - ConcatSource, - ReplaceSource -} = __webpack_require__(51255); -const ConcatenationScope = __webpack_require__(98229); -const { UsageState } = __webpack_require__(63686); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const HarmonyImportDependency = __webpack_require__(57154); -const JavascriptParser = __webpack_require__(29050); -const { equals } = __webpack_require__(84953); -const LazySet = __webpack_require__(38938); -const { concatComparators, keepOriginalOrder } = __webpack_require__(29579); -const createHash = __webpack_require__(49835); -const { makePathsRelative } = __webpack_require__(82186); +const Dependency = __webpack_require__(54912); const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const { - filterRuntime, - intersectRuntime, - mergeRuntimeCondition, - mergeRuntimeConditionNonFalse, - runtimeConditionToString, - subtractRuntimeCondition -} = __webpack_require__(17156); +const ModuleDependency = __webpack_require__(80321); -/** @typedef {import("eslint-scope").Scope} Scope */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ -/** @template T @typedef {import("../InitFragment")} InitFragment */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {typeof import("../util/Hash")} HashConstructor */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -// fix eslint-scope to support class properties correctly -// cspell:word Referencer -const ReferencerClass = Referencer; -if (!ReferencerClass.prototype.PropertyDefinition) { - ReferencerClass.prototype.PropertyDefinition = - ReferencerClass.prototype.Property; -} +class ImportDependency extends ModuleDependency { + /** + * @param {string} request the request + * @param {[number, number]} range expression range + * @param {string[][]=} referencedExports list of referenced exports + */ + constructor(request, range, referencedExports) { + super(request); + this.range = range; + this.referencedExports = referencedExports; + } -/** - * @typedef {Object} ReexportInfo - * @property {Module} module - * @property {string[]} export - */ + get type() { + return "import()"; + } -/** @typedef {RawBinding | SymbolBinding} Binding */ + get category() { + return "esm"; + } -/** - * @typedef {Object} RawBinding - * @property {ModuleInfo} info - * @property {string} rawName - * @property {string=} comment - * @property {string[]} ids - * @property {string[]} exportName - */ + /** + * 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 this.referencedExports + ? this.referencedExports.map(e => ({ + name: e, + canMangle: false + })) + : Dependency.EXPORTS_OBJECT_REFERENCED; + } -/** - * @typedef {Object} SymbolBinding - * @property {ConcatenatedModuleInfo} info - * @property {string} name - * @property {string=} comment - * @property {string[]} ids - * @property {string[]} exportName - */ + serialize(context) { + context.write(this.range); + context.write(this.referencedExports); + super.serialize(context); + } -/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo } ModuleInfo */ -/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo | ReferenceToModuleInfo } ModuleInfoOrReference */ + deserialize(context) { + this.range = context.read(); + this.referencedExports = context.read(); + super.deserialize(context); + } +} -/** - * @typedef {Object} ConcatenatedModuleInfo - * @property {"concatenated"} type - * @property {Module} module - * @property {number} index - * @property {Object} ast - * @property {Source} internalSource - * @property {ReplaceSource} source - * @property {InitFragment[]=} chunkInitFragments - * @property {Iterable} runtimeRequirements - * @property {Scope} globalScope - * @property {Scope} moduleScope - * @property {Map} internalNames - * @property {Map} exportMap - * @property {Map} rawExportMap - * @property {string=} namespaceExportSymbol - * @property {string} namespaceObjectName - * @property {boolean} interopNamespaceObjectUsed - * @property {string} interopNamespaceObjectName - * @property {boolean} interopNamespaceObject2Used - * @property {string} interopNamespaceObject2Name - * @property {boolean} interopDefaultAccessUsed - * @property {string} interopDefaultAccessName - */ +makeSerializable(ImportDependency, "webpack/lib/dependencies/ImportDependency"); -/** - * @typedef {Object} ExternalModuleInfo - * @property {"external"} type - * @property {Module} module - * @property {RuntimeSpec | boolean} runtimeCondition - * @property {number} index - * @property {string} name - * @property {boolean} interopNamespaceObjectUsed - * @property {string} interopNamespaceObjectName - * @property {boolean} interopNamespaceObject2Used - * @property {string} interopNamespaceObject2Name - * @property {boolean} interopDefaultAccessUsed - * @property {string} interopDefaultAccessName - */ +ImportDependency.Template = class ImportDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @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, + { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ImportDependency} */ (dependency); + const block = /** @type {AsyncDependenciesBlock} */ ( + moduleGraph.getParentBlock(dep) + ); + const content = runtimeTemplate.moduleNamespacePromise({ + chunkGraph, + block: block, + module: moduleGraph.getModule(dep), + request: dep.request, + strict: module.buildMeta.strictHarmonyModule, + message: "import()", + runtimeRequirements + }); -/** - * @typedef {Object} ReferenceToModuleInfo - * @property {"reference"} type - * @property {RuntimeSpec | boolean} runtimeCondition - * @property {ConcatenatedModuleInfo | ExternalModuleInfo} target - */ + source.replace(dep.range[0], dep.range[1] - 1, content); + } +}; -const RESERVED_NAMES = new Set( - [ - // internal names (should always be renamed) - ConcatenationScope.DEFAULT_EXPORT, - ConcatenationScope.NAMESPACE_OBJECT_EXPORT, +module.exports = ImportDependency; - // keywords - "abstract,arguments,async,await,boolean,break,byte,case,catch,char,class,const,continue", - "debugger,default,delete,do,double,else,enum,eval,export,extends,false,final,finally,float", - "for,function,goto,if,implements,import,in,instanceof,int,interface,let,long,native,new,null", - "package,private,protected,public,return,short,static,super,switch,synchronized,this,throw", - "throws,transient,true,try,typeof,var,void,volatile,while,with,yield", - // commonjs/amd - "module,__dirname,__filename,exports,require,define", +/***/ }), - // js globals - "Array,Date,eval,function,hasOwnProperty,Infinity,isFinite,isNaN,isPrototypeOf,length,Math", - "NaN,name,Number,Object,prototype,String,toString,undefined,valueOf", +/***/ 50718: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // browser globals - "alert,all,anchor,anchors,area,assign,blur,button,checkbox,clearInterval,clearTimeout", - "clientInformation,close,closed,confirm,constructor,crypto,decodeURI,decodeURIComponent", - "defaultStatus,document,element,elements,embed,embeds,encodeURI,encodeURIComponent,escape", - "event,fileUpload,focus,form,forms,frame,innerHeight,innerWidth,layer,layers,link,location", - "mimeTypes,navigate,navigator,frames,frameRate,hidden,history,image,images,offscreenBuffering", - "open,opener,option,outerHeight,outerWidth,packages,pageXOffset,pageYOffset,parent,parseFloat", - "parseInt,password,pkcs11,plugin,prompt,propertyIsEnum,radio,reset,screenX,screenY,scroll", - "secure,select,self,setInterval,setTimeout,status,submit,taint,text,textarea,top,unescape", - "untaint,window", +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // window events - "onblur,onclick,onerror,onfocus,onkeydown,onkeypress,onkeyup,onmouseover,onload,onmouseup,onmousedown,onsubmit" - ] - .join(",") - .split(",") -); -const bySourceOrder = (a, b) => { - const aOrder = a.sourceOrder; - const bOrder = b.sourceOrder; - if (isNaN(aOrder)) { - if (!isNaN(bOrder)) { - return 1; - } - } else { - if (isNaN(bOrder)) { - return -1; - } - if (aOrder !== bOrder) { - return aOrder < bOrder ? -1 : 1; - } - } - return 0; -}; -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; -}; +const makeSerializable = __webpack_require__(33032); +const ImportDependency = __webpack_require__(89376); -/** - * @typedef {Object} ConcatenationEntry - * @property {"concatenated" | "external"} type - * @property {Module} module - * @property {RuntimeSpec | boolean} runtimeCondition - */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** - * @param {ModuleGraph} moduleGraph the module graph - * @param {ModuleInfo} info module info - * @param {string[]} exportName exportName - * @param {Map} moduleToInfoMap moduleToInfoMap - * @param {RuntimeSpec} runtime for which runtime - * @param {RequestShortener} requestShortener the request shortener - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {Set} neededNamespaceObjects modules for which a namespace object should be generated - * @param {boolean} asCall asCall - * @param {boolean} strictHarmonyModule strictHarmonyModule - * @param {boolean | undefined} asiSafe asiSafe - * @param {Set} alreadyVisited alreadyVisited - * @returns {Binding} the final variable - */ -const getFinalBinding = ( - moduleGraph, - info, - exportName, - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - asCall, - strictHarmonyModule, - asiSafe, - alreadyVisited = new Set() -) => { - const exportsType = info.module.getExportsType( - moduleGraph, - strictHarmonyModule - ); - if (exportName.length === 0) { - switch (exportsType) { - case "default-only": - info.interopNamespaceObject2Used = true; - return { - info, - rawName: info.interopNamespaceObject2Name, - ids: exportName, - exportName - }; - case "default-with-named": - info.interopNamespaceObjectUsed = true; - return { - info, - rawName: info.interopNamespaceObjectName, - ids: exportName, - exportName - }; - case "namespace": - case "dynamic": - break; - default: - throw new Error(`Unexpected exportsType ${exportsType}`); - } - } else { - switch (exportsType) { - case "namespace": - break; - case "default-with-named": - switch (exportName[0]) { - case "default": - exportName = exportName.slice(1); - break; - case "__esModule": - return { - info, - rawName: "/* __esModule */true", - ids: exportName.slice(1), - exportName - }; - } - break; - case "default-only": { - const exportId = exportName[0]; - if (exportId === "__esModule") { - return { - info, - rawName: "/* __esModule */true", - ids: exportName.slice(1), - exportName - }; - } - exportName = exportName.slice(1); - if (exportId !== "default") { - return { - info, - rawName: - "/* non-default import from default-exporting module */undefined", - ids: exportName, - exportName - }; - } - break; - } - case "dynamic": - switch (exportName[0]) { - case "default": { - exportName = exportName.slice(1); - info.interopDefaultAccessUsed = true; - const defaultExport = asCall - ? `${info.interopDefaultAccessName}()` - : asiSafe - ? `(${info.interopDefaultAccessName}())` - : asiSafe === false - ? `;(${info.interopDefaultAccessName}())` - : `${info.interopDefaultAccessName}.a`; - return { - info, - rawName: defaultExport, - ids: exportName, - exportName - }; - } - case "__esModule": - return { - info, - rawName: "/* __esModule */true", - ids: exportName.slice(1), - exportName - }; - } - break; - default: - throw new Error(`Unexpected exportsType ${exportsType}`); - } - } - if (exportName.length === 0) { - switch (info.type) { - case "concatenated": - neededNamespaceObjects.add(info); - return { - info, - rawName: info.namespaceObjectName, - ids: exportName, - exportName - }; - case "external": - return { info, rawName: info.name, ids: exportName, exportName }; - } - } - const exportsInfo = moduleGraph.getExportsInfo(info.module); - const exportInfo = exportsInfo.getExportInfo(exportName[0]); - if (alreadyVisited.has(exportInfo)) { - return { - info, - rawName: "/* circular reexport */ Object(function x() { x() }())", - ids: [], - exportName - }; +class ImportEagerDependency extends ImportDependency { + /** + * @param {string} request the request + * @param {[number, number]} range expression range + * @param {string[][]=} referencedExports list of referenced exports + */ + constructor(request, range, referencedExports) { + super(request, range, referencedExports); } - alreadyVisited.add(exportInfo); - switch (info.type) { - case "concatenated": { - const exportId = exportName[0]; - if (exportInfo.provided === false) { - // It's not provided, but it could be on the prototype - neededNamespaceObjects.add(info); - return { - info, - rawName: info.namespaceObjectName, - ids: exportName, - exportName - }; - } - const directExport = info.exportMap && info.exportMap.get(exportId); - if (directExport) { - const usedName = /** @type {string[]} */ ( - exportsInfo.getUsedName(exportName, runtime) - ); - if (!usedName) { - return { - info, - rawName: "/* unused export */ undefined", - ids: exportName.slice(1), - exportName - }; - } - return { - info, - name: directExport, - ids: usedName.slice(1), - exportName - }; - } - const rawExport = info.rawExportMap && info.rawExportMap.get(exportId); - if (rawExport) { - return { - info, - rawName: rawExport, - ids: exportName.slice(1), - exportName - }; - } - const reexport = exportInfo.findTarget(moduleGraph, module => - moduleToInfoMap.has(module) - ); - if (reexport === false) { - throw new Error( - `Target module of reexport from '${info.module.readableIdentifier( - requestShortener - )}' is not part of the concatenation (export '${exportId}')\nModules in the concatenation:\n${Array.from( - moduleToInfoMap, - ([m, info]) => - ` * ${info.type} ${m.readableIdentifier(requestShortener)}` - ).join("\n")}` - ); - } - if (reexport) { - const refInfo = moduleToInfoMap.get(reexport.module); - return getFinalBinding( - moduleGraph, - refInfo, - reexport.export - ? [...reexport.export, ...exportName.slice(1)] - : exportName.slice(1), - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - asCall, - info.module.buildMeta.strictHarmonyModule, - asiSafe, - alreadyVisited - ); - } - if (info.namespaceExportSymbol) { - const usedName = /** @type {string[]} */ ( - exportsInfo.getUsedName(exportName, runtime) - ); - return { - info, - rawName: info.namespaceObjectName, - ids: usedName, - exportName - }; - } - throw new Error( - `Cannot get final name for export '${exportName.join( - "." - )}' of ${info.module.readableIdentifier(requestShortener)}` - ); - } - case "external": { - const used = /** @type {string[]} */ ( - exportsInfo.getUsedName(exportName, runtime) - ); - if (!used) { - return { - info, - rawName: "/* unused export */ undefined", - ids: exportName.slice(1), - exportName - }; - } - const comment = equals(used, exportName) - ? "" - : Template.toNormalComment(`${exportName.join(".")}`); - return { info, rawName: info.name + comment, ids: used, exportName }; - } + get type() { + return "import() eager"; } -}; -/** - * @param {ModuleGraph} moduleGraph the module graph - * @param {ModuleInfo} info module info - * @param {string[]} exportName exportName - * @param {Map} moduleToInfoMap moduleToInfoMap - * @param {RuntimeSpec} runtime for which runtime - * @param {RequestShortener} requestShortener the request shortener - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {Set} neededNamespaceObjects modules for which a namespace object should be generated - * @param {boolean} asCall asCall - * @param {boolean} callContext callContext - * @param {boolean} strictHarmonyModule strictHarmonyModule - * @param {boolean | undefined} asiSafe asiSafe - * @returns {string} the final name - */ -const getFinalName = ( - moduleGraph, - info, - exportName, - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - asCall, - callContext, - strictHarmonyModule, - asiSafe -) => { - const binding = getFinalBinding( - moduleGraph, - info, - exportName, - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - asCall, - strictHarmonyModule, - asiSafe - ); - { - const { ids, comment } = binding; - let reference; - let isPropertyAccess; - if ("rawName" in binding) { - reference = `${binding.rawName}${comment || ""}${propertyAccess(ids)}`; - isPropertyAccess = ids.length > 0; - } else { - const { info, name: exportId } = binding; - const name = info.internalNames.get(exportId); - if (!name) { - throw new Error( - `The export "${exportId}" in "${info.module.readableIdentifier( - requestShortener - )}" has no internal name (existing names: ${ - Array.from( - info.internalNames, - ([name, symbol]) => `${name}: ${symbol}` - ).join(", ") || "none" - })` - ); - } - reference = `${name}${comment || ""}${propertyAccess(ids)}`; - isPropertyAccess = ids.length > 1; - } - if (isPropertyAccess && asCall && callContext === false) { - return asiSafe - ? `(0,${reference})` - : asiSafe === false - ? `;(0,${reference})` - : `/*#__PURE__*/Object(${reference})`; - } - return reference; + get category() { + return "esm"; } -}; +} -const addScopeSymbols = (s, nameSet, scopeSet1, scopeSet2) => { - let scope = s; - while (scope) { - if (scopeSet1.has(scope)) break; - if (scopeSet2.has(scope)) break; - scopeSet1.add(scope); - for (const variable of scope.variables) { - nameSet.add(variable.name); - } - scope = scope.upper; - } -}; +makeSerializable( + ImportEagerDependency, + "webpack/lib/dependencies/ImportEagerDependency" +); -const getAllReferences = variable => { - let set = variable.references; - // Look for inner scope variables too (like in class Foo { t() { Foo } }) - const identifiers = new Set(variable.identifiers); - for (const scope of variable.scope.childScopes) { - for (const innerVar of scope.variables) { - if (innerVar.identifiers.some(id => identifiers.has(id))) { - set = set.concat(innerVar.references); - break; - } - } +ImportEagerDependency.Template = class ImportEagerDependencyTemplate extends ( + ImportDependency.Template +) { + /** + * @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, + { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ImportEagerDependency} */ (dependency); + const content = runtimeTemplate.moduleNamespacePromise({ + chunkGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + strict: module.buildMeta.strictHarmonyModule, + message: "import() eager", + runtimeRequirements + }); + + source.replace(dep.range[0], dep.range[1] - 1, content); } - return set; }; -const getPathInAst = (ast, node) => { - if (ast === node) { - return []; - } +module.exports = ImportEagerDependency; - const nr = node.range; - const enterNode = n => { - if (!n) return undefined; - const r = n.range; - if (r) { - if (r[0] <= nr[0] && r[1] >= nr[1]) { - const path = getPathInAst(n, node); - if (path) { - path.push(n); - return path; - } - } - } - return undefined; - }; +/***/ }), - if (Array.isArray(ast)) { - for (let i = 0; i < ast.length; i++) { - const enterResult = enterNode(ast[i]); - if (enterResult !== undefined) return enterResult; - } - } else if (ast && typeof ast === "object") { - const keys = Object.keys(ast); - for (let i = 0; i < keys.length; i++) { - const value = ast[keys[i]]; - if (Array.isArray(value)) { - const pathResult = getPathInAst(value, node); - if (pathResult !== undefined) return pathResult; - } else if (value && typeof value === "object") { - const enterResult = enterNode(value); - if (enterResult !== undefined) return enterResult; - } - } - } -}; +/***/ 51274: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const TYPES = new Set(["javascript"]); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ -class ConcatenatedModule extends Module { - /** - * @param {Module} rootModule the root module of the concatenation - * @param {Set} modules all modules in the concatenation (including the root module) - * @param {RuntimeSpec} runtime the runtime - * @param {Object=} associatedObjectForCache object for caching - * @param {string | HashConstructor=} hashFunction hash function to use - * @returns {ConcatenatedModule} the module - */ - static create( - rootModule, - modules, - runtime, - associatedObjectForCache, - hashFunction = "md4" - ) { - const identifier = ConcatenatedModule._createIdentifier( - rootModule, - modules, - associatedObjectForCache, - hashFunction - ); - return new ConcatenatedModule({ - identifier, - rootModule, - modules, - runtime - }); - } - /** - * @param {Object} options options - * @param {string} options.identifier the identifier of the module - * @param {Module=} options.rootModule the root module of the concatenation - * @param {RuntimeSpec} options.runtime the selected runtime - * @param {Set=} options.modules all concatenated modules - */ - constructor({ identifier, rootModule, modules, runtime }) { - super("javascript/esm", null, rootModule && rootModule.layer); - // Info from Factory - /** @type {string} */ - this._identifier = identifier; - /** @type {Module} */ - this.rootModule = rootModule; - /** @type {Set} */ - this._modules = modules; - this._runtime = runtime; - this.factoryMeta = rootModule && rootModule.factoryMeta; - } +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyTemplateAsId = __webpack_require__(80825); - /** - * 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) { - throw new Error("Must not be called"); +class ImportMetaHotAcceptDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; } - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; + get type() { + return "import.meta.webpackHot.accept"; } - get modules() { - return Array.from(this._modules); + get category() { + return "esm"; } +} - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return this._identifier; - } +makeSerializable( + ImportMetaHotAcceptDependency, + "webpack/lib/dependencies/ImportMetaHotAcceptDependency" +); - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return ( - this.rootModule.readableIdentifier(requestShortener) + - ` + ${this._modules.size - 1} modules` - ); - } +ImportMetaHotAcceptDependency.Template = ModuleDependencyTemplateAsId; - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - return this.rootModule.libIdent(options); +module.exports = ImportMetaHotAcceptDependency; + + +/***/ }), + +/***/ 53141: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyTemplateAsId = __webpack_require__(80825); + +class ImportMetaHotDeclineDependency extends ModuleDependency { + constructor(request, range) { + super(request); + + this.range = range; + this.weak = true; } - /** - * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) - */ - nameForCondition() { - return this.rootModule.nameForCondition(); + get type() { + return "import.meta.webpackHot.decline"; } - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only - */ - getSideEffectsConnectionState(moduleGraph) { - return this.rootModule.getSideEffectsConnectionState(moduleGraph); + get category() { + return "esm"; } +} - /** - * @param {WebpackOptions} options webpack options - * @param {Compilation} compilation the compilation - * @param {ResolverWithOptions} resolver the resolver - * @param {InputFileSystem} fs the file system - * @param {function(WebpackError=): void} callback callback function - * @returns {void} - */ - build(options, compilation, resolver, fs, callback) { - const { rootModule } = this; - this.buildInfo = { - strict: true, - cacheable: true, - moduleArgument: rootModule.buildInfo.moduleArgument, - exportsArgument: rootModule.buildInfo.exportsArgument, - fileDependencies: new LazySet(), - contextDependencies: new LazySet(), - missingDependencies: new LazySet(), - topLevelDeclarations: new Set(), - assets: undefined - }; - this.buildMeta = rootModule.buildMeta; - this.clearDependenciesAndBlocks(); - this.clearWarningsAndErrors(); +makeSerializable( + ImportMetaHotDeclineDependency, + "webpack/lib/dependencies/ImportMetaHotDeclineDependency" +); - for (const m of this._modules) { - // populate cacheable - if (!m.buildInfo.cacheable) { - this.buildInfo.cacheable = false; - } +ImportMetaHotDeclineDependency.Template = ModuleDependencyTemplateAsId; - // populate dependencies - for (const d of m.dependencies.filter( - dep => - !(dep instanceof HarmonyImportDependency) || - !this._modules.has(compilation.moduleGraph.getModule(dep)) - )) { - this.dependencies.push(d); - } - // populate blocks - for (const d of m.blocks) { - this.blocks.push(d); - } +module.exports = ImportMetaHotDeclineDependency; - // populate warnings - const warnings = m.getWarnings(); - if (warnings !== undefined) { - for (const warning of warnings) { - this.addWarning(warning); - } - } - // populate errors - const errors = m.getErrors(); - if (errors !== undefined) { - for (const error of errors) { - this.addError(error); - } - } +/***/ }), - // populate topLevelDeclarations - if (m.buildInfo.topLevelDeclarations) { - const topLevelDeclarations = this.buildInfo.topLevelDeclarations; - if (topLevelDeclarations !== undefined) { - for (const decl of m.buildInfo.topLevelDeclarations) { - // reserved names will always be renamed - if (RESERVED_NAMES.has(decl)) continue; - // TODO actually this is incorrect since with renaming there could be more - // We should do the renaming during build - topLevelDeclarations.add(decl); - } - } - } else { - this.buildInfo.topLevelDeclarations = undefined; - } +/***/ 17228: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // populate assets - if (m.buildInfo.assets) { - if (this.buildInfo.assets === undefined) { - this.buildInfo.assets = Object.create(null); - } - Object.assign(this.buildInfo.assets, m.buildInfo.assets); - } - if (m.buildInfo.assetsInfo) { - if (this.buildInfo.assetsInfo === undefined) { - this.buildInfo.assetsInfo = new Map(); - } - for (const [key, value] of m.buildInfo.assetsInfo) { - this.buildInfo.assetsInfo.set(key, value); - } - } - } - callback(); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - /** - * @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) { - // Guess size from embedded modules - let size = 0; - for (const module of this._modules) { - size += module.size(type); - } - return size; - } + +const { pathToFileURL } = __webpack_require__(57310); +const ModuleDependencyWarning = __webpack_require__(29656); +const Template = __webpack_require__(39722); +const BasicEvaluatedExpression = __webpack_require__(950); +const { + evaluateToIdentifier, + toConstantDependency, + evaluateToString, + evaluateToNumber +} = __webpack_require__(93998); +const memoize = __webpack_require__(78676); +const propertyAccess = __webpack_require__(54190); +const ConstDependency = __webpack_require__(76911); + +/** @typedef {import("estree").MemberExpression} MemberExpression */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ + +const getCriticalDependencyWarning = memoize(() => + __webpack_require__(15427) +); + +class ImportMetaPlugin { /** - * @private - * @param {Module} rootModule the root of the concatenation - * @param {Set} modulesSet a set of modules which should be concatenated - * @param {RuntimeSpec} runtime for this runtime - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConcatenationEntry[]} concatenation list + * @param {Compiler} compiler compiler */ - _createConcatenationList(rootModule, modulesSet, runtime, moduleGraph) { - /** @type {ConcatenationEntry[]} */ - const list = []; - /** @type {Map} */ - const existingEntries = new Map(); - - /** - * @param {Module} module a module - * @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} imported modules in order - */ - const getConcatenatedImports = module => { - let connections = Array.from(moduleGraph.getOutgoingConnections(module)); - if (module === rootModule) { - for (const c of moduleGraph.getOutgoingConnections(this)) - connections.push(c); - } - const references = connections - .filter(connection => { - if (!(connection.dependency instanceof HarmonyImportDependency)) - return false; - return ( - connection && - connection.resolvedOriginModule === module && - connection.module && - connection.isTargetActive(runtime) + apply(compiler) { + compiler.hooks.compilation.tap( + "ImportMetaPlugin", + (compilation, { normalModuleFactory }) => { + /** + * @param {NormalModule} module module + * @returns {string} file url + */ + const getUrl = module => { + return pathToFileURL(module.resource).toString(); + }; + /** + * @param {Parser} parser parser + * @param {Object} parserOptions parserOptions + * @returns {void} + */ + const parserHandler = (parser, parserOptions) => { + /// import.meta direct /// + parser.hooks.typeof + .for("import.meta") + .tap( + "ImportMetaPlugin", + toConstantDependency(parser, JSON.stringify("object")) + ); + parser.hooks.expression + .for("import.meta") + .tap("ImportMetaPlugin", metaProperty => { + const CriticalDependencyWarning = getCriticalDependencyWarning(); + parser.state.module.addWarning( + new ModuleDependencyWarning( + parser.state.module, + new CriticalDependencyWarning( + "Accessing import.meta directly is unsupported (only property access is supported)" + ), + metaProperty.loc + ) + ); + const dep = new ConstDependency( + `${parser.isAsiPosition(metaProperty.range[0]) ? ";" : ""}({})`, + metaProperty.range + ); + dep.loc = metaProperty.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.evaluateTypeof + .for("import.meta") + .tap("ImportMetaPlugin", evaluateToString("object")); + parser.hooks.evaluateIdentifier.for("import.meta").tap( + "ImportMetaPlugin", + evaluateToIdentifier("import.meta", "import.meta", () => [], true) ); - }) - .map(connection => ({ - connection, - sourceOrder: /** @type {HarmonyImportDependency} */ ( - connection.dependency - ).sourceOrder - })); - references.sort( - concatComparators(bySourceOrder, keepOriginalOrder(references)) - ); - /** @type {Map} */ - const referencesMap = new Map(); - for (const { connection } of references) { - const runtimeCondition = filterRuntime(runtime, r => - connection.isTargetActive(r) - ); - if (runtimeCondition === false) continue; - const module = connection.module; - const entry = referencesMap.get(module); - if (entry === undefined) { - referencesMap.set(module, { connection, runtimeCondition }); - continue; - } - entry.runtimeCondition = mergeRuntimeConditionNonFalse( - entry.runtimeCondition, - runtimeCondition, - runtime - ); - } - return referencesMap.values(); - }; - /** - * @param {ModuleGraphConnection} connection graph connection - * @param {RuntimeSpec | true} runtimeCondition runtime condition - * @returns {void} - */ - const enterModule = (connection, runtimeCondition) => { - const module = connection.module; - if (!module) return; - const existingEntry = existingEntries.get(module); - if (existingEntry === true) { - return; - } - if (modulesSet.has(module)) { - existingEntries.set(module, true); - if (runtimeCondition !== true) { - throw new Error( - `Cannot runtime-conditional concatenate a module (${module.identifier()} in ${this.rootModule.identifier()}, ${runtimeConditionToString( - runtimeCondition - )}). This should not happen.` - ); - } - const imports = getConcatenatedImports(module); - for (const { connection, runtimeCondition } of imports) - enterModule(connection, runtimeCondition); - list.push({ - type: "concatenated", - module: connection.module, - runtimeCondition - }); - } else { - if (existingEntry !== undefined) { - const reducedRuntimeCondition = subtractRuntimeCondition( - runtimeCondition, - existingEntry, - runtime - ); - if (reducedRuntimeCondition === false) return; - runtimeCondition = reducedRuntimeCondition; - existingEntries.set( - connection.module, - mergeRuntimeConditionNonFalse( - existingEntry, - runtimeCondition, - runtime - ) - ); - } else { - existingEntries.set(connection.module, runtimeCondition); - } - if (list.length > 0) { - const lastItem = list[list.length - 1]; - if ( - lastItem.type === "external" && - lastItem.module === connection.module - ) { - lastItem.runtimeCondition = mergeRuntimeCondition( - lastItem.runtimeCondition, - runtimeCondition, - runtime + /// import.meta.url /// + parser.hooks.typeof + .for("import.meta.url") + .tap( + "ImportMetaPlugin", + toConstantDependency(parser, JSON.stringify("string")) ); - return; - } - } - list.push({ - type: "external", - get module() { - // We need to use a getter here, because the module in the dependency - // could be replaced by some other process (i. e. also replaced with a - // concatenated module) - return connection.module; - }, - runtimeCondition - }); - } - }; + parser.hooks.expression + .for("import.meta.url") + .tap("ImportMetaPlugin", expr => { + const dep = new ConstDependency( + JSON.stringify(getUrl(parser.state.module)), + expr.range + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.evaluateTypeof + .for("import.meta.url") + .tap("ImportMetaPlugin", evaluateToString("string")); + parser.hooks.evaluateIdentifier + .for("import.meta.url") + .tap("ImportMetaPlugin", expr => { + return new BasicEvaluatedExpression() + .setString(getUrl(parser.state.module)) + .setRange(expr.range); + }); - existingEntries.set(rootModule, true); - const imports = getConcatenatedImports(rootModule); - for (const { connection, runtimeCondition } of imports) - enterModule(connection, runtimeCondition); - list.push({ - type: "concatenated", - module: rootModule, - runtimeCondition: true - }); + /// import.meta.webpack /// + const webpackVersion = parseInt( + (__webpack_require__(32702)/* .version */ .i8), + 10 + ); + parser.hooks.typeof + .for("import.meta.webpack") + .tap( + "ImportMetaPlugin", + toConstantDependency(parser, JSON.stringify("number")) + ); + parser.hooks.expression + .for("import.meta.webpack") + .tap( + "ImportMetaPlugin", + toConstantDependency(parser, JSON.stringify(webpackVersion)) + ); + parser.hooks.evaluateTypeof + .for("import.meta.webpack") + .tap("ImportMetaPlugin", evaluateToString("number")); + parser.hooks.evaluateIdentifier + .for("import.meta.webpack") + .tap("ImportMetaPlugin", evaluateToNumber(webpackVersion)); - return list; - } + /// Unknown properties /// + parser.hooks.unhandledExpressionMemberChain + .for("import.meta") + .tap("ImportMetaPlugin", (expr, members) => { + const dep = new ConstDependency( + `${Template.toNormalComment( + "unsupported import.meta." + members.join(".") + )} undefined${propertyAccess(members, 1)}`, + expr.range + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.evaluate + .for("MemberExpression") + .tap("ImportMetaPlugin", expression => { + const expr = /** @type {MemberExpression} */ (expression); + if ( + expr.object.type === "MetaProperty" && + expr.object.meta.name === "import" && + expr.object.property.name === "meta" && + expr.property.type === + (expr.computed ? "Literal" : "Identifier") + ) { + return new BasicEvaluatedExpression() + .setUndefined() + .setRange(expr.range); + } + }); + }; - /** - * @param {Module} rootModule the root module of the concatenation - * @param {Set} modules all modules in the concatenation (including the root module) - * @param {Object=} associatedObjectForCache object for caching - * @param {string | HashConstructor=} hashFunction hash function to use - * @returns {string} the identifier - */ - static _createIdentifier( - rootModule, - modules, - associatedObjectForCache, - hashFunction = "md4" - ) { - const cachedMakePathsRelative = makePathsRelative.bindContextCache( - rootModule.context, - associatedObjectForCache + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ImportMetaPlugin", parserHandler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ImportMetaPlugin", parserHandler); + } ); - let identifiers = []; - for (const module of modules) { - identifiers.push(cachedMakePathsRelative(module.identifier())); - } - identifiers.sort(); - const hash = createHash(hashFunction); - hash.update(identifiers.join(" ")); - return rootModule.identifier() + "|" + hash.digest("hex"); } +} - /** - * @param {LazySet} fileDependencies set where file dependencies are added to - * @param {LazySet} contextDependencies set where context dependencies are added to - * @param {LazySet} missingDependencies set where missing dependencies are added to - * @param {LazySet} buildDependencies set where build dependencies are added to - */ - addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ) { - for (const module of this._modules) { - module.addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ); - } - } +module.exports = ImportMetaPlugin; - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration({ - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime: generationRuntime, - codeGenerationResults - }) { - /** @type {Set} */ - const runtimeRequirements = new Set(); - const runtime = intersectRuntime(generationRuntime, this._runtime); - const requestShortener = runtimeTemplate.requestShortener; - // Meta info for each module - const [modulesWithInfo, moduleToInfoMap] = this._getModulesWithInfo( - moduleGraph, - runtime - ); +/***/ }), - // Set with modules that need a generated namespace object - /** @type {Set} */ - const neededNamespaceObjects = new Set(); +/***/ 88130: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Generate source code and analyse scopes - // Prepare a ReplaceSource for the final source - for (const info of moduleToInfoMap.values()) { - this._analyseModule( - moduleToInfoMap, - info, - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime, - codeGenerationResults - ); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // List of all used names to avoid conflicts - const allUsedNames = new Set(RESERVED_NAMES); - // List of additional names in scope for module references - /** @type {Map, alreadyCheckedScopes: Set }>} */ - const usedNamesInScopeInfo = new Map(); - /** - * @param {string} module module identifier - * @param {string} id export id - * @returns {{ usedNames: Set, alreadyCheckedScopes: Set }} info - */ - const getUsedNamesInScopeInfo = (module, id) => { - const key = `${module}-${id}`; - let info = usedNamesInScopeInfo.get(key); - if (info === undefined) { - info = { - usedNames: new Set(), - alreadyCheckedScopes: new Set() - }; - usedNamesInScopeInfo.set(key, info); - } - return info; - }; - // Set of already checked scopes - const ignoredScopes = new Set(); +const AsyncDependenciesBlock = __webpack_require__(47736); +const CommentCompilationWarning = __webpack_require__(98427); +const UnsupportedFeatureWarning = __webpack_require__(42495); +const ContextDependencyHelpers = __webpack_require__(99630); +const ImportContextDependency = __webpack_require__(1902); +const ImportDependency = __webpack_require__(89376); +const ImportEagerDependency = __webpack_require__(50718); +const ImportWeakDependency = __webpack_require__(82483); - // get all global names - for (const info of modulesWithInfo) { - if (info.type === "concatenated") { - // ignore symbols from moduleScope - if (info.moduleScope) { - ignoredScopes.add(info.moduleScope); - } +/** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ +/** @typedef {import("../ContextModule").ContextMode} ContextMode */ - // The super class expression in class scopes behaves weird - // We get ranges of all super class expressions to make - // renaming to work correctly - const superClassCache = new WeakMap(); - const getSuperClassExpressions = scope => { - const cacheEntry = superClassCache.get(scope); - if (cacheEntry !== undefined) return cacheEntry; - const superClassExpressions = []; - for (const childScope of scope.childScopes) { - if (childScope.type !== "class") continue; - const block = childScope.block; - if ( - (block.type === "ClassDeclaration" || - block.type === "ClassExpression") && - block.superClass - ) { - superClassExpressions.push({ - range: block.superClass.range, - variables: childScope.variables - }); - } - } - superClassCache.set(scope, superClassExpressions); - return superClassExpressions; - }; +class ImportParserPlugin { + constructor(options) { + this.options = options; + } - // add global symbols - if (info.globalScope) { - for (const reference of info.globalScope.through) { - const name = reference.identifier.name; - if (ConcatenationScope.isModuleReference(name)) { - const match = ConcatenationScope.matchModuleReference(name); - if (!match) continue; - const referencedInfo = modulesWithInfo[match.index]; - if (referencedInfo.type === "reference") - throw new Error("Module reference can't point to a reference"); - const binding = getFinalBinding( - moduleGraph, - referencedInfo, - match.ids, - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - false, - info.module.buildMeta.strictHarmonyModule, - true - ); - if (!binding.ids) continue; - const { usedNames, alreadyCheckedScopes } = - getUsedNamesInScopeInfo( - binding.info.module.identifier(), - "name" in binding ? binding.name : "" - ); - for (const expr of getSuperClassExpressions(reference.from)) { - if ( - expr.range[0] <= reference.identifier.range[0] && - expr.range[1] >= reference.identifier.range[1] - ) { - for (const variable of expr.variables) { - usedNames.add(variable.name); - } - } - } - addScopeSymbols( - reference.from, - usedNames, - alreadyCheckedScopes, - ignoredScopes - ); - } else { - allUsedNames.add(name); - } - } + apply(parser) { + parser.hooks.importCall.tap("ImportParserPlugin", expr => { + const param = parser.evaluateExpression(expr.source); + + let chunkName = null; + /** @type {ContextMode} */ + let mode = "lazy"; + let include = null; + let exclude = null; + /** @type {string[][] | null} */ + let exports = null; + /** @type {RawChunkGroupOptions} */ + const groupOptions = {}; + + const { options: importOptions, errors: commentErrors } = + parser.parseCommentOptions(expr.range); + + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + comment.loc + ) + ); } } - } - // generate names for symbols - for (const info of moduleToInfoMap.values()) { - const { usedNames: namespaceObjectUsedNames } = getUsedNamesInScopeInfo( - info.module.identifier(), - "" - ); - switch (info.type) { - case "concatenated": { - for (const variable of info.moduleScope.variables) { - const name = variable.name; - const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo( - info.module.identifier(), - name + if (importOptions) { + if (importOptions.webpackIgnore !== undefined) { + if (typeof importOptions.webpackIgnore !== "boolean") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, + expr.loc + ) ); - if (allUsedNames.has(name) || usedNames.has(name)) { - const references = getAllReferences(variable); - for (const ref of references) { - addScopeSymbols( - ref.from, - usedNames, - alreadyCheckedScopes, - ignoredScopes - ); - } - const newName = this.findNewName( - name, - allUsedNames, - usedNames, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(newName); - info.internalNames.set(name, newName); - const source = info.source; - const allIdentifiers = new Set( - references.map(r => r.identifier).concat(variable.identifiers) - ); - for (const identifier of allIdentifiers) { - const r = identifier.range; - const path = getPathInAst(info.ast, identifier); - if (path && path.length > 1) { - const maybeProperty = - path[1].type === "AssignmentPattern" && - path[1].left === path[0] - ? path[2] - : path[1]; - if ( - maybeProperty.type === "Property" && - maybeProperty.shorthand - ) { - source.insert(r[1], `: ${newName}`); - continue; - } - } - source.replace(r[0], r[1] - 1, newName); - } - } else { - allUsedNames.add(name); - info.internalNames.set(name, name); + } else { + // Do not instrument `import()` if `webpackIgnore` is `true` + if (importOptions.webpackIgnore) { + return false; } } - let namespaceObjectName; - if (info.namespaceExportSymbol) { - namespaceObjectName = info.internalNames.get( - info.namespaceExportSymbol + } + if (importOptions.webpackChunkName !== undefined) { + if (typeof importOptions.webpackChunkName !== "string") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, + expr.loc + ) ); } else { - namespaceObjectName = this.findNewName( - "namespaceObject", - allUsedNames, - namespaceObjectUsedNames, - info.module.readableIdentifier(requestShortener) + chunkName = importOptions.webpackChunkName; + } + } + if (importOptions.webpackMode !== undefined) { + if (typeof importOptions.webpackMode !== "string") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackMode\` expected a string, but received: ${importOptions.webpackMode}.`, + expr.loc + ) ); - allUsedNames.add(namespaceObjectName); + } else { + mode = importOptions.webpackMode; } - info.namespaceObjectName = namespaceObjectName; - break; } - case "external": { - const externalName = this.findNewName( - "", - allUsedNames, - namespaceObjectUsedNames, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(externalName); - info.name = externalName; - break; + if (importOptions.webpackPrefetch !== undefined) { + if (importOptions.webpackPrefetch === true) { + groupOptions.prefetchOrder = 0; + } else if (typeof importOptions.webpackPrefetch === "number") { + groupOptions.prefetchOrder = importOptions.webpackPrefetch; + } else { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackPrefetch\` expected true or a number, but received: ${importOptions.webpackPrefetch}.`, + expr.loc + ) + ); + } } - } - if (info.module.buildMeta.exportsType !== "namespace") { - const externalNameInterop = this.findNewName( - "namespaceObject", - allUsedNames, - namespaceObjectUsedNames, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(externalNameInterop); - info.interopNamespaceObjectName = externalNameInterop; - } - if ( - info.module.buildMeta.exportsType === "default" && - info.module.buildMeta.defaultObject !== "redirect" - ) { - const externalNameInterop = this.findNewName( - "namespaceObject2", - allUsedNames, - namespaceObjectUsedNames, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(externalNameInterop); - info.interopNamespaceObject2Name = externalNameInterop; - } - if ( - info.module.buildMeta.exportsType === "dynamic" || - !info.module.buildMeta.exportsType - ) { - const externalNameInterop = this.findNewName( - "default", - allUsedNames, - namespaceObjectUsedNames, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(externalNameInterop); - info.interopDefaultAccessName = externalNameInterop; - } - } - - // Find and replace references to modules - for (const info of moduleToInfoMap.values()) { - if (info.type === "concatenated") { - for (const reference of info.globalScope.through) { - const name = reference.identifier.name; - const match = ConcatenationScope.matchModuleReference(name); - if (match) { - const referencedInfo = modulesWithInfo[match.index]; - if (referencedInfo.type === "reference") - throw new Error("Module reference can't point to a reference"); - const finalName = getFinalName( - moduleGraph, - referencedInfo, - match.ids, - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - match.call, - !match.directImport, - info.module.buildMeta.strictHarmonyModule, - match.asiSafe + if (importOptions.webpackPreload !== undefined) { + if (importOptions.webpackPreload === true) { + groupOptions.preloadOrder = 0; + } else if (typeof importOptions.webpackPreload === "number") { + groupOptions.preloadOrder = importOptions.webpackPreload; + } else { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackPreload\` expected true or a number, but received: ${importOptions.webpackPreload}.`, + expr.loc + ) ); - const r = reference.identifier.range; - const source = info.source; - // range is extended by 2 chars to cover the appended "._" - source.replace(r[0], r[1] + 1, finalName); + } + } + if (importOptions.webpackInclude !== undefined) { + if ( + !importOptions.webpackInclude || + importOptions.webpackInclude.constructor.name !== "RegExp" + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackInclude\` expected a regular expression, but received: ${importOptions.webpackInclude}.`, + expr.loc + ) + ); + } else { + include = new RegExp(importOptions.webpackInclude); + } + } + if (importOptions.webpackExclude !== undefined) { + if ( + !importOptions.webpackExclude || + importOptions.webpackExclude.constructor.name !== "RegExp" + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackExclude\` expected a regular expression, but received: ${importOptions.webpackExclude}.`, + expr.loc + ) + ); + } else { + exclude = new RegExp(importOptions.webpackExclude); + } + } + if (importOptions.webpackExports !== undefined) { + if ( + !( + typeof importOptions.webpackExports === "string" || + (Array.isArray(importOptions.webpackExports) && + importOptions.webpackExports.every( + item => typeof item === "string" + )) + ) + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackExports\` expected a string or an array of strings, but received: ${importOptions.webpackExports}.`, + expr.loc + ) + ); + } else { + if (typeof importOptions.webpackExports === "string") { + exports = [[importOptions.webpackExports]]; + } else { + exports = Array.from(importOptions.webpackExports, e => [e]); + } } } } - } - // Map with all root exposed used exports - /** @type {Map} */ - const exportsMap = new Map(); - - // Set with all root exposed unused exports - /** @type {Set} */ - const unusedExports = new Set(); - - const rootInfo = /** @type {ConcatenatedModuleInfo} */ ( - moduleToInfoMap.get(this.rootModule) - ); - const strictHarmonyModule = rootInfo.module.buildMeta.strictHarmonyModule; - const exportsInfo = moduleGraph.getExportsInfo(rootInfo.module); - for (const exportInfo of exportsInfo.orderedExports) { - const name = exportInfo.name; - if (exportInfo.provided === false) continue; - const used = exportInfo.getUsedName(undefined, runtime); - if (!used) { - unusedExports.add(name); - continue; - } - exportsMap.set(used, requestShortener => { - try { - const finalName = getFinalName( - moduleGraph, - rootInfo, - [name], - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - false, - false, - strictHarmonyModule, - true + if (param.isString()) { + if (mode !== "lazy" && mode !== "eager" && mode !== "weak") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackMode\` expected 'lazy', 'eager' or 'weak', but received: ${mode}.`, + expr.loc + ) ); - return `/* ${ - exportInfo.isReexport() ? "reexport" : "binding" - } */ ${finalName}`; - } catch (e) { - e.message += `\nwhile generating the root export '${name}' (used name: '${used}')`; - throw e; } - }); - } - - const result = new ConcatSource(); - // add harmony compatibility flag (must be first because of possible circular dependencies) - if ( - moduleGraph.getExportsInfo(this).otherExportsInfo.getUsed(runtime) !== - UsageState.Unused - ) { - result.add(`// ESM COMPAT FLAG\n`); - result.add( - runtimeTemplate.defineEsModuleFlagStatement({ - exportsArgument: this.exportsArgument, - runtimeRequirements - }) - ); - } + if (mode === "eager") { + const dep = new ImportEagerDependency( + param.string, + expr.range, + exports + ); + parser.state.current.addDependency(dep); + } else if (mode === "weak") { + const dep = new ImportWeakDependency( + param.string, + expr.range, + exports + ); + parser.state.current.addDependency(dep); + } else { + const depBlock = new AsyncDependenciesBlock( + { + ...groupOptions, + name: chunkName + }, + expr.loc, + param.string + ); + const dep = new ImportDependency(param.string, expr.range, exports); + dep.loc = expr.loc; + depBlock.addDependency(dep); + parser.state.current.addBlock(depBlock); + } + return true; + } else { + if ( + mode !== "lazy" && + mode !== "lazy-once" && + mode !== "eager" && + mode !== "weak" + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`, + expr.loc + ) + ); + mode = "lazy"; + } - // define exports - if (exportsMap.size > 0) { - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - const definitions = []; - for (const [key, value] of exportsMap) { - definitions.push( - `\n ${JSON.stringify(key)}: ${runtimeTemplate.returningFunction( - value(requestShortener) - )}` + if (mode === "weak") { + mode = "async-weak"; + } + const dep = ContextDependencyHelpers.create( + ImportContextDependency, + expr.range, + param, + expr, + this.options, + { + chunkName, + groupOptions, + include, + exclude, + mode, + namespaceObject: parser.state.module.buildMeta.strictHarmonyModule + ? "strict" + : true, + typePrefix: "import()", + category: "esm", + referencedExports: exports + }, + parser ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; } - result.add(`\n// EXPORTS\n`); - result.add( - `${RuntimeGlobals.definePropertyGetters}(${ - this.exportsArgument - }, {${definitions.join(",")}\n});\n` - ); - } + }); + } +} - // list unused exports - if (unusedExports.size > 0) { - result.add( - `\n// UNUSED EXPORTS: ${joinIterableWithComma(unusedExports)}\n` - ); - } +module.exports = ImportParserPlugin; - // generate namespace objects - const namespaceObjectSources = new Map(); - for (const info of neededNamespaceObjects) { - if (info.namespaceExportSymbol) continue; - const nsObj = []; - const exportsInfo = moduleGraph.getExportsInfo(info.module); - for (const exportInfo of exportsInfo.orderedExports) { - if (exportInfo.provided === false) continue; - const usedName = exportInfo.getUsedName(undefined, runtime); - if (usedName) { - const finalName = getFinalName( - moduleGraph, - info, - [exportInfo.name], - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - false, - undefined, - info.module.buildMeta.strictHarmonyModule, - true - ); - nsObj.push( - `\n ${JSON.stringify( - usedName - )}: ${runtimeTemplate.returningFunction(finalName)}` - ); - } - } - const name = info.namespaceObjectName; - const defineGetters = - nsObj.length > 0 - ? `${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join( - "," - )}\n});\n` - : ""; - if (nsObj.length > 0) - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - namespaceObjectSources.set( - info, - ` -// NAMESPACE OBJECT: ${info.module.readableIdentifier(requestShortener)} -var ${name} = {}; -${RuntimeGlobals.makeNamespaceObject}(${name}); -${defineGetters}` - ); - runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); - } - // define required namespace objects (must be before evaluation modules) - for (const info of modulesWithInfo) { - if (info.type === "concatenated") { - const source = namespaceObjectSources.get(info); - if (!source) continue; - result.add(source); - } - } +/***/ }), - const chunkInitFragments = []; +/***/ 41293: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // evaluate modules in order - for (const rawInfo of modulesWithInfo) { - let name; - let isConditional = false; - const info = rawInfo.type === "reference" ? rawInfo.target : rawInfo; - switch (info.type) { - case "concatenated": { - result.add( - `\n;// CONCATENATED MODULE: ${info.module.readableIdentifier( - requestShortener - )}\n` - ); - result.add(info.source); - if (info.chunkInitFragments) { - for (const f of info.chunkInitFragments) chunkInitFragments.push(f); - } - if (info.runtimeRequirements) { - for (const r of info.runtimeRequirements) { - runtimeRequirements.add(r); - } - } - name = info.namespaceObjectName; - break; - } - case "external": { - result.add( - `\n// EXTERNAL MODULE: ${info.module.readableIdentifier( - requestShortener - )}\n` - ); - runtimeRequirements.add(RuntimeGlobals.require); - const { runtimeCondition } = - /** @type {ExternalModuleInfo | ReferenceToModuleInfo} */ (rawInfo); - const condition = runtimeTemplate.runtimeConditionExpression({ - chunkGraph, - runtimeCondition, - runtime, - runtimeRequirements - }); - if (condition !== "true") { - isConditional = true; - result.add(`if (${condition}) {\n`); - } - result.add( - `var ${info.name} = __webpack_require__(${JSON.stringify( - chunkGraph.getModuleId(info.module) - )});` - ); - name = info.name; - break; - } - default: - // @ts-expect-error never is expected here - throw new Error(`Unsupported concatenation entry type ${info.type}`); - } - if (info.interopNamespaceObjectUsed) { - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - result.add( - `\nvar ${info.interopNamespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name}, 2);` +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const ImportContextDependency = __webpack_require__(1902); +const ImportDependency = __webpack_require__(89376); +const ImportEagerDependency = __webpack_require__(50718); +const ImportParserPlugin = __webpack_require__(88130); +const ImportWeakDependency = __webpack_require__(82483); + +/** @typedef {import("../Compiler")} Compiler */ + +class ImportPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "ImportPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + ImportDependency, + normalModuleFactory ); - } - if (info.interopNamespaceObject2Used) { - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - result.add( - `\nvar ${info.interopNamespaceObject2Name} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name});` + compilation.dependencyTemplates.set( + ImportDependency, + new ImportDependency.Template() ); - } - if (info.interopDefaultAccessUsed) { - runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport); - result.add( - `\nvar ${info.interopDefaultAccessName} = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${name});` + + compilation.dependencyFactories.set( + ImportEagerDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportEagerDependency, + new ImportEagerDependency.Template() ); - } - if (isConditional) { - result.add("\n}"); - } - } - const data = new Map(); - if (chunkInitFragments.length > 0) - data.set("chunkInitFragments", chunkInitFragments); + compilation.dependencyFactories.set( + ImportWeakDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportWeakDependency, + new ImportWeakDependency.Template() + ); - /** @type {CodeGenerationResult} */ - const resultEntry = { - sources: new Map([["javascript", new CachedSource(result)]]), - data, - runtimeRequirements - }; + compilation.dependencyFactories.set( + ImportContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + ImportContextDependency, + new ImportContextDependency.Template() + ); - return resultEntry; + const handler = (parser, parserOptions) => { + if (parserOptions.import !== undefined && !parserOptions.import) + return; + + new ImportParserPlugin(parserOptions).apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ImportPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ImportPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ImportPlugin", handler); + } + ); } +} +module.exports = ImportPlugin; + + +/***/ }), + +/***/ 82483: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const makeSerializable = __webpack_require__(33032); +const ImportDependency = __webpack_require__(89376); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ + +class ImportWeakDependency extends ImportDependency { /** - * @param {Map} modulesMap modulesMap - * @param {ModuleInfo} info info - * @param {DependencyTemplates} dependencyTemplates dependencyTemplates - * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate - * @param {ModuleGraph} moduleGraph moduleGraph - * @param {ChunkGraph} chunkGraph chunkGraph - * @param {RuntimeSpec} runtime runtime - * @param {CodeGenerationResults} codeGenerationResults codeGenerationResults + * @param {string} request the request + * @param {[number, number]} range expression range + * @param {string[][]=} referencedExports list of referenced exports */ - _analyseModule( - modulesMap, - info, - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime, - codeGenerationResults - ) { - if (info.type === "concatenated") { - const m = info.module; - try { - // Create a concatenation scope to track and capture information - const concatenationScope = new ConcatenationScope(modulesMap, info); + constructor(request, range, referencedExports) { + super(request, range, referencedExports); + this.weak = true; + } - // TODO cache codeGeneration results - const codeGenResult = m.codeGeneration({ - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime, - concatenationScope, - codeGenerationResults - }); - const source = codeGenResult.sources.get("javascript"); - const data = codeGenResult.data; - const chunkInitFragments = data && data.get("chunkInitFragments"); - const code = source.source().toString(); - let ast; - try { - ast = JavascriptParser._parse(code, { - sourceType: "module" - }); - } catch (err) { - if ( - err.loc && - typeof err.loc === "object" && - typeof err.loc.line === "number" - ) { - const lineNumber = err.loc.line; - const lines = code.split("\n"); - err.message += - "\n| " + - lines - .slice(Math.max(0, lineNumber - 3), lineNumber + 2) - .join("\n| "); - } - throw err; - } - const scopeManager = eslintScope.analyze(ast, { - ecmaVersion: 6, - sourceType: "module", - optimistic: true, - ignoreEval: true, - impliedStrict: true - }); - const globalScope = scopeManager.acquire(ast); - const moduleScope = globalScope.childScopes[0]; - const resultSource = new ReplaceSource(source); - info.runtimeRequirements = codeGenResult.runtimeRequirements; - info.ast = ast; - info.internalSource = source; - info.source = resultSource; - info.chunkInitFragments = chunkInitFragments; - info.globalScope = globalScope; - info.moduleScope = moduleScope; - } catch (err) { - err.message += `\nwhile analyzing module ${m.identifier()} for concatenation`; - throw err; - } - } + get type() { + return "import() weak"; } +} + +makeSerializable( + ImportWeakDependency, + "webpack/lib/dependencies/ImportWeakDependency" +); +ImportWeakDependency.Template = class ImportDependencyTemplate extends ( + ImportDependency.Template +) { /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {RuntimeSpec} runtime the runtime - * @returns {[ModuleInfoOrReference[], Map]} module info items + * @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} */ - _getModulesWithInfo(moduleGraph, runtime) { - const orderedConcatenationList = this._createConcatenationList( - this.rootModule, - this._modules, - runtime, - moduleGraph - ); - /** @type {Map} */ - const map = new Map(); - const list = orderedConcatenationList.map((info, index) => { - let item = map.get(info.module); - if (item === undefined) { - switch (info.type) { - case "concatenated": - item = { - type: "concatenated", - module: info.module, - index, - ast: undefined, - internalSource: undefined, - runtimeRequirements: undefined, - source: undefined, - globalScope: undefined, - moduleScope: undefined, - internalNames: new Map(), - exportMap: undefined, - rawExportMap: undefined, - namespaceExportSymbol: undefined, - namespaceObjectName: undefined, - interopNamespaceObjectUsed: false, - interopNamespaceObjectName: undefined, - interopNamespaceObject2Used: false, - interopNamespaceObject2Name: undefined, - interopDefaultAccessUsed: false, - interopDefaultAccessName: undefined - }; - break; - case "external": - item = { - type: "external", - module: info.module, - runtimeCondition: info.runtimeCondition, - index, - name: undefined, - interopNamespaceObjectUsed: false, - interopNamespaceObjectName: undefined, - interopNamespaceObject2Used: false, - interopNamespaceObject2Name: undefined, - interopDefaultAccessUsed: false, - interopDefaultAccessName: undefined - }; - break; - default: - throw new Error( - `Unsupported concatenation entry type ${info.type}` - ); - } - map.set(item.module, item); - return item; - } else { - /** @type {ReferenceToModuleInfo} */ - const ref = { - type: "reference", - runtimeCondition: info.runtimeCondition, - target: item - }; - return ref; - } + apply( + dependency, + source, + { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ImportWeakDependency} */ (dependency); + const content = runtimeTemplate.moduleNamespacePromise({ + chunkGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + strict: module.buildMeta.strictHarmonyModule, + message: "import() weak", + weak: true, + runtimeRequirements }); - return [list, map]; + + source.replace(dep.range[0], dep.range[1] - 1, content); } +}; - findNewName(oldName, usedNamed1, usedNamed2, extraInfo) { - let name = oldName; +module.exports = ImportWeakDependency; - if (name === ConcatenationScope.DEFAULT_EXPORT) { - name = ""; - } - if (name === ConcatenationScope.NAMESPACE_OBJECT_EXPORT) { - name = "namespaceObject"; - } - // Remove uncool stuff - extraInfo = extraInfo.replace( - /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, - "" - ); +/***/ }), - const splittedInfo = extraInfo.split("/"); - while (splittedInfo.length) { - name = splittedInfo.pop() + (name ? "_" + name : ""); - const nameIdent = Template.toIdentifier(name); - if ( - !usedNamed1.has(nameIdent) && - (!usedNamed2 || !usedNamed2.has(nameIdent)) - ) - return nameIdent; - } +/***/ 750: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - let i = 0; - let nameWithNumber = Template.toIdentifier(`${name}_${i}`); - while ( - usedNamed1.has(nameWithNumber) || - (usedNamed2 && usedNamed2.has(nameWithNumber)) - ) { - i++; - nameWithNumber = Template.toIdentifier(`${name}_${i}`); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ExportSpec} ExportSpec */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/Hash")} Hash */ + +const getExportsFromData = data => { + if (data && typeof data === "object") { + if (Array.isArray(data)) { + return data.map((item, idx) => { + return { + name: `${idx}`, + canMangle: true, + exports: getExportsFromData(item) + }; + }); + } else { + const exports = []; + for (const key of Object.keys(data)) { + exports.push({ + name: key, + canMangle: true, + exports: getExportsFromData(data[key]) + }); + } + return exports; } - return nameWithNumber; } + return undefined; +}; +class JsonExportsDependency extends NullDependency { /** - * @param {Hash} hash the hash used to track dependencies + * @param {(string | ExportSpec)[]} exports json exports + */ + constructor(exports) { + super(); + this.exports = exports; + this._hashUpdate = undefined; + } + + get type() { + return "json exports"; + } + + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + return { + exports: this.exports, + dependencies: undefined + }; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated * @param {UpdateHashContext} context context * @returns {void} */ updateHash(hash, context) { - const { chunkGraph, runtime } = context; - for (const info of this._createConcatenationList( - this.rootModule, - this._modules, - intersectRuntime(runtime, this._runtime), - chunkGraph.moduleGraph - )) { - switch (info.type) { - case "concatenated": - info.module.updateHash(hash, context); - break; - case "external": - hash.update(`${chunkGraph.getModuleId(info.module)}`); - // TODO runtimeCondition - break; - } + if (this._hashUpdate === undefined) { + this._hashUpdate = this.exports + ? JSON.stringify(this.exports) + : "undefined"; } - super.updateHash(hash, context); + hash.update(this._hashUpdate); } - static deserialize(context) { - const obj = new ConcatenatedModule({ - identifier: undefined, - rootModule: undefined, - modules: undefined, - runtime: undefined - }); - obj.deserialize(context); - return obj; + serialize(context) { + const { write } = context; + write(this.exports); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.exports = read(); + super.deserialize(context); } } -makeSerializable(ConcatenatedModule, "webpack/lib/optimize/ConcatenatedModule"); +makeSerializable( + JsonExportsDependency, + "webpack/lib/dependencies/JsonExportsDependency" +); -module.exports = ConcatenatedModule; +module.exports = JsonExportsDependency; +module.exports.getExportsFromData = getExportsFromData; /***/ }), -/***/ 96260: +/***/ 71693: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -101708,90 +93738,68 @@ module.exports = ConcatenatedModule; -const { STAGE_BASIC } = __webpack_require__(80057); +const ModuleDependency = __webpack_require__(80321); -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compiler")} Compiler */ +class LoaderDependency extends ModuleDependency { + /** + * @param {string} request request string + */ + constructor(request) { + super(request); + } -class EnsureChunkConditionsPlugin { + get type() { + return "loader"; + } + + get category() { + return "loader"; + } +} + +module.exports = LoaderDependency; + + +/***/ }), + +/***/ 223: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const ModuleDependency = __webpack_require__(80321); + +class LoaderImportDependency extends ModuleDependency { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {string} request request string */ - apply(compiler) { - compiler.hooks.compilation.tap( - "EnsureChunkConditionsPlugin", - compilation => { - const handler = chunks => { - const chunkGraph = compilation.chunkGraph; - // These sets are hoisted here to save memory - // They are cleared at the end of every loop - /** @type {Set} */ - const sourceChunks = new Set(); - /** @type {Set} */ - const chunkGroups = new Set(); - for (const module of compilation.modules) { - if (!module.hasChunkCondition()) continue; - for (const chunk of chunkGraph.getModuleChunksIterable(module)) { - if (!module.chunkCondition(chunk, compilation)) { - sourceChunks.add(chunk); - for (const group of chunk.groupsIterable) { - chunkGroups.add(group); - } - } - } - if (sourceChunks.size === 0) continue; - /** @type {Set} */ - const targetChunks = new Set(); - chunkGroupLoop: for (const chunkGroup of chunkGroups) { - // Can module be placed in a chunk of this group? - for (const chunk of chunkGroup.chunks) { - if (module.chunkCondition(chunk, compilation)) { - targetChunks.add(chunk); - continue chunkGroupLoop; - } - } - // We reached the entrypoint: fail - if (chunkGroup.isInitial()) { - throw new Error( - "Cannot fullfil chunk condition of " + module.identifier() - ); - } - // Try placing in all parents - for (const group of chunkGroup.parentsIterable) { - chunkGroups.add(group); - } - } - for (const sourceChunk of sourceChunks) { - chunkGraph.disconnectChunkAndModule(sourceChunk, module); - } - for (const targetChunk of targetChunks) { - chunkGraph.connectChunkAndModule(targetChunk, module); - } - sourceChunks.clear(); - chunkGroups.clear(); - } - }; - compilation.hooks.optimizeChunks.tap( - { - name: "EnsureChunkConditionsPlugin", - stage: STAGE_BASIC - }, - handler - ); - } - ); + constructor(request) { + super(request); + this.weak = true; + } + + get type() { + return "loader import"; + } + + get category() { + return "loaderImport"; } } -module.exports = EnsureChunkConditionsPlugin; + +module.exports = LoaderImportDependency; /***/ }), -/***/ 50089: -/***/ (function(module) { +/***/ 24721: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -101801,476 +93809,587 @@ module.exports = EnsureChunkConditionsPlugin; -/** @typedef {import("../Chunk")} Chunk */ +const NormalModule = __webpack_require__(39); +const LazySet = __webpack_require__(38938); +const LoaderDependency = __webpack_require__(71693); +const LoaderImportDependency = __webpack_require__(223); + +/** @typedef {import("../Compilation").DepConstructor} DepConstructor */ /** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Module")} Module */ -class FlagIncludedChunksPlugin { +/** + * @callback LoadModuleCallback + * @param {(Error | null)=} err error object + * @param {string | Buffer=} source source code + * @param {object=} map source map + * @param {Module=} module loaded module if successful + */ + +/** + * @callback ImportModuleCallback + * @param {(Error | null)=} err error object + * @param {any=} exports exports of the evaluated module + */ + +/** + * @typedef {Object} ImportModuleOptions + * @property {string=} layer the target layer + * @property {string=} publicPath the target public path + */ + +class LoaderPlugin { + /** + * @param {Object} options options + */ + constructor(options = {}) {} + /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap("FlagIncludedChunksPlugin", compilation => { - compilation.hooks.optimizeChunkIds.tap( - "FlagIncludedChunksPlugin", - chunks => { - const chunkGraph = compilation.chunkGraph; - - // prepare two bit integers for each module - // 2^31 is the max number represented as SMI in v8 - // we want the bits distributed this way: - // the bit 2^31 is pretty rar and only one module should get it - // so it has a probability of 1 / modulesCount - // the first bit (2^0) is the easiest and every module could get it - // if it doesn't get a better bit - // from bit 2^n to 2^(n+1) there is a probability of p - // so 1 / modulesCount == p^31 - // <=> p = sqrt31(1 / modulesCount) - // so we use a modulo of 1 / sqrt31(1 / modulesCount) - /** @type {WeakMap} */ - const moduleBits = new WeakMap(); - const modulesCount = compilation.modules.size; - - // precalculate the modulo values for each bit - const modulo = 1 / Math.pow(1 / modulesCount, 1 / 31); - const modulos = Array.from( - { length: 31 }, - (x, i) => Math.pow(modulo, i) | 0 - ); + compiler.hooks.compilation.tap( + "LoaderPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + LoaderDependency, + normalModuleFactory + ); + compilation.dependencyFactories.set( + LoaderImportDependency, + normalModuleFactory + ); + } + ); - // iterate all modules to generate bit values - let i = 0; - for (const module of compilation.modules) { - let bit = 30; - while (i % modulos[bit] !== 0) { - bit--; + compiler.hooks.compilation.tap("LoaderPlugin", compilation => { + const moduleGraph = compilation.moduleGraph; + NormalModule.getCompilationHooks(compilation).loader.tap( + "LoaderPlugin", + loaderContext => { + /** + * @param {string} request the request string to load the module from + * @param {LoadModuleCallback} callback callback returning the loaded module or error + * @returns {void} + */ + loaderContext.loadModule = (request, callback) => { + const dep = new LoaderDependency(request); + dep.loc = { + name: request + }; + const factory = compilation.dependencyFactories.get( + /** @type {DepConstructor} */ (dep.constructor) + ); + if (factory === undefined) { + return callback( + new Error( + `No module factory available for dependency type: ${dep.constructor.name}` + ) + ); } - moduleBits.set(module, 1 << bit); - i++; - } + compilation.buildQueue.increaseParallelism(); + compilation.handleModuleCreation( + { + factory, + dependencies: [dep], + originModule: loaderContext._module, + context: loaderContext.context, + recursive: false + }, + err => { + compilation.buildQueue.decreaseParallelism(); + if (err) { + return callback(err); + } + const referencedModule = moduleGraph.getModule(dep); + if (!referencedModule) { + return callback(new Error("Cannot load the module")); + } + if (referencedModule.getNumberOfErrors() > 0) { + return callback( + new Error("The loaded module contains errors") + ); + } + const moduleSource = referencedModule.originalSource(); + if (!moduleSource) { + return callback( + new Error( + "The module created for a LoaderDependency must have an original source" + ) + ); + } + let source, map; + if (moduleSource.sourceAndMap) { + const sourceAndMap = moduleSource.sourceAndMap(); + map = sourceAndMap.map; + source = sourceAndMap.source; + } else { + map = moduleSource.map(); + source = moduleSource.source(); + } + const fileDependencies = new LazySet(); + const contextDependencies = new LazySet(); + const missingDependencies = new LazySet(); + const buildDependencies = new LazySet(); + referencedModule.addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ); - // iterate all chunks to generate bitmaps - /** @type {WeakMap} */ - const chunkModulesHash = new WeakMap(); - for (const chunk of chunks) { - let hash = 0; - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - hash |= moduleBits.get(module); - } - chunkModulesHash.set(chunk, hash); - } + for (const d of fileDependencies) { + loaderContext.addDependency(d); + } + for (const d of contextDependencies) { + loaderContext.addContextDependency(d); + } + for (const d of missingDependencies) { + loaderContext.addMissingDependency(d); + } + for (const d of buildDependencies) { + loaderContext.addBuildDependency(d); + } + return callback(null, source, map, referencedModule); + } + ); + }; - for (const chunkA of chunks) { - const chunkAHash = chunkModulesHash.get(chunkA); - const chunkAModulesCount = - chunkGraph.getNumberOfChunkModules(chunkA); - if (chunkAModulesCount === 0) continue; - let bestModule = undefined; - for (const module of chunkGraph.getChunkModulesIterable(chunkA)) { - if ( - bestModule === undefined || - chunkGraph.getNumberOfModuleChunks(bestModule) > - chunkGraph.getNumberOfModuleChunks(module) - ) - bestModule = module; + /** + * @param {string} request the request string to load the module from + * @param {ImportModuleOptions=} options options + * @param {ImportModuleCallback=} callback callback returning the exports + * @returns {void} + */ + const importModule = (request, options, callback) => { + const dep = new LoaderImportDependency(request); + dep.loc = { + name: request + }; + const factory = compilation.dependencyFactories.get( + /** @type {DepConstructor} */ (dep.constructor) + ); + if (factory === undefined) { + return callback( + new Error( + `No module factory available for dependency type: ${dep.constructor.name}` + ) + ); } - loopB: for (const chunkB of chunkGraph.getModuleChunksIterable( - bestModule - )) { - // as we iterate the same iterables twice - // skip if we find ourselves - if (chunkA === chunkB) continue; - - const chunkBModulesCount = - chunkGraph.getNumberOfChunkModules(chunkB); - - // ids for empty chunks are not included - if (chunkBModulesCount === 0) continue; - - // instead of swapping A and B just bail - // as we loop twice the current A will be B and B then A - if (chunkAModulesCount > chunkBModulesCount) continue; - - // is chunkA in chunkB? - - // we do a cheap check for the hash value - const chunkBHash = chunkModulesHash.get(chunkB); - if ((chunkBHash & chunkAHash) !== chunkAHash) continue; - - // compare all modules - for (const m of chunkGraph.getChunkModulesIterable(chunkA)) { - if (!chunkGraph.isModuleInChunk(m, chunkB)) continue loopB; + compilation.buildQueue.increaseParallelism(); + compilation.handleModuleCreation( + { + factory, + dependencies: [dep], + originModule: loaderContext._module, + contextInfo: { + issuerLayer: options.layer + }, + context: loaderContext.context, + connectOrigin: false + }, + err => { + compilation.buildQueue.decreaseParallelism(); + if (err) { + return callback(err); + } + const referencedModule = moduleGraph.getModule(dep); + if (!referencedModule) { + return callback(new Error("Cannot load the module")); + } + compilation.executeModule( + referencedModule, + { + entryOptions: { + publicPath: options.publicPath + } + }, + (err, result) => { + if (err) return callback(err); + for (const d of result.fileDependencies) { + loaderContext.addDependency(d); + } + for (const d of result.contextDependencies) { + loaderContext.addContextDependency(d); + } + for (const d of result.missingDependencies) { + loaderContext.addMissingDependency(d); + } + for (const d of result.buildDependencies) { + loaderContext.addBuildDependency(d); + } + if (result.cacheable === false) + loaderContext.cacheable(false); + for (const [name, { source, info }] of result.assets) { + const { buildInfo } = loaderContext._module; + if (!buildInfo.assets) { + buildInfo.assets = Object.create(null); + buildInfo.assetsInfo = new Map(); + } + buildInfo.assets[name] = source; + buildInfo.assetsInfo.set(name, info); + } + callback(null, result.exports); + } + ); } - chunkB.ids.push(chunkA.id); + ); + }; + + /** + * @param {string} request the request string to load the module from + * @param {ImportModuleOptions} options options + * @param {ImportModuleCallback=} callback callback returning the exports + * @returns {Promise | void} exports + */ + loaderContext.importModule = (request, options, callback) => { + if (!callback) { + return new Promise((resolve, reject) => { + importModule(request, options || {}, (err, result) => { + if (err) reject(err); + else resolve(result); + }); + }); } - } + return importModule(request, options || {}, callback); + }; } ); }); } } -module.exports = FlagIncludedChunksPlugin; +module.exports = LoaderPlugin; /***/ }), -/***/ 38988: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 5826: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov + Author Tobias Koppers @sokra */ -const { UsageState } = __webpack_require__(63686); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("estree").Node} AnyNode */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +class LocalModule { + constructor(name, idx) { + this.name = name; + this.idx = idx; + this.used = false; + } -/** @typedef {Map | true>} InnerGraph */ -/** @typedef {function(boolean | Set | undefined): void} UsageCallback */ + flagUsed() { + this.used = true; + } -/** - * @typedef {Object} StateObject - * @property {InnerGraph} innerGraph - * @property {TopLevelSymbol=} currentTopLevelSymbol - * @property {Map>} usageCallbackMap - */ + variableName() { + return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__"; + } -/** @typedef {false|StateObject} State */ + serialize(context) { + const { write } = context; -/** @type {WeakMap} */ -const parserStateMap = new WeakMap(); -const topLevelSymbolTag = Symbol("top level symbol"); + write(this.name); + write(this.idx); + write(this.used); + } -/** - * @param {ParserState} parserState parser state - * @returns {State} state - */ -function getState(parserState) { - return parserStateMap.get(parserState); + deserialize(context) { + const { read } = context; + + this.name = read(); + this.idx = read(); + this.used = read(); + } } -/** - * @param {ParserState} parserState parser state - * @returns {void} - */ -exports.bailout = parserState => { - parserStateMap.set(parserState, false); -}; +makeSerializable(LocalModule, "webpack/lib/dependencies/LocalModule"); -/** - * @param {ParserState} parserState parser state - * @returns {void} - */ -exports.enable = parserState => { - const state = parserStateMap.get(parserState); - if (state === false) { - return; - } - parserStateMap.set(parserState, { - innerGraph: new Map(), - currentTopLevelSymbol: undefined, - usageCallbackMap: new Map() - }); -}; +module.exports = LocalModule; -/** - * @param {ParserState} parserState parser state - * @returns {boolean} true, when enabled - */ -exports.isEnabled = parserState => { - const state = parserStateMap.get(parserState); - return !!state; -}; -/** - * @param {ParserState} state parser state - * @param {TopLevelSymbol | null} symbol the symbol, or null for all symbols - * @param {string | TopLevelSymbol | true} usage usage data - * @returns {void} - */ -exports.addUsage = (state, symbol, usage) => { - const innerGraphState = getState(state); +/***/ }), - if (innerGraphState) { - const { innerGraph } = innerGraphState; - const info = innerGraph.get(symbol); - if (usage === true) { - innerGraph.set(symbol, true); - } else if (info === undefined) { - innerGraph.set(symbol, new Set([usage])); - } else if (info !== true) { - info.add(usage); - } - } -}; +/***/ 52805: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * @param {JavascriptParser} parser the parser - * @param {string} name name of variable - * @param {string | TopLevelSymbol | true} usage usage data - * @returns {void} - */ -exports.addVariableUsage = (parser, name, usage) => { - const symbol = - /** @type {TopLevelSymbol} */ ( - parser.getTagData(name, topLevelSymbolTag) - ) || exports.tagTopLevelSymbol(parser, name); - if (symbol) { - exports.addUsage(parser.state, symbol, usage); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + +class LocalModuleDependency extends NullDependency { + constructor(localModule, range, callNew) { + super(); + + this.localModule = localModule; + this.range = range; + this.callNew = callNew; } -}; -/** - * @param {ParserState} state parser state - * @returns {void} - */ -exports.inferDependencyUsage = state => { - const innerGraphState = getState(state); + serialize(context) { + const { write } = context; - if (!innerGraphState) { - return; + write(this.localModule); + write(this.range); + write(this.callNew); + + super.serialize(context); } - const { innerGraph, usageCallbackMap } = innerGraphState; - const processed = new Map(); - // flatten graph to terminal nodes (string, undefined or true) - const nonTerminal = new Set(innerGraph.keys()); - while (nonTerminal.size > 0) { - for (const key of nonTerminal) { - /** @type {Set | true} */ - let newSet = new Set(); - let isTerminal = true; - const value = innerGraph.get(key); - let alreadyProcessed = processed.get(key); - if (alreadyProcessed === undefined) { - alreadyProcessed = new Set(); - processed.set(key, alreadyProcessed); - } - if (value !== true && value !== undefined) { - for (const item of value) { - alreadyProcessed.add(item); - } - for (const item of value) { - if (typeof item === "string") { - newSet.add(item); - } else { - const itemValue = innerGraph.get(item); - if (itemValue === true) { - newSet = true; - break; - } - if (itemValue !== undefined) { - for (const i of itemValue) { - if (i === key) continue; - if (alreadyProcessed.has(i)) continue; - newSet.add(i); - if (typeof i !== "string") { - isTerminal = false; - } - } - } - } - } - if (newSet === true) { - innerGraph.set(key, true); - } else if (newSet.size === 0) { - innerGraph.set(key, undefined); - } else { - innerGraph.set(key, newSet); - } - } - if (isTerminal) { - nonTerminal.delete(key); + deserialize(context) { + const { read } = context; - // For the global key, merge with all other keys - if (key === null) { - const globalValue = innerGraph.get(null); - if (globalValue) { - for (const [key, value] of innerGraph) { - if (key !== null && value !== true) { - if (globalValue === true) { - innerGraph.set(key, true); - } else { - const newSet = new Set(value); - for (const item of globalValue) { - newSet.add(item); - } - innerGraph.set(key, newSet); - } - } - } - } - } - } - } + this.localModule = read(); + this.range = read(); + this.callNew = read(); + + super.deserialize(context); } +} - /** @type {Map>} */ - for (const [symbol, callbacks] of usageCallbackMap) { - const usage = /** @type {true | Set | undefined} */ ( - innerGraph.get(symbol) - ); - for (const callback of callbacks) { - callback(usage === undefined ? false : usage); - } +makeSerializable( + LocalModuleDependency, + "webpack/lib/dependencies/LocalModuleDependency" +); + +LocalModuleDependency.Template = class LocalModuleDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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 dep = /** @type {LocalModuleDependency} */ (dependency); + if (!dep.range) return; + const moduleInstance = dep.callNew + ? `new (function () { return ${dep.localModule.variableName()}; })()` + : dep.localModule.variableName(); + source.replace(dep.range[0], dep.range[1] - 1, moduleInstance); } }; -/** - * @param {ParserState} state parser state - * @param {UsageCallback} onUsageCallback on usage callback - */ -exports.onUsage = (state, onUsageCallback) => { - const innerGraphState = getState(state); +module.exports = LocalModuleDependency; - if (innerGraphState) { - const { usageCallbackMap, currentTopLevelSymbol } = innerGraphState; - if (currentTopLevelSymbol) { - let callbacks = usageCallbackMap.get(currentTopLevelSymbol); - if (callbacks === undefined) { - callbacks = new Set(); - usageCallbackMap.set(currentTopLevelSymbol, callbacks); - } +/***/ }), - callbacks.add(onUsageCallback); - } else { - onUsageCallback(true); +/***/ 75827: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const LocalModule = __webpack_require__(5826); + +const lookup = (parent, mod) => { + if (mod.charAt(0) !== ".") return mod; + + var path = parent.split("/"); + var segments = mod.split("/"); + path.pop(); + + for (let i = 0; i < segments.length; i++) { + const seg = segments[i]; + if (seg === "..") { + path.pop(); + } else if (seg !== ".") { + path.push(seg); } - } else { - onUsageCallback(undefined); } + + return path.join("/"); }; -/** - * @param {ParserState} state parser state - * @param {TopLevelSymbol} symbol the symbol - */ -exports.setTopLevelSymbol = (state, symbol) => { - const innerGraphState = getState(state); +exports.addLocalModule = (state, name) => { + if (!state.localModules) { + state.localModules = []; + } + const m = new LocalModule(name, state.localModules.length); + state.localModules.push(m); + return m; +}; - if (innerGraphState) { - innerGraphState.currentTopLevelSymbol = symbol; +exports.getLocalModule = (state, name, namedModule) => { + if (!state.localModules) return null; + if (namedModule) { + // resolve dependency name relative to the defining named module + name = lookup(namedModule, name); + } + for (let i = 0; i < state.localModules.length; i++) { + if (state.localModules[i].name === name) { + return state.localModules[i]; + } } + return null; }; -/** - * @param {ParserState} state parser state - * @returns {TopLevelSymbol|void} usage data - */ -exports.getTopLevelSymbol = state => { - const innerGraphState = getState(state); - if (innerGraphState) { - return innerGraphState.currentTopLevelSymbol; +/***/ }), + +/***/ 88488: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const Dependency = __webpack_require__(54912); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class ModuleDecoratorDependency extends NullDependency { + /** + * @param {string} decorator the decorator requirement + * @param {boolean} allowExportsAccess allow to access exports from module + */ + constructor(decorator, allowExportsAccess) { + super(); + this.decorator = decorator; + this.allowExportsAccess = allowExportsAccess; + this._hashUpdate = undefined; } -}; -/** - * @param {JavascriptParser} parser parser - * @param {string} name name of variable - * @returns {TopLevelSymbol} symbol - */ -exports.tagTopLevelSymbol = (parser, name) => { - const innerGraphState = getState(parser.state); - if (!innerGraphState) return; + /** + * @returns {string} a display name for the type of dependency + */ + get type() { + return "module decorator"; + } - parser.defineVariable(name); + get category() { + return "self"; + } - const existingTag = /** @type {TopLevelSymbol} */ ( - parser.getTagData(name, topLevelSymbolTag) - ); - if (existingTag) { - return existingTag; + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return `self`; } - const fn = new TopLevelSymbol(name); - parser.tagVariable(name, topLevelSymbolTag, fn); - return fn; -}; + /** + * 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 this.allowExportsAccess + ? Dependency.EXPORTS_OBJECT_REFERENCED + : Dependency.NO_EXPORTS_REFERENCED; + } -/** - * @param {Dependency} dependency the dependency - * @param {Set | boolean} usedByExports usedByExports info - * @param {ModuleGraph} moduleGraph moduleGraph - * @param {RuntimeSpec} runtime runtime - * @returns {boolean} false, when unused. Otherwise true - */ -exports.isDependencyUsedByExports = ( - dependency, - usedByExports, - moduleGraph, - runtime -) => { - if (usedByExports === false) return false; - if (usedByExports !== true && usedByExports !== undefined) { - const selfModule = moduleGraph.getParentModule(dependency); - const exportsInfo = moduleGraph.getExportsInfo(selfModule); - let used = false; - for (const exportName of usedByExports) { - if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) - used = true; + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = `${this.decorator}${this.allowExportsAccess}`; } - if (!used) return false; + hash.update(this._hashUpdate); } - return true; -}; -/** - * @param {Dependency} dependency the dependency - * @param {Set | boolean} usedByExports usedByExports info - * @param {ModuleGraph} moduleGraph moduleGraph - * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active - */ -exports.getDependencyUsedByExportsCondition = ( - dependency, - usedByExports, - moduleGraph -) => { - if (usedByExports === false) return false; - if (usedByExports !== true && usedByExports !== undefined) { - const selfModule = moduleGraph.getParentModule(dependency); - const exportsInfo = moduleGraph.getExportsInfo(selfModule); - return (connections, runtime) => { - for (const exportName of usedByExports) { - if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) - return true; - } - return false; - }; + serialize(context) { + const { write } = context; + write(this.decorator); + write(this.allowExportsAccess); + super.serialize(context); } - return null; -}; -class TopLevelSymbol { + deserialize(context) { + const { read } = context; + this.decorator = read(); + this.allowExportsAccess = read(); + super.deserialize(context); + } +} + +makeSerializable( + ModuleDecoratorDependency, + "webpack/lib/dependencies/ModuleDecoratorDependency" +); + +ModuleDecoratorDependency.Template = class ModuleDecoratorDependencyTemplate extends ( + NullDependency.Template +) { /** - * @param {string} name name of the variable + * @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} */ - constructor(name) { - this.name = name; + apply( + dependency, + source, + { module, chunkGraph, initFragments, runtimeRequirements } + ) { + const dep = /** @type {ModuleDecoratorDependency} */ (dependency); + runtimeRequirements.add(RuntimeGlobals.moduleLoaded); + runtimeRequirements.add(RuntimeGlobals.moduleId); + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(dep.decorator); + initFragments.push( + new InitFragment( + `/* module decorator */ ${module.moduleArgument} = ${dep.decorator}(${module.moduleArgument});\n`, + InitFragment.STAGE_PROVIDES, + 0, + `module decorator ${chunkGraph.getModuleId(module)}` + ) + ); } -} +}; -exports.TopLevelSymbol = TopLevelSymbol; -exports.topLevelSymbolTag = topLevelSymbolTag; +module.exports = ModuleDecoratorDependency; /***/ }), -/***/ 28758: +/***/ 80321: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102281,372 +94400,216 @@ exports.topLevelSymbolTag = topLevelSymbolTag; -const PureExpressionDependency = __webpack_require__(55799); -const InnerGraph = __webpack_require__(38988); +const Dependency = __webpack_require__(54912); +const DependencyTemplate = __webpack_require__(5160); +const memoize = __webpack_require__(78676); -/** @typedef {import("estree").ClassDeclaration} ClassDeclarationNode */ -/** @typedef {import("estree").ClassExpression} ClassExpressionNode */ -/** @typedef {import("estree").Node} Node */ -/** @typedef {import("estree").VariableDeclarator} VariableDeclaratorNode */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../dependencies/HarmonyImportSpecifierDependency")} HarmonyImportSpecifierDependency */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ -/** @typedef {import("./InnerGraph").InnerGraph} InnerGraph */ -/** @typedef {import("./InnerGraph").TopLevelSymbol} TopLevelSymbol */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../Module")} Module */ -const { topLevelSymbolTag } = InnerGraph; +const getRawModule = memoize(() => __webpack_require__(84929)); -class InnerGraphPlugin { +class ModuleDependency extends Dependency { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {string} request request path which needs resolving */ - apply(compiler) { - compiler.hooks.compilation.tap( - "InnerGraphPlugin", - (compilation, { normalModuleFactory }) => { - const logger = compilation.getLogger("webpack.InnerGraphPlugin"); + constructor(request) { + super(); + this.request = request; + this.userRequest = request; + this.range = undefined; + // assertions must be serialized by subclasses that use it + /** @type {Record | undefined} */ + this.assertions = undefined; + } - compilation.dependencyTemplates.set( - PureExpressionDependency, - new PureExpressionDependency.Template() - ); + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + let str = `module${this.request}`; + if (this.assertions !== undefined) { + str += JSON.stringify(this.assertions); + } + return str; + } - /** - * @param {JavascriptParser} parser the parser - * @param {Object} parserOptions options - * @returns {void} - */ - const handler = (parser, parserOptions) => { - const onUsageSuper = sup => { - InnerGraph.onUsage(parser.state, usedByExports => { - switch (usedByExports) { - case undefined: - case true: - return; - default: { - const dep = new PureExpressionDependency(sup.range); - dep.loc = sup.loc; - dep.usedByExports = usedByExports; - parser.state.module.addDependency(dep); - break; - } - } - }); - }; + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return true; + } - parser.hooks.program.tap("InnerGraphPlugin", () => { - InnerGraph.enable(parser.state); - }); + /** + * @param {string} context context directory + * @returns {Module} a module + */ + createIgnoredModule(context) { + const RawModule = getRawModule(); + return new RawModule( + "/* (ignored) */", + `ignored|${context}|${this.request}`, + `${this.request} (ignored)` + ); + } - parser.hooks.finish.tap("InnerGraphPlugin", () => { - if (!InnerGraph.isEnabled(parser.state)) return; + serialize(context) { + const { write } = context; + write(this.request); + write(this.userRequest); + write(this.range); + super.serialize(context); + } - logger.time("infer dependency usage"); - InnerGraph.inferDependencyUsage(parser.state); - logger.timeAggregate("infer dependency usage"); - }); + deserialize(context) { + const { read } = context; + this.request = read(); + this.userRequest = read(); + this.range = read(); + super.deserialize(context); + } +} - // During prewalking the following datastructures are filled with - // nodes that have a TopLevelSymbol assigned and - // variables are tagged with the assigned TopLevelSymbol +ModuleDependency.Template = DependencyTemplate; - // We differ 3 types of nodes: - // 1. full statements (export default, function declaration) - // 2. classes (class declaration, class expression) - // 3. variable declarators (const x = ...) +module.exports = ModuleDependency; - /** @type {WeakMap} */ - const statementWithTopLevelSymbol = new WeakMap(); - /** @type {WeakMap} */ - const statementPurePart = new WeakMap(); - /** @type {WeakMap} */ - const classWithTopLevelSymbol = new WeakMap(); +/***/ }), - /** @type {WeakMap} */ - const declWithTopLevelSymbol = new WeakMap(); - /** @type {WeakSet} */ - const pureDeclarators = new WeakSet(); +/***/ 80825: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // The following hooks are used during prewalking: +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - parser.hooks.preStatement.tap("InnerGraphPlugin", statement => { - if (!InnerGraph.isEnabled(parser.state)) return; - if (parser.scope.topLevelScope === true) { - if (statement.type === "FunctionDeclaration") { - const name = statement.id ? statement.id.name : "*default*"; - const fn = InnerGraph.tagTopLevelSymbol(parser, name); - statementWithTopLevelSymbol.set(statement, fn); - return true; - } - } - }); - parser.hooks.blockPreStatement.tap("InnerGraphPlugin", statement => { - if (!InnerGraph.isEnabled(parser.state)) return; +const ModuleDependency = __webpack_require__(80321); - if (parser.scope.topLevelScope === true) { - if (statement.type === "ClassDeclaration") { - const name = statement.id ? statement.id.name : "*default*"; - const fn = InnerGraph.tagTopLevelSymbol(parser, name); - classWithTopLevelSymbol.set(statement, fn); - return true; - } - if (statement.type === "ExportDefaultDeclaration") { - const name = "*default*"; - const fn = InnerGraph.tagTopLevelSymbol(parser, name); - const decl = statement.declaration; - if ( - decl.type === "ClassExpression" || - decl.type === "ClassDeclaration" - ) { - classWithTopLevelSymbol.set(decl, fn); - } else if (parser.isPure(decl, statement.range[0])) { - statementWithTopLevelSymbol.set(statement, fn); - if ( - !decl.type.endsWith("FunctionExpression") && - !decl.type.endsWith("Declaration") && - decl.type !== "Literal" - ) { - statementPurePart.set(statement, decl); - } - } - } - } - }); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - parser.hooks.preDeclarator.tap( - "InnerGraphPlugin", - (decl, statement) => { - if (!InnerGraph.isEnabled(parser.state)) return; - if ( - parser.scope.topLevelScope === true && - decl.init && - decl.id.type === "Identifier" - ) { - const name = decl.id.name; - if (decl.init.type === "ClassExpression") { - const fn = InnerGraph.tagTopLevelSymbol(parser, name); - classWithTopLevelSymbol.set(decl.init, fn); - } else if (parser.isPure(decl.init, decl.id.range[1])) { - const fn = InnerGraph.tagTopLevelSymbol(parser, name); - declWithTopLevelSymbol.set(decl, fn); - if ( - !decl.init.type.endsWith("FunctionExpression") && - decl.init.type !== "Literal" - ) { - pureDeclarators.add(decl); - } - return true; - } - } - } - ); +class ModuleDependencyTemplateAsId extends ModuleDependency.Template { + /** + * @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, { runtimeTemplate, moduleGraph, chunkGraph }) { + const dep = /** @type {ModuleDependency} */ (dependency); + if (!dep.range) return; + const content = runtimeTemplate.moduleId({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + weak: dep.weak + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +} - // During real walking we set the TopLevelSymbol state to the assigned - // TopLevelSymbol by using the fill datastructures. +module.exports = ModuleDependencyTemplateAsId; - // In addition to tracking TopLevelSymbols, we sometimes need to - // add a PureExpressionDependency. This is needed to skip execution - // of pure expressions, even when they are not dropped due to - // minimizing. Otherwise symbols used there might not exist anymore - // as they are removed as unused by this optimization - // When we find a reference to a TopLevelSymbol, we register a - // TopLevelSymbol dependency from TopLevelSymbol in state to the - // referenced TopLevelSymbol. This way we get a graph of all - // TopLevelSymbols. +/***/ }), - // The following hooks are called during walking: +/***/ 36873: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - parser.hooks.statement.tap("InnerGraphPlugin", statement => { - if (!InnerGraph.isEnabled(parser.state)) return; - if (parser.scope.topLevelScope === true) { - InnerGraph.setTopLevelSymbol(parser.state, undefined); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const fn = statementWithTopLevelSymbol.get(statement); - if (fn) { - InnerGraph.setTopLevelSymbol(parser.state, fn); - const purePart = statementPurePart.get(statement); - if (purePart) { - InnerGraph.onUsage(parser.state, usedByExports => { - switch (usedByExports) { - case undefined: - case true: - return; - default: { - const dep = new PureExpressionDependency( - purePart.range - ); - dep.loc = statement.loc; - dep.usedByExports = usedByExports; - parser.state.module.addDependency(dep); - break; - } - } - }); - } - } - } - }); - parser.hooks.classExtendsExpression.tap( - "InnerGraphPlugin", - (expr, statement) => { - if (!InnerGraph.isEnabled(parser.state)) return; - if (parser.scope.topLevelScope === true) { - const fn = classWithTopLevelSymbol.get(statement); - if ( - fn && - parser.isPure( - expr, - statement.id ? statement.id.range[1] : statement.range[0] - ) - ) { - InnerGraph.setTopLevelSymbol(parser.state, fn); - onUsageSuper(expr); - } - } - } - ); - parser.hooks.classBodyElement.tap( - "InnerGraphPlugin", - (element, classDefinition) => { - if (!InnerGraph.isEnabled(parser.state)) return; - if (parser.scope.topLevelScope === true) { - const fn = classWithTopLevelSymbol.get(classDefinition); - if (fn) { - InnerGraph.setTopLevelSymbol(parser.state, undefined); - } - } - } - ); +const ModuleDependency = __webpack_require__(80321); - parser.hooks.classBodyValue.tap( - "InnerGraphPlugin", - (expression, element, classDefinition) => { - if (!InnerGraph.isEnabled(parser.state)) return; - if (parser.scope.topLevelScope === true) { - const fn = classWithTopLevelSymbol.get(classDefinition); - if (fn) { - if ( - !element.static || - parser.isPure( - expression, - element.key ? element.key.range[1] : element.range[0] - ) - ) { - InnerGraph.setTopLevelSymbol(parser.state, fn); - if (element.type !== "MethodDefinition" && element.static) { - InnerGraph.onUsage(parser.state, usedByExports => { - switch (usedByExports) { - case undefined: - case true: - return; - default: { - const dep = new PureExpressionDependency( - expression.range - ); - dep.loc = expression.loc; - dep.usedByExports = usedByExports; - parser.state.module.addDependency(dep); - break; - } - } - }); - } - } else { - InnerGraph.setTopLevelSymbol(parser.state, undefined); - } - } - } - } - ); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - parser.hooks.declarator.tap("InnerGraphPlugin", (decl, statement) => { - if (!InnerGraph.isEnabled(parser.state)) return; - const fn = declWithTopLevelSymbol.get(decl); +class ModuleDependencyTemplateAsRequireId extends ModuleDependency.Template { + /** + * @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, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ModuleDependency} */ (dependency); + if (!dep.range) return; + const content = runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + weak: dep.weak, + runtimeRequirements + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +} +module.exports = ModuleDependencyTemplateAsRequireId; - if (fn) { - InnerGraph.setTopLevelSymbol(parser.state, fn); - if (pureDeclarators.has(decl)) { - if (decl.init.type === "ClassExpression") { - if (decl.init.superClass) { - onUsageSuper(decl.init.superClass); - } - } else { - InnerGraph.onUsage(parser.state, usedByExports => { - switch (usedByExports) { - case undefined: - case true: - return; - default: { - const dep = new PureExpressionDependency( - decl.init.range - ); - dep.loc = decl.loc; - dep.usedByExports = usedByExports; - parser.state.module.addDependency(dep); - break; - } - } - }); - } - } - parser.walkExpression(decl.init); - InnerGraph.setTopLevelSymbol(parser.state, undefined); - return true; - } - }); - parser.hooks.expression - .for(topLevelSymbolTag) - .tap("InnerGraphPlugin", () => { - const topLevelSymbol = /** @type {TopLevelSymbol} */ ( - parser.currentTagData - ); - const currentTopLevelSymbol = InnerGraph.getTopLevelSymbol( - parser.state - ); - InnerGraph.addUsage( - parser.state, - topLevelSymbol, - currentTopLevelSymbol || true - ); - }); - parser.hooks.assign - .for(topLevelSymbolTag) - .tap("InnerGraphPlugin", expr => { - if (!InnerGraph.isEnabled(parser.state)) return; - if (expr.operator === "=") return true; - }); - }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("InnerGraphPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("InnerGraphPlugin", handler); +/***/ }), - compilation.hooks.finishModules.tap("InnerGraphPlugin", () => { - logger.timeAggregateEnd("infer dependency usage"); - }); - } - ); +/***/ 47511: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyTemplateAsId = __webpack_require__(80825); + +class ModuleHotAcceptDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; + } + + get type() { + return "module.hot.accept"; + } + + get category() { + return "commonjs"; } } -module.exports = InnerGraphPlugin; +makeSerializable( + ModuleHotAcceptDependency, + "webpack/lib/dependencies/ModuleHotAcceptDependency" +); + +ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = ModuleHotAcceptDependency; /***/ }), -/***/ 83608: +/***/ 86301: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102657,445 +94620,250 @@ module.exports = InnerGraphPlugin; -const { STAGE_ADVANCED } = __webpack_require__(80057); -const LazyBucketSortedSet = __webpack_require__(48424); -const { compareChunks } = __webpack_require__(29579); -const createSchemaValidation = __webpack_require__(32540); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyTemplateAsId = __webpack_require__(80825); -/** @typedef {import("../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions} LimitChunkCountPluginOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ +class ModuleHotDeclineDependency extends ModuleDependency { + constructor(request, range) { + super(request); -const validate = createSchemaValidation( - __webpack_require__(36557), - () => __webpack_require__(30837), - { - name: "Limit Chunk Count Plugin", - baseDataPath: "options" + this.range = range; + this.weak = true; } -); - -/** - * @typedef {Object} ChunkCombination - * @property {boolean} deleted this is set to true when combination was removed - * @property {number} sizeDiff - * @property {number} integratedSize - * @property {Chunk} a - * @property {Chunk} b - * @property {number} aIdx - * @property {number} bIdx - * @property {number} aSize - * @property {number} bSize - */ -const addToSetMap = (map, key, value) => { - const set = map.get(key); - if (set === undefined) { - map.set(key, new Set([value])); - } else { - set.add(value); + get type() { + return "module.hot.decline"; } -}; -class LimitChunkCountPlugin { - /** - * @param {LimitChunkCountPluginOptions=} options options object - */ - constructor(options) { - validate(options); - this.options = options; + get category() { + return "commonjs"; } +} - /** - * @param {Compiler} compiler the webpack compiler - * @returns {void} - */ - apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap("LimitChunkCountPlugin", compilation => { - compilation.hooks.optimizeChunks.tap( - { - name: "LimitChunkCountPlugin", - stage: STAGE_ADVANCED - }, - chunks => { - const chunkGraph = compilation.chunkGraph; - const maxChunks = options.maxChunks; - if (!maxChunks) return; - if (maxChunks < 1) return; - if (compilation.chunks.size <= maxChunks) return; +makeSerializable( + ModuleHotDeclineDependency, + "webpack/lib/dependencies/ModuleHotDeclineDependency" +); - let remainingChunksToMerge = compilation.chunks.size - maxChunks; +ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId; - // order chunks in a deterministic way - const compareChunksWithGraph = compareChunks(chunkGraph); - const orderedChunks = Array.from(chunks).sort(compareChunksWithGraph); +module.exports = ModuleHotDeclineDependency; - // create a lazy sorted data structure to keep all combinations - // this is large. Size = chunks * (chunks - 1) / 2 - // It uses a multi layer bucket sort plus normal sort in the last layer - // It's also lazy so only accessed buckets are sorted - const combinations = new LazyBucketSortedSet( - // Layer 1: ordered by largest size benefit - c => c.sizeDiff, - (a, b) => b - a, - // Layer 2: ordered by smallest combined size - c => c.integratedSize, - (a, b) => a - b, - // Layer 3: ordered by position difference in orderedChunk (-> to be deterministic) - c => c.bIdx - c.aIdx, - (a, b) => a - b, - // Layer 4: ordered by position in orderedChunk (-> to be deterministic) - (a, b) => a.bIdx - b.bIdx - ); - // we keep a mapping from chunk to all combinations - // but this mapping is not kept up-to-date with deletions - // so `deleted` flag need to be considered when iterating this - /** @type {Map>} */ - const combinationsByChunk = new Map(); +/***/ }), - orderedChunks.forEach((b, bIdx) => { - // create combination pairs with size and integrated size - for (let aIdx = 0; aIdx < bIdx; aIdx++) { - const a = orderedChunks[aIdx]; - // filter pairs that can not be integrated! - if (!chunkGraph.canChunksBeIntegrated(a, b)) continue; +/***/ 31830: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const integratedSize = chunkGraph.getIntegratedChunksSize( - a, - b, - options - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const aSize = chunkGraph.getChunkSize(a, options); - const bSize = chunkGraph.getChunkSize(b, options); - const c = { - deleted: false, - sizeDiff: aSize + bSize - integratedSize, - integratedSize, - a, - b, - aIdx, - bIdx, - aSize, - bSize - }; - combinations.add(c); - addToSetMap(combinationsByChunk, a, c); - addToSetMap(combinationsByChunk, b, c); - } - return combinations; - }); - // list of modified chunks during this run - // combinations affected by this change are skipped to allow - // further optimizations - /** @type {Set} */ - const modifiedChunks = new Set(); - let changed = false; - // eslint-disable-next-line no-constant-condition - loop: while (true) { - const combination = combinations.popFirst(); - if (combination === undefined) break; +const Dependency = __webpack_require__(54912); +const DependencyTemplate = __webpack_require__(5160); - combination.deleted = true; - const { a, b, integratedSize } = combination; +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - // skip over pair when - // one of the already merged chunks is a parent of one of the chunks - if (modifiedChunks.size > 0) { - const queue = new Set(a.groupsIterable); - for (const group of b.groupsIterable) { - queue.add(group); - } - for (const group of queue) { - for (const mChunk of modifiedChunks) { - if (mChunk !== a && mChunk !== b && mChunk.isInGroup(group)) { - // This is a potential pair which needs recalculation - // We can't do that now, but it merge before following pairs - // so we leave space for it, and consider chunks as modified - // just for the worse case - remainingChunksToMerge--; - if (remainingChunksToMerge <= 0) break loop; - modifiedChunks.add(a); - modifiedChunks.add(b); - continue loop; - } - } - for (const parent of group.parentsIterable) { - queue.add(parent); - } - } - } +class NullDependency extends Dependency { + get type() { + return "null"; + } - // merge the chunks - if (chunkGraph.canChunksBeIntegrated(a, b)) { - chunkGraph.integrateChunks(a, b); - compilation.chunks.delete(b); + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return false; + } +} - // flag chunk a as modified as further optimization are possible for all children here - modifiedChunks.add(a); +NullDependency.Template = class NullDependencyTemplate extends ( + DependencyTemplate +) { + /** + * @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) {} +}; - changed = true; - remainingChunksToMerge--; - if (remainingChunksToMerge <= 0) break; +module.exports = NullDependency; - // Update all affected combinations - // delete all combination with the removed chunk - // we will use combinations with the kept chunk instead - for (const combination of combinationsByChunk.get(a)) { - if (combination.deleted) continue; - combination.deleted = true; - combinations.delete(combination); - } - // Update combinations with the kept chunk with new sizes - for (const combination of combinationsByChunk.get(b)) { - if (combination.deleted) continue; - if (combination.a === b) { - if (!chunkGraph.canChunksBeIntegrated(a, combination.b)) { - combination.deleted = true; - combinations.delete(combination); - continue; - } - // Update size - const newIntegratedSize = chunkGraph.getIntegratedChunksSize( - a, - combination.b, - options - ); - const finishUpdate = combinations.startUpdate(combination); - combination.a = a; - combination.integratedSize = newIntegratedSize; - combination.aSize = integratedSize; - combination.sizeDiff = - combination.bSize + integratedSize - newIntegratedSize; - finishUpdate(); - } else if (combination.b === b) { - if (!chunkGraph.canChunksBeIntegrated(combination.a, a)) { - combination.deleted = true; - combinations.delete(combination); - continue; - } - // Update size - const newIntegratedSize = chunkGraph.getIntegratedChunksSize( - combination.a, - a, - options - ); +/***/ }), - const finishUpdate = combinations.startUpdate(combination); - combination.b = a; - combination.integratedSize = newIntegratedSize; - combination.bSize = integratedSize; - combination.sizeDiff = - integratedSize + combination.aSize - newIntegratedSize; - finishUpdate(); - } - } - combinationsByChunk.set(a, combinationsByChunk.get(b)); - combinationsByChunk.delete(b); - } - } - if (changed) return true; - } - ); - }); +/***/ 31618: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const ModuleDependency = __webpack_require__(80321); + +class PrefetchDependency extends ModuleDependency { + constructor(request) { + super(request); + } + + get type() { + return "prefetch"; + } + + get category() { + return "esm"; } } -module.exports = LimitChunkCountPlugin; + +module.exports = PrefetchDependency; /***/ }), -/***/ 27868: +/***/ 95770: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Florent Cailhol @ooflorent */ -const { UsageState } = __webpack_require__(63686); -const { - numberToIdentifier, - NUMBER_OF_IDENTIFIER_START_CHARS, - NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS -} = __webpack_require__(1626); -const { assignDeterministicIds } = __webpack_require__(63290); -const { compareSelect, compareStringsNumeric } = __webpack_require__(29579); +const InitFragment = __webpack_require__(55870); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../ExportsInfo")} ExportsInfo */ -/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../util/Hash")} Hash */ /** - * @param {ExportsInfo} exportsInfo exports info - * @returns {boolean} mangle is possible + * @param {string[]|null} path the property path array + * @returns {string} the converted path */ -const canMangle = exportsInfo => { - if (exportsInfo.otherExportsInfo.getUsed(undefined) !== UsageState.Unused) - return false; - let hasSomethingToMangle = false; - for (const exportInfo of exportsInfo.exports) { - if (exportInfo.canMangle === true) { - hasSomethingToMangle = true; - } +const pathToString = path => + path !== null && path.length > 0 + ? path.map(part => `[${JSON.stringify(part)}]`).join("") + : ""; + +class ProvidedDependency extends ModuleDependency { + constructor(request, identifier, path, range) { + super(request); + this.identifier = identifier; + this.path = path; + this.range = range; + this._hashUpdate = undefined; } - return hasSomethingToMangle; -}; -// Sort by name -const comparator = compareSelect(e => e.name, compareStringsNumeric); -/** - * @param {boolean} deterministic use deterministic names - * @param {ExportsInfo} exportsInfo exports info - * @param {boolean} isNamespace is namespace object - * @returns {void} - */ -const mangleExportsInfo = (deterministic, exportsInfo, isNamespace) => { - if (!canMangle(exportsInfo)) return; - const usedNames = new Set(); - /** @type {ExportInfo[]} */ - const mangleableExports = []; + get type() { + return "provided"; + } - // Avoid to renamed exports that are not provided when - // 1. it's not a namespace export: non-provided exports can be found in prototype chain - // 2. there are other provided exports and deterministic mode is chosen: - // non-provided exports would break the determinism - let avoidMangleNonProvided = !isNamespace; - if (!avoidMangleNonProvided && deterministic) { - for (const exportInfo of exportsInfo.ownedExports) { - if (exportInfo.provided !== false) { - avoidMangleNonProvided = true; - break; - } - } + get category() { + return "esm"; } - for (const exportInfo of exportsInfo.ownedExports) { - const name = exportInfo.name; - if (!exportInfo.hasUsedName()) { - if ( - // Can the export be mangled? - exportInfo.canMangle !== true || - // Never rename 1 char exports - (name.length === 1 && /^[a-zA-Z0-9_$]/.test(name)) || - // Don't rename 2 char exports in deterministic mode - (deterministic && - name.length === 2 && - /^[a-zA-Z_$][a-zA-Z0-9_$]|^[1-9][0-9]/.test(name)) || - // Don't rename exports that are not provided - (avoidMangleNonProvided && exportInfo.provided !== true) - ) { - exportInfo.setUsedName(name); - usedNames.add(name); - } else { - mangleableExports.push(exportInfo); - } - } - if (exportInfo.exportsInfoOwned) { - const used = exportInfo.getUsed(undefined); - if ( - used === UsageState.OnlyPropertiesUsed || - used === UsageState.Unused - ) { - mangleExportsInfo(deterministic, exportInfo.exportsInfo, false); - } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = + this.identifier + (this.path ? this.path.join(",") : "null"); } + hash.update(this._hashUpdate); } - if (deterministic) { - assignDeterministicIds( - mangleableExports, - e => e.name, - comparator, - (e, id) => { - const name = numberToIdentifier(id); - const size = usedNames.size; - usedNames.add(name); - if (size === usedNames.size) return false; - e.setUsedName(name); - return true; - }, - [ - NUMBER_OF_IDENTIFIER_START_CHARS, - NUMBER_OF_IDENTIFIER_START_CHARS * - NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS - ], - NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS, - usedNames.size - ); - } else { - const usedExports = []; - const unusedExports = []; - for (const exportInfo of mangleableExports) { - if (exportInfo.getUsed(undefined) === UsageState.Unused) { - unusedExports.push(exportInfo); - } else { - usedExports.push(exportInfo); - } - } - usedExports.sort(comparator); - unusedExports.sort(comparator); - let i = 0; - for (const list of [usedExports, unusedExports]) { - for (const exportInfo of list) { - let name; - do { - name = numberToIdentifier(i++); - } while (usedNames.has(name)); - exportInfo.setUsedName(name); - } - } + + serialize(context) { + const { write } = context; + write(this.identifier); + write(this.path); + super.serialize(context); } -}; -class MangleExportsPlugin { - /** - * @param {boolean} deterministic use deterministic names - */ - constructor(deterministic) { - this._deterministic = deterministic; + deserialize(context) { + const { read } = context; + this.identifier = read(); + this.path = read(); + super.deserialize(context); } +} + +makeSerializable( + ProvidedDependency, + "webpack/lib/dependencies/ProvidedDependency" +); + +class ProvidedDependencyTemplate extends ModuleDependency.Template { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - const { _deterministic: deterministic } = this; - compiler.hooks.compilation.tap("MangleExportsPlugin", compilation => { - const moduleGraph = compilation.moduleGraph; - compilation.hooks.optimizeCodeGeneration.tap( - "MangleExportsPlugin", - modules => { - if (compilation.moduleMemCaches) { - throw new Error( - "optimization.mangleExports can't be used with cacheUnaffected as export mangling is a global effect" - ); - } - for (const module of modules) { - const isNamespace = - module.buildMeta && module.buildMeta.exportsType === "namespace"; - const exportsInfo = moduleGraph.getExportsInfo(module); - mangleExportsInfo(deterministic, exportsInfo, isNamespace); - } - } - ); - }); + apply( + dependency, + source, + { + runtimeTemplate, + moduleGraph, + chunkGraph, + initFragments, + runtimeRequirements + } + ) { + const dep = /** @type {ProvidedDependency} */ (dependency); + initFragments.push( + new InitFragment( + `/* provided dependency */ var ${ + dep.identifier + } = ${runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + runtimeRequirements + })}${pathToString(dep.path)};\n`, + InitFragment.STAGE_PROVIDES, + 1, + `provided ${dep.identifier}` + ) + ); + source.replace(dep.range[0], dep.range[1] - 1, dep.identifier); } } -module.exports = MangleExportsPlugin; +ProvidedDependency.Template = ProvidedDependencyTemplate; + +module.exports = ProvidedDependency; /***/ }), -/***/ 85067: +/***/ 55799: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103106,119 +94874,132 @@ module.exports = MangleExportsPlugin; -const { STAGE_BASIC } = __webpack_require__(80057); -const { runtimeEqual } = __webpack_require__(17156); +const { UsageState } = __webpack_require__(63686); +const makeSerializable = __webpack_require__(33032); +const { filterRuntime } = __webpack_require__(17156); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/Hash")} Hash */ -class MergeDuplicateChunksPlugin { +class PureExpressionDependency extends NullDependency { /** - * @param {Compiler} compiler the compiler + * @param {[number, number]} range the source range + */ + constructor(range) { + super(); + this.range = range; + /** @type {Set | false} */ + this.usedByExports = false; + this._hashUpdate = undefined; + } + + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context * @returns {void} */ - apply(compiler) { - compiler.hooks.compilation.tap( - "MergeDuplicateChunksPlugin", - compilation => { - compilation.hooks.optimizeChunks.tap( - { - name: "MergeDuplicateChunksPlugin", - stage: STAGE_BASIC - }, - chunks => { - const { chunkGraph, moduleGraph } = compilation; + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = this.range + ""; + } + hash.update(this._hashUpdate); + } - // remember already tested chunks for performance - const notDuplicates = new Set(); + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } - // for each chunk - for (const chunk of chunks) { - // track a Set of all chunk that could be duplicates - let possibleDuplicates; - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - if (possibleDuplicates === undefined) { - // when possibleDuplicates is not yet set, - // create a new Set from chunks of the current module - // including only chunks with the same number of modules - for (const dup of chunkGraph.getModuleChunksIterable( - module - )) { - if ( - dup !== chunk && - chunkGraph.getNumberOfChunkModules(chunk) === - chunkGraph.getNumberOfChunkModules(dup) && - !notDuplicates.has(dup) - ) { - // delay allocating the new Set until here, reduce memory pressure - if (possibleDuplicates === undefined) { - possibleDuplicates = new Set(); - } - possibleDuplicates.add(dup); - } - } - // when no chunk is possible we can break here - if (possibleDuplicates === undefined) break; - } else { - // validate existing possible duplicates - for (const dup of possibleDuplicates) { - // remove possible duplicate when module is not contained - if (!chunkGraph.isModuleInChunk(module, dup)) { - possibleDuplicates.delete(dup); - } - } - // when all chunks has been removed we can break here - if (possibleDuplicates.size === 0) break; - } - } + serialize(context) { + const { write } = context; + write(this.range); + write(this.usedByExports); + super.serialize(context); + } - // when we found duplicates - if ( - possibleDuplicates !== undefined && - possibleDuplicates.size > 0 - ) { - outer: for (const otherChunk of possibleDuplicates) { - if (otherChunk.hasRuntime() !== chunk.hasRuntime()) continue; - if (chunkGraph.getNumberOfEntryModules(chunk) > 0) continue; - if (chunkGraph.getNumberOfEntryModules(otherChunk) > 0) - continue; - if (!runtimeEqual(chunk.runtime, otherChunk.runtime)) { - for (const module of chunkGraph.getChunkModulesIterable( - chunk - )) { - const exportsInfo = moduleGraph.getExportsInfo(module); - if ( - !exportsInfo.isEquallyUsed( - chunk.runtime, - otherChunk.runtime - ) - ) { - continue outer; - } - } - } - // merge them - if (chunkGraph.canChunksBeIntegrated(chunk, otherChunk)) { - chunkGraph.integrateChunks(chunk, otherChunk); - compilation.chunks.delete(otherChunk); - } - } - } + deserialize(context) { + const { read } = context; + this.range = read(); + this.usedByExports = read(); + super.deserialize(context); + } +} - // don't check already processed chunks twice - notDuplicates.add(chunk); - } +makeSerializable( + PureExpressionDependency, + "webpack/lib/dependencies/PureExpressionDependency" +); + +PureExpressionDependency.Template = class PureExpressionDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, + { chunkGraph, moduleGraph, runtime, runtimeTemplate, runtimeRequirements } + ) { + const dep = /** @type {PureExpressionDependency} */ (dependency); + + const usedByExports = dep.usedByExports; + if (usedByExports !== false) { + const selfModule = moduleGraph.getParentModule(dep); + const exportsInfo = moduleGraph.getExportsInfo(selfModule); + const runtimeCondition = filterRuntime(runtime, runtime => { + for (const exportName of usedByExports) { + if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) { + return true; } + } + return false; + }); + if (runtimeCondition === true) return; + if (runtimeCondition !== false) { + const condition = runtimeTemplate.runtimeConditionExpression({ + chunkGraph, + runtime, + runtimeCondition, + runtimeRequirements + }); + source.insert( + dep.range[0], + `(/* runtime-dependent pure expression or super */ ${condition} ? (` ); + source.insert(dep.range[1], ") : null)"); + return; } + } + + source.insert( + dep.range[0], + `(/* unused pure expression or super */ null && (` ); + source.insert(dep.range[1], "))"); } -} -module.exports = MergeDuplicateChunksPlugin; +}; + +module.exports = PureExpressionDependency; /***/ }), -/***/ 53912: +/***/ 46917: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103229,117 +95010,51 @@ module.exports = MergeDuplicateChunksPlugin; -const { STAGE_ADVANCED } = __webpack_require__(80057); -const createSchemaValidation = __webpack_require__(32540); +const makeSerializable = __webpack_require__(33032); +const ContextDependency = __webpack_require__(88101); +const ModuleDependencyTemplateAsRequireId = __webpack_require__(36873); -/** @typedef {import("../../declarations/plugins/optimize/MinChunkSizePlugin").MinChunkSizePluginOptions} MinChunkSizePluginOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ +class RequireContextDependency extends ContextDependency { + constructor(options, range) { + super(options); -const validate = createSchemaValidation( - __webpack_require__(60135), - () => __webpack_require__(53850), - { - name: "Min Chunk Size Plugin", - baseDataPath: "options" + this.range = range; } -); -class MinChunkSizePlugin { - /** - * @param {MinChunkSizePluginOptions} options options object - */ - constructor(options) { - validate(options); - this.options = options; + get type() { + return "require.context"; } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const options = this.options; - const minChunkSize = options.minChunkSize; - compiler.hooks.compilation.tap("MinChunkSizePlugin", compilation => { - compilation.hooks.optimizeChunks.tap( - { - name: "MinChunkSizePlugin", - stage: STAGE_ADVANCED - }, - chunks => { - const chunkGraph = compilation.chunkGraph; - const equalOptions = { - chunkOverhead: 1, - entryChunkMultiplicator: 1 - }; + serialize(context) { + const { write } = context; - const chunkSizesMap = new Map(); - /** @type {[Chunk, Chunk][]} */ - const combinations = []; - /** @type {Chunk[]} */ - const smallChunks = []; - const visitedChunks = []; - for (const a of chunks) { - // check if one of the chunks sizes is smaller than the minChunkSize - // and filter pairs that can NOT be integrated! - if (chunkGraph.getChunkSize(a, equalOptions) < minChunkSize) { - smallChunks.push(a); - for (const b of visitedChunks) { - if (chunkGraph.canChunksBeIntegrated(b, a)) - combinations.push([b, a]); - } - } else { - for (const b of smallChunks) { - if (chunkGraph.canChunksBeIntegrated(b, a)) - combinations.push([b, a]); - } - } - chunkSizesMap.set(a, chunkGraph.getChunkSize(a, options)); - visitedChunks.push(a); - } + write(this.range); - const sortedSizeFilteredExtendedPairCombinations = combinations - .map(pair => { - // extend combination pairs with size and integrated size - const a = chunkSizesMap.get(pair[0]); - const b = chunkSizesMap.get(pair[1]); - const ab = chunkGraph.getIntegratedChunksSize( - pair[0], - pair[1], - options - ); - /** @type {[number, number, Chunk, Chunk]} */ - const extendedPair = [a + b - ab, ab, pair[0], pair[1]]; - return extendedPair; - }) - .sort((a, b) => { - // sadly javascript does an in place sort here - // sort by size - const diff = b[0] - a[0]; - if (diff !== 0) return diff; - return a[1] - b[1]; - }); + super.serialize(context); + } - if (sortedSizeFilteredExtendedPairCombinations.length === 0) return; + deserialize(context) { + const { read } = context; - const pair = sortedSizeFilteredExtendedPairCombinations[0]; + this.range = read(); - chunkGraph.integrateChunks(pair[2], pair[3]); - compilation.chunks.delete(pair[3]); - return true; - } - ); - }); + super.deserialize(context); } } -module.exports = MinChunkSizePlugin; + +makeSerializable( + RequireContextDependency, + "webpack/lib/dependencies/RequireContextDependency" +); + +RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; + +module.exports = RequireContextDependency; /***/ }), -/***/ 85305: +/***/ 18851: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103350,34 +95065,62 @@ module.exports = MinChunkSizePlugin; -const SizeFormatHelpers = __webpack_require__(71070); -const WebpackError = __webpack_require__(53799); +const RequireContextDependency = __webpack_require__(46917); -class MinMaxSizeWarning extends WebpackError { - constructor(keys, minSize, maxSize) { - let keysMessage = "Fallback cache group"; - if (keys) { - keysMessage = - keys.length > 1 - ? `Cache groups ${keys.sort().join(", ")}` - : `Cache group ${keys[0]}`; - } - super( - `SplitChunksPlugin\n` + - `${keysMessage}\n` + - `Configured minSize (${SizeFormatHelpers.formatSize(minSize)}) is ` + - `bigger than maxSize (${SizeFormatHelpers.formatSize(maxSize)}).\n` + - "This seem to be a invalid optimization.splitChunks configuration." - ); +module.exports = class RequireContextDependencyParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.context") + .tap("RequireContextDependencyParserPlugin", expr => { + let regExp = /^\.\/.*$/; + let recursive = true; + let mode = "sync"; + switch (expr.arguments.length) { + case 4: { + const modeExpr = parser.evaluateExpression(expr.arguments[3]); + if (!modeExpr.isString()) return; + mode = modeExpr.string; + } + // falls through + case 3: { + const regExpExpr = parser.evaluateExpression(expr.arguments[2]); + if (!regExpExpr.isRegExp()) return; + regExp = regExpExpr.regExp; + } + // falls through + case 2: { + const recursiveExpr = parser.evaluateExpression(expr.arguments[1]); + if (!recursiveExpr.isBoolean()) return; + recursive = recursiveExpr.bool; + } + // falls through + case 1: { + const requestExpr = parser.evaluateExpression(expr.arguments[0]); + if (!requestExpr.isString()) return; + const dep = new RequireContextDependency( + { + request: requestExpr.string, + recursive, + regExp, + mode, + category: "commonjs" + }, + expr.range + ); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + }); } -} - -module.exports = MinMaxSizeWarning; +}; /***/ }), -/***/ 74844: +/***/ 2928: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103388,870 +95131,422 @@ module.exports = MinMaxSizeWarning; -const asyncLib = __webpack_require__(78175); -const ChunkGraph = __webpack_require__(64971); -const ModuleGraph = __webpack_require__(99988); -const { STAGE_DEFAULT } = __webpack_require__(80057); -const HarmonyImportDependency = __webpack_require__(57154); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const { - intersectRuntime, - mergeRuntimeOwned, - filterRuntime, - runtimeToString, - mergeRuntime -} = __webpack_require__(17156); -const ConcatenatedModule = __webpack_require__(97198); +const { cachedSetProperty } = __webpack_require__(60839); +const ContextElementDependency = __webpack_require__(58477); +const RequireContextDependency = __webpack_require__(46917); +const RequireContextDependencyParserPlugin = __webpack_require__(18851); -/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ /** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -/** - * @typedef {Object} Statistics - * @property {number} cached - * @property {number} alreadyInConfig - * @property {number} invalidModule - * @property {number} incorrectChunks - * @property {number} incorrectDependency - * @property {number} incorrectModuleDependency - * @property {number} incorrectChunksOfImporter - * @property {number} incorrectRuntimeCondition - * @property {number} importerFailed - * @property {number} added - */ - -const formatBailoutReason = msg => { - return "ModuleConcatenation bailout: " + msg; -}; -class ModuleConcatenationPlugin { - constructor(options) { - if (typeof options !== "object") options = {}; - this.options = options; - } +/** @type {ResolveOptions} */ +const EMPTY_RESOLVE_OPTIONS = {}; +class RequireContextPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - const { _backCompat: backCompat } = compiler; - compiler.hooks.compilation.tap("ModuleConcatenationPlugin", compilation => { - const moduleGraph = compilation.moduleGraph; - const bailoutReasonMap = new Map(); - - const setBailoutReason = (module, reason) => { - setInnerBailoutReason(module, reason); - moduleGraph - .getOptimizationBailout(module) - .push( - typeof reason === "function" - ? rs => formatBailoutReason(reason(rs)) - : formatBailoutReason(reason) - ); - }; + compiler.hooks.compilation.tap( + "RequireContextPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireContextDependency, + new RequireContextDependency.Template() + ); - const setInnerBailoutReason = (module, reason) => { - bailoutReasonMap.set(module, reason); - }; + compilation.dependencyFactories.set( + ContextElementDependency, + normalModuleFactory + ); - const getInnerBailoutReason = (module, requestShortener) => { - const reason = bailoutReasonMap.get(module); - if (typeof reason === "function") return reason(requestShortener); - return reason; - }; + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireContext !== undefined && + !parserOptions.requireContext + ) + return; - const formatBailoutWarning = (module, problem) => requestShortener => { - if (typeof problem === "function") { - return formatBailoutReason( - `Cannot concat with ${module.readableIdentifier( - requestShortener - )}: ${problem(requestShortener)}` - ); - } - const reason = getInnerBailoutReason(module, requestShortener); - const reasonWithPrefix = reason ? `: ${reason}` : ""; - if (module === problem) { - return formatBailoutReason( - `Cannot concat with ${module.readableIdentifier( - requestShortener - )}${reasonWithPrefix}` - ); - } else { - return formatBailoutReason( - `Cannot concat with ${module.readableIdentifier( - requestShortener - )} because of ${problem.readableIdentifier( - requestShortener - )}${reasonWithPrefix}` - ); - } - }; + new RequireContextDependencyParserPlugin().apply(parser); + }; - compilation.hooks.optimizeChunkModules.tapAsync( - { - name: "ModuleConcatenationPlugin", - stage: STAGE_DEFAULT - }, - (allChunks, modules, callback) => { - const logger = compilation.getLogger( - "webpack.ModuleConcatenationPlugin" - ); - const { chunkGraph, moduleGraph } = compilation; - const relevantModules = []; - const possibleInners = new Set(); - const context = { - chunkGraph, - moduleGraph - }; - logger.time("select relevant modules"); - for (const module of modules) { - let canBeRoot = true; - let canBeInner = true; - - const bailoutReason = module.getConcatenationBailoutReason(context); - if (bailoutReason) { - setBailoutReason(module, bailoutReason); - continue; - } - - // Must not be an async module - if (moduleGraph.isAsync(module)) { - setBailoutReason(module, `Module is async`); - continue; - } - - // Must be in strict mode - if (!module.buildInfo.strict) { - setBailoutReason(module, `Module is not in strict mode`); - continue; - } + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireContextPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireContextPlugin", handler); - // Module must be in any chunk (we don't want to do useless work) - if (chunkGraph.getNumberOfModuleChunks(module) === 0) { - setBailoutReason(module, "Module is not in any chunk"); - continue; - } + contextModuleFactory.hooks.alternativeRequests.tap( + "RequireContextPlugin", + (items, options) => { + if (items.length === 0) return items; - // Exports must be known (and not dynamic) - const exportsInfo = moduleGraph.getExportsInfo(module); - const relevantExports = exportsInfo.getRelevantExports(undefined); - const unknownReexports = relevantExports.filter(exportInfo => { - return ( - exportInfo.isReexport() && !exportInfo.getTarget(moduleGraph) - ); - }); - if (unknownReexports.length > 0) { - setBailoutReason( - module, - `Reexports in this module do not have a static target (${Array.from( - unknownReexports, - exportInfo => - `${ - exportInfo.name || "other exports" - }: ${exportInfo.getUsedInfo()}` - ).join(", ")})` - ); - continue; - } + const finalResolveOptions = compiler.resolverFactory.get( + "normal", + cachedSetProperty( + options.resolveOptions || EMPTY_RESOLVE_OPTIONS, + "dependencyType", + options.category + ) + ).options; - // Root modules must have a static list of exports - const unknownProvidedExports = relevantExports.filter( - exportInfo => { - return exportInfo.provided !== true; + let newItems; + if (!finalResolveOptions.fullySpecified) { + newItems = []; + for (const item of items) { + const { request, context } = item; + for (const ext of finalResolveOptions.extensions) { + if (request.endsWith(ext)) { + newItems.push({ + context, + request: request.slice(0, -ext.length) + }); + } + } + if (!finalResolveOptions.enforceExtension) { + newItems.push(item); + } } - ); - if (unknownProvidedExports.length > 0) { - setBailoutReason( - module, - `List of module exports is dynamic (${Array.from( - unknownProvidedExports, - exportInfo => - `${ - exportInfo.name || "other exports" - }: ${exportInfo.getProvidedInfo()} and ${exportInfo.getUsedInfo()}` - ).join(", ")})` - ); - canBeRoot = false; - } - - // Module must not be an entry point - if (chunkGraph.isEntryModule(module)) { - setInnerBailoutReason(module, "Module is an entry point"); - canBeInner = false; - } - - if (canBeRoot) relevantModules.push(module); - if (canBeInner) possibleInners.add(module); - } - logger.timeEnd("select relevant modules"); - logger.debug( - `${relevantModules.length} potential root modules, ${possibleInners.size} potential inner modules` - ); - // sort by depth - // modules with lower depth are more likely suited as roots - // this improves performance, because modules already selected as inner are skipped - logger.time("sort relevant modules"); - relevantModules.sort((a, b) => { - return moduleGraph.getDepth(a) - moduleGraph.getDepth(b); - }); - logger.timeEnd("sort relevant modules"); - - /** @type {Statistics} */ - const stats = { - cached: 0, - alreadyInConfig: 0, - invalidModule: 0, - incorrectChunks: 0, - incorrectDependency: 0, - incorrectModuleDependency: 0, - incorrectChunksOfImporter: 0, - incorrectRuntimeCondition: 0, - importerFailed: 0, - added: 0 - }; - let statsCandidates = 0; - let statsSizeSum = 0; - let statsEmptyConfigurations = 0; - - logger.time("find modules to concatenate"); - const concatConfigurations = []; - const usedAsInner = new Set(); - for (const currentRoot of relevantModules) { - // when used by another configuration as inner: - // the other configuration is better and we can skip this one - // TODO reconsider that when it's only used in a different runtime - if (usedAsInner.has(currentRoot)) continue; - - let chunkRuntime = undefined; - for (const r of chunkGraph.getModuleRuntimes(currentRoot)) { - chunkRuntime = mergeRuntimeOwned(chunkRuntime, r); - } - const exportsInfo = moduleGraph.getExportsInfo(currentRoot); - const filteredRuntime = filterRuntime(chunkRuntime, r => - exportsInfo.isModuleUsed(r) - ); - const activeRuntime = - filteredRuntime === true - ? chunkRuntime - : filteredRuntime === false - ? undefined - : filteredRuntime; - - // create a configuration with the root - const currentConfiguration = new ConcatConfiguration( - currentRoot, - activeRuntime - ); - - // cache failures to add modules - const failureCache = new Map(); - - // potential optional import candidates - /** @type {Set} */ - const candidates = new Set(); - - // try to add all imports - for (const imp of this._getImports( - compilation, - currentRoot, - activeRuntime - )) { - candidates.add(imp); - } + items = newItems; - for (const imp of candidates) { - const impCandidates = new Set(); - const problem = this._tryToAdd( - compilation, - currentConfiguration, - imp, - chunkRuntime, - activeRuntime, - possibleInners, - impCandidates, - failureCache, - chunkGraph, - true, - stats - ); - if (problem) { - failureCache.set(imp, problem); - currentConfiguration.addWarning(imp, problem); - } else { - for (const c of impCandidates) { - candidates.add(c); + newItems = []; + for (const obj of items) { + const { request, context } = obj; + for (const mainFile of finalResolveOptions.mainFiles) { + if (request.endsWith(`/${mainFile}`)) { + newItems.push({ + context, + request: request.slice(0, -mainFile.length) + }); + newItems.push({ + context, + request: request.slice(0, -mainFile.length - 1) + }); + } } + newItems.push(obj); } + items = newItems; } - statsCandidates += candidates.size; - if (!currentConfiguration.isEmpty()) { - const modules = currentConfiguration.getModules(); - statsSizeSum += modules.size; - concatConfigurations.push(currentConfiguration); - for (const module of modules) { - if (module !== currentConfiguration.rootModule) { - usedAsInner.add(module); + + newItems = []; + for (const item of items) { + let hideOriginal = false; + for (const modulesItems of finalResolveOptions.modules) { + if (Array.isArray(modulesItems)) { + for (const dir of modulesItems) { + if (item.request.startsWith(`./${dir}/`)) { + newItems.push({ + context: item.context, + request: item.request.slice(dir.length + 3) + }); + hideOriginal = true; + } + } + } else { + const dir = modulesItems.replace(/\\/g, "/"); + const fullPath = + item.context.replace(/\\/g, "/") + item.request.slice(1); + if (fullPath.startsWith(dir)) { + newItems.push({ + context: item.context, + request: fullPath.slice(dir.length + 1) + }); + } } } - } else { - statsEmptyConfigurations++; - const optimizationBailouts = - moduleGraph.getOptimizationBailout(currentRoot); - for (const warning of currentConfiguration.getWarningsSorted()) { - optimizationBailouts.push( - formatBailoutWarning(warning[0], warning[1]) - ); + if (!hideOriginal) { + newItems.push(item); } } + return newItems; } - logger.timeEnd("find modules to concatenate"); - logger.debug( - `${ - concatConfigurations.length - } successful concat configurations (avg size: ${ - statsSizeSum / concatConfigurations.length - }), ${statsEmptyConfigurations} bailed out completely` - ); - logger.debug( - `${statsCandidates} candidates were considered for adding (${stats.cached} cached failure, ${stats.alreadyInConfig} already in config, ${stats.invalidModule} invalid module, ${stats.incorrectChunks} incorrect chunks, ${stats.incorrectDependency} incorrect dependency, ${stats.incorrectChunksOfImporter} incorrect chunks of importer, ${stats.incorrectModuleDependency} incorrect module dependency, ${stats.incorrectRuntimeCondition} incorrect runtime condition, ${stats.importerFailed} importer failed, ${stats.added} added)` - ); - // HACK: Sort configurations by length and start with the longest one - // to get the biggest groups possible. Used modules are marked with usedModules - // TODO: Allow to reuse existing configuration while trying to add dependencies. - // This would improve performance. O(n^2) -> O(n) - logger.time(`sort concat configurations`); - concatConfigurations.sort((a, b) => { - return b.modules.size - a.modules.size; - }); - logger.timeEnd(`sort concat configurations`); - const usedModules = new Set(); - - logger.time("create concatenated modules"); - asyncLib.each( - concatConfigurations, - (concatConfiguration, callback) => { - const rootModule = concatConfiguration.rootModule; + ); + } + ); + } +} +module.exports = RequireContextPlugin; - // Avoid overlapping configurations - // TODO: remove this when todo above is fixed - if (usedModules.has(rootModule)) return callback(); - const modules = concatConfiguration.getModules(); - for (const m of modules) { - usedModules.add(m); - } - // Create a new ConcatenatedModule - let newModule = ConcatenatedModule.create( - rootModule, - modules, - concatConfiguration.runtime, - compiler.root, - compilation.outputOptions.hashFunction - ); +/***/ }), - const build = () => { - newModule.build( - compiler.options, - compilation, - null, - null, - err => { - if (err) { - if (!err.module) { - err.module = newModule; - } - return callback(err); - } - integrate(); - } - ); - }; +/***/ 27153: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const integrate = () => { - if (backCompat) { - ChunkGraph.setChunkGraphForModule(newModule, chunkGraph); - ModuleGraph.setModuleGraphForModule(newModule, moduleGraph); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - for (const warning of concatConfiguration.getWarningsSorted()) { - moduleGraph - .getOptimizationBailout(newModule) - .push(formatBailoutWarning(warning[0], warning[1])); - } - moduleGraph.cloneModuleAttributes(rootModule, newModule); - for (const m of modules) { - // add to builtModules when one of the included modules was built - if (compilation.builtModules.has(m)) { - compilation.builtModules.add(newModule); - } - if (m !== rootModule) { - // attach external references to the concatenated module too - moduleGraph.copyOutgoingModuleConnections( - m, - newModule, - c => { - return ( - c.originModule === m && - !( - c.dependency instanceof HarmonyImportDependency && - modules.has(c.module) - ) - ); - } - ); - // remove module from chunk - for (const chunk of chunkGraph.getModuleChunksIterable( - rootModule - )) { - chunkGraph.disconnectChunkAndModule(chunk, m); - } - } - } - compilation.modules.delete(rootModule); - ChunkGraph.clearChunkGraphForModule(rootModule); - ModuleGraph.clearModuleGraphForModule(rootModule); - // remove module from chunk - chunkGraph.replaceModule(rootModule, newModule); - // replace module references with the concatenated module - moduleGraph.moveModuleConnections(rootModule, newModule, c => { - const otherModule = - c.module === rootModule ? c.originModule : c.module; - const innerConnection = - c.dependency instanceof HarmonyImportDependency && - modules.has(otherModule); - return !innerConnection; - }); - // add concatenated module to the compilation - compilation.modules.add(newModule); - callback(); - }; +const AsyncDependenciesBlock = __webpack_require__(47736); +const makeSerializable = __webpack_require__(33032); - build(); - }, - err => { - logger.timeEnd("create concatenated modules"); - process.nextTick(callback.bind(null, err)); - } - ); - } - ); - }); +class RequireEnsureDependenciesBlock extends AsyncDependenciesBlock { + constructor(chunkName, loc) { + super(chunkName, loc, null); } +} - /** - * @param {Compilation} compilation the compilation - * @param {Module} module the module to be added - * @param {RuntimeSpec} runtime the runtime scope - * @returns {Set} the imported modules - */ - _getImports(compilation, module, runtime) { - const moduleGraph = compilation.moduleGraph; - const set = new Set(); - for (const dep of module.dependencies) { - // Get reference info only for harmony Dependencies - if (!(dep instanceof HarmonyImportDependency)) continue; +makeSerializable( + RequireEnsureDependenciesBlock, + "webpack/lib/dependencies/RequireEnsureDependenciesBlock" +); - const connection = moduleGraph.getConnection(dep); - // Reference is valid and has a module - if ( - !connection || - !connection.module || - !connection.isTargetActive(runtime) - ) { - continue; - } +module.exports = RequireEnsureDependenciesBlock; - const importedNames = compilation.getDependencyReferencedExports( - dep, - undefined - ); - if ( - importedNames.every(i => - Array.isArray(i) ? i.length > 0 : i.name.length > 0 - ) || - Array.isArray(moduleGraph.getProvidedExports(module)) - ) { - set.add(connection.module); - } - } - return set; - } +/***/ }), - /** - * @param {Compilation} compilation webpack compilation - * @param {ConcatConfiguration} config concat configuration (will be modified when added) - * @param {Module} module the module to be added - * @param {RuntimeSpec} runtime the runtime scope of the generated code - * @param {RuntimeSpec} activeRuntime the runtime scope of the root module - * @param {Set} possibleModules modules that are candidates - * @param {Set} candidates list of potential candidates (will be added to) - * @param {Map} failureCache cache for problematic modules to be more performant - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {boolean} avoidMutateOnFailure avoid mutating the config when adding fails - * @param {Statistics} statistics gathering metrics - * @returns {Module | function(RequestShortener): string} the problematic module - */ - _tryToAdd( - compilation, - config, - module, - runtime, - activeRuntime, - possibleModules, - candidates, - failureCache, - chunkGraph, - avoidMutateOnFailure, - statistics - ) { - const cacheEntry = failureCache.get(module); - if (cacheEntry) { - statistics.cached++; - return cacheEntry; - } +/***/ 7235: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Already added? - if (config.has(module)) { - statistics.alreadyInConfig++; - return null; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Not possible to add? - if (!possibleModules.has(module)) { - statistics.invalidModule++; - failureCache.set(module, module); // cache failures for performance - return module; - } - // Module must be in the correct chunks - const missingChunks = Array.from( - chunkGraph.getModuleChunksIterable(config.rootModule) - ).filter(chunk => !chunkGraph.isModuleInChunk(module, chunk)); - if (missingChunks.length > 0) { - const problem = requestShortener => { - const missingChunksList = Array.from( - new Set(missingChunks.map(chunk => chunk.name || "unnamed chunk(s)")) - ).sort(); - const chunks = Array.from( - new Set( - Array.from(chunkGraph.getModuleChunksIterable(module)).map( - chunk => chunk.name || "unnamed chunk(s)" - ) - ) - ).sort(); - return `Module ${module.readableIdentifier( - requestShortener - )} is not in the same chunk(s) (expected in chunk(s) ${missingChunksList.join( - ", " - )}, module is in chunk(s) ${chunks.join(", ")})`; - }; - statistics.incorrectChunks++; - failureCache.set(module, problem); // cache failures for performance - return problem; - } - const moduleGraph = compilation.moduleGraph; +const RequireEnsureDependenciesBlock = __webpack_require__(27153); +const RequireEnsureDependency = __webpack_require__(27223); +const RequireEnsureItemDependency = __webpack_require__(50329); +const getFunctionExpression = __webpack_require__(50396); - const incomingConnections = - moduleGraph.getIncomingConnectionsByOriginModule(module); +module.exports = class RequireEnsureDependenciesBlockParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.ensure") + .tap("RequireEnsureDependenciesBlockParserPlugin", expr => { + let chunkName = null; + let errorExpressionArg = null; + let errorExpression = null; + switch (expr.arguments.length) { + case 4: { + const chunkNameExpr = parser.evaluateExpression(expr.arguments[3]); + if (!chunkNameExpr.isString()) return; + chunkName = chunkNameExpr.string; + } + // falls through + case 3: { + errorExpressionArg = expr.arguments[2]; + errorExpression = getFunctionExpression(errorExpressionArg); - const incomingConnectionsFromNonModules = - incomingConnections.get(null) || incomingConnections.get(undefined); - if (incomingConnectionsFromNonModules) { - const activeNonModulesConnections = - incomingConnectionsFromNonModules.filter(connection => { - // We are not interested in inactive connections - // or connections without dependency - return connection.isActive(runtime) || connection.dependency; - }); - if (activeNonModulesConnections.length > 0) { - const problem = requestShortener => { - const importingExplanations = new Set( - activeNonModulesConnections.map(c => c.explanation).filter(Boolean) - ); - const explanations = Array.from(importingExplanations).sort(); - return `Module ${module.readableIdentifier( - requestShortener - )} is referenced ${ - explanations.length > 0 - ? `by: ${explanations.join(", ")}` - : "in an unsupported way" - }`; - }; - statistics.incorrectDependency++; - failureCache.set(module, problem); // cache failures for performance - return problem; - } - } + if (!errorExpression && !chunkName) { + const chunkNameExpr = parser.evaluateExpression( + expr.arguments[2] + ); + if (!chunkNameExpr.isString()) return; + chunkName = chunkNameExpr.string; + } + } + // falls through + case 2: { + const dependenciesExpr = parser.evaluateExpression( + expr.arguments[0] + ); + const dependenciesItems = dependenciesExpr.isArray() + ? dependenciesExpr.items + : [dependenciesExpr]; + const successExpressionArg = expr.arguments[1]; + const successExpression = + getFunctionExpression(successExpressionArg); - /** @type {Map} */ - const incomingConnectionsFromModules = new Map(); - for (const [originModule, connections] of incomingConnections) { - if (originModule) { - // Ignore connection from orphan modules - if (chunkGraph.getNumberOfModuleChunks(originModule) === 0) continue; + if (successExpression) { + parser.walkExpressions(successExpression.expressions); + } + if (errorExpression) { + parser.walkExpressions(errorExpression.expressions); + } - // We don't care for connections from other runtimes - let originRuntime = undefined; - for (const r of chunkGraph.getModuleRuntimes(originModule)) { - originRuntime = mergeRuntimeOwned(originRuntime, r); + const depBlock = new RequireEnsureDependenciesBlock( + chunkName, + expr.loc + ); + const errorCallbackExists = + expr.arguments.length === 4 || + (!chunkName && expr.arguments.length === 3); + const dep = new RequireEnsureDependency( + expr.range, + expr.arguments[1].range, + errorCallbackExists && expr.arguments[2].range + ); + dep.loc = expr.loc; + depBlock.addDependency(dep); + const old = parser.state.current; + parser.state.current = depBlock; + try { + let failed = false; + parser.inScope([], () => { + for (const ee of dependenciesItems) { + if (ee.isString()) { + const ensureDependency = new RequireEnsureItemDependency( + ee.string + ); + ensureDependency.loc = ee.loc || expr.loc; + depBlock.addDependency(ensureDependency); + } else { + failed = true; + } + } + }); + if (failed) { + return; + } + if (successExpression) { + if (successExpression.fn.body.type === "BlockStatement") { + parser.walkStatement(successExpression.fn.body); + } else { + parser.walkExpression(successExpression.fn.body); + } + } + old.addBlock(depBlock); + } finally { + parser.state.current = old; + } + if (!successExpression) { + parser.walkExpression(successExpressionArg); + } + if (errorExpression) { + if (errorExpression.fn.body.type === "BlockStatement") { + parser.walkStatement(errorExpression.fn.body); + } else { + parser.walkExpression(errorExpression.fn.body); + } + } else if (errorExpressionArg) { + parser.walkExpression(errorExpressionArg); + } + return true; + } } + }); + } +}; - if (!intersectRuntime(runtime, originRuntime)) continue; - - // We are not interested in inactive connections - const activeConnections = connections.filter(connection => - connection.isActive(runtime) - ); - if (activeConnections.length > 0) - incomingConnectionsFromModules.set(originModule, activeConnections); - } - } - const incomingModules = Array.from(incomingConnectionsFromModules.keys()); +/***/ }), - // Module must be in the same chunks like the referencing module - const otherChunkModules = incomingModules.filter(originModule => { - for (const chunk of chunkGraph.getModuleChunksIterable( - config.rootModule - )) { - if (!chunkGraph.isModuleInChunk(originModule, chunk)) { - return true; - } - } - return false; - }); - if (otherChunkModules.length > 0) { - const problem = requestShortener => { - const names = otherChunkModules - .map(m => m.readableIdentifier(requestShortener)) - .sort(); - return `Module ${module.readableIdentifier( - requestShortener - )} is referenced from different chunks by these modules: ${names.join( - ", " - )}`; - }; - statistics.incorrectChunksOfImporter++; - failureCache.set(module, problem); // cache failures for performance - return problem; - } +/***/ 27223: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {Map} */ - const nonHarmonyConnections = new Map(); - for (const [originModule, connections] of incomingConnectionsFromModules) { - const selected = connections.filter( - connection => - !connection.dependency || - !(connection.dependency instanceof HarmonyImportDependency) - ); - if (selected.length > 0) - nonHarmonyConnections.set(originModule, connections); - } - if (nonHarmonyConnections.size > 0) { - const problem = requestShortener => { - const names = Array.from(nonHarmonyConnections) - .map(([originModule, connections]) => { - return `${originModule.readableIdentifier( - requestShortener - )} (referenced with ${Array.from( - new Set( - connections - .map(c => c.dependency && c.dependency.type) - .filter(Boolean) - ) - ) - .sort() - .join(", ")})`; - }) - .sort(); - return `Module ${module.readableIdentifier( - requestShortener - )} is referenced from these modules with unsupported syntax: ${names.join( - ", " - )}`; - }; - statistics.incorrectModuleDependency++; - failureCache.set(module, problem); // cache failures for performance - return problem; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (runtime !== undefined && typeof runtime !== "string") { - // Module must be consistently referenced in the same runtimes - /** @type {{ originModule: Module, runtimeCondition: RuntimeSpec }[]} */ - const otherRuntimeConnections = []; - outer: for (const [ - originModule, - connections - ] of incomingConnectionsFromModules) { - /** @type {false | RuntimeSpec} */ - let currentRuntimeCondition = false; - for (const connection of connections) { - const runtimeCondition = filterRuntime(runtime, runtime => { - return connection.isTargetActive(runtime); - }); - if (runtimeCondition === false) continue; - if (runtimeCondition === true) continue outer; - if (currentRuntimeCondition !== false) { - currentRuntimeCondition = mergeRuntime( - currentRuntimeCondition, - runtimeCondition - ); - } else { - currentRuntimeCondition = runtimeCondition; - } - } - if (currentRuntimeCondition !== false) { - otherRuntimeConnections.push({ - originModule, - runtimeCondition: currentRuntimeCondition - }); - } - } - if (otherRuntimeConnections.length > 0) { - const problem = requestShortener => { - return `Module ${module.readableIdentifier( - requestShortener - )} is runtime-dependent referenced by these modules: ${Array.from( - otherRuntimeConnections, - ({ originModule, runtimeCondition }) => - `${originModule.readableIdentifier( - requestShortener - )} (expected runtime ${runtimeToString( - runtime - )}, module is only referenced in ${runtimeToString( - /** @type {RuntimeSpec} */ (runtimeCondition) - )})` - ).join(", ")}`; - }; - statistics.incorrectRuntimeCondition++; - failureCache.set(module, problem); // cache failures for performance - return problem; - } - } - let backup; - if (avoidMutateOnFailure) { - backup = config.snapshot(); - } - // Add the module - config.add(module); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); - incomingModules.sort(compareModulesByIdentifier); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - // Every module which depends on the added module must be in the configuration too. - for (const originModule of incomingModules) { - const problem = this._tryToAdd( - compilation, - config, - originModule, - runtime, - activeRuntime, - possibleModules, - candidates, - failureCache, - chunkGraph, - false, - statistics - ); - if (problem) { - if (backup !== undefined) config.rollback(backup); - statistics.importerFailed++; - failureCache.set(module, problem); // cache failures for performance - return problem; - } - } +class RequireEnsureDependency extends NullDependency { + constructor(range, contentRange, errorHandlerRange) { + super(); - // Add imports to possible candidates list - for (const imp of this._getImports(compilation, module, runtime)) { - candidates.add(imp); - } - statistics.added++; - return null; + this.range = range; + this.contentRange = contentRange; + this.errorHandlerRange = errorHandlerRange; } -} -class ConcatConfiguration { - /** - * @param {Module} rootModule the root module - * @param {RuntimeSpec} runtime the runtime - */ - constructor(rootModule, runtime) { - this.rootModule = rootModule; - this.runtime = runtime; - /** @type {Set} */ - this.modules = new Set(); - this.modules.add(rootModule); - /** @type {Map} */ - this.warnings = new Map(); + get type() { + return "require.ensure"; } - add(module) { - this.modules.add(module); - } + serialize(context) { + const { write } = context; - has(module) { - return this.modules.has(module); - } + write(this.range); + write(this.contentRange); + write(this.errorHandlerRange); - isEmpty() { - return this.modules.size === 1; + super.serialize(context); } - addWarning(module, problem) { - this.warnings.set(module, problem); - } + deserialize(context) { + const { read } = context; - getWarningsSorted() { - return new Map( - Array.from(this.warnings).sort((a, b) => { - const ai = a[0].identifier(); - const bi = b[0].identifier(); - if (ai < bi) return -1; - if (ai > bi) return 1; - return 0; - }) - ); - } + this.range = read(); + this.contentRange = read(); + this.errorHandlerRange = read(); - /** - * @returns {Set} modules as set - */ - getModules() { - return this.modules; + super.deserialize(context); } +} - snapshot() { - return this.modules.size; - } +makeSerializable( + RequireEnsureDependency, + "webpack/lib/dependencies/RequireEnsureDependency" +); - rollback(snapshot) { - const modules = this.modules; - for (const m of modules) { - if (snapshot === 0) { - modules.delete(m); - } else { - snapshot--; - } +RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {RequireEnsureDependency} */ (dependency); + const depBlock = /** @type {AsyncDependenciesBlock} */ ( + moduleGraph.getParentBlock(dep) + ); + const promise = runtimeTemplate.blockPromise({ + chunkGraph, + block: depBlock, + message: "require.ensure", + runtimeRequirements + }); + const range = dep.range; + const contentRange = dep.contentRange; + const errorHandlerRange = dep.errorHandlerRange; + source.replace(range[0], contentRange[0] - 1, `${promise}.then((`); + if (errorHandlerRange) { + source.replace( + contentRange[1], + errorHandlerRange[0] - 1, + ").bind(null, __webpack_require__))['catch'](" + ); + source.replace(errorHandlerRange[1], range[1] - 1, ")"); + } else { + source.replace( + contentRange[1], + range[1] - 1, + `).bind(null, __webpack_require__))['catch'](${RuntimeGlobals.uncaughtErrorHandler})` + ); } } -} +}; -module.exports = ModuleConcatenationPlugin; +module.exports = RequireEnsureDependency; /***/ }), -/***/ 46043: +/***/ 50329: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -104262,412 +95557,343 @@ module.exports = ModuleConcatenationPlugin; -const { SyncBailHook } = __webpack_require__(6967); -const { RawSource, CachedSource, CompatSource } = __webpack_require__(51255); -const Compilation = __webpack_require__(85720); -const WebpackError = __webpack_require__(53799); -const { compareSelect, compareStrings } = __webpack_require__(29579); -const createHash = __webpack_require__(49835); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("../Compiler")} Compiler */ +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const NullDependency = __webpack_require__(31830); -const EMPTY_SET = new Set(); +class RequireEnsureItemDependency extends ModuleDependency { + constructor(request) { + super(request); + } -const addToList = (itemOrItems, list) => { - if (Array.isArray(itemOrItems)) { - for (const item of itemOrItems) { - list.add(item); - } - } else if (itemOrItems) { - list.add(itemOrItems); + get type() { + return "require.ensure item"; } -}; -/** - * @template T - * @param {T[]} input list - * @param {function(T): Buffer} fn map function - * @returns {Buffer[]} buffers without duplicates - */ -const mapAndDeduplicateBuffers = (input, fn) => { - // Buffer.equals compares size first so this should be efficient enough - // If it becomes a performance problem we can use a map and group by size - // instead of looping over all assets. - const result = []; - outer: for (const value of input) { - const buf = fn(value); - for (const other of result) { - if (buf.equals(other)) continue outer; - } - result.push(buf); + get category() { + return "commonjs"; } - return result; -}; +} -/** - * Escapes regular expression metacharacters - * @param {string} str String to quote - * @returns {string} Escaped string - */ -const quoteMeta = str => { - return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); -}; +makeSerializable( + RequireEnsureItemDependency, + "webpack/lib/dependencies/RequireEnsureItemDependency" +); -const cachedSourceMap = new WeakMap(); +RequireEnsureItemDependency.Template = NullDependency.Template; -const toCachedSource = source => { - if (source instanceof CachedSource) { - return source; +module.exports = RequireEnsureItemDependency; + + +/***/ }), + +/***/ 8434: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RequireEnsureDependency = __webpack_require__(27223); +const RequireEnsureItemDependency = __webpack_require__(50329); + +const RequireEnsureDependenciesBlockParserPlugin = __webpack_require__(7235); + +const { + evaluateToString, + toConstantDependency +} = __webpack_require__(93998); + +class RequireEnsurePlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireEnsurePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireEnsureItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireEnsureItemDependency, + new RequireEnsureItemDependency.Template() + ); + + compilation.dependencyTemplates.set( + RequireEnsureDependency, + new RequireEnsureDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireEnsure !== undefined && + !parserOptions.requireEnsure + ) + return; + + new RequireEnsureDependenciesBlockParserPlugin().apply(parser); + parser.hooks.evaluateTypeof + .for("require.ensure") + .tap("RequireEnsurePlugin", evaluateToString("function")); + parser.hooks.typeof + .for("require.ensure") + .tap( + "RequireEnsurePlugin", + toConstantDependency(parser, JSON.stringify("function")) + ); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireEnsurePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireEnsurePlugin", handler); + } + ); + } +} +module.exports = RequireEnsurePlugin; + + +/***/ }), + +/***/ 89183: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + +class RequireHeaderDependency extends NullDependency { + constructor(range) { + super(); + if (!Array.isArray(range)) throw new Error("range must be valid"); + this.range = range; + } + + serialize(context) { + const { write } = context; + write(this.range); + super.serialize(context); + } + + static deserialize(context) { + const obj = new RequireHeaderDependency(context.read()); + obj.deserialize(context); + return obj; + } +} + +makeSerializable( + RequireHeaderDependency, + "webpack/lib/dependencies/RequireHeaderDependency" +); + +RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, { runtimeRequirements }) { + const dep = /** @type {RequireHeaderDependency} */ (dependency); + runtimeRequirements.add(RuntimeGlobals.require); + source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__"); } - const entry = cachedSourceMap.get(source); - if (entry !== undefined) return entry; - const newSource = new CachedSource(CompatSource.from(source)); - cachedSourceMap.set(source, newSource); - return newSource; }; -/** - * @typedef {Object} AssetInfoForRealContentHash - * @property {string} name - * @property {AssetInfo} info - * @property {Source} source - * @property {RawSource | undefined} newSource - * @property {RawSource | undefined} newSourceWithoutOwn - * @property {string} content - * @property {Set} ownHashes - * @property {Promise} contentComputePromise - * @property {Promise} contentComputeWithoutOwnPromise - * @property {Set} referencedHashes - * @property {Set} hashes - */ +module.exports = RequireHeaderDependency; -/** - * @typedef {Object} CompilationHooks - * @property {SyncBailHook<[Buffer[], string], string>} updateHash - */ -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); +/***/ }), + +/***/ 71284: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const Dependency = __webpack_require__(54912); +const Template = __webpack_require__(39722); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class RequireIncludeDependency extends ModuleDependency { + constructor(request, range) { + super(request); + + this.range = range; + } -class RealContentHashPlugin { /** - * @param {Compilation} compilation the compilation - * @returns {CompilationHooks} the attached hooks + * 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 */ - 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 = { - updateHash: new SyncBailHook(["content", "oldHash"]) - }; - compilationHooksMap.set(compilation, hooks); - } - return hooks; + getReferencedExports(moduleGraph, runtime) { + // This doesn't use any export + return Dependency.NO_EXPORTS_REFERENCED; } - constructor({ hashFunction, hashDigest }) { - this._hashFunction = hashFunction; - this._hashDigest = hashDigest; + get type() { + return "require.include"; + } + + get category() { + return "commonjs"; } +} + +makeSerializable( + RequireIncludeDependency, + "webpack/lib/dependencies/RequireIncludeDependency" +); +RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate extends ( + ModuleDependency.Template +) { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - compiler.hooks.compilation.tap("RealContentHashPlugin", compilation => { - const cacheAnalyse = compilation.getCache( - "RealContentHashPlugin|analyse" - ); - const cacheGenerate = compilation.getCache( - "RealContentHashPlugin|generate" - ); - const hooks = RealContentHashPlugin.getCompilationHooks(compilation); - compilation.hooks.processAssets.tapPromise( - { - name: "RealContentHashPlugin", - stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH - }, - async () => { - const assets = compilation.getAssets(); - /** @type {AssetInfoForRealContentHash[]} */ - const assetsWithInfo = []; - const hashToAssets = new Map(); - for (const { source, info, name } of assets) { - const cachedSource = toCachedSource(source); - const content = cachedSource.source(); - /** @type {Set} */ - const hashes = new Set(); - addToList(info.contenthash, hashes); - const data = { - name, - info, - source: cachedSource, - /** @type {RawSource | undefined} */ - newSource: undefined, - /** @type {RawSource | undefined} */ - newSourceWithoutOwn: undefined, - content, - /** @type {Set} */ - ownHashes: undefined, - contentComputePromise: undefined, - contentComputeWithoutOwnPromise: undefined, - /** @type {Set} */ - referencedHashes: undefined, - hashes - }; - assetsWithInfo.push(data); - for (const hash of hashes) { - const list = hashToAssets.get(hash); - if (list === undefined) { - hashToAssets.set(hash, [data]); - } else { - list.push(data); - } - } - } - if (hashToAssets.size === 0) return; - const hashRegExp = new RegExp( - Array.from(hashToAssets.keys(), quoteMeta).join("|"), - "g" - ); - await Promise.all( - assetsWithInfo.map(async asset => { - const { name, source, content, hashes } = asset; - if (Buffer.isBuffer(content)) { - asset.referencedHashes = EMPTY_SET; - asset.ownHashes = EMPTY_SET; - return; - } - const etag = cacheAnalyse.mergeEtags( - cacheAnalyse.getLazyHashedEtag(source), - Array.from(hashes).join("|") - ); - [asset.referencedHashes, asset.ownHashes] = - await cacheAnalyse.providePromise(name, etag, () => { - const referencedHashes = new Set(); - let ownHashes = new Set(); - const inContent = content.match(hashRegExp); - if (inContent) { - for (const hash of inContent) { - if (hashes.has(hash)) { - ownHashes.add(hash); - continue; - } - referencedHashes.add(hash); - } - } - return [referencedHashes, ownHashes]; - }); - }) - ); - const getDependencies = hash => { - const assets = hashToAssets.get(hash); - if (!assets) { - const referencingAssets = assetsWithInfo.filter(asset => - asset.referencedHashes.has(hash) - ); - const err = new WebpackError(`RealContentHashPlugin -Some kind of unexpected caching problem occurred. -An asset was cached with a reference to another asset (${hash}) that's not in the compilation anymore. -Either the asset was incorrectly cached, or the referenced asset should also be restored from cache. -Referenced by: -${referencingAssets - .map(a => { - const match = new RegExp(`.{0,20}${quoteMeta(hash)}.{0,20}`).exec( - a.content - ); - return ` - ${a.name}: ...${match ? match[0] : "???"}...`; - }) - .join("\n")}`); - compilation.errors.push(err); - return undefined; - } - const hashes = new Set(); - for (const { referencedHashes, ownHashes } of assets) { - if (!ownHashes.has(hash)) { - for (const hash of ownHashes) { - hashes.add(hash); - } - } - for (const hash of referencedHashes) { - hashes.add(hash); - } - } - return hashes; - }; - const hashInfo = hash => { - const assets = hashToAssets.get(hash); - return `${hash} (${Array.from(assets, a => a.name)})`; - }; - const hashesInOrder = new Set(); - for (const hash of hashToAssets.keys()) { - const add = (hash, stack) => { - const deps = getDependencies(hash); - if (!deps) return; - stack.add(hash); - for (const dep of deps) { - if (hashesInOrder.has(dep)) continue; - if (stack.has(dep)) { - throw new Error( - `Circular hash dependency ${Array.from( - stack, - hashInfo - ).join(" -> ")} -> ${hashInfo(dep)}` - ); - } - add(dep, stack); - } - hashesInOrder.add(hash); - stack.delete(hash); - }; - if (hashesInOrder.has(hash)) continue; - add(hash, new Set()); - } - const hashToNewHash = new Map(); - const getEtag = asset => - cacheGenerate.mergeEtags( - cacheGenerate.getLazyHashedEtag(asset.source), - Array.from(asset.referencedHashes, hash => - hashToNewHash.get(hash) - ).join("|") - ); - const computeNewContent = asset => { - if (asset.contentComputePromise) return asset.contentComputePromise; - return (asset.contentComputePromise = (async () => { - if ( - asset.ownHashes.size > 0 || - Array.from(asset.referencedHashes).some( - hash => hashToNewHash.get(hash) !== hash - ) - ) { - const identifier = asset.name; - const etag = getEtag(asset); - asset.newSource = await cacheGenerate.providePromise( - identifier, - etag, - () => { - const newContent = asset.content.replace(hashRegExp, hash => - hashToNewHash.get(hash) - ); - return new RawSource(newContent); - } - ); - } - })()); - }; - const computeNewContentWithoutOwn = asset => { - if (asset.contentComputeWithoutOwnPromise) - return asset.contentComputeWithoutOwnPromise; - return (asset.contentComputeWithoutOwnPromise = (async () => { - if ( - asset.ownHashes.size > 0 || - Array.from(asset.referencedHashes).some( - hash => hashToNewHash.get(hash) !== hash - ) - ) { - const identifier = asset.name + "|without-own"; - const etag = getEtag(asset); - asset.newSourceWithoutOwn = await cacheGenerate.providePromise( - identifier, - etag, - () => { - const newContent = asset.content.replace( - hashRegExp, - hash => { - if (asset.ownHashes.has(hash)) { - return ""; - } - return hashToNewHash.get(hash); - } - ); - return new RawSource(newContent); - } - ); - } - })()); - }; - const comparator = compareSelect(a => a.name, compareStrings); - for (const oldHash of hashesInOrder) { - const assets = hashToAssets.get(oldHash); - assets.sort(comparator); - const hash = createHash(this._hashFunction); - await Promise.all( - assets.map(asset => - asset.ownHashes.has(oldHash) - ? computeNewContentWithoutOwn(asset) - : computeNewContent(asset) - ) - ); - const assetsContent = mapAndDeduplicateBuffers(assets, asset => { - if (asset.ownHashes.has(oldHash)) { - return asset.newSourceWithoutOwn - ? asset.newSourceWithoutOwn.buffer() - : asset.source.buffer(); - } else { - return asset.newSource - ? asset.newSource.buffer() - : asset.source.buffer(); - } - }); - let newHash = hooks.updateHash.call(assetsContent, oldHash); - if (!newHash) { - for (const content of assetsContent) { - hash.update(content); - } - const digest = hash.digest(this._hashDigest); - newHash = /** @type {string} */ (digest.slice(0, oldHash.length)); - } - hashToNewHash.set(oldHash, newHash); - } - await Promise.all( - assetsWithInfo.map(async asset => { - await computeNewContent(asset); - const newName = asset.name.replace(hashRegExp, hash => - hashToNewHash.get(hash) - ); + apply(dependency, source, { runtimeTemplate }) { + const dep = /** @type {RequireIncludeDependency} */ (dependency); + const comment = runtimeTemplate.outputOptions.pathinfo + ? Template.toComment( + `require.include ${runtimeTemplate.requestShortener.shorten( + dep.request + )}` + ) + : ""; - const infoUpdate = {}; - const hash = asset.info.contenthash; - infoUpdate.contenthash = Array.isArray(hash) - ? hash.map(hash => hashToNewHash.get(hash)) - : hashToNewHash.get(hash); + source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`); + } +}; - if (asset.newSource !== undefined) { - compilation.updateAsset( - asset.name, - asset.newSource, - infoUpdate - ); - } else { - compilation.updateAsset(asset.name, asset.source, infoUpdate); - } +module.exports = RequireIncludeDependency; - if (asset.name !== newName) { - compilation.renameAsset(asset.name, newName); - } - }) + +/***/ }), + +/***/ 35768: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const WebpackError = __webpack_require__(53799); +const { + evaluateToString, + toConstantDependency +} = __webpack_require__(93998); +const makeSerializable = __webpack_require__(33032); +const RequireIncludeDependency = __webpack_require__(71284); + +module.exports = class RequireIncludeDependencyParserPlugin { + constructor(warn) { + this.warn = warn; + } + apply(parser) { + const { warn } = this; + parser.hooks.call + .for("require.include") + .tap("RequireIncludeDependencyParserPlugin", expr => { + if (expr.arguments.length !== 1) return; + const param = parser.evaluateExpression(expr.arguments[0]); + if (!param.isString()) return; + + if (warn) { + parser.state.module.addWarning( + new RequireIncludeDeprecationWarning(expr.loc) ); } - ); - }); + + const dep = new RequireIncludeDependency(param.string, expr.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }); + parser.hooks.evaluateTypeof + .for("require.include") + .tap("RequireIncludePlugin", expr => { + if (warn) { + parser.state.module.addWarning( + new RequireIncludeDeprecationWarning(expr.loc) + ); + } + return evaluateToString("function")(expr); + }); + parser.hooks.typeof + .for("require.include") + .tap("RequireIncludePlugin", expr => { + if (warn) { + parser.state.module.addWarning( + new RequireIncludeDeprecationWarning(expr.loc) + ); + } + return toConstantDependency(parser, JSON.stringify("function"))(expr); + }); + } +}; + +class RequireIncludeDeprecationWarning extends WebpackError { + constructor(loc) { + super("require.include() is deprecated and will be removed soon."); + + this.name = "RequireIncludeDeprecationWarning"; + + this.loc = loc; } } -module.exports = RealContentHashPlugin; +makeSerializable( + RequireIncludeDeprecationWarning, + "webpack/lib/dependencies/RequireIncludeDependencyParserPlugin", + "RequireIncludeDeprecationWarning" +); /***/ }), -/***/ 84760: +/***/ 37378: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -104678,61 +95904,46 @@ module.exports = RealContentHashPlugin; -const { STAGE_BASIC, STAGE_ADVANCED } = __webpack_require__(80057); - -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ +const RequireIncludeDependency = __webpack_require__(71284); +const RequireIncludeDependencyParserPlugin = __webpack_require__(35768); -class RemoveEmptyChunksPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ +class RequireIncludePlugin { apply(compiler) { - compiler.hooks.compilation.tap("RemoveEmptyChunksPlugin", compilation => { - /** - * @param {Iterable} chunks the chunks array - * @returns {void} - */ - const handler = chunks => { - const chunkGraph = compilation.chunkGraph; - for (const chunk of chunks) { - if ( - chunkGraph.getNumberOfChunkModules(chunk) === 0 && - !chunk.hasRuntime() && - chunkGraph.getNumberOfEntryModules(chunk) === 0 - ) { - compilation.chunkGraph.disconnectChunk(chunk); - compilation.chunks.delete(chunk); - } - } - }; + compiler.hooks.compilation.tap( + "RequireIncludePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireIncludeDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireIncludeDependency, + new RequireIncludeDependency.Template() + ); - // TODO do it once - compilation.hooks.optimizeChunks.tap( - { - name: "RemoveEmptyChunksPlugin", - stage: STAGE_BASIC - }, - handler - ); - compilation.hooks.optimizeChunks.tap( - { - name: "RemoveEmptyChunksPlugin", - stage: STAGE_ADVANCED - }, - handler - ); - }); + const handler = (parser, parserOptions) => { + if (parserOptions.requireInclude === false) return; + const warn = parserOptions.requireInclude === undefined; + + new RequireIncludeDependencyParserPlugin(warn).apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireIncludePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireIncludePlugin", handler); + } + ); } } -module.exports = RemoveEmptyChunksPlugin; +module.exports = RequireIncludePlugin; /***/ }), -/***/ 7081: +/***/ 55627: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -104743,126 +95954,55 @@ module.exports = RemoveEmptyChunksPlugin; -const { STAGE_BASIC } = __webpack_require__(80057); -const Queue = __webpack_require__(65930); -const { intersect } = __webpack_require__(93347); +const makeSerializable = __webpack_require__(33032); +const ContextDependency = __webpack_require__(88101); +const ContextDependencyTemplateAsId = __webpack_require__(76081); -/** @typedef {import("../Compiler")} Compiler */ +class RequireResolveContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); -class RemoveParentModulesPlugin { - /** - * @param {Compiler} compiler the compiler - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap("RemoveParentModulesPlugin", compilation => { - const handler = (chunks, chunkGroups) => { - const chunkGraph = compilation.chunkGraph; - const queue = new Queue(); - const availableModulesMap = new WeakMap(); + this.range = range; + this.valueRange = valueRange; + } - for (const chunkGroup of compilation.entrypoints.values()) { - // initialize available modules for chunks without parents - availableModulesMap.set(chunkGroup, new Set()); - for (const child of chunkGroup.childrenIterable) { - queue.enqueue(child); - } - } - for (const chunkGroup of compilation.asyncEntrypoints) { - // initialize available modules for chunks without parents - availableModulesMap.set(chunkGroup, new Set()); - for (const child of chunkGroup.childrenIterable) { - queue.enqueue(child); - } - } + get type() { + return "amd require context"; + } - while (queue.length > 0) { - const chunkGroup = queue.dequeue(); - let availableModules = availableModulesMap.get(chunkGroup); - let changed = false; - for (const parent of chunkGroup.parentsIterable) { - const availableModulesInParent = availableModulesMap.get(parent); - if (availableModulesInParent !== undefined) { - // If we know the available modules in parent: process these - if (availableModules === undefined) { - // if we have not own info yet: create new entry - availableModules = new Set(availableModulesInParent); - for (const chunk of parent.chunks) { - for (const m of chunkGraph.getChunkModulesIterable(chunk)) { - availableModules.add(m); - } - } - availableModulesMap.set(chunkGroup, availableModules); - changed = true; - } else { - for (const m of availableModules) { - if ( - !chunkGraph.isModuleInChunkGroup(m, parent) && - !availableModulesInParent.has(m) - ) { - availableModules.delete(m); - changed = true; - } - } - } - } - } - if (changed) { - // if something changed: enqueue our children - for (const child of chunkGroup.childrenIterable) { - queue.enqueue(child); - } - } - } + serialize(context) { + const { write } = context; - // now we have available modules for every chunk - for (const chunk of chunks) { - const availableModulesSets = Array.from( - chunk.groupsIterable, - chunkGroup => availableModulesMap.get(chunkGroup) - ); - if (availableModulesSets.some(s => s === undefined)) continue; // No info about this chunk group - const availableModules = - availableModulesSets.length === 1 - ? availableModulesSets[0] - : intersect(availableModulesSets); - const numberOfModules = chunkGraph.getNumberOfChunkModules(chunk); - const toRemove = new Set(); - if (numberOfModules < availableModules.size) { - for (const m of chunkGraph.getChunkModulesIterable(chunk)) { - if (availableModules.has(m)) { - toRemove.add(m); - } - } - } else { - for (const m of availableModules) { - if (chunkGraph.isModuleInChunk(m, chunk)) { - toRemove.add(m); - } - } - } - for (const module of toRemove) { - chunkGraph.disconnectChunkAndModule(chunk, module); - } - } - }; - compilation.hooks.optimizeChunks.tap( - { - name: "RemoveParentModulesPlugin", - stage: STAGE_BASIC - }, - handler - ); - }); + write(this.range); + write(this.valueRange); + + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + + this.range = read(); + this.valueRange = read(); + + super.deserialize(context); } } -module.exports = RemoveParentModulesPlugin; + +makeSerializable( + RequireResolveContextDependency, + "webpack/lib/dependencies/RequireResolveContextDependency" +); + +RequireResolveContextDependency.Template = ContextDependencyTemplateAsId; + +module.exports = RequireResolveContextDependency; /***/ }), -/***/ 2837: -/***/ (function(module) { +/***/ 68582: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -104872,48 +96012,55 @@ module.exports = RemoveParentModulesPlugin; -/** @typedef {import("../Compiler")} Compiler */ +const Dependency = __webpack_require__(54912); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyAsId = __webpack_require__(80825); -class RuntimeChunkPlugin { - constructor(options) { - this.options = { - name: entrypoint => `runtime~${entrypoint.name}`, - ...options - }; +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class RequireResolveDependency extends ModuleDependency { + constructor(request, range) { + super(request); + + this.range = range; + } + + get type() { + return "require.resolve"; + } + + get category() { + return "commonjs"; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * 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 */ - apply(compiler) { - compiler.hooks.thisCompilation.tap("RuntimeChunkPlugin", compilation => { - compilation.hooks.addEntry.tap( - "RuntimeChunkPlugin", - (_, { name: entryName }) => { - if (entryName === undefined) return; - const data = compilation.entries.get(entryName); - if (data.options.runtime === undefined && !data.options.dependOn) { - // Determine runtime chunk name - let name = this.options.name; - if (typeof name === "function") { - name = name({ name: entryName }); - } - data.options.runtime = name; - } - } - ); - }); + getReferencedExports(moduleGraph, runtime) { + // This doesn't use any export + return Dependency.NO_EXPORTS_REFERENCED; } } -module.exports = RuntimeChunkPlugin; +makeSerializable( + RequireResolveDependency, + "webpack/lib/dependencies/RequireResolveDependency" +); + +RequireResolveDependency.Template = ModuleDependencyAsId; + +module.exports = RequireResolveDependency; /***/ }), -/***/ 84800: +/***/ 9880: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -104924,341 +96071,152 @@ module.exports = RuntimeChunkPlugin; -const glob2regexp = __webpack_require__(86140); -const { STAGE_DEFAULT } = __webpack_require__(80057); -const HarmonyExportImportedSpecifierDependency = __webpack_require__(67157); -const HarmonyImportSpecifierDependency = __webpack_require__(14077); -const formatLocation = __webpack_require__(16734); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** - * @typedef {Object} ExportInModule - * @property {Module} module the module - * @property {string} exportName the name of the export - * @property {boolean} checked if the export is conditional - */ +class RequireResolveHeaderDependency extends NullDependency { + constructor(range) { + super(); -/** - * @typedef {Object} ReexportInfo - * @property {Map} static - * @property {Map>} dynamic - */ + if (!Array.isArray(range)) throw new Error("range must be valid"); -/** @type {WeakMap>} */ -const globToRegexpCache = new WeakMap(); + this.range = range; + } -/** - * @param {string} glob the pattern - * @param {Map} cache the glob to RegExp cache - * @returns {RegExp} a regular expression - */ -const globToRegexp = (glob, cache) => { - const cacheEntry = cache.get(glob); - if (cacheEntry !== undefined) return cacheEntry; - if (!glob.includes("/")) { - glob = `**/${glob}`; + serialize(context) { + const { write } = context; + + write(this.range); + + super.serialize(context); } - const baseRegexp = glob2regexp(glob, { globstar: true, extended: true }); - const regexpSource = baseRegexp.source; - const regexp = new RegExp("^(\\./)?" + regexpSource.slice(1)); - cache.set(glob, regexp); - return regexp; -}; -class SideEffectsFlagPlugin { - /** - * @param {boolean} analyseSource analyse source code for side effects - */ - constructor(analyseSource = true) { - this._analyseSource = analyseSource; + static deserialize(context) { + const obj = new RequireResolveHeaderDependency(context.read()); + obj.deserialize(context); + return obj; } +} + +makeSerializable( + RequireResolveHeaderDependency, + "webpack/lib/dependencies/RequireResolveHeaderDependency" +); + +RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTemplate extends ( + NullDependency.Template +) { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - let cache = globToRegexpCache.get(compiler.root); - if (cache === undefined) { - cache = new Map(); - globToRegexpCache.set(compiler.root, cache); - } - compiler.hooks.compilation.tap( - "SideEffectsFlagPlugin", - (compilation, { normalModuleFactory }) => { - const moduleGraph = compilation.moduleGraph; - normalModuleFactory.hooks.module.tap( - "SideEffectsFlagPlugin", - (module, data) => { - const resolveData = data.resourceResolveData; - if ( - resolveData && - resolveData.descriptionFileData && - resolveData.relativePath - ) { - const sideEffects = resolveData.descriptionFileData.sideEffects; - if (sideEffects !== undefined) { - if (module.factoryMeta === undefined) { - module.factoryMeta = {}; - } - const hasSideEffects = - SideEffectsFlagPlugin.moduleHasSideEffects( - resolveData.relativePath, - sideEffects, - cache - ); - module.factoryMeta.sideEffectFree = !hasSideEffects; - } - } + apply(dependency, source, templateContext) { + const dep = /** @type {RequireResolveHeaderDependency} */ (dependency); + source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + } - return module; - } - ); - normalModuleFactory.hooks.module.tap( - "SideEffectsFlagPlugin", - (module, data) => { - if (typeof data.settings.sideEffects === "boolean") { - if (module.factoryMeta === undefined) { - module.factoryMeta = {}; - } - module.factoryMeta.sideEffectFree = !data.settings.sideEffects; - } - return module; - } - ); - if (this._analyseSource) { - /** - * @param {JavascriptParser} parser the parser - * @returns {void} - */ - const parserHandler = parser => { - let sideEffectsStatement; - parser.hooks.program.tap("SideEffectsFlagPlugin", () => { - sideEffectsStatement = undefined; - }); - parser.hooks.statement.tap( - { name: "SideEffectsFlagPlugin", stage: -100 }, - statement => { - if (sideEffectsStatement) return; - if (parser.scope.topLevelScope !== true) return; - switch (statement.type) { - case "ExpressionStatement": - if ( - !parser.isPure(statement.expression, statement.range[0]) - ) { - sideEffectsStatement = statement; - } - break; - case "IfStatement": - case "WhileStatement": - case "DoWhileStatement": - if (!parser.isPure(statement.test, statement.range[0])) { - sideEffectsStatement = statement; - } - // statement hook will be called for child statements too - break; - case "ForStatement": - if ( - !parser.isPure(statement.init, statement.range[0]) || - !parser.isPure( - statement.test, - statement.init - ? statement.init.range[1] - : statement.range[0] - ) || - !parser.isPure( - statement.update, - statement.test - ? statement.test.range[1] - : statement.init - ? statement.init.range[1] - : statement.range[0] - ) - ) { - sideEffectsStatement = statement; - } - // statement hook will be called for child statements too - break; - case "SwitchStatement": - if ( - !parser.isPure(statement.discriminant, statement.range[0]) - ) { - sideEffectsStatement = statement; - } - // statement hook will be called for child statements too - break; - case "VariableDeclaration": - case "ClassDeclaration": - case "FunctionDeclaration": - if (!parser.isPure(statement, statement.range[0])) { - sideEffectsStatement = statement; - } - break; - case "ExportNamedDeclaration": - case "ExportDefaultDeclaration": - if ( - !parser.isPure(statement.declaration, statement.range[0]) - ) { - sideEffectsStatement = statement; - } - break; - case "LabeledStatement": - case "BlockStatement": - // statement hook will be called for child statements too - break; - case "EmptyStatement": - break; - case "ExportAllDeclaration": - case "ImportDeclaration": - // imports will be handled by the dependencies - break; - default: - sideEffectsStatement = statement; - break; - } - } - ); - parser.hooks.finish.tap("SideEffectsFlagPlugin", () => { - if (sideEffectsStatement === undefined) { - parser.state.module.buildMeta.sideEffectFree = true; - } else { - const { loc, type } = sideEffectsStatement; - moduleGraph - .getOptimizationBailout(parser.state.module) - .push( - () => - `Statement (${type}) with side effects in source code at ${formatLocation( - loc - )}` - ); - } - }); - }; - for (const key of [ - "javascript/auto", - "javascript/esm", - "javascript/dynamic" - ]) { - normalModuleFactory.hooks.parser - .for(key) - .tap("SideEffectsFlagPlugin", parserHandler); - } - } - compilation.hooks.optimizeDependencies.tap( - { - name: "SideEffectsFlagPlugin", - stage: STAGE_DEFAULT - }, - modules => { - const logger = compilation.getLogger( - "webpack.SideEffectsFlagPlugin" - ); + applyAsTemplateArgument(name, dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + } +}; - logger.time("update dependencies"); - for (const module of modules) { - if (module.getSideEffectsConnectionState(moduleGraph) === false) { - const exportsInfo = moduleGraph.getExportsInfo(module); - for (const connection of moduleGraph.getIncomingConnections( - module - )) { - const dep = connection.dependency; - let isReexport; - if ( - (isReexport = - dep instanceof - HarmonyExportImportedSpecifierDependency) || - (dep instanceof HarmonyImportSpecifierDependency && - !dep.namespaceObjectAsContext) - ) { - // TODO improve for export * - if (isReexport && dep.name) { - const exportInfo = moduleGraph.getExportInfo( - connection.originModule, - dep.name - ); - exportInfo.moveTarget( - moduleGraph, - ({ module }) => - module.getSideEffectsConnectionState(moduleGraph) === - false, - ({ module: newModule, export: exportName }) => { - moduleGraph.updateModule(dep, newModule); - moduleGraph.addExplanation( - dep, - "(skipped side-effect-free modules)" - ); - const ids = dep.getIds(moduleGraph); - dep.setIds( - moduleGraph, - exportName - ? [...exportName, ...ids.slice(1)] - : ids.slice(1) - ); - return moduleGraph.getConnection(dep); - } - ); - continue; - } - // TODO improve for nested imports - const ids = dep.getIds(moduleGraph); - if (ids.length > 0) { - const exportInfo = exportsInfo.getExportInfo(ids[0]); - const target = exportInfo.getTarget( - moduleGraph, - ({ module }) => - module.getSideEffectsConnectionState(moduleGraph) === - false - ); - if (!target) continue; +module.exports = RequireResolveHeaderDependency; - moduleGraph.updateModule(dep, target.module); - moduleGraph.addExplanation( - dep, - "(skipped side-effect-free modules)" - ); - dep.setIds( - moduleGraph, - target.export - ? [...target.export, ...ids.slice(1)] - : ids.slice(1) - ); - } - } - } - } - } - logger.timeEnd("update dependencies"); - } - ); - } - ); + +/***/ }), + +/***/ 24187: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/Hash")} Hash */ + +class RuntimeRequirementsDependency extends NullDependency { + /** + * @param {string[]} runtimeRequirements runtime requirements + */ + constructor(runtimeRequirements) { + super(); + this.runtimeRequirements = new Set(runtimeRequirements); + this._hashUpdate = undefined; } - static moduleHasSideEffects(moduleName, flagValue, cache) { - switch (typeof flagValue) { - case "undefined": - return true; - case "boolean": - return flagValue; - case "string": - return globToRegexp(flagValue, cache).test(moduleName); - case "object": - return flagValue.some(glob => - SideEffectsFlagPlugin.moduleHasSideEffects(moduleName, glob, cache) - ); + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = Array.from(this.runtimeRequirements).join() + ""; } + hash.update(this._hashUpdate); + } + + serialize(context) { + const { write } = context; + write(this.runtimeRequirements); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.runtimeRequirements = read(); + super.deserialize(context); } } -module.exports = SideEffectsFlagPlugin; + +makeSerializable( + RuntimeRequirementsDependency, + "webpack/lib/dependencies/RuntimeRequirementsDependency" +); + +RuntimeRequirementsDependency.Template = class RuntimeRequirementsDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, { runtimeRequirements }) { + const dep = /** @type {RuntimeRequirementsDependency} */ (dependency); + for (const req of dep.runtimeRequirements) { + runtimeRequirements.add(req); + } + } +}; + +module.exports = RuntimeRequirementsDependency; /***/ }), -/***/ 21478: +/***/ 91418: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -105269,2335 +96227,1643 @@ module.exports = SideEffectsFlagPlugin; -const Chunk = __webpack_require__(39385); -const { STAGE_ADVANCED } = __webpack_require__(80057); -const WebpackError = __webpack_require__(53799); -const { requestToId } = __webpack_require__(63290); -const { isSubset } = __webpack_require__(93347); -const SortableSet = __webpack_require__(13098); -const { - compareModulesByIdentifier, - compareIterables -} = __webpack_require__(29579); -const createHash = __webpack_require__(49835); -const deterministicGrouping = __webpack_require__(59836); -const { makePathsRelative } = __webpack_require__(82186); -const memoize = __webpack_require__(78676); -const MinMaxSizeWarning = __webpack_require__(85305); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksCacheGroup} OptimizationSplitChunksCacheGroup */ -/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksGetCacheGroups} OptimizationSplitChunksGetCacheGroups */ -/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksOptions} OptimizationSplitChunksOptions */ -/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksSizes} OptimizationSplitChunksSizes */ -/** @typedef {import("../../declarations/WebpackOptions").Output} OutputOptions */ /** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("../Compilation").PathData} PathData */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Dependency").ExportSpec} ExportSpec */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/deterministicGrouping").GroupedItems} DeterministicGroupingGroupedItemsForModule */ -/** @typedef {import("../util/deterministicGrouping").Options} DeterministicGroupingOptionsForModule */ +/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {Record} SplitChunksSizes */ +class StaticExportsDependency extends NullDependency { + /** + * @param {string[] | true} exports export names + * @param {boolean} canMangle true, if mangling exports names is allowed + */ + constructor(exports, canMangle) { + super(); + this.exports = exports; + this.canMangle = canMangle; + } -/** - * @callback ChunkFilterFunction - * @param {Chunk} chunk - * @returns {boolean} - */ + get type() { + return "static exports"; + } -/** - * @callback CombineSizeFunction - * @param {number} a - * @param {number} b - * @returns {number} - */ + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + return { + exports: this.exports, + canMangle: this.canMangle, + dependencies: undefined + }; + } -/** - * @typedef {Object} CacheGroupSource - * @property {string=} key - * @property {number=} priority - * @property {GetName=} getName - * @property {ChunkFilterFunction=} chunksFilter - * @property {boolean=} enforce - * @property {SplitChunksSizes} minSize - * @property {SplitChunksSizes} minSizeReduction - * @property {SplitChunksSizes} minRemainingSize - * @property {SplitChunksSizes} enforceSizeThreshold - * @property {SplitChunksSizes} maxAsyncSize - * @property {SplitChunksSizes} maxInitialSize - * @property {number=} minChunks - * @property {number=} maxAsyncRequests - * @property {number=} maxInitialRequests - * @property {(string | function(PathData, AssetInfo=): string)=} filename - * @property {string=} idHint - * @property {string} automaticNameDelimiter - * @property {boolean=} reuseExistingChunk - * @property {boolean=} usedExports - */ + serialize(context) { + const { write } = context; + write(this.exports); + write(this.canMangle); + super.serialize(context); + } -/** - * @typedef {Object} CacheGroup - * @property {string} key - * @property {number=} priority - * @property {GetName=} getName - * @property {ChunkFilterFunction=} chunksFilter - * @property {SplitChunksSizes} minSize - * @property {SplitChunksSizes} minSizeReduction - * @property {SplitChunksSizes} minRemainingSize - * @property {SplitChunksSizes} enforceSizeThreshold - * @property {SplitChunksSizes} maxAsyncSize - * @property {SplitChunksSizes} maxInitialSize - * @property {number=} minChunks - * @property {number=} maxAsyncRequests - * @property {number=} maxInitialRequests - * @property {(string | function(PathData, AssetInfo=): string)=} filename - * @property {string=} idHint - * @property {string} automaticNameDelimiter - * @property {boolean} reuseExistingChunk - * @property {boolean} usedExports - * @property {boolean} _validateSize - * @property {boolean} _validateRemainingSize - * @property {SplitChunksSizes} _minSizeForMaxSize - * @property {boolean} _conditionalEnforce - */ + deserialize(context) { + const { read } = context; + this.exports = read(); + this.canMangle = read(); + super.deserialize(context); + } +} -/** - * @typedef {Object} FallbackCacheGroup - * @property {ChunkFilterFunction} chunksFilter - * @property {SplitChunksSizes} minSize - * @property {SplitChunksSizes} maxAsyncSize - * @property {SplitChunksSizes} maxInitialSize - * @property {string} automaticNameDelimiter - */ +makeSerializable( + StaticExportsDependency, + "webpack/lib/dependencies/StaticExportsDependency" +); -/** - * @typedef {Object} CacheGroupsContext - * @property {ModuleGraph} moduleGraph - * @property {ChunkGraph} chunkGraph - */ +module.exports = StaticExportsDependency; -/** - * @callback GetCacheGroups - * @param {Module} module - * @param {CacheGroupsContext} context - * @returns {CacheGroupSource[]} - */ -/** - * @callback GetName - * @param {Module=} module - * @param {Chunk[]=} chunks - * @param {string=} key - * @returns {string=} - */ +/***/ }), -/** - * @typedef {Object} SplitChunksOptions - * @property {ChunkFilterFunction} chunksFilter - * @property {string[]} defaultSizeTypes - * @property {SplitChunksSizes} minSize - * @property {SplitChunksSizes} minSizeReduction - * @property {SplitChunksSizes} minRemainingSize - * @property {SplitChunksSizes} enforceSizeThreshold - * @property {SplitChunksSizes} maxInitialSize - * @property {SplitChunksSizes} maxAsyncSize - * @property {number} minChunks - * @property {number} maxAsyncRequests - * @property {number} maxInitialRequests - * @property {boolean} hidePathInfo - * @property {string | function(PathData, AssetInfo=): string} filename - * @property {string} automaticNameDelimiter - * @property {GetCacheGroups} getCacheGroups - * @property {GetName} getName - * @property {boolean} usedExports - * @property {FallbackCacheGroup} fallbackCacheGroup - */ +/***/ 97981: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * @typedef {Object} ChunksInfoItem - * @property {SortableSet} modules - * @property {CacheGroup} cacheGroup - * @property {number} cacheGroupIndex - * @property {string} name - * @property {Record} sizes - * @property {Set} chunks - * @property {Set} reuseableChunks - * @property {Set} chunksKeys - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -const defaultGetName = /** @type {GetName} */ (() => {}); -const deterministicGroupingForModules = - /** @type {function(DeterministicGroupingOptionsForModule): DeterministicGroupingGroupedItemsForModule[]} */ ( - deterministicGrouping - ); -/** @type {WeakMap} */ -const getKeyCache = new WeakMap(); +const RuntimeGlobals = __webpack_require__(16475); +const WebpackError = __webpack_require__(53799); +const { + evaluateToString, + expressionIsUnsupported, + toConstantDependency +} = __webpack_require__(93998); +const makeSerializable = __webpack_require__(33032); +const ConstDependency = __webpack_require__(76911); +const SystemRuntimeModule = __webpack_require__(85439); -/** - * @param {string} name a filename to hash - * @param {OutputOptions} outputOptions hash function used - * @returns {string} hashed filename - */ -const hashFilename = (name, outputOptions) => { - const digest = /** @type {string} */ ( - createHash(outputOptions.hashFunction) - .update(name) - .digest(outputOptions.hashDigest) - ); - return digest.slice(0, 8); -}; +/** @typedef {import("../Compiler")} Compiler */ -/** - * @param {Chunk} chunk the chunk - * @returns {number} the number of requests - */ -const getRequests = chunk => { - let requests = 0; - for (const chunkGroup of chunk.groupsIterable) { - requests = Math.max(requests, chunkGroup.chunks.length); - } - return requests; -}; +class SystemPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "SystemPlugin", + (compilation, { normalModuleFactory }) => { + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.system) + .tap("SystemPlugin", (module, set) => { + set.add(RuntimeGlobals.requireScope); + }); -const mapObject = (obj, fn) => { - const newObj = Object.create(null); - for (const key of Object.keys(obj)) { - newObj[key] = fn(obj[key], key); - } - return newObj; -}; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.system) + .tap("SystemPlugin", (chunk, set) => { + compilation.addRuntimeModule(chunk, new SystemRuntimeModule()); + }); -/** - * @template T - * @param {Set} a set - * @param {Set} b other set - * @returns {boolean} true if at least one item of a is in b - */ -const isOverlap = (a, b) => { - for (const item of a) { - if (b.has(item)) return true; - } - return false; -}; + const handler = (parser, parserOptions) => { + if (parserOptions.system === undefined || !parserOptions.system) { + return; + } -const compareModuleIterables = compareIterables(compareModulesByIdentifier); + const setNotSupported = name => { + parser.hooks.evaluateTypeof + .for(name) + .tap("SystemPlugin", evaluateToString("undefined")); + parser.hooks.expression + .for(name) + .tap( + "SystemPlugin", + expressionIsUnsupported( + parser, + name + " is not supported by webpack." + ) + ); + }; -/** - * @param {ChunksInfoItem} a item - * @param {ChunksInfoItem} b item - * @returns {number} compare result - */ -const compareEntries = (a, b) => { - // 1. by priority - const diffPriority = a.cacheGroup.priority - b.cacheGroup.priority; - if (diffPriority) return diffPriority; - // 2. by number of chunks - const diffCount = a.chunks.size - b.chunks.size; - if (diffCount) return diffCount; - // 3. by size reduction - const aSizeReduce = totalSize(a.sizes) * (a.chunks.size - 1); - const bSizeReduce = totalSize(b.sizes) * (b.chunks.size - 1); - const diffSizeReduce = aSizeReduce - bSizeReduce; - if (diffSizeReduce) return diffSizeReduce; - // 4. by cache group index - const indexDiff = b.cacheGroupIndex - a.cacheGroupIndex; - if (indexDiff) return indexDiff; - // 5. by number of modules (to be able to compare by identifier) - const modulesA = a.modules; - const modulesB = b.modules; - const diff = modulesA.size - modulesB.size; - if (diff) return diff; - // 6. by module identifiers - modulesA.sort(); - modulesB.sort(); - return compareModuleIterables(modulesA, modulesB); -}; + parser.hooks.typeof + .for("System.import") + .tap( + "SystemPlugin", + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for("System.import") + .tap("SystemPlugin", evaluateToString("function")); + parser.hooks.typeof + .for("System") + .tap( + "SystemPlugin", + toConstantDependency(parser, JSON.stringify("object")) + ); + parser.hooks.evaluateTypeof + .for("System") + .tap("SystemPlugin", evaluateToString("object")); -const INITIAL_CHUNK_FILTER = chunk => chunk.canBeInitial(); -const ASYNC_CHUNK_FILTER = chunk => !chunk.canBeInitial(); -const ALL_CHUNK_FILTER = chunk => true; + setNotSupported("System.set"); + setNotSupported("System.get"); + setNotSupported("System.register"); -/** - * @param {OptimizationSplitChunksSizes} value the sizes - * @param {string[]} defaultSizeTypes the default size types - * @returns {SplitChunksSizes} normalized representation - */ -const normalizeSizes = (value, defaultSizeTypes) => { - if (typeof value === "number") { - /** @type {Record} */ - const o = {}; - for (const sizeType of defaultSizeTypes) o[sizeType] = value; - return o; - } else if (typeof value === "object" && value !== null) { - return { ...value }; - } else { - return {}; - } -}; + parser.hooks.expression.for("System").tap("SystemPlugin", expr => { + const dep = new ConstDependency(RuntimeGlobals.system, expr.range, [ + RuntimeGlobals.system + ]); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); -/** - * @param {...SplitChunksSizes} sizes the sizes - * @returns {SplitChunksSizes} the merged sizes - */ -const mergeSizes = (...sizes) => { - /** @type {SplitChunksSizes} */ - let merged = {}; - for (let i = sizes.length - 1; i >= 0; i--) { - merged = Object.assign(merged, sizes[i]); - } - return merged; -}; + parser.hooks.call.for("System.import").tap("SystemPlugin", expr => { + parser.state.module.addWarning( + new SystemImportDeprecationWarning(expr.loc) + ); -/** - * @param {SplitChunksSizes} sizes the sizes - * @returns {boolean} true, if there are sizes > 0 - */ -const hasNonZeroSizes = sizes => { - for (const key of Object.keys(sizes)) { - if (sizes[key] > 0) return true; - } - return false; -}; + return parser.hooks.importCall.call({ + type: "ImportExpression", + source: expr.arguments[0], + loc: expr.loc, + range: expr.range + }); + }); + }; -/** - * @param {SplitChunksSizes} a first sizes - * @param {SplitChunksSizes} b second sizes - * @param {CombineSizeFunction} combine a function to combine sizes - * @returns {SplitChunksSizes} the combine sizes - */ -const combineSizes = (a, b, combine) => { - const aKeys = new Set(Object.keys(a)); - const bKeys = new Set(Object.keys(b)); - /** @type {SplitChunksSizes} */ - const result = {}; - for (const key of aKeys) { - if (bKeys.has(key)) { - result[key] = combine(a[key], b[key]); - } else { - result[key] = a[key]; - } - } - for (const key of bKeys) { - if (!aKeys.has(key)) { - result[key] = b[key]; - } + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("SystemPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("SystemPlugin", handler); + } + ); } - return result; -}; +} -/** - * @param {SplitChunksSizes} sizes the sizes - * @param {SplitChunksSizes} minSize the min sizes - * @returns {boolean} true if there are sizes and all existing sizes are at least `minSize` - */ -const checkMinSize = (sizes, minSize) => { - for (const key of Object.keys(minSize)) { - const size = sizes[key]; - if (size === undefined || size === 0) continue; - if (size < minSize[key]) return false; - } - return true; -}; +class SystemImportDeprecationWarning extends WebpackError { + constructor(loc) { + super( + "System.import() is deprecated and will be removed soon. Use import() instead.\n" + + "For more info visit https://webpack.js.org/guides/code-splitting/" + ); -/** - * @param {SplitChunksSizes} sizes the sizes - * @param {SplitChunksSizes} minSizeReduction the min sizes - * @param {number} chunkCount number of chunks - * @returns {boolean} true if there are sizes and all existing sizes are at least `minSizeReduction` - */ -const checkMinSizeReduction = (sizes, minSizeReduction, chunkCount) => { - for (const key of Object.keys(minSizeReduction)) { - const size = sizes[key]; - if (size === undefined || size === 0) continue; - if (size * chunkCount < minSizeReduction[key]) return false; + this.name = "SystemImportDeprecationWarning"; + + this.loc = loc; } - return true; -}; +} -/** - * @param {SplitChunksSizes} sizes the sizes - * @param {SplitChunksSizes} minSize the min sizes - * @returns {undefined | string[]} list of size types that are below min size - */ -const getViolatingMinSizes = (sizes, minSize) => { - let list; - for (const key of Object.keys(minSize)) { - const size = sizes[key]; - if (size === undefined || size === 0) continue; - if (size < minSize[key]) { - if (list === undefined) list = [key]; - else list.push(key); - } +makeSerializable( + SystemImportDeprecationWarning, + "webpack/lib/dependencies/SystemPlugin", + "SystemImportDeprecationWarning" +); + +module.exports = SystemPlugin; +module.exports.SystemImportDeprecationWarning = SystemImportDeprecationWarning; + + +/***/ }), + +/***/ 85439: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); + +class SystemRuntimeModule extends RuntimeModule { + constructor() { + super("system"); } - return list; -}; -/** - * @param {SplitChunksSizes} sizes the sizes - * @returns {number} the total size - */ -const totalSize = sizes => { - let size = 0; - for (const key of Object.keys(sizes)) { - size += sizes[key]; + /** + * @returns {string} runtime code + */ + generate() { + return Template.asString([ + `${RuntimeGlobals.system} = {`, + Template.indent([ + "import: function () {", + Template.indent( + "throw new Error('System.import cannot be used indirectly');" + ), + "}" + ]), + "};" + ]); } - return size; -}; +} -/** - * @param {false|string|Function} name the chunk name - * @returns {GetName} a function to get the name of the chunk - */ -const normalizeName = name => { - if (typeof name === "string") { - return () => name; +module.exports = SystemRuntimeModule; + + +/***/ }), + +/***/ 58612: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const { + getDependencyUsedByExportsCondition +} = __webpack_require__(38988); +const makeSerializable = __webpack_require__(33032); +const memoize = __webpack_require__(78676); +const ModuleDependency = __webpack_require__(80321); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +const getRawDataUrlModule = memoize(() => __webpack_require__(19684)); + +class URLDependency extends ModuleDependency { + /** + * @param {string} request request + * @param {[number, number]} range range of the arguments of new URL( |> ... <| ) + * @param {[number, number]} outerRange range of the full |> new URL(...) <| + * @param {boolean=} relative use relative urls instead of absolute with base uri + */ + constructor(request, range, outerRange, relative) { + super(request); + this.range = range; + this.outerRange = outerRange; + this.relative = relative || false; + /** @type {Set | boolean} */ + this.usedByExports = undefined; } - if (typeof name === "function") { - return /** @type {GetName} */ (name); + + get type() { + return "new URL()"; } -}; -/** - * @param {OptimizationSplitChunksCacheGroup["chunks"]} chunks the chunk filter option - * @returns {ChunkFilterFunction} the chunk filter function - */ -const normalizeChunksFilter = chunks => { - if (chunks === "initial") { - return INITIAL_CHUNK_FILTER; + get category() { + return "url"; } - if (chunks === "async") { - return ASYNC_CHUNK_FILTER; + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return getDependencyUsedByExportsCondition( + this, + this.usedByExports, + moduleGraph + ); } - if (chunks === "all") { - return ALL_CHUNK_FILTER; + + /** + * @param {string} context context directory + * @returns {Module} a module + */ + createIgnoredModule(context) { + const RawDataUrlModule = getRawDataUrlModule(); + return new RawDataUrlModule("data:,", `ignored-asset`, `(ignored asset)`); } - if (typeof chunks === "function") { - return chunks; + + serialize(context) { + const { write } = context; + write(this.outerRange); + write(this.relative); + write(this.usedByExports); + super.serialize(context); } -}; -/** - * @param {GetCacheGroups | Record} cacheGroups the cache group options - * @param {string[]} defaultSizeTypes the default size types - * @returns {GetCacheGroups} a function to get the cache groups - */ -const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => { - if (typeof cacheGroups === "function") { - return cacheGroups; + deserialize(context) { + const { read } = context; + this.outerRange = read(); + this.relative = read(); + this.usedByExports = read(); + super.deserialize(context); } - if (typeof cacheGroups === "object" && cacheGroups !== null) { - /** @type {(function(Module, CacheGroupsContext, CacheGroupSource[]): void)[]} */ - const handlers = []; - for (const key of Object.keys(cacheGroups)) { - const option = cacheGroups[key]; - if (option === false) { - continue; - } - if (typeof option === "string" || option instanceof RegExp) { - const source = createCacheGroupSource({}, key, defaultSizeTypes); - handlers.push((module, context, results) => { - if (checkTest(option, module, context)) { - results.push(source); - } - }); - } else if (typeof option === "function") { - const cache = new WeakMap(); - handlers.push((module, context, results) => { - const result = option(module); - if (result) { - const groups = Array.isArray(result) ? result : [result]; - for (const group of groups) { - const cachedSource = cache.get(group); - if (cachedSource !== undefined) { - results.push(cachedSource); - } else { - const source = createCacheGroupSource( - group, - key, - defaultSizeTypes - ); - cache.set(group, source); - results.push(source); - } - } - } - }); - } else { - const source = createCacheGroupSource(option, key, defaultSizeTypes); - handlers.push((module, context, results) => { - if ( - checkTest(option.test, module, context) && - checkModuleType(option.type, module) && - checkModuleLayer(option.layer, module) - ) { - results.push(source); - } - }); - } +} + +URLDependency.Template = class URLDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @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 { + chunkGraph, + moduleGraph, + runtimeRequirements, + runtimeTemplate, + runtime + } = templateContext; + const dep = /** @type {URLDependency} */ (dependency); + const connection = moduleGraph.getConnection(dep); + // Skip rendering depending when dependency is conditional + if (connection && !connection.isTargetActive(runtime)) { + source.replace( + dep.outerRange[0], + dep.outerRange[1] - 1, + "/* unused asset import */ undefined" + ); + return; } - /** - * @param {Module} module the current module - * @param {CacheGroupsContext} context the current context - * @returns {CacheGroupSource[]} the matching cache groups - */ - const fn = (module, context) => { - /** @type {CacheGroupSource[]} */ - let results = []; - for (const fn of handlers) { - fn(module, context, results); - } - return results; - }; - return fn; - } - return () => null; -}; -/** - * @param {undefined|boolean|string|RegExp|Function} test test option - * @param {Module} module the module - * @param {CacheGroupsContext} context context object - * @returns {boolean} true, if the module should be selected - */ -const checkTest = (test, module, context) => { - if (test === undefined) return true; - if (typeof test === "function") { - return test(module, context); - } - if (typeof test === "boolean") return test; - if (typeof test === "string") { - const name = module.nameForCondition(); - return name && name.startsWith(test); - } - if (test instanceof RegExp) { - const name = module.nameForCondition(); - return name && test.test(name); - } - return false; -}; + runtimeRequirements.add(RuntimeGlobals.require); -/** - * @param {undefined|string|RegExp|Function} test type option - * @param {Module} module the module - * @returns {boolean} true, if the module should be selected - */ -const checkModuleType = (test, module) => { - if (test === undefined) return true; - if (typeof test === "function") { - return test(module.type); - } - if (typeof test === "string") { - const type = module.type; - return test === type; - } - if (test instanceof RegExp) { - const type = module.type; - return test.test(type); - } - return false; -}; + if (dep.relative) { + runtimeRequirements.add(RuntimeGlobals.relativeUrl); + source.replace( + dep.outerRange[0], + dep.outerRange[1] - 1, + `/* asset import */ new ${ + RuntimeGlobals.relativeUrl + }(${runtimeTemplate.moduleRaw({ + chunkGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + runtimeRequirements, + weak: false + })})` + ); + } else { + runtimeRequirements.add(RuntimeGlobals.baseURI); -/** - * @param {undefined|string|RegExp|Function} test type option - * @param {Module} module the module - * @returns {boolean} true, if the module should be selected - */ -const checkModuleLayer = (test, module) => { - if (test === undefined) return true; - if (typeof test === "function") { - return test(module.layer); - } - if (typeof test === "string") { - const layer = module.layer; - return test === "" ? !layer : layer && layer.startsWith(test); - } - if (test instanceof RegExp) { - const layer = module.layer; - return test.test(layer); + source.replace( + dep.range[0], + dep.range[1] - 1, + `/* asset import */ ${runtimeTemplate.moduleRaw({ + chunkGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + runtimeRequirements, + weak: false + })}, ${RuntimeGlobals.baseURI}` + ); + } } - return false; }; -/** - * @param {OptimizationSplitChunksCacheGroup} options the group options - * @param {string} key key of cache group - * @param {string[]} defaultSizeTypes the default size types - * @returns {CacheGroupSource} the normalized cached group - */ -const createCacheGroupSource = (options, key, defaultSizeTypes) => { - const minSize = normalizeSizes(options.minSize, defaultSizeTypes); - const minSizeReduction = normalizeSizes( - options.minSizeReduction, - defaultSizeTypes - ); - const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes); - return { - key, - priority: options.priority, - getName: normalizeName(options.name), - chunksFilter: normalizeChunksFilter(options.chunks), - enforce: options.enforce, - minSize, - minSizeReduction, - minRemainingSize: mergeSizes( - normalizeSizes(options.minRemainingSize, defaultSizeTypes), - minSize - ), - enforceSizeThreshold: normalizeSizes( - options.enforceSizeThreshold, - defaultSizeTypes - ), - maxAsyncSize: mergeSizes( - normalizeSizes(options.maxAsyncSize, defaultSizeTypes), - maxSize - ), - maxInitialSize: mergeSizes( - normalizeSizes(options.maxInitialSize, defaultSizeTypes), - maxSize - ), - minChunks: options.minChunks, - maxAsyncRequests: options.maxAsyncRequests, - maxInitialRequests: options.maxInitialRequests, - filename: options.filename, - idHint: options.idHint, - automaticNameDelimiter: options.automaticNameDelimiter, - reuseExistingChunk: options.reuseExistingChunk, - usedExports: options.usedExports - }; -}; +makeSerializable(URLDependency, "webpack/lib/dependencies/URLDependency"); -module.exports = class SplitChunksPlugin { - /** - * @param {OptimizationSplitChunksOptions=} options plugin options - */ - constructor(options = {}) { - const defaultSizeTypes = options.defaultSizeTypes || [ - "javascript", - "unknown" - ]; - const fallbackCacheGroup = options.fallbackCacheGroup || {}; - const minSize = normalizeSizes(options.minSize, defaultSizeTypes); - const minSizeReduction = normalizeSizes( - options.minSizeReduction, - defaultSizeTypes - ); - const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes); +module.exports = URLDependency; - /** @type {SplitChunksOptions} */ - this.options = { - chunksFilter: normalizeChunksFilter(options.chunks || "all"), - defaultSizeTypes, - minSize, - minSizeReduction, - minRemainingSize: mergeSizes( - normalizeSizes(options.minRemainingSize, defaultSizeTypes), - minSize - ), - enforceSizeThreshold: normalizeSizes( - options.enforceSizeThreshold, - defaultSizeTypes - ), - maxAsyncSize: mergeSizes( - normalizeSizes(options.maxAsyncSize, defaultSizeTypes), - maxSize - ), - maxInitialSize: mergeSizes( - normalizeSizes(options.maxInitialSize, defaultSizeTypes), - maxSize - ), - minChunks: options.minChunks || 1, - maxAsyncRequests: options.maxAsyncRequests || 1, - maxInitialRequests: options.maxInitialRequests || 1, - hidePathInfo: options.hidePathInfo || false, - filename: options.filename || undefined, - getCacheGroups: normalizeCacheGroups( - options.cacheGroups, - defaultSizeTypes - ), - getName: options.name ? normalizeName(options.name) : defaultGetName, - automaticNameDelimiter: options.automaticNameDelimiter, - usedExports: options.usedExports, - fallbackCacheGroup: { - chunksFilter: normalizeChunksFilter( - fallbackCacheGroup.chunks || options.chunks || "all" - ), - minSize: mergeSizes( - normalizeSizes(fallbackCacheGroup.minSize, defaultSizeTypes), - minSize - ), - maxAsyncSize: mergeSizes( - normalizeSizes(fallbackCacheGroup.maxAsyncSize, defaultSizeTypes), - normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes), - normalizeSizes(options.maxAsyncSize, defaultSizeTypes), - normalizeSizes(options.maxSize, defaultSizeTypes) - ), - maxInitialSize: mergeSizes( - normalizeSizes(fallbackCacheGroup.maxInitialSize, defaultSizeTypes), - normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes), - normalizeSizes(options.maxInitialSize, defaultSizeTypes), - normalizeSizes(options.maxSize, defaultSizeTypes) - ), - automaticNameDelimiter: - fallbackCacheGroup.automaticNameDelimiter || - options.automaticNameDelimiter || - "~" - } - }; - /** @type {WeakMap} */ - this._cacheGroupCache = new WeakMap(); - } +/***/ }), - /** - * @param {CacheGroupSource} cacheGroupSource source - * @returns {CacheGroup} the cache group (cached) - */ - _getCacheGroup(cacheGroupSource) { - const cacheEntry = this._cacheGroupCache.get(cacheGroupSource); - if (cacheEntry !== undefined) return cacheEntry; - const minSize = mergeSizes( - cacheGroupSource.minSize, - cacheGroupSource.enforce ? undefined : this.options.minSize - ); - const minSizeReduction = mergeSizes( - cacheGroupSource.minSizeReduction, - cacheGroupSource.enforce ? undefined : this.options.minSizeReduction - ); - const minRemainingSize = mergeSizes( - cacheGroupSource.minRemainingSize, - cacheGroupSource.enforce ? undefined : this.options.minRemainingSize - ); - const enforceSizeThreshold = mergeSizes( - cacheGroupSource.enforceSizeThreshold, - cacheGroupSource.enforce ? undefined : this.options.enforceSizeThreshold - ); - const cacheGroup = { - key: cacheGroupSource.key, - priority: cacheGroupSource.priority || 0, - chunksFilter: cacheGroupSource.chunksFilter || this.options.chunksFilter, - minSize, - minSizeReduction, - minRemainingSize, - enforceSizeThreshold, - maxAsyncSize: mergeSizes( - cacheGroupSource.maxAsyncSize, - cacheGroupSource.enforce ? undefined : this.options.maxAsyncSize - ), - maxInitialSize: mergeSizes( - cacheGroupSource.maxInitialSize, - cacheGroupSource.enforce ? undefined : this.options.maxInitialSize - ), - minChunks: - cacheGroupSource.minChunks !== undefined - ? cacheGroupSource.minChunks - : cacheGroupSource.enforce - ? 1 - : this.options.minChunks, - maxAsyncRequests: - cacheGroupSource.maxAsyncRequests !== undefined - ? cacheGroupSource.maxAsyncRequests - : cacheGroupSource.enforce - ? Infinity - : this.options.maxAsyncRequests, - maxInitialRequests: - cacheGroupSource.maxInitialRequests !== undefined - ? cacheGroupSource.maxInitialRequests - : cacheGroupSource.enforce - ? Infinity - : this.options.maxInitialRequests, - getName: - cacheGroupSource.getName !== undefined - ? cacheGroupSource.getName - : this.options.getName, - usedExports: - cacheGroupSource.usedExports !== undefined - ? cacheGroupSource.usedExports - : this.options.usedExports, - filename: - cacheGroupSource.filename !== undefined - ? cacheGroupSource.filename - : this.options.filename, - automaticNameDelimiter: - cacheGroupSource.automaticNameDelimiter !== undefined - ? cacheGroupSource.automaticNameDelimiter - : this.options.automaticNameDelimiter, - idHint: - cacheGroupSource.idHint !== undefined - ? cacheGroupSource.idHint - : cacheGroupSource.key, - reuseExistingChunk: cacheGroupSource.reuseExistingChunk || false, - _validateSize: hasNonZeroSizes(minSize), - _validateRemainingSize: hasNonZeroSizes(minRemainingSize), - _minSizeForMaxSize: mergeSizes( - cacheGroupSource.minSize, - this.options.minSize - ), - _conditionalEnforce: hasNonZeroSizes(enforceSizeThreshold) - }; - this._cacheGroupCache.set(cacheGroupSource, cacheGroup); - return cacheGroup; - } +/***/ 14412: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +const { approve } = __webpack_require__(93998); +const InnerGraph = __webpack_require__(38988); +const URLDependency = __webpack_require__(58612); + +/** @typedef {import("estree").NewExpression} NewExpressionNode */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +class URLPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {Compiler} compiler compiler */ apply(compiler) { - const cachedMakePathsRelative = makePathsRelative.bindContextCache( - compiler.context, - compiler.root - ); - compiler.hooks.thisCompilation.tap("SplitChunksPlugin", compilation => { - const logger = compilation.getLogger("webpack.SplitChunksPlugin"); - let alreadyOptimized = false; - compilation.hooks.unseal.tap("SplitChunksPlugin", () => { - alreadyOptimized = false; - }); - compilation.hooks.optimizeChunks.tap( - { - name: "SplitChunksPlugin", - stage: STAGE_ADVANCED - }, - chunks => { - if (alreadyOptimized) return; - alreadyOptimized = true; - logger.time("prepare"); - const chunkGraph = compilation.chunkGraph; - const moduleGraph = compilation.moduleGraph; - // Give each selected chunk an index (to create strings from chunks) - /** @type {Map} */ - const chunkIndexMap = new Map(); - const ZERO = BigInt("0"); - const ONE = BigInt("1"); - const START = ONE << BigInt("31"); - let index = START; - for (const chunk of chunks) { - chunkIndexMap.set( - chunk, - index | BigInt((Math.random() * 0x7fffffff) | 0) - ); - index = index << ONE; - } - /** - * @param {Iterable} chunks list of chunks - * @returns {bigint | Chunk} key of the chunks - */ - const getKey = chunks => { - const iterator = chunks[Symbol.iterator](); - let result = iterator.next(); - if (result.done) return ZERO; - const first = result.value; - result = iterator.next(); - if (result.done) return first; - let key = - chunkIndexMap.get(first) | chunkIndexMap.get(result.value); - while (!(result = iterator.next()).done) { - const raw = chunkIndexMap.get(result.value); - key = key ^ raw; - } - return key; - }; - const keyToString = key => { - if (typeof key === "bigint") return key.toString(16); - return chunkIndexMap.get(key).toString(16); - }; + compiler.hooks.compilation.tap( + "URLPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(URLDependency, normalModuleFactory); + compilation.dependencyTemplates.set( + URLDependency, + new URLDependency.Template() + ); - const getChunkSetsInGraph = memoize(() => { - /** @type {Map>} */ - const chunkSetsInGraph = new Map(); - /** @type {Set} */ - const singleChunkSets = new Set(); - for (const module of compilation.modules) { - const chunks = chunkGraph.getModuleChunksIterable(module); - const chunksKey = getKey(chunks); - if (typeof chunksKey === "bigint") { - if (!chunkSetsInGraph.has(chunksKey)) { - chunkSetsInGraph.set(chunksKey, new Set(chunks)); - } - } else { - singleChunkSets.add(chunksKey); - } - } - return { chunkSetsInGraph, singleChunkSets }; - }); + /** + * @param {JavascriptParser} parser parser + * @param {object} parserOptions options + */ + const parserCallback = (parser, parserOptions) => { + if (parserOptions.url === false) return; + const relative = parserOptions.url === "relative"; /** - * @param {Module} module the module - * @returns {Iterable} groups of chunks with equal exports + * @param {NewExpressionNode} expr expression + * @returns {undefined | string} request */ - const groupChunksByExports = module => { - const exportsInfo = moduleGraph.getExportsInfo(module); - const groupedByUsedExports = new Map(); - for (const chunk of chunkGraph.getModuleChunksIterable(module)) { - const key = exportsInfo.getUsageKey(chunk.runtime); - const list = groupedByUsedExports.get(key); - if (list !== undefined) { - list.push(chunk); - } else { - groupedByUsedExports.set(key, [chunk]); - } - } - return groupedByUsedExports.values(); - }; - - /** @type {Map>} */ - const groupedByExportsMap = new Map(); + const getUrlRequest = expr => { + if (expr.arguments.length !== 2) return; - const getExportsChunkSetsInGraph = memoize(() => { - /** @type {Map>} */ - const chunkSetsInGraph = new Map(); - /** @type {Set} */ - const singleChunkSets = new Set(); - for (const module of compilation.modules) { - const groupedChunks = Array.from(groupChunksByExports(module)); - groupedByExportsMap.set(module, groupedChunks); - for (const chunks of groupedChunks) { - if (chunks.length === 1) { - singleChunkSets.add(chunks[0]); - } else { - const chunksKey = /** @type {bigint} */ (getKey(chunks)); - if (!chunkSetsInGraph.has(chunksKey)) { - chunkSetsInGraph.set(chunksKey, new Set(chunks)); - } - } - } - } - return { chunkSetsInGraph, singleChunkSets }; - }); + const [arg1, arg2] = expr.arguments; - // group these set of chunks by count - // to allow to check less sets via isSubset - // (only smaller sets can be subset) - const groupChunkSetsByCount = chunkSets => { - /** @type {Map>>} */ - const chunkSetsByCount = new Map(); - for (const chunksSet of chunkSets) { - const count = chunksSet.size; - let array = chunkSetsByCount.get(count); - if (array === undefined) { - array = []; - chunkSetsByCount.set(count, array); - } - array.push(chunksSet); - } - return chunkSetsByCount; - }; - const getChunkSetsByCount = memoize(() => - groupChunkSetsByCount( - getChunkSetsInGraph().chunkSetsInGraph.values() + if ( + arg2.type !== "MemberExpression" || + arg1.type === "SpreadElement" ) - ); - const getExportsChunkSetsByCount = memoize(() => - groupChunkSetsByCount( - getExportsChunkSetsInGraph().chunkSetsInGraph.values() + return; + + const chain = parser.extractMemberExpressionChain(arg2); + + if ( + chain.members.length !== 1 || + chain.object.type !== "MetaProperty" || + chain.object.meta.name !== "import" || + chain.object.property.name !== "meta" || + chain.members[0] !== "url" ) - ); + return; - // Create a list of possible combinations - const createGetCombinations = ( - chunkSets, - singleChunkSets, - chunkSetsByCount - ) => { - /** @type {Map | Chunk)[]>} */ - const combinationsCache = new Map(); + const request = parser.evaluateExpression(arg1).asString(); - return key => { - const cacheEntry = combinationsCache.get(key); - if (cacheEntry !== undefined) return cacheEntry; - if (key instanceof Chunk) { - const result = [key]; - combinationsCache.set(key, result); - return result; - } - const chunksSet = chunkSets.get(key); - /** @type {(Set | Chunk)[]} */ - const array = [chunksSet]; - for (const [count, setArray] of chunkSetsByCount) { - // "equal" is not needed because they would have been merge in the first step - if (count < chunksSet.size) { - for (const set of setArray) { - if (isSubset(chunksSet, set)) { - array.push(set); - } - } - } - } - for (const chunk of singleChunkSets) { - if (chunksSet.has(chunk)) { - array.push(chunk); - } - } - combinationsCache.set(key, array); - return array; - }; + return request; }; - const getCombinationsFactory = memoize(() => { - const { chunkSetsInGraph, singleChunkSets } = getChunkSetsInGraph(); - return createGetCombinations( - chunkSetsInGraph, - singleChunkSets, - getChunkSetsByCount() - ); - }); - const getCombinations = key => getCombinationsFactory()(key); + parser.hooks.canRename.for("URL").tap("URLPlugin", approve); + parser.hooks.new.for("URL").tap("URLPlugin", _expr => { + const expr = /** @type {NewExpressionNode} */ (_expr); - const getExportsCombinationsFactory = memoize(() => { - const { chunkSetsInGraph, singleChunkSets } = - getExportsChunkSetsInGraph(); - return createGetCombinations( - chunkSetsInGraph, - singleChunkSets, - getExportsChunkSetsByCount() + const request = getUrlRequest(expr); + + if (!request) return; + + const [arg1, arg2] = expr.arguments; + const dep = new URLDependency( + request, + [arg1.range[0], arg2.range[1]], + expr.range, + relative ); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); + return true; }); - const getExportsCombinations = key => - getExportsCombinationsFactory()(key); + parser.hooks.isPure.for("NewExpression").tap("URLPlugin", _expr => { + const expr = /** @type {NewExpressionNode} */ (_expr); + const { callee } = expr; + if (callee.type !== "Identifier") return; + const calleeInfo = parser.getFreeInfoFromVariable(callee.name); + if (!calleeInfo || calleeInfo.name !== "URL") return; - /** - * @typedef {Object} SelectedChunksResult - * @property {Chunk[]} chunks the list of chunks - * @property {bigint | Chunk} key a key of the list - */ + const request = getUrlRequest(expr); - /** @type {WeakMap | Chunk, WeakMap>} */ - const selectedChunksCacheByChunksSet = new WeakMap(); + if (request) return true; + }); + }; - /** - * get list and key by applying the filter function to the list - * It is cached for performance reasons - * @param {Set | Chunk} chunks list of chunks - * @param {ChunkFilterFunction} chunkFilter filter function for chunks - * @returns {SelectedChunksResult} list and key - */ - const getSelectedChunks = (chunks, chunkFilter) => { - let entry = selectedChunksCacheByChunksSet.get(chunks); - if (entry === undefined) { - entry = new WeakMap(); - selectedChunksCacheByChunksSet.set(chunks, entry); - } - /** @type {SelectedChunksResult} */ - let entry2 = entry.get(chunkFilter); - if (entry2 === undefined) { - /** @type {Chunk[]} */ - const selectedChunks = []; - if (chunks instanceof Chunk) { - if (chunkFilter(chunks)) selectedChunks.push(chunks); - } else { - for (const chunk of chunks) { - if (chunkFilter(chunk)) selectedChunks.push(chunk); - } - } - entry2 = { - chunks: selectedChunks, - key: getKey(selectedChunks) - }; - entry.set(chunkFilter, entry2); - } - return entry2; - }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("URLPlugin", parserCallback); - /** @type {Map} */ - const alreadyValidatedParents = new Map(); - /** @type {Set} */ - const alreadyReportedErrors = new Set(); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("URLPlugin", parserCallback); + } + ); + } +} - // Map a list of chunks to a list of modules - // For the key the chunk "index" is used, the value is a SortableSet of modules - /** @type {Map} */ - const chunksInfoMap = new Map(); +module.exports = URLPlugin; - /** - * @param {CacheGroup} cacheGroup the current cache group - * @param {number} cacheGroupIndex the index of the cache group of ordering - * @param {Chunk[]} selectedChunks chunks selected for this module - * @param {bigint | Chunk} selectedChunksKey a key of selectedChunks - * @param {Module} module the current module - * @returns {void} - */ - const addModuleToChunksInfoMap = ( - cacheGroup, - cacheGroupIndex, - selectedChunks, - selectedChunksKey, - module - ) => { - // Break if minimum number of chunks is not reached - if (selectedChunks.length < cacheGroup.minChunks) return; - // Determine name for split chunk - const name = cacheGroup.getName( - module, - selectedChunks, - cacheGroup.key - ); - // Check if the name is ok - const existingChunk = compilation.namedChunks.get(name); - if (existingChunk) { - const parentValidationKey = `${name}|${ - typeof selectedChunksKey === "bigint" - ? selectedChunksKey - : selectedChunksKey.debugId - }`; - const valid = alreadyValidatedParents.get(parentValidationKey); - if (valid === false) return; - if (valid === undefined) { - // Module can only be moved into the existing chunk if the existing chunk - // is a parent of all selected chunks - let isInAllParents = true; - /** @type {Set} */ - const queue = new Set(); - for (const chunk of selectedChunks) { - for (const group of chunk.groupsIterable) { - queue.add(group); - } - } - for (const group of queue) { - if (existingChunk.isInGroup(group)) continue; - let hasParent = false; - for (const parent of group.parentsIterable) { - hasParent = true; - queue.add(parent); - } - if (!hasParent) { - isInAllParents = false; - } - } - const valid = isInAllParents; - alreadyValidatedParents.set(parentValidationKey, valid); - if (!valid) { - if (!alreadyReportedErrors.has(name)) { - alreadyReportedErrors.add(name); - compilation.errors.push( - new WebpackError( - "SplitChunksPlugin\n" + - `Cache group "${cacheGroup.key}" conflicts with existing chunk.\n` + - `Both have the same name "${name}" and existing chunk is not a parent of the selected modules.\n` + - "Use a different name for the cache group or make sure that the existing chunk is a parent (e. g. via dependOn).\n" + - 'HINT: You can omit "name" to automatically create a name.\n' + - "BREAKING CHANGE: webpack < 5 used to allow to use an entrypoint as splitChunk. " + - "This is no longer allowed when the entrypoint is not a parent of the selected modules.\n" + - "Remove this entrypoint and add modules to cache group's 'test' instead. " + - "If you need modules to be evaluated on startup, add them to the existing entrypoints (make them arrays). " + - "See migration guide of more info." - ) - ); - } - return; - } - } - } - // Create key for maps - // When it has a name we use the name as key - // Otherwise we create the key from chunks and cache group key - // This automatically merges equal names - const key = - cacheGroup.key + - (name - ? ` name:${name}` - : ` chunks:${keyToString(selectedChunksKey)}`); - // Add module to maps - let info = chunksInfoMap.get(key); - if (info === undefined) { - chunksInfoMap.set( - key, - (info = { - modules: new SortableSet( - undefined, - compareModulesByIdentifier - ), - cacheGroup, - cacheGroupIndex, - name, - sizes: {}, - chunks: new Set(), - reuseableChunks: new Set(), - chunksKeys: new Set() - }) - ); - } - const oldSize = info.modules.size; - info.modules.add(module); - if (info.modules.size !== oldSize) { - for (const type of module.getSourceTypes()) { - info.sizes[type] = (info.sizes[type] || 0) + module.size(type); - } - } - const oldChunksKeysSize = info.chunksKeys.size; - info.chunksKeys.add(selectedChunksKey); - if (oldChunksKeysSize !== info.chunksKeys.size) { - for (const chunk of selectedChunks) { - info.chunks.add(chunk); - } - } - }; - const context = { - moduleGraph, - chunkGraph - }; +/***/ }), - logger.timeEnd("prepare"); +/***/ 51669: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - logger.time("modules"); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Walk through all modules - for (const module of compilation.modules) { - // Get cache group - let cacheGroups = this.options.getCacheGroups(module, context); - if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { - continue; - } - // Prepare some values (usedExports = false) - const getCombs = memoize(() => { - const chunks = chunkGraph.getModuleChunksIterable(module); - const chunksKey = getKey(chunks); - return getCombinations(chunksKey); - }); - // Prepare some values (usedExports = true) - const getCombsByUsedExports = memoize(() => { - // fill the groupedByExportsMap - getExportsChunkSetsInGraph(); - /** @type {Set | Chunk>} */ - const set = new Set(); - const groupedByUsedExports = groupedByExportsMap.get(module); - for (const chunks of groupedByUsedExports) { - const chunksKey = getKey(chunks); - for (const comb of getExportsCombinations(chunksKey)) - set.add(comb); - } - return set; - }); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); - let cacheGroupIndex = 0; - for (const cacheGroupSource of cacheGroups) { - const cacheGroup = this._getCacheGroup(cacheGroupSource); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - const combs = cacheGroup.usedExports - ? getCombsByUsedExports() - : getCombs(); - // For all combination of chunk selection - for (const chunkCombination of combs) { - // Break if minimum number of chunks is not reached - const count = - chunkCombination instanceof Chunk ? 1 : chunkCombination.size; - if (count < cacheGroup.minChunks) continue; - // Select chunks by configuration - const { chunks: selectedChunks, key: selectedChunksKey } = - getSelectedChunks(chunkCombination, cacheGroup.chunksFilter); +class UnsupportedDependency extends NullDependency { + constructor(request, range) { + super(); - addModuleToChunksInfoMap( - cacheGroup, - cacheGroupIndex, - selectedChunks, - selectedChunksKey, - module - ); - } - cacheGroupIndex++; - } - } + this.request = request; + this.range = range; + } - logger.timeEnd("modules"); + serialize(context) { + const { write } = context; - logger.time("queue"); + write(this.request); + write(this.range); - /** - * @param {ChunksInfoItem} info entry - * @param {string[]} sourceTypes source types to be removed - */ - const removeModulesWithSourceType = (info, sourceTypes) => { - for (const module of info.modules) { - const types = module.getSourceTypes(); - if (sourceTypes.some(type => types.has(type))) { - info.modules.delete(module); - for (const type of types) { - info.sizes[type] -= module.size(type); - } - } - } - }; + super.serialize(context); + } - /** - * @param {ChunksInfoItem} info entry - * @returns {boolean} true, if entry become empty - */ - const removeMinSizeViolatingModules = info => { - if (!info.cacheGroup._validateSize) return false; - const violatingSizes = getViolatingMinSizes( - info.sizes, - info.cacheGroup.minSize - ); - if (violatingSizes === undefined) return false; - removeModulesWithSourceType(info, violatingSizes); - return info.modules.size === 0; - }; + deserialize(context) { + const { read } = context; - // Filter items were size < minSize - for (const [key, info] of chunksInfoMap) { - if (removeMinSizeViolatingModules(info)) { - chunksInfoMap.delete(key); - } else if ( - !checkMinSizeReduction( - info.sizes, - info.cacheGroup.minSizeReduction, - info.chunks.size - ) - ) { - chunksInfoMap.delete(key); - } - } + this.request = read(); + this.range = read(); - /** - * @typedef {Object} MaxSizeQueueItem - * @property {SplitChunksSizes} minSize - * @property {SplitChunksSizes} maxAsyncSize - * @property {SplitChunksSizes} maxInitialSize - * @property {string} automaticNameDelimiter - * @property {string[]} keys - */ + super.deserialize(context); + } +} - /** @type {Map} */ - const maxSizeQueueMap = new Map(); +makeSerializable( + UnsupportedDependency, + "webpack/lib/dependencies/UnsupportedDependency" +); - while (chunksInfoMap.size > 0) { - // Find best matching entry - let bestEntryKey; - let bestEntry; - for (const pair of chunksInfoMap) { - const key = pair[0]; - const info = pair[1]; - if ( - bestEntry === undefined || - compareEntries(bestEntry, info) < 0 - ) { - bestEntry = info; - bestEntryKey = key; - } - } - - const item = bestEntry; - chunksInfoMap.delete(bestEntryKey); - - let chunkName = item.name; - // Variable for the new chunk (lazy created) - /** @type {Chunk} */ - let newChunk; - // When no chunk name, check if we can reuse a chunk instead of creating a new one - let isExistingChunk = false; - let isReusedWithAllModules = false; - if (chunkName) { - const chunkByName = compilation.namedChunks.get(chunkName); - if (chunkByName !== undefined) { - newChunk = chunkByName; - const oldSize = item.chunks.size; - item.chunks.delete(newChunk); - isExistingChunk = item.chunks.size !== oldSize; - } - } else if (item.cacheGroup.reuseExistingChunk) { - outer: for (const chunk of item.chunks) { - if ( - chunkGraph.getNumberOfChunkModules(chunk) !== - item.modules.size - ) { - continue; - } - if ( - item.chunks.size > 1 && - chunkGraph.getNumberOfEntryModules(chunk) > 0 - ) { - continue; - } - for (const module of item.modules) { - if (!chunkGraph.isModuleInChunk(module, chunk)) { - continue outer; - } - } - if (!newChunk || !newChunk.name) { - newChunk = chunk; - } else if ( - chunk.name && - chunk.name.length < newChunk.name.length - ) { - newChunk = chunk; - } else if ( - chunk.name && - chunk.name.length === newChunk.name.length && - chunk.name < newChunk.name - ) { - newChunk = chunk; - } - } - if (newChunk) { - item.chunks.delete(newChunk); - chunkName = undefined; - isExistingChunk = true; - isReusedWithAllModules = true; - } - } - - const enforced = - item.cacheGroup._conditionalEnforce && - checkMinSize(item.sizes, item.cacheGroup.enforceSizeThreshold); - - const usedChunks = new Set(item.chunks); - - // Check if maxRequests condition can be fulfilled - if ( - !enforced && - (Number.isFinite(item.cacheGroup.maxInitialRequests) || - Number.isFinite(item.cacheGroup.maxAsyncRequests)) - ) { - for (const chunk of usedChunks) { - // respect max requests - const maxRequests = chunk.isOnlyInitial() - ? item.cacheGroup.maxInitialRequests - : chunk.canBeInitial() - ? Math.min( - item.cacheGroup.maxInitialRequests, - item.cacheGroup.maxAsyncRequests - ) - : item.cacheGroup.maxAsyncRequests; - if ( - isFinite(maxRequests) && - getRequests(chunk) >= maxRequests - ) { - usedChunks.delete(chunk); - } - } - } - - outer: for (const chunk of usedChunks) { - for (const module of item.modules) { - if (chunkGraph.isModuleInChunk(module, chunk)) continue outer; - } - usedChunks.delete(chunk); - } - - // Were some (invalid) chunks removed from usedChunks? - // => readd all modules to the queue, as things could have been changed - if (usedChunks.size < item.chunks.size) { - if (isExistingChunk) usedChunks.add(newChunk); - if (usedChunks.size >= item.cacheGroup.minChunks) { - const chunksArr = Array.from(usedChunks); - for (const module of item.modules) { - addModuleToChunksInfoMap( - item.cacheGroup, - item.cacheGroupIndex, - chunksArr, - getKey(usedChunks), - module - ); - } - } - continue; - } - - // Validate minRemainingSize constraint when a single chunk is left over - if ( - !enforced && - item.cacheGroup._validateRemainingSize && - usedChunks.size === 1 - ) { - const [chunk] = usedChunks; - let chunkSizes = Object.create(null); - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - if (!item.modules.has(module)) { - for (const type of module.getSourceTypes()) { - chunkSizes[type] = - (chunkSizes[type] || 0) + module.size(type); - } - } - } - const violatingSizes = getViolatingMinSizes( - chunkSizes, - item.cacheGroup.minRemainingSize - ); - if (violatingSizes !== undefined) { - const oldModulesSize = item.modules.size; - removeModulesWithSourceType(item, violatingSizes); - if ( - item.modules.size > 0 && - item.modules.size !== oldModulesSize - ) { - // queue this item again to be processed again - // without violating modules - chunksInfoMap.set(bestEntryKey, item); - } - continue; - } - } - - // Create the new chunk if not reusing one - if (newChunk === undefined) { - newChunk = compilation.addChunk(chunkName); - } - // Walk through all chunks - for (const chunk of usedChunks) { - // Add graph connections for splitted chunk - chunk.split(newChunk); - } - - // Add a note to the chunk - newChunk.chunkReason = - (newChunk.chunkReason ? newChunk.chunkReason + ", " : "") + - (isReusedWithAllModules - ? "reused as split chunk" - : "split chunk"); - if (item.cacheGroup.key) { - newChunk.chunkReason += ` (cache group: ${item.cacheGroup.key})`; - } - if (chunkName) { - newChunk.chunkReason += ` (name: ${chunkName})`; - } - if (item.cacheGroup.filename) { - newChunk.filenameTemplate = item.cacheGroup.filename; - } - if (item.cacheGroup.idHint) { - newChunk.idNameHints.add(item.cacheGroup.idHint); - } - if (!isReusedWithAllModules) { - // Add all modules to the new chunk - for (const module of item.modules) { - if (!module.chunkCondition(newChunk, compilation)) continue; - // Add module to new chunk - chunkGraph.connectChunkAndModule(newChunk, module); - // Remove module from used chunks - for (const chunk of usedChunks) { - chunkGraph.disconnectChunkAndModule(chunk, module); - } - } - } else { - // Remove all modules from used chunks - for (const module of item.modules) { - for (const chunk of usedChunks) { - chunkGraph.disconnectChunkAndModule(chunk, module); - } - } - } - - if ( - Object.keys(item.cacheGroup.maxAsyncSize).length > 0 || - Object.keys(item.cacheGroup.maxInitialSize).length > 0 - ) { - const oldMaxSizeSettings = maxSizeQueueMap.get(newChunk); - maxSizeQueueMap.set(newChunk, { - minSize: oldMaxSizeSettings - ? combineSizes( - oldMaxSizeSettings.minSize, - item.cacheGroup._minSizeForMaxSize, - Math.max - ) - : item.cacheGroup.minSize, - maxAsyncSize: oldMaxSizeSettings - ? combineSizes( - oldMaxSizeSettings.maxAsyncSize, - item.cacheGroup.maxAsyncSize, - Math.min - ) - : item.cacheGroup.maxAsyncSize, - maxInitialSize: oldMaxSizeSettings - ? combineSizes( - oldMaxSizeSettings.maxInitialSize, - item.cacheGroup.maxInitialSize, - Math.min - ) - : item.cacheGroup.maxInitialSize, - automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter, - keys: oldMaxSizeSettings - ? oldMaxSizeSettings.keys.concat(item.cacheGroup.key) - : [item.cacheGroup.key] - }); - } - - // remove all modules from other entries and update size - for (const [key, info] of chunksInfoMap) { - if (isOverlap(info.chunks, usedChunks)) { - // update modules and total size - // may remove it from the map when < minSize - let updated = false; - for (const module of item.modules) { - if (info.modules.has(module)) { - // remove module - info.modules.delete(module); - // update size - for (const key of module.getSourceTypes()) { - info.sizes[key] -= module.size(key); - } - updated = true; - } - } - if (updated) { - if (info.modules.size === 0) { - chunksInfoMap.delete(key); - continue; - } - if ( - removeMinSizeViolatingModules(info) || - !checkMinSizeReduction( - info.sizes, - info.cacheGroup.minSizeReduction, - info.chunks.size - ) - ) { - chunksInfoMap.delete(key); - continue; - } - } - } - } - } - - logger.timeEnd("queue"); - - logger.time("maxSize"); - - /** @type {Set} */ - const incorrectMinMaxSizeSet = new Set(); - - const { outputOptions } = compilation; +UnsupportedDependency.Template = class UnsupportedDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, { runtimeTemplate }) { + const dep = /** @type {UnsupportedDependency} */ (dependency); - // Make sure that maxSize is fulfilled - const { fallbackCacheGroup } = this.options; - for (const chunk of Array.from(compilation.chunks)) { - const chunkConfig = maxSizeQueueMap.get(chunk); - const { - minSize, - maxAsyncSize, - maxInitialSize, - automaticNameDelimiter - } = chunkConfig || fallbackCacheGroup; - if (!chunkConfig && !fallbackCacheGroup.chunksFilter(chunk)) - continue; - /** @type {SplitChunksSizes} */ - let maxSize; - if (chunk.isOnlyInitial()) { - maxSize = maxInitialSize; - } else if (chunk.canBeInitial()) { - maxSize = combineSizes(maxAsyncSize, maxInitialSize, Math.min); - } else { - maxSize = maxAsyncSize; - } - if (Object.keys(maxSize).length === 0) { - continue; - } - for (const key of Object.keys(maxSize)) { - const maxSizeValue = maxSize[key]; - const minSizeValue = minSize[key]; - if ( - typeof minSizeValue === "number" && - minSizeValue > maxSizeValue - ) { - const keys = chunkConfig && chunkConfig.keys; - const warningKey = `${ - keys && keys.join() - } ${minSizeValue} ${maxSizeValue}`; - if (!incorrectMinMaxSizeSet.has(warningKey)) { - incorrectMinMaxSizeSet.add(warningKey); - compilation.warnings.push( - new MinMaxSizeWarning(keys, minSizeValue, maxSizeValue) - ); - } - } - } - const results = deterministicGroupingForModules({ - minSize, - maxSize: mapObject(maxSize, (value, key) => { - const minSizeValue = minSize[key]; - return typeof minSizeValue === "number" - ? Math.max(value, minSizeValue) - : value; - }), - items: chunkGraph.getChunkModulesIterable(chunk), - getKey(module) { - const cache = getKeyCache.get(module); - if (cache !== undefined) return cache; - const ident = cachedMakePathsRelative(module.identifier()); - const nameForCondition = - module.nameForCondition && module.nameForCondition(); - const name = nameForCondition - ? cachedMakePathsRelative(nameForCondition) - : ident.replace(/^.*!|\?[^?!]*$/g, ""); - const fullKey = - name + - automaticNameDelimiter + - hashFilename(ident, outputOptions); - const key = requestToId(fullKey); - getKeyCache.set(module, key); - return key; - }, - getSize(module) { - const size = Object.create(null); - for (const key of module.getSourceTypes()) { - size[key] = module.size(key); - } - return size; - } - }); - if (results.length <= 1) { - continue; - } - for (let i = 0; i < results.length; i++) { - const group = results[i]; - const key = this.options.hidePathInfo - ? hashFilename(group.key, outputOptions) - : group.key; - let name = chunk.name - ? chunk.name + automaticNameDelimiter + key - : null; - if (name && name.length > 100) { - name = - name.slice(0, 100) + - automaticNameDelimiter + - hashFilename(name, outputOptions); - } - if (i !== results.length - 1) { - const newPart = compilation.addChunk(name); - chunk.split(newPart); - newPart.chunkReason = chunk.chunkReason; - // Add all modules to the new chunk - for (const module of group.items) { - if (!module.chunkCondition(newPart, compilation)) { - continue; - } - // Add module to new chunk - chunkGraph.connectChunkAndModule(newPart, module); - // Remove module from used chunks - chunkGraph.disconnectChunkAndModule(chunk, module); - } - } else { - // change the chunk to be a part - chunk.name = name; - } - } - } - logger.timeEnd("maxSize"); - } - ); - }); + source.replace( + dep.range[0], + dep.range[1], + runtimeTemplate.missingModule({ + request: dep.request + }) + ); } }; +module.exports = UnsupportedDependency; + /***/ }), -/***/ 52149: +/***/ 52204: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn + Author Tobias Koppers @sokra */ -const { formatSize } = __webpack_require__(71070); -const WebpackError = __webpack_require__(53799); +const Dependency = __webpack_require__(54912); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); -/** @typedef {import("./SizeLimitsPlugin").AssetDetails} AssetDetails */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class WebAssemblyExportImportedDependency extends ModuleDependency { + constructor(exportName, request, name, valueType) { + super(request); + /** @type {string} */ + this.exportName = exportName; + /** @type {string} */ + this.name = name; + /** @type {string} */ + this.valueType = valueType; + } -module.exports = class AssetsOverSizeLimitWarning extends WebpackError { /** - * @param {AssetDetails[]} assetsOverSizeLimit the assets - * @param {number} assetLimit the size limit + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module */ - constructor(assetsOverSizeLimit, assetLimit) { - const assetLists = assetsOverSizeLimit - .map(asset => `\n ${asset.name} (${formatSize(asset.size)})`) - .join(""); - - super(`asset size limit: The following asset(s) exceed the recommended size limit (${formatSize( - assetLimit - )}). -This can impact web performance. -Assets: ${assetLists}`); - - this.name = "AssetsOverSizeLimitWarning"; - this.assets = assetsOverSizeLimit; + couldAffectReferencingModule() { + return Dependency.TRANSITIVE; } -}; - - -/***/ }), - -/***/ 84229: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ - - -const { formatSize } = __webpack_require__(71070); -const WebpackError = __webpack_require__(53799); - -/** @typedef {import("./SizeLimitsPlugin").EntrypointDetails} EntrypointDetails */ - -module.exports = class EntrypointsOverSizeLimitWarning extends WebpackError { /** - * @param {EntrypointDetails[]} entrypoints the entrypoints - * @param {number} entrypointLimit the size limit + * 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 */ - constructor(entrypoints, entrypointLimit) { - const entrypointList = entrypoints - .map( - entrypoint => - `\n ${entrypoint.name} (${formatSize( - entrypoint.size - )})\n${entrypoint.files.map(asset => ` ${asset}`).join("\n")}` - ) - .join(""); - super(`entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (${formatSize( - entrypointLimit - )}). This can impact web performance. -Entrypoints:${entrypointList}\n`); + getReferencedExports(moduleGraph, runtime) { + return [[this.name]]; + } - this.name = "EntrypointsOverSizeLimitWarning"; - this.entrypoints = entrypoints; + get type() { + return "wasm export import"; } -}; + get category() { + return "wasm"; + } -/***/ }), + serialize(context) { + const { write } = context; -/***/ 17791: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + write(this.exportName); + write(this.name); + write(this.valueType); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ + super.serialize(context); + } + deserialize(context) { + const { read } = context; + this.exportName = read(); + this.name = read(); + this.valueType = read(); -const WebpackError = __webpack_require__(53799); + super.deserialize(context); + } +} -module.exports = class NoAsyncChunksWarning extends WebpackError { - constructor() { - super( - "webpack performance recommendations: \n" + - "You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\n" + - "For more info visit https://webpack.js.org/guides/code-splitting/" - ); +makeSerializable( + WebAssemblyExportImportedDependency, + "webpack/lib/dependencies/WebAssemblyExportImportedDependency" +); - this.name = "NoAsyncChunksWarning"; - } -}; +module.exports = WebAssemblyExportImportedDependency; /***/ }), -/***/ 32557: +/***/ 5239: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn + Author Tobias Koppers @sokra */ -const { find } = __webpack_require__(93347); -const AssetsOverSizeLimitWarning = __webpack_require__(52149); -const EntrypointsOverSizeLimitWarning = __webpack_require__(84229); -const NoAsyncChunksWarning = __webpack_require__(17791); +const makeSerializable = __webpack_require__(33032); +const UnsupportedWebAssemblyFeatureError = __webpack_require__(78455); +const ModuleDependency = __webpack_require__(80321); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").PerformanceOptions} PerformanceOptions */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Entrypoint")} Entrypoint */ +/** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -/** - * @typedef {Object} AssetDetails - * @property {string} name - * @property {number} size - */ - -/** - * @typedef {Object} EntrypointDetails - * @property {string} name - * @property {number} size - * @property {string[]} files - */ - -const isOverSizeLimitSet = new WeakSet(); - -const excludeSourceMap = (name, source, info) => !info.development; - -module.exports = class SizeLimitsPlugin { +class WebAssemblyImportDependency extends ModuleDependency { /** - * @param {PerformanceOptions} options the plugin options + * @param {string} request the request + * @param {string} name the imported name + * @param {ModuleImportDescription} description the WASM ast node + * @param {false | string} onlyDirectImport if only direct imports are allowed */ - constructor(options) { - this.hints = options.hints; - this.maxAssetSize = options.maxAssetSize; - this.maxEntrypointSize = options.maxEntrypointSize; - this.assetFilter = options.assetFilter; + constructor(request, name, description, onlyDirectImport) { + super(request); + /** @type {string} */ + this.name = name; + /** @type {ModuleImportDescription} */ + this.description = description; + /** @type {false | string} */ + this.onlyDirectImport = onlyDirectImport; + } + + get type() { + return "wasm import"; + } + + get category() { + return "wasm"; } /** - * @param {ChunkGroup | Source} thing the resource to test - * @returns {boolean} true if over the limit + * 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 */ - static isOverSizeLimit(thing) { - return isOverSizeLimitSet.has(thing); + getReferencedExports(moduleGraph, runtime) { + return [[this.name]]; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * Returns errors + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} errors */ - apply(compiler) { - const entrypointSizeLimit = this.maxEntrypointSize; - const assetSizeLimit = this.maxAssetSize; - const hints = this.hints; - const assetFilter = this.assetFilter || excludeSourceMap; - - compiler.hooks.afterEmit.tap("SizeLimitsPlugin", compilation => { - /** @type {WebpackError[]} */ - const warnings = []; - - /** - * @param {Entrypoint} entrypoint an entrypoint - * @returns {number} the size of the entrypoint - */ - const getEntrypointSize = entrypoint => { - let size = 0; - for (const file of entrypoint.getFiles()) { - const asset = compilation.getAsset(file); - if ( - asset && - assetFilter(asset.name, asset.source, asset.info) && - asset.source - ) { - size += asset.info.size || asset.source.size(); - } - } - return size; - }; + getErrors(moduleGraph) { + const module = moduleGraph.getModule(this); - /** @type {AssetDetails[]} */ - const assetsOverSizeLimit = []; - for (const { name, source, info } of compilation.getAssets()) { - if (!assetFilter(name, source, info) || !source) { - continue; - } + if ( + this.onlyDirectImport && + module && + !module.type.startsWith("webassembly") + ) { + return [ + new UnsupportedWebAssemblyFeatureError( + `Import "${this.name}" from "${this.request}" with ${this.onlyDirectImport} can only be used for direct wasm to wasm dependencies` + ) + ]; + } + } - const size = info.size || source.size(); - if (size > assetSizeLimit) { - assetsOverSizeLimit.push({ - name, - size - }); - isOverSizeLimitSet.add(source); - } - } + serialize(context) { + const { write } = context; - const fileFilter = name => { - const asset = compilation.getAsset(name); - return asset && assetFilter(asset.name, asset.source, asset.info); - }; + write(this.name); + write(this.description); + write(this.onlyDirectImport); - /** @type {EntrypointDetails[]} */ - const entrypointsOverLimit = []; - for (const [name, entry] of compilation.entrypoints) { - const size = getEntrypointSize(entry); + super.serialize(context); + } - if (size > entrypointSizeLimit) { - entrypointsOverLimit.push({ - name: name, - size: size, - files: entry.getFiles().filter(fileFilter) - }); - isOverSizeLimitSet.add(entry); - } - } + deserialize(context) { + const { read } = context; - if (hints) { - // 1. Individual Chunk: Size < 250kb - // 2. Collective Initial Chunks [entrypoint] (Each Set?): Size < 250kb - // 3. No Async Chunks - // if !1, then 2, if !2 return - if (assetsOverSizeLimit.length > 0) { - warnings.push( - new AssetsOverSizeLimitWarning(assetsOverSizeLimit, assetSizeLimit) - ); - } - if (entrypointsOverLimit.length > 0) { - warnings.push( - new EntrypointsOverSizeLimitWarning( - entrypointsOverLimit, - entrypointSizeLimit - ) - ); - } + this.name = read(); + this.description = read(); + this.onlyDirectImport = read(); - if (warnings.length > 0) { - const someAsyncChunk = find( - compilation.chunks, - chunk => !chunk.canBeInitial() - ); + super.deserialize(context); + } +} - if (!someAsyncChunk) { - warnings.push(new NoAsyncChunksWarning()); - } +makeSerializable( + WebAssemblyImportDependency, + "webpack/lib/dependencies/WebAssemblyImportDependency" +); - if (hints === "error") { - compilation.errors.push(...warnings); - } else { - compilation.warnings.push(...warnings); - } - } - } - }); - } -}; +module.exports = WebAssemblyImportDependency; /***/ }), -/***/ 95175: +/***/ 26505: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop */ -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); +const Dependency = __webpack_require__(54912); +const Template = __webpack_require__(39722); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class WebpackIsIncludedDependency extends ModuleDependency { + constructor(request, range) { + super(request); + + this.weak = true; + this.range = range; + } -class ChunkPrefetchFunctionRuntimeModule extends RuntimeModule { /** - * @param {string} childType TODO - * @param {string} runtimeFunction TODO - * @param {string} runtimeHandlers TODO + * 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 */ - constructor(childType, runtimeFunction, runtimeHandlers) { - super(`chunk ${childType} function`); - this.childType = childType; - this.runtimeFunction = runtimeFunction; - this.runtimeHandlers = runtimeHandlers; + getReferencedExports(moduleGraph, runtime) { + // This doesn't use any export + return Dependency.NO_EXPORTS_REFERENCED; + } + + get type() { + return "__webpack_is_included__"; } +} + +makeSerializable( + WebpackIsIncludedDependency, + "webpack/lib/dependencies/WebpackIsIncludedDependency" +); +WebpackIsIncludedDependency.Template = class WebpackIsIncludedDependencyTemplate extends ( + ModuleDependency.Template +) { /** - * @returns {string} runtime code + * @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} */ - generate() { - const { runtimeFunction, runtimeHandlers } = this; - const { runtimeTemplate } = this.compilation; - return Template.asString([ - `${runtimeHandlers} = {};`, - `${runtimeFunction} = ${runtimeTemplate.basicFunction("chunkId", [ - // map is shorter than forEach - `Object.keys(${runtimeHandlers}).map(${runtimeTemplate.basicFunction( - "key", - `${runtimeHandlers}[key](chunkId);` - )});` - ])}` - ]); + apply(dependency, source, { runtimeTemplate, chunkGraph, moduleGraph }) { + const dep = /** @type {WebpackIsIncludedDependency} */ (dependency); + const connection = moduleGraph.getConnection(dep); + const included = connection + ? chunkGraph.getNumberOfModuleChunks(connection.module) > 0 + : false; + const comment = runtimeTemplate.outputOptions.pathinfo + ? Template.toComment( + `__webpack_is_included__ ${runtimeTemplate.requestShortener.shorten( + dep.request + )}` + ) + : ""; + + source.replace( + dep.range[0], + dep.range[1] - 1, + `${comment}${JSON.stringify(included)}` + ); } -} +}; -module.exports = ChunkPrefetchFunctionRuntimeModule; +module.exports = WebpackIsIncludedDependency; /***/ }), -/***/ 33895: +/***/ 1466: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ +const Dependency = __webpack_require__(54912); const RuntimeGlobals = __webpack_require__(16475); -const ChunkPrefetchFunctionRuntimeModule = __webpack_require__(95175); -const ChunkPrefetchStartupRuntimeModule = __webpack_require__(15294); -const ChunkPrefetchTriggerRuntimeModule = __webpack_require__(98441); -const ChunkPreloadTriggerRuntimeModule = __webpack_require__(56236); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Entrypoint")} Entrypoint */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -class ChunkPrefetchPreloadPlugin { +class WorkerDependency extends ModuleDependency { /** - * @param {Compiler} compiler the compiler + * @param {string} request request + * @param {[number, number]} range range + */ + constructor(request, range) { + super(request); + this.range = range; + } + + /** + * 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.NO_EXPORTS_REFERENCED; + } + + get type() { + return "new Worker()"; + } + + get category() { + return "worker"; + } +} + +WorkerDependency.Template = class WorkerDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @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(compiler) { - compiler.hooks.compilation.tap( - "ChunkPrefetchPreloadPlugin", - compilation => { - compilation.hooks.additionalChunkRuntimeRequirements.tap( - "ChunkPrefetchPreloadPlugin", - (chunk, set, { chunkGraph }) => { - if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return; - const startupChildChunks = chunk.getChildrenOfTypeInOrder( - chunkGraph, - "prefetchOrder" - ); - if (startupChildChunks) { - set.add(RuntimeGlobals.prefetchChunk); - set.add(RuntimeGlobals.onChunksLoaded); - compilation.addRuntimeModule( - chunk, - new ChunkPrefetchStartupRuntimeModule(startupChildChunks) - ); - } - } - ); - compilation.hooks.additionalTreeRuntimeRequirements.tap( - "ChunkPrefetchPreloadPlugin", - (chunk, set, { chunkGraph }) => { - const chunkMap = chunk.getChildIdsByOrdersMap(chunkGraph, false); + apply(dependency, source, templateContext) { + const { chunkGraph, moduleGraph, runtimeRequirements } = templateContext; + const dep = /** @type {WorkerDependency} */ (dependency); + const block = /** @type {AsyncDependenciesBlock} */ ( + moduleGraph.getParentBlock(dependency) + ); + const entrypoint = /** @type {Entrypoint} */ ( + chunkGraph.getBlockChunkGroup(block) + ); + const chunk = entrypoint.getEntrypointChunk(); - if (chunkMap.prefetch) { - set.add(RuntimeGlobals.prefetchChunk); - compilation.addRuntimeModule( - chunk, - new ChunkPrefetchTriggerRuntimeModule(chunkMap.prefetch) - ); - } - if (chunkMap.preload) { - set.add(RuntimeGlobals.preloadChunk); - compilation.addRuntimeModule( - chunk, - new ChunkPreloadTriggerRuntimeModule(chunkMap.preload) - ); - } - } - ); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.prefetchChunk) - .tap("ChunkPrefetchPreloadPlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new ChunkPrefetchFunctionRuntimeModule( - "prefetch", - RuntimeGlobals.prefetchChunk, - RuntimeGlobals.prefetchChunkHandlers - ) - ); - set.add(RuntimeGlobals.prefetchChunkHandlers); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.preloadChunk) - .tap("ChunkPrefetchPreloadPlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new ChunkPrefetchFunctionRuntimeModule( - "preload", - RuntimeGlobals.preloadChunk, - RuntimeGlobals.preloadChunkHandlers - ) - ); - set.add(RuntimeGlobals.preloadChunkHandlers); - }); - } + runtimeRequirements.add(RuntimeGlobals.publicPath); + runtimeRequirements.add(RuntimeGlobals.baseURI); + runtimeRequirements.add(RuntimeGlobals.getChunkScriptFilename); + + source.replace( + dep.range[0], + dep.range[1] - 1, + `/* worker import */ ${RuntimeGlobals.publicPath} + ${ + RuntimeGlobals.getChunkScriptFilename + }(${JSON.stringify(chunk.id)}), ${RuntimeGlobals.baseURI}` ); } -} +}; -module.exports = ChunkPrefetchPreloadPlugin; +makeSerializable(WorkerDependency, "webpack/lib/dependencies/WorkerDependency"); + +module.exports = WorkerDependency; /***/ }), -/***/ 15294: +/***/ 82509: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); - -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ - -class ChunkPrefetchStartupRuntimeModule extends RuntimeModule { - /** - * @param {{ onChunks: Chunk[], chunks: Set }[]} startupChunks chunk ids to trigger when chunks are loaded - */ - constructor(startupChunks) { - super("startup prefetch", RuntimeModule.STAGE_TRIGGER); - this.startupChunks = startupChunks; - } +const { pathToFileURL } = __webpack_require__(57310); +const AsyncDependenciesBlock = __webpack_require__(47736); +const CommentCompilationWarning = __webpack_require__(98427); +const UnsupportedFeatureWarning = __webpack_require__(42495); +const EnableChunkLoadingPlugin = __webpack_require__(61291); +const { equals } = __webpack_require__(84953); +const createHash = __webpack_require__(49835); +const { contextify } = __webpack_require__(82186); +const EnableWasmLoadingPlugin = __webpack_require__(78613); +const ConstDependency = __webpack_require__(76911); +const CreateScriptUrlDependency = __webpack_require__(79062); +const { + harmonySpecifierTag +} = __webpack_require__(20862); +const WorkerDependency = __webpack_require__(1466); + +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").ObjectExpression} ObjectExpression */ +/** @typedef {import("estree").Pattern} Pattern */ +/** @typedef {import("estree").Property} Property */ +/** @typedef {import("estree").SpreadElement} SpreadElement */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./HarmonyImportDependencyParserPlugin").HarmonySettings} HarmonySettings */ +const getUrl = module => { + return pathToFileURL(module.resource).toString(); +}; + +const DEFAULT_SYNTAX = [ + "Worker", + "SharedWorker", + "navigator.serviceWorker.register()", + "Worker from worker_threads" +]; + +/** @type {WeakMap} */ +const workerIndexMap = new WeakMap(); + +class WorkerPlugin { + constructor(chunkLoading, wasmLoading, module) { + this._chunkLoading = chunkLoading; + this._wasmLoading = wasmLoading; + this._module = module; + } /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - const { startupChunks, chunk } = this; - const { runtimeTemplate } = this.compilation; - return Template.asString( - startupChunks.map( - ({ onChunks, chunks }) => - `${RuntimeGlobals.onChunksLoaded}(0, ${JSON.stringify( - // This need to include itself to delay execution after this chunk has been fully loaded - onChunks.filter(c => c === chunk).map(c => c.id) - )}, ${runtimeTemplate.basicFunction( - "", - chunks.size < 3 - ? Array.from( - chunks, - c => - `${RuntimeGlobals.prefetchChunk}(${JSON.stringify(c.id)});` - ) - : `${JSON.stringify(Array.from(chunks, c => c.id))}.map(${ - RuntimeGlobals.prefetchChunk - });` - )}, 5);` - ) + apply(compiler) { + if (this._chunkLoading) { + new EnableChunkLoadingPlugin(this._chunkLoading).apply(compiler); + } + if (this._wasmLoading) { + new EnableWasmLoadingPlugin(this._wasmLoading).apply(compiler); + } + const cachedContextify = contextify.bindContextCache( + compiler.context, + compiler.root + ); + compiler.hooks.thisCompilation.tap( + "WorkerPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + WorkerDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + WorkerDependency, + new WorkerDependency.Template() + ); + compilation.dependencyTemplates.set( + CreateScriptUrlDependency, + new CreateScriptUrlDependency.Template() + ); + + /** + * @param {JavascriptParser} parser the parser + * @param {Expression} expr expression + * @returns {[BasicEvaluatedExpression, [number, number]]} parsed + */ + const parseModuleUrl = (parser, expr) => { + if ( + expr.type !== "NewExpression" || + expr.callee.type === "Super" || + expr.arguments.length !== 2 + ) + return; + const [arg1, arg2] = expr.arguments; + if (arg1.type === "SpreadElement") return; + if (arg2.type === "SpreadElement") return; + const callee = parser.evaluateExpression(expr.callee); + if (!callee.isIdentifier() || callee.identifier !== "URL") return; + const arg2Value = parser.evaluateExpression(arg2); + if ( + !arg2Value.isString() || + !arg2Value.string.startsWith("file://") || + arg2Value.string !== getUrl(parser.state.module) + ) { + return; + } + const arg1Value = parser.evaluateExpression(arg1); + return [arg1Value, [arg1.range[0], arg2.range[1]]]; + }; + + /** + * @param {JavascriptParser} parser the parser + * @param {ObjectExpression} expr expression + * @returns {{ expressions: Record, otherElements: (Property | SpreadElement)[], values: Record, spread: boolean, insertType: "comma" | "single", insertLocation: number }} parsed object + */ + const parseObjectExpression = (parser, expr) => { + /** @type {Record} */ + const values = {}; + /** @type {Record} */ + const expressions = {}; + /** @type {(Property | SpreadElement)[]} */ + const otherElements = []; + let spread = false; + for (const prop of expr.properties) { + if (prop.type === "SpreadElement") { + spread = true; + } else if ( + prop.type === "Property" && + !prop.method && + !prop.computed && + prop.key.type === "Identifier" + ) { + expressions[prop.key.name] = prop.value; + if (!prop.shorthand && !prop.value.type.endsWith("Pattern")) { + const value = parser.evaluateExpression( + /** @type {Expression} */ (prop.value) + ); + if (value.isCompileTimeValue()) + values[prop.key.name] = value.asCompileTimeValue(); + } + } else { + otherElements.push(prop); + } + } + const insertType = expr.properties.length > 0 ? "comma" : "single"; + const insertLocation = + expr.properties[expr.properties.length - 1].range[1]; + return { + expressions, + otherElements, + values, + spread, + insertType, + insertLocation + }; + }; + + /** + * @param {JavascriptParser} parser the parser + * @param {object} parserOptions options + */ + const parserPlugin = (parser, parserOptions) => { + if (parserOptions.worker === false) return; + const options = !Array.isArray(parserOptions.worker) + ? ["..."] + : parserOptions.worker; + const handleNewWorker = expr => { + if (expr.arguments.length === 0 || expr.arguments.length > 2) + return; + const [arg1, arg2] = expr.arguments; + if (arg1.type === "SpreadElement") return; + if (arg2 && arg2.type === "SpreadElement") return; + const parsedUrl = parseModuleUrl(parser, arg1); + if (!parsedUrl) return; + const [url, range] = parsedUrl; + if (!url.isString()) return; + const { + expressions, + otherElements, + values: options, + spread: hasSpreadInOptions, + insertType, + insertLocation + } = arg2 && arg2.type === "ObjectExpression" + ? parseObjectExpression(parser, arg2) + : { + expressions: {}, + otherElements: [], + values: {}, + spread: false, + insertType: arg2 ? "spread" : "argument", + insertLocation: arg2 ? arg2.range : arg1.range[1] + }; + const { options: importOptions, errors: commentErrors } = + parser.parseCommentOptions(expr.range); + + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + comment.loc + ) + ); + } + } + + /** @type {EntryOptions} */ + let entryOptions = {}; + + if (importOptions) { + if (importOptions.webpackIgnore !== undefined) { + if (typeof importOptions.webpackIgnore !== "boolean") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, + expr.loc + ) + ); + } else { + if (importOptions.webpackIgnore) { + return false; + } + } + } + if (importOptions.webpackEntryOptions !== undefined) { + if ( + typeof importOptions.webpackEntryOptions !== "object" || + importOptions.webpackEntryOptions === null + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackEntryOptions\` expected a object, but received: ${importOptions.webpackEntryOptions}.`, + expr.loc + ) + ); + } else { + Object.assign( + entryOptions, + importOptions.webpackEntryOptions + ); + } + } + if (importOptions.webpackChunkName !== undefined) { + if (typeof importOptions.webpackChunkName !== "string") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, + expr.loc + ) + ); + } else { + entryOptions.name = importOptions.webpackChunkName; + } + } + } + + if ( + !Object.prototype.hasOwnProperty.call(entryOptions, "name") && + options && + typeof options.name === "string" + ) { + entryOptions.name = options.name; + } + + if (entryOptions.runtime === undefined) { + let i = workerIndexMap.get(parser.state) || 0; + workerIndexMap.set(parser.state, i + 1); + let name = `${cachedContextify( + parser.state.module.identifier() + )}|${i}`; + const hash = createHash(compilation.outputOptions.hashFunction); + hash.update(name); + const digest = /** @type {string} */ ( + hash.digest(compilation.outputOptions.hashDigest) + ); + entryOptions.runtime = digest.slice( + 0, + compilation.outputOptions.hashDigestLength + ); + } + + const block = new AsyncDependenciesBlock({ + name: entryOptions.name, + entryOptions: { + chunkLoading: this._chunkLoading, + wasmLoading: this._wasmLoading, + ...entryOptions + } + }); + block.loc = expr.loc; + const dep = new WorkerDependency(url.string, range); + dep.loc = expr.loc; + block.addDependency(dep); + parser.state.module.addBlock(block); + + if (compilation.outputOptions.trustedTypes) { + const dep = new CreateScriptUrlDependency( + expr.arguments[0].range + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + } + + if (expressions.type) { + const expr = expressions.type; + if (options.type !== false) { + const dep = new ConstDependency( + this._module ? '"module"' : "undefined", + expr.range + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + expressions.type = undefined; + } + } else if (insertType === "comma") { + if (this._module || hasSpreadInOptions) { + const dep = new ConstDependency( + `, type: ${this._module ? '"module"' : "undefined"}`, + insertLocation + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + } + } else if (insertType === "spread") { + const dep1 = new ConstDependency( + "Object.assign({}, ", + insertLocation[0] + ); + const dep2 = new ConstDependency( + `, { type: ${this._module ? '"module"' : "undefined"} })`, + insertLocation[1] + ); + dep1.loc = expr.loc; + dep2.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep1); + parser.state.module.addPresentationalDependency(dep2); + } else if (insertType === "argument") { + if (this._module) { + const dep = new ConstDependency( + ', { type: "module" }', + insertLocation + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + } + } + + parser.walkExpression(expr.callee); + for (const key of Object.keys(expressions)) { + if (expressions[key]) parser.walkExpression(expressions[key]); + } + for (const prop of otherElements) { + parser.walkProperty(prop); + } + if (insertType === "spread") { + parser.walkExpression(arg2); + } + + return true; + }; + const processItem = item => { + if (item.endsWith("()")) { + parser.hooks.call + .for(item.slice(0, -2)) + .tap("WorkerPlugin", handleNewWorker); + } else { + const match = /^(.+?)(\(\))?\s+from\s+(.+)$/.exec(item); + if (match) { + const ids = match[1].split("."); + const call = match[2]; + const source = match[3]; + (call ? parser.hooks.call : parser.hooks.new) + .for(harmonySpecifierTag) + .tap("WorkerPlugin", expr => { + const settings = /** @type {HarmonySettings} */ ( + parser.currentTagData + ); + if ( + !settings || + settings.source !== source || + !equals(settings.ids, ids) + ) { + return; + } + return handleNewWorker(expr); + }); + } else { + parser.hooks.new.for(item).tap("WorkerPlugin", handleNewWorker); + } + } + }; + for (const item of options) { + if (item === "...") { + DEFAULT_SYNTAX.forEach(processItem); + } else processItem(item); + } + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("WorkerPlugin", parserPlugin); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("WorkerPlugin", parserPlugin); + } ); } } +module.exports = WorkerPlugin; -module.exports = ChunkPrefetchStartupRuntimeModule; + +/***/ }), + +/***/ 50396: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +module.exports = expr => { + // + if ( + expr.type === "FunctionExpression" || + expr.type === "ArrowFunctionExpression" + ) { + return { + fn: expr, + expressions: [], + needThis: false + }; + } + + // .bind() + if ( + expr.type === "CallExpression" && + expr.callee.type === "MemberExpression" && + expr.callee.object.type === "FunctionExpression" && + expr.callee.property.type === "Identifier" && + expr.callee.property.name === "bind" && + expr.arguments.length === 1 + ) { + return { + fn: expr.callee.object, + expressions: [expr.arguments[0]], + needThis: undefined + }; + } + // (function(_this) {return })(this) (Coffeescript) + if ( + expr.type === "CallExpression" && + expr.callee.type === "FunctionExpression" && + expr.callee.body.type === "BlockStatement" && + expr.arguments.length === 1 && + expr.arguments[0].type === "ThisExpression" && + expr.callee.body.body && + expr.callee.body.body.length === 1 && + expr.callee.body.body[0].type === "ReturnStatement" && + expr.callee.body.body[0].argument && + expr.callee.body.body[0].argument.type === "FunctionExpression" + ) { + return { + fn: expr.callee.body.body[0].argument, + expressions: [], + needThis: true + }; + } +}; /***/ }), -/***/ 98441: +/***/ 55207: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); +const { UsageState } = __webpack_require__(63686); -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -class ChunkPrefetchTriggerRuntimeModule extends RuntimeModule { - /** - * @param {Record} chunkMap map from chunk to - */ - constructor(chunkMap) { - super(`chunk prefetch trigger`, RuntimeModule.STAGE_TRIGGER); - this.chunkMap = chunkMap; +/** + * @param {RuntimeSpec} runtime the runtime + * @param {string[][]} referencedExports list of referenced exports, will be added to + * @param {string[]} prefix export prefix + * @param {ExportInfo=} exportInfo the export info + * @param {boolean} defaultPointsToSelf when true, using default will reference itself + * @param {Set} alreadyVisited already visited export info (to handle circular reexports) + */ +const processExportInfo = ( + runtime, + referencedExports, + prefix, + exportInfo, + defaultPointsToSelf = false, + alreadyVisited = new Set() +) => { + if (!exportInfo) { + referencedExports.push(prefix); + return; } - - /** - * @returns {string} runtime code - */ - generate() { - const { chunkMap } = this; - const { runtimeTemplate } = this.compilation; - const body = [ - "var chunks = chunkToChildrenMap[chunkId];", - `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.prefetchChunk});` - ]; - return Template.asString([ - Template.asString([ - `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, - `${ - RuntimeGlobals.ensureChunkHandlers - }.prefetch = ${runtimeTemplate.expressionFunction( - `Promise.all(promises).then(${runtimeTemplate.basicFunction( - "", - body - )})`, - "chunkId, promises" - )};` - ]) - ]); + const used = exportInfo.getUsed(runtime); + if (used === UsageState.Unused) return; + if (alreadyVisited.has(exportInfo)) { + referencedExports.push(prefix); + return; } -} - -module.exports = ChunkPrefetchTriggerRuntimeModule; + alreadyVisited.add(exportInfo); + if ( + used !== UsageState.OnlyPropertiesUsed || + !exportInfo.exportsInfo || + exportInfo.exportsInfo.otherExportsInfo.getUsed(runtime) !== + UsageState.Unused + ) { + alreadyVisited.delete(exportInfo); + referencedExports.push(prefix); + return; + } + const exportsInfo = exportInfo.exportsInfo; + for (const exportInfo of exportsInfo.orderedExports) { + processExportInfo( + runtime, + referencedExports, + defaultPointsToSelf && exportInfo.name === "default" + ? prefix + : prefix.concat(exportInfo.name), + exportInfo, + false, + alreadyVisited + ); + } + alreadyVisited.delete(exportInfo); +}; +module.exports = processExportInfo; /***/ }), -/***/ 56236: +/***/ 32277: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); +const ExternalsPlugin = __webpack_require__(6652); -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../Compiler")} Compiler */ -class ChunkPreloadTriggerRuntimeModule extends RuntimeModule { +class ElectronTargetPlugin { /** - * @param {Record} chunkMap map from chunk to chunks + * @param {"main" | "preload" | "renderer"=} context in main, preload or renderer context? */ - constructor(chunkMap) { - super(`chunk preload trigger`, RuntimeModule.STAGE_TRIGGER); - this.chunkMap = chunkMap; + constructor(context) { + this._context = context; } - /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - const { chunkMap } = this; - const { runtimeTemplate } = this.compilation; - const body = [ - "var chunks = chunkToChildrenMap[chunkId];", - `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.preloadChunk});` - ]; - return Template.asString([ - Template.asString([ - `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, - `${ - RuntimeGlobals.ensureChunkHandlers - }.preload = ${runtimeTemplate.basicFunction("chunkId", body)};` - ]) - ]); + apply(compiler) { + new ExternalsPlugin("node-commonjs", [ + "clipboard", + "crash-reporter", + "electron", + "ipc", + "native-image", + "original-fs", + "screen", + "shell" + ]).apply(compiler); + switch (this._context) { + case "main": + new ExternalsPlugin("node-commonjs", [ + "app", + "auto-updater", + "browser-window", + "content-tracing", + "dialog", + "global-shortcut", + "ipc-main", + "menu", + "menu-item", + "power-monitor", + "power-save-blocker", + "protocol", + "session", + "tray", + "web-contents" + ]).apply(compiler); + break; + case "preload": + case "renderer": + new ExternalsPlugin("node-commonjs", [ + "desktop-capturer", + "ipc-renderer", + "remote", + "web-frame" + ]).apply(compiler); + break; + } } } -module.exports = ChunkPreloadTriggerRuntimeModule; +module.exports = ElectronTargetPlugin; /***/ }), -/***/ 30318: -/***/ (function(module) { +/***/ 22273: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -107607,99 +97873,69 @@ module.exports = ChunkPreloadTriggerRuntimeModule; -/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ +const WebpackError = __webpack_require__(53799); -class BasicEffectRulePlugin { - constructor(ruleProperty, effectType) { - this.ruleProperty = ruleProperty; - this.effectType = effectType || ruleProperty; - } +/** @typedef {import("../Module")} Module */ +class BuildCycleError extends WebpackError { /** - * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler - * @returns {void} + * Creates an instance of ModuleDependencyError. + * @param {Module} module the module starting the cycle */ - apply(ruleSetCompiler) { - ruleSetCompiler.hooks.rule.tap( - "BasicEffectRulePlugin", - (path, rule, unhandledProperties, result, references) => { - if (unhandledProperties.has(this.ruleProperty)) { - unhandledProperties.delete(this.ruleProperty); - - const value = rule[this.ruleProperty]; - - result.effects.push({ - type: this.effectType, - value - }); - } - } + constructor(module) { + super( + "There is a circular build dependency, which makes it impossible to create this module" ); + + this.name = "BuildCycleError"; + this.module = module; } } -module.exports = BasicEffectRulePlugin; +module.exports = BuildCycleError; /***/ }), -/***/ 94215: -/***/ (function(module) { +/***/ 5294: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ -/** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */ +const RuntimeModule = __webpack_require__(16963); -class BasicMatcherRulePlugin { - constructor(ruleProperty, dataProperty, invert) { - this.ruleProperty = ruleProperty; - this.dataProperty = dataProperty || ruleProperty; - this.invert = invert || false; +class ExportWebpackRequireRuntimeModule extends RuntimeModule { + constructor() { + super("export webpack runtime", RuntimeModule.STAGE_ATTACH); } /** - * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler - * @returns {void} + * @returns {boolean} true, if the runtime module should get it's own scope */ - apply(ruleSetCompiler) { - ruleSetCompiler.hooks.rule.tap( - "BasicMatcherRulePlugin", - (path, rule, unhandledProperties, result) => { - if (unhandledProperties.has(this.ruleProperty)) { - unhandledProperties.delete(this.ruleProperty); - const value = rule[this.ruleProperty]; - const condition = ruleSetCompiler.compileCondition( - `${path}.${this.ruleProperty}`, - value - ); - const fn = condition.fn; - result.conditions.push({ - property: this.dataProperty, - matchWhenEmpty: this.invert - ? !condition.matchWhenEmpty - : condition.matchWhenEmpty, - fn: this.invert ? v => !fn(v) : fn - }); - } - } - ); + shouldIsolate() { + return false; + } + + /** + * @returns {string} runtime code + */ + generate() { + return "export default __webpack_require__;"; } } -module.exports = BasicMatcherRulePlugin; +module.exports = ExportWebpackRequireRuntimeModule; /***/ }), -/***/ 72021: -/***/ (function(module) { +/***/ 68927: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -107709,51 +97945,206 @@ module.exports = BasicMatcherRulePlugin; -/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ -/** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */ +const { ConcatSource } = __webpack_require__(51255); +const { RuntimeGlobals } = __webpack_require__(91919); +const HotUpdateChunk = __webpack_require__(9597); +const Template = __webpack_require__(39722); +const { getAllChunks } = __webpack_require__(91145); +const { + getCompilationHooks, + getChunkFilenameTemplate +} = __webpack_require__(89464); +const { updateHashForEntryStartup } = __webpack_require__(98124); -class ObjectMatcherRulePlugin { - constructor(ruleProperty, dataProperty) { - this.ruleProperty = ruleProperty; - this.dataProperty = dataProperty || ruleProperty; - } +/** @typedef {import("../Compiler")} Compiler */ +class ModuleChunkFormatPlugin { /** - * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply(ruleSetCompiler) { - const { ruleProperty, dataProperty } = this; - ruleSetCompiler.hooks.rule.tap( - "ObjectMatcherRulePlugin", - (path, rule, unhandledProperties, result) => { - if (unhandledProperties.has(ruleProperty)) { - unhandledProperties.delete(ruleProperty); - const value = rule[ruleProperty]; - for (const property of Object.keys(value)) { - const nestedDataProperties = property.split("."); - const condition = ruleSetCompiler.compileCondition( - `${path}.${ruleProperty}.${property}`, - value[property] + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "ModuleChunkFormatPlugin", + compilation => { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + "ModuleChunkFormatPlugin", + (chunk, set) => { + if (chunk.hasRuntime()) return; + if (compilation.chunkGraph.getNumberOfEntryModules(chunk) > 0) { + set.add(RuntimeGlobals.require); + set.add(RuntimeGlobals.startupEntrypoint); + set.add(RuntimeGlobals.externalInstallChunk); + } + } + ); + const hooks = getCompilationHooks(compilation); + hooks.renderChunk.tap( + "ModuleChunkFormatPlugin", + (modules, renderContext) => { + const { chunk, chunkGraph, runtimeTemplate } = renderContext; + const hotUpdateChunk = + chunk instanceof HotUpdateChunk ? chunk : null; + const source = new ConcatSource(); + if (hotUpdateChunk) { + throw new Error( + "HMR is not implemented for module chunk format yet" + ); + } else { + source.add(`export const id = ${JSON.stringify(chunk.id)};\n`); + source.add(`export const ids = ${JSON.stringify(chunk.ids)};\n`); + source.add(`export const modules = `); + source.add(modules); + source.add(`;\n`); + const runtimeModules = + chunkGraph.getChunkRuntimeModulesInOrder(chunk); + if (runtimeModules.length > 0) { + source.add("export const runtime =\n"); + source.add( + Template.renderChunkRuntimeModules( + runtimeModules, + renderContext + ) + ); + } + const entries = Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ); + if (entries.length > 0) { + const runtimeChunk = entries[0][1].getRuntimeChunk(); + const currentOutputName = compilation + .getPath( + getChunkFilenameTemplate(chunk, compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ) + .split("/"); + + // remove filename, we only need the directory + currentOutputName.pop(); + + const getRelativePath = chunk => { + const baseOutputName = currentOutputName.slice(); + const chunkOutputName = compilation + .getPath( + getChunkFilenameTemplate( + chunk, + compilation.outputOptions + ), + { + chunk: chunk, + contentHashType: "javascript" + } + ) + .split("/"); + + // remove common parts + while ( + baseOutputName.length > 0 && + chunkOutputName.length > 0 && + baseOutputName[0] === chunkOutputName[0] + ) { + baseOutputName.shift(); + chunkOutputName.shift(); + } + // create final path + return ( + (baseOutputName.length > 0 + ? "../".repeat(baseOutputName.length) + : "./") + chunkOutputName.join("/") + ); + }; + + const entrySource = new ConcatSource(); + entrySource.add(source); + entrySource.add(";\n\n// load runtime\n"); + entrySource.add( + `import __webpack_require__ from ${JSON.stringify( + getRelativePath(runtimeChunk) + )};\n` + ); + + const startupSource = new ConcatSource(); + startupSource.add( + `var __webpack_exec__ = ${runtimeTemplate.returningFunction( + `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)`, + "moduleId" + )}\n` + ); + + const loadedChunks = new Set(); + let index = 0; + for (let i = 0; i < entries.length; i++) { + const [module, entrypoint] = entries[i]; + const final = i + 1 === entries.length; + const moduleId = chunkGraph.getModuleId(module); + const chunks = getAllChunks( + entrypoint, + runtimeChunk, + undefined + ); + for (const chunk of chunks) { + if (loadedChunks.has(chunk)) continue; + loadedChunks.add(chunk); + startupSource.add( + `import * as __webpack_chunk_${index}__ from ${JSON.stringify( + getRelativePath(chunk) + )};\n` + ); + startupSource.add( + `${RuntimeGlobals.externalInstallChunk}(__webpack_chunk_${index}__);\n` + ); + index++; + } + startupSource.add( + `${ + final ? "var __webpack_exports__ = " : "" + }__webpack_exec__(${JSON.stringify(moduleId)});\n` + ); + } + + entrySource.add( + hooks.renderStartup.call( + startupSource, + entries[entries.length - 1][0], + { + ...renderContext, + inlined: false + } + ) + ); + return entrySource; + } + } + return source; + } + ); + hooks.chunkHash.tap( + "ModuleChunkFormatPlugin", + (chunk, hash, { chunkGraph, runtimeTemplate }) => { + if (chunk.hasRuntime()) return; + hash.update("ModuleChunkFormatPlugin"); + hash.update("1"); + const entries = Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) ); - result.conditions.push({ - property: [dataProperty, ...nestedDataProperties], - matchWhenEmpty: condition.matchWhenEmpty, - fn: condition.fn - }); + updateHashForEntryStartup(hash, chunkGraph, entries, chunk); } - } + ); } ); } } -module.exports = ObjectMatcherRulePlugin; +module.exports = ModuleChunkFormatPlugin; /***/ }), -/***/ 83349: +/***/ 89831: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -107764,384 +98155,315 @@ module.exports = ObjectMatcherRulePlugin; -const { SyncHook } = __webpack_require__(6967); - -/** - * @typedef {Object} RuleCondition - * @property {string | string[]} property - * @property {boolean} matchWhenEmpty - * @property {function(string): boolean} fn - */ - -/** - * @typedef {Object} Condition - * @property {boolean} matchWhenEmpty - * @property {function(string): boolean} fn - */ - -/** - * @typedef {Object} CompiledRule - * @property {RuleCondition[]} conditions - * @property {(Effect|function(object): Effect[])[]} effects - * @property {CompiledRule[]=} rules - * @property {CompiledRule[]=} oneOf - */ - -/** - * @typedef {Object} Effect - * @property {string} type - * @property {any} value - */ +const RuntimeGlobals = __webpack_require__(16475); +const ExportWebpackRequireRuntimeModule = __webpack_require__(5294); +const ModuleChunkLoadingRuntimeModule = __webpack_require__(64747); -/** - * @typedef {Object} RuleSet - * @property {Map} references map of references in the rule set (may grow over time) - * @property {function(object): Effect[]} exec execute the rule set - */ - -class RuleSetCompiler { - constructor(plugins) { - this.hooks = Object.freeze({ - /** @type {SyncHook<[string, object, Set, CompiledRule, Map]>} */ - rule: new SyncHook([ - "path", - "rule", - "unhandledProperties", - "compiledRule", - "references" - ]) - }); - if (plugins) { - for (const plugin of plugins) { - plugin.apply(this); - } - } - } +/** @typedef {import("../Compiler")} Compiler */ +class ModuleChunkLoadingPlugin { /** - * @param {object[]} ruleSet raw user provided rules - * @returns {RuleSet} compiled RuleSet + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - compile(ruleSet) { - const refs = new Map(); - const rules = this.compileRules("ruleSet", ruleSet, refs); - - /** - * @param {object} data data passed in - * @param {CompiledRule} rule the compiled rule - * @param {Effect[]} effects an array where effects are pushed to - * @returns {boolean} true, if the rule has matched - */ - const execRule = (data, rule, effects) => { - for (const condition of rule.conditions) { - const p = condition.property; - if (Array.isArray(p)) { - let current = data; - for (const subProperty of p) { - if ( - current && - typeof current === "object" && - Object.prototype.hasOwnProperty.call(current, subProperty) - ) { - current = current[subProperty]; - } else { - current = undefined; - break; - } - } - if (current !== undefined) { - if (!condition.fn(current)) return false; - continue; - } - } else if (p in data) { - const value = data[p]; - if (value !== undefined) { - if (!condition.fn(value)) return false; - continue; - } - } - if (!condition.matchWhenEmpty) { - return false; - } - } - for (const effect of rule.effects) { - if (typeof effect === "function") { - const returnedEffects = effect(data); - for (const effect of returnedEffects) { - effects.push(effect); - } - } else { - effects.push(effect); - } - } - if (rule.rules) { - for (const childRule of rule.rules) { - execRule(data, childRule, effects); - } - } - if (rule.oneOf) { - for (const childRule of rule.oneOf) { - if (execRule(data, childRule, effects)) { - break; - } - } - } - return true; - }; + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "ModuleChunkLoadingPlugin", + compilation => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const chunkLoading = + (options && options.chunkLoading) || globalChunkLoading; + return chunkLoading === "import"; + }; + const onceForChunkSet = new WeakSet(); + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new ModuleChunkLoadingRuntimeModule(set) + ); + }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("ModuleChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap("ModuleChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.externalInstallChunk) + .tap("ModuleChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap("ModuleChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.externalInstallChunk) + .tap("ModuleChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + compilation.addRuntimeModule( + chunk, + new ExportWebpackRequireRuntimeModule() + ); + }); - return { - references: refs, - exec: data => { - /** @type {Effect[]} */ - const effects = []; - for (const rule of rules) { - execRule(data, rule, effects); - } - return effects; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("ModuleChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.getChunkScriptFilename); + }); } - }; - } - - /** - * @param {string} path current path - * @param {object[]} rules the raw rules provided by user - * @param {Map} refs references - * @returns {CompiledRule[]} rules - */ - compileRules(path, rules, refs) { - return rules.map((rule, i) => - this.compileRule(`${path}[${i}]`, rule, refs) ); } +} - /** - * @param {string} path current path - * @param {object} rule the raw rule provided by user - * @param {Map} refs references - * @returns {CompiledRule} normalized and compiled rule for processing - */ - compileRule(path, rule, refs) { - const unhandledProperties = new Set( - Object.keys(rule).filter(key => rule[key] !== undefined) - ); +module.exports = ModuleChunkLoadingPlugin; - /** @type {CompiledRule} */ - const compiledRule = { - conditions: [], - effects: [], - rules: undefined, - oneOf: undefined - }; - this.hooks.rule.call(path, rule, unhandledProperties, compiledRule, refs); +/***/ }), - if (unhandledProperties.has("rules")) { - unhandledProperties.delete("rules"); - const rules = rule.rules; - if (!Array.isArray(rules)) - throw this.error(path, rules, "Rule.rules must be an array of rules"); - compiledRule.rules = this.compileRules(`${path}.rules`, rules, refs); - } +/***/ 64747: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (unhandledProperties.has("oneOf")) { - unhandledProperties.delete("oneOf"); - const oneOf = rule.oneOf; - if (!Array.isArray(oneOf)) - throw this.error(path, oneOf, "Rule.oneOf must be an array of rules"); - compiledRule.oneOf = this.compileRules(`${path}.oneOf`, oneOf, refs); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - if (unhandledProperties.size > 0) { - throw this.error( - path, - rule, - `Properties ${Array.from(unhandledProperties).join(", ")} are unknown` - ); - } - return compiledRule; - } - /** - * @param {string} path current path - * @param {any} condition user provided condition value - * @returns {Condition} compiled condition - */ - compileCondition(path, condition) { - if (condition === "") { - return { - matchWhenEmpty: true, - fn: str => str === "" - }; - } - if (!condition) { - throw this.error( - path, - condition, - "Expected condition but got falsy value" - ); - } - if (typeof condition === "string") { - return { - matchWhenEmpty: condition.length === 0, - fn: str => typeof str === "string" && str.startsWith(condition) - }; - } - if (typeof condition === "function") { - try { - return { - matchWhenEmpty: condition(""), - fn: condition - }; - } catch (err) { - throw this.error( - path, - condition, - "Evaluation of condition function threw error" - ); - } - } - if (condition instanceof RegExp) { - return { - matchWhenEmpty: condition.test(""), - fn: v => typeof v === "string" && condition.test(v) - }; - } - if (Array.isArray(condition)) { - const items = condition.map((c, i) => - this.compileCondition(`${path}[${i}]`, c) - ); - return this.combineConditionsOr(items); - } +const { SyncWaterfallHook } = __webpack_require__(41242); +const Compilation = __webpack_require__(85720); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); +const { + getChunkFilenameTemplate, + chunkHasJs +} = __webpack_require__(89464); +const { getInitialChunkIds } = __webpack_require__(98124); +const compileBooleanMatcher = __webpack_require__(29404); +const { getUndoPath } = __webpack_require__(82186); - if (typeof condition !== "object") { - throw this.error( - path, - condition, - `Unexpected ${typeof condition} when condition was expected` - ); - } +/** @typedef {import("../Chunk")} Chunk */ - const conditions = []; - for (const key of Object.keys(condition)) { - const value = condition[key]; - switch (key) { - case "or": - if (value) { - if (!Array.isArray(value)) { - throw this.error( - `${path}.or`, - condition.and, - "Expected array of conditions" - ); - } - conditions.push(this.compileCondition(`${path}.or`, value)); - } - break; - case "and": - if (value) { - if (!Array.isArray(value)) { - throw this.error( - `${path}.and`, - condition.and, - "Expected array of conditions" - ); - } - let i = 0; - for (const item of value) { - conditions.push(this.compileCondition(`${path}.and[${i}]`, item)); - i++; - } - } - break; - case "not": - if (value) { - const matcher = this.compileCondition(`${path}.not`, value); - const fn = matcher.fn; - conditions.push({ - matchWhenEmpty: !matcher.matchWhenEmpty, - fn: v => !fn(v) - }); - } - break; - default: - throw this.error( - `${path}.${key}`, - condition[key], - `Unexpected property ${key} in condition` - ); - } - } - if (conditions.length === 0) { - throw this.error( - path, - condition, - "Expected condition, but got empty thing" - ); - } - return this.combineConditionsAnd(conditions); - } +/** + * @typedef {Object} JsonpCompilationPluginHooks + * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload + * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); +class ModuleChunkLoadingRuntimeModule extends RuntimeModule { /** - * @param {Condition[]} conditions some conditions - * @returns {Condition} merged condition + * @param {Compilation} compilation the compilation + * @returns {JsonpCompilationPluginHooks} hooks */ - combineConditionsOr(conditions) { - if (conditions.length === 0) { - return { - matchWhenEmpty: false, - fn: () => false - }; - } else if (conditions.length === 1) { - return conditions[0]; - } else { - return { - matchWhenEmpty: conditions.some(c => c.matchWhenEmpty), - fn: v => conditions.some(c => c.fn(v)) + 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 = { + linkPreload: new SyncWaterfallHook(["source", "chunk"]), + linkPrefetch: new SyncWaterfallHook(["source", "chunk"]) }; + compilationHooksMap.set(compilation, hooks); } + return hooks; } - /** - * @param {Condition[]} conditions some conditions - * @returns {Condition} merged condition - */ - combineConditionsAnd(conditions) { - if (conditions.length === 0) { - return { - matchWhenEmpty: false, - fn: () => false - }; - } else if (conditions.length === 1) { - return conditions[0]; - } else { - return { - matchWhenEmpty: conditions.every(c => c.matchWhenEmpty), - fn: v => conditions.every(c => c.fn(v)) - }; - } + constructor(runtimeRequirements) { + super("import chunk loading", RuntimeModule.STAGE_ATTACH); + this._runtimeRequirements = runtimeRequirements; } /** - * @param {string} path current path - * @param {any} value value at the error location - * @param {string} message message explaining the problem - * @returns {Error} an error object + * @returns {string} runtime code */ - error(path, value, message) { - return new Error( - `Compiling RuleSet failed: ${message} (at ${path}: ${value})` + generate() { + const { compilation, chunk } = this; + const { + runtimeTemplate, + chunkGraph, + outputOptions: { importFunctionName, importMetaName } + } = compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI); + const withExternalInstallChunk = this._runtimeRequirements.has( + RuntimeGlobals.externalInstallChunk + ); + const withLoading = this._runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withOnChunkLoad = this._runtimeRequirements.has( + RuntimeGlobals.onChunksLoaded + ); + const withHmr = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers ); + const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); + const hasJsMatcher = compileBooleanMatcher(conditionMap); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + + const outputName = this.compilation.getPath( + getChunkFilenameTemplate(chunk, this.compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath( + outputName, + this.compilation.outputOptions.path, + true + ); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_module` + : undefined; + + return Template.asString([ + withBaseURI + ? Template.asString([ + `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify( + rootOutputDir + )}, ${importMetaName}.url);` + ]) + : "// no baseURI", + "", + "// object to store loaded and loading chunks", + "// undefined = chunk not loaded, null = chunk preloaded/prefetched", + "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join( + ",\n" + ) + ), + "};", + "", + withLoading || withExternalInstallChunk + ? `var installChunk = ${runtimeTemplate.basicFunction("data", [ + runtimeTemplate.destructureObject( + ["ids", "modules", "runtime"], + "data" + ), + '// add "modules" to the modules object,', + '// then flag all "ids" as loaded and fire callback', + "var moduleId, chunkId, i = 0;", + "for(moduleId in modules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(modules, moduleId)) {`, + Template.indent( + `${RuntimeGlobals.moduleFactories}[moduleId] = modules[moduleId];` + ), + "}" + ]), + "}", + "if(runtime) runtime(__webpack_require__);", + "for(;i < ids.length; i++) {", + Template.indent([ + "chunkId = ids[i];", + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`, + Template.indent("installedChunks[chunkId][0]();"), + "}", + "installedChunks[ids[i]] = 0;" + ]), + "}", + withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" + ])}` + : "// no install chunk", + "", + withLoading + ? Template.asString([ + `${fn}.j = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasJsMatcher !== false + ? Template.indent([ + "// import() chunk loading for javascript", + `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + "", + '// a Promise means "currently loading".', + "if(installedChunkData) {", + Template.indent([ + "promises.push(installedChunkData[1]);" + ]), + "} else {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent([ + "// setup Promise in chunk cache", + `var promise = ${importFunctionName}(${JSON.stringify( + rootOutputDir + )} + ${ + RuntimeGlobals.getChunkScriptFilename + }(chunkId)).then(installChunk, ${runtimeTemplate.basicFunction( + "e", + [ + "if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;", + "throw e;" + ] + )});`, + `var promise = Promise.race([promise, new Promise(${runtimeTemplate.expressionFunction( + `installedChunkData = installedChunks[chunkId] = [resolve]`, + "resolve" + )})])`, + `promises.push(installedChunkData[1] = promise);` + ]), + "} else installedChunks[chunkId] = 0;" + ]), + "}" + ]), + "}" + ]) + : Template.indent(["installedChunks[chunkId] = 0;"]) + )};` + ]) + : "// no chunk on demand loading", + "", + withExternalInstallChunk + ? Template.asString([ + `${RuntimeGlobals.externalInstallChunk} = installChunk;` + ]) + : "// no external install chunk", + "", + withOnChunkLoad + ? `${ + RuntimeGlobals.onChunksLoaded + }.j = ${runtimeTemplate.returningFunction( + "installedChunks[chunkId] === 0", + "chunkId" + )};` + : "// no on chunks loaded" + ]); } } -module.exports = RuleSetCompiler; +module.exports = ModuleChunkLoadingRuntimeModule; /***/ }), -/***/ 84977: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 16734: +/***/ (function(module) { "use strict"; /* @@ -108151,1889 +98473,2068 @@ module.exports = RuleSetCompiler; -const util = __webpack_require__(73837); - -/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ -/** @typedef {import("./RuleSetCompiler").Effect} Effect */ - -class UseEffectRulePlugin { - /** - * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler - * @returns {void} - */ - apply(ruleSetCompiler) { - ruleSetCompiler.hooks.rule.tap( - "UseEffectRulePlugin", - (path, rule, unhandledProperties, result, references) => { - const conflictWith = (property, correctProperty) => { - if (unhandledProperties.has(property)) { - throw ruleSetCompiler.error( - `${path}.${property}`, - rule[property], - `A Rule must not have a '${property}' property when it has a '${correctProperty}' property` - ); - } - }; - - if (unhandledProperties.has("use")) { - unhandledProperties.delete("use"); - unhandledProperties.delete("enforce"); - - conflictWith("loader", "use"); - conflictWith("options", "use"); - - const use = rule.use; - const enforce = rule.enforce; - - const type = enforce ? `use-${enforce}` : "use"; - - /** - * - * @param {string} path options path - * @param {string} defaultIdent default ident when none is provided - * @param {object} item user provided use value - * @returns {Effect|function(any): Effect[]} effect - */ - const useToEffect = (path, defaultIdent, item) => { - if (typeof item === "function") { - return data => useToEffectsWithoutIdent(path, item(data)); - } else { - return useToEffectRaw(path, defaultIdent, item); - } - }; - - /** - * - * @param {string} path options path - * @param {string} defaultIdent default ident when none is provided - * @param {object} item user provided use value - * @returns {Effect} effect - */ - const useToEffectRaw = (path, defaultIdent, item) => { - if (typeof item === "string") { - return { - type, - value: { - loader: item, - options: undefined, - ident: undefined - } - }; - } else { - const loader = item.loader; - const options = item.options; - let ident = item.ident; - if (options && typeof options === "object") { - if (!ident) ident = defaultIdent; - references.set(ident, options); - } - if (typeof options === "string") { - util.deprecate( - () => {}, - `Using a string as loader options is deprecated (${path}.options)`, - "DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING" - )(); - } - return { - type: enforce ? `use-${enforce}` : "use", - value: { - loader, - options, - ident - } - }; - } - }; - - /** - * @param {string} path options path - * @param {any} items user provided use value - * @returns {Effect[]} effects - */ - const useToEffectsWithoutIdent = (path, items) => { - if (Array.isArray(items)) { - return items.map((item, idx) => - useToEffectRaw(`${path}[${idx}]`, "[[missing ident]]", item) - ); - } - return [useToEffectRaw(path, "[[missing ident]]", items)]; - }; - - /** - * @param {string} path current path - * @param {any} items user provided use value - * @returns {(Effect|function(any): Effect[])[]} effects - */ - const useToEffects = (path, items) => { - if (Array.isArray(items)) { - return items.map((item, idx) => { - const subPath = `${path}[${idx}]`; - return useToEffect(subPath, subPath, item); - }); - } - return [useToEffect(path, path, items)]; - }; - - if (typeof use === "function") { - result.effects.push(data => - useToEffectsWithoutIdent(`${path}.use`, use(data)) - ); - } else { - for (const effect of useToEffects(`${path}.use`, use)) { - result.effects.push(effect); - } - } - } - - if (unhandledProperties.has("loader")) { - unhandledProperties.delete("loader"); - unhandledProperties.delete("options"); - unhandledProperties.delete("enforce"); - - const loader = rule.loader; - const options = rule.options; - const enforce = rule.enforce; - - if (loader.includes("!")) { - throw ruleSetCompiler.error( - `${path}.loader`, - loader, - "Exclamation mark separated loader lists has been removed in favor of the 'use' property with arrays" - ); - } - - if (loader.includes("?")) { - throw ruleSetCompiler.error( - `${path}.loader`, - loader, - "Query arguments on 'loader' has been removed in favor of the 'options' property" - ); - } +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Dependency").SourcePosition} SourcePosition */ - if (typeof options === "string") { - util.deprecate( - () => {}, - `Using a string as loader options is deprecated (${path}.options)`, - "DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING" - )(); - } +/** + * @param {SourcePosition} pos position + * @returns {string} formatted position + */ +const formatPosition = pos => { + if (pos && typeof pos === "object") { + if ("line" in pos && "column" in pos) { + return `${pos.line}:${pos.column}`; + } else if ("line" in pos) { + return `${pos.line}:?`; + } + } + return ""; +}; - const ident = - options && typeof options === "object" ? path : undefined; - references.set(ident, options); - result.effects.push({ - type: enforce ? `use-${enforce}` : "use", - value: { - loader, - options, - ident - } - }); - } +/** + * @param {DependencyLocation} loc location + * @returns {string} formatted location + */ +const formatLocation = loc => { + if (loc && typeof loc === "object") { + if ("start" in loc && loc.start && "end" in loc && loc.end) { + if ( + typeof loc.start === "object" && + typeof loc.start.line === "number" && + typeof loc.end === "object" && + typeof loc.end.line === "number" && + typeof loc.end.column === "number" && + loc.start.line === loc.end.line + ) { + return `${formatPosition(loc.start)}-${loc.end.column}`; + } else if ( + typeof loc.start === "object" && + typeof loc.start.line === "number" && + typeof loc.start.column !== "number" && + typeof loc.end === "object" && + typeof loc.end.line === "number" && + typeof loc.end.column !== "number" + ) { + return `${loc.start.line}-${loc.end.line}`; + } else { + return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; } - ); + } + if ("start" in loc && loc.start) { + return formatPosition(loc.start); + } + if ("name" in loc && "index" in loc) { + return `${loc.name}[${loc.index}]`; + } + if ("name" in loc) { + return loc.name; + } } + return ""; +}; - useItemToEffects(path, item) {} -} - -module.exports = UseEffectRulePlugin; +module.exports = formatLocation; /***/ }), -/***/ 63672: +/***/ 27899: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const HelperRuntimeModule = __webpack_require__(82444); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); -class AsyncModuleRuntimeModule extends HelperRuntimeModule { +class HotModuleReplacementRuntimeModule extends RuntimeModule { constructor() { - super("async module"); + super("hot module replacement", RuntimeModule.STAGE_BASIC); } - /** * @returns {string} runtime code */ generate() { - const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.asyncModule; - return Template.asString([ - 'var webpackThen = typeof Symbol === "function" ? Symbol("webpack then") : "__webpack_then__";', - 'var webpackExports = typeof Symbol === "function" ? Symbol("webpack exports") : "__webpack_exports__";', - `var completeQueue = ${runtimeTemplate.basicFunction("queue", [ - "if(queue) {", - Template.indent([ - `queue.forEach(${runtimeTemplate.expressionFunction( - "fn.r--", - "fn" - )});`, - `queue.forEach(${runtimeTemplate.expressionFunction( - "fn.r-- ? fn.r++ : fn()", - "fn" - )});` - ]), - "}" - ])}`, - `var completeFunction = ${runtimeTemplate.expressionFunction( - "!--fn.r && fn()", - "fn" - )};`, - `var queueFunction = ${runtimeTemplate.expressionFunction( - "queue ? queue.push(fn) : completeFunction(fn)", - "queue, fn" - )};`, - `var wrapDeps = ${runtimeTemplate.returningFunction( - `deps.map(${runtimeTemplate.basicFunction("dep", [ - 'if(dep !== null && typeof dep === "object") {', - Template.indent([ - "if(dep[webpackThen]) return dep;", - "if(dep.then) {", - Template.indent([ - "var queue = [];", - `dep.then(${runtimeTemplate.basicFunction("r", [ - "obj[webpackExports] = r;", - "completeQueue(queue);", - "queue = 0;" - ])});`, - `var obj = {}; - obj[webpackThen] = ${runtimeTemplate.expressionFunction( - "queueFunction(queue, fn), dep['catch'](reject)", - "fn, reject" - )};`, - "return obj;" - ]), - "}" - ]), - "}", - `var ret = {}; - ret[webpackThen] = ${runtimeTemplate.expressionFunction( - "completeFunction(fn)", - "fn" - )}; - ret[webpackExports] = dep; - return ret;` - ])})`, - "deps" - )};`, - `${fn} = ${runtimeTemplate.basicFunction("module, body, hasAwait", [ - "var queue = hasAwait && [];", - "var exports = module.exports;", - "var currentDeps;", - "var outerResolve;", - "var reject;", - "var isEvaluating = true;", - "var nested = false;", - `var whenAll = ${runtimeTemplate.basicFunction( - "deps, onResolve, onReject", - [ - "if (nested) return;", - "nested = true;", - "onResolve.r += deps.length;", - `deps.map(${runtimeTemplate.expressionFunction( - "dep[webpackThen](onResolve, onReject)", - "dep, i" - )});`, - "nested = false;" - ] - )};`, - `var promise = new Promise(${runtimeTemplate.basicFunction( - "resolve, rej", - [ - "reject = rej;", - `outerResolve = ${runtimeTemplate.expressionFunction( - "resolve(exports), completeQueue(queue), queue = 0" - )};` - ] - )});`, - "promise[webpackExports] = exports;", - `promise[webpackThen] = ${runtimeTemplate.basicFunction( - "fn, rejectFn", - [ - "if (isEvaluating) { return completeFunction(fn); }", - "if (currentDeps) whenAll(currentDeps, fn, rejectFn);", - "queueFunction(queue, fn);", - "promise['catch'](rejectFn);" - ] - )};`, - "module.exports = promise;", - `body(${runtimeTemplate.basicFunction("deps", [ - "if(!deps) return outerResolve();", - "currentDeps = wrapDeps(deps);", - "var fn, result;", - `var promise = new Promise(${runtimeTemplate.basicFunction( - "resolve, reject", - [ - `fn = ${runtimeTemplate.expressionFunction( - `resolve(result = currentDeps.map(${runtimeTemplate.returningFunction( - "d[webpackExports]", - "d" - )}))` - )};`, - "fn.r = 0;", - "whenAll(currentDeps, fn, reject);" - ] - )});`, - "return fn.r ? promise : result;" - ])}).then(outerResolve, reject);`, - "isEvaluating = false;" - ])};` - ]); + return Template.getFunctionContent( + require('./HotModuleReplacement.runtime.js') + ) + .replace(/\$getFullHash\$/g, RuntimeGlobals.getFullHash) + .replace( + /\$interceptModuleExecution\$/g, + RuntimeGlobals.interceptModuleExecution + ) + .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) + .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) + .replace(/\$hmrDownloadManifest\$/g, RuntimeGlobals.hmrDownloadManifest) + .replace( + /\$hmrInvalidateModuleHandlers\$/g, + RuntimeGlobals.hmrInvalidateModuleHandlers + ) + .replace( + /\$hmrDownloadUpdateHandlers\$/g, + RuntimeGlobals.hmrDownloadUpdateHandlers + ); } } -module.exports = AsyncModuleRuntimeModule; +module.exports = HotModuleReplacementRuntimeModule; /***/ }), -/***/ 66532: +/***/ 79040: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ +const { RawSource } = __webpack_require__(51255); +const AsyncDependenciesBlock = __webpack_require__(47736); +const Dependency = __webpack_require__(54912); +const Module = __webpack_require__(73208); +const ModuleFactory = __webpack_require__(51010); const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); -const JavascriptModulesPlugin = __webpack_require__(89464); -const { getUndoPath } = __webpack_require__(82186); +const Template = __webpack_require__(39722); +const CommonJsRequireDependency = __webpack_require__(21264); +const { registerNotSerializable } = __webpack_require__(8282); -class AutoPublicPathRuntimeModule extends RuntimeModule { - constructor() { - super("publicPath", RuntimeModule.STAGE_BASIC); - } +/** @typedef {import("../../declarations/WebpackOptions")} WebpackOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../dependencies/HarmonyImportDependency")} HarmonyImportDependency */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ - /** - * @returns {string} runtime code - */ - generate() { - const { compilation } = this; - const { scriptType, importMetaName, path } = compilation.outputOptions; - const chunkName = compilation.getPath( - JavascriptModulesPlugin.getChunkFilenameTemplate( - this.chunk, - compilation.outputOptions - ), - { - chunk: this.chunk, - contentHashType: "javascript" - } - ); - const undoPath = getUndoPath(chunkName, path, false); +/** + * @typedef {Object} BackendApi + * @property {function(Error=): void} dispose + * @property {function(Module): { client: string, data: string, active: boolean }} module + */ - return Template.asString([ - "var scriptUrl;", - scriptType === "module" - ? `if (typeof ${importMetaName}.url === "string") scriptUrl = ${importMetaName}.url` - : Template.asString([ - `if (${RuntimeGlobals.global}.importScripts) scriptUrl = ${RuntimeGlobals.global}.location + "";`, - `var document = ${RuntimeGlobals.global}.document;`, - "if (!scriptUrl && document) {", - Template.indent([ - `if (document.currentScript)`, - Template.indent(`scriptUrl = document.currentScript.src`), - "if (!scriptUrl) {", - Template.indent([ - 'var scripts = document.getElementsByTagName("script");', - "if(scripts.length) scriptUrl = scripts[scripts.length - 1].src" - ]), - "}" - ]), - "}" - ]), - "// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration", - '// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.', - 'if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");', - 'scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\\?.*$/, "").replace(/\\/[^\\/]+$/, "/");', - !undoPath - ? `${RuntimeGlobals.publicPath} = scriptUrl;` - : `${RuntimeGlobals.publicPath} = scriptUrl + ${JSON.stringify( - undoPath - )};` - ]); +const HMR_DEPENDENCY_TYPES = new Set([ + "import.meta.webpackHot.accept", + "import.meta.webpackHot.decline", + "module.hot.accept", + "module.hot.decline" +]); + +/** + * @param {undefined|string|RegExp|Function} test test option + * @param {Module} module the module + * @returns {boolean} true, if the module should be selected + */ +const checkTest = (test, module) => { + if (test === undefined) return true; + if (typeof test === "function") { + return test(module); } -} + if (typeof test === "string") { + const name = module.nameForCondition(); + return name && name.startsWith(test); + } + if (test instanceof RegExp) { + const name = module.nameForCondition(); + return name && test.test(name); + } + return false; +}; -module.exports = AutoPublicPathRuntimeModule; +const TYPES = new Set(["javascript"]); +class LazyCompilationDependency extends Dependency { + constructor(proxyModule) { + super(); + this.proxyModule = proxyModule; + } -/***/ }), + get category() { + return "esm"; + } -/***/ 84519: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + get type() { + return "lazy import()"; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return this.proxyModule.originalModule.identifier(); + } +} +registerNotSerializable(LazyCompilationDependency); +class LazyCompilationProxyModule extends Module { + constructor(context, originalModule, request, client, data, active) { + super("lazy-compilation-proxy", context, originalModule.layer); + this.originalModule = originalModule; + this.request = request; + this.client = client; + this.data = data; + this.active = active; + } -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `lazy-compilation-proxy|${this.originalModule.identifier()}`; + } -class ChunkNameRuntimeModule extends RuntimeModule { /** - * @param {string} chunkName the chunk's name + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module */ - constructor(chunkName) { - super("chunkName"); - this.chunkName = chunkName; + readableIdentifier(requestShortener) { + return `lazy-compilation-proxy ${this.originalModule.readableIdentifier( + requestShortener + )}`; } /** - * @returns {string} runtime code + * 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} */ - generate() { - return `${RuntimeGlobals.chunkName} = ${JSON.stringify(this.chunkName)};`; + updateCacheModule(module) { + super.updateCacheModule(module); + const m = /** @type {LazyCompilationProxyModule} */ (module); + this.originalModule = m.originalModule; + this.request = m.request; + this.client = m.client; + this.data = m.data; + this.active = m.active; } -} -module.exports = ChunkNameRuntimeModule; + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `${this.originalModule.libIdent(options)}!lazy-compilation-proxy`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + callback(null, !this.buildInfo || this.buildInfo.active !== this.active); + } + /** + * @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.buildInfo = { + active: this.active + }; + /** @type {BuildMeta} */ + this.buildMeta = {}; + this.clearDependenciesAndBlocks(); + const dep = new CommonJsRequireDependency(this.client); + this.addDependency(dep); + if (this.active) { + const dep = new LazyCompilationDependency(this); + const block = new AsyncDependenciesBlock({}); + block.addDependency(dep); + this.addBlock(block); + } + callback(); + } -/***/ }), + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; + } -/***/ 44793: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @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 200; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ runtimeTemplate, chunkGraph, moduleGraph }) { + const sources = new Map(); + const runtimeRequirements = new Set(); + runtimeRequirements.add(RuntimeGlobals.module); + const clientDep = /** @type {CommonJsRequireDependency} */ ( + this.dependencies[0] + ); + const clientModule = moduleGraph.getModule(clientDep); + const block = this.blocks[0]; + const client = Template.asString([ + `var client = ${runtimeTemplate.moduleExports({ + module: clientModule, + chunkGraph, + request: clientDep.userRequest, + runtimeRequirements + })}`, + `var data = ${JSON.stringify(this.data)};` + ]); + const keepActive = Template.asString([ + `var dispose = client.keepAlive({ data: data, active: ${JSON.stringify( + !!block + )}, module: module, onError: onError });` + ]); + let source; + if (block) { + const dep = block.dependencies[0]; + const module = moduleGraph.getModule(dep); + source = Template.asString([ + client, + `module.exports = ${runtimeTemplate.moduleNamespacePromise({ + chunkGraph, + block, + module, + request: this.request, + strict: false, // TODO this should be inherited from the original module + message: "import()", + runtimeRequirements + })};`, + "if (module.hot) {", + Template.indent([ + "module.hot.accept();", + `module.hot.accept(${JSON.stringify( + chunkGraph.getModuleId(module) + )}, function() { module.hot.invalidate(); });`, + "module.hot.dispose(function(data) { delete data.resolveSelf; dispose(data); });", + "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);" + ]), + "}", + "function onError() { /* ignore */ }", + keepActive + ]); + } else { + source = Template.asString([ + client, + "var resolveSelf, onError;", + `module.exports = new Promise(function(resolve, reject) { resolveSelf = resolve; onError = reject; });`, + "if (module.hot) {", + Template.indent([ + "module.hot.accept();", + "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);", + "module.hot.dispose(function(data) { data.resolveSelf = resolveSelf; dispose(data); });" + ]), + "}", + keepActive + ]); + } + sources.set("javascript", new RawSource(source)); + return { + sources, + runtimeRequirements + }; + } + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + super.updateHash(hash, context); + hash.update(this.active ? "active" : ""); + hash.update(JSON.stringify(this.data)); + } +} +registerNotSerializable(LazyCompilationProxyModule); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const HelperRuntimeModule = __webpack_require__(82444); +class LazyCompilationDependencyFactory extends ModuleFactory { + constructor(factory) { + super(); + this._factory = factory; + } -class CompatGetDefaultExportRuntimeModule extends HelperRuntimeModule { - constructor() { - super("compat get default export"); + /** + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * @returns {void} + */ + create(data, callback) { + const dependency = /** @type {LazyCompilationDependency} */ ( + data.dependencies[0] + ); + callback(null, { + module: dependency.proxyModule.originalModule + }); } +} +class LazyCompilationPlugin { /** - * @returns {string} runtime code + * @param {Object} options options + * @param {(function(Compiler, function(Error?, BackendApi?): void): void) | function(Compiler): Promise} options.backend the backend + * @param {boolean} options.entries true, when entries are lazy compiled + * @param {boolean} options.imports true, when import() modules are lazy compiled + * @param {RegExp | string | (function(Module): boolean)} options.test additional filter for lazy compiled entrypoint modules */ - generate() { - const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.compatGetDefaultExport; - return Template.asString([ - "// getDefaultExport function for compatibility with non-harmony modules", - `${fn} = ${runtimeTemplate.basicFunction("module", [ - "var getter = module && module.__esModule ?", - Template.indent([ - `${runtimeTemplate.returningFunction("module['default']")} :`, - `${runtimeTemplate.returningFunction("module")};` - ]), - `${RuntimeGlobals.definePropertyGetters}(getter, { a: getter });`, - "return getter;" - ])};` - ]); + constructor({ backend, entries, imports, test }) { + this.backend = backend; + this.entries = entries; + this.imports = imports; + this.test = test; + } + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + let backend; + compiler.hooks.beforeCompile.tapAsync( + "LazyCompilationPlugin", + (params, callback) => { + if (backend !== undefined) return callback(); + const promise = this.backend(compiler, (err, result) => { + if (err) return callback(err); + backend = result; + callback(); + }); + if (promise && promise.then) { + promise.then(b => { + backend = b; + callback(); + }, callback); + } + } + ); + compiler.hooks.thisCompilation.tap( + "LazyCompilationPlugin", + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.module.tap( + "LazyCompilationPlugin", + (originalModule, createData, resolveData) => { + if ( + resolveData.dependencies.every(dep => + HMR_DEPENDENCY_TYPES.has(dep.type) + ) + ) { + // for HMR only resolving, try to determine if the HMR accept/decline refers to + // an import() or not + const hmrDep = resolveData.dependencies[0]; + const originModule = + compilation.moduleGraph.getParentModule(hmrDep); + const isReferringToDynamicImport = originModule.blocks.some( + block => + block.dependencies.some( + dep => + dep.type === "import()" && + /** @type {HarmonyImportDependency} */ (dep).request === + hmrDep.request + ) + ); + if (!isReferringToDynamicImport) return; + } else if ( + !resolveData.dependencies.every( + dep => + HMR_DEPENDENCY_TYPES.has(dep.type) || + (this.imports && + (dep.type === "import()" || + dep.type === "import() context element")) || + (this.entries && dep.type === "entry") + ) + ) + return; + if ( + /webpack[/\\]hot[/\\]|webpack-dev-server[/\\]client|webpack-hot-middleware[/\\]client/.test( + resolveData.request + ) || + !checkTest(this.test, originalModule) + ) + return; + const moduleInfo = backend.module(originalModule); + if (!moduleInfo) return; + const { client, data, active } = moduleInfo; + + return new LazyCompilationProxyModule( + compiler.context, + originalModule, + resolveData.request, + client, + data, + active + ); + } + ); + compilation.dependencyFactories.set( + LazyCompilationDependency, + new LazyCompilationDependencyFactory() + ); + } + ); + compiler.hooks.shutdown.tapAsync("LazyCompilationPlugin", callback => { + backend.dispose(callback); + }); } } -module.exports = CompatGetDefaultExportRuntimeModule; +module.exports = LazyCompilationPlugin; /***/ }), -/***/ 88234: +/***/ 17781: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); +/** @typedef {import("http").ServerOptions} HttpServerOptions */ +/** @typedef {import("https").ServerOptions} HttpsServerOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LazyCompilationDefaultBackendOptions} LazyCompilationDefaultBackendOptions */ +/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../MainTemplate")} MainTemplate */ +/** + * @callback BackendHandler + * @param {Compiler} compiler compiler + * @param {function((Error | null)=, any=): void} callback callback + * @returns {void} + */ -class CompatRuntimeModule extends RuntimeModule { - constructor() { - super("compat", RuntimeModule.STAGE_ATTACH); - this.fullHash = true; - } +/** + * @param {Omit & { client: NonNullable}} options additional options for the backend + * @returns {BackendHandler} backend + */ +module.exports = options => (compiler, callback) => { + const logger = compiler.getInfrastructureLogger("LazyCompilationBackend"); + const activeModules = new Map(); + const prefix = "/lazy-compilation-using-"; - /** - * @returns {string} runtime code - */ - generate() { - const { chunkGraph, chunk, compilation } = this; - const { - runtimeTemplate, - mainTemplate, - moduleTemplates, - dependencyTemplates - } = compilation; - const bootstrap = mainTemplate.hooks.bootstrap.call( - "", - chunk, - compilation.hash || "XXXX", - moduleTemplates.javascript, - dependencyTemplates - ); - const localVars = mainTemplate.hooks.localVars.call( - "", - chunk, - compilation.hash || "XXXX" - ); - const requireExtensions = mainTemplate.hooks.requireExtensions.call( - "", - chunk, - compilation.hash || "XXXX" - ); - const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); - let requireEnsure = ""; - if (runtimeRequirements.has(RuntimeGlobals.ensureChunk)) { - const requireEnsureHandler = mainTemplate.hooks.requireEnsure.call( - "", - chunk, - compilation.hash || "XXXX", - "chunkId" - ); - if (requireEnsureHandler) { - requireEnsure = `${ - RuntimeGlobals.ensureChunkHandlers - }.compat = ${runtimeTemplate.basicFunction( - "chunkId, promises", - requireEnsureHandler - )};`; + const isHttps = + options.protocol === "https" || + (typeof options.server === "object" && + ("key" in options.server || "pfx" in options.server)); + + const createServer = + typeof options.server === "function" + ? options.server + : (() => { + const http = isHttps ? __webpack_require__(95687) : __webpack_require__(13685); + return http.createServer.bind(http, options.server); + })(); + const listen = + typeof options.listen === "function" + ? options.listen + : server => { + let listen = options.listen; + if (typeof listen === "object" && !("port" in listen)) + listen = { ...listen, port: undefined }; + server.listen(listen); + }; + + const protocol = options.protocol || (isHttps ? "https" : "http"); + + const requestListener = (req, res) => { + const keys = req.url.slice(prefix.length).split("@"); + req.socket.on("close", () => { + setTimeout(() => { + for (const key of keys) { + const oldValue = activeModules.get(key) || 0; + activeModules.set(key, oldValue - 1); + if (oldValue === 1) { + logger.log( + `${key} is no longer in use. Next compilation will skip this module.` + ); + } + } + }, 120000); + }); + req.socket.setNoDelay(true); + res.writeHead(200, { + "content-type": "text/event-stream", + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "*", + "Access-Control-Allow-Headers": "*" + }); + res.write("\n"); + let moduleActivated = false; + for (const key of keys) { + const oldValue = activeModules.get(key) || 0; + activeModules.set(key, oldValue + 1); + if (oldValue === 0) { + logger.log(`${key} is now in use and will be compiled.`); + moduleActivated = true; } } - return [bootstrap, localVars, requireEnsure, requireExtensions] - .filter(Boolean) - .join("\n"); - } + if (moduleActivated && compiler.watching) compiler.watching.invalidate(); + }; - /** - * @returns {boolean} true, if the runtime module should get it's own scope - */ - shouldIsolate() { - // We avoid isolating this to have better backward-compat - return false; - } -} + const server = /** @type {import("net").Server} */ (createServer()); + server.on("request", requestListener); -module.exports = CompatRuntimeModule; + let isClosing = false; + /** @type {Set} */ + const sockets = new Set(); + server.on("connection", socket => { + sockets.add(socket); + socket.on("close", () => { + sockets.delete(socket); + }); + if (isClosing) socket.destroy(); + }); + server.on("clientError", e => { + if (e.message !== "Server is disposing") logger.warn(e); + }); + server.on("listening", err => { + if (err) return callback(err); + const addr = server.address(); + if (typeof addr === "string") throw new Error("addr must not be a string"); + const urlBase = + addr.address === "::" || addr.address === "0.0.0.0" + ? `${protocol}://localhost:${addr.port}` + : addr.family === "IPv6" + ? `${protocol}://[${addr.address}]:${addr.port}` + : `${protocol}://${addr.address}:${addr.port}`; + logger.log( + `Server-Sent-Events server for lazy compilation open at ${urlBase}.` + ); + callback(null, { + dispose(callback) { + isClosing = true; + // Removing the listener is a workaround for a memory leak in node.js + server.off("request", requestListener); + server.close(err => { + callback(err); + }); + for (const socket of sockets) { + socket.destroy(new Error("Server is disposing")); + } + }, + module(originalModule) { + const key = `${encodeURIComponent( + originalModule.identifier().replace(/\\/g, "/").replace(/@/g, "_") + ).replace(/%(2F|3A|24|26|2B|2C|3B|3D|3A)/g, decodeURIComponent)}`; + const active = activeModules.get(key) > 0; + return { + client: `${options.client}?${encodeURIComponent(urlBase + prefix)}`, + data: key, + active + }; + } + }); + }); + listen(server); +}; /***/ }), -/***/ 94669: +/***/ 64618: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const HelperRuntimeModule = __webpack_require__(82444); +const { find } = __webpack_require__(93347); +const { + compareModulesByPreOrderIndexOrIdentifier, + compareModulesByPostOrderIndexOrIdentifier +} = __webpack_require__(29579); -class CreateFakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { - constructor() { - super("create fake namespace object"); +/** @typedef {import("../Compiler")} Compiler */ + +class ChunkModuleIdRangePlugin { + constructor(options) { + this.options = options; } /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.createFakeNamespaceObject; - return Template.asString([ - `var getProto = Object.getPrototypeOf ? ${runtimeTemplate.returningFunction( - "Object.getPrototypeOf(obj)", - "obj" - )} : ${runtimeTemplate.returningFunction("obj.__proto__", "obj")};`, - "var leafPrototypes;", - "// create a fake namespace object", - "// mode & 1: value is a module id, require it", - "// mode & 2: merge all properties of value into the ns", - "// mode & 4: return value when already ns object", - "// mode & 16: return value when it's Promise-like", - "// mode & 8|1: behave like require", - // Note: must be a function (not arrow), because this is used in body! - `${fn} = function(value, mode) {`, - Template.indent([ - `if(mode & 1) value = this(value);`, - `if(mode & 8) return value;`, - "if(typeof value === 'object' && value) {", - Template.indent([ - "if((mode & 4) && value.__esModule) return value;", - "if((mode & 16) && typeof value.then === 'function') return value;" - ]), - "}", - "var ns = Object.create(null);", - `${RuntimeGlobals.makeNamespaceObject}(ns);`, - "var def = {};", - "leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];", - "for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {", - Template.indent([ - `Object.getOwnPropertyNames(current).forEach(${runtimeTemplate.expressionFunction( - `def[key] = ${runtimeTemplate.returningFunction("value[key]", "")}`, - "key" - )});` - ]), - "}", - `def['default'] = ${runtimeTemplate.returningFunction("value", "")};`, - `${RuntimeGlobals.definePropertyGetters}(ns, def);`, - "return ns;" - ]), - "};" - ]); + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => { + const moduleGraph = compilation.moduleGraph; + compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => { + const chunkGraph = compilation.chunkGraph; + const chunk = find( + compilation.chunks, + chunk => chunk.name === options.name + ); + if (!chunk) { + throw new Error( + `ChunkModuleIdRangePlugin: Chunk with name '${options.name}"' was not found` + ); + } + + let chunkModules; + if (options.order) { + let cmpFn; + switch (options.order) { + case "index": + case "preOrderIndex": + cmpFn = compareModulesByPreOrderIndexOrIdentifier(moduleGraph); + break; + case "index2": + case "postOrderIndex": + cmpFn = compareModulesByPostOrderIndexOrIdentifier(moduleGraph); + break; + default: + throw new Error( + "ChunkModuleIdRangePlugin: unexpected value of order" + ); + } + chunkModules = chunkGraph.getOrderedChunkModules(chunk, cmpFn); + } else { + chunkModules = Array.from(modules) + .filter(m => { + return chunkGraph.isModuleInChunk(m, chunk); + }) + .sort(compareModulesByPreOrderIndexOrIdentifier(moduleGraph)); + } + + let currentId = options.start || 0; + for (let i = 0; i < chunkModules.length; i++) { + const m = chunkModules[i]; + if (m.needId && chunkGraph.getModuleId(m) === null) { + chunkGraph.setModuleId(m, currentId++); + } + if (options.end && currentId > options.end) break; + } + }); + }); } } - -module.exports = CreateFakeNamespaceObjectRuntimeModule; +module.exports = ChunkModuleIdRangePlugin; /***/ }), -/***/ 2759: +/***/ 8747: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent */ -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const HelperRuntimeModule = __webpack_require__(82444); +const { compareChunksNatural } = __webpack_require__(29579); +const { + getFullChunkName, + getUsedChunkIds, + assignDeterministicIds +} = __webpack_require__(63290); -class CreateScriptRuntimeModule extends HelperRuntimeModule { - constructor() { - super("trusted types script"); +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +class DeterministicChunkIdsPlugin { + constructor(options) { + this.options = options || {}; } /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - const { compilation } = this; - const { runtimeTemplate, outputOptions } = compilation; - const { trustedTypes } = outputOptions; - const fn = RuntimeGlobals.createScript; + apply(compiler) { + compiler.hooks.compilation.tap( + "DeterministicChunkIdsPlugin", + compilation => { + compilation.hooks.chunkIds.tap( + "DeterministicChunkIdsPlugin", + chunks => { + const chunkGraph = compilation.chunkGraph; + const context = this.options.context + ? this.options.context + : compiler.context; + const maxLength = this.options.maxLength || 3; - return Template.asString( - `${fn} = ${runtimeTemplate.returningFunction( - trustedTypes - ? `${RuntimeGlobals.getTrustedTypesPolicy}().createScript(script)` - : "script", - "script" - )};` + const compareNatural = compareChunksNatural(chunkGraph); + + const usedIds = getUsedChunkIds(compilation); + assignDeterministicIds( + Array.from(chunks).filter(chunk => { + return chunk.id === null; + }), + chunk => + getFullChunkName(chunk, chunkGraph, context, compiler.root), + compareNatural, + (chunk, id) => { + const size = usedIds.size; + usedIds.add(`${id}`); + if (size === usedIds.size) return false; + chunk.id = id; + chunk.ids = [id]; + return true; + }, + [Math.pow(10, maxLength)], + 10, + usedIds.size + ); + } + ); + } ); } } -module.exports = CreateScriptRuntimeModule; +module.exports = DeterministicChunkIdsPlugin; /***/ }), -/***/ 21213: +/***/ 76692: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent */ -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const HelperRuntimeModule = __webpack_require__(82444); +const { + compareModulesByPreOrderIndexOrIdentifier +} = __webpack_require__(29579); +const { + getUsedModuleIdsAndModules, + getFullModuleName, + assignDeterministicIds +} = __webpack_require__(63290); -class CreateScriptUrlRuntimeModule extends HelperRuntimeModule { - constructor() { - super("trusted types script url"); +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +class DeterministicModuleIdsPlugin { + /** + * @param {Object} options options + * @param {string=} options.context context relative to which module identifiers are computed + * @param {function(Module): boolean=} options.test selector function for modules + * @param {number=} options.maxLength maximum id length in digits (used as starting point) + * @param {number=} options.salt hash salt for ids + * @param {boolean=} options.fixedLength do not increase the maxLength to find an optimal id space size + * @param {boolean=} options.failOnConflict throw an error when id conflicts occur (instead of rehashing) + */ + constructor(options = {}) { + this.options = options; } /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - const { compilation } = this; - const { runtimeTemplate, outputOptions } = compilation; - const { trustedTypes } = outputOptions; - const fn = RuntimeGlobals.createScriptUrl; + apply(compiler) { + compiler.hooks.compilation.tap( + "DeterministicModuleIdsPlugin", + compilation => { + compilation.hooks.moduleIds.tap("DeterministicModuleIdsPlugin", () => { + const chunkGraph = compilation.chunkGraph; + const context = this.options.context + ? this.options.context + : compiler.context; + const maxLength = this.options.maxLength || 3; + const failOnConflict = this.options.failOnConflict || false; + const fixedLength = this.options.fixedLength || false; + const salt = this.options.salt || 0; + let conflicts = 0; - return Template.asString( - `${fn} = ${runtimeTemplate.returningFunction( - trustedTypes - ? `${RuntimeGlobals.getTrustedTypesPolicy}().createScriptURL(url)` - : "url", - "url" - )};` + const [usedIds, modules] = getUsedModuleIdsAndModules( + compilation, + this.options.test + ); + assignDeterministicIds( + modules, + module => getFullModuleName(module, context, compiler.root), + failOnConflict + ? () => 0 + : compareModulesByPreOrderIndexOrIdentifier( + compilation.moduleGraph + ), + (module, id) => { + const size = usedIds.size; + usedIds.add(`${id}`); + if (size === usedIds.size) { + conflicts++; + return false; + } + chunkGraph.setModuleId(module, id); + return true; + }, + [Math.pow(10, maxLength)], + fixedLength ? 0 : 10, + usedIds.size, + salt + ); + if (failOnConflict && conflicts) + throw new Error( + `Assigning deterministic module ids has lead to ${conflicts} conflict${ + conflicts > 1 ? "s" : "" + }.\nIncrease the 'maxLength' to increase the id space and make conflicts less likely (recommended when there are many conflicts or application is expected to grow), or add an 'salt' number to try another hash starting value in the same id space (recommended when there is only a single conflict).` + ); + }); + } ); } } -module.exports = CreateScriptUrlRuntimeModule; +module.exports = DeterministicModuleIdsPlugin; /***/ }), -/***/ 75481: +/***/ 21825: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const HelperRuntimeModule = __webpack_require__(82444); +const { + compareModulesByPreOrderIndexOrIdentifier +} = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); +const createHash = __webpack_require__(49835); +const { + getUsedModuleIdsAndModules, + getFullModuleName +} = __webpack_require__(63290); -class DefinePropertyGettersRuntimeModule extends HelperRuntimeModule { - constructor() { - super("define property getters"); +/** @typedef {import("../../declarations/plugins/HashedModuleIdsPlugin").HashedModuleIdsPluginOptions} HashedModuleIdsPluginOptions */ + +const validate = createSchemaValidation( + __webpack_require__(52210), + () => __webpack_require__(59106), + { + name: "Hashed Module Ids Plugin", + baseDataPath: "options" } +); +class HashedModuleIdsPlugin { /** - * @returns {string} runtime code + * @param {HashedModuleIdsPluginOptions=} options options object */ - generate() { - const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.definePropertyGetters; - return Template.asString([ - "// define getter functions for harmony exports", - `${fn} = ${runtimeTemplate.basicFunction("exports, definition", [ - `for(var key in definition) {`, - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(definition, key) && !${RuntimeGlobals.hasOwnProperty}(exports, key)) {`, - Template.indent([ - "Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });" - ]), - "}" - ]), - "}" - ])};` - ]); + constructor(options = {}) { + validate(options); + + /** @type {HashedModuleIdsPluginOptions} */ + this.options = { + context: null, + hashFunction: "md4", + hashDigest: "base64", + hashDigestLength: 4, + ...options + }; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("HashedModuleIdsPlugin", compilation => { + compilation.hooks.moduleIds.tap("HashedModuleIdsPlugin", () => { + const chunkGraph = compilation.chunkGraph; + const context = this.options.context + ? this.options.context + : compiler.context; + + const [usedIds, modules] = getUsedModuleIdsAndModules(compilation); + const modulesInNaturalOrder = modules.sort( + compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph) + ); + for (const module of modulesInNaturalOrder) { + const ident = getFullModuleName(module, context, compiler.root); + const hash = createHash(options.hashFunction); + hash.update(ident || ""); + const hashId = /** @type {string} */ ( + hash.digest(options.hashDigest) + ); + let len = options.hashDigestLength; + while (usedIds.has(hashId.substr(0, len))) len++; + const moduleId = hashId.substr(0, len); + chunkGraph.setModuleId(module, moduleId); + usedIds.add(moduleId); + } + }); + }); } } -module.exports = DefinePropertyGettersRuntimeModule; +module.exports = HashedModuleIdsPlugin; /***/ }), -/***/ 71519: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 63290: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); +const createHash = __webpack_require__(49835); +const { makePathsRelative } = __webpack_require__(82186); +const numberHash = __webpack_require__(70002); -class EnsureChunkRuntimeModule extends RuntimeModule { - constructor(runtimeRequirements) { - super("ensure chunk"); - this.runtimeRequirements = runtimeRequirements; - } +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {typeof import("../util/Hash")} Hash */ - /** - * @returns {string} runtime code - */ - generate() { - const { runtimeTemplate } = this.compilation; - // Check if there are non initial chunks which need to be imported using require-ensure - if (this.runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers)) { - const handlers = RuntimeGlobals.ensureChunkHandlers; - return Template.asString([ - `${handlers} = {};`, - "// This file contains only the entry chunk.", - "// The chunk loading function for additional chunks", - `${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.basicFunction( - "chunkId", - [ - `return Promise.all(Object.keys(${handlers}).reduce(${runtimeTemplate.basicFunction( - "promises, key", - [`${handlers}[key](chunkId, promises);`, "return promises;"] - )}, []));` - ] - )};` - ]); - } else { - // There ensureChunk is used somewhere in the tree, so we need an empty requireEnsure - // function. This can happen with multiple entrypoints. - return Template.asString([ - "// The chunk loading function for additional chunks", - "// Since all referenced chunks are already included", - "// in this file, this function is empty here.", - `${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.returningFunction( - "Promise.resolve()" - )};` - ]); - } - } -} - -module.exports = EnsureChunkRuntimeModule; +/** + * @param {string} str string to hash + * @param {number} len max length of the hash + * @param {string | Hash} hashFunction hash function to use + * @returns {string} hash + */ +const getHash = (str, len, hashFunction) => { + const hash = createHash(hashFunction); + hash.update(str); + const digest = /** @type {string} */ (hash.digest("hex")); + return digest.substr(0, len); +}; +/** + * @param {string} str the string + * @returns {string} string prefixed by an underscore if it is a number + */ +const avoidNumber = str => { + // max length of a number is 21 chars, bigger numbers a written as "...e+xx" + if (str.length > 21) return str; + const firstChar = str.charCodeAt(0); + // skip everything that doesn't look like a number + // charCodes: "-": 45, "1": 49, "9": 57 + if (firstChar < 49) { + if (firstChar !== 45) return str; + } else if (firstChar > 57) { + return str; + } + if (str === +str + "") { + return `_${str}`; + } + return str; +}; -/***/ }), +/** + * @param {string} request the request + * @returns {string} id representation + */ +const requestToId = request => { + return request + .replace(/^(\.\.?\/)+/, "") + .replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_"); +}; +exports.requestToId = requestToId; -/***/ 34277: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @param {string} string the string + * @param {string} delimiter separator for string and hash + * @param {string | Hash} hashFunction hash function to use + * @returns {string} string with limited max length to 100 chars + */ +const shortenLongString = (string, delimiter, hashFunction) => { + if (string.length < 100) return string; + return ( + string.slice(0, 100 - 6 - delimiter.length) + + delimiter + + getHash(string, 6, hashFunction) + ); +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ +/** + * @param {Module} module the module + * @param {string} context context directory + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} short module name + */ +const getShortModuleName = (module, context, associatedObjectForCache) => { + const libIdent = module.libIdent({ context, associatedObjectForCache }); + if (libIdent) return avoidNumber(libIdent); + const nameForCondition = module.nameForCondition(); + if (nameForCondition) + return avoidNumber( + makePathsRelative(context, nameForCondition, associatedObjectForCache) + ); + return ""; +}; +exports.getShortModuleName = getShortModuleName; +/** + * @param {string} shortName the short name + * @param {Module} module the module + * @param {string} context context directory + * @param {string | Hash} hashFunction hash function to use + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} long module name + */ +const getLongModuleName = ( + shortName, + module, + context, + hashFunction, + associatedObjectForCache +) => { + const fullName = getFullModuleName(module, context, associatedObjectForCache); + return `${shortName}?${getHash(fullName, 4, hashFunction)}`; +}; +exports.getLongModuleName = getLongModuleName; +/** + * @param {Module} module the module + * @param {string} context context directory + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} full module name + */ +const getFullModuleName = (module, context, associatedObjectForCache) => { + return makePathsRelative( + context, + module.identifier(), + associatedObjectForCache + ); +}; +exports.getFullModuleName = getFullModuleName; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); -const { first } = __webpack_require__(93347); +/** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} context context directory + * @param {string} delimiter delimiter for names + * @param {string | Hash} hashFunction hash function to use + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} short chunk name + */ +const getShortChunkName = ( + chunk, + chunkGraph, + context, + delimiter, + hashFunction, + associatedObjectForCache +) => { + const modules = chunkGraph.getChunkRootModules(chunk); + const shortModuleNames = modules.map(m => + requestToId(getShortModuleName(m, context, associatedObjectForCache)) + ); + chunk.idNameHints.sort(); + const chunkName = Array.from(chunk.idNameHints) + .concat(shortModuleNames) + .filter(Boolean) + .join(delimiter); + return shortenLongString(chunkName, delimiter, hashFunction); +}; +exports.getShortChunkName = getShortChunkName; -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("../Compilation").PathData} PathData */ +/** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} context context directory + * @param {string} delimiter delimiter for names + * @param {string | Hash} hashFunction hash function to use + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} short chunk name + */ +const getLongChunkName = ( + chunk, + chunkGraph, + context, + delimiter, + hashFunction, + associatedObjectForCache +) => { + const modules = chunkGraph.getChunkRootModules(chunk); + const shortModuleNames = modules.map(m => + requestToId(getShortModuleName(m, context, associatedObjectForCache)) + ); + const longModuleNames = modules.map(m => + requestToId( + getLongModuleName("", m, context, hashFunction, associatedObjectForCache) + ) + ); + chunk.idNameHints.sort(); + const chunkName = Array.from(chunk.idNameHints) + .concat(shortModuleNames, longModuleNames) + .filter(Boolean) + .join(delimiter); + return shortenLongString(chunkName, delimiter, hashFunction); +}; +exports.getLongChunkName = getLongChunkName; -/** @typedef {function(PathData, AssetInfo=): string} FilenameFunction */ +/** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} context context directory + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} full chunk name + */ +const getFullChunkName = ( + chunk, + chunkGraph, + context, + associatedObjectForCache +) => { + if (chunk.name) return chunk.name; + const modules = chunkGraph.getChunkRootModules(chunk); + const fullModuleNames = modules.map(m => + makePathsRelative(context, m.identifier(), associatedObjectForCache) + ); + return fullModuleNames.join(); +}; +exports.getFullChunkName = getFullChunkName; -class GetChunkFilenameRuntimeModule extends RuntimeModule { - /** - * @param {string} contentType the contentType to use the content hash for - * @param {string} name kind of filename - * @param {string} global function name to be assigned - * @param {function(Chunk): string | FilenameFunction} getFilenameForChunk functor to get the filename or function - * @param {boolean} allChunks when false, only async chunks are included - */ - constructor(contentType, name, global, getFilenameForChunk, allChunks) { - super(`get ${name} chunk filename`); - this.contentType = contentType; - this.global = global; - this.getFilenameForChunk = getFilenameForChunk; - this.allChunks = allChunks; - this.dependentHash = true; +/** + * @template K + * @template V + * @param {Map} map a map from key to values + * @param {K} key key + * @param {V} value value + * @returns {void} + */ +const addToMapOfItems = (map, key, value) => { + let array = map.get(key); + if (array === undefined) { + array = []; + map.set(key, array); } + array.push(value); +}; - /** - * @returns {string} runtime code - */ - generate() { - const { - global, - chunk, - chunkGraph, - contentType, - getFilenameForChunk, - allChunks, - compilation - } = this; - const { runtimeTemplate } = compilation; +/** + * @param {Compilation} compilation the compilation + * @param {function(Module): boolean=} filter filter modules + * @returns {[Set, Module[]]} used module ids as strings and modules without id matching the filter + */ +const getUsedModuleIdsAndModules = (compilation, filter) => { + const chunkGraph = compilation.chunkGraph; - /** @type {Map>} */ - const chunkFilenames = new Map(); - let maxChunks = 0; - /** @type {string} */ - let dynamicFilename; + const modules = []; - /** - * @param {Chunk} c the chunk - * @returns {void} - */ - const addChunk = c => { - const chunkFilename = getFilenameForChunk(c); - if (chunkFilename) { - let set = chunkFilenames.get(chunkFilename); - if (set === undefined) { - chunkFilenames.set(chunkFilename, (set = new Set())); - } - set.add(c); - if (typeof chunkFilename === "string") { - if (set.size < maxChunks) return; - if (set.size === maxChunks) { - if (chunkFilename.length < dynamicFilename.length) return; - if (chunkFilename.length === dynamicFilename.length) { - if (chunkFilename < dynamicFilename) return; - } - } - maxChunks = set.size; - dynamicFilename = chunkFilename; - } - } - }; + /** @type {Set} */ + const usedIds = new Set(); + if (compilation.usedModuleIds) { + for (const id of compilation.usedModuleIds) { + usedIds.add(id + ""); + } + } - /** @type {string[]} */ - const includedChunksMessages = []; - if (allChunks) { - includedChunksMessages.push("all chunks"); - for (const c of chunk.getAllReferencedChunks()) { - addChunk(c); - } + for (const module of compilation.modules) { + if (!module.needId) continue; + const moduleId = chunkGraph.getModuleId(module); + if (moduleId !== null) { + usedIds.add(moduleId + ""); } else { - includedChunksMessages.push("async chunks"); - for (const c of chunk.getAllAsyncChunks()) { - addChunk(c); - } - const includeEntries = chunkGraph - .getTreeRuntimeRequirements(chunk) - .has(RuntimeGlobals.ensureChunkIncludeEntries); - if (includeEntries) { - includedChunksMessages.push("sibling chunks for the entrypoint"); - for (const c of chunkGraph.getChunkEntryDependentChunksIterable( - chunk - )) { - addChunk(c); - } + if ( + (!filter || filter(module)) && + chunkGraph.getNumberOfModuleChunks(module) !== 0 + ) { + modules.push(module); } } - for (const entrypoint of chunk.getAllReferencedAsyncEntrypoints()) { - addChunk(entrypoint.chunks[entrypoint.chunks.length - 1]); + } + + return [usedIds, modules]; +}; +exports.getUsedModuleIdsAndModules = getUsedModuleIdsAndModules; + +/** + * @param {Compilation} compilation the compilation + * @returns {Set} used chunk ids as strings + */ +const getUsedChunkIds = compilation => { + /** @type {Set} */ + const usedIds = new Set(); + if (compilation.usedChunkIds) { + for (const id of compilation.usedChunkIds) { + usedIds.add(id + ""); } + } - /** @type {Map>} */ - const staticUrls = new Map(); - /** @type {Set} */ - const dynamicUrlChunks = new Set(); + for (const chunk of compilation.chunks) { + const chunkId = chunk.id; + if (chunkId !== null) { + usedIds.add(chunkId + ""); + } + } - /** - * @param {Chunk} c the chunk - * @param {string | FilenameFunction} chunkFilename the filename template for the chunk - * @returns {void} - */ - const addStaticUrl = (c, chunkFilename) => { - /** - * @param {string | number} value a value - * @returns {string} string to put in quotes - */ - const unquotedStringify = value => { - const str = `${value}`; - if (str.length >= 5 && str === `${c.id}`) { - // This is shorter and generates the same result - return '" + chunkId + "'; - } - const s = JSON.stringify(str); - return s.slice(1, s.length - 1); - }; - const unquotedStringifyWithLength = value => length => - unquotedStringify(`${value}`.slice(0, length)); - const chunkFilenameValue = - typeof chunkFilename === "function" - ? JSON.stringify( - chunkFilename({ - chunk: c, - contentHashType: contentType - }) - ) - : JSON.stringify(chunkFilename); - const staticChunkFilename = compilation.getPath(chunkFilenameValue, { - hash: `" + ${RuntimeGlobals.getFullHash}() + "`, - hashWithLength: length => - `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, - chunk: { - id: unquotedStringify(c.id), - hash: unquotedStringify(c.renderedHash), - hashWithLength: unquotedStringifyWithLength(c.renderedHash), - name: unquotedStringify(c.name || c.id), - contentHash: { - [contentType]: unquotedStringify(c.contentHash[contentType]) - }, - contentHashWithLength: { - [contentType]: unquotedStringifyWithLength( - c.contentHash[contentType] - ) - } - }, - contentHashType: contentType - }); - let set = staticUrls.get(staticChunkFilename); - if (set === undefined) { - staticUrls.set(staticChunkFilename, (set = new Set())); - } - set.add(c.id); - }; + return usedIds; +}; +exports.getUsedChunkIds = getUsedChunkIds; - for (const [filename, chunks] of chunkFilenames) { - if (filename !== dynamicFilename) { - for (const c of chunks) addStaticUrl(c, filename); - } else { - for (const c of chunks) dynamicUrlChunks.add(c); +/** + * @template T + * @param {Iterable} items list of items to be named + * @param {function(T): string} getShortName get a short name for an item + * @param {function(T, string): string} getLongName get a long name for an item + * @param {function(T, T): -1|0|1} comparator order of items + * @param {Set} usedIds already used ids, will not be assigned + * @param {function(T, string): void} assignName assign a name to an item + * @returns {T[]} list of items without a name + */ +const assignNames = ( + items, + getShortName, + getLongName, + comparator, + usedIds, + assignName +) => { + /** @type {Map} */ + const nameToItems = new Map(); + + for (const item of items) { + const name = getShortName(item); + addToMapOfItems(nameToItems, name, item); + } + + /** @type {Map} */ + const nameToItems2 = new Map(); + + for (const [name, items] of nameToItems) { + if (items.length > 1 || !name) { + for (const item of items) { + const longName = getLongName(item, name); + addToMapOfItems(nameToItems2, longName, item); } + } else { + addToMapOfItems(nameToItems2, name, items[0]); } + } - /** - * @param {function(Chunk): string | number} fn function from chunk to value - * @returns {string} code with static mapping of results of fn - */ - const createMap = fn => { - const obj = {}; - let useId = false; - let lastKey; - let entries = 0; - for (const c of dynamicUrlChunks) { - const value = fn(c); - if (value === c.id) { - useId = true; - } else { - obj[c.id] = value; - lastKey = c.id; - entries++; - } + /** @type {T[]} */ + const unnamedItems = []; + + for (const [name, items] of nameToItems2) { + if (!name) { + for (const item of items) { + unnamedItems.push(item); } - if (entries === 0) return "chunkId"; - if (entries === 1) { - return useId - ? `(chunkId === ${JSON.stringify(lastKey)} ? ${JSON.stringify( - obj[lastKey] - )} : chunkId)` - : JSON.stringify(obj[lastKey]); + } else if (items.length === 1 && !usedIds.has(name)) { + assignName(items[0], name); + usedIds.add(name); + } else { + items.sort(comparator); + let i = 0; + for (const item of items) { + while (nameToItems2.has(name + i) && usedIds.has(name + i)) i++; + assignName(item, name + i); + usedIds.add(name + i); + i++; } - return useId - ? `(${JSON.stringify(obj)}[chunkId] || chunkId)` - : `${JSON.stringify(obj)}[chunkId]`; - }; + } + } - /** - * @param {function(Chunk): string | number} fn function from chunk to value - * @returns {string} code with static mapping of results of fn for including in quoted string - */ - const mapExpr = fn => { - return `" + ${createMap(fn)} + "`; - }; + unnamedItems.sort(comparator); + return unnamedItems; +}; +exports.assignNames = assignNames; - /** - * @param {function(Chunk): string | number} fn function from chunk to value - * @returns {function(number): string} function which generates code with static mapping of results of fn for including in quoted string for specific length - */ - const mapExprWithLength = fn => length => { - return `" + ${createMap(c => `${fn(c)}`.slice(0, length))} + "`; - }; +/** + * @template T + * @param {T[]} items list of items to be named + * @param {function(T): string} getName get a name for an item + * @param {function(T, T): -1|0|1} comparator order of items + * @param {function(T, number): boolean} assignId assign an id to an item + * @param {number[]} ranges usable ranges for ids + * @param {number} expandFactor factor to create more ranges + * @param {number} extraSpace extra space to allocate, i. e. when some ids are already used + * @param {number} salt salting number to initialize hashing + * @returns {void} + */ +const assignDeterministicIds = ( + items, + getName, + comparator, + assignId, + ranges = [10], + expandFactor = 10, + extraSpace = 0, + salt = 0 +) => { + items.sort(comparator); - const url = - dynamicFilename && - compilation.getPath(JSON.stringify(dynamicFilename), { - hash: `" + ${RuntimeGlobals.getFullHash}() + "`, - hashWithLength: length => - `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, - chunk: { - id: `" + chunkId + "`, - hash: mapExpr(c => c.renderedHash), - hashWithLength: mapExprWithLength(c => c.renderedHash), - name: mapExpr(c => c.name || c.id), - contentHash: { - [contentType]: mapExpr(c => c.contentHash[contentType]) - }, - contentHashWithLength: { - [contentType]: mapExprWithLength(c => c.contentHash[contentType]) - } - }, - contentHashType: contentType - }); + // max 5% fill rate + const optimalRange = Math.min( + Math.ceil(items.length * 20) + extraSpace, + Number.MAX_SAFE_INTEGER + ); - return Template.asString([ - `// This function allow to reference ${includedChunksMessages.join( - " and " - )}`, - `${global} = ${runtimeTemplate.basicFunction( - "chunkId", + let i = 0; + let range = ranges[i]; + while (range < optimalRange) { + i++; + if (i < ranges.length) { + range = Math.min(ranges[i], Number.MAX_SAFE_INTEGER); + } else if (expandFactor) { + range = Math.min(range * expandFactor, Number.MAX_SAFE_INTEGER); + } else { + break; + } + } - staticUrls.size > 0 - ? [ - "// return url for filenames not based on template", - // it minimizes to `x===1?"...":x===2?"...":"..."` - Template.asString( - Array.from(staticUrls, ([url, ids]) => { - const condition = - ids.size === 1 - ? `chunkId === ${JSON.stringify(first(ids))}` - : `{${Array.from( - ids, - id => `${JSON.stringify(id)}:1` - ).join(",")}}[chunkId]`; - return `if (${condition}) return ${url};`; - }) - ), - "// return url for filenames based on template", - `return ${url};` - ] - : ["// return url for filenames based on template", `return ${url};`] - )};` - ]); + for (const item of items) { + const ident = getName(item); + let id; + let i = salt; + do { + id = numberHash(ident + i++, range); + } while (!assignId(item, id)); } -} +}; +exports.assignDeterministicIds = assignDeterministicIds; -module.exports = GetChunkFilenameRuntimeModule; +/** + * @param {Set} usedIds used ids + * @param {Iterable} modules the modules + * @param {Compilation} compilation the compilation + * @returns {void} + */ +const assignAscendingModuleIds = (usedIds, modules, compilation) => { + const chunkGraph = compilation.chunkGraph; + + let nextId = 0; + let assignId; + if (usedIds.size > 0) { + assignId = module => { + if (chunkGraph.getModuleId(module) === null) { + while (usedIds.has(nextId + "")) nextId++; + chunkGraph.setModuleId(module, nextId++); + } + }; + } else { + assignId = module => { + if (chunkGraph.getModuleId(module) === null) { + chunkGraph.setModuleId(module, nextId++); + } + }; + } + for (const module of modules) { + assignId(module); + } +}; +exports.assignAscendingModuleIds = assignAscendingModuleIds; + +/** + * @param {Iterable} chunks the chunks + * @param {Compilation} compilation the compilation + * @returns {void} + */ +const assignAscendingChunkIds = (chunks, compilation) => { + const usedIds = getUsedChunkIds(compilation); + + let nextId = 0; + if (usedIds.size > 0) { + for (const chunk of chunks) { + if (chunk.id === null) { + while (usedIds.has(nextId + "")) nextId++; + chunk.id = nextId; + chunk.ids = [nextId]; + nextId++; + } + } + } else { + for (const chunk of chunks) { + if (chunk.id === null) { + chunk.id = nextId; + chunk.ids = [nextId]; + nextId++; + } + } + } +}; +exports.assignAscendingChunkIds = assignAscendingChunkIds; /***/ }), -/***/ 88732: +/***/ 6454: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); +const { compareChunksNatural } = __webpack_require__(29579); +const { + getShortChunkName, + getLongChunkName, + assignNames, + getUsedChunkIds, + assignAscendingChunkIds +} = __webpack_require__(63290); -/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ -class GetFullHashRuntimeModule extends RuntimeModule { - constructor() { - super("getFullHash"); - this.fullHash = true; +class NamedChunkIdsPlugin { + constructor(options) { + this.delimiter = (options && options.delimiter) || "-"; + this.context = options && options.context; } /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - const { runtimeTemplate } = this.compilation; - return `${RuntimeGlobals.getFullHash} = ${runtimeTemplate.returningFunction( - JSON.stringify(this.compilation.hash || "XXXX") - )}`; + apply(compiler) { + compiler.hooks.compilation.tap("NamedChunkIdsPlugin", compilation => { + const { hashFunction } = compilation.outputOptions; + compilation.hooks.chunkIds.tap("NamedChunkIdsPlugin", chunks => { + const chunkGraph = compilation.chunkGraph; + const context = this.context ? this.context : compiler.context; + const delimiter = this.delimiter; + + const unnamedChunks = assignNames( + Array.from(chunks).filter(chunk => { + if (chunk.name) { + chunk.id = chunk.name; + chunk.ids = [chunk.name]; + } + return chunk.id === null; + }), + chunk => + getShortChunkName( + chunk, + chunkGraph, + context, + delimiter, + hashFunction, + compiler.root + ), + chunk => + getLongChunkName( + chunk, + chunkGraph, + context, + delimiter, + hashFunction, + compiler.root + ), + compareChunksNatural(chunkGraph), + getUsedChunkIds(compilation), + (chunk, name) => { + chunk.id = name; + chunk.ids = [name]; + } + ); + if (unnamedChunks.length > 0) { + assignAscendingChunkIds(unnamedChunks, compilation); + } + }); + }); } } -module.exports = GetFullHashRuntimeModule; +module.exports = NamedChunkIdsPlugin; /***/ }), -/***/ 10029: +/***/ 24339: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const { + getShortModuleName, + getLongModuleName, + assignNames, + getUsedModuleIdsAndModules, + assignAscendingModuleIds +} = __webpack_require__(63290); -/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ -class GetMainFilenameRuntimeModule extends RuntimeModule { - /** - * @param {string} name readable name - * @param {string} global global object binding - * @param {string} filename main file name - */ - constructor(name, global, filename) { - super(`get ${name} filename`); - this.global = global; - this.filename = filename; +class NamedModuleIdsPlugin { + constructor(options) { + this.options = options || {}; } /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - const { global, filename, compilation, chunk } = this; - const { runtimeTemplate } = compilation; - const url = compilation.getPath(JSON.stringify(filename), { - hash: `" + ${RuntimeGlobals.getFullHash}() + "`, - hashWithLength: length => - `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, - chunk, - runtime: chunk.runtime + apply(compiler) { + const { root } = compiler; + compiler.hooks.compilation.tap("NamedModuleIdsPlugin", compilation => { + const { hashFunction } = compilation.outputOptions; + compilation.hooks.moduleIds.tap("NamedModuleIdsPlugin", () => { + const chunkGraph = compilation.chunkGraph; + const context = this.options.context + ? this.options.context + : compiler.context; + + const [usedIds, modules] = getUsedModuleIdsAndModules(compilation); + const unnamedModules = assignNames( + modules, + m => getShortModuleName(m, context, root), + (m, shortName) => + getLongModuleName(shortName, m, context, hashFunction, root), + compareModulesByIdentifier, + usedIds, + (m, name) => chunkGraph.setModuleId(m, name) + ); + if (unnamedModules.length > 0) { + assignAscendingModuleIds(usedIds, unnamedModules, compilation); + } + }); }); - return Template.asString([ - `${global} = ${runtimeTemplate.returningFunction(url)};` - ]); } } -module.exports = GetMainFilenameRuntimeModule; +module.exports = NamedModuleIdsPlugin; /***/ }), -/***/ 38713: +/***/ 86221: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const HelperRuntimeModule = __webpack_require__(82444); +const { compareChunksNatural } = __webpack_require__(29579); +const { assignAscendingChunkIds } = __webpack_require__(63290); -class GetTrustedTypesPolicyRuntimeModule extends HelperRuntimeModule { - /** - * @param {Set} runtimeRequirements runtime requirements - */ - constructor(runtimeRequirements) { - super("trusted types policy"); - this.runtimeRequirements = runtimeRequirements; - } +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +class NaturalChunkIdsPlugin { /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - const { compilation } = this; - const { runtimeTemplate, outputOptions } = compilation; - const { trustedTypes } = outputOptions; - const fn = RuntimeGlobals.getTrustedTypesPolicy; - - return Template.asString([ - "var policy;", - `${fn} = ${runtimeTemplate.basicFunction("", [ - "// Create Trusted Type policy if Trusted Types are available and the policy doesn't exist yet.", - "if (policy === undefined) {", - Template.indent([ - "policy = {", - Template.indent( - [ - ...(this.runtimeRequirements.has(RuntimeGlobals.createScript) - ? [ - `createScript: ${runtimeTemplate.returningFunction( - "script", - "script" - )}` - ] - : []), - ...(this.runtimeRequirements.has(RuntimeGlobals.createScriptUrl) - ? [ - `createScriptURL: ${runtimeTemplate.returningFunction( - "url", - "url" - )}` - ] - : []) - ].join(",\n") - ), - "};", - ...(trustedTypes - ? [ - 'if (typeof trustedTypes !== "undefined" && trustedTypes.createPolicy) {', - Template.indent([ - `policy = trustedTypes.createPolicy(${JSON.stringify( - trustedTypes.policyName - )}, policy);` - ]), - "}" - ] - : []) - ]), - "}", - "return policy;" - ])};` - ]); + apply(compiler) { + compiler.hooks.compilation.tap("NaturalChunkIdsPlugin", compilation => { + compilation.hooks.chunkIds.tap("NaturalChunkIdsPlugin", chunks => { + const chunkGraph = compilation.chunkGraph; + const compareNatural = compareChunksNatural(chunkGraph); + const chunksInNaturalOrder = Array.from(chunks).sort(compareNatural); + assignAscendingChunkIds(chunksInNaturalOrder, compilation); + }); + }); } } -module.exports = GetTrustedTypesPolicyRuntimeModule; +module.exports = NaturalChunkIdsPlugin; /***/ }), -/***/ 23255: +/***/ 83366: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); +const { + compareModulesByPreOrderIndexOrIdentifier +} = __webpack_require__(29579); +const { + assignAscendingModuleIds, + getUsedModuleIdsAndModules +} = __webpack_require__(63290); -class GlobalRuntimeModule extends RuntimeModule { - constructor() { - super("global"); - } +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +class NaturalModuleIdsPlugin { /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - return Template.asString([ - `${RuntimeGlobals.global} = (function() {`, - Template.indent([ - "if (typeof globalThis === 'object') return globalThis;", - "try {", - Template.indent( - // This works in non-strict mode - // or - // This works if eval is allowed (see CSP) - "return this || new Function('return this')();" - ), - "} catch (e) {", - Template.indent( - // This works if the window reference is available - "if (typeof window === 'object') return window;" - ), - "}" - // It can still be `undefined`, but nothing to do about it... - // We return `undefined`, instead of nothing here, so it's - // easier to handle this case: - // if (!global) { … } - ]), - "})();" - ]); + apply(compiler) { + compiler.hooks.compilation.tap("NaturalModuleIdsPlugin", compilation => { + compilation.hooks.moduleIds.tap("NaturalModuleIdsPlugin", modules => { + const [usedIds, modulesInNaturalOrder] = + getUsedModuleIdsAndModules(compilation); + modulesInNaturalOrder.sort( + compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph) + ); + assignAscendingModuleIds(usedIds, modulesInNaturalOrder, compilation); + }); + }); } } -module.exports = GlobalRuntimeModule; +module.exports = NaturalModuleIdsPlugin; /***/ }), -/***/ 8011: +/***/ 51020: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); +const { compareChunksNatural } = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); +const { assignAscendingChunkIds } = __webpack_require__(63290); -class HasOwnPropertyRuntimeModule extends RuntimeModule { - constructor() { - super("hasOwnProperty shorthand"); - } +/** @typedef {import("../../declarations/plugins/ids/OccurrenceChunkIdsPlugin").OccurrenceChunkIdsPluginOptions} OccurrenceChunkIdsPluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ - /** - * @returns {string} runtime code - */ - generate() { - const { runtimeTemplate } = this.compilation; - - return Template.asString([ - `${RuntimeGlobals.hasOwnProperty} = ${runtimeTemplate.returningFunction( - "Object.prototype.hasOwnProperty.call(obj, prop)", - "obj, prop" - )}` - ]); - } -} - -module.exports = HasOwnPropertyRuntimeModule; - - -/***/ }), - -/***/ 82444: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeModule = __webpack_require__(16963); - -class HelperRuntimeModule extends RuntimeModule { - /** - * @param {string} name a readable name - */ - constructor(name) { - super(name); +const validate = createSchemaValidation( + __webpack_require__(24344), + () => __webpack_require__(53576), + { + name: "Occurrence Order Chunk Ids Plugin", + baseDataPath: "options" } -} - -module.exports = HelperRuntimeModule; - - -/***/ }), - -/***/ 19942: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const { SyncWaterfallHook } = __webpack_require__(6967); -const Compilation = __webpack_require__(85720); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const HelperRuntimeModule = __webpack_require__(82444); - -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ - -/** - * @typedef {Object} LoadScriptCompilationHooks - * @property {SyncWaterfallHook<[string, Chunk]>} createScript - */ - -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); +); -class LoadScriptRuntimeModule extends HelperRuntimeModule { +class OccurrenceChunkIdsPlugin { /** - * @param {Compilation} compilation the compilation - * @returns {LoadScriptCompilationHooks} hooks + * @param {OccurrenceChunkIdsPluginOptions=} options options object */ - 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 = { - createScript: new SyncWaterfallHook(["source", "chunk"]) - }; - compilationHooksMap.set(compilation, hooks); - } - return hooks; + constructor(options = {}) { + validate(options); + this.options = options; } /** - * @param {boolean=} withCreateScriptUrl use create script url for trusted types + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - constructor(withCreateScriptUrl) { - super("load script"); - this._withCreateScriptUrl = withCreateScriptUrl; - } + apply(compiler) { + const prioritiseInitial = this.options.prioritiseInitial; + compiler.hooks.compilation.tap("OccurrenceChunkIdsPlugin", compilation => { + compilation.hooks.chunkIds.tap("OccurrenceChunkIdsPlugin", chunks => { + const chunkGraph = compilation.chunkGraph; - /** - * @returns {string} runtime code - */ - generate() { - const { compilation } = this; - const { runtimeTemplate, outputOptions } = compilation; - const { - scriptType, - chunkLoadTimeout: loadTimeout, - crossOriginLoading, - uniqueName, - charset - } = outputOptions; - const fn = RuntimeGlobals.loadScript; + /** @type {Map} */ + const occursInInitialChunksMap = new Map(); - const { createScript } = - LoadScriptRuntimeModule.getCompilationHooks(compilation); + const compareNatural = compareChunksNatural(chunkGraph); - const code = Template.asString([ - "script = document.createElement('script');", - scriptType ? `script.type = ${JSON.stringify(scriptType)};` : "", - charset ? "script.charset = 'utf-8';" : "", - `script.timeout = ${loadTimeout / 1000};`, - `if (${RuntimeGlobals.scriptNonce}) {`, - Template.indent( - `script.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` - ), - "}", - uniqueName - ? 'script.setAttribute("data-webpack", dataWebpackPrefix + key);' - : "", - `script.src = ${ - this._withCreateScriptUrl - ? `${RuntimeGlobals.createScriptUrl}(url)` - : "url" - };`, - crossOriginLoading - ? Template.asString([ - "if (script.src.indexOf(window.location.origin + '/') !== 0) {", - Template.indent( - `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` - ), - "}" - ]) - : "" - ]); + for (const c of chunks) { + let occurs = 0; + for (const chunkGroup of c.groupsIterable) { + for (const parent of chunkGroup.parentsIterable) { + if (parent.isInitial()) occurs++; + } + } + occursInInitialChunksMap.set(c, occurs); + } - return Template.asString([ - "var inProgress = {};", - uniqueName - ? `var dataWebpackPrefix = ${JSON.stringify(uniqueName + ":")};` - : "// data-webpack is not used as build has no uniqueName", - "// loadScript function to load a script via script tag", - `${fn} = ${runtimeTemplate.basicFunction("url, done, key, chunkId", [ - "if(inProgress[url]) { inProgress[url].push(done); return; }", - "var script, needAttach;", - "if(key !== undefined) {", - Template.indent([ - 'var scripts = document.getElementsByTagName("script");', - "for(var i = 0; i < scripts.length; i++) {", - Template.indent([ - "var s = scripts[i];", - `if(s.getAttribute("src") == url${ - uniqueName - ? ' || s.getAttribute("data-webpack") == dataWebpackPrefix + key' - : "" - }) { script = s; break; }` - ]), - "}" - ]), - "}", - "if(!script) {", - Template.indent([ - "needAttach = true;", - createScript.call(code, this.chunk) - ]), - "}", - "inProgress[url] = [done];", - "var onScriptComplete = " + - runtimeTemplate.basicFunction( - "prev, event", - Template.asString([ - "// avoid mem leaks in IE.", - "script.onerror = script.onload = null;", - "clearTimeout(timeout);", - "var doneFns = inProgress[url];", - "delete inProgress[url];", - "script.parentNode && script.parentNode.removeChild(script);", - `doneFns && doneFns.forEach(${runtimeTemplate.returningFunction( - "fn(event)", - "fn" - )});`, - "if(prev) return prev(event);" - ]) - ), - ";", - `var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), ${loadTimeout});`, - "script.onerror = onScriptComplete.bind(null, script.onerror);", - "script.onload = onScriptComplete.bind(null, script.onload);", - "needAttach && document.head.appendChild(script);" - ])};` - ]); + const chunksInOccurrenceOrder = Array.from(chunks).sort((a, b) => { + if (prioritiseInitial) { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + } + const aOccurs = a.getNumberOfGroups(); + const bOccurs = b.getNumberOfGroups(); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + return compareNatural(a, b); + }); + assignAscendingChunkIds(chunksInOccurrenceOrder, compilation); + }); + }); } } -module.exports = LoadScriptRuntimeModule; +module.exports = OccurrenceChunkIdsPlugin; /***/ }), -/***/ 65714: +/***/ 35371: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const HelperRuntimeModule = __webpack_require__(82444); - -class MakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { - constructor() { - super("make namespace object"); - } - - /** - * @returns {string} runtime code - */ - generate() { - const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.makeNamespaceObject; - return Template.asString([ - "// define __esModule on exports", - `${fn} = ${runtimeTemplate.basicFunction("exports", [ - "if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {", - Template.indent([ - "Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });" - ]), - "}", - "Object.defineProperty(exports, '__esModule', { value: true });" - ])};` - ]); - } -} - -module.exports = MakeNamespaceObjectRuntimeModule; - - -/***/ }), - -/***/ 44518: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - +const { + compareModulesByPreOrderIndexOrIdentifier +} = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); +const { + assignAscendingModuleIds, + getUsedModuleIdsAndModules +} = __webpack_require__(63290); -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); +/** @typedef {import("../../declarations/plugins/ids/OccurrenceModuleIdsPlugin").OccurrenceModuleIdsPluginOptions} OccurrenceModuleIdsPluginOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -class OnChunksLoadedRuntimeModule extends RuntimeModule { - constructor() { - super("chunk loaded"); +const validate = createSchemaValidation( + __webpack_require__(14916), + () => __webpack_require__(19330), + { + name: "Occurrence Order Module Ids Plugin", + baseDataPath: "options" } +); +class OccurrenceModuleIdsPlugin { /** - * @returns {string} runtime code + * @param {OccurrenceModuleIdsPluginOptions=} options options object */ - generate() { - const { compilation } = this; - const { runtimeTemplate } = compilation; - return Template.asString([ - "var deferred = [];", - `${RuntimeGlobals.onChunksLoaded} = ${runtimeTemplate.basicFunction( - "result, chunkIds, fn, priority", - [ - "if(chunkIds) {", - Template.indent([ - "priority = priority || 0;", - "for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];", - "deferred[i] = [chunkIds, fn, priority];", - "return;" - ]), - "}", - "var notFulfilled = Infinity;", - "for (var i = 0; i < deferred.length; i++) {", - Template.indent([ - runtimeTemplate.destructureArray( - ["chunkIds", "fn", "priority"], - "deferred[i]" - ), - "var fulfilled = true;", - "for (var j = 0; j < chunkIds.length; j++) {", - Template.indent([ - `if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(${ - RuntimeGlobals.onChunksLoaded - }).every(${runtimeTemplate.returningFunction( - `${RuntimeGlobals.onChunksLoaded}[key](chunkIds[j])`, - "key" - )})) {`, - Template.indent(["chunkIds.splice(j--, 1);"]), - "} else {", - Template.indent([ - "fulfilled = false;", - "if(priority < notFulfilled) notFulfilled = priority;" - ]), - "}" - ]), - "}", - "if(fulfilled) {", - Template.indent([ - "deferred.splice(i--, 1)", - "var r = fn();", - "if (r !== undefined) result = r;" - ]), - "}" - ]), - "}", - "return result;" - ] - )};` - ]); - } -} - -module.exports = OnChunksLoadedRuntimeModule; - - -/***/ }), - -/***/ 56030: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); - -class PublicPathRuntimeModule extends RuntimeModule { - constructor(publicPath) { - super("publicPath", RuntimeModule.STAGE_BASIC); - this.publicPath = publicPath; + constructor(options = {}) { + validate(options); + this.options = options; } /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - const { compilation, publicPath } = this; + apply(compiler) { + const prioritiseInitial = this.options.prioritiseInitial; + compiler.hooks.compilation.tap("OccurrenceModuleIdsPlugin", compilation => { + const moduleGraph = compilation.moduleGraph; - return `${RuntimeGlobals.publicPath} = ${JSON.stringify( - compilation.getPath(publicPath || "", { - hash: compilation.hash || "XXXX" - }) - )};`; - } -} + compilation.hooks.moduleIds.tap("OccurrenceModuleIdsPlugin", () => { + const chunkGraph = compilation.chunkGraph; -module.exports = PublicPathRuntimeModule; + const [usedIds, modulesInOccurrenceOrder] = + getUsedModuleIdsAndModules(compilation); + const occursInInitialChunksMap = new Map(); + const occursInAllChunksMap = new Map(); -/***/ }), + const initialChunkChunkMap = new Map(); + const entryCountMap = new Map(); + for (const m of modulesInOccurrenceOrder) { + let initial = 0; + let entry = 0; + for (const c of chunkGraph.getModuleChunksIterable(m)) { + if (c.canBeInitial()) initial++; + if (chunkGraph.isEntryModuleInChunk(m, c)) entry++; + } + initialChunkChunkMap.set(m, initial); + entryCountMap.set(m, entry); + } -/***/ 4537: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {Module} module module + * @returns {number} count of occurs + */ + const countOccursInEntry = module => { + let sum = 0; + for (const [ + originModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if (!originModule) continue; + if (!connections.some(c => c.isTargetActive(undefined))) continue; + sum += initialChunkChunkMap.get(originModule); + } + return sum; + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + /** + * @param {Module} module module + * @returns {number} count of occurs + */ + const countOccurs = module => { + let sum = 0; + for (const [ + originModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if (!originModule) continue; + const chunkModules = + chunkGraph.getNumberOfModuleChunks(originModule); + for (const c of connections) { + if (!c.isTargetActive(undefined)) continue; + if (!c.dependency) continue; + const factor = c.dependency.getNumberOfIdOccurrences(); + if (factor === 0) continue; + sum += factor * chunkModules; + } + } + return sum; + }; + if (prioritiseInitial) { + for (const m of modulesInOccurrenceOrder) { + const result = + countOccursInEntry(m) + + initialChunkChunkMap.get(m) + + entryCountMap.get(m); + occursInInitialChunksMap.set(m, result); + } + } + for (const m of modulesInOccurrenceOrder) { + const result = + countOccurs(m) + + chunkGraph.getNumberOfModuleChunks(m) + + entryCountMap.get(m); + occursInAllChunksMap.set(m, result); + } -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const HelperRuntimeModule = __webpack_require__(82444); + const naturalCompare = compareModulesByPreOrderIndexOrIdentifier( + compilation.moduleGraph + ); -class RelativeUrlRuntimeModule extends HelperRuntimeModule { - constructor() { - super("relative url"); - } + modulesInOccurrenceOrder.sort((a, b) => { + if (prioritiseInitial) { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + } + const aOccurs = occursInAllChunksMap.get(a); + const bOccurs = occursInAllChunksMap.get(b); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + return naturalCompare(a, b); + }); - /** - * @returns {string} runtime code - */ - generate() { - const { runtimeTemplate } = this.compilation; - return Template.asString([ - `${RuntimeGlobals.relativeUrl} = function RelativeURL(url) {`, - Template.indent([ - 'var realUrl = new URL(url, "x:/");', - "var values = {};", - "for (var key in realUrl) values[key] = realUrl[key];", - "values.href = url;", - 'values.pathname = url.replace(/[?#].*/, "");', - 'values.origin = values.protocol = "";', - `values.toString = values.toJSON = ${runtimeTemplate.returningFunction( - "url" - )};`, - "for (var key in values) Object.defineProperty(this, key, { enumerable: true, configurable: true, value: values[key] });" - ]), - "};", - `${RuntimeGlobals.relativeUrl}.prototype = URL.prototype;` - ]); + assignAscendingModuleIds( + usedIds, + modulesInOccurrenceOrder, + compilation + ); + }); + }); } } -module.exports = RelativeUrlRuntimeModule; +module.exports = OccurrenceModuleIdsPlugin; /***/ }), -/***/ 97115: +/***/ 8635: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); +const { WebpackError } = __webpack_require__(91919); +const { getUsedModuleIdsAndModules } = __webpack_require__(63290); -class RuntimeIdRuntimeModule extends RuntimeModule { - constructor() { - super("runtimeId"); - } +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +const plugin = "SyncModuleIdsPlugin"; +class SyncModuleIdsPlugin { /** - * @returns {string} runtime code + * @param {Object} options options + * @param {string} options.path path to file + * @param {string=} options.context context for module names + * @param {function(Module): boolean} options.test selector for modules + * @param {"read" | "create" | "merge" | "update"=} options.mode operation mode (defaults to merge) */ - generate() { - const { chunkGraph, chunk } = this; - const runtime = chunk.runtime; - if (typeof runtime !== "string") - throw new Error("RuntimeIdRuntimeModule must be in a single runtime"); - const id = chunkGraph.getRuntimeId(runtime); - return `${RuntimeGlobals.runtimeId} = ${JSON.stringify(id)};`; - } -} - -module.exports = RuntimeIdRuntimeModule; - - -/***/ }), - -/***/ 22339: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const StartupChunkDependenciesRuntimeModule = __webpack_require__(38157); -const StartupEntrypointRuntimeModule = __webpack_require__(97672); - -/** @typedef {import("../Compiler")} Compiler */ - -class StartupChunkDependenciesPlugin { - constructor(options) { - this.chunkLoading = options.chunkLoading; - this.asyncChunkLoading = - typeof options.asyncChunkLoading === "boolean" - ? options.asyncChunkLoading - : true; + constructor({ path, context, test, mode }) { + this._path = path; + this._context = context; + this._test = test || (() => true); + const readAndWrite = !mode || mode === "merge" || mode === "update"; + this._read = readAndWrite || mode === "read"; + this._write = readAndWrite || mode === "create"; + this._prune = mode === "update"; } /** @@ -110042,224 +100543,112 @@ class StartupChunkDependenciesPlugin { * @returns {void} */ apply(compiler) { - compiler.hooks.thisCompilation.tap( - "StartupChunkDependenciesPlugin", - compilation => { - const globalChunkLoading = compilation.outputOptions.chunkLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const chunkLoading = - options && options.chunkLoading !== undefined - ? options.chunkLoading - : globalChunkLoading; - return chunkLoading === this.chunkLoading; - }; - compilation.hooks.additionalTreeRuntimeRequirements.tap( - "StartupChunkDependenciesPlugin", - (chunk, set, { chunkGraph }) => { - if (!isEnabledForChunk(chunk)) return; - if (chunkGraph.hasChunkEntryDependentChunks(chunk)) { - set.add(RuntimeGlobals.startup); - set.add(RuntimeGlobals.ensureChunk); - set.add(RuntimeGlobals.ensureChunkIncludeEntries); - compilation.addRuntimeModule( - chunk, - new StartupChunkDependenciesRuntimeModule( - this.asyncChunkLoading - ) + /** @type {Map} */ + let data; + let dataChanged = false; + if (this._read) { + compiler.hooks.readRecords.tapAsync(plugin, callback => { + const fs = compiler.intermediateFileSystem; + fs.readFile(this._path, (err, buffer) => { + if (err) { + if (err.code !== "ENOENT") { + return callback(err); + } + return callback(); + } + const json = JSON.parse(buffer.toString()); + data = new Map(); + for (const key of Object.keys(json)) { + data.set(key, json[key]); + } + dataChanged = false; + return callback(); + }); + }); + } + if (this._write) { + compiler.hooks.emitRecords.tapAsync(plugin, callback => { + if (!data || !dataChanged) return callback(); + const json = {}; + const sorted = Array.from(data).sort(([a], [b]) => (a < b ? -1 : 1)); + for (const [key, value] of sorted) { + json[key] = value; + } + const fs = compiler.intermediateFileSystem; + fs.writeFile(this._path, JSON.stringify(json), callback); + }); + } + compiler.hooks.thisCompilation.tap(plugin, compilation => { + const associatedObjectForCache = compiler.root; + const context = this._context || compiler.context; + if (this._read) { + compilation.hooks.reviveModules.tap(plugin, (_1, _2) => { + if (!data) return; + const { chunkGraph } = compilation; + const [usedIds, modules] = getUsedModuleIdsAndModules( + compilation, + this._test + ); + for (const module of modules) { + const name = module.libIdent({ + context, + associatedObjectForCache + }); + if (!name) continue; + const id = data.get(name); + const idAsString = `${id}`; + if (usedIds.has(idAsString)) { + const err = new WebpackError( + `SyncModuleIdsPlugin: Unable to restore id '${id}' from '${this._path}' as it's already used.` ); + err.module = module; + compilation.errors.push(err); } + chunkGraph.setModuleId(module, id); + usedIds.add(idAsString); } - ); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.startupEntrypoint) - .tap("StartupChunkDependenciesPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.require); - set.add(RuntimeGlobals.ensureChunk); - set.add(RuntimeGlobals.ensureChunkIncludeEntries); - compilation.addRuntimeModule( - chunk, - new StartupEntrypointRuntimeModule(this.asyncChunkLoading) - ); - }); + }); + } + if (this._write) { + compilation.hooks.recordModules.tap(plugin, modules => { + const { chunkGraph } = compilation; + let oldData = data; + if (!oldData) { + oldData = data = new Map(); + } else if (this._prune) { + data = new Map(); + } + for (const module of modules) { + if (this._test(module)) { + const name = module.libIdent({ + context, + associatedObjectForCache + }); + if (!name) continue; + const id = chunkGraph.getModuleId(module); + if (id === null) continue; + const oldId = oldData.get(name); + if (oldId !== id) { + dataChanged = true; + } else if (data === oldData) { + continue; + } + data.set(name, id); + } + } + if (data.size !== oldData.size) dataChanged = true; + }); } - ); - } -} - -module.exports = StartupChunkDependenciesPlugin; - - -/***/ }), - -/***/ 38157: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); - -class StartupChunkDependenciesRuntimeModule extends RuntimeModule { - constructor(asyncChunkLoading) { - super("startup chunk dependencies", RuntimeModule.STAGE_TRIGGER); - this.asyncChunkLoading = asyncChunkLoading; - } - - /** - * @returns {string} runtime code - */ - generate() { - const { chunkGraph, chunk, compilation } = this; - const { runtimeTemplate } = compilation; - const chunkIds = Array.from( - chunkGraph.getChunkEntryDependentChunksIterable(chunk) - ).map(chunk => { - return chunk.id; }); - return Template.asString([ - `var next = ${RuntimeGlobals.startup};`, - `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction( - "", - !this.asyncChunkLoading - ? chunkIds - .map( - id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)});` - ) - .concat("return next();") - : chunkIds.length === 1 - ? `return ${RuntimeGlobals.ensureChunk}(${JSON.stringify( - chunkIds[0] - )}).then(next);` - : chunkIds.length > 2 - ? [ - // using map is shorter for 3 or more chunks - `return Promise.all(${JSON.stringify(chunkIds)}.map(${ - RuntimeGlobals.ensureChunk - }, __webpack_require__)).then(next);` - ] - : [ - // calling ensureChunk directly is shorter for 0 - 2 chunks - "return Promise.all([", - Template.indent( - chunkIds - .map( - id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)})` - ) - .join(",\n") - ), - "]).then(next);" - ] - )};` - ]); - } -} - -module.exports = StartupChunkDependenciesRuntimeModule; - - -/***/ }), - -/***/ 97672: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); - -/** @typedef {import("../MainTemplate")} MainTemplate */ - -class StartupEntrypointRuntimeModule extends RuntimeModule { - constructor(asyncChunkLoading) { - super("startup entrypoint"); - this.asyncChunkLoading = asyncChunkLoading; - } - - /** - * @returns {string} runtime code - */ - generate() { - const { compilation } = this; - const { runtimeTemplate } = compilation; - return `${ - RuntimeGlobals.startupEntrypoint - } = ${runtimeTemplate.basicFunction("result, chunkIds, fn", [ - "// arguments: chunkIds, moduleId are deprecated", - "var moduleId = chunkIds;", - `if(!fn) chunkIds = result, fn = ${runtimeTemplate.returningFunction( - `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)` - )};`, - ...(this.asyncChunkLoading - ? [ - `return Promise.all(chunkIds.map(${ - RuntimeGlobals.ensureChunk - }, __webpack_require__)).then(${runtimeTemplate.basicFunction("", [ - "var r = fn();", - "return r === undefined ? result : r;" - ])})` - ] - : [ - `chunkIds.map(${RuntimeGlobals.ensureChunk}, __webpack_require__)`, - "var r = fn();", - "return r === undefined ? result : r;" - ]) - ])}`; - } -} - -module.exports = StartupEntrypointRuntimeModule; - - -/***/ }), - -/***/ 80655: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); - -/** @typedef {import("../Compilation")} Compilation */ - -class SystemContextRuntimeModule extends RuntimeModule { - constructor() { - super("__system_context__"); - } - - /** - * @returns {string} runtime code - */ - generate() { - return `${RuntimeGlobals.systemContext} = __system_context__;`; } } -module.exports = SystemContextRuntimeModule; +module.exports = SyncModuleIdsPlugin; /***/ }), -/***/ 64820: +/***/ 91919: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -110270,60 +100659,578 @@ module.exports = SystemContextRuntimeModule; -const NormalModule = __webpack_require__(39); - -/** @typedef {import("../Compiler")} Compiler */ +const util = __webpack_require__(73837); +const memoize = __webpack_require__(78676); -// data URL scheme: "data:text/javascript;charset=utf-8;base64,some-string" -// http://www.ietf.org/rfc/rfc2397.txt -const URIRegEx = /^data:([^;,]+)?((?:;[^;,]+)*?)(?:;(base64))?,(.*)$/i; +/** @typedef {import("../declarations/WebpackOptions").Entry} Entry */ +/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} EntryNormalized */ +/** @typedef {import("../declarations/WebpackOptions").EntryObject} EntryObject */ +/** @typedef {import("../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../declarations/WebpackOptions").ModuleOptions} ModuleOptions */ +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetCondition} RuleSetCondition */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetConditionAbsolute} RuleSetConditionAbsolute */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetRule} RuleSetRule */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetUse} RuleSetUse */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetUseItem} RuleSetUseItem */ +/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} Configuration */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ +/** @typedef {import("./Compilation").Asset} Asset */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./MultiStats")} MultiStats */ +/** @typedef {import("./Parser").ParserState} ParserState */ +/** @typedef {import("./ResolverFactory").ResolvePluginInstance} ResolvePluginInstance */ +/** @typedef {import("./ResolverFactory").Resolver} Resolver */ +/** @typedef {import("./Watching")} Watching */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunk} StatsChunk */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunkGroup} StatsChunkGroup */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunkOrigin} StatsChunkOrigin */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsLogging} StatsLogging */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsLoggingEntry} StatsLoggingEntry */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleIssuer} StatsModuleIssuer */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleReason} StatsModuleReason */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleTraceDependency} StatsModuleTraceDependency */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleTraceItem} StatsModuleTraceItem */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsProfile} StatsProfile */ -const decodeDataURI = uri => { - const match = URIRegEx.exec(uri); - if (!match) return null; +/** + * @template {Function} T + * @param {function(): T} factory factory function + * @returns {T} function + */ +const lazyFunction = factory => { + const fac = memoize(factory); + const f = /** @type {any} */ ( + (...args) => { + return fac()(...args); + } + ); + return /** @type {T} */ (f); +}; - const isBase64 = match[3]; - const body = match[4]; - return isBase64 - ? Buffer.from(body, "base64") - : Buffer.from(decodeURIComponent(body), "ascii"); +/** + * @template A + * @template B + * @param {A} obj input a + * @param {B} exports input b + * @returns {A & B} merged + */ +const mergeExports = (obj, exports) => { + const descriptors = Object.getOwnPropertyDescriptors(exports); + for (const name of Object.keys(descriptors)) { + const descriptor = descriptors[name]; + if (descriptor.get) { + const fn = descriptor.get; + Object.defineProperty(obj, name, { + configurable: false, + enumerable: true, + get: memoize(fn) + }); + } else if (typeof descriptor.value === "object") { + Object.defineProperty(obj, name, { + configurable: false, + enumerable: true, + writable: false, + value: mergeExports({}, descriptor.value) + }); + } else { + throw new Error( + "Exposed values must be either a getter or an nested object" + ); + } + } + return /** @type {A & B} */ (Object.freeze(obj)); }; -class DataUriPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "DataUriPlugin", - (compilation, { normalModuleFactory }) => { - normalModuleFactory.hooks.resolveForScheme - .for("data") - .tap("DataUriPlugin", resourceData => { - const match = URIRegEx.exec(resourceData.resource); - if (match) { - resourceData.data.mimetype = match[1] || ""; - resourceData.data.parameters = match[2] || ""; - resourceData.data.encoding = match[3] || false; - resourceData.data.encodedContent = match[4] || ""; - } - }); - NormalModule.getCompilationHooks(compilation) - .readResourceForScheme.for("data") - .tap("DataUriPlugin", resource => decodeDataURI(resource)); +const fn = lazyFunction(() => __webpack_require__(36243)); +module.exports = mergeExports(fn, { + get webpack() { + return __webpack_require__(36243); + }, + get validate() { + const webpackOptionsSchemaCheck = __webpack_require__(10382); + const getRealValidate = memoize(() => { + const validateSchema = __webpack_require__(12047); + const webpackOptionsSchema = __webpack_require__(73342); + return options => validateSchema(webpackOptionsSchema, options); + }); + return options => { + if (!webpackOptionsSchemaCheck(options)) getRealValidate()(options); + }; + }, + get validateSchema() { + const validateSchema = __webpack_require__(12047); + return validateSchema; + }, + get version() { + return /** @type {string} */ ((__webpack_require__(32702)/* .version */ .i8)); + }, + + get cli() { + return __webpack_require__(13462); + }, + get AutomaticPrefetchPlugin() { + return __webpack_require__(17714); + }, + get AsyncDependenciesBlock() { + return __webpack_require__(47736); + }, + get BannerPlugin() { + return __webpack_require__(21242); + }, + get Cache() { + return __webpack_require__(7592); + }, + get Chunk() { + return __webpack_require__(39385); + }, + get ChunkGraph() { + return __webpack_require__(64971); + }, + get CleanPlugin() { + return __webpack_require__(31085); + }, + get Compilation() { + return __webpack_require__(85720); + }, + get Compiler() { + return __webpack_require__(70845); + }, + get ConcatenationScope() { + return __webpack_require__(98229); + }, + get ContextExclusionPlugin() { + return __webpack_require__(21411); + }, + get ContextReplacementPlugin() { + return __webpack_require__(12206); + }, + get DefinePlugin() { + return __webpack_require__(79065); + }, + get DelegatedPlugin() { + return __webpack_require__(80632); + }, + get Dependency() { + return __webpack_require__(54912); + }, + get DllPlugin() { + return __webpack_require__(40038); + }, + get DllReferencePlugin() { + return __webpack_require__(90999); + }, + get DynamicEntryPlugin() { + return __webpack_require__(96475); + }, + get EntryOptionPlugin() { + return __webpack_require__(9909); + }, + get EntryPlugin() { + return __webpack_require__(96953); + }, + get EnvironmentPlugin() { + return __webpack_require__(22070); + }, + get EvalDevToolModulePlugin() { + return __webpack_require__(65218); + }, + get EvalSourceMapDevToolPlugin() { + return __webpack_require__(14790); + }, + get ExternalModule() { + return __webpack_require__(73071); + }, + get ExternalsPlugin() { + return __webpack_require__(6652); + }, + get Generator() { + return __webpack_require__(93401); + }, + get HotUpdateChunk() { + return __webpack_require__(9597); + }, + get HotModuleReplacementPlugin() { + return __webpack_require__(6404); + }, + get IgnorePlugin() { + return __webpack_require__(84808); + }, + get JavascriptModulesPlugin() { + return util.deprecate( + () => __webpack_require__(89464), + "webpack.JavascriptModulesPlugin has moved to webpack.javascript.JavascriptModulesPlugin", + "DEP_WEBPACK_JAVASCRIPT_MODULES_PLUGIN" + )(); + }, + get LibManifestPlugin() { + return __webpack_require__(93837); + }, + get LibraryTemplatePlugin() { + return util.deprecate( + () => __webpack_require__(14157), + "webpack.LibraryTemplatePlugin is deprecated and has been replaced by compilation.outputOptions.library or compilation.addEntry + passing a library option", + "DEP_WEBPACK_LIBRARY_TEMPLATE_PLUGIN" + )(); + }, + get LoaderOptionsPlugin() { + return __webpack_require__(22078); + }, + get LoaderTargetPlugin() { + return __webpack_require__(86738); + }, + get Module() { + return __webpack_require__(73208); + }, + get ModuleFilenameHelpers() { + return __webpack_require__(88821); + }, + get ModuleGraph() { + return __webpack_require__(99988); + }, + get ModuleGraphConnection() { + return __webpack_require__(40639); + }, + get NoEmitOnErrorsPlugin() { + return __webpack_require__(50169); + }, + get NormalModule() { + return __webpack_require__(39); + }, + get NormalModuleReplacementPlugin() { + return __webpack_require__(30633); + }, + get MultiCompiler() { + return __webpack_require__(33370); + }, + get Parser() { + return __webpack_require__(11715); + }, + get PrefetchPlugin() { + return __webpack_require__(73850); + }, + get ProgressPlugin() { + return __webpack_require__(13216); + }, + get ProvidePlugin() { + return __webpack_require__(38309); + }, + get RuntimeGlobals() { + return __webpack_require__(16475); + }, + get RuntimeModule() { + return __webpack_require__(16963); + }, + get SingleEntryPlugin() { + return util.deprecate( + () => __webpack_require__(96953), + "SingleEntryPlugin was renamed to EntryPlugin", + "DEP_WEBPACK_SINGLE_ENTRY_PLUGIN" + )(); + }, + get SourceMapDevToolPlugin() { + return __webpack_require__(63872); + }, + get Stats() { + return __webpack_require__(31743); + }, + get Template() { + return __webpack_require__(39722); + }, + get UsageState() { + return (__webpack_require__(63686).UsageState); + }, + get WatchIgnorePlugin() { + return __webpack_require__(65193); + }, + get WebpackError() { + return __webpack_require__(53799); + }, + get WebpackOptionsApply() { + return __webpack_require__(88422); + }, + get WebpackOptionsDefaulter() { + return util.deprecate( + () => __webpack_require__(14452), + "webpack.WebpackOptionsDefaulter is deprecated and has been replaced by webpack.config.getNormalizedWebpackOptions and webpack.config.applyWebpackOptionsDefaults", + "DEP_WEBPACK_OPTIONS_DEFAULTER" + )(); + }, + // TODO webpack 6 deprecate + get WebpackOptionsValidationError() { + return (__webpack_require__(38476).ValidationError); + }, + get ValidationError() { + return (__webpack_require__(38476).ValidationError); + }, + + cache: { + get MemoryCachePlugin() { + return __webpack_require__(52539); + } + }, + + config: { + get getNormalizedWebpackOptions() { + return (__webpack_require__(26693).getNormalizedWebpackOptions); + }, + get applyWebpackOptionsDefaults() { + return (__webpack_require__(92988).applyWebpackOptionsDefaults); + } + }, + + dependencies: { + get ModuleDependency() { + return __webpack_require__(80321); + }, + get ConstDependency() { + return __webpack_require__(76911); + }, + get NullDependency() { + return __webpack_require__(31830); + } + }, + + ids: { + get ChunkModuleIdRangePlugin() { + return __webpack_require__(64618); + }, + get NaturalModuleIdsPlugin() { + return __webpack_require__(83366); + }, + get OccurrenceModuleIdsPlugin() { + return __webpack_require__(35371); + }, + get NamedModuleIdsPlugin() { + return __webpack_require__(24339); + }, + get DeterministicChunkIdsPlugin() { + return __webpack_require__(8747); + }, + get DeterministicModuleIdsPlugin() { + return __webpack_require__(76692); + }, + get NamedChunkIdsPlugin() { + return __webpack_require__(6454); + }, + get OccurrenceChunkIdsPlugin() { + return __webpack_require__(51020); + }, + get HashedModuleIdsPlugin() { + return __webpack_require__(21825); + } + }, + + javascript: { + get EnableChunkLoadingPlugin() { + return __webpack_require__(61291); + }, + get JavascriptModulesPlugin() { + return __webpack_require__(89464); + }, + get JavascriptParser() { + return __webpack_require__(29050); + } + }, + + optimize: { + get AggressiveMergingPlugin() { + return __webpack_require__(64395); + }, + get AggressiveSplittingPlugin() { + return util.deprecate( + () => __webpack_require__(15543), + "AggressiveSplittingPlugin is deprecated in favor of SplitChunksPlugin", + "DEP_WEBPACK_AGGRESSIVE_SPLITTING_PLUGIN" + )(); + }, + get InnerGraph() { + return __webpack_require__(38988); + }, + get LimitChunkCountPlugin() { + return __webpack_require__(83608); + }, + get MinChunkSizePlugin() { + return __webpack_require__(53912); + }, + get ModuleConcatenationPlugin() { + return __webpack_require__(74844); + }, + get RealContentHashPlugin() { + return __webpack_require__(46043); + }, + get RuntimeChunkPlugin() { + return __webpack_require__(2837); + }, + get SideEffectsFlagPlugin() { + return __webpack_require__(84800); + }, + get SplitChunksPlugin() { + return __webpack_require__(21478); + } + }, + + runtime: { + get GetChunkFilenameRuntimeModule() { + return __webpack_require__(34277); + }, + get LoadScriptRuntimeModule() { + return __webpack_require__(19942); + } + }, + + prefetch: { + get ChunkPrefetchPreloadPlugin() { + return __webpack_require__(33895); + } + }, + + web: { + get FetchCompileAsyncWasmPlugin() { + return __webpack_require__(8437); + }, + get FetchCompileWasmPlugin() { + return __webpack_require__(35537); + }, + get JsonpChunkLoadingRuntimeModule() { + return __webpack_require__(84154); + }, + get JsonpTemplatePlugin() { + return __webpack_require__(4607); + } + }, + + webworker: { + get WebWorkerTemplatePlugin() { + return __webpack_require__(68693); + } + }, + + node: { + get NodeEnvironmentPlugin() { + return __webpack_require__(7553); + }, + get NodeSourcePlugin() { + return __webpack_require__(7103); + }, + get NodeTargetPlugin() { + return __webpack_require__(17916); + }, + get NodeTemplatePlugin() { + return __webpack_require__(61052); + }, + get ReadFileCompileWasmPlugin() { + return __webpack_require__(98939); + } + }, + + electron: { + get ElectronTargetPlugin() { + return __webpack_require__(32277); + } + }, + + wasm: { + get AsyncWebAssemblyModulesPlugin() { + return __webpack_require__(7538); + } + }, + + library: { + get AbstractLibraryPlugin() { + return __webpack_require__(26030); + }, + get EnableLibraryPlugin() { + return __webpack_require__(91452); + } + }, + + container: { + get ContainerPlugin() { + return __webpack_require__(9244); + }, + get ContainerReferencePlugin() { + return __webpack_require__(95757); + }, + get ModuleFederationPlugin() { + return __webpack_require__(30569); + }, + get scope() { + return (__webpack_require__(3083).scope); + } + }, + + sharing: { + get ConsumeSharedPlugin() { + return __webpack_require__(15046); + }, + get ProvideSharedPlugin() { + return __webpack_require__(31225); + }, + get SharePlugin() { + return __webpack_require__(26335); + }, + get scope() { + return (__webpack_require__(3083).scope); + } + }, + + debug: { + get ProfilingPlugin() { + return __webpack_require__(2757); + } + }, + + util: { + get createHash() { + return __webpack_require__(49835); + }, + get comparators() { + return __webpack_require__(29579); + }, + get runtime() { + return __webpack_require__(17156); + }, + get serialization() { + return __webpack_require__(8282); + }, + get cleverMerge() { + return (__webpack_require__(60839).cachedCleverMerge); + }, + get LazySet() { + return __webpack_require__(38938); + } + }, + + get sources() { + return __webpack_require__(51255); + }, + + experiments: { + schemes: { + get HttpUriPlugin() { + return __webpack_require__(42110); } - ); + }, + ids: { + get SyncModuleIdsPlugin() { + return __webpack_require__(8635); + } + } } -} - -module.exports = DataUriPlugin; +}); /***/ }), -/***/ 57637: +/***/ 18535: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -110334,54 +101241,159 @@ module.exports = DataUriPlugin; -const { URL, fileURLToPath } = __webpack_require__(57310); -const { NormalModule } = __webpack_require__(91919); +const { ConcatSource, PrefixSource, RawSource } = __webpack_require__(51255); +const { RuntimeGlobals } = __webpack_require__(91919); +const HotUpdateChunk = __webpack_require__(9597); +const Template = __webpack_require__(39722); +const { getCompilationHooks } = __webpack_require__(89464); +const { + generateEntryStartup, + updateHashForEntryStartup +} = __webpack_require__(98124); /** @typedef {import("../Compiler")} Compiler */ -class FileUriPlugin { +class ArrayPushCallbackChunkFormatPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap( - "FileUriPlugin", - (compilation, { normalModuleFactory }) => { - normalModuleFactory.hooks.resolveForScheme - .for("file") - .tap("FileUriPlugin", resourceData => { - const url = new URL(resourceData.resource); - const path = fileURLToPath(url); - const query = url.search; - const fragment = url.hash; - resourceData.path = path; - resourceData.query = query; - resourceData.fragment = fragment; - resourceData.resource = path + query + fragment; - return true; - }); - const hooks = NormalModule.getCompilationHooks(compilation); - hooks.readResource - .for(undefined) - .tapAsync("FileUriPlugin", (loaderContext, callback) => { - const { resourcePath } = loaderContext; - loaderContext.addDependency(resourcePath); - loaderContext.fs.readFile(resourcePath, callback); - }); + compiler.hooks.thisCompilation.tap( + "ArrayPushCallbackChunkFormatPlugin", + compilation => { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + "ArrayPushCallbackChunkFormatPlugin", + (chunk, set, { chunkGraph }) => { + if (chunk.hasRuntime()) return; + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { + set.add(RuntimeGlobals.onChunksLoaded); + set.add(RuntimeGlobals.require); + } + set.add(RuntimeGlobals.chunkCallback); + } + ); + const hooks = getCompilationHooks(compilation); + hooks.renderChunk.tap( + "ArrayPushCallbackChunkFormatPlugin", + (modules, renderContext) => { + const { chunk, chunkGraph, runtimeTemplate } = renderContext; + const hotUpdateChunk = + chunk instanceof HotUpdateChunk ? chunk : null; + const globalObject = runtimeTemplate.globalObject; + const source = new ConcatSource(); + const runtimeModules = + chunkGraph.getChunkRuntimeModulesInOrder(chunk); + if (hotUpdateChunk) { + const hotUpdateGlobal = + runtimeTemplate.outputOptions.hotUpdateGlobal; + source.add( + `${globalObject}[${JSON.stringify(hotUpdateGlobal)}](` + ); + source.add(`${JSON.stringify(chunk.id)},`); + source.add(modules); + if (runtimeModules.length > 0) { + source.add(",\n"); + const runtimePart = Template.renderChunkRuntimeModules( + runtimeModules, + renderContext + ); + source.add(runtimePart); + } + source.add(")"); + } else { + const chunkLoadingGlobal = + runtimeTemplate.outputOptions.chunkLoadingGlobal; + source.add( + `(${globalObject}[${JSON.stringify( + chunkLoadingGlobal + )}] = ${globalObject}[${JSON.stringify( + chunkLoadingGlobal + )}] || []).push([` + ); + source.add(`${JSON.stringify(chunk.ids)},`); + source.add(modules); + const entries = Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ); + if (runtimeModules.length > 0 || entries.length > 0) { + const runtime = new ConcatSource( + (runtimeTemplate.supportsArrowFunction() + ? "__webpack_require__ =>" + : "function(__webpack_require__)") + + " { // webpackRuntimeModules\n" + ); + if (runtimeModules.length > 0) { + runtime.add( + Template.renderRuntimeModules(runtimeModules, { + ...renderContext, + codeGenerationResults: compilation.codeGenerationResults + }) + ); + } + if (entries.length > 0) { + const startupSource = new RawSource( + generateEntryStartup( + chunkGraph, + runtimeTemplate, + entries, + chunk, + true + ) + ); + runtime.add( + hooks.renderStartup.call( + startupSource, + entries[entries.length - 1][0], + { + ...renderContext, + inlined: false + } + ) + ); + if ( + chunkGraph + .getChunkRuntimeRequirements(chunk) + .has(RuntimeGlobals.returnExportsFromRuntime) + ) { + runtime.add("return __webpack_exports__;\n"); + } + } + runtime.add("}\n"); + source.add(",\n"); + source.add(new PrefixSource("/******/ ", runtime)); + } + source.add("])"); + } + return source; + } + ); + hooks.chunkHash.tap( + "ArrayPushCallbackChunkFormatPlugin", + (chunk, hash, { chunkGraph, runtimeTemplate }) => { + if (chunk.hasRuntime()) return; + hash.update( + `ArrayPushCallbackChunkFormatPlugin1${runtimeTemplate.outputOptions.chunkLoadingGlobal}${runtimeTemplate.outputOptions.hotUpdateGlobal}${runtimeTemplate.globalObject}` + ); + const entries = Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ); + updateHashForEntryStartup(hash, chunkGraph, entries, chunk); + } + ); } ); } } -module.exports = FileUriPlugin; +module.exports = ArrayPushCallbackChunkFormatPlugin; /***/ }), -/***/ 42110: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 950: +/***/ (function(module) { "use strict"; /* @@ -110391,11937 +101403,25729 @@ module.exports = FileUriPlugin; -const { extname, basename } = __webpack_require__(71017); -const { URL } = __webpack_require__(57310); -const { createGunzip, createBrotliDecompress, createInflate } = __webpack_require__(59796); -const NormalModule = __webpack_require__(39); -const createSchemaValidation = __webpack_require__(32540); -const createHash = __webpack_require__(49835); -const { mkdirp, dirname, join } = __webpack_require__(17139); -const memoize = __webpack_require__(78676); - -/** @typedef {import("../../declarations/plugins/schemes/HttpUriPlugin").HttpUriPluginOptions} HttpUriPluginOptions */ -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("estree").Node} EsTreeNode */ +/** @typedef {import("./JavascriptParser").VariableInfoInterface} VariableInfoInterface */ -const getHttp = memoize(() => __webpack_require__(13685)); -const getHttps = memoize(() => __webpack_require__(95687)); +const TypeUnknown = 0; +const TypeUndefined = 1; +const TypeNull = 2; +const TypeString = 3; +const TypeNumber = 4; +const TypeBoolean = 5; +const TypeRegExp = 6; +const TypeConditional = 7; +const TypeArray = 8; +const TypeConstArray = 9; +const TypeIdentifier = 10; +const TypeWrapped = 11; +const TypeTemplateString = 12; +const TypeBigInt = 13; -/** @type {(() => void)[] | undefined} */ -let inProgressWrite = undefined; +class BasicEvaluatedExpression { + constructor() { + this.type = TypeUnknown; + /** @type {[number, number]} */ + this.range = undefined; + /** @type {boolean} */ + this.falsy = false; + /** @type {boolean} */ + this.truthy = false; + /** @type {boolean | undefined} */ + this.nullish = undefined; + /** @type {boolean} */ + this.sideEffects = true; + /** @type {boolean | undefined} */ + this.bool = undefined; + /** @type {number | undefined} */ + this.number = undefined; + /** @type {bigint | undefined} */ + this.bigint = undefined; + /** @type {RegExp | undefined} */ + this.regExp = undefined; + /** @type {string | undefined} */ + this.string = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.quasis = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.parts = undefined; + /** @type {any[] | undefined} */ + this.array = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.items = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.options = undefined; + /** @type {BasicEvaluatedExpression | undefined} */ + this.prefix = undefined; + /** @type {BasicEvaluatedExpression | undefined} */ + this.postfix = undefined; + this.wrappedInnerExpressions = undefined; + /** @type {string | undefined} */ + this.identifier = undefined; + /** @type {VariableInfoInterface} */ + this.rootInfo = undefined; + /** @type {() => string[]} */ + this.getMembers = undefined; + /** @type {EsTreeNode} */ + this.expression = undefined; + } -const validate = createSchemaValidation( - __webpack_require__(67263), - () => __webpack_require__(27256), - { - name: "Http Uri Plugin", - baseDataPath: "options" + isUnknown() { + return this.type === TypeUnknown; } -); -const toSafePath = str => - str - .replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, "") - .replace(/[^a-zA-Z0-9._-]+/g, "_"); + isNull() { + return this.type === TypeNull; + } -const computeIntegrity = content => { - const hash = createHash("sha512"); - hash.update(content); - const integrity = "sha512-" + hash.digest("base64"); - return integrity; -}; + isUndefined() { + return this.type === TypeUndefined; + } -const verifyIntegrity = (content, integrity) => { - if (integrity === "ignore") return true; - return computeIntegrity(content) === integrity; -}; + isString() { + return this.type === TypeString; + } -/** - * @param {string} str input - * @returns {Record} parsed - */ -const parseKeyValuePairs = str => { - /** @type {Record} */ - const result = {}; - for (const item of str.split(",")) { - const i = item.indexOf("="); - if (i >= 0) { - const key = item.slice(0, i).trim(); - const value = item.slice(i + 1).trim(); - result[key] = value; - } else { - const key = item.trim(); - if (!key) continue; - result[key] = key; - } + isNumber() { + return this.type === TypeNumber; } - return result; -}; -const parseCacheControl = (cacheControl, requestTime) => { - // When false resource is not stored in cache - let storeCache = true; - // When false resource is not stored in lockfile cache - let storeLock = true; - // Resource is only revalidated, after that timestamp and when upgrade is chosen - let validUntil = 0; - if (cacheControl) { - const parsed = parseKeyValuePairs(cacheControl); - if (parsed["no-cache"]) storeCache = storeLock = false; - if (parsed["max-age"] && !isNaN(+parsed["max-age"])) { - validUntil = requestTime + +parsed["max-age"] * 1000; - } - if (parsed["must-revalidate"]) validUntil = 0; + isBigInt() { + return this.type === TypeBigInt; } - return { - storeLock, - storeCache, - validUntil - }; -}; -/** - * @typedef {Object} LockfileEntry - * @property {string} resolved - * @property {string} integrity - * @property {string} contentType - */ + isBoolean() { + return this.type === TypeBoolean; + } -const areLockfileEntriesEqual = (a, b) => { - return ( - a.resolved === b.resolved && - a.integrity === b.integrity && - a.contentType === b.contentType - ); -}; + isRegExp() { + return this.type === TypeRegExp; + } -const entryToString = entry => { - return `resolved: ${entry.resolved}, integrity: ${entry.integrity}, contentType: ${entry.contentType}`; -}; + isConditional() { + return this.type === TypeConditional; + } -class Lockfile { - constructor() { - this.version = 1; - /** @type {Map} */ - this.entries = new Map(); + isArray() { + return this.type === TypeArray; } - static parse(content) { - // TODO handle merge conflicts - const data = JSON.parse(content); - if (data.version !== 1) - throw new Error(`Unsupported lockfile version ${data.version}`); - const lockfile = new Lockfile(); - for (const key of Object.keys(data)) { - if (key === "version") continue; - const entry = data[key]; - lockfile.entries.set( - key, - typeof entry === "string" - ? entry - : { - resolved: key, - ...entry - } - ); - } - return lockfile; + isConstArray() { + return this.type === TypeConstArray; } - toString() { - let str = "{\n"; - const entries = Array.from(this.entries).sort(([a], [b]) => - a < b ? -1 : 1 - ); - for (const [key, entry] of entries) { - if (typeof entry === "string") { - str += ` ${JSON.stringify(key)}: ${JSON.stringify(entry)},\n`; - } else { - str += ` ${JSON.stringify(key)}: { `; - if (entry.resolved !== key) - str += `"resolved": ${JSON.stringify(entry.resolved)}, `; - str += `"integrity": ${JSON.stringify( - entry.integrity - )}, "contentType": ${JSON.stringify(entry.contentType)} },\n`; - } - } - str += ` "version": ${this.version}\n}\n`; - return str; + isIdentifier() { + return this.type === TypeIdentifier; } -} -/** - * @template R - * @param {function(function(Error=, R=): void): void} fn function - * @returns {function(function((Error | null)=, R=): void): void} cached function - */ -const cachedWithoutKey = fn => { - let inFlight = false; - /** @type {Error | undefined} */ - let cachedError = undefined; - /** @type {R | undefined} */ - let cachedResult = undefined; - /** @type {(function(Error=, R=): void)[] | undefined} */ - let cachedCallbacks = undefined; - return callback => { - if (inFlight) { - if (cachedResult !== undefined) return callback(null, cachedResult); - if (cachedError !== undefined) return callback(cachedError); - if (cachedCallbacks === undefined) cachedCallbacks = [callback]; - else cachedCallbacks.push(callback); - return; - } - inFlight = true; - fn((err, result) => { - if (err) cachedError = err; - else cachedResult = result; - const callbacks = cachedCallbacks; - cachedCallbacks = undefined; - callback(err, result); - if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); - }); - }; -}; + isWrapped() { + return this.type === TypeWrapped; + } -/** - * @template T - * @template R - * @param {function(T, function(Error=, R=): void): void} fn function - * @param {function(T, function(Error=, R=): void): void=} forceFn function for the second try - * @returns {(function(T, function((Error | null)=, R=): void): void) & { force: function(T, function((Error | null)=, R=): void): void }} cached function - */ -const cachedWithKey = (fn, forceFn = fn) => { - /** @typedef {{ result?: R, error?: Error, callbacks?: (function((Error | null)=, R=): void)[], force?: true }} CacheEntry */ - /** @type {Map} */ - const cache = new Map(); - const resultFn = (arg, callback) => { - const cacheEntry = cache.get(arg); - if (cacheEntry !== undefined) { - if (cacheEntry.result !== undefined) - return callback(null, cacheEntry.result); - if (cacheEntry.error !== undefined) return callback(cacheEntry.error); - if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback]; - else cacheEntry.callbacks.push(callback); - return; - } - /** @type {CacheEntry} */ - const newCacheEntry = { - result: undefined, - error: undefined, - callbacks: undefined - }; - cache.set(arg, newCacheEntry); - fn(arg, (err, result) => { - if (err) newCacheEntry.error = err; - else newCacheEntry.result = result; - const callbacks = newCacheEntry.callbacks; - newCacheEntry.callbacks = undefined; - callback(err, result); - if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); - }); - }; - resultFn.force = (arg, callback) => { - const cacheEntry = cache.get(arg); - if (cacheEntry !== undefined && cacheEntry.force) { - if (cacheEntry.result !== undefined) - return callback(null, cacheEntry.result); - if (cacheEntry.error !== undefined) return callback(cacheEntry.error); - if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback]; - else cacheEntry.callbacks.push(callback); - return; - } - /** @type {CacheEntry} */ - const newCacheEntry = { - result: undefined, - error: undefined, - callbacks: undefined, - force: true - }; - cache.set(arg, newCacheEntry); - forceFn(arg, (err, result) => { - if (err) newCacheEntry.error = err; - else newCacheEntry.result = result; - const callbacks = newCacheEntry.callbacks; - newCacheEntry.callbacks = undefined; - callback(err, result); - if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); - }); - }; - return resultFn; -}; + isTemplateString() { + return this.type === TypeTemplateString; + } -class HttpUriPlugin { /** - * @param {HttpUriPluginOptions} options options + * Is expression a primitive or an object type value? + * @returns {boolean | undefined} true: primitive type, false: object type, undefined: unknown/runtime-defined */ - constructor(options) { - validate(options); - this._lockfileLocation = options.lockfileLocation; - this._cacheLocation = options.cacheLocation; - this._upgrade = options.upgrade; - this._frozen = options.frozen; - this._allowedUris = options.allowedUris; + isPrimitiveType() { + switch (this.type) { + case TypeUndefined: + case TypeNull: + case TypeString: + case TypeNumber: + case TypeBoolean: + case TypeBigInt: + case TypeWrapped: + case TypeTemplateString: + return true; + case TypeRegExp: + case TypeArray: + case TypeConstArray: + return false; + default: + return undefined; + } } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * Is expression a runtime or compile-time value? + * @returns {boolean} true: compile time value, false: runtime value */ - apply(compiler) { - const schemes = [ - { - scheme: "http", - fetch: (url, options, callback) => getHttp().get(url, options, callback) - }, - { - scheme: "https", - fetch: (url, options, callback) => - getHttps().get(url, options, callback) - } - ]; - let lockfileCache; - compiler.hooks.compilation.tap( - "HttpUriPlugin", - (compilation, { normalModuleFactory }) => { - const intermediateFs = compiler.intermediateFileSystem; - const fs = compilation.inputFileSystem; - const cache = compilation.getCache("webpack.HttpUriPlugin"); - const logger = compilation.getLogger("webpack.HttpUriPlugin"); - const lockfileLocation = - this._lockfileLocation || - join( - intermediateFs, - compiler.context, - compiler.name - ? `${toSafePath(compiler.name)}.webpack.lock` - : "webpack.lock" - ); - const cacheLocation = - this._cacheLocation !== undefined - ? this._cacheLocation - : lockfileLocation + ".data"; - const upgrade = this._upgrade || false; - const frozen = this._frozen || false; - const hashFunction = "sha512"; - const hashDigest = "hex"; - const hashDigestLength = 20; - const allowedUris = this._allowedUris; - - let warnedAboutEol = false; - - const cacheKeyCache = new Map(); - /** - * @param {string} url the url - * @returns {string} the key - */ - const getCacheKey = url => { - const cachedResult = cacheKeyCache.get(url); - if (cachedResult !== undefined) return cachedResult; - const result = _getCacheKey(url); - cacheKeyCache.set(url, result); - return result; - }; - - /** - * @param {string} url the url - * @returns {string} the key - */ - const _getCacheKey = url => { - const parsedUrl = new URL(url); - const folder = toSafePath(parsedUrl.origin); - const name = toSafePath(parsedUrl.pathname); - const query = toSafePath(parsedUrl.search); - let ext = extname(name); - if (ext.length > 20) ext = ""; - const basename = ext ? name.slice(0, -ext.length) : name; - const hash = createHash(hashFunction); - hash.update(url); - const digest = hash.digest(hashDigest).slice(0, hashDigestLength); - return `${folder.slice(-50)}/${`${basename}${ - query ? `_${query}` : "" - }`.slice(0, 150)}_${digest}${ext}`; - }; + isCompileTimeValue() { + switch (this.type) { + case TypeUndefined: + case TypeNull: + case TypeString: + case TypeNumber: + case TypeBoolean: + case TypeRegExp: + case TypeConstArray: + case TypeBigInt: + return true; + default: + return false; + } + } - const getLockfile = cachedWithoutKey( - /** - * @param {function((Error | null)=, Lockfile=): void} callback callback - * @returns {void} - */ - callback => { - const readLockfile = () => { - intermediateFs.readFile(lockfileLocation, (err, buffer) => { - if (err && err.code !== "ENOENT") { - compilation.missingDependencies.add(lockfileLocation); - return callback(err); - } - compilation.fileDependencies.add(lockfileLocation); - compilation.fileSystemInfo.createSnapshot( - compiler.fsStartTime, - buffer ? [lockfileLocation] : [], - [], - buffer ? [] : [lockfileLocation], - { timestamp: true }, - (err, snapshot) => { - if (err) return callback(err); - const lockfile = buffer - ? Lockfile.parse(buffer.toString("utf-8")) - : new Lockfile(); - lockfileCache = { - lockfile, - snapshot - }; - callback(null, lockfile); - } - ); - }); - }; - if (lockfileCache) { - compilation.fileSystemInfo.checkSnapshotValid( - lockfileCache.snapshot, - (err, valid) => { - if (err) return callback(err); - if (!valid) return readLockfile(); - callback(null, lockfileCache.lockfile); - } - ); - } else { - readLockfile(); - } - } + /** + * Gets the compile-time value of the expression + * @returns {any} the javascript value + */ + asCompileTimeValue() { + switch (this.type) { + case TypeUndefined: + return undefined; + case TypeNull: + return null; + case TypeString: + return this.string; + case TypeNumber: + return this.number; + case TypeBoolean: + return this.bool; + case TypeRegExp: + return this.regExp; + case TypeConstArray: + return this.array; + case TypeBigInt: + return this.bigint; + default: + throw new Error( + "asCompileTimeValue must only be called for compile-time values" ); + } + } - /** @type {Map | undefined} */ - let lockfileUpdates = undefined; - const storeLockEntry = (lockfile, url, entry) => { - const oldEntry = lockfile.entries.get(url); - if (lockfileUpdates === undefined) lockfileUpdates = new Map(); - lockfileUpdates.set(url, entry); - lockfile.entries.set(url, entry); - if (!oldEntry) { - logger.log(`${url} added to lockfile`); - } else if (typeof oldEntry === "string") { - if (typeof entry === "string") { - logger.log(`${url} updated in lockfile: ${oldEntry} -> ${entry}`); - } else { - logger.log( - `${url} updated in lockfile: ${oldEntry} -> ${entry.resolved}` - ); - } - } else if (typeof entry === "string") { - logger.log( - `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry}` - ); - } else if (oldEntry.resolved !== entry.resolved) { - logger.log( - `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry.resolved}` - ); - } else if (oldEntry.integrity !== entry.integrity) { - logger.log(`${url} updated in lockfile: content changed`); - } else if (oldEntry.contentType !== entry.contentType) { - logger.log( - `${url} updated in lockfile: ${oldEntry.contentType} -> ${entry.contentType}` - ); - } else { - logger.log(`${url} updated in lockfile`); - } - }; - - const storeResult = (lockfile, url, result, callback) => { - if (result.storeLock) { - storeLockEntry(lockfile, url, result.entry); - if (!cacheLocation || !result.content) - return callback(null, result); - const key = getCacheKey(result.entry.resolved); - const filePath = join(intermediateFs, cacheLocation, key); - mkdirp(intermediateFs, dirname(intermediateFs, filePath), err => { - if (err) return callback(err); - intermediateFs.writeFile(filePath, result.content, err => { - if (err) return callback(err); - callback(null, result); - }); - }); - } else { - storeLockEntry(lockfile, url, "no-cache"); - callback(null, result); - } - }; + isTruthy() { + return this.truthy; + } - for (const { scheme, fetch } of schemes) { - /** - * - * @param {string} url URL - * @param {string} integrity integrity - * @param {function((Error | null)=, { entry: LockfileEntry, content: Buffer, storeLock: boolean }=): void} callback callback - */ - const resolveContent = (url, integrity, callback) => { - const handleResult = (err, result) => { - if (err) return callback(err); - if ("location" in result) { - return resolveContent( - result.location, - integrity, - (err, innerResult) => { - if (err) return callback(err); - callback(null, { - entry: innerResult.entry, - content: innerResult.content, - storeLock: innerResult.storeLock && result.storeLock - }); - } - ); - } else { - if ( - !result.fresh && - integrity && - result.entry.integrity !== integrity && - !verifyIntegrity(result.content, integrity) - ) { - return fetchContent.force(url, handleResult); - } - return callback(null, { - entry: result.entry, - content: result.content, - storeLock: result.storeLock - }); - } - }; - fetchContent(url, handleResult); - }; + isFalsy() { + return this.falsy; + } - /** @typedef {{ storeCache: boolean, storeLock: boolean, validUntil: number, etag: string | undefined, fresh: boolean }} FetchResultMeta */ - /** @typedef {FetchResultMeta & { location: string }} RedirectFetchResult */ - /** @typedef {FetchResultMeta & { entry: LockfileEntry, content: Buffer }} ContentFetchResult */ - /** @typedef {RedirectFetchResult | ContentFetchResult} FetchResult */ + isNullish() { + return this.nullish; + } - /** - * @param {string} url URL - * @param {FetchResult} cachedResult result from cache - * @param {function((Error | null)=, FetchResult=): void} callback callback - * @returns {void} - */ - const fetchContentRaw = (url, cachedResult, callback) => { - const requestTime = Date.now(); - fetch( - new URL(url), - { - headers: { - "accept-encoding": "gzip, deflate, br", - "user-agent": "webpack", - "if-none-match": cachedResult - ? cachedResult.etag || null - : null - } - }, - res => { - const etag = res.headers["etag"]; - const location = res.headers["location"]; - const cacheControl = res.headers["cache-control"]; - const { storeLock, storeCache, validUntil } = parseCacheControl( - cacheControl, - requestTime - ); - /** - * @param {Partial> & (Pick | Pick)} partialResult result - * @returns {void} - */ - const finishWith = partialResult => { - if ("location" in partialResult) { - logger.debug( - `GET ${url} [${res.statusCode}] -> ${partialResult.location}` - ); - } else { - logger.debug( - `GET ${url} [${res.statusCode}] ${Math.ceil( - partialResult.content.length / 1024 - )} kB${!storeLock ? " no-cache" : ""}` - ); - } - const result = { - ...partialResult, - fresh: true, - storeLock, - storeCache, - validUntil, - etag - }; - if (!storeCache) { - logger.log( - `${url} can't be stored in cache, due to Cache-Control header: ${cacheControl}` - ); - return callback(null, result); - } - cache.store( - url, - null, - { - ...result, - fresh: false - }, - err => { - if (err) { - logger.warn( - `${url} can't be stored in cache: ${err.message}` - ); - logger.debug(err.stack); - } - callback(null, result); - } - ); - }; - if (res.statusCode === 304) { - if ( - cachedResult.validUntil < validUntil || - cachedResult.storeLock !== storeLock || - cachedResult.storeCache !== storeCache || - cachedResult.etag !== etag - ) { - return finishWith(cachedResult); - } else { - logger.debug(`GET ${url} [${res.statusCode}] (unchanged)`); - return callback(null, { - ...cachedResult, - fresh: true - }); - } - } - if ( - location && - res.statusCode >= 301 && - res.statusCode <= 308 - ) { - return finishWith({ - location: new URL(location, url).href - }); - } - const contentType = res.headers["content-type"] || ""; - const bufferArr = []; + /** + * Can this expression have side effects? + * @returns {boolean} false: never has side effects + */ + couldHaveSideEffects() { + return this.sideEffects; + } - const contentEncoding = res.headers["content-encoding"]; - let stream = res; - if (contentEncoding === "gzip") { - stream = stream.pipe(createGunzip()); - } else if (contentEncoding === "br") { - stream = stream.pipe(createBrotliDecompress()); - } else if (contentEncoding === "deflate") { - stream = stream.pipe(createInflate()); - } + asBool() { + if (this.truthy) return true; + if (this.falsy || this.nullish) return false; + if (this.isBoolean()) return this.bool; + if (this.isNull()) return false; + if (this.isUndefined()) return false; + if (this.isString()) return this.string !== ""; + if (this.isNumber()) return this.number !== 0; + if (this.isBigInt()) return this.bigint !== BigInt(0); + if (this.isRegExp()) return true; + if (this.isArray()) return true; + if (this.isConstArray()) return true; + if (this.isWrapped()) { + return (this.prefix && this.prefix.asBool()) || + (this.postfix && this.postfix.asBool()) + ? true + : undefined; + } + if (this.isTemplateString()) { + const str = this.asString(); + if (typeof str === "string") return str !== ""; + } + return undefined; + } - stream.on("data", chunk => { - bufferArr.push(chunk); - }); + asNullish() { + const nullish = this.isNullish(); - stream.on("end", () => { - if (!res.complete) { - logger.log(`GET ${url} [${res.statusCode}] (terminated)`); - return callback(new Error(`${url} request was terminated`)); - } + if (nullish === true || this.isNull() || this.isUndefined()) return true; - const content = Buffer.concat(bufferArr); + if (nullish === false) return false; + if (this.isTruthy()) return false; + if (this.isBoolean()) return false; + if (this.isString()) return false; + if (this.isNumber()) return false; + if (this.isBigInt()) return false; + if (this.isRegExp()) return false; + if (this.isArray()) return false; + if (this.isConstArray()) return false; + if (this.isTemplateString()) return false; + if (this.isRegExp()) return false; - if (res.statusCode !== 200) { - logger.log(`GET ${url} [${res.statusCode}]`); - return callback( - new Error( - `${url} request status code = ${ - res.statusCode - }\n${content.toString("utf-8")}` - ) - ); - } + return undefined; + } - const integrity = computeIntegrity(content); - const entry = { resolved: url, integrity, contentType }; + asString() { + if (this.isBoolean()) return `${this.bool}`; + if (this.isNull()) return "null"; + if (this.isUndefined()) return "undefined"; + if (this.isString()) return this.string; + if (this.isNumber()) return `${this.number}`; + if (this.isBigInt()) return `${this.bigint}`; + if (this.isRegExp()) return `${this.regExp}`; + if (this.isArray()) { + let array = []; + for (const item of this.items) { + const itemStr = item.asString(); + if (itemStr === undefined) return undefined; + array.push(itemStr); + } + return `${array}`; + } + if (this.isConstArray()) return `${this.array}`; + if (this.isTemplateString()) { + let str = ""; + for (const part of this.parts) { + const partStr = part.asString(); + if (partStr === undefined) return undefined; + str += partStr; + } + return str; + } + return undefined; + } - finishWith({ - entry, - content - }); - }); - } - ).on("error", err => { - logger.log(`GET ${url} (error)`); - err.message += `\nwhile fetching ${url}`; - callback(err); - }); - }; + setString(string) { + this.type = TypeString; + this.string = string; + this.sideEffects = false; + return this; + } - const fetchContent = cachedWithKey( - /** - * @param {string} url URL - * @param {function((Error | null)=, { validUntil: number, etag?: string, entry: LockfileEntry, content: Buffer, fresh: boolean } | { validUntil: number, etag?: string, location: string, fresh: boolean }=): void} callback callback - * @returns {void} - */ (url, callback) => { - cache.get(url, null, (err, cachedResult) => { - if (err) return callback(err); - if (cachedResult) { - const isValid = cachedResult.validUntil >= Date.now(); - if (isValid) return callback(null, cachedResult); - } - fetchContentRaw(url, cachedResult, callback); - }); - }, - (url, callback) => fetchContentRaw(url, undefined, callback) - ); + setUndefined() { + this.type = TypeUndefined; + this.sideEffects = false; + return this; + } - const isAllowed = uri => { - for (const allowed of allowedUris) { - if (typeof allowed === "string") { - if (uri.startsWith(allowed)) return true; - } else if (typeof allowed === "function") { - if (allowed(uri)) return true; - } else { - if (allowed.test(uri)) return true; - } - } - return false; - }; + setNull() { + this.type = TypeNull; + this.sideEffects = false; + return this; + } - const getInfo = cachedWithKey( - /** - * @param {string} url the url - * @param {function((Error | null)=, { entry: LockfileEntry, content: Buffer }=): void} callback callback - * @returns {void} - */ - (url, callback) => { - if (!isAllowed(url)) { - return callback( - new Error( - `${url} doesn't match the allowedUris policy. These URIs are allowed:\n${allowedUris - .map(uri => ` - ${uri}`) - .join("\n")}` - ) - ); - } - getLockfile((err, lockfile) => { - if (err) return callback(err); - const entryOrString = lockfile.entries.get(url); - if (!entryOrString) { - if (frozen) { - return callback( - new Error( - `${url} has no lockfile entry and lockfile is frozen` - ) - ); - } - resolveContent(url, null, (err, result) => { - if (err) return callback(err); - storeResult(lockfile, url, result, callback); - }); - return; - } - if (typeof entryOrString === "string") { - const entryTag = entryOrString; - resolveContent(url, null, (err, result) => { - if (err) return callback(err); - if (!result.storeLock || entryTag === "ignore") - return callback(null, result); - if (frozen) { - return callback( - new Error( - `${url} used to have ${entryTag} lockfile entry and has content now, but lockfile is frozen` - ) - ); - } - if (!upgrade) { - return callback( - new Error( - `${url} used to have ${entryTag} lockfile entry and has content now. -This should be reflected in the lockfile, so this lockfile entry must be upgraded, but upgrading is not enabled. -Remove this line from the lockfile to force upgrading.` - ) - ); - } - storeResult(lockfile, url, result, callback); - }); - return; - } - let entry = entryOrString; - const doFetch = lockedContent => { - resolveContent(url, entry.integrity, (err, result) => { - if (err) { - if (lockedContent) { - logger.warn( - `Upgrade request to ${url} failed: ${err.message}` - ); - logger.debug(err.stack); - return callback(null, { - entry, - content: lockedContent - }); - } - return callback(err); - } - if (!result.storeLock) { - // When the lockfile entry should be no-cache - // we need to update the lockfile - if (frozen) { - return callback( - new Error( - `${url} has a lockfile entry and is no-cache now, but lockfile is frozen\nLockfile: ${entryToString( - entry - )}` - ) - ); - } - storeResult(lockfile, url, result, callback); - return; - } - if (!areLockfileEntriesEqual(result.entry, entry)) { - // When the lockfile entry is outdated - // we need to update the lockfile - if (frozen) { - return callback( - new Error( - `${url} has an outdated lockfile entry, but lockfile is frozen\nLockfile: ${entryToString( - entry - )}\nExpected: ${entryToString(result.entry)}` - ) - ); - } - storeResult(lockfile, url, result, callback); - return; - } - if (!lockedContent && cacheLocation) { - // When the lockfile cache content is missing - // we need to update the lockfile - if (frozen) { - return callback( - new Error( - `${url} is missing content in the lockfile cache, but lockfile is frozen\nLockfile: ${entryToString( - entry - )}` - ) - ); - } - storeResult(lockfile, url, result, callback); - return; - } - return callback(null, result); - }); - }; - if (cacheLocation) { - // When there is a lockfile cache - // we read the content from there - const key = getCacheKey(entry.resolved); - const filePath = join(intermediateFs, cacheLocation, key); - fs.readFile(filePath, (err, result) => { - const content = /** @type {Buffer} */ (result); - if (err) { - if (err.code === "ENOENT") return doFetch(); - return callback(err); - } - const continueWithCachedContent = result => { - if (!upgrade) { - // When not in upgrade mode, we accept the result from the lockfile cache - return callback(null, { entry, content }); - } - return doFetch(content); - }; - if (!verifyIntegrity(content, entry.integrity)) { - let contentWithChangedEol; - let isEolChanged = false; - try { - contentWithChangedEol = Buffer.from( - content.toString("utf-8").replace(/\r\n/g, "\n") - ); - isEolChanged = verifyIntegrity( - contentWithChangedEol, - entry.integrity - ); - } catch (e) { - // ignore - } - if (isEolChanged) { - if (!warnedAboutEol) { - const explainer = `Incorrect end of line sequence was detected in the lockfile cache. -The lockfile cache is protected by integrity checks, so any external modification will lead to a corrupted lockfile cache. -When using git make sure to configure .gitattributes correctly for the lockfile cache: - **/*webpack.lock.data/** -text -This will avoid that the end of line sequence is changed by git on Windows.`; - if (frozen) { - logger.error(explainer); - } else { - logger.warn(explainer); - logger.info( - "Lockfile cache will be automatically fixed now, but when lockfile is frozen this would result in an error." - ); - } - warnedAboutEol = true; - } - if (!frozen) { - // "fix" the end of line sequence of the lockfile content - logger.log( - `${filePath} fixed end of line sequence (\\r\\n instead of \\n).` - ); - intermediateFs.writeFile( - filePath, - contentWithChangedEol, - err => { - if (err) return callback(err); - continueWithCachedContent(contentWithChangedEol); - } - ); - return; - } - } - if (frozen) { - return callback( - new Error( - `${ - entry.resolved - } integrity mismatch, expected content with integrity ${ - entry.integrity - } but got ${computeIntegrity(content)}. -Lockfile corrupted (${ - isEolChanged - ? "end of line sequence was unexpectedly changed" - : "incorrectly merged? changed by other tools?" - }). -Run build with un-frozen lockfile to automatically fix lockfile.` - ) - ); - } else { - // "fix" the lockfile entry to the correct integrity - // the content has priority over the integrity value - entry = { - ...entry, - integrity: computeIntegrity(content) - }; - storeLockEntry(lockfile, url, entry); - } - } - continueWithCachedContent(result); - }); - } else { - doFetch(); - } - }); - } - ); + setNumber(number) { + this.type = TypeNumber; + this.number = number; + this.sideEffects = false; + return this; + } - const respondWithUrlModule = (url, resourceData, callback) => { - getInfo(url.href, (err, result) => { - if (err) return callback(err); - resourceData.resource = url.href; - resourceData.path = url.origin + url.pathname; - resourceData.query = url.search; - resourceData.fragment = url.hash; - resourceData.context = new URL( - ".", - result.entry.resolved - ).href.slice(0, -1); - resourceData.data.mimetype = result.entry.contentType; - callback(null, true); - }); - }; - normalModuleFactory.hooks.resolveForScheme - .for(scheme) - .tapAsync( - "HttpUriPlugin", - (resourceData, resolveData, callback) => { - respondWithUrlModule( - new URL(resourceData.resource), - resourceData, - callback - ); - } - ); - normalModuleFactory.hooks.resolveInScheme - .for(scheme) - .tapAsync("HttpUriPlugin", (resourceData, data, callback) => { - // Only handle relative urls (./xxx, ../xxx, /xxx, //xxx) - if ( - data.dependencyType !== "url" && - !/^\.{0,2}\//.test(resourceData.resource) - ) { - return callback(); - } - respondWithUrlModule( - new URL(resourceData.resource, data.context + "/"), - resourceData, - callback - ); - }); - const hooks = NormalModule.getCompilationHooks(compilation); - hooks.readResourceForScheme - .for(scheme) - .tapAsync("HttpUriPlugin", (resource, module, callback) => { - return getInfo(resource, (err, result) => { - if (err) return callback(err); - module.buildInfo.resourceIntegrity = result.entry.integrity; - callback(null, result.content); - }); - }); - hooks.needBuild.tapAsync( - "HttpUriPlugin", - (module, context, callback) => { - if ( - module.resource && - module.resource.startsWith(`${scheme}://`) - ) { - getInfo(module.resource, (err, result) => { - if (err) return callback(err); - if ( - result.entry.integrity !== - module.buildInfo.resourceIntegrity - ) { - return callback(null, true); - } - callback(); - }); - } else { - return callback(); - } - } - ); - } - compilation.hooks.finishModules.tapAsync( - "HttpUriPlugin", - (modules, callback) => { - if (!lockfileUpdates) return callback(); - const ext = extname(lockfileLocation); - const tempFile = join( - intermediateFs, - dirname(intermediateFs, lockfileLocation), - `.${basename(lockfileLocation, ext)}.${ - (Math.random() * 10000) | 0 - }${ext}` - ); + setBigInt(bigint) { + this.type = TypeBigInt; + this.bigint = bigint; + this.sideEffects = false; + return this; + } - const writeDone = () => { - const nextOperation = inProgressWrite.shift(); - if (nextOperation) { - nextOperation(); - } else { - inProgressWrite = undefined; - } - }; - const runWrite = () => { - intermediateFs.readFile(lockfileLocation, (err, buffer) => { - if (err && err.code !== "ENOENT") { - writeDone(); - return callback(err); - } - const lockfile = buffer - ? Lockfile.parse(buffer.toString("utf-8")) - : new Lockfile(); - for (const [key, value] of lockfileUpdates) { - lockfile.entries.set(key, value); - } - intermediateFs.writeFile(tempFile, lockfile.toString(), err => { - if (err) { - writeDone(); - return intermediateFs.unlink(tempFile, () => callback(err)); - } - intermediateFs.rename(tempFile, lockfileLocation, err => { - if (err) { - writeDone(); - return intermediateFs.unlink(tempFile, () => - callback(err) - ); - } - writeDone(); - callback(); - }); - }); - }); - }; - if (inProgressWrite) { - inProgressWrite.push(runWrite); - } else { - inProgressWrite = []; - runWrite(); - } - } - ); - } - ); + setBoolean(bool) { + this.type = TypeBoolean; + this.bool = bool; + this.sideEffects = false; + return this; } -} -module.exports = HttpUriPlugin; + setRegExp(regExp) { + this.type = TypeRegExp; + this.regExp = regExp; + this.sideEffects = false; + return this; + } + setIdentifier(identifier, rootInfo, getMembers) { + this.type = TypeIdentifier; + this.identifier = identifier; + this.rootInfo = rootInfo; + this.getMembers = getMembers; + this.sideEffects = true; + return this; + } -/***/ }), + setWrapped(prefix, postfix, innerExpressions) { + this.type = TypeWrapped; + this.prefix = prefix; + this.postfix = postfix; + this.wrappedInnerExpressions = innerExpressions; + this.sideEffects = true; + return this; + } -/***/ 41721: -/***/ (function(module) { + setOptions(options) { + this.type = TypeConditional; + this.options = options; + this.sideEffects = true; + return this; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + addOptions(options) { + if (!this.options) { + this.type = TypeConditional; + this.options = []; + this.sideEffects = true; + } + for (const item of options) { + this.options.push(item); + } + return this; + } + setItems(items) { + this.type = TypeArray; + this.items = items; + this.sideEffects = items.some(i => i.couldHaveSideEffects()); + return this; + } + setArray(array) { + this.type = TypeConstArray; + this.array = array; + this.sideEffects = false; + return this; + } -class ArraySerializer { - serialize(array, { write }) { - write(array.length); - for (const item of array) write(item); + setTemplateString(quasis, parts, kind) { + this.type = TypeTemplateString; + this.quasis = quasis; + this.parts = parts; + this.templateStringKind = kind; + this.sideEffects = parts.some(p => p.sideEffects); + return this; } - deserialize({ read }) { - const length = read(); - const array = []; - for (let i = 0; i < length; i++) { - array.push(read()); - } - return array; + + setTruthy() { + this.falsy = false; + this.truthy = true; + this.nullish = false; + return this; } -} -module.exports = ArraySerializer; + setFalsy() { + this.falsy = true; + this.truthy = false; + return this; + } + setNullish(value) { + this.nullish = value; -/***/ }), + if (value) return this.setFalsy(); -/***/ 97059: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + return this; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + setRange(range) { + this.range = range; + return this; + } + setSideEffects(sideEffects = true) { + this.sideEffects = sideEffects; + return this; + } + setExpression(expression) { + this.expression = expression; + return this; + } +} -const memoize = __webpack_require__(78676); -const SerializerMiddleware = __webpack_require__(83137); +/** + * @param {string} flags regexp flags + * @returns {boolean} is valid flags + */ +BasicEvaluatedExpression.isValidRegExpFlags = flags => { + const len = flags.length; -/** @typedef {import("./types").BufferSerializableType} BufferSerializableType */ -/** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */ + if (len === 0) return true; + if (len > 4) return false; -/* -Format: + // cspell:word gimy + let remaining = 0b0000; // bit per RegExp flag: gimy -File -> Section* + for (let i = 0; i < len; i++) + switch (flags.charCodeAt(i)) { + case 103 /* g */: + if (remaining & 0b1000) return false; + remaining |= 0b1000; + break; + case 105 /* i */: + if (remaining & 0b0100) return false; + remaining |= 0b0100; + break; + case 109 /* m */: + if (remaining & 0b0010) return false; + remaining |= 0b0010; + break; + case 121 /* y */: + if (remaining & 0b0001) return false; + remaining |= 0b0001; + break; + default: + return false; + } -Section -> NullsSection | - BooleansSection | - F64NumbersSection | - I32NumbersSection | - I8NumbersSection | - ShortStringSection | - StringSection | - BufferSection | - NopSection + return true; +}; +module.exports = BasicEvaluatedExpression; -NullsSection -> - NullHeaderByte | Null2HeaderByte | Null3HeaderByte | - Nulls8HeaderByte 0xnn (n:count - 4) | - Nulls32HeaderByte n:ui32 (n:count - 260) | -BooleansSection -> TrueHeaderByte | FalseHeaderByte | BooleansSectionHeaderByte BooleansCountAndBitsByte -F64NumbersSection -> F64NumbersSectionHeaderByte f64* -I32NumbersSection -> I32NumbersSectionHeaderByte i32* -I8NumbersSection -> I8NumbersSectionHeaderByte i8* -ShortStringSection -> ShortStringSectionHeaderByte ascii-byte* -StringSection -> StringSectionHeaderByte i32:length utf8-byte* -BufferSection -> BufferSectionHeaderByte i32:length byte* -NopSection --> NopSectionHeaderByte +/***/ }), -ShortStringSectionHeaderByte -> 0b1nnn_nnnn (n:length) +/***/ 91145: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -F64NumbersSectionHeaderByte -> 0b001n_nnnn (n:count - 1) -I32NumbersSectionHeaderByte -> 0b010n_nnnn (n:count - 1) -I8NumbersSectionHeaderByte -> 0b011n_nnnn (n:count - 1) +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -NullsSectionHeaderByte -> 0b0001_nnnn (n:count - 1) -BooleansCountAndBitsByte -> - 0b0000_1xxx (count = 3) | - 0b0001_xxxx (count = 4) | - 0b001x_xxxx (count = 5) | - 0b01xx_xxxx (count = 6) | - 0b1nnn_nnnn (n:count - 7, 7 <= count <= 133) - 0xff n:ui32 (n:count, 134 <= count < 2^32) -StringSectionHeaderByte -> 0b0000_1110 -BufferSectionHeaderByte -> 0b0000_1111 -NopSectionHeaderByte -> 0b0000_1011 -FalseHeaderByte -> 0b0000_1100 -TrueHeaderByte -> 0b0000_1101 -RawNumber -> n (n <= 10) +const Entrypoint = __webpack_require__(13795); + +/** @typedef {import("../Chunk")} Chunk */ + +/** + * @param {Entrypoint} entrypoint a chunk group + * @param {Chunk} excludedChunk1 current chunk which is excluded + * @param {Chunk} excludedChunk2 runtime chunk which is excluded + * @returns {Set} chunks + */ +const getAllChunks = (entrypoint, excludedChunk1, excludedChunk2) => { + const queue = new Set([entrypoint]); + const chunks = new Set(); + for (const entrypoint of queue) { + for (const chunk of entrypoint.chunks) { + if (chunk === excludedChunk1) continue; + if (chunk === excludedChunk2) continue; + chunks.add(chunk); + } + for (const parent of entrypoint.parentsIterable) { + if (parent instanceof Entrypoint) queue.add(parent); + } + } + return chunks; +}; +exports.getAllChunks = getAllChunks; + + +/***/ }), +/***/ 84508: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const LAZY_HEADER = 0x0b; -const TRUE_HEADER = 0x0c; -const FALSE_HEADER = 0x0d; -const BOOLEANS_HEADER = 0x0e; -const NULL_HEADER = 0x10; -const NULL2_HEADER = 0x11; -const NULL3_HEADER = 0x12; -const NULLS8_HEADER = 0x13; -const NULLS32_HEADER = 0x14; -const NULL_AND_I8_HEADER = 0x15; -const NULL_AND_I32_HEADER = 0x16; -const NULL_AND_TRUE_HEADER = 0x17; -const NULL_AND_FALSE_HEADER = 0x18; -const STRING_HEADER = 0x1e; -const BUFFER_HEADER = 0x1f; -const I8_HEADER = 0x60; -const I32_HEADER = 0x40; -const F64_HEADER = 0x20; -const SHORT_STRING_HEADER = 0x80; -/** Uplift high-order bits */ -const NUMBERS_HEADER_MASK = 0xe0; -const NUMBERS_COUNT_MASK = 0x1f; // 0b0001_1111 -const SHORT_STRING_LENGTH_MASK = 0x7f; // 0b0111_1111 -const HEADER_SIZE = 1; -const I8_SIZE = 1; -const I32_SIZE = 4; -const F64_SIZE = 8; +const { ConcatSource, RawSource } = __webpack_require__(51255); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const { + getChunkFilenameTemplate, + getCompilationHooks +} = __webpack_require__(89464); +const { + generateEntryStartup, + updateHashForEntryStartup +} = __webpack_require__(98124); -const MEASURE_START_OPERATION = Symbol("MEASURE_START_OPERATION"); -const MEASURE_END_OPERATION = Symbol("MEASURE_END_OPERATION"); +/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {typeof MEASURE_START_OPERATION} MEASURE_START_OPERATION_TYPE */ -/** @typedef {typeof MEASURE_END_OPERATION} MEASURE_END_OPERATION_TYPE */ +class CommonJsChunkFormatPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "CommonJsChunkFormatPlugin", + compilation => { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + "CommonJsChunkLoadingPlugin", + (chunk, set, { chunkGraph }) => { + if (chunk.hasRuntime()) return; + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { + set.add(RuntimeGlobals.require); + set.add(RuntimeGlobals.startupEntrypoint); + set.add(RuntimeGlobals.externalInstallChunk); + } + } + ); + const hooks = getCompilationHooks(compilation); + hooks.renderChunk.tap( + "CommonJsChunkFormatPlugin", + (modules, renderContext) => { + const { chunk, chunkGraph, runtimeTemplate } = renderContext; + const source = new ConcatSource(); + source.add(`exports.id = ${JSON.stringify(chunk.id)};\n`); + source.add(`exports.ids = ${JSON.stringify(chunk.ids)};\n`); + source.add(`exports.modules = `); + source.add(modules); + source.add(";\n"); + const runtimeModules = + chunkGraph.getChunkRuntimeModulesInOrder(chunk); + if (runtimeModules.length > 0) { + source.add("exports.runtime =\n"); + source.add( + Template.renderChunkRuntimeModules( + runtimeModules, + renderContext + ) + ); + } + const entries = Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ); + if (entries.length > 0) { + const runtimeChunk = entries[0][1].getRuntimeChunk(); + const currentOutputName = compilation + .getPath( + getChunkFilenameTemplate(chunk, compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ) + .split("/"); + const runtimeOutputName = compilation + .getPath( + getChunkFilenameTemplate( + runtimeChunk, + compilation.outputOptions + ), + { + chunk: runtimeChunk, + contentHashType: "javascript" + } + ) + .split("/"); -const identifyNumber = n => { - if (n === (n | 0)) { - if (n <= 127 && n >= -128) return 0; - if (n <= 2147483647 && n >= -2147483648) return 1; + // remove filename, we only need the directory + currentOutputName.pop(); + + // remove common parts + while ( + currentOutputName.length > 0 && + runtimeOutputName.length > 0 && + currentOutputName[0] === runtimeOutputName[0] + ) { + currentOutputName.shift(); + runtimeOutputName.shift(); + } + + // create final path + const runtimePath = + (currentOutputName.length > 0 + ? "../".repeat(currentOutputName.length) + : "./") + runtimeOutputName.join("/"); + + const entrySource = new ConcatSource(); + entrySource.add( + `(${ + runtimeTemplate.supportsArrowFunction() + ? "() => " + : "function() " + }{\n` + ); + entrySource.add("var exports = {};\n"); + entrySource.add(source); + entrySource.add(";\n\n// load runtime\n"); + entrySource.add( + `var __webpack_require__ = require(${JSON.stringify( + runtimePath + )});\n` + ); + entrySource.add( + `${RuntimeGlobals.externalInstallChunk}(exports);\n` + ); + const startupSource = new RawSource( + generateEntryStartup( + chunkGraph, + runtimeTemplate, + entries, + chunk, + false + ) + ); + entrySource.add( + hooks.renderStartup.call( + startupSource, + entries[entries.length - 1][0], + { + ...renderContext, + inlined: false + } + ) + ); + entrySource.add("\n})()"); + return entrySource; + } + return source; + } + ); + hooks.chunkHash.tap( + "CommonJsChunkFormatPlugin", + (chunk, hash, { chunkGraph }) => { + if (chunk.hasRuntime()) return; + hash.update("CommonJsChunkFormatPlugin"); + hash.update("1"); + const entries = Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ); + updateHashForEntryStartup(hash, chunkGraph, entries, chunk); + } + ); + } + ); } - return 2; +} + +module.exports = CommonJsChunkFormatPlugin; + + +/***/ }), + +/***/ 61291: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("../../declarations/WebpackOptions").ChunkLoadingType} ChunkLoadingType */ +/** @typedef {import("../Compiler")} Compiler */ + +/** @type {WeakMap>} */ +const enabledTypes = new WeakMap(); + +const getEnabledTypes = compiler => { + let set = enabledTypes.get(compiler); + if (set === undefined) { + set = new Set(); + enabledTypes.set(compiler, set); + } + return set; }; -/** - * @typedef {PrimitiveSerializableType[]} DeserializedType - * @typedef {BufferSerializableType[]} SerializedType - * @extends {SerializerMiddleware} - */ -class BinaryMiddleware extends SerializerMiddleware { +class EnableChunkLoadingPlugin { /** - * @param {DeserializedType} data data - * @param {Object} context context object - * @returns {SerializedType|Promise} serialized data + * @param {ChunkLoadingType} type library type that should be available */ - serialize(data, context) { - return this._serialize(data, context); + constructor(type) { + this.type = type; } - _serializeLazy(fn, context) { - return SerializerMiddleware.serializeLazy(fn, data => - this._serialize(data, context) - ); + /** + * @param {Compiler} compiler the compiler instance + * @param {ChunkLoadingType} type type of library + * @returns {void} + */ + static setEnabled(compiler, type) { + getEnabledTypes(compiler).add(type); } /** - * @param {DeserializedType} data data - * @param {Object} context context object - * @param {{ leftOverBuffer: Buffer | null, allocationSize: number, increaseCounter: number }} allocationScope allocation scope - * @returns {SerializedType} serialized data + * @param {Compiler} compiler the compiler instance + * @param {ChunkLoadingType} type type of library + * @returns {void} */ - _serialize( - data, - context, - allocationScope = { - allocationSize: 1024, - increaseCounter: 0, - leftOverBuffer: null - } - ) { - /** @type {Buffer} */ - let leftOverBuffer = null; - /** @type {BufferSerializableType[]} */ - let buffers = []; - /** @type {Buffer} */ - let currentBuffer = allocationScope ? allocationScope.leftOverBuffer : null; - allocationScope.leftOverBuffer = null; - let currentPosition = 0; - if (currentBuffer === null) { - currentBuffer = Buffer.allocUnsafe(allocationScope.allocationSize); + static checkEnabled(compiler, type) { + if (!getEnabledTypes(compiler).has(type)) { + throw new Error( + `Chunk loading type "${type}" is not enabled. ` + + "EnableChunkLoadingPlugin need to be used to enable this type of chunk loading. " + + 'This usually happens through the "output.enabledChunkLoadingTypes" option. ' + + 'If you are using a function as entry which sets "chunkLoading", you need to add all potential chunk loading types to "output.enabledChunkLoadingTypes". ' + + "These types are enabled: " + + Array.from(getEnabledTypes(compiler)).join(", ") + ); } - const allocate = bytesNeeded => { - if (currentBuffer !== null) { - if (currentBuffer.length - currentPosition >= bytesNeeded) return; - flush(); - } - if (leftOverBuffer && leftOverBuffer.length >= bytesNeeded) { - currentBuffer = leftOverBuffer; - leftOverBuffer = null; - } else { - currentBuffer = Buffer.allocUnsafe( - Math.max(bytesNeeded, allocationScope.allocationSize) - ); - if ( - !(allocationScope.increaseCounter = - (allocationScope.increaseCounter + 1) % 4) && - allocationScope.allocationSize < 16777216 - ) { - allocationScope.allocationSize = allocationScope.allocationSize << 1; - } - } - }; - const flush = () => { - if (currentBuffer !== null) { - if (currentPosition > 0) { - buffers.push( - Buffer.from( - currentBuffer.buffer, - currentBuffer.byteOffset, - currentPosition - ) - ); - } - if ( - !leftOverBuffer || - leftOverBuffer.length < currentBuffer.length - currentPosition - ) { - leftOverBuffer = Buffer.from( - currentBuffer.buffer, - currentBuffer.byteOffset + currentPosition, - currentBuffer.byteLength - currentPosition - ); - } + } - currentBuffer = null; - currentPosition = 0; - } - }; - const writeU8 = byte => { - currentBuffer.writeUInt8(byte, currentPosition++); - }; - const writeU32 = ui32 => { - currentBuffer.writeUInt32LE(ui32, currentPosition); - currentPosition += 4; - }; - const measureStack = []; - const measureStart = () => { - measureStack.push(buffers.length, currentPosition); - }; - const measureEnd = () => { - const oldPos = measureStack.pop(); - const buffersIndex = measureStack.pop(); - let size = currentPosition - oldPos; - for (let i = buffersIndex; i < buffers.length; i++) { - size += buffers[i].length; - } - return size; - }; - for (let i = 0; i < data.length; i++) { - const thing = data[i]; - switch (typeof thing) { - case "function": { - if (!SerializerMiddleware.isLazy(thing)) - throw new Error("Unexpected function " + thing); - /** @type {SerializedType | (() => SerializedType)} */ - let serializedData = - SerializerMiddleware.getLazySerializedValue(thing); - if (serializedData === undefined) { - if (SerializerMiddleware.isLazy(thing, this)) { - flush(); - allocationScope.leftOverBuffer = leftOverBuffer; - const result = - /** @type {(Exclude>)[]} */ ( - thing() - ); - const data = this._serialize(result, context, allocationScope); - leftOverBuffer = allocationScope.leftOverBuffer; - allocationScope.leftOverBuffer = null; - SerializerMiddleware.setLazySerializedValue(thing, data); - serializedData = data; - } else { - serializedData = this._serializeLazy(thing, context); - flush(); - buffers.push(serializedData); - break; - } - } else { - if (typeof serializedData === "function") { - flush(); - buffers.push(serializedData); - break; - } - } - const lengths = []; - for (const item of serializedData) { - let last; - if (typeof item === "function") { - lengths.push(0); - } else if (item.length === 0) { - // ignore - } else if ( - lengths.length > 0 && - (last = lengths[lengths.length - 1]) !== 0 - ) { - const remaining = 0xffffffff - last; - if (remaining >= item.length) { - lengths[lengths.length - 1] += item.length; - } else { - lengths.push(item.length - remaining); - lengths[lengths.length - 2] = 0xffffffff; - } - } else { - lengths.push(item.length); - } - } - allocate(5 + lengths.length * 4); - writeU8(LAZY_HEADER); - writeU32(lengths.length); - for (const l of lengths) { - writeU32(l); - } - flush(); - for (const item of serializedData) { - buffers.push(item); - } - break; - } - case "string": { - const len = Buffer.byteLength(thing); - if (len >= 128 || len !== thing.length) { - allocate(len + HEADER_SIZE + I32_SIZE); - writeU8(STRING_HEADER); - writeU32(len); - currentBuffer.write(thing, currentPosition); - currentPosition += len; - } else if (len >= 70) { - allocate(len + HEADER_SIZE); - writeU8(SHORT_STRING_HEADER | len); + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { type } = this; - currentBuffer.write(thing, currentPosition, "latin1"); - currentPosition += len; - } else { - allocate(len + HEADER_SIZE); - writeU8(SHORT_STRING_HEADER | len); + // Only enable once + const enabled = getEnabledTypes(compiler); + if (enabled.has(type)) return; + enabled.add(type); - for (let i = 0; i < len; i++) { - currentBuffer[currentPosition++] = thing.charCodeAt(i); - } - } + if (typeof type === "string") { + switch (type) { + case "jsonp": { + const JsonpChunkLoadingPlugin = __webpack_require__(83121); + new JsonpChunkLoadingPlugin().apply(compiler); break; } - case "number": { - const type = identifyNumber(thing); - if (type === 0 && thing >= 0 && thing <= 10) { - // shortcut for very small numbers - allocate(I8_SIZE); - writeU8(thing); - break; - } - /** - * amount of numbers to write - * @type {number} - */ - let n = 1; - for (; n < 32 && i + n < data.length; n++) { - const item = data[i + n]; - if (typeof item !== "number") break; - if (identifyNumber(item) !== type) break; - } - switch (type) { - case 0: - allocate(HEADER_SIZE + I8_SIZE * n); - writeU8(I8_HEADER | (n - 1)); - while (n > 0) { - currentBuffer.writeInt8( - /** @type {number} */ (data[i]), - currentPosition - ); - currentPosition += I8_SIZE; - n--; - i++; - } - break; - case 1: - allocate(HEADER_SIZE + I32_SIZE * n); - writeU8(I32_HEADER | (n - 1)); - while (n > 0) { - currentBuffer.writeInt32LE( - /** @type {number} */ (data[i]), - currentPosition - ); - currentPosition += I32_SIZE; - n--; - i++; - } - break; - case 2: - allocate(HEADER_SIZE + F64_SIZE * n); - writeU8(F64_HEADER | (n - 1)); - while (n > 0) { - currentBuffer.writeDoubleLE( - /** @type {number} */ (data[i]), - currentPosition - ); - currentPosition += F64_SIZE; - n--; - i++; - } - break; - } - - i--; + case "import-scripts": { + const ImportScriptsChunkLoadingPlugin = __webpack_require__(54182); + new ImportScriptsChunkLoadingPlugin().apply(compiler); break; } - case "boolean": { - let lastByte = thing === true ? 1 : 0; - const bytes = []; - let count = 1; - let n; - for (n = 1; n < 0xffffffff && i + n < data.length; n++) { - const item = data[i + n]; - if (typeof item !== "boolean") break; - const pos = count & 0x7; - if (pos === 0) { - bytes.push(lastByte); - lastByte = item === true ? 1 : 0; - } else if (item === true) { - lastByte |= 1 << pos; - } - count++; - } - i += count - 1; - if (count === 1) { - allocate(HEADER_SIZE); - writeU8(lastByte === 1 ? TRUE_HEADER : FALSE_HEADER); - } else if (count === 2) { - allocate(HEADER_SIZE * 2); - writeU8(lastByte & 1 ? TRUE_HEADER : FALSE_HEADER); - writeU8(lastByte & 2 ? TRUE_HEADER : FALSE_HEADER); - } else if (count <= 6) { - allocate(HEADER_SIZE + I8_SIZE); - writeU8(BOOLEANS_HEADER); - writeU8((1 << count) | lastByte); - } else if (count <= 133) { - allocate(HEADER_SIZE + I8_SIZE + I8_SIZE * bytes.length + I8_SIZE); - writeU8(BOOLEANS_HEADER); - writeU8(0x80 | (count - 7)); - for (const byte of bytes) writeU8(byte); - writeU8(lastByte); - } else { - allocate( - HEADER_SIZE + - I8_SIZE + - I32_SIZE + - I8_SIZE * bytes.length + - I8_SIZE - ); - writeU8(BOOLEANS_HEADER); - writeU8(0xff); - writeU32(count); - for (const byte of bytes) writeU8(byte); - writeU8(lastByte); - } + case "require": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const CommonJsChunkLoadingPlugin = __webpack_require__(1313); + new CommonJsChunkLoadingPlugin({ + asyncChunkLoading: false + }).apply(compiler); break; } - case "object": { - if (thing === null) { - let n; - for (n = 1; n < 0x100000104 && i + n < data.length; n++) { - const item = data[i + n]; - if (item !== null) break; - } - i += n - 1; - if (n === 1) { - if (i + 1 < data.length) { - const next = data[i + 1]; - if (next === true) { - allocate(HEADER_SIZE); - writeU8(NULL_AND_TRUE_HEADER); - i++; - } else if (next === false) { - allocate(HEADER_SIZE); - writeU8(NULL_AND_FALSE_HEADER); - i++; - } else if (typeof next === "number") { - const type = identifyNumber(next); - if (type === 0) { - allocate(HEADER_SIZE + I8_SIZE); - writeU8(NULL_AND_I8_HEADER); - currentBuffer.writeInt8(next, currentPosition); - currentPosition += I8_SIZE; - i++; - } else if (type === 1) { - allocate(HEADER_SIZE + I32_SIZE); - writeU8(NULL_AND_I32_HEADER); - currentBuffer.writeInt32LE(next, currentPosition); - currentPosition += I32_SIZE; - i++; - } else { - allocate(HEADER_SIZE); - writeU8(NULL_HEADER); - } - } else { - allocate(HEADER_SIZE); - writeU8(NULL_HEADER); - } - } else { - allocate(HEADER_SIZE); - writeU8(NULL_HEADER); - } - } else if (n === 2) { - allocate(HEADER_SIZE); - writeU8(NULL2_HEADER); - } else if (n === 3) { - allocate(HEADER_SIZE); - writeU8(NULL3_HEADER); - } else if (n < 260) { - allocate(HEADER_SIZE + I8_SIZE); - writeU8(NULLS8_HEADER); - writeU8(n - 4); - } else { - allocate(HEADER_SIZE + I32_SIZE); - writeU8(NULLS32_HEADER); - writeU32(n - 260); - } - } else if (Buffer.isBuffer(thing)) { - if (thing.length < 8192) { - allocate(HEADER_SIZE + I32_SIZE + thing.length); - writeU8(BUFFER_HEADER); - writeU32(thing.length); - thing.copy(currentBuffer, currentPosition); - currentPosition += thing.length; - } else { - allocate(HEADER_SIZE + I32_SIZE); - writeU8(BUFFER_HEADER); - writeU32(thing.length); - flush(); - buffers.push(thing); - } - } + case "async-node": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const CommonJsChunkLoadingPlugin = __webpack_require__(1313); + new CommonJsChunkLoadingPlugin({ + asyncChunkLoading: true + }).apply(compiler); break; } - case "symbol": { - if (thing === MEASURE_START_OPERATION) { - measureStart(); - } else if (thing === MEASURE_END_OPERATION) { - const size = measureEnd(); - allocate(HEADER_SIZE + I32_SIZE); - writeU8(I32_HEADER); - currentBuffer.writeInt32LE(size, currentPosition); - currentPosition += I32_SIZE; - } + case "import": { + const ModuleChunkLoadingPlugin = __webpack_require__(89831); + new ModuleChunkLoadingPlugin().apply(compiler); break; } + case "universal": + // TODO implement universal chunk loading + throw new Error("Universal Chunk Loading is not implemented yet"); + default: + throw new Error(`Unsupported chunk loading type ${type}. +Plugins which provide custom chunk loading types must call EnableChunkLoadingPlugin.setEnabled(compiler, type) to disable this error.`); } + } else { + // TODO support plugin instances here + // apply them to the compiler } - flush(); + } +} - allocationScope.leftOverBuffer = leftOverBuffer; +module.exports = EnableChunkLoadingPlugin; - // avoid leaking memory - currentBuffer = null; - leftOverBuffer = null; - allocationScope = undefined; - const _buffers = buffers; - buffers = undefined; - return _buffers; - } +/***/ }), + +/***/ 77106: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const util = __webpack_require__(73837); +const { RawSource, ReplaceSource } = __webpack_require__(51255); +const Generator = __webpack_require__(93401); +const InitFragment = __webpack_require__(55870); +const HarmonyCompatibilityDependency = __webpack_require__(72906); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +// TODO: clean up this file +// replace with newer constructs + +const deprecatedGetInitFragments = util.deprecate( + (template, dependency, templateContext) => + template.getInitFragments(dependency, templateContext), + "DependencyTemplate.getInitFragment is deprecated (use apply(dep, source, { initFragments }) instead)", + "DEP_WEBPACK_JAVASCRIPT_GENERATOR_GET_INIT_FRAGMENTS" +); + +const TYPES = new Set(["javascript"]); + +class JavascriptGenerator extends Generator { /** - * @param {SerializedType} data data - * @param {Object} context context object - * @returns {DeserializedType|Promise} deserialized data + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - deserialize(data, context) { - return this._deserialize(data, context); + getTypes(module) { + return TYPES; } - _createLazyDeserialized(content, context) { - return SerializerMiddleware.createLazy( - memoize(() => this._deserialize(content, context)), - this, - undefined, - content - ); + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + const originalSource = module.originalSource(); + if (!originalSource) { + return 39; + } + return originalSource.size(); } - _deserializeLazy(fn, context) { - return SerializerMiddleware.deserializeLazy(fn, data => - this._deserialize(data, context) - ); + /** + * @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) { + // Only harmony modules are valid for optimization + if ( + !module.buildMeta || + module.buildMeta.exportsType !== "namespace" || + module.presentationalDependencies === undefined || + !module.presentationalDependencies.some( + d => d instanceof HarmonyCompatibilityDependency + ) + ) { + return "Module is not an ECMAScript module"; + } + + // Some expressions are not compatible with module concatenation + // because they may produce unexpected results. The plugin bails out + // if some were detected upfront. + if (module.buildInfo && module.buildInfo.moduleConcatenationBailout) { + return `Module uses ${module.buildInfo.moduleConcatenationBailout}`; + } } /** - * @param {SerializedType} data data - * @param {Object} context context object - * @returns {DeserializedType} deserialized data + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code */ - _deserialize(data, context) { - let currentDataItem = 0; - let currentBuffer = data[0]; - let currentIsBuffer = Buffer.isBuffer(currentBuffer); - let currentPosition = 0; + generate(module, generateContext) { + const originalSource = module.originalSource(); + if (!originalSource) { + return new RawSource("throw new Error('No source available');"); + } - const retainedBuffer = context.retainedBuffer || (x => x); + const source = new ReplaceSource(originalSource); + const initFragments = []; - const checkOverflow = () => { - if (currentPosition >= currentBuffer.length) { - currentPosition = 0; - currentDataItem++; - currentBuffer = - currentDataItem < data.length ? data[currentDataItem] : null; - currentIsBuffer = Buffer.isBuffer(currentBuffer); - } - }; - const isInCurrentBuffer = n => { - return currentIsBuffer && n + currentPosition <= currentBuffer.length; - }; - const ensureBuffer = () => { - if (!currentIsBuffer) { - throw new Error( - currentBuffer === null - ? "Unexpected end of stream" - : "Unexpected lazy element in stream" + this.sourceModule(module, initFragments, source, generateContext); + + return InitFragment.addToSource(source, initFragments, generateContext); + } + + /** + * @param {Module} module the module to generate + * @param {InitFragment[]} initFragments mutable list of init fragments + * @param {ReplaceSource} source the current replace source which can be modified + * @param {GenerateContext} generateContext the generateContext + * @returns {void} + */ + sourceModule(module, initFragments, source, generateContext) { + for (const dependency of module.dependencies) { + this.sourceDependency( + module, + dependency, + initFragments, + source, + generateContext + ); + } + + if (module.presentationalDependencies !== undefined) { + for (const dependency of module.presentationalDependencies) { + this.sourceDependency( + module, + dependency, + initFragments, + source, + generateContext ); } - }; - /** - * Reads n bytes - * @param {number} n amount of bytes to read - * @returns {Buffer} buffer with bytes - */ - const read = n => { - ensureBuffer(); - const rem = currentBuffer.length - currentPosition; - if (rem < n) { - const buffers = [read(rem)]; - n -= rem; - ensureBuffer(); - while (currentBuffer.length < n) { - const b = /** @type {Buffer} */ (currentBuffer); - buffers.push(b); - n -= b.length; - currentDataItem++; - currentBuffer = - currentDataItem < data.length ? data[currentDataItem] : null; - currentIsBuffer = Buffer.isBuffer(currentBuffer); - ensureBuffer(); - } - buffers.push(read(n)); - return Buffer.concat(buffers); - } - const b = /** @type {Buffer} */ (currentBuffer); - const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n); - currentPosition += n; - checkOverflow(); - return res; - }; - /** - * Reads up to n bytes - * @param {number} n amount of bytes to read - * @returns {Buffer} buffer with bytes - */ - const readUpTo = n => { - ensureBuffer(); - const rem = currentBuffer.length - currentPosition; - if (rem < n) { - n = rem; - } - const b = /** @type {Buffer} */ (currentBuffer); - const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n); - currentPosition += n; - checkOverflow(); - return res; - }; - const readU8 = () => { - ensureBuffer(); - /** - * There is no need to check remaining buffer size here - * since {@link checkOverflow} guarantees at least one byte remaining - */ - const byte = /** @type {Buffer} */ (currentBuffer).readUInt8( - currentPosition - ); - currentPosition += I8_SIZE; - checkOverflow(); - return byte; - }; - const readU32 = () => { - return read(I32_SIZE).readUInt32LE(0); - }; - const readBits = (data, n) => { - let mask = 1; - while (n !== 0) { - result.push((data & mask) !== 0); - mask = mask << 1; - n--; - } - }; - const dispatchTable = Array.from({ length: 256 }).map((_, header) => { - switch (header) { - case LAZY_HEADER: - return () => { - const count = readU32(); - const lengths = Array.from({ length: count }).map(() => readU32()); - const content = []; - for (let l of lengths) { - if (l === 0) { - if (typeof currentBuffer !== "function") { - throw new Error("Unexpected non-lazy element in stream"); - } - content.push(currentBuffer); - currentDataItem++; - currentBuffer = - currentDataItem < data.length ? data[currentDataItem] : null; - currentIsBuffer = Buffer.isBuffer(currentBuffer); - } else { - do { - const buf = readUpTo(l); - l -= buf.length; - content.push(retainedBuffer(buf)); - } while (l > 0); - } - } - result.push(this._createLazyDeserialized(content, context)); - }; - case BUFFER_HEADER: - return () => { - const len = readU32(); - result.push(retainedBuffer(read(len))); - }; - case TRUE_HEADER: - return () => result.push(true); - case FALSE_HEADER: - return () => result.push(false); - case NULL3_HEADER: - return () => result.push(null, null, null); - case NULL2_HEADER: - return () => result.push(null, null); - case NULL_HEADER: - return () => result.push(null); - case NULL_AND_TRUE_HEADER: - return () => result.push(null, true); - case NULL_AND_FALSE_HEADER: - return () => result.push(null, false); - case NULL_AND_I8_HEADER: - return () => { - if (currentIsBuffer) { - result.push( - null, - /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition) - ); - currentPosition += I8_SIZE; - checkOverflow(); - } else { - result.push(null, read(I8_SIZE).readInt8(0)); - } - }; - case NULL_AND_I32_HEADER: - return () => { - result.push(null); - if (isInCurrentBuffer(I32_SIZE)) { - result.push( - /** @type {Buffer} */ (currentBuffer).readInt32LE( - currentPosition - ) - ); - currentPosition += I32_SIZE; - checkOverflow(); - } else { - result.push(read(I32_SIZE).readInt32LE(0)); - } - }; - case NULLS8_HEADER: - return () => { - const len = readU8() + 4; - for (let i = 0; i < len; i++) { - result.push(null); - } - }; - case NULLS32_HEADER: - return () => { - const len = readU32() + 260; - for (let i = 0; i < len; i++) { - result.push(null); - } - }; - case BOOLEANS_HEADER: - return () => { - const innerHeader = readU8(); - if ((innerHeader & 0xf0) === 0) { - readBits(innerHeader, 3); - } else if ((innerHeader & 0xe0) === 0) { - readBits(innerHeader, 4); - } else if ((innerHeader & 0xc0) === 0) { - readBits(innerHeader, 5); - } else if ((innerHeader & 0x80) === 0) { - readBits(innerHeader, 6); - } else if (innerHeader !== 0xff) { - let count = (innerHeader & 0x7f) + 7; - while (count > 8) { - readBits(readU8(), 8); - count -= 8; - } - readBits(readU8(), count); - } else { - let count = readU32(); - while (count > 8) { - readBits(readU8(), 8); - count -= 8; - } - readBits(readU8(), count); - } - }; - case STRING_HEADER: - return () => { - const len = readU32(); - if (isInCurrentBuffer(len) && currentPosition + len < 0x7fffffff) { - result.push( - currentBuffer.toString( - undefined, - currentPosition, - currentPosition + len - ) - ); - currentPosition += len; - checkOverflow(); - } else { - result.push(read(len).toString()); - } - }; - case SHORT_STRING_HEADER: - return () => result.push(""); - case SHORT_STRING_HEADER | 1: - return () => { - if (currentIsBuffer && currentPosition < 0x7ffffffe) { - result.push( - currentBuffer.toString( - "latin1", - currentPosition, - currentPosition + 1 - ) - ); - currentPosition++; - checkOverflow(); - } else { - result.push(read(1).toString("latin1")); - } - }; - case I8_HEADER: - return () => { - if (currentIsBuffer) { - result.push( - /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition) - ); - currentPosition++; - checkOverflow(); - } else { - result.push(read(1).readInt8(0)); - } - }; - default: - if (header <= 10) { - return () => result.push(header); - } else if ((header & SHORT_STRING_HEADER) === SHORT_STRING_HEADER) { - const len = header & SHORT_STRING_LENGTH_MASK; - return () => { - if ( - isInCurrentBuffer(len) && - currentPosition + len < 0x7fffffff - ) { - result.push( - currentBuffer.toString( - "latin1", - currentPosition, - currentPosition + len - ) - ); - currentPosition += len; - checkOverflow(); - } else { - result.push(read(len).toString("latin1")); - } - }; - } else if ((header & NUMBERS_HEADER_MASK) === F64_HEADER) { - const len = (header & NUMBERS_COUNT_MASK) + 1; - return () => { - const need = F64_SIZE * len; - if (isInCurrentBuffer(need)) { - for (let i = 0; i < len; i++) { - result.push( - /** @type {Buffer} */ (currentBuffer).readDoubleLE( - currentPosition - ) - ); - currentPosition += F64_SIZE; - } - checkOverflow(); - } else { - const buf = read(need); - for (let i = 0; i < len; i++) { - result.push(buf.readDoubleLE(i * F64_SIZE)); - } - } - }; - } else if ((header & NUMBERS_HEADER_MASK) === I32_HEADER) { - const len = (header & NUMBERS_COUNT_MASK) + 1; - return () => { - const need = I32_SIZE * len; - if (isInCurrentBuffer(need)) { - for (let i = 0; i < len; i++) { - result.push( - /** @type {Buffer} */ (currentBuffer).readInt32LE( - currentPosition - ) - ); - currentPosition += I32_SIZE; - } - checkOverflow(); - } else { - const buf = read(need); - for (let i = 0; i < len; i++) { - result.push(buf.readInt32LE(i * I32_SIZE)); - } - } - }; - } else if ((header & NUMBERS_HEADER_MASK) === I8_HEADER) { - const len = (header & NUMBERS_COUNT_MASK) + 1; - return () => { - const need = I8_SIZE * len; - if (isInCurrentBuffer(need)) { - for (let i = 0; i < len; i++) { - result.push( - /** @type {Buffer} */ (currentBuffer).readInt8( - currentPosition - ) - ); - currentPosition += I8_SIZE; - } - checkOverflow(); - } else { - const buf = read(need); - for (let i = 0; i < len; i++) { - result.push(buf.readInt8(i * I8_SIZE)); - } - } - }; - } else { - return () => { - throw new Error( - `Unexpected header byte 0x${header.toString(16)}` - ); - }; - } - } - }); - - /** @type {DeserializedType} */ - let result = []; - while (currentBuffer !== null) { - if (typeof currentBuffer === "function") { - result.push(this._deserializeLazy(currentBuffer, context)); - currentDataItem++; - currentBuffer = - currentDataItem < data.length ? data[currentDataItem] : null; - currentIsBuffer = Buffer.isBuffer(currentBuffer); - } else { - const header = readU8(); - dispatchTable[header](); - } } - // avoid leaking memory in context - let _result = result; - result = undefined; - return _result; + for (const childBlock of module.blocks) { + this.sourceBlock( + module, + childBlock, + initFragments, + source, + generateContext + ); + } } -} - -module.exports = BinaryMiddleware; - -module.exports.MEASURE_START_OPERATION = MEASURE_START_OPERATION; -module.exports.MEASURE_END_OPERATION = MEASURE_END_OPERATION; - - -/***/ }), - -/***/ 93475: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - + /** + * @param {Module} module the module to generate + * @param {DependenciesBlock} block the dependencies block which will be processed + * @param {InitFragment[]} initFragments mutable list of init fragments + * @param {ReplaceSource} source the current replace source which can be modified + * @param {GenerateContext} generateContext the generateContext + * @returns {void} + */ + sourceBlock(module, block, initFragments, source, generateContext) { + for (const dependency of block.dependencies) { + this.sourceDependency( + module, + dependency, + initFragments, + source, + generateContext + ); + } -class DateObjectSerializer { - serialize(obj, { write }) { - write(obj.getTime()); - } - deserialize({ read }) { - return new Date(read()); + for (const childBlock of block.blocks) { + this.sourceBlock( + module, + childBlock, + initFragments, + source, + generateContext + ); + } } -} - -module.exports = DateObjectSerializer; + /** + * @param {Module} module the current module + * @param {Dependency} dependency the dependency to generate + * @param {InitFragment[]} initFragments mutable list of init fragments + * @param {ReplaceSource} source the current replace source which can be modified + * @param {GenerateContext} generateContext the render context + * @returns {void} + */ + sourceDependency(module, dependency, initFragments, source, generateContext) { + const constructor = /** @type {new (...args: any[]) => Dependency} */ ( + dependency.constructor + ); + const template = generateContext.dependencyTemplates.get(constructor); + if (!template) { + throw new Error( + "No template for dependency: " + dependency.constructor.name + ); + } -/***/ }), - -/***/ 79479: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -class ErrorObjectSerializer { - constructor(Type) { - this.Type = Type; - } - - serialize(obj, { write }) { - write(obj.message); - write(obj.stack); - } + const templateContext = { + runtimeTemplate: generateContext.runtimeTemplate, + dependencyTemplates: generateContext.dependencyTemplates, + moduleGraph: generateContext.moduleGraph, + chunkGraph: generateContext.chunkGraph, + module, + runtime: generateContext.runtime, + runtimeRequirements: generateContext.runtimeRequirements, + concatenationScope: generateContext.concatenationScope, + codeGenerationResults: generateContext.codeGenerationResults, + initFragments + }; - deserialize({ read }) { - const err = new this.Type(); + template.apply(dependency, source, templateContext); - err.message = read(); - err.stack = read(); + // TODO remove in webpack 6 + if ("getInitFragments" in template) { + const fragments = deprecatedGetInitFragments( + template, + dependency, + templateContext + ); - return err; + if (fragments) { + for (const fragment of fragments) { + initFragments.push(fragment); + } + } + } } } -module.exports = ErrorObjectSerializer; +module.exports = JavascriptGenerator; /***/ }), -/***/ 65321: +/***/ 89464: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const { constants } = __webpack_require__(14300); -const { pipeline } = __webpack_require__(12781); +const { SyncWaterfallHook, SyncHook, SyncBailHook } = __webpack_require__(41242); +const vm = __webpack_require__(26144); const { - createBrotliCompress, - createBrotliDecompress, - createGzip, - createGunzip, - constants: zConstants -} = __webpack_require__(59796); + ConcatSource, + OriginalSource, + PrefixSource, + RawSource, + CachedSource +} = __webpack_require__(51255); +const Compilation = __webpack_require__(85720); +const { tryRunOrWebpackError } = __webpack_require__(11351); +const HotUpdateChunk = __webpack_require__(9597); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const { last, someInIterable } = __webpack_require__(39104); +const StringXor = __webpack_require__(40293); +const { compareModulesByIdentifier } = __webpack_require__(29579); const createHash = __webpack_require__(49835); -const { dirname, join, mkdirp } = __webpack_require__(17139); -const memoize = __webpack_require__(78676); -const SerializerMiddleware = __webpack_require__(83137); - -/** @typedef {typeof import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ -/** @typedef {import("./types").BufferSerializableType} BufferSerializableType */ - -/* -Format: - -File -> Header Section* - -Version -> u32 -AmountOfSections -> u32 -SectionSize -> i32 (if less than zero represents lazy value) - -Header -> Version AmountOfSections SectionSize* - -Buffer -> n bytes -Section -> Buffer - -*/ +const { intersectRuntime } = __webpack_require__(17156); +const JavascriptGenerator = __webpack_require__(77106); +const JavascriptParser = __webpack_require__(29050); -// "wpc" + 1 in little-endian -const VERSION = 0x01637077; +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../util/Hash")} Hash */ /** - * @param {Buffer[]} buffers buffers - * @param {string | Hash} hashFunction hash function to use - * @returns {string} hash + * @param {Chunk} chunk a chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {boolean} true, when a JS file is needed for this chunk */ -const hashForName = (buffers, hashFunction) => { - const hash = createHash(hashFunction); - for (const buf of buffers) hash.update(buf); - return /** @type {string} */ (hash.digest("hex")); +const chunkHasJs = (chunk, chunkGraph) => { + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) return true; + + return chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript") + ? true + : false; }; -const COMPRESSION_CHUNK_SIZE = 100 * 1024 * 1024; -const DECOMPRESSION_CHUNK_SIZE = 100 * 1024 * 1024; +const printGeneratedCodeForStack = (module, code) => { + const lines = code.split("\n"); + const n = `${lines.length}`.length; + return `\n\nGenerated code for ${module.identifier()}\n${lines + .map((line, i, lines) => { + const iStr = `${i + 1}`; + return `${" ".repeat(n - iStr.length)}${iStr} | ${line}`; + }) + .join("\n")}`; +}; -const writeUInt64LE = Buffer.prototype.writeBigUInt64LE - ? (buf, value, offset) => { - buf.writeBigUInt64LE(BigInt(value), offset); - } - : (buf, value, offset) => { - const low = value % 0x100000000; - const high = (value - low) / 0x100000000; - buf.writeUInt32LE(low, offset); - buf.writeUInt32LE(high, offset + 4); - }; +/** + * @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 + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {boolean} strictMode rendering in strict context + */ -const readUInt64LE = Buffer.prototype.readBigUInt64LE - ? (buf, offset) => { - return Number(buf.readBigUInt64LE(offset)); - } - : (buf, offset) => { - const low = buf.readUInt32LE(offset); - const high = buf.readUInt32LE(offset + 4); - return high * 0x100000000 + low; - }; +/** + * @typedef {Object} MainRenderContext + * @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 + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {string} hash hash to be used for render call + * @property {boolean} strictMode rendering in strict context + */ /** - * @typedef {Object} SerializeResult - * @property {string | false} name - * @property {number} size - * @property {Promise=} backgroundJob + * @typedef {Object} ChunkRenderContext + * @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 + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {InitFragment[]} chunkInitFragments init fragments for the chunk + * @property {boolean} strictMode rendering in strict context */ /** - * @param {FileMiddleware} middleware this - * @param {BufferSerializableType[] | Promise} data data to be serialized - * @param {string | boolean} name file base name - * @param {function(string | false, Buffer[]): Promise} writeFile writes a file - * @param {string | Hash} hashFunction hash function to use - * @returns {Promise} resulting file pointer and promise + * @typedef {Object} RenderBootstrapContext + * @property {Chunk} chunk the chunk + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {string} hash hash to be used for render call */ -const serialize = async ( - middleware, - data, - name, - writeFile, - hashFunction = "md4" -) => { - /** @type {(Buffer[] | Buffer | SerializeResult | Promise)[]} */ - const processedData = []; - /** @type {WeakMap>} */ - const resultToLazy = new WeakMap(); - /** @type {Buffer[]} */ - let lastBuffers = undefined; - for (const item of await data) { - if (typeof item === "function") { - if (!SerializerMiddleware.isLazy(item)) - throw new Error("Unexpected function"); - if (!SerializerMiddleware.isLazy(item, middleware)) { - throw new Error( - "Unexpected lazy value with non-this target (can't pass through lazy values)" - ); - } - lastBuffers = undefined; - const serializedInfo = SerializerMiddleware.getLazySerializedValue(item); - if (serializedInfo) { - if (typeof serializedInfo === "function") { - throw new Error( - "Unexpected lazy value with non-this target (can't pass through lazy values)" - ); - } else { - processedData.push(serializedInfo); - } - } else { - const content = item(); - if (content) { - const options = SerializerMiddleware.getLazyOptions(item); - processedData.push( - serialize( - middleware, - content, - (options && options.name) || true, - writeFile, - hashFunction - ).then(result => { - /** @type {any} */ (item).options.size = result.size; - resultToLazy.set(result, item); - return result; - }) - ); - } else { - throw new Error( - "Unexpected falsy value returned by lazy value function" - ); - } - } - } else if (item) { - if (lastBuffers) { - lastBuffers.push(item); - } else { - lastBuffers = [item]; - processedData.push(lastBuffers); - } - } else { - throw new Error("Unexpected falsy value in items array"); - } - } - /** @type {Promise[]} */ - const backgroundJobs = []; - const resolvedData = ( - await Promise.all( - /** @type {Promise[]} */ ( - processedData - ) - ) - ).map(item => { - if (Array.isArray(item) || Buffer.isBuffer(item)) return item; - backgroundJobs.push(item.backgroundJob); - // create pointer buffer from size and name - const name = /** @type {string} */ (item.name); - const nameBuffer = Buffer.from(name); - const buf = Buffer.allocUnsafe(8 + nameBuffer.length); - writeUInt64LE(buf, item.size, 0); - nameBuffer.copy(buf, 8, 0); - const lazy = resultToLazy.get(item); - SerializerMiddleware.setLazySerializedValue(lazy, buf); - return buf; - }); - const lengths = []; - for (const item of resolvedData) { - if (Array.isArray(item)) { - let l = 0; - for (const b of item) l += b.length; - while (l > 0x7fffffff) { - lengths.push(0x7fffffff); - l -= 0x7fffffff; - } - lengths.push(l); - } else if (item) { - lengths.push(-item.length); - } else { - throw new Error("Unexpected falsy value in resolved data " + item); - } - } - const header = Buffer.allocUnsafe(8 + lengths.length * 4); - header.writeUInt32LE(VERSION, 0); - header.writeUInt32LE(lengths.length, 4); - for (let i = 0; i < lengths.length; i++) { - header.writeInt32LE(lengths[i], 8 + i * 4); - } - const buf = [header]; - for (const item of resolvedData) { - if (Array.isArray(item)) { - for (const b of item) buf.push(b); - } else if (item) { - buf.push(item); - } - } - if (name === true) { - name = hashForName(buf, hashFunction); - } - backgroundJobs.push(writeFile(name, buf)); - let size = 0; - for (const b of buf) size += b.length; - return { - size, - name, - backgroundJob: - backgroundJobs.length === 1 - ? backgroundJobs[0] - : Promise.all(backgroundJobs) - }; -}; +/** @typedef {RenderContext & { inlined: boolean }} StartupRenderContext */ /** - * @param {FileMiddleware} middleware this - * @param {string | false} name filename - * @param {function(string | false): Promise} readFile read content of a file - * @returns {Promise} deserialized data + * @typedef {Object} CompilationHooks + * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModuleContent + * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModuleContainer + * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModulePackage + * @property {SyncWaterfallHook<[Source, RenderContext]>} renderChunk + * @property {SyncWaterfallHook<[Source, RenderContext]>} renderMain + * @property {SyncWaterfallHook<[Source, RenderContext]>} renderContent + * @property {SyncWaterfallHook<[Source, RenderContext]>} render + * @property {SyncWaterfallHook<[Source, Module, StartupRenderContext]>} renderStartup + * @property {SyncWaterfallHook<[string, RenderBootstrapContext]>} renderRequire + * @property {SyncBailHook<[Module, RenderBootstrapContext], string>} inlineInRuntimeBailout + * @property {SyncBailHook<[Module, RenderContext], string>} embedInRuntimeBailout + * @property {SyncBailHook<[RenderContext], string>} strictRuntimeBailout + * @property {SyncHook<[Chunk, Hash, ChunkHashContext]>} chunkHash + * @property {SyncBailHook<[Chunk, RenderContext], boolean>} useSourceMap */ -const deserialize = async (middleware, name, readFile) => { - const contents = await readFile(name); - if (contents.length === 0) throw new Error("Empty file " + name); - let contentsIndex = 0; - let contentItem = contents[0]; - let contentItemLength = contentItem.length; - let contentPosition = 0; - if (contentItemLength === 0) throw new Error("Empty file " + name); - const nextContent = () => { - contentsIndex++; - contentItem = contents[contentsIndex]; - contentItemLength = contentItem.length; - contentPosition = 0; - }; - const ensureData = n => { - if (contentPosition === contentItemLength) { - nextContent(); - } - while (contentItemLength - contentPosition < n) { - const remaining = contentItem.slice(contentPosition); - let lengthFromNext = n - remaining.length; - const buffers = [remaining]; - for (let i = contentsIndex + 1; i < contents.length; i++) { - const l = contents[i].length; - if (l > lengthFromNext) { - buffers.push(contents[i].slice(0, lengthFromNext)); - contents[i] = contents[i].slice(lengthFromNext); - lengthFromNext = 0; - break; - } else { - buffers.push(contents[i]); - contentsIndex = i; - lengthFromNext -= l; - } - } - if (lengthFromNext > 0) throw new Error("Unexpected end of data"); - contentItem = Buffer.concat(buffers, n); - contentItemLength = n; - contentPosition = 0; - } - }; - const readUInt32LE = () => { - ensureData(4); - const value = contentItem.readUInt32LE(contentPosition); - contentPosition += 4; - return value; - }; - const readInt32LE = () => { - ensureData(4); - const value = contentItem.readInt32LE(contentPosition); - contentPosition += 4; - return value; - }; - const readSlice = l => { - ensureData(l); - if (contentPosition === 0 && contentItemLength === l) { - const result = contentItem; - if (contentsIndex + 1 < contents.length) { - nextContent(); - } else { - contentPosition = l; - } - return result; - } - const result = contentItem.slice(contentPosition, contentPosition + l); - contentPosition += l; - // we clone the buffer here to allow the original content to be garbage collected - return l * 2 < contentItem.buffer.byteLength ? Buffer.from(result) : result; - }; - const version = readUInt32LE(); - if (version !== VERSION) { - throw new Error("Invalid file version"); - } - const sectionCount = readUInt32LE(); - const lengths = []; - let lastLengthPositive = false; - for (let i = 0; i < sectionCount; i++) { - const value = readInt32LE(); - const valuePositive = value >= 0; - if (lastLengthPositive && valuePositive) { - lengths[lengths.length - 1] += value; - } else { - lengths.push(value); - lastLengthPositive = valuePositive; - } - } - const result = []; - for (let length of lengths) { - if (length < 0) { - const slice = readSlice(-length); - const size = Number(readUInt64LE(slice, 0)); - const nameBuffer = slice.slice(8); - const name = nameBuffer.toString(); - result.push( - SerializerMiddleware.createLazy( - memoize(() => deserialize(middleware, name, readFile)), - middleware, - { - name, - size - }, - slice - ) + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class JavascriptModulesPlugin { + /** + * @param {Compilation} compilation the compilation + * @returns {CompilationHooks} the attached hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" ); - } else { - if (contentPosition === contentItemLength) { - nextContent(); - } else if (contentPosition !== 0) { - if (length <= contentItemLength - contentPosition) { - result.push( - Buffer.from( - contentItem.buffer, - contentItem.byteOffset + contentPosition, - length - ) - ); - contentPosition += length; - length = 0; - } else { - const l = contentItemLength - contentPosition; - result.push( - Buffer.from( - contentItem.buffer, - contentItem.byteOffset + contentPosition, - l - ) - ); - length -= l; - contentPosition = contentItemLength; - } - } else { - if (length >= contentItemLength) { - result.push(contentItem); - length -= contentItemLength; - contentPosition = contentItemLength; - } else { - result.push( - Buffer.from(contentItem.buffer, contentItem.byteOffset, length) - ); - contentPosition += length; - length = 0; - } - } - while (length > 0) { - nextContent(); - if (length >= contentItemLength) { - result.push(contentItem); - length -= contentItemLength; - contentPosition = contentItemLength; - } else { - result.push( - Buffer.from(contentItem.buffer, contentItem.byteOffset, length) - ); - contentPosition += length; - length = 0; - } - } } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + renderModuleContent: new SyncWaterfallHook([ + "source", + "module", + "renderContext" + ]), + renderModuleContainer: new SyncWaterfallHook([ + "source", + "module", + "renderContext" + ]), + renderModulePackage: new SyncWaterfallHook([ + "source", + "module", + "renderContext" + ]), + render: new SyncWaterfallHook(["source", "renderContext"]), + renderContent: new SyncWaterfallHook(["source", "renderContext"]), + renderStartup: new SyncWaterfallHook([ + "source", + "module", + "startupRenderContext" + ]), + renderChunk: new SyncWaterfallHook(["source", "renderContext"]), + renderMain: new SyncWaterfallHook(["source", "renderContext"]), + renderRequire: new SyncWaterfallHook(["code", "renderContext"]), + inlineInRuntimeBailout: new SyncBailHook(["module", "renderContext"]), + embedInRuntimeBailout: new SyncBailHook(["module", "renderContext"]), + strictRuntimeBailout: new SyncBailHook(["renderContext"]), + chunkHash: new SyncHook(["chunk", "hash", "context"]), + useSourceMap: new SyncBailHook(["chunk", "renderContext"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; } - return result; -}; -/** - * @typedef {BufferSerializableType[]} DeserializedType - * @typedef {true} SerializedType - * @extends {SerializerMiddleware} - */ -class FileMiddleware extends SerializerMiddleware { - /** - * @param {IntermediateFileSystem} fs filesystem - * @param {string | Hash} hashFunction hash function to use - */ - constructor(fs, hashFunction = "md4") { - super(); - this.fs = fs; - this._hashFunction = hashFunction; + constructor(options = {}) { + this.options = options; + /** @type {WeakMap} */ + this._moduleFactoryCache = new WeakMap(); } + /** - * @param {DeserializedType} data data - * @param {Object} context context object - * @returns {SerializedType|Promise} serialized data + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - serialize(data, context) { - const { filename, extension = "" } = context; - return new Promise((resolve, reject) => { - mkdirp(this.fs, dirname(this.fs, filename), err => { - if (err) return reject(err); - - // It's important that we don't touch existing files during serialization - // because serialize may read existing files (when deserializing) - const allWrittenFiles = new Set(); - const writeFile = async (name, content) => { - const file = name - ? join(this.fs, filename, `../${name}${extension}`) - : filename; - await new Promise((resolve, reject) => { - let stream = this.fs.createWriteStream(file + "_"); - let compression; - if (file.endsWith(".gz")) { - compression = createGzip({ - chunkSize: COMPRESSION_CHUNK_SIZE, - level: zConstants.Z_BEST_SPEED - }); - } else if (file.endsWith(".br")) { - compression = createBrotliCompress({ - chunkSize: COMPRESSION_CHUNK_SIZE, - params: { - [zConstants.BROTLI_PARAM_MODE]: zConstants.BROTLI_MODE_TEXT, - [zConstants.BROTLI_PARAM_QUALITY]: 2, - [zConstants.BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING]: true, - [zConstants.BROTLI_PARAM_SIZE_HINT]: content.reduce( - (size, b) => size + b.length, - 0 - ) - } - }); - } - if (compression) { - pipeline(compression, stream, reject); - stream = compression; - stream.on("finish", () => resolve()); - } else { - stream.on("error", err => reject(err)); - stream.on("finish", () => resolve()); - } - for (const b of content) stream.write(b); - stream.end(); + apply(compiler) { + compiler.hooks.compilation.tap( + "JavascriptModulesPlugin", + (compilation, { normalModuleFactory }) => { + const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); + normalModuleFactory.hooks.createParser + .for("javascript/auto") + .tap("JavascriptModulesPlugin", options => { + return new JavascriptParser("auto"); }); - if (name) allWrittenFiles.add(file); - }; - - resolve( - serialize(this, data, false, writeFile, this._hashFunction).then( - async ({ backgroundJob }) => { - await backgroundJob; + normalModuleFactory.hooks.createParser + .for("javascript/dynamic") + .tap("JavascriptModulesPlugin", options => { + return new JavascriptParser("script"); + }); + normalModuleFactory.hooks.createParser + .for("javascript/esm") + .tap("JavascriptModulesPlugin", options => { + return new JavascriptParser("module"); + }); + normalModuleFactory.hooks.createGenerator + .for("javascript/auto") + .tap("JavascriptModulesPlugin", () => { + return new JavascriptGenerator(); + }); + normalModuleFactory.hooks.createGenerator + .for("javascript/dynamic") + .tap("JavascriptModulesPlugin", () => { + return new JavascriptGenerator(); + }); + normalModuleFactory.hooks.createGenerator + .for("javascript/esm") + .tap("JavascriptModulesPlugin", () => { + return new JavascriptGenerator(); + }); + compilation.hooks.renderManifest.tap( + "JavascriptModulesPlugin", + (result, options) => { + const { + hash, + chunk, + chunkGraph, + moduleGraph, + runtimeTemplate, + dependencyTemplates, + outputOptions, + codeGenerationResults + } = options; - // Rename the index file to disallow access during inconsistent file state - await new Promise(resolve => - this.fs.rename(filename, filename + ".old", err => { - resolve(); - }) - ); + const hotUpdateChunk = + chunk instanceof HotUpdateChunk ? chunk : null; - // update all written files - await Promise.all( - Array.from( - allWrittenFiles, - file => - new Promise((resolve, reject) => { - this.fs.rename(file + "_", file, err => { - if (err) return reject(err); - resolve(); - }); - }) - ) + let render; + const filenameTemplate = + JavascriptModulesPlugin.getChunkFilenameTemplate( + chunk, + outputOptions ); + if (hotUpdateChunk) { + render = () => + this.renderChunk( + { + chunk, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + codeGenerationResults, + strictMode: runtimeTemplate.isModule() + }, + hooks + ); + } else if (chunk.hasRuntime()) { + render = () => + this.renderMain( + { + hash, + chunk, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + codeGenerationResults, + strictMode: runtimeTemplate.isModule() + }, + hooks, + compilation + ); + } else { + if (!chunkHasJs(chunk, chunkGraph)) { + return result; + } - // As final step automatically update the index file to have a consistent pack again - await new Promise(resolve => { - this.fs.rename(filename + "_", filename, err => { - if (err) return reject(err); - resolve(); - }); - }); - return /** @type {true} */ (true); + render = () => + this.renderChunk( + { + chunk, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + codeGenerationResults, + strictMode: runtimeTemplate.isModule() + }, + hooks + ); } - ) - ); - }); - }); - } - /** - * @param {SerializedType} data data - * @param {Object} context context object - * @returns {DeserializedType|Promise} deserialized data - */ - deserialize(data, context) { - const { filename, extension = "" } = context; - const readFile = name => - new Promise((resolve, reject) => { - const file = name - ? join(this.fs, filename, `../${name}${extension}`) - : filename; - this.fs.stat(file, (err, stats) => { - if (err) { - reject(err); - return; - } - let remaining = /** @type {number} */ (stats.size); - let currentBuffer; - let currentBufferUsed; - const buf = []; - let decompression; - if (file.endsWith(".gz")) { - decompression = createGunzip({ - chunkSize: DECOMPRESSION_CHUNK_SIZE - }); - } else if (file.endsWith(".br")) { - decompression = createBrotliDecompress({ - chunkSize: DECOMPRESSION_CHUNK_SIZE + result.push({ + render, + filenameTemplate, + pathOptions: { + hash, + runtime: chunk.runtime, + chunk, + contentHashType: "javascript" + }, + info: { + javascriptModule: compilation.runtimeTemplate.isModule() + }, + identifier: hotUpdateChunk + ? `hotupdatechunk${chunk.id}` + : `chunk${chunk.id}`, + hash: chunk.contentHash.javascript }); + + return result; } - if (decompression) { - let newResolve, newReject; - resolve( - Promise.all([ - new Promise((rs, rj) => { - newResolve = rs; - newReject = rj; - }), - new Promise((resolve, reject) => { - decompression.on("data", chunk => buf.push(chunk)); - decompression.on("end", () => resolve()); - decompression.on("error", err => reject(err)); - }) - ]).then(() => buf) - ); - resolve = newResolve; - reject = newReject; + ); + compilation.hooks.chunkHash.tap( + "JavascriptModulesPlugin", + (chunk, hash, context) => { + hooks.chunkHash.call(chunk, hash, context); + if (chunk.hasRuntime()) { + this.updateHashWithBootstrap( + hash, + { + hash: "0000", + chunk, + chunkGraph: context.chunkGraph, + moduleGraph: context.moduleGraph, + runtimeTemplate: context.runtimeTemplate + }, + hooks + ); + } } - this.fs.open(file, "r", (err, fd) => { - if (err) { - reject(err); - return; + ); + compilation.hooks.contentHash.tap("JavascriptModulesPlugin", chunk => { + const { + chunkGraph, + moduleGraph, + runtimeTemplate, + outputOptions: { + hashSalt, + hashDigest, + hashDigestLength, + hashFunction } - const read = () => { - if (currentBuffer === undefined) { - currentBuffer = Buffer.allocUnsafeSlow( - Math.min( - constants.MAX_LENGTH, - remaining, - decompression ? DECOMPRESSION_CHUNK_SIZE : Infinity - ) - ); - currentBufferUsed = 0; - } - let readBuffer = currentBuffer; - let readOffset = currentBufferUsed; - let readLength = currentBuffer.length - currentBufferUsed; - // values passed to fs.read must be valid int32 values - if (readOffset > 0x7fffffff) { - readBuffer = currentBuffer.slice(readOffset); - readOffset = 0; - } - if (readLength > 0x7fffffff) { - readLength = 0x7fffffff; - } - this.fs.read( - fd, - readBuffer, - readOffset, - readLength, - null, - (err, bytesRead) => { - if (err) { - this.fs.close(fd, () => { - reject(err); - }); - return; - } - currentBufferUsed += bytesRead; - remaining -= bytesRead; - if (currentBufferUsed === currentBuffer.length) { - if (decompression) { - decompression.write(currentBuffer); - } else { - buf.push(currentBuffer); - } - currentBuffer = undefined; - if (remaining === 0) { - if (decompression) { - decompression.end(); - } - this.fs.close(fd, err => { - if (err) { - reject(err); - return; - } - resolve(buf); - }); - return; - } - } - read(); - } - ); - }; - read(); + } = compilation; + const hash = createHash(hashFunction); + if (hashSalt) hash.update(hashSalt); + if (chunk.hasRuntime()) { + this.updateHashWithBootstrap( + hash, + { + hash: "0000", + chunk, + chunkGraph: compilation.chunkGraph, + moduleGraph: compilation.moduleGraph, + runtimeTemplate: compilation.runtimeTemplate + }, + hooks + ); + } else { + hash.update(`${chunk.id} `); + hash.update(chunk.ids ? chunk.ids.join(",") : ""); + } + hooks.chunkHash.call(chunk, hash, { + chunkGraph, + moduleGraph, + runtimeTemplate }); + const modules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "javascript" + ); + if (modules) { + const xor = new StringXor(); + for (const m of modules) { + xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); + } + xor.updateHash(hash); + } + const runtimeModules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "runtime" + ); + if (runtimeModules) { + const xor = new StringXor(); + for (const m of runtimeModules) { + xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); + } + xor.updateHash(hash); + } + const digest = /** @type {string} */ (hash.digest(hashDigest)); + chunk.contentHash.javascript = digest.substr(0, hashDigestLength); }); - }); - return deserialize(this, false, readFile); - } -} - -module.exports = FileMiddleware; - - -/***/ }), - -/***/ 86791: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -class MapObjectSerializer { - serialize(obj, { write }) { - write(obj.size); - for (const key of obj.keys()) { - write(key); - } - for (const value of obj.values()) { - write(value); - } - } - deserialize({ read }) { - let size = read(); - const map = new Map(); - const keys = []; - for (let i = 0; i < size; i++) { - keys.push(read()); - } - for (let i = 0; i < size; i++) { - map.set(keys[i], read()); - } - return map; - } -} - -module.exports = MapObjectSerializer; - - -/***/ }), - -/***/ 21048: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -class NullPrototypeObjectSerializer { - serialize(obj, { write }) { - const keys = Object.keys(obj); - for (const key of keys) { - write(key); - } - write(null); - for (const key of keys) { - write(obj[key]); - } - } - deserialize({ read }) { - const obj = Object.create(null); - const keys = []; - let key = read(); - while (key !== null) { - keys.push(key); - key = read(); - } - for (const key of keys) { - obj[key] = read(); - } - return obj; - } -} - -module.exports = NullPrototypeObjectSerializer; - - -/***/ }), - -/***/ 34795: -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const createHash = __webpack_require__(49835); -const ArraySerializer = __webpack_require__(41721); -const DateObjectSerializer = __webpack_require__(93475); -const ErrorObjectSerializer = __webpack_require__(79479); -const MapObjectSerializer = __webpack_require__(86791); -const NullPrototypeObjectSerializer = __webpack_require__(21048); -const PlainObjectSerializer = __webpack_require__(33040); -const RegExpObjectSerializer = __webpack_require__(57328); -const SerializerMiddleware = __webpack_require__(83137); -const SetObjectSerializer = __webpack_require__(79240); - -/** @typedef {typeof import("../util/Hash")} Hash */ -/** @typedef {import("./types").ComplexSerializableType} ComplexSerializableType */ -/** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */ - -/** @typedef {new (...params: any[]) => any} Constructor */ - -/* - -Format: - -File -> Section* -Section -> ObjectSection | ReferenceSection | EscapeSection | OtherSection - -ObjectSection -> ESCAPE ( - number:relativeOffset (number > 0) | - string:request (string|null):export -) Section:value* ESCAPE ESCAPE_END_OBJECT -ReferenceSection -> ESCAPE number:relativeOffset (number < 0) -EscapeSection -> ESCAPE ESCAPE_ESCAPE_VALUE (escaped value ESCAPE) -EscapeSection -> ESCAPE ESCAPE_UNDEFINED (escaped value ESCAPE) -OtherSection -> any (except ESCAPE) - -Why using null as escape value? -Multiple null values can merged by the BinaryMiddleware, which makes it very efficient -Technically any value can be used. - -*/ - -/** - * @typedef {Object} ObjectSerializerContext - * @property {function(any): void} write - */ - -/** - * @typedef {Object} ObjectDeserializerContext - * @property {function(): any} read - */ - -/** - * @typedef {Object} ObjectSerializer - * @property {function(any, ObjectSerializerContext): void} serialize - * @property {function(ObjectDeserializerContext): any} deserialize - */ + compilation.hooks.additionalTreeRuntimeRequirements.tap( + "JavascriptModulesPlugin", + (chunk, set, { chunkGraph }) => { + if ( + !set.has(RuntimeGlobals.startupNoDefault) && + chunkGraph.hasChunkEntryDependentChunks(chunk) + ) { + set.add(RuntimeGlobals.onChunksLoaded); + set.add(RuntimeGlobals.require); + } + } + ); + compilation.hooks.executeModule.tap( + "JavascriptModulesPlugin", + (options, context) => { + const source = + options.codeGenerationResult.sources.get("javascript"); + if (source === undefined) return; + const { module, moduleObject } = options; + const code = source.source(); -const setSetSize = (set, size) => { - let i = 0; - for (const item of set) { - if (i++ >= size) { - set.delete(item); - } - } -}; + const fn = vm.runInThisContext( + `(function(${module.moduleArgument}, ${module.exportsArgument}, __webpack_require__) {\n${code}\n/**/})`, + { + filename: module.identifier(), + lineOffset: -1 + } + ); + try { + fn.call( + moduleObject.exports, + moduleObject, + moduleObject.exports, + context.__webpack_require__ + ); + } catch (e) { + e.stack += printGeneratedCodeForStack(options.module, code); + throw e; + } + } + ); + compilation.hooks.executeModule.tap( + "JavascriptModulesPlugin", + (options, context) => { + const source = options.codeGenerationResult.sources.get("runtime"); + if (source === undefined) return; + let code = source.source(); + if (typeof code !== "string") code = code.toString(); -const setMapSize = (map, size) => { - let i = 0; - for (const item of map.keys()) { - if (i++ >= size) { - map.delete(item); - } + const fn = vm.runInThisContext( + `(function(__webpack_require__) {\n${code}\n/**/})`, + { + filename: options.module.identifier(), + lineOffset: -1 + } + ); + try { + fn.call(null, context.__webpack_require__); + } catch (e) { + e.stack += printGeneratedCodeForStack(options.module, code); + throw e; + } + } + ); + } + ); } -}; - -/** - * @param {Buffer} buffer buffer - * @param {string | Hash} hashFunction hash function to use - * @returns {string} hash - */ -const toHash = (buffer, hashFunction) => { - const hash = createHash(hashFunction); - hash.update(buffer); - return /** @type {string} */ (hash.digest("latin1")); -}; - -const ESCAPE = null; -const ESCAPE_ESCAPE_VALUE = null; -const ESCAPE_END_OBJECT = true; -const ESCAPE_UNDEFINED = false; - -const CURRENT_VERSION = 2; - -const serializers = new Map(); -const serializerInversed = new Map(); - -const loadedRequests = new Set(); - -const NOT_SERIALIZABLE = {}; -const jsTypes = new Map(); -jsTypes.set(Object, new PlainObjectSerializer()); -jsTypes.set(Array, new ArraySerializer()); -jsTypes.set(null, new NullPrototypeObjectSerializer()); -jsTypes.set(Map, new MapObjectSerializer()); -jsTypes.set(Set, new SetObjectSerializer()); -jsTypes.set(Date, new DateObjectSerializer()); -jsTypes.set(RegExp, new RegExpObjectSerializer()); -jsTypes.set(Error, new ErrorObjectSerializer(Error)); -jsTypes.set(EvalError, new ErrorObjectSerializer(EvalError)); -jsTypes.set(RangeError, new ErrorObjectSerializer(RangeError)); -jsTypes.set(ReferenceError, new ErrorObjectSerializer(ReferenceError)); -jsTypes.set(SyntaxError, new ErrorObjectSerializer(SyntaxError)); -jsTypes.set(TypeError, new ErrorObjectSerializer(TypeError)); - -// If in a sandboxed environment (e. g. jest), this escapes the sandbox and registers -// real Object and Array types to. These types may occur in the wild too, e. g. when -// using Structured Clone in postMessage. -if (exports.constructor !== Object) { - const Obj = /** @type {typeof Object} */ (exports.constructor); - const Fn = /** @type {typeof Function} */ (Obj.constructor); - for (const [type, config] of Array.from(jsTypes)) { - if (type) { - const Type = new Fn(`return ${type.name};`)(); - jsTypes.set(Type, config); + static getChunkFilenameTemplate(chunk, outputOptions) { + if (chunk.filenameTemplate) { + return chunk.filenameTemplate; + } else if (chunk instanceof HotUpdateChunk) { + return outputOptions.hotUpdateChunkFilename; + } else if (chunk.canBeInitial()) { + return outputOptions.filename; + } else { + return outputOptions.chunkFilename; } } -} - -{ - let i = 1; - for (const [type, serializer] of jsTypes) { - serializers.set(type, { - request: "", - name: i++, - serializer - }); - } -} - -for (const { request, name, serializer } of serializers.values()) { - serializerInversed.set(`${request}/${name}`, serializer); -} - -/** @type {Map boolean>} */ -const loaders = new Map(); -/** - * @typedef {ComplexSerializableType[]} DeserializedType - * @typedef {PrimitiveSerializableType[]} SerializedType - * @extends {SerializerMiddleware} - */ -class ObjectMiddleware extends SerializerMiddleware { - /** - * @param {function(any): void} extendContext context extensions - * @param {string | Hash} hashFunction hash function to use - */ - constructor(extendContext, hashFunction = "md4") { - super(); - this.extendContext = extendContext; - this._hashFunction = hashFunction; - } /** - * @param {RegExp} regExp RegExp for which the request is tested - * @param {function(string): boolean} loader loader to load the request, returns true when successful - * @returns {void} + * @param {Module} module the rendered module + * @param {ChunkRenderContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @param {boolean} factory true: renders as factory method, false: pure module content + * @returns {Source} the newly generated source from rendering */ - static registerLoader(regExp, loader) { - loaders.set(regExp, loader); + renderModule(module, renderContext, hooks, factory) { + const { + chunk, + chunkGraph, + runtimeTemplate, + codeGenerationResults, + strictMode + } = renderContext; + try { + const codeGenResult = codeGenerationResults.get(module, chunk.runtime); + const moduleSource = codeGenResult.sources.get("javascript"); + if (!moduleSource) return null; + if (codeGenResult.data !== undefined) { + const chunkInitFragments = codeGenResult.data.get("chunkInitFragments"); + if (chunkInitFragments) { + for (const i of chunkInitFragments) + renderContext.chunkInitFragments.push(i); + } + } + const moduleSourcePostContent = tryRunOrWebpackError( + () => + hooks.renderModuleContent.call(moduleSource, module, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderModuleContent" + ); + let moduleSourcePostContainer; + if (factory) { + const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( + module, + chunk.runtime + ); + const needModule = runtimeRequirements.has(RuntimeGlobals.module); + const needExports = runtimeRequirements.has(RuntimeGlobals.exports); + const needRequire = + runtimeRequirements.has(RuntimeGlobals.require) || + runtimeRequirements.has(RuntimeGlobals.requireScope); + const needThisAsExports = runtimeRequirements.has( + RuntimeGlobals.thisAsExports + ); + const needStrict = module.buildInfo.strict && !strictMode; + const cacheEntry = this._moduleFactoryCache.get( + moduleSourcePostContent + ); + let source; + if ( + cacheEntry && + cacheEntry.needModule === needModule && + cacheEntry.needExports === needExports && + cacheEntry.needRequire === needRequire && + cacheEntry.needThisAsExports === needThisAsExports && + cacheEntry.needStrict === needStrict + ) { + source = cacheEntry.source; + } else { + const factorySource = new ConcatSource(); + const args = []; + if (needExports || needRequire || needModule) + args.push( + needModule + ? module.moduleArgument + : "__unused_webpack_" + module.moduleArgument + ); + if (needExports || needRequire) + args.push( + needExports + ? module.exportsArgument + : "__unused_webpack_" + module.exportsArgument + ); + if (needRequire) args.push("__webpack_require__"); + if (!needThisAsExports && runtimeTemplate.supportsArrowFunction()) { + factorySource.add("/***/ ((" + args.join(", ") + ") => {\n\n"); + } else { + factorySource.add("/***/ (function(" + args.join(", ") + ") {\n\n"); + } + if (needStrict) { + factorySource.add('"use strict";\n'); + } + factorySource.add(moduleSourcePostContent); + factorySource.add("\n\n/***/ })"); + source = new CachedSource(factorySource); + this._moduleFactoryCache.set(moduleSourcePostContent, { + source, + needModule, + needExports, + needRequire, + needThisAsExports, + needStrict + }); + } + moduleSourcePostContainer = tryRunOrWebpackError( + () => hooks.renderModuleContainer.call(source, module, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderModuleContainer" + ); + } else { + moduleSourcePostContainer = moduleSourcePostContent; + } + return tryRunOrWebpackError( + () => + hooks.renderModulePackage.call( + moduleSourcePostContainer, + module, + renderContext + ), + "JavascriptModulesPlugin.getCompilationHooks().renderModulePackage" + ); + } catch (e) { + e.module = module; + throw e; + } } /** - * @param {Constructor} Constructor the constructor - * @param {string} request the request which will be required when deserializing - * @param {string} name the name to make multiple serializer unique when sharing a request - * @param {ObjectSerializer} serializer the serializer - * @returns {void} + * @param {RenderContext} renderContext the render context + * @param {CompilationHooks} hooks hooks + * @returns {Source} the rendered source */ - static register(Constructor, request, name, serializer) { - const key = request + "/" + name; - - if (serializers.has(Constructor)) { + renderChunk(renderContext, hooks) { + const { chunk, chunkGraph } = renderContext; + const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "javascript", + compareModulesByIdentifier + ); + const allModules = modules ? Array.from(modules) : []; + let strictHeader; + let allStrict = renderContext.strictMode; + if (!allStrict && allModules.every(m => m.buildInfo.strict)) { + const strictBailout = hooks.strictRuntimeBailout.call(renderContext); + strictHeader = strictBailout + ? `// runtime can't be in strict mode because ${strictBailout}.\n` + : '"use strict";\n'; + if (!strictBailout) allStrict = true; + } + /** @type {ChunkRenderContext} */ + const chunkRenderContext = { + ...renderContext, + chunkInitFragments: [], + strictMode: allStrict + }; + const moduleSources = + Template.renderChunkModules(chunkRenderContext, allModules, module => + this.renderModule(module, chunkRenderContext, hooks, true) + ) || new RawSource("{}"); + let source = tryRunOrWebpackError( + () => hooks.renderChunk.call(moduleSources, chunkRenderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderChunk" + ); + source = tryRunOrWebpackError( + () => hooks.renderContent.call(source, chunkRenderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderContent" + ); + if (!source) { throw new Error( - `ObjectMiddleware.register: serializer for ${Constructor.name} is already registered` + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something" ); } - - if (serializerInversed.has(key)) { + source = InitFragment.addToSource( + source, + chunkRenderContext.chunkInitFragments, + chunkRenderContext + ); + source = tryRunOrWebpackError( + () => hooks.render.call(source, chunkRenderContext), + "JavascriptModulesPlugin.getCompilationHooks().render" + ); + if (!source) { throw new Error( - `ObjectMiddleware.register: serializer for ${key} is already registered` + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something" ); } - - serializers.set(Constructor, { - request, - name, - serializer - }); - - serializerInversed.set(key, serializer); + chunk.rendered = true; + return strictHeader + ? new ConcatSource(strictHeader, source, ";") + : renderContext.runtimeTemplate.isModule() + ? source + : new ConcatSource(source, ";"); } /** - * @param {Constructor} Constructor the constructor - * @returns {void} + * @param {MainRenderContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @param {Compilation} compilation the compilation + * @returns {Source} the newly generated source from rendering */ - static registerNotSerializable(Constructor) { - if (serializers.has(Constructor)) { - throw new Error( - `ObjectMiddleware.registerNotSerializable: serializer for ${Constructor.name} is already registered` - ); - } + renderMain(renderContext, hooks, compilation) { + const { chunk, chunkGraph, runtimeTemplate } = renderContext; - serializers.set(Constructor, NOT_SERIALIZABLE); - } + const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); + const iife = runtimeTemplate.isIIFE(); - static getSerializerFor(object) { - const proto = Object.getPrototypeOf(object); - let c; - if (proto === null) { - // Object created with Object.create(null) - c = null; + const bootstrap = this.renderBootstrap(renderContext, hooks); + const useSourceMap = hooks.useSourceMap.call(chunk, renderContext); + + const allModules = Array.from( + chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "javascript", + compareModulesByIdentifier + ) || [] + ); + + const hasEntryModules = chunkGraph.getNumberOfEntryModules(chunk) > 0; + let inlinedModules; + if (bootstrap.allowInlineStartup && hasEntryModules) { + inlinedModules = new Set(chunkGraph.getChunkEntryModulesIterable(chunk)); + } + + let source = new ConcatSource(); + let prefix; + if (iife) { + if (runtimeTemplate.supportsArrowFunction()) { + source.add("/******/ (() => { // webpackBootstrap\n"); + } else { + source.add("/******/ (function() { // webpackBootstrap\n"); + } + prefix = "/******/ \t"; } else { - c = proto.constructor; - if (!c) { - throw new Error( - "Serialization of objects with prototype without valid constructor property not possible" + prefix = "/******/ "; + } + let allStrict = renderContext.strictMode; + if (!allStrict && allModules.every(m => m.buildInfo.strict)) { + const strictBailout = hooks.strictRuntimeBailout.call(renderContext); + if (strictBailout) { + source.add( + prefix + + `// runtime can't be in strict mode because ${strictBailout}.\n` ); + } else { + allStrict = true; + source.add(prefix + '"use strict";\n'); } } - const config = serializers.get(c); - - if (!config) throw new Error(`No serializer registered for ${c.name}`); - if (config === NOT_SERIALIZABLE) throw NOT_SERIALIZABLE; - - return config; - } - static getDeserializerFor(request, name) { - const key = request + "/" + name; - const serializer = serializerInversed.get(key); + /** @type {ChunkRenderContext} */ + const chunkRenderContext = { + ...renderContext, + chunkInitFragments: [], + strictMode: allStrict + }; - if (serializer === undefined) { - throw new Error(`No deserializer registered for ${key}`); + const chunkModules = Template.renderChunkModules( + chunkRenderContext, + inlinedModules + ? allModules.filter(m => !inlinedModules.has(m)) + : allModules, + module => this.renderModule(module, chunkRenderContext, hooks, true), + prefix + ); + if ( + chunkModules || + runtimeRequirements.has(RuntimeGlobals.moduleFactories) || + runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) || + runtimeRequirements.has(RuntimeGlobals.require) + ) { + source.add(prefix + "var __webpack_modules__ = ("); + source.add(chunkModules || "{}"); + source.add(");\n"); + source.add( + "/************************************************************************/\n" + ); } - return serializer; - } + if (bootstrap.header.length > 0) { + const header = Template.asString(bootstrap.header) + "\n"; + source.add( + new PrefixSource( + prefix, + useSourceMap + ? new OriginalSource(header, "webpack/bootstrap") + : new RawSource(header) + ) + ); + source.add( + "/************************************************************************/\n" + ); + } - static _getDeserializerForWithoutError(request, name) { - const key = request + "/" + name; - const serializer = serializerInversed.get(key); - return serializer; - } + const runtimeModules = + renderContext.chunkGraph.getChunkRuntimeModulesInOrder(chunk); - /** - * @param {DeserializedType} data data - * @param {Object} context context object - * @returns {SerializedType|Promise} serialized data - */ - serialize(data, context) { - /** @type {any[]} */ - let result = [CURRENT_VERSION]; - let currentPos = 0; - let referenceable = new Map(); - const addReferenceable = item => { - referenceable.set(item, currentPos++); - }; - let bufferDedupeMap = new Map(); - const dedupeBuffer = buf => { - const len = buf.length; - const entry = bufferDedupeMap.get(len); - if (entry === undefined) { - bufferDedupeMap.set(len, buf); - return buf; - } - if (Buffer.isBuffer(entry)) { - if (len < 32) { - if (buf.equals(entry)) { - return entry; - } - bufferDedupeMap.set(len, [entry, buf]); - return buf; - } else { - const hash = toHash(entry, this._hashFunction); - const newMap = new Map(); - newMap.set(hash, entry); - bufferDedupeMap.set(len, newMap); - const hashBuf = toHash(buf, this._hashFunction); - if (hash === hashBuf) { - return entry; - } - return buf; - } - } else if (Array.isArray(entry)) { - if (entry.length < 16) { - for (const item of entry) { - if (buf.equals(item)) { - return item; + if (runtimeModules.length > 0) { + source.add( + new PrefixSource( + prefix, + Template.renderRuntimeModules(runtimeModules, chunkRenderContext) + ) + ); + source.add( + "/************************************************************************/\n" + ); + // runtimeRuntimeModules calls codeGeneration + for (const module of runtimeModules) { + compilation.codeGeneratedModules.add(module); + } + } + if (inlinedModules) { + if (bootstrap.beforeStartup.length > 0) { + const beforeStartup = Template.asString(bootstrap.beforeStartup) + "\n"; + source.add( + new PrefixSource( + prefix, + useSourceMap + ? new OriginalSource(beforeStartup, "webpack/before-startup") + : new RawSource(beforeStartup) + ) + ); + } + const lastInlinedModule = last(inlinedModules); + const startupSource = new ConcatSource(); + startupSource.add(`var __webpack_exports__ = {};\n`); + for (const m of inlinedModules) { + const renderedModule = this.renderModule( + m, + chunkRenderContext, + hooks, + false + ); + if (renderedModule) { + const innerStrict = !allStrict && m.buildInfo.strict; + const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( + m, + chunk.runtime + ); + const exports = runtimeRequirements.has(RuntimeGlobals.exports); + const webpackExports = + exports && m.exportsArgument === "__webpack_exports__"; + let iife = innerStrict + ? "it need to be in strict mode." + : inlinedModules.size > 1 + ? // TODO check globals and top-level declarations of other entries and chunk modules + // to make a better decision + "it need to be isolated against other entry modules." + : chunkModules + ? "it need to be isolated against other modules in the chunk." + : exports && !webpackExports + ? `it uses a non-standard name for the exports (${m.exportsArgument}).` + : hooks.embedInRuntimeBailout.call(m, renderContext); + let footer; + if (iife !== undefined) { + startupSource.add( + `// This entry need to be wrapped in an IIFE because ${iife}\n` + ); + const arrow = runtimeTemplate.supportsArrowFunction(); + if (arrow) { + startupSource.add("(() => {\n"); + footer = "\n})();\n\n"; + } else { + startupSource.add("!function() {\n"); + footer = "\n}();\n"; } - } - entry.push(buf); - return buf; - } else { - const newMap = new Map(); - const hash = toHash(buf, this._hashFunction); - let found; - for (const item of entry) { - const itemHash = toHash(item, this._hashFunction); - newMap.set(itemHash, item); - if (found === undefined && itemHash === hash) found = item; - } - bufferDedupeMap.set(len, newMap); - if (found === undefined) { - newMap.set(hash, buf); - return buf; + if (innerStrict) startupSource.add('"use strict";\n'); } else { - return found; + footer = "\n"; } + if (exports) { + if (m !== lastInlinedModule) + startupSource.add(`var ${m.exportsArgument} = {};\n`); + else if (m.exportsArgument !== "__webpack_exports__") + startupSource.add( + `var ${m.exportsArgument} = __webpack_exports__;\n` + ); + } + startupSource.add(renderedModule); + startupSource.add(footer); } - } else { - const hash = toHash(buf, this._hashFunction); - const item = entry.get(hash); - if (item !== undefined) { - return item; - } - entry.set(hash, buf); - return buf; } - }; - let currentPosTypeLookup = 0; - let objectTypeLookup = new Map(); - const cycleStack = new Set(); - const stackToString = item => { - const arr = Array.from(cycleStack); - arr.push(item); - return arr - .map(item => { - if (typeof item === "string") { - if (item.length > 100) { - return `String ${JSON.stringify(item.slice(0, 100)).slice( - 0, - -1 - )}..."`; - } - return `String ${JSON.stringify(item)}`; - } - try { - const { request, name } = ObjectMiddleware.getSerializerFor(item); - if (request) { - return `${request}${name ? `.${name}` : ""}`; - } - } catch (e) { - // ignore -> fallback - } - if (typeof item === "object" && item !== null) { - if (item.constructor) { - if (item.constructor === Object) - return `Object { ${Object.keys(item).join(", ")} }`; - if (item.constructor === Map) return `Map { ${item.size} items }`; - if (item.constructor === Array) - return `Array { ${item.length} items }`; - if (item.constructor === Set) return `Set { ${item.size} items }`; - if (item.constructor === RegExp) return item.toString(); - return `${item.constructor.name}`; - } - return `Object [null prototype] { ${Object.keys(item).join( - ", " - )} }`; - } - try { - return `${item}`; - } catch (e) { - return `(${e.message})`; - } + if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) { + startupSource.add( + `__webpack_exports__ = ${RuntimeGlobals.onChunksLoaded}(__webpack_exports__);\n` + ); + } + source.add( + hooks.renderStartup.call(startupSource, lastInlinedModule, { + ...renderContext, + inlined: true }) - .join(" -> "); - }; - let hasDebugInfoAttached; - let ctx = { - write(value, key) { - try { - process(value); - } catch (e) { - if (e !== NOT_SERIALIZABLE) { - if (hasDebugInfoAttached === undefined) - hasDebugInfoAttached = new WeakSet(); - if (!hasDebugInfoAttached.has(e)) { - e.message += `\nwhile serializing ${stackToString(value)}`; - hasDebugInfoAttached.add(e); - } - } - throw e; - } - }, - setCircularReference(ref) { - addReferenceable(ref); - }, - snapshot() { - return { - length: result.length, - cycleStackSize: cycleStack.size, - referenceableSize: referenceable.size, - currentPos, - objectTypeLookupSize: objectTypeLookup.size, - currentPosTypeLookup - }; - }, - rollback(snapshot) { - result.length = snapshot.length; - setSetSize(cycleStack, snapshot.cycleStackSize); - setMapSize(referenceable, snapshot.referenceableSize); - currentPos = snapshot.currentPos; - setMapSize(objectTypeLookup, snapshot.objectTypeLookupSize); - currentPosTypeLookup = snapshot.currentPosTypeLookup; - }, - ...context - }; - this.extendContext(ctx); - const process = item => { - if (Buffer.isBuffer(item)) { - // check if we can emit a reference - const ref = referenceable.get(item); - if (ref !== undefined) { - result.push(ESCAPE, ref - currentPos); - return; - } - const alreadyUsedBuffer = dedupeBuffer(item); - if (alreadyUsedBuffer !== item) { - const ref = referenceable.get(alreadyUsedBuffer); - if (ref !== undefined) { - referenceable.set(item, ref); - result.push(ESCAPE, ref - currentPos); - return; - } - item = alreadyUsedBuffer; - } - addReferenceable(item); - - result.push(item); - } else if (item === ESCAPE) { - result.push(ESCAPE, ESCAPE_ESCAPE_VALUE); - } else if ( - typeof item === "object" - // We don't have to check for null as ESCAPE is null and this has been checked before - ) { - // check if we can emit a reference - const ref = referenceable.get(item); - if (ref !== undefined) { - result.push(ESCAPE, ref - currentPos); - return; - } - - if (cycleStack.has(item)) { - throw new Error( - `This is a circular references. To serialize circular references use 'setCircularReference' somewhere in the circle during serialize and deserialize.` - ); - } - - const { request, name, serializer } = - ObjectMiddleware.getSerializerFor(item); - const key = `${request}/${name}`; - const lastIndex = objectTypeLookup.get(key); - - if (lastIndex === undefined) { - objectTypeLookup.set(key, currentPosTypeLookup++); - - result.push(ESCAPE, request, name); - } else { - result.push(ESCAPE, currentPosTypeLookup - lastIndex); - } - - cycleStack.add(item); - - try { - serializer.serialize(item, ctx); - } finally { - cycleStack.delete(item); - } - - result.push(ESCAPE, ESCAPE_END_OBJECT); - - addReferenceable(item); - } else if (typeof item === "string") { - if (item.length > 1) { - // short strings are shorter when not emitting a reference (this saves 1 byte per empty string) - // check if we can emit a reference - const ref = referenceable.get(item); - if (ref !== undefined) { - result.push(ESCAPE, ref - currentPos); - return; - } - addReferenceable(item); - } + ); + if (bootstrap.afterStartup.length > 0) { + const afterStartup = Template.asString(bootstrap.afterStartup) + "\n"; + source.add( + new PrefixSource( + prefix, + useSourceMap + ? new OriginalSource(afterStartup, "webpack/after-startup") + : new RawSource(afterStartup) + ) + ); + } + } else { + const lastEntryModule = last( + chunkGraph.getChunkEntryModulesIterable(chunk) + ); + const toSource = useSourceMap + ? (content, name) => + new OriginalSource(Template.asString(content), name) + : content => new RawSource(Template.asString(content)); + source.add( + new PrefixSource( + prefix, + new ConcatSource( + toSource(bootstrap.beforeStartup, "webpack/before-startup"), + "\n", + hooks.renderStartup.call( + toSource(bootstrap.startup.concat(""), "webpack/startup"), + lastEntryModule, + { + ...renderContext, + inlined: false + } + ), + toSource(bootstrap.afterStartup, "webpack/after-startup"), + "\n" + ) + ) + ); + } + if ( + hasEntryModules && + runtimeRequirements.has(RuntimeGlobals.returnExportsFromRuntime) + ) { + source.add(`${prefix}return __webpack_exports__;\n`); + } + if (iife) { + source.add("/******/ })()\n"); + } - if (item.length > 102400 && context.logger) { - context.logger.warn( - `Serializing big strings (${Math.round( - item.length / 1024 - )}kiB) impacts deserialization performance (consider using Buffer instead and decode when needed)` - ); - } + /** @type {Source} */ + let finalSource = tryRunOrWebpackError( + () => hooks.renderMain.call(source, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderMain" + ); + if (!finalSource) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderMain plugins should return something" + ); + } + finalSource = tryRunOrWebpackError( + () => hooks.renderContent.call(finalSource, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderContent" + ); + if (!finalSource) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something" + ); + } + finalSource = InitFragment.addToSource( + finalSource, + chunkRenderContext.chunkInitFragments, + chunkRenderContext + ); + finalSource = tryRunOrWebpackError( + () => hooks.render.call(finalSource, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().render" + ); + if (!finalSource) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something" + ); + } + chunk.rendered = true; + return iife ? new ConcatSource(finalSource, ";") : finalSource; + } - result.push(item); - } else if (typeof item === "function") { - if (!SerializerMiddleware.isLazy(item)) - throw new Error("Unexpected function " + item); - /** @type {SerializedType} */ - const serializedData = - SerializerMiddleware.getLazySerializedValue(item); - if (serializedData !== undefined) { - if (typeof serializedData === "function") { - result.push(serializedData); - } else { - throw new Error("Not implemented"); - } - } else if (SerializerMiddleware.isLazy(item, this)) { - throw new Error("Not implemented"); - } else { - const data = SerializerMiddleware.serializeLazy(item, data => - this.serialize([data], context) - ); - SerializerMiddleware.setLazySerializedValue(item, data); - result.push(data); + /** + * @param {Hash} hash the hash to be updated + * @param {RenderBootstrapContext} renderContext options object + * @param {CompilationHooks} hooks hooks + */ + updateHashWithBootstrap(hash, renderContext, hooks) { + const bootstrap = this.renderBootstrap(renderContext, hooks); + for (const key of Object.keys(bootstrap)) { + hash.update(key); + if (Array.isArray(bootstrap[key])) { + for (const line of bootstrap[key]) { + hash.update(line); } - } else if (item === undefined) { - result.push(ESCAPE, ESCAPE_UNDEFINED); } else { - result.push(item); - } - }; - - try { - for (const item of data) { - process(item); + hash.update(JSON.stringify(bootstrap[key])); } - return result; - } catch (e) { - if (e === NOT_SERIALIZABLE) return null; - - throw e; - } finally { - // Get rid of these references to avoid leaking memory - // This happens because the optimized code v8 generates - // is optimized for our "ctx.write" method so it will reference - // it from e. g. Dependency.prototype.serialize -(IC)-> ctx.write - data = - result = - referenceable = - bufferDedupeMap = - objectTypeLookup = - ctx = - undefined; } } /** - * @param {SerializedType} data data - * @param {Object} context context object - * @returns {DeserializedType|Promise} deserialized data + * @param {RenderBootstrapContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @returns {{ header: string[], beforeStartup: string[], startup: string[], afterStartup: string[], allowInlineStartup: boolean }} the generated source of the bootstrap code */ - deserialize(data, context) { - let currentDataPos = 0; - const read = () => { - if (currentDataPos >= data.length) - throw new Error("Unexpected end of stream"); + renderBootstrap(renderContext, hooks) { + const { chunkGraph, moduleGraph, chunk, runtimeTemplate } = renderContext; - return data[currentDataPos++]; - }; + const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); - if (read() !== CURRENT_VERSION) - throw new Error("Version mismatch, serializer changed"); + const requireFunction = runtimeRequirements.has(RuntimeGlobals.require); + const moduleCache = runtimeRequirements.has(RuntimeGlobals.moduleCache); + const moduleFactories = runtimeRequirements.has( + RuntimeGlobals.moduleFactories + ); + const moduleUsed = runtimeRequirements.has(RuntimeGlobals.module); + const requireScopeUsed = runtimeRequirements.has( + RuntimeGlobals.requireScope + ); + const interceptModuleExecution = runtimeRequirements.has( + RuntimeGlobals.interceptModuleExecution + ); - let currentPos = 0; - let referenceable = []; - const addReferenceable = item => { - referenceable.push(item); - currentPos++; - }; - let currentPosTypeLookup = 0; - let objectTypeLookup = []; - let result = []; - let ctx = { - read() { - return decodeValue(); - }, - setCircularReference(ref) { - addReferenceable(ref); - }, - ...context + const useRequire = + requireFunction || interceptModuleExecution || moduleUsed; + + const result = { + header: [], + beforeStartup: [], + startup: [], + afterStartup: [], + allowInlineStartup: true }; - this.extendContext(ctx); - const decodeValue = () => { - const item = read(); - if (item === ESCAPE) { - const nextItem = read(); + let { header: buf, startup, beforeStartup, afterStartup } = result; - if (nextItem === ESCAPE_ESCAPE_VALUE) { - return ESCAPE; - } else if (nextItem === ESCAPE_UNDEFINED) { - return undefined; - } else if (nextItem === ESCAPE_END_OBJECT) { - throw new Error( - `Unexpected end of object at position ${currentDataPos - 1}` - ); - } else { - const request = nextItem; - let serializer; + if (result.allowInlineStartup && moduleFactories) { + startup.push( + "// module factories are used so entry inlining is disabled" + ); + result.allowInlineStartup = false; + } + if (result.allowInlineStartup && moduleCache) { + startup.push("// module cache are used so entry inlining is disabled"); + result.allowInlineStartup = false; + } + if (result.allowInlineStartup && interceptModuleExecution) { + startup.push( + "// module execution is intercepted so entry inlining is disabled" + ); + result.allowInlineStartup = false; + } - if (typeof request === "number") { - if (request < 0) { - // relative reference - return referenceable[currentPos + request]; - } - serializer = objectTypeLookup[currentPosTypeLookup - request]; - } else { - if (typeof request !== "string") { - throw new Error( - `Unexpected type (${typeof request}) of request ` + - `at position ${currentDataPos - 1}` - ); - } - const name = read(); + if (useRequire || moduleCache) { + buf.push("// The module cache"); + buf.push("var __webpack_module_cache__ = {};"); + buf.push(""); + } - serializer = ObjectMiddleware._getDeserializerForWithoutError( - request, - name - ); + if (useRequire) { + buf.push("// The require function"); + buf.push(`function __webpack_require__(moduleId) {`); + buf.push(Template.indent(this.renderRequire(renderContext, hooks))); + buf.push("}"); + buf.push(""); + } else if (runtimeRequirements.has(RuntimeGlobals.requireScope)) { + buf.push("// The require scope"); + buf.push("var __webpack_require__ = {};"); + buf.push(""); + } - if (serializer === undefined) { - if (request && !loadedRequests.has(request)) { - let loaded = false; - for (const [regExp, loader] of loaders) { - if (regExp.test(request)) { - if (loader(request)) { - loaded = true; - break; - } - } - } - if (!loaded) { - require(request); - } + if ( + moduleFactories || + runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) + ) { + buf.push("// expose the modules object (__webpack_modules__)"); + buf.push(`${RuntimeGlobals.moduleFactories} = __webpack_modules__;`); + buf.push(""); + } - loadedRequests.add(request); - } + if (moduleCache) { + buf.push("// expose the module cache"); + buf.push(`${RuntimeGlobals.moduleCache} = __webpack_module_cache__;`); + buf.push(""); + } - serializer = ObjectMiddleware.getDeserializerFor(request, name); - } + if (interceptModuleExecution) { + buf.push("// expose the module execution interceptor"); + buf.push(`${RuntimeGlobals.interceptModuleExecution} = [];`); + buf.push(""); + } - objectTypeLookup.push(serializer); - currentPosTypeLookup++; + if (!runtimeRequirements.has(RuntimeGlobals.startupNoDefault)) { + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { + /** @type {string[]} */ + const buf2 = []; + const runtimeRequirements = + chunkGraph.getTreeRuntimeRequirements(chunk); + buf2.push("// Load entry module and return exports"); + let i = chunkGraph.getNumberOfEntryModules(chunk); + for (const [ + entryModule, + entrypoint + ] of chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)) { + const chunks = entrypoint.chunks.filter(c => c !== chunk); + if (result.allowInlineStartup && chunks.length > 0) { + buf2.push( + "// This entry module depends on other loaded chunks and execution need to be delayed" + ); + result.allowInlineStartup = false; } - try { - const item = serializer.deserialize(ctx); - const end1 = read(); - - if (end1 !== ESCAPE) { - throw new Error("Expected end of object"); - } - - const end2 = read(); - - if (end2 !== ESCAPE_END_OBJECT) { - throw new Error("Expected end of object"); + if ( + result.allowInlineStartup && + someInIterable( + moduleGraph.getIncomingConnectionsByOriginModule(entryModule), + ([originModule, connections]) => + originModule && + connections.some(c => c.isTargetActive(chunk.runtime)) && + someInIterable( + chunkGraph.getModuleRuntimes(originModule), + runtime => + intersectRuntime(runtime, chunk.runtime) !== undefined + ) + ) + ) { + buf2.push( + "// This entry module is referenced by other modules so it can't be inlined" + ); + result.allowInlineStartup = false; + } + if ( + result.allowInlineStartup && + (!entryModule.buildInfo || + !entryModule.buildInfo.topLevelDeclarations) + ) { + buf2.push( + "// This entry module doesn't tell about it's top-level declarations so it can't be inlined" + ); + result.allowInlineStartup = false; + } + if (result.allowInlineStartup) { + const bailout = hooks.inlineInRuntimeBailout.call( + entryModule, + renderContext + ); + if (bailout !== undefined) { + buf2.push( + `// This entry module can't be inlined because ${bailout}` + ); + result.allowInlineStartup = false; } - - addReferenceable(item); - - return item; - } catch (err) { - // As this is only for error handling, we omit creating a Map for - // faster access to this information, as this would affect performance - // in the good case - let serializerEntry; - for (const entry of serializers) { - if (entry[1].serializer === serializer) { - serializerEntry = entry; - break; - } + } + i--; + const moduleId = chunkGraph.getModuleId(entryModule); + const entryRuntimeRequirements = + chunkGraph.getModuleRuntimeRequirements(entryModule, chunk.runtime); + let moduleIdExpr = JSON.stringify(moduleId); + if (runtimeRequirements.has(RuntimeGlobals.entryModuleId)) { + moduleIdExpr = `${RuntimeGlobals.entryModuleId} = ${moduleIdExpr}`; + } + if ( + result.allowInlineStartup && + entryRuntimeRequirements.has(RuntimeGlobals.module) + ) { + result.allowInlineStartup = false; + buf2.push( + "// This entry module used 'module' so it can't be inlined" + ); + } + if (chunks.length > 0) { + buf2.push( + `${i === 0 ? "var __webpack_exports__ = " : ""}${ + RuntimeGlobals.onChunksLoaded + }(undefined, ${JSON.stringify( + chunks.map(c => c.id) + )}, ${runtimeTemplate.returningFunction( + `__webpack_require__(${moduleIdExpr})` + )})` + ); + } else if (useRequire) { + buf2.push( + `${ + i === 0 ? "var __webpack_exports__ = " : "" + }__webpack_require__(${moduleIdExpr});` + ); + } else { + if (i === 0) buf2.push("var __webpack_exports__ = {};"); + if (requireScopeUsed) { + buf2.push( + `__webpack_modules__[${moduleIdExpr}](0, ${ + i === 0 ? "__webpack_exports__" : "{}" + }, __webpack_require__);` + ); + } else if (entryRuntimeRequirements.has(RuntimeGlobals.exports)) { + buf2.push( + `__webpack_modules__[${moduleIdExpr}](0, ${ + i === 0 ? "__webpack_exports__" : "{}" + });` + ); + } else { + buf2.push(`__webpack_modules__[${moduleIdExpr}]();`); } - const name = !serializerEntry - ? "unknown" - : !serializerEntry[1].request - ? serializerEntry[0].name - : serializerEntry[1].name - ? `${serializerEntry[1].request} ${serializerEntry[1].name}` - : serializerEntry[1].request; - err.message += `\n(during deserialization of ${name})`; - throw err; } } - } else if (typeof item === "string") { - if (item.length > 1) { - addReferenceable(item); + if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) { + buf2.push( + `__webpack_exports__ = ${RuntimeGlobals.onChunksLoaded}(__webpack_exports__);` + ); } - - return item; - } else if (Buffer.isBuffer(item)) { - addReferenceable(item); - - return item; - } else if (typeof item === "function") { - return SerializerMiddleware.deserializeLazy( - item, - data => this.deserialize(data, context)[0] + if ( + runtimeRequirements.has(RuntimeGlobals.startup) || + (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) && + runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)) + ) { + result.allowInlineStartup = false; + buf.push("// the startup function"); + buf.push( + `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction("", [ + ...buf2, + "return __webpack_exports__;" + ])};` + ); + buf.push(""); + startup.push("// run startup"); + startup.push( + `var __webpack_exports__ = ${RuntimeGlobals.startup}();` + ); + } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore)) { + buf.push("// the startup function"); + buf.push( + `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` + ); + beforeStartup.push("// run runtime startup"); + beforeStartup.push(`${RuntimeGlobals.startup}();`); + startup.push("// startup"); + startup.push(Template.asString(buf2)); + } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)) { + buf.push("// the startup function"); + buf.push( + `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` + ); + startup.push("// startup"); + startup.push(Template.asString(buf2)); + afterStartup.push("// run runtime startup"); + afterStartup.push(`${RuntimeGlobals.startup}();`); + } else { + startup.push("// startup"); + startup.push(Template.asString(buf2)); + } + } else if ( + runtimeRequirements.has(RuntimeGlobals.startup) || + runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) || + runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter) + ) { + buf.push( + "// the startup function", + "// It's empty as no entry modules are in this chunk", + `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};`, + "" ); - } else { - return item; - } - }; - - try { - while (currentDataPos < data.length) { - result.push(decodeValue()); } - return result; - } finally { - // Get rid of these references to avoid leaking memory - // This happens because the optimized code v8 generates - // is optimized for our "ctx.read" method so it will reference - // it from e. g. Dependency.prototype.deserialize -(IC)-> ctx.read - result = referenceable = data = objectTypeLookup = ctx = undefined; + } else if ( + runtimeRequirements.has(RuntimeGlobals.startup) || + runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) || + runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter) + ) { + result.allowInlineStartup = false; + buf.push( + "// the startup function", + "// It's empty as some runtime module handles the default behavior", + `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` + ); + startup.push("// run startup"); + startup.push(`var __webpack_exports__ = ${RuntimeGlobals.startup}();`); } + return result; + } + + /** + * @param {RenderBootstrapContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @returns {string} the generated source of the require function + */ + renderRequire(renderContext, hooks) { + const { + chunk, + chunkGraph, + runtimeTemplate: { outputOptions } + } = renderContext; + const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); + const moduleExecution = runtimeRequirements.has( + RuntimeGlobals.interceptModuleExecution + ) + ? Template.asString([ + "var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: __webpack_require__ };", + `${RuntimeGlobals.interceptModuleExecution}.forEach(function(handler) { handler(execOptions); });`, + "module = execOptions.module;", + "execOptions.factory.call(module.exports, module, module.exports, execOptions.require);" + ]) + : runtimeRequirements.has(RuntimeGlobals.thisAsExports) + ? Template.asString([ + "__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);" + ]) + : Template.asString([ + "__webpack_modules__[moduleId](module, module.exports, __webpack_require__);" + ]); + const needModuleId = runtimeRequirements.has(RuntimeGlobals.moduleId); + const needModuleLoaded = runtimeRequirements.has( + RuntimeGlobals.moduleLoaded + ); + const content = Template.asString([ + "// Check if module is in cache", + "var cachedModule = __webpack_module_cache__[moduleId];", + "if (cachedModule !== undefined) {", + outputOptions.strictModuleErrorHandling + ? Template.indent([ + "if (cachedModule.error !== undefined) throw cachedModule.error;", + "return cachedModule.exports;" + ]) + : Template.indent("return cachedModule.exports;"), + "}", + "// Create a new module (and put it into the cache)", + "var module = __webpack_module_cache__[moduleId] = {", + Template.indent([ + needModuleId ? "id: moduleId," : "// no module.id needed", + needModuleLoaded ? "loaded: false," : "// no module.loaded needed", + "exports: {}" + ]), + "};", + "", + outputOptions.strictModuleExceptionHandling + ? Template.asString([ + "// Execute the module function", + "var threw = true;", + "try {", + Template.indent([moduleExecution, "threw = false;"]), + "} finally {", + Template.indent([ + "if(threw) delete __webpack_module_cache__[moduleId];" + ]), + "}" + ]) + : outputOptions.strictModuleErrorHandling + ? Template.asString([ + "// Execute the module function", + "try {", + Template.indent(moduleExecution), + "} catch(e) {", + Template.indent(["module.error = e;", "throw e;"]), + "}" + ]) + : Template.asString([ + "// Execute the module function", + moduleExecution + ]), + needModuleLoaded + ? Template.asString([ + "", + "// Flag the module as loaded", + "module.loaded = true;", + "" + ]) + : "", + "// Return the exports of the module", + "return module.exports;" + ]); + return tryRunOrWebpackError( + () => hooks.renderRequire.call(content, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderRequire" + ); } } -module.exports = ObjectMiddleware; -module.exports.NOT_SERIALIZABLE = NOT_SERIALIZABLE; +module.exports = JavascriptModulesPlugin; +module.exports.chunkHasJs = chunkHasJs; /***/ }), -/***/ 33040: -/***/ (function(module) { +/***/ 29050: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const cache = new WeakMap(); +const { Parser: AcornParser } = __webpack_require__(70108); +const { importAssertions } = __webpack_require__(72617); +const { SyncBailHook, HookMap } = __webpack_require__(41242); +const vm = __webpack_require__(26144); +const Parser = __webpack_require__(11715); +const StackedMap = __webpack_require__(58845); +const binarySearchBounds = __webpack_require__(92229); +const memoize = __webpack_require__(78676); +const BasicEvaluatedExpression = __webpack_require__(950); -class ObjectStructure { - constructor() { - this.keys = undefined; - this.children = undefined; - } +/** @typedef {import("acorn").Options} AcornOptions */ +/** @typedef {import("estree").ArrayExpression} ArrayExpressionNode */ +/** @typedef {import("estree").BinaryExpression} BinaryExpressionNode */ +/** @typedef {import("estree").BlockStatement} BlockStatementNode */ +/** @typedef {import("estree").SequenceExpression} SequenceExpressionNode */ +/** @typedef {import("estree").CallExpression} CallExpressionNode */ +/** @typedef {import("estree").ClassDeclaration} ClassDeclarationNode */ +/** @typedef {import("estree").ClassExpression} ClassExpressionNode */ +/** @typedef {import("estree").Comment} CommentNode */ +/** @typedef {import("estree").ConditionalExpression} ConditionalExpressionNode */ +/** @typedef {import("estree").Declaration} DeclarationNode */ +/** @typedef {import("estree").PrivateIdentifier} PrivateIdentifierNode */ +/** @typedef {import("estree").PropertyDefinition} PropertyDefinitionNode */ +/** @typedef {import("estree").Expression} ExpressionNode */ +/** @typedef {import("estree").Identifier} IdentifierNode */ +/** @typedef {import("estree").IfStatement} IfStatementNode */ +/** @typedef {import("estree").LabeledStatement} LabeledStatementNode */ +/** @typedef {import("estree").Literal} LiteralNode */ +/** @typedef {import("estree").LogicalExpression} LogicalExpressionNode */ +/** @typedef {import("estree").ChainExpression} ChainExpressionNode */ +/** @typedef {import("estree").MemberExpression} MemberExpressionNode */ +/** @typedef {import("estree").MetaProperty} MetaPropertyNode */ +/** @typedef {import("estree").MethodDefinition} MethodDefinitionNode */ +/** @typedef {import("estree").ModuleDeclaration} ModuleDeclarationNode */ +/** @typedef {import("estree").NewExpression} NewExpressionNode */ +/** @typedef {import("estree").Node} AnyNode */ +/** @typedef {import("estree").Program} ProgramNode */ +/** @typedef {import("estree").Statement} StatementNode */ +/** @typedef {import("estree").ImportDeclaration} ImportDeclarationNode */ +/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclarationNode */ +/** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclarationNode */ +/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclarationNode */ +/** @typedef {import("estree").Super} SuperNode */ +/** @typedef {import("estree").TaggedTemplateExpression} TaggedTemplateExpressionNode */ +/** @typedef {import("estree").TemplateLiteral} TemplateLiteralNode */ +/** @typedef {import("estree").ThisExpression} ThisExpressionNode */ +/** @typedef {import("estree").UnaryExpression} UnaryExpressionNode */ +/** @typedef {import("estree").VariableDeclarator} VariableDeclaratorNode */ +/** @template T @typedef {import("tapable").AsArray} AsArray */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ +/** @typedef {{declaredScope: ScopeInfo, freeName: string | true, tagInfo: TagInfo | undefined}} VariableInfoInterface */ +/** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[] }} GetInfoResult */ - getKeys(keys) { - if (this.keys === undefined) this.keys = keys; - return this.keys; - } +const EMPTY_ARRAY = []; +const ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = 0b01; +const ALLOWED_MEMBER_TYPES_EXPRESSION = 0b10; +const ALLOWED_MEMBER_TYPES_ALL = 0b11; - key(key) { - if (this.children === undefined) this.children = new Map(); - const child = this.children.get(key); - if (child !== undefined) return child; - const newChild = new ObjectStructure(); - this.children.set(key, newChild); - return newChild; - } -} - -const getCachedKeys = (keys, cacheAssoc) => { - let root = cache.get(cacheAssoc); - if (root === undefined) { - root = new ObjectStructure(); - cache.set(cacheAssoc, root); - } - let current = root; - for (const key of keys) { - current = current.key(key); - } - return current.getKeys(keys); -}; - -class PlainObjectSerializer { - serialize(obj, { write }) { - const keys = Object.keys(obj); - if (keys.length > 128) { - // Objects with so many keys are unlikely to share structure - // with other objects - write(keys); - for (const key of keys) { - write(obj[key]); - } - } else if (keys.length > 1) { - write(getCachedKeys(keys, write)); - for (const key of keys) { - write(obj[key]); - } - } else if (keys.length === 1) { - const key = keys[0]; - write(key); - write(obj[key]); - } else { - write(null); - } - } - deserialize({ read }) { - const keys = read(); - const obj = {}; - if (Array.isArray(keys)) { - for (const key of keys) { - obj[key] = read(); - } - } else if (keys !== null) { - obj[keys] = read(); - } - return obj; - } -} - -module.exports = PlainObjectSerializer; - - -/***/ }), - -/***/ 57328: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -class RegExpObjectSerializer { - serialize(obj, { write }) { - write(obj.source); - write(obj.flags); - } - deserialize({ read }) { - return new RegExp(read(), read()); - } -} - -module.exports = RegExpObjectSerializer; - - -/***/ }), - -/***/ 53080: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -class Serializer { - constructor(middlewares, context) { - this.serializeMiddlewares = middlewares.slice(); - this.deserializeMiddlewares = middlewares.slice().reverse(); - this.context = context; - } +// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API - serialize(obj, context) { - const ctx = { ...context, ...this.context }; - let current = obj; - for (const middleware of this.serializeMiddlewares) { - if (current && typeof current.then === "function") { - current = current.then(data => data && middleware.serialize(data, ctx)); - } else if (current) { - try { - current = middleware.serialize(current, ctx); - } catch (err) { - current = Promise.reject(err); - } - } else break; - } - return current; - } +const parser = AcornParser.extend(importAssertions); - deserialize(value, context) { - const ctx = { ...context, ...this.context }; - /** @type {any} */ - let current = value; - for (const middleware of this.deserializeMiddlewares) { - if (current && typeof current.then === "function") { - current = current.then(data => middleware.deserialize(data, ctx)); - } else { - current = middleware.deserialize(current, ctx); - } - } - return current; +class VariableInfo { + /** + * @param {ScopeInfo} declaredScope scope in which the variable is declared + * @param {string | true} freeName which free name the variable aliases, or true when none + * @param {TagInfo | undefined} tagInfo info about tags + */ + constructor(declaredScope, freeName, tagInfo) { + this.declaredScope = declaredScope; + this.freeName = freeName; + this.tagInfo = tagInfo; } } -module.exports = Serializer; - - -/***/ }), - -/***/ 83137: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const memoize = __webpack_require__(78676); +/** @typedef {string | ScopeInfo | VariableInfo} ExportedVariableInfo */ +/** @typedef {LiteralNode | string | null | undefined} ImportSource */ +/** @typedef {Omit & { sourceType: "module" | "script" | "auto", ecmaVersion?: AcornOptions["ecmaVersion"] }} ParseOptions */ -const LAZY_TARGET = Symbol("lazy serialization target"); -const LAZY_SERIALIZED_VALUE = Symbol("lazy serialization data"); +/** + * @typedef {Object} TagInfo + * @property {any} tag + * @property {any} data + * @property {TagInfo | undefined} next + */ /** - * @template DeserializedType - * @template SerializedType + * @typedef {Object} ScopeInfo + * @property {StackedMap} definitions + * @property {boolean | "arrow"} topLevelScope + * @property {boolean} inShorthand + * @property {boolean} isStrict + * @property {boolean} isAsmJs + * @property {boolean} inTry */ -class SerializerMiddleware { - /* istanbul ignore next */ - /** - * @abstract - * @param {DeserializedType} data data - * @param {Object} context context object - * @returns {SerializedType|Promise} serialized data - */ - serialize(data, context) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); - } - /* istanbul ignore next */ - /** - * @abstract - * @param {SerializedType} data data - * @param {Object} context context object - * @returns {DeserializedType|Promise} deserialized data - */ - deserialize(data, context) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); - } +const joinRanges = (startRange, endRange) => { + if (!endRange) return startRange; + if (!startRange) return endRange; + return [startRange[0], endRange[1]]; +}; - /** - * @param {any | function(): Promise | any} value contained value or function to value - * @param {SerializerMiddleware} target target middleware - * @param {object=} options lazy options - * @param {any=} serializedValue serialized value - * @returns {function(): Promise | any} lazy function - */ - static createLazy(value, target, options = {}, serializedValue) { - if (SerializerMiddleware.isLazy(value, target)) return value; - const fn = typeof value === "function" ? value : () => value; - fn[LAZY_TARGET] = target; - /** @type {any} */ (fn).options = options; - fn[LAZY_SERIALIZED_VALUE] = serializedValue; - return fn; +const objectAndMembersToName = (object, membersReversed) => { + let name = object; + for (let i = membersReversed.length - 1; i >= 0; i--) { + name = name + "." + membersReversed[i]; } + return name; +}; - /** - * @param {function(): Promise | any} fn lazy function - * @param {SerializerMiddleware=} target target middleware - * @returns {boolean} true, when fn is a lazy function (optionally of that target) - */ - static isLazy(fn, target) { - if (typeof fn !== "function") return false; - const t = fn[LAZY_TARGET]; - return target ? t === target : !!t; +const getRootName = expression => { + switch (expression.type) { + case "Identifier": + return expression.name; + case "ThisExpression": + return "this"; + case "MetaProperty": + return `${expression.meta.name}.${expression.property.name}`; + default: + return undefined; } +}; - /** - * @param {function(): Promise | any} fn lazy function - * @returns {object} options - */ - static getLazyOptions(fn) { - if (typeof fn !== "function") return undefined; - return /** @type {any} */ (fn).options; - } +/** @type {AcornOptions} */ +const defaultParserOptions = { + ranges: true, + locations: true, + ecmaVersion: "latest", + sourceType: "module", + // https://github.com/tc39/proposal-hashbang + allowHashBang: true, + onComment: null +}; - /** - * @param {function(): Promise | any} fn lazy function - * @returns {any} serialized value - */ - static getLazySerializedValue(fn) { - if (typeof fn !== "function") return undefined; - return fn[LAZY_SERIALIZED_VALUE]; - } +// regexp to match at least one "magic comment" +const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/); - /** - * @param {function(): Promise | any} fn lazy function - * @param {any} value serialized value - * @returns {void} - */ - static setLazySerializedValue(fn, value) { - fn[LAZY_SERIALIZED_VALUE] = value; - } +const EMPTY_COMMENT_OPTIONS = { + options: null, + errors: null +}; +class JavascriptParser extends Parser { /** - * @param {function(): Promise | any} lazy lazy function - * @param {function(any): Promise | any} serialize serialize function - * @returns {function(): Promise | any} new lazy + * @param {"module" | "script" | "auto"} sourceType default source type */ - static serializeLazy(lazy, serialize) { - const fn = memoize(() => { - const r = lazy(); - if (r && typeof r.then === "function") { - return r.then(data => data && serialize(data)); - } - return serialize(r); - }); - fn[LAZY_TARGET] = lazy[LAZY_TARGET]; - /** @type {any} */ (fn).options = /** @type {any} */ (lazy).options; - lazy[LAZY_SERIALIZED_VALUE] = fn; - return fn; - } + constructor(sourceType = "auto") { + super(); + this.hooks = Object.freeze({ + /** @type {HookMap>} */ + evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + evaluate: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + evaluateDefinedIdentifier: new HookMap( + () => new SyncBailHook(["expression"]) + ), + /** @type {HookMap>} */ + evaluateCallExpressionMember: new HookMap( + () => new SyncBailHook(["expression", "param"]) + ), + /** @type {HookMap>} */ + isPure: new HookMap( + () => new SyncBailHook(["expression", "commentsStartPosition"]) + ), + /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ + preStatement: new SyncBailHook(["statement"]), - /** - * @param {function(): Promise | any} lazy lazy function - * @param {function(any): Promise | any} deserialize deserialize function - * @returns {function(): Promise | any} new lazy - */ - static deserializeLazy(lazy, deserialize) { - const fn = memoize(() => { - const r = lazy(); - if (r && typeof r.then === "function") { - return r.then(data => deserialize(data)); - } - return deserialize(r); + /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ + blockPreStatement: new SyncBailHook(["declaration"]), + /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ + statement: new SyncBailHook(["statement"]), + /** @type {SyncBailHook<[IfStatementNode], boolean | void>} */ + statementIf: new SyncBailHook(["statement"]), + /** @type {SyncBailHook<[ExpressionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ + classExtendsExpression: new SyncBailHook([ + "expression", + "classDefinition" + ]), + /** @type {SyncBailHook<[MethodDefinitionNode | PropertyDefinitionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ + classBodyElement: new SyncBailHook(["element", "classDefinition"]), + /** @type {SyncBailHook<[ExpressionNode, MethodDefinitionNode | PropertyDefinitionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ + classBodyValue: new SyncBailHook([ + "expression", + "element", + "classDefinition" + ]), + /** @type {HookMap>} */ + label: new HookMap(() => new SyncBailHook(["statement"])), + /** @type {SyncBailHook<[ImportDeclarationNode, ImportSource], boolean | void>} */ + import: new SyncBailHook(["statement", "source"]), + /** @type {SyncBailHook<[ImportDeclarationNode, ImportSource, string, string], boolean | void>} */ + importSpecifier: new SyncBailHook([ + "statement", + "source", + "exportName", + "identifierName" + ]), + /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode], boolean | void>} */ + export: new SyncBailHook(["statement"]), + /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, ImportSource], boolean | void>} */ + exportImport: new SyncBailHook(["statement", "source"]), + /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, DeclarationNode], boolean | void>} */ + exportDeclaration: new SyncBailHook(["statement", "declaration"]), + /** @type {SyncBailHook<[ExportDefaultDeclarationNode, DeclarationNode], boolean | void>} */ + exportExpression: new SyncBailHook(["statement", "declaration"]), + /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, string, string, number | undefined], boolean | void>} */ + exportSpecifier: new SyncBailHook([ + "statement", + "identifierName", + "exportName", + "index" + ]), + /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, ImportSource, string, string, number | undefined], boolean | void>} */ + exportImportSpecifier: new SyncBailHook([ + "statement", + "source", + "identifierName", + "exportName", + "index" + ]), + /** @type {SyncBailHook<[VariableDeclaratorNode, StatementNode], boolean | void>} */ + preDeclarator: new SyncBailHook(["declarator", "statement"]), + /** @type {SyncBailHook<[VariableDeclaratorNode, StatementNode], boolean | void>} */ + declarator: new SyncBailHook(["declarator", "statement"]), + /** @type {HookMap>} */ + varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + pattern: new HookMap(() => new SyncBailHook(["pattern"])), + /** @type {HookMap>} */ + canRename: new HookMap(() => new SyncBailHook(["initExpression"])), + /** @type {HookMap>} */ + rename: new HookMap(() => new SyncBailHook(["initExpression"])), + /** @type {HookMap>} */ + assign: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + assignMemberChain: new HookMap( + () => new SyncBailHook(["expression", "members"]) + ), + /** @type {HookMap>} */ + typeof: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ + importCall: new SyncBailHook(["expression"]), + /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ + topLevelAwait: new SyncBailHook(["expression"]), + /** @type {HookMap>} */ + call: new HookMap(() => new SyncBailHook(["expression"])), + /** Something like "a.b()" */ + /** @type {HookMap>} */ + callMemberChain: new HookMap( + () => new SyncBailHook(["expression", "members"]) + ), + /** Something like "a.b().c.d" */ + /** @type {HookMap>} */ + memberChainOfCallMemberChain: new HookMap( + () => + new SyncBailHook([ + "expression", + "calleeMembers", + "callExpression", + "members" + ]) + ), + /** Something like "a.b().c.d()"" */ + /** @type {HookMap>} */ + callMemberChainOfCallMemberChain: new HookMap( + () => + new SyncBailHook([ + "expression", + "calleeMembers", + "innerCallExpression", + "members" + ]) + ), + /** @type {SyncBailHook<[ChainExpressionNode], boolean | void>} */ + optionalChaining: new SyncBailHook(["optionalChaining"]), + /** @type {HookMap>} */ + new: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + expression: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + expressionMemberChain: new HookMap( + () => new SyncBailHook(["expression", "members"]) + ), + /** @type {HookMap>} */ + unhandledExpressionMemberChain: new HookMap( + () => new SyncBailHook(["expression", "members"]) + ), + /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ + expressionConditionalOperator: new SyncBailHook(["expression"]), + /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ + expressionLogicalOperator: new SyncBailHook(["expression"]), + /** @type {SyncBailHook<[ProgramNode, CommentNode[]], boolean | void>} */ + program: new SyncBailHook(["ast", "comments"]), + /** @type {SyncBailHook<[ProgramNode, CommentNode[]], boolean | void>} */ + finish: new SyncBailHook(["ast", "comments"]) }); - fn[LAZY_TARGET] = lazy[LAZY_TARGET]; - /** @type {any} */ (fn).options = /** @type {any} */ (lazy).options; - fn[LAZY_SERIALIZED_VALUE] = lazy; - return fn; - } - - /** - * @param {function(): Promise | any} lazy lazy function - * @returns {function(): Promise | any} new lazy - */ - static unMemoizeLazy(lazy) { - if (!SerializerMiddleware.isLazy(lazy)) return lazy; - const fn = () => { - throw new Error( - "A lazy value that has been unmemorized can't be called again" - ); - }; - fn[LAZY_SERIALIZED_VALUE] = SerializerMiddleware.unMemoizeLazy( - lazy[LAZY_SERIALIZED_VALUE] - ); - fn[LAZY_TARGET] = lazy[LAZY_TARGET]; - fn.options = /** @type {any} */ (lazy).options; - return fn; - } -} - -module.exports = SerializerMiddleware; - - -/***/ }), - -/***/ 79240: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -class SetObjectSerializer { - serialize(obj, { write }) { - write(obj.size); - for (const value of obj) { - write(value); - } - } - deserialize({ read }) { - let size = read(); - const set = new Set(); - for (let i = 0; i < size; i++) { - set.add(read()); - } - return set; + this.sourceType = sourceType; + /** @type {ScopeInfo} */ + this.scope = undefined; + /** @type {ParserState} */ + this.state = undefined; + this.comments = undefined; + this.semicolons = undefined; + /** @type {(StatementNode|ExpressionNode)[]} */ + this.statementPath = undefined; + this.prevStatement = undefined; + this.currentTagData = undefined; + this._initializeEvaluating(); } -} - -module.exports = SetObjectSerializer; - - -/***/ }), - -/***/ 65112: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - + _initializeEvaluating() { + this.hooks.evaluate.for("Literal").tap("JavascriptParser", _expr => { + const expr = /** @type {LiteralNode} */ (_expr); -const SerializerMiddleware = __webpack_require__(83137); + switch (typeof expr.value) { + case "number": + return new BasicEvaluatedExpression() + .setNumber(expr.value) + .setRange(expr.range); + case "bigint": + return new BasicEvaluatedExpression() + .setBigInt(expr.value) + .setRange(expr.range); + case "string": + return new BasicEvaluatedExpression() + .setString(expr.value) + .setRange(expr.range); + case "boolean": + return new BasicEvaluatedExpression() + .setBoolean(expr.value) + .setRange(expr.range); + } + if (expr.value === null) { + return new BasicEvaluatedExpression().setNull().setRange(expr.range); + } + if (expr.value instanceof RegExp) { + return new BasicEvaluatedExpression() + .setRegExp(expr.value) + .setRange(expr.range); + } + }); + this.hooks.evaluate.for("NewExpression").tap("JavascriptParser", _expr => { + const expr = /** @type {NewExpressionNode} */ (_expr); + const callee = expr.callee; + if ( + callee.type !== "Identifier" || + callee.name !== "RegExp" || + expr.arguments.length > 2 || + this.getVariableInfo("RegExp") !== "RegExp" + ) + return; -/** - * @typedef {any} DeserializedType - * @typedef {any[]} SerializedType - * @extends {SerializerMiddleware} - */ -class SingleItemMiddleware extends SerializerMiddleware { - /** - * @param {DeserializedType} data data - * @param {Object} context context object - * @returns {SerializedType|Promise} serialized data - */ - serialize(data, context) { - return [data]; - } + let regExp, flags; + const arg1 = expr.arguments[0]; - /** - * @param {SerializedType} data data - * @param {Object} context context object - * @returns {DeserializedType|Promise} deserialized data - */ - deserialize(data, context) { - return data[0]; - } -} + if (arg1) { + if (arg1.type === "SpreadElement") return; -module.exports = SingleItemMiddleware; + const evaluatedRegExp = this.evaluateExpression(arg1); + if (!evaluatedRegExp) return; -/***/ }), + regExp = evaluatedRegExp.asString(); -/***/ 58831: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (!regExp) return; + } else { + return new BasicEvaluatedExpression() + .setRegExp(new RegExp("")) + .setRange(expr.range); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const arg2 = expr.arguments[1]; + if (arg2) { + if (arg2.type === "SpreadElement") return; + const evaluatedFlags = this.evaluateExpression(arg2); -const ModuleDependency = __webpack_require__(80321); -const makeSerializable = __webpack_require__(33032); + if (!evaluatedFlags) return; -class ConsumeSharedFallbackDependency extends ModuleDependency { - constructor(request) { - super(request); - } + if (!evaluatedFlags.isUndefined()) { + flags = evaluatedFlags.asString(); - get type() { - return "consume shared fallback"; - } + if ( + flags === undefined || + !BasicEvaluatedExpression.isValidRegExpFlags(flags) + ) + return; + } + } - get category() { - return "esm"; - } -} + return new BasicEvaluatedExpression() + .setRegExp(flags ? new RegExp(regExp, flags) : new RegExp(regExp)) + .setRange(expr.range); + }); + this.hooks.evaluate + .for("LogicalExpression") + .tap("JavascriptParser", _expr => { + const expr = /** @type {LogicalExpressionNode} */ (_expr); -makeSerializable( - ConsumeSharedFallbackDependency, - "webpack/lib/sharing/ConsumeSharedFallbackDependency" -); + const left = this.evaluateExpression(expr.left); + if (!left) return; + let returnRight = false; + /** @type {boolean|undefined} */ + let allowedRight; + if (expr.operator === "&&") { + const leftAsBool = left.asBool(); + if (leftAsBool === false) return left.setRange(expr.range); + returnRight = leftAsBool === true; + allowedRight = false; + } else if (expr.operator === "||") { + const leftAsBool = left.asBool(); + if (leftAsBool === true) return left.setRange(expr.range); + returnRight = leftAsBool === false; + allowedRight = true; + } else if (expr.operator === "??") { + const leftAsNullish = left.asNullish(); + if (leftAsNullish === false) return left.setRange(expr.range); + if (leftAsNullish !== true) return; + returnRight = true; + } else return; + const right = this.evaluateExpression(expr.right); + if (!right) return; + if (returnRight) { + if (left.couldHaveSideEffects()) right.setSideEffects(); + return right.setRange(expr.range); + } -module.exports = ConsumeSharedFallbackDependency; + const asBool = right.asBool(); + if (allowedRight === true && asBool === true) { + return new BasicEvaluatedExpression() + .setRange(expr.range) + .setTruthy(); + } else if (allowedRight === false && asBool === false) { + return new BasicEvaluatedExpression().setRange(expr.range).setFalsy(); + } + }); -/***/ }), + const valueAsExpression = (value, expr, sideEffects) => { + switch (typeof value) { + case "boolean": + return new BasicEvaluatedExpression() + .setBoolean(value) + .setSideEffects(sideEffects) + .setRange(expr.range); + case "number": + return new BasicEvaluatedExpression() + .setNumber(value) + .setSideEffects(sideEffects) + .setRange(expr.range); + case "bigint": + return new BasicEvaluatedExpression() + .setBigInt(value) + .setSideEffects(sideEffects) + .setRange(expr.range); + case "string": + return new BasicEvaluatedExpression() + .setString(value) + .setSideEffects(sideEffects) + .setRange(expr.range); + } + }; -/***/ 62286: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.hooks.evaluate + .for("BinaryExpression") + .tap("JavascriptParser", _expr => { + const expr = /** @type {BinaryExpressionNode} */ (_expr); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const handleConstOperation = fn => { + const left = this.evaluateExpression(expr.left); + if (!left || !left.isCompileTimeValue()) return; + const right = this.evaluateExpression(expr.right); + if (!right || !right.isCompileTimeValue()) return; + const result = fn( + left.asCompileTimeValue(), + right.asCompileTimeValue() + ); + return valueAsExpression( + result, + expr, + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + }; -const { RawSource } = __webpack_require__(51255); -const AsyncDependenciesBlock = __webpack_require__(47736); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const { rangeToString, stringifyHoley } = __webpack_require__(19702); -const ConsumeSharedFallbackDependency = __webpack_require__(58831); + const isAlwaysDifferent = (a, b) => + (a === true && b === false) || (a === false && b === true); -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {import("../util/semver").SemVerRange} SemVerRange */ + const handleTemplateStringCompare = (left, right, res, eql) => { + const getPrefix = parts => { + let value = ""; + for (const p of parts) { + const v = p.asString(); + if (v !== undefined) value += v; + else break; + } + return value; + }; + const getSuffix = parts => { + let value = ""; + for (let i = parts.length - 1; i >= 0; i--) { + const v = parts[i].asString(); + if (v !== undefined) value = v + value; + else break; + } + return value; + }; + const leftPrefix = getPrefix(left.parts); + const rightPrefix = getPrefix(right.parts); + const leftSuffix = getSuffix(left.parts); + const rightSuffix = getSuffix(right.parts); + const lenPrefix = Math.min(leftPrefix.length, rightPrefix.length); + const lenSuffix = Math.min(leftSuffix.length, rightSuffix.length); + if ( + leftPrefix.slice(0, lenPrefix) !== + rightPrefix.slice(0, lenPrefix) || + leftSuffix.slice(-lenSuffix) !== rightSuffix.slice(-lenSuffix) + ) { + return res + .setBoolean(!eql) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + }; -/** - * @typedef {Object} ConsumeOptions - * @property {string=} import fallback request - * @property {string=} importResolved resolved fallback request - * @property {string} shareKey global share key - * @property {string} shareScope share scope - * @property {SemVerRange | false | undefined} requiredVersion version requirement - * @property {string} packageName package name to determine required version automatically - * @property {boolean} strictVersion don't use shared version even if version isn't valid - * @property {boolean} singleton use single global version - * @property {boolean} eager include the fallback module in a sync way - */ + const handleStrictEqualityComparison = eql => { + const left = this.evaluateExpression(expr.left); + if (!left) return; + const right = this.evaluateExpression(expr.right); + if (!right) return; + const res = new BasicEvaluatedExpression(); + res.setRange(expr.range); -const TYPES = new Set(["consume-shared"]); + const leftConst = left.isCompileTimeValue(); + const rightConst = right.isCompileTimeValue(); -class ConsumeSharedModule extends Module { - /** - * @param {string} context context - * @param {ConsumeOptions} options consume options - */ - constructor(context, options) { - super("consume-shared-module", context); - this.options = options; - } + if (leftConst && rightConst) { + return res + .setBoolean( + eql === + (left.asCompileTimeValue() === right.asCompileTimeValue()) + ) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - const { - shareKey, - shareScope, - importResolved, - requiredVersion, - strictVersion, - singleton, - eager - } = this.options; - return `consume-shared-module|${shareScope}|${shareKey}|${ - requiredVersion && rangeToString(requiredVersion) - }|${strictVersion}|${importResolved}|${singleton}|${eager}`; - } + if (left.isArray() && right.isArray()) { + return res + .setBoolean(!eql) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + if (left.isTemplateString() && right.isTemplateString()) { + return handleTemplateStringCompare(left, right, res, eql); + } - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - const { - shareKey, - shareScope, - importResolved, - requiredVersion, - strictVersion, - singleton, - eager - } = this.options; - return `consume shared module (${shareScope}) ${shareKey}@${ - requiredVersion ? rangeToString(requiredVersion) : "*" - }${strictVersion ? " (strict)" : ""}${singleton ? " (singleton)" : ""}${ - importResolved - ? ` (fallback: ${requestShortener.shorten(importResolved)})` - : "" - }${eager ? " (eager)" : ""}`; - } + const leftPrimitive = left.isPrimitiveType(); + const rightPrimitive = right.isPrimitiveType(); - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - const { shareKey, shareScope, import: request } = this.options; - return `${ - this.layer ? `(${this.layer})/` : "" - }webpack/sharing/consume/${shareScope}/${shareKey}${ - request ? `/${request}` : "" - }`; - } + if ( + // Primitive !== Object or + // compile-time object types are never equal to something at runtime + (leftPrimitive === false && + (leftConst || rightPrimitive === true)) || + (rightPrimitive === false && + (rightConst || leftPrimitive === true)) || + // Different nullish or boolish status also means not equal + isAlwaysDifferent(left.asBool(), right.asBool()) || + isAlwaysDifferent(left.asNullish(), right.asNullish()) + ) { + return res + .setBoolean(!eql) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + }; - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - callback(null, !this.buildInfo); - } + const handleAbstractEqualityComparison = eql => { + const left = this.evaluateExpression(expr.left); + if (!left) return; + const right = this.evaluateExpression(expr.right); + if (!right) return; + const res = new BasicEvaluatedExpression(); + res.setRange(expr.range); - /** - * @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 = {}; - if (this.options.import) { - const dep = new ConsumeSharedFallbackDependency(this.options.import); - if (this.options.eager) { - this.addDependency(dep); - } else { - const block = new AsyncDependenciesBlock({}); - block.addDependency(dep); - this.addBlock(block); - } - } - callback(); - } + const leftConst = left.isCompileTimeValue(); + const rightConst = right.isCompileTimeValue(); - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; - } + if (leftConst && rightConst) { + return res + .setBoolean( + eql === + // eslint-disable-next-line eqeqeq + (left.asCompileTimeValue() == right.asCompileTimeValue()) + ) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } - /** - * @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; - } + if (left.isArray() && right.isArray()) { + return res + .setBoolean(!eql) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + if (left.isTemplateString() && right.isTemplateString()) { + return handleTemplateStringCompare(left, right, res, eql); + } + }; - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - hash.update(JSON.stringify(this.options)); - super.updateHash(hash, context); - } + if (expr.operator === "+") { + const left = this.evaluateExpression(expr.left); + if (!left) return; + const right = this.evaluateExpression(expr.right); + if (!right) return; + const res = new BasicEvaluatedExpression(); + if (left.isString()) { + if (right.isString()) { + res.setString(left.string + right.string); + } else if (right.isNumber()) { + res.setString(left.string + right.number); + } else if ( + right.isWrapped() && + right.prefix && + right.prefix.isString() + ) { + // "left" + ("prefix" + inner + "postfix") + // => ("leftPrefix" + inner + "postfix") + res.setWrapped( + new BasicEvaluatedExpression() + .setString(left.string + right.prefix.string) + .setRange(joinRanges(left.range, right.prefix.range)), + right.postfix, + right.wrappedInnerExpressions + ); + } else if (right.isWrapped()) { + // "left" + ([null] + inner + "postfix") + // => ("left" + inner + "postfix") + res.setWrapped( + left, + right.postfix, + right.wrappedInnerExpressions + ); + } else { + // "left" + expr + // => ("left" + expr + "") + res.setWrapped(left, null, [right]); + } + } else if (left.isNumber()) { + if (right.isString()) { + res.setString(left.number + right.string); + } else if (right.isNumber()) { + res.setNumber(left.number + right.number); + } else { + return; + } + } else if (left.isBigInt()) { + if (right.isBigInt()) { + res.setBigInt(left.bigint + right.bigint); + } + } else if (left.isWrapped()) { + if (left.postfix && left.postfix.isString() && right.isString()) { + // ("prefix" + inner + "postfix") + "right" + // => ("prefix" + inner + "postfixRight") + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(left.postfix.string + right.string) + .setRange(joinRanges(left.postfix.range, right.range)), + left.wrappedInnerExpressions + ); + } else if ( + left.postfix && + left.postfix.isString() && + right.isNumber() + ) { + // ("prefix" + inner + "postfix") + 123 + // => ("prefix" + inner + "postfix123") + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(left.postfix.string + right.number) + .setRange(joinRanges(left.postfix.range, right.range)), + left.wrappedInnerExpressions + ); + } else if (right.isString()) { + // ("prefix" + inner + [null]) + "right" + // => ("prefix" + inner + "right") + res.setWrapped(left.prefix, right, left.wrappedInnerExpressions); + } else if (right.isNumber()) { + // ("prefix" + inner + [null]) + 123 + // => ("prefix" + inner + "123") + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(right.number + "") + .setRange(right.range), + left.wrappedInnerExpressions + ); + } else if (right.isWrapped()) { + // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2") + // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2") + res.setWrapped( + left.prefix, + right.postfix, + left.wrappedInnerExpressions && + right.wrappedInnerExpressions && + left.wrappedInnerExpressions + .concat(left.postfix ? [left.postfix] : []) + .concat(right.prefix ? [right.prefix] : []) + .concat(right.wrappedInnerExpressions) + ); + } else { + // ("prefix" + inner + postfix) + expr + // => ("prefix" + inner + postfix + expr + [null]) + res.setWrapped( + left.prefix, + null, + left.wrappedInnerExpressions && + left.wrappedInnerExpressions.concat( + left.postfix ? [left.postfix, right] : [right] + ) + ); + } + } else { + if (right.isString()) { + // left + "right" + // => ([null] + left + "right") + res.setWrapped(null, right, [left]); + } else if (right.isWrapped()) { + // left + (prefix + inner + "postfix") + // => ([null] + left + prefix + inner + "postfix") + res.setWrapped( + null, + right.postfix, + right.wrappedInnerExpressions && + (right.prefix ? [left, right.prefix] : [left]).concat( + right.wrappedInnerExpressions + ) + ); + } else { + return; + } + } + if (left.couldHaveSideEffects() || right.couldHaveSideEffects()) + res.setSideEffects(); + res.setRange(expr.range); + return res; + } else if (expr.operator === "-") { + return handleConstOperation((l, r) => l - r); + } else if (expr.operator === "*") { + return handleConstOperation((l, r) => l * r); + } else if (expr.operator === "/") { + return handleConstOperation((l, r) => l / r); + } else if (expr.operator === "**") { + return handleConstOperation((l, r) => l ** r); + } else if (expr.operator === "===") { + return handleStrictEqualityComparison(true); + } else if (expr.operator === "==") { + return handleAbstractEqualityComparison(true); + } else if (expr.operator === "!==") { + return handleStrictEqualityComparison(false); + } else if (expr.operator === "!=") { + return handleAbstractEqualityComparison(false); + } else if (expr.operator === "&") { + return handleConstOperation((l, r) => l & r); + } else if (expr.operator === "|") { + return handleConstOperation((l, r) => l | r); + } else if (expr.operator === "^") { + return handleConstOperation((l, r) => l ^ r); + } else if (expr.operator === ">>>") { + return handleConstOperation((l, r) => l >>> r); + } else if (expr.operator === ">>") { + return handleConstOperation((l, r) => l >> r); + } else if (expr.operator === "<<") { + return handleConstOperation((l, r) => l << r); + } else if (expr.operator === "<") { + return handleConstOperation((l, r) => l < r); + } else if (expr.operator === ">") { + return handleConstOperation((l, r) => l > r); + } else if (expr.operator === "<=") { + return handleConstOperation((l, r) => l <= r); + } else if (expr.operator === ">=") { + return handleConstOperation((l, r) => l >= r); + } + }); + this.hooks.evaluate + .for("UnaryExpression") + .tap("JavascriptParser", _expr => { + const expr = /** @type {UnaryExpressionNode} */ (_expr); - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration({ chunkGraph, moduleGraph, runtimeTemplate }) { - const runtimeRequirements = new Set([RuntimeGlobals.shareScopeMap]); - const { - shareScope, - shareKey, - strictVersion, - requiredVersion, - import: request, - singleton, - eager - } = this.options; - let fallbackCode; - if (request) { - if (eager) { - const dep = this.dependencies[0]; - fallbackCode = runtimeTemplate.syncModuleFactory({ - dependency: dep, - chunkGraph, - runtimeRequirements, - request: this.options.import - }); - } else { - const block = this.blocks[0]; - fallbackCode = runtimeTemplate.asyncModuleFactory({ - block, - chunkGraph, - runtimeRequirements, - request: this.options.import + const handleConstOperation = fn => { + const argument = this.evaluateExpression(expr.argument); + if (!argument || !argument.isCompileTimeValue()) return; + const result = fn(argument.asCompileTimeValue()); + return valueAsExpression( + result, + expr, + argument.couldHaveSideEffects() + ); + }; + + if (expr.operator === "typeof") { + switch (expr.argument.type) { + case "Identifier": { + const res = this.callHooksForName( + this.hooks.evaluateTypeof, + expr.argument.name, + expr + ); + if (res !== undefined) return res; + break; + } + case "MetaProperty": { + const res = this.callHooksForName( + this.hooks.evaluateTypeof, + getRootName(expr.argument), + expr + ); + if (res !== undefined) return res; + break; + } + case "MemberExpression": { + const res = this.callHooksForExpression( + this.hooks.evaluateTypeof, + expr.argument, + expr + ); + if (res !== undefined) return res; + break; + } + case "ChainExpression": { + const res = this.callHooksForExpression( + this.hooks.evaluateTypeof, + expr.argument.expression, + expr + ); + if (res !== undefined) return res; + break; + } + case "FunctionExpression": { + return new BasicEvaluatedExpression() + .setString("function") + .setRange(expr.range); + } + } + const arg = this.evaluateExpression(expr.argument); + if (arg.isUnknown()) return; + if (arg.isString()) { + return new BasicEvaluatedExpression() + .setString("string") + .setRange(expr.range); + } + if (arg.isWrapped()) { + return new BasicEvaluatedExpression() + .setString("string") + .setSideEffects() + .setRange(expr.range); + } + if (arg.isUndefined()) { + return new BasicEvaluatedExpression() + .setString("undefined") + .setRange(expr.range); + } + if (arg.isNumber()) { + return new BasicEvaluatedExpression() + .setString("number") + .setRange(expr.range); + } + if (arg.isBigInt()) { + return new BasicEvaluatedExpression() + .setString("bigint") + .setRange(expr.range); + } + if (arg.isBoolean()) { + return new BasicEvaluatedExpression() + .setString("boolean") + .setRange(expr.range); + } + if (arg.isConstArray() || arg.isRegExp() || arg.isNull()) { + return new BasicEvaluatedExpression() + .setString("object") + .setRange(expr.range); + } + if (arg.isArray()) { + return new BasicEvaluatedExpression() + .setString("object") + .setSideEffects(arg.couldHaveSideEffects()) + .setRange(expr.range); + } + } else if (expr.operator === "!") { + const argument = this.evaluateExpression(expr.argument); + if (!argument) return; + const bool = argument.asBool(); + if (typeof bool !== "boolean") return; + return new BasicEvaluatedExpression() + .setBoolean(!bool) + .setSideEffects(argument.couldHaveSideEffects()) + .setRange(expr.range); + } else if (expr.operator === "~") { + return handleConstOperation(v => ~v); + } else if (expr.operator === "+") { + return handleConstOperation(v => +v); + } else if (expr.operator === "-") { + return handleConstOperation(v => -v); + } + }); + this.hooks.evaluateTypeof.for("undefined").tap("JavascriptParser", expr => { + return new BasicEvaluatedExpression() + .setString("undefined") + .setRange(expr.range); + }); + this.hooks.evaluate.for("Identifier").tap("JavascriptParser", expr => { + if (/** @type {IdentifierNode} */ (expr).name === "undefined") { + return new BasicEvaluatedExpression() + .setUndefined() + .setRange(expr.range); + } + }); + /** + * @param {string} exprType expression type name + * @param {function(ExpressionNode): GetInfoResult | undefined} getInfo get info + * @returns {void} + */ + const tapEvaluateWithVariableInfo = (exprType, getInfo) => { + /** @type {ExpressionNode | undefined} */ + let cachedExpression = undefined; + /** @type {GetInfoResult | undefined} */ + let cachedInfo = undefined; + this.hooks.evaluate.for(exprType).tap("JavascriptParser", expr => { + const expression = /** @type {MemberExpressionNode} */ (expr); + + const info = getInfo(expr); + if (info !== undefined) { + return this.callHooksForInfoWithFallback( + this.hooks.evaluateIdentifier, + info.name, + name => { + cachedExpression = expression; + cachedInfo = info; + }, + name => { + const hook = this.hooks.evaluateDefinedIdentifier.get(name); + if (hook !== undefined) { + return hook.call(expression); + } + }, + expression + ); + } + }); + this.hooks.evaluate + .for(exprType) + .tap({ name: "JavascriptParser", stage: 100 }, expr => { + const info = cachedExpression === expr ? cachedInfo : getInfo(expr); + if (info !== undefined) { + return new BasicEvaluatedExpression() + .setIdentifier(info.name, info.rootInfo, info.getMembers) + .setRange(expr.range); + } }); + this.hooks.finish.tap("JavascriptParser", () => { + // Cleanup for GC + cachedExpression = cachedInfo = undefined; + }); + }; + tapEvaluateWithVariableInfo("Identifier", expr => { + const info = this.getVariableInfo( + /** @type {IdentifierNode} */ (expr).name + ); + if ( + typeof info === "string" || + (info instanceof VariableInfo && typeof info.freeName === "string") + ) { + return { name: info, rootInfo: info, getMembers: () => [] }; } - } - let fn = "load"; - const args = [JSON.stringify(shareScope), JSON.stringify(shareKey)]; - if (requiredVersion) { - if (strictVersion) { - fn += "Strict"; + }); + tapEvaluateWithVariableInfo("ThisExpression", expr => { + const info = this.getVariableInfo("this"); + if ( + typeof info === "string" || + (info instanceof VariableInfo && typeof info.freeName === "string") + ) { + return { name: info, rootInfo: info, getMembers: () => [] }; } - if (singleton) { - fn += "Singleton"; + }); + this.hooks.evaluate.for("MetaProperty").tap("JavascriptParser", expr => { + const metaProperty = /** @type {MetaPropertyNode} */ (expr); + + return this.callHooksForName( + this.hooks.evaluateIdentifier, + getRootName(expr), + metaProperty + ); + }); + tapEvaluateWithVariableInfo("MemberExpression", expr => + this.getMemberExpressionInfo( + /** @type {MemberExpressionNode} */ (expr), + ALLOWED_MEMBER_TYPES_EXPRESSION + ) + ); + + this.hooks.evaluate.for("CallExpression").tap("JavascriptParser", _expr => { + const expr = /** @type {CallExpressionNode} */ (_expr); + if ( + expr.callee.type !== "MemberExpression" || + expr.callee.property.type !== + (expr.callee.computed ? "Literal" : "Identifier") + ) { + return; } - args.push(stringifyHoley(requiredVersion)); - fn += "VersionCheck"; - } else { - if (singleton) { - fn += "Singleton"; + + // type Super also possible here + const param = this.evaluateExpression( + /** @type {ExpressionNode} */ (expr.callee.object) + ); + if (!param) return; + const property = + expr.callee.property.type === "Literal" + ? `${expr.callee.property.value}` + : expr.callee.property.name; + const hook = this.hooks.evaluateCallExpressionMember.get(property); + if (hook !== undefined) { + return hook.call(expr, param); } - } - if (fallbackCode) { - fn += "Fallback"; - args.push(fallbackCode); - } - const code = runtimeTemplate.returningFunction(`${fn}(${args.join(", ")})`); - const sources = new Map(); - sources.set("consume-shared", new RawSource(code)); - return { - runtimeRequirements, - sources + }); + this.hooks.evaluateCallExpressionMember + .for("indexOf") + .tap("JavascriptParser", (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length === 0) return; + const [arg1, arg2] = expr.arguments; + if (arg1.type === "SpreadElement") return; + const arg1Eval = this.evaluateExpression(arg1); + if (!arg1Eval.isString()) return; + const arg1Value = arg1Eval.string; + + let result; + if (arg2) { + if (arg2.type === "SpreadElement") return; + const arg2Eval = this.evaluateExpression(arg2); + if (!arg2Eval.isNumber()) return; + result = param.string.indexOf(arg1Value, arg2Eval.number); + } else { + result = param.string.indexOf(arg1Value); + } + return new BasicEvaluatedExpression() + .setNumber(result) + .setSideEffects(param.couldHaveSideEffects()) + .setRange(expr.range); + }); + this.hooks.evaluateCallExpressionMember + .for("replace") + .tap("JavascriptParser", (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length !== 2) return; + if (expr.arguments[0].type === "SpreadElement") return; + if (expr.arguments[1].type === "SpreadElement") return; + let arg1 = this.evaluateExpression(expr.arguments[0]); + let arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isString() && !arg1.isRegExp()) return; + const arg1Value = arg1.regExp || arg1.string; + if (!arg2.isString()) return; + const arg2Value = arg2.string; + return new BasicEvaluatedExpression() + .setString(param.string.replace(arg1Value, arg2Value)) + .setSideEffects(param.couldHaveSideEffects()) + .setRange(expr.range); + }); + ["substr", "substring", "slice"].forEach(fn => { + this.hooks.evaluateCallExpressionMember + .for(fn) + .tap("JavascriptParser", (expr, param) => { + if (!param.isString()) return; + let arg1; + let result, + str = param.string; + switch (expr.arguments.length) { + case 1: + if (expr.arguments[0].type === "SpreadElement") return; + arg1 = this.evaluateExpression(expr.arguments[0]); + if (!arg1.isNumber()) return; + result = str[fn](arg1.number); + break; + case 2: { + if (expr.arguments[0].type === "SpreadElement") return; + if (expr.arguments[1].type === "SpreadElement") return; + arg1 = this.evaluateExpression(expr.arguments[0]); + const arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isNumber()) return; + if (!arg2.isNumber()) return; + result = str[fn](arg1.number, arg2.number); + break; + } + default: + return; + } + return new BasicEvaluatedExpression() + .setString(result) + .setSideEffects(param.couldHaveSideEffects()) + .setRange(expr.range); + }); + }); + + /** + * @param {"cooked" | "raw"} kind kind of values to get + * @param {TemplateLiteralNode} templateLiteralExpr TemplateLiteral expr + * @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template + */ + const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => { + /** @type {BasicEvaluatedExpression[]} */ + const quasis = []; + /** @type {BasicEvaluatedExpression[]} */ + const parts = []; + + for (let i = 0; i < templateLiteralExpr.quasis.length; i++) { + const quasiExpr = templateLiteralExpr.quasis[i]; + const quasi = quasiExpr.value[kind]; + + if (i > 0) { + const prevExpr = parts[parts.length - 1]; + const expr = this.evaluateExpression( + templateLiteralExpr.expressions[i - 1] + ); + const exprAsString = expr.asString(); + if ( + typeof exprAsString === "string" && + !expr.couldHaveSideEffects() + ) { + // We can merge quasi + expr + quasi when expr + // is a const string + + prevExpr.setString(prevExpr.string + exprAsString + quasi); + prevExpr.setRange([prevExpr.range[0], quasiExpr.range[1]]); + // We unset the expression as it doesn't match to a single expression + prevExpr.setExpression(undefined); + continue; + } + parts.push(expr); + } + + const part = new BasicEvaluatedExpression() + .setString(quasi) + .setRange(quasiExpr.range) + .setExpression(quasiExpr); + quasis.push(part); + parts.push(part); + } + return { + quasis, + parts + }; }; - } - serialize(context) { - const { write } = context; - write(this.options); - super.serialize(context); - } + this.hooks.evaluate + .for("TemplateLiteral") + .tap("JavascriptParser", _node => { + const node = /** @type {TemplateLiteralNode} */ (_node); - deserialize(context) { - const { read } = context; - this.options = read(); - super.deserialize(context); - } -} + const { quasis, parts } = getSimplifiedTemplateResult("cooked", node); + if (parts.length === 1) { + return parts[0].setRange(node.range); + } + return new BasicEvaluatedExpression() + .setTemplateString(quasis, parts, "cooked") + .setRange(node.range); + }); + this.hooks.evaluate + .for("TaggedTemplateExpression") + .tap("JavascriptParser", _node => { + const node = /** @type {TaggedTemplateExpressionNode} */ (_node); + const tag = this.evaluateExpression(node.tag); -makeSerializable( - ConsumeSharedModule, - "webpack/lib/sharing/ConsumeSharedModule" -); + if (tag.isIdentifier() && tag.identifier === "String.raw") { + const { quasis, parts } = getSimplifiedTemplateResult( + "raw", + node.quasi + ); + return new BasicEvaluatedExpression() + .setTemplateString(quasis, parts, "raw") + .setRange(node.range); + } + }); -module.exports = ConsumeSharedModule; + this.hooks.evaluateCallExpressionMember + .for("concat") + .tap("JavascriptParser", (expr, param) => { + if (!param.isString() && !param.isWrapped()) return; + let stringSuffix = null; + let hasUnknownParams = false; + const innerExpressions = []; + for (let i = expr.arguments.length - 1; i >= 0; i--) { + const arg = expr.arguments[i]; + if (arg.type === "SpreadElement") return; + const argExpr = this.evaluateExpression(arg); + if ( + hasUnknownParams || + (!argExpr.isString() && !argExpr.isNumber()) + ) { + hasUnknownParams = true; + innerExpressions.push(argExpr); + continue; + } -/***/ }), + const value = argExpr.isString() + ? argExpr.string + : "" + argExpr.number; -/***/ 15046: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const newString = value + (stringSuffix ? stringSuffix.string : ""); + const newRange = [ + argExpr.range[0], + (stringSuffix || argExpr).range[1] + ]; + stringSuffix = new BasicEvaluatedExpression() + .setString(newString) + .setSideEffects( + (stringSuffix && stringSuffix.couldHaveSideEffects()) || + argExpr.couldHaveSideEffects() + ) + .setRange(newRange); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (hasUnknownParams) { + const prefix = param.isString() ? param : param.prefix; + const inner = + param.isWrapped() && param.wrappedInnerExpressions + ? param.wrappedInnerExpressions.concat(innerExpressions.reverse()) + : innerExpressions.reverse(); + return new BasicEvaluatedExpression() + .setWrapped(prefix, stringSuffix, inner) + .setRange(expr.range); + } else if (param.isWrapped()) { + const postfix = stringSuffix || param.postfix; + const inner = param.wrappedInnerExpressions + ? param.wrappedInnerExpressions.concat(innerExpressions.reverse()) + : innerExpressions.reverse(); + return new BasicEvaluatedExpression() + .setWrapped(param.prefix, postfix, inner) + .setRange(expr.range); + } else { + const newString = + param.string + (stringSuffix ? stringSuffix.string : ""); + return new BasicEvaluatedExpression() + .setString(newString) + .setSideEffects( + (stringSuffix && stringSuffix.couldHaveSideEffects()) || + param.couldHaveSideEffects() + ) + .setRange(expr.range); + } + }); + this.hooks.evaluateCallExpressionMember + .for("split") + .tap("JavascriptParser", (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length !== 1) return; + if (expr.arguments[0].type === "SpreadElement") return; + let result; + const arg = this.evaluateExpression(expr.arguments[0]); + if (arg.isString()) { + result = param.string.split(arg.string); + } else if (arg.isRegExp()) { + result = param.string.split(arg.regExp); + } else { + return; + } + return new BasicEvaluatedExpression() + .setArray(result) + .setSideEffects(param.couldHaveSideEffects()) + .setRange(expr.range); + }); + this.hooks.evaluate + .for("ConditionalExpression") + .tap("JavascriptParser", _expr => { + const expr = /** @type {ConditionalExpressionNode} */ (_expr); + const condition = this.evaluateExpression(expr.test); + const conditionValue = condition.asBool(); + let res; + if (conditionValue === undefined) { + const consequent = this.evaluateExpression(expr.consequent); + const alternate = this.evaluateExpression(expr.alternate); + if (!consequent || !alternate) return; + res = new BasicEvaluatedExpression(); + if (consequent.isConditional()) { + res.setOptions(consequent.options); + } else { + res.setOptions([consequent]); + } + if (alternate.isConditional()) { + res.addOptions(alternate.options); + } else { + res.addOptions([alternate]); + } + } else { + res = this.evaluateExpression( + conditionValue ? expr.consequent : expr.alternate + ); + if (condition.couldHaveSideEffects()) res.setSideEffects(); + } + res.setRange(expr.range); + return res; + }); + this.hooks.evaluate + .for("ArrayExpression") + .tap("JavascriptParser", _expr => { + const expr = /** @type {ArrayExpressionNode} */ (_expr); + const items = expr.elements.map(element => { + return ( + element !== null && + element.type !== "SpreadElement" && + this.evaluateExpression(element) + ); + }); + if (!items.every(Boolean)) return; + return new BasicEvaluatedExpression() + .setItems(items) + .setRange(expr.range); + }); + this.hooks.evaluate + .for("ChainExpression") + .tap("JavascriptParser", _expr => { + const expr = /** @type {ChainExpressionNode} */ (_expr); + /** @type {ExpressionNode[]} */ + const optionalExpressionsStack = []; + /** @type {ExpressionNode|SuperNode} */ + let next = expr.expression; -const ModuleNotFoundError = __webpack_require__(32882); -const RuntimeGlobals = __webpack_require__(16475); -const WebpackError = __webpack_require__(53799); -const { parseOptions } = __webpack_require__(3083); -const LazySet = __webpack_require__(38938); -const createSchemaValidation = __webpack_require__(32540); -const { parseRange } = __webpack_require__(19702); -const ConsumeSharedFallbackDependency = __webpack_require__(58831); -const ConsumeSharedModule = __webpack_require__(62286); -const ConsumeSharedRuntimeModule = __webpack_require__(10394); -const ProvideForSharedDependency = __webpack_require__(40017); -const { resolveMatchedConfigs } = __webpack_require__(3591); -const { - isRequiredVersion, - getDescriptionFile, - getRequiredVersionFromDescriptionFile -} = __webpack_require__(84379); + 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; + } + } -/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumeSharedPluginOptions} ConsumeSharedPluginOptions */ -/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumesConfig} ConsumesConfig */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */ -/** @typedef {import("./ConsumeSharedModule").ConsumeOptions} ConsumeOptions */ + while (optionalExpressionsStack.length > 0) { + const expression = optionalExpressionsStack.pop(); + const evaluated = this.evaluateExpression(expression); -const validate = createSchemaValidation( - __webpack_require__(6464), - () => __webpack_require__(16116), - { - name: "Consume Shared Plugin", - baseDataPath: "options" + if (evaluated && evaluated.asNullish()) { + return evaluated.setRange(_expr.range); + } + } + return this.evaluateExpression(expr.expression); + }); } -); - -/** @type {ResolveOptionsWithDependencyType} */ -const RESOLVE_OPTIONS = { dependencyType: "esm" }; -const PLUGIN_NAME = "ConsumeSharedPlugin"; -class ConsumeSharedPlugin { - /** - * @param {ConsumeSharedPluginOptions} options options - */ - constructor(options) { - if (typeof options !== "string") { - validate(options); + getRenameIdentifier(expr) { + const result = this.evaluateExpression(expr); + if (result && result.isIdentifier()) { + return result.identifier; } - - /** @type {[string, ConsumeOptions][]} */ - this._consumes = parseOptions( - options.consumes, - (item, key) => { - if (Array.isArray(item)) throw new Error("Unexpected array in options"); - /** @type {ConsumeOptions} */ - let result = - item === key || !isRequiredVersion(item) - ? // item is a request/key - { - import: key, - shareScope: options.shareScope || "default", - shareKey: key, - requiredVersion: undefined, - packageName: undefined, - strictVersion: false, - singleton: false, - eager: false - } - : // key is a request/key - // item is a version - { - import: key, - shareScope: options.shareScope || "default", - shareKey: key, - requiredVersion: parseRange(item), - strictVersion: true, - packageName: undefined, - singleton: false, - eager: false - }; - return result; - }, - (item, key) => ({ - import: item.import === false ? undefined : item.import || key, - shareScope: item.shareScope || options.shareScope || "default", - shareKey: item.shareKey || key, - requiredVersion: - typeof item.requiredVersion === "string" - ? parseRange(item.requiredVersion) - : item.requiredVersion, - strictVersion: - typeof item.strictVersion === "boolean" - ? item.strictVersion - : item.import !== false && !item.singleton, - packageName: item.packageName, - singleton: !!item.singleton, - eager: !!item.eager - }) - ); } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {ClassExpressionNode | ClassDeclarationNode} classy a class node * @returns {void} */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - PLUGIN_NAME, - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - ConsumeSharedFallbackDependency, - normalModuleFactory - ); - - let unresolvedConsumes, resolvedConsumes, prefixedConsumes; - const promise = resolveMatchedConfigs(compilation, this._consumes).then( - ({ resolved, unresolved, prefixed }) => { - resolvedConsumes = resolved; - unresolvedConsumes = unresolved; - prefixedConsumes = prefixed; + walkClass(classy) { + if (classy.superClass) { + if (!this.hooks.classExtendsExpression.call(classy.superClass, classy)) { + this.walkExpression(classy.superClass); + } + } + if (classy.body && classy.body.type === "ClassBody") { + for (const classElement of /** @type {TODO} */ (classy.body.body)) { + if (!this.hooks.classBodyElement.call(classElement, classy)) { + if (classElement.computed && classElement.key) { + this.walkExpression(classElement.key); } - ); + if (classElement.value) { + if ( + !this.hooks.classBodyValue.call( + classElement.value, + classElement, + classy + ) + ) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + this.walkExpression(classElement.value); + this.scope.topLevelScope = wasTopLevel; + } + } + } + } + } + } - const resolver = compilation.resolverFactory.get( - "normal", - RESOLVE_OPTIONS - ); + // Pre walking iterates the scope for variable declarations + preWalkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.preWalkStatement(statement); + } + } - /** - * @param {string} context issuer directory - * @param {string} request request - * @param {ConsumeOptions} config options - * @returns {Promise} create module - */ - const createConsumeSharedModule = (context, request, config) => { - const requiredVersionWarning = details => { - const error = new WebpackError( - `No required version specified and unable to automatically determine one. ${details}` - ); - error.file = `shared module ${request}`; - compilation.warnings.push(error); - }; - const directFallback = - config.import && - /^(\.\.?(\/|$)|\/|[A-Za-z]:|\\\\)/.test(config.import); - return Promise.all([ - new Promise(resolve => { - if (!config.import) return resolve(); - const resolveContext = { - /** @type {LazySet} */ - fileDependencies: new LazySet(), - /** @type {LazySet} */ - contextDependencies: new LazySet(), - /** @type {LazySet} */ - missingDependencies: new LazySet() - }; - resolver.resolve( - {}, - directFallback ? compiler.context : context, - config.import, - resolveContext, - (err, result) => { - compilation.contextDependencies.addAll( - resolveContext.contextDependencies - ); - compilation.fileDependencies.addAll( - resolveContext.fileDependencies - ); - compilation.missingDependencies.addAll( - resolveContext.missingDependencies - ); - if (err) { - compilation.errors.push( - new ModuleNotFoundError(null, err, { - name: `resolving fallback for shared module ${request}` - }) - ); - return resolve(); - } - resolve(result); - } - ); - }), - new Promise(resolve => { - if (config.requiredVersion !== undefined) - return resolve(config.requiredVersion); - let packageName = config.packageName; - if (packageName === undefined) { - if (/^(\/|[A-Za-z]:|\\\\)/.test(request)) { - // For relative or absolute requests we don't automatically use a packageName. - // If wished one can specify one with the packageName option. - return resolve(); - } - const match = /^((?:@[^\\/]+[\\/])?[^\\/]+)/.exec(request); - if (!match) { - requiredVersionWarning( - "Unable to extract the package name from request." - ); - return resolve(); - } - packageName = match[0]; - } - - getDescriptionFile( - compilation.inputFileSystem, - context, - ["package.json"], - (err, result) => { - if (err) { - requiredVersionWarning( - `Unable to read description file: ${err}` - ); - return resolve(); - } - const { data, path: descriptionPath } = result; - if (!data) { - requiredVersionWarning( - `Unable to find description file in ${context}.` - ); - return resolve(); - } - const requiredVersion = getRequiredVersionFromDescriptionFile( - data, - packageName - ); - if (typeof requiredVersion !== "string") { - requiredVersionWarning( - `Unable to find required version for "${packageName}" in description file (${descriptionPath}). It need to be in dependencies, devDependencies or peerDependencies.` - ); - return resolve(); - } - resolve(parseRange(requiredVersion)); - } - ); - }) - ]).then(([importResolved, requiredVersion]) => { - return new ConsumeSharedModule( - directFallback ? compiler.context : context, - { - ...config, - importResolved, - import: importResolved ? config.import : undefined, - requiredVersion - } - ); - }); - }; - - normalModuleFactory.hooks.factorize.tapPromise( - PLUGIN_NAME, - ({ context, request, dependencies }) => - // wait for resolving to be complete - promise.then(() => { - if ( - dependencies[0] instanceof ConsumeSharedFallbackDependency || - dependencies[0] instanceof ProvideForSharedDependency - ) { - return; - } - const match = unresolvedConsumes.get(request); - if (match !== undefined) { - return createConsumeSharedModule(context, request, match); - } - for (const [prefix, options] of prefixedConsumes) { - if (request.startsWith(prefix)) { - const remainder = request.slice(prefix.length); - return createConsumeSharedModule(context, request, { - ...options, - import: options.import - ? options.import + remainder - : undefined, - shareKey: options.shareKey + remainder - }); - } - } - }) - ); - normalModuleFactory.hooks.createModule.tapPromise( - PLUGIN_NAME, - ({ resource }, { context, dependencies }) => { - if ( - dependencies[0] instanceof ConsumeSharedFallbackDependency || - dependencies[0] instanceof ProvideForSharedDependency - ) { - return Promise.resolve(); - } - const options = resolvedConsumes.get(resource); - if (options !== undefined) { - return createConsumeSharedModule(context, resource, options); - } - return Promise.resolve(); - } - ); - compilation.hooks.additionalTreeRuntimeRequirements.tap( - PLUGIN_NAME, - (chunk, set) => { - set.add(RuntimeGlobals.module); - set.add(RuntimeGlobals.moduleCache); - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.shareScopeMap); - set.add(RuntimeGlobals.initializeSharing); - set.add(RuntimeGlobals.hasOwnProperty); - compilation.addRuntimeModule( - chunk, - new ConsumeSharedRuntimeModule(set) - ); - } - ); - } - ); + // Block pre walking iterates the scope for block variable declarations + blockPreWalkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.blockPreWalkStatement(statement); + } } -} - -module.exports = ConsumeSharedPlugin; - - -/***/ }), - -/***/ 10394: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); -const { - parseVersionRuntimeCode, - versionLtRuntimeCode, - rangeToStringRuntimeCode, - satisfyRuntimeCode -} = __webpack_require__(19702); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("./ConsumeSharedModule")} ConsumeSharedModule */ -class ConsumeSharedRuntimeModule extends RuntimeModule { - constructor(runtimeRequirements) { - super("consumes", RuntimeModule.STAGE_ATTACH); - this._runtimeRequirements = runtimeRequirements; + // Walking iterates the statements and expressions and processes them + walkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.walkStatement(statement); + } } - /** - * @returns {string} runtime code - */ - generate() { - const { compilation, chunkGraph } = this; - const { runtimeTemplate, codeGenerationResults } = compilation; - const chunkToModuleMapping = {}; - /** @type {Map} */ - const moduleIdToSourceMapping = new Map(); - const initialConsumes = []; - /** - * - * @param {Iterable} modules modules - * @param {Chunk} chunk the chunk - * @param {(string | number)[]} list list of ids - */ - const addModules = (modules, chunk, list) => { - for (const m of modules) { - const module = /** @type {ConsumeSharedModule} */ (m); - const id = chunkGraph.getModuleId(module); - list.push(id); - moduleIdToSourceMapping.set( - id, - codeGenerationResults.getSource( - module, - chunk.runtime, - "consume-shared" - ) - ); - } - }; - for (const chunk of this.chunk.getAllAsyncChunks()) { - const modules = chunkGraph.getChunkModulesIterableBySourceType( - chunk, - "consume-shared" - ); - if (!modules) continue; - addModules(modules, chunk, (chunkToModuleMapping[chunk.id] = [])); + preWalkStatement(statement) { + this.statementPath.push(statement); + if (this.hooks.preStatement.call(statement)) { + this.prevStatement = this.statementPath.pop(); + return; } - for (const chunk of this.chunk.getAllInitialChunks()) { - const modules = chunkGraph.getChunkModulesIterableBySourceType( - chunk, - "consume-shared" - ); - if (!modules) continue; - addModules(modules, chunk, initialConsumes); + switch (statement.type) { + case "BlockStatement": + this.preWalkBlockStatement(statement); + break; + case "DoWhileStatement": + this.preWalkDoWhileStatement(statement); + break; + case "ForInStatement": + this.preWalkForInStatement(statement); + break; + case "ForOfStatement": + this.preWalkForOfStatement(statement); + break; + case "ForStatement": + this.preWalkForStatement(statement); + break; + case "FunctionDeclaration": + this.preWalkFunctionDeclaration(statement); + break; + case "IfStatement": + this.preWalkIfStatement(statement); + break; + case "LabeledStatement": + this.preWalkLabeledStatement(statement); + break; + case "SwitchStatement": + this.preWalkSwitchStatement(statement); + break; + case "TryStatement": + this.preWalkTryStatement(statement); + break; + case "VariableDeclaration": + this.preWalkVariableDeclaration(statement); + break; + case "WhileStatement": + this.preWalkWhileStatement(statement); + break; + case "WithStatement": + this.preWalkWithStatement(statement); + break; } - if (moduleIdToSourceMapping.size === 0) return null; - return Template.asString([ - parseVersionRuntimeCode(runtimeTemplate), - versionLtRuntimeCode(runtimeTemplate), - rangeToStringRuntimeCode(runtimeTemplate), - satisfyRuntimeCode(runtimeTemplate), - `var ensureExistence = ${runtimeTemplate.basicFunction("scopeName, key", [ - `var scope = ${RuntimeGlobals.shareScopeMap}[scopeName];`, - `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) throw new Error("Shared module " + key + " doesn't exist in shared scope " + scopeName);`, - "return scope;" - ])};`, - `var findVersion = ${runtimeTemplate.basicFunction("scope, key", [ - "var versions = scope[key];", - `var key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( - "a, b", - ["return !a || versionLt(a, b) ? b : a;"] - )}, 0);`, - "return key && versions[key]" - ])};`, - `var findSingletonVersionKey = ${runtimeTemplate.basicFunction( - "scope, key", - [ - "var versions = scope[key];", - `return Object.keys(versions).reduce(${runtimeTemplate.basicFunction( - "a, b", - ["return !a || (!versions[a].loaded && versionLt(a, b)) ? b : a;"] - )}, 0);` - ] - )};`, - `var getInvalidSingletonVersionMessage = ${runtimeTemplate.basicFunction( - "scope, key, version, requiredVersion", - [ - `return "Unsatisfied version " + version + " from " + (version && scope[key][version].from) + " of shared singleton module " + key + " (required " + rangeToString(requiredVersion) + ")"` - ] - )};`, - `var getSingleton = ${runtimeTemplate.basicFunction( - "scope, scopeName, key, requiredVersion", - [ - "var version = findSingletonVersionKey(scope, key);", - "return get(scope[key][version]);" - ] - )};`, - `var getSingletonVersion = ${runtimeTemplate.basicFunction( - "scope, scopeName, key, requiredVersion", - [ - "var version = findSingletonVersionKey(scope, key);", - "if (!satisfy(requiredVersion, version)) " + - 'typeof console !== "undefined" && console.warn && console.warn(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));', - "return get(scope[key][version]);" - ] - )};`, - `var getStrictSingletonVersion = ${runtimeTemplate.basicFunction( - "scope, scopeName, key, requiredVersion", - [ - "var version = findSingletonVersionKey(scope, key);", - "if (!satisfy(requiredVersion, version)) " + - "throw new Error(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));", - "return get(scope[key][version]);" - ] - )};`, - `var findValidVersion = ${runtimeTemplate.basicFunction( - "scope, key, requiredVersion", - [ - "var versions = scope[key];", - `var key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( - "a, b", - [ - "if (!satisfy(requiredVersion, b)) return a;", - "return !a || versionLt(a, b) ? b : a;" - ] - )}, 0);`, - "return key && versions[key]" - ] - )};`, - `var getInvalidVersionMessage = ${runtimeTemplate.basicFunction( - "scope, scopeName, key, requiredVersion", - [ - "var versions = scope[key];", - 'return "No satisfying version (" + rangeToString(requiredVersion) + ") of shared module " + key + " found in shared scope " + scopeName + ".\\n" +', - `\t"Available versions: " + Object.keys(versions).map(${runtimeTemplate.basicFunction( - "key", - ['return key + " from " + versions[key].from;'] - )}).join(", ");` - ] - )};`, - `var getValidVersion = ${runtimeTemplate.basicFunction( - "scope, scopeName, key, requiredVersion", - [ - "var entry = findValidVersion(scope, key, requiredVersion);", - "if(entry) return get(entry);", - "throw new Error(getInvalidVersionMessage(scope, scopeName, key, requiredVersion));" - ] - )};`, - `var warnInvalidVersion = ${runtimeTemplate.basicFunction( - "scope, scopeName, key, requiredVersion", - [ - 'typeof console !== "undefined" && console.warn && console.warn(getInvalidVersionMessage(scope, scopeName, key, requiredVersion));' - ] - )};`, - `var get = ${runtimeTemplate.basicFunction("entry", [ - "entry.loaded = 1;", - "return entry.get()" - ])};`, - `var init = ${runtimeTemplate.returningFunction( - Template.asString([ - "function(scopeName, a, b, c) {", - Template.indent([ - `var promise = ${RuntimeGlobals.initializeSharing}(scopeName);`, - `if (promise && promise.then) return promise.then(fn.bind(fn, scopeName, ${RuntimeGlobals.shareScopeMap}[scopeName], a, b, c));`, - `return fn(scopeName, ${RuntimeGlobals.shareScopeMap}[scopeName], a, b, c);` - ]), - "}" - ]), - "fn" - )};`, - "", - `var load = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key", - [ - "ensureExistence(scopeName, key);", - "return get(findVersion(scope, key));" - ] - )});`, - `var loadFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, fallback", - [ - `return scope && ${RuntimeGlobals.hasOwnProperty}(scope, key) ? get(findVersion(scope, key)) : fallback();` - ] - )});`, - `var loadVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version", - [ - "ensureExistence(scopeName, key);", - "return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key));" - ] - )});`, - `var loadSingleton = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key", - [ - "ensureExistence(scopeName, key);", - "return getSingleton(scope, scopeName, key);" - ] - )});`, - `var loadSingletonVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version", - [ - "ensureExistence(scopeName, key);", - "return getSingletonVersion(scope, scopeName, key, version);" - ] - )});`, - `var loadStrictVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version", - [ - "ensureExistence(scopeName, key);", - "return getValidVersion(scope, scopeName, key, version);" - ] - )});`, - `var loadStrictSingletonVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version", - [ - "ensureExistence(scopeName, key);", - "return getStrictSingletonVersion(scope, scopeName, key, version);" - ] - )});`, - `var loadVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version, fallback", - [ - `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, - "return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key));" - ] - )});`, - `var loadSingletonFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, fallback", - [ - `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, - "return getSingleton(scope, scopeName, key);" - ] - )});`, - `var loadSingletonVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version, fallback", - [ - `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, - "return getSingletonVersion(scope, scopeName, key, version);" - ] - )});`, - `var loadStrictVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version, fallback", - [ - `var entry = scope && ${RuntimeGlobals.hasOwnProperty}(scope, key) && findValidVersion(scope, key, version);`, - `return entry ? get(entry) : fallback();` - ] - )});`, - `var loadStrictSingletonVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version, fallback", - [ - `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, - "return getStrictSingletonVersion(scope, scopeName, key, version);" - ] - )});`, - "var installedModules = {};", - "var moduleToHandlerMapping = {", - Template.indent( - Array.from( - moduleIdToSourceMapping, - ([key, source]) => `${JSON.stringify(key)}: ${source.source()}` - ).join(",\n") - ), - "};", - - initialConsumes.length > 0 - ? Template.asString([ - `var initialConsumes = ${JSON.stringify(initialConsumes)};`, - `initialConsumes.forEach(${runtimeTemplate.basicFunction("id", [ - `${ - RuntimeGlobals.moduleFactories - }[id] = ${runtimeTemplate.basicFunction("module", [ - "// Handle case when module is used sync", - "installedModules[id] = 0;", - `delete ${RuntimeGlobals.moduleCache}[id];`, - "var factory = moduleToHandlerMapping[id]();", - 'if(typeof factory !== "function") throw new Error("Shared module is not available for eager consumption: " + id);', - `module.exports = factory();` - ])}` - ])});` - ]) - : "// no consumes in initial chunks", - this._runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) - ? Template.asString([ - `var chunkMapping = ${JSON.stringify( - chunkToModuleMapping, - null, - "\t" - )};`, - `${ - RuntimeGlobals.ensureChunkHandlers - }.consumes = ${runtimeTemplate.basicFunction("chunkId, promises", [ - `if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`, - Template.indent([ - `chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction( - "id", - [ - `if(${RuntimeGlobals.hasOwnProperty}(installedModules, id)) return promises.push(installedModules[id]);`, - `var onFactory = ${runtimeTemplate.basicFunction( - "factory", - [ - "installedModules[id] = 0;", - `${ - RuntimeGlobals.moduleFactories - }[id] = ${runtimeTemplate.basicFunction("module", [ - `delete ${RuntimeGlobals.moduleCache}[id];`, - "module.exports = factory();" - ])}` - ] - )};`, - `var onError = ${runtimeTemplate.basicFunction("error", [ - "delete installedModules[id];", - `${ - RuntimeGlobals.moduleFactories - }[id] = ${runtimeTemplate.basicFunction("module", [ - `delete ${RuntimeGlobals.moduleCache}[id];`, - "throw error;" - ])}` - ])};`, - "try {", - Template.indent([ - "var promise = moduleToHandlerMapping[id]();", - "if(promise.then) {", - Template.indent( - "promises.push(installedModules[id] = promise.then(onFactory)['catch'](onError));" - ), - "} else onFactory(promise);" - ]), - "} catch(e) { onError(e); }" - ] - )});` - ]), - "}" - ])}` - ]) - : "// no chunk loading of consumes" - ]); + this.prevStatement = this.statementPath.pop(); } -} - -module.exports = ConsumeSharedRuntimeModule; - - -/***/ }), - -/***/ 40017: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + blockPreWalkStatement(statement) { + this.statementPath.push(statement); + if (this.hooks.blockPreStatement.call(statement)) { + this.prevStatement = this.statementPath.pop(); + return; + } + switch (statement.type) { + case "ImportDeclaration": + this.blockPreWalkImportDeclaration(statement); + break; + case "ExportAllDeclaration": + this.blockPreWalkExportAllDeclaration(statement); + break; + case "ExportDefaultDeclaration": + this.blockPreWalkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.blockPreWalkExportNamedDeclaration(statement); + break; + case "VariableDeclaration": + this.blockPreWalkVariableDeclaration(statement); + break; + case "ClassDeclaration": + this.blockPreWalkClassDeclaration(statement); + break; + } + this.prevStatement = this.statementPath.pop(); + } -const ModuleDependency = __webpack_require__(80321); -const makeSerializable = __webpack_require__(33032); + walkStatement(statement) { + this.statementPath.push(statement); + if (this.hooks.statement.call(statement) !== undefined) { + this.prevStatement = this.statementPath.pop(); + return; + } + switch (statement.type) { + case "BlockStatement": + this.walkBlockStatement(statement); + break; + case "ClassDeclaration": + this.walkClassDeclaration(statement); + break; + case "DoWhileStatement": + this.walkDoWhileStatement(statement); + break; + case "ExportDefaultDeclaration": + this.walkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.walkExportNamedDeclaration(statement); + break; + case "ExpressionStatement": + this.walkExpressionStatement(statement); + break; + case "ForInStatement": + this.walkForInStatement(statement); + break; + case "ForOfStatement": + this.walkForOfStatement(statement); + break; + case "ForStatement": + this.walkForStatement(statement); + break; + case "FunctionDeclaration": + this.walkFunctionDeclaration(statement); + break; + case "IfStatement": + this.walkIfStatement(statement); + break; + case "LabeledStatement": + this.walkLabeledStatement(statement); + break; + case "ReturnStatement": + this.walkReturnStatement(statement); + break; + case "SwitchStatement": + this.walkSwitchStatement(statement); + break; + case "ThrowStatement": + this.walkThrowStatement(statement); + break; + case "TryStatement": + this.walkTryStatement(statement); + break; + case "VariableDeclaration": + this.walkVariableDeclaration(statement); + break; + case "WhileStatement": + this.walkWhileStatement(statement); + break; + case "WithStatement": + this.walkWithStatement(statement); + break; + } + this.prevStatement = this.statementPath.pop(); + } -class ProvideForSharedDependency extends ModuleDependency { /** - * - * @param {string} request request string + * Walks a statements that is nested within a parent statement + * and can potentially be a non-block statement. + * This enforces the nested statement to never be in ASI position. + * @param {StatementNode} statement the nested statement + * @returns {void} */ - constructor(request) { - super(request); + walkNestedStatement(statement) { + this.prevStatement = undefined; + this.walkStatement(statement); } - get type() { - return "provide module for shared"; + // Real Statements + preWalkBlockStatement(statement) { + this.preWalkStatements(statement.body); } - get category() { - return "esm"; + walkBlockStatement(statement) { + this.inBlockScope(() => { + const body = statement.body; + const prev = this.prevStatement; + this.blockPreWalkStatements(body); + this.prevStatement = prev; + this.walkStatements(body); + }); } -} - -makeSerializable( - ProvideForSharedDependency, - "webpack/lib/sharing/ProvideForSharedDependency" -); - -module.exports = ProvideForSharedDependency; - - -/***/ }), -/***/ 1798: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Dependency = __webpack_require__(54912); -const makeSerializable = __webpack_require__(33032); - -class ProvideSharedDependency extends Dependency { - constructor(shareScope, name, version, request, eager) { - super(); - this.shareScope = shareScope; - this.name = name; - this.version = version; - this.request = request; - this.eager = eager; + walkExpressionStatement(statement) { + this.walkExpression(statement.expression); } - get type() { - return "provide shared module"; + preWalkIfStatement(statement) { + this.preWalkStatement(statement.consequent); + if (statement.alternate) { + this.preWalkStatement(statement.alternate); + } } - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - return `provide module (${this.shareScope}) ${this.request} as ${ - this.name - } @ ${this.version}${this.eager ? " (eager)" : ""}`; + walkIfStatement(statement) { + const result = this.hooks.statementIf.call(statement); + if (result === undefined) { + this.walkExpression(statement.test); + this.walkNestedStatement(statement.consequent); + if (statement.alternate) { + this.walkNestedStatement(statement.alternate); + } + } else { + if (result) { + this.walkNestedStatement(statement.consequent); + } else if (statement.alternate) { + this.walkNestedStatement(statement.alternate); + } + } } - serialize(context) { - context.write(this.shareScope); - context.write(this.name); - context.write(this.request); - context.write(this.version); - context.write(this.eager); - super.serialize(context); + preWalkLabeledStatement(statement) { + this.preWalkStatement(statement.body); } - static deserialize(context) { - const { read } = context; - const obj = new ProvideSharedDependency( - read(), - read(), - read(), - read(), - read() - ); - this.shareScope = context.read(); - obj.deserialize(context); - return obj; + walkLabeledStatement(statement) { + const hook = this.hooks.label.get(statement.label.name); + if (hook !== undefined) { + const result = hook.call(statement); + if (result === true) return; + } + this.walkNestedStatement(statement.body); } -} - -makeSerializable( - ProvideSharedDependency, - "webpack/lib/sharing/ProvideSharedDependency" -); - -module.exports = ProvideSharedDependency; - - -/***/ }), - -/***/ 50821: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy -*/ - - - -const AsyncDependenciesBlock = __webpack_require__(47736); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const ProvideForSharedDependency = __webpack_require__(40017); -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ + preWalkWithStatement(statement) { + this.preWalkStatement(statement.body); + } -const TYPES = new Set(["share-init"]); + walkWithStatement(statement) { + this.walkExpression(statement.object); + this.walkNestedStatement(statement.body); + } -class ProvideSharedModule extends Module { - /** - * @param {string} shareScope shared scope name - * @param {string} name shared key - * @param {string | false} version version - * @param {string} request request to the provided module - * @param {boolean} eager include the module in sync way - */ - constructor(shareScope, name, version, request, eager) { - super("provide-module"); - this._shareScope = shareScope; - this._name = name; - this._version = version; - this._request = request; - this._eager = eager; + preWalkSwitchStatement(statement) { + this.preWalkSwitchCases(statement.cases); } - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return `provide module (${this._shareScope}) ${this._name}@${this._version} = ${this._request}`; + walkSwitchStatement(statement) { + this.walkExpression(statement.discriminant); + this.walkSwitchCases(statement.cases); } - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return `provide shared module (${this._shareScope}) ${this._name}@${ - this._version - } = ${requestShortener.shorten(this._request)}`; + walkTerminatingStatement(statement) { + if (statement.argument) this.walkExpression(statement.argument); } - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - return `${this.layer ? `(${this.layer})/` : ""}webpack/sharing/provide/${ - this._shareScope - }/${this._name}`; + walkReturnStatement(statement) { + this.walkTerminatingStatement(statement); } - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - callback(null, !this.buildInfo); + walkThrowStatement(statement) { + this.walkTerminatingStatement(statement); } - /** - * @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 = { - strict: true - }; + preWalkTryStatement(statement) { + this.preWalkStatement(statement.block); + if (statement.handler) this.preWalkCatchClause(statement.handler); + if (statement.finializer) this.preWalkStatement(statement.finializer); + } - this.clearDependenciesAndBlocks(); - const dep = new ProvideForSharedDependency(this._request); - if (this._eager) { - this.addDependency(dep); + walkTryStatement(statement) { + if (this.scope.inTry) { + this.walkStatement(statement.block); } else { - const block = new AsyncDependenciesBlock({}); - block.addDependency(dep); - this.addBlock(block); + this.scope.inTry = true; + this.walkStatement(statement.block); + this.scope.inTry = false; } - - callback(); + if (statement.handler) this.walkCatchClause(statement.handler); + if (statement.finalizer) this.walkStatement(statement.finalizer); } - /** - * @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; + preWalkWhileStatement(statement) { + this.preWalkStatement(statement.body); } - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; + walkWhileStatement(statement) { + this.walkExpression(statement.test); + this.walkNestedStatement(statement.body); } - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { - const runtimeRequirements = new Set([RuntimeGlobals.initializeSharing]); - const code = `register(${JSON.stringify(this._name)}, ${JSON.stringify( - this._version || "0" - )}, ${ - this._eager - ? runtimeTemplate.syncModuleFactory({ - dependency: this.dependencies[0], - chunkGraph, - request: this._request, - runtimeRequirements - }) - : runtimeTemplate.asyncModuleFactory({ - block: this.blocks[0], - chunkGraph, - request: this._request, - runtimeRequirements - }) - }${this._eager ? ", 1" : ""});`; - const sources = new Map(); - const data = new Map(); - data.set("share-init", [ - { - shareScope: this._shareScope, - initStage: 10, - init: code - } - ]); - return { sources, data, runtimeRequirements }; + preWalkDoWhileStatement(statement) { + this.preWalkStatement(statement.body); } - serialize(context) { - const { write } = context; - write(this._shareScope); - write(this._name); - write(this._version); - write(this._request); - write(this._eager); - super.serialize(context); + walkDoWhileStatement(statement) { + this.walkNestedStatement(statement.body); + this.walkExpression(statement.test); } - static deserialize(context) { - const { read } = context; - const obj = new ProvideSharedModule(read(), read(), read(), read(), read()); - obj.deserialize(context); - return obj; + preWalkForStatement(statement) { + if (statement.init) { + if (statement.init.type === "VariableDeclaration") { + this.preWalkStatement(statement.init); + } + } + this.preWalkStatement(statement.body); } -} - -makeSerializable( - ProvideSharedModule, - "webpack/lib/sharing/ProvideSharedModule" -); - -module.exports = ProvideSharedModule; - - -/***/ }), - -/***/ 39344: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy -*/ - - -const ModuleFactory = __webpack_require__(51010); -const ProvideSharedModule = __webpack_require__(50821); - -/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("./ProvideSharedDependency")} ProvideSharedDependency */ - -class ProvideSharedModuleFactory extends ModuleFactory { - /** - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback - * @returns {void} - */ - create(data, callback) { - const dep = /** @type {ProvideSharedDependency} */ (data.dependencies[0]); - callback(null, { - module: new ProvideSharedModule( - dep.shareScope, - dep.name, - dep.version, - dep.request, - dep.eager - ) + walkForStatement(statement) { + this.inBlockScope(() => { + if (statement.init) { + if (statement.init.type === "VariableDeclaration") { + this.blockPreWalkVariableDeclaration(statement.init); + this.prevStatement = undefined; + this.walkStatement(statement.init); + } else { + this.walkExpression(statement.init); + } + } + if (statement.test) { + this.walkExpression(statement.test); + } + if (statement.update) { + this.walkExpression(statement.update); + } + const body = statement.body; + if (body.type === "BlockStatement") { + // no need to add additional scope + const prev = this.prevStatement; + this.blockPreWalkStatements(body.body); + this.prevStatement = prev; + this.walkStatements(body.body); + } else { + this.walkNestedStatement(body); + } }); } -} -module.exports = ProvideSharedModuleFactory; + preWalkForInStatement(statement) { + if (statement.left.type === "VariableDeclaration") { + this.preWalkVariableDeclaration(statement.left); + } + this.preWalkStatement(statement.body); + } + walkForInStatement(statement) { + this.inBlockScope(() => { + if (statement.left.type === "VariableDeclaration") { + this.blockPreWalkVariableDeclaration(statement.left); + this.walkVariableDeclaration(statement.left); + } else { + this.walkPattern(statement.left); + } + this.walkExpression(statement.right); + const body = statement.body; + if (body.type === "BlockStatement") { + // no need to add additional scope + const prev = this.prevStatement; + this.blockPreWalkStatements(body.body); + this.prevStatement = prev; + this.walkStatements(body.body); + } else { + this.walkNestedStatement(body); + } + }); + } -/***/ }), + preWalkForOfStatement(statement) { + if (statement.await && this.scope.topLevelScope === true) { + this.hooks.topLevelAwait.call(statement); + } + if (statement.left.type === "VariableDeclaration") { + this.preWalkVariableDeclaration(statement.left); + } + this.preWalkStatement(statement.body); + } -/***/ 31225: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + walkForOfStatement(statement) { + this.inBlockScope(() => { + if (statement.left.type === "VariableDeclaration") { + this.blockPreWalkVariableDeclaration(statement.left); + this.walkVariableDeclaration(statement.left); + } else { + this.walkPattern(statement.left); + } + this.walkExpression(statement.right); + const body = statement.body; + if (body.type === "BlockStatement") { + // no need to add additional scope + const prev = this.prevStatement; + this.blockPreWalkStatements(body.body); + this.prevStatement = prev; + this.walkStatements(body.body); + } else { + this.walkNestedStatement(body); + } + }); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy -*/ + // Declarations + preWalkFunctionDeclaration(statement) { + if (statement.id) { + this.defineVariable(statement.id.name); + } + } + walkFunctionDeclaration(statement) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + this.inFunctionScope(true, statement.params, () => { + for (const param of statement.params) { + this.walkPattern(param); + } + if (statement.body.type === "BlockStatement") { + this.detectMode(statement.body.body); + const prev = this.prevStatement; + this.preWalkStatement(statement.body); + this.prevStatement = prev; + this.walkStatement(statement.body); + } else { + this.walkExpression(statement.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } + blockPreWalkImportDeclaration(statement) { + const source = statement.source.value; + this.hooks.import.call(statement, source); + for (const specifier of statement.specifiers) { + const name = specifier.local.name; + switch (specifier.type) { + case "ImportDefaultSpecifier": + if ( + !this.hooks.importSpecifier.call(statement, source, "default", name) + ) { + this.defineVariable(name); + } + break; + case "ImportSpecifier": + if ( + !this.hooks.importSpecifier.call( + statement, + source, + specifier.imported.name, + name + ) + ) { + this.defineVariable(name); + } + break; + case "ImportNamespaceSpecifier": + if (!this.hooks.importSpecifier.call(statement, source, null, name)) { + this.defineVariable(name); + } + break; + default: + this.defineVariable(name); + } + } + } -const WebpackError = __webpack_require__(53799); -const { parseOptions } = __webpack_require__(3083); -const createSchemaValidation = __webpack_require__(32540); -const ProvideForSharedDependency = __webpack_require__(40017); -const ProvideSharedDependency = __webpack_require__(1798); -const ProvideSharedModuleFactory = __webpack_require__(39344); + enterDeclaration(declaration, onIdent) { + switch (declaration.type) { + case "VariableDeclaration": + for (const declarator of declaration.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + this.enterPattern(declarator.id, onIdent); + break; + } + } + } + break; + case "FunctionDeclaration": + this.enterPattern(declaration.id, onIdent); + break; + case "ClassDeclaration": + this.enterPattern(declaration.id, onIdent); + break; + } + } -/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvideSharedPluginOptions} ProvideSharedPluginOptions */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compiler")} Compiler */ + blockPreWalkExportNamedDeclaration(statement) { + let source; + if (statement.source) { + source = statement.source.value; + this.hooks.exportImport.call(statement, source); + } else { + this.hooks.export.call(statement); + } + if (statement.declaration) { + if ( + !this.hooks.exportDeclaration.call(statement, statement.declaration) + ) { + const prev = this.prevStatement; + this.preWalkStatement(statement.declaration); + this.prevStatement = prev; + this.blockPreWalkStatement(statement.declaration); + let index = 0; + this.enterDeclaration(statement.declaration, def => { + this.hooks.exportSpecifier.call(statement, def, def, index++); + }); + } + } + if (statement.specifiers) { + for ( + let specifierIndex = 0; + specifierIndex < statement.specifiers.length; + specifierIndex++ + ) { + const specifier = statement.specifiers[specifierIndex]; + switch (specifier.type) { + case "ExportSpecifier": { + const name = specifier.exported.name; + if (source) { + this.hooks.exportImportSpecifier.call( + statement, + source, + specifier.local.name, + name, + specifierIndex + ); + } else { + this.hooks.exportSpecifier.call( + statement, + specifier.local.name, + name, + specifierIndex + ); + } + break; + } + } + } + } + } -const validate = createSchemaValidation( - __webpack_require__(91924), - () => __webpack_require__(438), - { - name: "Provide Shared Plugin", - baseDataPath: "options" + walkExportNamedDeclaration(statement) { + if (statement.declaration) { + this.walkStatement(statement.declaration); + } } -); -/** - * @typedef {Object} ProvideOptions - * @property {string} shareKey - * @property {string} shareScope - * @property {string | undefined | false} version - * @property {boolean} eager - */ + blockPreWalkExportDefaultDeclaration(statement) { + const prev = this.prevStatement; + this.preWalkStatement(statement.declaration); + this.prevStatement = prev; + this.blockPreWalkStatement(statement.declaration); + if ( + statement.declaration.id && + statement.declaration.type !== "FunctionExpression" && + statement.declaration.type !== "ClassExpression" + ) { + this.hooks.exportSpecifier.call( + statement, + statement.declaration.id.name, + "default", + undefined + ); + } + } -/** @typedef {Map} ResolvedProvideMap */ + walkExportDefaultDeclaration(statement) { + this.hooks.export.call(statement); + if ( + statement.declaration.id && + statement.declaration.type !== "FunctionExpression" && + statement.declaration.type !== "ClassExpression" + ) { + if ( + !this.hooks.exportDeclaration.call(statement, statement.declaration) + ) { + this.walkStatement(statement.declaration); + } + } else { + // Acorn parses `export default function() {}` as `FunctionDeclaration` and + // `export default class {}` as `ClassDeclaration`, both with `id = null`. + // These nodes must be treated as expressions. + if ( + statement.declaration.type === "FunctionDeclaration" || + statement.declaration.type === "ClassDeclaration" + ) { + this.walkStatement(statement.declaration); + } else { + this.walkExpression(statement.declaration); + } + if (!this.hooks.exportExpression.call(statement, statement.declaration)) { + this.hooks.exportSpecifier.call( + statement, + statement.declaration, + "default", + undefined + ); + } + } + } -class ProvideSharedPlugin { - /** - * @param {ProvideSharedPluginOptions} options options - */ - constructor(options) { - validate(options); + blockPreWalkExportAllDeclaration(statement) { + const source = statement.source.value; + const name = statement.exported ? statement.exported.name : null; + this.hooks.exportImport.call(statement, source); + this.hooks.exportImportSpecifier.call(statement, source, null, name, 0); + } - /** @type {[string, ProvideOptions][]} */ - this._provides = parseOptions( - options.provides, - item => { - if (Array.isArray(item)) - throw new Error("Unexpected array of provides"); - /** @type {ProvideOptions} */ - const result = { - shareKey: item, - version: undefined, - shareScope: options.shareScope || "default", - eager: false - }; - return result; - }, - item => ({ - shareKey: item.shareKey, - version: item.version, - shareScope: item.shareScope || options.shareScope || "default", - eager: !!item.eager - }) - ); - this._provides.sort(([a], [b]) => { - if (a < b) return -1; - if (b < a) return 1; - return 0; - }); + preWalkVariableDeclaration(statement) { + if (statement.kind !== "var") return; + this._preWalkVariableDeclaration(statement, this.hooks.varDeclarationVar); } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - /** @type {WeakMap} */ - const compilationData = new WeakMap(); + blockPreWalkVariableDeclaration(statement) { + if (statement.kind === "var") return; + const hookMap = + statement.kind === "const" + ? this.hooks.varDeclarationConst + : this.hooks.varDeclarationLet; + this._preWalkVariableDeclaration(statement, hookMap); + } - compiler.hooks.compilation.tap( - "ProvideSharedPlugin", - (compilation, { normalModuleFactory }) => { - /** @type {ResolvedProvideMap} */ - const resolvedProvideMap = new Map(); - /** @type {Map} */ - const matchProvides = new Map(); - /** @type {Map} */ - const prefixMatchProvides = new Map(); - for (const [request, config] of this._provides) { - if (/^(\/|[A-Za-z]:\\|\\\\|\.\.?(\/|$))/.test(request)) { - // relative request - resolvedProvideMap.set(request, { - config, - version: config.version - }); - } else if (/^(\/|[A-Za-z]:\\|\\\\)/.test(request)) { - // absolute path - resolvedProvideMap.set(request, { - config, - version: config.version + _preWalkVariableDeclaration(statement, hookMap) { + for (const declarator of statement.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + if (!this.hooks.preDeclarator.call(declarator, statement)) { + this.enterPattern(declarator.id, (name, decl) => { + let hook = hookMap.get(name); + if (hook === undefined || !hook.call(decl)) { + hook = this.hooks.varDeclaration.get(name); + if (hook === undefined || !hook.call(decl)) { + this.defineVariable(name); + } + } }); - } else if (request.endsWith("/")) { - // module request prefix - prefixMatchProvides.set(request, config); - } else { - // module request - matchProvides.set(request, config); } + break; } - compilationData.set(compilation, resolvedProvideMap); - const provideSharedModule = ( - key, - config, - resource, - resourceResolveData - ) => { - let version = config.version; - if (version === undefined) { - let details = ""; - if (!resourceResolveData) { - details = `No resolve data provided from resolver.`; - } else { - const descriptionFileData = - resourceResolveData.descriptionFileData; - if (!descriptionFileData) { - details = - "No description file (usually package.json) found. Add description file with name and version, or manually specify version in shared config."; - } else if (!descriptionFileData.version) { - details = - "No version in description file (usually package.json). Add version to description file, or manually specify version in shared config."; - } else { - version = descriptionFileData.version; + } + } + } + + walkVariableDeclaration(statement) { + for (const declarator of statement.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + const renameIdentifier = + declarator.init && this.getRenameIdentifier(declarator.init); + if (renameIdentifier && declarator.id.type === "Identifier") { + const hook = this.hooks.canRename.get(renameIdentifier); + if (hook !== undefined && hook.call(declarator.init)) { + // renaming with "var a = b;" + const hook = this.hooks.rename.get(renameIdentifier); + if (hook === undefined || !hook.call(declarator.init)) { + this.setVariable(declarator.id.name, renameIdentifier); } - } - if (!version) { - const error = new WebpackError( - `No version specified and unable to automatically determine one. ${details}` - ); - error.file = `shared module ${key} -> ${resource}`; - compilation.warnings.push(error); + break; } } - resolvedProvideMap.set(resource, { - config, - version - }); - }; - normalModuleFactory.hooks.module.tap( - "ProvideSharedPlugin", - (module, { resource, resourceResolveData }, resolveData) => { - if (resolvedProvideMap.has(resource)) { - return module; - } - const { request } = resolveData; - { - const config = matchProvides.get(request); - if (config !== undefined) { - provideSharedModule( - request, - config, - resource, - resourceResolveData - ); - resolveData.cacheable = false; - } - } - for (const [prefix, config] of prefixMatchProvides) { - if (request.startsWith(prefix)) { - const remainder = request.slice(prefix.length); - provideSharedModule( - resource, - { - ...config, - shareKey: config.shareKey + remainder - }, - resource, - resourceResolveData - ); - resolveData.cacheable = false; - } - } - return module; + if (!this.hooks.declarator.call(declarator, statement)) { + this.walkPattern(declarator.id); + if (declarator.init) this.walkExpression(declarator.init); } - ); + break; + } } - ); - compiler.hooks.finishMake.tapPromise("ProvideSharedPlugin", compilation => { - const resolvedProvideMap = compilationData.get(compilation); - if (!resolvedProvideMap) return Promise.resolve(); - return Promise.all( - Array.from( - resolvedProvideMap, - ([resource, { config, version }]) => - new Promise((resolve, reject) => { - compilation.addInclude( - compiler.context, - new ProvideSharedDependency( - config.shareScope, - config.shareKey, - version || false, - resource, - config.eager - ), - { - name: undefined - }, - err => { - if (err) return reject(err); - resolve(); - } - ); - }) - ) - ).then(() => {}); - }); + } + } - compiler.hooks.compilation.tap( - "ProvideSharedPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - ProvideForSharedDependency, - normalModuleFactory - ); + blockPreWalkClassDeclaration(statement) { + if (statement.id) { + this.defineVariable(statement.id.name); + } + } - compilation.dependencyFactories.set( - ProvideSharedDependency, - new ProvideSharedModuleFactory() - ); - } - ); + walkClassDeclaration(statement) { + this.walkClass(statement); } -} -module.exports = ProvideSharedPlugin; + preWalkSwitchCases(switchCases) { + for (let index = 0, len = switchCases.length; index < len; index++) { + const switchCase = switchCases[index]; + this.preWalkStatements(switchCase.consequent); + } + } + walkSwitchCases(switchCases) { + this.inBlockScope(() => { + const len = switchCases.length; -/***/ }), + // we need to pre walk all statements first since we can have invalid code + // import A from "module"; + // switch(1) { + // case 1: + // console.log(A); // should fail at runtime + // case 2: + // const A = 1; + // } + for (let index = 0; index < len; index++) { + const switchCase = switchCases[index]; -/***/ 26335: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (switchCase.consequent.length > 0) { + const prev = this.prevStatement; + this.blockPreWalkStatements(switchCase.consequent); + this.prevStatement = prev; + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy -*/ + for (let index = 0; index < len; index++) { + const switchCase = switchCases[index]; + if (switchCase.test) { + this.walkExpression(switchCase.test); + } + if (switchCase.consequent.length > 0) { + this.walkStatements(switchCase.consequent); + } + } + }); + } + preWalkCatchClause(catchClause) { + this.preWalkStatement(catchClause.body); + } -const { parseOptions } = __webpack_require__(3083); -const ConsumeSharedPlugin = __webpack_require__(15046); -const ProvideSharedPlugin = __webpack_require__(31225); -const { isRequiredVersion } = __webpack_require__(84379); + walkCatchClause(catchClause) { + this.inBlockScope(() => { + // Error binding is optional in catch clause since ECMAScript 2019 + if (catchClause.param !== null) { + this.enterPattern(catchClause.param, ident => { + this.defineVariable(ident); + }); + this.walkPattern(catchClause.param); + } + const prev = this.prevStatement; + this.blockPreWalkStatement(catchClause.body); + this.prevStatement = prev; + this.walkStatement(catchClause.body); + }); + } -/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumeSharedPluginOptions} ConsumeSharedPluginOptions */ -/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumesConfig} ConsumesConfig */ -/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvideSharedPluginOptions} ProvideSharedPluginOptions */ -/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvidesConfig} ProvidesConfig */ -/** @typedef {import("../../declarations/plugins/sharing/SharePlugin").SharePluginOptions} SharePluginOptions */ -/** @typedef {import("../../declarations/plugins/sharing/SharePlugin").SharedConfig} SharedConfig */ -/** @typedef {import("../Compiler")} Compiler */ + walkPattern(pattern) { + switch (pattern.type) { + case "ArrayPattern": + this.walkArrayPattern(pattern); + break; + case "AssignmentPattern": + this.walkAssignmentPattern(pattern); + break; + case "MemberExpression": + this.walkMemberExpression(pattern); + break; + case "ObjectPattern": + this.walkObjectPattern(pattern); + break; + case "RestElement": + this.walkRestElement(pattern); + break; + } + } -class SharePlugin { - /** - * @param {SharePluginOptions} options options - */ - constructor(options) { - /** @type {[string, SharedConfig][]} */ - const sharedOptions = parseOptions( - options.shared, - (item, key) => { - if (typeof item !== "string") - throw new Error("Unexpected array in shared"); - /** @type {SharedConfig} */ - const config = - item === key || !isRequiredVersion(item) - ? { - import: item - } - : { - import: key, - requiredVersion: item - }; - return config; - }, - item => item - ); - /** @type {Record[]} */ - const consumes = sharedOptions.map(([key, options]) => ({ - [key]: { - import: options.import, - shareKey: options.shareKey || key, - shareScope: options.shareScope, - requiredVersion: options.requiredVersion, - strictVersion: options.strictVersion, - singleton: options.singleton, - packageName: options.packageName, - eager: options.eager + walkAssignmentPattern(pattern) { + this.walkExpression(pattern.right); + this.walkPattern(pattern.left); + } + + walkObjectPattern(pattern) { + for (let i = 0, len = pattern.properties.length; i < len; i++) { + const prop = pattern.properties[i]; + if (prop) { + if (prop.computed) this.walkExpression(prop.key); + if (prop.value) this.walkPattern(prop.value); } - })); - /** @type {Record[]} */ - const provides = sharedOptions - .filter(([, options]) => options.import !== false) - .map(([key, options]) => ({ - [options.import || key]: { - shareKey: options.shareKey || key, - shareScope: options.shareScope, - version: options.version, - eager: options.eager - } - })); - this._shareScope = options.shareScope; - this._consumes = consumes; - this._provides = provides; + } } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - new ConsumeSharedPlugin({ - shareScope: this._shareScope, - consumes: this._consumes - }).apply(compiler); - new ProvideSharedPlugin({ - shareScope: this._shareScope, - provides: this._provides - }).apply(compiler); + walkArrayPattern(pattern) { + for (let i = 0, len = pattern.elements.length; i < len; i++) { + const element = pattern.elements[i]; + if (element) this.walkPattern(element); + } } -} -module.exports = SharePlugin; + walkRestElement(pattern) { + this.walkPattern(pattern.argument); + } + walkExpressions(expressions) { + for (const expression of expressions) { + if (expression) { + this.walkExpression(expression); + } + } + } -/***/ }), + walkExpression(expression) { + switch (expression.type) { + case "ArrayExpression": + this.walkArrayExpression(expression); + break; + case "ArrowFunctionExpression": + this.walkArrowFunctionExpression(expression); + break; + case "AssignmentExpression": + this.walkAssignmentExpression(expression); + break; + case "AwaitExpression": + this.walkAwaitExpression(expression); + break; + case "BinaryExpression": + this.walkBinaryExpression(expression); + break; + case "CallExpression": + this.walkCallExpression(expression); + break; + case "ChainExpression": + this.walkChainExpression(expression); + break; + case "ClassExpression": + this.walkClassExpression(expression); + break; + case "ConditionalExpression": + this.walkConditionalExpression(expression); + break; + case "FunctionExpression": + this.walkFunctionExpression(expression); + break; + case "Identifier": + this.walkIdentifier(expression); + break; + case "ImportExpression": + this.walkImportExpression(expression); + break; + case "LogicalExpression": + this.walkLogicalExpression(expression); + break; + case "MetaProperty": + this.walkMetaProperty(expression); + break; + case "MemberExpression": + this.walkMemberExpression(expression); + break; + case "NewExpression": + this.walkNewExpression(expression); + break; + case "ObjectExpression": + this.walkObjectExpression(expression); + break; + case "SequenceExpression": + this.walkSequenceExpression(expression); + break; + case "SpreadElement": + this.walkSpreadElement(expression); + break; + case "TaggedTemplateExpression": + this.walkTaggedTemplateExpression(expression); + break; + case "TemplateLiteral": + this.walkTemplateLiteral(expression); + break; + case "ThisExpression": + this.walkThisExpression(expression); + break; + case "UnaryExpression": + this.walkUnaryExpression(expression); + break; + case "UpdateExpression": + this.walkUpdateExpression(expression); + break; + case "YieldExpression": + this.walkYieldExpression(expression); + break; + } + } -/***/ 96066: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + walkAwaitExpression(expression) { + if (this.scope.topLevelScope === true) + this.hooks.topLevelAwait.call(expression); + this.walkExpression(expression.argument); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + walkArrayExpression(expression) { + if (expression.elements) { + this.walkExpressions(expression.elements); + } + } + walkSpreadElement(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } + } + walkObjectExpression(expression) { + for ( + let propIndex = 0, len = expression.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = expression.properties[propIndex]; + this.walkProperty(prop); + } + } -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); -const { - compareModulesByIdentifier, - compareStrings -} = __webpack_require__(29579); + walkProperty(prop) { + if (prop.type === "SpreadElement") { + this.walkExpression(prop.argument); + return; + } + if (prop.computed) { + this.walkExpression(prop.key); + } + if (prop.shorthand && prop.value && prop.value.type === "Identifier") { + this.scope.inShorthand = prop.value.name; + this.walkIdentifier(prop.value); + this.scope.inShorthand = false; + } else { + this.walkExpression(prop.value); + } + } -class ShareRuntimeModule extends RuntimeModule { - constructor() { - super("sharing"); + walkFunctionExpression(expression) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + const scopeParams = expression.params; + + // Add function name in scope for recursive calls + if (expression.id) { + scopeParams.push(expression.id.name); + } + + this.inFunctionScope(true, scopeParams, () => { + for (const param of expression.params) { + this.walkPattern(param); + } + if (expression.body.type === "BlockStatement") { + this.detectMode(expression.body.body); + const prev = this.prevStatement; + this.preWalkStatement(expression.body); + this.prevStatement = prev; + this.walkStatement(expression.body); + } else { + this.walkExpression(expression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } + + walkArrowFunctionExpression(expression) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = wasTopLevel ? "arrow" : false; + this.inFunctionScope(false, expression.params, () => { + for (const param of expression.params) { + this.walkPattern(param); + } + if (expression.body.type === "BlockStatement") { + this.detectMode(expression.body.body); + const prev = this.prevStatement; + this.preWalkStatement(expression.body); + this.prevStatement = prev; + this.walkStatement(expression.body); + } else { + this.walkExpression(expression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; } /** - * @returns {string} runtime code + * @param {SequenceExpressionNode} expression the sequence */ - generate() { - const { compilation, chunkGraph } = this; - const { - runtimeTemplate, - codeGenerationResults, - outputOptions: { uniqueName } - } = compilation; - /** @type {Map>>} */ - const initCodePerScope = new Map(); - for (const chunk of this.chunk.getAllReferencedChunks()) { - const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( - chunk, - "share-init", - compareModulesByIdentifier + walkSequenceExpression(expression) { + if (!expression.expressions) return; + // We treat sequence expressions like statements when they are one statement level + // This has some benefits for optimizations that only work on statement level + const currentStatement = this.statementPath[this.statementPath.length - 1]; + if ( + currentStatement === expression || + (currentStatement.type === "ExpressionStatement" && + currentStatement.expression === expression) + ) { + const old = this.statementPath.pop(); + for (const expr of expression.expressions) { + this.statementPath.push(expr); + this.walkExpression(expr); + this.statementPath.pop(); + } + this.statementPath.push(old); + } else { + this.walkExpressions(expression.expressions); + } + } + + walkUpdateExpression(expression) { + this.walkExpression(expression.argument); + } + + walkUnaryExpression(expression) { + if (expression.operator === "typeof") { + const result = this.callHooksForExpression( + this.hooks.typeof, + expression.argument, + expression ); - if (!modules) continue; - for (const m of modules) { - const data = codeGenerationResults.getData( - m, - chunk.runtime, - "share-init" + if (result === true) return; + if (expression.argument.type === "ChainExpression") { + const result = this.callHooksForExpression( + this.hooks.typeof, + expression.argument.expression, + expression ); - if (!data) continue; - for (const item of data) { - const { shareScope, initStage, init } = item; - let stages = initCodePerScope.get(shareScope); - if (stages === undefined) { - initCodePerScope.set(shareScope, (stages = new Map())); - } - let list = stages.get(initStage || 0); - if (list === undefined) { - stages.set(initStage || 0, (list = new Set())); - } - list.add(init); - } + if (result === true) return; } } - return Template.asString([ - `${RuntimeGlobals.shareScopeMap} = {};`, - "var initPromises = {};", - "var initTokens = {};", - `${RuntimeGlobals.initializeSharing} = ${runtimeTemplate.basicFunction( - "name, initScope", - [ - "if(!initScope) initScope = [];", - "// handling circular init calls", - "var initToken = initTokens[name];", - "if(!initToken) initToken = initTokens[name] = {};", - "if(initScope.indexOf(initToken) >= 0) return;", - "initScope.push(initToken);", - "// only runs once", - "if(initPromises[name]) return initPromises[name];", - "// creates a new share scope if needed", - `if(!${RuntimeGlobals.hasOwnProperty}(${RuntimeGlobals.shareScopeMap}, name)) ${RuntimeGlobals.shareScopeMap}[name] = {};`, - "// runs all init snippets from all modules reachable", - `var scope = ${RuntimeGlobals.shareScopeMap}[name];`, - `var warn = ${runtimeTemplate.returningFunction( - 'typeof console !== "undefined" && console.warn && console.warn(msg)', - "msg" - )};`, - `var uniqueName = ${JSON.stringify(uniqueName || undefined)};`, - `var register = ${runtimeTemplate.basicFunction( - "name, version, factory, eager", - [ - "var versions = scope[name] = scope[name] || {};", - "var activeVersion = versions[version];", - "if(!activeVersion || (!activeVersion.loaded && (!eager != !activeVersion.eager ? eager : uniqueName > activeVersion.from))) versions[version] = { get: factory, from: uniqueName, eager: !!eager };" - ] - )};`, - `var initExternal = ${runtimeTemplate.basicFunction("id", [ - `var handleError = ${runtimeTemplate.expressionFunction( - 'warn("Initialization of sharing external failed: " + err)', - "err" - )};`, - "try {", - Template.indent([ - "var module = __webpack_require__(id);", - "if(!module) return;", - `var initFn = ${runtimeTemplate.returningFunction( - `module && module.init && module.init(${RuntimeGlobals.shareScopeMap}[name], initScope)`, - "module" - )}`, - "if(module.then) return promises.push(module.then(initFn, handleError));", - "var initResult = initFn(module);", - "if(initResult && initResult.then) return promises.push(initResult['catch'](handleError));" - ]), - "} catch(err) { handleError(err); }" - ])}`, - "var promises = [];", - "switch(name) {", - ...Array.from(initCodePerScope) - .sort(([a], [b]) => compareStrings(a, b)) - .map(([name, stages]) => - Template.indent([ - `case ${JSON.stringify(name)}: {`, - Template.indent( - Array.from(stages) - .sort(([a], [b]) => a - b) - .map(([, initCode]) => - Template.asString(Array.from(initCode)) - ) - ), - "}", - "break;" - ]) - ), - "}", - "if(!promises.length) return initPromises[name] = 1;", - `return initPromises[name] = Promise.all(promises).then(${runtimeTemplate.returningFunction( - "initPromises[name] = 1" - )});` - ] - )};` - ]); + this.walkExpression(expression.argument); } -} - -module.exports = ShareRuntimeModule; + walkLeftRightExpression(expression) { + this.walkExpression(expression.left); + this.walkExpression(expression.right); + } -/***/ }), + walkBinaryExpression(expression) { + this.walkLeftRightExpression(expression); + } -/***/ 3591: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + walkLogicalExpression(expression) { + const result = this.hooks.expressionLogicalOperator.call(expression); + if (result === undefined) { + this.walkLeftRightExpression(expression); + } else { + if (result) { + this.walkExpression(expression.right); + } + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + walkAssignmentExpression(expression) { + if (expression.left.type === "Identifier") { + const renameIdentifier = this.getRenameIdentifier(expression.right); + if (renameIdentifier) { + if ( + this.callHooksForInfo( + this.hooks.canRename, + renameIdentifier, + expression.right + ) + ) { + // renaming "a = b;" + if ( + !this.callHooksForInfo( + this.hooks.rename, + renameIdentifier, + expression.right + ) + ) { + this.setVariable( + expression.left.name, + this.getVariableInfo(renameIdentifier) + ); + } + return; + } + } + this.walkExpression(expression.right); + this.enterPattern(expression.left, (name, decl) => { + if (!this.callHooksForName(this.hooks.assign, name, expression)) { + this.walkExpression(expression.left); + } + }); + return; + } + if (expression.left.type.endsWith("Pattern")) { + this.walkExpression(expression.right); + this.enterPattern(expression.left, (name, decl) => { + if (!this.callHooksForName(this.hooks.assign, name, expression)) { + this.defineVariable(name); + } + }); + this.walkPattern(expression.left); + } else if (expression.left.type === "MemberExpression") { + const exprName = this.getMemberExpressionInfo( + expression.left, + ALLOWED_MEMBER_TYPES_EXPRESSION + ); + if (exprName) { + if ( + this.callHooksForInfo( + this.hooks.assignMemberChain, + exprName.rootInfo, + expression, + exprName.getMembers() + ) + ) { + return; + } + } + this.walkExpression(expression.right); + this.walkExpression(expression.left); + } else { + this.walkExpression(expression.right); + this.walkExpression(expression.left); + } + } + walkConditionalExpression(expression) { + const result = this.hooks.expressionConditionalOperator.call(expression); + if (result === undefined) { + this.walkExpression(expression.test); + this.walkExpression(expression.consequent); + if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } else { + if (result) { + this.walkExpression(expression.consequent); + } else if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } + } + walkNewExpression(expression) { + const result = this.callHooksForExpression( + this.hooks.new, + expression.callee, + expression + ); + if (result === true) return; + this.walkExpression(expression.callee); + if (expression.arguments) { + this.walkExpressions(expression.arguments); + } + } -const ModuleNotFoundError = __webpack_require__(32882); -const LazySet = __webpack_require__(38938); + walkYieldExpression(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } + } -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */ + walkTemplateLiteral(expression) { + if (expression.expressions) { + this.walkExpressions(expression.expressions); + } + } -/** - * @template T - * @typedef {Object} MatchedConfigs - * @property {Map} resolved - * @property {Map} unresolved - * @property {Map} prefixed - */ + walkTaggedTemplateExpression(expression) { + if (expression.tag) { + this.walkExpression(expression.tag); + } + if (expression.quasi && expression.quasi.expressions) { + this.walkExpressions(expression.quasi.expressions); + } + } -/** @type {ResolveOptionsWithDependencyType} */ -const RESOLVE_OPTIONS = { dependencyType: "esm" }; + walkClassExpression(expression) { + this.walkClass(expression); + } -/** - * @template T - * @param {Compilation} compilation the compilation - * @param {[string, T][]} configs to be processed configs - * @returns {Promise>} resolved matchers - */ -exports.resolveMatchedConfigs = (compilation, configs) => { - /** @type {Map} */ - const resolved = new Map(); - /** @type {Map} */ - const unresolved = new Map(); - /** @type {Map} */ - const prefixed = new Map(); - const resolveContext = { - /** @type {LazySet} */ - fileDependencies: new LazySet(), - /** @type {LazySet} */ - contextDependencies: new LazySet(), - /** @type {LazySet} */ - missingDependencies: new LazySet() - }; - const resolver = compilation.resolverFactory.get("normal", RESOLVE_OPTIONS); - const context = compilation.compiler.context; + /** + * @param {ChainExpressionNode} expression expression + */ + walkChainExpression(expression) { + const result = this.hooks.optionalChaining.call(expression); - return Promise.all( - configs.map(([request, config]) => { - if (/^\.\.?(\/|$)/.test(request)) { - // relative request - return new Promise(resolve => { - resolver.resolve( - {}, - context, - request, - resolveContext, - (err, result) => { - if (err || result === false) { - err = err || new Error(`Can't resolve ${request}`); - compilation.errors.push( - new ModuleNotFoundError(null, err, { - name: `shared module ${request}` - }) - ); - return resolve(); - } - resolved.set(result, config); - resolve(); - } - ); - }); - } else if (/^(\/|[A-Za-z]:\\|\\\\)/.test(request)) { - // absolute path - resolved.set(request, config); - } else if (request.endsWith("/")) { - // module request prefix - prefixed.set(request, config); + if (result === undefined) { + if (expression.expression.type === "CallExpression") { + this.walkCallExpression(expression.expression); } else { - // module request - unresolved.set(request, config); + this.walkMemberExpression(expression.expression); } - }) - ).then(() => { - compilation.contextDependencies.addAll(resolveContext.contextDependencies); - compilation.fileDependencies.addAll(resolveContext.fileDependencies); - compilation.missingDependencies.addAll(resolveContext.missingDependencies); - return { resolved, unresolved, prefixed }; - }); -}; - - -/***/ }), - -/***/ 84379: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + } + } + _walkIIFE(functionExpression, options, currentThis) { + const getVarInfo = argOrThis => { + const renameIdentifier = this.getRenameIdentifier(argOrThis); + if (renameIdentifier) { + if ( + this.callHooksForInfo( + this.hooks.canRename, + renameIdentifier, + argOrThis + ) + ) { + if ( + !this.callHooksForInfo( + this.hooks.rename, + renameIdentifier, + argOrThis + ) + ) { + return this.getVariableInfo(renameIdentifier); + } + } + } + this.walkExpression(argOrThis); + }; + const { params, type } = functionExpression; + const arrow = type === "ArrowFunctionExpression"; + const renameThis = currentThis ? getVarInfo(currentThis) : null; + const varInfoForArgs = options.map(getVarInfo); + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = wasTopLevel && arrow ? "arrow" : false; + const scopeParams = params.filter( + (identifier, idx) => !varInfoForArgs[idx] + ); + // Add function name in scope for recursive calls + if (functionExpression.id) { + scopeParams.push(functionExpression.id.name); + } -const { join, dirname, readJson } = __webpack_require__(17139); + this.inFunctionScope(true, scopeParams, () => { + if (renameThis && !arrow) { + this.setVariable("this", renameThis); + } + for (let i = 0; i < varInfoForArgs.length; i++) { + const varInfo = varInfoForArgs[i]; + if (!varInfo) continue; + if (!params[i] || params[i].type !== "Identifier") continue; + this.setVariable(params[i].name, varInfo); + } + if (functionExpression.body.type === "BlockStatement") { + this.detectMode(functionExpression.body.body); + const prev = this.prevStatement; + this.preWalkStatement(functionExpression.body); + this.prevStatement = prev; + this.walkStatement(functionExpression.body); + } else { + this.walkExpression(functionExpression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ + walkImportExpression(expression) { + let result = this.hooks.importCall.call(expression); + if (result === true) return; -/** - * @param {string} str maybe required version - * @returns {boolean} true, if it looks like a version - */ -exports.isRequiredVersion = str => { - return /^([\d^=v<>~]|[*xX]$)/.test(str); -}; + this.walkExpression(expression.source); + } -/** - * - * @param {InputFileSystem} fs file system - * @param {string} directory directory to start looking into - * @param {string[]} descriptionFiles possible description filenames - * @param {function((Error | null)=, {data: object, path: string}=): void} callback callback - */ -const getDescriptionFile = (fs, directory, descriptionFiles, callback) => { - let i = 0; - const tryLoadCurrent = () => { - if (i >= descriptionFiles.length) { - const parentDirectory = dirname(fs, directory); - if (!parentDirectory || parentDirectory === directory) return callback(); - return getDescriptionFile( - fs, - parentDirectory, - descriptionFiles, - callback + walkCallExpression(expression) { + const isSimpleFunction = fn => { + return fn.params.every(p => p.type === "Identifier"); + }; + if ( + expression.callee.type === "MemberExpression" && + expression.callee.object.type.endsWith("FunctionExpression") && + !expression.callee.computed && + (expression.callee.property.name === "call" || + expression.callee.property.name === "bind") && + expression.arguments.length > 0 && + isSimpleFunction(expression.callee.object) + ) { + // (function(…) { }.call/bind(?, …)) + this._walkIIFE( + expression.callee.object, + expression.arguments.slice(1), + expression.arguments[0] ); - } - const filePath = join(fs, directory, descriptionFiles[i]); - readJson(fs, filePath, (err, data) => { - if (err) { - if ("code" in err && err.code === "ENOENT") { - i++; - return tryLoadCurrent(); + } else if ( + expression.callee.type.endsWith("FunctionExpression") && + isSimpleFunction(expression.callee) + ) { + // (function(…) { }(…)) + this._walkIIFE(expression.callee, expression.arguments, null); + } else { + if (expression.callee.type === "MemberExpression") { + const exprInfo = this.getMemberExpressionInfo( + expression.callee, + ALLOWED_MEMBER_TYPES_CALL_EXPRESSION + ); + if (exprInfo && exprInfo.type === "call") { + const result = this.callHooksForInfo( + this.hooks.callMemberChainOfCallMemberChain, + exprInfo.rootInfo, + expression, + exprInfo.getCalleeMembers(), + exprInfo.call, + exprInfo.getMembers() + ); + if (result === true) return; } - return callback(err); } - if (!data || typeof data !== "object" || Array.isArray(data)) { - return callback( - new Error(`Description file ${filePath} is not an object`) + const callee = this.evaluateExpression(expression.callee); + if (callee.isIdentifier()) { + const result1 = this.callHooksForInfo( + this.hooks.callMemberChain, + callee.rootInfo, + expression, + callee.getMembers() + ); + if (result1 === true) return; + const result2 = this.callHooksForInfo( + this.hooks.call, + callee.identifier, + expression ); + if (result2 === true) return; } - callback(null, { data, path: filePath }); - }); - }; - tryLoadCurrent(); -}; -exports.getDescriptionFile = getDescriptionFile; -exports.getRequiredVersionFromDescriptionFile = (data, packageName) => { - if ( - data.optionalDependencies && - typeof data.optionalDependencies === "object" && - packageName in data.optionalDependencies - ) { - return data.optionalDependencies[packageName]; + if (expression.callee) { + if (expression.callee.type === "MemberExpression") { + // because of call context we need to walk the call context as expression + this.walkExpression(expression.callee.object); + if (expression.callee.computed === true) + this.walkExpression(expression.callee.property); + } else { + this.walkExpression(expression.callee); + } + } + if (expression.arguments) this.walkExpressions(expression.arguments); + } } - if ( - data.dependencies && - typeof data.dependencies === "object" && - packageName in data.dependencies - ) { - return data.dependencies[packageName]; + + walkMemberExpression(expression) { + const exprInfo = this.getMemberExpressionInfo( + expression, + ALLOWED_MEMBER_TYPES_ALL + ); + if (exprInfo) { + switch (exprInfo.type) { + case "expression": { + const result1 = this.callHooksForInfo( + this.hooks.expression, + exprInfo.name, + expression + ); + if (result1 === true) return; + const members = exprInfo.getMembers(); + const result2 = this.callHooksForInfo( + this.hooks.expressionMemberChain, + exprInfo.rootInfo, + expression, + members + ); + if (result2 === true) return; + this.walkMemberExpressionWithExpressionName( + expression, + exprInfo.name, + exprInfo.rootInfo, + members.slice(), + () => + this.callHooksForInfo( + this.hooks.unhandledExpressionMemberChain, + exprInfo.rootInfo, + expression, + members + ) + ); + return; + } + case "call": { + const result = this.callHooksForInfo( + this.hooks.memberChainOfCallMemberChain, + exprInfo.rootInfo, + expression, + exprInfo.getCalleeMembers(), + exprInfo.call, + exprInfo.getMembers() + ); + if (result === true) return; + // Fast skip over the member chain as we already called memberChainOfCallMemberChain + // and call computed property are literals anyway + this.walkExpression(exprInfo.call); + return; + } + } + } + this.walkExpression(expression.object); + if (expression.computed === true) this.walkExpression(expression.property); } - if ( - data.peerDependencies && - typeof data.peerDependencies === "object" && - packageName in data.peerDependencies + + walkMemberExpressionWithExpressionName( + expression, + name, + rootInfo, + members, + onUnhandled ) { - return data.peerDependencies[packageName]; + if (expression.object.type === "MemberExpression") { + // optimize the case where expression.object is a MemberExpression too. + // we can keep info here when calling walkMemberExpression directly + const property = + expression.property.name || `${expression.property.value}`; + name = name.slice(0, -property.length - 1); + members.pop(); + const result = this.callHooksForInfo( + this.hooks.expression, + name, + expression.object + ); + if (result === true) return; + this.walkMemberExpressionWithExpressionName( + expression.object, + name, + rootInfo, + members, + onUnhandled + ); + } else if (!onUnhandled || !onUnhandled()) { + this.walkExpression(expression.object); + } + if (expression.computed === true) this.walkExpression(expression.property); } - if ( - data.devDependencies && - typeof data.devDependencies === "object" && - packageName in data.devDependencies + + walkThisExpression(expression) { + this.callHooksForName(this.hooks.expression, "this", expression); + } + + walkIdentifier(expression) { + this.callHooksForName(this.hooks.expression, expression.name, expression); + } + + /** + * @param {MetaPropertyNode} metaProperty meta property + */ + walkMetaProperty(metaProperty) { + this.hooks.expression.for(getRootName(metaProperty)).call(metaProperty); + } + + callHooksForExpression(hookMap, expr, ...args) { + return this.callHooksForExpressionWithFallback( + hookMap, + expr, + undefined, + undefined, + ...args + ); + } + + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {MemberExpressionNode} expr expression info + * @param {function(string, string | ScopeInfo | VariableInfo, function(): string[]): any} fallback callback when variable in not handled by hooks + * @param {function(string): any} defined callback when variable is defined + * @param {AsArray} args args for the hook + * @returns {R} result of hook + */ + callHooksForExpressionWithFallback( + hookMap, + expr, + fallback, + defined, + ...args ) { - return data.devDependencies[packageName]; + const exprName = this.getMemberExpressionInfo( + expr, + ALLOWED_MEMBER_TYPES_EXPRESSION + ); + if (exprName !== undefined) { + const members = exprName.getMembers(); + return this.callHooksForInfoWithFallback( + hookMap, + members.length === 0 ? exprName.rootInfo : exprName.name, + fallback && + (name => fallback(name, exprName.rootInfo, exprName.getMembers)), + defined && (() => defined(exprName.name)), + ...args + ); + } } -}; + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {string} name key in map + * @param {AsArray} args args for the hook + * @returns {R} result of hook + */ + callHooksForName(hookMap, name, ...args) { + return this.callHooksForNameWithFallback( + hookMap, + name, + undefined, + undefined, + ...args + ); + } -/***/ }), + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks that should be called + * @param {ExportedVariableInfo} info variable info + * @param {AsArray} args args for the hook + * @returns {R} result of hook + */ + callHooksForInfo(hookMap, info, ...args) { + return this.callHooksForInfoWithFallback( + hookMap, + info, + undefined, + undefined, + ...args + ); + } -/***/ 71760: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {ExportedVariableInfo} info variable info + * @param {function(string): any} fallback callback when variable in not handled by hooks + * @param {function(): any} defined callback when variable is defined + * @param {AsArray} args args for the hook + * @returns {R} result of hook + */ + callHooksForInfoWithFallback(hookMap, info, fallback, defined, ...args) { + let name; + if (typeof info === "string") { + name = info; + } else { + if (!(info instanceof VariableInfo)) { + if (defined !== undefined) { + return defined(); + } + return; + } + let tagInfo = info.tagInfo; + while (tagInfo !== undefined) { + const hook = hookMap.get(tagInfo.tag); + if (hook !== undefined) { + this.currentTagData = tagInfo.data; + const result = hook.call(...args); + this.currentTagData = undefined; + if (result !== undefined) return result; + } + tagInfo = tagInfo.next; + } + if (info.freeName === true) { + if (defined !== undefined) { + return defined(); + } + return; + } + name = info.freeName; + } + const hook = hookMap.get(name); + if (hook !== undefined) { + const result = hook.call(...args); + if (result !== undefined) return result; + } + if (fallback !== undefined) { + return fallback(name); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {string} name key in map + * @param {function(string): any} fallback callback when variable in not handled by hooks + * @param {function(): any} defined callback when variable is defined + * @param {AsArray} args args for the hook + * @returns {R} result of hook + */ + callHooksForNameWithFallback(hookMap, name, fallback, defined, ...args) { + return this.callHooksForInfoWithFallback( + hookMap, + this.getVariableInfo(name), + fallback, + defined, + ...args + ); + } + /** + * @deprecated + * @param {any} params scope params + * @param {function(): void} fn inner function + * @returns {void} + */ + inScope(params, fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: false, + inShorthand: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + definitions: oldScope.definitions.createChild() + }; + this.undefineVariable("this"); -const util = __webpack_require__(73837); -const ModuleDependency = __webpack_require__(80321); -const formatLocation = __webpack_require__(16734); -const { LogType } = __webpack_require__(32597); -const AggressiveSplittingPlugin = __webpack_require__(15543); -const SizeLimitsPlugin = __webpack_require__(32557); -const { countIterable } = __webpack_require__(39104); -const { - compareLocations, - compareChunksById, - compareNumbers, - compareIds, - concatComparators, - compareSelect, - compareModulesByIdentifier -} = __webpack_require__(29579); -const { makePathsRelative, parseResource } = __webpack_require__(82186); + this.enterPatterns(params, (ident, pattern) => { + this.defineVariable(ident); + }); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../ChunkGroup").OriginRecord} OriginRecord */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compilation").Asset} Asset */ -/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("../Compilation").NormalizedStatsOptions} NormalizedStatsOptions */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleProfile")} ModuleProfile */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @template T @typedef {import("../util/comparators").Comparator} Comparator */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -/** @typedef {import("../util/smartGrouping").GroupConfig} GroupConfig */ -/** @typedef {import("./StatsFactory")} StatsFactory */ -/** @typedef {import("./StatsFactory").StatsFactoryContext} StatsFactoryContext */ + fn(); -/** @typedef {KnownStatsCompilation & Record} StatsCompilation */ -/** - * @typedef {Object} KnownStatsCompilation - * @property {any=} env - * @property {string=} name - * @property {string=} hash - * @property {string=} version - * @property {number=} time - * @property {number=} builtAt - * @property {boolean=} needAdditionalPass - * @property {string=} publicPath - * @property {string=} outputPath - * @property {Record=} assetsByChunkName - * @property {StatsAsset[]=} assets - * @property {number=} filteredAssets - * @property {StatsChunk[]=} chunks - * @property {StatsModule[]=} modules - * @property {number=} filteredModules - * @property {Record=} entrypoints - * @property {Record=} namedChunkGroups - * @property {StatsError[]=} errors - * @property {number=} errorsCount - * @property {StatsError[]=} warnings - * @property {number=} warningsCount - * @property {StatsCompilation[]=} children - * @property {Record=} logging - */ + this.scope = oldScope; + } -/** @typedef {KnownStatsLogging & Record} StatsLogging */ -/** - * @typedef {Object} KnownStatsLogging - * @property {StatsLoggingEntry[]} entries - * @property {number} filteredEntries - * @property {boolean} debug - */ + inFunctionScope(hasThis, params, fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: false, + inShorthand: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + definitions: oldScope.definitions.createChild() + }; -/** @typedef {KnownStatsLoggingEntry & Record} StatsLoggingEntry */ -/** - * @typedef {Object} KnownStatsLoggingEntry - * @property {string} type - * @property {string} message - * @property {string[]=} trace - * @property {StatsLoggingEntry[]=} children - * @property {any[]=} args - * @property {number=} time - */ + if (hasThis) { + this.undefineVariable("this"); + } -/** @typedef {KnownStatsAsset & Record} StatsAsset */ -/** - * @typedef {Object} KnownStatsAsset - * @property {string} type - * @property {string} name - * @property {AssetInfo} info - * @property {number} size - * @property {boolean} emitted - * @property {boolean} comparedForEmit - * @property {boolean} cached - * @property {StatsAsset[]=} related - * @property {(string|number)[]=} chunkNames - * @property {(string|number)[]=} chunkIdHints - * @property {(string|number)[]=} chunks - * @property {(string|number)[]=} auxiliaryChunkNames - * @property {(string|number)[]=} auxiliaryChunks - * @property {(string|number)[]=} auxiliaryChunkIdHints - * @property {number=} filteredRelated - * @property {boolean=} isOverSizeLimit - */ + this.enterPatterns(params, (ident, pattern) => { + this.defineVariable(ident); + }); -/** @typedef {KnownStatsChunkGroup & Record} StatsChunkGroup */ -/** - * @typedef {Object} KnownStatsChunkGroup - * @property {string=} name - * @property {(string|number)[]=} chunks - * @property {({ name: string, size?: number })[]=} assets - * @property {number=} filteredAssets - * @property {number=} assetsSize - * @property {({ name: string, size?: number })[]=} auxiliaryAssets - * @property {number=} filteredAuxiliaryAssets - * @property {number=} auxiliaryAssetsSize - * @property {{ [x: string]: StatsChunkGroup[] }=} children - * @property {{ [x: string]: string[] }=} childAssets - * @property {boolean=} isOverSizeLimit - */ + fn(); -/** @typedef {KnownStatsModule & Record} StatsModule */ -/** - * @typedef {Object} KnownStatsModule - * @property {string=} type - * @property {string=} moduleType - * @property {string=} layer - * @property {string=} identifier - * @property {string=} name - * @property {string=} nameForCondition - * @property {number=} index - * @property {number=} preOrderIndex - * @property {number=} index2 - * @property {number=} postOrderIndex - * @property {number=} size - * @property {{[x: string]: number}=} sizes - * @property {boolean=} cacheable - * @property {boolean=} built - * @property {boolean=} codeGenerated - * @property {boolean=} buildTimeExecuted - * @property {boolean=} cached - * @property {boolean=} optional - * @property {boolean=} orphan - * @property {string|number=} id - * @property {string|number=} issuerId - * @property {(string|number)[]=} chunks - * @property {(string|number)[]=} assets - * @property {boolean=} dependent - * @property {string=} issuer - * @property {string=} issuerName - * @property {StatsModuleIssuer[]=} issuerPath - * @property {boolean=} failed - * @property {number=} errors - * @property {number=} warnings - * @property {StatsProfile=} profile - * @property {StatsModuleReason[]=} reasons - * @property {(boolean | string[])=} usedExports - * @property {string[]=} providedExports - * @property {string[]=} optimizationBailout - * @property {number=} depth - * @property {StatsModule[]=} modules - * @property {number=} filteredModules - * @property {ReturnType=} source - */ + this.scope = oldScope; + } -/** @typedef {KnownStatsProfile & Record} StatsProfile */ -/** - * @typedef {Object} KnownStatsProfile - * @property {number} total - * @property {number} resolving - * @property {number} restoring - * @property {number} building - * @property {number} integration - * @property {number} storing - * @property {number} additionalResolving - * @property {number} additionalIntegration - * @property {number} factory - * @property {number} dependencies - */ + inBlockScope(fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: oldScope.inTry, + inShorthand: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + definitions: oldScope.definitions.createChild() + }; -/** @typedef {KnownStatsModuleIssuer & Record} StatsModuleIssuer */ -/** - * @typedef {Object} KnownStatsModuleIssuer - * @property {string=} identifier - * @property {string=} name - * @property {(string|number)=} id - * @property {StatsProfile=} profile - */ + fn(); -/** @typedef {KnownStatsModuleReason & Record} StatsModuleReason */ -/** - * @typedef {Object} KnownStatsModuleReason - * @property {string=} moduleIdentifier - * @property {string=} module - * @property {string=} moduleName - * @property {string=} resolvedModuleIdentifier - * @property {string=} resolvedModule - * @property {string=} type - * @property {boolean} active - * @property {string=} explanation - * @property {string=} userRequest - * @property {string=} loc - * @property {(string|number)=} moduleId - * @property {(string|number)=} resolvedModuleId - */ + this.scope = oldScope; + } -/** @typedef {KnownStatsChunk & Record} StatsChunk */ -/** - * @typedef {Object} KnownStatsChunk - * @property {boolean} rendered - * @property {boolean} initial - * @property {boolean} entry - * @property {boolean} recorded - * @property {string=} reason - * @property {number} size - * @property {Record=} sizes - * @property {string[]=} names - * @property {string[]=} idHints - * @property {string[]=} runtime - * @property {string[]=} files - * @property {string[]=} auxiliaryFiles - * @property {string} hash - * @property {Record=} childrenByOrder - * @property {(string|number)=} id - * @property {(string|number)[]=} siblings - * @property {(string|number)[]=} parents - * @property {(string|number)[]=} children - * @property {StatsModule[]=} modules - * @property {number=} filteredModules - * @property {StatsChunkOrigin[]=} origins - */ + detectMode(statements) { + const isLiteral = + statements.length >= 1 && + statements[0].type === "ExpressionStatement" && + statements[0].expression.type === "Literal"; + if (isLiteral && statements[0].expression.value === "use strict") { + this.scope.isStrict = true; + } + if (isLiteral && statements[0].expression.value === "use asm") { + this.scope.isAsmJs = true; + } + } -/** @typedef {KnownStatsChunkOrigin & Record} StatsChunkOrigin */ -/** - * @typedef {Object} KnownStatsChunkOrigin - * @property {string=} module - * @property {string=} moduleIdentifier - * @property {string=} moduleName - * @property {string=} loc - * @property {string=} request - * @property {(string|number)=} moduleId - */ + enterPatterns(patterns, onIdent) { + for (const pattern of patterns) { + if (typeof pattern !== "string") { + this.enterPattern(pattern, onIdent); + } else if (pattern) { + onIdent(pattern); + } + } + } -/** @typedef {KnownStatsModuleTraceItem & Record} StatsModuleTraceItem */ -/** - * @typedef {Object} KnownStatsModuleTraceItem - * @property {string=} originIdentifier - * @property {string=} originName - * @property {string=} moduleIdentifier - * @property {string=} moduleName - * @property {StatsModuleTraceDependency[]=} dependencies - * @property {(string|number)=} originId - * @property {(string|number)=} moduleId - */ + enterPattern(pattern, onIdent) { + if (!pattern) return; + switch (pattern.type) { + case "ArrayPattern": + this.enterArrayPattern(pattern, onIdent); + break; + case "AssignmentPattern": + this.enterAssignmentPattern(pattern, onIdent); + break; + case "Identifier": + this.enterIdentifier(pattern, onIdent); + break; + case "ObjectPattern": + this.enterObjectPattern(pattern, onIdent); + break; + case "RestElement": + this.enterRestElement(pattern, onIdent); + break; + case "Property": + if (pattern.shorthand && pattern.value.type === "Identifier") { + this.scope.inShorthand = pattern.value.name; + this.enterIdentifier(pattern.value, onIdent); + this.scope.inShorthand = false; + } else { + this.enterPattern(pattern.value, onIdent); + } + break; + } + } -/** @typedef {KnownStatsModuleTraceDependency & Record} StatsModuleTraceDependency */ -/** - * @typedef {Object} KnownStatsModuleTraceDependency - * @property {string=} loc - */ + enterIdentifier(pattern, onIdent) { + if (!this.callHooksForName(this.hooks.pattern, pattern.name, pattern)) { + onIdent(pattern.name, pattern); + } + } -/** @typedef {KnownStatsError & Record} StatsError */ -/** - * @typedef {Object} KnownStatsError - * @property {string} message - * @property {string=} chunkName - * @property {boolean=} chunkEntry - * @property {boolean=} chunkInitial - * @property {string=} file - * @property {string=} moduleIdentifier - * @property {string=} moduleName - * @property {string=} loc - * @property {string|number=} chunkId - * @property {string|number=} moduleId - * @property {StatsModuleTraceItem[]=} moduleTrace - * @property {any=} details - * @property {string=} stack - */ + enterObjectPattern(pattern, onIdent) { + for ( + let propIndex = 0, len = pattern.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = pattern.properties[propIndex]; + this.enterPattern(prop, onIdent); + } + } -/** @typedef {Asset & { type: string, related: PreprocessedAsset[] }} PreprocessedAsset */ + enterArrayPattern(pattern, onIdent) { + for ( + let elementIndex = 0, len = pattern.elements.length; + elementIndex < len; + elementIndex++ + ) { + const element = pattern.elements[elementIndex]; + this.enterPattern(element, onIdent); + } + } -/** - * @template T - * @template O - * @typedef {Record void>} ExtractorsByOption - */ + enterRestElement(pattern, onIdent) { + this.enterPattern(pattern.argument, onIdent); + } -/** - * @typedef {Object} SimpleExtractors - * @property {ExtractorsByOption} compilation - * @property {ExtractorsByOption} asset - * @property {ExtractorsByOption} asset$visible - * @property {ExtractorsByOption<{ name: string, chunkGroup: ChunkGroup }, StatsChunkGroup>} chunkGroup - * @property {ExtractorsByOption} module - * @property {ExtractorsByOption} module$visible - * @property {ExtractorsByOption} moduleIssuer - * @property {ExtractorsByOption} profile - * @property {ExtractorsByOption} moduleReason - * @property {ExtractorsByOption} chunk - * @property {ExtractorsByOption} chunkOrigin - * @property {ExtractorsByOption} error - * @property {ExtractorsByOption} warning - * @property {ExtractorsByOption<{ origin: Module, module: Module }, StatsModuleTraceItem>} moduleTraceItem - * @property {ExtractorsByOption} moduleTraceDependency - */ + enterAssignmentPattern(pattern, onIdent) { + this.enterPattern(pattern.left, onIdent); + } -/** - * @template T - * @template I - * @param {Iterable} items items to select from - * @param {function(T): Iterable} selector selector function to select values from item - * @returns {I[]} array of values - */ -const uniqueArray = (items, selector) => { - /** @type {Set} */ - const set = new Set(); - for (const item of items) { - for (const i of selector(item)) { - set.add(i); + /** + * @param {ExpressionNode} expression expression node + * @returns {BasicEvaluatedExpression | undefined} evaluation result + */ + evaluateExpression(expression) { + try { + const hook = this.hooks.evaluate.get(expression.type); + if (hook !== undefined) { + const result = hook.call(expression); + if (result !== undefined) { + if (result) { + result.setExpression(expression); + } + return result; + } + } + } catch (e) { + console.warn(e); + // ignore error } + return new BasicEvaluatedExpression() + .setRange(expression.range) + .setExpression(expression); } - return Array.from(set); -}; -/** - * @template T - * @template I - * @param {Iterable} items items to select from - * @param {function(T): Iterable} selector selector function to select values from item - * @param {Comparator} comparator comparator function - * @returns {I[]} array of values - */ -const uniqueOrderedArray = (items, selector, comparator) => { - return uniqueArray(items, selector).sort(comparator); -}; + parseString(expression) { + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + return ( + this.parseString(expression.left) + + this.parseString(expression.right) + ); + } + break; + case "Literal": + return expression.value + ""; + } + throw new Error( + expression.type + " is not supported as parameter for require" + ); + } -/** @template T @template R @typedef {{ [P in keyof T]: R }} MappedValues */ + parseCalculatedString(expression) { + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + const left = this.parseCalculatedString(expression.left); + const right = this.parseCalculatedString(expression.right); + if (left.code) { + return { + range: left.range, + value: left.value, + code: true, + conditional: false + }; + } else if (right.code) { + return { + range: [ + left.range[0], + right.range ? right.range[1] : left.range[1] + ], + value: left.value + right.value, + code: true, + conditional: false + }; + } else { + return { + range: [left.range[0], right.range[1]], + value: left.value + right.value, + code: false, + conditional: false + }; + } + } + break; + case "ConditionalExpression": { + const consequent = this.parseCalculatedString(expression.consequent); + const alternate = this.parseCalculatedString(expression.alternate); + const items = []; + if (consequent.conditional) { + items.push(...consequent.conditional); + } else if (!consequent.code) { + items.push(consequent); + } else { + break; + } + if (alternate.conditional) { + items.push(...alternate.conditional); + } else if (!alternate.code) { + items.push(alternate); + } else { + break; + } + return { + range: undefined, + value: "", + code: true, + conditional: items + }; + } + case "Literal": + return { + range: expression.range, + value: expression.value + "", + code: false, + conditional: false + }; + } + return { + range: undefined, + value: "", + code: true, + conditional: false + }; + } -/** - * @template T - * @template R - * @param {T} obj object to be mapped - * @param {function(T[keyof T], keyof T): R} fn mapping function - * @returns {MappedValues} mapped object - */ -const mapObject = (obj, fn) => { - const newObj = Object.create(null); - for (const key of Object.keys(obj)) { - newObj[key] = fn(obj[key], /** @type {keyof T} */ (key)); + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + let ast; + let comments; + const semicolons = new Set(); + if (source === null) { + throw new Error("source must not be null"); + } + if (Buffer.isBuffer(source)) { + source = source.toString("utf-8"); + } + if (typeof source === "object") { + ast = /** @type {ProgramNode} */ (source); + comments = source.comments; + } else { + comments = []; + ast = JavascriptParser._parse(source, { + sourceType: this.sourceType, + onComment: comments, + onInsertedSemicolon: pos => semicolons.add(pos) + }); + } + + const oldScope = this.scope; + const oldState = this.state; + const oldComments = this.comments; + const oldSemicolons = this.semicolons; + const oldStatementPath = this.statementPath; + const oldPrevStatement = this.prevStatement; + this.scope = { + topLevelScope: true, + inTry: false, + inShorthand: false, + isStrict: false, + isAsmJs: false, + definitions: new StackedMap() + }; + /** @type {ParserState} */ + this.state = state; + this.comments = comments; + this.semicolons = semicolons; + this.statementPath = []; + this.prevStatement = undefined; + if (this.hooks.program.call(ast, comments) === undefined) { + this.detectMode(ast.body); + this.preWalkStatements(ast.body); + this.prevStatement = undefined; + this.blockPreWalkStatements(ast.body); + this.prevStatement = undefined; + this.walkStatements(ast.body); + } + this.hooks.finish.call(ast, comments); + this.scope = oldScope; + /** @type {ParserState} */ + this.state = oldState; + this.comments = oldComments; + this.semicolons = oldSemicolons; + this.statementPath = oldStatementPath; + this.prevStatement = oldPrevStatement; + return state; } - return newObj; -}; -/** - * @param {Compilation} compilation the compilation - * @param {function(Compilation, string): any[]} getItems get items - * @returns {number} total number - */ -const countWithChildren = (compilation, getItems) => { - let count = getItems(compilation, "").length; - for (const child of compilation.children) { - count += countWithChildren(child, (c, type) => - getItems(c, `.children[].compilation${type}`) - ); + evaluate(source) { + const ast = JavascriptParser._parse("(" + source + ")", { + sourceType: this.sourceType, + locations: false + }); + if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") { + throw new Error("evaluate: Source is not a expression"); + } + return this.evaluateExpression(ast.body[0].expression); } - return count; -}; -/** @type {ExtractorsByOption} */ -const EXTRACT_ERROR = { - _: (object, error, context, { requestShortener }) => { - // TODO webpack 6 disallow strings in the errors/warnings list - if (typeof error === "string") { - object.message = error; - } else { - if (error.chunk) { - object.chunkName = error.chunk.name; - object.chunkEntry = error.chunk.hasRuntime(); - object.chunkInitial = error.chunk.canBeInitial(); - } - if (error.file) { - object.file = error.file; - } - if (error.module) { - object.moduleIdentifier = error.module.identifier(); - object.moduleName = error.module.readableIdentifier(requestShortener); + /** + * @param {ExpressionNode | DeclarationNode | PrivateIdentifierNode | null | undefined} expr an expression + * @param {number} commentsStartPos source position from which annotation comments are checked + * @returns {boolean} true, when the expression is pure + */ + isPure(expr, commentsStartPos) { + if (!expr) return true; + const result = this.hooks.isPure + .for(expr.type) + .call(expr, commentsStartPos); + if (typeof result === "boolean") return result; + switch (expr.type) { + case "ClassDeclaration": + case "ClassExpression": { + if (expr.body.type !== "ClassBody") return false; + if (expr.superClass && !this.isPure(expr.superClass, expr.range[0])) { + return false; + } + const items = + /** @type {(MethodDefinitionNode | PropertyDefinitionNode)[]} */ ( + expr.body.body + ); + return items.every( + item => + (!item.computed || + !item.key || + this.isPure(item.key, item.range[0])) && + (!item.static || + !item.value || + this.isPure( + item.value, + item.key ? item.key.range[1] : item.range[0] + )) + ); } - if (error.loc) { - object.loc = formatLocation(error.loc); + + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "Literal": + case "PrivateIdentifier": + return true; + + case "VariableDeclaration": + return expr.declarations.every(decl => + this.isPure(decl.init, decl.range[0]) + ); + + case "ConditionalExpression": + return ( + this.isPure(expr.test, commentsStartPos) && + this.isPure(expr.consequent, expr.test.range[1]) && + this.isPure(expr.alternate, expr.consequent.range[1]) + ); + + case "SequenceExpression": + return expr.expressions.every(expr => { + const pureFlag = this.isPure(expr, commentsStartPos); + commentsStartPos = expr.range[1]; + return pureFlag; + }); + + case "CallExpression": { + const pureFlag = + expr.range[0] - commentsStartPos > 12 && + this.getComments([commentsStartPos, expr.range[0]]).some( + comment => + comment.type === "Block" && + /^\s*(#|@)__PURE__\s*$/.test(comment.value) + ); + if (!pureFlag) return false; + commentsStartPos = expr.callee.range[1]; + return expr.arguments.every(arg => { + if (arg.type === "SpreadElement") return false; + const pureFlag = this.isPure(arg, commentsStartPos); + commentsStartPos = arg.range[1]; + return pureFlag; + }); } - object.message = error.message; } - }, - ids: (object, error, { compilation: { chunkGraph } }) => { - if (typeof error !== "string") { - if (error.chunk) { - object.chunkId = error.chunk.id; - } - if (error.module) { - object.moduleId = chunkGraph.getModuleId(error.module); - } + const evaluated = this.evaluateExpression(expr); + return !evaluated.couldHaveSideEffects(); + } + + getComments(range) { + const [rangeStart, rangeEnd] = range; + const compare = (comment, needle) => comment.range[0] - needle; + let idx = binarySearchBounds.ge(this.comments, rangeStart, compare); + let commentsInRange = []; + while (this.comments[idx] && this.comments[idx].range[1] <= rangeEnd) { + commentsInRange.push(this.comments[idx]); + idx++; } - }, - moduleTrace: (object, error, context, options, factory) => { - if (typeof error !== "string" && error.module) { - const { - type, - compilation: { moduleGraph } - } = context; - /** @type {Set} */ - const visitedModules = new Set(); - const moduleTrace = []; - let current = error.module; - while (current) { - if (visitedModules.has(current)) break; // circular (technically impossible, but how knows) - visitedModules.add(current); - const origin = moduleGraph.getIssuer(current); - if (!origin) break; - moduleTrace.push({ origin, module: current }); - current = origin; + + return commentsInRange; + } + + /** + * @param {number} pos source code position + * @returns {boolean} true when a semicolon has been inserted before this position, false if not + */ + isAsiPosition(pos) { + const currentStatement = this.statementPath[this.statementPath.length - 1]; + if (currentStatement === undefined) throw new Error("Not in statement"); + return ( + // Either asking directly for the end position of the current statement + (currentStatement.range[1] === pos && this.semicolons.has(pos)) || + // Or asking for the start position of the current statement, + // here we have to check multiple things + (currentStatement.range[0] === pos && + // is there a previous statement which might be relevant? + this.prevStatement !== undefined && + // is the end position of the previous statement an ASI position? + this.semicolons.has(this.prevStatement.range[1])) + ); + } + + /** + * @param {number} pos source code position + * @returns {void} + */ + unsetAsiPosition(pos) { + this.semicolons.delete(pos); + } + + isStatementLevelExpression(expr) { + const currentStatement = this.statementPath[this.statementPath.length - 1]; + return ( + expr === currentStatement || + (currentStatement.type === "ExpressionStatement" && + currentStatement.expression === expr) + ); + } + + getTagData(name, tag) { + const info = this.scope.definitions.get(name); + if (info instanceof VariableInfo) { + let tagInfo = info.tagInfo; + while (tagInfo !== undefined) { + if (tagInfo.tag === tag) return tagInfo.data; + tagInfo = tagInfo.next; } - object.moduleTrace = factory.create( - `${type}.moduleTrace`, - moduleTrace, - context - ); } - }, - errorDetails: ( - object, - error, - { type, compilation, cachedGetErrors, cachedGetWarnings }, - { errorDetails } - ) => { - if ( - typeof error !== "string" && - (errorDetails === true || - (type.endsWith(".error") && cachedGetErrors(compilation).length < 3)) - ) { - object.details = error.details; + } + + tagVariable(name, tag, data) { + const oldInfo = this.scope.definitions.get(name); + /** @type {VariableInfo} */ + let newInfo; + if (oldInfo === undefined) { + newInfo = new VariableInfo(this.scope, name, { + tag, + data, + next: undefined + }); + } else if (oldInfo instanceof VariableInfo) { + newInfo = new VariableInfo(oldInfo.declaredScope, oldInfo.freeName, { + tag, + data, + next: oldInfo.tagInfo + }); + } else { + newInfo = new VariableInfo(oldInfo, true, { + tag, + data, + next: undefined + }); } - }, - errorStack: (object, error) => { - if (typeof error !== "string") { - object.stack = error.stack; + this.scope.definitions.set(name, newInfo); + } + + defineVariable(name) { + const oldInfo = this.scope.definitions.get(name); + // Don't redefine variable in same scope to keep existing tags + if (oldInfo instanceof VariableInfo && oldInfo.declaredScope === this.scope) + return; + this.scope.definitions.set(name, this.scope); + } + + undefineVariable(name) { + this.scope.definitions.delete(name); + } + + isVariableDefined(name) { + const info = this.scope.definitions.get(name); + if (info === undefined) return false; + if (info instanceof VariableInfo) { + return info.freeName === true; } + return true; } -}; -/** @type {SimpleExtractors} */ -const SIMPLE_EXTRACTORS = { - compilation: { - _: (object, compilation, context, options) => { - if (!context.makePathsRelative) { - context.makePathsRelative = makePathsRelative.bindContextCache( - compilation.compiler.context, - compilation.compiler.root + /** + * @param {string} name variable name + * @returns {ExportedVariableInfo} info for this variable + */ + getVariableInfo(name) { + const value = this.scope.definitions.get(name); + if (value === undefined) { + return name; + } else { + return value; + } + } + + /** + * @param {string} name variable name + * @param {ExportedVariableInfo} variableInfo new info for this variable + * @returns {void} + */ + setVariable(name, variableInfo) { + if (typeof variableInfo === "string") { + if (variableInfo === name) { + this.scope.definitions.delete(name); + } else { + this.scope.definitions.set( + name, + new VariableInfo(this.scope, variableInfo, undefined) ); } - if (!context.cachedGetErrors) { - const map = new WeakMap(); - context.cachedGetErrors = compilation => { - return ( - map.get(compilation) || - (errors => (map.set(compilation, errors), errors))( - compilation.getErrors() - ) - ); + } else { + this.scope.definitions.set(name, variableInfo); + } + } + + parseCommentOptions(range) { + const comments = this.getComments(range); + if (comments.length === 0) { + return EMPTY_COMMENT_OPTIONS; + } + let options = {}; + let errors = []; + for (const comment of comments) { + const { value } = comment; + if (value && webpackCommentRegExp.test(value)) { + // try compile only if webpack options comment is present + try { + const val = vm.runInNewContext(`(function(){return {${value}};})()`); + Object.assign(options, val); + } catch (e) { + e.comment = comment; + errors.push(e); + } + } + } + return { options, errors }; + } + + /** + * @param {MemberExpressionNode} expression a member expression + * @returns {{ members: string[], object: ExpressionNode | SuperNode }} member names (reverse order) and remaining object + */ + extractMemberExpressionChain(expression) { + /** @type {AnyNode} */ + let expr = expression; + const members = []; + while (expr.type === "MemberExpression") { + if (expr.computed) { + if (expr.property.type !== "Literal") break; + members.push(`${expr.property.value}`); + } else { + if (expr.property.type !== "Identifier") break; + members.push(expr.property.name); + } + expr = expr.object; + } + return { + members, + object: expr + }; + } + + /** + * @param {string} varName variable name + * @returns {{name: string, info: VariableInfo | string}} name of the free variable and variable info for that + */ + getFreeInfoFromVariable(varName) { + const info = this.getVariableInfo(varName); + let name; + if (info instanceof VariableInfo) { + name = info.freeName; + if (typeof name !== "string") return undefined; + } else if (typeof info !== "string") { + return undefined; + } else { + name = info; + } + return { info, name }; + } + + /** @typedef {{ type: "call", call: CallExpressionNode, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => string[], name: string, getMembers: () => string[]}} CallExpressionInfo */ + /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[]}} ExpressionExpressionInfo */ + + /** + * @param {MemberExpressionNode} expression a member expression + * @param {number} allowedTypes which types should be returned, presented in bit mask + * @returns {CallExpressionInfo | ExpressionExpressionInfo | undefined} expression info + */ + getMemberExpressionInfo(expression, allowedTypes) { + const { object, members } = this.extractMemberExpressionChain(expression); + switch (object.type) { + case "CallExpression": { + if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0) + return undefined; + let callee = object.callee; + let rootMembers = EMPTY_ARRAY; + if (callee.type === "MemberExpression") { + ({ object: callee, members: rootMembers } = + this.extractMemberExpressionChain(callee)); + } + const rootName = getRootName(callee); + if (!rootName) return undefined; + const result = this.getFreeInfoFromVariable(rootName); + if (!result) return undefined; + const { info: rootInfo, name: resolvedRoot } = result; + const calleeName = objectAndMembersToName(resolvedRoot, rootMembers); + return { + type: "call", + call: object, + calleeName, + rootInfo, + getCalleeMembers: memoize(() => rootMembers.reverse()), + name: objectAndMembersToName(`${calleeName}()`, members), + getMembers: memoize(() => members.reverse()) }; } - if (!context.cachedGetWarnings) { - const map = new WeakMap(); - context.cachedGetWarnings = compilation => { - return ( - map.get(compilation) || - (warnings => (map.set(compilation, warnings), warnings))( - compilation.getWarnings() - ) - ); + case "Identifier": + case "MetaProperty": + case "ThisExpression": { + if ((allowedTypes & ALLOWED_MEMBER_TYPES_EXPRESSION) === 0) + return undefined; + const rootName = getRootName(object); + if (!rootName) return undefined; + + const result = this.getFreeInfoFromVariable(rootName); + if (!result) return undefined; + const { info: rootInfo, name: resolvedRoot } = result; + return { + type: "expression", + name: objectAndMembersToName(resolvedRoot, members), + rootInfo, + getMembers: memoize(() => members.reverse()) }; } - if (compilation.name) { - object.name = compilation.name; + } + } + + /** + * @param {MemberExpressionNode} expression an expression + * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => string[]}} name info + */ + getNameForExpression(expression) { + return this.getMemberExpressionInfo( + expression, + ALLOWED_MEMBER_TYPES_EXPRESSION + ); + } + + /** + * @param {string} code source code + * @param {ParseOptions} options parsing options + * @returns {ProgramNode} parsed ast + */ + static _parse(code, options) { + const type = options ? options.sourceType : "module"; + /** @type {AcornOptions} */ + const parserOptions = { + ...defaultParserOptions, + allowReturnOutsideFunction: type === "script", + ...options, + sourceType: type === "auto" ? "module" : type + }; + + /** @type {AnyNode} */ + let ast; + let error; + let threw = false; + try { + ast = /** @type {AnyNode} */ (parser.parse(code, parserOptions)); + } catch (e) { + error = e; + threw = true; + } + + if (threw && type === "auto") { + parserOptions.sourceType = "script"; + if (!("allowReturnOutsideFunction" in options)) { + parserOptions.allowReturnOutsideFunction = true; } - if (compilation.needAdditionalPass) { - object.needAdditionalPass = true; + if (Array.isArray(parserOptions.onComment)) { + parserOptions.onComment.length = 0; + } + try { + ast = /** @type {AnyNode} */ (parser.parse(code, parserOptions)); + threw = false; + } catch (e) { + // we use the error from first parse try + // so nothing to do here } + } - const { logging, loggingDebug, loggingTrace } = options; - if (logging || (loggingDebug && loggingDebug.length > 0)) { - const util = __webpack_require__(73837); - object.logging = {}; - let acceptedTypes; - let collapsedGroups = false; - switch (logging) { - default: - acceptedTypes = new Set(); - break; - case "error": - acceptedTypes = new Set([LogType.error]); - break; - case "warn": - acceptedTypes = new Set([LogType.error, LogType.warn]); - break; - case "info": - acceptedTypes = new Set([ - LogType.error, - LogType.warn, - LogType.info - ]); - break; - case "log": - acceptedTypes = new Set([ - LogType.error, - LogType.warn, - LogType.info, - LogType.log, - LogType.group, - LogType.groupEnd, - LogType.groupCollapsed, - LogType.clear - ]); - break; - case "verbose": - acceptedTypes = new Set([ - LogType.error, - LogType.warn, - LogType.info, - LogType.log, - LogType.group, - LogType.groupEnd, - LogType.groupCollapsed, - LogType.profile, - LogType.profileEnd, - LogType.time, - LogType.status, - LogType.clear - ]); - collapsedGroups = true; - break; - } - const cachedMakePathsRelative = makePathsRelative.bindContextCache( - options.context, - compilation.compiler.root - ); - let depthInCollapsedGroup = 0; - for (const [origin, logEntries] of compilation.logging) { - const debugMode = loggingDebug.some(fn => fn(origin)); - if (logging === false && !debugMode) continue; - /** @type {KnownStatsLoggingEntry[]} */ - const groupStack = []; - /** @type {KnownStatsLoggingEntry[]} */ - const rootList = []; - let currentList = rootList; - let processedLogEntries = 0; - for (const entry of logEntries) { - let type = entry.type; - if (!debugMode && !acceptedTypes.has(type)) continue; + if (threw) { + throw error; + } - // Expand groups in verbose and debug modes - if ( - type === LogType.groupCollapsed && - (debugMode || collapsedGroups) - ) - type = LogType.group; + return /** @type {ProgramNode} */ (ast); + } +} - if (depthInCollapsedGroup === 0) { - processedLogEntries++; - } +module.exports = JavascriptParser; +module.exports.ALLOWED_MEMBER_TYPES_ALL = ALLOWED_MEMBER_TYPES_ALL; +module.exports.ALLOWED_MEMBER_TYPES_EXPRESSION = + ALLOWED_MEMBER_TYPES_EXPRESSION; +module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = + ALLOWED_MEMBER_TYPES_CALL_EXPRESSION; - if (type === LogType.groupEnd) { - groupStack.pop(); - if (groupStack.length > 0) { - currentList = groupStack[groupStack.length - 1].children; - } else { - currentList = rootList; - } - if (depthInCollapsedGroup > 0) depthInCollapsedGroup--; - continue; - } - let message = undefined; - if (entry.type === LogType.time) { - message = `${entry.args[0]}: ${ - entry.args[1] * 1000 + entry.args[2] / 1000000 - } ms`; - } else if (entry.args && entry.args.length > 0) { - message = util.format(entry.args[0], ...entry.args.slice(1)); - } - /** @type {KnownStatsLoggingEntry} */ - const newEntry = { - ...entry, - type, - message, - trace: loggingTrace ? entry.trace : undefined, - children: - type === LogType.group || type === LogType.groupCollapsed - ? [] - : undefined - }; - currentList.push(newEntry); - if (newEntry.children) { - groupStack.push(newEntry); - currentList = newEntry.children; - if (depthInCollapsedGroup > 0) { - depthInCollapsedGroup++; - } else if (type === LogType.groupCollapsed) { - depthInCollapsedGroup = 1; - } - } - } - let name = cachedMakePathsRelative(origin).replace(/\|/g, " "); - if (name in object.logging) { - let i = 1; - while (`${name}#${i}` in object.logging) { - i++; - } - name = `${name}#${i}`; - } - object.logging[name] = { - entries: rootList, - filteredEntries: logEntries.length - processedLogEntries, - debug: debugMode - }; - } - } - }, - hash: (object, compilation) => { - object.hash = compilation.hash; - }, - version: object => { - object.version = (__webpack_require__(32702)/* .version */ .i8); - }, - env: (object, compilation, context, { _env }) => { - object.env = _env; - }, - timings: (object, compilation) => { - object.time = compilation.endTime - compilation.startTime; - }, - builtAt: (object, compilation) => { - object.builtAt = compilation.endTime; - }, - publicPath: (object, compilation) => { - object.publicPath = compilation.getPath( - compilation.outputOptions.publicPath - ); - }, - outputPath: (object, compilation) => { - object.outputPath = compilation.outputOptions.path; - }, - assets: (object, compilation, context, options, factory) => { - const { type } = context; - /** @type {Map} */ - const compilationFileToChunks = new Map(); - /** @type {Map} */ - const compilationAuxiliaryFileToChunks = new Map(); - for (const chunk of compilation.chunks) { - for (const file of chunk.files) { - let array = compilationFileToChunks.get(file); - if (array === undefined) { - array = []; - compilationFileToChunks.set(file, array); - } - array.push(chunk); - } - for (const file of chunk.auxiliaryFiles) { - let array = compilationAuxiliaryFileToChunks.get(file); - if (array === undefined) { - array = []; - compilationAuxiliaryFileToChunks.set(file, array); - } - array.push(chunk); - } - } - /** @type {Map} */ - const assetMap = new Map(); - /** @type {Set} */ - const assets = new Set(); - for (const asset of compilation.getAssets()) { - /** @type {PreprocessedAsset} */ - const item = { - ...asset, - type: "asset", - related: undefined - }; - assets.add(item); - assetMap.set(asset.name, item); - } - for (const item of assetMap.values()) { - const related = item.info.related; - if (!related) continue; - for (const type of Object.keys(related)) { - const relatedEntry = related[type]; - const deps = Array.isArray(relatedEntry) - ? relatedEntry - : [relatedEntry]; - for (const dep of deps) { - const depItem = assetMap.get(dep); - if (!depItem) continue; - assets.delete(depItem); - depItem.type = type; - item.related = item.related || []; - item.related.push(depItem); - } - } - } - object.assetsByChunkName = {}; - for (const [file, chunks] of compilationFileToChunks) { - for (const chunk of chunks) { - const name = chunk.name; - if (!name) continue; - if ( - !Object.prototype.hasOwnProperty.call( - object.assetsByChunkName, - name - ) - ) { - object.assetsByChunkName[name] = []; - } - object.assetsByChunkName[name].push(file); - } - } +/***/ }), - const groupedAssets = factory.create( - `${type}.assets`, - Array.from(assets), - { - ...context, - compilationFileToChunks, - compilationAuxiliaryFileToChunks - } - ); - const limited = spaceLimited(groupedAssets, options.assetsSpace); - object.assets = limited.children; - object.filteredAssets = limited.filteredChildren; - }, - chunks: (object, compilation, context, options, factory) => { - const { type } = context; - object.chunks = factory.create( - `${type}.chunks`, - Array.from(compilation.chunks), - context - ); - }, - modules: (object, compilation, context, options, factory) => { - const { type } = context; - const array = Array.from(compilation.modules); - const groupedModules = factory.create(`${type}.modules`, array, context); - const limited = spaceLimited(groupedModules, options.modulesSpace); - object.modules = limited.children; - object.filteredModules = limited.filteredChildren; - }, - entrypoints: ( - object, - compilation, - context, - { entrypoints, chunkGroups, chunkGroupAuxiliary, chunkGroupChildren }, - factory - ) => { - const { type } = context; - const array = Array.from(compilation.entrypoints, ([key, value]) => ({ - name: key, - chunkGroup: value - })); - if (entrypoints === "auto" && !chunkGroups) { - if (array.length > 5) return; - if ( - !chunkGroupChildren && - array.every(({ chunkGroup }) => { - if (chunkGroup.chunks.length !== 1) return false; - const chunk = chunkGroup.chunks[0]; - return ( - chunk.files.size === 1 && - (!chunkGroupAuxiliary || chunk.auxiliaryFiles.size === 0) - ); - }) - ) { - return; - } - } - object.entrypoints = factory.create( - `${type}.entrypoints`, - array, - context - ); - }, - chunkGroups: (object, compilation, context, options, factory) => { - const { type } = context; - const array = Array.from( - compilation.namedChunkGroups, - ([key, value]) => ({ - name: key, - chunkGroup: value - }) - ); - object.namedChunkGroups = factory.create( - `${type}.namedChunkGroups`, - array, - context - ); - }, - errors: (object, compilation, context, options, factory) => { - const { type, cachedGetErrors } = context; - object.errors = factory.create( - `${type}.errors`, - cachedGetErrors(compilation), - context +/***/ 93998: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const UnsupportedFeatureWarning = __webpack_require__(42495); +const ConstDependency = __webpack_require__(76911); +const BasicEvaluatedExpression = __webpack_require__(950); + +/** @typedef {import("estree").Expression} ExpressionNode */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("./JavascriptParser")} JavascriptParser */ + +/** + * @param {JavascriptParser} parser the parser + * @param {string} value the const value + * @param {string[]=} runtimeRequirements runtime requirements + * @returns {function(ExpressionNode): true} plugin function + */ +exports.toConstantDependency = (parser, value, runtimeRequirements) => { + return function constDependency(expr) { + const dep = new ConstDependency(value, expr.range, runtimeRequirements); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }; +}; + +/** + * @param {string} value the string value + * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + */ +exports.evaluateToString = value => { + return function stringExpression(expr) { + return new BasicEvaluatedExpression().setString(value).setRange(expr.range); + }; +}; + +/** + * @param {number} value the number value + * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + */ +exports.evaluateToNumber = value => { + return function stringExpression(expr) { + return new BasicEvaluatedExpression().setNumber(value).setRange(expr.range); + }; +}; + +/** + * @param {boolean} value the boolean value + * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + */ +exports.evaluateToBoolean = value => { + return function booleanExpression(expr) { + return new BasicEvaluatedExpression() + .setBoolean(value) + .setRange(expr.range); + }; +}; + +/** + * @param {string} identifier identifier + * @param {string} rootInfo rootInfo + * @param {function(): string[]} getMembers getMembers + * @param {boolean|null=} truthy is truthy, null if nullish + * @returns {function(ExpressionNode): BasicEvaluatedExpression} callback + */ +exports.evaluateToIdentifier = (identifier, rootInfo, getMembers, truthy) => { + return function identifierExpression(expr) { + let evaluatedExpression = new BasicEvaluatedExpression() + .setIdentifier(identifier, rootInfo, getMembers) + .setSideEffects(false) + .setRange(expr.range); + switch (truthy) { + case true: + evaluatedExpression.setTruthy(); + break; + case null: + evaluatedExpression.setNullish(true); + break; + case false: + evaluatedExpression.setFalsy(); + break; + } + + return evaluatedExpression; + }; +}; + +exports.expressionIsUnsupported = (parser, message) => { + return function unsupportedExpression(expr) { + const dep = new ConstDependency("(void 0)", expr.range, null); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + if (!parser.state.module) return; + parser.state.module.addWarning( + new UnsupportedFeatureWarning(message, expr.loc) + ); + return true; + }; +}; + +exports.skipTraversal = () => true; + +exports.approve = () => true; + + +/***/ }), + +/***/ 98124: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const { isSubset } = __webpack_require__(93347); +const { getAllChunks } = __webpack_require__(91145); + +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {(string|number)[]} EntryItem */ + +const EXPORT_PREFIX = "var __webpack_exports__ = "; + +/** + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate + * @param {import("../ChunkGraph").EntryModuleWithChunkGroup[]} entries entries + * @param {Chunk} chunk chunk + * @param {boolean} passive true: passive startup with on chunks loaded + * @returns {string} runtime code + */ +exports.generateEntryStartup = ( + chunkGraph, + runtimeTemplate, + entries, + chunk, + passive +) => { + /** @type {string[]} */ + const runtime = [ + `var __webpack_exec__ = ${runtimeTemplate.returningFunction( + `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)`, + "moduleId" + )}` + ]; + + const runModule = id => { + return `__webpack_exec__(${JSON.stringify(id)})`; + }; + const outputCombination = (chunks, moduleIds, final) => { + if (chunks.size === 0) { + runtime.push( + `${final ? EXPORT_PREFIX : ""}(${moduleIds.map(runModule).join(", ")});` ); - }, - errorsCount: (object, compilation, { cachedGetErrors }) => { - object.errorsCount = countWithChildren(compilation, c => - cachedGetErrors(c) + } else { + const fn = runtimeTemplate.returningFunction( + moduleIds.map(runModule).join(", ") ); - }, - warnings: (object, compilation, context, options, factory) => { - const { type, cachedGetWarnings } = context; - object.warnings = factory.create( - `${type}.warnings`, - cachedGetWarnings(compilation), - context + runtime.push( + `${final && !passive ? EXPORT_PREFIX : ""}${ + passive + ? RuntimeGlobals.onChunksLoaded + : RuntimeGlobals.startupEntrypoint + }(0, ${JSON.stringify(Array.from(chunks, c => c.id))}, ${fn});` ); - }, - warningsCount: ( - object, - compilation, - context, - { warningsFilter }, - factory - ) => { - const { type, cachedGetWarnings } = context; - object.warningsCount = countWithChildren(compilation, (c, childType) => { - if (!warningsFilter && warningsFilter.length === 0) - return cachedGetWarnings(c); - return factory - .create(`${type}${childType}.warnings`, cachedGetWarnings(c), context) - .filter(warning => { - const warningString = Object.keys(warning) - .map(key => `${warning[key]}`) - .join("\n"); - return !warningsFilter.some(filter => - filter(warning, warningString) - ); - }); - }); - }, - errorDetails: ( - object, - compilation, - { cachedGetErrors, cachedGetWarnings }, - { errorDetails, errors, warnings } - ) => { - if (errorDetails === "auto") { - if (warnings) { - const warnings = cachedGetWarnings(compilation); - object.filteredWarningDetailsCount = warnings - .map(e => typeof e !== "string" && e.details) - .filter(Boolean).length; - } - if (errors) { - const errors = cachedGetErrors(compilation); - if (errors.length >= 3) { - object.filteredErrorDetailsCount = errors - .map(e => typeof e !== "string" && e.details) - .filter(Boolean).length; - } - } + if (final && passive) { + runtime.push(`${EXPORT_PREFIX}${RuntimeGlobals.onChunksLoaded}();`); } - }, - children: (object, compilation, context, options, factory) => { - const { type } = context; - object.children = factory.create( - `${type}.children`, - compilation.children, - context - ); } - }, - asset: { - _: (object, asset, context, options, factory) => { - const { compilation } = context; - object.type = asset.type; - object.name = asset.name; - object.size = asset.source.size(); - object.emitted = compilation.emittedAssets.has(asset.name); - object.comparedForEmit = compilation.comparedForEmitAssets.has( - asset.name - ); - const cached = !object.emitted && !object.comparedForEmit; - object.cached = cached; - object.info = asset.info; - if (!cached || options.cachedAssets) { - Object.assign( - object, - factory.create(`${context.type}$visible`, asset, context) - ); + }; + + let currentChunks = undefined; + let currentModuleIds = undefined; + + for (const [module, entrypoint] of entries) { + const runtimeChunk = entrypoint.getRuntimeChunk(); + const moduleId = chunkGraph.getModuleId(module); + const chunks = getAllChunks(entrypoint, chunk, runtimeChunk); + if ( + currentChunks && + currentChunks.size === chunks.size && + isSubset(currentChunks, chunks) + ) { + currentModuleIds.push(moduleId); + } else { + if (currentChunks) { + outputCombination(currentChunks, currentModuleIds); } + currentChunks = chunks; + currentModuleIds = [moduleId]; } - }, - asset$visible: { - _: ( - object, - asset, - { compilation, compilationFileToChunks, compilationAuxiliaryFileToChunks } - ) => { - const chunks = compilationFileToChunks.get(asset.name) || []; - const auxiliaryChunks = - compilationAuxiliaryFileToChunks.get(asset.name) || []; - object.chunkNames = uniqueOrderedArray( - chunks, - c => (c.name ? [c.name] : []), - compareIds - ); - object.chunkIdHints = uniqueOrderedArray( - chunks, - c => Array.from(c.idNameHints), - compareIds - ); - object.auxiliaryChunkNames = uniqueOrderedArray( - auxiliaryChunks, - c => (c.name ? [c.name] : []), - compareIds - ); - object.auxiliaryChunkIdHints = uniqueOrderedArray( - auxiliaryChunks, - c => Array.from(c.idNameHints), - compareIds - ); - object.filteredRelated = asset.related ? asset.related.length : undefined; - }, - relatedAssets: (object, asset, context, options, factory) => { - const { type } = context; - object.related = factory.create( - `${type.slice(0, -8)}.related`, - asset.related, - context - ); - object.filteredRelated = asset.related - ? asset.related.length - object.related.length - : undefined; - }, - ids: ( - object, - asset, - { compilationFileToChunks, compilationAuxiliaryFileToChunks } - ) => { - const chunks = compilationFileToChunks.get(asset.name) || []; - const auxiliaryChunks = - compilationAuxiliaryFileToChunks.get(asset.name) || []; - object.chunks = uniqueOrderedArray(chunks, c => c.ids, compareIds); - object.auxiliaryChunks = uniqueOrderedArray( - auxiliaryChunks, - c => c.ids, - compareIds - ); - }, - performance: (object, asset) => { - object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(asset.source); - } - }, - chunkGroup: { - _: ( - object, - { name, chunkGroup }, - { compilation, compilation: { moduleGraph, chunkGraph } }, - { ids, chunkGroupAuxiliary, chunkGroupChildren, chunkGroupMaxAssets } - ) => { - const children = - chunkGroupChildren && - chunkGroup.getChildrenByOrders(moduleGraph, chunkGraph); - /** - * @param {string} name Name - * @returns {{ name: string, size: number }} Asset object - */ - const toAsset = name => { - const asset = compilation.getAsset(name); - return { - name, - size: asset ? asset.info.size : -1 - }; - }; - /** @type {(total: number, asset: { size: number }) => number} */ - const sizeReducer = (total, { size }) => total + size; - const assets = uniqueArray(chunkGroup.chunks, c => c.files).map(toAsset); - const auxiliaryAssets = uniqueOrderedArray( - chunkGroup.chunks, - c => c.auxiliaryFiles, - compareIds - ).map(toAsset); - const assetsSize = assets.reduce(sizeReducer, 0); - const auxiliaryAssetsSize = auxiliaryAssets.reduce(sizeReducer, 0); - /** @type {KnownStatsChunkGroup} */ - const statsChunkGroup = { - name, - chunks: ids ? chunkGroup.chunks.map(c => c.id) : undefined, - assets: assets.length <= chunkGroupMaxAssets ? assets : undefined, - filteredAssets: - assets.length <= chunkGroupMaxAssets ? 0 : assets.length, - assetsSize, - auxiliaryAssets: - chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets - ? auxiliaryAssets - : undefined, - filteredAuxiliaryAssets: - chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets - ? 0 - : auxiliaryAssets.length, - auxiliaryAssetsSize, - children: children - ? mapObject(children, groups => - groups.map(group => { - const assets = uniqueArray(group.chunks, c => c.files).map( - toAsset - ); - const auxiliaryAssets = uniqueOrderedArray( - group.chunks, - c => c.auxiliaryFiles, - compareIds - ).map(toAsset); + } - /** @type {KnownStatsChunkGroup} */ - const childStatsChunkGroup = { - name: group.name, - chunks: ids ? group.chunks.map(c => c.id) : undefined, - assets: - assets.length <= chunkGroupMaxAssets ? assets : undefined, - filteredAssets: - assets.length <= chunkGroupMaxAssets ? 0 : assets.length, - auxiliaryAssets: - chunkGroupAuxiliary && - auxiliaryAssets.length <= chunkGroupMaxAssets - ? auxiliaryAssets - : undefined, - filteredAuxiliaryAssets: - chunkGroupAuxiliary && - auxiliaryAssets.length <= chunkGroupMaxAssets - ? 0 - : auxiliaryAssets.length - }; + // output current modules with export prefix + if (currentChunks) { + outputCombination(currentChunks, currentModuleIds, true); + } + runtime.push(""); + return Template.asString(runtime); +}; - return childStatsChunkGroup; - }) - ) - : undefined, - childAssets: children - ? mapObject(children, groups => { - /** @type {Set} */ - const set = new Set(); - for (const group of groups) { - for (const chunk of group.chunks) { - for (const asset of chunk.files) { - set.add(asset); - } - } - } - return Array.from(set); - }) - : undefined - }; - Object.assign(object, statsChunkGroup); - }, - performance: (object, { chunkGroup }) => { - object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(chunkGroup); +/** + * @param {Hash} hash the hash to update + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {import("../ChunkGraph").EntryModuleWithChunkGroup[]} entries entries + * @param {Chunk} chunk chunk + * @returns {void} + */ +exports.updateHashForEntryStartup = (hash, chunkGraph, entries, chunk) => { + for (const [module, entrypoint] of entries) { + const runtimeChunk = entrypoint.getRuntimeChunk(); + const moduleId = chunkGraph.getModuleId(module); + hash.update(`${moduleId}`); + for (const c of getAllChunks(entrypoint, chunk, runtimeChunk)) + hash.update(`${c.id}`); + } +}; + +/** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {function(Chunk, ChunkGraph): boolean} filterFn filter function + * @returns {Set} initially fulfilled chunk ids + */ +exports.getInitialChunkIds = (chunk, chunkGraph, filterFn) => { + const initialChunkIds = new Set(chunk.ids); + for (const c of chunk.getAllInitialChunks()) { + if (c === chunk || filterFn(c, chunkGraph)) continue; + for (const id of c.ids) initialChunkIds.add(id); + } + return initialChunkIds; +}; + + +/***/ }), + +/***/ 90490: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { register } = __webpack_require__(8282); + +class JsonData { + constructor(data) { + this._buffer = undefined; + this._data = undefined; + if (Buffer.isBuffer(data)) { + this._buffer = data; + } else { + this._data = data; } - }, - module: { - _: (object, module, context, options, factory) => { - const { compilation, type } = context; - const built = compilation.builtModules.has(module); - const codeGenerated = compilation.codeGeneratedModules.has(module); - const buildTimeExecuted = - compilation.buildTimeExecutedModules.has(module); - /** @type {{[x: string]: number}} */ - const sizes = {}; - for (const sourceType of module.getSourceTypes()) { - sizes[sourceType] = module.size(sourceType); - } - /** @type {KnownStatsModule} */ - const statsModule = { - type: "module", - moduleType: module.type, - layer: module.layer, - size: module.size(), - sizes, - built, - codeGenerated, - buildTimeExecuted, - cached: !built && !codeGenerated - }; - Object.assign(object, statsModule); + } - if (built || codeGenerated || options.cachedModules) { - Object.assign( - object, - factory.create(`${type}$visible`, module, context) - ); - } + get() { + if (this._data === undefined && this._buffer !== undefined) { + this._data = JSON.parse(this._buffer.toString()); + } + return this._data; + } +} + +register(JsonData, "webpack/lib/json/JsonData", null, { + serialize(obj, { write }) { + if (obj._buffer === undefined && obj._data !== undefined) { + obj._buffer = Buffer.from(JSON.stringify(obj._data)); } + write(obj._buffer); }, - module$visible: { - _: (object, module, context, { requestShortener }, factory) => { - const { compilation, type, rootModules } = context; - const { moduleGraph } = compilation; - /** @type {Module[]} */ - const path = []; - const issuer = moduleGraph.getIssuer(module); - let current = issuer; - while (current) { - path.push(current); - current = moduleGraph.getIssuer(current); - } - path.reverse(); - const profile = moduleGraph.getProfile(module); - const errors = module.getErrors(); - const errorsCount = errors !== undefined ? countIterable(errors) : 0; - const warnings = module.getWarnings(); - const warningsCount = - warnings !== undefined ? countIterable(warnings) : 0; - /** @type {{[x: string]: number}} */ - const sizes = {}; - for (const sourceType of module.getSourceTypes()) { - sizes[sourceType] = module.size(sourceType); - } - /** @type {KnownStatsModule} */ - const statsModule = { - identifier: module.identifier(), - name: module.readableIdentifier(requestShortener), - nameForCondition: module.nameForCondition(), - index: moduleGraph.getPreOrderIndex(module), - preOrderIndex: moduleGraph.getPreOrderIndex(module), - index2: moduleGraph.getPostOrderIndex(module), - postOrderIndex: moduleGraph.getPostOrderIndex(module), - cacheable: module.buildInfo.cacheable, - optional: module.isOptional(moduleGraph), - orphan: - !type.endsWith("module.modules[].module$visible") && - compilation.chunkGraph.getNumberOfModuleChunks(module) === 0, - dependent: rootModules ? !rootModules.has(module) : undefined, - issuer: issuer && issuer.identifier(), - issuerName: issuer && issuer.readableIdentifier(requestShortener), - issuerPath: - issuer && - factory.create(`${type.slice(0, -8)}.issuerPath`, path, context), - failed: errorsCount > 0, - errors: errorsCount, - warnings: warningsCount - }; - Object.assign(object, statsModule); - if (profile) { - object.profile = factory.create( - `${type.slice(0, -8)}.profile`, - profile, - context - ); - } - }, - ids: (object, module, { compilation: { chunkGraph, moduleGraph } }) => { - object.id = chunkGraph.getModuleId(module); - const issuer = moduleGraph.getIssuer(module); - object.issuerId = issuer && chunkGraph.getModuleId(issuer); - object.chunks = Array.from( - chunkGraph.getOrderedModuleChunksIterable(module, compareChunksById), - chunk => chunk.id - ); - }, - moduleAssets: (object, module) => { - object.assets = module.buildInfo.assets - ? Object.keys(module.buildInfo.assets) - : []; - }, - reasons: (object, module, context, options, factory) => { - const { - type, - compilation: { moduleGraph } - } = context; - const groupsReasons = factory.create( - `${type.slice(0, -8)}.reasons`, - Array.from(moduleGraph.getIncomingConnections(module)), - context + deserialize({ read }) { + return new JsonData(read()); + } +}); + +module.exports = JsonData; + + +/***/ }), + +/***/ 70393: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { RawSource } = __webpack_require__(51255); +const ConcatenationScope = __webpack_require__(98229); +const { UsageState } = __webpack_require__(63686); +const Generator = __webpack_require__(93401); +const RuntimeGlobals = __webpack_require__(16475); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../ExportsInfo")} ExportsInfo */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +const stringifySafe = data => { + const stringified = JSON.stringify(data); + if (!stringified) { + return undefined; // Invalid JSON + } + + return stringified.replace(/\u2028|\u2029/g, str => + str === "\u2029" ? "\\u2029" : "\\u2028" + ); // invalid in JavaScript but valid JSON +}; + +/** + * @param {Object} data data (always an object or array) + * @param {ExportsInfo} exportsInfo exports info + * @param {RuntimeSpec} runtime the runtime + * @returns {Object} reduced data + */ +const createObjectForExportsInfo = (data, exportsInfo, runtime) => { + if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) + return data; + const isArray = Array.isArray(data); + const reducedData = isArray ? [] : {}; + for (const key of Object.keys(data)) { + const exportInfo = exportsInfo.getReadOnlyExportInfo(key); + const used = exportInfo.getUsed(runtime); + if (used === UsageState.Unused) continue; + + let value; + if (used === UsageState.OnlyPropertiesUsed && exportInfo.exportsInfo) { + value = createObjectForExportsInfo( + data[key], + exportInfo.exportsInfo, + runtime ); - const limited = spaceLimited(groupsReasons, options.reasonsSpace); - object.reasons = limited.children; - object.filteredReasons = limited.filteredChildren; - }, - usedExports: ( - object, - module, - { runtime, compilation: { moduleGraph } } - ) => { - const usedExports = moduleGraph.getUsedExports(module, runtime); - if (usedExports === null) { - object.usedExports = null; - } else if (typeof usedExports === "boolean") { - object.usedExports = usedExports; + } else { + value = data[key]; + } + const name = exportInfo.getUsedName(key, runtime); + reducedData[name] = value; + } + if (isArray) { + let arrayLengthWhenUsed = + exportsInfo.getReadOnlyExportInfo("length").getUsed(runtime) !== + UsageState.Unused + ? data.length + : undefined; + + let sizeObjectMinusArray = 0; + for (let i = 0; i < reducedData.length; i++) { + if (reducedData[i] === undefined) { + sizeObjectMinusArray -= 2; } else { - object.usedExports = Array.from(usedExports); - } - }, - providedExports: (object, module, { compilation: { moduleGraph } }) => { - const providedExports = moduleGraph.getProvidedExports(module); - object.providedExports = Array.isArray(providedExports) - ? providedExports - : null; - }, - optimizationBailout: ( - object, - module, - { compilation: { moduleGraph } }, - { requestShortener } - ) => { - object.optimizationBailout = moduleGraph - .getOptimizationBailout(module) - .map(item => { - if (typeof item === "function") return item(requestShortener); - return item; - }); - }, - depth: (object, module, { compilation: { moduleGraph } }) => { - object.depth = moduleGraph.getDepth(module); - }, - nestedModules: (object, module, context, options, factory) => { - const { type } = context; - const innerModules = /** @type {Module & { modules?: Module[] }} */ ( - module - ).modules; - if (Array.isArray(innerModules)) { - const groupedModules = factory.create( - `${type.slice(0, -8)}.modules`, - innerModules, - context - ); - const limited = spaceLimited( - groupedModules, - options.nestedModulesSpace - ); - object.modules = limited.children; - object.filteredModules = limited.filteredChildren; - } - }, - source: (object, module) => { - const originalSource = module.originalSource(); - if (originalSource) { - object.source = originalSource.source(); + sizeObjectMinusArray += `${i}`.length + 3; } } - }, - profile: { - _: (object, profile) => { - /** @type {KnownStatsProfile} */ - const statsProfile = { - total: - profile.factory + - profile.restoring + - profile.integration + - profile.building + - profile.storing, - resolving: profile.factory, - restoring: profile.restoring, - building: profile.building, - integration: profile.integration, - storing: profile.storing, - additionalResolving: profile.additionalFactories, - additionalIntegration: profile.additionalIntegration, - // TODO remove this in webpack 6 - factory: profile.factory, - // TODO remove this in webpack 6 - dependencies: profile.additionalFactories - }; - Object.assign(object, statsProfile); + if (arrayLengthWhenUsed !== undefined) { + sizeObjectMinusArray += + `${arrayLengthWhenUsed}`.length + + 8 - + (arrayLengthWhenUsed - reducedData.length) * 2; } - }, - moduleIssuer: { - _: (object, module, context, { requestShortener }, factory) => { - const { compilation, type } = context; - const { moduleGraph } = compilation; - const profile = moduleGraph.getProfile(module); - /** @type {KnownStatsModuleIssuer} */ - const statsModuleIssuer = { - identifier: module.identifier(), - name: module.readableIdentifier(requestShortener) - }; - Object.assign(object, statsModuleIssuer); - if (profile) { - object.profile = factory.create(`${type}.profile`, profile, context); - } - }, - ids: (object, module, { compilation: { chunkGraph } }) => { - object.id = chunkGraph.getModuleId(module); - } - }, - moduleReason: { - _: (object, reason, { runtime }, { requestShortener }) => { - const dep = reason.dependency; - const moduleDep = - dep && dep instanceof ModuleDependency ? dep : undefined; - /** @type {KnownStatsModuleReason} */ - const statsModuleReason = { - moduleIdentifier: reason.originModule - ? reason.originModule.identifier() - : null, - module: reason.originModule - ? reason.originModule.readableIdentifier(requestShortener) - : null, - moduleName: reason.originModule - ? reason.originModule.readableIdentifier(requestShortener) - : null, - resolvedModuleIdentifier: reason.resolvedOriginModule - ? reason.resolvedOriginModule.identifier() - : null, - resolvedModule: reason.resolvedOriginModule - ? reason.resolvedOriginModule.readableIdentifier(requestShortener) - : null, - type: reason.dependency ? reason.dependency.type : null, - active: reason.isActive(runtime), - explanation: reason.explanation, - userRequest: (moduleDep && moduleDep.userRequest) || null - }; - Object.assign(object, statsModuleReason); - if (reason.dependency) { - const locInfo = formatLocation(reason.dependency.loc); - if (locInfo) { - object.loc = locInfo; - } - } - }, - ids: (object, reason, { compilation: { chunkGraph } }) => { - object.moduleId = reason.originModule - ? chunkGraph.getModuleId(reason.originModule) - : null; - object.resolvedModuleId = reason.resolvedOriginModule - ? chunkGraph.getModuleId(reason.resolvedOriginModule) - : null; - } - }, - chunk: { - _: (object, chunk, { makePathsRelative, compilation: { chunkGraph } }) => { - const childIdByOrder = chunk.getChildIdsByOrders(chunkGraph); - - /** @type {KnownStatsChunk} */ - const statsChunk = { - rendered: chunk.rendered, - initial: chunk.canBeInitial(), - entry: chunk.hasRuntime(), - recorded: AggressiveSplittingPlugin.wasChunkRecorded(chunk), - reason: chunk.chunkReason, - size: chunkGraph.getChunkModulesSize(chunk), - sizes: chunkGraph.getChunkModulesSizes(chunk), - names: chunk.name ? [chunk.name] : [], - idHints: Array.from(chunk.idNameHints), - runtime: - chunk.runtime === undefined - ? undefined - : typeof chunk.runtime === "string" - ? [makePathsRelative(chunk.runtime)] - : Array.from(chunk.runtime.sort(), makePathsRelative), - files: Array.from(chunk.files), - auxiliaryFiles: Array.from(chunk.auxiliaryFiles).sort(compareIds), - hash: chunk.renderedHash, - childrenByOrder: childIdByOrder - }; - Object.assign(object, statsChunk); - }, - ids: (object, chunk) => { - object.id = chunk.id; - }, - chunkRelations: (object, chunk, { compilation: { chunkGraph } }) => { - /** @type {Set} */ - const parents = new Set(); - /** @type {Set} */ - const children = new Set(); - /** @type {Set} */ - const siblings = new Set(); - - for (const chunkGroup of chunk.groupsIterable) { - for (const parentGroup of chunkGroup.parentsIterable) { - for (const chunk of parentGroup.chunks) { - parents.add(chunk.id); - } - } - for (const childGroup of chunkGroup.childrenIterable) { - for (const chunk of childGroup.chunks) { - children.add(chunk.id); - } - } - for (const sibling of chunkGroup.chunks) { - if (sibling !== chunk) siblings.add(sibling.id); - } - } - object.siblings = Array.from(siblings).sort(compareIds); - object.parents = Array.from(parents).sort(compareIds); - object.children = Array.from(children).sort(compareIds); - }, - chunkModules: (object, chunk, context, options, factory) => { - const { - type, - compilation: { chunkGraph } - } = context; - const array = chunkGraph.getChunkModules(chunk); - const groupedModules = factory.create(`${type}.modules`, array, { - ...context, - runtime: chunk.runtime, - rootModules: new Set(chunkGraph.getChunkRootModules(chunk)) - }); - const limited = spaceLimited(groupedModules, options.chunkModulesSpace); - object.modules = limited.children; - object.filteredModules = limited.filteredChildren; - }, - chunkOrigins: (object, chunk, context, options, factory) => { - const { - type, - compilation: { chunkGraph } - } = context; - /** @type {Set} */ - const originsKeySet = new Set(); - const origins = []; - for (const g of chunk.groupsIterable) { - origins.push(...g.origins); - } - const array = origins.filter(origin => { - const key = [ - origin.module ? chunkGraph.getModuleId(origin.module) : undefined, - formatLocation(origin.loc), - origin.request - ].join(); - if (originsKeySet.has(key)) return false; - originsKeySet.add(key); - return true; - }); - object.origins = factory.create(`${type}.origins`, array, context); - } - }, - chunkOrigin: { - _: (object, origin, context, { requestShortener }) => { - /** @type {KnownStatsChunkOrigin} */ - const statsChunkOrigin = { - module: origin.module ? origin.module.identifier() : "", - moduleIdentifier: origin.module ? origin.module.identifier() : "", - moduleName: origin.module - ? origin.module.readableIdentifier(requestShortener) - : "", - loc: formatLocation(origin.loc), - request: origin.request - }; - Object.assign(object, statsChunkOrigin); - }, - ids: (object, origin, { compilation: { chunkGraph } }) => { - object.moduleId = origin.module - ? chunkGraph.getModuleId(origin.module) - : undefined; - } - }, - error: EXTRACT_ERROR, - warning: EXTRACT_ERROR, - moduleTraceItem: { - _: (object, { origin, module }, context, { requestShortener }, factory) => { - const { - type, - compilation: { moduleGraph } - } = context; - object.originIdentifier = origin.identifier(); - object.originName = origin.readableIdentifier(requestShortener); - object.moduleIdentifier = module.identifier(); - object.moduleName = module.readableIdentifier(requestShortener); - const dependencies = Array.from( - moduleGraph.getIncomingConnections(module) - ) - .filter(c => c.resolvedOriginModule === origin && c.dependency) - .map(c => c.dependency); - object.dependencies = factory.create( - `${type}.dependencies`, - Array.from(new Set(dependencies)), - context + if (sizeObjectMinusArray < 0) + return Object.assign( + arrayLengthWhenUsed === undefined + ? {} + : { length: arrayLengthWhenUsed }, + reducedData ); - }, - ids: (object, { origin, module }, { compilation: { chunkGraph } }) => { - object.originId = chunkGraph.getModuleId(origin); - object.moduleId = chunkGraph.getModuleId(module); - } - }, - moduleTraceDependency: { - _: (object, dependency) => { - object.loc = formatLocation(dependency.loc); + const generatedLength = + arrayLengthWhenUsed !== undefined + ? Math.max(arrayLengthWhenUsed, reducedData.length) + : reducedData.length; + for (let i = 0; i < generatedLength; i++) { + if (reducedData[i] === undefined) { + reducedData[i] = 0; + } } } + return reducedData; }; -/** @type {Record boolean | undefined>>} */ -const FILTER = { - "module.reasons": { - "!orphanModules": (reason, { compilation: { chunkGraph } }) => { - if ( - reason.originModule && - chunkGraph.getNumberOfModuleChunks(reason.originModule) === 0 - ) { - return false; - } - } +const TYPES = new Set(["javascript"]); + +class JsonGenerator extends Generator { + /** + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) + */ + getTypes(module) { + return TYPES; } -}; -/** @type {Record boolean | undefined>>} */ -const FILTER_RESULTS = { - "compilation.warnings": { - warningsFilter: util.deprecate( - (warning, context, { warningsFilter }) => { - const warningString = Object.keys(warning) - .map(key => `${warning[key]}`) - .join("\n"); - return !warningsFilter.some(filter => filter(warning, warningString)); - }, - "config.stats.warningsFilter is deprecated in favor of config.ignoreWarnings", - "DEP_WEBPACK_STATS_WARNINGS_FILTER" - ) + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + let data = + module.buildInfo && + module.buildInfo.jsonData && + module.buildInfo.jsonData.get(); + if (!data) return 0; + return stringifySafe(data).length + 10; } -}; -/** @type {Record void>} */ -const MODULES_SORTER = { - _: (comparators, { compilation: { moduleGraph } }) => { - comparators.push( - compareSelect( - /** - * @param {Module} m module - * @returns {number} depth - */ - m => moduleGraph.getDepth(m), - compareNumbers - ), - compareSelect( - /** - * @param {Module} m module - * @returns {number} index - */ - m => moduleGraph.getPreOrderIndex(m), - compareNumbers - ), - compareSelect( - /** - * @param {Module} m module - * @returns {string} identifier - */ - m => m.identifier(), - compareIds - ) - ); + /** + * @param {NormalModule} module module for which the bailout reason should be determined + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + */ + getConcatenationBailoutReason(module, context) { + return undefined; } -}; -/** @type {Record void>>} */ -const SORTERS = { - "compilation.chunks": { - _: comparators => { - comparators.push(compareSelect(c => c.id, compareIds)); + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code + */ + generate( + module, + { + moduleGraph, + runtimeTemplate, + runtimeRequirements, + runtime, + concatenationScope } - }, - "compilation.modules": MODULES_SORTER, - "chunk.rootModules": MODULES_SORTER, - "chunk.modules": MODULES_SORTER, - "module.modules": MODULES_SORTER, - "module.reasons": { - _: (comparators, { compilation: { chunkGraph } }) => { - comparators.push( - compareSelect(x => x.originModule, compareModulesByIdentifier) - ); - comparators.push( - compareSelect(x => x.resolvedOriginModule, compareModulesByIdentifier) - ); - comparators.push( - compareSelect( - x => x.dependency, - concatComparators( - compareSelect( - /** - * @param {Dependency} x dependency - * @returns {DependencyLocation} location - */ - x => x.loc, - compareLocations - ), - compareSelect(x => x.type, compareIds) - ) - ) + ) { + const data = + module.buildInfo && + module.buildInfo.jsonData && + module.buildInfo.jsonData.get(); + if (data === undefined) { + return new RawSource( + runtimeTemplate.missingModuleStatement({ + request: module.rawRequest + }) ); } - }, - "chunk.origins": { - _: (comparators, { compilation: { chunkGraph } }) => { - comparators.push( - compareSelect( - origin => - origin.module ? chunkGraph.getModuleId(origin.module) : undefined, - compareIds - ), - compareSelect(origin => formatLocation(origin.loc), compareIds), - compareSelect(origin => origin.request, compareIds) + const exportsInfo = moduleGraph.getExportsInfo(module); + let finalJson = + typeof data === "object" && + data && + exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused + ? createObjectForExportsInfo(data, exportsInfo, runtime) + : data; + // Use JSON because JSON.parse() is much faster than JavaScript evaluation + const jsonStr = stringifySafe(finalJson); + const jsonExpr = + jsonStr.length > 20 && typeof finalJson === "object" + ? `JSON.parse('${jsonStr.replace(/[\\']/g, "\\$&")}')` + : jsonStr; + let content; + if (concatenationScope) { + content = `${runtimeTemplate.supportsConst() ? "const" : "var"} ${ + ConcatenationScope.NAMESPACE_OBJECT_EXPORT + } = ${jsonExpr};`; + concatenationScope.registerNamespaceExport( + ConcatenationScope.NAMESPACE_OBJECT_EXPORT ); + } else { + runtimeRequirements.add(RuntimeGlobals.module); + content = `${module.moduleArgument}.exports = ${jsonExpr};`; } + return new RawSource(content); } -}; +} -const getItemSize = item => { - // Each item takes 1 line - // + the size of the children - // + 1 extra line when it has children and filteredChildren - return !item.children - ? 1 - : item.filteredChildren - ? 2 + getTotalSize(item.children) - : 1 + getTotalSize(item.children); -}; +module.exports = JsonGenerator; -const getTotalSize = children => { - let size = 0; - for (const child of children) { - size += getItemSize(child); - } - return size; -}; -const getTotalItems = children => { - let count = 0; - for (const child of children) { - if (!child.children && !child.filteredChildren) { - count++; - } else { - if (child.children) count += getTotalItems(child.children); - if (child.filteredChildren) count += child.filteredChildren; - } - } - return count; -}; +/***/ }), -const collapse = children => { - // After collapse each child must take exactly one line - const newChildren = []; - for (const child of children) { - if (child.children) { - let filteredChildren = child.filteredChildren || 0; - filteredChildren += getTotalItems(child.children); - newChildren.push({ - ...child, - children: undefined, - filteredChildren - }); - } else { - newChildren.push(child); - } - } - return newChildren; -}; +/***/ 86770: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const spaceLimited = ( - itemsAndGroups, - max, - filteredChildrenLineReserved = false -) => { - if (max < 1) { - return { - children: undefined, - filteredChildren: getTotalItems(itemsAndGroups) - }; - } - /** @type {any[] | undefined} */ - let children = undefined; - /** @type {number | undefined} */ - let filteredChildren = undefined; - // This are the groups, which take 1+ lines each - const groups = []; - // The sizes of the groups are stored in groupSizes - const groupSizes = []; - // This are the items, which take 1 line each - const items = []; - // The total of group sizes - let groupsSize = 0; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - for (const itemOrGroup of itemsAndGroups) { - // is item - if (!itemOrGroup.children && !itemOrGroup.filteredChildren) { - items.push(itemOrGroup); - } else { - groups.push(itemOrGroup); - const size = getItemSize(itemOrGroup); - groupSizes.push(size); - groupsSize += size; - } + + +const createSchemaValidation = __webpack_require__(32540); +const JsonGenerator = __webpack_require__(70393); +const JsonParser = __webpack_require__(41090); + +/** @typedef {import("../Compiler")} Compiler */ + +const validate = createSchemaValidation( + __webpack_require__(54094), + () => __webpack_require__(50166), + { + name: "Json Modules Plugin", + baseDataPath: "parser" } +); - if (groupsSize + items.length <= max) { - // The total size in the current state fits into the max - // keep all - children = groups.length > 0 ? groups.concat(items) : items; - } else if (groups.length === 0) { - // slice items to max - // inner space marks that lines for filteredChildren already reserved - const limit = max - (filteredChildrenLineReserved ? 0 : 1); - filteredChildren = items.length - limit; - items.length = limit; - children = items; - } else { - // limit is the size when all groups are collapsed - const limit = - groups.length + - (filteredChildrenLineReserved || items.length === 0 ? 0 : 1); - if (limit < max) { - // calculate how much we are over the size limit - // this allows to approach the limit faster - let oversize; - // If each group would take 1 line the total would be below the maximum - // collapse some groups, keep items - while ( - (oversize = - groupsSize + - items.length + - (filteredChildren && !filteredChildrenLineReserved ? 1 : 0) - - max) > 0 - ) { - // Find the maximum group and process only this one - const maxGroupSize = Math.max(...groupSizes); - if (maxGroupSize < items.length) { - filteredChildren = items.length; - items.length = 0; - continue; - } - for (let i = 0; i < groups.length; i++) { - if (groupSizes[i] === maxGroupSize) { - const group = groups[i]; - // run this algorithm recursively and limit the size of the children to - // current size - oversize / number of groups - // So it should always end up being smaller - const headerSize = group.filteredChildren ? 2 : 1; - const limited = spaceLimited( - group.children, - maxGroupSize - - // we should use ceil to always feet in max - Math.ceil(oversize / groups.length) - - // we substitute size of group head - headerSize, - headerSize === 2 - ); - groups[i] = { - ...group, - children: limited.children, - filteredChildren: limited.filteredChildren - ? (group.filteredChildren || 0) + limited.filteredChildren - : group.filteredChildren - }; - const newSize = getItemSize(groups[i]); - groupsSize -= maxGroupSize - newSize; - groupSizes[i] = newSize; - break; - } - } +class JsonModulesPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "JsonModulesPlugin", + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.createParser + .for("json") + .tap("JsonModulesPlugin", parserOptions => { + validate(parserOptions); + + return new JsonParser(parserOptions); + }); + normalModuleFactory.hooks.createGenerator + .for("json") + .tap("JsonModulesPlugin", () => { + return new JsonGenerator(); + }); } - children = groups.concat(items); - } else if (limit === max) { - // If we have only enough space to show one line per group and one line for the filtered items - // collapse all groups and items - children = collapse(groups); - filteredChildren = items.length; - } else { - // If we have no space - // collapse complete group - filteredChildren = getTotalItems(itemsAndGroups); - } + ); } +} - return { - children, - filteredChildren - }; -}; +module.exports = JsonModulesPlugin; -const assetGroup = (children, assets) => { - let size = 0; - for (const asset of children) { - size += asset.size; + +/***/ }), + +/***/ 41090: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const parseJson = __webpack_require__(15235); +const Parser = __webpack_require__(11715); +const JsonExportsDependency = __webpack_require__(750); +const JsonData = __webpack_require__(90490); + +/** @typedef {import("../../declarations/plugins/JsonModulesPluginParser").JsonModulesPluginParserOptions} JsonModulesPluginParserOptions */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ + +class JsonParser extends Parser { + /** + * @param {JsonModulesPluginParserOptions} options parser options + */ + constructor(options) { + super(); + this.options = options || {}; } - return { - size - }; -}; -const moduleGroup = (children, modules) => { - let size = 0; - const sizes = {}; - for (const module of children) { - size += module.size; - for (const key of Object.keys(module.sizes)) { - sizes[key] = (sizes[key] || 0) + module.sizes[key]; + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (Buffer.isBuffer(source)) { + source = source.toString("utf-8"); } - } - return { - size, - sizes - }; -}; -const reasonGroup = (children, reasons) => { - let active = false; - for (const reason of children) { - active = active || reason.active; + /** @type {JsonModulesPluginParserOptions["parse"]} */ + const parseFn = + typeof this.options.parse === "function" ? this.options.parse : parseJson; + + const data = + typeof source === "object" + ? source + : parseFn(source[0] === "\ufeff" ? source.slice(1) : source); + + state.module.buildInfo.jsonData = new JsonData(data); + state.module.buildInfo.strict = true; + state.module.buildMeta.exportsType = "default"; + state.module.buildMeta.defaultObject = + typeof data === "object" ? "redirect-warn" : false; + state.module.addDependency( + new JsonExportsDependency(JsonExportsDependency.getExportsFromData(data)) + ); + return state; } - return { - active - }; -}; +} -const GROUP_EXTENSION_REGEXP = /(\.[^.]+?)(?:\?|(?: \+ \d+ modules?)?$)/; -const GROUP_PATH_REGEXP = /(.+)[/\\][^/\\]+?(?:\?|(?: \+ \d+ modules?)?$)/; +module.exports = JsonParser; -/** @type {Record void>} */ -const ASSETS_GROUPERS = { - _: (groupConfigs, context, options) => { - const groupByFlag = (name, exclude) => { - groupConfigs.push({ - getKeys: asset => { - return asset[name] ? ["1"] : undefined; - }, - getOptions: () => { - return { - groupChildren: !exclude, - force: exclude - }; - }, - createGroup: (key, children, assets) => { - return exclude - ? { - type: "assets by status", - [name]: !!key, - filteredChildren: assets.length, - ...assetGroup(children, assets) - } - : { - type: "assets by status", - [name]: !!key, - children, - ...assetGroup(children, assets) - }; - } - }); - }; - const { - groupAssetsByEmitStatus, - groupAssetsByPath, - groupAssetsByExtension - } = options; - if (groupAssetsByEmitStatus) { - groupByFlag("emitted"); - groupByFlag("comparedForEmit"); - groupByFlag("isOverSizeLimit"); - } - if (groupAssetsByEmitStatus || !options.cachedAssets) { - groupByFlag("cached", !options.cachedAssets); - } - if (groupAssetsByPath || groupAssetsByExtension) { - groupConfigs.push({ - getKeys: asset => { - const extensionMatch = - groupAssetsByExtension && GROUP_EXTENSION_REGEXP.exec(asset.name); - const extension = extensionMatch ? extensionMatch[1] : ""; - const pathMatch = - groupAssetsByPath && GROUP_PATH_REGEXP.exec(asset.name); - const path = pathMatch ? pathMatch[1].split(/[/\\]/) : []; - const keys = []; - if (groupAssetsByPath) { - keys.push("."); - if (extension) - keys.push( - path.length - ? `${path.join("/")}/*${extension}` - : `*${extension}` - ); - while (path.length > 0) { - keys.push(path.join("/") + "/"); - path.pop(); + +/***/ }), + +/***/ 26030: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const JavascriptModulesPlugin = __webpack_require__(89464); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ +/** @typedef {import("../util/Hash")} Hash */ + +const COMMON_LIBRARY_NAME_MESSAGE = + "Common configuration options that specific library names are 'output.library[.name]', 'entry.xyz.library[.name]', 'ModuleFederationPlugin.name' and 'ModuleFederationPlugin.library[.name]'."; + +/** + * @template T + * @typedef {Object} LibraryContext + * @property {Compilation} compilation + * @property {ChunkGraph} chunkGraph + * @property {T} options + */ + +/** + * @template T + */ +class AbstractLibraryPlugin { + /** + * @param {Object} options options + * @param {string} options.pluginName name of the plugin + * @param {LibraryType} options.type used library type + */ + constructor({ pluginName, type }) { + this._pluginName = pluginName; + this._type = type; + this._parseCache = new WeakMap(); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { _pluginName } = this; + compiler.hooks.thisCompilation.tap(_pluginName, compilation => { + compilation.hooks.finishModules.tap( + { name: _pluginName, stage: 10 }, + () => { + for (const [ + name, + { + dependencies: deps, + options: { library } + } + ] of compilation.entries) { + const options = this._parseOptionsCached( + library !== undefined + ? library + : compilation.outputOptions.library + ); + if (options !== false) { + const dep = deps[deps.length - 1]; + if (dep) { + const module = compilation.moduleGraph.getModule(dep); + if (module) { + this.finishEntryModule(module, name, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + } + } } - } else { - if (extension) keys.push(`*${extension}`); } - return keys; - }, - createGroup: (key, children, assets) => { - return { - type: groupAssetsByPath ? "assets by path" : "assets by extension", - name: key, - children, - ...assetGroup(children, assets) - }; - } - }); - } - }, - groupAssetsByInfo: (groupConfigs, context, options) => { - const groupByAssetInfoFlag = name => { - groupConfigs.push({ - getKeys: asset => { - return asset.info && asset.info[name] ? ["1"] : undefined; - }, - createGroup: (key, children, assets) => { - return { - type: "assets by info", - info: { - [name]: !!key - }, - children, - ...assetGroup(children, assets) - }; - } - }); - }; - groupByAssetInfoFlag("immutable"); - groupByAssetInfoFlag("development"); - groupByAssetInfoFlag("hotModuleReplacement"); - }, - groupAssetsByChunk: (groupConfigs, context, options) => { - const groupByNames = name => { - groupConfigs.push({ - getKeys: asset => { - return asset[name]; - }, - createGroup: (key, children, assets) => { - return { - type: "assets by chunk", - [name]: [key], - children, - ...assetGroup(children, assets) - }; } + ); + + const getOptionsForChunk = chunk => { + if (compilation.chunkGraph.getNumberOfEntryModules(chunk) === 0) + return false; + const options = chunk.getEntryOptions(); + const library = options && options.library; + return this._parseOptionsCached( + library !== undefined ? library : compilation.outputOptions.library + ); + }; + + if ( + this.render !== AbstractLibraryPlugin.prototype.render || + this.runtimeRequirements !== + AbstractLibraryPlugin.prototype.runtimeRequirements + ) { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + _pluginName, + (chunk, set, { chunkGraph }) => { + const options = getOptionsForChunk(chunk); + if (options !== false) { + this.runtimeRequirements(chunk, set, { + options, + compilation, + chunkGraph + }); + } + } + ); + } + + const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); + + if (this.render !== AbstractLibraryPlugin.prototype.render) { + hooks.render.tap(_pluginName, (source, renderContext) => { + const options = getOptionsForChunk(renderContext.chunk); + if (options === false) return source; + return this.render(source, renderContext, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + }); + } + + if ( + this.embedInRuntimeBailout !== + AbstractLibraryPlugin.prototype.embedInRuntimeBailout + ) { + hooks.embedInRuntimeBailout.tap( + _pluginName, + (module, renderContext) => { + const options = getOptionsForChunk(renderContext.chunk); + if (options === false) return; + return this.embedInRuntimeBailout(module, renderContext, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + } + ); + } + + if ( + this.strictRuntimeBailout !== + AbstractLibraryPlugin.prototype.strictRuntimeBailout + ) { + hooks.strictRuntimeBailout.tap(_pluginName, renderContext => { + const options = getOptionsForChunk(renderContext.chunk); + if (options === false) return; + return this.strictRuntimeBailout(renderContext, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + }); + } + + if ( + this.renderStartup !== AbstractLibraryPlugin.prototype.renderStartup + ) { + hooks.renderStartup.tap( + _pluginName, + (source, module, renderContext) => { + const options = getOptionsForChunk(renderContext.chunk); + if (options === false) return source; + return this.renderStartup(source, module, renderContext, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + } + ); + } + + hooks.chunkHash.tap(_pluginName, (chunk, hash, context) => { + const options = getOptionsForChunk(chunk); + if (options === false) return; + this.chunkHash(chunk, hash, context, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); }); - }; - groupByNames("chunkNames"); - groupByNames("auxiliaryChunkNames"); - groupByNames("chunkIdHints"); - groupByNames("auxiliaryChunkIdHints"); - }, - excludeAssets: (groupConfigs, context, { excludeAssets }) => { - groupConfigs.push({ - getKeys: asset => { - const ident = asset.name; - const excluded = excludeAssets.some(fn => fn(ident, asset)); - if (excluded) return ["excluded"]; - }, - getOptions: () => ({ - groupChildren: false, - force: true - }), - createGroup: (key, children, assets) => ({ - type: "hidden assets", - filteredChildren: assets.length, - ...assetGroup(children, assets) - }) }); } -}; -/** @type {function("module" | "chunk" | "root-of-chunk" | "nested"): Record void>} */ -const MODULES_GROUPERS = type => ({ - _: (groupConfigs, context, options) => { - const groupByFlag = (name, type, exclude) => { - groupConfigs.push({ - getKeys: module => { - return module[name] ? ["1"] : undefined; - }, - getOptions: () => { - return { - groupChildren: !exclude, - force: exclude - }; - }, - createGroup: (key, children, modules) => { - return { + /** + * @param {LibraryOptions=} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + _parseOptionsCached(library) { + if (!library) return false; + if (library.type !== this._type) return false; + const cacheEntry = this._parseCache.get(library); + if (cacheEntry !== undefined) return cacheEntry; + const result = this.parseOptions(library); + this._parseCache.set(library, result); + return result; + } + + /* istanbul ignore next */ + /** + * @abstract + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); + } + + /** + * @param {Module} module the exporting entry module + * @param {string} entryName the name of the entrypoint + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + finishEntryModule(module, entryName, libraryContext) {} + + /** + * @param {Module} module the exporting entry module + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {string | undefined} bailout reason + */ + embedInRuntimeBailout(module, renderContext, libraryContext) { + return undefined; + } + + /** + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {string | undefined} bailout reason + */ + strictRuntimeBailout(renderContext, libraryContext) { + return undefined; + } + + /** + * @param {Chunk} chunk the chunk + * @param {Set} set runtime requirements + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + runtimeRequirements(chunk, set, libraryContext) { + if (this.render !== AbstractLibraryPlugin.prototype.render) + set.add(RuntimeGlobals.returnExportsFromRuntime); + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render(source, renderContext, libraryContext) { + return source; + } + + /** + * @param {Source} source source + * @param {Module} module module + * @param {StartupRenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + renderStartup(source, module, renderContext, libraryContext) { + return source; + } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, libraryContext) { + const options = this._parseOptionsCached( + libraryContext.compilation.outputOptions.library + ); + hash.update(this._pluginName); + hash.update(JSON.stringify(options)); + } +} + +AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE = COMMON_LIBRARY_NAME_MESSAGE; +module.exports = AbstractLibraryPlugin; + + +/***/ }), + +/***/ 67416: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { ConcatSource } = __webpack_require__(51255); +const ExternalModule = __webpack_require__(73071); +const Template = __webpack_require__(39722); +const AbstractLibraryPlugin = __webpack_require__(26030); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +/** + * @typedef {Object} AmdLibraryPluginOptions + * @property {LibraryType} type + * @property {boolean=} requireAsWrapper + */ + +/** + * @typedef {Object} AmdLibraryPluginParsed + * @property {string} name + */ + +/** + * @typedef {AmdLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class AmdLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {AmdLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "AmdLibraryPlugin", + type: options.type + }); + this.requireAsWrapper = options.requireAsWrapper; + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (this.requireAsWrapper) { + if (name) { + throw new Error( + `AMD library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + } else { + if (name && typeof name !== "string") { + throw new Error( + `AMD library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + } + return { + name: /** @type {string=} */ (name) + }; + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render( + source, + { chunkGraph, chunk, runtimeTemplate }, + { options, compilation } + ) { + const modern = runtimeTemplate.supportsArrowFunction(); + const modules = chunkGraph + .getChunkModules(chunk) + .filter(m => m instanceof ExternalModule); + const externals = /** @type {ExternalModule[]} */ (modules); + const externalsDepsArray = JSON.stringify( + externals.map(m => + typeof m.request === "object" && !Array.isArray(m.request) + ? m.request.amd + : m.request + ) + ); + const externalsArguments = externals + .map( + m => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${chunkGraph.getModuleId(m)}` + )}__` + ) + .join(", "); + + const iife = runtimeTemplate.isIIFE(); + const fnStart = + (modern + ? `(${externalsArguments}) => {` + : `function(${externalsArguments}) {`) + + (iife || !chunk.hasRuntime() ? " return " : "\n"); + const fnEnd = iife ? ";\n}" : "\n}"; + + if (this.requireAsWrapper) { + return new ConcatSource( + `require(${externalsDepsArray}, ${fnStart}`, + source, + `${fnEnd});` + ); + } else if (options.name) { + const name = compilation.getPath(options.name, { + chunk + }); + + return new ConcatSource( + `define(${JSON.stringify(name)}, ${externalsDepsArray}, ${fnStart}`, + source, + `${fnEnd});` + ); + } else if (externalsArguments) { + return new ConcatSource( + `define(${externalsDepsArray}, ${fnStart}`, + source, + `${fnEnd});` + ); + } else { + return new ConcatSource(`define(${fnStart}`, source, `${fnEnd});`); + } + } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { + hash.update("AmdLibraryPlugin"); + if (this.requireAsWrapper) { + hash.update("requireAsWrapper"); + } else if (options.name) { + hash.update("named"); + const name = compilation.getPath(options.name, { + chunk + }); + hash.update(name); + } + } +} + +module.exports = AmdLibraryPlugin; + + +/***/ }), + +/***/ 40080: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { ConcatSource } = __webpack_require__(51255); +const { UsageState } = __webpack_require__(63686); +const Template = __webpack_require__(39722); +const propertyAccess = __webpack_require__(54190); +const { getEntryRuntime } = __webpack_require__(17156); +const AbstractLibraryPlugin = __webpack_require__(26030); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +const KEYWORD_REGEX = + /^(await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|super|switch|static|this|throw|try|true|typeof|var|void|while|with|yield)$/; +const IDENTIFIER_REGEX = + /^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/iu; + +/** + * Validates the library name by checking for keywords and valid characters + * @param {string} name name to be validated + * @returns {boolean} true, when valid + */ +const isNameValid = name => { + return !KEYWORD_REGEX.test(name) && IDENTIFIER_REGEX.test(name); +}; + +/** + * @param {string[]} accessor variable plus properties + * @param {number} existingLength items of accessor that are existing already + * @param {boolean=} initLast if the last property should also be initialized to an object + * @returns {string} code to access the accessor while initializing + */ +const accessWithInit = (accessor, existingLength, initLast = false) => { + // This generates for [a, b, c, d]: + // (((a = typeof a === "undefined" ? {} : a).b = a.b || {}).c = a.b.c || {}).d + const base = accessor[0]; + if (accessor.length === 1 && !initLast) return base; + let current = + existingLength > 0 + ? base + : `(${base} = typeof ${base} === "undefined" ? {} : ${base})`; + + // i is the current position in accessor that has been printed + let i = 1; + + // all properties printed so far (excluding base) + let propsSoFar; + + // if there is existingLength, print all properties until this position as property access + if (existingLength > i) { + propsSoFar = accessor.slice(1, existingLength); + i = existingLength; + current += propertyAccess(propsSoFar); + } else { + propsSoFar = []; + } + + // all remaining properties (except the last one when initLast is not set) + // should be printed as initializer + const initUntil = initLast ? accessor.length : accessor.length - 1; + for (; i < initUntil; i++) { + const prop = accessor[i]; + propsSoFar.push(prop); + current = `(${current}${propertyAccess([prop])} = ${base}${propertyAccess( + propsSoFar + )} || {})`; + } + + // print the last property as property access if not yet printed + if (i < accessor.length) + current = `${current}${propertyAccess([accessor[accessor.length - 1]])}`; + + return current; +}; + +/** + * @typedef {Object} AssignLibraryPluginOptions + * @property {LibraryType} type + * @property {string[] | "global"} prefix name prefix + * @property {string | false} declare declare name as variable + * @property {"error"|"static"|"copy"|"assign"} unnamed behavior for unnamed library name + * @property {"copy"|"assign"=} named behavior for named library name + */ + +/** + * @typedef {Object} AssignLibraryPluginParsed + * @property {string | string[]} name + * @property {string | string[] | undefined} export + */ + +/** + * @typedef {AssignLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class AssignLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {AssignLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "AssignLibraryPlugin", + type: options.type + }); + this.prefix = options.prefix; + this.declare = options.declare; + this.unnamed = options.unnamed; + this.named = options.named || "assign"; + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (this.unnamed === "error") { + if (typeof name !== "string" && !Array.isArray(name)) { + throw new Error( + `Library name must be a string or string array. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + } else { + if (name && typeof name !== "string" && !Array.isArray(name)) { + throw new Error( + `Library name must be a string, string array or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + } + return { + name: /** @type {string|string[]=} */ (name), + export: library.export + }; + } + + /** + * @param {Module} module the exporting entry module + * @param {string} entryName the name of the entrypoint + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + finishEntryModule( + module, + entryName, + { options, compilation, compilation: { moduleGraph } } + ) { + const runtime = getEntryRuntime(compilation, entryName); + if (options.export) { + const exportsInfo = moduleGraph.getExportInfo( + module, + Array.isArray(options.export) ? options.export[0] : options.export + ); + exportsInfo.setUsed(UsageState.Used, runtime); + exportsInfo.canMangleUse = false; + } else { + const exportsInfo = moduleGraph.getExportsInfo(module); + exportsInfo.setUsedInUnknownWay(runtime); + } + moduleGraph.addExtraReason(module, "used as library export"); + } + + _getPrefix(compilation) { + return this.prefix === "global" + ? [compilation.runtimeTemplate.globalObject] + : this.prefix; + } + + _getResolvedFullName(options, chunk, compilation) { + const prefix = this._getPrefix(compilation); + const fullName = options.name ? prefix.concat(options.name) : prefix; + return fullName.map(n => + compilation.getPath(n, { + chunk + }) + ); + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render(source, { chunk }, { options, compilation }) { + const fullNameResolved = this._getResolvedFullName( + options, + chunk, + compilation + ); + if (this.declare) { + const base = fullNameResolved[0]; + if (!isNameValid(base)) { + throw new Error( + `Library name base (${base}) must be a valid identifier when using a var declaring library type. Either use a valid identifier (e. g. ${Template.toIdentifier( + base + )}) or use a different library type (e. g. 'type: "global"', which assign a property on the global scope instead of declaring a variable). ${ + AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE + }` + ); + } + source = new ConcatSource(`${this.declare} ${base};\n`, source); + } + return source; + } + + /** + * @param {Module} module the exporting entry module + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {string | undefined} bailout reason + */ + embedInRuntimeBailout(module, { chunk }, { options, compilation }) { + const topLevelDeclarations = + module.buildInfo && module.buildInfo.topLevelDeclarations; + if (!topLevelDeclarations) + return "it doesn't tell about top level declarations."; + const fullNameResolved = this._getResolvedFullName( + options, + chunk, + compilation + ); + const base = fullNameResolved[0]; + if (topLevelDeclarations.has(base)) + return `it declares '${base}' on top-level, which conflicts with the current library output.`; + } + + /** + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {string | undefined} bailout reason + */ + strictRuntimeBailout({ chunk }, { options, compilation }) { + if ( + this.declare || + this.prefix === "global" || + this.prefix.length > 0 || + !options.name + ) { + return; + } + return "a global variable is assign and maybe created"; + } + + /** + * @param {Source} source source + * @param {Module} module module + * @param {StartupRenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + renderStartup( + source, + module, + { moduleGraph, chunk }, + { options, compilation } + ) { + const fullNameResolved = this._getResolvedFullName( + options, + chunk, + compilation + ); + const staticExports = this.unnamed === "static"; + const exportAccess = options.export + ? propertyAccess( + Array.isArray(options.export) ? options.export : [options.export] + ) + : ""; + const result = new ConcatSource(source); + if (staticExports) { + const exportsInfo = moduleGraph.getExportsInfo(module); + const exportTarget = accessWithInit( + fullNameResolved, + this._getPrefix(compilation).length, + true + ); + for (const exportInfo of exportsInfo.orderedExports) { + if (!exportInfo.provided) continue; + const nameAccess = propertyAccess([exportInfo.name]); + result.add( + `${exportTarget}${nameAccess} = __webpack_exports__${exportAccess}${nameAccess};\n` + ); + } + result.add( + `Object.defineProperty(${exportTarget}, "__esModule", { value: true });\n` + ); + } else if (options.name ? this.named === "copy" : this.unnamed === "copy") { + result.add( + `var __webpack_export_target__ = ${accessWithInit( + fullNameResolved, + this._getPrefix(compilation).length, + true + )};\n` + ); + let exports = "__webpack_exports__"; + if (exportAccess) { + result.add( + `var __webpack_exports_export__ = __webpack_exports__${exportAccess};\n` + ); + exports = "__webpack_exports_export__"; + } + result.add( + `for(var i in ${exports}) __webpack_export_target__[i] = ${exports}[i];\n` + ); + result.add( + `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n` + ); + } else { + result.add( + `${accessWithInit( + fullNameResolved, + this._getPrefix(compilation).length, + false + )} = __webpack_exports__${exportAccess};\n` + ); + } + return result; + } + + /** + * @param {Chunk} chunk the chunk + * @param {Set} set runtime requirements + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + runtimeRequirements(chunk, set, libraryContext) { + // we don't need to return exports from runtime + } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { + hash.update("AssignLibraryPlugin"); + const fullNameResolved = this._getResolvedFullName( + options, + chunk, + compilation + ); + if (options.name ? this.named === "copy" : this.unnamed === "copy") { + hash.update("copy"); + } + if (this.declare) { + hash.update(this.declare); + } + hash.update(fullNameResolved.join(".")); + if (options.export) { + hash.update(`${options.export}`); + } + } +} + +module.exports = AssignLibraryPlugin; + + +/***/ }), + +/***/ 91452: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Compiler")} Compiler */ + +/** @type {WeakMap>} */ +const enabledTypes = new WeakMap(); + +const getEnabledTypes = compiler => { + let set = enabledTypes.get(compiler); + if (set === undefined) { + set = new Set(); + enabledTypes.set(compiler, set); + } + return set; +}; + +class EnableLibraryPlugin { + /** + * @param {LibraryType} type library type that should be available + */ + constructor(type) { + this.type = type; + } + + /** + * @param {Compiler} compiler the compiler instance + * @param {LibraryType} type type of library + * @returns {void} + */ + static setEnabled(compiler, type) { + getEnabledTypes(compiler).add(type); + } + + /** + * @param {Compiler} compiler the compiler instance + * @param {LibraryType} type type of library + * @returns {void} + */ + static checkEnabled(compiler, type) { + if (!getEnabledTypes(compiler).has(type)) { + throw new Error( + `Library type "${type}" is not enabled. ` + + "EnableLibraryPlugin need to be used to enable this type of library. " + + 'This usually happens through the "output.enabledLibraryTypes" option. ' + + 'If you are using a function as entry which sets "library", you need to add all potential library types to "output.enabledLibraryTypes". ' + + "These types are enabled: " + + Array.from(getEnabledTypes(compiler)).join(", ") + ); + } + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { type } = this; + + // Only enable once + const enabled = getEnabledTypes(compiler); + if (enabled.has(type)) return; + enabled.add(type); + + if (typeof type === "string") { + const enableExportProperty = () => { + const ExportPropertyTemplatePlugin = __webpack_require__(5487); + new ExportPropertyTemplatePlugin({ + type, + nsObjectUsed: type !== "module" + }).apply(compiler); + }; + switch (type) { + case "var": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ type, - [name]: !!key, - ...(exclude ? { filteredChildren: modules.length } : { children }), - ...moduleGroup(children, modules) - }; + prefix: [], + declare: "var", + unnamed: "error" + }).apply(compiler); + break; } - }); + case "assign-properties": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: [], + declare: false, + unnamed: "error", + named: "copy" + }).apply(compiler); + break; + } + case "assign": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: [], + declare: false, + unnamed: "error" + }).apply(compiler); + break; + } + case "this": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: ["this"], + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "window": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: ["window"], + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "self": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: ["self"], + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "global": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: "global", + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "commonjs": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: ["exports"], + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "commonjs-static": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: ["exports"], + declare: false, + unnamed: "static" + }).apply(compiler); + break; + } + case "commonjs2": + case "commonjs-module": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: ["module", "exports"], + declare: false, + unnamed: "assign" + }).apply(compiler); + break; + } + case "amd": + case "amd-require": { + enableExportProperty(); + const AmdLibraryPlugin = __webpack_require__(67416); + new AmdLibraryPlugin({ + type, + requireAsWrapper: type === "amd-require" + }).apply(compiler); + break; + } + case "umd": + case "umd2": { + enableExportProperty(); + const UmdLibraryPlugin = __webpack_require__(54442); + new UmdLibraryPlugin({ + type, + optionalAmdExternalAsGlobal: type === "umd2" + }).apply(compiler); + break; + } + case "system": { + enableExportProperty(); + const SystemLibraryPlugin = __webpack_require__(11707); + new SystemLibraryPlugin({ + type + }).apply(compiler); + break; + } + case "jsonp": { + enableExportProperty(); + const JsonpLibraryPlugin = __webpack_require__(84415); + new JsonpLibraryPlugin({ + type + }).apply(compiler); + break; + } + case "module": { + enableExportProperty(); + const ModuleLibraryPlugin = __webpack_require__(59780); + new ModuleLibraryPlugin({ + type + }).apply(compiler); + break; + } + default: + throw new Error(`Unsupported library type ${type}. +Plugins which provide custom library types must call EnableLibraryPlugin.setEnabled(compiler, type) to disable this error.`); + } + } else { + // TODO support plugin instances here + // apply them to the compiler + } + } +} + +module.exports = EnableLibraryPlugin; + + +/***/ }), + +/***/ 5487: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { ConcatSource } = __webpack_require__(51255); +const { UsageState } = __webpack_require__(63686); +const propertyAccess = __webpack_require__(54190); +const { getEntryRuntime } = __webpack_require__(17156); +const AbstractLibraryPlugin = __webpack_require__(26030); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +/** + * @typedef {Object} ExportPropertyLibraryPluginParsed + * @property {string | string[]} export + */ + +/** + * @typedef {Object} ExportPropertyLibraryPluginOptions + * @property {LibraryType} type + * @property {boolean} nsObjectUsed the namespace object is used + */ +/** + * @typedef {ExportPropertyLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {ExportPropertyLibraryPluginOptions} options options + */ + constructor({ type, nsObjectUsed }) { + super({ + pluginName: "ExportPropertyLibraryPlugin", + type + }); + this.nsObjectUsed = nsObjectUsed; + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + return { + export: library.export }; - const { - groupModulesByCacheStatus, - groupModulesByLayer, - groupModulesByAttributes, - groupModulesByType, - groupModulesByPath, - groupModulesByExtension - } = options; - if (groupModulesByAttributes) { - groupByFlag("errors", "modules with errors"); - groupByFlag("warnings", "modules with warnings"); - groupByFlag("assets", "modules with assets"); - groupByFlag("optional", "optional modules"); + } + + /** + * @param {Module} module the exporting entry module + * @param {string} entryName the name of the entrypoint + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + finishEntryModule( + module, + entryName, + { options, compilation, compilation: { moduleGraph } } + ) { + const runtime = getEntryRuntime(compilation, entryName); + if (options.export) { + const exportsInfo = moduleGraph.getExportInfo( + module, + Array.isArray(options.export) ? options.export[0] : options.export + ); + exportsInfo.setUsed(UsageState.Used, runtime); + exportsInfo.canMangleUse = false; + } else { + const exportsInfo = moduleGraph.getExportsInfo(module); + if (this.nsObjectUsed) { + exportsInfo.setUsedInUnknownWay(runtime); + } else { + exportsInfo.setAllKnownExportsUsed(runtime); + } + } + moduleGraph.addExtraReason(module, "used as library export"); + } + + /** + * @param {Chunk} chunk the chunk + * @param {Set} set runtime requirements + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + runtimeRequirements(chunk, set, libraryContext) {} + + /** + * @param {Source} source source + * @param {Module} module module + * @param {StartupRenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + renderStartup(source, module, renderContext, { options }) { + if (!options.export) return source; + const postfix = `__webpack_exports__ = __webpack_exports__${propertyAccess( + Array.isArray(options.export) ? options.export : [options.export] + )};\n`; + return new ConcatSource(source, postfix); + } +} + +module.exports = ExportPropertyLibraryPlugin; + + +/***/ }), + +/***/ 84415: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { ConcatSource } = __webpack_require__(51255); +const AbstractLibraryPlugin = __webpack_require__(26030); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +/** + * @typedef {Object} JsonpLibraryPluginOptions + * @property {LibraryType} type + */ + +/** + * @typedef {Object} JsonpLibraryPluginParsed + * @property {string} name + */ + +/** + * @typedef {JsonpLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class JsonpLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {JsonpLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "JsonpLibraryPlugin", + type: options.type + }); + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (typeof name !== "string") { + throw new Error( + `Jsonp library name must be a simple string. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + return { + name: /** @type {string} */ (name) + }; + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render(source, { chunk }, { options, compilation }) { + const name = compilation.getPath(options.name, { + chunk + }); + return new ConcatSource(`${name}(`, source, ")"); + } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { + hash.update("JsonpLibraryPlugin"); + hash.update(compilation.getPath(options.name, { chunk })); + } +} + +module.exports = JsonpLibraryPlugin; + + +/***/ }), + +/***/ 59780: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { ConcatSource } = __webpack_require__(51255); +const Template = __webpack_require__(39722); +const propertyAccess = __webpack_require__(54190); +const AbstractLibraryPlugin = __webpack_require__(26030); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +/** + * @typedef {Object} ModuleLibraryPluginOptions + * @property {LibraryType} type + */ + +/** + * @typedef {Object} ModuleLibraryPluginParsed + * @property {string} name + */ + +/** + * @typedef {ModuleLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class ModuleLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {ModuleLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "ModuleLibraryPlugin", + type: options.type + }); + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (name) { + throw new Error( + `Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + return { + name: /** @type {string} */ (name) + }; + } + + /** + * @param {Source} source source + * @param {Module} module module + * @param {StartupRenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + renderStartup( + source, + module, + { moduleGraph, chunk }, + { options, compilation } + ) { + const result = new ConcatSource(source); + const exportsInfo = moduleGraph.getExportsInfo(module); + const exports = []; + const isAsync = moduleGraph.isAsync(module); + if (isAsync) { + result.add(`__webpack_exports__ = await __webpack_exports__;\n`); + } + for (const exportInfo of exportsInfo.orderedExports) { + if (!exportInfo.provided) continue; + const varName = `__webpack_exports__${Template.toIdentifier( + exportInfo.name + )}`; + result.add( + `var ${varName} = __webpack_exports__${propertyAccess([ + exportInfo.getUsedName(exportInfo.name, chunk.runtime) + ])};\n` + ); + exports.push(`${varName} as ${exportInfo.name}`); + } + if (exports.length > 0) { + result.add(`export { ${exports.join(", ")} };\n`); + } + return result; + } +} + +module.exports = ModuleLibraryPlugin; + + +/***/ }), + +/***/ 11707: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Joel Denning @joeldenning +*/ + + + +const { ConcatSource } = __webpack_require__(51255); +const { UsageState } = __webpack_require__(63686); +const ExternalModule = __webpack_require__(73071); +const Template = __webpack_require__(39722); +const propertyAccess = __webpack_require__(54190); +const AbstractLibraryPlugin = __webpack_require__(26030); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +/** + * @typedef {Object} SystemLibraryPluginOptions + * @property {LibraryType} type + */ + +/** + * @typedef {Object} SystemLibraryPluginParsed + * @property {string} name + */ + +/** + * @typedef {SystemLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class SystemLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {SystemLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "SystemLibraryPlugin", + type: options.type + }); + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (name && typeof name !== "string") { + throw new Error( + `System.js library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + return { + name: /** @type {string=} */ (name) + }; + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render(source, { chunkGraph, moduleGraph, chunk }, { options, compilation }) { + const modules = chunkGraph + .getChunkModules(chunk) + .filter(m => m instanceof ExternalModule && m.externalType === "system"); + const externals = /** @type {ExternalModule[]} */ (modules); + + // The name this bundle should be registered as with System + const name = options.name + ? `${JSON.stringify(compilation.getPath(options.name, { chunk }))}, ` + : ""; + + // The array of dependencies that are external to webpack and will be provided by System + const systemDependencies = JSON.stringify( + externals.map(m => + typeof m.request === "object" && !Array.isArray(m.request) + ? m.request.amd + : m.request + ) + ); + + // The name of the variable provided by System for exporting + const dynamicExport = "__WEBPACK_DYNAMIC_EXPORT__"; + + // An array of the internal variable names for the webpack externals + const externalWebpackNames = externals.map( + m => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${chunkGraph.getModuleId(m)}` + )}__` + ); + + // Declaring variables for the internal variable names for the webpack externals + const externalVarDeclarations = externalWebpackNames + .map(name => `var ${name} = {};`) + .join("\n"); + + // Define __esModule flag on all internal variables and helpers + const externalVarInitialization = []; + + // The system.register format requires an array of setter functions for externals. + const setters = + externalWebpackNames.length === 0 + ? "" + : Template.asString([ + "setters: [", + Template.indent( + externals + .map((module, i) => { + const external = externalWebpackNames[i]; + const exportsInfo = moduleGraph.getExportsInfo(module); + const otherUnused = + exportsInfo.otherExportsInfo.getUsed(chunk.runtime) === + UsageState.Unused; + const instructions = []; + const handledNames = []; + for (const exportInfo of exportsInfo.orderedExports) { + const used = exportInfo.getUsedName( + undefined, + chunk.runtime + ); + if (used) { + if (otherUnused || used !== exportInfo.name) { + instructions.push( + `${external}${propertyAccess([ + used + ])} = module${propertyAccess([exportInfo.name])};` + ); + handledNames.push(exportInfo.name); + } + } else { + handledNames.push(exportInfo.name); + } + } + if (!otherUnused) { + if ( + !Array.isArray(module.request) || + module.request.length === 1 + ) { + externalVarInitialization.push( + `Object.defineProperty(${external}, "__esModule", { value: true });` + ); + } + if (handledNames.length > 0) { + const name = `${external}handledNames`; + externalVarInitialization.push( + `var ${name} = ${JSON.stringify(handledNames)};` + ); + instructions.push( + Template.asString([ + "Object.keys(module).forEach(function(key) {", + Template.indent([ + `if(${name}.indexOf(key) >= 0)`, + Template.indent(`${external}[key] = module[key];`) + ]), + "});" + ]) + ); + } else { + instructions.push( + Template.asString([ + "Object.keys(module).forEach(function(key) {", + Template.indent([`${external}[key] = module[key];`]), + "});" + ]) + ); + } + } + if (instructions.length === 0) return "function() {}"; + return Template.asString([ + "function(module) {", + Template.indent(instructions), + "}" + ]); + }) + .join(",\n") + ), + "]," + ]); + + return new ConcatSource( + Template.asString([ + `System.register(${name}${systemDependencies}, function(${dynamicExport}, __system_context__) {`, + Template.indent([ + externalVarDeclarations, + Template.asString(externalVarInitialization), + "return {", + Template.indent([ + setters, + "execute: function() {", + Template.indent(`${dynamicExport}(`) + ]) + ]), + "" + ]), + source, + Template.asString([ + "", + Template.indent([ + Template.indent([Template.indent([");"]), "}"]), + "};" + ]), + "})" + ]) + ); + } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { + hash.update("SystemLibraryPlugin"); + if (options.name) { + hash.update(compilation.getPath(options.name, { chunk })); + } + } +} + +module.exports = SystemLibraryPlugin; + + +/***/ }), + +/***/ 54442: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { ConcatSource, OriginalSource } = __webpack_require__(51255); +const ExternalModule = __webpack_require__(73071); +const Template = __webpack_require__(39722); +const AbstractLibraryPlugin = __webpack_require__(26030); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryCustomUmdCommentObject} LibraryCustomUmdCommentObject */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +}; + +/** + * @param {string|undefined} base the path prefix + * @param {string|string[]} accessor the accessor + * @param {string=} joinWith the element separator + * @returns {string} the path + */ +const accessorAccess = (base, accessor, joinWith = ", ") => { + const accessors = Array.isArray(accessor) ? accessor : [accessor]; + return accessors + .map((_, idx) => { + const a = base + ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) + : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); + if (idx === accessors.length - 1) return a; + if (idx === 0 && base === undefined) + return `${a} = typeof ${a} === "object" ? ${a} : {}`; + return `${a} = ${a} || {}`; + }) + .join(joinWith); +}; + +/** @typedef {string | string[] | LibraryCustomUmdObject} UmdLibraryPluginName */ + +/** + * @typedef {Object} UmdLibraryPluginOptions + * @property {LibraryType} type + * @property {boolean=} optionalAmdExternalAsGlobal + */ + +/** + * @typedef {Object} UmdLibraryPluginParsed + * @property {string | string[]} name + * @property {LibraryCustomUmdObject} names + * @property {string | LibraryCustomUmdCommentObject} auxiliaryComment + * @property {boolean} namedDefine + */ + +/** + * @typedef {UmdLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class UmdLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {UmdLibraryPluginOptions} options the plugin option + */ + constructor(options) { + super({ + pluginName: "UmdLibraryPlugin", + type: options.type + }); + + this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal; + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + /** @type {LibraryName} */ + let name; + /** @type {LibraryCustomUmdObject} */ + let names; + if (typeof library.name === "object" && !Array.isArray(library.name)) { + name = library.name.root || library.name.amd || library.name.commonjs; + names = library.name; + } else { + name = library.name; + const singleName = Array.isArray(name) ? name[0] : name; + names = { + commonjs: singleName, + root: library.name, + amd: singleName + }; + } + return { + name, + names, + auxiliaryComment: library.auxiliaryComment, + namedDefine: library.umdNamedDefine + }; + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render( + source, + { chunkGraph, runtimeTemplate, chunk, moduleGraph }, + { options, compilation } + ) { + const modules = chunkGraph + .getChunkModules(chunk) + .filter( + m => + m instanceof ExternalModule && + (m.externalType === "umd" || m.externalType === "umd2") + ); + let externals = /** @type {ExternalModule[]} */ (modules); + /** @type {ExternalModule[]} */ + const optionalExternals = []; + /** @type {ExternalModule[]} */ + let requiredExternals = []; + if (this.optionalAmdExternalAsGlobal) { + for (const m of externals) { + if (m.isOptional(moduleGraph)) { + optionalExternals.push(m); + } else { + requiredExternals.push(m); + } + } + externals = requiredExternals.concat(optionalExternals); + } else { + requiredExternals = externals; + } + + const replaceKeys = str => { + return compilation.getPath(str, { + chunk + }); + }; + + const externalsDepsArray = modules => { + return `[${replaceKeys( + modules + .map(m => + JSON.stringify( + typeof m.request === "object" ? m.request.amd : m.request + ) + ) + .join(", ") + )}]`; + }; + + const externalsRootArray = modules => { + return replaceKeys( + modules + .map(m => { + let request = m.request; + if (typeof request === "object") request = request.root; + return `root${accessorToObjectAccess([].concat(request))}`; + }) + .join(", ") + ); + }; + + const externalsRequireArray = type => { + return replaceKeys( + externals + .map(m => { + let expr; + let request = m.request; + if (typeof request === "object") { + request = request[type]; + } + if (request === undefined) { + throw new Error( + "Missing external configuration for type:" + type + ); + } + if (Array.isArray(request)) { + expr = `require(${JSON.stringify( + request[0] + )})${accessorToObjectAccess(request.slice(1))}`; + } else { + expr = `require(${JSON.stringify(request)})`; + } + if (m.isOptional(moduleGraph)) { + expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; + } + return expr; + }) + .join(", ") + ); + }; + + const externalsArguments = modules => { + return modules + .map( + m => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${chunkGraph.getModuleId(m)}` + )}__` + ) + .join(", "); + }; + + const libraryName = library => { + return JSON.stringify(replaceKeys([].concat(library).pop())); + }; + + let amdFactory; + if (optionalExternals.length > 0) { + const wrapperArguments = externalsArguments(requiredExternals); + const factoryArguments = + requiredExternals.length > 0 + ? externalsArguments(requiredExternals) + + ", " + + externalsRootArray(optionalExternals) + : externalsRootArray(optionalExternals); + amdFactory = + `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` + + ` return factory(${factoryArguments});\n` + + " }"; + } else { + amdFactory = "factory"; + } + + const { auxiliaryComment, namedDefine, names } = options; + + const getAuxiliaryComment = type => { + if (auxiliaryComment) { + if (typeof auxiliaryComment === "string") + return "\t//" + auxiliaryComment + "\n"; + if (auxiliaryComment[type]) + return "\t//" + auxiliaryComment[type] + "\n"; + } + return ""; + }; + + return new ConcatSource( + new OriginalSource( + "(function webpackUniversalModuleDefinition(root, factory) {\n" + + getAuxiliaryComment("commonjs2") + + " if(typeof exports === 'object' && typeof module === 'object')\n" + + " module.exports = factory(" + + externalsRequireArray("commonjs2") + + ");\n" + + getAuxiliaryComment("amd") + + " else if(typeof define === 'function' && define.amd)\n" + + (requiredExternals.length > 0 + ? names.amd && namedDefine === true + ? " define(" + + libraryName(names.amd) + + ", " + + externalsDepsArray(requiredExternals) + + ", " + + amdFactory + + ");\n" + : " define(" + + externalsDepsArray(requiredExternals) + + ", " + + amdFactory + + ");\n" + : names.amd && namedDefine === true + ? " define(" + + libraryName(names.amd) + + ", [], " + + amdFactory + + ");\n" + : " define([], " + amdFactory + ");\n") + + (names.root || names.commonjs + ? getAuxiliaryComment("commonjs") + + " else if(typeof exports === 'object')\n" + + " exports[" + + libraryName(names.commonjs || names.root) + + "] = factory(" + + externalsRequireArray("commonjs") + + ");\n" + + getAuxiliaryComment("root") + + " else\n" + + " " + + replaceKeys( + accessorAccess("root", names.root || names.commonjs) + ) + + " = factory(" + + externalsRootArray(externals) + + ");\n" + : " else {\n" + + (externals.length > 0 + ? " var a = typeof exports === 'object' ? factory(" + + externalsRequireArray("commonjs") + + ") : factory(" + + externalsRootArray(externals) + + ");\n" + : " var a = factory();\n") + + " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" + + " }\n") + + `})(${ + runtimeTemplate.outputOptions.globalObject + }, function(${externalsArguments(externals)}) {\nreturn `, + "webpack/universalModuleDefinition" + ), + source, + ";\n})" + ); + } +} + +module.exports = UmdLibraryPlugin; + + +/***/ }), + +/***/ 32597: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const LogType = Object.freeze({ + error: /** @type {"error"} */ ("error"), // message, c style arguments + warn: /** @type {"warn"} */ ("warn"), // message, c style arguments + info: /** @type {"info"} */ ("info"), // message, c style arguments + log: /** @type {"log"} */ ("log"), // message, c style arguments + debug: /** @type {"debug"} */ ("debug"), // message, c style arguments + + trace: /** @type {"trace"} */ ("trace"), // no arguments + + group: /** @type {"group"} */ ("group"), // [label] + groupCollapsed: /** @type {"groupCollapsed"} */ ("groupCollapsed"), // [label] + groupEnd: /** @type {"groupEnd"} */ ("groupEnd"), // [label] + + profile: /** @type {"profile"} */ ("profile"), // [profileName] + profileEnd: /** @type {"profileEnd"} */ ("profileEnd"), // [profileName] + + time: /** @type {"time"} */ ("time"), // name, time as [seconds, nanoseconds] + + clear: /** @type {"clear"} */ ("clear"), // no arguments + status: /** @type {"status"} */ ("status") // message, arguments +}); + +exports.LogType = LogType; + +/** @typedef {typeof LogType[keyof typeof LogType]} LogTypeEnum */ + +const LOG_SYMBOL = Symbol("webpack logger raw log method"); +const TIMERS_SYMBOL = Symbol("webpack logger times"); +const TIMERS_AGGREGATES_SYMBOL = Symbol("webpack logger aggregated times"); + +class WebpackLogger { + /** + * @param {function(LogTypeEnum, any[]=): void} log log function + * @param {function(string | function(): string): WebpackLogger} getChildLogger function to create child logger + */ + constructor(log, getChildLogger) { + this[LOG_SYMBOL] = log; + this.getChildLogger = getChildLogger; + } + + error(...args) { + this[LOG_SYMBOL](LogType.error, args); + } + + warn(...args) { + this[LOG_SYMBOL](LogType.warn, args); + } + + info(...args) { + this[LOG_SYMBOL](LogType.info, args); + } + + log(...args) { + this[LOG_SYMBOL](LogType.log, args); + } + + debug(...args) { + this[LOG_SYMBOL](LogType.debug, args); + } + + assert(assertion, ...args) { + if (!assertion) { + this[LOG_SYMBOL](LogType.error, args); + } + } + + trace() { + this[LOG_SYMBOL](LogType.trace, ["Trace"]); + } + + clear() { + this[LOG_SYMBOL](LogType.clear); + } + + status(...args) { + this[LOG_SYMBOL](LogType.status, args); + } + + group(...args) { + this[LOG_SYMBOL](LogType.group, args); + } + + groupCollapsed(...args) { + this[LOG_SYMBOL](LogType.groupCollapsed, args); + } + + groupEnd(...args) { + this[LOG_SYMBOL](LogType.groupEnd, args); + } + + profile(label) { + this[LOG_SYMBOL](LogType.profile, [label]); + } + + profileEnd(label) { + this[LOG_SYMBOL](LogType.profileEnd, [label]); + } + + time(label) { + this[TIMERS_SYMBOL] = this[TIMERS_SYMBOL] || new Map(); + this[TIMERS_SYMBOL].set(label, process.hrtime()); + } + + timeLog(label) { + const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); + if (!prev) { + throw new Error(`No such label '${label}' for WebpackLogger.timeLog()`); + } + const time = process.hrtime(prev); + this[LOG_SYMBOL](LogType.time, [label, ...time]); + } + + timeEnd(label) { + const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); + if (!prev) { + throw new Error(`No such label '${label}' for WebpackLogger.timeEnd()`); + } + const time = process.hrtime(prev); + this[TIMERS_SYMBOL].delete(label); + this[LOG_SYMBOL](LogType.time, [label, ...time]); + } + + timeAggregate(label) { + const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); + if (!prev) { + throw new Error( + `No such label '${label}' for WebpackLogger.timeAggregate()` + ); + } + const time = process.hrtime(prev); + this[TIMERS_SYMBOL].delete(label); + this[TIMERS_AGGREGATES_SYMBOL] = + this[TIMERS_AGGREGATES_SYMBOL] || new Map(); + const current = this[TIMERS_AGGREGATES_SYMBOL].get(label); + if (current !== undefined) { + if (time[1] + current[1] > 1e9) { + time[0] += current[0] + 1; + time[1] = time[1] - 1e9 + current[1]; + } else { + time[0] += current[0]; + time[1] += current[1]; + } + } + this[TIMERS_AGGREGATES_SYMBOL].set(label, time); + } + + timeAggregateEnd(label) { + if (this[TIMERS_AGGREGATES_SYMBOL] === undefined) return; + const time = this[TIMERS_AGGREGATES_SYMBOL].get(label); + if (time === undefined) return; + this[TIMERS_AGGREGATES_SYMBOL].delete(label); + this[LOG_SYMBOL](LogType.time, [label, ...time]); + } +} + +exports.Logger = WebpackLogger; + + +/***/ }), + +/***/ 54963: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { LogType } = __webpack_require__(32597); + +/** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */ +/** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */ +/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ + +/** @typedef {function(string): boolean} FilterFunction */ + +/** + * @typedef {Object} LoggerConsole + * @property {function(): void} clear + * @property {function(): void} trace + * @property {(...args: any[]) => void} info + * @property {(...args: any[]) => void} log + * @property {(...args: any[]) => void} warn + * @property {(...args: any[]) => void} error + * @property {(...args: any[]) => void=} debug + * @property {(...args: any[]) => void=} group + * @property {(...args: any[]) => void=} groupCollapsed + * @property {(...args: any[]) => void=} groupEnd + * @property {(...args: any[]) => void=} status + * @property {(...args: any[]) => void=} profile + * @property {(...args: any[]) => void=} profileEnd + * @property {(...args: any[]) => void=} logTime + */ + +/** + * @typedef {Object} LoggerOptions + * @property {false|true|"none"|"error"|"warn"|"info"|"log"|"verbose"} level loglevel + * @property {FilterTypes|boolean} debug filter for debug logging + * @property {LoggerConsole} console the console to log to + */ + +/** + * @param {FilterItemTypes} item an input item + * @returns {FilterFunction} filter function + */ +const filterToFunction = item => { + if (typeof item === "string") { + const regExp = new RegExp( + `[\\\\/]${item.replace( + // eslint-disable-next-line no-useless-escape + /[-[\]{}()*+?.\\^$|]/g, + "\\$&" + )}([\\\\/]|$|!|\\?)` + ); + return ident => regExp.test(ident); + } + if (item && typeof item === "object" && typeof item.test === "function") { + return ident => item.test(ident); + } + if (typeof item === "function") { + return item; + } + if (typeof item === "boolean") { + return () => item; + } +}; + +/** + * @enum {number} + */ +const LogLevel = { + none: 6, + false: 6, + error: 5, + warn: 4, + info: 3, + log: 2, + true: 2, + verbose: 1 +}; + +/** + * @param {LoggerOptions} options options object + * @returns {function(string, LogTypeEnum, any[]): void} logging function + */ +module.exports = ({ level = "info", debug = false, console }) => { + const debugFilters = + typeof debug === "boolean" + ? [() => debug] + : /** @type {FilterItemTypes[]} */ ([]) + .concat(debug) + .map(filterToFunction); + /** @type {number} */ + const loglevel = LogLevel[`${level}`] || 0; + + /** + * @param {string} name name of the logger + * @param {LogTypeEnum} type type of the log entry + * @param {any[]} args arguments of the log entry + * @returns {void} + */ + const logger = (name, type, args) => { + const labeledArgs = () => { + if (Array.isArray(args)) { + if (args.length > 0 && typeof args[0] === "string") { + return [`[${name}] ${args[0]}`, ...args.slice(1)]; + } else { + return [`[${name}]`, ...args]; + } + } else { + return []; + } + }; + const debug = debugFilters.some(f => f(name)); + switch (type) { + case LogType.debug: + if (!debug) return; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.debug === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.debug(...labeledArgs()); + } else { + console.log(...labeledArgs()); + } + break; + case LogType.log: + if (!debug && loglevel > LogLevel.log) return; + console.log(...labeledArgs()); + break; + case LogType.info: + if (!debug && loglevel > LogLevel.info) return; + console.info(...labeledArgs()); + break; + case LogType.warn: + if (!debug && loglevel > LogLevel.warn) return; + console.warn(...labeledArgs()); + break; + case LogType.error: + if (!debug && loglevel > LogLevel.error) return; + console.error(...labeledArgs()); + break; + case LogType.trace: + if (!debug) return; + console.trace(); + break; + case LogType.groupCollapsed: + if (!debug && loglevel > LogLevel.log) return; + if (!debug && loglevel > LogLevel.verbose) { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.groupCollapsed === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.groupCollapsed(...labeledArgs()); + } else { + console.log(...labeledArgs()); + } + break; + } + // falls through + case LogType.group: + if (!debug && loglevel > LogLevel.log) return; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.group === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.group(...labeledArgs()); + } else { + console.log(...labeledArgs()); + } + break; + case LogType.groupEnd: + if (!debug && loglevel > LogLevel.log) return; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.groupEnd === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.groupEnd(); + } + break; + case LogType.time: { + if (!debug && loglevel > LogLevel.log) return; + const ms = args[1] * 1000 + args[2] / 1000000; + const msg = `[${name}] ${args[0]}: ${ms} ms`; + if (typeof console.logTime === "function") { + console.logTime(msg); + } else { + console.log(msg); + } + break; + } + case LogType.profile: + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.profile === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.profile(...labeledArgs()); + } + break; + case LogType.profileEnd: + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.profileEnd === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.profileEnd(...labeledArgs()); + } + break; + case LogType.clear: + if (!debug && loglevel > LogLevel.log) return; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.clear === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.clear(); + } + break; + case LogType.status: + if (!debug && loglevel > LogLevel.info) return; + if (typeof console.status === "function") { + if (args.length === 0) { + console.status(); + } else { + console.status(...labeledArgs()); + } + } else { + if (args.length !== 0) { + console.info(...labeledArgs()); + } + } + break; + default: + throw new Error(`Unexpected LogType ${type}`); + } + }; + return logger; +}; + + +/***/ }), + +/***/ 62090: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const arraySum = array => { + let sum = 0; + for (const item of array) sum += item; + return sum; +}; + +/** + * @param {any[]} args items to be truncated + * @param {number} maxLength maximum length of args including spaces between + * @returns {string[]} truncated args + */ +const truncateArgs = (args, maxLength) => { + const lengths = args.map(a => `${a}`.length); + const availableLength = maxLength - lengths.length + 1; + + if (availableLength > 0 && args.length === 1) { + if (availableLength >= args[0].length) { + return args; + } else if (availableLength > 3) { + return ["..." + args[0].slice(-availableLength + 3)]; + } else { + return [args[0].slice(-availableLength)]; + } + } + + // Check if there is space for at least 4 chars per arg + if (availableLength < arraySum(lengths.map(i => Math.min(i, 6)))) { + // remove args + if (args.length > 1) + return truncateArgs(args.slice(0, args.length - 1), maxLength); + return []; + } + + let currentLength = arraySum(lengths); + + // Check if all fits into maxLength + if (currentLength <= availableLength) return args; + + // Try to remove chars from the longest items until it fits + while (currentLength > availableLength) { + const maxLength = Math.max(...lengths); + const shorterItems = lengths.filter(l => l !== maxLength); + const nextToMaxLength = + shorterItems.length > 0 ? Math.max(...shorterItems) : 0; + const maxReduce = maxLength - nextToMaxLength; + let maxItems = lengths.length - shorterItems.length; + let overrun = currentLength - availableLength; + for (let i = 0; i < lengths.length; i++) { + if (lengths[i] === maxLength) { + const reduce = Math.min(Math.floor(overrun / maxItems), maxReduce); + lengths[i] -= reduce; + currentLength -= reduce; + overrun -= reduce; + maxItems--; + } + } + } + + // Return args reduced to length in lengths + return args.map((a, i) => { + const str = `${a}`; + const length = lengths[i]; + if (str.length === length) { + return str; + } else if (length > 5) { + return "..." + str.slice(-length + 3); + } else if (length > 0) { + return str.slice(-length); + } else { + return ""; + } + }); +}; + +module.exports = truncateArgs; + + +/***/ }), + +/***/ 1313: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const StartupChunkDependenciesPlugin = __webpack_require__(22339); + +/** @typedef {import("../Compiler")} Compiler */ + +class CommonJsChunkLoadingPlugin { + constructor(options) { + options = options || {}; + this._asyncChunkLoading = options.asyncChunkLoading; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const ChunkLoadingRuntimeModule = this._asyncChunkLoading + ? __webpack_require__(73369) + : __webpack_require__(94172); + const chunkLoadingValue = this._asyncChunkLoading + ? "async-node" + : "require"; + new StartupChunkDependenciesPlugin({ + chunkLoading: chunkLoadingValue, + asyncChunkLoading: this._asyncChunkLoading + }).apply(compiler); + compiler.hooks.thisCompilation.tap( + "CommonJsChunkLoadingPlugin", + compilation => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === chunkLoadingValue; + }; + const onceForChunkSet = new WeakSet(); + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new ChunkLoadingRuntimeModule(set) + ); + }; + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("CommonJsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap("CommonJsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap("CommonJsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap("CommonJsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.externalInstallChunk) + .tap("CommonJsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap("CommonJsChunkLoadingPlugin", handler); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.getChunkScriptFilename); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.getChunkUpdateScriptFilename); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.hmrModuleData); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.getUpdateManifestFilename); + }); + } + ); + } +} + +module.exports = CommonJsChunkLoadingPlugin; + + +/***/ }), + +/***/ 7553: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const CachedInputFileSystem = __webpack_require__(89429); +const fs = __webpack_require__(90552); +const createConsoleLogger = __webpack_require__(54963); +const NodeWatchFileSystem = __webpack_require__(98810); +const nodeConsole = __webpack_require__(91786); + +/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */ +/** @typedef {import("../Compiler")} Compiler */ + +class NodeEnvironmentPlugin { + /** + * @param {Object} options options + * @param {InfrastructureLogging} options.infrastructureLogging infrastructure logging options + */ + constructor(options) { + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { infrastructureLogging } = this.options; + compiler.infrastructureLogger = createConsoleLogger({ + level: infrastructureLogging.level || "info", + debug: infrastructureLogging.debug || false, + console: + infrastructureLogging.console || + nodeConsole({ + colors: infrastructureLogging.colors, + appendOnly: infrastructureLogging.appendOnly, + stream: infrastructureLogging.stream + }) + }); + compiler.inputFileSystem = new CachedInputFileSystem(fs, 60000); + const inputFileSystem = compiler.inputFileSystem; + compiler.outputFileSystem = fs; + compiler.intermediateFileSystem = fs; + compiler.watchFileSystem = new NodeWatchFileSystem( + compiler.inputFileSystem + ); + compiler.hooks.beforeRun.tap("NodeEnvironmentPlugin", compiler => { + if (compiler.inputFileSystem === inputFileSystem) { + compiler.fsStartTime = Date.now(); + inputFileSystem.purge(); + } + }); + } +} + +module.exports = NodeEnvironmentPlugin; + + +/***/ }), + +/***/ 7103: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("../Compiler")} Compiler */ + +class NodeSourcePlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) {} +} + +module.exports = NodeSourcePlugin; + + +/***/ }), + +/***/ 17916: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const ExternalsPlugin = __webpack_require__(6652); + +/** @typedef {import("../Compiler")} Compiler */ + +const builtins = [ + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "diagnostics_channel", + "dns", + "dns/promises", + "domain", + "events", + "fs", + "fs/promises", + "http", + "http2", + "https", + "inspector", + "module", + "net", + "os", + "path", + "path/posix", + "path/win32", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "stream/promises", + "stream/web", + "string_decoder", + "sys", + "timers", + "timers/promises", + "tls", + "trace_events", + "tty", + "url", + "util", + "v8", + "vm", + "wasi", + "worker_threads", + "zlib", + /^node:/, + + // cspell:word pnpapi + // Yarn PnP adds pnpapi as "builtin" + "pnpapi" +]; + +class NodeTargetPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + new ExternalsPlugin("node-commonjs", builtins).apply(compiler); + } +} + +module.exports = NodeTargetPlugin; + + +/***/ }), + +/***/ 61052: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const CommonJsChunkFormatPlugin = __webpack_require__(84508); +const EnableChunkLoadingPlugin = __webpack_require__(61291); + +/** @typedef {import("../Compiler")} Compiler */ + +class NodeTemplatePlugin { + constructor(options) { + this._options = options || {}; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const chunkLoading = this._options.asyncChunkLoading + ? "async-node" + : "require"; + compiler.options.output.chunkLoading = chunkLoading; + new CommonJsChunkFormatPlugin().apply(compiler); + new EnableChunkLoadingPlugin(chunkLoading).apply(compiler); + } +} + +module.exports = NodeTemplatePlugin; + + +/***/ }), + +/***/ 98810: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const util = __webpack_require__(73837); +const Watchpack = __webpack_require__(36871); + +/** @typedef {import("../../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("../FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ +/** @typedef {import("../util/fs").WatchFileSystem} WatchFileSystem */ +/** @typedef {import("../util/fs").WatchMethod} WatchMethod */ +/** @typedef {import("../util/fs").Watcher} Watcher */ + +class NodeWatchFileSystem { + constructor(inputFileSystem) { + this.inputFileSystem = inputFileSystem; + this.watcherOptions = { + aggregateTimeout: 0 + }; + this.watcher = new Watchpack(this.watcherOptions); + } + + /** + * @param {Iterable} files watched files + * @param {Iterable} directories watched directories + * @param {Iterable} missing watched exitance entries + * @param {number} startTime timestamp of start time + * @param {WatchOptions} options options object + * @param {function(Error=, Map, Map, Set, Set): void} callback aggregated callback + * @param {function(string, number): void} callbackUndelayed callback when the first change was detected + * @returns {Watcher} a watcher + */ + watch( + files, + directories, + missing, + startTime, + options, + callback, + callbackUndelayed + ) { + if (!files || typeof files[Symbol.iterator] !== "function") { + throw new Error("Invalid arguments: 'files'"); + } + if (!directories || typeof directories[Symbol.iterator] !== "function") { + throw new Error("Invalid arguments: 'directories'"); + } + if (!missing || typeof missing[Symbol.iterator] !== "function") { + throw new Error("Invalid arguments: 'missing'"); + } + if (typeof callback !== "function") { + throw new Error("Invalid arguments: 'callback'"); + } + if (typeof startTime !== "number" && startTime) { + throw new Error("Invalid arguments: 'startTime'"); + } + if (typeof options !== "object") { + throw new Error("Invalid arguments: 'options'"); + } + if (typeof callbackUndelayed !== "function" && callbackUndelayed) { + throw new Error("Invalid arguments: 'callbackUndelayed'"); + } + const oldWatcher = this.watcher; + this.watcher = new Watchpack(options); + + if (callbackUndelayed) { + this.watcher.once("change", callbackUndelayed); + } + + const fetchTimeInfo = () => { + const fileTimeInfoEntries = new Map(); + const contextTimeInfoEntries = new Map(); + if (this.watcher) { + this.watcher.collectTimeInfoEntries( + fileTimeInfoEntries, + contextTimeInfoEntries + ); + } + return { fileTimeInfoEntries, contextTimeInfoEntries }; + }; + this.watcher.once("aggregated", (changes, removals) => { + // pause emitting events (avoids clearing aggregated changes and removals on timeout) + this.watcher.pause(); + + if (this.inputFileSystem && this.inputFileSystem.purge) { + const fs = this.inputFileSystem; + for (const item of changes) { + fs.purge(item); + } + for (const item of removals) { + fs.purge(item); + } + } + const { fileTimeInfoEntries, contextTimeInfoEntries } = fetchTimeInfo(); + callback( + null, + fileTimeInfoEntries, + contextTimeInfoEntries, + changes, + removals + ); + }); + + this.watcher.watch({ files, directories, missing, startTime }); + + if (oldWatcher) { + oldWatcher.close(); + } + return { + close: () => { + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + }, + pause: () => { + if (this.watcher) { + this.watcher.pause(); + } + }, + getAggregatedRemovals: util.deprecate( + () => { + const items = this.watcher && this.watcher.aggregatedRemovals; + if (items && this.inputFileSystem && this.inputFileSystem.purge) { + const fs = this.inputFileSystem; + for (const item of items) { + fs.purge(item); + } + } + return items; + }, + "Watcher.getAggregatedRemovals is deprecated in favor of Watcher.getInfo since that's more performant.", + "DEP_WEBPACK_WATCHER_GET_AGGREGATED_REMOVALS" + ), + getAggregatedChanges: util.deprecate( + () => { + const items = this.watcher && this.watcher.aggregatedChanges; + if (items && this.inputFileSystem && this.inputFileSystem.purge) { + const fs = this.inputFileSystem; + for (const item of items) { + fs.purge(item); + } + } + return items; + }, + "Watcher.getAggregatedChanges is deprecated in favor of Watcher.getInfo since that's more performant.", + "DEP_WEBPACK_WATCHER_GET_AGGREGATED_CHANGES" + ), + getFileTimeInfoEntries: util.deprecate( + () => { + return fetchTimeInfo().fileTimeInfoEntries; + }, + "Watcher.getFileTimeInfoEntries is deprecated in favor of Watcher.getInfo since that's more performant.", + "DEP_WEBPACK_WATCHER_FILE_TIME_INFO_ENTRIES" + ), + getContextTimeInfoEntries: util.deprecate( + () => { + return fetchTimeInfo().contextTimeInfoEntries; + }, + "Watcher.getContextTimeInfoEntries is deprecated in favor of Watcher.getInfo since that's more performant.", + "DEP_WEBPACK_WATCHER_CONTEXT_TIME_INFO_ENTRIES" + ), + getInfo: () => { + const removals = this.watcher && this.watcher.aggregatedRemovals; + const changes = this.watcher && this.watcher.aggregatedChanges; + if (this.inputFileSystem && this.inputFileSystem.purge) { + const fs = this.inputFileSystem; + if (removals) { + for (const item of removals) { + fs.purge(item); + } + } + if (changes) { + for (const item of changes) { + fs.purge(item); + } + } + } + const { fileTimeInfoEntries, contextTimeInfoEntries } = fetchTimeInfo(); + return { + changes, + removals, + fileTimeInfoEntries, + contextTimeInfoEntries + }; + } + }; + } +} + +module.exports = NodeWatchFileSystem; + + +/***/ }), + +/***/ 73369: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); +const { + chunkHasJs, + getChunkFilenameTemplate +} = __webpack_require__(89464); +const { getInitialChunkIds } = __webpack_require__(98124); +const compileBooleanMatcher = __webpack_require__(29404); +const { getUndoPath } = __webpack_require__(82186); + +class ReadFileChunkLoadingRuntimeModule extends RuntimeModule { + constructor(runtimeRequirements) { + super("readFile chunk loading", RuntimeModule.STAGE_ATTACH); + this.runtimeRequirements = runtimeRequirements; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { chunkGraph, chunk } = this; + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); + const withExternalInstallChunk = this.runtimeRequirements.has( + RuntimeGlobals.externalInstallChunk + ); + const withOnChunkLoad = this.runtimeRequirements.has( + RuntimeGlobals.onChunksLoaded + ); + const withLoading = this.runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withHmr = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); + const hasJsMatcher = compileBooleanMatcher(conditionMap); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + + const outputName = this.compilation.getPath( + getChunkFilenameTemplate(chunk, this.compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath( + outputName, + this.compilation.outputOptions.path, + false + ); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_readFileVm` + : undefined; + + return Template.asString([ + withBaseURI + ? Template.asString([ + `${RuntimeGlobals.baseURI} = require("url").pathToFileURL(${ + rootOutputDir + ? `__dirname + ${JSON.stringify("/" + rootOutputDir)}` + : "__filename" + });` + ]) + : "// no baseURI", + "", + "// object to store loaded chunks", + '// "0" means "already loaded", Promise means loading', + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join( + ",\n" + ) + ), + "};", + "", + withOnChunkLoad + ? `${ + RuntimeGlobals.onChunksLoaded + }.readFileVm = ${runtimeTemplate.returningFunction( + "installedChunks[chunkId] === 0", + "chunkId" + )};` + : "// no on chunks loaded", + "", + withLoading || withExternalInstallChunk + ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [ + "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent([ + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ]), + "}" + ]), + "}", + `if(runtime) runtime(__webpack_require__);`, + "for(var i = 0; i < chunkIds.length; i++) {", + Template.indent([ + "if(installedChunks[chunkIds[i]]) {", + Template.indent(["installedChunks[chunkIds[i]][0]();"]), + "}", + "installedChunks[chunkIds[i]] = 0;" + ]), + "}", + withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" + ])};` + : "// no chunk install function needed", + "", + withLoading + ? Template.asString([ + "// ReadFile + VM.run chunk loading for javascript", + `${fn}.readFileVm = function(chunkId, promises) {`, + hasJsMatcher !== false + ? Template.indent([ + "", + "var installedChunkData = installedChunks[chunkId];", + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + '// array of [resolve, reject, promise] means "currently loading"', + "if(installedChunkData) {", + Template.indent(["promises.push(installedChunkData[2]);"]), + "} else {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent([ + "// load the chunk and return promise to it", + "var promise = new Promise(function(resolve, reject) {", + Template.indent([ + "installedChunkData = installedChunks[chunkId] = [resolve, reject];", + `var filename = require('path').join(__dirname, ${JSON.stringify( + rootOutputDir + )} + ${ + RuntimeGlobals.getChunkScriptFilename + }(chunkId));`, + "require('fs').readFile(filename, 'utf-8', function(err, content) {", + Template.indent([ + "if(err) return reject(err);", + "var chunk = {};", + "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + + "(chunk, require, require('path').dirname(filename), filename);", + "installChunk(chunk);" + ]), + "});" + ]), + "});", + "promises.push(installedChunkData[2] = promise);" + ]), + "} else installedChunks[chunkId] = 0;" + ]), + "}" + ]), + "}" + ]) + : Template.indent(["installedChunks[chunkId] = 0;"]), + "};" + ]) + : "// no chunk loading", + "", + withExternalInstallChunk + ? Template.asString([ + "module.exports = __webpack_require__;", + `${RuntimeGlobals.externalInstallChunk} = installChunk;` + ]) + : "// no external install chunk", + "", + withHmr + ? Template.asString([ + "function loadUpdateChunk(chunkId, updatedModulesList) {", + Template.indent([ + "return new Promise(function(resolve, reject) {", + Template.indent([ + `var filename = require('path').join(__dirname, ${JSON.stringify( + rootOutputDir + )} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`, + "require('fs').readFile(filename, 'utf-8', function(err, content) {", + Template.indent([ + "if(err) return reject(err);", + "var update = {};", + "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + + "(update, require, require('path').dirname(filename), filename);", + "var updatedModules = update.modules;", + "var runtime = update.runtime;", + "for(var moduleId in updatedModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, + Template.indent([ + `currentUpdate[moduleId] = updatedModules[moduleId];`, + "if(updatedModulesList) updatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "if(runtime) currentUpdateRuntime.push(runtime);", + "resolve();" + ]), + "});" + ]), + "});" + ]), + "}", + "", + Template.getFunctionContent( + require('./JavascriptHotModuleReplacement.runtime.js') + ) + .replace(/\$key\$/g, "readFileVm") + .replace(/\$installedChunks\$/g, "installedChunks") + .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") + .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) + .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) + .replace( + /\$ensureChunkHandlers\$/g, + RuntimeGlobals.ensureChunkHandlers + ) + .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) + .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) + .replace( + /\$hmrDownloadUpdateHandlers\$/g, + RuntimeGlobals.hmrDownloadUpdateHandlers + ) + .replace( + /\$hmrInvalidateModuleHandlers\$/g, + RuntimeGlobals.hmrInvalidateModuleHandlers + ) + ]) + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${RuntimeGlobals.hmrDownloadManifest} = function() {`, + Template.indent([ + "return new Promise(function(resolve, reject) {", + Template.indent([ + `var filename = require('path').join(__dirname, ${JSON.stringify( + rootOutputDir + )} + ${RuntimeGlobals.getUpdateManifestFilename}());`, + "require('fs').readFile(filename, 'utf-8', function(err, content) {", + Template.indent([ + "if(err) {", + Template.indent([ + 'if(err.code === "ENOENT") return resolve();', + "return reject(err);" + ]), + "}", + "try { resolve(JSON.parse(content)); }", + "catch(e) { reject(e); }" + ]), + "});" + ]), + "});" + ]), + "}" + ]) + : "// no HMR manifest" + ]); + } +} + +module.exports = ReadFileChunkLoadingRuntimeModule; + + +/***/ }), + +/***/ 73163: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const AsyncWasmLoadingRuntimeModule = __webpack_require__(5434); + +/** @typedef {import("../Compiler")} Compiler */ + +class ReadFileCompileAsyncWasmPlugin { + constructor({ type = "async-node", import: useImport = false } = {}) { + this._type = type; + this._import = useImport; + } + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "ReadFileCompileAsyncWasmPlugin", + compilation => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === this._type; + }; + const generateLoadBinaryCode = this._import + ? path => + Template.asString([ + "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {", + Template.indent([ + `readFile(new URL(${path}, import.meta.url), (err, buffer) => {`, + Template.indent([ + "if (err) return reject(err);", + "", + "// Fake fetch response", + "resolve({", + Template.indent(["arrayBuffer() { return buffer; }"]), + "});" + ]), + "});" + ]), + "}))" + ]) + : path => + Template.asString([ + "new Promise(function (resolve, reject) {", + Template.indent([ + "try {", + Template.indent([ + "var { readFile } = require('fs');", + "var { join } = require('path');", + "", + `readFile(join(__dirname, ${path}), function(err, buffer){`, + Template.indent([ + "if (err) return reject(err);", + "", + "// Fake fetch response", + "resolve({", + Template.indent(["arrayBuffer() { return buffer; }"]), + "});" + ]), + "});" + ]), + "} catch (err) { reject(err); }" + ]), + "})" + ]); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.instantiateWasm) + .tap("ReadFileCompileAsyncWasmPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + const chunkGraph = compilation.chunkGraph; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + m => m.type === "webassembly/async" + ) + ) { + return; + } + set.add(RuntimeGlobals.publicPath); + compilation.addRuntimeModule( + chunk, + new AsyncWasmLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: false + }) + ); + }); + } + ); + } +} + +module.exports = ReadFileCompileAsyncWasmPlugin; + + +/***/ }), + +/***/ 98939: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const WasmChunkLoadingRuntimeModule = __webpack_require__(87394); + +/** @typedef {import("../Compiler")} Compiler */ + +// TODO webpack 6 remove + +class ReadFileCompileWasmPlugin { + constructor(options) { + this.options = options || {}; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "ReadFileCompileWasmPlugin", + compilation => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === "async-node"; + }; + const generateLoadBinaryCode = path => + Template.asString([ + "new Promise(function (resolve, reject) {", + Template.indent([ + "var { readFile } = require('fs');", + "var { join } = require('path');", + "", + "try {", + Template.indent([ + `readFile(join(__dirname, ${path}), function(err, buffer){`, + Template.indent([ + "if (err) return reject(err);", + "", + "// Fake fetch response", + "resolve({", + Template.indent(["arrayBuffer() { return buffer; }"]), + "});" + ]), + "});" + ]), + "} catch (err) { reject(err); }" + ]), + "})" + ]); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("ReadFileCompileWasmPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + const chunkGraph = compilation.chunkGraph; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + m => m.type === "webassembly/sync" + ) + ) { + return; + } + set.add(RuntimeGlobals.moduleCache); + compilation.addRuntimeModule( + chunk, + new WasmChunkLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: false, + mangleImports: this.options.mangleImports, + runtimeRequirements: set + }) + ); + }); + } + ); + } +} + +module.exports = ReadFileCompileWasmPlugin; + + +/***/ }), + +/***/ 94172: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); +const { + chunkHasJs, + getChunkFilenameTemplate +} = __webpack_require__(89464); +const { getInitialChunkIds } = __webpack_require__(98124); +const compileBooleanMatcher = __webpack_require__(29404); +const { getUndoPath } = __webpack_require__(82186); + +class RequireChunkLoadingRuntimeModule extends RuntimeModule { + constructor(runtimeRequirements) { + super("require chunk loading", RuntimeModule.STAGE_ATTACH); + this.runtimeRequirements = runtimeRequirements; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { chunkGraph, chunk } = this; + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); + const withExternalInstallChunk = this.runtimeRequirements.has( + RuntimeGlobals.externalInstallChunk + ); + const withOnChunkLoad = this.runtimeRequirements.has( + RuntimeGlobals.onChunksLoaded + ); + const withLoading = this.runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withHmr = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); + const hasJsMatcher = compileBooleanMatcher(conditionMap); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + + const outputName = this.compilation.getPath( + getChunkFilenameTemplate(chunk, this.compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath( + outputName, + this.compilation.outputOptions.path, + true + ); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_require` + : undefined; + + return Template.asString([ + withBaseURI + ? Template.asString([ + `${RuntimeGlobals.baseURI} = require("url").pathToFileURL(${ + rootOutputDir !== "./" + ? `__dirname + ${JSON.stringify("/" + rootOutputDir)}` + : "__filename" + });` + ]) + : "// no baseURI", + "", + "// object to store loaded chunks", + '// "1" means "loaded", otherwise not loaded yet', + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 1`).join( + ",\n" + ) + ), + "};", + "", + withOnChunkLoad + ? `${ + RuntimeGlobals.onChunksLoaded + }.require = ${runtimeTemplate.returningFunction( + "installedChunks[chunkId]", + "chunkId" + )};` + : "// no on chunks loaded", + "", + withLoading || withExternalInstallChunk + ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [ + "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent([ + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ]), + "}" + ]), + "}", + `if(runtime) runtime(__webpack_require__);`, + "for(var i = 0; i < chunkIds.length; i++)", + Template.indent("installedChunks[chunkIds[i]] = 1;"), + withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" + ])};` + : "// no chunk install function needed", + "", + withLoading + ? Template.asString([ + "// require() chunk loading for javascript", + `${fn}.require = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasJsMatcher !== false + ? [ + '// "1" is the signal for "already loaded"', + "if(!installedChunks[chunkId]) {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent([ + `installChunk(require(${JSON.stringify( + rootOutputDir + )} + ${ + RuntimeGlobals.getChunkScriptFilename + }(chunkId)));` + ]), + "} else installedChunks[chunkId] = 1;", + "" + ]), + "}" + ] + : "installedChunks[chunkId] = 1;" + )};` + ]) + : "// no chunk loading", + "", + withExternalInstallChunk + ? Template.asString([ + "module.exports = __webpack_require__;", + `${RuntimeGlobals.externalInstallChunk} = installChunk;` + ]) + : "// no external install chunk", + "", + withHmr + ? Template.asString([ + "function loadUpdateChunk(chunkId, updatedModulesList) {", + Template.indent([ + `var update = require(${JSON.stringify(rootOutputDir)} + ${ + RuntimeGlobals.getChunkUpdateScriptFilename + }(chunkId));`, + "var updatedModules = update.modules;", + "var runtime = update.runtime;", + "for(var moduleId in updatedModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, + Template.indent([ + `currentUpdate[moduleId] = updatedModules[moduleId];`, + "if(updatedModulesList) updatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "if(runtime) currentUpdateRuntime.push(runtime);" + ]), + "}", + "", + Template.getFunctionContent( + require('./JavascriptHotModuleReplacement.runtime.js') + ) + .replace(/\$key\$/g, "require") + .replace(/\$installedChunks\$/g, "installedChunks") + .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") + .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) + .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) + .replace( + /\$ensureChunkHandlers\$/g, + RuntimeGlobals.ensureChunkHandlers + ) + .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) + .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) + .replace( + /\$hmrDownloadUpdateHandlers\$/g, + RuntimeGlobals.hmrDownloadUpdateHandlers + ) + .replace( + /\$hmrInvalidateModuleHandlers\$/g, + RuntimeGlobals.hmrInvalidateModuleHandlers + ) + ]) + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${RuntimeGlobals.hmrDownloadManifest} = function() {`, + Template.indent([ + "return Promise.resolve().then(function() {", + Template.indent([ + `return require(${JSON.stringify(rootOutputDir)} + ${ + RuntimeGlobals.getUpdateManifestFilename + }());` + ]), + "})['catch'](function(err) { if(err.code !== 'MODULE_NOT_FOUND') throw err; });" + ]), + "}" + ]) + : "// no HMR manifest" + ]); + } +} + +module.exports = RequireChunkLoadingRuntimeModule; + + +/***/ }), + +/***/ 91786: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const util = __webpack_require__(73837); +const truncateArgs = __webpack_require__(62090); + +module.exports = ({ colors, appendOnly, stream }) => { + let currentStatusMessage = undefined; + let hasStatusMessage = false; + let currentIndent = ""; + let currentCollapsed = 0; + + const indent = (str, prefix, colorPrefix, colorSuffix) => { + if (str === "") return str; + prefix = currentIndent + prefix; + if (colors) { + return ( + prefix + + colorPrefix + + str.replace(/\n/g, colorSuffix + "\n" + prefix + colorPrefix) + + colorSuffix + ); + } else { + return prefix + str.replace(/\n/g, "\n" + prefix); + } + }; + + const clearStatusMessage = () => { + if (hasStatusMessage) { + stream.write("\x1b[2K\r"); + hasStatusMessage = false; + } + }; + + const writeStatusMessage = () => { + if (!currentStatusMessage) return; + const l = stream.columns; + const args = l + ? truncateArgs(currentStatusMessage, l - 1) + : currentStatusMessage; + const str = args.join(" "); + const coloredStr = `\u001b[1m${str}\u001b[39m\u001b[22m`; + stream.write(`\x1b[2K\r${coloredStr}`); + hasStatusMessage = true; + }; + + const writeColored = (prefix, colorPrefix, colorSuffix) => { + return (...args) => { + if (currentCollapsed > 0) return; + clearStatusMessage(); + const str = indent( + util.format(...args), + prefix, + colorPrefix, + colorSuffix + ); + stream.write(str + "\n"); + writeStatusMessage(); + }; + }; + + const writeGroupMessage = writeColored( + "<-> ", + "\u001b[1m\u001b[36m", + "\u001b[39m\u001b[22m" + ); + + const writeGroupCollapsedMessage = writeColored( + "<+> ", + "\u001b[1m\u001b[36m", + "\u001b[39m\u001b[22m" + ); + + return { + log: writeColored(" ", "\u001b[1m", "\u001b[22m"), + debug: writeColored(" ", "", ""), + trace: writeColored(" ", "", ""), + info: writeColored(" ", "\u001b[1m\u001b[32m", "\u001b[39m\u001b[22m"), + warn: writeColored(" ", "\u001b[1m\u001b[33m", "\u001b[39m\u001b[22m"), + error: writeColored(" ", "\u001b[1m\u001b[31m", "\u001b[39m\u001b[22m"), + logTime: writeColored( + " ", + "\u001b[1m\u001b[35m", + "\u001b[39m\u001b[22m" + ), + group: (...args) => { + writeGroupMessage(...args); + if (currentCollapsed > 0) { + currentCollapsed++; + } else { + currentIndent += " "; + } + }, + groupCollapsed: (...args) => { + writeGroupCollapsedMessage(...args); + currentCollapsed++; + }, + groupEnd: () => { + if (currentCollapsed > 0) currentCollapsed--; + else if (currentIndent.length >= 2) + currentIndent = currentIndent.slice(0, currentIndent.length - 2); + }, + // eslint-disable-next-line node/no-unsupported-features/node-builtins + profile: console.profile && (name => console.profile(name)), + // eslint-disable-next-line node/no-unsupported-features/node-builtins + profileEnd: console.profileEnd && (name => console.profileEnd(name)), + clear: + !appendOnly && + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.clear && + (() => { + clearStatusMessage(); + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.clear(); + writeStatusMessage(); + }), + status: appendOnly + ? writeColored(" ", "", "") + : (name, ...args) => { + args = args.filter(Boolean); + if (name === undefined && args.length === 0) { + clearStatusMessage(); + currentStatusMessage = undefined; + } else if ( + typeof name === "string" && + name.startsWith("[webpack.Progress] ") + ) { + currentStatusMessage = [name.slice(19), ...args]; + writeStatusMessage(); + } else if (name === "[webpack.Progress]") { + currentStatusMessage = [...args]; + writeStatusMessage(); + } else { + currentStatusMessage = [name, ...args]; + writeStatusMessage(); + } + } + }; +}; + + +/***/ }), + +/***/ 64395: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { STAGE_ADVANCED } = __webpack_require__(80057); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +class AggressiveMergingPlugin { + constructor(options) { + if ( + (options !== undefined && typeof options !== "object") || + Array.isArray(options) + ) { + throw new Error( + "Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see https://webpack.js.org/plugins/" + ); + } + this.options = options || {}; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const options = this.options; + const minSizeReduce = options.minSizeReduce || 1.5; + + compiler.hooks.thisCompilation.tap( + "AggressiveMergingPlugin", + compilation => { + compilation.hooks.optimizeChunks.tap( + { + name: "AggressiveMergingPlugin", + stage: STAGE_ADVANCED + }, + chunks => { + const chunkGraph = compilation.chunkGraph; + /** @type {{a: Chunk, b: Chunk, improvement: number}[]} */ + let combinations = []; + for (const a of chunks) { + if (a.canBeInitial()) continue; + for (const b of chunks) { + if (b.canBeInitial()) continue; + if (b === a) break; + if (!chunkGraph.canChunksBeIntegrated(a, b)) { + continue; + } + const aSize = chunkGraph.getChunkSize(b, { + chunkOverhead: 0 + }); + const bSize = chunkGraph.getChunkSize(a, { + chunkOverhead: 0 + }); + const abSize = chunkGraph.getIntegratedChunksSize(b, a, { + chunkOverhead: 0 + }); + const improvement = (aSize + bSize) / abSize; + combinations.push({ + a, + b, + improvement + }); + } + } + + combinations.sort((a, b) => { + return b.improvement - a.improvement; + }); + + const pair = combinations[0]; + + if (!pair) return; + if (pair.improvement < minSizeReduce) return; + + chunkGraph.integrateChunks(pair.b, pair.a); + compilation.chunks.delete(pair.a); + return true; + } + ); + } + ); + } +} + +module.exports = AggressiveMergingPlugin; + + +/***/ }), + +/***/ 15543: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { STAGE_ADVANCED } = __webpack_require__(80057); +const { intersect } = __webpack_require__(93347); +const { + compareModulesByIdentifier, + compareChunks +} = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); +const identifierUtils = __webpack_require__(82186); + +/** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +const validate = createSchemaValidation( + __webpack_require__(32697), + () => + __webpack_require__(47995), + { + name: "Aggressive Splitting Plugin", + baseDataPath: "options" + } +); + +const moveModuleBetween = (chunkGraph, oldChunk, newChunk) => { + return module => { + chunkGraph.disconnectChunkAndModule(oldChunk, module); + chunkGraph.connectChunkAndModule(newChunk, module); + }; +}; + +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk} chunk the chunk + * @returns {function(Module): boolean} filter for entry module + */ +const isNotAEntryModule = (chunkGraph, chunk) => { + return module => { + return !chunkGraph.isEntryModuleInChunk(module, chunk); + }; +}; + +/** @type {WeakSet} */ +const recordedChunks = new WeakSet(); + +class AggressiveSplittingPlugin { + /** + * @param {AggressiveSplittingPluginOptions=} options options object + */ + constructor(options = {}) { + validate(options); + + this.options = options; + if (typeof this.options.minSize !== "number") { + this.options.minSize = 30 * 1024; + } + if (typeof this.options.maxSize !== "number") { + this.options.maxSize = 50 * 1024; + } + if (typeof this.options.chunkOverhead !== "number") { + this.options.chunkOverhead = 0; + } + if (typeof this.options.entryChunkMultiplicator !== "number") { + this.options.entryChunkMultiplicator = 1; + } + } + + /** + * @param {Chunk} chunk the chunk to test + * @returns {boolean} true if the chunk was recorded + */ + static wasChunkRecorded(chunk) { + return recordedChunks.has(chunk); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "AggressiveSplittingPlugin", + compilation => { + let needAdditionalSeal = false; + let newSplits; + let fromAggressiveSplittingSet; + let chunkSplitDataMap; + compilation.hooks.optimize.tap("AggressiveSplittingPlugin", () => { + newSplits = []; + fromAggressiveSplittingSet = new Set(); + chunkSplitDataMap = new Map(); + }); + compilation.hooks.optimizeChunks.tap( + { + name: "AggressiveSplittingPlugin", + stage: STAGE_ADVANCED + }, + chunks => { + const chunkGraph = compilation.chunkGraph; + // Precompute stuff + const nameToModuleMap = new Map(); + const moduleToNameMap = new Map(); + const makePathsRelative = + identifierUtils.makePathsRelative.bindContextCache( + compiler.context, + compiler.root + ); + for (const m of compilation.modules) { + const name = makePathsRelative(m.identifier()); + nameToModuleMap.set(name, m); + moduleToNameMap.set(m, name); + } + + // Check used chunk ids + const usedIds = new Set(); + for (const chunk of chunks) { + usedIds.add(chunk.id); + } + + const recordedSplits = + (compilation.records && compilation.records.aggressiveSplits) || + []; + const usedSplits = newSplits + ? recordedSplits.concat(newSplits) + : recordedSplits; + + const minSize = this.options.minSize; + const maxSize = this.options.maxSize; + + const applySplit = splitData => { + // Cannot split if id is already taken + if (splitData.id !== undefined && usedIds.has(splitData.id)) { + return false; + } + + // Get module objects from names + const selectedModules = splitData.modules.map(name => + nameToModuleMap.get(name) + ); + + // Does the modules exist at all? + if (!selectedModules.every(Boolean)) return false; + + // Check if size matches (faster than waiting for hash) + let size = 0; + for (const m of selectedModules) size += m.size(); + if (size !== splitData.size) return false; + + // get chunks with all modules + const selectedChunks = intersect( + selectedModules.map( + m => new Set(chunkGraph.getModuleChunksIterable(m)) + ) + ); + + // No relevant chunks found + if (selectedChunks.size === 0) return false; + + // The found chunk is already the split or similar + if ( + selectedChunks.size === 1 && + chunkGraph.getNumberOfChunkModules( + Array.from(selectedChunks)[0] + ) === selectedModules.length + ) { + const chunk = Array.from(selectedChunks)[0]; + if (fromAggressiveSplittingSet.has(chunk)) return false; + fromAggressiveSplittingSet.add(chunk); + chunkSplitDataMap.set(chunk, splitData); + return true; + } + + // split the chunk into two parts + const newChunk = compilation.addChunk(); + newChunk.chunkReason = "aggressive splitted"; + for (const chunk of selectedChunks) { + selectedModules.forEach( + moveModuleBetween(chunkGraph, chunk, newChunk) + ); + chunk.split(newChunk); + chunk.name = null; + } + fromAggressiveSplittingSet.add(newChunk); + chunkSplitDataMap.set(newChunk, splitData); + + if (splitData.id !== null && splitData.id !== undefined) { + newChunk.id = splitData.id; + newChunk.ids = [splitData.id]; + } + return true; + }; + + // try to restore to recorded splitting + let changed = false; + for (let j = 0; j < usedSplits.length; j++) { + const splitData = usedSplits[j]; + if (applySplit(splitData)) changed = true; + } + + // for any chunk which isn't splitted yet, split it and create a new entry + // start with the biggest chunk + const cmpFn = compareChunks(chunkGraph); + const sortedChunks = Array.from(chunks).sort((a, b) => { + const diff1 = + chunkGraph.getChunkModulesSize(b) - + chunkGraph.getChunkModulesSize(a); + if (diff1) return diff1; + const diff2 = + chunkGraph.getNumberOfChunkModules(a) - + chunkGraph.getNumberOfChunkModules(b); + if (diff2) return diff2; + return cmpFn(a, b); + }); + for (const chunk of sortedChunks) { + if (fromAggressiveSplittingSet.has(chunk)) continue; + const size = chunkGraph.getChunkModulesSize(chunk); + if ( + size > maxSize && + chunkGraph.getNumberOfChunkModules(chunk) > 1 + ) { + const modules = chunkGraph + .getOrderedChunkModules(chunk, compareModulesByIdentifier) + .filter(isNotAEntryModule(chunkGraph, chunk)); + const selectedModules = []; + let selectedModulesSize = 0; + for (let k = 0; k < modules.length; k++) { + const module = modules[k]; + const newSize = selectedModulesSize + module.size(); + if (newSize > maxSize && selectedModulesSize >= minSize) { + break; + } + selectedModulesSize = newSize; + selectedModules.push(module); + } + if (selectedModules.length === 0) continue; + const splitData = { + modules: selectedModules + .map(m => moduleToNameMap.get(m)) + .sort(), + size: selectedModulesSize + }; + + if (applySplit(splitData)) { + newSplits = (newSplits || []).concat(splitData); + changed = true; + } + } + } + if (changed) return true; + } + ); + compilation.hooks.recordHash.tap( + "AggressiveSplittingPlugin", + records => { + // 4. save made splittings to records + const allSplits = new Set(); + const invalidSplits = new Set(); + + // Check if some splittings are invalid + // We remove invalid splittings and try again + for (const chunk of compilation.chunks) { + const splitData = chunkSplitDataMap.get(chunk); + if (splitData !== undefined) { + if (splitData.hash && chunk.hash !== splitData.hash) { + // Split was successful, but hash doesn't equal + // We can throw away the split since it's useless now + invalidSplits.add(splitData); + } + } + } + + if (invalidSplits.size > 0) { + records.aggressiveSplits = records.aggressiveSplits.filter( + splitData => !invalidSplits.has(splitData) + ); + needAdditionalSeal = true; + } else { + // set hash and id values on all (new) splittings + for (const chunk of compilation.chunks) { + const splitData = chunkSplitDataMap.get(chunk); + if (splitData !== undefined) { + splitData.hash = chunk.hash; + splitData.id = chunk.id; + allSplits.add(splitData); + // set flag for stats + recordedChunks.add(chunk); + } + } + + // Also add all unused historical splits (after the used ones) + // They can still be used in some future compilation + const recordedSplits = + compilation.records && compilation.records.aggressiveSplits; + if (recordedSplits) { + for (const splitData of recordedSplits) { + if (!invalidSplits.has(splitData)) allSplits.add(splitData); + } + } + + // record all splits + records.aggressiveSplits = Array.from(allSplits); + + needAdditionalSeal = false; + } + } + ); + compilation.hooks.needAdditionalSeal.tap( + "AggressiveSplittingPlugin", + () => { + if (needAdditionalSeal) { + needAdditionalSeal = false; + return true; + } + } + ); + } + ); + } +} +module.exports = AggressiveSplittingPlugin; + + +/***/ }), + +/***/ 97198: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const eslintScope = __webpack_require__(36007); +const Referencer = __webpack_require__(44585); +const { + CachedSource, + ConcatSource, + ReplaceSource +} = __webpack_require__(51255); +const ConcatenationScope = __webpack_require__(98229); +const { UsageState } = __webpack_require__(63686); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const HarmonyImportDependency = __webpack_require__(57154); +const JavascriptParser = __webpack_require__(29050); +const { equals } = __webpack_require__(84953); +const LazySet = __webpack_require__(38938); +const { concatComparators, keepOriginalOrder } = __webpack_require__(29579); +const createHash = __webpack_require__(49835); +const { makePathsRelative } = __webpack_require__(82186); +const makeSerializable = __webpack_require__(33032); +const propertyAccess = __webpack_require__(54190); +const { + filterRuntime, + intersectRuntime, + mergeRuntimeCondition, + mergeRuntimeConditionNonFalse, + runtimeConditionToString, + subtractRuntimeCondition +} = __webpack_require__(17156); + +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ +/** @template T @typedef {import("../InitFragment")} InitFragment */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {typeof import("../util/Hash")} HashConstructor */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +// fix eslint-scope to support class properties correctly +// cspell:word Referencer +const ReferencerClass = Referencer; +if (!ReferencerClass.prototype.PropertyDefinition) { + ReferencerClass.prototype.PropertyDefinition = + ReferencerClass.prototype.Property; +} + +/** + * @typedef {Object} ReexportInfo + * @property {Module} module + * @property {string[]} export + */ + +/** @typedef {RawBinding | SymbolBinding} Binding */ + +/** + * @typedef {Object} RawBinding + * @property {ModuleInfo} info + * @property {string} rawName + * @property {string=} comment + * @property {string[]} ids + * @property {string[]} exportName + */ + +/** + * @typedef {Object} SymbolBinding + * @property {ConcatenatedModuleInfo} info + * @property {string} name + * @property {string=} comment + * @property {string[]} ids + * @property {string[]} exportName + */ + +/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo } ModuleInfo */ +/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo | ReferenceToModuleInfo } ModuleInfoOrReference */ + +/** + * @typedef {Object} ConcatenatedModuleInfo + * @property {"concatenated"} type + * @property {Module} module + * @property {number} index + * @property {Object} ast + * @property {Source} internalSource + * @property {ReplaceSource} source + * @property {InitFragment[]=} chunkInitFragments + * @property {Iterable} runtimeRequirements + * @property {Scope} globalScope + * @property {Scope} moduleScope + * @property {Map} internalNames + * @property {Map} exportMap + * @property {Map} rawExportMap + * @property {string=} namespaceExportSymbol + * @property {string} namespaceObjectName + * @property {boolean} interopNamespaceObjectUsed + * @property {string} interopNamespaceObjectName + * @property {boolean} interopNamespaceObject2Used + * @property {string} interopNamespaceObject2Name + * @property {boolean} interopDefaultAccessUsed + * @property {string} interopDefaultAccessName + */ + +/** + * @typedef {Object} ExternalModuleInfo + * @property {"external"} type + * @property {Module} module + * @property {RuntimeSpec | boolean} runtimeCondition + * @property {number} index + * @property {string} name + * @property {boolean} interopNamespaceObjectUsed + * @property {string} interopNamespaceObjectName + * @property {boolean} interopNamespaceObject2Used + * @property {string} interopNamespaceObject2Name + * @property {boolean} interopDefaultAccessUsed + * @property {string} interopDefaultAccessName + */ + +/** + * @typedef {Object} ReferenceToModuleInfo + * @property {"reference"} type + * @property {RuntimeSpec | boolean} runtimeCondition + * @property {ConcatenatedModuleInfo | ExternalModuleInfo} target + */ + +const RESERVED_NAMES = new Set( + [ + // internal names (should always be renamed) + ConcatenationScope.DEFAULT_EXPORT, + ConcatenationScope.NAMESPACE_OBJECT_EXPORT, + + // keywords + "abstract,arguments,async,await,boolean,break,byte,case,catch,char,class,const,continue", + "debugger,default,delete,do,double,else,enum,eval,export,extends,false,final,finally,float", + "for,function,goto,if,implements,import,in,instanceof,int,interface,let,long,native,new,null", + "package,private,protected,public,return,short,static,super,switch,synchronized,this,throw", + "throws,transient,true,try,typeof,var,void,volatile,while,with,yield", + + // commonjs/amd + "module,__dirname,__filename,exports,require,define", + + // js globals + "Array,Date,eval,function,hasOwnProperty,Infinity,isFinite,isNaN,isPrototypeOf,length,Math", + "NaN,name,Number,Object,prototype,String,toString,undefined,valueOf", + + // browser globals + "alert,all,anchor,anchors,area,assign,blur,button,checkbox,clearInterval,clearTimeout", + "clientInformation,close,closed,confirm,constructor,crypto,decodeURI,decodeURIComponent", + "defaultStatus,document,element,elements,embed,embeds,encodeURI,encodeURIComponent,escape", + "event,fileUpload,focus,form,forms,frame,innerHeight,innerWidth,layer,layers,link,location", + "mimeTypes,navigate,navigator,frames,frameRate,hidden,history,image,images,offscreenBuffering", + "open,opener,option,outerHeight,outerWidth,packages,pageXOffset,pageYOffset,parent,parseFloat", + "parseInt,password,pkcs11,plugin,prompt,propertyIsEnum,radio,reset,screenX,screenY,scroll", + "secure,select,self,setInterval,setTimeout,status,submit,taint,text,textarea,top,unescape", + "untaint,window", + + // window events + "onblur,onclick,onerror,onfocus,onkeydown,onkeypress,onkeyup,onmouseover,onload,onmouseup,onmousedown,onsubmit" + ] + .join(",") + .split(",") +); + +const bySourceOrder = (a, b) => { + const aOrder = a.sourceOrder; + const bOrder = b.sourceOrder; + if (isNaN(aOrder)) { + if (!isNaN(bOrder)) { + return 1; + } + } else { + if (isNaN(bOrder)) { + return -1; + } + if (aOrder !== bOrder) { + return aOrder < bOrder ? -1 : 1; + } + } + return 0; +}; + +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; +}; + +/** + * @typedef {Object} ConcatenationEntry + * @property {"concatenated" | "external"} type + * @property {Module} module + * @property {RuntimeSpec | boolean} runtimeCondition + */ + +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ModuleInfo} info module info + * @param {string[]} exportName exportName + * @param {Map} moduleToInfoMap moduleToInfoMap + * @param {RuntimeSpec} runtime for which runtime + * @param {RequestShortener} requestShortener the request shortener + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {Set} neededNamespaceObjects modules for which a namespace object should be generated + * @param {boolean} asCall asCall + * @param {boolean} strictHarmonyModule strictHarmonyModule + * @param {boolean | undefined} asiSafe asiSafe + * @param {Set} alreadyVisited alreadyVisited + * @returns {Binding} the final variable + */ +const getFinalBinding = ( + moduleGraph, + info, + exportName, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + asCall, + strictHarmonyModule, + asiSafe, + alreadyVisited = new Set() +) => { + const exportsType = info.module.getExportsType( + moduleGraph, + strictHarmonyModule + ); + if (exportName.length === 0) { + switch (exportsType) { + case "default-only": + info.interopNamespaceObject2Used = true; + return { + info, + rawName: info.interopNamespaceObject2Name, + ids: exportName, + exportName + }; + case "default-with-named": + info.interopNamespaceObjectUsed = true; + return { + info, + rawName: info.interopNamespaceObjectName, + ids: exportName, + exportName + }; + case "namespace": + case "dynamic": + break; + default: + throw new Error(`Unexpected exportsType ${exportsType}`); + } + } else { + switch (exportsType) { + case "namespace": + break; + case "default-with-named": + switch (exportName[0]) { + case "default": + exportName = exportName.slice(1); + break; + case "__esModule": + return { + info, + rawName: "/* __esModule */true", + ids: exportName.slice(1), + exportName + }; + } + break; + case "default-only": { + const exportId = exportName[0]; + if (exportId === "__esModule") { + return { + info, + rawName: "/* __esModule */true", + ids: exportName.slice(1), + exportName + }; + } + exportName = exportName.slice(1); + if (exportId !== "default") { + return { + info, + rawName: + "/* non-default import from default-exporting module */undefined", + ids: exportName, + exportName + }; + } + break; + } + case "dynamic": + switch (exportName[0]) { + case "default": { + exportName = exportName.slice(1); + info.interopDefaultAccessUsed = true; + const defaultExport = asCall + ? `${info.interopDefaultAccessName}()` + : asiSafe + ? `(${info.interopDefaultAccessName}())` + : asiSafe === false + ? `;(${info.interopDefaultAccessName}())` + : `${info.interopDefaultAccessName}.a`; + return { + info, + rawName: defaultExport, + ids: exportName, + exportName + }; + } + case "__esModule": + return { + info, + rawName: "/* __esModule */true", + ids: exportName.slice(1), + exportName + }; + } + break; + default: + throw new Error(`Unexpected exportsType ${exportsType}`); + } + } + if (exportName.length === 0) { + switch (info.type) { + case "concatenated": + neededNamespaceObjects.add(info); + return { + info, + rawName: info.namespaceObjectName, + ids: exportName, + exportName + }; + case "external": + return { info, rawName: info.name, ids: exportName, exportName }; + } + } + const exportsInfo = moduleGraph.getExportsInfo(info.module); + const exportInfo = exportsInfo.getExportInfo(exportName[0]); + if (alreadyVisited.has(exportInfo)) { + return { + info, + rawName: "/* circular reexport */ Object(function x() { x() }())", + ids: [], + exportName + }; + } + alreadyVisited.add(exportInfo); + switch (info.type) { + case "concatenated": { + const exportId = exportName[0]; + if (exportInfo.provided === false) { + // It's not provided, but it could be on the prototype + neededNamespaceObjects.add(info); + return { + info, + rawName: info.namespaceObjectName, + ids: exportName, + exportName + }; + } + const directExport = info.exportMap && info.exportMap.get(exportId); + if (directExport) { + const usedName = /** @type {string[]} */ ( + exportsInfo.getUsedName(exportName, runtime) + ); + if (!usedName) { + return { + info, + rawName: "/* unused export */ undefined", + ids: exportName.slice(1), + exportName + }; + } + return { + info, + name: directExport, + ids: usedName.slice(1), + exportName + }; + } + const rawExport = info.rawExportMap && info.rawExportMap.get(exportId); + if (rawExport) { + return { + info, + rawName: rawExport, + ids: exportName.slice(1), + exportName + }; + } + const reexport = exportInfo.findTarget(moduleGraph, module => + moduleToInfoMap.has(module) + ); + if (reexport === false) { + throw new Error( + `Target module of reexport from '${info.module.readableIdentifier( + requestShortener + )}' is not part of the concatenation (export '${exportId}')\nModules in the concatenation:\n${Array.from( + moduleToInfoMap, + ([m, info]) => + ` * ${info.type} ${m.readableIdentifier(requestShortener)}` + ).join("\n")}` + ); + } + if (reexport) { + const refInfo = moduleToInfoMap.get(reexport.module); + return getFinalBinding( + moduleGraph, + refInfo, + reexport.export + ? [...reexport.export, ...exportName.slice(1)] + : exportName.slice(1), + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + asCall, + info.module.buildMeta.strictHarmonyModule, + asiSafe, + alreadyVisited + ); + } + if (info.namespaceExportSymbol) { + const usedName = /** @type {string[]} */ ( + exportsInfo.getUsedName(exportName, runtime) + ); + return { + info, + rawName: info.namespaceObjectName, + ids: usedName, + exportName + }; + } + throw new Error( + `Cannot get final name for export '${exportName.join( + "." + )}' of ${info.module.readableIdentifier(requestShortener)}` + ); + } + + case "external": { + const used = /** @type {string[]} */ ( + exportsInfo.getUsedName(exportName, runtime) + ); + if (!used) { + return { + info, + rawName: "/* unused export */ undefined", + ids: exportName.slice(1), + exportName + }; + } + const comment = equals(used, exportName) + ? "" + : Template.toNormalComment(`${exportName.join(".")}`); + return { info, rawName: info.name + comment, ids: used, exportName }; + } + } +}; + +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ModuleInfo} info module info + * @param {string[]} exportName exportName + * @param {Map} moduleToInfoMap moduleToInfoMap + * @param {RuntimeSpec} runtime for which runtime + * @param {RequestShortener} requestShortener the request shortener + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {Set} neededNamespaceObjects modules for which a namespace object should be generated + * @param {boolean} asCall asCall + * @param {boolean} callContext callContext + * @param {boolean} strictHarmonyModule strictHarmonyModule + * @param {boolean | undefined} asiSafe asiSafe + * @returns {string} the final name + */ +const getFinalName = ( + moduleGraph, + info, + exportName, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + asCall, + callContext, + strictHarmonyModule, + asiSafe +) => { + const binding = getFinalBinding( + moduleGraph, + info, + exportName, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + asCall, + strictHarmonyModule, + asiSafe + ); + { + const { ids, comment } = binding; + let reference; + let isPropertyAccess; + if ("rawName" in binding) { + reference = `${binding.rawName}${comment || ""}${propertyAccess(ids)}`; + isPropertyAccess = ids.length > 0; + } else { + const { info, name: exportId } = binding; + const name = info.internalNames.get(exportId); + if (!name) { + throw new Error( + `The export "${exportId}" in "${info.module.readableIdentifier( + requestShortener + )}" has no internal name (existing names: ${ + Array.from( + info.internalNames, + ([name, symbol]) => `${name}: ${symbol}` + ).join(", ") || "none" + })` + ); + } + reference = `${name}${comment || ""}${propertyAccess(ids)}`; + isPropertyAccess = ids.length > 1; + } + if (isPropertyAccess && asCall && callContext === false) { + return asiSafe + ? `(0,${reference})` + : asiSafe === false + ? `;(0,${reference})` + : `/*#__PURE__*/Object(${reference})`; + } + return reference; + } +}; + +const addScopeSymbols = (s, nameSet, scopeSet1, scopeSet2) => { + let scope = s; + while (scope) { + if (scopeSet1.has(scope)) break; + if (scopeSet2.has(scope)) break; + scopeSet1.add(scope); + for (const variable of scope.variables) { + nameSet.add(variable.name); + } + scope = scope.upper; + } +}; + +const getAllReferences = variable => { + let set = variable.references; + // Look for inner scope variables too (like in class Foo { t() { Foo } }) + const identifiers = new Set(variable.identifiers); + for (const scope of variable.scope.childScopes) { + for (const innerVar of scope.variables) { + if (innerVar.identifiers.some(id => identifiers.has(id))) { + set = set.concat(innerVar.references); + break; + } + } + } + return set; +}; + +const getPathInAst = (ast, node) => { + if (ast === node) { + return []; + } + + const nr = node.range; + + const enterNode = n => { + if (!n) return undefined; + const r = n.range; + if (r) { + if (r[0] <= nr[0] && r[1] >= nr[1]) { + const path = getPathInAst(n, node); + if (path) { + path.push(n); + return path; + } + } + } + return undefined; + }; + + if (Array.isArray(ast)) { + for (let i = 0; i < ast.length; i++) { + const enterResult = enterNode(ast[i]); + if (enterResult !== undefined) return enterResult; + } + } else if (ast && typeof ast === "object") { + const keys = Object.keys(ast); + for (let i = 0; i < keys.length; i++) { + const value = ast[keys[i]]; + if (Array.isArray(value)) { + const pathResult = getPathInAst(value, node); + if (pathResult !== undefined) return pathResult; + } else if (value && typeof value === "object") { + const enterResult = enterNode(value); + if (enterResult !== undefined) return enterResult; + } + } + } +}; + +const TYPES = new Set(["javascript"]); + +class ConcatenatedModule extends Module { + /** + * @param {Module} rootModule the root module of the concatenation + * @param {Set} modules all modules in the concatenation (including the root module) + * @param {RuntimeSpec} runtime the runtime + * @param {Object=} associatedObjectForCache object for caching + * @param {string | HashConstructor=} hashFunction hash function to use + * @returns {ConcatenatedModule} the module + */ + static create( + rootModule, + modules, + runtime, + associatedObjectForCache, + hashFunction = "md4" + ) { + const identifier = ConcatenatedModule._createIdentifier( + rootModule, + modules, + associatedObjectForCache, + hashFunction + ); + return new ConcatenatedModule({ + identifier, + rootModule, + modules, + runtime + }); + } + + /** + * @param {Object} options options + * @param {string} options.identifier the identifier of the module + * @param {Module=} options.rootModule the root module of the concatenation + * @param {RuntimeSpec} options.runtime the selected runtime + * @param {Set=} options.modules all concatenated modules + */ + constructor({ identifier, rootModule, modules, runtime }) { + super("javascript/esm", null, rootModule && rootModule.layer); + + // Info from Factory + /** @type {string} */ + this._identifier = identifier; + /** @type {Module} */ + this.rootModule = rootModule; + /** @type {Set} */ + this._modules = modules; + this._runtime = runtime; + this.factoryMeta = rootModule && rootModule.factoryMeta; + } + + /** + * 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) { + throw new Error("Must not be called"); + } + + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; + } + + get modules() { + return Array.from(this._modules); + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this._identifier; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return ( + this.rootModule.readableIdentifier(requestShortener) + + ` + ${this._modules.size - 1} modules` + ); + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return this.rootModule.libIdent(options); + } + + /** + * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + */ + nameForCondition() { + return this.rootModule.nameForCondition(); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only + */ + getSideEffectsConnectionState(moduleGraph) { + return this.rootModule.getSideEffectsConnectionState(moduleGraph); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {function(WebpackError=): void} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + const { rootModule } = this; + this.buildInfo = { + strict: true, + cacheable: true, + moduleArgument: rootModule.buildInfo.moduleArgument, + exportsArgument: rootModule.buildInfo.exportsArgument, + fileDependencies: new LazySet(), + contextDependencies: new LazySet(), + missingDependencies: new LazySet(), + topLevelDeclarations: new Set(), + assets: undefined + }; + this.buildMeta = rootModule.buildMeta; + this.clearDependenciesAndBlocks(); + this.clearWarningsAndErrors(); + + for (const m of this._modules) { + // populate cacheable + if (!m.buildInfo.cacheable) { + this.buildInfo.cacheable = false; + } + + // populate dependencies + for (const d of m.dependencies.filter( + dep => + !(dep instanceof HarmonyImportDependency) || + !this._modules.has(compilation.moduleGraph.getModule(dep)) + )) { + this.dependencies.push(d); + } + // populate blocks + for (const d of m.blocks) { + this.blocks.push(d); + } + + // populate warnings + const warnings = m.getWarnings(); + if (warnings !== undefined) { + for (const warning of warnings) { + this.addWarning(warning); + } + } + + // populate errors + const errors = m.getErrors(); + if (errors !== undefined) { + for (const error of errors) { + this.addError(error); + } + } + + // populate topLevelDeclarations + if (m.buildInfo.topLevelDeclarations) { + const topLevelDeclarations = this.buildInfo.topLevelDeclarations; + if (topLevelDeclarations !== undefined) { + for (const decl of m.buildInfo.topLevelDeclarations) { + // reserved names will always be renamed + if (RESERVED_NAMES.has(decl)) continue; + // TODO actually this is incorrect since with renaming there could be more + // We should do the renaming during build + topLevelDeclarations.add(decl); + } + } + } else { + this.buildInfo.topLevelDeclarations = undefined; + } + + // populate assets + if (m.buildInfo.assets) { + if (this.buildInfo.assets === undefined) { + this.buildInfo.assets = Object.create(null); + } + Object.assign(this.buildInfo.assets, m.buildInfo.assets); + } + if (m.buildInfo.assetsInfo) { + if (this.buildInfo.assetsInfo === undefined) { + this.buildInfo.assetsInfo = new Map(); + } + for (const [key, value] of m.buildInfo.assetsInfo) { + this.buildInfo.assetsInfo.set(key, value); + } + } + } + callback(); + } + + /** + * @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) { + // Guess size from embedded modules + let size = 0; + for (const module of this._modules) { + size += module.size(type); + } + return size; + } + + /** + * @private + * @param {Module} rootModule the root of the concatenation + * @param {Set} modulesSet a set of modules which should be concatenated + * @param {RuntimeSpec} runtime for this runtime + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConcatenationEntry[]} concatenation list + */ + _createConcatenationList(rootModule, modulesSet, runtime, moduleGraph) { + /** @type {ConcatenationEntry[]} */ + const list = []; + /** @type {Map} */ + const existingEntries = new Map(); + + /** + * @param {Module} module a module + * @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} imported modules in order + */ + const getConcatenatedImports = module => { + let connections = Array.from(moduleGraph.getOutgoingConnections(module)); + if (module === rootModule) { + for (const c of moduleGraph.getOutgoingConnections(this)) + connections.push(c); + } + const references = connections + .filter(connection => { + if (!(connection.dependency instanceof HarmonyImportDependency)) + return false; + return ( + connection && + connection.resolvedOriginModule === module && + connection.module && + connection.isTargetActive(runtime) + ); + }) + .map(connection => ({ + connection, + sourceOrder: /** @type {HarmonyImportDependency} */ ( + connection.dependency + ).sourceOrder + })); + references.sort( + concatComparators(bySourceOrder, keepOriginalOrder(references)) + ); + /** @type {Map} */ + const referencesMap = new Map(); + for (const { connection } of references) { + const runtimeCondition = filterRuntime(runtime, r => + connection.isTargetActive(r) + ); + if (runtimeCondition === false) continue; + const module = connection.module; + const entry = referencesMap.get(module); + if (entry === undefined) { + referencesMap.set(module, { connection, runtimeCondition }); + continue; + } + entry.runtimeCondition = mergeRuntimeConditionNonFalse( + entry.runtimeCondition, + runtimeCondition, + runtime + ); + } + return referencesMap.values(); + }; + + /** + * @param {ModuleGraphConnection} connection graph connection + * @param {RuntimeSpec | true} runtimeCondition runtime condition + * @returns {void} + */ + const enterModule = (connection, runtimeCondition) => { + const module = connection.module; + if (!module) return; + const existingEntry = existingEntries.get(module); + if (existingEntry === true) { + return; + } + if (modulesSet.has(module)) { + existingEntries.set(module, true); + if (runtimeCondition !== true) { + throw new Error( + `Cannot runtime-conditional concatenate a module (${module.identifier()} in ${this.rootModule.identifier()}, ${runtimeConditionToString( + runtimeCondition + )}). This should not happen.` + ); + } + const imports = getConcatenatedImports(module); + for (const { connection, runtimeCondition } of imports) + enterModule(connection, runtimeCondition); + list.push({ + type: "concatenated", + module: connection.module, + runtimeCondition + }); + } else { + if (existingEntry !== undefined) { + const reducedRuntimeCondition = subtractRuntimeCondition( + runtimeCondition, + existingEntry, + runtime + ); + if (reducedRuntimeCondition === false) return; + runtimeCondition = reducedRuntimeCondition; + existingEntries.set( + connection.module, + mergeRuntimeConditionNonFalse( + existingEntry, + runtimeCondition, + runtime + ) + ); + } else { + existingEntries.set(connection.module, runtimeCondition); + } + if (list.length > 0) { + const lastItem = list[list.length - 1]; + if ( + lastItem.type === "external" && + lastItem.module === connection.module + ) { + lastItem.runtimeCondition = mergeRuntimeCondition( + lastItem.runtimeCondition, + runtimeCondition, + runtime + ); + return; + } + } + list.push({ + type: "external", + get module() { + // We need to use a getter here, because the module in the dependency + // could be replaced by some other process (i. e. also replaced with a + // concatenated module) + return connection.module; + }, + runtimeCondition + }); + } + }; + + existingEntries.set(rootModule, true); + const imports = getConcatenatedImports(rootModule); + for (const { connection, runtimeCondition } of imports) + enterModule(connection, runtimeCondition); + list.push({ + type: "concatenated", + module: rootModule, + runtimeCondition: true + }); + + return list; + } + + /** + * @param {Module} rootModule the root module of the concatenation + * @param {Set} modules all modules in the concatenation (including the root module) + * @param {Object=} associatedObjectForCache object for caching + * @param {string | HashConstructor=} hashFunction hash function to use + * @returns {string} the identifier + */ + static _createIdentifier( + rootModule, + modules, + associatedObjectForCache, + hashFunction = "md4" + ) { + const cachedMakePathsRelative = makePathsRelative.bindContextCache( + rootModule.context, + associatedObjectForCache + ); + let identifiers = []; + for (const module of modules) { + identifiers.push(cachedMakePathsRelative(module.identifier())); + } + identifiers.sort(); + const hash = createHash(hashFunction); + hash.update(identifiers.join(" ")); + return rootModule.identifier() + "|" + hash.digest("hex"); + } + + /** + * @param {LazySet} fileDependencies set where file dependencies are added to + * @param {LazySet} contextDependencies set where context dependencies are added to + * @param {LazySet} missingDependencies set where missing dependencies are added to + * @param {LazySet} buildDependencies set where build dependencies are added to + */ + addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ) { + for (const module of this._modules) { + module.addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ); + } + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime: generationRuntime, + codeGenerationResults + }) { + /** @type {Set} */ + const runtimeRequirements = new Set(); + const runtime = intersectRuntime(generationRuntime, this._runtime); + + const requestShortener = runtimeTemplate.requestShortener; + // Meta info for each module + const [modulesWithInfo, moduleToInfoMap] = this._getModulesWithInfo( + moduleGraph, + runtime + ); + + // Set with modules that need a generated namespace object + /** @type {Set} */ + const neededNamespaceObjects = new Set(); + + // Generate source code and analyse scopes + // Prepare a ReplaceSource for the final source + for (const info of moduleToInfoMap.values()) { + this._analyseModule( + moduleToInfoMap, + info, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + codeGenerationResults + ); + } + + // List of all used names to avoid conflicts + const allUsedNames = new Set(RESERVED_NAMES); + + // List of additional names in scope for module references + /** @type {Map, alreadyCheckedScopes: Set }>} */ + const usedNamesInScopeInfo = new Map(); + /** + * @param {string} module module identifier + * @param {string} id export id + * @returns {{ usedNames: Set, alreadyCheckedScopes: Set }} info + */ + const getUsedNamesInScopeInfo = (module, id) => { + const key = `${module}-${id}`; + let info = usedNamesInScopeInfo.get(key); + if (info === undefined) { + info = { + usedNames: new Set(), + alreadyCheckedScopes: new Set() + }; + usedNamesInScopeInfo.set(key, info); + } + return info; + }; + + // Set of already checked scopes + const ignoredScopes = new Set(); + + // get all global names + for (const info of modulesWithInfo) { + if (info.type === "concatenated") { + // ignore symbols from moduleScope + if (info.moduleScope) { + ignoredScopes.add(info.moduleScope); + } + + // The super class expression in class scopes behaves weird + // We get ranges of all super class expressions to make + // renaming to work correctly + const superClassCache = new WeakMap(); + const getSuperClassExpressions = scope => { + const cacheEntry = superClassCache.get(scope); + if (cacheEntry !== undefined) return cacheEntry; + const superClassExpressions = []; + for (const childScope of scope.childScopes) { + if (childScope.type !== "class") continue; + const block = childScope.block; + if ( + (block.type === "ClassDeclaration" || + block.type === "ClassExpression") && + block.superClass + ) { + superClassExpressions.push({ + range: block.superClass.range, + variables: childScope.variables + }); + } + } + superClassCache.set(scope, superClassExpressions); + return superClassExpressions; + }; + + // add global symbols + if (info.globalScope) { + for (const reference of info.globalScope.through) { + const name = reference.identifier.name; + if (ConcatenationScope.isModuleReference(name)) { + const match = ConcatenationScope.matchModuleReference(name); + if (!match) continue; + const referencedInfo = modulesWithInfo[match.index]; + if (referencedInfo.type === "reference") + throw new Error("Module reference can't point to a reference"); + const binding = getFinalBinding( + moduleGraph, + referencedInfo, + match.ids, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + false, + info.module.buildMeta.strictHarmonyModule, + true + ); + if (!binding.ids) continue; + const { usedNames, alreadyCheckedScopes } = + getUsedNamesInScopeInfo( + binding.info.module.identifier(), + "name" in binding ? binding.name : "" + ); + for (const expr of getSuperClassExpressions(reference.from)) { + if ( + expr.range[0] <= reference.identifier.range[0] && + expr.range[1] >= reference.identifier.range[1] + ) { + for (const variable of expr.variables) { + usedNames.add(variable.name); + } + } + } + addScopeSymbols( + reference.from, + usedNames, + alreadyCheckedScopes, + ignoredScopes + ); + } else { + allUsedNames.add(name); + } + } + } + } + } + + // generate names for symbols + for (const info of moduleToInfoMap.values()) { + const { usedNames: namespaceObjectUsedNames } = getUsedNamesInScopeInfo( + info.module.identifier(), + "" + ); + switch (info.type) { + case "concatenated": { + for (const variable of info.moduleScope.variables) { + const name = variable.name; + const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo( + info.module.identifier(), + name + ); + if (allUsedNames.has(name) || usedNames.has(name)) { + const references = getAllReferences(variable); + for (const ref of references) { + addScopeSymbols( + ref.from, + usedNames, + alreadyCheckedScopes, + ignoredScopes + ); + } + const newName = this.findNewName( + name, + allUsedNames, + usedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(newName); + info.internalNames.set(name, newName); + const source = info.source; + const allIdentifiers = new Set( + references.map(r => r.identifier).concat(variable.identifiers) + ); + for (const identifier of allIdentifiers) { + const r = identifier.range; + const path = getPathInAst(info.ast, identifier); + if (path && path.length > 1) { + const maybeProperty = + path[1].type === "AssignmentPattern" && + path[1].left === path[0] + ? path[2] + : path[1]; + if ( + maybeProperty.type === "Property" && + maybeProperty.shorthand + ) { + source.insert(r[1], `: ${newName}`); + continue; + } + } + source.replace(r[0], r[1] - 1, newName); + } + } else { + allUsedNames.add(name); + info.internalNames.set(name, name); + } + } + let namespaceObjectName; + if (info.namespaceExportSymbol) { + namespaceObjectName = info.internalNames.get( + info.namespaceExportSymbol + ); + } else { + namespaceObjectName = this.findNewName( + "namespaceObject", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(namespaceObjectName); + } + info.namespaceObjectName = namespaceObjectName; + break; + } + case "external": { + const externalName = this.findNewName( + "", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalName); + info.name = externalName; + break; + } + } + if (info.module.buildMeta.exportsType !== "namespace") { + const externalNameInterop = this.findNewName( + "namespaceObject", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopNamespaceObjectName = externalNameInterop; + } + if ( + info.module.buildMeta.exportsType === "default" && + info.module.buildMeta.defaultObject !== "redirect" + ) { + const externalNameInterop = this.findNewName( + "namespaceObject2", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopNamespaceObject2Name = externalNameInterop; + } + if ( + info.module.buildMeta.exportsType === "dynamic" || + !info.module.buildMeta.exportsType + ) { + const externalNameInterop = this.findNewName( + "default", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopDefaultAccessName = externalNameInterop; + } + } + + // Find and replace references to modules + for (const info of moduleToInfoMap.values()) { + if (info.type === "concatenated") { + for (const reference of info.globalScope.through) { + const name = reference.identifier.name; + const match = ConcatenationScope.matchModuleReference(name); + if (match) { + const referencedInfo = modulesWithInfo[match.index]; + if (referencedInfo.type === "reference") + throw new Error("Module reference can't point to a reference"); + const finalName = getFinalName( + moduleGraph, + referencedInfo, + match.ids, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + match.call, + !match.directImport, + info.module.buildMeta.strictHarmonyModule, + match.asiSafe + ); + const r = reference.identifier.range; + const source = info.source; + // range is extended by 2 chars to cover the appended "._" + source.replace(r[0], r[1] + 1, finalName); + } + } + } + } + + // Map with all root exposed used exports + /** @type {Map} */ + const exportsMap = new Map(); + + // Set with all root exposed unused exports + /** @type {Set} */ + const unusedExports = new Set(); + + const rootInfo = /** @type {ConcatenatedModuleInfo} */ ( + moduleToInfoMap.get(this.rootModule) + ); + const strictHarmonyModule = rootInfo.module.buildMeta.strictHarmonyModule; + const exportsInfo = moduleGraph.getExportsInfo(rootInfo.module); + for (const exportInfo of exportsInfo.orderedExports) { + const name = exportInfo.name; + if (exportInfo.provided === false) continue; + const used = exportInfo.getUsedName(undefined, runtime); + if (!used) { + unusedExports.add(name); + continue; + } + exportsMap.set(used, requestShortener => { + try { + const finalName = getFinalName( + moduleGraph, + rootInfo, + [name], + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + false, + false, + strictHarmonyModule, + true + ); + return `/* ${ + exportInfo.isReexport() ? "reexport" : "binding" + } */ ${finalName}`; + } catch (e) { + e.message += `\nwhile generating the root export '${name}' (used name: '${used}')`; + throw e; + } + }); + } + + const result = new ConcatSource(); + + // add harmony compatibility flag (must be first because of possible circular dependencies) + if ( + moduleGraph.getExportsInfo(this).otherExportsInfo.getUsed(runtime) !== + UsageState.Unused + ) { + result.add(`// ESM COMPAT FLAG\n`); + result.add( + runtimeTemplate.defineEsModuleFlagStatement({ + exportsArgument: this.exportsArgument, + runtimeRequirements + }) + ); + } + + // define exports + if (exportsMap.size > 0) { + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + const definitions = []; + for (const [key, value] of exportsMap) { + definitions.push( + `\n ${JSON.stringify(key)}: ${runtimeTemplate.returningFunction( + value(requestShortener) + )}` + ); + } + result.add(`\n// EXPORTS\n`); + result.add( + `${RuntimeGlobals.definePropertyGetters}(${ + this.exportsArgument + }, {${definitions.join(",")}\n});\n` + ); + } + + // list unused exports + if (unusedExports.size > 0) { + result.add( + `\n// UNUSED EXPORTS: ${joinIterableWithComma(unusedExports)}\n` + ); + } + + // generate namespace objects + const namespaceObjectSources = new Map(); + for (const info of neededNamespaceObjects) { + if (info.namespaceExportSymbol) continue; + const nsObj = []; + const exportsInfo = moduleGraph.getExportsInfo(info.module); + for (const exportInfo of exportsInfo.orderedExports) { + if (exportInfo.provided === false) continue; + const usedName = exportInfo.getUsedName(undefined, runtime); + if (usedName) { + const finalName = getFinalName( + moduleGraph, + info, + [exportInfo.name], + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + false, + undefined, + info.module.buildMeta.strictHarmonyModule, + true + ); + nsObj.push( + `\n ${JSON.stringify( + usedName + )}: ${runtimeTemplate.returningFunction(finalName)}` + ); + } + } + const name = info.namespaceObjectName; + const defineGetters = + nsObj.length > 0 + ? `${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join( + "," + )}\n});\n` + : ""; + if (nsObj.length > 0) + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + namespaceObjectSources.set( + info, + ` +// NAMESPACE OBJECT: ${info.module.readableIdentifier(requestShortener)} +var ${name} = {}; +${RuntimeGlobals.makeNamespaceObject}(${name}); +${defineGetters}` + ); + runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); + } + + // define required namespace objects (must be before evaluation modules) + for (const info of modulesWithInfo) { + if (info.type === "concatenated") { + const source = namespaceObjectSources.get(info); + if (!source) continue; + result.add(source); + } + } + + const chunkInitFragments = []; + + // evaluate modules in order + for (const rawInfo of modulesWithInfo) { + let name; + let isConditional = false; + const info = rawInfo.type === "reference" ? rawInfo.target : rawInfo; + switch (info.type) { + case "concatenated": { + result.add( + `\n;// CONCATENATED MODULE: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + result.add(info.source); + if (info.chunkInitFragments) { + for (const f of info.chunkInitFragments) chunkInitFragments.push(f); + } + if (info.runtimeRequirements) { + for (const r of info.runtimeRequirements) { + runtimeRequirements.add(r); + } + } + name = info.namespaceObjectName; + break; + } + case "external": { + result.add( + `\n// EXTERNAL MODULE: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + runtimeRequirements.add(RuntimeGlobals.require); + const { runtimeCondition } = + /** @type {ExternalModuleInfo | ReferenceToModuleInfo} */ (rawInfo); + const condition = runtimeTemplate.runtimeConditionExpression({ + chunkGraph, + runtimeCondition, + runtime, + runtimeRequirements + }); + if (condition !== "true") { + isConditional = true; + result.add(`if (${condition}) {\n`); + } + result.add( + `var ${info.name} = __webpack_require__(${JSON.stringify( + chunkGraph.getModuleId(info.module) + )});` + ); + name = info.name; + break; + } + default: + // @ts-expect-error never is expected here + throw new Error(`Unsupported concatenation entry type ${info.type}`); + } + if (info.interopNamespaceObjectUsed) { + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + result.add( + `\nvar ${info.interopNamespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name}, 2);` + ); + } + if (info.interopNamespaceObject2Used) { + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + result.add( + `\nvar ${info.interopNamespaceObject2Name} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name});` + ); + } + if (info.interopDefaultAccessUsed) { + runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport); + result.add( + `\nvar ${info.interopDefaultAccessName} = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${name});` + ); + } + if (isConditional) { + result.add("\n}"); + } + } + + const data = new Map(); + if (chunkInitFragments.length > 0) + data.set("chunkInitFragments", chunkInitFragments); + + /** @type {CodeGenerationResult} */ + const resultEntry = { + sources: new Map([["javascript", new CachedSource(result)]]), + data, + runtimeRequirements + }; + + return resultEntry; + } + + /** + * @param {Map} modulesMap modulesMap + * @param {ModuleInfo} info info + * @param {DependencyTemplates} dependencyTemplates dependencyTemplates + * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {RuntimeSpec} runtime runtime + * @param {CodeGenerationResults} codeGenerationResults codeGenerationResults + */ + _analyseModule( + modulesMap, + info, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + codeGenerationResults + ) { + if (info.type === "concatenated") { + const m = info.module; + try { + // Create a concatenation scope to track and capture information + const concatenationScope = new ConcatenationScope(modulesMap, info); + + // TODO cache codeGeneration results + const codeGenResult = m.codeGeneration({ + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + concatenationScope, + codeGenerationResults + }); + const source = codeGenResult.sources.get("javascript"); + const data = codeGenResult.data; + const chunkInitFragments = data && data.get("chunkInitFragments"); + const code = source.source().toString(); + let ast; + try { + ast = JavascriptParser._parse(code, { + sourceType: "module" + }); + } catch (err) { + if ( + err.loc && + typeof err.loc === "object" && + typeof err.loc.line === "number" + ) { + const lineNumber = err.loc.line; + const lines = code.split("\n"); + err.message += + "\n| " + + lines + .slice(Math.max(0, lineNumber - 3), lineNumber + 2) + .join("\n| "); + } + throw err; + } + const scopeManager = eslintScope.analyze(ast, { + ecmaVersion: 6, + sourceType: "module", + optimistic: true, + ignoreEval: true, + impliedStrict: true + }); + const globalScope = scopeManager.acquire(ast); + const moduleScope = globalScope.childScopes[0]; + const resultSource = new ReplaceSource(source); + info.runtimeRequirements = codeGenResult.runtimeRequirements; + info.ast = ast; + info.internalSource = source; + info.source = resultSource; + info.chunkInitFragments = chunkInitFragments; + info.globalScope = globalScope; + info.moduleScope = moduleScope; + } catch (err) { + err.message += `\nwhile analyzing module ${m.identifier()} for concatenation`; + throw err; + } + } + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @returns {[ModuleInfoOrReference[], Map]} module info items + */ + _getModulesWithInfo(moduleGraph, runtime) { + const orderedConcatenationList = this._createConcatenationList( + this.rootModule, + this._modules, + runtime, + moduleGraph + ); + /** @type {Map} */ + const map = new Map(); + const list = orderedConcatenationList.map((info, index) => { + let item = map.get(info.module); + if (item === undefined) { + switch (info.type) { + case "concatenated": + item = { + type: "concatenated", + module: info.module, + index, + ast: undefined, + internalSource: undefined, + runtimeRequirements: undefined, + source: undefined, + globalScope: undefined, + moduleScope: undefined, + internalNames: new Map(), + exportMap: undefined, + rawExportMap: undefined, + namespaceExportSymbol: undefined, + namespaceObjectName: undefined, + interopNamespaceObjectUsed: false, + interopNamespaceObjectName: undefined, + interopNamespaceObject2Used: false, + interopNamespaceObject2Name: undefined, + interopDefaultAccessUsed: false, + interopDefaultAccessName: undefined + }; + break; + case "external": + item = { + type: "external", + module: info.module, + runtimeCondition: info.runtimeCondition, + index, + name: undefined, + interopNamespaceObjectUsed: false, + interopNamespaceObjectName: undefined, + interopNamespaceObject2Used: false, + interopNamespaceObject2Name: undefined, + interopDefaultAccessUsed: false, + interopDefaultAccessName: undefined + }; + break; + default: + throw new Error( + `Unsupported concatenation entry type ${info.type}` + ); + } + map.set(item.module, item); + return item; + } else { + /** @type {ReferenceToModuleInfo} */ + const ref = { + type: "reference", + runtimeCondition: info.runtimeCondition, + target: item + }; + return ref; + } + }); + return [list, map]; + } + + findNewName(oldName, usedNamed1, usedNamed2, extraInfo) { + let name = oldName; + + if (name === ConcatenationScope.DEFAULT_EXPORT) { + name = ""; + } + if (name === ConcatenationScope.NAMESPACE_OBJECT_EXPORT) { + name = "namespaceObject"; + } + + // Remove uncool stuff + extraInfo = extraInfo.replace( + /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, + "" + ); + + const splittedInfo = extraInfo.split("/"); + while (splittedInfo.length) { + name = splittedInfo.pop() + (name ? "_" + name : ""); + const nameIdent = Template.toIdentifier(name); + if ( + !usedNamed1.has(nameIdent) && + (!usedNamed2 || !usedNamed2.has(nameIdent)) + ) + return nameIdent; + } + + let i = 0; + let nameWithNumber = Template.toIdentifier(`${name}_${i}`); + while ( + usedNamed1.has(nameWithNumber) || + (usedNamed2 && usedNamed2.has(nameWithNumber)) + ) { + i++; + nameWithNumber = Template.toIdentifier(`${name}_${i}`); + } + return nameWithNumber; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + const { chunkGraph, runtime } = context; + for (const info of this._createConcatenationList( + this.rootModule, + this._modules, + intersectRuntime(runtime, this._runtime), + chunkGraph.moduleGraph + )) { + switch (info.type) { + case "concatenated": + info.module.updateHash(hash, context); + break; + case "external": + hash.update(`${chunkGraph.getModuleId(info.module)}`); + // TODO runtimeCondition + break; + } + } + super.updateHash(hash, context); + } + + static deserialize(context) { + const obj = new ConcatenatedModule({ + identifier: undefined, + rootModule: undefined, + modules: undefined, + runtime: undefined + }); + obj.deserialize(context); + return obj; + } +} + +makeSerializable(ConcatenatedModule, "webpack/lib/optimize/ConcatenatedModule"); + +module.exports = ConcatenatedModule; + + +/***/ }), + +/***/ 96260: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { STAGE_BASIC } = __webpack_require__(80057); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compiler")} Compiler */ + +class EnsureChunkConditionsPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "EnsureChunkConditionsPlugin", + compilation => { + const handler = chunks => { + const chunkGraph = compilation.chunkGraph; + // These sets are hoisted here to save memory + // They are cleared at the end of every loop + /** @type {Set} */ + const sourceChunks = new Set(); + /** @type {Set} */ + const chunkGroups = new Set(); + for (const module of compilation.modules) { + if (!module.hasChunkCondition()) continue; + for (const chunk of chunkGraph.getModuleChunksIterable(module)) { + if (!module.chunkCondition(chunk, compilation)) { + sourceChunks.add(chunk); + for (const group of chunk.groupsIterable) { + chunkGroups.add(group); + } + } + } + if (sourceChunks.size === 0) continue; + /** @type {Set} */ + const targetChunks = new Set(); + chunkGroupLoop: for (const chunkGroup of chunkGroups) { + // Can module be placed in a chunk of this group? + for (const chunk of chunkGroup.chunks) { + if (module.chunkCondition(chunk, compilation)) { + targetChunks.add(chunk); + continue chunkGroupLoop; + } + } + // We reached the entrypoint: fail + if (chunkGroup.isInitial()) { + throw new Error( + "Cannot fullfil chunk condition of " + module.identifier() + ); + } + // Try placing in all parents + for (const group of chunkGroup.parentsIterable) { + chunkGroups.add(group); + } + } + for (const sourceChunk of sourceChunks) { + chunkGraph.disconnectChunkAndModule(sourceChunk, module); + } + for (const targetChunk of targetChunks) { + chunkGraph.connectChunkAndModule(targetChunk, module); + } + sourceChunks.clear(); + chunkGroups.clear(); + } + }; + compilation.hooks.optimizeChunks.tap( + { + name: "EnsureChunkConditionsPlugin", + stage: STAGE_BASIC + }, + handler + ); + } + ); + } +} +module.exports = EnsureChunkConditionsPlugin; + + +/***/ }), + +/***/ 50089: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +class FlagIncludedChunksPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap("FlagIncludedChunksPlugin", compilation => { + compilation.hooks.optimizeChunkIds.tap( + "FlagIncludedChunksPlugin", + chunks => { + const chunkGraph = compilation.chunkGraph; + + // prepare two bit integers for each module + // 2^31 is the max number represented as SMI in v8 + // we want the bits distributed this way: + // the bit 2^31 is pretty rar and only one module should get it + // so it has a probability of 1 / modulesCount + // the first bit (2^0) is the easiest and every module could get it + // if it doesn't get a better bit + // from bit 2^n to 2^(n+1) there is a probability of p + // so 1 / modulesCount == p^31 + // <=> p = sqrt31(1 / modulesCount) + // so we use a modulo of 1 / sqrt31(1 / modulesCount) + /** @type {WeakMap} */ + const moduleBits = new WeakMap(); + const modulesCount = compilation.modules.size; + + // precalculate the modulo values for each bit + const modulo = 1 / Math.pow(1 / modulesCount, 1 / 31); + const modulos = Array.from( + { length: 31 }, + (x, i) => Math.pow(modulo, i) | 0 + ); + + // iterate all modules to generate bit values + let i = 0; + for (const module of compilation.modules) { + let bit = 30; + while (i % modulos[bit] !== 0) { + bit--; + } + moduleBits.set(module, 1 << bit); + i++; + } + + // iterate all chunks to generate bitmaps + /** @type {WeakMap} */ + const chunkModulesHash = new WeakMap(); + for (const chunk of chunks) { + let hash = 0; + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + hash |= moduleBits.get(module); + } + chunkModulesHash.set(chunk, hash); + } + + for (const chunkA of chunks) { + const chunkAHash = chunkModulesHash.get(chunkA); + const chunkAModulesCount = + chunkGraph.getNumberOfChunkModules(chunkA); + if (chunkAModulesCount === 0) continue; + let bestModule = undefined; + for (const module of chunkGraph.getChunkModulesIterable(chunkA)) { + if ( + bestModule === undefined || + chunkGraph.getNumberOfModuleChunks(bestModule) > + chunkGraph.getNumberOfModuleChunks(module) + ) + bestModule = module; + } + loopB: for (const chunkB of chunkGraph.getModuleChunksIterable( + bestModule + )) { + // as we iterate the same iterables twice + // skip if we find ourselves + if (chunkA === chunkB) continue; + + const chunkBModulesCount = + chunkGraph.getNumberOfChunkModules(chunkB); + + // ids for empty chunks are not included + if (chunkBModulesCount === 0) continue; + + // instead of swapping A and B just bail + // as we loop twice the current A will be B and B then A + if (chunkAModulesCount > chunkBModulesCount) continue; + + // is chunkA in chunkB? + + // we do a cheap check for the hash value + const chunkBHash = chunkModulesHash.get(chunkB); + if ((chunkBHash & chunkAHash) !== chunkAHash) continue; + + // compare all modules + for (const m of chunkGraph.getChunkModulesIterable(chunkA)) { + if (!chunkGraph.isModuleInChunk(m, chunkB)) continue loopB; + } + chunkB.ids.push(chunkA.id); + } + } + } + ); + }); + } +} +module.exports = FlagIncludedChunksPlugin; + + +/***/ }), + +/***/ 38988: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + + + +const { UsageState } = __webpack_require__(63686); + +/** @typedef {import("estree").Node} AnyNode */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +/** @typedef {Map | true>} InnerGraph */ +/** @typedef {function(boolean | Set | undefined): void} UsageCallback */ + +/** + * @typedef {Object} StateObject + * @property {InnerGraph} innerGraph + * @property {TopLevelSymbol=} currentTopLevelSymbol + * @property {Map>} usageCallbackMap + */ + +/** @typedef {false|StateObject} State */ + +/** @type {WeakMap} */ +const parserStateMap = new WeakMap(); +const topLevelSymbolTag = Symbol("top level symbol"); + +/** + * @param {ParserState} parserState parser state + * @returns {State} state + */ +function getState(parserState) { + return parserStateMap.get(parserState); +} + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +exports.bailout = parserState => { + parserStateMap.set(parserState, false); +}; + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +exports.enable = parserState => { + const state = parserStateMap.get(parserState); + if (state === false) { + return; + } + parserStateMap.set(parserState, { + innerGraph: new Map(), + currentTopLevelSymbol: undefined, + usageCallbackMap: new Map() + }); +}; + +/** + * @param {ParserState} parserState parser state + * @returns {boolean} true, when enabled + */ +exports.isEnabled = parserState => { + const state = parserStateMap.get(parserState); + return !!state; +}; + +/** + * @param {ParserState} state parser state + * @param {TopLevelSymbol | null} symbol the symbol, or null for all symbols + * @param {string | TopLevelSymbol | true} usage usage data + * @returns {void} + */ +exports.addUsage = (state, symbol, usage) => { + const innerGraphState = getState(state); + + if (innerGraphState) { + const { innerGraph } = innerGraphState; + const info = innerGraph.get(symbol); + if (usage === true) { + innerGraph.set(symbol, true); + } else if (info === undefined) { + innerGraph.set(symbol, new Set([usage])); + } else if (info !== true) { + info.add(usage); + } + } +}; + +/** + * @param {JavascriptParser} parser the parser + * @param {string} name name of variable + * @param {string | TopLevelSymbol | true} usage usage data + * @returns {void} + */ +exports.addVariableUsage = (parser, name, usage) => { + const symbol = + /** @type {TopLevelSymbol} */ ( + parser.getTagData(name, topLevelSymbolTag) + ) || exports.tagTopLevelSymbol(parser, name); + if (symbol) { + exports.addUsage(parser.state, symbol, usage); + } +}; + +/** + * @param {ParserState} state parser state + * @returns {void} + */ +exports.inferDependencyUsage = state => { + const innerGraphState = getState(state); + + if (!innerGraphState) { + return; + } + + const { innerGraph, usageCallbackMap } = innerGraphState; + const processed = new Map(); + // flatten graph to terminal nodes (string, undefined or true) + const nonTerminal = new Set(innerGraph.keys()); + while (nonTerminal.size > 0) { + for (const key of nonTerminal) { + /** @type {Set | true} */ + let newSet = new Set(); + let isTerminal = true; + const value = innerGraph.get(key); + let alreadyProcessed = processed.get(key); + if (alreadyProcessed === undefined) { + alreadyProcessed = new Set(); + processed.set(key, alreadyProcessed); + } + if (value !== true && value !== undefined) { + for (const item of value) { + alreadyProcessed.add(item); + } + for (const item of value) { + if (typeof item === "string") { + newSet.add(item); + } else { + const itemValue = innerGraph.get(item); + if (itemValue === true) { + newSet = true; + break; + } + if (itemValue !== undefined) { + for (const i of itemValue) { + if (i === key) continue; + if (alreadyProcessed.has(i)) continue; + newSet.add(i); + if (typeof i !== "string") { + isTerminal = false; + } + } + } + } + } + if (newSet === true) { + innerGraph.set(key, true); + } else if (newSet.size === 0) { + innerGraph.set(key, undefined); + } else { + innerGraph.set(key, newSet); + } + } + if (isTerminal) { + nonTerminal.delete(key); + + // For the global key, merge with all other keys + if (key === null) { + const globalValue = innerGraph.get(null); + if (globalValue) { + for (const [key, value] of innerGraph) { + if (key !== null && value !== true) { + if (globalValue === true) { + innerGraph.set(key, true); + } else { + const newSet = new Set(value); + for (const item of globalValue) { + newSet.add(item); + } + innerGraph.set(key, newSet); + } + } + } + } + } + } + } + } + + /** @type {Map>} */ + for (const [symbol, callbacks] of usageCallbackMap) { + const usage = /** @type {true | Set | undefined} */ ( + innerGraph.get(symbol) + ); + for (const callback of callbacks) { + callback(usage === undefined ? false : usage); + } + } +}; + +/** + * @param {ParserState} state parser state + * @param {UsageCallback} onUsageCallback on usage callback + */ +exports.onUsage = (state, onUsageCallback) => { + const innerGraphState = getState(state); + + if (innerGraphState) { + const { usageCallbackMap, currentTopLevelSymbol } = innerGraphState; + if (currentTopLevelSymbol) { + let callbacks = usageCallbackMap.get(currentTopLevelSymbol); + + if (callbacks === undefined) { + callbacks = new Set(); + usageCallbackMap.set(currentTopLevelSymbol, callbacks); + } + + callbacks.add(onUsageCallback); + } else { + onUsageCallback(true); + } + } else { + onUsageCallback(undefined); + } +}; + +/** + * @param {ParserState} state parser state + * @param {TopLevelSymbol} symbol the symbol + */ +exports.setTopLevelSymbol = (state, symbol) => { + const innerGraphState = getState(state); + + if (innerGraphState) { + innerGraphState.currentTopLevelSymbol = symbol; + } +}; + +/** + * @param {ParserState} state parser state + * @returns {TopLevelSymbol|void} usage data + */ +exports.getTopLevelSymbol = state => { + const innerGraphState = getState(state); + + if (innerGraphState) { + return innerGraphState.currentTopLevelSymbol; + } +}; + +/** + * @param {JavascriptParser} parser parser + * @param {string} name name of variable + * @returns {TopLevelSymbol} symbol + */ +exports.tagTopLevelSymbol = (parser, name) => { + const innerGraphState = getState(parser.state); + if (!innerGraphState) return; + + parser.defineVariable(name); + + const existingTag = /** @type {TopLevelSymbol} */ ( + parser.getTagData(name, topLevelSymbolTag) + ); + if (existingTag) { + return existingTag; + } + + const fn = new TopLevelSymbol(name); + parser.tagVariable(name, topLevelSymbolTag, fn); + return fn; +}; + +/** + * @param {Dependency} dependency the dependency + * @param {Set | boolean} usedByExports usedByExports info + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {RuntimeSpec} runtime runtime + * @returns {boolean} false, when unused. Otherwise true + */ +exports.isDependencyUsedByExports = ( + dependency, + usedByExports, + moduleGraph, + runtime +) => { + if (usedByExports === false) return false; + if (usedByExports !== true && usedByExports !== undefined) { + const selfModule = moduleGraph.getParentModule(dependency); + const exportsInfo = moduleGraph.getExportsInfo(selfModule); + let used = false; + for (const exportName of usedByExports) { + if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) + used = true; + } + if (!used) return false; + } + return true; +}; + +/** + * @param {Dependency} dependency the dependency + * @param {Set | boolean} usedByExports usedByExports info + * @param {ModuleGraph} moduleGraph moduleGraph + * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active + */ +exports.getDependencyUsedByExportsCondition = ( + dependency, + usedByExports, + moduleGraph +) => { + if (usedByExports === false) return false; + if (usedByExports !== true && usedByExports !== undefined) { + const selfModule = moduleGraph.getParentModule(dependency); + const exportsInfo = moduleGraph.getExportsInfo(selfModule); + return (connections, runtime) => { + for (const exportName of usedByExports) { + if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) + return true; + } + return false; + }; + } + return null; +}; + +class TopLevelSymbol { + /** + * @param {string} name name of the variable + */ + constructor(name) { + this.name = name; + } +} + +exports.TopLevelSymbol = TopLevelSymbol; +exports.topLevelSymbolTag = topLevelSymbolTag; + + +/***/ }), + +/***/ 28758: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const PureExpressionDependency = __webpack_require__(55799); +const InnerGraph = __webpack_require__(38988); + +/** @typedef {import("estree").ClassDeclaration} ClassDeclarationNode */ +/** @typedef {import("estree").ClassExpression} ClassExpressionNode */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("estree").VariableDeclarator} VariableDeclaratorNode */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../dependencies/HarmonyImportSpecifierDependency")} HarmonyImportSpecifierDependency */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./InnerGraph").InnerGraph} InnerGraph */ +/** @typedef {import("./InnerGraph").TopLevelSymbol} TopLevelSymbol */ + +const { topLevelSymbolTag } = InnerGraph; + +class InnerGraphPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "InnerGraphPlugin", + (compilation, { normalModuleFactory }) => { + const logger = compilation.getLogger("webpack.InnerGraphPlugin"); + + compilation.dependencyTemplates.set( + PureExpressionDependency, + new PureExpressionDependency.Template() + ); + + /** + * @param {JavascriptParser} parser the parser + * @param {Object} parserOptions options + * @returns {void} + */ + const handler = (parser, parserOptions) => { + const onUsageSuper = sup => { + InnerGraph.onUsage(parser.state, usedByExports => { + switch (usedByExports) { + case undefined: + case true: + return; + default: { + const dep = new PureExpressionDependency(sup.range); + dep.loc = sup.loc; + dep.usedByExports = usedByExports; + parser.state.module.addDependency(dep); + break; + } + } + }); + }; + + parser.hooks.program.tap("InnerGraphPlugin", () => { + InnerGraph.enable(parser.state); + }); + + parser.hooks.finish.tap("InnerGraphPlugin", () => { + if (!InnerGraph.isEnabled(parser.state)) return; + + logger.time("infer dependency usage"); + InnerGraph.inferDependencyUsage(parser.state); + logger.timeAggregate("infer dependency usage"); + }); + + // During prewalking the following datastructures are filled with + // nodes that have a TopLevelSymbol assigned and + // variables are tagged with the assigned TopLevelSymbol + + // We differ 3 types of nodes: + // 1. full statements (export default, function declaration) + // 2. classes (class declaration, class expression) + // 3. variable declarators (const x = ...) + + /** @type {WeakMap} */ + const statementWithTopLevelSymbol = new WeakMap(); + /** @type {WeakMap} */ + const statementPurePart = new WeakMap(); + + /** @type {WeakMap} */ + const classWithTopLevelSymbol = new WeakMap(); + + /** @type {WeakMap} */ + const declWithTopLevelSymbol = new WeakMap(); + /** @type {WeakSet} */ + const pureDeclarators = new WeakSet(); + + // The following hooks are used during prewalking: + + parser.hooks.preStatement.tap("InnerGraphPlugin", statement => { + if (!InnerGraph.isEnabled(parser.state)) return; + + if (parser.scope.topLevelScope === true) { + if (statement.type === "FunctionDeclaration") { + const name = statement.id ? statement.id.name : "*default*"; + const fn = InnerGraph.tagTopLevelSymbol(parser, name); + statementWithTopLevelSymbol.set(statement, fn); + return true; + } + } + }); + + parser.hooks.blockPreStatement.tap("InnerGraphPlugin", statement => { + if (!InnerGraph.isEnabled(parser.state)) return; + + if (parser.scope.topLevelScope === true) { + if (statement.type === "ClassDeclaration") { + const name = statement.id ? statement.id.name : "*default*"; + const fn = InnerGraph.tagTopLevelSymbol(parser, name); + classWithTopLevelSymbol.set(statement, fn); + return true; + } + if (statement.type === "ExportDefaultDeclaration") { + const name = "*default*"; + const fn = InnerGraph.tagTopLevelSymbol(parser, name); + const decl = statement.declaration; + if ( + decl.type === "ClassExpression" || + decl.type === "ClassDeclaration" + ) { + classWithTopLevelSymbol.set(decl, fn); + } else if (parser.isPure(decl, statement.range[0])) { + statementWithTopLevelSymbol.set(statement, fn); + if ( + !decl.type.endsWith("FunctionExpression") && + !decl.type.endsWith("Declaration") && + decl.type !== "Literal" + ) { + statementPurePart.set(statement, decl); + } + } + } + } + }); + + parser.hooks.preDeclarator.tap( + "InnerGraphPlugin", + (decl, statement) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if ( + parser.scope.topLevelScope === true && + decl.init && + decl.id.type === "Identifier" + ) { + const name = decl.id.name; + if (decl.init.type === "ClassExpression") { + const fn = InnerGraph.tagTopLevelSymbol(parser, name); + classWithTopLevelSymbol.set(decl.init, fn); + } else if (parser.isPure(decl.init, decl.id.range[1])) { + const fn = InnerGraph.tagTopLevelSymbol(parser, name); + declWithTopLevelSymbol.set(decl, fn); + if ( + !decl.init.type.endsWith("FunctionExpression") && + decl.init.type !== "Literal" + ) { + pureDeclarators.add(decl); + } + return true; + } + } + } + ); + + // During real walking we set the TopLevelSymbol state to the assigned + // TopLevelSymbol by using the fill datastructures. + + // In addition to tracking TopLevelSymbols, we sometimes need to + // add a PureExpressionDependency. This is needed to skip execution + // of pure expressions, even when they are not dropped due to + // minimizing. Otherwise symbols used there might not exist anymore + // as they are removed as unused by this optimization + + // When we find a reference to a TopLevelSymbol, we register a + // TopLevelSymbol dependency from TopLevelSymbol in state to the + // referenced TopLevelSymbol. This way we get a graph of all + // TopLevelSymbols. + + // The following hooks are called during walking: + + parser.hooks.statement.tap("InnerGraphPlugin", statement => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (parser.scope.topLevelScope === true) { + InnerGraph.setTopLevelSymbol(parser.state, undefined); + + const fn = statementWithTopLevelSymbol.get(statement); + if (fn) { + InnerGraph.setTopLevelSymbol(parser.state, fn); + const purePart = statementPurePart.get(statement); + if (purePart) { + InnerGraph.onUsage(parser.state, usedByExports => { + switch (usedByExports) { + case undefined: + case true: + return; + default: { + const dep = new PureExpressionDependency( + purePart.range + ); + dep.loc = statement.loc; + dep.usedByExports = usedByExports; + parser.state.module.addDependency(dep); + break; + } + } + }); + } + } + } + }); + + parser.hooks.classExtendsExpression.tap( + "InnerGraphPlugin", + (expr, statement) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (parser.scope.topLevelScope === true) { + const fn = classWithTopLevelSymbol.get(statement); + if ( + fn && + parser.isPure( + expr, + statement.id ? statement.id.range[1] : statement.range[0] + ) + ) { + InnerGraph.setTopLevelSymbol(parser.state, fn); + onUsageSuper(expr); + } + } + } + ); + + parser.hooks.classBodyElement.tap( + "InnerGraphPlugin", + (element, classDefinition) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (parser.scope.topLevelScope === true) { + const fn = classWithTopLevelSymbol.get(classDefinition); + if (fn) { + InnerGraph.setTopLevelSymbol(parser.state, undefined); + } + } + } + ); + + parser.hooks.classBodyValue.tap( + "InnerGraphPlugin", + (expression, element, classDefinition) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (parser.scope.topLevelScope === true) { + const fn = classWithTopLevelSymbol.get(classDefinition); + if (fn) { + if ( + !element.static || + parser.isPure( + expression, + element.key ? element.key.range[1] : element.range[0] + ) + ) { + InnerGraph.setTopLevelSymbol(parser.state, fn); + if (element.type !== "MethodDefinition" && element.static) { + InnerGraph.onUsage(parser.state, usedByExports => { + switch (usedByExports) { + case undefined: + case true: + return; + default: { + const dep = new PureExpressionDependency( + expression.range + ); + dep.loc = expression.loc; + dep.usedByExports = usedByExports; + parser.state.module.addDependency(dep); + break; + } + } + }); + } + } else { + InnerGraph.setTopLevelSymbol(parser.state, undefined); + } + } + } + } + ); + + parser.hooks.declarator.tap("InnerGraphPlugin", (decl, statement) => { + if (!InnerGraph.isEnabled(parser.state)) return; + const fn = declWithTopLevelSymbol.get(decl); + + if (fn) { + InnerGraph.setTopLevelSymbol(parser.state, fn); + if (pureDeclarators.has(decl)) { + if (decl.init.type === "ClassExpression") { + if (decl.init.superClass) { + onUsageSuper(decl.init.superClass); + } + } else { + InnerGraph.onUsage(parser.state, usedByExports => { + switch (usedByExports) { + case undefined: + case true: + return; + default: { + const dep = new PureExpressionDependency( + decl.init.range + ); + dep.loc = decl.loc; + dep.usedByExports = usedByExports; + parser.state.module.addDependency(dep); + break; + } + } + }); + } + } + parser.walkExpression(decl.init); + InnerGraph.setTopLevelSymbol(parser.state, undefined); + return true; + } + }); + + parser.hooks.expression + .for(topLevelSymbolTag) + .tap("InnerGraphPlugin", () => { + const topLevelSymbol = /** @type {TopLevelSymbol} */ ( + parser.currentTagData + ); + const currentTopLevelSymbol = InnerGraph.getTopLevelSymbol( + parser.state + ); + InnerGraph.addUsage( + parser.state, + topLevelSymbol, + currentTopLevelSymbol || true + ); + }); + parser.hooks.assign + .for(topLevelSymbolTag) + .tap("InnerGraphPlugin", expr => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (expr.operator === "=") return true; + }); + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("InnerGraphPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("InnerGraphPlugin", handler); + + compilation.hooks.finishModules.tap("InnerGraphPlugin", () => { + logger.timeAggregateEnd("infer dependency usage"); + }); + } + ); + } +} + +module.exports = InnerGraphPlugin; + + +/***/ }), + +/***/ 83608: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { STAGE_ADVANCED } = __webpack_require__(80057); +const LazyBucketSortedSet = __webpack_require__(48424); +const { compareChunks } = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); + +/** @typedef {import("../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions} LimitChunkCountPluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +const validate = createSchemaValidation( + __webpack_require__(36557), + () => __webpack_require__(30837), + { + name: "Limit Chunk Count Plugin", + baseDataPath: "options" + } +); + +/** + * @typedef {Object} ChunkCombination + * @property {boolean} deleted this is set to true when combination was removed + * @property {number} sizeDiff + * @property {number} integratedSize + * @property {Chunk} a + * @property {Chunk} b + * @property {number} aIdx + * @property {number} bIdx + * @property {number} aSize + * @property {number} bSize + */ + +const addToSetMap = (map, key, value) => { + const set = map.get(key); + if (set === undefined) { + map.set(key, new Set([value])); + } else { + set.add(value); + } +}; + +class LimitChunkCountPlugin { + /** + * @param {LimitChunkCountPluginOptions=} options options object + */ + constructor(options) { + validate(options); + this.options = options; + } + + /** + * @param {Compiler} compiler the webpack compiler + * @returns {void} + */ + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("LimitChunkCountPlugin", compilation => { + compilation.hooks.optimizeChunks.tap( + { + name: "LimitChunkCountPlugin", + stage: STAGE_ADVANCED + }, + chunks => { + const chunkGraph = compilation.chunkGraph; + const maxChunks = options.maxChunks; + if (!maxChunks) return; + if (maxChunks < 1) return; + if (compilation.chunks.size <= maxChunks) return; + + let remainingChunksToMerge = compilation.chunks.size - maxChunks; + + // order chunks in a deterministic way + const compareChunksWithGraph = compareChunks(chunkGraph); + const orderedChunks = Array.from(chunks).sort(compareChunksWithGraph); + + // create a lazy sorted data structure to keep all combinations + // this is large. Size = chunks * (chunks - 1) / 2 + // It uses a multi layer bucket sort plus normal sort in the last layer + // It's also lazy so only accessed buckets are sorted + const combinations = new LazyBucketSortedSet( + // Layer 1: ordered by largest size benefit + c => c.sizeDiff, + (a, b) => b - a, + // Layer 2: ordered by smallest combined size + c => c.integratedSize, + (a, b) => a - b, + // Layer 3: ordered by position difference in orderedChunk (-> to be deterministic) + c => c.bIdx - c.aIdx, + (a, b) => a - b, + // Layer 4: ordered by position in orderedChunk (-> to be deterministic) + (a, b) => a.bIdx - b.bIdx + ); + + // we keep a mapping from chunk to all combinations + // but this mapping is not kept up-to-date with deletions + // so `deleted` flag need to be considered when iterating this + /** @type {Map>} */ + const combinationsByChunk = new Map(); + + orderedChunks.forEach((b, bIdx) => { + // create combination pairs with size and integrated size + for (let aIdx = 0; aIdx < bIdx; aIdx++) { + const a = orderedChunks[aIdx]; + // filter pairs that can not be integrated! + if (!chunkGraph.canChunksBeIntegrated(a, b)) continue; + + const integratedSize = chunkGraph.getIntegratedChunksSize( + a, + b, + options + ); + + const aSize = chunkGraph.getChunkSize(a, options); + const bSize = chunkGraph.getChunkSize(b, options); + const c = { + deleted: false, + sizeDiff: aSize + bSize - integratedSize, + integratedSize, + a, + b, + aIdx, + bIdx, + aSize, + bSize + }; + combinations.add(c); + addToSetMap(combinationsByChunk, a, c); + addToSetMap(combinationsByChunk, b, c); + } + return combinations; + }); + + // list of modified chunks during this run + // combinations affected by this change are skipped to allow + // further optimizations + /** @type {Set} */ + const modifiedChunks = new Set(); + + let changed = false; + // eslint-disable-next-line no-constant-condition + loop: while (true) { + const combination = combinations.popFirst(); + if (combination === undefined) break; + + combination.deleted = true; + const { a, b, integratedSize } = combination; + + // skip over pair when + // one of the already merged chunks is a parent of one of the chunks + if (modifiedChunks.size > 0) { + const queue = new Set(a.groupsIterable); + for (const group of b.groupsIterable) { + queue.add(group); + } + for (const group of queue) { + for (const mChunk of modifiedChunks) { + if (mChunk !== a && mChunk !== b && mChunk.isInGroup(group)) { + // This is a potential pair which needs recalculation + // We can't do that now, but it merge before following pairs + // so we leave space for it, and consider chunks as modified + // just for the worse case + remainingChunksToMerge--; + if (remainingChunksToMerge <= 0) break loop; + modifiedChunks.add(a); + modifiedChunks.add(b); + continue loop; + } + } + for (const parent of group.parentsIterable) { + queue.add(parent); + } + } + } + + // merge the chunks + if (chunkGraph.canChunksBeIntegrated(a, b)) { + chunkGraph.integrateChunks(a, b); + compilation.chunks.delete(b); + + // flag chunk a as modified as further optimization are possible for all children here + modifiedChunks.add(a); + + changed = true; + remainingChunksToMerge--; + if (remainingChunksToMerge <= 0) break; + + // Update all affected combinations + // delete all combination with the removed chunk + // we will use combinations with the kept chunk instead + for (const combination of combinationsByChunk.get(a)) { + if (combination.deleted) continue; + combination.deleted = true; + combinations.delete(combination); + } + + // Update combinations with the kept chunk with new sizes + for (const combination of combinationsByChunk.get(b)) { + if (combination.deleted) continue; + if (combination.a === b) { + if (!chunkGraph.canChunksBeIntegrated(a, combination.b)) { + combination.deleted = true; + combinations.delete(combination); + continue; + } + // Update size + const newIntegratedSize = chunkGraph.getIntegratedChunksSize( + a, + combination.b, + options + ); + const finishUpdate = combinations.startUpdate(combination); + combination.a = a; + combination.integratedSize = newIntegratedSize; + combination.aSize = integratedSize; + combination.sizeDiff = + combination.bSize + integratedSize - newIntegratedSize; + finishUpdate(); + } else if (combination.b === b) { + if (!chunkGraph.canChunksBeIntegrated(combination.a, a)) { + combination.deleted = true; + combinations.delete(combination); + continue; + } + // Update size + const newIntegratedSize = chunkGraph.getIntegratedChunksSize( + combination.a, + a, + options + ); + + const finishUpdate = combinations.startUpdate(combination); + combination.b = a; + combination.integratedSize = newIntegratedSize; + combination.bSize = integratedSize; + combination.sizeDiff = + integratedSize + combination.aSize - newIntegratedSize; + finishUpdate(); + } + } + combinationsByChunk.set(a, combinationsByChunk.get(b)); + combinationsByChunk.delete(b); + } + } + if (changed) return true; + } + ); + }); + } +} +module.exports = LimitChunkCountPlugin; + + +/***/ }), + +/***/ 27868: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { UsageState } = __webpack_require__(63686); +const { + numberToIdentifier, + NUMBER_OF_IDENTIFIER_START_CHARS, + NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS +} = __webpack_require__(39722); +const { assignDeterministicIds } = __webpack_require__(63290); +const { compareSelect, compareStringsNumeric } = __webpack_require__(29579); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../ExportsInfo")} ExportsInfo */ +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ + +/** + * @param {ExportsInfo} exportsInfo exports info + * @returns {boolean} mangle is possible + */ +const canMangle = exportsInfo => { + if (exportsInfo.otherExportsInfo.getUsed(undefined) !== UsageState.Unused) + return false; + let hasSomethingToMangle = false; + for (const exportInfo of exportsInfo.exports) { + if (exportInfo.canMangle === true) { + hasSomethingToMangle = true; + } + } + return hasSomethingToMangle; +}; + +// Sort by name +const comparator = compareSelect(e => e.name, compareStringsNumeric); +/** + * @param {boolean} deterministic use deterministic names + * @param {ExportsInfo} exportsInfo exports info + * @param {boolean} isNamespace is namespace object + * @returns {void} + */ +const mangleExportsInfo = (deterministic, exportsInfo, isNamespace) => { + if (!canMangle(exportsInfo)) return; + const usedNames = new Set(); + /** @type {ExportInfo[]} */ + const mangleableExports = []; + + // Avoid to renamed exports that are not provided when + // 1. it's not a namespace export: non-provided exports can be found in prototype chain + // 2. there are other provided exports and deterministic mode is chosen: + // non-provided exports would break the determinism + let avoidMangleNonProvided = !isNamespace; + if (!avoidMangleNonProvided && deterministic) { + for (const exportInfo of exportsInfo.ownedExports) { + if (exportInfo.provided !== false) { + avoidMangleNonProvided = true; + break; + } + } + } + for (const exportInfo of exportsInfo.ownedExports) { + const name = exportInfo.name; + if (!exportInfo.hasUsedName()) { + if ( + // Can the export be mangled? + exportInfo.canMangle !== true || + // Never rename 1 char exports + (name.length === 1 && /^[a-zA-Z0-9_$]/.test(name)) || + // Don't rename 2 char exports in deterministic mode + (deterministic && + name.length === 2 && + /^[a-zA-Z_$][a-zA-Z0-9_$]|^[1-9][0-9]/.test(name)) || + // Don't rename exports that are not provided + (avoidMangleNonProvided && exportInfo.provided !== true) + ) { + exportInfo.setUsedName(name); + usedNames.add(name); + } else { + mangleableExports.push(exportInfo); + } + } + if (exportInfo.exportsInfoOwned) { + const used = exportInfo.getUsed(undefined); + if ( + used === UsageState.OnlyPropertiesUsed || + used === UsageState.Unused + ) { + mangleExportsInfo(deterministic, exportInfo.exportsInfo, false); + } + } + } + if (deterministic) { + assignDeterministicIds( + mangleableExports, + e => e.name, + comparator, + (e, id) => { + const name = numberToIdentifier(id); + const size = usedNames.size; + usedNames.add(name); + if (size === usedNames.size) return false; + e.setUsedName(name); + return true; + }, + [ + NUMBER_OF_IDENTIFIER_START_CHARS, + NUMBER_OF_IDENTIFIER_START_CHARS * + NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS + ], + NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS, + usedNames.size + ); + } else { + const usedExports = []; + const unusedExports = []; + for (const exportInfo of mangleableExports) { + if (exportInfo.getUsed(undefined) === UsageState.Unused) { + unusedExports.push(exportInfo); + } else { + usedExports.push(exportInfo); + } + } + usedExports.sort(comparator); + unusedExports.sort(comparator); + let i = 0; + for (const list of [usedExports, unusedExports]) { + for (const exportInfo of list) { + let name; + do { + name = numberToIdentifier(i++); + } while (usedNames.has(name)); + exportInfo.setUsedName(name); + } + } + } +}; + +class MangleExportsPlugin { + /** + * @param {boolean} deterministic use deterministic names + */ + constructor(deterministic) { + this._deterministic = deterministic; + } + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { _deterministic: deterministic } = this; + compiler.hooks.compilation.tap("MangleExportsPlugin", compilation => { + const moduleGraph = compilation.moduleGraph; + compilation.hooks.optimizeCodeGeneration.tap( + "MangleExportsPlugin", + modules => { + if (compilation.moduleMemCaches) { + throw new Error( + "optimization.mangleExports can't be used with cacheUnaffected as export mangling is a global effect" + ); + } + for (const module of modules) { + const isNamespace = + module.buildMeta && module.buildMeta.exportsType === "namespace"; + const exportsInfo = moduleGraph.getExportsInfo(module); + mangleExportsInfo(deterministic, exportsInfo, isNamespace); + } + } + ); + }); + } +} + +module.exports = MangleExportsPlugin; + + +/***/ }), + +/***/ 85067: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { STAGE_BASIC } = __webpack_require__(80057); +const { runtimeEqual } = __webpack_require__(17156); + +/** @typedef {import("../Compiler")} Compiler */ + +class MergeDuplicateChunksPlugin { + /** + * @param {Compiler} compiler the compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "MergeDuplicateChunksPlugin", + compilation => { + compilation.hooks.optimizeChunks.tap( + { + name: "MergeDuplicateChunksPlugin", + stage: STAGE_BASIC + }, + chunks => { + const { chunkGraph, moduleGraph } = compilation; + + // remember already tested chunks for performance + const notDuplicates = new Set(); + + // for each chunk + for (const chunk of chunks) { + // track a Set of all chunk that could be duplicates + let possibleDuplicates; + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (possibleDuplicates === undefined) { + // when possibleDuplicates is not yet set, + // create a new Set from chunks of the current module + // including only chunks with the same number of modules + for (const dup of chunkGraph.getModuleChunksIterable( + module + )) { + if ( + dup !== chunk && + chunkGraph.getNumberOfChunkModules(chunk) === + chunkGraph.getNumberOfChunkModules(dup) && + !notDuplicates.has(dup) + ) { + // delay allocating the new Set until here, reduce memory pressure + if (possibleDuplicates === undefined) { + possibleDuplicates = new Set(); + } + possibleDuplicates.add(dup); + } + } + // when no chunk is possible we can break here + if (possibleDuplicates === undefined) break; + } else { + // validate existing possible duplicates + for (const dup of possibleDuplicates) { + // remove possible duplicate when module is not contained + if (!chunkGraph.isModuleInChunk(module, dup)) { + possibleDuplicates.delete(dup); + } + } + // when all chunks has been removed we can break here + if (possibleDuplicates.size === 0) break; + } + } + + // when we found duplicates + if ( + possibleDuplicates !== undefined && + possibleDuplicates.size > 0 + ) { + outer: for (const otherChunk of possibleDuplicates) { + if (otherChunk.hasRuntime() !== chunk.hasRuntime()) continue; + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) continue; + if (chunkGraph.getNumberOfEntryModules(otherChunk) > 0) + continue; + if (!runtimeEqual(chunk.runtime, otherChunk.runtime)) { + for (const module of chunkGraph.getChunkModulesIterable( + chunk + )) { + const exportsInfo = moduleGraph.getExportsInfo(module); + if ( + !exportsInfo.isEquallyUsed( + chunk.runtime, + otherChunk.runtime + ) + ) { + continue outer; + } + } + } + // merge them + if (chunkGraph.canChunksBeIntegrated(chunk, otherChunk)) { + chunkGraph.integrateChunks(chunk, otherChunk); + compilation.chunks.delete(otherChunk); + } + } + } + + // don't check already processed chunks twice + notDuplicates.add(chunk); + } + } + ); + } + ); + } +} +module.exports = MergeDuplicateChunksPlugin; + + +/***/ }), + +/***/ 53912: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { STAGE_ADVANCED } = __webpack_require__(80057); +const createSchemaValidation = __webpack_require__(32540); + +/** @typedef {import("../../declarations/plugins/optimize/MinChunkSizePlugin").MinChunkSizePluginOptions} MinChunkSizePluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +const validate = createSchemaValidation( + __webpack_require__(60135), + () => __webpack_require__(53850), + { + name: "Min Chunk Size Plugin", + baseDataPath: "options" + } +); + +class MinChunkSizePlugin { + /** + * @param {MinChunkSizePluginOptions} options options object + */ + constructor(options) { + validate(options); + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const options = this.options; + const minChunkSize = options.minChunkSize; + compiler.hooks.compilation.tap("MinChunkSizePlugin", compilation => { + compilation.hooks.optimizeChunks.tap( + { + name: "MinChunkSizePlugin", + stage: STAGE_ADVANCED + }, + chunks => { + const chunkGraph = compilation.chunkGraph; + const equalOptions = { + chunkOverhead: 1, + entryChunkMultiplicator: 1 + }; + + const chunkSizesMap = new Map(); + /** @type {[Chunk, Chunk][]} */ + const combinations = []; + /** @type {Chunk[]} */ + const smallChunks = []; + const visitedChunks = []; + for (const a of chunks) { + // check if one of the chunks sizes is smaller than the minChunkSize + // and filter pairs that can NOT be integrated! + if (chunkGraph.getChunkSize(a, equalOptions) < minChunkSize) { + smallChunks.push(a); + for (const b of visitedChunks) { + if (chunkGraph.canChunksBeIntegrated(b, a)) + combinations.push([b, a]); + } + } else { + for (const b of smallChunks) { + if (chunkGraph.canChunksBeIntegrated(b, a)) + combinations.push([b, a]); + } + } + chunkSizesMap.set(a, chunkGraph.getChunkSize(a, options)); + visitedChunks.push(a); + } + + const sortedSizeFilteredExtendedPairCombinations = combinations + .map(pair => { + // extend combination pairs with size and integrated size + const a = chunkSizesMap.get(pair[0]); + const b = chunkSizesMap.get(pair[1]); + const ab = chunkGraph.getIntegratedChunksSize( + pair[0], + pair[1], + options + ); + /** @type {[number, number, Chunk, Chunk]} */ + const extendedPair = [a + b - ab, ab, pair[0], pair[1]]; + return extendedPair; + }) + .sort((a, b) => { + // sadly javascript does an in place sort here + // sort by size + const diff = b[0] - a[0]; + if (diff !== 0) return diff; + return a[1] - b[1]; + }); + + if (sortedSizeFilteredExtendedPairCombinations.length === 0) return; + + const pair = sortedSizeFilteredExtendedPairCombinations[0]; + + chunkGraph.integrateChunks(pair[2], pair[3]); + compilation.chunks.delete(pair[3]); + return true; + } + ); + }); + } +} +module.exports = MinChunkSizePlugin; + + +/***/ }), + +/***/ 85305: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const SizeFormatHelpers = __webpack_require__(71070); +const WebpackError = __webpack_require__(53799); + +class MinMaxSizeWarning extends WebpackError { + constructor(keys, minSize, maxSize) { + let keysMessage = "Fallback cache group"; + if (keys) { + keysMessage = + keys.length > 1 + ? `Cache groups ${keys.sort().join(", ")}` + : `Cache group ${keys[0]}`; + } + super( + `SplitChunksPlugin\n` + + `${keysMessage}\n` + + `Configured minSize (${SizeFormatHelpers.formatSize(minSize)}) is ` + + `bigger than maxSize (${SizeFormatHelpers.formatSize(maxSize)}).\n` + + "This seem to be a invalid optimization.splitChunks configuration." + ); + } +} + +module.exports = MinMaxSizeWarning; + + +/***/ }), + +/***/ 74844: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const asyncLib = __webpack_require__(78175); +const ChunkGraph = __webpack_require__(64971); +const ModuleGraph = __webpack_require__(99988); +const { STAGE_DEFAULT } = __webpack_require__(80057); +const HarmonyImportDependency = __webpack_require__(57154); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const { + intersectRuntime, + mergeRuntimeOwned, + filterRuntime, + runtimeToString, + mergeRuntime +} = __webpack_require__(17156); +const ConcatenatedModule = __webpack_require__(97198); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @typedef {Object} Statistics + * @property {number} cached + * @property {number} alreadyInConfig + * @property {number} invalidModule + * @property {number} incorrectChunks + * @property {number} incorrectDependency + * @property {number} incorrectModuleDependency + * @property {number} incorrectChunksOfImporter + * @property {number} incorrectRuntimeCondition + * @property {number} importerFailed + * @property {number} added + */ + +const formatBailoutReason = msg => { + return "ModuleConcatenation bailout: " + msg; +}; + +class ModuleConcatenationPlugin { + constructor(options) { + if (typeof options !== "object") options = {}; + this.options = options; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { _backCompat: backCompat } = compiler; + compiler.hooks.compilation.tap("ModuleConcatenationPlugin", compilation => { + const moduleGraph = compilation.moduleGraph; + const bailoutReasonMap = new Map(); + + const setBailoutReason = (module, reason) => { + setInnerBailoutReason(module, reason); + moduleGraph + .getOptimizationBailout(module) + .push( + typeof reason === "function" + ? rs => formatBailoutReason(reason(rs)) + : formatBailoutReason(reason) + ); + }; + + const setInnerBailoutReason = (module, reason) => { + bailoutReasonMap.set(module, reason); + }; + + const getInnerBailoutReason = (module, requestShortener) => { + const reason = bailoutReasonMap.get(module); + if (typeof reason === "function") return reason(requestShortener); + return reason; + }; + + const formatBailoutWarning = (module, problem) => requestShortener => { + if (typeof problem === "function") { + return formatBailoutReason( + `Cannot concat with ${module.readableIdentifier( + requestShortener + )}: ${problem(requestShortener)}` + ); + } + const reason = getInnerBailoutReason(module, requestShortener); + const reasonWithPrefix = reason ? `: ${reason}` : ""; + if (module === problem) { + return formatBailoutReason( + `Cannot concat with ${module.readableIdentifier( + requestShortener + )}${reasonWithPrefix}` + ); + } else { + return formatBailoutReason( + `Cannot concat with ${module.readableIdentifier( + requestShortener + )} because of ${problem.readableIdentifier( + requestShortener + )}${reasonWithPrefix}` + ); + } + }; + + compilation.hooks.optimizeChunkModules.tapAsync( + { + name: "ModuleConcatenationPlugin", + stage: STAGE_DEFAULT + }, + (allChunks, modules, callback) => { + const logger = compilation.getLogger( + "webpack.ModuleConcatenationPlugin" + ); + const { chunkGraph, moduleGraph } = compilation; + const relevantModules = []; + const possibleInners = new Set(); + const context = { + chunkGraph, + moduleGraph + }; + logger.time("select relevant modules"); + for (const module of modules) { + let canBeRoot = true; + let canBeInner = true; + + const bailoutReason = module.getConcatenationBailoutReason(context); + if (bailoutReason) { + setBailoutReason(module, bailoutReason); + continue; + } + + // Must not be an async module + if (moduleGraph.isAsync(module)) { + setBailoutReason(module, `Module is async`); + continue; + } + + // Must be in strict mode + if (!module.buildInfo.strict) { + setBailoutReason(module, `Module is not in strict mode`); + continue; + } + + // Module must be in any chunk (we don't want to do useless work) + if (chunkGraph.getNumberOfModuleChunks(module) === 0) { + setBailoutReason(module, "Module is not in any chunk"); + continue; + } + + // Exports must be known (and not dynamic) + const exportsInfo = moduleGraph.getExportsInfo(module); + const relevantExports = exportsInfo.getRelevantExports(undefined); + const unknownReexports = relevantExports.filter(exportInfo => { + return ( + exportInfo.isReexport() && !exportInfo.getTarget(moduleGraph) + ); + }); + if (unknownReexports.length > 0) { + setBailoutReason( + module, + `Reexports in this module do not have a static target (${Array.from( + unknownReexports, + exportInfo => + `${ + exportInfo.name || "other exports" + }: ${exportInfo.getUsedInfo()}` + ).join(", ")})` + ); + continue; + } + + // Root modules must have a static list of exports + const unknownProvidedExports = relevantExports.filter( + exportInfo => { + return exportInfo.provided !== true; + } + ); + if (unknownProvidedExports.length > 0) { + setBailoutReason( + module, + `List of module exports is dynamic (${Array.from( + unknownProvidedExports, + exportInfo => + `${ + exportInfo.name || "other exports" + }: ${exportInfo.getProvidedInfo()} and ${exportInfo.getUsedInfo()}` + ).join(", ")})` + ); + canBeRoot = false; + } + + // Module must not be an entry point + if (chunkGraph.isEntryModule(module)) { + setInnerBailoutReason(module, "Module is an entry point"); + canBeInner = false; + } + + if (canBeRoot) relevantModules.push(module); + if (canBeInner) possibleInners.add(module); + } + logger.timeEnd("select relevant modules"); + logger.debug( + `${relevantModules.length} potential root modules, ${possibleInners.size} potential inner modules` + ); + // sort by depth + // modules with lower depth are more likely suited as roots + // this improves performance, because modules already selected as inner are skipped + logger.time("sort relevant modules"); + relevantModules.sort((a, b) => { + return moduleGraph.getDepth(a) - moduleGraph.getDepth(b); + }); + logger.timeEnd("sort relevant modules"); + + /** @type {Statistics} */ + const stats = { + cached: 0, + alreadyInConfig: 0, + invalidModule: 0, + incorrectChunks: 0, + incorrectDependency: 0, + incorrectModuleDependency: 0, + incorrectChunksOfImporter: 0, + incorrectRuntimeCondition: 0, + importerFailed: 0, + added: 0 + }; + let statsCandidates = 0; + let statsSizeSum = 0; + let statsEmptyConfigurations = 0; + + logger.time("find modules to concatenate"); + const concatConfigurations = []; + const usedAsInner = new Set(); + for (const currentRoot of relevantModules) { + // when used by another configuration as inner: + // the other configuration is better and we can skip this one + // TODO reconsider that when it's only used in a different runtime + if (usedAsInner.has(currentRoot)) continue; + + let chunkRuntime = undefined; + for (const r of chunkGraph.getModuleRuntimes(currentRoot)) { + chunkRuntime = mergeRuntimeOwned(chunkRuntime, r); + } + const exportsInfo = moduleGraph.getExportsInfo(currentRoot); + const filteredRuntime = filterRuntime(chunkRuntime, r => + exportsInfo.isModuleUsed(r) + ); + const activeRuntime = + filteredRuntime === true + ? chunkRuntime + : filteredRuntime === false + ? undefined + : filteredRuntime; + + // create a configuration with the root + const currentConfiguration = new ConcatConfiguration( + currentRoot, + activeRuntime + ); + + // cache failures to add modules + const failureCache = new Map(); + + // potential optional import candidates + /** @type {Set} */ + const candidates = new Set(); + + // try to add all imports + for (const imp of this._getImports( + compilation, + currentRoot, + activeRuntime + )) { + candidates.add(imp); + } + + for (const imp of candidates) { + const impCandidates = new Set(); + const problem = this._tryToAdd( + compilation, + currentConfiguration, + imp, + chunkRuntime, + activeRuntime, + possibleInners, + impCandidates, + failureCache, + chunkGraph, + true, + stats + ); + if (problem) { + failureCache.set(imp, problem); + currentConfiguration.addWarning(imp, problem); + } else { + for (const c of impCandidates) { + candidates.add(c); + } + } + } + statsCandidates += candidates.size; + if (!currentConfiguration.isEmpty()) { + const modules = currentConfiguration.getModules(); + statsSizeSum += modules.size; + concatConfigurations.push(currentConfiguration); + for (const module of modules) { + if (module !== currentConfiguration.rootModule) { + usedAsInner.add(module); + } + } + } else { + statsEmptyConfigurations++; + const optimizationBailouts = + moduleGraph.getOptimizationBailout(currentRoot); + for (const warning of currentConfiguration.getWarningsSorted()) { + optimizationBailouts.push( + formatBailoutWarning(warning[0], warning[1]) + ); + } + } + } + logger.timeEnd("find modules to concatenate"); + logger.debug( + `${ + concatConfigurations.length + } successful concat configurations (avg size: ${ + statsSizeSum / concatConfigurations.length + }), ${statsEmptyConfigurations} bailed out completely` + ); + logger.debug( + `${statsCandidates} candidates were considered for adding (${stats.cached} cached failure, ${stats.alreadyInConfig} already in config, ${stats.invalidModule} invalid module, ${stats.incorrectChunks} incorrect chunks, ${stats.incorrectDependency} incorrect dependency, ${stats.incorrectChunksOfImporter} incorrect chunks of importer, ${stats.incorrectModuleDependency} incorrect module dependency, ${stats.incorrectRuntimeCondition} incorrect runtime condition, ${stats.importerFailed} importer failed, ${stats.added} added)` + ); + // HACK: Sort configurations by length and start with the longest one + // to get the biggest groups possible. Used modules are marked with usedModules + // TODO: Allow to reuse existing configuration while trying to add dependencies. + // This would improve performance. O(n^2) -> O(n) + logger.time(`sort concat configurations`); + concatConfigurations.sort((a, b) => { + return b.modules.size - a.modules.size; + }); + logger.timeEnd(`sort concat configurations`); + const usedModules = new Set(); + + logger.time("create concatenated modules"); + asyncLib.each( + concatConfigurations, + (concatConfiguration, callback) => { + const rootModule = concatConfiguration.rootModule; + + // Avoid overlapping configurations + // TODO: remove this when todo above is fixed + if (usedModules.has(rootModule)) return callback(); + const modules = concatConfiguration.getModules(); + for (const m of modules) { + usedModules.add(m); + } + + // Create a new ConcatenatedModule + let newModule = ConcatenatedModule.create( + rootModule, + modules, + concatConfiguration.runtime, + compiler.root, + compilation.outputOptions.hashFunction + ); + + const build = () => { + newModule.build( + compiler.options, + compilation, + null, + null, + err => { + if (err) { + if (!err.module) { + err.module = newModule; + } + return callback(err); + } + integrate(); + } + ); + }; + + const integrate = () => { + if (backCompat) { + ChunkGraph.setChunkGraphForModule(newModule, chunkGraph); + ModuleGraph.setModuleGraphForModule(newModule, moduleGraph); + } + + for (const warning of concatConfiguration.getWarningsSorted()) { + moduleGraph + .getOptimizationBailout(newModule) + .push(formatBailoutWarning(warning[0], warning[1])); + } + moduleGraph.cloneModuleAttributes(rootModule, newModule); + for (const m of modules) { + // add to builtModules when one of the included modules was built + if (compilation.builtModules.has(m)) { + compilation.builtModules.add(newModule); + } + if (m !== rootModule) { + // attach external references to the concatenated module too + moduleGraph.copyOutgoingModuleConnections( + m, + newModule, + c => { + return ( + c.originModule === m && + !( + c.dependency instanceof HarmonyImportDependency && + modules.has(c.module) + ) + ); + } + ); + // remove module from chunk + for (const chunk of chunkGraph.getModuleChunksIterable( + rootModule + )) { + chunkGraph.disconnectChunkAndModule(chunk, m); + } + } + } + compilation.modules.delete(rootModule); + ChunkGraph.clearChunkGraphForModule(rootModule); + ModuleGraph.clearModuleGraphForModule(rootModule); + + // remove module from chunk + chunkGraph.replaceModule(rootModule, newModule); + // replace module references with the concatenated module + moduleGraph.moveModuleConnections(rootModule, newModule, c => { + const otherModule = + c.module === rootModule ? c.originModule : c.module; + const innerConnection = + c.dependency instanceof HarmonyImportDependency && + modules.has(otherModule); + return !innerConnection; + }); + // add concatenated module to the compilation + compilation.modules.add(newModule); + + callback(); + }; + + build(); + }, + err => { + logger.timeEnd("create concatenated modules"); + process.nextTick(callback.bind(null, err)); + } + ); + } + ); + }); + } + + /** + * @param {Compilation} compilation the compilation + * @param {Module} module the module to be added + * @param {RuntimeSpec} runtime the runtime scope + * @returns {Set} the imported modules + */ + _getImports(compilation, module, runtime) { + const moduleGraph = compilation.moduleGraph; + const set = new Set(); + for (const dep of module.dependencies) { + // Get reference info only for harmony Dependencies + if (!(dep instanceof HarmonyImportDependency)) continue; + + const connection = moduleGraph.getConnection(dep); + // Reference is valid and has a module + if ( + !connection || + !connection.module || + !connection.isTargetActive(runtime) + ) { + continue; + } + + const importedNames = compilation.getDependencyReferencedExports( + dep, + undefined + ); + + if ( + importedNames.every(i => + Array.isArray(i) ? i.length > 0 : i.name.length > 0 + ) || + Array.isArray(moduleGraph.getProvidedExports(module)) + ) { + set.add(connection.module); + } + } + return set; + } + + /** + * @param {Compilation} compilation webpack compilation + * @param {ConcatConfiguration} config concat configuration (will be modified when added) + * @param {Module} module the module to be added + * @param {RuntimeSpec} runtime the runtime scope of the generated code + * @param {RuntimeSpec} activeRuntime the runtime scope of the root module + * @param {Set} possibleModules modules that are candidates + * @param {Set} candidates list of potential candidates (will be added to) + * @param {Map} failureCache cache for problematic modules to be more performant + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {boolean} avoidMutateOnFailure avoid mutating the config when adding fails + * @param {Statistics} statistics gathering metrics + * @returns {Module | function(RequestShortener): string} the problematic module + */ + _tryToAdd( + compilation, + config, + module, + runtime, + activeRuntime, + possibleModules, + candidates, + failureCache, + chunkGraph, + avoidMutateOnFailure, + statistics + ) { + const cacheEntry = failureCache.get(module); + if (cacheEntry) { + statistics.cached++; + return cacheEntry; + } + + // Already added? + if (config.has(module)) { + statistics.alreadyInConfig++; + return null; + } + + // Not possible to add? + if (!possibleModules.has(module)) { + statistics.invalidModule++; + failureCache.set(module, module); // cache failures for performance + return module; + } + + // Module must be in the correct chunks + const missingChunks = Array.from( + chunkGraph.getModuleChunksIterable(config.rootModule) + ).filter(chunk => !chunkGraph.isModuleInChunk(module, chunk)); + if (missingChunks.length > 0) { + const problem = requestShortener => { + const missingChunksList = Array.from( + new Set(missingChunks.map(chunk => chunk.name || "unnamed chunk(s)")) + ).sort(); + const chunks = Array.from( + new Set( + Array.from(chunkGraph.getModuleChunksIterable(module)).map( + chunk => chunk.name || "unnamed chunk(s)" + ) + ) + ).sort(); + return `Module ${module.readableIdentifier( + requestShortener + )} is not in the same chunk(s) (expected in chunk(s) ${missingChunksList.join( + ", " + )}, module is in chunk(s) ${chunks.join(", ")})`; + }; + statistics.incorrectChunks++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + + const moduleGraph = compilation.moduleGraph; + + const incomingConnections = + moduleGraph.getIncomingConnectionsByOriginModule(module); + + const incomingConnectionsFromNonModules = + incomingConnections.get(null) || incomingConnections.get(undefined); + if (incomingConnectionsFromNonModules) { + const activeNonModulesConnections = + incomingConnectionsFromNonModules.filter(connection => { + // We are not interested in inactive connections + // or connections without dependency + return connection.isActive(runtime) || connection.dependency; + }); + if (activeNonModulesConnections.length > 0) { + const problem = requestShortener => { + const importingExplanations = new Set( + activeNonModulesConnections.map(c => c.explanation).filter(Boolean) + ); + const explanations = Array.from(importingExplanations).sort(); + return `Module ${module.readableIdentifier( + requestShortener + )} is referenced ${ + explanations.length > 0 + ? `by: ${explanations.join(", ")}` + : "in an unsupported way" + }`; + }; + statistics.incorrectDependency++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + } + + /** @type {Map} */ + const incomingConnectionsFromModules = new Map(); + for (const [originModule, connections] of incomingConnections) { + if (originModule) { + // Ignore connection from orphan modules + if (chunkGraph.getNumberOfModuleChunks(originModule) === 0) continue; + + // We don't care for connections from other runtimes + let originRuntime = undefined; + for (const r of chunkGraph.getModuleRuntimes(originModule)) { + originRuntime = mergeRuntimeOwned(originRuntime, r); + } + + if (!intersectRuntime(runtime, originRuntime)) continue; + + // We are not interested in inactive connections + const activeConnections = connections.filter(connection => + connection.isActive(runtime) + ); + if (activeConnections.length > 0) + incomingConnectionsFromModules.set(originModule, activeConnections); + } + } + + const incomingModules = Array.from(incomingConnectionsFromModules.keys()); + + // Module must be in the same chunks like the referencing module + const otherChunkModules = incomingModules.filter(originModule => { + for (const chunk of chunkGraph.getModuleChunksIterable( + config.rootModule + )) { + if (!chunkGraph.isModuleInChunk(originModule, chunk)) { + return true; + } + } + return false; + }); + if (otherChunkModules.length > 0) { + const problem = requestShortener => { + const names = otherChunkModules + .map(m => m.readableIdentifier(requestShortener)) + .sort(); + return `Module ${module.readableIdentifier( + requestShortener + )} is referenced from different chunks by these modules: ${names.join( + ", " + )}`; + }; + statistics.incorrectChunksOfImporter++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + + /** @type {Map} */ + const nonHarmonyConnections = new Map(); + for (const [originModule, connections] of incomingConnectionsFromModules) { + const selected = connections.filter( + connection => + !connection.dependency || + !(connection.dependency instanceof HarmonyImportDependency) + ); + if (selected.length > 0) + nonHarmonyConnections.set(originModule, connections); + } + if (nonHarmonyConnections.size > 0) { + const problem = requestShortener => { + const names = Array.from(nonHarmonyConnections) + .map(([originModule, connections]) => { + return `${originModule.readableIdentifier( + requestShortener + )} (referenced with ${Array.from( + new Set( + connections + .map(c => c.dependency && c.dependency.type) + .filter(Boolean) + ) + ) + .sort() + .join(", ")})`; + }) + .sort(); + return `Module ${module.readableIdentifier( + requestShortener + )} is referenced from these modules with unsupported syntax: ${names.join( + ", " + )}`; + }; + statistics.incorrectModuleDependency++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + + if (runtime !== undefined && typeof runtime !== "string") { + // Module must be consistently referenced in the same runtimes + /** @type {{ originModule: Module, runtimeCondition: RuntimeSpec }[]} */ + const otherRuntimeConnections = []; + outer: for (const [ + originModule, + connections + ] of incomingConnectionsFromModules) { + /** @type {false | RuntimeSpec} */ + let currentRuntimeCondition = false; + for (const connection of connections) { + const runtimeCondition = filterRuntime(runtime, runtime => { + return connection.isTargetActive(runtime); + }); + if (runtimeCondition === false) continue; + if (runtimeCondition === true) continue outer; + if (currentRuntimeCondition !== false) { + currentRuntimeCondition = mergeRuntime( + currentRuntimeCondition, + runtimeCondition + ); + } else { + currentRuntimeCondition = runtimeCondition; + } + } + if (currentRuntimeCondition !== false) { + otherRuntimeConnections.push({ + originModule, + runtimeCondition: currentRuntimeCondition + }); + } + } + if (otherRuntimeConnections.length > 0) { + const problem = requestShortener => { + return `Module ${module.readableIdentifier( + requestShortener + )} is runtime-dependent referenced by these modules: ${Array.from( + otherRuntimeConnections, + ({ originModule, runtimeCondition }) => + `${originModule.readableIdentifier( + requestShortener + )} (expected runtime ${runtimeToString( + runtime + )}, module is only referenced in ${runtimeToString( + /** @type {RuntimeSpec} */ (runtimeCondition) + )})` + ).join(", ")}`; + }; + statistics.incorrectRuntimeCondition++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + } + + let backup; + if (avoidMutateOnFailure) { + backup = config.snapshot(); + } + + // Add the module + config.add(module); + + incomingModules.sort(compareModulesByIdentifier); + + // Every module which depends on the added module must be in the configuration too. + for (const originModule of incomingModules) { + const problem = this._tryToAdd( + compilation, + config, + originModule, + runtime, + activeRuntime, + possibleModules, + candidates, + failureCache, + chunkGraph, + false, + statistics + ); + if (problem) { + if (backup !== undefined) config.rollback(backup); + statistics.importerFailed++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + } + + // Add imports to possible candidates list + for (const imp of this._getImports(compilation, module, runtime)) { + candidates.add(imp); + } + statistics.added++; + return null; + } +} + +class ConcatConfiguration { + /** + * @param {Module} rootModule the root module + * @param {RuntimeSpec} runtime the runtime + */ + constructor(rootModule, runtime) { + this.rootModule = rootModule; + this.runtime = runtime; + /** @type {Set} */ + this.modules = new Set(); + this.modules.add(rootModule); + /** @type {Map} */ + this.warnings = new Map(); + } + + add(module) { + this.modules.add(module); + } + + has(module) { + return this.modules.has(module); + } + + isEmpty() { + return this.modules.size === 1; + } + + addWarning(module, problem) { + this.warnings.set(module, problem); + } + + getWarningsSorted() { + return new Map( + Array.from(this.warnings).sort((a, b) => { + const ai = a[0].identifier(); + const bi = b[0].identifier(); + if (ai < bi) return -1; + if (ai > bi) return 1; + return 0; + }) + ); + } + + /** + * @returns {Set} modules as set + */ + getModules() { + return this.modules; + } + + snapshot() { + return this.modules.size; + } + + rollback(snapshot) { + const modules = this.modules; + for (const m of modules) { + if (snapshot === 0) { + modules.delete(m); + } else { + snapshot--; + } + } + } +} + +module.exports = ModuleConcatenationPlugin; + + +/***/ }), + +/***/ 46043: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { SyncBailHook } = __webpack_require__(41242); +const { RawSource, CachedSource, CompatSource } = __webpack_require__(51255); +const Compilation = __webpack_require__(85720); +const WebpackError = __webpack_require__(53799); +const { compareSelect, compareStrings } = __webpack_require__(29579); +const createHash = __webpack_require__(49835); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("../Compiler")} Compiler */ + +const EMPTY_SET = new Set(); + +const addToList = (itemOrItems, list) => { + if (Array.isArray(itemOrItems)) { + for (const item of itemOrItems) { + list.add(item); + } + } else if (itemOrItems) { + list.add(itemOrItems); + } +}; + +/** + * @template T + * @param {T[]} input list + * @param {function(T): Buffer} fn map function + * @returns {Buffer[]} buffers without duplicates + */ +const mapAndDeduplicateBuffers = (input, fn) => { + // Buffer.equals compares size first so this should be efficient enough + // If it becomes a performance problem we can use a map and group by size + // instead of looping over all assets. + const result = []; + outer: for (const value of input) { + const buf = fn(value); + for (const other of result) { + if (buf.equals(other)) continue outer; + } + result.push(buf); + } + return result; +}; + +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string + */ +const quoteMeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); +}; + +const cachedSourceMap = new WeakMap(); + +const toCachedSource = source => { + if (source instanceof CachedSource) { + return source; + } + const entry = cachedSourceMap.get(source); + if (entry !== undefined) return entry; + const newSource = new CachedSource(CompatSource.from(source)); + cachedSourceMap.set(source, newSource); + return newSource; +}; + +/** + * @typedef {Object} AssetInfoForRealContentHash + * @property {string} name + * @property {AssetInfo} info + * @property {Source} source + * @property {RawSource | undefined} newSource + * @property {RawSource | undefined} newSourceWithoutOwn + * @property {string} content + * @property {Set} ownHashes + * @property {Promise} contentComputePromise + * @property {Promise} contentComputeWithoutOwnPromise + * @property {Set} referencedHashes + * @property {Set} hashes + */ + +/** + * @typedef {Object} CompilationHooks + * @property {SyncBailHook<[Buffer[], string], string>} updateHash + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class RealContentHashPlugin { + /** + * @param {Compilation} compilation the compilation + * @returns {CompilationHooks} 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 = { + updateHash: new SyncBailHook(["content", "oldHash"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + constructor({ hashFunction, hashDigest }) { + this._hashFunction = hashFunction; + this._hashDigest = hashDigest; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap("RealContentHashPlugin", compilation => { + const cacheAnalyse = compilation.getCache( + "RealContentHashPlugin|analyse" + ); + const cacheGenerate = compilation.getCache( + "RealContentHashPlugin|generate" + ); + const hooks = RealContentHashPlugin.getCompilationHooks(compilation); + compilation.hooks.processAssets.tapPromise( + { + name: "RealContentHashPlugin", + stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH + }, + async () => { + const assets = compilation.getAssets(); + /** @type {AssetInfoForRealContentHash[]} */ + const assetsWithInfo = []; + const hashToAssets = new Map(); + for (const { source, info, name } of assets) { + const cachedSource = toCachedSource(source); + const content = cachedSource.source(); + /** @type {Set} */ + const hashes = new Set(); + addToList(info.contenthash, hashes); + const data = { + name, + info, + source: cachedSource, + /** @type {RawSource | undefined} */ + newSource: undefined, + /** @type {RawSource | undefined} */ + newSourceWithoutOwn: undefined, + content, + /** @type {Set} */ + ownHashes: undefined, + contentComputePromise: undefined, + contentComputeWithoutOwnPromise: undefined, + /** @type {Set} */ + referencedHashes: undefined, + hashes + }; + assetsWithInfo.push(data); + for (const hash of hashes) { + const list = hashToAssets.get(hash); + if (list === undefined) { + hashToAssets.set(hash, [data]); + } else { + list.push(data); + } + } + } + if (hashToAssets.size === 0) return; + const hashRegExp = new RegExp( + Array.from(hashToAssets.keys(), quoteMeta).join("|"), + "g" + ); + await Promise.all( + assetsWithInfo.map(async asset => { + const { name, source, content, hashes } = asset; + if (Buffer.isBuffer(content)) { + asset.referencedHashes = EMPTY_SET; + asset.ownHashes = EMPTY_SET; + return; + } + const etag = cacheAnalyse.mergeEtags( + cacheAnalyse.getLazyHashedEtag(source), + Array.from(hashes).join("|") + ); + [asset.referencedHashes, asset.ownHashes] = + await cacheAnalyse.providePromise(name, etag, () => { + const referencedHashes = new Set(); + let ownHashes = new Set(); + const inContent = content.match(hashRegExp); + if (inContent) { + for (const hash of inContent) { + if (hashes.has(hash)) { + ownHashes.add(hash); + continue; + } + referencedHashes.add(hash); + } + } + return [referencedHashes, ownHashes]; + }); + }) + ); + const getDependencies = hash => { + const assets = hashToAssets.get(hash); + if (!assets) { + const referencingAssets = assetsWithInfo.filter(asset => + asset.referencedHashes.has(hash) + ); + const err = new WebpackError(`RealContentHashPlugin +Some kind of unexpected caching problem occurred. +An asset was cached with a reference to another asset (${hash}) that's not in the compilation anymore. +Either the asset was incorrectly cached, or the referenced asset should also be restored from cache. +Referenced by: +${referencingAssets + .map(a => { + const match = new RegExp(`.{0,20}${quoteMeta(hash)}.{0,20}`).exec( + a.content + ); + return ` - ${a.name}: ...${match ? match[0] : "???"}...`; + }) + .join("\n")}`); + compilation.errors.push(err); + return undefined; + } + const hashes = new Set(); + for (const { referencedHashes, ownHashes } of assets) { + if (!ownHashes.has(hash)) { + for (const hash of ownHashes) { + hashes.add(hash); + } + } + for (const hash of referencedHashes) { + hashes.add(hash); + } + } + return hashes; + }; + const hashInfo = hash => { + const assets = hashToAssets.get(hash); + return `${hash} (${Array.from(assets, a => a.name)})`; + }; + const hashesInOrder = new Set(); + for (const hash of hashToAssets.keys()) { + const add = (hash, stack) => { + const deps = getDependencies(hash); + if (!deps) return; + stack.add(hash); + for (const dep of deps) { + if (hashesInOrder.has(dep)) continue; + if (stack.has(dep)) { + throw new Error( + `Circular hash dependency ${Array.from( + stack, + hashInfo + ).join(" -> ")} -> ${hashInfo(dep)}` + ); + } + add(dep, stack); + } + hashesInOrder.add(hash); + stack.delete(hash); + }; + if (hashesInOrder.has(hash)) continue; + add(hash, new Set()); + } + const hashToNewHash = new Map(); + const getEtag = asset => + cacheGenerate.mergeEtags( + cacheGenerate.getLazyHashedEtag(asset.source), + Array.from(asset.referencedHashes, hash => + hashToNewHash.get(hash) + ).join("|") + ); + const computeNewContent = asset => { + if (asset.contentComputePromise) return asset.contentComputePromise; + return (asset.contentComputePromise = (async () => { + if ( + asset.ownHashes.size > 0 || + Array.from(asset.referencedHashes).some( + hash => hashToNewHash.get(hash) !== hash + ) + ) { + const identifier = asset.name; + const etag = getEtag(asset); + asset.newSource = await cacheGenerate.providePromise( + identifier, + etag, + () => { + const newContent = asset.content.replace(hashRegExp, hash => + hashToNewHash.get(hash) + ); + return new RawSource(newContent); + } + ); + } + })()); + }; + const computeNewContentWithoutOwn = asset => { + if (asset.contentComputeWithoutOwnPromise) + return asset.contentComputeWithoutOwnPromise; + return (asset.contentComputeWithoutOwnPromise = (async () => { + if ( + asset.ownHashes.size > 0 || + Array.from(asset.referencedHashes).some( + hash => hashToNewHash.get(hash) !== hash + ) + ) { + const identifier = asset.name + "|without-own"; + const etag = getEtag(asset); + asset.newSourceWithoutOwn = await cacheGenerate.providePromise( + identifier, + etag, + () => { + const newContent = asset.content.replace( + hashRegExp, + hash => { + if (asset.ownHashes.has(hash)) { + return ""; + } + return hashToNewHash.get(hash); + } + ); + return new RawSource(newContent); + } + ); + } + })()); + }; + const comparator = compareSelect(a => a.name, compareStrings); + for (const oldHash of hashesInOrder) { + const assets = hashToAssets.get(oldHash); + assets.sort(comparator); + const hash = createHash(this._hashFunction); + await Promise.all( + assets.map(asset => + asset.ownHashes.has(oldHash) + ? computeNewContentWithoutOwn(asset) + : computeNewContent(asset) + ) + ); + const assetsContent = mapAndDeduplicateBuffers(assets, asset => { + if (asset.ownHashes.has(oldHash)) { + return asset.newSourceWithoutOwn + ? asset.newSourceWithoutOwn.buffer() + : asset.source.buffer(); + } else { + return asset.newSource + ? asset.newSource.buffer() + : asset.source.buffer(); + } + }); + let newHash = hooks.updateHash.call(assetsContent, oldHash); + if (!newHash) { + for (const content of assetsContent) { + hash.update(content); + } + const digest = hash.digest(this._hashDigest); + newHash = /** @type {string} */ (digest.slice(0, oldHash.length)); + } + hashToNewHash.set(oldHash, newHash); + } + await Promise.all( + assetsWithInfo.map(async asset => { + await computeNewContent(asset); + const newName = asset.name.replace(hashRegExp, hash => + hashToNewHash.get(hash) + ); + + const infoUpdate = {}; + const hash = asset.info.contenthash; + infoUpdate.contenthash = Array.isArray(hash) + ? hash.map(hash => hashToNewHash.get(hash)) + : hashToNewHash.get(hash); + + if (asset.newSource !== undefined) { + compilation.updateAsset( + asset.name, + asset.newSource, + infoUpdate + ); + } else { + compilation.updateAsset(asset.name, asset.source, infoUpdate); + } + + if (asset.name !== newName) { + compilation.renameAsset(asset.name, newName); + } + }) + ); + } + ); + }); + } +} + +module.exports = RealContentHashPlugin; + + +/***/ }), + +/***/ 84760: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { STAGE_BASIC, STAGE_ADVANCED } = __webpack_require__(80057); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +class RemoveEmptyChunksPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap("RemoveEmptyChunksPlugin", compilation => { + /** + * @param {Iterable} chunks the chunks array + * @returns {void} + */ + const handler = chunks => { + const chunkGraph = compilation.chunkGraph; + for (const chunk of chunks) { + if ( + chunkGraph.getNumberOfChunkModules(chunk) === 0 && + !chunk.hasRuntime() && + chunkGraph.getNumberOfEntryModules(chunk) === 0 + ) { + compilation.chunkGraph.disconnectChunk(chunk); + compilation.chunks.delete(chunk); + } + } + }; + + // TODO do it once + compilation.hooks.optimizeChunks.tap( + { + name: "RemoveEmptyChunksPlugin", + stage: STAGE_BASIC + }, + handler + ); + compilation.hooks.optimizeChunks.tap( + { + name: "RemoveEmptyChunksPlugin", + stage: STAGE_ADVANCED + }, + handler + ); + }); + } +} +module.exports = RemoveEmptyChunksPlugin; + + +/***/ }), + +/***/ 7081: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { STAGE_BASIC } = __webpack_require__(80057); +const Queue = __webpack_require__(65930); +const { intersect } = __webpack_require__(93347); + +/** @typedef {import("../Compiler")} Compiler */ + +class RemoveParentModulesPlugin { + /** + * @param {Compiler} compiler the compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap("RemoveParentModulesPlugin", compilation => { + const handler = (chunks, chunkGroups) => { + const chunkGraph = compilation.chunkGraph; + const queue = new Queue(); + const availableModulesMap = new WeakMap(); + + for (const chunkGroup of compilation.entrypoints.values()) { + // initialize available modules for chunks without parents + availableModulesMap.set(chunkGroup, new Set()); + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } + } + for (const chunkGroup of compilation.asyncEntrypoints) { + // initialize available modules for chunks without parents + availableModulesMap.set(chunkGroup, new Set()); + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } + } + + while (queue.length > 0) { + const chunkGroup = queue.dequeue(); + let availableModules = availableModulesMap.get(chunkGroup); + let changed = false; + for (const parent of chunkGroup.parentsIterable) { + const availableModulesInParent = availableModulesMap.get(parent); + if (availableModulesInParent !== undefined) { + // If we know the available modules in parent: process these + if (availableModules === undefined) { + // if we have not own info yet: create new entry + availableModules = new Set(availableModulesInParent); + for (const chunk of parent.chunks) { + for (const m of chunkGraph.getChunkModulesIterable(chunk)) { + availableModules.add(m); + } + } + availableModulesMap.set(chunkGroup, availableModules); + changed = true; + } else { + for (const m of availableModules) { + if ( + !chunkGraph.isModuleInChunkGroup(m, parent) && + !availableModulesInParent.has(m) + ) { + availableModules.delete(m); + changed = true; + } + } + } + } + } + if (changed) { + // if something changed: enqueue our children + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } + } + } + + // now we have available modules for every chunk + for (const chunk of chunks) { + const availableModulesSets = Array.from( + chunk.groupsIterable, + chunkGroup => availableModulesMap.get(chunkGroup) + ); + if (availableModulesSets.some(s => s === undefined)) continue; // No info about this chunk group + const availableModules = + availableModulesSets.length === 1 + ? availableModulesSets[0] + : intersect(availableModulesSets); + const numberOfModules = chunkGraph.getNumberOfChunkModules(chunk); + const toRemove = new Set(); + if (numberOfModules < availableModules.size) { + for (const m of chunkGraph.getChunkModulesIterable(chunk)) { + if (availableModules.has(m)) { + toRemove.add(m); + } + } + } else { + for (const m of availableModules) { + if (chunkGraph.isModuleInChunk(m, chunk)) { + toRemove.add(m); + } + } + } + for (const module of toRemove) { + chunkGraph.disconnectChunkAndModule(chunk, module); + } + } + }; + compilation.hooks.optimizeChunks.tap( + { + name: "RemoveParentModulesPlugin", + stage: STAGE_BASIC + }, + handler + ); + }); + } +} +module.exports = RemoveParentModulesPlugin; + + +/***/ }), + +/***/ 2837: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("../Compiler")} Compiler */ + +class RuntimeChunkPlugin { + constructor(options) { + this.options = { + name: entrypoint => `runtime~${entrypoint.name}`, + ...options + }; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap("RuntimeChunkPlugin", compilation => { + compilation.hooks.addEntry.tap( + "RuntimeChunkPlugin", + (_, { name: entryName }) => { + if (entryName === undefined) return; + const data = compilation.entries.get(entryName); + if (data.options.runtime === undefined && !data.options.dependOn) { + // Determine runtime chunk name + let name = this.options.name; + if (typeof name === "function") { + name = name({ name: entryName }); + } + data.options.runtime = name; + } + } + ); + }); + } +} + +module.exports = RuntimeChunkPlugin; + + +/***/ }), + +/***/ 84800: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const glob2regexp = __webpack_require__(86140); +const { STAGE_DEFAULT } = __webpack_require__(80057); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(67157); +const HarmonyImportSpecifierDependency = __webpack_require__(14077); +const formatLocation = __webpack_require__(16734); + +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ + +/** + * @typedef {Object} ExportInModule + * @property {Module} module the module + * @property {string} exportName the name of the export + * @property {boolean} checked if the export is conditional + */ + +/** + * @typedef {Object} ReexportInfo + * @property {Map} static + * @property {Map>} dynamic + */ + +/** @type {WeakMap>} */ +const globToRegexpCache = new WeakMap(); + +/** + * @param {string} glob the pattern + * @param {Map} cache the glob to RegExp cache + * @returns {RegExp} a regular expression + */ +const globToRegexp = (glob, cache) => { + const cacheEntry = cache.get(glob); + if (cacheEntry !== undefined) return cacheEntry; + if (!glob.includes("/")) { + glob = `**/${glob}`; + } + const baseRegexp = glob2regexp(glob, { globstar: true, extended: true }); + const regexpSource = baseRegexp.source; + const regexp = new RegExp("^(\\./)?" + regexpSource.slice(1)); + cache.set(glob, regexp); + return regexp; +}; + +class SideEffectsFlagPlugin { + /** + * @param {boolean} analyseSource analyse source code for side effects + */ + constructor(analyseSource = true) { + this._analyseSource = analyseSource; + } + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + let cache = globToRegexpCache.get(compiler.root); + if (cache === undefined) { + cache = new Map(); + globToRegexpCache.set(compiler.root, cache); + } + compiler.hooks.compilation.tap( + "SideEffectsFlagPlugin", + (compilation, { normalModuleFactory }) => { + const moduleGraph = compilation.moduleGraph; + normalModuleFactory.hooks.module.tap( + "SideEffectsFlagPlugin", + (module, data) => { + const resolveData = data.resourceResolveData; + if ( + resolveData && + resolveData.descriptionFileData && + resolveData.relativePath + ) { + const sideEffects = resolveData.descriptionFileData.sideEffects; + if (sideEffects !== undefined) { + if (module.factoryMeta === undefined) { + module.factoryMeta = {}; + } + const hasSideEffects = + SideEffectsFlagPlugin.moduleHasSideEffects( + resolveData.relativePath, + sideEffects, + cache + ); + module.factoryMeta.sideEffectFree = !hasSideEffects; + } + } + + return module; + } + ); + normalModuleFactory.hooks.module.tap( + "SideEffectsFlagPlugin", + (module, data) => { + if (typeof data.settings.sideEffects === "boolean") { + if (module.factoryMeta === undefined) { + module.factoryMeta = {}; + } + module.factoryMeta.sideEffectFree = !data.settings.sideEffects; + } + return module; + } + ); + if (this._analyseSource) { + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + const parserHandler = parser => { + let sideEffectsStatement; + parser.hooks.program.tap("SideEffectsFlagPlugin", () => { + sideEffectsStatement = undefined; + }); + parser.hooks.statement.tap( + { name: "SideEffectsFlagPlugin", stage: -100 }, + statement => { + if (sideEffectsStatement) return; + if (parser.scope.topLevelScope !== true) return; + switch (statement.type) { + case "ExpressionStatement": + if ( + !parser.isPure(statement.expression, statement.range[0]) + ) { + sideEffectsStatement = statement; + } + break; + case "IfStatement": + case "WhileStatement": + case "DoWhileStatement": + if (!parser.isPure(statement.test, statement.range[0])) { + sideEffectsStatement = statement; + } + // statement hook will be called for child statements too + break; + case "ForStatement": + if ( + !parser.isPure(statement.init, statement.range[0]) || + !parser.isPure( + statement.test, + statement.init + ? statement.init.range[1] + : statement.range[0] + ) || + !parser.isPure( + statement.update, + statement.test + ? statement.test.range[1] + : statement.init + ? statement.init.range[1] + : statement.range[0] + ) + ) { + sideEffectsStatement = statement; + } + // statement hook will be called for child statements too + break; + case "SwitchStatement": + if ( + !parser.isPure(statement.discriminant, statement.range[0]) + ) { + sideEffectsStatement = statement; + } + // statement hook will be called for child statements too + break; + case "VariableDeclaration": + case "ClassDeclaration": + case "FunctionDeclaration": + if (!parser.isPure(statement, statement.range[0])) { + sideEffectsStatement = statement; + } + break; + case "ExportNamedDeclaration": + case "ExportDefaultDeclaration": + if ( + !parser.isPure(statement.declaration, statement.range[0]) + ) { + sideEffectsStatement = statement; + } + break; + case "LabeledStatement": + case "BlockStatement": + // statement hook will be called for child statements too + break; + case "EmptyStatement": + break; + case "ExportAllDeclaration": + case "ImportDeclaration": + // imports will be handled by the dependencies + break; + default: + sideEffectsStatement = statement; + break; + } + } + ); + parser.hooks.finish.tap("SideEffectsFlagPlugin", () => { + if (sideEffectsStatement === undefined) { + parser.state.module.buildMeta.sideEffectFree = true; + } else { + const { loc, type } = sideEffectsStatement; + moduleGraph + .getOptimizationBailout(parser.state.module) + .push( + () => + `Statement (${type}) with side effects in source code at ${formatLocation( + loc + )}` + ); + } + }); + }; + for (const key of [ + "javascript/auto", + "javascript/esm", + "javascript/dynamic" + ]) { + normalModuleFactory.hooks.parser + .for(key) + .tap("SideEffectsFlagPlugin", parserHandler); + } + } + compilation.hooks.optimizeDependencies.tap( + { + name: "SideEffectsFlagPlugin", + stage: STAGE_DEFAULT + }, + modules => { + const logger = compilation.getLogger( + "webpack.SideEffectsFlagPlugin" + ); + + logger.time("update dependencies"); + for (const module of modules) { + if (module.getSideEffectsConnectionState(moduleGraph) === false) { + const exportsInfo = moduleGraph.getExportsInfo(module); + for (const connection of moduleGraph.getIncomingConnections( + module + )) { + const dep = connection.dependency; + let isReexport; + if ( + (isReexport = + dep instanceof + HarmonyExportImportedSpecifierDependency) || + (dep instanceof HarmonyImportSpecifierDependency && + !dep.namespaceObjectAsContext) + ) { + // TODO improve for export * + if (isReexport && dep.name) { + const exportInfo = moduleGraph.getExportInfo( + connection.originModule, + dep.name + ); + exportInfo.moveTarget( + moduleGraph, + ({ module }) => + module.getSideEffectsConnectionState(moduleGraph) === + false, + ({ module: newModule, export: exportName }) => { + moduleGraph.updateModule(dep, newModule); + moduleGraph.addExplanation( + dep, + "(skipped side-effect-free modules)" + ); + const ids = dep.getIds(moduleGraph); + dep.setIds( + moduleGraph, + exportName + ? [...exportName, ...ids.slice(1)] + : ids.slice(1) + ); + return moduleGraph.getConnection(dep); + } + ); + continue; + } + // TODO improve for nested imports + const ids = dep.getIds(moduleGraph); + if (ids.length > 0) { + const exportInfo = exportsInfo.getExportInfo(ids[0]); + const target = exportInfo.getTarget( + moduleGraph, + ({ module }) => + module.getSideEffectsConnectionState(moduleGraph) === + false + ); + if (!target) continue; + + moduleGraph.updateModule(dep, target.module); + moduleGraph.addExplanation( + dep, + "(skipped side-effect-free modules)" + ); + dep.setIds( + moduleGraph, + target.export + ? [...target.export, ...ids.slice(1)] + : ids.slice(1) + ); + } + } + } + } + } + logger.timeEnd("update dependencies"); + } + ); + } + ); + } + + static moduleHasSideEffects(moduleName, flagValue, cache) { + switch (typeof flagValue) { + case "undefined": + return true; + case "boolean": + return flagValue; + case "string": + return globToRegexp(flagValue, cache).test(moduleName); + case "object": + return flagValue.some(glob => + SideEffectsFlagPlugin.moduleHasSideEffects(moduleName, glob, cache) + ); + } + } +} +module.exports = SideEffectsFlagPlugin; + + +/***/ }), + +/***/ 21478: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const Chunk = __webpack_require__(39385); +const { STAGE_ADVANCED } = __webpack_require__(80057); +const WebpackError = __webpack_require__(53799); +const { requestToId } = __webpack_require__(63290); +const { isSubset } = __webpack_require__(93347); +const SortableSet = __webpack_require__(13098); +const { + compareModulesByIdentifier, + compareIterables +} = __webpack_require__(29579); +const createHash = __webpack_require__(49835); +const deterministicGrouping = __webpack_require__(59836); +const { makePathsRelative } = __webpack_require__(82186); +const memoize = __webpack_require__(78676); +const MinMaxSizeWarning = __webpack_require__(85305); + +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksCacheGroup} OptimizationSplitChunksCacheGroup */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksGetCacheGroups} OptimizationSplitChunksGetCacheGroups */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksOptions} OptimizationSplitChunksOptions */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksSizes} OptimizationSplitChunksSizes */ +/** @typedef {import("../../declarations/WebpackOptions").Output} OutputOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("../Compilation").PathData} PathData */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/deterministicGrouping").GroupedItems} DeterministicGroupingGroupedItemsForModule */ +/** @typedef {import("../util/deterministicGrouping").Options} DeterministicGroupingOptionsForModule */ + +/** @typedef {Record} SplitChunksSizes */ + +/** + * @callback ChunkFilterFunction + * @param {Chunk} chunk + * @returns {boolean} + */ + +/** + * @callback CombineSizeFunction + * @param {number} a + * @param {number} b + * @returns {number} + */ + +/** + * @typedef {Object} CacheGroupSource + * @property {string=} key + * @property {number=} priority + * @property {GetName=} getName + * @property {ChunkFilterFunction=} chunksFilter + * @property {boolean=} enforce + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} minSizeReduction + * @property {SplitChunksSizes} minRemainingSize + * @property {SplitChunksSizes} enforceSizeThreshold + * @property {SplitChunksSizes} maxAsyncSize + * @property {SplitChunksSizes} maxInitialSize + * @property {number=} minChunks + * @property {number=} maxAsyncRequests + * @property {number=} maxInitialRequests + * @property {(string | function(PathData, AssetInfo=): string)=} filename + * @property {string=} idHint + * @property {string} automaticNameDelimiter + * @property {boolean=} reuseExistingChunk + * @property {boolean=} usedExports + */ + +/** + * @typedef {Object} CacheGroup + * @property {string} key + * @property {number=} priority + * @property {GetName=} getName + * @property {ChunkFilterFunction=} chunksFilter + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} minSizeReduction + * @property {SplitChunksSizes} minRemainingSize + * @property {SplitChunksSizes} enforceSizeThreshold + * @property {SplitChunksSizes} maxAsyncSize + * @property {SplitChunksSizes} maxInitialSize + * @property {number=} minChunks + * @property {number=} maxAsyncRequests + * @property {number=} maxInitialRequests + * @property {(string | function(PathData, AssetInfo=): string)=} filename + * @property {string=} idHint + * @property {string} automaticNameDelimiter + * @property {boolean} reuseExistingChunk + * @property {boolean} usedExports + * @property {boolean} _validateSize + * @property {boolean} _validateRemainingSize + * @property {SplitChunksSizes} _minSizeForMaxSize + * @property {boolean} _conditionalEnforce + */ + +/** + * @typedef {Object} FallbackCacheGroup + * @property {ChunkFilterFunction} chunksFilter + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} maxAsyncSize + * @property {SplitChunksSizes} maxInitialSize + * @property {string} automaticNameDelimiter + */ + +/** + * @typedef {Object} CacheGroupsContext + * @property {ModuleGraph} moduleGraph + * @property {ChunkGraph} chunkGraph + */ + +/** + * @callback GetCacheGroups + * @param {Module} module + * @param {CacheGroupsContext} context + * @returns {CacheGroupSource[]} + */ + +/** + * @callback GetName + * @param {Module=} module + * @param {Chunk[]=} chunks + * @param {string=} key + * @returns {string=} + */ + +/** + * @typedef {Object} SplitChunksOptions + * @property {ChunkFilterFunction} chunksFilter + * @property {string[]} defaultSizeTypes + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} minSizeReduction + * @property {SplitChunksSizes} minRemainingSize + * @property {SplitChunksSizes} enforceSizeThreshold + * @property {SplitChunksSizes} maxInitialSize + * @property {SplitChunksSizes} maxAsyncSize + * @property {number} minChunks + * @property {number} maxAsyncRequests + * @property {number} maxInitialRequests + * @property {boolean} hidePathInfo + * @property {string | function(PathData, AssetInfo=): string} filename + * @property {string} automaticNameDelimiter + * @property {GetCacheGroups} getCacheGroups + * @property {GetName} getName + * @property {boolean} usedExports + * @property {FallbackCacheGroup} fallbackCacheGroup + */ + +/** + * @typedef {Object} ChunksInfoItem + * @property {SortableSet} modules + * @property {CacheGroup} cacheGroup + * @property {number} cacheGroupIndex + * @property {string} name + * @property {Record} sizes + * @property {Set} chunks + * @property {Set} reuseableChunks + * @property {Set} chunksKeys + */ + +const defaultGetName = /** @type {GetName} */ (() => {}); + +const deterministicGroupingForModules = + /** @type {function(DeterministicGroupingOptionsForModule): DeterministicGroupingGroupedItemsForModule[]} */ ( + deterministicGrouping + ); + +/** @type {WeakMap} */ +const getKeyCache = new WeakMap(); + +/** + * @param {string} name a filename to hash + * @param {OutputOptions} outputOptions hash function used + * @returns {string} hashed filename + */ +const hashFilename = (name, outputOptions) => { + const digest = /** @type {string} */ ( + createHash(outputOptions.hashFunction) + .update(name) + .digest(outputOptions.hashDigest) + ); + return digest.slice(0, 8); +}; + +/** + * @param {Chunk} chunk the chunk + * @returns {number} the number of requests + */ +const getRequests = chunk => { + let requests = 0; + for (const chunkGroup of chunk.groupsIterable) { + requests = Math.max(requests, chunkGroup.chunks.length); + } + return requests; +}; + +const mapObject = (obj, fn) => { + const newObj = Object.create(null); + for (const key of Object.keys(obj)) { + newObj[key] = fn(obj[key], key); + } + return newObj; +}; + +/** + * @template T + * @param {Set} a set + * @param {Set} b other set + * @returns {boolean} true if at least one item of a is in b + */ +const isOverlap = (a, b) => { + for (const item of a) { + if (b.has(item)) return true; + } + return false; +}; + +const compareModuleIterables = compareIterables(compareModulesByIdentifier); + +/** + * @param {ChunksInfoItem} a item + * @param {ChunksInfoItem} b item + * @returns {number} compare result + */ +const compareEntries = (a, b) => { + // 1. by priority + const diffPriority = a.cacheGroup.priority - b.cacheGroup.priority; + if (diffPriority) return diffPriority; + // 2. by number of chunks + const diffCount = a.chunks.size - b.chunks.size; + if (diffCount) return diffCount; + // 3. by size reduction + const aSizeReduce = totalSize(a.sizes) * (a.chunks.size - 1); + const bSizeReduce = totalSize(b.sizes) * (b.chunks.size - 1); + const diffSizeReduce = aSizeReduce - bSizeReduce; + if (diffSizeReduce) return diffSizeReduce; + // 4. by cache group index + const indexDiff = b.cacheGroupIndex - a.cacheGroupIndex; + if (indexDiff) return indexDiff; + // 5. by number of modules (to be able to compare by identifier) + const modulesA = a.modules; + const modulesB = b.modules; + const diff = modulesA.size - modulesB.size; + if (diff) return diff; + // 6. by module identifiers + modulesA.sort(); + modulesB.sort(); + return compareModuleIterables(modulesA, modulesB); +}; + +const INITIAL_CHUNK_FILTER = chunk => chunk.canBeInitial(); +const ASYNC_CHUNK_FILTER = chunk => !chunk.canBeInitial(); +const ALL_CHUNK_FILTER = chunk => true; + +/** + * @param {OptimizationSplitChunksSizes} value the sizes + * @param {string[]} defaultSizeTypes the default size types + * @returns {SplitChunksSizes} normalized representation + */ +const normalizeSizes = (value, defaultSizeTypes) => { + if (typeof value === "number") { + /** @type {Record} */ + const o = {}; + for (const sizeType of defaultSizeTypes) o[sizeType] = value; + return o; + } else if (typeof value === "object" && value !== null) { + return { ...value }; + } else { + return {}; + } +}; + +/** + * @param {...SplitChunksSizes} sizes the sizes + * @returns {SplitChunksSizes} the merged sizes + */ +const mergeSizes = (...sizes) => { + /** @type {SplitChunksSizes} */ + let merged = {}; + for (let i = sizes.length - 1; i >= 0; i--) { + merged = Object.assign(merged, sizes[i]); + } + return merged; +}; + +/** + * @param {SplitChunksSizes} sizes the sizes + * @returns {boolean} true, if there are sizes > 0 + */ +const hasNonZeroSizes = sizes => { + for (const key of Object.keys(sizes)) { + if (sizes[key] > 0) return true; + } + return false; +}; + +/** + * @param {SplitChunksSizes} a first sizes + * @param {SplitChunksSizes} b second sizes + * @param {CombineSizeFunction} combine a function to combine sizes + * @returns {SplitChunksSizes} the combine sizes + */ +const combineSizes = (a, b, combine) => { + const aKeys = new Set(Object.keys(a)); + const bKeys = new Set(Object.keys(b)); + /** @type {SplitChunksSizes} */ + const result = {}; + for (const key of aKeys) { + if (bKeys.has(key)) { + result[key] = combine(a[key], b[key]); + } else { + result[key] = a[key]; + } + } + for (const key of bKeys) { + if (!aKeys.has(key)) { + result[key] = b[key]; + } + } + return result; +}; + +/** + * @param {SplitChunksSizes} sizes the sizes + * @param {SplitChunksSizes} minSize the min sizes + * @returns {boolean} true if there are sizes and all existing sizes are at least `minSize` + */ +const checkMinSize = (sizes, minSize) => { + for (const key of Object.keys(minSize)) { + const size = sizes[key]; + if (size === undefined || size === 0) continue; + if (size < minSize[key]) return false; + } + return true; +}; + +/** + * @param {SplitChunksSizes} sizes the sizes + * @param {SplitChunksSizes} minSizeReduction the min sizes + * @param {number} chunkCount number of chunks + * @returns {boolean} true if there are sizes and all existing sizes are at least `minSizeReduction` + */ +const checkMinSizeReduction = (sizes, minSizeReduction, chunkCount) => { + for (const key of Object.keys(minSizeReduction)) { + const size = sizes[key]; + if (size === undefined || size === 0) continue; + if (size * chunkCount < minSizeReduction[key]) return false; + } + return true; +}; + +/** + * @param {SplitChunksSizes} sizes the sizes + * @param {SplitChunksSizes} minSize the min sizes + * @returns {undefined | string[]} list of size types that are below min size + */ +const getViolatingMinSizes = (sizes, minSize) => { + let list; + for (const key of Object.keys(minSize)) { + const size = sizes[key]; + if (size === undefined || size === 0) continue; + if (size < minSize[key]) { + if (list === undefined) list = [key]; + else list.push(key); + } + } + return list; +}; + +/** + * @param {SplitChunksSizes} sizes the sizes + * @returns {number} the total size + */ +const totalSize = sizes => { + let size = 0; + for (const key of Object.keys(sizes)) { + size += sizes[key]; + } + return size; +}; + +/** + * @param {false|string|Function} name the chunk name + * @returns {GetName} a function to get the name of the chunk + */ +const normalizeName = name => { + if (typeof name === "string") { + return () => name; + } + if (typeof name === "function") { + return /** @type {GetName} */ (name); + } +}; + +/** + * @param {OptimizationSplitChunksCacheGroup["chunks"]} chunks the chunk filter option + * @returns {ChunkFilterFunction} the chunk filter function + */ +const normalizeChunksFilter = chunks => { + if (chunks === "initial") { + return INITIAL_CHUNK_FILTER; + } + if (chunks === "async") { + return ASYNC_CHUNK_FILTER; + } + if (chunks === "all") { + return ALL_CHUNK_FILTER; + } + if (typeof chunks === "function") { + return chunks; + } +}; + +/** + * @param {GetCacheGroups | Record} cacheGroups the cache group options + * @param {string[]} defaultSizeTypes the default size types + * @returns {GetCacheGroups} a function to get the cache groups + */ +const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => { + if (typeof cacheGroups === "function") { + return cacheGroups; + } + if (typeof cacheGroups === "object" && cacheGroups !== null) { + /** @type {(function(Module, CacheGroupsContext, CacheGroupSource[]): void)[]} */ + const handlers = []; + for (const key of Object.keys(cacheGroups)) { + const option = cacheGroups[key]; + if (option === false) { + continue; + } + if (typeof option === "string" || option instanceof RegExp) { + const source = createCacheGroupSource({}, key, defaultSizeTypes); + handlers.push((module, context, results) => { + if (checkTest(option, module, context)) { + results.push(source); + } + }); + } else if (typeof option === "function") { + const cache = new WeakMap(); + handlers.push((module, context, results) => { + const result = option(module); + if (result) { + const groups = Array.isArray(result) ? result : [result]; + for (const group of groups) { + const cachedSource = cache.get(group); + if (cachedSource !== undefined) { + results.push(cachedSource); + } else { + const source = createCacheGroupSource( + group, + key, + defaultSizeTypes + ); + cache.set(group, source); + results.push(source); + } + } + } + }); + } else { + const source = createCacheGroupSource(option, key, defaultSizeTypes); + handlers.push((module, context, results) => { + if ( + checkTest(option.test, module, context) && + checkModuleType(option.type, module) && + checkModuleLayer(option.layer, module) + ) { + results.push(source); + } + }); + } + } + /** + * @param {Module} module the current module + * @param {CacheGroupsContext} context the current context + * @returns {CacheGroupSource[]} the matching cache groups + */ + const fn = (module, context) => { + /** @type {CacheGroupSource[]} */ + let results = []; + for (const fn of handlers) { + fn(module, context, results); + } + return results; + }; + return fn; + } + return () => null; +}; + +/** + * @param {undefined|boolean|string|RegExp|Function} test test option + * @param {Module} module the module + * @param {CacheGroupsContext} context context object + * @returns {boolean} true, if the module should be selected + */ +const checkTest = (test, module, context) => { + if (test === undefined) return true; + if (typeof test === "function") { + return test(module, context); + } + if (typeof test === "boolean") return test; + if (typeof test === "string") { + const name = module.nameForCondition(); + return name && name.startsWith(test); + } + if (test instanceof RegExp) { + const name = module.nameForCondition(); + return name && test.test(name); + } + return false; +}; + +/** + * @param {undefined|string|RegExp|Function} test type option + * @param {Module} module the module + * @returns {boolean} true, if the module should be selected + */ +const checkModuleType = (test, module) => { + if (test === undefined) return true; + if (typeof test === "function") { + return test(module.type); + } + if (typeof test === "string") { + const type = module.type; + return test === type; + } + if (test instanceof RegExp) { + const type = module.type; + return test.test(type); + } + return false; +}; + +/** + * @param {undefined|string|RegExp|Function} test type option + * @param {Module} module the module + * @returns {boolean} true, if the module should be selected + */ +const checkModuleLayer = (test, module) => { + if (test === undefined) return true; + if (typeof test === "function") { + return test(module.layer); + } + if (typeof test === "string") { + const layer = module.layer; + return test === "" ? !layer : layer && layer.startsWith(test); + } + if (test instanceof RegExp) { + const layer = module.layer; + return test.test(layer); + } + return false; +}; + +/** + * @param {OptimizationSplitChunksCacheGroup} options the group options + * @param {string} key key of cache group + * @param {string[]} defaultSizeTypes the default size types + * @returns {CacheGroupSource} the normalized cached group + */ +const createCacheGroupSource = (options, key, defaultSizeTypes) => { + const minSize = normalizeSizes(options.minSize, defaultSizeTypes); + const minSizeReduction = normalizeSizes( + options.minSizeReduction, + defaultSizeTypes + ); + const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes); + return { + key, + priority: options.priority, + getName: normalizeName(options.name), + chunksFilter: normalizeChunksFilter(options.chunks), + enforce: options.enforce, + minSize, + minSizeReduction, + minRemainingSize: mergeSizes( + normalizeSizes(options.minRemainingSize, defaultSizeTypes), + minSize + ), + enforceSizeThreshold: normalizeSizes( + options.enforceSizeThreshold, + defaultSizeTypes + ), + maxAsyncSize: mergeSizes( + normalizeSizes(options.maxAsyncSize, defaultSizeTypes), + maxSize + ), + maxInitialSize: mergeSizes( + normalizeSizes(options.maxInitialSize, defaultSizeTypes), + maxSize + ), + minChunks: options.minChunks, + maxAsyncRequests: options.maxAsyncRequests, + maxInitialRequests: options.maxInitialRequests, + filename: options.filename, + idHint: options.idHint, + automaticNameDelimiter: options.automaticNameDelimiter, + reuseExistingChunk: options.reuseExistingChunk, + usedExports: options.usedExports + }; +}; + +module.exports = class SplitChunksPlugin { + /** + * @param {OptimizationSplitChunksOptions=} options plugin options + */ + constructor(options = {}) { + const defaultSizeTypes = options.defaultSizeTypes || [ + "javascript", + "unknown" + ]; + const fallbackCacheGroup = options.fallbackCacheGroup || {}; + const minSize = normalizeSizes(options.minSize, defaultSizeTypes); + const minSizeReduction = normalizeSizes( + options.minSizeReduction, + defaultSizeTypes + ); + const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes); + + /** @type {SplitChunksOptions} */ + this.options = { + chunksFilter: normalizeChunksFilter(options.chunks || "all"), + defaultSizeTypes, + minSize, + minSizeReduction, + minRemainingSize: mergeSizes( + normalizeSizes(options.minRemainingSize, defaultSizeTypes), + minSize + ), + enforceSizeThreshold: normalizeSizes( + options.enforceSizeThreshold, + defaultSizeTypes + ), + maxAsyncSize: mergeSizes( + normalizeSizes(options.maxAsyncSize, defaultSizeTypes), + maxSize + ), + maxInitialSize: mergeSizes( + normalizeSizes(options.maxInitialSize, defaultSizeTypes), + maxSize + ), + minChunks: options.minChunks || 1, + maxAsyncRequests: options.maxAsyncRequests || 1, + maxInitialRequests: options.maxInitialRequests || 1, + hidePathInfo: options.hidePathInfo || false, + filename: options.filename || undefined, + getCacheGroups: normalizeCacheGroups( + options.cacheGroups, + defaultSizeTypes + ), + getName: options.name ? normalizeName(options.name) : defaultGetName, + automaticNameDelimiter: options.automaticNameDelimiter, + usedExports: options.usedExports, + fallbackCacheGroup: { + chunksFilter: normalizeChunksFilter( + fallbackCacheGroup.chunks || options.chunks || "all" + ), + minSize: mergeSizes( + normalizeSizes(fallbackCacheGroup.minSize, defaultSizeTypes), + minSize + ), + maxAsyncSize: mergeSizes( + normalizeSizes(fallbackCacheGroup.maxAsyncSize, defaultSizeTypes), + normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes), + normalizeSizes(options.maxAsyncSize, defaultSizeTypes), + normalizeSizes(options.maxSize, defaultSizeTypes) + ), + maxInitialSize: mergeSizes( + normalizeSizes(fallbackCacheGroup.maxInitialSize, defaultSizeTypes), + normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes), + normalizeSizes(options.maxInitialSize, defaultSizeTypes), + normalizeSizes(options.maxSize, defaultSizeTypes) + ), + automaticNameDelimiter: + fallbackCacheGroup.automaticNameDelimiter || + options.automaticNameDelimiter || + "~" + } + }; + + /** @type {WeakMap} */ + this._cacheGroupCache = new WeakMap(); + } + + /** + * @param {CacheGroupSource} cacheGroupSource source + * @returns {CacheGroup} the cache group (cached) + */ + _getCacheGroup(cacheGroupSource) { + const cacheEntry = this._cacheGroupCache.get(cacheGroupSource); + if (cacheEntry !== undefined) return cacheEntry; + const minSize = mergeSizes( + cacheGroupSource.minSize, + cacheGroupSource.enforce ? undefined : this.options.minSize + ); + const minSizeReduction = mergeSizes( + cacheGroupSource.minSizeReduction, + cacheGroupSource.enforce ? undefined : this.options.minSizeReduction + ); + const minRemainingSize = mergeSizes( + cacheGroupSource.minRemainingSize, + cacheGroupSource.enforce ? undefined : this.options.minRemainingSize + ); + const enforceSizeThreshold = mergeSizes( + cacheGroupSource.enforceSizeThreshold, + cacheGroupSource.enforce ? undefined : this.options.enforceSizeThreshold + ); + const cacheGroup = { + key: cacheGroupSource.key, + priority: cacheGroupSource.priority || 0, + chunksFilter: cacheGroupSource.chunksFilter || this.options.chunksFilter, + minSize, + minSizeReduction, + minRemainingSize, + enforceSizeThreshold, + maxAsyncSize: mergeSizes( + cacheGroupSource.maxAsyncSize, + cacheGroupSource.enforce ? undefined : this.options.maxAsyncSize + ), + maxInitialSize: mergeSizes( + cacheGroupSource.maxInitialSize, + cacheGroupSource.enforce ? undefined : this.options.maxInitialSize + ), + minChunks: + cacheGroupSource.minChunks !== undefined + ? cacheGroupSource.minChunks + : cacheGroupSource.enforce + ? 1 + : this.options.minChunks, + maxAsyncRequests: + cacheGroupSource.maxAsyncRequests !== undefined + ? cacheGroupSource.maxAsyncRequests + : cacheGroupSource.enforce + ? Infinity + : this.options.maxAsyncRequests, + maxInitialRequests: + cacheGroupSource.maxInitialRequests !== undefined + ? cacheGroupSource.maxInitialRequests + : cacheGroupSource.enforce + ? Infinity + : this.options.maxInitialRequests, + getName: + cacheGroupSource.getName !== undefined + ? cacheGroupSource.getName + : this.options.getName, + usedExports: + cacheGroupSource.usedExports !== undefined + ? cacheGroupSource.usedExports + : this.options.usedExports, + filename: + cacheGroupSource.filename !== undefined + ? cacheGroupSource.filename + : this.options.filename, + automaticNameDelimiter: + cacheGroupSource.automaticNameDelimiter !== undefined + ? cacheGroupSource.automaticNameDelimiter + : this.options.automaticNameDelimiter, + idHint: + cacheGroupSource.idHint !== undefined + ? cacheGroupSource.idHint + : cacheGroupSource.key, + reuseExistingChunk: cacheGroupSource.reuseExistingChunk || false, + _validateSize: hasNonZeroSizes(minSize), + _validateRemainingSize: hasNonZeroSizes(minRemainingSize), + _minSizeForMaxSize: mergeSizes( + cacheGroupSource.minSize, + this.options.minSize + ), + _conditionalEnforce: hasNonZeroSizes(enforceSizeThreshold) + }; + this._cacheGroupCache.set(cacheGroupSource, cacheGroup); + return cacheGroup; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const cachedMakePathsRelative = makePathsRelative.bindContextCache( + compiler.context, + compiler.root + ); + compiler.hooks.thisCompilation.tap("SplitChunksPlugin", compilation => { + const logger = compilation.getLogger("webpack.SplitChunksPlugin"); + let alreadyOptimized = false; + compilation.hooks.unseal.tap("SplitChunksPlugin", () => { + alreadyOptimized = false; + }); + compilation.hooks.optimizeChunks.tap( + { + name: "SplitChunksPlugin", + stage: STAGE_ADVANCED + }, + chunks => { + if (alreadyOptimized) return; + alreadyOptimized = true; + logger.time("prepare"); + const chunkGraph = compilation.chunkGraph; + const moduleGraph = compilation.moduleGraph; + // Give each selected chunk an index (to create strings from chunks) + /** @type {Map} */ + const chunkIndexMap = new Map(); + const ZERO = BigInt("0"); + const ONE = BigInt("1"); + const START = ONE << BigInt("31"); + let index = START; + for (const chunk of chunks) { + chunkIndexMap.set( + chunk, + index | BigInt((Math.random() * 0x7fffffff) | 0) + ); + index = index << ONE; + } + /** + * @param {Iterable} chunks list of chunks + * @returns {bigint | Chunk} key of the chunks + */ + const getKey = chunks => { + const iterator = chunks[Symbol.iterator](); + let result = iterator.next(); + if (result.done) return ZERO; + const first = result.value; + result = iterator.next(); + if (result.done) return first; + let key = + chunkIndexMap.get(first) | chunkIndexMap.get(result.value); + while (!(result = iterator.next()).done) { + const raw = chunkIndexMap.get(result.value); + key = key ^ raw; + } + return key; + }; + const keyToString = key => { + if (typeof key === "bigint") return key.toString(16); + return chunkIndexMap.get(key).toString(16); + }; + + const getChunkSetsInGraph = memoize(() => { + /** @type {Map>} */ + const chunkSetsInGraph = new Map(); + /** @type {Set} */ + const singleChunkSets = new Set(); + for (const module of compilation.modules) { + const chunks = chunkGraph.getModuleChunksIterable(module); + const chunksKey = getKey(chunks); + if (typeof chunksKey === "bigint") { + if (!chunkSetsInGraph.has(chunksKey)) { + chunkSetsInGraph.set(chunksKey, new Set(chunks)); + } + } else { + singleChunkSets.add(chunksKey); + } + } + return { chunkSetsInGraph, singleChunkSets }; + }); + + /** + * @param {Module} module the module + * @returns {Iterable} groups of chunks with equal exports + */ + const groupChunksByExports = module => { + const exportsInfo = moduleGraph.getExportsInfo(module); + const groupedByUsedExports = new Map(); + for (const chunk of chunkGraph.getModuleChunksIterable(module)) { + const key = exportsInfo.getUsageKey(chunk.runtime); + const list = groupedByUsedExports.get(key); + if (list !== undefined) { + list.push(chunk); + } else { + groupedByUsedExports.set(key, [chunk]); + } + } + return groupedByUsedExports.values(); + }; + + /** @type {Map>} */ + const groupedByExportsMap = new Map(); + + const getExportsChunkSetsInGraph = memoize(() => { + /** @type {Map>} */ + const chunkSetsInGraph = new Map(); + /** @type {Set} */ + const singleChunkSets = new Set(); + for (const module of compilation.modules) { + const groupedChunks = Array.from(groupChunksByExports(module)); + groupedByExportsMap.set(module, groupedChunks); + for (const chunks of groupedChunks) { + if (chunks.length === 1) { + singleChunkSets.add(chunks[0]); + } else { + const chunksKey = /** @type {bigint} */ (getKey(chunks)); + if (!chunkSetsInGraph.has(chunksKey)) { + chunkSetsInGraph.set(chunksKey, new Set(chunks)); + } + } + } + } + return { chunkSetsInGraph, singleChunkSets }; + }); + + // group these set of chunks by count + // to allow to check less sets via isSubset + // (only smaller sets can be subset) + const groupChunkSetsByCount = chunkSets => { + /** @type {Map>>} */ + const chunkSetsByCount = new Map(); + for (const chunksSet of chunkSets) { + const count = chunksSet.size; + let array = chunkSetsByCount.get(count); + if (array === undefined) { + array = []; + chunkSetsByCount.set(count, array); + } + array.push(chunksSet); + } + return chunkSetsByCount; + }; + const getChunkSetsByCount = memoize(() => + groupChunkSetsByCount( + getChunkSetsInGraph().chunkSetsInGraph.values() + ) + ); + const getExportsChunkSetsByCount = memoize(() => + groupChunkSetsByCount( + getExportsChunkSetsInGraph().chunkSetsInGraph.values() + ) + ); + + // Create a list of possible combinations + const createGetCombinations = ( + chunkSets, + singleChunkSets, + chunkSetsByCount + ) => { + /** @type {Map | Chunk)[]>} */ + const combinationsCache = new Map(); + + return key => { + const cacheEntry = combinationsCache.get(key); + if (cacheEntry !== undefined) return cacheEntry; + if (key instanceof Chunk) { + const result = [key]; + combinationsCache.set(key, result); + return result; + } + const chunksSet = chunkSets.get(key); + /** @type {(Set | Chunk)[]} */ + const array = [chunksSet]; + for (const [count, setArray] of chunkSetsByCount) { + // "equal" is not needed because they would have been merge in the first step + if (count < chunksSet.size) { + for (const set of setArray) { + if (isSubset(chunksSet, set)) { + array.push(set); + } + } + } + } + for (const chunk of singleChunkSets) { + if (chunksSet.has(chunk)) { + array.push(chunk); + } + } + combinationsCache.set(key, array); + return array; + }; + }; + + const getCombinationsFactory = memoize(() => { + const { chunkSetsInGraph, singleChunkSets } = getChunkSetsInGraph(); + return createGetCombinations( + chunkSetsInGraph, + singleChunkSets, + getChunkSetsByCount() + ); + }); + const getCombinations = key => getCombinationsFactory()(key); + + const getExportsCombinationsFactory = memoize(() => { + const { chunkSetsInGraph, singleChunkSets } = + getExportsChunkSetsInGraph(); + return createGetCombinations( + chunkSetsInGraph, + singleChunkSets, + getExportsChunkSetsByCount() + ); + }); + const getExportsCombinations = key => + getExportsCombinationsFactory()(key); + + /** + * @typedef {Object} SelectedChunksResult + * @property {Chunk[]} chunks the list of chunks + * @property {bigint | Chunk} key a key of the list + */ + + /** @type {WeakMap | Chunk, WeakMap>} */ + const selectedChunksCacheByChunksSet = new WeakMap(); + + /** + * get list and key by applying the filter function to the list + * It is cached for performance reasons + * @param {Set | Chunk} chunks list of chunks + * @param {ChunkFilterFunction} chunkFilter filter function for chunks + * @returns {SelectedChunksResult} list and key + */ + const getSelectedChunks = (chunks, chunkFilter) => { + let entry = selectedChunksCacheByChunksSet.get(chunks); + if (entry === undefined) { + entry = new WeakMap(); + selectedChunksCacheByChunksSet.set(chunks, entry); + } + /** @type {SelectedChunksResult} */ + let entry2 = entry.get(chunkFilter); + if (entry2 === undefined) { + /** @type {Chunk[]} */ + const selectedChunks = []; + if (chunks instanceof Chunk) { + if (chunkFilter(chunks)) selectedChunks.push(chunks); + } else { + for (const chunk of chunks) { + if (chunkFilter(chunk)) selectedChunks.push(chunk); + } + } + entry2 = { + chunks: selectedChunks, + key: getKey(selectedChunks) + }; + entry.set(chunkFilter, entry2); + } + return entry2; + }; + + /** @type {Map} */ + const alreadyValidatedParents = new Map(); + /** @type {Set} */ + const alreadyReportedErrors = new Set(); + + // Map a list of chunks to a list of modules + // For the key the chunk "index" is used, the value is a SortableSet of modules + /** @type {Map} */ + const chunksInfoMap = new Map(); + + /** + * @param {CacheGroup} cacheGroup the current cache group + * @param {number} cacheGroupIndex the index of the cache group of ordering + * @param {Chunk[]} selectedChunks chunks selected for this module + * @param {bigint | Chunk} selectedChunksKey a key of selectedChunks + * @param {Module} module the current module + * @returns {void} + */ + const addModuleToChunksInfoMap = ( + cacheGroup, + cacheGroupIndex, + selectedChunks, + selectedChunksKey, + module + ) => { + // Break if minimum number of chunks is not reached + if (selectedChunks.length < cacheGroup.minChunks) return; + // Determine name for split chunk + const name = cacheGroup.getName( + module, + selectedChunks, + cacheGroup.key + ); + // Check if the name is ok + const existingChunk = compilation.namedChunks.get(name); + if (existingChunk) { + const parentValidationKey = `${name}|${ + typeof selectedChunksKey === "bigint" + ? selectedChunksKey + : selectedChunksKey.debugId + }`; + const valid = alreadyValidatedParents.get(parentValidationKey); + if (valid === false) return; + if (valid === undefined) { + // Module can only be moved into the existing chunk if the existing chunk + // is a parent of all selected chunks + let isInAllParents = true; + /** @type {Set} */ + const queue = new Set(); + for (const chunk of selectedChunks) { + for (const group of chunk.groupsIterable) { + queue.add(group); + } + } + for (const group of queue) { + if (existingChunk.isInGroup(group)) continue; + let hasParent = false; + for (const parent of group.parentsIterable) { + hasParent = true; + queue.add(parent); + } + if (!hasParent) { + isInAllParents = false; + } + } + const valid = isInAllParents; + alreadyValidatedParents.set(parentValidationKey, valid); + if (!valid) { + if (!alreadyReportedErrors.has(name)) { + alreadyReportedErrors.add(name); + compilation.errors.push( + new WebpackError( + "SplitChunksPlugin\n" + + `Cache group "${cacheGroup.key}" conflicts with existing chunk.\n` + + `Both have the same name "${name}" and existing chunk is not a parent of the selected modules.\n` + + "Use a different name for the cache group or make sure that the existing chunk is a parent (e. g. via dependOn).\n" + + 'HINT: You can omit "name" to automatically create a name.\n' + + "BREAKING CHANGE: webpack < 5 used to allow to use an entrypoint as splitChunk. " + + "This is no longer allowed when the entrypoint is not a parent of the selected modules.\n" + + "Remove this entrypoint and add modules to cache group's 'test' instead. " + + "If you need modules to be evaluated on startup, add them to the existing entrypoints (make them arrays). " + + "See migration guide of more info." + ) + ); + } + return; + } + } + } + // Create key for maps + // When it has a name we use the name as key + // Otherwise we create the key from chunks and cache group key + // This automatically merges equal names + const key = + cacheGroup.key + + (name + ? ` name:${name}` + : ` chunks:${keyToString(selectedChunksKey)}`); + // Add module to maps + let info = chunksInfoMap.get(key); + if (info === undefined) { + chunksInfoMap.set( + key, + (info = { + modules: new SortableSet( + undefined, + compareModulesByIdentifier + ), + cacheGroup, + cacheGroupIndex, + name, + sizes: {}, + chunks: new Set(), + reuseableChunks: new Set(), + chunksKeys: new Set() + }) + ); + } + const oldSize = info.modules.size; + info.modules.add(module); + if (info.modules.size !== oldSize) { + for (const type of module.getSourceTypes()) { + info.sizes[type] = (info.sizes[type] || 0) + module.size(type); + } + } + const oldChunksKeysSize = info.chunksKeys.size; + info.chunksKeys.add(selectedChunksKey); + if (oldChunksKeysSize !== info.chunksKeys.size) { + for (const chunk of selectedChunks) { + info.chunks.add(chunk); + } + } + }; + + const context = { + moduleGraph, + chunkGraph + }; + + logger.timeEnd("prepare"); + + logger.time("modules"); + + // Walk through all modules + for (const module of compilation.modules) { + // Get cache group + let cacheGroups = this.options.getCacheGroups(module, context); + if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { + continue; + } + + // Prepare some values (usedExports = false) + const getCombs = memoize(() => { + const chunks = chunkGraph.getModuleChunksIterable(module); + const chunksKey = getKey(chunks); + return getCombinations(chunksKey); + }); + + // Prepare some values (usedExports = true) + const getCombsByUsedExports = memoize(() => { + // fill the groupedByExportsMap + getExportsChunkSetsInGraph(); + /** @type {Set | Chunk>} */ + const set = new Set(); + const groupedByUsedExports = groupedByExportsMap.get(module); + for (const chunks of groupedByUsedExports) { + const chunksKey = getKey(chunks); + for (const comb of getExportsCombinations(chunksKey)) + set.add(comb); + } + return set; + }); + + let cacheGroupIndex = 0; + for (const cacheGroupSource of cacheGroups) { + const cacheGroup = this._getCacheGroup(cacheGroupSource); + + const combs = cacheGroup.usedExports + ? getCombsByUsedExports() + : getCombs(); + // For all combination of chunk selection + for (const chunkCombination of combs) { + // Break if minimum number of chunks is not reached + const count = + chunkCombination instanceof Chunk ? 1 : chunkCombination.size; + if (count < cacheGroup.minChunks) continue; + // Select chunks by configuration + const { chunks: selectedChunks, key: selectedChunksKey } = + getSelectedChunks(chunkCombination, cacheGroup.chunksFilter); + + addModuleToChunksInfoMap( + cacheGroup, + cacheGroupIndex, + selectedChunks, + selectedChunksKey, + module + ); + } + cacheGroupIndex++; + } + } + + logger.timeEnd("modules"); + + logger.time("queue"); + + /** + * @param {ChunksInfoItem} info entry + * @param {string[]} sourceTypes source types to be removed + */ + const removeModulesWithSourceType = (info, sourceTypes) => { + for (const module of info.modules) { + const types = module.getSourceTypes(); + if (sourceTypes.some(type => types.has(type))) { + info.modules.delete(module); + for (const type of types) { + info.sizes[type] -= module.size(type); + } + } + } + }; + + /** + * @param {ChunksInfoItem} info entry + * @returns {boolean} true, if entry become empty + */ + const removeMinSizeViolatingModules = info => { + if (!info.cacheGroup._validateSize) return false; + const violatingSizes = getViolatingMinSizes( + info.sizes, + info.cacheGroup.minSize + ); + if (violatingSizes === undefined) return false; + removeModulesWithSourceType(info, violatingSizes); + return info.modules.size === 0; + }; + + // Filter items were size < minSize + for (const [key, info] of chunksInfoMap) { + if (removeMinSizeViolatingModules(info)) { + chunksInfoMap.delete(key); + } else if ( + !checkMinSizeReduction( + info.sizes, + info.cacheGroup.minSizeReduction, + info.chunks.size + ) + ) { + chunksInfoMap.delete(key); + } + } + + /** + * @typedef {Object} MaxSizeQueueItem + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} maxAsyncSize + * @property {SplitChunksSizes} maxInitialSize + * @property {string} automaticNameDelimiter + * @property {string[]} keys + */ + + /** @type {Map} */ + const maxSizeQueueMap = new Map(); + + while (chunksInfoMap.size > 0) { + // Find best matching entry + let bestEntryKey; + let bestEntry; + for (const pair of chunksInfoMap) { + const key = pair[0]; + const info = pair[1]; + if ( + bestEntry === undefined || + compareEntries(bestEntry, info) < 0 + ) { + bestEntry = info; + bestEntryKey = key; + } + } + + const item = bestEntry; + chunksInfoMap.delete(bestEntryKey); + + let chunkName = item.name; + // Variable for the new chunk (lazy created) + /** @type {Chunk} */ + let newChunk; + // When no chunk name, check if we can reuse a chunk instead of creating a new one + let isExistingChunk = false; + let isReusedWithAllModules = false; + if (chunkName) { + const chunkByName = compilation.namedChunks.get(chunkName); + if (chunkByName !== undefined) { + newChunk = chunkByName; + const oldSize = item.chunks.size; + item.chunks.delete(newChunk); + isExistingChunk = item.chunks.size !== oldSize; + } + } else if (item.cacheGroup.reuseExistingChunk) { + outer: for (const chunk of item.chunks) { + if ( + chunkGraph.getNumberOfChunkModules(chunk) !== + item.modules.size + ) { + continue; + } + if ( + item.chunks.size > 1 && + chunkGraph.getNumberOfEntryModules(chunk) > 0 + ) { + continue; + } + for (const module of item.modules) { + if (!chunkGraph.isModuleInChunk(module, chunk)) { + continue outer; + } + } + if (!newChunk || !newChunk.name) { + newChunk = chunk; + } else if ( + chunk.name && + chunk.name.length < newChunk.name.length + ) { + newChunk = chunk; + } else if ( + chunk.name && + chunk.name.length === newChunk.name.length && + chunk.name < newChunk.name + ) { + newChunk = chunk; + } + } + if (newChunk) { + item.chunks.delete(newChunk); + chunkName = undefined; + isExistingChunk = true; + isReusedWithAllModules = true; + } + } + + const enforced = + item.cacheGroup._conditionalEnforce && + checkMinSize(item.sizes, item.cacheGroup.enforceSizeThreshold); + + const usedChunks = new Set(item.chunks); + + // Check if maxRequests condition can be fulfilled + if ( + !enforced && + (Number.isFinite(item.cacheGroup.maxInitialRequests) || + Number.isFinite(item.cacheGroup.maxAsyncRequests)) + ) { + for (const chunk of usedChunks) { + // respect max requests + const maxRequests = chunk.isOnlyInitial() + ? item.cacheGroup.maxInitialRequests + : chunk.canBeInitial() + ? Math.min( + item.cacheGroup.maxInitialRequests, + item.cacheGroup.maxAsyncRequests + ) + : item.cacheGroup.maxAsyncRequests; + if ( + isFinite(maxRequests) && + getRequests(chunk) >= maxRequests + ) { + usedChunks.delete(chunk); + } + } + } + + outer: for (const chunk of usedChunks) { + for (const module of item.modules) { + if (chunkGraph.isModuleInChunk(module, chunk)) continue outer; + } + usedChunks.delete(chunk); + } + + // Were some (invalid) chunks removed from usedChunks? + // => readd all modules to the queue, as things could have been changed + if (usedChunks.size < item.chunks.size) { + if (isExistingChunk) usedChunks.add(newChunk); + if (usedChunks.size >= item.cacheGroup.minChunks) { + const chunksArr = Array.from(usedChunks); + for (const module of item.modules) { + addModuleToChunksInfoMap( + item.cacheGroup, + item.cacheGroupIndex, + chunksArr, + getKey(usedChunks), + module + ); + } + } + continue; + } + + // Validate minRemainingSize constraint when a single chunk is left over + if ( + !enforced && + item.cacheGroup._validateRemainingSize && + usedChunks.size === 1 + ) { + const [chunk] = usedChunks; + let chunkSizes = Object.create(null); + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (!item.modules.has(module)) { + for (const type of module.getSourceTypes()) { + chunkSizes[type] = + (chunkSizes[type] || 0) + module.size(type); + } + } + } + const violatingSizes = getViolatingMinSizes( + chunkSizes, + item.cacheGroup.minRemainingSize + ); + if (violatingSizes !== undefined) { + const oldModulesSize = item.modules.size; + removeModulesWithSourceType(item, violatingSizes); + if ( + item.modules.size > 0 && + item.modules.size !== oldModulesSize + ) { + // queue this item again to be processed again + // without violating modules + chunksInfoMap.set(bestEntryKey, item); + } + continue; + } + } + + // Create the new chunk if not reusing one + if (newChunk === undefined) { + newChunk = compilation.addChunk(chunkName); + } + // Walk through all chunks + for (const chunk of usedChunks) { + // Add graph connections for splitted chunk + chunk.split(newChunk); + } + + // Add a note to the chunk + newChunk.chunkReason = + (newChunk.chunkReason ? newChunk.chunkReason + ", " : "") + + (isReusedWithAllModules + ? "reused as split chunk" + : "split chunk"); + if (item.cacheGroup.key) { + newChunk.chunkReason += ` (cache group: ${item.cacheGroup.key})`; + } + if (chunkName) { + newChunk.chunkReason += ` (name: ${chunkName})`; + } + if (item.cacheGroup.filename) { + newChunk.filenameTemplate = item.cacheGroup.filename; + } + if (item.cacheGroup.idHint) { + newChunk.idNameHints.add(item.cacheGroup.idHint); + } + if (!isReusedWithAllModules) { + // Add all modules to the new chunk + for (const module of item.modules) { + if (!module.chunkCondition(newChunk, compilation)) continue; + // Add module to new chunk + chunkGraph.connectChunkAndModule(newChunk, module); + // Remove module from used chunks + for (const chunk of usedChunks) { + chunkGraph.disconnectChunkAndModule(chunk, module); + } + } + } else { + // Remove all modules from used chunks + for (const module of item.modules) { + for (const chunk of usedChunks) { + chunkGraph.disconnectChunkAndModule(chunk, module); + } + } + } + + if ( + Object.keys(item.cacheGroup.maxAsyncSize).length > 0 || + Object.keys(item.cacheGroup.maxInitialSize).length > 0 + ) { + const oldMaxSizeSettings = maxSizeQueueMap.get(newChunk); + maxSizeQueueMap.set(newChunk, { + minSize: oldMaxSizeSettings + ? combineSizes( + oldMaxSizeSettings.minSize, + item.cacheGroup._minSizeForMaxSize, + Math.max + ) + : item.cacheGroup.minSize, + maxAsyncSize: oldMaxSizeSettings + ? combineSizes( + oldMaxSizeSettings.maxAsyncSize, + item.cacheGroup.maxAsyncSize, + Math.min + ) + : item.cacheGroup.maxAsyncSize, + maxInitialSize: oldMaxSizeSettings + ? combineSizes( + oldMaxSizeSettings.maxInitialSize, + item.cacheGroup.maxInitialSize, + Math.min + ) + : item.cacheGroup.maxInitialSize, + automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter, + keys: oldMaxSizeSettings + ? oldMaxSizeSettings.keys.concat(item.cacheGroup.key) + : [item.cacheGroup.key] + }); + } + + // remove all modules from other entries and update size + for (const [key, info] of chunksInfoMap) { + if (isOverlap(info.chunks, usedChunks)) { + // update modules and total size + // may remove it from the map when < minSize + let updated = false; + for (const module of item.modules) { + if (info.modules.has(module)) { + // remove module + info.modules.delete(module); + // update size + for (const key of module.getSourceTypes()) { + info.sizes[key] -= module.size(key); + } + updated = true; + } + } + if (updated) { + if (info.modules.size === 0) { + chunksInfoMap.delete(key); + continue; + } + if ( + removeMinSizeViolatingModules(info) || + !checkMinSizeReduction( + info.sizes, + info.cacheGroup.minSizeReduction, + info.chunks.size + ) + ) { + chunksInfoMap.delete(key); + continue; + } + } + } + } + } + + logger.timeEnd("queue"); + + logger.time("maxSize"); + + /** @type {Set} */ + const incorrectMinMaxSizeSet = new Set(); + + const { outputOptions } = compilation; + + // Make sure that maxSize is fulfilled + const { fallbackCacheGroup } = this.options; + for (const chunk of Array.from(compilation.chunks)) { + const chunkConfig = maxSizeQueueMap.get(chunk); + const { + minSize, + maxAsyncSize, + maxInitialSize, + automaticNameDelimiter + } = chunkConfig || fallbackCacheGroup; + if (!chunkConfig && !fallbackCacheGroup.chunksFilter(chunk)) + continue; + /** @type {SplitChunksSizes} */ + let maxSize; + if (chunk.isOnlyInitial()) { + maxSize = maxInitialSize; + } else if (chunk.canBeInitial()) { + maxSize = combineSizes(maxAsyncSize, maxInitialSize, Math.min); + } else { + maxSize = maxAsyncSize; + } + if (Object.keys(maxSize).length === 0) { + continue; + } + for (const key of Object.keys(maxSize)) { + const maxSizeValue = maxSize[key]; + const minSizeValue = minSize[key]; + if ( + typeof minSizeValue === "number" && + minSizeValue > maxSizeValue + ) { + const keys = chunkConfig && chunkConfig.keys; + const warningKey = `${ + keys && keys.join() + } ${minSizeValue} ${maxSizeValue}`; + if (!incorrectMinMaxSizeSet.has(warningKey)) { + incorrectMinMaxSizeSet.add(warningKey); + compilation.warnings.push( + new MinMaxSizeWarning(keys, minSizeValue, maxSizeValue) + ); + } + } + } + const results = deterministicGroupingForModules({ + minSize, + maxSize: mapObject(maxSize, (value, key) => { + const minSizeValue = minSize[key]; + return typeof minSizeValue === "number" + ? Math.max(value, minSizeValue) + : value; + }), + items: chunkGraph.getChunkModulesIterable(chunk), + getKey(module) { + const cache = getKeyCache.get(module); + if (cache !== undefined) return cache; + const ident = cachedMakePathsRelative(module.identifier()); + const nameForCondition = + module.nameForCondition && module.nameForCondition(); + const name = nameForCondition + ? cachedMakePathsRelative(nameForCondition) + : ident.replace(/^.*!|\?[^?!]*$/g, ""); + const fullKey = + name + + automaticNameDelimiter + + hashFilename(ident, outputOptions); + const key = requestToId(fullKey); + getKeyCache.set(module, key); + return key; + }, + getSize(module) { + const size = Object.create(null); + for (const key of module.getSourceTypes()) { + size[key] = module.size(key); + } + return size; + } + }); + if (results.length <= 1) { + continue; + } + for (let i = 0; i < results.length; i++) { + const group = results[i]; + const key = this.options.hidePathInfo + ? hashFilename(group.key, outputOptions) + : group.key; + let name = chunk.name + ? chunk.name + automaticNameDelimiter + key + : null; + if (name && name.length > 100) { + name = + name.slice(0, 100) + + automaticNameDelimiter + + hashFilename(name, outputOptions); + } + if (i !== results.length - 1) { + const newPart = compilation.addChunk(name); + chunk.split(newPart); + newPart.chunkReason = chunk.chunkReason; + // Add all modules to the new chunk + for (const module of group.items) { + if (!module.chunkCondition(newPart, compilation)) { + continue; + } + // Add module to new chunk + chunkGraph.connectChunkAndModule(newPart, module); + // Remove module from used chunks + chunkGraph.disconnectChunkAndModule(chunk, module); + } + } else { + // change the chunk to be a part + chunk.name = name; + } + } + } + logger.timeEnd("maxSize"); + } + ); + }); + } +}; + + +/***/ }), + +/***/ 52149: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + + + +const { formatSize } = __webpack_require__(71070); +const WebpackError = __webpack_require__(53799); + +/** @typedef {import("./SizeLimitsPlugin").AssetDetails} AssetDetails */ + +module.exports = class AssetsOverSizeLimitWarning extends WebpackError { + /** + * @param {AssetDetails[]} assetsOverSizeLimit the assets + * @param {number} assetLimit the size limit + */ + constructor(assetsOverSizeLimit, assetLimit) { + const assetLists = assetsOverSizeLimit + .map(asset => `\n ${asset.name} (${formatSize(asset.size)})`) + .join(""); + + super(`asset size limit: The following asset(s) exceed the recommended size limit (${formatSize( + assetLimit + )}). +This can impact web performance. +Assets: ${assetLists}`); + + this.name = "AssetsOverSizeLimitWarning"; + this.assets = assetsOverSizeLimit; + } +}; + + +/***/ }), + +/***/ 84229: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + + + +const { formatSize } = __webpack_require__(71070); +const WebpackError = __webpack_require__(53799); + +/** @typedef {import("./SizeLimitsPlugin").EntrypointDetails} EntrypointDetails */ + +module.exports = class EntrypointsOverSizeLimitWarning extends WebpackError { + /** + * @param {EntrypointDetails[]} entrypoints the entrypoints + * @param {number} entrypointLimit the size limit + */ + constructor(entrypoints, entrypointLimit) { + const entrypointList = entrypoints + .map( + entrypoint => + `\n ${entrypoint.name} (${formatSize( + entrypoint.size + )})\n${entrypoint.files.map(asset => ` ${asset}`).join("\n")}` + ) + .join(""); + super(`entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (${formatSize( + entrypointLimit + )}). This can impact web performance. +Entrypoints:${entrypointList}\n`); + + this.name = "EntrypointsOverSizeLimitWarning"; + this.entrypoints = entrypoints; + } +}; + + +/***/ }), + +/***/ 17791: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + + + +const WebpackError = __webpack_require__(53799); + +module.exports = class NoAsyncChunksWarning extends WebpackError { + constructor() { + super( + "webpack performance recommendations: \n" + + "You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\n" + + "For more info visit https://webpack.js.org/guides/code-splitting/" + ); + + this.name = "NoAsyncChunksWarning"; + } +}; + + +/***/ }), + +/***/ 32557: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + + + +const { find } = __webpack_require__(93347); +const AssetsOverSizeLimitWarning = __webpack_require__(52149); +const EntrypointsOverSizeLimitWarning = __webpack_require__(84229); +const NoAsyncChunksWarning = __webpack_require__(17791); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").PerformanceOptions} PerformanceOptions */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Entrypoint")} Entrypoint */ +/** @typedef {import("../WebpackError")} WebpackError */ + +/** + * @typedef {Object} AssetDetails + * @property {string} name + * @property {number} size + */ + +/** + * @typedef {Object} EntrypointDetails + * @property {string} name + * @property {number} size + * @property {string[]} files + */ + +const isOverSizeLimitSet = new WeakSet(); + +const excludeSourceMap = (name, source, info) => !info.development; + +module.exports = class SizeLimitsPlugin { + /** + * @param {PerformanceOptions} options the plugin options + */ + constructor(options) { + this.hints = options.hints; + this.maxAssetSize = options.maxAssetSize; + this.maxEntrypointSize = options.maxEntrypointSize; + this.assetFilter = options.assetFilter; + } + + /** + * @param {ChunkGroup | Source} thing the resource to test + * @returns {boolean} true if over the limit + */ + static isOverSizeLimit(thing) { + return isOverSizeLimitSet.has(thing); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const entrypointSizeLimit = this.maxEntrypointSize; + const assetSizeLimit = this.maxAssetSize; + const hints = this.hints; + const assetFilter = this.assetFilter || excludeSourceMap; + + compiler.hooks.afterEmit.tap("SizeLimitsPlugin", compilation => { + /** @type {WebpackError[]} */ + const warnings = []; + + /** + * @param {Entrypoint} entrypoint an entrypoint + * @returns {number} the size of the entrypoint + */ + const getEntrypointSize = entrypoint => { + let size = 0; + for (const file of entrypoint.getFiles()) { + const asset = compilation.getAsset(file); + if ( + asset && + assetFilter(asset.name, asset.source, asset.info) && + asset.source + ) { + size += asset.info.size || asset.source.size(); + } + } + return size; + }; + + /** @type {AssetDetails[]} */ + const assetsOverSizeLimit = []; + for (const { name, source, info } of compilation.getAssets()) { + if (!assetFilter(name, source, info) || !source) { + continue; + } + + const size = info.size || source.size(); + if (size > assetSizeLimit) { + assetsOverSizeLimit.push({ + name, + size + }); + isOverSizeLimitSet.add(source); + } + } + + const fileFilter = name => { + const asset = compilation.getAsset(name); + return asset && assetFilter(asset.name, asset.source, asset.info); + }; + + /** @type {EntrypointDetails[]} */ + const entrypointsOverLimit = []; + for (const [name, entry] of compilation.entrypoints) { + const size = getEntrypointSize(entry); + + if (size > entrypointSizeLimit) { + entrypointsOverLimit.push({ + name: name, + size: size, + files: entry.getFiles().filter(fileFilter) + }); + isOverSizeLimitSet.add(entry); + } + } + + if (hints) { + // 1. Individual Chunk: Size < 250kb + // 2. Collective Initial Chunks [entrypoint] (Each Set?): Size < 250kb + // 3. No Async Chunks + // if !1, then 2, if !2 return + if (assetsOverSizeLimit.length > 0) { + warnings.push( + new AssetsOverSizeLimitWarning(assetsOverSizeLimit, assetSizeLimit) + ); + } + if (entrypointsOverLimit.length > 0) { + warnings.push( + new EntrypointsOverSizeLimitWarning( + entrypointsOverLimit, + entrypointSizeLimit + ) + ); + } + + if (warnings.length > 0) { + const someAsyncChunk = find( + compilation.chunks, + chunk => !chunk.canBeInitial() + ); + + if (!someAsyncChunk) { + warnings.push(new NoAsyncChunksWarning()); + } + + if (hints === "error") { + compilation.errors.push(...warnings); + } else { + compilation.warnings.push(...warnings); + } + } + } + }); + } +}; + + +/***/ }), + +/***/ 95175: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); + +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +class ChunkPrefetchFunctionRuntimeModule extends RuntimeModule { + /** + * @param {string} childType TODO + * @param {string} runtimeFunction TODO + * @param {string} runtimeHandlers TODO + */ + constructor(childType, runtimeFunction, runtimeHandlers) { + super(`chunk ${childType} function`); + this.childType = childType; + this.runtimeFunction = runtimeFunction; + this.runtimeHandlers = runtimeHandlers; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeFunction, runtimeHandlers } = this; + const { runtimeTemplate } = this.compilation; + return Template.asString([ + `${runtimeHandlers} = {};`, + `${runtimeFunction} = ${runtimeTemplate.basicFunction("chunkId", [ + // map is shorter than forEach + `Object.keys(${runtimeHandlers}).map(${runtimeTemplate.basicFunction( + "key", + `${runtimeHandlers}[key](chunkId);` + )});` + ])}` + ]); + } +} + +module.exports = ChunkPrefetchFunctionRuntimeModule; + + +/***/ }), + +/***/ 33895: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const ChunkPrefetchFunctionRuntimeModule = __webpack_require__(95175); +const ChunkPrefetchStartupRuntimeModule = __webpack_require__(15294); +const ChunkPrefetchTriggerRuntimeModule = __webpack_require__(98441); +const ChunkPreloadTriggerRuntimeModule = __webpack_require__(56236); + +/** @typedef {import("../Compiler")} Compiler */ + +class ChunkPrefetchPreloadPlugin { + /** + * @param {Compiler} compiler the compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "ChunkPrefetchPreloadPlugin", + compilation => { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + "ChunkPrefetchPreloadPlugin", + (chunk, set, { chunkGraph }) => { + if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return; + const startupChildChunks = chunk.getChildrenOfTypeInOrder( + chunkGraph, + "prefetchOrder" + ); + if (startupChildChunks) { + set.add(RuntimeGlobals.prefetchChunk); + set.add(RuntimeGlobals.onChunksLoaded); + compilation.addRuntimeModule( + chunk, + new ChunkPrefetchStartupRuntimeModule(startupChildChunks) + ); + } + } + ); + compilation.hooks.additionalTreeRuntimeRequirements.tap( + "ChunkPrefetchPreloadPlugin", + (chunk, set, { chunkGraph }) => { + const chunkMap = chunk.getChildIdsByOrdersMap(chunkGraph, false); + + if (chunkMap.prefetch) { + set.add(RuntimeGlobals.prefetchChunk); + compilation.addRuntimeModule( + chunk, + new ChunkPrefetchTriggerRuntimeModule(chunkMap.prefetch) + ); + } + if (chunkMap.preload) { + set.add(RuntimeGlobals.preloadChunk); + compilation.addRuntimeModule( + chunk, + new ChunkPreloadTriggerRuntimeModule(chunkMap.preload) + ); + } + } + ); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.prefetchChunk) + .tap("ChunkPrefetchPreloadPlugin", (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new ChunkPrefetchFunctionRuntimeModule( + "prefetch", + RuntimeGlobals.prefetchChunk, + RuntimeGlobals.prefetchChunkHandlers + ) + ); + set.add(RuntimeGlobals.prefetchChunkHandlers); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.preloadChunk) + .tap("ChunkPrefetchPreloadPlugin", (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new ChunkPrefetchFunctionRuntimeModule( + "preload", + RuntimeGlobals.preloadChunk, + RuntimeGlobals.preloadChunkHandlers + ) + ); + set.add(RuntimeGlobals.preloadChunkHandlers); + }); + } + ); + } +} + +module.exports = ChunkPrefetchPreloadPlugin; + + +/***/ }), + +/***/ 15294: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +class ChunkPrefetchStartupRuntimeModule extends RuntimeModule { + /** + * @param {{ onChunks: Chunk[], chunks: Set }[]} startupChunks chunk ids to trigger when chunks are loaded + */ + constructor(startupChunks) { + super("startup prefetch", RuntimeModule.STAGE_TRIGGER); + this.startupChunks = startupChunks; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { startupChunks, chunk } = this; + const { runtimeTemplate } = this.compilation; + return Template.asString( + startupChunks.map( + ({ onChunks, chunks }) => + `${RuntimeGlobals.onChunksLoaded}(0, ${JSON.stringify( + // This need to include itself to delay execution after this chunk has been fully loaded + onChunks.filter(c => c === chunk).map(c => c.id) + )}, ${runtimeTemplate.basicFunction( + "", + chunks.size < 3 + ? Array.from( + chunks, + c => + `${RuntimeGlobals.prefetchChunk}(${JSON.stringify(c.id)});` + ) + : `${JSON.stringify(Array.from(chunks, c => c.id))}.map(${ + RuntimeGlobals.prefetchChunk + });` + )}, 5);` + ) + ); + } +} + +module.exports = ChunkPrefetchStartupRuntimeModule; + + +/***/ }), + +/***/ 98441: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); + +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +class ChunkPrefetchTriggerRuntimeModule extends RuntimeModule { + /** + * @param {Record} chunkMap map from chunk to + */ + constructor(chunkMap) { + super(`chunk prefetch trigger`, RuntimeModule.STAGE_TRIGGER); + this.chunkMap = chunkMap; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { chunkMap } = this; + const { runtimeTemplate } = this.compilation; + const body = [ + "var chunks = chunkToChildrenMap[chunkId];", + `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.prefetchChunk});` + ]; + return Template.asString([ + Template.asString([ + `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, + `${ + RuntimeGlobals.ensureChunkHandlers + }.prefetch = ${runtimeTemplate.expressionFunction( + `Promise.all(promises).then(${runtimeTemplate.basicFunction( + "", + body + )})`, + "chunkId, promises" + )};` + ]) + ]); + } +} + +module.exports = ChunkPrefetchTriggerRuntimeModule; + + +/***/ }), + +/***/ 56236: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); + +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +class ChunkPreloadTriggerRuntimeModule extends RuntimeModule { + /** + * @param {Record} chunkMap map from chunk to chunks + */ + constructor(chunkMap) { + super(`chunk preload trigger`, RuntimeModule.STAGE_TRIGGER); + this.chunkMap = chunkMap; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { chunkMap } = this; + const { runtimeTemplate } = this.compilation; + const body = [ + "var chunks = chunkToChildrenMap[chunkId];", + `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.preloadChunk});` + ]; + return Template.asString([ + Template.asString([ + `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, + `${ + RuntimeGlobals.ensureChunkHandlers + }.preload = ${runtimeTemplate.basicFunction("chunkId", body)};` + ]) + ]); + } +} + +module.exports = ChunkPreloadTriggerRuntimeModule; + + +/***/ }), + +/***/ 30318: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ + +class BasicEffectRulePlugin { + constructor(ruleProperty, effectType) { + this.ruleProperty = ruleProperty; + this.effectType = effectType || ruleProperty; + } + + /** + * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @returns {void} + */ + apply(ruleSetCompiler) { + ruleSetCompiler.hooks.rule.tap( + "BasicEffectRulePlugin", + (path, rule, unhandledProperties, result, references) => { + if (unhandledProperties.has(this.ruleProperty)) { + unhandledProperties.delete(this.ruleProperty); + + const value = rule[this.ruleProperty]; + + result.effects.push({ + type: this.effectType, + value + }); + } + } + ); + } +} + +module.exports = BasicEffectRulePlugin; + + +/***/ }), + +/***/ 94215: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ +/** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */ + +class BasicMatcherRulePlugin { + constructor(ruleProperty, dataProperty, invert) { + this.ruleProperty = ruleProperty; + this.dataProperty = dataProperty || ruleProperty; + this.invert = invert || false; + } + + /** + * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @returns {void} + */ + apply(ruleSetCompiler) { + ruleSetCompiler.hooks.rule.tap( + "BasicMatcherRulePlugin", + (path, rule, unhandledProperties, result) => { + if (unhandledProperties.has(this.ruleProperty)) { + unhandledProperties.delete(this.ruleProperty); + const value = rule[this.ruleProperty]; + const condition = ruleSetCompiler.compileCondition( + `${path}.${this.ruleProperty}`, + value + ); + const fn = condition.fn; + result.conditions.push({ + property: this.dataProperty, + matchWhenEmpty: this.invert + ? !condition.matchWhenEmpty + : condition.matchWhenEmpty, + fn: this.invert ? v => !fn(v) : fn + }); + } + } + ); + } +} + +module.exports = BasicMatcherRulePlugin; + + +/***/ }), + +/***/ 72021: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ +/** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */ + +class ObjectMatcherRulePlugin { + constructor(ruleProperty, dataProperty) { + this.ruleProperty = ruleProperty; + this.dataProperty = dataProperty || ruleProperty; + } + + /** + * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @returns {void} + */ + apply(ruleSetCompiler) { + const { ruleProperty, dataProperty } = this; + ruleSetCompiler.hooks.rule.tap( + "ObjectMatcherRulePlugin", + (path, rule, unhandledProperties, result) => { + if (unhandledProperties.has(ruleProperty)) { + unhandledProperties.delete(ruleProperty); + const value = rule[ruleProperty]; + for (const property of Object.keys(value)) { + const nestedDataProperties = property.split("."); + const condition = ruleSetCompiler.compileCondition( + `${path}.${ruleProperty}.${property}`, + value[property] + ); + result.conditions.push({ + property: [dataProperty, ...nestedDataProperties], + matchWhenEmpty: condition.matchWhenEmpty, + fn: condition.fn + }); + } + } + } + ); + } +} + +module.exports = ObjectMatcherRulePlugin; + + +/***/ }), + +/***/ 83349: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { SyncHook } = __webpack_require__(41242); + +/** + * @typedef {Object} RuleCondition + * @property {string | string[]} property + * @property {boolean} matchWhenEmpty + * @property {function(string): boolean} fn + */ + +/** + * @typedef {Object} Condition + * @property {boolean} matchWhenEmpty + * @property {function(string): boolean} fn + */ + +/** + * @typedef {Object} CompiledRule + * @property {RuleCondition[]} conditions + * @property {(Effect|function(object): Effect[])[]} effects + * @property {CompiledRule[]=} rules + * @property {CompiledRule[]=} oneOf + */ + +/** + * @typedef {Object} Effect + * @property {string} type + * @property {any} value + */ + +/** + * @typedef {Object} RuleSet + * @property {Map} references map of references in the rule set (may grow over time) + * @property {function(object): Effect[]} exec execute the rule set + */ + +class RuleSetCompiler { + constructor(plugins) { + this.hooks = Object.freeze({ + /** @type {SyncHook<[string, object, Set, CompiledRule, Map]>} */ + rule: new SyncHook([ + "path", + "rule", + "unhandledProperties", + "compiledRule", + "references" + ]) + }); + if (plugins) { + for (const plugin of plugins) { + plugin.apply(this); + } + } + } + + /** + * @param {object[]} ruleSet raw user provided rules + * @returns {RuleSet} compiled RuleSet + */ + compile(ruleSet) { + const refs = new Map(); + const rules = this.compileRules("ruleSet", ruleSet, refs); + + /** + * @param {object} data data passed in + * @param {CompiledRule} rule the compiled rule + * @param {Effect[]} effects an array where effects are pushed to + * @returns {boolean} true, if the rule has matched + */ + const execRule = (data, rule, effects) => { + for (const condition of rule.conditions) { + const p = condition.property; + if (Array.isArray(p)) { + let current = data; + for (const subProperty of p) { + if ( + current && + typeof current === "object" && + Object.prototype.hasOwnProperty.call(current, subProperty) + ) { + current = current[subProperty]; + } else { + current = undefined; + break; + } + } + if (current !== undefined) { + if (!condition.fn(current)) return false; + continue; + } + } else if (p in data) { + const value = data[p]; + if (value !== undefined) { + if (!condition.fn(value)) return false; + continue; + } + } + if (!condition.matchWhenEmpty) { + return false; + } + } + for (const effect of rule.effects) { + if (typeof effect === "function") { + const returnedEffects = effect(data); + for (const effect of returnedEffects) { + effects.push(effect); + } + } else { + effects.push(effect); + } + } + if (rule.rules) { + for (const childRule of rule.rules) { + execRule(data, childRule, effects); + } + } + if (rule.oneOf) { + for (const childRule of rule.oneOf) { + if (execRule(data, childRule, effects)) { + break; + } + } + } + return true; + }; + + return { + references: refs, + exec: data => { + /** @type {Effect[]} */ + const effects = []; + for (const rule of rules) { + execRule(data, rule, effects); + } + return effects; + } + }; + } + + /** + * @param {string} path current path + * @param {object[]} rules the raw rules provided by user + * @param {Map} refs references + * @returns {CompiledRule[]} rules + */ + compileRules(path, rules, refs) { + return rules.map((rule, i) => + this.compileRule(`${path}[${i}]`, rule, refs) + ); + } + + /** + * @param {string} path current path + * @param {object} rule the raw rule provided by user + * @param {Map} refs references + * @returns {CompiledRule} normalized and compiled rule for processing + */ + compileRule(path, rule, refs) { + const unhandledProperties = new Set( + Object.keys(rule).filter(key => rule[key] !== undefined) + ); + + /** @type {CompiledRule} */ + const compiledRule = { + conditions: [], + effects: [], + rules: undefined, + oneOf: undefined + }; + + this.hooks.rule.call(path, rule, unhandledProperties, compiledRule, refs); + + if (unhandledProperties.has("rules")) { + unhandledProperties.delete("rules"); + const rules = rule.rules; + if (!Array.isArray(rules)) + throw this.error(path, rules, "Rule.rules must be an array of rules"); + compiledRule.rules = this.compileRules(`${path}.rules`, rules, refs); + } + + if (unhandledProperties.has("oneOf")) { + unhandledProperties.delete("oneOf"); + const oneOf = rule.oneOf; + if (!Array.isArray(oneOf)) + throw this.error(path, oneOf, "Rule.oneOf must be an array of rules"); + compiledRule.oneOf = this.compileRules(`${path}.oneOf`, oneOf, refs); + } + + if (unhandledProperties.size > 0) { + throw this.error( + path, + rule, + `Properties ${Array.from(unhandledProperties).join(", ")} are unknown` + ); + } + + return compiledRule; + } + + /** + * @param {string} path current path + * @param {any} condition user provided condition value + * @returns {Condition} compiled condition + */ + compileCondition(path, condition) { + if (condition === "") { + return { + matchWhenEmpty: true, + fn: str => str === "" + }; + } + if (!condition) { + throw this.error( + path, + condition, + "Expected condition but got falsy value" + ); + } + if (typeof condition === "string") { + return { + matchWhenEmpty: condition.length === 0, + fn: str => typeof str === "string" && str.startsWith(condition) + }; + } + if (typeof condition === "function") { + try { + return { + matchWhenEmpty: condition(""), + fn: condition + }; + } catch (err) { + throw this.error( + path, + condition, + "Evaluation of condition function threw error" + ); + } + } + if (condition instanceof RegExp) { + return { + matchWhenEmpty: condition.test(""), + fn: v => typeof v === "string" && condition.test(v) + }; + } + if (Array.isArray(condition)) { + const items = condition.map((c, i) => + this.compileCondition(`${path}[${i}]`, c) + ); + return this.combineConditionsOr(items); + } + + if (typeof condition !== "object") { + throw this.error( + path, + condition, + `Unexpected ${typeof condition} when condition was expected` + ); + } + + const conditions = []; + for (const key of Object.keys(condition)) { + const value = condition[key]; + switch (key) { + case "or": + if (value) { + if (!Array.isArray(value)) { + throw this.error( + `${path}.or`, + condition.and, + "Expected array of conditions" + ); + } + conditions.push(this.compileCondition(`${path}.or`, value)); + } + break; + case "and": + if (value) { + if (!Array.isArray(value)) { + throw this.error( + `${path}.and`, + condition.and, + "Expected array of conditions" + ); + } + let i = 0; + for (const item of value) { + conditions.push(this.compileCondition(`${path}.and[${i}]`, item)); + i++; + } + } + break; + case "not": + if (value) { + const matcher = this.compileCondition(`${path}.not`, value); + const fn = matcher.fn; + conditions.push({ + matchWhenEmpty: !matcher.matchWhenEmpty, + fn: v => !fn(v) + }); + } + break; + default: + throw this.error( + `${path}.${key}`, + condition[key], + `Unexpected property ${key} in condition` + ); + } + } + if (conditions.length === 0) { + throw this.error( + path, + condition, + "Expected condition, but got empty thing" + ); + } + return this.combineConditionsAnd(conditions); + } + + /** + * @param {Condition[]} conditions some conditions + * @returns {Condition} merged condition + */ + combineConditionsOr(conditions) { + if (conditions.length === 0) { + return { + matchWhenEmpty: false, + fn: () => false + }; + } else if (conditions.length === 1) { + return conditions[0]; + } else { + return { + matchWhenEmpty: conditions.some(c => c.matchWhenEmpty), + fn: v => conditions.some(c => c.fn(v)) + }; + } + } + + /** + * @param {Condition[]} conditions some conditions + * @returns {Condition} merged condition + */ + combineConditionsAnd(conditions) { + if (conditions.length === 0) { + return { + matchWhenEmpty: false, + fn: () => false + }; + } else if (conditions.length === 1) { + return conditions[0]; + } else { + return { + matchWhenEmpty: conditions.every(c => c.matchWhenEmpty), + fn: v => conditions.every(c => c.fn(v)) + }; + } + } + + /** + * @param {string} path current path + * @param {any} value value at the error location + * @param {string} message message explaining the problem + * @returns {Error} an error object + */ + error(path, value, message) { + return new Error( + `Compiling RuleSet failed: ${message} (at ${path}: ${value})` + ); + } +} + +module.exports = RuleSetCompiler; + + +/***/ }), + +/***/ 84977: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const util = __webpack_require__(73837); + +/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ +/** @typedef {import("./RuleSetCompiler").Effect} Effect */ + +class UseEffectRulePlugin { + /** + * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @returns {void} + */ + apply(ruleSetCompiler) { + ruleSetCompiler.hooks.rule.tap( + "UseEffectRulePlugin", + (path, rule, unhandledProperties, result, references) => { + const conflictWith = (property, correctProperty) => { + if (unhandledProperties.has(property)) { + throw ruleSetCompiler.error( + `${path}.${property}`, + rule[property], + `A Rule must not have a '${property}' property when it has a '${correctProperty}' property` + ); + } + }; + + if (unhandledProperties.has("use")) { + unhandledProperties.delete("use"); + unhandledProperties.delete("enforce"); + + conflictWith("loader", "use"); + conflictWith("options", "use"); + + const use = rule.use; + const enforce = rule.enforce; + + const type = enforce ? `use-${enforce}` : "use"; + + /** + * + * @param {string} path options path + * @param {string} defaultIdent default ident when none is provided + * @param {object} item user provided use value + * @returns {Effect|function(any): Effect[]} effect + */ + const useToEffect = (path, defaultIdent, item) => { + if (typeof item === "function") { + return data => useToEffectsWithoutIdent(path, item(data)); + } else { + return useToEffectRaw(path, defaultIdent, item); + } + }; + + /** + * + * @param {string} path options path + * @param {string} defaultIdent default ident when none is provided + * @param {object} item user provided use value + * @returns {Effect} effect + */ + const useToEffectRaw = (path, defaultIdent, item) => { + if (typeof item === "string") { + return { + type, + value: { + loader: item, + options: undefined, + ident: undefined + } + }; + } else { + const loader = item.loader; + const options = item.options; + let ident = item.ident; + if (options && typeof options === "object") { + if (!ident) ident = defaultIdent; + references.set(ident, options); + } + if (typeof options === "string") { + util.deprecate( + () => {}, + `Using a string as loader options is deprecated (${path}.options)`, + "DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING" + )(); + } + return { + type: enforce ? `use-${enforce}` : "use", + value: { + loader, + options, + ident + } + }; + } + }; + + /** + * @param {string} path options path + * @param {any} items user provided use value + * @returns {Effect[]} effects + */ + const useToEffectsWithoutIdent = (path, items) => { + if (Array.isArray(items)) { + return items.map((item, idx) => + useToEffectRaw(`${path}[${idx}]`, "[[missing ident]]", item) + ); + } + return [useToEffectRaw(path, "[[missing ident]]", items)]; + }; + + /** + * @param {string} path current path + * @param {any} items user provided use value + * @returns {(Effect|function(any): Effect[])[]} effects + */ + const useToEffects = (path, items) => { + if (Array.isArray(items)) { + return items.map((item, idx) => { + const subPath = `${path}[${idx}]`; + return useToEffect(subPath, subPath, item); + }); + } + return [useToEffect(path, path, items)]; + }; + + if (typeof use === "function") { + result.effects.push(data => + useToEffectsWithoutIdent(`${path}.use`, use(data)) + ); + } else { + for (const effect of useToEffects(`${path}.use`, use)) { + result.effects.push(effect); + } + } + } + + if (unhandledProperties.has("loader")) { + unhandledProperties.delete("loader"); + unhandledProperties.delete("options"); + unhandledProperties.delete("enforce"); + + const loader = rule.loader; + const options = rule.options; + const enforce = rule.enforce; + + if (loader.includes("!")) { + throw ruleSetCompiler.error( + `${path}.loader`, + loader, + "Exclamation mark separated loader lists has been removed in favor of the 'use' property with arrays" + ); + } + + if (loader.includes("?")) { + throw ruleSetCompiler.error( + `${path}.loader`, + loader, + "Query arguments on 'loader' has been removed in favor of the 'options' property" + ); + } + + if (typeof options === "string") { + util.deprecate( + () => {}, + `Using a string as loader options is deprecated (${path}.options)`, + "DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING" + )(); + } + + const ident = + options && typeof options === "object" ? path : undefined; + references.set(ident, options); + result.effects.push({ + type: enforce ? `use-${enforce}` : "use", + value: { + loader, + options, + ident + } + }); + } + } + ); + } + + useItemToEffects(path, item) {} +} + +module.exports = UseEffectRulePlugin; + + +/***/ }), + +/***/ 63672: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const HelperRuntimeModule = __webpack_require__(82444); + +class AsyncModuleRuntimeModule extends HelperRuntimeModule { + constructor() { + super("async module"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.asyncModule; + return Template.asString([ + 'var webpackThen = typeof Symbol === "function" ? Symbol("webpack then") : "__webpack_then__";', + 'var webpackExports = typeof Symbol === "function" ? Symbol("webpack exports") : "__webpack_exports__";', + `var completeQueue = ${runtimeTemplate.basicFunction("queue", [ + "if(queue) {", + Template.indent([ + `queue.forEach(${runtimeTemplate.expressionFunction( + "fn.r--", + "fn" + )});`, + `queue.forEach(${runtimeTemplate.expressionFunction( + "fn.r-- ? fn.r++ : fn()", + "fn" + )});` + ]), + "}" + ])}`, + `var completeFunction = ${runtimeTemplate.expressionFunction( + "!--fn.r && fn()", + "fn" + )};`, + `var queueFunction = ${runtimeTemplate.expressionFunction( + "queue ? queue.push(fn) : completeFunction(fn)", + "queue, fn" + )};`, + `var wrapDeps = ${runtimeTemplate.returningFunction( + `deps.map(${runtimeTemplate.basicFunction("dep", [ + 'if(dep !== null && typeof dep === "object") {', + Template.indent([ + "if(dep[webpackThen]) return dep;", + "if(dep.then) {", + Template.indent([ + "var queue = [];", + `dep.then(${runtimeTemplate.basicFunction("r", [ + "obj[webpackExports] = r;", + "completeQueue(queue);", + "queue = 0;" + ])});`, + `var obj = {}; + obj[webpackThen] = ${runtimeTemplate.expressionFunction( + "queueFunction(queue, fn), dep['catch'](reject)", + "fn, reject" + )};`, + "return obj;" + ]), + "}" + ]), + "}", + `var ret = {}; + ret[webpackThen] = ${runtimeTemplate.expressionFunction( + "completeFunction(fn)", + "fn" + )}; + ret[webpackExports] = dep; + return ret;` + ])})`, + "deps" + )};`, + `${fn} = ${runtimeTemplate.basicFunction("module, body, hasAwait", [ + "var queue = hasAwait && [];", + "var exports = module.exports;", + "var currentDeps;", + "var outerResolve;", + "var reject;", + "var isEvaluating = true;", + "var nested = false;", + `var whenAll = ${runtimeTemplate.basicFunction( + "deps, onResolve, onReject", + [ + "if (nested) return;", + "nested = true;", + "onResolve.r += deps.length;", + `deps.map(${runtimeTemplate.expressionFunction( + "dep[webpackThen](onResolve, onReject)", + "dep, i" + )});`, + "nested = false;" + ] + )};`, + `var promise = new Promise(${runtimeTemplate.basicFunction( + "resolve, rej", + [ + "reject = rej;", + `outerResolve = ${runtimeTemplate.expressionFunction( + "resolve(exports), completeQueue(queue), queue = 0" + )};` + ] + )});`, + "promise[webpackExports] = exports;", + `promise[webpackThen] = ${runtimeTemplate.basicFunction( + "fn, rejectFn", + [ + "if (isEvaluating) { return completeFunction(fn); }", + "if (currentDeps) whenAll(currentDeps, fn, rejectFn);", + "queueFunction(queue, fn);", + "promise['catch'](rejectFn);" + ] + )};`, + "module.exports = promise;", + `body(${runtimeTemplate.basicFunction("deps", [ + "if(!deps) return outerResolve();", + "currentDeps = wrapDeps(deps);", + "var fn, result;", + `var promise = new Promise(${runtimeTemplate.basicFunction( + "resolve, reject", + [ + `fn = ${runtimeTemplate.expressionFunction( + `resolve(result = currentDeps.map(${runtimeTemplate.returningFunction( + "d[webpackExports]", + "d" + )}))` + )};`, + "fn.r = 0;", + "whenAll(currentDeps, fn, reject);" + ] + )});`, + "return fn.r ? promise : result;" + ])}).then(outerResolve, reject);`, + "isEvaluating = false;" + ])};` + ]); + } +} + +module.exports = AsyncModuleRuntimeModule; + + +/***/ }), + +/***/ 66532: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); +const JavascriptModulesPlugin = __webpack_require__(89464); +const { getUndoPath } = __webpack_require__(82186); + +class AutoPublicPathRuntimeModule extends RuntimeModule { + constructor() { + super("publicPath", RuntimeModule.STAGE_BASIC); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { compilation } = this; + const { scriptType, importMetaName, path } = compilation.outputOptions; + const chunkName = compilation.getPath( + JavascriptModulesPlugin.getChunkFilenameTemplate( + this.chunk, + compilation.outputOptions + ), + { + chunk: this.chunk, + contentHashType: "javascript" + } + ); + const undoPath = getUndoPath(chunkName, path, false); + + return Template.asString([ + "var scriptUrl;", + scriptType === "module" + ? `if (typeof ${importMetaName}.url === "string") scriptUrl = ${importMetaName}.url` + : Template.asString([ + `if (${RuntimeGlobals.global}.importScripts) scriptUrl = ${RuntimeGlobals.global}.location + "";`, + `var document = ${RuntimeGlobals.global}.document;`, + "if (!scriptUrl && document) {", + Template.indent([ + `if (document.currentScript)`, + Template.indent(`scriptUrl = document.currentScript.src`), + "if (!scriptUrl) {", + Template.indent([ + 'var scripts = document.getElementsByTagName("script");', + "if(scripts.length) scriptUrl = scripts[scripts.length - 1].src" + ]), + "}" + ]), + "}" + ]), + "// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration", + '// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.', + 'if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");', + 'scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\\?.*$/, "").replace(/\\/[^\\/]+$/, "/");', + !undoPath + ? `${RuntimeGlobals.publicPath} = scriptUrl;` + : `${RuntimeGlobals.publicPath} = scriptUrl + ${JSON.stringify( + undoPath + )};` + ]); + } +} + +module.exports = AutoPublicPathRuntimeModule; + + +/***/ }), + +/***/ 84519: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); + +class ChunkNameRuntimeModule extends RuntimeModule { + /** + * @param {string} chunkName the chunk's name + */ + constructor(chunkName) { + super("chunkName"); + this.chunkName = chunkName; + } + + /** + * @returns {string} runtime code + */ + generate() { + return `${RuntimeGlobals.chunkName} = ${JSON.stringify(this.chunkName)};`; + } +} + +module.exports = ChunkNameRuntimeModule; + + +/***/ }), + +/***/ 44793: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const HelperRuntimeModule = __webpack_require__(82444); + +class CompatGetDefaultExportRuntimeModule extends HelperRuntimeModule { + constructor() { + super("compat get default export"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.compatGetDefaultExport; + return Template.asString([ + "// getDefaultExport function for compatibility with non-harmony modules", + `${fn} = ${runtimeTemplate.basicFunction("module", [ + "var getter = module && module.__esModule ?", + Template.indent([ + `${runtimeTemplate.returningFunction("module['default']")} :`, + `${runtimeTemplate.returningFunction("module")};` + ]), + `${RuntimeGlobals.definePropertyGetters}(getter, { a: getter });`, + "return getter;" + ])};` + ]); + } +} + +module.exports = CompatGetDefaultExportRuntimeModule; + + +/***/ }), + +/***/ 88234: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); + +/** @typedef {import("../MainTemplate")} MainTemplate */ + +class CompatRuntimeModule extends RuntimeModule { + constructor() { + super("compat", RuntimeModule.STAGE_ATTACH); + this.fullHash = true; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { chunkGraph, chunk, compilation } = this; + const { + runtimeTemplate, + mainTemplate, + moduleTemplates, + dependencyTemplates + } = compilation; + const bootstrap = mainTemplate.hooks.bootstrap.call( + "", + chunk, + compilation.hash || "XXXX", + moduleTemplates.javascript, + dependencyTemplates + ); + const localVars = mainTemplate.hooks.localVars.call( + "", + chunk, + compilation.hash || "XXXX" + ); + const requireExtensions = mainTemplate.hooks.requireExtensions.call( + "", + chunk, + compilation.hash || "XXXX" + ); + const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); + let requireEnsure = ""; + if (runtimeRequirements.has(RuntimeGlobals.ensureChunk)) { + const requireEnsureHandler = mainTemplate.hooks.requireEnsure.call( + "", + chunk, + compilation.hash || "XXXX", + "chunkId" + ); + if (requireEnsureHandler) { + requireEnsure = `${ + RuntimeGlobals.ensureChunkHandlers + }.compat = ${runtimeTemplate.basicFunction( + "chunkId, promises", + requireEnsureHandler + )};`; + } + } + return [bootstrap, localVars, requireEnsure, requireExtensions] + .filter(Boolean) + .join("\n"); + } + + /** + * @returns {boolean} true, if the runtime module should get it's own scope + */ + shouldIsolate() { + // We avoid isolating this to have better backward-compat + return false; + } +} + +module.exports = CompatRuntimeModule; + + +/***/ }), + +/***/ 94669: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const HelperRuntimeModule = __webpack_require__(82444); + +class CreateFakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { + constructor() { + super("create fake namespace object"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.createFakeNamespaceObject; + return Template.asString([ + `var getProto = Object.getPrototypeOf ? ${runtimeTemplate.returningFunction( + "Object.getPrototypeOf(obj)", + "obj" + )} : ${runtimeTemplate.returningFunction("obj.__proto__", "obj")};`, + "var leafPrototypes;", + "// create a fake namespace object", + "// mode & 1: value is a module id, require it", + "// mode & 2: merge all properties of value into the ns", + "// mode & 4: return value when already ns object", + "// mode & 16: return value when it's Promise-like", + "// mode & 8|1: behave like require", + // Note: must be a function (not arrow), because this is used in body! + `${fn} = function(value, mode) {`, + Template.indent([ + `if(mode & 1) value = this(value);`, + `if(mode & 8) return value;`, + "if(typeof value === 'object' && value) {", + Template.indent([ + "if((mode & 4) && value.__esModule) return value;", + "if((mode & 16) && typeof value.then === 'function') return value;" + ]), + "}", + "var ns = Object.create(null);", + `${RuntimeGlobals.makeNamespaceObject}(ns);`, + "var def = {};", + "leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];", + "for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {", + Template.indent([ + `Object.getOwnPropertyNames(current).forEach(${runtimeTemplate.expressionFunction( + `def[key] = ${runtimeTemplate.returningFunction("value[key]", "")}`, + "key" + )});` + ]), + "}", + `def['default'] = ${runtimeTemplate.returningFunction("value", "")};`, + `${RuntimeGlobals.definePropertyGetters}(ns, def);`, + "return ns;" + ]), + "};" + ]); + } +} + +module.exports = CreateFakeNamespaceObjectRuntimeModule; + + +/***/ }), + +/***/ 2759: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const HelperRuntimeModule = __webpack_require__(82444); + +class CreateScriptRuntimeModule extends HelperRuntimeModule { + constructor() { + super("trusted types script"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { compilation } = this; + const { runtimeTemplate, outputOptions } = compilation; + const { trustedTypes } = outputOptions; + const fn = RuntimeGlobals.createScript; + + return Template.asString( + `${fn} = ${runtimeTemplate.returningFunction( + trustedTypes + ? `${RuntimeGlobals.getTrustedTypesPolicy}().createScript(script)` + : "script", + "script" + )};` + ); + } +} + +module.exports = CreateScriptRuntimeModule; + + +/***/ }), + +/***/ 21213: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const HelperRuntimeModule = __webpack_require__(82444); + +class CreateScriptUrlRuntimeModule extends HelperRuntimeModule { + constructor() { + super("trusted types script url"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { compilation } = this; + const { runtimeTemplate, outputOptions } = compilation; + const { trustedTypes } = outputOptions; + const fn = RuntimeGlobals.createScriptUrl; + + return Template.asString( + `${fn} = ${runtimeTemplate.returningFunction( + trustedTypes + ? `${RuntimeGlobals.getTrustedTypesPolicy}().createScriptURL(url)` + : "url", + "url" + )};` + ); + } +} + +module.exports = CreateScriptUrlRuntimeModule; + + +/***/ }), + +/***/ 75481: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const HelperRuntimeModule = __webpack_require__(82444); + +class DefinePropertyGettersRuntimeModule extends HelperRuntimeModule { + constructor() { + super("define property getters"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.definePropertyGetters; + return Template.asString([ + "// define getter functions for harmony exports", + `${fn} = ${runtimeTemplate.basicFunction("exports, definition", [ + `for(var key in definition) {`, + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(definition, key) && !${RuntimeGlobals.hasOwnProperty}(exports, key)) {`, + Template.indent([ + "Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });" + ]), + "}" + ]), + "}" + ])};` + ]); + } +} + +module.exports = DefinePropertyGettersRuntimeModule; + + +/***/ }), + +/***/ 71519: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); + +class EnsureChunkRuntimeModule extends RuntimeModule { + constructor(runtimeRequirements) { + super("ensure chunk"); + this.runtimeRequirements = runtimeRequirements; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + // Check if there are non initial chunks which need to be imported using require-ensure + if (this.runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers)) { + const handlers = RuntimeGlobals.ensureChunkHandlers; + return Template.asString([ + `${handlers} = {};`, + "// This file contains only the entry chunk.", + "// The chunk loading function for additional chunks", + `${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.basicFunction( + "chunkId", + [ + `return Promise.all(Object.keys(${handlers}).reduce(${runtimeTemplate.basicFunction( + "promises, key", + [`${handlers}[key](chunkId, promises);`, "return promises;"] + )}, []));` + ] + )};` + ]); + } else { + // There ensureChunk is used somewhere in the tree, so we need an empty requireEnsure + // function. This can happen with multiple entrypoints. + return Template.asString([ + "// The chunk loading function for additional chunks", + "// Since all referenced chunks are already included", + "// in this file, this function is empty here.", + `${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.returningFunction( + "Promise.resolve()" + )};` + ]); + } + } +} + +module.exports = EnsureChunkRuntimeModule; + + +/***/ }), + +/***/ 34277: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); +const { first } = __webpack_require__(93347); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("../Compilation").PathData} PathData */ + +/** @typedef {function(PathData, AssetInfo=): string} FilenameFunction */ + +class GetChunkFilenameRuntimeModule extends RuntimeModule { + /** + * @param {string} contentType the contentType to use the content hash for + * @param {string} name kind of filename + * @param {string} global function name to be assigned + * @param {function(Chunk): string | FilenameFunction} getFilenameForChunk functor to get the filename or function + * @param {boolean} allChunks when false, only async chunks are included + */ + constructor(contentType, name, global, getFilenameForChunk, allChunks) { + super(`get ${name} chunk filename`); + this.contentType = contentType; + this.global = global; + this.getFilenameForChunk = getFilenameForChunk; + this.allChunks = allChunks; + this.dependentHash = true; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { + global, + chunk, + chunkGraph, + contentType, + getFilenameForChunk, + allChunks, + compilation + } = this; + const { runtimeTemplate } = compilation; + + /** @type {Map>} */ + const chunkFilenames = new Map(); + let maxChunks = 0; + /** @type {string} */ + let dynamicFilename; + + /** + * @param {Chunk} c the chunk + * @returns {void} + */ + const addChunk = c => { + const chunkFilename = getFilenameForChunk(c); + if (chunkFilename) { + let set = chunkFilenames.get(chunkFilename); + if (set === undefined) { + chunkFilenames.set(chunkFilename, (set = new Set())); + } + set.add(c); + if (typeof chunkFilename === "string") { + if (set.size < maxChunks) return; + if (set.size === maxChunks) { + if (chunkFilename.length < dynamicFilename.length) return; + if (chunkFilename.length === dynamicFilename.length) { + if (chunkFilename < dynamicFilename) return; + } + } + maxChunks = set.size; + dynamicFilename = chunkFilename; + } + } + }; + + /** @type {string[]} */ + const includedChunksMessages = []; + if (allChunks) { + includedChunksMessages.push("all chunks"); + for (const c of chunk.getAllReferencedChunks()) { + addChunk(c); + } + } else { + includedChunksMessages.push("async chunks"); + for (const c of chunk.getAllAsyncChunks()) { + addChunk(c); + } + const includeEntries = chunkGraph + .getTreeRuntimeRequirements(chunk) + .has(RuntimeGlobals.ensureChunkIncludeEntries); + if (includeEntries) { + includedChunksMessages.push("sibling chunks for the entrypoint"); + for (const c of chunkGraph.getChunkEntryDependentChunksIterable( + chunk + )) { + addChunk(c); + } + } + } + for (const entrypoint of chunk.getAllReferencedAsyncEntrypoints()) { + addChunk(entrypoint.chunks[entrypoint.chunks.length - 1]); + } + + /** @type {Map>} */ + const staticUrls = new Map(); + /** @type {Set} */ + const dynamicUrlChunks = new Set(); + + /** + * @param {Chunk} c the chunk + * @param {string | FilenameFunction} chunkFilename the filename template for the chunk + * @returns {void} + */ + const addStaticUrl = (c, chunkFilename) => { + /** + * @param {string | number} value a value + * @returns {string} string to put in quotes + */ + const unquotedStringify = value => { + const str = `${value}`; + if (str.length >= 5 && str === `${c.id}`) { + // This is shorter and generates the same result + return '" + chunkId + "'; + } + const s = JSON.stringify(str); + return s.slice(1, s.length - 1); + }; + const unquotedStringifyWithLength = value => length => + unquotedStringify(`${value}`.slice(0, length)); + const chunkFilenameValue = + typeof chunkFilename === "function" + ? JSON.stringify( + chunkFilename({ + chunk: c, + contentHashType: contentType + }) + ) + : JSON.stringify(chunkFilename); + const staticChunkFilename = compilation.getPath(chunkFilenameValue, { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: length => + `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, + chunk: { + id: unquotedStringify(c.id), + hash: unquotedStringify(c.renderedHash), + hashWithLength: unquotedStringifyWithLength(c.renderedHash), + name: unquotedStringify(c.name || c.id), + contentHash: { + [contentType]: unquotedStringify(c.contentHash[contentType]) + }, + contentHashWithLength: { + [contentType]: unquotedStringifyWithLength( + c.contentHash[contentType] + ) + } + }, + contentHashType: contentType + }); + let set = staticUrls.get(staticChunkFilename); + if (set === undefined) { + staticUrls.set(staticChunkFilename, (set = new Set())); + } + set.add(c.id); + }; + + for (const [filename, chunks] of chunkFilenames) { + if (filename !== dynamicFilename) { + for (const c of chunks) addStaticUrl(c, filename); + } else { + for (const c of chunks) dynamicUrlChunks.add(c); + } + } + + /** + * @param {function(Chunk): string | number} fn function from chunk to value + * @returns {string} code with static mapping of results of fn + */ + const createMap = fn => { + const obj = {}; + let useId = false; + let lastKey; + let entries = 0; + for (const c of dynamicUrlChunks) { + const value = fn(c); + if (value === c.id) { + useId = true; + } else { + obj[c.id] = value; + lastKey = c.id; + entries++; + } + } + if (entries === 0) return "chunkId"; + if (entries === 1) { + return useId + ? `(chunkId === ${JSON.stringify(lastKey)} ? ${JSON.stringify( + obj[lastKey] + )} : chunkId)` + : JSON.stringify(obj[lastKey]); + } + return useId + ? `(${JSON.stringify(obj)}[chunkId] || chunkId)` + : `${JSON.stringify(obj)}[chunkId]`; + }; + + /** + * @param {function(Chunk): string | number} fn function from chunk to value + * @returns {string} code with static mapping of results of fn for including in quoted string + */ + const mapExpr = fn => { + return `" + ${createMap(fn)} + "`; + }; + + /** + * @param {function(Chunk): string | number} fn function from chunk to value + * @returns {function(number): string} function which generates code with static mapping of results of fn for including in quoted string for specific length + */ + const mapExprWithLength = fn => length => { + return `" + ${createMap(c => `${fn(c)}`.slice(0, length))} + "`; + }; + + const url = + dynamicFilename && + compilation.getPath(JSON.stringify(dynamicFilename), { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: length => + `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, + chunk: { + id: `" + chunkId + "`, + hash: mapExpr(c => c.renderedHash), + hashWithLength: mapExprWithLength(c => c.renderedHash), + name: mapExpr(c => c.name || c.id), + contentHash: { + [contentType]: mapExpr(c => c.contentHash[contentType]) + }, + contentHashWithLength: { + [contentType]: mapExprWithLength(c => c.contentHash[contentType]) + } + }, + contentHashType: contentType + }); + + return Template.asString([ + `// This function allow to reference ${includedChunksMessages.join( + " and " + )}`, + `${global} = ${runtimeTemplate.basicFunction( + "chunkId", + + staticUrls.size > 0 + ? [ + "// return url for filenames not based on template", + // it minimizes to `x===1?"...":x===2?"...":"..."` + Template.asString( + Array.from(staticUrls, ([url, ids]) => { + const condition = + ids.size === 1 + ? `chunkId === ${JSON.stringify(first(ids))}` + : `{${Array.from( + ids, + id => `${JSON.stringify(id)}:1` + ).join(",")}}[chunkId]`; + return `if (${condition}) return ${url};`; + }) + ), + "// return url for filenames based on template", + `return ${url};` + ] + : ["// return url for filenames based on template", `return ${url};`] + )};` + ]); + } +} + +module.exports = GetChunkFilenameRuntimeModule; + + +/***/ }), + +/***/ 88732: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); + +/** @typedef {import("../Compilation")} Compilation */ + +class GetFullHashRuntimeModule extends RuntimeModule { + constructor() { + super("getFullHash"); + this.fullHash = true; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + return `${RuntimeGlobals.getFullHash} = ${runtimeTemplate.returningFunction( + JSON.stringify(this.compilation.hash || "XXXX") + )}`; + } +} + +module.exports = GetFullHashRuntimeModule; + + +/***/ }), + +/***/ 10029: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); + +/** @typedef {import("../Compilation")} Compilation */ + +class GetMainFilenameRuntimeModule extends RuntimeModule { + /** + * @param {string} name readable name + * @param {string} global global object binding + * @param {string} filename main file name + */ + constructor(name, global, filename) { + super(`get ${name} filename`); + this.global = global; + this.filename = filename; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { global, filename, compilation, chunk } = this; + const { runtimeTemplate } = compilation; + const url = compilation.getPath(JSON.stringify(filename), { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: length => + `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, + chunk, + runtime: chunk.runtime + }); + return Template.asString([ + `${global} = ${runtimeTemplate.returningFunction(url)};` + ]); + } +} + +module.exports = GetMainFilenameRuntimeModule; + + +/***/ }), + +/***/ 38713: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const HelperRuntimeModule = __webpack_require__(82444); + +class GetTrustedTypesPolicyRuntimeModule extends HelperRuntimeModule { + /** + * @param {Set} runtimeRequirements runtime requirements + */ + constructor(runtimeRequirements) { + super("trusted types policy"); + this.runtimeRequirements = runtimeRequirements; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { compilation } = this; + const { runtimeTemplate, outputOptions } = compilation; + const { trustedTypes } = outputOptions; + const fn = RuntimeGlobals.getTrustedTypesPolicy; + + return Template.asString([ + "var policy;", + `${fn} = ${runtimeTemplate.basicFunction("", [ + "// Create Trusted Type policy if Trusted Types are available and the policy doesn't exist yet.", + "if (policy === undefined) {", + Template.indent([ + "policy = {", + Template.indent( + [ + ...(this.runtimeRequirements.has(RuntimeGlobals.createScript) + ? [ + `createScript: ${runtimeTemplate.returningFunction( + "script", + "script" + )}` + ] + : []), + ...(this.runtimeRequirements.has(RuntimeGlobals.createScriptUrl) + ? [ + `createScriptURL: ${runtimeTemplate.returningFunction( + "url", + "url" + )}` + ] + : []) + ].join(",\n") + ), + "};", + ...(trustedTypes + ? [ + 'if (typeof trustedTypes !== "undefined" && trustedTypes.createPolicy) {', + Template.indent([ + `policy = trustedTypes.createPolicy(${JSON.stringify( + trustedTypes.policyName + )}, policy);` + ]), + "}" + ] + : []) + ]), + "}", + "return policy;" + ])};` + ]); + } +} + +module.exports = GetTrustedTypesPolicyRuntimeModule; + + +/***/ }), + +/***/ 23255: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); + +class GlobalRuntimeModule extends RuntimeModule { + constructor() { + super("global"); + } + + /** + * @returns {string} runtime code + */ + generate() { + return Template.asString([ + `${RuntimeGlobals.global} = (function() {`, + Template.indent([ + "if (typeof globalThis === 'object') return globalThis;", + "try {", + Template.indent( + // This works in non-strict mode + // or + // This works if eval is allowed (see CSP) + "return this || new Function('return this')();" + ), + "} catch (e) {", + Template.indent( + // This works if the window reference is available + "if (typeof window === 'object') return window;" + ), + "}" + // It can still be `undefined`, but nothing to do about it... + // We return `undefined`, instead of nothing here, so it's + // easier to handle this case: + // if (!global) { … } + ]), + "})();" + ]); + } +} + +module.exports = GlobalRuntimeModule; + + +/***/ }), + +/***/ 8011: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); + +class HasOwnPropertyRuntimeModule extends RuntimeModule { + constructor() { + super("hasOwnProperty shorthand"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + + return Template.asString([ + `${RuntimeGlobals.hasOwnProperty} = ${runtimeTemplate.returningFunction( + "Object.prototype.hasOwnProperty.call(obj, prop)", + "obj, prop" + )}` + ]); + } +} + +module.exports = HasOwnPropertyRuntimeModule; + + +/***/ }), + +/***/ 82444: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeModule = __webpack_require__(16963); + +class HelperRuntimeModule extends RuntimeModule { + /** + * @param {string} name a readable name + */ + constructor(name) { + super(name); + } +} + +module.exports = HelperRuntimeModule; + + +/***/ }), + +/***/ 19942: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const { SyncWaterfallHook } = __webpack_require__(41242); +const Compilation = __webpack_require__(85720); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const HelperRuntimeModule = __webpack_require__(82444); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +/** + * @typedef {Object} LoadScriptCompilationHooks + * @property {SyncWaterfallHook<[string, Chunk]>} createScript + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class LoadScriptRuntimeModule extends HelperRuntimeModule { + /** + * @param {Compilation} compilation the compilation + * @returns {LoadScriptCompilationHooks} 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 = { + createScript: new SyncWaterfallHook(["source", "chunk"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + /** + * @param {boolean=} withCreateScriptUrl use create script url for trusted types + */ + constructor(withCreateScriptUrl) { + super("load script"); + this._withCreateScriptUrl = withCreateScriptUrl; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { compilation } = this; + const { runtimeTemplate, outputOptions } = compilation; + const { + scriptType, + chunkLoadTimeout: loadTimeout, + crossOriginLoading, + uniqueName, + charset + } = outputOptions; + const fn = RuntimeGlobals.loadScript; + + const { createScript } = + LoadScriptRuntimeModule.getCompilationHooks(compilation); + + const code = Template.asString([ + "script = document.createElement('script');", + scriptType ? `script.type = ${JSON.stringify(scriptType)};` : "", + charset ? "script.charset = 'utf-8';" : "", + `script.timeout = ${loadTimeout / 1000};`, + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `script.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + uniqueName + ? 'script.setAttribute("data-webpack", dataWebpackPrefix + key);' + : "", + `script.src = ${ + this._withCreateScriptUrl + ? `${RuntimeGlobals.createScriptUrl}(url)` + : "url" + };`, + crossOriginLoading + ? Template.asString([ + "if (script.src.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` + ), + "}" + ]) + : "" + ]); + + return Template.asString([ + "var inProgress = {};", + uniqueName + ? `var dataWebpackPrefix = ${JSON.stringify(uniqueName + ":")};` + : "// data-webpack is not used as build has no uniqueName", + "// loadScript function to load a script via script tag", + `${fn} = ${runtimeTemplate.basicFunction("url, done, key, chunkId", [ + "if(inProgress[url]) { inProgress[url].push(done); return; }", + "var script, needAttach;", + "if(key !== undefined) {", + Template.indent([ + 'var scripts = document.getElementsByTagName("script");', + "for(var i = 0; i < scripts.length; i++) {", + Template.indent([ + "var s = scripts[i];", + `if(s.getAttribute("src") == url${ + uniqueName + ? ' || s.getAttribute("data-webpack") == dataWebpackPrefix + key' + : "" + }) { script = s; break; }` + ]), + "}" + ]), + "}", + "if(!script) {", + Template.indent([ + "needAttach = true;", + createScript.call(code, this.chunk) + ]), + "}", + "inProgress[url] = [done];", + "var onScriptComplete = " + + runtimeTemplate.basicFunction( + "prev, event", + Template.asString([ + "// avoid mem leaks in IE.", + "script.onerror = script.onload = null;", + "clearTimeout(timeout);", + "var doneFns = inProgress[url];", + "delete inProgress[url];", + "script.parentNode && script.parentNode.removeChild(script);", + `doneFns && doneFns.forEach(${runtimeTemplate.returningFunction( + "fn(event)", + "fn" + )});`, + "if(prev) return prev(event);" + ]) + ), + ";", + `var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), ${loadTimeout});`, + "script.onerror = onScriptComplete.bind(null, script.onerror);", + "script.onload = onScriptComplete.bind(null, script.onload);", + "needAttach && document.head.appendChild(script);" + ])};` + ]); + } +} + +module.exports = LoadScriptRuntimeModule; + + +/***/ }), + +/***/ 65714: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const HelperRuntimeModule = __webpack_require__(82444); + +class MakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { + constructor() { + super("make namespace object"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.makeNamespaceObject; + return Template.asString([ + "// define __esModule on exports", + `${fn} = ${runtimeTemplate.basicFunction("exports", [ + "if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {", + Template.indent([ + "Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });" + ]), + "}", + "Object.defineProperty(exports, '__esModule', { value: true });" + ])};` + ]); + } +} + +module.exports = MakeNamespaceObjectRuntimeModule; + + +/***/ }), + +/***/ 44518: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); + +class OnChunksLoadedRuntimeModule extends RuntimeModule { + constructor() { + super("chunk loaded"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { compilation } = this; + const { runtimeTemplate } = compilation; + return Template.asString([ + "var deferred = [];", + `${RuntimeGlobals.onChunksLoaded} = ${runtimeTemplate.basicFunction( + "result, chunkIds, fn, priority", + [ + "if(chunkIds) {", + Template.indent([ + "priority = priority || 0;", + "for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];", + "deferred[i] = [chunkIds, fn, priority];", + "return;" + ]), + "}", + "var notFulfilled = Infinity;", + "for (var i = 0; i < deferred.length; i++) {", + Template.indent([ + runtimeTemplate.destructureArray( + ["chunkIds", "fn", "priority"], + "deferred[i]" + ), + "var fulfilled = true;", + "for (var j = 0; j < chunkIds.length; j++) {", + Template.indent([ + `if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(${ + RuntimeGlobals.onChunksLoaded + }).every(${runtimeTemplate.returningFunction( + `${RuntimeGlobals.onChunksLoaded}[key](chunkIds[j])`, + "key" + )})) {`, + Template.indent(["chunkIds.splice(j--, 1);"]), + "} else {", + Template.indent([ + "fulfilled = false;", + "if(priority < notFulfilled) notFulfilled = priority;" + ]), + "}" + ]), + "}", + "if(fulfilled) {", + Template.indent([ + "deferred.splice(i--, 1)", + "var r = fn();", + "if (r !== undefined) result = r;" + ]), + "}" + ]), + "}", + "return result;" + ] + )};` + ]); + } +} + +module.exports = OnChunksLoadedRuntimeModule; + + +/***/ }), + +/***/ 56030: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); + +class PublicPathRuntimeModule extends RuntimeModule { + constructor(publicPath) { + super("publicPath", RuntimeModule.STAGE_BASIC); + this.publicPath = publicPath; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { compilation, publicPath } = this; + + return `${RuntimeGlobals.publicPath} = ${JSON.stringify( + compilation.getPath(publicPath || "", { + hash: compilation.hash || "XXXX" + }) + )};`; + } +} + +module.exports = PublicPathRuntimeModule; + + +/***/ }), + +/***/ 4537: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const HelperRuntimeModule = __webpack_require__(82444); + +class RelativeUrlRuntimeModule extends HelperRuntimeModule { + constructor() { + super("relative url"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + return Template.asString([ + `${RuntimeGlobals.relativeUrl} = function RelativeURL(url) {`, + Template.indent([ + 'var realUrl = new URL(url, "x:/");', + "var values = {};", + "for (var key in realUrl) values[key] = realUrl[key];", + "values.href = url;", + 'values.pathname = url.replace(/[?#].*/, "");', + 'values.origin = values.protocol = "";', + `values.toString = values.toJSON = ${runtimeTemplate.returningFunction( + "url" + )};`, + "for (var key in values) Object.defineProperty(this, key, { enumerable: true, configurable: true, value: values[key] });" + ]), + "};", + `${RuntimeGlobals.relativeUrl}.prototype = URL.prototype;` + ]); + } +} + +module.exports = RelativeUrlRuntimeModule; + + +/***/ }), + +/***/ 97115: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); + +class RuntimeIdRuntimeModule extends RuntimeModule { + constructor() { + super("runtimeId"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { chunkGraph, chunk } = this; + const runtime = chunk.runtime; + if (typeof runtime !== "string") + throw new Error("RuntimeIdRuntimeModule must be in a single runtime"); + const id = chunkGraph.getRuntimeId(runtime); + return `${RuntimeGlobals.runtimeId} = ${JSON.stringify(id)};`; + } +} + +module.exports = RuntimeIdRuntimeModule; + + +/***/ }), + +/***/ 22339: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const StartupChunkDependenciesRuntimeModule = __webpack_require__(38157); +const StartupEntrypointRuntimeModule = __webpack_require__(97672); + +/** @typedef {import("../Compiler")} Compiler */ + +class StartupChunkDependenciesPlugin { + constructor(options) { + this.chunkLoading = options.chunkLoading; + this.asyncChunkLoading = + typeof options.asyncChunkLoading === "boolean" + ? options.asyncChunkLoading + : true; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "StartupChunkDependenciesPlugin", + compilation => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === this.chunkLoading; + }; + compilation.hooks.additionalTreeRuntimeRequirements.tap( + "StartupChunkDependenciesPlugin", + (chunk, set, { chunkGraph }) => { + if (!isEnabledForChunk(chunk)) return; + if (chunkGraph.hasChunkEntryDependentChunks(chunk)) { + set.add(RuntimeGlobals.startup); + set.add(RuntimeGlobals.ensureChunk); + set.add(RuntimeGlobals.ensureChunkIncludeEntries); + compilation.addRuntimeModule( + chunk, + new StartupChunkDependenciesRuntimeModule( + this.asyncChunkLoading + ) + ); + } + } + ); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.startupEntrypoint) + .tap("StartupChunkDependenciesPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.require); + set.add(RuntimeGlobals.ensureChunk); + set.add(RuntimeGlobals.ensureChunkIncludeEntries); + compilation.addRuntimeModule( + chunk, + new StartupEntrypointRuntimeModule(this.asyncChunkLoading) + ); + }); + } + ); + } +} + +module.exports = StartupChunkDependenciesPlugin; + + +/***/ }), + +/***/ 38157: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); + +class StartupChunkDependenciesRuntimeModule extends RuntimeModule { + constructor(asyncChunkLoading) { + super("startup chunk dependencies", RuntimeModule.STAGE_TRIGGER); + this.asyncChunkLoading = asyncChunkLoading; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { chunkGraph, chunk, compilation } = this; + const { runtimeTemplate } = compilation; + const chunkIds = Array.from( + chunkGraph.getChunkEntryDependentChunksIterable(chunk) + ).map(chunk => { + return chunk.id; + }); + return Template.asString([ + `var next = ${RuntimeGlobals.startup};`, + `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction( + "", + !this.asyncChunkLoading + ? chunkIds + .map( + id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)});` + ) + .concat("return next();") + : chunkIds.length === 1 + ? `return ${RuntimeGlobals.ensureChunk}(${JSON.stringify( + chunkIds[0] + )}).then(next);` + : chunkIds.length > 2 + ? [ + // using map is shorter for 3 or more chunks + `return Promise.all(${JSON.stringify(chunkIds)}.map(${ + RuntimeGlobals.ensureChunk + }, __webpack_require__)).then(next);` + ] + : [ + // calling ensureChunk directly is shorter for 0 - 2 chunks + "return Promise.all([", + Template.indent( + chunkIds + .map( + id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)})` + ) + .join(",\n") + ), + "]).then(next);" + ] + )};` + ]); + } +} + +module.exports = StartupChunkDependenciesRuntimeModule; + + +/***/ }), + +/***/ 97672: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); + +/** @typedef {import("../MainTemplate")} MainTemplate */ + +class StartupEntrypointRuntimeModule extends RuntimeModule { + constructor(asyncChunkLoading) { + super("startup entrypoint"); + this.asyncChunkLoading = asyncChunkLoading; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { compilation } = this; + const { runtimeTemplate } = compilation; + return `${ + RuntimeGlobals.startupEntrypoint + } = ${runtimeTemplate.basicFunction("result, chunkIds, fn", [ + "// arguments: chunkIds, moduleId are deprecated", + "var moduleId = chunkIds;", + `if(!fn) chunkIds = result, fn = ${runtimeTemplate.returningFunction( + `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)` + )};`, + ...(this.asyncChunkLoading + ? [ + `return Promise.all(chunkIds.map(${ + RuntimeGlobals.ensureChunk + }, __webpack_require__)).then(${runtimeTemplate.basicFunction("", [ + "var r = fn();", + "return r === undefined ? result : r;" + ])})` + ] + : [ + `chunkIds.map(${RuntimeGlobals.ensureChunk}, __webpack_require__)`, + "var r = fn();", + "return r === undefined ? result : r;" + ]) + ])}`; + } +} + +module.exports = StartupEntrypointRuntimeModule; + + +/***/ }), + +/***/ 80655: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); + +/** @typedef {import("../Compilation")} Compilation */ + +class SystemContextRuntimeModule extends RuntimeModule { + constructor() { + super("__system_context__"); + } + + /** + * @returns {string} runtime code + */ + generate() { + return `${RuntimeGlobals.systemContext} = __system_context__;`; + } +} + +module.exports = SystemContextRuntimeModule; + + +/***/ }), + +/***/ 64820: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const NormalModule = __webpack_require__(39); + +/** @typedef {import("../Compiler")} Compiler */ + +// data URL scheme: "data:text/javascript;charset=utf-8;base64,some-string" +// http://www.ietf.org/rfc/rfc2397.txt +const URIRegEx = /^data:([^;,]+)?((?:;[^;,]+)*?)(?:;(base64))?,(.*)$/i; + +const decodeDataURI = uri => { + const match = URIRegEx.exec(uri); + if (!match) return null; + + const isBase64 = match[3]; + const body = match[4]; + return isBase64 + ? Buffer.from(body, "base64") + : Buffer.from(decodeURIComponent(body), "ascii"); +}; + +class DataUriPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "DataUriPlugin", + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.resolveForScheme + .for("data") + .tap("DataUriPlugin", resourceData => { + const match = URIRegEx.exec(resourceData.resource); + if (match) { + resourceData.data.mimetype = match[1] || ""; + resourceData.data.parameters = match[2] || ""; + resourceData.data.encoding = match[3] || false; + resourceData.data.encodedContent = match[4] || ""; + } + }); + NormalModule.getCompilationHooks(compilation) + .readResourceForScheme.for("data") + .tap("DataUriPlugin", resource => decodeDataURI(resource)); + } + ); + } +} + +module.exports = DataUriPlugin; + + +/***/ }), + +/***/ 57637: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { URL, fileURLToPath } = __webpack_require__(57310); +const { NormalModule } = __webpack_require__(91919); + +/** @typedef {import("../Compiler")} Compiler */ + +class FileUriPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "FileUriPlugin", + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.resolveForScheme + .for("file") + .tap("FileUriPlugin", resourceData => { + const url = new URL(resourceData.resource); + const path = fileURLToPath(url); + const query = url.search; + const fragment = url.hash; + resourceData.path = path; + resourceData.query = query; + resourceData.fragment = fragment; + resourceData.resource = path + query + fragment; + return true; + }); + const hooks = NormalModule.getCompilationHooks(compilation); + hooks.readResource + .for(undefined) + .tapAsync("FileUriPlugin", (loaderContext, callback) => { + const { resourcePath } = loaderContext; + loaderContext.addDependency(resourcePath); + loaderContext.fs.readFile(resourcePath, callback); + }); + } + ); + } +} + +module.exports = FileUriPlugin; + + +/***/ }), + +/***/ 42110: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { extname, basename } = __webpack_require__(71017); +const { URL } = __webpack_require__(57310); +const { createGunzip, createBrotliDecompress, createInflate } = __webpack_require__(59796); +const NormalModule = __webpack_require__(39); +const createSchemaValidation = __webpack_require__(32540); +const createHash = __webpack_require__(49835); +const { mkdirp, dirname, join } = __webpack_require__(17139); +const memoize = __webpack_require__(78676); + +/** @typedef {import("../../declarations/plugins/schemes/HttpUriPlugin").HttpUriPluginOptions} HttpUriPluginOptions */ +/** @typedef {import("../Compiler")} Compiler */ + +const getHttp = memoize(() => __webpack_require__(13685)); +const getHttps = memoize(() => __webpack_require__(95687)); + +/** @type {(() => void)[] | undefined} */ +let inProgressWrite = undefined; + +const validate = createSchemaValidation( + __webpack_require__(67263), + () => __webpack_require__(27256), + { + name: "Http Uri Plugin", + baseDataPath: "options" + } +); + +const toSafePath = str => + str + .replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, "") + .replace(/[^a-zA-Z0-9._-]+/g, "_"); + +const computeIntegrity = content => { + const hash = createHash("sha512"); + hash.update(content); + const integrity = "sha512-" + hash.digest("base64"); + return integrity; +}; + +const verifyIntegrity = (content, integrity) => { + if (integrity === "ignore") return true; + return computeIntegrity(content) === integrity; +}; + +/** + * @param {string} str input + * @returns {Record} parsed + */ +const parseKeyValuePairs = str => { + /** @type {Record} */ + const result = {}; + for (const item of str.split(",")) { + const i = item.indexOf("="); + if (i >= 0) { + const key = item.slice(0, i).trim(); + const value = item.slice(i + 1).trim(); + result[key] = value; + } else { + const key = item.trim(); + if (!key) continue; + result[key] = key; + } + } + return result; +}; + +const parseCacheControl = (cacheControl, requestTime) => { + // When false resource is not stored in cache + let storeCache = true; + // When false resource is not stored in lockfile cache + let storeLock = true; + // Resource is only revalidated, after that timestamp and when upgrade is chosen + let validUntil = 0; + if (cacheControl) { + const parsed = parseKeyValuePairs(cacheControl); + if (parsed["no-cache"]) storeCache = storeLock = false; + if (parsed["max-age"] && !isNaN(+parsed["max-age"])) { + validUntil = requestTime + +parsed["max-age"] * 1000; } - if (groupModulesByCacheStatus) { - groupByFlag("cacheable", "cacheable modules"); - groupByFlag("built", "built modules"); - groupByFlag("codeGenerated", "code generated modules"); + if (parsed["must-revalidate"]) validUntil = 0; + } + return { + storeLock, + storeCache, + validUntil + }; +}; + +/** + * @typedef {Object} LockfileEntry + * @property {string} resolved + * @property {string} integrity + * @property {string} contentType + */ + +const areLockfileEntriesEqual = (a, b) => { + return ( + a.resolved === b.resolved && + a.integrity === b.integrity && + a.contentType === b.contentType + ); +}; + +const entryToString = entry => { + return `resolved: ${entry.resolved}, integrity: ${entry.integrity}, contentType: ${entry.contentType}`; +}; + +class Lockfile { + constructor() { + this.version = 1; + /** @type {Map} */ + this.entries = new Map(); + } + + static parse(content) { + // TODO handle merge conflicts + const data = JSON.parse(content); + if (data.version !== 1) + throw new Error(`Unsupported lockfile version ${data.version}`); + const lockfile = new Lockfile(); + for (const key of Object.keys(data)) { + if (key === "version") continue; + const entry = data[key]; + lockfile.entries.set( + key, + typeof entry === "string" + ? entry + : { + resolved: key, + ...entry + } + ); } - if (groupModulesByCacheStatus || !options.cachedModules) { - groupByFlag("cached", "cached modules", !options.cachedModules); + return lockfile; + } + + toString() { + let str = "{\n"; + const entries = Array.from(this.entries).sort(([a], [b]) => + a < b ? -1 : 1 + ); + for (const [key, entry] of entries) { + if (typeof entry === "string") { + str += ` ${JSON.stringify(key)}: ${JSON.stringify(entry)},\n`; + } else { + str += ` ${JSON.stringify(key)}: { `; + if (entry.resolved !== key) + str += `"resolved": ${JSON.stringify(entry.resolved)}, `; + str += `"integrity": ${JSON.stringify( + entry.integrity + )}, "contentType": ${JSON.stringify(entry.contentType)} },\n`; + } } - if (groupModulesByAttributes || !options.orphanModules) { - groupByFlag("orphan", "orphan modules", !options.orphanModules); + str += ` "version": ${this.version}\n}\n`; + return str; + } +} + +/** + * @template R + * @param {function(function(Error=, R=): void): void} fn function + * @returns {function(function((Error | null)=, R=): void): void} cached function + */ +const cachedWithoutKey = fn => { + let inFlight = false; + /** @type {Error | undefined} */ + let cachedError = undefined; + /** @type {R | undefined} */ + let cachedResult = undefined; + /** @type {(function(Error=, R=): void)[] | undefined} */ + let cachedCallbacks = undefined; + return callback => { + if (inFlight) { + if (cachedResult !== undefined) return callback(null, cachedResult); + if (cachedError !== undefined) return callback(cachedError); + if (cachedCallbacks === undefined) cachedCallbacks = [callback]; + else cachedCallbacks.push(callback); + return; } - if (groupModulesByAttributes || !options.dependentModules) { - groupByFlag("dependent", "dependent modules", !options.dependentModules); + inFlight = true; + fn((err, result) => { + if (err) cachedError = err; + else cachedResult = result; + const callbacks = cachedCallbacks; + cachedCallbacks = undefined; + callback(err, result); + if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); + }); + }; +}; + +/** + * @template T + * @template R + * @param {function(T, function(Error=, R=): void): void} fn function + * @param {function(T, function(Error=, R=): void): void=} forceFn function for the second try + * @returns {(function(T, function((Error | null)=, R=): void): void) & { force: function(T, function((Error | null)=, R=): void): void }} cached function + */ +const cachedWithKey = (fn, forceFn = fn) => { + /** @typedef {{ result?: R, error?: Error, callbacks?: (function((Error | null)=, R=): void)[], force?: true }} CacheEntry */ + /** @type {Map} */ + const cache = new Map(); + const resultFn = (arg, callback) => { + const cacheEntry = cache.get(arg); + if (cacheEntry !== undefined) { + if (cacheEntry.result !== undefined) + return callback(null, cacheEntry.result); + if (cacheEntry.error !== undefined) return callback(cacheEntry.error); + if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback]; + else cacheEntry.callbacks.push(callback); + return; } - if (groupModulesByType || !options.runtimeModules) { - groupConfigs.push({ - getKeys: module => { - if (!module.moduleType) return; - if (groupModulesByType) { - return [module.moduleType.split("/", 1)[0]]; - } else if (module.moduleType === "runtime") { - return ["runtime"]; + /** @type {CacheEntry} */ + const newCacheEntry = { + result: undefined, + error: undefined, + callbacks: undefined + }; + cache.set(arg, newCacheEntry); + fn(arg, (err, result) => { + if (err) newCacheEntry.error = err; + else newCacheEntry.result = result; + const callbacks = newCacheEntry.callbacks; + newCacheEntry.callbacks = undefined; + callback(err, result); + if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); + }); + }; + resultFn.force = (arg, callback) => { + const cacheEntry = cache.get(arg); + if (cacheEntry !== undefined && cacheEntry.force) { + if (cacheEntry.result !== undefined) + return callback(null, cacheEntry.result); + if (cacheEntry.error !== undefined) return callback(cacheEntry.error); + if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback]; + else cacheEntry.callbacks.push(callback); + return; + } + /** @type {CacheEntry} */ + const newCacheEntry = { + result: undefined, + error: undefined, + callbacks: undefined, + force: true + }; + cache.set(arg, newCacheEntry); + forceFn(arg, (err, result) => { + if (err) newCacheEntry.error = err; + else newCacheEntry.result = result; + const callbacks = newCacheEntry.callbacks; + newCacheEntry.callbacks = undefined; + callback(err, result); + if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); + }); + }; + return resultFn; +}; + +class HttpUriPlugin { + /** + * @param {HttpUriPluginOptions} options options + */ + constructor(options) { + validate(options); + this._lockfileLocation = options.lockfileLocation; + this._cacheLocation = options.cacheLocation; + this._upgrade = options.upgrade; + this._frozen = options.frozen; + this._allowedUris = options.allowedUris; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const schemes = [ + { + scheme: "http", + fetch: (url, options, callback) => getHttp().get(url, options, callback) + }, + { + scheme: "https", + fetch: (url, options, callback) => + getHttps().get(url, options, callback) + } + ]; + let lockfileCache; + compiler.hooks.compilation.tap( + "HttpUriPlugin", + (compilation, { normalModuleFactory }) => { + const intermediateFs = compiler.intermediateFileSystem; + const fs = compilation.inputFileSystem; + const cache = compilation.getCache("webpack.HttpUriPlugin"); + const logger = compilation.getLogger("webpack.HttpUriPlugin"); + const lockfileLocation = + this._lockfileLocation || + join( + intermediateFs, + compiler.context, + compiler.name + ? `${toSafePath(compiler.name)}.webpack.lock` + : "webpack.lock" + ); + const cacheLocation = + this._cacheLocation !== undefined + ? this._cacheLocation + : lockfileLocation + ".data"; + const upgrade = this._upgrade || false; + const frozen = this._frozen || false; + const hashFunction = "sha512"; + const hashDigest = "hex"; + const hashDigestLength = 20; + const allowedUris = this._allowedUris; + + let warnedAboutEol = false; + + const cacheKeyCache = new Map(); + /** + * @param {string} url the url + * @returns {string} the key + */ + const getCacheKey = url => { + const cachedResult = cacheKeyCache.get(url); + if (cachedResult !== undefined) return cachedResult; + const result = _getCacheKey(url); + cacheKeyCache.set(url, result); + return result; + }; + + /** + * @param {string} url the url + * @returns {string} the key + */ + const _getCacheKey = url => { + const parsedUrl = new URL(url); + const folder = toSafePath(parsedUrl.origin); + const name = toSafePath(parsedUrl.pathname); + const query = toSafePath(parsedUrl.search); + let ext = extname(name); + if (ext.length > 20) ext = ""; + const basename = ext ? name.slice(0, -ext.length) : name; + const hash = createHash(hashFunction); + hash.update(url); + const digest = hash.digest(hashDigest).slice(0, hashDigestLength); + return `${folder.slice(-50)}/${`${basename}${ + query ? `_${query}` : "" + }`.slice(0, 150)}_${digest}${ext}`; + }; + + const getLockfile = cachedWithoutKey( + /** + * @param {function((Error | null)=, Lockfile=): void} callback callback + * @returns {void} + */ + callback => { + const readLockfile = () => { + intermediateFs.readFile(lockfileLocation, (err, buffer) => { + if (err && err.code !== "ENOENT") { + compilation.missingDependencies.add(lockfileLocation); + return callback(err); + } + compilation.fileDependencies.add(lockfileLocation); + compilation.fileSystemInfo.createSnapshot( + compiler.fsStartTime, + buffer ? [lockfileLocation] : [], + [], + buffer ? [] : [lockfileLocation], + { timestamp: true }, + (err, snapshot) => { + if (err) return callback(err); + const lockfile = buffer + ? Lockfile.parse(buffer.toString("utf-8")) + : new Lockfile(); + lockfileCache = { + lockfile, + snapshot + }; + callback(null, lockfile); + } + ); + }); + }; + if (lockfileCache) { + compilation.fileSystemInfo.checkSnapshotValid( + lockfileCache.snapshot, + (err, valid) => { + if (err) return callback(err); + if (!valid) return readLockfile(); + callback(null, lockfileCache.lockfile); + } + ); + } else { + readLockfile(); + } } - }, - getOptions: key => { - const exclude = key === "runtime" && !options.runtimeModules; - return { - groupChildren: !exclude, - force: exclude + ); + + /** @type {Map | undefined} */ + let lockfileUpdates = undefined; + const storeLockEntry = (lockfile, url, entry) => { + const oldEntry = lockfile.entries.get(url); + if (lockfileUpdates === undefined) lockfileUpdates = new Map(); + lockfileUpdates.set(url, entry); + lockfile.entries.set(url, entry); + if (!oldEntry) { + logger.log(`${url} added to lockfile`); + } else if (typeof oldEntry === "string") { + if (typeof entry === "string") { + logger.log(`${url} updated in lockfile: ${oldEntry} -> ${entry}`); + } else { + logger.log( + `${url} updated in lockfile: ${oldEntry} -> ${entry.resolved}` + ); + } + } else if (typeof entry === "string") { + logger.log( + `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry}` + ); + } else if (oldEntry.resolved !== entry.resolved) { + logger.log( + `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry.resolved}` + ); + } else if (oldEntry.integrity !== entry.integrity) { + logger.log(`${url} updated in lockfile: content changed`); + } else if (oldEntry.contentType !== entry.contentType) { + logger.log( + `${url} updated in lockfile: ${oldEntry.contentType} -> ${entry.contentType}` + ); + } else { + logger.log(`${url} updated in lockfile`); + } + }; + + const storeResult = (lockfile, url, result, callback) => { + if (result.storeLock) { + storeLockEntry(lockfile, url, result.entry); + if (!cacheLocation || !result.content) + return callback(null, result); + const key = getCacheKey(result.entry.resolved); + const filePath = join(intermediateFs, cacheLocation, key); + mkdirp(intermediateFs, dirname(intermediateFs, filePath), err => { + if (err) return callback(err); + intermediateFs.writeFile(filePath, result.content, err => { + if (err) return callback(err); + callback(null, result); + }); + }); + } else { + storeLockEntry(lockfile, url, "no-cache"); + callback(null, result); + } + }; + + for (const { scheme, fetch } of schemes) { + /** + * + * @param {string} url URL + * @param {string} integrity integrity + * @param {function((Error | null)=, { entry: LockfileEntry, content: Buffer, storeLock: boolean }=): void} callback callback + */ + const resolveContent = (url, integrity, callback) => { + const handleResult = (err, result) => { + if (err) return callback(err); + if ("location" in result) { + return resolveContent( + result.location, + integrity, + (err, innerResult) => { + if (err) return callback(err); + callback(null, { + entry: innerResult.entry, + content: innerResult.content, + storeLock: innerResult.storeLock && result.storeLock + }); + } + ); + } else { + if ( + !result.fresh && + integrity && + result.entry.integrity !== integrity && + !verifyIntegrity(result.content, integrity) + ) { + return fetchContent.force(url, handleResult); + } + return callback(null, { + entry: result.entry, + content: result.content, + storeLock: result.storeLock + }); + } + }; + fetchContent(url, handleResult); }; - }, - createGroup: (key, children, modules) => { - const exclude = key === "runtime" && !options.runtimeModules; - return { - type: `${key} modules`, - moduleType: key, - ...(exclude ? { filteredChildren: modules.length } : { children }), - ...moduleGroup(children, modules) + + /** @typedef {{ storeCache: boolean, storeLock: boolean, validUntil: number, etag: string | undefined, fresh: boolean }} FetchResultMeta */ + /** @typedef {FetchResultMeta & { location: string }} RedirectFetchResult */ + /** @typedef {FetchResultMeta & { entry: LockfileEntry, content: Buffer }} ContentFetchResult */ + /** @typedef {RedirectFetchResult | ContentFetchResult} FetchResult */ + + /** + * @param {string} url URL + * @param {FetchResult} cachedResult result from cache + * @param {function((Error | null)=, FetchResult=): void} callback callback + * @returns {void} + */ + const fetchContentRaw = (url, cachedResult, callback) => { + const requestTime = Date.now(); + fetch( + new URL(url), + { + headers: { + "accept-encoding": "gzip, deflate, br", + "user-agent": "webpack", + "if-none-match": cachedResult + ? cachedResult.etag || null + : null + } + }, + res => { + const etag = res.headers["etag"]; + const location = res.headers["location"]; + const cacheControl = res.headers["cache-control"]; + const { storeLock, storeCache, validUntil } = parseCacheControl( + cacheControl, + requestTime + ); + /** + * @param {Partial> & (Pick | Pick)} partialResult result + * @returns {void} + */ + const finishWith = partialResult => { + if ("location" in partialResult) { + logger.debug( + `GET ${url} [${res.statusCode}] -> ${partialResult.location}` + ); + } else { + logger.debug( + `GET ${url} [${res.statusCode}] ${Math.ceil( + partialResult.content.length / 1024 + )} kB${!storeLock ? " no-cache" : ""}` + ); + } + const result = { + ...partialResult, + fresh: true, + storeLock, + storeCache, + validUntil, + etag + }; + if (!storeCache) { + logger.log( + `${url} can't be stored in cache, due to Cache-Control header: ${cacheControl}` + ); + return callback(null, result); + } + cache.store( + url, + null, + { + ...result, + fresh: false + }, + err => { + if (err) { + logger.warn( + `${url} can't be stored in cache: ${err.message}` + ); + logger.debug(err.stack); + } + callback(null, result); + } + ); + }; + if (res.statusCode === 304) { + if ( + cachedResult.validUntil < validUntil || + cachedResult.storeLock !== storeLock || + cachedResult.storeCache !== storeCache || + cachedResult.etag !== etag + ) { + return finishWith(cachedResult); + } else { + logger.debug(`GET ${url} [${res.statusCode}] (unchanged)`); + return callback(null, { + ...cachedResult, + fresh: true + }); + } + } + if ( + location && + res.statusCode >= 301 && + res.statusCode <= 308 + ) { + return finishWith({ + location: new URL(location, url).href + }); + } + const contentType = res.headers["content-type"] || ""; + const bufferArr = []; + + const contentEncoding = res.headers["content-encoding"]; + let stream = res; + if (contentEncoding === "gzip") { + stream = stream.pipe(createGunzip()); + } else if (contentEncoding === "br") { + stream = stream.pipe(createBrotliDecompress()); + } else if (contentEncoding === "deflate") { + stream = stream.pipe(createInflate()); + } + + stream.on("data", chunk => { + bufferArr.push(chunk); + }); + + stream.on("end", () => { + if (!res.complete) { + logger.log(`GET ${url} [${res.statusCode}] (terminated)`); + return callback(new Error(`${url} request was terminated`)); + } + + const content = Buffer.concat(bufferArr); + + if (res.statusCode !== 200) { + logger.log(`GET ${url} [${res.statusCode}]`); + return callback( + new Error( + `${url} request status code = ${ + res.statusCode + }\n${content.toString("utf-8")}` + ) + ); + } + + const integrity = computeIntegrity(content); + const entry = { resolved: url, integrity, contentType }; + + finishWith({ + entry, + content + }); + }); + } + ).on("error", err => { + logger.log(`GET ${url} (error)`); + err.message += `\nwhile fetching ${url}`; + callback(err); + }); }; - } - }); - } - if (groupModulesByLayer) { - groupConfigs.push({ - getKeys: module => { - return [module.layer]; - }, - createGroup: (key, children, modules) => { - return { - type: "modules by layer", - layer: key, - children, - ...moduleGroup(children, modules) + + const fetchContent = cachedWithKey( + /** + * @param {string} url URL + * @param {function((Error | null)=, { validUntil: number, etag?: string, entry: LockfileEntry, content: Buffer, fresh: boolean } | { validUntil: number, etag?: string, location: string, fresh: boolean }=): void} callback callback + * @returns {void} + */ (url, callback) => { + cache.get(url, null, (err, cachedResult) => { + if (err) return callback(err); + if (cachedResult) { + const isValid = cachedResult.validUntil >= Date.now(); + if (isValid) return callback(null, cachedResult); + } + fetchContentRaw(url, cachedResult, callback); + }); + }, + (url, callback) => fetchContentRaw(url, undefined, callback) + ); + + const isAllowed = uri => { + for (const allowed of allowedUris) { + if (typeof allowed === "string") { + if (uri.startsWith(allowed)) return true; + } else if (typeof allowed === "function") { + if (allowed(uri)) return true; + } else { + if (allowed.test(uri)) return true; + } + } + return false; }; - } - }); - } - if (groupModulesByPath || groupModulesByExtension) { - groupConfigs.push({ - getKeys: module => { - if (!module.name) return; - const resource = parseResource(module.name.split("!").pop()).path; - const dataUrl = /^data:[^,;]+/.exec(resource); - if (dataUrl) return [dataUrl[0]]; - const extensionMatch = - groupModulesByExtension && GROUP_EXTENSION_REGEXP.exec(resource); - const extension = extensionMatch ? extensionMatch[1] : ""; - const pathMatch = - groupModulesByPath && GROUP_PATH_REGEXP.exec(resource); - const path = pathMatch ? pathMatch[1].split(/[/\\]/) : []; - const keys = []; - if (groupModulesByPath) { - if (extension) - keys.push( - path.length - ? `${path.join("/")}/*${extension}` - : `*${extension}` + + const getInfo = cachedWithKey( + /** + * @param {string} url the url + * @param {function((Error | null)=, { entry: LockfileEntry, content: Buffer }=): void} callback callback + * @returns {void} + */ + (url, callback) => { + if (!isAllowed(url)) { + return callback( + new Error( + `${url} doesn't match the allowedUris policy. These URIs are allowed:\n${allowedUris + .map(uri => ` - ${uri}`) + .join("\n")}` + ) + ); + } + getLockfile((err, lockfile) => { + if (err) return callback(err); + const entryOrString = lockfile.entries.get(url); + if (!entryOrString) { + if (frozen) { + return callback( + new Error( + `${url} has no lockfile entry and lockfile is frozen` + ) + ); + } + resolveContent(url, null, (err, result) => { + if (err) return callback(err); + storeResult(lockfile, url, result, callback); + }); + return; + } + if (typeof entryOrString === "string") { + const entryTag = entryOrString; + resolveContent(url, null, (err, result) => { + if (err) return callback(err); + if (!result.storeLock || entryTag === "ignore") + return callback(null, result); + if (frozen) { + return callback( + new Error( + `${url} used to have ${entryTag} lockfile entry and has content now, but lockfile is frozen` + ) + ); + } + if (!upgrade) { + return callback( + new Error( + `${url} used to have ${entryTag} lockfile entry and has content now. +This should be reflected in the lockfile, so this lockfile entry must be upgraded, but upgrading is not enabled. +Remove this line from the lockfile to force upgrading.` + ) + ); + } + storeResult(lockfile, url, result, callback); + }); + return; + } + let entry = entryOrString; + const doFetch = lockedContent => { + resolveContent(url, entry.integrity, (err, result) => { + if (err) { + if (lockedContent) { + logger.warn( + `Upgrade request to ${url} failed: ${err.message}` + ); + logger.debug(err.stack); + return callback(null, { + entry, + content: lockedContent + }); + } + return callback(err); + } + if (!result.storeLock) { + // When the lockfile entry should be no-cache + // we need to update the lockfile + if (frozen) { + return callback( + new Error( + `${url} has a lockfile entry and is no-cache now, but lockfile is frozen\nLockfile: ${entryToString( + entry + )}` + ) + ); + } + storeResult(lockfile, url, result, callback); + return; + } + if (!areLockfileEntriesEqual(result.entry, entry)) { + // When the lockfile entry is outdated + // we need to update the lockfile + if (frozen) { + return callback( + new Error( + `${url} has an outdated lockfile entry, but lockfile is frozen\nLockfile: ${entryToString( + entry + )}\nExpected: ${entryToString(result.entry)}` + ) + ); + } + storeResult(lockfile, url, result, callback); + return; + } + if (!lockedContent && cacheLocation) { + // When the lockfile cache content is missing + // we need to update the lockfile + if (frozen) { + return callback( + new Error( + `${url} is missing content in the lockfile cache, but lockfile is frozen\nLockfile: ${entryToString( + entry + )}` + ) + ); + } + storeResult(lockfile, url, result, callback); + return; + } + return callback(null, result); + }); + }; + if (cacheLocation) { + // When there is a lockfile cache + // we read the content from there + const key = getCacheKey(entry.resolved); + const filePath = join(intermediateFs, cacheLocation, key); + fs.readFile(filePath, (err, result) => { + const content = /** @type {Buffer} */ (result); + if (err) { + if (err.code === "ENOENT") return doFetch(); + return callback(err); + } + const continueWithCachedContent = result => { + if (!upgrade) { + // When not in upgrade mode, we accept the result from the lockfile cache + return callback(null, { entry, content }); + } + return doFetch(content); + }; + if (!verifyIntegrity(content, entry.integrity)) { + let contentWithChangedEol; + let isEolChanged = false; + try { + contentWithChangedEol = Buffer.from( + content.toString("utf-8").replace(/\r\n/g, "\n") + ); + isEolChanged = verifyIntegrity( + contentWithChangedEol, + entry.integrity + ); + } catch (e) { + // ignore + } + if (isEolChanged) { + if (!warnedAboutEol) { + const explainer = `Incorrect end of line sequence was detected in the lockfile cache. +The lockfile cache is protected by integrity checks, so any external modification will lead to a corrupted lockfile cache. +When using git make sure to configure .gitattributes correctly for the lockfile cache: + **/*webpack.lock.data/** -text +This will avoid that the end of line sequence is changed by git on Windows.`; + if (frozen) { + logger.error(explainer); + } else { + logger.warn(explainer); + logger.info( + "Lockfile cache will be automatically fixed now, but when lockfile is frozen this would result in an error." + ); + } + warnedAboutEol = true; + } + if (!frozen) { + // "fix" the end of line sequence of the lockfile content + logger.log( + `${filePath} fixed end of line sequence (\\r\\n instead of \\n).` + ); + intermediateFs.writeFile( + filePath, + contentWithChangedEol, + err => { + if (err) return callback(err); + continueWithCachedContent(contentWithChangedEol); + } + ); + return; + } + } + if (frozen) { + return callback( + new Error( + `${ + entry.resolved + } integrity mismatch, expected content with integrity ${ + entry.integrity + } but got ${computeIntegrity(content)}. +Lockfile corrupted (${ + isEolChanged + ? "end of line sequence was unexpectedly changed" + : "incorrectly merged? changed by other tools?" + }). +Run build with un-frozen lockfile to automatically fix lockfile.` + ) + ); + } else { + // "fix" the lockfile entry to the correct integrity + // the content has priority over the integrity value + entry = { + ...entry, + integrity: computeIntegrity(content) + }; + storeLockEntry(lockfile, url, entry); + } + } + continueWithCachedContent(result); + }); + } else { + doFetch(); + } + }); + } + ); + + const respondWithUrlModule = (url, resourceData, callback) => { + getInfo(url.href, (err, result) => { + if (err) return callback(err); + resourceData.resource = url.href; + resourceData.path = url.origin + url.pathname; + resourceData.query = url.search; + resourceData.fragment = url.hash; + resourceData.context = new URL( + ".", + result.entry.resolved + ).href.slice(0, -1); + resourceData.data.mimetype = result.entry.contentType; + callback(null, true); + }); + }; + normalModuleFactory.hooks.resolveForScheme + .for(scheme) + .tapAsync( + "HttpUriPlugin", + (resourceData, resolveData, callback) => { + respondWithUrlModule( + new URL(resourceData.resource), + resourceData, + callback + ); + } + ); + normalModuleFactory.hooks.resolveInScheme + .for(scheme) + .tapAsync("HttpUriPlugin", (resourceData, data, callback) => { + // Only handle relative urls (./xxx, ../xxx, /xxx, //xxx) + if ( + data.dependencyType !== "url" && + !/^\.{0,2}\//.test(resourceData.resource) + ) { + return callback(); + } + respondWithUrlModule( + new URL(resourceData.resource, data.context + "/"), + resourceData, + callback ); - while (path.length > 0) { - keys.push(path.join("/") + "/"); - path.pop(); + }); + const hooks = NormalModule.getCompilationHooks(compilation); + hooks.readResourceForScheme + .for(scheme) + .tapAsync("HttpUriPlugin", (resource, module, callback) => { + return getInfo(resource, (err, result) => { + if (err) return callback(err); + module.buildInfo.resourceIntegrity = result.entry.integrity; + callback(null, result.content); + }); + }); + hooks.needBuild.tapAsync( + "HttpUriPlugin", + (module, context, callback) => { + if ( + module.resource && + module.resource.startsWith(`${scheme}://`) + ) { + getInfo(module.resource, (err, result) => { + if (err) return callback(err); + if ( + result.entry.integrity !== + module.buildInfo.resourceIntegrity + ) { + return callback(null, true); + } + callback(); + }); + } else { + return callback(); + } + } + ); + } + compilation.hooks.finishModules.tapAsync( + "HttpUriPlugin", + (modules, callback) => { + if (!lockfileUpdates) return callback(); + const ext = extname(lockfileLocation); + const tempFile = join( + intermediateFs, + dirname(intermediateFs, lockfileLocation), + `.${basename(lockfileLocation, ext)}.${ + (Math.random() * 10000) | 0 + }${ext}` + ); + + const writeDone = () => { + const nextOperation = inProgressWrite.shift(); + if (nextOperation) { + nextOperation(); + } else { + inProgressWrite = undefined; + } + }; + const runWrite = () => { + intermediateFs.readFile(lockfileLocation, (err, buffer) => { + if (err && err.code !== "ENOENT") { + writeDone(); + return callback(err); + } + const lockfile = buffer + ? Lockfile.parse(buffer.toString("utf-8")) + : new Lockfile(); + for (const [key, value] of lockfileUpdates) { + lockfile.entries.set(key, value); + } + intermediateFs.writeFile(tempFile, lockfile.toString(), err => { + if (err) { + writeDone(); + return intermediateFs.unlink(tempFile, () => callback(err)); + } + intermediateFs.rename(tempFile, lockfileLocation, err => { + if (err) { + writeDone(); + return intermediateFs.unlink(tempFile, () => + callback(err) + ); + } + writeDone(); + callback(); + }); + }); + }); + }; + if (inProgressWrite) { + inProgressWrite.push(runWrite); + } else { + inProgressWrite = []; + runWrite(); } - } else { - if (extension) keys.push(`*${extension}`); } - return keys; - }, - createGroup: (key, children, modules) => { - const isDataUrl = key.startsWith("data:"); - return { - type: isDataUrl - ? "modules by mime type" - : groupModulesByPath - ? "modules by path" - : "modules by extension", - name: isDataUrl ? key.slice(/* 'data:'.length */ 5) : key, - children, - ...moduleGroup(children, modules) - }; - } - }); - } - }, - excludeModules: (groupConfigs, context, { excludeModules }) => { - groupConfigs.push({ - getKeys: module => { - const name = module.name; - if (name) { - const excluded = excludeModules.some(fn => fn(name, module, type)); - if (excluded) return ["1"]; - } - }, - getOptions: () => ({ - groupChildren: false, - force: true - }), - createGroup: (key, children, modules) => ({ - type: "hidden modules", - filteredChildren: children.length, - ...moduleGroup(children, modules) - }) - }); + ); + } + ); } -}); +} -/** @type {Record void>>} */ -const RESULT_GROUPERS = { - "compilation.assets": ASSETS_GROUPERS, - "asset.related": ASSETS_GROUPERS, - "compilation.modules": MODULES_GROUPERS("module"), - "chunk.modules": MODULES_GROUPERS("chunk"), - "chunk.rootModules": MODULES_GROUPERS("root-of-chunk"), - "module.modules": MODULES_GROUPERS("nested"), - "module.reasons": { - groupReasonsByOrigin: groupConfigs => { - groupConfigs.push({ - getKeys: reason => { - return [reason.module]; - }, - createGroup: (key, children, reasons) => { - return { - type: "from origin", - module: key, - children, - ...reasonGroup(children, reasons) - }; - } - }); +module.exports = HttpUriPlugin; + + +/***/ }), + +/***/ 41721: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +class ArraySerializer { + serialize(array, { write }) { + write(array.length); + for (const item of array) write(item); + } + deserialize({ read }) { + const length = read(); + const array = []; + for (let i = 0; i < length; i++) { + array.push(read()); } + return array; } -}; +} -// remove a prefixed "!" that can be specified to reverse sort order -const normalizeFieldKey = field => { - if (field[0] === "!") { - return field.substr(1); - } - return field; -}; +module.exports = ArraySerializer; -// if a field is prefixed by a "!" reverse sort order -const sortOrderRegular = field => { - if (field[0] === "!") { - return false; - } - return true; -}; -/** - * @param {string} field field name - * @returns {function(Object, Object): number} comparators - */ -const sortByField = field => { - if (!field) { - /** - * @param {any} a first - * @param {any} b second - * @returns {-1|0|1} zero - */ - const noSort = (a, b) => 0; - return noSort; - } +/***/ }), - const fieldKey = normalizeFieldKey(field); +/***/ 97059: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - let sortFn = compareSelect(m => m[fieldKey], compareIds); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - // if a field is prefixed with a "!" the sort is reversed! - const sortIsRegular = sortOrderRegular(field); - if (!sortIsRegular) { - const oldSortFn = sortFn; - sortFn = (a, b) => oldSortFn(b, a); - } - return sortFn; -}; +const memoize = __webpack_require__(78676); +const SerializerMiddleware = __webpack_require__(83137); -const ASSET_SORTERS = { - /** @type {(comparators: Function[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void} */ - assetsSort: (comparators, context, { assetsSort }) => { - comparators.push(sortByField(assetsSort)); - }, - _: comparators => { - comparators.push(compareSelect(a => a.name, compareIds)); - } -}; +/** @typedef {import("./types").BufferSerializableType} BufferSerializableType */ +/** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */ -/** @type {Record void>>} */ -const RESULT_SORTERS = { - "compilation.chunks": { - chunksSort: (comparators, context, { chunksSort }) => { - comparators.push(sortByField(chunksSort)); - } - }, - "compilation.modules": { - modulesSort: (comparators, context, { modulesSort }) => { - comparators.push(sortByField(modulesSort)); - } - }, - "chunk.modules": { - chunkModulesSort: (comparators, context, { chunkModulesSort }) => { - comparators.push(sortByField(chunkModulesSort)); - } - }, - "module.modules": { - nestedModulesSort: (comparators, context, { nestedModulesSort }) => { - comparators.push(sortByField(nestedModulesSort)); - } - }, - "compilation.assets": ASSET_SORTERS, - "asset.related": ASSET_SORTERS -}; +/* +Format: -/** - * @param {Record>} config the config see above - * @param {NormalizedStatsOptions} options stats options - * @param {function(string, Function): void} fn handler function called for every active line in config - * @returns {void} - */ -const iterateConfig = (config, options, fn) => { - for (const hookFor of Object.keys(config)) { - const subConfig = config[hookFor]; - for (const option of Object.keys(subConfig)) { - if (option !== "_") { - if (option.startsWith("!")) { - if (options[option.slice(1)]) continue; - } else { - const value = options[option]; - if ( - value === false || - value === undefined || - (Array.isArray(value) && value.length === 0) - ) - continue; - } - } - fn(hookFor, subConfig[option]); - } - } -}; +File -> Section* -/** @type {Record} */ -const ITEM_NAMES = { - "compilation.children[]": "compilation", - "compilation.modules[]": "module", - "compilation.entrypoints[]": "chunkGroup", - "compilation.namedChunkGroups[]": "chunkGroup", - "compilation.errors[]": "error", - "compilation.warnings[]": "warning", - "chunk.modules[]": "module", - "chunk.rootModules[]": "module", - "chunk.origins[]": "chunkOrigin", - "compilation.chunks[]": "chunk", - "compilation.assets[]": "asset", - "asset.related[]": "asset", - "module.issuerPath[]": "moduleIssuer", - "module.reasons[]": "moduleReason", - "module.modules[]": "module", - "module.children[]": "module", - "moduleTrace[]": "moduleTraceItem", - "moduleTraceItem.dependencies[]": "moduleTraceDependency" -}; +Section -> NullsSection | + BooleansSection | + F64NumbersSection | + I32NumbersSection | + I8NumbersSection | + ShortStringSection | + StringSection | + BufferSection | + NopSection -/** - * @param {Object[]} items items to be merged - * @returns {Object} an object - */ -const mergeToObject = items => { - const obj = Object.create(null); - for (const item of items) { - obj[item.name] = item; - } - return obj; -}; -/** @type {Record any>} */ -const MERGER = { - "compilation.entrypoints": mergeToObject, - "compilation.namedChunkGroups": mergeToObject -}; -class DefaultStatsFactoryPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap("DefaultStatsFactoryPlugin", compilation => { - compilation.hooks.statsFactory.tap( - "DefaultStatsFactoryPlugin", - (stats, options, context) => { - iterateConfig(SIMPLE_EXTRACTORS, options, (hookFor, fn) => { - stats.hooks.extract - .for(hookFor) - .tap("DefaultStatsFactoryPlugin", (obj, data, ctx) => - fn(obj, data, ctx, options, stats) - ); - }); - iterateConfig(FILTER, options, (hookFor, fn) => { - stats.hooks.filter - .for(hookFor) - .tap("DefaultStatsFactoryPlugin", (item, ctx, idx, i) => - fn(item, ctx, options, idx, i) - ); - }); - iterateConfig(FILTER_RESULTS, options, (hookFor, fn) => { - stats.hooks.filterResults - .for(hookFor) - .tap("DefaultStatsFactoryPlugin", (item, ctx, idx, i) => - fn(item, ctx, options, idx, i) - ); - }); - iterateConfig(SORTERS, options, (hookFor, fn) => { - stats.hooks.sort - .for(hookFor) - .tap("DefaultStatsFactoryPlugin", (comparators, ctx) => - fn(comparators, ctx, options) - ); - }); - iterateConfig(RESULT_SORTERS, options, (hookFor, fn) => { - stats.hooks.sortResults - .for(hookFor) - .tap("DefaultStatsFactoryPlugin", (comparators, ctx) => - fn(comparators, ctx, options) - ); - }); - iterateConfig(RESULT_GROUPERS, options, (hookFor, fn) => { - stats.hooks.groupResults - .for(hookFor) - .tap("DefaultStatsFactoryPlugin", (groupConfigs, ctx) => - fn(groupConfigs, ctx, options) - ); - }); - for (const key of Object.keys(ITEM_NAMES)) { - const itemName = ITEM_NAMES[key]; - stats.hooks.getItemName - .for(key) - .tap("DefaultStatsFactoryPlugin", () => itemName); - } - for (const key of Object.keys(MERGER)) { - const merger = MERGER[key]; - stats.hooks.merge.for(key).tap("DefaultStatsFactoryPlugin", merger); - } - if (options.children) { - if (Array.isArray(options.children)) { - stats.hooks.getItemFactory - .for("compilation.children[].compilation") - .tap("DefaultStatsFactoryPlugin", (comp, { _index: idx }) => { - if (idx < options.children.length) { - return compilation.createStatsFactory( - compilation.createStatsOptions( - options.children[idx], - context - ) - ); - } - }); - } else if (options.children !== true) { - const childFactory = compilation.createStatsFactory( - compilation.createStatsOptions(options.children, context) - ); - stats.hooks.getItemFactory - .for("compilation.children[].compilation") - .tap("DefaultStatsFactoryPlugin", () => { - return childFactory; - }); - } - } - } - ); - }); - } -} -module.exports = DefaultStatsFactoryPlugin; +NullsSection -> + NullHeaderByte | Null2HeaderByte | Null3HeaderByte | + Nulls8HeaderByte 0xnn (n:count - 4) | + Nulls32HeaderByte n:ui32 (n:count - 260) | +BooleansSection -> TrueHeaderByte | FalseHeaderByte | BooleansSectionHeaderByte BooleansCountAndBitsByte +F64NumbersSection -> F64NumbersSectionHeaderByte f64* +I32NumbersSection -> I32NumbersSectionHeaderByte i32* +I8NumbersSection -> I8NumbersSectionHeaderByte i8* +ShortStringSection -> ShortStringSectionHeaderByte ascii-byte* +StringSection -> StringSectionHeaderByte i32:length utf8-byte* +BufferSection -> BufferSectionHeaderByte i32:length byte* +NopSection --> NopSectionHeaderByte +ShortStringSectionHeaderByte -> 0b1nnn_nnnn (n:length) -/***/ }), +F64NumbersSectionHeaderByte -> 0b001n_nnnn (n:count - 1) +I32NumbersSectionHeaderByte -> 0b010n_nnnn (n:count - 1) +I8NumbersSectionHeaderByte -> 0b011n_nnnn (n:count - 1) -/***/ 55442: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +NullsSectionHeaderByte -> 0b0001_nnnn (n:count - 1) +BooleansCountAndBitsByte -> + 0b0000_1xxx (count = 3) | + 0b0001_xxxx (count = 4) | + 0b001x_xxxx (count = 5) | + 0b01xx_xxxx (count = 6) | + 0b1nnn_nnnn (n:count - 7, 7 <= count <= 133) + 0xff n:ui32 (n:count, 134 <= count < 2^32) + +StringSectionHeaderByte -> 0b0000_1110 +BufferSectionHeaderByte -> 0b0000_1111 +NopSectionHeaderByte -> 0b0000_1011 +FalseHeaderByte -> 0b0000_1100 +TrueHeaderByte -> 0b0000_1101 + +RawNumber -> n (n <= 10) -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ +const LAZY_HEADER = 0x0b; +const TRUE_HEADER = 0x0c; +const FALSE_HEADER = 0x0d; +const BOOLEANS_HEADER = 0x0e; +const NULL_HEADER = 0x10; +const NULL2_HEADER = 0x11; +const NULL3_HEADER = 0x12; +const NULLS8_HEADER = 0x13; +const NULLS32_HEADER = 0x14; +const NULL_AND_I8_HEADER = 0x15; +const NULL_AND_I32_HEADER = 0x16; +const NULL_AND_TRUE_HEADER = 0x17; +const NULL_AND_FALSE_HEADER = 0x18; +const STRING_HEADER = 0x1e; +const BUFFER_HEADER = 0x1f; +const I8_HEADER = 0x60; +const I32_HEADER = 0x40; +const F64_HEADER = 0x20; +const SHORT_STRING_HEADER = 0x80; +/** Uplift high-order bits */ +const NUMBERS_HEADER_MASK = 0xe0; +const NUMBERS_COUNT_MASK = 0x1f; // 0b0001_1111 +const SHORT_STRING_LENGTH_MASK = 0x7f; // 0b0111_1111 -const RequestShortener = __webpack_require__(73406); +const HEADER_SIZE = 1; +const I8_SIZE = 1; +const I32_SIZE = 4; +const F64_SIZE = 8; -/** @typedef {import("../../declarations/WebpackOptions").StatsOptions} StatsOptions */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compilation").CreateStatsOptionsContext} CreateStatsOptionsContext */ -/** @typedef {import("../Compiler")} Compiler */ +const MEASURE_START_OPERATION = Symbol("MEASURE_START_OPERATION"); +const MEASURE_END_OPERATION = Symbol("MEASURE_END_OPERATION"); -const applyDefaults = (options, defaults) => { - for (const key of Object.keys(defaults)) { - if (typeof options[key] === "undefined") { - options[key] = defaults[key]; - } - } -}; +/** @typedef {typeof MEASURE_START_OPERATION} MEASURE_START_OPERATION_TYPE */ +/** @typedef {typeof MEASURE_END_OPERATION} MEASURE_END_OPERATION_TYPE */ -const NAMED_PRESETS = { - verbose: { - hash: true, - builtAt: true, - relatedAssets: true, - entrypoints: true, - chunkGroups: true, - ids: true, - modules: false, - chunks: true, - chunkRelations: true, - chunkModules: true, - dependentModules: true, - chunkOrigins: true, - depth: true, - env: true, - reasons: true, - usedExports: true, - providedExports: true, - optimizationBailout: true, - errorDetails: true, - errorStack: true, - publicPath: true, - logging: "verbose", - orphanModules: true, - runtimeModules: true, - exclude: false, - modulesSpace: Infinity, - chunkModulesSpace: Infinity, - assetsSpace: Infinity, - reasonsSpace: Infinity, - children: true - }, - detailed: { - hash: true, - builtAt: true, - relatedAssets: true, - entrypoints: true, - chunkGroups: true, - ids: true, - chunks: true, - chunkRelations: true, - chunkModules: false, - chunkOrigins: true, - depth: true, - usedExports: true, - providedExports: true, - optimizationBailout: true, - errorDetails: true, - publicPath: true, - logging: true, - runtimeModules: true, - exclude: false, - modulesSpace: 1000, - assetsSpace: 1000, - reasonsSpace: 1000 - }, - minimal: { - all: false, - version: true, - timings: true, - modules: true, - modulesSpace: 0, - assets: true, - assetsSpace: 0, - errors: true, - errorsCount: true, - warnings: true, - warningsCount: true, - logging: "warn" - }, - "errors-only": { - all: false, - errors: true, - errorsCount: true, - moduleTrace: true, - logging: "error" - }, - "errors-warnings": { - all: false, - errors: true, - errorsCount: true, - warnings: true, - warningsCount: true, - logging: "warn" - }, - summary: { - all: false, - version: true, - errorsCount: true, - warningsCount: true - }, - none: { - all: false +const identifyNumber = n => { + if (n === (n | 0)) { + if (n <= 127 && n >= -128) return 0; + if (n <= 2147483647 && n >= -2147483648) return 1; } + return 2; }; -const NORMAL_ON = ({ all }) => all !== false; -const NORMAL_OFF = ({ all }) => all === true; -const ON_FOR_TO_STRING = ({ all }, { forToString }) => - forToString ? all !== false : all === true; -const OFF_FOR_TO_STRING = ({ all }, { forToString }) => - forToString ? all === true : all !== false; -const AUTO_FOR_TO_STRING = ({ all }, { forToString }) => { - if (all === false) return false; - if (all === true) return true; - if (forToString) return "auto"; - return true; -}; - -/** @type {Record any>} */ -const DEFAULTS = { - context: (options, context, compilation) => compilation.compiler.context, - requestShortener: (options, context, compilation) => - compilation.compiler.context === options.context - ? compilation.requestShortener - : new RequestShortener(options.context, compilation.compiler.root), - performance: NORMAL_ON, - hash: OFF_FOR_TO_STRING, - env: NORMAL_OFF, - version: NORMAL_ON, - timings: NORMAL_ON, - builtAt: OFF_FOR_TO_STRING, - assets: NORMAL_ON, - entrypoints: AUTO_FOR_TO_STRING, - chunkGroups: OFF_FOR_TO_STRING, - chunkGroupAuxiliary: OFF_FOR_TO_STRING, - chunkGroupChildren: OFF_FOR_TO_STRING, - chunkGroupMaxAssets: (o, { forToString }) => (forToString ? 5 : Infinity), - chunks: OFF_FOR_TO_STRING, - chunkRelations: OFF_FOR_TO_STRING, - chunkModules: ({ all, modules }) => { - if (all === false) return false; - if (all === true) return true; - if (modules) return false; - return true; - }, - dependentModules: OFF_FOR_TO_STRING, - chunkOrigins: OFF_FOR_TO_STRING, - ids: OFF_FOR_TO_STRING, - modules: ({ all, chunks, chunkModules }, { forToString }) => { - if (all === false) return false; - if (all === true) return true; - if (forToString && chunks && chunkModules) return false; - return true; - }, - nestedModules: OFF_FOR_TO_STRING, - groupModulesByType: ON_FOR_TO_STRING, - groupModulesByCacheStatus: ON_FOR_TO_STRING, - groupModulesByLayer: ON_FOR_TO_STRING, - groupModulesByAttributes: ON_FOR_TO_STRING, - groupModulesByPath: ON_FOR_TO_STRING, - groupModulesByExtension: ON_FOR_TO_STRING, - modulesSpace: (o, { forToString }) => (forToString ? 15 : Infinity), - chunkModulesSpace: (o, { forToString }) => (forToString ? 10 : Infinity), - nestedModulesSpace: (o, { forToString }) => (forToString ? 10 : Infinity), - relatedAssets: OFF_FOR_TO_STRING, - groupAssetsByEmitStatus: ON_FOR_TO_STRING, - groupAssetsByInfo: ON_FOR_TO_STRING, - groupAssetsByPath: ON_FOR_TO_STRING, - groupAssetsByExtension: ON_FOR_TO_STRING, - groupAssetsByChunk: ON_FOR_TO_STRING, - assetsSpace: (o, { forToString }) => (forToString ? 15 : Infinity), - orphanModules: OFF_FOR_TO_STRING, - runtimeModules: ({ all, runtime }, { forToString }) => - runtime !== undefined - ? runtime - : forToString - ? all === true - : all !== false, - cachedModules: ({ all, cached }, { forToString }) => - cached !== undefined ? cached : forToString ? all === true : all !== false, - moduleAssets: OFF_FOR_TO_STRING, - depth: OFF_FOR_TO_STRING, - cachedAssets: OFF_FOR_TO_STRING, - reasons: OFF_FOR_TO_STRING, - reasonsSpace: (o, { forToString }) => (forToString ? 15 : Infinity), - groupReasonsByOrigin: ON_FOR_TO_STRING, - usedExports: OFF_FOR_TO_STRING, - providedExports: OFF_FOR_TO_STRING, - optimizationBailout: OFF_FOR_TO_STRING, - children: OFF_FOR_TO_STRING, - source: NORMAL_OFF, - moduleTrace: NORMAL_ON, - errors: NORMAL_ON, - errorsCount: NORMAL_ON, - errorDetails: AUTO_FOR_TO_STRING, - errorStack: OFF_FOR_TO_STRING, - warnings: NORMAL_ON, - warningsCount: NORMAL_ON, - publicPath: OFF_FOR_TO_STRING, - logging: ({ all }, { forToString }) => - forToString && all !== false ? "info" : false, - loggingDebug: () => [], - loggingTrace: OFF_FOR_TO_STRING, - excludeModules: () => [], - excludeAssets: () => [], - modulesSort: () => "depth", - chunkModulesSort: () => "name", - nestedModulesSort: () => false, - chunksSort: () => false, - assetsSort: () => "!size", - outputPath: OFF_FOR_TO_STRING, - colors: () => false -}; +/** + * @typedef {PrimitiveSerializableType[]} DeserializedType + * @typedef {BufferSerializableType[]} SerializedType + * @extends {SerializerMiddleware} + */ +class BinaryMiddleware extends SerializerMiddleware { + /** + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType|Promise} serialized data + */ + serialize(data, context) { + return this._serialize(data, context); + } -const normalizeFilter = item => { - if (typeof item === "string") { - const regExp = new RegExp( - `[\\\\/]${item.replace( - // eslint-disable-next-line no-useless-escape - /[-[\]{}()*+?.\\^$|]/g, - "\\$&" - )}([\\\\/]|$|!|\\?)` + _serializeLazy(fn, context) { + return SerializerMiddleware.serializeLazy(fn, data => + this._serialize(data, context) ); - return ident => regExp.test(ident); - } - if (item && typeof item === "object" && typeof item.test === "function") { - return ident => item.test(ident); - } - if (typeof item === "function") { - return item; - } - if (typeof item === "boolean") { - return () => item; } -}; -const NORMALIZER = { - excludeModules: value => { - if (!Array.isArray(value)) { - value = value ? [value] : []; - } - return value.map(normalizeFilter); - }, - excludeAssets: value => { - if (!Array.isArray(value)) { - value = value ? [value] : []; + /** + * @param {DeserializedType} data data + * @param {Object} context context object + * @param {{ leftOverBuffer: Buffer | null, allocationSize: number, increaseCounter: number }} allocationScope allocation scope + * @returns {SerializedType} serialized data + */ + _serialize( + data, + context, + allocationScope = { + allocationSize: 1024, + increaseCounter: 0, + leftOverBuffer: null } - return value.map(normalizeFilter); - }, - warningsFilter: value => { - if (!Array.isArray(value)) { - value = value ? [value] : []; + ) { + /** @type {Buffer} */ + let leftOverBuffer = null; + /** @type {BufferSerializableType[]} */ + let buffers = []; + /** @type {Buffer} */ + let currentBuffer = allocationScope ? allocationScope.leftOverBuffer : null; + allocationScope.leftOverBuffer = null; + let currentPosition = 0; + if (currentBuffer === null) { + currentBuffer = Buffer.allocUnsafe(allocationScope.allocationSize); } - return value.map(filter => { - if (typeof filter === "string") { - return (warning, warningString) => warningString.includes(filter); + const allocate = bytesNeeded => { + if (currentBuffer !== null) { + if (currentBuffer.length - currentPosition >= bytesNeeded) return; + flush(); } - if (filter instanceof RegExp) { - return (warning, warningString) => filter.test(warningString); + if (leftOverBuffer && leftOverBuffer.length >= bytesNeeded) { + currentBuffer = leftOverBuffer; + leftOverBuffer = null; + } else { + currentBuffer = Buffer.allocUnsafe( + Math.max(bytesNeeded, allocationScope.allocationSize) + ); + if ( + !(allocationScope.increaseCounter = + (allocationScope.increaseCounter + 1) % 4) && + allocationScope.allocationSize < 16777216 + ) { + allocationScope.allocationSize = allocationScope.allocationSize << 1; + } } - if (typeof filter === "function") { - return filter; + }; + const flush = () => { + if (currentBuffer !== null) { + if (currentPosition > 0) { + buffers.push( + Buffer.from( + currentBuffer.buffer, + currentBuffer.byteOffset, + currentPosition + ) + ); + } + if ( + !leftOverBuffer || + leftOverBuffer.length < currentBuffer.length - currentPosition + ) { + leftOverBuffer = Buffer.from( + currentBuffer.buffer, + currentBuffer.byteOffset + currentPosition, + currentBuffer.byteLength - currentPosition + ); + } + + currentBuffer = null; + currentPosition = 0; + } + }; + const writeU8 = byte => { + currentBuffer.writeUInt8(byte, currentPosition++); + }; + const writeU32 = ui32 => { + currentBuffer.writeUInt32LE(ui32, currentPosition); + currentPosition += 4; + }; + const measureStack = []; + const measureStart = () => { + measureStack.push(buffers.length, currentPosition); + }; + const measureEnd = () => { + const oldPos = measureStack.pop(); + const buffersIndex = measureStack.pop(); + let size = currentPosition - oldPos; + for (let i = buffersIndex; i < buffers.length; i++) { + size += buffers[i].length; + } + return size; + }; + for (let i = 0; i < data.length; i++) { + const thing = data[i]; + switch (typeof thing) { + case "function": { + if (!SerializerMiddleware.isLazy(thing)) + throw new Error("Unexpected function " + thing); + /** @type {SerializedType | (() => SerializedType)} */ + let serializedData = + SerializerMiddleware.getLazySerializedValue(thing); + if (serializedData === undefined) { + if (SerializerMiddleware.isLazy(thing, this)) { + flush(); + allocationScope.leftOverBuffer = leftOverBuffer; + const result = + /** @type {(Exclude>)[]} */ ( + thing() + ); + const data = this._serialize(result, context, allocationScope); + leftOverBuffer = allocationScope.leftOverBuffer; + allocationScope.leftOverBuffer = null; + SerializerMiddleware.setLazySerializedValue(thing, data); + serializedData = data; + } else { + serializedData = this._serializeLazy(thing, context); + flush(); + buffers.push(serializedData); + break; + } + } else { + if (typeof serializedData === "function") { + flush(); + buffers.push(serializedData); + break; + } + } + const lengths = []; + for (const item of serializedData) { + let last; + if (typeof item === "function") { + lengths.push(0); + } else if (item.length === 0) { + // ignore + } else if ( + lengths.length > 0 && + (last = lengths[lengths.length - 1]) !== 0 + ) { + const remaining = 0xffffffff - last; + if (remaining >= item.length) { + lengths[lengths.length - 1] += item.length; + } else { + lengths.push(item.length - remaining); + lengths[lengths.length - 2] = 0xffffffff; + } + } else { + lengths.push(item.length); + } + } + allocate(5 + lengths.length * 4); + writeU8(LAZY_HEADER); + writeU32(lengths.length); + for (const l of lengths) { + writeU32(l); + } + flush(); + for (const item of serializedData) { + buffers.push(item); + } + break; + } + case "string": { + const len = Buffer.byteLength(thing); + if (len >= 128 || len !== thing.length) { + allocate(len + HEADER_SIZE + I32_SIZE); + writeU8(STRING_HEADER); + writeU32(len); + currentBuffer.write(thing, currentPosition); + currentPosition += len; + } else if (len >= 70) { + allocate(len + HEADER_SIZE); + writeU8(SHORT_STRING_HEADER | len); + + currentBuffer.write(thing, currentPosition, "latin1"); + currentPosition += len; + } else { + allocate(len + HEADER_SIZE); + writeU8(SHORT_STRING_HEADER | len); + + for (let i = 0; i < len; i++) { + currentBuffer[currentPosition++] = thing.charCodeAt(i); + } + } + break; + } + case "number": { + const type = identifyNumber(thing); + if (type === 0 && thing >= 0 && thing <= 10) { + // shortcut for very small numbers + allocate(I8_SIZE); + writeU8(thing); + break; + } + /** + * amount of numbers to write + * @type {number} + */ + let n = 1; + for (; n < 32 && i + n < data.length; n++) { + const item = data[i + n]; + if (typeof item !== "number") break; + if (identifyNumber(item) !== type) break; + } + switch (type) { + case 0: + allocate(HEADER_SIZE + I8_SIZE * n); + writeU8(I8_HEADER | (n - 1)); + while (n > 0) { + currentBuffer.writeInt8( + /** @type {number} */ (data[i]), + currentPosition + ); + currentPosition += I8_SIZE; + n--; + i++; + } + break; + case 1: + allocate(HEADER_SIZE + I32_SIZE * n); + writeU8(I32_HEADER | (n - 1)); + while (n > 0) { + currentBuffer.writeInt32LE( + /** @type {number} */ (data[i]), + currentPosition + ); + currentPosition += I32_SIZE; + n--; + i++; + } + break; + case 2: + allocate(HEADER_SIZE + F64_SIZE * n); + writeU8(F64_HEADER | (n - 1)); + while (n > 0) { + currentBuffer.writeDoubleLE( + /** @type {number} */ (data[i]), + currentPosition + ); + currentPosition += F64_SIZE; + n--; + i++; + } + break; + } + + i--; + break; + } + case "boolean": { + let lastByte = thing === true ? 1 : 0; + const bytes = []; + let count = 1; + let n; + for (n = 1; n < 0xffffffff && i + n < data.length; n++) { + const item = data[i + n]; + if (typeof item !== "boolean") break; + const pos = count & 0x7; + if (pos === 0) { + bytes.push(lastByte); + lastByte = item === true ? 1 : 0; + } else if (item === true) { + lastByte |= 1 << pos; + } + count++; + } + i += count - 1; + if (count === 1) { + allocate(HEADER_SIZE); + writeU8(lastByte === 1 ? TRUE_HEADER : FALSE_HEADER); + } else if (count === 2) { + allocate(HEADER_SIZE * 2); + writeU8(lastByte & 1 ? TRUE_HEADER : FALSE_HEADER); + writeU8(lastByte & 2 ? TRUE_HEADER : FALSE_HEADER); + } else if (count <= 6) { + allocate(HEADER_SIZE + I8_SIZE); + writeU8(BOOLEANS_HEADER); + writeU8((1 << count) | lastByte); + } else if (count <= 133) { + allocate(HEADER_SIZE + I8_SIZE + I8_SIZE * bytes.length + I8_SIZE); + writeU8(BOOLEANS_HEADER); + writeU8(0x80 | (count - 7)); + for (const byte of bytes) writeU8(byte); + writeU8(lastByte); + } else { + allocate( + HEADER_SIZE + + I8_SIZE + + I32_SIZE + + I8_SIZE * bytes.length + + I8_SIZE + ); + writeU8(BOOLEANS_HEADER); + writeU8(0xff); + writeU32(count); + for (const byte of bytes) writeU8(byte); + writeU8(lastByte); + } + break; + } + case "object": { + if (thing === null) { + let n; + for (n = 1; n < 0x100000104 && i + n < data.length; n++) { + const item = data[i + n]; + if (item !== null) break; + } + i += n - 1; + if (n === 1) { + if (i + 1 < data.length) { + const next = data[i + 1]; + if (next === true) { + allocate(HEADER_SIZE); + writeU8(NULL_AND_TRUE_HEADER); + i++; + } else if (next === false) { + allocate(HEADER_SIZE); + writeU8(NULL_AND_FALSE_HEADER); + i++; + } else if (typeof next === "number") { + const type = identifyNumber(next); + if (type === 0) { + allocate(HEADER_SIZE + I8_SIZE); + writeU8(NULL_AND_I8_HEADER); + currentBuffer.writeInt8(next, currentPosition); + currentPosition += I8_SIZE; + i++; + } else if (type === 1) { + allocate(HEADER_SIZE + I32_SIZE); + writeU8(NULL_AND_I32_HEADER); + currentBuffer.writeInt32LE(next, currentPosition); + currentPosition += I32_SIZE; + i++; + } else { + allocate(HEADER_SIZE); + writeU8(NULL_HEADER); + } + } else { + allocate(HEADER_SIZE); + writeU8(NULL_HEADER); + } + } else { + allocate(HEADER_SIZE); + writeU8(NULL_HEADER); + } + } else if (n === 2) { + allocate(HEADER_SIZE); + writeU8(NULL2_HEADER); + } else if (n === 3) { + allocate(HEADER_SIZE); + writeU8(NULL3_HEADER); + } else if (n < 260) { + allocate(HEADER_SIZE + I8_SIZE); + writeU8(NULLS8_HEADER); + writeU8(n - 4); + } else { + allocate(HEADER_SIZE + I32_SIZE); + writeU8(NULLS32_HEADER); + writeU32(n - 260); + } + } else if (Buffer.isBuffer(thing)) { + if (thing.length < 8192) { + allocate(HEADER_SIZE + I32_SIZE + thing.length); + writeU8(BUFFER_HEADER); + writeU32(thing.length); + thing.copy(currentBuffer, currentPosition); + currentPosition += thing.length; + } else { + allocate(HEADER_SIZE + I32_SIZE); + writeU8(BUFFER_HEADER); + writeU32(thing.length); + flush(); + buffers.push(thing); + } + } + break; + } + case "symbol": { + if (thing === MEASURE_START_OPERATION) { + measureStart(); + } else if (thing === MEASURE_END_OPERATION) { + const size = measureEnd(); + allocate(HEADER_SIZE + I32_SIZE); + writeU8(I32_HEADER); + currentBuffer.writeInt32LE(size, currentPosition); + currentPosition += I32_SIZE; + } + break; + } } - throw new Error( - `Can only filter warnings with Strings or RegExps. (Given: ${filter})` - ); - }); - }, - logging: value => { - if (value === true) value = "log"; - return value; - }, - loggingDebug: value => { - if (!Array.isArray(value)) { - value = value ? [value] : []; } - return value.map(normalizeFilter); + flush(); + + allocationScope.leftOverBuffer = leftOverBuffer; + + // avoid leaking memory + currentBuffer = null; + leftOverBuffer = null; + allocationScope = undefined; + const _buffers = buffers; + buffers = undefined; + return _buffers; } -}; -class DefaultStatsPresetPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data */ - apply(compiler) { - compiler.hooks.compilation.tap("DefaultStatsPresetPlugin", compilation => { - for (const key of Object.keys(NAMED_PRESETS)) { - const defaults = NAMED_PRESETS[key]; - compilation.hooks.statsPreset - .for(key) - .tap("DefaultStatsPresetPlugin", (options, context) => { - applyDefaults(options, defaults); - }); - } - compilation.hooks.statsNormalize.tap( - "DefaultStatsPresetPlugin", - (options, context) => { - for (const key of Object.keys(DEFAULTS)) { - if (options[key] === undefined) - options[key] = DEFAULTS[key](options, context, compilation); - } - for (const key of Object.keys(NORMALIZER)) { - options[key] = NORMALIZER[key](options[key]); - } - } - ); - }); + deserialize(data, context) { + return this._deserialize(data, context); } -} -module.exports = DefaultStatsPresetPlugin; - - -/***/ }), - -/***/ 58692: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("./StatsPrinter")} StatsPrinter */ -/** @typedef {import("./StatsPrinter").StatsPrinterContext} StatsPrinterContext */ - -const DATA_URI_CONTENT_LENGTH = 16; - -const plural = (n, singular, plural) => (n === 1 ? singular : plural); -/** - * @param {Record} sizes sizes by source type - * @param {Object} options options - * @param {(number) => string=} options.formatSize size formatter - * @returns {string} text - */ -const printSizes = (sizes, { formatSize = n => `${n}` }) => { - const keys = Object.keys(sizes); - if (keys.length > 1) { - return keys.map(key => `${formatSize(sizes[key])} (${key})`).join(" "); - } else if (keys.length === 1) { - return formatSize(sizes[keys[0]]); + _createLazyDeserialized(content, context) { + return SerializerMiddleware.createLazy( + memoize(() => this._deserialize(content, context)), + this, + undefined, + content + ); } -}; - -const getResourceName = resource => { - const dataUrl = /^data:[^,]+,/.exec(resource); - if (!dataUrl) return resource; - - const len = dataUrl[0].length + DATA_URI_CONTENT_LENGTH; - if (resource.length < len) return resource; - return `${resource.slice( - 0, - Math.min(resource.length - /* '..'.length */ 2, len) - )}..`; -}; - -const getModuleName = name => { - const [, prefix, resource] = /^(.*!)?([^!]*)$/.exec(name); - return [prefix, getResourceName(resource)]; -}; -const mapLines = (str, fn) => str.split("\n").map(fn).join("\n"); - -/** - * @param {number} n a number - * @returns {string} number as two digit string, leading 0 - */ -const twoDigit = n => (n >= 10 ? `${n}` : `0${n}`); + _deserializeLazy(fn, context) { + return SerializerMiddleware.deserializeLazy(fn, data => + this._deserialize(data, context) + ); + } -const isValidId = id => { - return typeof id === "number" || id; -}; + /** + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType} deserialized data + */ + _deserialize(data, context) { + let currentDataItem = 0; + let currentBuffer = data[0]; + let currentIsBuffer = Buffer.isBuffer(currentBuffer); + let currentPosition = 0; -const moreCount = (list, count) => { - return list && list.length > 0 ? `+ ${count}` : `${count}`; -}; + const retainedBuffer = context.retainedBuffer || (x => x); -/** @type {Record string | void>} */ -const SIMPLE_PRINTERS = { - "compilation.summary!": ( - _, - { - type, - bold, - green, - red, - yellow, - formatDateTime, - formatTime, - compilation: { - name, - hash, - version, - time, - builtAt, - errorsCount, - warningsCount + const checkOverflow = () => { + if (currentPosition >= currentBuffer.length) { + currentPosition = 0; + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); } - } - ) => { - const root = type === "compilation.summary!"; - const warningsMessage = - warningsCount > 0 - ? yellow( - `${warningsCount} ${plural(warningsCount, "warning", "warnings")}` - ) - : ""; - const errorsMessage = - errorsCount > 0 - ? red(`${errorsCount} ${plural(errorsCount, "error", "errors")}`) - : ""; - const timeMessage = root && time ? ` in ${formatTime(time)}` : ""; - const hashMessage = hash ? ` (${hash})` : ""; - const builtAtMessage = - root && builtAt ? `${formatDateTime(builtAt)}: ` : ""; - const versionMessage = root && version ? `webpack ${version}` : ""; - const nameMessage = - root && name - ? bold(name) - : name - ? `Child ${bold(name)}` - : root - ? "" - : "Child"; - const subjectMessage = - nameMessage && versionMessage - ? `${nameMessage} (${versionMessage})` - : versionMessage || nameMessage || "webpack"; - let statusMessage; - if (errorsMessage && warningsMessage) { - statusMessage = `compiled with ${errorsMessage} and ${warningsMessage}`; - } else if (errorsMessage) { - statusMessage = `compiled with ${errorsMessage}`; - } else if (warningsMessage) { - statusMessage = `compiled with ${warningsMessage}`; - } else if (errorsCount === 0 && warningsCount === 0) { - statusMessage = `compiled ${green("successfully")}`; - } else { - statusMessage = `compiled`; - } - if ( - builtAtMessage || - versionMessage || - errorsMessage || - warningsMessage || - (errorsCount === 0 && warningsCount === 0) || - timeMessage || - hashMessage - ) - return `${builtAtMessage}${subjectMessage} ${statusMessage}${timeMessage}${hashMessage}`; - }, - "compilation.filteredWarningDetailsCount": count => - count - ? `${count} ${plural( - count, - "warning has", - "warnings have" - )} detailed information that is not shown.\nUse 'stats.errorDetails: true' resp. '--stats-error-details' to show it.` - : undefined, - "compilation.filteredErrorDetailsCount": (count, { yellow }) => - count - ? yellow( - `${count} ${plural( - count, - "error has", - "errors have" - )} detailed information that is not shown.\nUse 'stats.errorDetails: true' resp. '--stats-error-details' to show it.` - ) - : undefined, - "compilation.env": (env, { bold }) => - env - ? `Environment (--env): ${bold(JSON.stringify(env, null, 2))}` - : undefined, - "compilation.publicPath": (publicPath, { bold }) => - `PublicPath: ${bold(publicPath || "(none)")}`, - "compilation.entrypoints": (entrypoints, context, printer) => - Array.isArray(entrypoints) - ? undefined - : printer.print(context.type, Object.values(entrypoints), { - ...context, - chunkGroupKind: "Entrypoint" - }), - "compilation.namedChunkGroups": (namedChunkGroups, context, printer) => { - if (!Array.isArray(namedChunkGroups)) { - const { - compilation: { entrypoints } - } = context; - let chunkGroups = Object.values(namedChunkGroups); - if (entrypoints) { - chunkGroups = chunkGroups.filter( - group => - !Object.prototype.hasOwnProperty.call(entrypoints, group.name) + }; + const isInCurrentBuffer = n => { + return currentIsBuffer && n + currentPosition <= currentBuffer.length; + }; + const ensureBuffer = () => { + if (!currentIsBuffer) { + throw new Error( + currentBuffer === null + ? "Unexpected end of stream" + : "Unexpected lazy element in stream" ); } - return printer.print(context.type, chunkGroups, { - ...context, - chunkGroupKind: "Chunk Group" - }); - } - }, - "compilation.assetsByChunkName": () => "", - - "compilation.filteredModules": ( - filteredModules, - { compilation: { modules } } - ) => - filteredModules > 0 - ? `${moreCount(modules, filteredModules)} ${plural( - filteredModules, - "module", - "modules" - )}` - : undefined, - "compilation.filteredAssets": (filteredAssets, { compilation: { assets } }) => - filteredAssets > 0 - ? `${moreCount(assets, filteredAssets)} ${plural( - filteredAssets, - "asset", - "assets" - )}` - : undefined, - "compilation.logging": (logging, context, printer) => - Array.isArray(logging) - ? undefined - : printer.print( - context.type, - Object.entries(logging).map(([name, value]) => ({ ...value, name })), - context - ), - "compilation.warningsInChildren!": (_, { yellow, compilation }) => { - if ( - !compilation.children && - compilation.warningsCount > 0 && - compilation.warnings - ) { - const childWarnings = - compilation.warningsCount - compilation.warnings.length; - if (childWarnings > 0) { - return yellow( - `${childWarnings} ${plural( - childWarnings, - "WARNING", - "WARNINGS" - )} in child compilations${ - compilation.children - ? "" - : " (Use 'stats.children: true' resp. '--stats-children' for more details)" - }` - ); + }; + /** + * Reads n bytes + * @param {number} n amount of bytes to read + * @returns {Buffer} buffer with bytes + */ + const read = n => { + ensureBuffer(); + const rem = currentBuffer.length - currentPosition; + if (rem < n) { + const buffers = [read(rem)]; + n -= rem; + ensureBuffer(); + while (currentBuffer.length < n) { + const b = /** @type {Buffer} */ (currentBuffer); + buffers.push(b); + n -= b.length; + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); + ensureBuffer(); + } + buffers.push(read(n)); + return Buffer.concat(buffers); } - } - }, - "compilation.errorsInChildren!": (_, { red, compilation }) => { - if ( - !compilation.children && - compilation.errorsCount > 0 && - compilation.errors - ) { - const childErrors = compilation.errorsCount - compilation.errors.length; - if (childErrors > 0) { - return red( - `${childErrors} ${plural( - childErrors, - "ERROR", - "ERRORS" - )} in child compilations${ - compilation.children - ? "" - : " (Use 'stats.children: true' resp. '--stats-children' for more details)" - }` - ); + const b = /** @type {Buffer} */ (currentBuffer); + const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n); + currentPosition += n; + checkOverflow(); + return res; + }; + /** + * Reads up to n bytes + * @param {number} n amount of bytes to read + * @returns {Buffer} buffer with bytes + */ + const readUpTo = n => { + ensureBuffer(); + const rem = currentBuffer.length - currentPosition; + if (rem < n) { + n = rem; } - } - }, - - "asset.type": type => type, - "asset.name": (name, { formatFilename, asset: { isOverSizeLimit } }) => - formatFilename(name, isOverSizeLimit), - "asset.size": ( - size, - { asset: { isOverSizeLimit }, yellow, green, formatSize } - ) => (isOverSizeLimit ? yellow(formatSize(size)) : formatSize(size)), - "asset.emitted": (emitted, { green, formatFlag }) => - emitted ? green(formatFlag("emitted")) : undefined, - "asset.comparedForEmit": (comparedForEmit, { yellow, formatFlag }) => - comparedForEmit ? yellow(formatFlag("compared for emit")) : undefined, - "asset.cached": (cached, { green, formatFlag }) => - cached ? green(formatFlag("cached")) : undefined, - "asset.isOverSizeLimit": (isOverSizeLimit, { yellow, formatFlag }) => - isOverSizeLimit ? yellow(formatFlag("big")) : undefined, + const b = /** @type {Buffer} */ (currentBuffer); + const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n); + currentPosition += n; + checkOverflow(); + return res; + }; + const readU8 = () => { + ensureBuffer(); + /** + * There is no need to check remaining buffer size here + * since {@link checkOverflow} guarantees at least one byte remaining + */ + const byte = /** @type {Buffer} */ (currentBuffer).readUInt8( + currentPosition + ); + currentPosition += I8_SIZE; + checkOverflow(); + return byte; + }; + const readU32 = () => { + return read(I32_SIZE).readUInt32LE(0); + }; + const readBits = (data, n) => { + let mask = 1; + while (n !== 0) { + result.push((data & mask) !== 0); + mask = mask << 1; + n--; + } + }; + const dispatchTable = Array.from({ length: 256 }).map((_, header) => { + switch (header) { + case LAZY_HEADER: + return () => { + const count = readU32(); + const lengths = Array.from({ length: count }).map(() => readU32()); + const content = []; + for (let l of lengths) { + if (l === 0) { + if (typeof currentBuffer !== "function") { + throw new Error("Unexpected non-lazy element in stream"); + } + content.push(currentBuffer); + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); + } else { + do { + const buf = readUpTo(l); + l -= buf.length; + content.push(retainedBuffer(buf)); + } while (l > 0); + } + } + result.push(this._createLazyDeserialized(content, context)); + }; + case BUFFER_HEADER: + return () => { + const len = readU32(); + result.push(retainedBuffer(read(len))); + }; + case TRUE_HEADER: + return () => result.push(true); + case FALSE_HEADER: + return () => result.push(false); + case NULL3_HEADER: + return () => result.push(null, null, null); + case NULL2_HEADER: + return () => result.push(null, null); + case NULL_HEADER: + return () => result.push(null); + case NULL_AND_TRUE_HEADER: + return () => result.push(null, true); + case NULL_AND_FALSE_HEADER: + return () => result.push(null, false); + case NULL_AND_I8_HEADER: + return () => { + if (currentIsBuffer) { + result.push( + null, + /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition) + ); + currentPosition += I8_SIZE; + checkOverflow(); + } else { + result.push(null, read(I8_SIZE).readInt8(0)); + } + }; + case NULL_AND_I32_HEADER: + return () => { + result.push(null); + if (isInCurrentBuffer(I32_SIZE)) { + result.push( + /** @type {Buffer} */ (currentBuffer).readInt32LE( + currentPosition + ) + ); + currentPosition += I32_SIZE; + checkOverflow(); + } else { + result.push(read(I32_SIZE).readInt32LE(0)); + } + }; + case NULLS8_HEADER: + return () => { + const len = readU8() + 4; + for (let i = 0; i < len; i++) { + result.push(null); + } + }; + case NULLS32_HEADER: + return () => { + const len = readU32() + 260; + for (let i = 0; i < len; i++) { + result.push(null); + } + }; + case BOOLEANS_HEADER: + return () => { + const innerHeader = readU8(); + if ((innerHeader & 0xf0) === 0) { + readBits(innerHeader, 3); + } else if ((innerHeader & 0xe0) === 0) { + readBits(innerHeader, 4); + } else if ((innerHeader & 0xc0) === 0) { + readBits(innerHeader, 5); + } else if ((innerHeader & 0x80) === 0) { + readBits(innerHeader, 6); + } else if (innerHeader !== 0xff) { + let count = (innerHeader & 0x7f) + 7; + while (count > 8) { + readBits(readU8(), 8); + count -= 8; + } + readBits(readU8(), count); + } else { + let count = readU32(); + while (count > 8) { + readBits(readU8(), 8); + count -= 8; + } + readBits(readU8(), count); + } + }; + case STRING_HEADER: + return () => { + const len = readU32(); + if (isInCurrentBuffer(len) && currentPosition + len < 0x7fffffff) { + result.push( + currentBuffer.toString( + undefined, + currentPosition, + currentPosition + len + ) + ); + currentPosition += len; + checkOverflow(); + } else { + result.push(read(len).toString()); + } + }; + case SHORT_STRING_HEADER: + return () => result.push(""); + case SHORT_STRING_HEADER | 1: + return () => { + if (currentIsBuffer && currentPosition < 0x7ffffffe) { + result.push( + currentBuffer.toString( + "latin1", + currentPosition, + currentPosition + 1 + ) + ); + currentPosition++; + checkOverflow(); + } else { + result.push(read(1).toString("latin1")); + } + }; + case I8_HEADER: + return () => { + if (currentIsBuffer) { + result.push( + /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition) + ); + currentPosition++; + checkOverflow(); + } else { + result.push(read(1).readInt8(0)); + } + }; + default: + if (header <= 10) { + return () => result.push(header); + } else if ((header & SHORT_STRING_HEADER) === SHORT_STRING_HEADER) { + const len = header & SHORT_STRING_LENGTH_MASK; + return () => { + if ( + isInCurrentBuffer(len) && + currentPosition + len < 0x7fffffff + ) { + result.push( + currentBuffer.toString( + "latin1", + currentPosition, + currentPosition + len + ) + ); + currentPosition += len; + checkOverflow(); + } else { + result.push(read(len).toString("latin1")); + } + }; + } else if ((header & NUMBERS_HEADER_MASK) === F64_HEADER) { + const len = (header & NUMBERS_COUNT_MASK) + 1; + return () => { + const need = F64_SIZE * len; + if (isInCurrentBuffer(need)) { + for (let i = 0; i < len; i++) { + result.push( + /** @type {Buffer} */ (currentBuffer).readDoubleLE( + currentPosition + ) + ); + currentPosition += F64_SIZE; + } + checkOverflow(); + } else { + const buf = read(need); + for (let i = 0; i < len; i++) { + result.push(buf.readDoubleLE(i * F64_SIZE)); + } + } + }; + } else if ((header & NUMBERS_HEADER_MASK) === I32_HEADER) { + const len = (header & NUMBERS_COUNT_MASK) + 1; + return () => { + const need = I32_SIZE * len; + if (isInCurrentBuffer(need)) { + for (let i = 0; i < len; i++) { + result.push( + /** @type {Buffer} */ (currentBuffer).readInt32LE( + currentPosition + ) + ); + currentPosition += I32_SIZE; + } + checkOverflow(); + } else { + const buf = read(need); + for (let i = 0; i < len; i++) { + result.push(buf.readInt32LE(i * I32_SIZE)); + } + } + }; + } else if ((header & NUMBERS_HEADER_MASK) === I8_HEADER) { + const len = (header & NUMBERS_COUNT_MASK) + 1; + return () => { + const need = I8_SIZE * len; + if (isInCurrentBuffer(need)) { + for (let i = 0; i < len; i++) { + result.push( + /** @type {Buffer} */ (currentBuffer).readInt8( + currentPosition + ) + ); + currentPosition += I8_SIZE; + } + checkOverflow(); + } else { + const buf = read(need); + for (let i = 0; i < len; i++) { + result.push(buf.readInt8(i * I8_SIZE)); + } + } + }; + } else { + return () => { + throw new Error( + `Unexpected header byte 0x${header.toString(16)}` + ); + }; + } + } + }); - "asset.info.immutable": (immutable, { green, formatFlag }) => - immutable ? green(formatFlag("immutable")) : undefined, - "asset.info.javascriptModule": (javascriptModule, { formatFlag }) => - javascriptModule ? formatFlag("javascript module") : undefined, - "asset.info.sourceFilename": (sourceFilename, { formatFlag }) => - sourceFilename - ? formatFlag( - sourceFilename === true - ? "from source file" - : `from: ${sourceFilename}` - ) - : undefined, - "asset.info.development": (development, { green, formatFlag }) => - development ? green(formatFlag("dev")) : undefined, - "asset.info.hotModuleReplacement": ( - hotModuleReplacement, - { green, formatFlag } - ) => (hotModuleReplacement ? green(formatFlag("hmr")) : undefined), - "asset.separator!": () => "\n", - "asset.filteredRelated": (filteredRelated, { asset: { related } }) => - filteredRelated > 0 - ? `${moreCount(related, filteredRelated)} related ${plural( - filteredRelated, - "asset", - "assets" - )}` - : undefined, - "asset.filteredChildren": (filteredChildren, { asset: { children } }) => - filteredChildren > 0 - ? `${moreCount(children, filteredChildren)} ${plural( - filteredChildren, - "asset", - "assets" - )}` - : undefined, + /** @type {DeserializedType} */ + let result = []; + while (currentBuffer !== null) { + if (typeof currentBuffer === "function") { + result.push(this._deserializeLazy(currentBuffer, context)); + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); + } else { + const header = readU8(); + dispatchTable[header](); + } + } - assetChunk: (id, { formatChunkId }) => formatChunkId(id), + // avoid leaking memory in context + let _result = result; + result = undefined; + return _result; + } +} - assetChunkName: name => name, - assetChunkIdHint: name => name, +module.exports = BinaryMiddleware; - "module.type": type => (type !== "module" ? type : undefined), - "module.id": (id, { formatModuleId }) => - isValidId(id) ? formatModuleId(id) : undefined, - "module.name": (name, { bold }) => { - const [prefix, resource] = getModuleName(name); - return `${prefix || ""}${bold(resource || "")}`; - }, - "module.identifier": identifier => undefined, - "module.layer": (layer, { formatLayer }) => - layer ? formatLayer(layer) : undefined, - "module.sizes": printSizes, - "module.chunks[]": (id, { formatChunkId }) => formatChunkId(id), - "module.depth": (depth, { formatFlag }) => - depth !== null ? formatFlag(`depth ${depth}`) : undefined, - "module.cacheable": (cacheable, { formatFlag, red }) => - cacheable === false ? red(formatFlag("not cacheable")) : undefined, - "module.orphan": (orphan, { formatFlag, yellow }) => - orphan ? yellow(formatFlag("orphan")) : undefined, - "module.runtime": (runtime, { formatFlag, yellow }) => - runtime ? yellow(formatFlag("runtime")) : undefined, - "module.optional": (optional, { formatFlag, yellow }) => - optional ? yellow(formatFlag("optional")) : undefined, - "module.dependent": (dependent, { formatFlag, cyan }) => - dependent ? cyan(formatFlag("dependent")) : undefined, - "module.built": (built, { formatFlag, yellow }) => - built ? yellow(formatFlag("built")) : undefined, - "module.codeGenerated": (codeGenerated, { formatFlag, yellow }) => - codeGenerated ? yellow(formatFlag("code generated")) : undefined, - "module.buildTimeExecuted": (buildTimeExecuted, { formatFlag, green }) => - buildTimeExecuted ? green(formatFlag("build time executed")) : undefined, - "module.cached": (cached, { formatFlag, green }) => - cached ? green(formatFlag("cached")) : undefined, - "module.assets": (assets, { formatFlag, magenta }) => - assets && assets.length - ? magenta( - formatFlag( - `${assets.length} ${plural(assets.length, "asset", "assets")}` - ) - ) - : undefined, - "module.warnings": (warnings, { formatFlag, yellow }) => - warnings === true - ? yellow(formatFlag("warnings")) - : warnings - ? yellow( - formatFlag(`${warnings} ${plural(warnings, "warning", "warnings")}`) - ) - : undefined, - "module.errors": (errors, { formatFlag, red }) => - errors === true - ? red(formatFlag("errors")) - : errors - ? red(formatFlag(`${errors} ${plural(errors, "error", "errors")}`)) - : undefined, - "module.providedExports": (providedExports, { formatFlag, cyan }) => { - if (Array.isArray(providedExports)) { - if (providedExports.length === 0) return cyan(formatFlag("no exports")); - return cyan(formatFlag(`exports: ${providedExports.join(", ")}`)); - } - }, - "module.usedExports": (usedExports, { formatFlag, cyan, module }) => { - if (usedExports !== true) { - if (usedExports === null) return cyan(formatFlag("used exports unknown")); - if (usedExports === false) return cyan(formatFlag("module unused")); - if (Array.isArray(usedExports)) { - if (usedExports.length === 0) - return cyan(formatFlag("no exports used")); - const providedExportsCount = Array.isArray(module.providedExports) - ? module.providedExports.length - : null; - if ( - providedExportsCount !== null && - providedExportsCount === usedExports.length - ) { - return cyan(formatFlag("all exports used")); - } else { - return cyan( - formatFlag(`only some exports used: ${usedExports.join(", ")}`) - ); - } - } - } - }, - "module.optimizationBailout[]": (optimizationBailout, { yellow }) => - yellow(optimizationBailout), - "module.issuerPath": (issuerPath, { module }) => - module.profile ? undefined : "", - "module.profile": profile => undefined, - "module.filteredModules": (filteredModules, { module: { modules } }) => - filteredModules > 0 - ? `${moreCount(modules, filteredModules)} nested ${plural( - filteredModules, - "module", - "modules" - )}` - : undefined, - "module.filteredReasons": (filteredReasons, { module: { reasons } }) => - filteredReasons > 0 - ? `${moreCount(reasons, filteredReasons)} ${plural( - filteredReasons, - "reason", - "reasons" - )}` - : undefined, - "module.filteredChildren": (filteredChildren, { module: { children } }) => - filteredChildren > 0 - ? `${moreCount(children, filteredChildren)} ${plural( - filteredChildren, - "module", - "modules" - )}` - : undefined, - "module.separator!": () => "\n", +module.exports.MEASURE_START_OPERATION = MEASURE_START_OPERATION; +module.exports.MEASURE_END_OPERATION = MEASURE_END_OPERATION; - "moduleIssuer.id": (id, { formatModuleId }) => formatModuleId(id), - "moduleIssuer.profile.total": (value, { formatTime }) => formatTime(value), - "moduleReason.type": type => type, - "moduleReason.userRequest": (userRequest, { cyan }) => - cyan(getResourceName(userRequest)), - "moduleReason.moduleId": (moduleId, { formatModuleId }) => - isValidId(moduleId) ? formatModuleId(moduleId) : undefined, - "moduleReason.module": (module, { magenta }) => magenta(module), - "moduleReason.loc": loc => loc, - "moduleReason.explanation": (explanation, { cyan }) => cyan(explanation), - "moduleReason.active": (active, { formatFlag }) => - active ? undefined : formatFlag("inactive"), - "moduleReason.resolvedModule": (module, { magenta }) => magenta(module), - "moduleReason.filteredChildren": ( - filteredChildren, - { moduleReason: { children } } - ) => - filteredChildren > 0 - ? `${moreCount(children, filteredChildren)} ${plural( - filteredChildren, - "reason", - "reasons" - )}` - : undefined, +/***/ }), - "module.profile.total": (value, { formatTime }) => formatTime(value), - "module.profile.resolving": (value, { formatTime }) => - `resolving: ${formatTime(value)}`, - "module.profile.restoring": (value, { formatTime }) => - `restoring: ${formatTime(value)}`, - "module.profile.integration": (value, { formatTime }) => - `integration: ${formatTime(value)}`, - "module.profile.building": (value, { formatTime }) => - `building: ${formatTime(value)}`, - "module.profile.storing": (value, { formatTime }) => - `storing: ${formatTime(value)}`, - "module.profile.additionalResolving": (value, { formatTime }) => - value ? `additional resolving: ${formatTime(value)}` : undefined, - "module.profile.additionalIntegration": (value, { formatTime }) => - value ? `additional integration: ${formatTime(value)}` : undefined, +/***/ 93475: +/***/ (function(module) { - "chunkGroup.kind!": (_, { chunkGroupKind }) => chunkGroupKind, - "chunkGroup.separator!": () => "\n", - "chunkGroup.name": (name, { bold }) => bold(name), - "chunkGroup.isOverSizeLimit": (isOverSizeLimit, { formatFlag, yellow }) => - isOverSizeLimit ? yellow(formatFlag("big")) : undefined, - "chunkGroup.assetsSize": (size, { formatSize }) => - size ? formatSize(size) : undefined, - "chunkGroup.auxiliaryAssetsSize": (size, { formatSize }) => - size ? `(${formatSize(size)})` : undefined, - "chunkGroup.filteredAssets": (n, { chunkGroup: { assets } }) => - n > 0 - ? `${moreCount(assets, n)} ${plural(n, "asset", "assets")}` - : undefined, - "chunkGroup.filteredAuxiliaryAssets": ( - n, - { chunkGroup: { auxiliaryAssets } } - ) => - n > 0 - ? `${moreCount(auxiliaryAssets, n)} auxiliary ${plural( - n, - "asset", - "assets" - )}` - : undefined, - "chunkGroup.is!": () => "=", - "chunkGroupAsset.name": (asset, { green }) => green(asset), - "chunkGroupAsset.size": (size, { formatSize, chunkGroup }) => - chunkGroup.assets.length > 1 || - (chunkGroup.auxiliaryAssets && chunkGroup.auxiliaryAssets.length > 0) - ? formatSize(size) - : undefined, - "chunkGroup.children": (children, context, printer) => - Array.isArray(children) - ? undefined - : printer.print( - context.type, - Object.keys(children).map(key => ({ - type: key, - children: children[key] - })), - context - ), - "chunkGroupChildGroup.type": type => `${type}:`, - "chunkGroupChild.assets[]": (file, { formatFilename }) => - formatFilename(file), - "chunkGroupChild.chunks[]": (id, { formatChunkId }) => formatChunkId(id), - "chunkGroupChild.name": name => (name ? `(name: ${name})` : undefined), +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - "chunk.id": (id, { formatChunkId }) => formatChunkId(id), - "chunk.files[]": (file, { formatFilename }) => formatFilename(file), - "chunk.names[]": name => name, - "chunk.idHints[]": name => name, - "chunk.runtime[]": name => name, - "chunk.sizes": (sizes, context) => printSizes(sizes, context), - "chunk.parents[]": (parents, context) => - context.formatChunkId(parents, "parent"), - "chunk.siblings[]": (siblings, context) => - context.formatChunkId(siblings, "sibling"), - "chunk.children[]": (children, context) => - context.formatChunkId(children, "child"), - "chunk.childrenByOrder": (childrenByOrder, context, printer) => - Array.isArray(childrenByOrder) - ? undefined - : printer.print( - context.type, - Object.keys(childrenByOrder).map(key => ({ - type: key, - children: childrenByOrder[key] - })), - context - ), - "chunk.childrenByOrder[].type": type => `${type}:`, - "chunk.childrenByOrder[].children[]": (id, { formatChunkId }) => - isValidId(id) ? formatChunkId(id) : undefined, - "chunk.entry": (entry, { formatFlag, yellow }) => - entry ? yellow(formatFlag("entry")) : undefined, - "chunk.initial": (initial, { formatFlag, yellow }) => - initial ? yellow(formatFlag("initial")) : undefined, - "chunk.rendered": (rendered, { formatFlag, green }) => - rendered ? green(formatFlag("rendered")) : undefined, - "chunk.recorded": (recorded, { formatFlag, green }) => - recorded ? green(formatFlag("recorded")) : undefined, - "chunk.reason": (reason, { yellow }) => (reason ? yellow(reason) : undefined), - "chunk.filteredModules": (filteredModules, { chunk: { modules } }) => - filteredModules > 0 - ? `${moreCount(modules, filteredModules)} chunk ${plural( - filteredModules, - "module", - "modules" - )}` - : undefined, - "chunk.separator!": () => "\n", - "chunkOrigin.request": request => request, - "chunkOrigin.moduleId": (moduleId, { formatModuleId }) => - isValidId(moduleId) ? formatModuleId(moduleId) : undefined, - "chunkOrigin.moduleName": (moduleName, { bold }) => bold(moduleName), - "chunkOrigin.loc": loc => loc, - "error.compilerPath": (compilerPath, { bold }) => - compilerPath ? bold(`(${compilerPath})`) : undefined, - "error.chunkId": (chunkId, { formatChunkId }) => - isValidId(chunkId) ? formatChunkId(chunkId) : undefined, - "error.chunkEntry": (chunkEntry, { formatFlag }) => - chunkEntry ? formatFlag("entry") : undefined, - "error.chunkInitial": (chunkInitial, { formatFlag }) => - chunkInitial ? formatFlag("initial") : undefined, - "error.file": (file, { bold }) => bold(file), - "error.moduleName": (moduleName, { bold }) => { - return moduleName.includes("!") - ? `${bold(moduleName.replace(/^(\s|\S)*!/, ""))} (${moduleName})` - : `${bold(moduleName)}`; - }, - "error.loc": (loc, { green }) => green(loc), - "error.message": (message, { bold, formatError }) => - message.includes("\u001b[") ? message : bold(formatError(message)), - "error.details": (details, { formatError }) => formatError(details), - "error.stack": stack => stack, - "error.moduleTrace": moduleTrace => undefined, - "error.separator!": () => "\n", +class DateObjectSerializer { + serialize(obj, { write }) { + write(obj.getTime()); + } + deserialize({ read }) { + return new Date(read()); + } +} - "loggingEntry(error).loggingEntry.message": (message, { red }) => - mapLines(message, x => ` ${red(x)}`), - "loggingEntry(warn).loggingEntry.message": (message, { yellow }) => - mapLines(message, x => ` ${yellow(x)}`), - "loggingEntry(info).loggingEntry.message": (message, { green }) => - mapLines(message, x => ` ${green(x)}`), - "loggingEntry(log).loggingEntry.message": (message, { bold }) => - mapLines(message, x => ` ${bold(x)}`), - "loggingEntry(debug).loggingEntry.message": message => - mapLines(message, x => ` ${x}`), - "loggingEntry(trace).loggingEntry.message": message => - mapLines(message, x => ` ${x}`), - "loggingEntry(status).loggingEntry.message": (message, { magenta }) => - mapLines(message, x => ` ${magenta(x)}`), - "loggingEntry(profile).loggingEntry.message": (message, { magenta }) => - mapLines(message, x => `

${magenta(x)}`), - "loggingEntry(profileEnd).loggingEntry.message": (message, { magenta }) => - mapLines(message, x => `

${magenta(x)}`), - "loggingEntry(time).loggingEntry.message": (message, { magenta }) => - mapLines(message, x => ` ${magenta(x)}`), - "loggingEntry(group).loggingEntry.message": (message, { cyan }) => - mapLines(message, x => `<-> ${cyan(x)}`), - "loggingEntry(groupCollapsed).loggingEntry.message": (message, { cyan }) => - mapLines(message, x => `<+> ${cyan(x)}`), - "loggingEntry(clear).loggingEntry": () => " -------", - "loggingEntry(groupCollapsed).loggingEntry.children": () => "", - "loggingEntry.trace[]": trace => - trace ? mapLines(trace, x => `| ${x}`) : undefined, +module.exports = DateObjectSerializer; - "moduleTraceItem.originName": originName => originName, - loggingGroup: loggingGroup => - loggingGroup.entries.length === 0 ? "" : undefined, - "loggingGroup.debug": (flag, { red }) => (flag ? red("DEBUG") : undefined), - "loggingGroup.name": (name, { bold }) => bold(`LOG from ${name}`), - "loggingGroup.separator!": () => "\n", - "loggingGroup.filteredEntries": filteredEntries => - filteredEntries > 0 ? `+ ${filteredEntries} hidden lines` : undefined, +/***/ }), - "moduleTraceDependency.loc": loc => loc -}; +/***/ 79479: +/***/ (function(module) { -/** @type {Record} */ -const ITEM_NAMES = { - "compilation.assets[]": "asset", - "compilation.modules[]": "module", - "compilation.chunks[]": "chunk", - "compilation.entrypoints[]": "chunkGroup", - "compilation.namedChunkGroups[]": "chunkGroup", - "compilation.errors[]": "error", - "compilation.warnings[]": "error", - "compilation.logging[]": "loggingGroup", - "compilation.children[]": "compilation", - "asset.related[]": "asset", - "asset.children[]": "asset", - "asset.chunks[]": "assetChunk", - "asset.auxiliaryChunks[]": "assetChunk", - "asset.chunkNames[]": "assetChunkName", - "asset.chunkIdHints[]": "assetChunkIdHint", - "asset.auxiliaryChunkNames[]": "assetChunkName", - "asset.auxiliaryChunkIdHints[]": "assetChunkIdHint", - "chunkGroup.assets[]": "chunkGroupAsset", - "chunkGroup.auxiliaryAssets[]": "chunkGroupAsset", - "chunkGroupChild.assets[]": "chunkGroupAsset", - "chunkGroupChild.auxiliaryAssets[]": "chunkGroupAsset", - "chunkGroup.children[]": "chunkGroupChildGroup", - "chunkGroupChildGroup.children[]": "chunkGroupChild", - "module.modules[]": "module", - "module.children[]": "module", - "module.reasons[]": "moduleReason", - "moduleReason.children[]": "moduleReason", - "module.issuerPath[]": "moduleIssuer", - "chunk.origins[]": "chunkOrigin", - "chunk.modules[]": "module", - "loggingGroup.entries[]": logEntry => - `loggingEntry(${logEntry.type}).loggingEntry`, - "loggingEntry.children[]": logEntry => - `loggingEntry(${logEntry.type}).loggingEntry`, - "error.moduleTrace[]": "moduleTraceItem", - "moduleTraceItem.dependencies[]": "moduleTraceDependency" -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ -const ERROR_PREFERRED_ORDER = [ - "compilerPath", - "chunkId", - "chunkEntry", - "chunkInitial", - "file", - "separator!", - "moduleName", - "loc", - "separator!", - "message", - "separator!", - "details", - "separator!", - "stack", - "separator!", - "missing", - "separator!", - "moduleTrace" -]; -/** @type {Record} */ -const PREFERRED_ORDERS = { - compilation: [ - "name", - "hash", - "version", - "time", - "builtAt", - "env", - "publicPath", - "assets", - "filteredAssets", - "entrypoints", - "namedChunkGroups", - "chunks", - "modules", - "filteredModules", - "children", - "logging", - "warnings", - "warningsInChildren!", - "filteredWarningDetailsCount", - "errors", - "errorsInChildren!", - "filteredErrorDetailsCount", - "summary!", - "needAdditionalPass" - ], - asset: [ - "type", - "name", - "size", - "chunks", - "auxiliaryChunks", - "emitted", - "comparedForEmit", - "cached", - "info", - "isOverSizeLimit", - "chunkNames", - "auxiliaryChunkNames", - "chunkIdHints", - "auxiliaryChunkIdHints", - "related", - "filteredRelated", - "children", - "filteredChildren" - ], - "asset.info": [ - "immutable", - "sourceFilename", - "javascriptModule", - "development", - "hotModuleReplacement" - ], - chunkGroup: [ - "kind!", - "name", - "isOverSizeLimit", - "assetsSize", - "auxiliaryAssetsSize", - "is!", - "assets", - "filteredAssets", - "auxiliaryAssets", - "filteredAuxiliaryAssets", - "separator!", - "children" - ], - chunkGroupAsset: ["name", "size"], - chunkGroupChildGroup: ["type", "children"], - chunkGroupChild: ["assets", "chunks", "name"], - module: [ - "type", - "name", - "identifier", - "id", - "layer", - "sizes", - "chunks", - "depth", - "cacheable", - "orphan", - "runtime", - "optional", - "dependent", - "built", - "codeGenerated", - "cached", - "assets", - "failed", - "warnings", - "errors", - "children", - "filteredChildren", - "providedExports", - "usedExports", - "optimizationBailout", - "reasons", - "filteredReasons", - "issuerPath", - "profile", - "modules", - "filteredModules" - ], - moduleReason: [ - "active", - "type", - "userRequest", - "moduleId", - "module", - "resolvedModule", - "loc", - "explanation", - "children", - "filteredChildren" - ], - "module.profile": [ - "total", - "separator!", - "resolving", - "restoring", - "integration", - "building", - "storing", - "additionalResolving", - "additionalIntegration" - ], - chunk: [ - "id", - "runtime", - "files", - "names", - "idHints", - "sizes", - "parents", - "siblings", - "children", - "childrenByOrder", - "entry", - "initial", - "rendered", - "recorded", - "reason", - "separator!", - "origins", - "separator!", - "modules", - "separator!", - "filteredModules" - ], - chunkOrigin: ["request", "moduleId", "moduleName", "loc"], - error: ERROR_PREFERRED_ORDER, - warning: ERROR_PREFERRED_ORDER, - "chunk.childrenByOrder[]": ["type", "children"], - loggingGroup: [ - "debug", - "name", - "separator!", - "entries", - "separator!", - "filteredEntries" - ], - loggingEntry: ["message", "trace", "children"] -}; -const itemsJoinOneLine = items => items.filter(Boolean).join(" "); -const itemsJoinOneLineBrackets = items => - items.length > 0 ? `(${items.filter(Boolean).join(" ")})` : undefined; -const itemsJoinMoreSpacing = items => items.filter(Boolean).join("\n\n"); -const itemsJoinComma = items => items.filter(Boolean).join(", "); -const itemsJoinCommaBrackets = items => - items.length > 0 ? `(${items.filter(Boolean).join(", ")})` : undefined; -const itemsJoinCommaBracketsWithName = name => items => - items.length > 0 - ? `(${name}: ${items.filter(Boolean).join(", ")})` - : undefined; +class ErrorObjectSerializer { + constructor(Type) { + this.Type = Type; + } -/** @type {Record string>} */ -const SIMPLE_ITEMS_JOINER = { - "chunk.parents": itemsJoinOneLine, - "chunk.siblings": itemsJoinOneLine, - "chunk.children": itemsJoinOneLine, - "chunk.names": itemsJoinCommaBrackets, - "chunk.idHints": itemsJoinCommaBracketsWithName("id hint"), - "chunk.runtime": itemsJoinCommaBracketsWithName("runtime"), - "chunk.files": itemsJoinComma, - "chunk.childrenByOrder": itemsJoinOneLine, - "chunk.childrenByOrder[].children": itemsJoinOneLine, - "chunkGroup.assets": itemsJoinOneLine, - "chunkGroup.auxiliaryAssets": itemsJoinOneLineBrackets, - "chunkGroupChildGroup.children": itemsJoinComma, - "chunkGroupChild.assets": itemsJoinOneLine, - "chunkGroupChild.auxiliaryAssets": itemsJoinOneLineBrackets, - "asset.chunks": itemsJoinComma, - "asset.auxiliaryChunks": itemsJoinCommaBrackets, - "asset.chunkNames": itemsJoinCommaBracketsWithName("name"), - "asset.auxiliaryChunkNames": itemsJoinCommaBracketsWithName("auxiliary name"), - "asset.chunkIdHints": itemsJoinCommaBracketsWithName("id hint"), - "asset.auxiliaryChunkIdHints": - itemsJoinCommaBracketsWithName("auxiliary id hint"), - "module.chunks": itemsJoinOneLine, - "module.issuerPath": items => - items - .filter(Boolean) - .map(item => `${item} ->`) - .join(" "), - "compilation.errors": itemsJoinMoreSpacing, - "compilation.warnings": itemsJoinMoreSpacing, - "compilation.logging": itemsJoinMoreSpacing, - "compilation.children": items => indent(itemsJoinMoreSpacing(items), " "), - "moduleTraceItem.dependencies": itemsJoinOneLine, - "loggingEntry.children": items => - indent(items.filter(Boolean).join("\n"), " ", false) -}; + serialize(obj, { write }) { + write(obj.message); + write(obj.stack); + } -const joinOneLine = items => - items - .map(item => item.content) - .filter(Boolean) - .join(" "); + deserialize({ read }) { + const err = new this.Type(); -const joinInBrackets = items => { - const res = []; - let mode = 0; - for (const item of items) { - if (item.element === "separator!") { - switch (mode) { - case 0: - case 1: - mode += 2; - break; - case 4: - res.push(")"); - mode = 3; - break; - } - } - if (!item.content) continue; - switch (mode) { - case 0: - mode = 1; - break; - case 1: - res.push(" "); - break; - case 2: - res.push("("); - mode = 4; - break; - case 3: - res.push(" ("); - mode = 4; - break; - case 4: - res.push(", "); - break; - } - res.push(item.content); + err.message = read(); + err.stack = read(); + + return err; } - if (mode === 4) res.push(")"); - return res.join(""); -}; +} -const indent = (str, prefix, noPrefixInFirstLine) => { - const rem = str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); - if (noPrefixInFirstLine) return rem; - const ind = str[0] === "\n" ? "" : prefix; - return ind + rem; -}; +module.exports = ErrorObjectSerializer; -const joinExplicitNewLine = (items, indenter) => { - let firstInLine = true; - let first = true; - return items - .map(item => { - if (!item || !item.content) return; - let content = indent(item.content, first ? "" : indenter, !firstInLine); - if (firstInLine) { - content = content.replace(/^\n+/, ""); - } - if (!content) return; - first = false; - const noJoiner = firstInLine || content.startsWith("\n"); - firstInLine = content.endsWith("\n"); - return noJoiner ? content : " " + content; - }) - .filter(Boolean) - .join("") - .trim(); + +/***/ }), + +/***/ 65321: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const { constants } = __webpack_require__(14300); +const { pipeline } = __webpack_require__(12781); +const { + createBrotliCompress, + createBrotliDecompress, + createGzip, + createGunzip, + constants: zConstants +} = __webpack_require__(59796); +const createHash = __webpack_require__(49835); +const { dirname, join, mkdirp } = __webpack_require__(17139); +const memoize = __webpack_require__(78676); +const SerializerMiddleware = __webpack_require__(83137); + +/** @typedef {typeof import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ +/** @typedef {import("./types").BufferSerializableType} BufferSerializableType */ + +/* +Format: + +File -> Header Section* + +Version -> u32 +AmountOfSections -> u32 +SectionSize -> i32 (if less than zero represents lazy value) + +Header -> Version AmountOfSections SectionSize* + +Buffer -> n bytes +Section -> Buffer + +*/ + +// "wpc" + 1 in little-endian +const VERSION = 0x01637077; + +/** + * @param {Buffer[]} buffers buffers + * @param {string | Hash} hashFunction hash function to use + * @returns {string} hash + */ +const hashForName = (buffers, hashFunction) => { + const hash = createHash(hashFunction); + for (const buf of buffers) hash.update(buf); + return /** @type {string} */ (hash.digest("hex")); }; -const joinError = - error => - (items, { red, yellow }) => - `${error ? red("ERROR") : yellow("WARNING")} in ${joinExplicitNewLine( - items, - "" - )}`; +const COMPRESSION_CHUNK_SIZE = 100 * 1024 * 1024; +const DECOMPRESSION_CHUNK_SIZE = 100 * 1024 * 1024; -/** @type {Record string>} */ -const SIMPLE_ELEMENT_JOINERS = { - compilation: items => { - const result = []; - let lastNeedMore = false; - for (const item of items) { - if (!item.content) continue; - const needMoreSpace = - item.element === "warnings" || - item.element === "filteredWarningDetailsCount" || - item.element === "errors" || - item.element === "filteredErrorDetailsCount" || - item.element === "logging"; - if (result.length !== 0) { - result.push(needMoreSpace || lastNeedMore ? "\n\n" : "\n"); +const writeUInt64LE = Buffer.prototype.writeBigUInt64LE + ? (buf, value, offset) => { + buf.writeBigUInt64LE(BigInt(value), offset); + } + : (buf, value, offset) => { + const low = value % 0x100000000; + const high = (value - low) / 0x100000000; + buf.writeUInt32LE(low, offset); + buf.writeUInt32LE(high, offset + 4); + }; + +const readUInt64LE = Buffer.prototype.readBigUInt64LE + ? (buf, offset) => { + return Number(buf.readBigUInt64LE(offset)); + } + : (buf, offset) => { + const low = buf.readUInt32LE(offset); + const high = buf.readUInt32LE(offset + 4); + return high * 0x100000000 + low; + }; + +/** + * @typedef {Object} SerializeResult + * @property {string | false} name + * @property {number} size + * @property {Promise=} backgroundJob + */ + +/** + * @param {FileMiddleware} middleware this + * @param {BufferSerializableType[] | Promise} data data to be serialized + * @param {string | boolean} name file base name + * @param {function(string | false, Buffer[]): Promise} writeFile writes a file + * @param {string | Hash} hashFunction hash function to use + * @returns {Promise} resulting file pointer and promise + */ +const serialize = async ( + middleware, + data, + name, + writeFile, + hashFunction = "md4" +) => { + /** @type {(Buffer[] | Buffer | SerializeResult | Promise)[]} */ + const processedData = []; + /** @type {WeakMap>} */ + const resultToLazy = new WeakMap(); + /** @type {Buffer[]} */ + let lastBuffers = undefined; + for (const item of await data) { + if (typeof item === "function") { + if (!SerializerMiddleware.isLazy(item)) + throw new Error("Unexpected function"); + if (!SerializerMiddleware.isLazy(item, middleware)) { + throw new Error( + "Unexpected lazy value with non-this target (can't pass through lazy values)" + ); } - result.push(item.content); - lastNeedMore = needMoreSpace; - } - if (lastNeedMore) result.push("\n"); - return result.join(""); - }, - asset: items => - joinExplicitNewLine( - items.map(item => { - if ( - (item.element === "related" || item.element === "children") && - item.content - ) { - return { - ...item, - content: `\n${item.content}\n` - }; + lastBuffers = undefined; + const serializedInfo = SerializerMiddleware.getLazySerializedValue(item); + if (serializedInfo) { + if (typeof serializedInfo === "function") { + throw new Error( + "Unexpected lazy value with non-this target (can't pass through lazy values)" + ); + } else { + processedData.push(serializedInfo); } - return item; - }), - " " - ), - "asset.info": joinOneLine, - module: (items, { module }) => { - let hasName = false; - return joinExplicitNewLine( - items.map(item => { - switch (item.element) { - case "id": - if (module.id === module.name) { - if (hasName) return false; - if (item.content) hasName = true; - } - break; - case "name": - if (hasName) return false; - if (item.content) hasName = true; - break; - case "providedExports": - case "usedExports": - case "optimizationBailout": - case "reasons": - case "issuerPath": - case "profile": - case "children": - case "modules": - if (item.content) { - return { - ...item, - content: `\n${item.content}\n` - }; - } - break; + } else { + const content = item(); + if (content) { + const options = SerializerMiddleware.getLazyOptions(item); + processedData.push( + serialize( + middleware, + content, + (options && options.name) || true, + writeFile, + hashFunction + ).then(result => { + /** @type {any} */ (item).options.size = result.size; + resultToLazy.set(result, item); + return result; + }) + ); + } else { + throw new Error( + "Unexpected falsy value returned by lazy value function" + ); } - return item; - }), - " " - ); - }, - chunk: items => { - let hasEntry = false; - return ( - "chunk " + - joinExplicitNewLine( - items.filter(item => { - switch (item.element) { - case "entry": - if (item.content) hasEntry = true; - break; - case "initial": - if (hasEntry) return false; - break; - } - return true; - }), - " " + } + } else if (item) { + if (lastBuffers) { + lastBuffers.push(item); + } else { + lastBuffers = [item]; + processedData.push(lastBuffers); + } + } else { + throw new Error("Unexpected falsy value in items array"); + } + } + /** @type {Promise[]} */ + const backgroundJobs = []; + const resolvedData = ( + await Promise.all( + /** @type {Promise[]} */ ( + processedData ) - ); - }, - "chunk.childrenByOrder[]": items => `(${joinOneLine(items)})`, - chunkGroup: items => joinExplicitNewLine(items, " "), - chunkGroupAsset: joinOneLine, - chunkGroupChildGroup: joinOneLine, - chunkGroupChild: joinOneLine, - // moduleReason: (items, { moduleReason }) => { - // let hasName = false; - // return joinOneLine( - // items.filter(item => { - // switch (item.element) { - // case "moduleId": - // if (moduleReason.moduleId === moduleReason.module && item.content) - // hasName = true; - // break; - // case "module": - // if (hasName) return false; - // break; - // case "resolvedModule": - // return ( - // moduleReason.module !== moduleReason.resolvedModule && - // item.content - // ); - // } - // return true; - // }) - // ); - // }, - moduleReason: (items, { moduleReason }) => { - let hasName = false; - return joinExplicitNewLine( - items.map(item => { - switch (item.element) { - case "moduleId": - if (moduleReason.moduleId === moduleReason.module && item.content) - hasName = true; - break; - case "module": - if (hasName) return false; - break; - case "resolvedModule": - if (moduleReason.module === moduleReason.resolvedModule) - return false; - break; - case "children": - if (item.content) { - return { - ...item, - content: `\n${item.content}\n` - }; - } - break; - } - return item; - }), - " " - ); - }, - "module.profile": joinInBrackets, - moduleIssuer: joinOneLine, - chunkOrigin: items => "> " + joinOneLine(items), - "errors[].error": joinError(true), - "warnings[].error": joinError(false), - loggingGroup: items => joinExplicitNewLine(items, "").trimRight(), - moduleTraceItem: items => " @ " + joinOneLine(items), - moduleTraceDependency: joinOneLine -}; - -const AVAILABLE_COLORS = { - bold: "\u001b[1m", - yellow: "\u001b[1m\u001b[33m", - red: "\u001b[1m\u001b[31m", - green: "\u001b[1m\u001b[32m", - cyan: "\u001b[1m\u001b[36m", - magenta: "\u001b[1m\u001b[35m" -}; + ) + ).map(item => { + if (Array.isArray(item) || Buffer.isBuffer(item)) return item; -const AVAILABLE_FORMATS = { - formatChunkId: (id, { yellow }, direction) => { - switch (direction) { - case "parent": - return `<{${yellow(id)}}>`; - case "sibling": - return `={${yellow(id)}}=`; - case "child": - return `>{${yellow(id)}}<`; - default: - return `{${yellow(id)}}`; - } - }, - formatModuleId: id => `[${id}]`, - formatFilename: (filename, { green, yellow }, oversize) => - (oversize ? yellow : green)(filename), - formatFlag: flag => `[${flag}]`, - formatLayer: layer => `(in ${layer})`, - formatSize: (__webpack_require__(71070).formatSize), - formatDateTime: (dateTime, { bold }) => { - const d = new Date(dateTime); - const x = twoDigit; - const date = `${d.getFullYear()}-${x(d.getMonth() + 1)}-${x(d.getDate())}`; - const time = `${x(d.getHours())}:${x(d.getMinutes())}:${x(d.getSeconds())}`; - return `${date} ${bold(time)}`; - }, - formatTime: ( - time, - { timeReference, bold, green, yellow, red }, - boldQuantity - ) => { - const unit = " ms"; - if (timeReference && time !== timeReference) { - const times = [ - timeReference / 2, - timeReference / 4, - timeReference / 8, - timeReference / 16 - ]; - if (time < times[3]) return `${time}${unit}`; - else if (time < times[2]) return bold(`${time}${unit}`); - else if (time < times[1]) return green(`${time}${unit}`); - else if (time < times[0]) return yellow(`${time}${unit}`); - else return red(`${time}${unit}`); + backgroundJobs.push(item.backgroundJob); + // create pointer buffer from size and name + const name = /** @type {string} */ (item.name); + const nameBuffer = Buffer.from(name); + const buf = Buffer.allocUnsafe(8 + nameBuffer.length); + writeUInt64LE(buf, item.size, 0); + nameBuffer.copy(buf, 8, 0); + const lazy = resultToLazy.get(item); + SerializerMiddleware.setLazySerializedValue(lazy, buf); + return buf; + }); + const lengths = []; + for (const item of resolvedData) { + if (Array.isArray(item)) { + let l = 0; + for (const b of item) l += b.length; + while (l > 0x7fffffff) { + lengths.push(0x7fffffff); + l -= 0x7fffffff; + } + lengths.push(l); + } else if (item) { + lengths.push(-item.length); } else { - return `${boldQuantity ? bold(time) : time}${unit}`; + throw new Error("Unexpected falsy value in resolved data " + item); } - }, - formatError: (message, { green, yellow, red }) => { - if (message.includes("\u001b[")) return message; - const highlights = [ - { regExp: /(Did you mean .+)/g, format: green }, - { - regExp: /(Set 'mode' option to 'development' or 'production')/g, - format: green - }, - { regExp: /(\(module has no exports\))/g, format: red }, - { regExp: /\(possible exports: (.+)\)/g, format: green }, - { regExp: /(?:^|\n)(.* doesn't exist)/g, format: red }, - { regExp: /('\w+' option has not been set)/g, format: red }, - { - regExp: /(Emitted value instead of an instance of Error)/g, - format: yellow - }, - { regExp: /(Used? .+ instead)/gi, format: yellow }, - { regExp: /\b(deprecated|must|required)\b/g, format: yellow }, - { - regExp: /\b(BREAKING CHANGE)\b/gi, - format: red - }, - { - regExp: - /\b(error|failed|unexpected|invalid|not found|not supported|not available|not possible|not implemented|doesn't support|conflict|conflicting|not existing|duplicate)\b/gi, - format: red - } - ]; - for (const { regExp, format } of highlights) { - message = message.replace(regExp, (match, content) => { - return match.replace(content, format(content)); - }); + } + const header = Buffer.allocUnsafe(8 + lengths.length * 4); + header.writeUInt32LE(VERSION, 0); + header.writeUInt32LE(lengths.length, 4); + for (let i = 0; i < lengths.length; i++) { + header.writeInt32LE(lengths[i], 8 + i * 4); + } + const buf = [header]; + for (const item of resolvedData) { + if (Array.isArray(item)) { + for (const b of item) buf.push(b); + } else if (item) { + buf.push(item); } - return message; } + if (name === true) { + name = hashForName(buf, hashFunction); + } + backgroundJobs.push(writeFile(name, buf)); + let size = 0; + for (const b of buf) size += b.length; + return { + size, + name, + backgroundJob: + backgroundJobs.length === 1 + ? backgroundJobs[0] + : Promise.all(backgroundJobs) + }; }; -const RESULT_MODIFIER = { - "module.modules": result => { - return indent(result, "| "); +/** + * @param {FileMiddleware} middleware this + * @param {string | false} name filename + * @param {function(string | false): Promise} readFile read content of a file + * @returns {Promise} deserialized data + */ +const deserialize = async (middleware, name, readFile) => { + const contents = await readFile(name); + if (contents.length === 0) throw new Error("Empty file " + name); + let contentsIndex = 0; + let contentItem = contents[0]; + let contentItemLength = contentItem.length; + let contentPosition = 0; + if (contentItemLength === 0) throw new Error("Empty file " + name); + const nextContent = () => { + contentsIndex++; + contentItem = contents[contentsIndex]; + contentItemLength = contentItem.length; + contentPosition = 0; + }; + const ensureData = n => { + if (contentPosition === contentItemLength) { + nextContent(); + } + while (contentItemLength - contentPosition < n) { + const remaining = contentItem.slice(contentPosition); + let lengthFromNext = n - remaining.length; + const buffers = [remaining]; + for (let i = contentsIndex + 1; i < contents.length; i++) { + const l = contents[i].length; + if (l > lengthFromNext) { + buffers.push(contents[i].slice(0, lengthFromNext)); + contents[i] = contents[i].slice(lengthFromNext); + lengthFromNext = 0; + break; + } else { + buffers.push(contents[i]); + contentsIndex = i; + lengthFromNext -= l; + } + } + if (lengthFromNext > 0) throw new Error("Unexpected end of data"); + contentItem = Buffer.concat(buffers, n); + contentItemLength = n; + contentPosition = 0; + } + }; + const readUInt32LE = () => { + ensureData(4); + const value = contentItem.readUInt32LE(contentPosition); + contentPosition += 4; + return value; + }; + const readInt32LE = () => { + ensureData(4); + const value = contentItem.readInt32LE(contentPosition); + contentPosition += 4; + return value; + }; + const readSlice = l => { + ensureData(l); + if (contentPosition === 0 && contentItemLength === l) { + const result = contentItem; + if (contentsIndex + 1 < contents.length) { + nextContent(); + } else { + contentPosition = l; + } + return result; + } + const result = contentItem.slice(contentPosition, contentPosition + l); + contentPosition += l; + // we clone the buffer here to allow the original content to be garbage collected + return l * 2 < contentItem.buffer.byteLength ? Buffer.from(result) : result; + }; + const version = readUInt32LE(); + if (version !== VERSION) { + throw new Error("Invalid file version"); } -}; - -const createOrder = (array, preferredOrder) => { - const originalArray = array.slice(); - const set = new Set(array); - const usedSet = new Set(); - array.length = 0; - for (const element of preferredOrder) { - if (element.endsWith("!") || set.has(element)) { - array.push(element); - usedSet.add(element); + const sectionCount = readUInt32LE(); + const lengths = []; + let lastLengthPositive = false; + for (let i = 0; i < sectionCount; i++) { + const value = readInt32LE(); + const valuePositive = value >= 0; + if (lastLengthPositive && valuePositive) { + lengths[lengths.length - 1] += value; + } else { + lengths.push(value); + lastLengthPositive = valuePositive; } } - for (const element of originalArray) { - if (!usedSet.has(element)) { - array.push(element); + const result = []; + for (let length of lengths) { + if (length < 0) { + const slice = readSlice(-length); + const size = Number(readUInt64LE(slice, 0)); + const nameBuffer = slice.slice(8); + const name = nameBuffer.toString(); + result.push( + SerializerMiddleware.createLazy( + memoize(() => deserialize(middleware, name, readFile)), + middleware, + { + name, + size + }, + slice + ) + ); + } else { + if (contentPosition === contentItemLength) { + nextContent(); + } else if (contentPosition !== 0) { + if (length <= contentItemLength - contentPosition) { + result.push( + Buffer.from( + contentItem.buffer, + contentItem.byteOffset + contentPosition, + length + ) + ); + contentPosition += length; + length = 0; + } else { + const l = contentItemLength - contentPosition; + result.push( + Buffer.from( + contentItem.buffer, + contentItem.byteOffset + contentPosition, + l + ) + ); + length -= l; + contentPosition = contentItemLength; + } + } else { + if (length >= contentItemLength) { + result.push(contentItem); + length -= contentItemLength; + contentPosition = contentItemLength; + } else { + result.push( + Buffer.from(contentItem.buffer, contentItem.byteOffset, length) + ); + contentPosition += length; + length = 0; + } + } + while (length > 0) { + nextContent(); + if (length >= contentItemLength) { + result.push(contentItem); + length -= contentItemLength; + contentPosition = contentItemLength; + } else { + result.push( + Buffer.from(contentItem.buffer, contentItem.byteOffset, length) + ); + contentPosition += length; + length = 0; + } + } } } - return array; + return result; }; -class DefaultStatsPrinterPlugin { +/** + * @typedef {BufferSerializableType[]} DeserializedType + * @typedef {true} SerializedType + * @extends {SerializerMiddleware} + */ +class FileMiddleware extends SerializerMiddleware { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {IntermediateFileSystem} fs filesystem + * @param {string | Hash} hashFunction hash function to use */ - apply(compiler) { - compiler.hooks.compilation.tap("DefaultStatsPrinterPlugin", compilation => { - compilation.hooks.statsPrinter.tap( - "DefaultStatsPrinterPlugin", - (stats, options, context) => { - // Put colors into context - stats.hooks.print - .for("compilation") - .tap("DefaultStatsPrinterPlugin", (compilation, context) => { - for (const color of Object.keys(AVAILABLE_COLORS)) { - let start; - if (options.colors) { - if ( - typeof options.colors === "object" && - typeof options.colors[color] === "string" - ) { - start = options.colors[color]; - } else { - start = AVAILABLE_COLORS[color]; - } - } - if (start) { - context[color] = str => - `${start}${ - typeof str === "string" - ? str.replace( - /((\u001b\[39m|\u001b\[22m|\u001b\[0m)+)/g, - `$1${start}` - ) - : str - }\u001b[39m\u001b[22m`; - } else { - context[color] = str => str; + constructor(fs, hashFunction = "md4") { + super(); + this.fs = fs; + this._hashFunction = hashFunction; + } + /** + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType|Promise} serialized data + */ + serialize(data, context) { + const { filename, extension = "" } = context; + return new Promise((resolve, reject) => { + mkdirp(this.fs, dirname(this.fs, filename), err => { + if (err) return reject(err); + + // It's important that we don't touch existing files during serialization + // because serialize may read existing files (when deserializing) + const allWrittenFiles = new Set(); + const writeFile = async (name, content) => { + const file = name + ? join(this.fs, filename, `../${name}${extension}`) + : filename; + await new Promise((resolve, reject) => { + let stream = this.fs.createWriteStream(file + "_"); + let compression; + if (file.endsWith(".gz")) { + compression = createGzip({ + chunkSize: COMPRESSION_CHUNK_SIZE, + level: zConstants.Z_BEST_SPEED + }); + } else if (file.endsWith(".br")) { + compression = createBrotliCompress({ + chunkSize: COMPRESSION_CHUNK_SIZE, + params: { + [zConstants.BROTLI_PARAM_MODE]: zConstants.BROTLI_MODE_TEXT, + [zConstants.BROTLI_PARAM_QUALITY]: 2, + [zConstants.BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING]: true, + [zConstants.BROTLI_PARAM_SIZE_HINT]: content.reduce( + (size, b) => size + b.length, + 0 + ) } - } - for (const format of Object.keys(AVAILABLE_FORMATS)) { - context[format] = (content, ...args) => - AVAILABLE_FORMATS[format](content, context, ...args); - } - context.timeReference = compilation.time; - }); + }); + } + if (compression) { + pipeline(compression, stream, reject); + stream = compression; + stream.on("finish", () => resolve()); + } else { + stream.on("error", err => reject(err)); + stream.on("finish", () => resolve()); + } + for (const b of content) stream.write(b); + stream.end(); + }); + if (name) allWrittenFiles.add(file); + }; - for (const key of Object.keys(SIMPLE_PRINTERS)) { - stats.hooks.print - .for(key) - .tap("DefaultStatsPrinterPlugin", (obj, ctx) => - SIMPLE_PRINTERS[key](obj, ctx, stats) - ); - } + resolve( + serialize(this, data, false, writeFile, this._hashFunction).then( + async ({ backgroundJob }) => { + await backgroundJob; - for (const key of Object.keys(PREFERRED_ORDERS)) { - const preferredOrder = PREFERRED_ORDERS[key]; - stats.hooks.sortElements - .for(key) - .tap("DefaultStatsPrinterPlugin", (elements, context) => { - createOrder(elements, preferredOrder); - }); - } + // Rename the index file to disallow access during inconsistent file state + await new Promise(resolve => + this.fs.rename(filename, filename + ".old", err => { + resolve(); + }) + ); - for (const key of Object.keys(ITEM_NAMES)) { - const itemName = ITEM_NAMES[key]; - stats.hooks.getItemName - .for(key) - .tap( - "DefaultStatsPrinterPlugin", - typeof itemName === "string" ? () => itemName : itemName + // update all written files + await Promise.all( + Array.from( + allWrittenFiles, + file => + new Promise((resolve, reject) => { + this.fs.rename(file + "_", file, err => { + if (err) return reject(err); + resolve(); + }); + }) + ) ); - } - for (const key of Object.keys(SIMPLE_ITEMS_JOINER)) { - const joiner = SIMPLE_ITEMS_JOINER[key]; - stats.hooks.printItems - .for(key) - .tap("DefaultStatsPrinterPlugin", joiner); - } + // As final step automatically update the index file to have a consistent pack again + await new Promise(resolve => { + this.fs.rename(filename + "_", filename, err => { + if (err) return reject(err); + resolve(); + }); + }); + return /** @type {true} */ (true); + } + ) + ); + }); + }); + } - for (const key of Object.keys(SIMPLE_ELEMENT_JOINERS)) { - const joiner = SIMPLE_ELEMENT_JOINERS[key]; - stats.hooks.printElements - .for(key) - .tap("DefaultStatsPrinterPlugin", joiner); + /** + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data + */ + deserialize(data, context) { + const { filename, extension = "" } = context; + const readFile = name => + new Promise((resolve, reject) => { + const file = name + ? join(this.fs, filename, `../${name}${extension}`) + : filename; + this.fs.stat(file, (err, stats) => { + if (err) { + reject(err); + return; } - - for (const key of Object.keys(RESULT_MODIFIER)) { - const modifier = RESULT_MODIFIER[key]; - stats.hooks.result - .for(key) - .tap("DefaultStatsPrinterPlugin", modifier); + let remaining = /** @type {number} */ (stats.size); + let currentBuffer; + let currentBufferUsed; + const buf = []; + let decompression; + if (file.endsWith(".gz")) { + decompression = createGunzip({ + chunkSize: DECOMPRESSION_CHUNK_SIZE + }); + } else if (file.endsWith(".br")) { + decompression = createBrotliDecompress({ + chunkSize: DECOMPRESSION_CHUNK_SIZE + }); } - } - ); - }); + if (decompression) { + let newResolve, newReject; + resolve( + Promise.all([ + new Promise((rs, rj) => { + newResolve = rs; + newReject = rj; + }), + new Promise((resolve, reject) => { + decompression.on("data", chunk => buf.push(chunk)); + decompression.on("end", () => resolve()); + decompression.on("error", err => reject(err)); + }) + ]).then(() => buf) + ); + resolve = newResolve; + reject = newReject; + } + this.fs.open(file, "r", (err, fd) => { + if (err) { + reject(err); + return; + } + const read = () => { + if (currentBuffer === undefined) { + currentBuffer = Buffer.allocUnsafeSlow( + Math.min( + constants.MAX_LENGTH, + remaining, + decompression ? DECOMPRESSION_CHUNK_SIZE : Infinity + ) + ); + currentBufferUsed = 0; + } + let readBuffer = currentBuffer; + let readOffset = currentBufferUsed; + let readLength = currentBuffer.length - currentBufferUsed; + // values passed to fs.read must be valid int32 values + if (readOffset > 0x7fffffff) { + readBuffer = currentBuffer.slice(readOffset); + readOffset = 0; + } + if (readLength > 0x7fffffff) { + readLength = 0x7fffffff; + } + this.fs.read( + fd, + readBuffer, + readOffset, + readLength, + null, + (err, bytesRead) => { + if (err) { + this.fs.close(fd, () => { + reject(err); + }); + return; + } + currentBufferUsed += bytesRead; + remaining -= bytesRead; + if (currentBufferUsed === currentBuffer.length) { + if (decompression) { + decompression.write(currentBuffer); + } else { + buf.push(currentBuffer); + } + currentBuffer = undefined; + if (remaining === 0) { + if (decompression) { + decompression.end(); + } + this.fs.close(fd, err => { + if (err) { + reject(err); + return; + } + resolve(buf); + }); + return; + } + } + read(); + } + ); + }; + read(); + }); + }); + }); + return deserialize(this, false, readFile); } } -module.exports = DefaultStatsPrinterPlugin; + +module.exports = FileMiddleware; /***/ }), -/***/ 92629: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 86791: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const { HookMap, SyncBailHook, SyncWaterfallHook } = __webpack_require__(6967); -const { concatComparators, keepOriginalOrder } = __webpack_require__(29579); -const smartGrouping = __webpack_require__(15652); - -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -/** @typedef {import("../util/smartGrouping").GroupConfig} GroupConfig */ - -/** - * @typedef {Object} KnownStatsFactoryContext - * @property {string} type - * @property {function(string): string=} makePathsRelative - * @property {Compilation=} compilation - * @property {Set=} rootModules - * @property {Map=} compilationFileToChunks - * @property {Map=} compilationAuxiliaryFileToChunks - * @property {RuntimeSpec=} runtime - * @property {function(Compilation): WebpackError[]=} cachedGetErrors - * @property {function(Compilation): WebpackError[]=} cachedGetWarnings - */ - -/** @typedef {KnownStatsFactoryContext & Record} StatsFactoryContext */ - -class StatsFactory { - constructor() { - this.hooks = Object.freeze({ - /** @type {HookMap>} */ - extract: new HookMap( - () => new SyncBailHook(["object", "data", "context"]) - ), - /** @type {HookMap>} */ - filter: new HookMap( - () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) - ), - /** @type {HookMap>} */ - sort: new HookMap(() => new SyncBailHook(["comparators", "context"])), - /** @type {HookMap>} */ - filterSorted: new HookMap( - () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) - ), - /** @type {HookMap>} */ - groupResults: new HookMap( - () => new SyncBailHook(["groupConfigs", "context"]) - ), - /** @type {HookMap>} */ - sortResults: new HookMap( - () => new SyncBailHook(["comparators", "context"]) - ), - /** @type {HookMap>} */ - filterResults: new HookMap( - () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) - ), - /** @type {HookMap>} */ - merge: new HookMap(() => new SyncBailHook(["items", "context"])), - /** @type {HookMap>} */ - result: new HookMap(() => new SyncWaterfallHook(["result", "context"])), - /** @type {HookMap>} */ - getItemName: new HookMap(() => new SyncBailHook(["item", "context"])), - /** @type {HookMap>} */ - getItemFactory: new HookMap(() => new SyncBailHook(["item", "context"])) - }); - const hooks = this.hooks; - this._caches = - /** @type {Record[]>>} */ ({}); - for (const key of Object.keys(hooks)) { - this._caches[key] = new Map(); - } - this._inCreate = false; - } - - _getAllLevelHooks(hookMap, cache, type) { - const cacheEntry = cache.get(type); - if (cacheEntry !== undefined) { - return cacheEntry; - } - const hooks = []; - const typeParts = type.split("."); - for (let i = 0; i < typeParts.length; i++) { - const hook = hookMap.get(typeParts.slice(i).join(".")); - if (hook) { - hooks.push(hook); - } +class MapObjectSerializer { + serialize(obj, { write }) { + write(obj.size); + for (const key of obj.keys()) { + write(key); } - cache.set(type, hooks); - return hooks; - } - - _forEachLevel(hookMap, cache, type, fn) { - for (const hook of this._getAllLevelHooks(hookMap, cache, type)) { - const result = fn(hook); - if (result !== undefined) return result; + for (const value of obj.values()) { + write(value); } } - - _forEachLevelWaterfall(hookMap, cache, type, data, fn) { - for (const hook of this._getAllLevelHooks(hookMap, cache, type)) { - data = fn(hook, data); + deserialize({ read }) { + let size = read(); + const map = new Map(); + const keys = []; + for (let i = 0; i < size; i++) { + keys.push(read()); } - return data; - } - - _forEachLevelFilter(hookMap, cache, type, items, fn, forceClone) { - const hooks = this._getAllLevelHooks(hookMap, cache, type); - if (hooks.length === 0) return forceClone ? items.slice() : items; - let i = 0; - return items.filter((item, idx) => { - for (const hook of hooks) { - const r = fn(hook, item, idx, i); - if (r !== undefined) { - if (r) i++; - return r; - } - } - i++; - return true; - }); - } - - /** - * @param {string} type type - * @param {any} data factory data - * @param {Omit} baseContext context used as base - * @returns {any} created object - */ - create(type, data, baseContext) { - if (this._inCreate) { - return this._create(type, data, baseContext); - } else { - try { - this._inCreate = true; - return this._create(type, data, baseContext); - } finally { - for (const key of Object.keys(this._caches)) this._caches[key].clear(); - this._inCreate = false; - } + for (let i = 0; i < size; i++) { + map.set(keys[i], read()); } + return map; } +} - _create(type, data, baseContext) { - const context = { - ...baseContext, - type, - [type]: data - }; - if (Array.isArray(data)) { - // run filter on unsorted items - const items = this._forEachLevelFilter( - this.hooks.filter, - this._caches.filter, - type, - data, - (h, r, idx, i) => h.call(r, context, idx, i), - true - ); - - // sort items - const comparators = []; - this._forEachLevel(this.hooks.sort, this._caches.sort, type, h => - h.call(comparators, context) - ); - if (comparators.length > 0) { - items.sort( - // @ts-expect-error number of arguments is correct - concatComparators(...comparators, keepOriginalOrder(items)) - ); - } - - // run filter on sorted items - const items2 = this._forEachLevelFilter( - this.hooks.filterSorted, - this._caches.filterSorted, - type, - items, - (h, r, idx, i) => h.call(r, context, idx, i), - false - ); - - // for each item - let resultItems = items2.map((item, i) => { - const itemContext = { - ...context, - _index: i - }; - - // run getItemName - const itemName = this._forEachLevel( - this.hooks.getItemName, - this._caches.getItemName, - `${type}[]`, - h => h.call(item, itemContext) - ); - if (itemName) itemContext[itemName] = item; - const innerType = itemName ? `${type}[].${itemName}` : `${type}[]`; - - // run getItemFactory - const itemFactory = - this._forEachLevel( - this.hooks.getItemFactory, - this._caches.getItemFactory, - innerType, - h => h.call(item, itemContext) - ) || this; - - // run item factory - return itemFactory.create(innerType, item, itemContext); - }); +module.exports = MapObjectSerializer; - // sort result items - const comparators2 = []; - this._forEachLevel( - this.hooks.sortResults, - this._caches.sortResults, - type, - h => h.call(comparators2, context) - ); - if (comparators2.length > 0) { - resultItems.sort( - // @ts-expect-error number of arguments is correct - concatComparators(...comparators2, keepOriginalOrder(resultItems)) - ); - } - // group result items - const groupConfigs = []; - this._forEachLevel( - this.hooks.groupResults, - this._caches.groupResults, - type, - h => h.call(groupConfigs, context) - ); - if (groupConfigs.length > 0) { - resultItems = smartGrouping(resultItems, groupConfigs); - } +/***/ }), - // run filter on sorted result items - const finalResultItems = this._forEachLevelFilter( - this.hooks.filterResults, - this._caches.filterResults, - type, - resultItems, - (h, r, idx, i) => h.call(r, context, idx, i), - false - ); +/***/ 21048: +/***/ (function(module) { - // run merge on mapped items - let result = this._forEachLevel( - this.hooks.merge, - this._caches.merge, - type, - h => h.call(finalResultItems, context) - ); - if (result === undefined) result = finalResultItems; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - // run result on merged items - return this._forEachLevelWaterfall( - this.hooks.result, - this._caches.result, - type, - result, - (h, r) => h.call(r, context) - ); - } else { - const object = {}; - // run extract on value - this._forEachLevel(this.hooks.extract, this._caches.extract, type, h => - h.call(object, data, context) - ); - // run result on extracted object - return this._forEachLevelWaterfall( - this.hooks.result, - this._caches.result, - type, - object, - (h, r) => h.call(r, context) - ); +class NullPrototypeObjectSerializer { + serialize(obj, { write }) { + const keys = Object.keys(obj); + for (const key of keys) { + write(key); + } + write(null); + for (const key of keys) { + write(obj[key]); + } + } + deserialize({ read }) { + const obj = Object.create(null); + const keys = []; + let key = read(); + while (key !== null) { + keys.push(key); + key = read(); + } + for (const key of keys) { + obj[key] = read(); } + return obj; } } -module.exports = StatsFactory; + +module.exports = NullPrototypeObjectSerializer; /***/ }), -/***/ 30198: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 34795: +/***/ (function(module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const { HookMap, SyncWaterfallHook, SyncBailHook } = __webpack_require__(6967); - -/** @template T @typedef {import("tapable").AsArray} AsArray */ -/** @typedef {import("tapable").Hook} Hook */ -/** @typedef {import("./DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ -/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunk} StatsChunk */ -/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunkGroup} StatsChunkGroup */ -/** @typedef {import("./DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ -/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModule} StatsModule */ -/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleReason} StatsModuleReason */ - -/** - * @typedef {Object} PrintedElement - * @property {string} element - * @property {string} content - */ - -/** - * @typedef {Object} KnownStatsPrinterContext - * @property {string=} type - * @property {StatsCompilation=} compilation - * @property {StatsChunkGroup=} chunkGroup - * @property {StatsAsset=} asset - * @property {StatsModule=} module - * @property {StatsChunk=} chunk - * @property {StatsModuleReason=} moduleReason - * @property {(str: string) => string=} bold - * @property {(str: string) => string=} yellow - * @property {(str: string) => string=} red - * @property {(str: string) => string=} green - * @property {(str: string) => string=} magenta - * @property {(str: string) => string=} cyan - * @property {(file: string, oversize?: boolean) => string=} formatFilename - * @property {(id: string) => string=} formatModuleId - * @property {(id: string, direction?: "parent"|"child"|"sibling") => string=} formatChunkId - * @property {(size: number) => string=} formatSize - * @property {(dateTime: number) => string=} formatDateTime - * @property {(flag: string) => string=} formatFlag - * @property {(time: number, boldQuantity?: boolean) => string=} formatTime - * @property {string=} chunkGroupKind - */ - -/** @typedef {KnownStatsPrinterContext & Record} StatsPrinterContext */ - -class StatsPrinter { - constructor() { - this.hooks = Object.freeze({ - /** @type {HookMap>} */ - sortElements: new HookMap( - () => new SyncBailHook(["elements", "context"]) - ), - /** @type {HookMap>} */ - printElements: new HookMap( - () => new SyncBailHook(["printedElements", "context"]) - ), - /** @type {HookMap>} */ - sortItems: new HookMap(() => new SyncBailHook(["items", "context"])), - /** @type {HookMap>} */ - getItemName: new HookMap(() => new SyncBailHook(["item", "context"])), - /** @type {HookMap>} */ - printItems: new HookMap( - () => new SyncBailHook(["printedItems", "context"]) - ), - /** @type {HookMap>} */ - print: new HookMap(() => new SyncBailHook(["object", "context"])), - /** @type {HookMap>} */ - result: new HookMap(() => new SyncWaterfallHook(["result", "context"])) - }); - /** @type {Map, Map>} */ - this._levelHookCache = new Map(); - this._inPrint = false; - } - - /** - * get all level hooks - * @private - * @template {Hook} T - * @param {HookMap} hookMap HookMap - * @param {string} type type - * @returns {T[]} hooks - */ - _getAllLevelHooks(hookMap, type) { - let cache = /** @type {Map} */ ( - this._levelHookCache.get(hookMap) - ); - if (cache === undefined) { - cache = new Map(); - this._levelHookCache.set(hookMap, cache); - } - const cacheEntry = cache.get(type); - if (cacheEntry !== undefined) { - return cacheEntry; - } - /** @type {T[]} */ - const hooks = []; - const typeParts = type.split("."); - for (let i = 0; i < typeParts.length; i++) { - const hook = hookMap.get(typeParts.slice(i).join(".")); - if (hook) { - hooks.push(hook); - } - } - cache.set(type, hooks); - return hooks; - } - - /** - * Run `fn` for each level - * @private - * @template T - * @template R - * @param {HookMap>} hookMap HookMap - * @param {string} type type - * @param {(hook: SyncBailHook) => R} fn function - * @returns {R} result of `fn` - */ - _forEachLevel(hookMap, type, fn) { - for (const hook of this._getAllLevelHooks(hookMap, type)) { - const result = fn(hook); - if (result !== undefined) return result; - } - } - - /** - * Run `fn` for each level - * @private - * @template T - * @param {HookMap>} hookMap HookMap - * @param {string} type type - * @param {AsArray[0]} data data - * @param {(hook: SyncWaterfallHook, data: AsArray[0]) => AsArray[0]} fn function - * @returns {AsArray[0]} result of `fn` - */ - _forEachLevelWaterfall(hookMap, type, data, fn) { - for (const hook of this._getAllLevelHooks(hookMap, type)) { - data = fn(hook, data); - } - return data; - } +const createHash = __webpack_require__(49835); +const ArraySerializer = __webpack_require__(41721); +const DateObjectSerializer = __webpack_require__(93475); +const ErrorObjectSerializer = __webpack_require__(79479); +const MapObjectSerializer = __webpack_require__(86791); +const NullPrototypeObjectSerializer = __webpack_require__(21048); +const PlainObjectSerializer = __webpack_require__(33040); +const RegExpObjectSerializer = __webpack_require__(57328); +const SerializerMiddleware = __webpack_require__(83137); +const SetObjectSerializer = __webpack_require__(79240); - /** - * @param {string} type The type - * @param {Object} object Object to print - * @param {Object=} baseContext The base context - * @returns {string} printed result - */ - print(type, object, baseContext) { - if (this._inPrint) { - return this._print(type, object, baseContext); - } else { - try { - this._inPrint = true; - return this._print(type, object, baseContext); - } finally { - this._levelHookCache.clear(); - this._inPrint = false; - } - } - } +/** @typedef {typeof import("../util/Hash")} Hash */ +/** @typedef {import("./types").ComplexSerializableType} ComplexSerializableType */ +/** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */ - /** - * @private - * @param {string} type type - * @param {Object} object object - * @param {Object=} baseContext context - * @returns {string} printed result - */ - _print(type, object, baseContext) { - const context = { - ...baseContext, - type, - [type]: object - }; +/** @typedef {new (...params: any[]) => any} Constructor */ - let printResult = this._forEachLevel(this.hooks.print, type, hook => - hook.call(object, context) - ); - if (printResult === undefined) { - if (Array.isArray(object)) { - const sortedItems = object.slice(); - this._forEachLevel(this.hooks.sortItems, type, h => - h.call(sortedItems, context) - ); - const printedItems = sortedItems.map((item, i) => { - const itemContext = { - ...context, - _index: i - }; - const itemName = this._forEachLevel( - this.hooks.getItemName, - `${type}[]`, - h => h.call(item, itemContext) - ); - if (itemName) itemContext[itemName] = item; - return this.print( - itemName ? `${type}[].${itemName}` : `${type}[]`, - item, - itemContext - ); - }); - printResult = this._forEachLevel(this.hooks.printItems, type, h => - h.call(printedItems, context) - ); - if (printResult === undefined) { - const result = printedItems.filter(Boolean); - if (result.length > 0) printResult = result.join("\n"); - } - } else if (object !== null && typeof object === "object") { - const elements = Object.keys(object).filter( - key => object[key] !== undefined - ); - this._forEachLevel(this.hooks.sortElements, type, h => - h.call(elements, context) - ); - const printedElements = elements.map(element => { - const content = this.print(`${type}.${element}`, object[element], { - ...context, - _parent: object, - _element: element, - [element]: object[element] - }); - return { element, content }; - }); - printResult = this._forEachLevel(this.hooks.printElements, type, h => - h.call(printedElements, context) - ); - if (printResult === undefined) { - const result = printedElements.map(e => e.content).filter(Boolean); - if (result.length > 0) printResult = result.join("\n"); - } - } - } +/* - return this._forEachLevelWaterfall( - this.hooks.result, - type, - printResult, - (h, r) => h.call(r, context) - ); - } -} -module.exports = StatsPrinter; +Format: +File -> Section* +Section -> ObjectSection | ReferenceSection | EscapeSection | OtherSection -/***/ }), +ObjectSection -> ESCAPE ( + number:relativeOffset (number > 0) | + string:request (string|null):export +) Section:value* ESCAPE ESCAPE_END_OBJECT +ReferenceSection -> ESCAPE number:relativeOffset (number < 0) +EscapeSection -> ESCAPE ESCAPE_ESCAPE_VALUE (escaped value ESCAPE) +EscapeSection -> ESCAPE ESCAPE_UNDEFINED (escaped value ESCAPE) +OtherSection -> any (except ESCAPE) -/***/ 84953: -/***/ (function(__unused_webpack_module, exports) { +Why using null as escape value? +Multiple null values can merged by the BinaryMiddleware, which makes it very efficient +Technically any value can be used. -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ +/** + * @typedef {Object} ObjectSerializerContext + * @property {function(any): void} write + */ + +/** + * @typedef {Object} ObjectDeserializerContext + * @property {function(): any} read + */ +/** + * @typedef {Object} ObjectSerializer + * @property {function(any, ObjectSerializerContext): void} serialize + * @property {function(ObjectDeserializerContext): any} deserialize + */ -exports.equals = (a, b) => { - if (a.length !== b.length) return false; - for (let i = 0; i < a.length; i++) { - if (a[i] !== b[i]) return false; +const setSetSize = (set, size) => { + let i = 0; + for (const item of set) { + if (i++ >= size) { + set.delete(item); + } + } +}; + +const setMapSize = (map, size) => { + let i = 0; + for (const item of map.keys()) { + if (i++ >= size) { + map.delete(item); + } } - return true; }; /** - * - * @param {Array} arr Array of values to be partitioned - * @param {(value: any) => boolean} fn Partition function which partitions based on truthiness of result. - * @returns {[Array, Array]} returns the values of `arr` partitioned into two new arrays based on fn predicate. + * @param {Buffer} buffer buffer + * @param {string | Hash} hashFunction hash function to use + * @returns {string} hash */ -exports.groupBy = (arr = [], fn) => { - return arr.reduce( - (groups, value) => { - groups[fn(value) ? 0 : 1].push(value); - return groups; - }, - [[], []] - ); +const toHash = (buffer, hashFunction) => { + const hash = createHash(hashFunction); + hash.update(buffer); + return /** @type {string} */ (hash.digest("latin1")); }; +const ESCAPE = null; +const ESCAPE_ESCAPE_VALUE = null; +const ESCAPE_END_OBJECT = true; +const ESCAPE_UNDEFINED = false; -/***/ }), +const CURRENT_VERSION = 2; -/***/ 41792: -/***/ (function(module) { +const serializers = new Map(); +const serializerInversed = new Map(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const loadedRequests = new Set(); +const NOT_SERIALIZABLE = {}; +const jsTypes = new Map(); +jsTypes.set(Object, new PlainObjectSerializer()); +jsTypes.set(Array, new ArraySerializer()); +jsTypes.set(null, new NullPrototypeObjectSerializer()); +jsTypes.set(Map, new MapObjectSerializer()); +jsTypes.set(Set, new SetObjectSerializer()); +jsTypes.set(Date, new DateObjectSerializer()); +jsTypes.set(RegExp, new RegExpObjectSerializer()); +jsTypes.set(Error, new ErrorObjectSerializer(Error)); +jsTypes.set(EvalError, new ErrorObjectSerializer(EvalError)); +jsTypes.set(RangeError, new ErrorObjectSerializer(RangeError)); +jsTypes.set(ReferenceError, new ErrorObjectSerializer(ReferenceError)); +jsTypes.set(SyntaxError, new ErrorObjectSerializer(SyntaxError)); +jsTypes.set(TypeError, new ErrorObjectSerializer(TypeError)); -/** - * @template T - */ -class ArrayQueue { - /** - * @param {Iterable=} items The initial elements. - */ - constructor(items) { - /** @private @type {T[]} */ - this._list = items ? Array.from(items) : []; - /** @private @type {T[]} */ - this._listReversed = []; +// If in a sandboxed environment (e. g. jest), this escapes the sandbox and registers +// real Object and Array types to. These types may occur in the wild too, e. g. when +// using Structured Clone in postMessage. +if (exports.constructor !== Object) { + const Obj = /** @type {typeof Object} */ (exports.constructor); + const Fn = /** @type {typeof Function} */ (Obj.constructor); + for (const [type, config] of Array.from(jsTypes)) { + if (type) { + const Type = new Fn(`return ${type.name};`)(); + jsTypes.set(Type, config); + } } +} - /** - * Returns the number of elements in this queue. - * @returns {number} The number of elements in this queue. - */ - get length() { - return this._list.length + this._listReversed.length; +{ + let i = 1; + for (const [type, serializer] of jsTypes) { + serializers.set(type, { + request: "", + name: i++, + serializer + }); } +} + +for (const { request, name, serializer } of serializers.values()) { + serializerInversed.set(`${request}/${name}`, serializer); +} + +/** @type {Map boolean>} */ +const loaders = new Map(); +/** + * @typedef {ComplexSerializableType[]} DeserializedType + * @typedef {PrimitiveSerializableType[]} SerializedType + * @extends {SerializerMiddleware} + */ +class ObjectMiddleware extends SerializerMiddleware { /** - * Empties the queue. + * @param {function(any): void} extendContext context extensions + * @param {string | Hash} hashFunction hash function to use */ - clear() { - this._list.length = 0; - this._listReversed.length = 0; + constructor(extendContext, hashFunction = "md4") { + super(); + this.extendContext = extendContext; + this._hashFunction = hashFunction; } - /** - * Appends the specified element to this queue. - * @param {T} item The element to add. + * @param {RegExp} regExp RegExp for which the request is tested + * @param {function(string): boolean} loader loader to load the request, returns true when successful * @returns {void} */ - enqueue(item) { - this._list.push(item); + static registerLoader(regExp, loader) { + loaders.set(regExp, loader); } /** - * Retrieves and removes the head of this queue. - * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + * @param {Constructor} Constructor the constructor + * @param {string} request the request which will be required when deserializing + * @param {string} name the name to make multiple serializer unique when sharing a request + * @param {ObjectSerializer} serializer the serializer + * @returns {void} */ - dequeue() { - if (this._listReversed.length === 0) { - if (this._list.length === 0) return undefined; - if (this._list.length === 1) return this._list.pop(); - if (this._list.length < 16) return this._list.shift(); - const temp = this._listReversed; - this._listReversed = this._list; - this._listReversed.reverse(); - this._list = temp; + static register(Constructor, request, name, serializer) { + const key = request + "/" + name; + + if (serializers.has(Constructor)) { + throw new Error( + `ObjectMiddleware.register: serializer for ${Constructor.name} is already registered` + ); } - return this._listReversed.pop(); + + if (serializerInversed.has(key)) { + throw new Error( + `ObjectMiddleware.register: serializer for ${key} is already registered` + ); + } + + serializers.set(Constructor, { + request, + name, + serializer + }); + + serializerInversed.set(key, serializer); } /** - * Finds and removes an item - * @param {T} item the item + * @param {Constructor} Constructor the constructor * @returns {void} */ - delete(item) { - const i = this._list.indexOf(item); - if (i >= 0) { - this._list.splice(i, 1); - } else { - const i = this._listReversed.indexOf(item); - if (i >= 0) this._listReversed.splice(i, 1); + static registerNotSerializable(Constructor) { + if (serializers.has(Constructor)) { + throw new Error( + `ObjectMiddleware.registerNotSerializable: serializer for ${Constructor.name} is already registered` + ); } + + serializers.set(Constructor, NOT_SERIALIZABLE); } - [Symbol.iterator]() { - let i = -1; - let reversed = false; - return { - next: () => { - if (!reversed) { - i++; - if (i < this._list.length) { - return { - done: false, - value: this._list[i] - }; - } - reversed = true; - i = this._listReversed.length; - } - i--; - if (i < 0) { - return { - done: true, - value: undefined - }; - } - return { - done: false, - value: this._listReversed[i] - }; + static getSerializerFor(object) { + const proto = Object.getPrototypeOf(object); + let c; + if (proto === null) { + // Object created with Object.create(null) + c = null; + } else { + c = proto.constructor; + if (!c) { + throw new Error( + "Serialization of objects with prototype without valid constructor property not possible" + ); } - }; + } + const config = serializers.get(c); + + if (!config) throw new Error(`No serializer registered for ${c.name}`); + if (config === NOT_SERIALIZABLE) throw NOT_SERIALIZABLE; + + return config; } -} -module.exports = ArrayQueue; + static getDeserializerFor(request, name) { + const key = request + "/" + name; + const serializer = serializerInversed.get(key); + if (serializer === undefined) { + throw new Error(`No deserializer registered for ${key}`); + } -/***/ }), + return serializer; + } -/***/ 12260: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + static _getDeserializerForWithoutError(request, name) { + const key = request + "/" + name; + const serializer = serializerInversed.get(key); + return serializer; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType|Promise} serialized data + */ + serialize(data, context) { + /** @type {any[]} */ + let result = [CURRENT_VERSION]; + let currentPos = 0; + let referenceable = new Map(); + const addReferenceable = item => { + referenceable.set(item, currentPos++); + }; + let bufferDedupeMap = new Map(); + const dedupeBuffer = buf => { + const len = buf.length; + const entry = bufferDedupeMap.get(len); + if (entry === undefined) { + bufferDedupeMap.set(len, buf); + return buf; + } + if (Buffer.isBuffer(entry)) { + if (len < 32) { + if (buf.equals(entry)) { + return entry; + } + bufferDedupeMap.set(len, [entry, buf]); + return buf; + } else { + const hash = toHash(entry, this._hashFunction); + const newMap = new Map(); + newMap.set(hash, entry); + bufferDedupeMap.set(len, newMap); + const hashBuf = toHash(buf, this._hashFunction); + if (hash === hashBuf) { + return entry; + } + return buf; + } + } else if (Array.isArray(entry)) { + if (entry.length < 16) { + for (const item of entry) { + if (buf.equals(item)) { + return item; + } + } + entry.push(buf); + return buf; + } else { + const newMap = new Map(); + const hash = toHash(buf, this._hashFunction); + let found; + for (const item of entry) { + const itemHash = toHash(item, this._hashFunction); + newMap.set(itemHash, item); + if (found === undefined && itemHash === hash) found = item; + } + bufferDedupeMap.set(len, newMap); + if (found === undefined) { + newMap.set(hash, buf); + return buf; + } else { + return found; + } + } + } else { + const hash = toHash(buf, this._hashFunction); + const item = entry.get(hash); + if (item !== undefined) { + return item; + } + entry.set(hash, buf); + return buf; + } + }; + let currentPosTypeLookup = 0; + let objectTypeLookup = new Map(); + const cycleStack = new Set(); + const stackToString = item => { + const arr = Array.from(cycleStack); + arr.push(item); + return arr + .map(item => { + if (typeof item === "string") { + if (item.length > 100) { + return `String ${JSON.stringify(item.slice(0, 100)).slice( + 0, + -1 + )}..."`; + } + return `String ${JSON.stringify(item)}`; + } + try { + const { request, name } = ObjectMiddleware.getSerializerFor(item); + if (request) { + return `${request}${name ? `.${name}` : ""}`; + } + } catch (e) { + // ignore -> fallback + } + if (typeof item === "object" && item !== null) { + if (item.constructor) { + if (item.constructor === Object) + return `Object { ${Object.keys(item).join(", ")} }`; + if (item.constructor === Map) return `Map { ${item.size} items }`; + if (item.constructor === Array) + return `Array { ${item.length} items }`; + if (item.constructor === Set) return `Set { ${item.size} items }`; + if (item.constructor === RegExp) return item.toString(); + return `${item.constructor.name}`; + } + return `Object [null prototype] { ${Object.keys(item).join( + ", " + )} }`; + } + try { + return `${item}`; + } catch (e) { + return `(${e.message})`; + } + }) + .join(" -> "); + }; + let hasDebugInfoAttached; + let ctx = { + write(value, key) { + try { + process(value); + } catch (e) { + if (e !== NOT_SERIALIZABLE) { + if (hasDebugInfoAttached === undefined) + hasDebugInfoAttached = new WeakSet(); + if (!hasDebugInfoAttached.has(e)) { + e.message += `\nwhile serializing ${stackToString(value)}`; + hasDebugInfoAttached.add(e); + } + } + throw e; + } + }, + setCircularReference(ref) { + addReferenceable(ref); + }, + snapshot() { + return { + length: result.length, + cycleStackSize: cycleStack.size, + referenceableSize: referenceable.size, + currentPos, + objectTypeLookupSize: objectTypeLookup.size, + currentPosTypeLookup + }; + }, + rollback(snapshot) { + result.length = snapshot.length; + setSetSize(cycleStack, snapshot.cycleStackSize); + setMapSize(referenceable, snapshot.referenceableSize); + currentPos = snapshot.currentPos; + setMapSize(objectTypeLookup, snapshot.objectTypeLookupSize); + currentPosTypeLookup = snapshot.currentPosTypeLookup; + }, + ...context + }; + this.extendContext(ctx); + const process = item => { + if (Buffer.isBuffer(item)) { + // check if we can emit a reference + const ref = referenceable.get(item); + if (ref !== undefined) { + result.push(ESCAPE, ref - currentPos); + return; + } + const alreadyUsedBuffer = dedupeBuffer(item); + if (alreadyUsedBuffer !== item) { + const ref = referenceable.get(alreadyUsedBuffer); + if (ref !== undefined) { + referenceable.set(item, ref); + result.push(ESCAPE, ref - currentPos); + return; + } + item = alreadyUsedBuffer; + } + addReferenceable(item); + result.push(item); + } else if (item === ESCAPE) { + result.push(ESCAPE, ESCAPE_ESCAPE_VALUE); + } else if ( + typeof item === "object" + // We don't have to check for null as ESCAPE is null and this has been checked before + ) { + // check if we can emit a reference + const ref = referenceable.get(item); + if (ref !== undefined) { + result.push(ESCAPE, ref - currentPos); + return; + } + if (cycleStack.has(item)) { + throw new Error( + `This is a circular references. To serialize circular references use 'setCircularReference' somewhere in the circle during serialize and deserialize.` + ); + } -const { SyncHook, AsyncSeriesHook } = __webpack_require__(6967); -const { makeWebpackError } = __webpack_require__(11351); -const WebpackError = __webpack_require__(53799); -const ArrayQueue = __webpack_require__(41792); + const { request, name, serializer } = + ObjectMiddleware.getSerializerFor(item); + const key = `${request}/${name}`; + const lastIndex = objectTypeLookup.get(key); -const QUEUED_STATE = 0; -const PROCESSING_STATE = 1; -const DONE_STATE = 2; + if (lastIndex === undefined) { + objectTypeLookup.set(key, currentPosTypeLookup++); -let inHandleResult = 0; + result.push(ESCAPE, request, name); + } else { + result.push(ESCAPE, currentPosTypeLookup - lastIndex); + } -/** - * @template T - * @callback Callback - * @param {(WebpackError | null)=} err - * @param {T=} result - */ + cycleStack.add(item); -/** - * @template T - * @template K - * @template R - */ -class AsyncQueueEntry { - /** - * @param {T} item the item - * @param {Callback} callback the callback - */ - constructor(item, callback) { - this.item = item; - /** @type {typeof QUEUED_STATE | typeof PROCESSING_STATE | typeof DONE_STATE} */ - this.state = QUEUED_STATE; - this.callback = callback; - /** @type {Callback[] | undefined} */ - this.callbacks = undefined; - this.result = undefined; - /** @type {WebpackError | undefined} */ - this.error = undefined; - } -} + try { + serializer.serialize(item, ctx); + } finally { + cycleStack.delete(item); + } -/** - * @template T - * @template K - * @template R - */ -class AsyncQueue { - /** - * @param {Object} options options object - * @param {string=} options.name name of the queue - * @param {number=} options.parallelism how many items should be processed at once - * @param {AsyncQueue=} options.parent parent queue, which will have priority over this queue and with shared parallelism - * @param {function(T): K=} options.getKey extract key from item - * @param {function(T, Callback): void} options.processor async function to process items - */ - constructor({ name, parallelism, parent, processor, getKey }) { - this._name = name; - this._parallelism = parallelism || 1; - this._processor = processor; - this._getKey = - getKey || /** @type {(T) => K} */ (item => /** @type {any} */ (item)); - /** @type {Map>} */ - this._entries = new Map(); - /** @type {ArrayQueue>} */ - this._queued = new ArrayQueue(); - /** @type {AsyncQueue[]} */ - this._children = undefined; - this._activeTasks = 0; - this._willEnsureProcessing = false; - this._needProcessing = false; - this._stopped = false; - this._root = parent ? parent._root : this; - if (parent) { - if (this._root._children === undefined) { - this._root._children = [this]; - } else { - this._root._children.push(this); - } - } + result.push(ESCAPE, ESCAPE_END_OBJECT); - this.hooks = { - /** @type {AsyncSeriesHook<[T]>} */ - beforeAdd: new AsyncSeriesHook(["item"]), - /** @type {SyncHook<[T]>} */ - added: new SyncHook(["item"]), - /** @type {AsyncSeriesHook<[T]>} */ - beforeStart: new AsyncSeriesHook(["item"]), - /** @type {SyncHook<[T]>} */ - started: new SyncHook(["item"]), - /** @type {SyncHook<[T, Error, R]>} */ - result: new SyncHook(["item", "error", "result"]) - }; + addReferenceable(item); + } else if (typeof item === "string") { + if (item.length > 1) { + // short strings are shorter when not emitting a reference (this saves 1 byte per empty string) + // check if we can emit a reference + const ref = referenceable.get(item); + if (ref !== undefined) { + result.push(ESCAPE, ref - currentPos); + return; + } + addReferenceable(item); + } - this._ensureProcessing = this._ensureProcessing.bind(this); - } + if (item.length > 102400 && context.logger) { + context.logger.warn( + `Serializing big strings (${Math.round( + item.length / 1024 + )}kiB) impacts deserialization performance (consider using Buffer instead and decode when needed)` + ); + } - /** - * @param {T} item an item - * @param {Callback} callback callback function - * @returns {void} - */ - add(item, callback) { - if (this._stopped) return callback(new WebpackError("Queue was stopped")); - this.hooks.beforeAdd.callAsync(item, err => { - if (err) { - callback( - makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeAdd`) - ); - return; - } - const key = this._getKey(item); - const entry = this._entries.get(key); - if (entry !== undefined) { - if (entry.state === DONE_STATE) { - if (inHandleResult++ > 3) { - process.nextTick(() => callback(entry.error, entry.result)); + result.push(item); + } else if (typeof item === "function") { + if (!SerializerMiddleware.isLazy(item)) + throw new Error("Unexpected function " + item); + /** @type {SerializedType} */ + const serializedData = + SerializerMiddleware.getLazySerializedValue(item); + if (serializedData !== undefined) { + if (typeof serializedData === "function") { + result.push(serializedData); } else { - callback(entry.error, entry.result); + throw new Error("Not implemented"); } - inHandleResult--; - } else if (entry.callbacks === undefined) { - entry.callbacks = [callback]; + } else if (SerializerMiddleware.isLazy(item, this)) { + throw new Error("Not implemented"); } else { - entry.callbacks.push(callback); + const data = SerializerMiddleware.serializeLazy(item, data => + this.serialize([data], context) + ); + SerializerMiddleware.setLazySerializedValue(item, data); + result.push(data); } - return; - } - const newEntry = new AsyncQueueEntry(item, callback); - if (this._stopped) { - this.hooks.added.call(item); - this._root._activeTasks++; - process.nextTick(() => - this._handleResult(newEntry, new WebpackError("Queue was stopped")) - ); + } else if (item === undefined) { + result.push(ESCAPE, ESCAPE_UNDEFINED); } else { - this._entries.set(key, newEntry); - this._queued.enqueue(newEntry); - const root = this._root; - root._needProcessing = true; - if (root._willEnsureProcessing === false) { - root._willEnsureProcessing = true; - setImmediate(root._ensureProcessing); - } - this.hooks.added.call(item); + result.push(item); } - }); - } - - /** - * @param {T} item an item - * @returns {void} - */ - invalidate(item) { - const key = this._getKey(item); - const entry = this._entries.get(key); - this._entries.delete(key); - if (entry.state === QUEUED_STATE) { - this._queued.delete(entry); - } - } + }; - /** - * Waits for an already started item - * @param {T} item an item - * @param {Callback} callback callback function - * @returns {void} - */ - waitFor(item, callback) { - const key = this._getKey(item); - const entry = this._entries.get(key); - if (entry === undefined) { - return callback( - new WebpackError( - "waitFor can only be called for an already started item" - ) - ); - } - if (entry.state === DONE_STATE) { - process.nextTick(() => callback(entry.error, entry.result)); - } else if (entry.callbacks === undefined) { - entry.callbacks = [callback]; - } else { - entry.callbacks.push(callback); - } - } + try { + for (const item of data) { + process(item); + } + return result; + } catch (e) { + if (e === NOT_SERIALIZABLE) return null; - /** - * @returns {void} - */ - stop() { - this._stopped = true; - const queue = this._queued; - this._queued = new ArrayQueue(); - const root = this._root; - for (const entry of queue) { - this._entries.delete(this._getKey(entry.item)); - root._activeTasks++; - this._handleResult(entry, new WebpackError("Queue was stopped")); + throw e; + } finally { + // Get rid of these references to avoid leaking memory + // This happens because the optimized code v8 generates + // is optimized for our "ctx.write" method so it will reference + // it from e. g. Dependency.prototype.serialize -(IC)-> ctx.write + data = + result = + referenceable = + bufferDedupeMap = + objectTypeLookup = + ctx = + undefined; } } /** - * @returns {void} + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data */ - increaseParallelism() { - const root = this._root; - root._parallelism++; - /* istanbul ignore next */ - if (root._willEnsureProcessing === false && root._needProcessing) { - root._willEnsureProcessing = true; - setImmediate(root._ensureProcessing); - } - } + deserialize(data, context) { + let currentDataPos = 0; + const read = () => { + if (currentDataPos >= data.length) + throw new Error("Unexpected end of stream"); - /** - * @returns {void} - */ - decreaseParallelism() { - const root = this._root; - root._parallelism--; - } + return data[currentDataPos++]; + }; - /** - * @param {T} item an item - * @returns {boolean} true, if the item is currently being processed - */ - isProcessing(item) { - const key = this._getKey(item); - const entry = this._entries.get(key); - return entry !== undefined && entry.state === PROCESSING_STATE; - } + if (read() !== CURRENT_VERSION) + throw new Error("Version mismatch, serializer changed"); - /** - * @param {T} item an item - * @returns {boolean} true, if the item is currently queued - */ - isQueued(item) { - const key = this._getKey(item); - const entry = this._entries.get(key); - return entry !== undefined && entry.state === QUEUED_STATE; - } + let currentPos = 0; + let referenceable = []; + const addReferenceable = item => { + referenceable.push(item); + currentPos++; + }; + let currentPosTypeLookup = 0; + let objectTypeLookup = []; + let result = []; + let ctx = { + read() { + return decodeValue(); + }, + setCircularReference(ref) { + addReferenceable(ref); + }, + ...context + }; + this.extendContext(ctx); + const decodeValue = () => { + const item = read(); - /** - * @param {T} item an item - * @returns {boolean} true, if the item is currently queued - */ - isDone(item) { - const key = this._getKey(item); - const entry = this._entries.get(key); - return entry !== undefined && entry.state === DONE_STATE; - } + if (item === ESCAPE) { + const nextItem = read(); - /** - * @returns {void} - */ - _ensureProcessing() { - while (this._activeTasks < this._parallelism) { - const entry = this._queued.dequeue(); - if (entry === undefined) break; - this._activeTasks++; - entry.state = PROCESSING_STATE; - this._startProcessing(entry); - } - this._willEnsureProcessing = false; - if (this._queued.length > 0) return; - if (this._children !== undefined) { - for (const child of this._children) { - while (this._activeTasks < this._parallelism) { - const entry = child._queued.dequeue(); - if (entry === undefined) break; - this._activeTasks++; - entry.state = PROCESSING_STATE; - child._startProcessing(entry); - } - if (child._queued.length > 0) return; - } - } - if (!this._willEnsureProcessing) this._needProcessing = false; - } + if (nextItem === ESCAPE_ESCAPE_VALUE) { + return ESCAPE; + } else if (nextItem === ESCAPE_UNDEFINED) { + return undefined; + } else if (nextItem === ESCAPE_END_OBJECT) { + throw new Error( + `Unexpected end of object at position ${currentDataPos - 1}` + ); + } else { + const request = nextItem; + let serializer; - /** - * @param {AsyncQueueEntry} entry the entry - * @returns {void} - */ - _startProcessing(entry) { - this.hooks.beforeStart.callAsync(entry.item, err => { - if (err) { - this._handleResult( - entry, - makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeStart`) - ); - return; - } - let inCallback = false; - try { - this._processor(entry.item, (e, r) => { - inCallback = true; - this._handleResult(entry, e, r); - }); - } catch (err) { - if (inCallback) throw err; - this._handleResult(entry, err, null); - } - this.hooks.started.call(entry.item); - }); - } + if (typeof request === "number") { + if (request < 0) { + // relative reference + return referenceable[currentPos + request]; + } + serializer = objectTypeLookup[currentPosTypeLookup - request]; + } else { + if (typeof request !== "string") { + throw new Error( + `Unexpected type (${typeof request}) of request ` + + `at position ${currentDataPos - 1}` + ); + } + const name = read(); - /** - * @param {AsyncQueueEntry} entry the entry - * @param {WebpackError=} err error, if any - * @param {R=} result result, if any - * @returns {void} - */ - _handleResult(entry, err, result) { - this.hooks.result.callAsync(entry.item, err, result, hookError => { - const error = hookError - ? makeWebpackError(hookError, `AsyncQueue(${this._name}).hooks.result`) - : err; + serializer = ObjectMiddleware._getDeserializerForWithoutError( + request, + name + ); - const callback = entry.callback; - const callbacks = entry.callbacks; - entry.state = DONE_STATE; - entry.callback = undefined; - entry.callbacks = undefined; - entry.result = result; - entry.error = error; + if (serializer === undefined) { + if (request && !loadedRequests.has(request)) { + let loaded = false; + for (const [regExp, loader] of loaders) { + if (regExp.test(request)) { + if (loader(request)) { + loaded = true; + break; + } + } + } + if (!loaded) { + require(request); + } - const root = this._root; - root._activeTasks--; - if (root._willEnsureProcessing === false && root._needProcessing) { - root._willEnsureProcessing = true; - setImmediate(root._ensureProcessing); - } + loadedRequests.add(request); + } - if (inHandleResult++ > 3) { - process.nextTick(() => { - callback(error, result); - if (callbacks !== undefined) { - for (const callback of callbacks) { - callback(error, result); + serializer = ObjectMiddleware.getDeserializerFor(request, name); } + + objectTypeLookup.push(serializer); + currentPosTypeLookup++; } - }); - } else { - callback(error, result); - if (callbacks !== undefined) { - for (const callback of callbacks) { - callback(error, result); + try { + const item = serializer.deserialize(ctx); + const end1 = read(); + + if (end1 !== ESCAPE) { + throw new Error("Expected end of object"); + } + + const end2 = read(); + + if (end2 !== ESCAPE_END_OBJECT) { + throw new Error("Expected end of object"); + } + + addReferenceable(item); + + return item; + } catch (err) { + // As this is only for error handling, we omit creating a Map for + // faster access to this information, as this would affect performance + // in the good case + let serializerEntry; + for (const entry of serializers) { + if (entry[1].serializer === serializer) { + serializerEntry = entry; + break; + } + } + const name = !serializerEntry + ? "unknown" + : !serializerEntry[1].request + ? serializerEntry[0].name + : serializerEntry[1].name + ? `${serializerEntry[1].request} ${serializerEntry[1].name}` + : serializerEntry[1].request; + err.message += `\n(during deserialization of ${name})`; + throw err; } } + } else if (typeof item === "string") { + if (item.length > 1) { + addReferenceable(item); + } + + return item; + } else if (Buffer.isBuffer(item)) { + addReferenceable(item); + + return item; + } else if (typeof item === "function") { + return SerializerMiddleware.deserializeLazy( + item, + data => this.deserialize(data, context)[0] + ); + } else { + return item; } - inHandleResult--; - }); - } + }; - clear() { - this._entries.clear(); - this._queued.clear(); - this._activeTasks = 0; - this._willEnsureProcessing = false; - this._needProcessing = false; - this._stopped = false; + try { + while (currentDataPos < data.length) { + result.push(decodeValue()); + } + return result; + } finally { + // Get rid of these references to avoid leaking memory + // This happens because the optimized code v8 generates + // is optimized for our "ctx.read" method so it will reference + // it from e. g. Dependency.prototype.deserialize -(IC)-> ctx.read + result = referenceable = data = objectTypeLookup = ctx = undefined; + } } } -module.exports = AsyncQueue; +module.exports = ObjectMiddleware; +module.exports.NOT_SERIALIZABLE = NOT_SERIALIZABLE; /***/ }), -/***/ 36692: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 33040: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -class Hash { - /* istanbul ignore next */ - /** - * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} - * @abstract - * @param {string|Buffer} data data - * @param {string=} inputEncoding data encoding - * @returns {this} updated hash - */ - update(data, inputEncoding) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); +const cache = new WeakMap(); + +class ObjectStructure { + constructor() { + this.keys = undefined; + this.children = undefined; } - /* istanbul ignore next */ - /** - * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} - * @abstract - * @param {string=} encoding encoding of the return value - * @returns {string|Buffer} digest - */ - digest(encoding) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + getKeys(keys) { + if (this.keys === undefined) this.keys = keys; + return this.keys; + } + + key(key) { + if (this.children === undefined) this.children = new Map(); + const child = this.children.get(key); + if (child !== undefined) return child; + const newChild = new ObjectStructure(); + this.children.set(key, newChild); + return newChild; } } -module.exports = Hash; +const getCachedKeys = (keys, cacheAssoc) => { + let root = cache.get(cacheAssoc); + if (root === undefined) { + root = new ObjectStructure(); + cache.set(cacheAssoc, root); + } + let current = root; + for (const key of keys) { + current = current.key(key); + } + return current.getKeys(keys); +}; + +class PlainObjectSerializer { + serialize(obj, { write }) { + const keys = Object.keys(obj); + if (keys.length > 128) { + // Objects with so many keys are unlikely to share structure + // with other objects + write(keys); + for (const key of keys) { + write(obj[key]); + } + } else if (keys.length > 1) { + write(getCachedKeys(keys, write)); + for (const key of keys) { + write(obj[key]); + } + } else if (keys.length === 1) { + const key = keys[0]; + write(key); + write(obj[key]); + } else { + write(null); + } + } + deserialize({ read }) { + const keys = read(); + const obj = {}; + if (Array.isArray(keys)) { + for (const key of keys) { + obj[key] = read(); + } + } else if (keys !== null) { + obj[keys] = read(); + } + return obj; + } +} + +module.exports = PlainObjectSerializer; /***/ }), -/***/ 39104: -/***/ (function(__unused_webpack_module, exports) { +/***/ 57328: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -/** - * @template T - * @param {Iterable} set a set - * @returns {T | undefined} last item - */ -const last = set => { - let last; - for (const item of set) last = item; - return last; -}; - -/** - * @template T - * @param {Iterable} iterable iterable - * @param {function(T): boolean} filter predicate - * @returns {boolean} true, if some items match the filter predicate - */ -const someInIterable = (iterable, filter) => { - for (const item of iterable) { - if (filter(item)) return true; +class RegExpObjectSerializer { + serialize(obj, { write }) { + write(obj.source); + write(obj.flags); } - return false; -}; - -/** - * @template T - * @param {Iterable} iterable an iterable - * @returns {number} count of items - */ -const countIterable = iterable => { - let i = 0; - // eslint-disable-next-line no-unused-vars - for (const _ of iterable) i++; - return i; -}; + deserialize({ read }) { + return new RegExp(read(), read()); + } +} -exports.last = last; -exports.someInIterable = someInIterable; -exports.countIterable = countIterable; +module.exports = RegExpObjectSerializer; /***/ }), -/***/ 48424: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 53080: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const { first } = __webpack_require__(93347); -const SortableSet = __webpack_require__(13098); - -/** - * Multi layer bucket sorted set: - * Supports adding non-existing items (DO NOT ADD ITEM TWICE), - * Supports removing exiting items (DO NOT REMOVE ITEM NOT IN SET), - * Supports popping the first items according to defined order, - * Supports iterating all items without order, - * Supports updating an item in an efficient way, - * Supports size property, which is the number of items, - * Items are lazy partially sorted when needed - * @template T - * @template K - */ -class LazyBucketSortedSet { - /** - * @param {function(T): K} getKey function to get key from item - * @param {function(K, K): number} comparator comparator to sort keys - * @param {...((function(T): any) | (function(any, any): number))} args more pairs of getKey and comparator plus optional final comparator for the last layer - */ - constructor(getKey, comparator, ...args) { - this._getKey = getKey; - this._innerArgs = args; - this._leaf = args.length <= 1; - this._keys = new SortableSet(undefined, comparator); - /** @type {Map | SortableSet>} */ - this._map = new Map(); - this._unsortedItems = new Set(); - this.size = 0; - } - - /** - * @param {T} item an item - * @returns {void} - */ - add(item) { - this.size++; - this._unsortedItems.add(item); - } - - /** - * @param {K} key key of item - * @param {T} item the item - * @returns {void} - */ - _addInternal(key, item) { - let entry = this._map.get(key); - if (entry === undefined) { - entry = this._leaf - ? new SortableSet(undefined, this._innerArgs[0]) - : new /** @type {any} */ (LazyBucketSortedSet)(...this._innerArgs); - this._keys.add(key); - this._map.set(key, entry); - } - entry.add(item); - } - - /** - * @param {T} item an item - * @returns {void} - */ - delete(item) { - this.size--; - if (this._unsortedItems.has(item)) { - this._unsortedItems.delete(item); - return; - } - const key = this._getKey(item); - const entry = this._map.get(key); - entry.delete(item); - if (entry.size === 0) { - this._deleteKey(key); - } - } - - /** - * @param {K} key key to be removed - * @returns {void} - */ - _deleteKey(key) { - this._keys.delete(key); - this._map.delete(key); - } - - /** - * @returns {T | undefined} an item - */ - popFirst() { - if (this.size === 0) return undefined; - this.size--; - if (this._unsortedItems.size > 0) { - for (const item of this._unsortedItems) { - const key = this._getKey(item); - this._addInternal(key, item); - } - this._unsortedItems.clear(); - } - this._keys.sort(); - const key = first(this._keys); - const entry = this._map.get(key); - if (this._leaf) { - const leafEntry = /** @type {SortableSet} */ (entry); - leafEntry.sort(); - const item = first(leafEntry); - leafEntry.delete(item); - if (leafEntry.size === 0) { - this._deleteKey(key); - } - return item; - } else { - const nodeEntry = /** @type {LazyBucketSortedSet} */ (entry); - const item = nodeEntry.popFirst(); - if (nodeEntry.size === 0) { - this._deleteKey(key); - } - return item; - } +class Serializer { + constructor(middlewares, context) { + this.serializeMiddlewares = middlewares.slice(); + this.deserializeMiddlewares = middlewares.slice().reverse(); + this.context = context; } - /** - * @param {T} item to be updated item - * @returns {function(true=): void} finish update - */ - startUpdate(item) { - if (this._unsortedItems.has(item)) { - return remove => { - if (remove) { - this._unsortedItems.delete(item); - this.size--; - return; - } - }; - } - const key = this._getKey(item); - if (this._leaf) { - const oldEntry = /** @type {SortableSet} */ (this._map.get(key)); - return remove => { - if (remove) { - this.size--; - oldEntry.delete(item); - if (oldEntry.size === 0) { - this._deleteKey(key); - } - return; - } - const newKey = this._getKey(item); - if (key === newKey) { - // This flags the sortable set as unordered - oldEntry.add(item); - } else { - oldEntry.delete(item); - if (oldEntry.size === 0) { - this._deleteKey(key); - } - this._addInternal(newKey, item); - } - }; - } else { - const oldEntry = /** @type {LazyBucketSortedSet} */ ( - this._map.get(key) - ); - const finishUpdate = oldEntry.startUpdate(item); - return remove => { - if (remove) { - this.size--; - finishUpdate(true); - if (oldEntry.size === 0) { - this._deleteKey(key); - } - return; - } - const newKey = this._getKey(item); - if (key === newKey) { - finishUpdate(); - } else { - finishUpdate(true); - if (oldEntry.size === 0) { - this._deleteKey(key); - } - this._addInternal(newKey, item); + serialize(obj, context) { + const ctx = { ...context, ...this.context }; + let current = obj; + for (const middleware of this.serializeMiddlewares) { + if (current && typeof current.then === "function") { + current = current.then(data => data && middleware.serialize(data, ctx)); + } else if (current) { + try { + current = middleware.serialize(current, ctx); + } catch (err) { + current = Promise.reject(err); } - }; + } else break; } + return current; } - /** - * @param {Iterator[]} iterators list of iterators to append to - * @returns {void} - */ - _appendIterators(iterators) { - if (this._unsortedItems.size > 0) - iterators.push(this._unsortedItems[Symbol.iterator]()); - for (const key of this._keys) { - const entry = this._map.get(key); - if (this._leaf) { - const leafEntry = /** @type {SortableSet} */ (entry); - const iterator = leafEntry[Symbol.iterator](); - iterators.push(iterator); + deserialize(value, context) { + const ctx = { ...context, ...this.context }; + /** @type {any} */ + let current = value; + for (const middleware of this.deserializeMiddlewares) { + if (current && typeof current.then === "function") { + current = current.then(data => middleware.deserialize(data, ctx)); } else { - const nodeEntry = /** @type {LazyBucketSortedSet} */ (entry); - nodeEntry._appendIterators(iterators); + current = middleware.deserialize(current, ctx); } } - } - - /** - * @returns {Iterator} the iterator - */ - [Symbol.iterator]() { - const iterators = []; - this._appendIterators(iterators); - iterators.reverse(); - let currentIterator = iterators.pop(); - return { - next: () => { - const res = currentIterator.next(); - if (res.done) { - if (iterators.length === 0) return res; - currentIterator = iterators.pop(); - return currentIterator.next(); - } - return res; - } - }; + return current; } } -module.exports = LazyBucketSortedSet; +module.exports = Serializer; /***/ }), -/***/ 38938: +/***/ 83137: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const makeSerializable = __webpack_require__(33032); - -/** - * @template T - * @param {Set} targetSet set where items should be added - * @param {Set>} toMerge iterables to be merged - * @returns {void} - */ -const merge = (targetSet, toMerge) => { - for (const set of toMerge) { - for (const item of set) { - targetSet.add(item); - } - } -}; +const memoize = __webpack_require__(78676); -/** - * @template T - * @param {Set>} targetSet set where iterables should be added - * @param {Array>} toDeepMerge lazy sets to be flattened - * @returns {void} - */ -const flatten = (targetSet, toDeepMerge) => { - for (const set of toDeepMerge) { - if (set._set.size > 0) targetSet.add(set._set); - if (set._needMerge) { - for (const mergedSet of set._toMerge) { - targetSet.add(mergedSet); - } - flatten(targetSet, set._toDeepMerge); - } - } -}; +const LAZY_TARGET = Symbol("lazy serialization target"); +const LAZY_SERIALIZED_VALUE = Symbol("lazy serialization data"); /** - * Like Set but with an addAll method to eventually add items from another iterable. - * Access methods make sure that all delayed operations are executed. - * Iteration methods deopts to normal Set performance until clear is called again (because of the chance of modifications during iteration). - * @template T + * @template DeserializedType + * @template SerializedType */ -class LazySet { +class SerializerMiddleware { + /* istanbul ignore next */ /** - * @param {Iterable=} iterable init iterable + * @abstract + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType|Promise} serialized data */ - constructor(iterable) { - /** @type {Set} */ - this._set = new Set(iterable); - /** @type {Set>} */ - this._toMerge = new Set(); - /** @type {Array>} */ - this._toDeepMerge = []; - this._needMerge = false; - this._deopt = false; - } - - _flatten() { - flatten(this._toMerge, this._toDeepMerge); - this._toDeepMerge.length = 0; - } - - _merge() { - this._flatten(); - merge(this._set, this._toMerge); - this._toMerge.clear(); - this._needMerge = false; - } - - _isEmpty() { - return ( - this._set.size === 0 && - this._toMerge.size === 0 && - this._toDeepMerge.length === 0 - ); - } - - get size() { - if (this._needMerge) this._merge(); - return this._set.size; + serialize(data, context) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } + /* istanbul ignore next */ /** - * @param {T} item an item - * @returns {this} itself + * @abstract + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data */ - add(item) { - this._set.add(item); - return this; + deserialize(data, context) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } /** - * @param {Iterable | LazySet} iterable a immutable iterable or another immutable LazySet which will eventually be merged into the Set - * @returns {this} itself + * @param {any | function(): Promise | any} value contained value or function to value + * @param {SerializerMiddleware} target target middleware + * @param {object=} options lazy options + * @param {any=} serializedValue serialized value + * @returns {function(): Promise | any} lazy function */ - addAll(iterable) { - if (this._deopt) { - const _set = this._set; - for (const item of iterable) { - _set.add(item); - } - } else { - if (iterable instanceof LazySet) { - if (iterable._isEmpty()) return this; - this._toDeepMerge.push(iterable); - this._needMerge = true; - if (this._toDeepMerge.length > 100000) { - this._flatten(); - } - } else { - this._toMerge.add(iterable); - this._needMerge = true; - } - if (this._toMerge.size > 100000) this._merge(); - } - return this; + static createLazy(value, target, options = {}, serializedValue) { + if (SerializerMiddleware.isLazy(value, target)) return value; + const fn = typeof value === "function" ? value : () => value; + fn[LAZY_TARGET] = target; + /** @type {any} */ (fn).options = options; + fn[LAZY_SERIALIZED_VALUE] = serializedValue; + return fn; } - clear() { - this._set.clear(); - this._toMerge.clear(); - this._toDeepMerge.length = 0; - this._needMerge = false; - this._deopt = false; + /** + * @param {function(): Promise | any} fn lazy function + * @param {SerializerMiddleware=} target target middleware + * @returns {boolean} true, when fn is a lazy function (optionally of that target) + */ + static isLazy(fn, target) { + if (typeof fn !== "function") return false; + const t = fn[LAZY_TARGET]; + return target ? t === target : !!t; } /** - * @param {T} value an item - * @returns {boolean} true, if the value was in the Set before + * @param {function(): Promise | any} fn lazy function + * @returns {object} options */ - delete(value) { - if (this._needMerge) this._merge(); - return this._set.delete(value); + static getLazyOptions(fn) { + if (typeof fn !== "function") return undefined; + return /** @type {any} */ (fn).options; } - entries() { - this._deopt = true; - if (this._needMerge) this._merge(); - return this._set.entries(); + /** + * @param {function(): Promise | any} fn lazy function + * @returns {any} serialized value + */ + static getLazySerializedValue(fn) { + if (typeof fn !== "function") return undefined; + return fn[LAZY_SERIALIZED_VALUE]; } /** - * @param {function(T, T, Set): void} callbackFn function called for each entry - * @param {any} thisArg this argument for the callbackFn + * @param {function(): Promise | any} fn lazy function + * @param {any} value serialized value * @returns {void} */ - forEach(callbackFn, thisArg) { - this._deopt = true; - if (this._needMerge) this._merge(); - this._set.forEach(callbackFn, thisArg); + static setLazySerializedValue(fn, value) { + fn[LAZY_SERIALIZED_VALUE] = value; } /** - * @param {T} item an item - * @returns {boolean} true, when the item is in the Set + * @param {function(): Promise | any} lazy lazy function + * @param {function(any): Promise | any} serialize serialize function + * @returns {function(): Promise | any} new lazy */ - has(item) { - if (this._needMerge) this._merge(); - return this._set.has(item); - } - - keys() { - this._deopt = true; - if (this._needMerge) this._merge(); - return this._set.keys(); - } - - values() { - this._deopt = true; - if (this._needMerge) this._merge(); - return this._set.values(); - } - - [Symbol.iterator]() { - this._deopt = true; - if (this._needMerge) this._merge(); - return this._set[Symbol.iterator](); - } - - /* istanbul ignore next */ - get [Symbol.toStringTag]() { - return "LazySet"; + static serializeLazy(lazy, serialize) { + const fn = memoize(() => { + const r = lazy(); + if (r && typeof r.then === "function") { + return r.then(data => data && serialize(data)); + } + return serialize(r); + }); + fn[LAZY_TARGET] = lazy[LAZY_TARGET]; + /** @type {any} */ (fn).options = /** @type {any} */ (lazy).options; + lazy[LAZY_SERIALIZED_VALUE] = fn; + return fn; } - serialize({ write }) { - if (this._needMerge) this._merge(); - write(this._set.size); - for (const item of this._set) write(item); + /** + * @param {function(): Promise | any} lazy lazy function + * @param {function(any): Promise | any} deserialize deserialize function + * @returns {function(): Promise | any} new lazy + */ + static deserializeLazy(lazy, deserialize) { + const fn = memoize(() => { + const r = lazy(); + if (r && typeof r.then === "function") { + return r.then(data => deserialize(data)); + } + return deserialize(r); + }); + fn[LAZY_TARGET] = lazy[LAZY_TARGET]; + /** @type {any} */ (fn).options = /** @type {any} */ (lazy).options; + fn[LAZY_SERIALIZED_VALUE] = lazy; + return fn; } - static deserialize({ read }) { - const count = read(); - const items = []; - for (let i = 0; i < count; i++) { - items.push(read()); - } - return new LazySet(items); + /** + * @param {function(): Promise | any} lazy lazy function + * @returns {function(): Promise | any} new lazy + */ + static unMemoizeLazy(lazy) { + if (!SerializerMiddleware.isLazy(lazy)) return lazy; + const fn = () => { + throw new Error( + "A lazy value that has been unmemorized can't be called again" + ); + }; + fn[LAZY_SERIALIZED_VALUE] = SerializerMiddleware.unMemoizeLazy( + lazy[LAZY_SERIALIZED_VALUE] + ); + fn[LAZY_TARGET] = lazy[LAZY_TARGET]; + fn.options = /** @type {any} */ (lazy).options; + return fn; } } -makeSerializable(LazySet, "webpack/lib/util/LazySet"); - -module.exports = LazySet; - - -/***/ }), - -/***/ 82482: -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** - * @template K - * @template V - * @param {Map} map a map - * @param {K} key the key - * @param {function(): V} computer compute value - * @returns {V} value - */ -exports.provide = (map, key, computer) => { - const value = map.get(key); - if (value !== undefined) return value; - const newValue = computer(); - map.set(key, newValue); - return newValue; -}; +module.exports = SerializerMiddleware; /***/ }), -/***/ 50780: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 79240: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const binarySearchBounds = __webpack_require__(92229); - -class ParallelismFactorCalculator { - constructor() { - this._rangePoints = []; - this._rangeCallbacks = []; - } - - range(start, end, callback) { - if (start === end) return callback(1); - this._rangePoints.push(start); - this._rangePoints.push(end); - this._rangeCallbacks.push(callback); - } - - calculate() { - const segments = Array.from(new Set(this._rangePoints)).sort((a, b) => - a < b ? -1 : 1 - ); - const parallelism = segments.map(() => 0); - const rangeStartIndices = []; - for (let i = 0; i < this._rangePoints.length; i += 2) { - const start = this._rangePoints[i]; - const end = this._rangePoints[i + 1]; - let idx = binarySearchBounds.eq(segments, start); - rangeStartIndices.push(idx); - do { - parallelism[idx]++; - idx++; - } while (segments[idx] < end); +class SetObjectSerializer { + serialize(obj, { write }) { + write(obj.size); + for (const value of obj) { + write(value); } - for (let i = 0; i < this._rangeCallbacks.length; i++) { - const start = this._rangePoints[i * 2]; - const end = this._rangePoints[i * 2 + 1]; - let idx = rangeStartIndices[i]; - let sum = 0; - let totalDuration = 0; - let current = start; - do { - const p = parallelism[idx]; - idx++; - const duration = segments[idx] - current; - totalDuration += duration; - current = segments[idx]; - sum += p * duration; - } while (current < end); - this._rangeCallbacks[i](sum / totalDuration); + } + deserialize({ read }) { + let size = read(); + const set = new Set(); + for (let i = 0; i < size; i++) { + set.add(read()); } + return set; } } -module.exports = ParallelismFactorCalculator; +module.exports = SetObjectSerializer; /***/ }), -/***/ 65930: -/***/ (function(module) { +/***/ 65112: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ +const SerializerMiddleware = __webpack_require__(83137); + /** - * @template T + * @typedef {any} DeserializedType + * @typedef {any[]} SerializedType + * @extends {SerializerMiddleware} */ -class Queue { - /** - * @param {Iterable=} items The initial elements. - */ - constructor(items) { - /** @private @type {Set} */ - this._set = new Set(items); - /** @private @type {Iterator} */ - this._iterator = this._set[Symbol.iterator](); - } - - /** - * Returns the number of elements in this queue. - * @returns {number} The number of elements in this queue. - */ - get length() { - return this._set.size; - } - +class SingleItemMiddleware extends SerializerMiddleware { /** - * Appends the specified element to this queue. - * @param {T} item The element to add. - * @returns {void} + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType|Promise} serialized data */ - enqueue(item) { - this._set.add(item); + serialize(data, context) { + return [data]; } /** - * Retrieves and removes the head of this queue. - * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data */ - dequeue() { - const result = this._iterator.next(); - if (result.done) return undefined; - this._set.delete(result.value); - return result.value; + deserialize(data, context) { + return data[0]; } } -module.exports = Queue; +module.exports = SingleItemMiddleware; /***/ }), -/***/ 93347: -/***/ (function(__unused_webpack_module, exports) { +/***/ 58831: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -122331,99 +127135,35 @@ module.exports = Queue; -/** - * intersect creates Set containing the intersection of elements between all sets - * @template T - * @param {Set[]} sets an array of sets being checked for shared elements - * @returns {Set} returns a new Set containing the intersecting items - */ -const intersect = sets => { - if (sets.length === 0) return new Set(); - if (sets.length === 1) return new Set(sets[0]); - let minSize = Infinity; - let minIndex = -1; - for (let i = 0; i < sets.length; i++) { - const size = sets[i].size; - if (size < minSize) { - minIndex = i; - minSize = size; - } - } - const current = new Set(sets[minIndex]); - for (let i = 0; i < sets.length; i++) { - if (i === minIndex) continue; - const set = sets[i]; - for (const item of current) { - if (!set.has(item)) { - current.delete(item); - } - } - } - return current; -}; +const ModuleDependency = __webpack_require__(80321); +const makeSerializable = __webpack_require__(33032); -/** - * Checks if a set is the subset of another set - * @template T - * @param {Set} bigSet a Set which contains the original elements to compare against - * @param {Set} smallSet the set whose elements might be contained inside of bigSet - * @returns {boolean} returns true if smallSet contains all elements inside of the bigSet - */ -const isSubset = (bigSet, smallSet) => { - if (bigSet.size < smallSet.size) return false; - for (const item of smallSet) { - if (!bigSet.has(item)) return false; +class ConsumeSharedFallbackDependency extends ModuleDependency { + constructor(request) { + super(request); } - return true; -}; -/** - * @template T - * @param {Set} set a set - * @param {function(T): boolean} fn selector function - * @returns {T | undefined} found item - */ -const find = (set, fn) => { - for (const item of set) { - if (fn(item)) return item; + get type() { + return "consume shared fallback"; } -}; -/** - * @template T - * @param {Set} set a set - * @returns {T | undefined} first item - */ -const first = set => { - const entry = set.values().next(); - return entry.done ? undefined : entry.value; -}; + get category() { + return "esm"; + } +} -/** - * @template T - * @param {Set} a first - * @param {Set} b second - * @returns {Set} combined set, may be identical to a or b - */ -const combine = (a, b) => { - if (b.size === 0) return a; - if (a.size === 0) return b; - const set = new Set(a); - for (const item of b) set.add(item); - return set; -}; +makeSerializable( + ConsumeSharedFallbackDependency, + "webpack/lib/sharing/ConsumeSharedFallbackDependency" +); -exports.intersect = intersect; -exports.isSubset = isSubset; -exports.find = find; -exports.first = first; -exports.combine = combine; +module.exports = ConsumeSharedFallbackDependency; /***/ }), -/***/ 13098: -/***/ (function(module) { +/***/ 62286: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -122433,165 +127173,256 @@ exports.combine = combine; -const NONE = Symbol("not sorted"); +const { RawSource } = __webpack_require__(51255); +const AsyncDependenciesBlock = __webpack_require__(47736); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const { rangeToString, stringifyHoley } = __webpack_require__(19702); +const ConsumeSharedFallbackDependency = __webpack_require__(58831); + +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("../util/semver").SemVerRange} SemVerRange */ /** - * A subset of Set that offers sorting functionality - * @template T item type in set - * @extends {Set} + * @typedef {Object} ConsumeOptions + * @property {string=} import fallback request + * @property {string=} importResolved resolved fallback request + * @property {string} shareKey global share key + * @property {string} shareScope share scope + * @property {SemVerRange | false | undefined} requiredVersion version requirement + * @property {string} packageName package name to determine required version automatically + * @property {boolean} strictVersion don't use shared version even if version isn't valid + * @property {boolean} singleton use single global version + * @property {boolean} eager include the fallback module in a sync way */ -class SortableSet extends Set { + +const TYPES = new Set(["consume-shared"]); + +class ConsumeSharedModule extends Module { /** - * Create a new sortable set - * @param {Iterable=} initialIterable The initial iterable value - * @typedef {function(T, T): number} SortFunction - * @param {SortFunction=} defaultSort Default sorting function + * @param {string} context context + * @param {ConsumeOptions} options consume options */ - constructor(initialIterable, defaultSort) { - super(initialIterable); - /** @private @type {undefined | function(T, T): number}} */ - this._sortFn = defaultSort; - /** @private @type {typeof NONE | undefined | function(T, T): number}} */ - this._lastActiveSortFn = NONE; - /** @private @type {Map | undefined} */ - this._cache = undefined; - /** @private @type {Map | undefined} */ - this._cacheOrderIndependent = undefined; + constructor(context, options) { + super("consume-shared-module", context); + this.options = options; } /** - * @param {T} value value to add to set - * @returns {this} returns itself + * @returns {string} a unique identifier of the module */ - add(value) { - this._lastActiveSortFn = NONE; - this._invalidateCache(); - this._invalidateOrderedCache(); - super.add(value); - return this; + identifier() { + const { + shareKey, + shareScope, + importResolved, + requiredVersion, + strictVersion, + singleton, + eager + } = this.options; + return `consume-shared-module|${shareScope}|${shareKey}|${ + requiredVersion && rangeToString(requiredVersion) + }|${strictVersion}|${importResolved}|${singleton}|${eager}`; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + const { + shareKey, + shareScope, + importResolved, + requiredVersion, + strictVersion, + singleton, + eager + } = this.options; + return `consume shared module (${shareScope}) ${shareKey}@${ + requiredVersion ? rangeToString(requiredVersion) : "*" + }${strictVersion ? " (strict)" : ""}${singleton ? " (singleton)" : ""}${ + importResolved + ? ` (fallback: ${requestShortener.shorten(importResolved)})` + : "" + }${eager ? " (eager)" : ""}`; } /** - * @param {T} value value to delete - * @returns {boolean} true if value existed in set, false otherwise + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion */ - delete(value) { - this._invalidateCache(); - this._invalidateOrderedCache(); - return super.delete(value); + libIdent(options) { + const { shareKey, shareScope, import: request } = this.options; + return `${ + this.layer ? `(${this.layer})/` : "" + }webpack/sharing/consume/${shareScope}/${shareKey}${ + request ? `/${request}` : "" + }`; } /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild * @returns {void} */ - clear() { - this._invalidateCache(); - this._invalidateOrderedCache(); - return super.clear(); + needBuild(context, callback) { + callback(null, !this.buildInfo); } /** - * Sort with a comparer function - * @param {SortFunction} sortFn Sorting comparer function + * @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} */ - sortWith(sortFn) { - if (this.size <= 1 || sortFn === this._lastActiveSortFn) { - // already sorted - nothing to do - return; - } - - const sortedArray = Array.from(this).sort(sortFn); - super.clear(); - for (let i = 0; i < sortedArray.length; i += 1) { - super.add(sortedArray[i]); + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = {}; + if (this.options.import) { + const dep = new ConsumeSharedFallbackDependency(this.options.import); + if (this.options.eager) { + this.addDependency(dep); + } else { + const block = new AsyncDependenciesBlock({}); + block.addDependency(dep); + this.addBlock(block); + } } - this._lastActiveSortFn = sortFn; - this._invalidateCache(); - } - - sort() { - this.sortWith(this._sortFn); - return this; + callback(); } /** - * Get data from cache - * @template R - * @param {function(SortableSet): R} fn function to calculate value - * @returns {R} returns result of fn(this), cached until set changes + * @returns {Set} types available (do not mutate) */ - getFromCache(fn) { - if (this._cache === undefined) { - this._cache = new Map(); - } else { - const result = this._cache.get(fn); - const data = /** @type {R} */ (result); - if (data !== undefined) { - return data; - } - } - const newData = fn(this); - this._cache.set(fn, newData); - return newData; + getSourceTypes() { + return TYPES; } /** - * Get data from cache (ignoring sorting) - * @template R - * @param {function(SortableSet): R} fn function to calculate value - * @returns {R} returns result of fn(this), cached until set changes + * @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) */ - getFromUnorderedCache(fn) { - if (this._cacheOrderIndependent === undefined) { - this._cacheOrderIndependent = new Map(); - } else { - const result = this._cacheOrderIndependent.get(fn); - const data = /** @type {R} */ (result); - if (data !== undefined) { - return data; - } - } - const newData = fn(this); - this._cacheOrderIndependent.set(fn, newData); - return newData; + size(type) { + return 42; } /** - * @private + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context * @returns {void} */ - _invalidateCache() { - if (this._cache !== undefined) { - this._cache.clear(); - } + updateHash(hash, context) { + hash.update(JSON.stringify(this.options)); + super.updateHash(hash, context); } /** - * @private - * @returns {void} + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - _invalidateOrderedCache() { - if (this._cacheOrderIndependent !== undefined) { - this._cacheOrderIndependent.clear(); + codeGeneration({ chunkGraph, moduleGraph, runtimeTemplate }) { + const runtimeRequirements = new Set([RuntimeGlobals.shareScopeMap]); + const { + shareScope, + shareKey, + strictVersion, + requiredVersion, + import: request, + singleton, + eager + } = this.options; + let fallbackCode; + if (request) { + if (eager) { + const dep = this.dependencies[0]; + fallbackCode = runtimeTemplate.syncModuleFactory({ + dependency: dep, + chunkGraph, + runtimeRequirements, + request: this.options.import + }); + } else { + const block = this.blocks[0]; + fallbackCode = runtimeTemplate.asyncModuleFactory({ + block, + chunkGraph, + runtimeRequirements, + request: this.options.import + }); + } + } + let fn = "load"; + const args = [JSON.stringify(shareScope), JSON.stringify(shareKey)]; + if (requiredVersion) { + if (strictVersion) { + fn += "Strict"; + } + if (singleton) { + fn += "Singleton"; + } + args.push(stringifyHoley(requiredVersion)); + fn += "VersionCheck"; + } else { + if (singleton) { + fn += "Singleton"; + } + } + if (fallbackCode) { + fn += "Fallback"; + args.push(fallbackCode); } + const code = runtimeTemplate.returningFunction(`${fn}(${args.join(", ")})`); + const sources = new Map(); + sources.set("consume-shared", new RawSource(code)); + return { + runtimeRequirements, + sources + }; } - /** - * @returns {T[]} the raw array - */ - toJSON() { - return Array.from(this); + serialize(context) { + const { write } = context; + write(this.options); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.options = read(); + super.deserialize(context); } } -module.exports = SortableSet; +makeSerializable( + ConsumeSharedModule, + "webpack/lib/sharing/ConsumeSharedModule" +); + +module.exports = ConsumeSharedModule; /***/ }), -/***/ 64985: -/***/ (function(module) { +/***/ 15046: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -122601,115 +127432,324 @@ module.exports = SortableSet; -/** - * @template K - * @template V - */ -class StackedCacheMap { - constructor() { - /** @type {Map} */ - this.map = new Map(); - /** @type {ReadonlyMap[]} */ - this.stack = []; - } +const ModuleNotFoundError = __webpack_require__(32882); +const RuntimeGlobals = __webpack_require__(16475); +const WebpackError = __webpack_require__(53799); +const { parseOptions } = __webpack_require__(3083); +const LazySet = __webpack_require__(38938); +const createSchemaValidation = __webpack_require__(32540); +const { parseRange } = __webpack_require__(19702); +const ConsumeSharedFallbackDependency = __webpack_require__(58831); +const ConsumeSharedModule = __webpack_require__(62286); +const ConsumeSharedRuntimeModule = __webpack_require__(10394); +const ProvideForSharedDependency = __webpack_require__(40017); +const { resolveMatchedConfigs } = __webpack_require__(3591); +const { + isRequiredVersion, + getDescriptionFile, + getRequiredVersionFromDescriptionFile +} = __webpack_require__(84379); - /** - * @param {ReadonlyMap} map map to add - * @param {boolean} immutable if 'map' is immutable and StackedCacheMap can keep referencing it - */ - addAll(map, immutable) { - if (immutable) { - this.stack.push(map); +/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumeSharedPluginOptions} ConsumeSharedPluginOptions */ +/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumesConfig} ConsumesConfig */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */ +/** @typedef {import("./ConsumeSharedModule").ConsumeOptions} ConsumeOptions */ - // largest map should go first - for (let i = this.stack.length - 1; i > 0; i--) { - const beforeLast = this.stack[i - 1]; - if (beforeLast.size >= map.size) break; - this.stack[i] = beforeLast; - this.stack[i - 1] = map; - } - } else { - for (const [key, value] of map) { - this.map.set(key, value); - } - } +const validate = createSchemaValidation( + __webpack_require__(6464), + () => __webpack_require__(16116), + { + name: "Consume Shared Plugin", + baseDataPath: "options" } +); - /** - * @param {K} item the key of the element to add - * @param {V} value the value of the element to add - * @returns {void} - */ - set(item, value) { - this.map.set(item, value); - } +/** @type {ResolveOptionsWithDependencyType} */ +const RESOLVE_OPTIONS = { dependencyType: "esm" }; +const PLUGIN_NAME = "ConsumeSharedPlugin"; +class ConsumeSharedPlugin { /** - * @param {K} item the item to delete - * @returns {void} + * @param {ConsumeSharedPluginOptions} options options */ - delete(item) { - throw new Error("Items can't be deleted from a StackedCacheMap"); - } + constructor(options) { + if (typeof options !== "string") { + validate(options); + } - /** - * @param {K} item the item to test - * @returns {boolean} true if the item exists in this set - */ - has(item) { - throw new Error( - "Checking StackedCacheMap.has before reading is inefficient, use StackedCacheMap.get and check for undefined" + /** @type {[string, ConsumeOptions][]} */ + this._consumes = parseOptions( + options.consumes, + (item, key) => { + if (Array.isArray(item)) throw new Error("Unexpected array in options"); + /** @type {ConsumeOptions} */ + let result = + item === key || !isRequiredVersion(item) + ? // item is a request/key + { + import: key, + shareScope: options.shareScope || "default", + shareKey: key, + requiredVersion: undefined, + packageName: undefined, + strictVersion: false, + singleton: false, + eager: false + } + : // key is a request/key + // item is a version + { + import: key, + shareScope: options.shareScope || "default", + shareKey: key, + requiredVersion: parseRange(item), + strictVersion: true, + packageName: undefined, + singleton: false, + eager: false + }; + return result; + }, + (item, key) => ({ + import: item.import === false ? undefined : item.import || key, + shareScope: item.shareScope || options.shareScope || "default", + shareKey: item.shareKey || key, + requiredVersion: + typeof item.requiredVersion === "string" + ? parseRange(item.requiredVersion) + : item.requiredVersion, + strictVersion: + typeof item.strictVersion === "boolean" + ? item.strictVersion + : item.import !== false && !item.singleton, + packageName: item.packageName, + singleton: !!item.singleton, + eager: !!item.eager + }) ); } /** - * @param {K} item the key of the element to return - * @returns {V} the value of the element + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - get(item) { - for (const map of this.stack) { - const value = map.get(item); - if (value !== undefined) return value; - } - return this.map.get(item); - } + apply(compiler) { + compiler.hooks.thisCompilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + ConsumeSharedFallbackDependency, + normalModuleFactory + ); - clear() { - this.stack.length = 0; - this.map.clear(); - } + let unresolvedConsumes, resolvedConsumes, prefixedConsumes; + const promise = resolveMatchedConfigs(compilation, this._consumes).then( + ({ resolved, unresolved, prefixed }) => { + resolvedConsumes = resolved; + unresolvedConsumes = unresolved; + prefixedConsumes = prefixed; + } + ); - get size() { - let size = this.map.size; - for (const map of this.stack) { - size += map.size; - } - return size; - } + const resolver = compilation.resolverFactory.get( + "normal", + RESOLVE_OPTIONS + ); - [Symbol.iterator]() { - const iterators = this.stack.map(map => map[Symbol.iterator]()); - let current = this.map[Symbol.iterator](); - return { - next() { - let result = current.next(); - while (result.done && iterators.length > 0) { - current = iterators.pop(); - result = current.next(); - } - return result; + /** + * @param {string} context issuer directory + * @param {string} request request + * @param {ConsumeOptions} config options + * @returns {Promise} create module + */ + const createConsumeSharedModule = (context, request, config) => { + const requiredVersionWarning = details => { + const error = new WebpackError( + `No required version specified and unable to automatically determine one. ${details}` + ); + error.file = `shared module ${request}`; + compilation.warnings.push(error); + }; + const directFallback = + config.import && + /^(\.\.?(\/|$)|\/|[A-Za-z]:|\\\\)/.test(config.import); + return Promise.all([ + new Promise(resolve => { + if (!config.import) return resolve(); + const resolveContext = { + /** @type {LazySet} */ + fileDependencies: new LazySet(), + /** @type {LazySet} */ + contextDependencies: new LazySet(), + /** @type {LazySet} */ + missingDependencies: new LazySet() + }; + resolver.resolve( + {}, + directFallback ? compiler.context : context, + config.import, + resolveContext, + (err, result) => { + compilation.contextDependencies.addAll( + resolveContext.contextDependencies + ); + compilation.fileDependencies.addAll( + resolveContext.fileDependencies + ); + compilation.missingDependencies.addAll( + resolveContext.missingDependencies + ); + if (err) { + compilation.errors.push( + new ModuleNotFoundError(null, err, { + name: `resolving fallback for shared module ${request}` + }) + ); + return resolve(); + } + resolve(result); + } + ); + }), + new Promise(resolve => { + if (config.requiredVersion !== undefined) + return resolve(config.requiredVersion); + let packageName = config.packageName; + if (packageName === undefined) { + if (/^(\/|[A-Za-z]:|\\\\)/.test(request)) { + // For relative or absolute requests we don't automatically use a packageName. + // If wished one can specify one with the packageName option. + return resolve(); + } + const match = /^((?:@[^\\/]+[\\/])?[^\\/]+)/.exec(request); + if (!match) { + requiredVersionWarning( + "Unable to extract the package name from request." + ); + return resolve(); + } + packageName = match[0]; + } + + getDescriptionFile( + compilation.inputFileSystem, + context, + ["package.json"], + (err, result) => { + if (err) { + requiredVersionWarning( + `Unable to read description file: ${err}` + ); + return resolve(); + } + const { data, path: descriptionPath } = result; + if (!data) { + requiredVersionWarning( + `Unable to find description file in ${context}.` + ); + return resolve(); + } + const requiredVersion = getRequiredVersionFromDescriptionFile( + data, + packageName + ); + if (typeof requiredVersion !== "string") { + requiredVersionWarning( + `Unable to find required version for "${packageName}" in description file (${descriptionPath}). It need to be in dependencies, devDependencies or peerDependencies.` + ); + return resolve(); + } + resolve(parseRange(requiredVersion)); + } + ); + }) + ]).then(([importResolved, requiredVersion]) => { + return new ConsumeSharedModule( + directFallback ? compiler.context : context, + { + ...config, + importResolved, + import: importResolved ? config.import : undefined, + requiredVersion + } + ); + }); + }; + + normalModuleFactory.hooks.factorize.tapPromise( + PLUGIN_NAME, + ({ context, request, dependencies }) => + // wait for resolving to be complete + promise.then(() => { + if ( + dependencies[0] instanceof ConsumeSharedFallbackDependency || + dependencies[0] instanceof ProvideForSharedDependency + ) { + return; + } + const match = unresolvedConsumes.get(request); + if (match !== undefined) { + return createConsumeSharedModule(context, request, match); + } + for (const [prefix, options] of prefixedConsumes) { + if (request.startsWith(prefix)) { + const remainder = request.slice(prefix.length); + return createConsumeSharedModule(context, request, { + ...options, + import: options.import + ? options.import + remainder + : undefined, + shareKey: options.shareKey + remainder + }); + } + } + }) + ); + normalModuleFactory.hooks.createModule.tapPromise( + PLUGIN_NAME, + ({ resource }, { context, dependencies }) => { + if ( + dependencies[0] instanceof ConsumeSharedFallbackDependency || + dependencies[0] instanceof ProvideForSharedDependency + ) { + return Promise.resolve(); + } + const options = resolvedConsumes.get(resource); + if (options !== undefined) { + return createConsumeSharedModule(context, resource, options); + } + return Promise.resolve(); + } + ); + compilation.hooks.additionalTreeRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, set) => { + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.shareScopeMap); + set.add(RuntimeGlobals.initializeSharing); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new ConsumeSharedRuntimeModule(set) + ); + } + ); } - }; + ); } } -module.exports = StackedCacheMap; +module.exports = ConsumeSharedPlugin; /***/ }), -/***/ 58845: -/***/ (function(module) { +/***/ 10394: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -122719,171 +127759,365 @@ module.exports = StackedCacheMap; -const TOMBSTONE = Symbol("tombstone"); -const UNDEFINED_MARKER = Symbol("undefined"); - -/** - * @template T - * @typedef {T | undefined} Cell - */ - -/** - * @template T - * @typedef {T | typeof TOMBSTONE | typeof UNDEFINED_MARKER} InternalCell - */ - -/** - * @template K - * @template V - * @param {[K, InternalCell]} pair the internal cell - * @returns {[K, Cell]} its “safe” representation - */ -const extractPair = pair => { - const key = pair[0]; - const val = pair[1]; - if (val === UNDEFINED_MARKER || val === TOMBSTONE) { - return [key, undefined]; - } else { - return /** @type {[K, Cell]} */ (pair); - } -}; - -/** - * @template K - * @template V - */ -class StackedMap { - /** - * @param {Map>[]=} parentStack an optional parent - */ - constructor(parentStack) { - /** @type {Map>} */ - this.map = new Map(); - /** @type {Map>[]} */ - this.stack = parentStack === undefined ? [] : parentStack.slice(); - this.stack.push(this.map); - } - - /** - * @param {K} item the key of the element to add - * @param {V} value the value of the element to add - * @returns {void} - */ - set(item, value) { - this.map.set(item, value === undefined ? UNDEFINED_MARKER : value); - } +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); +const { + parseVersionRuntimeCode, + versionLtRuntimeCode, + rangeToStringRuntimeCode, + satisfyRuntimeCode +} = __webpack_require__(19702); - /** - * @param {K} item the item to delete - * @returns {void} - */ - delete(item) { - if (this.stack.length > 1) { - this.map.set(item, TOMBSTONE); - } else { - this.map.delete(item); - } - } +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("./ConsumeSharedModule")} ConsumeSharedModule */ - /** - * @param {K} item the item to test - * @returns {boolean} true if the item exists in this set - */ - has(item) { - const topValue = this.map.get(item); - if (topValue !== undefined) { - return topValue !== TOMBSTONE; - } - if (this.stack.length > 1) { - for (let i = this.stack.length - 2; i >= 0; i--) { - const value = this.stack[i].get(item); - if (value !== undefined) { - this.map.set(item, value); - return value !== TOMBSTONE; - } - } - this.map.set(item, TOMBSTONE); - } - return false; +class ConsumeSharedRuntimeModule extends RuntimeModule { + constructor(runtimeRequirements) { + super("consumes", RuntimeModule.STAGE_ATTACH); + this._runtimeRequirements = runtimeRequirements; } /** - * @param {K} item the key of the element to return - * @returns {Cell} the value of the element + * @returns {string} runtime code */ - get(item) { - const topValue = this.map.get(item); - if (topValue !== undefined) { - return topValue === TOMBSTONE || topValue === UNDEFINED_MARKER - ? undefined - : topValue; - } - if (this.stack.length > 1) { - for (let i = this.stack.length - 2; i >= 0; i--) { - const value = this.stack[i].get(item); - if (value !== undefined) { - this.map.set(item, value); - return value === TOMBSTONE || value === UNDEFINED_MARKER - ? undefined - : value; - } + generate() { + const { compilation, chunkGraph } = this; + const { runtimeTemplate, codeGenerationResults } = compilation; + const chunkToModuleMapping = {}; + /** @type {Map} */ + const moduleIdToSourceMapping = new Map(); + const initialConsumes = []; + /** + * + * @param {Iterable} modules modules + * @param {Chunk} chunk the chunk + * @param {(string | number)[]} list list of ids + */ + const addModules = (modules, chunk, list) => { + for (const m of modules) { + const module = /** @type {ConsumeSharedModule} */ (m); + const id = chunkGraph.getModuleId(module); + list.push(id); + moduleIdToSourceMapping.set( + id, + codeGenerationResults.getSource( + module, + chunk.runtime, + "consume-shared" + ) + ); } - this.map.set(item, TOMBSTONE); + }; + for (const chunk of this.chunk.getAllAsyncChunks()) { + const modules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "consume-shared" + ); + if (!modules) continue; + addModules(modules, chunk, (chunkToModuleMapping[chunk.id] = [])); } - return undefined; - } - - _compress() { - if (this.stack.length === 1) return; - this.map = new Map(); - for (const data of this.stack) { - for (const pair of data) { - if (pair[1] === TOMBSTONE) { - this.map.delete(pair[0]); - } else { - this.map.set(pair[0], pair[1]); - } - } + for (const chunk of this.chunk.getAllInitialChunks()) { + const modules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "consume-shared" + ); + if (!modules) continue; + addModules(modules, chunk, initialConsumes); } - this.stack = [this.map]; - } - - asArray() { - this._compress(); - return Array.from(this.map.keys()); - } - - asSet() { - this._compress(); - return new Set(this.map.keys()); - } - - asPairArray() { - this._compress(); - return Array.from(this.map.entries(), extractPair); - } - - asMap() { - return new Map(this.asPairArray()); - } - - get size() { - this._compress(); - return this.map.size; - } + if (moduleIdToSourceMapping.size === 0) return null; + return Template.asString([ + parseVersionRuntimeCode(runtimeTemplate), + versionLtRuntimeCode(runtimeTemplate), + rangeToStringRuntimeCode(runtimeTemplate), + satisfyRuntimeCode(runtimeTemplate), + `var ensureExistence = ${runtimeTemplate.basicFunction("scopeName, key", [ + `var scope = ${RuntimeGlobals.shareScopeMap}[scopeName];`, + `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) throw new Error("Shared module " + key + " doesn't exist in shared scope " + scopeName);`, + "return scope;" + ])};`, + `var findVersion = ${runtimeTemplate.basicFunction("scope, key", [ + "var versions = scope[key];", + `var key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( + "a, b", + ["return !a || versionLt(a, b) ? b : a;"] + )}, 0);`, + "return key && versions[key]" + ])};`, + `var findSingletonVersionKey = ${runtimeTemplate.basicFunction( + "scope, key", + [ + "var versions = scope[key];", + `return Object.keys(versions).reduce(${runtimeTemplate.basicFunction( + "a, b", + ["return !a || (!versions[a].loaded && versionLt(a, b)) ? b : a;"] + )}, 0);` + ] + )};`, + `var getInvalidSingletonVersionMessage = ${runtimeTemplate.basicFunction( + "scope, key, version, requiredVersion", + [ + `return "Unsatisfied version " + version + " from " + (version && scope[key][version].from) + " of shared singleton module " + key + " (required " + rangeToString(requiredVersion) + ")"` + ] + )};`, + `var getSingleton = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion", + [ + "var version = findSingletonVersionKey(scope, key);", + "return get(scope[key][version]);" + ] + )};`, + `var getSingletonVersion = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion", + [ + "var version = findSingletonVersionKey(scope, key);", + "if (!satisfy(requiredVersion, version)) " + + 'typeof console !== "undefined" && console.warn && console.warn(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));', + "return get(scope[key][version]);" + ] + )};`, + `var getStrictSingletonVersion = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion", + [ + "var version = findSingletonVersionKey(scope, key);", + "if (!satisfy(requiredVersion, version)) " + + "throw new Error(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));", + "return get(scope[key][version]);" + ] + )};`, + `var findValidVersion = ${runtimeTemplate.basicFunction( + "scope, key, requiredVersion", + [ + "var versions = scope[key];", + `var key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( + "a, b", + [ + "if (!satisfy(requiredVersion, b)) return a;", + "return !a || versionLt(a, b) ? b : a;" + ] + )}, 0);`, + "return key && versions[key]" + ] + )};`, + `var getInvalidVersionMessage = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion", + [ + "var versions = scope[key];", + 'return "No satisfying version (" + rangeToString(requiredVersion) + ") of shared module " + key + " found in shared scope " + scopeName + ".\\n" +', + `\t"Available versions: " + Object.keys(versions).map(${runtimeTemplate.basicFunction( + "key", + ['return key + " from " + versions[key].from;'] + )}).join(", ");` + ] + )};`, + `var getValidVersion = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion", + [ + "var entry = findValidVersion(scope, key, requiredVersion);", + "if(entry) return get(entry);", + "throw new Error(getInvalidVersionMessage(scope, scopeName, key, requiredVersion));" + ] + )};`, + `var warnInvalidVersion = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion", + [ + 'typeof console !== "undefined" && console.warn && console.warn(getInvalidVersionMessage(scope, scopeName, key, requiredVersion));' + ] + )};`, + `var get = ${runtimeTemplate.basicFunction("entry", [ + "entry.loaded = 1;", + "return entry.get()" + ])};`, + `var init = ${runtimeTemplate.returningFunction( + Template.asString([ + "function(scopeName, a, b, c) {", + Template.indent([ + `var promise = ${RuntimeGlobals.initializeSharing}(scopeName);`, + `if (promise && promise.then) return promise.then(fn.bind(fn, scopeName, ${RuntimeGlobals.shareScopeMap}[scopeName], a, b, c));`, + `return fn(scopeName, ${RuntimeGlobals.shareScopeMap}[scopeName], a, b, c);` + ]), + "}" + ]), + "fn" + )};`, + "", + `var load = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key", + [ + "ensureExistence(scopeName, key);", + "return get(findVersion(scope, key));" + ] + )});`, + `var loadFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, fallback", + [ + `return scope && ${RuntimeGlobals.hasOwnProperty}(scope, key) ? get(findVersion(scope, key)) : fallback();` + ] + )});`, + `var loadVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version", + [ + "ensureExistence(scopeName, key);", + "return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key));" + ] + )});`, + `var loadSingleton = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key", + [ + "ensureExistence(scopeName, key);", + "return getSingleton(scope, scopeName, key);" + ] + )});`, + `var loadSingletonVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version", + [ + "ensureExistence(scopeName, key);", + "return getSingletonVersion(scope, scopeName, key, version);" + ] + )});`, + `var loadStrictVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version", + [ + "ensureExistence(scopeName, key);", + "return getValidVersion(scope, scopeName, key, version);" + ] + )});`, + `var loadStrictSingletonVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version", + [ + "ensureExistence(scopeName, key);", + "return getStrictSingletonVersion(scope, scopeName, key, version);" + ] + )});`, + `var loadVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version, fallback", + [ + `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, + "return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key));" + ] + )});`, + `var loadSingletonFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, fallback", + [ + `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, + "return getSingleton(scope, scopeName, key);" + ] + )});`, + `var loadSingletonVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version, fallback", + [ + `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, + "return getSingletonVersion(scope, scopeName, key, version);" + ] + )});`, + `var loadStrictVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version, fallback", + [ + `var entry = scope && ${RuntimeGlobals.hasOwnProperty}(scope, key) && findValidVersion(scope, key, version);`, + `return entry ? get(entry) : fallback();` + ] + )});`, + `var loadStrictSingletonVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version, fallback", + [ + `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, + "return getStrictSingletonVersion(scope, scopeName, key, version);" + ] + )});`, + "var installedModules = {};", + "var moduleToHandlerMapping = {", + Template.indent( + Array.from( + moduleIdToSourceMapping, + ([key, source]) => `${JSON.stringify(key)}: ${source.source()}` + ).join(",\n") + ), + "};", - createChild() { - return new StackedMap(this.stack); + initialConsumes.length > 0 + ? Template.asString([ + `var initialConsumes = ${JSON.stringify(initialConsumes)};`, + `initialConsumes.forEach(${runtimeTemplate.basicFunction("id", [ + `${ + RuntimeGlobals.moduleFactories + }[id] = ${runtimeTemplate.basicFunction("module", [ + "// Handle case when module is used sync", + "installedModules[id] = 0;", + `delete ${RuntimeGlobals.moduleCache}[id];`, + "var factory = moduleToHandlerMapping[id]();", + 'if(typeof factory !== "function") throw new Error("Shared module is not available for eager consumption: " + id);', + `module.exports = factory();` + ])}` + ])});` + ]) + : "// no consumes in initial chunks", + this._runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) + ? Template.asString([ + `var chunkMapping = ${JSON.stringify( + chunkToModuleMapping, + null, + "\t" + )};`, + `${ + RuntimeGlobals.ensureChunkHandlers + }.consumes = ${runtimeTemplate.basicFunction("chunkId, promises", [ + `if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`, + Template.indent([ + `chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction( + "id", + [ + `if(${RuntimeGlobals.hasOwnProperty}(installedModules, id)) return promises.push(installedModules[id]);`, + `var onFactory = ${runtimeTemplate.basicFunction( + "factory", + [ + "installedModules[id] = 0;", + `${ + RuntimeGlobals.moduleFactories + }[id] = ${runtimeTemplate.basicFunction("module", [ + `delete ${RuntimeGlobals.moduleCache}[id];`, + "module.exports = factory();" + ])}` + ] + )};`, + `var onError = ${runtimeTemplate.basicFunction("error", [ + "delete installedModules[id];", + `${ + RuntimeGlobals.moduleFactories + }[id] = ${runtimeTemplate.basicFunction("module", [ + `delete ${RuntimeGlobals.moduleCache}[id];`, + "throw error;" + ])}` + ])};`, + "try {", + Template.indent([ + "var promise = moduleToHandlerMapping[id]();", + "if(promise.then) {", + Template.indent( + "promises.push(installedModules[id] = promise.then(onFactory)['catch'](onError));" + ), + "} else onFactory(promise);" + ]), + "} catch(e) { onError(e); }" + ] + )});` + ]), + "}" + ])}` + ]) + : "// no chunk loading of consumes" + ]); } } -module.exports = StackedMap; +module.exports = ConsumeSharedRuntimeModule; /***/ }), -/***/ 40293: -/***/ (function(module) { +/***/ 40017: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -122893,59 +128127,38 @@ module.exports = StackedMap; -class StringXor { - constructor() { - this._value = undefined; - } +const ModuleDependency = __webpack_require__(80321); +const makeSerializable = __webpack_require__(33032); +class ProvideForSharedDependency extends ModuleDependency { /** - * @param {string} str string - * @returns {void} + * + * @param {string} request request string */ - add(str) { - const len = str.length; - const value = this._value; - if (value === undefined) { - const newValue = (this._value = Buffer.allocUnsafe(len)); - for (let i = 0; i < len; i++) { - newValue[i] = str.charCodeAt(i); - } - return; - } - const valueLen = value.length; - if (valueLen < len) { - const newValue = (this._value = Buffer.allocUnsafe(len)); - let i; - for (i = 0; i < valueLen; i++) { - newValue[i] = value[i] ^ str.charCodeAt(i); - } - for (; i < len; i++) { - newValue[i] = str.charCodeAt(i); - } - } else { - for (let i = 0; i < len; i++) { - value[i] = value[i] ^ str.charCodeAt(i); - } - } + constructor(request) { + super(request); } - toString() { - const value = this._value; - return value === undefined ? "" : value.toString("latin1"); + get type() { + return "provide module for shared"; } - updateHash(hash) { - const value = this._value; - if (value !== undefined) hash.update(value); + get category() { + return "esm"; } } -module.exports = StringXor; +makeSerializable( + ProvideForSharedDependency, + "webpack/lib/sharing/ProvideForSharedDependency" +); + +module.exports = ProvideForSharedDependency; /***/ }), -/***/ 38415: +/***/ 1798: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -122956,592 +128169,648 @@ module.exports = StringXor; -const TupleSet = __webpack_require__(76455); +const Dependency = __webpack_require__(54912); +const makeSerializable = __webpack_require__(33032); -/** - * @template {any[]} T - */ -class TupleQueue { - /** - * @param {Iterable=} items The initial elements. - */ - constructor(items) { - /** @private @type {TupleSet} */ - this._set = new TupleSet(items); - /** @private @type {Iterator} */ - this._iterator = this._set[Symbol.iterator](); +class ProvideSharedDependency extends Dependency { + constructor(shareScope, name, version, request, eager) { + super(); + this.shareScope = shareScope; + this.name = name; + this.version = version; + this.request = request; + this.eager = eager; } - /** - * Returns the number of elements in this queue. - * @returns {number} The number of elements in this queue. - */ - get length() { - return this._set.size; + get type() { + return "provide shared module"; } /** - * Appends the specified element to this queue. - * @param {T} item The element to add. - * @returns {void} + * @returns {string | null} an identifier to merge equal requests */ - enqueue(...item) { - this._set.add(...item); + getResourceIdentifier() { + return `provide module (${this.shareScope}) ${this.request} as ${ + this.name + } @ ${this.version}${this.eager ? " (eager)" : ""}`; } - /** - * Retrieves and removes the head of this queue. - * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. - */ - dequeue() { - const result = this._iterator.next(); - if (result.done) { - if (this._set.size > 0) { - this._iterator = this._set[Symbol.iterator](); - const value = this._iterator.next().value; - this._set.delete(...value); - return value; - } - return undefined; - } - this._set.delete(...result.value); - return result.value; + serialize(context) { + context.write(this.shareScope); + context.write(this.name); + context.write(this.request); + context.write(this.version); + context.write(this.eager); + super.serialize(context); + } + + static deserialize(context) { + const { read } = context; + const obj = new ProvideSharedDependency( + read(), + read(), + read(), + read(), + read() + ); + this.shareScope = context.read(); + obj.deserialize(context); + return obj; } } -module.exports = TupleQueue; +makeSerializable( + ProvideSharedDependency, + "webpack/lib/sharing/ProvideSharedDependency" +); + +module.exports = ProvideSharedDependency; /***/ }), -/***/ 76455: -/***/ (function(module) { +/***/ 50821: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ -/** - * @template {any[]} T - */ -class TupleSet { - constructor(init) { - this._map = new Map(); - this.size = 0; - if (init) { - for (const tuple of init) { - this.add(...tuple); - } - } - } +const AsyncDependenciesBlock = __webpack_require__(47736); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const ProvideForSharedDependency = __webpack_require__(40017); + +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +const TYPES = new Set(["share-init"]); + +class ProvideSharedModule extends Module { /** - * @param {T} args tuple - * @returns {void} + * @param {string} shareScope shared scope name + * @param {string} name shared key + * @param {string | false} version version + * @param {string} request request to the provided module + * @param {boolean} eager include the module in sync way */ - add(...args) { - let map = this._map; - for (let i = 0; i < args.length - 2; i++) { - const arg = args[i]; - const innerMap = map.get(arg); - if (innerMap === undefined) { - map.set(arg, (map = new Map())); - } else { - map = innerMap; - } - } - - const beforeLast = args[args.length - 2]; - let set = map.get(beforeLast); - if (set === undefined) { - map.set(beforeLast, (set = new Set())); - } + constructor(shareScope, name, version, request, eager) { + super("provide-module"); + this._shareScope = shareScope; + this._name = name; + this._version = version; + this._request = request; + this._eager = eager; + } - const last = args[args.length - 1]; - this.size -= set.size; - set.add(last); - this.size += set.size; + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `provide module (${this._shareScope}) ${this._name}@${this._version} = ${this._request}`; } /** - * @param {T} args tuple - * @returns {boolean} true, if the tuple is in the Set + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module */ - has(...args) { - let map = this._map; - for (let i = 0; i < args.length - 2; i++) { - const arg = args[i]; - map = map.get(arg); - if (map === undefined) { - return false; - } - } + readableIdentifier(requestShortener) { + return `provide shared module (${this._shareScope}) ${this._name}@${ + this._version + } = ${requestShortener.shorten(this._request)}`; + } - const beforeLast = args[args.length - 2]; - let set = map.get(beforeLast); - if (set === undefined) { - return false; - } + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `${this.layer ? `(${this.layer})/` : ""}webpack/sharing/provide/${ + this._shareScope + }/${this._name}`; + } - const last = args[args.length - 1]; - return set.has(last); + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + callback(null, !this.buildInfo); } /** - * @param {T} args tuple + * @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} */ - delete(...args) { - let map = this._map; - for (let i = 0; i < args.length - 2; i++) { - const arg = args[i]; - map = map.get(arg); - if (map === undefined) { - return; - } - } + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = { + strict: true + }; - const beforeLast = args[args.length - 2]; - let set = map.get(beforeLast); - if (set === undefined) { - return; + this.clearDependenciesAndBlocks(); + const dep = new ProvideForSharedDependency(this._request); + if (this._eager) { + this.addDependency(dep); + } else { + const block = new AsyncDependenciesBlock({}); + block.addDependency(dep); + this.addBlock(block); } - const last = args[args.length - 1]; - this.size -= set.size; - set.delete(last); - this.size += set.size; + callback(); } /** - * @returns {Iterator} iterator + * @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) */ - [Symbol.iterator]() { - const iteratorStack = []; - const tuple = []; - let currentSetIterator = undefined; + size(type) { + return 42; + } - const next = it => { - const result = it.next(); - if (result.done) { - if (iteratorStack.length === 0) return false; - tuple.pop(); - return next(iteratorStack.pop()); - } - const [key, value] = result.value; - iteratorStack.push(it); - tuple.push(key); - if (value instanceof Set) { - currentSetIterator = value[Symbol.iterator](); - return true; - } else { - return next(value[Symbol.iterator]()); + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { + const runtimeRequirements = new Set([RuntimeGlobals.initializeSharing]); + const code = `register(${JSON.stringify(this._name)}, ${JSON.stringify( + this._version || "0" + )}, ${ + this._eager + ? runtimeTemplate.syncModuleFactory({ + dependency: this.dependencies[0], + chunkGraph, + request: this._request, + runtimeRequirements + }) + : runtimeTemplate.asyncModuleFactory({ + block: this.blocks[0], + chunkGraph, + request: this._request, + runtimeRequirements + }) + }${this._eager ? ", 1" : ""});`; + const sources = new Map(); + const data = new Map(); + data.set("share-init", [ + { + shareScope: this._shareScope, + initStage: 10, + init: code } - }; + ]); + return { sources, data, runtimeRequirements }; + } - next(this._map[Symbol.iterator]()); + serialize(context) { + const { write } = context; + write(this._shareScope); + write(this._name); + write(this._version); + write(this._request); + write(this._eager); + super.serialize(context); + } - return { - next() { - while (currentSetIterator) { - const result = currentSetIterator.next(); - if (result.done) { - tuple.pop(); - if (!next(iteratorStack.pop())) { - currentSetIterator = undefined; - } - } else { - return { - done: false, - value: /** @type {T} */ (tuple.concat(result.value)) - }; - } - } - return { done: true, value: undefined }; - } - }; + static deserialize(context) { + const { read } = context; + const obj = new ProvideSharedModule(read(), read(), read(), read(), read()); + obj.deserialize(context); + return obj; } } -module.exports = TupleSet; +makeSerializable( + ProvideSharedModule, + "webpack/lib/sharing/ProvideSharedModule" +); + +module.exports = ProvideSharedModule; /***/ }), -/***/ 54500: -/***/ (function(__unused_webpack_module, exports) { +/***/ 39344: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ -/** @typedef {import("./fs").InputFileSystem} InputFileSystem */ -/** @typedef {(error: Error|null, result?: Buffer) => void} ErrorFirstCallback */ - -const backSlashCharCode = "\\".charCodeAt(0); -const slashCharCode = "/".charCodeAt(0); -const aLowerCaseCharCode = "a".charCodeAt(0); -const zLowerCaseCharCode = "z".charCodeAt(0); -const aUpperCaseCharCode = "A".charCodeAt(0); -const zUpperCaseCharCode = "Z".charCodeAt(0); -const _0CharCode = "0".charCodeAt(0); -const _9CharCode = "9".charCodeAt(0); -const plusCharCode = "+".charCodeAt(0); -const hyphenCharCode = "-".charCodeAt(0); -const colonCharCode = ":".charCodeAt(0); -const hashCharCode = "#".charCodeAt(0); -const queryCharCode = "?".charCodeAt(0); -/** - * Get scheme if specifier is an absolute URL specifier - * e.g. Absolute specifiers like 'file:///user/webpack/index.js' - * https://tools.ietf.org/html/rfc3986#section-3.1 - * @param {string} specifier specifier - * @returns {string|undefined} scheme if absolute URL specifier provided - */ -function getScheme(specifier) { - const start = specifier.charCodeAt(0); - - // First char maybe only a letter - if ( - (start < aLowerCaseCharCode || start > zLowerCaseCharCode) && - (start < aUpperCaseCharCode || start > zUpperCaseCharCode) - ) { - return undefined; - } - - let i = 1; - let ch = specifier.charCodeAt(i); - - while ( - (ch >= aLowerCaseCharCode && ch <= zLowerCaseCharCode) || - (ch >= aUpperCaseCharCode && ch <= zUpperCaseCharCode) || - (ch >= _0CharCode && ch <= _9CharCode) || - ch === plusCharCode || - ch === hyphenCharCode - ) { - if (++i === specifier.length) return undefined; - ch = specifier.charCodeAt(i); - } +const ModuleFactory = __webpack_require__(51010); +const ProvideSharedModule = __webpack_require__(50821); - // Scheme must end with colon - if (ch !== colonCharCode) return undefined; +/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./ProvideSharedDependency")} ProvideSharedDependency */ - // Check for Windows absolute path - // https://url.spec.whatwg.org/#url-miscellaneous - if (i === 1) { - const nextChar = i + 1 < specifier.length ? specifier.charCodeAt(i + 1) : 0; - if ( - nextChar === 0 || - nextChar === backSlashCharCode || - nextChar === slashCharCode || - nextChar === hashCharCode || - nextChar === queryCharCode - ) { - return undefined; - } +class ProvideSharedModuleFactory extends ModuleFactory { + /** + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * @returns {void} + */ + create(data, callback) { + const dep = /** @type {ProvideSharedDependency} */ (data.dependencies[0]); + callback(null, { + module: new ProvideSharedModule( + dep.shareScope, + dep.name, + dep.version, + dep.request, + dep.eager + ) + }); } - - return specifier.slice(0, i).toLowerCase(); -} - -/** - * @param {string} specifier specifier - * @returns {string|null} protocol if absolute URL specifier provided - */ -function getProtocol(specifier) { - const scheme = getScheme(specifier); - return scheme === undefined ? undefined : scheme + ":"; } -exports.getScheme = getScheme; -exports.getProtocol = getProtocol; +module.exports = ProvideSharedModuleFactory; /***/ }), -/***/ 28745: -/***/ (function(module) { +/***/ 31225: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ -const isWeakKey = thing => typeof thing === "object" && thing !== null; +const WebpackError = __webpack_require__(53799); +const { parseOptions } = __webpack_require__(3083); +const createSchemaValidation = __webpack_require__(32540); +const ProvideForSharedDependency = __webpack_require__(40017); +const ProvideSharedDependency = __webpack_require__(1798); +const ProvideSharedModuleFactory = __webpack_require__(39344); -/** - * @template {any[]} T - * @template V - */ -class WeakTupleMap { - constructor() { - /** @private */ - this.f = 0; - /** @private @type {any} */ - this.v = undefined; - /** @private @type {Map> | undefined} */ - this.m = undefined; - /** @private @type {WeakMap> | undefined} */ - this.w = undefined; - } +/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvideSharedPluginOptions} ProvideSharedPluginOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ - /** - * @param {[...T, V]} args tuple - * @returns {void} - */ - set(...args) { - /** @type {WeakTupleMap} */ - let node = this; - for (let i = 0; i < args.length - 1; i++) { - node = node._get(args[i]); - } - node._setValue(args[args.length - 1]); +const validate = createSchemaValidation( + __webpack_require__(91924), + () => __webpack_require__(438), + { + name: "Provide Shared Plugin", + baseDataPath: "options" } +); - /** - * @param {T} args tuple - * @returns {boolean} true, if the tuple is in the Set - */ - has(...args) { - /** @type {WeakTupleMap} */ - let node = this; - for (let i = 0; i < args.length; i++) { - node = node._peek(args[i]); - if (node === undefined) return false; - } - return node._hasValue(); - } +/** + * @typedef {Object} ProvideOptions + * @property {string} shareKey + * @property {string} shareScope + * @property {string | undefined | false} version + * @property {boolean} eager + */ - /** - * @param {T} args tuple - * @returns {V} the value - */ - get(...args) { - /** @type {WeakTupleMap} */ - let node = this; - for (let i = 0; i < args.length; i++) { - node = node._peek(args[i]); - if (node === undefined) return undefined; - } - return node._getValue(); - } +/** @typedef {Map} ResolvedProvideMap */ +class ProvideSharedPlugin { /** - * @param {[...T, function(): V]} args tuple - * @returns {V} the value + * @param {ProvideSharedPluginOptions} options options */ - provide(...args) { - /** @type {WeakTupleMap} */ - let node = this; - for (let i = 0; i < args.length - 1; i++) { - node = node._get(args[i]); - } - if (node._hasValue()) return node._getValue(); - const fn = args[args.length - 1]; - const newValue = fn(...args.slice(0, -1)); - node._setValue(newValue); - return newValue; - } + constructor(options) { + validate(options); - /** - * @param {T} args tuple - * @returns {void} - */ - delete(...args) { - /** @type {WeakTupleMap} */ - let node = this; - for (let i = 0; i < args.length; i++) { - node = node._peek(args[i]); - if (node === undefined) return; - } - node._deleteValue(); + /** @type {[string, ProvideOptions][]} */ + this._provides = parseOptions( + options.provides, + item => { + if (Array.isArray(item)) + throw new Error("Unexpected array of provides"); + /** @type {ProvideOptions} */ + const result = { + shareKey: item, + version: undefined, + shareScope: options.shareScope || "default", + eager: false + }; + return result; + }, + item => ({ + shareKey: item.shareKey, + version: item.version, + shareScope: item.shareScope || options.shareScope || "default", + eager: !!item.eager + }) + ); + this._provides.sort(([a], [b]) => { + if (a < b) return -1; + if (b < a) return 1; + return 0; + }); } /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - clear() { - this.f = 0; - this.v = undefined; - this.w = undefined; - this.m = undefined; - } - - _getValue() { - return this.v; - } - - _hasValue() { - return (this.f & 1) === 1; - } - - _setValue(v) { - this.f |= 1; - this.v = v; - } + apply(compiler) { + /** @type {WeakMap} */ + const compilationData = new WeakMap(); - _deleteValue() { - this.f &= 6; - this.v = undefined; - } + compiler.hooks.compilation.tap( + "ProvideSharedPlugin", + (compilation, { normalModuleFactory }) => { + /** @type {ResolvedProvideMap} */ + const resolvedProvideMap = new Map(); + /** @type {Map} */ + const matchProvides = new Map(); + /** @type {Map} */ + const prefixMatchProvides = new Map(); + for (const [request, config] of this._provides) { + if (/^(\/|[A-Za-z]:\\|\\\\|\.\.?(\/|$))/.test(request)) { + // relative request + resolvedProvideMap.set(request, { + config, + version: config.version + }); + } else if (/^(\/|[A-Za-z]:\\|\\\\)/.test(request)) { + // absolute path + resolvedProvideMap.set(request, { + config, + version: config.version + }); + } else if (request.endsWith("/")) { + // module request prefix + prefixMatchProvides.set(request, config); + } else { + // module request + matchProvides.set(request, config); + } + } + compilationData.set(compilation, resolvedProvideMap); + const provideSharedModule = ( + key, + config, + resource, + resourceResolveData + ) => { + let version = config.version; + if (version === undefined) { + let details = ""; + if (!resourceResolveData) { + details = `No resolve data provided from resolver.`; + } else { + const descriptionFileData = + resourceResolveData.descriptionFileData; + if (!descriptionFileData) { + details = + "No description file (usually package.json) found. Add description file with name and version, or manually specify version in shared config."; + } else if (!descriptionFileData.version) { + details = + "No version in description file (usually package.json). Add version to description file, or manually specify version in shared config."; + } else { + version = descriptionFileData.version; + } + } + if (!version) { + const error = new WebpackError( + `No version specified and unable to automatically determine one. ${details}` + ); + error.file = `shared module ${key} -> ${resource}`; + compilation.warnings.push(error); + } + } + resolvedProvideMap.set(resource, { + config, + version + }); + }; + normalModuleFactory.hooks.module.tap( + "ProvideSharedPlugin", + (module, { resource, resourceResolveData }, resolveData) => { + if (resolvedProvideMap.has(resource)) { + return module; + } + const { request } = resolveData; + { + const config = matchProvides.get(request); + if (config !== undefined) { + provideSharedModule( + request, + config, + resource, + resourceResolveData + ); + resolveData.cacheable = false; + } + } + for (const [prefix, config] of prefixMatchProvides) { + if (request.startsWith(prefix)) { + const remainder = request.slice(prefix.length); + provideSharedModule( + resource, + { + ...config, + shareKey: config.shareKey + remainder + }, + resource, + resourceResolveData + ); + resolveData.cacheable = false; + } + } + return module; + } + ); + } + ); + compiler.hooks.finishMake.tapPromise("ProvideSharedPlugin", compilation => { + const resolvedProvideMap = compilationData.get(compilation); + if (!resolvedProvideMap) return Promise.resolve(); + return Promise.all( + Array.from( + resolvedProvideMap, + ([resource, { config, version }]) => + new Promise((resolve, reject) => { + compilation.addInclude( + compiler.context, + new ProvideSharedDependency( + config.shareScope, + config.shareKey, + version || false, + resource, + config.eager + ), + { + name: undefined + }, + err => { + if (err) return reject(err); + resolve(); + } + ); + }) + ) + ).then(() => {}); + }); - _peek(thing) { - if (isWeakKey(thing)) { - if ((this.f & 4) !== 4) return undefined; - return this.w.get(thing); - } else { - if ((this.f & 2) !== 2) return undefined; - return this.m.get(thing); - } - } + compiler.hooks.compilation.tap( + "ProvideSharedPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + ProvideForSharedDependency, + normalModuleFactory + ); - _get(thing) { - if (isWeakKey(thing)) { - if ((this.f & 4) !== 4) { - const newMap = new WeakMap(); - this.f |= 4; - const newNode = new WeakTupleMap(); - (this.w = newMap).set(thing, newNode); - return newNode; - } - const entry = this.w.get(thing); - if (entry !== undefined) { - return entry; - } - const newNode = new WeakTupleMap(); - this.w.set(thing, newNode); - return newNode; - } else { - if ((this.f & 2) !== 2) { - const newMap = new Map(); - this.f |= 2; - const newNode = new WeakTupleMap(); - (this.m = newMap).set(thing, newNode); - return newNode; - } - const entry = this.m.get(thing); - if (entry !== undefined) { - return entry; + compilation.dependencyFactories.set( + ProvideSharedDependency, + new ProvideSharedModuleFactory() + ); } - const newNode = new WeakTupleMap(); - this.m.set(thing, newNode); - return newNode; - } + ); } } -module.exports = WeakTupleMap; +module.exports = ProvideSharedPlugin; /***/ }), -/***/ 92229: -/***/ (function(module) { +/***/ 26335: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Mikola Lysenko @mikolalysenko + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ -/* cspell:disable-next-line */ -// Refactor: Peter Somogyvari @petermetz +const { parseOptions } = __webpack_require__(3083); +const ConsumeSharedPlugin = __webpack_require__(15046); +const ProvideSharedPlugin = __webpack_require__(31225); +const { isRequiredVersion } = __webpack_require__(84379); -const compileSearch = (funcName, predicate, reversed, extraArgs, earlyOut) => { - const code = [ - "function ", - funcName, - "(a,l,h,", - extraArgs.join(","), - "){", - earlyOut ? "" : "var i=", - reversed ? "l-1" : "h+1", - ";while(l<=h){var m=(l+h)>>>1,x=a[m]" - ]; +/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumeSharedPluginOptions} ConsumeSharedPluginOptions */ +/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumesConfig} ConsumesConfig */ +/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvideSharedPluginOptions} ProvideSharedPluginOptions */ +/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvidesConfig} ProvidesConfig */ +/** @typedef {import("../../declarations/plugins/sharing/SharePlugin").SharePluginOptions} SharePluginOptions */ +/** @typedef {import("../../declarations/plugins/sharing/SharePlugin").SharedConfig} SharedConfig */ +/** @typedef {import("../Compiler")} Compiler */ - if (earlyOut) { - if (predicate.indexOf("c") < 0) { - code.push(";if(x===y){return m}else if(x<=y){"); - } else { - code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"); - } - } else { - code.push(";if(", predicate, "){i=m;"); - } - if (reversed) { - code.push("l=m+1}else{h=m-1}"); - } else { - code.push("h=m-1}else{l=m+1}"); - } - code.push("}"); - if (earlyOut) { - code.push("return -1};"); - } else { - code.push("return i};"); +class SharePlugin { + /** + * @param {SharePluginOptions} options options + */ + constructor(options) { + /** @type {[string, SharedConfig][]} */ + const sharedOptions = parseOptions( + options.shared, + (item, key) => { + if (typeof item !== "string") + throw new Error("Unexpected array in shared"); + /** @type {SharedConfig} */ + const config = + item === key || !isRequiredVersion(item) + ? { + import: item + } + : { + import: key, + requiredVersion: item + }; + return config; + }, + item => item + ); + /** @type {Record[]} */ + const consumes = sharedOptions.map(([key, options]) => ({ + [key]: { + import: options.import, + shareKey: options.shareKey || key, + shareScope: options.shareScope, + requiredVersion: options.requiredVersion, + strictVersion: options.strictVersion, + singleton: options.singleton, + packageName: options.packageName, + eager: options.eager + } + })); + /** @type {Record[]} */ + const provides = sharedOptions + .filter(([, options]) => options.import !== false) + .map(([key, options]) => ({ + [options.import || key]: { + shareKey: options.shareKey || key, + shareScope: options.shareScope, + version: options.version, + eager: options.eager + } + })); + this._shareScope = options.shareScope; + this._consumes = consumes; + this._provides = provides; } - return code.join(""); -}; - -const compileBoundsSearch = (predicate, reversed, suffix, earlyOut) => { - const arg1 = compileSearch( - "A", - "x" + predicate + "y", - reversed, - ["y"], - earlyOut - ); - - const arg2 = compileSearch( - "P", - "c(x,y)" + predicate + "0", - reversed, - ["y", "c"], - earlyOut - ); - - const fnHeader = "function dispatchBinarySearch"; - - const fnBody = - "(a,y,c,l,h){\ -if(typeof(c)==='function'){\ -return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ -}else{\ -return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ -}}\ -return dispatchBinarySearch"; - const fnArgList = [arg1, arg2, fnHeader, suffix, fnBody, suffix]; - const fnSource = fnArgList.join(""); - const result = new Function(fnSource); - return result(); -}; + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + new ConsumeSharedPlugin({ + shareScope: this._shareScope, + consumes: this._consumes + }).apply(compiler); + new ProvideSharedPlugin({ + shareScope: this._shareScope, + provides: this._provides + }).apply(compiler); + } +} -module.exports = { - ge: compileBoundsSearch(">=", false, "GE"), - gt: compileBoundsSearch(">", false, "GT"), - lt: compileBoundsSearch("<", true, "LT"), - le: compileBoundsSearch("<=", true, "LE"), - eq: compileBoundsSearch("-", true, "EQ", true) -}; +module.exports = SharePlugin; /***/ }), -/***/ 60839: -/***/ (function(__unused_webpack_module, exports) { +/***/ 96066: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -123551,573 +128820,343 @@ module.exports = { -/** @type {WeakMap>} */ -const mergeCache = new WeakMap(); -/** @type {WeakMap>>} */ -const setPropertyCache = new WeakMap(); -const DELETE = Symbol("DELETE"); -const DYNAMIC_INFO = Symbol("cleverMerge dynamic info"); - -/** - * Merges two given objects and caches the result to avoid computation if same objects passed as arguments again. - * @template T - * @template O - * @example - * // performs cleverMerge(first, second), stores the result in WeakMap and returns result - * cachedCleverMerge({a: 1}, {a: 2}) - * {a: 2} - * // when same arguments passed, gets the result from WeakMap and returns it. - * cachedCleverMerge({a: 1}, {a: 2}) - * {a: 2} - * @param {T} first first object - * @param {O} second second object - * @returns {T & O | T | O} merged object of first and second object - */ -const cachedCleverMerge = (first, second) => { - if (second === undefined) return first; - if (first === undefined) return second; - if (typeof second !== "object" || second === null) return second; - if (typeof first !== "object" || first === null) return first; +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); +const { + compareModulesByIdentifier, + compareStrings +} = __webpack_require__(29579); - let innerCache = mergeCache.get(first); - if (innerCache === undefined) { - innerCache = new WeakMap(); - mergeCache.set(first, innerCache); +class ShareRuntimeModule extends RuntimeModule { + constructor() { + super("sharing"); } - const prevMerge = innerCache.get(second); - if (prevMerge !== undefined) return prevMerge; - const newMerge = _cleverMerge(first, second, true); - innerCache.set(second, newMerge); - return newMerge; -}; - -/** - * @template T - * @param {Partial} obj object - * @param {string} property property - * @param {string|number|boolean} value assignment value - * @returns {T} new object - */ -const cachedSetProperty = (obj, property, value) => { - let mapByProperty = setPropertyCache.get(obj); - if (mapByProperty === undefined) { - mapByProperty = new Map(); - setPropertyCache.set(obj, mapByProperty); + /** + * @returns {string} runtime code + */ + generate() { + const { compilation, chunkGraph } = this; + const { + runtimeTemplate, + codeGenerationResults, + outputOptions: { uniqueName } + } = compilation; + /** @type {Map>>} */ + const initCodePerScope = new Map(); + for (const chunk of this.chunk.getAllReferencedChunks()) { + const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "share-init", + compareModulesByIdentifier + ); + if (!modules) continue; + for (const m of modules) { + const data = codeGenerationResults.getData( + m, + chunk.runtime, + "share-init" + ); + if (!data) continue; + for (const item of data) { + const { shareScope, initStage, init } = item; + let stages = initCodePerScope.get(shareScope); + if (stages === undefined) { + initCodePerScope.set(shareScope, (stages = new Map())); + } + let list = stages.get(initStage || 0); + if (list === undefined) { + stages.set(initStage || 0, (list = new Set())); + } + list.add(init); + } + } + } + return Template.asString([ + `${RuntimeGlobals.shareScopeMap} = {};`, + "var initPromises = {};", + "var initTokens = {};", + `${RuntimeGlobals.initializeSharing} = ${runtimeTemplate.basicFunction( + "name, initScope", + [ + "if(!initScope) initScope = [];", + "// handling circular init calls", + "var initToken = initTokens[name];", + "if(!initToken) initToken = initTokens[name] = {};", + "if(initScope.indexOf(initToken) >= 0) return;", + "initScope.push(initToken);", + "// only runs once", + "if(initPromises[name]) return initPromises[name];", + "// creates a new share scope if needed", + `if(!${RuntimeGlobals.hasOwnProperty}(${RuntimeGlobals.shareScopeMap}, name)) ${RuntimeGlobals.shareScopeMap}[name] = {};`, + "// runs all init snippets from all modules reachable", + `var scope = ${RuntimeGlobals.shareScopeMap}[name];`, + `var warn = ${runtimeTemplate.returningFunction( + 'typeof console !== "undefined" && console.warn && console.warn(msg)', + "msg" + )};`, + `var uniqueName = ${JSON.stringify(uniqueName || undefined)};`, + `var register = ${runtimeTemplate.basicFunction( + "name, version, factory, eager", + [ + "var versions = scope[name] = scope[name] || {};", + "var activeVersion = versions[version];", + "if(!activeVersion || (!activeVersion.loaded && (!eager != !activeVersion.eager ? eager : uniqueName > activeVersion.from))) versions[version] = { get: factory, from: uniqueName, eager: !!eager };" + ] + )};`, + `var initExternal = ${runtimeTemplate.basicFunction("id", [ + `var handleError = ${runtimeTemplate.expressionFunction( + 'warn("Initialization of sharing external failed: " + err)', + "err" + )};`, + "try {", + Template.indent([ + "var module = __webpack_require__(id);", + "if(!module) return;", + `var initFn = ${runtimeTemplate.returningFunction( + `module && module.init && module.init(${RuntimeGlobals.shareScopeMap}[name], initScope)`, + "module" + )}`, + "if(module.then) return promises.push(module.then(initFn, handleError));", + "var initResult = initFn(module);", + "if(initResult && initResult.then) return promises.push(initResult['catch'](handleError));" + ]), + "} catch(err) { handleError(err); }" + ])}`, + "var promises = [];", + "switch(name) {", + ...Array.from(initCodePerScope) + .sort(([a], [b]) => compareStrings(a, b)) + .map(([name, stages]) => + Template.indent([ + `case ${JSON.stringify(name)}: {`, + Template.indent( + Array.from(stages) + .sort(([a], [b]) => a - b) + .map(([, initCode]) => + Template.asString(Array.from(initCode)) + ) + ), + "}", + "break;" + ]) + ), + "}", + "if(!promises.length) return initPromises[name] = 1;", + `return initPromises[name] = Promise.all(promises).then(${runtimeTemplate.returningFunction( + "initPromises[name] = 1" + )});` + ] + )};` + ]); } +} - let mapByValue = mapByProperty.get(property); +module.exports = ShareRuntimeModule; - if (mapByValue === undefined) { - mapByValue = new Map(); - mapByProperty.set(property, mapByValue); - } - let result = mapByValue.get(value); +/***/ }), - if (result) return result; +/***/ 3591: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - result = { - ...obj, - [property]: value - }; - mapByValue.set(value, result); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - return result; -}; -/** - * @typedef {Object} ObjectParsedPropertyEntry - * @property {any | undefined} base base value - * @property {string | undefined} byProperty the name of the selector property - * @property {Map} byValues value depending on selector property, merged with base - */ -/** - * @typedef {Object} ParsedObject - * @property {Map} static static properties (key is property name) - * @property {{ byProperty: string, fn: Function } | undefined} dynamic dynamic part - */ +const ModuleNotFoundError = __webpack_require__(32882); +const LazySet = __webpack_require__(38938); -/** @type {WeakMap} */ -const parseCache = new WeakMap(); +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */ /** - * @param {object} obj the object - * @returns {ParsedObject} parsed object + * @template T + * @typedef {Object} MatchedConfigs + * @property {Map} resolved + * @property {Map} unresolved + * @property {Map} prefixed */ -const cachedParseObject = obj => { - const entry = parseCache.get(obj); - if (entry !== undefined) return entry; - const result = parseObject(obj); - parseCache.set(obj, result); - return result; -}; + +/** @type {ResolveOptionsWithDependencyType} */ +const RESOLVE_OPTIONS = { dependencyType: "esm" }; /** - * @param {object} obj the object - * @returns {ParsedObject} parsed object + * @template T + * @param {Compilation} compilation the compilation + * @param {[string, T][]} configs to be processed configs + * @returns {Promise>} resolved matchers */ -const parseObject = obj => { - const info = new Map(); - let dynamicInfo; - const getInfo = p => { - const entry = info.get(p); - if (entry !== undefined) return entry; - const newEntry = { - base: undefined, - byProperty: undefined, - byValues: undefined - }; - info.set(p, newEntry); - return newEntry; +exports.resolveMatchedConfigs = (compilation, configs) => { + /** @type {Map} */ + const resolved = new Map(); + /** @type {Map} */ + const unresolved = new Map(); + /** @type {Map} */ + const prefixed = new Map(); + const resolveContext = { + /** @type {LazySet} */ + fileDependencies: new LazySet(), + /** @type {LazySet} */ + contextDependencies: new LazySet(), + /** @type {LazySet} */ + missingDependencies: new LazySet() }; - for (const key of Object.keys(obj)) { - if (key.startsWith("by")) { - const byProperty = key; - const byObj = obj[byProperty]; - if (typeof byObj === "object") { - for (const byValue of Object.keys(byObj)) { - const obj = byObj[byValue]; - for (const key of Object.keys(obj)) { - const entry = getInfo(key); - if (entry.byProperty === undefined) { - entry.byProperty = byProperty; - entry.byValues = new Map(); - } else if (entry.byProperty !== byProperty) { - throw new Error( - `${byProperty} and ${entry.byProperty} for a single property is not supported` - ); - } - entry.byValues.set(byValue, obj[key]); - if (byValue === "default") { - for (const otherByValue of Object.keys(byObj)) { - if (!entry.byValues.has(otherByValue)) - entry.byValues.set(otherByValue, undefined); + const resolver = compilation.resolverFactory.get("normal", RESOLVE_OPTIONS); + const context = compilation.compiler.context; + + return Promise.all( + configs.map(([request, config]) => { + if (/^\.\.?(\/|$)/.test(request)) { + // relative request + return new Promise(resolve => { + resolver.resolve( + {}, + context, + request, + resolveContext, + (err, result) => { + if (err || result === false) { + err = err || new Error(`Can't resolve ${request}`); + compilation.errors.push( + new ModuleNotFoundError(null, err, { + name: `shared module ${request}` + }) + ); + return resolve(); } + resolved.set(result, config); + resolve(); } - } - } - } else if (typeof byObj === "function") { - if (dynamicInfo === undefined) { - dynamicInfo = { - byProperty: key, - fn: byObj - }; - } else { - throw new Error( - `${key} and ${dynamicInfo.byProperty} when both are functions is not supported` ); - } + }); + } else if (/^(\/|[A-Za-z]:\\|\\\\)/.test(request)) { + // absolute path + resolved.set(request, config); + } else if (request.endsWith("/")) { + // module request prefix + prefixed.set(request, config); } else { - const entry = getInfo(key); - entry.base = obj[key]; - } - } else { - const entry = getInfo(key); - entry.base = obj[key]; - } - } - return { - static: info, - dynamic: dynamicInfo - }; -}; - -/** - * @param {Map} info static properties (key is property name) - * @param {{ byProperty: string, fn: Function } | undefined} dynamicInfo dynamic part - * @returns {object} the object - */ -const serializeObject = (info, dynamicInfo) => { - const obj = {}; - // Setup byProperty structure - for (const entry of info.values()) { - if (entry.byProperty !== undefined) { - const byObj = (obj[entry.byProperty] = obj[entry.byProperty] || {}); - for (const byValue of entry.byValues.keys()) { - byObj[byValue] = byObj[byValue] || {}; - } - } - } - for (const [key, entry] of info) { - if (entry.base !== undefined) { - obj[key] = entry.base; - } - // Fill byProperty structure - if (entry.byProperty !== undefined) { - const byObj = (obj[entry.byProperty] = obj[entry.byProperty] || {}); - for (const byValue of Object.keys(byObj)) { - const value = getFromByValues(entry.byValues, byValue); - if (value !== undefined) byObj[byValue][key] = value; + // module request + unresolved.set(request, config); } - } - } - if (dynamicInfo !== undefined) { - obj[dynamicInfo.byProperty] = dynamicInfo.fn; - } - return obj; + }) + ).then(() => { + compilation.contextDependencies.addAll(resolveContext.contextDependencies); + compilation.fileDependencies.addAll(resolveContext.fileDependencies); + compilation.missingDependencies.addAll(resolveContext.missingDependencies); + return { resolved, unresolved, prefixed }; + }); }; -const VALUE_TYPE_UNDEFINED = 0; -const VALUE_TYPE_ATOM = 1; -const VALUE_TYPE_ARRAY_EXTEND = 2; -const VALUE_TYPE_OBJECT = 3; -const VALUE_TYPE_DELETE = 4; -/** - * @param {any} value a single value - * @returns {VALUE_TYPE_UNDEFINED | VALUE_TYPE_ATOM | VALUE_TYPE_ARRAY_EXTEND | VALUE_TYPE_OBJECT | VALUE_TYPE_DELETE} value type - */ -const getValueType = value => { - if (value === undefined) { - return VALUE_TYPE_UNDEFINED; - } else if (value === DELETE) { - return VALUE_TYPE_DELETE; - } else if (Array.isArray(value)) { - if (value.lastIndexOf("...") !== -1) return VALUE_TYPE_ARRAY_EXTEND; - return VALUE_TYPE_ATOM; - } else if ( - typeof value === "object" && - value !== null && - (!value.constructor || value.constructor === Object) - ) { - return VALUE_TYPE_OBJECT; - } - return VALUE_TYPE_ATOM; -}; +/***/ }), -/** - * Merges two objects. Objects are deeply clever merged. - * Arrays might reference the old value with "...". - * Non-object values take preference over object values. - * @template T - * @template O - * @param {T} first first object - * @param {O} second second object - * @returns {T & O | T | O} merged object of first and second object - */ -const cleverMerge = (first, second) => { - if (second === undefined) return first; - if (first === undefined) return second; - if (typeof second !== "object" || second === null) return second; - if (typeof first !== "object" || first === null) return first; +/***/ 84379: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - return _cleverMerge(first, second, false); -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * Merges two objects. Objects are deeply clever merged. - * @param {object} first first object - * @param {object} second second object - * @param {boolean} internalCaching should parsing of objects and nested merges be cached - * @returns {object} merged object of first and second object - */ -const _cleverMerge = (first, second, internalCaching = false) => { - const firstObject = internalCaching - ? cachedParseObject(first) - : parseObject(first); - const { static: firstInfo, dynamic: firstDynamicInfo } = firstObject; - // If the first argument has a dynamic part we modify the dynamic part to merge the second argument - if (firstDynamicInfo !== undefined) { - let { byProperty, fn } = firstDynamicInfo; - const fnInfo = fn[DYNAMIC_INFO]; - if (fnInfo) { - second = internalCaching - ? cachedCleverMerge(fnInfo[1], second) - : cleverMerge(fnInfo[1], second); - fn = fnInfo[0]; - } - const newFn = (...args) => { - const fnResult = fn(...args); - return internalCaching - ? cachedCleverMerge(fnResult, second) - : cleverMerge(fnResult, second); - }; - newFn[DYNAMIC_INFO] = [fn, second]; - return serializeObject(firstObject.static, { byProperty, fn: newFn }); - } - // If the first part is static only, we merge the static parts and keep the dynamic part of the second argument - const secondObject = internalCaching - ? cachedParseObject(second) - : parseObject(second); - const { static: secondInfo, dynamic: secondDynamicInfo } = secondObject; - /** @type {Map} */ - const resultInfo = new Map(); - for (const [key, firstEntry] of firstInfo) { - const secondEntry = secondInfo.get(key); - const entry = - secondEntry !== undefined - ? mergeEntries(firstEntry, secondEntry, internalCaching) - : firstEntry; - resultInfo.set(key, entry); - } - for (const [key, secondEntry] of secondInfo) { - if (!firstInfo.has(key)) { - resultInfo.set(key, secondEntry); - } - } - return serializeObject(resultInfo, secondDynamicInfo); -}; +const { join, dirname, readJson } = __webpack_require__(17139); -/** - * @param {ObjectParsedPropertyEntry} firstEntry a - * @param {ObjectParsedPropertyEntry} secondEntry b - * @param {boolean} internalCaching should parsing of objects and nested merges be cached - * @returns {ObjectParsedPropertyEntry} new entry - */ -const mergeEntries = (firstEntry, secondEntry, internalCaching) => { - switch (getValueType(secondEntry.base)) { - case VALUE_TYPE_ATOM: - case VALUE_TYPE_DELETE: - // No need to consider firstEntry at all - // second value override everything - // = second.base + second.byProperty - return secondEntry; - case VALUE_TYPE_UNDEFINED: - if (!firstEntry.byProperty) { - // = first.base + second.byProperty - return { - base: firstEntry.base, - byProperty: secondEntry.byProperty, - byValues: secondEntry.byValues - }; - } else if (firstEntry.byProperty !== secondEntry.byProperty) { - throw new Error( - `${firstEntry.byProperty} and ${secondEntry.byProperty} for a single property is not supported` - ); - } else { - // = first.base + (first.byProperty + second.byProperty) - // need to merge first and second byValues - const newByValues = new Map(firstEntry.byValues); - for (const [key, value] of secondEntry.byValues) { - const firstValue = getFromByValues(firstEntry.byValues, key); - newByValues.set( - key, - mergeSingleValue(firstValue, value, internalCaching) - ); - } - return { - base: firstEntry.base, - byProperty: firstEntry.byProperty, - byValues: newByValues - }; - } - default: { - if (!firstEntry.byProperty) { - // The simple case - // = (first.base + second.base) + second.byProperty - return { - base: mergeSingleValue( - firstEntry.base, - secondEntry.base, - internalCaching - ), - byProperty: secondEntry.byProperty, - byValues: secondEntry.byValues - }; - } - let newBase; - const intermediateByValues = new Map(firstEntry.byValues); - for (const [key, value] of intermediateByValues) { - intermediateByValues.set( - key, - mergeSingleValue(value, secondEntry.base, internalCaching) - ); - } - if ( - Array.from(firstEntry.byValues.values()).every(value => { - const type = getValueType(value); - return type === VALUE_TYPE_ATOM || type === VALUE_TYPE_DELETE; - }) - ) { - // = (first.base + second.base) + ((first.byProperty + second.base) + second.byProperty) - newBase = mergeSingleValue( - firstEntry.base, - secondEntry.base, - internalCaching - ); - } else { - // = first.base + ((first.byProperty (+default) + second.base) + second.byProperty) - newBase = firstEntry.base; - if (!intermediateByValues.has("default")) - intermediateByValues.set("default", secondEntry.base); - } - if (!secondEntry.byProperty) { - // = first.base + (first.byProperty + second.base) - return { - base: newBase, - byProperty: firstEntry.byProperty, - byValues: intermediateByValues - }; - } else if (firstEntry.byProperty !== secondEntry.byProperty) { - throw new Error( - `${firstEntry.byProperty} and ${secondEntry.byProperty} for a single property is not supported` - ); - } - const newByValues = new Map(intermediateByValues); - for (const [key, value] of secondEntry.byValues) { - const firstValue = getFromByValues(intermediateByValues, key); - newByValues.set( - key, - mergeSingleValue(firstValue, value, internalCaching) - ); - } - return { - base: newBase, - byProperty: firstEntry.byProperty, - byValues: newByValues - }; - } - } -}; +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ /** - * @param {Map} byValues all values - * @param {string} key value of the selector - * @returns {any | undefined} value + * @param {string} str maybe required version + * @returns {boolean} true, if it looks like a version */ -const getFromByValues = (byValues, key) => { - if (key !== "default" && byValues.has(key)) { - return byValues.get(key); - } - return byValues.get("default"); +exports.isRequiredVersion = str => { + return /^([\d^=v<>~]|[*xX]$)/.test(str); }; /** - * @param {any} a value - * @param {any} b value - * @param {boolean} internalCaching should parsing of objects and nested merges be cached - * @returns {any} value + * + * @param {InputFileSystem} fs file system + * @param {string} directory directory to start looking into + * @param {string[]} descriptionFiles possible description filenames + * @param {function((Error | null)=, {data: object, path: string}=): void} callback callback */ -const mergeSingleValue = (a, b, internalCaching) => { - const bType = getValueType(b); - const aType = getValueType(a); - switch (bType) { - case VALUE_TYPE_DELETE: - case VALUE_TYPE_ATOM: - return b; - case VALUE_TYPE_OBJECT: { - return aType !== VALUE_TYPE_OBJECT - ? b - : internalCaching - ? cachedCleverMerge(a, b) - : cleverMerge(a, b); +const getDescriptionFile = (fs, directory, descriptionFiles, callback) => { + let i = 0; + const tryLoadCurrent = () => { + if (i >= descriptionFiles.length) { + const parentDirectory = dirname(fs, directory); + if (!parentDirectory || parentDirectory === directory) return callback(); + return getDescriptionFile( + fs, + parentDirectory, + descriptionFiles, + callback + ); } - case VALUE_TYPE_UNDEFINED: - return a; - case VALUE_TYPE_ARRAY_EXTEND: - switch ( - aType !== VALUE_TYPE_ATOM - ? aType - : Array.isArray(a) - ? VALUE_TYPE_ARRAY_EXTEND - : VALUE_TYPE_OBJECT - ) { - case VALUE_TYPE_UNDEFINED: - return b; - case VALUE_TYPE_DELETE: - return b.filter(item => item !== "..."); - case VALUE_TYPE_ARRAY_EXTEND: { - const newArray = []; - for (const item of b) { - if (item === "...") { - for (const item of a) { - newArray.push(item); - } - } else { - newArray.push(item); - } - } - return newArray; + const filePath = join(fs, directory, descriptionFiles[i]); + readJson(fs, filePath, (err, data) => { + if (err) { + if ("code" in err && err.code === "ENOENT") { + i++; + return tryLoadCurrent(); } - case VALUE_TYPE_OBJECT: - return b.map(item => (item === "..." ? a : item)); - default: - throw new Error("Not implemented"); + return callback(err); } - default: - throw new Error("Not implemented"); - } + if (!data || typeof data !== "object" || Array.isArray(data)) { + return callback( + new Error(`Description file ${filePath} is not an object`) + ); + } + callback(null, { data, path: filePath }); + }); + }; + tryLoadCurrent(); }; +exports.getDescriptionFile = getDescriptionFile; -/** - * @template T - * @param {T} obj the object - * @returns {T} the object without operations like "..." or DELETE - */ -const removeOperations = obj => { - const newObj = /** @type {T} */ ({}); - for (const key of Object.keys(obj)) { - const value = obj[key]; - const type = getValueType(value); - switch (type) { - case VALUE_TYPE_UNDEFINED: - case VALUE_TYPE_DELETE: - break; - case VALUE_TYPE_OBJECT: - newObj[key] = removeOperations(value); - break; - case VALUE_TYPE_ARRAY_EXTEND: - newObj[key] = value.filter(i => i !== "..."); - break; - default: - newObj[key] = value; - break; - } +exports.getRequiredVersionFromDescriptionFile = (data, packageName) => { + if ( + data.optionalDependencies && + typeof data.optionalDependencies === "object" && + packageName in data.optionalDependencies + ) { + return data.optionalDependencies[packageName]; } - return newObj; -}; - -/** - * @template T - * @template {string} P - * @param {T} obj the object - * @param {P} byProperty the by description - * @param {...any} values values - * @returns {Omit} object with merged byProperty - */ -const resolveByProperty = (obj, byProperty, ...values) => { - if (typeof obj !== "object" || obj === null || !(byProperty in obj)) { - return obj; + if ( + data.dependencies && + typeof data.dependencies === "object" && + packageName in data.dependencies + ) { + return data.dependencies[packageName]; } - const { [byProperty]: _byValue, ..._remaining } = /** @type {object} */ (obj); - const remaining = /** @type {T} */ (_remaining); - const byValue = /** @type {Record | function(...any[]): T} */ ( - _byValue - ); - if (typeof byValue === "object") { - const key = values[0]; - if (key in byValue) { - return cachedCleverMerge(remaining, byValue[key]); - } else if ("default" in byValue) { - return cachedCleverMerge(remaining, byValue.default); - } else { - return /** @type {T} */ (remaining); - } - } else if (typeof byValue === "function") { - const result = byValue.apply(null, values); - return cachedCleverMerge( - remaining, - resolveByProperty(result, byProperty, ...values) - ); + if ( + data.peerDependencies && + typeof data.peerDependencies === "object" && + packageName in data.peerDependencies + ) { + return data.peerDependencies[packageName]; + } + if ( + data.devDependencies && + typeof data.devDependencies === "object" && + packageName in data.devDependencies + ) { + return data.devDependencies[packageName]; } }; -exports.cachedSetProperty = cachedSetProperty; -exports.cachedCleverMerge = cachedCleverMerge; -exports.cleverMerge = cleverMerge; -exports.resolveByProperty = resolveByProperty; -exports.removeOperations = removeOperations; -exports.DELETE = DELETE; - /***/ }), -/***/ 29579: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 71760: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -124127,1944 +129166,2403 @@ exports.DELETE = DELETE; -const { compareRuntime } = __webpack_require__(17156); +const util = __webpack_require__(73837); +const ModuleDependency = __webpack_require__(80321); +const formatLocation = __webpack_require__(16734); +const { LogType } = __webpack_require__(32597); +const AggressiveSplittingPlugin = __webpack_require__(15543); +const SizeLimitsPlugin = __webpack_require__(32557); +const { countIterable } = __webpack_require__(39104); +const { + compareLocations, + compareChunksById, + compareNumbers, + compareIds, + concatComparators, + compareSelect, + compareModulesByIdentifier +} = __webpack_require__(29579); +const { makePathsRelative, parseResource } = __webpack_require__(82186); +/** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ /** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../ChunkGroup").OriginRecord} OriginRecord */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").Asset} Asset */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("../Compilation").NormalizedStatsOptions} NormalizedStatsOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ - -/** @template T @typedef {function(T, T): -1|0|1} Comparator */ -/** @template TArg @template T @typedef {function(TArg, T, T): -1|0|1} RawParameterizedComparator */ -/** @template TArg @template T @typedef {function(TArg): Comparator} ParameterizedComparator */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleProfile")} ModuleProfile */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @template T @typedef {import("../util/comparators").Comparator} Comparator */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("../util/smartGrouping").GroupConfig} GroupConfig */ +/** @typedef {import("./StatsFactory")} StatsFactory */ +/** @typedef {import("./StatsFactory").StatsFactoryContext} StatsFactoryContext */ +/** @typedef {KnownStatsCompilation & Record} StatsCompilation */ /** - * @template T - * @param {RawParameterizedComparator} fn comparator with argument - * @returns {ParameterizedComparator} comparator + * @typedef {Object} KnownStatsCompilation + * @property {any=} env + * @property {string=} name + * @property {string=} hash + * @property {string=} version + * @property {number=} time + * @property {number=} builtAt + * @property {boolean=} needAdditionalPass + * @property {string=} publicPath + * @property {string=} outputPath + * @property {Record=} assetsByChunkName + * @property {StatsAsset[]=} assets + * @property {number=} filteredAssets + * @property {StatsChunk[]=} chunks + * @property {StatsModule[]=} modules + * @property {number=} filteredModules + * @property {Record=} entrypoints + * @property {Record=} namedChunkGroups + * @property {StatsError[]=} errors + * @property {number=} errorsCount + * @property {StatsError[]=} warnings + * @property {number=} warningsCount + * @property {StatsCompilation[]=} children + * @property {Record=} logging */ -const createCachedParameterizedComparator = fn => { - /** @type {WeakMap>} */ - const map = new WeakMap(); - return arg => { - const cachedResult = map.get(arg); - if (cachedResult !== undefined) return cachedResult; - /** - * @param {T} a first item - * @param {T} b second item - * @returns {-1|0|1} compare result - */ - const result = fn.bind(null, arg); - map.set(arg, result); - return result; - }; -}; +/** @typedef {KnownStatsLogging & Record} StatsLogging */ /** - * @param {Chunk} a chunk - * @param {Chunk} b chunk - * @returns {-1|0|1} compare result + * @typedef {Object} KnownStatsLogging + * @property {StatsLoggingEntry[]} entries + * @property {number} filteredEntries + * @property {boolean} debug */ -exports.compareChunksById = (a, b) => { - return compareIds(a.id, b.id); -}; +/** @typedef {KnownStatsLoggingEntry & Record} StatsLoggingEntry */ /** - * @param {Module} a module - * @param {Module} b module - * @returns {-1|0|1} compare result + * @typedef {Object} KnownStatsLoggingEntry + * @property {string} type + * @property {string} message + * @property {string[]=} trace + * @property {StatsLoggingEntry[]=} children + * @property {any[]=} args + * @property {number=} time */ -exports.compareModulesByIdentifier = (a, b) => { - return compareIds(a.identifier(), b.identifier()); -}; +/** @typedef {KnownStatsAsset & Record} StatsAsset */ /** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {Module} a module - * @param {Module} b module - * @returns {-1|0|1} compare result + * @typedef {Object} KnownStatsAsset + * @property {string} type + * @property {string} name + * @property {AssetInfo} info + * @property {number} size + * @property {boolean} emitted + * @property {boolean} comparedForEmit + * @property {boolean} cached + * @property {StatsAsset[]=} related + * @property {(string|number)[]=} chunkNames + * @property {(string|number)[]=} chunkIdHints + * @property {(string|number)[]=} chunks + * @property {(string|number)[]=} auxiliaryChunkNames + * @property {(string|number)[]=} auxiliaryChunks + * @property {(string|number)[]=} auxiliaryChunkIdHints + * @property {number=} filteredRelated + * @property {boolean=} isOverSizeLimit */ -const compareModulesById = (chunkGraph, a, b) => { - return compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b)); -}; -/** @type {ParameterizedComparator} */ -exports.compareModulesById = - createCachedParameterizedComparator(compareModulesById); +/** @typedef {KnownStatsChunkGroup & Record} StatsChunkGroup */ /** - * @param {number} a number - * @param {number} b number - * @returns {-1|0|1} compare result + * @typedef {Object} KnownStatsChunkGroup + * @property {string=} name + * @property {(string|number)[]=} chunks + * @property {({ name: string, size?: number })[]=} assets + * @property {number=} filteredAssets + * @property {number=} assetsSize + * @property {({ name: string, size?: number })[]=} auxiliaryAssets + * @property {number=} filteredAuxiliaryAssets + * @property {number=} auxiliaryAssetsSize + * @property {{ [x: string]: StatsChunkGroup[] }=} children + * @property {{ [x: string]: string[] }=} childAssets + * @property {boolean=} isOverSizeLimit */ -const compareNumbers = (a, b) => { - if (typeof a !== typeof b) { - return typeof a < typeof b ? -1 : 1; - } - if (a < b) return -1; - if (a > b) return 1; - return 0; -}; -exports.compareNumbers = compareNumbers; +/** @typedef {KnownStatsModule & Record} StatsModule */ /** - * @param {string} a string - * @param {string} b string - * @returns {-1|0|1} compare result + * @typedef {Object} KnownStatsModule + * @property {string=} type + * @property {string=} moduleType + * @property {string=} layer + * @property {string=} identifier + * @property {string=} name + * @property {string=} nameForCondition + * @property {number=} index + * @property {number=} preOrderIndex + * @property {number=} index2 + * @property {number=} postOrderIndex + * @property {number=} size + * @property {{[x: string]: number}=} sizes + * @property {boolean=} cacheable + * @property {boolean=} built + * @property {boolean=} codeGenerated + * @property {boolean=} buildTimeExecuted + * @property {boolean=} cached + * @property {boolean=} optional + * @property {boolean=} orphan + * @property {string|number=} id + * @property {string|number=} issuerId + * @property {(string|number)[]=} chunks + * @property {(string|number)[]=} assets + * @property {boolean=} dependent + * @property {string=} issuer + * @property {string=} issuerName + * @property {StatsModuleIssuer[]=} issuerPath + * @property {boolean=} failed + * @property {number=} errors + * @property {number=} warnings + * @property {StatsProfile=} profile + * @property {StatsModuleReason[]=} reasons + * @property {(boolean | string[])=} usedExports + * @property {string[]=} providedExports + * @property {string[]=} optimizationBailout + * @property {number=} depth + * @property {StatsModule[]=} modules + * @property {number=} filteredModules + * @property {ReturnType=} source */ -const compareStringsNumeric = (a, b) => { - const partsA = a.split(/(\d+)/); - const partsB = b.split(/(\d+)/); - const len = Math.min(partsA.length, partsB.length); - for (let i = 0; i < len; i++) { - const pA = partsA[i]; - const pB = partsB[i]; - if (i % 2 === 0) { - if (pA.length > pB.length) { - if (pA.slice(0, pB.length) > pB) return 1; - return -1; - } else if (pB.length > pA.length) { - if (pB.slice(0, pA.length) > pA) return -1; - return 1; - } else { - if (pA < pB) return -1; - if (pA > pB) return 1; - } - } else { - const nA = +pA; - const nB = +pB; - if (nA < nB) return -1; - if (nA > nB) return 1; - } - } - if (partsB.length < partsA.length) return 1; - if (partsB.length > partsA.length) return -1; - return 0; -}; -exports.compareStringsNumeric = compareStringsNumeric; +/** @typedef {KnownStatsProfile & Record} StatsProfile */ /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {Module} a module - * @param {Module} b module - * @returns {-1|0|1} compare result + * @typedef {Object} KnownStatsProfile + * @property {number} total + * @property {number} resolving + * @property {number} restoring + * @property {number} building + * @property {number} integration + * @property {number} storing + * @property {number} additionalResolving + * @property {number} additionalIntegration + * @property {number} factory + * @property {number} dependencies */ -const compareModulesByPostOrderIndexOrIdentifier = (moduleGraph, a, b) => { - const cmp = compareNumbers( - moduleGraph.getPostOrderIndex(a), - moduleGraph.getPostOrderIndex(b) - ); - if (cmp !== 0) return cmp; - return compareIds(a.identifier(), b.identifier()); -}; -/** @type {ParameterizedComparator} */ -exports.compareModulesByPostOrderIndexOrIdentifier = - createCachedParameterizedComparator( - compareModulesByPostOrderIndexOrIdentifier - ); +/** @typedef {KnownStatsModuleIssuer & Record} StatsModuleIssuer */ /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {Module} a module - * @param {Module} b module - * @returns {-1|0|1} compare result + * @typedef {Object} KnownStatsModuleIssuer + * @property {string=} identifier + * @property {string=} name + * @property {(string|number)=} id + * @property {StatsProfile=} profile */ -const compareModulesByPreOrderIndexOrIdentifier = (moduleGraph, a, b) => { - const cmp = compareNumbers( - moduleGraph.getPreOrderIndex(a), - moduleGraph.getPreOrderIndex(b) - ); - if (cmp !== 0) return cmp; - return compareIds(a.identifier(), b.identifier()); -}; -/** @type {ParameterizedComparator} */ -exports.compareModulesByPreOrderIndexOrIdentifier = - createCachedParameterizedComparator( - compareModulesByPreOrderIndexOrIdentifier - ); +/** @typedef {KnownStatsModuleReason & Record} StatsModuleReason */ /** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {Module} a module - * @param {Module} b module - * @returns {-1|0|1} compare result + * @typedef {Object} KnownStatsModuleReason + * @property {string=} moduleIdentifier + * @property {string=} module + * @property {string=} moduleName + * @property {string=} resolvedModuleIdentifier + * @property {string=} resolvedModule + * @property {string=} type + * @property {boolean} active + * @property {string=} explanation + * @property {string=} userRequest + * @property {string=} loc + * @property {(string|number)=} moduleId + * @property {(string|number)=} resolvedModuleId */ -const compareModulesByIdOrIdentifier = (chunkGraph, a, b) => { - const cmp = compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b)); - if (cmp !== 0) return cmp; - return compareIds(a.identifier(), b.identifier()); -}; -/** @type {ParameterizedComparator} */ -exports.compareModulesByIdOrIdentifier = createCachedParameterizedComparator( - compareModulesByIdOrIdentifier -); +/** @typedef {KnownStatsChunk & Record} StatsChunk */ /** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {Chunk} a chunk - * @param {Chunk} b chunk - * @returns {-1|0|1} compare result + * @typedef {Object} KnownStatsChunk + * @property {boolean} rendered + * @property {boolean} initial + * @property {boolean} entry + * @property {boolean} recorded + * @property {string=} reason + * @property {number} size + * @property {Record=} sizes + * @property {string[]=} names + * @property {string[]=} idHints + * @property {string[]=} runtime + * @property {string[]=} files + * @property {string[]=} auxiliaryFiles + * @property {string} hash + * @property {Record=} childrenByOrder + * @property {(string|number)=} id + * @property {(string|number)[]=} siblings + * @property {(string|number)[]=} parents + * @property {(string|number)[]=} children + * @property {StatsModule[]=} modules + * @property {number=} filteredModules + * @property {StatsChunkOrigin[]=} origins */ -const compareChunks = (chunkGraph, a, b) => { - return chunkGraph.compareChunks(a, b); -}; -/** @type {ParameterizedComparator} */ -exports.compareChunks = createCachedParameterizedComparator(compareChunks); +/** @typedef {KnownStatsChunkOrigin & Record} StatsChunkOrigin */ /** - * @param {string|number} a first id - * @param {string|number} b second id - * @returns {-1|0|1} compare result + * @typedef {Object} KnownStatsChunkOrigin + * @property {string=} module + * @property {string=} moduleIdentifier + * @property {string=} moduleName + * @property {string=} loc + * @property {string=} request + * @property {(string|number)=} moduleId */ -const compareIds = (a, b) => { - if (typeof a !== typeof b) { - return typeof a < typeof b ? -1 : 1; - } - if (a < b) return -1; - if (a > b) return 1; - return 0; -}; - -exports.compareIds = compareIds; +/** @typedef {KnownStatsModuleTraceItem & Record} StatsModuleTraceItem */ /** - * @param {string} a first string - * @param {string} b second string - * @returns {-1|0|1} compare result + * @typedef {Object} KnownStatsModuleTraceItem + * @property {string=} originIdentifier + * @property {string=} originName + * @property {string=} moduleIdentifier + * @property {string=} moduleName + * @property {StatsModuleTraceDependency[]=} dependencies + * @property {(string|number)=} originId + * @property {(string|number)=} moduleId */ -const compareStrings = (a, b) => { - if (a < b) return -1; - if (a > b) return 1; - return 0; -}; - -exports.compareStrings = compareStrings; +/** @typedef {KnownStatsModuleTraceDependency & Record} StatsModuleTraceDependency */ /** - * @param {ChunkGroup} a first chunk group - * @param {ChunkGroup} b second chunk group - * @returns {-1|0|1} compare result + * @typedef {Object} KnownStatsModuleTraceDependency + * @property {string=} loc */ -const compareChunkGroupsByIndex = (a, b) => { - return a.index < b.index ? -1 : 1; -}; - -exports.compareChunkGroupsByIndex = compareChunkGroupsByIndex; +/** @typedef {KnownStatsError & Record} StatsError */ /** - * @template K1 {Object} - * @template K2 - * @template T + * @typedef {Object} KnownStatsError + * @property {string} message + * @property {string=} chunkName + * @property {boolean=} chunkEntry + * @property {boolean=} chunkInitial + * @property {string=} file + * @property {string=} moduleIdentifier + * @property {string=} moduleName + * @property {string=} loc + * @property {string|number=} chunkId + * @property {string|number=} moduleId + * @property {StatsModuleTraceItem[]=} moduleTrace + * @property {any=} details + * @property {string=} stack */ -class TwoKeyWeakMap { - constructor() { - /** @private @type {WeakMap>} */ - this._map = new WeakMap(); - } - - /** - * @param {K1} key1 first key - * @param {K2} key2 second key - * @returns {T | undefined} value - */ - get(key1, key2) { - const childMap = this._map.get(key1); - if (childMap === undefined) { - return undefined; - } - return childMap.get(key2); - } - - /** - * @param {K1} key1 first key - * @param {K2} key2 second key - * @param {T | undefined} value new value - * @returns {void} - */ - set(key1, key2, value) { - let childMap = this._map.get(key1); - if (childMap === undefined) { - childMap = new WeakMap(); - this._map.set(key1, childMap); - } - childMap.set(key2, value); - } -} -/** @type {TwoKeyWeakMap, Comparator, Comparator>}} */ -const concatComparatorsCache = new TwoKeyWeakMap(); +/** @typedef {Asset & { type: string, related: PreprocessedAsset[] }} PreprocessedAsset */ /** * @template T - * @param {Comparator} c1 comparator - * @param {Comparator} c2 comparator - * @param {Comparator[]} cRest comparators - * @returns {Comparator} comparator + * @template O + * @typedef {Record void>} ExtractorsByOption */ -const concatComparators = (c1, c2, ...cRest) => { - if (cRest.length > 0) { - const [c3, ...cRest2] = cRest; - return concatComparators(c1, concatComparators(c2, c3, ...cRest2)); - } - const cacheEntry = /** @type {Comparator} */ ( - concatComparatorsCache.get(c1, c2) - ); - if (cacheEntry !== undefined) return cacheEntry; - /** - * @param {T} a first value - * @param {T} b second value - * @returns {-1|0|1} compare result - */ - const result = (a, b) => { - const res = c1(a, b); - if (res !== 0) return res; - return c2(a, b); - }; - concatComparatorsCache.set(c1, c2, result); - return result; -}; -exports.concatComparators = concatComparators; - -/** @template A, B @typedef {(input: A) => B} Selector */ -/** @type {TwoKeyWeakMap, Comparator, Comparator>}} */ -const compareSelectCache = new TwoKeyWeakMap(); +/** + * @typedef {Object} SimpleExtractors + * @property {ExtractorsByOption} compilation + * @property {ExtractorsByOption} asset + * @property {ExtractorsByOption} asset$visible + * @property {ExtractorsByOption<{ name: string, chunkGroup: ChunkGroup }, StatsChunkGroup>} chunkGroup + * @property {ExtractorsByOption} module + * @property {ExtractorsByOption} module$visible + * @property {ExtractorsByOption} moduleIssuer + * @property {ExtractorsByOption} profile + * @property {ExtractorsByOption} moduleReason + * @property {ExtractorsByOption} chunk + * @property {ExtractorsByOption} chunkOrigin + * @property {ExtractorsByOption} error + * @property {ExtractorsByOption} warning + * @property {ExtractorsByOption<{ origin: Module, module: Module }, StatsModuleTraceItem>} moduleTraceItem + * @property {ExtractorsByOption} moduleTraceDependency + */ /** * @template T - * @template R - * @param {Selector} getter getter for value - * @param {Comparator} comparator comparator - * @returns {Comparator} comparator + * @template I + * @param {Iterable} items items to select from + * @param {function(T): Iterable} selector selector function to select values from item + * @returns {I[]} array of values */ -const compareSelect = (getter, comparator) => { - const cacheEntry = compareSelectCache.get(getter, comparator); - if (cacheEntry !== undefined) return cacheEntry; - /** - * @param {T} a first value - * @param {T} b second value - * @returns {-1|0|1} compare result - */ - const result = (a, b) => { - const aValue = getter(a); - const bValue = getter(b); - if (aValue !== undefined && aValue !== null) { - if (bValue !== undefined && bValue !== null) { - return comparator(aValue, bValue); - } - return -1; - } else { - if (bValue !== undefined && bValue !== null) { - return 1; - } - return 0; +const uniqueArray = (items, selector) => { + /** @type {Set} */ + const set = new Set(); + for (const item of items) { + for (const i of selector(item)) { + set.add(i); } - }; - compareSelectCache.set(getter, comparator, result); - return result; + } + return Array.from(set); }; -exports.compareSelect = compareSelect; - -/** @type {WeakMap, Comparator>>} */ -const compareIteratorsCache = new WeakMap(); /** * @template T - * @param {Comparator} elementComparator comparator for elements - * @returns {Comparator>} comparator for iterables of elements + * @template I + * @param {Iterable} items items to select from + * @param {function(T): Iterable} selector selector function to select values from item + * @param {Comparator} comparator comparator function + * @returns {I[]} array of values */ -const compareIterables = elementComparator => { - const cacheEntry = compareIteratorsCache.get(elementComparator); - if (cacheEntry !== undefined) return cacheEntry; - /** - * @param {Iterable} a first value - * @param {Iterable} b second value - * @returns {-1|0|1} compare result - */ - const result = (a, b) => { - const aI = a[Symbol.iterator](); - const bI = b[Symbol.iterator](); - // eslint-disable-next-line no-constant-condition - while (true) { - const aItem = aI.next(); - const bItem = bI.next(); - if (aItem.done) { - return bItem.done ? 0 : -1; - } else if (bItem.done) { - return 1; - } - const res = elementComparator(aItem.value, bItem.value); - if (res !== 0) return res; - } - }; - compareIteratorsCache.set(elementComparator, result); - return result; +const uniqueOrderedArray = (items, selector, comparator) => { + return uniqueArray(items, selector).sort(comparator); }; -exports.compareIterables = compareIterables; -// TODO this is no longer needed when minimum node.js version is >= 12 -// since these versions ship with a stable sort function +/** @template T @template R @typedef {{ [P in keyof T]: R }} MappedValues */ + /** * @template T - * @param {Iterable} iterable original ordered list - * @returns {Comparator} comparator + * @template R + * @param {T} obj object to be mapped + * @param {function(T[keyof T], keyof T): R} fn mapping function + * @returns {MappedValues} mapped object */ -exports.keepOriginalOrder = iterable => { - /** @type {Map} */ - const map = new Map(); - let i = 0; - for (const item of iterable) { - map.set(item, i++); +const mapObject = (obj, fn) => { + const newObj = Object.create(null); + for (const key of Object.keys(obj)) { + newObj[key] = fn(obj[key], /** @type {keyof T} */ (key)); } - return (a, b) => compareNumbers(map.get(a), map.get(b)); + return newObj; }; /** - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {Comparator} comparator + * @param {Compilation} compilation the compilation + * @param {function(Compilation, string): any[]} getItems get items + * @returns {number} total number */ -exports.compareChunksNatural = chunkGraph => { - const cmpFn = exports.compareModulesById(chunkGraph); - const cmpIterableFn = compareIterables(cmpFn); - return concatComparators( - compareSelect(chunk => chunk.name, compareIds), - compareSelect(chunk => chunk.runtime, compareRuntime), - compareSelect( - /** - * @param {Chunk} chunk a chunk - * @returns {Iterable} modules - */ - chunk => chunkGraph.getOrderedChunkModulesIterable(chunk, cmpFn), - cmpIterableFn - ) - ); +const countWithChildren = (compilation, getItems) => { + let count = getItems(compilation, "").length; + for (const child of compilation.children) { + count += countWithChildren(child, (c, type) => + getItems(c, `.children[].compilation${type}`) + ); + } + return count; }; -/** - * Compare two locations - * @param {DependencyLocation} a A location node - * @param {DependencyLocation} b A location node - * @returns {-1|0|1} sorting comparator value - */ -exports.compareLocations = (a, b) => { - let isObjectA = typeof a === "object" && a !== null; - let isObjectB = typeof b === "object" && b !== null; - if (!isObjectA || !isObjectB) { - if (isObjectA) return 1; - if (isObjectB) return -1; - return 0; +/** @type {ExtractorsByOption} */ +const EXTRACT_ERROR = { + _: (object, error, context, { requestShortener }) => { + // TODO webpack 6 disallow strings in the errors/warnings list + if (typeof error === "string") { + object.message = error; + } else { + if (error.chunk) { + object.chunkName = error.chunk.name; + object.chunkEntry = error.chunk.hasRuntime(); + object.chunkInitial = error.chunk.canBeInitial(); + } + if (error.file) { + object.file = error.file; + } + if (error.module) { + object.moduleIdentifier = error.module.identifier(); + object.moduleName = error.module.readableIdentifier(requestShortener); + } + if (error.loc) { + object.loc = formatLocation(error.loc); + } + object.message = error.message; + } + }, + ids: (object, error, { compilation: { chunkGraph } }) => { + if (typeof error !== "string") { + if (error.chunk) { + object.chunkId = error.chunk.id; + } + if (error.module) { + object.moduleId = chunkGraph.getModuleId(error.module); + } + } + }, + moduleTrace: (object, error, context, options, factory) => { + if (typeof error !== "string" && error.module) { + const { + type, + compilation: { moduleGraph } + } = context; + /** @type {Set} */ + const visitedModules = new Set(); + const moduleTrace = []; + let current = error.module; + while (current) { + if (visitedModules.has(current)) break; // circular (technically impossible, but how knows) + visitedModules.add(current); + const origin = moduleGraph.getIssuer(current); + if (!origin) break; + moduleTrace.push({ origin, module: current }); + current = origin; + } + object.moduleTrace = factory.create( + `${type}.moduleTrace`, + moduleTrace, + context + ); + } + }, + errorDetails: ( + object, + error, + { type, compilation, cachedGetErrors, cachedGetWarnings }, + { errorDetails } + ) => { + if ( + typeof error !== "string" && + (errorDetails === true || + (type.endsWith(".error") && cachedGetErrors(compilation).length < 3)) + ) { + object.details = error.details; + } + }, + errorStack: (object, error) => { + if (typeof error !== "string") { + object.stack = error.stack; + } } - if ("start" in a) { - if ("start" in b) { - const ap = a.start; - const bp = b.start; - if (ap.line < bp.line) return -1; - if (ap.line > bp.line) return 1; - if (ap.column < bp.column) return -1; - if (ap.column > bp.column) return 1; - } else return -1; - } else if ("start" in b) return 1; - if ("name" in a) { - if ("name" in b) { - if (a.name < b.name) return -1; - if (a.name > b.name) return 1; - } else return -1; - } else if ("name" in b) return 1; - if ("index" in a) { - if ("index" in b) { - if (a.index < b.index) return -1; - if (a.index > b.index) return 1; - } else return -1; - } else if ("index" in b) return 1; - return 0; }; +/** @type {SimpleExtractors} */ +const SIMPLE_EXTRACTORS = { + compilation: { + _: (object, compilation, context, options) => { + if (!context.makePathsRelative) { + context.makePathsRelative = makePathsRelative.bindContextCache( + compilation.compiler.context, + compilation.compiler.root + ); + } + if (!context.cachedGetErrors) { + const map = new WeakMap(); + context.cachedGetErrors = compilation => { + return ( + map.get(compilation) || + (errors => (map.set(compilation, errors), errors))( + compilation.getErrors() + ) + ); + }; + } + if (!context.cachedGetWarnings) { + const map = new WeakMap(); + context.cachedGetWarnings = compilation => { + return ( + map.get(compilation) || + (warnings => (map.set(compilation, warnings), warnings))( + compilation.getWarnings() + ) + ); + }; + } + if (compilation.name) { + object.name = compilation.name; + } + if (compilation.needAdditionalPass) { + object.needAdditionalPass = true; + } -/***/ }), - -/***/ 29404: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - + const { logging, loggingDebug, loggingTrace } = options; + if (logging || (loggingDebug && loggingDebug.length > 0)) { + const util = __webpack_require__(73837); + object.logging = {}; + let acceptedTypes; + let collapsedGroups = false; + switch (logging) { + default: + acceptedTypes = new Set(); + break; + case "error": + acceptedTypes = new Set([LogType.error]); + break; + case "warn": + acceptedTypes = new Set([LogType.error, LogType.warn]); + break; + case "info": + acceptedTypes = new Set([ + LogType.error, + LogType.warn, + LogType.info + ]); + break; + case "log": + acceptedTypes = new Set([ + LogType.error, + LogType.warn, + LogType.info, + LogType.log, + LogType.group, + LogType.groupEnd, + LogType.groupCollapsed, + LogType.clear + ]); + break; + case "verbose": + acceptedTypes = new Set([ + LogType.error, + LogType.warn, + LogType.info, + LogType.log, + LogType.group, + LogType.groupEnd, + LogType.groupCollapsed, + LogType.profile, + LogType.profileEnd, + LogType.time, + LogType.status, + LogType.clear + ]); + collapsedGroups = true; + break; + } + const cachedMakePathsRelative = makePathsRelative.bindContextCache( + options.context, + compilation.compiler.root + ); + let depthInCollapsedGroup = 0; + for (const [origin, logEntries] of compilation.logging) { + const debugMode = loggingDebug.some(fn => fn(origin)); + if (logging === false && !debugMode) continue; + /** @type {KnownStatsLoggingEntry[]} */ + const groupStack = []; + /** @type {KnownStatsLoggingEntry[]} */ + const rootList = []; + let currentList = rootList; + let processedLogEntries = 0; + for (const entry of logEntries) { + let type = entry.type; + if (!debugMode && !acceptedTypes.has(type)) continue; -const quoteMeta = str => { - return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); -}; + // Expand groups in verbose and debug modes + if ( + type === LogType.groupCollapsed && + (debugMode || collapsedGroups) + ) + type = LogType.group; -const toSimpleString = str => { - if (`${+str}` === str) { - return str; - } - return JSON.stringify(str); -}; + if (depthInCollapsedGroup === 0) { + processedLogEntries++; + } -/** - * @param {Record} map value map - * @returns {true|false|function(string): string} true/false, when unconditionally true/false, or a template function to determine the value at runtime - */ -const compileBooleanMatcher = map => { - const positiveItems = Object.keys(map).filter(i => map[i]); - const negativeItems = Object.keys(map).filter(i => !map[i]); - if (positiveItems.length === 0) return false; - if (negativeItems.length === 0) return true; - return compileBooleanMatcherFromLists(positiveItems, negativeItems); -}; + if (type === LogType.groupEnd) { + groupStack.pop(); + if (groupStack.length > 0) { + currentList = groupStack[groupStack.length - 1].children; + } else { + currentList = rootList; + } + if (depthInCollapsedGroup > 0) depthInCollapsedGroup--; + continue; + } + let message = undefined; + if (entry.type === LogType.time) { + message = `${entry.args[0]}: ${ + entry.args[1] * 1000 + entry.args[2] / 1000000 + } ms`; + } else if (entry.args && entry.args.length > 0) { + message = util.format(entry.args[0], ...entry.args.slice(1)); + } + /** @type {KnownStatsLoggingEntry} */ + const newEntry = { + ...entry, + type, + message, + trace: loggingTrace ? entry.trace : undefined, + children: + type === LogType.group || type === LogType.groupCollapsed + ? [] + : undefined + }; + currentList.push(newEntry); + if (newEntry.children) { + groupStack.push(newEntry); + currentList = newEntry.children; + if (depthInCollapsedGroup > 0) { + depthInCollapsedGroup++; + } else if (type === LogType.groupCollapsed) { + depthInCollapsedGroup = 1; + } + } + } + let name = cachedMakePathsRelative(origin).replace(/\|/g, " "); + if (name in object.logging) { + let i = 1; + while (`${name}#${i}` in object.logging) { + i++; + } + name = `${name}#${i}`; + } + object.logging[name] = { + entries: rootList, + filteredEntries: logEntries.length - processedLogEntries, + debug: debugMode + }; + } + } + }, + hash: (object, compilation) => { + object.hash = compilation.hash; + }, + version: object => { + object.version = (__webpack_require__(32702)/* .version */ .i8); + }, + env: (object, compilation, context, { _env }) => { + object.env = _env; + }, + timings: (object, compilation) => { + object.time = compilation.endTime - compilation.startTime; + }, + builtAt: (object, compilation) => { + object.builtAt = compilation.endTime; + }, + publicPath: (object, compilation) => { + object.publicPath = compilation.getPath( + compilation.outputOptions.publicPath + ); + }, + outputPath: (object, compilation) => { + object.outputPath = compilation.outputOptions.path; + }, + assets: (object, compilation, context, options, factory) => { + const { type } = context; + /** @type {Map} */ + const compilationFileToChunks = new Map(); + /** @type {Map} */ + const compilationAuxiliaryFileToChunks = new Map(); + for (const chunk of compilation.chunks) { + for (const file of chunk.files) { + let array = compilationFileToChunks.get(file); + if (array === undefined) { + array = []; + compilationFileToChunks.set(file, array); + } + array.push(chunk); + } + for (const file of chunk.auxiliaryFiles) { + let array = compilationAuxiliaryFileToChunks.get(file); + if (array === undefined) { + array = []; + compilationAuxiliaryFileToChunks.set(file, array); + } + array.push(chunk); + } + } + /** @type {Map} */ + const assetMap = new Map(); + /** @type {Set} */ + const assets = new Set(); + for (const asset of compilation.getAssets()) { + /** @type {PreprocessedAsset} */ + const item = { + ...asset, + type: "asset", + related: undefined + }; + assets.add(item); + assetMap.set(asset.name, item); + } + for (const item of assetMap.values()) { + const related = item.info.related; + if (!related) continue; + for (const type of Object.keys(related)) { + const relatedEntry = related[type]; + const deps = Array.isArray(relatedEntry) + ? relatedEntry + : [relatedEntry]; + for (const dep of deps) { + const depItem = assetMap.get(dep); + if (!depItem) continue; + assets.delete(depItem); + depItem.type = type; + item.related = item.related || []; + item.related.push(depItem); + } + } + } -/** - * @param {string[]} positiveItems positive items - * @param {string[]} negativeItems negative items - * @returns {function(string): string} a template function to determine the value at runtime - */ -const compileBooleanMatcherFromLists = (positiveItems, negativeItems) => { - if (positiveItems.length === 0) return () => "false"; - if (negativeItems.length === 0) return () => "true"; - if (positiveItems.length === 1) - return value => `${toSimpleString(positiveItems[0])} == ${value}`; - if (negativeItems.length === 1) - return value => `${toSimpleString(negativeItems[0])} != ${value}`; - const positiveRegexp = itemsToRegexp(positiveItems); - const negativeRegexp = itemsToRegexp(negativeItems); - if (positiveRegexp.length <= negativeRegexp.length) { - return value => `/^${positiveRegexp}$/.test(${value})`; - } else { - return value => `!/^${negativeRegexp}$/.test(${value})`; - } -}; + object.assetsByChunkName = {}; + for (const [file, chunks] of compilationFileToChunks) { + for (const chunk of chunks) { + const name = chunk.name; + if (!name) continue; + if ( + !Object.prototype.hasOwnProperty.call( + object.assetsByChunkName, + name + ) + ) { + object.assetsByChunkName[name] = []; + } + object.assetsByChunkName[name].push(file); + } + } -const popCommonItems = (itemsSet, getKey, condition) => { - const map = new Map(); - for (const item of itemsSet) { - const key = getKey(item); - if (key) { - let list = map.get(key); - if (list === undefined) { - list = []; - map.set(key, list); + const groupedAssets = factory.create( + `${type}.assets`, + Array.from(assets), + { + ...context, + compilationFileToChunks, + compilationAuxiliaryFileToChunks + } + ); + const limited = spaceLimited(groupedAssets, options.assetsSpace); + object.assets = limited.children; + object.filteredAssets = limited.filteredChildren; + }, + chunks: (object, compilation, context, options, factory) => { + const { type } = context; + object.chunks = factory.create( + `${type}.chunks`, + Array.from(compilation.chunks), + context + ); + }, + modules: (object, compilation, context, options, factory) => { + const { type } = context; + const array = Array.from(compilation.modules); + const groupedModules = factory.create(`${type}.modules`, array, context); + const limited = spaceLimited(groupedModules, options.modulesSpace); + object.modules = limited.children; + object.filteredModules = limited.filteredChildren; + }, + entrypoints: ( + object, + compilation, + context, + { entrypoints, chunkGroups, chunkGroupAuxiliary, chunkGroupChildren }, + factory + ) => { + const { type } = context; + const array = Array.from(compilation.entrypoints, ([key, value]) => ({ + name: key, + chunkGroup: value + })); + if (entrypoints === "auto" && !chunkGroups) { + if (array.length > 5) return; + if ( + !chunkGroupChildren && + array.every(({ chunkGroup }) => { + if (chunkGroup.chunks.length !== 1) return false; + const chunk = chunkGroup.chunks[0]; + return ( + chunk.files.size === 1 && + (!chunkGroupAuxiliary || chunk.auxiliaryFiles.size === 0) + ); + }) + ) { + return; + } } - list.push(item); - } - } - const result = []; - for (const list of map.values()) { - if (condition(list)) { - for (const item of list) { - itemsSet.delete(item); + object.entrypoints = factory.create( + `${type}.entrypoints`, + array, + context + ); + }, + chunkGroups: (object, compilation, context, options, factory) => { + const { type } = context; + const array = Array.from( + compilation.namedChunkGroups, + ([key, value]) => ({ + name: key, + chunkGroup: value + }) + ); + object.namedChunkGroups = factory.create( + `${type}.namedChunkGroups`, + array, + context + ); + }, + errors: (object, compilation, context, options, factory) => { + const { type, cachedGetErrors } = context; + object.errors = factory.create( + `${type}.errors`, + cachedGetErrors(compilation), + context + ); + }, + errorsCount: (object, compilation, { cachedGetErrors }) => { + object.errorsCount = countWithChildren(compilation, c => + cachedGetErrors(c) + ); + }, + warnings: (object, compilation, context, options, factory) => { + const { type, cachedGetWarnings } = context; + object.warnings = factory.create( + `${type}.warnings`, + cachedGetWarnings(compilation), + context + ); + }, + warningsCount: ( + object, + compilation, + context, + { warningsFilter }, + factory + ) => { + const { type, cachedGetWarnings } = context; + object.warningsCount = countWithChildren(compilation, (c, childType) => { + if (!warningsFilter && warningsFilter.length === 0) + return cachedGetWarnings(c); + return factory + .create(`${type}${childType}.warnings`, cachedGetWarnings(c), context) + .filter(warning => { + const warningString = Object.keys(warning) + .map(key => `${warning[key]}`) + .join("\n"); + return !warningsFilter.some(filter => + filter(warning, warningString) + ); + }); + }); + }, + errorDetails: ( + object, + compilation, + { cachedGetErrors, cachedGetWarnings }, + { errorDetails, errors, warnings } + ) => { + if (errorDetails === "auto") { + if (warnings) { + const warnings = cachedGetWarnings(compilation); + object.filteredWarningDetailsCount = warnings + .map(e => typeof e !== "string" && e.details) + .filter(Boolean).length; + } + if (errors) { + const errors = cachedGetErrors(compilation); + if (errors.length >= 3) { + object.filteredErrorDetailsCount = errors + .map(e => typeof e !== "string" && e.details) + .filter(Boolean).length; + } + } } - result.push(list); + }, + children: (object, compilation, context, options, factory) => { + const { type } = context; + object.children = factory.create( + `${type}.children`, + compilation.children, + context + ); } - } - return result; -}; - -const getCommonPrefix = items => { - let prefix = items[0]; - for (let i = 1; i < items.length; i++) { - const item = items[i]; - for (let p = 0; p < prefix.length; p++) { - if (item[p] !== prefix[p]) { - prefix = prefix.slice(0, p); - break; + }, + asset: { + _: (object, asset, context, options, factory) => { + const { compilation } = context; + object.type = asset.type; + object.name = asset.name; + object.size = asset.source.size(); + object.emitted = compilation.emittedAssets.has(asset.name); + object.comparedForEmit = compilation.comparedForEmitAssets.has( + asset.name + ); + const cached = !object.emitted && !object.comparedForEmit; + object.cached = cached; + object.info = asset.info; + if (!cached || options.cachedAssets) { + Object.assign( + object, + factory.create(`${context.type}$visible`, asset, context) + ); } } - } - return prefix; -}; - -const getCommonSuffix = items => { - let suffix = items[0]; - for (let i = 1; i < items.length; i++) { - const item = items[i]; - for (let p = item.length - 1, s = suffix.length - 1; s >= 0; p--, s--) { - if (item[p] !== suffix[s]) { - suffix = suffix.slice(s + 1); - break; - } + }, + asset$visible: { + _: ( + object, + asset, + { compilation, compilationFileToChunks, compilationAuxiliaryFileToChunks } + ) => { + const chunks = compilationFileToChunks.get(asset.name) || []; + const auxiliaryChunks = + compilationAuxiliaryFileToChunks.get(asset.name) || []; + object.chunkNames = uniqueOrderedArray( + chunks, + c => (c.name ? [c.name] : []), + compareIds + ); + object.chunkIdHints = uniqueOrderedArray( + chunks, + c => Array.from(c.idNameHints), + compareIds + ); + object.auxiliaryChunkNames = uniqueOrderedArray( + auxiliaryChunks, + c => (c.name ? [c.name] : []), + compareIds + ); + object.auxiliaryChunkIdHints = uniqueOrderedArray( + auxiliaryChunks, + c => Array.from(c.idNameHints), + compareIds + ); + object.filteredRelated = asset.related ? asset.related.length : undefined; + }, + relatedAssets: (object, asset, context, options, factory) => { + const { type } = context; + object.related = factory.create( + `${type.slice(0, -8)}.related`, + asset.related, + context + ); + object.filteredRelated = asset.related + ? asset.related.length - object.related.length + : undefined; + }, + ids: ( + object, + asset, + { compilationFileToChunks, compilationAuxiliaryFileToChunks } + ) => { + const chunks = compilationFileToChunks.get(asset.name) || []; + const auxiliaryChunks = + compilationAuxiliaryFileToChunks.get(asset.name) || []; + object.chunks = uniqueOrderedArray(chunks, c => c.ids, compareIds); + object.auxiliaryChunks = uniqueOrderedArray( + auxiliaryChunks, + c => c.ids, + compareIds + ); + }, + performance: (object, asset) => { + object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(asset.source); } - } - return suffix; -}; + }, + chunkGroup: { + _: ( + object, + { name, chunkGroup }, + { compilation, compilation: { moduleGraph, chunkGraph } }, + { ids, chunkGroupAuxiliary, chunkGroupChildren, chunkGroupMaxAssets } + ) => { + const children = + chunkGroupChildren && + chunkGroup.getChildrenByOrders(moduleGraph, chunkGraph); + /** + * @param {string} name Name + * @returns {{ name: string, size: number }} Asset object + */ + const toAsset = name => { + const asset = compilation.getAsset(name); + return { + name, + size: asset ? asset.info.size : -1 + }; + }; + /** @type {(total: number, asset: { size: number }) => number} */ + const sizeReducer = (total, { size }) => total + size; + const assets = uniqueArray(chunkGroup.chunks, c => c.files).map(toAsset); + const auxiliaryAssets = uniqueOrderedArray( + chunkGroup.chunks, + c => c.auxiliaryFiles, + compareIds + ).map(toAsset); + const assetsSize = assets.reduce(sizeReducer, 0); + const auxiliaryAssetsSize = auxiliaryAssets.reduce(sizeReducer, 0); + /** @type {KnownStatsChunkGroup} */ + const statsChunkGroup = { + name, + chunks: ids ? chunkGroup.chunks.map(c => c.id) : undefined, + assets: assets.length <= chunkGroupMaxAssets ? assets : undefined, + filteredAssets: + assets.length <= chunkGroupMaxAssets ? 0 : assets.length, + assetsSize, + auxiliaryAssets: + chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets + ? auxiliaryAssets + : undefined, + filteredAuxiliaryAssets: + chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets + ? 0 + : auxiliaryAssets.length, + auxiliaryAssetsSize, + children: children + ? mapObject(children, groups => + groups.map(group => { + const assets = uniqueArray(group.chunks, c => c.files).map( + toAsset + ); + const auxiliaryAssets = uniqueOrderedArray( + group.chunks, + c => c.auxiliaryFiles, + compareIds + ).map(toAsset); -const itemsToRegexp = itemsArr => { - if (itemsArr.length === 1) { - return quoteMeta(itemsArr[0]); - } - const finishedItems = []; + /** @type {KnownStatsChunkGroup} */ + const childStatsChunkGroup = { + name: group.name, + chunks: ids ? group.chunks.map(c => c.id) : undefined, + assets: + assets.length <= chunkGroupMaxAssets ? assets : undefined, + filteredAssets: + assets.length <= chunkGroupMaxAssets ? 0 : assets.length, + auxiliaryAssets: + chunkGroupAuxiliary && + auxiliaryAssets.length <= chunkGroupMaxAssets + ? auxiliaryAssets + : undefined, + filteredAuxiliaryAssets: + chunkGroupAuxiliary && + auxiliaryAssets.length <= chunkGroupMaxAssets + ? 0 + : auxiliaryAssets.length + }; - // merge single char items: (a|b|c|d|ef) => ([abcd]|ef) - let countOfSingleCharItems = 0; - for (const item of itemsArr) { - if (item.length === 1) { - countOfSingleCharItems++; + return childStatsChunkGroup; + }) + ) + : undefined, + childAssets: children + ? mapObject(children, groups => { + /** @type {Set} */ + const set = new Set(); + for (const group of groups) { + for (const chunk of group.chunks) { + for (const asset of chunk.files) { + set.add(asset); + } + } + } + return Array.from(set); + }) + : undefined + }; + Object.assign(object, statsChunkGroup); + }, + performance: (object, { chunkGroup }) => { + object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(chunkGroup); } - } - // special case for only single char items - if (countOfSingleCharItems === itemsArr.length) { - return `[${quoteMeta(itemsArr.sort().join(""))}]`; - } - const items = new Set(itemsArr.sort()); - if (countOfSingleCharItems > 2) { - let singleCharItems = ""; - for (const item of items) { - if (item.length === 1) { - singleCharItems += item; - items.delete(item); + }, + module: { + _: (object, module, context, options, factory) => { + const { compilation, type } = context; + const built = compilation.builtModules.has(module); + const codeGenerated = compilation.codeGeneratedModules.has(module); + const buildTimeExecuted = + compilation.buildTimeExecutedModules.has(module); + /** @type {{[x: string]: number}} */ + const sizes = {}; + for (const sourceType of module.getSourceTypes()) { + sizes[sourceType] = module.size(sourceType); } - } - finishedItems.push(`[${quoteMeta(singleCharItems)}]`); - } - - // special case for 2 items with common prefix/suffix - if (finishedItems.length === 0 && items.size === 2) { - const prefix = getCommonPrefix(itemsArr); - const suffix = getCommonSuffix( - itemsArr.map(item => item.slice(prefix.length)) - ); - if (prefix.length > 0 || suffix.length > 0) { - return `${quoteMeta(prefix)}${itemsToRegexp( - itemsArr.map(i => i.slice(prefix.length, -suffix.length || undefined)) - )}${quoteMeta(suffix)}`; - } - } - - // special case for 2 items with common suffix - if (finishedItems.length === 0 && items.size === 2) { - const it = items[Symbol.iterator](); - const a = it.next().value; - const b = it.next().value; - if (a.length > 0 && b.length > 0 && a.slice(-1) === b.slice(-1)) { - return `${itemsToRegexp([a.slice(0, -1), b.slice(0, -1)])}${quoteMeta( - a.slice(-1) - )}`; - } - } - - // find common prefix: (a1|a2|a3|a4|b5) => (a(1|2|3|4)|b5) - const prefixed = popCommonItems( - items, - item => (item.length >= 1 ? item[0] : false), - list => { - if (list.length >= 3) return true; - if (list.length <= 1) return false; - return list[0][1] === list[1][1]; - } - ); - for (const prefixedItems of prefixed) { - const prefix = getCommonPrefix(prefixedItems); - finishedItems.push( - `${quoteMeta(prefix)}${itemsToRegexp( - prefixedItems.map(i => i.slice(prefix.length)) - )}` - ); - } - - // find common suffix: (a1|b1|c1|d1|e2) => ((a|b|c|d)1|e2) - const suffixed = popCommonItems( - items, - item => (item.length >= 1 ? item.slice(-1) : false), - list => { - if (list.length >= 3) return true; - if (list.length <= 1) return false; - return list[0].slice(-2) === list[1].slice(-2); - } - ); - for (const suffixedItems of suffixed) { - const suffix = getCommonSuffix(suffixedItems); - finishedItems.push( - `${itemsToRegexp( - suffixedItems.map(i => i.slice(0, -suffix.length)) - )}${quoteMeta(suffix)}` - ); - } - - // TODO further optimize regexp, i. e. - // use ranges: (1|2|3|4|a) => [1-4a] - const conditional = finishedItems.concat(Array.from(items, quoteMeta)); - if (conditional.length === 1) return conditional[0]; - return `(${conditional.join("|")})`; -}; - -compileBooleanMatcher.fromLists = compileBooleanMatcherFromLists; -compileBooleanMatcher.itemsToRegexp = itemsToRegexp; -module.exports = compileBooleanMatcher; - - -/***/ }), - -/***/ 32540: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const memoize = __webpack_require__(78676); - -const getValidate = memoize(() => (__webpack_require__(38476).validate)); + /** @type {KnownStatsModule} */ + const statsModule = { + type: "module", + moduleType: module.type, + layer: module.layer, + size: module.size(), + sizes, + built, + codeGenerated, + buildTimeExecuted, + cached: !built && !codeGenerated + }; + Object.assign(object, statsModule); -const createSchemaValidation = (check, getSchema, options) => { - getSchema = memoize(getSchema); - return value => { - if (check && !check(value)) { - getValidate()(getSchema(), value, options); - if (check) { - (__webpack_require__(73837).deprecate)( - () => {}, - "webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.", - "DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID" - )(); + if (built || codeGenerated || options.cachedModules) { + Object.assign( + object, + factory.create(`${type}$visible`, module, context) + ); } } - }; -}; - -module.exports = createSchemaValidation; - - -/***/ }), - -/***/ 49835: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Hash = __webpack_require__(36692); - -const BULK_SIZE = 2000; - -// We are using an object instead of a Map as this will stay static during the runtime -// so access to it can be optimized by v8 -const digestCaches = {}; - -class BulkUpdateDecorator extends Hash { - /** - * @param {Hash | function(): Hash} hashOrFactory function to create a hash - * @param {string=} hashKey key for caching - */ - constructor(hashOrFactory, hashKey) { - super(); - this.hashKey = hashKey; - if (typeof hashOrFactory === "function") { - this.hashFactory = hashOrFactory; - this.hash = undefined; - } else { - this.hashFactory = undefined; - this.hash = hashOrFactory; - } - this.buffer = ""; - } - - /** - * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} - * @param {string|Buffer} data data - * @param {string=} inputEncoding data encoding - * @returns {this} updated hash - */ - update(data, inputEncoding) { - if ( - inputEncoding !== undefined || - typeof data !== "string" || - data.length > BULK_SIZE - ) { - if (this.hash === undefined) this.hash = this.hashFactory(); - if (this.buffer.length > 0) { - this.hash.update(this.buffer); - this.buffer = ""; + }, + module$visible: { + _: (object, module, context, { requestShortener }, factory) => { + const { compilation, type, rootModules } = context; + const { moduleGraph } = compilation; + /** @type {Module[]} */ + const path = []; + const issuer = moduleGraph.getIssuer(module); + let current = issuer; + while (current) { + path.push(current); + current = moduleGraph.getIssuer(current); } - this.hash.update(data, inputEncoding); - } else { - this.buffer += data; - if (this.buffer.length > BULK_SIZE) { - if (this.hash === undefined) this.hash = this.hashFactory(); - this.hash.update(this.buffer); - this.buffer = ""; + path.reverse(); + const profile = moduleGraph.getProfile(module); + const errors = module.getErrors(); + const errorsCount = errors !== undefined ? countIterable(errors) : 0; + const warnings = module.getWarnings(); + const warningsCount = + warnings !== undefined ? countIterable(warnings) : 0; + /** @type {{[x: string]: number}} */ + const sizes = {}; + for (const sourceType of module.getSourceTypes()) { + sizes[sourceType] = module.size(sourceType); } - } - return this; - } - - /** - * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} - * @param {string=} encoding encoding of the return value - * @returns {string|Buffer} digest - */ - digest(encoding) { - let digestCache; - const buffer = this.buffer; - if (this.hash === undefined) { - // short data for hash, we can use caching - const cacheKey = `${this.hashKey}-${encoding}`; - digestCache = digestCaches[cacheKey]; - if (digestCache === undefined) { - digestCache = digestCaches[cacheKey] = new Map(); + /** @type {KnownStatsModule} */ + const statsModule = { + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener), + nameForCondition: module.nameForCondition(), + index: moduleGraph.getPreOrderIndex(module), + preOrderIndex: moduleGraph.getPreOrderIndex(module), + index2: moduleGraph.getPostOrderIndex(module), + postOrderIndex: moduleGraph.getPostOrderIndex(module), + cacheable: module.buildInfo.cacheable, + optional: module.isOptional(moduleGraph), + orphan: + !type.endsWith("module.modules[].module$visible") && + compilation.chunkGraph.getNumberOfModuleChunks(module) === 0, + dependent: rootModules ? !rootModules.has(module) : undefined, + issuer: issuer && issuer.identifier(), + issuerName: issuer && issuer.readableIdentifier(requestShortener), + issuerPath: + issuer && + factory.create(`${type.slice(0, -8)}.issuerPath`, path, context), + failed: errorsCount > 0, + errors: errorsCount, + warnings: warningsCount + }; + Object.assign(object, statsModule); + if (profile) { + object.profile = factory.create( + `${type.slice(0, -8)}.profile`, + profile, + context + ); + } + }, + ids: (object, module, { compilation: { chunkGraph, moduleGraph } }) => { + object.id = chunkGraph.getModuleId(module); + const issuer = moduleGraph.getIssuer(module); + object.issuerId = issuer && chunkGraph.getModuleId(issuer); + object.chunks = Array.from( + chunkGraph.getOrderedModuleChunksIterable(module, compareChunksById), + chunk => chunk.id + ); + }, + moduleAssets: (object, module) => { + object.assets = module.buildInfo.assets + ? Object.keys(module.buildInfo.assets) + : []; + }, + reasons: (object, module, context, options, factory) => { + const { + type, + compilation: { moduleGraph } + } = context; + const groupsReasons = factory.create( + `${type.slice(0, -8)}.reasons`, + Array.from(moduleGraph.getIncomingConnections(module)), + context + ); + const limited = spaceLimited(groupsReasons, options.reasonsSpace); + object.reasons = limited.children; + object.filteredReasons = limited.filteredChildren; + }, + usedExports: ( + object, + module, + { runtime, compilation: { moduleGraph } } + ) => { + const usedExports = moduleGraph.getUsedExports(module, runtime); + if (usedExports === null) { + object.usedExports = null; + } else if (typeof usedExports === "boolean") { + object.usedExports = usedExports; + } else { + object.usedExports = Array.from(usedExports); + } + }, + providedExports: (object, module, { compilation: { moduleGraph } }) => { + const providedExports = moduleGraph.getProvidedExports(module); + object.providedExports = Array.isArray(providedExports) + ? providedExports + : null; + }, + optimizationBailout: ( + object, + module, + { compilation: { moduleGraph } }, + { requestShortener } + ) => { + object.optimizationBailout = moduleGraph + .getOptimizationBailout(module) + .map(item => { + if (typeof item === "function") return item(requestShortener); + return item; + }); + }, + depth: (object, module, { compilation: { moduleGraph } }) => { + object.depth = moduleGraph.getDepth(module); + }, + nestedModules: (object, module, context, options, factory) => { + const { type } = context; + const innerModules = /** @type {Module & { modules?: Module[] }} */ ( + module + ).modules; + if (Array.isArray(innerModules)) { + const groupedModules = factory.create( + `${type.slice(0, -8)}.modules`, + innerModules, + context + ); + const limited = spaceLimited( + groupedModules, + options.nestedModulesSpace + ); + object.modules = limited.children; + object.filteredModules = limited.filteredChildren; + } + }, + source: (object, module) => { + const originalSource = module.originalSource(); + if (originalSource) { + object.source = originalSource.source(); } - const cacheEntry = digestCache.get(buffer); - if (cacheEntry !== undefined) return cacheEntry; - this.hash = this.hashFactory(); } - if (buffer.length > 0) { - this.hash.update(buffer); + }, + profile: { + _: (object, profile) => { + /** @type {KnownStatsProfile} */ + const statsProfile = { + total: + profile.factory + + profile.restoring + + profile.integration + + profile.building + + profile.storing, + resolving: profile.factory, + restoring: profile.restoring, + building: profile.building, + integration: profile.integration, + storing: profile.storing, + additionalResolving: profile.additionalFactories, + additionalIntegration: profile.additionalIntegration, + // TODO remove this in webpack 6 + factory: profile.factory, + // TODO remove this in webpack 6 + dependencies: profile.additionalFactories + }; + Object.assign(object, statsProfile); } - const digestResult = this.hash.digest(encoding); - const result = - typeof digestResult === "string" ? digestResult : digestResult.toString(); - if (digestCache !== undefined) { - digestCache.set(buffer, result); + }, + moduleIssuer: { + _: (object, module, context, { requestShortener }, factory) => { + const { compilation, type } = context; + const { moduleGraph } = compilation; + const profile = moduleGraph.getProfile(module); + /** @type {KnownStatsModuleIssuer} */ + const statsModuleIssuer = { + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener) + }; + Object.assign(object, statsModuleIssuer); + if (profile) { + object.profile = factory.create(`${type}.profile`, profile, context); + } + }, + ids: (object, module, { compilation: { chunkGraph } }) => { + object.id = chunkGraph.getModuleId(module); } - return result; - } -} - -/* istanbul ignore next */ -class DebugHash extends Hash { - constructor() { - super(); - this.string = ""; - } - - /** - * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} - * @param {string|Buffer} data data - * @param {string=} inputEncoding data encoding - * @returns {this} updated hash - */ - update(data, inputEncoding) { - if (typeof data !== "string") data = data.toString("utf-8"); - if (data.startsWith("debug-digest-")) { - data = Buffer.from(data.slice("debug-digest-".length), "hex").toString(); + }, + moduleReason: { + _: (object, reason, { runtime }, { requestShortener }) => { + const dep = reason.dependency; + const moduleDep = + dep && dep instanceof ModuleDependency ? dep : undefined; + /** @type {KnownStatsModuleReason} */ + const statsModuleReason = { + moduleIdentifier: reason.originModule + ? reason.originModule.identifier() + : null, + module: reason.originModule + ? reason.originModule.readableIdentifier(requestShortener) + : null, + moduleName: reason.originModule + ? reason.originModule.readableIdentifier(requestShortener) + : null, + resolvedModuleIdentifier: reason.resolvedOriginModule + ? reason.resolvedOriginModule.identifier() + : null, + resolvedModule: reason.resolvedOriginModule + ? reason.resolvedOriginModule.readableIdentifier(requestShortener) + : null, + type: reason.dependency ? reason.dependency.type : null, + active: reason.isActive(runtime), + explanation: reason.explanation, + userRequest: (moduleDep && moduleDep.userRequest) || null + }; + Object.assign(object, statsModuleReason); + if (reason.dependency) { + const locInfo = formatLocation(reason.dependency.loc); + if (locInfo) { + object.loc = locInfo; + } + } + }, + ids: (object, reason, { compilation: { chunkGraph } }) => { + object.moduleId = reason.originModule + ? chunkGraph.getModuleId(reason.originModule) + : null; + object.resolvedModuleId = reason.resolvedOriginModule + ? chunkGraph.getModuleId(reason.resolvedOriginModule) + : null; } - this.string += `[${data}](${new Error().stack.split("\n", 3)[2]})\n`; - return this; - } - - /** - * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} - * @param {string=} encoding encoding of the return value - * @returns {string|Buffer} digest - */ - digest(encoding) { - return "debug-digest-" + Buffer.from(this.string).toString("hex"); - } -} + }, + chunk: { + _: (object, chunk, { makePathsRelative, compilation: { chunkGraph } }) => { + const childIdByOrder = chunk.getChildIdsByOrders(chunkGraph); -let crypto = undefined; -let createXXHash64 = undefined; -let createMd4 = undefined; -let BatchedHash = undefined; + /** @type {KnownStatsChunk} */ + const statsChunk = { + rendered: chunk.rendered, + initial: chunk.canBeInitial(), + entry: chunk.hasRuntime(), + recorded: AggressiveSplittingPlugin.wasChunkRecorded(chunk), + reason: chunk.chunkReason, + size: chunkGraph.getChunkModulesSize(chunk), + sizes: chunkGraph.getChunkModulesSizes(chunk), + names: chunk.name ? [chunk.name] : [], + idHints: Array.from(chunk.idNameHints), + runtime: + chunk.runtime === undefined + ? undefined + : typeof chunk.runtime === "string" + ? [makePathsRelative(chunk.runtime)] + : Array.from(chunk.runtime.sort(), makePathsRelative), + files: Array.from(chunk.files), + auxiliaryFiles: Array.from(chunk.auxiliaryFiles).sort(compareIds), + hash: chunk.renderedHash, + childrenByOrder: childIdByOrder + }; + Object.assign(object, statsChunk); + }, + ids: (object, chunk) => { + object.id = chunk.id; + }, + chunkRelations: (object, chunk, { compilation: { chunkGraph } }) => { + /** @type {Set} */ + const parents = new Set(); + /** @type {Set} */ + const children = new Set(); + /** @type {Set} */ + const siblings = new Set(); -/** - * Creates a hash by name or function - * @param {string | typeof Hash} algorithm the algorithm name or a constructor creating a hash - * @returns {Hash} the hash - */ -module.exports = algorithm => { - if (typeof algorithm === "function") { - return new BulkUpdateDecorator(() => new algorithm()); - } - switch (algorithm) { - // TODO add non-cryptographic algorithm here - case "debug": - return new DebugHash(); - case "xxhash64": - if (createXXHash64 === undefined) { - createXXHash64 = __webpack_require__(35028); - if (BatchedHash === undefined) { - BatchedHash = __webpack_require__(59461); + for (const chunkGroup of chunk.groupsIterable) { + for (const parentGroup of chunkGroup.parentsIterable) { + for (const chunk of parentGroup.chunks) { + parents.add(chunk.id); + } } - } - return new BatchedHash(createXXHash64()); - case "md4": - if (createMd4 === undefined) { - createMd4 = __webpack_require__(86884); - if (BatchedHash === undefined) { - BatchedHash = __webpack_require__(59461); + for (const childGroup of chunkGroup.childrenIterable) { + for (const chunk of childGroup.chunks) { + children.add(chunk.id); + } + } + for (const sibling of chunkGroup.chunks) { + if (sibling !== chunk) siblings.add(sibling.id); } } - return new BatchedHash(createMd4()); - case "native-md4": - if (crypto === undefined) crypto = __webpack_require__(6113); - return new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4"); - default: - if (crypto === undefined) crypto = __webpack_require__(6113); - return new BulkUpdateDecorator( - () => crypto.createHash(algorithm), - algorithm - ); - } -}; - - -/***/ }), - -/***/ 64518: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const util = __webpack_require__(73837); - -/** @type {Map} */ -const deprecationCache = new Map(); - -/** - * @typedef {Object} FakeHookMarker - * @property {true} _fakeHook it's a fake hook - */ - -/** @template T @typedef {T & FakeHookMarker} FakeHook */ - -/** - * @param {string} message deprecation message - * @param {string} code deprecation code - * @returns {Function} function to trigger deprecation - */ -const createDeprecation = (message, code) => { - const cached = deprecationCache.get(message); - if (cached !== undefined) return cached; - const fn = util.deprecate( - () => {}, - message, - "DEP_WEBPACK_DEPRECATION_" + code - ); - deprecationCache.set(message, fn); - return fn; -}; - -const COPY_METHODS = [ - "concat", - "entry", - "filter", - "find", - "findIndex", - "includes", - "indexOf", - "join", - "lastIndexOf", - "map", - "reduce", - "reduceRight", - "slice", - "some" -]; - -const DISABLED_METHODS = [ - "copyWithin", - "entries", - "fill", - "keys", - "pop", - "reverse", - "shift", - "splice", - "sort", - "unshift" -]; - -/** - * @param {any} set new set - * @param {string} name property name - * @returns {void} - */ -exports.arrayToSetDeprecation = (set, name) => { - for (const method of COPY_METHODS) { - if (set[method]) continue; - const d = createDeprecation( - `${name} was changed from Array to Set (using Array method '${method}' is deprecated)`, - "ARRAY_TO_SET" - ); - /** - * @deprecated - * @this {Set} - * @returns {number} count - */ - set[method] = function () { - d(); - const array = Array.from(this); - return Array.prototype[method].apply(array, arguments); - }; - } - const dPush = createDeprecation( - `${name} was changed from Array to Set (using Array method 'push' is deprecated)`, - "ARRAY_TO_SET_PUSH" - ); - const dLength = createDeprecation( - `${name} was changed from Array to Set (using Array property 'length' is deprecated)`, - "ARRAY_TO_SET_LENGTH" - ); - const dIndexer = createDeprecation( - `${name} was changed from Array to Set (indexing Array is deprecated)`, - "ARRAY_TO_SET_INDEXER" - ); - /** - * @deprecated - * @this {Set} - * @returns {number} count - */ - set.push = function () { - dPush(); - for (const item of Array.from(arguments)) { - this.add(item); - } - return this.size; - }; - for (const method of DISABLED_METHODS) { - if (set[method]) continue; - set[method] = () => { - throw new Error( - `${name} was changed from Array to Set (using Array method '${method}' is not possible)` - ); - }; - } - const createIndexGetter = index => { - /** - * @this {Set} a Set - * @returns {any} the value at this location - */ - const fn = function () { - dIndexer(); - let i = 0; - for (const item of this) { - if (i++ === index) return item; - } - return undefined; - }; - return fn; - }; - const defineIndexGetter = index => { - Object.defineProperty(set, index, { - get: createIndexGetter(index), - set(value) { - throw new Error( - `${name} was changed from Array to Set (indexing Array with write is not possible)` - ); - } - }); - }; - defineIndexGetter(0); - let indexerDefined = 1; - Object.defineProperty(set, "length", { - get() { - dLength(); - const length = this.size; - for (indexerDefined; indexerDefined < length + 1; indexerDefined++) { - defineIndexGetter(indexerDefined); + object.siblings = Array.from(siblings).sort(compareIds); + object.parents = Array.from(parents).sort(compareIds); + object.children = Array.from(children).sort(compareIds); + }, + chunkModules: (object, chunk, context, options, factory) => { + const { + type, + compilation: { chunkGraph } + } = context; + const array = chunkGraph.getChunkModules(chunk); + const groupedModules = factory.create(`${type}.modules`, array, { + ...context, + runtime: chunk.runtime, + rootModules: new Set(chunkGraph.getChunkRootModules(chunk)) + }); + const limited = spaceLimited(groupedModules, options.chunkModulesSpace); + object.modules = limited.children; + object.filteredModules = limited.filteredChildren; + }, + chunkOrigins: (object, chunk, context, options, factory) => { + const { + type, + compilation: { chunkGraph } + } = context; + /** @type {Set} */ + const originsKeySet = new Set(); + const origins = []; + for (const g of chunk.groupsIterable) { + origins.push(...g.origins); } - return length; + const array = origins.filter(origin => { + const key = [ + origin.module ? chunkGraph.getModuleId(origin.module) : undefined, + formatLocation(origin.loc), + origin.request + ].join(); + if (originsKeySet.has(key)) return false; + originsKeySet.add(key); + return true; + }); + object.origins = factory.create(`${type}.origins`, array, context); + } + }, + chunkOrigin: { + _: (object, origin, context, { requestShortener }) => { + /** @type {KnownStatsChunkOrigin} */ + const statsChunkOrigin = { + module: origin.module ? origin.module.identifier() : "", + moduleIdentifier: origin.module ? origin.module.identifier() : "", + moduleName: origin.module + ? origin.module.readableIdentifier(requestShortener) + : "", + loc: formatLocation(origin.loc), + request: origin.request + }; + Object.assign(object, statsChunkOrigin); }, - set(value) { - throw new Error( - `${name} was changed from Array to Set (writing to Array property 'length' is not possible)` + ids: (object, origin, { compilation: { chunkGraph } }) => { + object.moduleId = origin.module + ? chunkGraph.getModuleId(origin.module) + : undefined; + } + }, + error: EXTRACT_ERROR, + warning: EXTRACT_ERROR, + moduleTraceItem: { + _: (object, { origin, module }, context, { requestShortener }, factory) => { + const { + type, + compilation: { moduleGraph } + } = context; + object.originIdentifier = origin.identifier(); + object.originName = origin.readableIdentifier(requestShortener); + object.moduleIdentifier = module.identifier(); + object.moduleName = module.readableIdentifier(requestShortener); + const dependencies = Array.from( + moduleGraph.getIncomingConnections(module) + ) + .filter(c => c.resolvedOriginModule === origin && c.dependency) + .map(c => c.dependency); + object.dependencies = factory.create( + `${type}.dependencies`, + Array.from(new Set(dependencies)), + context ); + }, + ids: (object, { origin, module }, { compilation: { chunkGraph } }) => { + object.originId = chunkGraph.getModuleId(origin); + object.moduleId = chunkGraph.getModuleId(module); } - }); - set[Symbol.isConcatSpreadable] = true; -}; - -exports.createArrayToSetDeprecationSet = name => { - let initialized = false; - class SetDeprecatedArray extends Set { - constructor(items) { - super(items); - if (!initialized) { - initialized = true; - exports.arrayToSetDeprecation(SetDeprecatedArray.prototype, name); - } + }, + moduleTraceDependency: { + _: (object, dependency) => { + object.loc = formatLocation(dependency.loc); } } - return SetDeprecatedArray; -}; - -exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => { - const message = `${name} will be frozen in future, all modifications are deprecated.${ - note && `\n${note}` - }`; - return new Proxy(obj, { - set: util.deprecate( - (target, property, value, receiver) => - Reflect.set(target, property, value, receiver), - message, - code - ), - defineProperty: util.deprecate( - (target, property, descriptor) => - Reflect.defineProperty(target, property, descriptor), - message, - code - ), - deleteProperty: util.deprecate( - (target, property) => Reflect.deleteProperty(target, property), - message, - code - ), - setPrototypeOf: util.deprecate( - (target, proto) => Reflect.setPrototypeOf(target, proto), - message, - code - ) - }); }; -/** - * @template T - * @param {T} obj object - * @param {string} message deprecation message - * @param {string} code deprecation code - * @returns {T} object with property access deprecated - */ -const deprecateAllProperties = (obj, message, code) => { - const newObj = {}; - const descriptors = Object.getOwnPropertyDescriptors(obj); - for (const name of Object.keys(descriptors)) { - const descriptor = descriptors[name]; - if (typeof descriptor.value === "function") { - Object.defineProperty(newObj, name, { - ...descriptor, - value: util.deprecate(descriptor.value, message, code) - }); - } else if (descriptor.get || descriptor.set) { - Object.defineProperty(newObj, name, { - ...descriptor, - get: descriptor.get && util.deprecate(descriptor.get, message, code), - set: descriptor.set && util.deprecate(descriptor.set, message, code) - }); - } else { - let value = descriptor.value; - Object.defineProperty(newObj, name, { - configurable: descriptor.configurable, - enumerable: descriptor.enumerable, - get: util.deprecate(() => value, message, code), - set: descriptor.writable - ? util.deprecate(v => (value = v), message, code) - : undefined - }); +/** @type {Record boolean | undefined>>} */ +const FILTER = { + "module.reasons": { + "!orphanModules": (reason, { compilation: { chunkGraph } }) => { + if ( + reason.originModule && + chunkGraph.getNumberOfModuleChunks(reason.originModule) === 0 + ) { + return false; + } } } - return /** @type {T} */ (newObj); }; -exports.deprecateAllProperties = deprecateAllProperties; -/** - * @template T - * @param {T} fakeHook fake hook implementation - * @param {string=} message deprecation message (not deprecated when unset) - * @param {string=} code deprecation code (not deprecated when unset) - * @returns {FakeHook} fake hook which redirects - */ -exports.createFakeHook = (fakeHook, message, code) => { - if (message && code) { - fakeHook = deprecateAllProperties(fakeHook, message, code); +/** @type {Record boolean | undefined>>} */ +const FILTER_RESULTS = { + "compilation.warnings": { + warningsFilter: util.deprecate( + (warning, context, { warningsFilter }) => { + const warningString = Object.keys(warning) + .map(key => `${warning[key]}`) + .join("\n"); + return !warningsFilter.some(filter => filter(warning, warningString)); + }, + "config.stats.warningsFilter is deprecated in favor of config.ignoreWarnings", + "DEP_WEBPACK_STATS_WARNINGS_FILTER" + ) } - return Object.freeze( - Object.assign(fakeHook, { _fakeHook: /** @type {true} */ (true) }) - ); }; - -/***/ }), - -/***/ 59836: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -// Simulations show these probabilities for a single change -// 93.1% that one group is invalidated -// 4.8% that two groups are invalidated -// 1.1% that 3 groups are invalidated -// 0.1% that 4 or more groups are invalidated -// -// And these for removing/adding 10 lexically adjacent files -// 64.5% that one group is invalidated -// 24.8% that two groups are invalidated -// 7.8% that 3 groups are invalidated -// 2.7% that 4 or more groups are invalidated -// -// And these for removing/adding 3 random files -// 0% that one group is invalidated -// 3.7% that two groups are invalidated -// 80.8% that 3 groups are invalidated -// 12.3% that 4 groups are invalidated -// 3.2% that 5 or more groups are invalidated - -/** - * - * @param {string} a key - * @param {string} b key - * @returns {number} the similarity as number - */ -const similarity = (a, b) => { - const l = Math.min(a.length, b.length); - let dist = 0; - for (let i = 0; i < l; i++) { - const ca = a.charCodeAt(i); - const cb = b.charCodeAt(i); - dist += Math.max(0, 10 - Math.abs(ca - cb)); +/** @type {Record void>} */ +const MODULES_SORTER = { + _: (comparators, { compilation: { moduleGraph } }) => { + comparators.push( + compareSelect( + /** + * @param {Module} m module + * @returns {number} depth + */ + m => moduleGraph.getDepth(m), + compareNumbers + ), + compareSelect( + /** + * @param {Module} m module + * @returns {number} index + */ + m => moduleGraph.getPreOrderIndex(m), + compareNumbers + ), + compareSelect( + /** + * @param {Module} m module + * @returns {string} identifier + */ + m => m.identifier(), + compareIds + ) + ); } - return dist; }; -/** - * @param {string} a key - * @param {string} b key - * @param {Set} usedNames set of already used names - * @returns {string} the common part and a single char for the difference - */ -const getName = (a, b, usedNames) => { - const l = Math.min(a.length, b.length); - let i = 0; - while (i < l) { - if (a.charCodeAt(i) !== b.charCodeAt(i)) { - i++; - break; +/** @type {Record void>>} */ +const SORTERS = { + "compilation.chunks": { + _: comparators => { + comparators.push(compareSelect(c => c.id, compareIds)); } - i++; - } - while (i < l) { - const name = a.slice(0, i); - const lowerName = name.toLowerCase(); - if (!usedNames.has(lowerName)) { - usedNames.add(lowerName); - return name; + }, + "compilation.modules": MODULES_SORTER, + "chunk.rootModules": MODULES_SORTER, + "chunk.modules": MODULES_SORTER, + "module.modules": MODULES_SORTER, + "module.reasons": { + _: (comparators, { compilation: { chunkGraph } }) => { + comparators.push( + compareSelect(x => x.originModule, compareModulesByIdentifier) + ); + comparators.push( + compareSelect(x => x.resolvedOriginModule, compareModulesByIdentifier) + ); + comparators.push( + compareSelect( + x => x.dependency, + concatComparators( + compareSelect( + /** + * @param {Dependency} x dependency + * @returns {DependencyLocation} location + */ + x => x.loc, + compareLocations + ), + compareSelect(x => x.type, compareIds) + ) + ) + ); + } + }, + "chunk.origins": { + _: (comparators, { compilation: { chunkGraph } }) => { + comparators.push( + compareSelect( + origin => + origin.module ? chunkGraph.getModuleId(origin.module) : undefined, + compareIds + ), + compareSelect(origin => formatLocation(origin.loc), compareIds), + compareSelect(origin => origin.request, compareIds) + ); } - i++; } - // names always contain a hash, so this is always unique - // we don't need to check usedNames nor add it - return a; }; -/** - * @param {Record} total total size - * @param {Record} size single size - * @returns {void} - */ -const addSizeTo = (total, size) => { - for (const key of Object.keys(size)) { - total[key] = (total[key] || 0) + size[key]; - } +const getItemSize = item => { + // Each item takes 1 line + // + the size of the children + // + 1 extra line when it has children and filteredChildren + return !item.children + ? 1 + : item.filteredChildren + ? 2 + getTotalSize(item.children) + : 1 + getTotalSize(item.children); }; -/** - * @param {Record} total total size - * @param {Record} size single size - * @returns {void} - */ -const subtractSizeFrom = (total, size) => { - for (const key of Object.keys(size)) { - total[key] -= size[key]; +const getTotalSize = children => { + let size = 0; + for (const child of children) { + size += getItemSize(child); } + return size; }; -/** - * @param {Iterable} nodes some nodes - * @returns {Record} total size - */ -const sumSize = nodes => { - const sum = Object.create(null); - for (const node of nodes) { - addSizeTo(sum, node.size); +const getTotalItems = children => { + let count = 0; + for (const child of children) { + if (!child.children && !child.filteredChildren) { + count++; + } else { + if (child.children) count += getTotalItems(child.children); + if (child.filteredChildren) count += child.filteredChildren; + } } - return sum; + return count; }; -const isTooBig = (size, maxSize) => { - for (const key of Object.keys(size)) { - const s = size[key]; - if (s === 0) continue; - const maxSizeValue = maxSize[key]; - if (typeof maxSizeValue === "number") { - if (s > maxSizeValue) return true; +const collapse = children => { + // After collapse each child must take exactly one line + const newChildren = []; + for (const child of children) { + if (child.children) { + let filteredChildren = child.filteredChildren || 0; + filteredChildren += getTotalItems(child.children); + newChildren.push({ + ...child, + children: undefined, + filteredChildren + }); + } else { + newChildren.push(child); } } - return false; + return newChildren; }; -const isTooSmall = (size, minSize) => { - for (const key of Object.keys(size)) { - const s = size[key]; - if (s === 0) continue; - const minSizeValue = minSize[key]; - if (typeof minSizeValue === "number") { - if (s < minSizeValue) return true; +const spaceLimited = ( + itemsAndGroups, + max, + filteredChildrenLineReserved = false +) => { + if (max < 1) { + return { + children: undefined, + filteredChildren: getTotalItems(itemsAndGroups) + }; + } + /** @type {any[] | undefined} */ + let children = undefined; + /** @type {number | undefined} */ + let filteredChildren = undefined; + // This are the groups, which take 1+ lines each + const groups = []; + // The sizes of the groups are stored in groupSizes + const groupSizes = []; + // This are the items, which take 1 line each + const items = []; + // The total of group sizes + let groupsSize = 0; + + for (const itemOrGroup of itemsAndGroups) { + // is item + if (!itemOrGroup.children && !itemOrGroup.filteredChildren) { + items.push(itemOrGroup); + } else { + groups.push(itemOrGroup); + const size = getItemSize(itemOrGroup); + groupSizes.push(size); + groupsSize += size; } } - return false; -}; -const getTooSmallTypes = (size, minSize) => { - const types = new Set(); - for (const key of Object.keys(size)) { - const s = size[key]; - if (s === 0) continue; - const minSizeValue = minSize[key]; - if (typeof minSizeValue === "number") { - if (s < minSizeValue) types.add(key); + if (groupsSize + items.length <= max) { + // The total size in the current state fits into the max + // keep all + children = groups.length > 0 ? groups.concat(items) : items; + } else if (groups.length === 0) { + // slice items to max + // inner space marks that lines for filteredChildren already reserved + const limit = max - (filteredChildrenLineReserved ? 0 : 1); + filteredChildren = items.length - limit; + items.length = limit; + children = items; + } else { + // limit is the size when all groups are collapsed + const limit = + groups.length + + (filteredChildrenLineReserved || items.length === 0 ? 0 : 1); + if (limit < max) { + // calculate how much we are over the size limit + // this allows to approach the limit faster + let oversize; + // If each group would take 1 line the total would be below the maximum + // collapse some groups, keep items + while ( + (oversize = + groupsSize + + items.length + + (filteredChildren && !filteredChildrenLineReserved ? 1 : 0) - + max) > 0 + ) { + // Find the maximum group and process only this one + const maxGroupSize = Math.max(...groupSizes); + if (maxGroupSize < items.length) { + filteredChildren = items.length; + items.length = 0; + continue; + } + for (let i = 0; i < groups.length; i++) { + if (groupSizes[i] === maxGroupSize) { + const group = groups[i]; + // run this algorithm recursively and limit the size of the children to + // current size - oversize / number of groups + // So it should always end up being smaller + const headerSize = group.filteredChildren ? 2 : 1; + const limited = spaceLimited( + group.children, + maxGroupSize - + // we should use ceil to always feet in max + Math.ceil(oversize / groups.length) - + // we substitute size of group head + headerSize, + headerSize === 2 + ); + groups[i] = { + ...group, + children: limited.children, + filteredChildren: limited.filteredChildren + ? (group.filteredChildren || 0) + limited.filteredChildren + : group.filteredChildren + }; + const newSize = getItemSize(groups[i]); + groupsSize -= maxGroupSize - newSize; + groupSizes[i] = newSize; + break; + } + } + } + children = groups.concat(items); + } else if (limit === max) { + // If we have only enough space to show one line per group and one line for the filtered items + // collapse all groups and items + children = collapse(groups); + filteredChildren = items.length; + } else { + // If we have no space + // collapse complete group + filteredChildren = getTotalItems(itemsAndGroups); } } - return types; + + return { + children, + filteredChildren + }; }; -const getNumberOfMatchingSizeTypes = (size, types) => { - let i = 0; - for (const key of Object.keys(size)) { - if (size[key] !== 0 && types.has(key)) i++; +const assetGroup = (children, assets) => { + let size = 0; + for (const asset of children) { + size += asset.size; } - return i; + return { + size + }; }; -const selectiveSizeSum = (size, types) => { - let sum = 0; - for (const key of Object.keys(size)) { - if (size[key] !== 0 && types.has(key)) sum += size[key]; +const moduleGroup = (children, modules) => { + let size = 0; + const sizes = {}; + for (const module of children) { + size += module.size; + for (const key of Object.keys(module.sizes)) { + sizes[key] = (sizes[key] || 0) + module.sizes[key]; + } } - return sum; + return { + size, + sizes + }; }; -/** - * @template T - */ -class Node { - /** - * @param {T} item item - * @param {string} key key - * @param {Record} size size - */ - constructor(item, key, size) { - this.item = item; - this.key = key; - this.size = size; +const reasonGroup = (children, reasons) => { + let active = false; + for (const reason of children) { + active = active || reason.active; } -} + return { + active + }; +}; -/** - * @template T - */ -class Group { - /** - * @param {Node[]} nodes nodes - * @param {number[]} similarities similarities between the nodes (length = nodes.length - 1) - * @param {Record=} size size of the group - */ - constructor(nodes, similarities, size) { - this.nodes = nodes; - this.similarities = similarities; - this.size = size || sumSize(nodes); - /** @type {string} */ - this.key = undefined; - } +const GROUP_EXTENSION_REGEXP = /(\.[^.]+?)(?:\?|(?: \+ \d+ modules?)?$)/; +const GROUP_PATH_REGEXP = /(.+)[/\\][^/\\]+?(?:\?|(?: \+ \d+ modules?)?$)/; - /** - * @param {function(Node): boolean} filter filter function - * @returns {Node[]} removed nodes - */ - popNodes(filter) { - const newNodes = []; - const newSimilarities = []; - const resultNodes = []; - let lastNode; - for (let i = 0; i < this.nodes.length; i++) { - const node = this.nodes[i]; - if (filter(node)) { - resultNodes.push(node); - } else { - if (newNodes.length > 0) { - newSimilarities.push( - lastNode === this.nodes[i - 1] - ? this.similarities[i - 1] - : similarity(lastNode.key, node.key) - ); +/** @type {Record void>} */ +const ASSETS_GROUPERS = { + _: (groupConfigs, context, options) => { + const groupByFlag = (name, exclude) => { + groupConfigs.push({ + getKeys: asset => { + return asset[name] ? ["1"] : undefined; + }, + getOptions: () => { + return { + groupChildren: !exclude, + force: exclude + }; + }, + createGroup: (key, children, assets) => { + return exclude + ? { + type: "assets by status", + [name]: !!key, + filteredChildren: assets.length, + ...assetGroup(children, assets) + } + : { + type: "assets by status", + [name]: !!key, + children, + ...assetGroup(children, assets) + }; } - newNodes.push(node); - lastNode = node; - } + }); + }; + const { + groupAssetsByEmitStatus, + groupAssetsByPath, + groupAssetsByExtension + } = options; + if (groupAssetsByEmitStatus) { + groupByFlag("emitted"); + groupByFlag("comparedForEmit"); + groupByFlag("isOverSizeLimit"); } - if (resultNodes.length === this.nodes.length) return undefined; - this.nodes = newNodes; - this.similarities = newSimilarities; - this.size = sumSize(newNodes); - return resultNodes; - } -} - -/** - * @param {Iterable} nodes nodes - * @returns {number[]} similarities - */ -const getSimilarities = nodes => { - // calculate similarities between lexically adjacent nodes - /** @type {number[]} */ - const similarities = []; - let last = undefined; - for (const node of nodes) { - if (last !== undefined) { - similarities.push(similarity(last.key, node.key)); + if (groupAssetsByEmitStatus || !options.cachedAssets) { + groupByFlag("cached", !options.cachedAssets); } - last = node; - } - return similarities; -}; - -/** - * @template T - * @typedef {Object} GroupedItems - * @property {string} key - * @property {T[]} items - * @property {Record} size - */ - -/** - * @template T - * @typedef {Object} Options - * @property {Record} maxSize maximum size of a group - * @property {Record} minSize minimum size of a group (preferred over maximum size) - * @property {Iterable} items a list of items - * @property {function(T): Record} getSize function to get size of an item - * @property {function(T): string} getKey function to get the key of an item - */ - -/** - * @template T - * @param {Options} options options object - * @returns {GroupedItems[]} grouped items - */ -module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { - /** @type {Group[]} */ - const result = []; - - const nodes = Array.from( - items, - item => new Node(item, getKey(item), getSize(item)) - ); - - /** @type {Node[]} */ - const initialNodes = []; - - // lexically ordering of keys - nodes.sort((a, b) => { - if (a.key < b.key) return -1; - if (a.key > b.key) return 1; - return 0; - }); - - // return nodes bigger than maxSize directly as group - // But make sure that minSize is not violated - for (const node of nodes) { - if (isTooBig(node.size, maxSize) && !isTooSmall(node.size, minSize)) { - result.push(new Group([node], [])); - } else { - initialNodes.push(node); + if (groupAssetsByPath || groupAssetsByExtension) { + groupConfigs.push({ + getKeys: asset => { + const extensionMatch = + groupAssetsByExtension && GROUP_EXTENSION_REGEXP.exec(asset.name); + const extension = extensionMatch ? extensionMatch[1] : ""; + const pathMatch = + groupAssetsByPath && GROUP_PATH_REGEXP.exec(asset.name); + const path = pathMatch ? pathMatch[1].split(/[/\\]/) : []; + const keys = []; + if (groupAssetsByPath) { + keys.push("."); + if (extension) + keys.push( + path.length + ? `${path.join("/")}/*${extension}` + : `*${extension}` + ); + while (path.length > 0) { + keys.push(path.join("/") + "/"); + path.pop(); + } + } else { + if (extension) keys.push(`*${extension}`); + } + return keys; + }, + createGroup: (key, children, assets) => { + return { + type: groupAssetsByPath ? "assets by path" : "assets by extension", + name: key, + children, + ...assetGroup(children, assets) + }; + } + }); } - } - - if (initialNodes.length > 0) { - const initialGroup = new Group(initialNodes, getSimilarities(initialNodes)); - - const removeProblematicNodes = (group, consideredSize = group.size) => { - const problemTypes = getTooSmallTypes(consideredSize, minSize); - if (problemTypes.size > 0) { - // We hit an edge case where the working set is already smaller than minSize - // We merge problematic nodes with the smallest result node to keep minSize intact - const problemNodes = group.popNodes( - n => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0 - ); - if (problemNodes === undefined) return false; - // Only merge it with result nodes that have the problematic size type - const possibleResultGroups = result.filter( - n => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0 - ); - if (possibleResultGroups.length > 0) { - const bestGroup = possibleResultGroups.reduce((min, group) => { - const minMatches = getNumberOfMatchingSizeTypes(min, problemTypes); - const groupMatches = getNumberOfMatchingSizeTypes( - group, - problemTypes - ); - if (minMatches !== groupMatches) - return minMatches < groupMatches ? group : min; - if ( - selectiveSizeSum(min.size, problemTypes) > - selectiveSizeSum(group.size, problemTypes) - ) - return group; - return min; - }); - for (const node of problemNodes) bestGroup.nodes.push(node); - bestGroup.nodes.sort((a, b) => { - if (a.key < b.key) return -1; - if (a.key > b.key) return 1; - return 0; - }); - } else { - // There are no other nodes with the same size types - // We create a new group and have to accept that it's smaller than minSize - result.push(new Group(problemNodes, null)); + }, + groupAssetsByInfo: (groupConfigs, context, options) => { + const groupByAssetInfoFlag = name => { + groupConfigs.push({ + getKeys: asset => { + return asset.info && asset.info[name] ? ["1"] : undefined; + }, + createGroup: (key, children, assets) => { + return { + type: "assets by info", + info: { + [name]: !!key + }, + children, + ...assetGroup(children, assets) + }; } - return true; - } else { - return false; - } + }); }; - - if (initialGroup.nodes.length > 0) { - const queue = [initialGroup]; - - while (queue.length) { - const group = queue.pop(); - // only groups bigger than maxSize need to be splitted - if (!isTooBig(group.size, maxSize)) { - result.push(group); - continue; - } - // If the group is already too small - // we try to work only with the unproblematic nodes - if (removeProblematicNodes(group)) { - // This changed something, so we try this group again - queue.push(group); - continue; + groupByAssetInfoFlag("immutable"); + groupByAssetInfoFlag("development"); + groupByAssetInfoFlag("hotModuleReplacement"); + }, + groupAssetsByChunk: (groupConfigs, context, options) => { + const groupByNames = name => { + groupConfigs.push({ + getKeys: asset => { + return asset[name]; + }, + createGroup: (key, children, assets) => { + return { + type: "assets by chunk", + [name]: [key], + children, + ...assetGroup(children, assets) + }; } + }); + }; + groupByNames("chunkNames"); + groupByNames("auxiliaryChunkNames"); + groupByNames("chunkIdHints"); + groupByNames("auxiliaryChunkIdHints"); + }, + excludeAssets: (groupConfigs, context, { excludeAssets }) => { + groupConfigs.push({ + getKeys: asset => { + const ident = asset.name; + const excluded = excludeAssets.some(fn => fn(ident, asset)); + if (excluded) return ["excluded"]; + }, + getOptions: () => ({ + groupChildren: false, + force: true + }), + createGroup: (key, children, assets) => ({ + type: "hidden assets", + filteredChildren: assets.length, + ...assetGroup(children, assets) + }) + }); + } +}; - // find unsplittable area from left and right - // going minSize from left and right - // at least one node need to be included otherwise we get stuck - let left = 1; - let leftSize = Object.create(null); - addSizeTo(leftSize, group.nodes[0].size); - while (left < group.nodes.length && isTooSmall(leftSize, minSize)) { - addSizeTo(leftSize, group.nodes[left].size); - left++; - } - let right = group.nodes.length - 2; - let rightSize = Object.create(null); - addSizeTo(rightSize, group.nodes[group.nodes.length - 1].size); - while (right >= 0 && isTooSmall(rightSize, minSize)) { - addSizeTo(rightSize, group.nodes[right].size); - right--; +/** @type {function("module" | "chunk" | "root-of-chunk" | "nested"): Record void>} */ +const MODULES_GROUPERS = type => ({ + _: (groupConfigs, context, options) => { + const groupByFlag = (name, type, exclude) => { + groupConfigs.push({ + getKeys: module => { + return module[name] ? ["1"] : undefined; + }, + getOptions: () => { + return { + groupChildren: !exclude, + force: exclude + }; + }, + createGroup: (key, children, modules) => { + return { + type, + [name]: !!key, + ...(exclude ? { filteredChildren: modules.length } : { children }), + ...moduleGroup(children, modules) + }; } - - // left v v right - // [ O O O ] O O O [ O O O ] - // ^^^^^^^^^ leftSize - // rightSize ^^^^^^^^^ - // leftSize > minSize - // rightSize > minSize - - // Perfect split: [ O O O ] [ O O O ] - // right === left - 1 - - if (left - 1 > right) { - // We try to remove some problematic nodes to "fix" that - let prevSize; - if (right < group.nodes.length - left) { - subtractSizeFrom(rightSize, group.nodes[right + 1].size); - prevSize = rightSize; - } else { - subtractSizeFrom(leftSize, group.nodes[left - 1].size); - prevSize = leftSize; - } - if (removeProblematicNodes(group, prevSize)) { - // This changed something, so we try this group again - queue.push(group); - continue; + }); + }; + const { + groupModulesByCacheStatus, + groupModulesByLayer, + groupModulesByAttributes, + groupModulesByType, + groupModulesByPath, + groupModulesByExtension + } = options; + if (groupModulesByAttributes) { + groupByFlag("errors", "modules with errors"); + groupByFlag("warnings", "modules with warnings"); + groupByFlag("assets", "modules with assets"); + groupByFlag("optional", "optional modules"); + } + if (groupModulesByCacheStatus) { + groupByFlag("cacheable", "cacheable modules"); + groupByFlag("built", "built modules"); + groupByFlag("codeGenerated", "code generated modules"); + } + if (groupModulesByCacheStatus || !options.cachedModules) { + groupByFlag("cached", "cached modules", !options.cachedModules); + } + if (groupModulesByAttributes || !options.orphanModules) { + groupByFlag("orphan", "orphan modules", !options.orphanModules); + } + if (groupModulesByAttributes || !options.dependentModules) { + groupByFlag("dependent", "dependent modules", !options.dependentModules); + } + if (groupModulesByType || !options.runtimeModules) { + groupConfigs.push({ + getKeys: module => { + if (!module.moduleType) return; + if (groupModulesByType) { + return [module.moduleType.split("/", 1)[0]]; + } else if (module.moduleType === "runtime") { + return ["runtime"]; } - // can't split group while holding minSize - // because minSize is preferred of maxSize we return - // the problematic nodes as result here even while it's too big - // To avoid this make sure maxSize > minSize * 3 - result.push(group); - continue; + }, + getOptions: key => { + const exclude = key === "runtime" && !options.runtimeModules; + return { + groupChildren: !exclude, + force: exclude + }; + }, + createGroup: (key, children, modules) => { + const exclude = key === "runtime" && !options.runtimeModules; + return { + type: `${key} modules`, + moduleType: key, + ...(exclude ? { filteredChildren: modules.length } : { children }), + ...moduleGroup(children, modules) + }; } - if (left <= right) { - // when there is a area between left and right - // we look for best split point - // we split at the minimum similarity - // here key space is separated the most - // But we also need to make sure to not create too small groups - let best = -1; - let bestSimilarity = Infinity; - let pos = left; - let rightSize = sumSize(group.nodes.slice(pos)); - - // pos v v right - // [ O O O ] O O O [ O O O ] - // ^^^^^^^^^ leftSize - // rightSize ^^^^^^^^^^^^^^^ - - while (pos <= right + 1) { - const similarity = group.similarities[pos - 1]; - if ( - similarity < bestSimilarity && - !isTooSmall(leftSize, minSize) && - !isTooSmall(rightSize, minSize) - ) { - best = pos; - bestSimilarity = similarity; + }); + } + if (groupModulesByLayer) { + groupConfigs.push({ + getKeys: module => { + return [module.layer]; + }, + createGroup: (key, children, modules) => { + return { + type: "modules by layer", + layer: key, + children, + ...moduleGroup(children, modules) + }; + } + }); + } + if (groupModulesByPath || groupModulesByExtension) { + groupConfigs.push({ + getKeys: module => { + if (!module.name) return; + const resource = parseResource(module.name.split("!").pop()).path; + const dataUrl = /^data:[^,;]+/.exec(resource); + if (dataUrl) return [dataUrl[0]]; + const extensionMatch = + groupModulesByExtension && GROUP_EXTENSION_REGEXP.exec(resource); + const extension = extensionMatch ? extensionMatch[1] : ""; + const pathMatch = + groupModulesByPath && GROUP_PATH_REGEXP.exec(resource); + const path = pathMatch ? pathMatch[1].split(/[/\\]/) : []; + const keys = []; + if (groupModulesByPath) { + if (extension) + keys.push( + path.length + ? `${path.join("/")}/*${extension}` + : `*${extension}` + ); + while (path.length > 0) { + keys.push(path.join("/") + "/"); + path.pop(); } - addSizeTo(leftSize, group.nodes[pos].size); - subtractSizeFrom(rightSize, group.nodes[pos].size); - pos++; - } - if (best < 0) { - // This can't happen - // but if that assumption is wrong - // fallback to a big group - result.push(group); - continue; + } else { + if (extension) keys.push(`*${extension}`); } - left = best; - right = best - 1; + return keys; + }, + createGroup: (key, children, modules) => { + const isDataUrl = key.startsWith("data:"); + return { + type: isDataUrl + ? "modules by mime type" + : groupModulesByPath + ? "modules by path" + : "modules by extension", + name: isDataUrl ? key.slice(/* 'data:'.length */ 5) : key, + children, + ...moduleGroup(children, modules) + }; } - - // create two new groups for left and right area - // and queue them up - const rightNodes = [group.nodes[right + 1]]; - /** @type {number[]} */ - const rightSimilarities = []; - for (let i = right + 2; i < group.nodes.length; i++) { - rightSimilarities.push(group.similarities[i - 1]); - rightNodes.push(group.nodes[i]); + }); + } + }, + excludeModules: (groupConfigs, context, { excludeModules }) => { + groupConfigs.push({ + getKeys: module => { + const name = module.name; + if (name) { + const excluded = excludeModules.some(fn => fn(name, module, type)); + if (excluded) return ["1"]; } - queue.push(new Group(rightNodes, rightSimilarities)); + }, + getOptions: () => ({ + groupChildren: false, + force: true + }), + createGroup: (key, children, modules) => ({ + type: "hidden modules", + filteredChildren: children.length, + ...moduleGroup(children, modules) + }) + }); + } +}); - const leftNodes = [group.nodes[0]]; - /** @type {number[]} */ - const leftSimilarities = []; - for (let i = 1; i < left; i++) { - leftSimilarities.push(group.similarities[i - 1]); - leftNodes.push(group.nodes[i]); +/** @type {Record void>>} */ +const RESULT_GROUPERS = { + "compilation.assets": ASSETS_GROUPERS, + "asset.related": ASSETS_GROUPERS, + "compilation.modules": MODULES_GROUPERS("module"), + "chunk.modules": MODULES_GROUPERS("chunk"), + "chunk.rootModules": MODULES_GROUPERS("root-of-chunk"), + "module.modules": MODULES_GROUPERS("nested"), + "module.reasons": { + groupReasonsByOrigin: groupConfigs => { + groupConfigs.push({ + getKeys: reason => { + return [reason.module]; + }, + createGroup: (key, children, reasons) => { + return { + type: "from origin", + module: key, + children, + ...reasonGroup(children, reasons) + }; } - queue.push(new Group(leftNodes, leftSimilarities)); - } + }); } } +}; - // lexically ordering - result.sort((a, b) => { - if (a.nodes[0].key < b.nodes[0].key) return -1; - if (a.nodes[0].key > b.nodes[0].key) return 1; - return 0; - }); - - // give every group a name - const usedNames = new Set(); - for (let i = 0; i < result.length; i++) { - const group = result[i]; - if (group.nodes.length === 1) { - group.key = group.nodes[0].key; - } else { - const first = group.nodes[0]; - const last = group.nodes[group.nodes.length - 1]; - const name = getName(first.key, last.key, usedNames); - group.key = name; - } +// remove a prefixed "!" that can be specified to reverse sort order +const normalizeFieldKey = field => { + if (field[0] === "!") { + return field.substr(1); } - - // return the results - return result.map(group => { - /** @type {GroupedItems} */ - return { - key: group.key, - items: group.nodes.map(node => node.item), - size: group.size - }; - }); + return field; }; - -/***/ }), - -/***/ 11850: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sam Chen @chenxsan -*/ - - +// if a field is prefixed by a "!" reverse sort order +const sortOrderRegular = field => { + if (field[0] === "!") { + return false; + } + return true; +}; /** - * @param {string} urlAndGlobal the script request - * @returns {string[]} script url and its global variable + * @param {string} field field name + * @returns {function(Object, Object): number} comparators */ -module.exports = function extractUrlAndGlobal(urlAndGlobal) { - const index = urlAndGlobal.indexOf("@"); - if (index <= 0 || index === urlAndGlobal.length - 1) { - throw new Error(`Invalid request "${urlAndGlobal}"`); +const sortByField = field => { + if (!field) { + /** + * @param {any} a first + * @param {any} b second + * @returns {-1|0|1} zero + */ + const noSort = (a, b) => 0; + return noSort; } - return [urlAndGlobal.substring(index + 1), urlAndGlobal.substring(0, index)]; -}; + const fieldKey = normalizeFieldKey(field); -/***/ }), - -/***/ 6261: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + let sortFn = compareSelect(m => m[fieldKey], compareIds); + // if a field is prefixed with a "!" the sort is reversed! + const sortIsRegular = sortOrderRegular(field); + if (!sortIsRegular) { + const oldSortFn = sortFn; + sortFn = (a, b) => oldSortFn(b, a); + } -const NO_MARKER = 0; -const IN_PROGRESS_MARKER = 1; -const DONE_MARKER = 2; -const DONE_MAYBE_ROOT_CYCLE_MARKER = 3; -const DONE_AND_ROOT_MARKER = 4; + return sortFn; +}; -/** - * @template T - */ -class Node { - /** - * @param {T} item the value of the node - */ - constructor(item) { - this.item = item; - /** @type {Set>} */ - this.dependencies = new Set(); - this.marker = NO_MARKER; - /** @type {Cycle | undefined} */ - this.cycle = undefined; - this.incoming = 0; +const ASSET_SORTERS = { + /** @type {(comparators: Function[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void} */ + assetsSort: (comparators, context, { assetsSort }) => { + comparators.push(sortByField(assetsSort)); + }, + _: comparators => { + comparators.push(compareSelect(a => a.name, compareIds)); } -} +}; + +/** @type {Record void>>} */ +const RESULT_SORTERS = { + "compilation.chunks": { + chunksSort: (comparators, context, { chunksSort }) => { + comparators.push(sortByField(chunksSort)); + } + }, + "compilation.modules": { + modulesSort: (comparators, context, { modulesSort }) => { + comparators.push(sortByField(modulesSort)); + } + }, + "chunk.modules": { + chunkModulesSort: (comparators, context, { chunkModulesSort }) => { + comparators.push(sortByField(chunkModulesSort)); + } + }, + "module.modules": { + nestedModulesSort: (comparators, context, { nestedModulesSort }) => { + comparators.push(sortByField(nestedModulesSort)); + } + }, + "compilation.assets": ASSET_SORTERS, + "asset.related": ASSET_SORTERS +}; /** - * @template T + * @param {Record>} config the config see above + * @param {NormalizedStatsOptions} options stats options + * @param {function(string, Function): void} fn handler function called for every active line in config + * @returns {void} */ -class Cycle { - constructor() { - /** @type {Set>} */ - this.nodes = new Set(); +const iterateConfig = (config, options, fn) => { + for (const hookFor of Object.keys(config)) { + const subConfig = config[hookFor]; + for (const option of Object.keys(subConfig)) { + if (option !== "_") { + if (option.startsWith("!")) { + if (options[option.slice(1)]) continue; + } else { + const value = options[option]; + if ( + value === false || + value === undefined || + (Array.isArray(value) && value.length === 0) + ) + continue; + } + } + fn(hookFor, subConfig[option]); + } } -} +}; -/** - * @template T - * @typedef {Object} StackEntry - * @property {Node} node - * @property {Node[]} openEdges - */ +/** @type {Record} */ +const ITEM_NAMES = { + "compilation.children[]": "compilation", + "compilation.modules[]": "module", + "compilation.entrypoints[]": "chunkGroup", + "compilation.namedChunkGroups[]": "chunkGroup", + "compilation.errors[]": "error", + "compilation.warnings[]": "warning", + "chunk.modules[]": "module", + "chunk.rootModules[]": "module", + "chunk.origins[]": "chunkOrigin", + "compilation.chunks[]": "chunk", + "compilation.assets[]": "asset", + "asset.related[]": "asset", + "module.issuerPath[]": "moduleIssuer", + "module.reasons[]": "moduleReason", + "module.modules[]": "module", + "module.children[]": "module", + "moduleTrace[]": "moduleTraceItem", + "moduleTraceItem.dependencies[]": "moduleTraceDependency" +}; /** - * @template T - * @param {Iterable} items list of items - * @param {function(T): Iterable} getDependencies function to get dependencies of an item (items that are not in list are ignored) - * @returns {Iterable} graph roots of the items + * @param {Object[]} items items to be merged + * @returns {Object} an object */ -module.exports = (items, getDependencies) => { - /** @type {Map>} */ - const itemToNode = new Map(); +const mergeToObject = items => { + const obj = Object.create(null); for (const item of items) { - const node = new Node(item); - itemToNode.set(item, node); - } - - // early exit when there is only a single item - if (itemToNode.size <= 1) return items; - - // grab all the dependencies - for (const node of itemToNode.values()) { - for (const dep of getDependencies(node.item)) { - const depNode = itemToNode.get(dep); - if (depNode !== undefined) { - node.dependencies.add(depNode); - } - } + obj[item.name] = item; } + return obj; +}; - // Set of current root modules - // items will be removed if a new reference to it has been found - /** @type {Set>} */ - const roots = new Set(); - - // Set of current cycles without references to it - // cycles will be removed if a new reference to it has been found - // that is not part of the cycle - /** @type {Set>} */ - const rootCycles = new Set(); - - // For all non-marked nodes - for (const selectedNode of itemToNode.values()) { - if (selectedNode.marker === NO_MARKER) { - // deep-walk all referenced modules - // in a non-recursive way - - // start by entering the selected node - selectedNode.marker = IN_PROGRESS_MARKER; - - // keep a stack to avoid recursive walk - /** @type {StackEntry[]} */ - const stack = [ - { - node: selectedNode, - openEdges: Array.from(selectedNode.dependencies) - } - ]; - - // process the top item until stack is empty - while (stack.length > 0) { - const topOfStack = stack[stack.length - 1]; +/** @type {Record any>} */ +const MERGER = { + "compilation.entrypoints": mergeToObject, + "compilation.namedChunkGroups": mergeToObject +}; - // Are there still edges unprocessed in the current node? - if (topOfStack.openEdges.length > 0) { - // Process one dependency - const dependency = topOfStack.openEdges.pop(); - switch (dependency.marker) { - case NO_MARKER: - // dependency has not be visited yet - // mark it as in-progress and recurse - stack.push({ - node: dependency, - openEdges: Array.from(dependency.dependencies) - }); - dependency.marker = IN_PROGRESS_MARKER; - break; - case IN_PROGRESS_MARKER: { - // It's a in-progress cycle - let cycle = dependency.cycle; - if (!cycle) { - cycle = new Cycle(); - cycle.nodes.add(dependency); - dependency.cycle = cycle; - } - // set cycle property for each node in the cycle - // if nodes are already part of a cycle - // we merge the cycles to a shared cycle - for ( - let i = stack.length - 1; - stack[i].node !== dependency; - i-- - ) { - const node = stack[i].node; - if (node.cycle) { - if (node.cycle !== cycle) { - // merge cycles - for (const cycleNode of node.cycle.nodes) { - cycleNode.cycle = cycle; - cycle.nodes.add(cycleNode); - } +class DefaultStatsFactoryPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap("DefaultStatsFactoryPlugin", compilation => { + compilation.hooks.statsFactory.tap( + "DefaultStatsFactoryPlugin", + (stats, options, context) => { + iterateConfig(SIMPLE_EXTRACTORS, options, (hookFor, fn) => { + stats.hooks.extract + .for(hookFor) + .tap("DefaultStatsFactoryPlugin", (obj, data, ctx) => + fn(obj, data, ctx, options, stats) + ); + }); + iterateConfig(FILTER, options, (hookFor, fn) => { + stats.hooks.filter + .for(hookFor) + .tap("DefaultStatsFactoryPlugin", (item, ctx, idx, i) => + fn(item, ctx, options, idx, i) + ); + }); + iterateConfig(FILTER_RESULTS, options, (hookFor, fn) => { + stats.hooks.filterResults + .for(hookFor) + .tap("DefaultStatsFactoryPlugin", (item, ctx, idx, i) => + fn(item, ctx, options, idx, i) + ); + }); + iterateConfig(SORTERS, options, (hookFor, fn) => { + stats.hooks.sort + .for(hookFor) + .tap("DefaultStatsFactoryPlugin", (comparators, ctx) => + fn(comparators, ctx, options) + ); + }); + iterateConfig(RESULT_SORTERS, options, (hookFor, fn) => { + stats.hooks.sortResults + .for(hookFor) + .tap("DefaultStatsFactoryPlugin", (comparators, ctx) => + fn(comparators, ctx, options) + ); + }); + iterateConfig(RESULT_GROUPERS, options, (hookFor, fn) => { + stats.hooks.groupResults + .for(hookFor) + .tap("DefaultStatsFactoryPlugin", (groupConfigs, ctx) => + fn(groupConfigs, ctx, options) + ); + }); + for (const key of Object.keys(ITEM_NAMES)) { + const itemName = ITEM_NAMES[key]; + stats.hooks.getItemName + .for(key) + .tap("DefaultStatsFactoryPlugin", () => itemName); + } + for (const key of Object.keys(MERGER)) { + const merger = MERGER[key]; + stats.hooks.merge.for(key).tap("DefaultStatsFactoryPlugin", merger); + } + if (options.children) { + if (Array.isArray(options.children)) { + stats.hooks.getItemFactory + .for("compilation.children[].compilation") + .tap("DefaultStatsFactoryPlugin", (comp, { _index: idx }) => { + if (idx < options.children.length) { + return compilation.createStatsFactory( + compilation.createStatsOptions( + options.children[idx], + context + ) + ); } - } else { - node.cycle = cycle; - cycle.nodes.add(node); - } - } - // don't recurse into dependencies - // these are already on the stack - break; + }); + } else if (options.children !== true) { + const childFactory = compilation.createStatsFactory( + compilation.createStatsOptions(options.children, context) + ); + stats.hooks.getItemFactory + .for("compilation.children[].compilation") + .tap("DefaultStatsFactoryPlugin", () => { + return childFactory; + }); } - case DONE_AND_ROOT_MARKER: - // This node has be visited yet and is currently a root node - // But as this is a new reference to the node - // it's not really a root - // so we have to convert it to a normal node - dependency.marker = DONE_MARKER; - roots.delete(dependency); - break; - case DONE_MAYBE_ROOT_CYCLE_MARKER: - // This node has be visited yet and - // is maybe currently part of a completed root cycle - // we found a new reference to the cycle - // so it's not really a root cycle - // remove the cycle from the root cycles - // and convert it to a normal node - rootCycles.delete(dependency.cycle); - dependency.marker = DONE_MARKER; - break; - // DONE_MARKER: nothing to do, don't recurse into dependencies - } - } else { - // All dependencies of the current node has been visited - // we leave the node - stack.pop(); - topOfStack.node.marker = DONE_MARKER; - } - } - const cycle = selectedNode.cycle; - if (cycle) { - for (const node of cycle.nodes) { - node.marker = DONE_MAYBE_ROOT_CYCLE_MARKER; - } - rootCycles.add(cycle); - } else { - selectedNode.marker = DONE_AND_ROOT_MARKER; - roots.add(selectedNode); - } - } - } - - // Extract roots from root cycles - // We take the nodes with most incoming edges - // inside of the cycle - for (const cycle of rootCycles) { - let max = 0; - /** @type {Set>} */ - const cycleRoots = new Set(); - const nodes = cycle.nodes; - for (const node of nodes) { - for (const dep of node.dependencies) { - if (nodes.has(dep)) { - dep.incoming++; - if (dep.incoming < max) continue; - if (dep.incoming > max) { - cycleRoots.clear(); - max = dep.incoming; } - cycleRoots.add(dep); } - } - } - for (const cycleRoot of cycleRoots) { - roots.add(cycleRoot); - } - } - - // When roots were found, return them - if (roots.size > 0) { - return Array.from(roots, r => r.item); - } else { - throw new Error("Implementation of findGraphRoots is broken"); + ); + }); } -}; +} +module.exports = DefaultStatsFactoryPlugin; /***/ }), -/***/ 17139: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 55442: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -126074,417 +131572,330 @@ module.exports = (items, getDependencies) => { -const path = __webpack_require__(71017); - -/** @typedef {import("../../declarations/WebpackOptions").WatchOptions} WatchOptions */ -/** @typedef {import("../FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ - -/** - * @typedef {Object} IStats - * @property {() => boolean} isFile - * @property {() => boolean} isDirectory - * @property {() => boolean} isBlockDevice - * @property {() => boolean} isCharacterDevice - * @property {() => boolean} isSymbolicLink - * @property {() => boolean} isFIFO - * @property {() => boolean} isSocket - * @property {number | bigint} dev - * @property {number | bigint} ino - * @property {number | bigint} mode - * @property {number | bigint} nlink - * @property {number | bigint} uid - * @property {number | bigint} gid - * @property {number | bigint} rdev - * @property {number | bigint} size - * @property {number | bigint} blksize - * @property {number | bigint} blocks - * @property {number | bigint} atimeMs - * @property {number | bigint} mtimeMs - * @property {number | bigint} ctimeMs - * @property {number | bigint} birthtimeMs - * @property {Date} atime - * @property {Date} mtime - * @property {Date} ctime - * @property {Date} birthtime - */ - -/** - * @typedef {Object} IDirent - * @property {() => boolean} isFile - * @property {() => boolean} isDirectory - * @property {() => boolean} isBlockDevice - * @property {() => boolean} isCharacterDevice - * @property {() => boolean} isSymbolicLink - * @property {() => boolean} isFIFO - * @property {() => boolean} isSocket - * @property {string | Buffer} name - */ - -/** @typedef {function((NodeJS.ErrnoException | null)=): void} Callback */ -/** @typedef {function((NodeJS.ErrnoException | null)=, Buffer=): void} BufferCallback */ -/** @typedef {function((NodeJS.ErrnoException | null)=, Buffer|string=): void} BufferOrStringCallback */ -/** @typedef {function((NodeJS.ErrnoException | null)=, (string | Buffer)[] | IDirent[]=): void} DirentArrayCallback */ -/** @typedef {function((NodeJS.ErrnoException | null)=, string=): void} StringCallback */ -/** @typedef {function((NodeJS.ErrnoException | null)=, number=): void} NumberCallback */ -/** @typedef {function((NodeJS.ErrnoException | null)=, IStats=): void} StatsCallback */ -/** @typedef {function((NodeJS.ErrnoException | Error | null)=, any=): void} ReadJsonCallback */ -/** @typedef {function((NodeJS.ErrnoException | Error | null)=, IStats|string=): void} LstatReadlinkAbsoluteCallback */ - -/** - * @typedef {Object} WatcherInfo - * @property {Set} changes get current aggregated changes that have not yet send to callback - * @property {Set} removals get current aggregated removals that have not yet send to callback - * @property {Map} fileTimeInfoEntries get info about files - * @property {Map} contextTimeInfoEntries get info about directories - */ - -// TODO webpack 6 deprecate missing getInfo -/** - * @typedef {Object} Watcher - * @property {function(): void} close closes the watcher and all underlying file watchers - * @property {function(): void} pause closes the watcher, but keeps underlying file watchers alive until the next watch call - * @property {function(): Set=} getAggregatedChanges get current aggregated changes that have not yet send to callback - * @property {function(): Set=} getAggregatedRemovals get current aggregated removals that have not yet send to callback - * @property {function(): Map} getFileTimeInfoEntries get info about files - * @property {function(): Map} getContextTimeInfoEntries get info about directories - * @property {function(): WatcherInfo=} getInfo get info about timestamps and changes - */ - -/** - * @callback WatchMethod - * @param {Iterable} files watched files - * @param {Iterable} directories watched directories - * @param {Iterable} missing watched exitance entries - * @param {number} startTime timestamp of start time - * @param {WatchOptions} options options object - * @param {function(Error=, Map, Map, Set, Set): void} callback aggregated callback - * @param {function(string, number): void} callbackUndelayed callback when the first change was detected - * @returns {Watcher} a watcher - */ - -// TODO webpack 6 make optional methods required - -/** - * @typedef {Object} OutputFileSystem - * @property {function(string, Buffer|string, Callback): void} writeFile - * @property {function(string, Callback): void} mkdir - * @property {function(string, DirentArrayCallback): void=} readdir - * @property {function(string, Callback): void=} rmdir - * @property {function(string, Callback): void=} unlink - * @property {function(string, StatsCallback): void} stat - * @property {function(string, StatsCallback): void=} lstat - * @property {function(string, BufferOrStringCallback): void} readFile - * @property {(function(string, string): string)=} join - * @property {(function(string, string): string)=} relative - * @property {(function(string): string)=} dirname - */ +const RequestShortener = __webpack_require__(73406); -/** - * @typedef {Object} InputFileSystem - * @property {function(string, BufferOrStringCallback): void} readFile - * @property {(function(string, ReadJsonCallback): void)=} readJson - * @property {function(string, BufferOrStringCallback): void} readlink - * @property {function(string, DirentArrayCallback): void} readdir - * @property {function(string, StatsCallback): void} stat - * @property {function(string, StatsCallback): void=} lstat - * @property {(function(string, BufferOrStringCallback): void)=} realpath - * @property {(function(string=): void)=} purge - * @property {(function(string, string): string)=} join - * @property {(function(string, string): string)=} relative - * @property {(function(string): string)=} dirname - */ +/** @typedef {import("../../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").CreateStatsOptionsContext} CreateStatsOptionsContext */ +/** @typedef {import("../Compiler")} Compiler */ -/** - * @typedef {Object} WatchFileSystem - * @property {WatchMethod} watch - */ +const applyDefaults = (options, defaults) => { + for (const key of Object.keys(defaults)) { + if (typeof options[key] === "undefined") { + options[key] = defaults[key]; + } + } +}; -/** - * @typedef {Object} IntermediateFileSystemExtras - * @property {function(string): void} mkdirSync - * @property {function(string): NodeJS.WritableStream} createWriteStream - * @property {function(string, string, NumberCallback): void} open - * @property {function(number, Buffer, number, number, number, NumberCallback): void} read - * @property {function(number, Callback): void} close - * @property {function(string, string, Callback): void} rename - */ +const NAMED_PRESETS = { + verbose: { + hash: true, + builtAt: true, + relatedAssets: true, + entrypoints: true, + chunkGroups: true, + ids: true, + modules: false, + chunks: true, + chunkRelations: true, + chunkModules: true, + dependentModules: true, + chunkOrigins: true, + depth: true, + env: true, + reasons: true, + usedExports: true, + providedExports: true, + optimizationBailout: true, + errorDetails: true, + errorStack: true, + publicPath: true, + logging: "verbose", + orphanModules: true, + runtimeModules: true, + exclude: false, + modulesSpace: Infinity, + chunkModulesSpace: Infinity, + assetsSpace: Infinity, + reasonsSpace: Infinity, + children: true + }, + detailed: { + hash: true, + builtAt: true, + relatedAssets: true, + entrypoints: true, + chunkGroups: true, + ids: true, + chunks: true, + chunkRelations: true, + chunkModules: false, + chunkOrigins: true, + depth: true, + usedExports: true, + providedExports: true, + optimizationBailout: true, + errorDetails: true, + publicPath: true, + logging: true, + runtimeModules: true, + exclude: false, + modulesSpace: 1000, + assetsSpace: 1000, + reasonsSpace: 1000 + }, + minimal: { + all: false, + version: true, + timings: true, + modules: true, + modulesSpace: 0, + assets: true, + assetsSpace: 0, + errors: true, + errorsCount: true, + warnings: true, + warningsCount: true, + logging: "warn" + }, + "errors-only": { + all: false, + errors: true, + errorsCount: true, + moduleTrace: true, + logging: "error" + }, + "errors-warnings": { + all: false, + errors: true, + errorsCount: true, + warnings: true, + warningsCount: true, + logging: "warn" + }, + summary: { + all: false, + version: true, + errorsCount: true, + warningsCount: true + }, + none: { + all: false + } +}; -/** @typedef {InputFileSystem & OutputFileSystem & IntermediateFileSystemExtras} IntermediateFileSystem */ +const NORMAL_ON = ({ all }) => all !== false; +const NORMAL_OFF = ({ all }) => all === true; +const ON_FOR_TO_STRING = ({ all }, { forToString }) => + forToString ? all !== false : all === true; +const OFF_FOR_TO_STRING = ({ all }, { forToString }) => + forToString ? all === true : all !== false; +const AUTO_FOR_TO_STRING = ({ all }, { forToString }) => { + if (all === false) return false; + if (all === true) return true; + if (forToString) return "auto"; + return true; +}; -/** - * - * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system - * @param {string} rootPath the root path - * @param {string} targetPath the target path - * @returns {string} location of targetPath relative to rootPath - */ -const relative = (fs, rootPath, targetPath) => { - if (fs && fs.relative) { - return fs.relative(rootPath, targetPath); - } else if (path.posix.isAbsolute(rootPath)) { - return path.posix.relative(rootPath, targetPath); - } else if (path.win32.isAbsolute(rootPath)) { - return path.win32.relative(rootPath, targetPath); - } else { - throw new Error( - `${rootPath} is neither a posix nor a windows path, and there is no 'relative' method defined in the file system` - ); - } +/** @type {Record any>} */ +const DEFAULTS = { + context: (options, context, compilation) => compilation.compiler.context, + requestShortener: (options, context, compilation) => + compilation.compiler.context === options.context + ? compilation.requestShortener + : new RequestShortener(options.context, compilation.compiler.root), + performance: NORMAL_ON, + hash: OFF_FOR_TO_STRING, + env: NORMAL_OFF, + version: NORMAL_ON, + timings: NORMAL_ON, + builtAt: OFF_FOR_TO_STRING, + assets: NORMAL_ON, + entrypoints: AUTO_FOR_TO_STRING, + chunkGroups: OFF_FOR_TO_STRING, + chunkGroupAuxiliary: OFF_FOR_TO_STRING, + chunkGroupChildren: OFF_FOR_TO_STRING, + chunkGroupMaxAssets: (o, { forToString }) => (forToString ? 5 : Infinity), + chunks: OFF_FOR_TO_STRING, + chunkRelations: OFF_FOR_TO_STRING, + chunkModules: ({ all, modules }) => { + if (all === false) return false; + if (all === true) return true; + if (modules) return false; + return true; + }, + dependentModules: OFF_FOR_TO_STRING, + chunkOrigins: OFF_FOR_TO_STRING, + ids: OFF_FOR_TO_STRING, + modules: ({ all, chunks, chunkModules }, { forToString }) => { + if (all === false) return false; + if (all === true) return true; + if (forToString && chunks && chunkModules) return false; + return true; + }, + nestedModules: OFF_FOR_TO_STRING, + groupModulesByType: ON_FOR_TO_STRING, + groupModulesByCacheStatus: ON_FOR_TO_STRING, + groupModulesByLayer: ON_FOR_TO_STRING, + groupModulesByAttributes: ON_FOR_TO_STRING, + groupModulesByPath: ON_FOR_TO_STRING, + groupModulesByExtension: ON_FOR_TO_STRING, + modulesSpace: (o, { forToString }) => (forToString ? 15 : Infinity), + chunkModulesSpace: (o, { forToString }) => (forToString ? 10 : Infinity), + nestedModulesSpace: (o, { forToString }) => (forToString ? 10 : Infinity), + relatedAssets: OFF_FOR_TO_STRING, + groupAssetsByEmitStatus: ON_FOR_TO_STRING, + groupAssetsByInfo: ON_FOR_TO_STRING, + groupAssetsByPath: ON_FOR_TO_STRING, + groupAssetsByExtension: ON_FOR_TO_STRING, + groupAssetsByChunk: ON_FOR_TO_STRING, + assetsSpace: (o, { forToString }) => (forToString ? 15 : Infinity), + orphanModules: OFF_FOR_TO_STRING, + runtimeModules: ({ all, runtime }, { forToString }) => + runtime !== undefined + ? runtime + : forToString + ? all === true + : all !== false, + cachedModules: ({ all, cached }, { forToString }) => + cached !== undefined ? cached : forToString ? all === true : all !== false, + moduleAssets: OFF_FOR_TO_STRING, + depth: OFF_FOR_TO_STRING, + cachedAssets: OFF_FOR_TO_STRING, + reasons: OFF_FOR_TO_STRING, + reasonsSpace: (o, { forToString }) => (forToString ? 15 : Infinity), + groupReasonsByOrigin: ON_FOR_TO_STRING, + usedExports: OFF_FOR_TO_STRING, + providedExports: OFF_FOR_TO_STRING, + optimizationBailout: OFF_FOR_TO_STRING, + children: OFF_FOR_TO_STRING, + source: NORMAL_OFF, + moduleTrace: NORMAL_ON, + errors: NORMAL_ON, + errorsCount: NORMAL_ON, + errorDetails: AUTO_FOR_TO_STRING, + errorStack: OFF_FOR_TO_STRING, + warnings: NORMAL_ON, + warningsCount: NORMAL_ON, + publicPath: OFF_FOR_TO_STRING, + logging: ({ all }, { forToString }) => + forToString && all !== false ? "info" : false, + loggingDebug: () => [], + loggingTrace: OFF_FOR_TO_STRING, + excludeModules: () => [], + excludeAssets: () => [], + modulesSort: () => "depth", + chunkModulesSort: () => "name", + nestedModulesSort: () => false, + chunksSort: () => false, + assetsSort: () => "!size", + outputPath: OFF_FOR_TO_STRING, + colors: () => false }; -exports.relative = relative; -/** - * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system - * @param {string} rootPath a path - * @param {string} filename a filename - * @returns {string} the joined path - */ -const join = (fs, rootPath, filename) => { - if (fs && fs.join) { - return fs.join(rootPath, filename); - } else if (path.posix.isAbsolute(rootPath)) { - return path.posix.join(rootPath, filename); - } else if (path.win32.isAbsolute(rootPath)) { - return path.win32.join(rootPath, filename); - } else { - throw new Error( - `${rootPath} is neither a posix nor a windows path, and there is no 'join' method defined in the file system` +const normalizeFilter = item => { + if (typeof item === "string") { + const regExp = new RegExp( + `[\\\\/]${item.replace( + // eslint-disable-next-line no-useless-escape + /[-[\]{}()*+?.\\^$|]/g, + "\\$&" + )}([\\\\/]|$|!|\\?)` ); + return ident => regExp.test(ident); } -}; -exports.join = join; - -/** - * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system - * @param {string} absPath an absolute path - * @returns {string} the parent directory of the absolute path - */ -const dirname = (fs, absPath) => { - if (fs && fs.dirname) { - return fs.dirname(absPath); - } else if (path.posix.isAbsolute(absPath)) { - return path.posix.dirname(absPath); - } else if (path.win32.isAbsolute(absPath)) { - return path.win32.dirname(absPath); - } else { - throw new Error( - `${absPath} is neither a posix nor a windows path, and there is no 'dirname' method defined in the file system` - ); + if (item && typeof item === "object" && typeof item.test === "function") { + return ident => item.test(ident); + } + if (typeof item === "function") { + return item; + } + if (typeof item === "boolean") { + return () => item; } }; -exports.dirname = dirname; -/** - * @param {OutputFileSystem} fs a file system - * @param {string} p an absolute path - * @param {function(Error=): void} callback callback function for the error - * @returns {void} - */ -const mkdirp = (fs, p, callback) => { - fs.mkdir(p, err => { - if (err) { - if (err.code === "ENOENT") { - const dir = dirname(fs, p); - if (dir === p) { - callback(err); - return; - } - mkdirp(fs, dir, err => { - if (err) { - callback(err); - return; - } - fs.mkdir(p, err => { - if (err) { - if (err.code === "EEXIST") { - callback(); - return; - } - callback(err); - return; - } - callback(); - }); - }); - return; - } else if (err.code === "EEXIST") { - callback(); - return; - } - callback(err); - return; +const NORMALIZER = { + excludeModules: value => { + if (!Array.isArray(value)) { + value = value ? [value] : []; } - callback(); - }); -}; -exports.mkdirp = mkdirp; - -/** - * @param {IntermediateFileSystem} fs a file system - * @param {string} p an absolute path - * @returns {void} - */ -const mkdirpSync = (fs, p) => { - try { - fs.mkdirSync(p); - } catch (err) { - if (err) { - if (err.code === "ENOENT") { - const dir = dirname(fs, p); - if (dir === p) { - throw err; - } - mkdirpSync(fs, dir); - fs.mkdirSync(p); - return; - } else if (err.code === "EEXIST") { - return; - } - throw err; + return value.map(normalizeFilter); + }, + excludeAssets: value => { + if (!Array.isArray(value)) { + value = value ? [value] : []; } - } -}; -exports.mkdirpSync = mkdirpSync; - -/** - * @param {InputFileSystem} fs a file system - * @param {string} p an absolute path - * @param {ReadJsonCallback} callback callback - * @returns {void} - */ -const readJson = (fs, p, callback) => { - if ("readJson" in fs) return fs.readJson(p, callback); - fs.readFile(p, (err, buf) => { - if (err) return callback(err); - let data; - try { - data = JSON.parse(buf.toString("utf-8")); - } catch (e) { - return callback(e); + return value.map(normalizeFilter); + }, + warningsFilter: value => { + if (!Array.isArray(value)) { + value = value ? [value] : []; } - return callback(null, data); - }); -}; -exports.readJson = readJson; - -/** - * @param {InputFileSystem} fs a file system - * @param {string} p an absolute path - * @param {ReadJsonCallback} callback callback - * @returns {void} - */ -const lstatReadlinkAbsolute = (fs, p, callback) => { - let i = 3; - const doReadLink = () => { - fs.readlink(p, (err, target) => { - if (err && --i > 0) { - // It might was just changed from symlink to file - // we retry 2 times to catch this case before throwing the error - return doStat(); + return value.map(filter => { + if (typeof filter === "string") { + return (warning, warningString) => warningString.includes(filter); } - if (err || !target) return doStat(); - const value = target.toString(); - callback(null, join(fs, dirname(fs, p), value)); - }); - }; - const doStat = () => { - if ("lstat" in fs) { - return fs.lstat(p, (err, stats) => { - if (err) return callback(err); - if (stats.isSymbolicLink()) { - return doReadLink(); - } - callback(null, stats); - }); - } else { - return fs.stat(p, callback); - } - }; - if ("lstat" in fs) return doStat(); - doReadLink(); -}; -exports.lstatReadlinkAbsolute = lstatReadlinkAbsolute; - - -/***/ }), - -/***/ 59461: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Hash = __webpack_require__(36692); -const MAX_SHORT_STRING = (__webpack_require__(1842).MAX_SHORT_STRING); - -class BatchedHash extends Hash { - constructor(hash) { - super(); - this.string = undefined; - this.encoding = undefined; - this.hash = hash; - } - - /** - * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} - * @param {string|Buffer} data data - * @param {string=} inputEncoding data encoding - * @returns {this} updated hash - */ - update(data, inputEncoding) { - if (this.string !== undefined) { - if ( - typeof data === "string" && - inputEncoding === this.encoding && - this.string.length + data.length < MAX_SHORT_STRING - ) { - this.string += data; - return this; + if (filter instanceof RegExp) { + return (warning, warningString) => filter.test(warningString); } - this.hash.update(this.string, this.encoding); - this.string = undefined; - } - if (typeof data === "string") { - if ( - data.length < MAX_SHORT_STRING && - // base64 encoding is not valid since it may contain padding chars - (!inputEncoding || !inputEncoding.startsWith("ba")) - ) { - this.string = data; - this.encoding = inputEncoding; - } else { - this.hash.update(data, inputEncoding); + if (typeof filter === "function") { + return filter; } - } else { - this.hash.update(data); + throw new Error( + `Can only filter warnings with Strings or RegExps. (Given: ${filter})` + ); + }); + }, + logging: value => { + if (value === true) value = "log"; + return value; + }, + loggingDebug: value => { + if (!Array.isArray(value)) { + value = value ? [value] : []; } - return this; + return value.map(normalizeFilter); } +}; +class DefaultStatsPresetPlugin { /** - * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} - * @param {string=} encoding encoding of the return value - * @returns {string|Buffer} digest + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - digest(encoding) { - if (this.string !== undefined) { - this.hash.update(this.string, this.encoding); - } - return this.hash.digest(encoding); + apply(compiler) { + compiler.hooks.compilation.tap("DefaultStatsPresetPlugin", compilation => { + for (const key of Object.keys(NAMED_PRESETS)) { + const defaults = NAMED_PRESETS[key]; + compilation.hooks.statsPreset + .for(key) + .tap("DefaultStatsPresetPlugin", (options, context) => { + applyDefaults(options, defaults); + }); + } + compilation.hooks.statsNormalize.tap( + "DefaultStatsPresetPlugin", + (options, context) => { + for (const key of Object.keys(DEFAULTS)) { + if (options[key] === undefined) + options[key] = DEFAULTS[key](options, context, compilation); + } + for (const key of Object.keys(NORMALIZER)) { + options[key] = NORMALIZER[key](options[key]); + } + } + ); + }); } } - -module.exports = BatchedHash; +module.exports = DefaultStatsPresetPlugin; /***/ }), -/***/ 86884: +/***/ 58692: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -126495,587 +131906,1384 @@ module.exports = BatchedHash; -const create = __webpack_require__(1842); - -//#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1 -const md4 = new WebAssembly.Module( - Buffer.from( - // 2156 bytes - "AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqLEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvSCgEZfyMBIQUjAiECIwMhAyMEIQQDQCAAIAFLBEAgASgCJCISIAEoAiAiEyABKAIcIgkgASgCGCIIIAEoAhQiByABKAIQIg4gASgCDCIGIAEoAggiDyABKAIEIhAgASgCACIRIAMgBHMgAnEgBHMgBWpqQQN3IgogAiADc3EgA3MgBGpqQQd3IgsgAiAKc3EgAnMgA2pqQQt3IgwgCiALc3EgCnMgAmpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IgogDCANc3EgDHMgC2pqQQd3IgsgCiANc3EgDXMgDGpqQQt3IgwgCiALc3EgCnMgDWpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IhQgDCANc3EgDHMgC2pqQQd3IRUgASgCLCILIAEoAigiCiAMIA0gDSAUcyAVcXNqakELdyIWIBQgFXNxIBRzIA1qakETdyEXIAEoAjQiGCABKAIwIhkgFSAWcyAXcSAVcyAUampBA3ciFCAWIBdzcSAWcyAVampBB3chFSABKAI8Ig0gASgCOCIMIBQgF3MgFXEgF3MgFmpqQQt3IhYgFCAVc3EgFHMgF2pqQRN3IRcgEyAOIBEgFCAVIBZyIBdxIBUgFnFyampBmfOJ1AVqQQN3IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEFdyIVIBQgF3JxIBQgF3FyIBZqakGZ84nUBWpBCXchFiAPIBggEiAWIAcgFSAQIBQgGSAUIBVyIBZxIBQgFXFyIBdqakGZ84nUBWpBDXciFCAVIBZycSAVIBZxcmpqQZnzidQFakEDdyIVIBQgFnJxIBQgFnFyampBmfOJ1AVqQQV3IhcgFCAVcnEgFCAVcXJqakGZ84nUBWpBCXciFiAVIBdycSAVIBdxciAUampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEDdyEVIBEgBiAVIAwgFCAKIBYgCCAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFyAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIWIBUgF3JxIBUgF3FyampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXJqakGZ84nUBWpBA3ciFSALIBYgCSAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFiAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIXIA0gFSAWciAXcSAVIBZxciAUampBmfOJ1AVqQQ13IhRzIBZzampBodfn9gZqQQN3IREgByAIIA4gFCARIBcgESAUc3MgFmogE2pBodfn9gZqQQl3IhNzcyAXampBodfn9gZqQQt3Ig4gDyARIBMgDiARIA4gE3NzIBRqIBlqQaHX5/YGakEPdyIRc3NqakGh1+f2BmpBA3ciDyAOIA8gEXNzIBNqIApqQaHX5/YGakEJdyIKcyARc2pqQaHX5/YGakELdyIIIBAgDyAKIAggDCAPIAggCnNzIBFqakGh1+f2BmpBD3ciDHNzampBodfn9gZqQQN3Ig4gEiAIIAwgDnNzIApqakGh1+f2BmpBCXciCHMgDHNqakGh1+f2BmpBC3chByAFIAYgCCAHIBggDiAHIAhzcyAMampBodfn9gZqQQ93IgpzcyAOampBodfn9gZqQQN3IgZqIQUgDSAGIAkgByAGIAsgByAGIApzcyAIampBodfn9gZqQQl3IgdzIApzampBodfn9gZqQQt3IgYgB3NzIApqakGh1+f2BmpBD3cgAmohAiADIAZqIQMgBCAHaiEEIAFBQGshAQwBCwsgBSQBIAIkAiADJAMgBCQECw0AIAAQASAAIwBqJAAL/wQCA38BfiAAIwBqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=", - "base64" - ) -); -//#endregion +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("./StatsPrinter")} StatsPrinter */ +/** @typedef {import("./StatsPrinter").StatsPrinterContext} StatsPrinterContext */ -module.exports = create.bind(null, md4, [], 64, 32); +const DATA_URI_CONTENT_LENGTH = 16; +const plural = (n, singular, plural) => (n === 1 ? singular : plural); -/***/ }), +/** + * @param {Record} sizes sizes by source type + * @param {Object} options options + * @param {(number) => string=} options.formatSize size formatter + * @returns {string} text + */ +const printSizes = (sizes, { formatSize = n => `${n}` }) => { + const keys = Object.keys(sizes); + if (keys.length > 1) { + return keys.map(key => `${formatSize(sizes[key])} (${key})`).join(" "); + } else if (keys.length === 1) { + return formatSize(sizes[keys[0]]); + } +}; -/***/ 1842: -/***/ (function(module) { +const getResourceName = resource => { + const dataUrl = /^data:[^,]+,/.exec(resource); + if (!dataUrl) return resource; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const len = dataUrl[0].length + DATA_URI_CONTENT_LENGTH; + if (resource.length < len) return resource; + return `${resource.slice( + 0, + Math.min(resource.length - /* '..'.length */ 2, len) + )}..`; +}; +const getModuleName = name => { + const [, prefix, resource] = /^(.*!)?([^!]*)$/.exec(name); + return [prefix, getResourceName(resource)]; +}; +const mapLines = (str, fn) => str.split("\n").map(fn).join("\n"); -// 65536 is the size of a wasm memory page -// 64 is the maximum chunk size for every possible wasm hash implementation -// 4 is the maximum number of bytes per char for string encoding (max is utf-8) -// ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64 -const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3; +/** + * @param {number} n a number + * @returns {string} number as two digit string, leading 0 + */ +const twoDigit = n => (n >= 10 ? `${n}` : `0${n}`); -class WasmHash { - /** - * @param {WebAssembly.Instance} instance wasm instance - * @param {WebAssembly.Instance[]} instancesPool pool of instances - * @param {number} chunkSize size of data chunks passed to wasm - * @param {number} digestSize size of digest returned by wasm - */ - constructor(instance, instancesPool, chunkSize, digestSize) { - const exports = /** @type {any} */ (instance.exports); - exports.init(); - this.exports = exports; - this.mem = Buffer.from(exports.memory.buffer, 0, 65536); - this.buffered = 0; - this.instancesPool = instancesPool; - this.chunkSize = chunkSize; - this.digestSize = digestSize; - } +const isValidId = id => { + return typeof id === "number" || id; +}; - reset() { - this.buffered = 0; - this.exports.init(); - } +const moreCount = (list, count) => { + return list && list.length > 0 ? `+ ${count}` : `${count}`; +}; - /** - * @param {Buffer | string} data data - * @param {BufferEncoding=} encoding encoding - * @returns {this} itself - */ - update(data, encoding) { - if (typeof data === "string") { - while (data.length > MAX_SHORT_STRING) { - this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding); - data = data.slice(MAX_SHORT_STRING); +/** @type {Record string | void>} */ +const SIMPLE_PRINTERS = { + "compilation.summary!": ( + _, + { + type, + bold, + green, + red, + yellow, + formatDateTime, + formatTime, + compilation: { + name, + hash, + version, + time, + builtAt, + errorsCount, + warningsCount } - this._updateWithShortString(data, encoding); - return this; } - this._updateWithBuffer(data); - return this; - } - - /** - * @param {string} data data - * @param {BufferEncoding=} encoding encoding - * @returns {void} - */ - _updateWithShortString(data, encoding) { - const { exports, buffered, mem, chunkSize } = this; - let endPos; - if (data.length < 70) { - if (!encoding || encoding === "utf-8" || encoding === "utf8") { - endPos = buffered; - for (let i = 0; i < data.length; i++) { - const cc = data.charCodeAt(i); - if (cc < 0x80) mem[endPos++] = cc; - else if (cc < 0x800) { - mem[endPos] = (cc >> 6) | 0xc0; - mem[endPos + 1] = (cc & 0x3f) | 0x80; - endPos += 2; - } else { - // bail-out for weird chars - endPos += mem.write(data.slice(i), endPos, encoding); - break; - } - } - } else if (encoding === "latin1") { - endPos = buffered; - for (let i = 0; i < data.length; i++) { - const cc = data.charCodeAt(i); - mem[endPos++] = cc; - } - } else { - endPos = buffered + mem.write(data, buffered, encoding); - } + ) => { + const root = type === "compilation.summary!"; + const warningsMessage = + warningsCount > 0 + ? yellow( + `${warningsCount} ${plural(warningsCount, "warning", "warnings")}` + ) + : ""; + const errorsMessage = + errorsCount > 0 + ? red(`${errorsCount} ${plural(errorsCount, "error", "errors")}`) + : ""; + const timeMessage = root && time ? ` in ${formatTime(time)}` : ""; + const hashMessage = hash ? ` (${hash})` : ""; + const builtAtMessage = + root && builtAt ? `${formatDateTime(builtAt)}: ` : ""; + const versionMessage = root && version ? `webpack ${version}` : ""; + const nameMessage = + root && name + ? bold(name) + : name + ? `Child ${bold(name)}` + : root + ? "" + : "Child"; + const subjectMessage = + nameMessage && versionMessage + ? `${nameMessage} (${versionMessage})` + : versionMessage || nameMessage || "webpack"; + let statusMessage; + if (errorsMessage && warningsMessage) { + statusMessage = `compiled with ${errorsMessage} and ${warningsMessage}`; + } else if (errorsMessage) { + statusMessage = `compiled with ${errorsMessage}`; + } else if (warningsMessage) { + statusMessage = `compiled with ${warningsMessage}`; + } else if (errorsCount === 0 && warningsCount === 0) { + statusMessage = `compiled ${green("successfully")}`; } else { - endPos = buffered + mem.write(data, buffered, encoding); + statusMessage = `compiled`; } - if (endPos < chunkSize) { - this.buffered = endPos; - } else { - const l = endPos & ~(this.chunkSize - 1); - exports.update(l); - const newBuffered = endPos - l; - this.buffered = newBuffered; - if (newBuffered > 0) mem.copyWithin(0, l, endPos); + if ( + builtAtMessage || + versionMessage || + errorsMessage || + warningsMessage || + (errorsCount === 0 && warningsCount === 0) || + timeMessage || + hashMessage + ) + return `${builtAtMessage}${subjectMessage} ${statusMessage}${timeMessage}${hashMessage}`; + }, + "compilation.filteredWarningDetailsCount": count => + count + ? `${count} ${plural( + count, + "warning has", + "warnings have" + )} detailed information that is not shown.\nUse 'stats.errorDetails: true' resp. '--stats-error-details' to show it.` + : undefined, + "compilation.filteredErrorDetailsCount": (count, { yellow }) => + count + ? yellow( + `${count} ${plural( + count, + "error has", + "errors have" + )} detailed information that is not shown.\nUse 'stats.errorDetails: true' resp. '--stats-error-details' to show it.` + ) + : undefined, + "compilation.env": (env, { bold }) => + env + ? `Environment (--env): ${bold(JSON.stringify(env, null, 2))}` + : undefined, + "compilation.publicPath": (publicPath, { bold }) => + `PublicPath: ${bold(publicPath || "(none)")}`, + "compilation.entrypoints": (entrypoints, context, printer) => + Array.isArray(entrypoints) + ? undefined + : printer.print(context.type, Object.values(entrypoints), { + ...context, + chunkGroupKind: "Entrypoint" + }), + "compilation.namedChunkGroups": (namedChunkGroups, context, printer) => { + if (!Array.isArray(namedChunkGroups)) { + const { + compilation: { entrypoints } + } = context; + let chunkGroups = Object.values(namedChunkGroups); + if (entrypoints) { + chunkGroups = chunkGroups.filter( + group => + !Object.prototype.hasOwnProperty.call(entrypoints, group.name) + ); + } + return printer.print(context.type, chunkGroups, { + ...context, + chunkGroupKind: "Chunk Group" + }); } - } + }, + "compilation.assetsByChunkName": () => "", - /** - * @param {Buffer} data data - * @returns {void} - */ - _updateWithBuffer(data) { - const { exports, buffered, mem } = this; - const length = data.length; - if (buffered + length < this.chunkSize) { - data.copy(mem, buffered, 0, length); - this.buffered += length; - } else { - const l = (buffered + length) & ~(this.chunkSize - 1); - if (l > 65536) { - let i = 65536 - buffered; - data.copy(mem, buffered, 0, i); - exports.update(65536); - const stop = l - buffered - 65536; - while (i < stop) { - data.copy(mem, 0, i, i + 65536); - exports.update(65536); - i += 65536; - } - data.copy(mem, 0, i, l - buffered); - exports.update(l - buffered - i); - } else { - data.copy(mem, buffered, 0, l - buffered); - exports.update(l); + "compilation.filteredModules": ( + filteredModules, + { compilation: { modules } } + ) => + filteredModules > 0 + ? `${moreCount(modules, filteredModules)} ${plural( + filteredModules, + "module", + "modules" + )}` + : undefined, + "compilation.filteredAssets": (filteredAssets, { compilation: { assets } }) => + filteredAssets > 0 + ? `${moreCount(assets, filteredAssets)} ${plural( + filteredAssets, + "asset", + "assets" + )}` + : undefined, + "compilation.logging": (logging, context, printer) => + Array.isArray(logging) + ? undefined + : printer.print( + context.type, + Object.entries(logging).map(([name, value]) => ({ ...value, name })), + context + ), + "compilation.warningsInChildren!": (_, { yellow, compilation }) => { + if ( + !compilation.children && + compilation.warningsCount > 0 && + compilation.warnings + ) { + const childWarnings = + compilation.warningsCount - compilation.warnings.length; + if (childWarnings > 0) { + return yellow( + `${childWarnings} ${plural( + childWarnings, + "WARNING", + "WARNINGS" + )} in child compilations${ + compilation.children + ? "" + : " (Use 'stats.children: true' resp. '--stats-children' for more details)" + }` + ); } - const newBuffered = length + buffered - l; - this.buffered = newBuffered; - if (newBuffered > 0) data.copy(mem, 0, length - newBuffered, length); } - } - - digest(type) { - const { exports, buffered, mem, digestSize } = this; - exports.final(buffered); - this.instancesPool.push(this); - const hex = mem.toString("latin1", 0, digestSize); - if (type === "hex") return hex; - if (type === "binary" || !type) return Buffer.from(hex, "hex"); - return Buffer.from(hex, "hex").toString(type); - } -} + }, + "compilation.errorsInChildren!": (_, { red, compilation }) => { + if ( + !compilation.children && + compilation.errorsCount > 0 && + compilation.errors + ) { + const childErrors = compilation.errorsCount - compilation.errors.length; + if (childErrors > 0) { + return red( + `${childErrors} ${plural( + childErrors, + "ERROR", + "ERRORS" + )} in child compilations${ + compilation.children + ? "" + : " (Use 'stats.children: true' resp. '--stats-children' for more details)" + }` + ); + } + } + }, -const create = (wasmModule, instancesPool, chunkSize, digestSize) => { - if (instancesPool.length > 0) { - const old = instancesPool.pop(); - old.reset(); - return old; - } else { - return new WasmHash( - new WebAssembly.Instance(wasmModule), - instancesPool, - chunkSize, - digestSize - ); - } -}; + "asset.type": type => type, + "asset.name": (name, { formatFilename, asset: { isOverSizeLimit } }) => + formatFilename(name, isOverSizeLimit), + "asset.size": ( + size, + { asset: { isOverSizeLimit }, yellow, green, formatSize } + ) => (isOverSizeLimit ? yellow(formatSize(size)) : formatSize(size)), + "asset.emitted": (emitted, { green, formatFlag }) => + emitted ? green(formatFlag("emitted")) : undefined, + "asset.comparedForEmit": (comparedForEmit, { yellow, formatFlag }) => + comparedForEmit ? yellow(formatFlag("compared for emit")) : undefined, + "asset.cached": (cached, { green, formatFlag }) => + cached ? green(formatFlag("cached")) : undefined, + "asset.isOverSizeLimit": (isOverSizeLimit, { yellow, formatFlag }) => + isOverSizeLimit ? yellow(formatFlag("big")) : undefined, -module.exports = create; -module.exports.MAX_SHORT_STRING = MAX_SHORT_STRING; + "asset.info.immutable": (immutable, { green, formatFlag }) => + immutable ? green(formatFlag("immutable")) : undefined, + "asset.info.javascriptModule": (javascriptModule, { formatFlag }) => + javascriptModule ? formatFlag("javascript module") : undefined, + "asset.info.sourceFilename": (sourceFilename, { formatFlag }) => + sourceFilename + ? formatFlag( + sourceFilename === true + ? "from source file" + : `from: ${sourceFilename}` + ) + : undefined, + "asset.info.development": (development, { green, formatFlag }) => + development ? green(formatFlag("dev")) : undefined, + "asset.info.hotModuleReplacement": ( + hotModuleReplacement, + { green, formatFlag } + ) => (hotModuleReplacement ? green(formatFlag("hmr")) : undefined), + "asset.separator!": () => "\n", + "asset.filteredRelated": (filteredRelated, { asset: { related } }) => + filteredRelated > 0 + ? `${moreCount(related, filteredRelated)} related ${plural( + filteredRelated, + "asset", + "assets" + )}` + : undefined, + "asset.filteredChildren": (filteredChildren, { asset: { children } }) => + filteredChildren > 0 + ? `${moreCount(children, filteredChildren)} ${plural( + filteredChildren, + "asset", + "assets" + )}` + : undefined, + assetChunk: (id, { formatChunkId }) => formatChunkId(id), -/***/ }), + assetChunkName: name => name, + assetChunkIdHint: name => name, -/***/ 35028: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + "module.type": type => (type !== "module" ? type : undefined), + "module.id": (id, { formatModuleId }) => + isValidId(id) ? formatModuleId(id) : undefined, + "module.name": (name, { bold }) => { + const [prefix, resource] = getModuleName(name); + return `${prefix || ""}${bold(resource || "")}`; + }, + "module.identifier": identifier => undefined, + "module.layer": (layer, { formatLayer }) => + layer ? formatLayer(layer) : undefined, + "module.sizes": printSizes, + "module.chunks[]": (id, { formatChunkId }) => formatChunkId(id), + "module.depth": (depth, { formatFlag }) => + depth !== null ? formatFlag(`depth ${depth}`) : undefined, + "module.cacheable": (cacheable, { formatFlag, red }) => + cacheable === false ? red(formatFlag("not cacheable")) : undefined, + "module.orphan": (orphan, { formatFlag, yellow }) => + orphan ? yellow(formatFlag("orphan")) : undefined, + "module.runtime": (runtime, { formatFlag, yellow }) => + runtime ? yellow(formatFlag("runtime")) : undefined, + "module.optional": (optional, { formatFlag, yellow }) => + optional ? yellow(formatFlag("optional")) : undefined, + "module.dependent": (dependent, { formatFlag, cyan }) => + dependent ? cyan(formatFlag("dependent")) : undefined, + "module.built": (built, { formatFlag, yellow }) => + built ? yellow(formatFlag("built")) : undefined, + "module.codeGenerated": (codeGenerated, { formatFlag, yellow }) => + codeGenerated ? yellow(formatFlag("code generated")) : undefined, + "module.buildTimeExecuted": (buildTimeExecuted, { formatFlag, green }) => + buildTimeExecuted ? green(formatFlag("build time executed")) : undefined, + "module.cached": (cached, { formatFlag, green }) => + cached ? green(formatFlag("cached")) : undefined, + "module.assets": (assets, { formatFlag, magenta }) => + assets && assets.length + ? magenta( + formatFlag( + `${assets.length} ${plural(assets.length, "asset", "assets")}` + ) + ) + : undefined, + "module.warnings": (warnings, { formatFlag, yellow }) => + warnings === true + ? yellow(formatFlag("warnings")) + : warnings + ? yellow( + formatFlag(`${warnings} ${plural(warnings, "warning", "warnings")}`) + ) + : undefined, + "module.errors": (errors, { formatFlag, red }) => + errors === true + ? red(formatFlag("errors")) + : errors + ? red(formatFlag(`${errors} ${plural(errors, "error", "errors")}`)) + : undefined, + "module.providedExports": (providedExports, { formatFlag, cyan }) => { + if (Array.isArray(providedExports)) { + if (providedExports.length === 0) return cyan(formatFlag("no exports")); + return cyan(formatFlag(`exports: ${providedExports.join(", ")}`)); + } + }, + "module.usedExports": (usedExports, { formatFlag, cyan, module }) => { + if (usedExports !== true) { + if (usedExports === null) return cyan(formatFlag("used exports unknown")); + if (usedExports === false) return cyan(formatFlag("module unused")); + if (Array.isArray(usedExports)) { + if (usedExports.length === 0) + return cyan(formatFlag("no exports used")); + const providedExportsCount = Array.isArray(module.providedExports) + ? module.providedExports.length + : null; + if ( + providedExportsCount !== null && + providedExportsCount === usedExports.length + ) { + return cyan(formatFlag("all exports used")); + } else { + return cyan( + formatFlag(`only some exports used: ${usedExports.join(", ")}`) + ); + } + } + } + }, + "module.optimizationBailout[]": (optimizationBailout, { yellow }) => + yellow(optimizationBailout), + "module.issuerPath": (issuerPath, { module }) => + module.profile ? undefined : "", + "module.profile": profile => undefined, + "module.filteredModules": (filteredModules, { module: { modules } }) => + filteredModules > 0 + ? `${moreCount(modules, filteredModules)} nested ${plural( + filteredModules, + "module", + "modules" + )}` + : undefined, + "module.filteredReasons": (filteredReasons, { module: { reasons } }) => + filteredReasons > 0 + ? `${moreCount(reasons, filteredReasons)} ${plural( + filteredReasons, + "reason", + "reasons" + )}` + : undefined, + "module.filteredChildren": (filteredChildren, { module: { children } }) => + filteredChildren > 0 + ? `${moreCount(children, filteredChildren)} ${plural( + filteredChildren, + "module", + "modules" + )}` + : undefined, + "module.separator!": () => "\n", -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + "moduleIssuer.id": (id, { formatModuleId }) => formatModuleId(id), + "moduleIssuer.profile.total": (value, { formatTime }) => formatTime(value), + "moduleReason.type": type => type, + "moduleReason.userRequest": (userRequest, { cyan }) => + cyan(getResourceName(userRequest)), + "moduleReason.moduleId": (moduleId, { formatModuleId }) => + isValidId(moduleId) ? formatModuleId(moduleId) : undefined, + "moduleReason.module": (module, { magenta }) => magenta(module), + "moduleReason.loc": loc => loc, + "moduleReason.explanation": (explanation, { cyan }) => cyan(explanation), + "moduleReason.active": (active, { formatFlag }) => + active ? undefined : formatFlag("inactive"), + "moduleReason.resolvedModule": (module, { magenta }) => magenta(module), + "moduleReason.filteredChildren": ( + filteredChildren, + { moduleReason: { children } } + ) => + filteredChildren > 0 + ? `${moreCount(children, filteredChildren)} ${plural( + filteredChildren, + "reason", + "reasons" + )}` + : undefined, + "module.profile.total": (value, { formatTime }) => formatTime(value), + "module.profile.resolving": (value, { formatTime }) => + `resolving: ${formatTime(value)}`, + "module.profile.restoring": (value, { formatTime }) => + `restoring: ${formatTime(value)}`, + "module.profile.integration": (value, { formatTime }) => + `integration: ${formatTime(value)}`, + "module.profile.building": (value, { formatTime }) => + `building: ${formatTime(value)}`, + "module.profile.storing": (value, { formatTime }) => + `storing: ${formatTime(value)}`, + "module.profile.additionalResolving": (value, { formatTime }) => + value ? `additional resolving: ${formatTime(value)}` : undefined, + "module.profile.additionalIntegration": (value, { formatTime }) => + value ? `additional integration: ${formatTime(value)}` : undefined, -const create = __webpack_require__(1842); + "chunkGroup.kind!": (_, { chunkGroupKind }) => chunkGroupKind, + "chunkGroup.separator!": () => "\n", + "chunkGroup.name": (name, { bold }) => bold(name), + "chunkGroup.isOverSizeLimit": (isOverSizeLimit, { formatFlag, yellow }) => + isOverSizeLimit ? yellow(formatFlag("big")) : undefined, + "chunkGroup.assetsSize": (size, { formatSize }) => + size ? formatSize(size) : undefined, + "chunkGroup.auxiliaryAssetsSize": (size, { formatSize }) => + size ? `(${formatSize(size)})` : undefined, + "chunkGroup.filteredAssets": (n, { chunkGroup: { assets } }) => + n > 0 + ? `${moreCount(assets, n)} ${plural(n, "asset", "assets")}` + : undefined, + "chunkGroup.filteredAuxiliaryAssets": ( + n, + { chunkGroup: { auxiliaryAssets } } + ) => + n > 0 + ? `${moreCount(auxiliaryAssets, n)} auxiliary ${plural( + n, + "asset", + "assets" + )}` + : undefined, + "chunkGroup.is!": () => "=", + "chunkGroupAsset.name": (asset, { green }) => green(asset), + "chunkGroupAsset.size": (size, { formatSize, chunkGroup }) => + chunkGroup.assets.length > 1 || + (chunkGroup.auxiliaryAssets && chunkGroup.auxiliaryAssets.length > 0) + ? formatSize(size) + : undefined, + "chunkGroup.children": (children, context, printer) => + Array.isArray(children) + ? undefined + : printer.print( + context.type, + Object.keys(children).map(key => ({ + type: key, + children: children[key] + })), + context + ), + "chunkGroupChildGroup.type": type => `${type}:`, + "chunkGroupChild.assets[]": (file, { formatFilename }) => + formatFilename(file), + "chunkGroupChild.chunks[]": (id, { formatChunkId }) => formatChunkId(id), + "chunkGroupChild.name": name => (name ? `(name: ${name})` : undefined), -//#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1 -const xxhash64 = new WebAssembly.Module( - Buffer.from( - // 1170 bytes - "AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrIIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqAYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEAgAiABNQIAQoeVr6+Ytt6bnn9+hUIXiULP1tO+0ser2UJ+Qvnz3fGZ9pmrFnwhAiABQQRqIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAkIdiCAChUL5893xmfaZqxZ+IgJCIIggAoUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL", - "base64" - ) -); -//#endregion + "chunk.id": (id, { formatChunkId }) => formatChunkId(id), + "chunk.files[]": (file, { formatFilename }) => formatFilename(file), + "chunk.names[]": name => name, + "chunk.idHints[]": name => name, + "chunk.runtime[]": name => name, + "chunk.sizes": (sizes, context) => printSizes(sizes, context), + "chunk.parents[]": (parents, context) => + context.formatChunkId(parents, "parent"), + "chunk.siblings[]": (siblings, context) => + context.formatChunkId(siblings, "sibling"), + "chunk.children[]": (children, context) => + context.formatChunkId(children, "child"), + "chunk.childrenByOrder": (childrenByOrder, context, printer) => + Array.isArray(childrenByOrder) + ? undefined + : printer.print( + context.type, + Object.keys(childrenByOrder).map(key => ({ + type: key, + children: childrenByOrder[key] + })), + context + ), + "chunk.childrenByOrder[].type": type => `${type}:`, + "chunk.childrenByOrder[].children[]": (id, { formatChunkId }) => + isValidId(id) ? formatChunkId(id) : undefined, + "chunk.entry": (entry, { formatFlag, yellow }) => + entry ? yellow(formatFlag("entry")) : undefined, + "chunk.initial": (initial, { formatFlag, yellow }) => + initial ? yellow(formatFlag("initial")) : undefined, + "chunk.rendered": (rendered, { formatFlag, green }) => + rendered ? green(formatFlag("rendered")) : undefined, + "chunk.recorded": (recorded, { formatFlag, green }) => + recorded ? green(formatFlag("recorded")) : undefined, + "chunk.reason": (reason, { yellow }) => (reason ? yellow(reason) : undefined), + "chunk.filteredModules": (filteredModules, { chunk: { modules } }) => + filteredModules > 0 + ? `${moreCount(modules, filteredModules)} chunk ${plural( + filteredModules, + "module", + "modules" + )}` + : undefined, + "chunk.separator!": () => "\n", -module.exports = create.bind(null, xxhash64, [], 32, 16); + "chunkOrigin.request": request => request, + "chunkOrigin.moduleId": (moduleId, { formatModuleId }) => + isValidId(moduleId) ? formatModuleId(moduleId) : undefined, + "chunkOrigin.moduleName": (moduleName, { bold }) => bold(moduleName), + "chunkOrigin.loc": loc => loc, + "error.compilerPath": (compilerPath, { bold }) => + compilerPath ? bold(`(${compilerPath})`) : undefined, + "error.chunkId": (chunkId, { formatChunkId }) => + isValidId(chunkId) ? formatChunkId(chunkId) : undefined, + "error.chunkEntry": (chunkEntry, { formatFlag }) => + chunkEntry ? formatFlag("entry") : undefined, + "error.chunkInitial": (chunkInitial, { formatFlag }) => + chunkInitial ? formatFlag("initial") : undefined, + "error.file": (file, { bold }) => bold(file), + "error.moduleName": (moduleName, { bold }) => { + return moduleName.includes("!") + ? `${bold(moduleName.replace(/^(\s|\S)*!/, ""))} (${moduleName})` + : `${bold(moduleName)}`; + }, + "error.loc": (loc, { green }) => green(loc), + "error.message": (message, { bold, formatError }) => + message.includes("\u001b[") ? message : bold(formatError(message)), + "error.details": (details, { formatError }) => formatError(details), + "error.stack": stack => stack, + "error.moduleTrace": moduleTrace => undefined, + "error.separator!": () => "\n", -/***/ }), + "loggingEntry(error).loggingEntry.message": (message, { red }) => + mapLines(message, x => ` ${red(x)}`), + "loggingEntry(warn).loggingEntry.message": (message, { yellow }) => + mapLines(message, x => ` ${yellow(x)}`), + "loggingEntry(info).loggingEntry.message": (message, { green }) => + mapLines(message, x => ` ${green(x)}`), + "loggingEntry(log).loggingEntry.message": (message, { bold }) => + mapLines(message, x => ` ${bold(x)}`), + "loggingEntry(debug).loggingEntry.message": message => + mapLines(message, x => ` ${x}`), + "loggingEntry(trace).loggingEntry.message": message => + mapLines(message, x => ` ${x}`), + "loggingEntry(status).loggingEntry.message": (message, { magenta }) => + mapLines(message, x => ` ${magenta(x)}`), + "loggingEntry(profile).loggingEntry.message": (message, { magenta }) => + mapLines(message, x => `

${magenta(x)}`), + "loggingEntry(profileEnd).loggingEntry.message": (message, { magenta }) => + mapLines(message, x => `

${magenta(x)}`), + "loggingEntry(time).loggingEntry.message": (message, { magenta }) => + mapLines(message, x => ` ${magenta(x)}`), + "loggingEntry(group).loggingEntry.message": (message, { cyan }) => + mapLines(message, x => `<-> ${cyan(x)}`), + "loggingEntry(groupCollapsed).loggingEntry.message": (message, { cyan }) => + mapLines(message, x => `<+> ${cyan(x)}`), + "loggingEntry(clear).loggingEntry": () => " -------", + "loggingEntry(groupCollapsed).loggingEntry.children": () => "", + "loggingEntry.trace[]": trace => + trace ? mapLines(trace, x => `| ${x}`) : undefined, -/***/ 82186: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + "moduleTraceItem.originName": originName => originName, -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + loggingGroup: loggingGroup => + loggingGroup.entries.length === 0 ? "" : undefined, + "loggingGroup.debug": (flag, { red }) => (flag ? red("DEBUG") : undefined), + "loggingGroup.name": (name, { bold }) => bold(`LOG from ${name}`), + "loggingGroup.separator!": () => "\n", + "loggingGroup.filteredEntries": filteredEntries => + filteredEntries > 0 ? `+ ${filteredEntries} hidden lines` : undefined, + "moduleTraceDependency.loc": loc => loc +}; +/** @type {Record} */ +const ITEM_NAMES = { + "compilation.assets[]": "asset", + "compilation.modules[]": "module", + "compilation.chunks[]": "chunk", + "compilation.entrypoints[]": "chunkGroup", + "compilation.namedChunkGroups[]": "chunkGroup", + "compilation.errors[]": "error", + "compilation.warnings[]": "error", + "compilation.logging[]": "loggingGroup", + "compilation.children[]": "compilation", + "asset.related[]": "asset", + "asset.children[]": "asset", + "asset.chunks[]": "assetChunk", + "asset.auxiliaryChunks[]": "assetChunk", + "asset.chunkNames[]": "assetChunkName", + "asset.chunkIdHints[]": "assetChunkIdHint", + "asset.auxiliaryChunkNames[]": "assetChunkName", + "asset.auxiliaryChunkIdHints[]": "assetChunkIdHint", + "chunkGroup.assets[]": "chunkGroupAsset", + "chunkGroup.auxiliaryAssets[]": "chunkGroupAsset", + "chunkGroupChild.assets[]": "chunkGroupAsset", + "chunkGroupChild.auxiliaryAssets[]": "chunkGroupAsset", + "chunkGroup.children[]": "chunkGroupChildGroup", + "chunkGroupChildGroup.children[]": "chunkGroupChild", + "module.modules[]": "module", + "module.children[]": "module", + "module.reasons[]": "moduleReason", + "moduleReason.children[]": "moduleReason", + "module.issuerPath[]": "moduleIssuer", + "chunk.origins[]": "chunkOrigin", + "chunk.modules[]": "module", + "loggingGroup.entries[]": logEntry => + `loggingEntry(${logEntry.type}).loggingEntry`, + "loggingEntry.children[]": logEntry => + `loggingEntry(${logEntry.type}).loggingEntry`, + "error.moduleTrace[]": "moduleTraceItem", + "moduleTraceItem.dependencies[]": "moduleTraceDependency" +}; -const path = __webpack_require__(71017); +const ERROR_PREFERRED_ORDER = [ + "compilerPath", + "chunkId", + "chunkEntry", + "chunkInitial", + "file", + "separator!", + "moduleName", + "loc", + "separator!", + "message", + "separator!", + "details", + "separator!", + "stack", + "separator!", + "missing", + "separator!", + "moduleTrace" +]; -const WINDOWS_ABS_PATH_REGEXP = /^[a-zA-Z]:[\\/]/; -const SEGMENTS_SPLIT_REGEXP = /([|!])/; -const WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g; +/** @type {Record} */ +const PREFERRED_ORDERS = { + compilation: [ + "name", + "hash", + "version", + "time", + "builtAt", + "env", + "publicPath", + "assets", + "filteredAssets", + "entrypoints", + "namedChunkGroups", + "chunks", + "modules", + "filteredModules", + "children", + "logging", + "warnings", + "warningsInChildren!", + "filteredWarningDetailsCount", + "errors", + "errorsInChildren!", + "filteredErrorDetailsCount", + "summary!", + "needAdditionalPass" + ], + asset: [ + "type", + "name", + "size", + "chunks", + "auxiliaryChunks", + "emitted", + "comparedForEmit", + "cached", + "info", + "isOverSizeLimit", + "chunkNames", + "auxiliaryChunkNames", + "chunkIdHints", + "auxiliaryChunkIdHints", + "related", + "filteredRelated", + "children", + "filteredChildren" + ], + "asset.info": [ + "immutable", + "sourceFilename", + "javascriptModule", + "development", + "hotModuleReplacement" + ], + chunkGroup: [ + "kind!", + "name", + "isOverSizeLimit", + "assetsSize", + "auxiliaryAssetsSize", + "is!", + "assets", + "filteredAssets", + "auxiliaryAssets", + "filteredAuxiliaryAssets", + "separator!", + "children" + ], + chunkGroupAsset: ["name", "size"], + chunkGroupChildGroup: ["type", "children"], + chunkGroupChild: ["assets", "chunks", "name"], + module: [ + "type", + "name", + "identifier", + "id", + "layer", + "sizes", + "chunks", + "depth", + "cacheable", + "orphan", + "runtime", + "optional", + "dependent", + "built", + "codeGenerated", + "cached", + "assets", + "failed", + "warnings", + "errors", + "children", + "filteredChildren", + "providedExports", + "usedExports", + "optimizationBailout", + "reasons", + "filteredReasons", + "issuerPath", + "profile", + "modules", + "filteredModules" + ], + moduleReason: [ + "active", + "type", + "userRequest", + "moduleId", + "module", + "resolvedModule", + "loc", + "explanation", + "children", + "filteredChildren" + ], + "module.profile": [ + "total", + "separator!", + "resolving", + "restoring", + "integration", + "building", + "storing", + "additionalResolving", + "additionalIntegration" + ], + chunk: [ + "id", + "runtime", + "files", + "names", + "idHints", + "sizes", + "parents", + "siblings", + "children", + "childrenByOrder", + "entry", + "initial", + "rendered", + "recorded", + "reason", + "separator!", + "origins", + "separator!", + "modules", + "separator!", + "filteredModules" + ], + chunkOrigin: ["request", "moduleId", "moduleName", "loc"], + error: ERROR_PREFERRED_ORDER, + warning: ERROR_PREFERRED_ORDER, + "chunk.childrenByOrder[]": ["type", "children"], + loggingGroup: [ + "debug", + "name", + "separator!", + "entries", + "separator!", + "filteredEntries" + ], + loggingEntry: ["message", "trace", "children"] +}; -/** - * @typedef {Object} MakeRelativePathsCache - * @property {Map>=} relativePaths - */ +const itemsJoinOneLine = items => items.filter(Boolean).join(" "); +const itemsJoinOneLineBrackets = items => + items.length > 0 ? `(${items.filter(Boolean).join(" ")})` : undefined; +const itemsJoinMoreSpacing = items => items.filter(Boolean).join("\n\n"); +const itemsJoinComma = items => items.filter(Boolean).join(", "); +const itemsJoinCommaBrackets = items => + items.length > 0 ? `(${items.filter(Boolean).join(", ")})` : undefined; +const itemsJoinCommaBracketsWithName = name => items => + items.length > 0 + ? `(${name}: ${items.filter(Boolean).join(", ")})` + : undefined; -const relativePathToRequest = relativePath => { - if (relativePath === "") return "./."; - if (relativePath === "..") return "../."; - if (relativePath.startsWith("../")) return relativePath; - return `./${relativePath}`; +/** @type {Record string>} */ +const SIMPLE_ITEMS_JOINER = { + "chunk.parents": itemsJoinOneLine, + "chunk.siblings": itemsJoinOneLine, + "chunk.children": itemsJoinOneLine, + "chunk.names": itemsJoinCommaBrackets, + "chunk.idHints": itemsJoinCommaBracketsWithName("id hint"), + "chunk.runtime": itemsJoinCommaBracketsWithName("runtime"), + "chunk.files": itemsJoinComma, + "chunk.childrenByOrder": itemsJoinOneLine, + "chunk.childrenByOrder[].children": itemsJoinOneLine, + "chunkGroup.assets": itemsJoinOneLine, + "chunkGroup.auxiliaryAssets": itemsJoinOneLineBrackets, + "chunkGroupChildGroup.children": itemsJoinComma, + "chunkGroupChild.assets": itemsJoinOneLine, + "chunkGroupChild.auxiliaryAssets": itemsJoinOneLineBrackets, + "asset.chunks": itemsJoinComma, + "asset.auxiliaryChunks": itemsJoinCommaBrackets, + "asset.chunkNames": itemsJoinCommaBracketsWithName("name"), + "asset.auxiliaryChunkNames": itemsJoinCommaBracketsWithName("auxiliary name"), + "asset.chunkIdHints": itemsJoinCommaBracketsWithName("id hint"), + "asset.auxiliaryChunkIdHints": + itemsJoinCommaBracketsWithName("auxiliary id hint"), + "module.chunks": itemsJoinOneLine, + "module.issuerPath": items => + items + .filter(Boolean) + .map(item => `${item} ->`) + .join(" "), + "compilation.errors": itemsJoinMoreSpacing, + "compilation.warnings": itemsJoinMoreSpacing, + "compilation.logging": itemsJoinMoreSpacing, + "compilation.children": items => indent(itemsJoinMoreSpacing(items), " "), + "moduleTraceItem.dependencies": itemsJoinOneLine, + "loggingEntry.children": items => + indent(items.filter(Boolean).join("\n"), " ", false) }; -/** - * @param {string} context context for relative path - * @param {string} maybeAbsolutePath path to make relative - * @returns {string} relative path in request style - */ -const absoluteToRequest = (context, maybeAbsolutePath) => { - if (maybeAbsolutePath[0] === "/") { - if ( - maybeAbsolutePath.length > 1 && - maybeAbsolutePath[maybeAbsolutePath.length - 1] === "/" - ) { - // this 'path' is actually a regexp generated by dynamic requires. - // Don't treat it as an absolute path. - return maybeAbsolutePath; - } - - const querySplitPos = maybeAbsolutePath.indexOf("?"); - let resource = - querySplitPos === -1 - ? maybeAbsolutePath - : maybeAbsolutePath.slice(0, querySplitPos); - resource = relativePathToRequest(path.posix.relative(context, resource)); - return querySplitPos === -1 - ? resource - : resource + maybeAbsolutePath.slice(querySplitPos); - } +const joinOneLine = items => + items + .map(item => item.content) + .filter(Boolean) + .join(" "); - if (WINDOWS_ABS_PATH_REGEXP.test(maybeAbsolutePath)) { - const querySplitPos = maybeAbsolutePath.indexOf("?"); - let resource = - querySplitPos === -1 - ? maybeAbsolutePath - : maybeAbsolutePath.slice(0, querySplitPos); - resource = path.win32.relative(context, resource); - if (!WINDOWS_ABS_PATH_REGEXP.test(resource)) { - resource = relativePathToRequest( - resource.replace(WINDOWS_PATH_SEPARATOR_REGEXP, "/") - ); +const joinInBrackets = items => { + const res = []; + let mode = 0; + for (const item of items) { + if (item.element === "separator!") { + switch (mode) { + case 0: + case 1: + mode += 2; + break; + case 4: + res.push(")"); + mode = 3; + break; + } } - return querySplitPos === -1 - ? resource - : resource + maybeAbsolutePath.slice(querySplitPos); + if (!item.content) continue; + switch (mode) { + case 0: + mode = 1; + break; + case 1: + res.push(" "); + break; + case 2: + res.push("("); + mode = 4; + break; + case 3: + res.push(" ("); + mode = 4; + break; + case 4: + res.push(", "); + break; + } + res.push(item.content); } - - // not an absolute path - return maybeAbsolutePath; + if (mode === 4) res.push(")"); + return res.join(""); }; -/** - * @param {string} context context for relative path - * @param {string} relativePath path - * @returns {string} absolute path - */ -const requestToAbsolute = (context, relativePath) => { - if (relativePath.startsWith("./") || relativePath.startsWith("../")) - return path.join(context, relativePath); - return relativePath; +const indent = (str, prefix, noPrefixInFirstLine) => { + const rem = str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); + if (noPrefixInFirstLine) return rem; + const ind = str[0] === "\n" ? "" : prefix; + return ind + rem; }; -const makeCacheable = fn => { - /** @type {WeakMap>>} */ - const cache = new WeakMap(); +const joinExplicitNewLine = (items, indenter) => { + let firstInLine = true; + let first = true; + return items + .map(item => { + if (!item || !item.content) return; + let content = indent(item.content, first ? "" : indenter, !firstInLine); + if (firstInLine) { + content = content.replace(/^\n+/, ""); + } + if (!content) return; + first = false; + const noJoiner = firstInLine || content.startsWith("\n"); + firstInLine = content.endsWith("\n"); + return noJoiner ? content : " " + content; + }) + .filter(Boolean) + .join("") + .trim(); +}; - /** - * @param {string} context context used to create relative path - * @param {string} identifier identifier used to create relative path - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} the returned relative path - */ - const cachedFn = (context, identifier, associatedObjectForCache) => { - if (!associatedObjectForCache) return fn(context, identifier); +const joinError = + error => + (items, { red, yellow }) => + `${error ? red("ERROR") : yellow("WARNING")} in ${joinExplicitNewLine( + items, + "" + )}`; - let innerCache = cache.get(associatedObjectForCache); - if (innerCache === undefined) { - innerCache = new Map(); - cache.set(associatedObjectForCache, innerCache); +/** @type {Record string>} */ +const SIMPLE_ELEMENT_JOINERS = { + compilation: items => { + const result = []; + let lastNeedMore = false; + for (const item of items) { + if (!item.content) continue; + const needMoreSpace = + item.element === "warnings" || + item.element === "filteredWarningDetailsCount" || + item.element === "errors" || + item.element === "filteredErrorDetailsCount" || + item.element === "logging"; + if (result.length !== 0) { + result.push(needMoreSpace || lastNeedMore ? "\n\n" : "\n"); + } + result.push(item.content); + lastNeedMore = needMoreSpace; } + if (lastNeedMore) result.push("\n"); + return result.join(""); + }, + asset: items => + joinExplicitNewLine( + items.map(item => { + if ( + (item.element === "related" || item.element === "children") && + item.content + ) { + return { + ...item, + content: `\n${item.content}\n` + }; + } + return item; + }), + " " + ), + "asset.info": joinOneLine, + module: (items, { module }) => { + let hasName = false; + return joinExplicitNewLine( + items.map(item => { + switch (item.element) { + case "id": + if (module.id === module.name) { + if (hasName) return false; + if (item.content) hasName = true; + } + break; + case "name": + if (hasName) return false; + if (item.content) hasName = true; + break; + case "providedExports": + case "usedExports": + case "optimizationBailout": + case "reasons": + case "issuerPath": + case "profile": + case "children": + case "modules": + if (item.content) { + return { + ...item, + content: `\n${item.content}\n` + }; + } + break; + } + return item; + }), + " " + ); + }, + chunk: items => { + let hasEntry = false; + return ( + "chunk " + + joinExplicitNewLine( + items.filter(item => { + switch (item.element) { + case "entry": + if (item.content) hasEntry = true; + break; + case "initial": + if (hasEntry) return false; + break; + } + return true; + }), + " " + ) + ); + }, + "chunk.childrenByOrder[]": items => `(${joinOneLine(items)})`, + chunkGroup: items => joinExplicitNewLine(items, " "), + chunkGroupAsset: joinOneLine, + chunkGroupChildGroup: joinOneLine, + chunkGroupChild: joinOneLine, + // moduleReason: (items, { moduleReason }) => { + // let hasName = false; + // return joinOneLine( + // items.filter(item => { + // switch (item.element) { + // case "moduleId": + // if (moduleReason.moduleId === moduleReason.module && item.content) + // hasName = true; + // break; + // case "module": + // if (hasName) return false; + // break; + // case "resolvedModule": + // return ( + // moduleReason.module !== moduleReason.resolvedModule && + // item.content + // ); + // } + // return true; + // }) + // ); + // }, + moduleReason: (items, { moduleReason }) => { + let hasName = false; + return joinExplicitNewLine( + items.map(item => { + switch (item.element) { + case "moduleId": + if (moduleReason.moduleId === moduleReason.module && item.content) + hasName = true; + break; + case "module": + if (hasName) return false; + break; + case "resolvedModule": + if (moduleReason.module === moduleReason.resolvedModule) + return false; + break; + case "children": + if (item.content) { + return { + ...item, + content: `\n${item.content}\n` + }; + } + break; + } + return item; + }), + " " + ); + }, + "module.profile": joinInBrackets, + moduleIssuer: joinOneLine, + chunkOrigin: items => "> " + joinOneLine(items), + "errors[].error": joinError(true), + "warnings[].error": joinError(false), + loggingGroup: items => joinExplicitNewLine(items, "").trimRight(), + moduleTraceItem: items => " @ " + joinOneLine(items), + moduleTraceDependency: joinOneLine +}; - let cachedResult; - let innerSubCache = innerCache.get(context); - if (innerSubCache === undefined) { - innerCache.set(context, (innerSubCache = new Map())); - } else { - cachedResult = innerSubCache.get(identifier); - } +const AVAILABLE_COLORS = { + bold: "\u001b[1m", + yellow: "\u001b[1m\u001b[33m", + red: "\u001b[1m\u001b[31m", + green: "\u001b[1m\u001b[32m", + cyan: "\u001b[1m\u001b[36m", + magenta: "\u001b[1m\u001b[35m" +}; - if (cachedResult !== undefined) { - return cachedResult; - } else { - const result = fn(context, identifier); - innerSubCache.set(identifier, result); - return result; +const AVAILABLE_FORMATS = { + formatChunkId: (id, { yellow }, direction) => { + switch (direction) { + case "parent": + return `<{${yellow(id)}}>`; + case "sibling": + return `={${yellow(id)}}=`; + case "child": + return `>{${yellow(id)}}<`; + default: + return `{${yellow(id)}}`; } - }; - - /** - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {function(string, string): string} cached function - */ - cachedFn.bindCache = associatedObjectForCache => { - let innerCache; - if (associatedObjectForCache) { - innerCache = cache.get(associatedObjectForCache); - if (innerCache === undefined) { - innerCache = new Map(); - cache.set(associatedObjectForCache, innerCache); - } + }, + formatModuleId: id => `[${id}]`, + formatFilename: (filename, { green, yellow }, oversize) => + (oversize ? yellow : green)(filename), + formatFlag: flag => `[${flag}]`, + formatLayer: layer => `(in ${layer})`, + formatSize: (__webpack_require__(71070).formatSize), + formatDateTime: (dateTime, { bold }) => { + const d = new Date(dateTime); + const x = twoDigit; + const date = `${d.getFullYear()}-${x(d.getMonth() + 1)}-${x(d.getDate())}`; + const time = `${x(d.getHours())}:${x(d.getMinutes())}:${x(d.getSeconds())}`; + return `${date} ${bold(time)}`; + }, + formatTime: ( + time, + { timeReference, bold, green, yellow, red }, + boldQuantity + ) => { + const unit = " ms"; + if (timeReference && time !== timeReference) { + const times = [ + timeReference / 2, + timeReference / 4, + timeReference / 8, + timeReference / 16 + ]; + if (time < times[3]) return `${time}${unit}`; + else if (time < times[2]) return bold(`${time}${unit}`); + else if (time < times[1]) return green(`${time}${unit}`); + else if (time < times[0]) return yellow(`${time}${unit}`); + else return red(`${time}${unit}`); } else { - innerCache = new Map(); + return `${boldQuantity ? bold(time) : time}${unit}`; } - - /** - * @param {string} context context used to create relative path - * @param {string} identifier identifier used to create relative path - * @returns {string} the returned relative path - */ - const boundFn = (context, identifier) => { - let cachedResult; - let innerSubCache = innerCache.get(context); - if (innerSubCache === undefined) { - innerCache.set(context, (innerSubCache = new Map())); - } else { - cachedResult = innerSubCache.get(identifier); - } - - if (cachedResult !== undefined) { - return cachedResult; - } else { - const result = fn(context, identifier); - innerSubCache.set(identifier, result); - return result; - } - }; - - return boundFn; - }; - - /** - * @param {string} context context used to create relative path - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {function(string): string} cached function - */ - cachedFn.bindContextCache = (context, associatedObjectForCache) => { - let innerSubCache; - if (associatedObjectForCache) { - let innerCache = cache.get(associatedObjectForCache); - if (innerCache === undefined) { - innerCache = new Map(); - cache.set(associatedObjectForCache, innerCache); - } - - innerSubCache = innerCache.get(context); - if (innerSubCache === undefined) { - innerCache.set(context, (innerSubCache = new Map())); + }, + formatError: (message, { green, yellow, red }) => { + if (message.includes("\u001b[")) return message; + const highlights = [ + { regExp: /(Did you mean .+)/g, format: green }, + { + regExp: /(Set 'mode' option to 'development' or 'production')/g, + format: green + }, + { regExp: /(\(module has no exports\))/g, format: red }, + { regExp: /\(possible exports: (.+)\)/g, format: green }, + { regExp: /(?:^|\n)(.* doesn't exist)/g, format: red }, + { regExp: /('\w+' option has not been set)/g, format: red }, + { + regExp: /(Emitted value instead of an instance of Error)/g, + format: yellow + }, + { regExp: /(Used? .+ instead)/gi, format: yellow }, + { regExp: /\b(deprecated|must|required)\b/g, format: yellow }, + { + regExp: /\b(BREAKING CHANGE)\b/gi, + format: red + }, + { + regExp: + /\b(error|failed|unexpected|invalid|not found|not supported|not available|not possible|not implemented|doesn't support|conflict|conflicting|not existing|duplicate)\b/gi, + format: red } - } else { - innerSubCache = new Map(); + ]; + for (const { regExp, format } of highlights) { + message = message.replace(regExp, (match, content) => { + return match.replace(content, format(content)); + }); } - - /** - * @param {string} identifier identifier used to create relative path - * @returns {string} the returned relative path - */ - const boundFn = identifier => { - const cachedResult = innerSubCache.get(identifier); - if (cachedResult !== undefined) { - return cachedResult; - } else { - const result = fn(context, identifier); - innerSubCache.set(identifier, result); - return result; - } - }; - - return boundFn; - }; - - return cachedFn; -}; - -/** - * - * @param {string} context context for relative path - * @param {string} identifier identifier for path - * @returns {string} a converted relative path - */ -const _makePathsRelative = (context, identifier) => { - return identifier - .split(SEGMENTS_SPLIT_REGEXP) - .map(str => absoluteToRequest(context, str)) - .join(""); -}; - -exports.makePathsRelative = makeCacheable(_makePathsRelative); - -/** - * - * @param {string} context context for relative path - * @param {string} identifier identifier for path - * @returns {string} a converted relative path - */ -const _makePathsAbsolute = (context, identifier) => { - return identifier - .split(SEGMENTS_SPLIT_REGEXP) - .map(str => requestToAbsolute(context, str)) - .join(""); + return message; + } }; -exports.makePathsAbsolute = makeCacheable(_makePathsAbsolute); - -/** - * @param {string} context absolute context path - * @param {string} request any request string may containing absolute paths, query string, etc. - * @returns {string} a new request string avoiding absolute paths when possible - */ -const _contextify = (context, request) => { - return request - .split("!") - .map(r => absoluteToRequest(context, r)) - .join("!"); +const RESULT_MODIFIER = { + "module.modules": result => { + return indent(result, "| "); + } }; -const contextify = makeCacheable(_contextify); -exports.contextify = contextify; - -/** - * @param {string} context absolute context path - * @param {string} request any request string - * @returns {string} a new request string using absolute paths when possible - */ -const _absolutify = (context, request) => { - return request - .split("!") - .map(r => requestToAbsolute(context, r)) - .join("!"); +const createOrder = (array, preferredOrder) => { + const originalArray = array.slice(); + const set = new Set(array); + const usedSet = new Set(); + array.length = 0; + for (const element of preferredOrder) { + if (element.endsWith("!") || set.has(element)) { + array.push(element); + usedSet.add(element); + } + } + for (const element of originalArray) { + if (!usedSet.has(element)) { + array.push(element); + } + } + return array; }; -const absolutify = makeCacheable(_absolutify); -exports.absolutify = absolutify; - -const PATH_QUERY_FRAGMENT_REGEXP = - /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; - -/** @typedef {{ resource: string, path: string, query: string, fragment: string }} ParsedResource */ +class DefaultStatsPrinterPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap("DefaultStatsPrinterPlugin", compilation => { + compilation.hooks.statsPrinter.tap( + "DefaultStatsPrinterPlugin", + (stats, options, context) => { + // Put colors into context + stats.hooks.print + .for("compilation") + .tap("DefaultStatsPrinterPlugin", (compilation, context) => { + for (const color of Object.keys(AVAILABLE_COLORS)) { + let start; + if (options.colors) { + if ( + typeof options.colors === "object" && + typeof options.colors[color] === "string" + ) { + start = options.colors[color]; + } else { + start = AVAILABLE_COLORS[color]; + } + } + if (start) { + context[color] = str => + `${start}${ + typeof str === "string" + ? str.replace( + /((\u001b\[39m|\u001b\[22m|\u001b\[0m)+)/g, + `$1${start}` + ) + : str + }\u001b[39m\u001b[22m`; + } else { + context[color] = str => str; + } + } + for (const format of Object.keys(AVAILABLE_FORMATS)) { + context[format] = (content, ...args) => + AVAILABLE_FORMATS[format](content, context, ...args); + } + context.timeReference = compilation.time; + }); -/** - * @param {string} str the path with query and fragment - * @returns {ParsedResource} parsed parts - */ -const _parseResource = str => { - const match = PATH_QUERY_FRAGMENT_REGEXP.exec(str); - return { - resource: str, - path: match[1].replace(/\0(.)/g, "$1"), - query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "", - fragment: match[3] || "" - }; -}; -exports.parseResource = (realFn => { - /** @type {WeakMap>} */ - const cache = new WeakMap(); + for (const key of Object.keys(SIMPLE_PRINTERS)) { + stats.hooks.print + .for(key) + .tap("DefaultStatsPrinterPlugin", (obj, ctx) => + SIMPLE_PRINTERS[key](obj, ctx, stats) + ); + } - const getCache = associatedObjectForCache => { - const entry = cache.get(associatedObjectForCache); - if (entry !== undefined) return entry; - /** @type {Map} */ - const map = new Map(); - cache.set(associatedObjectForCache, map); - return map; - }; + for (const key of Object.keys(PREFERRED_ORDERS)) { + const preferredOrder = PREFERRED_ORDERS[key]; + stats.hooks.sortElements + .for(key) + .tap("DefaultStatsPrinterPlugin", (elements, context) => { + createOrder(elements, preferredOrder); + }); + } - /** - * @param {string} str the path with query and fragment - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {ParsedResource} parsed parts - */ - const fn = (str, associatedObjectForCache) => { - if (!associatedObjectForCache) return realFn(str); - const cache = getCache(associatedObjectForCache); - const entry = cache.get(str); - if (entry !== undefined) return entry; - const result = realFn(str); - cache.set(str, result); - return result; - }; + for (const key of Object.keys(ITEM_NAMES)) { + const itemName = ITEM_NAMES[key]; + stats.hooks.getItemName + .for(key) + .tap( + "DefaultStatsPrinterPlugin", + typeof itemName === "string" ? () => itemName : itemName + ); + } - fn.bindCache = associatedObjectForCache => { - const cache = getCache(associatedObjectForCache); - return str => { - const entry = cache.get(str); - if (entry !== undefined) return entry; - const result = realFn(str); - cache.set(str, result); - return result; - }; - }; + for (const key of Object.keys(SIMPLE_ITEMS_JOINER)) { + const joiner = SIMPLE_ITEMS_JOINER[key]; + stats.hooks.printItems + .for(key) + .tap("DefaultStatsPrinterPlugin", joiner); + } - return fn; -})(_parseResource); + for (const key of Object.keys(SIMPLE_ELEMENT_JOINERS)) { + const joiner = SIMPLE_ELEMENT_JOINERS[key]; + stats.hooks.printElements + .for(key) + .tap("DefaultStatsPrinterPlugin", joiner); + } -/** - * @param {string} filename the filename which should be undone - * @param {string} outputPath the output path that is restored (only relevant when filename contains "..") - * @param {boolean} enforceRelative true returns ./ for empty paths - * @returns {string} repeated ../ to leave the directory of the provided filename to be back on output dir - */ -exports.getUndoPath = (filename, outputPath, enforceRelative) => { - let depth = -1; - let append = ""; - outputPath = outputPath.replace(/[\\/]$/, ""); - for (const part of filename.split(/[/\\]+/)) { - if (part === "..") { - if (depth > -1) { - depth--; - } else { - const i = outputPath.lastIndexOf("/"); - const j = outputPath.lastIndexOf("\\"); - const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j); - if (pos < 0) return outputPath + "/"; - append = outputPath.slice(pos + 1) + "/" + append; - outputPath = outputPath.slice(0, pos); - } - } else if (part !== ".") { - depth++; - } + for (const key of Object.keys(RESULT_MODIFIER)) { + const modifier = RESULT_MODIFIER[key]; + stats.hooks.result + .for(key) + .tap("DefaultStatsPrinterPlugin", modifier); + } + } + ); + }); } - return depth > 0 - ? `${"../".repeat(depth)}${append}` - : enforceRelative - ? `./${append}` - : append; -}; +} +module.exports = DefaultStatsPrinterPlugin; /***/ }), -/***/ 53023: +/***/ 92629: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -127086,292 +133294,297 @@ exports.getUndoPath = (filename, outputPath, enforceRelative) => { -// We need to include a list of requires here -// to allow webpack to be bundled with only static requires -// We could use a dynamic require(`../${request}`) but this -// would include too many modules and not every tool is able -// to process this -module.exports = { - AsyncDependenciesBlock: () => __webpack_require__(47736), - CommentCompilationWarning: () => __webpack_require__(98427), - ContextModule: () => __webpack_require__(76729), - "cache/PackFileCacheStrategy": () => - __webpack_require__(86180), - "cache/ResolverCachePlugin": () => __webpack_require__(97347), - "container/ContainerEntryDependency": () => - __webpack_require__(64813), - "container/ContainerEntryModule": () => - __webpack_require__(80580), - "container/ContainerExposedDependency": () => - __webpack_require__(72374), - "container/FallbackDependency": () => - __webpack_require__(57764), - "container/FallbackItemDependency": () => - __webpack_require__(29593), - "container/FallbackModule": () => __webpack_require__(82886), - "container/RemoteModule": () => __webpack_require__(62916), - "container/RemoteToExternalDependency": () => - __webpack_require__(14389), - "dependencies/AMDDefineDependency": () => - __webpack_require__(96816), - "dependencies/AMDRequireArrayDependency": () => - __webpack_require__(33516), - "dependencies/AMDRequireContextDependency": () => - __webpack_require__(96123), - "dependencies/AMDRequireDependenciesBlock": () => - __webpack_require__(76932), - "dependencies/AMDRequireDependency": () => - __webpack_require__(43911), - "dependencies/AMDRequireItemDependency": () => - __webpack_require__(71806), - "dependencies/CachedConstDependency": () => - __webpack_require__(57403), - "dependencies/CreateScriptUrlDependency": () => - __webpack_require__(79062), - "dependencies/CommonJsRequireContextDependency": () => - __webpack_require__(23962), - "dependencies/CommonJsExportRequireDependency": () => - __webpack_require__(62892), - "dependencies/CommonJsExportsDependency": () => - __webpack_require__(45598), - "dependencies/CommonJsFullRequireDependency": () => - __webpack_require__(59440), - "dependencies/CommonJsRequireDependency": () => - __webpack_require__(21264), - "dependencies/CommonJsSelfReferenceDependency": () => - __webpack_require__(52225), - "dependencies/ConstDependency": () => - __webpack_require__(76911), - "dependencies/ContextDependency": () => - __webpack_require__(88101), - "dependencies/ContextElementDependency": () => - __webpack_require__(58477), - "dependencies/CriticalDependencyWarning": () => - __webpack_require__(15427), - "dependencies/CssImportDependency": () => - __webpack_require__(90542), - "dependencies/CssLocalIdentifierDependency": () => - __webpack_require__(92328), - "dependencies/CssSelfLocalIdentifierDependency": () => - __webpack_require__(29094), - "dependencies/CssExportDependency": () => - __webpack_require__(76760), - "dependencies/CssUrlDependency": () => - __webpack_require__(70749), - "dependencies/DelegatedSourceDependency": () => - __webpack_require__(22914), - "dependencies/DllEntryDependency": () => - __webpack_require__(95666), - "dependencies/EntryDependency": () => - __webpack_require__(3979), - "dependencies/ExportsInfoDependency": () => - __webpack_require__(78988), - "dependencies/HarmonyAcceptDependency": () => - __webpack_require__(23624), - "dependencies/HarmonyAcceptImportDependency": () => - __webpack_require__(99843), - "dependencies/HarmonyCompatibilityDependency": () => - __webpack_require__(72906), - "dependencies/HarmonyExportExpressionDependency": () => - __webpack_require__(51340), - "dependencies/HarmonyExportHeaderDependency": () => - __webpack_require__(38873), - "dependencies/HarmonyExportImportedSpecifierDependency": () => - __webpack_require__(67157), - "dependencies/HarmonyExportSpecifierDependency": () => - __webpack_require__(48567), - "dependencies/HarmonyImportSideEffectDependency": () => - __webpack_require__(73132), - "dependencies/HarmonyImportSpecifierDependency": () => - __webpack_require__(14077), - "dependencies/ImportContextDependency": () => - __webpack_require__(1902), - "dependencies/ImportDependency": () => - __webpack_require__(89376), - "dependencies/ImportEagerDependency": () => - __webpack_require__(50718), - "dependencies/ImportWeakDependency": () => - __webpack_require__(82483), - "dependencies/JsonExportsDependency": () => - __webpack_require__(750), - "dependencies/LocalModule": () => __webpack_require__(5826), - "dependencies/LocalModuleDependency": () => - __webpack_require__(52805), - "dependencies/ModuleDecoratorDependency": () => - __webpack_require__(88488), - "dependencies/ModuleHotAcceptDependency": () => - __webpack_require__(47511), - "dependencies/ModuleHotDeclineDependency": () => - __webpack_require__(86301), - "dependencies/ImportMetaHotAcceptDependency": () => - __webpack_require__(51274), - "dependencies/ImportMetaHotDeclineDependency": () => - __webpack_require__(53141), - "dependencies/ProvidedDependency": () => - __webpack_require__(95770), - "dependencies/PureExpressionDependency": () => - __webpack_require__(55799), - "dependencies/RequireContextDependency": () => - __webpack_require__(46917), - "dependencies/RequireEnsureDependenciesBlock": () => - __webpack_require__(27153), - "dependencies/RequireEnsureDependency": () => - __webpack_require__(27223), - "dependencies/RequireEnsureItemDependency": () => - __webpack_require__(50329), - "dependencies/RequireHeaderDependency": () => - __webpack_require__(89183), - "dependencies/RequireIncludeDependency": () => - __webpack_require__(71284), - "dependencies/RequireIncludeDependencyParserPlugin": () => - __webpack_require__(35768), - "dependencies/RequireResolveContextDependency": () => - __webpack_require__(55627), - "dependencies/RequireResolveDependency": () => - __webpack_require__(68582), - "dependencies/RequireResolveHeaderDependency": () => - __webpack_require__(9880), - "dependencies/RuntimeRequirementsDependency": () => - __webpack_require__(24187), - "dependencies/StaticExportsDependency": () => - __webpack_require__(91418), - "dependencies/SystemPlugin": () => __webpack_require__(97981), - "dependencies/UnsupportedDependency": () => - __webpack_require__(51669), - "dependencies/URLDependency": () => __webpack_require__(58612), - "dependencies/WebAssemblyExportImportedDependency": () => - __webpack_require__(52204), - "dependencies/WebAssemblyImportDependency": () => - __webpack_require__(5239), - "dependencies/WebpackIsIncludedDependency": () => - __webpack_require__(26505), - "dependencies/WorkerDependency": () => - __webpack_require__(1466), - "json/JsonData": () => __webpack_require__(90490), - "optimize/ConcatenatedModule": () => - __webpack_require__(97198), - DelegatedModule: () => __webpack_require__(28623), - DependenciesBlock: () => __webpack_require__(71040), - DllModule: () => __webpack_require__(28280), - ExternalModule: () => __webpack_require__(73071), - FileSystemInfo: () => __webpack_require__(79453), - InitFragment: () => __webpack_require__(55870), - InvalidDependenciesModuleWarning: () => - __webpack_require__(68257), - Module: () => __webpack_require__(73208), - ModuleBuildError: () => __webpack_require__(21305), - ModuleDependencyWarning: () => __webpack_require__(29656), - ModuleError: () => __webpack_require__(23744), - ModuleGraph: () => __webpack_require__(99988), - ModuleParseError: () => __webpack_require__(58443), - ModuleWarning: () => __webpack_require__(11234), - NormalModule: () => __webpack_require__(39), - RawDataUrlModule: () => __webpack_require__(19684), - RawModule: () => __webpack_require__(84929), - "sharing/ConsumeSharedModule": () => - __webpack_require__(62286), - "sharing/ConsumeSharedFallbackDependency": () => - __webpack_require__(58831), - "sharing/ProvideSharedModule": () => - __webpack_require__(50821), - "sharing/ProvideSharedDependency": () => - __webpack_require__(1798), - "sharing/ProvideForSharedDependency": () => - __webpack_require__(40017), - UnsupportedFeatureWarning: () => __webpack_require__(42495), - "util/LazySet": () => __webpack_require__(38938), - UnhandledSchemeError: () => __webpack_require__(68099), - NodeStuffInWebError: () => __webpack_require__(6325), - WebpackError: () => __webpack_require__(53799), - - "util/registerExternalSerializer": () => { - // already registered - } -}; +const { HookMap, SyncBailHook, SyncWaterfallHook } = __webpack_require__(41242); +const { concatComparators, keepOriginalOrder } = __webpack_require__(29579); +const smartGrouping = __webpack_require__(15652); +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -/***/ }), +/** @typedef {import("../util/smartGrouping").GroupConfig} GroupConfig */ -/***/ 33032: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @typedef {Object} KnownStatsFactoryContext + * @property {string} type + * @property {function(string): string=} makePathsRelative + * @property {Compilation=} compilation + * @property {Set=} rootModules + * @property {Map=} compilationFileToChunks + * @property {Map=} compilationAuxiliaryFileToChunks + * @property {RuntimeSpec=} runtime + * @property {function(Compilation): WebpackError[]=} cachedGetErrors + * @property {function(Compilation): WebpackError[]=} cachedGetWarnings + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ +/** @typedef {KnownStatsFactoryContext & Record} StatsFactoryContext */ +class StatsFactory { + constructor() { + this.hooks = Object.freeze({ + /** @type {HookMap>} */ + extract: new HookMap( + () => new SyncBailHook(["object", "data", "context"]) + ), + /** @type {HookMap>} */ + filter: new HookMap( + () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) + ), + /** @type {HookMap>} */ + sort: new HookMap(() => new SyncBailHook(["comparators", "context"])), + /** @type {HookMap>} */ + filterSorted: new HookMap( + () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) + ), + /** @type {HookMap>} */ + groupResults: new HookMap( + () => new SyncBailHook(["groupConfigs", "context"]) + ), + /** @type {HookMap>} */ + sortResults: new HookMap( + () => new SyncBailHook(["comparators", "context"]) + ), + /** @type {HookMap>} */ + filterResults: new HookMap( + () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) + ), + /** @type {HookMap>} */ + merge: new HookMap(() => new SyncBailHook(["items", "context"])), + /** @type {HookMap>} */ + result: new HookMap(() => new SyncWaterfallHook(["result", "context"])), + /** @type {HookMap>} */ + getItemName: new HookMap(() => new SyncBailHook(["item", "context"])), + /** @type {HookMap>} */ + getItemFactory: new HookMap(() => new SyncBailHook(["item", "context"])) + }); + const hooks = this.hooks; + this._caches = + /** @type {Record[]>>} */ ({}); + for (const key of Object.keys(hooks)) { + this._caches[key] = new Map(); + } + this._inCreate = false; + } + _getAllLevelHooks(hookMap, cache, type) { + const cacheEntry = cache.get(type); + if (cacheEntry !== undefined) { + return cacheEntry; + } + const hooks = []; + const typeParts = type.split("."); + for (let i = 0; i < typeParts.length; i++) { + const hook = hookMap.get(typeParts.slice(i).join(".")); + if (hook) { + hooks.push(hook); + } + } + cache.set(type, hooks); + return hooks; + } -const { register } = __webpack_require__(8282); + _forEachLevel(hookMap, cache, type, fn) { + for (const hook of this._getAllLevelHooks(hookMap, cache, type)) { + const result = fn(hook); + if (result !== undefined) return result; + } + } -class ClassSerializer { - constructor(Constructor) { - this.Constructor = Constructor; + _forEachLevelWaterfall(hookMap, cache, type, data, fn) { + for (const hook of this._getAllLevelHooks(hookMap, cache, type)) { + data = fn(hook, data); + } + return data; } - serialize(obj, context) { - obj.serialize(context); + _forEachLevelFilter(hookMap, cache, type, items, fn, forceClone) { + const hooks = this._getAllLevelHooks(hookMap, cache, type); + if (hooks.length === 0) return forceClone ? items.slice() : items; + let i = 0; + return items.filter((item, idx) => { + for (const hook of hooks) { + const r = fn(hook, item, idx, i); + if (r !== undefined) { + if (r) i++; + return r; + } + } + i++; + return true; + }); } - deserialize(context) { - if (typeof this.Constructor.deserialize === "function") { - return this.Constructor.deserialize(context); + /** + * @param {string} type type + * @param {any} data factory data + * @param {Omit} baseContext context used as base + * @returns {any} created object + */ + create(type, data, baseContext) { + if (this._inCreate) { + return this._create(type, data, baseContext); + } else { + try { + this._inCreate = true; + return this._create(type, data, baseContext); + } finally { + for (const key of Object.keys(this._caches)) this._caches[key].clear(); + this._inCreate = false; + } } - const obj = new this.Constructor(); - obj.deserialize(context); - return obj; } -} -module.exports = (Constructor, request, name = null) => { - register(Constructor, request, name, new ClassSerializer(Constructor)); -}; + _create(type, data, baseContext) { + const context = { + ...baseContext, + type, + [type]: data + }; + if (Array.isArray(data)) { + // run filter on unsorted items + const items = this._forEachLevelFilter( + this.hooks.filter, + this._caches.filter, + type, + data, + (h, r, idx, i) => h.call(r, context, idx, i), + true + ); + // sort items + const comparators = []; + this._forEachLevel(this.hooks.sort, this._caches.sort, type, h => + h.call(comparators, context) + ); + if (comparators.length > 0) { + items.sort( + // @ts-expect-error number of arguments is correct + concatComparators(...comparators, keepOriginalOrder(items)) + ); + } -/***/ }), + // run filter on sorted items + const items2 = this._forEachLevelFilter( + this.hooks.filterSorted, + this._caches.filterSorted, + type, + items, + (h, r, idx, i) => h.call(r, context, idx, i), + false + ); -/***/ 78676: -/***/ (function(module) { + // for each item + let resultItems = items2.map((item, i) => { + const itemContext = { + ...context, + _index: i + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + // run getItemName + const itemName = this._forEachLevel( + this.hooks.getItemName, + this._caches.getItemName, + `${type}[]`, + h => h.call(item, itemContext) + ); + if (itemName) itemContext[itemName] = item; + const innerType = itemName ? `${type}[].${itemName}` : `${type}[]`; + // run getItemFactory + const itemFactory = + this._forEachLevel( + this.hooks.getItemFactory, + this._caches.getItemFactory, + innerType, + h => h.call(item, itemContext) + ) || this; + // run item factory + return itemFactory.create(innerType, item, itemContext); + }); -/** @template T @typedef {function(): T} FunctionReturning */ + // sort result items + const comparators2 = []; + this._forEachLevel( + this.hooks.sortResults, + this._caches.sortResults, + type, + h => h.call(comparators2, context) + ); + if (comparators2.length > 0) { + resultItems.sort( + // @ts-expect-error number of arguments is correct + concatComparators(...comparators2, keepOriginalOrder(resultItems)) + ); + } -/** - * @template T - * @param {FunctionReturning} fn memorized function - * @returns {FunctionReturning} new function - */ -const memoize = fn => { - let cache = false; - /** @type {T} */ - let result = undefined; - return () => { - if (cache) { - return result; + // group result items + const groupConfigs = []; + this._forEachLevel( + this.hooks.groupResults, + this._caches.groupResults, + type, + h => h.call(groupConfigs, context) + ); + if (groupConfigs.length > 0) { + resultItems = smartGrouping(resultItems, groupConfigs); + } + + // run filter on sorted result items + const finalResultItems = this._forEachLevelFilter( + this.hooks.filterResults, + this._caches.filterResults, + type, + resultItems, + (h, r, idx, i) => h.call(r, context, idx, i), + false + ); + + // run merge on mapped items + let result = this._forEachLevel( + this.hooks.merge, + this._caches.merge, + type, + h => h.call(finalResultItems, context) + ); + if (result === undefined) result = finalResultItems; + + // run result on merged items + return this._forEachLevelWaterfall( + this.hooks.result, + this._caches.result, + type, + result, + (h, r) => h.call(r, context) + ); } else { - result = fn(); - cache = true; - // Allow to clean up memory for fn - // and all dependent resources - fn = undefined; - return result; - } - }; -}; + const object = {}; -module.exports = memoize; + // run extract on value + this._forEachLevel(this.hooks.extract, this._caches.extract, type, h => + h.call(object, data, context) + ); + + // run result on extracted object + return this._forEachLevelWaterfall( + this.hooks.result, + this._caches.result, + type, + object, + (h, r) => h.call(r, context) + ); + } + } +} +module.exports = StatsFactory; /***/ }), -/***/ 70002: -/***/ (function(module) { +/***/ 30198: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -127381,50 +133594,254 @@ module.exports = memoize; -const SAFE_LIMIT = 0x80000000; -const SAFE_PART = SAFE_LIMIT - 1; -const COUNT = 4; -const arr = [0, 0, 0, 0, 0]; -const primes = [3, 7, 17, 19]; +const { HookMap, SyncWaterfallHook, SyncBailHook } = __webpack_require__(41242); -module.exports = (str, range) => { - arr.fill(0); - for (let i = 0; i < str.length; i++) { - const c = str.charCodeAt(i); - for (let j = 0; j < COUNT; j++) { - const p = (j + COUNT - 1) % COUNT; - arr[j] = (arr[j] + c * primes[j] + arr[p]) & SAFE_PART; +/** @template T @typedef {import("tapable").AsArray} AsArray */ +/** @typedef {import("tapable").Hook} Hook */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunk} StatsChunk */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunkGroup} StatsChunkGroup */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModule} StatsModule */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleReason} StatsModuleReason */ + +/** + * @typedef {Object} PrintedElement + * @property {string} element + * @property {string} content + */ + +/** + * @typedef {Object} KnownStatsPrinterContext + * @property {string=} type + * @property {StatsCompilation=} compilation + * @property {StatsChunkGroup=} chunkGroup + * @property {StatsAsset=} asset + * @property {StatsModule=} module + * @property {StatsChunk=} chunk + * @property {StatsModuleReason=} moduleReason + * @property {(str: string) => string=} bold + * @property {(str: string) => string=} yellow + * @property {(str: string) => string=} red + * @property {(str: string) => string=} green + * @property {(str: string) => string=} magenta + * @property {(str: string) => string=} cyan + * @property {(file: string, oversize?: boolean) => string=} formatFilename + * @property {(id: string) => string=} formatModuleId + * @property {(id: string, direction?: "parent"|"child"|"sibling") => string=} formatChunkId + * @property {(size: number) => string=} formatSize + * @property {(dateTime: number) => string=} formatDateTime + * @property {(flag: string) => string=} formatFlag + * @property {(time: number, boldQuantity?: boolean) => string=} formatTime + * @property {string=} chunkGroupKind + */ + +/** @typedef {KnownStatsPrinterContext & Record} StatsPrinterContext */ + +class StatsPrinter { + constructor() { + this.hooks = Object.freeze({ + /** @type {HookMap>} */ + sortElements: new HookMap( + () => new SyncBailHook(["elements", "context"]) + ), + /** @type {HookMap>} */ + printElements: new HookMap( + () => new SyncBailHook(["printedElements", "context"]) + ), + /** @type {HookMap>} */ + sortItems: new HookMap(() => new SyncBailHook(["items", "context"])), + /** @type {HookMap>} */ + getItemName: new HookMap(() => new SyncBailHook(["item", "context"])), + /** @type {HookMap>} */ + printItems: new HookMap( + () => new SyncBailHook(["printedItems", "context"]) + ), + /** @type {HookMap>} */ + print: new HookMap(() => new SyncBailHook(["object", "context"])), + /** @type {HookMap>} */ + result: new HookMap(() => new SyncWaterfallHook(["result", "context"])) + }); + /** @type {Map, Map>} */ + this._levelHookCache = new Map(); + this._inPrint = false; + } + + /** + * get all level hooks + * @private + * @template {Hook} T + * @param {HookMap} hookMap HookMap + * @param {string} type type + * @returns {T[]} hooks + */ + _getAllLevelHooks(hookMap, type) { + let cache = /** @type {Map} */ ( + this._levelHookCache.get(hookMap) + ); + if (cache === undefined) { + cache = new Map(); + this._levelHookCache.set(hookMap, cache); } - for (let j = 0; j < COUNT; j++) { - const q = arr[j] % COUNT; - arr[j] = arr[j] ^ (arr[q] >> 1); + const cacheEntry = cache.get(type); + if (cacheEntry !== undefined) { + return cacheEntry; + } + /** @type {T[]} */ + const hooks = []; + const typeParts = type.split("."); + for (let i = 0; i < typeParts.length; i++) { + const hook = hookMap.get(typeParts.slice(i).join(".")); + if (hook) { + hooks.push(hook); + } } + cache.set(type, hooks); + return hooks; } - if (range <= SAFE_PART) { - let sum = 0; - for (let j = 0; j < COUNT; j++) { - sum = (sum + arr[j]) % range; + + /** + * Run `fn` for each level + * @private + * @template T + * @template R + * @param {HookMap>} hookMap HookMap + * @param {string} type type + * @param {(hook: SyncBailHook) => R} fn function + * @returns {R} result of `fn` + */ + _forEachLevel(hookMap, type, fn) { + for (const hook of this._getAllLevelHooks(hookMap, type)) { + const result = fn(hook); + if (result !== undefined) return result; } - return sum; - } else { - let sum1 = 0; - let sum2 = 0; - const rangeExt = Math.floor(range / SAFE_LIMIT); - for (let j = 0; j < COUNT; j += 2) { - sum1 = (sum1 + arr[j]) & SAFE_PART; + } + + /** + * Run `fn` for each level + * @private + * @template T + * @param {HookMap>} hookMap HookMap + * @param {string} type type + * @param {AsArray[0]} data data + * @param {(hook: SyncWaterfallHook, data: AsArray[0]) => AsArray[0]} fn function + * @returns {AsArray[0]} result of `fn` + */ + _forEachLevelWaterfall(hookMap, type, data, fn) { + for (const hook of this._getAllLevelHooks(hookMap, type)) { + data = fn(hook, data); } - for (let j = 1; j < COUNT; j += 2) { - sum2 = (sum2 + arr[j]) % rangeExt; + return data; + } + + /** + * @param {string} type The type + * @param {Object} object Object to print + * @param {Object=} baseContext The base context + * @returns {string} printed result + */ + print(type, object, baseContext) { + if (this._inPrint) { + return this._print(type, object, baseContext); + } else { + try { + this._inPrint = true; + return this._print(type, object, baseContext); + } finally { + this._levelHookCache.clear(); + this._inPrint = false; + } } - return (sum2 * SAFE_LIMIT + sum1) % range; } -}; + + /** + * @private + * @param {string} type type + * @param {Object} object object + * @param {Object=} baseContext context + * @returns {string} printed result + */ + _print(type, object, baseContext) { + const context = { + ...baseContext, + type, + [type]: object + }; + + let printResult = this._forEachLevel(this.hooks.print, type, hook => + hook.call(object, context) + ); + if (printResult === undefined) { + if (Array.isArray(object)) { + const sortedItems = object.slice(); + this._forEachLevel(this.hooks.sortItems, type, h => + h.call(sortedItems, context) + ); + const printedItems = sortedItems.map((item, i) => { + const itemContext = { + ...context, + _index: i + }; + const itemName = this._forEachLevel( + this.hooks.getItemName, + `${type}[]`, + h => h.call(item, itemContext) + ); + if (itemName) itemContext[itemName] = item; + return this.print( + itemName ? `${type}[].${itemName}` : `${type}[]`, + item, + itemContext + ); + }); + printResult = this._forEachLevel(this.hooks.printItems, type, h => + h.call(printedItems, context) + ); + if (printResult === undefined) { + const result = printedItems.filter(Boolean); + if (result.length > 0) printResult = result.join("\n"); + } + } else if (object !== null && typeof object === "object") { + const elements = Object.keys(object).filter( + key => object[key] !== undefined + ); + this._forEachLevel(this.hooks.sortElements, type, h => + h.call(elements, context) + ); + const printedElements = elements.map(element => { + const content = this.print(`${type}.${element}`, object[element], { + ...context, + _parent: object, + _element: element, + [element]: object[element] + }); + return { element, content }; + }); + printResult = this._forEachLevel(this.hooks.printElements, type, h => + h.call(printedElements, context) + ); + if (printResult === undefined) { + const result = printedElements.map(e => e.content).filter(Boolean); + if (result.length > 0) printResult = result.join("\n"); + } + } + } + + return this._forEachLevelWaterfall( + this.hooks.result, + type, + printResult, + (h, r) => h.call(r, context) + ); + } +} +module.exports = StatsPrinter; /***/ }), -/***/ 42791: -/***/ (function(module) { +/***/ 84953: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -127434,66 +133851,34 @@ module.exports = (str, range) => { +exports.equals = (a, b) => { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; +}; + /** - * @template T - * @template {Error} E - * @param {Iterable} items initial items - * @param {number} concurrency number of items running in parallel - * @param {function(T, function(T): void, function(E=): void): void} processor worker which pushes more items - * @param {function(E=): void} callback all items processed - * @returns {void} + * + * @param {Array} arr Array of values to be partitioned + * @param {(value: any) => boolean} fn Partition function which partitions based on truthiness of result. + * @returns {[Array, Array]} returns the values of `arr` partitioned into two new arrays based on fn predicate. */ -const processAsyncTree = (items, concurrency, processor, callback) => { - const queue = Array.from(items); - if (queue.length === 0) return callback(); - let processing = 0; - let finished = false; - let processScheduled = true; - - const push = item => { - queue.push(item); - if (!processScheduled && processing < concurrency) { - processScheduled = true; - process.nextTick(processQueue); - } - }; - - const processorCallback = err => { - processing--; - if (err && !finished) { - finished = true; - callback(err); - return; - } - if (!processScheduled) { - processScheduled = true; - process.nextTick(processQueue); - } - }; - - const processQueue = () => { - if (finished) return; - while (processing < concurrency && queue.length > 0) { - processing++; - const item = queue.pop(); - processor(item, push, processorCallback); - } - processScheduled = false; - if (queue.length === 0 && processing === 0 && !finished) { - finished = true; - callback(); - } - }; - - processQueue(); +exports.groupBy = (arr = [], fn) => { + return arr.reduce( + (groups, value) => { + groups[fn(value) ? 0 : 1].push(value); + return groups; + }, + [[], []] + ); }; -module.exports = processAsyncTree; - /***/ }), -/***/ 54190: +/***/ 41792: /***/ (function(module) { "use strict"; @@ -127504,83 +133889,116 @@ module.exports = processAsyncTree; -const SAFE_IDENTIFIER = /^[_a-zA-Z$][_a-zA-Z$0-9]*$/; -const RESERVED_IDENTIFIER = new Set([ - "break", - "case", - "catch", - "class", - "const", - "continue", - "debugger", - "default", - "delete", - "do", - "else", - "export", - "extends", - "finally", - "for", - "function", - "if", - "import", - "in", - "instanceof", - "new", - "return", - "super", - "switch", - "this", - "throw", - "try", - "typeof", - "var", - "void", - "while", - "with", - "enum", - // strict mode - "implements", - "interface", - "let", - "package", - "private", - "protected", - "public", - "static", - "yield", - "yield", - // module code - "await", - // skip future reserved keywords defined under ES1 till ES3 - // additional - "null", - "true", - "false" -]); +/** + * @template T + */ +class ArrayQueue { + /** + * @param {Iterable=} items The initial elements. + */ + constructor(items) { + /** @private @type {T[]} */ + this._list = items ? Array.from(items) : []; + /** @private @type {T[]} */ + this._listReversed = []; + } + + /** + * Returns the number of elements in this queue. + * @returns {number} The number of elements in this queue. + */ + get length() { + return this._list.length + this._listReversed.length; + } -const propertyAccess = (properties, start = 0) => { - let str = ""; - for (let i = start; i < properties.length; i++) { - const p = properties[i]; - if (`${+p}` === p) { - str += `[${p}]`; - } else if (SAFE_IDENTIFIER.test(p) && !RESERVED_IDENTIFIER.has(p)) { - str += `.${p}`; + /** + * Empties the queue. + */ + clear() { + this._list.length = 0; + this._listReversed.length = 0; + } + + /** + * Appends the specified element to this queue. + * @param {T} item The element to add. + * @returns {void} + */ + enqueue(item) { + this._list.push(item); + } + + /** + * Retrieves and removes the head of this queue. + * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + */ + dequeue() { + if (this._listReversed.length === 0) { + if (this._list.length === 0) return undefined; + if (this._list.length === 1) return this._list.pop(); + if (this._list.length < 16) return this._list.shift(); + const temp = this._listReversed; + this._listReversed = this._list; + this._listReversed.reverse(); + this._list = temp; + } + return this._listReversed.pop(); + } + + /** + * Finds and removes an item + * @param {T} item the item + * @returns {void} + */ + delete(item) { + const i = this._list.indexOf(item); + if (i >= 0) { + this._list.splice(i, 1); } else { - str += `[${JSON.stringify(p)}]`; + const i = this._listReversed.indexOf(item); + if (i >= 0) this._listReversed.splice(i, 1); } } - return str; -}; -module.exports = propertyAccess; + [Symbol.iterator]() { + let i = -1; + let reversed = false; + return { + next: () => { + if (!reversed) { + i++; + if (i < this._list.length) { + return { + done: false, + value: this._list[i] + }; + } + reversed = true; + i = this._listReversed.length; + } + i--; + if (i < 0) { + return { + done: true, + value: undefined + }; + } + return { + done: false, + value: this._listReversed[i] + }; + } + }; + } +} + +module.exports = ArrayQueue; /***/ }), -/***/ 26611: -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { +/***/ 12260: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -127590,973 +134008,719 @@ module.exports = propertyAccess; -const { register } = __webpack_require__(8282); +const { SyncHook, AsyncSeriesHook } = __webpack_require__(41242); +const { makeWebpackError } = __webpack_require__(11351); +const WebpackError = __webpack_require__(53799); +const ArrayQueue = __webpack_require__(41792); -const Position = /** @type {TODO} */ (__webpack_require__(31988).Position); -const SourceLocation = (__webpack_require__(31988).SourceLocation); -const ValidationError = (__webpack_require__(54983)/* ["default"] */ .Z); -const { - CachedSource, - ConcatSource, - OriginalSource, - PrefixSource, - RawSource, - ReplaceSource, - SourceMapSource -} = __webpack_require__(51255); +const QUEUED_STATE = 0; +const PROCESSING_STATE = 1; +const DONE_STATE = 2; -/** @typedef {import("acorn").Position} Position */ -/** @typedef {import("../Dependency").RealDependencyLocation} RealDependencyLocation */ -/** @typedef {import("../Dependency").SourcePosition} SourcePosition */ -/** @typedef {import("./serialization").ObjectDeserializerContext} ObjectDeserializerContext */ -/** @typedef {import("./serialization").ObjectSerializerContext} ObjectSerializerContext */ +let inHandleResult = 0; -/** @typedef {ObjectSerializerContext & { writeLazy?: (any) => void }} WebpackObjectSerializerContext */ +/** + * @template T + * @callback Callback + * @param {(WebpackError | null)=} err + * @param {T=} result + */ -const CURRENT_MODULE = "webpack/lib/util/registerExternalSerializer"; +/** + * @template T + * @template K + * @template R + */ +class AsyncQueueEntry { + /** + * @param {T} item the item + * @param {Callback} callback the callback + */ + constructor(item, callback) { + this.item = item; + /** @type {typeof QUEUED_STATE | typeof PROCESSING_STATE | typeof DONE_STATE} */ + this.state = QUEUED_STATE; + this.callback = callback; + /** @type {Callback[] | undefined} */ + this.callbacks = undefined; + this.result = undefined; + /** @type {WebpackError | undefined} */ + this.error = undefined; + } +} -register( - CachedSource, - CURRENT_MODULE, - "webpack-sources/CachedSource", - new (class CachedSourceSerializer { - /** - * @param {CachedSource} source the cached source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write, writeLazy }) { - if (writeLazy) { - writeLazy(source.originalLazy()); +/** + * @template T + * @template K + * @template R + */ +class AsyncQueue { + /** + * @param {Object} options options object + * @param {string=} options.name name of the queue + * @param {number=} options.parallelism how many items should be processed at once + * @param {AsyncQueue=} options.parent parent queue, which will have priority over this queue and with shared parallelism + * @param {function(T): K=} options.getKey extract key from item + * @param {function(T, Callback): void} options.processor async function to process items + */ + constructor({ name, parallelism, parent, processor, getKey }) { + this._name = name; + this._parallelism = parallelism || 1; + this._processor = processor; + this._getKey = + getKey || /** @type {(T) => K} */ (item => /** @type {any} */ (item)); + /** @type {Map>} */ + this._entries = new Map(); + /** @type {ArrayQueue>} */ + this._queued = new ArrayQueue(); + /** @type {AsyncQueue[]} */ + this._children = undefined; + this._activeTasks = 0; + this._willEnsureProcessing = false; + this._needProcessing = false; + this._stopped = false; + this._root = parent ? parent._root : this; + if (parent) { + if (this._root._children === undefined) { + this._root._children = [this]; } else { - write(source.original()); + this._root._children.push(this); } - write(source.getCachedData()); - } - - /** - * @param {ObjectDeserializerContext} context context - * @returns {CachedSource} cached source - */ - deserialize({ read }) { - const source = read(); - const cachedData = read(); - return new CachedSource(source, cachedData); - } - })() -); - -register( - RawSource, - CURRENT_MODULE, - "webpack-sources/RawSource", - new (class RawSourceSerializer { - /** - * @param {RawSource} source the raw source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write }) { - write(source.buffer()); - write(!source.isBuffer()); - } - - /** - * @param {ObjectDeserializerContext} context context - * @returns {RawSource} raw source - */ - deserialize({ read }) { - const source = read(); - const convertToString = read(); - return new RawSource(source, convertToString); - } - })() -); - -register( - ConcatSource, - CURRENT_MODULE, - "webpack-sources/ConcatSource", - new (class ConcatSourceSerializer { - /** - * @param {ConcatSource} source the concat source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write }) { - write(source.getChildren()); - } - - /** - * @param {ObjectDeserializerContext} context context - * @returns {ConcatSource} concat source - */ - deserialize({ read }) { - const source = new ConcatSource(); - source.addAllSkipOptimizing(read()); - return source; } - })() -); -register( - PrefixSource, - CURRENT_MODULE, - "webpack-sources/PrefixSource", - new (class PrefixSourceSerializer { - /** - * @param {PrefixSource} source the prefix source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write }) { - write(source.getPrefix()); - write(source.original()); - } + this.hooks = { + /** @type {AsyncSeriesHook<[T]>} */ + beforeAdd: new AsyncSeriesHook(["item"]), + /** @type {SyncHook<[T]>} */ + added: new SyncHook(["item"]), + /** @type {AsyncSeriesHook<[T]>} */ + beforeStart: new AsyncSeriesHook(["item"]), + /** @type {SyncHook<[T]>} */ + started: new SyncHook(["item"]), + /** @type {SyncHook<[T, Error, R]>} */ + result: new SyncHook(["item", "error", "result"]) + }; - /** - * @param {ObjectDeserializerContext} context context - * @returns {PrefixSource} prefix source - */ - deserialize({ read }) { - return new PrefixSource(read(), read()); - } - })() -); + this._ensureProcessing = this._ensureProcessing.bind(this); + } -register( - ReplaceSource, - CURRENT_MODULE, - "webpack-sources/ReplaceSource", - new (class ReplaceSourceSerializer { - /** - * @param {ReplaceSource} source the replace source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write }) { - write(source.original()); - write(source.getName()); - const replacements = source.getReplacements(); - write(replacements.length); - for (const repl of replacements) { - write(repl.start); - write(repl.end); - } - for (const repl of replacements) { - write(repl.content); - write(repl.name); + /** + * @param {T} item an item + * @param {Callback} callback callback function + * @returns {void} + */ + add(item, callback) { + if (this._stopped) return callback(new WebpackError("Queue was stopped")); + this.hooks.beforeAdd.callAsync(item, err => { + if (err) { + callback( + makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeAdd`) + ); + return; } - } - - /** - * @param {ObjectDeserializerContext} context context - * @returns {ReplaceSource} replace source - */ - deserialize({ read }) { - const source = new ReplaceSource(read(), read()); - const len = read(); - const startEndBuffer = []; - for (let i = 0; i < len; i++) { - startEndBuffer.push(read(), read()); + const key = this._getKey(item); + const entry = this._entries.get(key); + if (entry !== undefined) { + if (entry.state === DONE_STATE) { + if (inHandleResult++ > 3) { + process.nextTick(() => callback(entry.error, entry.result)); + } else { + callback(entry.error, entry.result); + } + inHandleResult--; + } else if (entry.callbacks === undefined) { + entry.callbacks = [callback]; + } else { + entry.callbacks.push(callback); + } + return; } - let j = 0; - for (let i = 0; i < len; i++) { - source.replace( - startEndBuffer[j++], - startEndBuffer[j++], - read(), - read() + const newEntry = new AsyncQueueEntry(item, callback); + if (this._stopped) { + this.hooks.added.call(item); + this._root._activeTasks++; + process.nextTick(() => + this._handleResult(newEntry, new WebpackError("Queue was stopped")) ); + } else { + this._entries.set(key, newEntry); + this._queued.enqueue(newEntry); + const root = this._root; + root._needProcessing = true; + if (root._willEnsureProcessing === false) { + root._willEnsureProcessing = true; + setImmediate(root._ensureProcessing); + } + this.hooks.added.call(item); } - return source; - } - })() -); + }); + } -register( - OriginalSource, - CURRENT_MODULE, - "webpack-sources/OriginalSource", - new (class OriginalSourceSerializer { - /** - * @param {OriginalSource} source the original source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write }) { - write(source.buffer()); - write(source.getName()); + /** + * @param {T} item an item + * @returns {void} + */ + invalidate(item) { + const key = this._getKey(item); + const entry = this._entries.get(key); + this._entries.delete(key); + if (entry.state === QUEUED_STATE) { + this._queued.delete(entry); } + } - /** - * @param {ObjectDeserializerContext} context context - * @returns {OriginalSource} original source - */ - deserialize({ read }) { - const buffer = read(); - const name = read(); - return new OriginalSource(buffer, name); + /** + * Waits for an already started item + * @param {T} item an item + * @param {Callback} callback callback function + * @returns {void} + */ + waitFor(item, callback) { + const key = this._getKey(item); + const entry = this._entries.get(key); + if (entry === undefined) { + return callback( + new WebpackError( + "waitFor can only be called for an already started item" + ) + ); } - })() -); - -register( - SourceLocation, - CURRENT_MODULE, - "acorn/SourceLocation", - new (class SourceLocationSerializer { - /** - * @param {SourceLocation} loc the location to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(loc, { write }) { - write(loc.start.line); - write(loc.start.column); - write(loc.end.line); - write(loc.end.column); + if (entry.state === DONE_STATE) { + process.nextTick(() => callback(entry.error, entry.result)); + } else if (entry.callbacks === undefined) { + entry.callbacks = [callback]; + } else { + entry.callbacks.push(callback); } + } - /** - * @param {ObjectDeserializerContext} context context - * @returns {RealDependencyLocation} location - */ - deserialize({ read }) { - return { - start: { - line: read(), - column: read() - }, - end: { - line: read(), - column: read() - } - }; + /** + * @returns {void} + */ + stop() { + this._stopped = true; + const queue = this._queued; + this._queued = new ArrayQueue(); + const root = this._root; + for (const entry of queue) { + this._entries.delete(this._getKey(entry.item)); + root._activeTasks++; + this._handleResult(entry, new WebpackError("Queue was stopped")); } - })() -); + } -register( - Position, - CURRENT_MODULE, - "acorn/Position", - new (class PositionSerializer { - /** - * @param {Position} pos the position to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(pos, { write }) { - write(pos.line); - write(pos.column); + /** + * @returns {void} + */ + increaseParallelism() { + const root = this._root; + root._parallelism++; + /* istanbul ignore next */ + if (root._willEnsureProcessing === false && root._needProcessing) { + root._willEnsureProcessing = true; + setImmediate(root._ensureProcessing); } + } - /** - * @param {ObjectDeserializerContext} context context - * @returns {SourcePosition} position - */ - deserialize({ read }) { - return { - line: read(), - column: read() - }; - } - })() -); + /** + * @returns {void} + */ + decreaseParallelism() { + const root = this._root; + root._parallelism--; + } -register( - SourceMapSource, - CURRENT_MODULE, - "webpack-sources/SourceMapSource", - new (class SourceMapSourceSerializer { - /** - * @param {SourceMapSource} source the source map source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write }) { - write(source.getArgsAsBuffers()); - } + /** + * @param {T} item an item + * @returns {boolean} true, if the item is currently being processed + */ + isProcessing(item) { + const key = this._getKey(item); + const entry = this._entries.get(key); + return entry !== undefined && entry.state === PROCESSING_STATE; + } - /** - * @param {ObjectDeserializerContext} context context - * @returns {SourceMapSource} source source map source - */ - deserialize({ read }) { - // @ts-expect-error - return new SourceMapSource(...read()); - } - })() -); + /** + * @param {T} item an item + * @returns {boolean} true, if the item is currently queued + */ + isQueued(item) { + const key = this._getKey(item); + const entry = this._entries.get(key); + return entry !== undefined && entry.state === QUEUED_STATE; + } -register( - ValidationError, - CURRENT_MODULE, - "schema-utils/ValidationError", - new (class ValidationErrorSerializer { - // TODO error should be ValidationError, but this fails the type checks - /** - * @param {TODO} error the source map source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(error, { write }) { - write(error.errors); - write(error.schema); - write({ - name: error.headerName, - baseDataPath: error.baseDataPath, - postFormatter: error.postFormatter - }); - } + /** + * @param {T} item an item + * @returns {boolean} true, if the item is currently queued + */ + isDone(item) { + const key = this._getKey(item); + const entry = this._entries.get(key); + return entry !== undefined && entry.state === DONE_STATE; + } - /** - * @param {ObjectDeserializerContext} context context - * @returns {TODO} error - */ - deserialize({ read }) { - return new ValidationError(read(), read(), read()); + /** + * @returns {void} + */ + _ensureProcessing() { + while (this._activeTasks < this._parallelism) { + const entry = this._queued.dequeue(); + if (entry === undefined) break; + this._activeTasks++; + entry.state = PROCESSING_STATE; + this._startProcessing(entry); } - })() -); - - -/***/ }), - -/***/ 17156: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + this._willEnsureProcessing = false; + if (this._queued.length > 0) return; + if (this._children !== undefined) { + for (const child of this._children) { + while (this._activeTasks < this._parallelism) { + const entry = child._queued.dequeue(); + if (entry === undefined) break; + this._activeTasks++; + entry.state = PROCESSING_STATE; + child._startProcessing(entry); + } + if (child._queued.length > 0) return; + } + } + if (!this._willEnsureProcessing) this._needProcessing = false; + } + /** + * @param {AsyncQueueEntry} entry the entry + * @returns {void} + */ + _startProcessing(entry) { + this.hooks.beforeStart.callAsync(entry.item, err => { + if (err) { + this._handleResult( + entry, + makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeStart`) + ); + return; + } + let inCallback = false; + try { + this._processor(entry.item, (e, r) => { + inCallback = true; + this._handleResult(entry, e, r); + }); + } catch (err) { + if (inCallback) throw err; + this._handleResult(entry, err, null); + } + this.hooks.started.call(entry.item); + }); + } -const SortableSet = __webpack_require__(13098); + /** + * @param {AsyncQueueEntry} entry the entry + * @param {WebpackError=} err error, if any + * @param {R=} result result, if any + * @returns {void} + */ + _handleResult(entry, err, result) { + this.hooks.result.callAsync(entry.item, err, result, hookError => { + const error = hookError + ? makeWebpackError(hookError, `AsyncQueue(${this._name}).hooks.result`) + : err; -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */ + const callback = entry.callback; + const callbacks = entry.callbacks; + entry.state = DONE_STATE; + entry.callback = undefined; + entry.callbacks = undefined; + entry.result = result; + entry.error = error; -/** @typedef {string | SortableSet | undefined} RuntimeSpec */ -/** @typedef {RuntimeSpec | boolean} RuntimeCondition */ + const root = this._root; + root._activeTasks--; + if (root._willEnsureProcessing === false && root._needProcessing) { + root._willEnsureProcessing = true; + setImmediate(root._ensureProcessing); + } -/** - * @param {Compilation} compilation the compilation - * @param {string} name name of the entry - * @param {EntryOptions=} options optionally already received entry options - * @returns {RuntimeSpec} runtime - */ -exports.getEntryRuntime = (compilation, name, options) => { - let dependOn; - let runtime; - if (options) { - ({ dependOn, runtime } = options); - } else { - const entry = compilation.entries.get(name); - if (!entry) return name; - ({ dependOn, runtime } = entry.options); - } - if (dependOn) { - /** @type {RuntimeSpec} */ - let result = undefined; - const queue = new Set(dependOn); - for (const name of queue) { - const dep = compilation.entries.get(name); - if (!dep) continue; - const { dependOn, runtime } = dep.options; - if (dependOn) { - for (const name of dependOn) { - queue.add(name); - } + if (inHandleResult++ > 3) { + process.nextTick(() => { + callback(error, result); + if (callbacks !== undefined) { + for (const callback of callbacks) { + callback(error, result); + } + } + }); } else { - result = mergeRuntimeOwned(result, runtime || name); + callback(error, result); + if (callbacks !== undefined) { + for (const callback of callbacks) { + callback(error, result); + } + } } - } - return result || name; - } else { - return runtime || name; + inHandleResult--; + }); } -}; -/** - * @param {RuntimeSpec} runtime runtime - * @param {function(string): void} fn functor - * @param {boolean} deterministicOrder enforce a deterministic order - * @returns {void} - */ -exports.forEachRuntime = (runtime, fn, deterministicOrder = false) => { - if (runtime === undefined) { - fn(undefined); - } else if (typeof runtime === "string") { - fn(runtime); - } else { - if (deterministicOrder) runtime.sort(); - for (const r of runtime) { - fn(r); - } + clear() { + this._entries.clear(); + this._queued.clear(); + this._activeTasks = 0; + this._willEnsureProcessing = false; + this._needProcessing = false; + this._stopped = false; } -}; - -const getRuntimesKey = set => { - set.sort(); - return Array.from(set).join("\n"); -}; - -/** - * @param {RuntimeSpec} runtime runtime(s) - * @returns {string} key of runtimes - */ -const getRuntimeKey = runtime => { - if (runtime === undefined) return "*"; - if (typeof runtime === "string") return runtime; - return runtime.getFromUnorderedCache(getRuntimesKey); -}; -exports.getRuntimeKey = getRuntimeKey; - -/** - * @param {string} key key of runtimes - * @returns {RuntimeSpec} runtime(s) - */ -const keyToRuntime = key => { - if (key === "*") return undefined; - const items = key.split("\n"); - if (items.length === 1) return items[0]; - return new SortableSet(items); -}; -exports.keyToRuntime = keyToRuntime; +} -const getRuntimesString = set => { - set.sort(); - return Array.from(set).join("+"); -}; +module.exports = AsyncQueue; -/** - * @param {RuntimeSpec} runtime runtime(s) - * @returns {string} readable version - */ -const runtimeToString = runtime => { - if (runtime === undefined) return "*"; - if (typeof runtime === "string") return runtime; - return runtime.getFromUnorderedCache(getRuntimesString); -}; -exports.runtimeToString = runtimeToString; -/** - * @param {RuntimeCondition} runtimeCondition runtime condition - * @returns {string} readable version - */ -exports.runtimeConditionToString = runtimeCondition => { - if (runtimeCondition === true) return "true"; - if (runtimeCondition === false) return "false"; - return runtimeToString(runtimeCondition); -}; +/***/ }), -/** - * @param {RuntimeSpec} a first - * @param {RuntimeSpec} b second - * @returns {boolean} true, when they are equal - */ -const runtimeEqual = (a, b) => { - if (a === b) { - return true; - } else if ( - a === undefined || - b === undefined || - typeof a === "string" || - typeof b === "string" - ) { - return false; - } else if (a.size !== b.size) { - return false; - } else { - a.sort(); - b.sort(); - const aIt = a[Symbol.iterator](); - const bIt = b[Symbol.iterator](); - for (;;) { - const aV = aIt.next(); - if (aV.done) return true; - const bV = bIt.next(); - if (aV.value !== bV.value) return false; - } - } -}; -exports.runtimeEqual = runtimeEqual; +/***/ 36692: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * @param {RuntimeSpec} a first - * @param {RuntimeSpec} b second - * @returns {-1|0|1} compare - */ -exports.compareRuntime = (a, b) => { - if (a === b) { - return 0; - } else if (a === undefined) { - return -1; - } else if (b === undefined) { - return 1; - } else { - const aKey = getRuntimeKey(a); - const bKey = getRuntimeKey(b); - if (aKey < bKey) return -1; - if (aKey > bKey) return 1; - return 0; - } -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * @param {RuntimeSpec} a first - * @param {RuntimeSpec} b second - * @returns {RuntimeSpec} merged - */ -const mergeRuntime = (a, b) => { - if (a === undefined) { - return b; - } else if (b === undefined) { - return a; - } else if (a === b) { - return a; - } else if (typeof a === "string") { - if (typeof b === "string") { - const set = new SortableSet(); - set.add(a); - set.add(b); - return set; - } else if (b.has(a)) { - return b; - } else { - const set = new SortableSet(b); - set.add(a); - return set; - } - } else { - if (typeof b === "string") { - if (a.has(b)) return a; - const set = new SortableSet(a); - set.add(b); - return set; - } else { - const set = new SortableSet(a); - for (const item of b) set.add(item); - if (set.size === a.size) return a; - return set; - } - } -}; -exports.mergeRuntime = mergeRuntime; -/** - * @param {RuntimeCondition} a first - * @param {RuntimeCondition} b second - * @param {RuntimeSpec} runtime full runtime - * @returns {RuntimeCondition} result - */ -exports.mergeRuntimeCondition = (a, b, runtime) => { - if (a === false) return b; - if (b === false) return a; - if (a === true || b === true) return true; - const merged = mergeRuntime(a, b); - if (merged === undefined) return undefined; - if (typeof merged === "string") { - if (typeof runtime === "string" && merged === runtime) return true; - return merged; - } - if (typeof runtime === "string" || runtime === undefined) return merged; - if (merged.size === runtime.size) return true; - return merged; -}; -/** - * @param {RuntimeSpec | true} a first - * @param {RuntimeSpec | true} b second - * @param {RuntimeSpec} runtime full runtime - * @returns {RuntimeSpec | true} result - */ -exports.mergeRuntimeConditionNonFalse = (a, b, runtime) => { - if (a === true || b === true) return true; - const merged = mergeRuntime(a, b); - if (merged === undefined) return undefined; - if (typeof merged === "string") { - if (typeof runtime === "string" && merged === runtime) return true; - return merged; +class Hash { + /* istanbul ignore next */ + /** + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @abstract + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash + */ + update(data, inputEncoding) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } - if (typeof runtime === "string" || runtime === undefined) return merged; - if (merged.size === runtime.size) return true; - return merged; -}; -/** - * @param {RuntimeSpec} a first (may be modified) - * @param {RuntimeSpec} b second - * @returns {RuntimeSpec} merged - */ -const mergeRuntimeOwned = (a, b) => { - if (b === undefined) { - return a; - } else if (a === b) { - return a; - } else if (a === undefined) { - if (typeof b === "string") { - return b; - } else { - return new SortableSet(b); - } - } else if (typeof a === "string") { - if (typeof b === "string") { - const set = new SortableSet(); - set.add(a); - set.add(b); - return set; - } else { - const set = new SortableSet(b); - set.add(a); - return set; - } - } else { - if (typeof b === "string") { - a.add(b); - return a; - } else { - for (const item of b) a.add(item); - return a; - } + /* istanbul ignore next */ + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @abstract + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } -}; -exports.mergeRuntimeOwned = mergeRuntimeOwned; +} + +module.exports = Hash; + + +/***/ }), + +/***/ 39104: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + /** - * @param {RuntimeSpec} a first - * @param {RuntimeSpec} b second - * @returns {RuntimeSpec} merged + * @template T + * @param {Iterable} set a set + * @returns {T | undefined} last item */ -exports.intersectRuntime = (a, b) => { - if (a === undefined) { - return b; - } else if (b === undefined) { - return a; - } else if (a === b) { - return a; - } else if (typeof a === "string") { - if (typeof b === "string") { - return undefined; - } else if (b.has(a)) { - return a; - } else { - return undefined; - } - } else { - if (typeof b === "string") { - if (a.has(b)) return b; - return undefined; - } else { - const set = new SortableSet(); - for (const item of b) { - if (a.has(item)) set.add(item); - } - if (set.size === 0) return undefined; - if (set.size === 1) for (const item of set) return item; - return set; - } - } +const last = set => { + let last; + for (const item of set) last = item; + return last; }; /** - * @param {RuntimeSpec} a first - * @param {RuntimeSpec} b second - * @returns {RuntimeSpec} result + * @template T + * @param {Iterable} iterable iterable + * @param {function(T): boolean} filter predicate + * @returns {boolean} true, if some items match the filter predicate */ -const subtractRuntime = (a, b) => { - if (a === undefined) { - return undefined; - } else if (b === undefined) { - return a; - } else if (a === b) { - return undefined; - } else if (typeof a === "string") { - if (typeof b === "string") { - return a; - } else if (b.has(a)) { - return undefined; - } else { - return a; - } - } else { - if (typeof b === "string") { - if (!a.has(b)) return a; - if (a.size === 2) { - for (const item of a) { - if (item !== b) return item; - } - } - const set = new SortableSet(a); - set.delete(b); - } else { - const set = new SortableSet(); - for (const item of a) { - if (!b.has(item)) set.add(item); - } - if (set.size === 0) return undefined; - if (set.size === 1) for (const item of set) return item; - return set; - } +const someInIterable = (iterable, filter) => { + for (const item of iterable) { + if (filter(item)) return true; } + return false; }; -exports.subtractRuntime = subtractRuntime; /** - * @param {RuntimeCondition} a first - * @param {RuntimeCondition} b second - * @param {RuntimeSpec} runtime runtime - * @returns {RuntimeCondition} result + * @template T + * @param {Iterable} iterable an iterable + * @returns {number} count of items */ -exports.subtractRuntimeCondition = (a, b, runtime) => { - if (b === true) return false; - if (b === false) return a; - if (a === false) return false; - const result = subtractRuntime(a === true ? runtime : a, b); - return result === undefined ? false : result; +const countIterable = iterable => { + let i = 0; + // eslint-disable-next-line no-unused-vars + for (const _ of iterable) i++; + return i; }; -/** - * @param {RuntimeSpec} runtime runtime - * @param {function(RuntimeSpec): boolean} filter filter function - * @returns {boolean | RuntimeSpec} true/false if filter is constant for all runtimes, otherwise runtimes that are active - */ -exports.filterRuntime = (runtime, filter) => { - if (runtime === undefined) return filter(undefined); - if (typeof runtime === "string") return filter(runtime); - let some = false; - let every = true; - let result = undefined; - for (const r of runtime) { - const v = filter(r); - if (v) { - some = true; - result = mergeRuntimeOwned(result, r); - } else { - every = false; - } - } - if (!some) return false; - if (every) return true; - return result; -}; +exports.last = last; +exports.someInIterable = someInIterable; +exports.countIterable = countIterable; + + +/***/ }), + +/***/ 48424: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { first } = __webpack_require__(93347); +const SortableSet = __webpack_require__(13098); /** + * Multi layer bucket sorted set: + * Supports adding non-existing items (DO NOT ADD ITEM TWICE), + * Supports removing exiting items (DO NOT REMOVE ITEM NOT IN SET), + * Supports popping the first items according to defined order, + * Supports iterating all items without order, + * Supports updating an item in an efficient way, + * Supports size property, which is the number of items, + * Items are lazy partially sorted when needed * @template T + * @template K */ -class RuntimeSpecMap { +class LazyBucketSortedSet { /** - * @param {RuntimeSpecMap=} clone copy form this + * @param {function(T): K} getKey function to get key from item + * @param {function(K, K): number} comparator comparator to sort keys + * @param {...((function(T): any) | (function(any, any): number))} args more pairs of getKey and comparator plus optional final comparator for the last layer */ - constructor(clone) { - this._mode = clone ? clone._mode : 0; // 0 = empty, 1 = single entry, 2 = map - /** @type {RuntimeSpec} */ - this._singleRuntime = clone ? clone._singleRuntime : undefined; - /** @type {T} */ - this._singleValue = clone ? clone._singleValue : undefined; - /** @type {Map | undefined} */ - this._map = clone && clone._map ? new Map(clone._map) : undefined; + constructor(getKey, comparator, ...args) { + this._getKey = getKey; + this._innerArgs = args; + this._leaf = args.length <= 1; + this._keys = new SortableSet(undefined, comparator); + /** @type {Map | SortableSet>} */ + this._map = new Map(); + this._unsortedItems = new Set(); + this.size = 0; } /** - * @param {RuntimeSpec} runtime the runtimes - * @returns {T} value + * @param {T} item an item + * @returns {void} */ - get(runtime) { - switch (this._mode) { - case 0: - return undefined; - case 1: - return runtimeEqual(this._singleRuntime, runtime) - ? this._singleValue - : undefined; - default: - return this._map.get(getRuntimeKey(runtime)); - } + add(item) { + this.size++; + this._unsortedItems.add(item); } /** - * @param {RuntimeSpec} runtime the runtimes - * @returns {boolean} true, when the runtime is stored + * @param {K} key key of item + * @param {T} item the item + * @returns {void} */ - has(runtime) { - switch (this._mode) { - case 0: - return false; - case 1: - return runtimeEqual(this._singleRuntime, runtime); - default: - return this._map.has(getRuntimeKey(runtime)); + _addInternal(key, item) { + let entry = this._map.get(key); + if (entry === undefined) { + entry = this._leaf + ? new SortableSet(undefined, this._innerArgs[0]) + : new /** @type {any} */ (LazyBucketSortedSet)(...this._innerArgs); + this._keys.add(key); + this._map.set(key, entry); } + entry.add(item); } - set(runtime, value) { - switch (this._mode) { - case 0: - this._mode = 1; - this._singleRuntime = runtime; - this._singleValue = value; - break; - case 1: - if (runtimeEqual(this._singleRuntime, runtime)) { - this._singleValue = value; - break; - } - this._mode = 2; - this._map = new Map(); - this._map.set(getRuntimeKey(this._singleRuntime), this._singleValue); - this._singleRuntime = undefined; - this._singleValue = undefined; - /* falls through */ - default: - this._map.set(getRuntimeKey(runtime), value); + /** + * @param {T} item an item + * @returns {void} + */ + delete(item) { + this.size--; + if (this._unsortedItems.has(item)) { + this._unsortedItems.delete(item); + return; } - } - - provide(runtime, computer) { - switch (this._mode) { - case 0: - this._mode = 1; - this._singleRuntime = runtime; - return (this._singleValue = computer()); - case 1: { - if (runtimeEqual(this._singleRuntime, runtime)) { - return this._singleValue; - } - this._mode = 2; - this._map = new Map(); - this._map.set(getRuntimeKey(this._singleRuntime), this._singleValue); - this._singleRuntime = undefined; - this._singleValue = undefined; - const newValue = computer(); - this._map.set(getRuntimeKey(runtime), newValue); - return newValue; - } - default: { - const key = getRuntimeKey(runtime); - const value = this._map.get(key); - if (value !== undefined) return value; - const newValue = computer(); - this._map.set(key, newValue); - return newValue; - } + const key = this._getKey(item); + const entry = this._map.get(key); + entry.delete(item); + if (entry.size === 0) { + this._deleteKey(key); } } - delete(runtime) { - switch (this._mode) { - case 0: - return; - case 1: - if (runtimeEqual(this._singleRuntime, runtime)) { - this._mode = 0; - this._singleRuntime = undefined; - this._singleValue = undefined; - } - return; - default: - this._map.delete(getRuntimeKey(runtime)); - } + /** + * @param {K} key key to be removed + * @returns {void} + */ + _deleteKey(key) { + this._keys.delete(key); + this._map.delete(key); } - update(runtime, fn) { - switch (this._mode) { - case 0: - throw new Error("runtime passed to update must exist"); - case 1: { - if (runtimeEqual(this._singleRuntime, runtime)) { - this._singleValue = fn(this._singleValue); - break; - } - const newValue = fn(undefined); - if (newValue !== undefined) { - this._mode = 2; - this._map = new Map(); - this._map.set(getRuntimeKey(this._singleRuntime), this._singleValue); - this._singleRuntime = undefined; - this._singleValue = undefined; - this._map.set(getRuntimeKey(runtime), newValue); - } - break; + /** + * @returns {T | undefined} an item + */ + popFirst() { + if (this.size === 0) return undefined; + this.size--; + if (this._unsortedItems.size > 0) { + for (const item of this._unsortedItems) { + const key = this._getKey(item); + this._addInternal(key, item); } - default: { - const key = getRuntimeKey(runtime); - const oldValue = this._map.get(key); - const newValue = fn(oldValue); - if (newValue !== oldValue) this._map.set(key, newValue); + this._unsortedItems.clear(); + } + this._keys.sort(); + const key = first(this._keys); + const entry = this._map.get(key); + if (this._leaf) { + const leafEntry = /** @type {SortableSet} */ (entry); + leafEntry.sort(); + const item = first(leafEntry); + leafEntry.delete(item); + if (leafEntry.size === 0) { + this._deleteKey(key); + } + return item; + } else { + const nodeEntry = /** @type {LazyBucketSortedSet} */ (entry); + const item = nodeEntry.popFirst(); + if (nodeEntry.size === 0) { + this._deleteKey(key); } + return item; } } - keys() { - switch (this._mode) { - case 0: - return []; - case 1: - return [this._singleRuntime]; - default: - return Array.from(this._map.keys(), keyToRuntime); + /** + * @param {T} item to be updated item + * @returns {function(true=): void} finish update + */ + startUpdate(item) { + if (this._unsortedItems.has(item)) { + return remove => { + if (remove) { + this._unsortedItems.delete(item); + this.size--; + return; + } + }; } - } - - values() { - switch (this._mode) { - case 0: - return [][Symbol.iterator](); - case 1: - return [this._singleValue][Symbol.iterator](); - default: - return this._map.values(); + const key = this._getKey(item); + if (this._leaf) { + const oldEntry = /** @type {SortableSet} */ (this._map.get(key)); + return remove => { + if (remove) { + this.size--; + oldEntry.delete(item); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + return; + } + const newKey = this._getKey(item); + if (key === newKey) { + // This flags the sortable set as unordered + oldEntry.add(item); + } else { + oldEntry.delete(item); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + this._addInternal(newKey, item); + } + }; + } else { + const oldEntry = /** @type {LazyBucketSortedSet} */ ( + this._map.get(key) + ); + const finishUpdate = oldEntry.startUpdate(item); + return remove => { + if (remove) { + this.size--; + finishUpdate(true); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + return; + } + const newKey = this._getKey(item); + if (key === newKey) { + finishUpdate(); + } else { + finishUpdate(true); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + this._addInternal(newKey, item); + } + }; } } - get size() { - if (this._mode <= 1) return this._mode; - return this._map.size; - } -} - -exports.RuntimeSpecMap = RuntimeSpecMap; - -class RuntimeSpecSet { - constructor(iterable) { - /** @type {Map} */ - this._map = new Map(); - if (iterable) { - for (const item of iterable) { - this.add(item); + /** + * @param {Iterator[]} iterators list of iterators to append to + * @returns {void} + */ + _appendIterators(iterators) { + if (this._unsortedItems.size > 0) + iterators.push(this._unsortedItems[Symbol.iterator]()); + for (const key of this._keys) { + const entry = this._map.get(key); + if (this._leaf) { + const leafEntry = /** @type {SortableSet} */ (entry); + const iterator = leafEntry[Symbol.iterator](); + iterators.push(iterator); + } else { + const nodeEntry = /** @type {LazyBucketSortedSet} */ (entry); + nodeEntry._appendIterators(iterators); } } } - add(runtime) { - this._map.set(getRuntimeKey(runtime), runtime); - } - - has(runtime) { - return this._map.has(getRuntimeKey(runtime)); - } - + /** + * @returns {Iterator} the iterator + */ [Symbol.iterator]() { - return this._map.values(); - } - - get size() { - return this._map.size; + const iterators = []; + this._appendIterators(iterators); + iterators.reverse(); + let currentIterator = iterators.pop(); + return { + next: () => { + const res = currentIterator.next(); + if (res.done) { + if (iterators.length === 0) return res; + currentIterator = iterators.pop(); + return currentIterator.next(); + } + return res; + } + }; } } -exports.RuntimeSpecSet = RuntimeSpecSet; +module.exports = LazyBucketSortedSet; /***/ }), -/***/ 19702: -/***/ (function(__unused_webpack_module, exports) { +/***/ 38938: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -128566,617 +134730,309 @@ exports.RuntimeSpecSet = RuntimeSpecSet; -/** @typedef {(string|number|undefined|[])[]} SemVerRange */ +const makeSerializable = __webpack_require__(33032); /** - * @param {string} str version string - * @returns {(string|number|undefined|[])[]} parsed version + * @template T + * @param {Set} targetSet set where items should be added + * @param {Set>} toMerge iterables to be merged + * @returns {void} */ -const parseVersion = str => { - var splitAndConvert = function (str) { - return str.split(".").map(function (item) { - // eslint-disable-next-line eqeqeq - return +item == item ? +item : item; - }); - }; - var match = /^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str); - /** @type {(string|number|undefined|[])[]} */ - var ver = match[1] ? splitAndConvert(match[1]) : []; - if (match[2]) { - ver.length++; - ver.push.apply(ver, splitAndConvert(match[2])); - } - if (match[3]) { - ver.push([]); - ver.push.apply(ver, splitAndConvert(match[3])); +const merge = (targetSet, toMerge) => { + for (const set of toMerge) { + for (const item of set) { + targetSet.add(item); + } } - return ver; }; -exports.parseVersion = parseVersion; -/* eslint-disable eqeqeq */ /** - * @param {string} a version - * @param {string} b version - * @returns {boolean} true, iff a < b + * @template T + * @param {Set>} targetSet set where iterables should be added + * @param {Array>} toDeepMerge lazy sets to be flattened + * @returns {void} */ -const versionLt = (a, b) => { - // @ts-expect-error - a = parseVersion(a); - // @ts-expect-error - b = parseVersion(b); - var i = 0; - for (;;) { - // a b EOA object undefined number string - // EOA a == b a < b b < a a < b a < b - // object b < a (0) b < a a < b a < b - // undefined a < b a < b (0) a < b a < b - // number b < a b < a b < a (1) a < b - // string b < a b < a b < a b < a (1) - // EOA end of array - // (0) continue on - // (1) compare them via "<" - - // Handles first row in table - if (i >= a.length) return i < b.length && (typeof b[i])[0] != "u"; - - var aValue = a[i]; - var aType = (typeof aValue)[0]; - - // Handles first column in table - if (i >= b.length) return aType == "u"; - - var bValue = b[i]; - var bType = (typeof bValue)[0]; - - if (aType == bType) { - if (aType != "o" && aType != "u" && aValue != bValue) { - return aValue < bValue; +const flatten = (targetSet, toDeepMerge) => { + for (const set of toDeepMerge) { + if (set._set.size > 0) targetSet.add(set._set); + if (set._needMerge) { + for (const mergedSet of set._toMerge) { + targetSet.add(mergedSet); } - i++; - } else { - // Handles remaining cases - if (aType == "o" && bType == "n") return true; - return bType == "s" || aType == "u"; + flatten(targetSet, set._toDeepMerge); } } }; -/* eslint-enable eqeqeq */ -exports.versionLt = versionLt; /** - * @param {string} str range string - * @returns {SemVerRange} parsed range + * Like Set but with an addAll method to eventually add items from another iterable. + * Access methods make sure that all delayed operations are executed. + * Iteration methods deopts to normal Set performance until clear is called again (because of the chance of modifications during iteration). + * @template T */ -exports.parseRange = str => { - const splitAndConvert = str => { - return str.split(".").map(item => (`${+item}` === item ? +item : item)); - }; - // see https://docs.npmjs.com/misc/semver#range-grammar for grammar - const parsePartial = str => { - const match = /^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str); - /** @type {(string|number|undefined|[])[]} */ - const ver = match[1] ? [0, ...splitAndConvert(match[1])] : [0]; - if (match[2]) { - ver.length++; - ver.push.apply(ver, splitAndConvert(match[2])); - } +class LazySet { + /** + * @param {Iterable=} iterable init iterable + */ + constructor(iterable) { + /** @type {Set} */ + this._set = new Set(iterable); + /** @type {Set>} */ + this._toMerge = new Set(); + /** @type {Array>} */ + this._toDeepMerge = []; + this._needMerge = false; + this._deopt = false; + } - // remove trailing any matchers - let last = ver[ver.length - 1]; - while ( - ver.length && - (last === undefined || /^[*xX]$/.test(/** @type {string} */ (last))) - ) { - ver.pop(); - last = ver[ver.length - 1]; - } + _flatten() { + flatten(this._toMerge, this._toDeepMerge); + this._toDeepMerge.length = 0; + } - return ver; - }; - const toFixed = range => { - if (range.length === 1) { - // Special case for "*" is "x.x.x" instead of "=" - return [0]; - } else if (range.length === 2) { - // Special case for "1" is "1.x.x" instead of "=1" - return [1, ...range.slice(1)]; - } else if (range.length === 3) { - // Special case for "1.2" is "1.2.x" instead of "=1.2" - return [2, ...range.slice(1)]; + _merge() { + this._flatten(); + merge(this._set, this._toMerge); + this._toMerge.clear(); + this._needMerge = false; + } + + _isEmpty() { + return ( + this._set.size === 0 && + this._toMerge.size === 0 && + this._toDeepMerge.length === 0 + ); + } + + get size() { + if (this._needMerge) this._merge(); + return this._set.size; + } + + /** + * @param {T} item an item + * @returns {this} itself + */ + add(item) { + this._set.add(item); + return this; + } + + /** + * @param {Iterable | LazySet} iterable a immutable iterable or another immutable LazySet which will eventually be merged into the Set + * @returns {this} itself + */ + addAll(iterable) { + if (this._deopt) { + const _set = this._set; + for (const item of iterable) { + _set.add(item); + } } else { - return [range.length, ...range.slice(1)]; - } - }; - const negate = range => { - return [-range[0] - 1, ...range.slice(1)]; - }; - const parseSimple = str => { - // simple ::= primitive | partial | tilde | caret - // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial - // tilde ::= '~' partial - // caret ::= '^' partial - const match = /^(\^|~|<=|<|>=|>|=|v|!)/.exec(str); - const start = match ? match[0] : ""; - const remainder = parsePartial(str.slice(start.length)); - switch (start) { - case "^": - if (remainder.length > 1 && remainder[1] === 0) { - if (remainder.length > 2 && remainder[2] === 0) { - return [3, ...remainder.slice(1)]; - } - return [2, ...remainder.slice(1)]; + if (iterable instanceof LazySet) { + if (iterable._isEmpty()) return this; + this._toDeepMerge.push(iterable); + this._needMerge = true; + if (this._toDeepMerge.length > 100000) { + this._flatten(); } - return [1, ...remainder.slice(1)]; - case "~": - return [2, ...remainder.slice(1)]; - case ">=": - return remainder; - case "=": - case "v": - case "": - return toFixed(remainder); - case "<": - return negate(remainder); - case ">": { - // and( >=, not( = ) ) => >=, =, not, and - const fixed = toFixed(remainder); - // eslint-disable-next-line no-sparse-arrays - return [, fixed, 0, remainder, 2]; - } - case "<=": - // or( <, = ) => <, =, or - // eslint-disable-next-line no-sparse-arrays - return [, toFixed(remainder), negate(remainder), 1]; - case "!": { - // not = - const fixed = toFixed(remainder); - // eslint-disable-next-line no-sparse-arrays - return [, fixed, 0]; - } - default: - throw new Error("Unexpected start value"); - } - }; - const combine = (items, fn) => { - if (items.length === 1) return items[0]; - const arr = []; - for (const item of items.slice().reverse()) { - if (0 in item) { - arr.push(item); } else { - arr.push(...item.slice(1)); + this._toMerge.add(iterable); + this._needMerge = true; } + if (this._toMerge.size > 100000) this._merge(); } - // eslint-disable-next-line no-sparse-arrays - return [, ...arr, ...items.slice(1).map(() => fn)]; - }; - const parseRange = str => { - // range ::= hyphen | simple ( ' ' simple ) * | '' - // hyphen ::= partial ' - ' partial - const items = str.split(" - "); - if (items.length === 1) { - const items = str.trim().split(/\s+/g).map(parseSimple); - return combine(items, 2); - } - const a = parsePartial(items[0]); - const b = parsePartial(items[1]); - // >=a <=b => and( >=a, or( >=a, { - // range-set ::= range ( logical-or range ) * - // logical-or ::= ( ' ' ) * '||' ( ' ' ) * - const items = str.split(/\s*\|\|\s*/).map(parseRange); - return combine(items, 1); - }; - return parseLogicalOr(str); -}; - -/* eslint-disable eqeqeq */ -const rangeToString = range => { - var fixCount = range[0]; - var str = ""; - if (range.length === 1) { - return "*"; - } else if (fixCount + 0.5) { - str += - fixCount == 0 - ? ">=" - : fixCount == -1 - ? "<" - : fixCount == 1 - ? "^" - : fixCount == 2 - ? "~" - : fixCount > 0 - ? "=" - : "!="; - var needDot = 1; - // eslint-disable-next-line no-redeclare - for (var i = 1; i < range.length; i++) { - var item = range[i]; - var t = (typeof item)[0]; - needDot--; - str += - t == "u" - ? // undefined: prerelease marker, add an "-" - "-" - : // number or string: add the item, set flag to add an "." between two of them - (needDot > 0 ? "." : "") + ((needDot = 2), item); - } - return str; - } else { - var stack = []; - // eslint-disable-next-line no-redeclare - for (var i = 1; i < range.length; i++) { - // eslint-disable-next-line no-redeclare - var item = range[i]; - stack.push( - item === 0 - ? "not(" + pop() + ")" - : item === 1 - ? "(" + pop() + " || " + pop() + ")" - : item === 2 - ? stack.pop() + " " + stack.pop() - : rangeToString(item) - ); - } - return pop(); - } - function pop() { - return stack.pop().replace(/^\((.+)\)$/, "$1"); + return this; } -}; -/* eslint-enable eqeqeq */ -exports.rangeToString = rangeToString; - -/* eslint-disable eqeqeq */ -/** - * @param {SemVerRange} range version range - * @param {string} version the version - * @returns {boolean} if version satisfy the range - */ -const satisfy = (range, version) => { - if (0 in range) { - // @ts-expect-error - version = parseVersion(version); - var fixCount = range[0]; - // when negated is set it swill set for < instead of >= - var negated = fixCount < 0; - if (negated) fixCount = -fixCount - 1; - for (var i = 0, j = 1, isEqual = true; ; j++, i++) { - // cspell:word nequal nequ - - // when isEqual = true: - // range version: EOA/object undefined number string - // EOA equal block big-ver big-ver - // undefined bigger next big-ver big-ver - // number smaller block cmp big-cmp - // fixed number smaller block cmp-fix differ - // string smaller block differ cmp - // fixed string smaller block small-cmp cmp-fix - - // when isEqual = false: - // range version: EOA/object undefined number string - // EOA nequal block next-ver next-ver - // undefined nequal block next-ver next-ver - // number nequal block next next - // fixed number nequal block next next (this never happens) - // string nequal block next next - // fixed string nequal block next next (this never happens) - - // EOA end of array - // equal (version is equal range): - // when !negated: return true, - // when negated: return false - // bigger (version is bigger as range): - // when fixed: return false, - // when !negated: return true, - // when negated: return false, - // smaller (version is smaller as range): - // when !negated: return false, - // when negated: return true - // nequal (version is not equal range (> resp <)): return true - // block (version is in different prerelease area): return false - // differ (version is different from fixed range (string vs. number)): return false - // next: continues to the next items - // next-ver: when fixed: return false, continues to the next item only for the version, sets isEqual=false - // big-ver: when fixed || negated: return false, continues to the next item only for the version, sets isEqual=false - // next-nequ: continues to the next items, sets isEqual=false - // cmp (negated === false): version < range => return false, version > range => next-nequ, else => next - // cmp (negated === true): version > range => return false, version < range => next-nequ, else => next - // cmp-fix: version == range => next, else => return false - // big-cmp: when negated => return false, else => next-nequ - // small-cmp: when negated => next-nequ, else => return false - - var rangeType = j < range.length ? (typeof range[j])[0] : ""; - var versionValue; - var versionType; + clear() { + this._set.clear(); + this._toMerge.clear(); + this._toDeepMerge.length = 0; + this._needMerge = false; + this._deopt = false; + } - // Handles first column in both tables (end of version or object) - if ( - i >= version.length || - ((versionValue = version[i]), - (versionType = (typeof versionValue)[0]) == "o") - ) { - // Handles nequal - if (!isEqual) return true; - // Handles bigger - if (rangeType == "u") return j > fixCount && !negated; - // Handles equal and smaller: (range === EOA) XOR negated - return (rangeType == "") != negated; // equal + smaller - } + /** + * @param {T} value an item + * @returns {boolean} true, if the value was in the Set before + */ + delete(value) { + if (this._needMerge) this._merge(); + return this._set.delete(value); + } - // Handles second column in both tables (version = undefined) - if (versionType == "u") { - if (!isEqual || rangeType != "u") { - return false; - } - } + entries() { + this._deopt = true; + if (this._needMerge) this._merge(); + return this._set.entries(); + } - // switch between first and second table - else if (isEqual) { - // Handle diagonal - if (rangeType == versionType) { - if (j <= fixCount) { - // Handles "cmp-fix" cases - if (versionValue != range[j]) { - return false; - } - } else { - // Handles "cmp" cases - if (negated ? versionValue > range[j] : versionValue < range[j]) { - return false; - } - if (versionValue != range[j]) isEqual = false; - } - } + /** + * @param {function(T, T, Set): void} callbackFn function called for each entry + * @param {any} thisArg this argument for the callbackFn + * @returns {void} + */ + forEach(callbackFn, thisArg) { + this._deopt = true; + if (this._needMerge) this._merge(); + this._set.forEach(callbackFn, thisArg); + } - // Handle big-ver - else if (rangeType != "s" && rangeType != "n") { - if (negated || j <= fixCount) return false; - isEqual = false; - j--; - } + /** + * @param {T} item an item + * @returns {boolean} true, when the item is in the Set + */ + has(item) { + if (this._needMerge) this._merge(); + return this._set.has(item); + } - // Handle differ, big-cmp and small-cmp - else if (j <= fixCount || versionType < rangeType != negated) { - return false; - } else { - isEqual = false; - } - } else { - // Handles all "next-ver" cases in the second table - if (rangeType != "s" && rangeType != "n") { - isEqual = false; - j--; - } + keys() { + this._deopt = true; + if (this._needMerge) this._merge(); + return this._set.keys(); + } - // next is applied by default - } - } + values() { + this._deopt = true; + if (this._needMerge) this._merge(); + return this._set.values(); } - /** @type {(boolean | number)[]} */ - var stack = []; - var p = stack.pop.bind(stack); - // eslint-disable-next-line no-redeclare - for (var i = 1; i < range.length; i++) { - var item = /** @type {SemVerRange | 0 | 1 | 2} */ (range[i]); - stack.push( - item == 1 - ? p() | p() - : item == 2 - ? p() & p() - : item - ? satisfy(item, version) - : !p() - ); + + [Symbol.iterator]() { + this._deopt = true; + if (this._needMerge) this._merge(); + return this._set[Symbol.iterator](); } - return !!p(); -}; -/* eslint-enable eqeqeq */ -exports.satisfy = satisfy; -exports.stringifyHoley = json => { - switch (typeof json) { - case "undefined": - return ""; - case "object": - if (Array.isArray(json)) { - let str = "["; - for (let i = 0; i < json.length; i++) { - if (i !== 0) str += ","; - str += this.stringifyHoley(json[i]); - } - str += "]"; - return str; - } else { - return JSON.stringify(json); - } - default: - return JSON.stringify(json); + /* istanbul ignore next */ + get [Symbol.toStringTag]() { + return "LazySet"; } -}; -//#region runtime code: parseVersion -exports.parseVersionRuntimeCode = runtimeTemplate => - `var parseVersion = ${runtimeTemplate.basicFunction("str", [ - "// see webpack/lib/util/semver.js for original code", - `var p=${ - runtimeTemplate.supportsArrowFunction() ? "p=>" : "function(p)" - }{return p.split(".").map((${ - runtimeTemplate.supportsArrowFunction() ? "p=>" : "function(p)" - }{return+p==p?+p:p}))},n=/^([^-+]+)?(?:-([^+]+))?(?:\\+(.+))?$/.exec(str),r=n[1]?p(n[1]):[];return n[2]&&(r.length++,r.push.apply(r,p(n[2]))),n[3]&&(r.push([]),r.push.apply(r,p(n[3]))),r;` - ])}`; -//#endregion + serialize({ write }) { + if (this._needMerge) this._merge(); + write(this._set.size); + for (const item of this._set) write(item); + } -//#region runtime code: versionLt -exports.versionLtRuntimeCode = runtimeTemplate => - `var versionLt = ${runtimeTemplate.basicFunction("a, b", [ - "// see webpack/lib/util/semver.js for original code", - 'a=parseVersion(a),b=parseVersion(b);for(var r=0;;){if(r>=a.length)return r=b.length)return"u"==n;var t=b[r],f=(typeof t)[0];if(n!=f)return"o"==n&&"n"==f||("s"==f||"u"==n);if("o"!=n&&"u"!=n&&e!=t)return e - `var rangeToString = ${runtimeTemplate.basicFunction("range", [ - "// see webpack/lib/util/semver.js for original code", - 'var r=range[0],n="";if(1===range.length)return"*";if(r+.5){n+=0==r?">=":-1==r?"<":1==r?"^":2==r?"~":r>0?"=":"!=";for(var e=1,a=1;a0?".":"")+(e=2,t)}return n}var g=[];for(a=1;a - `var satisfy = ${runtimeTemplate.basicFunction("range, version", [ - "// see webpack/lib/util/semver.js for original code", - 'if(0 in range){version=parseVersion(version);var e=range[0],r=e<0;r&&(e=-e-1);for(var n=0,i=1,a=!0;;i++,n++){var f,s,g=i=version.length||"o"==(s=(typeof(f=version[n]))[0]))return!a||("u"==g?i>e&&!r:""==g!=r);if("u"==s){if(!a||"u"!=g)return!1}else if(a)if(g==s)if(i<=e){if(f!=range[i])return!1}else{if(r?f>range[i]:f} map a map + * @param {K} key the key + * @param {function(): V} computer compute value + * @returns {V} value + */ +exports.provide = (map, key, computer) => { + const value = map.get(key); + if (value !== undefined) return value; + const newValue = computer(); + map.set(key, newValue); + return newValue; +}; -/** @typedef {import("../serialization/BinaryMiddleware").MEASURE_END_OPERATION_TYPE} MEASURE_END_OPERATION */ -/** @typedef {import("../serialization/BinaryMiddleware").MEASURE_START_OPERATION_TYPE} MEASURE_START_OPERATION */ -/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ -/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ -/** @typedef {import("../serialization/Serializer")} Serializer */ -const getBinaryMiddleware = memoize(() => - __webpack_require__(97059) -); -const getObjectMiddleware = memoize(() => - __webpack_require__(34795) -); -const getSingleItemMiddleware = memoize(() => - __webpack_require__(65112) -); -const getSerializer = memoize(() => __webpack_require__(53080)); -const getSerializerMiddleware = memoize(() => - __webpack_require__(83137) -); +/***/ }), -const getBinaryMiddlewareInstance = memoize( - () => new (getBinaryMiddleware())() -); +/***/ 50780: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const registerSerializers = memoize(() => { - __webpack_require__(26611); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Load internal paths with a relative require - // This allows bundling all internal serializers - const internalSerializables = __webpack_require__(53023); - getObjectMiddleware().registerLoader(/^webpack\/lib\//, req => { - const loader = internalSerializables[req.slice("webpack/lib/".length)]; - if (loader) { - loader(); - } else { - console.warn(`${req} not found in internalSerializables`); - } - return true; - }); -}); -/** @type {Serializer} */ -let buffersSerializer; -// Expose serialization API -module.exports = { - get register() { - return getObjectMiddleware().register; - }, - get registerLoader() { - return getObjectMiddleware().registerLoader; - }, - get registerNotSerializable() { - return getObjectMiddleware().registerNotSerializable; - }, - get NOT_SERIALIZABLE() { - return getObjectMiddleware().NOT_SERIALIZABLE; - }, - /** @type {MEASURE_START_OPERATION} */ - get MEASURE_START_OPERATION() { - return getBinaryMiddleware().MEASURE_START_OPERATION; - }, - /** @type {MEASURE_END_OPERATION} */ - get MEASURE_END_OPERATION() { - return getBinaryMiddleware().MEASURE_END_OPERATION; - }, - get buffersSerializer() { - if (buffersSerializer !== undefined) return buffersSerializer; - registerSerializers(); - const Serializer = getSerializer(); - const binaryMiddleware = getBinaryMiddlewareInstance(); - const SerializerMiddleware = getSerializerMiddleware(); - const SingleItemMiddleware = getSingleItemMiddleware(); - return (buffersSerializer = new Serializer([ - new SingleItemMiddleware(), - new (getObjectMiddleware())(context => { - if (context.write) { - context.writeLazy = value => { - context.write( - SerializerMiddleware.createLazy(value, binaryMiddleware) - ); - }; - } - }, "md4"), - binaryMiddleware - ])); - }, - createFileSerializer: (fs, hashFunction) => { - registerSerializers(); - const Serializer = getSerializer(); - const FileMiddleware = __webpack_require__(65321); - const fileMiddleware = new FileMiddleware(fs, hashFunction); - const binaryMiddleware = getBinaryMiddlewareInstance(); - const SerializerMiddleware = getSerializerMiddleware(); - const SingleItemMiddleware = getSingleItemMiddleware(); - return new Serializer([ - new SingleItemMiddleware(), - new (getObjectMiddleware())(context => { - if (context.write) { - context.writeLazy = value => { - context.write( - SerializerMiddleware.createLazy(value, binaryMiddleware) - ); - }; - context.writeSeparate = (value, options) => { - const lazy = SerializerMiddleware.createLazy( - value, - fileMiddleware, - options - ); - context.write(lazy); - return lazy; - }; - } - }, hashFunction), - binaryMiddleware, - fileMiddleware - ]); +const binarySearchBounds = __webpack_require__(92229); + +class ParallelismFactorCalculator { + constructor() { + this._rangePoints = []; + this._rangeCallbacks = []; + } + + range(start, end, callback) { + if (start === end) return callback(1); + this._rangePoints.push(start); + this._rangePoints.push(end); + this._rangeCallbacks.push(callback); } -}; + + calculate() { + const segments = Array.from(new Set(this._rangePoints)).sort((a, b) => + a < b ? -1 : 1 + ); + const parallelism = segments.map(() => 0); + const rangeStartIndices = []; + for (let i = 0; i < this._rangePoints.length; i += 2) { + const start = this._rangePoints[i]; + const end = this._rangePoints[i + 1]; + let idx = binarySearchBounds.eq(segments, start); + rangeStartIndices.push(idx); + do { + parallelism[idx]++; + idx++; + } while (segments[idx] < end); + } + for (let i = 0; i < this._rangeCallbacks.length; i++) { + const start = this._rangePoints[i * 2]; + const end = this._rangePoints[i * 2 + 1]; + let idx = rangeStartIndices[i]; + let sum = 0; + let totalDuration = 0; + let current = start; + do { + const p = parallelism[idx]; + idx++; + const duration = segments[idx] - current; + totalDuration += duration; + current = segments[idx]; + sum += p * duration; + } while (current < end); + this._rangeCallbacks[i](sum / totalDuration); + } + } +} + +module.exports = ParallelismFactorCalculator; /***/ }), -/***/ 15652: +/***/ 65930: /***/ (function(module) { "use strict"; @@ -129188,210 +135044,325 @@ module.exports = { /** - * @typedef {Object} GroupOptions - * @property {boolean=} groupChildren - * @property {boolean=} force - * @property {number=} targetGroupCount + * @template T */ +class Queue { + /** + * @param {Iterable=} items The initial elements. + */ + constructor(items) { + /** @private @type {Set} */ + this._set = new Set(items); + /** @private @type {Iterator} */ + this._iterator = this._set[Symbol.iterator](); + } + + /** + * Returns the number of elements in this queue. + * @returns {number} The number of elements in this queue. + */ + get length() { + return this._set.size; + } + + /** + * Appends the specified element to this queue. + * @param {T} item The element to add. + * @returns {void} + */ + enqueue(item) { + this._set.add(item); + } + + /** + * Retrieves and removes the head of this queue. + * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + */ + dequeue() { + const result = this._iterator.next(); + if (result.done) return undefined; + this._set.delete(result.value); + return result.value; + } +} + +module.exports = Queue; + + +/***/ }), + +/***/ 93347: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + /** + * intersect creates Set containing the intersection of elements between all sets * @template T - * @template R - * @typedef {Object} GroupConfig - * @property {function(T): string[]} getKeys - * @property {function(string, (R | T)[], T[]): R} createGroup - * @property {function(string, T[]): GroupOptions=} getOptions + * @param {Set[]} sets an array of sets being checked for shared elements + * @returns {Set} returns a new Set containing the intersecting items + */ +const intersect = sets => { + if (sets.length === 0) return new Set(); + if (sets.length === 1) return new Set(sets[0]); + let minSize = Infinity; + let minIndex = -1; + for (let i = 0; i < sets.length; i++) { + const size = sets[i].size; + if (size < minSize) { + minIndex = i; + minSize = size; + } + } + const current = new Set(sets[minIndex]); + for (let i = 0; i < sets.length; i++) { + if (i === minIndex) continue; + const set = sets[i]; + for (const item of current) { + if (!set.has(item)) { + current.delete(item); + } + } + } + return current; +}; + +/** + * Checks if a set is the subset of another set + * @template T + * @param {Set} bigSet a Set which contains the original elements to compare against + * @param {Set} smallSet the set whose elements might be contained inside of bigSet + * @returns {boolean} returns true if smallSet contains all elements inside of the bigSet */ +const isSubset = (bigSet, smallSet) => { + if (bigSet.size < smallSet.size) return false; + for (const item of smallSet) { + if (!bigSet.has(item)) return false; + } + return true; +}; /** * @template T - * @template R - * @typedef {Object} ItemWithGroups - * @property {T} item - * @property {Set>} groups + * @param {Set} set a set + * @param {function(T): boolean} fn selector function + * @returns {T | undefined} found item */ +const find = (set, fn) => { + for (const item of set) { + if (fn(item)) return item; + } +}; /** * @template T - * @template R - * @typedef {{ config: GroupConfig, name: string, alreadyGrouped: boolean, items: Set> | undefined }} Group + * @param {Set} set a set + * @returns {T | undefined} first item */ +const first = set => { + const entry = set.values().next(); + return entry.done ? undefined : entry.value; +}; /** * @template T - * @template R - * @param {T[]} items the list of items - * @param {GroupConfig[]} groupConfigs configuration - * @returns {(R | T)[]} grouped items + * @param {Set} a first + * @param {Set} b second + * @returns {Set} combined set, may be identical to a or b */ -const smartGrouping = (items, groupConfigs) => { - /** @type {Set>} */ - const itemsWithGroups = new Set(); - /** @type {Map>} */ - const allGroups = new Map(); - for (const item of items) { - /** @type {Set>} */ - const groups = new Set(); - for (let i = 0; i < groupConfigs.length; i++) { - const groupConfig = groupConfigs[i]; - const keys = groupConfig.getKeys(item); - if (keys) { - for (const name of keys) { - const key = `${i}:${name}`; - let group = allGroups.get(key); - if (group === undefined) { - allGroups.set( - key, - (group = { - config: groupConfig, - name, - alreadyGrouped: false, - items: undefined - }) - ); - } - groups.add(group); - } - } - } - itemsWithGroups.add({ - item, - groups - }); +const combine = (a, b) => { + if (b.size === 0) return a; + if (a.size === 0) return b; + const set = new Set(a); + for (const item of b) set.add(item); + return set; +}; + +exports.intersect = intersect; +exports.isSubset = isSubset; +exports.find = find; +exports.first = first; +exports.combine = combine; + + +/***/ }), + +/***/ 13098: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const NONE = Symbol("not sorted"); + +/** + * A subset of Set that offers sorting functionality + * @template T item type in set + * @extends {Set} + */ +class SortableSet extends Set { + /** + * Create a new sortable set + * @param {Iterable=} initialIterable The initial iterable value + * @typedef {function(T, T): number} SortFunction + * @param {SortFunction=} defaultSort Default sorting function + */ + constructor(initialIterable, defaultSort) { + super(initialIterable); + /** @private @type {undefined | function(T, T): number}} */ + this._sortFn = defaultSort; + /** @private @type {typeof NONE | undefined | function(T, T): number}} */ + this._lastActiveSortFn = NONE; + /** @private @type {Map | undefined} */ + this._cache = undefined; + /** @private @type {Map | undefined} */ + this._cacheOrderIndependent = undefined; } + /** - * @param {Set>} itemsWithGroups input items with groups - * @returns {(T | R)[]} groups items + * @param {T} value value to add to set + * @returns {this} returns itself */ - const runGrouping = itemsWithGroups => { - const totalSize = itemsWithGroups.size; - for (const entry of itemsWithGroups) { - for (const group of entry.groups) { - if (group.alreadyGrouped) continue; - const items = group.items; - if (items === undefined) { - group.items = new Set([entry]); - } else { - items.add(entry); - } - } - } - /** @type {Map, { items: Set>, options: GroupOptions | false | undefined, used: boolean }>} */ - const groupMap = new Map(); - for (const group of allGroups.values()) { - if (group.items) { - const items = group.items; - group.items = undefined; - groupMap.set(group, { - items, - options: undefined, - used: false - }); - } - } - /** @type {(T | R)[]} */ - const results = []; - for (;;) { - /** @type {Group} */ - let bestGroup = undefined; - let bestGroupSize = -1; - let bestGroupItems = undefined; - let bestGroupOptions = undefined; - for (const [group, state] of groupMap) { - const { items, used } = state; - let options = state.options; - if (options === undefined) { - const groupConfig = group.config; - state.options = options = - (groupConfig.getOptions && - groupConfig.getOptions( - group.name, - Array.from(items, ({ item }) => item) - )) || - false; - } + add(value) { + this._lastActiveSortFn = NONE; + this._invalidateCache(); + this._invalidateOrderedCache(); + super.add(value); + return this; + } - const force = options && options.force; - if (!force) { - if (bestGroupOptions && bestGroupOptions.force) continue; - if (used) continue; - if (items.size <= 1 || totalSize - items.size <= 1) { - continue; - } - } - const targetGroupCount = (options && options.targetGroupCount) || 4; - let sizeValue = force - ? items.size - : Math.min( - items.size, - (totalSize * 2) / targetGroupCount + - itemsWithGroups.size - - items.size - ); - if ( - sizeValue > bestGroupSize || - (force && (!bestGroupOptions || !bestGroupOptions.force)) - ) { - bestGroup = group; - bestGroupSize = sizeValue; - bestGroupItems = items; - bestGroupOptions = options; - } - } - if (bestGroup === undefined) { - break; - } - const items = new Set(bestGroupItems); - const options = bestGroupOptions; + /** + * @param {T} value value to delete + * @returns {boolean} true if value existed in set, false otherwise + */ + delete(value) { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.delete(value); + } - const groupChildren = !options || options.groupChildren !== false; + /** + * @returns {void} + */ + clear() { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.clear(); + } - for (const item of items) { - itemsWithGroups.delete(item); - // Remove all groups that items have from the map to not select them again - for (const group of item.groups) { - const state = groupMap.get(group); - if (state !== undefined) { - state.items.delete(item); - if (state.items.size === 0) { - groupMap.delete(group); - } else { - state.options = undefined; - if (groupChildren) { - state.used = true; - } - } - } - } - } - groupMap.delete(bestGroup); + /** + * Sort with a comparer function + * @param {SortFunction} sortFn Sorting comparer function + * @returns {void} + */ + sortWith(sortFn) { + if (this.size <= 1 || sortFn === this._lastActiveSortFn) { + // already sorted - nothing to do + return; + } - const key = bestGroup.name; - const groupConfig = bestGroup.config; + const sortedArray = Array.from(this).sort(sortFn); + super.clear(); + for (let i = 0; i < sortedArray.length; i += 1) { + super.add(sortedArray[i]); + } + this._lastActiveSortFn = sortFn; + this._invalidateCache(); + } - const allItems = Array.from(items, ({ item }) => item); + sort() { + this.sortWith(this._sortFn); + return this; + } - bestGroup.alreadyGrouped = true; - const children = groupChildren ? runGrouping(items) : allItems; - bestGroup.alreadyGrouped = false; + /** + * Get data from cache + * @template R + * @param {function(SortableSet): R} fn function to calculate value + * @returns {R} returns result of fn(this), cached until set changes + */ + getFromCache(fn) { + if (this._cache === undefined) { + this._cache = new Map(); + } else { + const result = this._cache.get(fn); + const data = /** @type {R} */ (result); + if (data !== undefined) { + return data; + } + } + const newData = fn(this); + this._cache.set(fn, newData); + return newData; + } - results.push(groupConfig.createGroup(key, children, allItems)); + /** + * Get data from cache (ignoring sorting) + * @template R + * @param {function(SortableSet): R} fn function to calculate value + * @returns {R} returns result of fn(this), cached until set changes + */ + getFromUnorderedCache(fn) { + if (this._cacheOrderIndependent === undefined) { + this._cacheOrderIndependent = new Map(); + } else { + const result = this._cacheOrderIndependent.get(fn); + const data = /** @type {R} */ (result); + if (data !== undefined) { + return data; + } } - for (const { item } of itemsWithGroups) { - results.push(item); + const newData = fn(this); + this._cacheOrderIndependent.set(fn, newData); + return newData; + } + + /** + * @private + * @returns {void} + */ + _invalidateCache() { + if (this._cache !== undefined) { + this._cache.clear(); } - return results; - }; - return runGrouping(itemsWithGroups); -}; + } -module.exports = smartGrouping; + /** + * @private + * @returns {void} + */ + _invalidateOrderedCache() { + if (this._cacheOrderIndependent !== undefined) { + this._cacheOrderIndependent.clear(); + } + } + + /** + * @returns {T[]} the raw array + */ + toJSON() { + return Array.from(this); + } +} + +module.exports = SortableSet; /***/ }), -/***/ 41245: -/***/ (function(__unused_webpack_module, exports) { +/***/ 64985: +/***/ (function(module) { "use strict"; /* @@ -129401,66 +135372,115 @@ module.exports = smartGrouping; -/** @typedef {import("webpack-sources").Source} Source */ - -/** @type {WeakMap>} */ -const equalityCache = new WeakMap(); - /** - * @param {Source} a a source - * @param {Source} b another source - * @returns {boolean} true, when both sources are equal + * @template K + * @template V */ -const _isSourceEqual = (a, b) => { - // prefer .buffer(), it's called anyway during emit - /** @type {Buffer|string} */ - let aSource = typeof a.buffer === "function" ? a.buffer() : a.source(); - /** @type {Buffer|string} */ - let bSource = typeof b.buffer === "function" ? b.buffer() : b.source(); - if (aSource === bSource) return true; - if (typeof aSource === "string" && typeof bSource === "string") return false; - if (!Buffer.isBuffer(aSource)) aSource = Buffer.from(aSource, "utf-8"); - if (!Buffer.isBuffer(bSource)) bSource = Buffer.from(bSource, "utf-8"); - return aSource.equals(bSource); -}; +class StackedCacheMap { + constructor() { + /** @type {Map} */ + this.map = new Map(); + /** @type {ReadonlyMap[]} */ + this.stack = []; + } -/** - * @param {Source} a a source - * @param {Source} b another source - * @returns {boolean} true, when both sources are equal - */ -const isSourceEqual = (a, b) => { - if (a === b) return true; - const cache1 = equalityCache.get(a); - if (cache1 !== undefined) { - const result = cache1.get(b); - if (result !== undefined) return result; + /** + * @param {ReadonlyMap} map map to add + * @param {boolean} immutable if 'map' is immutable and StackedCacheMap can keep referencing it + */ + addAll(map, immutable) { + if (immutable) { + this.stack.push(map); + + // largest map should go first + for (let i = this.stack.length - 1; i > 0; i--) { + const beforeLast = this.stack[i - 1]; + if (beforeLast.size >= map.size) break; + this.stack[i] = beforeLast; + this.stack[i - 1] = map; + } + } else { + for (const [key, value] of map) { + this.map.set(key, value); + } + } } - const result = _isSourceEqual(a, b); - if (cache1 !== undefined) { - cache1.set(b, result); - } else { - const map = new WeakMap(); - map.set(b, result); - equalityCache.set(a, map); + + /** + * @param {K} item the key of the element to add + * @param {V} value the value of the element to add + * @returns {void} + */ + set(item, value) { + this.map.set(item, value); } - const cache2 = equalityCache.get(b); - if (cache2 !== undefined) { - cache2.set(a, result); - } else { - const map = new WeakMap(); - map.set(a, result); - equalityCache.set(b, map); + + /** + * @param {K} item the item to delete + * @returns {void} + */ + delete(item) { + throw new Error("Items can't be deleted from a StackedCacheMap"); } - return result; -}; -exports.isSourceEqual = isSourceEqual; + + /** + * @param {K} item the item to test + * @returns {boolean} true if the item exists in this set + */ + has(item) { + throw new Error( + "Checking StackedCacheMap.has before reading is inefficient, use StackedCacheMap.get and check for undefined" + ); + } + + /** + * @param {K} item the key of the element to return + * @returns {V} the value of the element + */ + get(item) { + for (const map of this.stack) { + const value = map.get(item); + if (value !== undefined) return value; + } + return this.map.get(item); + } + + clear() { + this.stack.length = 0; + this.map.clear(); + } + + get size() { + let size = this.map.size; + for (const map of this.stack) { + size += map.size; + } + return size; + } + + [Symbol.iterator]() { + const iterators = this.stack.map(map => map[Symbol.iterator]()); + let current = this.map[Symbol.iterator](); + return { + next() { + let result = current.next(); + while (result.done && iterators.length > 0) { + current = iterators.pop(); + result = current.next(); + } + return result; + } + }; + } +} + +module.exports = StackedCacheMap; /***/ }), -/***/ 12047: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 58845: +/***/ (function(module) { "use strict"; /* @@ -129470,180 +135490,171 @@ exports.isSourceEqual = isSourceEqual; -const { validate } = __webpack_require__(38476); +const TOMBSTONE = Symbol("tombstone"); +const UNDEFINED_MARKER = Symbol("undefined"); -/* cSpell:disable */ -const DID_YOU_MEAN = { - rules: "module.rules", - loaders: "module.rules or module.rules.*.use", - query: "module.rules.*.options (BREAKING CHANGE since webpack 5)", - noParse: "module.noParse", - filename: "output.filename or module.rules.*.generator.filename", - file: "output.filename", - chunkFilename: "output.chunkFilename", - chunkfilename: "output.chunkFilename", - ecmaVersion: - "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", - ecmaversion: - "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", - ecma: "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", - path: "output.path", - pathinfo: "output.pathinfo", - pathInfo: "output.pathinfo", - jsonpFunction: "output.chunkLoadingGlobal (BREAKING CHANGE since webpack 5)", - chunkCallbackName: - "output.chunkLoadingGlobal (BREAKING CHANGE since webpack 5)", - jsonpScriptType: "output.scriptType (BREAKING CHANGE since webpack 5)", - hotUpdateFunction: "output.hotUpdateGlobal (BREAKING CHANGE since webpack 5)", - splitChunks: "optimization.splitChunks", - immutablePaths: "snapshot.immutablePaths", - managedPaths: "snapshot.managedPaths", - maxModules: "stats.modulesSpace (BREAKING CHANGE since webpack 5)", - hashedModuleIds: - 'optimization.moduleIds: "hashed" (BREAKING CHANGE since webpack 5)', - namedChunks: - 'optimization.chunkIds: "named" (BREAKING CHANGE since webpack 5)', - namedModules: - 'optimization.moduleIds: "named" (BREAKING CHANGE since webpack 5)', - occurrenceOrder: - 'optimization.chunkIds: "size" and optimization.moduleIds: "size" (BREAKING CHANGE since webpack 5)', - automaticNamePrefix: - "optimization.splitChunks.[cacheGroups.*].idHint (BREAKING CHANGE since webpack 5)", - noEmitOnErrors: - "optimization.emitOnErrors (BREAKING CHANGE since webpack 5: logic is inverted to avoid negative flags)", - Buffer: - "to use the ProvidePlugin to process the Buffer variable to modules as polyfill\n" + - "BREAKING CHANGE: webpack 5 no longer provided Node.js polyfills by default.\n" + - "Note: if you are using 'node.Buffer: false', you can just remove that as this is the default behavior now.\n" + - "To provide a polyfill to modules use:\n" + - 'new ProvidePlugin({ Buffer: ["buffer", "Buffer"] }) and npm install buffer.', - process: - "to use the ProvidePlugin to process the process variable to modules as polyfill\n" + - "BREAKING CHANGE: webpack 5 no longer provided Node.js polyfills by default.\n" + - "Note: if you are using 'node.process: false', you can just remove that as this is the default behavior now.\n" + - "To provide a polyfill to modules use:\n" + - 'new ProvidePlugin({ process: "process" }) and npm install buffer.' -}; +/** + * @template T + * @typedef {T | undefined} Cell + */ -const REMOVED = { - concord: - "BREAKING CHANGE: resolve.concord has been removed and is no longer available.", - devtoolLineToLine: - "BREAKING CHANGE: output.devtoolLineToLine has been removed and is no longer available." +/** + * @template T + * @typedef {T | typeof TOMBSTONE | typeof UNDEFINED_MARKER} InternalCell + */ + +/** + * @template K + * @template V + * @param {[K, InternalCell]} pair the internal cell + * @returns {[K, Cell]} its “safe” representation + */ +const extractPair = pair => { + const key = pair[0]; + const val = pair[1]; + if (val === UNDEFINED_MARKER || val === TOMBSTONE) { + return [key, undefined]; + } else { + return /** @type {[K, Cell]} */ (pair); + } }; -/* cSpell:enable */ -/** - * @param {Parameters[0]} schema a json schema - * @param {Parameters[1]} options the options that should be validated - * @param {Parameters[2]=} validationConfiguration configuration for generating errors - * @returns {void} - */ -const validateSchema = (schema, options, validationConfiguration) => { - validate( - schema, - options, - validationConfiguration || { - name: "Webpack", - postFormatter: (formattedError, error) => { - const children = error.children; - if ( - children && - children.some( - child => - child.keyword === "absolutePath" && - child.dataPath === ".output.filename" - ) - ) { - return `${formattedError}\nPlease use output.path to specify absolute path and output.filename for the file name.`; +/** + * @template K + * @template V + */ +class StackedMap { + /** + * @param {Map>[]=} parentStack an optional parent + */ + constructor(parentStack) { + /** @type {Map>} */ + this.map = new Map(); + /** @type {Map>[]} */ + this.stack = parentStack === undefined ? [] : parentStack.slice(); + this.stack.push(this.map); + } + + /** + * @param {K} item the key of the element to add + * @param {V} value the value of the element to add + * @returns {void} + */ + set(item, value) { + this.map.set(item, value === undefined ? UNDEFINED_MARKER : value); + } + + /** + * @param {K} item the item to delete + * @returns {void} + */ + delete(item) { + if (this.stack.length > 1) { + this.map.set(item, TOMBSTONE); + } else { + this.map.delete(item); + } + } + + /** + * @param {K} item the item to test + * @returns {boolean} true if the item exists in this set + */ + has(item) { + const topValue = this.map.get(item); + if (topValue !== undefined) { + return topValue !== TOMBSTONE; + } + if (this.stack.length > 1) { + for (let i = this.stack.length - 2; i >= 0; i--) { + const value = this.stack[i].get(item); + if (value !== undefined) { + this.map.set(item, value); + return value !== TOMBSTONE; + } + } + this.map.set(item, TOMBSTONE); + } + return false; + } + + /** + * @param {K} item the key of the element to return + * @returns {Cell} the value of the element + */ + get(item) { + const topValue = this.map.get(item); + if (topValue !== undefined) { + return topValue === TOMBSTONE || topValue === UNDEFINED_MARKER + ? undefined + : topValue; + } + if (this.stack.length > 1) { + for (let i = this.stack.length - 2; i >= 0; i--) { + const value = this.stack[i].get(item); + if (value !== undefined) { + this.map.set(item, value); + return value === TOMBSTONE || value === UNDEFINED_MARKER + ? undefined + : value; } + } + this.map.set(item, TOMBSTONE); + } + return undefined; + } - if ( - children && - children.some( - child => - child.keyword === "pattern" && child.dataPath === ".devtool" - ) - ) { - return ( - `${formattedError}\n` + - "BREAKING CHANGE since webpack 5: The devtool option is more strict.\n" + - "Please strictly follow the order of the keywords in the pattern." - ); + _compress() { + if (this.stack.length === 1) return; + this.map = new Map(); + for (const data of this.stack) { + for (const pair of data) { + if (pair[1] === TOMBSTONE) { + this.map.delete(pair[0]); + } else { + this.map.set(pair[0], pair[1]); } + } + } + this.stack = [this.map]; + } - if (error.keyword === "additionalProperties") { - const params = - /** @type {import("ajv").AdditionalPropertiesParams} */ ( - error.params - ); - if ( - Object.prototype.hasOwnProperty.call( - DID_YOU_MEAN, - params.additionalProperty - ) - ) { - return `${formattedError}\nDid you mean ${ - DID_YOU_MEAN[params.additionalProperty] - }?`; - } + asArray() { + this._compress(); + return Array.from(this.map.keys()); + } - if ( - Object.prototype.hasOwnProperty.call( - REMOVED, - params.additionalProperty - ) - ) { - return `${formattedError}\n${REMOVED[params.additionalProperty]}?`; - } + asSet() { + this._compress(); + return new Set(this.map.keys()); + } - if (!error.dataPath) { - if (params.additionalProperty === "debug") { - return ( - `${formattedError}\n` + - "The 'debug' property was removed in webpack 2.0.0.\n" + - "Loaders should be updated to allow passing this option via loader options in module.rules.\n" + - "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" + - "plugins: [\n" + - " new webpack.LoaderOptionsPlugin({\n" + - " debug: true\n" + - " })\n" + - "]" - ); - } + asPairArray() { + this._compress(); + return Array.from(this.map.entries(), extractPair); + } - if (params.additionalProperty) { - return ( - `${formattedError}\n` + - "For typos: please correct them.\n" + - "For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.\n" + - " Loaders should be updated to allow passing options via loader options in module.rules.\n" + - " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" + - " plugins: [\n" + - " new webpack.LoaderOptionsPlugin({\n" + - " // test: /\\.xxx$/, // may apply this only for some modules\n" + - " options: {\n" + - ` ${params.additionalProperty}: …\n` + - " }\n" + - " })\n" + - " ]" - ); - } - } - } + asMap() { + return new Map(this.asPairArray()); + } - return formattedError; - } - } - ); -}; -module.exports = validateSchema; + get size() { + this._compress(); + return this.map.size; + } + + createChild() { + return new StackedMap(this.stack); + } +} + +module.exports = StackedMap; /***/ }), -/***/ 5434: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 40293: +/***/ (function(module) { "use strict"; /* @@ -129653,82 +135664,59 @@ module.exports = validateSchema; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); - -class AsyncWasmLoadingRuntimeModule extends RuntimeModule { - constructor({ generateLoadBinaryCode, supportsStreaming }) { - super("wasm loading", RuntimeModule.STAGE_NORMAL); - this.generateLoadBinaryCode = generateLoadBinaryCode; - this.supportsStreaming = supportsStreaming; +class StringXor { + constructor() { + this._value = undefined; } /** - * @returns {string} runtime code + * @param {string} str string + * @returns {void} */ - generate() { - const { compilation, chunk } = this; - const { outputOptions, runtimeTemplate } = compilation; - const fn = RuntimeGlobals.instantiateWasm; - const wasmModuleSrcPath = compilation.getPath( - JSON.stringify(outputOptions.webassemblyModuleFilename), - { - hash: `" + ${RuntimeGlobals.getFullHash}() + "`, - hashWithLength: length => - `" + ${RuntimeGlobals.getFullHash}}().slice(0, ${length}) + "`, - module: { - id: '" + wasmModuleId + "', - hash: `" + wasmModuleHash + "`, - hashWithLength(length) { - return `" + wasmModuleHash.slice(0, ${length}) + "`; - } - }, - runtime: chunk.runtime + add(str) { + const len = str.length; + const value = this._value; + if (value === undefined) { + const newValue = (this._value = Buffer.allocUnsafe(len)); + for (let i = 0; i < len; i++) { + newValue[i] = str.charCodeAt(i); } - ); - return `${fn} = ${runtimeTemplate.basicFunction( - "exports, wasmModuleId, wasmModuleHash, importsObj", - [ - `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, - this.supportsStreaming - ? Template.asString([ - "if (typeof WebAssembly.instantiateStreaming === 'function') {", - Template.indent([ - "return WebAssembly.instantiateStreaming(req, importsObj)", - Template.indent([ - `.then(${runtimeTemplate.returningFunction( - "Object.assign(exports, res.instance.exports)", - "res" - )});` - ]) - ]), - "}" - ]) - : "// no support for streaming compilation", - "return req", - Template.indent([ - `.then(${runtimeTemplate.returningFunction("x.arrayBuffer()", "x")})`, - `.then(${runtimeTemplate.returningFunction( - "WebAssembly.instantiate(bytes, importsObj)", - "bytes" - )})`, - `.then(${runtimeTemplate.returningFunction( - "Object.assign(exports, res.instance.exports)", - "res" - )});` - ]) - ] - )};`; + return; + } + const valueLen = value.length; + if (valueLen < len) { + const newValue = (this._value = Buffer.allocUnsafe(len)); + let i; + for (i = 0; i < valueLen; i++) { + newValue[i] = value[i] ^ str.charCodeAt(i); + } + for (; i < len; i++) { + newValue[i] = str.charCodeAt(i); + } + } else { + for (let i = 0; i < len; i++) { + value[i] = value[i] ^ str.charCodeAt(i); + } + } + } + + toString() { + const value = this._value; + return value === undefined ? "" : value.toString("latin1"); + } + + updateHash(hash) { + const value = this._value; + if (value !== undefined) hash.update(value); } } -module.exports = AsyncWasmLoadingRuntimeModule; +module.exports = StringXor; /***/ }), -/***/ 58461: +/***/ 38415: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -129739,58 +135727,66 @@ module.exports = AsyncWasmLoadingRuntimeModule; -const Generator = __webpack_require__(93401); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../NormalModule")} NormalModule */ - -const TYPES = new Set(["webassembly"]); +const TupleSet = __webpack_require__(76455); -class AsyncWebAssemblyGenerator extends Generator { - constructor(options) { - super(); - this.options = options; +/** + * @template {any[]} T + */ +class TupleQueue { + /** + * @param {Iterable=} items The initial elements. + */ + constructor(items) { + /** @private @type {TupleSet} */ + this._set = new TupleSet(items); + /** @private @type {Iterator} */ + this._iterator = this._set[Symbol.iterator](); } /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) + * Returns the number of elements in this queue. + * @returns {number} The number of elements in this queue. */ - getTypes(module) { - return TYPES; + get length() { + return this._set.size; } /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module + * Appends the specified element to this queue. + * @param {T} item The element to add. + * @returns {void} */ - getSize(module, type) { - const originalSource = module.originalSource(); - if (!originalSource) { - return 0; - } - return originalSource.size(); + enqueue(...item) { + this._set.add(...item); } /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code + * Retrieves and removes the head of this queue. + * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. */ - generate(module, generateContext) { - return module.originalSource(); + dequeue() { + const result = this._iterator.next(); + if (result.done) { + if (this._set.size > 0) { + this._iterator = this._set[Symbol.iterator](); + const value = this._iterator.next().value; + this._set.delete(...value); + return value; + } + return undefined; + } + this._set.delete(...result.value); + return result.value; } } -module.exports = AsyncWebAssemblyGenerator; +module.exports = TupleQueue; /***/ }), -/***/ 95614: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 76455: +/***/ (function(module) { "use strict"; /* @@ -129800,193 +135796,250 @@ module.exports = AsyncWebAssemblyGenerator; -const { RawSource } = __webpack_require__(51255); -const Generator = __webpack_require__(93401); -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const WebAssemblyImportDependency = __webpack_require__(5239); +/** + * @template {any[]} T + */ +class TupleSet { + constructor(init) { + this._map = new Map(); + this.size = 0; + if (init) { + for (const tuple of init) { + this.add(...tuple); + } + } + } -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + /** + * @param {T} args tuple + * @returns {void} + */ + add(...args) { + let map = this._map; + for (let i = 0; i < args.length - 2; i++) { + const arg = args[i]; + const innerMap = map.get(arg); + if (innerMap === undefined) { + map.set(arg, (map = new Map())); + } else { + map = innerMap; + } + } -const TYPES = new Set(["webassembly"]); + const beforeLast = args[args.length - 2]; + let set = map.get(beforeLast); + if (set === undefined) { + map.set(beforeLast, (set = new Set())); + } -class AsyncWebAssemblyJavascriptGenerator extends Generator { - constructor(filenameTemplate) { - super(); - this.filenameTemplate = filenameTemplate; + const last = args[args.length - 1]; + this.size -= set.size; + set.add(last); + this.size += set.size; } /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) + * @param {T} args tuple + * @returns {boolean} true, if the tuple is in the Set */ - getTypes(module) { - return TYPES; + has(...args) { + let map = this._map; + for (let i = 0; i < args.length - 2; i++) { + const arg = args[i]; + map = map.get(arg); + if (map === undefined) { + return false; + } + } + + const beforeLast = args[args.length - 2]; + let set = map.get(beforeLast); + if (set === undefined) { + return false; + } + + const last = args[args.length - 1]; + return set.has(last); } /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module + * @param {T} args tuple + * @returns {void} */ - getSize(module, type) { - return 40 + module.dependencies.length * 10; + delete(...args) { + let map = this._map; + for (let i = 0; i < args.length - 2; i++) { + const arg = args[i]; + map = map.get(arg); + if (map === undefined) { + return; + } + } + + const beforeLast = args[args.length - 2]; + let set = map.get(beforeLast); + if (set === undefined) { + return; + } + + const last = args[args.length - 1]; + this.size -= set.size; + set.delete(last); + this.size += set.size; } /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code + * @returns {Iterator} iterator */ - generate(module, generateContext) { - const { - runtimeTemplate, - chunkGraph, - moduleGraph, - runtimeRequirements, - runtime - } = generateContext; - runtimeRequirements.add(RuntimeGlobals.module); - runtimeRequirements.add(RuntimeGlobals.moduleId); - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.instantiateWasm); - /** @type {InitFragment[]} */ - const initFragments = []; - /** @type {Map} */ - const depModules = new Map(); - /** @type {Map} */ - const wasmDepsByRequest = new Map(); - for (const dep of module.dependencies) { - if (dep instanceof WebAssemblyImportDependency) { - const module = moduleGraph.getModule(dep); - if (!depModules.has(module)) { - depModules.set(module, { - request: dep.request, - importVar: `WEBPACK_IMPORTED_MODULE_${depModules.size}` - }); - } - let list = wasmDepsByRequest.get(dep.request); - if (list === undefined) { - list = []; - wasmDepsByRequest.set(dep.request, list); - } - list.push(dep); + [Symbol.iterator]() { + const iteratorStack = []; + const tuple = []; + let currentSetIterator = undefined; + + const next = it => { + const result = it.next(); + if (result.done) { + if (iteratorStack.length === 0) return false; + tuple.pop(); + return next(iteratorStack.pop()); } - } + const [key, value] = result.value; + iteratorStack.push(it); + tuple.push(key); + if (value instanceof Set) { + currentSetIterator = value[Symbol.iterator](); + return true; + } else { + return next(value[Symbol.iterator]()); + } + }; - const promises = []; + next(this._map[Symbol.iterator]()); - const importStatements = Array.from( - depModules, - ([importedModule, { request, importVar }]) => { - if (moduleGraph.isAsync(importedModule)) { - promises.push(importVar); + return { + next() { + while (currentSetIterator) { + const result = currentSetIterator.next(); + if (result.done) { + tuple.pop(); + if (!next(iteratorStack.pop())) { + currentSetIterator = undefined; + } + } else { + return { + done: false, + value: /** @type {T} */ (tuple.concat(result.value)) + }; + } } - return runtimeTemplate.importStatement({ - update: false, - module: importedModule, - chunkGraph, - request, - originModule: module, - importVar, - runtimeRequirements - }); + return { done: true, value: undefined }; } - ); - const importsCode = importStatements.map(([x]) => x).join(""); - const importsCompatCode = importStatements.map(([_, x]) => x).join(""); + }; + } +} - const importObjRequestItems = Array.from( - wasmDepsByRequest, - ([request, deps]) => { - const exportItems = deps.map(dep => { - const importedModule = moduleGraph.getModule(dep); - const importVar = depModules.get(importedModule).importVar; - return `${JSON.stringify( - dep.name - )}: ${runtimeTemplate.exportFromImport({ - moduleGraph, - module: importedModule, - request, - exportName: dep.name, - originModule: module, - asiSafe: true, - isCall: false, - callContext: false, - defaultInterop: true, - importVar, - initFragments, - runtime, - runtimeRequirements - })}`; - }); - return Template.asString([ - `${JSON.stringify(request)}: {`, - Template.indent(exportItems.join(",\n")), - "}" - ]); - } - ); +module.exports = TupleSet; - const importsObj = - importObjRequestItems.length > 0 - ? Template.asString([ - "{", - Template.indent(importObjRequestItems.join(",\n")), - "}" - ]) - : undefined; - const instantiateCall = - `${RuntimeGlobals.instantiateWasm}(${module.exportsArgument}, ${ - module.moduleArgument - }.id, ${JSON.stringify( - chunkGraph.getRenderedModuleHash(module, runtime) - )}` + (importsObj ? `, ${importsObj})` : `)`); +/***/ }), - if (promises.length > 0) - runtimeRequirements.add(RuntimeGlobals.asyncModule); +/***/ 54500: +/***/ (function(__unused_webpack_module, exports) { - const source = new RawSource( - promises.length > 0 - ? Template.asString([ - `var __webpack_instantiate__ = ${runtimeTemplate.basicFunction( - `[${promises.join(", ")}]`, - `${importsCompatCode}return ${instantiateCall};` - )}`, - `${RuntimeGlobals.asyncModule}(${ - module.moduleArgument - }, ${runtimeTemplate.basicFunction( - "__webpack_handle_async_dependencies__", - [ - importsCode, - `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${promises.join( - ", " - )}]);`, - "return __webpack_async_dependencies__.then ? __webpack_async_dependencies__.then(__webpack_instantiate__) : __webpack_instantiate__(__webpack_async_dependencies__);" - ] - )}, 1);` - ]) - : `${importsCode}${importsCompatCode}module.exports = ${instantiateCall};` - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - return InitFragment.addToSource(source, initFragments, generateContext); + + +/** @typedef {import("./fs").InputFileSystem} InputFileSystem */ +/** @typedef {(error: Error|null, result?: Buffer) => void} ErrorFirstCallback */ + +const backSlashCharCode = "\\".charCodeAt(0); +const slashCharCode = "/".charCodeAt(0); +const aLowerCaseCharCode = "a".charCodeAt(0); +const zLowerCaseCharCode = "z".charCodeAt(0); +const aUpperCaseCharCode = "A".charCodeAt(0); +const zUpperCaseCharCode = "Z".charCodeAt(0); +const _0CharCode = "0".charCodeAt(0); +const _9CharCode = "9".charCodeAt(0); +const plusCharCode = "+".charCodeAt(0); +const hyphenCharCode = "-".charCodeAt(0); +const colonCharCode = ":".charCodeAt(0); +const hashCharCode = "#".charCodeAt(0); +const queryCharCode = "?".charCodeAt(0); +/** + * Get scheme if specifier is an absolute URL specifier + * e.g. Absolute specifiers like 'file:///user/webpack/index.js' + * https://tools.ietf.org/html/rfc3986#section-3.1 + * @param {string} specifier specifier + * @returns {string|undefined} scheme if absolute URL specifier provided + */ +function getScheme(specifier) { + const start = specifier.charCodeAt(0); + + // First char maybe only a letter + if ( + (start < aLowerCaseCharCode || start > zLowerCaseCharCode) && + (start < aUpperCaseCharCode || start > zUpperCaseCharCode) + ) { + return undefined; + } + + let i = 1; + let ch = specifier.charCodeAt(i); + + while ( + (ch >= aLowerCaseCharCode && ch <= zLowerCaseCharCode) || + (ch >= aUpperCaseCharCode && ch <= zUpperCaseCharCode) || + (ch >= _0CharCode && ch <= _9CharCode) || + ch === plusCharCode || + ch === hyphenCharCode + ) { + if (++i === specifier.length) return undefined; + ch = specifier.charCodeAt(i); + } + + // Scheme must end with colon + if (ch !== colonCharCode) return undefined; + + // Check for Windows absolute path + // https://url.spec.whatwg.org/#url-miscellaneous + if (i === 1) { + const nextChar = i + 1 < specifier.length ? specifier.charCodeAt(i + 1) : 0; + if ( + nextChar === 0 || + nextChar === backSlashCharCode || + nextChar === slashCharCode || + nextChar === hashCharCode || + nextChar === queryCharCode + ) { + return undefined; + } } + + return specifier.slice(0, i).toLowerCase(); } -module.exports = AsyncWebAssemblyJavascriptGenerator; +/** + * @param {string} specifier specifier + * @returns {string|null} protocol if absolute URL specifier provided + */ +function getProtocol(specifier) { + const scheme = getScheme(specifier); + return scheme === undefined ? undefined : scheme + ":"; +} + +exports.getScheme = getScheme; +exports.getProtocol = getProtocol; /***/ }), -/***/ 7538: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 28745: +/***/ (function(module) { "use strict"; /* @@ -129996,780 +136049,846 @@ module.exports = AsyncWebAssemblyJavascriptGenerator; -const { SyncWaterfallHook } = __webpack_require__(6967); -const Compilation = __webpack_require__(85720); -const Generator = __webpack_require__(93401); -const { tryRunOrWebpackError } = __webpack_require__(11351); -const WebAssemblyImportDependency = __webpack_require__(5239); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const memoize = __webpack_require__(78676); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../Template").RenderManifestEntry} RenderManifestEntry */ -/** @typedef {import("../Template").RenderManifestOptions} RenderManifestOptions */ - -const getAsyncWebAssemblyGenerator = memoize(() => - __webpack_require__(58461) -); -const getAsyncWebAssemblyJavascriptGenerator = memoize(() => - __webpack_require__(95614) -); -const getAsyncWebAssemblyParser = memoize(() => - __webpack_require__(96305) -); - -/** - * @typedef {Object} WebAssemblyRenderContext - * @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 - * @property {CodeGenerationResults} codeGenerationResults results of code generation - */ +const isWeakKey = thing => typeof thing === "object" && thing !== null; /** - * @typedef {Object} CompilationHooks - * @property {SyncWaterfallHook<[Source, Module, WebAssemblyRenderContext]>} renderModuleContent + * @template {any[]} T + * @template V */ +class WeakTupleMap { + constructor() { + /** @private */ + this.f = 0; + /** @private @type {any} */ + this.v = undefined; + /** @private @type {Map> | undefined} */ + this.m = undefined; + /** @private @type {WeakMap> | undefined} */ + this.w = undefined; + } -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); + /** + * @param {[...T, V]} args tuple + * @returns {void} + */ + set(...args) { + /** @type {WeakTupleMap} */ + let node = this; + for (let i = 0; i < args.length - 1; i++) { + node = node._get(args[i]); + } + node._setValue(args[args.length - 1]); + } -class AsyncWebAssemblyModulesPlugin { /** - * @param {Compilation} compilation the compilation - * @returns {CompilationHooks} the attached hooks + * @param {T} args tuple + * @returns {boolean} true, if the tuple is in the Set */ - static getCompilationHooks(compilation) { - if (!(compilation instanceof Compilation)) { - throw new TypeError( - "The 'compilation' argument must be an instance of Compilation" - ); + has(...args) { + /** @type {WeakTupleMap} */ + let node = this; + for (let i = 0; i < args.length; i++) { + node = node._peek(args[i]); + if (node === undefined) return false; } - let hooks = compilationHooksMap.get(compilation); - if (hooks === undefined) { - hooks = { - renderModuleContent: new SyncWaterfallHook([ - "source", - "module", - "renderContext" - ]) - }; - compilationHooksMap.set(compilation, hooks); + return node._hasValue(); + } + + /** + * @param {T} args tuple + * @returns {V} the value + */ + get(...args) { + /** @type {WeakTupleMap} */ + let node = this; + for (let i = 0; i < args.length; i++) { + node = node._peek(args[i]); + if (node === undefined) return undefined; } - return hooks; + return node._getValue(); } - constructor(options) { - this.options = options; + /** + * @param {[...T, function(): V]} args tuple + * @returns {V} the value + */ + provide(...args) { + /** @type {WeakTupleMap} */ + let node = this; + for (let i = 0; i < args.length - 1; i++) { + node = node._get(args[i]); + } + if (node._hasValue()) return node._getValue(); + const fn = args[args.length - 1]; + const newValue = fn(...args.slice(0, -1)); + node._setValue(newValue); + return newValue; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {T} args tuple * @returns {void} */ - apply(compiler) { - compiler.hooks.compilation.tap( - "AsyncWebAssemblyModulesPlugin", - (compilation, { normalModuleFactory }) => { - const hooks = - AsyncWebAssemblyModulesPlugin.getCompilationHooks(compilation); - compilation.dependencyFactories.set( - WebAssemblyImportDependency, - normalModuleFactory - ); - - normalModuleFactory.hooks.createParser - .for("webassembly/async") - .tap("AsyncWebAssemblyModulesPlugin", () => { - const AsyncWebAssemblyParser = getAsyncWebAssemblyParser(); + delete(...args) { + /** @type {WeakTupleMap} */ + let node = this; + for (let i = 0; i < args.length; i++) { + node = node._peek(args[i]); + if (node === undefined) return; + } + node._deleteValue(); + } - return new AsyncWebAssemblyParser(); - }); - normalModuleFactory.hooks.createGenerator - .for("webassembly/async") - .tap("AsyncWebAssemblyModulesPlugin", () => { - const AsyncWebAssemblyJavascriptGenerator = - getAsyncWebAssemblyJavascriptGenerator(); - const AsyncWebAssemblyGenerator = getAsyncWebAssemblyGenerator(); + /** + * @returns {void} + */ + clear() { + this.f = 0; + this.v = undefined; + this.w = undefined; + this.m = undefined; + } - return Generator.byType({ - javascript: new AsyncWebAssemblyJavascriptGenerator( - compilation.outputOptions.webassemblyModuleFilename - ), - webassembly: new AsyncWebAssemblyGenerator(this.options) - }); - }); + _getValue() { + return this.v; + } - compilation.hooks.renderManifest.tap( - "WebAssemblyModulesPlugin", - (result, options) => { - const { moduleGraph, chunkGraph, runtimeTemplate } = compilation; - const { - chunk, - outputOptions, - dependencyTemplates, - codeGenerationResults - } = options; + _hasValue() { + return (this.f & 1) === 1; + } - for (const module of chunkGraph.getOrderedChunkModulesIterable( - chunk, - compareModulesByIdentifier - )) { - if (module.type === "webassembly/async") { - const filenameTemplate = - outputOptions.webassemblyModuleFilename; + _setValue(v) { + this.f |= 1; + this.v = v; + } - result.push({ - render: () => - this.renderModule( - module, - { - chunk, - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - codeGenerationResults - }, - hooks - ), - filenameTemplate, - pathOptions: { - module, - runtime: chunk.runtime, - chunkGraph - }, - auxiliary: true, - identifier: `webassemblyAsyncModule${chunkGraph.getModuleId( - module - )}`, - hash: chunkGraph.getModuleHash(module, chunk.runtime) - }); - } - } + _deleteValue() { + this.f &= 6; + this.v = undefined; + } - return result; - } - ); - } - ); + _peek(thing) { + if (isWeakKey(thing)) { + if ((this.f & 4) !== 4) return undefined; + return this.w.get(thing); + } else { + if ((this.f & 2) !== 2) return undefined; + return this.m.get(thing); + } } - renderModule(module, renderContext, hooks) { - const { codeGenerationResults, chunk } = renderContext; - try { - const moduleSource = codeGenerationResults.getSource( - module, - chunk.runtime, - "webassembly" - ); - return tryRunOrWebpackError( - () => - hooks.renderModuleContent.call(moduleSource, module, renderContext), - "AsyncWebAssemblyModulesPlugin.getCompilationHooks().renderModuleContent" - ); - } catch (e) { - e.module = module; - throw e; + _get(thing) { + if (isWeakKey(thing)) { + if ((this.f & 4) !== 4) { + const newMap = new WeakMap(); + this.f |= 4; + const newNode = new WeakTupleMap(); + (this.w = newMap).set(thing, newNode); + return newNode; + } + const entry = this.w.get(thing); + if (entry !== undefined) { + return entry; + } + const newNode = new WeakTupleMap(); + this.w.set(thing, newNode); + return newNode; + } else { + if ((this.f & 2) !== 2) { + const newMap = new Map(); + this.f |= 2; + const newNode = new WeakTupleMap(); + (this.m = newMap).set(thing, newNode); + return newNode; + } + const entry = this.m.get(thing); + if (entry !== undefined) { + return entry; + } + const newNode = new WeakTupleMap(); + this.m.set(thing, newNode); + return newNode; } } } -module.exports = AsyncWebAssemblyModulesPlugin; +module.exports = WeakTupleMap; /***/ }), -/***/ 96305: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - +/***/ 92229: +/***/ (function(module) { + "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Mikola Lysenko @mikolalysenko */ -const t = __webpack_require__(51826); -const { decode } = __webpack_require__(73726); -const Parser = __webpack_require__(11715); -const StaticExportsDependency = __webpack_require__(91418); -const WebAssemblyImportDependency = __webpack_require__(5239); - -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ - -const decoderOpts = { - ignoreCodeSection: true, - ignoreDataSection: true, - - // this will avoid having to lookup with identifiers in the ModuleContext - ignoreCustomNameSection: true -}; +/* cspell:disable-next-line */ +// Refactor: Peter Somogyvari @petermetz -class WebAssemblyParser extends Parser { - constructor(options) { - super(); - this.hooks = Object.freeze({}); - this.options = options; - } +const compileSearch = (funcName, predicate, reversed, extraArgs, earlyOut) => { + const code = [ + "function ", + funcName, + "(a,l,h,", + extraArgs.join(","), + "){", + earlyOut ? "" : "var i=", + reversed ? "l-1" : "h+1", + ";while(l<=h){var m=(l+h)>>>1,x=a[m]" + ]; - /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state - */ - parse(source, state) { - if (!Buffer.isBuffer(source)) { - throw new Error("WebAssemblyParser input must be a Buffer"); + if (earlyOut) { + if (predicate.indexOf("c") < 0) { + code.push(";if(x===y){return m}else if(x<=y){"); + } else { + code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"); } + } else { + code.push(";if(", predicate, "){i=m;"); + } + if (reversed) { + code.push("l=m+1}else{h=m-1}"); + } else { + code.push("h=m-1}else{l=m+1}"); + } + code.push("}"); + if (earlyOut) { + code.push("return -1};"); + } else { + code.push("return i};"); + } + return code.join(""); +}; - // flag it as async module - state.module.buildInfo.strict = true; - state.module.buildMeta.exportsType = "namespace"; - state.module.buildMeta.async = true; - - // parse it - const program = decode(source, decoderOpts); - const module = program.body[0]; - - const exports = []; - t.traverse(module, { - ModuleExport({ node }) { - exports.push(node.name); - }, +const compileBoundsSearch = (predicate, reversed, suffix, earlyOut) => { + const arg1 = compileSearch( + "A", + "x" + predicate + "y", + reversed, + ["y"], + earlyOut + ); - ModuleImport({ node }) { - const dep = new WebAssemblyImportDependency( - node.module, - node.name, - node.descr, - false - ); + const arg2 = compileSearch( + "P", + "c(x,y)" + predicate + "0", + reversed, + ["y", "c"], + earlyOut + ); - state.module.addDependency(dep); - } - }); + const fnHeader = "function dispatchBinarySearch"; - state.module.addDependency(new StaticExportsDependency(exports, false)); + const fnBody = + "(a,y,c,l,h){\ +if(typeof(c)==='function'){\ +return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ +}else{\ +return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ +}}\ +return dispatchBinarySearch"; - return state; - } -} + const fnArgList = [arg1, arg2, fnHeader, suffix, fnBody, suffix]; + const fnSource = fnArgList.join(""); + const result = new Function(fnSource); + return result(); +}; -module.exports = WebAssemblyParser; +module.exports = { + ge: compileBoundsSearch(">=", false, "GE"), + gt: compileBoundsSearch(">", false, "GT"), + lt: compileBoundsSearch("<", true, "LT"), + le: compileBoundsSearch("<=", true, "LE"), + eq: compileBoundsSearch("-", true, "EQ", true) +}; /***/ }), -/***/ 78455: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 60839: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const WebpackError = __webpack_require__(53799); +/** @type {WeakMap>} */ +const mergeCache = new WeakMap(); +/** @type {WeakMap>>} */ +const setPropertyCache = new WeakMap(); +const DELETE = Symbol("DELETE"); +const DYNAMIC_INFO = Symbol("cleverMerge dynamic info"); -module.exports = class UnsupportedWebAssemblyFeatureError extends WebpackError { - /** @param {string} message Error message */ - constructor(message) { - super(message); - this.name = "UnsupportedWebAssemblyFeatureError"; - this.hideStack = true; +/** + * Merges two given objects and caches the result to avoid computation if same objects passed as arguments again. + * @template T + * @template O + * @example + * // performs cleverMerge(first, second), stores the result in WeakMap and returns result + * cachedCleverMerge({a: 1}, {a: 2}) + * {a: 2} + * // when same arguments passed, gets the result from WeakMap and returns it. + * cachedCleverMerge({a: 1}, {a: 2}) + * {a: 2} + * @param {T} first first object + * @param {O} second second object + * @returns {T & O | T | O} merged object of first and second object + */ +const cachedCleverMerge = (first, second) => { + if (second === undefined) return first; + if (first === undefined) return second; + if (typeof second !== "object" || second === null) return second; + if (typeof first !== "object" || first === null) return first; + + let innerCache = mergeCache.get(first); + if (innerCache === undefined) { + innerCache = new WeakMap(); + mergeCache.set(first, innerCache); } + const prevMerge = innerCache.get(second); + if (prevMerge !== undefined) return prevMerge; + const newMerge = _cleverMerge(first, second, true); + innerCache.set(second, newMerge); + return newMerge; }; +/** + * @template T + * @param {Partial} obj object + * @param {string} property property + * @param {string|number|boolean} value assignment value + * @returns {T} new object + */ +const cachedSetProperty = (obj, property, value) => { + let mapByProperty = setPropertyCache.get(obj); -/***/ }), - -/***/ 87394: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - + if (mapByProperty === undefined) { + mapByProperty = new Map(); + setPropertyCache.set(obj, mapByProperty); + } + let mapByValue = mapByProperty.get(property); -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const WebAssemblyUtils = __webpack_require__(18650); + if (mapByValue === undefined) { + mapByValue = new Map(); + mapByProperty.set(property, mapByValue); + } -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + let result = mapByValue.get(value); -// TODO webpack 6 remove the whole folder + if (result) return result; -// Get all wasm modules -const getAllWasmModules = (moduleGraph, chunkGraph, chunk) => { - const wasmModules = chunk.getAllAsyncChunks(); - const array = []; - for (const chunk of wasmModules) { - for (const m of chunkGraph.getOrderedChunkModulesIterable( - chunk, - compareModulesByIdentifier - )) { - if (m.type.startsWith("webassembly")) { - array.push(m); - } - } - } + result = { + ...obj, + [property]: value + }; + mapByValue.set(value, result); - return array; + return result; }; /** - * generates the import object function for a module - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {Module} module the module - * @param {boolean} mangle mangle imports - * @param {string[]} declarations array where declarations are pushed to - * @param {RuntimeSpec} runtime the runtime - * @returns {string} source code + * @typedef {Object} ObjectParsedPropertyEntry + * @property {any | undefined} base base value + * @property {string | undefined} byProperty the name of the selector property + * @property {Map} byValues value depending on selector property, merged with base */ -const generateImportObject = ( - chunkGraph, - module, - mangle, - declarations, - runtime -) => { - const moduleGraph = chunkGraph.moduleGraph; - const waitForInstances = new Map(); - const properties = []; - const usedWasmDependencies = WebAssemblyUtils.getUsedDependencies( - moduleGraph, - module, - mangle - ); - for (const usedDep of usedWasmDependencies) { - const dep = usedDep.dependency; - const importedModule = moduleGraph.getModule(dep); - const exportName = dep.name; - const usedName = - importedModule && - moduleGraph - .getExportsInfo(importedModule) - .getUsedName(exportName, runtime); - const description = dep.description; - const direct = dep.onlyDirectImport; - - const module = usedDep.module; - const name = usedDep.name; - if (direct) { - const instanceVar = `m${waitForInstances.size}`; - waitForInstances.set(instanceVar, chunkGraph.getModuleId(importedModule)); - properties.push({ - module, - name, - value: `${instanceVar}[${JSON.stringify(usedName)}]` - }); - } else { - const params = description.signature.params.map( - (param, k) => "p" + k + param.valtype - ); +/** + * @typedef {Object} ParsedObject + * @property {Map} static static properties (key is property name) + * @property {{ byProperty: string, fn: Function } | undefined} dynamic dynamic part + */ - const mod = `${RuntimeGlobals.moduleCache}[${JSON.stringify( - chunkGraph.getModuleId(importedModule) - )}]`; - const modExports = `${mod}.exports`; +/** @type {WeakMap} */ +const parseCache = new WeakMap(); - const cache = `wasmImportedFuncCache${declarations.length}`; - declarations.push(`var ${cache};`); +/** + * @param {object} obj the object + * @returns {ParsedObject} parsed object + */ +const cachedParseObject = obj => { + const entry = parseCache.get(obj); + if (entry !== undefined) return entry; + const result = parseObject(obj); + parseCache.set(obj, result); + return result; +}; - properties.push({ - module, - name, - value: Template.asString([ - (importedModule.type.startsWith("webassembly") - ? `${mod} ? ${modExports}[${JSON.stringify(usedName)}] : ` - : "") + `function(${params}) {`, - Template.indent([ - `if(${cache} === undefined) ${cache} = ${modExports};`, - `return ${cache}[${JSON.stringify(usedName)}](${params});` - ]), - "}" - ]) - }); +/** + * @param {object} obj the object + * @returns {ParsedObject} parsed object + */ +const parseObject = obj => { + const info = new Map(); + let dynamicInfo; + const getInfo = p => { + const entry = info.get(p); + if (entry !== undefined) return entry; + const newEntry = { + base: undefined, + byProperty: undefined, + byValues: undefined + }; + info.set(p, newEntry); + return newEntry; + }; + for (const key of Object.keys(obj)) { + if (key.startsWith("by")) { + const byProperty = key; + const byObj = obj[byProperty]; + if (typeof byObj === "object") { + for (const byValue of Object.keys(byObj)) { + const obj = byObj[byValue]; + for (const key of Object.keys(obj)) { + const entry = getInfo(key); + if (entry.byProperty === undefined) { + entry.byProperty = byProperty; + entry.byValues = new Map(); + } else if (entry.byProperty !== byProperty) { + throw new Error( + `${byProperty} and ${entry.byProperty} for a single property is not supported` + ); + } + entry.byValues.set(byValue, obj[key]); + if (byValue === "default") { + for (const otherByValue of Object.keys(byObj)) { + if (!entry.byValues.has(otherByValue)) + entry.byValues.set(otherByValue, undefined); + } + } + } + } + } else if (typeof byObj === "function") { + if (dynamicInfo === undefined) { + dynamicInfo = { + byProperty: key, + fn: byObj + }; + } else { + throw new Error( + `${key} and ${dynamicInfo.byProperty} when both are functions is not supported` + ); + } + } else { + const entry = getInfo(key); + entry.base = obj[key]; + } + } else { + const entry = getInfo(key); + entry.base = obj[key]; } } + return { + static: info, + dynamic: dynamicInfo + }; +}; - let importObject; - if (mangle) { - importObject = [ - "return {", - Template.indent([ - properties.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") - ]), - "};" - ]; - } else { - const propertiesByModule = new Map(); - for (const p of properties) { - let list = propertiesByModule.get(p.module); - if (list === undefined) { - propertiesByModule.set(p.module, (list = [])); +/** + * @param {Map} info static properties (key is property name) + * @param {{ byProperty: string, fn: Function } | undefined} dynamicInfo dynamic part + * @returns {object} the object + */ +const serializeObject = (info, dynamicInfo) => { + const obj = {}; + // Setup byProperty structure + for (const entry of info.values()) { + if (entry.byProperty !== undefined) { + const byObj = (obj[entry.byProperty] = obj[entry.byProperty] || {}); + for (const byValue of entry.byValues.keys()) { + byObj[byValue] = byObj[byValue] || {}; } - list.push(p); } - importObject = [ - "return {", - Template.indent([ - Array.from(propertiesByModule, ([module, list]) => { - return Template.asString([ - `${JSON.stringify(module)}: {`, - Template.indent([ - list.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") - ]), - "}" - ]); - }).join(",\n") - ]), - "};" - ]; } - - const moduleIdStringified = JSON.stringify(chunkGraph.getModuleId(module)); - if (waitForInstances.size === 1) { - const moduleId = Array.from(waitForInstances.values())[0]; - const promise = `installedWasmModules[${JSON.stringify(moduleId)}]`; - const variable = Array.from(waitForInstances.keys())[0]; - return Template.asString([ - `${moduleIdStringified}: function() {`, - Template.indent([ - `return promiseResolve().then(function() { return ${promise}; }).then(function(${variable}) {`, - Template.indent(importObject), - "});" - ]), - "}," - ]); - } else if (waitForInstances.size > 0) { - const promises = Array.from( - waitForInstances.values(), - id => `installedWasmModules[${JSON.stringify(id)}]` - ).join(", "); - const variables = Array.from( - waitForInstances.keys(), - (name, i) => `${name} = array[${i}]` - ).join(", "); - return Template.asString([ - `${moduleIdStringified}: function() {`, - Template.indent([ - `return promiseResolve().then(function() { return Promise.all([${promises}]); }).then(function(array) {`, - Template.indent([`var ${variables};`, ...importObject]), - "});" - ]), - "}," - ]); - } else { - return Template.asString([ - `${moduleIdStringified}: function() {`, - Template.indent(importObject), - "}," - ]); + for (const [key, entry] of info) { + if (entry.base !== undefined) { + obj[key] = entry.base; + } + // Fill byProperty structure + if (entry.byProperty !== undefined) { + const byObj = (obj[entry.byProperty] = obj[entry.byProperty] || {}); + for (const byValue of Object.keys(byObj)) { + const value = getFromByValues(entry.byValues, byValue); + if (value !== undefined) byObj[byValue][key] = value; + } + } } -}; - -class WasmChunkLoadingRuntimeModule extends RuntimeModule { - constructor({ - generateLoadBinaryCode, - supportsStreaming, - mangleImports, - runtimeRequirements - }) { - super("wasm chunk loading", RuntimeModule.STAGE_ATTACH); - this.generateLoadBinaryCode = generateLoadBinaryCode; - this.supportsStreaming = supportsStreaming; - this.mangleImports = mangleImports; - this._runtimeRequirements = runtimeRequirements; + if (dynamicInfo !== undefined) { + obj[dynamicInfo.byProperty] = dynamicInfo.fn; } + return obj; +}; - /** - * @returns {string} runtime code - */ - generate() { - const { chunkGraph, compilation, chunk, mangleImports } = this; - const { moduleGraph, outputOptions } = compilation; - const fn = RuntimeGlobals.ensureChunkHandlers; - const withHmr = this._runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const wasmModules = getAllWasmModules(moduleGraph, chunkGraph, chunk); - const declarations = []; - const importObjects = wasmModules.map(module => { - return generateImportObject( - chunkGraph, - module, - this.mangleImports, - declarations, - chunk.runtime - ); - }); - const chunkModuleIdMap = chunkGraph.getChunkModuleIdMap(chunk, m => - m.type.startsWith("webassembly") - ); - const createImportObject = content => - mangleImports - ? `{ ${JSON.stringify(WebAssemblyUtils.MANGLED_MODULE)}: ${content} }` - : content; - const wasmModuleSrcPath = compilation.getPath( - JSON.stringify(outputOptions.webassemblyModuleFilename), - { - hash: `" + ${RuntimeGlobals.getFullHash}() + "`, - hashWithLength: length => - `" + ${RuntimeGlobals.getFullHash}}().slice(0, ${length}) + "`, - module: { - id: '" + wasmModuleId + "', - hash: `" + ${JSON.stringify( - chunkGraph.getChunkModuleRenderedHashMap(chunk, m => - m.type.startsWith("webassembly") - ) - )}[chunkId][wasmModuleId] + "`, - hashWithLength(length) { - return `" + ${JSON.stringify( - chunkGraph.getChunkModuleRenderedHashMap( - chunk, - m => m.type.startsWith("webassembly"), - length - ) - )}[chunkId][wasmModuleId] + "`; - } - }, - runtime: chunk.runtime - } - ); - - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_wasm` - : undefined; +const VALUE_TYPE_UNDEFINED = 0; +const VALUE_TYPE_ATOM = 1; +const VALUE_TYPE_ARRAY_EXTEND = 2; +const VALUE_TYPE_OBJECT = 3; +const VALUE_TYPE_DELETE = 4; - return Template.asString([ - "// object to store loaded and loading wasm modules", - `var installedWasmModules = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{};`, - "", - // This function is used to delay reading the installed wasm module promises - // by a microtask. Sorting them doesn't help because there are edge cases where - // sorting is not possible (modules splitted into different chunks). - // So we not even trying and solve this by a microtask delay. - "function promiseResolve() { return Promise.resolve(); }", - "", - Template.asString(declarations), - "var wasmImportObjects = {", - Template.indent(importObjects), - "};", - "", - `var wasmModuleMap = ${JSON.stringify( - chunkModuleIdMap, - undefined, - "\t" - )};`, - "", - "// object with all WebAssembly.instance exports", - `${RuntimeGlobals.wasmInstances} = {};`, - "", - "// Fetch + compile chunk loading for webassembly", - `${fn}.wasm = function(chunkId, promises) {`, - Template.indent([ - "", - `var wasmModules = wasmModuleMap[chunkId] || [];`, - "", - "wasmModules.forEach(function(wasmModuleId, idx) {", - Template.indent([ - "var installedWasmModuleData = installedWasmModules[wasmModuleId];", - "", - '// a Promise means "currently loading" or "already loaded".', - "if(installedWasmModuleData)", - Template.indent(["promises.push(installedWasmModuleData);"]), - "else {", - Template.indent([ - `var importObject = wasmImportObjects[wasmModuleId]();`, - `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, - "var promise;", - this.supportsStreaming - ? Template.asString([ - "if(importObject && typeof importObject.then === 'function' && typeof WebAssembly.compileStreaming === 'function') {", - Template.indent([ - "promise = Promise.all([WebAssembly.compileStreaming(req), importObject]).then(function(items) {", - Template.indent([ - `return WebAssembly.instantiate(items[0], ${createImportObject( - "items[1]" - )});` - ]), - "});" - ]), - "} else if(typeof WebAssembly.instantiateStreaming === 'function') {", - Template.indent([ - `promise = WebAssembly.instantiateStreaming(req, ${createImportObject( - "importObject" - )});` - ]) - ]) - : Template.asString([ - "if(importObject && typeof importObject.then === 'function') {", - Template.indent([ - "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", - "promise = Promise.all([", - Template.indent([ - "bytesPromise.then(function(bytes) { return WebAssembly.compile(bytes); }),", - "importObject" - ]), - "]).then(function(items) {", - Template.indent([ - `return WebAssembly.instantiate(items[0], ${createImportObject( - "items[1]" - )});` - ]), - "});" - ]) - ]), - "} else {", - Template.indent([ - "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", - "promise = bytesPromise.then(function(bytes) {", - Template.indent([ - `return WebAssembly.instantiate(bytes, ${createImportObject( - "importObject" - )});` - ]), - "});" - ]), - "}", - "promises.push(installedWasmModules[wasmModuleId] = promise.then(function(res) {", - Template.indent([ - `return ${RuntimeGlobals.wasmInstances}[wasmModuleId] = (res.instance || res).exports;` - ]), - "}));" - ]), - "}" - ]), - "});" - ]), - "};" - ]); +/** + * @param {any} value a single value + * @returns {VALUE_TYPE_UNDEFINED | VALUE_TYPE_ATOM | VALUE_TYPE_ARRAY_EXTEND | VALUE_TYPE_OBJECT | VALUE_TYPE_DELETE} value type + */ +const getValueType = value => { + if (value === undefined) { + return VALUE_TYPE_UNDEFINED; + } else if (value === DELETE) { + return VALUE_TYPE_DELETE; + } else if (Array.isArray(value)) { + if (value.lastIndexOf("...") !== -1) return VALUE_TYPE_ARRAY_EXTEND; + return VALUE_TYPE_ATOM; + } else if ( + typeof value === "object" && + value !== null && + (!value.constructor || value.constructor === Object) + ) { + return VALUE_TYPE_OBJECT; } -} - -module.exports = WasmChunkLoadingRuntimeModule; - - -/***/ }), - -/***/ 19810: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return VALUE_TYPE_ATOM; +}; +/** + * Merges two objects. Objects are deeply clever merged. + * Arrays might reference the old value with "...". + * Non-object values take preference over object values. + * @template T + * @template O + * @param {T} first first object + * @param {O} second second object + * @returns {T & O | T | O} merged object of first and second object + */ +const cleverMerge = (first, second) => { + if (second === undefined) return first; + if (first === undefined) return second; + if (typeof second !== "object" || second === null) return second; + if (typeof first !== "object" || first === null) return first; + return _cleverMerge(first, second, false); +}; -const formatLocation = __webpack_require__(16734); -const UnsupportedWebAssemblyFeatureError = __webpack_require__(78455); +/** + * Merges two objects. Objects are deeply clever merged. + * @param {object} first first object + * @param {object} second second object + * @param {boolean} internalCaching should parsing of objects and nested merges be cached + * @returns {object} merged object of first and second object + */ +const _cleverMerge = (first, second, internalCaching = false) => { + const firstObject = internalCaching + ? cachedParseObject(first) + : parseObject(first); + const { static: firstInfo, dynamic: firstDynamicInfo } = firstObject; -/** @typedef {import("../Compiler")} Compiler */ + // If the first argument has a dynamic part we modify the dynamic part to merge the second argument + if (firstDynamicInfo !== undefined) { + let { byProperty, fn } = firstDynamicInfo; + const fnInfo = fn[DYNAMIC_INFO]; + if (fnInfo) { + second = internalCaching + ? cachedCleverMerge(fnInfo[1], second) + : cleverMerge(fnInfo[1], second); + fn = fnInfo[0]; + } + const newFn = (...args) => { + const fnResult = fn(...args); + return internalCaching + ? cachedCleverMerge(fnResult, second) + : cleverMerge(fnResult, second); + }; + newFn[DYNAMIC_INFO] = [fn, second]; + return serializeObject(firstObject.static, { byProperty, fn: newFn }); + } -class WasmFinalizeExportsPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap("WasmFinalizeExportsPlugin", compilation => { - compilation.hooks.finishModules.tap( - "WasmFinalizeExportsPlugin", - modules => { - for (const module of modules) { - // 1. if a WebAssembly module - if (module.type.startsWith("webassembly") === true) { - const jsIncompatibleExports = - module.buildMeta.jsIncompatibleExports; + // If the first part is static only, we merge the static parts and keep the dynamic part of the second argument + const secondObject = internalCaching + ? cachedParseObject(second) + : parseObject(second); + const { static: secondInfo, dynamic: secondDynamicInfo } = secondObject; + /** @type {Map} */ + const resultInfo = new Map(); + for (const [key, firstEntry] of firstInfo) { + const secondEntry = secondInfo.get(key); + const entry = + secondEntry !== undefined + ? mergeEntries(firstEntry, secondEntry, internalCaching) + : firstEntry; + resultInfo.set(key, entry); + } + for (const [key, secondEntry] of secondInfo) { + if (!firstInfo.has(key)) { + resultInfo.set(key, secondEntry); + } + } + return serializeObject(resultInfo, secondDynamicInfo); +}; - if (jsIncompatibleExports === undefined) { - continue; - } +/** + * @param {ObjectParsedPropertyEntry} firstEntry a + * @param {ObjectParsedPropertyEntry} secondEntry b + * @param {boolean} internalCaching should parsing of objects and nested merges be cached + * @returns {ObjectParsedPropertyEntry} new entry + */ +const mergeEntries = (firstEntry, secondEntry, internalCaching) => { + switch (getValueType(secondEntry.base)) { + case VALUE_TYPE_ATOM: + case VALUE_TYPE_DELETE: + // No need to consider firstEntry at all + // second value override everything + // = second.base + second.byProperty + return secondEntry; + case VALUE_TYPE_UNDEFINED: + if (!firstEntry.byProperty) { + // = first.base + second.byProperty + return { + base: firstEntry.base, + byProperty: secondEntry.byProperty, + byValues: secondEntry.byValues + }; + } else if (firstEntry.byProperty !== secondEntry.byProperty) { + throw new Error( + `${firstEntry.byProperty} and ${secondEntry.byProperty} for a single property is not supported` + ); + } else { + // = first.base + (first.byProperty + second.byProperty) + // need to merge first and second byValues + const newByValues = new Map(firstEntry.byValues); + for (const [key, value] of secondEntry.byValues) { + const firstValue = getFromByValues(firstEntry.byValues, key); + newByValues.set( + key, + mergeSingleValue(firstValue, value, internalCaching) + ); + } + return { + base: firstEntry.base, + byProperty: firstEntry.byProperty, + byValues: newByValues + }; + } + default: { + if (!firstEntry.byProperty) { + // The simple case + // = (first.base + second.base) + second.byProperty + return { + base: mergeSingleValue( + firstEntry.base, + secondEntry.base, + internalCaching + ), + byProperty: secondEntry.byProperty, + byValues: secondEntry.byValues + }; + } + let newBase; + const intermediateByValues = new Map(firstEntry.byValues); + for (const [key, value] of intermediateByValues) { + intermediateByValues.set( + key, + mergeSingleValue(value, secondEntry.base, internalCaching) + ); + } + if ( + Array.from(firstEntry.byValues.values()).every(value => { + const type = getValueType(value); + return type === VALUE_TYPE_ATOM || type === VALUE_TYPE_DELETE; + }) + ) { + // = (first.base + second.base) + ((first.byProperty + second.base) + second.byProperty) + newBase = mergeSingleValue( + firstEntry.base, + secondEntry.base, + internalCaching + ); + } else { + // = first.base + ((first.byProperty (+default) + second.base) + second.byProperty) + newBase = firstEntry.base; + if (!intermediateByValues.has("default")) + intermediateByValues.set("default", secondEntry.base); + } + if (!secondEntry.byProperty) { + // = first.base + (first.byProperty + second.base) + return { + base: newBase, + byProperty: firstEntry.byProperty, + byValues: intermediateByValues + }; + } else if (firstEntry.byProperty !== secondEntry.byProperty) { + throw new Error( + `${firstEntry.byProperty} and ${secondEntry.byProperty} for a single property is not supported` + ); + } + const newByValues = new Map(intermediateByValues); + for (const [key, value] of secondEntry.byValues) { + const firstValue = getFromByValues(intermediateByValues, key); + newByValues.set( + key, + mergeSingleValue(firstValue, value, internalCaching) + ); + } + return { + base: newBase, + byProperty: firstEntry.byProperty, + byValues: newByValues + }; + } + } +}; - for (const connection of compilation.moduleGraph.getIncomingConnections( - module - )) { - // 2. is active and referenced by a non-WebAssembly module - if ( - connection.isTargetActive(undefined) && - connection.originModule.type.startsWith("webassembly") === - false - ) { - const referencedExports = - compilation.getDependencyReferencedExports( - connection.dependency, - undefined - ); +/** + * @param {Map} byValues all values + * @param {string} key value of the selector + * @returns {any | undefined} value + */ +const getFromByValues = (byValues, key) => { + if (key !== "default" && byValues.has(key)) { + return byValues.get(key); + } + return byValues.get("default"); +}; - for (const info of referencedExports) { - const names = Array.isArray(info) ? info : info.name; - if (names.length === 0) continue; - const name = names[0]; - if (typeof name === "object") continue; - // 3. and uses a func with an incompatible JS signature - if ( - Object.prototype.hasOwnProperty.call( - jsIncompatibleExports, - name - ) - ) { - // 4. error - const error = new UnsupportedWebAssemblyFeatureError( - `Export "${name}" with ${jsIncompatibleExports[name]} can only be used for direct wasm to wasm dependencies\n` + - `It's used from ${connection.originModule.readableIdentifier( - compilation.requestShortener - )} at ${formatLocation(connection.dependency.loc)}.` - ); - error.module = module; - compilation.errors.push(error); - } - } - } +/** + * @param {any} a value + * @param {any} b value + * @param {boolean} internalCaching should parsing of objects and nested merges be cached + * @returns {any} value + */ +const mergeSingleValue = (a, b, internalCaching) => { + const bType = getValueType(b); + const aType = getValueType(a); + switch (bType) { + case VALUE_TYPE_DELETE: + case VALUE_TYPE_ATOM: + return b; + case VALUE_TYPE_OBJECT: { + return aType !== VALUE_TYPE_OBJECT + ? b + : internalCaching + ? cachedCleverMerge(a, b) + : cleverMerge(a, b); + } + case VALUE_TYPE_UNDEFINED: + return a; + case VALUE_TYPE_ARRAY_EXTEND: + switch ( + aType !== VALUE_TYPE_ATOM + ? aType + : Array.isArray(a) + ? VALUE_TYPE_ARRAY_EXTEND + : VALUE_TYPE_OBJECT + ) { + case VALUE_TYPE_UNDEFINED: + return b; + case VALUE_TYPE_DELETE: + return b.filter(item => item !== "..."); + case VALUE_TYPE_ARRAY_EXTEND: { + const newArray = []; + for (const item of b) { + if (item === "...") { + for (const item of a) { + newArray.push(item); } + } else { + newArray.push(item); } } + return newArray; } - ); - }); + case VALUE_TYPE_OBJECT: + return b.map(item => (item === "..." ? a : item)); + default: + throw new Error("Not implemented"); + } + default: + throw new Error("Not implemented"); + } +}; + +/** + * @template T + * @param {T} obj the object + * @returns {T} the object without operations like "..." or DELETE + */ +const removeOperations = obj => { + const newObj = /** @type {T} */ ({}); + for (const key of Object.keys(obj)) { + const value = obj[key]; + const type = getValueType(value); + switch (type) { + case VALUE_TYPE_UNDEFINED: + case VALUE_TYPE_DELETE: + break; + case VALUE_TYPE_OBJECT: + newObj[key] = removeOperations(value); + break; + case VALUE_TYPE_ARRAY_EXTEND: + newObj[key] = value.filter(i => i !== "..."); + break; + default: + newObj[key] = value; + break; + } } -} + return newObj; +}; -module.exports = WasmFinalizeExportsPlugin; +/** + * @template T + * @template {string} P + * @param {T} obj the object + * @param {P} byProperty the by description + * @param {...any} values values + * @returns {Omit} object with merged byProperty + */ +const resolveByProperty = (obj, byProperty, ...values) => { + if (typeof obj !== "object" || obj === null || !(byProperty in obj)) { + return obj; + } + const { [byProperty]: _byValue, ..._remaining } = /** @type {object} */ (obj); + const remaining = /** @type {T} */ (_remaining); + const byValue = /** @type {Record | function(...any[]): T} */ ( + _byValue + ); + if (typeof byValue === "object") { + const key = values[0]; + if (key in byValue) { + return cachedCleverMerge(remaining, byValue[key]); + } else if ("default" in byValue) { + return cachedCleverMerge(remaining, byValue.default); + } else { + return /** @type {T} */ (remaining); + } + } else if (typeof byValue === "function") { + const result = byValue.apply(null, values); + return cachedCleverMerge( + remaining, + resolveByProperty(result, byProperty, ...values) + ); + } +}; + +exports.cachedSetProperty = cachedSetProperty; +exports.cachedCleverMerge = cachedCleverMerge; +exports.cleverMerge = cleverMerge; +exports.resolveByProperty = resolveByProperty; +exports.removeOperations = removeOperations; +exports.DELETE = DELETE; /***/ }), -/***/ 47012: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 29579: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -130779,619 +136898,713 @@ module.exports = WasmFinalizeExportsPlugin; -const { RawSource } = __webpack_require__(51255); -const Generator = __webpack_require__(93401); -const WebAssemblyUtils = __webpack_require__(18650); - -const t = __webpack_require__(51826); -const { moduleContextFromModuleAST } = __webpack_require__(51826); -const { editWithAST, addWithAST } = __webpack_require__(87362); -const { decode } = __webpack_require__(73726); - -const WebAssemblyExportImportedDependency = __webpack_require__(52204); +const { compareRuntime } = __webpack_require__(17156); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../Module")} Module */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -/** @typedef {import("./WebAssemblyUtils").UsedWasmDependency} UsedWasmDependency */ -/** - * @typedef {(ArrayBuffer) => ArrayBuffer} ArrayBufferTransform - */ +/** @template T @typedef {function(T, T): -1|0|1} Comparator */ +/** @template TArg @template T @typedef {function(TArg, T, T): -1|0|1} RawParameterizedComparator */ +/** @template TArg @template T @typedef {function(TArg): Comparator} ParameterizedComparator */ /** * @template T - * @param {Function[]} fns transforms - * @returns {Function} composed transform + * @param {RawParameterizedComparator} fn comparator with argument + * @returns {ParameterizedComparator} comparator */ -const compose = (...fns) => { - return fns.reduce( - (prevFn, nextFn) => { - return value => nextFn(prevFn(value)); - }, - value => value - ); +const createCachedParameterizedComparator = fn => { + /** @type {WeakMap>} */ + const map = new WeakMap(); + return arg => { + const cachedResult = map.get(arg); + if (cachedResult !== undefined) return cachedResult; + /** + * @param {T} a first item + * @param {T} b second item + * @returns {-1|0|1} compare result + */ + const result = fn.bind(null, arg); + map.set(arg, result); + return result; + }; }; /** - * Removes the start instruction - * - * @param {Object} state unused state - * @returns {ArrayBufferTransform} transform + * @param {Chunk} a chunk + * @param {Chunk} b chunk + * @returns {-1|0|1} compare result */ -const removeStartFunc = state => bin => { - return editWithAST(state.ast, bin, { - Start(path) { - path.remove(); - } - }); +exports.compareChunksById = (a, b) => { + return compareIds(a.id, b.id); }; /** - * Get imported globals - * - * @param {Object} ast Module's AST - * @returns {Array} - nodes + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result */ -const getImportedGlobals = ast => { - const importedGlobals = []; - - t.traverse(ast, { - ModuleImport({ node }) { - if (t.isGlobalType(node.descr)) { - importedGlobals.push(node); - } - } - }); - - return importedGlobals; +exports.compareModulesByIdentifier = (a, b) => { + return compareIds(a.identifier(), b.identifier()); }; /** - * Get the count for imported func - * - * @param {Object} ast Module's AST - * @returns {Number} - count + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result */ -const getCountImportedFunc = ast => { - let count = 0; - - t.traverse(ast, { - ModuleImport({ node }) { - if (t.isFuncImportDescr(node.descr)) { - count++; - } - } - }); - - return count; +const compareModulesById = (chunkGraph, a, b) => { + return compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b)); }; +/** @type {ParameterizedComparator} */ +exports.compareModulesById = + createCachedParameterizedComparator(compareModulesById); /** - * Get next type index - * - * @param {Object} ast Module's AST - * @returns {t.Index} - index + * @param {number} a number + * @param {number} b number + * @returns {-1|0|1} compare result */ -const getNextTypeIndex = ast => { - const typeSectionMetadata = t.getSectionMetadata(ast, "type"); - - if (typeSectionMetadata === undefined) { - return t.indexLiteral(0); +const compareNumbers = (a, b) => { + if (typeof a !== typeof b) { + return typeof a < typeof b ? -1 : 1; } - - return t.indexLiteral(typeSectionMetadata.vectorOfSize.value); + if (a < b) return -1; + if (a > b) return 1; + return 0; }; +exports.compareNumbers = compareNumbers; /** - * Get next func index - * - * The Func section metadata provide informations for implemented funcs - * in order to have the correct index we shift the index by number of external - * functions. - * - * @param {Object} ast Module's AST - * @param {Number} countImportedFunc number of imported funcs - * @returns {t.Index} - index + * @param {string} a string + * @param {string} b string + * @returns {-1|0|1} compare result */ -const getNextFuncIndex = (ast, countImportedFunc) => { - const funcSectionMetadata = t.getSectionMetadata(ast, "func"); - - if (funcSectionMetadata === undefined) { - return t.indexLiteral(0 + countImportedFunc); +const compareStringsNumeric = (a, b) => { + const partsA = a.split(/(\d+)/); + const partsB = b.split(/(\d+)/); + const len = Math.min(partsA.length, partsB.length); + for (let i = 0; i < len; i++) { + const pA = partsA[i]; + const pB = partsB[i]; + if (i % 2 === 0) { + if (pA.length > pB.length) { + if (pA.slice(0, pB.length) > pB) return 1; + return -1; + } else if (pB.length > pA.length) { + if (pB.slice(0, pA.length) > pA) return -1; + return 1; + } else { + if (pA < pB) return -1; + if (pA > pB) return 1; + } + } else { + const nA = +pA; + const nB = +pB; + if (nA < nB) return -1; + if (nA > nB) return 1; + } } + if (partsB.length < partsA.length) return 1; + if (partsB.length > partsA.length) return -1; + return 0; +}; +exports.compareStringsNumeric = compareStringsNumeric; - const vectorOfSize = funcSectionMetadata.vectorOfSize.value; +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result + */ +const compareModulesByPostOrderIndexOrIdentifier = (moduleGraph, a, b) => { + const cmp = compareNumbers( + moduleGraph.getPostOrderIndex(a), + moduleGraph.getPostOrderIndex(b) + ); + if (cmp !== 0) return cmp; + return compareIds(a.identifier(), b.identifier()); +}; +/** @type {ParameterizedComparator} */ +exports.compareModulesByPostOrderIndexOrIdentifier = + createCachedParameterizedComparator( + compareModulesByPostOrderIndexOrIdentifier + ); - return t.indexLiteral(vectorOfSize + countImportedFunc); +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result + */ +const compareModulesByPreOrderIndexOrIdentifier = (moduleGraph, a, b) => { + const cmp = compareNumbers( + moduleGraph.getPreOrderIndex(a), + moduleGraph.getPreOrderIndex(b) + ); + if (cmp !== 0) return cmp; + return compareIds(a.identifier(), b.identifier()); }; +/** @type {ParameterizedComparator} */ +exports.compareModulesByPreOrderIndexOrIdentifier = + createCachedParameterizedComparator( + compareModulesByPreOrderIndexOrIdentifier + ); /** - * Creates an init instruction for a global type - * @param {t.GlobalType} globalType the global type - * @returns {t.Instruction} init expression + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result */ -const createDefaultInitForGlobal = globalType => { - if (globalType.valtype[0] === "i") { - // create NumberLiteral global initializer - return t.objectInstruction("const", globalType.valtype, [ - t.numberLiteralFromRaw(66) - ]); - } else if (globalType.valtype[0] === "f") { - // create FloatLiteral global initializer - return t.objectInstruction("const", globalType.valtype, [ - t.floatLiteral(66, false, false, "66") - ]); - } else { - throw new Error("unknown type: " + globalType.valtype); - } +const compareModulesByIdOrIdentifier = (chunkGraph, a, b) => { + const cmp = compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b)); + if (cmp !== 0) return cmp; + return compareIds(a.identifier(), b.identifier()); }; +/** @type {ParameterizedComparator} */ +exports.compareModulesByIdOrIdentifier = createCachedParameterizedComparator( + compareModulesByIdOrIdentifier +); /** - * Rewrite the import globals: - * - removes the ModuleImport instruction - * - injects at the same offset a mutable global of the same type - * - * Since the imported globals are before the other global declarations, our - * indices will be preserved. - * - * Note that globals will become mutable. - * - * @param {Object} state unused state - * @returns {ArrayBufferTransform} transform + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk} a chunk + * @param {Chunk} b chunk + * @returns {-1|0|1} compare result */ -const rewriteImportedGlobals = state => bin => { - const additionalInitCode = state.additionalInitCode; - const newGlobals = []; +const compareChunks = (chunkGraph, a, b) => { + return chunkGraph.compareChunks(a, b); +}; +/** @type {ParameterizedComparator} */ +exports.compareChunks = createCachedParameterizedComparator(compareChunks); - bin = editWithAST(state.ast, bin, { - ModuleImport(path) { - if (t.isGlobalType(path.node.descr)) { - const globalType = path.node.descr; +/** + * @param {string|number} a first id + * @param {string|number} b second id + * @returns {-1|0|1} compare result + */ +const compareIds = (a, b) => { + if (typeof a !== typeof b) { + return typeof a < typeof b ? -1 : 1; + } + if (a < b) return -1; + if (a > b) return 1; + return 0; +}; - globalType.mutability = "var"; +exports.compareIds = compareIds; - const init = [ - createDefaultInitForGlobal(globalType), - t.instruction("end") - ]; +/** + * @param {string} a first string + * @param {string} b second string + * @returns {-1|0|1} compare result + */ +const compareStrings = (a, b) => { + if (a < b) return -1; + if (a > b) return 1; + return 0; +}; - newGlobals.push(t.global(globalType, init)); +exports.compareStrings = compareStrings; - path.remove(); - } - }, +/** + * @param {ChunkGroup} a first chunk group + * @param {ChunkGroup} b second chunk group + * @returns {-1|0|1} compare result + */ +const compareChunkGroupsByIndex = (a, b) => { + return a.index < b.index ? -1 : 1; +}; - // in order to preserve non-imported global's order we need to re-inject - // those as well - Global(path) { - const { node } = path; - const [init] = node.init; +exports.compareChunkGroupsByIndex = compareChunkGroupsByIndex; - if (init.id === "get_global") { - node.globalType.mutability = "var"; +/** + * @template K1 {Object} + * @template K2 + * @template T + */ +class TwoKeyWeakMap { + constructor() { + /** @private @type {WeakMap>} */ + this._map = new WeakMap(); + } - const initialGlobalIdx = init.args[0]; + /** + * @param {K1} key1 first key + * @param {K2} key2 second key + * @returns {T | undefined} value + */ + get(key1, key2) { + const childMap = this._map.get(key1); + if (childMap === undefined) { + return undefined; + } + return childMap.get(key2); + } - node.init = [ - createDefaultInitForGlobal(node.globalType), - t.instruction("end") - ]; + /** + * @param {K1} key1 first key + * @param {K2} key2 second key + * @param {T | undefined} value new value + * @returns {void} + */ + set(key1, key2, value) { + let childMap = this._map.get(key1); + if (childMap === undefined) { + childMap = new WeakMap(); + this._map.set(key1, childMap); + } + childMap.set(key2, value); + } +} - additionalInitCode.push( - /** - * get_global in global initializer only works for imported globals. - * They have the same indices as the init params, so use the - * same index. - */ - t.instruction("get_local", [initialGlobalIdx]), - t.instruction("set_global", [t.indexLiteral(newGlobals.length)]) - ); - } +/** @type {TwoKeyWeakMap, Comparator, Comparator>}} */ +const concatComparatorsCache = new TwoKeyWeakMap(); - newGlobals.push(node); +/** + * @template T + * @param {Comparator} c1 comparator + * @param {Comparator} c2 comparator + * @param {Comparator[]} cRest comparators + * @returns {Comparator} comparator + */ +const concatComparators = (c1, c2, ...cRest) => { + if (cRest.length > 0) { + const [c3, ...cRest2] = cRest; + return concatComparators(c1, concatComparators(c2, c3, ...cRest2)); + } + const cacheEntry = /** @type {Comparator} */ ( + concatComparatorsCache.get(c1, c2) + ); + if (cacheEntry !== undefined) return cacheEntry; + /** + * @param {T} a first value + * @param {T} b second value + * @returns {-1|0|1} compare result + */ + const result = (a, b) => { + const res = c1(a, b); + if (res !== 0) return res; + return c2(a, b); + }; + concatComparatorsCache.set(c1, c2, result); + return result; +}; +exports.concatComparators = concatComparators; - path.remove(); - } - }); +/** @template A, B @typedef {(input: A) => B} Selector */ - // Add global declaration instructions - return addWithAST(state.ast, bin, newGlobals); -}; +/** @type {TwoKeyWeakMap, Comparator, Comparator>}} */ +const compareSelectCache = new TwoKeyWeakMap(); /** - * Rewrite the export names - * @param {Object} state state - * @param {Object} state.ast Module's ast - * @param {Module} state.module Module - * @param {ModuleGraph} state.moduleGraph module graph - * @param {Set} state.externalExports Module - * @param {RuntimeSpec} state.runtime runtime - * @returns {ArrayBufferTransform} transform + * @template T + * @template R + * @param {Selector} getter getter for value + * @param {Comparator} comparator comparator + * @returns {Comparator} comparator */ -const rewriteExportNames = - ({ ast, moduleGraph, module, externalExports, runtime }) => - bin => { - return editWithAST(ast, bin, { - ModuleExport(path) { - const isExternal = externalExports.has(path.node.name); - if (isExternal) { - path.remove(); - return; - } - const usedName = moduleGraph - .getExportsInfo(module) - .getUsedName(path.node.name, runtime); - if (!usedName) { - path.remove(); - return; - } - path.node.name = usedName; +const compareSelect = (getter, comparator) => { + const cacheEntry = compareSelectCache.get(getter, comparator); + if (cacheEntry !== undefined) return cacheEntry; + /** + * @param {T} a first value + * @param {T} b second value + * @returns {-1|0|1} compare result + */ + const result = (a, b) => { + const aValue = getter(a); + const bValue = getter(b); + if (aValue !== undefined && aValue !== null) { + if (bValue !== undefined && bValue !== null) { + return comparator(aValue, bValue); } - }); + return -1; + } else { + if (bValue !== undefined && bValue !== null) { + return 1; + } + return 0; + } }; + compareSelectCache.set(getter, comparator, result); + return result; +}; +exports.compareSelect = compareSelect; + +/** @type {WeakMap, Comparator>>} */ +const compareIteratorsCache = new WeakMap(); /** - * Mangle import names and modules - * @param {Object} state state - * @param {Object} state.ast Module's ast - * @param {Map} state.usedDependencyMap mappings to mangle names - * @returns {ArrayBufferTransform} transform + * @template T + * @param {Comparator} elementComparator comparator for elements + * @returns {Comparator>} comparator for iterables of elements */ -const rewriteImports = - ({ ast, usedDependencyMap }) => - bin => { - return editWithAST(ast, bin, { - ModuleImport(path) { - const result = usedDependencyMap.get( - path.node.module + ":" + path.node.name - ); - - if (result !== undefined) { - path.node.module = result.module; - path.node.name = result.name; - } +const compareIterables = elementComparator => { + const cacheEntry = compareIteratorsCache.get(elementComparator); + if (cacheEntry !== undefined) return cacheEntry; + /** + * @param {Iterable} a first value + * @param {Iterable} b second value + * @returns {-1|0|1} compare result + */ + const result = (a, b) => { + const aI = a[Symbol.iterator](); + const bI = b[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = aI.next(); + const bItem = bI.next(); + if (aItem.done) { + return bItem.done ? 0 : -1; + } else if (bItem.done) { + return 1; } - }); + const res = elementComparator(aItem.value, bItem.value); + if (res !== 0) return res; + } }; + compareIteratorsCache.set(elementComparator, result); + return result; +}; +exports.compareIterables = compareIterables; +// TODO this is no longer needed when minimum node.js version is >= 12 +// since these versions ship with a stable sort function /** - * Add an init function. - * - * The init function fills the globals given input arguments. - * - * @param {Object} state transformation state - * @param {Object} state.ast Module's ast - * @param {t.Identifier} state.initFuncId identifier of the init function - * @param {t.Index} state.startAtFuncOffset index of the start function - * @param {t.ModuleImport[]} state.importedGlobals list of imported globals - * @param {t.Instruction[]} state.additionalInitCode list of addition instructions for the init function - * @param {t.Index} state.nextFuncIndex index of the next function - * @param {t.Index} state.nextTypeIndex index of the next type - * @returns {ArrayBufferTransform} transform + * @template T + * @param {Iterable} iterable original ordered list + * @returns {Comparator} comparator */ -const addInitFunction = - ({ - ast, - initFuncId, - startAtFuncOffset, - importedGlobals, - additionalInitCode, - nextFuncIndex, - nextTypeIndex - }) => - bin => { - const funcParams = importedGlobals.map(importedGlobal => { - // used for debugging - const id = t.identifier( - `${importedGlobal.module}.${importedGlobal.name}` - ); - - return t.funcParam(importedGlobal.descr.valtype, id); - }); +exports.keepOriginalOrder = iterable => { + /** @type {Map} */ + const map = new Map(); + let i = 0; + for (const item of iterable) { + map.set(item, i++); + } + return (a, b) => compareNumbers(map.get(a), map.get(b)); +}; - const funcBody = []; - importedGlobals.forEach((importedGlobal, index) => { - const args = [t.indexLiteral(index)]; - const body = [ - t.instruction("get_local", args), - t.instruction("set_global", args) - ]; +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {Comparator} comparator + */ +exports.compareChunksNatural = chunkGraph => { + const cmpFn = exports.compareModulesById(chunkGraph); + const cmpIterableFn = compareIterables(cmpFn); + return concatComparators( + compareSelect(chunk => chunk.name, compareIds), + compareSelect(chunk => chunk.runtime, compareRuntime), + compareSelect( + /** + * @param {Chunk} chunk a chunk + * @returns {Iterable} modules + */ + chunk => chunkGraph.getOrderedChunkModulesIterable(chunk, cmpFn), + cmpIterableFn + ) + ); +}; - funcBody.push(...body); - }); +/** + * Compare two locations + * @param {DependencyLocation} a A location node + * @param {DependencyLocation} b A location node + * @returns {-1|0|1} sorting comparator value + */ +exports.compareLocations = (a, b) => { + let isObjectA = typeof a === "object" && a !== null; + let isObjectB = typeof b === "object" && b !== null; + if (!isObjectA || !isObjectB) { + if (isObjectA) return 1; + if (isObjectB) return -1; + return 0; + } + if ("start" in a) { + if ("start" in b) { + const ap = a.start; + const bp = b.start; + if (ap.line < bp.line) return -1; + if (ap.line > bp.line) return 1; + if (ap.column < bp.column) return -1; + if (ap.column > bp.column) return 1; + } else return -1; + } else if ("start" in b) return 1; + if ("name" in a) { + if ("name" in b) { + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + } else return -1; + } else if ("name" in b) return 1; + if ("index" in a) { + if ("index" in b) { + if (a.index < b.index) return -1; + if (a.index > b.index) return 1; + } else return -1; + } else if ("index" in b) return 1; + return 0; +}; - if (typeof startAtFuncOffset === "number") { - funcBody.push( - t.callInstruction(t.numberLiteralFromRaw(startAtFuncOffset)) - ); - } - for (const instr of additionalInitCode) { - funcBody.push(instr); - } +/***/ }), - funcBody.push(t.instruction("end")); +/***/ 29404: +/***/ (function(module) { - const funcResults = []; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Code section - const funcSignature = t.signature(funcParams, funcResults); - const func = t.func(initFuncId, funcSignature, funcBody); - // Type section - const functype = t.typeInstruction(undefined, funcSignature); - // Func section - const funcindex = t.indexInFuncSection(nextTypeIndex); +const quoteMeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); +}; - // Export section - const moduleExport = t.moduleExport( - initFuncId.value, - t.moduleExportDescr("Func", nextFuncIndex) - ); +const toSimpleString = str => { + if (`${+str}` === str) { + return str; + } + return JSON.stringify(str); +}; - return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]); - }; +/** + * @param {Record} map value map + * @returns {true|false|function(string): string} true/false, when unconditionally true/false, or a template function to determine the value at runtime + */ +const compileBooleanMatcher = map => { + const positiveItems = Object.keys(map).filter(i => map[i]); + const negativeItems = Object.keys(map).filter(i => !map[i]); + if (positiveItems.length === 0) return false; + if (negativeItems.length === 0) return true; + return compileBooleanMatcherFromLists(positiveItems, negativeItems); +}; /** - * Extract mangle mappings from module - * @param {ModuleGraph} moduleGraph module graph - * @param {Module} module current module - * @param {boolean} mangle mangle imports - * @returns {Map} mappings to mangled names + * @param {string[]} positiveItems positive items + * @param {string[]} negativeItems negative items + * @returns {function(string): string} a template function to determine the value at runtime */ -const getUsedDependencyMap = (moduleGraph, module, mangle) => { - /** @type {Map} */ - const map = new Map(); - for (const usedDep of WebAssemblyUtils.getUsedDependencies( - moduleGraph, - module, - mangle - )) { - const dep = usedDep.dependency; - const request = dep.request; - const exportName = dep.name; - map.set(request + ":" + exportName, usedDep); +const compileBooleanMatcherFromLists = (positiveItems, negativeItems) => { + if (positiveItems.length === 0) return () => "false"; + if (negativeItems.length === 0) return () => "true"; + if (positiveItems.length === 1) + return value => `${toSimpleString(positiveItems[0])} == ${value}`; + if (negativeItems.length === 1) + return value => `${toSimpleString(negativeItems[0])} != ${value}`; + const positiveRegexp = itemsToRegexp(positiveItems); + const negativeRegexp = itemsToRegexp(negativeItems); + if (positiveRegexp.length <= negativeRegexp.length) { + return value => `/^${positiveRegexp}$/.test(${value})`; + } else { + return value => `!/^${negativeRegexp}$/.test(${value})`; } - return map; }; -const TYPES = new Set(["webassembly"]); - -class WebAssemblyGenerator extends Generator { - constructor(options) { - super(); - this.options = options; +const popCommonItems = (itemsSet, getKey, condition) => { + const map = new Map(); + for (const item of itemsSet) { + const key = getKey(item); + if (key) { + let list = map.get(key); + if (list === undefined) { + list = []; + map.set(key, list); + } + list.push(item); + } } - - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; + const result = []; + for (const list of map.values()) { + if (condition(list)) { + for (const item of list) { + itemsSet.delete(item); + } + result.push(list); + } } + return result; +}; - /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module - */ - getSize(module, type) { - const originalSource = module.originalSource(); - if (!originalSource) { - return 0; +const getCommonPrefix = items => { + let prefix = items[0]; + for (let i = 1; i < items.length; i++) { + const item = items[i]; + for (let p = 0; p < prefix.length; p++) { + if (item[p] !== prefix[p]) { + prefix = prefix.slice(0, p); + break; + } } - return originalSource.size(); } + return prefix; +}; - /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code - */ - generate(module, { moduleGraph, runtime }) { - const bin = module.originalSource().source(); - - const initFuncId = t.identifier(""); - - // parse it - const ast = decode(bin, { - ignoreDataSection: true, - ignoreCodeSection: true, - ignoreCustomNameSection: true - }); +const getCommonSuffix = items => { + let suffix = items[0]; + for (let i = 1; i < items.length; i++) { + const item = items[i]; + for (let p = item.length - 1, s = suffix.length - 1; s >= 0; p--, s--) { + if (item[p] !== suffix[s]) { + suffix = suffix.slice(s + 1); + break; + } + } + } + return suffix; +}; - const moduleContext = moduleContextFromModuleAST(ast.body[0]); +const itemsToRegexp = itemsArr => { + if (itemsArr.length === 1) { + return quoteMeta(itemsArr[0]); + } + const finishedItems = []; - const importedGlobals = getImportedGlobals(ast); - const countImportedFunc = getCountImportedFunc(ast); - const startAtFuncOffset = moduleContext.getStart(); - const nextFuncIndex = getNextFuncIndex(ast, countImportedFunc); - const nextTypeIndex = getNextTypeIndex(ast); + // merge single char items: (a|b|c|d|ef) => ([abcd]|ef) + let countOfSingleCharItems = 0; + for (const item of itemsArr) { + if (item.length === 1) { + countOfSingleCharItems++; + } + } + // special case for only single char items + if (countOfSingleCharItems === itemsArr.length) { + return `[${quoteMeta(itemsArr.sort().join(""))}]`; + } + const items = new Set(itemsArr.sort()); + if (countOfSingleCharItems > 2) { + let singleCharItems = ""; + for (const item of items) { + if (item.length === 1) { + singleCharItems += item; + items.delete(item); + } + } + finishedItems.push(`[${quoteMeta(singleCharItems)}]`); + } - const usedDependencyMap = getUsedDependencyMap( - moduleGraph, - module, - this.options.mangleImports - ); - const externalExports = new Set( - module.dependencies - .filter(d => d instanceof WebAssemblyExportImportedDependency) - .map(d => { - const wasmDep = /** @type {WebAssemblyExportImportedDependency} */ ( - d - ); - return wasmDep.exportName; - }) + // special case for 2 items with common prefix/suffix + if (finishedItems.length === 0 && items.size === 2) { + const prefix = getCommonPrefix(itemsArr); + const suffix = getCommonSuffix( + itemsArr.map(item => item.slice(prefix.length)) ); + if (prefix.length > 0 || suffix.length > 0) { + return `${quoteMeta(prefix)}${itemsToRegexp( + itemsArr.map(i => i.slice(prefix.length, -suffix.length || undefined)) + )}${quoteMeta(suffix)}`; + } + } - /** @type {t.Instruction[]} */ - const additionalInitCode = []; - - const transform = compose( - rewriteExportNames({ - ast, - moduleGraph, - module, - externalExports, - runtime - }), - - removeStartFunc({ ast }), - - rewriteImportedGlobals({ ast, additionalInitCode }), - - rewriteImports({ - ast, - usedDependencyMap - }), + // special case for 2 items with common suffix + if (finishedItems.length === 0 && items.size === 2) { + const it = items[Symbol.iterator](); + const a = it.next().value; + const b = it.next().value; + if (a.length > 0 && b.length > 0 && a.slice(-1) === b.slice(-1)) { + return `${itemsToRegexp([a.slice(0, -1), b.slice(0, -1)])}${quoteMeta( + a.slice(-1) + )}`; + } + } - addInitFunction({ - ast, - initFuncId, - importedGlobals, - additionalInitCode, - startAtFuncOffset, - nextFuncIndex, - nextTypeIndex - }) + // find common prefix: (a1|a2|a3|a4|b5) => (a(1|2|3|4)|b5) + const prefixed = popCommonItems( + items, + item => (item.length >= 1 ? item[0] : false), + list => { + if (list.length >= 3) return true; + if (list.length <= 1) return false; + return list[0][1] === list[1][1]; + } + ); + for (const prefixedItems of prefixed) { + const prefix = getCommonPrefix(prefixedItems); + finishedItems.push( + `${quoteMeta(prefix)}${itemsToRegexp( + prefixedItems.map(i => i.slice(prefix.length)) + )}` ); + } - const newBin = transform(bin); - - const newBuf = Buffer.from(newBin); - - return new RawSource(newBuf); + // find common suffix: (a1|b1|c1|d1|e2) => ((a|b|c|d)1|e2) + const suffixed = popCommonItems( + items, + item => (item.length >= 1 ? item.slice(-1) : false), + list => { + if (list.length >= 3) return true; + if (list.length <= 1) return false; + return list[0].slice(-2) === list[1].slice(-2); + } + ); + for (const suffixedItems of suffixed) { + const suffix = getCommonSuffix(suffixedItems); + finishedItems.push( + `${itemsToRegexp( + suffixedItems.map(i => i.slice(0, -suffix.length)) + )}${quoteMeta(suffix)}` + ); } -} -module.exports = WebAssemblyGenerator; + // TODO further optimize regexp, i. e. + // use ranges: (1|2|3|4|a) => [1-4a] + const conditional = finishedItems.concat(Array.from(items, quoteMeta)); + if (conditional.length === 1) return conditional[0]; + return `(${conditional.join("|")})`; +}; + +compileBooleanMatcher.fromLists = compileBooleanMatcherFromLists; +compileBooleanMatcher.itemsToRegexp = itemsToRegexp; +module.exports = compileBooleanMatcher; /***/ }), -/***/ 47342: +/***/ 32540: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const WebpackError = __webpack_require__(53799); - -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../RequestShortener")} RequestShortener */ +const memoize = __webpack_require__(78676); -/** - * @param {Module} module module to get chains from - * @param {ModuleGraph} moduleGraph the module graph - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {RequestShortener} requestShortener to make readable identifiers - * @returns {string[]} all chains to the module - */ -const getInitialModuleChains = ( - module, - moduleGraph, - chunkGraph, - requestShortener -) => { - const queue = [ - { head: module, message: module.readableIdentifier(requestShortener) } - ]; - /** @type {Set} */ - const results = new Set(); - /** @type {Set} */ - const incompleteResults = new Set(); - /** @type {Set} */ - const visitedModules = new Set(); +const getValidate = memoize(() => (__webpack_require__(38476).validate)); - for (const chain of queue) { - const { head, message } = chain; - let final = true; - /** @type {Set} */ - const alreadyReferencedModules = new Set(); - for (const connection of moduleGraph.getIncomingConnections(head)) { - const newHead = connection.originModule; - if (newHead) { - if (!chunkGraph.getModuleChunks(newHead).some(c => c.canBeInitial())) - continue; - final = false; - if (alreadyReferencedModules.has(newHead)) continue; - alreadyReferencedModules.add(newHead); - const moduleName = newHead.readableIdentifier(requestShortener); - const detail = connection.explanation - ? ` (${connection.explanation})` - : ""; - const newMessage = `${moduleName}${detail} --> ${message}`; - if (visitedModules.has(newHead)) { - incompleteResults.add(`... --> ${newMessage}`); - continue; - } - visitedModules.add(newHead); - queue.push({ - head: newHead, - message: newMessage - }); - } else { - final = false; - const newMessage = connection.explanation - ? `(${connection.explanation}) --> ${message}` - : message; - results.add(newMessage); +const createSchemaValidation = (check, getSchema, options) => { + getSchema = memoize(getSchema); + return value => { + if (check && !check(value)) { + getValidate()(getSchema(), value, options); + if (check) { + (__webpack_require__(73837).deprecate)( + () => {}, + "webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.", + "DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID" + )(); } } - if (final) { - results.add(message); - } - } - for (const result of incompleteResults) { - results.add(result); - } - return Array.from(results); + }; }; -module.exports = class WebAssemblyInInitialChunkError extends WebpackError { - /** - * @param {Module} module WASM module - * @param {ModuleGraph} moduleGraph the module graph - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {RequestShortener} requestShortener request shortener - */ - constructor(module, moduleGraph, chunkGraph, requestShortener) { - const moduleChains = getInitialModuleChains( - module, - moduleGraph, - chunkGraph, - requestShortener - ); - const message = `WebAssembly module is included in initial chunk. -This is not allowed, because WebAssembly download and compilation must happen asynchronous. -Add an async split point (i. e. import()) somewhere between your entrypoint and the WebAssembly module: -${moduleChains.map(s => `* ${s}`).join("\n")}`; - - super(message); - this.name = "WebAssemblyInInitialChunkError"; - this.hideStack = true; - this.module = module; - } -}; +module.exports = createSchemaValidation; /***/ }), -/***/ 46545: +/***/ 49835: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -131402,371 +137615,176 @@ ${moduleChains.map(s => `* ${s}`).join("\n")}`; -const { RawSource } = __webpack_require__(51255); -const { UsageState } = __webpack_require__(63686); -const Generator = __webpack_require__(93401); -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(1626); -const ModuleDependency = __webpack_require__(80321); -const WebAssemblyExportImportedDependency = __webpack_require__(52204); -const WebAssemblyImportDependency = __webpack_require__(5239); +const Hash = __webpack_require__(36692); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +const BULK_SIZE = 2000; -const TYPES = new Set(["webassembly"]); +// We are using an object instead of a Map as this will stay static during the runtime +// so access to it can be optimized by v8 +const digestCaches = {}; -class WebAssemblyJavascriptGenerator extends Generator { +class BulkUpdateDecorator extends Hash { /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) + * @param {Hash | function(): Hash} hashOrFactory function to create a hash + * @param {string=} hashKey key for caching */ - getTypes(module) { - return TYPES; + constructor(hashOrFactory, hashKey) { + super(); + this.hashKey = hashKey; + if (typeof hashOrFactory === "function") { + this.hashFactory = hashOrFactory; + this.hash = undefined; + } else { + this.hashFactory = undefined; + this.hash = hashOrFactory; + } + this.buffer = ""; } /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash */ - getSize(module, type) { - return 95 + module.dependencies.length * 5; + update(data, inputEncoding) { + if ( + inputEncoding !== undefined || + typeof data !== "string" || + data.length > BULK_SIZE + ) { + if (this.hash === undefined) this.hash = this.hashFactory(); + if (this.buffer.length > 0) { + this.hash.update(this.buffer); + this.buffer = ""; + } + this.hash.update(data, inputEncoding); + } else { + this.buffer += data; + if (this.buffer.length > BULK_SIZE) { + if (this.hash === undefined) this.hash = this.hashFactory(); + this.hash.update(this.buffer); + this.buffer = ""; + } + } + return this; } /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest */ - generate(module, generateContext) { - const { - runtimeTemplate, - moduleGraph, - chunkGraph, - runtimeRequirements, - runtime - } = generateContext; - /** @type {InitFragment[]} */ - const initFragments = []; - - const exportsInfo = moduleGraph.getExportsInfo(module); - - let needExportsCopy = false; - const importedModules = new Map(); - const initParams = []; - let index = 0; - for (const dep of module.dependencies) { - const moduleDep = - dep && dep instanceof ModuleDependency ? dep : undefined; - if (moduleGraph.getModule(dep)) { - let importData = importedModules.get(moduleGraph.getModule(dep)); - if (importData === undefined) { - importedModules.set( - moduleGraph.getModule(dep), - (importData = { - importVar: `m${index}`, - index, - request: (moduleDep && moduleDep.userRequest) || undefined, - names: new Set(), - reexports: [] - }) - ); - index++; - } - if (dep instanceof WebAssemblyImportDependency) { - importData.names.add(dep.name); - if (dep.description.type === "GlobalType") { - const exportName = dep.name; - const importedModule = moduleGraph.getModule(dep); - - if (importedModule) { - const usedName = moduleGraph - .getExportsInfo(importedModule) - .getUsedName(exportName, runtime); - if (usedName) { - initParams.push( - runtimeTemplate.exportFromImport({ - moduleGraph, - module: importedModule, - request: dep.request, - importVar: importData.importVar, - originModule: module, - exportName: dep.name, - asiSafe: true, - isCall: false, - callContext: null, - defaultInterop: true, - initFragments, - runtime, - runtimeRequirements - }) - ); - } - } - } - } - if (dep instanceof WebAssemblyExportImportedDependency) { - importData.names.add(dep.name); - const usedName = moduleGraph - .getExportsInfo(module) - .getUsedName(dep.exportName, runtime); - if (usedName) { - runtimeRequirements.add(RuntimeGlobals.exports); - const exportProp = `${module.exportsArgument}[${JSON.stringify( - usedName - )}]`; - const defineStatement = Template.asString([ - `${exportProp} = ${runtimeTemplate.exportFromImport({ - moduleGraph, - module: moduleGraph.getModule(dep), - request: dep.request, - importVar: importData.importVar, - originModule: module, - exportName: dep.name, - asiSafe: true, - isCall: false, - callContext: null, - defaultInterop: true, - initFragments, - runtime, - runtimeRequirements - })};`, - `if(WebAssembly.Global) ${exportProp} = ` + - `new WebAssembly.Global({ value: ${JSON.stringify( - dep.valueType - )} }, ${exportProp});` - ]); - importData.reexports.push(defineStatement); - needExportsCopy = true; - } - } + digest(encoding) { + let digestCache; + const buffer = this.buffer; + if (this.hash === undefined) { + // short data for hash, we can use caching + const cacheKey = `${this.hashKey}-${encoding}`; + digestCache = digestCaches[cacheKey]; + if (digestCache === undefined) { + digestCache = digestCaches[cacheKey] = new Map(); } + const cacheEntry = digestCache.get(buffer); + if (cacheEntry !== undefined) return cacheEntry; + this.hash = this.hashFactory(); } - const importsCode = Template.asString( - Array.from( - importedModules, - ([module, { importVar, request, reexports }]) => { - const importStatement = runtimeTemplate.importStatement({ - module, - chunkGraph, - request, - importVar, - originModule: module, - runtimeRequirements - }); - return importStatement[0] + importStatement[1] + reexports.join("\n"); - } - ) - ); - - const copyAllExports = - exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused && - !needExportsCopy; - - // need these globals - runtimeRequirements.add(RuntimeGlobals.module); - runtimeRequirements.add(RuntimeGlobals.moduleId); - runtimeRequirements.add(RuntimeGlobals.wasmInstances); - if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { - runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); - runtimeRequirements.add(RuntimeGlobals.exports); + if (buffer.length > 0) { + this.hash.update(buffer); } - if (!copyAllExports) { - runtimeRequirements.add(RuntimeGlobals.exports); + const digestResult = this.hash.digest(encoding); + const result = + typeof digestResult === "string" ? digestResult : digestResult.toString(); + if (digestCache !== undefined) { + digestCache.set(buffer, result); } - - // create source - const source = new RawSource( - [ - '"use strict";', - "// Instantiate WebAssembly module", - `var wasmExports = ${RuntimeGlobals.wasmInstances}[${module.moduleArgument}.id];`, - - exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused - ? `${RuntimeGlobals.makeNamespaceObject}(${module.exportsArgument});` - : "", - - // this must be before import for circular dependencies - "// export exports from WebAssembly module", - copyAllExports - ? `${module.moduleArgument}.exports = wasmExports;` - : "for(var name in wasmExports) " + - `if(name) ` + - `${module.exportsArgument}[name] = wasmExports[name];`, - "// exec imports from WebAssembly module (for esm order)", - importsCode, - "", - "// exec wasm module", - `wasmExports[""](${initParams.join(", ")})` - ].join("\n") - ); - return InitFragment.addToSource(source, initFragments, generateContext); + return result; } } -module.exports = WebAssemblyJavascriptGenerator; - - -/***/ }), - -/***/ 53639: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Generator = __webpack_require__(93401); -const WebAssemblyExportImportedDependency = __webpack_require__(52204); -const WebAssemblyImportDependency = __webpack_require__(5239); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const memoize = __webpack_require__(78676); -const WebAssemblyInInitialChunkError = __webpack_require__(47342); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleTemplate")} ModuleTemplate */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ - -const getWebAssemblyGenerator = memoize(() => - __webpack_require__(47012) -); -const getWebAssemblyJavascriptGenerator = memoize(() => - __webpack_require__(46545) -); -const getWebAssemblyParser = memoize(() => __webpack_require__(57059)); - -class WebAssemblyModulesPlugin { - constructor(options) { - this.options = options; +/* istanbul ignore next */ +class DebugHash extends Hash { + constructor() { + super(); + this.string = ""; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash */ - apply(compiler) { - compiler.hooks.compilation.tap( - "WebAssemblyModulesPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - WebAssemblyImportDependency, - normalModuleFactory - ); - - compilation.dependencyFactories.set( - WebAssemblyExportImportedDependency, - normalModuleFactory - ); - - normalModuleFactory.hooks.createParser - .for("webassembly/sync") - .tap("WebAssemblyModulesPlugin", () => { - const WebAssemblyParser = getWebAssemblyParser(); - - return new WebAssemblyParser(); - }); - - normalModuleFactory.hooks.createGenerator - .for("webassembly/sync") - .tap("WebAssemblyModulesPlugin", () => { - const WebAssemblyJavascriptGenerator = - getWebAssemblyJavascriptGenerator(); - const WebAssemblyGenerator = getWebAssemblyGenerator(); - - return Generator.byType({ - javascript: new WebAssemblyJavascriptGenerator(), - webassembly: new WebAssemblyGenerator(this.options) - }); - }); - - compilation.hooks.renderManifest.tap( - "WebAssemblyModulesPlugin", - (result, options) => { - const { chunkGraph } = compilation; - const { chunk, outputOptions, codeGenerationResults } = options; - - for (const module of chunkGraph.getOrderedChunkModulesIterable( - chunk, - compareModulesByIdentifier - )) { - if (module.type === "webassembly/sync") { - const filenameTemplate = - outputOptions.webassemblyModuleFilename; + update(data, inputEncoding) { + if (typeof data !== "string") data = data.toString("utf-8"); + if (data.startsWith("debug-digest-")) { + data = Buffer.from(data.slice("debug-digest-".length), "hex").toString(); + } + this.string += `[${data}](${new Error().stack.split("\n", 3)[2]})\n`; + return this; + } - result.push({ - render: () => - codeGenerationResults.getSource( - module, - chunk.runtime, - "webassembly" - ), - filenameTemplate, - pathOptions: { - module, - runtime: chunk.runtime, - chunkGraph - }, - auxiliary: true, - identifier: `webassemblyModule${chunkGraph.getModuleId( - module - )}`, - hash: chunkGraph.getModuleHash(module, chunk.runtime) - }); - } - } + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + return "debug-digest-" + Buffer.from(this.string).toString("hex"); + } +} - return result; - } - ); +let crypto = undefined; +let createXXHash64 = undefined; +let createMd4 = undefined; +let BatchedHash = undefined; - compilation.hooks.afterChunks.tap("WebAssemblyModulesPlugin", () => { - const chunkGraph = compilation.chunkGraph; - const initialWasmModules = new Set(); - for (const chunk of compilation.chunks) { - if (chunk.canBeInitial()) { - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - if (module.type === "webassembly/sync") { - initialWasmModules.add(module); - } - } - } - } - for (const module of initialWasmModules) { - compilation.errors.push( - new WebAssemblyInInitialChunkError( - module, - compilation.moduleGraph, - compilation.chunkGraph, - compilation.requestShortener - ) - ); - } - }); +/** + * Creates a hash by name or function + * @param {string | typeof Hash} algorithm the algorithm name or a constructor creating a hash + * @returns {Hash} the hash + */ +module.exports = algorithm => { + if (typeof algorithm === "function") { + return new BulkUpdateDecorator(() => new algorithm()); + } + switch (algorithm) { + // TODO add non-cryptographic algorithm here + case "debug": + return new DebugHash(); + case "xxhash64": + if (createXXHash64 === undefined) { + createXXHash64 = __webpack_require__(35028); + if (BatchedHash === undefined) { + BatchedHash = __webpack_require__(59461); + } } - ); + return new BatchedHash(createXXHash64()); + case "md4": + if (createMd4 === undefined) { + createMd4 = __webpack_require__(86884); + if (BatchedHash === undefined) { + BatchedHash = __webpack_require__(59461); + } + } + return new BatchedHash(createMd4()); + case "native-md4": + if (crypto === undefined) crypto = __webpack_require__(6113); + return new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4"); + default: + if (crypto === undefined) crypto = __webpack_require__(6113); + return new BulkUpdateDecorator( + () => crypto.createHash(algorithm), + algorithm + ); } -} - -module.exports = WebAssemblyModulesPlugin; +}; /***/ }), -/***/ 57059: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 64518: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -131776,270 +137794,269 @@ module.exports = WebAssemblyModulesPlugin; -const t = __webpack_require__(51826); -const { moduleContextFromModuleAST } = __webpack_require__(51826); -const { decode } = __webpack_require__(73726); -const Parser = __webpack_require__(11715); -const StaticExportsDependency = __webpack_require__(91418); -const WebAssemblyExportImportedDependency = __webpack_require__(52204); -const WebAssemblyImportDependency = __webpack_require__(5239); - -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ +const util = __webpack_require__(73837); -const JS_COMPAT_TYPES = new Set(["i32", "f32", "f64"]); +/** @type {Map} */ +const deprecationCache = new Map(); /** - * @param {t.Signature} signature the func signature - * @returns {null | string} the type incompatible with js types + * @typedef {Object} FakeHookMarker + * @property {true} _fakeHook it's a fake hook */ -const getJsIncompatibleType = signature => { - for (const param of signature.params) { - if (!JS_COMPAT_TYPES.has(param.valtype)) { - return `${param.valtype} as parameter`; - } - } - for (const type of signature.results) { - if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; - } - return null; -}; + +/** @template T @typedef {T & FakeHookMarker} FakeHook */ /** - * TODO why are there two different Signature types? - * @param {t.FuncSignature} signature the func signature - * @returns {null | string} the type incompatible with js types + * @param {string} message deprecation message + * @param {string} code deprecation code + * @returns {Function} function to trigger deprecation */ -const getJsIncompatibleTypeOfFuncSignature = signature => { - for (const param of signature.args) { - if (!JS_COMPAT_TYPES.has(param)) { - return `${param} as parameter`; - } - } - for (const type of signature.result) { - if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; - } - return null; +const createDeprecation = (message, code) => { + const cached = deprecationCache.get(message); + if (cached !== undefined) return cached; + const fn = util.deprecate( + () => {}, + message, + "DEP_WEBPACK_DEPRECATION_" + code + ); + deprecationCache.set(message, fn); + return fn; }; -const decoderOpts = { - ignoreCodeSection: true, - ignoreDataSection: true, +const COPY_METHODS = [ + "concat", + "entry", + "filter", + "find", + "findIndex", + "includes", + "indexOf", + "join", + "lastIndexOf", + "map", + "reduce", + "reduceRight", + "slice", + "some" +]; - // this will avoid having to lookup with identifiers in the ModuleContext - ignoreCustomNameSection: true -}; +const DISABLED_METHODS = [ + "copyWithin", + "entries", + "fill", + "keys", + "pop", + "reverse", + "shift", + "splice", + "sort", + "unshift" +]; -class WebAssemblyParser extends Parser { - constructor(options) { - super(); - this.hooks = Object.freeze({}); - this.options = options; +/** + * @param {any} set new set + * @param {string} name property name + * @returns {void} + */ +exports.arrayToSetDeprecation = (set, name) => { + for (const method of COPY_METHODS) { + if (set[method]) continue; + const d = createDeprecation( + `${name} was changed from Array to Set (using Array method '${method}' is deprecated)`, + "ARRAY_TO_SET" + ); + /** + * @deprecated + * @this {Set} + * @returns {number} count + */ + set[method] = function () { + d(); + const array = Array.from(this); + return Array.prototype[method].apply(array, arguments); + }; } - + const dPush = createDeprecation( + `${name} was changed from Array to Set (using Array method 'push' is deprecated)`, + "ARRAY_TO_SET_PUSH" + ); + const dLength = createDeprecation( + `${name} was changed from Array to Set (using Array property 'length' is deprecated)`, + "ARRAY_TO_SET_LENGTH" + ); + const dIndexer = createDeprecation( + `${name} was changed from Array to Set (indexing Array is deprecated)`, + "ARRAY_TO_SET_INDEXER" + ); /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state + * @deprecated + * @this {Set} + * @returns {number} count */ - parse(source, state) { - if (!Buffer.isBuffer(source)) { - throw new Error("WebAssemblyParser input must be a Buffer"); + set.push = function () { + dPush(); + for (const item of Array.from(arguments)) { + this.add(item); } - - // flag it as ESM - state.module.buildInfo.strict = true; - state.module.buildMeta.exportsType = "namespace"; - - // parse it - const program = decode(source, decoderOpts); - const module = program.body[0]; - - const moduleContext = moduleContextFromModuleAST(module); - - // extract imports and exports - const exports = []; - let jsIncompatibleExports = (state.module.buildMeta.jsIncompatibleExports = - undefined); - - const importedGlobals = []; - t.traverse(module, { - ModuleExport({ node }) { - const descriptor = node.descr; - - if (descriptor.exportType === "Func") { - const funcIdx = descriptor.id.value; - - /** @type {t.FuncSignature} */ - const funcSignature = moduleContext.getFunction(funcIdx); - - const incompatibleType = - getJsIncompatibleTypeOfFuncSignature(funcSignature); - - if (incompatibleType) { - if (jsIncompatibleExports === undefined) { - jsIncompatibleExports = - state.module.buildMeta.jsIncompatibleExports = {}; - } - jsIncompatibleExports[node.name] = incompatibleType; - } - } - - exports.push(node.name); - - if (node.descr && node.descr.exportType === "Global") { - const refNode = importedGlobals[node.descr.id.value]; - if (refNode) { - const dep = new WebAssemblyExportImportedDependency( - node.name, - refNode.module, - refNode.name, - refNode.descr.valtype - ); - - state.module.addDependency(dep); - } - } - }, - - Global({ node }) { - const init = node.init[0]; - - let importNode = null; - - if (init.id === "get_global") { - const globalIdx = init.args[0].value; - - if (globalIdx < importedGlobals.length) { - importNode = importedGlobals[globalIdx]; - } - } - - importedGlobals.push(importNode); - }, - - ModuleImport({ node }) { - /** @type {false | string} */ - let onlyDirectImport = false; - - if (t.isMemory(node.descr) === true) { - onlyDirectImport = "Memory"; - } else if (t.isTable(node.descr) === true) { - onlyDirectImport = "Table"; - } else if (t.isFuncImportDescr(node.descr) === true) { - const incompatibleType = getJsIncompatibleType(node.descr.signature); - if (incompatibleType) { - onlyDirectImport = `Non-JS-compatible Func Signature (${incompatibleType})`; - } - } else if (t.isGlobalType(node.descr) === true) { - const type = node.descr.valtype; - if (!JS_COMPAT_TYPES.has(type)) { - onlyDirectImport = `Non-JS-compatible Global Type (${type})`; - } - } - - const dep = new WebAssemblyImportDependency( - node.module, - node.name, - node.descr, - onlyDirectImport + return this.size; + }; + for (const method of DISABLED_METHODS) { + if (set[method]) continue; + set[method] = () => { + throw new Error( + `${name} was changed from Array to Set (using Array method '${method}' is not possible)` + ); + }; + } + const createIndexGetter = index => { + /** + * @this {Set} a Set + * @returns {any} the value at this location + */ + const fn = function () { + dIndexer(); + let i = 0; + for (const item of this) { + if (i++ === index) return item; + } + return undefined; + }; + return fn; + }; + const defineIndexGetter = index => { + Object.defineProperty(set, index, { + get: createIndexGetter(index), + set(value) { + throw new Error( + `${name} was changed from Array to Set (indexing Array with write is not possible)` ); - - state.module.addDependency(dep); - - if (t.isGlobalType(node.descr)) { - importedGlobals.push(node); - } } }); + }; + defineIndexGetter(0); + let indexerDefined = 1; + Object.defineProperty(set, "length", { + get() { + dLength(); + const length = this.size; + for (indexerDefined; indexerDefined < length + 1; indexerDefined++) { + defineIndexGetter(indexerDefined); + } + return length; + }, + set(value) { + throw new Error( + `${name} was changed from Array to Set (writing to Array property 'length' is not possible)` + ); + } + }); + set[Symbol.isConcatSpreadable] = true; +}; - state.module.addDependency(new StaticExportsDependency(exports, false)); - - return state; +exports.createArrayToSetDeprecationSet = name => { + let initialized = false; + class SetDeprecatedArray extends Set { + constructor(items) { + super(items); + if (!initialized) { + initialized = true; + exports.arrayToSetDeprecation(SetDeprecatedArray.prototype, name); + } + } } -} - -module.exports = WebAssemblyParser; - - -/***/ }), - -/***/ 18650: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Template = __webpack_require__(1626); -const WebAssemblyImportDependency = __webpack_require__(5239); - -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ - -/** @typedef {Object} UsedWasmDependency - * @property {WebAssemblyImportDependency} dependency the dependency - * @property {string} name the export name - * @property {string} module the module name - */ + return SetDeprecatedArray; +}; -const MANGLED_MODULE = "a"; +exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => { + const message = `${name} will be frozen in future, all modifications are deprecated.${ + note && `\n${note}` + }`; + return new Proxy(obj, { + set: util.deprecate( + (target, property, value, receiver) => + Reflect.set(target, property, value, receiver), + message, + code + ), + defineProperty: util.deprecate( + (target, property, descriptor) => + Reflect.defineProperty(target, property, descriptor), + message, + code + ), + deleteProperty: util.deprecate( + (target, property) => Reflect.deleteProperty(target, property), + message, + code + ), + setPrototypeOf: util.deprecate( + (target, proto) => Reflect.setPrototypeOf(target, proto), + message, + code + ) + }); +}; /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {Module} module the module - * @param {boolean} mangle mangle module and export names - * @returns {UsedWasmDependency[]} used dependencies and (mangled) name + * @template T + * @param {T} obj object + * @param {string} message deprecation message + * @param {string} code deprecation code + * @returns {T} object with property access deprecated */ -const getUsedDependencies = (moduleGraph, module, mangle) => { - /** @type {UsedWasmDependency[]} */ - const array = []; - let importIndex = 0; - for (const dep of module.dependencies) { - if (dep instanceof WebAssemblyImportDependency) { - if ( - dep.description.type === "GlobalType" || - moduleGraph.getModule(dep) === null - ) { - continue; - } - - const exportName = dep.name; - // TODO add the following 3 lines when removing of ModuleExport is possible - // const importedModule = moduleGraph.getModule(dep); - // const usedName = importedModule && moduleGraph.getExportsInfo(importedModule).getUsedName(exportName, runtime); - // if (usedName !== false) { - if (mangle) { - array.push({ - dependency: dep, - name: Template.numberToIdentifier(importIndex++), - module: MANGLED_MODULE - }); - } else { - array.push({ - dependency: dep, - name: exportName, - module: dep.request - }); - } +const deprecateAllProperties = (obj, message, code) => { + const newObj = {}; + const descriptors = Object.getOwnPropertyDescriptors(obj); + for (const name of Object.keys(descriptors)) { + const descriptor = descriptors[name]; + if (typeof descriptor.value === "function") { + Object.defineProperty(newObj, name, { + ...descriptor, + value: util.deprecate(descriptor.value, message, code) + }); + } else if (descriptor.get || descriptor.set) { + Object.defineProperty(newObj, name, { + ...descriptor, + get: descriptor.get && util.deprecate(descriptor.get, message, code), + set: descriptor.set && util.deprecate(descriptor.set, message, code) + }); + } else { + let value = descriptor.value; + Object.defineProperty(newObj, name, { + configurable: descriptor.configurable, + enumerable: descriptor.enumerable, + get: util.deprecate(() => value, message, code), + set: descriptor.writable + ? util.deprecate(v => (value = v), message, code) + : undefined + }); } } - return array; + return /** @type {T} */ (newObj); }; +exports.deprecateAllProperties = deprecateAllProperties; -exports.getUsedDependencies = getUsedDependencies; -exports.MANGLED_MODULE = MANGLED_MODULE; +/** + * @template T + * @param {T} fakeHook fake hook implementation + * @param {string=} message deprecation message (not deprecated when unset) + * @param {string=} code deprecation code (not deprecated when unset) + * @returns {FakeHook} fake hook which redirects + */ +exports.createFakeHook = (fakeHook, message, code) => { + if (message && code) { + fakeHook = deprecateAllProperties(fakeHook, message, code); + } + return Object.freeze( + Object.assign(fakeHook, { _fakeHook: /** @type {true} */ (true) }) + ); +}; /***/ }), -/***/ 78613: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 59836: +/***/ (function(module) { "use strict"; /* @@ -132049,1044 +138066,539 @@ exports.MANGLED_MODULE = MANGLED_MODULE; -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").WasmLoadingType} WasmLoadingType */ -/** @typedef {import("../Compiler")} Compiler */ - -/** @type {WeakMap>} */ -const enabledTypes = new WeakMap(); +// Simulations show these probabilities for a single change +// 93.1% that one group is invalidated +// 4.8% that two groups are invalidated +// 1.1% that 3 groups are invalidated +// 0.1% that 4 or more groups are invalidated +// +// And these for removing/adding 10 lexically adjacent files +// 64.5% that one group is invalidated +// 24.8% that two groups are invalidated +// 7.8% that 3 groups are invalidated +// 2.7% that 4 or more groups are invalidated +// +// And these for removing/adding 3 random files +// 0% that one group is invalidated +// 3.7% that two groups are invalidated +// 80.8% that 3 groups are invalidated +// 12.3% that 4 groups are invalidated +// 3.2% that 5 or more groups are invalidated -const getEnabledTypes = compiler => { - let set = enabledTypes.get(compiler); - if (set === undefined) { - set = new Set(); - enabledTypes.set(compiler, set); +/** + * + * @param {string} a key + * @param {string} b key + * @returns {number} the similarity as number + */ +const similarity = (a, b) => { + const l = Math.min(a.length, b.length); + let dist = 0; + for (let i = 0; i < l; i++) { + const ca = a.charCodeAt(i); + const cb = b.charCodeAt(i); + dist += Math.max(0, 10 - Math.abs(ca - cb)); } - return set; + return dist; }; -class EnableWasmLoadingPlugin { - /** - * @param {WasmLoadingType} type library type that should be available - */ - constructor(type) { - this.type = type; +/** + * @param {string} a key + * @param {string} b key + * @param {Set} usedNames set of already used names + * @returns {string} the common part and a single char for the difference + */ +const getName = (a, b, usedNames) => { + const l = Math.min(a.length, b.length); + let i = 0; + while (i < l) { + if (a.charCodeAt(i) !== b.charCodeAt(i)) { + i++; + break; + } + i++; } - - /** - * @param {Compiler} compiler the compiler instance - * @param {WasmLoadingType} type type of library - * @returns {void} - */ - static setEnabled(compiler, type) { - getEnabledTypes(compiler).add(type); + while (i < l) { + const name = a.slice(0, i); + const lowerName = name.toLowerCase(); + if (!usedNames.has(lowerName)) { + usedNames.add(lowerName); + return name; + } + i++; } + // names always contain a hash, so this is always unique + // we don't need to check usedNames nor add it + return a; +}; - /** - * @param {Compiler} compiler the compiler instance - * @param {WasmLoadingType} type type of library - * @returns {void} - */ - static checkEnabled(compiler, type) { - if (!getEnabledTypes(compiler).has(type)) { - throw new Error( - `Library type "${type}" is not enabled. ` + - "EnableWasmLoadingPlugin need to be used to enable this type of wasm loading. " + - 'This usually happens through the "output.enabledWasmLoadingTypes" option. ' + - 'If you are using a function as entry which sets "wasmLoading", you need to add all potential library types to "output.enabledWasmLoadingTypes". ' + - "These types are enabled: " + - Array.from(getEnabledTypes(compiler)).join(", ") - ); - } +/** + * @param {Record} total total size + * @param {Record} size single size + * @returns {void} + */ +const addSizeTo = (total, size) => { + for (const key of Object.keys(size)) { + total[key] = (total[key] || 0) + size[key]; } +}; - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const { type } = this; +/** + * @param {Record} total total size + * @param {Record} size single size + * @returns {void} + */ +const subtractSizeFrom = (total, size) => { + for (const key of Object.keys(size)) { + total[key] -= size[key]; + } +}; - // Only enable once - const enabled = getEnabledTypes(compiler); - if (enabled.has(type)) return; - enabled.add(type); +/** + * @param {Iterable} nodes some nodes + * @returns {Record} total size + */ +const sumSize = nodes => { + const sum = Object.create(null); + for (const node of nodes) { + addSizeTo(sum, node.size); + } + return sum; +}; - if (typeof type === "string") { - switch (type) { - case "fetch": { - // TODO webpack 6 remove FetchCompileWasmPlugin - const FetchCompileWasmPlugin = __webpack_require__(35537); - const FetchCompileAsyncWasmPlugin = __webpack_require__(8437); - new FetchCompileWasmPlugin({ - mangleImports: compiler.options.optimization.mangleWasmImports - }).apply(compiler); - new FetchCompileAsyncWasmPlugin().apply(compiler); - break; - } - case "async-node": { - // TODO webpack 6 remove ReadFileCompileWasmPlugin - const ReadFileCompileWasmPlugin = __webpack_require__(98939); - // @ts-expect-error typescript bug for duplicate require - const ReadFileCompileAsyncWasmPlugin = __webpack_require__(73163); - new ReadFileCompileWasmPlugin({ - mangleImports: compiler.options.optimization.mangleWasmImports - }).apply(compiler); - new ReadFileCompileAsyncWasmPlugin({ type }).apply(compiler); - break; - } - case "async-node-module": { - // @ts-expect-error typescript bug for duplicate require - const ReadFileCompileAsyncWasmPlugin = __webpack_require__(73163); - new ReadFileCompileAsyncWasmPlugin({ type, import: true }).apply( - compiler - ); - break; - } - case "universal": - throw new Error( - "Universal WebAssembly Loading is not implemented yet" - ); - default: - throw new Error(`Unsupported wasm loading type ${type}. -Plugins which provide custom wasm loading types must call EnableWasmLoadingPlugin.setEnabled(compiler, type) to disable this error.`); - } - } else { - // TODO support plugin instances here - // apply them to the compiler +const isTooBig = (size, maxSize) => { + for (const key of Object.keys(size)) { + const s = size[key]; + if (s === 0) continue; + const maxSizeValue = maxSize[key]; + if (typeof maxSizeValue === "number") { + if (s > maxSizeValue) return true; } } -} - -module.exports = EnableWasmLoadingPlugin; - - -/***/ }), - -/***/ 8437: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return false; +}; +const isTooSmall = (size, minSize) => { + for (const key of Object.keys(size)) { + const s = size[key]; + if (s === 0) continue; + const minSizeValue = minSize[key]; + if (typeof minSizeValue === "number") { + if (s < minSizeValue) return true; + } + } + return false; +}; +const getTooSmallTypes = (size, minSize) => { + const types = new Set(); + for (const key of Object.keys(size)) { + const s = size[key]; + if (s === 0) continue; + const minSizeValue = minSize[key]; + if (typeof minSizeValue === "number") { + if (s < minSizeValue) types.add(key); + } + } + return types; +}; -const RuntimeGlobals = __webpack_require__(16475); -const AsyncWasmLoadingRuntimeModule = __webpack_require__(5434); +const getNumberOfMatchingSizeTypes = (size, types) => { + let i = 0; + for (const key of Object.keys(size)) { + if (size[key] !== 0 && types.has(key)) i++; + } + return i; +}; -/** @typedef {import("../Compiler")} Compiler */ +const selectiveSizeSum = (size, types) => { + let sum = 0; + for (const key of Object.keys(size)) { + if (size[key] !== 0 && types.has(key)) sum += size[key]; + } + return sum; +}; -class FetchCompileAsyncWasmPlugin { +/** + * @template T + */ +class Node { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {T} item item + * @param {string} key key + * @param {Record} size size */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "FetchCompileAsyncWasmPlugin", - compilation => { - const globalWasmLoading = compilation.outputOptions.wasmLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const wasmLoading = - options && options.wasmLoading !== undefined - ? options.wasmLoading - : globalWasmLoading; - return wasmLoading === "fetch"; - }; - const generateLoadBinaryCode = path => - `fetch(${RuntimeGlobals.publicPath} + ${path})`; - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.instantiateWasm) - .tap("FetchCompileAsyncWasmPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - const chunkGraph = compilation.chunkGraph; - if ( - !chunkGraph.hasModuleInGraph( - chunk, - m => m.type === "webassembly/async" - ) - ) { - return; - } - set.add(RuntimeGlobals.publicPath); - compilation.addRuntimeModule( - chunk, - new AsyncWasmLoadingRuntimeModule({ - generateLoadBinaryCode, - supportsStreaming: true - }) - ); - }); - } - ); + constructor(item, key, size) { + this.item = item; + this.key = key; + this.size = size; } } -module.exports = FetchCompileAsyncWasmPlugin; - - -/***/ }), - -/***/ 35537: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const WasmChunkLoadingRuntimeModule = __webpack_require__(87394); - -/** @typedef {import("../Compiler")} Compiler */ - -// TODO webpack 6 remove - -class FetchCompileWasmPlugin { - constructor(options) { - this.options = options || {}; - } - +/** + * @template T + */ +class Group { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {Node[]} nodes nodes + * @param {number[]} similarities similarities between the nodes (length = nodes.length - 1) + * @param {Record=} size size of the group */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "FetchCompileWasmPlugin", - compilation => { - const globalWasmLoading = compilation.outputOptions.wasmLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const wasmLoading = - options && options.wasmLoading !== undefined - ? options.wasmLoading - : globalWasmLoading; - return wasmLoading === "fetch"; - }; - const generateLoadBinaryCode = path => - `fetch(${RuntimeGlobals.publicPath} + ${path})`; - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("FetchCompileWasmPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - const chunkGraph = compilation.chunkGraph; - if ( - !chunkGraph.hasModuleInGraph( - chunk, - m => m.type === "webassembly/sync" - ) - ) { - return; - } - set.add(RuntimeGlobals.moduleCache); - set.add(RuntimeGlobals.publicPath); - compilation.addRuntimeModule( - chunk, - new WasmChunkLoadingRuntimeModule({ - generateLoadBinaryCode, - supportsStreaming: true, - mangleImports: this.options.mangleImports, - runtimeRequirements: set - }) - ); - }); - } - ); + constructor(nodes, similarities, size) { + this.nodes = nodes; + this.similarities = similarities; + this.size = size || sumSize(nodes); + /** @type {string} */ + this.key = undefined; } -} - -module.exports = FetchCompileWasmPlugin; - - -/***/ }), - -/***/ 83121: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const JsonpChunkLoadingRuntimeModule = __webpack_require__(84154); - -/** @typedef {import("../Compiler")} Compiler */ -class JsonpChunkLoadingPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {function(Node): boolean} filter filter function + * @returns {Node[]} removed nodes */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "JsonpChunkLoadingPlugin", - compilation => { - const globalChunkLoading = compilation.outputOptions.chunkLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const chunkLoading = - options && options.chunkLoading !== undefined - ? options.chunkLoading - : globalChunkLoading; - return chunkLoading === "jsonp"; - }; - const onceForChunkSet = new WeakSet(); - const handler = (chunk, set) => { - if (onceForChunkSet.has(chunk)) return; - onceForChunkSet.add(chunk); - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.hasOwnProperty); - compilation.addRuntimeModule( - chunk, - new JsonpChunkLoadingRuntimeModule(set) + popNodes(filter) { + const newNodes = []; + const newSimilarities = []; + const resultNodes = []; + let lastNode; + for (let i = 0; i < this.nodes.length; i++) { + const node = this.nodes[i]; + if (filter(node)) { + resultNodes.push(node); + } else { + if (newNodes.length > 0) { + newSimilarities.push( + lastNode === this.nodes[i - 1] + ? this.similarities[i - 1] + : similarity(lastNode.key, node.key) ); - }; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("JsonpChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap("JsonpChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadManifest) - .tap("JsonpChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.baseURI) - .tap("JsonpChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.onChunksLoaded) - .tap("JsonpChunkLoadingPlugin", handler); - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("JsonpChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.loadScript); - set.add(RuntimeGlobals.getChunkScriptFilename); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap("JsonpChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.loadScript); - set.add(RuntimeGlobals.getChunkUpdateScriptFilename); - set.add(RuntimeGlobals.moduleCache); - set.add(RuntimeGlobals.hmrModuleData); - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadManifest) - .tap("JsonpChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.getUpdateManifestFilename); - }); + } + newNodes.push(node); + lastNode = node; } - ); + } + if (resultNodes.length === this.nodes.length) return undefined; + this.nodes = newNodes; + this.similarities = newSimilarities; + this.size = sumSize(newNodes); + return resultNodes; } } -module.exports = JsonpChunkLoadingPlugin; - - -/***/ }), - -/***/ 84154: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const { SyncWaterfallHook } = __webpack_require__(6967); -const Compilation = __webpack_require__(85720); -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); -const chunkHasJs = (__webpack_require__(89464).chunkHasJs); -const { getInitialChunkIds } = __webpack_require__(98124); -const compileBooleanMatcher = __webpack_require__(29404); - -/** @typedef {import("../Chunk")} Chunk */ +/** + * @param {Iterable} nodes nodes + * @returns {number[]} similarities + */ +const getSimilarities = nodes => { + // calculate similarities between lexically adjacent nodes + /** @type {number[]} */ + const similarities = []; + let last = undefined; + for (const node of nodes) { + if (last !== undefined) { + similarities.push(similarity(last.key, node.key)); + } + last = node; + } + return similarities; +}; /** - * @typedef {Object} JsonpCompilationPluginHooks - * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload - * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch + * @template T + * @typedef {Object} GroupedItems + * @property {string} key + * @property {T[]} items + * @property {Record} size */ -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); +/** + * @template T + * @typedef {Object} Options + * @property {Record} maxSize maximum size of a group + * @property {Record} minSize minimum size of a group (preferred over maximum size) + * @property {Iterable} items a list of items + * @property {function(T): Record} getSize function to get size of an item + * @property {function(T): string} getKey function to get the key of an item + */ -class JsonpChunkLoadingRuntimeModule extends RuntimeModule { - /** - * @param {Compilation} compilation the compilation - * @returns {JsonpCompilationPluginHooks} 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 = { - linkPreload: new SyncWaterfallHook(["source", "chunk"]), - linkPrefetch: new SyncWaterfallHook(["source", "chunk"]) - }; - compilationHooksMap.set(compilation, hooks); - } - return hooks; - } +/** + * @template T + * @param {Options} options options object + * @returns {GroupedItems[]} grouped items + */ +module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { + /** @type {Group[]} */ + const result = []; - constructor(runtimeRequirements) { - super("jsonp chunk loading", RuntimeModule.STAGE_ATTACH); - this._runtimeRequirements = runtimeRequirements; - } + const nodes = Array.from( + items, + item => new Node(item, getKey(item), getSize(item)) + ); - /** - * @returns {string} runtime code - */ - generate() { - const { chunkGraph, compilation, chunk } = this; - const { - runtimeTemplate, - outputOptions: { - chunkLoadingGlobal, - hotUpdateGlobal, - crossOriginLoading, - scriptType - } - } = compilation; - const globalObject = runtimeTemplate.globalObject; - const { linkPreload, linkPrefetch } = - JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation); - const fn = RuntimeGlobals.ensureChunkHandlers; - const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI); - const withLoading = this._runtimeRequirements.has( - RuntimeGlobals.ensureChunkHandlers - ); - const withCallback = this._runtimeRequirements.has( - RuntimeGlobals.chunkCallback - ); - const withOnChunkLoad = this._runtimeRequirements.has( - RuntimeGlobals.onChunksLoaded - ); - const withHmr = this._runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const withHmrManifest = this._runtimeRequirements.has( - RuntimeGlobals.hmrDownloadManifest - ); - const withPrefetch = this._runtimeRequirements.has( - RuntimeGlobals.prefetchChunkHandlers - ); - const withPreload = this._runtimeRequirements.has( - RuntimeGlobals.preloadChunkHandlers - ); - const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( - chunkLoadingGlobal - )}]`; - const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); - const hasJsMatcher = compileBooleanMatcher(conditionMap); - const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + /** @type {Node[]} */ + const initialNodes = []; - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_jsonp` - : undefined; + // lexically ordering of keys + nodes.sort((a, b) => { + if (a.key < b.key) return -1; + if (a.key > b.key) return 1; + return 0; + }); - return Template.asString([ - withBaseURI - ? Template.asString([ - `${RuntimeGlobals.baseURI} = document.baseURI || self.location.href;` - ]) - : "// no baseURI", - "", - "// object to store loaded and loading chunks", - "// undefined = chunk not loaded, null = chunk preloaded/prefetched", - "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", - `var installedChunks = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{`, - Template.indent( - Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join( - ",\n" - ) - ), - "};", - "", - withLoading - ? Template.asString([ - `${fn}.j = ${runtimeTemplate.basicFunction( - "chunkId, promises", - hasJsMatcher !== false - ? Template.indent([ - "// JSONP chunk loading for javascript", - `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, - 'if(installedChunkData !== 0) { // 0 means "already installed".', - Template.indent([ - "", - '// a Promise means "currently loading".', - "if(installedChunkData) {", - Template.indent([ - "promises.push(installedChunkData[2]);" - ]), - "} else {", - Template.indent([ - hasJsMatcher === true - ? "if(true) { // all chunks have JS" - : `if(${hasJsMatcher("chunkId")}) {`, - Template.indent([ - "// setup Promise in chunk cache", - `var promise = new Promise(${runtimeTemplate.expressionFunction( - `installedChunkData = installedChunks[chunkId] = [resolve, reject]`, - "resolve, reject" - )});`, - "promises.push(installedChunkData[2] = promise);", - "", - "// start chunk loading", - `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, - "// create error before stack unwound to get useful stacktrace later", - "var error = new Error();", - `var loadingEnded = ${runtimeTemplate.basicFunction( - "event", - [ - `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`, - Template.indent([ - "installedChunkData = installedChunks[chunkId];", - "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;", - "if(installedChunkData) {", - Template.indent([ - "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", - "var realSrc = event && event.target && event.target.src;", - "error.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", - "error.name = 'ChunkLoadError';", - "error.type = errorType;", - "error.request = realSrc;", - "installedChunkData[1](error);" - ]), - "}" - ]), - "}" - ] - )};`, - `${RuntimeGlobals.loadScript}(url, loadingEnded, "chunk-" + chunkId, chunkId);` - ]), - "} else installedChunks[chunkId] = 0;" - ]), - "}" - ]), - "}" - ]) - : Template.indent(["installedChunks[chunkId] = 0;"]) - )};` - ]) - : "// no chunk on demand loading", - "", - withPrefetch && hasJsMatcher !== false - ? `${ - RuntimeGlobals.prefetchChunkHandlers - }.j = ${runtimeTemplate.basicFunction("chunkId", [ - `if((!${ - RuntimeGlobals.hasOwnProperty - }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ - hasJsMatcher === true ? "true" : hasJsMatcher("chunkId") - }) {`, - Template.indent([ - "installedChunks[chunkId] = null;", - linkPrefetch.call( - Template.asString([ - "var link = document.createElement('link');", - crossOriginLoading - ? `link.crossOrigin = ${JSON.stringify( - crossOriginLoading - )};` - : "", - `if (${RuntimeGlobals.scriptNonce}) {`, - Template.indent( - `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` - ), - "}", - 'link.rel = "prefetch";', - 'link.as = "script";', - `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);` - ]), - chunk - ), - "document.head.appendChild(link);" - ]), - "}" - ])};` - : "// no prefetching", - "", - withPreload && hasJsMatcher !== false - ? `${ - RuntimeGlobals.preloadChunkHandlers - }.j = ${runtimeTemplate.basicFunction("chunkId", [ - `if((!${ - RuntimeGlobals.hasOwnProperty - }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ - hasJsMatcher === true ? "true" : hasJsMatcher("chunkId") - }) {`, - Template.indent([ - "installedChunks[chunkId] = null;", - linkPreload.call( - Template.asString([ - "var link = document.createElement('link');", - scriptType - ? `link.type = ${JSON.stringify(scriptType)};` - : "", - "link.charset = 'utf-8';", - `if (${RuntimeGlobals.scriptNonce}) {`, - Template.indent( - `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` - ), - "}", - 'link.rel = "preload";', - 'link.as = "script";', - `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, - crossOriginLoading - ? Template.asString([ - "if (link.href.indexOf(window.location.origin + '/') !== 0) {", - Template.indent( - `link.crossOrigin = ${JSON.stringify( - crossOriginLoading - )};` - ), - "}" - ]) - : "" - ]), - chunk - ), - "document.head.appendChild(link);" - ]), - "}" - ])};` - : "// no preloaded", - "", - withHmr - ? Template.asString([ - "var currentUpdatedModulesList;", - "var waitingUpdateResolves = {};", - "function loadUpdateChunk(chunkId) {", - Template.indent([ - `return new Promise(${runtimeTemplate.basicFunction( - "resolve, reject", - [ - "waitingUpdateResolves[chunkId] = resolve;", - "// start update chunk loading", - `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`, - "// create error before stack unwound to get useful stacktrace later", - "var error = new Error();", - `var loadingEnded = ${runtimeTemplate.basicFunction("event", [ - "if(waitingUpdateResolves[chunkId]) {", - Template.indent([ - "waitingUpdateResolves[chunkId] = undefined", - "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", - "var realSrc = event && event.target && event.target.src;", - "error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", - "error.name = 'ChunkLoadError';", - "error.type = errorType;", - "error.request = realSrc;", - "reject(error);" - ]), - "}" - ])};`, - `${RuntimeGlobals.loadScript}(url, loadingEnded);` - ] - )});` - ]), - "}", - "", - `${globalObject}[${JSON.stringify( - hotUpdateGlobal - )}] = ${runtimeTemplate.basicFunction( - "chunkId, moreModules, runtime", - [ - "for(var moduleId in moreModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, - Template.indent([ - "currentUpdate[moduleId] = moreModules[moduleId];", - "if(currentUpdatedModulesList) currentUpdatedModulesList.push(moduleId);" - ]), - "}" - ]), - "}", - "if(runtime) currentUpdateRuntime.push(runtime);", - "if(waitingUpdateResolves[chunkId]) {", - Template.indent([ - "waitingUpdateResolves[chunkId]();", - "waitingUpdateResolves[chunkId] = undefined;" - ]), - "}" - ] - )};`, - "", - Template.getFunctionContent( - require('./JavascriptHotModuleReplacement.runtime.js') - ) - .replace(/\$key\$/g, "jsonp") - .replace(/\$installedChunks\$/g, "installedChunks") - .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") - .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) - .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) - .replace( - /\$ensureChunkHandlers\$/g, - RuntimeGlobals.ensureChunkHandlers - ) - .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) - .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) - .replace( - /\$hmrDownloadUpdateHandlers\$/g, - RuntimeGlobals.hmrDownloadUpdateHandlers - ) - .replace( - /\$hmrInvalidateModuleHandlers\$/g, - RuntimeGlobals.hmrInvalidateModuleHandlers - ) - ]) - : "// no HMR", - "", - withHmrManifest - ? Template.asString([ - `${ - RuntimeGlobals.hmrDownloadManifest - } = ${runtimeTemplate.basicFunction("", [ - 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");', - `return fetch(${RuntimeGlobals.publicPath} + ${ - RuntimeGlobals.getUpdateManifestFilename - }()).then(${runtimeTemplate.basicFunction("response", [ - "if(response.status === 404) return; // no update available", - 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);', - "return response.json();" - ])});` - ])};` - ]) - : "// no HMR manifest", - "", - withOnChunkLoad - ? `${ - RuntimeGlobals.onChunksLoaded - }.j = ${runtimeTemplate.returningFunction( - "installedChunks[chunkId] === 0", - "chunkId" - )};` - : "// no on chunks loaded", - "", - withCallback || withLoading - ? Template.asString([ - "// install a JSONP callback for chunk loading", - `var webpackJsonpCallback = ${runtimeTemplate.basicFunction( - "parentChunkLoadingFunction, data", - [ - runtimeTemplate.destructureArray( - ["chunkIds", "moreModules", "runtime"], - "data" - ), - '// add "moreModules" to the modules object,', - '// then flag all "chunkIds" as loaded and fire callback', - "var moduleId, chunkId, i = 0;", - `if(chunkIds.some(${runtimeTemplate.returningFunction( - "installedChunks[id] !== 0", - "id" - )})) {`, - Template.indent([ - "for(moduleId in moreModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, - Template.indent( - `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` - ), - "}" - ]), - "}", - "if(runtime) var result = runtime(__webpack_require__);" - ]), - "}", - "if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);", - "for(;i < chunkIds.length; i++) {", - Template.indent([ - "chunkId = chunkIds[i];", - `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`, - Template.indent("installedChunks[chunkId][0]();"), - "}", - "installedChunks[chunkId] = 0;" - ]), - "}", - withOnChunkLoad - ? `return ${RuntimeGlobals.onChunksLoaded}(result);` - : "" - ] - )}`, - "", - `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, - "chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));", - "chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));" - ]) - : "// no jsonp function" - ]); + // return nodes bigger than maxSize directly as group + // But make sure that minSize is not violated + for (const node of nodes) { + if (isTooBig(node.size, maxSize) && !isTooSmall(node.size, minSize)) { + result.push(new Group([node], [])); + } else { + initialNodes.push(node); + } } -} -module.exports = JsonpChunkLoadingRuntimeModule; + if (initialNodes.length > 0) { + const initialGroup = new Group(initialNodes, getSimilarities(initialNodes)); + const removeProblematicNodes = (group, consideredSize = group.size) => { + const problemTypes = getTooSmallTypes(consideredSize, minSize); + if (problemTypes.size > 0) { + // We hit an edge case where the working set is already smaller than minSize + // We merge problematic nodes with the smallest result node to keep minSize intact + const problemNodes = group.popNodes( + n => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0 + ); + if (problemNodes === undefined) return false; + // Only merge it with result nodes that have the problematic size type + const possibleResultGroups = result.filter( + n => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0 + ); + if (possibleResultGroups.length > 0) { + const bestGroup = possibleResultGroups.reduce((min, group) => { + const minMatches = getNumberOfMatchingSizeTypes(min, problemTypes); + const groupMatches = getNumberOfMatchingSizeTypes( + group, + problemTypes + ); + if (minMatches !== groupMatches) + return minMatches < groupMatches ? group : min; + if ( + selectiveSizeSum(min.size, problemTypes) > + selectiveSizeSum(group.size, problemTypes) + ) + return group; + return min; + }); + for (const node of problemNodes) bestGroup.nodes.push(node); + bestGroup.nodes.sort((a, b) => { + if (a.key < b.key) return -1; + if (a.key > b.key) return 1; + return 0; + }); + } else { + // There are no other nodes with the same size types + // We create a new group and have to accept that it's smaller than minSize + result.push(new Group(problemNodes, null)); + } + return true; + } else { + return false; + } + }; -/***/ }), + if (initialGroup.nodes.length > 0) { + const queue = [initialGroup]; -/***/ 4607: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + while (queue.length) { + const group = queue.pop(); + // only groups bigger than maxSize need to be splitted + if (!isTooBig(group.size, maxSize)) { + result.push(group); + continue; + } + // If the group is already too small + // we try to work only with the unproblematic nodes + if (removeProblematicNodes(group)) { + // This changed something, so we try this group again + queue.push(group); + continue; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // find unsplittable area from left and right + // going minSize from left and right + // at least one node need to be included otherwise we get stuck + let left = 1; + let leftSize = Object.create(null); + addSizeTo(leftSize, group.nodes[0].size); + while (left < group.nodes.length && isTooSmall(leftSize, minSize)) { + addSizeTo(leftSize, group.nodes[left].size); + left++; + } + let right = group.nodes.length - 2; + let rightSize = Object.create(null); + addSizeTo(rightSize, group.nodes[group.nodes.length - 1].size); + while (right >= 0 && isTooSmall(rightSize, minSize)) { + addSizeTo(rightSize, group.nodes[right].size); + right--; + } + // left v v right + // [ O O O ] O O O [ O O O ] + // ^^^^^^^^^ leftSize + // rightSize ^^^^^^^^^ + // leftSize > minSize + // rightSize > minSize + // Perfect split: [ O O O ] [ O O O ] + // right === left - 1 -const ArrayPushCallbackChunkFormatPlugin = __webpack_require__(18535); -const EnableChunkLoadingPlugin = __webpack_require__(61291); -const JsonpChunkLoadingRuntimeModule = __webpack_require__(84154); + if (left - 1 > right) { + // We try to remove some problematic nodes to "fix" that + let prevSize; + if (right < group.nodes.length - left) { + subtractSizeFrom(rightSize, group.nodes[right + 1].size); + prevSize = rightSize; + } else { + subtractSizeFrom(leftSize, group.nodes[left - 1].size); + prevSize = leftSize; + } + if (removeProblematicNodes(group, prevSize)) { + // This changed something, so we try this group again + queue.push(group); + continue; + } + // can't split group while holding minSize + // because minSize is preferred of maxSize we return + // the problematic nodes as result here even while it's too big + // To avoid this make sure maxSize > minSize * 3 + result.push(group); + continue; + } + if (left <= right) { + // when there is a area between left and right + // we look for best split point + // we split at the minimum similarity + // here key space is separated the most + // But we also need to make sure to not create too small groups + let best = -1; + let bestSimilarity = Infinity; + let pos = left; + let rightSize = sumSize(group.nodes.slice(pos)); -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compiler")} Compiler */ + // pos v v right + // [ O O O ] O O O [ O O O ] + // ^^^^^^^^^ leftSize + // rightSize ^^^^^^^^^^^^^^^ -class JsonpTemplatePlugin { - /** - * @deprecated use JsonpChunkLoadingRuntimeModule.getCompilationHooks instead - * @param {Compilation} compilation the compilation - * @returns {JsonpChunkLoadingRuntimeModule.JsonpCompilationPluginHooks} hooks - */ - static getCompilationHooks(compilation) { - return JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation); + while (pos <= right + 1) { + const similarity = group.similarities[pos - 1]; + if ( + similarity < bestSimilarity && + !isTooSmall(leftSize, minSize) && + !isTooSmall(rightSize, minSize) + ) { + best = pos; + bestSimilarity = similarity; + } + addSizeTo(leftSize, group.nodes[pos].size); + subtractSizeFrom(rightSize, group.nodes[pos].size); + pos++; + } + if (best < 0) { + // This can't happen + // but if that assumption is wrong + // fallback to a big group + result.push(group); + continue; + } + left = best; + right = best - 1; + } + + // create two new groups for left and right area + // and queue them up + const rightNodes = [group.nodes[right + 1]]; + /** @type {number[]} */ + const rightSimilarities = []; + for (let i = right + 2; i < group.nodes.length; i++) { + rightSimilarities.push(group.similarities[i - 1]); + rightNodes.push(group.nodes[i]); + } + queue.push(new Group(rightNodes, rightSimilarities)); + + const leftNodes = [group.nodes[0]]; + /** @type {number[]} */ + const leftSimilarities = []; + for (let i = 1; i < left; i++) { + leftSimilarities.push(group.similarities[i - 1]); + leftNodes.push(group.nodes[i]); + } + queue.push(new Group(leftNodes, leftSimilarities)); + } + } } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.options.output.chunkLoading = "jsonp"; - new ArrayPushCallbackChunkFormatPlugin().apply(compiler); - new EnableChunkLoadingPlugin("jsonp").apply(compiler); + // lexically ordering + result.sort((a, b) => { + if (a.nodes[0].key < b.nodes[0].key) return -1; + if (a.nodes[0].key > b.nodes[0].key) return 1; + return 0; + }); + + // give every group a name + const usedNames = new Set(); + for (let i = 0; i < result.length; i++) { + const group = result[i]; + if (group.nodes.length === 1) { + group.key = group.nodes[0].key; + } else { + const first = group.nodes[0]; + const last = group.nodes[group.nodes.length - 1]; + const name = getName(first.key, last.key, usedNames); + group.key = name; + } } -} -module.exports = JsonpTemplatePlugin; + // return the results + return result.map(group => { + /** @type {GroupedItems} */ + return { + key: group.key, + items: group.nodes.map(node => node.item), + size: group.size + }; + }); +}; /***/ }), -/***/ 36243: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 11850: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sam Chen @chenxsan */ -const util = __webpack_require__(73837); -const webpackOptionsSchemaCheck = __webpack_require__(10382); -const webpackOptionsSchema = __webpack_require__(73342); -const Compiler = __webpack_require__(70845); -const MultiCompiler = __webpack_require__(33370); -const WebpackOptionsApply = __webpack_require__(88422); -const { - applyWebpackOptionsDefaults, - applyWebpackOptionsBaseDefaults -} = __webpack_require__(92988); -const { getNormalizedWebpackOptions } = __webpack_require__(26693); -const NodeEnvironmentPlugin = __webpack_require__(7553); -const memoize = __webpack_require__(78676); - -/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ -/** @typedef {import("./Compiler").WatchOptions} WatchOptions */ -/** @typedef {import("./MultiCompiler").MultiCompilerOptions} MultiCompilerOptions */ -/** @typedef {import("./MultiStats")} MultiStats */ -/** @typedef {import("./Stats")} Stats */ - -const getValidateSchema = memoize(() => __webpack_require__(12047)); - -/** - * @template T - * @callback Callback - * @param {Error=} err - * @param {T=} stats - * @returns {void} - */ - -/** - * @param {ReadonlyArray} childOptions options array - * @param {MultiCompilerOptions} options options - * @returns {MultiCompiler} a multi-compiler - */ -const createMultiCompiler = (childOptions, options) => { - const compilers = childOptions.map(options => createCompiler(options)); - const compiler = new MultiCompiler(compilers, options); - for (const childCompiler of compilers) { - if (childCompiler.options.dependencies) { - compiler.setDependencies( - childCompiler, - childCompiler.options.dependencies - ); - } - } - return compiler; -}; - /** - * @param {WebpackOptions} rawOptions options object - * @returns {Compiler} a compiler + * @param {string} urlAndGlobal the script request + * @returns {string[]} script url and its global variable */ -const createCompiler = rawOptions => { - const options = getNormalizedWebpackOptions(rawOptions); - applyWebpackOptionsBaseDefaults(options); - const compiler = new Compiler(options.context, options); - new NodeEnvironmentPlugin({ - infrastructureLogging: options.infrastructureLogging - }).apply(compiler); - if (Array.isArray(options.plugins)) { - for (const plugin of options.plugins) { - if (typeof plugin === "function") { - plugin.call(compiler, compiler); - } else { - plugin.apply(compiler); - } - } +module.exports = function extractUrlAndGlobal(urlAndGlobal) { + const index = urlAndGlobal.indexOf("@"); + if (index <= 0 || index === urlAndGlobal.length - 1) { + throw new Error(`Invalid request "${urlAndGlobal}"`); } - applyWebpackOptionsDefaults(options); - compiler.hooks.environment.call(); - compiler.hooks.afterEnvironment.call(); - new WebpackOptionsApply().process(options, compiler); - compiler.hooks.initialize.call(); - return compiler; + return [urlAndGlobal.substring(index + 1), urlAndGlobal.substring(0, index)]; }; -/** - * @callback WebpackFunctionSingle - * @param {WebpackOptions} options options object - * @param {Callback=} callback callback - * @returns {Compiler} the compiler object - */ - -/** - * @callback WebpackFunctionMulti - * @param {ReadonlyArray & MultiCompilerOptions} options options objects - * @param {Callback=} callback callback - * @returns {MultiCompiler} the multi compiler object - */ - -const asArray = options => - Array.isArray(options) ? Array.from(options) : [options]; - -const webpack = /** @type {WebpackFunctionSingle & WebpackFunctionMulti} */ ( - /** - * @param {WebpackOptions | (ReadonlyArray & MultiCompilerOptions)} options options - * @param {Callback & Callback=} callback callback - * @returns {Compiler | MultiCompiler} - */ - (options, callback) => { - const create = () => { - if (!asArray(options).every(webpackOptionsSchemaCheck)) { - getValidateSchema()(webpackOptionsSchema, options); - util.deprecate( - () => {}, - "webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.", - "DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID" - )(); - } - /** @type {MultiCompiler|Compiler} */ - let compiler; - let watch = false; - /** @type {WatchOptions|WatchOptions[]} */ - let watchOptions; - if (Array.isArray(options)) { - /** @type {MultiCompiler} */ - compiler = createMultiCompiler( - options, - /** @type {MultiCompilerOptions} */ (options) - ); - watch = options.some(options => options.watch); - watchOptions = options.map(options => options.watchOptions || {}); - } else { - const webpackOptions = /** @type {WebpackOptions} */ (options); - /** @type {Compiler} */ - compiler = createCompiler(webpackOptions); - watch = webpackOptions.watch; - watchOptions = webpackOptions.watchOptions || {}; - } - return { compiler, watch, watchOptions }; - }; - if (callback) { - try { - const { compiler, watch, watchOptions } = create(); - if (watch) { - compiler.watch(watchOptions, callback); - } else { - compiler.run((err, stats) => { - compiler.close(err2 => { - callback(err || err2, stats); - }); - }); - } - return compiler; - } catch (err) { - process.nextTick(() => callback(err)); - return null; - } - } else { - const { compiler, watch } = create(); - if (watch) { - util.deprecate( - () => {}, - "A 'callback' argument needs to be provided to the 'webpack(options, callback)' function when the 'watch' option is set. There is no way to handle the 'watch' option without a callback.", - "DEP_WEBPACK_WATCH_WITHOUT_CALLBACK" - )(); - } - return compiler; - } - } -); - -module.exports = webpack; - /***/ }), -/***/ 54182: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 6261: +/***/ (function(module) { "use strict"; /* @@ -133096,335 +138608,234 @@ module.exports = webpack; -const RuntimeGlobals = __webpack_require__(16475); -const StartupChunkDependenciesPlugin = __webpack_require__(22339); -const ImportScriptsChunkLoadingRuntimeModule = __webpack_require__(96952); - -/** @typedef {import("../Compiler")} Compiler */ +const NO_MARKER = 0; +const IN_PROGRESS_MARKER = 1; +const DONE_MARKER = 2; +const DONE_MAYBE_ROOT_CYCLE_MARKER = 3; +const DONE_AND_ROOT_MARKER = 4; -class ImportScriptsChunkLoadingPlugin { +/** + * @template T + */ +class Node { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {T} item the value of the node */ - apply(compiler) { - new StartupChunkDependenciesPlugin({ - chunkLoading: "import-scripts", - asyncChunkLoading: true - }).apply(compiler); - compiler.hooks.thisCompilation.tap( - "ImportScriptsChunkLoadingPlugin", - compilation => { - const globalChunkLoading = compilation.outputOptions.chunkLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const chunkLoading = - options && options.chunkLoading !== undefined - ? options.chunkLoading - : globalChunkLoading; - return chunkLoading === "import-scripts"; - }; - const onceForChunkSet = new WeakSet(); - const handler = (chunk, set) => { - if (onceForChunkSet.has(chunk)) return; - onceForChunkSet.add(chunk); - if (!isEnabledForChunk(chunk)) return; - const withCreateScriptUrl = !!compilation.outputOptions.trustedTypes; - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.hasOwnProperty); - if (withCreateScriptUrl) { - set.add(RuntimeGlobals.createScriptUrl); - } - compilation.addRuntimeModule( - chunk, - new ImportScriptsChunkLoadingRuntimeModule(set, withCreateScriptUrl) - ); - }; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("ImportScriptsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap("ImportScriptsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadManifest) - .tap("ImportScriptsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.baseURI) - .tap("ImportScriptsChunkLoadingPlugin", handler); + constructor(item) { + this.item = item; + /** @type {Set>} */ + this.dependencies = new Set(); + this.marker = NO_MARKER; + /** @type {Cycle | undefined} */ + this.cycle = undefined; + this.incoming = 0; + } +} - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("ImportScriptsChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.getChunkScriptFilename); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap("ImportScriptsChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.getChunkUpdateScriptFilename); - set.add(RuntimeGlobals.moduleCache); - set.add(RuntimeGlobals.hmrModuleData); - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadManifest) - .tap("ImportScriptsChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.getUpdateManifestFilename); - }); - } - ); +/** + * @template T + */ +class Cycle { + constructor() { + /** @type {Set>} */ + this.nodes = new Set(); } } -module.exports = ImportScriptsChunkLoadingPlugin; +/** + * @template T + * @typedef {Object} StackEntry + * @property {Node} node + * @property {Node[]} openEdges + */ -/***/ }), +/** + * @template T + * @param {Iterable} items list of items + * @param {function(T): Iterable} getDependencies function to get dependencies of an item (items that are not in list are ignored) + * @returns {Iterable} graph roots of the items + */ +module.exports = (items, getDependencies) => { + /** @type {Map>} */ + const itemToNode = new Map(); + for (const item of items) { + const node = new Node(item); + itemToNode.set(item, node); + } -/***/ 96952: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // early exit when there is only a single item + if (itemToNode.size <= 1) return items; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + // grab all the dependencies + for (const node of itemToNode.values()) { + for (const dep of getDependencies(node.item)) { + const depNode = itemToNode.get(dep); + if (depNode !== undefined) { + node.dependencies.add(depNode); + } + } + } + // Set of current root modules + // items will be removed if a new reference to it has been found + /** @type {Set>} */ + const roots = new Set(); + // Set of current cycles without references to it + // cycles will be removed if a new reference to it has been found + // that is not part of the cycle + /** @type {Set>} */ + const rootCycles = new Set(); -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(1626); -const { - getChunkFilenameTemplate, - chunkHasJs -} = __webpack_require__(89464); -const { getInitialChunkIds } = __webpack_require__(98124); -const compileBooleanMatcher = __webpack_require__(29404); -const { getUndoPath } = __webpack_require__(82186); + // For all non-marked nodes + for (const selectedNode of itemToNode.values()) { + if (selectedNode.marker === NO_MARKER) { + // deep-walk all referenced modules + // in a non-recursive way -class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { - constructor(runtimeRequirements, withCreateScriptUrl) { - super("importScripts chunk loading", RuntimeModule.STAGE_ATTACH); - this.runtimeRequirements = runtimeRequirements; - this._withCreateScriptUrl = withCreateScriptUrl; - } + // start by entering the selected node + selectedNode.marker = IN_PROGRESS_MARKER; - /** - * @returns {string} runtime code - */ - generate() { - const { - chunk, - chunkGraph, - compilation: { - runtimeTemplate, - outputOptions: { chunkLoadingGlobal, hotUpdateGlobal } - }, - _withCreateScriptUrl: withCreateScriptUrl - } = this; - const globalObject = runtimeTemplate.globalObject; - const fn = RuntimeGlobals.ensureChunkHandlers; - const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); - const withLoading = this.runtimeRequirements.has( - RuntimeGlobals.ensureChunkHandlers - ); - const withHmr = this.runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const withHmrManifest = this.runtimeRequirements.has( - RuntimeGlobals.hmrDownloadManifest - ); - const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( - chunkLoadingGlobal - )}]`; - const hasJsMatcher = compileBooleanMatcher( - chunkGraph.getChunkConditionMap(chunk, chunkHasJs) - ); - const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + // keep a stack to avoid recursive walk + /** @type {StackEntry[]} */ + const stack = [ + { + node: selectedNode, + openEdges: Array.from(selectedNode.dependencies) + } + ]; - const outputName = this.compilation.getPath( - getChunkFilenameTemplate(chunk, this.compilation.outputOptions), - { - chunk, - contentHashType: "javascript" - } - ); - const rootOutputDir = getUndoPath( - outputName, - this.compilation.outputOptions.path, - false - ); + // process the top item until stack is empty + while (stack.length > 0) { + const topOfStack = stack[stack.length - 1]; - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_importScripts` - : undefined; + // Are there still edges unprocessed in the current node? + if (topOfStack.openEdges.length > 0) { + // Process one dependency + const dependency = topOfStack.openEdges.pop(); + switch (dependency.marker) { + case NO_MARKER: + // dependency has not be visited yet + // mark it as in-progress and recurse + stack.push({ + node: dependency, + openEdges: Array.from(dependency.dependencies) + }); + dependency.marker = IN_PROGRESS_MARKER; + break; + case IN_PROGRESS_MARKER: { + // It's a in-progress cycle + let cycle = dependency.cycle; + if (!cycle) { + cycle = new Cycle(); + cycle.nodes.add(dependency); + dependency.cycle = cycle; + } + // set cycle property for each node in the cycle + // if nodes are already part of a cycle + // we merge the cycles to a shared cycle + for ( + let i = stack.length - 1; + stack[i].node !== dependency; + i-- + ) { + const node = stack[i].node; + if (node.cycle) { + if (node.cycle !== cycle) { + // merge cycles + for (const cycleNode of node.cycle.nodes) { + cycleNode.cycle = cycle; + cycle.nodes.add(cycleNode); + } + } + } else { + node.cycle = cycle; + cycle.nodes.add(node); + } + } + // don't recurse into dependencies + // these are already on the stack + break; + } + case DONE_AND_ROOT_MARKER: + // This node has be visited yet and is currently a root node + // But as this is a new reference to the node + // it's not really a root + // so we have to convert it to a normal node + dependency.marker = DONE_MARKER; + roots.delete(dependency); + break; + case DONE_MAYBE_ROOT_CYCLE_MARKER: + // This node has be visited yet and + // is maybe currently part of a completed root cycle + // we found a new reference to the cycle + // so it's not really a root cycle + // remove the cycle from the root cycles + // and convert it to a normal node + rootCycles.delete(dependency.cycle); + dependency.marker = DONE_MARKER; + break; + // DONE_MARKER: nothing to do, don't recurse into dependencies + } + } else { + // All dependencies of the current node has been visited + // we leave the node + stack.pop(); + topOfStack.node.marker = DONE_MARKER; + } + } + const cycle = selectedNode.cycle; + if (cycle) { + for (const node of cycle.nodes) { + node.marker = DONE_MAYBE_ROOT_CYCLE_MARKER; + } + rootCycles.add(cycle); + } else { + selectedNode.marker = DONE_AND_ROOT_MARKER; + roots.add(selectedNode); + } + } + } - return Template.asString([ - withBaseURI - ? Template.asString([ - `${RuntimeGlobals.baseURI} = self.location + ${JSON.stringify( - rootOutputDir ? "/../" + rootOutputDir : "" - )};` - ]) - : "// no baseURI", - "", - "// object to store loaded chunks", - '// "1" means "already loaded"', - `var installedChunks = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{`, - Template.indent( - Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 1`).join( - ",\n" - ) - ), - "};", - "", - withLoading - ? Template.asString([ - "// importScripts chunk loading", - `var installChunk = ${runtimeTemplate.basicFunction("data", [ - runtimeTemplate.destructureArray( - ["chunkIds", "moreModules", "runtime"], - "data" - ), - "for(var moduleId in moreModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, - Template.indent( - `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` - ), - "}" - ]), - "}", - "if(runtime) runtime(__webpack_require__);", - "while(chunkIds.length)", - Template.indent("installedChunks[chunkIds.pop()] = 1;"), - "parentChunkLoadingFunction(data);" - ])};` - ]) - : "// no chunk install function needed", - withLoading - ? Template.asString([ - `${fn}.i = ${runtimeTemplate.basicFunction( - "chunkId, promises", - hasJsMatcher !== false - ? [ - '// "1" is the signal for "already loaded"', - "if(!installedChunks[chunkId]) {", - Template.indent([ - hasJsMatcher === true - ? "if(true) { // all chunks have JS" - : `if(${hasJsMatcher("chunkId")}) {`, - Template.indent( - `importScripts(${ - withCreateScriptUrl - ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId))` - : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId)` - });` - ), - "}" - ]), - "}" - ] - : "installedChunks[chunkId] = 1;" - )};`, - "", - `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, - "var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);", - "chunkLoadingGlobal.push = installChunk;" - ]) - : "// no chunk loading", - "", - withHmr - ? Template.asString([ - "function loadUpdateChunk(chunkId, updatedModulesList) {", - Template.indent([ - "var success = false;", - `${globalObject}[${JSON.stringify( - hotUpdateGlobal - )}] = ${runtimeTemplate.basicFunction("_, moreModules, runtime", [ - "for(var moduleId in moreModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, - Template.indent([ - "currentUpdate[moduleId] = moreModules[moduleId];", - "if(updatedModulesList) updatedModulesList.push(moduleId);" - ]), - "}" - ]), - "}", - "if(runtime) currentUpdateRuntime.push(runtime);", - "success = true;" - ])};`, - "// start update chunk loading", - `importScripts(${ - withCreateScriptUrl - ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId))` - : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)` - });`, - 'if(!success) throw new Error("Loading update chunk failed for unknown reason");' - ]), - "}", - "", - Template.getFunctionContent( - require('./JavascriptHotModuleReplacement.runtime.js') - ) - .replace(/\$key\$/g, "importScrips") - .replace(/\$installedChunks\$/g, "installedChunks") - .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") - .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) - .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) - .replace( - /\$ensureChunkHandlers\$/g, - RuntimeGlobals.ensureChunkHandlers - ) - .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) - .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) - .replace( - /\$hmrDownloadUpdateHandlers\$/g, - RuntimeGlobals.hmrDownloadUpdateHandlers - ) - .replace( - /\$hmrInvalidateModuleHandlers\$/g, - RuntimeGlobals.hmrInvalidateModuleHandlers - ) - ]) - : "// no HMR", - "", - withHmrManifest - ? Template.asString([ - `${ - RuntimeGlobals.hmrDownloadManifest - } = ${runtimeTemplate.basicFunction("", [ - 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");', - `return fetch(${RuntimeGlobals.publicPath} + ${ - RuntimeGlobals.getUpdateManifestFilename - }()).then(${runtimeTemplate.basicFunction("response", [ - "if(response.status === 404) return; // no update available", - 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);', - "return response.json();" - ])});` - ])};` - ]) - : "// no HMR manifest" - ]); + // Extract roots from root cycles + // We take the nodes with most incoming edges + // inside of the cycle + for (const cycle of rootCycles) { + let max = 0; + /** @type {Set>} */ + const cycleRoots = new Set(); + const nodes = cycle.nodes; + for (const node of nodes) { + for (const dep of node.dependencies) { + if (nodes.has(dep)) { + dep.incoming++; + if (dep.incoming < max) continue; + if (dep.incoming > max) { + cycleRoots.clear(); + max = dep.incoming; + } + cycleRoots.add(dep); + } + } + } + for (const cycleRoot of cycleRoots) { + roots.add(cycleRoot); + } } -} -module.exports = ImportScriptsChunkLoadingRuntimeModule; + // When roots were found, return them + if (roots.size > 0) { + return Array.from(roots, r => r.item); + } else { + throw new Error("Implementation of findGraphRoots is broken"); + } +}; /***/ }), -/***/ 68693: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 17139: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -133434,129 +138845,341 @@ module.exports = ImportScriptsChunkLoadingRuntimeModule; -const ArrayPushCallbackChunkFormatPlugin = __webpack_require__(18535); -const EnableChunkLoadingPlugin = __webpack_require__(61291); +const path = __webpack_require__(71017); -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("../FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ -class WebWorkerTemplatePlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.options.output.chunkLoading = "import-scripts"; - new ArrayPushCallbackChunkFormatPlugin().apply(compiler); - new EnableChunkLoadingPlugin("import-scripts").apply(compiler); - } -} -module.exports = WebWorkerTemplatePlugin; +/** + * @typedef {Object} IStats + * @property {() => boolean} isFile + * @property {() => boolean} isDirectory + * @property {() => boolean} isBlockDevice + * @property {() => boolean} isCharacterDevice + * @property {() => boolean} isSymbolicLink + * @property {() => boolean} isFIFO + * @property {() => boolean} isSocket + * @property {number | bigint} dev + * @property {number | bigint} ino + * @property {number | bigint} mode + * @property {number | bigint} nlink + * @property {number | bigint} uid + * @property {number | bigint} gid + * @property {number | bigint} rdev + * @property {number | bigint} size + * @property {number | bigint} blksize + * @property {number | bigint} blocks + * @property {number | bigint} atimeMs + * @property {number | bigint} mtimeMs + * @property {number | bigint} ctimeMs + * @property {number | bigint} birthtimeMs + * @property {Date} atime + * @property {Date} mtime + * @property {Date} ctime + * @property {Date} birthtime + */ + +/** + * @typedef {Object} IDirent + * @property {() => boolean} isFile + * @property {() => boolean} isDirectory + * @property {() => boolean} isBlockDevice + * @property {() => boolean} isCharacterDevice + * @property {() => boolean} isSymbolicLink + * @property {() => boolean} isFIFO + * @property {() => boolean} isSocket + * @property {string | Buffer} name + */ + +/** @typedef {function((NodeJS.ErrnoException | null)=): void} Callback */ +/** @typedef {function((NodeJS.ErrnoException | null)=, Buffer=): void} BufferCallback */ +/** @typedef {function((NodeJS.ErrnoException | null)=, Buffer|string=): void} BufferOrStringCallback */ +/** @typedef {function((NodeJS.ErrnoException | null)=, (string | Buffer)[] | IDirent[]=): void} DirentArrayCallback */ +/** @typedef {function((NodeJS.ErrnoException | null)=, string=): void} StringCallback */ +/** @typedef {function((NodeJS.ErrnoException | null)=, number=): void} NumberCallback */ +/** @typedef {function((NodeJS.ErrnoException | null)=, IStats=): void} StatsCallback */ +/** @typedef {function((NodeJS.ErrnoException | Error | null)=, any=): void} ReadJsonCallback */ +/** @typedef {function((NodeJS.ErrnoException | Error | null)=, IStats|string=): void} LstatReadlinkAbsoluteCallback */ + +/** + * @typedef {Object} WatcherInfo + * @property {Set} changes get current aggregated changes that have not yet send to callback + * @property {Set} removals get current aggregated removals that have not yet send to callback + * @property {Map} fileTimeInfoEntries get info about files + * @property {Map} contextTimeInfoEntries get info about directories + */ + +// TODO webpack 6 deprecate missing getInfo +/** + * @typedef {Object} Watcher + * @property {function(): void} close closes the watcher and all underlying file watchers + * @property {function(): void} pause closes the watcher, but keeps underlying file watchers alive until the next watch call + * @property {function(): Set=} getAggregatedChanges get current aggregated changes that have not yet send to callback + * @property {function(): Set=} getAggregatedRemovals get current aggregated removals that have not yet send to callback + * @property {function(): Map} getFileTimeInfoEntries get info about files + * @property {function(): Map} getContextTimeInfoEntries get info about directories + * @property {function(): WatcherInfo=} getInfo get info about timestamps and changes + */ + +/** + * @callback WatchMethod + * @param {Iterable} files watched files + * @param {Iterable} directories watched directories + * @param {Iterable} missing watched exitance entries + * @param {number} startTime timestamp of start time + * @param {WatchOptions} options options object + * @param {function(Error=, Map, Map, Set, Set): void} callback aggregated callback + * @param {function(string, number): void} callbackUndelayed callback when the first change was detected + * @returns {Watcher} a watcher + */ +// TODO webpack 6 make optional methods required -/***/ }), +/** + * @typedef {Object} OutputFileSystem + * @property {function(string, Buffer|string, Callback): void} writeFile + * @property {function(string, Callback): void} mkdir + * @property {function(string, DirentArrayCallback): void=} readdir + * @property {function(string, Callback): void=} rmdir + * @property {function(string, Callback): void=} unlink + * @property {function(string, StatsCallback): void} stat + * @property {function(string, StatsCallback): void=} lstat + * @property {function(string, BufferOrStringCallback): void} readFile + * @property {(function(string, string): string)=} join + * @property {(function(string, string): string)=} relative + * @property {(function(string): string)=} dirname + */ -/***/ 14819: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @typedef {Object} InputFileSystem + * @property {function(string, BufferOrStringCallback): void} readFile + * @property {(function(string, ReadJsonCallback): void)=} readJson + * @property {function(string, BufferOrStringCallback): void} readlink + * @property {function(string, DirentArrayCallback): void} readdir + * @property {function(string, StatsCallback): void} stat + * @property {function(string, StatsCallback): void=} lstat + * @property {(function(string, BufferOrStringCallback): void)=} realpath + * @property {(function(string=): void)=} purge + * @property {(function(string, string): string)=} join + * @property {(function(string, string): string)=} relative + * @property {(function(string): string)=} dirname + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @typedef {Object} WatchFileSystem + * @property {WatchMethod} watch + */ +/** + * @typedef {Object} IntermediateFileSystemExtras + * @property {function(string): void} mkdirSync + * @property {function(string): NodeJS.WritableStream} createWriteStream + * @property {function(string, string, NumberCallback): void} open + * @property {function(number, Buffer, number, number, number, NumberCallback): void} read + * @property {function(number, Callback): void} close + * @property {function(string, string, Callback): void} rename + */ +/** @typedef {InputFileSystem & OutputFileSystem & IntermediateFileSystemExtras} IntermediateFileSystem */ -const DescriptionFileUtils = __webpack_require__(25424); -const getInnerRequest = __webpack_require__(47956); +/** + * + * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system + * @param {string} rootPath the root path + * @param {string} targetPath the target path + * @returns {string} location of targetPath relative to rootPath + */ +const relative = (fs, rootPath, targetPath) => { + if (fs && fs.relative) { + return fs.relative(rootPath, targetPath); + } else if (path.posix.isAbsolute(rootPath)) { + return path.posix.relative(rootPath, targetPath); + } else if (path.win32.isAbsolute(rootPath)) { + return path.win32.relative(rootPath, targetPath); + } else { + throw new Error( + `${rootPath} is neither a posix nor a windows path, and there is no 'relative' method defined in the file system` + ); + } +}; +exports.relative = relative; -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** + * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system + * @param {string} rootPath a path + * @param {string} filename a filename + * @returns {string} the joined path + */ +const join = (fs, rootPath, filename) => { + if (fs && fs.join) { + return fs.join(rootPath, filename); + } else if (path.posix.isAbsolute(rootPath)) { + return path.posix.join(rootPath, filename); + } else if (path.win32.isAbsolute(rootPath)) { + return path.win32.join(rootPath, filename); + } else { + throw new Error( + `${rootPath} is neither a posix nor a windows path, and there is no 'join' method defined in the file system` + ); + } +}; +exports.join = join; -module.exports = class AliasFieldPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | Array} field field - * @param {string | ResolveStepHook} target target - */ - constructor(source, field, target) { - this.source = source; - this.field = field; - this.target = target; +/** + * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system + * @param {string} absPath an absolute path + * @returns {string} the parent directory of the absolute path + */ +const dirname = (fs, absPath) => { + if (fs && fs.dirname) { + return fs.dirname(absPath); + } else if (path.posix.isAbsolute(absPath)) { + return path.posix.dirname(absPath); + } else if (path.win32.isAbsolute(absPath)) { + return path.win32.dirname(absPath); + } else { + throw new Error( + `${absPath} is neither a posix nor a windows path, and there is no 'dirname' method defined in the file system` + ); } +}; +exports.dirname = dirname; - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("AliasFieldPlugin", (request, resolveContext, callback) => { - if (!request.descriptionFileData) return callback(); - const innerRequest = getInnerRequest(resolver, request); - if (!innerRequest) return callback(); - const fieldData = DescriptionFileUtils.getField( - request.descriptionFileData, - this.field - ); - if (fieldData === null || typeof fieldData !== "object") { - if (resolveContext.log) - resolveContext.log( - "Field '" + - this.field + - "' doesn't contain a valid alias configuration" - ); - return callback(); +/** + * @param {OutputFileSystem} fs a file system + * @param {string} p an absolute path + * @param {function(Error=): void} callback callback function for the error + * @returns {void} + */ +const mkdirp = (fs, p, callback) => { + fs.mkdir(p, err => { + if (err) { + if (err.code === "ENOENT") { + const dir = dirname(fs, p); + if (dir === p) { + callback(err); + return; } - const data1 = fieldData[innerRequest]; - const data2 = fieldData[innerRequest.replace(/^\.\//, "")]; - const data = typeof data1 !== "undefined" ? data1 : data2; - if (data === innerRequest) return callback(); - if (data === undefined) return callback(); - if (data === false) { - /** @type {ResolveRequest} */ - const ignoreObj = { - ...request, - path: false - }; - return callback(null, ignoreObj); + mkdirp(fs, dir, err => { + if (err) { + callback(err); + return; + } + fs.mkdir(p, err => { + if (err) { + if (err.code === "EEXIST") { + callback(); + return; + } + callback(err); + return; + } + callback(); + }); + }); + return; + } else if (err.code === "EEXIST") { + callback(); + return; + } + callback(err); + return; + } + callback(); + }); +}; +exports.mkdirp = mkdirp; + +/** + * @param {IntermediateFileSystem} fs a file system + * @param {string} p an absolute path + * @returns {void} + */ +const mkdirpSync = (fs, p) => { + try { + fs.mkdirSync(p); + } catch (err) { + if (err) { + if (err.code === "ENOENT") { + const dir = dirname(fs, p); + if (dir === p) { + throw err; } - const obj = { - ...request, - path: request.descriptionFileRoot, - request: data, - fullySpecified: false - }; - resolver.doResolve( - target, - obj, - "aliased from description file " + - request.descriptionFilePath + - " with mapping '" + - innerRequest + - "' to '" + - data + - "'", - resolveContext, - (err, result) => { - if (err) return callback(err); + mkdirpSync(fs, dir); + fs.mkdirSync(p); + return; + } else if (err.code === "EEXIST") { + return; + } + throw err; + } + } +}; +exports.mkdirpSync = mkdirpSync; - // Don't allow other aliasing or raw request - if (result === undefined) return callback(null, null); - callback(null, result); - } - ); +/** + * @param {InputFileSystem} fs a file system + * @param {string} p an absolute path + * @param {ReadJsonCallback} callback callback + * @returns {void} + */ +const readJson = (fs, p, callback) => { + if ("readJson" in fs) return fs.readJson(p, callback); + fs.readFile(p, (err, buf) => { + if (err) return callback(err); + let data; + try { + data = JSON.parse(buf.toString("utf-8")); + } catch (e) { + return callback(e); + } + return callback(null, data); + }); +}; +exports.readJson = readJson; + +/** + * @param {InputFileSystem} fs a file system + * @param {string} p an absolute path + * @param {ReadJsonCallback} callback callback + * @returns {void} + */ +const lstatReadlinkAbsolute = (fs, p, callback) => { + let i = 3; + const doReadLink = () => { + fs.readlink(p, (err, target) => { + if (err && --i > 0) { + // It might was just changed from symlink to file + // we retry 2 times to catch this case before throwing the error + return doStat(); + } + if (err || !target) return doStat(); + const value = target.toString(); + callback(null, join(fs, dirname(fs, p), value)); + }); + }; + const doStat = () => { + if ("lstat" in fs) { + return fs.lstat(p, (err, stats) => { + if (err) return callback(err); + if (stats.isSymbolicLink()) { + return doReadLink(); + } + callback(null, stats); }); - } + } else { + return fs.stat(p, callback); + } + }; + if ("lstat" in fs) return doStat(); + doReadLink(); }; +exports.lstatReadlinkAbsolute = lstatReadlinkAbsolute; /***/ }), -/***/ 63676: +/***/ 59461: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -133567,114 +139190,73 @@ module.exports = class AliasFieldPlugin { -const forEachBail = __webpack_require__(78565); +const Hash = __webpack_require__(36692); +const MAX_SHORT_STRING = (__webpack_require__(1842).MAX_SHORT_STRING); -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {{alias: string|Array|false, name: string, onlyModule?: boolean}} AliasOption */ +class BatchedHash extends Hash { + constructor(hash) { + super(); + this.string = undefined; + this.encoding = undefined; + this.hash = hash; + } -module.exports = class AliasPlugin { /** - * @param {string | ResolveStepHook} source source - * @param {AliasOption | Array} options options - * @param {string | ResolveStepHook} target target + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash */ - constructor(source, options, target) { - this.source = source; - this.options = Array.isArray(options) ? options : [options]; - this.target = target; + update(data, inputEncoding) { + if (this.string !== undefined) { + if ( + typeof data === "string" && + inputEncoding === this.encoding && + this.string.length + data.length < MAX_SHORT_STRING + ) { + this.string += data; + return this; + } + this.hash.update(this.string, this.encoding); + this.string = undefined; + } + if (typeof data === "string") { + if ( + data.length < MAX_SHORT_STRING && + // base64 encoding is not valid since it may contain padding chars + (!inputEncoding || !inputEncoding.startsWith("ba")) + ) { + this.string = data; + this.encoding = inputEncoding; + } else { + this.hash.update(data, inputEncoding); + } + } else { + this.hash.update(data); + } + return this; } /** - * @param {Resolver} resolver the resolver - * @returns {void} + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("AliasPlugin", (request, resolveContext, callback) => { - const innerRequest = request.request || request.path; - if (!innerRequest) return callback(); - forEachBail( - this.options, - (item, callback) => { - let shouldStop = false; - if ( - innerRequest === item.name || - (!item.onlyModule && innerRequest.startsWith(item.name + "/")) - ) { - const remainingRequest = innerRequest.substr(item.name.length); - const resolveWithAlias = (alias, callback) => { - if (alias === false) { - const ignoreObj = { - ...request, - path: false - }; - return callback(null, ignoreObj); - } - if ( - innerRequest !== alias && - !innerRequest.startsWith(alias + "/") - ) { - shouldStop = true; - const newRequestStr = alias + remainingRequest; - const obj = { - ...request, - request: newRequestStr, - fullySpecified: false - }; - return resolver.doResolve( - target, - obj, - "aliased with mapping '" + - item.name + - "': '" + - alias + - "' to '" + - newRequestStr + - "'", - resolveContext, - (err, result) => { - if (err) return callback(err); - if (result) return callback(null, result); - return callback(); - } - ); - } - return callback(); - }; - const stoppingCallback = (err, result) => { - if (err) return callback(err); - - if (result) return callback(null, result); - // Don't allow other aliasing or raw request - if (shouldStop) return callback(null, null); - return callback(); - }; - if (Array.isArray(item.alias)) { - return forEachBail( - item.alias, - resolveWithAlias, - stoppingCallback - ); - } else { - return resolveWithAlias(item.alias, stoppingCallback); - } - } - return callback(); - }, - callback - ); - }); + digest(encoding) { + if (this.string !== undefined) { + this.hash.update(this.string, this.encoding); + } + return this.hash.digest(encoding); } -}; +} + +module.exports = BatchedHash; /***/ }), -/***/ 92088: -/***/ (function(module) { +/***/ 86884: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -133684,52 +139266,25 @@ module.exports = class AliasPlugin { -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +const create = __webpack_require__(1842); -module.exports = class AppendPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string} appending appending - * @param {string | ResolveStepHook} target target - */ - constructor(source, appending, target) { - this.source = source; - this.appending = appending; - this.target = target; - } +//#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1 +const md4 = new WebAssembly.Module( + Buffer.from( + // 2156 bytes + "AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqLEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvSCgEZfyMBIQUjAiECIwMhAyMEIQQDQCAAIAFLBEAgASgCJCISIAEoAiAiEyABKAIcIgkgASgCGCIIIAEoAhQiByABKAIQIg4gASgCDCIGIAEoAggiDyABKAIEIhAgASgCACIRIAMgBHMgAnEgBHMgBWpqQQN3IgogAiADc3EgA3MgBGpqQQd3IgsgAiAKc3EgAnMgA2pqQQt3IgwgCiALc3EgCnMgAmpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IgogDCANc3EgDHMgC2pqQQd3IgsgCiANc3EgDXMgDGpqQQt3IgwgCiALc3EgCnMgDWpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IhQgDCANc3EgDHMgC2pqQQd3IRUgASgCLCILIAEoAigiCiAMIA0gDSAUcyAVcXNqakELdyIWIBQgFXNxIBRzIA1qakETdyEXIAEoAjQiGCABKAIwIhkgFSAWcyAXcSAVcyAUampBA3ciFCAWIBdzcSAWcyAVampBB3chFSABKAI8Ig0gASgCOCIMIBQgF3MgFXEgF3MgFmpqQQt3IhYgFCAVc3EgFHMgF2pqQRN3IRcgEyAOIBEgFCAVIBZyIBdxIBUgFnFyampBmfOJ1AVqQQN3IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEFdyIVIBQgF3JxIBQgF3FyIBZqakGZ84nUBWpBCXchFiAPIBggEiAWIAcgFSAQIBQgGSAUIBVyIBZxIBQgFXFyIBdqakGZ84nUBWpBDXciFCAVIBZycSAVIBZxcmpqQZnzidQFakEDdyIVIBQgFnJxIBQgFnFyampBmfOJ1AVqQQV3IhcgFCAVcnEgFCAVcXJqakGZ84nUBWpBCXciFiAVIBdycSAVIBdxciAUampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEDdyEVIBEgBiAVIAwgFCAKIBYgCCAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFyAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIWIBUgF3JxIBUgF3FyampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXJqakGZ84nUBWpBA3ciFSALIBYgCSAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFiAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIXIA0gFSAWciAXcSAVIBZxciAUampBmfOJ1AVqQQ13IhRzIBZzampBodfn9gZqQQN3IREgByAIIA4gFCARIBcgESAUc3MgFmogE2pBodfn9gZqQQl3IhNzcyAXampBodfn9gZqQQt3Ig4gDyARIBMgDiARIA4gE3NzIBRqIBlqQaHX5/YGakEPdyIRc3NqakGh1+f2BmpBA3ciDyAOIA8gEXNzIBNqIApqQaHX5/YGakEJdyIKcyARc2pqQaHX5/YGakELdyIIIBAgDyAKIAggDCAPIAggCnNzIBFqakGh1+f2BmpBD3ciDHNzampBodfn9gZqQQN3Ig4gEiAIIAwgDnNzIApqakGh1+f2BmpBCXciCHMgDHNqakGh1+f2BmpBC3chByAFIAYgCCAHIBggDiAHIAhzcyAMampBodfn9gZqQQ93IgpzcyAOampBodfn9gZqQQN3IgZqIQUgDSAGIAkgByAGIAsgByAGIApzcyAIampBodfn9gZqQQl3IgdzIApzampBodfn9gZqQQt3IgYgB3NzIApqakGh1+f2BmpBD3cgAmohAiADIAZqIQMgBCAHaiEEIAFBQGshAQwBCwsgBSQBIAIkAiADJAMgBCQECw0AIAAQASAAIwBqJAAL/wQCA38BfiAAIwBqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=", + "base64" + ) +); +//#endregion - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("AppendPlugin", (request, resolveContext, callback) => { - const obj = { - ...request, - path: request.path + this.appending, - relativePath: - request.relativePath && request.relativePath + this.appending - }; - resolver.doResolve( - target, - obj, - this.appending, - resolveContext, - callback - ); - }); - } -}; +module.exports = create.bind(null, md4, [], 64, 32); /***/ }), -/***/ 52788: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 1842: +/***/ (function(module) { "use strict"; /* @@ -133739,481 +139294,167 @@ module.exports = class AppendPlugin { -const nextTick = (__webpack_require__(77282).nextTick); - -/** @typedef {import("./Resolver").FileSystem} FileSystem */ -/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ - -const dirname = path => { - let idx = path.length - 1; - while (idx >= 0) { - const c = path.charCodeAt(idx); - // slash or backslash - if (c === 47 || c === 92) break; - idx--; - } - if (idx < 0) return ""; - return path.slice(0, idx); -}; - -const runCallbacks = (callbacks, err, result) => { - if (callbacks.length === 1) { - callbacks[0](err, result); - callbacks.length = 0; - return; - } - let error; - for (const callback of callbacks) { - try { - callback(err, result); - } catch (e) { - if (!error) error = e; - } - } - callbacks.length = 0; - if (error) throw error; -}; +// 65536 is the size of a wasm memory page +// 64 is the maximum chunk size for every possible wasm hash implementation +// 4 is the maximum number of bytes per char for string encoding (max is utf-8) +// ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64 +const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3; -class OperationMergerBackend { +class WasmHash { /** - * @param {any} provider async method - * @param {any} syncProvider sync method - * @param {any} providerContext call context for the provider methods + * @param {WebAssembly.Instance} instance wasm instance + * @param {WebAssembly.Instance[]} instancesPool pool of instances + * @param {number} chunkSize size of data chunks passed to wasm + * @param {number} digestSize size of digest returned by wasm */ - constructor(provider, syncProvider, providerContext) { - this._provider = provider; - this._syncProvider = syncProvider; - this._providerContext = providerContext; - this._activeAsyncOperations = new Map(); - - this.provide = this._provider - ? (path, options, callback) => { - if (typeof options === "function") { - callback = options; - options = undefined; - } - if (options) { - return this._provider.call( - this._providerContext, - path, - options, - callback - ); - } - if (typeof path !== "string") { - callback(new TypeError("path must be a string")); - return; - } - let callbacks = this._activeAsyncOperations.get(path); - if (callbacks) { - callbacks.push(callback); - return; - } - this._activeAsyncOperations.set(path, (callbacks = [callback])); - provider(path, (err, result) => { - this._activeAsyncOperations.delete(path); - runCallbacks(callbacks, err, result); - }); - } - : null; - this.provideSync = this._syncProvider - ? (path, options) => { - return this._syncProvider.call(this._providerContext, path, options); - } - : null; + constructor(instance, instancesPool, chunkSize, digestSize) { + const exports = /** @type {any} */ (instance.exports); + exports.init(); + this.exports = exports; + this.mem = Buffer.from(exports.memory.buffer, 0, 65536); + this.buffered = 0; + this.instancesPool = instancesPool; + this.chunkSize = chunkSize; + this.digestSize = digestSize; } - purge() {} - purgeParent() {} -} - -/* - -IDLE: - insert data: goto SYNC - -SYNC: - before provide: run ticks - event loop tick: goto ASYNC_ACTIVE - -ASYNC: - timeout: run tick, goto ASYNC_PASSIVE - -ASYNC_PASSIVE: - before provide: run ticks - -IDLE --[insert data]--> SYNC --[event loop tick]--> ASYNC_ACTIVE --[interval tick]-> ASYNC_PASSIVE - ^ | - +---------[insert data]-------+ -*/ - -const STORAGE_MODE_IDLE = 0; -const STORAGE_MODE_SYNC = 1; -const STORAGE_MODE_ASYNC = 2; + reset() { + this.buffered = 0; + this.exports.init(); + } -class CacheBackend { /** - * @param {number} duration max cache duration of items - * @param {any} provider async method - * @param {any} syncProvider sync method - * @param {any} providerContext call context for the provider methods + * @param {Buffer | string} data data + * @param {BufferEncoding=} encoding encoding + * @returns {this} itself */ - constructor(duration, provider, syncProvider, providerContext) { - this._duration = duration; - this._provider = provider; - this._syncProvider = syncProvider; - this._providerContext = providerContext; - /** @type {Map} */ - this._activeAsyncOperations = new Map(); - /** @type {Map }>} */ - this._data = new Map(); - /** @type {Set[]} */ - this._levels = []; - for (let i = 0; i < 10; i++) this._levels.push(new Set()); - for (let i = 5000; i < duration; i += 500) this._levels.push(new Set()); - this._currentLevel = 0; - this._tickInterval = Math.floor(duration / this._levels.length); - /** @type {STORAGE_MODE_IDLE | STORAGE_MODE_SYNC | STORAGE_MODE_ASYNC} */ - this._mode = STORAGE_MODE_IDLE; - - /** @type {NodeJS.Timeout | undefined} */ - this._timeout = undefined; - /** @type {number | undefined} */ - this._nextDecay = undefined; - - this.provide = provider ? this.provide.bind(this) : null; - this.provideSync = syncProvider ? this.provideSync.bind(this) : null; - } - - provide(path, options, callback) { - if (typeof options === "function") { - callback = options; - options = undefined; - } - if (typeof path !== "string") { - callback(new TypeError("path must be a string")); - return; - } - if (options) { - return this._provider.call( - this._providerContext, - path, - options, - callback - ); - } - - // When in sync mode we can move to async mode - if (this._mode === STORAGE_MODE_SYNC) { - this._enterAsyncMode(); - } - - // Check in cache - let cacheEntry = this._data.get(path); - if (cacheEntry !== undefined) { - if (cacheEntry.err) return nextTick(callback, cacheEntry.err); - return nextTick(callback, null, cacheEntry.result); - } - - // Check if there is already the same operation running - let callbacks = this._activeAsyncOperations.get(path); - if (callbacks !== undefined) { - callbacks.push(callback); - return; - } - this._activeAsyncOperations.set(path, (callbacks = [callback])); - - // Run the operation - this._provider.call(this._providerContext, path, (err, result) => { - this._activeAsyncOperations.delete(path); - this._storeResult(path, err, result); - - // Enter async mode if not yet done - this._enterAsyncMode(); - - runCallbacks(callbacks, err, result); - }); - } - - provideSync(path, options) { - if (typeof path !== "string") { - throw new TypeError("path must be a string"); - } - if (options) { - return this._syncProvider.call(this._providerContext, path, options); - } - - // In sync mode we may have to decay some cache items - if (this._mode === STORAGE_MODE_SYNC) { - this._runDecays(); - } - - // Check in cache - let cacheEntry = this._data.get(path); - if (cacheEntry !== undefined) { - if (cacheEntry.err) throw cacheEntry.err; - return cacheEntry.result; - } - - // Get all active async operations - // This sync operation will also complete them - const callbacks = this._activeAsyncOperations.get(path); - this._activeAsyncOperations.delete(path); - - // Run the operation - // When in idle mode, we will enter sync mode - let result; - try { - result = this._syncProvider.call(this._providerContext, path); - } catch (err) { - this._storeResult(path, err, undefined); - this._enterSyncModeWhenIdle(); - if (callbacks) runCallbacks(callbacks, err, undefined); - throw err; + update(data, encoding) { + if (typeof data === "string") { + while (data.length > MAX_SHORT_STRING) { + this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding); + data = data.slice(MAX_SHORT_STRING); + } + this._updateWithShortString(data, encoding); + return this; } - this._storeResult(path, undefined, result); - this._enterSyncModeWhenIdle(); - if (callbacks) runCallbacks(callbacks, undefined, result); - return result; + this._updateWithBuffer(data); + return this; } - purge(what) { - if (!what) { - if (this._mode !== STORAGE_MODE_IDLE) { - this._data.clear(); - for (const level of this._levels) { - level.clear(); - } - this._enterIdleMode(); - } - } else if (typeof what === "string") { - for (let [key, data] of this._data) { - if (key.startsWith(what)) { - this._data.delete(key); - data.level.delete(key); - } - } - if (this._data.size === 0) { - this._enterIdleMode(); - } - } else { - for (let [key, data] of this._data) { - for (const item of what) { - if (key.startsWith(item)) { - this._data.delete(key); - data.level.delete(key); + /** + * @param {string} data data + * @param {BufferEncoding=} encoding encoding + * @returns {void} + */ + _updateWithShortString(data, encoding) { + const { exports, buffered, mem, chunkSize } = this; + let endPos; + if (data.length < 70) { + if (!encoding || encoding === "utf-8" || encoding === "utf8") { + endPos = buffered; + for (let i = 0; i < data.length; i++) { + const cc = data.charCodeAt(i); + if (cc < 0x80) mem[endPos++] = cc; + else if (cc < 0x800) { + mem[endPos] = (cc >> 6) | 0xc0; + mem[endPos + 1] = (cc & 0x3f) | 0x80; + endPos += 2; + } else { + // bail-out for weird chars + endPos += mem.write(data.slice(i), endPos, encoding); break; } } + } else if (encoding === "latin1") { + endPos = buffered; + for (let i = 0; i < data.length; i++) { + const cc = data.charCodeAt(i); + mem[endPos++] = cc; + } + } else { + endPos = buffered + mem.write(data, buffered, encoding); } - if (this._data.size === 0) { - this._enterIdleMode(); - } - } - } - - purgeParent(what) { - if (!what) { - this.purge(); - } else if (typeof what === "string") { - this.purge(dirname(what)); } else { - const set = new Set(); - for (const item of what) { - set.add(dirname(item)); - } - this.purge(set); - } - } - - _storeResult(path, err, result) { - if (this._data.has(path)) return; - const level = this._levels[this._currentLevel]; - this._data.set(path, { err, result, level }); - level.add(path); - } - - _decayLevel() { - const nextLevel = (this._currentLevel + 1) % this._levels.length; - const decay = this._levels[nextLevel]; - this._currentLevel = nextLevel; - for (let item of decay) { - this._data.delete(item); + endPos = buffered + mem.write(data, buffered, encoding); } - decay.clear(); - if (this._data.size === 0) { - this._enterIdleMode(); + if (endPos < chunkSize) { + this.buffered = endPos; } else { - // @ts-ignore _nextDecay is always a number in sync mode - this._nextDecay += this._tickInterval; - } - } - - _runDecays() { - while ( - /** @type {number} */ (this._nextDecay) <= Date.now() && - this._mode !== STORAGE_MODE_IDLE - ) { - this._decayLevel(); - } - } - - _enterAsyncMode() { - let timeout = 0; - switch (this._mode) { - case STORAGE_MODE_ASYNC: - return; - case STORAGE_MODE_IDLE: - this._nextDecay = Date.now() + this._tickInterval; - timeout = this._tickInterval; - break; - case STORAGE_MODE_SYNC: - this._runDecays(); - // @ts-ignore _runDecays may change the mode - if (this._mode === STORAGE_MODE_IDLE) return; - timeout = Math.max( - 0, - /** @type {number} */ (this._nextDecay) - Date.now() - ); - break; - } - this._mode = STORAGE_MODE_ASYNC; - const ref = setTimeout(() => { - this._mode = STORAGE_MODE_SYNC; - this._runDecays(); - }, timeout); - if (ref.unref) ref.unref(); - this._timeout = ref; - } - - _enterSyncModeWhenIdle() { - if (this._mode === STORAGE_MODE_IDLE) { - this._mode = STORAGE_MODE_SYNC; - this._nextDecay = Date.now() + this._tickInterval; + const l = endPos & ~(this.chunkSize - 1); + exports.update(l); + const newBuffered = endPos - l; + this.buffered = newBuffered; + if (newBuffered > 0) mem.copyWithin(0, l, endPos); } } - _enterIdleMode() { - this._mode = STORAGE_MODE_IDLE; - this._nextDecay = undefined; - if (this._timeout) clearTimeout(this._timeout); - } -} - -const createBackend = (duration, provider, syncProvider, providerContext) => { - if (duration > 0) { - return new CacheBackend(duration, provider, syncProvider, providerContext); - } - return new OperationMergerBackend(provider, syncProvider, providerContext); -}; - -module.exports = class CachedInputFileSystem { - constructor(fileSystem, duration) { - this.fileSystem = fileSystem; - - this._lstatBackend = createBackend( - duration, - this.fileSystem.lstat, - this.fileSystem.lstatSync, - this.fileSystem - ); - const lstat = this._lstatBackend.provide; - this.lstat = /** @type {FileSystem["lstat"]} */ (lstat); - const lstatSync = this._lstatBackend.provideSync; - this.lstatSync = /** @type {SyncFileSystem["lstatSync"]} */ (lstatSync); - - this._statBackend = createBackend( - duration, - this.fileSystem.stat, - this.fileSystem.statSync, - this.fileSystem - ); - const stat = this._statBackend.provide; - this.stat = /** @type {FileSystem["stat"]} */ (stat); - const statSync = this._statBackend.provideSync; - this.statSync = /** @type {SyncFileSystem["statSync"]} */ (statSync); - - this._readdirBackend = createBackend( - duration, - this.fileSystem.readdir, - this.fileSystem.readdirSync, - this.fileSystem - ); - const readdir = this._readdirBackend.provide; - this.readdir = /** @type {FileSystem["readdir"]} */ (readdir); - const readdirSync = this._readdirBackend.provideSync; - this.readdirSync = /** @type {SyncFileSystem["readdirSync"]} */ (readdirSync); - - this._readFileBackend = createBackend( - duration, - this.fileSystem.readFile, - this.fileSystem.readFileSync, - this.fileSystem - ); - const readFile = this._readFileBackend.provide; - this.readFile = /** @type {FileSystem["readFile"]} */ (readFile); - const readFileSync = this._readFileBackend.provideSync; - this.readFileSync = /** @type {SyncFileSystem["readFileSync"]} */ (readFileSync); - - this._readJsonBackend = createBackend( - duration, - this.fileSystem.readJson || - (this.readFile && - ((path, callback) => { - // @ts-ignore - this.readFile(path, (err, buffer) => { - if (err) return callback(err); - if (!buffer || buffer.length === 0) - return callback(new Error("No file content")); - let data; - try { - data = JSON.parse(buffer.toString("utf-8")); - } catch (e) { - return callback(e); - } - callback(null, data); - }); - })), - this.fileSystem.readJsonSync || - (this.readFileSync && - (path => { - const buffer = this.readFileSync(path); - const data = JSON.parse(buffer.toString("utf-8")); - return data; - })), - this.fileSystem - ); - const readJson = this._readJsonBackend.provide; - this.readJson = /** @type {FileSystem["readJson"]} */ (readJson); - const readJsonSync = this._readJsonBackend.provideSync; - this.readJsonSync = /** @type {SyncFileSystem["readJsonSync"]} */ (readJsonSync); + /** + * @param {Buffer} data data + * @returns {void} + */ + _updateWithBuffer(data) { + const { exports, buffered, mem } = this; + const length = data.length; + if (buffered + length < this.chunkSize) { + data.copy(mem, buffered, 0, length); + this.buffered += length; + } else { + const l = (buffered + length) & ~(this.chunkSize - 1); + if (l > 65536) { + let i = 65536 - buffered; + data.copy(mem, buffered, 0, i); + exports.update(65536); + const stop = l - buffered - 65536; + while (i < stop) { + data.copy(mem, 0, i, i + 65536); + exports.update(65536); + i += 65536; + } + data.copy(mem, 0, i, l - buffered); + exports.update(l - buffered - i); + } else { + data.copy(mem, buffered, 0, l - buffered); + exports.update(l); + } + const newBuffered = length + buffered - l; + this.buffered = newBuffered; + if (newBuffered > 0) data.copy(mem, 0, length - newBuffered, length); + } + } - this._readlinkBackend = createBackend( - duration, - this.fileSystem.readlink, - this.fileSystem.readlinkSync, - this.fileSystem - ); - const readlink = this._readlinkBackend.provide; - this.readlink = /** @type {FileSystem["readlink"]} */ (readlink); - const readlinkSync = this._readlinkBackend.provideSync; - this.readlinkSync = /** @type {SyncFileSystem["readlinkSync"]} */ (readlinkSync); + digest(type) { + const { exports, buffered, mem, digestSize } = this; + exports.final(buffered); + this.instancesPool.push(this); + const hex = mem.toString("latin1", 0, digestSize); + if (type === "hex") return hex; + if (type === "binary" || !type) return Buffer.from(hex, "hex"); + return Buffer.from(hex, "hex").toString(type); } +} - purge(what) { - this._statBackend.purge(what); - this._lstatBackend.purge(what); - this._readdirBackend.purgeParent(what); - this._readFileBackend.purge(what); - this._readlinkBackend.purge(what); - this._readJsonBackend.purge(what); +const create = (wasmModule, instancesPool, chunkSize, digestSize) => { + if (instancesPool.length > 0) { + const old = instancesPool.pop(); + old.reset(); + return old; + } else { + return new WasmHash( + new WebAssembly.Instance(wasmModule), + instancesPool, + chunkSize, + digestSize + ); } }; +module.exports = create; +module.exports.MAX_SHORT_STRING = MAX_SHORT_STRING; + /***/ }), -/***/ 22254: +/***/ 35028: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -134224,943 +139465,683 @@ module.exports = class CachedInputFileSystem { -const basename = (__webpack_require__(82918).basename); - -/** @typedef {import("./Resolver")} Resolver */ +const create = __webpack_require__(1842); -module.exports = class CloneBasenamePlugin { - constructor(source, target) { - this.source = source; - this.target = target; - } +//#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1 +const xxhash64 = new WebAssembly.Module( + Buffer.from( + // 1170 bytes + "AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrIIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqAYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEAgAiABNQIAQoeVr6+Ytt6bnn9+hUIXiULP1tO+0ser2UJ+Qvnz3fGZ9pmrFnwhAiABQQRqIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAkIdiCAChUL5893xmfaZqxZ+IgJCIIggAoUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL", + "base64" + ) +); +//#endregion - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("CloneBasenamePlugin", (request, resolveContext, callback) => { - const filename = basename(request.path); - const filePath = resolver.join(request.path, filename); - const obj = { - ...request, - path: filePath, - relativePath: - request.relativePath && - resolver.join(request.relativePath, filename) - }; - resolver.doResolve( - target, - obj, - "using path: " + filePath, - resolveContext, - callback - ); - }); - } -}; +module.exports = create.bind(null, xxhash64, [], 32, 16); /***/ }), -/***/ 6953: -/***/ (function(module) { +/***/ 82186: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +const path = __webpack_require__(71017); -module.exports = class ConditionalPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {Partial} test compare object - * @param {string | null} message log message - * @param {boolean} allowAlternatives when false, do not continue with the current step when "test" matches - * @param {string | ResolveStepHook} target target - */ - constructor(source, test, message, allowAlternatives, target) { - this.source = source; - this.test = test; - this.message = message; - this.allowAlternatives = allowAlternatives; - this.target = target; - } +const WINDOWS_ABS_PATH_REGEXP = /^[a-zA-Z]:[\\/]/; +const SEGMENTS_SPLIT_REGEXP = /([|!])/; +const WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g; - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - const { test, message, allowAlternatives } = this; - const keys = Object.keys(test); - resolver - .getHook(this.source) - .tapAsync("ConditionalPlugin", (request, resolveContext, callback) => { - for (const prop of keys) { - if (request[prop] !== test[prop]) return callback(); - } - resolver.doResolve( - target, - request, - message, - resolveContext, - allowAlternatives - ? callback - : (err, result) => { - if (err) return callback(err); +/** + * @typedef {Object} MakeRelativePathsCache + * @property {Map>=} relativePaths + */ - // Don't allow other alternatives - if (result === undefined) return callback(null, null); - callback(null, result); - } - ); - }); - } +const relativePathToRequest = relativePath => { + if (relativePath === "") return "./."; + if (relativePath === "..") return "../."; + if (relativePath.startsWith("../")) return relativePath; + return `./${relativePath}`; }; +/** + * @param {string} context context for relative path + * @param {string} maybeAbsolutePath path to make relative + * @returns {string} relative path in request style + */ +const absoluteToRequest = (context, maybeAbsolutePath) => { + if (maybeAbsolutePath[0] === "/") { + if ( + maybeAbsolutePath.length > 1 && + maybeAbsolutePath[maybeAbsolutePath.length - 1] === "/" + ) { + // this 'path' is actually a regexp generated by dynamic requires. + // Don't treat it as an absolute path. + return maybeAbsolutePath; + } -/***/ }), - -/***/ 44112: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const querySplitPos = maybeAbsolutePath.indexOf("?"); + let resource = + querySplitPos === -1 + ? maybeAbsolutePath + : maybeAbsolutePath.slice(0, querySplitPos); + resource = relativePathToRequest(path.posix.relative(context, resource)); + return querySplitPos === -1 + ? resource + : resource + maybeAbsolutePath.slice(querySplitPos); + } + if (WINDOWS_ABS_PATH_REGEXP.test(maybeAbsolutePath)) { + const querySplitPos = maybeAbsolutePath.indexOf("?"); + let resource = + querySplitPos === -1 + ? maybeAbsolutePath + : maybeAbsolutePath.slice(0, querySplitPos); + resource = path.win32.relative(context, resource); + if (!WINDOWS_ABS_PATH_REGEXP.test(resource)) { + resource = relativePathToRequest( + resource.replace(WINDOWS_PATH_SEPARATOR_REGEXP, "/") + ); + } + return querySplitPos === -1 + ? resource + : resource + maybeAbsolutePath.slice(querySplitPos); + } + // not an absolute path + return maybeAbsolutePath; +}; -const DescriptionFileUtils = __webpack_require__(25424); +/** + * @param {string} context context for relative path + * @param {string} relativePath path + * @returns {string} absolute path + */ +const requestToAbsolute = (context, relativePath) => { + if (relativePath.startsWith("./") || relativePath.startsWith("../")) + return path.join(context, relativePath); + return relativePath; +}; -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +const makeCacheable = fn => { + /** @type {WeakMap>>} */ + const cache = new WeakMap(); -module.exports = class DescriptionFilePlugin { /** - * @param {string | ResolveStepHook} source source - * @param {string[]} filenames filenames - * @param {boolean} pathIsFile pathIsFile - * @param {string | ResolveStepHook} target target + * @param {string} context context used to create relative path + * @param {string} identifier identifier used to create relative path + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} the returned relative path */ - constructor(source, filenames, pathIsFile, target) { - this.source = source; - this.filenames = filenames; - this.pathIsFile = pathIsFile; - this.target = target; - } + const cachedFn = (context, identifier, associatedObjectForCache) => { + if (!associatedObjectForCache) return fn(context, identifier); + + let innerCache = cache.get(associatedObjectForCache); + if (innerCache === undefined) { + innerCache = new Map(); + cache.set(associatedObjectForCache, innerCache); + } + + let cachedResult; + let innerSubCache = innerCache.get(context); + if (innerSubCache === undefined) { + innerCache.set(context, (innerSubCache = new Map())); + } else { + cachedResult = innerSubCache.get(identifier); + } + + if (cachedResult !== undefined) { + return cachedResult; + } else { + const result = fn(context, identifier); + innerSubCache.set(identifier, result); + return result; + } + }; /** - * @param {Resolver} resolver the resolver - * @returns {void} + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {function(string, string): string} cached function */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync( - "DescriptionFilePlugin", - (request, resolveContext, callback) => { - const path = request.path; - if (!path) return callback(); - const directory = this.pathIsFile - ? DescriptionFileUtils.cdUp(path) - : path; - if (!directory) return callback(); - DescriptionFileUtils.loadDescriptionFile( - resolver, - directory, - this.filenames, - request.descriptionFilePath - ? { - path: request.descriptionFilePath, - content: request.descriptionFileData, - directory: /** @type {string} */ (request.descriptionFileRoot) - } - : undefined, - resolveContext, - (err, result) => { - if (err) return callback(err); - if (!result) { - if (resolveContext.log) - resolveContext.log( - `No description file found in ${directory} or above` - ); - return callback(); - } - const relativePath = - "." + path.substr(result.directory.length).replace(/\\/g, "/"); - const obj = { - ...request, - descriptionFilePath: result.path, - descriptionFileData: result.content, - descriptionFileRoot: result.directory, - relativePath: relativePath - }; - resolver.doResolve( - target, - obj, - "using description file: " + - result.path + - " (relative path: " + - relativePath + - ")", - resolveContext, - (err, result) => { - if (err) return callback(err); - - // Don't allow other processing - if (result === undefined) return callback(null, null); - callback(null, result); - } - ); - } - ); - } - ); - } -}; + cachedFn.bindCache = associatedObjectForCache => { + let innerCache; + if (associatedObjectForCache) { + innerCache = cache.get(associatedObjectForCache); + if (innerCache === undefined) { + innerCache = new Map(); + cache.set(associatedObjectForCache, innerCache); + } + } else { + innerCache = new Map(); + } + /** + * @param {string} context context used to create relative path + * @param {string} identifier identifier used to create relative path + * @returns {string} the returned relative path + */ + const boundFn = (context, identifier) => { + let cachedResult; + let innerSubCache = innerCache.get(context); + if (innerSubCache === undefined) { + innerCache.set(context, (innerSubCache = new Map())); + } else { + cachedResult = innerSubCache.get(identifier); + } -/***/ }), + if (cachedResult !== undefined) { + return cachedResult; + } else { + const result = fn(context, identifier); + innerSubCache.set(identifier, result); + return result; + } + }; -/***/ 25424: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + return boundFn; + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {string} context context used to create relative path + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {function(string): string} cached function + */ + cachedFn.bindContextCache = (context, associatedObjectForCache) => { + let innerSubCache; + if (associatedObjectForCache) { + let innerCache = cache.get(associatedObjectForCache); + if (innerCache === undefined) { + innerCache = new Map(); + cache.set(associatedObjectForCache, innerCache); + } + innerSubCache = innerCache.get(context); + if (innerSubCache === undefined) { + innerCache.set(context, (innerSubCache = new Map())); + } + } else { + innerSubCache = new Map(); + } + /** + * @param {string} identifier identifier used to create relative path + * @returns {string} the returned relative path + */ + const boundFn = identifier => { + const cachedResult = innerSubCache.get(identifier); + if (cachedResult !== undefined) { + return cachedResult; + } else { + const result = fn(context, identifier); + innerSubCache.set(identifier, result); + return result; + } + }; -const forEachBail = __webpack_require__(78565); + return boundFn; + }; -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ + return cachedFn; +}; /** - * @typedef {Object} DescriptionFileInfo - * @property {any=} content - * @property {string} path - * @property {string} directory + * + * @param {string} context context for relative path + * @param {string} identifier identifier for path + * @returns {string} a converted relative path */ +const _makePathsRelative = (context, identifier) => { + return identifier + .split(SEGMENTS_SPLIT_REGEXP) + .map(str => absoluteToRequest(context, str)) + .join(""); +}; -/** - * @callback ErrorFirstCallback - * @param {Error|null=} error - * @param {DescriptionFileInfo=} result - */ +exports.makePathsRelative = makeCacheable(_makePathsRelative); /** - * @param {Resolver} resolver resolver - * @param {string} directory directory - * @param {string[]} filenames filenames - * @param {DescriptionFileInfo|undefined} oldInfo oldInfo - * @param {ResolveContext} resolveContext resolveContext - * @param {ErrorFirstCallback} callback callback + * + * @param {string} context context for relative path + * @param {string} identifier identifier for path + * @returns {string} a converted relative path */ -function loadDescriptionFile( - resolver, - directory, - filenames, - oldInfo, - resolveContext, - callback -) { - (function findDescriptionFile() { - if (oldInfo && oldInfo.directory === directory) { - // We already have info for this directory and can reuse it - return callback(null, oldInfo); - } - forEachBail( - filenames, - (filename, callback) => { - const descriptionFilePath = resolver.join(directory, filename); - if (resolver.fileSystem.readJson) { - resolver.fileSystem.readJson(descriptionFilePath, (err, content) => { - if (err) { - if (typeof err.code !== "undefined") { - if (resolveContext.missingDependencies) { - resolveContext.missingDependencies.add(descriptionFilePath); - } - return callback(); - } - if (resolveContext.fileDependencies) { - resolveContext.fileDependencies.add(descriptionFilePath); - } - return onJson(err); - } - if (resolveContext.fileDependencies) { - resolveContext.fileDependencies.add(descriptionFilePath); - } - onJson(null, content); - }); - } else { - resolver.fileSystem.readFile(descriptionFilePath, (err, content) => { - if (err) { - if (resolveContext.missingDependencies) { - resolveContext.missingDependencies.add(descriptionFilePath); - } - return callback(); - } - if (resolveContext.fileDependencies) { - resolveContext.fileDependencies.add(descriptionFilePath); - } - let json; - - if (content) { - try { - json = JSON.parse(content.toString()); - } catch (e) { - return onJson(e); - } - } else { - return onJson(new Error("No content in file")); - } - - onJson(null, json); - }); - } +const _makePathsAbsolute = (context, identifier) => { + return identifier + .split(SEGMENTS_SPLIT_REGEXP) + .map(str => requestToAbsolute(context, str)) + .join(""); +}; - function onJson(err, content) { - if (err) { - if (resolveContext.log) - resolveContext.log( - descriptionFilePath + " (directory description file): " + err - ); - else - err.message = - descriptionFilePath + " (directory description file): " + err; - return callback(err); - } - callback(null, { - content, - directory, - path: descriptionFilePath - }); - } - }, - (err, result) => { - if (err) return callback(err); - if (result) { - return callback(null, result); - } else { - const dir = cdUp(directory); - if (!dir) { - return callback(); - } else { - directory = dir; - return findDescriptionFile(); - } - } - } - ); - })(); -} +exports.makePathsAbsolute = makeCacheable(_makePathsAbsolute); /** - * @param {any} content content - * @param {string|string[]} field field - * @returns {object|string|number|boolean|undefined} field data + * @param {string} context absolute context path + * @param {string} request any request string may containing absolute paths, query string, etc. + * @returns {string} a new request string avoiding absolute paths when possible */ -function getField(content, field) { - if (!content) return undefined; - if (Array.isArray(field)) { - let current = content; - for (let j = 0; j < field.length; j++) { - if (current === null || typeof current !== "object") { - current = null; - break; - } - current = current[field[j]]; - } - return current; - } else { - return content[field]; - } -} +const _contextify = (context, request) => { + return request + .split("!") + .map(r => absoluteToRequest(context, r)) + .join("!"); +}; + +const contextify = makeCacheable(_contextify); +exports.contextify = contextify; /** - * @param {string} directory directory - * @returns {string|null} parent directory or null + * @param {string} context absolute context path + * @param {string} request any request string + * @returns {string} a new request string using absolute paths when possible */ -function cdUp(directory) { - if (directory === "/") return null; - const i = directory.lastIndexOf("/"), - j = directory.lastIndexOf("\\"); - const p = i < 0 ? j : j < 0 ? i : i < j ? j : i; - if (p < 0) return null; - return directory.substr(0, p || 1); -} - -exports.loadDescriptionFile = loadDescriptionFile; -exports.getField = getField; -exports.cdUp = cdUp; - - -/***/ }), +const _absolutify = (context, request) => { + return request + .split("!") + .map(r => requestToAbsolute(context, r)) + .join("!"); +}; -/***/ 60895: -/***/ (function(module) { +const absolutify = makeCacheable(_absolutify); +exports.absolutify = absolutify; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const PATH_QUERY_FRAGMENT_REGEXP = + /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; +/** @typedef {{ resource: string, path: string, query: string, fragment: string }} ParsedResource */ +/** + * @param {string} str the path with query and fragment + * @returns {ParsedResource} parsed parts + */ +const _parseResource = str => { + const match = PATH_QUERY_FRAGMENT_REGEXP.exec(str); + return { + resource: str, + path: match[1].replace(/\0(.)/g, "$1"), + query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "", + fragment: match[3] || "" + }; +}; +exports.parseResource = (realFn => { + /** @type {WeakMap>} */ + const cache = new WeakMap(); -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + const getCache = associatedObjectForCache => { + const entry = cache.get(associatedObjectForCache); + if (entry !== undefined) return entry; + /** @type {Map} */ + const map = new Map(); + cache.set(associatedObjectForCache, map); + return map; + }; -module.exports = class DirectoryExistsPlugin { /** - * @param {string | ResolveStepHook} source source - * @param {string | ResolveStepHook} target target + * @param {string} str the path with query and fragment + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {ParsedResource} parsed parts */ - constructor(source, target) { - this.source = source; - this.target = target; - } + const fn = (str, associatedObjectForCache) => { + if (!associatedObjectForCache) return realFn(str); + const cache = getCache(associatedObjectForCache); + const entry = cache.get(str); + if (entry !== undefined) return entry; + const result = realFn(str); + cache.set(str, result); + return result; + }; - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync( - "DirectoryExistsPlugin", - (request, resolveContext, callback) => { - const fs = resolver.fileSystem; - const directory = request.path; - if (!directory) return callback(); - fs.stat(directory, (err, stat) => { - if (err || !stat) { - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(directory); - if (resolveContext.log) - resolveContext.log(directory + " doesn't exist"); - return callback(); - } - if (!stat.isDirectory()) { - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(directory); - if (resolveContext.log) - resolveContext.log(directory + " is not a directory"); - return callback(); - } - if (resolveContext.fileDependencies) - resolveContext.fileDependencies.add(directory); - resolver.doResolve( - target, - request, - `existing directory ${directory}`, - resolveContext, - callback - ); - }); - } - ); + fn.bindCache = associatedObjectForCache => { + const cache = getCache(associatedObjectForCache); + return str => { + const entry = cache.get(str); + if (entry !== undefined) return entry; + const result = realFn(str); + cache.set(str, result); + return result; + }; + }; + + return fn; +})(_parseResource); + +/** + * @param {string} filename the filename which should be undone + * @param {string} outputPath the output path that is restored (only relevant when filename contains "..") + * @param {boolean} enforceRelative true returns ./ for empty paths + * @returns {string} repeated ../ to leave the directory of the provided filename to be back on output dir + */ +exports.getUndoPath = (filename, outputPath, enforceRelative) => { + let depth = -1; + let append = ""; + outputPath = outputPath.replace(/[\\/]$/, ""); + for (const part of filename.split(/[/\\]+/)) { + if (part === "..") { + if (depth > -1) { + depth--; + } else { + const i = outputPath.lastIndexOf("/"); + const j = outputPath.lastIndexOf("\\"); + const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j); + if (pos < 0) return outputPath + "/"; + append = outputPath.slice(pos + 1) + "/" + append; + outputPath = outputPath.slice(0, pos); + } + } else if (part !== ".") { + depth++; + } } + return depth > 0 + ? `${"../".repeat(depth)}${append}` + : enforceRelative + ? `./${append}` + : append; }; /***/ }), -/***/ 83849: +/***/ 53023: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const path = __webpack_require__(71017); -const DescriptionFileUtils = __webpack_require__(25424); -const forEachBail = __webpack_require__(78565); -const { processExportsField } = __webpack_require__(55863); -const { parseIdentifier } = __webpack_require__(71053); -const { checkExportsFieldTarget } = __webpack_require__(67079); - -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {import("./util/entrypoints").ExportsField} ExportsField */ -/** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ - -module.exports = class ExportsFieldPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {Set} conditionNames condition names - * @param {string | string[]} fieldNamePath name path - * @param {string | ResolveStepHook} target target - */ - constructor(source, conditionNames, fieldNamePath, target) { - this.source = source; - this.target = target; - this.conditionNames = conditionNames; - this.fieldName = fieldNamePath; - /** @type {WeakMap} */ - this.fieldProcessorCache = new WeakMap(); - } - - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("ExportsFieldPlugin", (request, resolveContext, callback) => { - // When there is no description file, abort - if (!request.descriptionFilePath) return callback(); - if ( - // When the description file is inherited from parent, abort - // (There is no description file inside of this package) - request.relativePath !== "." || - request.request === undefined - ) - return callback(); - - const remainingRequest = - request.query || request.fragment - ? (request.request === "." ? "./" : request.request) + - request.query + - request.fragment - : request.request; - /** @type {ExportsField|null} */ - const exportsField = DescriptionFileUtils.getField( - request.descriptionFileData, - this.fieldName - ); - if (!exportsField) return callback(); - - if (request.directory) { - return callback( - new Error( - `Resolving to directories is not possible with the exports field (request was ${remainingRequest}/)` - ) - ); - } - - let paths; - - try { - // We attach the cache to the description file instead of the exportsField value - // because we use a WeakMap and the exportsField could be a string too. - // Description file is always an object when exports field can be accessed. - let fieldProcessor = this.fieldProcessorCache.get( - request.descriptionFileData - ); - if (fieldProcessor === undefined) { - fieldProcessor = processExportsField(exportsField); - this.fieldProcessorCache.set( - request.descriptionFileData, - fieldProcessor - ); - } - paths = fieldProcessor(remainingRequest, this.conditionNames); - } catch (err) { - if (resolveContext.log) { - resolveContext.log( - `Exports field in ${request.descriptionFilePath} can't be processed: ${err}` - ); - } - return callback(err); - } - - if (paths.length === 0) { - return callback( - new Error( - `Package path ${remainingRequest} is not exported from package ${request.descriptionFileRoot} (see exports field in ${request.descriptionFilePath})` - ) - ); - } - - forEachBail( - paths, - (p, callback) => { - const parsedIdentifier = parseIdentifier(p); - - if (!parsedIdentifier) return callback(); - - const [relativePath, query, fragment] = parsedIdentifier; - - const error = checkExportsFieldTarget(relativePath); - - if (error) { - return callback(error); - } - - const obj = { - ...request, - request: undefined, - path: path.join( - /** @type {string} */ (request.descriptionFileRoot), - relativePath - ), - relativePath, - query, - fragment - }; +// We need to include a list of requires here +// to allow webpack to be bundled with only static requires +// We could use a dynamic require(`../${request}`) but this +// would include too many modules and not every tool is able +// to process this +module.exports = { + AsyncDependenciesBlock: () => __webpack_require__(47736), + CommentCompilationWarning: () => __webpack_require__(98427), + ContextModule: () => __webpack_require__(76729), + "cache/PackFileCacheStrategy": () => + __webpack_require__(86180), + "cache/ResolverCachePlugin": () => __webpack_require__(97347), + "container/ContainerEntryDependency": () => + __webpack_require__(64813), + "container/ContainerEntryModule": () => + __webpack_require__(80580), + "container/ContainerExposedDependency": () => + __webpack_require__(72374), + "container/FallbackDependency": () => + __webpack_require__(57764), + "container/FallbackItemDependency": () => + __webpack_require__(29593), + "container/FallbackModule": () => __webpack_require__(82886), + "container/RemoteModule": () => __webpack_require__(62916), + "container/RemoteToExternalDependency": () => + __webpack_require__(14389), + "dependencies/AMDDefineDependency": () => + __webpack_require__(96816), + "dependencies/AMDRequireArrayDependency": () => + __webpack_require__(33516), + "dependencies/AMDRequireContextDependency": () => + __webpack_require__(96123), + "dependencies/AMDRequireDependenciesBlock": () => + __webpack_require__(76932), + "dependencies/AMDRequireDependency": () => + __webpack_require__(43911), + "dependencies/AMDRequireItemDependency": () => + __webpack_require__(71806), + "dependencies/CachedConstDependency": () => + __webpack_require__(57403), + "dependencies/CreateScriptUrlDependency": () => + __webpack_require__(79062), + "dependencies/CommonJsRequireContextDependency": () => + __webpack_require__(23962), + "dependencies/CommonJsExportRequireDependency": () => + __webpack_require__(62892), + "dependencies/CommonJsExportsDependency": () => + __webpack_require__(45598), + "dependencies/CommonJsFullRequireDependency": () => + __webpack_require__(59440), + "dependencies/CommonJsRequireDependency": () => + __webpack_require__(21264), + "dependencies/CommonJsSelfReferenceDependency": () => + __webpack_require__(52225), + "dependencies/ConstDependency": () => + __webpack_require__(76911), + "dependencies/ContextDependency": () => + __webpack_require__(88101), + "dependencies/ContextElementDependency": () => + __webpack_require__(58477), + "dependencies/CriticalDependencyWarning": () => + __webpack_require__(15427), + "dependencies/CssImportDependency": () => + __webpack_require__(90542), + "dependencies/CssLocalIdentifierDependency": () => + __webpack_require__(92328), + "dependencies/CssSelfLocalIdentifierDependency": () => + __webpack_require__(29094), + "dependencies/CssExportDependency": () => + __webpack_require__(76760), + "dependencies/CssUrlDependency": () => + __webpack_require__(70749), + "dependencies/DelegatedSourceDependency": () => + __webpack_require__(22914), + "dependencies/DllEntryDependency": () => + __webpack_require__(95666), + "dependencies/EntryDependency": () => + __webpack_require__(3979), + "dependencies/ExportsInfoDependency": () => + __webpack_require__(78988), + "dependencies/HarmonyAcceptDependency": () => + __webpack_require__(23624), + "dependencies/HarmonyAcceptImportDependency": () => + __webpack_require__(99843), + "dependencies/HarmonyCompatibilityDependency": () => + __webpack_require__(72906), + "dependencies/HarmonyExportExpressionDependency": () => + __webpack_require__(51340), + "dependencies/HarmonyExportHeaderDependency": () => + __webpack_require__(38873), + "dependencies/HarmonyExportImportedSpecifierDependency": () => + __webpack_require__(67157), + "dependencies/HarmonyExportSpecifierDependency": () => + __webpack_require__(48567), + "dependencies/HarmonyImportSideEffectDependency": () => + __webpack_require__(73132), + "dependencies/HarmonyImportSpecifierDependency": () => + __webpack_require__(14077), + "dependencies/ImportContextDependency": () => + __webpack_require__(1902), + "dependencies/ImportDependency": () => + __webpack_require__(89376), + "dependencies/ImportEagerDependency": () => + __webpack_require__(50718), + "dependencies/ImportWeakDependency": () => + __webpack_require__(82483), + "dependencies/JsonExportsDependency": () => + __webpack_require__(750), + "dependencies/LocalModule": () => __webpack_require__(5826), + "dependencies/LocalModuleDependency": () => + __webpack_require__(52805), + "dependencies/ModuleDecoratorDependency": () => + __webpack_require__(88488), + "dependencies/ModuleHotAcceptDependency": () => + __webpack_require__(47511), + "dependencies/ModuleHotDeclineDependency": () => + __webpack_require__(86301), + "dependencies/ImportMetaHotAcceptDependency": () => + __webpack_require__(51274), + "dependencies/ImportMetaHotDeclineDependency": () => + __webpack_require__(53141), + "dependencies/ProvidedDependency": () => + __webpack_require__(95770), + "dependencies/PureExpressionDependency": () => + __webpack_require__(55799), + "dependencies/RequireContextDependency": () => + __webpack_require__(46917), + "dependencies/RequireEnsureDependenciesBlock": () => + __webpack_require__(27153), + "dependencies/RequireEnsureDependency": () => + __webpack_require__(27223), + "dependencies/RequireEnsureItemDependency": () => + __webpack_require__(50329), + "dependencies/RequireHeaderDependency": () => + __webpack_require__(89183), + "dependencies/RequireIncludeDependency": () => + __webpack_require__(71284), + "dependencies/RequireIncludeDependencyParserPlugin": () => + __webpack_require__(35768), + "dependencies/RequireResolveContextDependency": () => + __webpack_require__(55627), + "dependencies/RequireResolveDependency": () => + __webpack_require__(68582), + "dependencies/RequireResolveHeaderDependency": () => + __webpack_require__(9880), + "dependencies/RuntimeRequirementsDependency": () => + __webpack_require__(24187), + "dependencies/StaticExportsDependency": () => + __webpack_require__(91418), + "dependencies/SystemPlugin": () => __webpack_require__(97981), + "dependencies/UnsupportedDependency": () => + __webpack_require__(51669), + "dependencies/URLDependency": () => __webpack_require__(58612), + "dependencies/WebAssemblyExportImportedDependency": () => + __webpack_require__(52204), + "dependencies/WebAssemblyImportDependency": () => + __webpack_require__(5239), + "dependencies/WebpackIsIncludedDependency": () => + __webpack_require__(26505), + "dependencies/WorkerDependency": () => + __webpack_require__(1466), + "json/JsonData": () => __webpack_require__(90490), + "optimize/ConcatenatedModule": () => + __webpack_require__(97198), + DelegatedModule: () => __webpack_require__(28623), + DependenciesBlock: () => __webpack_require__(71040), + DllModule: () => __webpack_require__(28280), + ExternalModule: () => __webpack_require__(73071), + FileSystemInfo: () => __webpack_require__(79453), + InitFragment: () => __webpack_require__(55870), + InvalidDependenciesModuleWarning: () => + __webpack_require__(68257), + Module: () => __webpack_require__(73208), + ModuleBuildError: () => __webpack_require__(21305), + ModuleDependencyWarning: () => __webpack_require__(29656), + ModuleError: () => __webpack_require__(23744), + ModuleGraph: () => __webpack_require__(99988), + ModuleParseError: () => __webpack_require__(58443), + ModuleWarning: () => __webpack_require__(11234), + NormalModule: () => __webpack_require__(39), + RawDataUrlModule: () => __webpack_require__(19684), + RawModule: () => __webpack_require__(84929), + "sharing/ConsumeSharedModule": () => + __webpack_require__(62286), + "sharing/ConsumeSharedFallbackDependency": () => + __webpack_require__(58831), + "sharing/ProvideSharedModule": () => + __webpack_require__(50821), + "sharing/ProvideSharedDependency": () => + __webpack_require__(1798), + "sharing/ProvideForSharedDependency": () => + __webpack_require__(40017), + UnsupportedFeatureWarning: () => __webpack_require__(42495), + "util/LazySet": () => __webpack_require__(38938), + UnhandledSchemeError: () => __webpack_require__(68099), + NodeStuffInWebError: () => __webpack_require__(6325), + WebpackError: () => __webpack_require__(53799), - resolver.doResolve( - target, - obj, - "using exports field: " + p, - resolveContext, - callback - ); - }, - (err, result) => callback(err, result || null) - ); - }); + "util/registerExternalSerializer": () => { + // already registered } }; /***/ }), -/***/ 50295: -/***/ (function(module) { +/***/ 33032: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +const { register } = __webpack_require__(8282); -module.exports = class FileExistsPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | ResolveStepHook} target target - */ - constructor(source, target) { - this.source = source; - this.target = target; +class ClassSerializer { + constructor(Constructor) { + this.Constructor = Constructor; } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - const fs = resolver.fileSystem; - resolver - .getHook(this.source) - .tapAsync("FileExistsPlugin", (request, resolveContext, callback) => { - const file = request.path; - if (!file) return callback(); - fs.stat(file, (err, stat) => { - if (err || !stat) { - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(file); - if (resolveContext.log) resolveContext.log(file + " doesn't exist"); - return callback(); - } - if (!stat.isFile()) { - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(file); - if (resolveContext.log) resolveContext.log(file + " is not a file"); - return callback(); - } - if (resolveContext.fileDependencies) - resolveContext.fileDependencies.add(file); - resolver.doResolve( - target, - request, - "existing file: " + file, - resolveContext, - callback - ); - }); - }); + serialize(obj, context) { + obj.serialize(context); } -}; - - -/***/ }), - -/***/ 7317: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - - -const path = __webpack_require__(71017); -const DescriptionFileUtils = __webpack_require__(25424); -const forEachBail = __webpack_require__(78565); -const { processImportsField } = __webpack_require__(55863); -const { parseIdentifier } = __webpack_require__(71053); - -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ -/** @typedef {import("./util/entrypoints").ImportsField} ImportsField */ - -const dotCode = ".".charCodeAt(0); - -module.exports = class ImportsFieldPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {Set} conditionNames condition names - * @param {string | string[]} fieldNamePath name path - * @param {string | ResolveStepHook} targetFile target file - * @param {string | ResolveStepHook} targetPackage target package - */ - constructor( - source, - conditionNames, - fieldNamePath, - targetFile, - targetPackage - ) { - this.source = source; - this.targetFile = targetFile; - this.targetPackage = targetPackage; - this.conditionNames = conditionNames; - this.fieldName = fieldNamePath; - /** @type {WeakMap} */ - this.fieldProcessorCache = new WeakMap(); + deserialize(context) { + if (typeof this.Constructor.deserialize === "function") { + return this.Constructor.deserialize(context); + } + const obj = new this.Constructor(); + obj.deserialize(context); + return obj; } +} - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const targetFile = resolver.ensureHook(this.targetFile); - const targetPackage = resolver.ensureHook(this.targetPackage); - - resolver - .getHook(this.source) - .tapAsync("ImportsFieldPlugin", (request, resolveContext, callback) => { - // When there is no description file, abort - if (!request.descriptionFilePath || request.request === undefined) { - return callback(); - } - - const remainingRequest = - request.request + request.query + request.fragment; - /** @type {ImportsField|null} */ - const importsField = DescriptionFileUtils.getField( - request.descriptionFileData, - this.fieldName - ); - if (!importsField) return callback(); - - if (request.directory) { - return callback( - new Error( - `Resolving to directories is not possible with the imports field (request was ${remainingRequest}/)` - ) - ); - } - - let paths; - - try { - // We attach the cache to the description file instead of the importsField value - // because we use a WeakMap and the importsField could be a string too. - // Description file is always an object when exports field can be accessed. - let fieldProcessor = this.fieldProcessorCache.get( - request.descriptionFileData - ); - if (fieldProcessor === undefined) { - fieldProcessor = processImportsField(importsField); - this.fieldProcessorCache.set( - request.descriptionFileData, - fieldProcessor - ); - } - paths = fieldProcessor(remainingRequest, this.conditionNames); - } catch (err) { - if (resolveContext.log) { - resolveContext.log( - `Imports field in ${request.descriptionFilePath} can't be processed: ${err}` - ); - } - return callback(err); - } - - if (paths.length === 0) { - return callback( - new Error( - `Package import ${remainingRequest} is not imported from package ${request.descriptionFileRoot} (see imports field in ${request.descriptionFilePath})` - ) - ); - } - - forEachBail( - paths, - (p, callback) => { - const parsedIdentifier = parseIdentifier(p); - - if (!parsedIdentifier) return callback(); - - const [path_, query, fragment] = parsedIdentifier; - - switch (path_.charCodeAt(0)) { - // should be relative - case dotCode: { - const obj = { - ...request, - request: undefined, - path: path.join( - /** @type {string} */ (request.descriptionFileRoot), - path_ - ), - relativePath: path_, - query, - fragment - }; - - resolver.doResolve( - targetFile, - obj, - "using imports field: " + p, - resolveContext, - callback - ); - break; - } - - // package resolving - default: { - const obj = { - ...request, - request: path_, - relativePath: path_, - fullySpecified: true, - query, - fragment - }; - - resolver.doResolve( - targetPackage, - obj, - "using imports field: " + p, - resolveContext, - callback - ); - } - } - }, - (err, result) => callback(err, result || null) - ); - }); - } +module.exports = (Constructor, request, name = null) => { + register(Constructor, request, name, new ClassSerializer(Constructor)); }; /***/ }), -/***/ 35949: +/***/ 78676: /***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - -const namespaceStartCharCode = "@".charCodeAt(0); - -module.exports = class JoinRequestPartPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | ResolveStepHook} target target - */ - constructor(source, target) { - this.source = source; - this.target = target; - } - - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync( - "JoinRequestPartPlugin", - (request, resolveContext, callback) => { - const req = request.request || ""; - let i = req.indexOf("/", 3); - - if (i >= 0 && req.charCodeAt(2) === namespaceStartCharCode) { - i = req.indexOf("/", i + 1); - } +/** @template T @typedef {function(): T} FunctionReturning */ - let moduleName, remainingRequest, fullySpecified; - if (i < 0) { - moduleName = req; - remainingRequest = "."; - fullySpecified = false; - } else { - moduleName = req.slice(0, i); - remainingRequest = "." + req.slice(i); - fullySpecified = request.fullySpecified; - } - const obj = { - ...request, - path: resolver.join(request.path, moduleName), - relativePath: - request.relativePath && - resolver.join(request.relativePath, moduleName), - request: remainingRequest, - fullySpecified - }; - resolver.doResolve(target, obj, null, resolveContext, callback); - } - ); - } +/** + * @template T + * @param {FunctionReturning} fn memorized function + * @returns {FunctionReturning} new function + */ +const memoize = fn => { + let cache = false; + /** @type {T} */ + let result = undefined; + return () => { + if (cache) { + return result; + } else { + result = fn(); + cache = true; + // Allow to clean up memory for fn + // and all dependent resources + fn = undefined; + return result; + } + }; }; +module.exports = memoize; + /***/ }), -/***/ 5190: +/***/ 70002: /***/ (function(module) { "use strict"; @@ -135171,45 +140152,49 @@ module.exports = class JoinRequestPartPlugin { -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +const SAFE_LIMIT = 0x80000000; +const SAFE_PART = SAFE_LIMIT - 1; +const COUNT = 4; +const arr = [0, 0, 0, 0, 0]; +const primes = [3, 7, 17, 19]; -module.exports = class JoinRequestPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | ResolveStepHook} target target - */ - constructor(source, target) { - this.source = source; - this.target = target; +module.exports = (str, range) => { + arr.fill(0); + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + for (let j = 0; j < COUNT; j++) { + const p = (j + COUNT - 1) % COUNT; + arr[j] = (arr[j] + c * primes[j] + arr[p]) & SAFE_PART; + } + for (let j = 0; j < COUNT; j++) { + const q = arr[j] % COUNT; + arr[j] = arr[j] ^ (arr[q] >> 1); + } } - - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("JoinRequestPlugin", (request, resolveContext, callback) => { - const obj = { - ...request, - path: resolver.join(request.path, request.request), - relativePath: - request.relativePath && - resolver.join(request.relativePath, request.request), - request: undefined - }; - resolver.doResolve(target, obj, null, resolveContext, callback); - }); + if (range <= SAFE_PART) { + let sum = 0; + for (let j = 0; j < COUNT; j++) { + sum = (sum + arr[j]) % range; + } + return sum; + } else { + let sum1 = 0; + let sum2 = 0; + const rangeExt = Math.floor(range / SAFE_LIMIT); + for (let j = 0; j < COUNT; j += 2) { + sum1 = (sum1 + arr[j]) & SAFE_PART; + } + for (let j = 1; j < COUNT; j += 2) { + sum2 = (sum2 + arr[j]) % rangeExt; + } + return (sum2 * SAFE_LIMIT + sum1) % range; } }; /***/ }), -/***/ 5049: +/***/ 42791: /***/ (function(module) { "use strict"; @@ -135220,55 +140205,67 @@ module.exports = class JoinRequestPlugin { -/** @typedef {import("./Resolver")} Resolver */ +/** + * @template T + * @template {Error} E + * @param {Iterable} items initial items + * @param {number} concurrency number of items running in parallel + * @param {function(T, function(T): void, function(E=): void): void} processor worker which pushes more items + * @param {function(E=): void} callback all items processed + * @returns {void} + */ +const processAsyncTree = (items, concurrency, processor, callback) => { + const queue = Array.from(items); + if (queue.length === 0) return callback(); + let processing = 0; + let finished = false; + let processScheduled = true; -module.exports = class LogInfoPlugin { - constructor(source) { - this.source = source; - } + const push = item => { + queue.push(item); + if (!processScheduled && processing < concurrency) { + processScheduled = true; + process.nextTick(processQueue); + } + }; - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const source = this.source; - resolver - .getHook(this.source) - .tapAsync("LogInfoPlugin", (request, resolveContext, callback) => { - if (!resolveContext.log) return callback(); - const log = resolveContext.log; - const prefix = "[" + source + "] "; - if (request.path) - log(prefix + "Resolving in directory: " + request.path); - if (request.request) - log(prefix + "Resolving request: " + request.request); - if (request.module) log(prefix + "Request is an module request."); - if (request.directory) log(prefix + "Request is a directory request."); - if (request.query) - log(prefix + "Resolving request query: " + request.query); - if (request.fragment) - log(prefix + "Resolving request fragment: " + request.fragment); - if (request.descriptionFilePath) - log( - prefix + "Has description data from " + request.descriptionFilePath - ); - if (request.relativePath) - log( - prefix + - "Relative path from description file is: " + - request.relativePath - ); - callback(); - }); - } + const processorCallback = err => { + processing--; + if (err && !finished) { + finished = true; + callback(err); + return; + } + if (!processScheduled) { + processScheduled = true; + process.nextTick(processQueue); + } + }; + + const processQueue = () => { + if (finished) return; + while (processing < concurrency && queue.length > 0) { + processing++; + const item = queue.pop(); + processor(item, push, processorCallback); + } + processScheduled = false; + if (queue.length === 0 && processing === 0 && !finished) { + finished = true; + callback(); + } + }; + + processQueue(); }; +module.exports = processAsyncTree; + /***/ }), -/***/ 47450: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 54190: +/***/ (function(module) { "use strict"; /* @@ -135278,86 +140275,83 @@ module.exports = class LogInfoPlugin { -const path = __webpack_require__(71017); -const DescriptionFileUtils = __webpack_require__(25424); - -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {{name: string|Array, forceRelative: boolean}} MainFieldOptions */ - -const alreadyTriedMainField = Symbol("alreadyTriedMainField"); - -module.exports = class MainFieldPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {MainFieldOptions} options options - * @param {string | ResolveStepHook} target target - */ - constructor(source, options, target) { - this.source = source; - this.options = options; - this.target = target; - } - - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("MainFieldPlugin", (request, resolveContext, callback) => { - if ( - request.path !== request.descriptionFileRoot || - request[alreadyTriedMainField] === request.descriptionFilePath || - !request.descriptionFilePath - ) - return callback(); - const filename = path.basename(request.descriptionFilePath); - let mainModule = DescriptionFileUtils.getField( - request.descriptionFileData, - this.options.name - ); +const SAFE_IDENTIFIER = /^[_a-zA-Z$][_a-zA-Z$0-9]*$/; +const RESERVED_IDENTIFIER = new Set([ + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "export", + "extends", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "return", + "super", + "switch", + "this", + "throw", + "try", + "typeof", + "var", + "void", + "while", + "with", + "enum", + // strict mode + "implements", + "interface", + "let", + "package", + "private", + "protected", + "public", + "static", + "yield", + "yield", + // module code + "await", + // skip future reserved keywords defined under ES1 till ES3 + // additional + "null", + "true", + "false" +]); - if ( - !mainModule || - typeof mainModule !== "string" || - mainModule === "." || - mainModule === "./" - ) { - return callback(); - } - if (this.options.forceRelative && !/^\.\.?\//.test(mainModule)) - mainModule = "./" + mainModule; - const obj = { - ...request, - request: mainModule, - module: false, - directory: mainModule.endsWith("/"), - [alreadyTriedMainField]: request.descriptionFilePath - }; - return resolver.doResolve( - target, - obj, - "use " + - mainModule + - " from " + - this.options.name + - " in " + - filename, - resolveContext, - callback - ); - }); +const propertyAccess = (properties, start = 0) => { + let str = ""; + for (let i = start; i < properties.length; i++) { + const p = properties[i]; + if (`${+p}` === p) { + str += `[${p}]`; + } else if (SAFE_IDENTIFIER.test(p) && !RESERVED_IDENTIFIER.has(p)) { + str += `.${p}`; + } else { + str += `[${JSON.stringify(p)}]`; + } } + return str; }; +module.exports = propertyAccess; + /***/ }), -/***/ 48506: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 26611: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -135367,181 +140361,342 @@ module.exports = class MainFieldPlugin { -const forEachBail = __webpack_require__(78565); -const getPaths = __webpack_require__(82918); +const { register } = __webpack_require__(8282); -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +const Position = /** @type {TODO} */ (__webpack_require__(70108).Position); +const SourceLocation = (__webpack_require__(70108).SourceLocation); +const ValidationError = (__webpack_require__(54983)/* ["default"] */ .Z); +const { + CachedSource, + ConcatSource, + OriginalSource, + PrefixSource, + RawSource, + ReplaceSource, + SourceMapSource +} = __webpack_require__(51255); -module.exports = class ModulesInHierachicDirectoriesPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | Array} directories directories - * @param {string | ResolveStepHook} target target - */ - constructor(source, directories, target) { - this.source = source; - this.directories = /** @type {Array} */ ([]).concat(directories); - this.target = target; - } +/** @typedef {import("acorn").Position} Position */ +/** @typedef {import("../Dependency").RealDependencyLocation} RealDependencyLocation */ +/** @typedef {import("../Dependency").SourcePosition} SourcePosition */ +/** @typedef {import("./serialization").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization").ObjectSerializerContext} ObjectSerializerContext */ - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync( - "ModulesInHierachicDirectoriesPlugin", - (request, resolveContext, callback) => { - const fs = resolver.fileSystem; - const addrs = getPaths(request.path) - .paths.map(p => { - return this.directories.map(d => resolver.join(p, d)); - }) - .reduce((array, p) => { - array.push.apply(array, p); - return array; - }, []); - forEachBail( - addrs, - (addr, callback) => { - fs.stat(addr, (err, stat) => { - if (!err && stat && stat.isDirectory()) { - const obj = { - ...request, - path: addr, - request: "./" + request.request, - module: false - }; - const message = "looking for modules in " + addr; - return resolver.doResolve( - target, - obj, - message, - resolveContext, - callback - ); - } - if (resolveContext.log) - resolveContext.log( - addr + " doesn't exist or is not a directory" - ); - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(addr); - return callback(); - }); - }, - callback - ); - } - ); - } -}; +/** @typedef {ObjectSerializerContext & { writeLazy?: (any) => void }} WebpackObjectSerializerContext */ +const CURRENT_MODULE = "webpack/lib/util/registerExternalSerializer"; -/***/ }), +register( + CachedSource, + CURRENT_MODULE, + "webpack-sources/CachedSource", + new (class CachedSourceSerializer { + /** + * @param {CachedSource} source the cached source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write, writeLazy }) { + if (writeLazy) { + writeLazy(source.originalLazy()); + } else { + write(source.original()); + } + write(source.getCachedData()); + } -/***/ 88138: -/***/ (function(module) { + /** + * @param {ObjectDeserializerContext} context context + * @returns {CachedSource} cached source + */ + deserialize({ read }) { + const source = read(); + const cachedData = read(); + return new CachedSource(source, cachedData); + } + })() +); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +register( + RawSource, + CURRENT_MODULE, + "webpack-sources/RawSource", + new (class RawSourceSerializer { + /** + * @param {RawSource} source the raw source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.buffer()); + write(!source.isBuffer()); + } + /** + * @param {ObjectDeserializerContext} context context + * @returns {RawSource} raw source + */ + deserialize({ read }) { + const source = read(); + const convertToString = read(); + return new RawSource(source, convertToString); + } + })() +); +register( + ConcatSource, + CURRENT_MODULE, + "webpack-sources/ConcatSource", + new (class ConcatSourceSerializer { + /** + * @param {ConcatSource} source the concat source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.getChildren()); + } -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + /** + * @param {ObjectDeserializerContext} context context + * @returns {ConcatSource} concat source + */ + deserialize({ read }) { + const source = new ConcatSource(); + source.addAllSkipOptimizing(read()); + return source; + } + })() +); -module.exports = class ModulesInRootPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string} path path - * @param {string | ResolveStepHook} target target - */ - constructor(source, path, target) { - this.source = source; - this.path = path; - this.target = target; - } +register( + PrefixSource, + CURRENT_MODULE, + "webpack-sources/PrefixSource", + new (class PrefixSourceSerializer { + /** + * @param {PrefixSource} source the prefix source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.getPrefix()); + write(source.original()); + } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("ModulesInRootPlugin", (request, resolveContext, callback) => { - const obj = { - ...request, - path: this.path, - request: "./" + request.request, - module: false - }; - resolver.doResolve( - target, - obj, - "looking for modules in " + this.path, - resolveContext, - callback - ); - }); - } -}; + /** + * @param {ObjectDeserializerContext} context context + * @returns {PrefixSource} prefix source + */ + deserialize({ read }) { + return new PrefixSource(read(), read()); + } + })() +); +register( + ReplaceSource, + CURRENT_MODULE, + "webpack-sources/ReplaceSource", + new (class ReplaceSourceSerializer { + /** + * @param {ReplaceSource} source the replace source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.original()); + write(source.getName()); + const replacements = source.getReplacements(); + write(replacements.length); + for (const repl of replacements) { + write(repl.start); + write(repl.end); + } + for (const repl of replacements) { + write(repl.content); + write(repl.name); + } + } -/***/ }), + /** + * @param {ObjectDeserializerContext} context context + * @returns {ReplaceSource} replace source + */ + deserialize({ read }) { + const source = new ReplaceSource(read(), read()); + const len = read(); + const startEndBuffer = []; + for (let i = 0; i < len; i++) { + startEndBuffer.push(read(), read()); + } + let j = 0; + for (let i = 0; i < len; i++) { + source.replace( + startEndBuffer[j++], + startEndBuffer[j++], + read(), + read() + ); + } + return source; + } + })() +); -/***/ 40777: -/***/ (function(module) { +register( + OriginalSource, + CURRENT_MODULE, + "webpack-sources/OriginalSource", + new (class OriginalSourceSerializer { + /** + * @param {OriginalSource} source the original source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.buffer()); + write(source.getName()); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {ObjectDeserializerContext} context context + * @returns {OriginalSource} original source + */ + deserialize({ read }) { + const buffer = read(); + const name = read(); + return new OriginalSource(buffer, name); + } + })() +); + +register( + SourceLocation, + CURRENT_MODULE, + "acorn/SourceLocation", + new (class SourceLocationSerializer { + /** + * @param {SourceLocation} loc the location to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(loc, { write }) { + write(loc.start.line); + write(loc.start.column); + write(loc.end.line); + write(loc.end.column); + } + /** + * @param {ObjectDeserializerContext} context context + * @returns {RealDependencyLocation} location + */ + deserialize({ read }) { + return { + start: { + line: read(), + column: read() + }, + end: { + line: read(), + column: read() + } + }; + } + })() +); +register( + Position, + CURRENT_MODULE, + "acorn/Position", + new (class PositionSerializer { + /** + * @param {Position} pos the position to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(pos, { write }) { + write(pos.line); + write(pos.column); + } -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + /** + * @param {ObjectDeserializerContext} context context + * @returns {SourcePosition} position + */ + deserialize({ read }) { + return { + line: read(), + column: read() + }; + } + })() +); -module.exports = class NextPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | ResolveStepHook} target target - */ - constructor(source, target) { - this.source = source; - this.target = target; - } +register( + SourceMapSource, + CURRENT_MODULE, + "webpack-sources/SourceMapSource", + new (class SourceMapSourceSerializer { + /** + * @param {SourceMapSource} source the source map source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.getArgsAsBuffers()); + } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("NextPlugin", (request, resolveContext, callback) => { - resolver.doResolve(target, request, null, resolveContext, callback); + /** + * @param {ObjectDeserializerContext} context context + * @returns {SourceMapSource} source source map source + */ + deserialize({ read }) { + // @ts-expect-error + return new SourceMapSource(...read()); + } + })() +); + +register( + ValidationError, + CURRENT_MODULE, + "schema-utils/ValidationError", + new (class ValidationErrorSerializer { + // TODO error should be ValidationError, but this fails the type checks + /** + * @param {TODO} error the source map source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(error, { write }) { + write(error.errors); + write(error.schema); + write({ + name: error.headerName, + baseDataPath: error.baseDataPath, + postFormatter: error.postFormatter }); - } -}; + } + + /** + * @param {ObjectDeserializerContext} context context + * @returns {TODO} error + */ + deserialize({ read }) { + return new ValidationError(read(), read(), read()); + } + })() +); /***/ }), -/***/ 97849: -/***/ (function(module) { +/***/ 17156: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -135551,673 +140706,628 @@ module.exports = class NextPlugin { -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - -module.exports = class ParsePlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {Partial} requestOptions request options - * @param {string | ResolveStepHook} target target - */ - constructor(source, requestOptions, target) { - this.source = source; - this.requestOptions = requestOptions; - this.target = target; - } - - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("ParsePlugin", (request, resolveContext, callback) => { - const parsed = resolver.parse(/** @type {string} */ (request.request)); - const obj = { ...request, ...parsed, ...this.requestOptions }; - if (request.query && !parsed.query) { - obj.query = request.query; - } - if (request.fragment && !parsed.fragment) { - obj.fragment = request.fragment; - } - if (parsed && resolveContext.log) { - if (parsed.module) resolveContext.log("Parsed request is a module"); - if (parsed.directory) - resolveContext.log("Parsed request is a directory"); - } - // There is an edge-case where a request with # can be a path or a fragment -> try both - if (obj.request && !obj.query && obj.fragment) { - const directory = obj.fragment.endsWith("/"); - const alternative = { - ...obj, - directory, - request: - obj.request + - (obj.directory ? "/" : "") + - (directory ? obj.fragment.slice(0, -1) : obj.fragment), - fragment: "" - }; - resolver.doResolve( - target, - alternative, - null, - resolveContext, - (err, result) => { - if (err) return callback(err); - if (result) return callback(null, result); - resolver.doResolve(target, obj, null, resolveContext, callback); - } - ); - return; - } - resolver.doResolve(target, obj, null, resolveContext, callback); - }); - } -}; - - -/***/ }), - -/***/ 44222: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Maël Nison @arcanis -*/ +const SortableSet = __webpack_require__(13098); +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */ +/** @typedef {string | SortableSet | undefined} RuntimeSpec */ +/** @typedef {RuntimeSpec | boolean} RuntimeCondition */ -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ /** - * @typedef {Object} PnpApiImpl - * @property {function(string, string, object): string} resolveToUnqualified + * @param {Compilation} compilation the compilation + * @param {string} name name of the entry + * @param {EntryOptions=} options optionally already received entry options + * @returns {RuntimeSpec} runtime */ - -module.exports = class PnpPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {PnpApiImpl} pnpApi pnpApi - * @param {string | ResolveStepHook} target target - */ - constructor(source, pnpApi, target) { - this.source = source; - this.pnpApi = pnpApi; - this.target = target; +exports.getEntryRuntime = (compilation, name, options) => { + let dependOn; + let runtime; + if (options) { + ({ dependOn, runtime } = options); + } else { + const entry = compilation.entries.get(name); + if (!entry) return name; + ({ dependOn, runtime } = entry.options); } - - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("PnpPlugin", (request, resolveContext, callback) => { - const req = request.request; - if (!req) return callback(); - - // The trailing slash indicates to PnP that this value is a folder rather than a file - const issuer = `${request.path}/`; - - const packageMatch = /^(@[^/]+\/)?[^/]+/.exec(req); - if (!packageMatch) return callback(); - - const packageName = packageMatch[0]; - const innerRequest = `.${req.slice(packageName.length)}`; - - let resolution; - let apiResolution; - try { - resolution = this.pnpApi.resolveToUnqualified(packageName, issuer, { - considerBuiltins: false - }); - if (resolveContext.fileDependencies) { - apiResolution = this.pnpApi.resolveToUnqualified("pnpapi", issuer, { - considerBuiltins: false - }); - } - } catch (error) { - if ( - error.code === "MODULE_NOT_FOUND" && - error.pnpCode === "UNDECLARED_DEPENDENCY" - ) { - // This is not a PnP managed dependency. - // Try to continue resolving with our alternatives - if (resolveContext.log) { - resolveContext.log(`request is not managed by the pnpapi`); - for (const line of error.message.split("\n").filter(Boolean)) - resolveContext.log(` ${line}`); - } - return callback(); - } - return callback(error); - } - - if (resolution === packageName) return callback(); - - if (apiResolution && resolveContext.fileDependencies) { - resolveContext.fileDependencies.add(apiResolution); + if (dependOn) { + /** @type {RuntimeSpec} */ + let result = undefined; + const queue = new Set(dependOn); + for (const name of queue) { + const dep = compilation.entries.get(name); + if (!dep) continue; + const { dependOn, runtime } = dep.options; + if (dependOn) { + for (const name of dependOn) { + queue.add(name); } - - const obj = { - ...request, - path: resolution, - request: innerRequest, - ignoreSymlinks: true, - fullySpecified: request.fullySpecified && innerRequest !== "." - }; - resolver.doResolve( - target, - obj, - `resolved by pnp to ${resolution}`, - resolveContext, - (err, result) => { - if (err) return callback(err); - if (result) return callback(null, result); - // Skip alternatives - return callback(null, null); - } - ); - }); + } else { + result = mergeRuntimeOwned(result, runtime || name); + } + } + return result || name; + } else { + return runtime || name; } }; +/** + * @param {RuntimeSpec} runtime runtime + * @param {function(string): void} fn functor + * @param {boolean} deterministicOrder enforce a deterministic order + * @returns {void} + */ +exports.forEachRuntime = (runtime, fn, deterministicOrder = false) => { + if (runtime === undefined) { + fn(undefined); + } else if (typeof runtime === "string") { + fn(runtime); + } else { + if (deterministicOrder) runtime.sort(); + for (const r of runtime) { + fn(r); + } + } +}; -/***/ }), - -/***/ 55516: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - +const getRuntimesKey = set => { + set.sort(); + return Array.from(set).join("\n"); +}; +/** + * @param {RuntimeSpec} runtime runtime(s) + * @returns {string} key of runtimes + */ +const getRuntimeKey = runtime => { + if (runtime === undefined) return "*"; + if (typeof runtime === "string") return runtime; + return runtime.getFromUnorderedCache(getRuntimesKey); +}; +exports.getRuntimeKey = getRuntimeKey; -const { AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } = __webpack_require__(6967); -const createInnerContext = __webpack_require__(81218); -const { parseIdentifier } = __webpack_require__(71053); -const { - normalize, - cachedJoin: join, - getType, - PathType -} = __webpack_require__(67079); +/** + * @param {string} key key of runtimes + * @returns {RuntimeSpec} runtime(s) + */ +const keyToRuntime = key => { + if (key === "*") return undefined; + const items = key.split("\n"); + if (items.length === 1) return items[0]; + return new SortableSet(items); +}; +exports.keyToRuntime = keyToRuntime; -/** @typedef {import("./ResolverFactory").ResolveOptions} ResolveOptions */ +const getRuntimesString = set => { + set.sort(); + return Array.from(set).join("+"); +}; /** - * @typedef {Object} FileSystemStats - * @property {function(): boolean} isDirectory - * @property {function(): boolean} isFile + * @param {RuntimeSpec} runtime runtime(s) + * @returns {string} readable version */ +const runtimeToString = runtime => { + if (runtime === undefined) return "*"; + if (typeof runtime === "string") return runtime; + return runtime.getFromUnorderedCache(getRuntimesString); +}; +exports.runtimeToString = runtimeToString; /** - * @typedef {Object} FileSystemDirent - * @property {Buffer | string} name - * @property {function(): boolean} isDirectory - * @property {function(): boolean} isFile + * @param {RuntimeCondition} runtimeCondition runtime condition + * @returns {string} readable version */ +exports.runtimeConditionToString = runtimeCondition => { + if (runtimeCondition === true) return "true"; + if (runtimeCondition === false) return "false"; + return runtimeToString(runtimeCondition); +}; /** - * @typedef {Object} PossibleFileSystemError - * @property {string=} code - * @property {number=} errno - * @property {string=} path - * @property {string=} syscall + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {boolean} true, when they are equal */ +const runtimeEqual = (a, b) => { + if (a === b) { + return true; + } else if ( + a === undefined || + b === undefined || + typeof a === "string" || + typeof b === "string" + ) { + return false; + } else if (a.size !== b.size) { + return false; + } else { + a.sort(); + b.sort(); + const aIt = a[Symbol.iterator](); + const bIt = b[Symbol.iterator](); + for (;;) { + const aV = aIt.next(); + if (aV.done) return true; + const bV = bIt.next(); + if (aV.value !== bV.value) return false; + } + } +}; +exports.runtimeEqual = runtimeEqual; /** - * @template T - * @callback FileSystemCallback - * @param {PossibleFileSystemError & Error | null | undefined} err - * @param {T=} result + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {-1|0|1} compare */ +exports.compareRuntime = (a, b) => { + if (a === b) { + return 0; + } else if (a === undefined) { + return -1; + } else if (b === undefined) { + return 1; + } else { + const aKey = getRuntimeKey(a); + const bKey = getRuntimeKey(b); + if (aKey < bKey) return -1; + if (aKey > bKey) return 1; + return 0; + } +}; /** - * @typedef {Object} FileSystem - * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} readFile - * @property {(function(string, FileSystemCallback<(Buffer | string)[] | FileSystemDirent[]>): void) & function(string, object, FileSystemCallback<(Buffer | string)[] | FileSystemDirent[]>): void} readdir - * @property {((function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void)=} readJson - * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} readlink - * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void=} lstat - * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} stat + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {RuntimeSpec} merged */ +const mergeRuntime = (a, b) => { + if (a === undefined) { + return b; + } else if (b === undefined) { + return a; + } else if (a === b) { + return a; + } else if (typeof a === "string") { + if (typeof b === "string") { + const set = new SortableSet(); + set.add(a); + set.add(b); + return set; + } else if (b.has(a)) { + return b; + } else { + const set = new SortableSet(b); + set.add(a); + return set; + } + } else { + if (typeof b === "string") { + if (a.has(b)) return a; + const set = new SortableSet(a); + set.add(b); + return set; + } else { + const set = new SortableSet(a); + for (const item of b) set.add(item); + if (set.size === a.size) return a; + return set; + } + } +}; +exports.mergeRuntime = mergeRuntime; /** - * @typedef {Object} SyncFileSystem - * @property {function(string, object=): Buffer | string} readFileSync - * @property {function(string, object=): (Buffer | string)[] | FileSystemDirent[]} readdirSync - * @property {(function(string, object=): object)=} readJsonSync - * @property {function(string, object=): Buffer | string} readlinkSync - * @property {function(string, object=): FileSystemStats=} lstatSync - * @property {function(string, object=): FileSystemStats} statSync + * @param {RuntimeCondition} a first + * @param {RuntimeCondition} b second + * @param {RuntimeSpec} runtime full runtime + * @returns {RuntimeCondition} result */ +exports.mergeRuntimeCondition = (a, b, runtime) => { + if (a === false) return b; + if (b === false) return a; + if (a === true || b === true) return true; + const merged = mergeRuntime(a, b); + if (merged === undefined) return undefined; + if (typeof merged === "string") { + if (typeof runtime === "string" && merged === runtime) return true; + return merged; + } + if (typeof runtime === "string" || runtime === undefined) return merged; + if (merged.size === runtime.size) return true; + return merged; +}; /** - * @typedef {Object} ParsedIdentifier - * @property {string} request - * @property {string} query - * @property {string} fragment - * @property {boolean} directory - * @property {boolean} module - * @property {boolean} file - * @property {boolean} internal + * @param {RuntimeSpec | true} a first + * @param {RuntimeSpec | true} b second + * @param {RuntimeSpec} runtime full runtime + * @returns {RuntimeSpec | true} result */ +exports.mergeRuntimeConditionNonFalse = (a, b, runtime) => { + if (a === true || b === true) return true; + const merged = mergeRuntime(a, b); + if (merged === undefined) return undefined; + if (typeof merged === "string") { + if (typeof runtime === "string" && merged === runtime) return true; + return merged; + } + if (typeof runtime === "string" || runtime === undefined) return merged; + if (merged.size === runtime.size) return true; + return merged; +}; /** - * @typedef {Object} BaseResolveRequest - * @property {string | false} path - * @property {string=} descriptionFilePath - * @property {string=} descriptionFileRoot - * @property {object=} descriptionFileData - * @property {string=} relativePath - * @property {boolean=} ignoreSymlinks - * @property {boolean=} fullySpecified + * @param {RuntimeSpec} a first (may be modified) + * @param {RuntimeSpec} b second + * @returns {RuntimeSpec} merged */ - -/** @typedef {BaseResolveRequest & Partial} ResolveRequest */ +const mergeRuntimeOwned = (a, b) => { + if (b === undefined) { + return a; + } else if (a === b) { + return a; + } else if (a === undefined) { + if (typeof b === "string") { + return b; + } else { + return new SortableSet(b); + } + } else if (typeof a === "string") { + if (typeof b === "string") { + const set = new SortableSet(); + set.add(a); + set.add(b); + return set; + } else { + const set = new SortableSet(b); + set.add(a); + return set; + } + } else { + if (typeof b === "string") { + a.add(b); + return a; + } else { + for (const item of b) a.add(item); + return a; + } + } +}; +exports.mergeRuntimeOwned = mergeRuntimeOwned; /** - * String with special formatting - * @typedef {string} StackEntry + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {RuntimeSpec} merged */ - -/** @template T @typedef {{ add: (T) => void }} WriteOnlySet */ +exports.intersectRuntime = (a, b) => { + if (a === undefined) { + return b; + } else if (b === undefined) { + return a; + } else if (a === b) { + return a; + } else if (typeof a === "string") { + if (typeof b === "string") { + return undefined; + } else if (b.has(a)) { + return a; + } else { + return undefined; + } + } else { + if (typeof b === "string") { + if (a.has(b)) return b; + return undefined; + } else { + const set = new SortableSet(); + for (const item of b) { + if (a.has(item)) set.add(item); + } + if (set.size === 0) return undefined; + if (set.size === 1) for (const item of set) return item; + return set; + } + } +}; /** - * Resolve context - * @typedef {Object} ResolveContext - * @property {WriteOnlySet=} contextDependencies - * @property {WriteOnlySet=} fileDependencies files that was found on file system - * @property {WriteOnlySet=} missingDependencies dependencies that was not found on file system - * @property {Set=} stack set of hooks' calls. For instance, `resolve → parsedResolve → describedResolve`, - * @property {(function(string): void)=} log log function + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {RuntimeSpec} result */ - -/** @typedef {AsyncSeriesBailHook<[ResolveRequest, ResolveContext], ResolveRequest | null>} ResolveStepHook */ +const subtractRuntime = (a, b) => { + if (a === undefined) { + return undefined; + } else if (b === undefined) { + return a; + } else if (a === b) { + return undefined; + } else if (typeof a === "string") { + if (typeof b === "string") { + return a; + } else if (b.has(a)) { + return undefined; + } else { + return a; + } + } else { + if (typeof b === "string") { + if (!a.has(b)) return a; + if (a.size === 2) { + for (const item of a) { + if (item !== b) return item; + } + } + const set = new SortableSet(a); + set.delete(b); + } else { + const set = new SortableSet(); + for (const item of a) { + if (!b.has(item)) set.add(item); + } + if (set.size === 0) return undefined; + if (set.size === 1) for (const item of set) return item; + return set; + } + } +}; +exports.subtractRuntime = subtractRuntime; /** - * @param {string} str input string - * @returns {string} in camel case + * @param {RuntimeCondition} a first + * @param {RuntimeCondition} b second + * @param {RuntimeSpec} runtime runtime + * @returns {RuntimeCondition} result */ -function toCamelCase(str) { - return str.replace(/-([a-z])/g, str => str.substr(1).toUpperCase()); -} +exports.subtractRuntimeCondition = (a, b, runtime) => { + if (b === true) return false; + if (b === false) return a; + if (a === false) return false; + const result = subtractRuntime(a === true ? runtime : a, b); + return result === undefined ? false : result; +}; -class Resolver { - /** - * @param {ResolveStepHook} hook hook - * @param {ResolveRequest} request request - * @returns {StackEntry} stack entry - */ - static createStackEntry(hook, request) { - return ( - hook.name + - ": (" + - request.path + - ") " + - (request.request || "") + - (request.query || "") + - (request.fragment || "") + - (request.directory ? " directory" : "") + - (request.module ? " module" : "") - ); +/** + * @param {RuntimeSpec} runtime runtime + * @param {function(RuntimeSpec): boolean} filter filter function + * @returns {boolean | RuntimeSpec} true/false if filter is constant for all runtimes, otherwise runtimes that are active + */ +exports.filterRuntime = (runtime, filter) => { + if (runtime === undefined) return filter(undefined); + if (typeof runtime === "string") return filter(runtime); + let some = false; + let every = true; + let result = undefined; + for (const r of runtime) { + const v = filter(r); + if (v) { + some = true; + result = mergeRuntimeOwned(result, r); + } else { + every = false; + } } + if (!some) return false; + if (every) return true; + return result; +}; +/** + * @template T + */ +class RuntimeSpecMap { /** - * @param {FileSystem} fileSystem a filesystem - * @param {ResolveOptions} options options + * @param {RuntimeSpecMap=} clone copy form this */ - constructor(fileSystem, options) { - this.fileSystem = fileSystem; - this.options = options; - this.hooks = { - /** @type {SyncHook<[ResolveStepHook, ResolveRequest], void>} */ - resolveStep: new SyncHook(["hook", "request"], "resolveStep"), - /** @type {SyncHook<[ResolveRequest, Error]>} */ - noResolve: new SyncHook(["request", "error"], "noResolve"), - /** @type {ResolveStepHook} */ - resolve: new AsyncSeriesBailHook( - ["request", "resolveContext"], - "resolve" - ), - /** @type {AsyncSeriesHook<[ResolveRequest, ResolveContext]>} */ - result: new AsyncSeriesHook(["result", "resolveContext"], "result") - }; + constructor(clone) { + this._mode = clone ? clone._mode : 0; // 0 = empty, 1 = single entry, 2 = map + /** @type {RuntimeSpec} */ + this._singleRuntime = clone ? clone._singleRuntime : undefined; + /** @type {T} */ + this._singleValue = clone ? clone._singleValue : undefined; + /** @type {Map | undefined} */ + this._map = clone && clone._map ? new Map(clone._map) : undefined; } /** - * @param {string | ResolveStepHook} name hook name or hook itself - * @returns {ResolveStepHook} the hook + * @param {RuntimeSpec} runtime the runtimes + * @returns {T} value */ - ensureHook(name) { - if (typeof name !== "string") { - return name; - } - name = toCamelCase(name); - if (/^before/.test(name)) { - return /** @type {ResolveStepHook} */ (this.ensureHook( - name[6].toLowerCase() + name.substr(7) - ).withOptions({ - stage: -10 - })); - } - if (/^after/.test(name)) { - return /** @type {ResolveStepHook} */ (this.ensureHook( - name[5].toLowerCase() + name.substr(6) - ).withOptions({ - stage: 10 - })); - } - const hook = this.hooks[name]; - if (!hook) { - return (this.hooks[name] = new AsyncSeriesBailHook( - ["request", "resolveContext"], - name - )); + get(runtime) { + switch (this._mode) { + case 0: + return undefined; + case 1: + return runtimeEqual(this._singleRuntime, runtime) + ? this._singleValue + : undefined; + default: + return this._map.get(getRuntimeKey(runtime)); } - return hook; } /** - * @param {string | ResolveStepHook} name hook name or hook itself - * @returns {ResolveStepHook} the hook + * @param {RuntimeSpec} runtime the runtimes + * @returns {boolean} true, when the runtime is stored */ - getHook(name) { - if (typeof name !== "string") { - return name; - } - name = toCamelCase(name); - if (/^before/.test(name)) { - return /** @type {ResolveStepHook} */ (this.getHook( - name[6].toLowerCase() + name.substr(7) - ).withOptions({ - stage: -10 - })); - } - if (/^after/.test(name)) { - return /** @type {ResolveStepHook} */ (this.getHook( - name[5].toLowerCase() + name.substr(6) - ).withOptions({ - stage: 10 - })); - } - const hook = this.hooks[name]; - if (!hook) { - throw new Error(`Hook ${name} doesn't exist`); + has(runtime) { + switch (this._mode) { + case 0: + return false; + case 1: + return runtimeEqual(this._singleRuntime, runtime); + default: + return this._map.has(getRuntimeKey(runtime)); } - return hook; } - /** - * @param {object} context context information object - * @param {string} path context path - * @param {string} request request string - * @returns {string | false} result - */ - resolveSync(context, path, request) { - /** @type {Error | null | undefined} */ - let err = undefined; - /** @type {string | false | undefined} */ - let result = undefined; - let sync = false; - this.resolve(context, path, request, {}, (e, r) => { - err = e; - result = r; - sync = true; - }); - if (!sync) { - throw new Error( - "Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!" - ); + set(runtime, value) { + switch (this._mode) { + case 0: + this._mode = 1; + this._singleRuntime = runtime; + this._singleValue = value; + break; + case 1: + if (runtimeEqual(this._singleRuntime, runtime)) { + this._singleValue = value; + break; + } + this._mode = 2; + this._map = new Map(); + this._map.set(getRuntimeKey(this._singleRuntime), this._singleValue); + this._singleRuntime = undefined; + this._singleValue = undefined; + /* falls through */ + default: + this._map.set(getRuntimeKey(runtime), value); } - if (err) throw err; - if (result === undefined) throw new Error("No result"); - return result; } - /** - * @param {object} context context information object - * @param {string} path context path - * @param {string} request request string - * @param {ResolveContext} resolveContext resolve context - * @param {function(Error | null, (string|false)=, ResolveRequest=): void} callback callback function - * @returns {void} - */ - resolve(context, path, request, resolveContext, callback) { - if (!context || typeof context !== "object") - return callback(new Error("context argument is not an object")); - if (typeof path !== "string") - return callback(new Error("path argument is not a string")); - if (typeof request !== "string") - return callback(new Error("path argument is not a string")); - if (!resolveContext) - return callback(new Error("resolveContext argument is not set")); - - const obj = { - context: context, - path: path, - request: request - }; - - const message = `resolve '${request}' in '${path}'`; - - const finishResolved = result => { - return callback( - null, - result.path === false - ? false - : `${result.path.replace(/#/g, "\0#")}${ - result.query ? result.query.replace(/#/g, "\0#") : "" - }${result.fragment || ""}`, - result - ); - }; - - const finishWithoutResolve = log => { - /** - * @type {Error & {details?: string}} - */ - const error = new Error("Can't " + message); - error.details = log.join("\n"); - this.hooks.noResolve.call(obj, error); - return callback(error); - }; - - if (resolveContext.log) { - // We need log anyway to capture it in case of an error - const parentLog = resolveContext.log; - const log = []; - return this.doResolve( - this.hooks.resolve, - obj, - message, - { - log: msg => { - parentLog(msg); - log.push(msg); - }, - fileDependencies: resolveContext.fileDependencies, - contextDependencies: resolveContext.contextDependencies, - missingDependencies: resolveContext.missingDependencies, - stack: resolveContext.stack - }, - (err, result) => { - if (err) return callback(err); - - if (result) return finishResolved(result); - - return finishWithoutResolve(log); - } - ); - } else { - // Try to resolve assuming there is no error - // We don't log stuff in this case - return this.doResolve( - this.hooks.resolve, - obj, - message, - { - log: undefined, - fileDependencies: resolveContext.fileDependencies, - contextDependencies: resolveContext.contextDependencies, - missingDependencies: resolveContext.missingDependencies, - stack: resolveContext.stack - }, - (err, result) => { - if (err) return callback(err); - - if (result) return finishResolved(result); - - // log is missing for the error details - // so we redo the resolving for the log info - // this is more expensive to the success case - // is assumed by default - - const log = []; - - return this.doResolve( - this.hooks.resolve, - obj, - message, - { - log: msg => log.push(msg), - stack: resolveContext.stack - }, - (err, result) => { - if (err) return callback(err); - - return finishWithoutResolve(log); - } - ); + provide(runtime, computer) { + switch (this._mode) { + case 0: + this._mode = 1; + this._singleRuntime = runtime; + return (this._singleValue = computer()); + case 1: { + if (runtimeEqual(this._singleRuntime, runtime)) { + return this._singleValue; } - ); + this._mode = 2; + this._map = new Map(); + this._map.set(getRuntimeKey(this._singleRuntime), this._singleValue); + this._singleRuntime = undefined; + this._singleValue = undefined; + const newValue = computer(); + this._map.set(getRuntimeKey(runtime), newValue); + return newValue; + } + default: { + const key = getRuntimeKey(runtime); + const value = this._map.get(key); + if (value !== undefined) return value; + const newValue = computer(); + this._map.set(key, newValue); + return newValue; + } } } - doResolve(hook, request, message, resolveContext, callback) { - const stackEntry = Resolver.createStackEntry(hook, request); + delete(runtime) { + switch (this._mode) { + case 0: + return; + case 1: + if (runtimeEqual(this._singleRuntime, runtime)) { + this._mode = 0; + this._singleRuntime = undefined; + this._singleValue = undefined; + } + return; + default: + this._map.delete(getRuntimeKey(runtime)); + } + } - let newStack; - if (resolveContext.stack) { - newStack = new Set(resolveContext.stack); - if (resolveContext.stack.has(stackEntry)) { - /** - * Prevent recursion - * @type {Error & {recursion?: boolean}} - */ - const recursionError = new Error( - "Recursion in resolving\nStack:\n " + - Array.from(newStack).join("\n ") - ); - recursionError.recursion = true; - if (resolveContext.log) - resolveContext.log("abort resolving because of recursion"); - return callback(recursionError); + update(runtime, fn) { + switch (this._mode) { + case 0: + throw new Error("runtime passed to update must exist"); + case 1: { + if (runtimeEqual(this._singleRuntime, runtime)) { + this._singleValue = fn(this._singleValue); + break; + } + const newValue = fn(undefined); + if (newValue !== undefined) { + this._mode = 2; + this._map = new Map(); + this._map.set(getRuntimeKey(this._singleRuntime), this._singleValue); + this._singleRuntime = undefined; + this._singleValue = undefined; + this._map.set(getRuntimeKey(runtime), newValue); + } + break; + } + default: { + const key = getRuntimeKey(runtime); + const oldValue = this._map.get(key); + const newValue = fn(oldValue); + if (newValue !== oldValue) this._map.set(key, newValue); } - newStack.add(stackEntry); - } else { - newStack = new Set([stackEntry]); } - this.hooks.resolveStep.call(hook, request); + } - if (hook.isUsed()) { - const innerContext = createInnerContext( - { - log: resolveContext.log, - fileDependencies: resolveContext.fileDependencies, - contextDependencies: resolveContext.contextDependencies, - missingDependencies: resolveContext.missingDependencies, - stack: newStack - }, - message - ); - return hook.callAsync(request, innerContext, (err, result) => { - if (err) return callback(err); - if (result) return callback(null, result); - callback(); - }); - } else { - callback(); + keys() { + switch (this._mode) { + case 0: + return []; + case 1: + return [this._singleRuntime]; + default: + return Array.from(this._map.keys(), keyToRuntime); } } - /** - * @param {string} identifier identifier - * @returns {ParsedIdentifier} parsed identifier - */ - parse(identifier) { - const part = { - request: "", - query: "", - fragment: "", - module: false, - directory: false, - file: false, - internal: false - }; - - const parsedIdentifier = parseIdentifier(identifier); + values() { + switch (this._mode) { + case 0: + return [][Symbol.iterator](); + case 1: + return [this._singleValue][Symbol.iterator](); + default: + return this._map.values(); + } + } - if (!parsedIdentifier) return part; + get size() { + if (this._mode <= 1) return this._mode; + return this._map.size; + } +} - [part.request, part.query, part.fragment] = parsedIdentifier; +exports.RuntimeSpecMap = RuntimeSpecMap; - if (part.request.length > 0) { - part.internal = this.isPrivate(identifier); - part.module = this.isModule(part.request); - part.directory = this.isDirectory(part.request); - if (part.directory) { - part.request = part.request.substr(0, part.request.length - 1); +class RuntimeSpecSet { + constructor(iterable) { + /** @type {Map} */ + this._map = new Map(); + if (iterable) { + for (const item of iterable) { + this.add(item); } } - - return part; - } - - isModule(path) { - return getType(path) === PathType.Normal; } - isPrivate(path) { - return getType(path) === PathType.Internal; + add(runtime) { + this._map.set(getRuntimeKey(runtime), runtime); } - /** - * @param {string} path a path - * @returns {boolean} true, if the path is a directory path - */ - isDirectory(path) { - return path.endsWith("/"); + has(runtime) { + return this._map.has(getRuntimeKey(runtime)); } - join(path, request) { - return join(path, request); + [Symbol.iterator]() { + return this._map.values(); } - normalize(path) { - return normalize(path); + get size() { + return this._map.size; } } -module.exports = Resolver; +exports.RuntimeSpecSet = RuntimeSpecSet; /***/ }), -/***/ 47716: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 19702: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -136227,730 +141337,832 @@ module.exports = Resolver; -const versions = (__webpack_require__(77282).versions); -const Resolver = __webpack_require__(55516); -const { getType, PathType } = __webpack_require__(67079); - -const SyncAsyncFileSystemDecorator = __webpack_require__(87474); - -const AliasFieldPlugin = __webpack_require__(14819); -const AliasPlugin = __webpack_require__(63676); -const AppendPlugin = __webpack_require__(92088); -const ConditionalPlugin = __webpack_require__(6953); -const DescriptionFilePlugin = __webpack_require__(44112); -const DirectoryExistsPlugin = __webpack_require__(60895); -const ExportsFieldPlugin = __webpack_require__(83849); -const FileExistsPlugin = __webpack_require__(50295); -const ImportsFieldPlugin = __webpack_require__(7317); -const JoinRequestPartPlugin = __webpack_require__(35949); -const JoinRequestPlugin = __webpack_require__(5190); -const MainFieldPlugin = __webpack_require__(47450); -const ModulesInHierachicDirectoriesPlugin = __webpack_require__(48506); -const ModulesInRootPlugin = __webpack_require__(88138); -const NextPlugin = __webpack_require__(40777); -const ParsePlugin = __webpack_require__(97849); -const PnpPlugin = __webpack_require__(44222); -const RestrictionsPlugin = __webpack_require__(36400); -const ResultPlugin = __webpack_require__(13965); -const RootsPlugin = __webpack_require__(66737); -const SelfReferencePlugin = __webpack_require__(52232); -const SymlinkPlugin = __webpack_require__(58885); -const TryNextPlugin = __webpack_require__(99324); -const UnsafeCachePlugin = __webpack_require__(41606); -const UseFilePlugin = __webpack_require__(96972); - -/** @typedef {import("./AliasPlugin").AliasOption} AliasOptionEntry */ -/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ -/** @typedef {import("./Resolver").FileSystem} FileSystem */ -/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ -/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ - -/** @typedef {string|string[]|false} AliasOptionNewRequest */ -/** @typedef {{[k: string]: AliasOptionNewRequest}} AliasOptions */ -/** @typedef {{apply: function(Resolver): void} | function(this: Resolver, Resolver): void} Plugin */ +/** @typedef {(string|number|undefined|[])[]} SemVerRange */ /** - * @typedef {Object} UserResolveOptions - * @property {(AliasOptions | AliasOptionEntry[])=} alias A list of module alias configurations or an object which maps key to value - * @property {(AliasOptions | AliasOptionEntry[])=} fallback A list of module alias configurations or an object which maps key to value, applied only after modules option - * @property {(string | string[])[]=} aliasFields A list of alias fields in description files - * @property {(function(ResolveRequest): boolean)=} cachePredicate A function which decides whether a request should be cached or not. An object is passed with at least `path` and `request` properties. - * @property {boolean=} cacheWithContext Whether or not the unsafeCache should include request context as part of the cache key. - * @property {string[]=} descriptionFiles A list of description files to read from - * @property {string[]=} conditionNames A list of exports field condition names. - * @property {boolean=} enforceExtension Enforce that a extension from extensions must be used - * @property {(string | string[])[]=} exportsFields A list of exports fields in description files - * @property {(string | string[])[]=} importsFields A list of imports fields in description files - * @property {string[]=} extensions A list of extensions which should be tried for files - * @property {FileSystem} fileSystem The file system which should be used - * @property {(object | boolean)=} unsafeCache Use this cache object to unsafely cache the successful requests - * @property {boolean=} symlinks Resolve symlinks to their symlinked location - * @property {Resolver=} resolver A prepared Resolver to which the plugins are attached - * @property {string[] | string=} modules A list of directories to resolve modules from, can be absolute path or folder name - * @property {(string | string[] | {name: string | string[], forceRelative: boolean})[]=} mainFields A list of main fields in description files - * @property {string[]=} mainFiles A list of main files in directories - * @property {Plugin[]=} plugins A list of additional resolve plugins which should be applied - * @property {PnpApi | null=} pnpApi A PnP API that should be used - null is "never", undefined is "auto" - * @property {string[]=} roots A list of root paths - * @property {boolean=} fullySpecified The request is already fully specified and no extensions or directories are resolved for it - * @property {boolean=} resolveToContext Resolve to a context instead of a file - * @property {(string|RegExp)[]=} restrictions A list of resolve restrictions - * @property {boolean=} useSyncFileSystemCalls Use only the sync constiants of the file system calls - * @property {boolean=} preferRelative Prefer to resolve module requests as relative requests before falling back to modules - * @property {boolean=} preferAbsolute Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots + * @param {string} str version string + * @returns {(string|number|undefined|[])[]} parsed version */ +const parseVersion = str => { + var splitAndConvert = function (str) { + return str.split(".").map(function (item) { + // eslint-disable-next-line eqeqeq + return +item == item ? +item : item; + }); + }; + var match = /^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str); + /** @type {(string|number|undefined|[])[]} */ + var ver = match[1] ? splitAndConvert(match[1]) : []; + if (match[2]) { + ver.length++; + ver.push.apply(ver, splitAndConvert(match[2])); + } + if (match[3]) { + ver.push([]); + ver.push.apply(ver, splitAndConvert(match[3])); + } + return ver; +}; +exports.parseVersion = parseVersion; +/* eslint-disable eqeqeq */ /** - * @typedef {Object} ResolveOptions - * @property {AliasOptionEntry[]} alias - * @property {AliasOptionEntry[]} fallback - * @property {Set} aliasFields - * @property {(function(ResolveRequest): boolean)} cachePredicate - * @property {boolean} cacheWithContext - * @property {Set} conditionNames A list of exports field condition names. - * @property {string[]} descriptionFiles - * @property {boolean} enforceExtension - * @property {Set} exportsFields - * @property {Set} importsFields - * @property {Set} extensions - * @property {FileSystem} fileSystem - * @property {object | false} unsafeCache - * @property {boolean} symlinks - * @property {Resolver=} resolver - * @property {Array} modules - * @property {{name: string[], forceRelative: boolean}[]} mainFields - * @property {Set} mainFiles - * @property {Plugin[]} plugins - * @property {PnpApi | null} pnpApi - * @property {Set} roots - * @property {boolean} fullySpecified - * @property {boolean} resolveToContext - * @property {Set} restrictions - * @property {boolean} preferRelative - * @property {boolean} preferAbsolute + * @param {string} a version + * @param {string} b version + * @returns {boolean} true, iff a < b */ +const versionLt = (a, b) => { + // @ts-expect-error + a = parseVersion(a); + // @ts-expect-error + b = parseVersion(b); + var i = 0; + for (;;) { + // a b EOA object undefined number string + // EOA a == b a < b b < a a < b a < b + // object b < a (0) b < a a < b a < b + // undefined a < b a < b (0) a < b a < b + // number b < a b < a b < a (1) a < b + // string b < a b < a b < a b < a (1) + // EOA end of array + // (0) continue on + // (1) compare them via "<" -/** - * @param {PnpApi | null=} option option - * @returns {PnpApi | null} processed option - */ -function processPnpApiOption(option) { - if ( - option === undefined && - /** @type {NodeJS.ProcessVersions & {pnp: string}} */ versions.pnp - ) { - // @ts-ignore - return __webpack_require__(35125); // eslint-disable-line node/no-missing-require - } + // Handles first row in table + if (i >= a.length) return i < b.length && (typeof b[i])[0] != "u"; - return option || null; -} + var aValue = a[i]; + var aType = (typeof aValue)[0]; -/** - * @param {AliasOptions | AliasOptionEntry[] | undefined} alias alias - * @returns {AliasOptionEntry[]} normalized aliases - */ -function normalizeAlias(alias) { - return typeof alias === "object" && !Array.isArray(alias) && alias !== null - ? Object.keys(alias).map(key => { - /** @type {AliasOptionEntry} */ - const obj = { name: key, onlyModule: false, alias: alias[key] }; + // Handles first column in table + if (i >= b.length) return aType == "u"; - if (/\$$/.test(key)) { - obj.onlyModule = true; - obj.name = key.substr(0, key.length - 1); - } + var bValue = b[i]; + var bType = (typeof bValue)[0]; - return obj; - }) - : /** @type {Array} */ (alias) || []; -} + if (aType == bType) { + if (aType != "o" && aType != "u" && aValue != bValue) { + return aValue < bValue; + } + i++; + } else { + // Handles remaining cases + if (aType == "o" && bType == "n") return true; + return bType == "s" || aType == "u"; + } + } +}; +/* eslint-enable eqeqeq */ +exports.versionLt = versionLt; /** - * @param {UserResolveOptions} options input options - * @returns {ResolveOptions} output options + * @param {string} str range string + * @returns {SemVerRange} parsed range */ -function createOptions(options) { - const mainFieldsSet = new Set(options.mainFields || ["main"]); - const mainFields = []; +exports.parseRange = str => { + const splitAndConvert = str => { + return str.split(".").map(item => (`${+item}` === item ? +item : item)); + }; + // see https://docs.npmjs.com/misc/semver#range-grammar for grammar + const parsePartial = str => { + const match = /^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str); + /** @type {(string|number|undefined|[])[]} */ + const ver = match[1] ? [0, ...splitAndConvert(match[1])] : [0]; + if (match[2]) { + ver.length++; + ver.push.apply(ver, splitAndConvert(match[2])); + } - for (const item of mainFieldsSet) { - if (typeof item === "string") { - mainFields.push({ - name: [item], - forceRelative: true - }); - } else if (Array.isArray(item)) { - mainFields.push({ - name: item, - forceRelative: true - }); - } else { - mainFields.push({ - name: Array.isArray(item.name) ? item.name : [item.name], - forceRelative: item.forceRelative - }); + // remove trailing any matchers + let last = ver[ver.length - 1]; + while ( + ver.length && + (last === undefined || /^[*xX]$/.test(/** @type {string} */ (last))) + ) { + ver.pop(); + last = ver[ver.length - 1]; } - } - return { - alias: normalizeAlias(options.alias), - fallback: normalizeAlias(options.fallback), - aliasFields: new Set(options.aliasFields), - cachePredicate: - options.cachePredicate || - function () { - return true; - }, - cacheWithContext: - typeof options.cacheWithContext !== "undefined" - ? options.cacheWithContext - : true, - exportsFields: new Set(options.exportsFields || ["exports"]), - importsFields: new Set(options.importsFields || ["imports"]), - conditionNames: new Set(options.conditionNames), - descriptionFiles: Array.from( - new Set(options.descriptionFiles || ["package.json"]) - ), - enforceExtension: - options.enforceExtension === undefined - ? options.extensions && options.extensions.includes("") - ? true - : false - : options.enforceExtension, - extensions: new Set(options.extensions || [".js", ".json", ".node"]), - fileSystem: options.useSyncFileSystemCalls - ? new SyncAsyncFileSystemDecorator( - /** @type {SyncFileSystem} */ ( - /** @type {unknown} */ (options.fileSystem) - ) - ) - : options.fileSystem, - unsafeCache: - options.unsafeCache && typeof options.unsafeCache !== "object" - ? {} - : options.unsafeCache || false, - symlinks: typeof options.symlinks !== "undefined" ? options.symlinks : true, - resolver: options.resolver, - modules: mergeFilteredToArray( - Array.isArray(options.modules) - ? options.modules - : options.modules - ? [options.modules] - : ["node_modules"], - item => { - const type = getType(item); - return type === PathType.Normal || type === PathType.Relative; + return ver; + }; + const toFixed = range => { + if (range.length === 1) { + // Special case for "*" is "x.x.x" instead of "=" + return [0]; + } else if (range.length === 2) { + // Special case for "1" is "1.x.x" instead of "=1" + return [1, ...range.slice(1)]; + } else if (range.length === 3) { + // Special case for "1.2" is "1.2.x" instead of "=1.2" + return [2, ...range.slice(1)]; + } else { + return [range.length, ...range.slice(1)]; + } + }; + const negate = range => { + return [-range[0] - 1, ...range.slice(1)]; + }; + const parseSimple = str => { + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + const match = /^(\^|~|<=|<|>=|>|=|v|!)/.exec(str); + const start = match ? match[0] : ""; + const remainder = parsePartial(str.slice(start.length)); + switch (start) { + case "^": + if (remainder.length > 1 && remainder[1] === 0) { + if (remainder.length > 2 && remainder[2] === 0) { + return [3, ...remainder.slice(1)]; + } + return [2, ...remainder.slice(1)]; + } + return [1, ...remainder.slice(1)]; + case "~": + return [2, ...remainder.slice(1)]; + case ">=": + return remainder; + case "=": + case "v": + case "": + return toFixed(remainder); + case "<": + return negate(remainder); + case ">": { + // and( >=, not( = ) ) => >=, =, not, and + const fixed = toFixed(remainder); + // eslint-disable-next-line no-sparse-arrays + return [, fixed, 0, remainder, 2]; } - ), - mainFields, - mainFiles: new Set(options.mainFiles || ["index"]), - plugins: options.plugins || [], - pnpApi: processPnpApiOption(options.pnpApi), - roots: new Set(options.roots || undefined), - fullySpecified: options.fullySpecified || false, - resolveToContext: options.resolveToContext || false, - preferRelative: options.preferRelative || false, - preferAbsolute: options.preferAbsolute || false, - restrictions: new Set(options.restrictions) + case "<=": + // or( <, = ) => <, =, or + // eslint-disable-next-line no-sparse-arrays + return [, toFixed(remainder), negate(remainder), 1]; + case "!": { + // not = + const fixed = toFixed(remainder); + // eslint-disable-next-line no-sparse-arrays + return [, fixed, 0]; + } + default: + throw new Error("Unexpected start value"); + } }; -} + const combine = (items, fn) => { + if (items.length === 1) return items[0]; + const arr = []; + for (const item of items.slice().reverse()) { + if (0 in item) { + arr.push(item); + } else { + arr.push(...item.slice(1)); + } + } + // eslint-disable-next-line no-sparse-arrays + return [, ...arr, ...items.slice(1).map(() => fn)]; + }; + const parseRange = str => { + // range ::= hyphen | simple ( ' ' simple ) * | '' + // hyphen ::= partial ' - ' partial + const items = str.split(" - "); + if (items.length === 1) { + const items = str.trim().split(/\s+/g).map(parseSimple); + return combine(items, 2); + } + const a = parsePartial(items[0]); + const b = parsePartial(items[1]); + // >=a <=b => and( >=a, or( >=a, { + // range-set ::= range ( logical-or range ) * + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + const items = str.split(/\s*\|\|\s*/).map(parseRange); + return combine(items, 1); + }; + return parseLogicalOr(str); +}; + +/* eslint-disable eqeqeq */ +const rangeToString = range => { + var fixCount = range[0]; + var str = ""; + if (range.length === 1) { + return "*"; + } else if (fixCount + 0.5) { + str += + fixCount == 0 + ? ">=" + : fixCount == -1 + ? "<" + : fixCount == 1 + ? "^" + : fixCount == 2 + ? "~" + : fixCount > 0 + ? "=" + : "!="; + var needDot = 1; + // eslint-disable-next-line no-redeclare + for (var i = 1; i < range.length; i++) { + var item = range[i]; + var t = (typeof item)[0]; + needDot--; + str += + t == "u" + ? // undefined: prerelease marker, add an "-" + "-" + : // number or string: add the item, set flag to add an "." between two of them + (needDot > 0 ? "." : "") + ((needDot = 2), item); + } + return str; + } else { + var stack = []; + // eslint-disable-next-line no-redeclare + for (var i = 1; i < range.length; i++) { + // eslint-disable-next-line no-redeclare + var item = range[i]; + stack.push( + item === 0 + ? "not(" + pop() + ")" + : item === 1 + ? "(" + pop() + " || " + pop() + ")" + : item === 2 + ? stack.pop() + " " + stack.pop() + : rangeToString(item) + ); + } + return pop(); + } + function pop() { + return stack.pop().replace(/^\((.+)\)$/, "$1"); + } +}; +/* eslint-enable eqeqeq */ +exports.rangeToString = rangeToString; +/* eslint-disable eqeqeq */ /** - * @param {UserResolveOptions} options resolve options - * @returns {Resolver} created resolver + * @param {SemVerRange} range version range + * @param {string} version the version + * @returns {boolean} if version satisfy the range */ -exports.createResolver = function (options) { - const normalizedOptions = createOptions(options); - - const { - alias, - fallback, - aliasFields, - cachePredicate, - cacheWithContext, - conditionNames, - descriptionFiles, - enforceExtension, - exportsFields, - importsFields, - extensions, - fileSystem, - fullySpecified, - mainFields, - mainFiles, - modules, - plugins: userPlugins, - pnpApi, - resolveToContext, - preferRelative, - preferAbsolute, - symlinks, - unsafeCache, - resolver: customResolver, - restrictions, - roots - } = normalizedOptions; +const satisfy = (range, version) => { + if (0 in range) { + // @ts-expect-error + version = parseVersion(version); + var fixCount = range[0]; + // when negated is set it swill set for < instead of >= + var negated = fixCount < 0; + if (negated) fixCount = -fixCount - 1; + for (var i = 0, j = 1, isEqual = true; ; j++, i++) { + // cspell:word nequal nequ - const plugins = userPlugins.slice(); + // when isEqual = true: + // range version: EOA/object undefined number string + // EOA equal block big-ver big-ver + // undefined bigger next big-ver big-ver + // number smaller block cmp big-cmp + // fixed number smaller block cmp-fix differ + // string smaller block differ cmp + // fixed string smaller block small-cmp cmp-fix - const resolver = customResolver - ? customResolver - : new Resolver(fileSystem, normalizedOptions); + // when isEqual = false: + // range version: EOA/object undefined number string + // EOA nequal block next-ver next-ver + // undefined nequal block next-ver next-ver + // number nequal block next next + // fixed number nequal block next next (this never happens) + // string nequal block next next + // fixed string nequal block next next (this never happens) - //// pipeline //// + // EOA end of array + // equal (version is equal range): + // when !negated: return true, + // when negated: return false + // bigger (version is bigger as range): + // when fixed: return false, + // when !negated: return true, + // when negated: return false, + // smaller (version is smaller as range): + // when !negated: return false, + // when negated: return true + // nequal (version is not equal range (> resp <)): return true + // block (version is in different prerelease area): return false + // differ (version is different from fixed range (string vs. number)): return false + // next: continues to the next items + // next-ver: when fixed: return false, continues to the next item only for the version, sets isEqual=false + // big-ver: when fixed || negated: return false, continues to the next item only for the version, sets isEqual=false + // next-nequ: continues to the next items, sets isEqual=false + // cmp (negated === false): version < range => return false, version > range => next-nequ, else => next + // cmp (negated === true): version > range => return false, version < range => next-nequ, else => next + // cmp-fix: version == range => next, else => return false + // big-cmp: when negated => return false, else => next-nequ + // small-cmp: when negated => next-nequ, else => return false - resolver.ensureHook("resolve"); - resolver.ensureHook("internalResolve"); - resolver.ensureHook("newInteralResolve"); - resolver.ensureHook("parsedResolve"); - resolver.ensureHook("describedResolve"); - resolver.ensureHook("internal"); - resolver.ensureHook("rawModule"); - resolver.ensureHook("module"); - resolver.ensureHook("resolveAsModule"); - resolver.ensureHook("undescribedResolveInPackage"); - resolver.ensureHook("resolveInPackage"); - resolver.ensureHook("resolveInExistingDirectory"); - resolver.ensureHook("relative"); - resolver.ensureHook("describedRelative"); - resolver.ensureHook("directory"); - resolver.ensureHook("undescribedExistingDirectory"); - resolver.ensureHook("existingDirectory"); - resolver.ensureHook("undescribedRawFile"); - resolver.ensureHook("rawFile"); - resolver.ensureHook("file"); - resolver.ensureHook("finalFile"); - resolver.ensureHook("existingFile"); - resolver.ensureHook("resolved"); + var rangeType = j < range.length ? (typeof range[j])[0] : ""; - // resolve - for (const { source, resolveOptions } of [ - { source: "resolve", resolveOptions: { fullySpecified } }, - { source: "internal-resolve", resolveOptions: { fullySpecified: false } } - ]) { - if (unsafeCache) { - plugins.push( - new UnsafeCachePlugin( - source, - cachePredicate, - unsafeCache, - cacheWithContext, - `new-${source}` - ) - ); - plugins.push( - new ParsePlugin(`new-${source}`, resolveOptions, "parsed-resolve") - ); - } else { - plugins.push(new ParsePlugin(source, resolveOptions, "parsed-resolve")); - } - } + var versionValue; + var versionType; - // parsed-resolve - plugins.push( - new DescriptionFilePlugin( - "parsed-resolve", - descriptionFiles, - false, - "described-resolve" - ) - ); - plugins.push(new NextPlugin("after-parsed-resolve", "described-resolve")); + // Handles first column in both tables (end of version or object) + if ( + i >= version.length || + ((versionValue = version[i]), + (versionType = (typeof versionValue)[0]) == "o") + ) { + // Handles nequal + if (!isEqual) return true; + // Handles bigger + if (rangeType == "u") return j > fixCount && !negated; + // Handles equal and smaller: (range === EOA) XOR negated + return (rangeType == "") != negated; // equal + smaller + } - // described-resolve - plugins.push(new NextPlugin("described-resolve", "normal-resolve")); - if (fallback.length > 0) { - plugins.push( - new AliasPlugin("described-resolve", fallback, "internal-resolve") - ); - } + // Handles second column in both tables (version = undefined) + if (versionType == "u") { + if (!isEqual || rangeType != "u") { + return false; + } + } - // normal-resolve - if (alias.length > 0) - plugins.push(new AliasPlugin("normal-resolve", alias, "internal-resolve")); - aliasFields.forEach(item => { - plugins.push( - new AliasFieldPlugin("normal-resolve", item, "internal-resolve") - ); - }); - if (preferRelative) { - plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); - } - plugins.push( - new ConditionalPlugin( - "after-normal-resolve", - { module: true }, - "resolve as module", - false, - "raw-module" - ) - ); - plugins.push( - new ConditionalPlugin( - "after-normal-resolve", - { internal: true }, - "resolve as internal import", - false, - "internal" - ) - ); - if (preferAbsolute) { - plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); - } - if (roots.size > 0) { - plugins.push(new RootsPlugin("after-normal-resolve", roots, "relative")); - } - if (!preferRelative && !preferAbsolute) { - plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); - } + // switch between first and second table + else if (isEqual) { + // Handle diagonal + if (rangeType == versionType) { + if (j <= fixCount) { + // Handles "cmp-fix" cases + if (versionValue != range[j]) { + return false; + } + } else { + // Handles "cmp" cases + if (negated ? versionValue > range[j] : versionValue < range[j]) { + return false; + } + if (versionValue != range[j]) isEqual = false; + } + } - // internal - importsFields.forEach(importsField => { - plugins.push( - new ImportsFieldPlugin( - "internal", - conditionNames, - importsField, - "relative", - "internal-resolve" - ) - ); - }); + // Handle big-ver + else if (rangeType != "s" && rangeType != "n") { + if (negated || j <= fixCount) return false; + isEqual = false; + j--; + } - // raw-module - exportsFields.forEach(exportsField => { - plugins.push( - new SelfReferencePlugin("raw-module", exportsField, "resolve-as-module") - ); - }); - modules.forEach(item => { - if (Array.isArray(item)) { - if (item.includes("node_modules") && pnpApi) { - plugins.push( - new ModulesInHierachicDirectoriesPlugin( - "raw-module", - item.filter(i => i !== "node_modules"), - "module" - ) - ); - plugins.push( - new PnpPlugin("raw-module", pnpApi, "undescribed-resolve-in-package") - ); + // Handle differ, big-cmp and small-cmp + else if (j <= fixCount || versionType < rangeType != negated) { + return false; + } else { + isEqual = false; + } } else { - plugins.push( - new ModulesInHierachicDirectoriesPlugin("raw-module", item, "module") - ); + // Handles all "next-ver" cases in the second table + if (rangeType != "s" && rangeType != "n") { + isEqual = false; + j--; + } + + // next is applied by default } - } else { - plugins.push(new ModulesInRootPlugin("raw-module", item, "module")); } - }); - - // module - plugins.push(new JoinRequestPartPlugin("module", "resolve-as-module")); - - // resolve-as-module - if (!resolveToContext) { - plugins.push( - new ConditionalPlugin( - "resolve-as-module", - { directory: false, request: "." }, - "single file module", - true, - "undescribed-raw-file" - ) - ); } - plugins.push( - new DirectoryExistsPlugin( - "resolve-as-module", - "undescribed-resolve-in-package" - ) - ); - - // undescribed-resolve-in-package - plugins.push( - new DescriptionFilePlugin( - "undescribed-resolve-in-package", - descriptionFiles, - false, - "resolve-in-package" - ) - ); - plugins.push( - new NextPlugin("after-undescribed-resolve-in-package", "resolve-in-package") - ); - - // resolve-in-package - exportsFields.forEach(exportsField => { - plugins.push( - new ExportsFieldPlugin( - "resolve-in-package", - conditionNames, - exportsField, - "relative" - ) + /** @type {(boolean | number)[]} */ + var stack = []; + var p = stack.pop.bind(stack); + // eslint-disable-next-line no-redeclare + for (var i = 1; i < range.length; i++) { + var item = /** @type {SemVerRange | 0 | 1 | 2} */ (range[i]); + stack.push( + item == 1 + ? p() | p() + : item == 2 + ? p() & p() + : item + ? satisfy(item, version) + : !p() ); - }); - plugins.push( - new NextPlugin("resolve-in-package", "resolve-in-existing-directory") - ); - - // resolve-in-existing-directory - plugins.push( - new JoinRequestPlugin("resolve-in-existing-directory", "relative") - ); - - // relative - plugins.push( - new DescriptionFilePlugin( - "relative", - descriptionFiles, - true, - "described-relative" - ) - ); - plugins.push(new NextPlugin("after-relative", "described-relative")); + } + return !!p(); +}; +/* eslint-enable eqeqeq */ +exports.satisfy = satisfy; - // described-relative - if (resolveToContext) { - plugins.push(new NextPlugin("described-relative", "directory")); - } else { - plugins.push( - new ConditionalPlugin( - "described-relative", - { directory: false }, - null, - true, - "raw-file" - ) - ); - plugins.push( - new ConditionalPlugin( - "described-relative", - { fullySpecified: false }, - "as directory", - true, - "directory" - ) - ); +exports.stringifyHoley = json => { + switch (typeof json) { + case "undefined": + return ""; + case "object": + if (Array.isArray(json)) { + let str = "["; + for (let i = 0; i < json.length; i++) { + if (i !== 0) str += ","; + str += this.stringifyHoley(json[i]); + } + str += "]"; + return str; + } else { + return JSON.stringify(json); + } + default: + return JSON.stringify(json); } +}; + +//#region runtime code: parseVersion +exports.parseVersionRuntimeCode = runtimeTemplate => + `var parseVersion = ${runtimeTemplate.basicFunction("str", [ + "// see webpack/lib/util/semver.js for original code", + `var p=${ + runtimeTemplate.supportsArrowFunction() ? "p=>" : "function(p)" + }{return p.split(".").map((${ + runtimeTemplate.supportsArrowFunction() ? "p=>" : "function(p)" + }{return+p==p?+p:p}))},n=/^([^-+]+)?(?:-([^+]+))?(?:\\+(.+))?$/.exec(str),r=n[1]?p(n[1]):[];return n[2]&&(r.length++,r.push.apply(r,p(n[2]))),n[3]&&(r.push([]),r.push.apply(r,p(n[3]))),r;` + ])}`; +//#endregion - // directory - plugins.push( - new DirectoryExistsPlugin("directory", "undescribed-existing-directory") - ); +//#region runtime code: versionLt +exports.versionLtRuntimeCode = runtimeTemplate => + `var versionLt = ${runtimeTemplate.basicFunction("a, b", [ + "// see webpack/lib/util/semver.js for original code", + 'a=parseVersion(a),b=parseVersion(b);for(var r=0;;){if(r>=a.length)return r=b.length)return"u"==n;var t=b[r],f=(typeof t)[0];if(n!=f)return"o"==n&&"n"==f||("s"==f||"u"==n);if("o"!=n&&"u"!=n&&e!=t)return e { - plugins.push( - new UseFilePlugin( - "undescribed-existing-directory", - item, - "undescribed-raw-file" - ) - ); - }); +//#region runtime code: rangeToString +exports.rangeToStringRuntimeCode = runtimeTemplate => + `var rangeToString = ${runtimeTemplate.basicFunction("range", [ + "// see webpack/lib/util/semver.js for original code", + 'var r=range[0],n="";if(1===range.length)return"*";if(r+.5){n+=0==r?">=":-1==r?"<":1==r?"^":2==r?"~":r>0?"=":"!=";for(var e=1,a=1;a0?".":"")+(e=2,t)}return n}var g=[];for(a=1;a { - plugins.push( - new MainFieldPlugin( - "existing-directory", - item, - "resolve-in-existing-directory" - ) - ); - }); - mainFiles.forEach(item => { - plugins.push( - new UseFilePlugin("existing-directory", item, "undescribed-raw-file") - ); - }); +//#region runtime code: satisfy +exports.satisfyRuntimeCode = runtimeTemplate => + `var satisfy = ${runtimeTemplate.basicFunction("range, version", [ + "// see webpack/lib/util/semver.js for original code", + 'if(0 in range){version=parseVersion(version);var e=range[0],r=e<0;r&&(e=-e-1);for(var n=0,i=1,a=!0;;i++,n++){var f,s,g=i=version.length||"o"==(s=(typeof(f=version[n]))[0]))return!a||("u"==g?i>e&&!r:""==g!=r);if("u"==s){if(!a||"u"!=g)return!1}else if(a)if(g==s)if(i<=e){if(f!=range[i])return!1}else{if(r?f>range[i]:f { - plugins.push(new AppendPlugin("raw-file", item, "file")); - }); +/***/ }), - // file - if (alias.length > 0) - plugins.push(new AliasPlugin("file", alias, "internal-resolve")); - aliasFields.forEach(item => { - plugins.push(new AliasFieldPlugin("file", item, "internal-resolve")); - }); - plugins.push(new NextPlugin("file", "final-file")); +/***/ 8282: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // final-file - plugins.push(new FileExistsPlugin("final-file", "existing-file")); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - // existing-file - if (symlinks) - plugins.push(new SymlinkPlugin("existing-file", "existing-file")); - plugins.push(new NextPlugin("existing-file", "resolved")); - } - // resolved - if (restrictions.size > 0) { - plugins.push(new RestrictionsPlugin(resolver.hooks.resolved, restrictions)); - } - plugins.push(new ResultPlugin(resolver.hooks.resolved)); - //// RESOLVER //// +const memoize = __webpack_require__(78676); - for (const plugin of plugins) { - if (typeof plugin === "function") { - plugin.call(resolver, resolver); - } else { - plugin.apply(resolver); - } - } +/** @typedef {import("../serialization/BinaryMiddleware").MEASURE_END_OPERATION_TYPE} MEASURE_END_OPERATION */ +/** @typedef {import("../serialization/BinaryMiddleware").MEASURE_START_OPERATION_TYPE} MEASURE_START_OPERATION */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ +/** @typedef {import("../serialization/Serializer")} Serializer */ - return resolver; -}; +const getBinaryMiddleware = memoize(() => + __webpack_require__(97059) +); +const getObjectMiddleware = memoize(() => + __webpack_require__(34795) +); +const getSingleItemMiddleware = memoize(() => + __webpack_require__(65112) +); +const getSerializer = memoize(() => __webpack_require__(53080)); +const getSerializerMiddleware = memoize(() => + __webpack_require__(83137) +); -/** - * Merging filtered elements - * @param {string[]} array source array - * @param {function(string): boolean} filter predicate - * @returns {Array} merge result - */ -function mergeFilteredToArray(array, filter) { - /** @type {Array} */ - const result = []; - const set = new Set(array); +const getBinaryMiddlewareInstance = memoize( + () => new (getBinaryMiddleware())() +); - for (const item of set) { - if (filter(item)) { - const lastElement = - result.length > 0 ? result[result.length - 1] : undefined; - if (Array.isArray(lastElement)) { - lastElement.push(item); - } else { - result.push([item]); - } +const registerSerializers = memoize(() => { + __webpack_require__(26611); + + // Load internal paths with a relative require + // This allows bundling all internal serializers + const internalSerializables = __webpack_require__(53023); + getObjectMiddleware().registerLoader(/^webpack\/lib\//, req => { + const loader = internalSerializables[req.slice("webpack/lib/".length)]; + if (loader) { + loader(); } else { - result.push(item); + console.warn(`${req} not found in internalSerializables`); } - } + return true; + }); +}); - return result; -} +/** @type {Serializer} */ +let buffersSerializer; + +// Expose serialization API +module.exports = { + get register() { + return getObjectMiddleware().register; + }, + get registerLoader() { + return getObjectMiddleware().registerLoader; + }, + get registerNotSerializable() { + return getObjectMiddleware().registerNotSerializable; + }, + get NOT_SERIALIZABLE() { + return getObjectMiddleware().NOT_SERIALIZABLE; + }, + /** @type {MEASURE_START_OPERATION} */ + get MEASURE_START_OPERATION() { + return getBinaryMiddleware().MEASURE_START_OPERATION; + }, + /** @type {MEASURE_END_OPERATION} */ + get MEASURE_END_OPERATION() { + return getBinaryMiddleware().MEASURE_END_OPERATION; + }, + get buffersSerializer() { + if (buffersSerializer !== undefined) return buffersSerializer; + registerSerializers(); + const Serializer = getSerializer(); + const binaryMiddleware = getBinaryMiddlewareInstance(); + const SerializerMiddleware = getSerializerMiddleware(); + const SingleItemMiddleware = getSingleItemMiddleware(); + return (buffersSerializer = new Serializer([ + new SingleItemMiddleware(), + new (getObjectMiddleware())(context => { + if (context.write) { + context.writeLazy = value => { + context.write( + SerializerMiddleware.createLazy(value, binaryMiddleware) + ); + }; + } + }, "md4"), + binaryMiddleware + ])); + }, + createFileSerializer: (fs, hashFunction) => { + registerSerializers(); + const Serializer = getSerializer(); + const FileMiddleware = __webpack_require__(65321); + const fileMiddleware = new FileMiddleware(fs, hashFunction); + const binaryMiddleware = getBinaryMiddlewareInstance(); + const SerializerMiddleware = getSerializerMiddleware(); + const SingleItemMiddleware = getSingleItemMiddleware(); + return new Serializer([ + new SingleItemMiddleware(), + new (getObjectMiddleware())(context => { + if (context.write) { + context.writeLazy = value => { + context.write( + SerializerMiddleware.createLazy(value, binaryMiddleware) + ); + }; + context.writeSeparate = (value, options) => { + const lazy = SerializerMiddleware.createLazy( + value, + fileMiddleware, + options + ); + context.write(lazy); + return lazy; + }; + } + }, hashFunction), + binaryMiddleware, + fileMiddleware + ]); + } +}; /***/ }), -/***/ 36400: +/***/ 15652: /***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** + * @typedef {Object} GroupOptions + * @property {boolean=} groupChildren + * @property {boolean=} force + * @property {number=} targetGroupCount + */ -const slashCode = "/".charCodeAt(0); -const backslashCode = "\\".charCodeAt(0); +/** + * @template T + * @template R + * @typedef {Object} GroupConfig + * @property {function(T): string[]} getKeys + * @property {function(string, (R | T)[], T[]): R} createGroup + * @property {function(string, T[]): GroupOptions=} getOptions + */ -const isInside = (path, parent) => { - if (!path.startsWith(parent)) return false; - if (path.length === parent.length) return true; - const charCode = path.charCodeAt(parent.length); - return charCode === slashCode || charCode === backslashCode; -}; +/** + * @template T + * @template R + * @typedef {Object} ItemWithGroups + * @property {T} item + * @property {Set>} groups + */ -module.exports = class RestrictionsPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {Set} restrictions restrictions - */ - constructor(source, restrictions) { - this.source = source; - this.restrictions = restrictions; - } +/** + * @template T + * @template R + * @typedef {{ config: GroupConfig, name: string, alreadyGrouped: boolean, items: Set> | undefined }} Group + */ +/** + * @template T + * @template R + * @param {T[]} items the list of items + * @param {GroupConfig[]} groupConfigs configuration + * @returns {(R | T)[]} grouped items + */ +const smartGrouping = (items, groupConfigs) => { + /** @type {Set>} */ + const itemsWithGroups = new Set(); + /** @type {Map>} */ + const allGroups = new Map(); + for (const item of items) { + /** @type {Set>} */ + const groups = new Set(); + for (let i = 0; i < groupConfigs.length; i++) { + const groupConfig = groupConfigs[i]; + const keys = groupConfig.getKeys(item); + if (keys) { + for (const name of keys) { + const key = `${i}:${name}`; + let group = allGroups.get(key); + if (group === undefined) { + allGroups.set( + key, + (group = { + config: groupConfig, + name, + alreadyGrouped: false, + items: undefined + }) + ); + } + groups.add(group); + } + } + } + itemsWithGroups.add({ + item, + groups + }); + } /** - * @param {Resolver} resolver the resolver - * @returns {void} + * @param {Set>} itemsWithGroups input items with groups + * @returns {(T | R)[]} groups items */ - apply(resolver) { - resolver - .getHook(this.source) - .tapAsync("RestrictionsPlugin", (request, resolveContext, callback) => { - if (typeof request.path === "string") { - const path = request.path; - for (const rule of this.restrictions) { - if (typeof rule === "string") { - if (!isInside(path, rule)) { - if (resolveContext.log) { - resolveContext.log( - `${path} is not inside of the restriction ${rule}` - ); - } - return callback(null, null); - } - } else if (!rule.test(path)) { - if (resolveContext.log) { - resolveContext.log( - `${path} doesn't match the restriction ${rule}` - ); + const runGrouping = itemsWithGroups => { + const totalSize = itemsWithGroups.size; + for (const entry of itemsWithGroups) { + for (const group of entry.groups) { + if (group.alreadyGrouped) continue; + const items = group.items; + if (items === undefined) { + group.items = new Set([entry]); + } else { + items.add(entry); + } + } + } + /** @type {Map, { items: Set>, options: GroupOptions | false | undefined, used: boolean }>} */ + const groupMap = new Map(); + for (const group of allGroups.values()) { + if (group.items) { + const items = group.items; + group.items = undefined; + groupMap.set(group, { + items, + options: undefined, + used: false + }); + } + } + /** @type {(T | R)[]} */ + const results = []; + for (;;) { + /** @type {Group} */ + let bestGroup = undefined; + let bestGroupSize = -1; + let bestGroupItems = undefined; + let bestGroupOptions = undefined; + for (const [group, state] of groupMap) { + const { items, used } = state; + let options = state.options; + if (options === undefined) { + const groupConfig = group.config; + state.options = options = + (groupConfig.getOptions && + groupConfig.getOptions( + group.name, + Array.from(items, ({ item }) => item) + )) || + false; + } + + const force = options && options.force; + if (!force) { + if (bestGroupOptions && bestGroupOptions.force) continue; + if (used) continue; + if (items.size <= 1 || totalSize - items.size <= 1) { + continue; + } + } + const targetGroupCount = (options && options.targetGroupCount) || 4; + let sizeValue = force + ? items.size + : Math.min( + items.size, + (totalSize * 2) / targetGroupCount + + itemsWithGroups.size - + items.size + ); + if ( + sizeValue > bestGroupSize || + (force && (!bestGroupOptions || !bestGroupOptions.force)) + ) { + bestGroup = group; + bestGroupSize = sizeValue; + bestGroupItems = items; + bestGroupOptions = options; + } + } + if (bestGroup === undefined) { + break; + } + const items = new Set(bestGroupItems); + const options = bestGroupOptions; + + const groupChildren = !options || options.groupChildren !== false; + + for (const item of items) { + itemsWithGroups.delete(item); + // Remove all groups that items have from the map to not select them again + for (const group of item.groups) { + const state = groupMap.get(group); + if (state !== undefined) { + state.items.delete(item); + if (state.items.size === 0) { + groupMap.delete(group); + } else { + state.options = undefined; + if (groupChildren) { + state.used = true; } - return callback(null, null); } } } + } + groupMap.delete(bestGroup); - callback(); - }); - } + const key = bestGroup.name; + const groupConfig = bestGroup.config; + + const allItems = Array.from(items, ({ item }) => item); + + bestGroup.alreadyGrouped = true; + const children = groupChildren ? runGrouping(items) : allItems; + bestGroup.alreadyGrouped = false; + + results.push(groupConfig.createGroup(key, children, allItems)); + } + for (const { item } of itemsWithGroups) { + results.push(item); + } + return results; + }; + return runGrouping(itemsWithGroups); }; +module.exports = smartGrouping; + /***/ }), -/***/ 13965: -/***/ (function(module) { +/***/ 41245: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -136960,111 +142172,248 @@ module.exports = class RestrictionsPlugin { -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("webpack-sources").Source} Source */ -module.exports = class ResultPlugin { - /** - * @param {ResolveStepHook} source source - */ - constructor(source) { - this.source = source; - } +/** @type {WeakMap>} */ +const equalityCache = new WeakMap(); - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - this.source.tapAsync( - "ResultPlugin", - (request, resolverContext, callback) => { - const obj = { ...request }; - if (resolverContext.log) - resolverContext.log("reporting result " + obj.path); - resolver.hooks.result.callAsync(obj, resolverContext, err => { - if (err) return callback(err); - callback(null, obj); - }); - } - ); +/** + * @param {Source} a a source + * @param {Source} b another source + * @returns {boolean} true, when both sources are equal + */ +const _isSourceEqual = (a, b) => { + // prefer .buffer(), it's called anyway during emit + /** @type {Buffer|string} */ + let aSource = typeof a.buffer === "function" ? a.buffer() : a.source(); + /** @type {Buffer|string} */ + let bSource = typeof b.buffer === "function" ? b.buffer() : b.source(); + if (aSource === bSource) return true; + if (typeof aSource === "string" && typeof bSource === "string") return false; + if (!Buffer.isBuffer(aSource)) aSource = Buffer.from(aSource, "utf-8"); + if (!Buffer.isBuffer(bSource)) bSource = Buffer.from(bSource, "utf-8"); + return aSource.equals(bSource); +}; + +/** + * @param {Source} a a source + * @param {Source} b another source + * @returns {boolean} true, when both sources are equal + */ +const isSourceEqual = (a, b) => { + if (a === b) return true; + const cache1 = equalityCache.get(a); + if (cache1 !== undefined) { + const result = cache1.get(b); + if (result !== undefined) return result; + } + const result = _isSourceEqual(a, b); + if (cache1 !== undefined) { + cache1.set(b, result); + } else { + const map = new WeakMap(); + map.set(b, result); + equalityCache.set(a, map); } + const cache2 = equalityCache.get(b); + if (cache2 !== undefined) { + cache2.set(a, result); + } else { + const map = new WeakMap(); + map.set(a, result); + equalityCache.set(b, map); + } + return result; }; +exports.isSourceEqual = isSourceEqual; /***/ }), -/***/ 66737: +/***/ 12047: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const forEachBail = __webpack_require__(78565); +const { validate } = __webpack_require__(38476); -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/* cSpell:disable */ +const DID_YOU_MEAN = { + rules: "module.rules", + loaders: "module.rules or module.rules.*.use", + query: "module.rules.*.options (BREAKING CHANGE since webpack 5)", + noParse: "module.noParse", + filename: "output.filename or module.rules.*.generator.filename", + file: "output.filename", + chunkFilename: "output.chunkFilename", + chunkfilename: "output.chunkFilename", + ecmaVersion: + "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", + ecmaversion: + "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", + ecma: "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", + path: "output.path", + pathinfo: "output.pathinfo", + pathInfo: "output.pathinfo", + jsonpFunction: "output.chunkLoadingGlobal (BREAKING CHANGE since webpack 5)", + chunkCallbackName: + "output.chunkLoadingGlobal (BREAKING CHANGE since webpack 5)", + jsonpScriptType: "output.scriptType (BREAKING CHANGE since webpack 5)", + hotUpdateFunction: "output.hotUpdateGlobal (BREAKING CHANGE since webpack 5)", + splitChunks: "optimization.splitChunks", + immutablePaths: "snapshot.immutablePaths", + managedPaths: "snapshot.managedPaths", + maxModules: "stats.modulesSpace (BREAKING CHANGE since webpack 5)", + hashedModuleIds: + 'optimization.moduleIds: "hashed" (BREAKING CHANGE since webpack 5)', + namedChunks: + 'optimization.chunkIds: "named" (BREAKING CHANGE since webpack 5)', + namedModules: + 'optimization.moduleIds: "named" (BREAKING CHANGE since webpack 5)', + occurrenceOrder: + 'optimization.chunkIds: "size" and optimization.moduleIds: "size" (BREAKING CHANGE since webpack 5)', + automaticNamePrefix: + "optimization.splitChunks.[cacheGroups.*].idHint (BREAKING CHANGE since webpack 5)", + noEmitOnErrors: + "optimization.emitOnErrors (BREAKING CHANGE since webpack 5: logic is inverted to avoid negative flags)", + Buffer: + "to use the ProvidePlugin to process the Buffer variable to modules as polyfill\n" + + "BREAKING CHANGE: webpack 5 no longer provided Node.js polyfills by default.\n" + + "Note: if you are using 'node.Buffer: false', you can just remove that as this is the default behavior now.\n" + + "To provide a polyfill to modules use:\n" + + 'new ProvidePlugin({ Buffer: ["buffer", "Buffer"] }) and npm install buffer.', + process: + "to use the ProvidePlugin to process the process variable to modules as polyfill\n" + + "BREAKING CHANGE: webpack 5 no longer provided Node.js polyfills by default.\n" + + "Note: if you are using 'node.process: false', you can just remove that as this is the default behavior now.\n" + + "To provide a polyfill to modules use:\n" + + 'new ProvidePlugin({ process: "process" }) and npm install buffer.' +}; -class RootsPlugin { - /** - * @param {string | ResolveStepHook} source source hook - * @param {Set} roots roots - * @param {string | ResolveStepHook} target target hook - */ - constructor(source, roots, target) { - this.roots = Array.from(roots); - this.source = source; - this.target = target; - } +const REMOVED = { + concord: + "BREAKING CHANGE: resolve.concord has been removed and is no longer available.", + devtoolLineToLine: + "BREAKING CHANGE: output.devtoolLineToLine has been removed and is no longer available." +}; +/* cSpell:enable */ - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); +/** + * @param {Parameters[0]} schema a json schema + * @param {Parameters[1]} options the options that should be validated + * @param {Parameters[2]=} validationConfiguration configuration for generating errors + * @returns {void} + */ +const validateSchema = (schema, options, validationConfiguration) => { + validate( + schema, + options, + validationConfiguration || { + name: "Webpack", + postFormatter: (formattedError, error) => { + const children = error.children; + if ( + children && + children.some( + child => + child.keyword === "absolutePath" && + child.dataPath === ".output.filename" + ) + ) { + return `${formattedError}\nPlease use output.path to specify absolute path and output.filename for the file name.`; + } - resolver - .getHook(this.source) - .tapAsync("RootsPlugin", (request, resolveContext, callback) => { - const req = request.request; - if (!req) return callback(); - if (!req.startsWith("/")) return callback(); + if ( + children && + children.some( + child => + child.keyword === "pattern" && child.dataPath === ".devtool" + ) + ) { + return ( + `${formattedError}\n` + + "BREAKING CHANGE since webpack 5: The devtool option is more strict.\n" + + "Please strictly follow the order of the keywords in the pattern." + ); + } - forEachBail( - this.roots, - (root, callback) => { - const path = resolver.join(root, req.slice(1)); - const obj = { - ...request, - path, - relativePath: request.relativePath && path - }; - resolver.doResolve( - target, - obj, - `root path ${root}`, - resolveContext, - callback + if (error.keyword === "additionalProperties") { + const params = + /** @type {import("ajv").AdditionalPropertiesParams} */ ( + error.params ); - }, - callback - ); - }); - } -} + if ( + Object.prototype.hasOwnProperty.call( + DID_YOU_MEAN, + params.additionalProperty + ) + ) { + return `${formattedError}\nDid you mean ${ + DID_YOU_MEAN[params.additionalProperty] + }?`; + } -module.exports = RootsPlugin; + if ( + Object.prototype.hasOwnProperty.call( + REMOVED, + params.additionalProperty + ) + ) { + return `${formattedError}\n${REMOVED[params.additionalProperty]}?`; + } + + if (!error.dataPath) { + if (params.additionalProperty === "debug") { + return ( + `${formattedError}\n` + + "The 'debug' property was removed in webpack 2.0.0.\n" + + "Loaders should be updated to allow passing this option via loader options in module.rules.\n" + + "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" + + "plugins: [\n" + + " new webpack.LoaderOptionsPlugin({\n" + + " debug: true\n" + + " })\n" + + "]" + ); + } + + if (params.additionalProperty) { + return ( + `${formattedError}\n` + + "For typos: please correct them.\n" + + "For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.\n" + + " Loaders should be updated to allow passing options via loader options in module.rules.\n" + + " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" + + " plugins: [\n" + + " new webpack.LoaderOptionsPlugin({\n" + + " // test: /\\.xxx$/, // may apply this only for some modules\n" + + " options: {\n" + + ` ${params.additionalProperty}: …\n` + + " }\n" + + " })\n" + + " ]" + ); + } + } + } + + return formattedError; + } + } + ); +}; +module.exports = validateSchema; /***/ }), -/***/ 52232: +/***/ 5434: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -137075,84 +142424,82 @@ module.exports = RootsPlugin; -const DescriptionFileUtils = __webpack_require__(25424); - -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - -const slashCode = "/".charCodeAt(0); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); -module.exports = class SelfReferencePlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | string[]} fieldNamePath name path - * @param {string | ResolveStepHook} target target - */ - constructor(source, fieldNamePath, target) { - this.source = source; - this.target = target; - this.fieldName = fieldNamePath; +class AsyncWasmLoadingRuntimeModule extends RuntimeModule { + constructor({ generateLoadBinaryCode, supportsStreaming }) { + super("wasm loading", RuntimeModule.STAGE_NORMAL); + this.generateLoadBinaryCode = generateLoadBinaryCode; + this.supportsStreaming = supportsStreaming; } /** - * @param {Resolver} resolver the resolver - * @returns {void} + * @returns {string} runtime code */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("SelfReferencePlugin", (request, resolveContext, callback) => { - if (!request.descriptionFilePath) return callback(); - - const req = request.request; - if (!req) return callback(); - - // Feature is only enabled when an exports field is present - const exportsField = DescriptionFileUtils.getField( - request.descriptionFileData, - this.fieldName - ); - if (!exportsField) return callback(); - - const name = DescriptionFileUtils.getField( - request.descriptionFileData, - "name" - ); - if (typeof name !== "string") return callback(); - - if ( - req.startsWith(name) && - (req.length === name.length || - req.charCodeAt(name.length) === slashCode) - ) { - const remainingRequest = `.${req.slice(name.length)}`; - - const obj = { - ...request, - request: remainingRequest, - path: /** @type {string} */ (request.descriptionFileRoot), - relativePath: "." - }; - - resolver.doResolve( - target, - obj, - "self reference", - resolveContext, - callback - ); - } else { - return callback(); - } - }); + generate() { + const { compilation, chunk } = this; + const { outputOptions, runtimeTemplate } = compilation; + const fn = RuntimeGlobals.instantiateWasm; + const wasmModuleSrcPath = compilation.getPath( + JSON.stringify(outputOptions.webassemblyModuleFilename), + { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: length => + `" + ${RuntimeGlobals.getFullHash}}().slice(0, ${length}) + "`, + module: { + id: '" + wasmModuleId + "', + hash: `" + wasmModuleHash + "`, + hashWithLength(length) { + return `" + wasmModuleHash.slice(0, ${length}) + "`; + } + }, + runtime: chunk.runtime + } + ); + return `${fn} = ${runtimeTemplate.basicFunction( + "exports, wasmModuleId, wasmModuleHash, importsObj", + [ + `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, + this.supportsStreaming + ? Template.asString([ + "if (typeof WebAssembly.instantiateStreaming === 'function') {", + Template.indent([ + "return WebAssembly.instantiateStreaming(req, importsObj)", + Template.indent([ + `.then(${runtimeTemplate.returningFunction( + "Object.assign(exports, res.instance.exports)", + "res" + )});` + ]) + ]), + "}" + ]) + : "// no support for streaming compilation", + "return req", + Template.indent([ + `.then(${runtimeTemplate.returningFunction("x.arrayBuffer()", "x")})`, + `.then(${runtimeTemplate.returningFunction( + "WebAssembly.instantiate(bytes, importsObj)", + "bytes" + )})`, + `.then(${runtimeTemplate.returningFunction( + "Object.assign(exports, res.instance.exports)", + "res" + )});` + ]) + ] + )};`; } -}; +} + +module.exports = AsyncWasmLoadingRuntimeModule; /***/ }), -/***/ 58885: +/***/ 58461: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -137163,93 +142510,58 @@ module.exports = class SelfReferencePlugin { -const forEachBail = __webpack_require__(78565); -const getPaths = __webpack_require__(82918); -const { getType, PathType } = __webpack_require__(67079); +const Generator = __webpack_require__(93401); -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../NormalModule")} NormalModule */ + +const TYPES = new Set(["webassembly"]); + +class AsyncWebAssemblyGenerator extends Generator { + constructor(options) { + super(); + this.options = options; + } -module.exports = class SymlinkPlugin { /** - * @param {string | ResolveStepHook} source source - * @param {string | ResolveStepHook} target target + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - constructor(source, target) { - this.source = source; - this.target = target; + getTypes(module) { + return TYPES; } /** - * @param {Resolver} resolver the resolver - * @returns {void} + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - const fs = resolver.fileSystem; - resolver - .getHook(this.source) - .tapAsync("SymlinkPlugin", (request, resolveContext, callback) => { - if (request.ignoreSymlinks) return callback(); - const pathsResult = getPaths(request.path); - const pathSeqments = pathsResult.seqments; - const paths = pathsResult.paths; + getSize(module, type) { + const originalSource = module.originalSource(); + if (!originalSource) { + return 0; + } + return originalSource.size(); + } - let containsSymlink = false; - let idx = -1; - forEachBail( - paths, - (path, callback) => { - idx++; - if (resolveContext.fileDependencies) - resolveContext.fileDependencies.add(path); - fs.readlink(path, (err, result) => { - if (!err && result) { - pathSeqments[idx] = result; - containsSymlink = true; - // Shortcut when absolute symlink found - const resultType = getType(result.toString()); - if ( - resultType === PathType.AbsoluteWin || - resultType === PathType.AbsolutePosix - ) { - return callback(null, idx); - } - } - callback(); - }); - }, - (err, idx) => { - if (!containsSymlink) return callback(); - const resultSeqments = - typeof idx === "number" - ? pathSeqments.slice(0, idx + 1) - : pathSeqments.slice(); - const result = resultSeqments.reduceRight((a, b) => { - return resolver.join(a, b); - }); - const obj = { - ...request, - path: result - }; - resolver.doResolve( - target, - obj, - "resolved symlink to " + result, - resolveContext, - callback - ); - } - ); - }); + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code + */ + generate(module, generateContext) { + return module.originalSource(); } -}; +} + +module.exports = AsyncWebAssemblyGenerator; /***/ }), -/***/ 87474: -/***/ (function(module) { +/***/ 95614: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -137259,100 +142571,193 @@ module.exports = class SymlinkPlugin { -/** @typedef {import("./Resolver").FileSystem} FileSystem */ -/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ +const { RawSource } = __webpack_require__(51255); +const Generator = __webpack_require__(93401); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const WebAssemblyImportDependency = __webpack_require__(5239); -/** - * @param {SyncFileSystem} fs file system implementation - * @constructor - */ -function SyncAsyncFileSystemDecorator(fs) { - this.fs = fs; +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ - this.lstat = undefined; - this.lstatSync = undefined; - const lstatSync = fs.lstatSync; - if (lstatSync) { - this.lstat = (arg, options, callback) => { - let result; - try { - result = lstatSync.call(fs, arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.lstatSync = (arg, options) => lstatSync.call(fs, arg, options); +const TYPES = new Set(["webassembly"]); + +class AsyncWebAssemblyJavascriptGenerator extends Generator { + constructor(filenameTemplate) { + super(); + this.filenameTemplate = filenameTemplate; } - this.stat = (arg, options, callback) => { - let result; - try { - result = callback ? fs.statSync(arg, options) : fs.statSync(arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.statSync = (arg, options) => fs.statSync(arg, options); + /** + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) + */ + getTypes(module) { + return TYPES; + } - this.readdir = (arg, options, callback) => { - let result; - try { - result = fs.readdirSync(arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.readdirSync = (arg, options) => fs.readdirSync(arg, options); + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + return 40 + module.dependencies.length * 10; + } - this.readFile = (arg, options, callback) => { - let result; - try { - result = fs.readFileSync(arg); - } catch (e) { - return (callback || options)(e); + /** + * @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 { + runtimeTemplate, + chunkGraph, + moduleGraph, + runtimeRequirements, + runtime + } = generateContext; + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(RuntimeGlobals.moduleId); + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.instantiateWasm); + /** @type {InitFragment[]} */ + const initFragments = []; + /** @type {Map} */ + const depModules = new Map(); + /** @type {Map} */ + const wasmDepsByRequest = new Map(); + for (const dep of module.dependencies) { + if (dep instanceof WebAssemblyImportDependency) { + const module = moduleGraph.getModule(dep); + if (!depModules.has(module)) { + depModules.set(module, { + request: dep.request, + importVar: `WEBPACK_IMPORTED_MODULE_${depModules.size}` + }); + } + let list = wasmDepsByRequest.get(dep.request); + if (list === undefined) { + list = []; + wasmDepsByRequest.set(dep.request, list); + } + list.push(dep); + } } - (callback || options)(null, result); - }; - this.readFileSync = (arg, options) => fs.readFileSync(arg, options); - this.readlink = (arg, options, callback) => { - let result; - try { - result = fs.readlinkSync(arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.readlinkSync = (arg, options) => fs.readlinkSync(arg, options); + const promises = []; - this.readJson = undefined; - this.readJsonSync = undefined; - const readJsonSync = fs.readJsonSync; - if (readJsonSync) { - this.readJson = (arg, options, callback) => { - let result; - try { - result = readJsonSync.call(fs, arg); - } catch (e) { - return (callback || options)(e); + const importStatements = Array.from( + depModules, + ([importedModule, { request, importVar }]) => { + if (moduleGraph.isAsync(importedModule)) { + promises.push(importVar); + } + return runtimeTemplate.importStatement({ + update: false, + module: importedModule, + chunkGraph, + request, + originModule: module, + importVar, + runtimeRequirements + }); } - (callback || options)(null, result); - }; + ); + const importsCode = importStatements.map(([x]) => x).join(""); + const importsCompatCode = importStatements.map(([_, x]) => x).join(""); - this.readJsonSync = (arg, options) => readJsonSync.call(fs, arg, options); + const importObjRequestItems = Array.from( + wasmDepsByRequest, + ([request, deps]) => { + const exportItems = deps.map(dep => { + const importedModule = moduleGraph.getModule(dep); + const importVar = depModules.get(importedModule).importVar; + return `${JSON.stringify( + dep.name + )}: ${runtimeTemplate.exportFromImport({ + moduleGraph, + module: importedModule, + request, + exportName: dep.name, + originModule: module, + asiSafe: true, + isCall: false, + callContext: false, + defaultInterop: true, + importVar, + initFragments, + runtime, + runtimeRequirements + })}`; + }); + return Template.asString([ + `${JSON.stringify(request)}: {`, + Template.indent(exportItems.join(",\n")), + "}" + ]); + } + ); + + const importsObj = + importObjRequestItems.length > 0 + ? Template.asString([ + "{", + Template.indent(importObjRequestItems.join(",\n")), + "}" + ]) + : undefined; + + const instantiateCall = + `${RuntimeGlobals.instantiateWasm}(${module.exportsArgument}, ${ + module.moduleArgument + }.id, ${JSON.stringify( + chunkGraph.getRenderedModuleHash(module, runtime) + )}` + (importsObj ? `, ${importsObj})` : `)`); + + if (promises.length > 0) + runtimeRequirements.add(RuntimeGlobals.asyncModule); + + const source = new RawSource( + promises.length > 0 + ? Template.asString([ + `var __webpack_instantiate__ = ${runtimeTemplate.basicFunction( + `[${promises.join(", ")}]`, + `${importsCompatCode}return ${instantiateCall};` + )}`, + `${RuntimeGlobals.asyncModule}(${ + module.moduleArgument + }, ${runtimeTemplate.basicFunction( + "__webpack_handle_async_dependencies__", + [ + importsCode, + `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${promises.join( + ", " + )}]);`, + "return __webpack_async_dependencies__.then ? __webpack_async_dependencies__.then(__webpack_instantiate__) : __webpack_instantiate__(__webpack_async_dependencies__);" + ] + )}, 1);` + ]) + : `${importsCode}${importsCompatCode}module.exports = ${instantiateCall};` + ); + + return InitFragment.addToSource(source, initFragments, generateContext); } } -module.exports = SyncAsyncFileSystemDecorator; + +module.exports = AsyncWebAssemblyJavascriptGenerator; /***/ }), -/***/ 99324: -/***/ (function(module) { +/***/ 7538: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -137362,121 +142767,203 @@ module.exports = SyncAsyncFileSystemDecorator; -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +const { SyncWaterfallHook } = __webpack_require__(41242); +const Compilation = __webpack_require__(85720); +const Generator = __webpack_require__(93401); +const { tryRunOrWebpackError } = __webpack_require__(11351); +const WebAssemblyImportDependency = __webpack_require__(5239); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const memoize = __webpack_require__(78676); -module.exports = class TryNextPlugin { +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../Template").RenderManifestEntry} RenderManifestEntry */ +/** @typedef {import("../Template").RenderManifestOptions} RenderManifestOptions */ + +const getAsyncWebAssemblyGenerator = memoize(() => + __webpack_require__(58461) +); +const getAsyncWebAssemblyJavascriptGenerator = memoize(() => + __webpack_require__(95614) +); +const getAsyncWebAssemblyParser = memoize(() => + __webpack_require__(96305) +); + +/** + * @typedef {Object} WebAssemblyRenderContext + * @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 + * @property {CodeGenerationResults} codeGenerationResults results of code generation + */ + +/** + * @typedef {Object} CompilationHooks + * @property {SyncWaterfallHook<[Source, Module, WebAssemblyRenderContext]>} renderModuleContent + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class AsyncWebAssemblyModulesPlugin { /** - * @param {string | ResolveStepHook} source source - * @param {string} message message - * @param {string | ResolveStepHook} target target + * @param {Compilation} compilation the compilation + * @returns {CompilationHooks} the attached hooks */ - constructor(source, message, target) { - this.source = source; - this.message = message; - this.target = target; + 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 = { + renderModuleContent: new SyncWaterfallHook([ + "source", + "module", + "renderContext" + ]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + constructor(options) { + this.options = options; } /** - * @param {Resolver} resolver the resolver + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("TryNextPlugin", (request, resolveContext, callback) => { - resolver.doResolve( - target, - request, - this.message, - resolveContext, - callback + apply(compiler) { + compiler.hooks.compilation.tap( + "AsyncWebAssemblyModulesPlugin", + (compilation, { normalModuleFactory }) => { + const hooks = + AsyncWebAssemblyModulesPlugin.getCompilationHooks(compilation); + compilation.dependencyFactories.set( + WebAssemblyImportDependency, + normalModuleFactory ); - }); - } -}; - - -/***/ }), - -/***/ 41606: -/***/ (function(module) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + normalModuleFactory.hooks.createParser + .for("webassembly/async") + .tap("AsyncWebAssemblyModulesPlugin", () => { + const AsyncWebAssemblyParser = getAsyncWebAssemblyParser(); + return new AsyncWebAssemblyParser(); + }); + normalModuleFactory.hooks.createGenerator + .for("webassembly/async") + .tap("AsyncWebAssemblyModulesPlugin", () => { + const AsyncWebAssemblyJavascriptGenerator = + getAsyncWebAssemblyJavascriptGenerator(); + const AsyncWebAssemblyGenerator = getAsyncWebAssemblyGenerator(); + return Generator.byType({ + javascript: new AsyncWebAssemblyJavascriptGenerator( + compilation.outputOptions.webassemblyModuleFilename + ), + webassembly: new AsyncWebAssemblyGenerator(this.options) + }); + }); -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {{[k: string]: any}} Cache */ + compilation.hooks.renderManifest.tap( + "WebAssemblyModulesPlugin", + (result, options) => { + const { moduleGraph, chunkGraph, runtimeTemplate } = compilation; + const { + chunk, + outputOptions, + dependencyTemplates, + codeGenerationResults + } = options; -function getCacheId(request, withContext) { - return JSON.stringify({ - context: withContext ? request.context : "", - path: request.path, - query: request.query, - fragment: request.fragment, - request: request.request - }); -} + for (const module of chunkGraph.getOrderedChunkModulesIterable( + chunk, + compareModulesByIdentifier + )) { + if (module.type === "webassembly/async") { + const filenameTemplate = + outputOptions.webassemblyModuleFilename; -module.exports = class UnsafeCachePlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {function(ResolveRequest): boolean} filterPredicate filterPredicate - * @param {Cache} cache cache - * @param {boolean} withContext withContext - * @param {string | ResolveStepHook} target target - */ - constructor(source, filterPredicate, cache, withContext, target) { - this.source = source; - this.filterPredicate = filterPredicate; - this.withContext = withContext; - this.cache = cache; - this.target = target; - } + result.push({ + render: () => + this.renderModule( + module, + { + chunk, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + codeGenerationResults + }, + hooks + ), + filenameTemplate, + pathOptions: { + module, + runtime: chunk.runtime, + chunkGraph + }, + auxiliary: true, + identifier: `webassemblyAsyncModule${chunkGraph.getModuleId( + module + )}`, + hash: chunkGraph.getModuleHash(module, chunk.runtime) + }); + } + } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("UnsafeCachePlugin", (request, resolveContext, callback) => { - if (!this.filterPredicate(request)) return callback(); - const cacheId = getCacheId(request, this.withContext); - const cacheEntry = this.cache[cacheId]; - if (cacheEntry) { - return callback(null, cacheEntry); - } - resolver.doResolve( - target, - request, - null, - resolveContext, - (err, result) => { - if (err) return callback(err); - if (result) return callback(null, (this.cache[cacheId] = result)); - callback(); + return result; } ); - }); + } + ); } -}; + + renderModule(module, renderContext, hooks) { + const { codeGenerationResults, chunk } = renderContext; + try { + const moduleSource = codeGenerationResults.getSource( + module, + chunk.runtime, + "webassembly" + ); + return tryRunOrWebpackError( + () => + hooks.renderModuleContent.call(moduleSource, module, renderContext), + "AsyncWebAssemblyModulesPlugin.getCompilationHooks().renderModuleContent" + ); + } catch (e) { + e.module = module; + throw e; + } + } +} + +module.exports = AsyncWebAssemblyModulesPlugin; /***/ }), -/***/ 96972: -/***/ (function(module) { +/***/ 96305: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -137486,209 +142973,483 @@ module.exports = class UnsafeCachePlugin { -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +const t = __webpack_require__(51826); +const { decode } = __webpack_require__(73726); +const Parser = __webpack_require__(11715); +const StaticExportsDependency = __webpack_require__(91418); +const WebAssemblyImportDependency = __webpack_require__(5239); -module.exports = class UseFilePlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string} filename filename - * @param {string | ResolveStepHook} target target - */ - constructor(source, filename, target) { - this.source = source; - this.filename = filename; - this.target = target; +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ + +const decoderOpts = { + ignoreCodeSection: true, + ignoreDataSection: true, + + // this will avoid having to lookup with identifiers in the ModuleContext + ignoreCustomNameSection: true +}; + +class WebAssemblyParser extends Parser { + constructor(options) { + super(); + this.hooks = Object.freeze({}); + this.options = options; } /** - * @param {Resolver} resolver the resolver - * @returns {void} + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("UseFilePlugin", (request, resolveContext, callback) => { - const filePath = resolver.join(request.path, this.filename); - const obj = { - ...request, - path: filePath, - relativePath: - request.relativePath && - resolver.join(request.relativePath, this.filename) - }; - resolver.doResolve( - target, - obj, - "using path: " + filePath, - resolveContext, - callback + parse(source, state) { + if (!Buffer.isBuffer(source)) { + throw new Error("WebAssemblyParser input must be a Buffer"); + } + + // flag it as async module + state.module.buildInfo.strict = true; + state.module.buildMeta.exportsType = "namespace"; + state.module.buildMeta.async = true; + + // parse it + const program = decode(source, decoderOpts); + const module = program.body[0]; + + const exports = []; + t.traverse(module, { + ModuleExport({ node }) { + exports.push(node.name); + }, + + ModuleImport({ node }) { + const dep = new WebAssemblyImportDependency( + node.module, + node.name, + node.descr, + false ); - }); + + state.module.addDependency(dep); + } + }); + + state.module.addDependency(new StaticExportsDependency(exports, false)); + + return state; } -}; +} + +module.exports = WebAssemblyParser; /***/ }), -/***/ 81218: -/***/ (function(module) { +/***/ 78455: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -module.exports = function createInnerContext( - options, - message, - messageOptional -) { - let messageReported = false; - let innerLog = undefined; - if (options.log) { - if (message) { - innerLog = msg => { - if (!messageReported) { - options.log(message); - messageReported = true; - } - options.log(" " + msg); - }; - } else { - innerLog = options.log; - } +const WebpackError = __webpack_require__(53799); + +module.exports = class UnsupportedWebAssemblyFeatureError extends WebpackError { + /** @param {string} message Error message */ + constructor(message) { + super(message); + this.name = "UnsupportedWebAssemblyFeatureError"; + this.hideStack = true; } - const childContext = { - log: innerLog, - fileDependencies: options.fileDependencies, - contextDependencies: options.contextDependencies, - missingDependencies: options.missingDependencies, - stack: options.stack - }; - return childContext; }; /***/ }), -/***/ 78565: -/***/ (function(module) { +/***/ 87394: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -module.exports = function forEachBail(array, iterator, callback) { - if (array.length === 0) return callback(); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const WebAssemblyUtils = __webpack_require__(18650); - let i = 0; - const next = () => { - let loop = undefined; - iterator(array[i++], (err, result) => { - if (err || result !== undefined || i >= array.length) { - return callback(err, result); +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +// TODO webpack 6 remove the whole folder + +// Get all wasm modules +const getAllWasmModules = (moduleGraph, chunkGraph, chunk) => { + const wasmModules = chunk.getAllAsyncChunks(); + const array = []; + for (const chunk of wasmModules) { + for (const m of chunkGraph.getOrderedChunkModulesIterable( + chunk, + compareModulesByIdentifier + )) { + if (m.type.startsWith("webassembly")) { + array.push(m); } - if (loop === false) while (next()); - loop = true; - }); - if (!loop) loop = false; - return loop; - }; - while (next()); + } + } + + return array; }; +/** + * generates the import object function for a module + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Module} module the module + * @param {boolean} mangle mangle imports + * @param {string[]} declarations array where declarations are pushed to + * @param {RuntimeSpec} runtime the runtime + * @returns {string} source code + */ +const generateImportObject = ( + chunkGraph, + module, + mangle, + declarations, + runtime +) => { + const moduleGraph = chunkGraph.moduleGraph; + const waitForInstances = new Map(); + const properties = []; + const usedWasmDependencies = WebAssemblyUtils.getUsedDependencies( + moduleGraph, + module, + mangle + ); + for (const usedDep of usedWasmDependencies) { + const dep = usedDep.dependency; + const importedModule = moduleGraph.getModule(dep); + const exportName = dep.name; + const usedName = + importedModule && + moduleGraph + .getExportsInfo(importedModule) + .getUsedName(exportName, runtime); + const description = dep.description; + const direct = dep.onlyDirectImport; -/***/ }), + const module = usedDep.module; + const name = usedDep.name; -/***/ 47956: -/***/ (function(module) { + if (direct) { + const instanceVar = `m${waitForInstances.size}`; + waitForInstances.set(instanceVar, chunkGraph.getModuleId(importedModule)); + properties.push({ + module, + name, + value: `${instanceVar}[${JSON.stringify(usedName)}]` + }); + } else { + const params = description.signature.params.map( + (param, k) => "p" + k + param.valtype + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const mod = `${RuntimeGlobals.moduleCache}[${JSON.stringify( + chunkGraph.getModuleId(importedModule) + )}]`; + const modExports = `${mod}.exports`; + const cache = `wasmImportedFuncCache${declarations.length}`; + declarations.push(`var ${cache};`); + properties.push({ + module, + name, + value: Template.asString([ + (importedModule.type.startsWith("webassembly") + ? `${mod} ? ${modExports}[${JSON.stringify(usedName)}] : ` + : "") + `function(${params}) {`, + Template.indent([ + `if(${cache} === undefined) ${cache} = ${modExports};`, + `return ${cache}[${JSON.stringify(usedName)}](${params});` + ]), + "}" + ]) + }); + } + } -module.exports = function getInnerRequest(resolver, request) { - if ( - typeof request.__innerRequest === "string" && - request.__innerRequest_request === request.request && - request.__innerRequest_relativePath === request.relativePath - ) - return request.__innerRequest; - let innerRequest; - if (request.request) { - innerRequest = request.request; - if (/^\.\.?(?:\/|$)/.test(innerRequest) && request.relativePath) { - innerRequest = resolver.join(request.relativePath, innerRequest); + let importObject; + if (mangle) { + importObject = [ + "return {", + Template.indent([ + properties.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") + ]), + "};" + ]; + } else { + const propertiesByModule = new Map(); + for (const p of properties) { + let list = propertiesByModule.get(p.module); + if (list === undefined) { + propertiesByModule.set(p.module, (list = [])); + } + list.push(p); } + importObject = [ + "return {", + Template.indent([ + Array.from(propertiesByModule, ([module, list]) => { + return Template.asString([ + `${JSON.stringify(module)}: {`, + Template.indent([ + list.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") + ]), + "}" + ]); + }).join(",\n") + ]), + "};" + ]; + } + + const moduleIdStringified = JSON.stringify(chunkGraph.getModuleId(module)); + if (waitForInstances.size === 1) { + const moduleId = Array.from(waitForInstances.values())[0]; + const promise = `installedWasmModules[${JSON.stringify(moduleId)}]`; + const variable = Array.from(waitForInstances.keys())[0]; + return Template.asString([ + `${moduleIdStringified}: function() {`, + Template.indent([ + `return promiseResolve().then(function() { return ${promise}; }).then(function(${variable}) {`, + Template.indent(importObject), + "});" + ]), + "}," + ]); + } else if (waitForInstances.size > 0) { + const promises = Array.from( + waitForInstances.values(), + id => `installedWasmModules[${JSON.stringify(id)}]` + ).join(", "); + const variables = Array.from( + waitForInstances.keys(), + (name, i) => `${name} = array[${i}]` + ).join(", "); + return Template.asString([ + `${moduleIdStringified}: function() {`, + Template.indent([ + `return promiseResolve().then(function() { return Promise.all([${promises}]); }).then(function(array) {`, + Template.indent([`var ${variables};`, ...importObject]), + "});" + ]), + "}," + ]); } else { - innerRequest = request.relativePath; + return Template.asString([ + `${moduleIdStringified}: function() {`, + Template.indent(importObject), + "}," + ]); } - request.__innerRequest_request = request.request; - request.__innerRequest_relativePath = request.relativePath; - return (request.__innerRequest = innerRequest); }; +class WasmChunkLoadingRuntimeModule extends RuntimeModule { + constructor({ + generateLoadBinaryCode, + supportsStreaming, + mangleImports, + runtimeRequirements + }) { + super("wasm chunk loading", RuntimeModule.STAGE_ATTACH); + this.generateLoadBinaryCode = generateLoadBinaryCode; + this.supportsStreaming = supportsStreaming; + this.mangleImports = mangleImports; + this._runtimeRequirements = runtimeRequirements; + } -/***/ }), - -/***/ 82918: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + /** + * @returns {string} runtime code + */ + generate() { + const { chunkGraph, compilation, chunk, mangleImports } = this; + const { moduleGraph, outputOptions } = compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withHmr = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const wasmModules = getAllWasmModules(moduleGraph, chunkGraph, chunk); + const declarations = []; + const importObjects = wasmModules.map(module => { + return generateImportObject( + chunkGraph, + module, + this.mangleImports, + declarations, + chunk.runtime + ); + }); + const chunkModuleIdMap = chunkGraph.getChunkModuleIdMap(chunk, m => + m.type.startsWith("webassembly") + ); + const createImportObject = content => + mangleImports + ? `{ ${JSON.stringify(WebAssemblyUtils.MANGLED_MODULE)}: ${content} }` + : content; + const wasmModuleSrcPath = compilation.getPath( + JSON.stringify(outputOptions.webassemblyModuleFilename), + { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: length => + `" + ${RuntimeGlobals.getFullHash}}().slice(0, ${length}) + "`, + module: { + id: '" + wasmModuleId + "', + hash: `" + ${JSON.stringify( + chunkGraph.getChunkModuleRenderedHashMap(chunk, m => + m.type.startsWith("webassembly") + ) + )}[chunkId][wasmModuleId] + "`, + hashWithLength(length) { + return `" + ${JSON.stringify( + chunkGraph.getChunkModuleRenderedHashMap( + chunk, + m => m.type.startsWith("webassembly"), + length + ) + )}[chunkId][wasmModuleId] + "`; + } + }, + runtime: chunk.runtime + } + ); + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_wasm` + : undefined; -module.exports = function getPaths(path) { - const parts = path.split(/(.*?[\\/]+)/); - const paths = [path]; - const seqments = [parts[parts.length - 1]]; - let part = parts[parts.length - 1]; - path = path.substr(0, path.length - part.length - 1); - for (let i = parts.length - 2; i > 2; i -= 2) { - paths.push(path); - part = parts[i]; - path = path.substr(0, path.length - part.length) || "/"; - seqments.push(part.substr(0, part.length - 1)); + return Template.asString([ + "// object to store loaded and loading wasm modules", + `var installedWasmModules = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{};`, + "", + // This function is used to delay reading the installed wasm module promises + // by a microtask. Sorting them doesn't help because there are edge cases where + // sorting is not possible (modules splitted into different chunks). + // So we not even trying and solve this by a microtask delay. + "function promiseResolve() { return Promise.resolve(); }", + "", + Template.asString(declarations), + "var wasmImportObjects = {", + Template.indent(importObjects), + "};", + "", + `var wasmModuleMap = ${JSON.stringify( + chunkModuleIdMap, + undefined, + "\t" + )};`, + "", + "// object with all WebAssembly.instance exports", + `${RuntimeGlobals.wasmInstances} = {};`, + "", + "// Fetch + compile chunk loading for webassembly", + `${fn}.wasm = function(chunkId, promises) {`, + Template.indent([ + "", + `var wasmModules = wasmModuleMap[chunkId] || [];`, + "", + "wasmModules.forEach(function(wasmModuleId, idx) {", + Template.indent([ + "var installedWasmModuleData = installedWasmModules[wasmModuleId];", + "", + '// a Promise means "currently loading" or "already loaded".', + "if(installedWasmModuleData)", + Template.indent(["promises.push(installedWasmModuleData);"]), + "else {", + Template.indent([ + `var importObject = wasmImportObjects[wasmModuleId]();`, + `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, + "var promise;", + this.supportsStreaming + ? Template.asString([ + "if(importObject && typeof importObject.then === 'function' && typeof WebAssembly.compileStreaming === 'function') {", + Template.indent([ + "promise = Promise.all([WebAssembly.compileStreaming(req), importObject]).then(function(items) {", + Template.indent([ + `return WebAssembly.instantiate(items[0], ${createImportObject( + "items[1]" + )});` + ]), + "});" + ]), + "} else if(typeof WebAssembly.instantiateStreaming === 'function') {", + Template.indent([ + `promise = WebAssembly.instantiateStreaming(req, ${createImportObject( + "importObject" + )});` + ]) + ]) + : Template.asString([ + "if(importObject && typeof importObject.then === 'function') {", + Template.indent([ + "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", + "promise = Promise.all([", + Template.indent([ + "bytesPromise.then(function(bytes) { return WebAssembly.compile(bytes); }),", + "importObject" + ]), + "]).then(function(items) {", + Template.indent([ + `return WebAssembly.instantiate(items[0], ${createImportObject( + "items[1]" + )});` + ]), + "});" + ]) + ]), + "} else {", + Template.indent([ + "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", + "promise = bytesPromise.then(function(bytes) {", + Template.indent([ + `return WebAssembly.instantiate(bytes, ${createImportObject( + "importObject" + )});` + ]), + "});" + ]), + "}", + "promises.push(installedWasmModules[wasmModuleId] = promise.then(function(res) {", + Template.indent([ + `return ${RuntimeGlobals.wasmInstances}[wasmModuleId] = (res.instance || res).exports;` + ]), + "}));" + ]), + "}" + ]), + "});" + ]), + "};" + ]); } - part = parts[1]; - seqments.push(part); - paths.push(part); - return { - paths: paths, - seqments: seqments - }; -}; +} -module.exports.basename = function basename(path) { - const i = path.lastIndexOf("/"), - j = path.lastIndexOf("\\"); - const p = i < 0 ? j : j < 0 ? i : i < j ? j : i; - if (p < 0) return null; - const s = path.substr(p + 1); - return s; -}; +module.exports = WasmChunkLoadingRuntimeModule; /***/ }), -/***/ 9256: +/***/ 19810: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -137699,1883 +143460,1284 @@ module.exports.basename = function basename(path) { -const fs = __webpack_require__(90552); -const CachedInputFileSystem = __webpack_require__(52788); -const ResolverFactory = __webpack_require__(47716); +const formatLocation = __webpack_require__(16734); +const UnsupportedWebAssemblyFeatureError = __webpack_require__(78455); -/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").FileSystem} FileSystem */ -/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ -/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ -/** @typedef {import("./ResolverFactory").Plugin} Plugin */ -/** @typedef {import("./ResolverFactory").UserResolveOptions} ResolveOptions */ +/** @typedef {import("../Compiler")} Compiler */ -const nodeFileSystem = new CachedInputFileSystem(fs, 4000); +class WasmFinalizeExportsPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap("WasmFinalizeExportsPlugin", compilation => { + compilation.hooks.finishModules.tap( + "WasmFinalizeExportsPlugin", + modules => { + for (const module of modules) { + // 1. if a WebAssembly module + if (module.type.startsWith("webassembly") === true) { + const jsIncompatibleExports = + module.buildMeta.jsIncompatibleExports; -const nodeContext = { - environments: ["node+es3+es5+process+native"] -}; + if (jsIncompatibleExports === undefined) { + continue; + } -const asyncResolver = ResolverFactory.createResolver({ - conditionNames: ["node"], - extensions: [".js", ".json", ".node"], - fileSystem: nodeFileSystem -}); -function resolve(context, path, request, resolveContext, callback) { - if (typeof context === "string") { - callback = resolveContext; - resolveContext = request; - request = path; - path = context; - context = nodeContext; - } - if (typeof callback !== "function") { - callback = resolveContext; - } - asyncResolver.resolve(context, path, request, resolveContext, callback); -} + for (const connection of compilation.moduleGraph.getIncomingConnections( + module + )) { + // 2. is active and referenced by a non-WebAssembly module + if ( + connection.isTargetActive(undefined) && + connection.originModule.type.startsWith("webassembly") === + false + ) { + const referencedExports = + compilation.getDependencyReferencedExports( + connection.dependency, + undefined + ); -const syncResolver = ResolverFactory.createResolver({ - conditionNames: ["node"], - extensions: [".js", ".json", ".node"], - useSyncFileSystemCalls: true, - fileSystem: nodeFileSystem -}); -function resolveSync(context, path, request) { - if (typeof context === "string") { - request = path; - path = context; - context = nodeContext; + for (const info of referencedExports) { + const names = Array.isArray(info) ? info : info.name; + if (names.length === 0) continue; + const name = names[0]; + if (typeof name === "object") continue; + // 3. and uses a func with an incompatible JS signature + if ( + Object.prototype.hasOwnProperty.call( + jsIncompatibleExports, + name + ) + ) { + // 4. error + const error = new UnsupportedWebAssemblyFeatureError( + `Export "${name}" with ${jsIncompatibleExports[name]} can only be used for direct wasm to wasm dependencies\n` + + `It's used from ${connection.originModule.readableIdentifier( + compilation.requestShortener + )} at ${formatLocation(connection.dependency.loc)}.` + ); + error.module = module; + compilation.errors.push(error); + } + } + } + } + } + } + } + ); + }); } - return syncResolver.resolveSync(context, path, request); -} - -function create(options) { - options = { - fileSystem: nodeFileSystem, - ...options - }; - const resolver = ResolverFactory.createResolver(options); - return function (context, path, request, resolveContext, callback) { - if (typeof context === "string") { - callback = resolveContext; - resolveContext = request; - request = path; - path = context; - context = nodeContext; - } - if (typeof callback !== "function") { - callback = resolveContext; - } - resolver.resolve(context, path, request, resolveContext, callback); - }; -} - -function createSync(options) { - options = { - useSyncFileSystemCalls: true, - fileSystem: nodeFileSystem, - ...options - }; - const resolver = ResolverFactory.createResolver(options); - return function (context, path, request) { - if (typeof context === "string") { - request = path; - path = context; - context = nodeContext; - } - return resolver.resolveSync(context, path, request); - }; } -/** - * @template A - * @template B - * @param {A} obj input a - * @param {B} exports input b - * @returns {A & B} merged - */ -const mergeExports = (obj, exports) => { - const descriptors = Object.getOwnPropertyDescriptors(exports); - Object.defineProperties(obj, descriptors); - return /** @type {A & B} */ (Object.freeze(obj)); -}; - -module.exports = mergeExports(resolve, { - get sync() { - return resolveSync; - }, - create: mergeExports(create, { - get sync() { - return createSync; - } - }), - ResolverFactory, - CachedInputFileSystem, - get CloneBasenamePlugin() { - return __webpack_require__(22254); - }, - get LogInfoPlugin() { - return __webpack_require__(5049); - }, - get forEachBail() { - return __webpack_require__(78565); - } -}); +module.exports = WasmFinalizeExportsPlugin; /***/ }), -/***/ 55863: -/***/ (function(module) { +/***/ 47012: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -/** @typedef {string|(string|ConditionalMapping)[]} DirectMapping */ -/** @typedef {{[k: string]: MappingValue}} ConditionalMapping */ -/** @typedef {ConditionalMapping|DirectMapping|null} MappingValue */ -/** @typedef {Record|ConditionalMapping|DirectMapping} ExportsField */ -/** @typedef {Record} ImportsField */ - -/** - * @typedef {Object} PathTreeNode - * @property {Map|null} children - * @property {MappingValue} folder - * @property {Map|null} wildcards - * @property {Map} files - */ - -/** - * Processing exports/imports field - * @callback FieldProcessor - * @param {string} request request - * @param {Set} conditionNames condition names - * @returns {string[]} resolved paths - */ - -/* -Example exports field: -{ - ".": "./main.js", - "./feature": { - "browser": "./feature-browser.js", - "default": "./feature.js" - } -} -Terminology: - -Enhanced-resolve name keys ("." and "./feature") as exports field keys. - -If value is string or string[], mapping is called as a direct mapping -and value called as a direct export. - -If value is key-value object, mapping is called as a conditional mapping -and value called as a conditional export. - -Key in conditional mapping is called condition name. - -Conditional mapping nested in another conditional mapping is called nested mapping. - ----------- - -Example imports field: -{ - "#a": "./main.js", - "#moment": { - "browser": "./moment/index.js", - "default": "moment" - }, - "#moment/": { - "browser": "./moment/", - "default": "moment/" - } -} -Terminology: - -Enhanced-resolve name keys ("#a" and "#moment/", "#moment") as imports field keys. - -If value is string or string[], mapping is called as a direct mapping -and value called as a direct export. - -If value is key-value object, mapping is called as a conditional mapping -and value called as a conditional export. - -Key in conditional mapping is called condition name. +const { RawSource } = __webpack_require__(51255); +const Generator = __webpack_require__(93401); +const WebAssemblyUtils = __webpack_require__(18650); -Conditional mapping nested in another conditional mapping is called nested mapping. +const t = __webpack_require__(51826); +const { moduleContextFromModuleAST } = __webpack_require__(51826); +const { editWithAST, addWithAST } = __webpack_require__(87362); +const { decode } = __webpack_require__(73726); -*/ +const WebAssemblyExportImportedDependency = __webpack_require__(52204); -const slashCode = "/".charCodeAt(0); -const dotCode = ".".charCodeAt(0); -const hashCode = "#".charCodeAt(0); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./WebAssemblyUtils").UsedWasmDependency} UsedWasmDependency */ /** - * @param {ExportsField} exportsField the exports field - * @returns {FieldProcessor} process callback + * @typedef {(ArrayBuffer) => ArrayBuffer} ArrayBufferTransform */ -module.exports.processExportsField = function processExportsField( - exportsField -) { - return createFieldProcessor( - buildExportsFieldPathTree(exportsField), - assertExportsFieldRequest, - assertExportTarget - ); -}; /** - * @param {ImportsField} importsField the exports field - * @returns {FieldProcessor} process callback + * @template T + * @param {Function[]} fns transforms + * @returns {Function} composed transform */ -module.exports.processImportsField = function processImportsField( - importsField -) { - return createFieldProcessor( - buildImportsFieldPathTree(importsField), - assertImportsFieldRequest, - assertImportTarget +const compose = (...fns) => { + return fns.reduce( + (prevFn, nextFn) => { + return value => nextFn(prevFn(value)); + }, + value => value ); }; /** - * @param {PathTreeNode} treeRoot root - * @param {(s: string) => string} assertRequest assertRequest - * @param {(s: string, f: boolean) => void} assertTarget assertTarget - * @returns {FieldProcessor} field processor + * Removes the start instruction + * + * @param {Object} state unused state + * @returns {ArrayBufferTransform} transform */ -function createFieldProcessor(treeRoot, assertRequest, assertTarget) { - return function fieldProcessor(request, conditionNames) { - request = assertRequest(request); - - const match = findMatch(request, treeRoot); - - if (match === null) return []; - - const [mapping, remainRequestIndex] = match; - - /** @type {DirectMapping|null} */ - let direct = null; - - if (isConditionalMapping(mapping)) { - direct = conditionalMapping( - /** @type {ConditionalMapping} */ (mapping), - conditionNames - ); - - // matching not found - if (direct === null) return []; - } else { - direct = /** @type {DirectMapping} */ (mapping); +const removeStartFunc = state => bin => { + return editWithAST(state.ast, bin, { + Start(path) { + path.remove(); } - - const remainingRequest = - remainRequestIndex === request.length + 1 - ? undefined - : remainRequestIndex < 0 - ? request.slice(-remainRequestIndex - 1) - : request.slice(remainRequestIndex); - - return directMapping( - remainingRequest, - remainRequestIndex < 0, - direct, - conditionNames, - assertTarget - ); - }; -} - -/** - * @param {string} request request - * @returns {string} updated request - */ -function assertExportsFieldRequest(request) { - if (request.charCodeAt(0) !== dotCode) { - throw new Error('Request should be relative path and start with "."'); - } - if (request.length === 1) return ""; - if (request.charCodeAt(1) !== slashCode) { - throw new Error('Request should be relative path and start with "./"'); - } - if (request.charCodeAt(request.length - 1) === slashCode) { - throw new Error("Only requesting file allowed"); - } - - return request.slice(2); -} - -/** - * @param {string} request request - * @returns {string} updated request - */ -function assertImportsFieldRequest(request) { - if (request.charCodeAt(0) !== hashCode) { - throw new Error('Request should start with "#"'); - } - if (request.length === 1) { - throw new Error("Request should have at least 2 characters"); - } - if (request.charCodeAt(1) === slashCode) { - throw new Error('Request should not start with "#/"'); - } - if (request.charCodeAt(request.length - 1) === slashCode) { - throw new Error("Only requesting file allowed"); - } - - return request.slice(1); -} + }); +}; /** - * @param {string} exp export target - * @param {boolean} expectFolder is folder expected + * Get imported globals + * + * @param {Object} ast Module's AST + * @returns {Array} - nodes */ -function assertExportTarget(exp, expectFolder) { - if ( - exp.charCodeAt(0) === slashCode || - (exp.charCodeAt(0) === dotCode && exp.charCodeAt(1) !== slashCode) - ) { - throw new Error( - `Export should be relative path and start with "./", got ${JSON.stringify( - exp - )}.` - ); - } - - const isFolder = exp.charCodeAt(exp.length - 1) === slashCode; - - if (isFolder !== expectFolder) { - throw new Error( - expectFolder - ? `Expecting folder to folder mapping. ${JSON.stringify( - exp - )} should end with "/"` - : `Expecting file to file mapping. ${JSON.stringify( - exp - )} should not end with "/"` - ); - } -} +const getImportedGlobals = ast => { + const importedGlobals = []; -/** - * @param {string} imp import target - * @param {boolean} expectFolder is folder expected - */ -function assertImportTarget(imp, expectFolder) { - const isFolder = imp.charCodeAt(imp.length - 1) === slashCode; + t.traverse(ast, { + ModuleImport({ node }) { + if (t.isGlobalType(node.descr)) { + importedGlobals.push(node); + } + } + }); - if (isFolder !== expectFolder) { - throw new Error( - expectFolder - ? `Expecting folder to folder mapping. ${JSON.stringify( - imp - )} should end with "/"` - : `Expecting file to file mapping. ${JSON.stringify( - imp - )} should not end with "/"` - ); - } -} + return importedGlobals; +}; /** - * Trying to match request to field - * @param {string} request request - * @param {PathTreeNode} treeRoot path tree root - * @returns {[MappingValue, number]|null} match or null, number is negative and one less when it's a folder mapping, number is request.length + 1 for direct mappings + * Get the count for imported func + * + * @param {Object} ast Module's AST + * @returns {Number} - count */ -function findMatch(request, treeRoot) { - if (request.length === 0) { - const value = treeRoot.files.get(""); - - return value ? [value, 1] : null; - } - - if ( - treeRoot.children === null && - treeRoot.folder === null && - treeRoot.wildcards === null - ) { - const value = treeRoot.files.get(request); - - return value ? [value, request.length + 1] : null; - } - - let node = treeRoot; - let lastNonSlashIndex = 0; - let slashIndex = request.indexOf("/", 0); - - /** @type {[MappingValue, number]|null} */ - let lastFolderMatch = null; - - const applyFolderMapping = () => { - const folderMapping = node.folder; - if (folderMapping) { - if (lastFolderMatch) { - lastFolderMatch[0] = folderMapping; - lastFolderMatch[1] = -lastNonSlashIndex - 1; - } else { - lastFolderMatch = [folderMapping, -lastNonSlashIndex - 1]; - } - } - }; +const getCountImportedFunc = ast => { + let count = 0; - const applyWildcardMappings = (wildcardMappings, remainingRequest) => { - if (wildcardMappings) { - for (const [key, target] of wildcardMappings) { - if (remainingRequest.startsWith(key)) { - if (!lastFolderMatch) { - lastFolderMatch = [target, lastNonSlashIndex + key.length]; - } else if (lastFolderMatch[1] < lastNonSlashIndex + key.length) { - lastFolderMatch[0] = target; - lastFolderMatch[1] = lastNonSlashIndex + key.length; - } - } + t.traverse(ast, { + ModuleImport({ node }) { + if (t.isFuncImportDescr(node.descr)) { + count++; } } - }; - - while (slashIndex !== -1) { - applyFolderMapping(); - - const wildcardMappings = node.wildcards; - - if (!wildcardMappings && node.children === null) return lastFolderMatch; - - const folder = request.slice(lastNonSlashIndex, slashIndex); - - applyWildcardMappings(wildcardMappings, folder); - - if (node.children === null) return lastFolderMatch; - - const newNode = node.children.get(folder); - - if (!newNode) { - return lastFolderMatch; - } - - node = newNode; - lastNonSlashIndex = slashIndex + 1; - slashIndex = request.indexOf("/", lastNonSlashIndex); - } - - const remainingRequest = - lastNonSlashIndex > 0 ? request.slice(lastNonSlashIndex) : request; - - const value = node.files.get(remainingRequest); - - if (value) { - return [value, request.length + 1]; - } - - applyFolderMapping(); - - applyWildcardMappings(node.wildcards, remainingRequest); - - return lastFolderMatch; -} + }); -/** - * @param {ConditionalMapping|DirectMapping|null} mapping mapping - * @returns {boolean} is conditional mapping - */ -function isConditionalMapping(mapping) { - return ( - mapping !== null && typeof mapping === "object" && !Array.isArray(mapping) - ); -} + return count; +}; /** - * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings - * @param {boolean} subpathMapping true, for subpath mappings - * @param {DirectMapping|null} mappingTarget direct export - * @param {Set} conditionNames condition names - * @param {(d: string, f: boolean) => void} assert asserting direct value - * @returns {string[]} mapping result + * Get next type index + * + * @param {Object} ast Module's AST + * @returns {t.Index} - index */ -function directMapping( - remainingRequest, - subpathMapping, - mappingTarget, - conditionNames, - assert -) { - if (mappingTarget === null) return []; - - if (typeof mappingTarget === "string") { - return [ - targetMapping(remainingRequest, subpathMapping, mappingTarget, assert) - ]; - } - - const targets = []; - - for (const exp of mappingTarget) { - if (typeof exp === "string") { - targets.push( - targetMapping(remainingRequest, subpathMapping, exp, assert) - ); - continue; - } +const getNextTypeIndex = ast => { + const typeSectionMetadata = t.getSectionMetadata(ast, "type"); - const mapping = conditionalMapping(exp, conditionNames); - if (!mapping) continue; - const innerExports = directMapping( - remainingRequest, - subpathMapping, - mapping, - conditionNames, - assert - ); - for (const innerExport of innerExports) { - targets.push(innerExport); - } + if (typeSectionMetadata === undefined) { + return t.indexLiteral(0); } - return targets; -} - -/** - * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings - * @param {boolean} subpathMapping true, for subpath mappings - * @param {string} mappingTarget direct export - * @param {(d: string, f: boolean) => void} assert asserting direct value - * @returns {string} mapping result - */ -function targetMapping( - remainingRequest, - subpathMapping, - mappingTarget, - assert -) { - if (remainingRequest === undefined) { - assert(mappingTarget, false); - return mappingTarget; - } - if (subpathMapping) { - assert(mappingTarget, true); - return mappingTarget + remainingRequest; - } - assert(mappingTarget, false); - return mappingTarget.replace(/\*/g, remainingRequest.replace(/\$/g, "$$")); -} + return t.indexLiteral(typeSectionMetadata.vectorOfSize.value); +}; /** - * @param {ConditionalMapping} conditionalMapping_ conditional mapping - * @param {Set} conditionNames condition names - * @returns {DirectMapping|null} direct mapping if found + * Get next func index + * + * The Func section metadata provide informations for implemented funcs + * in order to have the correct index we shift the index by number of external + * functions. + * + * @param {Object} ast Module's AST + * @param {Number} countImportedFunc number of imported funcs + * @returns {t.Index} - index */ -function conditionalMapping(conditionalMapping_, conditionNames) { - /** @type {[ConditionalMapping, string[], number][]} */ - let lookup = [[conditionalMapping_, Object.keys(conditionalMapping_), 0]]; - - loop: while (lookup.length > 0) { - const [mapping, conditions, j] = lookup[lookup.length - 1]; - const last = conditions.length - 1; - - for (let i = j; i < conditions.length; i++) { - const condition = conditions[i]; - - // assert default. Could be last only - if (i !== last) { - if (condition === "default") { - throw new Error("Default condition should be last one"); - } - } else if (condition === "default") { - const innerMapping = mapping[condition]; - // is nested - if (isConditionalMapping(innerMapping)) { - const conditionalMapping = /** @type {ConditionalMapping} */ (innerMapping); - lookup[lookup.length - 1][2] = i + 1; - lookup.push([conditionalMapping, Object.keys(conditionalMapping), 0]); - continue loop; - } - - return /** @type {DirectMapping} */ (innerMapping); - } - - if (conditionNames.has(condition)) { - const innerMapping = mapping[condition]; - // is nested - if (isConditionalMapping(innerMapping)) { - const conditionalMapping = /** @type {ConditionalMapping} */ (innerMapping); - lookup[lookup.length - 1][2] = i + 1; - lookup.push([conditionalMapping, Object.keys(conditionalMapping), 0]); - continue loop; - } - - return /** @type {DirectMapping} */ (innerMapping); - } - } +const getNextFuncIndex = (ast, countImportedFunc) => { + const funcSectionMetadata = t.getSectionMetadata(ast, "func"); - lookup.pop(); + if (funcSectionMetadata === undefined) { + return t.indexLiteral(0 + countImportedFunc); } - return null; -} + const vectorOfSize = funcSectionMetadata.vectorOfSize.value; -/** - * Internal helper to create path tree node - * to ensure that each node gets the same hidden class - * @returns {PathTreeNode} node - */ -function createNode() { - return { - children: null, - folder: null, - wildcards: null, - files: new Map() - }; -} + return t.indexLiteral(vectorOfSize + countImportedFunc); +}; /** - * Internal helper for building path tree - * @param {PathTreeNode} root root - * @param {string} path path - * @param {MappingValue} target target + * Creates an init instruction for a global type + * @param {t.GlobalType} globalType the global type + * @returns {t.Instruction} init expression */ -function walkPath(root, path, target) { - if (path.length === 0) { - root.folder = target; - return; - } - - let node = root; - // Typical path tree can looks like - // root - // - files: ["a.js", "b.js"] - // - children: - // node1: - // - files: ["a.js", "b.js"] - let lastNonSlashIndex = 0; - let slashIndex = path.indexOf("/", 0); - - while (slashIndex !== -1) { - const folder = path.slice(lastNonSlashIndex, slashIndex); - let newNode; - - if (node.children === null) { - newNode = createNode(); - node.children = new Map(); - node.children.set(folder, newNode); - } else { - newNode = node.children.get(folder); - - if (!newNode) { - newNode = createNode(); - node.children.set(folder, newNode); - } - } - - node = newNode; - lastNonSlashIndex = slashIndex + 1; - slashIndex = path.indexOf("/", lastNonSlashIndex); - } - - if (lastNonSlashIndex >= path.length) { - node.folder = target; +const createDefaultInitForGlobal = globalType => { + if (globalType.valtype[0] === "i") { + // create NumberLiteral global initializer + return t.objectInstruction("const", globalType.valtype, [ + t.numberLiteralFromRaw(66) + ]); + } else if (globalType.valtype[0] === "f") { + // create FloatLiteral global initializer + return t.objectInstruction("const", globalType.valtype, [ + t.floatLiteral(66, false, false, "66") + ]); } else { - const file = lastNonSlashIndex > 0 ? path.slice(lastNonSlashIndex) : path; - if (file.endsWith("*")) { - if (node.wildcards === null) node.wildcards = new Map(); - node.wildcards.set(file.slice(0, -1), target); - } else { - node.files.set(file, target); - } + throw new Error("unknown type: " + globalType.valtype); } -} +}; /** - * @param {ExportsField} field exports field - * @returns {PathTreeNode} tree root + * Rewrite the import globals: + * - removes the ModuleImport instruction + * - injects at the same offset a mutable global of the same type + * + * Since the imported globals are before the other global declarations, our + * indices will be preserved. + * + * Note that globals will become mutable. + * + * @param {Object} state unused state + * @returns {ArrayBufferTransform} transform */ -function buildExportsFieldPathTree(field) { - const root = createNode(); - - // handle syntax sugar, if exports field is direct mapping for "." - if (typeof field === "string") { - root.files.set("", field); - - return root; - } else if (Array.isArray(field)) { - root.files.set("", field.slice()); +const rewriteImportedGlobals = state => bin => { + const additionalInitCode = state.additionalInitCode; + const newGlobals = []; - return root; - } + bin = editWithAST(state.ast, bin, { + ModuleImport(path) { + if (t.isGlobalType(path.node.descr)) { + const globalType = path.node.descr; - const keys = Object.keys(field); + globalType.mutability = "var"; - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; + const init = [ + createDefaultInitForGlobal(globalType), + t.instruction("end") + ]; - if (key.charCodeAt(0) !== dotCode) { - // handle syntax sugar, if exports field is conditional mapping for "." - if (i === 0) { - while (i < keys.length) { - const charCode = keys[i].charCodeAt(0); - if (charCode === dotCode || charCode === slashCode) { - throw new Error( - `Exports field key should be relative path and start with "." (key: ${JSON.stringify( - key - )})` - ); - } - i++; - } + newGlobals.push(t.global(globalType, init)); - root.files.set("", field); - return root; + path.remove(); } + }, - throw new Error( - `Exports field key should be relative path and start with "." (key: ${JSON.stringify( - key - )})` - ); - } - - if (key.length === 1) { - root.files.set("", field[key]); - continue; - } - - if (key.charCodeAt(1) !== slashCode) { - throw new Error( - `Exports field key should be relative path and start with "./" (key: ${JSON.stringify( - key - )})` - ); - } - - walkPath(root, key.slice(2), field[key]); - } - - return root; -} + // in order to preserve non-imported global's order we need to re-inject + // those as well + Global(path) { + const { node } = path; + const [init] = node.init; -/** - * @param {ImportsField} field imports field - * @returns {PathTreeNode} root - */ -function buildImportsFieldPathTree(field) { - const root = createNode(); + if (init.id === "get_global") { + node.globalType.mutability = "var"; - const keys = Object.keys(field); + const initialGlobalIdx = init.args[0]; - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; + node.init = [ + createDefaultInitForGlobal(node.globalType), + t.instruction("end") + ]; - if (key.charCodeAt(0) !== hashCode) { - throw new Error( - `Imports field key should start with "#" (key: ${JSON.stringify(key)})` - ); - } + additionalInitCode.push( + /** + * get_global in global initializer only works for imported globals. + * They have the same indices as the init params, so use the + * same index. + */ + t.instruction("get_local", [initialGlobalIdx]), + t.instruction("set_global", [t.indexLiteral(newGlobals.length)]) + ); + } - if (key.length === 1) { - throw new Error( - `Imports field key should have at least 2 characters (key: ${JSON.stringify( - key - )})` - ); - } + newGlobals.push(node); - if (key.charCodeAt(1) === slashCode) { - throw new Error( - `Imports field key should not start with "#/" (key: ${JSON.stringify( - key - )})` - ); + path.remove(); } + }); - walkPath(root, key.slice(1), field[key]); - } - - return root; -} - - -/***/ }), - -/***/ 71053: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ + // Add global declaration instructions + return addWithAST(state.ast, bin, newGlobals); +}; +/** + * Rewrite the export names + * @param {Object} state state + * @param {Object} state.ast Module's ast + * @param {Module} state.module Module + * @param {ModuleGraph} state.moduleGraph module graph + * @param {Set} state.externalExports Module + * @param {RuntimeSpec} state.runtime runtime + * @returns {ArrayBufferTransform} transform + */ +const rewriteExportNames = + ({ ast, moduleGraph, module, externalExports, runtime }) => + bin => { + return editWithAST(ast, bin, { + ModuleExport(path) { + const isExternal = externalExports.has(path.node.name); + if (isExternal) { + path.remove(); + return; + } + const usedName = moduleGraph + .getExportsInfo(module) + .getUsedName(path.node.name, runtime); + if (!usedName) { + path.remove(); + return; + } + path.node.name = usedName; + } + }); + }; +/** + * Mangle import names and modules + * @param {Object} state state + * @param {Object} state.ast Module's ast + * @param {Map} state.usedDependencyMap mappings to mangle names + * @returns {ArrayBufferTransform} transform + */ +const rewriteImports = + ({ ast, usedDependencyMap }) => + bin => { + return editWithAST(ast, bin, { + ModuleImport(path) { + const result = usedDependencyMap.get( + path.node.module + ":" + path.node.name + ); -const PATH_QUERY_FRAGMENT_REGEXP = /^(#?(?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; + if (result !== undefined) { + path.node.module = result.module; + path.node.name = result.name; + } + } + }); + }; /** - * @param {string} identifier identifier - * @returns {[string, string, string]|null} parsed identifier + * Add an init function. + * + * The init function fills the globals given input arguments. + * + * @param {Object} state transformation state + * @param {Object} state.ast Module's ast + * @param {t.Identifier} state.initFuncId identifier of the init function + * @param {t.Index} state.startAtFuncOffset index of the start function + * @param {t.ModuleImport[]} state.importedGlobals list of imported globals + * @param {t.Instruction[]} state.additionalInitCode list of addition instructions for the init function + * @param {t.Index} state.nextFuncIndex index of the next function + * @param {t.Index} state.nextTypeIndex index of the next type + * @returns {ArrayBufferTransform} transform */ -function parseIdentifier(identifier) { - const match = PATH_QUERY_FRAGMENT_REGEXP.exec(identifier); - - if (!match) return null; +const addInitFunction = + ({ + ast, + initFuncId, + startAtFuncOffset, + importedGlobals, + additionalInitCode, + nextFuncIndex, + nextTypeIndex + }) => + bin => { + const funcParams = importedGlobals.map(importedGlobal => { + // used for debugging + const id = t.identifier( + `${importedGlobal.module}.${importedGlobal.name}` + ); - return [ - match[1].replace(/\0(.)/g, "$1"), - match[2] ? match[2].replace(/\0(.)/g, "$1") : "", - match[3] || "" - ]; -} + return t.funcParam(importedGlobal.descr.valtype, id); + }); -module.exports.parseIdentifier = parseIdentifier; + const funcBody = []; + importedGlobals.forEach((importedGlobal, index) => { + const args = [t.indexLiteral(index)]; + const body = [ + t.instruction("get_local", args), + t.instruction("set_global", args) + ]; + funcBody.push(...body); + }); -/***/ }), + if (typeof startAtFuncOffset === "number") { + funcBody.push( + t.callInstruction(t.numberLiteralFromRaw(startAtFuncOffset)) + ); + } -/***/ 67079: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + for (const instr of additionalInitCode) { + funcBody.push(instr); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + funcBody.push(t.instruction("end")); + const funcResults = []; + // Code section + const funcSignature = t.signature(funcParams, funcResults); + const func = t.func(initFuncId, funcSignature, funcBody); -const path = __webpack_require__(71017); + // Type section + const functype = t.typeInstruction(undefined, funcSignature); -const CHAR_HASH = "#".charCodeAt(0); -const CHAR_SLASH = "/".charCodeAt(0); -const CHAR_BACKSLASH = "\\".charCodeAt(0); -const CHAR_A = "A".charCodeAt(0); -const CHAR_Z = "Z".charCodeAt(0); -const CHAR_LOWER_A = "a".charCodeAt(0); -const CHAR_LOWER_Z = "z".charCodeAt(0); -const CHAR_DOT = ".".charCodeAt(0); -const CHAR_COLON = ":".charCodeAt(0); + // Func section + const funcindex = t.indexInFuncSection(nextTypeIndex); -const posixNormalize = path.posix.normalize; -const winNormalize = path.win32.normalize; + // Export section + const moduleExport = t.moduleExport( + initFuncId.value, + t.moduleExportDescr("Func", nextFuncIndex) + ); -/** - * @enum {number} - */ -const PathType = Object.freeze({ - Empty: 0, - Normal: 1, - Relative: 2, - AbsoluteWin: 3, - AbsolutePosix: 4, - Internal: 5 -}); -exports.PathType = PathType; + return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]); + }; /** - * @param {string} p a path - * @returns {PathType} type of path + * Extract mangle mappings from module + * @param {ModuleGraph} moduleGraph module graph + * @param {Module} module current module + * @param {boolean} mangle mangle imports + * @returns {Map} mappings to mangled names */ -const getType = p => { - switch (p.length) { - case 0: - return PathType.Empty; - case 1: { - const c0 = p.charCodeAt(0); - switch (c0) { - case CHAR_DOT: - return PathType.Relative; - case CHAR_SLASH: - return PathType.AbsolutePosix; - case CHAR_HASH: - return PathType.Internal; - } - return PathType.Normal; - } - case 2: { - const c0 = p.charCodeAt(0); - switch (c0) { - case CHAR_DOT: { - const c1 = p.charCodeAt(1); - switch (c1) { - case CHAR_DOT: - case CHAR_SLASH: - return PathType.Relative; - } - return PathType.Normal; - } - case CHAR_SLASH: - return PathType.AbsolutePosix; - case CHAR_HASH: - return PathType.Internal; - } - const c1 = p.charCodeAt(1); - if (c1 === CHAR_COLON) { - if ( - (c0 >= CHAR_A && c0 <= CHAR_Z) || - (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z) - ) { - return PathType.AbsoluteWin; - } - } - return PathType.Normal; - } - } - const c0 = p.charCodeAt(0); - switch (c0) { - case CHAR_DOT: { - const c1 = p.charCodeAt(1); - switch (c1) { - case CHAR_SLASH: - return PathType.Relative; - case CHAR_DOT: { - const c2 = p.charCodeAt(2); - if (c2 === CHAR_SLASH) return PathType.Relative; - return PathType.Normal; - } - } - return PathType.Normal; - } - case CHAR_SLASH: - return PathType.AbsolutePosix; - case CHAR_HASH: - return PathType.Internal; - } - const c1 = p.charCodeAt(1); - if (c1 === CHAR_COLON) { - const c2 = p.charCodeAt(2); - if ( - (c2 === CHAR_BACKSLASH || c2 === CHAR_SLASH) && - ((c0 >= CHAR_A && c0 <= CHAR_Z) || - (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z)) - ) { - return PathType.AbsoluteWin; - } +const getUsedDependencyMap = (moduleGraph, module, mangle) => { + /** @type {Map} */ + const map = new Map(); + for (const usedDep of WebAssemblyUtils.getUsedDependencies( + moduleGraph, + module, + mangle + )) { + const dep = usedDep.dependency; + const request = dep.request; + const exportName = dep.name; + map.set(request + ":" + exportName, usedDep); } - return PathType.Normal; + return map; }; -exports.getType = getType; -/** - * @param {string} p a path - * @returns {string} the normalized path - */ -const normalize = p => { - switch (getType(p)) { - case PathType.Empty: - return p; - case PathType.AbsoluteWin: - return winNormalize(p); - case PathType.Relative: { - const r = posixNormalize(p); - return getType(r) === PathType.Relative ? r : `./${r}`; - } - } - return posixNormalize(p); -}; -exports.normalize = normalize; +const TYPES = new Set(["webassembly"]); -/** - * @param {string} rootPath the root path - * @param {string | undefined} request the request path - * @returns {string} the joined path - */ -const join = (rootPath, request) => { - if (!request) return normalize(rootPath); - const requestType = getType(request); - switch (requestType) { - case PathType.AbsolutePosix: - return posixNormalize(request); - case PathType.AbsoluteWin: - return winNormalize(request); +class WebAssemblyGenerator extends Generator { + constructor(options) { + super(); + this.options = options; } - switch (getType(rootPath)) { - case PathType.Normal: - case PathType.Relative: - case PathType.AbsolutePosix: - return posixNormalize(`${rootPath}/${request}`); - case PathType.AbsoluteWin: - return winNormalize(`${rootPath}\\${request}`); + + /** + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) + */ + getTypes(module) { + return TYPES; } - switch (requestType) { - case PathType.Empty: - return rootPath; - case PathType.Relative: { - const r = posixNormalize(rootPath); - return getType(r) === PathType.Relative ? r : `./${r}`; + + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + const originalSource = module.originalSource(); + if (!originalSource) { + return 0; } + return originalSource.size(); } - return posixNormalize(rootPath); -}; -exports.join = join; -const joinCache = new Map(); + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code + */ + generate(module, { moduleGraph, runtime }) { + const bin = module.originalSource().source(); -/** - * @param {string} rootPath the root path - * @param {string | undefined} request the request path - * @returns {string} the joined path - */ -const cachedJoin = (rootPath, request) => { - let cacheEntry; - let cache = joinCache.get(rootPath); - if (cache === undefined) { - joinCache.set(rootPath, (cache = new Map())); - } else { - cacheEntry = cache.get(request); - if (cacheEntry !== undefined) return cacheEntry; - } - cacheEntry = join(rootPath, request); - cache.set(request, cacheEntry); - return cacheEntry; -}; -exports.cachedJoin = cachedJoin; + const initFuncId = t.identifier(""); -const checkExportsFieldTarget = relativePath => { - let lastNonSlashIndex = 2; - let slashIndex = relativePath.indexOf("/", 2); - let cd = 0; + // parse it + const ast = decode(bin, { + ignoreDataSection: true, + ignoreCodeSection: true, + ignoreCustomNameSection: true + }); - while (slashIndex !== -1) { - const folder = relativePath.slice(lastNonSlashIndex, slashIndex); + const moduleContext = moduleContextFromModuleAST(ast.body[0]); - switch (folder) { - case "..": { - cd--; - if (cd < 0) - return new Error( - `Trying to access out of package scope. Requesting ${relativePath}` + const importedGlobals = getImportedGlobals(ast); + const countImportedFunc = getCountImportedFunc(ast); + const startAtFuncOffset = moduleContext.getStart(); + const nextFuncIndex = getNextFuncIndex(ast, countImportedFunc); + const nextTypeIndex = getNextTypeIndex(ast); + + const usedDependencyMap = getUsedDependencyMap( + moduleGraph, + module, + this.options.mangleImports + ); + const externalExports = new Set( + module.dependencies + .filter(d => d instanceof WebAssemblyExportImportedDependency) + .map(d => { + const wasmDep = /** @type {WebAssemblyExportImportedDependency} */ ( + d ); - break; - } - default: - cd++; - break; - } + return wasmDep.exportName; + }) + ); - lastNonSlashIndex = slashIndex + 1; - slashIndex = relativePath.indexOf("/", lastNonSlashIndex); - } -}; -exports.checkExportsFieldTarget = checkExportsFieldTarget; + /** @type {t.Instruction[]} */ + const additionalInitCode = []; + + const transform = compose( + rewriteExportNames({ + ast, + moduleGraph, + module, + externalExports, + runtime + }), + removeStartFunc({ ast }), -/***/ }), + rewriteImportedGlobals({ ast, additionalInitCode }), -/***/ 39102: -/***/ (function(module) { + rewriteImports({ + ast, + usedDependencyMap + }), -"use strict"; + addInitFunction({ + ast, + initFuncId, + importedGlobals, + additionalInitCode, + startAtFuncOffset, + nextFuncIndex, + nextTypeIndex + }) + ); + const newBin = transform(bin); -class LoadingLoaderError extends Error { - constructor(message) { - super(message); - this.name = "LoaderRunnerError"; - Error.captureStackTrace(this, this.constructor); + const newBuf = Buffer.from(newBin); + + return new RawSource(newBuf); } } -module.exports = LoadingLoaderError; +module.exports = WebAssemblyGenerator; /***/ }), -/***/ 8255: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 47342: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +"use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -var fs = __webpack_require__(57147); -var readFile = fs.readFile.bind(fs); -var loadLoader = __webpack_require__(44690); -function utf8BufferToString(buf) { - var str = buf.toString("utf-8"); - if(str.charCodeAt(0) === 0xFEFF) { - return str.substr(1); - } else { - return str; - } -} -const PATH_QUERY_FRAGMENT_REGEXP = /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; + +const WebpackError = __webpack_require__(53799); + +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RequestShortener")} RequestShortener */ /** - * @param {string} str the path with query and fragment - * @returns {{ path: string, query: string, fragment: string }} parsed parts + * @param {Module} module module to get chains from + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {RequestShortener} requestShortener to make readable identifiers + * @returns {string[]} all chains to the module */ -function parsePathQueryFragment(str) { - var match = PATH_QUERY_FRAGMENT_REGEXP.exec(str); - return { - path: match[1].replace(/\0(.)/g, "$1"), - query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "", - fragment: match[3] || "" - }; -} - -function dirname(path) { - if(path === "/") return "/"; - var i = path.lastIndexOf("/"); - var j = path.lastIndexOf("\\"); - var i2 = path.indexOf("/"); - var j2 = path.indexOf("\\"); - var idx = i > j ? i : j; - var idx2 = i > j ? i2 : j2; - if(idx < 0) return path; - if(idx === idx2) return path.substr(0, idx + 1); - return path.substr(0, idx); -} +const getInitialModuleChains = ( + module, + moduleGraph, + chunkGraph, + requestShortener +) => { + const queue = [ + { head: module, message: module.readableIdentifier(requestShortener) } + ]; + /** @type {Set} */ + const results = new Set(); + /** @type {Set} */ + const incompleteResults = new Set(); + /** @type {Set} */ + const visitedModules = new Set(); -function createLoaderObject(loader) { - var obj = { - path: null, - query: null, - fragment: null, - options: null, - ident: null, - normal: null, - pitch: null, - raw: null, - data: null, - pitchExecuted: false, - normalExecuted: false - }; - Object.defineProperty(obj, "request", { - enumerable: true, - get: function() { - return obj.path.replace(/#/g, "\0#") + obj.query.replace(/#/g, "\0#") + obj.fragment; - }, - set: function(value) { - if(typeof value === "string") { - var splittedRequest = parsePathQueryFragment(value); - obj.path = splittedRequest.path; - obj.query = splittedRequest.query; - obj.fragment = splittedRequest.fragment; - obj.options = undefined; - obj.ident = undefined; + for (const chain of queue) { + const { head, message } = chain; + let final = true; + /** @type {Set} */ + const alreadyReferencedModules = new Set(); + for (const connection of moduleGraph.getIncomingConnections(head)) { + const newHead = connection.originModule; + if (newHead) { + if (!chunkGraph.getModuleChunks(newHead).some(c => c.canBeInitial())) + continue; + final = false; + if (alreadyReferencedModules.has(newHead)) continue; + alreadyReferencedModules.add(newHead); + const moduleName = newHead.readableIdentifier(requestShortener); + const detail = connection.explanation + ? ` (${connection.explanation})` + : ""; + const newMessage = `${moduleName}${detail} --> ${message}`; + if (visitedModules.has(newHead)) { + incompleteResults.add(`... --> ${newMessage}`); + continue; + } + visitedModules.add(newHead); + queue.push({ + head: newHead, + message: newMessage + }); } else { - if(!value.loader) - throw new Error("request should be a string or object with loader and options (" + JSON.stringify(value) + ")"); - obj.path = value.loader; - obj.fragment = value.fragment || ""; - obj.type = value.type; - obj.options = value.options; - obj.ident = value.ident; - if(obj.options === null) - obj.query = ""; - else if(obj.options === undefined) - obj.query = ""; - else if(typeof obj.options === "string") - obj.query = "?" + obj.options; - else if(obj.ident) - obj.query = "??" + obj.ident; - else if(typeof obj.options === "object" && obj.options.ident) - obj.query = "??" + obj.options.ident; - else - obj.query = "?" + JSON.stringify(obj.options); - } - } - }); - obj.request = loader; - if(Object.preventExtensions) { - Object.preventExtensions(obj); - } - return obj; -} - -function runSyncOrAsync(fn, context, args, callback) { - var isSync = true; - var isDone = false; - var isError = false; // internal error - var reportedError = false; - context.async = function async() { - if(isDone) { - if(reportedError) return; // ignore - throw new Error("async(): The callback was already called."); - } - isSync = false; - return innerCallback; - }; - var innerCallback = context.callback = function() { - if(isDone) { - if(reportedError) return; // ignore - throw new Error("callback(): The callback was already called."); - } - isDone = true; - isSync = false; - try { - callback.apply(null, arguments); - } catch(e) { - isError = true; - throw e; - } - }; - try { - var result = (function LOADER_EXECUTION() { - return fn.apply(context, args); - }()); - if(isSync) { - isDone = true; - if(result === undefined) - return callback(); - if(result && typeof result === "object" && typeof result.then === "function") { - return result.then(function(r) { - callback(null, r); - }, callback); + final = false; + const newMessage = connection.explanation + ? `(${connection.explanation}) --> ${message}` + : message; + results.add(newMessage); } - return callback(null, result); } - } catch(e) { - if(isError) throw e; - if(isDone) { - // loader is already "done", so we cannot use the callback function - // for better debugging we print the error on the console - if(typeof e === "object" && e.stack) console.error(e.stack); - else console.error(e); - return; + if (final) { + results.add(message); } - isDone = true; - reportedError = true; - callback(e); } - -} - -function convertArgs(args, raw) { - if(!raw && Buffer.isBuffer(args[0])) - args[0] = utf8BufferToString(args[0]); - else if(raw && typeof args[0] === "string") - args[0] = Buffer.from(args[0], "utf-8"); -} - -function iteratePitchingLoaders(options, loaderContext, callback) { - // abort after last loader - if(loaderContext.loaderIndex >= loaderContext.loaders.length) - return processResource(options, loaderContext, callback); - - var currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex]; - - // iterate - if(currentLoaderObject.pitchExecuted) { - loaderContext.loaderIndex++; - return iteratePitchingLoaders(options, loaderContext, callback); + for (const result of incompleteResults) { + results.add(result); } + return Array.from(results); +}; - // load loader module - loadLoader(currentLoaderObject, function(err) { - if(err) { - loaderContext.cacheable(false); - return callback(err); - } - var fn = currentLoaderObject.pitch; - currentLoaderObject.pitchExecuted = true; - if(!fn) return iteratePitchingLoaders(options, loaderContext, callback); - - runSyncOrAsync( - fn, - loaderContext, [loaderContext.remainingRequest, loaderContext.previousRequest, currentLoaderObject.data = {}], - function(err) { - if(err) return callback(err); - var args = Array.prototype.slice.call(arguments, 1); - // Determine whether to continue the pitching process based on - // argument values (as opposed to argument presence) in order - // to support synchronous and asynchronous usages. - var hasArg = args.some(function(value) { - return value !== undefined; - }); - if(hasArg) { - loaderContext.loaderIndex--; - iterateNormalLoaders(options, loaderContext, args, callback); - } else { - iteratePitchingLoaders(options, loaderContext, callback); - } - } +module.exports = class WebAssemblyInInitialChunkError extends WebpackError { + /** + * @param {Module} module WASM module + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {RequestShortener} requestShortener request shortener + */ + constructor(module, moduleGraph, chunkGraph, requestShortener) { + const moduleChains = getInitialModuleChains( + module, + moduleGraph, + chunkGraph, + requestShortener ); - }); -} - -function processResource(options, loaderContext, callback) { - // set loader index to last loader - loaderContext.loaderIndex = loaderContext.loaders.length - 1; + const message = `WebAssembly module is included in initial chunk. +This is not allowed, because WebAssembly download and compilation must happen asynchronous. +Add an async split point (i. e. import()) somewhere between your entrypoint and the WebAssembly module: +${moduleChains.map(s => `* ${s}`).join("\n")}`; - var resourcePath = loaderContext.resourcePath; - if(resourcePath) { - options.processResource(loaderContext, resourcePath, function(err, buffer) { - if(err) return callback(err); - options.resourceBuffer = buffer; - iterateNormalLoaders(options, loaderContext, [buffer], callback); - }); - } else { - iterateNormalLoaders(options, loaderContext, [null], callback); + super(message); + this.name = "WebAssemblyInInitialChunkError"; + this.hideStack = true; + this.module = module; } -} +}; -function iterateNormalLoaders(options, loaderContext, args, callback) { - if(loaderContext.loaderIndex < 0) - return callback(null, args); - var currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex]; +/***/ }), - // iterate - if(currentLoaderObject.normalExecuted) { - loaderContext.loaderIndex--; - return iterateNormalLoaders(options, loaderContext, args, callback); - } +/***/ 46545: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - var fn = currentLoaderObject.normal; - currentLoaderObject.normalExecuted = true; - if(!fn) { - return iterateNormalLoaders(options, loaderContext, args, callback); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - convertArgs(args, currentLoaderObject.raw); - runSyncOrAsync(fn, loaderContext, args, function(err) { - if(err) return callback(err); - var args = Array.prototype.slice.call(arguments, 1); - iterateNormalLoaders(options, loaderContext, args, callback); - }); -} +const { RawSource } = __webpack_require__(51255); +const { UsageState } = __webpack_require__(63686); +const Generator = __webpack_require__(93401); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(39722); +const ModuleDependency = __webpack_require__(80321); +const WebAssemblyExportImportedDependency = __webpack_require__(52204); +const WebAssemblyImportDependency = __webpack_require__(5239); -exports.getContext = function getContext(resource) { - var path = parsePathQueryFragment(resource).path; - return dirname(path); -}; +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -exports.runLoaders = function runLoaders(options, callback) { - // read options - var resource = options.resource || ""; - var loaders = options.loaders || []; - var loaderContext = options.context || {}; - var processResource = options.processResource || ((readResource, context, resource, callback) => { - context.addDependency(resource); - readResource(resource, callback); - }).bind(null, options.readResource || readFile); +const TYPES = new Set(["webassembly"]); - // - var splittedResource = resource && parsePathQueryFragment(resource); - var resourcePath = splittedResource ? splittedResource.path : undefined; - var resourceQuery = splittedResource ? splittedResource.query : undefined; - var resourceFragment = splittedResource ? splittedResource.fragment : undefined; - var contextDirectory = resourcePath ? dirname(resourcePath) : null; +class WebAssemblyJavascriptGenerator extends Generator { + /** + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) + */ + getTypes(module) { + return TYPES; + } - // execution state - var requestCacheable = true; - var fileDependencies = []; - var contextDependencies = []; - var missingDependencies = []; + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + return 95 + module.dependencies.length * 5; + } - // prepare loader objects - loaders = loaders.map(createLoaderObject); + /** + * @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 { + runtimeTemplate, + moduleGraph, + chunkGraph, + runtimeRequirements, + runtime + } = generateContext; + /** @type {InitFragment[]} */ + const initFragments = []; - loaderContext.context = contextDirectory; - loaderContext.loaderIndex = 0; - loaderContext.loaders = loaders; - loaderContext.resourcePath = resourcePath; - loaderContext.resourceQuery = resourceQuery; - loaderContext.resourceFragment = resourceFragment; - loaderContext.async = null; - loaderContext.callback = null; - loaderContext.cacheable = function cacheable(flag) { - if(flag === false) { - requestCacheable = false; - } - }; - loaderContext.dependency = loaderContext.addDependency = function addDependency(file) { - fileDependencies.push(file); - }; - loaderContext.addContextDependency = function addContextDependency(context) { - contextDependencies.push(context); - }; - loaderContext.addMissingDependency = function addMissingDependency(context) { - missingDependencies.push(context); - }; - loaderContext.getDependencies = function getDependencies() { - return fileDependencies.slice(); - }; - loaderContext.getContextDependencies = function getContextDependencies() { - return contextDependencies.slice(); - }; - loaderContext.getMissingDependencies = function getMissingDependencies() { - return missingDependencies.slice(); - }; - loaderContext.clearDependencies = function clearDependencies() { - fileDependencies.length = 0; - contextDependencies.length = 0; - missingDependencies.length = 0; - requestCacheable = true; - }; - Object.defineProperty(loaderContext, "resource", { - enumerable: true, - get: function() { - if(loaderContext.resourcePath === undefined) - return undefined; - return loaderContext.resourcePath.replace(/#/g, "\0#") + loaderContext.resourceQuery.replace(/#/g, "\0#") + loaderContext.resourceFragment; - }, - set: function(value) { - var splittedResource = value && parsePathQueryFragment(value); - loaderContext.resourcePath = splittedResource ? splittedResource.path : undefined; - loaderContext.resourceQuery = splittedResource ? splittedResource.query : undefined; - loaderContext.resourceFragment = splittedResource ? splittedResource.fragment : undefined; - } - }); - Object.defineProperty(loaderContext, "request", { - enumerable: true, - get: function() { - return loaderContext.loaders.map(function(o) { - return o.request; - }).concat(loaderContext.resource || "").join("!"); - } - }); - Object.defineProperty(loaderContext, "remainingRequest", { - enumerable: true, - get: function() { - if(loaderContext.loaderIndex >= loaderContext.loaders.length - 1 && !loaderContext.resource) - return ""; - return loaderContext.loaders.slice(loaderContext.loaderIndex + 1).map(function(o) { - return o.request; - }).concat(loaderContext.resource || "").join("!"); - } - }); - Object.defineProperty(loaderContext, "currentRequest", { - enumerable: true, - get: function() { - return loaderContext.loaders.slice(loaderContext.loaderIndex).map(function(o) { - return o.request; - }).concat(loaderContext.resource || "").join("!"); - } - }); - Object.defineProperty(loaderContext, "previousRequest", { - enumerable: true, - get: function() { - return loaderContext.loaders.slice(0, loaderContext.loaderIndex).map(function(o) { - return o.request; - }).join("!"); - } - }); - Object.defineProperty(loaderContext, "query", { - enumerable: true, - get: function() { - var entry = loaderContext.loaders[loaderContext.loaderIndex]; - return entry.options && typeof entry.options === "object" ? entry.options : entry.query; - } - }); - Object.defineProperty(loaderContext, "data", { - enumerable: true, - get: function() { - return loaderContext.loaders[loaderContext.loaderIndex].data; - } - }); + const exportsInfo = moduleGraph.getExportsInfo(module); - // finish loader context - if(Object.preventExtensions) { - Object.preventExtensions(loaderContext); - } + let needExportsCopy = false; + const importedModules = new Map(); + const initParams = []; + let index = 0; + for (const dep of module.dependencies) { + const moduleDep = + dep && dep instanceof ModuleDependency ? dep : undefined; + if (moduleGraph.getModule(dep)) { + let importData = importedModules.get(moduleGraph.getModule(dep)); + if (importData === undefined) { + importedModules.set( + moduleGraph.getModule(dep), + (importData = { + importVar: `m${index}`, + index, + request: (moduleDep && moduleDep.userRequest) || undefined, + names: new Set(), + reexports: [] + }) + ); + index++; + } + if (dep instanceof WebAssemblyImportDependency) { + importData.names.add(dep.name); + if (dep.description.type === "GlobalType") { + const exportName = dep.name; + const importedModule = moduleGraph.getModule(dep); - var processOptions = { - resourceBuffer: null, - processResource: processResource - }; - iteratePitchingLoaders(processOptions, loaderContext, function(err, result) { - if(err) { - return callback(err, { - cacheable: requestCacheable, - fileDependencies: fileDependencies, - contextDependencies: contextDependencies, - missingDependencies: missingDependencies - }); + if (importedModule) { + const usedName = moduleGraph + .getExportsInfo(importedModule) + .getUsedName(exportName, runtime); + if (usedName) { + initParams.push( + runtimeTemplate.exportFromImport({ + moduleGraph, + module: importedModule, + request: dep.request, + importVar: importData.importVar, + originModule: module, + exportName: dep.name, + asiSafe: true, + isCall: false, + callContext: null, + defaultInterop: true, + initFragments, + runtime, + runtimeRequirements + }) + ); + } + } + } + } + if (dep instanceof WebAssemblyExportImportedDependency) { + importData.names.add(dep.name); + const usedName = moduleGraph + .getExportsInfo(module) + .getUsedName(dep.exportName, runtime); + if (usedName) { + runtimeRequirements.add(RuntimeGlobals.exports); + const exportProp = `${module.exportsArgument}[${JSON.stringify( + usedName + )}]`; + const defineStatement = Template.asString([ + `${exportProp} = ${runtimeTemplate.exportFromImport({ + moduleGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + importVar: importData.importVar, + originModule: module, + exportName: dep.name, + asiSafe: true, + isCall: false, + callContext: null, + defaultInterop: true, + initFragments, + runtime, + runtimeRequirements + })};`, + `if(WebAssembly.Global) ${exportProp} = ` + + `new WebAssembly.Global({ value: ${JSON.stringify( + dep.valueType + )} }, ${exportProp});` + ]); + importData.reexports.push(defineStatement); + needExportsCopy = true; + } + } + } } - callback(null, { - result: result, - resourceBuffer: processOptions.resourceBuffer, - cacheable: requestCacheable, - fileDependencies: fileDependencies, - contextDependencies: contextDependencies, - missingDependencies: missingDependencies - }); - }); -}; - - -/***/ }), - -/***/ 44690: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const importsCode = Template.asString( + Array.from( + importedModules, + ([module, { importVar, request, reexports }]) => { + const importStatement = runtimeTemplate.importStatement({ + module, + chunkGraph, + request, + importVar, + originModule: module, + runtimeRequirements + }); + return importStatement[0] + importStatement[1] + reexports.join("\n"); + } + ) + ); -var LoaderLoadingError = __webpack_require__(39102); -var url; + const copyAllExports = + exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused && + !needExportsCopy; -module.exports = function loadLoader(loader, callback) { - if(loader.type === "module") { - try { - if(url === undefined) url = __webpack_require__(57310); - var loaderUrl = url.pathToFileURL(loader.path); - var modulePromise = eval("import(" + JSON.stringify(loaderUrl.toString()) + ")"); - modulePromise.then(function(module) { - handleResult(loader, module, callback); - }, callback); - return; - } catch(e) { - callback(e); + // need these globals + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(RuntimeGlobals.moduleId); + runtimeRequirements.add(RuntimeGlobals.wasmInstances); + if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { + runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); + runtimeRequirements.add(RuntimeGlobals.exports); } - } else { - try { - var module = require(loader.path); - } catch(e) { - // it is possible for node to choke on a require if the FD descriptor - // limit has been reached. give it a chance to recover. - if(e instanceof Error && e.code === "EMFILE") { - var retry = loadLoader.bind(null, loader, callback); - if(typeof setImmediate === "function") { - // node >= 0.9.0 - return setImmediate(retry); - } else { - // node < 0.9.0 - return process.nextTick(retry); - } - } - return callback(e); + if (!copyAllExports) { + runtimeRequirements.add(RuntimeGlobals.exports); } - return handleResult(loader, module, callback); - } -}; -function handleResult(loader, module, callback) { - if(typeof module !== "function" && typeof module !== "object") { - return callback(new LoaderLoadingError( - "Module '" + loader.path + "' is not a loader (export function or es6 module)" - )); - } - loader.normal = typeof module === "function" ? module : module.default; - loader.pitch = module.pitch; - loader.raw = module.raw; - if(typeof loader.normal !== "function" && typeof loader.pitch !== "function") { - return callback(new LoaderLoadingError( - "Module '" + loader.path + "' is not a loader (must have normal or pitch function)" - )); + // create source + const source = new RawSource( + [ + '"use strict";', + "// Instantiate WebAssembly module", + `var wasmExports = ${RuntimeGlobals.wasmInstances}[${module.moduleArgument}.id];`, + + exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused + ? `${RuntimeGlobals.makeNamespaceObject}(${module.exportsArgument});` + : "", + + // this must be before import for circular dependencies + "// export exports from WebAssembly module", + copyAllExports + ? `${module.moduleArgument}.exports = wasmExports;` + : "for(var name in wasmExports) " + + `if(name) ` + + `${module.exportsArgument}[name] = wasmExports[name];`, + "// exec imports from WebAssembly module (for esm order)", + importsCode, + "", + "// exec wasm module", + `wasmExports[""](${initParams.join(", ")})` + ].join("\n") + ); + return InitFragment.addToSource(source, initFragments, generateContext); } - callback(); } +module.exports = WebAssemblyJavascriptGenerator; + /***/ }), -/***/ 50569: +/***/ 53639: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * Module exports. - */ -module.exports = __webpack_require__(58750) +const Generator = __webpack_require__(93401); +const WebAssemblyExportImportedDependency = __webpack_require__(52204); +const WebAssemblyImportDependency = __webpack_require__(5239); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const memoize = __webpack_require__(78676); +const WebAssemblyInInitialChunkError = __webpack_require__(47342); -/***/ }), +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/***/ 78585: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +const getWebAssemblyGenerator = memoize(() => + __webpack_require__(47012) +); +const getWebAssemblyJavascriptGenerator = memoize(() => + __webpack_require__(46545) +); +const getWebAssemblyParser = memoize(() => __webpack_require__(57059)); -"use strict"; -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ +class WebAssemblyModulesPlugin { + constructor(options) { + this.options = options; + } + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "WebAssemblyModulesPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + WebAssemblyImportDependency, + normalModuleFactory + ); + compilation.dependencyFactories.set( + WebAssemblyExportImportedDependency, + normalModuleFactory + ); -/** - * Module dependencies. - * @private - */ + normalModuleFactory.hooks.createParser + .for("webassembly/sync") + .tap("WebAssemblyModulesPlugin", () => { + const WebAssemblyParser = getWebAssemblyParser(); -var db = __webpack_require__(50569) -var extname = (__webpack_require__(71017).extname) + return new WebAssemblyParser(); + }); -/** - * Module variables. - * @private - */ + normalModuleFactory.hooks.createGenerator + .for("webassembly/sync") + .tap("WebAssemblyModulesPlugin", () => { + const WebAssemblyJavascriptGenerator = + getWebAssemblyJavascriptGenerator(); + const WebAssemblyGenerator = getWebAssemblyGenerator(); -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i + return Generator.byType({ + javascript: new WebAssemblyJavascriptGenerator(), + webassembly: new WebAssemblyGenerator(this.options) + }); + }); -/** - * Module exports. - * @public - */ + compilation.hooks.renderManifest.tap( + "WebAssemblyModulesPlugin", + (result, options) => { + const { chunkGraph } = compilation; + const { chunk, outputOptions, codeGenerationResults } = options; -exports.charset = charset -exports.charsets = { lookup: charset } -exports.contentType = contentType -exports.extension = extension -exports.extensions = Object.create(null) -exports.lookup = lookup -exports.types = Object.create(null) + for (const module of chunkGraph.getOrderedChunkModulesIterable( + chunk, + compareModulesByIdentifier + )) { + if (module.type === "webassembly/sync") { + const filenameTemplate = + outputOptions.webassemblyModuleFilename; -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) + result.push({ + render: () => + codeGenerationResults.getSource( + module, + chunk.runtime, + "webassembly" + ), + filenameTemplate, + pathOptions: { + module, + runtime: chunk.runtime, + chunkGraph + }, + auxiliary: true, + identifier: `webassemblyModule${chunkGraph.getModuleId( + module + )}`, + hash: chunkGraph.getModuleHash(module, chunk.runtime) + }); + } + } -/** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ + return result; + } + ); -function charset (type) { - if (!type || typeof type !== 'string') { - return false - } + compilation.hooks.afterChunks.tap("WebAssemblyModulesPlugin", () => { + const chunkGraph = compilation.chunkGraph; + const initialWasmModules = new Set(); + for (const chunk of compilation.chunks) { + if (chunk.canBeInitial()) { + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (module.type === "webassembly/sync") { + initialWasmModules.add(module); + } + } + } + } + for (const module of initialWasmModules) { + compilation.errors.push( + new WebAssemblyInInitialChunkError( + module, + compilation.moduleGraph, + compilation.chunkGraph, + compilation.requestShortener + ) + ); + } + }); + } + ); + } +} - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - var mime = match && db[match[1].toLowerCase()] +module.exports = WebAssemblyModulesPlugin; - if (mime && mime.charset) { - return mime.charset - } - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } +/***/ }), - return false -} +/***/ 57059: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false - } - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str - if (!mime) { - return false - } +const t = __webpack_require__(51826); +const { moduleContextFromModuleAST } = __webpack_require__(51826); +const { decode } = __webpack_require__(73726); +const Parser = __webpack_require__(11715); +const StaticExportsDependency = __webpack_require__(91418); +const WebAssemblyExportImportedDependency = __webpack_require__(52204); +const WebAssemblyImportDependency = __webpack_require__(5239); - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() - } +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ - return mime -} +const JS_COMPAT_TYPES = new Set(["i32", "f32", "f64"]); /** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} + * @param {t.Signature} signature the func signature + * @returns {null | string} the type incompatible with js types */ +const getJsIncompatibleType = signature => { + for (const param of signature.params) { + if (!JS_COMPAT_TYPES.has(param.valtype)) { + return `${param.valtype} as parameter`; + } + } + for (const type of signature.results) { + if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; + } + return null; +}; -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } +/** + * TODO why are there two different Signature types? + * @param {t.FuncSignature} signature the func signature + * @returns {null | string} the type incompatible with js types + */ +const getJsIncompatibleTypeOfFuncSignature = signature => { + for (const param of signature.args) { + if (!JS_COMPAT_TYPES.has(param)) { + return `${param} as parameter`; + } + } + for (const type of signature.result) { + if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; + } + return null; +}; - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) +const decoderOpts = { + ignoreCodeSection: true, + ignoreDataSection: true, - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] + // this will avoid having to lookup with identifiers in the ModuleContext + ignoreCustomNameSection: true +}; - if (!exts || !exts.length) { - return false - } +class WebAssemblyParser extends Parser { + constructor(options) { + super(); + this.hooks = Object.freeze({}); + this.options = options; + } - return exts[0] -} + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (!Buffer.isBuffer(source)) { + throw new Error("WebAssemblyParser input must be a Buffer"); + } -/** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} - */ + // flag it as ESM + state.module.buildInfo.strict = true; + state.module.buildMeta.exportsType = "namespace"; -function lookup (path) { - if (!path || typeof path !== 'string') { - return false - } + // parse it + const program = decode(source, decoderOpts); + const module = program.body[0]; - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) + const moduleContext = moduleContextFromModuleAST(module); - if (!extension) { - return false - } + // extract imports and exports + const exports = []; + let jsIncompatibleExports = (state.module.buildMeta.jsIncompatibleExports = + undefined); - return exports.types[extension] || false -} + const importedGlobals = []; + t.traverse(module, { + ModuleExport({ node }) { + const descriptor = node.descr; -/** - * Populate the extensions and types maps. - * @private - */ + if (descriptor.exportType === "Func") { + const funcIdx = descriptor.id.value; -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] + /** @type {t.FuncSignature} */ + const funcSignature = moduleContext.getFunction(funcIdx); - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions + const incompatibleType = + getJsIncompatibleTypeOfFuncSignature(funcSignature); - if (!exts || !exts.length) { - return - } + if (incompatibleType) { + if (jsIncompatibleExports === undefined) { + jsIncompatibleExports = + state.module.buildMeta.jsIncompatibleExports = {}; + } + jsIncompatibleExports[node.name] = incompatibleType; + } + } - // mime -> extensions - extensions[type] = exts + exports.push(node.name); - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] + if (node.descr && node.descr.exportType === "Global") { + const refNode = importedGlobals[node.descr.id.value]; + if (refNode) { + const dep = new WebAssemblyExportImportedDependency( + node.name, + refNode.module, + refNode.name, + refNode.descr.valtype + ); - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) + state.module.addDependency(dep); + } + } + }, - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } + Global({ node }) { + const init = node.init[0]; - // set the extension -> mime - types[extension] = type - } - }) -} + let importNode = null; + if (init.id === "get_global") { + const globalIdx = init.args[0].value; -/***/ }), + if (globalIdx < importedGlobals.length) { + importNode = importedGlobals[globalIdx]; + } + } -/***/ 76297: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + importedGlobals.push(importNode); + }, -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + ModuleImport({ node }) { + /** @type {false | string} */ + let onlyDirectImport = false; + if (t.isMemory(node.descr) === true) { + onlyDirectImport = "Memory"; + } else if (t.isTable(node.descr) === true) { + onlyDirectImport = "Table"; + } else if (t.isFuncImportDescr(node.descr) === true) { + const incompatibleType = getJsIncompatibleType(node.descr.signature); + if (incompatibleType) { + onlyDirectImport = `Non-JS-compatible Func Signature (${incompatibleType})`; + } + } else if (t.isGlobalType(node.descr) === true) { + const type = node.descr.valtype; + if (!JS_COMPAT_TYPES.has(type)) { + onlyDirectImport = `Non-JS-compatible Global Type (${type})`; + } + } -const Hook = __webpack_require__(72258); -const HookCodeFactory = __webpack_require__(177); + const dep = new WebAssemblyImportDependency( + node.module, + node.name, + node.descr, + onlyDirectImport + ); -class AsyncParallelBailHookCodeFactory extends HookCodeFactory { - content({ onError, onResult, onDone }) { - let code = ""; - code += `var _results = new Array(${this.options.taps.length});\n`; - code += "var _checkDone = function() {\n"; - code += "for(var i = 0; i < _results.length; i++) {\n"; - code += "var item = _results[i];\n"; - code += "if(item === undefined) return false;\n"; - code += "if(item.result !== undefined) {\n"; - code += onResult("item.result"); - code += "return true;\n"; - code += "}\n"; - code += "if(item.error) {\n"; - code += onError("item.error"); - code += "return true;\n"; - code += "}\n"; - code += "}\n"; - code += "return false;\n"; - code += "}\n"; - code += this.callTapsParallel({ - onError: (i, err, done, doneBreak) => { - let code = ""; - code += `if(${i} < _results.length && ((_results.length = ${i + - 1}), (_results[${i}] = { error: ${err} }), _checkDone())) {\n`; - code += doneBreak(true); - code += "} else {\n"; - code += done(); - code += "}\n"; - return code; - }, - onResult: (i, result, done, doneBreak) => { - let code = ""; - code += `if(${i} < _results.length && (${result} !== undefined && (_results.length = ${i + - 1}), (_results[${i}] = { result: ${result} }), _checkDone())) {\n`; - code += doneBreak(true); - code += "} else {\n"; - code += done(); - code += "}\n"; - return code; - }, - onTap: (i, run, done, doneBreak) => { - let code = ""; - if (i > 0) { - code += `if(${i} >= _results.length) {\n`; - code += done(); - code += "} else {\n"; + state.module.addDependency(dep); + + if (t.isGlobalType(node.descr)) { + importedGlobals.push(node); } - code += run(); - if (i > 0) code += "}\n"; - return code; - }, - onDone + } }); - return code; - } -} - -const factory = new AsyncParallelBailHookCodeFactory(); -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; + state.module.addDependency(new StaticExportsDependency(exports, false)); -function AsyncParallelBailHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = AsyncParallelBailHook; - hook.compile = COMPILE; - hook._call = undefined; - hook.call = undefined; - return hook; + return state; + } } -AsyncParallelBailHook.prototype = null; - -module.exports = AsyncParallelBailHook; +module.exports = WebAssemblyParser; /***/ }), -/***/ 45874: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 18650: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -139584,42 +144746,70 @@ module.exports = AsyncParallelBailHook; */ -const Hook = __webpack_require__(72258); -const HookCodeFactory = __webpack_require__(177); -class AsyncParallelHookCodeFactory extends HookCodeFactory { - content({ onError, onDone }) { - return this.callTapsParallel({ - onError: (i, err, done, doneBreak) => onError(err) + doneBreak(true), - onDone - }); - } -} +const Template = __webpack_require__(39722); +const WebAssemblyImportDependency = __webpack_require__(5239); -const factory = new AsyncParallelHookCodeFactory(); +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; +/** @typedef {Object} UsedWasmDependency + * @property {WebAssemblyImportDependency} dependency the dependency + * @property {string} name the export name + * @property {string} module the module name + */ -function AsyncParallelHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = AsyncParallelHook; - hook.compile = COMPILE; - hook._call = undefined; - hook.call = undefined; - return hook; -} +const MANGLED_MODULE = "a"; -AsyncParallelHook.prototype = null; +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {Module} module the module + * @param {boolean} mangle mangle module and export names + * @returns {UsedWasmDependency[]} used dependencies and (mangled) name + */ +const getUsedDependencies = (moduleGraph, module, mangle) => { + /** @type {UsedWasmDependency[]} */ + const array = []; + let importIndex = 0; + for (const dep of module.dependencies) { + if (dep instanceof WebAssemblyImportDependency) { + if ( + dep.description.type === "GlobalType" || + moduleGraph.getModule(dep) === null + ) { + continue; + } -module.exports = AsyncParallelHook; + const exportName = dep.name; + // TODO add the following 3 lines when removing of ModuleExport is possible + // const importedModule = moduleGraph.getModule(dep); + // const usedName = importedModule && moduleGraph.getExportsInfo(importedModule).getUsedName(exportName, runtime); + // if (usedName !== false) { + if (mangle) { + array.push({ + dependency: dep, + name: Template.numberToIdentifier(importIndex++), + module: MANGLED_MODULE + }); + } else { + array.push({ + dependency: dep, + name: exportName, + module: dep.request + }); + } + } + } + return array; +}; + +exports.getUsedDependencies = getUsedDependencies; +exports.MANGLED_MODULE = MANGLED_MODULE; /***/ }), -/***/ 13633: +/***/ 78613: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -139629,92 +144819,123 @@ module.exports = AsyncParallelHook; */ -const Hook = __webpack_require__(72258); -const HookCodeFactory = __webpack_require__(177); -class AsyncSeriesBailHookCodeFactory extends HookCodeFactory { - content({ onError, onResult, resultReturns, onDone }) { - return this.callTapsSeries({ - onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), - onResult: (i, result, next) => - `if(${result} !== undefined) {\n${onResult( - result - )}\n} else {\n${next()}}\n`, - resultReturns, - onDone - }); - } -} +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").WasmLoadingType} WasmLoadingType */ +/** @typedef {import("../Compiler")} Compiler */ -const factory = new AsyncSeriesBailHookCodeFactory(); +/** @type {WeakMap>} */ +const enabledTypes = new WeakMap(); -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); +const getEnabledTypes = compiler => { + let set = enabledTypes.get(compiler); + if (set === undefined) { + set = new Set(); + enabledTypes.set(compiler, set); + } + return set; }; -function AsyncSeriesBailHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = AsyncSeriesBailHook; - hook.compile = COMPILE; - hook._call = undefined; - hook.call = undefined; - return hook; -} - -AsyncSeriesBailHook.prototype = null; - -module.exports = AsyncSeriesBailHook; - - -/***/ }), - -/***/ 40436: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - +class EnableWasmLoadingPlugin { + /** + * @param {WasmLoadingType} type library type that should be available + */ + constructor(type) { + this.type = type; + } -const Hook = __webpack_require__(72258); -const HookCodeFactory = __webpack_require__(177); + /** + * @param {Compiler} compiler the compiler instance + * @param {WasmLoadingType} type type of library + * @returns {void} + */ + static setEnabled(compiler, type) { + getEnabledTypes(compiler).add(type); + } -class AsyncSeriesHookCodeFactory extends HookCodeFactory { - content({ onError, onDone }) { - return this.callTapsSeries({ - onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), - onDone - }); + /** + * @param {Compiler} compiler the compiler instance + * @param {WasmLoadingType} type type of library + * @returns {void} + */ + static checkEnabled(compiler, type) { + if (!getEnabledTypes(compiler).has(type)) { + throw new Error( + `Library type "${type}" is not enabled. ` + + "EnableWasmLoadingPlugin need to be used to enable this type of wasm loading. " + + 'This usually happens through the "output.enabledWasmLoadingTypes" option. ' + + 'If you are using a function as entry which sets "wasmLoading", you need to add all potential library types to "output.enabledWasmLoadingTypes". ' + + "These types are enabled: " + + Array.from(getEnabledTypes(compiler)).join(", ") + ); + } } -} -const factory = new AsyncSeriesHookCodeFactory(); + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { type } = this; -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; + // Only enable once + const enabled = getEnabledTypes(compiler); + if (enabled.has(type)) return; + enabled.add(type); -function AsyncSeriesHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = AsyncSeriesHook; - hook.compile = COMPILE; - hook._call = undefined; - hook.call = undefined; - return hook; + if (typeof type === "string") { + switch (type) { + case "fetch": { + // TODO webpack 6 remove FetchCompileWasmPlugin + const FetchCompileWasmPlugin = __webpack_require__(35537); + const FetchCompileAsyncWasmPlugin = __webpack_require__(8437); + new FetchCompileWasmPlugin({ + mangleImports: compiler.options.optimization.mangleWasmImports + }).apply(compiler); + new FetchCompileAsyncWasmPlugin().apply(compiler); + break; + } + case "async-node": { + // TODO webpack 6 remove ReadFileCompileWasmPlugin + const ReadFileCompileWasmPlugin = __webpack_require__(98939); + // @ts-expect-error typescript bug for duplicate require + const ReadFileCompileAsyncWasmPlugin = __webpack_require__(73163); + new ReadFileCompileWasmPlugin({ + mangleImports: compiler.options.optimization.mangleWasmImports + }).apply(compiler); + new ReadFileCompileAsyncWasmPlugin({ type }).apply(compiler); + break; + } + case "async-node-module": { + // @ts-expect-error typescript bug for duplicate require + const ReadFileCompileAsyncWasmPlugin = __webpack_require__(73163); + new ReadFileCompileAsyncWasmPlugin({ type, import: true }).apply( + compiler + ); + break; + } + case "universal": + throw new Error( + "Universal WebAssembly Loading is not implemented yet" + ); + default: + throw new Error(`Unsupported wasm loading type ${type}. +Plugins which provide custom wasm loading types must call EnableWasmLoadingPlugin.setEnabled(compiler, type) to disable this error.`); + } + } else { + // TODO support plugin instances here + // apply them to the compiler + } + } } -AsyncSeriesHook.prototype = null; - -module.exports = AsyncSeriesHook; +module.exports = EnableWasmLoadingPlugin; /***/ }), -/***/ 34656: +/***/ 8437: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -139724,42 +144945,67 @@ module.exports = AsyncSeriesHook; */ -const Hook = __webpack_require__(72258); -const HookCodeFactory = __webpack_require__(177); -class AsyncSeriesLoopHookCodeFactory extends HookCodeFactory { - content({ onError, onDone }) { - return this.callTapsLooping({ - onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), - onDone - }); - } -} +const RuntimeGlobals = __webpack_require__(16475); +const AsyncWasmLoadingRuntimeModule = __webpack_require__(5434); -const factory = new AsyncSeriesLoopHookCodeFactory(); +/** @typedef {import("../Compiler")} Compiler */ -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; +class FetchCompileAsyncWasmPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "FetchCompileAsyncWasmPlugin", + compilation => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === "fetch"; + }; + const generateLoadBinaryCode = path => + `fetch(${RuntimeGlobals.publicPath} + ${path})`; -function AsyncSeriesLoopHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = AsyncSeriesLoopHook; - hook.compile = COMPILE; - hook._call = undefined; - hook.call = undefined; - return hook; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.instantiateWasm) + .tap("FetchCompileAsyncWasmPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + const chunkGraph = compilation.chunkGraph; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + m => m.type === "webassembly/async" + ) + ) { + return; + } + set.add(RuntimeGlobals.publicPath); + compilation.addRuntimeModule( + chunk, + new AsyncWasmLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: true + }) + ); + }); + } + ); + } } -AsyncSeriesLoopHook.prototype = null; - -module.exports = AsyncSeriesLoopHook; +module.exports = FetchCompileAsyncWasmPlugin; /***/ }), -/***/ 47794: +/***/ 35537: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -139769,52 +145015,76 @@ module.exports = AsyncSeriesLoopHook; */ -const Hook = __webpack_require__(72258); -const HookCodeFactory = __webpack_require__(177); -class AsyncSeriesWaterfallHookCodeFactory extends HookCodeFactory { - content({ onError, onResult, onDone }) { - return this.callTapsSeries({ - onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), - onResult: (i, result, next) => { - let code = ""; - code += `if(${result} !== undefined) {\n`; - code += `${this._args[0]} = ${result};\n`; - code += `}\n`; - code += next(); - return code; - }, - onDone: () => onResult(this._args[0]) - }); +const RuntimeGlobals = __webpack_require__(16475); +const WasmChunkLoadingRuntimeModule = __webpack_require__(87394); + +/** @typedef {import("../Compiler")} Compiler */ + +// TODO webpack 6 remove + +class FetchCompileWasmPlugin { + constructor(options) { + this.options = options || {}; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "FetchCompileWasmPlugin", + compilation => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === "fetch"; + }; + const generateLoadBinaryCode = path => + `fetch(${RuntimeGlobals.publicPath} + ${path})`; + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("FetchCompileWasmPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + const chunkGraph = compilation.chunkGraph; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + m => m.type === "webassembly/sync" + ) + ) { + return; + } + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.publicPath); + compilation.addRuntimeModule( + chunk, + new WasmChunkLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: true, + mangleImports: this.options.mangleImports, + runtimeRequirements: set + }) + ); + }); + } + ); } } -const factory = new AsyncSeriesWaterfallHookCodeFactory(); - -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; - -function AsyncSeriesWaterfallHook(args = [], name = undefined) { - if (args.length < 1) - throw new Error("Waterfall hooks must have at least one argument"); - const hook = new Hook(args, name); - hook.constructor = AsyncSeriesWaterfallHook; - hook.compile = COMPILE; - hook._call = undefined; - hook.call = undefined; - return hook; -} - -AsyncSeriesWaterfallHook.prototype = null; - -module.exports = AsyncSeriesWaterfallHook; +module.exports = FetchCompileWasmPlugin; /***/ }), -/***/ 72258: +/***/ 83121: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -139824,656 +145094,590 @@ module.exports = AsyncSeriesWaterfallHook; */ -const util = __webpack_require__(73837); - -const deprecateContext = util.deprecate(() => {}, -"Hook.context is deprecated and will be removed"); - -const CALL_DELEGATE = function(...args) { - this.call = this._createCall("sync"); - return this.call(...args); -}; -const CALL_ASYNC_DELEGATE = function(...args) { - this.callAsync = this._createCall("async"); - return this.callAsync(...args); -}; -const PROMISE_DELEGATE = function(...args) { - this.promise = this._createCall("promise"); - return this.promise(...args); -}; - -class Hook { - constructor(args = [], name = undefined) { - this._args = args; - this.name = name; - this.taps = []; - this.interceptors = []; - this._call = CALL_DELEGATE; - this.call = CALL_DELEGATE; - this._callAsync = CALL_ASYNC_DELEGATE; - this.callAsync = CALL_ASYNC_DELEGATE; - this._promise = PROMISE_DELEGATE; - this.promise = PROMISE_DELEGATE; - this._x = undefined; - - this.compile = this.compile; - this.tap = this.tap; - this.tapAsync = this.tapAsync; - this.tapPromise = this.tapPromise; - } - - compile(options) { - throw new Error("Abstract: should be overridden"); - } - - _createCall(type) { - return this.compile({ - taps: this.taps, - interceptors: this.interceptors, - args: this._args, - type: type - }); - } - - _tap(type, options, fn) { - if (typeof options === "string") { - options = { - name: options.trim() - }; - } else if (typeof options !== "object" || options === null) { - throw new Error("Invalid tap options"); - } - if (typeof options.name !== "string" || options.name === "") { - throw new Error("Missing name for tap"); - } - if (typeof options.context !== "undefined") { - deprecateContext(); - } - options = Object.assign({ type, fn }, options); - options = this._runRegisterInterceptors(options); - this._insert(options); - } - - tap(options, fn) { - this._tap("sync", options, fn); - } - - tapAsync(options, fn) { - this._tap("async", options, fn); - } - - tapPromise(options, fn) { - this._tap("promise", options, fn); - } - - _runRegisterInterceptors(options) { - for (const interceptor of this.interceptors) { - if (interceptor.register) { - const newOptions = interceptor.register(options); - if (newOptions !== undefined) { - options = newOptions; - } - } - } - return options; - } - - withOptions(options) { - const mergeOptions = opt => - Object.assign({}, options, typeof opt === "string" ? { name: opt } : opt); - - return { - name: this.name, - tap: (opt, fn) => this.tap(mergeOptions(opt), fn), - tapAsync: (opt, fn) => this.tapAsync(mergeOptions(opt), fn), - tapPromise: (opt, fn) => this.tapPromise(mergeOptions(opt), fn), - intercept: interceptor => this.intercept(interceptor), - isUsed: () => this.isUsed(), - withOptions: opt => this.withOptions(mergeOptions(opt)) - }; - } - isUsed() { - return this.taps.length > 0 || this.interceptors.length > 0; - } +const RuntimeGlobals = __webpack_require__(16475); +const JsonpChunkLoadingRuntimeModule = __webpack_require__(84154); - intercept(interceptor) { - this._resetCompilation(); - this.interceptors.push(Object.assign({}, interceptor)); - if (interceptor.register) { - for (let i = 0; i < this.taps.length; i++) { - this.taps[i] = interceptor.register(this.taps[i]); - } - } - } +/** @typedef {import("../Compiler")} Compiler */ - _resetCompilation() { - this.call = this._call; - this.callAsync = this._callAsync; - this.promise = this._promise; - } +class JsonpChunkLoadingPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "JsonpChunkLoadingPlugin", + compilation => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === "jsonp"; + }; + const onceForChunkSet = new WeakSet(); + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new JsonpChunkLoadingRuntimeModule(set) + ); + }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("JsonpChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap("JsonpChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap("JsonpChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap("JsonpChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap("JsonpChunkLoadingPlugin", handler); - _insert(item) { - this._resetCompilation(); - let before; - if (typeof item.before === "string") { - before = new Set([item.before]); - } else if (Array.isArray(item.before)) { - before = new Set(item.before); - } - let stage = 0; - if (typeof item.stage === "number") { - stage = item.stage; - } - let i = this.taps.length; - while (i > 0) { - i--; - const x = this.taps[i]; - this.taps[i + 1] = x; - const xStage = x.stage || 0; - if (before) { - if (before.has(x.name)) { - before.delete(x.name); - continue; - } - if (before.size > 0) { - continue; - } - } - if (xStage > stage) { - continue; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("JsonpChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.loadScript); + set.add(RuntimeGlobals.getChunkScriptFilename); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap("JsonpChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.loadScript); + set.add(RuntimeGlobals.getChunkUpdateScriptFilename); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.hmrModuleData); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap("JsonpChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getUpdateManifestFilename); + }); } - i++; - break; - } - this.taps[i] = item; + ); } } -Object.setPrototypeOf(Hook.prototype, null); - -module.exports = Hook; +module.exports = JsonpChunkLoadingPlugin; /***/ }), -/***/ 177: -/***/ (function(module) { +/***/ 84154: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -class HookCodeFactory { - constructor(config) { - this.config = config; - this.options = undefined; - this._args = undefined; - } - create(options) { - this.init(options); - let fn; - switch (this.options.type) { - case "sync": - fn = new Function( - this.args(), - '"use strict";\n' + - this.header() + - this.contentWithInterceptors({ - onError: err => `throw ${err};\n`, - onResult: result => `return ${result};\n`, - resultReturns: true, - onDone: () => "", - rethrowIfPossible: true - }) - ); - break; - case "async": - fn = new Function( - this.args({ - after: "_callback" - }), - '"use strict";\n' + - this.header() + - this.contentWithInterceptors({ - onError: err => `_callback(${err});\n`, - onResult: result => `_callback(null, ${result});\n`, - onDone: () => "_callback();\n" - }) - ); - break; - case "promise": - let errorHelperUsed = false; - const content = this.contentWithInterceptors({ - onError: err => { - errorHelperUsed = true; - return `_error(${err});\n`; - }, - onResult: result => `_resolve(${result});\n`, - onDone: () => "_resolve();\n" - }); - let code = ""; - code += '"use strict";\n'; - code += this.header(); - code += "return new Promise((function(_resolve, _reject) {\n"; - if (errorHelperUsed) { - code += "var _sync = true;\n"; - code += "function _error(_err) {\n"; - code += "if(_sync)\n"; - code += - "_resolve(Promise.resolve().then((function() { throw _err; })));\n"; - code += "else\n"; - code += "_reject(_err);\n"; - code += "};\n"; - } - code += content; - if (errorHelperUsed) { - code += "_sync = false;\n"; - } - code += "}));\n"; - fn = new Function(this.args(), code); - break; - } - this.deinit(); - return fn; - } +const { SyncWaterfallHook } = __webpack_require__(41242); +const Compilation = __webpack_require__(85720); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); +const chunkHasJs = (__webpack_require__(89464).chunkHasJs); +const { getInitialChunkIds } = __webpack_require__(98124); +const compileBooleanMatcher = __webpack_require__(29404); - setup(instance, options) { - instance._x = options.taps.map(t => t.fn); - } +/** @typedef {import("../Chunk")} Chunk */ - /** - * @param {{ type: "sync" | "promise" | "async", taps: Array, interceptors: Array }} options - */ - init(options) { - this.options = options; - this._args = options.args.slice(); - } +/** + * @typedef {Object} JsonpCompilationPluginHooks + * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload + * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch + */ - deinit() { - this.options = undefined; - this._args = undefined; - } +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); - contentWithInterceptors(options) { - if (this.options.interceptors.length > 0) { - const onError = options.onError; - const onResult = options.onResult; - const onDone = options.onDone; - let code = ""; - for (let i = 0; i < this.options.interceptors.length; i++) { - const interceptor = this.options.interceptors[i]; - if (interceptor.call) { - code += `${this.getInterceptor(i)}.call(${this.args({ - before: interceptor.context ? "_context" : undefined - })});\n`; - } - } - code += this.content( - Object.assign(options, { - onError: - onError && - (err => { - let code = ""; - for (let i = 0; i < this.options.interceptors.length; i++) { - const interceptor = this.options.interceptors[i]; - if (interceptor.error) { - code += `${this.getInterceptor(i)}.error(${err});\n`; - } - } - code += onError(err); - return code; - }), - onResult: - onResult && - (result => { - let code = ""; - for (let i = 0; i < this.options.interceptors.length; i++) { - const interceptor = this.options.interceptors[i]; - if (interceptor.result) { - code += `${this.getInterceptor(i)}.result(${result});\n`; - } - } - code += onResult(result); - return code; - }), - onDone: - onDone && - (() => { - let code = ""; - for (let i = 0; i < this.options.interceptors.length; i++) { - const interceptor = this.options.interceptors[i]; - if (interceptor.done) { - code += `${this.getInterceptor(i)}.done();\n`; - } - } - code += onDone(); - return code; - }) - }) +class JsonpChunkLoadingRuntimeModule extends RuntimeModule { + /** + * @param {Compilation} compilation the compilation + * @returns {JsonpCompilationPluginHooks} hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" ); - return code; - } else { - return this.content(options); - } - } - - header() { - let code = ""; - if (this.needContext()) { - code += "var _context = {};\n"; - } else { - code += "var _context;\n"; } - code += "var _x = this._x;\n"; - if (this.options.interceptors.length > 0) { - code += "var _taps = this.taps;\n"; - code += "var _interceptors = this.interceptors;\n"; + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + linkPreload: new SyncWaterfallHook(["source", "chunk"]), + linkPrefetch: new SyncWaterfallHook(["source", "chunk"]) + }; + compilationHooksMap.set(compilation, hooks); } - return code; + return hooks; } - needContext() { - for (const tap of this.options.taps) if (tap.context) return true; - return false; + constructor(runtimeRequirements) { + super("jsonp chunk loading", RuntimeModule.STAGE_ATTACH); + this._runtimeRequirements = runtimeRequirements; } - callTap(tapIndex, { onError, onResult, onDone, rethrowIfPossible }) { - let code = ""; - let hasTapCached = false; - for (let i = 0; i < this.options.interceptors.length; i++) { - const interceptor = this.options.interceptors[i]; - if (interceptor.tap) { - if (!hasTapCached) { - code += `var _tap${tapIndex} = ${this.getTap(tapIndex)};\n`; - hasTapCached = true; - } - code += `${this.getInterceptor(i)}.tap(${ - interceptor.context ? "_context, " : "" - }_tap${tapIndex});\n`; + /** + * @returns {string} runtime code + */ + generate() { + const { chunkGraph, compilation, chunk } = this; + const { + runtimeTemplate, + outputOptions: { + chunkLoadingGlobal, + hotUpdateGlobal, + crossOriginLoading, + scriptType } - } - code += `var _fn${tapIndex} = ${this.getTapFn(tapIndex)};\n`; - const tap = this.options.taps[tapIndex]; - switch (tap.type) { - case "sync": - if (!rethrowIfPossible) { - code += `var _hasError${tapIndex} = false;\n`; - code += "try {\n"; - } - if (onResult) { - code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({ - before: tap.context ? "_context" : undefined - })});\n`; - } else { - code += `_fn${tapIndex}(${this.args({ - before: tap.context ? "_context" : undefined - })});\n`; - } - if (!rethrowIfPossible) { - code += "} catch(_err) {\n"; - code += `_hasError${tapIndex} = true;\n`; - code += onError("_err"); - code += "}\n"; - code += `if(!_hasError${tapIndex}) {\n`; - } - if (onResult) { - code += onResult(`_result${tapIndex}`); - } - if (onDone) { - code += onDone(); - } - if (!rethrowIfPossible) { - code += "}\n"; - } - break; - case "async": - let cbCode = ""; - if (onResult) - cbCode += `(function(_err${tapIndex}, _result${tapIndex}) {\n`; - else cbCode += `(function(_err${tapIndex}) {\n`; - cbCode += `if(_err${tapIndex}) {\n`; - cbCode += onError(`_err${tapIndex}`); - cbCode += "} else {\n"; - if (onResult) { - cbCode += onResult(`_result${tapIndex}`); - } - if (onDone) { - cbCode += onDone(); - } - cbCode += "}\n"; - cbCode += "})"; - code += `_fn${tapIndex}(${this.args({ - before: tap.context ? "_context" : undefined, - after: cbCode - })});\n`; - break; - case "promise": - code += `var _hasResult${tapIndex} = false;\n`; - code += `var _promise${tapIndex} = _fn${tapIndex}(${this.args({ - before: tap.context ? "_context" : undefined - })});\n`; - code += `if (!_promise${tapIndex} || !_promise${tapIndex}.then)\n`; - code += ` throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise${tapIndex} + ')');\n`; - code += `_promise${tapIndex}.then((function(_result${tapIndex}) {\n`; - code += `_hasResult${tapIndex} = true;\n`; - if (onResult) { - code += onResult(`_result${tapIndex}`); - } - if (onDone) { - code += onDone(); - } - code += `}), function(_err${tapIndex}) {\n`; - code += `if(_hasResult${tapIndex}) throw _err${tapIndex};\n`; - code += onError(`_err${tapIndex}`); - code += "});\n"; - break; - } - return code; - } + } = compilation; + const globalObject = runtimeTemplate.globalObject; + const { linkPreload, linkPrefetch } = + JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation); + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI); + const withLoading = this._runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withCallback = this._runtimeRequirements.has( + RuntimeGlobals.chunkCallback + ); + const withOnChunkLoad = this._runtimeRequirements.has( + RuntimeGlobals.onChunksLoaded + ); + const withHmr = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const withPrefetch = this._runtimeRequirements.has( + RuntimeGlobals.prefetchChunkHandlers + ); + const withPreload = this._runtimeRequirements.has( + RuntimeGlobals.preloadChunkHandlers + ); + const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( + chunkLoadingGlobal + )}]`; + const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); + const hasJsMatcher = compileBooleanMatcher(conditionMap); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); - callTapsSeries({ - onError, - onResult, - resultReturns, - onDone, - doneReturns, - rethrowIfPossible - }) { - if (this.options.taps.length === 0) return onDone(); - const firstAsync = this.options.taps.findIndex(t => t.type !== "sync"); - const somethingReturns = resultReturns || doneReturns; - let code = ""; - let current = onDone; - let unrollCounter = 0; - for (let j = this.options.taps.length - 1; j >= 0; j--) { - const i = j; - const unroll = - current !== onDone && - (this.options.taps[i].type !== "sync" || unrollCounter++ > 20); - if (unroll) { - unrollCounter = 0; - code += `function _next${i}() {\n`; - code += current(); - code += `}\n`; - current = () => `${somethingReturns ? "return " : ""}_next${i}();\n`; - } - const done = current; - const doneBreak = skipDone => { - if (skipDone) return ""; - return onDone(); - }; - const content = this.callTap(i, { - onError: error => onError(i, error, done, doneBreak), - onResult: - onResult && - (result => { - return onResult(i, result, done, doneBreak); - }), - onDone: !onResult && done, - rethrowIfPossible: - rethrowIfPossible && (firstAsync < 0 || i < firstAsync) - }); - current = () => content; - } - code += current(); - return code; - } + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_jsonp` + : undefined; - callTapsLooping({ onError, onDone, rethrowIfPossible }) { - if (this.options.taps.length === 0) return onDone(); - const syncOnly = this.options.taps.every(t => t.type === "sync"); - let code = ""; - if (!syncOnly) { - code += "var _looper = (function() {\n"; - code += "var _loopAsync = false;\n"; - } - code += "var _loop;\n"; - code += "do {\n"; - code += "_loop = false;\n"; - for (let i = 0; i < this.options.interceptors.length; i++) { - const interceptor = this.options.interceptors[i]; - if (interceptor.loop) { - code += `${this.getInterceptor(i)}.loop(${this.args({ - before: interceptor.context ? "_context" : undefined - })});\n`; - } - } - code += this.callTapsSeries({ - onError, - onResult: (i, result, next, doneBreak) => { - let code = ""; - code += `if(${result} !== undefined) {\n`; - code += "_loop = true;\n"; - if (!syncOnly) code += "if(_loopAsync) _looper();\n"; - code += doneBreak(true); - code += `} else {\n`; - code += next(); - code += `}\n`; - return code; - }, - onDone: - onDone && - (() => { - let code = ""; - code += "if(!_loop) {\n"; - code += onDone(); - code += "}\n"; - return code; - }), - rethrowIfPossible: rethrowIfPossible && syncOnly - }); - code += "} while(_loop);\n"; - if (!syncOnly) { - code += "_loopAsync = true;\n"; - code += "});\n"; - code += "_looper();\n"; - } - return code; + return Template.asString([ + withBaseURI + ? Template.asString([ + `${RuntimeGlobals.baseURI} = document.baseURI || self.location.href;` + ]) + : "// no baseURI", + "", + "// object to store loaded and loading chunks", + "// undefined = chunk not loaded, null = chunk preloaded/prefetched", + "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join( + ",\n" + ) + ), + "};", + "", + withLoading + ? Template.asString([ + `${fn}.j = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasJsMatcher !== false + ? Template.indent([ + "// JSONP chunk loading for javascript", + `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + "", + '// a Promise means "currently loading".', + "if(installedChunkData) {", + Template.indent([ + "promises.push(installedChunkData[2]);" + ]), + "} else {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent([ + "// setup Promise in chunk cache", + `var promise = new Promise(${runtimeTemplate.expressionFunction( + `installedChunkData = installedChunks[chunkId] = [resolve, reject]`, + "resolve, reject" + )});`, + "promises.push(installedChunkData[2] = promise);", + "", + "// start chunk loading", + `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, + "// create error before stack unwound to get useful stacktrace later", + "var error = new Error();", + `var loadingEnded = ${runtimeTemplate.basicFunction( + "event", + [ + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`, + Template.indent([ + "installedChunkData = installedChunks[chunkId];", + "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;", + "if(installedChunkData) {", + Template.indent([ + "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", + "var realSrc = event && event.target && event.target.src;", + "error.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realSrc;", + "installedChunkData[1](error);" + ]), + "}" + ]), + "}" + ] + )};`, + `${RuntimeGlobals.loadScript}(url, loadingEnded, "chunk-" + chunkId, chunkId);` + ]), + "} else installedChunks[chunkId] = 0;" + ]), + "}" + ]), + "}" + ]) + : Template.indent(["installedChunks[chunkId] = 0;"]) + )};` + ]) + : "// no chunk on demand loading", + "", + withPrefetch && hasJsMatcher !== false + ? `${ + RuntimeGlobals.prefetchChunkHandlers + }.j = ${runtimeTemplate.basicFunction("chunkId", [ + `if((!${ + RuntimeGlobals.hasOwnProperty + }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ + hasJsMatcher === true ? "true" : hasJsMatcher("chunkId") + }) {`, + Template.indent([ + "installedChunks[chunkId] = null;", + linkPrefetch.call( + Template.asString([ + "var link = document.createElement('link');", + crossOriginLoading + ? `link.crossOrigin = ${JSON.stringify( + crossOriginLoading + )};` + : "", + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + 'link.rel = "prefetch";', + 'link.as = "script";', + `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);` + ]), + chunk + ), + "document.head.appendChild(link);" + ]), + "}" + ])};` + : "// no prefetching", + "", + withPreload && hasJsMatcher !== false + ? `${ + RuntimeGlobals.preloadChunkHandlers + }.j = ${runtimeTemplate.basicFunction("chunkId", [ + `if((!${ + RuntimeGlobals.hasOwnProperty + }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ + hasJsMatcher === true ? "true" : hasJsMatcher("chunkId") + }) {`, + Template.indent([ + "installedChunks[chunkId] = null;", + linkPreload.call( + Template.asString([ + "var link = document.createElement('link');", + scriptType + ? `link.type = ${JSON.stringify(scriptType)};` + : "", + "link.charset = 'utf-8';", + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + 'link.rel = "preload";', + 'link.as = "script";', + `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, + crossOriginLoading + ? Template.asString([ + "if (link.href.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `link.crossOrigin = ${JSON.stringify( + crossOriginLoading + )};` + ), + "}" + ]) + : "" + ]), + chunk + ), + "document.head.appendChild(link);" + ]), + "}" + ])};` + : "// no preloaded", + "", + withHmr + ? Template.asString([ + "var currentUpdatedModulesList;", + "var waitingUpdateResolves = {};", + "function loadUpdateChunk(chunkId) {", + Template.indent([ + `return new Promise(${runtimeTemplate.basicFunction( + "resolve, reject", + [ + "waitingUpdateResolves[chunkId] = resolve;", + "// start update chunk loading", + `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`, + "// create error before stack unwound to get useful stacktrace later", + "var error = new Error();", + `var loadingEnded = ${runtimeTemplate.basicFunction("event", [ + "if(waitingUpdateResolves[chunkId]) {", + Template.indent([ + "waitingUpdateResolves[chunkId] = undefined", + "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", + "var realSrc = event && event.target && event.target.src;", + "error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realSrc;", + "reject(error);" + ]), + "}" + ])};`, + `${RuntimeGlobals.loadScript}(url, loadingEnded);` + ] + )});` + ]), + "}", + "", + `${globalObject}[${JSON.stringify( + hotUpdateGlobal + )}] = ${runtimeTemplate.basicFunction( + "chunkId, moreModules, runtime", + [ + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent([ + "currentUpdate[moduleId] = moreModules[moduleId];", + "if(currentUpdatedModulesList) currentUpdatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "if(runtime) currentUpdateRuntime.push(runtime);", + "if(waitingUpdateResolves[chunkId]) {", + Template.indent([ + "waitingUpdateResolves[chunkId]();", + "waitingUpdateResolves[chunkId] = undefined;" + ]), + "}" + ] + )};`, + "", + Template.getFunctionContent( + require('./JavascriptHotModuleReplacement.runtime.js') + ) + .replace(/\$key\$/g, "jsonp") + .replace(/\$installedChunks\$/g, "installedChunks") + .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") + .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) + .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) + .replace( + /\$ensureChunkHandlers\$/g, + RuntimeGlobals.ensureChunkHandlers + ) + .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) + .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) + .replace( + /\$hmrDownloadUpdateHandlers\$/g, + RuntimeGlobals.hmrDownloadUpdateHandlers + ) + .replace( + /\$hmrInvalidateModuleHandlers\$/g, + RuntimeGlobals.hmrInvalidateModuleHandlers + ) + ]) + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${ + RuntimeGlobals.hmrDownloadManifest + } = ${runtimeTemplate.basicFunction("", [ + 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");', + `return fetch(${RuntimeGlobals.publicPath} + ${ + RuntimeGlobals.getUpdateManifestFilename + }()).then(${runtimeTemplate.basicFunction("response", [ + "if(response.status === 404) return; // no update available", + 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);', + "return response.json();" + ])});` + ])};` + ]) + : "// no HMR manifest", + "", + withOnChunkLoad + ? `${ + RuntimeGlobals.onChunksLoaded + }.j = ${runtimeTemplate.returningFunction( + "installedChunks[chunkId] === 0", + "chunkId" + )};` + : "// no on chunks loaded", + "", + withCallback || withLoading + ? Template.asString([ + "// install a JSONP callback for chunk loading", + `var webpackJsonpCallback = ${runtimeTemplate.basicFunction( + "parentChunkLoadingFunction, data", + [ + runtimeTemplate.destructureArray( + ["chunkIds", "moreModules", "runtime"], + "data" + ), + '// add "moreModules" to the modules object,', + '// then flag all "chunkIds" as loaded and fire callback', + "var moduleId, chunkId, i = 0;", + `if(chunkIds.some(${runtimeTemplate.returningFunction( + "installedChunks[id] !== 0", + "id" + )})) {`, + Template.indent([ + "for(moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent( + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ), + "}" + ]), + "}", + "if(runtime) var result = runtime(__webpack_require__);" + ]), + "}", + "if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);", + "for(;i < chunkIds.length; i++) {", + Template.indent([ + "chunkId = chunkIds[i];", + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`, + Template.indent("installedChunks[chunkId][0]();"), + "}", + "installedChunks[chunkId] = 0;" + ]), + "}", + withOnChunkLoad + ? `return ${RuntimeGlobals.onChunksLoaded}(result);` + : "" + ] + )}`, + "", + `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, + "chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));", + "chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));" + ]) + : "// no jsonp function" + ]); } +} - callTapsParallel({ - onError, - onResult, - onDone, - rethrowIfPossible, - onTap = (i, run) => run() - }) { - if (this.options.taps.length <= 1) { - return this.callTapsSeries({ - onError, - onResult, - onDone, - rethrowIfPossible - }); - } - let code = ""; - code += "do {\n"; - code += `var _counter = ${this.options.taps.length};\n`; - if (onDone) { - code += "var _done = (function() {\n"; - code += onDone(); - code += "});\n"; - } - for (let i = 0; i < this.options.taps.length; i++) { - const done = () => { - if (onDone) return "if(--_counter === 0) _done();\n"; - else return "--_counter;"; - }; - const doneBreak = skipDone => { - if (skipDone || !onDone) return "_counter = 0;\n"; - else return "_counter = 0;\n_done();\n"; - }; - code += "if(_counter <= 0) break;\n"; - code += onTap( - i, - () => - this.callTap(i, { - onError: error => { - let code = ""; - code += "if(_counter > 0) {\n"; - code += onError(i, error, done, doneBreak); - code += "}\n"; - return code; - }, - onResult: - onResult && - (result => { - let code = ""; - code += "if(_counter > 0) {\n"; - code += onResult(i, result, done, doneBreak); - code += "}\n"; - return code; - }), - onDone: - !onResult && - (() => { - return done(); - }), - rethrowIfPossible - }), - done, - doneBreak - ); - } - code += "} while(false);\n"; - return code; - } +module.exports = JsonpChunkLoadingRuntimeModule; - args({ before, after } = {}) { - let allArgs = this._args; - if (before) allArgs = [before].concat(allArgs); - if (after) allArgs = allArgs.concat(after); - if (allArgs.length === 0) { - return ""; - } else { - return allArgs.join(", "); - } - } - getTapFn(idx) { - return `_x[${idx}]`; - } +/***/ }), - getTap(idx) { - return `_taps[${idx}]`; +/***/ 4607: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const ArrayPushCallbackChunkFormatPlugin = __webpack_require__(18535); +const EnableChunkLoadingPlugin = __webpack_require__(61291); +const JsonpChunkLoadingRuntimeModule = __webpack_require__(84154); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ + +class JsonpTemplatePlugin { + /** + * @deprecated use JsonpChunkLoadingRuntimeModule.getCompilationHooks instead + * @param {Compilation} compilation the compilation + * @returns {JsonpChunkLoadingRuntimeModule.JsonpCompilationPluginHooks} hooks + */ + static getCompilationHooks(compilation) { + return JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation); } - getInterceptor(idx) { - return `_interceptors[${idx}]`; + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.options.output.chunkLoading = "jsonp"; + new ArrayPushCallbackChunkFormatPlugin().apply(compiler); + new EnableChunkLoadingPlugin("jsonp").apply(compiler); } } -module.exports = HookCodeFactory; +module.exports = JsonpTemplatePlugin; /***/ }), -/***/ 5504: +/***/ 36243: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -140483,66 +145687,176 @@ module.exports = HookCodeFactory; */ + const util = __webpack_require__(73837); +const webpackOptionsSchemaCheck = __webpack_require__(10382); +const webpackOptionsSchema = __webpack_require__(73342); +const Compiler = __webpack_require__(70845); +const MultiCompiler = __webpack_require__(33370); +const WebpackOptionsApply = __webpack_require__(88422); +const { + applyWebpackOptionsDefaults, + applyWebpackOptionsBaseDefaults +} = __webpack_require__(92988); +const { getNormalizedWebpackOptions } = __webpack_require__(26693); +const NodeEnvironmentPlugin = __webpack_require__(7553); +const memoize = __webpack_require__(78676); -const defaultFactory = (key, hook) => hook; +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("./Compiler").WatchOptions} WatchOptions */ +/** @typedef {import("./MultiCompiler").MultiCompilerOptions} MultiCompilerOptions */ +/** @typedef {import("./MultiStats")} MultiStats */ +/** @typedef {import("./Stats")} Stats */ -class HookMap { - constructor(factory, name = undefined) { - this._map = new Map(); - this.name = name; - this._factory = factory; - this._interceptors = []; - } +const getValidateSchema = memoize(() => __webpack_require__(12047)); - get(key) { - return this._map.get(key); - } +/** + * @template T + * @callback Callback + * @param {Error=} err + * @param {T=} stats + * @returns {void} + */ - for(key) { - const hook = this.get(key); - if (hook !== undefined) { - return hook; - } - let newHook = this._factory(key); - const interceptors = this._interceptors; - for (let i = 0; i < interceptors.length; i++) { - newHook = interceptors[i].factory(key, newHook); +/** + * @param {ReadonlyArray} childOptions options array + * @param {MultiCompilerOptions} options options + * @returns {MultiCompiler} a multi-compiler + */ +const createMultiCompiler = (childOptions, options) => { + const compilers = childOptions.map(options => createCompiler(options)); + const compiler = new MultiCompiler(compilers, options); + for (const childCompiler of compilers) { + if (childCompiler.options.dependencies) { + compiler.setDependencies( + childCompiler, + childCompiler.options.dependencies + ); } - this._map.set(key, newHook); - return newHook; } + return compiler; +}; - intercept(interceptor) { - this._interceptors.push( - Object.assign( - { - factory: defaultFactory - }, - interceptor - ) - ); +/** + * @param {WebpackOptions} rawOptions options object + * @returns {Compiler} a compiler + */ +const createCompiler = rawOptions => { + const options = getNormalizedWebpackOptions(rawOptions); + applyWebpackOptionsBaseDefaults(options); + const compiler = new Compiler(options.context, options); + new NodeEnvironmentPlugin({ + infrastructureLogging: options.infrastructureLogging + }).apply(compiler); + if (Array.isArray(options.plugins)) { + for (const plugin of options.plugins) { + if (typeof plugin === "function") { + plugin.call(compiler, compiler); + } else { + plugin.apply(compiler); + } + } } -} + applyWebpackOptionsDefaults(options); + compiler.hooks.environment.call(); + compiler.hooks.afterEnvironment.call(); + new WebpackOptionsApply().process(options, compiler); + compiler.hooks.initialize.call(); + return compiler; +}; -HookMap.prototype.tap = util.deprecate(function(key, options, fn) { - return this.for(key).tap(options, fn); -}, "HookMap#tap(key,…) is deprecated. Use HookMap#for(key).tap(…) instead."); +/** + * @callback WebpackFunctionSingle + * @param {WebpackOptions} options options object + * @param {Callback=} callback callback + * @returns {Compiler} the compiler object + */ -HookMap.prototype.tapAsync = util.deprecate(function(key, options, fn) { - return this.for(key).tapAsync(options, fn); -}, "HookMap#tapAsync(key,…) is deprecated. Use HookMap#for(key).tapAsync(…) instead."); +/** + * @callback WebpackFunctionMulti + * @param {ReadonlyArray & MultiCompilerOptions} options options objects + * @param {Callback=} callback callback + * @returns {MultiCompiler} the multi compiler object + */ -HookMap.prototype.tapPromise = util.deprecate(function(key, options, fn) { - return this.for(key).tapPromise(options, fn); -}, "HookMap#tapPromise(key,…) is deprecated. Use HookMap#for(key).tapPromise(…) instead."); +const asArray = options => + Array.isArray(options) ? Array.from(options) : [options]; -module.exports = HookMap; +const webpack = /** @type {WebpackFunctionSingle & WebpackFunctionMulti} */ ( + /** + * @param {WebpackOptions | (ReadonlyArray & MultiCompilerOptions)} options options + * @param {Callback & Callback=} callback callback + * @returns {Compiler | MultiCompiler} + */ + (options, callback) => { + const create = () => { + if (!asArray(options).every(webpackOptionsSchemaCheck)) { + getValidateSchema()(webpackOptionsSchema, options); + util.deprecate( + () => {}, + "webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.", + "DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID" + )(); + } + /** @type {MultiCompiler|Compiler} */ + let compiler; + let watch = false; + /** @type {WatchOptions|WatchOptions[]} */ + let watchOptions; + if (Array.isArray(options)) { + /** @type {MultiCompiler} */ + compiler = createMultiCompiler( + options, + /** @type {MultiCompilerOptions} */ (options) + ); + watch = options.some(options => options.watch); + watchOptions = options.map(options => options.watchOptions || {}); + } else { + const webpackOptions = /** @type {WebpackOptions} */ (options); + /** @type {Compiler} */ + compiler = createCompiler(webpackOptions); + watch = webpackOptions.watch; + watchOptions = webpackOptions.watchOptions || {}; + } + return { compiler, watch, watchOptions }; + }; + if (callback) { + try { + const { compiler, watch, watchOptions } = create(); + if (watch) { + compiler.watch(watchOptions, callback); + } else { + compiler.run((err, stats) => { + compiler.close(err2 => { + callback(err || err2, stats); + }); + }); + } + return compiler; + } catch (err) { + process.nextTick(() => callback(err)); + return null; + } + } else { + const { compiler, watch } = create(); + if (watch) { + util.deprecate( + () => {}, + "A 'callback' argument needs to be provided to the 'webpack(options, callback)' function when the 'watch' option is set. There is no way to handle the 'watch' option without a callback.", + "DEP_WEBPACK_WATCH_WITHOUT_CALLBACK" + )(); + } + return compiler; + } + } +); + +module.exports = webpack; /***/ }), -/***/ 1081: +/***/ 54182: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -140552,118 +145866,335 @@ module.exports = HookMap; */ -const Hook = __webpack_require__(72258); - -class MultiHook { - constructor(hooks, name = undefined) { - this.hooks = hooks; - this.name = name; - } - - tap(options, fn) { - for (const hook of this.hooks) { - hook.tap(options, fn); - } - } - - tapAsync(options, fn) { - for (const hook of this.hooks) { - hook.tapAsync(options, fn); - } - } - tapPromise(options, fn) { - for (const hook of this.hooks) { - hook.tapPromise(options, fn); - } - } +const RuntimeGlobals = __webpack_require__(16475); +const StartupChunkDependenciesPlugin = __webpack_require__(22339); +const ImportScriptsChunkLoadingRuntimeModule = __webpack_require__(96952); - isUsed() { - for (const hook of this.hooks) { - if (hook.isUsed()) return true; - } - return false; - } +/** @typedef {import("../Compiler")} Compiler */ - intercept(interceptor) { - for (const hook of this.hooks) { - hook.intercept(interceptor); - } - } +class ImportScriptsChunkLoadingPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + new StartupChunkDependenciesPlugin({ + chunkLoading: "import-scripts", + asyncChunkLoading: true + }).apply(compiler); + compiler.hooks.thisCompilation.tap( + "ImportScriptsChunkLoadingPlugin", + compilation => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === "import-scripts"; + }; + const onceForChunkSet = new WeakSet(); + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + const withCreateScriptUrl = !!compilation.outputOptions.trustedTypes; + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + if (withCreateScriptUrl) { + set.add(RuntimeGlobals.createScriptUrl); + } + compilation.addRuntimeModule( + chunk, + new ImportScriptsChunkLoadingRuntimeModule(set, withCreateScriptUrl) + ); + }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("ImportScriptsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap("ImportScriptsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap("ImportScriptsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap("ImportScriptsChunkLoadingPlugin", handler); - withOptions(options) { - return new MultiHook( - this.hooks.map(h => h.withOptions(options)), - this.name + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("ImportScriptsChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getChunkScriptFilename); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap("ImportScriptsChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getChunkUpdateScriptFilename); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.hmrModuleData); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap("ImportScriptsChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getUpdateManifestFilename); + }); + } ); } } - -module.exports = MultiHook; +module.exports = ImportScriptsChunkLoadingPlugin; /***/ }), -/***/ 79106: +/***/ 96952: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const Hook = __webpack_require__(72258); -const HookCodeFactory = __webpack_require__(177); -class SyncBailHookCodeFactory extends HookCodeFactory { - content({ onError, onResult, resultReturns, onDone, rethrowIfPossible }) { - return this.callTapsSeries({ - onError: (i, err) => onError(err), - onResult: (i, result, next) => - `if(${result} !== undefined) {\n${onResult( - result - )};\n} else {\n${next()}}\n`, - resultReturns, - onDone, - rethrowIfPossible - }); - } -} +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(39722); +const { + getChunkFilenameTemplate, + chunkHasJs +} = __webpack_require__(89464); +const { getInitialChunkIds } = __webpack_require__(98124); +const compileBooleanMatcher = __webpack_require__(29404); +const { getUndoPath } = __webpack_require__(82186); -const factory = new SyncBailHookCodeFactory(); +class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { + constructor(runtimeRequirements, withCreateScriptUrl) { + super("importScripts chunk loading", RuntimeModule.STAGE_ATTACH); + this.runtimeRequirements = runtimeRequirements; + this._withCreateScriptUrl = withCreateScriptUrl; + } -const TAP_ASYNC = () => { - throw new Error("tapAsync is not supported on a SyncBailHook"); -}; + /** + * @returns {string} runtime code + */ + generate() { + const { + chunk, + chunkGraph, + compilation: { + runtimeTemplate, + outputOptions: { chunkLoadingGlobal, hotUpdateGlobal } + }, + _withCreateScriptUrl: withCreateScriptUrl + } = this; + const globalObject = runtimeTemplate.globalObject; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); + const withLoading = this.runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withHmr = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( + chunkLoadingGlobal + )}]`; + const hasJsMatcher = compileBooleanMatcher( + chunkGraph.getChunkConditionMap(chunk, chunkHasJs) + ); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); -const TAP_PROMISE = () => { - throw new Error("tapPromise is not supported on a SyncBailHook"); -}; + const outputName = this.compilation.getPath( + getChunkFilenameTemplate(chunk, this.compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath( + outputName, + this.compilation.outputOptions.path, + false + ); -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_importScripts` + : undefined; -function SyncBailHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = SyncBailHook; - hook.tapAsync = TAP_ASYNC; - hook.tapPromise = TAP_PROMISE; - hook.compile = COMPILE; - return hook; + return Template.asString([ + withBaseURI + ? Template.asString([ + `${RuntimeGlobals.baseURI} = self.location + ${JSON.stringify( + rootOutputDir ? "/../" + rootOutputDir : "" + )};` + ]) + : "// no baseURI", + "", + "// object to store loaded chunks", + '// "1" means "already loaded"', + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 1`).join( + ",\n" + ) + ), + "};", + "", + withLoading + ? Template.asString([ + "// importScripts chunk loading", + `var installChunk = ${runtimeTemplate.basicFunction("data", [ + runtimeTemplate.destructureArray( + ["chunkIds", "moreModules", "runtime"], + "data" + ), + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent( + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ), + "}" + ]), + "}", + "if(runtime) runtime(__webpack_require__);", + "while(chunkIds.length)", + Template.indent("installedChunks[chunkIds.pop()] = 1;"), + "parentChunkLoadingFunction(data);" + ])};` + ]) + : "// no chunk install function needed", + withLoading + ? Template.asString([ + `${fn}.i = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasJsMatcher !== false + ? [ + '// "1" is the signal for "already loaded"', + "if(!installedChunks[chunkId]) {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent( + `importScripts(${ + withCreateScriptUrl + ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId))` + : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId)` + });` + ), + "}" + ]), + "}" + ] + : "installedChunks[chunkId] = 1;" + )};`, + "", + `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, + "var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);", + "chunkLoadingGlobal.push = installChunk;" + ]) + : "// no chunk loading", + "", + withHmr + ? Template.asString([ + "function loadUpdateChunk(chunkId, updatedModulesList) {", + Template.indent([ + "var success = false;", + `${globalObject}[${JSON.stringify( + hotUpdateGlobal + )}] = ${runtimeTemplate.basicFunction("_, moreModules, runtime", [ + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent([ + "currentUpdate[moduleId] = moreModules[moduleId];", + "if(updatedModulesList) updatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "if(runtime) currentUpdateRuntime.push(runtime);", + "success = true;" + ])};`, + "// start update chunk loading", + `importScripts(${ + withCreateScriptUrl + ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId))` + : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)` + });`, + 'if(!success) throw new Error("Loading update chunk failed for unknown reason");' + ]), + "}", + "", + Template.getFunctionContent( + require('./JavascriptHotModuleReplacement.runtime.js') + ) + .replace(/\$key\$/g, "importScrips") + .replace(/\$installedChunks\$/g, "installedChunks") + .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") + .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) + .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) + .replace( + /\$ensureChunkHandlers\$/g, + RuntimeGlobals.ensureChunkHandlers + ) + .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) + .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) + .replace( + /\$hmrDownloadUpdateHandlers\$/g, + RuntimeGlobals.hmrDownloadUpdateHandlers + ) + .replace( + /\$hmrInvalidateModuleHandlers\$/g, + RuntimeGlobals.hmrInvalidateModuleHandlers + ) + ]) + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${ + RuntimeGlobals.hmrDownloadManifest + } = ${runtimeTemplate.basicFunction("", [ + 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");', + `return fetch(${RuntimeGlobals.publicPath} + ${ + RuntimeGlobals.getUpdateManifestFilename + }()).then(${runtimeTemplate.basicFunction("response", [ + "if(response.status === 404) return; // no update available", + 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);', + "return response.json();" + ])});` + ])};` + ]) + : "// no HMR manifest" + ]); + } } -SyncBailHook.prototype = null; - -module.exports = SyncBailHook; +module.exports = ImportScriptsChunkLoadingRuntimeModule; /***/ }), -/***/ 10533: +/***/ 68693: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -140673,192 +146204,239 @@ module.exports = SyncBailHook; */ -const Hook = __webpack_require__(72258); -const HookCodeFactory = __webpack_require__(177); -class SyncHookCodeFactory extends HookCodeFactory { - content({ onError, onDone, rethrowIfPossible }) { - return this.callTapsSeries({ - onError: (i, err) => onError(err), - onDone, - rethrowIfPossible - }); +const ArrayPushCallbackChunkFormatPlugin = __webpack_require__(18535); +const EnableChunkLoadingPlugin = __webpack_require__(61291); + +/** @typedef {import("../Compiler")} Compiler */ + +class WebWorkerTemplatePlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.options.output.chunkLoading = "import-scripts"; + new ArrayPushCallbackChunkFormatPlugin().apply(compiler); + new EnableChunkLoadingPlugin("import-scripts").apply(compiler); } } +module.exports = WebWorkerTemplatePlugin; -const factory = new SyncHookCodeFactory(); - -const TAP_ASYNC = () => { - throw new Error("tapAsync is not supported on a SyncHook"); -}; -const TAP_PROMISE = () => { - throw new Error("tapPromise is not supported on a SyncHook"); -}; +/***/ }), -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; +/***/ 50569: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -function SyncHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = SyncHook; - hook.tapAsync = TAP_ASYNC; - hook.tapPromise = TAP_PROMISE; - hook.compile = COMPILE; - return hook; -} +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ -SyncHook.prototype = null; +/** + * Module exports. + */ -module.exports = SyncHook; +module.exports = __webpack_require__(58750) /***/ }), -/***/ 95854: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 78585: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ -const Hook = __webpack_require__(72258); -const HookCodeFactory = __webpack_require__(177); -class SyncLoopHookCodeFactory extends HookCodeFactory { - content({ onError, onDone, rethrowIfPossible }) { - return this.callTapsLooping({ - onError: (i, err) => onError(err), - onDone, - rethrowIfPossible - }); - } -} +/** + * Module dependencies. + * @private + */ -const factory = new SyncLoopHookCodeFactory(); +var db = __webpack_require__(50569) +var extname = (__webpack_require__(71017).extname) -const TAP_ASYNC = () => { - throw new Error("tapAsync is not supported on a SyncLoopHook"); -}; +/** + * Module variables. + * @private + */ -const TAP_PROMISE = () => { - throw new Error("tapPromise is not supported on a SyncLoopHook"); -}; +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; +/** + * Module exports. + * @public + */ -function SyncLoopHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = SyncLoopHook; - hook.tapAsync = TAP_ASYNC; - hook.tapPromise = TAP_PROMISE; - hook.compile = COMPILE; - return hook; +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false } -SyncLoopHook.prototype = null; +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ -module.exports = SyncLoopHook; +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str -/***/ }), + if (!mime) { + return false + } -/***/ 60176: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return mime +} +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ -const Hook = __webpack_require__(72258); -const HookCodeFactory = __webpack_require__(177); +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } -class SyncWaterfallHookCodeFactory extends HookCodeFactory { - content({ onError, onResult, resultReturns, rethrowIfPossible }) { - return this.callTapsSeries({ - onError: (i, err) => onError(err), - onResult: (i, result, next) => { - let code = ""; - code += `if(${result} !== undefined) {\n`; - code += `${this._args[0]} = ${result};\n`; - code += `}\n`; - code += next(); - return code; - }, - onDone: () => onResult(this._args[0]), - doneReturns: resultReturns, - rethrowIfPossible - }); - } + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] } -const factory = new SyncWaterfallHookCodeFactory(); +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ -const TAP_ASYNC = () => { - throw new Error("tapAsync is not supported on a SyncWaterfallHook"); -}; +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } -const TAP_PROMISE = () => { - throw new Error("tapPromise is not supported on a SyncWaterfallHook"); -}; + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; + if (!extension) { + return false + } -function SyncWaterfallHook(args = [], name = undefined) { - if (args.length < 1) - throw new Error("Waterfall hooks must have at least one argument"); - const hook = new Hook(args, name); - hook.constructor = SyncWaterfallHook; - hook.tapAsync = TAP_ASYNC; - hook.tapPromise = TAP_PROMISE; - hook.compile = COMPILE; - return hook; + return exports.types[extension] || false } -SyncWaterfallHook.prototype = null; +/** + * Populate the extensions and types maps. + * @private + */ -module.exports = SyncWaterfallHook; +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions -/***/ }), + if (!exts || !exts.length) { + return + } -/***/ 6967: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // mime -> extensions + extensions[type] = exts -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) -exports.__esModule = true; -exports.SyncHook = __webpack_require__(10533); -exports.SyncBailHook = __webpack_require__(79106); -exports.SyncWaterfallHook = __webpack_require__(60176); -exports.SyncLoopHook = __webpack_require__(95854); -exports.AsyncParallelHook = __webpack_require__(45874); -exports.AsyncParallelBailHook = __webpack_require__(76297); -exports.AsyncSeriesHook = __webpack_require__(40436); -exports.AsyncSeriesBailHook = __webpack_require__(13633); -exports.AsyncSeriesLoopHook = __webpack_require__(34656); -exports.AsyncSeriesWaterfallHook = __webpack_require__(47794); -exports.HookMap = __webpack_require__(5504); -exports.MultiHook = __webpack_require__(1081); + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} /***/ }), @@ -141345,14 +146923,6 @@ module.exports = require("next/dist/build/webpack/plugins/terser-webpack-plugin" /***/ }), -/***/ 31988: -/***/ (function(module) { - -"use strict"; -module.exports = require("next/dist/compiled/acorn"); - -/***/ }), - /***/ 14907: /***/ (function(module) { From 038115cfae031fc091bd3d8c504b5201598eb64a Mon Sep 17 00:00:00 2001 From: Jiachi Liu Date: Wed, 26 Jan 2022 23:35:14 +0100 Subject: [PATCH 08/15] purge yarn lock --- packages/next/package.json | 1 - yarn.lock | 10 +++++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/packages/next/package.json b/packages/next/package.json index d66936dad338..40624c88c93c 100644 --- a/packages/next/package.json +++ b/packages/next/package.json @@ -162,7 +162,6 @@ "@types/ws": "8.2.0", "@vercel/ncc": "0.33.1", "@vercel/nft": "0.17.4", - "acorn": "8.5.0", "amphtml-validator": "1.0.33", "arg": "4.1.0", "assert": "2.0.0", diff --git a/yarn.lock b/yarn.lock index b376efc5417d..73f4e90b3c7c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5508,11 +5508,6 @@ acorn-walk@^8.0.0: resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.0.0.tgz#56ae4c0f434a45fff4a125e7ea95fa9c98f67a16" integrity sha512-oZRad/3SMOI/pxbbmqyurIx7jHw1wZDcR9G44L8pUVFEomX/0dH89SrM1KaDXuv1NpzAXz6Op/Xu/Qd5XXzdEA== -acorn@8.5.0, acorn@^8.4.1: - version "8.5.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.5.0.tgz#4512ccb99b3698c752591e9bb4472e38ad43cee2" - integrity sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q== - acorn@^6.2.1: version "6.4.2" resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.4.2.tgz#35866fd710528e92de10cf06016498e47e39e1e6" @@ -5546,6 +5541,11 @@ acorn@^8.2.4: resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.4.1.tgz#56c36251fc7cabc7096adc18f05afe814321a28c" integrity sha512-asabaBSkEKosYKMITunzX177CXxQ4Q8BSSzMTKD+FefUhipQC70gfW5SiUDhYQ3vk8G+81HqQk7Fv9OXwwn9KA== +acorn@^8.4.1: + version "8.5.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.5.0.tgz#4512ccb99b3698c752591e9bb4472e38ad43cee2" + integrity sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q== + acorn@^8.6.0: version "8.6.0" resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.6.0.tgz#e3692ba0eb1a0c83eaa4f37f5fa7368dd7142895" From 808b5313922149937f954e9d967371ff456f5ca9 Mon Sep 17 00:00:00 2001 From: Jiachi Liu Date: Thu, 27 Jan 2022 00:59:15 +0100 Subject: [PATCH 09/15] tune test case name --- .../react-streaming-and-server-components/test/index.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/integration/react-streaming-and-server-components/test/index.test.js b/test/integration/react-streaming-and-server-components/test/index.test.js index 9b556bcea3a5..a298254caaff 100644 --- a/test/integration/react-streaming-and-server-components/test/index.test.js +++ b/test/integration/react-streaming-and-server-components/test/index.test.js @@ -400,7 +400,7 @@ async function runBasicTests(context, env) { expect(imageTag.attr('src')).toContain('data:image') }) - it('should handle various exports', async () => { + it('should handle multiple named exports correctly', async () => { const clientExportsHTML = await renderViaHTTP( context.appPort, '/client-exports' From 3facefc20abdad4744f7c0b74a437d7d86ddac32 Mon Sep 17 00:00:00 2001 From: Donny Date: Thu, 27 Jan 2022 17:59:33 +0900 Subject: [PATCH 10/15] Use worker thread for serialization --- packages/next-swc/crates/napi/src/parse.rs | 76 +++++++++++----------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/packages/next-swc/crates/napi/src/parse.rs b/packages/next-swc/crates/napi/src/parse.rs index 382d28aeb873..ce8878e5c82d 100644 --- a/packages/next-swc/crates/napi/src/parse.rs +++ b/packages/next-swc/crates/napi/src/parse.rs @@ -1,56 +1,56 @@ use crate::{ - get_compiler, - util::{deserialize_json, CtxtExt, MapErr}, + get_compiler, + util::{deserialize_json, CtxtExt, MapErr}, }; use anyhow::Context as _; use napi::{CallContext, Either, Env, JsObject, JsString, JsUndefined, Task}; -use std::{sync::Arc}; -use swc::{try_with_handler, config::ParseOptions, Compiler}; +use std::sync::Arc; +use swc::{config::ParseOptions, try_with_handler, Compiler}; use swc_common::FileName; -use swc_ecmascript::ast::Program; pub struct ParseTask { - pub c: Arc, - pub filename: FileName, - pub src: String, - pub options: String, + pub c: Arc, + pub filename: FileName, + pub src: String, + pub options: String, } -pub fn complete_parse<'a>(env: &Env, program: Program, _c: &Compiler) -> napi::Result { - let s = serde_json::to_string(&program) - .context("failed to serialize Program") - .convert_err()?; - env.create_string_from_std(s) +pub fn complete_parse<'a>(env: &Env, ast_json: String, _c: &Compiler) -> napi::Result { + env.create_string_from_std(ast_json) } impl Task for ParseTask { - type Output = Program; - type JsValue = JsString; + type Output = String; + type JsValue = JsString; - fn compute(&mut self) -> napi::Result { - let options: ParseOptions = deserialize_json(&self.options).convert_err()?; - let fm = self - .c - .cm - .new_source_file(self.filename.clone(), self.src.clone()); - let program = try_with_handler(self.c.cm.clone(), false, |handler| { - self.c.parse_js( - fm, - &handler, - options.target, - options.syntax, - options.is_module, - options.comments, - ) - }) - .convert_err()?; + fn compute(&mut self) -> napi::Result { + let options: ParseOptions = deserialize_json(&self.options).convert_err()?; + let fm = self + .c + .cm + .new_source_file(self.filename.clone(), self.src.clone()); + let program = try_with_handler(self.c.cm.clone(), false, |handler| { + self.c.parse_js( + fm, + &handler, + options.target, + options.syntax, + options.is_module, + options.comments, + ) + }) + .convert_err()?; + + let ast_json = serde_json::to_string(&program) + .context("failed to serialize Program") + .convert_err()?; - Ok(program) - } + Ok(ast_json) + } - fn resolve(self, env: Env, result: Self::Output) -> napi::Result { - complete_parse(&env, result, &self.c) - } + fn resolve(self, env: Env, result: Self::Output) -> napi::Result { + complete_parse(&env, result, &self.c) + } } #[js_function(3)] From cb16b6aa3a07bb89460a077077618362e3301880 Mon Sep 17 00:00:00 2001 From: Donny Date: Thu, 27 Jan 2022 18:02:42 +0900 Subject: [PATCH 11/15] Use zero-based spans --- packages/next-swc/crates/napi/src/parse.rs | 28 +++++++++------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/packages/next-swc/crates/napi/src/parse.rs b/packages/next-swc/crates/napi/src/parse.rs index ce8878e5c82d..d89b6bd64d5c 100644 --- a/packages/next-swc/crates/napi/src/parse.rs +++ b/packages/next-swc/crates/napi/src/parse.rs @@ -1,21 +1,17 @@ -use crate::{ - get_compiler, - util::{deserialize_json, CtxtExt, MapErr}, -}; +use crate::util::{deserialize_json, CtxtExt, MapErr}; use anyhow::Context as _; use napi::{CallContext, Either, Env, JsObject, JsString, JsUndefined, Task}; use std::sync::Arc; -use swc::{config::ParseOptions, try_with_handler, Compiler}; -use swc_common::FileName; +use swc::{config::ParseOptions, try_with_handler}; +use swc_common::{FileName, FilePathMapping, SourceMap}; pub struct ParseTask { - pub c: Arc, pub filename: FileName, pub src: String, pub options: String, } -pub fn complete_parse<'a>(env: &Env, ast_json: String, _c: &Compiler) -> napi::Result { +pub fn complete_parse<'a>(env: &Env, ast_json: String) -> napi::Result { env.create_string_from_std(ast_json) } @@ -24,13 +20,13 @@ impl Task for ParseTask { type JsValue = JsString; fn compute(&mut self) -> napi::Result { + let c = swc::Compiler::new(Arc::new(SourceMap::new(FilePathMapping::empty()))); + let options: ParseOptions = deserialize_json(&self.options).convert_err()?; - let fm = self - .c - .cm - .new_source_file(self.filename.clone(), self.src.clone()); - let program = try_with_handler(self.c.cm.clone(), false, |handler| { - self.c.parse_js( + let fm = + c.cm.new_source_file(self.filename.clone(), self.src.clone()); + let program = try_with_handler(c.cm.clone(), false, |handler| { + c.parse_js( fm, &handler, options.target, @@ -49,13 +45,12 @@ impl Task for ParseTask { } fn resolve(self, env: Env, result: Self::Output) -> napi::Result { - complete_parse(&env, result, &self.c) + complete_parse(&env, result) } } #[js_function(3)] pub fn parse(ctx: CallContext) -> napi::Result { - let c = get_compiler(&ctx); let src = ctx.get_deserialized(0)?; let options = ctx.get_buffer_as_string(1)?; let filename = ctx.get::>(2)?; @@ -67,7 +62,6 @@ pub fn parse(ctx: CallContext) -> napi::Result { ctx.env .spawn(ParseTask { - c: c.clone(), filename, src, options, From 7f45560195c94e152f0dea1e21dc87a399713304 Mon Sep 17 00:00:00 2001 From: Jiachi Liu Date: Thu, 27 Jan 2022 12:19:18 +0100 Subject: [PATCH 12/15] remove toBuffer for src --- packages/next-swc/crates/napi/src/parse.rs | 2 +- packages/next/build/swc/index.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/next-swc/crates/napi/src/parse.rs b/packages/next-swc/crates/napi/src/parse.rs index d89b6bd64d5c..a6cb68a0291b 100644 --- a/packages/next-swc/crates/napi/src/parse.rs +++ b/packages/next-swc/crates/napi/src/parse.rs @@ -51,7 +51,7 @@ impl Task for ParseTask { #[js_function(3)] pub fn parse(ctx: CallContext) -> napi::Result { - let src = ctx.get_deserialized(0)?; + let src = ctx.get::(0)?.into_utf8()?.as_str()?.to_string(); let options = ctx.get_buffer_as_string(1)?; let filename = ctx.get::>(2)?; let filename = if let Either::A(value) = filename { diff --git a/packages/next/build/swc/index.js b/packages/next/build/swc/index.js index 677d782c762b..8998782147c3 100644 --- a/packages/next/build/swc/index.js +++ b/packages/next/build/swc/index.js @@ -184,7 +184,7 @@ function loadNative() { }, parse(src, options) { - return bindings.parse(toBuffer(src), toBuffer(options ?? {})) + return bindings.parse(src, toBuffer(options ?? {})) }, } return nativeBindings From 0d271b040bcdf353e00258665e7a3e3feaa1793d Mon Sep 17 00:00:00 2001 From: Jiachi Liu Date: Thu, 27 Jan 2022 15:21:10 +0100 Subject: [PATCH 13/15] keep pre-compiled acorn as external --- packages/next/compiled/@vercel/nft/index.js | 6 +- packages/next/compiled/acorn/LICENSE | 21 + packages/next/compiled/acorn/acorn.js | 1 + packages/next/compiled/acorn/package.json | 1 + packages/next/compiled/terser/bundle.min.js | 2 +- packages/next/compiled/webpack/bundle5.js | 5594 +------------------ packages/next/taskfile.js | 10 + packages/next/types/misc.d.ts | 4 + 8 files changed, 53 insertions(+), 5586 deletions(-) create mode 100644 packages/next/compiled/acorn/LICENSE create mode 100644 packages/next/compiled/acorn/acorn.js create mode 100644 packages/next/compiled/acorn/package.json diff --git a/packages/next/compiled/@vercel/nft/index.js b/packages/next/compiled/@vercel/nft/index.js index 047fab796424..734c300cf272 100644 --- a/packages/next/compiled/@vercel/nft/index.js +++ b/packages/next/compiled/@vercel/nft/index.js @@ -1,12 +1,12 @@ -(()=>{var __webpack_modules__={111:(e,t,r)=>{"use strict";e.exports=t;t.mockS3Http=r(7048).get_mockS3Http();t.mockS3Http("on");const s=t.mockS3Http("get");const a=r(7147);const o=r(1017);const u=r(1400);const c=r(9658);c.disableProgress();const f=r(5677);const p=r(2361).EventEmitter;const d=r(3837).inherits;const h=["clean","install","reinstall","build","rebuild","package","testpackage","publish","unpublish","info","testbinary","reveal","configure"];const v={};c.heading="node-pre-gyp";if(s){c.warn(`mocking s3 to ${process.env.node_pre_gyp_mock_s3}`)}Object.defineProperty(t,"find",{get:function(){return r(3093).find},enumerable:true});function Run({package_json_path:e="./package.json",argv:t}){this.package_json_path=e;this.commands={};const r=this;h.forEach((e=>{r.commands[e]=function(t,s){c.verbose("command",e,t);return require("./"+e)(r,t,s)}}));this.parseArgv(t);this.binaryHostSet=false}d(Run,p);t.Run=Run;const g=Run.prototype;g.package=r(9286);g.configDefs={help:Boolean,arch:String,debug:Boolean,directory:String,proxy:String,loglevel:String};g.shorthands={release:"--no-debug",C:"--directory",debug:"--debug",j:"--jobs",silent:"--loglevel=silent",silly:"--loglevel=silly",verbose:"--loglevel=verbose"};g.aliases=v;g.parseArgv=function parseOpts(e){this.opts=u(this.configDefs,this.shorthands,e);this.argv=this.opts.argv.remain.slice();const t=this.todo=[];e=this.argv.map((e=>{if(e in this.aliases){e=this.aliases[e]}return e}));e.slice().forEach((r=>{if(r in this.commands){const s=e.splice(0,e.indexOf(r));e.shift();if(t.length>0){t[t.length-1].args=s}t.push({name:r,args:[]})}}));if(t.length>0){t[t.length-1].args=e.splice(0)}let r=this.package_json_path;if(this.opts.directory){r=o.join(this.opts.directory,r)}this.package_json=JSON.parse(a.readFileSync(r));this.todo=f.expand_commands(this.package_json,this.opts,t);const s="npm_config_";Object.keys(process.env).forEach((e=>{if(e.indexOf(s)!==0)return;const t=process.env[e];if(e===s+"loglevel"){c.level=t}else{e=e.substring(s.length);if(e==="argv"){if(this.opts.argv&&this.opts.argv.remain&&this.opts.argv.remain.length){}else{this.opts[e]=t}}else{this.opts[e]=t}}}));if(this.opts.loglevel){c.level=this.opts.loglevel}c.resume()};g.setBinaryHostProperty=function(e){if(this.binaryHostSet){return this.package_json.binary.host}const t=this.package_json;if(!t||!t.binary||t.binary.host){return""}if(!t.binary.staging_host||!t.binary.production_host){return""}let r="production_host";if(e==="publish"){r="staging_host"}const s=process.env.node_pre_gyp_s3_host;if(s==="staging"||s==="production"){r=`${s}_host`}else if(this.opts["s3_host"]==="staging"||this.opts["s3_host"]==="production"){r=`${this.opts["s3_host"]}_host`}else if(this.opts["s3_host"]||s){throw new Error(`invalid s3_host ${this.opts["s3_host"]||s}`)}t.binary.host=t.binary[r];this.binaryHostSet=true;return t.binary.host};g.usage=function usage(){const e=[""," Usage: node-pre-gyp [options]",""," where is one of:",h.map((e=>" - "+e+" - "+require("./"+e).usage)).join("\n"),"","node-pre-gyp@"+this.version+" "+o.resolve(__dirname,".."),"node@"+process.versions.node].join("\n");return e};Object.defineProperty(g,"version",{get:function(){return this.package.version},enumerable:true})},3093:(e,t,r)=>{"use strict";const s=r(111);const a=r(302);const o=r(5677);const u=r(7147).existsSync||r(1017).existsSync;const c=r(1017);e.exports=t;t.usage="Finds the require path for the node-pre-gyp installed module";t.validate=function(e,t){a.validate_config(e,t)};t.find=function(e,t){if(!u(e)){throw new Error(e+"does not exist")}const r=new s.Run({package_json_path:e,argv:process.argv});r.setBinaryHostProperty();const f=r.package_json;a.validate_config(f,t);let p;if(o.get_napi_build_versions(f,t)){p=o.get_best_napi_build_version(f,t)}t=t||{};if(!t.module_root)t.module_root=c.dirname(e);const d=a.evaluate(f,t,p);return d.module}},5677:(e,t,r)=>{"use strict";const s=r(7147);e.exports=t;const a=process.version.substr(1).replace(/-.*$/,"").split(".").map((e=>+e));const o=["build","clean","configure","package","publish","reveal","testbinary","testpackage","unpublish"];const u="napi_build_version=";e.exports.get_napi_version=function(){let e=process.versions.napi;if(!e){if(a[0]===9&&a[1]>=3)e=2;else if(a[0]===8)e=1}return e};e.exports.get_napi_version_as_string=function(t){const r=e.exports.get_napi_version(t);return r?""+r:""};e.exports.validate_package_json=function(t,r){const s=t.binary;const a=pathOK(s.module_path);const o=pathOK(s.remote_path);const u=pathOK(s.package_name);const c=e.exports.get_napi_build_versions(t,r,true);const f=e.exports.get_napi_build_versions_raw(t);if(c){c.forEach((e=>{if(!(parseInt(e,10)===e&&e>0)){throw new Error("All values specified in napi_versions must be positive integers.")}}))}if(c&&(!a||!o&&!u)){throw new Error("When napi_versions is specified; module_path and either remote_path or "+"package_name must contain the substitution string '{napi_build_version}`.")}if((a||o||u)&&!f){throw new Error("When the substitution string '{napi_build_version}` is specified in "+"module_path, remote_path, or package_name; napi_versions must also be specified.")}if(c&&!e.exports.get_best_napi_build_version(t,r)&&e.exports.build_napi_only(t)){throw new Error("The Node-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports Node-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}if(f&&!c&&e.exports.build_napi_only(t)){throw new Error("The Node-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports Node-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}};function pathOK(e){return e&&(e.indexOf("{napi_build_version}")!==-1||e.indexOf("{node_napi_label}")!==-1)}e.exports.expand_commands=function(t,r,s){const a=[];const c=e.exports.get_napi_build_versions(t,r);s.forEach((s=>{if(c&&s.name==="install"){const o=e.exports.get_best_napi_build_version(t,r);const c=o?[u+o]:[];a.push({name:s.name,args:c})}else if(c&&o.indexOf(s.name)!==-1){c.forEach((e=>{const t=s.args.slice();t.push(u+e);a.push({name:s.name,args:t})}))}else{a.push(s)}}));return a};e.exports.get_napi_build_versions=function(t,s,a){const o=r(9658);let u=[];const c=e.exports.get_napi_version(s?s.target:undefined);if(t.binary&&t.binary.napi_versions){t.binary.napi_versions.forEach((e=>{const t=u.indexOf(e)!==-1;if(!t&&c&&e<=c){u.push(e)}else if(a&&!t&&c){o.info("This Node instance does not support builds for Node-API version",e)}}))}if(s&&s["build-latest-napi-version-only"]){let e=0;u.forEach((t=>{if(t>e)e=t}));u=e?[e]:[]}return u.length?u:undefined};e.exports.get_napi_build_versions_raw=function(e){const t=[];if(e.binary&&e.binary.napi_versions){e.binary.napi_versions.forEach((e=>{if(t.indexOf(e)===-1){t.push(e)}}))}return t.length?t:undefined};e.exports.get_command_arg=function(e){return u+e};e.exports.get_napi_build_version_from_command_args=function(e){for(let t=0;t{if(e>s&&e<=t){s=e}}))}return s===0?undefined:s};e.exports.build_napi_only=function(e){return e.binary&&e.binary.package_name&&e.binary.package_name.indexOf("{node_napi_label}")===-1}},7048:(e,t,r)=>{"use strict";e.exports=t;const s=r(7310);const a=r(7147);const o=r(1017);e.exports.detect=function(e,t){const r=e.hosted_path;const a=s.parse(r);t.prefix=!a.pathname||a.pathname==="/"?"":a.pathname.replace("/","");if(e.bucket&&e.region){t.bucket=e.bucket;t.region=e.region;t.endpoint=e.host;t.s3ForcePathStyle=e.s3ForcePathStyle}else{const e=a.hostname.split(".s3");const r=e[0];if(!r){return}if(!t.bucket){t.bucket=r}if(!t.region){const r=e[1].slice(1).split(".")[0];if(r==="amazonaws"){t.region="us-east-1"}else{t.region=r}}}};e.exports.get_s3=function(e){if(process.env.node_pre_gyp_mock_s3){const e=r(2722);const t=r(2037);e.config.basePath=`${t.tmpdir()}/mock`;const s=e.S3();const wcb=e=>(t,...r)=>{if(t&&t.code==="ENOENT"){t.code="NotFound"}return e(t,...r)};return{listObjects(e,t){return s.listObjects(e,wcb(t))},headObject(e,t){return s.headObject(e,wcb(t))},deleteObject(e,t){return s.deleteObject(e,wcb(t))},putObject(e,t){return s.putObject(e,wcb(t))}}}const t=r(918);t.config.update(e);const s=new t.S3;return{listObjects(e,t){return s.listObjects(e,t)},headObject(e,t){return s.headObject(e,t)},deleteObject(e,t){return s.deleteObject(e,t)},putObject(e,t){return s.putObject(e,t)}}};e.exports.get_mockS3Http=function(){let e=false;if(!process.env.node_pre_gyp_mock_s3){return()=>e}const t=r(3902);const s="https://mapbox-node-pre-gyp-public-testing-bucket.s3.us-east-1.amazonaws.com";const u=process.env.node_pre_gyp_mock_s3+"/mapbox-node-pre-gyp-public-testing-bucket";const mock_http=()=>{function get(e,t){const r=o.join(u,e.replace("%2B","+"));try{a.accessSync(r,a.constants.R_OK)}catch(e){return[404,"not found\n"]}return[200,a.createReadStream(r)]}return t(s).persist().get((()=>e)).reply(get)};mock_http(t,s,u);const mockS3Http=t=>{const r=e;if(t==="off"){e=false}else if(t==="on"){e=true}else if(t!=="get"){throw new Error(`illegal action for setMockHttp ${t}`)}return r};return mockS3Http}},302:(e,t,r)=>{"use strict";e.exports=t;const s=r(1017);const a=r(7849);const o=r(7310);const u=r(2157);const c=r(5677);let f;if(process.env.NODE_PRE_GYP_ABI_CROSSWALK){f=require(process.env.NODE_PRE_GYP_ABI_CROSSWALK)}else{f=r(2339)}const p={};Object.keys(f).forEach((e=>{const t=e.split(".")[0];if(!p[t]){p[t]=e}}));function get_electron_abi(e,t){if(!e){throw new Error("get_electron_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if electron is the target.")}const r=a.parse(t);return e+"-v"+r.major+"."+r.minor}e.exports.get_electron_abi=get_electron_abi;function get_node_webkit_abi(e,t){if(!e){throw new Error("get_node_webkit_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if node-webkit is the target.")}return e+"-v"+t}e.exports.get_node_webkit_abi=get_node_webkit_abi;function get_node_abi(e,t){if(!e){throw new Error("get_node_abi requires valid runtime arg")}if(!t){throw new Error("get_node_abi requires valid process.versions object")}const r=a.parse(t.node);if(r.major===0&&r.minor%2){return e+"-v"+t.node}else{return t.modules?e+"-v"+ +t.modules:"v8-"+t.v8.split(".").slice(0,2).join(".")}}e.exports.get_node_abi=get_node_abi;function get_runtime_abi(e,t){if(!e){throw new Error("get_runtime_abi requires valid runtime arg")}if(e==="node-webkit"){return get_node_webkit_abi(e,t||process.versions["node-webkit"])}else if(e==="electron"){return get_electron_abi(e,t||process.versions.electron)}else{if(e!=="node"){throw new Error("Unknown Runtime: '"+e+"'")}if(!t){return get_node_abi(e,process.versions)}else{let r;if(f[t]){r=f[t]}else{const e=t.split(".").map((e=>+e));if(e.length!==3){throw new Error("Unknown target version: "+t)}const s=e[0];let a=e[1];let o=e[2];if(s===1){while(true){if(a>0)--a;if(o>0)--o;const e=""+s+"."+a+"."+o;if(f[e]){r=f[e];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+e+" as ABI compatible target");break}if(a===0&&o===0){break}}}else if(s>=2){if(p[s]){r=f[p[s]];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+p[s]+" as ABI compatible target")}}else if(s===0){if(e[1]%2===0){while(--o>0){const e=""+s+"."+a+"."+o;if(f[e]){r=f[e];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+e+" as ABI compatible target");break}}}}}if(!r){throw new Error("Unsupported target version: "+t)}const s={node:t,v8:r.v8+".0",modules:r.node_abi>1?r.node_abi:undefined};return get_node_abi(e,s)}}}e.exports.get_runtime_abi=get_runtime_abi;const d=["module_name","module_path","host"];function validate_config(e,t){const r=e.name+" package.json is not node-pre-gyp ready:\n";const s=[];if(!e.main){s.push("main")}if(!e.version){s.push("version")}if(!e.name){s.push("name")}if(!e.binary){s.push("binary")}const a=e.binary;if(a){d.forEach((e=>{if(!a[e]||typeof a[e]!=="string"){s.push("binary."+e)}}))}if(s.length>=1){throw new Error(r+"package.json must declare these properties: \n"+s.join("\n"))}if(a){const e=o.parse(a.host).protocol;if(e==="http:"){throw new Error("'host' protocol ("+e+") is invalid - only 'https:' is accepted")}}c.validate_package_json(e,t)}e.exports.validate_config=validate_config;function eval_template(e,t){Object.keys(t).forEach((r=>{const s="{"+r+"}";while(e.indexOf(s)>-1){e=e.replace(s,t[r])}}));return e}function fix_slashes(e){if(e.slice(-1)!=="/"){return e+"/"}return e}function drop_double_slashes(e){return e.replace(/\/\//g,"/")}function get_process_runtime(e){let t="node";if(e["node-webkit"]){t="node-webkit"}else if(e.electron){t="electron"}return t}e.exports.get_process_runtime=get_process_runtime;const h="{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz";const v="";e.exports.evaluate=function(e,t,r){t=t||{};validate_config(e,t);const f=e.version;const p=a.parse(f);const d=t.runtime||get_process_runtime(process.versions);const g={name:e.name,configuration:t.debug?"Debug":"Release",debug:t.debug,module_name:e.binary.module_name,version:p.version,prerelease:p.prerelease.length?p.prerelease.join("."):"",build:p.build.length?p.build.join("."):"",major:p.major,minor:p.minor,patch:p.patch,runtime:d,node_abi:get_runtime_abi(d,t.target),node_abi_napi:c.get_napi_version(t.target)?"napi":get_runtime_abi(d,t.target),napi_version:c.get_napi_version(t.target),napi_build_version:r||"",node_napi_label:r?"napi-v"+r:get_runtime_abi(d,t.target),target:t.target||"",platform:t.target_platform||process.platform,target_platform:t.target_platform||process.platform,arch:t.target_arch||process.arch,target_arch:t.target_arch||process.arch,libc:t.target_libc||u.family||"unknown",module_main:e.main,toolset:t.toolset||"",bucket:e.binary.bucket,region:e.binary.region,s3ForcePathStyle:e.binary.s3ForcePathStyle||false};const m=g.module_name.replace("-","_");const _=process.env["npm_config_"+m+"_binary_host_mirror"]||e.binary.host;g.host=fix_slashes(eval_template(_,g));g.module_path=eval_template(e.binary.module_path,g);if(t.module_root){g.module_path=s.join(t.module_root,g.module_path)}else{g.module_path=s.resolve(g.module_path)}g.module=s.join(g.module_path,g.module_name+".node");g.remote_path=e.binary.remote_path?drop_double_slashes(fix_slashes(eval_template(e.binary.remote_path,g))):v;const y=e.binary.package_name?e.binary.package_name:h;g.package_name=eval_template(y,g);g.staged_tarball=s.join("build/stage",g.remote_path,g.package_name);g.hosted_path=o.resolve(g.host,g.remote_path);g.hosted_tarball=o.resolve(g.hosted_path,g.package_name);return g}},1400:(e,t,r)=>{var s=process.env.DEBUG_NOPT||process.env.NOPT_DEBUG?function(){console.error.apply(console,arguments)}:function(){};var a=r(7310),o=r(1017),u=r(2781).Stream,c=r(5920),f=r(2037);e.exports=t=nopt;t.clean=clean;t.typeDefs={String:{type:String,validate:validateString},Boolean:{type:Boolean,validate:validateBoolean},url:{type:a,validate:validateUrl},Number:{type:Number,validate:validateNumber},path:{type:o,validate:validatePath},Stream:{type:u,validate:validateStream},Date:{type:Date,validate:validateDate}};function nopt(e,r,a,o){a=a||process.argv;e=e||{};r=r||{};if(typeof o!=="number")o=2;s(e,r,a,o);a=a.slice(o);var u={},c,f={remain:[],cooked:a,original:a.slice(0)};parse(a,u,f.remain,e,r);clean(u,e,t.typeDefs);u.argv=f;Object.defineProperty(u.argv,"toString",{value:function(){return this.original.map(JSON.stringify).join(" ")},enumerable:false});return u}function clean(e,r,a){a=a||t.typeDefs;var o={},u=[false,true,null,String,Array];Object.keys(e).forEach((function(c){if(c==="argv")return;var f=e[c],p=Array.isArray(f),d=r[c];if(!p)f=[f];if(!d)d=u;if(d===Array)d=u.concat(Array);if(!Array.isArray(d))d=[d];s("val=%j",f);s("types=",d);f=f.map((function(u){if(typeof u==="string"){s("string %j",u);u=u.trim();if(u==="null"&&~d.indexOf(null)||u==="true"&&(~d.indexOf(true)||~d.indexOf(Boolean))||u==="false"&&(~d.indexOf(false)||~d.indexOf(Boolean))){u=JSON.parse(u);s("jsonable %j",u)}else if(~d.indexOf(Number)&&!isNaN(u)){s("convert to number",u);u=+u}else if(~d.indexOf(Date)&&!isNaN(Date.parse(u))){s("convert to date",u);u=new Date(u)}}if(!r.hasOwnProperty(c)){return u}if(u===false&&~d.indexOf(null)&&!(~d.indexOf(false)||~d.indexOf(Boolean))){u=null}var f={};f[c]=u;s("prevalidated val",f,u,r[c]);if(!validate(f,c,u,r[c],a)){if(t.invalidHandler){t.invalidHandler(c,u,r[c],e)}else if(t.invalidHandler!==false){s("invalid: "+c+"="+u,r[c])}return o}s("validated val",f,u,r[c]);return f[c]})).filter((function(e){return e!==o}));if(!f.length&&d.indexOf(Array)===-1){s("VAL HAS NO LENGTH, DELETE IT",f,c,d.indexOf(Array));delete e[c]}else if(p){s(p,e[c],f);e[c]=f}else e[c]=f[0];s("k=%s val=%j",c,f,e[c])}))}function validateString(e,t,r){e[t]=String(r)}function validatePath(e,t,r){if(r===true)return false;if(r===null)return true;r=String(r);var s=process.platform==="win32",a=s?/^~(\/|\\)/:/^~\//,u=f.homedir();if(u&&r.match(a)){e[t]=o.resolve(u,r.substr(2))}else{e[t]=o.resolve(r)}return true}function validateNumber(e,t,r){s("validate Number %j %j %j",t,r,isNaN(r));if(isNaN(r))return false;e[t]=+r}function validateDate(e,t,r){var a=Date.parse(r);s("validate Date %j %j %j",t,r,a);if(isNaN(a))return false;e[t]=new Date(r)}function validateBoolean(e,t,r){if(r instanceof Boolean)r=r.valueOf();else if(typeof r==="string"){if(!isNaN(r))r=!!+r;else if(r==="null"||r==="false")r=false;else r=true}else r=!!r;e[t]=r}function validateUrl(e,t,r){r=a.parse(String(r));if(!r.host)return false;e[t]=r.href}function validateStream(e,t,r){if(!(r instanceof u))return false;e[t]=r}function validate(e,t,r,a,o){if(Array.isArray(a)){for(var u=0,c=a.length;u1){var g=h.indexOf("=");if(g>-1){v=true;var m=h.substr(g+1);h=h.substr(0,g);e.splice(d,1,h,m)}var _=resolveShort(h,o,p,f);s("arg=%j shRes=%j",h,_);if(_){s(h,_);e.splice.apply(e,[d,1].concat(_));if(h!==_[0]){d--;continue}}h=h.replace(/^-+/,"");var y=null;while(h.toLowerCase().indexOf("no-")===0){y=!y;h=h.substr(3)}if(f[h])h=f[h];var x=a[h];var w=Array.isArray(x);if(w&&x.length===1){w=false;x=x[0]}var E=x===Array||w&&x.indexOf(Array)!==-1;if(!a.hasOwnProperty(h)&&t.hasOwnProperty(h)){if(!Array.isArray(t[h]))t[h]=[t[h]];E=true}var S,k=e[d+1];var A=typeof y==="boolean"||x===Boolean||w&&x.indexOf(Boolean)!==-1||typeof x==="undefined"&&!v||k==="false"&&(x===null||w&&~x.indexOf(null));if(A){S=!y;if(k==="true"||k==="false"){S=JSON.parse(k);k=null;if(y)S=!S;d++}if(w&&k){if(~x.indexOf(k)){S=k;d++}else if(k==="null"&&~x.indexOf(null)){S=null;d++}else if(!k.match(/^-{2,}[^-]/)&&!isNaN(k)&&~x.indexOf(Number)){S=+k;d++}else if(!k.match(/^-[^-]/)&&~x.indexOf(String)){S=k;d++}}if(E)(t[h]=t[h]||[]).push(S);else t[h]=S;continue}if(x===String){if(k===undefined){k=""}else if(k.match(/^-{1,2}[^-]+/)){k="";d--}}if(k&&k.match(/^-{2,}$/)){k=undefined;d--}S=k===undefined?true:k;if(E)(t[h]=t[h]||[]).push(S);else t[h]=S;d++;continue}r.push(h)}}function resolveShort(e,t,r,a){e=e.replace(/^-+/,"");if(a[e]===e)return null;if(t[e]){if(t[e]&&!Array.isArray(t[e]))t[e]=t[e].split(/\s+/);return t[e]}var o=t.___singles;if(!o){o=Object.keys(t).filter((function(e){return e.length===1})).reduce((function(e,t){e[t]=true;return e}),{});t.___singles=o;s("shorthand singles",o)}var u=e.split("").filter((function(e){return o[e]}));if(u.join("")===e)return u.map((function(e){return t[e]})).reduce((function(e,t){return e.concat(t)}),[]);if(a[e]&&!t[e])return null;if(r[e])e=r[e];if(t[e]&&!Array.isArray(t[e]))t[e]=t[e].split(/\s+/);return t[e]}},6286:(e,t,r)=>{const s=r(9491);const a=r(1017);const o=r(7147);let u=undefined;try{u=r(3535)}catch(e){}const c={nosort:true,silent:true};let f=0;const p=process.platform==="win32";const defaults=e=>{const t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach((t=>{e[t]=e[t]||o[t];t=t+"Sync";e[t]=e[t]||o[t]}));e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&u===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||c};const rimraf=(e,t,r)=>{if(typeof t==="function"){r=t;t={}}s(e,"rimraf: missing path");s.equal(typeof e,"string","rimraf: path should be a string");s.equal(typeof r,"function","rimraf: callback function required");s(t,"rimraf: invalid options argument provided");s.equal(typeof t,"object","rimraf: options should be object");defaults(t);let a=0;let o=null;let c=0;const next=e=>{o=o||e;if(--c===0)r(o)};const afterGlob=(e,s)=>{if(e)return r(e);c=s.length;if(c===0)return r();s.forEach((e=>{const CB=r=>{if(r){if((r.code==="EBUSY"||r.code==="ENOTEMPTY"||r.code==="EPERM")&&arimraf_(e,t,CB)),a*100)}if(r.code==="EMFILE"&&frimraf_(e,t,CB)),f++)}if(r.code==="ENOENT")r=null}f=0;next(r)};rimraf_(e,t,CB)}))};if(t.disableGlob||!u.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,((r,s)=>{if(!r)return afterGlob(null,[e]);u(e,t.glob,afterGlob)}))};const rimraf_=(e,t,r)=>{s(e);s(t);s(typeof r==="function");t.lstat(e,((s,a)=>{if(s&&s.code==="ENOENT")return r(null);if(s&&s.code==="EPERM"&&p)fixWinEPERM(e,t,s,r);if(a&&a.isDirectory())return rmdir(e,t,s,r);t.unlink(e,(s=>{if(s){if(s.code==="ENOENT")return r(null);if(s.code==="EPERM")return p?fixWinEPERM(e,t,s,r):rmdir(e,t,s,r);if(s.code==="EISDIR")return rmdir(e,t,s,r)}return r(s)}))}))};const fixWinEPERM=(e,t,r,a)=>{s(e);s(t);s(typeof a==="function");t.chmod(e,438,(s=>{if(s)a(s.code==="ENOENT"?null:r);else t.stat(e,((s,o)=>{if(s)a(s.code==="ENOENT"?null:r);else if(o.isDirectory())rmdir(e,t,r,a);else t.unlink(e,a)}))}))};const fixWinEPERMSync=(e,t,r)=>{s(e);s(t);try{t.chmodSync(e,438)}catch(e){if(e.code==="ENOENT")return;else throw r}let a;try{a=t.statSync(e)}catch(e){if(e.code==="ENOENT")return;else throw r}if(a.isDirectory())rmdirSync(e,t,r);else t.unlinkSync(e)};const rmdir=(e,t,r,a)=>{s(e);s(t);s(typeof a==="function");t.rmdir(e,(s=>{if(s&&(s.code==="ENOTEMPTY"||s.code==="EEXIST"||s.code==="EPERM"))rmkids(e,t,a);else if(s&&s.code==="ENOTDIR")a(r);else a(s)}))};const rmkids=(e,t,r)=>{s(e);s(t);s(typeof r==="function");t.readdir(e,((s,o)=>{if(s)return r(s);let u=o.length;if(u===0)return t.rmdir(e,r);let c;o.forEach((s=>{rimraf(a.join(e,s),t,(s=>{if(c)return;if(s)return r(c=s);if(--u===0)t.rmdir(e,r)}))}))}))};const rimrafSync=(e,t)=>{t=t||{};defaults(t);s(e,"rimraf: missing path");s.equal(typeof e,"string","rimraf: path should be a string");s(t,"rimraf: missing options");s.equal(typeof t,"object","rimraf: options should be object");let r;if(t.disableGlob||!u.hasMagic(e)){r=[e]}else{try{t.lstatSync(e);r=[e]}catch(s){r=u.sync(e,t.glob)}}if(!r.length)return;for(let e=0;e{s(e);s(t);try{t.rmdirSync(e)}catch(s){if(s.code==="ENOENT")return;if(s.code==="ENOTDIR")throw r;if(s.code==="ENOTEMPTY"||s.code==="EEXIST"||s.code==="EPERM")rmkidsSync(e,t)}};const rmkidsSync=(e,t)=>{s(e);s(t);t.readdirSync(e).forEach((r=>rimrafSync(a.join(e,r),t)));const r=p?100:1;let o=0;do{let s=true;try{const a=t.rmdirSync(e,t);s=false;return a}finally{if(++oe){return false}r+=t[s+1];if(r>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&c.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,p)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&f.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,p)||isInAstralSet(e,d)}var h=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new h(e,{beforeExpr:true,binop:t})}var v={beforeExpr:true},g={startsExpr:true};var m={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return m[e]=new h(e,t)}var _={num:new h("num",g),regexp:new h("regexp",g),string:new h("string",g),name:new h("name",g),privateId:new h("privateId",g),eof:new h("eof"),bracketL:new h("[",{beforeExpr:true,startsExpr:true}),bracketR:new h("]"),braceL:new h("{",{beforeExpr:true,startsExpr:true}),braceR:new h("}"),parenL:new h("(",{beforeExpr:true,startsExpr:true}),parenR:new h(")"),comma:new h(",",v),semi:new h(";",v),colon:new h(":",v),dot:new h("."),question:new h("?",v),questionDot:new h("?."),arrow:new h("=>",v),template:new h("template"),invalidTemplate:new h("invalidTemplate"),ellipsis:new h("...",v),backQuote:new h("`",g),dollarBraceL:new h("${",{beforeExpr:true,startsExpr:true}),eq:new h("=",{beforeExpr:true,isAssign:true}),assign:new h("_=",{beforeExpr:true,isAssign:true}),incDec:new h("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new h("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new h("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new h("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",v),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",v),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",v),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",g),_if:kw("if"),_return:kw("return",v),_switch:kw("switch"),_throw:kw("throw",v),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",g),_super:kw("super",g),_class:kw("class",g),_extends:kw("extends",v),_export:kw("export"),_import:kw("import",g),_null:kw("null",g),_true:kw("true",g),_false:kw("false",g),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var y=/\r\n?|\n|\u2028|\u2029/;var x=new RegExp(y.source,"g");function isNewLine(e){return e===10||e===13||e===8232||e===8233}var w=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var E=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var S=Object.prototype;var k=S.hasOwnProperty;var A=S.toString;function has(e,t){return k.call(e,t)}var C=Array.isArray||function(e){return A.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var R=function Position(e,t){this.line=e;this.column=t};R.prototype.offset=function offset(e){return new R(this.line,this.column+e)};var T=function SourceLocation(e,t,r){this.start=t;this.end=r;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var r=1,s=0;;){x.lastIndex=s;var a=x.exec(e);if(a&&a.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(C(t.onToken)){var s=t.onToken;t.onToken=function(e){return s.push(e)}}if(C(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(r,s,a,o,u,c){var f={type:r?"Block":"Line",value:s,start:a,end:o};if(e.locations){f.loc=new T(this,u,c)}if(e.ranges){f.range=[a,o]}t.push(f)}}var N=1,P=2,L=4,j=8,D=16,M=32,F=64,B=128,W=256,U=N|P|W;function functionFlags(e,t){return P|(e?L:0)|(t?j:0)}var V=0,q=1,H=2,$=3,G=4,K=5;var z=function Parser(e,r,a){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(s[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var o="";if(e.allowReserved!==true){o=t[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3];if(e.sourceType==="module"){o+=" await"}}this.reservedWords=wordsRegexp(o);var u=(o?o+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(u);this.reservedWordsStrictBind=wordsRegexp(u+" "+t.strictBind);this.input=String(r);this.containsEsc=false;if(a){this.pos=a;this.lineStart=this.input.lastIndexOf("\n",a-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(y).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=_.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.potentialArrowInForAwait=false;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports=Object.create(null);if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(N);this.regexpState=null;this.privateNameStack=[]};var Q={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},canAwait:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true},allowNewDotTarget:{configurable:true},inClassStaticBlock:{configurable:true}};z.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};Q.inFunction.get=function(){return(this.currentVarScope().flags&P)>0};Q.inGenerator.get=function(){return(this.currentVarScope().flags&j)>0&&!this.currentVarScope().inClassFieldInit};Q.inAsync.get=function(){return(this.currentVarScope().flags&L)>0&&!this.currentVarScope().inClassFieldInit};Q.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&W){return false}if(t.flags&P){return(t.flags&L)>0}}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};Q.allowSuper.get=function(){var e=this.currentThisScope();var t=e.flags;var r=e.inClassFieldInit;return(t&F)>0||r||this.options.allowSuperOutsideMethod};Q.allowDirectSuper.get=function(){return(this.currentThisScope().flags&B)>0};Q.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};Q.allowNewDotTarget.get=function(){var e=this.currentThisScope();var t=e.flags;var r=e.inClassFieldInit;return(t&(P|W))>0||r};Q.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&W)>0};z.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var r=this;for(var s=0;s=,?^&]/.test(a)||a==="!"&&this.input.charAt(s+1)==="=")}e+=t[0].length;E.lastIndex=e;e+=E.exec(this.input)[0].length;if(this.input[e]===";"){e++}}};Y.eat=function(e){if(this.type===e){this.next();return true}else{return false}};Y.isContextual=function(e){return this.type===_.name&&this.value===e&&!this.containsEsc};Y.eatContextual=function(e){if(!this.isContextual(e)){return false}this.next();return true};Y.expectContextual=function(e){if(!this.eatContextual(e)){this.unexpected()}};Y.canInsertSemicolon=function(){return this.type===_.eof||this.type===_.braceR||y.test(this.input.slice(this.lastTokEnd,this.start))};Y.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};Y.semicolon=function(){if(!this.eat(_.semi)&&!this.insertSemicolon()){this.unexpected()}};Y.afterTrailingComma=function(e,t){if(this.type===e){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!t){this.next()}return true}};Y.expect=function(e){this.eat(e)||this.unexpected()};Y.unexpected=function(e){this.raise(e!=null?e:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}Y.checkPatternErrors=function(e,t){if(!e){return}if(e.trailingComma>-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var r=t?e.parenthesizedAssign:e.parenthesizedBind;if(r>-1){this.raiseRecoverable(r,"Parenthesized pattern")}};Y.checkExpressionErrors=function(e,t){if(!e){return false}var r=e.shorthandAssign;var s=e.doubleProto;if(!t){return r>=0||s>=0}if(r>=0){this.raise(r,"Shorthand property assignments are valid only in destructuring patterns")}if(s>=0){this.raiseRecoverable(s,"Redefinition of __proto__ property")}};Y.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&s<56320){return true}if(e){return false}if(s===123){return true}if(isIdentifierStart(s,true)){var o=r+1;while(isIdentifierChar(s=this.input.charCodeAt(o),true)){++o}if(s===92||s>55295&&s<56320){return true}var u=this.input.slice(r,o);if(!a.test(u)){return true}}return false};Z.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async")){return false}E.lastIndex=this.pos;var e=E.exec(this.input);var t=this.pos+e[0].length,r;return!y.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)==="function"&&(t+8===this.input.length||!(isIdentifierChar(r=this.input.charCodeAt(t+8))||r>55295&&r<56320))};Z.parseStatement=function(e,t,r){var s=this.type,a=this.startNode(),o;if(this.isLet(e)){s=_._var;o="let"}switch(s){case _._break:case _._continue:return this.parseBreakContinueStatement(a,s.keyword);case _._debugger:return this.parseDebuggerStatement(a);case _._do:return this.parseDoStatement(a);case _._for:return this.parseForStatement(a);case _._function:if(e&&(this.strict||e!=="if"&&e!=="label")&&this.options.ecmaVersion>=6){this.unexpected()}return this.parseFunctionStatement(a,false,!e);case _._class:if(e){this.unexpected()}return this.parseClass(a,true);case _._if:return this.parseIfStatement(a);case _._return:return this.parseReturnStatement(a);case _._switch:return this.parseSwitchStatement(a);case _._throw:return this.parseThrowStatement(a);case _._try:return this.parseTryStatement(a);case _._const:case _._var:o=o||this.value;if(e&&o!=="var"){this.unexpected()}return this.parseVarStatement(a,o);case _._while:return this.parseWhileStatement(a);case _._with:return this.parseWithStatement(a);case _.braceL:return this.parseBlock(true,a);case _.semi:return this.parseEmptyStatement(a);case _._export:case _._import:if(this.options.ecmaVersion>10&&s===_._import){E.lastIndex=this.pos;var u=E.exec(this.input);var c=this.pos+u[0].length,f=this.input.charCodeAt(c);if(f===40||f===46){return this.parseExpressionStatement(a,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return s===_._import?this.parseImport(a):this.parseExport(a,r);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(a,true,!e)}var p=this.value,d=this.parseExpression();if(s===_.name&&d.type==="Identifier"&&this.eat(_.colon)){return this.parseLabeledStatement(a,p,d,e)}else{return this.parseExpressionStatement(a,d)}}};Z.parseBreakContinueStatement=function(e,t){var r=t==="break";this.next();if(this.eat(_.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==_.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var s=0;for(;s=6){this.eat(_.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};Z.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(J);this.enterScope(0);this.expect(_.parenL);if(this.type===_.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var r=this.isLet();if(this.type===_._var||this.type===_._const||r){var s=this.startNode(),a=r?"let":this.value;this.next();this.parseVar(s,true,a);this.finishNode(s,"VariableDeclaration");if((this.type===_._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&s.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===_._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,s)}if(t>-1){this.unexpected(t)}return this.parseFor(e,s)}var o=this.isContextual("let"),u=false;var c=new DestructuringErrors;var f=this.parseExpression(t>-1?"await":true,c);if(this.type===_._in||(u=this.options.ecmaVersion>=6&&this.isContextual("of"))){if(this.options.ecmaVersion>=9){if(this.type===_._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}if(o&&u){this.raise(f.start,"The left-hand side of a for-of loop may not start with 'let'.")}this.toAssignable(f,false,c);this.checkLValPattern(f);return this.parseForIn(e,f)}else{this.checkExpressionErrors(c,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,f)};Z.parseFunctionStatement=function(e,t,r){this.next();return this.parseFunction(e,ie|(r?0:re),false,t)};Z.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(_._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};Z.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(_.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};Z.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(_.braceL);this.labels.push(ee);this.enterScope(0);var t;for(var r=false;this.type!==_.braceR;){if(this.type===_._case||this.type===_._default){var s=this.type===_._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(s){t.test=this.parseExpression()}else{if(r){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}r=true;t.test=null}this.expect(_.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};Z.parseThrowStatement=function(e){this.next();if(y.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var te=[];Z.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===_._catch){var t=this.startNode();this.next();if(this.eat(_.parenL)){t.param=this.parseBindingAtom();var r=t.param.type==="Identifier";this.enterScope(r?M:0);this.checkLValPattern(t.param,r?G:H);this.expect(_.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(_._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};Z.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};Z.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(J);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};Z.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};Z.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};Z.parseLabeledStatement=function(e,t,r,s){for(var a=0,o=this.labels;a=0;f--){var p=this.labels[f];if(p.statementStart===e.start){p.statementStart=this.start;p.kind=c}else{break}}this.labels.push({name:t,kind:c,statementStart:this.start});e.body=this.parseStatement(s?s.indexOf("label")===-1?s+"label":s:"label");this.labels.pop();e.label=r;return this.finishNode(e,"LabeledStatement")};Z.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};Z.parseBlock=function(e,t,r){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(_.braceL);if(e){this.enterScope(0)}while(this.type!==_.braceR){var s=this.parseStatement(null);t.body.push(s)}if(r){this.strict=false}this.next();if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};Z.parseFor=function(e,t){e.init=t;this.expect(_.semi);e.test=this.type===_.semi?null:this.parseExpression();this.expect(_.semi);e.update=this.type===_.parenR?null:this.parseExpression();this.expect(_.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};Z.parseForIn=function(e,t){var r=this.type===_._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!r||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(r?"for-in":"for-of")+" loop variable declaration may not have an initializer")}e.left=t;e.right=r?this.parseExpression():this.parseMaybeAssign();this.expect(_.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,r?"ForInStatement":"ForOfStatement")};Z.parseVar=function(e,t,r){e.declarations=[];e.kind=r;for(;;){var s=this.startNode();this.parseVarId(s,r);if(this.eat(_.eq)){s.init=this.parseMaybeAssign(t)}else if(r==="const"&&!(this.type===_._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(s.id.type!=="Identifier"&&!(t&&(this.type===_._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{s.init=null}e.declarations.push(this.finishNode(s,"VariableDeclarator"));if(!this.eat(_.comma)){break}}return e};Z.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLValPattern(e.id,t==="var"?q:H,false)};var ie=1,re=2,ne=4;Z.parseFunction=function(e,t,r,s,a){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!s){if(this.type===_.star&&t&re){this.unexpected()}e.generator=this.eat(_.star)}if(this.options.ecmaVersion>=8){e.async=!!s}if(t&ie){e.id=t&ne&&this.type!==_.name?null:this.parseIdent();if(e.id&&!(t&re)){this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?q:H:$)}}var o=this.yieldPos,u=this.awaitPos,c=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&ie)){e.id=this.type===_.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,r,false,a);this.yieldPos=o;this.awaitPos=u;this.awaitIdentPos=c;return this.finishNode(e,t&ie?"FunctionDeclaration":"FunctionExpression")};Z.parseFunctionParams=function(e){this.expect(_.parenL);e.params=this.parseBindingList(_.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};Z.parseClass=function(e,t){this.next();var r=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var s=this.enterClassBody();var a=this.startNode();var o=false;a.body=[];this.expect(_.braceL);while(this.type!==_.braceR){var u=this.parseClassElement(e.superClass!==null);if(u){a.body.push(u);if(u.type==="MethodDefinition"&&u.kind==="constructor"){if(o){this.raise(u.start,"Duplicate constructor in the same class")}o=true}else if(u.key&&u.key.type==="PrivateIdentifier"&&isPrivateNameConflicted(s,u)){this.raiseRecoverable(u.key.start,"Identifier '#"+u.key.name+"' has already been declared")}}}this.strict=r;this.next();e.body=this.finishNode(a,"ClassBody");this.exitClassBody();return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};Z.parseClassElement=function(e){if(this.eat(_.semi)){return null}var t=this.options.ecmaVersion;var r=this.startNode();var s="";var a=false;var o=false;var u="method";var c=false;if(this.eatContextual("static")){if(t>=13&&this.eat(_.braceL)){this.parseClassStaticBlock(r);return r}if(this.isClassElementNameStart()||this.type===_.star){c=true}else{s="static"}}r.static=c;if(!s&&t>=8&&this.eatContextual("async")){if((this.isClassElementNameStart()||this.type===_.star)&&!this.canInsertSemicolon()){o=true}else{s="async"}}if(!s&&(t>=9||!o)&&this.eat(_.star)){a=true}if(!s&&!o&&!a){var f=this.value;if(this.eatContextual("get")||this.eatContextual("set")){if(this.isClassElementNameStart()){u=f}else{s=f}}}if(s){r.computed=false;r.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc);r.key.name=s;this.finishNode(r.key,"Identifier")}else{this.parseClassElementName(r)}if(t<13||this.type===_.parenL||u!=="method"||a||o){var p=!r.static&&checkKeyName(r,"constructor");var d=p&&e;if(p&&u!=="method"){this.raise(r.key.start,"Constructor can't have get/set modifier")}r.kind=p?"constructor":u;this.parseClassMethod(r,a,o,d)}else{this.parseClassField(r)}return r};Z.isClassElementNameStart=function(){return this.type===_.name||this.type===_.privateId||this.type===_.num||this.type===_.string||this.type===_.bracketL||this.type.keyword};Z.parseClassElementName=function(e){if(this.type===_.privateId){if(this.value==="constructor"){this.raise(this.start,"Classes can't have an element named '#constructor'")}e.computed=false;e.key=this.parsePrivateIdent()}else{this.parsePropertyName(e)}};Z.parseClassMethod=function(e,t,r,s){var a=e.key;if(e.kind==="constructor"){if(t){this.raise(a.start,"Constructor can't be a generator")}if(r){this.raise(a.start,"Constructor can't be an async method")}}else if(e.static&&checkKeyName(e,"prototype")){this.raise(a.start,"Classes may not have a static property named prototype")}var o=e.value=this.parseMethod(t,r,s);if(e.kind==="get"&&o.params.length!==0){this.raiseRecoverable(o.start,"getter should have no params")}if(e.kind==="set"&&o.params.length!==1){this.raiseRecoverable(o.start,"setter should have exactly one param")}if(e.kind==="set"&&o.params[0].type==="RestElement"){this.raiseRecoverable(o.params[0].start,"Setter cannot use rest params")}return this.finishNode(e,"MethodDefinition")};Z.parseClassField=function(e){if(checkKeyName(e,"constructor")){this.raise(e.key.start,"Classes can't have a field named 'constructor'")}else if(e.static&&checkKeyName(e,"prototype")){this.raise(e.key.start,"Classes can't have a static field named 'prototype'")}if(this.eat(_.eq)){var t=this.currentThisScope();var r=t.inClassFieldInit;t.inClassFieldInit=true;e.value=this.parseMaybeAssign();t.inClassFieldInit=r}else{e.value=null}this.semicolon();return this.finishNode(e,"PropertyDefinition")};Z.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;this.labels=[];this.enterScope(W|F);while(this.type!==_.braceR){var r=this.parseStatement(null);e.body.push(r)}this.next();this.exitScope();this.labels=t;return this.finishNode(e,"StaticBlock")};Z.parseClassId=function(e,t){if(this.type===_.name){e.id=this.parseIdent();if(t){this.checkLValSimple(e.id,H,false)}}else{if(t===true){this.unexpected()}e.id=null}};Z.parseClassSuper=function(e){e.superClass=this.eat(_._extends)?this.parseExprSubscripts(false):null};Z.enterClassBody=function(){var e={declared:Object.create(null),used:[]};this.privateNameStack.push(e);return e.declared};Z.exitClassBody=function(){var e=this.privateNameStack.pop();var t=e.declared;var r=e.used;var s=this.privateNameStack.length;var a=s===0?null:this.privateNameStack[s-1];for(var o=0;o=11){if(this.eatContextual("as")){e.exported=this.parseIdent(true);this.checkExport(t,e.exported.name,this.lastTokStart)}else{e.exported=null}}this.expectContextual("from");if(this.type!==_.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(_._default)){this.checkExport(t,"default",this.lastTokStart);var r;if(this.type===_._function||(r=this.isAsyncFunction())){var s=this.startNode();this.next();if(r){this.next()}e.declaration=this.parseFunction(s,ie|ne,false,r)}else if(this.type===_._class){var a=this.startNode();e.declaration=this.parseClass(a,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==_.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var o=0,u=e.specifiers;o=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(r){this.checkPatternErrors(r,true)}for(var s=0,a=e.properties;s=8&&!u&&c.name==="async"&&!this.canInsertSemicolon()&&this.eat(_._function)){this.overrideContext(oe.f_expr);return this.parseFunction(this.startNodeAt(a,o),0,false,true,t)}if(s&&!this.canInsertSemicolon()){if(this.eat(_.arrow)){return this.parseArrowExpression(this.startNodeAt(a,o),[c],false,t)}if(this.options.ecmaVersion>=8&&c.name==="async"&&this.type===_.name&&!u&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc)){c=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(_.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(a,o),[c],true,t)}}return c;case _.regexp:var f=this.value;r=this.parseLiteral(f.value);r.regex={pattern:f.pattern,flags:f.flags};return r;case _.num:case _.string:return this.parseLiteral(this.value);case _._null:case _._true:case _._false:r=this.startNode();r.value=this.type===_._null?null:this.type===_._true;r.raw=this.type.keyword;this.next();return this.finishNode(r,"Literal");case _.parenL:var p=this.start,d=this.parseParenAndDistinguishExpression(s,t);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(d)){e.parenthesizedAssign=p}if(e.parenthesizedBind<0){e.parenthesizedBind=p}}return d;case _.bracketL:r=this.startNode();this.next();r.elements=this.parseExprList(_.bracketR,true,true,e);return this.finishNode(r,"ArrayExpression");case _.braceL:this.overrideContext(oe.b_expr);return this.parseObj(false,e);case _._function:r=this.startNode();this.next();return this.parseFunction(r,0);case _._class:return this.parseClass(this.startNode(),false);case _._new:return this.parseNew();case _.backQuote:return this.parseTemplate();case _._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};ue.parseExprImport=function(){var e=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var t=this.parseIdent(true);switch(this.type){case _.parenL:return this.parseDynamicImport(e);case _.dot:e.meta=t;return this.parseImportMeta(e);default:this.unexpected()}};ue.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(_.parenR)){var t=this.start;if(this.eat(_.comma)&&this.eat(_.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};ue.parseImportMeta=function(e){this.next();var t=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="meta"){this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'")}if(t){this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere){this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(e,"MetaProperty")};ue.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(t,"Literal")};ue.parseParenExpression=function(){this.expect(_.parenL);var e=this.parseExpression();this.expect(_.parenR);return e};ue.parseParenAndDistinguishExpression=function(e,t){var r=this.start,s=this.startLoc,a,o=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var u=this.start,c=this.startLoc;var f=[],p=true,d=false;var h=new DestructuringErrors,v=this.yieldPos,g=this.awaitPos,m;this.yieldPos=0;this.awaitPos=0;while(this.type!==_.parenR){p?p=false:this.expect(_.comma);if(o&&this.afterTrailingComma(_.parenR,true)){d=true;break}else if(this.type===_.ellipsis){m=this.start;f.push(this.parseParenItem(this.parseRestBinding()));if(this.type===_.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{f.push(this.parseMaybeAssign(false,h,this.parseParenItem))}}var y=this.lastTokEnd,x=this.lastTokEndLoc;this.expect(_.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(_.arrow)){this.checkPatternErrors(h,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=v;this.awaitPos=g;return this.parseParenArrowList(r,s,f,t)}if(!f.length||d){this.unexpected(this.lastTokStart)}if(m){this.unexpected(m)}this.checkExpressionErrors(h,true);this.yieldPos=v||this.yieldPos;this.awaitPos=g||this.awaitPos;if(f.length>1){a=this.startNodeAt(u,c);a.expressions=f;this.finishNodeAt(a,"SequenceExpression",y,x)}else{a=f[0]}}else{a=this.parseParenExpression()}if(this.options.preserveParens){var w=this.startNodeAt(r,s);w.expression=a;return this.finishNode(w,"ParenthesizedExpression")}else{return a}};ue.parseParenItem=function(e){return e};ue.parseParenArrowList=function(e,t,r,s){return this.parseArrowExpression(this.startNodeAt(e,t),r,false,s)};var ce=[];ue.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(_.dot)){e.meta=t;var r=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"){this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'")}if(r){this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters")}if(!this.allowNewDotTarget){this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block")}return this.finishNode(e,"MetaProperty")}var s=this.start,a=this.startLoc,o=this.type===_._import;e.callee=this.parseSubscripts(this.parseExprAtom(),s,a,true,false);if(o&&e.callee.type==="ImportExpression"){this.raise(s,"Cannot use new with import()")}if(this.eat(_.parenL)){e.arguments=this.parseExprList(_.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=ce}return this.finishNode(e,"NewExpression")};ue.parseTemplateElement=function(e){var t=e.isTagged;var r=this.startNode();if(this.type===_.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}r.value={raw:this.value,cooked:null}}else{r.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();r.tail=this.type===_.backQuote;return this.finishNode(r,"TemplateElement")};ue.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var r=this.startNode();this.next();r.expressions=[];var s=this.parseTemplateElement({isTagged:t});r.quasis=[s];while(!s.tail){if(this.type===_.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(_.dollarBraceL);r.expressions.push(this.parseExpression());this.expect(_.braceR);r.quasis.push(s=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(r,"TemplateLiteral")};ue.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===_.name||this.type===_.num||this.type===_.string||this.type===_.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===_.star)&&!y.test(this.input.slice(this.lastTokEnd,this.start))};ue.parseObj=function(e,t){var r=this.startNode(),s=true,a={};r.properties=[];this.next();while(!this.eat(_.braceR)){if(!s){this.expect(_.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(_.braceR)){break}}else{s=false}var o=this.parseProperty(e,t);if(!e){this.checkPropClash(o,a,t)}r.properties.push(o)}return this.finishNode(r,e?"ObjectPattern":"ObjectExpression")};ue.parseProperty=function(e,t){var r=this.startNode(),s,a,o,u;if(this.options.ecmaVersion>=9&&this.eat(_.ellipsis)){if(e){r.argument=this.parseIdent(false);if(this.type===_.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(r,"RestElement")}if(this.type===_.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}r.argument=this.parseMaybeAssign(false,t);if(this.type===_.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(r,"SpreadElement")}if(this.options.ecmaVersion>=6){r.method=false;r.shorthand=false;if(e||t){o=this.start;u=this.startLoc}if(!e){s=this.eat(_.star)}}var c=this.containsEsc;this.parsePropertyName(r);if(!e&&!c&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(r)){a=true;s=this.options.ecmaVersion>=9&&this.eat(_.star);this.parsePropertyName(r,t)}else{a=false}this.parsePropertyValue(r,e,s,a,o,u,t,c);return this.finishNode(r,"Property")};ue.parsePropertyValue=function(e,t,r,s,a,o,u,c){if((r||s)&&this.type===_.colon){this.unexpected()}if(this.eat(_.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,u);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===_.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(r,s)}else if(!t&&!c&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==_.comma&&this.type!==_.braceR&&this.type!==_.eq)){if(r||s){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var f=e.kind==="get"?0:1;if(e.value.params.length!==f){var p=e.value.start;if(e.kind==="get"){this.raiseRecoverable(p,"getter should have no params")}else{this.raiseRecoverable(p,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(r||s){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=a}e.kind="init";if(t){e.value=this.parseMaybeDefault(a,o,this.copyNode(e.key))}else if(this.type===_.eq&&u){if(u.shorthandAssign<0){u.shorthandAssign=this.start}e.value=this.parseMaybeDefault(a,o,this.copyNode(e.key))}else{e.value=this.copyNode(e.key)}e.shorthand=true}else{this.unexpected()}};ue.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(_.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(_.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===_.num||this.type===_.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ue.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};ue.parseMethod=function(e,t,r){var s=this.startNode(),a=this.yieldPos,o=this.awaitPos,u=this.awaitIdentPos;this.initFunction(s);if(this.options.ecmaVersion>=6){s.generator=e}if(this.options.ecmaVersion>=8){s.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,s.generator)|F|(r?B:0));this.expect(_.parenL);s.params=this.parseBindingList(_.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(s,false,true,false);this.yieldPos=a;this.awaitPos=o;this.awaitIdentPos=u;return this.finishNode(s,"FunctionExpression")};ue.parseArrowExpression=function(e,t,r,s){var a=this.yieldPos,o=this.awaitPos,u=this.awaitIdentPos;this.enterScope(functionFlags(r,false)|D);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!r}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false,s);this.yieldPos=a;this.awaitPos=o;this.awaitIdentPos=u;return this.finishNode(e,"ArrowFunctionExpression")};ue.parseFunctionBody=function(e,t,r,s){var a=t&&this.type!==_.braceL;var o=this.strict,u=false;if(a){e.body=this.parseMaybeAssign(s);e.expression=true;this.checkParams(e,false)}else{var c=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!o||c){u=this.strictDirective(this.end);if(u&&c){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var f=this.labels;this.labels=[];if(u){this.strict=true}this.checkParams(e,!o&&!u&&!t&&!r&&this.isSimpleParamList(e.params));if(this.strict&&e.id){this.checkLValSimple(e.id,K)}e.body=this.parseBlock(false,undefined,u&&!o);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=f}this.exitScope()};ue.isSimpleParamList=function(e){for(var t=0,r=e;t-1||a.functions.indexOf(e)>-1||a.var.indexOf(e)>-1;a.lexical.push(e);if(this.inModule&&a.flags&N){delete this.undefinedExports[e]}}else if(t===G){var o=this.currentScope();o.lexical.push(e)}else if(t===$){var u=this.currentScope();if(this.treatFunctionsAsVar){s=u.lexical.indexOf(e)>-1}else{s=u.lexical.indexOf(e)>-1||u.var.indexOf(e)>-1}u.functions.push(e)}else{for(var c=this.scopeStack.length-1;c>=0;--c){var f=this.scopeStack[c];if(f.lexical.indexOf(e)>-1&&!(f.flags&M&&f.lexical[0]===e)||!this.treatFunctionsAsVarInScope(f)&&f.functions.indexOf(e)>-1){s=true;break}f.var.push(e);if(this.inModule&&f.flags&N){delete this.undefinedExports[e]}if(f.flags&U){break}}}if(s){this.raiseRecoverable(r,"Identifier '"+e+"' has already been declared")}};pe.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};pe.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pe.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&U){return t}}};pe.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&U&&!(t.flags&D)){return t}}};var he=function Node(e,t,r){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new T(e,r)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var ve=z.prototype;ve.startNode=function(){return new he(this,this.start,this.startLoc)};ve.startNodeAt=function(e,t){return new he(this,e,t)};function finishNodeAt(e,t,r,s){e.type=t;e.end=r;if(this.options.locations){e.loc.end=s}if(this.options.ranges){e.range[1]=r}return e}ve.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};ve.finishNodeAt=function(e,t,r,s){return finishNodeAt.call(this,e,t,r,s)};ve.copyNode=function(e){var t=new he(this,e.start,this.startLoc);for(var r in e){t[r]=e[r]}return t};var be="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var ge=be+" Extended_Pictographic";var me=ge;var _e=me+" EBase EComp EMod EPres ExtPict";var ye={9:be,10:ge,11:me,12:_e};var xe="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var we="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var Ee=we+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var Se=Ee+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var ke=Se+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";var Ae={9:we,10:Ee,11:Se,12:ke};var Ce={};function buildUnicodeData(e){var t=Ce[e]={binary:wordsRegexp(ye[e]+" "+xe),nonBinary:{General_Category:wordsRegexp(xe),Script:wordsRegexp(Ae[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);buildUnicodeData(12);var Re=z.prototype;var Te=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"");this.unicodeProperties=Ce[e.options.ecmaVersion>=12?12:e.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};Te.prototype.reset=function reset(e,t,r){var s=r.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=r;this.switchU=s&&this.parser.options.ecmaVersion>=6;this.switchN=s&&this.parser.options.ecmaVersion>=9};Te.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};Te.prototype.at=function at(e,t){if(t===void 0)t=false;var r=this.source;var s=r.length;if(e>=s){return-1}var a=r.charCodeAt(e);if(!(t||this.switchU)||a<=55295||a>=57344||e+1>=s){return a}var o=r.charCodeAt(e+1);return o>=56320&&o<=57343?(a<<10)+o-56613888:a};Te.prototype.nextIndex=function nextIndex(e,t){if(t===void 0)t=false;var r=this.source;var s=r.length;if(e>=s){return s}var a=r.charCodeAt(e),o;if(!(t||this.switchU)||a<=55295||a>=57344||e+1>=s||(o=r.charCodeAt(e+1))<56320||o>57343){return e+1}return e+2};Te.prototype.current=function current(e){if(e===void 0)e=false;return this.at(this.pos,e)};Te.prototype.lookahead=function lookahead(e){if(e===void 0)e=false;return this.at(this.nextIndex(this.pos,e),e)};Te.prototype.advance=function advance(e){if(e===void 0)e=false;this.pos=this.nextIndex(this.pos,e)};Te.prototype.eat=function eat(e,t){if(t===void 0)t=false;if(this.current(t)===e){this.advance(t);return true}return false};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Re.validateRegExpFlags=function(e){var t=e.validFlags;var r=e.flags;for(var s=0;s-1){this.raise(e.start,"Duplicate regular expression flag")}}};Re.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};Re.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,r=e.backReferenceNames;t=9){r=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!r;return true}}e.pos=t;return false};Re.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};Re.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};Re.regexp_eatBracedQuantifier=function(e,t){var r=e.pos;if(e.eat(123)){var s=0,a=-1;if(this.regexp_eatDecimalDigits(e)){s=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){a=e.lastIntValue}if(e.eat(125)){if(a!==-1&&a=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};Re.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};Re.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};Re.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}Re.regexp_eatPatternCharacters=function(e){var t=e.pos;var r=0;while((r=e.current())!==-1&&!isSyntaxCharacter(r)){e.advance()}return e.pos!==t};Re.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};Re.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};Re.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};Re.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString$1(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString$1(e.lastIntValue)}return true}return false};Re.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var r=this.options.ecmaVersion>=11;var s=e.current(r);e.advance(r);if(s===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,r)){s=e.lastIntValue}if(isRegExpIdentifierStart(s)){e.lastIntValue=s;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}Re.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var r=this.options.ecmaVersion>=11;var s=e.current(r);e.advance(r);if(s===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,r)){s=e.lastIntValue}if(isRegExpIdentifierPart(s)){e.lastIntValue=s;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}Re.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};Re.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var r=e.lastIntValue;if(e.switchU){if(r>e.maxBackReference){e.maxBackReference=r}return true}if(r<=e.numCapturingParens){return true}e.pos=t}return false};Re.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};Re.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,false)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};Re.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};Re.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};Re.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};Re.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}Re.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){if(t===void 0)t=false;var r=e.pos;var s=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var a=e.lastIntValue;if(s&&a>=55296&&a<=56319){var o=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var u=e.lastIntValue;if(u>=56320&&u<=57343){e.lastIntValue=(a-55296)*1024+(u-56320)+65536;return true}}e.pos=o;e.lastIntValue=a}return true}if(s&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(s){e.raise("Invalid unicode escape")}e.pos=r}return false};function isValidUnicode(e){return e>=0&&e<=1114111}Re.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};Re.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};Re.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}Re.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var r=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var s=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,r,s);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var a=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,a);return true}return false};Re.regexp_validateUnicodePropertyNameAndValue=function(e,t,r){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(r)){e.raise("Invalid property value")}};Re.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};Re.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString$1(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}Re.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString$1(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}Re.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};Re.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};Re.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var r=e.lastIntValue;if(e.switchU&&(t===-1||r===-1)){e.raise("Invalid character class")}if(t!==-1&&r!==-1&&t>r){e.raise("Range out of order in character class")}}}};Re.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var r=e.current();if(r===99||isOctalDigit(r)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var s=e.current();if(s!==93){e.lastIntValue=s;e.advance();return true}return false};Re.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};Re.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};Re.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};Re.regexp_eatDecimalDigits=function(e){var t=e.pos;var r=0;e.lastIntValue=0;while(isDecimalDigit(r=e.current())){e.lastIntValue=10*e.lastIntValue+(r-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}Re.regexp_eatHexDigits=function(e){var t=e.pos;var r=0;e.lastIntValue=0;while(isHexDigit(r=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(r);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}Re.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var r=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+r*8+e.lastIntValue}else{e.lastIntValue=t*8+r}}else{e.lastIntValue=t}return true}return false};Re.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}Re.regexp_eatFixedHexDigits=function(e,t){var r=e.pos;e.lastIntValue=0;for(var s=0;s=this.input.length){return this.finishToken(_.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};Oe.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};Oe.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320){return e}var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888};Oe.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,r=this.input.indexOf("*/",this.pos+=2);if(r===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=r+2;if(this.options.locations){x.lastIndex=t;var s;while((s=x.exec(this.input))&&s.index8&&e<14||e>=5760&&w.test(String.fromCharCode(e))){++this.pos}else{break e}}}};Oe.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var r=this.type;this.type=e;this.value=t;this.updateContext(r)};Oe.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(_.ellipsis)}else{++this.pos;return this.finishToken(_.dot)}};Oe.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(_.assign,2)}return this.finishOp(_.slash,1)};Oe.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var r=1;var s=e===42?_.star:_.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++r;s=_.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(_.assign,r+1)}return this.finishOp(s,r)};Oe.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var r=this.input.charCodeAt(this.pos+2);if(r===61){return this.finishOp(_.assign,3)}}return this.finishOp(e===124?_.logicalOR:_.logicalAND,2)}if(t===61){return this.finishOp(_.assign,2)}return this.finishOp(e===124?_.bitwiseOR:_.bitwiseAND,1)};Oe.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(_.assign,2)}return this.finishOp(_.bitwiseXOR,1)};Oe.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||y.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(_.incDec,2)}if(t===61){return this.finishOp(_.assign,2)}return this.finishOp(_.plusMin,1)};Oe.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var r=1;if(t===e){r=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+r)===61){return this.finishOp(_.assign,r+1)}return this.finishOp(_.bitShift,r)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){r=2}return this.finishOp(_.relational,r)};Oe.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(_.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(_.arrow)}return this.finishOp(e===61?_.eq:_.prefix,1)};Oe.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var r=this.input.charCodeAt(this.pos+2);if(r<48||r>57){return this.finishOp(_.questionDot,2)}}if(t===63){if(e>=12){var s=this.input.charCodeAt(this.pos+2);if(s===61){return this.finishOp(_.assign,3)}}return this.finishOp(_.coalesce,2)}}return this.finishOp(_.question,1)};Oe.readToken_numberSign=function(){var e=this.options.ecmaVersion;var t=35;if(e>=13){++this.pos;t=this.fullCharCodeAtPos();if(isIdentifierStart(t,true)||t===92){return this.finishToken(_.privateId,this.readWord1())}}this.raise(this.pos,"Unexpected character '"+codePointToString(t)+"'")};Oe.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(_.parenL);case 41:++this.pos;return this.finishToken(_.parenR);case 59:++this.pos;return this.finishToken(_.semi);case 44:++this.pos;return this.finishToken(_.comma);case 91:++this.pos;return this.finishToken(_.bracketL);case 93:++this.pos;return this.finishToken(_.bracketR);case 123:++this.pos;return this.finishToken(_.braceL);case 125:++this.pos;return this.finishToken(_.braceR);case 58:++this.pos;return this.finishToken(_.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(_.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(_.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+codePointToString(e)+"'")};Oe.finishOp=function(e,t){var r=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,r)};Oe.readRegexp=function(){var e,t,r=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(r,"Unterminated regular expression")}var s=this.input.charAt(this.pos);if(y.test(s)){this.raise(r,"Unterminated regular expression")}if(!e){if(s==="["){t=true}else if(s==="]"&&t){t=false}else if(s==="/"&&!t){break}e=s==="\\"}else{e=false}++this.pos}var a=this.input.slice(r,this.pos);++this.pos;var o=this.pos;var u=this.readWord1();if(this.containsEsc){this.unexpected(o)}var c=this.regexpState||(this.regexpState=new Te(this));c.reset(r,a,u);this.validateRegExpFlags(c);this.validateRegExpPattern(c);var f=null;try{f=new RegExp(a,u)}catch(e){}return this.finishToken(_.regexp,{pattern:a,flags:u,value:f})};Oe.readInt=function(e,t,r){var s=this.options.ecmaVersion>=12&&t===undefined;var a=r&&this.input.charCodeAt(this.pos)===48;var o=this.pos,u=0,c=0;for(var f=0,p=t==null?Infinity:t;f=97){h=d-97+10}else if(d>=65){h=d-65+10}else if(d>=48&&d<=57){h=d-48}else{h=Infinity}if(h>=e){break}c=d;u=u*e+h}if(s&&c===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===o||t!=null&&this.pos-o!==t){return null}return u};function stringToNumber(e,t){if(t){return parseInt(e,8)}return parseFloat(e.replace(/_/g,""))}function stringToBigInt(e){if(typeof BigInt!=="function"){return null}return BigInt(e.replace(/_/g,""))}Oe.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var r=this.readInt(e);if(r==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){r=stringToBigInt(this.input.slice(t,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(_.num,r)};Oe.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10,undefined,true)===null){this.raise(t,"Invalid number")}var r=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(r&&this.strict){this.raise(t,"Invalid number")}var s=this.input.charCodeAt(this.pos);if(!r&&!e&&this.options.ecmaVersion>=11&&s===110){var a=stringToBigInt(this.input.slice(t,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(_.num,a)}if(r&&/[89]/.test(this.input.slice(t,this.pos))){r=false}if(s===46&&!r){++this.pos;this.readInt(10);s=this.input.charCodeAt(this.pos)}if((s===69||s===101)&&!r){s=this.input.charCodeAt(++this.pos);if(s===43||s===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var o=stringToNumber(this.input.slice(t,this.pos),r);return this.finishToken(_.num,o)};Oe.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var r=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(r,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Oe.readString=function(e){var t="",r=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var s=this.input.charCodeAt(this.pos);if(s===e){break}if(s===92){t+=this.input.slice(r,this.pos);t+=this.readEscapedChar(false);r=this.pos}else if(s===8232||s===8233){if(this.options.ecmaVersion<10){this.raise(this.start,"Unterminated string constant")}++this.pos;if(this.options.locations){this.curLine++;this.lineStart=this.pos}}else{if(isNewLine(s)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(r,this.pos++);return this.finishToken(_.string,t)};var Ne={};Oe.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===Ne){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};Oe.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw Ne}else{this.raise(e,t)}};Oe.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var r=this.input.charCodeAt(this.pos);if(r===96||r===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===_.template||this.type===_.invalidTemplate)){if(r===36){this.pos+=2;return this.finishToken(_.dollarBraceL)}else{++this.pos;return this.finishToken(_.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(_.template,e)}if(r===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(r)){e+=this.input.slice(t,this.pos);++this.pos;switch(r){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(r);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};Oe.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var s=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var a=parseInt(s,8);if(a>255){s=s.slice(0,-1);a=parseInt(s,8)}this.pos+=s.length-1;t=this.input.charCodeAt(this.pos);if((s!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-s.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(a)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};Oe.readHexChar=function(e){var t=this.pos;var r=this.readInt(16,e);if(r===null){this.invalidStringToken(t,"Bad character escape sequence")}return r};Oe.readWord1=function(){this.containsEsc=false;var e="",t=true,r=this.pos;var s=this.options.ecmaVersion>=6;while(this.posH,env:{NODE_ENV:u.UNKNOWN,[u.UNKNOWN]:true},[u.UNKNOWN]:true};const T=Symbol();const I=Symbol();const O=Symbol();const N=Symbol();const P=Symbol();const L=Symbol();const j=Symbol();const D=Symbol();const M={access:L,accessSync:L,createReadStream:L,exists:L,existsSync:L,fstat:L,fstatSync:L,lstat:L,lstatSync:L,open:L,readFile:L,readFileSync:L,stat:L,statSync:L};const F=Object.assign(Object.create(null),{bindings:{default:j},express:{default:function(){return{[u.UNKNOWN]:true,set:T,engine:I}}},fs:Object.assign({default:M},M),process:Object.assign({default:R},R),path:{default:{}},os:Object.assign({default:k.default},k.default),"@mapbox/node-pre-gyp":Object.assign({default:x.default},x.default),"node-pre-gyp":v.pregyp,"node-pre-gyp/lib/pre-binding":v.pregyp,"node-pre-gyp/lib/pre-binding.js":v.pregyp,"node-gyp-build":{default:D},nbind:{init:O,default:{init:O}},"resolve-from":{default:C.default},"strong-globalize":{default:{SetRootDir:N},SetRootDir:N},pkginfo:{default:P}});const B={_interopRequireDefault:g.normalizeDefaultRequire,_interopRequireWildcard:g.normalizeWildcardRequire,__importDefault:g.normalizeDefaultRequire,__importStar:g.normalizeWildcardRequire,MONGOOSE_DRIVER_PATH:undefined,URL:w.URL,Object:{assign:Object.assign}};B.global=B.GLOBAL=B.globalThis=B;const W=Symbol();v.pregyp.find[W]=true;const U=F.path;Object.keys(a.default).forEach((e=>{const t=a.default[e];if(typeof t==="function"){const r=function mockPath(){return t.apply(mockPath,arguments)};r[W]=true;U[e]=U.default[e]=r}else{U[e]=U.default[e]=t}}));U.resolve=U.default.resolve=function(...e){return a.default.resolve.apply(this,[H,...e])};U.resolve[W]=true;const V=new Set([".h",".cmake",".c",".cpp"]);const q=new Set(["CHANGELOG.md","README.md","readme.md","changelog.md"]);let H;const $=/^\/[^\/]+|^[a-z]:[\\/][^\\/]+/i;function isAbsolutePathOrUrl(e){if(e instanceof w.URL)return e.protocol==="file:";if(typeof e==="string"){if(e.startsWith("file:")){try{new w.URL(e);return true}catch(e){return false}}return $.test(e)}return false}const G=Symbol();const K=/([\/\\]\*\*[\/\\]\*)+/g;async function analyze(e,t,r){const s=new Set;const c=new Set;const g=new Set;const x=a.default.dirname(e);H=r.cwd;const k=h.getPackageBase(e);const emitAssetDirectory=e=>{if(!r.analysis.emitGlobs)return;const t=e.indexOf(u.WILDCARD);const o=t===-1?e.length:e.lastIndexOf(a.default.sep,t);const c=e.substr(0,o);const f=e.substr(o);const p=f.replace(u.wildcardRegEx,((e,t)=>f[t-1]===a.default.sep?"**/*":"*")).replace(K,"/**/*")||"/**/*";if(r.ignoreFn(a.default.relative(r.base,c+p)))return;C=C.then((async()=>{if(r.log)console.log("Globbing "+c+p);const e=await new Promise(((e,t)=>d.default(c+p,{mark:true,ignore:c+"/**/node_modules/**/*"},((r,s)=>r?t(r):e(s)))));e.filter((e=>!V.has(a.default.extname(e))&&!q.has(a.default.basename(e))&&!e.endsWith("/"))).forEach((e=>s.add(e)))}))};let C=Promise.resolve();t=t.replace(/^#![^\n\r]*[\r\n]/,"");let M;let U=false;try{M=S.parse(t,{ecmaVersion:"latest",allowReturnOutsideFunction:true});U=false}catch(t){const s=t&&t.message&&t.message.includes("sourceType: module");if(!s){r.warnings.add(new Error(`Failed to parse ${e} as script:\n${t&&t.message}`))}}if(!M){try{M=S.parse(t,{ecmaVersion:"latest",sourceType:"module",allowAwaitOutsideFunction:true});U=true}catch(t){r.warnings.add(new Error(`Failed to parse ${e} as module:\n${t&&t.message}`));return{assets:s,deps:c,imports:g,isESM:false}}}const z=w.pathToFileURL(e).href;const Q=Object.assign(Object.create(null),{__dirname:{shadowDepth:0,value:{value:a.default.resolve(e,"..")}},__filename:{shadowDepth:0,value:{value:e}},process:{shadowDepth:0,value:{value:R}}});if(!U||r.mixedModules){Q.require={shadowDepth:0,value:{value:{[u.FUNCTION](e){c.add(e);const t=F[e];return t.default},resolve(t){return _.default(t,e,r)}}}};Q.require.value.value.resolve[W]=true}function setKnownBinding(e,t){if(e==="require")return;Q[e]={shadowDepth:0,value:t}}function getKnownBinding(e){const t=Q[e];if(t){if(t.shadowDepth===0){return t.value}}return undefined}function hasKnownBindingValue(e){const t=Q[e];return t&&t.shadowDepth===0}if((U||r.mixedModules)&&isAst(M)){for(const e of M.body){if(e.type==="ImportDeclaration"){const t=String(e.source.value);c.add(t);const r=F[t];if(r){for(const t of e.specifiers){if(t.type==="ImportNamespaceSpecifier")setKnownBinding(t.local.name,{value:r});else if(t.type==="ImportDefaultSpecifier"&&"default"in r)setKnownBinding(t.local.name,{value:r.default});else if(t.type==="ImportSpecifier"&&t.imported.name in r)setKnownBinding(t.local.name,{value:r[t.imported.name]})}}}else if(e.type==="ExportNamedDeclaration"||e.type==="ExportAllDeclaration"){if(e.source)c.add(String(e.source.value))}}}async function computePureStaticValue(e,t=true){const r=Object.create(null);Object.keys(B).forEach((e=>{r[e]={value:B[e]}}));Object.keys(Q).forEach((e=>{r[e]=getKnownBinding(e)}));r["import.meta"]={url:z};const s=await u.evaluate(e,r,t);return s}let Y;let X;let Z=false;function emitWildcardRequire(e){if(!r.analysis.emitGlobs||!e.startsWith("./")&&!e.startsWith("../"))return;e=a.default.resolve(x,e);const t=e.indexOf(u.WILDCARD);const o=t===-1?e.length:e.lastIndexOf(a.default.sep,t);const c=e.substr(0,o);const f=e.substr(o);let p=f.replace(u.wildcardRegEx,((e,t)=>f[t-1]===a.default.sep?"**/*":"*"))||"/**/*";if(!p.endsWith("*"))p+="?("+(r.ts?".ts|.tsx|":"")+".js|.json|.node)";if(r.ignoreFn(a.default.relative(r.base,c+p)))return;C=C.then((async()=>{if(r.log)console.log("Globbing "+c+p);const e=await new Promise(((e,t)=>d.default(c+p,{mark:true,ignore:c+"/**/node_modules/**/*"},((r,s)=>r?t(r):e(s)))));e.filter((e=>!V.has(a.default.extname(e))&&!q.has(a.default.basename(e))&&!e.endsWith("/"))).forEach((e=>s.add(e)))}))}async function processRequireArg(e,t=false){if(e.type==="ConditionalExpression"){await processRequireArg(e.consequent,t);await processRequireArg(e.alternate,t);return}if(e.type==="LogicalExpression"){await processRequireArg(e.left,t);await processRequireArg(e.right,t);return}let r=await computePureStaticValue(e,true);if(!r)return;if("value"in r&&typeof r.value==="string"){if(!r.wildcards)(t?g:c).add(r.value);else if(r.wildcards.length>=1)emitWildcardRequire(r.value)}else{if("then"in r&&typeof r.then==="string")(t?g:c).add(r.then);if("else"in r&&typeof r.else==="string")(t?g:c).add(r.else)}}let J=o.attachScopes(M,"scope");if(isAst(M)){A.handleWrappers(M);await m.default({id:e,ast:M,emitAsset:e=>s.add(e),emitAssetDirectory:emitAssetDirectory,job:r})}async function backtrack(e,t){if(!Y)throw new Error("Internal error: No staticChildNode for backtrack.");const r=await computePureStaticValue(e,true);if(r){if("value"in r&&typeof r.value!=="symbol"||"then"in r&&typeof r.then!=="symbol"&&typeof r.else!=="symbol"){X=r;Y=e;if(t)t.skip();return}}await emitStaticChildAsset()}await E(M,{async enter(t,o){var u;const d=t;const h=o;if(d.scope){J=d.scope;for(const e in d.scope.declarations){if(e in Q)Q[e].shadowDepth++}}if(Y)return;if(!h)return;if(d.type==="Identifier"){if(p.isIdentifierRead(d,h)&&r.analysis.computeFileReferences){let e;if(typeof(e=(u=getKnownBinding(d.name))===null||u===void 0?void 0:u.value)==="string"&&e.match($)||e&&(typeof e==="function"||typeof e==="object")&&e[W]){X={value:typeof e==="string"?e:undefined};Y=d;await backtrack(h,this)}}}else if(r.analysis.computeFileReferences&&d.type==="MemberExpression"&&d.object.type==="MetaProperty"&&d.object.meta.name==="import"&&d.object.property.name==="meta"&&(d.property.computed?d.property.value:d.property.name)==="url"){X={value:z};Y=d;await backtrack(h,this)}else if(d.type==="ImportExpression"){await processRequireArg(d.source,true);return}else if(d.type==="CallExpression"){if((!U||r.mixedModules)&&d.callee.type==="Identifier"&&d.arguments.length){if(d.callee.name==="require"&&Q.require.shadowDepth===0){await processRequireArg(d.arguments[0]);return}}else if((!U||r.mixedModules)&&d.callee.type==="MemberExpression"&&d.callee.object.type==="Identifier"&&d.callee.object.name==="module"&&"module"in Q===false&&d.callee.property.type==="Identifier"&&!d.callee.computed&&d.callee.property.name==="require"&&d.arguments.length){await processRequireArg(d.arguments[0]);return}const t=r.analysis.evaluatePureExpressions&&await computePureStaticValue(d.callee,false);if(t&&"value"in t&&typeof t.value==="function"&&t.value[W]&&r.analysis.computeFileReferences){X=await computePureStaticValue(d,true);if(X&&h){Y=d;await backtrack(h,this)}}else if(t&&"value"in t&&typeof t.value==="symbol"){switch(t.value){case G:if(d.arguments.length===1&&d.arguments[0].type==="Literal"&&d.callee.type==="Identifier"&&Q.require.shadowDepth===0){await processRequireArg(d.arguments[0])}break;case j:if(d.arguments.length){const e=await computePureStaticValue(d.arguments[0],false);if(e&&"value"in e&&e.value){let t;if(typeof e.value==="object")t=e.value;else if(typeof e.value==="string")t={bindings:e.value};if(!t.path){t.path=true}t.module_root=k;let r;try{r=f.default(t)}catch(e){}if(r){X={value:r};Y=d;await emitStaticChildAsset()}}}break;case D:if(d.arguments.length===1&&d.arguments[0].type==="Identifier"&&d.arguments[0].name==="__dirname"&&Q.__dirname.shadowDepth===0){let e;try{e=y.default.path(x)}catch(e){}if(e){X={value:e};Y=d;await emitStaticChildAsset()}}break;case O:if(d.arguments.length){const e=await computePureStaticValue(d.arguments[0],false);if(e&&"value"in e&&(typeof e.value==="string"||typeof e.value==="undefined")){const t=v.nbind(e.value);if(t&&t.path){c.add(a.default.relative(x,t.path).replace(/\\/g,"/"));return this.skip()}}}break;case T:if(d.arguments.length===2&&d.arguments[0].type==="Literal"&&d.arguments[0].value==="view engine"&&!Z){await processRequireArg(d.arguments[1]);return this.skip()}break;case I:Z=true;break;case L:if(d.arguments[0]&&r.analysis.computeFileReferences){X=await computePureStaticValue(d.arguments[0],true);if(X){Y=d.arguments[0];await backtrack(h,this);return this.skip()}}break;case N:if(d.arguments[0]){const e=await computePureStaticValue(d.arguments[0],false);if(e&&"value"in e&&e.value)emitAssetDirectory(e.value+"/intl");return this.skip()}break;case P:let t=a.default.resolve(e,"../package.json");const o=a.default.resolve("/package.json");while(t!==o&&await r.stat(t)===null)t=a.default.resolve(t,"../../package.json");if(t!==o)s.add(t);break}}}else if(d.type==="VariableDeclaration"&&h&&!p.isVarLoop(h)&&r.analysis.evaluatePureExpressions){for(const e of d.declarations){if(!e.init)continue;const t=await computePureStaticValue(e.init,true);if(t){if(e.id.type==="Identifier"){setKnownBinding(e.id.name,t)}else if(e.id.type==="ObjectPattern"&&"value"in t){for(const r of e.id.properties){if(r.type!=="Property"||r.key.type!=="Identifier"||r.value.type!=="Identifier"||typeof t.value!=="object"||t.value===null||!(r.key.name in t.value))continue;setKnownBinding(r.value.name,{value:t.value[r.key.name]})}}if(!("value"in t)&&isAbsolutePathOrUrl(t.then)&&isAbsolutePathOrUrl(t.else)){X=t;Y=e.init;await emitStaticChildAsset()}}}}else if(d.type==="AssignmentExpression"&&h&&!p.isLoop(h)&&r.analysis.evaluatePureExpressions){if(!hasKnownBindingValue(d.left.name)){const e=await computePureStaticValue(d.right,false);if(e&&"value"in e){if(d.left.type==="Identifier"){setKnownBinding(d.left.name,e)}else if(d.left.type==="ObjectPattern"){for(const t of d.left.properties){if(t.type!=="Property"||t.key.type!=="Identifier"||t.value.type!=="Identifier"||typeof e.value!=="object"||e.value===null||!(t.key.name in e.value))continue;setKnownBinding(t.value.name,{value:e.value[t.key.name]})}}if(isAbsolutePathOrUrl(e.value)){X=e;Y=d.right;await emitStaticChildAsset()}}}}else if((!U||r.mixedModules)&&(d.type==="FunctionDeclaration"||d.type==="FunctionExpression"||d.type==="ArrowFunctionExpression")&&(d.arguments||d.params)[0]&&(d.arguments||d.params)[0].type==="Identifier"){let e;let t;if((d.type==="ArrowFunctionExpression"||d.type==="FunctionExpression")&&h&&h.type==="VariableDeclarator"&&h.id.type==="Identifier"){e=h.id;t=d.arguments||d.params}else if(d.id){e=d.id;t=d.arguments||d.params}if(e&&d.body.body){let r,s=false;for(let e=0;ee&&e.id&&e.id.type==="Identifier"&&e.init&&e.init.type==="CallExpression"&&e.init.callee.type==="Identifier"&&e.init.callee.name==="require"&&Q.require.shadowDepth===0&&e.init.arguments[0]&&e.init.arguments[0].type==="Identifier"&&e.init.arguments[0].name===t[0].name))}if(r&&d.body.body[e].type==="ReturnStatement"&&d.body.body[e].argument&&d.body.body[e].argument.type==="Identifier"&&d.body.body[e].argument.name===r.id.name){s=true;break}}if(s)setKnownBinding(e.name,{value:G})}}},async leave(e,t){const r=e;const s=t;if(r.scope){if(J.parent){J=J.parent}for(const e in r.scope.declarations){if(e in Q){if(Q[e].shadowDepth>0)Q[e].shadowDepth--;else delete Q[e]}}}if(Y&&s)await backtrack(s,this)}});await C;return{assets:s,deps:c,imports:g,isESM:U};async function emitAssetPath(e){const t=e.indexOf(u.WILDCARD);const o=t===-1?e.length:e.lastIndexOf(a.default.sep,t);const c=e.substr(0,o);try{var f=await r.stat(c);if(f===null){throw new Error("file not found")}}catch(e){return}if(t!==-1&&f.isFile())return;if(f.isFile()){s.add(e)}else if(f.isDirectory()){if(validWildcard(e))emitAssetDirectory(e)}}function validWildcard(t){let s="";if(t.endsWith(a.default.sep))s=a.default.sep;else if(t.endsWith(a.default.sep+u.WILDCARD))s=a.default.sep+u.WILDCARD;else if(t.endsWith(u.WILDCARD))s=u.WILDCARD;if(t===x+s)return false;if(t===H+s)return false;if(t.endsWith(a.default.sep+"node_modules"+s))return false;if(x.startsWith(t.substr(0,t.length-s.length)+a.default.sep))return false;if(k){const s=e.substr(0,e.indexOf(a.default.sep+"node_modules"))+a.default.sep+"node_modules"+a.default.sep;if(!t.startsWith(s)){if(r.log)console.log("Skipping asset emission of "+t.replace(u.wildcardRegEx,"*")+" for "+e+" as it is outside the package base "+k);return false}}return true}function resolveAbsolutePathOrUrl(e){return e instanceof w.URL?w.fileURLToPath(e):e.startsWith("file:")?w.fileURLToPath(new w.URL(e)):a.default.resolve(e)}async function emitStaticChildAsset(){if(!X){return}if("value"in X&&isAbsolutePathOrUrl(X.value)){try{const e=resolveAbsolutePathOrUrl(X.value);await emitAssetPath(e)}catch(e){}}else if("then"in X&&"else"in X&&isAbsolutePathOrUrl(X.then)&&isAbsolutePathOrUrl(X.else)){let e;try{e=resolveAbsolutePathOrUrl(X.then)}catch(e){}let t;try{t=resolveAbsolutePathOrUrl(X.else)}catch(e){}if(e)await emitAssetPath(e);if(t)await emitAssetPath(t)}else if(Y&&Y.type==="ArrayExpression"&&"value"in X&&X.value instanceof Array){for(const e of X.value){try{const t=resolveAbsolutePathOrUrl(e);await emitAssetPath(t)}catch(e){}}}Y=X=undefined}}t["default"]=analyze;function isAst(e){return"body"in e}},9582:function(e,t,r){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){if(s===undefined)s=r;Object.defineProperty(e,s,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,s){if(s===undefined)s=r;e[s]=t[r]});var a=this&&this.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!t.hasOwnProperty(r))s(t,e,r)};Object.defineProperty(t,"__esModule",{value:true});a(r(3864),t);var o=r(3471);Object.defineProperty(t,"nodeFileTrace",{enumerable:true,get:function(){return o.nodeFileTrace}})},3471:function(e,t,r){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.Job=t.nodeFileTrace=void 0;const a=r(1017);const o=s(r(552));const u=s(r(8827));const c=s(r(2278));const f=r(2540);const p=r(2985);const d=r(1017);const h=o.default.promises.readFile;const v=o.default.promises.readlink;const g=o.default.promises.stat;function inPath(e,t){const r=d.join(t,a.sep);return e.startsWith(r)&&e!==r}async function nodeFileTrace(e,t={}){const r=new Job(t);if(t.readFile)r.readFile=t.readFile;if(t.stat)r.stat=t.stat;if(t.readlink)r.readlink=t.readlink;if(t.resolve)r.resolve=t.resolve;r.ts=true;await Promise.all(e.map((async e=>{const t=a.resolve(e);await r.emitFile(t,"initial");if(t.endsWith(".js")||t.endsWith(".cjs")||t.endsWith(".mjs")||t.endsWith(".node")||r.ts&&(t.endsWith(".ts")||t.endsWith(".tsx"))){return r.emitDependency(t)}return undefined})));const s={fileList:r.fileList,esmFileList:r.esmFileList,reasons:r.reasons,warnings:r.warnings};return s}t.nodeFileTrace=nodeFileTrace;class Job{constructor({base:e=process.cwd(),processCwd:t,exports:r,conditions:s=r||["node"],exportsOnly:o=false,paths:u={},ignore:c,log:p=false,mixedModules:d=false,ts:h=true,analysis:v={},cache:g}){this.reasons=new Map;this.ts=h;e=a.resolve(e);this.ignoreFn=e=>{if(e.startsWith(".."+a.sep))return true;return false};if(typeof c==="string")c=[c];if(typeof c==="function"){const e=c;this.ignoreFn=t=>{if(t.startsWith(".."+a.sep))return true;if(e(t))return true;return false}}else if(Array.isArray(c)){const t=c.map((t=>a.relative(e,a.resolve(e||process.cwd(),t))));this.ignoreFn=e=>{if(e.startsWith(".."+a.sep))return true;if(f.isMatch(e,t))return true;return false}}this.base=e;this.cwd=a.resolve(t||e);this.conditions=s;this.exportsOnly=o;const m={};for(const t of Object.keys(u)){const r=u[t].endsWith("/");const s=a.resolve(e,u[t]);m[t]=s+(r?"/":"")}this.paths=m;this.log=p;this.mixedModules=d;this.analysis={};if(v!==false){Object.assign(this.analysis,{emitGlobs:true,computeFileReferences:true,evaluatePureExpressions:true},v===true?{}:v)}this.fileCache=g&&g.fileCache||new Map;this.statCache=g&&g.statCache||new Map;this.symlinkCache=g&&g.symlinkCache||new Map;this.analysisCache=g&&g.analysisCache||new Map;if(g){g.fileCache=this.fileCache;g.statCache=this.statCache;g.symlinkCache=this.symlinkCache;g.analysisCache=this.analysisCache}this.fileList=new Set;this.esmFileList=new Set;this.processed=new Set;this.warnings=new Set}async readlink(e){const t=this.symlinkCache.get(e);if(t!==undefined)return t;try{const t=await v(e);const r=this.statCache.get(e);if(r)this.statCache.set(a.resolve(e,t),r);this.symlinkCache.set(e,t);return t}catch(t){if(t.code!=="EINVAL"&&t.code!=="ENOENT"&&t.code!=="UNKNOWN")throw t;this.symlinkCache.set(e,null);return null}}async isFile(e){const t=await this.stat(e);if(t)return t.isFile();return false}async isDir(e){const t=await this.stat(e);if(t)return t.isDirectory();return false}async stat(e){const t=this.statCache.get(e);if(t)return t;try{const t=await g(e);this.statCache.set(e,t);return t}catch(t){if(t.code==="ENOENT"){this.statCache.set(e,null);return null}throw t}}async resolve(e,t,r,s){return c.default(e,t,r,s)}async readFile(e){const t=this.fileCache.get(e);if(t!==undefined)return t;try{const t=(await h(e)).toString();this.fileCache.set(e,t);return t}catch(t){if(t.code==="ENOENT"||t.code==="EISDIR"){this.fileCache.set(e,null);return null}throw t}}async realpath(e,t,r=new Set){if(r.has(e))throw new Error("Recursive symlink detected resolving "+e);r.add(e);const s=await this.readlink(e);if(s){const o=a.dirname(e);const u=a.resolve(o,s);const c=await this.realpath(o,t);if(inPath(e,c))await this.emitFile(e,"resolve",t,true);return this.realpath(u,t,r)}if(!inPath(e,this.base))return e;return d.join(await this.realpath(a.dirname(e),t,r),a.basename(e))}async emitFile(e,t,r,s=false){if(!s){e=await this.realpath(e,r)}e=a.relative(this.base,e);if(r){r=a.relative(this.base,r)}let o=this.reasons.get(e);if(!o){o={type:t,ignored:false,parents:new Set};this.reasons.set(e,o)}if(r&&this.ignoreFn(e,r)){if(!this.fileList.has(e)&&o){o.ignored=true}return false}if(r){o.parents.add(r)}this.fileList.add(e);return true}async getPjsonBoundary(e){const t=e.indexOf(a.sep);let r;while((r=e.lastIndexOf(a.sep))>t){e=e.substr(0,r);if(await this.isFile(e+a.sep+"package.json"))return e}return undefined}async emitDependency(e,t){if(this.processed.has(e)){if(t){await this.emitFile(e,"dependency",t)}return}this.processed.add(e);const r=await this.emitFile(e,"dependency",t);if(!r)return;if(e.endsWith(".json"))return;if(e.endsWith(".node"))return await p.sharedLibEmit(e,this);if(e.endsWith(".js")){const t=await this.getPjsonBoundary(e);if(t)await this.emitFile(t+a.sep+"package.json","resolve",e)}let s;const o=this.analysisCache.get(e);if(o){s=o}else{const t=await this.readFile(e);if(t===null)throw new Error("File "+e+" does not exist.");s=await u.default(e,t.toString(),this);this.analysisCache.set(e,s)}const{deps:c,imports:f,assets:d,isESM:h}=s;if(h)this.esmFileList.add(a.relative(this.base,e));await Promise.all([...[...d].map((async t=>{const r=a.extname(t);if(r===".js"||r===".mjs"||r===".node"||r===""||this.ts&&(r===".ts"||r===".tsx")&&t.startsWith(this.base)&&t.substr(this.base.length).indexOf(a.sep+"node_modules"+a.sep)===-1)await this.emitDependency(t,e);else await this.emitFile(t,"asset",e)})),...[...c].map((async t=>{try{var r=await this.resolve(t,e,this,!h)}catch(e){this.warnings.add(new Error(`Failed to resolve dependency ${t}:\n${e&&e.message}`));return}if(Array.isArray(r)){for(const t of r){if(t.startsWith("node:"))return;await this.emitDependency(t,e)}}else{if(r.startsWith("node:"))return;await this.emitDependency(r,e)}})),...[...f].map((async t=>{try{var r=await this.resolve(t,e,this,false)}catch(e){this.warnings.add(new Error(`Failed to resolve dependency ${t}:\n${e&&e.message}`));return}if(Array.isArray(r)){for(const t of r){if(t.startsWith("node:"))return;await this.emitDependency(t,e)}}else{if(r.startsWith("node:"))return;await this.emitDependency(r,e)}}))])}}t.Job=Job},2278:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});const s=r(1017);async function resolveDependency(e,t,r,a=true){let o;if(s.isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")){const a=e.endsWith("/");o=await resolvePath(s.resolve(t,"..",e)+(a?"/":""),t,r)}else if(e[0]==="#"){o=await packageImportsResolve(e,t,r,a)}else{o=await resolvePackage(e,t,r,a)}if(Array.isArray(o)){return Promise.all(o.map((e=>r.realpath(e,t))))}else if(o.startsWith("node:")){return o}else{return r.realpath(o,t)}}t["default"]=resolveDependency;async function resolvePath(e,t,r){const s=await resolveFile(e,t,r)||await resolveDir(e,t,r);if(!s){throw new NotFoundError(e,t)}return s}async function resolveFile(e,t,r){if(e.endsWith("/"))return undefined;e=await r.realpath(e,t);if(await r.isFile(e))return e;if(r.ts&&e.startsWith(r.base)&&e.substr(r.base.length).indexOf(s.sep+"node_modules"+s.sep)===-1&&await r.isFile(e+".ts"))return e+".ts";if(r.ts&&e.startsWith(r.base)&&e.substr(r.base.length).indexOf(s.sep+"node_modules"+s.sep)===-1&&await r.isFile(e+".tsx"))return e+".tsx";if(await r.isFile(e+".js"))return e+".js";if(await r.isFile(e+".json"))return e+".json";if(await r.isFile(e+".node"))return e+".node";return undefined}async function resolveDir(e,t,r){if(e.endsWith("/"))e=e.slice(0,-1);if(!await r.isDir(e))return;const a=await getPkgCfg(e,r);if(a&&typeof a.main==="string"){const o=await resolveFile(s.resolve(e,a.main),t,r)||await resolveFile(s.resolve(e,a.main,"index"),t,r);if(o){await r.emitFile(e+s.sep+"package.json","resolve",t);return o}}return resolveFile(s.resolve(e,"index"),t,r)}class NotFoundError extends Error{constructor(e,t){super("Cannot find module '"+e+"' loaded from "+t);this.code="MODULE_NOT_FOUND"}}const a=new Set([...r(8102)._builtinLibs,"constants","module","timers","console","_stream_writable","_stream_readable","_stream_duplex","process","sys"]);function getPkgName(e){const t=e.split("/");if(e[0]==="@"&&t.length>1)return t.length>1?t.slice(0,2).join("/"):null;return t.length?t[0]:null}async function getPkgCfg(e,t){const r=await t.readFile(e+s.sep+"package.json");if(r){try{return JSON.parse(r.toString())}catch(e){}}return undefined}function getExportsTarget(e,t,r){if(typeof e==="string"){return e}else if(e===null){return e}else if(Array.isArray(e)){for(const s of e){const e=getExportsTarget(s,t,r);if(e===null||typeof e==="string"&&e.startsWith("./"))return e}}else if(typeof e==="object"){for(const s of Object.keys(e)){if(s==="default"||s==="require"&&r||s==="import"&&!r||t.includes(s)){const a=getExportsTarget(e[s],t,r);if(a!==undefined)return a}}}return undefined}function resolveExportsImports(e,t,r,s,a,o){let u;if(a){if(!(typeof t==="object"&&!Array.isArray(t)&&t!==null))return undefined;u=t}else if(typeof t==="string"||Array.isArray(t)||t===null||typeof t==="object"&&Object.keys(t).length&&Object.keys(t)[0][0]!=="."){u={".":t}}else{u=t}if(r in u){const t=getExportsTarget(u[r],s.conditions,o);if(typeof t==="string"&&t.startsWith("./"))return e+t.slice(1)}for(const t of Object.keys(u).sort(((e,t)=>t.length-e.length))){if(t.endsWith("*")&&r.startsWith(t.slice(0,-1))){const a=getExportsTarget(u[t],s.conditions,o);if(typeof a==="string"&&a.startsWith("./"))return e+a.slice(1).replace(/\*/g,r.slice(t.length-1))}if(!t.endsWith("/"))continue;if(r.startsWith(t)){const a=getExportsTarget(u[t],s.conditions,o);if(typeof a==="string"&&a.endsWith("/")&&a.startsWith("./"))return e+a.slice(1)+r.slice(t.length)}}return undefined}async function packageImportsResolve(e,t,r,a){if(e!=="#"&&!e.startsWith("#/")&&r.conditions){const o=await r.getPjsonBoundary(t);if(o){const u=await getPkgCfg(o,r);const{imports:c}=u||{};if(u&&c!==null&&c!==undefined){let u=resolveExportsImports(o,c,e,r,true,a);if(u){if(a)u=await resolveFile(u,t,r)||await resolveDir(u,t,r);else if(!await r.isFile(u))throw new NotFoundError(u,t);if(u){await r.emitFile(o+s.sep+"package.json","resolve",t);return u}}}}}throw new NotFoundError(e,t)}async function resolvePackage(e,t,r,o){let u=t;if(a.has(e))return"node:"+e;const c=getPkgName(e)||"";let f;if(r.conditions){const a=await r.getPjsonBoundary(t);if(a){const u=await getPkgCfg(a,r);const{exports:p}=u||{};if(u&&u.name&&u.name===c&&p!==null&&p!==undefined){f=resolveExportsImports(a,p,"."+e.slice(c.length),r,false,o);if(f){if(o)f=await resolveFile(f,t,r)||await resolveDir(f,t,r);else if(!await r.isFile(f))throw new NotFoundError(f,t)}if(f)await r.emitFile(a+s.sep+"package.json","resolve",t)}}}let p;const d=u.indexOf(s.sep);while((p=u.lastIndexOf(s.sep))>d){u=u.substr(0,p);const a=u+s.sep+"node_modules";const d=await r.stat(a);if(!d||!d.isDirectory())continue;const h=await getPkgCfg(a+s.sep+c,r);const{exports:v}=h||{};if(r.conditions&&v!==undefined&&v!==null&&!f){let u;if(!r.exportsOnly)u=await resolveFile(a+s.sep+e,t,r)||await resolveDir(a+s.sep+e,t,r);let f=resolveExportsImports(a+s.sep+c,v,"."+e.slice(c.length),r,false,o);if(f){if(o)f=await resolveFile(f,t,r)||await resolveDir(f,t,r);else if(!await r.isFile(f))throw new NotFoundError(f,t)}if(f){await r.emitFile(a+s.sep+c+s.sep+"package.json","resolve",t);if(u&&u!==f)return[f,u];return f}if(u)return u}else{const o=await resolveFile(a+s.sep+e,t,r)||await resolveDir(a+s.sep+e,t,r);if(o){if(f&&f!==o)return[o,f];return o}}}if(f)return f;if(Object.hasOwnProperty.call(r.paths,e)){return r.paths[e]}for(const s of Object.keys(r.paths)){if(s.endsWith("/")&&e.startsWith(s)){const a=r.paths[s]+e.slice(s.length);const o=await resolveFile(a,t,r)||await resolveDir(a,t,r);if(!o){throw new NotFoundError(e,t)}return o}}throw new NotFoundError(e,t)}},3864:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true})},5078:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.isLoop=t.isVarLoop=t.isIdentifierRead=void 0;function isIdentifierRead(e,t){switch(t.type){case"ObjectPattern":case"ArrayPattern":return false;case"AssignmentExpression":return t.right===e;case"MemberExpression":return t.computed||e===t.object;case"Property":return e===t.value;case"MethodDefinition":return false;case"VariableDeclarator":return t.id!==e;case"ExportSpecifier":return false;case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":return false;default:return true}}t.isIdentifierRead=isIdentifierRead;function isVarLoop(e){return e.type==="ForStatement"||e.type==="ForInStatement"||e.type==="ForOfStatement"}t.isVarLoop=isVarLoop;function isLoop(e){return e.type==="ForStatement"||e.type==="ForInStatement"||e.type==="ForOfStatement"||e.type==="WhileStatement"||e.type==="DoWhileStatement"}t.isLoop=isLoop},2774:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:true});exports.nbind=exports.pregyp=void 0;const path_1=__importDefault(__nccwpck_require__(1017));const graceful_fs_1=__importDefault(__nccwpck_require__(552));const versioning=__nccwpck_require__(5574);const napi=__nccwpck_require__(9248);const pregypFind=(e,t)=>{const r=JSON.parse(graceful_fs_1.default.readFileSync(e).toString());versioning.validate_config(r,t);var s;if(napi.get_napi_build_versions(r,t)){s=napi.get_best_napi_build_version(r,t)}t=t||{};if(!t.module_root)t.module_root=path_1.default.dirname(e);var a=versioning.evaluate(r,t,s);return a.module};exports.pregyp={default:{find:pregypFind},find:pregypFind};function makeModulePathList(e,t){return[[e,t],[e,"build",t],[e,"build","Debug",t],[e,"build","Release",t],[e,"out","Debug",t],[e,"Debug",t],[e,"out","Release",t],[e,"Release",t],[e,"build","default",t],[e,process.env["NODE_BINDINGS_COMPILED_DIR"]||"compiled",process.versions.node,process.platform,process.arch,t]]}function findCompiledModule(basePath,specList){var resolvedList=[];var ext=path_1.default.extname(basePath);for(var _i=0,specList_1=specList;_i{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.getPackageName=t.getPackageBase=void 0;const r=/^(@[^\\\/]+[\\\/])?[^\\\/]+/;function getPackageBase(e){const t=e.lastIndexOf("node_modules");if(t!==-1&&(e[t-1]==="/"||e[t-1]==="\\")&&(e[t+12]==="/"||e[t+12]==="\\")){const s=e.substr(t+13).match(r);if(s)return e.substr(0,t+13+s[0].length)}return undefined}t.getPackageBase=getPackageBase;function getPackageName(e){const t=e.lastIndexOf("node_modules");if(t!==-1&&(e[t-1]==="/"||e[t-1]==="\\")&&(e[t+12]==="/"||e[t+12]==="\\")){const s=e.substr(t+13).match(r);if(s&&s.length>0){return s[0].replace(/\\/g,"/")}}return undefined}t.getPackageName=getPackageName},216:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.normalizeWildcardRequire=t.normalizeDefaultRequire=void 0;function normalizeDefaultRequire(e){if(e&&e.__esModule)return e;return{default:e}}t.normalizeDefaultRequire=normalizeDefaultRequire;const r=Object.prototype.hasOwnProperty;function normalizeWildcardRequire(e){if(e&&e.__esModule)return e;const t={};for(const s in e){if(!r.call(e,s))continue;t[s]=e[s]}t["default"]=e;return t}t.normalizeWildcardRequire=normalizeWildcardRequire},2985:function(e,t,r){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.sharedLibEmit=void 0;const a=s(r(2037));const o=s(r(3535));const u=r(7468);let c="";switch(a.default.platform()){case"darwin":c="/**/*.@(dylib|so?(.*))";break;case"win32":c="/**/*.dll";break;default:c="/**/*.so?(.*)"}async function sharedLibEmit(e,t){const r=u.getPackageBase(e);if(!r)return;const s=await new Promise(((e,t)=>o.default(r+c,{ignore:r+"/**/node_modules/**/*"},((r,s)=>r?t(r):e(s)))));await Promise.all(s.map((r=>t.emitFile(r,"sharedlib",e))))}t.sharedLibEmit=sharedLibEmit},5735:function(e,t,r){"use strict";var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const a=r(1017);const o=s(r(2278));const u=r(7468);const c=r(552);const f={"@generated/photon"({id:e,emitAssetDirectory:t}){if(e.endsWith("@generated/photon/index.js")){t(a.resolve(a.dirname(e),"runtime/"))}},argon2({id:e,emitAssetDirectory:t}){if(e.endsWith("argon2/argon2.js")){t(a.resolve(a.dirname(e),"build","Release"));t(a.resolve(a.dirname(e),"prebuilds"));t(a.resolve(a.dirname(e),"lib","binding"))}},bull({id:e,emitAssetDirectory:t}){if(e.endsWith("bull/lib/commands/index.js")){t(a.resolve(a.dirname(e)))}},camaro({id:e,emitAsset:t}){if(e.endsWith("camaro/dist/camaro.js")){t(a.resolve(a.dirname(e),"camaro.wasm"))}},esbuild({id:e,emitAssetDirectory:t}){if(e.endsWith("esbuild/lib/main.js")){const r=a.resolve(e,"..","..","package.json");const s=JSON.parse(c.readFileSync(r,"utf8"));for(const r of Object.keys(s.optionalDependencies||{})){const s=a.resolve(e,"..","..","..",r);t(s)}}},"google-gax"({id:e,ast:t,emitAssetDirectory:r}){if(e.endsWith("google-gax/build/src/grpc.js")){for(const s of t.body){if(s.type==="VariableDeclaration"&&s.declarations[0].id.type==="Identifier"&&s.declarations[0].id.name==="googleProtoFilesDir"){r(a.resolve(a.dirname(e),"../../../google-proto-files"))}}}},oracledb({id:e,ast:t,emitAsset:r}){if(e.endsWith("oracledb/lib/oracledb.js")){for(const s of t.body){if(s.type==="ForStatement"&&"body"in s.body&&s.body.body&&Array.isArray(s.body.body)&&s.body.body[0]&&s.body.body[0].type==="TryStatement"&&s.body.body[0].block.body[0]&&s.body.body[0].block.body[0].type==="ExpressionStatement"&&s.body.body[0].block.body[0].expression.type==="AssignmentExpression"&&s.body.body[0].block.body[0].expression.operator==="="&&s.body.body[0].block.body[0].expression.left.type==="Identifier"&&s.body.body[0].block.body[0].expression.left.name==="oracledbCLib"&&s.body.body[0].block.body[0].expression.right.type==="CallExpression"&&s.body.body[0].block.body[0].expression.right.callee.type==="Identifier"&&s.body.body[0].block.body[0].expression.right.callee.name==="require"&&s.body.body[0].block.body[0].expression.right.arguments.length===1&&s.body.body[0].block.body[0].expression.right.arguments[0].type==="MemberExpression"&&s.body.body[0].block.body[0].expression.right.arguments[0].computed===true&&s.body.body[0].block.body[0].expression.right.arguments[0].object.type==="Identifier"&&s.body.body[0].block.body[0].expression.right.arguments[0].object.name==="binaryLocations"&&s.body.body[0].block.body[0].expression.right.arguments[0].property.type==="Identifier"&&s.body.body[0].block.body[0].expression.right.arguments[0].property.name==="i"){s.body.body[0].block.body[0].expression.right.arguments=[{type:"Literal",value:"_"}];const t=global._unit?"3.0.0":JSON.parse(c.readFileSync(e.slice(0,-15)+"package.json","utf8")).version;const o=Number(t.slice(0,t.indexOf(".")))>=4;const u="oracledb-"+(o?t:"abi"+process.versions.modules)+"-"+process.platform+"-"+process.arch+".node";r(a.resolve(e,"../../build/Release/"+u))}}}},"phantomjs-prebuilt"({id:e,emitAssetDirectory:t}){if(e.endsWith("phantomjs-prebuilt/lib/phantomjs.js")){t(a.resolve(a.dirname(e),"..","bin"))}},"remark-prism"({id:e,emitAssetDirectory:t}){const r="remark-prism/src/highlight.js";if(e.endsWith(r)){try{const s=e.slice(0,-r.length);t(a.resolve(s,"prismjs","components"))}catch(e){}}},semver({id:e,emitAsset:t}){if(e.endsWith("semver/index.js")){t(a.resolve(e.replace("index.js","preload.js")))}},"socket.io":async function({id:e,ast:t,job:r}){if(e.endsWith("socket.io/lib/index.js")){async function replaceResolvePathStatement(t){if(t.type==="ExpressionStatement"&&t.expression.type==="AssignmentExpression"&&t.expression.operator==="="&&t.expression.right.type==="CallExpression"&&t.expression.right.callee.type==="Identifier"&&t.expression.right.callee.name==="read"&&t.expression.right.arguments.length>=1&&t.expression.right.arguments[0].type==="CallExpression"&&t.expression.right.arguments[0].callee.type==="Identifier"&&t.expression.right.arguments[0].callee.name==="resolvePath"&&t.expression.right.arguments[0].arguments.length===1&&t.expression.right.arguments[0].arguments[0].type==="Literal"){const s=t.expression.right.arguments[0].arguments[0].value;let u;try{const t=await o.default(String(s),e,r);if(typeof t==="string"){u=t}else{return undefined}}catch(e){return undefined}const c="/"+a.relative(a.dirname(e),u);t.expression.right.arguments[0]={type:"BinaryExpression",start:t.expression.right.arguments[0].start,end:t.expression.right.arguments[0].end,operator:"+",left:{type:"Identifier",name:"__dirname"},right:{type:"Literal",value:c,raw:JSON.stringify(c)}}}return undefined}for(const e of t.body){if(e.type==="ExpressionStatement"&&e.expression.type==="AssignmentExpression"&&e.expression.operator==="="&&e.expression.left.type==="MemberExpression"&&e.expression.left.object.type==="MemberExpression"&&e.expression.left.object.object.type==="Identifier"&&e.expression.left.object.object.name==="Server"&&e.expression.left.object.property.type==="Identifier"&&e.expression.left.object.property.name==="prototype"&&e.expression.left.property.type==="Identifier"&&e.expression.left.property.name==="serveClient"&&e.expression.right.type==="FunctionExpression"){for(const t of e.expression.right.body.body){if(t.type==="IfStatement"&&t.consequent&&"body"in t.consequent&&t.consequent.body){const e=t.consequent.body;let r=false;if(Array.isArray(e)&&e[0]&&e[0].type==="ExpressionStatement"){r=await replaceResolvePathStatement(e[0])}if(Array.isArray(e)&&e[1]&&e[1].type==="TryStatement"&&e[1].block.body&&e[1].block.body[0]){r=await replaceResolvePathStatement(e[1].block.body[0])||r}return}}}}}},typescript({id:e,emitAssetDirectory:t}){if(e.endsWith("typescript/lib/tsc.js")){t(a.resolve(e,"../"))}},"uglify-es"({id:e,emitAsset:t}){if(e.endsWith("uglify-es/tools/node.js")){t(a.resolve(e,"../../lib/utils.js"));t(a.resolve(e,"../../lib/ast.js"));t(a.resolve(e,"../../lib/parse.js"));t(a.resolve(e,"../../lib/transform.js"));t(a.resolve(e,"../../lib/scope.js"));t(a.resolve(e,"../../lib/output.js"));t(a.resolve(e,"../../lib/compress.js"));t(a.resolve(e,"../../lib/sourcemap.js"));t(a.resolve(e,"../../lib/mozilla-ast.js"));t(a.resolve(e,"../../lib/propmangle.js"));t(a.resolve(e,"../../lib/minify.js"));t(a.resolve(e,"../exports.js"))}},"uglify-js"({id:e,emitAsset:t,emitAssetDirectory:r}){if(e.endsWith("uglify-js/tools/node.js")){r(a.resolve(e,"../../lib"));t(a.resolve(e,"../exports.js"))}},"playwright-core"({id:e,emitAsset:t}){if(e.endsWith("playwright-core/index.js")){t(a.resolve(a.dirname(e),"browsers.json"))}},"geo-tz"({id:e,emitAsset:t}){if(e.endsWith("geo-tz/dist/geo-tz.js")){t(a.resolve(a.dirname(e),"../data/geo.dat"))}}};async function handleSpecialCases({id:e,ast:t,emitAsset:r,emitAssetDirectory:s,job:a}){const o=u.getPackageName(e);const c=f[o||""];e=e.replace(/\\/g,"/");if(c)await c({id:e,ast:t,emitAsset:r,emitAssetDirectory:s,job:a})}t["default"]=handleSpecialCases},5401:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.wildcardRegEx=t.WILDCARD=t.FUNCTION=t.UNKNOWN=t.evaluate=void 0;const s=r(7310);async function evaluate(e,t={},r=true){const s={computeBranches:r,vars:t};return walk(e);function walk(e){const t=a[e.type];if(t){return t.call(s,e,walk)}return undefined}}t.evaluate=evaluate;t.UNKNOWN=Symbol();t.FUNCTION=Symbol();t.WILDCARD="";t.wildcardRegEx=/\x1a/g;function countWildcards(e){t.wildcardRegEx.lastIndex=0;let r=0;while(t.wildcardRegEx.exec(e))r++;return r}const a={ArrayExpression:async function ArrayExpression(e,t){const r=[];for(let s=0,a=e.elements.length;ss.value}}}return undefined},BinaryExpression:async function BinaryExpression(e,r){const s=e.operator;let a=await r(e.left);if(!a&&s!=="+")return;let o=await r(e.right);if(!a&&!o)return;if(!a){if(this.computeBranches&&o&&"value"in o&&typeof o.value==="string")return{value:t.WILDCARD+o.value,wildcards:[e.left,...o.wildcards||[]]};return}if(!o){if(this.computeBranches&&s==="+"){if(a&&"value"in a&&typeof a.value==="string")return{value:a.value+t.WILDCARD,wildcards:[...a.wildcards||[],e.right]}}if(!("test"in a)&&s==="||"&&a.value)return a;return}if("test"in a&&"value"in o){const e=o.value;if(s==="==")return{test:a.test,then:a.then==e,else:a.else==e};if(s==="===")return{test:a.test,then:a.then===e,else:a.else===e};if(s==="!=")return{test:a.test,then:a.then!=e,else:a.else!=e};if(s==="!==")return{test:a.test,then:a.then!==e,else:a.else!==e};if(s==="+")return{test:a.test,then:a.then+e,else:a.else+e};if(s==="-")return{test:a.test,then:a.then-e,else:a.else-e};if(s==="*")return{test:a.test,then:a.then*e,else:a.else*e};if(s==="/")return{test:a.test,then:a.then/e,else:a.else/e};if(s==="%")return{test:a.test,then:a.then%e,else:a.else%e};if(s==="<")return{test:a.test,then:a.then")return{test:a.test,then:a.then>e,else:a.else>e};if(s===">=")return{test:a.test,then:a.then>=e,else:a.else>=e};if(s==="|")return{test:a.test,then:a.then|e,else:a.else|e};if(s==="&")return{test:a.test,then:a.then&e,else:a.else&e};if(s==="^")return{test:a.test,then:a.then^e,else:a.else^e};if(s==="&&")return{test:a.test,then:a.then&&e,else:a.else&&e};if(s==="||")return{test:a.test,then:a.then||e,else:a.else||e}}else if("test"in o&&"value"in a){const e=a.value;if(s==="==")return{test:o.test,then:e==o.then,else:e==o.else};if(s==="===")return{test:o.test,then:e===o.then,else:e===o.else};if(s==="!=")return{test:o.test,then:e!=o.then,else:e!=o.else};if(s==="!==")return{test:o.test,then:e!==o.then,else:e!==o.else};if(s==="+")return{test:o.test,then:e+o.then,else:e+o.else};if(s==="-")return{test:o.test,then:e-o.then,else:e-o.else};if(s==="*")return{test:o.test,then:e*o.then,else:e*o.else};if(s==="/")return{test:o.test,then:e/o.then,else:e/o.else};if(s==="%")return{test:o.test,then:e%o.then,else:e%o.else};if(s==="<")return{test:o.test,then:e")return{test:o.test,then:e>o.then,else:e>o.else};if(s===">=")return{test:o.test,then:e>=o.then,else:e>=o.else};if(s==="|")return{test:o.test,then:e|o.then,else:e|o.else};if(s==="&")return{test:o.test,then:e&o.then,else:e&o.else};if(s==="^")return{test:o.test,then:e^o.then,else:e^o.else};if(s==="&&")return{test:o.test,then:e&&o.then,else:a&&o.else};if(s==="||")return{test:o.test,then:e||o.then,else:a||o.else}}else if("value"in a&&"value"in o){if(s==="==")return{value:a.value==o.value};if(s==="===")return{value:a.value===o.value};if(s==="!=")return{value:a.value!=o.value};if(s==="!==")return{value:a.value!==o.value};if(s==="+"){const e={value:a.value+o.value};let t=[];if("wildcards"in a&&a.wildcards){t=t.concat(a.wildcards)}if("wildcards"in o&&o.wildcards){t=t.concat(o.wildcards)}if(t.length>0){e.wildcards=t}return e}if(s==="-")return{value:a.value-o.value};if(s==="*")return{value:a.value*o.value};if(s==="/")return{value:a.value/o.value};if(s==="%")return{value:a.value%o.value};if(s==="<")return{value:a.value")return{value:a.value>o.value};if(s===">=")return{value:a.value>=o.value};if(s==="|")return{value:a.value|o.value};if(s==="&")return{value:a.value&o.value};if(s==="^")return{value:a.value^o.value};if(s==="&&")return{value:a.value&&o.value};if(s==="||")return{value:a.value||o.value}}return},CallExpression:async function CallExpression(e,r){var s;const a=await r(e.callee);if(!a||"test"in a)return;let o=a.value;if(typeof o==="object"&&o!==null)o=o[t.FUNCTION];if(typeof o!=="function")return;let u=null;if(e.callee.object){u=await r(e.callee.object);u=u&&"value"in u&&u.value?u.value:null}let c;let f=[];let p;let d=e.arguments.length>0&&((s=e.callee.property)===null||s===void 0?void 0:s.name)!=="concat";const h=[];for(let s=0,a=e.arguments.length;sh.push(e)))}else{if(!this.computeBranches)return;a={value:t.WILDCARD};h.push(e.arguments[s])}if("test"in a){if(h.length)return;if(c)return;c=a.test;p=f.concat([]);f.push(a.then);p.push(a.else)}else{f.push(a.value);if(p)p.push(a.value)}}if(d)return;try{const e=await o.apply(u,f);if(e===t.UNKNOWN)return;if(!c){if(h.length){if(typeof e!=="string"||countWildcards(e)!==h.length)return;return{value:e,wildcards:h}}return{value:e}}const r=await o.apply(u,p);if(e===t.UNKNOWN)return;return{test:c,then:e,else:r}}catch(e){return}},ConditionalExpression:async function ConditionalExpression(e,t){const r=await t(e.test);if(r&&"value"in r)return r.value?t(e.consequent):t(e.alternate);if(!this.computeBranches)return;const s=await t(e.consequent);if(!s||"wildcards"in s||"test"in s)return;const a=await t(e.alternate);if(!a||"wildcards"in a||"test"in a)return;return{test:e.test,then:s.value,else:a.value}},ExpressionStatement:async function ExpressionStatement(e,t){return t(e.expression)},Identifier:async function Identifier(e,t){if(Object.hasOwnProperty.call(this.vars,e.name))return this.vars[e.name];return undefined},Literal:async function Literal(e,t){return{value:e.value}},MemberExpression:async function MemberExpression(e,r){const s=await r(e.object);if(!s||"test"in s||typeof s.value==="function"){return undefined}if(e.property.type==="Identifier"){if(typeof s.value==="string"&&e.property.name==="concat"){return{value:{[t.FUNCTION]:(...e)=>s.value.concat(e)}}}if(typeof s.value==="object"&&s.value!==null){const a=s.value;if(e.computed){const o=await r(e.property);if(o&&"value"in o&&o.value){const e=a[o.value];if(e===t.UNKNOWN)return undefined;return{value:e}}if(!a[t.UNKNOWN]&&Object.keys(s).length===0){return{value:undefined}}}else if(e.property.name in a){const r=a[e.property.name];if(r===t.UNKNOWN)return undefined;return{value:r}}else if(a[t.UNKNOWN])return undefined}else{return{value:undefined}}}const a=await r(e.property);if(!a||"test"in a)return undefined;if(typeof s.value==="object"&&s.value!==null){if(a.value in s.value){const e=s.value[a.value];if(e===t.UNKNOWN)return undefined;return{value:e}}else if(s.value[t.UNKNOWN]){return undefined}}else{return{value:undefined}}return undefined},MetaProperty:async function MetaProperty(e){if(e.meta.name==="import"&&e.property.name==="meta")return{value:this.vars["import.meta"]};return undefined},NewExpression:async function NewExpression(e,t){const r=await t(e.callee);if(r&&"value"in r&&r.value===s.URL&&e.arguments.length){const r=await t(e.arguments[0]);if(!r)return undefined;let a=null;if(e.arguments[1]){a=await t(e.arguments[1]);if(!a||!("value"in a))return undefined}if("value"in r){if(a){try{return{value:new s.URL(r.value,a.value)}}catch(e){return undefined}}try{return{value:new s.URL(r.value)}}catch(e){return undefined}}else{const e=r.test;if(a){try{return{test:e,then:new s.URL(r.then,a.value),else:new s.URL(r.else,a.value)}}catch(e){return undefined}}try{return{test:e,then:new s.URL(r.then),else:new s.URL(r.else)}}catch(e){return undefined}}}return undefined},ObjectExpression:async function ObjectExpression(e,r){const s={};for(let a=0;a{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.handleWrappers=void 0;const s=r(7470);function isUndefinedOrVoid(e){return e.type==="Identifier"&&e.name==="undefined"||e.type==="UnaryExpression"&&e.operator==="void"&&e.argument.type==="Literal"&&e.argument.value===0}function handleWrappers(e){var t;let r;if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="UnaryExpression"&&e.body[0].expression.operator==="!"&&e.body[0].expression.argument.type==="CallExpression"&&e.body[0].expression.argument.callee.type==="FunctionExpression"&&e.body[0].expression.argument.arguments.length===1)r=e.body[0].expression.argument;else if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="CallExpression"&&e.body[0].expression.callee.type==="FunctionExpression"&&(e.body[0].expression.arguments.length===1||e.body[0].expression.arguments.length===0))r=e.body[0].expression;else if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="AssignmentExpression"&&e.body[0].expression.left.type==="MemberExpression"&&e.body[0].expression.left.object.type==="Identifier"&&e.body[0].expression.left.object.name==="module"&&e.body[0].expression.left.property.type==="Identifier"&&e.body[0].expression.left.property.name==="exports"&&e.body[0].expression.right.type==="CallExpression"&&e.body[0].expression.right.callee.type==="FunctionExpression"&&e.body[0].expression.right.arguments.length===1)r=e.body[0].expression.right;if(r){let e;let a;if(r.arguments[0]&&r.arguments[0].type==="ConditionalExpression"&&r.arguments[0].test.type==="LogicalExpression"&&r.arguments[0].test.operator==="&&"&&r.arguments[0].test.left.type==="BinaryExpression"&&r.arguments[0].test.left.operator==="==="&&r.arguments[0].test.left.left.type==="UnaryExpression"&&r.arguments[0].test.left.left.operator==="typeof"&&"name"in r.arguments[0].test.left.left.argument&&r.arguments[0].test.left.left.argument.name==="define"&&r.arguments[0].test.left.right.type==="Literal"&&r.arguments[0].test.left.right.value==="function"&&r.arguments[0].test.right.type==="MemberExpression"&&r.arguments[0].test.right.object.type==="Identifier"&&r.arguments[0].test.right.property.type==="Identifier"&&r.arguments[0].test.right.property.name==="amd"&&r.arguments[0].test.right.computed===false&&r.arguments[0].alternate.type==="FunctionExpression"&&r.arguments[0].alternate.params.length===1&&r.arguments[0].alternate.params[0].type==="Identifier"&&r.arguments[0].alternate.body.body.length===1&&r.arguments[0].alternate.body.body[0].type==="ExpressionStatement"&&r.arguments[0].alternate.body.body[0].expression.type==="AssignmentExpression"&&r.arguments[0].alternate.body.body[0].expression.left.type==="MemberExpression"&&r.arguments[0].alternate.body.body[0].expression.left.object.type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.left.object.name==="module"&&r.arguments[0].alternate.body.body[0].expression.left.property.type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.left.property.name==="exports"&&r.arguments[0].alternate.body.body[0].expression.left.computed===false&&r.arguments[0].alternate.body.body[0].expression.right.type==="CallExpression"&&r.arguments[0].alternate.body.body[0].expression.right.callee.type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.right.callee.name===r.arguments[0].alternate.params[0].name&&"body"in r.callee&&"body"in r.callee.body&&Array.isArray(r.callee.body.body)&&r.arguments[0].alternate.body.body[0].expression.right.arguments.length===1&&r.arguments[0].alternate.body.body[0].expression.right.arguments[0].type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.right.arguments[0].name==="require"){let e=r.callee.body.body;if(e[0].type==="ExpressionStatement"&&e[0].expression.type==="Literal"&&e[0].expression.value==="use strict"){e=e.slice(1)}if(e.length===1&&e[0].type==="ExpressionStatement"&&e[0].expression.type==="CallExpression"&&e[0].expression.callee.type==="Identifier"&&e[0].expression.callee.name===r.arguments[0].test.right.object.name&&e[0].expression.arguments.length===1&&e[0].expression.arguments[0].type==="FunctionExpression"&&e[0].expression.arguments[0].params.length===1&&e[0].expression.arguments[0].params[0].type==="Identifier"&&e[0].expression.arguments[0].params[0].name==="require"){const t=e[0].expression.arguments[0];t.params=[];try{delete t.scope.declarations.require}catch(e){}}}else if(r.arguments[0]&&r.arguments[0].type==="FunctionExpression"&&r.arguments[0].params.length===0&&(r.arguments[0].body.body.length===1||r.arguments[0].body.body.length===2&&r.arguments[0].body.body[0].type==="VariableDeclaration"&&r.arguments[0].body.body[0].declarations.length===3&&r.arguments[0].body.body[0].declarations.every((e=>e.init===null&&e.id.type==="Identifier")))&&r.arguments[0].body.body[r.arguments[0].body.body.length-1].type==="ReturnStatement"&&(e=r.arguments[0].body.body[r.arguments[0].body.body.length-1])&&((t=e.argument)===null||t===void 0?void 0:t.type)==="CallExpression"&&e.argument.arguments.length&&e.argument.arguments.every((e=>e&&e.type==="Literal"&&typeof e.value==="number"))&&e.argument.callee.type==="CallExpression"&&(e.argument.callee.callee.type==="FunctionExpression"||e.argument.callee.callee.type==="CallExpression"&&e.argument.callee.callee.callee.type==="FunctionExpression"&&e.argument.callee.callee.arguments.length===0)&&e.argument.callee.arguments.length===3&&e.argument.callee.arguments[0].type==="ObjectExpression"&&e.argument.callee.arguments[1].type==="ObjectExpression"&&e.argument.callee.arguments[2].type==="ArrayExpression"){const t=e.argument.callee.arguments[0].properties;const r={};if(t.every((e=>{if(e.type!=="Property"||e.computed!==false||e.key.type!=="Literal"||typeof e.key.value!=="number"||e.value.type!=="ArrayExpression"||e.value.elements.length!==2||!e.value.elements[0]||!e.value.elements[1]||e.value.elements[0].type!=="FunctionExpression"||e.value.elements[1].type!=="ObjectExpression"){return false}const t=e.value.elements[1].properties;for(const e of t){if(e.type!=="Property"||e.value.type!=="Identifier"&&e.value.type!=="Literal"&&!isUndefinedOrVoid(e.value)||!(e.key.type==="Literal"&&typeof e.key.value==="string"||e.key.type==="Identifier")||e.computed){return false}if(isUndefinedOrVoid(e.value)){if(e.key.type==="Identifier"){r[e.key.name]={type:"Literal",start:e.key.start,end:e.key.end,value:e.key.name,raw:JSON.stringify(e.key.name)}}else if(e.key.type==="Literal"){r[String(e.key.value)]=e.key}}}return true}))){const t=Object.keys(r);const s=e.argument.callee.arguments[1];s.properties=t.map((e=>({type:"Property",method:false,shorthand:false,computed:false,kind:"init",key:r[e],value:{type:"ObjectExpression",properties:[{type:"Property",kind:"init",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"exports"},value:{type:"CallExpression",optional:false,callee:{type:"Identifier",name:"require"},arguments:[r[e]]}}]}})))}}else if(r.arguments[0]&&r.arguments[0].type==="FunctionExpression"&&r.arguments[0].params.length===2&&r.arguments[0].params[0].type==="Identifier"&&r.arguments[0].params[1].type==="Identifier"&&"body"in r.callee&&"body"in r.callee.body&&Array.isArray(r.callee.body.body)&&r.callee.body.body.length===1){const e=r.callee.body.body[0];if(e.type==="IfStatement"&&e.test.type==="LogicalExpression"&&e.test.operator==="&&"&&e.test.left.type==="BinaryExpression"&&e.test.left.left.type==="UnaryExpression"&&e.test.left.left.operator==="typeof"&&e.test.left.left.argument.type==="Identifier"&&e.test.left.left.argument.name==="module"&&e.test.left.right.type==="Literal"&&e.test.left.right.value==="object"&&e.test.right.type==="BinaryExpression"&&e.test.right.left.type==="UnaryExpression"&&e.test.right.left.operator==="typeof"&&e.test.right.left.argument.type==="MemberExpression"&&e.test.right.left.argument.object.type==="Identifier"&&e.test.right.left.argument.object.name==="module"&&e.test.right.left.argument.property.type==="Identifier"&&e.test.right.left.argument.property.name==="exports"&&e.test.right.right.type==="Literal"&&e.test.right.right.value==="object"&&e.consequent.type==="BlockStatement"&&e.consequent.body.length>0){let t;if(e.consequent.body[0].type==="VariableDeclaration"&&e.consequent.body[0].declarations[0].init&&e.consequent.body[0].declarations[0].init.type==="CallExpression")t=e.consequent.body[0].declarations[0].init;else if(e.consequent.body[0].type==="ExpressionStatement"&&e.consequent.body[0].expression.type==="CallExpression")t=e.consequent.body[0].expression;else if(e.consequent.body[0].type==="ExpressionStatement"&&e.consequent.body[0].expression.type==="AssignmentExpression"&&e.consequent.body[0].expression.operator==="="&&e.consequent.body[0].expression.right.type==="CallExpression")t=e.consequent.body[0].expression.right;if(t&&t.callee.type==="Identifier"&&"params"in r.callee&&r.callee.params.length>0&&"name"in r.callee.params[0]&&t.callee.name===r.callee.params[0].name&&t.arguments.length===2&&t.arguments[0].type==="Identifier"&&t.arguments[0].name==="require"&&t.arguments[1].type==="Identifier"&&t.arguments[1].name==="exports"){const e=r.arguments[0];e.params=[];try{const t=e.scope;delete t.declarations.require;delete t.declarations.exports}catch(e){}}}}else if(r.callee.type==="FunctionExpression"&&r.callee.body.body.length>2&&r.callee.body.body[0].type==="VariableDeclaration"&&r.callee.body.body[0].declarations.length===1&&r.callee.body.body[0].declarations[0].type==="VariableDeclarator"&&r.callee.body.body[0].declarations[0].id.type==="Identifier"&&r.callee.body.body[0].declarations[0].init&&(r.callee.body.body[0].declarations[0].init.type==="ObjectExpression"&&r.callee.body.body[0].declarations[0].init.properties.length===0||r.callee.body.body[0].declarations[0].init.type==="CallExpression"&&r.callee.body.body[0].declarations[0].init.arguments.length===1)&&(r.callee.body.body[1]&&r.callee.body.body[1].type==="FunctionDeclaration"&&r.callee.body.body[1].params.length===1&&r.callee.body.body[1].body.body.length>=3||r.callee.body.body[2]&&r.callee.body.body[2].type==="FunctionDeclaration"&&r.callee.body.body[2].params.length===1&&r.callee.body.body[2].body.body.length>=3)&&(r.arguments[0]&&(r.arguments[0].type==="ArrayExpression"&&(a=r.arguments[0])&&r.arguments[0].elements.length>0&&r.arguments[0].elements.every((e=>e&&e.type==="FunctionExpression"))||r.arguments[0].type==="ObjectExpression"&&(a=r.arguments[0])&&r.arguments[0].properties&&r.arguments[0].properties.length>0&&r.arguments[0].properties.every((e=>e&&e.type==="Property"&&!e.computed&&e.key&&e.key.type==="Literal"&&(typeof e.key.value==="string"||typeof e.key.value==="number")&&e.value&&e.value.type==="FunctionExpression"))))||r.arguments.length===0&&r.callee.type==="FunctionExpression"&&r.callee.params.length===0&&r.callee.body.type==="BlockStatement"&&r.callee.body.body.length>5&&r.callee.body.body[0].type==="VariableDeclaration"&&r.callee.body.body[0].declarations.length===1&&r.callee.body.body[0].declarations[0].id.type==="Identifier"&&r.callee.body.body[1].type==="ExpressionStatement"&&r.callee.body.body[1].expression.type==="AssignmentExpression"&&r.callee.body.body[2].type==="ExpressionStatement"&&r.callee.body.body[2].expression.type==="AssignmentExpression"&&r.callee.body.body[3].type==="ExpressionStatement"&&r.callee.body.body[3].expression.type==="AssignmentExpression"&&r.callee.body.body[3].expression.left.type==="MemberExpression"&&r.callee.body.body[3].expression.left.object.type==="Identifier"&&r.callee.body.body[3].expression.left.object.name===r.callee.body.body[0].declarations[0].id.name&&r.callee.body.body[3].expression.left.property.type==="Identifier"&&r.callee.body.body[3].expression.left.property.name==="modules"&&r.callee.body.body[3].expression.right.type==="ObjectExpression"&&r.callee.body.body[3].expression.right.properties.every((e=>e&&e.type==="Property"&&!e.computed&&e.key&&e.key.type==="Literal"&&(typeof e.key.value==="string"||typeof e.key.value==="number")&&e.value&&e.value.type==="FunctionExpression"))&&(a=r.callee.body.body[3].expression.right)&&(r.callee.body.body[4].type==="VariableDeclaration"&&r.callee.body.body[4].declarations.length===1&&r.callee.body.body[4].declarations[0].init&&r.callee.body.body[4].declarations[0].init.type==="CallExpression"&&r.callee.body.body[4].declarations[0].init.callee.type==="Identifier"&&r.callee.body.body[4].declarations[0].init.callee.name==="require"||r.callee.body.body[5].type==="VariableDeclaration"&&r.callee.body.body[5].declarations.length===1&&r.callee.body.body[5].declarations[0].init&&r.callee.body.body[5].declarations[0].init.type==="CallExpression"&&r.callee.body.body[5].declarations[0].init.callee.type==="Identifier"&&r.callee.body.body[5].declarations[0].init.callee.name==="require")){const e=new Map;let t;if(a.type==="ArrayExpression")t=a.elements.filter((e=>(e===null||e===void 0?void 0:e.type)==="FunctionExpression")).map(((e,t)=>[String(t),e]));else t=a.properties.map((e=>[String(e.key.value),e.value]));for(const[r,s]of t){const t=s.body.body.length===1?s.body.body[0]:(s.body.body.length===2||s.body.body.length===3&&s.body.body[2].type==="EmptyStatement")&&s.body.body[0].type==="ExpressionStatement"&&s.body.body[0].expression.type==="Literal"&&s.body.body[0].expression.value==="use strict"?s.body.body[1]:null;if(t&&t.type==="ExpressionStatement"&&t.expression.type==="AssignmentExpression"&&t.expression.operator==="="&&t.expression.left.type==="MemberExpression"&&t.expression.left.object.type==="Identifier"&&"params"in s&&s.params.length>0&&"name"in s.params[0]&&t.expression.left.object.name===s.params[0].name&&t.expression.left.property.type==="Identifier"&&t.expression.left.property.name==="exports"&&t.expression.right.type==="CallExpression"&&t.expression.right.callee.type==="Identifier"&&t.expression.right.callee.name==="require"&&t.expression.right.arguments.length===1&&t.expression.right.arguments[0].type==="Literal"){e.set(r,t.expression.right.arguments[0].value)}}for(const[,r]of t){if("params"in r&&r.params.length===3&&r.params[2].type==="Identifier"){const t=new Map;s.walk(r.body,{enter(s,a){const o=s;const u=a;if(o.type==="CallExpression"&&o.callee.type==="Identifier"&&"name"in r.params[2]&&o.callee.name===r.params[2].name&&o.arguments.length===1&&o.arguments[0].type==="Literal"){const r=e.get(String(o.arguments[0].value));if(r){const e={type:"CallExpression",optional:false,callee:{type:"Identifier",name:"require"},arguments:[{type:"Literal",value:r}]};const s=u;if("right"in s&&s.right===o){s.right=e}else if("left"in s&&s.left===o){s.left=e}else if("object"in s&&s.object===o){s.object=e}else if("callee"in s&&s.callee===o){s.callee=e}else if("arguments"in s&&s.arguments.some((e=>e===o))){s.arguments=s.arguments.map((t=>t===o?e:t))}else if("init"in s&&s.init===o){if(s.type==="VariableDeclarator"&&s.id.type==="Identifier")t.set(s.id.name,r);s.init=e}}}else if(o.type==="CallExpression"&&o.callee.type==="MemberExpression"&&o.callee.object.type==="Identifier"&&"name"in r.params[2]&&o.callee.object.name===r.params[2].name&&o.callee.property.type==="Identifier"&&o.callee.property.name==="n"&&o.arguments.length===1&&o.arguments[0].type==="Identifier"){if(u&&"init"in u&&u.init===o){const e=o.arguments[0];const t={type:"CallExpression",optional:false,callee:{type:"MemberExpression",computed:false,optional:false,object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"assign"}},arguments:[{type:"ArrowFunctionExpression",expression:true,params:[],body:e},{type:"ObjectExpression",properties:[{type:"Property",kind:"init",method:false,computed:false,shorthand:false,key:{type:"Identifier",name:"a"},value:e}]}]};u.init=t}}}})}}}}}t.handleWrappers=handleWrappers},5920:(e,t)=>{e.exports=t=abbrev.abbrev=abbrev;abbrev.monkeyPatch=monkeyPatch;function monkeyPatch(){Object.defineProperty(Array.prototype,"abbrev",{value:function(){return abbrev(this)},enumerable:false,configurable:true,writable:true});Object.defineProperty(Object.prototype,"abbrev",{value:function(){return abbrev(Object.keys(this))},enumerable:false,configurable:true,writable:true})}function abbrev(e){if(arguments.length!==1||!Array.isArray(e)){e=Array.prototype.slice.call(arguments,0)}for(var t=0,r=e.length,s=[];tt?1:-1}},5534:e=>{"use strict";function isArguments(e){return e!=null&&typeof e==="object"&&e.hasOwnProperty("callee")}var t={"*":{label:"any",check:function(){return true}},A:{label:"array",check:function(e){return Array.isArray(e)||isArguments(e)}},S:{label:"string",check:function(e){return typeof e==="string"}},N:{label:"number",check:function(e){return typeof e==="number"}},F:{label:"function",check:function(e){return typeof e==="function"}},O:{label:"object",check:function(e){return typeof e==="object"&&e!=null&&!t.A.check(e)&&!t.E.check(e)}},B:{label:"boolean",check:function(e){return typeof e==="boolean"}},E:{label:"error",check:function(e){return e instanceof Error}},Z:{label:"null",check:function(e){return e==null}}};function addSchema(e,t){var r=t[e.length]=t[e.length]||[];if(r.indexOf(e)===-1)r.push(e)}var r=e.exports=function(e,r){if(arguments.length!==2)throw wrongNumberOfArgs(["SA"],arguments.length);if(!e)throw missingRequiredArg(0,"rawSchemas");if(!r)throw missingRequiredArg(1,"args");if(!t.S.check(e))throw invalidType(0,["string"],e);if(!t.A.check(r))throw invalidType(1,["array"],r);var s=e.split("|");var a={};s.forEach((function(e){for(var r=0;r{"use strict";t.TrackerGroup=r(2952);t.Tracker=r(6189);t.TrackerStream=r(5849)},8313:(e,t,r)=>{"use strict";var s=r(2361).EventEmitter;var a=r(3837);var o=0;var u=e.exports=function(e){s.call(this);this.id=++o;this.name=e};a.inherits(u,s)},2952:(e,t,r)=>{"use strict";var s=r(3837);var a=r(8313);var o=r(6189);var u=r(5849);var c=e.exports=function(e){a.call(this,e);this.parentGroup=null;this.trackers=[];this.completion={};this.weight={};this.totalWeight=0;this.finished=false;this.bubbleChange=bubbleChange(this)};s.inherits(c,a);function bubbleChange(e){return function(t,r,s){e.completion[s.id]=r;if(e.finished)return;e.emit("change",t||e.name,e.completed(),e)}}c.prototype.nameInTree=function(){var e=[];var t=this;while(t){e.unshift(t.name);t=t.parentGroup}return e.join("/")};c.prototype.addUnit=function(e,t){if(e.addUnit){var r=this;while(r){if(e===r){throw new Error("Attempted to add tracker group "+e.name+" to tree that already includes it "+this.nameInTree(this))}r=r.parentGroup}e.parentGroup=this}this.weight[e.id]=t||1;this.totalWeight+=this.weight[e.id];this.trackers.push(e);this.completion[e.id]=e.completed();e.on("change",this.bubbleChange);if(!this.finished)this.emit("change",e.name,this.completion[e.id],e);return e};c.prototype.completed=function(){if(this.trackers.length===0)return 0;var e=1/this.totalWeight;var t=0;for(var r=0;r{"use strict";var s=r(3837);var a=r(675);var o=r(1722);var u=r(6189);var c=e.exports=function(e,t,r){a.Transform.call(this,r);this.tracker=new u(e,t);this.name=e;this.id=this.tracker.id;this.tracker.on("change",delegateChange(this))};s.inherits(c,a.Transform);function delegateChange(e){return function(t,r,s){e.emit("change",t,r,e)}}c.prototype._transform=function(e,t,r){this.tracker.completeWork(e.length?e.length:1);this.push(e);r()};c.prototype._flush=function(e){this.tracker.finish();e()};o(c.prototype,"tracker").method("completed").method("addWork").method("finish")},6189:(e,t,r)=>{"use strict";var s=r(3837);var a=r(8313);var o=e.exports=function(e,t){a.call(this,e);this.workDone=0;this.workTodo=t||0};s.inherits(o,a);o.prototype.completed=function(){return this.workTodo===0?0:this.workDone/this.workTodo};o.prototype.addWork=function(e){this.workTodo+=e;this.emit("change",this.name,this.completed(),this)};o.prototype.completeWork=function(e){this.workDone+=e;if(this.workDone>this.workTodo)this.workDone=this.workTodo;this.emit("change",this.name,this.completed(),this)};o.prototype.finish=function(){this.workTodo=this.workDone=1;this.emit("change",this.name,1,this)}},5706:(module,exports,__nccwpck_require__)=>{var fs=__nccwpck_require__(7147),path=__nccwpck_require__(1017),fileURLToPath=__nccwpck_require__(9001),join=path.join,dirname=path.dirname,exists=fs.accessSync&&function(e){try{fs.accessSync(e)}catch(e){return false}return true}||fs.existsSync||path.existsSync,defaults={arrow:process.env.NODE_BINDINGS_ARROW||" → ",compiled:process.env.NODE_BINDINGS_COMPILED_DIR||"compiled",platform:process.platform,arch:process.arch,nodePreGyp:"node-v"+process.versions.modules+"-"+process.platform+"-"+process.arch,version:process.versions.node,bindings:"bindings.node",try:[["module_root","build","bindings"],["module_root","build","Debug","bindings"],["module_root","build","Release","bindings"],["module_root","out","Debug","bindings"],["module_root","Debug","bindings"],["module_root","out","Release","bindings"],["module_root","Release","bindings"],["module_root","build","default","bindings"],["module_root","compiled","version","platform","arch","bindings"],["module_root","addon-build","release","install-root","bindings"],["module_root","addon-build","debug","install-root","bindings"],["module_root","addon-build","default","install-root","bindings"],["module_root","lib","binding","nodePreGyp","bindings"]]};function bindings(opts){if(typeof opts=="string"){opts={bindings:opts}}else if(!opts){opts={}}Object.keys(defaults).map((function(e){if(!(e in opts))opts[e]=defaults[e]}));if(!opts.module_root){opts.module_root=exports.getRoot(exports.getFileName())}if(path.extname(opts.bindings)!=".node"){opts.bindings+=".node"}var requireFunc=true?eval("require"):0;var tries=[],i=0,l=opts.try.length,n,b,err;for(;i{"use strict";e.exports=function(e,t){if(e===null||e===undefined){throw TypeError()}e=String(e);var r=e.length;var s=t?Number(t):0;if(Number.isNaN(s)){s=0}if(s<0||s>=r){return undefined}var a=e.charCodeAt(s);if(a>=55296&&a<=56319&&r>s+1){var o=e.charCodeAt(s+1);if(o>=56320&&o<=57343){return(a-55296)*1024+o-56320+65536}}return a}},6322:(e,t)=>{"use strict";var r="[";t.up=function up(e){return r+(e||"")+"A"};t.down=function down(e){return r+(e||"")+"B"};t.forward=function forward(e){return r+(e||"")+"C"};t.back=function back(e){return r+(e||"")+"D"};t.nextLine=function nextLine(e){return r+(e||"")+"E"};t.previousLine=function previousLine(e){return r+(e||"")+"F"};t.horizontalAbsolute=function horizontalAbsolute(e){if(e==null)throw new Error("horizontalAboslute requires a column to position to");return r+e+"G"};t.eraseData=function eraseData(){return r+"J"};t.eraseLine=function eraseLine(){return r+"K"};t.goto=function(e,t){return r+t+";"+e+"H"};t.gotoSOL=function(){return"\r"};t.beep=function(){return""};t.hideCursor=function hideCursor(){return r+"?25l"};t.showCursor=function showCursor(){return r+"?25h"};var s={reset:0,bold:1,italic:3,underline:4,inverse:7,stopBold:22,stopItalic:23,stopUnderline:24,stopInverse:27,white:37,black:30,blue:34,cyan:36,green:32,magenta:35,red:31,yellow:33,bgWhite:47,bgBlack:40,bgBlue:44,bgCyan:46,bgGreen:42,bgMagenta:45,bgRed:41,bgYellow:43,grey:90,brightBlack:90,brightRed:91,brightGreen:92,brightYellow:93,brightBlue:94,brightMagenta:95,brightCyan:96,brightWhite:97,bgGrey:100,bgBrightBlack:100,bgBrightRed:101,bgBrightGreen:102,bgBrightYellow:103,bgBrightBlue:104,bgBrightMagenta:105,bgBrightCyan:106,bgBrightWhite:107};t.color=function color(e){if(arguments.length!==1||!Array.isArray(e)){e=Array.prototype.slice.call(arguments)}return r+e.map(colorNameToCode).join(";")+"m"};function colorNameToCode(e){if(s[e]!=null)return s[e];throw new Error("Unknown color or style name: "+e)}},3487:(e,t)=>{function isArray(e){if(Array.isArray){return Array.isArray(e)}return objectToString(e)==="[object Array]"}t.isArray=isArray;function isBoolean(e){return typeof e==="boolean"}t.isBoolean=isBoolean;function isNull(e){return e===null}t.isNull=isNull;function isNullOrUndefined(e){return e==null}t.isNullOrUndefined=isNullOrUndefined;function isNumber(e){return typeof e==="number"}t.isNumber=isNumber;function isString(e){return typeof e==="string"}t.isString=isString;function isSymbol(e){return typeof e==="symbol"}t.isSymbol=isSymbol;function isUndefined(e){return e===void 0}t.isUndefined=isUndefined;function isRegExp(e){return objectToString(e)==="[object RegExp]"}t.isRegExp=isRegExp;function isObject(e){return typeof e==="object"&&e!==null}t.isObject=isObject;function isDate(e){return objectToString(e)==="[object Date]"}t.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}t.isError=isError;function isFunction(e){return typeof e==="function"}t.isFunction=isFunction;function isPrimitive(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}t.isPrimitive=isPrimitive;t.isBuffer=Buffer.isBuffer;function objectToString(e){return Object.prototype.toString.call(e)}},1722:e=>{e.exports=Delegator;function Delegator(e,t){if(!(this instanceof Delegator))return new Delegator(e,t);this.proto=e;this.target=t;this.methods=[];this.getters=[];this.setters=[];this.fluents=[]}Delegator.prototype.method=function(e){var t=this.proto;var r=this.target;this.methods.push(e);t[e]=function(){return this[r][e].apply(this[r],arguments)};return this};Delegator.prototype.access=function(e){return this.getter(e).setter(e)};Delegator.prototype.getter=function(e){var t=this.proto;var r=this.target;this.getters.push(e);t.__defineGetter__(e,(function(){return this[r][e]}));return this};Delegator.prototype.setter=function(e){var t=this.proto;var r=this.target;this.setters.push(e);t.__defineSetter__(e,(function(t){return this[r][e]=t}));return this};Delegator.prototype.fluent=function(e){var t=this.proto;var r=this.target;this.fluents.push(e);t[e]=function(t){if("undefined"!=typeof t){this[r][e]=t;return this}else{return this[r][e]}};return this}},2157:(e,t,r)=>{"use strict";var s=r(2037).platform();var a=r(2081).spawnSync;var o=r(7147).readdirSync;var u="glibc";var c="musl";var f={encoding:"utf8",env:process.env};if(!a){a=function(){return{status:126,stdout:"",stderr:""}}}function contains(e){return function(t){return t.indexOf(e)!==-1}}function versionFromMuslLdd(e){return e.split(/[\r\n]+/)[1].trim().split(/\s/)[1]}function safeReaddirSync(e){try{return o(e)}catch(e){}return[]}var p="";var d="";var h="";if(s==="linux"){var v=a("getconf",["GNU_LIBC_VERSION"],f);if(v.status===0){p=u;d=v.stdout.trim().split(" ")[1];h="getconf"}else{var g=a("ldd",["--version"],f);if(g.status===0&&g.stdout.indexOf(c)!==-1){p=c;d=versionFromMuslLdd(g.stdout);h="ldd"}else if(g.status===1&&g.stderr.indexOf(c)!==-1){p=c;d=versionFromMuslLdd(g.stderr);h="ldd"}else{var m=safeReaddirSync("/lib");if(m.some(contains("-linux-gnu"))){p=u;h="filesystem"}else if(m.some(contains("libc.musl-"))){p=c;h="filesystem"}else if(m.some(contains("ld-musl-"))){p=c;h="filesystem"}else{var _=safeReaddirSync("/usr/sbin");if(_.some(contains("glibc"))){p=u;h="filesystem"}}}}}var y=p!==""&&p!==u;e.exports={GLIBC:u,MUSL:c,family:p,version:d,method:h,isNonGlibcLinux:y}},9001:(e,t,r)=>{var s=r(1017).sep||"/";e.exports=fileUriToPath;function fileUriToPath(e){if("string"!=typeof e||e.length<=7||"file://"!=e.substring(0,7)){throw new TypeError("must pass in a file:// URI to convert to a file path")}var t=decodeURI(e.substring(7));var r=t.indexOf("/");var a=t.substring(0,r);var o=t.substring(r+1);if("localhost"==a)a="";if(a){a=s+s+a}o=o.replace(/^(.+)\|/,"$1:");if(s=="\\"){o=o.replace(/\//g,"\\")}if(/^.+\:/.test(o)){}else{o=s+o}return a+o}},1271:(e,t,r)=>{"use strict";var s=r(1021);var a=r(5791);e.exports={activityIndicator:function(e,t,r){if(e.spun==null)return;return s(t,e.spun)},progressbar:function(e,t,r){if(e.completed==null)return;return a(t,r,e.completed)}}},2479:(e,t,r)=>{"use strict";var s=r(3837);var a=t.User=function User(e){var t=new Error(e);Error.captureStackTrace(t,User);t.code="EGAUGE";return t};t.MissingTemplateValue=function MissingTemplateValue(e,t){var r=new a(s.format('Missing template value "%s"',e.type));Error.captureStackTrace(r,MissingTemplateValue);r.template=e;r.values=t;return r};t.Internal=function Internal(e){var t=new Error(e);Error.captureStackTrace(t,Internal);t.code="EGAUGEINTERNAL";return t}},3278:e=>{"use strict";e.exports=isWin32()||isColorTerm();function isWin32(){return process.platform==="win32"}function isColorTerm(){var e=/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i;return!!process.env.COLORTERM||e.test(process.env.TERM)}},6054:(e,t,r)=>{"use strict";var s=r(4708);var a=r(7963);var o=r(3278);var u=r(2028);var c=r(7987);var f=r(75);var p=r(9186);var d=r(6401);e.exports=Gauge;function callWith(e,t){return function(){return t.call(e)}}function Gauge(e,t){var r,a;if(e&&e.write){a=e;r=t||{}}else if(t&&t.write){a=t;r=e||{}}else{a=p.stderr;r=e||t||{}}this._status={spun:0,section:"",subsection:""};this._paused=false;this._disabled=true;this._showing=false;this._onScreen=false;this._needsRedraw=false;this._hideCursor=r.hideCursor==null?true:r.hideCursor;this._fixedFramerate=r.fixedFramerate==null?!/^v0\.8\./.test(p.version):r.fixedFramerate;this._lastUpdateAt=null;this._updateInterval=r.updateInterval==null?50:r.updateInterval;this._themes=r.themes||c;this._theme=r.theme;var o=this._computeTheme(r.theme);var u=r.template||[{type:"progressbar",length:20},{type:"activityIndicator",kerning:1,length:1},{type:"section",kerning:1,default:""},{type:"subsection",kerning:1,default:""}];this.setWriteTo(a,r.tty);var f=r.Plumbing||s;this._gauge=new f(o,u,this.getWidth());this._$$doRedraw=callWith(this,this._doRedraw);this._$$handleSizeChange=callWith(this,this._handleSizeChange);this._cleanupOnExit=r.cleanupOnExit==null||r.cleanupOnExit;this._removeOnExit=null;if(r.enabled||r.enabled==null&&this._tty&&this._tty.isTTY){this.enable()}else{this.disable()}}Gauge.prototype={};Gauge.prototype.isEnabled=function(){return!this._disabled};Gauge.prototype.setTemplate=function(e){this._gauge.setTemplate(e);if(this._showing)this._requestRedraw()};Gauge.prototype._computeTheme=function(e){if(!e)e={};if(typeof e==="string"){e=this._themes.getTheme(e)}else if(e&&(Object.keys(e).length===0||e.hasUnicode!=null||e.hasColor!=null)){var t=e.hasUnicode==null?a():e.hasUnicode;var r=e.hasColor==null?o:e.hasColor;e=this._themes.getDefault({hasUnicode:t,hasColor:r,platform:e.platform})}return e};Gauge.prototype.setThemeset=function(e){this._themes=e;this.setTheme(this._theme)};Gauge.prototype.setTheme=function(e){this._gauge.setTheme(this._computeTheme(e));if(this._showing)this._requestRedraw();this._theme=e};Gauge.prototype._requestRedraw=function(){this._needsRedraw=true;if(!this._fixedFramerate)this._doRedraw()};Gauge.prototype.getWidth=function(){return(this._tty&&this._tty.columns||80)-1};Gauge.prototype.setWriteTo=function(e,t){var r=!this._disabled;if(r)this.disable();this._writeTo=e;this._tty=t||e===p.stderr&&p.stdout.isTTY&&p.stdout||e.isTTY&&e||this._tty;if(this._gauge)this._gauge.setWidth(this.getWidth());if(r)this.enable()};Gauge.prototype.enable=function(){if(!this._disabled)return;this._disabled=false;if(this._tty)this._enableEvents();if(this._showing)this.show()};Gauge.prototype.disable=function(){if(this._disabled)return;if(this._showing){this._lastUpdateAt=null;this._showing=false;this._doRedraw();this._showing=true}this._disabled=true;if(this._tty)this._disableEvents()};Gauge.prototype._enableEvents=function(){if(this._cleanupOnExit){this._removeOnExit=u(callWith(this,this.disable))}this._tty.on("resize",this._$$handleSizeChange);if(this._fixedFramerate){this.redrawTracker=f(this._$$doRedraw,this._updateInterval);if(this.redrawTracker.unref)this.redrawTracker.unref()}};Gauge.prototype._disableEvents=function(){this._tty.removeListener("resize",this._$$handleSizeChange);if(this._fixedFramerate)clearInterval(this.redrawTracker);if(this._removeOnExit)this._removeOnExit()};Gauge.prototype.hide=function(e){if(this._disabled)return e&&p.nextTick(e);if(!this._showing)return e&&p.nextTick(e);this._showing=false;this._doRedraw();e&&d(e)};Gauge.prototype.show=function(e,t){this._showing=true;if(typeof e==="string"){this._status.section=e}else if(typeof e==="object"){var r=Object.keys(e);for(var s=0;s{"use strict";var s=r(8753);e.exports=function(e){if(s(e)){return false}if(e>=4352&&(e<=4447||9001===e||9002===e||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141)){return true}return false}},5511:(e,t,r)=>{"use strict";var s=r(7518);var a=r(6708);var o=r(6062);e.exports=function(e){if(typeof e!=="string"||e.length===0){return 0}var t=0;e=s(e);for(var r=0;r=127&&u<=159){continue}if(u>=65536){r++}if(o(u)){t+=2}else{t++}}return t}},4708:(e,t,r)=>{"use strict";var s=r(6322);var a=r(4293);var o=r(5534);var u=e.exports=function(e,t,r){if(!r)r=80;o("OAN",[e,t,r]);this.showing=false;this.theme=e;this.width=r;this.template=t};u.prototype={};u.prototype.setTheme=function(e){o("O",[e]);this.theme=e};u.prototype.setTemplate=function(e){o("A",[e]);this.template=e};u.prototype.setWidth=function(e){o("N",[e]);this.width=e};u.prototype.hide=function(){return s.gotoSOL()+s.eraseLine()};u.prototype.hideCursor=s.hideCursor;u.prototype.showCursor=s.showCursor;u.prototype.show=function(e){var t=Object.create(this.theme);for(var r in e){t[r]=e[r]}return a(this.width,this.template,t).trim()+s.color("reset")+s.eraseLine()+s.gotoSOL()}},9186:e=>{"use strict";e.exports=process},5791:(e,t,r)=>{"use strict";var s=r(5534);var a=r(4293);var o=r(2343);var u=r(5511);e.exports=function(e,t,r){s("ONN",[e,t,r]);if(r<0)r=0;if(r>1)r=1;if(t<=0)return"";var o=Math.round(t*r);var u=t-o;var c=[{type:"complete",value:repeat(e.complete,o),length:o},{type:"remaining",value:repeat(e.remaining,u),length:u}];return a(t,c,e)};function repeat(e,t){var r="";var s=t;do{if(s%2){r+=e}s=Math.floor(s/2);e+=e}while(s&&u(r){"use strict";var s=r(7568);var a=r(5534);var o=r(1800);var u=r(2343);var c=r(2479);var f=r(5205);function renderValueWithValues(e){return function(t){return renderValue(t,e)}}var p=e.exports=function(e,t,r){var a=prepareItems(e,t,r);var o=a.map(renderValueWithValues(r)).join("");return s.left(u(o,e),e)};function preType(e){var t=e.type[0].toUpperCase()+e.type.slice(1);return"pre"+t}function postType(e){var t=e.type[0].toUpperCase()+e.type.slice(1);return"post"+t}function hasPreOrPost(e,t){if(!e.type)return;return t[preType(e)]||t[postType(e)]}function generatePreAndPost(e,t){var r=o({},e);var s=Object.create(t);var a=[];var u=preType(r);var c=postType(r);if(s[u]){a.push({value:s[u]});s[u]=null}r.minLength=null;r.length=null;r.maxLength=null;a.push(r);s[r.type]=s[r.type];if(s[c]){a.push({value:s[c]});s[c]=null}return function(e,t,r){return p(r,a,s)}}function prepareItems(e,t,r){function cloneAndObjectify(t,s,a){var o=new f(t,e);var u=o.type;if(o.value==null){if(!(u in r)){if(o.default==null){throw new c.MissingTemplateValue(o,r)}else{o.value=o.default}}else{o.value=r[u]}}if(o.value==null||o.value==="")return null;o.index=s;o.first=s===0;o.last=s===a.length-1;if(hasPreOrPost(o,r))o.value=generatePreAndPost(o,r);return o}var s=t.map(cloneAndObjectify).filter((function(e){return e!=null}));var a=0;var o=e;var u=s.length;function consumeSpace(e){if(e>o)e=o;a+=e;o-=e}function finishSizing(e,t){if(e.finished)throw new c.Internal("Tried to finish template item that was already finished");if(t===Infinity)throw new c.Internal("Length of template item cannot be infinity");if(t!=null)e.length=t;e.minLength=null;e.maxLength=null;--u;e.finished=true;if(e.length==null)e.length=e.getBaseLength();if(e.length==null)throw new c.Internal("Finished template items must have a length");consumeSpace(e.getLength())}s.forEach((function(e){if(!e.kerning)return;var t=e.first?0:s[e.index-1].padRight;if(!e.first&&t=h){finishSizing(e,e.minLength);d=true}}))}while(d&&p++{"use strict";var s=r(9186);try{e.exports=setImmediate}catch(t){e.exports=s.nextTick}},75:e=>{"use strict";e.exports=setInterval},1021:e=>{"use strict";e.exports=function spin(e,t){return e[t%e.length]}},5205:(e,t,r)=>{"use strict";var s=r(5511);e.exports=TemplateItem;function isPercent(e){if(typeof e!=="string")return false;return e.slice(-1)==="%"}function percent(e){return Number(e.slice(0,-1))/100}function TemplateItem(e,t){this.overallOutputLength=t;this.finished=false;this.type=null;this.value=null;this.length=null;this.maxLength=null;this.minLength=null;this.kerning=null;this.align="left";this.padLeft=0;this.padRight=0;this.index=null;this.first=null;this.last=null;if(typeof e==="string"){this.value=e}else{for(var r in e)this[r]=e[r]}if(isPercent(this.length)){this.length=Math.round(this.overallOutputLength*percent(this.length))}if(isPercent(this.minLength)){this.minLength=Math.round(this.overallOutputLength*percent(this.minLength))}if(isPercent(this.maxLength)){this.maxLength=Math.round(this.overallOutputLength*percent(this.maxLength))}return this}TemplateItem.prototype={};TemplateItem.prototype.getBaseLength=function(){var e=this.length;if(e==null&&typeof this.value==="string"&&this.maxLength==null&&this.minLength==null){e=s(this.value)}return e};TemplateItem.prototype.getLength=function(){var e=this.getBaseLength();if(e==null)return null;return e+this.padLeft+this.padRight};TemplateItem.prototype.getMaxLength=function(){if(this.maxLength==null)return null;return this.maxLength+this.padLeft+this.padRight};TemplateItem.prototype.getMinLength=function(){if(this.minLength==null)return null;return this.minLength+this.padLeft+this.padRight}},3117:(e,t,r)=>{"use strict";var s=r(1800);e.exports=function(){return a.newThemeSet()};var a={};a.baseTheme=r(1271);a.newTheme=function(e,t){if(!t){t=e;e=this.baseTheme}return s({},e,t)};a.getThemeNames=function(){return Object.keys(this.themes)};a.addTheme=function(e,t,r){this.themes[e]=this.newTheme(t,r)};a.addToAllThemes=function(e){var t=this.themes;Object.keys(t).forEach((function(r){s(t[r],e)}));s(this.baseTheme,e)};a.getTheme=function(e){if(!this.themes[e])throw this.newMissingThemeError(e);return this.themes[e]};a.setDefault=function(e,t){if(t==null){t=e;e={}}var r=e.platform==null?"fallback":e.platform;var s=!!e.hasUnicode;var a=!!e.hasColor;if(!this.defaults[r])this.defaults[r]={true:{},false:{}};this.defaults[r][s][a]=t};a.getDefault=function(e){if(!e)e={};var t=e.platform||process.platform;var r=this.defaults[t]||this.defaults.fallback;var a=!!e.hasUnicode;var o=!!e.hasColor;if(!r)throw this.newMissingDefaultThemeError(t,a,o);if(!r[a][o]){if(a&&o&&r[!a][o]){a=false}else if(a&&o&&r[a][!o]){o=false}else if(a&&o&&r[!a][!o]){a=false;o=false}else if(a&&!o&&r[!a][o]){a=false}else if(!a&&o&&r[a][!o]){o=false}else if(r===this.defaults.fallback){throw this.newMissingDefaultThemeError(t,a,o)}}if(r[a][o]){return this.getTheme(r[a][o])}else{return this.getDefault(s({},e,{platform:"fallback"}))}};a.newMissingThemeError=function newMissingThemeError(e){var t=new Error('Could not find a gauge theme named "'+e+'"');Error.captureStackTrace.call(t,newMissingThemeError);t.theme=e;t.code="EMISSINGTHEME";return t};a.newMissingDefaultThemeError=function newMissingDefaultThemeError(e,t,r){var s=new Error("Could not find a gauge theme for your platform/unicode/color use combo:\n"+" platform = "+e+"\n"+" hasUnicode = "+t+"\n"+" hasColor = "+r);Error.captureStackTrace.call(s,newMissingDefaultThemeError);s.platform=e;s.hasUnicode=t;s.hasColor=r;s.code="EMISSINGTHEME";return s};a.newThemeSet=function(){var themeset=function(e){return themeset.getDefault(e)};return s(themeset,a,{themes:s({},this.themes),baseTheme:s({},this.baseTheme),defaults:JSON.parse(JSON.stringify(this.defaults||{}))})}},7987:(e,t,r)=>{"use strict";var s=r(6322);var a=r(3117);var o=e.exports=new a;o.addTheme("ASCII",{preProgressbar:"[",postProgressbar:"]",progressbarTheme:{complete:"#",remaining:"."},activityIndicatorTheme:"-\\|/",preSubsection:">"});o.addTheme("colorASCII",o.getTheme("ASCII"),{progressbarTheme:{preComplete:s.color("inverse"),complete:" ",postComplete:s.color("stopInverse"),preRemaining:s.color("brightBlack"),remaining:".",postRemaining:s.color("reset")}});o.addTheme("brailleSpinner",{preProgressbar:"⸨",postProgressbar:"⸩",progressbarTheme:{complete:"░",remaining:"⠂"},activityIndicatorTheme:"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏",preSubsection:">"});o.addTheme("colorBrailleSpinner",o.getTheme("brailleSpinner"),{progressbarTheme:{preComplete:s.color("inverse"),complete:" ",postComplete:s.color("stopInverse"),preRemaining:s.color("brightBlack"),remaining:"░",postRemaining:s.color("reset")}});o.setDefault({},"ASCII");o.setDefault({hasColor:true},"colorASCII");o.setDefault({platform:"darwin",hasUnicode:true},"brailleSpinner");o.setDefault({platform:"darwin",hasUnicode:true,hasColor:true},"colorBrailleSpinner")},2343:(e,t,r)=>{"use strict";var s=r(5511);var a=r(7518);e.exports=wideTruncate;function wideTruncate(e,t){if(s(e)===0)return e;if(t<=0)return"";if(s(e)<=t)return e;var r=a(e);var o=e.length+r.length;var u=e.slice(0,t+o);while(s(u)>t){u=u.slice(0,-1)}return u}},9132:e=>{"use strict";e.exports=clone;var t=Object.getPrototypeOf||function(e){return e.__proto__};function clone(e){if(e===null||typeof e!=="object")return e;if(e instanceof Object)var r={__proto__:t(e)};else var r=Object.create(null);Object.getOwnPropertyNames(e).forEach((function(t){Object.defineProperty(r,t,Object.getOwnPropertyDescriptor(e,t))}));return r}},552:(e,t,r)=>{var s=r(7147);var a=r(1290);var o=r(4410);var u=r(9132);var c=r(3837);var f;var p;if(typeof Symbol==="function"&&typeof Symbol.for==="function"){f=Symbol.for("graceful-fs.queue");p=Symbol.for("graceful-fs.previous")}else{f="___graceful-fs.queue";p="___graceful-fs.previous"}function noop(){}function publishQueue(e,t){Object.defineProperty(e,f,{get:function(){return t}})}var d=noop;if(c.debuglog)d=c.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))d=function(){var e=c.format.apply(c,arguments);e="GFS4: "+e.split(/\n/).join("\nGFS4: ");console.error(e)};if(!s[f]){var h=global[f]||[];publishQueue(s,h);s.close=function(e){function close(t,r){return e.call(s,t,(function(e){if(!e){resetQueue()}if(typeof r==="function")r.apply(this,arguments)}))}Object.defineProperty(close,p,{value:e});return close}(s.close);s.closeSync=function(e){function closeSync(t){e.apply(s,arguments);resetQueue()}Object.defineProperty(closeSync,p,{value:e});return closeSync}(s.closeSync);if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")){process.on("exit",(function(){d(s[f]);r(9491).equal(s[f].length,0)}))}}if(!global[f]){publishQueue(global,s[f])}e.exports=patch(u(s));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!s.__patched){e.exports=patch(s);s.__patched=true}function patch(e){a(e);e.gracefulify=patch;e.createReadStream=createReadStream;e.createWriteStream=createWriteStream;var t=e.readFile;e.readFile=readFile;function readFile(e,r,s){if(typeof r==="function")s=r,r=null;return go$readFile(e,r,s);function go$readFile(e,r,s,a){return t(e,r,(function(t){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))enqueue([go$readFile,[e,r,s],t,a||Date.now(),Date.now()]);else{if(typeof s==="function")s.apply(this,arguments)}}))}}var r=e.writeFile;e.writeFile=writeFile;function writeFile(e,t,s,a){if(typeof s==="function")a=s,s=null;return go$writeFile(e,t,s,a);function go$writeFile(e,t,s,a,o){return r(e,t,s,(function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))enqueue([go$writeFile,[e,t,s,a],r,o||Date.now(),Date.now()]);else{if(typeof a==="function")a.apply(this,arguments)}}))}}var s=e.appendFile;if(s)e.appendFile=appendFile;function appendFile(e,t,r,a){if(typeof r==="function")a=r,r=null;return go$appendFile(e,t,r,a);function go$appendFile(e,t,r,a,o){return s(e,t,r,(function(s){if(s&&(s.code==="EMFILE"||s.code==="ENFILE"))enqueue([go$appendFile,[e,t,r,a],s,o||Date.now(),Date.now()]);else{if(typeof a==="function")a.apply(this,arguments)}}))}}var u=e.copyFile;if(u)e.copyFile=copyFile;function copyFile(e,t,r,s){if(typeof r==="function"){s=r;r=0}return go$copyFile(e,t,r,s);function go$copyFile(e,t,r,s,a){return u(e,t,r,(function(o){if(o&&(o.code==="EMFILE"||o.code==="ENFILE"))enqueue([go$copyFile,[e,t,r,s],o,a||Date.now(),Date.now()]);else{if(typeof s==="function")s.apply(this,arguments)}}))}}var c=e.readdir;e.readdir=readdir;function readdir(e,t,r){if(typeof t==="function")r=t,t=null;return go$readdir(e,t,r);function go$readdir(e,t,r,s){return c(e,t,(function(a,o){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))enqueue([go$readdir,[e,t,r],a,s||Date.now(),Date.now()]);else{if(o&&o.sort)o.sort();if(typeof r==="function")r.call(this,a,o)}}))}}if(process.version.substr(0,4)==="v0.8"){var f=o(e);ReadStream=f.ReadStream;WriteStream=f.WriteStream}var p=e.ReadStream;if(p){ReadStream.prototype=Object.create(p.prototype);ReadStream.prototype.open=ReadStream$open}var d=e.WriteStream;if(d){WriteStream.prototype=Object.create(d.prototype);WriteStream.prototype.open=WriteStream$open}Object.defineProperty(e,"ReadStream",{get:function(){return ReadStream},set:function(e){ReadStream=e},enumerable:true,configurable:true});Object.defineProperty(e,"WriteStream",{get:function(){return WriteStream},set:function(e){WriteStream=e},enumerable:true,configurable:true});var h=ReadStream;Object.defineProperty(e,"FileReadStream",{get:function(){return h},set:function(e){h=e},enumerable:true,configurable:true});var v=WriteStream;Object.defineProperty(e,"FileWriteStream",{get:function(){return v},set:function(e){v=e},enumerable:true,configurable:true});function ReadStream(e,t){if(this instanceof ReadStream)return p.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var e=this;open(e.path,e.flags,e.mode,(function(t,r){if(t){if(e.autoClose)e.destroy();e.emit("error",t)}else{e.fd=r;e.emit("open",r);e.read()}}))}function WriteStream(e,t){if(this instanceof WriteStream)return d.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var e=this;open(e.path,e.flags,e.mode,(function(t,r){if(t){e.destroy();e.emit("error",t)}else{e.fd=r;e.emit("open",r)}}))}function createReadStream(t,r){return new e.ReadStream(t,r)}function createWriteStream(t,r){return new e.WriteStream(t,r)}var g=e.open;e.open=open;function open(e,t,r,s){if(typeof r==="function")s=r,r=null;return go$open(e,t,r,s);function go$open(e,t,r,s,a){return g(e,t,r,(function(o,u){if(o&&(o.code==="EMFILE"||o.code==="ENFILE"))enqueue([go$open,[e,t,r,s],o,a||Date.now(),Date.now()]);else{if(typeof s==="function")s.apply(this,arguments)}}))}}return e}function enqueue(e){d("ENQUEUE",e[0].name,e[1]);s[f].push(e);retry()}var v;function resetQueue(){var e=Date.now();for(var t=0;t2){s[f][t][3]=e;s[f][t][4]=e}}retry()}function retry(){clearTimeout(v);v=undefined;if(s[f].length===0)return;var e=s[f].shift();var t=e[0];var r=e[1];var a=e[2];var o=e[3];var u=e[4];if(o===undefined){d("RETRY",t.name,r);t.apply(null,r)}else if(Date.now()-o>=6e4){d("TIMEOUT",t.name,r);var c=r.pop();if(typeof c==="function")c.call(null,a)}else{var p=Date.now()-u;var h=Math.max(u-o,1);var g=Math.min(h*1.2,100);if(p>=g){d("RETRY",t.name,r);t.apply(null,r.concat([o]))}else{s[f].push(e)}}if(v===undefined){v=setTimeout(retry,0)}}},4410:(e,t,r)=>{var s=r(2781).Stream;e.exports=legacy;function legacy(e){return{ReadStream:ReadStream,WriteStream:WriteStream};function ReadStream(t,r){if(!(this instanceof ReadStream))return new ReadStream(t,r);s.call(this);var a=this;this.path=t;this.fd=null;this.readable=true;this.paused=false;this.flags="r";this.mode=438;this.bufferSize=64*1024;r=r||{};var o=Object.keys(r);for(var u=0,c=o.length;uthis.end){throw new Error("start must be <= end")}this.pos=this.start}if(this.fd!==null){process.nextTick((function(){a._read()}));return}e.open(this.path,this.flags,this.mode,(function(e,t){if(e){a.emit("error",e);a.readable=false;return}a.fd=t;a.emit("open",t);a._read()}))}function WriteStream(t,r){if(!(this instanceof WriteStream))return new WriteStream(t,r);s.call(this);this.path=t;this.fd=null;this.writable=true;this.flags="w";this.encoding="binary";this.mode=438;this.bytesWritten=0;r=r||{};var a=Object.keys(r);for(var o=0,u=a.length;o= zero")}this.pos=this.start}this.busy=false;this._queue=[];if(this.fd===null){this._open=e.open;this._queue.push([this._open,this.path,this.flags,this.mode,undefined]);this.flush()}}}},1290:(e,t,r)=>{var s=r(2057);var a=process.cwd;var o=null;var u=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!o)o=a.call(process);return o};try{process.cwd()}catch(e){}if(typeof process.chdir==="function"){var c=process.chdir;process.chdir=function(e){o=null;c.call(process,e)};if(Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,c)}e.exports=patch;function patch(e){if(s.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)){patchLchmod(e)}if(!e.lutimes){patchLutimes(e)}e.chown=chownFix(e.chown);e.fchown=chownFix(e.fchown);e.lchown=chownFix(e.lchown);e.chmod=chmodFix(e.chmod);e.fchmod=chmodFix(e.fchmod);e.lchmod=chmodFix(e.lchmod);e.chownSync=chownFixSync(e.chownSync);e.fchownSync=chownFixSync(e.fchownSync);e.lchownSync=chownFixSync(e.lchownSync);e.chmodSync=chmodFixSync(e.chmodSync);e.fchmodSync=chmodFixSync(e.fchmodSync);e.lchmodSync=chmodFixSync(e.lchmodSync);e.stat=statFix(e.stat);e.fstat=statFix(e.fstat);e.lstat=statFix(e.lstat);e.statSync=statFixSync(e.statSync);e.fstatSync=statFixSync(e.fstatSync);e.lstatSync=statFixSync(e.lstatSync);if(!e.lchmod){e.lchmod=function(e,t,r){if(r)process.nextTick(r)};e.lchmodSync=function(){}}if(!e.lchown){e.lchown=function(e,t,r,s){if(s)process.nextTick(s)};e.lchownSync=function(){}}if(u==="win32"){e.rename=function(t){return function(r,s,a){var o=Date.now();var u=0;t(r,s,(function CB(c){if(c&&(c.code==="EACCES"||c.code==="EPERM")&&Date.now()-o<6e4){setTimeout((function(){e.stat(s,(function(e,o){if(e&&e.code==="ENOENT")t(r,s,CB);else a(c)}))}),u);if(u<100)u+=10;return}if(a)a(c)}))}}(e.rename)}e.read=function(t){function read(r,s,a,o,u,c){var f;if(c&&typeof c==="function"){var p=0;f=function(d,h,v){if(d&&d.code==="EAGAIN"&&p<10){p++;return t.call(e,r,s,a,o,u,f)}c.apply(this,arguments)}}return t.call(e,r,s,a,o,u,f)}if(Object.setPrototypeOf)Object.setPrototypeOf(read,t);return read}(e.read);e.readSync=function(t){return function(r,s,a,o,u){var c=0;while(true){try{return t.call(e,r,s,a,o,u)}catch(e){if(e.code==="EAGAIN"&&c<10){c++;continue}throw e}}}}(e.readSync);function patchLchmod(e){e.lchmod=function(t,r,a){e.open(t,s.O_WRONLY|s.O_SYMLINK,r,(function(t,s){if(t){if(a)a(t);return}e.fchmod(s,r,(function(t){e.close(s,(function(e){if(a)a(t||e)}))}))}))};e.lchmodSync=function(t,r){var a=e.openSync(t,s.O_WRONLY|s.O_SYMLINK,r);var o=true;var u;try{u=e.fchmodSync(a,r);o=false}finally{if(o){try{e.closeSync(a)}catch(e){}}else{e.closeSync(a)}}return u}}function patchLutimes(e){if(s.hasOwnProperty("O_SYMLINK")){e.lutimes=function(t,r,a,o){e.open(t,s.O_SYMLINK,(function(t,s){if(t){if(o)o(t);return}e.futimes(s,r,a,(function(t){e.close(s,(function(e){if(o)o(t||e)}))}))}))};e.lutimesSync=function(t,r,a){var o=e.openSync(t,s.O_SYMLINK);var u;var c=true;try{u=e.futimesSync(o,r,a);c=false}finally{if(c){try{e.closeSync(o)}catch(e){}}else{e.closeSync(o)}}return u}}else{e.lutimes=function(e,t,r,s){if(s)process.nextTick(s)};e.lutimesSync=function(){}}}function chmodFix(t){if(!t)return t;return function(r,s,a){return t.call(e,r,s,(function(e){if(chownErOk(e))e=null;if(a)a.apply(this,arguments)}))}}function chmodFixSync(t){if(!t)return t;return function(r,s){try{return t.call(e,r,s)}catch(e){if(!chownErOk(e))throw e}}}function chownFix(t){if(!t)return t;return function(r,s,a,o){return t.call(e,r,s,a,(function(e){if(chownErOk(e))e=null;if(o)o.apply(this,arguments)}))}}function chownFixSync(t){if(!t)return t;return function(r,s,a){try{return t.call(e,r,s,a)}catch(e){if(!chownErOk(e))throw e}}}function statFix(t){if(!t)return t;return function(r,s,a){if(typeof s==="function"){a=s;s=null}function callback(e,t){if(t){if(t.uid<0)t.uid+=4294967296;if(t.gid<0)t.gid+=4294967296}if(a)a.apply(this,arguments)}return s?t.call(e,r,s,callback):t.call(e,r,callback)}}function statFixSync(t){if(!t)return t;return function(r,s){var a=s?t.call(e,r,s):t.call(e,r);if(a){if(a.uid<0)a.uid+=4294967296;if(a.gid<0)a.gid+=4294967296}return a}}function chownErOk(e){if(!e)return true;if(e.code==="ENOSYS")return true;var t=!process.getuid||process.getuid()!==0;if(t){if(e.code==="EINVAL"||e.code==="EPERM")return true}return false}}},7963:(e,t,r)=>{"use strict";var s=r(2037);var a=e.exports=function(){if(s.type()=="Windows_NT"){return false}var e=/UTF-?8$/i;var t=process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG;return e.test(t)}},6919:(e,t,r)=>{try{var s=r(3837);if(typeof s.inherits!=="function")throw"";e.exports=s.inherits}catch(t){e.exports=r(7526)}},7526:e=>{if(typeof Object.create==="function"){e.exports=function inherits(e,t){if(t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}}else{e.exports=function inherits(e,t){if(t){e.super_=t;var TempCtor=function(){};TempCtor.prototype=t.prototype;e.prototype=new TempCtor;e.prototype.constructor=e}}}},9842:e=>{var t={}.toString;e.exports=Array.isArray||function(e){return t.call(e)=="[object Array]"}},3277:(module,__unused_webpack_exports,__nccwpck_require__)=>{var fs=__nccwpck_require__(7147);var path=__nccwpck_require__(1017);var os=__nccwpck_require__(2037);var runtimeRequire=true?eval("require"):0;var vars=process.config&&process.config.variables||{};var prebuildsOnly=!!process.env.PREBUILDS_ONLY;var abi=process.versions.modules;var runtime=isElectron()?"electron":"node";var arch=os.arch();var platform=os.platform();var libc=process.env.LIBC||(isAlpine(platform)?"musl":"glibc");var armv=process.env.ARM_VERSION||(arch==="arm64"?"8":vars.arm_version)||"";var uv=(process.versions.uv||"").split(".")[0];module.exports=load;function load(e){return runtimeRequire(load.path(e))}load.path=function(e){e=path.resolve(e||".");try{var t=runtimeRequire(path.join(e,"package.json")).name.toUpperCase().replace(/-/g,"_");if(process.env[t+"_PREBUILD"])e=process.env[t+"_PREBUILD"]}catch(e){}if(!prebuildsOnly){var r=getFirst(path.join(e,"build/Release"),matchBuild);if(r)return r;var s=getFirst(path.join(e,"build/Debug"),matchBuild);if(s)return s}var a=resolve(e);if(a)return a;var o=resolve(path.dirname(process.execPath));if(o)return o;var u=["platform="+platform,"arch="+arch,"runtime="+runtime,"abi="+abi,"uv="+uv,armv?"armv="+armv:"","libc="+libc,"node="+process.versions.node,process.versions&&process.versions.electron?"electron="+process.versions.electron:"",true?"webpack=true":0].filter(Boolean).join(" ");throw new Error("No native build was found for "+u+"\n loaded from: "+e+"\n");function resolve(e){var t=path.join(e,"prebuilds",platform+"-"+arch);var r=readdirSync(t).map(parseTags);var s=r.filter(matchTags(runtime,abi));var a=s.sort(compareTags(runtime))[0];if(a)return path.join(t,a.file)}};function readdirSync(e){try{return fs.readdirSync(e)}catch(e){return[]}}function getFirst(e,t){var r=readdirSync(e).filter(t);return r[0]&&path.join(e,r[0])}function matchBuild(e){return/\.node$/.test(e)}function parseTags(e){var t=e.split(".");var r=t.pop();var s={file:e,specificity:0};if(r!=="node")return;for(var a=0;ar.specificity?-1:1}else{return 0}}}function isElectron(){if(process.versions&&process.versions.electron)return true;if(process.env.ELECTRON_RUN_AS_NODE)return true;return typeof window!=="undefined"&&window.process&&window.process.type==="renderer"}function isAlpine(e){return e==="linux"&&fs.existsSync("/etc/alpine-release")}load.parseTags=parseTags;load.matchTags=matchTags;load.compareTags=compareTags},9248:(e,t,r)=>{"use strict";var s=r(7147);var a=r(3632);var o=r(9658);e.exports=t;var u=process.version.substr(1).replace(/-.*$/,"").split(".").map((function(e){return+e}));var c=["build","clean","configure","package","publish","reveal","testbinary","testpackage","unpublish"];var f="napi_build_version=";e.exports.get_napi_version=function(e){var t=process.versions.napi;if(!t){if(u[0]===9&&u[1]>=3)t=2;else if(u[0]===8)t=1}return t};e.exports.get_napi_version_as_string=function(t){var r=e.exports.get_napi_version(t);return r?""+r:""};e.exports.validate_package_json=function(t,r){var s=t.binary;var a=pathOK(s.module_path);var o=pathOK(s.remote_path);var u=pathOK(s.package_name);var c=e.exports.get_napi_build_versions(t,r,true);var f=e.exports.get_napi_build_versions_raw(t);if(c){c.forEach((function(e){if(!(parseInt(e,10)===e&&e>0)){throw new Error("All values specified in napi_versions must be positive integers.")}}))}if(c&&(!a||!o&&!u)){throw new Error("When napi_versions is specified; module_path and either remote_path or "+"package_name must contain the substitution string '{napi_build_version}`.")}if((a||o||u)&&!f){throw new Error("When the substitution string '{napi_build_version}` is specified in "+"module_path, remote_path, or package_name; napi_versions must also be specified.")}if(c&&!e.exports.get_best_napi_build_version(t,r)&&e.exports.build_napi_only(t)){throw new Error("The N-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports N-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}if(f&&!c&&e.exports.build_napi_only(t)){throw new Error("The N-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports N-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}};function pathOK(e){return e&&(e.indexOf("{napi_build_version}")!==-1||e.indexOf("{node_napi_label}")!==-1)}e.exports.expand_commands=function(t,r,s){var a=[];var o=e.exports.get_napi_build_versions(t,r);s.forEach((function(s){if(o&&s.name==="install"){var u=e.exports.get_best_napi_build_version(t,r);var p=u?[f+u]:[];a.push({name:s.name,args:p})}else if(o&&c.indexOf(s.name)!==-1){o.forEach((function(e){var t=s.args.slice();t.push(f+e);a.push({name:s.name,args:t})}))}else{a.push(s)}}));return a};e.exports.get_napi_build_versions=function(t,r,s){var a=[];var u=e.exports.get_napi_version(r?r.target:undefined);if(t.binary&&t.binary.napi_versions){t.binary.napi_versions.forEach((function(e){var t=a.indexOf(e)!==-1;if(!t&&u&&e<=u){a.push(e)}else if(s&&!t&&u){o.info("This Node instance does not support builds for N-API version",e)}}))}if(r&&r["build-latest-napi-version-only"]){var c=0;a.forEach((function(e){if(e>c)c=e}));a=c?[c]:[]}return a.length?a:undefined};e.exports.get_napi_build_versions_raw=function(e){var t=[];if(e.binary&&e.binary.napi_versions){e.binary.napi_versions.forEach((function(e){if(t.indexOf(e)===-1){t.push(e)}}))}return t.length?t:undefined};e.exports.get_command_arg=function(e){return f+e};e.exports.get_napi_build_version_from_command_args=function(e){for(var t=0;ts&&e<=o){s=e}}))}return s===0?undefined:s};e.exports.build_napi_only=function(e){return e.binary&&e.binary.package_name&&e.binary.package_name.indexOf("{node_napi_label}")===-1}},5574:(e,t,r)=>{"use strict";e.exports=t;var s=r(1017);var a=r(7849);var o=r(7310);var u=r(2157);var c=r(9248);var f;if(process.env.NODE_PRE_GYP_ABI_CROSSWALK){f=require(process.env.NODE_PRE_GYP_ABI_CROSSWALK)}else{f=r(7316)}var p={};Object.keys(f).forEach((function(e){var t=e.split(".")[0];if(!p[t]){p[t]=e}}));function get_electron_abi(e,t){if(!e){throw new Error("get_electron_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if electron is the target.")}var r=a.parse(t);return e+"-v"+r.major+"."+r.minor}e.exports.get_electron_abi=get_electron_abi;function get_node_webkit_abi(e,t){if(!e){throw new Error("get_node_webkit_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if node-webkit is the target.")}return e+"-v"+t}e.exports.get_node_webkit_abi=get_node_webkit_abi;function get_node_abi(e,t){if(!e){throw new Error("get_node_abi requires valid runtime arg")}if(!t){throw new Error("get_node_abi requires valid process.versions object")}var r=a.parse(t.node);if(r.major===0&&r.minor%2){return e+"-v"+t.node}else{return t.modules?e+"-v"+ +t.modules:"v8-"+t.v8.split(".").slice(0,2).join(".")}}e.exports.get_node_abi=get_node_abi;function get_runtime_abi(e,t){if(!e){throw new Error("get_runtime_abi requires valid runtime arg")}if(e==="node-webkit"){return get_node_webkit_abi(e,t||process.versions["node-webkit"])}else if(e==="electron"){return get_electron_abi(e,t||process.versions.electron)}else{if(e!="node"){throw new Error("Unknown Runtime: '"+e+"'")}if(!t){return get_node_abi(e,process.versions)}else{var r;if(f[t]){r=f[t]}else{var s=t.split(".").map((function(e){return+e}));if(s.length!=3){throw new Error("Unknown target version: "+t)}var a=s[0];var o=s[1];var u=s[2];if(a===1){while(true){if(o>0)--o;if(u>0)--u;var c=""+a+"."+o+"."+u;if(f[c]){r=f[c];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+c+" as ABI compatible target");break}if(o===0&&u===0){break}}}else if(a>=2){if(p[a]){r=f[p[a]];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+p[a]+" as ABI compatible target")}}else if(a===0){if(s[1]%2===0){while(--u>0){var d=""+a+"."+o+"."+u;if(f[d]){r=f[d];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+d+" as ABI compatible target");break}}}}}if(!r){throw new Error("Unsupported target version: "+t)}var h={node:t,v8:r.v8+".0",modules:r.node_abi>1?r.node_abi:undefined};return get_node_abi(e,h)}}}e.exports.get_runtime_abi=get_runtime_abi;var d=["module_name","module_path","host"];function validate_config(e,t){var r=e.name+" package.json is not node-pre-gyp ready:\n";var s=[];if(!e.main){s.push("main")}if(!e.version){s.push("version")}if(!e.name){s.push("name")}if(!e.binary){s.push("binary")}var a=e.binary;d.forEach((function(e){if(s.indexOf("binary")>-1){s.pop("binary")}if(!a||a[e]===undefined||a[e]===""){s.push("binary."+e)}}));if(s.length>=1){throw new Error(r+"package.json must declare these properties: \n"+s.join("\n"))}if(a){var u=o.parse(a.host).protocol;if(u==="http:"){throw new Error("'host' protocol ("+u+") is invalid - only 'https:' is accepted")}}c.validate_package_json(e,t)}e.exports.validate_config=validate_config;function eval_template(e,t){Object.keys(t).forEach((function(r){var s="{"+r+"}";while(e.indexOf(s)>-1){e=e.replace(s,t[r])}}));return e}function fix_slashes(e){if(e.slice(-1)!="/"){return e+"/"}return e}function drop_double_slashes(e){return e.replace(/\/\//g,"/")}function get_process_runtime(e){var t="node";if(e["node-webkit"]){t="node-webkit"}else if(e.electron){t="electron"}return t}e.exports.get_process_runtime=get_process_runtime;var h="{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz";var v="";e.exports.evaluate=function(e,t,r){t=t||{};validate_config(e,t);var f=e.version;var p=a.parse(f);var d=t.runtime||get_process_runtime(process.versions);var g={name:e.name,configuration:Boolean(t.debug)?"Debug":"Release",debug:t.debug,module_name:e.binary.module_name,version:p.version,prerelease:p.prerelease.length?p.prerelease.join("."):"",build:p.build.length?p.build.join("."):"",major:p.major,minor:p.minor,patch:p.patch,runtime:d,node_abi:get_runtime_abi(d,t.target),node_abi_napi:c.get_napi_version(t.target)?"napi":get_runtime_abi(d,t.target),napi_version:c.get_napi_version(t.target),napi_build_version:r||"",node_napi_label:r?"napi-v"+r:get_runtime_abi(d,t.target),target:t.target||"",platform:t.target_platform||process.platform,target_platform:t.target_platform||process.platform,arch:t.target_arch||process.arch,target_arch:t.target_arch||process.arch,libc:t.target_libc||u.family||"unknown",module_main:e.main,toolset:t.toolset||""};var m=process.env["npm_config_"+g.module_name+"_binary_host_mirror"]||e.binary.host;g.host=fix_slashes(eval_template(m,g));g.module_path=eval_template(e.binary.module_path,g);if(t.module_root){g.module_path=s.join(t.module_root,g.module_path)}else{g.module_path=s.resolve(g.module_path)}g.module=s.join(g.module_path,g.module_name+".node");g.remote_path=e.binary.remote_path?drop_double_slashes(fix_slashes(eval_template(e.binary.remote_path,g))):v;var _=e.binary.package_name?e.binary.package_name:h;g.package_name=eval_template(_,g);g.staged_tarball=s.join("build/stage",g.remote_path,g.package_name);g.hosted_path=o.resolve(g.host,g.remote_path);g.hosted_tarball=o.resolve(g.hosted_path,g.package_name);return g}},3632:(e,t,r)=>{e.exports=rimraf;rimraf.sync=rimrafSync;var s=r(9491);var a=r(1017);var o=r(7147);var u=undefined;try{u=r(3535)}catch(e){}var c=parseInt("666",8);var f={nosort:true,silent:true};var p=0;var d=process.platform==="win32";function defaults(e){var t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach((function(t){e[t]=e[t]||o[t];t=t+"Sync";e[t]=e[t]||o[t]}));e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&u===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||f}function rimraf(e,t,r){if(typeof t==="function"){r=t;t={}}s(e,"rimraf: missing path");s.equal(typeof e,"string","rimraf: path should be a string");s.equal(typeof r,"function","rimraf: callback function required");s(t,"rimraf: invalid options argument provided");s.equal(typeof t,"object","rimraf: options should be object");defaults(t);var a=0;var o=null;var c=0;if(t.disableGlob||!u.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,(function(r,s){if(!r)return afterGlob(null,[e]);u(e,t.glob,afterGlob)}));function next(e){o=o||e;if(--c===0)r(o)}function afterGlob(e,s){if(e)return r(e);c=s.length;if(c===0)return r();s.forEach((function(e){rimraf_(e,t,(function CB(r){if(r){if((r.code==="EBUSY"||r.code==="ENOTEMPTY"||r.code==="EPERM")&&a{"use strict";var s=r(2717);var a=r(6054);var o=r(2361).EventEmitter;var u=t=e.exports=new o;var c=r(3837);var f=r(8834);var p=r(6322);f(true);var d=process.stderr;Object.defineProperty(u,"stream",{set:function(e){d=e;if(this.gauge)this.gauge.setWriteTo(d,d)},get:function(){return d}});var h;u.useColor=function(){return h!=null?h:d.isTTY};u.enableColor=function(){h=true;this.gauge.setTheme({hasColor:h,hasUnicode:v})};u.disableColor=function(){h=false;this.gauge.setTheme({hasColor:h,hasUnicode:v})};u.level="info";u.gauge=new a(d,{enabled:false,theme:{hasColor:u.useColor()},template:[{type:"progressbar",length:20},{type:"activityIndicator",kerning:1,length:1},{type:"section",default:""},":",{type:"logline",kerning:1,default:""}]});u.tracker=new s.TrackerGroup;u.progressEnabled=u.gauge.isEnabled();var v;u.enableUnicode=function(){v=true;this.gauge.setTheme({hasColor:this.useColor(),hasUnicode:v})};u.disableUnicode=function(){v=false;this.gauge.setTheme({hasColor:this.useColor(),hasUnicode:v})};u.setGaugeThemeset=function(e){this.gauge.setThemeset(e)};u.setGaugeTemplate=function(e){this.gauge.setTemplate(e)};u.enableProgress=function(){if(this.progressEnabled)return;this.progressEnabled=true;this.tracker.on("change",this.showProgress);if(this._pause)return;this.gauge.enable()};u.disableProgress=function(){if(!this.progressEnabled)return;this.progressEnabled=false;this.tracker.removeListener("change",this.showProgress);this.gauge.disable()};var g=["newGroup","newItem","newStream"];var mixinLog=function(e){Object.keys(u).forEach((function(t){if(t[0]==="_")return;if(g.filter((function(e){return e===t})).length)return;if(e[t])return;if(typeof u[t]!=="function")return;var r=u[t];e[t]=function(){return r.apply(u,arguments)}}));if(e instanceof s.TrackerGroup){g.forEach((function(t){var r=e[t];e[t]=function(){return mixinLog(r.apply(e,arguments))}}))}return e};g.forEach((function(e){u[e]=function(){return mixinLog(this.tracker[e].apply(this.tracker,arguments))}}));u.clearProgress=function(e){if(!this.progressEnabled)return e&&process.nextTick(e);this.gauge.hide(e)};u.showProgress=function(e,t){if(!this.progressEnabled)return;var r={};if(e)r.section=e;var s=u.record[u.record.length-1];if(s){r.subsection=s.prefix;var a=u.disp[s.level]||s.level;var o=this._format(a,u.style[s.level]);if(s.prefix)o+=" "+this._format(s.prefix,this.prefixStyle);o+=" "+s.message.split(/\r?\n/)[0];r.logline=o}r.completed=t||this.tracker.completed();this.gauge.show(r)}.bind(u);u.pause=function(){this._paused=true;if(this.progressEnabled)this.gauge.disable()};u.resume=function(){if(!this._paused)return;this._paused=false;var e=this._buffer;this._buffer=[];e.forEach((function(e){this.emitLog(e)}),this);if(this.progressEnabled)this.gauge.enable()};u._buffer=[];var m=0;u.record=[];u.maxRecordSize=1e4;u.log=function(e,t,r){var s=this.levels[e];if(s===undefined){return this.emit("error",new Error(c.format("Undefined log level: %j",e)))}var a=new Array(arguments.length-2);var o=null;for(var u=2;ud/10){var v=Math.floor(d*.9);this.record=this.record.slice(-1*v)}this.emitLog(p)}.bind(u);u.emitLog=function(e){if(this._paused){this._buffer.push(e);return}if(this.progressEnabled)this.gauge.pulse(e.prefix);var t=this.levels[e.level];if(t===undefined)return;if(t0&&!isFinite(t))return;var r=u.disp[e.level]!=null?u.disp[e.level]:e.level;this.clearProgress();e.message.split(/\r?\n/).forEach((function(t){if(this.heading){this.write(this.heading,this.headingStyle);this.write(" ")}this.write(r,u.style[e.level]);var s=e.prefix||"";if(s)this.write(" ");this.write(s,this.prefixStyle);this.write(" "+t+"\n")}),this);this.showProgress()};u._format=function(e,t){if(!d)return;var r="";if(this.useColor()){t=t||{};var s=[];if(t.fg)s.push(t.fg);if(t.bg)s.push("bg"+t.bg[0].toUpperCase()+t.bg.slice(1));if(t.bold)s.push("bold");if(t.underline)s.push("underline");if(t.inverse)s.push("inverse");if(s.length)r+=p.color(s);if(t.beep)r+=p.beep()}r+=e;if(this.useColor()){r+=p.color("reset")}return r};u.write=function(e,t){if(!d)return;d.write(this._format(e,t))};u.addLevel=function(e,t,r,s){if(s==null)s=e;this.levels[e]=t;this.style[e]=r;if(!this[e]){this[e]=function(){var t=new Array(arguments.length+1);t[0]=e;for(var r=0;r{"use strict";e.exports=Number.isNaN||function(e){return e!==e}},1800:e=>{"use strict"; +(()=>{var __webpack_modules__={111:(e,t,r)=>{"use strict";e.exports=t;t.mockS3Http=r(7048).get_mockS3Http();t.mockS3Http("on");const a=t.mockS3Http("get");const o=r(7147);const s=r(1017);const u=r(1400);const c=r(9658);c.disableProgress();const d=r(5677);const f=r(2361).EventEmitter;const p=r(3837).inherits;const h=["clean","install","reinstall","build","rebuild","package","testpackage","publish","unpublish","info","testbinary","reveal","configure"];const v={};c.heading="node-pre-gyp";if(a){c.warn(`mocking s3 to ${process.env.node_pre_gyp_mock_s3}`)}Object.defineProperty(t,"find",{get:function(){return r(3093).find},enumerable:true});function Run({package_json_path:e="./package.json",argv:t}){this.package_json_path=e;this.commands={};const r=this;h.forEach((e=>{r.commands[e]=function(t,a){c.verbose("command",e,t);return require("./"+e)(r,t,a)}}));this.parseArgv(t);this.binaryHostSet=false}p(Run,f);t.Run=Run;const _=Run.prototype;_.package=r(9286);_.configDefs={help:Boolean,arch:String,debug:Boolean,directory:String,proxy:String,loglevel:String};_.shorthands={release:"--no-debug",C:"--directory",debug:"--debug",j:"--jobs",silent:"--loglevel=silent",silly:"--loglevel=silly",verbose:"--loglevel=verbose"};_.aliases=v;_.parseArgv=function parseOpts(e){this.opts=u(this.configDefs,this.shorthands,e);this.argv=this.opts.argv.remain.slice();const t=this.todo=[];e=this.argv.map((e=>{if(e in this.aliases){e=this.aliases[e]}return e}));e.slice().forEach((r=>{if(r in this.commands){const a=e.splice(0,e.indexOf(r));e.shift();if(t.length>0){t[t.length-1].args=a}t.push({name:r,args:[]})}}));if(t.length>0){t[t.length-1].args=e.splice(0)}let r=this.package_json_path;if(this.opts.directory){r=s.join(this.opts.directory,r)}this.package_json=JSON.parse(o.readFileSync(r));this.todo=d.expand_commands(this.package_json,this.opts,t);const a="npm_config_";Object.keys(process.env).forEach((e=>{if(e.indexOf(a)!==0)return;const t=process.env[e];if(e===a+"loglevel"){c.level=t}else{e=e.substring(a.length);if(e==="argv"){if(this.opts.argv&&this.opts.argv.remain&&this.opts.argv.remain.length){}else{this.opts[e]=t}}else{this.opts[e]=t}}}));if(this.opts.loglevel){c.level=this.opts.loglevel}c.resume()};_.setBinaryHostProperty=function(e){if(this.binaryHostSet){return this.package_json.binary.host}const t=this.package_json;if(!t||!t.binary||t.binary.host){return""}if(!t.binary.staging_host||!t.binary.production_host){return""}let r="production_host";if(e==="publish"){r="staging_host"}const a=process.env.node_pre_gyp_s3_host;if(a==="staging"||a==="production"){r=`${a}_host`}else if(this.opts["s3_host"]==="staging"||this.opts["s3_host"]==="production"){r=`${this.opts["s3_host"]}_host`}else if(this.opts["s3_host"]||a){throw new Error(`invalid s3_host ${this.opts["s3_host"]||a}`)}t.binary.host=t.binary[r];this.binaryHostSet=true;return t.binary.host};_.usage=function usage(){const e=[""," Usage: node-pre-gyp [options]",""," where is one of:",h.map((e=>" - "+e+" - "+require("./"+e).usage)).join("\n"),"","node-pre-gyp@"+this.version+" "+s.resolve(__dirname,".."),"node@"+process.versions.node].join("\n");return e};Object.defineProperty(_,"version",{get:function(){return this.package.version},enumerable:true})},3093:(e,t,r)=>{"use strict";const a=r(111);const o=r(302);const s=r(5677);const u=r(7147).existsSync||r(1017).existsSync;const c=r(1017);e.exports=t;t.usage="Finds the require path for the node-pre-gyp installed module";t.validate=function(e,t){o.validate_config(e,t)};t.find=function(e,t){if(!u(e)){throw new Error(e+"does not exist")}const r=new a.Run({package_json_path:e,argv:process.argv});r.setBinaryHostProperty();const d=r.package_json;o.validate_config(d,t);let f;if(s.get_napi_build_versions(d,t)){f=s.get_best_napi_build_version(d,t)}t=t||{};if(!t.module_root)t.module_root=c.dirname(e);const p=o.evaluate(d,t,f);return p.module}},5677:(e,t,r)=>{"use strict";const a=r(7147);e.exports=t;const o=process.version.substr(1).replace(/-.*$/,"").split(".").map((e=>+e));const s=["build","clean","configure","package","publish","reveal","testbinary","testpackage","unpublish"];const u="napi_build_version=";e.exports.get_napi_version=function(){let e=process.versions.napi;if(!e){if(o[0]===9&&o[1]>=3)e=2;else if(o[0]===8)e=1}return e};e.exports.get_napi_version_as_string=function(t){const r=e.exports.get_napi_version(t);return r?""+r:""};e.exports.validate_package_json=function(t,r){const a=t.binary;const o=pathOK(a.module_path);const s=pathOK(a.remote_path);const u=pathOK(a.package_name);const c=e.exports.get_napi_build_versions(t,r,true);const d=e.exports.get_napi_build_versions_raw(t);if(c){c.forEach((e=>{if(!(parseInt(e,10)===e&&e>0)){throw new Error("All values specified in napi_versions must be positive integers.")}}))}if(c&&(!o||!s&&!u)){throw new Error("When napi_versions is specified; module_path and either remote_path or "+"package_name must contain the substitution string '{napi_build_version}`.")}if((o||s||u)&&!d){throw new Error("When the substitution string '{napi_build_version}` is specified in "+"module_path, remote_path, or package_name; napi_versions must also be specified.")}if(c&&!e.exports.get_best_napi_build_version(t,r)&&e.exports.build_napi_only(t)){throw new Error("The Node-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports Node-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}if(d&&!c&&e.exports.build_napi_only(t)){throw new Error("The Node-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports Node-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}};function pathOK(e){return e&&(e.indexOf("{napi_build_version}")!==-1||e.indexOf("{node_napi_label}")!==-1)}e.exports.expand_commands=function(t,r,a){const o=[];const c=e.exports.get_napi_build_versions(t,r);a.forEach((a=>{if(c&&a.name==="install"){const s=e.exports.get_best_napi_build_version(t,r);const c=s?[u+s]:[];o.push({name:a.name,args:c})}else if(c&&s.indexOf(a.name)!==-1){c.forEach((e=>{const t=a.args.slice();t.push(u+e);o.push({name:a.name,args:t})}))}else{o.push(a)}}));return o};e.exports.get_napi_build_versions=function(t,a,o){const s=r(9658);let u=[];const c=e.exports.get_napi_version(a?a.target:undefined);if(t.binary&&t.binary.napi_versions){t.binary.napi_versions.forEach((e=>{const t=u.indexOf(e)!==-1;if(!t&&c&&e<=c){u.push(e)}else if(o&&!t&&c){s.info("This Node instance does not support builds for Node-API version",e)}}))}if(a&&a["build-latest-napi-version-only"]){let e=0;u.forEach((t=>{if(t>e)e=t}));u=e?[e]:[]}return u.length?u:undefined};e.exports.get_napi_build_versions_raw=function(e){const t=[];if(e.binary&&e.binary.napi_versions){e.binary.napi_versions.forEach((e=>{if(t.indexOf(e)===-1){t.push(e)}}))}return t.length?t:undefined};e.exports.get_command_arg=function(e){return u+e};e.exports.get_napi_build_version_from_command_args=function(e){for(let t=0;t{if(e>a&&e<=t){a=e}}))}return a===0?undefined:a};e.exports.build_napi_only=function(e){return e.binary&&e.binary.package_name&&e.binary.package_name.indexOf("{node_napi_label}")===-1}},7048:(e,t,r)=>{"use strict";e.exports=t;const a=r(7310);const o=r(7147);const s=r(1017);e.exports.detect=function(e,t){const r=e.hosted_path;const o=a.parse(r);t.prefix=!o.pathname||o.pathname==="/"?"":o.pathname.replace("/","");if(e.bucket&&e.region){t.bucket=e.bucket;t.region=e.region;t.endpoint=e.host;t.s3ForcePathStyle=e.s3ForcePathStyle}else{const e=o.hostname.split(".s3");const r=e[0];if(!r){return}if(!t.bucket){t.bucket=r}if(!t.region){const r=e[1].slice(1).split(".")[0];if(r==="amazonaws"){t.region="us-east-1"}else{t.region=r}}}};e.exports.get_s3=function(e){if(process.env.node_pre_gyp_mock_s3){const e=r(2722);const t=r(2037);e.config.basePath=`${t.tmpdir()}/mock`;const a=e.S3();const wcb=e=>(t,...r)=>{if(t&&t.code==="ENOENT"){t.code="NotFound"}return e(t,...r)};return{listObjects(e,t){return a.listObjects(e,wcb(t))},headObject(e,t){return a.headObject(e,wcb(t))},deleteObject(e,t){return a.deleteObject(e,wcb(t))},putObject(e,t){return a.putObject(e,wcb(t))}}}const t=r(918);t.config.update(e);const a=new t.S3;return{listObjects(e,t){return a.listObjects(e,t)},headObject(e,t){return a.headObject(e,t)},deleteObject(e,t){return a.deleteObject(e,t)},putObject(e,t){return a.putObject(e,t)}}};e.exports.get_mockS3Http=function(){let e=false;if(!process.env.node_pre_gyp_mock_s3){return()=>e}const t=r(3902);const a="https://mapbox-node-pre-gyp-public-testing-bucket.s3.us-east-1.amazonaws.com";const u=process.env.node_pre_gyp_mock_s3+"/mapbox-node-pre-gyp-public-testing-bucket";const mock_http=()=>{function get(e,t){const r=s.join(u,e.replace("%2B","+"));try{o.accessSync(r,o.constants.R_OK)}catch(e){return[404,"not found\n"]}return[200,o.createReadStream(r)]}return t(a).persist().get((()=>e)).reply(get)};mock_http(t,a,u);const mockS3Http=t=>{const r=e;if(t==="off"){e=false}else if(t==="on"){e=true}else if(t!=="get"){throw new Error(`illegal action for setMockHttp ${t}`)}return r};return mockS3Http}},302:(e,t,r)=>{"use strict";e.exports=t;const a=r(1017);const o=r(7849);const s=r(7310);const u=r(2157);const c=r(5677);let d;if(process.env.NODE_PRE_GYP_ABI_CROSSWALK){d=require(process.env.NODE_PRE_GYP_ABI_CROSSWALK)}else{d=r(2339)}const f={};Object.keys(d).forEach((e=>{const t=e.split(".")[0];if(!f[t]){f[t]=e}}));function get_electron_abi(e,t){if(!e){throw new Error("get_electron_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if electron is the target.")}const r=o.parse(t);return e+"-v"+r.major+"."+r.minor}e.exports.get_electron_abi=get_electron_abi;function get_node_webkit_abi(e,t){if(!e){throw new Error("get_node_webkit_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if node-webkit is the target.")}return e+"-v"+t}e.exports.get_node_webkit_abi=get_node_webkit_abi;function get_node_abi(e,t){if(!e){throw new Error("get_node_abi requires valid runtime arg")}if(!t){throw new Error("get_node_abi requires valid process.versions object")}const r=o.parse(t.node);if(r.major===0&&r.minor%2){return e+"-v"+t.node}else{return t.modules?e+"-v"+ +t.modules:"v8-"+t.v8.split(".").slice(0,2).join(".")}}e.exports.get_node_abi=get_node_abi;function get_runtime_abi(e,t){if(!e){throw new Error("get_runtime_abi requires valid runtime arg")}if(e==="node-webkit"){return get_node_webkit_abi(e,t||process.versions["node-webkit"])}else if(e==="electron"){return get_electron_abi(e,t||process.versions.electron)}else{if(e!=="node"){throw new Error("Unknown Runtime: '"+e+"'")}if(!t){return get_node_abi(e,process.versions)}else{let r;if(d[t]){r=d[t]}else{const e=t.split(".").map((e=>+e));if(e.length!==3){throw new Error("Unknown target version: "+t)}const a=e[0];let o=e[1];let s=e[2];if(a===1){while(true){if(o>0)--o;if(s>0)--s;const e=""+a+"."+o+"."+s;if(d[e]){r=d[e];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+e+" as ABI compatible target");break}if(o===0&&s===0){break}}}else if(a>=2){if(f[a]){r=d[f[a]];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+f[a]+" as ABI compatible target")}}else if(a===0){if(e[1]%2===0){while(--s>0){const e=""+a+"."+o+"."+s;if(d[e]){r=d[e];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+e+" as ABI compatible target");break}}}}}if(!r){throw new Error("Unsupported target version: "+t)}const a={node:t,v8:r.v8+".0",modules:r.node_abi>1?r.node_abi:undefined};return get_node_abi(e,a)}}}e.exports.get_runtime_abi=get_runtime_abi;const p=["module_name","module_path","host"];function validate_config(e,t){const r=e.name+" package.json is not node-pre-gyp ready:\n";const a=[];if(!e.main){a.push("main")}if(!e.version){a.push("version")}if(!e.name){a.push("name")}if(!e.binary){a.push("binary")}const o=e.binary;if(o){p.forEach((e=>{if(!o[e]||typeof o[e]!=="string"){a.push("binary."+e)}}))}if(a.length>=1){throw new Error(r+"package.json must declare these properties: \n"+a.join("\n"))}if(o){const e=s.parse(o.host).protocol;if(e==="http:"){throw new Error("'host' protocol ("+e+") is invalid - only 'https:' is accepted")}}c.validate_package_json(e,t)}e.exports.validate_config=validate_config;function eval_template(e,t){Object.keys(t).forEach((r=>{const a="{"+r+"}";while(e.indexOf(a)>-1){e=e.replace(a,t[r])}}));return e}function fix_slashes(e){if(e.slice(-1)!=="/"){return e+"/"}return e}function drop_double_slashes(e){return e.replace(/\/\//g,"/")}function get_process_runtime(e){let t="node";if(e["node-webkit"]){t="node-webkit"}else if(e.electron){t="electron"}return t}e.exports.get_process_runtime=get_process_runtime;const h="{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz";const v="";e.exports.evaluate=function(e,t,r){t=t||{};validate_config(e,t);const d=e.version;const f=o.parse(d);const p=t.runtime||get_process_runtime(process.versions);const _={name:e.name,configuration:t.debug?"Debug":"Release",debug:t.debug,module_name:e.binary.module_name,version:f.version,prerelease:f.prerelease.length?f.prerelease.join("."):"",build:f.build.length?f.build.join("."):"",major:f.major,minor:f.minor,patch:f.patch,runtime:p,node_abi:get_runtime_abi(p,t.target),node_abi_napi:c.get_napi_version(t.target)?"napi":get_runtime_abi(p,t.target),napi_version:c.get_napi_version(t.target),napi_build_version:r||"",node_napi_label:r?"napi-v"+r:get_runtime_abi(p,t.target),target:t.target||"",platform:t.target_platform||process.platform,target_platform:t.target_platform||process.platform,arch:t.target_arch||process.arch,target_arch:t.target_arch||process.arch,libc:t.target_libc||u.family||"unknown",module_main:e.main,toolset:t.toolset||"",bucket:e.binary.bucket,region:e.binary.region,s3ForcePathStyle:e.binary.s3ForcePathStyle||false};const g=_.module_name.replace("-","_");const y=process.env["npm_config_"+g+"_binary_host_mirror"]||e.binary.host;_.host=fix_slashes(eval_template(y,_));_.module_path=eval_template(e.binary.module_path,_);if(t.module_root){_.module_path=a.join(t.module_root,_.module_path)}else{_.module_path=a.resolve(_.module_path)}_.module=a.join(_.module_path,_.module_name+".node");_.remote_path=e.binary.remote_path?drop_double_slashes(fix_slashes(eval_template(e.binary.remote_path,_))):v;const m=e.binary.package_name?e.binary.package_name:h;_.package_name=eval_template(m,_);_.staged_tarball=a.join("build/stage",_.remote_path,_.package_name);_.hosted_path=s.resolve(_.host,_.remote_path);_.hosted_tarball=s.resolve(_.hosted_path,_.package_name);return _}},1400:(e,t,r)=>{var a=process.env.DEBUG_NOPT||process.env.NOPT_DEBUG?function(){console.error.apply(console,arguments)}:function(){};var o=r(7310),s=r(1017),u=r(2781).Stream,c=r(5920),d=r(2037);e.exports=t=nopt;t.clean=clean;t.typeDefs={String:{type:String,validate:validateString},Boolean:{type:Boolean,validate:validateBoolean},url:{type:o,validate:validateUrl},Number:{type:Number,validate:validateNumber},path:{type:s,validate:validatePath},Stream:{type:u,validate:validateStream},Date:{type:Date,validate:validateDate}};function nopt(e,r,o,s){o=o||process.argv;e=e||{};r=r||{};if(typeof s!=="number")s=2;a(e,r,o,s);o=o.slice(s);var u={},c,d={remain:[],cooked:o,original:o.slice(0)};parse(o,u,d.remain,e,r);clean(u,e,t.typeDefs);u.argv=d;Object.defineProperty(u.argv,"toString",{value:function(){return this.original.map(JSON.stringify).join(" ")},enumerable:false});return u}function clean(e,r,o){o=o||t.typeDefs;var s={},u=[false,true,null,String,Array];Object.keys(e).forEach((function(c){if(c==="argv")return;var d=e[c],f=Array.isArray(d),p=r[c];if(!f)d=[d];if(!p)p=u;if(p===Array)p=u.concat(Array);if(!Array.isArray(p))p=[p];a("val=%j",d);a("types=",p);d=d.map((function(u){if(typeof u==="string"){a("string %j",u);u=u.trim();if(u==="null"&&~p.indexOf(null)||u==="true"&&(~p.indexOf(true)||~p.indexOf(Boolean))||u==="false"&&(~p.indexOf(false)||~p.indexOf(Boolean))){u=JSON.parse(u);a("jsonable %j",u)}else if(~p.indexOf(Number)&&!isNaN(u)){a("convert to number",u);u=+u}else if(~p.indexOf(Date)&&!isNaN(Date.parse(u))){a("convert to date",u);u=new Date(u)}}if(!r.hasOwnProperty(c)){return u}if(u===false&&~p.indexOf(null)&&!(~p.indexOf(false)||~p.indexOf(Boolean))){u=null}var d={};d[c]=u;a("prevalidated val",d,u,r[c]);if(!validate(d,c,u,r[c],o)){if(t.invalidHandler){t.invalidHandler(c,u,r[c],e)}else if(t.invalidHandler!==false){a("invalid: "+c+"="+u,r[c])}return s}a("validated val",d,u,r[c]);return d[c]})).filter((function(e){return e!==s}));if(!d.length&&p.indexOf(Array)===-1){a("VAL HAS NO LENGTH, DELETE IT",d,c,p.indexOf(Array));delete e[c]}else if(f){a(f,e[c],d);e[c]=d}else e[c]=d[0];a("k=%s val=%j",c,d,e[c])}))}function validateString(e,t,r){e[t]=String(r)}function validatePath(e,t,r){if(r===true)return false;if(r===null)return true;r=String(r);var a=process.platform==="win32",o=a?/^~(\/|\\)/:/^~\//,u=d.homedir();if(u&&r.match(o)){e[t]=s.resolve(u,r.substr(2))}else{e[t]=s.resolve(r)}return true}function validateNumber(e,t,r){a("validate Number %j %j %j",t,r,isNaN(r));if(isNaN(r))return false;e[t]=+r}function validateDate(e,t,r){var o=Date.parse(r);a("validate Date %j %j %j",t,r,o);if(isNaN(o))return false;e[t]=new Date(r)}function validateBoolean(e,t,r){if(r instanceof Boolean)r=r.valueOf();else if(typeof r==="string"){if(!isNaN(r))r=!!+r;else if(r==="null"||r==="false")r=false;else r=true}else r=!!r;e[t]=r}function validateUrl(e,t,r){r=o.parse(String(r));if(!r.host)return false;e[t]=r.href}function validateStream(e,t,r){if(!(r instanceof u))return false;e[t]=r}function validate(e,t,r,o,s){if(Array.isArray(o)){for(var u=0,c=o.length;u1){var _=h.indexOf("=");if(_>-1){v=true;var g=h.substr(_+1);h=h.substr(0,_);e.splice(p,1,h,g)}var y=resolveShort(h,s,f,d);a("arg=%j shRes=%j",h,y);if(y){a(h,y);e.splice.apply(e,[p,1].concat(y));if(h!==y[0]){p--;continue}}h=h.replace(/^-+/,"");var m=null;while(h.toLowerCase().indexOf("no-")===0){m=!m;h=h.substr(3)}if(d[h])h=d[h];var w=o[h];var x=Array.isArray(w);if(x&&w.length===1){x=false;w=w[0]}var E=w===Array||x&&w.indexOf(Array)!==-1;if(!o.hasOwnProperty(h)&&t.hasOwnProperty(h)){if(!Array.isArray(t[h]))t[h]=[t[h]];E=true}var S,k=e[p+1];var R=typeof m==="boolean"||w===Boolean||x&&w.indexOf(Boolean)!==-1||typeof w==="undefined"&&!v||k==="false"&&(w===null||x&&~w.indexOf(null));if(R){S=!m;if(k==="true"||k==="false"){S=JSON.parse(k);k=null;if(m)S=!S;p++}if(x&&k){if(~w.indexOf(k)){S=k;p++}else if(k==="null"&&~w.indexOf(null)){S=null;p++}else if(!k.match(/^-{2,}[^-]/)&&!isNaN(k)&&~w.indexOf(Number)){S=+k;p++}else if(!k.match(/^-[^-]/)&&~w.indexOf(String)){S=k;p++}}if(E)(t[h]=t[h]||[]).push(S);else t[h]=S;continue}if(w===String){if(k===undefined){k=""}else if(k.match(/^-{1,2}[^-]+/)){k="";p--}}if(k&&k.match(/^-{2,}$/)){k=undefined;p--}S=k===undefined?true:k;if(E)(t[h]=t[h]||[]).push(S);else t[h]=S;p++;continue}r.push(h)}}function resolveShort(e,t,r,o){e=e.replace(/^-+/,"");if(o[e]===e)return null;if(t[e]){if(t[e]&&!Array.isArray(t[e]))t[e]=t[e].split(/\s+/);return t[e]}var s=t.___singles;if(!s){s=Object.keys(t).filter((function(e){return e.length===1})).reduce((function(e,t){e[t]=true;return e}),{});t.___singles=s;a("shorthand singles",s)}var u=e.split("").filter((function(e){return s[e]}));if(u.join("")===e)return u.map((function(e){return t[e]})).reduce((function(e,t){return e.concat(t)}),[]);if(o[e]&&!t[e])return null;if(r[e])e=r[e];if(t[e]&&!Array.isArray(t[e]))t[e]=t[e].split(/\s+/);return t[e]}},6286:(e,t,r)=>{const a=r(9491);const o=r(1017);const s=r(7147);let u=undefined;try{u=r(3535)}catch(e){}const c={nosort:true,silent:true};let d=0;const f=process.platform==="win32";const defaults=e=>{const t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach((t=>{e[t]=e[t]||s[t];t=t+"Sync";e[t]=e[t]||s[t]}));e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&u===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||c};const rimraf=(e,t,r)=>{if(typeof t==="function"){r=t;t={}}a(e,"rimraf: missing path");a.equal(typeof e,"string","rimraf: path should be a string");a.equal(typeof r,"function","rimraf: callback function required");a(t,"rimraf: invalid options argument provided");a.equal(typeof t,"object","rimraf: options should be object");defaults(t);let o=0;let s=null;let c=0;const next=e=>{s=s||e;if(--c===0)r(s)};const afterGlob=(e,a)=>{if(e)return r(e);c=a.length;if(c===0)return r();a.forEach((e=>{const CB=r=>{if(r){if((r.code==="EBUSY"||r.code==="ENOTEMPTY"||r.code==="EPERM")&&orimraf_(e,t,CB)),o*100)}if(r.code==="EMFILE"&&drimraf_(e,t,CB)),d++)}if(r.code==="ENOENT")r=null}d=0;next(r)};rimraf_(e,t,CB)}))};if(t.disableGlob||!u.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,((r,a)=>{if(!r)return afterGlob(null,[e]);u(e,t.glob,afterGlob)}))};const rimraf_=(e,t,r)=>{a(e);a(t);a(typeof r==="function");t.lstat(e,((a,o)=>{if(a&&a.code==="ENOENT")return r(null);if(a&&a.code==="EPERM"&&f)fixWinEPERM(e,t,a,r);if(o&&o.isDirectory())return rmdir(e,t,a,r);t.unlink(e,(a=>{if(a){if(a.code==="ENOENT")return r(null);if(a.code==="EPERM")return f?fixWinEPERM(e,t,a,r):rmdir(e,t,a,r);if(a.code==="EISDIR")return rmdir(e,t,a,r)}return r(a)}))}))};const fixWinEPERM=(e,t,r,o)=>{a(e);a(t);a(typeof o==="function");t.chmod(e,438,(a=>{if(a)o(a.code==="ENOENT"?null:r);else t.stat(e,((a,s)=>{if(a)o(a.code==="ENOENT"?null:r);else if(s.isDirectory())rmdir(e,t,r,o);else t.unlink(e,o)}))}))};const fixWinEPERMSync=(e,t,r)=>{a(e);a(t);try{t.chmodSync(e,438)}catch(e){if(e.code==="ENOENT")return;else throw r}let o;try{o=t.statSync(e)}catch(e){if(e.code==="ENOENT")return;else throw r}if(o.isDirectory())rmdirSync(e,t,r);else t.unlinkSync(e)};const rmdir=(e,t,r,o)=>{a(e);a(t);a(typeof o==="function");t.rmdir(e,(a=>{if(a&&(a.code==="ENOTEMPTY"||a.code==="EEXIST"||a.code==="EPERM"))rmkids(e,t,o);else if(a&&a.code==="ENOTDIR")o(r);else o(a)}))};const rmkids=(e,t,r)=>{a(e);a(t);a(typeof r==="function");t.readdir(e,((a,s)=>{if(a)return r(a);let u=s.length;if(u===0)return t.rmdir(e,r);let c;s.forEach((a=>{rimraf(o.join(e,a),t,(a=>{if(c)return;if(a)return r(c=a);if(--u===0)t.rmdir(e,r)}))}))}))};const rimrafSync=(e,t)=>{t=t||{};defaults(t);a(e,"rimraf: missing path");a.equal(typeof e,"string","rimraf: path should be a string");a(t,"rimraf: missing options");a.equal(typeof t,"object","rimraf: options should be object");let r;if(t.disableGlob||!u.hasMagic(e)){r=[e]}else{try{t.lstatSync(e);r=[e]}catch(a){r=u.sync(e,t.glob)}}if(!r.length)return;for(let e=0;e{a(e);a(t);try{t.rmdirSync(e)}catch(a){if(a.code==="ENOENT")return;if(a.code==="ENOTDIR")throw r;if(a.code==="ENOTEMPTY"||a.code==="EEXIST"||a.code==="EPERM")rmkidsSync(e,t)}};const rmkidsSync=(e,t)=>{a(e);a(t);t.readdirSync(e).forEach((r=>rimrafSync(o.join(e,r),t)));const r=f?100:1;let s=0;do{let a=true;try{const o=t.rmdirSync(e,t);a=false;return o}finally{if(++sq,env:{NODE_ENV:u.UNKNOWN,[u.UNKNOWN]:true},[u.UNKNOWN]:true};const T=Symbol();const C=Symbol();const j=Symbol();const N=Symbol();const L=Symbol();const I=Symbol();const P=Symbol();const D=Symbol();const M={access:I,accessSync:I,createReadStream:I,exists:I,existsSync:I,fstat:I,fstatSync:I,lstat:I,lstatSync:I,open:I,readFile:I,readFileSync:I,stat:I,statSync:I};const W=Object.assign(Object.create(null),{bindings:{default:P},express:{default:function(){return{[u.UNKNOWN]:true,set:T,engine:C}}},fs:Object.assign({default:M},M),process:Object.assign({default:O},O),path:{default:{}},os:Object.assign({default:k.default},k.default),"@mapbox/node-pre-gyp":Object.assign({default:w.default},w.default),"node-pre-gyp":v.pregyp,"node-pre-gyp/lib/pre-binding":v.pregyp,"node-pre-gyp/lib/pre-binding.js":v.pregyp,"node-gyp-build":{default:D},nbind:{init:j,default:{init:j}},"resolve-from":{default:A.default},"strong-globalize":{default:{SetRootDir:N},SetRootDir:N},pkginfo:{default:L}});const F={_interopRequireDefault:_.normalizeDefaultRequire,_interopRequireWildcard:_.normalizeWildcardRequire,__importDefault:_.normalizeDefaultRequire,__importStar:_.normalizeWildcardRequire,MONGOOSE_DRIVER_PATH:undefined,URL:x.URL,Object:{assign:Object.assign}};F.global=F.GLOBAL=F.globalThis=F;const B=Symbol();v.pregyp.find[B]=true;const $=W.path;Object.keys(o.default).forEach((e=>{const t=o.default[e];if(typeof t==="function"){const r=function mockPath(){return t.apply(mockPath,arguments)};r[B]=true;$[e]=$.default[e]=r}else{$[e]=$.default[e]=t}}));$.resolve=$.default.resolve=function(...e){return o.default.resolve.apply(this,[q,...e])};$.resolve[B]=true;const U=new Set([".h",".cmake",".c",".cpp"]);const H=new Set(["CHANGELOG.md","README.md","readme.md","changelog.md"]);let q;const G=/^\/[^\/]+|^[a-z]:[\\/][^\\/]+/i;function isAbsolutePathOrUrl(e){if(e instanceof x.URL)return e.protocol==="file:";if(typeof e==="string"){if(e.startsWith("file:")){try{new x.URL(e);return true}catch(e){return false}}return G.test(e)}return false}const K=Symbol();const z=/([\/\\]\*\*[\/\\]\*)+/g;async function analyze(e,t,r){const a=new Set;const c=new Set;const _=new Set;const w=o.default.dirname(e);q=r.cwd;const k=h.getPackageBase(e);const emitAssetDirectory=e=>{if(!r.analysis.emitGlobs)return;const t=e.indexOf(u.WILDCARD);const s=t===-1?e.length:e.lastIndexOf(o.default.sep,t);const c=e.substr(0,s);const d=e.substr(s);const f=d.replace(u.wildcardRegEx,((e,t)=>d[t-1]===o.default.sep?"**/*":"*")).replace(z,"/**/*")||"/**/*";if(r.ignoreFn(o.default.relative(r.base,c+f)))return;A=A.then((async()=>{if(r.log)console.log("Globbing "+c+f);const e=await new Promise(((e,t)=>p.default(c+f,{mark:true,ignore:c+"/**/node_modules/**/*"},((r,a)=>r?t(r):e(a)))));e.filter((e=>!U.has(o.default.extname(e))&&!H.has(o.default.basename(e))&&!e.endsWith("/"))).forEach((e=>a.add(e)))}))};let A=Promise.resolve();t=t.replace(/^#![^\n\r]*[\r\n]/,"");let M;let $=false;try{M=S.parse(t,{ecmaVersion:"latest",allowReturnOutsideFunction:true});$=false}catch(t){const a=t&&t.message&&t.message.includes("sourceType: module");if(!a){r.warnings.add(new Error(`Failed to parse ${e} as script:\n${t&&t.message}`))}}if(!M){try{M=S.parse(t,{ecmaVersion:"latest",sourceType:"module",allowAwaitOutsideFunction:true});$=true}catch(t){r.warnings.add(new Error(`Failed to parse ${e} as module:\n${t&&t.message}`));return{assets:a,deps:c,imports:_,isESM:false}}}const V=x.pathToFileURL(e).href;const Y=Object.assign(Object.create(null),{__dirname:{shadowDepth:0,value:{value:o.default.resolve(e,"..")}},__filename:{shadowDepth:0,value:{value:e}},process:{shadowDepth:0,value:{value:O}}});if(!$||r.mixedModules){Y.require={shadowDepth:0,value:{value:{[u.FUNCTION](e){c.add(e);const t=W[e];return t.default},resolve(t){return y.default(t,e,r)}}}};Y.require.value.value.resolve[B]=true}function setKnownBinding(e,t){if(e==="require")return;Y[e]={shadowDepth:0,value:t}}function getKnownBinding(e){const t=Y[e];if(t){if(t.shadowDepth===0){return t.value}}return undefined}function hasKnownBindingValue(e){const t=Y[e];return t&&t.shadowDepth===0}if(($||r.mixedModules)&&isAst(M)){for(const e of M.body){if(e.type==="ImportDeclaration"){const t=String(e.source.value);c.add(t);const r=W[t];if(r){for(const t of e.specifiers){if(t.type==="ImportNamespaceSpecifier")setKnownBinding(t.local.name,{value:r});else if(t.type==="ImportDefaultSpecifier"&&"default"in r)setKnownBinding(t.local.name,{value:r.default});else if(t.type==="ImportSpecifier"&&t.imported.name in r)setKnownBinding(t.local.name,{value:r[t.imported.name]})}}}else if(e.type==="ExportNamedDeclaration"||e.type==="ExportAllDeclaration"){if(e.source)c.add(String(e.source.value))}}}async function computePureStaticValue(e,t=true){const r=Object.create(null);Object.keys(F).forEach((e=>{r[e]={value:F[e]}}));Object.keys(Y).forEach((e=>{r[e]=getKnownBinding(e)}));r["import.meta"]={url:V};const a=await u.evaluate(e,r,t);return a}let Q;let X;let Z=false;function emitWildcardRequire(e){if(!r.analysis.emitGlobs||!e.startsWith("./")&&!e.startsWith("../"))return;e=o.default.resolve(w,e);const t=e.indexOf(u.WILDCARD);const s=t===-1?e.length:e.lastIndexOf(o.default.sep,t);const c=e.substr(0,s);const d=e.substr(s);let f=d.replace(u.wildcardRegEx,((e,t)=>d[t-1]===o.default.sep?"**/*":"*"))||"/**/*";if(!f.endsWith("*"))f+="?("+(r.ts?".ts|.tsx|":"")+".js|.json|.node)";if(r.ignoreFn(o.default.relative(r.base,c+f)))return;A=A.then((async()=>{if(r.log)console.log("Globbing "+c+f);const e=await new Promise(((e,t)=>p.default(c+f,{mark:true,ignore:c+"/**/node_modules/**/*"},((r,a)=>r?t(r):e(a)))));e.filter((e=>!U.has(o.default.extname(e))&&!H.has(o.default.basename(e))&&!e.endsWith("/"))).forEach((e=>a.add(e)))}))}async function processRequireArg(e,t=false){if(e.type==="ConditionalExpression"){await processRequireArg(e.consequent,t);await processRequireArg(e.alternate,t);return}if(e.type==="LogicalExpression"){await processRequireArg(e.left,t);await processRequireArg(e.right,t);return}let r=await computePureStaticValue(e,true);if(!r)return;if("value"in r&&typeof r.value==="string"){if(!r.wildcards)(t?_:c).add(r.value);else if(r.wildcards.length>=1)emitWildcardRequire(r.value)}else{if("then"in r&&typeof r.then==="string")(t?_:c).add(r.then);if("else"in r&&typeof r.else==="string")(t?_:c).add(r.else)}}let J=s.attachScopes(M,"scope");if(isAst(M)){R.handleWrappers(M);await g.default({id:e,ast:M,emitAsset:e=>a.add(e),emitAssetDirectory:emitAssetDirectory,job:r})}async function backtrack(e,t){if(!Q)throw new Error("Internal error: No staticChildNode for backtrack.");const r=await computePureStaticValue(e,true);if(r){if("value"in r&&typeof r.value!=="symbol"||"then"in r&&typeof r.then!=="symbol"&&typeof r.else!=="symbol"){X=r;Q=e;if(t)t.skip();return}}await emitStaticChildAsset()}await E(M,{async enter(t,s){var u;const p=t;const h=s;if(p.scope){J=p.scope;for(const e in p.scope.declarations){if(e in Y)Y[e].shadowDepth++}}if(Q)return;if(!h)return;if(p.type==="Identifier"){if(f.isIdentifierRead(p,h)&&r.analysis.computeFileReferences){let e;if(typeof(e=(u=getKnownBinding(p.name))===null||u===void 0?void 0:u.value)==="string"&&e.match(G)||e&&(typeof e==="function"||typeof e==="object")&&e[B]){X={value:typeof e==="string"?e:undefined};Q=p;await backtrack(h,this)}}}else if(r.analysis.computeFileReferences&&p.type==="MemberExpression"&&p.object.type==="MetaProperty"&&p.object.meta.name==="import"&&p.object.property.name==="meta"&&(p.property.computed?p.property.value:p.property.name)==="url"){X={value:V};Q=p;await backtrack(h,this)}else if(p.type==="ImportExpression"){await processRequireArg(p.source,true);return}else if(p.type==="CallExpression"){if((!$||r.mixedModules)&&p.callee.type==="Identifier"&&p.arguments.length){if(p.callee.name==="require"&&Y.require.shadowDepth===0){await processRequireArg(p.arguments[0]);return}}else if((!$||r.mixedModules)&&p.callee.type==="MemberExpression"&&p.callee.object.type==="Identifier"&&p.callee.object.name==="module"&&"module"in Y===false&&p.callee.property.type==="Identifier"&&!p.callee.computed&&p.callee.property.name==="require"&&p.arguments.length){await processRequireArg(p.arguments[0]);return}const t=r.analysis.evaluatePureExpressions&&await computePureStaticValue(p.callee,false);if(t&&"value"in t&&typeof t.value==="function"&&t.value[B]&&r.analysis.computeFileReferences){X=await computePureStaticValue(p,true);if(X&&h){Q=p;await backtrack(h,this)}}else if(t&&"value"in t&&typeof t.value==="symbol"){switch(t.value){case K:if(p.arguments.length===1&&p.arguments[0].type==="Literal"&&p.callee.type==="Identifier"&&Y.require.shadowDepth===0){await processRequireArg(p.arguments[0])}break;case P:if(p.arguments.length){const e=await computePureStaticValue(p.arguments[0],false);if(e&&"value"in e&&e.value){let t;if(typeof e.value==="object")t=e.value;else if(typeof e.value==="string")t={bindings:e.value};if(!t.path){t.path=true}t.module_root=k;let r;try{r=d.default(t)}catch(e){}if(r){X={value:r};Q=p;await emitStaticChildAsset()}}}break;case D:if(p.arguments.length===1&&p.arguments[0].type==="Identifier"&&p.arguments[0].name==="__dirname"&&Y.__dirname.shadowDepth===0){let e;try{e=m.default.path(w)}catch(e){}if(e){X={value:e};Q=p;await emitStaticChildAsset()}}break;case j:if(p.arguments.length){const e=await computePureStaticValue(p.arguments[0],false);if(e&&"value"in e&&(typeof e.value==="string"||typeof e.value==="undefined")){const t=v.nbind(e.value);if(t&&t.path){c.add(o.default.relative(w,t.path).replace(/\\/g,"/"));return this.skip()}}}break;case T:if(p.arguments.length===2&&p.arguments[0].type==="Literal"&&p.arguments[0].value==="view engine"&&!Z){await processRequireArg(p.arguments[1]);return this.skip()}break;case C:Z=true;break;case I:if(p.arguments[0]&&r.analysis.computeFileReferences){X=await computePureStaticValue(p.arguments[0],true);if(X){Q=p.arguments[0];await backtrack(h,this);return this.skip()}}break;case N:if(p.arguments[0]){const e=await computePureStaticValue(p.arguments[0],false);if(e&&"value"in e&&e.value)emitAssetDirectory(e.value+"/intl");return this.skip()}break;case L:let t=o.default.resolve(e,"../package.json");const s=o.default.resolve("/package.json");while(t!==s&&await r.stat(t)===null)t=o.default.resolve(t,"../../package.json");if(t!==s)a.add(t);break}}}else if(p.type==="VariableDeclaration"&&h&&!f.isVarLoop(h)&&r.analysis.evaluatePureExpressions){for(const e of p.declarations){if(!e.init)continue;const t=await computePureStaticValue(e.init,true);if(t){if(e.id.type==="Identifier"){setKnownBinding(e.id.name,t)}else if(e.id.type==="ObjectPattern"&&"value"in t){for(const r of e.id.properties){if(r.type!=="Property"||r.key.type!=="Identifier"||r.value.type!=="Identifier"||typeof t.value!=="object"||t.value===null||!(r.key.name in t.value))continue;setKnownBinding(r.value.name,{value:t.value[r.key.name]})}}if(!("value"in t)&&isAbsolutePathOrUrl(t.then)&&isAbsolutePathOrUrl(t.else)){X=t;Q=e.init;await emitStaticChildAsset()}}}}else if(p.type==="AssignmentExpression"&&h&&!f.isLoop(h)&&r.analysis.evaluatePureExpressions){if(!hasKnownBindingValue(p.left.name)){const e=await computePureStaticValue(p.right,false);if(e&&"value"in e){if(p.left.type==="Identifier"){setKnownBinding(p.left.name,e)}else if(p.left.type==="ObjectPattern"){for(const t of p.left.properties){if(t.type!=="Property"||t.key.type!=="Identifier"||t.value.type!=="Identifier"||typeof e.value!=="object"||e.value===null||!(t.key.name in e.value))continue;setKnownBinding(t.value.name,{value:e.value[t.key.name]})}}if(isAbsolutePathOrUrl(e.value)){X=e;Q=p.right;await emitStaticChildAsset()}}}}else if((!$||r.mixedModules)&&(p.type==="FunctionDeclaration"||p.type==="FunctionExpression"||p.type==="ArrowFunctionExpression")&&(p.arguments||p.params)[0]&&(p.arguments||p.params)[0].type==="Identifier"){let e;let t;if((p.type==="ArrowFunctionExpression"||p.type==="FunctionExpression")&&h&&h.type==="VariableDeclarator"&&h.id.type==="Identifier"){e=h.id;t=p.arguments||p.params}else if(p.id){e=p.id;t=p.arguments||p.params}if(e&&p.body.body){let r,a=false;for(let e=0;ee&&e.id&&e.id.type==="Identifier"&&e.init&&e.init.type==="CallExpression"&&e.init.callee.type==="Identifier"&&e.init.callee.name==="require"&&Y.require.shadowDepth===0&&e.init.arguments[0]&&e.init.arguments[0].type==="Identifier"&&e.init.arguments[0].name===t[0].name))}if(r&&p.body.body[e].type==="ReturnStatement"&&p.body.body[e].argument&&p.body.body[e].argument.type==="Identifier"&&p.body.body[e].argument.name===r.id.name){a=true;break}}if(a)setKnownBinding(e.name,{value:K})}}},async leave(e,t){const r=e;const a=t;if(r.scope){if(J.parent){J=J.parent}for(const e in r.scope.declarations){if(e in Y){if(Y[e].shadowDepth>0)Y[e].shadowDepth--;else delete Y[e]}}}if(Q&&a)await backtrack(a,this)}});await A;return{assets:a,deps:c,imports:_,isESM:$};async function emitAssetPath(e){const t=e.indexOf(u.WILDCARD);const s=t===-1?e.length:e.lastIndexOf(o.default.sep,t);const c=e.substr(0,s);try{var d=await r.stat(c);if(d===null){throw new Error("file not found")}}catch(e){return}if(t!==-1&&d.isFile())return;if(d.isFile()){a.add(e)}else if(d.isDirectory()){if(validWildcard(e))emitAssetDirectory(e)}}function validWildcard(t){let a="";if(t.endsWith(o.default.sep))a=o.default.sep;else if(t.endsWith(o.default.sep+u.WILDCARD))a=o.default.sep+u.WILDCARD;else if(t.endsWith(u.WILDCARD))a=u.WILDCARD;if(t===w+a)return false;if(t===q+a)return false;if(t.endsWith(o.default.sep+"node_modules"+a))return false;if(w.startsWith(t.substr(0,t.length-a.length)+o.default.sep))return false;if(k){const a=e.substr(0,e.indexOf(o.default.sep+"node_modules"))+o.default.sep+"node_modules"+o.default.sep;if(!t.startsWith(a)){if(r.log)console.log("Skipping asset emission of "+t.replace(u.wildcardRegEx,"*")+" for "+e+" as it is outside the package base "+k);return false}}return true}function resolveAbsolutePathOrUrl(e){return e instanceof x.URL?x.fileURLToPath(e):e.startsWith("file:")?x.fileURLToPath(new x.URL(e)):o.default.resolve(e)}async function emitStaticChildAsset(){if(!X){return}if("value"in X&&isAbsolutePathOrUrl(X.value)){try{const e=resolveAbsolutePathOrUrl(X.value);await emitAssetPath(e)}catch(e){}}else if("then"in X&&"else"in X&&isAbsolutePathOrUrl(X.then)&&isAbsolutePathOrUrl(X.else)){let e;try{e=resolveAbsolutePathOrUrl(X.then)}catch(e){}let t;try{t=resolveAbsolutePathOrUrl(X.else)}catch(e){}if(e)await emitAssetPath(e);if(t)await emitAssetPath(t)}else if(Q&&Q.type==="ArrayExpression"&&"value"in X&&X.value instanceof Array){for(const e of X.value){try{const t=resolveAbsolutePathOrUrl(e);await emitAssetPath(t)}catch(e){}}}Q=X=undefined}}t["default"]=analyze;function isAst(e){return"body"in e}},9582:function(e,t,r){"use strict";var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){if(a===undefined)a=r;Object.defineProperty(e,a,{enumerable:true,get:function(){return t[r]}})}:function(e,t,r,a){if(a===undefined)a=r;e[a]=t[r]});var o=this&&this.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!t.hasOwnProperty(r))a(t,e,r)};Object.defineProperty(t,"__esModule",{value:true});o(r(3864),t);var s=r(3471);Object.defineProperty(t,"nodeFileTrace",{enumerable:true,get:function(){return s.nodeFileTrace}})},3471:function(e,t,r){"use strict";var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.Job=t.nodeFileTrace=void 0;const o=r(1017);const s=a(r(552));const u=a(r(8827));const c=a(r(2278));const d=r(2540);const f=r(2985);const p=r(1017);const h=s.default.promises.readFile;const v=s.default.promises.readlink;const _=s.default.promises.stat;function inPath(e,t){const r=p.join(t,o.sep);return e.startsWith(r)&&e!==r}async function nodeFileTrace(e,t={}){const r=new Job(t);if(t.readFile)r.readFile=t.readFile;if(t.stat)r.stat=t.stat;if(t.readlink)r.readlink=t.readlink;if(t.resolve)r.resolve=t.resolve;r.ts=true;await Promise.all(e.map((async e=>{const t=o.resolve(e);await r.emitFile(t,"initial");if(t.endsWith(".js")||t.endsWith(".cjs")||t.endsWith(".mjs")||t.endsWith(".node")||r.ts&&(t.endsWith(".ts")||t.endsWith(".tsx"))){return r.emitDependency(t)}return undefined})));const a={fileList:r.fileList,esmFileList:r.esmFileList,reasons:r.reasons,warnings:r.warnings};return a}t.nodeFileTrace=nodeFileTrace;class Job{constructor({base:e=process.cwd(),processCwd:t,exports:r,conditions:a=r||["node"],exportsOnly:s=false,paths:u={},ignore:c,log:f=false,mixedModules:p=false,ts:h=true,analysis:v={},cache:_}){this.reasons=new Map;this.ts=h;e=o.resolve(e);this.ignoreFn=e=>{if(e.startsWith(".."+o.sep))return true;return false};if(typeof c==="string")c=[c];if(typeof c==="function"){const e=c;this.ignoreFn=t=>{if(t.startsWith(".."+o.sep))return true;if(e(t))return true;return false}}else if(Array.isArray(c)){const t=c.map((t=>o.relative(e,o.resolve(e||process.cwd(),t))));this.ignoreFn=e=>{if(e.startsWith(".."+o.sep))return true;if(d.isMatch(e,t))return true;return false}}this.base=e;this.cwd=o.resolve(t||e);this.conditions=a;this.exportsOnly=s;const g={};for(const t of Object.keys(u)){const r=u[t].endsWith("/");const a=o.resolve(e,u[t]);g[t]=a+(r?"/":"")}this.paths=g;this.log=f;this.mixedModules=p;this.analysis={};if(v!==false){Object.assign(this.analysis,{emitGlobs:true,computeFileReferences:true,evaluatePureExpressions:true},v===true?{}:v)}this.fileCache=_&&_.fileCache||new Map;this.statCache=_&&_.statCache||new Map;this.symlinkCache=_&&_.symlinkCache||new Map;this.analysisCache=_&&_.analysisCache||new Map;if(_){_.fileCache=this.fileCache;_.statCache=this.statCache;_.symlinkCache=this.symlinkCache;_.analysisCache=this.analysisCache}this.fileList=new Set;this.esmFileList=new Set;this.processed=new Set;this.warnings=new Set}async readlink(e){const t=this.symlinkCache.get(e);if(t!==undefined)return t;try{const t=await v(e);const r=this.statCache.get(e);if(r)this.statCache.set(o.resolve(e,t),r);this.symlinkCache.set(e,t);return t}catch(t){if(t.code!=="EINVAL"&&t.code!=="ENOENT"&&t.code!=="UNKNOWN")throw t;this.symlinkCache.set(e,null);return null}}async isFile(e){const t=await this.stat(e);if(t)return t.isFile();return false}async isDir(e){const t=await this.stat(e);if(t)return t.isDirectory();return false}async stat(e){const t=this.statCache.get(e);if(t)return t;try{const t=await _(e);this.statCache.set(e,t);return t}catch(t){if(t.code==="ENOENT"){this.statCache.set(e,null);return null}throw t}}async resolve(e,t,r,a){return c.default(e,t,r,a)}async readFile(e){const t=this.fileCache.get(e);if(t!==undefined)return t;try{const t=(await h(e)).toString();this.fileCache.set(e,t);return t}catch(t){if(t.code==="ENOENT"||t.code==="EISDIR"){this.fileCache.set(e,null);return null}throw t}}async realpath(e,t,r=new Set){if(r.has(e))throw new Error("Recursive symlink detected resolving "+e);r.add(e);const a=await this.readlink(e);if(a){const s=o.dirname(e);const u=o.resolve(s,a);const c=await this.realpath(s,t);if(inPath(e,c))await this.emitFile(e,"resolve",t,true);return this.realpath(u,t,r)}if(!inPath(e,this.base))return e;return p.join(await this.realpath(o.dirname(e),t,r),o.basename(e))}async emitFile(e,t,r,a=false){if(!a){e=await this.realpath(e,r)}e=o.relative(this.base,e);if(r){r=o.relative(this.base,r)}let s=this.reasons.get(e);if(!s){s={type:t,ignored:false,parents:new Set};this.reasons.set(e,s)}if(r&&this.ignoreFn(e,r)){if(!this.fileList.has(e)&&s){s.ignored=true}return false}if(r){s.parents.add(r)}this.fileList.add(e);return true}async getPjsonBoundary(e){const t=e.indexOf(o.sep);let r;while((r=e.lastIndexOf(o.sep))>t){e=e.substr(0,r);if(await this.isFile(e+o.sep+"package.json"))return e}return undefined}async emitDependency(e,t){if(this.processed.has(e)){if(t){await this.emitFile(e,"dependency",t)}return}this.processed.add(e);const r=await this.emitFile(e,"dependency",t);if(!r)return;if(e.endsWith(".json"))return;if(e.endsWith(".node"))return await f.sharedLibEmit(e,this);if(e.endsWith(".js")){const t=await this.getPjsonBoundary(e);if(t)await this.emitFile(t+o.sep+"package.json","resolve",e)}let a;const s=this.analysisCache.get(e);if(s){a=s}else{const t=await this.readFile(e);if(t===null)throw new Error("File "+e+" does not exist.");a=await u.default(e,t.toString(),this);this.analysisCache.set(e,a)}const{deps:c,imports:d,assets:p,isESM:h}=a;if(h)this.esmFileList.add(o.relative(this.base,e));await Promise.all([...[...p].map((async t=>{const r=o.extname(t);if(r===".js"||r===".mjs"||r===".node"||r===""||this.ts&&(r===".ts"||r===".tsx")&&t.startsWith(this.base)&&t.substr(this.base.length).indexOf(o.sep+"node_modules"+o.sep)===-1)await this.emitDependency(t,e);else await this.emitFile(t,"asset",e)})),...[...c].map((async t=>{try{var r=await this.resolve(t,e,this,!h)}catch(e){this.warnings.add(new Error(`Failed to resolve dependency ${t}:\n${e&&e.message}`));return}if(Array.isArray(r)){for(const t of r){if(t.startsWith("node:"))return;await this.emitDependency(t,e)}}else{if(r.startsWith("node:"))return;await this.emitDependency(r,e)}})),...[...d].map((async t=>{try{var r=await this.resolve(t,e,this,false)}catch(e){this.warnings.add(new Error(`Failed to resolve dependency ${t}:\n${e&&e.message}`));return}if(Array.isArray(r)){for(const t of r){if(t.startsWith("node:"))return;await this.emitDependency(t,e)}}else{if(r.startsWith("node:"))return;await this.emitDependency(r,e)}}))])}}t.Job=Job},2278:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});const a=r(1017);async function resolveDependency(e,t,r,o=true){let s;if(a.isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")){const o=e.endsWith("/");s=await resolvePath(a.resolve(t,"..",e)+(o?"/":""),t,r)}else if(e[0]==="#"){s=await packageImportsResolve(e,t,r,o)}else{s=await resolvePackage(e,t,r,o)}if(Array.isArray(s)){return Promise.all(s.map((e=>r.realpath(e,t))))}else if(s.startsWith("node:")){return s}else{return r.realpath(s,t)}}t["default"]=resolveDependency;async function resolvePath(e,t,r){const a=await resolveFile(e,t,r)||await resolveDir(e,t,r);if(!a){throw new NotFoundError(e,t)}return a}async function resolveFile(e,t,r){if(e.endsWith("/"))return undefined;e=await r.realpath(e,t);if(await r.isFile(e))return e;if(r.ts&&e.startsWith(r.base)&&e.substr(r.base.length).indexOf(a.sep+"node_modules"+a.sep)===-1&&await r.isFile(e+".ts"))return e+".ts";if(r.ts&&e.startsWith(r.base)&&e.substr(r.base.length).indexOf(a.sep+"node_modules"+a.sep)===-1&&await r.isFile(e+".tsx"))return e+".tsx";if(await r.isFile(e+".js"))return e+".js";if(await r.isFile(e+".json"))return e+".json";if(await r.isFile(e+".node"))return e+".node";return undefined}async function resolveDir(e,t,r){if(e.endsWith("/"))e=e.slice(0,-1);if(!await r.isDir(e))return;const o=await getPkgCfg(e,r);if(o&&typeof o.main==="string"){const s=await resolveFile(a.resolve(e,o.main),t,r)||await resolveFile(a.resolve(e,o.main,"index"),t,r);if(s){await r.emitFile(e+a.sep+"package.json","resolve",t);return s}}return resolveFile(a.resolve(e,"index"),t,r)}class NotFoundError extends Error{constructor(e,t){super("Cannot find module '"+e+"' loaded from "+t);this.code="MODULE_NOT_FOUND"}}const o=new Set([...r(8102)._builtinLibs,"constants","module","timers","console","_stream_writable","_stream_readable","_stream_duplex","process","sys"]);function getPkgName(e){const t=e.split("/");if(e[0]==="@"&&t.length>1)return t.length>1?t.slice(0,2).join("/"):null;return t.length?t[0]:null}async function getPkgCfg(e,t){const r=await t.readFile(e+a.sep+"package.json");if(r){try{return JSON.parse(r.toString())}catch(e){}}return undefined}function getExportsTarget(e,t,r){if(typeof e==="string"){return e}else if(e===null){return e}else if(Array.isArray(e)){for(const a of e){const e=getExportsTarget(a,t,r);if(e===null||typeof e==="string"&&e.startsWith("./"))return e}}else if(typeof e==="object"){for(const a of Object.keys(e)){if(a==="default"||a==="require"&&r||a==="import"&&!r||t.includes(a)){const o=getExportsTarget(e[a],t,r);if(o!==undefined)return o}}}return undefined}function resolveExportsImports(e,t,r,a,o,s){let u;if(o){if(!(typeof t==="object"&&!Array.isArray(t)&&t!==null))return undefined;u=t}else if(typeof t==="string"||Array.isArray(t)||t===null||typeof t==="object"&&Object.keys(t).length&&Object.keys(t)[0][0]!=="."){u={".":t}}else{u=t}if(r in u){const t=getExportsTarget(u[r],a.conditions,s);if(typeof t==="string"&&t.startsWith("./"))return e+t.slice(1)}for(const t of Object.keys(u).sort(((e,t)=>t.length-e.length))){if(t.endsWith("*")&&r.startsWith(t.slice(0,-1))){const o=getExportsTarget(u[t],a.conditions,s);if(typeof o==="string"&&o.startsWith("./"))return e+o.slice(1).replace(/\*/g,r.slice(t.length-1))}if(!t.endsWith("/"))continue;if(r.startsWith(t)){const o=getExportsTarget(u[t],a.conditions,s);if(typeof o==="string"&&o.endsWith("/")&&o.startsWith("./"))return e+o.slice(1)+r.slice(t.length)}}return undefined}async function packageImportsResolve(e,t,r,o){if(e!=="#"&&!e.startsWith("#/")&&r.conditions){const s=await r.getPjsonBoundary(t);if(s){const u=await getPkgCfg(s,r);const{imports:c}=u||{};if(u&&c!==null&&c!==undefined){let u=resolveExportsImports(s,c,e,r,true,o);if(u){if(o)u=await resolveFile(u,t,r)||await resolveDir(u,t,r);else if(!await r.isFile(u))throw new NotFoundError(u,t);if(u){await r.emitFile(s+a.sep+"package.json","resolve",t);return u}}}}}throw new NotFoundError(e,t)}async function resolvePackage(e,t,r,s){let u=t;if(o.has(e))return"node:"+e;const c=getPkgName(e)||"";let d;if(r.conditions){const o=await r.getPjsonBoundary(t);if(o){const u=await getPkgCfg(o,r);const{exports:f}=u||{};if(u&&u.name&&u.name===c&&f!==null&&f!==undefined){d=resolveExportsImports(o,f,"."+e.slice(c.length),r,false,s);if(d){if(s)d=await resolveFile(d,t,r)||await resolveDir(d,t,r);else if(!await r.isFile(d))throw new NotFoundError(d,t)}if(d)await r.emitFile(o+a.sep+"package.json","resolve",t)}}}let f;const p=u.indexOf(a.sep);while((f=u.lastIndexOf(a.sep))>p){u=u.substr(0,f);const o=u+a.sep+"node_modules";const p=await r.stat(o);if(!p||!p.isDirectory())continue;const h=await getPkgCfg(o+a.sep+c,r);const{exports:v}=h||{};if(r.conditions&&v!==undefined&&v!==null&&!d){let u;if(!r.exportsOnly)u=await resolveFile(o+a.sep+e,t,r)||await resolveDir(o+a.sep+e,t,r);let d=resolveExportsImports(o+a.sep+c,v,"."+e.slice(c.length),r,false,s);if(d){if(s)d=await resolveFile(d,t,r)||await resolveDir(d,t,r);else if(!await r.isFile(d))throw new NotFoundError(d,t)}if(d){await r.emitFile(o+a.sep+c+a.sep+"package.json","resolve",t);if(u&&u!==d)return[d,u];return d}if(u)return u}else{const s=await resolveFile(o+a.sep+e,t,r)||await resolveDir(o+a.sep+e,t,r);if(s){if(d&&d!==s)return[s,d];return s}}}if(d)return d;if(Object.hasOwnProperty.call(r.paths,e)){return r.paths[e]}for(const a of Object.keys(r.paths)){if(a.endsWith("/")&&e.startsWith(a)){const o=r.paths[a]+e.slice(a.length);const s=await resolveFile(o,t,r)||await resolveDir(o,t,r);if(!s){throw new NotFoundError(e,t)}return s}}throw new NotFoundError(e,t)}},3864:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true})},5078:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.isLoop=t.isVarLoop=t.isIdentifierRead=void 0;function isIdentifierRead(e,t){switch(t.type){case"ObjectPattern":case"ArrayPattern":return false;case"AssignmentExpression":return t.right===e;case"MemberExpression":return t.computed||e===t.object;case"Property":return e===t.value;case"MethodDefinition":return false;case"VariableDeclarator":return t.id!==e;case"ExportSpecifier":return false;case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":return false;default:return true}}t.isIdentifierRead=isIdentifierRead;function isVarLoop(e){return e.type==="ForStatement"||e.type==="ForInStatement"||e.type==="ForOfStatement"}t.isVarLoop=isVarLoop;function isLoop(e){return e.type==="ForStatement"||e.type==="ForInStatement"||e.type==="ForOfStatement"||e.type==="WhileStatement"||e.type==="DoWhileStatement"}t.isLoop=isLoop},2774:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:true});exports.nbind=exports.pregyp=void 0;const path_1=__importDefault(__nccwpck_require__(1017));const graceful_fs_1=__importDefault(__nccwpck_require__(552));const versioning=__nccwpck_require__(5574);const napi=__nccwpck_require__(9248);const pregypFind=(e,t)=>{const r=JSON.parse(graceful_fs_1.default.readFileSync(e).toString());versioning.validate_config(r,t);var a;if(napi.get_napi_build_versions(r,t)){a=napi.get_best_napi_build_version(r,t)}t=t||{};if(!t.module_root)t.module_root=path_1.default.dirname(e);var o=versioning.evaluate(r,t,a);return o.module};exports.pregyp={default:{find:pregypFind},find:pregypFind};function makeModulePathList(e,t){return[[e,t],[e,"build",t],[e,"build","Debug",t],[e,"build","Release",t],[e,"out","Debug",t],[e,"Debug",t],[e,"out","Release",t],[e,"Release",t],[e,"build","default",t],[e,process.env["NODE_BINDINGS_COMPILED_DIR"]||"compiled",process.versions.node,process.platform,process.arch,t]]}function findCompiledModule(basePath,specList){var resolvedList=[];var ext=path_1.default.extname(basePath);for(var _i=0,specList_1=specList;_i{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.getPackageName=t.getPackageBase=void 0;const r=/^(@[^\\\/]+[\\\/])?[^\\\/]+/;function getPackageBase(e){const t=e.lastIndexOf("node_modules");if(t!==-1&&(e[t-1]==="/"||e[t-1]==="\\")&&(e[t+12]==="/"||e[t+12]==="\\")){const a=e.substr(t+13).match(r);if(a)return e.substr(0,t+13+a[0].length)}return undefined}t.getPackageBase=getPackageBase;function getPackageName(e){const t=e.lastIndexOf("node_modules");if(t!==-1&&(e[t-1]==="/"||e[t-1]==="\\")&&(e[t+12]==="/"||e[t+12]==="\\")){const a=e.substr(t+13).match(r);if(a&&a.length>0){return a[0].replace(/\\/g,"/")}}return undefined}t.getPackageName=getPackageName},216:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.normalizeWildcardRequire=t.normalizeDefaultRequire=void 0;function normalizeDefaultRequire(e){if(e&&e.__esModule)return e;return{default:e}}t.normalizeDefaultRequire=normalizeDefaultRequire;const r=Object.prototype.hasOwnProperty;function normalizeWildcardRequire(e){if(e&&e.__esModule)return e;const t={};for(const a in e){if(!r.call(e,a))continue;t[a]=e[a]}t["default"]=e;return t}t.normalizeWildcardRequire=normalizeWildcardRequire},2985:function(e,t,r){"use strict";var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.sharedLibEmit=void 0;const o=a(r(2037));const s=a(r(3535));const u=r(7468);let c="";switch(o.default.platform()){case"darwin":c="/**/*.@(dylib|so?(.*))";break;case"win32":c="/**/*.dll";break;default:c="/**/*.so?(.*)"}async function sharedLibEmit(e,t){const r=u.getPackageBase(e);if(!r)return;const a=await new Promise(((e,t)=>s.default(r+c,{ignore:r+"/**/node_modules/**/*"},((r,a)=>r?t(r):e(a)))));await Promise.all(a.map((r=>t.emitFile(r,"sharedlib",e))))}t.sharedLibEmit=sharedLibEmit},5735:function(e,t,r){"use strict";var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const o=r(1017);const s=a(r(2278));const u=r(7468);const c=r(552);const d={"@generated/photon"({id:e,emitAssetDirectory:t}){if(e.endsWith("@generated/photon/index.js")){t(o.resolve(o.dirname(e),"runtime/"))}},argon2({id:e,emitAssetDirectory:t}){if(e.endsWith("argon2/argon2.js")){t(o.resolve(o.dirname(e),"build","Release"));t(o.resolve(o.dirname(e),"prebuilds"));t(o.resolve(o.dirname(e),"lib","binding"))}},bull({id:e,emitAssetDirectory:t}){if(e.endsWith("bull/lib/commands/index.js")){t(o.resolve(o.dirname(e)))}},camaro({id:e,emitAsset:t}){if(e.endsWith("camaro/dist/camaro.js")){t(o.resolve(o.dirname(e),"camaro.wasm"))}},esbuild({id:e,emitAssetDirectory:t}){if(e.endsWith("esbuild/lib/main.js")){const r=o.resolve(e,"..","..","package.json");const a=JSON.parse(c.readFileSync(r,"utf8"));for(const r of Object.keys(a.optionalDependencies||{})){const a=o.resolve(e,"..","..","..",r);t(a)}}},"google-gax"({id:e,ast:t,emitAssetDirectory:r}){if(e.endsWith("google-gax/build/src/grpc.js")){for(const a of t.body){if(a.type==="VariableDeclaration"&&a.declarations[0].id.type==="Identifier"&&a.declarations[0].id.name==="googleProtoFilesDir"){r(o.resolve(o.dirname(e),"../../../google-proto-files"))}}}},oracledb({id:e,ast:t,emitAsset:r}){if(e.endsWith("oracledb/lib/oracledb.js")){for(const a of t.body){if(a.type==="ForStatement"&&"body"in a.body&&a.body.body&&Array.isArray(a.body.body)&&a.body.body[0]&&a.body.body[0].type==="TryStatement"&&a.body.body[0].block.body[0]&&a.body.body[0].block.body[0].type==="ExpressionStatement"&&a.body.body[0].block.body[0].expression.type==="AssignmentExpression"&&a.body.body[0].block.body[0].expression.operator==="="&&a.body.body[0].block.body[0].expression.left.type==="Identifier"&&a.body.body[0].block.body[0].expression.left.name==="oracledbCLib"&&a.body.body[0].block.body[0].expression.right.type==="CallExpression"&&a.body.body[0].block.body[0].expression.right.callee.type==="Identifier"&&a.body.body[0].block.body[0].expression.right.callee.name==="require"&&a.body.body[0].block.body[0].expression.right.arguments.length===1&&a.body.body[0].block.body[0].expression.right.arguments[0].type==="MemberExpression"&&a.body.body[0].block.body[0].expression.right.arguments[0].computed===true&&a.body.body[0].block.body[0].expression.right.arguments[0].object.type==="Identifier"&&a.body.body[0].block.body[0].expression.right.arguments[0].object.name==="binaryLocations"&&a.body.body[0].block.body[0].expression.right.arguments[0].property.type==="Identifier"&&a.body.body[0].block.body[0].expression.right.arguments[0].property.name==="i"){a.body.body[0].block.body[0].expression.right.arguments=[{type:"Literal",value:"_"}];const t=global._unit?"3.0.0":JSON.parse(c.readFileSync(e.slice(0,-15)+"package.json","utf8")).version;const s=Number(t.slice(0,t.indexOf(".")))>=4;const u="oracledb-"+(s?t:"abi"+process.versions.modules)+"-"+process.platform+"-"+process.arch+".node";r(o.resolve(e,"../../build/Release/"+u))}}}},"phantomjs-prebuilt"({id:e,emitAssetDirectory:t}){if(e.endsWith("phantomjs-prebuilt/lib/phantomjs.js")){t(o.resolve(o.dirname(e),"..","bin"))}},"remark-prism"({id:e,emitAssetDirectory:t}){const r="remark-prism/src/highlight.js";if(e.endsWith(r)){try{const a=e.slice(0,-r.length);t(o.resolve(a,"prismjs","components"))}catch(e){}}},semver({id:e,emitAsset:t}){if(e.endsWith("semver/index.js")){t(o.resolve(e.replace("index.js","preload.js")))}},"socket.io":async function({id:e,ast:t,job:r}){if(e.endsWith("socket.io/lib/index.js")){async function replaceResolvePathStatement(t){if(t.type==="ExpressionStatement"&&t.expression.type==="AssignmentExpression"&&t.expression.operator==="="&&t.expression.right.type==="CallExpression"&&t.expression.right.callee.type==="Identifier"&&t.expression.right.callee.name==="read"&&t.expression.right.arguments.length>=1&&t.expression.right.arguments[0].type==="CallExpression"&&t.expression.right.arguments[0].callee.type==="Identifier"&&t.expression.right.arguments[0].callee.name==="resolvePath"&&t.expression.right.arguments[0].arguments.length===1&&t.expression.right.arguments[0].arguments[0].type==="Literal"){const a=t.expression.right.arguments[0].arguments[0].value;let u;try{const t=await s.default(String(a),e,r);if(typeof t==="string"){u=t}else{return undefined}}catch(e){return undefined}const c="/"+o.relative(o.dirname(e),u);t.expression.right.arguments[0]={type:"BinaryExpression",start:t.expression.right.arguments[0].start,end:t.expression.right.arguments[0].end,operator:"+",left:{type:"Identifier",name:"__dirname"},right:{type:"Literal",value:c,raw:JSON.stringify(c)}}}return undefined}for(const e of t.body){if(e.type==="ExpressionStatement"&&e.expression.type==="AssignmentExpression"&&e.expression.operator==="="&&e.expression.left.type==="MemberExpression"&&e.expression.left.object.type==="MemberExpression"&&e.expression.left.object.object.type==="Identifier"&&e.expression.left.object.object.name==="Server"&&e.expression.left.object.property.type==="Identifier"&&e.expression.left.object.property.name==="prototype"&&e.expression.left.property.type==="Identifier"&&e.expression.left.property.name==="serveClient"&&e.expression.right.type==="FunctionExpression"){for(const t of e.expression.right.body.body){if(t.type==="IfStatement"&&t.consequent&&"body"in t.consequent&&t.consequent.body){const e=t.consequent.body;let r=false;if(Array.isArray(e)&&e[0]&&e[0].type==="ExpressionStatement"){r=await replaceResolvePathStatement(e[0])}if(Array.isArray(e)&&e[1]&&e[1].type==="TryStatement"&&e[1].block.body&&e[1].block.body[0]){r=await replaceResolvePathStatement(e[1].block.body[0])||r}return}}}}}},typescript({id:e,emitAssetDirectory:t}){if(e.endsWith("typescript/lib/tsc.js")){t(o.resolve(e,"../"))}},"uglify-es"({id:e,emitAsset:t}){if(e.endsWith("uglify-es/tools/node.js")){t(o.resolve(e,"../../lib/utils.js"));t(o.resolve(e,"../../lib/ast.js"));t(o.resolve(e,"../../lib/parse.js"));t(o.resolve(e,"../../lib/transform.js"));t(o.resolve(e,"../../lib/scope.js"));t(o.resolve(e,"../../lib/output.js"));t(o.resolve(e,"../../lib/compress.js"));t(o.resolve(e,"../../lib/sourcemap.js"));t(o.resolve(e,"../../lib/mozilla-ast.js"));t(o.resolve(e,"../../lib/propmangle.js"));t(o.resolve(e,"../../lib/minify.js"));t(o.resolve(e,"../exports.js"))}},"uglify-js"({id:e,emitAsset:t,emitAssetDirectory:r}){if(e.endsWith("uglify-js/tools/node.js")){r(o.resolve(e,"../../lib"));t(o.resolve(e,"../exports.js"))}},"playwright-core"({id:e,emitAsset:t}){if(e.endsWith("playwright-core/index.js")){t(o.resolve(o.dirname(e),"browsers.json"))}},"geo-tz"({id:e,emitAsset:t}){if(e.endsWith("geo-tz/dist/geo-tz.js")){t(o.resolve(o.dirname(e),"../data/geo.dat"))}}};async function handleSpecialCases({id:e,ast:t,emitAsset:r,emitAssetDirectory:a,job:o}){const s=u.getPackageName(e);const c=d[s||""];e=e.replace(/\\/g,"/");if(c)await c({id:e,ast:t,emitAsset:r,emitAssetDirectory:a,job:o})}t["default"]=handleSpecialCases},5401:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.wildcardRegEx=t.WILDCARD=t.FUNCTION=t.UNKNOWN=t.evaluate=void 0;const a=r(7310);async function evaluate(e,t={},r=true){const a={computeBranches:r,vars:t};return walk(e);function walk(e){const t=o[e.type];if(t){return t.call(a,e,walk)}return undefined}}t.evaluate=evaluate;t.UNKNOWN=Symbol();t.FUNCTION=Symbol();t.WILDCARD="";t.wildcardRegEx=/\x1a/g;function countWildcards(e){t.wildcardRegEx.lastIndex=0;let r=0;while(t.wildcardRegEx.exec(e))r++;return r}const o={ArrayExpression:async function ArrayExpression(e,t){const r=[];for(let a=0,o=e.elements.length;aa.value}}}return undefined},BinaryExpression:async function BinaryExpression(e,r){const a=e.operator;let o=await r(e.left);if(!o&&a!=="+")return;let s=await r(e.right);if(!o&&!s)return;if(!o){if(this.computeBranches&&s&&"value"in s&&typeof s.value==="string")return{value:t.WILDCARD+s.value,wildcards:[e.left,...s.wildcards||[]]};return}if(!s){if(this.computeBranches&&a==="+"){if(o&&"value"in o&&typeof o.value==="string")return{value:o.value+t.WILDCARD,wildcards:[...o.wildcards||[],e.right]}}if(!("test"in o)&&a==="||"&&o.value)return o;return}if("test"in o&&"value"in s){const e=s.value;if(a==="==")return{test:o.test,then:o.then==e,else:o.else==e};if(a==="===")return{test:o.test,then:o.then===e,else:o.else===e};if(a==="!=")return{test:o.test,then:o.then!=e,else:o.else!=e};if(a==="!==")return{test:o.test,then:o.then!==e,else:o.else!==e};if(a==="+")return{test:o.test,then:o.then+e,else:o.else+e};if(a==="-")return{test:o.test,then:o.then-e,else:o.else-e};if(a==="*")return{test:o.test,then:o.then*e,else:o.else*e};if(a==="/")return{test:o.test,then:o.then/e,else:o.else/e};if(a==="%")return{test:o.test,then:o.then%e,else:o.else%e};if(a==="<")return{test:o.test,then:o.then")return{test:o.test,then:o.then>e,else:o.else>e};if(a===">=")return{test:o.test,then:o.then>=e,else:o.else>=e};if(a==="|")return{test:o.test,then:o.then|e,else:o.else|e};if(a==="&")return{test:o.test,then:o.then&e,else:o.else&e};if(a==="^")return{test:o.test,then:o.then^e,else:o.else^e};if(a==="&&")return{test:o.test,then:o.then&&e,else:o.else&&e};if(a==="||")return{test:o.test,then:o.then||e,else:o.else||e}}else if("test"in s&&"value"in o){const e=o.value;if(a==="==")return{test:s.test,then:e==s.then,else:e==s.else};if(a==="===")return{test:s.test,then:e===s.then,else:e===s.else};if(a==="!=")return{test:s.test,then:e!=s.then,else:e!=s.else};if(a==="!==")return{test:s.test,then:e!==s.then,else:e!==s.else};if(a==="+")return{test:s.test,then:e+s.then,else:e+s.else};if(a==="-")return{test:s.test,then:e-s.then,else:e-s.else};if(a==="*")return{test:s.test,then:e*s.then,else:e*s.else};if(a==="/")return{test:s.test,then:e/s.then,else:e/s.else};if(a==="%")return{test:s.test,then:e%s.then,else:e%s.else};if(a==="<")return{test:s.test,then:e")return{test:s.test,then:e>s.then,else:e>s.else};if(a===">=")return{test:s.test,then:e>=s.then,else:e>=s.else};if(a==="|")return{test:s.test,then:e|s.then,else:e|s.else};if(a==="&")return{test:s.test,then:e&s.then,else:e&s.else};if(a==="^")return{test:s.test,then:e^s.then,else:e^s.else};if(a==="&&")return{test:s.test,then:e&&s.then,else:o&&s.else};if(a==="||")return{test:s.test,then:e||s.then,else:o||s.else}}else if("value"in o&&"value"in s){if(a==="==")return{value:o.value==s.value};if(a==="===")return{value:o.value===s.value};if(a==="!=")return{value:o.value!=s.value};if(a==="!==")return{value:o.value!==s.value};if(a==="+"){const e={value:o.value+s.value};let t=[];if("wildcards"in o&&o.wildcards){t=t.concat(o.wildcards)}if("wildcards"in s&&s.wildcards){t=t.concat(s.wildcards)}if(t.length>0){e.wildcards=t}return e}if(a==="-")return{value:o.value-s.value};if(a==="*")return{value:o.value*s.value};if(a==="/")return{value:o.value/s.value};if(a==="%")return{value:o.value%s.value};if(a==="<")return{value:o.value")return{value:o.value>s.value};if(a===">=")return{value:o.value>=s.value};if(a==="|")return{value:o.value|s.value};if(a==="&")return{value:o.value&s.value};if(a==="^")return{value:o.value^s.value};if(a==="&&")return{value:o.value&&s.value};if(a==="||")return{value:o.value||s.value}}return},CallExpression:async function CallExpression(e,r){var a;const o=await r(e.callee);if(!o||"test"in o)return;let s=o.value;if(typeof s==="object"&&s!==null)s=s[t.FUNCTION];if(typeof s!=="function")return;let u=null;if(e.callee.object){u=await r(e.callee.object);u=u&&"value"in u&&u.value?u.value:null}let c;let d=[];let f;let p=e.arguments.length>0&&((a=e.callee.property)===null||a===void 0?void 0:a.name)!=="concat";const h=[];for(let a=0,o=e.arguments.length;ah.push(e)))}else{if(!this.computeBranches)return;o={value:t.WILDCARD};h.push(e.arguments[a])}if("test"in o){if(h.length)return;if(c)return;c=o.test;f=d.concat([]);d.push(o.then);f.push(o.else)}else{d.push(o.value);if(f)f.push(o.value)}}if(p)return;try{const e=await s.apply(u,d);if(e===t.UNKNOWN)return;if(!c){if(h.length){if(typeof e!=="string"||countWildcards(e)!==h.length)return;return{value:e,wildcards:h}}return{value:e}}const r=await s.apply(u,f);if(e===t.UNKNOWN)return;return{test:c,then:e,else:r}}catch(e){return}},ConditionalExpression:async function ConditionalExpression(e,t){const r=await t(e.test);if(r&&"value"in r)return r.value?t(e.consequent):t(e.alternate);if(!this.computeBranches)return;const a=await t(e.consequent);if(!a||"wildcards"in a||"test"in a)return;const o=await t(e.alternate);if(!o||"wildcards"in o||"test"in o)return;return{test:e.test,then:a.value,else:o.value}},ExpressionStatement:async function ExpressionStatement(e,t){return t(e.expression)},Identifier:async function Identifier(e,t){if(Object.hasOwnProperty.call(this.vars,e.name))return this.vars[e.name];return undefined},Literal:async function Literal(e,t){return{value:e.value}},MemberExpression:async function MemberExpression(e,r){const a=await r(e.object);if(!a||"test"in a||typeof a.value==="function"){return undefined}if(e.property.type==="Identifier"){if(typeof a.value==="string"&&e.property.name==="concat"){return{value:{[t.FUNCTION]:(...e)=>a.value.concat(e)}}}if(typeof a.value==="object"&&a.value!==null){const o=a.value;if(e.computed){const s=await r(e.property);if(s&&"value"in s&&s.value){const e=o[s.value];if(e===t.UNKNOWN)return undefined;return{value:e}}if(!o[t.UNKNOWN]&&Object.keys(a).length===0){return{value:undefined}}}else if(e.property.name in o){const r=o[e.property.name];if(r===t.UNKNOWN)return undefined;return{value:r}}else if(o[t.UNKNOWN])return undefined}else{return{value:undefined}}}const o=await r(e.property);if(!o||"test"in o)return undefined;if(typeof a.value==="object"&&a.value!==null){if(o.value in a.value){const e=a.value[o.value];if(e===t.UNKNOWN)return undefined;return{value:e}}else if(a.value[t.UNKNOWN]){return undefined}}else{return{value:undefined}}return undefined},MetaProperty:async function MetaProperty(e){if(e.meta.name==="import"&&e.property.name==="meta")return{value:this.vars["import.meta"]};return undefined},NewExpression:async function NewExpression(e,t){const r=await t(e.callee);if(r&&"value"in r&&r.value===a.URL&&e.arguments.length){const r=await t(e.arguments[0]);if(!r)return undefined;let o=null;if(e.arguments[1]){o=await t(e.arguments[1]);if(!o||!("value"in o))return undefined}if("value"in r){if(o){try{return{value:new a.URL(r.value,o.value)}}catch(e){return undefined}}try{return{value:new a.URL(r.value)}}catch(e){return undefined}}else{const e=r.test;if(o){try{return{test:e,then:new a.URL(r.then,o.value),else:new a.URL(r.else,o.value)}}catch(e){return undefined}}try{return{test:e,then:new a.URL(r.then),else:new a.URL(r.else)}}catch(e){return undefined}}}return undefined},ObjectExpression:async function ObjectExpression(e,r){const a={};for(let o=0;o{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.handleWrappers=void 0;const a=r(7470);function isUndefinedOrVoid(e){return e.type==="Identifier"&&e.name==="undefined"||e.type==="UnaryExpression"&&e.operator==="void"&&e.argument.type==="Literal"&&e.argument.value===0}function handleWrappers(e){var t;let r;if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="UnaryExpression"&&e.body[0].expression.operator==="!"&&e.body[0].expression.argument.type==="CallExpression"&&e.body[0].expression.argument.callee.type==="FunctionExpression"&&e.body[0].expression.argument.arguments.length===1)r=e.body[0].expression.argument;else if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="CallExpression"&&e.body[0].expression.callee.type==="FunctionExpression"&&(e.body[0].expression.arguments.length===1||e.body[0].expression.arguments.length===0))r=e.body[0].expression;else if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="AssignmentExpression"&&e.body[0].expression.left.type==="MemberExpression"&&e.body[0].expression.left.object.type==="Identifier"&&e.body[0].expression.left.object.name==="module"&&e.body[0].expression.left.property.type==="Identifier"&&e.body[0].expression.left.property.name==="exports"&&e.body[0].expression.right.type==="CallExpression"&&e.body[0].expression.right.callee.type==="FunctionExpression"&&e.body[0].expression.right.arguments.length===1)r=e.body[0].expression.right;if(r){let e;let o;if(r.arguments[0]&&r.arguments[0].type==="ConditionalExpression"&&r.arguments[0].test.type==="LogicalExpression"&&r.arguments[0].test.operator==="&&"&&r.arguments[0].test.left.type==="BinaryExpression"&&r.arguments[0].test.left.operator==="==="&&r.arguments[0].test.left.left.type==="UnaryExpression"&&r.arguments[0].test.left.left.operator==="typeof"&&"name"in r.arguments[0].test.left.left.argument&&r.arguments[0].test.left.left.argument.name==="define"&&r.arguments[0].test.left.right.type==="Literal"&&r.arguments[0].test.left.right.value==="function"&&r.arguments[0].test.right.type==="MemberExpression"&&r.arguments[0].test.right.object.type==="Identifier"&&r.arguments[0].test.right.property.type==="Identifier"&&r.arguments[0].test.right.property.name==="amd"&&r.arguments[0].test.right.computed===false&&r.arguments[0].alternate.type==="FunctionExpression"&&r.arguments[0].alternate.params.length===1&&r.arguments[0].alternate.params[0].type==="Identifier"&&r.arguments[0].alternate.body.body.length===1&&r.arguments[0].alternate.body.body[0].type==="ExpressionStatement"&&r.arguments[0].alternate.body.body[0].expression.type==="AssignmentExpression"&&r.arguments[0].alternate.body.body[0].expression.left.type==="MemberExpression"&&r.arguments[0].alternate.body.body[0].expression.left.object.type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.left.object.name==="module"&&r.arguments[0].alternate.body.body[0].expression.left.property.type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.left.property.name==="exports"&&r.arguments[0].alternate.body.body[0].expression.left.computed===false&&r.arguments[0].alternate.body.body[0].expression.right.type==="CallExpression"&&r.arguments[0].alternate.body.body[0].expression.right.callee.type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.right.callee.name===r.arguments[0].alternate.params[0].name&&"body"in r.callee&&"body"in r.callee.body&&Array.isArray(r.callee.body.body)&&r.arguments[0].alternate.body.body[0].expression.right.arguments.length===1&&r.arguments[0].alternate.body.body[0].expression.right.arguments[0].type==="Identifier"&&r.arguments[0].alternate.body.body[0].expression.right.arguments[0].name==="require"){let e=r.callee.body.body;if(e[0].type==="ExpressionStatement"&&e[0].expression.type==="Literal"&&e[0].expression.value==="use strict"){e=e.slice(1)}if(e.length===1&&e[0].type==="ExpressionStatement"&&e[0].expression.type==="CallExpression"&&e[0].expression.callee.type==="Identifier"&&e[0].expression.callee.name===r.arguments[0].test.right.object.name&&e[0].expression.arguments.length===1&&e[0].expression.arguments[0].type==="FunctionExpression"&&e[0].expression.arguments[0].params.length===1&&e[0].expression.arguments[0].params[0].type==="Identifier"&&e[0].expression.arguments[0].params[0].name==="require"){const t=e[0].expression.arguments[0];t.params=[];try{delete t.scope.declarations.require}catch(e){}}}else if(r.arguments[0]&&r.arguments[0].type==="FunctionExpression"&&r.arguments[0].params.length===0&&(r.arguments[0].body.body.length===1||r.arguments[0].body.body.length===2&&r.arguments[0].body.body[0].type==="VariableDeclaration"&&r.arguments[0].body.body[0].declarations.length===3&&r.arguments[0].body.body[0].declarations.every((e=>e.init===null&&e.id.type==="Identifier")))&&r.arguments[0].body.body[r.arguments[0].body.body.length-1].type==="ReturnStatement"&&(e=r.arguments[0].body.body[r.arguments[0].body.body.length-1])&&((t=e.argument)===null||t===void 0?void 0:t.type)==="CallExpression"&&e.argument.arguments.length&&e.argument.arguments.every((e=>e&&e.type==="Literal"&&typeof e.value==="number"))&&e.argument.callee.type==="CallExpression"&&(e.argument.callee.callee.type==="FunctionExpression"||e.argument.callee.callee.type==="CallExpression"&&e.argument.callee.callee.callee.type==="FunctionExpression"&&e.argument.callee.callee.arguments.length===0)&&e.argument.callee.arguments.length===3&&e.argument.callee.arguments[0].type==="ObjectExpression"&&e.argument.callee.arguments[1].type==="ObjectExpression"&&e.argument.callee.arguments[2].type==="ArrayExpression"){const t=e.argument.callee.arguments[0].properties;const r={};if(t.every((e=>{if(e.type!=="Property"||e.computed!==false||e.key.type!=="Literal"||typeof e.key.value!=="number"||e.value.type!=="ArrayExpression"||e.value.elements.length!==2||!e.value.elements[0]||!e.value.elements[1]||e.value.elements[0].type!=="FunctionExpression"||e.value.elements[1].type!=="ObjectExpression"){return false}const t=e.value.elements[1].properties;for(const e of t){if(e.type!=="Property"||e.value.type!=="Identifier"&&e.value.type!=="Literal"&&!isUndefinedOrVoid(e.value)||!(e.key.type==="Literal"&&typeof e.key.value==="string"||e.key.type==="Identifier")||e.computed){return false}if(isUndefinedOrVoid(e.value)){if(e.key.type==="Identifier"){r[e.key.name]={type:"Literal",start:e.key.start,end:e.key.end,value:e.key.name,raw:JSON.stringify(e.key.name)}}else if(e.key.type==="Literal"){r[String(e.key.value)]=e.key}}}return true}))){const t=Object.keys(r);const a=e.argument.callee.arguments[1];a.properties=t.map((e=>({type:"Property",method:false,shorthand:false,computed:false,kind:"init",key:r[e],value:{type:"ObjectExpression",properties:[{type:"Property",kind:"init",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"exports"},value:{type:"CallExpression",optional:false,callee:{type:"Identifier",name:"require"},arguments:[r[e]]}}]}})))}}else if(r.arguments[0]&&r.arguments[0].type==="FunctionExpression"&&r.arguments[0].params.length===2&&r.arguments[0].params[0].type==="Identifier"&&r.arguments[0].params[1].type==="Identifier"&&"body"in r.callee&&"body"in r.callee.body&&Array.isArray(r.callee.body.body)&&r.callee.body.body.length===1){const e=r.callee.body.body[0];if(e.type==="IfStatement"&&e.test.type==="LogicalExpression"&&e.test.operator==="&&"&&e.test.left.type==="BinaryExpression"&&e.test.left.left.type==="UnaryExpression"&&e.test.left.left.operator==="typeof"&&e.test.left.left.argument.type==="Identifier"&&e.test.left.left.argument.name==="module"&&e.test.left.right.type==="Literal"&&e.test.left.right.value==="object"&&e.test.right.type==="BinaryExpression"&&e.test.right.left.type==="UnaryExpression"&&e.test.right.left.operator==="typeof"&&e.test.right.left.argument.type==="MemberExpression"&&e.test.right.left.argument.object.type==="Identifier"&&e.test.right.left.argument.object.name==="module"&&e.test.right.left.argument.property.type==="Identifier"&&e.test.right.left.argument.property.name==="exports"&&e.test.right.right.type==="Literal"&&e.test.right.right.value==="object"&&e.consequent.type==="BlockStatement"&&e.consequent.body.length>0){let t;if(e.consequent.body[0].type==="VariableDeclaration"&&e.consequent.body[0].declarations[0].init&&e.consequent.body[0].declarations[0].init.type==="CallExpression")t=e.consequent.body[0].declarations[0].init;else if(e.consequent.body[0].type==="ExpressionStatement"&&e.consequent.body[0].expression.type==="CallExpression")t=e.consequent.body[0].expression;else if(e.consequent.body[0].type==="ExpressionStatement"&&e.consequent.body[0].expression.type==="AssignmentExpression"&&e.consequent.body[0].expression.operator==="="&&e.consequent.body[0].expression.right.type==="CallExpression")t=e.consequent.body[0].expression.right;if(t&&t.callee.type==="Identifier"&&"params"in r.callee&&r.callee.params.length>0&&"name"in r.callee.params[0]&&t.callee.name===r.callee.params[0].name&&t.arguments.length===2&&t.arguments[0].type==="Identifier"&&t.arguments[0].name==="require"&&t.arguments[1].type==="Identifier"&&t.arguments[1].name==="exports"){const e=r.arguments[0];e.params=[];try{const t=e.scope;delete t.declarations.require;delete t.declarations.exports}catch(e){}}}}else if(r.callee.type==="FunctionExpression"&&r.callee.body.body.length>2&&r.callee.body.body[0].type==="VariableDeclaration"&&r.callee.body.body[0].declarations.length===1&&r.callee.body.body[0].declarations[0].type==="VariableDeclarator"&&r.callee.body.body[0].declarations[0].id.type==="Identifier"&&r.callee.body.body[0].declarations[0].init&&(r.callee.body.body[0].declarations[0].init.type==="ObjectExpression"&&r.callee.body.body[0].declarations[0].init.properties.length===0||r.callee.body.body[0].declarations[0].init.type==="CallExpression"&&r.callee.body.body[0].declarations[0].init.arguments.length===1)&&(r.callee.body.body[1]&&r.callee.body.body[1].type==="FunctionDeclaration"&&r.callee.body.body[1].params.length===1&&r.callee.body.body[1].body.body.length>=3||r.callee.body.body[2]&&r.callee.body.body[2].type==="FunctionDeclaration"&&r.callee.body.body[2].params.length===1&&r.callee.body.body[2].body.body.length>=3)&&(r.arguments[0]&&(r.arguments[0].type==="ArrayExpression"&&(o=r.arguments[0])&&r.arguments[0].elements.length>0&&r.arguments[0].elements.every((e=>e&&e.type==="FunctionExpression"))||r.arguments[0].type==="ObjectExpression"&&(o=r.arguments[0])&&r.arguments[0].properties&&r.arguments[0].properties.length>0&&r.arguments[0].properties.every((e=>e&&e.type==="Property"&&!e.computed&&e.key&&e.key.type==="Literal"&&(typeof e.key.value==="string"||typeof e.key.value==="number")&&e.value&&e.value.type==="FunctionExpression"))))||r.arguments.length===0&&r.callee.type==="FunctionExpression"&&r.callee.params.length===0&&r.callee.body.type==="BlockStatement"&&r.callee.body.body.length>5&&r.callee.body.body[0].type==="VariableDeclaration"&&r.callee.body.body[0].declarations.length===1&&r.callee.body.body[0].declarations[0].id.type==="Identifier"&&r.callee.body.body[1].type==="ExpressionStatement"&&r.callee.body.body[1].expression.type==="AssignmentExpression"&&r.callee.body.body[2].type==="ExpressionStatement"&&r.callee.body.body[2].expression.type==="AssignmentExpression"&&r.callee.body.body[3].type==="ExpressionStatement"&&r.callee.body.body[3].expression.type==="AssignmentExpression"&&r.callee.body.body[3].expression.left.type==="MemberExpression"&&r.callee.body.body[3].expression.left.object.type==="Identifier"&&r.callee.body.body[3].expression.left.object.name===r.callee.body.body[0].declarations[0].id.name&&r.callee.body.body[3].expression.left.property.type==="Identifier"&&r.callee.body.body[3].expression.left.property.name==="modules"&&r.callee.body.body[3].expression.right.type==="ObjectExpression"&&r.callee.body.body[3].expression.right.properties.every((e=>e&&e.type==="Property"&&!e.computed&&e.key&&e.key.type==="Literal"&&(typeof e.key.value==="string"||typeof e.key.value==="number")&&e.value&&e.value.type==="FunctionExpression"))&&(o=r.callee.body.body[3].expression.right)&&(r.callee.body.body[4].type==="VariableDeclaration"&&r.callee.body.body[4].declarations.length===1&&r.callee.body.body[4].declarations[0].init&&r.callee.body.body[4].declarations[0].init.type==="CallExpression"&&r.callee.body.body[4].declarations[0].init.callee.type==="Identifier"&&r.callee.body.body[4].declarations[0].init.callee.name==="require"||r.callee.body.body[5].type==="VariableDeclaration"&&r.callee.body.body[5].declarations.length===1&&r.callee.body.body[5].declarations[0].init&&r.callee.body.body[5].declarations[0].init.type==="CallExpression"&&r.callee.body.body[5].declarations[0].init.callee.type==="Identifier"&&r.callee.body.body[5].declarations[0].init.callee.name==="require")){const e=new Map;let t;if(o.type==="ArrayExpression")t=o.elements.filter((e=>(e===null||e===void 0?void 0:e.type)==="FunctionExpression")).map(((e,t)=>[String(t),e]));else t=o.properties.map((e=>[String(e.key.value),e.value]));for(const[r,a]of t){const t=a.body.body.length===1?a.body.body[0]:(a.body.body.length===2||a.body.body.length===3&&a.body.body[2].type==="EmptyStatement")&&a.body.body[0].type==="ExpressionStatement"&&a.body.body[0].expression.type==="Literal"&&a.body.body[0].expression.value==="use strict"?a.body.body[1]:null;if(t&&t.type==="ExpressionStatement"&&t.expression.type==="AssignmentExpression"&&t.expression.operator==="="&&t.expression.left.type==="MemberExpression"&&t.expression.left.object.type==="Identifier"&&"params"in a&&a.params.length>0&&"name"in a.params[0]&&t.expression.left.object.name===a.params[0].name&&t.expression.left.property.type==="Identifier"&&t.expression.left.property.name==="exports"&&t.expression.right.type==="CallExpression"&&t.expression.right.callee.type==="Identifier"&&t.expression.right.callee.name==="require"&&t.expression.right.arguments.length===1&&t.expression.right.arguments[0].type==="Literal"){e.set(r,t.expression.right.arguments[0].value)}}for(const[,r]of t){if("params"in r&&r.params.length===3&&r.params[2].type==="Identifier"){const t=new Map;a.walk(r.body,{enter(a,o){const s=a;const u=o;if(s.type==="CallExpression"&&s.callee.type==="Identifier"&&"name"in r.params[2]&&s.callee.name===r.params[2].name&&s.arguments.length===1&&s.arguments[0].type==="Literal"){const r=e.get(String(s.arguments[0].value));if(r){const e={type:"CallExpression",optional:false,callee:{type:"Identifier",name:"require"},arguments:[{type:"Literal",value:r}]};const a=u;if("right"in a&&a.right===s){a.right=e}else if("left"in a&&a.left===s){a.left=e}else if("object"in a&&a.object===s){a.object=e}else if("callee"in a&&a.callee===s){a.callee=e}else if("arguments"in a&&a.arguments.some((e=>e===s))){a.arguments=a.arguments.map((t=>t===s?e:t))}else if("init"in a&&a.init===s){if(a.type==="VariableDeclarator"&&a.id.type==="Identifier")t.set(a.id.name,r);a.init=e}}}else if(s.type==="CallExpression"&&s.callee.type==="MemberExpression"&&s.callee.object.type==="Identifier"&&"name"in r.params[2]&&s.callee.object.name===r.params[2].name&&s.callee.property.type==="Identifier"&&s.callee.property.name==="n"&&s.arguments.length===1&&s.arguments[0].type==="Identifier"){if(u&&"init"in u&&u.init===s){const e=s.arguments[0];const t={type:"CallExpression",optional:false,callee:{type:"MemberExpression",computed:false,optional:false,object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"assign"}},arguments:[{type:"ArrowFunctionExpression",expression:true,params:[],body:e},{type:"ObjectExpression",properties:[{type:"Property",kind:"init",method:false,computed:false,shorthand:false,key:{type:"Identifier",name:"a"},value:e}]}]};u.init=t}}}})}}}}}t.handleWrappers=handleWrappers},5920:(e,t)=>{e.exports=t=abbrev.abbrev=abbrev;abbrev.monkeyPatch=monkeyPatch;function monkeyPatch(){Object.defineProperty(Array.prototype,"abbrev",{value:function(){return abbrev(this)},enumerable:false,configurable:true,writable:true});Object.defineProperty(Object.prototype,"abbrev",{value:function(){return abbrev(Object.keys(this))},enumerable:false,configurable:true,writable:true})}function abbrev(e){if(arguments.length!==1||!Array.isArray(e)){e=Array.prototype.slice.call(arguments,0)}for(var t=0,r=e.length,a=[];tt?1:-1}},5534:e=>{"use strict";function isArguments(e){return e!=null&&typeof e==="object"&&e.hasOwnProperty("callee")}var t={"*":{label:"any",check:function(){return true}},A:{label:"array",check:function(e){return Array.isArray(e)||isArguments(e)}},S:{label:"string",check:function(e){return typeof e==="string"}},N:{label:"number",check:function(e){return typeof e==="number"}},F:{label:"function",check:function(e){return typeof e==="function"}},O:{label:"object",check:function(e){return typeof e==="object"&&e!=null&&!t.A.check(e)&&!t.E.check(e)}},B:{label:"boolean",check:function(e){return typeof e==="boolean"}},E:{label:"error",check:function(e){return e instanceof Error}},Z:{label:"null",check:function(e){return e==null}}};function addSchema(e,t){var r=t[e.length]=t[e.length]||[];if(r.indexOf(e)===-1)r.push(e)}var r=e.exports=function(e,r){if(arguments.length!==2)throw wrongNumberOfArgs(["SA"],arguments.length);if(!e)throw missingRequiredArg(0,"rawSchemas");if(!r)throw missingRequiredArg(1,"args");if(!t.S.check(e))throw invalidType(0,["string"],e);if(!t.A.check(r))throw invalidType(1,["array"],r);var a=e.split("|");var o={};a.forEach((function(e){for(var r=0;r{"use strict";t.TrackerGroup=r(2952);t.Tracker=r(6189);t.TrackerStream=r(5849)},8313:(e,t,r)=>{"use strict";var a=r(2361).EventEmitter;var o=r(3837);var s=0;var u=e.exports=function(e){a.call(this);this.id=++s;this.name=e};o.inherits(u,a)},2952:(e,t,r)=>{"use strict";var a=r(3837);var o=r(8313);var s=r(6189);var u=r(5849);var c=e.exports=function(e){o.call(this,e);this.parentGroup=null;this.trackers=[];this.completion={};this.weight={};this.totalWeight=0;this.finished=false;this.bubbleChange=bubbleChange(this)};a.inherits(c,o);function bubbleChange(e){return function(t,r,a){e.completion[a.id]=r;if(e.finished)return;e.emit("change",t||e.name,e.completed(),e)}}c.prototype.nameInTree=function(){var e=[];var t=this;while(t){e.unshift(t.name);t=t.parentGroup}return e.join("/")};c.prototype.addUnit=function(e,t){if(e.addUnit){var r=this;while(r){if(e===r){throw new Error("Attempted to add tracker group "+e.name+" to tree that already includes it "+this.nameInTree(this))}r=r.parentGroup}e.parentGroup=this}this.weight[e.id]=t||1;this.totalWeight+=this.weight[e.id];this.trackers.push(e);this.completion[e.id]=e.completed();e.on("change",this.bubbleChange);if(!this.finished)this.emit("change",e.name,this.completion[e.id],e);return e};c.prototype.completed=function(){if(this.trackers.length===0)return 0;var e=1/this.totalWeight;var t=0;for(var r=0;r{"use strict";var a=r(3837);var o=r(675);var s=r(1722);var u=r(6189);var c=e.exports=function(e,t,r){o.Transform.call(this,r);this.tracker=new u(e,t);this.name=e;this.id=this.tracker.id;this.tracker.on("change",delegateChange(this))};a.inherits(c,o.Transform);function delegateChange(e){return function(t,r,a){e.emit("change",t,r,e)}}c.prototype._transform=function(e,t,r){this.tracker.completeWork(e.length?e.length:1);this.push(e);r()};c.prototype._flush=function(e){this.tracker.finish();e()};s(c.prototype,"tracker").method("completed").method("addWork").method("finish")},6189:(e,t,r)=>{"use strict";var a=r(3837);var o=r(8313);var s=e.exports=function(e,t){o.call(this,e);this.workDone=0;this.workTodo=t||0};a.inherits(s,o);s.prototype.completed=function(){return this.workTodo===0?0:this.workDone/this.workTodo};s.prototype.addWork=function(e){this.workTodo+=e;this.emit("change",this.name,this.completed(),this)};s.prototype.completeWork=function(e){this.workDone+=e;if(this.workDone>this.workTodo)this.workDone=this.workTodo;this.emit("change",this.name,this.completed(),this)};s.prototype.finish=function(){this.workTodo=this.workDone=1;this.emit("change",this.name,1,this)}},5706:(module,exports,__nccwpck_require__)=>{var fs=__nccwpck_require__(7147),path=__nccwpck_require__(1017),fileURLToPath=__nccwpck_require__(9001),join=path.join,dirname=path.dirname,exists=fs.accessSync&&function(e){try{fs.accessSync(e)}catch(e){return false}return true}||fs.existsSync||path.existsSync,defaults={arrow:process.env.NODE_BINDINGS_ARROW||" → ",compiled:process.env.NODE_BINDINGS_COMPILED_DIR||"compiled",platform:process.platform,arch:process.arch,nodePreGyp:"node-v"+process.versions.modules+"-"+process.platform+"-"+process.arch,version:process.versions.node,bindings:"bindings.node",try:[["module_root","build","bindings"],["module_root","build","Debug","bindings"],["module_root","build","Release","bindings"],["module_root","out","Debug","bindings"],["module_root","Debug","bindings"],["module_root","out","Release","bindings"],["module_root","Release","bindings"],["module_root","build","default","bindings"],["module_root","compiled","version","platform","arch","bindings"],["module_root","addon-build","release","install-root","bindings"],["module_root","addon-build","debug","install-root","bindings"],["module_root","addon-build","default","install-root","bindings"],["module_root","lib","binding","nodePreGyp","bindings"]]};function bindings(opts){if(typeof opts=="string"){opts={bindings:opts}}else if(!opts){opts={}}Object.keys(defaults).map((function(e){if(!(e in opts))opts[e]=defaults[e]}));if(!opts.module_root){opts.module_root=exports.getRoot(exports.getFileName())}if(path.extname(opts.bindings)!=".node"){opts.bindings+=".node"}var requireFunc=true?eval("require"):0;var tries=[],i=0,l=opts.try.length,n,b,err;for(;i{"use strict";e.exports=function(e,t){if(e===null||e===undefined){throw TypeError()}e=String(e);var r=e.length;var a=t?Number(t):0;if(Number.isNaN(a)){a=0}if(a<0||a>=r){return undefined}var o=e.charCodeAt(a);if(o>=55296&&o<=56319&&r>a+1){var s=e.charCodeAt(a+1);if(s>=56320&&s<=57343){return(o-55296)*1024+s-56320+65536}}return o}},6322:(e,t)=>{"use strict";var r="[";t.up=function up(e){return r+(e||"")+"A"};t.down=function down(e){return r+(e||"")+"B"};t.forward=function forward(e){return r+(e||"")+"C"};t.back=function back(e){return r+(e||"")+"D"};t.nextLine=function nextLine(e){return r+(e||"")+"E"};t.previousLine=function previousLine(e){return r+(e||"")+"F"};t.horizontalAbsolute=function horizontalAbsolute(e){if(e==null)throw new Error("horizontalAboslute requires a column to position to");return r+e+"G"};t.eraseData=function eraseData(){return r+"J"};t.eraseLine=function eraseLine(){return r+"K"};t.goto=function(e,t){return r+t+";"+e+"H"};t.gotoSOL=function(){return"\r"};t.beep=function(){return""};t.hideCursor=function hideCursor(){return r+"?25l"};t.showCursor=function showCursor(){return r+"?25h"};var a={reset:0,bold:1,italic:3,underline:4,inverse:7,stopBold:22,stopItalic:23,stopUnderline:24,stopInverse:27,white:37,black:30,blue:34,cyan:36,green:32,magenta:35,red:31,yellow:33,bgWhite:47,bgBlack:40,bgBlue:44,bgCyan:46,bgGreen:42,bgMagenta:45,bgRed:41,bgYellow:43,grey:90,brightBlack:90,brightRed:91,brightGreen:92,brightYellow:93,brightBlue:94,brightMagenta:95,brightCyan:96,brightWhite:97,bgGrey:100,bgBrightBlack:100,bgBrightRed:101,bgBrightGreen:102,bgBrightYellow:103,bgBrightBlue:104,bgBrightMagenta:105,bgBrightCyan:106,bgBrightWhite:107};t.color=function color(e){if(arguments.length!==1||!Array.isArray(e)){e=Array.prototype.slice.call(arguments)}return r+e.map(colorNameToCode).join(";")+"m"};function colorNameToCode(e){if(a[e]!=null)return a[e];throw new Error("Unknown color or style name: "+e)}},3487:(e,t)=>{function isArray(e){if(Array.isArray){return Array.isArray(e)}return objectToString(e)==="[object Array]"}t.isArray=isArray;function isBoolean(e){return typeof e==="boolean"}t.isBoolean=isBoolean;function isNull(e){return e===null}t.isNull=isNull;function isNullOrUndefined(e){return e==null}t.isNullOrUndefined=isNullOrUndefined;function isNumber(e){return typeof e==="number"}t.isNumber=isNumber;function isString(e){return typeof e==="string"}t.isString=isString;function isSymbol(e){return typeof e==="symbol"}t.isSymbol=isSymbol;function isUndefined(e){return e===void 0}t.isUndefined=isUndefined;function isRegExp(e){return objectToString(e)==="[object RegExp]"}t.isRegExp=isRegExp;function isObject(e){return typeof e==="object"&&e!==null}t.isObject=isObject;function isDate(e){return objectToString(e)==="[object Date]"}t.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}t.isError=isError;function isFunction(e){return typeof e==="function"}t.isFunction=isFunction;function isPrimitive(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}t.isPrimitive=isPrimitive;t.isBuffer=Buffer.isBuffer;function objectToString(e){return Object.prototype.toString.call(e)}},1722:e=>{e.exports=Delegator;function Delegator(e,t){if(!(this instanceof Delegator))return new Delegator(e,t);this.proto=e;this.target=t;this.methods=[];this.getters=[];this.setters=[];this.fluents=[]}Delegator.prototype.method=function(e){var t=this.proto;var r=this.target;this.methods.push(e);t[e]=function(){return this[r][e].apply(this[r],arguments)};return this};Delegator.prototype.access=function(e){return this.getter(e).setter(e)};Delegator.prototype.getter=function(e){var t=this.proto;var r=this.target;this.getters.push(e);t.__defineGetter__(e,(function(){return this[r][e]}));return this};Delegator.prototype.setter=function(e){var t=this.proto;var r=this.target;this.setters.push(e);t.__defineSetter__(e,(function(t){return this[r][e]=t}));return this};Delegator.prototype.fluent=function(e){var t=this.proto;var r=this.target;this.fluents.push(e);t[e]=function(t){if("undefined"!=typeof t){this[r][e]=t;return this}else{return this[r][e]}};return this}},2157:(e,t,r)=>{"use strict";var a=r(2037).platform();var o=r(2081).spawnSync;var s=r(7147).readdirSync;var u="glibc";var c="musl";var d={encoding:"utf8",env:process.env};if(!o){o=function(){return{status:126,stdout:"",stderr:""}}}function contains(e){return function(t){return t.indexOf(e)!==-1}}function versionFromMuslLdd(e){return e.split(/[\r\n]+/)[1].trim().split(/\s/)[1]}function safeReaddirSync(e){try{return s(e)}catch(e){}return[]}var f="";var p="";var h="";if(a==="linux"){var v=o("getconf",["GNU_LIBC_VERSION"],d);if(v.status===0){f=u;p=v.stdout.trim().split(" ")[1];h="getconf"}else{var _=o("ldd",["--version"],d);if(_.status===0&&_.stdout.indexOf(c)!==-1){f=c;p=versionFromMuslLdd(_.stdout);h="ldd"}else if(_.status===1&&_.stderr.indexOf(c)!==-1){f=c;p=versionFromMuslLdd(_.stderr);h="ldd"}else{var g=safeReaddirSync("/lib");if(g.some(contains("-linux-gnu"))){f=u;h="filesystem"}else if(g.some(contains("libc.musl-"))){f=c;h="filesystem"}else if(g.some(contains("ld-musl-"))){f=c;h="filesystem"}else{var y=safeReaddirSync("/usr/sbin");if(y.some(contains("glibc"))){f=u;h="filesystem"}}}}}var m=f!==""&&f!==u;e.exports={GLIBC:u,MUSL:c,family:f,version:p,method:h,isNonGlibcLinux:m}},9001:(e,t,r)=>{var a=r(1017).sep||"/";e.exports=fileUriToPath;function fileUriToPath(e){if("string"!=typeof e||e.length<=7||"file://"!=e.substring(0,7)){throw new TypeError("must pass in a file:// URI to convert to a file path")}var t=decodeURI(e.substring(7));var r=t.indexOf("/");var o=t.substring(0,r);var s=t.substring(r+1);if("localhost"==o)o="";if(o){o=a+a+o}s=s.replace(/^(.+)\|/,"$1:");if(a=="\\"){s=s.replace(/\//g,"\\")}if(/^.+\:/.test(s)){}else{s=a+s}return o+s}},1271:(e,t,r)=>{"use strict";var a=r(1021);var o=r(5791);e.exports={activityIndicator:function(e,t,r){if(e.spun==null)return;return a(t,e.spun)},progressbar:function(e,t,r){if(e.completed==null)return;return o(t,r,e.completed)}}},2479:(e,t,r)=>{"use strict";var a=r(3837);var o=t.User=function User(e){var t=new Error(e);Error.captureStackTrace(t,User);t.code="EGAUGE";return t};t.MissingTemplateValue=function MissingTemplateValue(e,t){var r=new o(a.format('Missing template value "%s"',e.type));Error.captureStackTrace(r,MissingTemplateValue);r.template=e;r.values=t;return r};t.Internal=function Internal(e){var t=new Error(e);Error.captureStackTrace(t,Internal);t.code="EGAUGEINTERNAL";return t}},3278:e=>{"use strict";e.exports=isWin32()||isColorTerm();function isWin32(){return process.platform==="win32"}function isColorTerm(){var e=/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i;return!!process.env.COLORTERM||e.test(process.env.TERM)}},6054:(e,t,r)=>{"use strict";var a=r(4708);var o=r(7963);var s=r(3278);var u=r(2028);var c=r(7987);var d=r(75);var f=r(9186);var p=r(6401);e.exports=Gauge;function callWith(e,t){return function(){return t.call(e)}}function Gauge(e,t){var r,o;if(e&&e.write){o=e;r=t||{}}else if(t&&t.write){o=t;r=e||{}}else{o=f.stderr;r=e||t||{}}this._status={spun:0,section:"",subsection:""};this._paused=false;this._disabled=true;this._showing=false;this._onScreen=false;this._needsRedraw=false;this._hideCursor=r.hideCursor==null?true:r.hideCursor;this._fixedFramerate=r.fixedFramerate==null?!/^v0\.8\./.test(f.version):r.fixedFramerate;this._lastUpdateAt=null;this._updateInterval=r.updateInterval==null?50:r.updateInterval;this._themes=r.themes||c;this._theme=r.theme;var s=this._computeTheme(r.theme);var u=r.template||[{type:"progressbar",length:20},{type:"activityIndicator",kerning:1,length:1},{type:"section",kerning:1,default:""},{type:"subsection",kerning:1,default:""}];this.setWriteTo(o,r.tty);var d=r.Plumbing||a;this._gauge=new d(s,u,this.getWidth());this._$$doRedraw=callWith(this,this._doRedraw);this._$$handleSizeChange=callWith(this,this._handleSizeChange);this._cleanupOnExit=r.cleanupOnExit==null||r.cleanupOnExit;this._removeOnExit=null;if(r.enabled||r.enabled==null&&this._tty&&this._tty.isTTY){this.enable()}else{this.disable()}}Gauge.prototype={};Gauge.prototype.isEnabled=function(){return!this._disabled};Gauge.prototype.setTemplate=function(e){this._gauge.setTemplate(e);if(this._showing)this._requestRedraw()};Gauge.prototype._computeTheme=function(e){if(!e)e={};if(typeof e==="string"){e=this._themes.getTheme(e)}else if(e&&(Object.keys(e).length===0||e.hasUnicode!=null||e.hasColor!=null)){var t=e.hasUnicode==null?o():e.hasUnicode;var r=e.hasColor==null?s:e.hasColor;e=this._themes.getDefault({hasUnicode:t,hasColor:r,platform:e.platform})}return e};Gauge.prototype.setThemeset=function(e){this._themes=e;this.setTheme(this._theme)};Gauge.prototype.setTheme=function(e){this._gauge.setTheme(this._computeTheme(e));if(this._showing)this._requestRedraw();this._theme=e};Gauge.prototype._requestRedraw=function(){this._needsRedraw=true;if(!this._fixedFramerate)this._doRedraw()};Gauge.prototype.getWidth=function(){return(this._tty&&this._tty.columns||80)-1};Gauge.prototype.setWriteTo=function(e,t){var r=!this._disabled;if(r)this.disable();this._writeTo=e;this._tty=t||e===f.stderr&&f.stdout.isTTY&&f.stdout||e.isTTY&&e||this._tty;if(this._gauge)this._gauge.setWidth(this.getWidth());if(r)this.enable()};Gauge.prototype.enable=function(){if(!this._disabled)return;this._disabled=false;if(this._tty)this._enableEvents();if(this._showing)this.show()};Gauge.prototype.disable=function(){if(this._disabled)return;if(this._showing){this._lastUpdateAt=null;this._showing=false;this._doRedraw();this._showing=true}this._disabled=true;if(this._tty)this._disableEvents()};Gauge.prototype._enableEvents=function(){if(this._cleanupOnExit){this._removeOnExit=u(callWith(this,this.disable))}this._tty.on("resize",this._$$handleSizeChange);if(this._fixedFramerate){this.redrawTracker=d(this._$$doRedraw,this._updateInterval);if(this.redrawTracker.unref)this.redrawTracker.unref()}};Gauge.prototype._disableEvents=function(){this._tty.removeListener("resize",this._$$handleSizeChange);if(this._fixedFramerate)clearInterval(this.redrawTracker);if(this._removeOnExit)this._removeOnExit()};Gauge.prototype.hide=function(e){if(this._disabled)return e&&f.nextTick(e);if(!this._showing)return e&&f.nextTick(e);this._showing=false;this._doRedraw();e&&p(e)};Gauge.prototype.show=function(e,t){this._showing=true;if(typeof e==="string"){this._status.section=e}else if(typeof e==="object"){var r=Object.keys(e);for(var a=0;a{"use strict";var a=r(8753);e.exports=function(e){if(a(e)){return false}if(e>=4352&&(e<=4447||9001===e||9002===e||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141)){return true}return false}},5511:(e,t,r)=>{"use strict";var a=r(7518);var o=r(6708);var s=r(6062);e.exports=function(e){if(typeof e!=="string"||e.length===0){return 0}var t=0;e=a(e);for(var r=0;r=127&&u<=159){continue}if(u>=65536){r++}if(s(u)){t+=2}else{t++}}return t}},4708:(e,t,r)=>{"use strict";var a=r(6322);var o=r(4293);var s=r(5534);var u=e.exports=function(e,t,r){if(!r)r=80;s("OAN",[e,t,r]);this.showing=false;this.theme=e;this.width=r;this.template=t};u.prototype={};u.prototype.setTheme=function(e){s("O",[e]);this.theme=e};u.prototype.setTemplate=function(e){s("A",[e]);this.template=e};u.prototype.setWidth=function(e){s("N",[e]);this.width=e};u.prototype.hide=function(){return a.gotoSOL()+a.eraseLine()};u.prototype.hideCursor=a.hideCursor;u.prototype.showCursor=a.showCursor;u.prototype.show=function(e){var t=Object.create(this.theme);for(var r in e){t[r]=e[r]}return o(this.width,this.template,t).trim()+a.color("reset")+a.eraseLine()+a.gotoSOL()}},9186:e=>{"use strict";e.exports=process},5791:(e,t,r)=>{"use strict";var a=r(5534);var o=r(4293);var s=r(2343);var u=r(5511);e.exports=function(e,t,r){a("ONN",[e,t,r]);if(r<0)r=0;if(r>1)r=1;if(t<=0)return"";var s=Math.round(t*r);var u=t-s;var c=[{type:"complete",value:repeat(e.complete,s),length:s},{type:"remaining",value:repeat(e.remaining,u),length:u}];return o(t,c,e)};function repeat(e,t){var r="";var a=t;do{if(a%2){r+=e}a=Math.floor(a/2);e+=e}while(a&&u(r){"use strict";var a=r(7568);var o=r(5534);var s=r(1800);var u=r(2343);var c=r(2479);var d=r(5205);function renderValueWithValues(e){return function(t){return renderValue(t,e)}}var f=e.exports=function(e,t,r){var o=prepareItems(e,t,r);var s=o.map(renderValueWithValues(r)).join("");return a.left(u(s,e),e)};function preType(e){var t=e.type[0].toUpperCase()+e.type.slice(1);return"pre"+t}function postType(e){var t=e.type[0].toUpperCase()+e.type.slice(1);return"post"+t}function hasPreOrPost(e,t){if(!e.type)return;return t[preType(e)]||t[postType(e)]}function generatePreAndPost(e,t){var r=s({},e);var a=Object.create(t);var o=[];var u=preType(r);var c=postType(r);if(a[u]){o.push({value:a[u]});a[u]=null}r.minLength=null;r.length=null;r.maxLength=null;o.push(r);a[r.type]=a[r.type];if(a[c]){o.push({value:a[c]});a[c]=null}return function(e,t,r){return f(r,o,a)}}function prepareItems(e,t,r){function cloneAndObjectify(t,a,o){var s=new d(t,e);var u=s.type;if(s.value==null){if(!(u in r)){if(s.default==null){throw new c.MissingTemplateValue(s,r)}else{s.value=s.default}}else{s.value=r[u]}}if(s.value==null||s.value==="")return null;s.index=a;s.first=a===0;s.last=a===o.length-1;if(hasPreOrPost(s,r))s.value=generatePreAndPost(s,r);return s}var a=t.map(cloneAndObjectify).filter((function(e){return e!=null}));var o=0;var s=e;var u=a.length;function consumeSpace(e){if(e>s)e=s;o+=e;s-=e}function finishSizing(e,t){if(e.finished)throw new c.Internal("Tried to finish template item that was already finished");if(t===Infinity)throw new c.Internal("Length of template item cannot be infinity");if(t!=null)e.length=t;e.minLength=null;e.maxLength=null;--u;e.finished=true;if(e.length==null)e.length=e.getBaseLength();if(e.length==null)throw new c.Internal("Finished template items must have a length");consumeSpace(e.getLength())}a.forEach((function(e){if(!e.kerning)return;var t=e.first?0:a[e.index-1].padRight;if(!e.first&&t=h){finishSizing(e,e.minLength);p=true}}))}while(p&&f++{"use strict";var a=r(9186);try{e.exports=setImmediate}catch(t){e.exports=a.nextTick}},75:e=>{"use strict";e.exports=setInterval},1021:e=>{"use strict";e.exports=function spin(e,t){return e[t%e.length]}},5205:(e,t,r)=>{"use strict";var a=r(5511);e.exports=TemplateItem;function isPercent(e){if(typeof e!=="string")return false;return e.slice(-1)==="%"}function percent(e){return Number(e.slice(0,-1))/100}function TemplateItem(e,t){this.overallOutputLength=t;this.finished=false;this.type=null;this.value=null;this.length=null;this.maxLength=null;this.minLength=null;this.kerning=null;this.align="left";this.padLeft=0;this.padRight=0;this.index=null;this.first=null;this.last=null;if(typeof e==="string"){this.value=e}else{for(var r in e)this[r]=e[r]}if(isPercent(this.length)){this.length=Math.round(this.overallOutputLength*percent(this.length))}if(isPercent(this.minLength)){this.minLength=Math.round(this.overallOutputLength*percent(this.minLength))}if(isPercent(this.maxLength)){this.maxLength=Math.round(this.overallOutputLength*percent(this.maxLength))}return this}TemplateItem.prototype={};TemplateItem.prototype.getBaseLength=function(){var e=this.length;if(e==null&&typeof this.value==="string"&&this.maxLength==null&&this.minLength==null){e=a(this.value)}return e};TemplateItem.prototype.getLength=function(){var e=this.getBaseLength();if(e==null)return null;return e+this.padLeft+this.padRight};TemplateItem.prototype.getMaxLength=function(){if(this.maxLength==null)return null;return this.maxLength+this.padLeft+this.padRight};TemplateItem.prototype.getMinLength=function(){if(this.minLength==null)return null;return this.minLength+this.padLeft+this.padRight}},3117:(e,t,r)=>{"use strict";var a=r(1800);e.exports=function(){return o.newThemeSet()};var o={};o.baseTheme=r(1271);o.newTheme=function(e,t){if(!t){t=e;e=this.baseTheme}return a({},e,t)};o.getThemeNames=function(){return Object.keys(this.themes)};o.addTheme=function(e,t,r){this.themes[e]=this.newTheme(t,r)};o.addToAllThemes=function(e){var t=this.themes;Object.keys(t).forEach((function(r){a(t[r],e)}));a(this.baseTheme,e)};o.getTheme=function(e){if(!this.themes[e])throw this.newMissingThemeError(e);return this.themes[e]};o.setDefault=function(e,t){if(t==null){t=e;e={}}var r=e.platform==null?"fallback":e.platform;var a=!!e.hasUnicode;var o=!!e.hasColor;if(!this.defaults[r])this.defaults[r]={true:{},false:{}};this.defaults[r][a][o]=t};o.getDefault=function(e){if(!e)e={};var t=e.platform||process.platform;var r=this.defaults[t]||this.defaults.fallback;var o=!!e.hasUnicode;var s=!!e.hasColor;if(!r)throw this.newMissingDefaultThemeError(t,o,s);if(!r[o][s]){if(o&&s&&r[!o][s]){o=false}else if(o&&s&&r[o][!s]){s=false}else if(o&&s&&r[!o][!s]){o=false;s=false}else if(o&&!s&&r[!o][s]){o=false}else if(!o&&s&&r[o][!s]){s=false}else if(r===this.defaults.fallback){throw this.newMissingDefaultThemeError(t,o,s)}}if(r[o][s]){return this.getTheme(r[o][s])}else{return this.getDefault(a({},e,{platform:"fallback"}))}};o.newMissingThemeError=function newMissingThemeError(e){var t=new Error('Could not find a gauge theme named "'+e+'"');Error.captureStackTrace.call(t,newMissingThemeError);t.theme=e;t.code="EMISSINGTHEME";return t};o.newMissingDefaultThemeError=function newMissingDefaultThemeError(e,t,r){var a=new Error("Could not find a gauge theme for your platform/unicode/color use combo:\n"+" platform = "+e+"\n"+" hasUnicode = "+t+"\n"+" hasColor = "+r);Error.captureStackTrace.call(a,newMissingDefaultThemeError);a.platform=e;a.hasUnicode=t;a.hasColor=r;a.code="EMISSINGTHEME";return a};o.newThemeSet=function(){var themeset=function(e){return themeset.getDefault(e)};return a(themeset,o,{themes:a({},this.themes),baseTheme:a({},this.baseTheme),defaults:JSON.parse(JSON.stringify(this.defaults||{}))})}},7987:(e,t,r)=>{"use strict";var a=r(6322);var o=r(3117);var s=e.exports=new o;s.addTheme("ASCII",{preProgressbar:"[",postProgressbar:"]",progressbarTheme:{complete:"#",remaining:"."},activityIndicatorTheme:"-\\|/",preSubsection:">"});s.addTheme("colorASCII",s.getTheme("ASCII"),{progressbarTheme:{preComplete:a.color("inverse"),complete:" ",postComplete:a.color("stopInverse"),preRemaining:a.color("brightBlack"),remaining:".",postRemaining:a.color("reset")}});s.addTheme("brailleSpinner",{preProgressbar:"⸨",postProgressbar:"⸩",progressbarTheme:{complete:"░",remaining:"⠂"},activityIndicatorTheme:"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏",preSubsection:">"});s.addTheme("colorBrailleSpinner",s.getTheme("brailleSpinner"),{progressbarTheme:{preComplete:a.color("inverse"),complete:" ",postComplete:a.color("stopInverse"),preRemaining:a.color("brightBlack"),remaining:"░",postRemaining:a.color("reset")}});s.setDefault({},"ASCII");s.setDefault({hasColor:true},"colorASCII");s.setDefault({platform:"darwin",hasUnicode:true},"brailleSpinner");s.setDefault({platform:"darwin",hasUnicode:true,hasColor:true},"colorBrailleSpinner")},2343:(e,t,r)=>{"use strict";var a=r(5511);var o=r(7518);e.exports=wideTruncate;function wideTruncate(e,t){if(a(e)===0)return e;if(t<=0)return"";if(a(e)<=t)return e;var r=o(e);var s=e.length+r.length;var u=e.slice(0,t+s);while(a(u)>t){u=u.slice(0,-1)}return u}},9132:e=>{"use strict";e.exports=clone;var t=Object.getPrototypeOf||function(e){return e.__proto__};function clone(e){if(e===null||typeof e!=="object")return e;if(e instanceof Object)var r={__proto__:t(e)};else var r=Object.create(null);Object.getOwnPropertyNames(e).forEach((function(t){Object.defineProperty(r,t,Object.getOwnPropertyDescriptor(e,t))}));return r}},552:(e,t,r)=>{var a=r(7147);var o=r(1290);var s=r(4410);var u=r(9132);var c=r(3837);var d;var f;if(typeof Symbol==="function"&&typeof Symbol.for==="function"){d=Symbol.for("graceful-fs.queue");f=Symbol.for("graceful-fs.previous")}else{d="___graceful-fs.queue";f="___graceful-fs.previous"}function noop(){}function publishQueue(e,t){Object.defineProperty(e,d,{get:function(){return t}})}var p=noop;if(c.debuglog)p=c.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))p=function(){var e=c.format.apply(c,arguments);e="GFS4: "+e.split(/\n/).join("\nGFS4: ");console.error(e)};if(!a[d]){var h=global[d]||[];publishQueue(a,h);a.close=function(e){function close(t,r){return e.call(a,t,(function(e){if(!e){resetQueue()}if(typeof r==="function")r.apply(this,arguments)}))}Object.defineProperty(close,f,{value:e});return close}(a.close);a.closeSync=function(e){function closeSync(t){e.apply(a,arguments);resetQueue()}Object.defineProperty(closeSync,f,{value:e});return closeSync}(a.closeSync);if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")){process.on("exit",(function(){p(a[d]);r(9491).equal(a[d].length,0)}))}}if(!global[d]){publishQueue(global,a[d])}e.exports=patch(u(a));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!a.__patched){e.exports=patch(a);a.__patched=true}function patch(e){o(e);e.gracefulify=patch;e.createReadStream=createReadStream;e.createWriteStream=createWriteStream;var t=e.readFile;e.readFile=readFile;function readFile(e,r,a){if(typeof r==="function")a=r,r=null;return go$readFile(e,r,a);function go$readFile(e,r,a,o){return t(e,r,(function(t){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))enqueue([go$readFile,[e,r,a],t,o||Date.now(),Date.now()]);else{if(typeof a==="function")a.apply(this,arguments)}}))}}var r=e.writeFile;e.writeFile=writeFile;function writeFile(e,t,a,o){if(typeof a==="function")o=a,a=null;return go$writeFile(e,t,a,o);function go$writeFile(e,t,a,o,s){return r(e,t,a,(function(r){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))enqueue([go$writeFile,[e,t,a,o],r,s||Date.now(),Date.now()]);else{if(typeof o==="function")o.apply(this,arguments)}}))}}var a=e.appendFile;if(a)e.appendFile=appendFile;function appendFile(e,t,r,o){if(typeof r==="function")o=r,r=null;return go$appendFile(e,t,r,o);function go$appendFile(e,t,r,o,s){return a(e,t,r,(function(a){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))enqueue([go$appendFile,[e,t,r,o],a,s||Date.now(),Date.now()]);else{if(typeof o==="function")o.apply(this,arguments)}}))}}var u=e.copyFile;if(u)e.copyFile=copyFile;function copyFile(e,t,r,a){if(typeof r==="function"){a=r;r=0}return go$copyFile(e,t,r,a);function go$copyFile(e,t,r,a,o){return u(e,t,r,(function(s){if(s&&(s.code==="EMFILE"||s.code==="ENFILE"))enqueue([go$copyFile,[e,t,r,a],s,o||Date.now(),Date.now()]);else{if(typeof a==="function")a.apply(this,arguments)}}))}}var c=e.readdir;e.readdir=readdir;function readdir(e,t,r){if(typeof t==="function")r=t,t=null;return go$readdir(e,t,r);function go$readdir(e,t,r,a){return c(e,t,(function(o,s){if(o&&(o.code==="EMFILE"||o.code==="ENFILE"))enqueue([go$readdir,[e,t,r],o,a||Date.now(),Date.now()]);else{if(s&&s.sort)s.sort();if(typeof r==="function")r.call(this,o,s)}}))}}if(process.version.substr(0,4)==="v0.8"){var d=s(e);ReadStream=d.ReadStream;WriteStream=d.WriteStream}var f=e.ReadStream;if(f){ReadStream.prototype=Object.create(f.prototype);ReadStream.prototype.open=ReadStream$open}var p=e.WriteStream;if(p){WriteStream.prototype=Object.create(p.prototype);WriteStream.prototype.open=WriteStream$open}Object.defineProperty(e,"ReadStream",{get:function(){return ReadStream},set:function(e){ReadStream=e},enumerable:true,configurable:true});Object.defineProperty(e,"WriteStream",{get:function(){return WriteStream},set:function(e){WriteStream=e},enumerable:true,configurable:true});var h=ReadStream;Object.defineProperty(e,"FileReadStream",{get:function(){return h},set:function(e){h=e},enumerable:true,configurable:true});var v=WriteStream;Object.defineProperty(e,"FileWriteStream",{get:function(){return v},set:function(e){v=e},enumerable:true,configurable:true});function ReadStream(e,t){if(this instanceof ReadStream)return f.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var e=this;open(e.path,e.flags,e.mode,(function(t,r){if(t){if(e.autoClose)e.destroy();e.emit("error",t)}else{e.fd=r;e.emit("open",r);e.read()}}))}function WriteStream(e,t){if(this instanceof WriteStream)return p.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var e=this;open(e.path,e.flags,e.mode,(function(t,r){if(t){e.destroy();e.emit("error",t)}else{e.fd=r;e.emit("open",r)}}))}function createReadStream(t,r){return new e.ReadStream(t,r)}function createWriteStream(t,r){return new e.WriteStream(t,r)}var _=e.open;e.open=open;function open(e,t,r,a){if(typeof r==="function")a=r,r=null;return go$open(e,t,r,a);function go$open(e,t,r,a,o){return _(e,t,r,(function(s,u){if(s&&(s.code==="EMFILE"||s.code==="ENFILE"))enqueue([go$open,[e,t,r,a],s,o||Date.now(),Date.now()]);else{if(typeof a==="function")a.apply(this,arguments)}}))}}return e}function enqueue(e){p("ENQUEUE",e[0].name,e[1]);a[d].push(e);retry()}var v;function resetQueue(){var e=Date.now();for(var t=0;t2){a[d][t][3]=e;a[d][t][4]=e}}retry()}function retry(){clearTimeout(v);v=undefined;if(a[d].length===0)return;var e=a[d].shift();var t=e[0];var r=e[1];var o=e[2];var s=e[3];var u=e[4];if(s===undefined){p("RETRY",t.name,r);t.apply(null,r)}else if(Date.now()-s>=6e4){p("TIMEOUT",t.name,r);var c=r.pop();if(typeof c==="function")c.call(null,o)}else{var f=Date.now()-u;var h=Math.max(u-s,1);var _=Math.min(h*1.2,100);if(f>=_){p("RETRY",t.name,r);t.apply(null,r.concat([s]))}else{a[d].push(e)}}if(v===undefined){v=setTimeout(retry,0)}}},4410:(e,t,r)=>{var a=r(2781).Stream;e.exports=legacy;function legacy(e){return{ReadStream:ReadStream,WriteStream:WriteStream};function ReadStream(t,r){if(!(this instanceof ReadStream))return new ReadStream(t,r);a.call(this);var o=this;this.path=t;this.fd=null;this.readable=true;this.paused=false;this.flags="r";this.mode=438;this.bufferSize=64*1024;r=r||{};var s=Object.keys(r);for(var u=0,c=s.length;uthis.end){throw new Error("start must be <= end")}this.pos=this.start}if(this.fd!==null){process.nextTick((function(){o._read()}));return}e.open(this.path,this.flags,this.mode,(function(e,t){if(e){o.emit("error",e);o.readable=false;return}o.fd=t;o.emit("open",t);o._read()}))}function WriteStream(t,r){if(!(this instanceof WriteStream))return new WriteStream(t,r);a.call(this);this.path=t;this.fd=null;this.writable=true;this.flags="w";this.encoding="binary";this.mode=438;this.bytesWritten=0;r=r||{};var o=Object.keys(r);for(var s=0,u=o.length;s= zero")}this.pos=this.start}this.busy=false;this._queue=[];if(this.fd===null){this._open=e.open;this._queue.push([this._open,this.path,this.flags,this.mode,undefined]);this.flush()}}}},1290:(e,t,r)=>{var a=r(2057);var o=process.cwd;var s=null;var u=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!s)s=o.call(process);return s};try{process.cwd()}catch(e){}if(typeof process.chdir==="function"){var c=process.chdir;process.chdir=function(e){s=null;c.call(process,e)};if(Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,c)}e.exports=patch;function patch(e){if(a.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)){patchLchmod(e)}if(!e.lutimes){patchLutimes(e)}e.chown=chownFix(e.chown);e.fchown=chownFix(e.fchown);e.lchown=chownFix(e.lchown);e.chmod=chmodFix(e.chmod);e.fchmod=chmodFix(e.fchmod);e.lchmod=chmodFix(e.lchmod);e.chownSync=chownFixSync(e.chownSync);e.fchownSync=chownFixSync(e.fchownSync);e.lchownSync=chownFixSync(e.lchownSync);e.chmodSync=chmodFixSync(e.chmodSync);e.fchmodSync=chmodFixSync(e.fchmodSync);e.lchmodSync=chmodFixSync(e.lchmodSync);e.stat=statFix(e.stat);e.fstat=statFix(e.fstat);e.lstat=statFix(e.lstat);e.statSync=statFixSync(e.statSync);e.fstatSync=statFixSync(e.fstatSync);e.lstatSync=statFixSync(e.lstatSync);if(!e.lchmod){e.lchmod=function(e,t,r){if(r)process.nextTick(r)};e.lchmodSync=function(){}}if(!e.lchown){e.lchown=function(e,t,r,a){if(a)process.nextTick(a)};e.lchownSync=function(){}}if(u==="win32"){e.rename=function(t){return function(r,a,o){var s=Date.now();var u=0;t(r,a,(function CB(c){if(c&&(c.code==="EACCES"||c.code==="EPERM")&&Date.now()-s<6e4){setTimeout((function(){e.stat(a,(function(e,s){if(e&&e.code==="ENOENT")t(r,a,CB);else o(c)}))}),u);if(u<100)u+=10;return}if(o)o(c)}))}}(e.rename)}e.read=function(t){function read(r,a,o,s,u,c){var d;if(c&&typeof c==="function"){var f=0;d=function(p,h,v){if(p&&p.code==="EAGAIN"&&f<10){f++;return t.call(e,r,a,o,s,u,d)}c.apply(this,arguments)}}return t.call(e,r,a,o,s,u,d)}if(Object.setPrototypeOf)Object.setPrototypeOf(read,t);return read}(e.read);e.readSync=function(t){return function(r,a,o,s,u){var c=0;while(true){try{return t.call(e,r,a,o,s,u)}catch(e){if(e.code==="EAGAIN"&&c<10){c++;continue}throw e}}}}(e.readSync);function patchLchmod(e){e.lchmod=function(t,r,o){e.open(t,a.O_WRONLY|a.O_SYMLINK,r,(function(t,a){if(t){if(o)o(t);return}e.fchmod(a,r,(function(t){e.close(a,(function(e){if(o)o(t||e)}))}))}))};e.lchmodSync=function(t,r){var o=e.openSync(t,a.O_WRONLY|a.O_SYMLINK,r);var s=true;var u;try{u=e.fchmodSync(o,r);s=false}finally{if(s){try{e.closeSync(o)}catch(e){}}else{e.closeSync(o)}}return u}}function patchLutimes(e){if(a.hasOwnProperty("O_SYMLINK")){e.lutimes=function(t,r,o,s){e.open(t,a.O_SYMLINK,(function(t,a){if(t){if(s)s(t);return}e.futimes(a,r,o,(function(t){e.close(a,(function(e){if(s)s(t||e)}))}))}))};e.lutimesSync=function(t,r,o){var s=e.openSync(t,a.O_SYMLINK);var u;var c=true;try{u=e.futimesSync(s,r,o);c=false}finally{if(c){try{e.closeSync(s)}catch(e){}}else{e.closeSync(s)}}return u}}else{e.lutimes=function(e,t,r,a){if(a)process.nextTick(a)};e.lutimesSync=function(){}}}function chmodFix(t){if(!t)return t;return function(r,a,o){return t.call(e,r,a,(function(e){if(chownErOk(e))e=null;if(o)o.apply(this,arguments)}))}}function chmodFixSync(t){if(!t)return t;return function(r,a){try{return t.call(e,r,a)}catch(e){if(!chownErOk(e))throw e}}}function chownFix(t){if(!t)return t;return function(r,a,o,s){return t.call(e,r,a,o,(function(e){if(chownErOk(e))e=null;if(s)s.apply(this,arguments)}))}}function chownFixSync(t){if(!t)return t;return function(r,a,o){try{return t.call(e,r,a,o)}catch(e){if(!chownErOk(e))throw e}}}function statFix(t){if(!t)return t;return function(r,a,o){if(typeof a==="function"){o=a;a=null}function callback(e,t){if(t){if(t.uid<0)t.uid+=4294967296;if(t.gid<0)t.gid+=4294967296}if(o)o.apply(this,arguments)}return a?t.call(e,r,a,callback):t.call(e,r,callback)}}function statFixSync(t){if(!t)return t;return function(r,a){var o=a?t.call(e,r,a):t.call(e,r);if(o){if(o.uid<0)o.uid+=4294967296;if(o.gid<0)o.gid+=4294967296}return o}}function chownErOk(e){if(!e)return true;if(e.code==="ENOSYS")return true;var t=!process.getuid||process.getuid()!==0;if(t){if(e.code==="EINVAL"||e.code==="EPERM")return true}return false}}},7963:(e,t,r)=>{"use strict";var a=r(2037);var o=e.exports=function(){if(a.type()=="Windows_NT"){return false}var e=/UTF-?8$/i;var t=process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG;return e.test(t)}},6919:(e,t,r)=>{try{var a=r(3837);if(typeof a.inherits!=="function")throw"";e.exports=a.inherits}catch(t){e.exports=r(7526)}},7526:e=>{if(typeof Object.create==="function"){e.exports=function inherits(e,t){if(t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}}else{e.exports=function inherits(e,t){if(t){e.super_=t;var TempCtor=function(){};TempCtor.prototype=t.prototype;e.prototype=new TempCtor;e.prototype.constructor=e}}}},9842:e=>{var t={}.toString;e.exports=Array.isArray||function(e){return t.call(e)=="[object Array]"}},3277:(module,__unused_webpack_exports,__nccwpck_require__)=>{var fs=__nccwpck_require__(7147);var path=__nccwpck_require__(1017);var os=__nccwpck_require__(2037);var runtimeRequire=true?eval("require"):0;var vars=process.config&&process.config.variables||{};var prebuildsOnly=!!process.env.PREBUILDS_ONLY;var abi=process.versions.modules;var runtime=isElectron()?"electron":"node";var arch=os.arch();var platform=os.platform();var libc=process.env.LIBC||(isAlpine(platform)?"musl":"glibc");var armv=process.env.ARM_VERSION||(arch==="arm64"?"8":vars.arm_version)||"";var uv=(process.versions.uv||"").split(".")[0];module.exports=load;function load(e){return runtimeRequire(load.path(e))}load.path=function(e){e=path.resolve(e||".");try{var t=runtimeRequire(path.join(e,"package.json")).name.toUpperCase().replace(/-/g,"_");if(process.env[t+"_PREBUILD"])e=process.env[t+"_PREBUILD"]}catch(e){}if(!prebuildsOnly){var r=getFirst(path.join(e,"build/Release"),matchBuild);if(r)return r;var a=getFirst(path.join(e,"build/Debug"),matchBuild);if(a)return a}var o=resolve(e);if(o)return o;var s=resolve(path.dirname(process.execPath));if(s)return s;var u=["platform="+platform,"arch="+arch,"runtime="+runtime,"abi="+abi,"uv="+uv,armv?"armv="+armv:"","libc="+libc,"node="+process.versions.node,process.versions&&process.versions.electron?"electron="+process.versions.electron:"",true?"webpack=true":0].filter(Boolean).join(" ");throw new Error("No native build was found for "+u+"\n loaded from: "+e+"\n");function resolve(e){var t=path.join(e,"prebuilds",platform+"-"+arch);var r=readdirSync(t).map(parseTags);var a=r.filter(matchTags(runtime,abi));var o=a.sort(compareTags(runtime))[0];if(o)return path.join(t,o.file)}};function readdirSync(e){try{return fs.readdirSync(e)}catch(e){return[]}}function getFirst(e,t){var r=readdirSync(e).filter(t);return r[0]&&path.join(e,r[0])}function matchBuild(e){return/\.node$/.test(e)}function parseTags(e){var t=e.split(".");var r=t.pop();var a={file:e,specificity:0};if(r!=="node")return;for(var o=0;or.specificity?-1:1}else{return 0}}}function isElectron(){if(process.versions&&process.versions.electron)return true;if(process.env.ELECTRON_RUN_AS_NODE)return true;return typeof window!=="undefined"&&window.process&&window.process.type==="renderer"}function isAlpine(e){return e==="linux"&&fs.existsSync("/etc/alpine-release")}load.parseTags=parseTags;load.matchTags=matchTags;load.compareTags=compareTags},9248:(e,t,r)=>{"use strict";var a=r(7147);var o=r(3632);var s=r(9658);e.exports=t;var u=process.version.substr(1).replace(/-.*$/,"").split(".").map((function(e){return+e}));var c=["build","clean","configure","package","publish","reveal","testbinary","testpackage","unpublish"];var d="napi_build_version=";e.exports.get_napi_version=function(e){var t=process.versions.napi;if(!t){if(u[0]===9&&u[1]>=3)t=2;else if(u[0]===8)t=1}return t};e.exports.get_napi_version_as_string=function(t){var r=e.exports.get_napi_version(t);return r?""+r:""};e.exports.validate_package_json=function(t,r){var a=t.binary;var o=pathOK(a.module_path);var s=pathOK(a.remote_path);var u=pathOK(a.package_name);var c=e.exports.get_napi_build_versions(t,r,true);var d=e.exports.get_napi_build_versions_raw(t);if(c){c.forEach((function(e){if(!(parseInt(e,10)===e&&e>0)){throw new Error("All values specified in napi_versions must be positive integers.")}}))}if(c&&(!o||!s&&!u)){throw new Error("When napi_versions is specified; module_path and either remote_path or "+"package_name must contain the substitution string '{napi_build_version}`.")}if((o||s||u)&&!d){throw new Error("When the substitution string '{napi_build_version}` is specified in "+"module_path, remote_path, or package_name; napi_versions must also be specified.")}if(c&&!e.exports.get_best_napi_build_version(t,r)&&e.exports.build_napi_only(t)){throw new Error("The N-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports N-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}if(d&&!c&&e.exports.build_napi_only(t)){throw new Error("The N-API version of this Node instance is "+e.exports.get_napi_version(r?r.target:undefined)+". "+"This module supports N-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}};function pathOK(e){return e&&(e.indexOf("{napi_build_version}")!==-1||e.indexOf("{node_napi_label}")!==-1)}e.exports.expand_commands=function(t,r,a){var o=[];var s=e.exports.get_napi_build_versions(t,r);a.forEach((function(a){if(s&&a.name==="install"){var u=e.exports.get_best_napi_build_version(t,r);var f=u?[d+u]:[];o.push({name:a.name,args:f})}else if(s&&c.indexOf(a.name)!==-1){s.forEach((function(e){var t=a.args.slice();t.push(d+e);o.push({name:a.name,args:t})}))}else{o.push(a)}}));return o};e.exports.get_napi_build_versions=function(t,r,a){var o=[];var u=e.exports.get_napi_version(r?r.target:undefined);if(t.binary&&t.binary.napi_versions){t.binary.napi_versions.forEach((function(e){var t=o.indexOf(e)!==-1;if(!t&&u&&e<=u){o.push(e)}else if(a&&!t&&u){s.info("This Node instance does not support builds for N-API version",e)}}))}if(r&&r["build-latest-napi-version-only"]){var c=0;o.forEach((function(e){if(e>c)c=e}));o=c?[c]:[]}return o.length?o:undefined};e.exports.get_napi_build_versions_raw=function(e){var t=[];if(e.binary&&e.binary.napi_versions){e.binary.napi_versions.forEach((function(e){if(t.indexOf(e)===-1){t.push(e)}}))}return t.length?t:undefined};e.exports.get_command_arg=function(e){return d+e};e.exports.get_napi_build_version_from_command_args=function(e){for(var t=0;ta&&e<=s){a=e}}))}return a===0?undefined:a};e.exports.build_napi_only=function(e){return e.binary&&e.binary.package_name&&e.binary.package_name.indexOf("{node_napi_label}")===-1}},5574:(e,t,r)=>{"use strict";e.exports=t;var a=r(1017);var o=r(7849);var s=r(7310);var u=r(2157);var c=r(9248);var d;if(process.env.NODE_PRE_GYP_ABI_CROSSWALK){d=require(process.env.NODE_PRE_GYP_ABI_CROSSWALK)}else{d=r(7316)}var f={};Object.keys(d).forEach((function(e){var t=e.split(".")[0];if(!f[t]){f[t]=e}}));function get_electron_abi(e,t){if(!e){throw new Error("get_electron_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if electron is the target.")}var r=o.parse(t);return e+"-v"+r.major+"."+r.minor}e.exports.get_electron_abi=get_electron_abi;function get_node_webkit_abi(e,t){if(!e){throw new Error("get_node_webkit_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if node-webkit is the target.")}return e+"-v"+t}e.exports.get_node_webkit_abi=get_node_webkit_abi;function get_node_abi(e,t){if(!e){throw new Error("get_node_abi requires valid runtime arg")}if(!t){throw new Error("get_node_abi requires valid process.versions object")}var r=o.parse(t.node);if(r.major===0&&r.minor%2){return e+"-v"+t.node}else{return t.modules?e+"-v"+ +t.modules:"v8-"+t.v8.split(".").slice(0,2).join(".")}}e.exports.get_node_abi=get_node_abi;function get_runtime_abi(e,t){if(!e){throw new Error("get_runtime_abi requires valid runtime arg")}if(e==="node-webkit"){return get_node_webkit_abi(e,t||process.versions["node-webkit"])}else if(e==="electron"){return get_electron_abi(e,t||process.versions.electron)}else{if(e!="node"){throw new Error("Unknown Runtime: '"+e+"'")}if(!t){return get_node_abi(e,process.versions)}else{var r;if(d[t]){r=d[t]}else{var a=t.split(".").map((function(e){return+e}));if(a.length!=3){throw new Error("Unknown target version: "+t)}var o=a[0];var s=a[1];var u=a[2];if(o===1){while(true){if(s>0)--s;if(u>0)--u;var c=""+o+"."+s+"."+u;if(d[c]){r=d[c];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+c+" as ABI compatible target");break}if(s===0&&u===0){break}}}else if(o>=2){if(f[o]){r=d[f[o]];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+f[o]+" as ABI compatible target")}}else if(o===0){if(a[1]%2===0){while(--u>0){var p=""+o+"."+s+"."+u;if(d[p]){r=d[p];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+p+" as ABI compatible target");break}}}}}if(!r){throw new Error("Unsupported target version: "+t)}var h={node:t,v8:r.v8+".0",modules:r.node_abi>1?r.node_abi:undefined};return get_node_abi(e,h)}}}e.exports.get_runtime_abi=get_runtime_abi;var p=["module_name","module_path","host"];function validate_config(e,t){var r=e.name+" package.json is not node-pre-gyp ready:\n";var a=[];if(!e.main){a.push("main")}if(!e.version){a.push("version")}if(!e.name){a.push("name")}if(!e.binary){a.push("binary")}var o=e.binary;p.forEach((function(e){if(a.indexOf("binary")>-1){a.pop("binary")}if(!o||o[e]===undefined||o[e]===""){a.push("binary."+e)}}));if(a.length>=1){throw new Error(r+"package.json must declare these properties: \n"+a.join("\n"))}if(o){var u=s.parse(o.host).protocol;if(u==="http:"){throw new Error("'host' protocol ("+u+") is invalid - only 'https:' is accepted")}}c.validate_package_json(e,t)}e.exports.validate_config=validate_config;function eval_template(e,t){Object.keys(t).forEach((function(r){var a="{"+r+"}";while(e.indexOf(a)>-1){e=e.replace(a,t[r])}}));return e}function fix_slashes(e){if(e.slice(-1)!="/"){return e+"/"}return e}function drop_double_slashes(e){return e.replace(/\/\//g,"/")}function get_process_runtime(e){var t="node";if(e["node-webkit"]){t="node-webkit"}else if(e.electron){t="electron"}return t}e.exports.get_process_runtime=get_process_runtime;var h="{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz";var v="";e.exports.evaluate=function(e,t,r){t=t||{};validate_config(e,t);var d=e.version;var f=o.parse(d);var p=t.runtime||get_process_runtime(process.versions);var _={name:e.name,configuration:Boolean(t.debug)?"Debug":"Release",debug:t.debug,module_name:e.binary.module_name,version:f.version,prerelease:f.prerelease.length?f.prerelease.join("."):"",build:f.build.length?f.build.join("."):"",major:f.major,minor:f.minor,patch:f.patch,runtime:p,node_abi:get_runtime_abi(p,t.target),node_abi_napi:c.get_napi_version(t.target)?"napi":get_runtime_abi(p,t.target),napi_version:c.get_napi_version(t.target),napi_build_version:r||"",node_napi_label:r?"napi-v"+r:get_runtime_abi(p,t.target),target:t.target||"",platform:t.target_platform||process.platform,target_platform:t.target_platform||process.platform,arch:t.target_arch||process.arch,target_arch:t.target_arch||process.arch,libc:t.target_libc||u.family||"unknown",module_main:e.main,toolset:t.toolset||""};var g=process.env["npm_config_"+_.module_name+"_binary_host_mirror"]||e.binary.host;_.host=fix_slashes(eval_template(g,_));_.module_path=eval_template(e.binary.module_path,_);if(t.module_root){_.module_path=a.join(t.module_root,_.module_path)}else{_.module_path=a.resolve(_.module_path)}_.module=a.join(_.module_path,_.module_name+".node");_.remote_path=e.binary.remote_path?drop_double_slashes(fix_slashes(eval_template(e.binary.remote_path,_))):v;var y=e.binary.package_name?e.binary.package_name:h;_.package_name=eval_template(y,_);_.staged_tarball=a.join("build/stage",_.remote_path,_.package_name);_.hosted_path=s.resolve(_.host,_.remote_path);_.hosted_tarball=s.resolve(_.hosted_path,_.package_name);return _}},3632:(e,t,r)=>{e.exports=rimraf;rimraf.sync=rimrafSync;var a=r(9491);var o=r(1017);var s=r(7147);var u=undefined;try{u=r(3535)}catch(e){}var c=parseInt("666",8);var d={nosort:true,silent:true};var f=0;var p=process.platform==="win32";function defaults(e){var t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach((function(t){e[t]=e[t]||s[t];t=t+"Sync";e[t]=e[t]||s[t]}));e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&u===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||d}function rimraf(e,t,r){if(typeof t==="function"){r=t;t={}}a(e,"rimraf: missing path");a.equal(typeof e,"string","rimraf: path should be a string");a.equal(typeof r,"function","rimraf: callback function required");a(t,"rimraf: invalid options argument provided");a.equal(typeof t,"object","rimraf: options should be object");defaults(t);var o=0;var s=null;var c=0;if(t.disableGlob||!u.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,(function(r,a){if(!r)return afterGlob(null,[e]);u(e,t.glob,afterGlob)}));function next(e){s=s||e;if(--c===0)r(s)}function afterGlob(e,a){if(e)return r(e);c=a.length;if(c===0)return r();a.forEach((function(e){rimraf_(e,t,(function CB(r){if(r){if((r.code==="EBUSY"||r.code==="ENOTEMPTY"||r.code==="EPERM")&&o{"use strict";var a=r(2717);var o=r(6054);var s=r(2361).EventEmitter;var u=t=e.exports=new s;var c=r(3837);var d=r(8834);var f=r(6322);d(true);var p=process.stderr;Object.defineProperty(u,"stream",{set:function(e){p=e;if(this.gauge)this.gauge.setWriteTo(p,p)},get:function(){return p}});var h;u.useColor=function(){return h!=null?h:p.isTTY};u.enableColor=function(){h=true;this.gauge.setTheme({hasColor:h,hasUnicode:v})};u.disableColor=function(){h=false;this.gauge.setTheme({hasColor:h,hasUnicode:v})};u.level="info";u.gauge=new o(p,{enabled:false,theme:{hasColor:u.useColor()},template:[{type:"progressbar",length:20},{type:"activityIndicator",kerning:1,length:1},{type:"section",default:""},":",{type:"logline",kerning:1,default:""}]});u.tracker=new a.TrackerGroup;u.progressEnabled=u.gauge.isEnabled();var v;u.enableUnicode=function(){v=true;this.gauge.setTheme({hasColor:this.useColor(),hasUnicode:v})};u.disableUnicode=function(){v=false;this.gauge.setTheme({hasColor:this.useColor(),hasUnicode:v})};u.setGaugeThemeset=function(e){this.gauge.setThemeset(e)};u.setGaugeTemplate=function(e){this.gauge.setTemplate(e)};u.enableProgress=function(){if(this.progressEnabled)return;this.progressEnabled=true;this.tracker.on("change",this.showProgress);if(this._pause)return;this.gauge.enable()};u.disableProgress=function(){if(!this.progressEnabled)return;this.progressEnabled=false;this.tracker.removeListener("change",this.showProgress);this.gauge.disable()};var _=["newGroup","newItem","newStream"];var mixinLog=function(e){Object.keys(u).forEach((function(t){if(t[0]==="_")return;if(_.filter((function(e){return e===t})).length)return;if(e[t])return;if(typeof u[t]!=="function")return;var r=u[t];e[t]=function(){return r.apply(u,arguments)}}));if(e instanceof a.TrackerGroup){_.forEach((function(t){var r=e[t];e[t]=function(){return mixinLog(r.apply(e,arguments))}}))}return e};_.forEach((function(e){u[e]=function(){return mixinLog(this.tracker[e].apply(this.tracker,arguments))}}));u.clearProgress=function(e){if(!this.progressEnabled)return e&&process.nextTick(e);this.gauge.hide(e)};u.showProgress=function(e,t){if(!this.progressEnabled)return;var r={};if(e)r.section=e;var a=u.record[u.record.length-1];if(a){r.subsection=a.prefix;var o=u.disp[a.level]||a.level;var s=this._format(o,u.style[a.level]);if(a.prefix)s+=" "+this._format(a.prefix,this.prefixStyle);s+=" "+a.message.split(/\r?\n/)[0];r.logline=s}r.completed=t||this.tracker.completed();this.gauge.show(r)}.bind(u);u.pause=function(){this._paused=true;if(this.progressEnabled)this.gauge.disable()};u.resume=function(){if(!this._paused)return;this._paused=false;var e=this._buffer;this._buffer=[];e.forEach((function(e){this.emitLog(e)}),this);if(this.progressEnabled)this.gauge.enable()};u._buffer=[];var g=0;u.record=[];u.maxRecordSize=1e4;u.log=function(e,t,r){var a=this.levels[e];if(a===undefined){return this.emit("error",new Error(c.format("Undefined log level: %j",e)))}var o=new Array(arguments.length-2);var s=null;for(var u=2;up/10){var v=Math.floor(p*.9);this.record=this.record.slice(-1*v)}this.emitLog(f)}.bind(u);u.emitLog=function(e){if(this._paused){this._buffer.push(e);return}if(this.progressEnabled)this.gauge.pulse(e.prefix);var t=this.levels[e.level];if(t===undefined)return;if(t0&&!isFinite(t))return;var r=u.disp[e.level]!=null?u.disp[e.level]:e.level;this.clearProgress();e.message.split(/\r?\n/).forEach((function(t){if(this.heading){this.write(this.heading,this.headingStyle);this.write(" ")}this.write(r,u.style[e.level]);var a=e.prefix||"";if(a)this.write(" ");this.write(a,this.prefixStyle);this.write(" "+t+"\n")}),this);this.showProgress()};u._format=function(e,t){if(!p)return;var r="";if(this.useColor()){t=t||{};var a=[];if(t.fg)a.push(t.fg);if(t.bg)a.push("bg"+t.bg[0].toUpperCase()+t.bg.slice(1));if(t.bold)a.push("bold");if(t.underline)a.push("underline");if(t.inverse)a.push("inverse");if(a.length)r+=f.color(a);if(t.beep)r+=f.beep()}r+=e;if(this.useColor()){r+=f.color("reset")}return r};u.write=function(e,t){if(!p)return;p.write(this._format(e,t))};u.addLevel=function(e,t,r,a){if(a==null)a=e;this.levels[e]=t;this.style[e]=r;if(!this[e]){this[e]=function(){var t=new Array(arguments.length+1);t[0]=e;for(var r=0;r{"use strict";e.exports=Number.isNaN||function(e){return e!==e}},1800:e=>{"use strict"; /* object-assign (c) Sindre Sorhus @license MIT -*/var t=Object.getOwnPropertySymbols;var r=Object.prototype.hasOwnProperty;var s=Object.prototype.propertyIsEnumerable;function toObject(e){if(e===null||e===undefined){throw new TypeError("Object.assign cannot be called with null or undefined")}return Object(e)}function shouldUseNative(){try{if(!Object.assign){return false}var e=new String("abc");e[5]="de";if(Object.getOwnPropertyNames(e)[0]==="5"){return false}var t={};for(var r=0;r<10;r++){t["_"+String.fromCharCode(r)]=r}var s=Object.getOwnPropertyNames(t).map((function(e){return t[e]}));if(s.join("")!=="0123456789"){return false}var a={};"abcdefghijklmnopqrst".split("").forEach((function(e){a[e]=e}));if(Object.keys(Object.assign({},a)).join("")!=="abcdefghijklmnopqrst"){return false}return true}catch(e){return false}}e.exports=shouldUseNative()?Object.assign:function(e,a){var o;var u=toObject(e);var c;for(var f=1;f{"use strict";if(typeof process==="undefined"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){e.exports={nextTick:nextTick}}else{e.exports=process}function nextTick(e,t,r,s){if(typeof e!=="function"){throw new TypeError('"callback" argument must be a function')}var a=arguments.length;var o,u;switch(a){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick((function afterTickOne(){e.call(null,t)}));case 3:return process.nextTick((function afterTickTwo(){e.call(null,t,r)}));case 4:return process.nextTick((function afterTickThree(){e.call(null,t,r,s)}));default:o=new Array(a-1);u=0;while(u{"use strict";var s=r(7843);var a=Object.keys||function(e){var t=[];for(var r in e){t.push(r)}return t};e.exports=Duplex;var o=Object.create(r(3487));o.inherits=r(6919);var u=r(284);var c=r(6100);o.inherits(Duplex,u);{var f=a(c.prototype);for(var p=0;p{"use strict";e.exports=PassThrough;var s=r(5469);var a=Object.create(r(3487));a.inherits=r(6919);a.inherits(PassThrough,s);function PassThrough(e){if(!(this instanceof PassThrough))return new PassThrough(e);s.call(this,e)}PassThrough.prototype._transform=function(e,t,r){r(null,e)}},284:(e,t,r)=>{"use strict";var s=r(7843);e.exports=Readable;var a=r(9842);var o;Readable.ReadableState=ReadableState;var u=r(2361).EventEmitter;var EElistenerCount=function(e,t){return e.listeners(t).length};var c=r(5016);var f=r(4810).Buffer;var p=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return f.from(e)}function _isUint8Array(e){return f.isBuffer(e)||e instanceof p}var d=Object.create(r(3487));d.inherits=r(6919);var h=r(3837);var v=void 0;if(h&&h.debuglog){v=h.debuglog("stream")}else{v=function(){}}var g=r(8739);var m=r(3090);var _;d.inherits(Readable,c);var y=["error","close","destroy","pause","resume"];function prependListener(e,t,r){if(typeof e.prependListener==="function")return e.prependListener(t,r);if(!e._events||!e._events[t])e.on(t,r);else if(a(e._events[t]))e._events[t].unshift(r);else e._events[t]=[r,e._events[t]]}function ReadableState(e,t){o=o||r(8393);e=e||{};var s=t instanceof o;this.objectMode=!!e.objectMode;if(s)this.objectMode=this.objectMode||!!e.readableObjectMode;var a=e.highWaterMark;var u=e.readableHighWaterMark;var c=this.objectMode?16:16*1024;if(a||a===0)this.highWaterMark=a;else if(s&&(u||u===0))this.highWaterMark=u;else this.highWaterMark=c;this.highWaterMark=Math.floor(this.highWaterMark);this.buffer=new g;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.destroyed=false;this.defaultEncoding=e.defaultEncoding||"utf8";this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(e.encoding){if(!_)_=r(6224).s;this.decoder=new _(e.encoding);this.encoding=e.encoding}}function Readable(e){o=o||r(8393);if(!(this instanceof Readable))return new Readable(e);this._readableState=new ReadableState(e,this);this.readable=true;if(e){if(typeof e.read==="function")this._read=e.read;if(typeof e.destroy==="function")this._destroy=e.destroy}c.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{get:function(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function(e){if(!this._readableState){return}this._readableState.destroyed=e}});Readable.prototype.destroy=m.destroy;Readable.prototype._undestroy=m.undestroy;Readable.prototype._destroy=function(e,t){this.push(null);t(e)};Readable.prototype.push=function(e,t){var r=this._readableState;var s;if(!r.objectMode){if(typeof e==="string"){t=t||r.defaultEncoding;if(t!==r.encoding){e=f.from(e,t);t=""}s=true}}else{s=true}return readableAddChunk(this,e,t,false,s)};Readable.prototype.unshift=function(e){return readableAddChunk(this,e,null,true,false)};function readableAddChunk(e,t,r,s,a){var o=e._readableState;if(t===null){o.reading=false;onEofChunk(e,o)}else{var u;if(!a)u=chunkInvalid(o,t);if(u){e.emit("error",u)}else if(o.objectMode||t&&t.length>0){if(typeof t!=="string"&&!o.objectMode&&Object.getPrototypeOf(t)!==f.prototype){t=_uint8ArrayToBuffer(t)}if(s){if(o.endEmitted)e.emit("error",new Error("stream.unshift() after end event"));else addChunk(e,o,t,true)}else if(o.ended){e.emit("error",new Error("stream.push() after EOF"))}else{o.reading=false;if(o.decoder&&!r){t=o.decoder.write(t);if(o.objectMode||t.length!==0)addChunk(e,o,t,false);else maybeReadMore(e,o)}else{addChunk(e,o,t,false)}}}else if(!s){o.reading=false}}return needMoreData(o)}function addChunk(e,t,r,s){if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(s)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)emitReadable(e)}maybeReadMore(e,t)}function chunkInvalid(e,t){var r;if(!_isUint8Array(t)&&typeof t!=="string"&&t!==undefined&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function needMoreData(e){return!e.ended&&(e.needReadable||e.length=x){e=x}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function howMuchToRead(e,t){if(e<=0||t.length===0&&t.ended)return 0;if(t.objectMode)return 1;if(e!==e){if(t.flowing&&t.length)return t.buffer.head.data.length;else return t.length}if(e>t.highWaterMark)t.highWaterMark=computeNewHighWaterMark(e);if(e<=t.length)return e;if(!t.ended){t.needReadable=true;return 0}return t.length}Readable.prototype.read=function(e){v("read",e);e=parseInt(e,10);var t=this._readableState;var r=e;if(e!==0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){v("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)endReadable(this);else emitReadable(this);return null}e=howMuchToRead(e,t);if(e===0&&t.ended){if(t.length===0)endReadable(this);return null}var s=t.needReadable;v("need readable",s);if(t.length===0||t.length-e0)a=fromList(e,t);else a=null;if(a===null){t.needReadable=true;e=0}else{t.length-=e}if(t.length===0){if(!t.ended)t.needReadable=true;if(r!==e&&t.ended)endReadable(this)}if(a!==null)this.emit("data",a);return a};function onEofChunk(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;emitReadable(e)}function emitReadable(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){v("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)s.nextTick(emitReadable_,e);else emitReadable_(e)}}function emitReadable_(e){v("emit readable");e.emit("readable");flow(e)}function maybeReadMore(e,t){if(!t.readingMore){t.readingMore=true;s.nextTick(maybeReadMore_,e,t)}}function maybeReadMore_(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length1&&indexOf(a.pipes,e)!==-1)&&!f){v("false write response, pause",r._readableState.awaitDrain);r._readableState.awaitDrain++;p=true}r.pause()}}function onerror(t){v("onerror",t);unpipe();e.removeListener("error",onerror);if(EElistenerCount(e,"error")===0)e.emit("error",t)}prependListener(e,"error",onerror);function onclose(){e.removeListener("finish",onfinish);unpipe()}e.once("close",onclose);function onfinish(){v("onfinish");e.removeListener("close",onclose);unpipe()}e.once("finish",onfinish);function unpipe(){v("unpipe");r.unpipe(e)}e.emit("pipe",r);if(!a.flowing){v("pipe resume");r.resume()}return e};function pipeOnDrain(e){return function(){var t=e._readableState;v("pipeOnDrain",t.awaitDrain);if(t.awaitDrain)t.awaitDrain--;if(t.awaitDrain===0&&EElistenerCount(e,"data")){t.flowing=true;flow(e)}}}Readable.prototype.unpipe=function(e){var t=this._readableState;var r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1){if(e&&e!==t.pipes)return this;if(!e)e=t.pipes;t.pipes=null;t.pipesCount=0;t.flowing=false;if(e)e.emit("unpipe",this,r);return this}if(!e){var s=t.pipes;var a=t.pipesCount;t.pipes=null;t.pipesCount=0;t.flowing=false;for(var o=0;o=t.length){if(t.decoder)r=t.buffer.join("");else if(t.buffer.length===1)r=t.buffer.head.data;else r=t.buffer.concat(t.length);t.buffer.clear()}else{r=fromListPartial(e,t.buffer,t.decoder)}return r}function fromListPartial(e,t,r){var s;if(eo.length?o.length:e;if(u===o.length)a+=o;else a+=o.slice(0,e);e-=u;if(e===0){if(u===o.length){++s;if(r.next)t.head=r.next;else t.head=t.tail=null}else{t.head=r;r.data=o.slice(u)}break}++s}t.length-=s;return a}function copyFromBuffer(e,t){var r=f.allocUnsafe(e);var s=t.head;var a=1;s.data.copy(r);e-=s.data.length;while(s=s.next){var o=s.data;var u=e>o.length?o.length:e;o.copy(r,r.length-e,0,u);e-=u;if(e===0){if(u===o.length){++a;if(s.next)t.head=s.next;else t.head=t.tail=null}else{t.head=s;s.data=o.slice(u)}break}++a}t.length-=a;return r}function endReadable(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!t.endEmitted){t.ended=true;s.nextTick(endReadableNT,t,e)}}function endReadableNT(e,t){if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end")}}function indexOf(e,t){for(var r=0,s=e.length;r{"use strict";e.exports=Transform;var s=r(8393);var a=Object.create(r(3487));a.inherits=r(6919);a.inherits(Transform,s);function afterTransform(e,t){var r=this._transformState;r.transforming=false;var s=r.writecb;if(!s){return this.emit("error",new Error("write callback called multiple times"))}r.writechunk=null;r.writecb=null;if(t!=null)this.push(t);s(e);var a=this._readableState;a.reading=false;if(a.needReadable||a.length{"use strict";var s=r(7843);e.exports=Writable;function WriteReq(e,t,r){this.chunk=e;this.encoding=t;this.callback=r;this.next=null}function CorkedRequest(e){var t=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(t,e)}}var a=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:s.nextTick;var o;Writable.WritableState=WritableState;var u=Object.create(r(3487));u.inherits=r(6919);var c={deprecate:r(9209)};var f=r(5016);var p=r(4810).Buffer;var d=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return p.from(e)}function _isUint8Array(e){return p.isBuffer(e)||e instanceof d}var h=r(3090);u.inherits(Writable,f);function nop(){}function WritableState(e,t){o=o||r(8393);e=e||{};var s=t instanceof o;this.objectMode=!!e.objectMode;if(s)this.objectMode=this.objectMode||!!e.writableObjectMode;var a=e.highWaterMark;var u=e.writableHighWaterMark;var c=this.objectMode?16:16*1024;if(a||a===0)this.highWaterMark=a;else if(s&&(u||u===0))this.highWaterMark=u;else this.highWaterMark=c;this.highWaterMark=Math.floor(this.highWaterMark);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;var f=e.decodeStrings===false;this.decodeStrings=!f;this.defaultEncoding=e.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(e){onwrite(t,e)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var e=this.bufferedRequest;var t=[];while(e){t.push(e);e=e.next}return t};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:c.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}catch(e){}})();var v;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){v=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(e){if(v.call(this,e))return true;if(this!==Writable)return false;return e&&e._writableState instanceof WritableState}})}else{v=function(e){return e instanceof this}}function Writable(e){o=o||r(8393);if(!v.call(Writable,this)&&!(this instanceof o)){return new Writable(e)}this._writableState=new WritableState(e,this);this.writable=true;if(e){if(typeof e.write==="function")this._write=e.write;if(typeof e.writev==="function")this._writev=e.writev;if(typeof e.destroy==="function")this._destroy=e.destroy;if(typeof e.final==="function")this._final=e.final}f.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(e,t){var r=new Error("write after end");e.emit("error",r);s.nextTick(t,r)}function validChunk(e,t,r,a){var o=true;var u=false;if(r===null){u=new TypeError("May not write null values to stream")}else if(typeof r!=="string"&&r!==undefined&&!t.objectMode){u=new TypeError("Invalid non-string/buffer chunk")}if(u){e.emit("error",u);s.nextTick(a,u);o=false}return o}Writable.prototype.write=function(e,t,r){var s=this._writableState;var a=false;var o=!s.objectMode&&_isUint8Array(e);if(o&&!p.isBuffer(e)){e=_uint8ArrayToBuffer(e)}if(typeof t==="function"){r=t;t=null}if(o)t="buffer";else if(!t)t=s.defaultEncoding;if(typeof r!=="function")r=nop;if(s.ended)writeAfterEnd(this,r);else if(o||validChunk(this,s,e,r)){s.pendingcb++;a=writeOrBuffer(this,s,o,e,t,r)}return a};Writable.prototype.cork=function(){var e=this._writableState;e.corked++};Writable.prototype.uncork=function(){var e=this._writableState;if(e.corked){e.corked--;if(!e.writing&&!e.corked&&!e.finished&&!e.bufferProcessing&&e.bufferedRequest)clearBuffer(this,e)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(e){if(typeof e==="string")e=e.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e;return this};function decodeChunk(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=p.from(t,r)}return t}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function writeOrBuffer(e,t,r,s,a,o){if(!r){var u=decodeChunk(t,s,a);if(s!==u){r=true;a="buffer";s=u}}var c=t.objectMode?1:s.length;t.length+=c;var f=t.length{"use strict";function _classCallCheck(e,t){if(!(e instanceof t)){throw new TypeError("Cannot call a class as a function")}}var s=r(4810).Buffer;var a=r(3837);function copyBuffer(e,t,r){e.copy(t,r)}e.exports=function(){function BufferList(){_classCallCheck(this,BufferList);this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function push(e){var t={data:e,next:null};if(this.length>0)this.tail.next=t;else this.head=t;this.tail=t;++this.length};BufferList.prototype.unshift=function unshift(e){var t={data:e,next:this.head};if(this.length===0)this.tail=t;this.head=t;++this.length};BufferList.prototype.shift=function shift(){if(this.length===0)return;var e=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return e};BufferList.prototype.clear=function clear(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function join(e){if(this.length===0)return"";var t=this.head;var r=""+t.data;while(t=t.next){r+=e+t.data}return r};BufferList.prototype.concat=function concat(e){if(this.length===0)return s.alloc(0);if(this.length===1)return this.head.data;var t=s.allocUnsafe(e>>>0);var r=this.head;var a=0;while(r){copyBuffer(r.data,t,a);a+=r.data.length;r=r.next}return t};return BufferList}();if(a&&a.inspect&&a.inspect.custom){e.exports.prototype[a.inspect.custom]=function(){var e=a.inspect({length:this.length});return this.constructor.name+" "+e}}},3090:(e,t,r)=>{"use strict";var s=r(7843);function destroy(e,t){var r=this;var a=this._readableState&&this._readableState.destroyed;var o=this._writableState&&this._writableState.destroyed;if(a||o){if(t){t(e)}else if(e&&(!this._writableState||!this._writableState.errorEmitted)){s.nextTick(emitErrorNT,this,e)}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(e||null,(function(e){if(!t&&e){s.nextTick(emitErrorNT,r,e);if(r._writableState){r._writableState.errorEmitted=true}}else if(t){t(e)}}));return this}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(e,t){e.emit("error",t)}e.exports={destroy:destroy,undestroy:undestroy}},5016:(e,t,r)=>{e.exports=r(2781)},4810:(e,t,r)=>{var s=r(4300);var a=s.Buffer;function copyProps(e,t){for(var r in e){t[r]=e[r]}}if(a.from&&a.alloc&&a.allocUnsafe&&a.allocUnsafeSlow){e.exports=s}else{copyProps(s,t);t.Buffer=SafeBuffer}function SafeBuffer(e,t,r){return a(e,t,r)}copyProps(a,SafeBuffer);SafeBuffer.from=function(e,t,r){if(typeof e==="number"){throw new TypeError("Argument must not be a number")}return a(e,t,r)};SafeBuffer.alloc=function(e,t,r){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}var s=a(e);if(t!==undefined){if(typeof r==="string"){s.fill(t,r)}else{s.fill(t)}}else{s.fill(0)}return s};SafeBuffer.allocUnsafe=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return a(e)};SafeBuffer.allocUnsafeSlow=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return s.SlowBuffer(e)}},6224:(e,t,r)=>{"use strict";var s=r(4810).Buffer;var a=s.isEncoding||function(e){e=""+e;switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function _normalizeEncoding(e){if(!e)return"utf8";var t;while(true){switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase();t=true}}}function normalizeEncoding(e){var t=_normalizeEncoding(e);if(typeof t!=="string"&&(s.isEncoding===a||!a(e)))throw new Error("Unknown encoding: "+e);return t||e}t.s=StringDecoder;function StringDecoder(e){this.encoding=normalizeEncoding(e);var t;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;t=4;break;case"utf8":this.fillLast=utf8FillLast;t=4;break;case"base64":this.text=base64Text;this.end=base64End;t=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=s.allocUnsafe(t)}StringDecoder.prototype.write=function(e){if(e.length===0)return"";var t;var r;if(this.lastNeed){t=this.fillLast(e);if(t===undefined)return"";r=this.lastNeed;this.lastNeed=0}else{r=0}if(r>5===6)return 2;else if(e>>4===14)return 3;else if(e>>3===30)return 4;return e>>6===2?-1:-2}function utf8CheckIncomplete(e,t,r){var s=t.length-1;if(s=0){if(a>0)e.lastNeed=a-1;return a}if(--s=0){if(a>0)e.lastNeed=a-2;return a}if(--s=0){if(a>0){if(a===2)a=0;else e.lastNeed=a-3}return a}return 0}function utf8CheckExtraBytes(e,t,r){if((t[0]&192)!==128){e.lastNeed=0;return"�"}if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128){e.lastNeed=1;return"�"}if(e.lastNeed>2&&t.length>2){if((t[2]&192)!==128){e.lastNeed=2;return"�"}}}}function utf8FillLast(e){var t=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,e,t);if(r!==undefined)return r;if(this.lastNeed<=e.length){e.copy(this.lastChar,t,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}e.copy(this.lastChar,t,0,e.length);this.lastNeed-=e.length}function utf8Text(e,t){var r=utf8CheckIncomplete(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var s=e.length-(r-this.lastNeed);e.copy(this.lastChar,0,s);return e.toString("utf8",t,s)}function utf8End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+"�";return t}function utf16Text(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var s=r.charCodeAt(r.length-1);if(s>=55296&&s<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=e[e.length-1];return e.toString("utf16le",t,e.length-1)}function utf16End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function base64Text(e,t){var r=(e.length-t)%3;if(r===0)return e.toString("base64",t);this.lastNeed=3-r;this.lastTotal=3;if(r===1){this.lastChar[0]=e[e.length-1]}else{this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1]}return e.toString("base64",t,e.length-r)}function base64End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+this.lastChar.toString("base64",0,3-this.lastNeed);return t}function simpleWrite(e){return e.toString(this.encoding)}function simpleEnd(e){return e&&e.length?this.write(e):""}},675:(e,t,r)=>{var s=r(2781);if(process.env.READABLE_STREAM==="disable"&&s){e.exports=s;t=e.exports=s.Readable;t.Readable=s.Readable;t.Writable=s.Writable;t.Duplex=s.Duplex;t.Transform=s.Transform;t.PassThrough=s.PassThrough;t.Stream=s}else{t=e.exports=r(284);t.Stream=s||t;t.Readable=t;t.Writable=r(6100);t.Duplex=r(8393);t.Transform=r(5469);t.PassThrough=r(5125)}},2753:(e,t,r)=>{"use strict";const s=r(1017);const a=r(8188);const o=r(7147);const resolveFrom=(e,t,r)=>{if(typeof e!=="string"){throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof e}\``)}if(typeof t!=="string"){throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof t}\``)}try{e=o.realpathSync(e)}catch(t){if(t.code==="ENOENT"){e=s.resolve(e)}else if(r){return}else{throw t}}const u=s.join(e,"noop.js");const resolveFileName=()=>a._resolveFilename(t,{id:u,filename:u,paths:a._nodeModulePaths(e)});if(r){try{return resolveFileName()}catch(e){return}}return resolveFileName()};e.exports=(e,t)=>resolveFrom(e,t);e.exports.silent=(e,t)=>resolveFrom(e,t,true)},7586:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});function _interopDefault(e){return e&&typeof e==="object"&&"default"in e?e["default"]:e}var s=r(1017);var a=_interopDefault(s);var o=r(619);var u=_interopDefault(r(3837));const c=function addExtension(e,t=".js"){if(!s.extname(e))e+=t;return e};const f={ArrayPattern(e,t){for(const r of t.elements){if(r)f[r.type](e,r)}},AssignmentPattern(e,t){f[t.left.type](e,t.left)},Identifier(e,t){e.push(t.name)},MemberExpression(){},ObjectPattern(e,t){for(const r of t.properties){if(r.type==="RestElement"){f.RestElement(e,r)}else{f[r.value.type](e,r.value)}}},RestElement(e,t){f[t.argument.type](e,t.argument)}};const p=function extractAssignedNames(e){const t=[];f[e.type](t,e);return t};const d={const:true,let:true};class Scope{constructor(e={}){this.parent=e.parent;this.isBlockScope=!!e.block;this.declarations=Object.create(null);if(e.params){e.params.forEach((e=>{p(e).forEach((e=>{this.declarations[e]=true}))}))}}addDeclaration(e,t,r){if(!t&&this.isBlockScope){this.parent.addDeclaration(e,t,r)}else if(e.id){p(e.id).forEach((e=>{this.declarations[e]=true}))}}contains(e){return this.declarations[e]||(this.parent?this.parent.contains(e):false)}}const h=function attachScopes(e,t="scope"){let r=new Scope;o.walk(e,{enter(e,s){if(/(Function|Class)Declaration/.test(e.type)){r.addDeclaration(e,false,false)}if(e.type==="VariableDeclaration"){const t=e.kind;const s=d[t];e.declarations.forEach((e=>{r.addDeclaration(e,s,true)}))}let a;if(/Function/.test(e.type)){a=new Scope({parent:r,block:false,params:e.params});if(e.type==="FunctionExpression"&&e.id){a.addDeclaration(e,false,false)}}if(e.type==="BlockStatement"&&!/Function/.test(s.type)){a=new Scope({parent:r,block:true})}if(e.type==="CatchClause"){a=new Scope({parent:r,params:e.param?[e.param]:[],block:true})}if(a){Object.defineProperty(e,t,{value:a,configurable:true});r=a}},leave(e){if(e[t])r=r.parent}});return r};function createCommonjsModule(e,t){return t={exports:{}},e(t,t.exports),t.exports}var v=createCommonjsModule((function(e,t){t.isInteger=e=>{if(typeof e==="number"){return Number.isInteger(e)}if(typeof e==="string"&&e.trim()!==""){return Number.isInteger(Number(e))}return false};t.find=(e,t)=>e.nodes.find((e=>e.type===t));t.exceedsLimit=(e,r,s=1,a)=>{if(a===false)return false;if(!t.isInteger(e)||!t.isInteger(r))return false;return(Number(r)-Number(e))/Number(s)>=a};t.escapeNode=(e,t=0,r)=>{let s=e.nodes[t];if(!s)return;if(r&&s.type===r||s.type==="open"||s.type==="close"){if(s.escaped!==true){s.value="\\"+s.value;s.escaped=true}}};t.encloseBrace=e=>{if(e.type!=="brace")return false;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}return false};t.isInvalidBrace=e=>{if(e.type!=="brace")return false;if(e.invalid===true||e.dollar)return true;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}if(e.open!==true||e.close!==true){e.invalid=true;return true}return false};t.isOpenOrClose=e=>{if(e.type==="open"||e.type==="close"){return true}return e.open===true||e.close===true};t.reduce=e=>e.reduce(((e,t)=>{if(t.type==="text")e.push(t.value);if(t.type==="range")t.type="text";return e}),[]);t.flatten=(...e)=>{const t=[];const flat=e=>{for(let r=0;r{let stringify=(e,r={})=>{let s=t.escapeInvalid&&v.isInvalidBrace(r);let a=e.invalid===true&&t.escapeInvalid===true;let o="";if(e.value){if((s||a)&&v.isOpenOrClose(e)){return"\\"+e.value}return e.value}if(e.value){return e.value}if(e.nodes){for(let t of e.nodes){o+=stringify(t)}}return o};return stringify(e)}; +*/var t=Object.getOwnPropertySymbols;var r=Object.prototype.hasOwnProperty;var a=Object.prototype.propertyIsEnumerable;function toObject(e){if(e===null||e===undefined){throw new TypeError("Object.assign cannot be called with null or undefined")}return Object(e)}function shouldUseNative(){try{if(!Object.assign){return false}var e=new String("abc");e[5]="de";if(Object.getOwnPropertyNames(e)[0]==="5"){return false}var t={};for(var r=0;r<10;r++){t["_"+String.fromCharCode(r)]=r}var a=Object.getOwnPropertyNames(t).map((function(e){return t[e]}));if(a.join("")!=="0123456789"){return false}var o={};"abcdefghijklmnopqrst".split("").forEach((function(e){o[e]=e}));if(Object.keys(Object.assign({},o)).join("")!=="abcdefghijklmnopqrst"){return false}return true}catch(e){return false}}e.exports=shouldUseNative()?Object.assign:function(e,o){var s;var u=toObject(e);var c;for(var d=1;d{"use strict";if(typeof process==="undefined"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){e.exports={nextTick:nextTick}}else{e.exports=process}function nextTick(e,t,r,a){if(typeof e!=="function"){throw new TypeError('"callback" argument must be a function')}var o=arguments.length;var s,u;switch(o){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick((function afterTickOne(){e.call(null,t)}));case 3:return process.nextTick((function afterTickTwo(){e.call(null,t,r)}));case 4:return process.nextTick((function afterTickThree(){e.call(null,t,r,a)}));default:s=new Array(o-1);u=0;while(u{"use strict";var a=r(7843);var o=Object.keys||function(e){var t=[];for(var r in e){t.push(r)}return t};e.exports=Duplex;var s=Object.create(r(3487));s.inherits=r(6919);var u=r(284);var c=r(6100);s.inherits(Duplex,u);{var d=o(c.prototype);for(var f=0;f{"use strict";e.exports=PassThrough;var a=r(5469);var o=Object.create(r(3487));o.inherits=r(6919);o.inherits(PassThrough,a);function PassThrough(e){if(!(this instanceof PassThrough))return new PassThrough(e);a.call(this,e)}PassThrough.prototype._transform=function(e,t,r){r(null,e)}},284:(e,t,r)=>{"use strict";var a=r(7843);e.exports=Readable;var o=r(9842);var s;Readable.ReadableState=ReadableState;var u=r(2361).EventEmitter;var EElistenerCount=function(e,t){return e.listeners(t).length};var c=r(5016);var d=r(4810).Buffer;var f=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return d.from(e)}function _isUint8Array(e){return d.isBuffer(e)||e instanceof f}var p=Object.create(r(3487));p.inherits=r(6919);var h=r(3837);var v=void 0;if(h&&h.debuglog){v=h.debuglog("stream")}else{v=function(){}}var _=r(8739);var g=r(3090);var y;p.inherits(Readable,c);var m=["error","close","destroy","pause","resume"];function prependListener(e,t,r){if(typeof e.prependListener==="function")return e.prependListener(t,r);if(!e._events||!e._events[t])e.on(t,r);else if(o(e._events[t]))e._events[t].unshift(r);else e._events[t]=[r,e._events[t]]}function ReadableState(e,t){s=s||r(8393);e=e||{};var a=t instanceof s;this.objectMode=!!e.objectMode;if(a)this.objectMode=this.objectMode||!!e.readableObjectMode;var o=e.highWaterMark;var u=e.readableHighWaterMark;var c=this.objectMode?16:16*1024;if(o||o===0)this.highWaterMark=o;else if(a&&(u||u===0))this.highWaterMark=u;else this.highWaterMark=c;this.highWaterMark=Math.floor(this.highWaterMark);this.buffer=new _;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.destroyed=false;this.defaultEncoding=e.defaultEncoding||"utf8";this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(e.encoding){if(!y)y=r(6224).s;this.decoder=new y(e.encoding);this.encoding=e.encoding}}function Readable(e){s=s||r(8393);if(!(this instanceof Readable))return new Readable(e);this._readableState=new ReadableState(e,this);this.readable=true;if(e){if(typeof e.read==="function")this._read=e.read;if(typeof e.destroy==="function")this._destroy=e.destroy}c.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{get:function(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function(e){if(!this._readableState){return}this._readableState.destroyed=e}});Readable.prototype.destroy=g.destroy;Readable.prototype._undestroy=g.undestroy;Readable.prototype._destroy=function(e,t){this.push(null);t(e)};Readable.prototype.push=function(e,t){var r=this._readableState;var a;if(!r.objectMode){if(typeof e==="string"){t=t||r.defaultEncoding;if(t!==r.encoding){e=d.from(e,t);t=""}a=true}}else{a=true}return readableAddChunk(this,e,t,false,a)};Readable.prototype.unshift=function(e){return readableAddChunk(this,e,null,true,false)};function readableAddChunk(e,t,r,a,o){var s=e._readableState;if(t===null){s.reading=false;onEofChunk(e,s)}else{var u;if(!o)u=chunkInvalid(s,t);if(u){e.emit("error",u)}else if(s.objectMode||t&&t.length>0){if(typeof t!=="string"&&!s.objectMode&&Object.getPrototypeOf(t)!==d.prototype){t=_uint8ArrayToBuffer(t)}if(a){if(s.endEmitted)e.emit("error",new Error("stream.unshift() after end event"));else addChunk(e,s,t,true)}else if(s.ended){e.emit("error",new Error("stream.push() after EOF"))}else{s.reading=false;if(s.decoder&&!r){t=s.decoder.write(t);if(s.objectMode||t.length!==0)addChunk(e,s,t,false);else maybeReadMore(e,s)}else{addChunk(e,s,t,false)}}}else if(!a){s.reading=false}}return needMoreData(s)}function addChunk(e,t,r,a){if(t.flowing&&t.length===0&&!t.sync){e.emit("data",r);e.read(0)}else{t.length+=t.objectMode?1:r.length;if(a)t.buffer.unshift(r);else t.buffer.push(r);if(t.needReadable)emitReadable(e)}maybeReadMore(e,t)}function chunkInvalid(e,t){var r;if(!_isUint8Array(t)&&typeof t!=="string"&&t!==undefined&&!e.objectMode){r=new TypeError("Invalid non-string/buffer chunk")}return r}function needMoreData(e){return!e.ended&&(e.needReadable||e.length=w){e=w}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function howMuchToRead(e,t){if(e<=0||t.length===0&&t.ended)return 0;if(t.objectMode)return 1;if(e!==e){if(t.flowing&&t.length)return t.buffer.head.data.length;else return t.length}if(e>t.highWaterMark)t.highWaterMark=computeNewHighWaterMark(e);if(e<=t.length)return e;if(!t.ended){t.needReadable=true;return 0}return t.length}Readable.prototype.read=function(e){v("read",e);e=parseInt(e,10);var t=this._readableState;var r=e;if(e!==0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){v("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)endReadable(this);else emitReadable(this);return null}e=howMuchToRead(e,t);if(e===0&&t.ended){if(t.length===0)endReadable(this);return null}var a=t.needReadable;v("need readable",a);if(t.length===0||t.length-e0)o=fromList(e,t);else o=null;if(o===null){t.needReadable=true;e=0}else{t.length-=e}if(t.length===0){if(!t.ended)t.needReadable=true;if(r!==e&&t.ended)endReadable(this)}if(o!==null)this.emit("data",o);return o};function onEofChunk(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();if(r&&r.length){t.buffer.push(r);t.length+=t.objectMode?1:r.length}}t.ended=true;emitReadable(e)}function emitReadable(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){v("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)a.nextTick(emitReadable_,e);else emitReadable_(e)}}function emitReadable_(e){v("emit readable");e.emit("readable");flow(e)}function maybeReadMore(e,t){if(!t.readingMore){t.readingMore=true;a.nextTick(maybeReadMore_,e,t)}}function maybeReadMore_(e,t){var r=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length1&&indexOf(o.pipes,e)!==-1)&&!d){v("false write response, pause",r._readableState.awaitDrain);r._readableState.awaitDrain++;f=true}r.pause()}}function onerror(t){v("onerror",t);unpipe();e.removeListener("error",onerror);if(EElistenerCount(e,"error")===0)e.emit("error",t)}prependListener(e,"error",onerror);function onclose(){e.removeListener("finish",onfinish);unpipe()}e.once("close",onclose);function onfinish(){v("onfinish");e.removeListener("close",onclose);unpipe()}e.once("finish",onfinish);function unpipe(){v("unpipe");r.unpipe(e)}e.emit("pipe",r);if(!o.flowing){v("pipe resume");r.resume()}return e};function pipeOnDrain(e){return function(){var t=e._readableState;v("pipeOnDrain",t.awaitDrain);if(t.awaitDrain)t.awaitDrain--;if(t.awaitDrain===0&&EElistenerCount(e,"data")){t.flowing=true;flow(e)}}}Readable.prototype.unpipe=function(e){var t=this._readableState;var r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1){if(e&&e!==t.pipes)return this;if(!e)e=t.pipes;t.pipes=null;t.pipesCount=0;t.flowing=false;if(e)e.emit("unpipe",this,r);return this}if(!e){var a=t.pipes;var o=t.pipesCount;t.pipes=null;t.pipesCount=0;t.flowing=false;for(var s=0;s=t.length){if(t.decoder)r=t.buffer.join("");else if(t.buffer.length===1)r=t.buffer.head.data;else r=t.buffer.concat(t.length);t.buffer.clear()}else{r=fromListPartial(e,t.buffer,t.decoder)}return r}function fromListPartial(e,t,r){var a;if(es.length?s.length:e;if(u===s.length)o+=s;else o+=s.slice(0,e);e-=u;if(e===0){if(u===s.length){++a;if(r.next)t.head=r.next;else t.head=t.tail=null}else{t.head=r;r.data=s.slice(u)}break}++a}t.length-=a;return o}function copyFromBuffer(e,t){var r=d.allocUnsafe(e);var a=t.head;var o=1;a.data.copy(r);e-=a.data.length;while(a=a.next){var s=a.data;var u=e>s.length?s.length:e;s.copy(r,r.length-e,0,u);e-=u;if(e===0){if(u===s.length){++o;if(a.next)t.head=a.next;else t.head=t.tail=null}else{t.head=a;a.data=s.slice(u)}break}++o}t.length-=o;return r}function endReadable(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!t.endEmitted){t.ended=true;a.nextTick(endReadableNT,t,e)}}function endReadableNT(e,t){if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end")}}function indexOf(e,t){for(var r=0,a=e.length;r{"use strict";e.exports=Transform;var a=r(8393);var o=Object.create(r(3487));o.inherits=r(6919);o.inherits(Transform,a);function afterTransform(e,t){var r=this._transformState;r.transforming=false;var a=r.writecb;if(!a){return this.emit("error",new Error("write callback called multiple times"))}r.writechunk=null;r.writecb=null;if(t!=null)this.push(t);a(e);var o=this._readableState;o.reading=false;if(o.needReadable||o.length{"use strict";var a=r(7843);e.exports=Writable;function WriteReq(e,t,r){this.chunk=e;this.encoding=t;this.callback=r;this.next=null}function CorkedRequest(e){var t=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(t,e)}}var o=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:a.nextTick;var s;Writable.WritableState=WritableState;var u=Object.create(r(3487));u.inherits=r(6919);var c={deprecate:r(9209)};var d=r(5016);var f=r(4810).Buffer;var p=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return f.from(e)}function _isUint8Array(e){return f.isBuffer(e)||e instanceof p}var h=r(3090);u.inherits(Writable,d);function nop(){}function WritableState(e,t){s=s||r(8393);e=e||{};var a=t instanceof s;this.objectMode=!!e.objectMode;if(a)this.objectMode=this.objectMode||!!e.writableObjectMode;var o=e.highWaterMark;var u=e.writableHighWaterMark;var c=this.objectMode?16:16*1024;if(o||o===0)this.highWaterMark=o;else if(a&&(u||u===0))this.highWaterMark=u;else this.highWaterMark=c;this.highWaterMark=Math.floor(this.highWaterMark);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;var d=e.decodeStrings===false;this.decodeStrings=!d;this.defaultEncoding=e.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(e){onwrite(t,e)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var e=this.bufferedRequest;var t=[];while(e){t.push(e);e=e.next}return t};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:c.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}catch(e){}})();var v;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){v=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(e){if(v.call(this,e))return true;if(this!==Writable)return false;return e&&e._writableState instanceof WritableState}})}else{v=function(e){return e instanceof this}}function Writable(e){s=s||r(8393);if(!v.call(Writable,this)&&!(this instanceof s)){return new Writable(e)}this._writableState=new WritableState(e,this);this.writable=true;if(e){if(typeof e.write==="function")this._write=e.write;if(typeof e.writev==="function")this._writev=e.writev;if(typeof e.destroy==="function")this._destroy=e.destroy;if(typeof e.final==="function")this._final=e.final}d.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(e,t){var r=new Error("write after end");e.emit("error",r);a.nextTick(t,r)}function validChunk(e,t,r,o){var s=true;var u=false;if(r===null){u=new TypeError("May not write null values to stream")}else if(typeof r!=="string"&&r!==undefined&&!t.objectMode){u=new TypeError("Invalid non-string/buffer chunk")}if(u){e.emit("error",u);a.nextTick(o,u);s=false}return s}Writable.prototype.write=function(e,t,r){var a=this._writableState;var o=false;var s=!a.objectMode&&_isUint8Array(e);if(s&&!f.isBuffer(e)){e=_uint8ArrayToBuffer(e)}if(typeof t==="function"){r=t;t=null}if(s)t="buffer";else if(!t)t=a.defaultEncoding;if(typeof r!=="function")r=nop;if(a.ended)writeAfterEnd(this,r);else if(s||validChunk(this,a,e,r)){a.pendingcb++;o=writeOrBuffer(this,a,s,e,t,r)}return o};Writable.prototype.cork=function(){var e=this._writableState;e.corked++};Writable.prototype.uncork=function(){var e=this._writableState;if(e.corked){e.corked--;if(!e.writing&&!e.corked&&!e.finished&&!e.bufferProcessing&&e.bufferedRequest)clearBuffer(this,e)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(e){if(typeof e==="string")e=e.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e;return this};function decodeChunk(e,t,r){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=f.from(t,r)}return t}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function writeOrBuffer(e,t,r,a,o,s){if(!r){var u=decodeChunk(t,a,o);if(a!==u){r=true;o="buffer";a=u}}var c=t.objectMode?1:a.length;t.length+=c;var d=t.length{"use strict";function _classCallCheck(e,t){if(!(e instanceof t)){throw new TypeError("Cannot call a class as a function")}}var a=r(4810).Buffer;var o=r(3837);function copyBuffer(e,t,r){e.copy(t,r)}e.exports=function(){function BufferList(){_classCallCheck(this,BufferList);this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function push(e){var t={data:e,next:null};if(this.length>0)this.tail.next=t;else this.head=t;this.tail=t;++this.length};BufferList.prototype.unshift=function unshift(e){var t={data:e,next:this.head};if(this.length===0)this.tail=t;this.head=t;++this.length};BufferList.prototype.shift=function shift(){if(this.length===0)return;var e=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return e};BufferList.prototype.clear=function clear(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function join(e){if(this.length===0)return"";var t=this.head;var r=""+t.data;while(t=t.next){r+=e+t.data}return r};BufferList.prototype.concat=function concat(e){if(this.length===0)return a.alloc(0);if(this.length===1)return this.head.data;var t=a.allocUnsafe(e>>>0);var r=this.head;var o=0;while(r){copyBuffer(r.data,t,o);o+=r.data.length;r=r.next}return t};return BufferList}();if(o&&o.inspect&&o.inspect.custom){e.exports.prototype[o.inspect.custom]=function(){var e=o.inspect({length:this.length});return this.constructor.name+" "+e}}},3090:(e,t,r)=>{"use strict";var a=r(7843);function destroy(e,t){var r=this;var o=this._readableState&&this._readableState.destroyed;var s=this._writableState&&this._writableState.destroyed;if(o||s){if(t){t(e)}else if(e&&(!this._writableState||!this._writableState.errorEmitted)){a.nextTick(emitErrorNT,this,e)}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(e||null,(function(e){if(!t&&e){a.nextTick(emitErrorNT,r,e);if(r._writableState){r._writableState.errorEmitted=true}}else if(t){t(e)}}));return this}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(e,t){e.emit("error",t)}e.exports={destroy:destroy,undestroy:undestroy}},5016:(e,t,r)=>{e.exports=r(2781)},4810:(e,t,r)=>{var a=r(4300);var o=a.Buffer;function copyProps(e,t){for(var r in e){t[r]=e[r]}}if(o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow){e.exports=a}else{copyProps(a,t);t.Buffer=SafeBuffer}function SafeBuffer(e,t,r){return o(e,t,r)}copyProps(o,SafeBuffer);SafeBuffer.from=function(e,t,r){if(typeof e==="number"){throw new TypeError("Argument must not be a number")}return o(e,t,r)};SafeBuffer.alloc=function(e,t,r){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}var a=o(e);if(t!==undefined){if(typeof r==="string"){a.fill(t,r)}else{a.fill(t)}}else{a.fill(0)}return a};SafeBuffer.allocUnsafe=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return o(e)};SafeBuffer.allocUnsafeSlow=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return a.SlowBuffer(e)}},6224:(e,t,r)=>{"use strict";var a=r(4810).Buffer;var o=a.isEncoding||function(e){e=""+e;switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function _normalizeEncoding(e){if(!e)return"utf8";var t;while(true){switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase();t=true}}}function normalizeEncoding(e){var t=_normalizeEncoding(e);if(typeof t!=="string"&&(a.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}t.s=StringDecoder;function StringDecoder(e){this.encoding=normalizeEncoding(e);var t;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;t=4;break;case"utf8":this.fillLast=utf8FillLast;t=4;break;case"base64":this.text=base64Text;this.end=base64End;t=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=a.allocUnsafe(t)}StringDecoder.prototype.write=function(e){if(e.length===0)return"";var t;var r;if(this.lastNeed){t=this.fillLast(e);if(t===undefined)return"";r=this.lastNeed;this.lastNeed=0}else{r=0}if(r>5===6)return 2;else if(e>>4===14)return 3;else if(e>>3===30)return 4;return e>>6===2?-1:-2}function utf8CheckIncomplete(e,t,r){var a=t.length-1;if(a=0){if(o>0)e.lastNeed=o-1;return o}if(--a=0){if(o>0)e.lastNeed=o-2;return o}if(--a=0){if(o>0){if(o===2)o=0;else e.lastNeed=o-3}return o}return 0}function utf8CheckExtraBytes(e,t,r){if((t[0]&192)!==128){e.lastNeed=0;return"�"}if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128){e.lastNeed=1;return"�"}if(e.lastNeed>2&&t.length>2){if((t[2]&192)!==128){e.lastNeed=2;return"�"}}}}function utf8FillLast(e){var t=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,e,t);if(r!==undefined)return r;if(this.lastNeed<=e.length){e.copy(this.lastChar,t,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}e.copy(this.lastChar,t,0,e.length);this.lastNeed-=e.length}function utf8Text(e,t){var r=utf8CheckIncomplete(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var a=e.length-(r-this.lastNeed);e.copy(this.lastChar,0,a);return e.toString("utf8",t,a)}function utf8End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+"�";return t}function utf16Text(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var a=r.charCodeAt(r.length-1);if(a>=55296&&a<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=e[e.length-1];return e.toString("utf16le",t,e.length-1)}function utf16End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function base64Text(e,t){var r=(e.length-t)%3;if(r===0)return e.toString("base64",t);this.lastNeed=3-r;this.lastTotal=3;if(r===1){this.lastChar[0]=e[e.length-1]}else{this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1]}return e.toString("base64",t,e.length-r)}function base64End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+this.lastChar.toString("base64",0,3-this.lastNeed);return t}function simpleWrite(e){return e.toString(this.encoding)}function simpleEnd(e){return e&&e.length?this.write(e):""}},675:(e,t,r)=>{var a=r(2781);if(process.env.READABLE_STREAM==="disable"&&a){e.exports=a;t=e.exports=a.Readable;t.Readable=a.Readable;t.Writable=a.Writable;t.Duplex=a.Duplex;t.Transform=a.Transform;t.PassThrough=a.PassThrough;t.Stream=a}else{t=e.exports=r(284);t.Stream=a||t;t.Readable=t;t.Writable=r(6100);t.Duplex=r(8393);t.Transform=r(5469);t.PassThrough=r(5125)}},2753:(e,t,r)=>{"use strict";const a=r(1017);const o=r(8188);const s=r(7147);const resolveFrom=(e,t,r)=>{if(typeof e!=="string"){throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof e}\``)}if(typeof t!=="string"){throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof t}\``)}try{e=s.realpathSync(e)}catch(t){if(t.code==="ENOENT"){e=a.resolve(e)}else if(r){return}else{throw t}}const u=a.join(e,"noop.js");const resolveFileName=()=>o._resolveFilename(t,{id:u,filename:u,paths:o._nodeModulePaths(e)});if(r){try{return resolveFileName()}catch(e){return}}return resolveFileName()};e.exports=(e,t)=>resolveFrom(e,t);e.exports.silent=(e,t)=>resolveFrom(e,t,true)},7586:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});function _interopDefault(e){return e&&typeof e==="object"&&"default"in e?e["default"]:e}var a=r(1017);var o=_interopDefault(a);var s=r(619);var u=_interopDefault(r(3837));const c=function addExtension(e,t=".js"){if(!a.extname(e))e+=t;return e};const d={ArrayPattern(e,t){for(const r of t.elements){if(r)d[r.type](e,r)}},AssignmentPattern(e,t){d[t.left.type](e,t.left)},Identifier(e,t){e.push(t.name)},MemberExpression(){},ObjectPattern(e,t){for(const r of t.properties){if(r.type==="RestElement"){d.RestElement(e,r)}else{d[r.value.type](e,r.value)}}},RestElement(e,t){d[t.argument.type](e,t.argument)}};const f=function extractAssignedNames(e){const t=[];d[e.type](t,e);return t};const p={const:true,let:true};class Scope{constructor(e={}){this.parent=e.parent;this.isBlockScope=!!e.block;this.declarations=Object.create(null);if(e.params){e.params.forEach((e=>{f(e).forEach((e=>{this.declarations[e]=true}))}))}}addDeclaration(e,t,r){if(!t&&this.isBlockScope){this.parent.addDeclaration(e,t,r)}else if(e.id){f(e.id).forEach((e=>{this.declarations[e]=true}))}}contains(e){return this.declarations[e]||(this.parent?this.parent.contains(e):false)}}const h=function attachScopes(e,t="scope"){let r=new Scope;s.walk(e,{enter(e,a){if(/(Function|Class)Declaration/.test(e.type)){r.addDeclaration(e,false,false)}if(e.type==="VariableDeclaration"){const t=e.kind;const a=p[t];e.declarations.forEach((e=>{r.addDeclaration(e,a,true)}))}let o;if(/Function/.test(e.type)){o=new Scope({parent:r,block:false,params:e.params});if(e.type==="FunctionExpression"&&e.id){o.addDeclaration(e,false,false)}}if(e.type==="BlockStatement"&&!/Function/.test(a.type)){o=new Scope({parent:r,block:true})}if(e.type==="CatchClause"){o=new Scope({parent:r,params:e.param?[e.param]:[],block:true})}if(o){Object.defineProperty(e,t,{value:o,configurable:true});r=o}},leave(e){if(e[t])r=r.parent}});return r};function createCommonjsModule(e,t){return t={exports:{}},e(t,t.exports),t.exports}var v=createCommonjsModule((function(e,t){t.isInteger=e=>{if(typeof e==="number"){return Number.isInteger(e)}if(typeof e==="string"&&e.trim()!==""){return Number.isInteger(Number(e))}return false};t.find=(e,t)=>e.nodes.find((e=>e.type===t));t.exceedsLimit=(e,r,a=1,o)=>{if(o===false)return false;if(!t.isInteger(e)||!t.isInteger(r))return false;return(Number(r)-Number(e))/Number(a)>=o};t.escapeNode=(e,t=0,r)=>{let a=e.nodes[t];if(!a)return;if(r&&a.type===r||a.type==="open"||a.type==="close"){if(a.escaped!==true){a.value="\\"+a.value;a.escaped=true}}};t.encloseBrace=e=>{if(e.type!=="brace")return false;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}return false};t.isInvalidBrace=e=>{if(e.type!=="brace")return false;if(e.invalid===true||e.dollar)return true;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}if(e.open!==true||e.close!==true){e.invalid=true;return true}return false};t.isOpenOrClose=e=>{if(e.type==="open"||e.type==="close"){return true}return e.open===true||e.close===true};t.reduce=e=>e.reduce(((e,t)=>{if(t.type==="text")e.push(t.value);if(t.type==="range")t.type="text";return e}),[]);t.flatten=(...e)=>{const t=[];const flat=e=>{for(let r=0;r{let stringify=(e,r={})=>{let a=t.escapeInvalid&&v.isInvalidBrace(r);let o=e.invalid===true&&t.escapeInvalid===true;let s="";if(e.value){if((a||o)&&v.isOpenOrClose(e)){return"\\"+e.value}return e.value}if(e.value){return e.value}if(e.nodes){for(let t of e.nodes){s+=stringify(t)}}return s};return stringify(e)}; /*! * is-number * * Copyright (c) 2014-present, Jon Schlinkert. * Released under the MIT License. - */var isNumber=function(e){if(typeof e==="number"){return e-e===0}if(typeof e==="string"&&e.trim()!==""){return Number.isFinite?Number.isFinite(+e):isFinite(+e)}return false};const toRegexRange=(e,t,r)=>{if(isNumber(e)===false){throw new TypeError("toRegexRange: expected the first argument to be a number")}if(t===void 0||e===t){return String(e)}if(isNumber(t)===false){throw new TypeError("toRegexRange: expected the second argument to be a number.")}let s=Object.assign({relaxZeros:true},r);if(typeof s.strictZeros==="boolean"){s.relaxZeros=s.strictZeros===false}let a=String(s.relaxZeros);let o=String(s.shorthand);let u=String(s.capture);let c=String(s.wrap);let f=e+":"+t+"="+a+o+u+c;if(toRegexRange.cache.hasOwnProperty(f)){return toRegexRange.cache[f].result}let p=Math.min(e,t);let d=Math.max(e,t);if(Math.abs(p-d)===1){let r=e+"|"+t;if(s.capture){return`(${r})`}if(s.wrap===false){return r}return`(?:${r})`}let h=hasPadding(e)||hasPadding(t);let v={min:e,max:t,a:p,b:d};let g=[];let m=[];if(h){v.isPadded=h;v.maxLen=String(v.max).length}if(p<0){let e=d<0?Math.abs(d):1;m=splitToPatterns(e,Math.abs(p),v,s);p=v.a=0}if(d>=0){g=splitToPatterns(p,d,v,s)}v.negatives=m;v.positives=g;v.result=collatePatterns(m,g,s);if(s.capture===true){v.result=`(${v.result})`}else if(s.wrap!==false&&g.length+m.length>1){v.result=`(?:${v.result})`}toRegexRange.cache[f]=v;return v.result};function collatePatterns(e,t,r){let s=filterPatterns(e,t,"-",false,r)||[];let a=filterPatterns(t,e,"",false,r)||[];let o=filterPatterns(e,t,"-?",true,r)||[];let u=s.concat(o).concat(a);return u.join("|")}function splitToRanges(e,t){let r=1;let s=1;let a=countNines(e,r);let o=new Set([t]);while(e<=a&&a<=t){o.add(a);r+=1;a=countNines(e,r)}a=countZeros(t+1,s)-1;while(e1){c.count.pop()}c.count.push(f.count[0]);c.string=c.pattern+toQuantifier(c.count);u=t+1;continue}if(r.isPadded){p=padZeros(t,r,s)}f.string=p+f.pattern+toQuantifier(f.count);o.push(f);u=t+1;c=f}return o}function filterPatterns(e,t,r,s,a){let o=[];for(let a of e){let{string:e}=a;if(!s&&!contains(t,"string",e)){o.push(r+e)}if(s&&contains(t,"string",e)){o.push(r+e)}}return o}function zip(e,t){let r=[];for(let s=0;st?1:t>e?-1:0}function contains(e,t,r){return e.some((e=>e[t]===r))}function countNines(e,t){return Number(String(e).slice(0,-t)+"9".repeat(t))}function countZeros(e,t){return e-e%Math.pow(10,t)}function toQuantifier(e){let[t=0,r=""]=e;if(r||t>1){return`{${t+(r?","+r:"")}}`}return""}function toCharacterClass(e,t,r){return`[${e}${t-e===1?"":"-"}${t}]`}function hasPadding(e){return/^-?(0+)\d/.test(e)}function padZeros(e,t,r){if(!t.isPadded){return e}let s=Math.abs(t.maxLen-String(e).length);let a=r.relaxZeros!==false;switch(s){case 0:return"";case 1:return a?"0?":"0";case 2:return a?"0{0,2}":"00";default:{return a?`0{0,${s}}`:`0{${s}}`}}}toRegexRange.cache={};toRegexRange.clearCache=()=>toRegexRange.cache={};var A=toRegexRange;const isObject=e=>e!==null&&typeof e==="object"&&!Array.isArray(e);const transform=e=>t=>e===true?Number(t):String(t);const isValidValue=e=>typeof e==="number"||typeof e==="string"&&e!=="";const isNumber$1=e=>Number.isInteger(+e);const zeros=e=>{let t=`${e}`;let r=-1;if(t[0]==="-")t=t.slice(1);if(t==="0")return false;while(t[++r]==="0");return r>0};const stringify$1=(e,t,r)=>{if(typeof e==="string"||typeof t==="string"){return true}return r.stringify===true};const pad=(e,t,r)=>{if(t>0){let r=e[0]==="-"?"-":"";if(r)e=e.slice(1);e=r+e.padStart(r?t-1:t,"0")}if(r===false){return String(e)}return e};const toMaxLen=(e,t)=>{let r=e[0]==="-"?"-":"";if(r){e=e.slice(1);t--}while(e.length{e.negatives.sort(((e,t)=>et?1:0));e.positives.sort(((e,t)=>et?1:0));let r=t.capture?"":"?:";let s="";let a="";let o;if(e.positives.length){s=e.positives.join("|")}if(e.negatives.length){a=`-(${r}${e.negatives.join("|")})`}if(s&&a){o=`${s}|${a}`}else{o=s||a}if(t.wrap){return`(${r}${o})`}return o};const toRange=(e,t,r,s)=>{if(r){return A(e,t,Object.assign({wrap:false},s))}let a=String.fromCharCode(e);if(e===t)return a;let o=String.fromCharCode(t);return`[${a}-${o}]`};const toRegex=(e,t,r)=>{if(Array.isArray(e)){let t=r.wrap===true;let s=r.capture?"":"?:";return t?`(${s}${e.join("|")})`:e.join("|")}return A(e,t,r)};const rangeError=(...e)=>new RangeError("Invalid range arguments: "+u.inspect(...e));const invalidRange=(e,t,r)=>{if(r.strictRanges===true)throw rangeError([e,t]);return[]};const invalidStep=(e,t)=>{if(t.strictRanges===true){throw new TypeError(`Expected step "${e}" to be a number`)}return[]};const fillNumbers=(e,t,r=1,s={})=>{let a=Number(e);let o=Number(t);if(!Number.isInteger(a)||!Number.isInteger(o)){if(s.strictRanges===true)throw rangeError([e,t]);return[]}if(a===0)a=0;if(o===0)o=0;let u=a>o;let c=String(e);let f=String(t);let p=String(r);r=Math.max(Math.abs(r),1);let d=zeros(c)||zeros(f)||zeros(p);let h=d?Math.max(c.length,f.length,p.length):0;let v=d===false&&stringify$1(e,t,s)===false;let g=s.transform||transform(v);if(s.toRegex&&r===1){return toRange(toMaxLen(e,h),toMaxLen(t,h),true,s)}let m={negatives:[],positives:[]};let push=e=>m[e<0?"negatives":"positives"].push(Math.abs(e));let _=[];let y=0;while(u?a>=o:a<=o){if(s.toRegex===true&&r>1){push(a)}else{_.push(pad(g(a,y),h,v))}a=u?a-r:a+r;y++}if(s.toRegex===true){return r>1?toSequence(m,s):toRegex(_,null,Object.assign({wrap:false},s))}return _};const fillLetters=(e,t,r=1,s={})=>{if(!isNumber$1(e)&&e.length>1||!isNumber$1(t)&&t.length>1){return invalidRange(e,t,s)}let a=s.transform||(e=>String.fromCharCode(e));let o=`${e}`.charCodeAt(0);let u=`${t}`.charCodeAt(0);let c=o>u;let f=Math.min(o,u);let p=Math.max(o,u);if(s.toRegex&&r===1){return toRange(f,p,false,s)}let d=[];let h=0;while(c?o>=u:o<=u){d.push(a(o,h));o=c?o-r:o+r;h++}if(s.toRegex===true){return toRegex(d,null,{wrap:false,options:s})}return d};const fill=(e,t,r,s={})=>{if(t==null&&isValidValue(e)){return[e]}if(!isValidValue(e)||!isValidValue(t)){return invalidRange(e,t,s)}if(typeof r==="function"){return fill(e,t,1,{transform:r})}if(isObject(r)){return fill(e,t,0,r)}let a=Object.assign({},s);if(a.capture===true)a.wrap=true;r=r||a.step||1;if(!isNumber$1(r)){if(r!=null&&!isObject(r))return invalidStep(r,a);return fill(e,t,1,r)}if(isNumber$1(e)&&isNumber$1(t)){return fillNumbers(e,t,r,a)}return fillLetters(e,t,Math.max(Math.abs(r),1),a)};var C=fill;const compile=(e,t={})=>{let walk=(e,r={})=>{let s=v.isInvalidBrace(r);let a=e.invalid===true&&t.escapeInvalid===true;let o=s===true||a===true;let u=t.escapeInvalid===true?"\\":"";let c="";if(e.isOpen===true){return u+e.value}if(e.isClose===true){return u+e.value}if(e.type==="open"){return o?u+e.value:"("}if(e.type==="close"){return o?u+e.value:")"}if(e.type==="comma"){return e.prev.type==="comma"?"":o?e.value:"|"}if(e.value){return e.value}if(e.nodes&&e.ranges>0){let r=v.reduce(e.nodes);let s=C(...r,Object.assign({},t,{wrap:false,toRegex:true}));if(s.length!==0){return r.length>1&&s.length>1?`(${s})`:s}}if(e.nodes){for(let t of e.nodes){c+=walk(t,e)}}return c};return walk(e)};var R=compile;const append=(e="",t="",r=false)=>{let s=[];e=[].concat(e);t=[].concat(t);if(!t.length)return e;if(!e.length){return r?v.flatten(t).map((e=>`{${e}}`)):t}for(let a of e){if(Array.isArray(a)){for(let e of a){s.push(append(e,t,r))}}else{for(let e of t){if(r===true&&typeof e==="string")e=`{${e}}`;s.push(Array.isArray(e)?append(a,e,r):a+e)}}}return v.flatten(s)};const expand=(e,t={})=>{let r=t.rangeLimit===void 0?1e3:t.rangeLimit;let walk=(e,s={})=>{e.queue=[];let a=s;let o=s.queue;while(a.type!=="brace"&&a.type!=="root"&&a.parent){a=a.parent;o=a.queue}if(e.invalid||e.dollar){o.push(append(o.pop(),stringify(e,t)));return}if(e.type==="brace"&&e.invalid!==true&&e.nodes.length===2){o.push(append(o.pop(),["{}"]));return}if(e.nodes&&e.ranges>0){let s=v.reduce(e.nodes);if(v.exceedsLimit(...s,t.step,r)){throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.")}let a=C(...s,t);if(a.length===0){a=stringify(e,t)}o.push(append(o.pop(),a));e.nodes=[];return}let u=v.encloseBrace(e);let c=e.queue;let f=e;while(f.type!=="brace"&&f.type!=="root"&&f.parent){f=f.parent;c=f.queue}for(let t=0;t",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:"\t",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\ufeff"};const{MAX_LENGTH:O,CHAR_BACKSLASH:N,CHAR_BACKTICK:P,CHAR_COMMA:L,CHAR_DOT:j,CHAR_LEFT_PARENTHESES:D,CHAR_RIGHT_PARENTHESES:M,CHAR_LEFT_CURLY_BRACE:F,CHAR_RIGHT_CURLY_BRACE:B,CHAR_LEFT_SQUARE_BRACKET:W,CHAR_RIGHT_SQUARE_BRACKET:U,CHAR_DOUBLE_QUOTE:V,CHAR_SINGLE_QUOTE:q,CHAR_NO_BREAK_SPACE:H,CHAR_ZERO_WIDTH_NOBREAK_SPACE:$}=I;const parse=(e,t={})=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}let r=t||{};let s=typeof r.maxLength==="number"?Math.min(O,r.maxLength):O;if(e.length>s){throw new SyntaxError(`Input length (${e.length}), exceeds max characters (${s})`)}let a={type:"root",input:e,nodes:[]};let o=[a];let u=a;let c=a;let f=0;let p=e.length;let d=0;let h=0;let v;const advance=()=>e[d++];const push=e=>{if(e.type==="text"&&c.type==="dot"){c.type="text"}if(c&&c.type==="text"&&e.type==="text"){c.value+=e.value;return}u.nodes.push(e);e.parent=u;e.prev=c;c=e;return e};push({type:"bos"});while(d0){if(u.ranges>0){u.ranges=0;let e=u.nodes.shift();u.nodes=[e,{type:"text",value:stringify(u)}]}push({type:"comma",value:v});u.commas++;continue}if(v===j&&h>0&&u.commas===0){let e=u.nodes;if(h===0||e.length===0){push({type:"text",value:v});continue}if(c.type==="dot"){u.range=[];c.value+=v;c.type="range";if(u.nodes.length!==3&&u.nodes.length!==5){u.invalid=true;u.ranges=0;c.type="text";continue}u.ranges++;u.args=[];continue}if(c.type==="range"){e.pop();let t=e[e.length-1];t.value+=c.value+v;c=t;u.ranges--;continue}push({type:"dot",value:v});continue}push({type:"text",value:v})}do{u=o.pop();if(u.type!=="root"){u.nodes.forEach((e=>{if(!e.nodes){if(e.type==="open")e.isOpen=true;if(e.type==="close")e.isClose=true;if(!e.nodes)e.type="text";e.invalid=true}}));let e=o[o.length-1];let t=e.nodes.indexOf(u);e.nodes.splice(t,1,...u.nodes)}}while(o.length>0);push({type:"eos"});return a};var G=parse;const braces=(e,t={})=>{let r=[];if(Array.isArray(e)){for(let s of e){let e=braces.create(s,t);if(Array.isArray(e)){r.push(...e)}else{r.push(e)}}}else{r=[].concat(braces.create(e,t))}if(t&&t.expand===true&&t.nodupes===true){r=[...new Set(r)]}return r};braces.parse=(e,t={})=>G(e,t);braces.stringify=(e,t={})=>{if(typeof e==="string"){return stringify(braces.parse(e,t),t)}return stringify(e,t)};braces.compile=(e,t={})=>{if(typeof e==="string"){e=braces.parse(e,t)}return R(e,t)};braces.expand=(e,t={})=>{if(typeof e==="string"){e=braces.parse(e,t)}let r=T(e,t);if(t.noempty===true){r=r.filter(Boolean)}if(t.nodupes===true){r=[...new Set(r)]}return r};braces.create=(e,t={})=>{if(e===""||e.length<3){return[e]}return t.expand!==true?braces.compile(e,t):braces.expand(e,t)};var K=braces;const z="\\\\/";const Q=`[^${z}]`;const Y="\\.";const X="\\+";const Z="\\?";const J="\\/";const ee="(?=.)";const te="[^/]";const ie=`(?:${J}|$)`;const re=`(?:^|${J})`;const ne=`${Y}{1,2}${ie}`;const se=`(?!${Y})`;const ae=`(?!${re}${ne})`;const oe=`(?!${Y}{0,1}${ie})`;const le=`(?!${ne})`;const ue=`[^.${J}]`;const ce=`${te}*?`;const fe={DOT_LITERAL:Y,PLUS_LITERAL:X,QMARK_LITERAL:Z,SLASH_LITERAL:J,ONE_CHAR:ee,QMARK:te,END_ANCHOR:ie,DOTS_SLASH:ne,NO_DOT:se,NO_DOTS:ae,NO_DOT_SLASH:oe,NO_DOTS_SLASH:le,QMARK_NO_DOT:ue,STAR:ce,START_ANCHOR:re};const pe=Object.assign({},fe,{SLASH_LITERAL:`[${z}]`,QMARK:Q,STAR:`${Q}*?`,DOTS_SLASH:`${Y}{1,2}(?:[${z}]|$)`,NO_DOT:`(?!${Y})`,NO_DOTS:`(?!(?:^|[${z}])${Y}{1,2}(?:[${z}]|$))`,NO_DOT_SLASH:`(?!${Y}{0,1}(?:[${z}]|$))`,NO_DOTS_SLASH:`(?!${Y}{1,2}(?:[${z}]|$))`,QMARK_NO_DOT:`[^.${z}]`,START_ANCHOR:`(?:^|[${z}])`,END_ANCHOR:`(?:[${z}]|$)`});const de={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};var he={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:de,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHAR:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:a.sep,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?pe:fe}};var ve=createCommonjsModule((function(e,t){const r=process.platform==="win32";const{REGEX_SPECIAL_CHARS:s,REGEX_SPECIAL_CHARS_GLOBAL:o,REGEX_REMOVE_BACKSLASH:u}=he;t.isObject=e=>e!==null&&typeof e==="object"&&!Array.isArray(e);t.hasRegexChars=e=>s.test(e);t.isRegexChar=e=>e.length===1&&t.hasRegexChars(e);t.escapeRegex=e=>e.replace(o,"\\$1");t.toPosixSlashes=e=>e.replace(/\\/g,"/");t.removeBackslashes=e=>e.replace(u,(e=>e==="\\"?"":e));t.supportsLookbehinds=()=>{let e=process.version.slice(1).split(".");if(e.length===3&&+e[0]>=9||+e[0]===8&&+e[1]>=10){return true}return false};t.isWindows=e=>{if(e&&typeof e.windows==="boolean"){return e.windows}return r===true||a.sep==="\\"};t.escapeLast=(e,r,s)=>{let a=e.lastIndexOf(r,s);if(a===-1)return e;if(e[a-1]==="\\")return t.escapeLast(e,r,a-1);return e.slice(0,a)+"\\"+e.slice(a)}}));var be=ve.isObject;var ge=ve.hasRegexChars;var me=ve.isRegexChar;var _e=ve.escapeRegex;var ye=ve.toPosixSlashes;var xe=ve.removeBackslashes;var we=ve.supportsLookbehinds;var Ee=ve.isWindows;var Se=ve.escapeLast;const{CHAR_ASTERISK:ke,CHAR_AT:Ae,CHAR_BACKWARD_SLASH:Ce,CHAR_COMMA:Re,CHAR_DOT:Te,CHAR_EXCLAMATION_MARK:Ie,CHAR_FORWARD_SLASH:Oe,CHAR_LEFT_CURLY_BRACE:Ne,CHAR_LEFT_PARENTHESES:Pe,CHAR_LEFT_SQUARE_BRACKET:Le,CHAR_PLUS:je,CHAR_QUESTION_MARK:De,CHAR_RIGHT_CURLY_BRACE:Me,CHAR_RIGHT_PARENTHESES:Fe,CHAR_RIGHT_SQUARE_BRACKET:Be}=he;const isPathSeparator=e=>e===Oe||e===Ce;var scan=(e,t)=>{let r=t||{};let s=e.length-1;let a=-1;let o=0;let u=0;let c=false;let f=false;let p=false;let d=0;let h;let v;let g=false;let eos=()=>a>=s;let advance=()=>{h=v;return e.charCodeAt(++a)};while(a0){m=e.slice(0,o);e=e.slice(o);u-=o}if(y&&c===true&&u>0){y=e.slice(0,u);x=e.slice(u)}else if(c===true){y="";x=e}else{y=e}if(y&&y!==""&&y!=="/"&&y!==e){if(isPathSeparator(y.charCodeAt(y.length-1))){y=y.slice(0,-1)}}if(r.unescape===true){if(x)x=ve.removeBackslashes(x);if(y&&f===true){y=ve.removeBackslashes(y)}}return{prefix:m,input:_,base:y,glob:x,negated:p,isGlob:c}};const{MAX_LENGTH:We,POSIX_REGEX_SOURCE:Ue,REGEX_NON_SPECIAL_CHAR:Ve,REGEX_SPECIAL_CHARS_BACKREF:qe,REPLACEMENTS:He}=he;const expandRange=(e,t)=>{if(typeof t.expandRange==="function"){return t.expandRange(...e,t)}e.sort();let r=`[${e.join("-")}]`;try{}catch(t){return e.map((e=>ve.escapeRegex(e))).join("..")}return r};const negate=e=>{let t=1;while(e.peek()==="!"&&(e.peek(2)!=="("||e.peek(3)==="?")){e.advance();e.start++;t++}if(t%2===0){return false}e.negated=true;e.start++;return true};const syntaxError=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`;const parse$1=(e,t)=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}e=He[e]||e;let r=Object.assign({},t);let s=typeof r.maxLength==="number"?Math.min(We,r.maxLength):We;let a=e.length;if(a>s){throw new SyntaxError(`Input length: ${a}, exceeds maximum allowed length: ${s}`)}let o={type:"bos",value:"",output:r.prepend||""};let u=[o];let c=r.capture?"":"?:";let f=ve.isWindows(t);const p=he.globChars(f);const d=he.extglobChars(p);const{DOT_LITERAL:h,PLUS_LITERAL:v,SLASH_LITERAL:g,ONE_CHAR:m,DOTS_SLASH:_,NO_DOT:y,NO_DOT_SLASH:x,NO_DOTS_SLASH:w,QMARK:E,QMARK_NO_DOT:S,STAR:k,START_ANCHOR:A}=p;const globstar=e=>`(${c}(?:(?!${A}${e.dot?_:h}).)*?)`;let C=r.dot?"":y;let R=r.bash===true?globstar(r):k;let T=r.dot?E:S;if(r.capture){R=`(${R})`}if(typeof r.noext==="boolean"){r.noextglob=r.noext}let I={index:-1,start:0,consumed:"",output:"",backtrack:false,brackets:0,braces:0,parens:0,quotes:0,tokens:u};let O=[];let N=[];let P=o;let L;const eos=()=>I.index===a-1;const j=I.peek=(t=1)=>e[I.index+t];const D=I.advance=()=>e[++I.index];const append=e=>{I.output+=e.output!=null?e.output:e.value;I.consumed+=e.value||""};const increment=e=>{I[e]++;N.push(e)};const decrement=e=>{I[e]--;N.pop()};const push=e=>{if(P.type==="globstar"){let t=I.braces>0&&(e.type==="comma"||e.type==="brace");let r=O.length&&(e.type==="pipe"||e.type==="paren");if(e.type!=="slash"&&e.type!=="paren"&&!t&&!r){I.output=I.output.slice(0,-P.output.length);P.type="star";P.value="*";P.output=R;I.output+=P.output}}if(O.length&&e.type!=="paren"&&!d[e.value]){O[O.length-1].inner+=e.value}if(e.value||e.output)append(e);if(P&&P.type==="text"&&e.type==="text"){P.value+=e.value;return}e.prev=P;u.push(e);P=e};const extglobOpen=(e,t)=>{let s=Object.assign({},d[t],{conditions:1,inner:""});s.prev=P;s.parens=I.parens;s.output=I.output;let a=(r.capture?"(":"")+s.open;push({type:e,value:t,output:I.output?"":m});push({type:"paren",extglob:true,value:D(),output:a});increment("parens");O.push(s)};const extglobClose=t=>{let s=t.close+(r.capture?")":"");if(t.type==="negate"){let a=R;if(t.inner&&t.inner.length>1&&t.inner.includes("/")){a=globstar(r)}if(a!==R||eos()||/^\)+$/.test(e.slice(I.index+1))){s=t.close=")$))"+a}if(t.prev.type==="bos"&&eos()){I.negatedExtglob=true}}push({type:"paren",extglob:true,value:L,output:s});decrement("parens")};if(r.fastpaths!==false&&!/(^[*!]|[/{[()\]}"])/.test(e)){let t=false;let s=e.replace(qe,((e,r,s,a,o,u)=>{if(a==="\\"){t=true;return e}if(a==="?"){if(r){return r+a+(o?E.repeat(o.length):"")}if(u===0){return T+(o?E.repeat(o.length):"")}return E.repeat(s.length)}if(a==="."){return h.repeat(s.length)}if(a==="*"){if(r){return r+a+(o?R:"")}return R}return r?e:"\\"+e}));if(t===true){if(r.unescape===true){s=s.replace(/\\/g,"")}else{s=s.replace(/\\+/g,(e=>e.length%2===0?"\\\\":e?"\\":""))}}I.output=s;return I}while(!eos()){L=D();if(L==="\0"){continue}if(L==="\\"){let t=j();if(t==="/"&&r.bash!==true){continue}if(t==="."||t===";"){continue}if(!t){L+="\\";push({type:"text",value:L});continue}let s=/^\\+/.exec(e.slice(I.index+1));let a=0;if(s&&s[0].length>2){a=s[0].length;I.index+=a;if(a%2!==0){L+="\\"}}if(r.unescape===true){L=D()||""}else{L+=D()||""}if(I.brackets===0){push({type:"text",value:L});continue}}if(I.brackets>0&&(L!=="]"||P.value==="["||P.value==="[^")){if(r.posix!==false&&L===":"){let e=P.value.slice(1);if(e.includes("[")){P.posix=true;if(e.includes(":")){let e=P.value.lastIndexOf("[");let t=P.value.slice(0,e);let r=P.value.slice(e+2);let s=Ue[r];if(s){P.value=t+s;I.backtrack=true;D();if(!o.output&&u.indexOf(P)===1){o.output=m}continue}}}}if(L==="["&&j()!==":"||L==="-"&&j()==="]"){L="\\"+L}if(L==="]"&&(P.value==="["||P.value==="[^")){L="\\"+L}if(r.posix===true&&L==="!"&&P.value==="["){L="^"}P.value+=L;append({value:L});continue}if(I.quotes===1&&L!=='"'){L=ve.escapeRegex(L);P.value+=L;append({value:L});continue}if(L==='"'){I.quotes=I.quotes===1?0:1;if(r.keepQuotes===true){push({type:"text",value:L})}continue}if(L==="("){push({type:"paren",value:L});increment("parens");continue}if(L===")"){if(I.parens===0&&r.strictBrackets===true){throw new SyntaxError(syntaxError("opening","("))}let e=O[O.length-1];if(e&&I.parens===e.parens+1){extglobClose(O.pop());continue}push({type:"paren",value:L,output:I.parens?")":"\\)"});decrement("parens");continue}if(L==="["){if(r.nobracket===true||!e.slice(I.index+1).includes("]")){if(r.nobracket!==true&&r.strictBrackets===true){throw new SyntaxError(syntaxError("closing","]"))}L="\\"+L}else{increment("brackets")}push({type:"bracket",value:L});continue}if(L==="]"){if(r.nobracket===true||P&&P.type==="bracket"&&P.value.length===1){push({type:"text",value:L,output:"\\"+L});continue}if(I.brackets===0){if(r.strictBrackets===true){throw new SyntaxError(syntaxError("opening","["))}push({type:"text",value:L,output:"\\"+L});continue}decrement("brackets");let e=P.value.slice(1);if(P.posix!==true&&e[0]==="^"&&!e.includes("/")){L="/"+L}P.value+=L;append({value:L});if(r.literalBrackets===false||ve.hasRegexChars(e)){continue}let t=ve.escapeRegex(P.value);I.output=I.output.slice(0,-P.value.length);if(r.literalBrackets===true){I.output+=t;P.value=t;continue}P.value=`(${c}${t}|${P.value})`;I.output+=P.value;continue}if(L==="{"&&r.nobrace!==true){push({type:"brace",value:L,output:"("});increment("braces");continue}if(L==="}"){if(r.nobrace===true||I.braces===0){push({type:"text",value:L,output:"\\"+L});continue}let e=")";if(I.dots===true){let t=u.slice();let s=[];for(let e=t.length-1;e>=0;e--){u.pop();if(t[e].type==="brace"){break}if(t[e].type!=="dots"){s.unshift(t[e].value)}}e=expandRange(s,r);I.backtrack=true}push({type:"brace",value:L,output:e});decrement("braces");continue}if(L==="|"){if(O.length>0){O[O.length-1].conditions++}push({type:"text",value:L});continue}if(L===","){let e=L;if(I.braces>0&&N[N.length-1]==="braces"){e="|"}push({type:"comma",value:L,output:e});continue}if(L==="/"){if(P.type==="dot"&&I.index===1){I.start=I.index+1;I.consumed="";I.output="";u.pop();P=o;continue}push({type:"slash",value:L,output:g});continue}if(L==="."){if(I.braces>0&&P.type==="dot"){if(P.value===".")P.output=h;P.type="dots";P.output+=L;P.value+=L;I.dots=true;continue}push({type:"dot",value:L,output:h});continue}if(L==="?"){if(P&&P.type==="paren"){let e=j();let t=L;if(e==="<"&&!ve.supportsLookbehinds()){throw new Error("Node.js v10 or higher is required for regex lookbehinds")}if(P.value==="("&&!/[!=<:]/.test(e)||e==="<"&&!/[!=]/.test(j(2))){t="\\"+L}push({type:"text",value:L,output:t});continue}if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){extglobOpen("qmark",L);continue}if(r.dot!==true&&(P.type==="slash"||P.type==="bos")){push({type:"qmark",value:L,output:S});continue}push({type:"qmark",value:L,output:E});continue}if(L==="!"){if(r.noextglob!==true&&j()==="("){if(j(2)!=="?"||!/[!=<:]/.test(j(3))){extglobOpen("negate",L);continue}}if(r.nonegate!==true&&I.index===0){negate(I);continue}}if(L==="+"){if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){extglobOpen("plus",L);continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")){let e=P.extglob===true?"\\"+L:L;push({type:"plus",value:L,output:e});continue}if(I.parens>0&&r.regex!==false){push({type:"plus",value:L});continue}push({type:"plus",value:v});continue}if(L==="@"){if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){push({type:"at",value:L,output:""});continue}push({type:"text",value:L});continue}if(L!=="*"){if(L==="$"||L==="^"){L="\\"+L}let t=Ve.exec(e.slice(I.index+1));if(t){L+=t[0];I.index+=t[0].length}push({type:"text",value:L});continue}if(P&&(P.type==="globstar"||P.star===true)){P.type="star";P.star=true;P.value+=L;P.output=R;I.backtrack=true;I.consumed+=L;continue}if(r.noextglob!==true&&j()==="("&&j(2)!=="?"){extglobOpen("star",L);continue}if(P.type==="star"){if(r.noglobstar===true){I.consumed+=L;continue}let t=P.prev;let s=t.prev;let a=t.type==="slash"||t.type==="bos";let o=s&&(s.type==="star"||s.type==="globstar");if(r.bash===true&&(!a||!eos()&&j()!=="/")){push({type:"star",value:L,output:""});continue}let u=I.braces>0&&(t.type==="comma"||t.type==="brace");let c=O.length&&(t.type==="pipe"||t.type==="paren");if(!a&&t.type!=="paren"&&!u&&!c){push({type:"star",value:L,output:""});continue}while(e.slice(I.index+1,I.index+4)==="/**"){let t=e[I.index+4];if(t&&t!=="/"){break}I.consumed+="/**";I.index+=3}if(t.type==="bos"&&eos()){P.type="globstar";P.value+=L;P.output=globstar(r);I.output=P.output;I.consumed+=L;continue}if(t.type==="slash"&&t.prev.type!=="bos"&&!o&&eos()){I.output=I.output.slice(0,-(t.output+P.output).length);t.output="(?:"+t.output;P.type="globstar";P.output=globstar(r)+"|$)";P.value+=L;I.output+=t.output+P.output;I.consumed+=L;continue}let f=j();if(t.type==="slash"&&t.prev.type!=="bos"&&f==="/"){let e=j(2)!==void 0?"|$":"";I.output=I.output.slice(0,-(t.output+P.output).length);t.output="(?:"+t.output;P.type="globstar";P.output=`${globstar(r)}${g}|${g}${e})`;P.value+=L;I.output+=t.output+P.output;I.consumed+=L+D();push({type:"slash",value:L,output:""});continue}if(t.type==="bos"&&f==="/"){P.type="globstar";P.value+=L;P.output=`(?:^|${g}|${globstar(r)}${g})`;I.output=P.output;I.consumed+=L+D();push({type:"slash",value:L,output:""});continue}I.output=I.output.slice(0,-P.output.length);P.type="globstar";P.output=globstar(r);P.value+=L;I.output+=P.output;I.consumed+=L;continue}let t={type:"star",value:L,output:R};if(r.bash===true){t.output=".*?";if(P.type==="bos"||P.type==="slash"){t.output=C+t.output}push(t);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&r.regex===true){t.output=L;push(t);continue}if(I.index===I.start||P.type==="slash"||P.type==="dot"){if(P.type==="dot"){I.output+=x;P.output+=x}else if(r.dot===true){I.output+=w;P.output+=w}else{I.output+=C;P.output+=C}if(j()!=="*"){I.output+=m;P.output+=m}}push(t)}while(I.brackets>0){if(r.strictBrackets===true)throw new SyntaxError(syntaxError("closing","]"));I.output=ve.escapeLast(I.output,"[");decrement("brackets")}while(I.parens>0){if(r.strictBrackets===true)throw new SyntaxError(syntaxError("closing",")"));I.output=ve.escapeLast(I.output,"(");decrement("parens")}while(I.braces>0){if(r.strictBrackets===true)throw new SyntaxError(syntaxError("closing","}"));I.output=ve.escapeLast(I.output,"{");decrement("braces")}if(r.strictSlashes!==true&&(P.type==="star"||P.type==="bracket")){push({type:"maybe_slash",value:"",output:`${g}?`})}if(I.backtrack===true){I.output="";for(let e of I.tokens){I.output+=e.output!=null?e.output:e.value;if(e.suffix){I.output+=e.suffix}}}return I};parse$1.fastpaths=(e,t)=>{let r=Object.assign({},t);let s=typeof r.maxLength==="number"?Math.min(We,r.maxLength):We;let a=e.length;if(a>s){throw new SyntaxError(`Input length: ${a}, exceeds maximum allowed length: ${s}`)}e=He[e]||e;let o=ve.isWindows(t);const{DOT_LITERAL:u,SLASH_LITERAL:c,ONE_CHAR:f,DOTS_SLASH:p,NO_DOT:d,NO_DOTS:h,NO_DOTS_SLASH:v,STAR:g,START_ANCHOR:m}=he.globChars(o);let _=r.capture?"":"?:";let y=r.bash===true?".*?":g;let x=r.dot?h:d;let w=r.dot?v:d;if(r.capture){y=`(${y})`}const globstar=e=>`(${_}(?:(?!${m}${e.dot?p:u}).)*?)`;const create=e=>{switch(e){case"*":return`${x}${f}${y}`;case".*":return`${u}${f}${y}`;case"*.*":return`${x}${y}${u}${f}${y}`;case"*/*":return`${x}${y}${c}${f}${w}${y}`;case"**":return x+globstar(r);case"**/*":return`(?:${x}${globstar(r)}${c})?${w}${f}${y}`;case"**/*.*":return`(?:${x}${globstar(r)}${c})?${w}${y}${u}${f}${y}`;case"**/.*":return`(?:${x}${globstar(r)}${c})?${u}${f}${y}`;default:{let r=/^(.*?)\.(\w+)$/.exec(e);if(!r)return;let s=create(r[1],t);if(!s)return;return s+u+r[2]}}};let E=create(e);if(E&&r.strictSlashes!==true){E+=`${c}?`}return E};var $e=parse$1;const picomatch=(e,t,r=false)=>{if(Array.isArray(e)){let s=e.map((e=>picomatch(e,t,r)));return e=>{for(let t of s){let r=t(e);if(r)return r}return false}}if(typeof e!=="string"||e===""){throw new TypeError("Expected pattern to be a non-empty string")}let s=t||{};let a=ve.isWindows(t);let o=picomatch.makeRe(e,t,false,true);let u=o.state;delete o.state;let isIgnored=()=>false;if(s.ignore){let e=Object.assign({},t,{ignore:null,onMatch:null,onResult:null});isIgnored=picomatch(s.ignore,e,r)}const matcher=(r,c=false)=>{let{isMatch:f,match:p,output:d}=picomatch.test(r,o,t,{glob:e,posix:a});let h={glob:e,state:u,regex:o,posix:a,input:r,output:d,match:p,isMatch:f};if(typeof s.onResult==="function"){s.onResult(h)}if(f===false){h.isMatch=false;return c?h:false}if(isIgnored(r)){if(typeof s.onIgnore==="function"){s.onIgnore(h)}h.isMatch=false;return c?h:false}if(typeof s.onMatch==="function"){s.onMatch(h)}return c?h:true};if(r){matcher.state=u}return matcher};picomatch.test=(e,t,r,{glob:s,posix:a}={})=>{if(typeof e!=="string"){throw new TypeError("Expected input to be a string")}if(e===""){return{isMatch:false,output:""}}let o=r||{};let u=o.format||(a?ve.toPosixSlashes:null);let c=e===s;let f=c&&u?u(e):e;if(c===false){f=u?u(e):e;c=f===s}if(c===false||o.capture===true){if(o.matchBase===true||o.basename===true){c=picomatch.matchBase(e,t,r,a)}else{c=t.exec(f)}}return{isMatch:!!c,match:c,output:f}};picomatch.matchBase=(e,t,r,s=ve.isWindows(r))=>{let o=t instanceof RegExp?t:picomatch.makeRe(t,r);return o.test(a.basename(e))};picomatch.isMatch=(e,t,r)=>picomatch(t,r)(e);picomatch.parse=(e,t)=>$e(e,t);picomatch.scan=(e,t)=>scan(e,t);picomatch.makeRe=(e,t,r=false,s=false)=>{if(!e||typeof e!=="string"){throw new TypeError("Expected a non-empty string")}let a=t||{};let o=a.contains?"":"^";let u=a.contains?"":"$";let c={negated:false,fastpaths:true};let f="";let p;if(e.startsWith("./")){e=e.slice(2);f=c.prefix="./"}if(a.fastpaths!==false&&(e[0]==="."||e[0]==="*")){p=$e.fastpaths(e,t)}if(p===void 0){c=picomatch.parse(e,t);c.prefix=f+(c.prefix||"");p=c.output}if(r===true){return p}let d=`${o}(?:${p})${u}`;if(c&&c.negated===true){d=`^(?!${d}).*$`}let h=picomatch.toRegex(d,t);if(s===true){h.state=c}return h};picomatch.toRegex=(e,t)=>{try{let r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(e){if(t&&t.debug===true)throw e;return/$^/}};picomatch.constants=he;var Ge=picomatch;var Ke=Ge;const isEmptyString=e=>typeof e==="string"&&(e===""||e==="./");const micromatch=(e,t,r)=>{t=[].concat(t);e=[].concat(e);let s=new Set;let a=new Set;let o=new Set;let u=0;let onResult=e=>{o.add(e.output);if(r&&r.onResult){r.onResult(e)}};for(let o=0;o!s.has(e)));if(r&&f.length===0){if(r.failglob===true){throw new Error(`No matches found for "${t.join(", ")}"`)}if(r.nonull===true||r.nullglob===true){return r.unescape?t.map((e=>e.replace(/\\/g,""))):t}}return f};micromatch.match=micromatch;micromatch.matcher=(e,t)=>Ke(e,t);micromatch.isMatch=(e,t,r)=>Ke(t,r)(e);micromatch.any=micromatch.isMatch;micromatch.not=(e,t,r={})=>{t=[].concat(t).map(String);let s=new Set;let a=[];let onResult=e=>{if(r.onResult)r.onResult(e);a.push(e.output)};let o=micromatch(e,t,Object.assign({},r,{onResult:onResult}));for(let e of a){if(!o.includes(e)){s.add(e)}}return[...s]};micromatch.contains=(e,t,r)=>{if(typeof e!=="string"){throw new TypeError(`Expected a string: "${u.inspect(e)}"`)}if(Array.isArray(t)){return t.some((t=>micromatch.contains(e,t,r)))}if(typeof t==="string"){if(isEmptyString(e)||isEmptyString(t)){return false}if(e.includes(t)||e.startsWith("./")&&e.slice(2).includes(t)){return true}}return micromatch.isMatch(e,t,Object.assign({},r,{contains:true}))};micromatch.matchKeys=(e,t,r)=>{if(!ve.isObject(e)){throw new TypeError("Expected the first argument to be an object")}let s=micromatch(Object.keys(e),t,r);let a={};for(let t of s)a[t]=e[t];return a};micromatch.some=(e,t,r)=>{let s=[].concat(e);for(let e of[].concat(t)){let t=Ke(String(e),r);if(s.some((e=>t(e)))){return true}}return false};micromatch.every=(e,t,r)=>{let s=[].concat(e);for(let e of[].concat(t)){let t=Ke(String(e),r);if(!s.every((e=>t(e)))){return false}}return true};micromatch.all=(e,t,r)=>{if(typeof e!=="string"){throw new TypeError(`Expected a string: "${u.inspect(e)}"`)}return[].concat(t).every((t=>Ke(t,r)(e)))};micromatch.capture=(e,t,r)=>{let s=ve.isWindows(r);let a=Ke.makeRe(String(e),Object.assign({},r,{capture:true}));let o=a.exec(s?ve.toPosixSlashes(t):t);if(o){return o.slice(1).map((e=>e===void 0?"":e))}};micromatch.makeRe=(...e)=>Ke.makeRe(...e);micromatch.scan=(...e)=>Ke.scan(...e);micromatch.parse=(e,t)=>{let r=[];for(let s of[].concat(e||[])){for(let e of K(String(s),t)){r.push(Ke.parse(e,t))}}return r};micromatch.braces=(e,t)=>{if(typeof e!=="string")throw new TypeError("Expected a string");if(t&&t.nobrace===true||!/\{.*\}/.test(e)){return[e]}return K(e,t)};micromatch.braceExpand=(e,t)=>{if(typeof e!=="string")throw new TypeError("Expected a string");return micromatch.braces(e,Object.assign({},t,{expand:true}))};var ze=micromatch;function ensureArray(e){if(Array.isArray(e))return e;if(e==undefined)return[];return[e]}function getMatcherString(e,t){if(t===false){return e}return s.resolve(...typeof t==="string"?[t,e]:[e])}const Qe=function createFilter(e,t,r){const a=r&&r.resolve;const getMatcher=e=>e instanceof RegExp?e:{test:ze.matcher(getMatcherString(e,a).split(s.sep).join("/"),{dot:true})};const o=ensureArray(e).map(getMatcher);const u=ensureArray(t).map(getMatcher);return function(e){if(typeof e!=="string")return false;if(/\0/.test(e))return false;e=e.split(s.sep).join("/");for(let t=0;tt.toUpperCase())).replace(/[^$_a-zA-Z0-9]/g,"_");if(/\d/.test(e[0])||Ze.has(e)){e=`_${e}`}return e||"_"};function stringify$2(e){return(JSON.stringify(e)||"undefined").replace(/[\u2028\u2029]/g,(e=>`\\u${("000"+e.charCodeAt(0).toString(16)).slice(-4)}`))}function serializeArray(e,t,r){let s="[";const a=t?"\n"+r+t:"";for(let o=0;o0?",":""}${a}${serialize(u,t,r+t)}`}return s+`${t?"\n"+r:""}]`}function serializeObject(e,t,r){let s="{";const a=t?"\n"+r+t:"";const o=Object.keys(e);for(let u=0;u0?",":""}${a}${f}:${t?" ":""}${serialize(e[c],t,r+t)}`}return s+`${t?"\n"+r:""}}`}function serialize(e,t,r){if(e===Infinity)return"Infinity";if(e===-Infinity)return"-Infinity";if(e===0&&1/e===-Infinity)return"-0";if(e instanceof Date)return"new Date("+e.getTime()+")";if(e instanceof RegExp)return e.toString();if(e!==e)return"NaN";if(Array.isArray(e))return serializeArray(e,t,r);if(e===null)return"null";if(typeof e==="object")return serializeObject(e,t,r);return stringify$2(e)}const et=function dataToEsm(e,t={}){const r=t.compact?"":"indent"in t?t.indent:"\t";const s=t.compact?"":" ";const a=t.compact?"":"\n";const o=t.preferConst?"const":"var";if(t.namedExports===false||typeof e!=="object"||Array.isArray(e)||e instanceof Date||e instanceof RegExp||e===null){const a=serialize(e,t.compact?null:r,"");const o=s||(/^[{[\-\/]/.test(a)?"":" ");return`export default${o}${a};`}let u="";const c=[];const f=Object.keys(e);for(let p=0;pt=true};const s={};const a=Object.prototype.toString;function isArray(e){return a.call(e)==="[object Array]"}function visit(e,a,o,u,c,f){if(!e)return;if(o){const s=t;t=false;o.call(r,e,a,c,f);const u=t;t=s;if(u)return}const p=e.type&&s[e.type]||(s[e.type]=Object.keys(e).filter((t=>typeof e[t]==="object")));for(let t=0;t{e.exports=function(e){[process.stdout,process.stderr].forEach((function(t){if(t._handle&&t.isTTY&&typeof t._handle.setBlocking==="function"){t._handle.setBlocking(e)}}))}},2028:(e,t,r)=>{var s=r(9491);var a=r(19);var o=r(2361);if(typeof o!=="function"){o=o.EventEmitter}var u;if(process.__signal_exit_emitter__){u=process.__signal_exit_emitter__}else{u=process.__signal_exit_emitter__=new o;u.count=0;u.emitted={}}if(!u.infinite){u.setMaxListeners(Infinity);u.infinite=true}e.exports=function(e,t){s.equal(typeof e,"function","a callback must be provided for exit handler");if(f===false){load()}var r="exit";if(t&&t.alwaysLast){r="afterexit"}var remove=function(){u.removeListener(r,e);if(u.listeners("exit").length===0&&u.listeners("afterexit").length===0){unload()}};u.on(r,e);return remove};e.exports.unload=unload;function unload(){if(!f){return}f=false;a.forEach((function(e){try{process.removeListener(e,c[e])}catch(e){}}));process.emit=d;process.reallyExit=p;u.count-=1}function emit(e,t,r){if(u.emitted[e]){return}u.emitted[e]=true;u.emit(e,t,r)}var c={};a.forEach((function(e){c[e]=function listener(){var t=process.listeners(e);if(t.length===u.count){unload();emit("exit",null,e);emit("afterexit",null,e);process.kill(process.pid,e)}}}));e.exports.signals=function(){return a};e.exports.load=load;var f=false;function load(){if(f){return}f=true;u.count+=1;a=a.filter((function(e){try{process.on(e,c[e]);return true}catch(e){return false}}));process.emit=processEmit;process.reallyExit=processReallyExit}var p=process.reallyExit;function processReallyExit(e){process.exitCode=e||0;emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);p.call(process,process.exitCode)}var d=process.emit;function processEmit(e,t){if(e==="exit"){if(t!==undefined){process.exitCode=t}var r=d.apply(this,arguments);emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);return r}else{return d.apply(this,arguments)}}},19:e=>{e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32"){e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT")}if(process.platform==="linux"){e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}},9209:(e,t,r)=>{e.exports=r(3837).deprecate},7568:(e,t,r)=>{"use strict";var s=r(3062);t.center=alignCenter;t.left=alignLeft;t.right=alignRight;function createPadding(e){var t="";var r=" ";var s=e;do{if(s%2){t+=r}s=Math.floor(s/2);r+=r}while(s);return t}function alignLeft(e,t){var r=e.trimRight();if(r.length===0&&e.length>=t)return e;var a="";var o=s(r);if(o=t)return e;var a="";var o=s(r);if(o=t)return e;var a="";var o="";var u=s(r);if(u{"use strict";e.exports=e=>{if(Number.isNaN(e)){return false}if(e>=4352&&(e<=4447||e===9001||e===9002||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141)){return true}return false}},3062:(e,t,r)=>{"use strict";const s=r(7518);const a=r(4994);e.exports=e=>{if(typeof e!=="string"||e.length===0){return 0}e=s(e);let t=0;for(let r=0;r=127&&s<=159){continue}if(s>=768&&s<=879){continue}if(s>65535){r++}t+=a(s)?2:1}return t}},918:module=>{module.exports=eval("require")("aws-sdk")},2722:module=>{module.exports=eval("require")("mock-aws-s3")},3902:module=>{module.exports=eval("require")("nock")},9491:e=>{"use strict";e.exports=require("assert")},4300:e=>{"use strict";e.exports=require("buffer")},2081:e=>{"use strict";e.exports=require("child_process")},2057:e=>{"use strict";e.exports=require("constants")},2361:e=>{"use strict";e.exports=require("events")},7147:e=>{"use strict";e.exports=require("fs")},8188:e=>{"use strict";e.exports=require("module")},3535:e=>{"use strict";e.exports=require("next/dist/compiled/glob")},2540:e=>{"use strict";e.exports=require("next/dist/compiled/micromatch")},7849:e=>{"use strict";e.exports=require("next/dist/compiled/semver")},7518:e=>{"use strict";e.exports=require("next/dist/compiled/strip-ansi")},2037:e=>{"use strict";e.exports=require("os")},1017:e=>{"use strict";e.exports=require("path")},8102:e=>{"use strict";e.exports=require("repl")},2781:e=>{"use strict";e.exports=require("stream")},7310:e=>{"use strict";e.exports=require("url")},3837:e=>{"use strict";e.exports=require("util")},7470:function(e,t){(function(e,r){true?r(t):0})(this,(function(e){"use strict";class WalkerBase{constructor(){this.should_skip=false;this.should_remove=false;this.replacement=null;this.context={skip:()=>this.should_skip=true,remove:()=>this.should_remove=true,replace:e=>this.replacement=e}}replace(e,t,r,s){if(e){if(r!==null){e[t][r]=s}else{e[t]=s}}}remove(e,t,r){if(e){if(r!==null){e[t].splice(r,1)}else{delete e[t]}}}}class SyncWalker extends WalkerBase{constructor(e,t){super();this.enter=e;this.leave=t}visit(e,t,r,s){if(e){if(this.enter){const a=this.should_skip;const o=this.should_remove;const u=this.replacement;this.should_skip=false;this.should_remove=false;this.replacement=null;this.enter.call(this.context,e,t,r,s);if(this.replacement){e=this.replacement;this.replace(t,r,s,e)}if(this.should_remove){this.remove(t,r,s)}const c=this.should_skip;const f=this.should_remove;this.should_skip=a;this.should_remove=o;this.replacement=u;if(c)return e;if(f)return null}for(const t in e){const r=e[t];if(typeof r!=="object"){continue}else if(Array.isArray(r)){for(let s=0;s{"use strict";e.exports=JSON.parse('{"0.1.14":{"node_abi":null,"v8":"1.3"},"0.1.15":{"node_abi":null,"v8":"1.3"},"0.1.16":{"node_abi":null,"v8":"1.3"},"0.1.17":{"node_abi":null,"v8":"1.3"},"0.1.18":{"node_abi":null,"v8":"1.3"},"0.1.19":{"node_abi":null,"v8":"2.0"},"0.1.20":{"node_abi":null,"v8":"2.0"},"0.1.21":{"node_abi":null,"v8":"2.0"},"0.1.22":{"node_abi":null,"v8":"2.0"},"0.1.23":{"node_abi":null,"v8":"2.0"},"0.1.24":{"node_abi":null,"v8":"2.0"},"0.1.25":{"node_abi":null,"v8":"2.0"},"0.1.26":{"node_abi":null,"v8":"2.0"},"0.1.27":{"node_abi":null,"v8":"2.1"},"0.1.28":{"node_abi":null,"v8":"2.1"},"0.1.29":{"node_abi":null,"v8":"2.1"},"0.1.30":{"node_abi":null,"v8":"2.1"},"0.1.31":{"node_abi":null,"v8":"2.1"},"0.1.32":{"node_abi":null,"v8":"2.1"},"0.1.33":{"node_abi":null,"v8":"2.1"},"0.1.90":{"node_abi":null,"v8":"2.2"},"0.1.91":{"node_abi":null,"v8":"2.2"},"0.1.92":{"node_abi":null,"v8":"2.2"},"0.1.93":{"node_abi":null,"v8":"2.2"},"0.1.94":{"node_abi":null,"v8":"2.2"},"0.1.95":{"node_abi":null,"v8":"2.2"},"0.1.96":{"node_abi":null,"v8":"2.2"},"0.1.97":{"node_abi":null,"v8":"2.2"},"0.1.98":{"node_abi":null,"v8":"2.2"},"0.1.99":{"node_abi":null,"v8":"2.2"},"0.1.100":{"node_abi":null,"v8":"2.2"},"0.1.101":{"node_abi":null,"v8":"2.3"},"0.1.102":{"node_abi":null,"v8":"2.3"},"0.1.103":{"node_abi":null,"v8":"2.3"},"0.1.104":{"node_abi":null,"v8":"2.3"},"0.2.0":{"node_abi":1,"v8":"2.3"},"0.2.1":{"node_abi":1,"v8":"2.3"},"0.2.2":{"node_abi":1,"v8":"2.3"},"0.2.3":{"node_abi":1,"v8":"2.3"},"0.2.4":{"node_abi":1,"v8":"2.3"},"0.2.5":{"node_abi":1,"v8":"2.3"},"0.2.6":{"node_abi":1,"v8":"2.3"},"0.3.0":{"node_abi":1,"v8":"2.5"},"0.3.1":{"node_abi":1,"v8":"2.5"},"0.3.2":{"node_abi":1,"v8":"3.0"},"0.3.3":{"node_abi":1,"v8":"3.0"},"0.3.4":{"node_abi":1,"v8":"3.0"},"0.3.5":{"node_abi":1,"v8":"3.0"},"0.3.6":{"node_abi":1,"v8":"3.0"},"0.3.7":{"node_abi":1,"v8":"3.0"},"0.3.8":{"node_abi":1,"v8":"3.1"},"0.4.0":{"node_abi":1,"v8":"3.1"},"0.4.1":{"node_abi":1,"v8":"3.1"},"0.4.2":{"node_abi":1,"v8":"3.1"},"0.4.3":{"node_abi":1,"v8":"3.1"},"0.4.4":{"node_abi":1,"v8":"3.1"},"0.4.5":{"node_abi":1,"v8":"3.1"},"0.4.6":{"node_abi":1,"v8":"3.1"},"0.4.7":{"node_abi":1,"v8":"3.1"},"0.4.8":{"node_abi":1,"v8":"3.1"},"0.4.9":{"node_abi":1,"v8":"3.1"},"0.4.10":{"node_abi":1,"v8":"3.1"},"0.4.11":{"node_abi":1,"v8":"3.1"},"0.4.12":{"node_abi":1,"v8":"3.1"},"0.5.0":{"node_abi":1,"v8":"3.1"},"0.5.1":{"node_abi":1,"v8":"3.4"},"0.5.2":{"node_abi":1,"v8":"3.4"},"0.5.3":{"node_abi":1,"v8":"3.4"},"0.5.4":{"node_abi":1,"v8":"3.5"},"0.5.5":{"node_abi":1,"v8":"3.5"},"0.5.6":{"node_abi":1,"v8":"3.6"},"0.5.7":{"node_abi":1,"v8":"3.6"},"0.5.8":{"node_abi":1,"v8":"3.6"},"0.5.9":{"node_abi":1,"v8":"3.6"},"0.5.10":{"node_abi":1,"v8":"3.7"},"0.6.0":{"node_abi":1,"v8":"3.6"},"0.6.1":{"node_abi":1,"v8":"3.6"},"0.6.2":{"node_abi":1,"v8":"3.6"},"0.6.3":{"node_abi":1,"v8":"3.6"},"0.6.4":{"node_abi":1,"v8":"3.6"},"0.6.5":{"node_abi":1,"v8":"3.6"},"0.6.6":{"node_abi":1,"v8":"3.6"},"0.6.7":{"node_abi":1,"v8":"3.6"},"0.6.8":{"node_abi":1,"v8":"3.6"},"0.6.9":{"node_abi":1,"v8":"3.6"},"0.6.10":{"node_abi":1,"v8":"3.6"},"0.6.11":{"node_abi":1,"v8":"3.6"},"0.6.12":{"node_abi":1,"v8":"3.6"},"0.6.13":{"node_abi":1,"v8":"3.6"},"0.6.14":{"node_abi":1,"v8":"3.6"},"0.6.15":{"node_abi":1,"v8":"3.6"},"0.6.16":{"node_abi":1,"v8":"3.6"},"0.6.17":{"node_abi":1,"v8":"3.6"},"0.6.18":{"node_abi":1,"v8":"3.6"},"0.6.19":{"node_abi":1,"v8":"3.6"},"0.6.20":{"node_abi":1,"v8":"3.6"},"0.6.21":{"node_abi":1,"v8":"3.6"},"0.7.0":{"node_abi":1,"v8":"3.8"},"0.7.1":{"node_abi":1,"v8":"3.8"},"0.7.2":{"node_abi":1,"v8":"3.8"},"0.7.3":{"node_abi":1,"v8":"3.9"},"0.7.4":{"node_abi":1,"v8":"3.9"},"0.7.5":{"node_abi":1,"v8":"3.9"},"0.7.6":{"node_abi":1,"v8":"3.9"},"0.7.7":{"node_abi":1,"v8":"3.9"},"0.7.8":{"node_abi":1,"v8":"3.9"},"0.7.9":{"node_abi":1,"v8":"3.11"},"0.7.10":{"node_abi":1,"v8":"3.9"},"0.7.11":{"node_abi":1,"v8":"3.11"},"0.7.12":{"node_abi":1,"v8":"3.11"},"0.8.0":{"node_abi":1,"v8":"3.11"},"0.8.1":{"node_abi":1,"v8":"3.11"},"0.8.2":{"node_abi":1,"v8":"3.11"},"0.8.3":{"node_abi":1,"v8":"3.11"},"0.8.4":{"node_abi":1,"v8":"3.11"},"0.8.5":{"node_abi":1,"v8":"3.11"},"0.8.6":{"node_abi":1,"v8":"3.11"},"0.8.7":{"node_abi":1,"v8":"3.11"},"0.8.8":{"node_abi":1,"v8":"3.11"},"0.8.9":{"node_abi":1,"v8":"3.11"},"0.8.10":{"node_abi":1,"v8":"3.11"},"0.8.11":{"node_abi":1,"v8":"3.11"},"0.8.12":{"node_abi":1,"v8":"3.11"},"0.8.13":{"node_abi":1,"v8":"3.11"},"0.8.14":{"node_abi":1,"v8":"3.11"},"0.8.15":{"node_abi":1,"v8":"3.11"},"0.8.16":{"node_abi":1,"v8":"3.11"},"0.8.17":{"node_abi":1,"v8":"3.11"},"0.8.18":{"node_abi":1,"v8":"3.11"},"0.8.19":{"node_abi":1,"v8":"3.11"},"0.8.20":{"node_abi":1,"v8":"3.11"},"0.8.21":{"node_abi":1,"v8":"3.11"},"0.8.22":{"node_abi":1,"v8":"3.11"},"0.8.23":{"node_abi":1,"v8":"3.11"},"0.8.24":{"node_abi":1,"v8":"3.11"},"0.8.25":{"node_abi":1,"v8":"3.11"},"0.8.26":{"node_abi":1,"v8":"3.11"},"0.8.27":{"node_abi":1,"v8":"3.11"},"0.8.28":{"node_abi":1,"v8":"3.11"},"0.9.0":{"node_abi":1,"v8":"3.11"},"0.9.1":{"node_abi":10,"v8":"3.11"},"0.9.2":{"node_abi":10,"v8":"3.11"},"0.9.3":{"node_abi":10,"v8":"3.13"},"0.9.4":{"node_abi":10,"v8":"3.13"},"0.9.5":{"node_abi":10,"v8":"3.13"},"0.9.6":{"node_abi":10,"v8":"3.15"},"0.9.7":{"node_abi":10,"v8":"3.15"},"0.9.8":{"node_abi":10,"v8":"3.15"},"0.9.9":{"node_abi":11,"v8":"3.15"},"0.9.10":{"node_abi":11,"v8":"3.15"},"0.9.11":{"node_abi":11,"v8":"3.14"},"0.9.12":{"node_abi":11,"v8":"3.14"},"0.10.0":{"node_abi":11,"v8":"3.14"},"0.10.1":{"node_abi":11,"v8":"3.14"},"0.10.2":{"node_abi":11,"v8":"3.14"},"0.10.3":{"node_abi":11,"v8":"3.14"},"0.10.4":{"node_abi":11,"v8":"3.14"},"0.10.5":{"node_abi":11,"v8":"3.14"},"0.10.6":{"node_abi":11,"v8":"3.14"},"0.10.7":{"node_abi":11,"v8":"3.14"},"0.10.8":{"node_abi":11,"v8":"3.14"},"0.10.9":{"node_abi":11,"v8":"3.14"},"0.10.10":{"node_abi":11,"v8":"3.14"},"0.10.11":{"node_abi":11,"v8":"3.14"},"0.10.12":{"node_abi":11,"v8":"3.14"},"0.10.13":{"node_abi":11,"v8":"3.14"},"0.10.14":{"node_abi":11,"v8":"3.14"},"0.10.15":{"node_abi":11,"v8":"3.14"},"0.10.16":{"node_abi":11,"v8":"3.14"},"0.10.17":{"node_abi":11,"v8":"3.14"},"0.10.18":{"node_abi":11,"v8":"3.14"},"0.10.19":{"node_abi":11,"v8":"3.14"},"0.10.20":{"node_abi":11,"v8":"3.14"},"0.10.21":{"node_abi":11,"v8":"3.14"},"0.10.22":{"node_abi":11,"v8":"3.14"},"0.10.23":{"node_abi":11,"v8":"3.14"},"0.10.24":{"node_abi":11,"v8":"3.14"},"0.10.25":{"node_abi":11,"v8":"3.14"},"0.10.26":{"node_abi":11,"v8":"3.14"},"0.10.27":{"node_abi":11,"v8":"3.14"},"0.10.28":{"node_abi":11,"v8":"3.14"},"0.10.29":{"node_abi":11,"v8":"3.14"},"0.10.30":{"node_abi":11,"v8":"3.14"},"0.10.31":{"node_abi":11,"v8":"3.14"},"0.10.32":{"node_abi":11,"v8":"3.14"},"0.10.33":{"node_abi":11,"v8":"3.14"},"0.10.34":{"node_abi":11,"v8":"3.14"},"0.10.35":{"node_abi":11,"v8":"3.14"},"0.10.36":{"node_abi":11,"v8":"3.14"},"0.10.37":{"node_abi":11,"v8":"3.14"},"0.10.38":{"node_abi":11,"v8":"3.14"},"0.10.39":{"node_abi":11,"v8":"3.14"},"0.10.40":{"node_abi":11,"v8":"3.14"},"0.10.41":{"node_abi":11,"v8":"3.14"},"0.10.42":{"node_abi":11,"v8":"3.14"},"0.10.43":{"node_abi":11,"v8":"3.14"},"0.10.44":{"node_abi":11,"v8":"3.14"},"0.10.45":{"node_abi":11,"v8":"3.14"},"0.10.46":{"node_abi":11,"v8":"3.14"},"0.10.47":{"node_abi":11,"v8":"3.14"},"0.10.48":{"node_abi":11,"v8":"3.14"},"0.11.0":{"node_abi":12,"v8":"3.17"},"0.11.1":{"node_abi":12,"v8":"3.18"},"0.11.2":{"node_abi":12,"v8":"3.19"},"0.11.3":{"node_abi":12,"v8":"3.19"},"0.11.4":{"node_abi":12,"v8":"3.20"},"0.11.5":{"node_abi":12,"v8":"3.20"},"0.11.6":{"node_abi":12,"v8":"3.20"},"0.11.7":{"node_abi":12,"v8":"3.20"},"0.11.8":{"node_abi":13,"v8":"3.21"},"0.11.9":{"node_abi":13,"v8":"3.22"},"0.11.10":{"node_abi":13,"v8":"3.22"},"0.11.11":{"node_abi":14,"v8":"3.22"},"0.11.12":{"node_abi":14,"v8":"3.22"},"0.11.13":{"node_abi":14,"v8":"3.25"},"0.11.14":{"node_abi":14,"v8":"3.26"},"0.11.15":{"node_abi":14,"v8":"3.28"},"0.11.16":{"node_abi":14,"v8":"3.28"},"0.12.0":{"node_abi":14,"v8":"3.28"},"0.12.1":{"node_abi":14,"v8":"3.28"},"0.12.2":{"node_abi":14,"v8":"3.28"},"0.12.3":{"node_abi":14,"v8":"3.28"},"0.12.4":{"node_abi":14,"v8":"3.28"},"0.12.5":{"node_abi":14,"v8":"3.28"},"0.12.6":{"node_abi":14,"v8":"3.28"},"0.12.7":{"node_abi":14,"v8":"3.28"},"0.12.8":{"node_abi":14,"v8":"3.28"},"0.12.9":{"node_abi":14,"v8":"3.28"},"0.12.10":{"node_abi":14,"v8":"3.28"},"0.12.11":{"node_abi":14,"v8":"3.28"},"0.12.12":{"node_abi":14,"v8":"3.28"},"0.12.13":{"node_abi":14,"v8":"3.28"},"0.12.14":{"node_abi":14,"v8":"3.28"},"0.12.15":{"node_abi":14,"v8":"3.28"},"0.12.16":{"node_abi":14,"v8":"3.28"},"0.12.17":{"node_abi":14,"v8":"3.28"},"0.12.18":{"node_abi":14,"v8":"3.28"},"1.0.0":{"node_abi":42,"v8":"3.31"},"1.0.1":{"node_abi":42,"v8":"3.31"},"1.0.2":{"node_abi":42,"v8":"3.31"},"1.0.3":{"node_abi":42,"v8":"4.1"},"1.0.4":{"node_abi":42,"v8":"4.1"},"1.1.0":{"node_abi":43,"v8":"4.1"},"1.2.0":{"node_abi":43,"v8":"4.1"},"1.3.0":{"node_abi":43,"v8":"4.1"},"1.4.1":{"node_abi":43,"v8":"4.1"},"1.4.2":{"node_abi":43,"v8":"4.1"},"1.4.3":{"node_abi":43,"v8":"4.1"},"1.5.0":{"node_abi":43,"v8":"4.1"},"1.5.1":{"node_abi":43,"v8":"4.1"},"1.6.0":{"node_abi":43,"v8":"4.1"},"1.6.1":{"node_abi":43,"v8":"4.1"},"1.6.2":{"node_abi":43,"v8":"4.1"},"1.6.3":{"node_abi":43,"v8":"4.1"},"1.6.4":{"node_abi":43,"v8":"4.1"},"1.7.1":{"node_abi":43,"v8":"4.1"},"1.8.1":{"node_abi":43,"v8":"4.1"},"1.8.2":{"node_abi":43,"v8":"4.1"},"1.8.3":{"node_abi":43,"v8":"4.1"},"1.8.4":{"node_abi":43,"v8":"4.1"},"2.0.0":{"node_abi":44,"v8":"4.2"},"2.0.1":{"node_abi":44,"v8":"4.2"},"2.0.2":{"node_abi":44,"v8":"4.2"},"2.1.0":{"node_abi":44,"v8":"4.2"},"2.2.0":{"node_abi":44,"v8":"4.2"},"2.2.1":{"node_abi":44,"v8":"4.2"},"2.3.0":{"node_abi":44,"v8":"4.2"},"2.3.1":{"node_abi":44,"v8":"4.2"},"2.3.2":{"node_abi":44,"v8":"4.2"},"2.3.3":{"node_abi":44,"v8":"4.2"},"2.3.4":{"node_abi":44,"v8":"4.2"},"2.4.0":{"node_abi":44,"v8":"4.2"},"2.5.0":{"node_abi":44,"v8":"4.2"},"3.0.0":{"node_abi":45,"v8":"4.4"},"3.1.0":{"node_abi":45,"v8":"4.4"},"3.2.0":{"node_abi":45,"v8":"4.4"},"3.3.0":{"node_abi":45,"v8":"4.4"},"3.3.1":{"node_abi":45,"v8":"4.4"},"4.0.0":{"node_abi":46,"v8":"4.5"},"4.1.0":{"node_abi":46,"v8":"4.5"},"4.1.1":{"node_abi":46,"v8":"4.5"},"4.1.2":{"node_abi":46,"v8":"4.5"},"4.2.0":{"node_abi":46,"v8":"4.5"},"4.2.1":{"node_abi":46,"v8":"4.5"},"4.2.2":{"node_abi":46,"v8":"4.5"},"4.2.3":{"node_abi":46,"v8":"4.5"},"4.2.4":{"node_abi":46,"v8":"4.5"},"4.2.5":{"node_abi":46,"v8":"4.5"},"4.2.6":{"node_abi":46,"v8":"4.5"},"4.3.0":{"node_abi":46,"v8":"4.5"},"4.3.1":{"node_abi":46,"v8":"4.5"},"4.3.2":{"node_abi":46,"v8":"4.5"},"4.4.0":{"node_abi":46,"v8":"4.5"},"4.4.1":{"node_abi":46,"v8":"4.5"},"4.4.2":{"node_abi":46,"v8":"4.5"},"4.4.3":{"node_abi":46,"v8":"4.5"},"4.4.4":{"node_abi":46,"v8":"4.5"},"4.4.5":{"node_abi":46,"v8":"4.5"},"4.4.6":{"node_abi":46,"v8":"4.5"},"4.4.7":{"node_abi":46,"v8":"4.5"},"4.5.0":{"node_abi":46,"v8":"4.5"},"4.6.0":{"node_abi":46,"v8":"4.5"},"4.6.1":{"node_abi":46,"v8":"4.5"},"4.6.2":{"node_abi":46,"v8":"4.5"},"4.7.0":{"node_abi":46,"v8":"4.5"},"4.7.1":{"node_abi":46,"v8":"4.5"},"4.7.2":{"node_abi":46,"v8":"4.5"},"4.7.3":{"node_abi":46,"v8":"4.5"},"4.8.0":{"node_abi":46,"v8":"4.5"},"4.8.1":{"node_abi":46,"v8":"4.5"},"4.8.2":{"node_abi":46,"v8":"4.5"},"4.8.3":{"node_abi":46,"v8":"4.5"},"4.8.4":{"node_abi":46,"v8":"4.5"},"4.8.5":{"node_abi":46,"v8":"4.5"},"4.8.6":{"node_abi":46,"v8":"4.5"},"4.8.7":{"node_abi":46,"v8":"4.5"},"4.9.0":{"node_abi":46,"v8":"4.5"},"4.9.1":{"node_abi":46,"v8":"4.5"},"5.0.0":{"node_abi":47,"v8":"4.6"},"5.1.0":{"node_abi":47,"v8":"4.6"},"5.1.1":{"node_abi":47,"v8":"4.6"},"5.2.0":{"node_abi":47,"v8":"4.6"},"5.3.0":{"node_abi":47,"v8":"4.6"},"5.4.0":{"node_abi":47,"v8":"4.6"},"5.4.1":{"node_abi":47,"v8":"4.6"},"5.5.0":{"node_abi":47,"v8":"4.6"},"5.6.0":{"node_abi":47,"v8":"4.6"},"5.7.0":{"node_abi":47,"v8":"4.6"},"5.7.1":{"node_abi":47,"v8":"4.6"},"5.8.0":{"node_abi":47,"v8":"4.6"},"5.9.0":{"node_abi":47,"v8":"4.6"},"5.9.1":{"node_abi":47,"v8":"4.6"},"5.10.0":{"node_abi":47,"v8":"4.6"},"5.10.1":{"node_abi":47,"v8":"4.6"},"5.11.0":{"node_abi":47,"v8":"4.6"},"5.11.1":{"node_abi":47,"v8":"4.6"},"5.12.0":{"node_abi":47,"v8":"4.6"},"6.0.0":{"node_abi":48,"v8":"5.0"},"6.1.0":{"node_abi":48,"v8":"5.0"},"6.2.0":{"node_abi":48,"v8":"5.0"},"6.2.1":{"node_abi":48,"v8":"5.0"},"6.2.2":{"node_abi":48,"v8":"5.0"},"6.3.0":{"node_abi":48,"v8":"5.0"},"6.3.1":{"node_abi":48,"v8":"5.0"},"6.4.0":{"node_abi":48,"v8":"5.0"},"6.5.0":{"node_abi":48,"v8":"5.1"},"6.6.0":{"node_abi":48,"v8":"5.1"},"6.7.0":{"node_abi":48,"v8":"5.1"},"6.8.0":{"node_abi":48,"v8":"5.1"},"6.8.1":{"node_abi":48,"v8":"5.1"},"6.9.0":{"node_abi":48,"v8":"5.1"},"6.9.1":{"node_abi":48,"v8":"5.1"},"6.9.2":{"node_abi":48,"v8":"5.1"},"6.9.3":{"node_abi":48,"v8":"5.1"},"6.9.4":{"node_abi":48,"v8":"5.1"},"6.9.5":{"node_abi":48,"v8":"5.1"},"6.10.0":{"node_abi":48,"v8":"5.1"},"6.10.1":{"node_abi":48,"v8":"5.1"},"6.10.2":{"node_abi":48,"v8":"5.1"},"6.10.3":{"node_abi":48,"v8":"5.1"},"6.11.0":{"node_abi":48,"v8":"5.1"},"6.11.1":{"node_abi":48,"v8":"5.1"},"6.11.2":{"node_abi":48,"v8":"5.1"},"6.11.3":{"node_abi":48,"v8":"5.1"},"6.11.4":{"node_abi":48,"v8":"5.1"},"6.11.5":{"node_abi":48,"v8":"5.1"},"6.12.0":{"node_abi":48,"v8":"5.1"},"6.12.1":{"node_abi":48,"v8":"5.1"},"6.12.2":{"node_abi":48,"v8":"5.1"},"6.12.3":{"node_abi":48,"v8":"5.1"},"6.13.0":{"node_abi":48,"v8":"5.1"},"6.13.1":{"node_abi":48,"v8":"5.1"},"6.14.0":{"node_abi":48,"v8":"5.1"},"6.14.1":{"node_abi":48,"v8":"5.1"},"6.14.2":{"node_abi":48,"v8":"5.1"},"6.14.3":{"node_abi":48,"v8":"5.1"},"6.14.4":{"node_abi":48,"v8":"5.1"},"6.15.0":{"node_abi":48,"v8":"5.1"},"6.15.1":{"node_abi":48,"v8":"5.1"},"6.16.0":{"node_abi":48,"v8":"5.1"},"6.17.0":{"node_abi":48,"v8":"5.1"},"6.17.1":{"node_abi":48,"v8":"5.1"},"7.0.0":{"node_abi":51,"v8":"5.4"},"7.1.0":{"node_abi":51,"v8":"5.4"},"7.2.0":{"node_abi":51,"v8":"5.4"},"7.2.1":{"node_abi":51,"v8":"5.4"},"7.3.0":{"node_abi":51,"v8":"5.4"},"7.4.0":{"node_abi":51,"v8":"5.4"},"7.5.0":{"node_abi":51,"v8":"5.4"},"7.6.0":{"node_abi":51,"v8":"5.5"},"7.7.0":{"node_abi":51,"v8":"5.5"},"7.7.1":{"node_abi":51,"v8":"5.5"},"7.7.2":{"node_abi":51,"v8":"5.5"},"7.7.3":{"node_abi":51,"v8":"5.5"},"7.7.4":{"node_abi":51,"v8":"5.5"},"7.8.0":{"node_abi":51,"v8":"5.5"},"7.9.0":{"node_abi":51,"v8":"5.5"},"7.10.0":{"node_abi":51,"v8":"5.5"},"7.10.1":{"node_abi":51,"v8":"5.5"},"8.0.0":{"node_abi":57,"v8":"5.8"},"8.1.0":{"node_abi":57,"v8":"5.8"},"8.1.1":{"node_abi":57,"v8":"5.8"},"8.1.2":{"node_abi":57,"v8":"5.8"},"8.1.3":{"node_abi":57,"v8":"5.8"},"8.1.4":{"node_abi":57,"v8":"5.8"},"8.2.0":{"node_abi":57,"v8":"5.8"},"8.2.1":{"node_abi":57,"v8":"5.8"},"8.3.0":{"node_abi":57,"v8":"6.0"},"8.4.0":{"node_abi":57,"v8":"6.0"},"8.5.0":{"node_abi":57,"v8":"6.0"},"8.6.0":{"node_abi":57,"v8":"6.0"},"8.7.0":{"node_abi":57,"v8":"6.1"},"8.8.0":{"node_abi":57,"v8":"6.1"},"8.8.1":{"node_abi":57,"v8":"6.1"},"8.9.0":{"node_abi":57,"v8":"6.1"},"8.9.1":{"node_abi":57,"v8":"6.1"},"8.9.2":{"node_abi":57,"v8":"6.1"},"8.9.3":{"node_abi":57,"v8":"6.1"},"8.9.4":{"node_abi":57,"v8":"6.1"},"8.10.0":{"node_abi":57,"v8":"6.2"},"8.11.0":{"node_abi":57,"v8":"6.2"},"8.11.1":{"node_abi":57,"v8":"6.2"},"8.11.2":{"node_abi":57,"v8":"6.2"},"8.11.3":{"node_abi":57,"v8":"6.2"},"8.11.4":{"node_abi":57,"v8":"6.2"},"8.12.0":{"node_abi":57,"v8":"6.2"},"8.13.0":{"node_abi":57,"v8":"6.2"},"8.14.0":{"node_abi":57,"v8":"6.2"},"8.14.1":{"node_abi":57,"v8":"6.2"},"8.15.0":{"node_abi":57,"v8":"6.2"},"8.15.1":{"node_abi":57,"v8":"6.2"},"8.16.0":{"node_abi":57,"v8":"6.2"},"8.16.1":{"node_abi":57,"v8":"6.2"},"8.16.2":{"node_abi":57,"v8":"6.2"},"8.17.0":{"node_abi":57,"v8":"6.2"},"9.0.0":{"node_abi":59,"v8":"6.2"},"9.1.0":{"node_abi":59,"v8":"6.2"},"9.2.0":{"node_abi":59,"v8":"6.2"},"9.2.1":{"node_abi":59,"v8":"6.2"},"9.3.0":{"node_abi":59,"v8":"6.2"},"9.4.0":{"node_abi":59,"v8":"6.2"},"9.5.0":{"node_abi":59,"v8":"6.2"},"9.6.0":{"node_abi":59,"v8":"6.2"},"9.6.1":{"node_abi":59,"v8":"6.2"},"9.7.0":{"node_abi":59,"v8":"6.2"},"9.7.1":{"node_abi":59,"v8":"6.2"},"9.8.0":{"node_abi":59,"v8":"6.2"},"9.9.0":{"node_abi":59,"v8":"6.2"},"9.10.0":{"node_abi":59,"v8":"6.2"},"9.10.1":{"node_abi":59,"v8":"6.2"},"9.11.0":{"node_abi":59,"v8":"6.2"},"9.11.1":{"node_abi":59,"v8":"6.2"},"9.11.2":{"node_abi":59,"v8":"6.2"},"10.0.0":{"node_abi":64,"v8":"6.6"},"10.1.0":{"node_abi":64,"v8":"6.6"},"10.2.0":{"node_abi":64,"v8":"6.6"},"10.2.1":{"node_abi":64,"v8":"6.6"},"10.3.0":{"node_abi":64,"v8":"6.6"},"10.4.0":{"node_abi":64,"v8":"6.7"},"10.4.1":{"node_abi":64,"v8":"6.7"},"10.5.0":{"node_abi":64,"v8":"6.7"},"10.6.0":{"node_abi":64,"v8":"6.7"},"10.7.0":{"node_abi":64,"v8":"6.7"},"10.8.0":{"node_abi":64,"v8":"6.7"},"10.9.0":{"node_abi":64,"v8":"6.8"},"10.10.0":{"node_abi":64,"v8":"6.8"},"10.11.0":{"node_abi":64,"v8":"6.8"},"10.12.0":{"node_abi":64,"v8":"6.8"},"10.13.0":{"node_abi":64,"v8":"6.8"},"10.14.0":{"node_abi":64,"v8":"6.8"},"10.14.1":{"node_abi":64,"v8":"6.8"},"10.14.2":{"node_abi":64,"v8":"6.8"},"10.15.0":{"node_abi":64,"v8":"6.8"},"10.15.1":{"node_abi":64,"v8":"6.8"},"10.15.2":{"node_abi":64,"v8":"6.8"},"10.15.3":{"node_abi":64,"v8":"6.8"},"10.16.0":{"node_abi":64,"v8":"6.8"},"10.16.1":{"node_abi":64,"v8":"6.8"},"10.16.2":{"node_abi":64,"v8":"6.8"},"10.16.3":{"node_abi":64,"v8":"6.8"},"10.17.0":{"node_abi":64,"v8":"6.8"},"10.18.0":{"node_abi":64,"v8":"6.8"},"10.18.1":{"node_abi":64,"v8":"6.8"},"10.19.0":{"node_abi":64,"v8":"6.8"},"10.20.0":{"node_abi":64,"v8":"6.8"},"10.20.1":{"node_abi":64,"v8":"6.8"},"10.21.0":{"node_abi":64,"v8":"6.8"},"10.22.0":{"node_abi":64,"v8":"6.8"},"10.22.1":{"node_abi":64,"v8":"6.8"},"10.23.0":{"node_abi":64,"v8":"6.8"},"10.23.1":{"node_abi":64,"v8":"6.8"},"10.23.2":{"node_abi":64,"v8":"6.8"},"10.23.3":{"node_abi":64,"v8":"6.8"},"10.24.0":{"node_abi":64,"v8":"6.8"},"10.24.1":{"node_abi":64,"v8":"6.8"},"11.0.0":{"node_abi":67,"v8":"7.0"},"11.1.0":{"node_abi":67,"v8":"7.0"},"11.2.0":{"node_abi":67,"v8":"7.0"},"11.3.0":{"node_abi":67,"v8":"7.0"},"11.4.0":{"node_abi":67,"v8":"7.0"},"11.5.0":{"node_abi":67,"v8":"7.0"},"11.6.0":{"node_abi":67,"v8":"7.0"},"11.7.0":{"node_abi":67,"v8":"7.0"},"11.8.0":{"node_abi":67,"v8":"7.0"},"11.9.0":{"node_abi":67,"v8":"7.0"},"11.10.0":{"node_abi":67,"v8":"7.0"},"11.10.1":{"node_abi":67,"v8":"7.0"},"11.11.0":{"node_abi":67,"v8":"7.0"},"11.12.0":{"node_abi":67,"v8":"7.0"},"11.13.0":{"node_abi":67,"v8":"7.0"},"11.14.0":{"node_abi":67,"v8":"7.0"},"11.15.0":{"node_abi":67,"v8":"7.0"},"12.0.0":{"node_abi":72,"v8":"7.4"},"12.1.0":{"node_abi":72,"v8":"7.4"},"12.2.0":{"node_abi":72,"v8":"7.4"},"12.3.0":{"node_abi":72,"v8":"7.4"},"12.3.1":{"node_abi":72,"v8":"7.4"},"12.4.0":{"node_abi":72,"v8":"7.4"},"12.5.0":{"node_abi":72,"v8":"7.5"},"12.6.0":{"node_abi":72,"v8":"7.5"},"12.7.0":{"node_abi":72,"v8":"7.5"},"12.8.0":{"node_abi":72,"v8":"7.5"},"12.8.1":{"node_abi":72,"v8":"7.5"},"12.9.0":{"node_abi":72,"v8":"7.6"},"12.9.1":{"node_abi":72,"v8":"7.6"},"12.10.0":{"node_abi":72,"v8":"7.6"},"12.11.0":{"node_abi":72,"v8":"7.7"},"12.11.1":{"node_abi":72,"v8":"7.7"},"12.12.0":{"node_abi":72,"v8":"7.7"},"12.13.0":{"node_abi":72,"v8":"7.7"},"12.13.1":{"node_abi":72,"v8":"7.7"},"12.14.0":{"node_abi":72,"v8":"7.7"},"12.14.1":{"node_abi":72,"v8":"7.7"},"12.15.0":{"node_abi":72,"v8":"7.7"},"12.16.0":{"node_abi":72,"v8":"7.8"},"12.16.1":{"node_abi":72,"v8":"7.8"},"12.16.2":{"node_abi":72,"v8":"7.8"},"12.16.3":{"node_abi":72,"v8":"7.8"},"12.17.0":{"node_abi":72,"v8":"7.8"},"12.18.0":{"node_abi":72,"v8":"7.8"},"12.18.1":{"node_abi":72,"v8":"7.8"},"12.18.2":{"node_abi":72,"v8":"7.8"},"12.18.3":{"node_abi":72,"v8":"7.8"},"12.18.4":{"node_abi":72,"v8":"7.8"},"12.19.0":{"node_abi":72,"v8":"7.8"},"12.19.1":{"node_abi":72,"v8":"7.8"},"12.20.0":{"node_abi":72,"v8":"7.8"},"12.20.1":{"node_abi":72,"v8":"7.8"},"12.20.2":{"node_abi":72,"v8":"7.8"},"12.21.0":{"node_abi":72,"v8":"7.8"},"12.22.0":{"node_abi":72,"v8":"7.8"},"12.22.1":{"node_abi":72,"v8":"7.8"},"13.0.0":{"node_abi":79,"v8":"7.8"},"13.0.1":{"node_abi":79,"v8":"7.8"},"13.1.0":{"node_abi":79,"v8":"7.8"},"13.2.0":{"node_abi":79,"v8":"7.9"},"13.3.0":{"node_abi":79,"v8":"7.9"},"13.4.0":{"node_abi":79,"v8":"7.9"},"13.5.0":{"node_abi":79,"v8":"7.9"},"13.6.0":{"node_abi":79,"v8":"7.9"},"13.7.0":{"node_abi":79,"v8":"7.9"},"13.8.0":{"node_abi":79,"v8":"7.9"},"13.9.0":{"node_abi":79,"v8":"7.9"},"13.10.0":{"node_abi":79,"v8":"7.9"},"13.10.1":{"node_abi":79,"v8":"7.9"},"13.11.0":{"node_abi":79,"v8":"7.9"},"13.12.0":{"node_abi":79,"v8":"7.9"},"13.13.0":{"node_abi":79,"v8":"7.9"},"13.14.0":{"node_abi":79,"v8":"7.9"},"14.0.0":{"node_abi":83,"v8":"8.1"},"14.1.0":{"node_abi":83,"v8":"8.1"},"14.2.0":{"node_abi":83,"v8":"8.1"},"14.3.0":{"node_abi":83,"v8":"8.1"},"14.4.0":{"node_abi":83,"v8":"8.1"},"14.5.0":{"node_abi":83,"v8":"8.3"},"14.6.0":{"node_abi":83,"v8":"8.4"},"14.7.0":{"node_abi":83,"v8":"8.4"},"14.8.0":{"node_abi":83,"v8":"8.4"},"14.9.0":{"node_abi":83,"v8":"8.4"},"14.10.0":{"node_abi":83,"v8":"8.4"},"14.10.1":{"node_abi":83,"v8":"8.4"},"14.11.0":{"node_abi":83,"v8":"8.4"},"14.12.0":{"node_abi":83,"v8":"8.4"},"14.13.0":{"node_abi":83,"v8":"8.4"},"14.13.1":{"node_abi":83,"v8":"8.4"},"14.14.0":{"node_abi":83,"v8":"8.4"},"14.15.0":{"node_abi":83,"v8":"8.4"},"14.15.1":{"node_abi":83,"v8":"8.4"},"14.15.2":{"node_abi":83,"v8":"8.4"},"14.15.3":{"node_abi":83,"v8":"8.4"},"14.15.4":{"node_abi":83,"v8":"8.4"},"14.15.5":{"node_abi":83,"v8":"8.4"},"14.16.0":{"node_abi":83,"v8":"8.4"},"14.16.1":{"node_abi":83,"v8":"8.4"},"15.0.0":{"node_abi":88,"v8":"8.6"},"15.0.1":{"node_abi":88,"v8":"8.6"},"15.1.0":{"node_abi":88,"v8":"8.6"},"15.2.0":{"node_abi":88,"v8":"8.6"},"15.2.1":{"node_abi":88,"v8":"8.6"},"15.3.0":{"node_abi":88,"v8":"8.6"},"15.4.0":{"node_abi":88,"v8":"8.6"},"15.5.0":{"node_abi":88,"v8":"8.6"},"15.5.1":{"node_abi":88,"v8":"8.6"},"15.6.0":{"node_abi":88,"v8":"8.6"},"15.7.0":{"node_abi":88,"v8":"8.6"},"15.8.0":{"node_abi":88,"v8":"8.6"},"15.9.0":{"node_abi":88,"v8":"8.6"},"15.10.0":{"node_abi":88,"v8":"8.6"},"15.11.0":{"node_abi":88,"v8":"8.6"},"15.12.0":{"node_abi":88,"v8":"8.6"},"15.13.0":{"node_abi":88,"v8":"8.6"},"15.14.0":{"node_abi":88,"v8":"8.6"},"16.0.0":{"node_abi":93,"v8":"9.0"}}')},9286:e=>{"use strict";e.exports=JSON.parse('{"name":"@mapbox/node-pre-gyp","description":"Node.js native addon binary install tool","version":"1.0.5","keywords":["native","addon","module","c","c++","bindings","binary"],"license":"BSD-3-Clause","author":"Dane Springmeyer ","repository":{"type":"git","url":"git://github.com/mapbox/node-pre-gyp.git"},"bin":"./bin/node-pre-gyp","main":"./lib/node-pre-gyp.js","dependencies":{"detect-libc":"^1.0.3","https-proxy-agent":"^5.0.0","make-dir":"^3.1.0","node-fetch":"^2.6.1","nopt":"^5.0.0","npmlog":"^4.1.2","rimraf":"^3.0.2","semver":"^7.3.4","tar":"^6.1.0"},"devDependencies":{"@mapbox/cloudfriend":"^4.6.0","@mapbox/eslint-config-mapbox":"^3.0.0","action-walk":"^2.2.0","aws-sdk":"^2.840.0","codecov":"^3.8.1","eslint":"^7.18.0","eslint-plugin-node":"^11.1.0","mock-aws-s3":"^4.0.1","nock":"^12.0.3","node-addon-api":"^3.1.0","nyc":"^15.1.0","tape":"^5.2.2","tar-fs":"^2.1.1"},"nyc":{"all":true,"skip-full":false,"exclude":["test/**"]},"scripts":{"coverage":"nyc --all --include index.js --include lib/ npm test","upload-coverage":"nyc report --reporter json && codecov --clear --flags=unit --file=./coverage/coverage-final.json","lint":"eslint bin/node-pre-gyp lib/*js lib/util/*js test/*js scripts/*js","fix":"npm run lint -- --fix","update-crosswalk":"node scripts/abi_crosswalk.js","test":"tape test/*test.js"}}')},7316:e=>{"use strict";e.exports=JSON.parse('{"0.1.14":{"node_abi":null,"v8":"1.3"},"0.1.15":{"node_abi":null,"v8":"1.3"},"0.1.16":{"node_abi":null,"v8":"1.3"},"0.1.17":{"node_abi":null,"v8":"1.3"},"0.1.18":{"node_abi":null,"v8":"1.3"},"0.1.19":{"node_abi":null,"v8":"2.0"},"0.1.20":{"node_abi":null,"v8":"2.0"},"0.1.21":{"node_abi":null,"v8":"2.0"},"0.1.22":{"node_abi":null,"v8":"2.0"},"0.1.23":{"node_abi":null,"v8":"2.0"},"0.1.24":{"node_abi":null,"v8":"2.0"},"0.1.25":{"node_abi":null,"v8":"2.0"},"0.1.26":{"node_abi":null,"v8":"2.0"},"0.1.27":{"node_abi":null,"v8":"2.1"},"0.1.28":{"node_abi":null,"v8":"2.1"},"0.1.29":{"node_abi":null,"v8":"2.1"},"0.1.30":{"node_abi":null,"v8":"2.1"},"0.1.31":{"node_abi":null,"v8":"2.1"},"0.1.32":{"node_abi":null,"v8":"2.1"},"0.1.33":{"node_abi":null,"v8":"2.1"},"0.1.90":{"node_abi":null,"v8":"2.2"},"0.1.91":{"node_abi":null,"v8":"2.2"},"0.1.92":{"node_abi":null,"v8":"2.2"},"0.1.93":{"node_abi":null,"v8":"2.2"},"0.1.94":{"node_abi":null,"v8":"2.2"},"0.1.95":{"node_abi":null,"v8":"2.2"},"0.1.96":{"node_abi":null,"v8":"2.2"},"0.1.97":{"node_abi":null,"v8":"2.2"},"0.1.98":{"node_abi":null,"v8":"2.2"},"0.1.99":{"node_abi":null,"v8":"2.2"},"0.1.100":{"node_abi":null,"v8":"2.2"},"0.1.101":{"node_abi":null,"v8":"2.3"},"0.1.102":{"node_abi":null,"v8":"2.3"},"0.1.103":{"node_abi":null,"v8":"2.3"},"0.1.104":{"node_abi":null,"v8":"2.3"},"0.2.0":{"node_abi":1,"v8":"2.3"},"0.2.1":{"node_abi":1,"v8":"2.3"},"0.2.2":{"node_abi":1,"v8":"2.3"},"0.2.3":{"node_abi":1,"v8":"2.3"},"0.2.4":{"node_abi":1,"v8":"2.3"},"0.2.5":{"node_abi":1,"v8":"2.3"},"0.2.6":{"node_abi":1,"v8":"2.3"},"0.3.0":{"node_abi":1,"v8":"2.5"},"0.3.1":{"node_abi":1,"v8":"2.5"},"0.3.2":{"node_abi":1,"v8":"3.0"},"0.3.3":{"node_abi":1,"v8":"3.0"},"0.3.4":{"node_abi":1,"v8":"3.0"},"0.3.5":{"node_abi":1,"v8":"3.0"},"0.3.6":{"node_abi":1,"v8":"3.0"},"0.3.7":{"node_abi":1,"v8":"3.0"},"0.3.8":{"node_abi":1,"v8":"3.1"},"0.4.0":{"node_abi":1,"v8":"3.1"},"0.4.1":{"node_abi":1,"v8":"3.1"},"0.4.2":{"node_abi":1,"v8":"3.1"},"0.4.3":{"node_abi":1,"v8":"3.1"},"0.4.4":{"node_abi":1,"v8":"3.1"},"0.4.5":{"node_abi":1,"v8":"3.1"},"0.4.6":{"node_abi":1,"v8":"3.1"},"0.4.7":{"node_abi":1,"v8":"3.1"},"0.4.8":{"node_abi":1,"v8":"3.1"},"0.4.9":{"node_abi":1,"v8":"3.1"},"0.4.10":{"node_abi":1,"v8":"3.1"},"0.4.11":{"node_abi":1,"v8":"3.1"},"0.4.12":{"node_abi":1,"v8":"3.1"},"0.5.0":{"node_abi":1,"v8":"3.1"},"0.5.1":{"node_abi":1,"v8":"3.4"},"0.5.2":{"node_abi":1,"v8":"3.4"},"0.5.3":{"node_abi":1,"v8":"3.4"},"0.5.4":{"node_abi":1,"v8":"3.5"},"0.5.5":{"node_abi":1,"v8":"3.5"},"0.5.6":{"node_abi":1,"v8":"3.6"},"0.5.7":{"node_abi":1,"v8":"3.6"},"0.5.8":{"node_abi":1,"v8":"3.6"},"0.5.9":{"node_abi":1,"v8":"3.6"},"0.5.10":{"node_abi":1,"v8":"3.7"},"0.6.0":{"node_abi":1,"v8":"3.6"},"0.6.1":{"node_abi":1,"v8":"3.6"},"0.6.2":{"node_abi":1,"v8":"3.6"},"0.6.3":{"node_abi":1,"v8":"3.6"},"0.6.4":{"node_abi":1,"v8":"3.6"},"0.6.5":{"node_abi":1,"v8":"3.6"},"0.6.6":{"node_abi":1,"v8":"3.6"},"0.6.7":{"node_abi":1,"v8":"3.6"},"0.6.8":{"node_abi":1,"v8":"3.6"},"0.6.9":{"node_abi":1,"v8":"3.6"},"0.6.10":{"node_abi":1,"v8":"3.6"},"0.6.11":{"node_abi":1,"v8":"3.6"},"0.6.12":{"node_abi":1,"v8":"3.6"},"0.6.13":{"node_abi":1,"v8":"3.6"},"0.6.14":{"node_abi":1,"v8":"3.6"},"0.6.15":{"node_abi":1,"v8":"3.6"},"0.6.16":{"node_abi":1,"v8":"3.6"},"0.6.17":{"node_abi":1,"v8":"3.6"},"0.6.18":{"node_abi":1,"v8":"3.6"},"0.6.19":{"node_abi":1,"v8":"3.6"},"0.6.20":{"node_abi":1,"v8":"3.6"},"0.6.21":{"node_abi":1,"v8":"3.6"},"0.7.0":{"node_abi":1,"v8":"3.8"},"0.7.1":{"node_abi":1,"v8":"3.8"},"0.7.2":{"node_abi":1,"v8":"3.8"},"0.7.3":{"node_abi":1,"v8":"3.9"},"0.7.4":{"node_abi":1,"v8":"3.9"},"0.7.5":{"node_abi":1,"v8":"3.9"},"0.7.6":{"node_abi":1,"v8":"3.9"},"0.7.7":{"node_abi":1,"v8":"3.9"},"0.7.8":{"node_abi":1,"v8":"3.9"},"0.7.9":{"node_abi":1,"v8":"3.11"},"0.7.10":{"node_abi":1,"v8":"3.9"},"0.7.11":{"node_abi":1,"v8":"3.11"},"0.7.12":{"node_abi":1,"v8":"3.11"},"0.8.0":{"node_abi":1,"v8":"3.11"},"0.8.1":{"node_abi":1,"v8":"3.11"},"0.8.2":{"node_abi":1,"v8":"3.11"},"0.8.3":{"node_abi":1,"v8":"3.11"},"0.8.4":{"node_abi":1,"v8":"3.11"},"0.8.5":{"node_abi":1,"v8":"3.11"},"0.8.6":{"node_abi":1,"v8":"3.11"},"0.8.7":{"node_abi":1,"v8":"3.11"},"0.8.8":{"node_abi":1,"v8":"3.11"},"0.8.9":{"node_abi":1,"v8":"3.11"},"0.8.10":{"node_abi":1,"v8":"3.11"},"0.8.11":{"node_abi":1,"v8":"3.11"},"0.8.12":{"node_abi":1,"v8":"3.11"},"0.8.13":{"node_abi":1,"v8":"3.11"},"0.8.14":{"node_abi":1,"v8":"3.11"},"0.8.15":{"node_abi":1,"v8":"3.11"},"0.8.16":{"node_abi":1,"v8":"3.11"},"0.8.17":{"node_abi":1,"v8":"3.11"},"0.8.18":{"node_abi":1,"v8":"3.11"},"0.8.19":{"node_abi":1,"v8":"3.11"},"0.8.20":{"node_abi":1,"v8":"3.11"},"0.8.21":{"node_abi":1,"v8":"3.11"},"0.8.22":{"node_abi":1,"v8":"3.11"},"0.8.23":{"node_abi":1,"v8":"3.11"},"0.8.24":{"node_abi":1,"v8":"3.11"},"0.8.25":{"node_abi":1,"v8":"3.11"},"0.8.26":{"node_abi":1,"v8":"3.11"},"0.8.27":{"node_abi":1,"v8":"3.11"},"0.8.28":{"node_abi":1,"v8":"3.11"},"0.9.0":{"node_abi":1,"v8":"3.11"},"0.9.1":{"node_abi":10,"v8":"3.11"},"0.9.2":{"node_abi":10,"v8":"3.11"},"0.9.3":{"node_abi":10,"v8":"3.13"},"0.9.4":{"node_abi":10,"v8":"3.13"},"0.9.5":{"node_abi":10,"v8":"3.13"},"0.9.6":{"node_abi":10,"v8":"3.15"},"0.9.7":{"node_abi":10,"v8":"3.15"},"0.9.8":{"node_abi":10,"v8":"3.15"},"0.9.9":{"node_abi":11,"v8":"3.15"},"0.9.10":{"node_abi":11,"v8":"3.15"},"0.9.11":{"node_abi":11,"v8":"3.14"},"0.9.12":{"node_abi":11,"v8":"3.14"},"0.10.0":{"node_abi":11,"v8":"3.14"},"0.10.1":{"node_abi":11,"v8":"3.14"},"0.10.2":{"node_abi":11,"v8":"3.14"},"0.10.3":{"node_abi":11,"v8":"3.14"},"0.10.4":{"node_abi":11,"v8":"3.14"},"0.10.5":{"node_abi":11,"v8":"3.14"},"0.10.6":{"node_abi":11,"v8":"3.14"},"0.10.7":{"node_abi":11,"v8":"3.14"},"0.10.8":{"node_abi":11,"v8":"3.14"},"0.10.9":{"node_abi":11,"v8":"3.14"},"0.10.10":{"node_abi":11,"v8":"3.14"},"0.10.11":{"node_abi":11,"v8":"3.14"},"0.10.12":{"node_abi":11,"v8":"3.14"},"0.10.13":{"node_abi":11,"v8":"3.14"},"0.10.14":{"node_abi":11,"v8":"3.14"},"0.10.15":{"node_abi":11,"v8":"3.14"},"0.10.16":{"node_abi":11,"v8":"3.14"},"0.10.17":{"node_abi":11,"v8":"3.14"},"0.10.18":{"node_abi":11,"v8":"3.14"},"0.10.19":{"node_abi":11,"v8":"3.14"},"0.10.20":{"node_abi":11,"v8":"3.14"},"0.10.21":{"node_abi":11,"v8":"3.14"},"0.10.22":{"node_abi":11,"v8":"3.14"},"0.10.23":{"node_abi":11,"v8":"3.14"},"0.10.24":{"node_abi":11,"v8":"3.14"},"0.10.25":{"node_abi":11,"v8":"3.14"},"0.10.26":{"node_abi":11,"v8":"3.14"},"0.10.27":{"node_abi":11,"v8":"3.14"},"0.10.28":{"node_abi":11,"v8":"3.14"},"0.10.29":{"node_abi":11,"v8":"3.14"},"0.10.30":{"node_abi":11,"v8":"3.14"},"0.10.31":{"node_abi":11,"v8":"3.14"},"0.10.32":{"node_abi":11,"v8":"3.14"},"0.10.33":{"node_abi":11,"v8":"3.14"},"0.10.34":{"node_abi":11,"v8":"3.14"},"0.10.35":{"node_abi":11,"v8":"3.14"},"0.10.36":{"node_abi":11,"v8":"3.14"},"0.10.37":{"node_abi":11,"v8":"3.14"},"0.10.38":{"node_abi":11,"v8":"3.14"},"0.10.39":{"node_abi":11,"v8":"3.14"},"0.10.40":{"node_abi":11,"v8":"3.14"},"0.10.41":{"node_abi":11,"v8":"3.14"},"0.10.42":{"node_abi":11,"v8":"3.14"},"0.10.43":{"node_abi":11,"v8":"3.14"},"0.10.44":{"node_abi":11,"v8":"3.14"},"0.10.45":{"node_abi":11,"v8":"3.14"},"0.10.46":{"node_abi":11,"v8":"3.14"},"0.10.47":{"node_abi":11,"v8":"3.14"},"0.10.48":{"node_abi":11,"v8":"3.14"},"0.11.0":{"node_abi":12,"v8":"3.17"},"0.11.1":{"node_abi":12,"v8":"3.18"},"0.11.2":{"node_abi":12,"v8":"3.19"},"0.11.3":{"node_abi":12,"v8":"3.19"},"0.11.4":{"node_abi":12,"v8":"3.20"},"0.11.5":{"node_abi":12,"v8":"3.20"},"0.11.6":{"node_abi":12,"v8":"3.20"},"0.11.7":{"node_abi":12,"v8":"3.20"},"0.11.8":{"node_abi":13,"v8":"3.21"},"0.11.9":{"node_abi":13,"v8":"3.22"},"0.11.10":{"node_abi":13,"v8":"3.22"},"0.11.11":{"node_abi":14,"v8":"3.22"},"0.11.12":{"node_abi":14,"v8":"3.22"},"0.11.13":{"node_abi":14,"v8":"3.25"},"0.11.14":{"node_abi":14,"v8":"3.26"},"0.11.15":{"node_abi":14,"v8":"3.28"},"0.11.16":{"node_abi":14,"v8":"3.28"},"0.12.0":{"node_abi":14,"v8":"3.28"},"0.12.1":{"node_abi":14,"v8":"3.28"},"0.12.2":{"node_abi":14,"v8":"3.28"},"0.12.3":{"node_abi":14,"v8":"3.28"},"0.12.4":{"node_abi":14,"v8":"3.28"},"0.12.5":{"node_abi":14,"v8":"3.28"},"0.12.6":{"node_abi":14,"v8":"3.28"},"0.12.7":{"node_abi":14,"v8":"3.28"},"0.12.8":{"node_abi":14,"v8":"3.28"},"0.12.9":{"node_abi":14,"v8":"3.28"},"0.12.10":{"node_abi":14,"v8":"3.28"},"0.12.11":{"node_abi":14,"v8":"3.28"},"0.12.12":{"node_abi":14,"v8":"3.28"},"0.12.13":{"node_abi":14,"v8":"3.28"},"0.12.14":{"node_abi":14,"v8":"3.28"},"0.12.15":{"node_abi":14,"v8":"3.28"},"0.12.16":{"node_abi":14,"v8":"3.28"},"0.12.17":{"node_abi":14,"v8":"3.28"},"0.12.18":{"node_abi":14,"v8":"3.28"},"1.0.0":{"node_abi":42,"v8":"3.31"},"1.0.1":{"node_abi":42,"v8":"3.31"},"1.0.2":{"node_abi":42,"v8":"3.31"},"1.0.3":{"node_abi":42,"v8":"4.1"},"1.0.4":{"node_abi":42,"v8":"4.1"},"1.1.0":{"node_abi":43,"v8":"4.1"},"1.2.0":{"node_abi":43,"v8":"4.1"},"1.3.0":{"node_abi":43,"v8":"4.1"},"1.4.1":{"node_abi":43,"v8":"4.1"},"1.4.2":{"node_abi":43,"v8":"4.1"},"1.4.3":{"node_abi":43,"v8":"4.1"},"1.5.0":{"node_abi":43,"v8":"4.1"},"1.5.1":{"node_abi":43,"v8":"4.1"},"1.6.0":{"node_abi":43,"v8":"4.1"},"1.6.1":{"node_abi":43,"v8":"4.1"},"1.6.2":{"node_abi":43,"v8":"4.1"},"1.6.3":{"node_abi":43,"v8":"4.1"},"1.6.4":{"node_abi":43,"v8":"4.1"},"1.7.1":{"node_abi":43,"v8":"4.1"},"1.8.1":{"node_abi":43,"v8":"4.1"},"1.8.2":{"node_abi":43,"v8":"4.1"},"1.8.3":{"node_abi":43,"v8":"4.1"},"1.8.4":{"node_abi":43,"v8":"4.1"},"2.0.0":{"node_abi":44,"v8":"4.2"},"2.0.1":{"node_abi":44,"v8":"4.2"},"2.0.2":{"node_abi":44,"v8":"4.2"},"2.1.0":{"node_abi":44,"v8":"4.2"},"2.2.0":{"node_abi":44,"v8":"4.2"},"2.2.1":{"node_abi":44,"v8":"4.2"},"2.3.0":{"node_abi":44,"v8":"4.2"},"2.3.1":{"node_abi":44,"v8":"4.2"},"2.3.2":{"node_abi":44,"v8":"4.2"},"2.3.3":{"node_abi":44,"v8":"4.2"},"2.3.4":{"node_abi":44,"v8":"4.2"},"2.4.0":{"node_abi":44,"v8":"4.2"},"2.5.0":{"node_abi":44,"v8":"4.2"},"3.0.0":{"node_abi":45,"v8":"4.4"},"3.1.0":{"node_abi":45,"v8":"4.4"},"3.2.0":{"node_abi":45,"v8":"4.4"},"3.3.0":{"node_abi":45,"v8":"4.4"},"3.3.1":{"node_abi":45,"v8":"4.4"},"4.0.0":{"node_abi":46,"v8":"4.5"},"4.1.0":{"node_abi":46,"v8":"4.5"},"4.1.1":{"node_abi":46,"v8":"4.5"},"4.1.2":{"node_abi":46,"v8":"4.5"},"4.2.0":{"node_abi":46,"v8":"4.5"},"4.2.1":{"node_abi":46,"v8":"4.5"},"4.2.2":{"node_abi":46,"v8":"4.5"},"4.2.3":{"node_abi":46,"v8":"4.5"},"4.2.4":{"node_abi":46,"v8":"4.5"},"4.2.5":{"node_abi":46,"v8":"4.5"},"4.2.6":{"node_abi":46,"v8":"4.5"},"4.3.0":{"node_abi":46,"v8":"4.5"},"4.3.1":{"node_abi":46,"v8":"4.5"},"4.3.2":{"node_abi":46,"v8":"4.5"},"4.4.0":{"node_abi":46,"v8":"4.5"},"4.4.1":{"node_abi":46,"v8":"4.5"},"4.4.2":{"node_abi":46,"v8":"4.5"},"4.4.3":{"node_abi":46,"v8":"4.5"},"4.4.4":{"node_abi":46,"v8":"4.5"},"4.4.5":{"node_abi":46,"v8":"4.5"},"4.4.6":{"node_abi":46,"v8":"4.5"},"4.4.7":{"node_abi":46,"v8":"4.5"},"4.5.0":{"node_abi":46,"v8":"4.5"},"4.6.0":{"node_abi":46,"v8":"4.5"},"4.6.1":{"node_abi":46,"v8":"4.5"},"4.6.2":{"node_abi":46,"v8":"4.5"},"4.7.0":{"node_abi":46,"v8":"4.5"},"4.7.1":{"node_abi":46,"v8":"4.5"},"4.7.2":{"node_abi":46,"v8":"4.5"},"4.7.3":{"node_abi":46,"v8":"4.5"},"4.8.0":{"node_abi":46,"v8":"4.5"},"4.8.1":{"node_abi":46,"v8":"4.5"},"4.8.2":{"node_abi":46,"v8":"4.5"},"4.8.3":{"node_abi":46,"v8":"4.5"},"4.8.4":{"node_abi":46,"v8":"4.5"},"4.8.5":{"node_abi":46,"v8":"4.5"},"4.8.6":{"node_abi":46,"v8":"4.5"},"4.8.7":{"node_abi":46,"v8":"4.5"},"4.9.0":{"node_abi":46,"v8":"4.5"},"4.9.1":{"node_abi":46,"v8":"4.5"},"5.0.0":{"node_abi":47,"v8":"4.6"},"5.1.0":{"node_abi":47,"v8":"4.6"},"5.1.1":{"node_abi":47,"v8":"4.6"},"5.2.0":{"node_abi":47,"v8":"4.6"},"5.3.0":{"node_abi":47,"v8":"4.6"},"5.4.0":{"node_abi":47,"v8":"4.6"},"5.4.1":{"node_abi":47,"v8":"4.6"},"5.5.0":{"node_abi":47,"v8":"4.6"},"5.6.0":{"node_abi":47,"v8":"4.6"},"5.7.0":{"node_abi":47,"v8":"4.6"},"5.7.1":{"node_abi":47,"v8":"4.6"},"5.8.0":{"node_abi":47,"v8":"4.6"},"5.9.0":{"node_abi":47,"v8":"4.6"},"5.9.1":{"node_abi":47,"v8":"4.6"},"5.10.0":{"node_abi":47,"v8":"4.6"},"5.10.1":{"node_abi":47,"v8":"4.6"},"5.11.0":{"node_abi":47,"v8":"4.6"},"5.11.1":{"node_abi":47,"v8":"4.6"},"5.12.0":{"node_abi":47,"v8":"4.6"},"6.0.0":{"node_abi":48,"v8":"5.0"},"6.1.0":{"node_abi":48,"v8":"5.0"},"6.2.0":{"node_abi":48,"v8":"5.0"},"6.2.1":{"node_abi":48,"v8":"5.0"},"6.2.2":{"node_abi":48,"v8":"5.0"},"6.3.0":{"node_abi":48,"v8":"5.0"},"6.3.1":{"node_abi":48,"v8":"5.0"},"6.4.0":{"node_abi":48,"v8":"5.0"},"6.5.0":{"node_abi":48,"v8":"5.1"},"6.6.0":{"node_abi":48,"v8":"5.1"},"6.7.0":{"node_abi":48,"v8":"5.1"},"6.8.0":{"node_abi":48,"v8":"5.1"},"6.8.1":{"node_abi":48,"v8":"5.1"},"6.9.0":{"node_abi":48,"v8":"5.1"},"6.9.1":{"node_abi":48,"v8":"5.1"},"6.9.2":{"node_abi":48,"v8":"5.1"},"6.9.3":{"node_abi":48,"v8":"5.1"},"6.9.4":{"node_abi":48,"v8":"5.1"},"6.9.5":{"node_abi":48,"v8":"5.1"},"6.10.0":{"node_abi":48,"v8":"5.1"},"6.10.1":{"node_abi":48,"v8":"5.1"},"6.10.2":{"node_abi":48,"v8":"5.1"},"6.10.3":{"node_abi":48,"v8":"5.1"},"6.11.0":{"node_abi":48,"v8":"5.1"},"6.11.1":{"node_abi":48,"v8":"5.1"},"6.11.2":{"node_abi":48,"v8":"5.1"},"6.11.3":{"node_abi":48,"v8":"5.1"},"6.11.4":{"node_abi":48,"v8":"5.1"},"6.11.5":{"node_abi":48,"v8":"5.1"},"6.12.0":{"node_abi":48,"v8":"5.1"},"6.12.1":{"node_abi":48,"v8":"5.1"},"6.12.2":{"node_abi":48,"v8":"5.1"},"6.12.3":{"node_abi":48,"v8":"5.1"},"6.13.0":{"node_abi":48,"v8":"5.1"},"6.13.1":{"node_abi":48,"v8":"5.1"},"6.14.0":{"node_abi":48,"v8":"5.1"},"6.14.1":{"node_abi":48,"v8":"5.1"},"6.14.2":{"node_abi":48,"v8":"5.1"},"6.14.3":{"node_abi":48,"v8":"5.1"},"6.14.4":{"node_abi":48,"v8":"5.1"},"6.15.0":{"node_abi":48,"v8":"5.1"},"6.15.1":{"node_abi":48,"v8":"5.1"},"6.16.0":{"node_abi":48,"v8":"5.1"},"6.17.0":{"node_abi":48,"v8":"5.1"},"6.17.1":{"node_abi":48,"v8":"5.1"},"7.0.0":{"node_abi":51,"v8":"5.4"},"7.1.0":{"node_abi":51,"v8":"5.4"},"7.2.0":{"node_abi":51,"v8":"5.4"},"7.2.1":{"node_abi":51,"v8":"5.4"},"7.3.0":{"node_abi":51,"v8":"5.4"},"7.4.0":{"node_abi":51,"v8":"5.4"},"7.5.0":{"node_abi":51,"v8":"5.4"},"7.6.0":{"node_abi":51,"v8":"5.5"},"7.7.0":{"node_abi":51,"v8":"5.5"},"7.7.1":{"node_abi":51,"v8":"5.5"},"7.7.2":{"node_abi":51,"v8":"5.5"},"7.7.3":{"node_abi":51,"v8":"5.5"},"7.7.4":{"node_abi":51,"v8":"5.5"},"7.8.0":{"node_abi":51,"v8":"5.5"},"7.9.0":{"node_abi":51,"v8":"5.5"},"7.10.0":{"node_abi":51,"v8":"5.5"},"7.10.1":{"node_abi":51,"v8":"5.5"},"8.0.0":{"node_abi":57,"v8":"5.8"},"8.1.0":{"node_abi":57,"v8":"5.8"},"8.1.1":{"node_abi":57,"v8":"5.8"},"8.1.2":{"node_abi":57,"v8":"5.8"},"8.1.3":{"node_abi":57,"v8":"5.8"},"8.1.4":{"node_abi":57,"v8":"5.8"},"8.2.0":{"node_abi":57,"v8":"5.8"},"8.2.1":{"node_abi":57,"v8":"5.8"},"8.3.0":{"node_abi":57,"v8":"6.0"},"8.4.0":{"node_abi":57,"v8":"6.0"},"8.5.0":{"node_abi":57,"v8":"6.0"},"8.6.0":{"node_abi":57,"v8":"6.0"},"8.7.0":{"node_abi":57,"v8":"6.1"},"8.8.0":{"node_abi":57,"v8":"6.1"},"8.8.1":{"node_abi":57,"v8":"6.1"},"8.9.0":{"node_abi":57,"v8":"6.1"},"8.9.1":{"node_abi":57,"v8":"6.1"},"8.9.2":{"node_abi":57,"v8":"6.1"},"8.9.3":{"node_abi":57,"v8":"6.1"},"8.9.4":{"node_abi":57,"v8":"6.1"},"8.10.0":{"node_abi":57,"v8":"6.2"},"8.11.0":{"node_abi":57,"v8":"6.2"},"8.11.1":{"node_abi":57,"v8":"6.2"},"8.11.2":{"node_abi":57,"v8":"6.2"},"8.11.3":{"node_abi":57,"v8":"6.2"},"8.11.4":{"node_abi":57,"v8":"6.2"},"8.12.0":{"node_abi":57,"v8":"6.2"},"8.13.0":{"node_abi":57,"v8":"6.2"},"8.14.0":{"node_abi":57,"v8":"6.2"},"8.14.1":{"node_abi":57,"v8":"6.2"},"8.15.0":{"node_abi":57,"v8":"6.2"},"8.15.1":{"node_abi":57,"v8":"6.2"},"8.16.0":{"node_abi":57,"v8":"6.2"},"9.0.0":{"node_abi":59,"v8":"6.2"},"9.1.0":{"node_abi":59,"v8":"6.2"},"9.2.0":{"node_abi":59,"v8":"6.2"},"9.2.1":{"node_abi":59,"v8":"6.2"},"9.3.0":{"node_abi":59,"v8":"6.2"},"9.4.0":{"node_abi":59,"v8":"6.2"},"9.5.0":{"node_abi":59,"v8":"6.2"},"9.6.0":{"node_abi":59,"v8":"6.2"},"9.6.1":{"node_abi":59,"v8":"6.2"},"9.7.0":{"node_abi":59,"v8":"6.2"},"9.7.1":{"node_abi":59,"v8":"6.2"},"9.8.0":{"node_abi":59,"v8":"6.2"},"9.9.0":{"node_abi":59,"v8":"6.2"},"9.10.0":{"node_abi":59,"v8":"6.2"},"9.10.1":{"node_abi":59,"v8":"6.2"},"9.11.0":{"node_abi":59,"v8":"6.2"},"9.11.1":{"node_abi":59,"v8":"6.2"},"9.11.2":{"node_abi":59,"v8":"6.2"},"10.0.0":{"node_abi":64,"v8":"6.6"},"10.1.0":{"node_abi":64,"v8":"6.6"},"10.2.0":{"node_abi":64,"v8":"6.6"},"10.2.1":{"node_abi":64,"v8":"6.6"},"10.3.0":{"node_abi":64,"v8":"6.6"},"10.4.0":{"node_abi":64,"v8":"6.7"},"10.4.1":{"node_abi":64,"v8":"6.7"},"10.5.0":{"node_abi":64,"v8":"6.7"},"10.6.0":{"node_abi":64,"v8":"6.7"},"10.7.0":{"node_abi":64,"v8":"6.7"},"10.8.0":{"node_abi":64,"v8":"6.7"},"10.9.0":{"node_abi":64,"v8":"6.8"},"10.10.0":{"node_abi":64,"v8":"6.8"},"10.11.0":{"node_abi":64,"v8":"6.8"},"10.12.0":{"node_abi":64,"v8":"6.8"},"10.13.0":{"node_abi":64,"v8":"6.8"},"10.14.0":{"node_abi":64,"v8":"6.8"},"10.14.1":{"node_abi":64,"v8":"6.8"},"10.14.2":{"node_abi":64,"v8":"6.8"},"10.15.0":{"node_abi":64,"v8":"6.8"},"10.15.1":{"node_abi":64,"v8":"6.8"},"10.15.2":{"node_abi":64,"v8":"6.8"},"10.15.3":{"node_abi":64,"v8":"6.8"},"11.0.0":{"node_abi":67,"v8":"7.0"},"11.1.0":{"node_abi":67,"v8":"7.0"},"11.2.0":{"node_abi":67,"v8":"7.0"},"11.3.0":{"node_abi":67,"v8":"7.0"},"11.4.0":{"node_abi":67,"v8":"7.0"},"11.5.0":{"node_abi":67,"v8":"7.0"},"11.6.0":{"node_abi":67,"v8":"7.0"},"11.7.0":{"node_abi":67,"v8":"7.0"},"11.8.0":{"node_abi":67,"v8":"7.0"},"11.9.0":{"node_abi":67,"v8":"7.0"},"11.10.0":{"node_abi":67,"v8":"7.0"},"11.10.1":{"node_abi":67,"v8":"7.0"},"11.11.0":{"node_abi":67,"v8":"7.0"},"11.12.0":{"node_abi":67,"v8":"7.0"},"11.13.0":{"node_abi":67,"v8":"7.0"},"11.14.0":{"node_abi":67,"v8":"7.0"},"12.0.0":{"node_abi":72,"v8":"7.4"}}')}};var __webpack_module_cache__={};function __nccwpck_require__(e){var t=__webpack_module_cache__[e];if(t!==undefined){return t.exports}var r=__webpack_module_cache__[e]={exports:{}};var s=true;try{__webpack_modules__[e].call(r.exports,r,r.exports,__nccwpck_require__);s=false}finally{if(s)delete __webpack_module_cache__[e]}return r.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var __webpack_exports__=__nccwpck_require__(9582);module.exports=__webpack_exports__})(); \ No newline at end of file + */var isNumber=function(e){if(typeof e==="number"){return e-e===0}if(typeof e==="string"&&e.trim()!==""){return Number.isFinite?Number.isFinite(+e):isFinite(+e)}return false};const toRegexRange=(e,t,r)=>{if(isNumber(e)===false){throw new TypeError("toRegexRange: expected the first argument to be a number")}if(t===void 0||e===t){return String(e)}if(isNumber(t)===false){throw new TypeError("toRegexRange: expected the second argument to be a number.")}let a=Object.assign({relaxZeros:true},r);if(typeof a.strictZeros==="boolean"){a.relaxZeros=a.strictZeros===false}let o=String(a.relaxZeros);let s=String(a.shorthand);let u=String(a.capture);let c=String(a.wrap);let d=e+":"+t+"="+o+s+u+c;if(toRegexRange.cache.hasOwnProperty(d)){return toRegexRange.cache[d].result}let f=Math.min(e,t);let p=Math.max(e,t);if(Math.abs(f-p)===1){let r=e+"|"+t;if(a.capture){return`(${r})`}if(a.wrap===false){return r}return`(?:${r})`}let h=hasPadding(e)||hasPadding(t);let v={min:e,max:t,a:f,b:p};let _=[];let g=[];if(h){v.isPadded=h;v.maxLen=String(v.max).length}if(f<0){let e=p<0?Math.abs(p):1;g=splitToPatterns(e,Math.abs(f),v,a);f=v.a=0}if(p>=0){_=splitToPatterns(f,p,v,a)}v.negatives=g;v.positives=_;v.result=collatePatterns(g,_,a);if(a.capture===true){v.result=`(${v.result})`}else if(a.wrap!==false&&_.length+g.length>1){v.result=`(?:${v.result})`}toRegexRange.cache[d]=v;return v.result};function collatePatterns(e,t,r){let a=filterPatterns(e,t,"-",false,r)||[];let o=filterPatterns(t,e,"",false,r)||[];let s=filterPatterns(e,t,"-?",true,r)||[];let u=a.concat(s).concat(o);return u.join("|")}function splitToRanges(e,t){let r=1;let a=1;let o=countNines(e,r);let s=new Set([t]);while(e<=o&&o<=t){s.add(o);r+=1;o=countNines(e,r)}o=countZeros(t+1,a)-1;while(e1){c.count.pop()}c.count.push(d.count[0]);c.string=c.pattern+toQuantifier(c.count);u=t+1;continue}if(r.isPadded){f=padZeros(t,r,a)}d.string=f+d.pattern+toQuantifier(d.count);s.push(d);u=t+1;c=d}return s}function filterPatterns(e,t,r,a,o){let s=[];for(let o of e){let{string:e}=o;if(!a&&!contains(t,"string",e)){s.push(r+e)}if(a&&contains(t,"string",e)){s.push(r+e)}}return s}function zip(e,t){let r=[];for(let a=0;at?1:t>e?-1:0}function contains(e,t,r){return e.some((e=>e[t]===r))}function countNines(e,t){return Number(String(e).slice(0,-t)+"9".repeat(t))}function countZeros(e,t){return e-e%Math.pow(10,t)}function toQuantifier(e){let[t=0,r=""]=e;if(r||t>1){return`{${t+(r?","+r:"")}}`}return""}function toCharacterClass(e,t,r){return`[${e}${t-e===1?"":"-"}${t}]`}function hasPadding(e){return/^-?(0+)\d/.test(e)}function padZeros(e,t,r){if(!t.isPadded){return e}let a=Math.abs(t.maxLen-String(e).length);let o=r.relaxZeros!==false;switch(a){case 0:return"";case 1:return o?"0?":"0";case 2:return o?"0{0,2}":"00";default:{return o?`0{0,${a}}`:`0{${a}}`}}}toRegexRange.cache={};toRegexRange.clearCache=()=>toRegexRange.cache={};var R=toRegexRange;const isObject=e=>e!==null&&typeof e==="object"&&!Array.isArray(e);const transform=e=>t=>e===true?Number(t):String(t);const isValidValue=e=>typeof e==="number"||typeof e==="string"&&e!=="";const isNumber$1=e=>Number.isInteger(+e);const zeros=e=>{let t=`${e}`;let r=-1;if(t[0]==="-")t=t.slice(1);if(t==="0")return false;while(t[++r]==="0");return r>0};const stringify$1=(e,t,r)=>{if(typeof e==="string"||typeof t==="string"){return true}return r.stringify===true};const pad=(e,t,r)=>{if(t>0){let r=e[0]==="-"?"-":"";if(r)e=e.slice(1);e=r+e.padStart(r?t-1:t,"0")}if(r===false){return String(e)}return e};const toMaxLen=(e,t)=>{let r=e[0]==="-"?"-":"";if(r){e=e.slice(1);t--}while(e.length{e.negatives.sort(((e,t)=>et?1:0));e.positives.sort(((e,t)=>et?1:0));let r=t.capture?"":"?:";let a="";let o="";let s;if(e.positives.length){a=e.positives.join("|")}if(e.negatives.length){o=`-(${r}${e.negatives.join("|")})`}if(a&&o){s=`${a}|${o}`}else{s=a||o}if(t.wrap){return`(${r}${s})`}return s};const toRange=(e,t,r,a)=>{if(r){return R(e,t,Object.assign({wrap:false},a))}let o=String.fromCharCode(e);if(e===t)return o;let s=String.fromCharCode(t);return`[${o}-${s}]`};const toRegex=(e,t,r)=>{if(Array.isArray(e)){let t=r.wrap===true;let a=r.capture?"":"?:";return t?`(${a}${e.join("|")})`:e.join("|")}return R(e,t,r)};const rangeError=(...e)=>new RangeError("Invalid range arguments: "+u.inspect(...e));const invalidRange=(e,t,r)=>{if(r.strictRanges===true)throw rangeError([e,t]);return[]};const invalidStep=(e,t)=>{if(t.strictRanges===true){throw new TypeError(`Expected step "${e}" to be a number`)}return[]};const fillNumbers=(e,t,r=1,a={})=>{let o=Number(e);let s=Number(t);if(!Number.isInteger(o)||!Number.isInteger(s)){if(a.strictRanges===true)throw rangeError([e,t]);return[]}if(o===0)o=0;if(s===0)s=0;let u=o>s;let c=String(e);let d=String(t);let f=String(r);r=Math.max(Math.abs(r),1);let p=zeros(c)||zeros(d)||zeros(f);let h=p?Math.max(c.length,d.length,f.length):0;let v=p===false&&stringify$1(e,t,a)===false;let _=a.transform||transform(v);if(a.toRegex&&r===1){return toRange(toMaxLen(e,h),toMaxLen(t,h),true,a)}let g={negatives:[],positives:[]};let push=e=>g[e<0?"negatives":"positives"].push(Math.abs(e));let y=[];let m=0;while(u?o>=s:o<=s){if(a.toRegex===true&&r>1){push(o)}else{y.push(pad(_(o,m),h,v))}o=u?o-r:o+r;m++}if(a.toRegex===true){return r>1?toSequence(g,a):toRegex(y,null,Object.assign({wrap:false},a))}return y};const fillLetters=(e,t,r=1,a={})=>{if(!isNumber$1(e)&&e.length>1||!isNumber$1(t)&&t.length>1){return invalidRange(e,t,a)}let o=a.transform||(e=>String.fromCharCode(e));let s=`${e}`.charCodeAt(0);let u=`${t}`.charCodeAt(0);let c=s>u;let d=Math.min(s,u);let f=Math.max(s,u);if(a.toRegex&&r===1){return toRange(d,f,false,a)}let p=[];let h=0;while(c?s>=u:s<=u){p.push(o(s,h));s=c?s-r:s+r;h++}if(a.toRegex===true){return toRegex(p,null,{wrap:false,options:a})}return p};const fill=(e,t,r,a={})=>{if(t==null&&isValidValue(e)){return[e]}if(!isValidValue(e)||!isValidValue(t)){return invalidRange(e,t,a)}if(typeof r==="function"){return fill(e,t,1,{transform:r})}if(isObject(r)){return fill(e,t,0,r)}let o=Object.assign({},a);if(o.capture===true)o.wrap=true;r=r||o.step||1;if(!isNumber$1(r)){if(r!=null&&!isObject(r))return invalidStep(r,o);return fill(e,t,1,r)}if(isNumber$1(e)&&isNumber$1(t)){return fillNumbers(e,t,r,o)}return fillLetters(e,t,Math.max(Math.abs(r),1),o)};var A=fill;const compile=(e,t={})=>{let walk=(e,r={})=>{let a=v.isInvalidBrace(r);let o=e.invalid===true&&t.escapeInvalid===true;let s=a===true||o===true;let u=t.escapeInvalid===true?"\\":"";let c="";if(e.isOpen===true){return u+e.value}if(e.isClose===true){return u+e.value}if(e.type==="open"){return s?u+e.value:"("}if(e.type==="close"){return s?u+e.value:")"}if(e.type==="comma"){return e.prev.type==="comma"?"":s?e.value:"|"}if(e.value){return e.value}if(e.nodes&&e.ranges>0){let r=v.reduce(e.nodes);let a=A(...r,Object.assign({},t,{wrap:false,toRegex:true}));if(a.length!==0){return r.length>1&&a.length>1?`(${a})`:a}}if(e.nodes){for(let t of e.nodes){c+=walk(t,e)}}return c};return walk(e)};var O=compile;const append=(e="",t="",r=false)=>{let a=[];e=[].concat(e);t=[].concat(t);if(!t.length)return e;if(!e.length){return r?v.flatten(t).map((e=>`{${e}}`)):t}for(let o of e){if(Array.isArray(o)){for(let e of o){a.push(append(e,t,r))}}else{for(let e of t){if(r===true&&typeof e==="string")e=`{${e}}`;a.push(Array.isArray(e)?append(o,e,r):o+e)}}}return v.flatten(a)};const expand=(e,t={})=>{let r=t.rangeLimit===void 0?1e3:t.rangeLimit;let walk=(e,a={})=>{e.queue=[];let o=a;let s=a.queue;while(o.type!=="brace"&&o.type!=="root"&&o.parent){o=o.parent;s=o.queue}if(e.invalid||e.dollar){s.push(append(s.pop(),stringify(e,t)));return}if(e.type==="brace"&&e.invalid!==true&&e.nodes.length===2){s.push(append(s.pop(),["{}"]));return}if(e.nodes&&e.ranges>0){let a=v.reduce(e.nodes);if(v.exceedsLimit(...a,t.step,r)){throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.")}let o=A(...a,t);if(o.length===0){o=stringify(e,t)}s.push(append(s.pop(),o));e.nodes=[];return}let u=v.encloseBrace(e);let c=e.queue;let d=e;while(d.type!=="brace"&&d.type!=="root"&&d.parent){d=d.parent;c=d.queue}for(let t=0;t",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:"\t",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\ufeff"};const{MAX_LENGTH:j,CHAR_BACKSLASH:N,CHAR_BACKTICK:L,CHAR_COMMA:I,CHAR_DOT:P,CHAR_LEFT_PARENTHESES:D,CHAR_RIGHT_PARENTHESES:M,CHAR_LEFT_CURLY_BRACE:W,CHAR_RIGHT_CURLY_BRACE:F,CHAR_LEFT_SQUARE_BRACKET:B,CHAR_RIGHT_SQUARE_BRACKET:$,CHAR_DOUBLE_QUOTE:U,CHAR_SINGLE_QUOTE:H,CHAR_NO_BREAK_SPACE:q,CHAR_ZERO_WIDTH_NOBREAK_SPACE:G}=C;const parse=(e,t={})=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}let r=t||{};let a=typeof r.maxLength==="number"?Math.min(j,r.maxLength):j;if(e.length>a){throw new SyntaxError(`Input length (${e.length}), exceeds max characters (${a})`)}let o={type:"root",input:e,nodes:[]};let s=[o];let u=o;let c=o;let d=0;let f=e.length;let p=0;let h=0;let v;const advance=()=>e[p++];const push=e=>{if(e.type==="text"&&c.type==="dot"){c.type="text"}if(c&&c.type==="text"&&e.type==="text"){c.value+=e.value;return}u.nodes.push(e);e.parent=u;e.prev=c;c=e;return e};push({type:"bos"});while(p0){if(u.ranges>0){u.ranges=0;let e=u.nodes.shift();u.nodes=[e,{type:"text",value:stringify(u)}]}push({type:"comma",value:v});u.commas++;continue}if(v===P&&h>0&&u.commas===0){let e=u.nodes;if(h===0||e.length===0){push({type:"text",value:v});continue}if(c.type==="dot"){u.range=[];c.value+=v;c.type="range";if(u.nodes.length!==3&&u.nodes.length!==5){u.invalid=true;u.ranges=0;c.type="text";continue}u.ranges++;u.args=[];continue}if(c.type==="range"){e.pop();let t=e[e.length-1];t.value+=c.value+v;c=t;u.ranges--;continue}push({type:"dot",value:v});continue}push({type:"text",value:v})}do{u=s.pop();if(u.type!=="root"){u.nodes.forEach((e=>{if(!e.nodes){if(e.type==="open")e.isOpen=true;if(e.type==="close")e.isClose=true;if(!e.nodes)e.type="text";e.invalid=true}}));let e=s[s.length-1];let t=e.nodes.indexOf(u);e.nodes.splice(t,1,...u.nodes)}}while(s.length>0);push({type:"eos"});return o};var K=parse;const braces=(e,t={})=>{let r=[];if(Array.isArray(e)){for(let a of e){let e=braces.create(a,t);if(Array.isArray(e)){r.push(...e)}else{r.push(e)}}}else{r=[].concat(braces.create(e,t))}if(t&&t.expand===true&&t.nodupes===true){r=[...new Set(r)]}return r};braces.parse=(e,t={})=>K(e,t);braces.stringify=(e,t={})=>{if(typeof e==="string"){return stringify(braces.parse(e,t),t)}return stringify(e,t)};braces.compile=(e,t={})=>{if(typeof e==="string"){e=braces.parse(e,t)}return O(e,t)};braces.expand=(e,t={})=>{if(typeof e==="string"){e=braces.parse(e,t)}let r=T(e,t);if(t.noempty===true){r=r.filter(Boolean)}if(t.nodupes===true){r=[...new Set(r)]}return r};braces.create=(e,t={})=>{if(e===""||e.length<3){return[e]}return t.expand!==true?braces.compile(e,t):braces.expand(e,t)};var z=braces;const V="\\\\/";const Y=`[^${V}]`;const Q="\\.";const X="\\+";const Z="\\?";const J="\\/";const ee="(?=.)";const te="[^/]";const ne=`(?:${J}|$)`;const re=`(?:^|${J})`;const ie=`${Q}{1,2}${ne}`;const ae=`(?!${Q})`;const oe=`(?!${re}${ie})`;const se=`(?!${Q}{0,1}${ne})`;const le=`(?!${ie})`;const ue=`[^.${J}]`;const ce=`${te}*?`;const de={DOT_LITERAL:Q,PLUS_LITERAL:X,QMARK_LITERAL:Z,SLASH_LITERAL:J,ONE_CHAR:ee,QMARK:te,END_ANCHOR:ne,DOTS_SLASH:ie,NO_DOT:ae,NO_DOTS:oe,NO_DOT_SLASH:se,NO_DOTS_SLASH:le,QMARK_NO_DOT:ue,STAR:ce,START_ANCHOR:re};const fe=Object.assign({},de,{SLASH_LITERAL:`[${V}]`,QMARK:Y,STAR:`${Y}*?`,DOTS_SLASH:`${Q}{1,2}(?:[${V}]|$)`,NO_DOT:`(?!${Q})`,NO_DOTS:`(?!(?:^|[${V}])${Q}{1,2}(?:[${V}]|$))`,NO_DOT_SLASH:`(?!${Q}{0,1}(?:[${V}]|$))`,NO_DOTS_SLASH:`(?!${Q}{1,2}(?:[${V}]|$))`,QMARK_NO_DOT:`[^.${V}]`,START_ANCHOR:`(?:^|[${V}])`,END_ANCHOR:`(?:[${V}]|$)`});const pe={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};var he={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:pe,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHAR:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:o.sep,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?fe:de}};var be=createCommonjsModule((function(e,t){const r=process.platform==="win32";const{REGEX_SPECIAL_CHARS:a,REGEX_SPECIAL_CHARS_GLOBAL:s,REGEX_REMOVE_BACKSLASH:u}=he;t.isObject=e=>e!==null&&typeof e==="object"&&!Array.isArray(e);t.hasRegexChars=e=>a.test(e);t.isRegexChar=e=>e.length===1&&t.hasRegexChars(e);t.escapeRegex=e=>e.replace(s,"\\$1");t.toPosixSlashes=e=>e.replace(/\\/g,"/");t.removeBackslashes=e=>e.replace(u,(e=>e==="\\"?"":e));t.supportsLookbehinds=()=>{let e=process.version.slice(1).split(".");if(e.length===3&&+e[0]>=9||+e[0]===8&&+e[1]>=10){return true}return false};t.isWindows=e=>{if(e&&typeof e.windows==="boolean"){return e.windows}return r===true||o.sep==="\\"};t.escapeLast=(e,r,a)=>{let o=e.lastIndexOf(r,a);if(o===-1)return e;if(e[o-1]==="\\")return t.escapeLast(e,r,o-1);return e.slice(0,o)+"\\"+e.slice(o)}}));var ve=be.isObject;var _e=be.hasRegexChars;var ge=be.isRegexChar;var ye=be.escapeRegex;var me=be.toPosixSlashes;var we=be.removeBackslashes;var xe=be.supportsLookbehinds;var Ee=be.isWindows;var Se=be.escapeLast;const{CHAR_ASTERISK:ke,CHAR_AT:Re,CHAR_BACKWARD_SLASH:Ae,CHAR_COMMA:Oe,CHAR_DOT:Te,CHAR_EXCLAMATION_MARK:Ce,CHAR_FORWARD_SLASH:je,CHAR_LEFT_CURLY_BRACE:Ne,CHAR_LEFT_PARENTHESES:Le,CHAR_LEFT_SQUARE_BRACKET:Ie,CHAR_PLUS:Pe,CHAR_QUESTION_MARK:De,CHAR_RIGHT_CURLY_BRACE:Me,CHAR_RIGHT_PARENTHESES:We,CHAR_RIGHT_SQUARE_BRACKET:Fe}=he;const isPathSeparator=e=>e===je||e===Ae;var scan=(e,t)=>{let r=t||{};let a=e.length-1;let o=-1;let s=0;let u=0;let c=false;let d=false;let f=false;let p=0;let h;let v;let _=false;let eos=()=>o>=a;let advance=()=>{h=v;return e.charCodeAt(++o)};while(o0){g=e.slice(0,s);e=e.slice(s);u-=s}if(m&&c===true&&u>0){m=e.slice(0,u);w=e.slice(u)}else if(c===true){m="";w=e}else{m=e}if(m&&m!==""&&m!=="/"&&m!==e){if(isPathSeparator(m.charCodeAt(m.length-1))){m=m.slice(0,-1)}}if(r.unescape===true){if(w)w=be.removeBackslashes(w);if(m&&d===true){m=be.removeBackslashes(m)}}return{prefix:g,input:y,base:m,glob:w,negated:f,isGlob:c}};const{MAX_LENGTH:Be,POSIX_REGEX_SOURCE:$e,REGEX_NON_SPECIAL_CHAR:Ue,REGEX_SPECIAL_CHARS_BACKREF:He,REPLACEMENTS:qe}=he;const expandRange=(e,t)=>{if(typeof t.expandRange==="function"){return t.expandRange(...e,t)}e.sort();let r=`[${e.join("-")}]`;try{}catch(t){return e.map((e=>be.escapeRegex(e))).join("..")}return r};const negate=e=>{let t=1;while(e.peek()==="!"&&(e.peek(2)!=="("||e.peek(3)==="?")){e.advance();e.start++;t++}if(t%2===0){return false}e.negated=true;e.start++;return true};const syntaxError=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`;const parse$1=(e,t)=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}e=qe[e]||e;let r=Object.assign({},t);let a=typeof r.maxLength==="number"?Math.min(Be,r.maxLength):Be;let o=e.length;if(o>a){throw new SyntaxError(`Input length: ${o}, exceeds maximum allowed length: ${a}`)}let s={type:"bos",value:"",output:r.prepend||""};let u=[s];let c=r.capture?"":"?:";let d=be.isWindows(t);const f=he.globChars(d);const p=he.extglobChars(f);const{DOT_LITERAL:h,PLUS_LITERAL:v,SLASH_LITERAL:_,ONE_CHAR:g,DOTS_SLASH:y,NO_DOT:m,NO_DOT_SLASH:w,NO_DOTS_SLASH:x,QMARK:E,QMARK_NO_DOT:S,STAR:k,START_ANCHOR:R}=f;const globstar=e=>`(${c}(?:(?!${R}${e.dot?y:h}).)*?)`;let A=r.dot?"":m;let O=r.bash===true?globstar(r):k;let T=r.dot?E:S;if(r.capture){O=`(${O})`}if(typeof r.noext==="boolean"){r.noextglob=r.noext}let C={index:-1,start:0,consumed:"",output:"",backtrack:false,brackets:0,braces:0,parens:0,quotes:0,tokens:u};let j=[];let N=[];let L=s;let I;const eos=()=>C.index===o-1;const P=C.peek=(t=1)=>e[C.index+t];const D=C.advance=()=>e[++C.index];const append=e=>{C.output+=e.output!=null?e.output:e.value;C.consumed+=e.value||""};const increment=e=>{C[e]++;N.push(e)};const decrement=e=>{C[e]--;N.pop()};const push=e=>{if(L.type==="globstar"){let t=C.braces>0&&(e.type==="comma"||e.type==="brace");let r=j.length&&(e.type==="pipe"||e.type==="paren");if(e.type!=="slash"&&e.type!=="paren"&&!t&&!r){C.output=C.output.slice(0,-L.output.length);L.type="star";L.value="*";L.output=O;C.output+=L.output}}if(j.length&&e.type!=="paren"&&!p[e.value]){j[j.length-1].inner+=e.value}if(e.value||e.output)append(e);if(L&&L.type==="text"&&e.type==="text"){L.value+=e.value;return}e.prev=L;u.push(e);L=e};const extglobOpen=(e,t)=>{let a=Object.assign({},p[t],{conditions:1,inner:""});a.prev=L;a.parens=C.parens;a.output=C.output;let o=(r.capture?"(":"")+a.open;push({type:e,value:t,output:C.output?"":g});push({type:"paren",extglob:true,value:D(),output:o});increment("parens");j.push(a)};const extglobClose=t=>{let a=t.close+(r.capture?")":"");if(t.type==="negate"){let o=O;if(t.inner&&t.inner.length>1&&t.inner.includes("/")){o=globstar(r)}if(o!==O||eos()||/^\)+$/.test(e.slice(C.index+1))){a=t.close=")$))"+o}if(t.prev.type==="bos"&&eos()){C.negatedExtglob=true}}push({type:"paren",extglob:true,value:I,output:a});decrement("parens")};if(r.fastpaths!==false&&!/(^[*!]|[/{[()\]}"])/.test(e)){let t=false;let a=e.replace(He,((e,r,a,o,s,u)=>{if(o==="\\"){t=true;return e}if(o==="?"){if(r){return r+o+(s?E.repeat(s.length):"")}if(u===0){return T+(s?E.repeat(s.length):"")}return E.repeat(a.length)}if(o==="."){return h.repeat(a.length)}if(o==="*"){if(r){return r+o+(s?O:"")}return O}return r?e:"\\"+e}));if(t===true){if(r.unescape===true){a=a.replace(/\\/g,"")}else{a=a.replace(/\\+/g,(e=>e.length%2===0?"\\\\":e?"\\":""))}}C.output=a;return C}while(!eos()){I=D();if(I==="\0"){continue}if(I==="\\"){let t=P();if(t==="/"&&r.bash!==true){continue}if(t==="."||t===";"){continue}if(!t){I+="\\";push({type:"text",value:I});continue}let a=/^\\+/.exec(e.slice(C.index+1));let o=0;if(a&&a[0].length>2){o=a[0].length;C.index+=o;if(o%2!==0){I+="\\"}}if(r.unescape===true){I=D()||""}else{I+=D()||""}if(C.brackets===0){push({type:"text",value:I});continue}}if(C.brackets>0&&(I!=="]"||L.value==="["||L.value==="[^")){if(r.posix!==false&&I===":"){let e=L.value.slice(1);if(e.includes("[")){L.posix=true;if(e.includes(":")){let e=L.value.lastIndexOf("[");let t=L.value.slice(0,e);let r=L.value.slice(e+2);let a=$e[r];if(a){L.value=t+a;C.backtrack=true;D();if(!s.output&&u.indexOf(L)===1){s.output=g}continue}}}}if(I==="["&&P()!==":"||I==="-"&&P()==="]"){I="\\"+I}if(I==="]"&&(L.value==="["||L.value==="[^")){I="\\"+I}if(r.posix===true&&I==="!"&&L.value==="["){I="^"}L.value+=I;append({value:I});continue}if(C.quotes===1&&I!=='"'){I=be.escapeRegex(I);L.value+=I;append({value:I});continue}if(I==='"'){C.quotes=C.quotes===1?0:1;if(r.keepQuotes===true){push({type:"text",value:I})}continue}if(I==="("){push({type:"paren",value:I});increment("parens");continue}if(I===")"){if(C.parens===0&&r.strictBrackets===true){throw new SyntaxError(syntaxError("opening","("))}let e=j[j.length-1];if(e&&C.parens===e.parens+1){extglobClose(j.pop());continue}push({type:"paren",value:I,output:C.parens?")":"\\)"});decrement("parens");continue}if(I==="["){if(r.nobracket===true||!e.slice(C.index+1).includes("]")){if(r.nobracket!==true&&r.strictBrackets===true){throw new SyntaxError(syntaxError("closing","]"))}I="\\"+I}else{increment("brackets")}push({type:"bracket",value:I});continue}if(I==="]"){if(r.nobracket===true||L&&L.type==="bracket"&&L.value.length===1){push({type:"text",value:I,output:"\\"+I});continue}if(C.brackets===0){if(r.strictBrackets===true){throw new SyntaxError(syntaxError("opening","["))}push({type:"text",value:I,output:"\\"+I});continue}decrement("brackets");let e=L.value.slice(1);if(L.posix!==true&&e[0]==="^"&&!e.includes("/")){I="/"+I}L.value+=I;append({value:I});if(r.literalBrackets===false||be.hasRegexChars(e)){continue}let t=be.escapeRegex(L.value);C.output=C.output.slice(0,-L.value.length);if(r.literalBrackets===true){C.output+=t;L.value=t;continue}L.value=`(${c}${t}|${L.value})`;C.output+=L.value;continue}if(I==="{"&&r.nobrace!==true){push({type:"brace",value:I,output:"("});increment("braces");continue}if(I==="}"){if(r.nobrace===true||C.braces===0){push({type:"text",value:I,output:"\\"+I});continue}let e=")";if(C.dots===true){let t=u.slice();let a=[];for(let e=t.length-1;e>=0;e--){u.pop();if(t[e].type==="brace"){break}if(t[e].type!=="dots"){a.unshift(t[e].value)}}e=expandRange(a,r);C.backtrack=true}push({type:"brace",value:I,output:e});decrement("braces");continue}if(I==="|"){if(j.length>0){j[j.length-1].conditions++}push({type:"text",value:I});continue}if(I===","){let e=I;if(C.braces>0&&N[N.length-1]==="braces"){e="|"}push({type:"comma",value:I,output:e});continue}if(I==="/"){if(L.type==="dot"&&C.index===1){C.start=C.index+1;C.consumed="";C.output="";u.pop();L=s;continue}push({type:"slash",value:I,output:_});continue}if(I==="."){if(C.braces>0&&L.type==="dot"){if(L.value===".")L.output=h;L.type="dots";L.output+=I;L.value+=I;C.dots=true;continue}push({type:"dot",value:I,output:h});continue}if(I==="?"){if(L&&L.type==="paren"){let e=P();let t=I;if(e==="<"&&!be.supportsLookbehinds()){throw new Error("Node.js v10 or higher is required for regex lookbehinds")}if(L.value==="("&&!/[!=<:]/.test(e)||e==="<"&&!/[!=]/.test(P(2))){t="\\"+I}push({type:"text",value:I,output:t});continue}if(r.noextglob!==true&&P()==="("&&P(2)!=="?"){extglobOpen("qmark",I);continue}if(r.dot!==true&&(L.type==="slash"||L.type==="bos")){push({type:"qmark",value:I,output:S});continue}push({type:"qmark",value:I,output:E});continue}if(I==="!"){if(r.noextglob!==true&&P()==="("){if(P(2)!=="?"||!/[!=<:]/.test(P(3))){extglobOpen("negate",I);continue}}if(r.nonegate!==true&&C.index===0){negate(C);continue}}if(I==="+"){if(r.noextglob!==true&&P()==="("&&P(2)!=="?"){extglobOpen("plus",I);continue}if(L&&(L.type==="bracket"||L.type==="paren"||L.type==="brace")){let e=L.extglob===true?"\\"+I:I;push({type:"plus",value:I,output:e});continue}if(C.parens>0&&r.regex!==false){push({type:"plus",value:I});continue}push({type:"plus",value:v});continue}if(I==="@"){if(r.noextglob!==true&&P()==="("&&P(2)!=="?"){push({type:"at",value:I,output:""});continue}push({type:"text",value:I});continue}if(I!=="*"){if(I==="$"||I==="^"){I="\\"+I}let t=Ue.exec(e.slice(C.index+1));if(t){I+=t[0];C.index+=t[0].length}push({type:"text",value:I});continue}if(L&&(L.type==="globstar"||L.star===true)){L.type="star";L.star=true;L.value+=I;L.output=O;C.backtrack=true;C.consumed+=I;continue}if(r.noextglob!==true&&P()==="("&&P(2)!=="?"){extglobOpen("star",I);continue}if(L.type==="star"){if(r.noglobstar===true){C.consumed+=I;continue}let t=L.prev;let a=t.prev;let o=t.type==="slash"||t.type==="bos";let s=a&&(a.type==="star"||a.type==="globstar");if(r.bash===true&&(!o||!eos()&&P()!=="/")){push({type:"star",value:I,output:""});continue}let u=C.braces>0&&(t.type==="comma"||t.type==="brace");let c=j.length&&(t.type==="pipe"||t.type==="paren");if(!o&&t.type!=="paren"&&!u&&!c){push({type:"star",value:I,output:""});continue}while(e.slice(C.index+1,C.index+4)==="/**"){let t=e[C.index+4];if(t&&t!=="/"){break}C.consumed+="/**";C.index+=3}if(t.type==="bos"&&eos()){L.type="globstar";L.value+=I;L.output=globstar(r);C.output=L.output;C.consumed+=I;continue}if(t.type==="slash"&&t.prev.type!=="bos"&&!s&&eos()){C.output=C.output.slice(0,-(t.output+L.output).length);t.output="(?:"+t.output;L.type="globstar";L.output=globstar(r)+"|$)";L.value+=I;C.output+=t.output+L.output;C.consumed+=I;continue}let d=P();if(t.type==="slash"&&t.prev.type!=="bos"&&d==="/"){let e=P(2)!==void 0?"|$":"";C.output=C.output.slice(0,-(t.output+L.output).length);t.output="(?:"+t.output;L.type="globstar";L.output=`${globstar(r)}${_}|${_}${e})`;L.value+=I;C.output+=t.output+L.output;C.consumed+=I+D();push({type:"slash",value:I,output:""});continue}if(t.type==="bos"&&d==="/"){L.type="globstar";L.value+=I;L.output=`(?:^|${_}|${globstar(r)}${_})`;C.output=L.output;C.consumed+=I+D();push({type:"slash",value:I,output:""});continue}C.output=C.output.slice(0,-L.output.length);L.type="globstar";L.output=globstar(r);L.value+=I;C.output+=L.output;C.consumed+=I;continue}let t={type:"star",value:I,output:O};if(r.bash===true){t.output=".*?";if(L.type==="bos"||L.type==="slash"){t.output=A+t.output}push(t);continue}if(L&&(L.type==="bracket"||L.type==="paren")&&r.regex===true){t.output=I;push(t);continue}if(C.index===C.start||L.type==="slash"||L.type==="dot"){if(L.type==="dot"){C.output+=w;L.output+=w}else if(r.dot===true){C.output+=x;L.output+=x}else{C.output+=A;L.output+=A}if(P()!=="*"){C.output+=g;L.output+=g}}push(t)}while(C.brackets>0){if(r.strictBrackets===true)throw new SyntaxError(syntaxError("closing","]"));C.output=be.escapeLast(C.output,"[");decrement("brackets")}while(C.parens>0){if(r.strictBrackets===true)throw new SyntaxError(syntaxError("closing",")"));C.output=be.escapeLast(C.output,"(");decrement("parens")}while(C.braces>0){if(r.strictBrackets===true)throw new SyntaxError(syntaxError("closing","}"));C.output=be.escapeLast(C.output,"{");decrement("braces")}if(r.strictSlashes!==true&&(L.type==="star"||L.type==="bracket")){push({type:"maybe_slash",value:"",output:`${_}?`})}if(C.backtrack===true){C.output="";for(let e of C.tokens){C.output+=e.output!=null?e.output:e.value;if(e.suffix){C.output+=e.suffix}}}return C};parse$1.fastpaths=(e,t)=>{let r=Object.assign({},t);let a=typeof r.maxLength==="number"?Math.min(Be,r.maxLength):Be;let o=e.length;if(o>a){throw new SyntaxError(`Input length: ${o}, exceeds maximum allowed length: ${a}`)}e=qe[e]||e;let s=be.isWindows(t);const{DOT_LITERAL:u,SLASH_LITERAL:c,ONE_CHAR:d,DOTS_SLASH:f,NO_DOT:p,NO_DOTS:h,NO_DOTS_SLASH:v,STAR:_,START_ANCHOR:g}=he.globChars(s);let y=r.capture?"":"?:";let m=r.bash===true?".*?":_;let w=r.dot?h:p;let x=r.dot?v:p;if(r.capture){m=`(${m})`}const globstar=e=>`(${y}(?:(?!${g}${e.dot?f:u}).)*?)`;const create=e=>{switch(e){case"*":return`${w}${d}${m}`;case".*":return`${u}${d}${m}`;case"*.*":return`${w}${m}${u}${d}${m}`;case"*/*":return`${w}${m}${c}${d}${x}${m}`;case"**":return w+globstar(r);case"**/*":return`(?:${w}${globstar(r)}${c})?${x}${d}${m}`;case"**/*.*":return`(?:${w}${globstar(r)}${c})?${x}${m}${u}${d}${m}`;case"**/.*":return`(?:${w}${globstar(r)}${c})?${u}${d}${m}`;default:{let r=/^(.*?)\.(\w+)$/.exec(e);if(!r)return;let a=create(r[1],t);if(!a)return;return a+u+r[2]}}};let E=create(e);if(E&&r.strictSlashes!==true){E+=`${c}?`}return E};var Ge=parse$1;const picomatch=(e,t,r=false)=>{if(Array.isArray(e)){let a=e.map((e=>picomatch(e,t,r)));return e=>{for(let t of a){let r=t(e);if(r)return r}return false}}if(typeof e!=="string"||e===""){throw new TypeError("Expected pattern to be a non-empty string")}let a=t||{};let o=be.isWindows(t);let s=picomatch.makeRe(e,t,false,true);let u=s.state;delete s.state;let isIgnored=()=>false;if(a.ignore){let e=Object.assign({},t,{ignore:null,onMatch:null,onResult:null});isIgnored=picomatch(a.ignore,e,r)}const matcher=(r,c=false)=>{let{isMatch:d,match:f,output:p}=picomatch.test(r,s,t,{glob:e,posix:o});let h={glob:e,state:u,regex:s,posix:o,input:r,output:p,match:f,isMatch:d};if(typeof a.onResult==="function"){a.onResult(h)}if(d===false){h.isMatch=false;return c?h:false}if(isIgnored(r)){if(typeof a.onIgnore==="function"){a.onIgnore(h)}h.isMatch=false;return c?h:false}if(typeof a.onMatch==="function"){a.onMatch(h)}return c?h:true};if(r){matcher.state=u}return matcher};picomatch.test=(e,t,r,{glob:a,posix:o}={})=>{if(typeof e!=="string"){throw new TypeError("Expected input to be a string")}if(e===""){return{isMatch:false,output:""}}let s=r||{};let u=s.format||(o?be.toPosixSlashes:null);let c=e===a;let d=c&&u?u(e):e;if(c===false){d=u?u(e):e;c=d===a}if(c===false||s.capture===true){if(s.matchBase===true||s.basename===true){c=picomatch.matchBase(e,t,r,o)}else{c=t.exec(d)}}return{isMatch:!!c,match:c,output:d}};picomatch.matchBase=(e,t,r,a=be.isWindows(r))=>{let s=t instanceof RegExp?t:picomatch.makeRe(t,r);return s.test(o.basename(e))};picomatch.isMatch=(e,t,r)=>picomatch(t,r)(e);picomatch.parse=(e,t)=>Ge(e,t);picomatch.scan=(e,t)=>scan(e,t);picomatch.makeRe=(e,t,r=false,a=false)=>{if(!e||typeof e!=="string"){throw new TypeError("Expected a non-empty string")}let o=t||{};let s=o.contains?"":"^";let u=o.contains?"":"$";let c={negated:false,fastpaths:true};let d="";let f;if(e.startsWith("./")){e=e.slice(2);d=c.prefix="./"}if(o.fastpaths!==false&&(e[0]==="."||e[0]==="*")){f=Ge.fastpaths(e,t)}if(f===void 0){c=picomatch.parse(e,t);c.prefix=d+(c.prefix||"");f=c.output}if(r===true){return f}let p=`${s}(?:${f})${u}`;if(c&&c.negated===true){p=`^(?!${p}).*$`}let h=picomatch.toRegex(p,t);if(a===true){h.state=c}return h};picomatch.toRegex=(e,t)=>{try{let r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(e){if(t&&t.debug===true)throw e;return/$^/}};picomatch.constants=he;var Ke=picomatch;var ze=Ke;const isEmptyString=e=>typeof e==="string"&&(e===""||e==="./");const micromatch=(e,t,r)=>{t=[].concat(t);e=[].concat(e);let a=new Set;let o=new Set;let s=new Set;let u=0;let onResult=e=>{s.add(e.output);if(r&&r.onResult){r.onResult(e)}};for(let s=0;s!a.has(e)));if(r&&d.length===0){if(r.failglob===true){throw new Error(`No matches found for "${t.join(", ")}"`)}if(r.nonull===true||r.nullglob===true){return r.unescape?t.map((e=>e.replace(/\\/g,""))):t}}return d};micromatch.match=micromatch;micromatch.matcher=(e,t)=>ze(e,t);micromatch.isMatch=(e,t,r)=>ze(t,r)(e);micromatch.any=micromatch.isMatch;micromatch.not=(e,t,r={})=>{t=[].concat(t).map(String);let a=new Set;let o=[];let onResult=e=>{if(r.onResult)r.onResult(e);o.push(e.output)};let s=micromatch(e,t,Object.assign({},r,{onResult:onResult}));for(let e of o){if(!s.includes(e)){a.add(e)}}return[...a]};micromatch.contains=(e,t,r)=>{if(typeof e!=="string"){throw new TypeError(`Expected a string: "${u.inspect(e)}"`)}if(Array.isArray(t)){return t.some((t=>micromatch.contains(e,t,r)))}if(typeof t==="string"){if(isEmptyString(e)||isEmptyString(t)){return false}if(e.includes(t)||e.startsWith("./")&&e.slice(2).includes(t)){return true}}return micromatch.isMatch(e,t,Object.assign({},r,{contains:true}))};micromatch.matchKeys=(e,t,r)=>{if(!be.isObject(e)){throw new TypeError("Expected the first argument to be an object")}let a=micromatch(Object.keys(e),t,r);let o={};for(let t of a)o[t]=e[t];return o};micromatch.some=(e,t,r)=>{let a=[].concat(e);for(let e of[].concat(t)){let t=ze(String(e),r);if(a.some((e=>t(e)))){return true}}return false};micromatch.every=(e,t,r)=>{let a=[].concat(e);for(let e of[].concat(t)){let t=ze(String(e),r);if(!a.every((e=>t(e)))){return false}}return true};micromatch.all=(e,t,r)=>{if(typeof e!=="string"){throw new TypeError(`Expected a string: "${u.inspect(e)}"`)}return[].concat(t).every((t=>ze(t,r)(e)))};micromatch.capture=(e,t,r)=>{let a=be.isWindows(r);let o=ze.makeRe(String(e),Object.assign({},r,{capture:true}));let s=o.exec(a?be.toPosixSlashes(t):t);if(s){return s.slice(1).map((e=>e===void 0?"":e))}};micromatch.makeRe=(...e)=>ze.makeRe(...e);micromatch.scan=(...e)=>ze.scan(...e);micromatch.parse=(e,t)=>{let r=[];for(let a of[].concat(e||[])){for(let e of z(String(a),t)){r.push(ze.parse(e,t))}}return r};micromatch.braces=(e,t)=>{if(typeof e!=="string")throw new TypeError("Expected a string");if(t&&t.nobrace===true||!/\{.*\}/.test(e)){return[e]}return z(e,t)};micromatch.braceExpand=(e,t)=>{if(typeof e!=="string")throw new TypeError("Expected a string");return micromatch.braces(e,Object.assign({},t,{expand:true}))};var Ve=micromatch;function ensureArray(e){if(Array.isArray(e))return e;if(e==undefined)return[];return[e]}function getMatcherString(e,t){if(t===false){return e}return a.resolve(...typeof t==="string"?[t,e]:[e])}const Ye=function createFilter(e,t,r){const o=r&&r.resolve;const getMatcher=e=>e instanceof RegExp?e:{test:Ve.matcher(getMatcherString(e,o).split(a.sep).join("/"),{dot:true})};const s=ensureArray(e).map(getMatcher);const u=ensureArray(t).map(getMatcher);return function(e){if(typeof e!=="string")return false;if(/\0/.test(e))return false;e=e.split(a.sep).join("/");for(let t=0;tt.toUpperCase())).replace(/[^$_a-zA-Z0-9]/g,"_");if(/\d/.test(e[0])||Ze.has(e)){e=`_${e}`}return e||"_"};function stringify$2(e){return(JSON.stringify(e)||"undefined").replace(/[\u2028\u2029]/g,(e=>`\\u${("000"+e.charCodeAt(0).toString(16)).slice(-4)}`))}function serializeArray(e,t,r){let a="[";const o=t?"\n"+r+t:"";for(let s=0;s0?",":""}${o}${serialize(u,t,r+t)}`}return a+`${t?"\n"+r:""}]`}function serializeObject(e,t,r){let a="{";const o=t?"\n"+r+t:"";const s=Object.keys(e);for(let u=0;u0?",":""}${o}${d}:${t?" ":""}${serialize(e[c],t,r+t)}`}return a+`${t?"\n"+r:""}}`}function serialize(e,t,r){if(e===Infinity)return"Infinity";if(e===-Infinity)return"-Infinity";if(e===0&&1/e===-Infinity)return"-0";if(e instanceof Date)return"new Date("+e.getTime()+")";if(e instanceof RegExp)return e.toString();if(e!==e)return"NaN";if(Array.isArray(e))return serializeArray(e,t,r);if(e===null)return"null";if(typeof e==="object")return serializeObject(e,t,r);return stringify$2(e)}const et=function dataToEsm(e,t={}){const r=t.compact?"":"indent"in t?t.indent:"\t";const a=t.compact?"":" ";const o=t.compact?"":"\n";const s=t.preferConst?"const":"var";if(t.namedExports===false||typeof e!=="object"||Array.isArray(e)||e instanceof Date||e instanceof RegExp||e===null){const o=serialize(e,t.compact?null:r,"");const s=a||(/^[{[\-\/]/.test(o)?"":" ");return`export default${s}${o};`}let u="";const c=[];const d=Object.keys(e);for(let f=0;ft=true};const a={};const o=Object.prototype.toString;function isArray(e){return o.call(e)==="[object Array]"}function visit(e,o,s,u,c,d){if(!e)return;if(s){const a=t;t=false;s.call(r,e,o,c,d);const u=t;t=a;if(u)return}const f=e.type&&a[e.type]||(a[e.type]=Object.keys(e).filter((t=>typeof e[t]==="object")));for(let t=0;t{e.exports=function(e){[process.stdout,process.stderr].forEach((function(t){if(t._handle&&t.isTTY&&typeof t._handle.setBlocking==="function"){t._handle.setBlocking(e)}}))}},2028:(e,t,r)=>{var a=r(9491);var o=r(19);var s=r(2361);if(typeof s!=="function"){s=s.EventEmitter}var u;if(process.__signal_exit_emitter__){u=process.__signal_exit_emitter__}else{u=process.__signal_exit_emitter__=new s;u.count=0;u.emitted={}}if(!u.infinite){u.setMaxListeners(Infinity);u.infinite=true}e.exports=function(e,t){a.equal(typeof e,"function","a callback must be provided for exit handler");if(d===false){load()}var r="exit";if(t&&t.alwaysLast){r="afterexit"}var remove=function(){u.removeListener(r,e);if(u.listeners("exit").length===0&&u.listeners("afterexit").length===0){unload()}};u.on(r,e);return remove};e.exports.unload=unload;function unload(){if(!d){return}d=false;o.forEach((function(e){try{process.removeListener(e,c[e])}catch(e){}}));process.emit=p;process.reallyExit=f;u.count-=1}function emit(e,t,r){if(u.emitted[e]){return}u.emitted[e]=true;u.emit(e,t,r)}var c={};o.forEach((function(e){c[e]=function listener(){var t=process.listeners(e);if(t.length===u.count){unload();emit("exit",null,e);emit("afterexit",null,e);process.kill(process.pid,e)}}}));e.exports.signals=function(){return o};e.exports.load=load;var d=false;function load(){if(d){return}d=true;u.count+=1;o=o.filter((function(e){try{process.on(e,c[e]);return true}catch(e){return false}}));process.emit=processEmit;process.reallyExit=processReallyExit}var f=process.reallyExit;function processReallyExit(e){process.exitCode=e||0;emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);f.call(process,process.exitCode)}var p=process.emit;function processEmit(e,t){if(e==="exit"){if(t!==undefined){process.exitCode=t}var r=p.apply(this,arguments);emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);return r}else{return p.apply(this,arguments)}}},19:e=>{e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32"){e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT")}if(process.platform==="linux"){e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}},9209:(e,t,r)=>{e.exports=r(3837).deprecate},7568:(e,t,r)=>{"use strict";var a=r(3062);t.center=alignCenter;t.left=alignLeft;t.right=alignRight;function createPadding(e){var t="";var r=" ";var a=e;do{if(a%2){t+=r}a=Math.floor(a/2);r+=r}while(a);return t}function alignLeft(e,t){var r=e.trimRight();if(r.length===0&&e.length>=t)return e;var o="";var s=a(r);if(s=t)return e;var o="";var s=a(r);if(s=t)return e;var o="";var s="";var u=a(r);if(u{"use strict";e.exports=e=>{if(Number.isNaN(e)){return false}if(e>=4352&&(e<=4447||e===9001||e===9002||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141)){return true}return false}},3062:(e,t,r)=>{"use strict";const a=r(7518);const o=r(4994);e.exports=e=>{if(typeof e!=="string"||e.length===0){return 0}e=a(e);let t=0;for(let r=0;r=127&&a<=159){continue}if(a>=768&&a<=879){continue}if(a>65535){r++}t+=o(a)?2:1}return t}},918:module=>{module.exports=eval("require")("aws-sdk")},2722:module=>{module.exports=eval("require")("mock-aws-s3")},3902:module=>{module.exports=eval("require")("nock")},9491:e=>{"use strict";e.exports=require("assert")},4300:e=>{"use strict";e.exports=require("buffer")},2081:e=>{"use strict";e.exports=require("child_process")},2057:e=>{"use strict";e.exports=require("constants")},2361:e=>{"use strict";e.exports=require("events")},7147:e=>{"use strict";e.exports=require("fs")},8188:e=>{"use strict";e.exports=require("module")},1988:e=>{"use strict";e.exports=require("next/dist/compiled/acorn")},3535:e=>{"use strict";e.exports=require("next/dist/compiled/glob")},2540:e=>{"use strict";e.exports=require("next/dist/compiled/micromatch")},7849:e=>{"use strict";e.exports=require("next/dist/compiled/semver")},7518:e=>{"use strict";e.exports=require("next/dist/compiled/strip-ansi")},2037:e=>{"use strict";e.exports=require("os")},1017:e=>{"use strict";e.exports=require("path")},8102:e=>{"use strict";e.exports=require("repl")},2781:e=>{"use strict";e.exports=require("stream")},7310:e=>{"use strict";e.exports=require("url")},3837:e=>{"use strict";e.exports=require("util")},7470:function(e,t){(function(e,r){true?r(t):0})(this,(function(e){"use strict";class WalkerBase{constructor(){this.should_skip=false;this.should_remove=false;this.replacement=null;this.context={skip:()=>this.should_skip=true,remove:()=>this.should_remove=true,replace:e=>this.replacement=e}}replace(e,t,r,a){if(e){if(r!==null){e[t][r]=a}else{e[t]=a}}}remove(e,t,r){if(e){if(r!==null){e[t].splice(r,1)}else{delete e[t]}}}}class SyncWalker extends WalkerBase{constructor(e,t){super();this.enter=e;this.leave=t}visit(e,t,r,a){if(e){if(this.enter){const o=this.should_skip;const s=this.should_remove;const u=this.replacement;this.should_skip=false;this.should_remove=false;this.replacement=null;this.enter.call(this.context,e,t,r,a);if(this.replacement){e=this.replacement;this.replace(t,r,a,e)}if(this.should_remove){this.remove(t,r,a)}const c=this.should_skip;const d=this.should_remove;this.should_skip=o;this.should_remove=s;this.replacement=u;if(c)return e;if(d)return null}for(const t in e){const r=e[t];if(typeof r!=="object"){continue}else if(Array.isArray(r)){for(let a=0;a{"use strict";e.exports=JSON.parse('{"0.1.14":{"node_abi":null,"v8":"1.3"},"0.1.15":{"node_abi":null,"v8":"1.3"},"0.1.16":{"node_abi":null,"v8":"1.3"},"0.1.17":{"node_abi":null,"v8":"1.3"},"0.1.18":{"node_abi":null,"v8":"1.3"},"0.1.19":{"node_abi":null,"v8":"2.0"},"0.1.20":{"node_abi":null,"v8":"2.0"},"0.1.21":{"node_abi":null,"v8":"2.0"},"0.1.22":{"node_abi":null,"v8":"2.0"},"0.1.23":{"node_abi":null,"v8":"2.0"},"0.1.24":{"node_abi":null,"v8":"2.0"},"0.1.25":{"node_abi":null,"v8":"2.0"},"0.1.26":{"node_abi":null,"v8":"2.0"},"0.1.27":{"node_abi":null,"v8":"2.1"},"0.1.28":{"node_abi":null,"v8":"2.1"},"0.1.29":{"node_abi":null,"v8":"2.1"},"0.1.30":{"node_abi":null,"v8":"2.1"},"0.1.31":{"node_abi":null,"v8":"2.1"},"0.1.32":{"node_abi":null,"v8":"2.1"},"0.1.33":{"node_abi":null,"v8":"2.1"},"0.1.90":{"node_abi":null,"v8":"2.2"},"0.1.91":{"node_abi":null,"v8":"2.2"},"0.1.92":{"node_abi":null,"v8":"2.2"},"0.1.93":{"node_abi":null,"v8":"2.2"},"0.1.94":{"node_abi":null,"v8":"2.2"},"0.1.95":{"node_abi":null,"v8":"2.2"},"0.1.96":{"node_abi":null,"v8":"2.2"},"0.1.97":{"node_abi":null,"v8":"2.2"},"0.1.98":{"node_abi":null,"v8":"2.2"},"0.1.99":{"node_abi":null,"v8":"2.2"},"0.1.100":{"node_abi":null,"v8":"2.2"},"0.1.101":{"node_abi":null,"v8":"2.3"},"0.1.102":{"node_abi":null,"v8":"2.3"},"0.1.103":{"node_abi":null,"v8":"2.3"},"0.1.104":{"node_abi":null,"v8":"2.3"},"0.2.0":{"node_abi":1,"v8":"2.3"},"0.2.1":{"node_abi":1,"v8":"2.3"},"0.2.2":{"node_abi":1,"v8":"2.3"},"0.2.3":{"node_abi":1,"v8":"2.3"},"0.2.4":{"node_abi":1,"v8":"2.3"},"0.2.5":{"node_abi":1,"v8":"2.3"},"0.2.6":{"node_abi":1,"v8":"2.3"},"0.3.0":{"node_abi":1,"v8":"2.5"},"0.3.1":{"node_abi":1,"v8":"2.5"},"0.3.2":{"node_abi":1,"v8":"3.0"},"0.3.3":{"node_abi":1,"v8":"3.0"},"0.3.4":{"node_abi":1,"v8":"3.0"},"0.3.5":{"node_abi":1,"v8":"3.0"},"0.3.6":{"node_abi":1,"v8":"3.0"},"0.3.7":{"node_abi":1,"v8":"3.0"},"0.3.8":{"node_abi":1,"v8":"3.1"},"0.4.0":{"node_abi":1,"v8":"3.1"},"0.4.1":{"node_abi":1,"v8":"3.1"},"0.4.2":{"node_abi":1,"v8":"3.1"},"0.4.3":{"node_abi":1,"v8":"3.1"},"0.4.4":{"node_abi":1,"v8":"3.1"},"0.4.5":{"node_abi":1,"v8":"3.1"},"0.4.6":{"node_abi":1,"v8":"3.1"},"0.4.7":{"node_abi":1,"v8":"3.1"},"0.4.8":{"node_abi":1,"v8":"3.1"},"0.4.9":{"node_abi":1,"v8":"3.1"},"0.4.10":{"node_abi":1,"v8":"3.1"},"0.4.11":{"node_abi":1,"v8":"3.1"},"0.4.12":{"node_abi":1,"v8":"3.1"},"0.5.0":{"node_abi":1,"v8":"3.1"},"0.5.1":{"node_abi":1,"v8":"3.4"},"0.5.2":{"node_abi":1,"v8":"3.4"},"0.5.3":{"node_abi":1,"v8":"3.4"},"0.5.4":{"node_abi":1,"v8":"3.5"},"0.5.5":{"node_abi":1,"v8":"3.5"},"0.5.6":{"node_abi":1,"v8":"3.6"},"0.5.7":{"node_abi":1,"v8":"3.6"},"0.5.8":{"node_abi":1,"v8":"3.6"},"0.5.9":{"node_abi":1,"v8":"3.6"},"0.5.10":{"node_abi":1,"v8":"3.7"},"0.6.0":{"node_abi":1,"v8":"3.6"},"0.6.1":{"node_abi":1,"v8":"3.6"},"0.6.2":{"node_abi":1,"v8":"3.6"},"0.6.3":{"node_abi":1,"v8":"3.6"},"0.6.4":{"node_abi":1,"v8":"3.6"},"0.6.5":{"node_abi":1,"v8":"3.6"},"0.6.6":{"node_abi":1,"v8":"3.6"},"0.6.7":{"node_abi":1,"v8":"3.6"},"0.6.8":{"node_abi":1,"v8":"3.6"},"0.6.9":{"node_abi":1,"v8":"3.6"},"0.6.10":{"node_abi":1,"v8":"3.6"},"0.6.11":{"node_abi":1,"v8":"3.6"},"0.6.12":{"node_abi":1,"v8":"3.6"},"0.6.13":{"node_abi":1,"v8":"3.6"},"0.6.14":{"node_abi":1,"v8":"3.6"},"0.6.15":{"node_abi":1,"v8":"3.6"},"0.6.16":{"node_abi":1,"v8":"3.6"},"0.6.17":{"node_abi":1,"v8":"3.6"},"0.6.18":{"node_abi":1,"v8":"3.6"},"0.6.19":{"node_abi":1,"v8":"3.6"},"0.6.20":{"node_abi":1,"v8":"3.6"},"0.6.21":{"node_abi":1,"v8":"3.6"},"0.7.0":{"node_abi":1,"v8":"3.8"},"0.7.1":{"node_abi":1,"v8":"3.8"},"0.7.2":{"node_abi":1,"v8":"3.8"},"0.7.3":{"node_abi":1,"v8":"3.9"},"0.7.4":{"node_abi":1,"v8":"3.9"},"0.7.5":{"node_abi":1,"v8":"3.9"},"0.7.6":{"node_abi":1,"v8":"3.9"},"0.7.7":{"node_abi":1,"v8":"3.9"},"0.7.8":{"node_abi":1,"v8":"3.9"},"0.7.9":{"node_abi":1,"v8":"3.11"},"0.7.10":{"node_abi":1,"v8":"3.9"},"0.7.11":{"node_abi":1,"v8":"3.11"},"0.7.12":{"node_abi":1,"v8":"3.11"},"0.8.0":{"node_abi":1,"v8":"3.11"},"0.8.1":{"node_abi":1,"v8":"3.11"},"0.8.2":{"node_abi":1,"v8":"3.11"},"0.8.3":{"node_abi":1,"v8":"3.11"},"0.8.4":{"node_abi":1,"v8":"3.11"},"0.8.5":{"node_abi":1,"v8":"3.11"},"0.8.6":{"node_abi":1,"v8":"3.11"},"0.8.7":{"node_abi":1,"v8":"3.11"},"0.8.8":{"node_abi":1,"v8":"3.11"},"0.8.9":{"node_abi":1,"v8":"3.11"},"0.8.10":{"node_abi":1,"v8":"3.11"},"0.8.11":{"node_abi":1,"v8":"3.11"},"0.8.12":{"node_abi":1,"v8":"3.11"},"0.8.13":{"node_abi":1,"v8":"3.11"},"0.8.14":{"node_abi":1,"v8":"3.11"},"0.8.15":{"node_abi":1,"v8":"3.11"},"0.8.16":{"node_abi":1,"v8":"3.11"},"0.8.17":{"node_abi":1,"v8":"3.11"},"0.8.18":{"node_abi":1,"v8":"3.11"},"0.8.19":{"node_abi":1,"v8":"3.11"},"0.8.20":{"node_abi":1,"v8":"3.11"},"0.8.21":{"node_abi":1,"v8":"3.11"},"0.8.22":{"node_abi":1,"v8":"3.11"},"0.8.23":{"node_abi":1,"v8":"3.11"},"0.8.24":{"node_abi":1,"v8":"3.11"},"0.8.25":{"node_abi":1,"v8":"3.11"},"0.8.26":{"node_abi":1,"v8":"3.11"},"0.8.27":{"node_abi":1,"v8":"3.11"},"0.8.28":{"node_abi":1,"v8":"3.11"},"0.9.0":{"node_abi":1,"v8":"3.11"},"0.9.1":{"node_abi":10,"v8":"3.11"},"0.9.2":{"node_abi":10,"v8":"3.11"},"0.9.3":{"node_abi":10,"v8":"3.13"},"0.9.4":{"node_abi":10,"v8":"3.13"},"0.9.5":{"node_abi":10,"v8":"3.13"},"0.9.6":{"node_abi":10,"v8":"3.15"},"0.9.7":{"node_abi":10,"v8":"3.15"},"0.9.8":{"node_abi":10,"v8":"3.15"},"0.9.9":{"node_abi":11,"v8":"3.15"},"0.9.10":{"node_abi":11,"v8":"3.15"},"0.9.11":{"node_abi":11,"v8":"3.14"},"0.9.12":{"node_abi":11,"v8":"3.14"},"0.10.0":{"node_abi":11,"v8":"3.14"},"0.10.1":{"node_abi":11,"v8":"3.14"},"0.10.2":{"node_abi":11,"v8":"3.14"},"0.10.3":{"node_abi":11,"v8":"3.14"},"0.10.4":{"node_abi":11,"v8":"3.14"},"0.10.5":{"node_abi":11,"v8":"3.14"},"0.10.6":{"node_abi":11,"v8":"3.14"},"0.10.7":{"node_abi":11,"v8":"3.14"},"0.10.8":{"node_abi":11,"v8":"3.14"},"0.10.9":{"node_abi":11,"v8":"3.14"},"0.10.10":{"node_abi":11,"v8":"3.14"},"0.10.11":{"node_abi":11,"v8":"3.14"},"0.10.12":{"node_abi":11,"v8":"3.14"},"0.10.13":{"node_abi":11,"v8":"3.14"},"0.10.14":{"node_abi":11,"v8":"3.14"},"0.10.15":{"node_abi":11,"v8":"3.14"},"0.10.16":{"node_abi":11,"v8":"3.14"},"0.10.17":{"node_abi":11,"v8":"3.14"},"0.10.18":{"node_abi":11,"v8":"3.14"},"0.10.19":{"node_abi":11,"v8":"3.14"},"0.10.20":{"node_abi":11,"v8":"3.14"},"0.10.21":{"node_abi":11,"v8":"3.14"},"0.10.22":{"node_abi":11,"v8":"3.14"},"0.10.23":{"node_abi":11,"v8":"3.14"},"0.10.24":{"node_abi":11,"v8":"3.14"},"0.10.25":{"node_abi":11,"v8":"3.14"},"0.10.26":{"node_abi":11,"v8":"3.14"},"0.10.27":{"node_abi":11,"v8":"3.14"},"0.10.28":{"node_abi":11,"v8":"3.14"},"0.10.29":{"node_abi":11,"v8":"3.14"},"0.10.30":{"node_abi":11,"v8":"3.14"},"0.10.31":{"node_abi":11,"v8":"3.14"},"0.10.32":{"node_abi":11,"v8":"3.14"},"0.10.33":{"node_abi":11,"v8":"3.14"},"0.10.34":{"node_abi":11,"v8":"3.14"},"0.10.35":{"node_abi":11,"v8":"3.14"},"0.10.36":{"node_abi":11,"v8":"3.14"},"0.10.37":{"node_abi":11,"v8":"3.14"},"0.10.38":{"node_abi":11,"v8":"3.14"},"0.10.39":{"node_abi":11,"v8":"3.14"},"0.10.40":{"node_abi":11,"v8":"3.14"},"0.10.41":{"node_abi":11,"v8":"3.14"},"0.10.42":{"node_abi":11,"v8":"3.14"},"0.10.43":{"node_abi":11,"v8":"3.14"},"0.10.44":{"node_abi":11,"v8":"3.14"},"0.10.45":{"node_abi":11,"v8":"3.14"},"0.10.46":{"node_abi":11,"v8":"3.14"},"0.10.47":{"node_abi":11,"v8":"3.14"},"0.10.48":{"node_abi":11,"v8":"3.14"},"0.11.0":{"node_abi":12,"v8":"3.17"},"0.11.1":{"node_abi":12,"v8":"3.18"},"0.11.2":{"node_abi":12,"v8":"3.19"},"0.11.3":{"node_abi":12,"v8":"3.19"},"0.11.4":{"node_abi":12,"v8":"3.20"},"0.11.5":{"node_abi":12,"v8":"3.20"},"0.11.6":{"node_abi":12,"v8":"3.20"},"0.11.7":{"node_abi":12,"v8":"3.20"},"0.11.8":{"node_abi":13,"v8":"3.21"},"0.11.9":{"node_abi":13,"v8":"3.22"},"0.11.10":{"node_abi":13,"v8":"3.22"},"0.11.11":{"node_abi":14,"v8":"3.22"},"0.11.12":{"node_abi":14,"v8":"3.22"},"0.11.13":{"node_abi":14,"v8":"3.25"},"0.11.14":{"node_abi":14,"v8":"3.26"},"0.11.15":{"node_abi":14,"v8":"3.28"},"0.11.16":{"node_abi":14,"v8":"3.28"},"0.12.0":{"node_abi":14,"v8":"3.28"},"0.12.1":{"node_abi":14,"v8":"3.28"},"0.12.2":{"node_abi":14,"v8":"3.28"},"0.12.3":{"node_abi":14,"v8":"3.28"},"0.12.4":{"node_abi":14,"v8":"3.28"},"0.12.5":{"node_abi":14,"v8":"3.28"},"0.12.6":{"node_abi":14,"v8":"3.28"},"0.12.7":{"node_abi":14,"v8":"3.28"},"0.12.8":{"node_abi":14,"v8":"3.28"},"0.12.9":{"node_abi":14,"v8":"3.28"},"0.12.10":{"node_abi":14,"v8":"3.28"},"0.12.11":{"node_abi":14,"v8":"3.28"},"0.12.12":{"node_abi":14,"v8":"3.28"},"0.12.13":{"node_abi":14,"v8":"3.28"},"0.12.14":{"node_abi":14,"v8":"3.28"},"0.12.15":{"node_abi":14,"v8":"3.28"},"0.12.16":{"node_abi":14,"v8":"3.28"},"0.12.17":{"node_abi":14,"v8":"3.28"},"0.12.18":{"node_abi":14,"v8":"3.28"},"1.0.0":{"node_abi":42,"v8":"3.31"},"1.0.1":{"node_abi":42,"v8":"3.31"},"1.0.2":{"node_abi":42,"v8":"3.31"},"1.0.3":{"node_abi":42,"v8":"4.1"},"1.0.4":{"node_abi":42,"v8":"4.1"},"1.1.0":{"node_abi":43,"v8":"4.1"},"1.2.0":{"node_abi":43,"v8":"4.1"},"1.3.0":{"node_abi":43,"v8":"4.1"},"1.4.1":{"node_abi":43,"v8":"4.1"},"1.4.2":{"node_abi":43,"v8":"4.1"},"1.4.3":{"node_abi":43,"v8":"4.1"},"1.5.0":{"node_abi":43,"v8":"4.1"},"1.5.1":{"node_abi":43,"v8":"4.1"},"1.6.0":{"node_abi":43,"v8":"4.1"},"1.6.1":{"node_abi":43,"v8":"4.1"},"1.6.2":{"node_abi":43,"v8":"4.1"},"1.6.3":{"node_abi":43,"v8":"4.1"},"1.6.4":{"node_abi":43,"v8":"4.1"},"1.7.1":{"node_abi":43,"v8":"4.1"},"1.8.1":{"node_abi":43,"v8":"4.1"},"1.8.2":{"node_abi":43,"v8":"4.1"},"1.8.3":{"node_abi":43,"v8":"4.1"},"1.8.4":{"node_abi":43,"v8":"4.1"},"2.0.0":{"node_abi":44,"v8":"4.2"},"2.0.1":{"node_abi":44,"v8":"4.2"},"2.0.2":{"node_abi":44,"v8":"4.2"},"2.1.0":{"node_abi":44,"v8":"4.2"},"2.2.0":{"node_abi":44,"v8":"4.2"},"2.2.1":{"node_abi":44,"v8":"4.2"},"2.3.0":{"node_abi":44,"v8":"4.2"},"2.3.1":{"node_abi":44,"v8":"4.2"},"2.3.2":{"node_abi":44,"v8":"4.2"},"2.3.3":{"node_abi":44,"v8":"4.2"},"2.3.4":{"node_abi":44,"v8":"4.2"},"2.4.0":{"node_abi":44,"v8":"4.2"},"2.5.0":{"node_abi":44,"v8":"4.2"},"3.0.0":{"node_abi":45,"v8":"4.4"},"3.1.0":{"node_abi":45,"v8":"4.4"},"3.2.0":{"node_abi":45,"v8":"4.4"},"3.3.0":{"node_abi":45,"v8":"4.4"},"3.3.1":{"node_abi":45,"v8":"4.4"},"4.0.0":{"node_abi":46,"v8":"4.5"},"4.1.0":{"node_abi":46,"v8":"4.5"},"4.1.1":{"node_abi":46,"v8":"4.5"},"4.1.2":{"node_abi":46,"v8":"4.5"},"4.2.0":{"node_abi":46,"v8":"4.5"},"4.2.1":{"node_abi":46,"v8":"4.5"},"4.2.2":{"node_abi":46,"v8":"4.5"},"4.2.3":{"node_abi":46,"v8":"4.5"},"4.2.4":{"node_abi":46,"v8":"4.5"},"4.2.5":{"node_abi":46,"v8":"4.5"},"4.2.6":{"node_abi":46,"v8":"4.5"},"4.3.0":{"node_abi":46,"v8":"4.5"},"4.3.1":{"node_abi":46,"v8":"4.5"},"4.3.2":{"node_abi":46,"v8":"4.5"},"4.4.0":{"node_abi":46,"v8":"4.5"},"4.4.1":{"node_abi":46,"v8":"4.5"},"4.4.2":{"node_abi":46,"v8":"4.5"},"4.4.3":{"node_abi":46,"v8":"4.5"},"4.4.4":{"node_abi":46,"v8":"4.5"},"4.4.5":{"node_abi":46,"v8":"4.5"},"4.4.6":{"node_abi":46,"v8":"4.5"},"4.4.7":{"node_abi":46,"v8":"4.5"},"4.5.0":{"node_abi":46,"v8":"4.5"},"4.6.0":{"node_abi":46,"v8":"4.5"},"4.6.1":{"node_abi":46,"v8":"4.5"},"4.6.2":{"node_abi":46,"v8":"4.5"},"4.7.0":{"node_abi":46,"v8":"4.5"},"4.7.1":{"node_abi":46,"v8":"4.5"},"4.7.2":{"node_abi":46,"v8":"4.5"},"4.7.3":{"node_abi":46,"v8":"4.5"},"4.8.0":{"node_abi":46,"v8":"4.5"},"4.8.1":{"node_abi":46,"v8":"4.5"},"4.8.2":{"node_abi":46,"v8":"4.5"},"4.8.3":{"node_abi":46,"v8":"4.5"},"4.8.4":{"node_abi":46,"v8":"4.5"},"4.8.5":{"node_abi":46,"v8":"4.5"},"4.8.6":{"node_abi":46,"v8":"4.5"},"4.8.7":{"node_abi":46,"v8":"4.5"},"4.9.0":{"node_abi":46,"v8":"4.5"},"4.9.1":{"node_abi":46,"v8":"4.5"},"5.0.0":{"node_abi":47,"v8":"4.6"},"5.1.0":{"node_abi":47,"v8":"4.6"},"5.1.1":{"node_abi":47,"v8":"4.6"},"5.2.0":{"node_abi":47,"v8":"4.6"},"5.3.0":{"node_abi":47,"v8":"4.6"},"5.4.0":{"node_abi":47,"v8":"4.6"},"5.4.1":{"node_abi":47,"v8":"4.6"},"5.5.0":{"node_abi":47,"v8":"4.6"},"5.6.0":{"node_abi":47,"v8":"4.6"},"5.7.0":{"node_abi":47,"v8":"4.6"},"5.7.1":{"node_abi":47,"v8":"4.6"},"5.8.0":{"node_abi":47,"v8":"4.6"},"5.9.0":{"node_abi":47,"v8":"4.6"},"5.9.1":{"node_abi":47,"v8":"4.6"},"5.10.0":{"node_abi":47,"v8":"4.6"},"5.10.1":{"node_abi":47,"v8":"4.6"},"5.11.0":{"node_abi":47,"v8":"4.6"},"5.11.1":{"node_abi":47,"v8":"4.6"},"5.12.0":{"node_abi":47,"v8":"4.6"},"6.0.0":{"node_abi":48,"v8":"5.0"},"6.1.0":{"node_abi":48,"v8":"5.0"},"6.2.0":{"node_abi":48,"v8":"5.0"},"6.2.1":{"node_abi":48,"v8":"5.0"},"6.2.2":{"node_abi":48,"v8":"5.0"},"6.3.0":{"node_abi":48,"v8":"5.0"},"6.3.1":{"node_abi":48,"v8":"5.0"},"6.4.0":{"node_abi":48,"v8":"5.0"},"6.5.0":{"node_abi":48,"v8":"5.1"},"6.6.0":{"node_abi":48,"v8":"5.1"},"6.7.0":{"node_abi":48,"v8":"5.1"},"6.8.0":{"node_abi":48,"v8":"5.1"},"6.8.1":{"node_abi":48,"v8":"5.1"},"6.9.0":{"node_abi":48,"v8":"5.1"},"6.9.1":{"node_abi":48,"v8":"5.1"},"6.9.2":{"node_abi":48,"v8":"5.1"},"6.9.3":{"node_abi":48,"v8":"5.1"},"6.9.4":{"node_abi":48,"v8":"5.1"},"6.9.5":{"node_abi":48,"v8":"5.1"},"6.10.0":{"node_abi":48,"v8":"5.1"},"6.10.1":{"node_abi":48,"v8":"5.1"},"6.10.2":{"node_abi":48,"v8":"5.1"},"6.10.3":{"node_abi":48,"v8":"5.1"},"6.11.0":{"node_abi":48,"v8":"5.1"},"6.11.1":{"node_abi":48,"v8":"5.1"},"6.11.2":{"node_abi":48,"v8":"5.1"},"6.11.3":{"node_abi":48,"v8":"5.1"},"6.11.4":{"node_abi":48,"v8":"5.1"},"6.11.5":{"node_abi":48,"v8":"5.1"},"6.12.0":{"node_abi":48,"v8":"5.1"},"6.12.1":{"node_abi":48,"v8":"5.1"},"6.12.2":{"node_abi":48,"v8":"5.1"},"6.12.3":{"node_abi":48,"v8":"5.1"},"6.13.0":{"node_abi":48,"v8":"5.1"},"6.13.1":{"node_abi":48,"v8":"5.1"},"6.14.0":{"node_abi":48,"v8":"5.1"},"6.14.1":{"node_abi":48,"v8":"5.1"},"6.14.2":{"node_abi":48,"v8":"5.1"},"6.14.3":{"node_abi":48,"v8":"5.1"},"6.14.4":{"node_abi":48,"v8":"5.1"},"6.15.0":{"node_abi":48,"v8":"5.1"},"6.15.1":{"node_abi":48,"v8":"5.1"},"6.16.0":{"node_abi":48,"v8":"5.1"},"6.17.0":{"node_abi":48,"v8":"5.1"},"6.17.1":{"node_abi":48,"v8":"5.1"},"7.0.0":{"node_abi":51,"v8":"5.4"},"7.1.0":{"node_abi":51,"v8":"5.4"},"7.2.0":{"node_abi":51,"v8":"5.4"},"7.2.1":{"node_abi":51,"v8":"5.4"},"7.3.0":{"node_abi":51,"v8":"5.4"},"7.4.0":{"node_abi":51,"v8":"5.4"},"7.5.0":{"node_abi":51,"v8":"5.4"},"7.6.0":{"node_abi":51,"v8":"5.5"},"7.7.0":{"node_abi":51,"v8":"5.5"},"7.7.1":{"node_abi":51,"v8":"5.5"},"7.7.2":{"node_abi":51,"v8":"5.5"},"7.7.3":{"node_abi":51,"v8":"5.5"},"7.7.4":{"node_abi":51,"v8":"5.5"},"7.8.0":{"node_abi":51,"v8":"5.5"},"7.9.0":{"node_abi":51,"v8":"5.5"},"7.10.0":{"node_abi":51,"v8":"5.5"},"7.10.1":{"node_abi":51,"v8":"5.5"},"8.0.0":{"node_abi":57,"v8":"5.8"},"8.1.0":{"node_abi":57,"v8":"5.8"},"8.1.1":{"node_abi":57,"v8":"5.8"},"8.1.2":{"node_abi":57,"v8":"5.8"},"8.1.3":{"node_abi":57,"v8":"5.8"},"8.1.4":{"node_abi":57,"v8":"5.8"},"8.2.0":{"node_abi":57,"v8":"5.8"},"8.2.1":{"node_abi":57,"v8":"5.8"},"8.3.0":{"node_abi":57,"v8":"6.0"},"8.4.0":{"node_abi":57,"v8":"6.0"},"8.5.0":{"node_abi":57,"v8":"6.0"},"8.6.0":{"node_abi":57,"v8":"6.0"},"8.7.0":{"node_abi":57,"v8":"6.1"},"8.8.0":{"node_abi":57,"v8":"6.1"},"8.8.1":{"node_abi":57,"v8":"6.1"},"8.9.0":{"node_abi":57,"v8":"6.1"},"8.9.1":{"node_abi":57,"v8":"6.1"},"8.9.2":{"node_abi":57,"v8":"6.1"},"8.9.3":{"node_abi":57,"v8":"6.1"},"8.9.4":{"node_abi":57,"v8":"6.1"},"8.10.0":{"node_abi":57,"v8":"6.2"},"8.11.0":{"node_abi":57,"v8":"6.2"},"8.11.1":{"node_abi":57,"v8":"6.2"},"8.11.2":{"node_abi":57,"v8":"6.2"},"8.11.3":{"node_abi":57,"v8":"6.2"},"8.11.4":{"node_abi":57,"v8":"6.2"},"8.12.0":{"node_abi":57,"v8":"6.2"},"8.13.0":{"node_abi":57,"v8":"6.2"},"8.14.0":{"node_abi":57,"v8":"6.2"},"8.14.1":{"node_abi":57,"v8":"6.2"},"8.15.0":{"node_abi":57,"v8":"6.2"},"8.15.1":{"node_abi":57,"v8":"6.2"},"8.16.0":{"node_abi":57,"v8":"6.2"},"8.16.1":{"node_abi":57,"v8":"6.2"},"8.16.2":{"node_abi":57,"v8":"6.2"},"8.17.0":{"node_abi":57,"v8":"6.2"},"9.0.0":{"node_abi":59,"v8":"6.2"},"9.1.0":{"node_abi":59,"v8":"6.2"},"9.2.0":{"node_abi":59,"v8":"6.2"},"9.2.1":{"node_abi":59,"v8":"6.2"},"9.3.0":{"node_abi":59,"v8":"6.2"},"9.4.0":{"node_abi":59,"v8":"6.2"},"9.5.0":{"node_abi":59,"v8":"6.2"},"9.6.0":{"node_abi":59,"v8":"6.2"},"9.6.1":{"node_abi":59,"v8":"6.2"},"9.7.0":{"node_abi":59,"v8":"6.2"},"9.7.1":{"node_abi":59,"v8":"6.2"},"9.8.0":{"node_abi":59,"v8":"6.2"},"9.9.0":{"node_abi":59,"v8":"6.2"},"9.10.0":{"node_abi":59,"v8":"6.2"},"9.10.1":{"node_abi":59,"v8":"6.2"},"9.11.0":{"node_abi":59,"v8":"6.2"},"9.11.1":{"node_abi":59,"v8":"6.2"},"9.11.2":{"node_abi":59,"v8":"6.2"},"10.0.0":{"node_abi":64,"v8":"6.6"},"10.1.0":{"node_abi":64,"v8":"6.6"},"10.2.0":{"node_abi":64,"v8":"6.6"},"10.2.1":{"node_abi":64,"v8":"6.6"},"10.3.0":{"node_abi":64,"v8":"6.6"},"10.4.0":{"node_abi":64,"v8":"6.7"},"10.4.1":{"node_abi":64,"v8":"6.7"},"10.5.0":{"node_abi":64,"v8":"6.7"},"10.6.0":{"node_abi":64,"v8":"6.7"},"10.7.0":{"node_abi":64,"v8":"6.7"},"10.8.0":{"node_abi":64,"v8":"6.7"},"10.9.0":{"node_abi":64,"v8":"6.8"},"10.10.0":{"node_abi":64,"v8":"6.8"},"10.11.0":{"node_abi":64,"v8":"6.8"},"10.12.0":{"node_abi":64,"v8":"6.8"},"10.13.0":{"node_abi":64,"v8":"6.8"},"10.14.0":{"node_abi":64,"v8":"6.8"},"10.14.1":{"node_abi":64,"v8":"6.8"},"10.14.2":{"node_abi":64,"v8":"6.8"},"10.15.0":{"node_abi":64,"v8":"6.8"},"10.15.1":{"node_abi":64,"v8":"6.8"},"10.15.2":{"node_abi":64,"v8":"6.8"},"10.15.3":{"node_abi":64,"v8":"6.8"},"10.16.0":{"node_abi":64,"v8":"6.8"},"10.16.1":{"node_abi":64,"v8":"6.8"},"10.16.2":{"node_abi":64,"v8":"6.8"},"10.16.3":{"node_abi":64,"v8":"6.8"},"10.17.0":{"node_abi":64,"v8":"6.8"},"10.18.0":{"node_abi":64,"v8":"6.8"},"10.18.1":{"node_abi":64,"v8":"6.8"},"10.19.0":{"node_abi":64,"v8":"6.8"},"10.20.0":{"node_abi":64,"v8":"6.8"},"10.20.1":{"node_abi":64,"v8":"6.8"},"10.21.0":{"node_abi":64,"v8":"6.8"},"10.22.0":{"node_abi":64,"v8":"6.8"},"10.22.1":{"node_abi":64,"v8":"6.8"},"10.23.0":{"node_abi":64,"v8":"6.8"},"10.23.1":{"node_abi":64,"v8":"6.8"},"10.23.2":{"node_abi":64,"v8":"6.8"},"10.23.3":{"node_abi":64,"v8":"6.8"},"10.24.0":{"node_abi":64,"v8":"6.8"},"10.24.1":{"node_abi":64,"v8":"6.8"},"11.0.0":{"node_abi":67,"v8":"7.0"},"11.1.0":{"node_abi":67,"v8":"7.0"},"11.2.0":{"node_abi":67,"v8":"7.0"},"11.3.0":{"node_abi":67,"v8":"7.0"},"11.4.0":{"node_abi":67,"v8":"7.0"},"11.5.0":{"node_abi":67,"v8":"7.0"},"11.6.0":{"node_abi":67,"v8":"7.0"},"11.7.0":{"node_abi":67,"v8":"7.0"},"11.8.0":{"node_abi":67,"v8":"7.0"},"11.9.0":{"node_abi":67,"v8":"7.0"},"11.10.0":{"node_abi":67,"v8":"7.0"},"11.10.1":{"node_abi":67,"v8":"7.0"},"11.11.0":{"node_abi":67,"v8":"7.0"},"11.12.0":{"node_abi":67,"v8":"7.0"},"11.13.0":{"node_abi":67,"v8":"7.0"},"11.14.0":{"node_abi":67,"v8":"7.0"},"11.15.0":{"node_abi":67,"v8":"7.0"},"12.0.0":{"node_abi":72,"v8":"7.4"},"12.1.0":{"node_abi":72,"v8":"7.4"},"12.2.0":{"node_abi":72,"v8":"7.4"},"12.3.0":{"node_abi":72,"v8":"7.4"},"12.3.1":{"node_abi":72,"v8":"7.4"},"12.4.0":{"node_abi":72,"v8":"7.4"},"12.5.0":{"node_abi":72,"v8":"7.5"},"12.6.0":{"node_abi":72,"v8":"7.5"},"12.7.0":{"node_abi":72,"v8":"7.5"},"12.8.0":{"node_abi":72,"v8":"7.5"},"12.8.1":{"node_abi":72,"v8":"7.5"},"12.9.0":{"node_abi":72,"v8":"7.6"},"12.9.1":{"node_abi":72,"v8":"7.6"},"12.10.0":{"node_abi":72,"v8":"7.6"},"12.11.0":{"node_abi":72,"v8":"7.7"},"12.11.1":{"node_abi":72,"v8":"7.7"},"12.12.0":{"node_abi":72,"v8":"7.7"},"12.13.0":{"node_abi":72,"v8":"7.7"},"12.13.1":{"node_abi":72,"v8":"7.7"},"12.14.0":{"node_abi":72,"v8":"7.7"},"12.14.1":{"node_abi":72,"v8":"7.7"},"12.15.0":{"node_abi":72,"v8":"7.7"},"12.16.0":{"node_abi":72,"v8":"7.8"},"12.16.1":{"node_abi":72,"v8":"7.8"},"12.16.2":{"node_abi":72,"v8":"7.8"},"12.16.3":{"node_abi":72,"v8":"7.8"},"12.17.0":{"node_abi":72,"v8":"7.8"},"12.18.0":{"node_abi":72,"v8":"7.8"},"12.18.1":{"node_abi":72,"v8":"7.8"},"12.18.2":{"node_abi":72,"v8":"7.8"},"12.18.3":{"node_abi":72,"v8":"7.8"},"12.18.4":{"node_abi":72,"v8":"7.8"},"12.19.0":{"node_abi":72,"v8":"7.8"},"12.19.1":{"node_abi":72,"v8":"7.8"},"12.20.0":{"node_abi":72,"v8":"7.8"},"12.20.1":{"node_abi":72,"v8":"7.8"},"12.20.2":{"node_abi":72,"v8":"7.8"},"12.21.0":{"node_abi":72,"v8":"7.8"},"12.22.0":{"node_abi":72,"v8":"7.8"},"12.22.1":{"node_abi":72,"v8":"7.8"},"13.0.0":{"node_abi":79,"v8":"7.8"},"13.0.1":{"node_abi":79,"v8":"7.8"},"13.1.0":{"node_abi":79,"v8":"7.8"},"13.2.0":{"node_abi":79,"v8":"7.9"},"13.3.0":{"node_abi":79,"v8":"7.9"},"13.4.0":{"node_abi":79,"v8":"7.9"},"13.5.0":{"node_abi":79,"v8":"7.9"},"13.6.0":{"node_abi":79,"v8":"7.9"},"13.7.0":{"node_abi":79,"v8":"7.9"},"13.8.0":{"node_abi":79,"v8":"7.9"},"13.9.0":{"node_abi":79,"v8":"7.9"},"13.10.0":{"node_abi":79,"v8":"7.9"},"13.10.1":{"node_abi":79,"v8":"7.9"},"13.11.0":{"node_abi":79,"v8":"7.9"},"13.12.0":{"node_abi":79,"v8":"7.9"},"13.13.0":{"node_abi":79,"v8":"7.9"},"13.14.0":{"node_abi":79,"v8":"7.9"},"14.0.0":{"node_abi":83,"v8":"8.1"},"14.1.0":{"node_abi":83,"v8":"8.1"},"14.2.0":{"node_abi":83,"v8":"8.1"},"14.3.0":{"node_abi":83,"v8":"8.1"},"14.4.0":{"node_abi":83,"v8":"8.1"},"14.5.0":{"node_abi":83,"v8":"8.3"},"14.6.0":{"node_abi":83,"v8":"8.4"},"14.7.0":{"node_abi":83,"v8":"8.4"},"14.8.0":{"node_abi":83,"v8":"8.4"},"14.9.0":{"node_abi":83,"v8":"8.4"},"14.10.0":{"node_abi":83,"v8":"8.4"},"14.10.1":{"node_abi":83,"v8":"8.4"},"14.11.0":{"node_abi":83,"v8":"8.4"},"14.12.0":{"node_abi":83,"v8":"8.4"},"14.13.0":{"node_abi":83,"v8":"8.4"},"14.13.1":{"node_abi":83,"v8":"8.4"},"14.14.0":{"node_abi":83,"v8":"8.4"},"14.15.0":{"node_abi":83,"v8":"8.4"},"14.15.1":{"node_abi":83,"v8":"8.4"},"14.15.2":{"node_abi":83,"v8":"8.4"},"14.15.3":{"node_abi":83,"v8":"8.4"},"14.15.4":{"node_abi":83,"v8":"8.4"},"14.15.5":{"node_abi":83,"v8":"8.4"},"14.16.0":{"node_abi":83,"v8":"8.4"},"14.16.1":{"node_abi":83,"v8":"8.4"},"15.0.0":{"node_abi":88,"v8":"8.6"},"15.0.1":{"node_abi":88,"v8":"8.6"},"15.1.0":{"node_abi":88,"v8":"8.6"},"15.2.0":{"node_abi":88,"v8":"8.6"},"15.2.1":{"node_abi":88,"v8":"8.6"},"15.3.0":{"node_abi":88,"v8":"8.6"},"15.4.0":{"node_abi":88,"v8":"8.6"},"15.5.0":{"node_abi":88,"v8":"8.6"},"15.5.1":{"node_abi":88,"v8":"8.6"},"15.6.0":{"node_abi":88,"v8":"8.6"},"15.7.0":{"node_abi":88,"v8":"8.6"},"15.8.0":{"node_abi":88,"v8":"8.6"},"15.9.0":{"node_abi":88,"v8":"8.6"},"15.10.0":{"node_abi":88,"v8":"8.6"},"15.11.0":{"node_abi":88,"v8":"8.6"},"15.12.0":{"node_abi":88,"v8":"8.6"},"15.13.0":{"node_abi":88,"v8":"8.6"},"15.14.0":{"node_abi":88,"v8":"8.6"},"16.0.0":{"node_abi":93,"v8":"9.0"}}')},9286:e=>{"use strict";e.exports=JSON.parse('{"name":"@mapbox/node-pre-gyp","description":"Node.js native addon binary install tool","version":"1.0.5","keywords":["native","addon","module","c","c++","bindings","binary"],"license":"BSD-3-Clause","author":"Dane Springmeyer ","repository":{"type":"git","url":"git://github.com/mapbox/node-pre-gyp.git"},"bin":"./bin/node-pre-gyp","main":"./lib/node-pre-gyp.js","dependencies":{"detect-libc":"^1.0.3","https-proxy-agent":"^5.0.0","make-dir":"^3.1.0","node-fetch":"^2.6.1","nopt":"^5.0.0","npmlog":"^4.1.2","rimraf":"^3.0.2","semver":"^7.3.4","tar":"^6.1.0"},"devDependencies":{"@mapbox/cloudfriend":"^4.6.0","@mapbox/eslint-config-mapbox":"^3.0.0","action-walk":"^2.2.0","aws-sdk":"^2.840.0","codecov":"^3.8.1","eslint":"^7.18.0","eslint-plugin-node":"^11.1.0","mock-aws-s3":"^4.0.1","nock":"^12.0.3","node-addon-api":"^3.1.0","nyc":"^15.1.0","tape":"^5.2.2","tar-fs":"^2.1.1"},"nyc":{"all":true,"skip-full":false,"exclude":["test/**"]},"scripts":{"coverage":"nyc --all --include index.js --include lib/ npm test","upload-coverage":"nyc report --reporter json && codecov --clear --flags=unit --file=./coverage/coverage-final.json","lint":"eslint bin/node-pre-gyp lib/*js lib/util/*js test/*js scripts/*js","fix":"npm run lint -- --fix","update-crosswalk":"node scripts/abi_crosswalk.js","test":"tape test/*test.js"}}')},7316:e=>{"use strict";e.exports=JSON.parse('{"0.1.14":{"node_abi":null,"v8":"1.3"},"0.1.15":{"node_abi":null,"v8":"1.3"},"0.1.16":{"node_abi":null,"v8":"1.3"},"0.1.17":{"node_abi":null,"v8":"1.3"},"0.1.18":{"node_abi":null,"v8":"1.3"},"0.1.19":{"node_abi":null,"v8":"2.0"},"0.1.20":{"node_abi":null,"v8":"2.0"},"0.1.21":{"node_abi":null,"v8":"2.0"},"0.1.22":{"node_abi":null,"v8":"2.0"},"0.1.23":{"node_abi":null,"v8":"2.0"},"0.1.24":{"node_abi":null,"v8":"2.0"},"0.1.25":{"node_abi":null,"v8":"2.0"},"0.1.26":{"node_abi":null,"v8":"2.0"},"0.1.27":{"node_abi":null,"v8":"2.1"},"0.1.28":{"node_abi":null,"v8":"2.1"},"0.1.29":{"node_abi":null,"v8":"2.1"},"0.1.30":{"node_abi":null,"v8":"2.1"},"0.1.31":{"node_abi":null,"v8":"2.1"},"0.1.32":{"node_abi":null,"v8":"2.1"},"0.1.33":{"node_abi":null,"v8":"2.1"},"0.1.90":{"node_abi":null,"v8":"2.2"},"0.1.91":{"node_abi":null,"v8":"2.2"},"0.1.92":{"node_abi":null,"v8":"2.2"},"0.1.93":{"node_abi":null,"v8":"2.2"},"0.1.94":{"node_abi":null,"v8":"2.2"},"0.1.95":{"node_abi":null,"v8":"2.2"},"0.1.96":{"node_abi":null,"v8":"2.2"},"0.1.97":{"node_abi":null,"v8":"2.2"},"0.1.98":{"node_abi":null,"v8":"2.2"},"0.1.99":{"node_abi":null,"v8":"2.2"},"0.1.100":{"node_abi":null,"v8":"2.2"},"0.1.101":{"node_abi":null,"v8":"2.3"},"0.1.102":{"node_abi":null,"v8":"2.3"},"0.1.103":{"node_abi":null,"v8":"2.3"},"0.1.104":{"node_abi":null,"v8":"2.3"},"0.2.0":{"node_abi":1,"v8":"2.3"},"0.2.1":{"node_abi":1,"v8":"2.3"},"0.2.2":{"node_abi":1,"v8":"2.3"},"0.2.3":{"node_abi":1,"v8":"2.3"},"0.2.4":{"node_abi":1,"v8":"2.3"},"0.2.5":{"node_abi":1,"v8":"2.3"},"0.2.6":{"node_abi":1,"v8":"2.3"},"0.3.0":{"node_abi":1,"v8":"2.5"},"0.3.1":{"node_abi":1,"v8":"2.5"},"0.3.2":{"node_abi":1,"v8":"3.0"},"0.3.3":{"node_abi":1,"v8":"3.0"},"0.3.4":{"node_abi":1,"v8":"3.0"},"0.3.5":{"node_abi":1,"v8":"3.0"},"0.3.6":{"node_abi":1,"v8":"3.0"},"0.3.7":{"node_abi":1,"v8":"3.0"},"0.3.8":{"node_abi":1,"v8":"3.1"},"0.4.0":{"node_abi":1,"v8":"3.1"},"0.4.1":{"node_abi":1,"v8":"3.1"},"0.4.2":{"node_abi":1,"v8":"3.1"},"0.4.3":{"node_abi":1,"v8":"3.1"},"0.4.4":{"node_abi":1,"v8":"3.1"},"0.4.5":{"node_abi":1,"v8":"3.1"},"0.4.6":{"node_abi":1,"v8":"3.1"},"0.4.7":{"node_abi":1,"v8":"3.1"},"0.4.8":{"node_abi":1,"v8":"3.1"},"0.4.9":{"node_abi":1,"v8":"3.1"},"0.4.10":{"node_abi":1,"v8":"3.1"},"0.4.11":{"node_abi":1,"v8":"3.1"},"0.4.12":{"node_abi":1,"v8":"3.1"},"0.5.0":{"node_abi":1,"v8":"3.1"},"0.5.1":{"node_abi":1,"v8":"3.4"},"0.5.2":{"node_abi":1,"v8":"3.4"},"0.5.3":{"node_abi":1,"v8":"3.4"},"0.5.4":{"node_abi":1,"v8":"3.5"},"0.5.5":{"node_abi":1,"v8":"3.5"},"0.5.6":{"node_abi":1,"v8":"3.6"},"0.5.7":{"node_abi":1,"v8":"3.6"},"0.5.8":{"node_abi":1,"v8":"3.6"},"0.5.9":{"node_abi":1,"v8":"3.6"},"0.5.10":{"node_abi":1,"v8":"3.7"},"0.6.0":{"node_abi":1,"v8":"3.6"},"0.6.1":{"node_abi":1,"v8":"3.6"},"0.6.2":{"node_abi":1,"v8":"3.6"},"0.6.3":{"node_abi":1,"v8":"3.6"},"0.6.4":{"node_abi":1,"v8":"3.6"},"0.6.5":{"node_abi":1,"v8":"3.6"},"0.6.6":{"node_abi":1,"v8":"3.6"},"0.6.7":{"node_abi":1,"v8":"3.6"},"0.6.8":{"node_abi":1,"v8":"3.6"},"0.6.9":{"node_abi":1,"v8":"3.6"},"0.6.10":{"node_abi":1,"v8":"3.6"},"0.6.11":{"node_abi":1,"v8":"3.6"},"0.6.12":{"node_abi":1,"v8":"3.6"},"0.6.13":{"node_abi":1,"v8":"3.6"},"0.6.14":{"node_abi":1,"v8":"3.6"},"0.6.15":{"node_abi":1,"v8":"3.6"},"0.6.16":{"node_abi":1,"v8":"3.6"},"0.6.17":{"node_abi":1,"v8":"3.6"},"0.6.18":{"node_abi":1,"v8":"3.6"},"0.6.19":{"node_abi":1,"v8":"3.6"},"0.6.20":{"node_abi":1,"v8":"3.6"},"0.6.21":{"node_abi":1,"v8":"3.6"},"0.7.0":{"node_abi":1,"v8":"3.8"},"0.7.1":{"node_abi":1,"v8":"3.8"},"0.7.2":{"node_abi":1,"v8":"3.8"},"0.7.3":{"node_abi":1,"v8":"3.9"},"0.7.4":{"node_abi":1,"v8":"3.9"},"0.7.5":{"node_abi":1,"v8":"3.9"},"0.7.6":{"node_abi":1,"v8":"3.9"},"0.7.7":{"node_abi":1,"v8":"3.9"},"0.7.8":{"node_abi":1,"v8":"3.9"},"0.7.9":{"node_abi":1,"v8":"3.11"},"0.7.10":{"node_abi":1,"v8":"3.9"},"0.7.11":{"node_abi":1,"v8":"3.11"},"0.7.12":{"node_abi":1,"v8":"3.11"},"0.8.0":{"node_abi":1,"v8":"3.11"},"0.8.1":{"node_abi":1,"v8":"3.11"},"0.8.2":{"node_abi":1,"v8":"3.11"},"0.8.3":{"node_abi":1,"v8":"3.11"},"0.8.4":{"node_abi":1,"v8":"3.11"},"0.8.5":{"node_abi":1,"v8":"3.11"},"0.8.6":{"node_abi":1,"v8":"3.11"},"0.8.7":{"node_abi":1,"v8":"3.11"},"0.8.8":{"node_abi":1,"v8":"3.11"},"0.8.9":{"node_abi":1,"v8":"3.11"},"0.8.10":{"node_abi":1,"v8":"3.11"},"0.8.11":{"node_abi":1,"v8":"3.11"},"0.8.12":{"node_abi":1,"v8":"3.11"},"0.8.13":{"node_abi":1,"v8":"3.11"},"0.8.14":{"node_abi":1,"v8":"3.11"},"0.8.15":{"node_abi":1,"v8":"3.11"},"0.8.16":{"node_abi":1,"v8":"3.11"},"0.8.17":{"node_abi":1,"v8":"3.11"},"0.8.18":{"node_abi":1,"v8":"3.11"},"0.8.19":{"node_abi":1,"v8":"3.11"},"0.8.20":{"node_abi":1,"v8":"3.11"},"0.8.21":{"node_abi":1,"v8":"3.11"},"0.8.22":{"node_abi":1,"v8":"3.11"},"0.8.23":{"node_abi":1,"v8":"3.11"},"0.8.24":{"node_abi":1,"v8":"3.11"},"0.8.25":{"node_abi":1,"v8":"3.11"},"0.8.26":{"node_abi":1,"v8":"3.11"},"0.8.27":{"node_abi":1,"v8":"3.11"},"0.8.28":{"node_abi":1,"v8":"3.11"},"0.9.0":{"node_abi":1,"v8":"3.11"},"0.9.1":{"node_abi":10,"v8":"3.11"},"0.9.2":{"node_abi":10,"v8":"3.11"},"0.9.3":{"node_abi":10,"v8":"3.13"},"0.9.4":{"node_abi":10,"v8":"3.13"},"0.9.5":{"node_abi":10,"v8":"3.13"},"0.9.6":{"node_abi":10,"v8":"3.15"},"0.9.7":{"node_abi":10,"v8":"3.15"},"0.9.8":{"node_abi":10,"v8":"3.15"},"0.9.9":{"node_abi":11,"v8":"3.15"},"0.9.10":{"node_abi":11,"v8":"3.15"},"0.9.11":{"node_abi":11,"v8":"3.14"},"0.9.12":{"node_abi":11,"v8":"3.14"},"0.10.0":{"node_abi":11,"v8":"3.14"},"0.10.1":{"node_abi":11,"v8":"3.14"},"0.10.2":{"node_abi":11,"v8":"3.14"},"0.10.3":{"node_abi":11,"v8":"3.14"},"0.10.4":{"node_abi":11,"v8":"3.14"},"0.10.5":{"node_abi":11,"v8":"3.14"},"0.10.6":{"node_abi":11,"v8":"3.14"},"0.10.7":{"node_abi":11,"v8":"3.14"},"0.10.8":{"node_abi":11,"v8":"3.14"},"0.10.9":{"node_abi":11,"v8":"3.14"},"0.10.10":{"node_abi":11,"v8":"3.14"},"0.10.11":{"node_abi":11,"v8":"3.14"},"0.10.12":{"node_abi":11,"v8":"3.14"},"0.10.13":{"node_abi":11,"v8":"3.14"},"0.10.14":{"node_abi":11,"v8":"3.14"},"0.10.15":{"node_abi":11,"v8":"3.14"},"0.10.16":{"node_abi":11,"v8":"3.14"},"0.10.17":{"node_abi":11,"v8":"3.14"},"0.10.18":{"node_abi":11,"v8":"3.14"},"0.10.19":{"node_abi":11,"v8":"3.14"},"0.10.20":{"node_abi":11,"v8":"3.14"},"0.10.21":{"node_abi":11,"v8":"3.14"},"0.10.22":{"node_abi":11,"v8":"3.14"},"0.10.23":{"node_abi":11,"v8":"3.14"},"0.10.24":{"node_abi":11,"v8":"3.14"},"0.10.25":{"node_abi":11,"v8":"3.14"},"0.10.26":{"node_abi":11,"v8":"3.14"},"0.10.27":{"node_abi":11,"v8":"3.14"},"0.10.28":{"node_abi":11,"v8":"3.14"},"0.10.29":{"node_abi":11,"v8":"3.14"},"0.10.30":{"node_abi":11,"v8":"3.14"},"0.10.31":{"node_abi":11,"v8":"3.14"},"0.10.32":{"node_abi":11,"v8":"3.14"},"0.10.33":{"node_abi":11,"v8":"3.14"},"0.10.34":{"node_abi":11,"v8":"3.14"},"0.10.35":{"node_abi":11,"v8":"3.14"},"0.10.36":{"node_abi":11,"v8":"3.14"},"0.10.37":{"node_abi":11,"v8":"3.14"},"0.10.38":{"node_abi":11,"v8":"3.14"},"0.10.39":{"node_abi":11,"v8":"3.14"},"0.10.40":{"node_abi":11,"v8":"3.14"},"0.10.41":{"node_abi":11,"v8":"3.14"},"0.10.42":{"node_abi":11,"v8":"3.14"},"0.10.43":{"node_abi":11,"v8":"3.14"},"0.10.44":{"node_abi":11,"v8":"3.14"},"0.10.45":{"node_abi":11,"v8":"3.14"},"0.10.46":{"node_abi":11,"v8":"3.14"},"0.10.47":{"node_abi":11,"v8":"3.14"},"0.10.48":{"node_abi":11,"v8":"3.14"},"0.11.0":{"node_abi":12,"v8":"3.17"},"0.11.1":{"node_abi":12,"v8":"3.18"},"0.11.2":{"node_abi":12,"v8":"3.19"},"0.11.3":{"node_abi":12,"v8":"3.19"},"0.11.4":{"node_abi":12,"v8":"3.20"},"0.11.5":{"node_abi":12,"v8":"3.20"},"0.11.6":{"node_abi":12,"v8":"3.20"},"0.11.7":{"node_abi":12,"v8":"3.20"},"0.11.8":{"node_abi":13,"v8":"3.21"},"0.11.9":{"node_abi":13,"v8":"3.22"},"0.11.10":{"node_abi":13,"v8":"3.22"},"0.11.11":{"node_abi":14,"v8":"3.22"},"0.11.12":{"node_abi":14,"v8":"3.22"},"0.11.13":{"node_abi":14,"v8":"3.25"},"0.11.14":{"node_abi":14,"v8":"3.26"},"0.11.15":{"node_abi":14,"v8":"3.28"},"0.11.16":{"node_abi":14,"v8":"3.28"},"0.12.0":{"node_abi":14,"v8":"3.28"},"0.12.1":{"node_abi":14,"v8":"3.28"},"0.12.2":{"node_abi":14,"v8":"3.28"},"0.12.3":{"node_abi":14,"v8":"3.28"},"0.12.4":{"node_abi":14,"v8":"3.28"},"0.12.5":{"node_abi":14,"v8":"3.28"},"0.12.6":{"node_abi":14,"v8":"3.28"},"0.12.7":{"node_abi":14,"v8":"3.28"},"0.12.8":{"node_abi":14,"v8":"3.28"},"0.12.9":{"node_abi":14,"v8":"3.28"},"0.12.10":{"node_abi":14,"v8":"3.28"},"0.12.11":{"node_abi":14,"v8":"3.28"},"0.12.12":{"node_abi":14,"v8":"3.28"},"0.12.13":{"node_abi":14,"v8":"3.28"},"0.12.14":{"node_abi":14,"v8":"3.28"},"0.12.15":{"node_abi":14,"v8":"3.28"},"0.12.16":{"node_abi":14,"v8":"3.28"},"0.12.17":{"node_abi":14,"v8":"3.28"},"0.12.18":{"node_abi":14,"v8":"3.28"},"1.0.0":{"node_abi":42,"v8":"3.31"},"1.0.1":{"node_abi":42,"v8":"3.31"},"1.0.2":{"node_abi":42,"v8":"3.31"},"1.0.3":{"node_abi":42,"v8":"4.1"},"1.0.4":{"node_abi":42,"v8":"4.1"},"1.1.0":{"node_abi":43,"v8":"4.1"},"1.2.0":{"node_abi":43,"v8":"4.1"},"1.3.0":{"node_abi":43,"v8":"4.1"},"1.4.1":{"node_abi":43,"v8":"4.1"},"1.4.2":{"node_abi":43,"v8":"4.1"},"1.4.3":{"node_abi":43,"v8":"4.1"},"1.5.0":{"node_abi":43,"v8":"4.1"},"1.5.1":{"node_abi":43,"v8":"4.1"},"1.6.0":{"node_abi":43,"v8":"4.1"},"1.6.1":{"node_abi":43,"v8":"4.1"},"1.6.2":{"node_abi":43,"v8":"4.1"},"1.6.3":{"node_abi":43,"v8":"4.1"},"1.6.4":{"node_abi":43,"v8":"4.1"},"1.7.1":{"node_abi":43,"v8":"4.1"},"1.8.1":{"node_abi":43,"v8":"4.1"},"1.8.2":{"node_abi":43,"v8":"4.1"},"1.8.3":{"node_abi":43,"v8":"4.1"},"1.8.4":{"node_abi":43,"v8":"4.1"},"2.0.0":{"node_abi":44,"v8":"4.2"},"2.0.1":{"node_abi":44,"v8":"4.2"},"2.0.2":{"node_abi":44,"v8":"4.2"},"2.1.0":{"node_abi":44,"v8":"4.2"},"2.2.0":{"node_abi":44,"v8":"4.2"},"2.2.1":{"node_abi":44,"v8":"4.2"},"2.3.0":{"node_abi":44,"v8":"4.2"},"2.3.1":{"node_abi":44,"v8":"4.2"},"2.3.2":{"node_abi":44,"v8":"4.2"},"2.3.3":{"node_abi":44,"v8":"4.2"},"2.3.4":{"node_abi":44,"v8":"4.2"},"2.4.0":{"node_abi":44,"v8":"4.2"},"2.5.0":{"node_abi":44,"v8":"4.2"},"3.0.0":{"node_abi":45,"v8":"4.4"},"3.1.0":{"node_abi":45,"v8":"4.4"},"3.2.0":{"node_abi":45,"v8":"4.4"},"3.3.0":{"node_abi":45,"v8":"4.4"},"3.3.1":{"node_abi":45,"v8":"4.4"},"4.0.0":{"node_abi":46,"v8":"4.5"},"4.1.0":{"node_abi":46,"v8":"4.5"},"4.1.1":{"node_abi":46,"v8":"4.5"},"4.1.2":{"node_abi":46,"v8":"4.5"},"4.2.0":{"node_abi":46,"v8":"4.5"},"4.2.1":{"node_abi":46,"v8":"4.5"},"4.2.2":{"node_abi":46,"v8":"4.5"},"4.2.3":{"node_abi":46,"v8":"4.5"},"4.2.4":{"node_abi":46,"v8":"4.5"},"4.2.5":{"node_abi":46,"v8":"4.5"},"4.2.6":{"node_abi":46,"v8":"4.5"},"4.3.0":{"node_abi":46,"v8":"4.5"},"4.3.1":{"node_abi":46,"v8":"4.5"},"4.3.2":{"node_abi":46,"v8":"4.5"},"4.4.0":{"node_abi":46,"v8":"4.5"},"4.4.1":{"node_abi":46,"v8":"4.5"},"4.4.2":{"node_abi":46,"v8":"4.5"},"4.4.3":{"node_abi":46,"v8":"4.5"},"4.4.4":{"node_abi":46,"v8":"4.5"},"4.4.5":{"node_abi":46,"v8":"4.5"},"4.4.6":{"node_abi":46,"v8":"4.5"},"4.4.7":{"node_abi":46,"v8":"4.5"},"4.5.0":{"node_abi":46,"v8":"4.5"},"4.6.0":{"node_abi":46,"v8":"4.5"},"4.6.1":{"node_abi":46,"v8":"4.5"},"4.6.2":{"node_abi":46,"v8":"4.5"},"4.7.0":{"node_abi":46,"v8":"4.5"},"4.7.1":{"node_abi":46,"v8":"4.5"},"4.7.2":{"node_abi":46,"v8":"4.5"},"4.7.3":{"node_abi":46,"v8":"4.5"},"4.8.0":{"node_abi":46,"v8":"4.5"},"4.8.1":{"node_abi":46,"v8":"4.5"},"4.8.2":{"node_abi":46,"v8":"4.5"},"4.8.3":{"node_abi":46,"v8":"4.5"},"4.8.4":{"node_abi":46,"v8":"4.5"},"4.8.5":{"node_abi":46,"v8":"4.5"},"4.8.6":{"node_abi":46,"v8":"4.5"},"4.8.7":{"node_abi":46,"v8":"4.5"},"4.9.0":{"node_abi":46,"v8":"4.5"},"4.9.1":{"node_abi":46,"v8":"4.5"},"5.0.0":{"node_abi":47,"v8":"4.6"},"5.1.0":{"node_abi":47,"v8":"4.6"},"5.1.1":{"node_abi":47,"v8":"4.6"},"5.2.0":{"node_abi":47,"v8":"4.6"},"5.3.0":{"node_abi":47,"v8":"4.6"},"5.4.0":{"node_abi":47,"v8":"4.6"},"5.4.1":{"node_abi":47,"v8":"4.6"},"5.5.0":{"node_abi":47,"v8":"4.6"},"5.6.0":{"node_abi":47,"v8":"4.6"},"5.7.0":{"node_abi":47,"v8":"4.6"},"5.7.1":{"node_abi":47,"v8":"4.6"},"5.8.0":{"node_abi":47,"v8":"4.6"},"5.9.0":{"node_abi":47,"v8":"4.6"},"5.9.1":{"node_abi":47,"v8":"4.6"},"5.10.0":{"node_abi":47,"v8":"4.6"},"5.10.1":{"node_abi":47,"v8":"4.6"},"5.11.0":{"node_abi":47,"v8":"4.6"},"5.11.1":{"node_abi":47,"v8":"4.6"},"5.12.0":{"node_abi":47,"v8":"4.6"},"6.0.0":{"node_abi":48,"v8":"5.0"},"6.1.0":{"node_abi":48,"v8":"5.0"},"6.2.0":{"node_abi":48,"v8":"5.0"},"6.2.1":{"node_abi":48,"v8":"5.0"},"6.2.2":{"node_abi":48,"v8":"5.0"},"6.3.0":{"node_abi":48,"v8":"5.0"},"6.3.1":{"node_abi":48,"v8":"5.0"},"6.4.0":{"node_abi":48,"v8":"5.0"},"6.5.0":{"node_abi":48,"v8":"5.1"},"6.6.0":{"node_abi":48,"v8":"5.1"},"6.7.0":{"node_abi":48,"v8":"5.1"},"6.8.0":{"node_abi":48,"v8":"5.1"},"6.8.1":{"node_abi":48,"v8":"5.1"},"6.9.0":{"node_abi":48,"v8":"5.1"},"6.9.1":{"node_abi":48,"v8":"5.1"},"6.9.2":{"node_abi":48,"v8":"5.1"},"6.9.3":{"node_abi":48,"v8":"5.1"},"6.9.4":{"node_abi":48,"v8":"5.1"},"6.9.5":{"node_abi":48,"v8":"5.1"},"6.10.0":{"node_abi":48,"v8":"5.1"},"6.10.1":{"node_abi":48,"v8":"5.1"},"6.10.2":{"node_abi":48,"v8":"5.1"},"6.10.3":{"node_abi":48,"v8":"5.1"},"6.11.0":{"node_abi":48,"v8":"5.1"},"6.11.1":{"node_abi":48,"v8":"5.1"},"6.11.2":{"node_abi":48,"v8":"5.1"},"6.11.3":{"node_abi":48,"v8":"5.1"},"6.11.4":{"node_abi":48,"v8":"5.1"},"6.11.5":{"node_abi":48,"v8":"5.1"},"6.12.0":{"node_abi":48,"v8":"5.1"},"6.12.1":{"node_abi":48,"v8":"5.1"},"6.12.2":{"node_abi":48,"v8":"5.1"},"6.12.3":{"node_abi":48,"v8":"5.1"},"6.13.0":{"node_abi":48,"v8":"5.1"},"6.13.1":{"node_abi":48,"v8":"5.1"},"6.14.0":{"node_abi":48,"v8":"5.1"},"6.14.1":{"node_abi":48,"v8":"5.1"},"6.14.2":{"node_abi":48,"v8":"5.1"},"6.14.3":{"node_abi":48,"v8":"5.1"},"6.14.4":{"node_abi":48,"v8":"5.1"},"6.15.0":{"node_abi":48,"v8":"5.1"},"6.15.1":{"node_abi":48,"v8":"5.1"},"6.16.0":{"node_abi":48,"v8":"5.1"},"6.17.0":{"node_abi":48,"v8":"5.1"},"6.17.1":{"node_abi":48,"v8":"5.1"},"7.0.0":{"node_abi":51,"v8":"5.4"},"7.1.0":{"node_abi":51,"v8":"5.4"},"7.2.0":{"node_abi":51,"v8":"5.4"},"7.2.1":{"node_abi":51,"v8":"5.4"},"7.3.0":{"node_abi":51,"v8":"5.4"},"7.4.0":{"node_abi":51,"v8":"5.4"},"7.5.0":{"node_abi":51,"v8":"5.4"},"7.6.0":{"node_abi":51,"v8":"5.5"},"7.7.0":{"node_abi":51,"v8":"5.5"},"7.7.1":{"node_abi":51,"v8":"5.5"},"7.7.2":{"node_abi":51,"v8":"5.5"},"7.7.3":{"node_abi":51,"v8":"5.5"},"7.7.4":{"node_abi":51,"v8":"5.5"},"7.8.0":{"node_abi":51,"v8":"5.5"},"7.9.0":{"node_abi":51,"v8":"5.5"},"7.10.0":{"node_abi":51,"v8":"5.5"},"7.10.1":{"node_abi":51,"v8":"5.5"},"8.0.0":{"node_abi":57,"v8":"5.8"},"8.1.0":{"node_abi":57,"v8":"5.8"},"8.1.1":{"node_abi":57,"v8":"5.8"},"8.1.2":{"node_abi":57,"v8":"5.8"},"8.1.3":{"node_abi":57,"v8":"5.8"},"8.1.4":{"node_abi":57,"v8":"5.8"},"8.2.0":{"node_abi":57,"v8":"5.8"},"8.2.1":{"node_abi":57,"v8":"5.8"},"8.3.0":{"node_abi":57,"v8":"6.0"},"8.4.0":{"node_abi":57,"v8":"6.0"},"8.5.0":{"node_abi":57,"v8":"6.0"},"8.6.0":{"node_abi":57,"v8":"6.0"},"8.7.0":{"node_abi":57,"v8":"6.1"},"8.8.0":{"node_abi":57,"v8":"6.1"},"8.8.1":{"node_abi":57,"v8":"6.1"},"8.9.0":{"node_abi":57,"v8":"6.1"},"8.9.1":{"node_abi":57,"v8":"6.1"},"8.9.2":{"node_abi":57,"v8":"6.1"},"8.9.3":{"node_abi":57,"v8":"6.1"},"8.9.4":{"node_abi":57,"v8":"6.1"},"8.10.0":{"node_abi":57,"v8":"6.2"},"8.11.0":{"node_abi":57,"v8":"6.2"},"8.11.1":{"node_abi":57,"v8":"6.2"},"8.11.2":{"node_abi":57,"v8":"6.2"},"8.11.3":{"node_abi":57,"v8":"6.2"},"8.11.4":{"node_abi":57,"v8":"6.2"},"8.12.0":{"node_abi":57,"v8":"6.2"},"8.13.0":{"node_abi":57,"v8":"6.2"},"8.14.0":{"node_abi":57,"v8":"6.2"},"8.14.1":{"node_abi":57,"v8":"6.2"},"8.15.0":{"node_abi":57,"v8":"6.2"},"8.15.1":{"node_abi":57,"v8":"6.2"},"8.16.0":{"node_abi":57,"v8":"6.2"},"9.0.0":{"node_abi":59,"v8":"6.2"},"9.1.0":{"node_abi":59,"v8":"6.2"},"9.2.0":{"node_abi":59,"v8":"6.2"},"9.2.1":{"node_abi":59,"v8":"6.2"},"9.3.0":{"node_abi":59,"v8":"6.2"},"9.4.0":{"node_abi":59,"v8":"6.2"},"9.5.0":{"node_abi":59,"v8":"6.2"},"9.6.0":{"node_abi":59,"v8":"6.2"},"9.6.1":{"node_abi":59,"v8":"6.2"},"9.7.0":{"node_abi":59,"v8":"6.2"},"9.7.1":{"node_abi":59,"v8":"6.2"},"9.8.0":{"node_abi":59,"v8":"6.2"},"9.9.0":{"node_abi":59,"v8":"6.2"},"9.10.0":{"node_abi":59,"v8":"6.2"},"9.10.1":{"node_abi":59,"v8":"6.2"},"9.11.0":{"node_abi":59,"v8":"6.2"},"9.11.1":{"node_abi":59,"v8":"6.2"},"9.11.2":{"node_abi":59,"v8":"6.2"},"10.0.0":{"node_abi":64,"v8":"6.6"},"10.1.0":{"node_abi":64,"v8":"6.6"},"10.2.0":{"node_abi":64,"v8":"6.6"},"10.2.1":{"node_abi":64,"v8":"6.6"},"10.3.0":{"node_abi":64,"v8":"6.6"},"10.4.0":{"node_abi":64,"v8":"6.7"},"10.4.1":{"node_abi":64,"v8":"6.7"},"10.5.0":{"node_abi":64,"v8":"6.7"},"10.6.0":{"node_abi":64,"v8":"6.7"},"10.7.0":{"node_abi":64,"v8":"6.7"},"10.8.0":{"node_abi":64,"v8":"6.7"},"10.9.0":{"node_abi":64,"v8":"6.8"},"10.10.0":{"node_abi":64,"v8":"6.8"},"10.11.0":{"node_abi":64,"v8":"6.8"},"10.12.0":{"node_abi":64,"v8":"6.8"},"10.13.0":{"node_abi":64,"v8":"6.8"},"10.14.0":{"node_abi":64,"v8":"6.8"},"10.14.1":{"node_abi":64,"v8":"6.8"},"10.14.2":{"node_abi":64,"v8":"6.8"},"10.15.0":{"node_abi":64,"v8":"6.8"},"10.15.1":{"node_abi":64,"v8":"6.8"},"10.15.2":{"node_abi":64,"v8":"6.8"},"10.15.3":{"node_abi":64,"v8":"6.8"},"11.0.0":{"node_abi":67,"v8":"7.0"},"11.1.0":{"node_abi":67,"v8":"7.0"},"11.2.0":{"node_abi":67,"v8":"7.0"},"11.3.0":{"node_abi":67,"v8":"7.0"},"11.4.0":{"node_abi":67,"v8":"7.0"},"11.5.0":{"node_abi":67,"v8":"7.0"},"11.6.0":{"node_abi":67,"v8":"7.0"},"11.7.0":{"node_abi":67,"v8":"7.0"},"11.8.0":{"node_abi":67,"v8":"7.0"},"11.9.0":{"node_abi":67,"v8":"7.0"},"11.10.0":{"node_abi":67,"v8":"7.0"},"11.10.1":{"node_abi":67,"v8":"7.0"},"11.11.0":{"node_abi":67,"v8":"7.0"},"11.12.0":{"node_abi":67,"v8":"7.0"},"11.13.0":{"node_abi":67,"v8":"7.0"},"11.14.0":{"node_abi":67,"v8":"7.0"},"12.0.0":{"node_abi":72,"v8":"7.4"}}')}};var __webpack_module_cache__={};function __nccwpck_require__(e){var t=__webpack_module_cache__[e];if(t!==undefined){return t.exports}var r=__webpack_module_cache__[e]={exports:{}};var a=true;try{__webpack_modules__[e].call(r.exports,r,r.exports,__nccwpck_require__);a=false}finally{if(a)delete __webpack_module_cache__[e]}return r.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var __webpack_exports__=__nccwpck_require__(9582);module.exports=__webpack_exports__})(); \ No newline at end of file diff --git a/packages/next/compiled/acorn/LICENSE b/packages/next/compiled/acorn/LICENSE new file mode 100644 index 000000000000..d6be6db2cfff --- /dev/null +++ b/packages/next/compiled/acorn/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2012-2020 by various contributors (see AUTHORS) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/packages/next/compiled/acorn/acorn.js b/packages/next/compiled/acorn/acorn.js new file mode 100644 index 000000000000..1b37fdba121b --- /dev/null +++ b/packages/next/compiled/acorn/acorn.js @@ -0,0 +1 @@ +(()=>{var e={108:function(e,t){(function(e,i){true?i(t):0})(this,(function(e){"use strict";var t={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"};var i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var s={5:i,"5module":i+" export import",6:i+" const class extends export import super"};var r=/^in(stanceof)?$/;var a="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-鿼ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var n="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var o=new RegExp("["+a+"]");var h=new RegExp("["+a+n+"]");a=n=null;var p=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];var c=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];function isInAstralSet(e,t){var i=65536;for(var s=0;se){return false}i+=t[s+1];if(i>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&o.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,p)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&h.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,p)||isInAstralSet(e,c)}var l=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new l(e,{beforeExpr:true,binop:t})}var u={beforeExpr:true},f={startsExpr:true};var d={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return d[e]=new l(e,t)}var m={num:new l("num",f),regexp:new l("regexp",f),string:new l("string",f),name:new l("name",f),privateId:new l("privateId",f),eof:new l("eof"),bracketL:new l("[",{beforeExpr:true,startsExpr:true}),bracketR:new l("]"),braceL:new l("{",{beforeExpr:true,startsExpr:true}),braceR:new l("}"),parenL:new l("(",{beforeExpr:true,startsExpr:true}),parenR:new l(")"),comma:new l(",",u),semi:new l(";",u),colon:new l(":",u),dot:new l("."),question:new l("?",u),questionDot:new l("?."),arrow:new l("=>",u),template:new l("template"),invalidTemplate:new l("invalidTemplate"),ellipsis:new l("...",u),backQuote:new l("`",f),dollarBraceL:new l("${",{beforeExpr:true,startsExpr:true}),eq:new l("=",{beforeExpr:true,isAssign:true}),assign:new l("_=",{beforeExpr:true,isAssign:true}),incDec:new l("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new l("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new l("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new l("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",u),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",u),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",u),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",f),_if:kw("if"),_return:kw("return",u),_switch:kw("switch"),_throw:kw("throw",u),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",f),_super:kw("super",f),_class:kw("class",f),_extends:kw("extends",u),_export:kw("export"),_import:kw("import",f),_null:kw("null",f),_true:kw("true",f),_false:kw("false",f),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var g=/\r\n?|\n|\u2028|\u2029/;var x=new RegExp(g.source,"g");function isNewLine(e){return e===10||e===13||e===8232||e===8233}var v=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var y=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var k=Object.prototype;var b=k.hasOwnProperty;var w=k.toString;function has(e,t){return b.call(e,t)}var _=Array.isArray||function(e){return w.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var S=function Position(e,t){this.line=e;this.column=t};S.prototype.offset=function offset(e){return new S(this.line,this.column+e)};var C=function SourceLocation(e,t,i){this.start=t;this.end=i;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var i=1,s=0;;){x.lastIndex=s;var r=x.exec(e);if(r&&r.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(_(t.onToken)){var s=t.onToken;t.onToken=function(e){return s.push(e)}}if(_(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(i,s,r,a,n,o){var h={type:i?"Block":"Line",value:s,start:r,end:a};if(e.locations){h.loc=new C(this,n,o)}if(e.ranges){h.range=[r,a]}t.push(h)}}var A=1,P=2,N=4,T=8,V=16,L=32,R=64,D=128,O=256,B=A|P|O;function functionFlags(e,t){return P|(e?N:0)|(t?T:0)}var M=0,F=1,U=2,q=3,H=4,G=5;var j=function Parser(e,i,r){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(s[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var a="";if(e.allowReserved!==true){a=t[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3];if(e.sourceType==="module"){a+=" await"}}this.reservedWords=wordsRegexp(a);var n=(a?a+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(n);this.reservedWordsStrictBind=wordsRegexp(n+" "+t.strictBind);this.input=String(i);this.containsEsc=false;if(r){this.pos=r;this.lineStart=this.input.lastIndexOf("\n",r-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(g).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=m.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.potentialArrowInForAwait=false;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports=Object.create(null);if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(A);this.regexpState=null;this.privateNameStack=[]};var z={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},canAwait:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true},allowNewDotTarget:{configurable:true},inClassStaticBlock:{configurable:true}};j.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};z.inFunction.get=function(){return(this.currentVarScope().flags&P)>0};z.inGenerator.get=function(){return(this.currentVarScope().flags&T)>0&&!this.currentVarScope().inClassFieldInit};z.inAsync.get=function(){return(this.currentVarScope().flags&N)>0&&!this.currentVarScope().inClassFieldInit};z.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&O){return false}if(t.flags&P){return(t.flags&N)>0}}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};z.allowSuper.get=function(){var e=this.currentThisScope();var t=e.flags;var i=e.inClassFieldInit;return(t&R)>0||i||this.options.allowSuperOutsideMethod};z.allowDirectSuper.get=function(){return(this.currentThisScope().flags&D)>0};z.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};z.allowNewDotTarget.get=function(){var e=this.currentThisScope();var t=e.flags;var i=e.inClassFieldInit;return(t&(P|O))>0||i};z.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&O)>0};j.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var i=this;for(var s=0;s=,?^&]/.test(r)||r==="!"&&this.input.charAt(s+1)==="=")}e+=t[0].length;y.lastIndex=e;e+=y.exec(this.input)[0].length;if(this.input[e]===";"){e++}}};W.eat=function(e){if(this.type===e){this.next();return true}else{return false}};W.isContextual=function(e){return this.type===m.name&&this.value===e&&!this.containsEsc};W.eatContextual=function(e){if(!this.isContextual(e)){return false}this.next();return true};W.expectContextual=function(e){if(!this.eatContextual(e)){this.unexpected()}};W.canInsertSemicolon=function(){return this.type===m.eof||this.type===m.braceR||g.test(this.input.slice(this.lastTokEnd,this.start))};W.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};W.semicolon=function(){if(!this.eat(m.semi)&&!this.insertSemicolon()){this.unexpected()}};W.afterTrailingComma=function(e,t){if(this.type===e){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!t){this.next()}return true}};W.expect=function(e){this.eat(e)||this.unexpected()};W.unexpected=function(e){this.raise(e!=null?e:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}W.checkPatternErrors=function(e,t){if(!e){return}if(e.trailingComma>-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var i=t?e.parenthesizedAssign:e.parenthesizedBind;if(i>-1){this.raiseRecoverable(i,"Parenthesized pattern")}};W.checkExpressionErrors=function(e,t){if(!e){return false}var i=e.shorthandAssign;var s=e.doubleProto;if(!t){return i>=0||s>=0}if(i>=0){this.raise(i,"Shorthand property assignments are valid only in destructuring patterns")}if(s>=0){this.raiseRecoverable(s,"Redefinition of __proto__ property")}};W.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&s<56320){return true}if(e){return false}if(s===123){return true}if(isIdentifierStart(s,true)){var a=i+1;while(isIdentifierChar(s=this.input.charCodeAt(a),true)){++a}if(s===92||s>55295&&s<56320){return true}var n=this.input.slice(i,a);if(!r.test(n)){return true}}return false};K.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async")){return false}y.lastIndex=this.pos;var e=y.exec(this.input);var t=this.pos+e[0].length,i;return!g.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)==="function"&&(t+8===this.input.length||!(isIdentifierChar(i=this.input.charCodeAt(t+8))||i>55295&&i<56320))};K.parseStatement=function(e,t,i){var s=this.type,r=this.startNode(),a;if(this.isLet(e)){s=m._var;a="let"}switch(s){case m._break:case m._continue:return this.parseBreakContinueStatement(r,s.keyword);case m._debugger:return this.parseDebuggerStatement(r);case m._do:return this.parseDoStatement(r);case m._for:return this.parseForStatement(r);case m._function:if(e&&(this.strict||e!=="if"&&e!=="label")&&this.options.ecmaVersion>=6){this.unexpected()}return this.parseFunctionStatement(r,false,!e);case m._class:if(e){this.unexpected()}return this.parseClass(r,true);case m._if:return this.parseIfStatement(r);case m._return:return this.parseReturnStatement(r);case m._switch:return this.parseSwitchStatement(r);case m._throw:return this.parseThrowStatement(r);case m._try:return this.parseTryStatement(r);case m._const:case m._var:a=a||this.value;if(e&&a!=="var"){this.unexpected()}return this.parseVarStatement(r,a);case m._while:return this.parseWhileStatement(r);case m._with:return this.parseWithStatement(r);case m.braceL:return this.parseBlock(true,r);case m.semi:return this.parseEmptyStatement(r);case m._export:case m._import:if(this.options.ecmaVersion>10&&s===m._import){y.lastIndex=this.pos;var n=y.exec(this.input);var o=this.pos+n[0].length,h=this.input.charCodeAt(o);if(h===40||h===46){return this.parseExpressionStatement(r,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return s===m._import?this.parseImport(r):this.parseExport(r,i);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(r,true,!e)}var p=this.value,c=this.parseExpression();if(s===m.name&&c.type==="Identifier"&&this.eat(m.colon)){return this.parseLabeledStatement(r,p,c,e)}else{return this.parseExpressionStatement(r,c)}}};K.parseBreakContinueStatement=function(e,t){var i=t==="break";this.next();if(this.eat(m.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==m.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var s=0;for(;s=6){this.eat(m.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};K.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(Y);this.enterScope(0);this.expect(m.parenL);if(this.type===m.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var i=this.isLet();if(this.type===m._var||this.type===m._const||i){var s=this.startNode(),r=i?"let":this.value;this.next();this.parseVar(s,true,r);this.finishNode(s,"VariableDeclaration");if((this.type===m._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&s.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===m._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,s)}if(t>-1){this.unexpected(t)}return this.parseFor(e,s)}var a=this.isContextual("let"),n=false;var o=new DestructuringErrors;var h=this.parseExpression(t>-1?"await":true,o);if(this.type===m._in||(n=this.options.ecmaVersion>=6&&this.isContextual("of"))){if(this.options.ecmaVersion>=9){if(this.type===m._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}if(a&&n){this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'.")}this.toAssignable(h,false,o);this.checkLValPattern(h);return this.parseForIn(e,h)}else{this.checkExpressionErrors(o,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,h)};K.parseFunctionStatement=function(e,t,i){this.next();return this.parseFunction(e,Z|(i?0:J),false,t)};K.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(m._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};K.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(m.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};K.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(m.braceL);this.labels.push(X);this.enterScope(0);var t;for(var i=false;this.type!==m.braceR;){if(this.type===m._case||this.type===m._default){var s=this.type===m._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(s){t.test=this.parseExpression()}else{if(i){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}i=true;t.test=null}this.expect(m.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};K.parseThrowStatement=function(e){this.next();if(g.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var $=[];K.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===m._catch){var t=this.startNode();this.next();if(this.eat(m.parenL)){t.param=this.parseBindingAtom();var i=t.param.type==="Identifier";this.enterScope(i?L:0);this.checkLValPattern(t.param,i?H:U);this.expect(m.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(m._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};K.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};K.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(Y);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};K.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};K.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};K.parseLabeledStatement=function(e,t,i,s){for(var r=0,a=this.labels;r=0;h--){var p=this.labels[h];if(p.statementStart===e.start){p.statementStart=this.start;p.kind=o}else{break}}this.labels.push({name:t,kind:o,statementStart:this.start});e.body=this.parseStatement(s?s.indexOf("label")===-1?s+"label":s:"label");this.labels.pop();e.label=i;return this.finishNode(e,"LabeledStatement")};K.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};K.parseBlock=function(e,t,i){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(m.braceL);if(e){this.enterScope(0)}while(this.type!==m.braceR){var s=this.parseStatement(null);t.body.push(s)}if(i){this.strict=false}this.next();if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};K.parseFor=function(e,t){e.init=t;this.expect(m.semi);e.test=this.type===m.semi?null:this.parseExpression();this.expect(m.semi);e.update=this.type===m.parenR?null:this.parseExpression();this.expect(m.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};K.parseForIn=function(e,t){var i=this.type===m._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!i||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(i?"for-in":"for-of")+" loop variable declaration may not have an initializer")}e.left=t;e.right=i?this.parseExpression():this.parseMaybeAssign();this.expect(m.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,i?"ForInStatement":"ForOfStatement")};K.parseVar=function(e,t,i){e.declarations=[];e.kind=i;for(;;){var s=this.startNode();this.parseVarId(s,i);if(this.eat(m.eq)){s.init=this.parseMaybeAssign(t)}else if(i==="const"&&!(this.type===m._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(s.id.type!=="Identifier"&&!(t&&(this.type===m._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{s.init=null}e.declarations.push(this.finishNode(s,"VariableDeclarator"));if(!this.eat(m.comma)){break}}return e};K.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLValPattern(e.id,t==="var"?F:U,false)};var Z=1,J=2,ee=4;K.parseFunction=function(e,t,i,s,r){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!s){if(this.type===m.star&&t&J){this.unexpected()}e.generator=this.eat(m.star)}if(this.options.ecmaVersion>=8){e.async=!!s}if(t&Z){e.id=t&ee&&this.type!==m.name?null:this.parseIdent();if(e.id&&!(t&J)){this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?F:U:q)}}var a=this.yieldPos,n=this.awaitPos,o=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&Z)){e.id=this.type===m.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,i,false,r);this.yieldPos=a;this.awaitPos=n;this.awaitIdentPos=o;return this.finishNode(e,t&Z?"FunctionDeclaration":"FunctionExpression")};K.parseFunctionParams=function(e){this.expect(m.parenL);e.params=this.parseBindingList(m.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};K.parseClass=function(e,t){this.next();var i=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var s=this.enterClassBody();var r=this.startNode();var a=false;r.body=[];this.expect(m.braceL);while(this.type!==m.braceR){var n=this.parseClassElement(e.superClass!==null);if(n){r.body.push(n);if(n.type==="MethodDefinition"&&n.kind==="constructor"){if(a){this.raise(n.start,"Duplicate constructor in the same class")}a=true}else if(n.key&&n.key.type==="PrivateIdentifier"&&isPrivateNameConflicted(s,n)){this.raiseRecoverable(n.key.start,"Identifier '#"+n.key.name+"' has already been declared")}}}this.strict=i;this.next();e.body=this.finishNode(r,"ClassBody");this.exitClassBody();return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};K.parseClassElement=function(e){if(this.eat(m.semi)){return null}var t=this.options.ecmaVersion;var i=this.startNode();var s="";var r=false;var a=false;var n="method";var o=false;if(this.eatContextual("static")){if(t>=13&&this.eat(m.braceL)){this.parseClassStaticBlock(i);return i}if(this.isClassElementNameStart()||this.type===m.star){o=true}else{s="static"}}i.static=o;if(!s&&t>=8&&this.eatContextual("async")){if((this.isClassElementNameStart()||this.type===m.star)&&!this.canInsertSemicolon()){a=true}else{s="async"}}if(!s&&(t>=9||!a)&&this.eat(m.star)){r=true}if(!s&&!a&&!r){var h=this.value;if(this.eatContextual("get")||this.eatContextual("set")){if(this.isClassElementNameStart()){n=h}else{s=h}}}if(s){i.computed=false;i.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc);i.key.name=s;this.finishNode(i.key,"Identifier")}else{this.parseClassElementName(i)}if(t<13||this.type===m.parenL||n!=="method"||r||a){var p=!i.static&&checkKeyName(i,"constructor");var c=p&&e;if(p&&n!=="method"){this.raise(i.key.start,"Constructor can't have get/set modifier")}i.kind=p?"constructor":n;this.parseClassMethod(i,r,a,c)}else{this.parseClassField(i)}return i};K.isClassElementNameStart=function(){return this.type===m.name||this.type===m.privateId||this.type===m.num||this.type===m.string||this.type===m.bracketL||this.type.keyword};K.parseClassElementName=function(e){if(this.type===m.privateId){if(this.value==="constructor"){this.raise(this.start,"Classes can't have an element named '#constructor'")}e.computed=false;e.key=this.parsePrivateIdent()}else{this.parsePropertyName(e)}};K.parseClassMethod=function(e,t,i,s){var r=e.key;if(e.kind==="constructor"){if(t){this.raise(r.start,"Constructor can't be a generator")}if(i){this.raise(r.start,"Constructor can't be an async method")}}else if(e.static&&checkKeyName(e,"prototype")){this.raise(r.start,"Classes may not have a static property named prototype")}var a=e.value=this.parseMethod(t,i,s);if(e.kind==="get"&&a.params.length!==0){this.raiseRecoverable(a.start,"getter should have no params")}if(e.kind==="set"&&a.params.length!==1){this.raiseRecoverable(a.start,"setter should have exactly one param")}if(e.kind==="set"&&a.params[0].type==="RestElement"){this.raiseRecoverable(a.params[0].start,"Setter cannot use rest params")}return this.finishNode(e,"MethodDefinition")};K.parseClassField=function(e){if(checkKeyName(e,"constructor")){this.raise(e.key.start,"Classes can't have a field named 'constructor'")}else if(e.static&&checkKeyName(e,"prototype")){this.raise(e.key.start,"Classes can't have a static field named 'prototype'")}if(this.eat(m.eq)){var t=this.currentThisScope();var i=t.inClassFieldInit;t.inClassFieldInit=true;e.value=this.parseMaybeAssign();t.inClassFieldInit=i}else{e.value=null}this.semicolon();return this.finishNode(e,"PropertyDefinition")};K.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;this.labels=[];this.enterScope(O|R);while(this.type!==m.braceR){var i=this.parseStatement(null);e.body.push(i)}this.next();this.exitScope();this.labels=t;return this.finishNode(e,"StaticBlock")};K.parseClassId=function(e,t){if(this.type===m.name){e.id=this.parseIdent();if(t){this.checkLValSimple(e.id,U,false)}}else{if(t===true){this.unexpected()}e.id=null}};K.parseClassSuper=function(e){e.superClass=this.eat(m._extends)?this.parseExprSubscripts(false):null};K.enterClassBody=function(){var e={declared:Object.create(null),used:[]};this.privateNameStack.push(e);return e.declared};K.exitClassBody=function(){var e=this.privateNameStack.pop();var t=e.declared;var i=e.used;var s=this.privateNameStack.length;var r=s===0?null:this.privateNameStack[s-1];for(var a=0;a=11){if(this.eatContextual("as")){e.exported=this.parseIdent(true);this.checkExport(t,e.exported.name,this.lastTokStart)}else{e.exported=null}}this.expectContextual("from");if(this.type!==m.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(m._default)){this.checkExport(t,"default",this.lastTokStart);var i;if(this.type===m._function||(i=this.isAsyncFunction())){var s=this.startNode();this.next();if(i){this.next()}e.declaration=this.parseFunction(s,Z|ee,false,i)}else if(this.type===m._class){var r=this.startNode();e.declaration=this.parseClass(r,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==m.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var a=0,n=e.specifiers;a=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(i){this.checkPatternErrors(i,true)}for(var s=0,r=e.properties;s=8&&!n&&o.name==="async"&&!this.canInsertSemicolon()&&this.eat(m._function)){this.overrideContext(se.f_expr);return this.parseFunction(this.startNodeAt(r,a),0,false,true,t)}if(s&&!this.canInsertSemicolon()){if(this.eat(m.arrow)){return this.parseArrowExpression(this.startNodeAt(r,a),[o],false,t)}if(this.options.ecmaVersion>=8&&o.name==="async"&&this.type===m.name&&!n&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc)){o=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(m.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(r,a),[o],true,t)}}return o;case m.regexp:var h=this.value;i=this.parseLiteral(h.value);i.regex={pattern:h.pattern,flags:h.flags};return i;case m.num:case m.string:return this.parseLiteral(this.value);case m._null:case m._true:case m._false:i=this.startNode();i.value=this.type===m._null?null:this.type===m._true;i.raw=this.type.keyword;this.next();return this.finishNode(i,"Literal");case m.parenL:var p=this.start,c=this.parseParenAndDistinguishExpression(s,t);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)){e.parenthesizedAssign=p}if(e.parenthesizedBind<0){e.parenthesizedBind=p}}return c;case m.bracketL:i=this.startNode();this.next();i.elements=this.parseExprList(m.bracketR,true,true,e);return this.finishNode(i,"ArrayExpression");case m.braceL:this.overrideContext(se.b_expr);return this.parseObj(false,e);case m._function:i=this.startNode();this.next();return this.parseFunction(i,0);case m._class:return this.parseClass(this.startNode(),false);case m._new:return this.parseNew();case m.backQuote:return this.parseTemplate();case m._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};ae.parseExprImport=function(){var e=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var t=this.parseIdent(true);switch(this.type){case m.parenL:return this.parseDynamicImport(e);case m.dot:e.meta=t;return this.parseImportMeta(e);default:this.unexpected()}};ae.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(m.parenR)){var t=this.start;if(this.eat(m.comma)&&this.eat(m.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="meta"){this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'")}if(t){this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere){this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(e,"MetaProperty")};ae.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(t,"Literal")};ae.parseParenExpression=function(){this.expect(m.parenL);var e=this.parseExpression();this.expect(m.parenR);return e};ae.parseParenAndDistinguishExpression=function(e,t){var i=this.start,s=this.startLoc,r,a=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var n=this.start,o=this.startLoc;var h=[],p=true,c=false;var l=new DestructuringErrors,u=this.yieldPos,f=this.awaitPos,d;this.yieldPos=0;this.awaitPos=0;while(this.type!==m.parenR){p?p=false:this.expect(m.comma);if(a&&this.afterTrailingComma(m.parenR,true)){c=true;break}else if(this.type===m.ellipsis){d=this.start;h.push(this.parseParenItem(this.parseRestBinding()));if(this.type===m.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{h.push(this.parseMaybeAssign(false,l,this.parseParenItem))}}var g=this.lastTokEnd,x=this.lastTokEndLoc;this.expect(m.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(m.arrow)){this.checkPatternErrors(l,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=u;this.awaitPos=f;return this.parseParenArrowList(i,s,h,t)}if(!h.length||c){this.unexpected(this.lastTokStart)}if(d){this.unexpected(d)}this.checkExpressionErrors(l,true);this.yieldPos=u||this.yieldPos;this.awaitPos=f||this.awaitPos;if(h.length>1){r=this.startNodeAt(n,o);r.expressions=h;this.finishNodeAt(r,"SequenceExpression",g,x)}else{r=h[0]}}else{r=this.parseParenExpression()}if(this.options.preserveParens){var v=this.startNodeAt(i,s);v.expression=r;return this.finishNode(v,"ParenthesizedExpression")}else{return r}};ae.parseParenItem=function(e){return e};ae.parseParenArrowList=function(e,t,i,s){return this.parseArrowExpression(this.startNodeAt(e,t),i,s)};var ne=[];ae.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(m.dot)){e.meta=t;var i=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"){this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'")}if(i){this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters")}if(!this.allowNewDotTarget){this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block")}return this.finishNode(e,"MetaProperty")}var s=this.start,r=this.startLoc,a=this.type===m._import;e.callee=this.parseSubscripts(this.parseExprAtom(),s,r,true,false);if(a&&e.callee.type==="ImportExpression"){this.raise(s,"Cannot use new with import()")}if(this.eat(m.parenL)){e.arguments=this.parseExprList(m.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=ne}return this.finishNode(e,"NewExpression")};ae.parseTemplateElement=function(e){var t=e.isTagged;var i=this.startNode();if(this.type===m.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}i.value={raw:this.value,cooked:null}}else{i.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();i.tail=this.type===m.backQuote;return this.finishNode(i,"TemplateElement")};ae.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var i=this.startNode();this.next();i.expressions=[];var s=this.parseTemplateElement({isTagged:t});i.quasis=[s];while(!s.tail){if(this.type===m.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(m.dollarBraceL);i.expressions.push(this.parseExpression());this.expect(m.braceR);i.quasis.push(s=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(i,"TemplateLiteral")};ae.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===m.name||this.type===m.num||this.type===m.string||this.type===m.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===m.star)&&!g.test(this.input.slice(this.lastTokEnd,this.start))};ae.parseObj=function(e,t){var i=this.startNode(),s=true,r={};i.properties=[];this.next();while(!this.eat(m.braceR)){if(!s){this.expect(m.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(m.braceR)){break}}else{s=false}var a=this.parseProperty(e,t);if(!e){this.checkPropClash(a,r,t)}i.properties.push(a)}return this.finishNode(i,e?"ObjectPattern":"ObjectExpression")};ae.parseProperty=function(e,t){var i=this.startNode(),s,r,a,n;if(this.options.ecmaVersion>=9&&this.eat(m.ellipsis)){if(e){i.argument=this.parseIdent(false);if(this.type===m.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(i,"RestElement")}if(this.type===m.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}i.argument=this.parseMaybeAssign(false,t);if(this.type===m.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(i,"SpreadElement")}if(this.options.ecmaVersion>=6){i.method=false;i.shorthand=false;if(e||t){a=this.start;n=this.startLoc}if(!e){s=this.eat(m.star)}}var o=this.containsEsc;this.parsePropertyName(i);if(!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(i)){r=true;s=this.options.ecmaVersion>=9&&this.eat(m.star);this.parsePropertyName(i,t)}else{r=false}this.parsePropertyValue(i,e,s,r,a,n,t,o);return this.finishNode(i,"Property")};ae.parsePropertyValue=function(e,t,i,s,r,a,n,o){if((i||s)&&this.type===m.colon){this.unexpected()}if(this.eat(m.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,n);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===m.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(i,s)}else if(!t&&!o&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==m.comma&&this.type!==m.braceR&&this.type!==m.eq)){if(i||s){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var h=e.kind==="get"?0:1;if(e.value.params.length!==h){var p=e.value.start;if(e.kind==="get"){this.raiseRecoverable(p,"getter should have no params")}else{this.raiseRecoverable(p,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(i||s){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=r}e.kind="init";if(t){e.value=this.parseMaybeDefault(r,a,this.copyNode(e.key))}else if(this.type===m.eq&&n){if(n.shorthandAssign<0){n.shorthandAssign=this.start}e.value=this.parseMaybeDefault(r,a,this.copyNode(e.key))}else{e.value=this.copyNode(e.key)}e.shorthand=true}else{this.unexpected()}};ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(m.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(m.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===m.num||this.type===m.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ae.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};ae.parseMethod=function(e,t,i){var s=this.startNode(),r=this.yieldPos,a=this.awaitPos,n=this.awaitIdentPos;this.initFunction(s);if(this.options.ecmaVersion>=6){s.generator=e}if(this.options.ecmaVersion>=8){s.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,s.generator)|R|(i?D:0));this.expect(m.parenL);s.params=this.parseBindingList(m.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(s,false,true,false);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=n;return this.finishNode(s,"FunctionExpression")};ae.parseArrowExpression=function(e,t,i,s){var r=this.yieldPos,a=this.awaitPos,n=this.awaitIdentPos;this.enterScope(functionFlags(i,false)|V);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!i}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false,s);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=n;return this.finishNode(e,"ArrowFunctionExpression")};ae.parseFunctionBody=function(e,t,i,s){var r=t&&this.type!==m.braceL;var a=this.strict,n=false;if(r){e.body=this.parseMaybeAssign(s);e.expression=true;this.checkParams(e,false)}else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!a||o){n=this.strictDirective(this.end);if(n&&o){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var h=this.labels;this.labels=[];if(n){this.strict=true}this.checkParams(e,!a&&!n&&!t&&!i&&this.isSimpleParamList(e.params));if(this.strict&&e.id){this.checkLValSimple(e.id,G)}e.body=this.parseBlock(false,undefined,n&&!a);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=h}this.exitScope()};ae.isSimpleParamList=function(e){for(var t=0,i=e;t-1||r.functions.indexOf(e)>-1||r.var.indexOf(e)>-1;r.lexical.push(e);if(this.inModule&&r.flags&A){delete this.undefinedExports[e]}}else if(t===H){var a=this.currentScope();a.lexical.push(e)}else if(t===q){var n=this.currentScope();if(this.treatFunctionsAsVar){s=n.lexical.indexOf(e)>-1}else{s=n.lexical.indexOf(e)>-1||n.var.indexOf(e)>-1}n.functions.push(e)}else{for(var o=this.scopeStack.length-1;o>=0;--o){var h=this.scopeStack[o];if(h.lexical.indexOf(e)>-1&&!(h.flags&L&&h.lexical[0]===e)||!this.treatFunctionsAsVarInScope(h)&&h.functions.indexOf(e)>-1){s=true;break}h.var.push(e);if(this.inModule&&h.flags&A){delete this.undefinedExports[e]}if(h.flags&B){break}}}if(s){this.raiseRecoverable(i,"Identifier '"+e+"' has already been declared")}};he.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};he.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};he.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&B){return t}}};he.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&B&&!(t.flags&V)){return t}}};var ce=function Node(e,t,i){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new C(e,i)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var le=j.prototype;le.startNode=function(){return new ce(this,this.start,this.startLoc)};le.startNodeAt=function(e,t){return new ce(this,e,t)};function finishNodeAt(e,t,i,s){e.type=t;e.end=i;if(this.options.locations){e.loc.end=s}if(this.options.ranges){e.range[1]=i}return e}le.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};le.finishNodeAt=function(e,t,i,s){return finishNodeAt.call(this,e,t,i,s)};le.copyNode=function(e){var t=new ce(this,e.start,this.startLoc);for(var i in e){t[i]=e[i]}return t};var ue="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var fe=ue+" Extended_Pictographic";var de=fe;var me=de+" EBase EComp EMod EPres ExtPict";var ge={9:ue,10:fe,11:de,12:me};var xe="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ve="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ye=ve+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ke=ye+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var be=ke+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";var we={9:ve,10:ye,11:ke,12:be};var _e={};function buildUnicodeData(e){var t=_e[e]={binary:wordsRegexp(ge[e]+" "+xe),nonBinary:{General_Category:wordsRegexp(xe),Script:wordsRegexp(we[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);buildUnicodeData(12);var Se=j.prototype;var Ce=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"");this.unicodeProperties=_e[e.options.ecmaVersion>=12?12:e.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};Ce.prototype.reset=function reset(e,t,i){var s=i.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=i;this.switchU=s&&this.parser.options.ecmaVersion>=6;this.switchN=s&&this.parser.options.ecmaVersion>=9};Ce.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};Ce.prototype.at=function at(e,t){if(t===void 0)t=false;var i=this.source;var s=i.length;if(e>=s){return-1}var r=i.charCodeAt(e);if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=s){return r}var a=i.charCodeAt(e+1);return a>=56320&&a<=57343?(r<<10)+a-56613888:r};Ce.prototype.nextIndex=function nextIndex(e,t){if(t===void 0)t=false;var i=this.source;var s=i.length;if(e>=s){return s}var r=i.charCodeAt(e),a;if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=s||(a=i.charCodeAt(e+1))<56320||a>57343){return e+1}return e+2};Ce.prototype.current=function current(e){if(e===void 0)e=false;return this.at(this.pos,e)};Ce.prototype.lookahead=function lookahead(e){if(e===void 0)e=false;return this.at(this.nextIndex(this.pos,e),e)};Ce.prototype.advance=function advance(e){if(e===void 0)e=false;this.pos=this.nextIndex(this.pos,e)};Ce.prototype.eat=function eat(e,t){if(t===void 0)t=false;if(this.current(t)===e){this.advance(t);return true}return false};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Se.validateRegExpFlags=function(e){var t=e.validFlags;var i=e.flags;for(var s=0;s-1){this.raise(e.start,"Duplicate regular expression flag")}}};Se.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};Se.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,i=e.backReferenceNames;t=9){i=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!i;return true}}e.pos=t;return false};Se.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};Se.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};Se.regexp_eatBracedQuantifier=function(e,t){var i=e.pos;if(e.eat(123)){var s=0,r=-1;if(this.regexp_eatDecimalDigits(e)){s=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){r=e.lastIntValue}if(e.eat(125)){if(r!==-1&&r=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};Se.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};Se.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};Se.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}Se.regexp_eatPatternCharacters=function(e){var t=e.pos;var i=0;while((i=e.current())!==-1&&!isSyntaxCharacter(i)){e.advance()}return e.pos!==t};Se.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};Se.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};Se.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};Se.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString(e.lastIntValue)}return true}return false};Se.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var i=this.options.ecmaVersion>=11;var s=e.current(i);e.advance(i);if(s===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)){s=e.lastIntValue}if(isRegExpIdentifierStart(s)){e.lastIntValue=s;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}Se.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var i=this.options.ecmaVersion>=11;var s=e.current(i);e.advance(i);if(s===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)){s=e.lastIntValue}if(isRegExpIdentifierPart(s)){e.lastIntValue=s;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}Se.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};Se.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var i=e.lastIntValue;if(e.switchU){if(i>e.maxBackReference){e.maxBackReference=i}return true}if(i<=e.numCapturingParens){return true}e.pos=t}return false};Se.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};Se.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,false)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};Se.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};Se.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};Se.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};Se.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}Se.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){if(t===void 0)t=false;var i=e.pos;var s=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var r=e.lastIntValue;if(s&&r>=55296&&r<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var n=e.lastIntValue;if(n>=56320&&n<=57343){e.lastIntValue=(r-55296)*1024+(n-56320)+65536;return true}}e.pos=a;e.lastIntValue=r}return true}if(s&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(s){e.raise("Invalid unicode escape")}e.pos=i}return false};function isValidUnicode(e){return e>=0&&e<=1114111}Se.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};Se.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};Se.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}Se.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var i=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var s=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,i,s);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var r=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,r);return true}return false};Se.regexp_validateUnicodePropertyNameAndValue=function(e,t,i){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(i)){e.raise("Invalid property value")}};Se.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};Se.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}Se.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}Se.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};Se.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};Se.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var i=e.lastIntValue;if(e.switchU&&(t===-1||i===-1)){e.raise("Invalid character class")}if(t!==-1&&i!==-1&&t>i){e.raise("Range out of order in character class")}}}};Se.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var i=e.current();if(i===99||isOctalDigit(i)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var s=e.current();if(s!==93){e.lastIntValue=s;e.advance();return true}return false};Se.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};Se.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};Se.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};Se.regexp_eatDecimalDigits=function(e){var t=e.pos;var i=0;e.lastIntValue=0;while(isDecimalDigit(i=e.current())){e.lastIntValue=10*e.lastIntValue+(i-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}Se.regexp_eatHexDigits=function(e){var t=e.pos;var i=0;e.lastIntValue=0;while(isHexDigit(i=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(i);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}Se.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var i=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+i*8+e.lastIntValue}else{e.lastIntValue=t*8+i}}else{e.lastIntValue=t}return true}return false};Se.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}Se.regexp_eatFixedHexDigits=function(e,t){var i=e.pos;e.lastIntValue=0;for(var s=0;s=this.input.length){return this.finishToken(m.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};Ie.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};Ie.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320){return e}var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888};Ie.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,i=this.input.indexOf("*/",this.pos+=2);if(i===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=i+2;if(this.options.locations){x.lastIndex=t;var s;while((s=x.exec(this.input))&&s.index8&&e<14||e>=5760&&v.test(String.fromCharCode(e))){++this.pos}else{break e}}}};Ie.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var i=this.type;this.type=e;this.value=t;this.updateContext(i)};Ie.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(m.ellipsis)}else{++this.pos;return this.finishToken(m.dot)}};Ie.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(m.assign,2)}return this.finishOp(m.slash,1)};Ie.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var i=1;var s=e===42?m.star:m.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++i;s=m.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(m.assign,i+1)}return this.finishOp(s,i)};Ie.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var i=this.input.charCodeAt(this.pos+2);if(i===61){return this.finishOp(m.assign,3)}}return this.finishOp(e===124?m.logicalOR:m.logicalAND,2)}if(t===61){return this.finishOp(m.assign,2)}return this.finishOp(e===124?m.bitwiseOR:m.bitwiseAND,1)};Ie.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(m.assign,2)}return this.finishOp(m.bitwiseXOR,1)};Ie.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||g.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(m.incDec,2)}if(t===61){return this.finishOp(m.assign,2)}return this.finishOp(m.plusMin,1)};Ie.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var i=1;if(t===e){i=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+i)===61){return this.finishOp(m.assign,i+1)}return this.finishOp(m.bitShift,i)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){i=2}return this.finishOp(m.relational,i)};Ie.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(m.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(m.arrow)}return this.finishOp(e===61?m.eq:m.prefix,1)};Ie.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var i=this.input.charCodeAt(this.pos+2);if(i<48||i>57){return this.finishOp(m.questionDot,2)}}if(t===63){if(e>=12){var s=this.input.charCodeAt(this.pos+2);if(s===61){return this.finishOp(m.assign,3)}}return this.finishOp(m.coalesce,2)}}return this.finishOp(m.question,1)};Ie.readToken_numberSign=function(){var e=this.options.ecmaVersion;var t=35;if(e>=13){++this.pos;t=this.fullCharCodeAtPos();if(isIdentifierStart(t,true)||t===92){return this.finishToken(m.privateId,this.readWord1())}}this.raise(this.pos,"Unexpected character '"+codePointToString$1(t)+"'")};Ie.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(m.parenL);case 41:++this.pos;return this.finishToken(m.parenR);case 59:++this.pos;return this.finishToken(m.semi);case 44:++this.pos;return this.finishToken(m.comma);case 91:++this.pos;return this.finishToken(m.bracketL);case 93:++this.pos;return this.finishToken(m.bracketR);case 123:++this.pos;return this.finishToken(m.braceL);case 125:++this.pos;return this.finishToken(m.braceR);case 58:++this.pos;return this.finishToken(m.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(m.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(m.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+codePointToString$1(e)+"'")};Ie.finishOp=function(e,t){var i=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,i)};Ie.readRegexp=function(){var e,t,i=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(i,"Unterminated regular expression")}var s=this.input.charAt(this.pos);if(g.test(s)){this.raise(i,"Unterminated regular expression")}if(!e){if(s==="["){t=true}else if(s==="]"&&t){t=false}else if(s==="/"&&!t){break}e=s==="\\"}else{e=false}++this.pos}var r=this.input.slice(i,this.pos);++this.pos;var a=this.pos;var n=this.readWord1();if(this.containsEsc){this.unexpected(a)}var o=this.regexpState||(this.regexpState=new Ce(this));o.reset(i,r,n);this.validateRegExpFlags(o);this.validateRegExpPattern(o);var h=null;try{h=new RegExp(r,n)}catch(e){}return this.finishToken(m.regexp,{pattern:r,flags:n,value:h})};Ie.readInt=function(e,t,i){var s=this.options.ecmaVersion>=12&&t===undefined;var r=i&&this.input.charCodeAt(this.pos)===48;var a=this.pos,n=0,o=0;for(var h=0,p=t==null?Infinity:t;h=97){l=c-97+10}else if(c>=65){l=c-65+10}else if(c>=48&&c<=57){l=c-48}else{l=Infinity}if(l>=e){break}o=c;n=n*e+l}if(s&&o===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===a||t!=null&&this.pos-a!==t){return null}return n};function stringToNumber(e,t){if(t){return parseInt(e,8)}return parseFloat(e.replace(/_/g,""))}function stringToBigInt(e){if(typeof BigInt!=="function"){return null}return BigInt(e.replace(/_/g,""))}Ie.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var i=this.readInt(e);if(i==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){i=stringToBigInt(this.input.slice(t,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(m.num,i)};Ie.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10,undefined,true)===null){this.raise(t,"Invalid number")}var i=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(i&&this.strict){this.raise(t,"Invalid number")}var s=this.input.charCodeAt(this.pos);if(!i&&!e&&this.options.ecmaVersion>=11&&s===110){var r=stringToBigInt(this.input.slice(t,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(m.num,r)}if(i&&/[89]/.test(this.input.slice(t,this.pos))){i=false}if(s===46&&!i){++this.pos;this.readInt(10);s=this.input.charCodeAt(this.pos)}if((s===69||s===101)&&!i){s=this.input.charCodeAt(++this.pos);if(s===43||s===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var a=stringToNumber(this.input.slice(t,this.pos),i);return this.finishToken(m.num,a)};Ie.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var i=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(i,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Ie.readString=function(e){var t="",i=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var s=this.input.charCodeAt(this.pos);if(s===e){break}if(s===92){t+=this.input.slice(i,this.pos);t+=this.readEscapedChar(false);i=this.pos}else if(s===8232||s===8233){if(this.options.ecmaVersion<10){this.raise(this.start,"Unterminated string constant")}++this.pos;if(this.options.locations){this.curLine++;this.lineStart=this.pos}}else{if(isNewLine(s)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(i,this.pos++);return this.finishToken(m.string,t)};var Ae={};Ie.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===Ae){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};Ie.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw Ae}else{this.raise(e,t)}};Ie.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var i=this.input.charCodeAt(this.pos);if(i===96||i===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===m.template||this.type===m.invalidTemplate)){if(i===36){this.pos+=2;return this.finishToken(m.dollarBraceL)}else{++this.pos;return this.finishToken(m.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(m.template,e)}if(i===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(i)){e+=this.input.slice(t,this.pos);++this.pos;switch(i){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(i);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};Ie.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var s=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var r=parseInt(s,8);if(r>255){s=s.slice(0,-1);r=parseInt(s,8)}this.pos+=s.length-1;t=this.input.charCodeAt(this.pos);if((s!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-s.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(r)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};Ie.readHexChar=function(e){var t=this.pos;var i=this.readInt(16,e);if(i===null){this.invalidStringToken(t,"Bad character escape sequence")}return i};Ie.readWord1=function(){this.containsEsc=false;var e="",t=true,i=this.pos;var s=this.options.ecmaVersion>=6;while(this.pos{var e={108:function(e,t){(function(e,n){true?n(t):0})(this,(function(e){"use strict";var t={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"};var n="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var i={5:n,"5module":n+" export import",6:n+" const class extends export import super"};var r=/^in(stanceof)?$/;var a="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-鿼ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var o="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var s=new RegExp("["+a+"]");var u=new RegExp("["+a+o+"]");a=o=null;var l=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];var c=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];function isInAstralSet(e,t){var n=65536;for(var i=0;ie){return false}n+=t[i+1];if(n>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&s.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,l)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&u.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,l)||isInAstralSet(e,c)}var f=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new f(e,{beforeExpr:true,binop:t})}var p={beforeExpr:true},_={startsExpr:true};var d={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return d[e]=new f(e,t)}var h={num:new f("num",_),regexp:new f("regexp",_),string:new f("string",_),name:new f("name",_),privateId:new f("privateId",_),eof:new f("eof"),bracketL:new f("[",{beforeExpr:true,startsExpr:true}),bracketR:new f("]"),braceL:new f("{",{beforeExpr:true,startsExpr:true}),braceR:new f("}"),parenL:new f("(",{beforeExpr:true,startsExpr:true}),parenR:new f(")"),comma:new f(",",p),semi:new f(";",p),colon:new f(":",p),dot:new f("."),question:new f("?",p),questionDot:new f("?."),arrow:new f("=>",p),template:new f("template"),invalidTemplate:new f("invalidTemplate"),ellipsis:new f("...",p),backQuote:new f("`",_),dollarBraceL:new f("${",{beforeExpr:true,startsExpr:true}),eq:new f("=",{beforeExpr:true,isAssign:true}),assign:new f("_=",{beforeExpr:true,isAssign:true}),incDec:new f("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new f("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new f("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new f("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",p),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",p),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",p),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",_),_if:kw("if"),_return:kw("return",p),_switch:kw("switch"),_throw:kw("throw",p),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",_),_super:kw("super",_),_class:kw("class",_),_extends:kw("extends",p),_export:kw("export"),_import:kw("import",_),_null:kw("null",_),_true:kw("true",_),_false:kw("false",_),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var m=/\r\n?|\n|\u2028|\u2029/;var E=new RegExp(m.source,"g");function isNewLine(e){return e===10||e===13||e===8232||e===8233}var g=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var v=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var b=Object.prototype;var D=b.hasOwnProperty;var y=b.toString;function has(e,t){return D.call(e,t)}var S=Array.isArray||function(e){return y.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var A=function Position(e,t){this.line=e;this.column=t};A.prototype.offset=function offset(e){return new A(this.line,this.column+e)};var k=function SourceLocation(e,t,n){this.start=t;this.end=n;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var n=1,i=0;;){E.lastIndex=i;var r=E.exec(e);if(r&&r.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(S(t.onToken)){var i=t.onToken;t.onToken=function(e){return i.push(e)}}if(S(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(n,i,r,a,o,s){var u={type:n?"Block":"Line",value:i,start:r,end:a};if(e.locations){u.loc=new k(this,o,s)}if(e.ranges){u.range=[r,a]}t.push(u)}}var C=1,R=2,w=4,O=8,F=16,N=32,M=64,I=128,P=256,L=C|R|P;function functionFlags(e,t){return R|(e?w:0)|(t?O:0)}var B=0,V=1,U=2,z=3,K=4,G=5;var H=function Parser(e,n,r){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(i[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var a="";if(e.allowReserved!==true){a=t[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3];if(e.sourceType==="module"){a+=" await"}}this.reservedWords=wordsRegexp(a);var o=(a?a+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(o);this.reservedWordsStrictBind=wordsRegexp(o+" "+t.strictBind);this.input=String(n);this.containsEsc=false;if(r){this.pos=r;this.lineStart=this.input.lastIndexOf("\n",r-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(m).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=h.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.potentialArrowInForAwait=false;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports=Object.create(null);if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(C);this.regexpState=null;this.privateNameStack=[]};var X={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},canAwait:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true},allowNewDotTarget:{configurable:true},inClassStaticBlock:{configurable:true}};H.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};X.inFunction.get=function(){return(this.currentVarScope().flags&R)>0};X.inGenerator.get=function(){return(this.currentVarScope().flags&O)>0&&!this.currentVarScope().inClassFieldInit};X.inAsync.get=function(){return(this.currentVarScope().flags&w)>0&&!this.currentVarScope().inClassFieldInit};X.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&P){return false}if(t.flags&R){return(t.flags&w)>0}}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};X.allowSuper.get=function(){var e=this.currentThisScope();var t=e.flags;var n=e.inClassFieldInit;return(t&M)>0||n||this.options.allowSuperOutsideMethod};X.allowDirectSuper.get=function(){return(this.currentThisScope().flags&I)>0};X.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};X.allowNewDotTarget.get=function(){var e=this.currentThisScope();var t=e.flags;var n=e.inClassFieldInit;return(t&(R|P))>0||n};X.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&P)>0};H.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var n=this;for(var i=0;i=,?^&]/.test(r)||r==="!"&&this.input.charAt(i+1)==="=")}e+=t[0].length;v.lastIndex=e;e+=v.exec(this.input)[0].length;if(this.input[e]===";"){e++}}};W.eat=function(e){if(this.type===e){this.next();return true}else{return false}};W.isContextual=function(e){return this.type===h.name&&this.value===e&&!this.containsEsc};W.eatContextual=function(e){if(!this.isContextual(e)){return false}this.next();return true};W.expectContextual=function(e){if(!this.eatContextual(e)){this.unexpected()}};W.canInsertSemicolon=function(){return this.type===h.eof||this.type===h.braceR||m.test(this.input.slice(this.lastTokEnd,this.start))};W.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};W.semicolon=function(){if(!this.eat(h.semi)&&!this.insertSemicolon()){this.unexpected()}};W.afterTrailingComma=function(e,t){if(this.type===e){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!t){this.next()}return true}};W.expect=function(e){this.eat(e)||this.unexpected()};W.unexpected=function(e){this.raise(e!=null?e:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}W.checkPatternErrors=function(e,t){if(!e){return}if(e.trailingComma>-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var n=t?e.parenthesizedAssign:e.parenthesizedBind;if(n>-1){this.raiseRecoverable(n,"Parenthesized pattern")}};W.checkExpressionErrors=function(e,t){if(!e){return false}var n=e.shorthandAssign;var i=e.doubleProto;if(!t){return n>=0||i>=0}if(n>=0){this.raise(n,"Shorthand property assignments are valid only in destructuring patterns")}if(i>=0){this.raiseRecoverable(i,"Redefinition of __proto__ property")}};W.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&i<56320){return true}if(e){return false}if(i===123){return true}if(isIdentifierStart(i,true)){var a=n+1;while(isIdentifierChar(i=this.input.charCodeAt(a),true)){++a}if(i===92||i>55295&&i<56320){return true}var o=this.input.slice(n,a);if(!r.test(o)){return true}}return false};Y.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async")){return false}v.lastIndex=this.pos;var e=v.exec(this.input);var t=this.pos+e[0].length,n;return!m.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)==="function"&&(t+8===this.input.length||!(isIdentifierChar(n=this.input.charCodeAt(t+8))||n>55295&&n<56320))};Y.parseStatement=function(e,t,n){var i=this.type,r=this.startNode(),a;if(this.isLet(e)){i=h._var;a="let"}switch(i){case h._break:case h._continue:return this.parseBreakContinueStatement(r,i.keyword);case h._debugger:return this.parseDebuggerStatement(r);case h._do:return this.parseDoStatement(r);case h._for:return this.parseForStatement(r);case h._function:if(e&&(this.strict||e!=="if"&&e!=="label")&&this.options.ecmaVersion>=6){this.unexpected()}return this.parseFunctionStatement(r,false,!e);case h._class:if(e){this.unexpected()}return this.parseClass(r,true);case h._if:return this.parseIfStatement(r);case h._return:return this.parseReturnStatement(r);case h._switch:return this.parseSwitchStatement(r);case h._throw:return this.parseThrowStatement(r);case h._try:return this.parseTryStatement(r);case h._const:case h._var:a=a||this.value;if(e&&a!=="var"){this.unexpected()}return this.parseVarStatement(r,a);case h._while:return this.parseWhileStatement(r);case h._with:return this.parseWithStatement(r);case h.braceL:return this.parseBlock(true,r);case h.semi:return this.parseEmptyStatement(r);case h._export:case h._import:if(this.options.ecmaVersion>10&&i===h._import){v.lastIndex=this.pos;var o=v.exec(this.input);var s=this.pos+o[0].length,u=this.input.charCodeAt(s);if(u===40||u===46){return this.parseExpressionStatement(r,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return i===h._import?this.parseImport(r):this.parseExport(r,n);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(r,true,!e)}var l=this.value,c=this.parseExpression();if(i===h.name&&c.type==="Identifier"&&this.eat(h.colon)){return this.parseLabeledStatement(r,l,c,e)}else{return this.parseExpressionStatement(r,c)}}};Y.parseBreakContinueStatement=function(e,t){var n=t==="break";this.next();if(this.eat(h.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==h.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(h.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};Y.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(j);this.enterScope(0);this.expect(h.parenL);if(this.type===h.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var n=this.isLet();if(this.type===h._var||this.type===h._const||n){var i=this.startNode(),r=n?"let":this.value;this.next();this.parseVar(i,true,r);this.finishNode(i,"VariableDeclaration");if((this.type===h._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&i.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===h._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,i)}if(t>-1){this.unexpected(t)}return this.parseFor(e,i)}var a=this.isContextual("let"),o=false;var s=new DestructuringErrors;var u=this.parseExpression(t>-1?"await":true,s);if(this.type===h._in||(o=this.options.ecmaVersion>=6&&this.isContextual("of"))){if(this.options.ecmaVersion>=9){if(this.type===h._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}if(a&&o){this.raise(u.start,"The left-hand side of a for-of loop may not start with 'let'.")}this.toAssignable(u,false,s);this.checkLValPattern(u);return this.parseForIn(e,u)}else{this.checkExpressionErrors(s,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,u)};Y.parseFunctionStatement=function(e,t,n){this.next();return this.parseFunction(e,Q|(n?0:J),false,t)};Y.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(h._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};Y.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(h.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};Y.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(h.braceL);this.labels.push($);this.enterScope(0);var t;for(var n=false;this.type!==h.braceR;){if(this.type===h._case||this.type===h._default){var i=this.type===h._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(i){t.test=this.parseExpression()}else{if(n){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}n=true;t.test=null}this.expect(h.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};Y.parseThrowStatement=function(e){this.next();if(m.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var Z=[];Y.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===h._catch){var t=this.startNode();this.next();if(this.eat(h.parenL)){t.param=this.parseBindingAtom();var n=t.param.type==="Identifier";this.enterScope(n?N:0);this.checkLValPattern(t.param,n?K:U);this.expect(h.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(h._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};Y.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};Y.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(j);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};Y.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};Y.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};Y.parseLabeledStatement=function(e,t,n,i){for(var r=0,a=this.labels;r=0;u--){var l=this.labels[u];if(l.statementStart===e.start){l.statementStart=this.start;l.kind=s}else{break}}this.labels.push({name:t,kind:s,statementStart:this.start});e.body=this.parseStatement(i?i.indexOf("label")===-1?i+"label":i:"label");this.labels.pop();e.label=n;return this.finishNode(e,"LabeledStatement")};Y.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};Y.parseBlock=function(e,t,n){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(h.braceL);if(e){this.enterScope(0)}while(this.type!==h.braceR){var i=this.parseStatement(null);t.body.push(i)}if(n){this.strict=false}this.next();if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};Y.parseFor=function(e,t){e.init=t;this.expect(h.semi);e.test=this.type===h.semi?null:this.parseExpression();this.expect(h.semi);e.update=this.type===h.parenR?null:this.parseExpression();this.expect(h.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};Y.parseForIn=function(e,t){var n=this.type===h._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!n||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(n?"for-in":"for-of")+" loop variable declaration may not have an initializer")}e.left=t;e.right=n?this.parseExpression():this.parseMaybeAssign();this.expect(h.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,n?"ForInStatement":"ForOfStatement")};Y.parseVar=function(e,t,n){e.declarations=[];e.kind=n;for(;;){var i=this.startNode();this.parseVarId(i,n);if(this.eat(h.eq)){i.init=this.parseMaybeAssign(t)}else if(n==="const"&&!(this.type===h._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(i.id.type!=="Identifier"&&!(t&&(this.type===h._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{i.init=null}e.declarations.push(this.finishNode(i,"VariableDeclarator"));if(!this.eat(h.comma)){break}}return e};Y.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLValPattern(e.id,t==="var"?V:U,false)};var Q=1,J=2,ee=4;Y.parseFunction=function(e,t,n,i,r){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!i){if(this.type===h.star&&t&J){this.unexpected()}e.generator=this.eat(h.star)}if(this.options.ecmaVersion>=8){e.async=!!i}if(t&Q){e.id=t&ee&&this.type!==h.name?null:this.parseIdent();if(e.id&&!(t&J)){this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?V:U:z)}}var a=this.yieldPos,o=this.awaitPos,s=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&Q)){e.id=this.type===h.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,n,false,r);this.yieldPos=a;this.awaitPos=o;this.awaitIdentPos=s;return this.finishNode(e,t&Q?"FunctionDeclaration":"FunctionExpression")};Y.parseFunctionParams=function(e){this.expect(h.parenL);e.params=this.parseBindingList(h.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};Y.parseClass=function(e,t){this.next();var n=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var i=this.enterClassBody();var r=this.startNode();var a=false;r.body=[];this.expect(h.braceL);while(this.type!==h.braceR){var o=this.parseClassElement(e.superClass!==null);if(o){r.body.push(o);if(o.type==="MethodDefinition"&&o.kind==="constructor"){if(a){this.raise(o.start,"Duplicate constructor in the same class")}a=true}else if(o.key&&o.key.type==="PrivateIdentifier"&&isPrivateNameConflicted(i,o)){this.raiseRecoverable(o.key.start,"Identifier '#"+o.key.name+"' has already been declared")}}}this.strict=n;this.next();e.body=this.finishNode(r,"ClassBody");this.exitClassBody();return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};Y.parseClassElement=function(e){if(this.eat(h.semi)){return null}var t=this.options.ecmaVersion;var n=this.startNode();var i="";var r=false;var a=false;var o="method";var s=false;if(this.eatContextual("static")){if(t>=13&&this.eat(h.braceL)){this.parseClassStaticBlock(n);return n}if(this.isClassElementNameStart()||this.type===h.star){s=true}else{i="static"}}n.static=s;if(!i&&t>=8&&this.eatContextual("async")){if((this.isClassElementNameStart()||this.type===h.star)&&!this.canInsertSemicolon()){a=true}else{i="async"}}if(!i&&(t>=9||!a)&&this.eat(h.star)){r=true}if(!i&&!a&&!r){var u=this.value;if(this.eatContextual("get")||this.eatContextual("set")){if(this.isClassElementNameStart()){o=u}else{i=u}}}if(i){n.computed=false;n.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc);n.key.name=i;this.finishNode(n.key,"Identifier")}else{this.parseClassElementName(n)}if(t<13||this.type===h.parenL||o!=="method"||r||a){var l=!n.static&&checkKeyName(n,"constructor");var c=l&&e;if(l&&o!=="method"){this.raise(n.key.start,"Constructor can't have get/set modifier")}n.kind=l?"constructor":o;this.parseClassMethod(n,r,a,c)}else{this.parseClassField(n)}return n};Y.isClassElementNameStart=function(){return this.type===h.name||this.type===h.privateId||this.type===h.num||this.type===h.string||this.type===h.bracketL||this.type.keyword};Y.parseClassElementName=function(e){if(this.type===h.privateId){if(this.value==="constructor"){this.raise(this.start,"Classes can't have an element named '#constructor'")}e.computed=false;e.key=this.parsePrivateIdent()}else{this.parsePropertyName(e)}};Y.parseClassMethod=function(e,t,n,i){var r=e.key;if(e.kind==="constructor"){if(t){this.raise(r.start,"Constructor can't be a generator")}if(n){this.raise(r.start,"Constructor can't be an async method")}}else if(e.static&&checkKeyName(e,"prototype")){this.raise(r.start,"Classes may not have a static property named prototype")}var a=e.value=this.parseMethod(t,n,i);if(e.kind==="get"&&a.params.length!==0){this.raiseRecoverable(a.start,"getter should have no params")}if(e.kind==="set"&&a.params.length!==1){this.raiseRecoverable(a.start,"setter should have exactly one param")}if(e.kind==="set"&&a.params[0].type==="RestElement"){this.raiseRecoverable(a.params[0].start,"Setter cannot use rest params")}return this.finishNode(e,"MethodDefinition")};Y.parseClassField=function(e){if(checkKeyName(e,"constructor")){this.raise(e.key.start,"Classes can't have a field named 'constructor'")}else if(e.static&&checkKeyName(e,"prototype")){this.raise(e.key.start,"Classes can't have a static field named 'prototype'")}if(this.eat(h.eq)){var t=this.currentThisScope();var n=t.inClassFieldInit;t.inClassFieldInit=true;e.value=this.parseMaybeAssign();t.inClassFieldInit=n}else{e.value=null}this.semicolon();return this.finishNode(e,"PropertyDefinition")};Y.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;this.labels=[];this.enterScope(P|M);while(this.type!==h.braceR){var n=this.parseStatement(null);e.body.push(n)}this.next();this.exitScope();this.labels=t;return this.finishNode(e,"StaticBlock")};Y.parseClassId=function(e,t){if(this.type===h.name){e.id=this.parseIdent();if(t){this.checkLValSimple(e.id,U,false)}}else{if(t===true){this.unexpected()}e.id=null}};Y.parseClassSuper=function(e){e.superClass=this.eat(h._extends)?this.parseExprSubscripts(false):null};Y.enterClassBody=function(){var e={declared:Object.create(null),used:[]};this.privateNameStack.push(e);return e.declared};Y.exitClassBody=function(){var e=this.privateNameStack.pop();var t=e.declared;var n=e.used;var i=this.privateNameStack.length;var r=i===0?null:this.privateNameStack[i-1];for(var a=0;a=11){if(this.eatContextual("as")){e.exported=this.parseIdent(true);this.checkExport(t,e.exported.name,this.lastTokStart)}else{e.exported=null}}this.expectContextual("from");if(this.type!==h.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(h._default)){this.checkExport(t,"default",this.lastTokStart);var n;if(this.type===h._function||(n=this.isAsyncFunction())){var i=this.startNode();this.next();if(n){this.next()}e.declaration=this.parseFunction(i,Q|ee,false,n)}else if(this.type===h._class){var r=this.startNode();e.declaration=this.parseClass(r,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==h.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var a=0,o=e.specifiers;a=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(n){this.checkPatternErrors(n,true)}for(var i=0,r=e.properties;i=8&&!o&&s.name==="async"&&!this.canInsertSemicolon()&&this.eat(h._function)){this.overrideContext(ie.f_expr);return this.parseFunction(this.startNodeAt(r,a),0,false,true,t)}if(i&&!this.canInsertSemicolon()){if(this.eat(h.arrow)){return this.parseArrowExpression(this.startNodeAt(r,a),[s],false,t)}if(this.options.ecmaVersion>=8&&s.name==="async"&&this.type===h.name&&!o&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc)){s=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(h.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(r,a),[s],true,t)}}return s;case h.regexp:var u=this.value;n=this.parseLiteral(u.value);n.regex={pattern:u.pattern,flags:u.flags};return n;case h.num:case h.string:return this.parseLiteral(this.value);case h._null:case h._true:case h._false:n=this.startNode();n.value=this.type===h._null?null:this.type===h._true;n.raw=this.type.keyword;this.next();return this.finishNode(n,"Literal");case h.parenL:var l=this.start,c=this.parseParenAndDistinguishExpression(i,t);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)){e.parenthesizedAssign=l}if(e.parenthesizedBind<0){e.parenthesizedBind=l}}return c;case h.bracketL:n=this.startNode();this.next();n.elements=this.parseExprList(h.bracketR,true,true,e);return this.finishNode(n,"ArrayExpression");case h.braceL:this.overrideContext(ie.b_expr);return this.parseObj(false,e);case h._function:n=this.startNode();this.next();return this.parseFunction(n,0);case h._class:return this.parseClass(this.startNode(),false);case h._new:return this.parseNew();case h.backQuote:return this.parseTemplate();case h._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};ae.parseExprImport=function(){var e=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var t=this.parseIdent(true);switch(this.type){case h.parenL:return this.parseDynamicImport(e);case h.dot:e.meta=t;return this.parseImportMeta(e);default:this.unexpected()}};ae.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(h.parenR)){var t=this.start;if(this.eat(h.comma)&&this.eat(h.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="meta"){this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'")}if(t){this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere){this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(e,"MetaProperty")};ae.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(t,"Literal")};ae.parseParenExpression=function(){this.expect(h.parenL);var e=this.parseExpression();this.expect(h.parenR);return e};ae.parseParenAndDistinguishExpression=function(e,t){var n=this.start,i=this.startLoc,r,a=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var o=this.start,s=this.startLoc;var u=[],l=true,c=false;var f=new DestructuringErrors,p=this.yieldPos,_=this.awaitPos,d;this.yieldPos=0;this.awaitPos=0;while(this.type!==h.parenR){l?l=false:this.expect(h.comma);if(a&&this.afterTrailingComma(h.parenR,true)){c=true;break}else if(this.type===h.ellipsis){d=this.start;u.push(this.parseParenItem(this.parseRestBinding()));if(this.type===h.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{u.push(this.parseMaybeAssign(false,f,this.parseParenItem))}}var m=this.lastTokEnd,E=this.lastTokEndLoc;this.expect(h.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(h.arrow)){this.checkPatternErrors(f,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=p;this.awaitPos=_;return this.parseParenArrowList(n,i,u,t)}if(!u.length||c){this.unexpected(this.lastTokStart)}if(d){this.unexpected(d)}this.checkExpressionErrors(f,true);this.yieldPos=p||this.yieldPos;this.awaitPos=_||this.awaitPos;if(u.length>1){r=this.startNodeAt(o,s);r.expressions=u;this.finishNodeAt(r,"SequenceExpression",m,E)}else{r=u[0]}}else{r=this.parseParenExpression()}if(this.options.preserveParens){var g=this.startNodeAt(n,i);g.expression=r;return this.finishNode(g,"ParenthesizedExpression")}else{return r}};ae.parseParenItem=function(e){return e};ae.parseParenArrowList=function(e,t,n,i){return this.parseArrowExpression(this.startNodeAt(e,t),n,i)};var oe=[];ae.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(h.dot)){e.meta=t;var n=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"){this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'")}if(n){this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters")}if(!this.allowNewDotTarget){this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block")}return this.finishNode(e,"MetaProperty")}var i=this.start,r=this.startLoc,a=this.type===h._import;e.callee=this.parseSubscripts(this.parseExprAtom(),i,r,true,false);if(a&&e.callee.type==="ImportExpression"){this.raise(i,"Cannot use new with import()")}if(this.eat(h.parenL)){e.arguments=this.parseExprList(h.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=oe}return this.finishNode(e,"NewExpression")};ae.parseTemplateElement=function(e){var t=e.isTagged;var n=this.startNode();if(this.type===h.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}n.value={raw:this.value,cooked:null}}else{n.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();n.tail=this.type===h.backQuote;return this.finishNode(n,"TemplateElement")};ae.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var n=this.startNode();this.next();n.expressions=[];var i=this.parseTemplateElement({isTagged:t});n.quasis=[i];while(!i.tail){if(this.type===h.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(h.dollarBraceL);n.expressions.push(this.parseExpression());this.expect(h.braceR);n.quasis.push(i=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(n,"TemplateLiteral")};ae.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===h.name||this.type===h.num||this.type===h.string||this.type===h.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===h.star)&&!m.test(this.input.slice(this.lastTokEnd,this.start))};ae.parseObj=function(e,t){var n=this.startNode(),i=true,r={};n.properties=[];this.next();while(!this.eat(h.braceR)){if(!i){this.expect(h.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(h.braceR)){break}}else{i=false}var a=this.parseProperty(e,t);if(!e){this.checkPropClash(a,r,t)}n.properties.push(a)}return this.finishNode(n,e?"ObjectPattern":"ObjectExpression")};ae.parseProperty=function(e,t){var n=this.startNode(),i,r,a,o;if(this.options.ecmaVersion>=9&&this.eat(h.ellipsis)){if(e){n.argument=this.parseIdent(false);if(this.type===h.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(n,"RestElement")}if(this.type===h.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}n.argument=this.parseMaybeAssign(false,t);if(this.type===h.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(n,"SpreadElement")}if(this.options.ecmaVersion>=6){n.method=false;n.shorthand=false;if(e||t){a=this.start;o=this.startLoc}if(!e){i=this.eat(h.star)}}var s=this.containsEsc;this.parsePropertyName(n);if(!e&&!s&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(n)){r=true;i=this.options.ecmaVersion>=9&&this.eat(h.star);this.parsePropertyName(n,t)}else{r=false}this.parsePropertyValue(n,e,i,r,a,o,t,s);return this.finishNode(n,"Property")};ae.parsePropertyValue=function(e,t,n,i,r,a,o,s){if((n||i)&&this.type===h.colon){this.unexpected()}if(this.eat(h.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,o);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===h.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(n,i)}else if(!t&&!s&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==h.comma&&this.type!==h.braceR&&this.type!==h.eq)){if(n||i){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var u=e.kind==="get"?0:1;if(e.value.params.length!==u){var l=e.value.start;if(e.kind==="get"){this.raiseRecoverable(l,"getter should have no params")}else{this.raiseRecoverable(l,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(n||i){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=r}e.kind="init";if(t){e.value=this.parseMaybeDefault(r,a,this.copyNode(e.key))}else if(this.type===h.eq&&o){if(o.shorthandAssign<0){o.shorthandAssign=this.start}e.value=this.parseMaybeDefault(r,a,this.copyNode(e.key))}else{e.value=this.copyNode(e.key)}e.shorthand=true}else{this.unexpected()}};ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(h.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(h.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===h.num||this.type===h.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ae.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};ae.parseMethod=function(e,t,n){var i=this.startNode(),r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;this.initFunction(i);if(this.options.ecmaVersion>=6){i.generator=e}if(this.options.ecmaVersion>=8){i.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,i.generator)|M|(n?I:0));this.expect(h.parenL);i.params=this.parseBindingList(h.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(i,false,true,false);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=o;return this.finishNode(i,"FunctionExpression")};ae.parseArrowExpression=function(e,t,n,i){var r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;this.enterScope(functionFlags(n,false)|F);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!n}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false,i);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=o;return this.finishNode(e,"ArrowFunctionExpression")};ae.parseFunctionBody=function(e,t,n,i){var r=t&&this.type!==h.braceL;var a=this.strict,o=false;if(r){e.body=this.parseMaybeAssign(i);e.expression=true;this.checkParams(e,false)}else{var s=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!a||s){o=this.strictDirective(this.end);if(o&&s){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var u=this.labels;this.labels=[];if(o){this.strict=true}this.checkParams(e,!a&&!o&&!t&&!n&&this.isSimpleParamList(e.params));if(this.strict&&e.id){this.checkLValSimple(e.id,G)}e.body=this.parseBlock(false,undefined,o&&!a);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=u}this.exitScope()};ae.isSimpleParamList=function(e){for(var t=0,n=e;t-1||r.functions.indexOf(e)>-1||r.var.indexOf(e)>-1;r.lexical.push(e);if(this.inModule&&r.flags&C){delete this.undefinedExports[e]}}else if(t===K){var a=this.currentScope();a.lexical.push(e)}else if(t===z){var o=this.currentScope();if(this.treatFunctionsAsVar){i=o.lexical.indexOf(e)>-1}else{i=o.lexical.indexOf(e)>-1||o.var.indexOf(e)>-1}o.functions.push(e)}else{for(var s=this.scopeStack.length-1;s>=0;--s){var u=this.scopeStack[s];if(u.lexical.indexOf(e)>-1&&!(u.flags&N&&u.lexical[0]===e)||!this.treatFunctionsAsVarInScope(u)&&u.functions.indexOf(e)>-1){i=true;break}u.var.push(e);if(this.inModule&&u.flags&C){delete this.undefinedExports[e]}if(u.flags&L){break}}}if(i){this.raiseRecoverable(n,"Identifier '"+e+"' has already been declared")}};ue.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};ue.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};ue.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&L){return t}}};ue.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&L&&!(t.flags&F)){return t}}};var ce=function Node(e,t,n){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new k(e,n)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var fe=H.prototype;fe.startNode=function(){return new ce(this,this.start,this.startLoc)};fe.startNodeAt=function(e,t){return new ce(this,e,t)};function finishNodeAt(e,t,n,i){e.type=t;e.end=n;if(this.options.locations){e.loc.end=i}if(this.options.ranges){e.range[1]=n}return e}fe.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};fe.finishNodeAt=function(e,t,n,i){return finishNodeAt.call(this,e,t,n,i)};fe.copyNode=function(e){var t=new ce(this,e.start,this.startLoc);for(var n in e){t[n]=e[n]}return t};var pe="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var _e=pe+" Extended_Pictographic";var de=_e;var he=de+" EBase EComp EMod EPres ExtPict";var me={9:pe,10:_e,11:de,12:he};var Ee="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ge="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ve=ge+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var be=ve+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var De=be+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";var ye={9:ge,10:ve,11:be,12:De};var Se={};function buildUnicodeData(e){var t=Se[e]={binary:wordsRegexp(me[e]+" "+Ee),nonBinary:{General_Category:wordsRegexp(Ee),Script:wordsRegexp(ye[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);buildUnicodeData(12);var Ae=H.prototype;var ke=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"");this.unicodeProperties=Se[e.options.ecmaVersion>=12?12:e.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};ke.prototype.reset=function reset(e,t,n){var i=n.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=n;this.switchU=i&&this.parser.options.ecmaVersion>=6;this.switchN=i&&this.parser.options.ecmaVersion>=9};ke.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};ke.prototype.at=function at(e,t){if(t===void 0)t=false;var n=this.source;var i=n.length;if(e>=i){return-1}var r=n.charCodeAt(e);if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=i){return r}var a=n.charCodeAt(e+1);return a>=56320&&a<=57343?(r<<10)+a-56613888:r};ke.prototype.nextIndex=function nextIndex(e,t){if(t===void 0)t=false;var n=this.source;var i=n.length;if(e>=i){return i}var r=n.charCodeAt(e),a;if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=i||(a=n.charCodeAt(e+1))<56320||a>57343){return e+1}return e+2};ke.prototype.current=function current(e){if(e===void 0)e=false;return this.at(this.pos,e)};ke.prototype.lookahead=function lookahead(e){if(e===void 0)e=false;return this.at(this.nextIndex(this.pos,e),e)};ke.prototype.advance=function advance(e){if(e===void 0)e=false;this.pos=this.nextIndex(this.pos,e)};ke.prototype.eat=function eat(e,t){if(t===void 0)t=false;if(this.current(t)===e){this.advance(t);return true}return false};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Ae.validateRegExpFlags=function(e){var t=e.validFlags;var n=e.flags;for(var i=0;i-1){this.raise(e.start,"Duplicate regular expression flag")}}};Ae.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};Ae.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,n=e.backReferenceNames;t=9){n=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!n;return true}}e.pos=t;return false};Ae.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};Ae.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};Ae.regexp_eatBracedQuantifier=function(e,t){var n=e.pos;if(e.eat(123)){var i=0,r=-1;if(this.regexp_eatDecimalDigits(e)){i=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){r=e.lastIntValue}if(e.eat(125)){if(r!==-1&&r=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};Ae.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};Ae.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};Ae.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}Ae.regexp_eatPatternCharacters=function(e){var t=e.pos;var n=0;while((n=e.current())!==-1&&!isSyntaxCharacter(n)){e.advance()}return e.pos!==t};Ae.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};Ae.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};Ae.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};Ae.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString(e.lastIntValue)}return true}return false};Ae.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var n=this.options.ecmaVersion>=11;var i=e.current(n);e.advance(n);if(i===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)){i=e.lastIntValue}if(isRegExpIdentifierStart(i)){e.lastIntValue=i;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}Ae.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var n=this.options.ecmaVersion>=11;var i=e.current(n);e.advance(n);if(i===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)){i=e.lastIntValue}if(isRegExpIdentifierPart(i)){e.lastIntValue=i;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}Ae.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};Ae.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var n=e.lastIntValue;if(e.switchU){if(n>e.maxBackReference){e.maxBackReference=n}return true}if(n<=e.numCapturingParens){return true}e.pos=t}return false};Ae.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};Ae.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,false)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};Ae.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};Ae.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};Ae.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};Ae.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}Ae.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){if(t===void 0)t=false;var n=e.pos;var i=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var r=e.lastIntValue;if(i&&r>=55296&&r<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343){e.lastIntValue=(r-55296)*1024+(o-56320)+65536;return true}}e.pos=a;e.lastIntValue=r}return true}if(i&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(i){e.raise("Invalid unicode escape")}e.pos=n}return false};function isValidUnicode(e){return e>=0&&e<=1114111}Ae.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};Ae.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};Ae.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}Ae.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var n=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var i=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,n,i);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var r=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,r);return true}return false};Ae.regexp_validateUnicodePropertyNameAndValue=function(e,t,n){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(n)){e.raise("Invalid property value")}};Ae.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};Ae.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}Ae.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}Ae.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};Ae.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};Ae.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var n=e.lastIntValue;if(e.switchU&&(t===-1||n===-1)){e.raise("Invalid character class")}if(t!==-1&&n!==-1&&t>n){e.raise("Range out of order in character class")}}}};Ae.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var n=e.current();if(n===99||isOctalDigit(n)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var i=e.current();if(i!==93){e.lastIntValue=i;e.advance();return true}return false};Ae.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};Ae.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};Ae.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};Ae.regexp_eatDecimalDigits=function(e){var t=e.pos;var n=0;e.lastIntValue=0;while(isDecimalDigit(n=e.current())){e.lastIntValue=10*e.lastIntValue+(n-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}Ae.regexp_eatHexDigits=function(e){var t=e.pos;var n=0;e.lastIntValue=0;while(isHexDigit(n=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(n);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}Ae.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var n=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+n*8+e.lastIntValue}else{e.lastIntValue=t*8+n}}else{e.lastIntValue=t}return true}return false};Ae.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}Ae.regexp_eatFixedHexDigits=function(e,t){var n=e.pos;e.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(h.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};xe.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};xe.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320){return e}var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888};xe.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,n=this.input.indexOf("*/",this.pos+=2);if(n===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=n+2;if(this.options.locations){E.lastIndex=t;var i;while((i=E.exec(this.input))&&i.index8&&e<14||e>=5760&&g.test(String.fromCharCode(e))){++this.pos}else{break e}}}};xe.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var n=this.type;this.type=e;this.value=t;this.updateContext(n)};xe.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(h.ellipsis)}else{++this.pos;return this.finishToken(h.dot)}};xe.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(h.assign,2)}return this.finishOp(h.slash,1)};xe.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var n=1;var i=e===42?h.star:h.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++n;i=h.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(h.assign,n+1)}return this.finishOp(i,n)};xe.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var n=this.input.charCodeAt(this.pos+2);if(n===61){return this.finishOp(h.assign,3)}}return this.finishOp(e===124?h.logicalOR:h.logicalAND,2)}if(t===61){return this.finishOp(h.assign,2)}return this.finishOp(e===124?h.bitwiseOR:h.bitwiseAND,1)};xe.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(h.assign,2)}return this.finishOp(h.bitwiseXOR,1)};xe.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||m.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(h.incDec,2)}if(t===61){return this.finishOp(h.assign,2)}return this.finishOp(h.plusMin,1)};xe.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var n=1;if(t===e){n=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+n)===61){return this.finishOp(h.assign,n+1)}return this.finishOp(h.bitShift,n)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){n=2}return this.finishOp(h.relational,n)};xe.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(h.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(h.arrow)}return this.finishOp(e===61?h.eq:h.prefix,1)};xe.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var n=this.input.charCodeAt(this.pos+2);if(n<48||n>57){return this.finishOp(h.questionDot,2)}}if(t===63){if(e>=12){var i=this.input.charCodeAt(this.pos+2);if(i===61){return this.finishOp(h.assign,3)}}return this.finishOp(h.coalesce,2)}}return this.finishOp(h.question,1)};xe.readToken_numberSign=function(){var e=this.options.ecmaVersion;var t=35;if(e>=13){++this.pos;t=this.fullCharCodeAtPos();if(isIdentifierStart(t,true)||t===92){return this.finishToken(h.privateId,this.readWord1())}}this.raise(this.pos,"Unexpected character '"+codePointToString$1(t)+"'")};xe.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(h.parenL);case 41:++this.pos;return this.finishToken(h.parenR);case 59:++this.pos;return this.finishToken(h.semi);case 44:++this.pos;return this.finishToken(h.comma);case 91:++this.pos;return this.finishToken(h.bracketL);case 93:++this.pos;return this.finishToken(h.bracketR);case 123:++this.pos;return this.finishToken(h.braceL);case 125:++this.pos;return this.finishToken(h.braceR);case 58:++this.pos;return this.finishToken(h.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(h.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(h.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+codePointToString$1(e)+"'")};xe.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,n)};xe.readRegexp=function(){var e,t,n=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(n,"Unterminated regular expression")}var i=this.input.charAt(this.pos);if(m.test(i)){this.raise(n,"Unterminated regular expression")}if(!e){if(i==="["){t=true}else if(i==="]"&&t){t=false}else if(i==="/"&&!t){break}e=i==="\\"}else{e=false}++this.pos}var r=this.input.slice(n,this.pos);++this.pos;var a=this.pos;var o=this.readWord1();if(this.containsEsc){this.unexpected(a)}var s=this.regexpState||(this.regexpState=new ke(this));s.reset(n,r,o);this.validateRegExpFlags(s);this.validateRegExpPattern(s);var u=null;try{u=new RegExp(r,o)}catch(e){}return this.finishToken(h.regexp,{pattern:r,flags:o,value:u})};xe.readInt=function(e,t,n){var i=this.options.ecmaVersion>=12&&t===undefined;var r=n&&this.input.charCodeAt(this.pos)===48;var a=this.pos,o=0,s=0;for(var u=0,l=t==null?Infinity:t;u=97){f=c-97+10}else if(c>=65){f=c-65+10}else if(c>=48&&c<=57){f=c-48}else{f=Infinity}if(f>=e){break}s=c;o=o*e+f}if(i&&s===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===a||t!=null&&this.pos-a!==t){return null}return o};function stringToNumber(e,t){if(t){return parseInt(e,8)}return parseFloat(e.replace(/_/g,""))}function stringToBigInt(e){if(typeof BigInt!=="function"){return null}return BigInt(e.replace(/_/g,""))}xe.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var n=this.readInt(e);if(n==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){n=stringToBigInt(this.input.slice(t,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(h.num,n)};xe.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10,undefined,true)===null){this.raise(t,"Invalid number")}var n=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(n&&this.strict){this.raise(t,"Invalid number")}var i=this.input.charCodeAt(this.pos);if(!n&&!e&&this.options.ecmaVersion>=11&&i===110){var r=stringToBigInt(this.input.slice(t,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(h.num,r)}if(n&&/[89]/.test(this.input.slice(t,this.pos))){n=false}if(i===46&&!n){++this.pos;this.readInt(10);i=this.input.charCodeAt(this.pos)}if((i===69||i===101)&&!n){i=this.input.charCodeAt(++this.pos);if(i===43||i===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var a=stringToNumber(this.input.slice(t,this.pos),n);return this.finishToken(h.num,a)};xe.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var n=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(n,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}xe.readString=function(e){var t="",n=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var i=this.input.charCodeAt(this.pos);if(i===e){break}if(i===92){t+=this.input.slice(n,this.pos);t+=this.readEscapedChar(false);n=this.pos}else if(i===8232||i===8233){if(this.options.ecmaVersion<10){this.raise(this.start,"Unterminated string constant")}++this.pos;if(this.options.locations){this.curLine++;this.lineStart=this.pos}}else{if(isNewLine(i)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(n,this.pos++);return this.finishToken(h.string,t)};var Ce={};xe.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===Ce){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};xe.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw Ce}else{this.raise(e,t)}};xe.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var n=this.input.charCodeAt(this.pos);if(n===96||n===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===h.template||this.type===h.invalidTemplate)){if(n===36){this.pos+=2;return this.finishToken(h.dollarBraceL)}else{++this.pos;return this.finishToken(h.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(h.template,e)}if(n===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(n)){e+=this.input.slice(t,this.pos);++this.pos;switch(n){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(n);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};xe.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var i=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var r=parseInt(i,8);if(r>255){i=i.slice(0,-1);r=parseInt(i,8)}this.pos+=i.length-1;t=this.input.charCodeAt(this.pos);if((i!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-i.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(r)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};xe.readHexChar=function(e){var t=this.pos;var n=this.readInt(16,e);if(n===null){this.invalidStringToken(t,"Bad character escape sequence")}return n};xe.readWord1=function(){this.containsEsc=false;var e="",t=true,n=this.pos;var i=this.options.ecmaVersion>=6;while(this.pos{"use strict";e.exports=require("next/dist/compiled/source-map")},405:function(e,t,n){(function(e,i){true?i(t,n(749)):0})(this,(function(e,t){"use strict";function _interopDefaultLegacy(e){return e&&typeof e==="object"&&"default"in e?e:{default:e}}var i=_interopDefaultLegacy(t);function characters(e){return e.split("")}function member(e,t){return t.includes(e)}class DefaultsError extends Error{constructor(e,t){super();this.name="DefaultsError";this.message=e;this.defs=t}}function defaults(e,t,n){if(e===true){e={}}else if(e!=null&&typeof e==="object"){e={...e}}const i=e||{};if(n)for(const e in i)if(HOP(i,e)&&!HOP(t,e)){throw new DefaultsError("`"+e+"` is not a supported option",t)}for(const n in t)if(HOP(t,n)){if(!e||!HOP(e,n)){i[n]=t[n]}else if(n==="ecma"){let t=e[n]|0;if(t>5&&t<2015)t+=2009;i[n]=t}else{i[n]=e&&HOP(e,n)?e[n]:t[n]}}return i}function noop(){}function return_false(){return false}function return_true(){return true}function return_this(){return this}function return_null(){return null}var r=function(){function MAP(t,n,i){var r=[],a=[],o;function doit(){var s=n(t[o],o);var u=s instanceof Last;if(u)s=s.v;if(s instanceof AtTop){s=s.v;if(s instanceof Splice){a.push.apply(a,i?s.v.slice().reverse():s.v)}else{a.push(s)}}else if(s!==e){if(s instanceof Splice){r.push.apply(r,i?s.v.slice().reverse():s.v)}else{r.push(s)}}return u}if(Array.isArray(t)){if(i){for(o=t.length;--o>=0;)if(doit())break;r.reverse();a.reverse()}else{for(o=0;o=0;){if(e[n]===t)e.splice(n,1)}}function mergeSort(e,t){if(e.length<2)return e.slice();function merge(e,n){var i=[],r=0,a=0,o=0;while(r{n+=e}))}return n}function has_annotation(e,t){return e._annotations&t}function set_annotation(e,t){e._annotations|=t}var s="";var u=true;var l="break case catch class const continue debugger default delete do else export extends finally for function if in instanceof let new return switch throw try typeof var void while with";var c="false null true";var f="enum implements import interface package private protected public static super this "+c+" "+l;var p="return new delete throw else case yield await";l=makePredicate(l);f=makePredicate(f);p=makePredicate(p);c=makePredicate(c);var _=makePredicate(characters("+-*&%=<>!?|~^"));var d=/[0-9a-f]/i;var h=/^0x[0-9a-f]+$/i;var m=/^0[0-7]+$/;var E=/^0o[0-7]+$/i;var g=/^0b[01]+$/i;var v=/^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;var b=/^(0[xob])?[0-9a-f]+n$/i;var D=makePredicate(["in","instanceof","typeof","new","void","delete","++","--","+","-","!","~","&","|","^","*","**","/","%",">>","<<",">>>","<",">","<=",">=","==","===","!=","!==","?","=","+=","-=","||=","&&=","??=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&=","&&","??","||"]);var y=makePredicate(characters("  \n\r\t\f\v​           \u2028\u2029   \ufeff"));var S=makePredicate(characters("\n\r\u2028\u2029"));var A=makePredicate(characters(";]),:"));var k=makePredicate(characters("[{(,;:"));var T=makePredicate(characters("[]{}(),;:"));var x={ID_Start:/[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/(?:[$0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF])+/};function get_full_char(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){if(is_surrogate_pair_tail(e.charCodeAt(t+1))){return e.charAt(t)+e.charAt(t+1)}}else if(is_surrogate_pair_tail(e.charCodeAt(t))){if(is_surrogate_pair_head(e.charCodeAt(t-1))){return e.charAt(t-1)+e.charAt(t)}}return e.charAt(t)}function get_full_char_code(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){return 65536+(e.charCodeAt(t)-55296<<10)+e.charCodeAt(t+1)-56320}return e.charCodeAt(t)}function get_full_char_length(e){var t=0;for(var n=0;n65535){e-=65536;return String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)}return String.fromCharCode(e)}function is_surrogate_pair_head(e){return e>=55296&&e<=56319}function is_surrogate_pair_tail(e){return e>=56320&&e<=57343}function is_digit(e){return e>=48&&e<=57}function is_identifier_start(e){return x.ID_Start.test(e)}function is_identifier_char(e){return x.ID_Continue.test(e)}const C=/^[a-z_$][a-z0-9_$]*$/i;function is_basic_identifier_string(e){return C.test(e)}function is_identifier_string(e,t){if(C.test(e)){return true}if(!t&&/[\ud800-\udfff]/.test(e)){return false}var n=x.ID_Start.exec(e);if(!n||n.index!==0){return false}e=e.slice(n[0].length);if(!e){return true}n=x.ID_Continue.exec(e);return!!n&&n[0].length===e.length}function parse_js_number(e,t=true){if(!t&&e.includes("e")){return NaN}if(h.test(e)){return parseInt(e.substr(2),16)}else if(m.test(e)){return parseInt(e.substr(1),8)}else if(E.test(e)){return parseInt(e.substr(2),8)}else if(g.test(e)){return parseInt(e.substr(2),2)}else if(v.test(e)){return parseFloat(e)}else{var n=parseFloat(e);if(n==e)return n}}class JS_Parse_Error extends Error{constructor(e,t,n,i,r){super();this.name="SyntaxError";this.message=e;this.filename=t;this.line=n;this.col=i;this.pos=r}}function js_error(e,t,n,i,r){throw new JS_Parse_Error(e,t,n,i,r)}function is_token(e,t,n){return e.type==t&&(n==null||e.value==n)}var R={};function tokenizer(e,t,n,i){var r={text:e,filename:t,pos:0,tokpos:0,line:1,tokline:0,col:0,tokcol:0,newline_before:false,regex_allowed:false,brace_counter:0,template_braces:[],comments_before:[],directives:{},directive_stack:[]};function peek(){return get_full_char(r.text,r.pos)}function is_option_chain_op(){const e=r.text.charCodeAt(r.pos+1)===46;if(!e)return false;const t=r.text.charCodeAt(r.pos+2);return t<48||t>57}function next(e,t){var n=get_full_char(r.text,r.pos++);if(e&&!n)throw R;if(S.has(n)){r.newline_before=r.newline_before||!t;++r.line;r.col=0;if(n=="\r"&&peek()=="\n"){++r.pos;n="\n"}}else{if(n.length>1){++r.pos;++r.col}++r.col}return n}function forward(e){while(e--)next()}function looking_at(e){return r.text.substr(r.pos,e.length)==e}function find_eol(){var e=r.text;for(var t=r.pos,n=r.text.length;t="0"&&e<="7"}function read_escaped_char(e,t,n){var i=next(true,e);switch(i.charCodeAt(0)){case 110:return"\n";case 114:return"\r";case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 120:return String.fromCharCode(hex_bytes(2,t));case 117:if(peek()=="{"){next(true);if(peek()==="}")parse_error("Expecting hex-character between {}");while(peek()=="0")next(true);var a,o=find("}",true)-r.pos;if(o>6||(a=hex_bytes(o,t))>1114111){parse_error("Unicode reference out of bounds")}next(true);return from_char_code(a)}return String.fromCharCode(hex_bytes(4,t));case 10:return"";case 13:if(peek()=="\n"){next(true,e);return""}}if(is_octal(i)){if(n&&t){const e=i==="0"&&!is_octal(peek());if(!e){parse_error("Octal escape sequences are not allowed in template strings")}}return read_octal_escape_sequence(i,t)}return i}function read_octal_escape_sequence(e,t){var n=peek();if(n>="0"&&n<="7"){e+=next(true);if(e[0]<="3"&&(n=peek())>="0"&&n<="7")e+=next(true)}if(e==="0")return"\0";if(e.length>0&&next_token.has_directive("use strict")&&t)parse_error("Legacy octal escape sequences are not allowed in strict mode");return String.fromCharCode(parseInt(e,8))}function hex_bytes(e,t){var n=0;for(;e>0;--e){if(!t&&isNaN(parseInt(peek(),16))){return parseInt(n,16)||""}var i=next(true);if(isNaN(parseInt(i,16)))parse_error("Invalid hex-character pattern in string");n+=i}return parseInt(n,16)}var E=with_eof_error("Unterminated string constant",(function(){const e=r.pos;var t=next(),n=[];for(;;){var i=next(true,true);if(i=="\\")i=read_escaped_char(true,true);else if(i=="\r"||i=="\n")parse_error("Unterminated string constant");else if(i==t)break;n.push(i)}var a=token("string",n.join(""));s=r.text.slice(e,r.pos);a.quote=t;return a}));var g=with_eof_error("Unterminated template",(function(e){if(e){r.template_braces.push(r.brace_counter)}var t="",n="",i,a;next(true,true);while((i=next(true,true))!="`"){if(i=="\r"){if(peek()=="\n")++r.pos;i="\n"}else if(i=="$"&&peek()=="{"){next(true,true);r.brace_counter++;a=token(e?"template_head":"template_substitution",t);s=n;u=false;return a}n+=i;if(i=="\\"){var l=r.pos;var c=o&&(o.type==="name"||o.type==="punc"&&(o.value===")"||o.value==="]"));i=read_escaped_char(true,!c,true);n+=r.text.substr(l,r.pos-l)}t+=i}r.template_braces.pop();a=token(e?"template_head":"template_substitution",t);s=n;u=true;return a}));function skip_line_comment(e){var t=r.regex_allowed;var n=find_eol(),i;if(n==-1){i=r.text.substr(r.pos);r.pos=r.text.length}else{i=r.text.substring(r.pos,n);r.pos=n}r.col=r.tokcol+(r.pos-r.tokpos);r.comments_before.push(token(e,i,true));r.regex_allowed=t;return next_token}var v=with_eof_error("Unterminated multiline comment",(function(){var e=r.regex_allowed;var t=find("*/",true);var n=r.text.substring(r.pos,t).replace(/\r\n|\r|\u2028|\u2029/g,"\n");forward(get_full_char_length(n)+2);r.comments_before.push(token("comment2",n,true));r.newline_before=r.newline_before||n.includes("\n");r.regex_allowed=e;return next_token}));var A=with_eof_error("Unterminated identifier name",(function(){var e=[],t,n=false;var read_escaped_identifier_char=function(){n=true;next();if(peek()!=="u"){parse_error("Expecting UnicodeEscapeSequence -- uXXXX or u{XXXX}")}return read_escaped_char(false,true)};if((t=peek())==="\\"){t=read_escaped_identifier_char();if(!is_identifier_start(t)){parse_error("First identifier char is an invalid identifier char")}}else if(is_identifier_start(t)){next()}else{return""}e.push(t);while((t=peek())!=null){if((t=peek())==="\\"){t=read_escaped_identifier_char();if(!is_identifier_char(t)){parse_error("Invalid escaped identifier char")}}else{if(!is_identifier_char(t)){break}next()}e.push(t)}const i=e.join("");if(f.has(i)&&n){parse_error("Escaped characters are not allowed in keywords")}return i}));var x=with_eof_error("Unterminated regular expression",(function(e){var t=false,n,i=false;while(n=next(true))if(S.has(n)){parse_error("Unexpected line terminator")}else if(t){e+="\\"+n;t=false}else if(n=="["){i=true;e+=n}else if(n=="]"&&i){i=false;e+=n}else if(n=="/"&&!i){break}else if(n=="\\"){t=true}else{e+=n}const r=A();return token("regexp","/"+e+"/"+r)}));function read_operator(e){function grow(e){if(!peek())return e;var t=e+peek();if(D.has(t)){next();return grow(t)}else{return e}}return token("operator",grow(e||next()))}function handle_slash(){next();switch(peek()){case"/":next();return skip_line_comment("comment1");case"*":next();return v()}return r.regex_allowed?x(""):read_operator("/")}function handle_eq_sign(){next();if(peek()===">"){next();return token("arrow","=>")}else{return read_operator("=")}}function handle_dot(){next();if(is_digit(peek().charCodeAt(0))){return read_num(".")}if(peek()==="."){next();next();return token("expand","...")}return token("punc",".")}function read_word(){var e=A();if(a)return token("name",e);return c.has(e)?token("atom",e):!l.has(e)?token("name",e):D.has(e)?token("operator",e):token("keyword",e)}function read_private_word(){next();return token("privatename",A())}function with_eof_error(e,t){return function(n){try{return t(n)}catch(t){if(t===R)parse_error(e);else throw t}}}function next_token(e){if(e!=null)return x(e);if(i&&r.pos==0&&looking_at("#!")){start_token();forward(2);skip_line_comment("comment5")}for(;;){skip_whitespace();start_token();if(n){if(looking_at("\x3c!--")){forward(4);skip_line_comment("comment3");continue}if(looking_at("--\x3e")&&r.newline_before){forward(3);skip_line_comment("comment4");continue}}var t=peek();if(!t)return token("eof");var a=t.charCodeAt(0);switch(a){case 34:case 39:return E();case 46:return handle_dot();case 47:{var o=handle_slash();if(o===next_token)continue;return o}case 61:return handle_eq_sign();case 63:{if(!is_option_chain_op())break;next();next();return token("punc","?.")}case 96:return g(true);case 123:r.brace_counter++;break;case 125:r.brace_counter--;if(r.template_braces.length>0&&r.template_braces[r.template_braces.length-1]===r.brace_counter)return g(false);break}if(is_digit(a))return read_num();if(T.has(t))return token("punc",next());if(_.has(t))return read_operator();if(a==92||is_identifier_start(t))return read_word();if(a==35)return read_private_word();break}parse_error("Unexpected character '"+t+"'")}next_token.next=next;next_token.peek=peek;next_token.context=function(e){if(e)r=e;return r};next_token.add_directive=function(e){r.directive_stack[r.directive_stack.length-1].push(e);if(r.directives[e]===undefined){r.directives[e]=1}else{r.directives[e]++}};next_token.push_directives_stack=function(){r.directive_stack.push([])};next_token.pop_directives_stack=function(){var e=r.directive_stack[r.directive_stack.length-1];for(var t=0;t0};return next_token}var w=makePredicate(["typeof","void","delete","--","++","!","~","-","+"]);var O=makePredicate(["--","++"]);var F=makePredicate(["=","+=","-=","??=","&&=","||=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&="]);var N=makePredicate(["??=","&&=","||="]);var M=function(e,t){for(var n=0;n","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],{});var I=makePredicate(["atom","num","big_int","string","regexp","name"]);function parse(e,t){const n=new WeakMap;t=defaults(t,{bare_returns:false,ecma:null,expression:false,filename:null,html5_comments:true,module:false,shebang:true,strict:false,toplevel:null},true);var i={input:typeof e=="string"?tokenizer(e,t.filename,t.html5_comments,t.shebang):e,token:null,prev:null,peeked:null,in_function:0,in_async:-1,in_generator:-1,in_directives:true,in_loop:0,labels:[]};i.token=next();function is(e,t){return is_token(i.token,e,t)}function peek(){return i.peeked||(i.peeked=i.input())}function next(){i.prev=i.token;if(!i.peeked)peek();i.token=i.peeked;i.peeked=null;i.in_directives=i.in_directives&&(i.token.type=="string"||is("punc",";"));return i.token}function prev(){return i.prev}function croak(e,t,n,r){var a=i.input.context();js_error(e,a.filename,t!=null?t:a.tokline,n!=null?n:a.tokcol,r!=null?r:a.tokpos)}function token_error(e,t){croak(t,e.line,e.col)}function unexpected(e){if(e==null)e=i.token;token_error(e,"Unexpected token: "+e.type+" ("+e.value+")")}function expect_token(e,t){if(is(e,t)){return next()}token_error(i.token,"Unexpected token "+i.token.type+" «"+i.token.value+"»"+", expected "+e+" «"+t+"»")}function expect(e){return expect_token("punc",e)}function has_newline_before(e){return e.nlb||!e.comments_before.every((e=>!e.nlb))}function can_insert_semicolon(){return!t.strict&&(is("eof")||is("punc","}")||has_newline_before(i.token))}function is_in_generator(){return i.in_generator===i.in_function}function is_in_async(){return i.in_async===i.in_function}function can_await(){return i.in_async===i.in_function||i.in_function===0&&i.input.has_directive("use strict")}function semicolon(e){if(is("punc",";"))next();else if(!e&&!can_insert_semicolon())unexpected()}function parenthesised(){expect("(");var e=expression(true);expect(")");return e}function embed_tokens(e){return function _embed_tokens_wrapper(...t){const n=i.token;const r=e(...t);r.start=n;r.end=prev();return r}}function handle_regexp(){if(is("operator","/")||is("operator","/=")){i.peeked=null;i.token=i.input(i.token.value.substr(1))}}var r=embed_tokens((function statement(e,n,r){handle_regexp();switch(i.token.type){case"string":if(i.in_directives){var a=peek();if(!s.includes("\\")&&(is_token(a,"punc",";")||is_token(a,"punc","}")||has_newline_before(a)||is_token(a,"eof"))){i.input.add_directive(i.token.value)}else{i.in_directives=false}}var o=i.in_directives,u=simple_statement();return o&&u.body instanceof Gt?new K(u.body):u;case"template_head":case"num":case"big_int":case"regexp":case"operator":case"atom":return simple_statement();case"name":if(i.token.value=="async"&&is_token(peek(),"keyword","function")){next();next();if(n){croak("functions are not allowed as the body of a loop")}return function_(ce,false,true,e)}if(i.token.value=="import"&&!is_token(peek(),"punc","(")&&!is_token(peek(),"punc",".")){next();var l=import_();semicolon();return l}return is_token(peek(),"punc",":")?labeled_statement():simple_statement();case"punc":switch(i.token.value){case"{":return new X({start:i.token,body:block_(),end:prev()});case"[":case"(":return simple_statement();case";":i.in_directives=false;next();return new W;default:unexpected()}case"keyword":switch(i.token.value){case"break":next();return break_cont(be);case"continue":next();return break_cont(De);case"debugger":next();semicolon();return new z;case"do":next();var c=in_loop(statement);expect_token("keyword","while");var f=parenthesised();semicolon(true);return new Z({body:c,condition:f});case"while":next();return new Q({condition:parenthesised(),body:in_loop((function(){return statement(false,true)}))});case"for":next();return for_();case"class":next();if(n){croak("classes are not allowed as the body of a loop")}if(r){croak("classes are not allowed as the body of an if")}return class_(mt,e);case"function":next();if(n){croak("functions are not allowed as the body of a loop")}return function_(ce,false,false,e);case"if":next();return if_();case"return":if(i.in_function==0&&!t.bare_returns)croak("'return' outside of function");next();var p=null;if(is("punc",";")){next()}else if(!can_insert_semicolon()){p=expression(true);semicolon()}return new Ee({value:p});case"switch":next();return new ke({expression:parenthesised(),body:in_loop(switch_body_)});case"throw":next();if(has_newline_before(i.token))croak("Illegal newline after 'throw'");var p=expression(true);semicolon();return new ge({value:p});case"try":next();return try_();case"var":next();var l=var_();semicolon();return l;case"let":next();var l=let_();semicolon();return l;case"const":next();var l=const_();semicolon();return l;case"with":if(i.input.has_directive("use strict")){croak("Strict mode may not include a with statement")}next();return new ne({expression:parenthesised(),body:statement()});case"export":if(!is_token(peek(),"punc","(")){next();var l=export_();if(is("punc",";"))semicolon();return l}}}unexpected()}));function labeled_statement(){var e=as_symbol(It);if(e.name==="await"&&is_in_async()){token_error(i.prev,"await cannot be used as label inside async function")}if(i.labels.some((t=>t.name===e.name))){croak("Label "+e.name+" defined twice")}expect(":");i.labels.push(e);var t=r();i.labels.pop();if(!(t instanceof j)){e.references.forEach((function(t){if(t instanceof De){t=t.label.start;croak("Continue label `"+e.name+"` refers to non-IterationStatement.",t.line,t.col,t.pos)}}))}return new Y({body:t,label:e})}function simple_statement(e){return new G({body:(e=expression(true),semicolon(),e)})}function break_cont(e){var t=null,n;if(!can_insert_semicolon()){t=as_symbol(Vt,true)}if(t!=null){n=i.labels.find((e=>e.name===t.name));if(!n)croak("Undefined label "+t.name);t.thedef=n}else if(i.in_loop==0)croak(e.TYPE+" not inside a loop or switch");semicolon();var r=new e({label:t});if(n)n.references.push(r);return r}function for_(){var e="`for await` invalid in this context";var t=i.token;if(t.type=="name"&&t.value=="await"){if(!can_await()){token_error(t,e)}next()}else{t=false}expect("(");var n=null;if(!is("punc",";")){n=is("keyword","var")?(next(),var_(true)):is("keyword","let")?(next(),let_(true)):is("keyword","const")?(next(),const_(true)):expression(true,true);var r=is("operator","in");var a=is("name","of");if(t&&!a){token_error(t,e)}if(r||a){if(n instanceof Fe){if(n.definitions.length>1)token_error(n.start,"Only one variable declaration allowed in for..in loop")}else if(!(is_assignable(n)||(n=to_destructuring(n))instanceof fe)){token_error(n.start,"Invalid left-hand side in for..in loop")}next();if(r){return for_in(n)}else{return for_of(n,!!t)}}}else if(t){token_error(t,e)}return regular_for(n)}function regular_for(e){expect(";");var t=is("punc",";")?null:expression(true);expect(";");var n=is("punc",")")?null:expression(true);expect(")");return new J({init:e,condition:t,step:n,body:in_loop((function(){return r(false,true)}))})}function for_of(e,t){var n=e instanceof Fe?e.definitions[0].name:null;var i=expression(true);expect(")");return new te({await:t,init:e,name:n,object:i,body:in_loop((function(){return r(false,true)}))})}function for_in(e){var t=expression(true);expect(")");return new ee({init:e,object:t,body:in_loop((function(){return r(false,true)}))})}var arrow_function=function(e,t,n){if(has_newline_before(i.token)){croak("Unexpected newline before arrow (=>)")}expect_token("arrow","=>");var r=_function_body(is("punc","{"),false,n);var a=r instanceof Array&&r.length?r[r.length-1].end:r instanceof Array?e:r.end;return new le({start:e,end:a,async:n,argnames:t,body:r})};var function_=function(e,t,n,i){var r=e===ce;var a=is("operator","*");if(a){next()}var o=is("name")?as_symbol(r?Tt:Rt):null;if(r&&!o){if(i){e=ue}else{unexpected()}}if(o&&e!==se&&!(o instanceof bt))unexpected(prev());var s=[];var u=_function_body(true,a||t,n,o,s);return new e({start:s.start,end:u.end,is_generator:a,async:n,name:o,argnames:s,body:u})};function track_used_binding_identifiers(e,t){var n=new Set;var i=false;var r=false;var a=false;var o=!!t;var s={add_parameter:function(t){if(n.has(t.value)){if(i===false){i=t}s.check_strict()}else{n.add(t.value);if(e){switch(t.value){case"arguments":case"eval":case"yield":if(o){token_error(t,"Unexpected "+t.value+" identifier as parameter inside strict mode")}break;default:if(f.has(t.value)){unexpected()}}}}},mark_default_assignment:function(e){if(r===false){r=e}},mark_spread:function(e){if(a===false){a=e}},mark_strict_mode:function(){o=true},is_strict:function(){return r!==false||a!==false||o},check_strict:function(){if(s.is_strict()&&i!==false){token_error(i,"Parameter "+i.value+" was used already")}}};return s}function parameters(e){var t=track_used_binding_identifiers(true,i.input.has_directive("use strict"));expect("(");while(!is("punc",")")){var n=parameter(t);e.push(n);if(!is("punc",")")){expect(",")}if(n instanceof ae){break}}next()}function parameter(e,t){var n;var r=false;if(e===undefined){e=track_used_binding_identifiers(true,i.input.has_directive("use strict"))}if(is("expand","...")){r=i.token;e.mark_spread(i.token);next()}n=binding_element(e,t);if(is("operator","=")&&r===false){e.mark_default_assignment(i.token);next();n=new tt({start:n.start,left:n,operator:"=",right:expression(false),end:i.token})}if(r!==false){if(!is("punc",")")){unexpected()}n=new ae({start:r,expression:n,end:r})}e.check_strict();return n}function binding_element(e,t){var n=[];var r=true;var a=false;var o;var s=i.token;if(e===undefined){e=track_used_binding_identifiers(false,i.input.has_directive("use strict"))}t=t===undefined?kt:t;if(is("punc","[")){next();while(!is("punc","]")){if(r){r=false}else{expect(",")}if(is("expand","...")){a=true;o=i.token;e.mark_spread(i.token);next()}if(is("punc")){switch(i.token.value){case",":n.push(new Zt({start:i.token,end:i.token}));continue;case"]":break;case"[":case"{":n.push(binding_element(e,t));break;default:unexpected()}}else if(is("name")){e.add_parameter(i.token);n.push(as_symbol(t))}else{croak("Invalid function parameter")}if(is("operator","=")&&a===false){e.mark_default_assignment(i.token);next();n[n.length-1]=new tt({start:n[n.length-1].start,left:n[n.length-1],operator:"=",right:expression(false),end:i.token})}if(a){if(!is("punc","]")){croak("Rest element must be last element")}n[n.length-1]=new ae({start:o,expression:n[n.length-1],end:o})}}expect("]");e.check_strict();return new fe({start:s,names:n,is_array:true,end:prev()})}else if(is("punc","{")){next();while(!is("punc","}")){if(r){r=false}else{expect(",")}if(is("expand","...")){a=true;o=i.token;e.mark_spread(i.token);next()}if(is("name")&&(is_token(peek(),"punc")||is_token(peek(),"operator"))&&[",","}","="].includes(peek().value)){e.add_parameter(i.token);var u=prev();var l=as_symbol(t);if(a){n.push(new ae({start:o,expression:l,end:l.end}))}else{n.push(new ot({start:u,key:l.name,value:l,end:l.end}))}}else if(is("punc","}")){continue}else{var c=i.token;var f=as_property_name();if(f===null){unexpected(prev())}else if(prev().type==="name"&&!is("punc",":")){n.push(new ot({start:prev(),key:f,value:new t({start:prev(),name:f,end:prev()}),end:prev()}))}else{expect(":");n.push(new ot({start:c,quote:c.quote,key:f,value:binding_element(e,t),end:prev()}))}}if(a){if(!is("punc","}")){croak("Rest element must be last element")}}else if(is("operator","=")){e.mark_default_assignment(i.token);next();n[n.length-1].value=new tt({start:n[n.length-1].value.start,left:n[n.length-1].value,operator:"=",right:expression(false),end:i.token})}}expect("}");e.check_strict();return new fe({start:s,names:n,is_array:false,end:prev()})}else if(is("name")){e.add_parameter(i.token);return as_symbol(t)}else{croak("Invalid function parameter")}}function params_or_seq_(e,t){var n;var r;var a;var o=[];expect("(");while(!is("punc",")")){if(n)unexpected(n);if(is("expand","...")){n=i.token;if(t)r=i.token;next();o.push(new ae({start:prev(),expression:expression(),end:i.token}))}else{o.push(expression())}if(!is("punc",")")){expect(",");if(is("punc",")")){a=prev();if(t)r=a}}}expect(")");if(e&&is("arrow","=>")){if(n&&a)unexpected(a)}else if(r){unexpected(r)}return o}function _function_body(e,t,n,r,a){var o=i.in_loop;var s=i.labels;var u=i.in_generator;var l=i.in_async;++i.in_function;if(t)i.in_generator=i.in_function;if(n)i.in_async=i.in_function;if(a)parameters(a);if(e)i.in_directives=true;i.in_loop=0;i.labels=[];if(e){i.input.push_directives_stack();var c=block_();if(r)_verify_symbol(r);if(a)a.forEach(_verify_symbol);i.input.pop_directives_stack()}else{var c=[new Ee({start:i.token,value:expression(false),end:i.token})]}--i.in_function;i.in_loop=o;i.labels=s;i.in_generator=u;i.in_async=l;return c}function _await_expression(){if(!can_await()){croak("Unexpected await expression outside async function",i.prev.line,i.prev.col,i.prev.pos)}return new ye({start:prev(),end:i.token,expression:maybe_unary(true)})}function _yield_expression(){if(!is_in_generator()){croak("Unexpected yield expression outside generator function",i.prev.line,i.prev.col,i.prev.pos)}var e=i.token;var t=false;var n=true;if(can_insert_semicolon()||is("punc")&&A.has(i.token.value)){n=false}else if(is("operator","*")){t=true;next()}return new Se({start:e,is_star:t,expression:n?expression():null,end:prev()})}function if_(){var e=parenthesised(),t=r(false,false,true),n=null;if(is("keyword","else")){next();n=r(false,false,true)}return new Ae({condition:e,body:t,alternative:n})}function block_(){expect("{");var e=[];while(!is("punc","}")){if(is("eof"))unexpected();e.push(r())}next();return e}function switch_body_(){expect("{");var e=[],t=null,n=null,a;while(!is("punc","}")){if(is("eof"))unexpected();if(is("keyword","case")){if(n)n.end=prev();t=[];n=new Ce({start:(a=i.token,next(),a),expression:expression(true),body:t});e.push(n);expect(":")}else if(is("keyword","default")){if(n)n.end=prev();t=[];n=new xe({start:(a=i.token,next(),expect(":"),a),body:t});e.push(n)}else{if(!t)unexpected();t.push(r())}}if(n)n.end=prev();next();return e}function try_(){var e=block_(),t=null,n=null;if(is("keyword","catch")){var r=i.token;next();if(is("punc","{")){var a=null}else{expect("(");var a=parameter(undefined,Ft);expect(")")}t=new we({start:r,argname:a,body:block_(),end:prev()})}if(is("keyword","finally")){var r=i.token;next();n=new Oe({start:r,body:block_(),end:prev()})}if(!t&&!n)croak("Missing catch/finally blocks");return new Re({body:e,bcatch:t,bfinally:n})}function vardefs(e,t){var n=[];var r;for(;;){var a=t==="var"?Dt:t==="const"?St:t==="let"?At:null;if(is("punc","{")||is("punc","[")){r=new Pe({start:i.token,name:binding_element(undefined,a),value:is("operator","=")?(expect_token("operator","="),expression(false,e)):null,end:prev()})}else{r=new Pe({start:i.token,name:as_symbol(a),value:is("operator","=")?(next(),expression(false,e)):!e&&t==="const"?croak("Missing initializer in const declaration"):null,end:prev()});if(r.name.name=="import")croak("Unexpected token: import")}n.push(r);if(!is("punc",","))break;next()}return n}var var_=function(e){return new Ne({start:prev(),definitions:vardefs(e,"var"),end:prev()})};var let_=function(e){return new Me({start:prev(),definitions:vardefs(e,"let"),end:prev()})};var const_=function(e){return new Ie({start:prev(),definitions:vardefs(e,"const"),end:prev()})};var new_=function(e){var t=i.token;expect_token("operator","new");if(is("punc",".")){next();expect_token("name","target");return subscripts(new vt({start:t,end:prev()}),e)}var n=expr_atom(false),r;if(is("punc","(")){next();r=expr_list(")",true)}else{r=[]}var a=new Ke({start:t,expression:n,args:r,end:prev()});annotate(a);return subscripts(a,e)};function as_atom_node(){var e=i.token,t;switch(e.type){case"name":t=_make_symbol(Pt);break;case"num":t=new Ht({start:e,end:e,value:e.value,raw:s});break;case"big_int":t=new Xt({start:e,end:e,value:e.value});break;case"string":t=new Gt({start:e,end:e,value:e.value,quote:e.quote});break;case"regexp":const[n,i,r]=e.value.match(/^\/(.*)\/(\w*)$/);t=new Wt({start:e,end:e,value:{source:i,flags:r}});break;case"atom":switch(e.value){case"false":t=new en({start:e,end:e});break;case"true":t=new tn({start:e,end:e});break;case"null":t=new Yt({start:e,end:e});break}break}next();return t}function to_fun_args(e,t){var insert_default=function(e,t){if(t){return new tt({start:e.start,left:e,operator:"=",right:t,end:t.end})}return e};if(e instanceof it){return insert_default(new fe({start:e.start,end:e.end,is_array:false,names:e.properties.map((e=>to_fun_args(e)))}),t)}else if(e instanceof ot){e.value=to_fun_args(e.value);return insert_default(e,t)}else if(e instanceof Zt){return e}else if(e instanceof fe){e.names=e.names.map((e=>to_fun_args(e)));return insert_default(e,t)}else if(e instanceof Pt){return insert_default(new kt({name:e.name,start:e.start,end:e.end}),t)}else if(e instanceof ae){e.expression=to_fun_args(e.expression);return insert_default(e,t)}else if(e instanceof nt){return insert_default(new fe({start:e.start,end:e.end,is_array:true,names:e.elements.map((e=>to_fun_args(e)))}),t)}else if(e instanceof et){return insert_default(to_fun_args(e.left,e.right),t)}else if(e instanceof tt){e.left=to_fun_args(e.left);return e}else{croak("Invalid function parameter",e.start.line,e.start.col)}}var expr_atom=function(e,t){if(is("operator","new")){return new_(e)}if(is("operator","import")){return import_meta()}var r=i.token;var o;var s=is("name","async")&&(o=peek()).value!="["&&o.type!="arrow"&&as_atom_node();if(is("punc")){switch(i.token.value){case"(":if(s&&!e)break;var u=params_or_seq_(t,!s);if(t&&is("arrow","=>")){return arrow_function(r,u.map((e=>to_fun_args(e))),!!s)}var c=s?new ze({expression:s,args:u}):u.length==1?u[0]:new Ge({expressions:u});if(c.start){const e=r.comments_before.length;n.set(r,e);c.start.comments_before.unshift(...r.comments_before);r.comments_before=c.start.comments_before;if(e==0&&r.comments_before.length>0){var f=r.comments_before[0];if(!f.nlb){f.nlb=r.nlb;r.nlb=false}}r.comments_after=c.start.comments_after}c.start=r;var p=prev();if(c.end){p.comments_before=c.end.comments_before;c.end.comments_after.push(...p.comments_after);p.comments_after=c.end.comments_after}c.end=p;if(c instanceof ze)annotate(c);return subscripts(c,e);case"[":return subscripts(a(),e);case"{":return subscripts(l(),e)}if(!s)unexpected()}if(t&&is("name")&&is_token(peek(),"arrow")){var _=new kt({name:i.token.value,start:r,end:r});next();return arrow_function(r,[_],!!s)}if(is("keyword","function")){next();var d=function_(ue,false,!!s);d.start=r;d.end=prev();return subscripts(d,e)}if(s)return subscripts(s,e);if(is("keyword","class")){next();var h=class_(Et);h.start=r;h.end=prev();return subscripts(h,e)}if(is("template_head")){return subscripts(template_string(),e)}if(I.has(i.token.type)){return subscripts(as_atom_node(),e)}unexpected()};function template_string(){var e=[],t=i.token;e.push(new de({start:i.token,raw:s,value:i.token.value,end:i.token}));while(!u){next();handle_regexp();e.push(expression(true));e.push(new de({start:i.token,raw:s,value:i.token.value,end:i.token}))}next();return new _e({start:t,segments:e,end:i.token})}function expr_list(e,t,n){var r=true,a=[];while(!is("punc",e)){if(r)r=false;else expect(",");if(t&&is("punc",e))break;if(is("punc",",")&&n){a.push(new Zt({start:i.token,end:i.token}))}else if(is("expand","...")){next();a.push(new ae({start:prev(),expression:expression(),end:i.token}))}else{a.push(expression(false))}}next();return a}var a=embed_tokens((function(){expect("[");return new nt({elements:expr_list("]",!t.strict,true)})}));var o=embed_tokens(((e,t)=>function_(se,e,t)));var l=embed_tokens((function object_or_destructuring_(){var e=i.token,n=true,r=[];expect("{");while(!is("punc","}")){if(n)n=false;else expect(",");if(!t.strict&&is("punc","}"))break;e=i.token;if(e.type=="expand"){next();r.push(new ae({start:e,expression:expression(false),end:prev()}));continue}var a=as_property_name();var o;if(!is("punc",":")){var s=concise_method_or_getset(a,e);if(s){r.push(s);continue}o=new Pt({start:prev(),name:a,end:prev()})}else if(a===null){unexpected(prev())}else{next();o=expression(false)}if(is("operator","=")){next();o=new et({start:e,left:o,operator:"=",right:expression(false),logical:false,end:prev()})}r.push(new ot({start:e,quote:e.quote,key:a instanceof V?a:""+a,value:o,end:prev()}))}next();return new it({properties:r})}));function class_(e,t){var n,r,a,o,s=[];i.input.push_directives_stack();i.input.add_directive("use strict");if(i.token.type=="name"&&i.token.value!="extends"){a=as_symbol(e===mt?wt:Ot)}if(e===mt&&!a){if(t){e=Et}else{unexpected()}}if(i.token.value=="extends"){next();o=expression(true)}expect("{");while(is("punc",";")){next()}while(!is("punc","}")){n=i.token;r=concise_method_or_getset(as_property_name(),n,true);if(!r){unexpected()}s.push(r);while(is("punc",";")){next()}}i.input.pop_directives_stack();next();return new e({start:n,name:a,extends:o,properties:s,end:prev()})}function concise_method_or_getset(e,t,n){const get_symbol_ast=(e,n=xt)=>{if(typeof e==="string"||typeof e==="number"){return new n({start:t,name:""+e,end:prev()})}else if(e===null){unexpected()}return e};const is_not_method_start=()=>!is("punc","(")&&!is("punc",",")&&!is("punc","}")&&!is("operator","=");var i=false;var r=false;var a=false;var s=false;var u=null;if(n&&e==="static"&&is_not_method_start()){r=true;e=as_property_name()}if(e==="async"&&is_not_method_start()){i=true;e=as_property_name()}if(prev().type==="operator"&&prev().value==="*"){a=true;e=as_property_name()}if((e==="get"||e==="set")&&is_not_method_start()){u=e;e=as_property_name()}if(prev().type==="privatename"){s=true}const l=prev();if(u!=null){if(!s){const n=u==="get"?ct:lt;e=get_symbol_ast(e);return new n({start:t,static:r,key:e,quote:e instanceof xt?l.quote:undefined,value:o(),end:prev()})}else{const n=u==="get"?ut:st;return new n({start:t,static:r,key:get_symbol_ast(e),value:o(),end:prev()})}}if(is("punc","(")){e=get_symbol_ast(e);const n=s?pt:ft;var c=new n({start:t,static:r,is_generator:a,async:i,key:e,quote:e instanceof xt?l.quote:undefined,value:o(a,i),end:prev()});return c}if(n){const n=get_symbol_ast(e,Ct);const i=n instanceof Ct?l.quote:undefined;const a=s?ht:dt;if(is("operator","=")){next();return new a({start:t,static:r,quote:i,key:n,value:expression(false),end:prev()})}else if(is("name")||is("privatename")||is("operator","*")||is("punc",";")||is("punc","}")){return new a({start:t,static:r,quote:i,key:n,end:prev()})}}}function import_(){var e=prev();var t;var n;if(is("name")){t=as_symbol(Nt)}if(is("punc",",")){next()}n=map_names(true);if(n||t){expect_token("name","from")}var r=i.token;if(r.type!=="string"){unexpected()}next();return new Be({start:e,imported_name:t,imported_names:n,module_name:new Gt({start:r,value:r.value,quote:r.quote,end:r}),end:i.token})}function import_meta(){var e=i.token;expect_token("operator","import");expect_token("punc",".");expect_token("name","meta");return subscripts(new Ve({start:e,end:prev()}),false)}function map_name(e){function make_symbol(e){return new e({name:as_property_name(),start:prev(),end:prev()})}var t=e?Mt:Bt;var n=e?Nt:Lt;var r=i.token;var a;var o;if(e){a=make_symbol(t)}else{o=make_symbol(n)}if(is("name","as")){next();if(e){o=make_symbol(n)}else{a=make_symbol(t)}}else if(e){o=new n(a)}else{a=new t(o)}return new Le({start:r,foreign_name:a,name:o,end:prev()})}function map_nameAsterisk(e,t){var n=e?Mt:Bt;var r=e?Nt:Lt;var a=i.token;var o;var s=prev();t=t||new r({name:"*",start:a,end:s});o=new n({name:"*",start:a,end:s});return new Le({start:a,foreign_name:o,name:t,end:s})}function map_names(e){var t;if(is("punc","{")){next();t=[];while(!is("punc","}")){t.push(map_name(e));if(is("punc",",")){next()}}next()}else if(is("operator","*")){var n;next();if(e&&is("name","as")){next();n=as_symbol(e?Nt:Bt)}t=[map_nameAsterisk(e,n)]}return t}function export_(){var e=i.token;var t;var n;if(is("keyword","default")){t=true;next()}else if(n=map_names(false)){if(is("name","from")){next();var a=i.token;if(a.type!=="string"){unexpected()}next();return new Ue({start:e,is_default:t,exported_names:n,module_name:new Gt({start:a,value:a.value,quote:a.quote,end:a}),end:prev()})}else{return new Ue({start:e,is_default:t,exported_names:n,end:prev()})}}var o;var s;var u;if(is("punc","{")||t&&(is("keyword","class")||is("keyword","function"))&&is_token(peek(),"punc")){s=expression(false);semicolon()}else if((o=r(t))instanceof Fe&&t){unexpected(o.start)}else if(o instanceof Fe||o instanceof ce||o instanceof mt){u=o}else if(o instanceof Et||o instanceof ue){s=o}else if(o instanceof G){s=o.body}else{unexpected(o.start)}return new Ue({start:e,is_default:t,exported_value:s,exported_definition:u,end:prev()})}function as_property_name(){var e=i.token;switch(e.type){case"punc":if(e.value==="["){next();var t=expression(false);expect("]");return t}else unexpected(e);case"operator":if(e.value==="*"){next();return null}if(!["delete","in","instanceof","new","typeof","void"].includes(e.value)){unexpected(e)}case"name":case"privatename":case"string":case"num":case"big_int":case"keyword":case"atom":next();return e.value;default:unexpected(e)}}function as_name(){var e=i.token;if(e.type!="name"&&e.type!="privatename")unexpected();next();return e.value}function _make_symbol(e){var t=i.token.value;return new(t=="this"?Ut:t=="super"?zt:e)({name:String(t),start:i.token,end:i.token})}function _verify_symbol(e){var t=e.name;if(is_in_generator()&&t=="yield"){token_error(e.start,"Yield cannot be used as identifier inside generators")}if(i.input.has_directive("use strict")){if(t=="yield"){token_error(e.start,"Unexpected yield identifier inside strict mode")}if(e instanceof bt&&(t=="arguments"||t=="eval")){token_error(e.start,"Unexpected "+t+" in strict mode")}}}function as_symbol(e,t){if(!is("name")){if(!t)croak("Name expected");return null}var n=_make_symbol(e);_verify_symbol(n);next();return n}function annotate(e){var t=e.start;var i=t.comments_before;const r=n.get(t);var a=r!=null?r:i.length;while(--a>=0){var o=i[a];if(/[@#]__/.test(o.value)){if(/[@#]__PURE__/.test(o.value)){set_annotation(e,rn);break}if(/[@#]__INLINE__/.test(o.value)){set_annotation(e,an);break}if(/[@#]__NOINLINE__/.test(o.value)){set_annotation(e,on);break}}}}var subscripts=function(e,t,n){var i=e.start;if(is("punc",".")){next();const r=is("privatename")?We:Xe;return subscripts(new r({start:i,expression:e,optional:false,property:as_name(),end:prev()}),t,n)}if(is("punc","[")){next();var r=expression(true);expect("]");return subscripts(new qe({start:i,expression:e,optional:false,property:r,end:prev()}),t,n)}if(t&&is("punc","(")){next();var a=new ze({start:i,expression:e,optional:false,args:call_args(),end:prev()});annotate(a);return subscripts(a,true,n)}if(is("punc","?.")){next();let n;if(t&&is("punc","(")){next();const t=new ze({start:i,optional:true,expression:e,args:call_args(),end:prev()});annotate(t);n=subscripts(t,true,true)}else if(is("name")||is("privatename")){const r=is("privatename")?We:Xe;n=subscripts(new r({start:i,expression:e,optional:true,property:as_name(),end:prev()}),t,true)}else if(is("punc","[")){next();const r=expression(true);expect("]");n=subscripts(new qe({start:i,expression:e,optional:true,property:r,end:prev()}),t,true)}if(!n)unexpected();if(n instanceof Ye)return n;return new Ye({start:i,expression:n,end:prev()})}if(is("template_head")){if(n){unexpected()}return subscripts(new pe({start:i,prefix:e,template_string:template_string(),end:prev()}),t)}return e};function call_args(){var e=[];while(!is("punc",")")){if(is("expand","...")){next();e.push(new ae({start:prev(),expression:expression(false),end:prev()}))}else{e.push(expression(false))}if(!is("punc",")")){expect(",")}}next();return e}var maybe_unary=function(e,t){var n=i.token;if(n.type=="name"&&n.value=="await"&&can_await()){next();return _await_expression()}if(is("operator")&&w.has(n.value)){next();handle_regexp();var r=make_unary($e,n,maybe_unary(e));r.start=n;r.end=prev();return r}var a=expr_atom(e,t);while(is("operator")&&O.has(i.token.value)&&!has_newline_before(i.token)){if(a instanceof le)unexpected();a=make_unary(Ze,i.token,a);a.start=n;a.end=i.token;next()}return a};function make_unary(e,t,n){var r=t.value;switch(r){case"++":case"--":if(!is_assignable(n))croak("Invalid use of "+r+" operator",t.line,t.col,t.pos);break;case"delete":if(n instanceof Pt&&i.input.has_directive("use strict"))croak("Calling delete on expression not allowed in strict mode",n.start.line,n.start.col,n.start.pos);break}return new e({operator:r,expression:n})}var expr_op=function(e,t,n){var r=is("operator")?i.token.value:null;if(r=="in"&&n)r=null;if(r=="**"&&e instanceof $e&&!is_token(e.start,"punc","(")&&e.operator!=="--"&&e.operator!=="++")unexpected(e.start);var a=r!=null?M[r]:null;if(a!=null&&(a>t||r==="**"&&t===a)){next();var o=expr_op(maybe_unary(true),a,n);return expr_op(new Qe({start:e.start,left:e,operator:r,right:o,end:o.end}),t,n)}return e};function expr_ops(e){return expr_op(maybe_unary(true,true),0,e)}var maybe_conditional=function(e){var t=i.token;var n=expr_ops(e);if(is("operator","?")){next();var r=expression(false);expect(":");return new Je({start:t,condition:n,consequent:r,alternative:expression(false,e),end:prev()})}return n};function is_assignable(e){return e instanceof He||e instanceof Pt}function to_destructuring(e){if(e instanceof it){e=new fe({start:e.start,names:e.properties.map(to_destructuring),is_array:false,end:e.end})}else if(e instanceof nt){var t=[];for(var n=0;n=0;){a+="this."+t[o]+" = props."+t[o]+";"}const s=i&&Object.create(i.prototype);if(s&&s.initialize||n&&n.initialize)a+="this.initialize();";a+="}";a+="this.flags = 0;";a+="}";var u=new Function(a)();if(s){u.prototype=s;u.BASE=i}if(i)i.SUBCLASSES.push(u);u.prototype.CTOR=u;u.prototype.constructor=u;u.PROPS=t||null;u.SELF_PROPS=r;u.SUBCLASSES=[];if(e){u.prototype.TYPE=u.TYPE=e}if(n)for(o in n)if(HOP(n,o)){if(o[0]==="$"){u[o.substr(1)]=n[o]}else{u.prototype[o]=n[o]}}u.DEFMETHOD=function(e,t){this.prototype[e]=t};return u}const has_tok_flag=(e,t)=>Boolean(e.flags&t);const set_tok_flag=(e,t,n)=>{if(n){e.flags|=t}else{e.flags&=~t}};const P=1;const L=2;const B=4;class AST_Token{constructor(e,t,n,i,r,a,o,s,u){this.flags=a?1:0;this.type=e;this.value=t;this.line=n;this.col=i;this.pos=r;this.comments_before=o;this.comments_after=s;this.file=u;Object.seal(this)}get nlb(){return has_tok_flag(this,P)}set nlb(e){set_tok_flag(this,P,e)}get quote(){return!has_tok_flag(this,B)?"":has_tok_flag(this,L)?"'":'"'}set quote(e){set_tok_flag(this,L,e==="'");set_tok_flag(this,B,!!e)}}var V=DEFNODE("Node","start end",{_clone:function(e){if(e){var t=this.clone();return t.transform(new TreeTransformer((function(e){if(e!==t){return e.clone(true)}})))}return new this.CTOR(this)},clone:function(e){return this._clone(e)},$documentation:"Base class of all AST nodes",$propdoc:{start:"[AST_Token] The first token of this node",end:"[AST_Token] The last token of this node"},_walk:function(e){return e._visit(this)},walk:function(e){return this._walk(e)},_children_backwards:()=>{}},null);var U=DEFNODE("Statement",null,{$documentation:"Base class of all statements"});var z=DEFNODE("Debugger",null,{$documentation:"Represents a debugger statement"},U);var K=DEFNODE("Directive","value quote",{$documentation:'Represents a directive, like "use strict";',$propdoc:{value:"[string] The value of this directive as a plain string (it's not an AST_String!)",quote:"[string] the original quote character"}},U);var G=DEFNODE("SimpleStatement","body",{$documentation:"A statement consisting of an expression, i.e. a = 1 + 2",$propdoc:{body:"[AST_Node] an expression node (should not be instanceof AST_Statement)"},_walk:function(e){return e._visit(this,(function(){this.body._walk(e)}))},_children_backwards(e){e(this.body)}},U);function walk_body(e,t){const n=e.body;for(var i=0,r=n.length;i SymbolDef for all variables/functions defined in this scope",uses_with:"[boolean/S] tells whether this scope uses the `with` statement",uses_eval:"[boolean/S] tells whether this scope contains a direct call to the global `eval`",parent_scope:"[AST_Scope?/S] link to the parent scope",enclosed:"[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",cname:"[integer/S] current index for mangling variables (used internally by the mangler)"},get_defun_scope:function(){var e=this;while(e.is_block_scope()){e=e.parent_scope}return e},clone:function(e,t){var n=this._clone(e);if(e&&this.variables&&t&&!this._block_scope){n.figure_out_scope({},{toplevel:t,parent_scope:this.parent_scope})}else{if(this.variables)n.variables=new Map(this.variables);if(this.enclosed)n.enclosed=this.enclosed.slice();if(this._block_scope)n._block_scope=this._block_scope}return n},pinned:function(){return this.uses_eval||this.uses_with}},H);var re=DEFNODE("Toplevel","globals",{$documentation:"The toplevel scope",$propdoc:{globals:"[Map/S] a map of name -> SymbolDef for all undeclared names"},wrap_commonjs:function(e){var t=this.body;var n="(function(exports){'$ORIG';})(typeof "+e+"=='undefined'?("+e+"={}):"+e+");";n=parse(n);n=n.transform(new TreeTransformer((function(e){if(e instanceof K&&e.value=="$ORIG"){return r.splice(t)}})));return n},wrap_enclose:function(e){if(typeof e!="string")e="";var t=e.indexOf(":");if(t<0)t=e.length;var n=this.body;return parse(["(function(",e.slice(0,t),'){"$ORIG"})(',e.slice(t+1),")"].join("")).transform(new TreeTransformer((function(e){if(e instanceof K&&e.value=="$ORIG"){return r.splice(n)}})))}},ie);var ae=DEFNODE("Expansion","expression",{$documentation:"An expandible argument, such as ...rest, a splat, such as [1,2,...all], or an expansion in a variable declaration, such as var [first, ...rest] = list",$propdoc:{expression:"[AST_Node] the thing to be expanded"},_walk:function(e){return e._visit(this,(function(){this.expression.walk(e)}))},_children_backwards(e){e(this.expression)}});var oe=DEFNODE("Lambda","name argnames uses_arguments is_generator async",{$documentation:"Base class for functions",$propdoc:{name:"[AST_SymbolDeclaration?] the name of this function",argnames:"[AST_SymbolFunarg|AST_Destructuring|AST_Expansion|AST_DefaultAssign*] array of function arguments, destructurings, or expanding arguments",uses_arguments:"[boolean/S] tells whether this function accesses the arguments array",is_generator:"[boolean] is this a generator method",async:"[boolean] is this method async"},args_as_names:function(){var e=[];for(var t=0;t b)"},oe);var ce=DEFNODE("Defun",null,{$documentation:"A function definition"},oe);var fe=DEFNODE("Destructuring","names is_array",{$documentation:"A destructuring of several names. Used in destructuring assignment and with destructuring function argument names",$propdoc:{names:"[AST_Node*] Array of properties or elements",is_array:"[Boolean] Whether the destructuring represents an object or array"},_walk:function(e){return e._visit(this,(function(){this.names.forEach((function(t){t._walk(e)}))}))},_children_backwards(e){let t=this.names.length;while(t--)e(this.names[t])},all_symbols:function(){var e=[];this.walk(new TreeWalker((function(t){if(t instanceof gt){e.push(t)}})));return e}});var pe=DEFNODE("PrefixedTemplateString","template_string prefix",{$documentation:"A templatestring with a prefix, such as String.raw`foobarbaz`",$propdoc:{template_string:"[AST_TemplateString] The template string",prefix:"[AST_Node] The prefix, which will get called."},_walk:function(e){return e._visit(this,(function(){this.prefix._walk(e);this.template_string._walk(e)}))},_children_backwards(e){e(this.template_string);e(this.prefix)}});var _e=DEFNODE("TemplateString","segments",{$documentation:"A template string literal",$propdoc:{segments:"[AST_Node*] One or more segments, starting with AST_TemplateSegment. AST_Node may follow AST_TemplateSegment, but each AST_Node must be followed by AST_TemplateSegment."},_walk:function(e){return e._visit(this,(function(){this.segments.forEach((function(t){t._walk(e)}))}))},_children_backwards(e){let t=this.segments.length;while(t--)e(this.segments[t])}});var de=DEFNODE("TemplateSegment","value raw",{$documentation:"A segment of a template string literal",$propdoc:{value:"Content of the segment",raw:"Raw source of the segment"}});var he=DEFNODE("Jump",null,{$documentation:"Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"},U);var me=DEFNODE("Exit","value",{$documentation:"Base class for “exits” (`return` and `throw`)",$propdoc:{value:"[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"},_walk:function(e){return e._visit(this,this.value&&function(){this.value._walk(e)})},_children_backwards(e){if(this.value)e(this.value)}},he);var Ee=DEFNODE("Return",null,{$documentation:"A `return` statement"},me);var ge=DEFNODE("Throw",null,{$documentation:"A `throw` statement"},me);var ve=DEFNODE("LoopControl","label",{$documentation:"Base class for loop control statements (`break` and `continue`)",$propdoc:{label:"[AST_LabelRef?] the label, or null if none"},_walk:function(e){return e._visit(this,this.label&&function(){this.label._walk(e)})},_children_backwards(e){if(this.label)e(this.label)}},he);var be=DEFNODE("Break",null,{$documentation:"A `break` statement"},ve);var De=DEFNODE("Continue",null,{$documentation:"A `continue` statement"},ve);var ye=DEFNODE("Await","expression",{$documentation:"An `await` statement",$propdoc:{expression:"[AST_Node] the mandatory expression being awaited"},_walk:function(e){return e._visit(this,(function(){this.expression._walk(e)}))},_children_backwards(e){e(this.expression)}});var Se=DEFNODE("Yield","expression is_star",{$documentation:"A `yield` statement",$propdoc:{expression:"[AST_Node?] the value returned or thrown by this statement; could be null (representing undefined) but only when is_star is set to false",is_star:"[Boolean] Whether this is a yield or yield* statement"},_walk:function(e){return e._visit(this,this.expression&&function(){this.expression._walk(e)})},_children_backwards(e){if(this.expression)e(this.expression)}});var Ae=DEFNODE("If","condition alternative",{$documentation:"A `if` statement",$propdoc:{condition:"[AST_Node] the `if` condition",alternative:"[AST_Statement?] the `else` part, or null if not present"},_walk:function(e){return e._visit(this,(function(){this.condition._walk(e);this.body._walk(e);if(this.alternative)this.alternative._walk(e)}))},_children_backwards(e){if(this.alternative){e(this.alternative)}e(this.body);e(this.condition)}},q);var ke=DEFNODE("Switch","expression",{$documentation:"A `switch` statement",$propdoc:{expression:"[AST_Node] the `switch` “discriminant”"},_walk:function(e){return e._visit(this,(function(){this.expression._walk(e);walk_body(this,e)}))},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},H);var Te=DEFNODE("SwitchBranch",null,{$documentation:"Base class for `switch` branches"},H);var xe=DEFNODE("Default",null,{$documentation:"A `default` switch branch"},Te);var Ce=DEFNODE("Case","expression",{$documentation:"A `case` switch branch",$propdoc:{expression:"[AST_Node] the `case` expression"},_walk:function(e){return e._visit(this,(function(){this.expression._walk(e);walk_body(this,e)}))},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},Te);var Re=DEFNODE("Try","bcatch bfinally",{$documentation:"A `try` statement",$propdoc:{bcatch:"[AST_Catch?] the catch block, or null if not present",bfinally:"[AST_Finally?] the finally block, or null if not present"},_walk:function(e){return e._visit(this,(function(){walk_body(this,e);if(this.bcatch)this.bcatch._walk(e);if(this.bfinally)this.bfinally._walk(e)}))},_children_backwards(e){if(this.bfinally)e(this.bfinally);if(this.bcatch)e(this.bcatch);let t=this.body.length;while(t--)e(this.body[t])}},H);var we=DEFNODE("Catch","argname",{$documentation:"A `catch` node; only makes sense as part of a `try` statement",$propdoc:{argname:"[AST_SymbolCatch|AST_Destructuring|AST_Expansion|AST_DefaultAssign] symbol for the exception"},_walk:function(e){return e._visit(this,(function(){if(this.argname)this.argname._walk(e);walk_body(this,e)}))},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);if(this.argname)e(this.argname)}},H);var Oe=DEFNODE("Finally",null,{$documentation:"A `finally` node; only makes sense as part of a `try` statement"},H);var Fe=DEFNODE("Definitions","definitions",{$documentation:"Base class for `var` or `const` nodes (variable declarations/initializations)",$propdoc:{definitions:"[AST_VarDef*] array of variable definitions"},_walk:function(e){return e._visit(this,(function(){var t=this.definitions;for(var n=0,i=t.length;n a`"},Qe);var nt=DEFNODE("Array","elements",{$documentation:"An array literal",$propdoc:{elements:"[AST_Node*] array of elements"},_walk:function(e){return e._visit(this,(function(){var t=this.elements;for(var n=0,i=t.length;nt._walk(e)))}))},_children_backwards(e){let t=this.properties.length;while(t--)e(this.properties[t]);if(this.extends)e(this.extends);if(this.name)e(this.name)}},ie);var dt=DEFNODE("ClassProperty","static quote",{$documentation:"A class property",$propdoc:{static:"[boolean] whether this is a static key",quote:"[string] which quote is being used"},_walk:function(e){return e._visit(this,(function(){if(this.key instanceof V)this.key._walk(e);if(this.value instanceof V)this.value._walk(e)}))},_children_backwards(e){if(this.value instanceof V)e(this.value);if(this.key instanceof V)e(this.key)},computed_key(){return!(this.key instanceof Ct)}},rt);var ht=DEFNODE("ClassProperty","",{$documentation:"A class property for a private property"},dt);var mt=DEFNODE("DefClass",null,{$documentation:"A class definition"},_t);var Et=DEFNODE("ClassExpression",null,{$documentation:"A class expression."},_t);var gt=DEFNODE("Symbol","scope name thedef",{$propdoc:{name:"[string] name of this symbol",scope:"[AST_Scope/S] the current scope (not necessarily the definition scope)",thedef:"[SymbolDef/S] the definition of this symbol"},$documentation:"Base class for all symbols"});var vt=DEFNODE("NewTarget",null,{$documentation:"A reference to new.target"});var bt=DEFNODE("SymbolDeclaration","init",{$documentation:"A declaration symbol (symbol in var/const, function name or argument, symbol in catch)"},gt);var Dt=DEFNODE("SymbolVar",null,{$documentation:"Symbol defining a variable"},bt);var yt=DEFNODE("SymbolBlockDeclaration",null,{$documentation:"Base class for block-scoped declaration symbols"},bt);var St=DEFNODE("SymbolConst",null,{$documentation:"A constant declaration"},yt);var At=DEFNODE("SymbolLet",null,{$documentation:"A block-scoped `let` declaration"},yt);var kt=DEFNODE("SymbolFunarg",null,{$documentation:"Symbol naming a function argument"},Dt);var Tt=DEFNODE("SymbolDefun",null,{$documentation:"Symbol defining a function"},bt);var xt=DEFNODE("SymbolMethod",null,{$documentation:"Symbol in an object defining a method"},gt);var Ct=DEFNODE("SymbolClassProperty",null,{$documentation:"Symbol for a class property"},gt);var Rt=DEFNODE("SymbolLambda",null,{$documentation:"Symbol naming a function expression"},bt);var wt=DEFNODE("SymbolDefClass",null,{$documentation:"Symbol naming a class's name in a class declaration. Lexically scoped to its containing scope, and accessible within the class."},yt);var Ot=DEFNODE("SymbolClass",null,{$documentation:"Symbol naming a class's name. Lexically scoped to the class."},bt);var Ft=DEFNODE("SymbolCatch",null,{$documentation:"Symbol naming the exception in catch"},yt);var Nt=DEFNODE("SymbolImport",null,{$documentation:"Symbol referring to an imported name"},yt);var Mt=DEFNODE("SymbolImportForeign",null,{$documentation:"A symbol imported from a module, but it is defined in the other module, and its real name is irrelevant for this module's purposes"},gt);var It=DEFNODE("Label","references",{$documentation:"Symbol naming a label (declaration)",$propdoc:{references:"[AST_LoopControl*] a list of nodes referring to this label"},initialize:function(){this.references=[];this.thedef=this}},gt);var Pt=DEFNODE("SymbolRef",null,{$documentation:"Reference to some symbol (not definition/declaration)"},gt);var Lt=DEFNODE("SymbolExport",null,{$documentation:"Symbol referring to a name to export"},Pt);var Bt=DEFNODE("SymbolExportForeign",null,{$documentation:"A symbol exported from this module, but it is used in the other module, and its real name is irrelevant for this module's purposes"},gt);var Vt=DEFNODE("LabelRef",null,{$documentation:"Reference to a label symbol"},gt);var Ut=DEFNODE("This",null,{$documentation:"The `this` symbol"},gt);var zt=DEFNODE("Super",null,{$documentation:"The `super` symbol"},Ut);var Kt=DEFNODE("Constant",null,{$documentation:"Base class for all constants",getValue:function(){return this.value}});var Gt=DEFNODE("String","value quote",{$documentation:"A string literal",$propdoc:{value:"[string] the contents of this string",quote:"[string] the original quote character"}},Kt);var Ht=DEFNODE("Number","value raw",{$documentation:"A number literal",$propdoc:{value:"[number] the numeric value",raw:"[string] numeric value as string"}},Kt);var Xt=DEFNODE("BigInt","value",{$documentation:"A big int literal",$propdoc:{value:"[string] big int value"}},Kt);var Wt=DEFNODE("RegExp","value",{$documentation:"A regexp literal",$propdoc:{value:"[RegExp] the actual regexp"}},Kt);var qt=DEFNODE("Atom",null,{$documentation:"Base class for atoms"},Kt);var Yt=DEFNODE("Null",null,{$documentation:"The `null` atom",value:null},qt);var jt=DEFNODE("NaN",null,{$documentation:"The impossible value",value:0/0},qt);var $t=DEFNODE("Undefined",null,{$documentation:"The `undefined` value",value:function(){}()},qt);var Zt=DEFNODE("Hole",null,{$documentation:"A hole in an array",value:function(){}()},qt);var Qt=DEFNODE("Infinity",null,{$documentation:"The `Infinity` value",value:1/0},qt);var Jt=DEFNODE("Boolean",null,{$documentation:"Base class for booleans"},qt);var en=DEFNODE("False",null,{$documentation:"The `false` atom",value:false},Jt);var tn=DEFNODE("True",null,{$documentation:"The `true` atom",value:true},Jt);function walk(e,t,n=[e]){const i=n.push.bind(n);while(n.length){const e=n.pop();const r=t(e,n);if(r){if(r===nn)return true;continue}e._children_backwards(i)}return false}function walk_parent(e,t,n){const i=[e];const r=i.push.bind(i);const a=n?n.slice():[];const o=[];let s;const u={parent:(e=0)=>{if(e===-1){return s}if(n&&e>=a.length){e-=a.length;return n[n.length-(e+1)]}return a[a.length-(1+e)]}};while(i.length){s=i.pop();while(o.length&&i.length==o[o.length-1]){a.pop();o.pop()}const e=t(s,u);if(e){if(e===nn)return true;continue}const n=i.length;s._children_backwards(r);if(i.length>n){a.push(s);o.push(n-1)}}return false}const nn=Symbol("abort walk");class TreeWalker{constructor(e){this.visit=e;this.stack=[];this.directives=Object.create(null)}_visit(e,t){this.push(e);var n=this.visit(e,t?function(){t.call(e)}:noop);if(!n&&t){t.call(e)}this.pop();return n}parent(e){return this.stack[this.stack.length-2-(e||0)]}push(e){if(e instanceof oe){this.directives=Object.create(this.directives)}else if(e instanceof K&&!this.directives[e.value]){this.directives[e.value]=e}else if(e instanceof _t){this.directives=Object.create(this.directives);if(!this.directives["use strict"]){this.directives["use strict"]=e}}this.stack.push(e)}pop(){var e=this.stack.pop();if(e instanceof oe||e instanceof _t){this.directives=Object.getPrototypeOf(this.directives)}}self(){return this.stack[this.stack.length-1]}find_parent(e){var t=this.stack;for(var n=t.length;--n>=0;){var i=t[n];if(i instanceof e)return i}}has_directive(e){var t=this.directives[e];if(t)return t;var n=this.stack[this.stack.length-1];if(n instanceof ie&&n.body){for(var i=0;i=0;){var i=t[n];if(i instanceof Y&&i.label.name==e.label.name)return i.body}else for(var n=t.length;--n>=0;){var i=t[n];if(i instanceof j||e instanceof be&&i instanceof ke)return i}}}class TreeTransformer extends TreeWalker{constructor(e,t){super();this.before=e;this.after=t}}const rn=1;const an=2;const on=4;var sn=Object.freeze({__proto__:null,AST_Accessor:se,AST_Array:nt,AST_Arrow:le,AST_Assign:et,AST_Atom:qt,AST_Await:ye,AST_BigInt:Xt,AST_Binary:Qe,AST_Block:H,AST_BlockStatement:X,AST_Boolean:Jt,AST_Break:be,AST_Call:ze,AST_Case:Ce,AST_Catch:we,AST_Chain:Ye,AST_Class:_t,AST_ClassExpression:Et,AST_ClassPrivateProperty:ht,AST_ClassProperty:dt,AST_ConciseMethod:ft,AST_Conditional:Je,AST_Const:Ie,AST_Constant:Kt,AST_Continue:De,AST_Debugger:z,AST_Default:xe,AST_DefaultAssign:tt,AST_DefClass:mt,AST_Definitions:Fe,AST_Defun:ce,AST_Destructuring:fe,AST_Directive:K,AST_Do:Z,AST_Dot:Xe,AST_DotHash:We,AST_DWLoop:$,AST_EmptyStatement:W,AST_Exit:me,AST_Expansion:ae,AST_Export:Ue,AST_False:en,AST_Finally:Oe,AST_For:J,AST_ForIn:ee,AST_ForOf:te,AST_Function:ue,AST_Hole:Zt,AST_If:Ae,AST_Import:Be,AST_ImportMeta:Ve,AST_Infinity:Qt,AST_IterationStatement:j,AST_Jump:he,AST_Label:It,AST_LabeledStatement:Y,AST_LabelRef:Vt,AST_Lambda:oe,AST_Let:Me,AST_LoopControl:ve,AST_NameMapping:Le,AST_NaN:jt,AST_New:Ke,AST_NewTarget:vt,AST_Node:V,AST_Null:Yt,AST_Number:Ht,AST_Object:it,AST_ObjectGetter:ct,AST_ObjectKeyVal:ot,AST_ObjectProperty:rt,AST_ObjectSetter:lt,AST_PrefixedTemplateString:pe,AST_PrivateGetter:ut,AST_PrivateMethod:pt,AST_PrivateSetter:st,AST_PropAccess:He,AST_RegExp:Wt,AST_Return:Ee,AST_Scope:ie,AST_Sequence:Ge,AST_SimpleStatement:G,AST_Statement:U,AST_StatementWithBody:q,AST_String:Gt,AST_Sub:qe,AST_Super:zt,AST_Switch:ke,AST_SwitchBranch:Te,AST_Symbol:gt,AST_SymbolBlockDeclaration:yt,AST_SymbolCatch:Ft,AST_SymbolClass:Ot,AST_SymbolClassProperty:Ct,AST_SymbolConst:St,AST_SymbolDeclaration:bt,AST_SymbolDefClass:wt,AST_SymbolDefun:Tt,AST_SymbolExport:Lt,AST_SymbolExportForeign:Bt,AST_SymbolFunarg:kt,AST_SymbolImport:Nt,AST_SymbolImportForeign:Mt,AST_SymbolLambda:Rt,AST_SymbolLet:At,AST_SymbolMethod:xt,AST_SymbolRef:Pt,AST_SymbolVar:Dt,AST_TemplateSegment:de,AST_TemplateString:_e,AST_This:Ut,AST_Throw:ge,AST_Token:AST_Token,AST_Toplevel:re,AST_True:tn,AST_Try:Re,AST_Unary:je,AST_UnaryPostfix:Ze,AST_UnaryPrefix:$e,AST_Undefined:$t,AST_Var:Ne,AST_VarDef:Pe,AST_While:Q,AST_With:ne,AST_Yield:Se,TreeTransformer:TreeTransformer,TreeWalker:TreeWalker,walk:walk,walk_abort:nn,walk_body:walk_body,walk_parent:walk_parent,_INLINE:an,_NOINLINE:on,_PURE:rn});function def_transform(e,t){e.DEFMETHOD("transform",(function(e,n){let i=undefined;e.push(this);if(e.before)i=e.before(this,t,n);if(i===undefined){i=this;t(i,e);if(e.after){const t=e.after(i,n);if(t!==undefined)i=t}}e.pop();return i}))}function do_list(e,t){return r(e,(function(e){return e.transform(t,true)}))}def_transform(V,noop);def_transform(Y,(function(e,t){e.label=e.label.transform(t);e.body=e.body.transform(t)}));def_transform(G,(function(e,t){e.body=e.body.transform(t)}));def_transform(H,(function(e,t){e.body=do_list(e.body,t)}));def_transform(Z,(function(e,t){e.body=e.body.transform(t);e.condition=e.condition.transform(t)}));def_transform(Q,(function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t)}));def_transform(J,(function(e,t){if(e.init)e.init=e.init.transform(t);if(e.condition)e.condition=e.condition.transform(t);if(e.step)e.step=e.step.transform(t);e.body=e.body.transform(t)}));def_transform(ee,(function(e,t){e.init=e.init.transform(t);e.object=e.object.transform(t);e.body=e.body.transform(t)}));def_transform(ne,(function(e,t){e.expression=e.expression.transform(t);e.body=e.body.transform(t)}));def_transform(me,(function(e,t){if(e.value)e.value=e.value.transform(t)}));def_transform(ve,(function(e,t){if(e.label)e.label=e.label.transform(t)}));def_transform(Ae,(function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t);if(e.alternative)e.alternative=e.alternative.transform(t)}));def_transform(ke,(function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)}));def_transform(Ce,(function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)}));def_transform(Re,(function(e,t){e.body=do_list(e.body,t);if(e.bcatch)e.bcatch=e.bcatch.transform(t);if(e.bfinally)e.bfinally=e.bfinally.transform(t)}));def_transform(we,(function(e,t){if(e.argname)e.argname=e.argname.transform(t);e.body=do_list(e.body,t)}));def_transform(Fe,(function(e,t){e.definitions=do_list(e.definitions,t)}));def_transform(Pe,(function(e,t){e.name=e.name.transform(t);if(e.value)e.value=e.value.transform(t)}));def_transform(fe,(function(e,t){e.names=do_list(e.names,t)}));def_transform(oe,(function(e,t){if(e.name)e.name=e.name.transform(t);e.argnames=do_list(e.argnames,t);if(e.body instanceof V){e.body=e.body.transform(t)}else{e.body=do_list(e.body,t)}}));def_transform(ze,(function(e,t){e.expression=e.expression.transform(t);e.args=do_list(e.args,t)}));def_transform(Ge,(function(e,t){const n=do_list(e.expressions,t);e.expressions=n.length?n:[new Ht({value:0})]}));def_transform(Xe,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(qe,(function(e,t){e.expression=e.expression.transform(t);e.property=e.property.transform(t)}));def_transform(Ye,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(Se,(function(e,t){if(e.expression)e.expression=e.expression.transform(t)}));def_transform(ye,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(je,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(Qe,(function(e,t){e.left=e.left.transform(t);e.right=e.right.transform(t)}));def_transform(Je,(function(e,t){e.condition=e.condition.transform(t);e.consequent=e.consequent.transform(t);e.alternative=e.alternative.transform(t)}));def_transform(nt,(function(e,t){e.elements=do_list(e.elements,t)}));def_transform(it,(function(e,t){e.properties=do_list(e.properties,t)}));def_transform(rt,(function(e,t){if(e.key instanceof V){e.key=e.key.transform(t)}if(e.value)e.value=e.value.transform(t)}));def_transform(_t,(function(e,t){if(e.name)e.name=e.name.transform(t);if(e.extends)e.extends=e.extends.transform(t);e.properties=do_list(e.properties,t)}));def_transform(ae,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(Le,(function(e,t){e.foreign_name=e.foreign_name.transform(t);e.name=e.name.transform(t)}));def_transform(Be,(function(e,t){if(e.imported_name)e.imported_name=e.imported_name.transform(t);if(e.imported_names)do_list(e.imported_names,t);e.module_name=e.module_name.transform(t)}));def_transform(Ue,(function(e,t){if(e.exported_definition)e.exported_definition=e.exported_definition.transform(t);if(e.exported_value)e.exported_value=e.exported_value.transform(t);if(e.exported_names)do_list(e.exported_names,t);if(e.module_name)e.module_name=e.module_name.transform(t)}));def_transform(_e,(function(e,t){e.segments=do_list(e.segments,t)}));def_transform(pe,(function(e,t){e.prefix=e.prefix.transform(t);e.template_string=e.template_string.transform(t)}));(function(){var normalize_directives=function(e){var t=true;for(var n=0;n1||e.guardedHandlers&&e.guardedHandlers.length){throw new Error("Multiple catch clauses are not supported.")}return new Re({start:my_start_token(e),end:my_end_token(e),body:from_moz(e.block).body,bcatch:from_moz(t[0]),bfinally:e.finalizer?new Oe(from_moz(e.finalizer)):null})},Property:function(e){var t=e.key;var n={start:my_start_token(t||e.value),end:my_end_token(e.value),key:t.type=="Identifier"?t.name:t.value,value:from_moz(e.value)};if(e.computed){n.key=from_moz(e.key)}if(e.method){n.is_generator=e.value.generator;n.async=e.value.async;if(!e.computed){n.key=new xt({name:n.key})}else{n.key=from_moz(e.key)}return new ft(n)}if(e.kind=="init"){if(t.type!="Identifier"&&t.type!="Literal"){n.key=from_moz(t)}return new ot(n)}if(typeof n.key==="string"||typeof n.key==="number"){n.key=new xt({name:n.key})}n.value=new se(n.value);if(e.kind=="get")return new ct(n);if(e.kind=="set")return new lt(n);if(e.kind=="method"){n.async=e.value.async;n.is_generator=e.value.generator;n.quote=e.computed?'"':null;return new ft(n)}},MethodDefinition:function(e){var t={start:my_start_token(e),end:my_end_token(e),key:e.computed?from_moz(e.key):new xt({name:e.key.name||e.key.value}),value:from_moz(e.value),static:e.static};if(e.kind=="get"){return new ct(t)}if(e.kind=="set"){return new lt(t)}t.is_generator=e.value.generator;t.async=e.value.async;return new ft(t)},FieldDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in FieldDefinition");t=from_moz(e.key)}return new dt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},PropertyDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in PropertyDefinition");t=from_moz(e.key)}return new dt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},ArrayExpression:function(e){return new nt({start:my_start_token(e),end:my_end_token(e),elements:e.elements.map((function(e){return e===null?new Zt:from_moz(e)}))})},ObjectExpression:function(e){return new it({start:my_start_token(e),end:my_end_token(e),properties:e.properties.map((function(e){if(e.type==="SpreadElement"){return from_moz(e)}e.type="Property";return from_moz(e)}))})},SequenceExpression:function(e){return new Ge({start:my_start_token(e),end:my_end_token(e),expressions:e.expressions.map(from_moz)})},MemberExpression:function(e){return new(e.computed?qe:Xe)({start:my_start_token(e),end:my_end_token(e),property:e.computed?from_moz(e.property):e.property.name,expression:from_moz(e.object),optional:e.optional||false})},ChainExpression:function(e){return new Ye({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.expression)})},SwitchCase:function(e){return new(e.test?Ce:xe)({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.test),body:e.consequent.map(from_moz)})},VariableDeclaration:function(e){return new(e.kind==="const"?Ie:e.kind==="let"?Me:Ne)({start:my_start_token(e),end:my_end_token(e),definitions:e.declarations.map(from_moz)})},ImportDeclaration:function(e){var t=null;var n=null;e.specifiers.forEach((function(e){if(e.type==="ImportSpecifier"){if(!n){n=[]}n.push(new Le({start:my_start_token(e),end:my_end_token(e),foreign_name:from_moz(e.imported),name:from_moz(e.local)}))}else if(e.type==="ImportDefaultSpecifier"){t=from_moz(e.local)}else if(e.type==="ImportNamespaceSpecifier"){if(!n){n=[]}n.push(new Le({start:my_start_token(e),end:my_end_token(e),foreign_name:new Mt({name:"*"}),name:from_moz(e.local)}))}}));return new Be({start:my_start_token(e),end:my_end_token(e),imported_name:t,imported_names:n,module_name:from_moz(e.source)})},ExportAllDeclaration:function(e){return new Ue({start:my_start_token(e),end:my_end_token(e),exported_names:[new Le({name:new Bt({name:"*"}),foreign_name:new Bt({name:"*"})})],module_name:from_moz(e.source)})},ExportNamedDeclaration:function(e){return new Ue({start:my_start_token(e),end:my_end_token(e),exported_definition:from_moz(e.declaration),exported_names:e.specifiers&&e.specifiers.length?e.specifiers.map((function(e){return new Le({foreign_name:from_moz(e.exported),name:from_moz(e.local)})})):null,module_name:from_moz(e.source)})},ExportDefaultDeclaration:function(e){return new Ue({start:my_start_token(e),end:my_end_token(e),exported_value:from_moz(e.declaration),is_default:true})},Literal:function(e){var t=e.value,n={start:my_start_token(e),end:my_end_token(e)};var i=e.regex;if(i&&i.pattern){n.value={source:i.pattern,flags:i.flags};return new Wt(n)}else if(i){const i=e.raw||t;const r=i.match(/^\/(.*)\/(\w*)$/);if(!r)throw new Error("Invalid regex source "+i);const[a,o,s]=r;n.value={source:o,flags:s};return new Wt(n)}if(t===null)return new Yt(n);switch(typeof t){case"string":n.value=t;return new Gt(n);case"number":n.value=t;n.raw=e.raw||t.toString();return new Ht(n);case"boolean":return new(t?tn:en)(n)}},MetaProperty:function(e){if(e.meta.name==="new"&&e.property.name==="target"){return new vt({start:my_start_token(e),end:my_end_token(e)})}else if(e.meta.name==="import"&&e.property.name==="meta"){return new Ve({start:my_start_token(e),end:my_end_token(e)})}},Identifier:function(e){var n=t[t.length-2];return new(n.type=="LabeledStatement"?It:n.type=="VariableDeclarator"&&n.id===e?n.kind=="const"?St:n.kind=="let"?At:Dt:/Import.*Specifier/.test(n.type)?n.local===e?Nt:Mt:n.type=="ExportSpecifier"?n.local===e?Lt:Bt:n.type=="FunctionExpression"?n.id===e?Rt:kt:n.type=="FunctionDeclaration"?n.id===e?Tt:kt:n.type=="ArrowFunctionExpression"?n.params.includes(e)?kt:Pt:n.type=="ClassExpression"?n.id===e?Ot:Pt:n.type=="Property"?n.key===e&&n.computed||n.value===e?Pt:xt:n.type=="PropertyDefinition"||n.type==="FieldDefinition"?n.key===e&&n.computed||n.value===e?Pt:Ct:n.type=="ClassDeclaration"?n.id===e?wt:Pt:n.type=="MethodDefinition"?n.computed?Pt:xt:n.type=="CatchClause"?Ft:n.type=="BreakStatement"||n.type=="ContinueStatement"?Vt:Pt)({start:my_start_token(e),end:my_end_token(e),name:e.name})},BigIntLiteral(e){return new Xt({start:my_start_token(e),end:my_end_token(e),value:e.value})}};e.UpdateExpression=e.UnaryExpression=function To_Moz_Unary(e){var t="prefix"in e?e.prefix:e.type=="UnaryExpression"?true:false;return new(t?$e:Ze)({start:my_start_token(e),end:my_end_token(e),operator:e.operator,expression:from_moz(e.argument)})};e.ClassDeclaration=e.ClassExpression=function From_Moz_Class(e){return new(e.type==="ClassDeclaration"?mt:Et)({start:my_start_token(e),end:my_end_token(e),name:from_moz(e.id),extends:from_moz(e.superClass),properties:e.body.body.map(from_moz)})};map("EmptyStatement",W);map("BlockStatement",X,"body@body");map("IfStatement",Ae,"test>condition, consequent>body, alternate>alternative");map("LabeledStatement",Y,"label>label, body>body");map("BreakStatement",be,"label>label");map("ContinueStatement",De,"label>label");map("WithStatement",ne,"object>expression, body>body");map("SwitchStatement",ke,"discriminant>expression, cases@body");map("ReturnStatement",Ee,"argument>value");map("ThrowStatement",ge,"argument>value");map("WhileStatement",Q,"test>condition, body>body");map("DoWhileStatement",Z,"test>condition, body>body");map("ForStatement",J,"init>init, test>condition, update>step, body>body");map("ForInStatement",ee,"left>init, right>object, body>body");map("ForOfStatement",te,"left>init, right>object, body>body, await=await");map("AwaitExpression",ye,"argument>expression");map("YieldExpression",Se,"argument>expression, delegate=is_star");map("DebuggerStatement",z);map("VariableDeclarator",Pe,"id>name, init>value");map("CatchClause",we,"param>argname, body%body");map("ThisExpression",Ut);map("Super",zt);map("BinaryExpression",Qe,"operator=operator, left>left, right>right");map("LogicalExpression",Qe,"operator=operator, left>left, right>right");map("AssignmentExpression",et,"operator=operator, left>left, right>right");map("ConditionalExpression",Je,"test>condition, consequent>consequent, alternate>alternative");map("NewExpression",Ke,"callee>expression, arguments@args");map("CallExpression",ze,"callee>expression, optional=optional, arguments@args");def_to_moz(re,(function To_Moz_Program(e){return to_moz_scope("Program",e)}));def_to_moz(ae,(function To_Moz_Spread(e){return{type:to_moz_in_destructuring()?"RestElement":"SpreadElement",argument:to_moz(e.expression)}}));def_to_moz(pe,(function To_Moz_TaggedTemplateExpression(e){return{type:"TaggedTemplateExpression",tag:to_moz(e.prefix),quasi:to_moz(e.template_string)}}));def_to_moz(_e,(function To_Moz_TemplateLiteral(e){var t=[];var n=[];for(var i=0;i({type:"BigIntLiteral",value:e.value})));Jt.DEFMETHOD("to_mozilla_ast",Kt.prototype.to_mozilla_ast);Yt.DEFMETHOD("to_mozilla_ast",Kt.prototype.to_mozilla_ast);Zt.DEFMETHOD("to_mozilla_ast",(function To_Moz_ArrayHole(){return null}));H.DEFMETHOD("to_mozilla_ast",X.prototype.to_mozilla_ast);oe.DEFMETHOD("to_mozilla_ast",ue.prototype.to_mozilla_ast);function my_start_token(e){var t=e.loc,n=t&&t.start;var i=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,i?i[0]:e.start,false,[],[],t&&t.source)}function my_end_token(e){var t=e.loc,n=t&&t.end;var i=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,i?i[0]:e.end,false,[],[],t&&t.source)}function map(t,n,i){var r="function From_Moz_"+t+"(M){\n";r+="return new U2."+n.name+"({\n"+"start: my_start_token(M),\n"+"end: my_end_token(M)";var a="function To_Moz_"+t+"(M){\n";a+="return {\n"+"type: "+JSON.stringify(t);if(i)i.split(/\s*,\s*/).forEach((function(e){var t=/([a-z0-9$_]+)([=@>%])([a-z0-9$_]+)/i.exec(e);if(!t)throw new Error("Can't understand property map: "+e);var n=t[1],i=t[2],o=t[3];r+=",\n"+o+": ";a+=",\n"+n+": ";switch(i){case"@":r+="M."+n+".map(from_moz)";a+="M."+o+".map(to_moz)";break;case">":r+="from_moz(M."+n+")";a+="to_moz(M."+o+")";break;case"=":r+="M."+n;a+="M."+o;break;case"%":r+="from_moz(M."+n+").body";a+="to_moz_block(M)";break;default:throw new Error("Can't understand operator in propmap: "+e)}}));r+="\n})\n}";a+="\n}\n}";r=new Function("U2","my_start_token","my_end_token","from_moz","return("+r+")")(sn,my_start_token,my_end_token,from_moz);a=new Function("to_moz","to_moz_block","to_moz_scope","return("+a+")")(to_moz,to_moz_block,to_moz_scope);e[t]=r;def_to_moz(n,a)}var t=null;function from_moz(n){t.push(n);var i=n!=null?e[n.type](n):null;t.pop();return i}V.from_mozilla_ast=function(e){var n=t;t=[];var i=from_moz(e);t=n;return i};function set_moz_loc(e,t){var n=e.start;var i=e.end;if(!(n&&i)){return t}if(n.pos!=null&&i.endpos!=null){t.range=[n.pos,i.endpos]}if(n.line){t.loc={start:{line:n.line,column:n.col},end:i.endline?{line:i.endline,column:i.endcol}:null};if(n.file){t.loc.source=n.file}}return t}function def_to_moz(e,t){e.DEFMETHOD("to_mozilla_ast",(function(e){return set_moz_loc(this,t(this,e))}))}var n=null;function to_moz(e){if(n===null){n=[]}n.push(e);var t=e!=null?e.to_mozilla_ast(n[n.length-2]):null;n.pop();if(n.length===0){n=null}return t}function to_moz_in_destructuring(){var e=n.length;while(e--){if(n[e]instanceof fe){return true}}return false}function to_moz_block(e){return{type:"BlockStatement",body:e.body.map(to_moz)}}function to_moz_scope(e,t){var n=t.body.map(to_moz);if(t.body[0]instanceof G&&t.body[0].body instanceof Gt){n.unshift(to_moz(new W(t.body[0])))}return{type:e,body:n}}})();function first_in_statement(e){let t=e.parent(-1);for(let n=0,i;i=e.parent(n);n++){if(i instanceof U&&i.body===t)return true;if(i instanceof Ge&&i.expressions[0]===t||i.TYPE==="Call"&&i.expression===t||i instanceof pe&&i.prefix===t||i instanceof Xe&&i.expression===t||i instanceof qe&&i.expression===t||i instanceof Je&&i.condition===t||i instanceof Qe&&i.left===t||i instanceof Ze&&i.expression===t){t=i}else{return false}}}function left_is_object(e){if(e instanceof it)return true;if(e instanceof Ge)return left_is_object(e.expressions[0]);if(e.TYPE==="Call")return left_is_object(e.expression);if(e instanceof pe)return left_is_object(e.prefix);if(e instanceof Xe||e instanceof qe)return left_is_object(e.expression);if(e instanceof Je)return left_is_object(e.condition);if(e instanceof Qe)return left_is_object(e.left);if(e instanceof Ze)return left_is_object(e.expression);return false}const un=/^$|[;{][\s\n]*$/;const ln=10;const cn=32;const pn=/[@#]__(PURE|INLINE|NOINLINE)__/g;function is_some_comments(e){return(e.type==="comment2"||e.type==="comment1")&&/@preserve|@lic|@cc_on|^\**!/i.test(e.value)}function OutputStream(e){var t=!e;e=defaults(e,{ascii_only:false,beautify:false,braces:false,comments:"some",ecma:5,ie8:false,indent_level:4,indent_start:0,inline_script:true,keep_numbers:false,keep_quoted_props:false,max_line_len:false,preamble:null,preserve_annotations:false,quote_keys:false,quote_style:0,safari10:false,semicolons:true,shebang:true,shorthand:undefined,source_map:null,webkit:false,width:80,wrap_iife:false,wrap_func_args:true},true);if(e.shorthand===undefined)e.shorthand=e.ecma>5;var n=return_false;if(e.comments){let t=e.comments;if(typeof e.comments==="string"&&/^\/.*\/[a-zA-Z]*$/.test(e.comments)){var i=e.comments.lastIndexOf("/");t=new RegExp(e.comments.substr(1,i-1),e.comments.substr(i+1))}if(t instanceof RegExp){n=function(e){return e.type!="comment5"&&t.test(e.value)}}else if(typeof t==="function"){n=function(e){return e.type!="comment5"&&t(this,e)}}else if(t==="some"){n=is_some_comments}else{n=return_true}}var r=0;var a=0;var o=1;var s=0;var u="";let l=new Set;var c=e.ascii_only?function(t,n){if(e.ecma>=2015&&!e.safari10){t=t.replace(/[\ud800-\udbff][\udc00-\udfff]/g,(function(e){var t=get_full_char_code(e,0).toString(16);return"\\u{"+t+"}"}))}return t.replace(/[\u0000-\u001f\u007f-\uffff]/g,(function(e){var t=e.charCodeAt(0).toString(16);if(t.length<=2&&!n){while(t.length<2)t="0"+t;return"\\x"+t}else{while(t.length<4)t="0"+t;return"\\u"+t}}))}:function(e){return e.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g,(function(e,t){if(t){return"\\u"+t.charCodeAt(0).toString(16)}return e}))};function make_string(t,n){var i=0,r=0;t=t.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,(function(n,a){switch(n){case'"':++i;return'"';case"'":++r;return"'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\t":return"\\t";case"\b":return"\\b";case"\f":return"\\f";case"\v":return e.ie8?"\\x0B":"\\v";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";case"\ufeff":return"\\ufeff";case"\0":return/[0-9]/.test(get_full_char(t,a+1))?"\\x00":"\\0"}return n}));function quote_single(){return"'"+t.replace(/\x27/g,"\\'")+"'"}function quote_double(){return'"'+t.replace(/\x22/g,'\\"')+'"'}function quote_template(){return"`"+t.replace(/`/g,"\\`")+"`"}t=c(t);if(n==="`")return quote_template();switch(e.quote_style){case 1:return quote_single();case 2:return quote_double();case 3:return n=="'"?quote_single():quote_double();default:return i>r?quote_single():quote_double()}}function encode_string(t,n){var i=make_string(t,n);if(e.inline_script){i=i.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi,"<\\/$1$2");i=i.replace(/\x3c!--/g,"\\x3c!--");i=i.replace(/--\x3e/g,"--\\x3e")}return i}function make_name(e){e=e.toString();e=c(e,true);return e}function make_indent(t){return" ".repeat(e.indent_start+r-t*e.indent_level)}var f=false;var p=false;var _=false;var d=0;var h=false;var m=false;var E=-1;var g="";var v,b,D=e.source_map&&[];var y=D?function(){D.forEach((function(t){try{let n=!t.name&&t.token.type=="name"?t.token.value:t.name;if(n instanceof gt){n=n.name}e.source_map.add(t.token.file,t.line,t.col,t.token.line,t.token.col,is_basic_identifier_string(n)?n:undefined)}catch(e){}}));D=[]}:noop;var S=e.max_line_len?function(){if(a>e.max_line_len){if(d){var t=u.slice(0,d);var n=u.slice(d);if(D){var i=n.length-a;D.forEach((function(e){e.line++;e.col+=i}))}u=t+"\n"+n;o++;s++;a=n.length}}if(d){d=0;y()}}:noop;var A=makePredicate("( [ + * / - , . `");function print(t){t=String(t);var n=get_full_char(t,0);if(h&&n){h=false;if(n!=="\n"){print("\n");T()}}if(m&&n){m=false;if(!/[\s;})]/.test(n)){k()}}E=-1;var i=g.charAt(g.length-1);if(_){_=false;if(i===":"&&n==="}"||(!n||!";}".includes(n))&&i!==";"){if(e.semicolons||A.has(n)){u+=";";a++;s++}else{S();if(a>0){u+="\n";s++;o++;a=0}if(/^\s+$/.test(t)){_=true}}if(!e.beautify)p=false}}if(p){if(is_identifier_char(i)&&(is_identifier_char(n)||n=="\\")||n=="/"&&n==i||(n=="+"||n=="-")&&n==g){u+=" ";a++;s++}p=false}if(v){D.push({token:v,name:b,line:o,col:a});v=false;if(!d)y()}u+=t;f=t[t.length-1]=="(";s+=t.length;var r=t.split(/\r?\n/),l=r.length-1;o+=l;a+=r[0].length;if(l>0){S();a=r[l].length}g=t}var star=function(){print("*")};var k=e.beautify?function(){print(" ")}:function(){p=true};var T=e.beautify?function(t){if(e.beautify){print(make_indent(t?.5:0))}}:noop;var x=e.beautify?function(e,t){if(e===true)e=next_indent();var n=r;r=e;var i=t();r=n;return i}:function(e,t){return t()};var C=e.beautify?function(){if(E<0)return print("\n");if(u[E]!="\n"){u=u.slice(0,E)+"\n"+u.slice(E);s++;o++}E++}:e.max_line_len?function(){S();d=u.length}:noop;var R=e.beautify?function(){print(";")}:function(){_=true};function force_semicolon(){_=false;print(";")}function next_indent(){return r+e.indent_level}function with_block(e){var t;print("{");C();x(next_indent(),(function(){t=e()}));T();print("}");return t}function with_parens(e){print("(");var t=e();print(")");return t}function with_square(e){print("[");var t=e();print("]");return t}function comma(){print(",");k()}function colon(){print(":");k()}var w=D?function(e,t){v=e;b=t}:noop;function get(){if(d){S()}return u}function has_nlb(){let e=u.length-1;while(e>=0){const t=u.charCodeAt(e);if(t===ln){return true}if(t!==cn){return false}e--}return true}function filter_comment(t){if(!e.preserve_annotations){t=t.replace(pn," ")}if(/^\s*$/.test(t)){return""}return t.replace(/(<\s*\/\s*)(script)/i,"<\\/$2")}function prepend_comments(t){var i=this;var r=t.start;if(!r)return;var a=i.printed_comments;const o=t instanceof me&&t.value;if(r.comments_before&&a.has(r.comments_before)){if(o){r.comments_before=[]}else{return}}var u=r.comments_before;if(!u){u=r.comments_before=[]}a.add(u);if(o){var l=new TreeWalker((function(e){var t=l.parent();if(t instanceof me||t instanceof Qe&&t.left===e||t.TYPE=="Call"&&t.expression===e||t instanceof Je&&t.condition===e||t instanceof Xe&&t.expression===e||t instanceof Ge&&t.expressions[0]===e||t instanceof qe&&t.expression===e||t instanceof Ze){if(!e.start)return;var n=e.start.comments_before;if(n&&!a.has(n)){a.add(n);u=u.concat(n)}}else{return true}}));l.push(t);t.value.walk(l)}if(s==0){if(u.length>0&&e.shebang&&u[0].type==="comment5"&&!a.has(u[0])){print("#!"+u.shift().value+"\n");T()}var c=e.preamble;if(c){print(c.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g,"\n"))}}u=u.filter(n,t).filter((e=>!a.has(e)));if(u.length==0)return;var f=has_nlb();u.forEach((function(e,t){a.add(e);if(!f){if(e.nlb){print("\n");T();f=true}else if(t>0){k()}}if(/comment[134]/.test(e.type)){var n=filter_comment(e.value);if(n){print("//"+n+"\n");T()}f=true}else if(e.type=="comment2"){var n=filter_comment(e.value);if(n){print("/*"+n+"*/")}f=false}}));if(!f){if(r.nlb){print("\n");T()}else{k()}}}function append_comments(e,t){var i=this;var r=e.end;if(!r)return;var a=i.printed_comments;var o=r[t?"comments_before":"comments_after"];if(!o||a.has(o))return;if(!(e instanceof U||o.every((e=>!/comment[134]/.test(e.type)))))return;a.add(o);var s=u.length;o.filter(n,e).forEach((function(e,n){if(a.has(e))return;a.add(e);m=false;if(h){print("\n");T();h=false}else if(e.nlb&&(n>0||!has_nlb())){print("\n");T()}else if(n>0||!t){k()}if(/comment[134]/.test(e.type)){const t=filter_comment(e.value);if(t){print("//"+t)}h=true}else if(e.type=="comment2"){const t=filter_comment(e.value);if(t){print("/*"+t+"*/")}m=true}}));if(u.length>s)E=s}var O=[];return{get:get,toString:get,indent:T,in_directive:false,use_asm:null,active_scope:null,indentation:function(){return r},current_width:function(){return a-r},should_break:function(){return e.width&&this.current_width()>=e.width},has_parens:function(){return f},newline:C,print:print,star:star,space:k,comma:comma,colon:colon,last:function(){return g},semicolon:R,force_semicolon:force_semicolon,to_utf8:c,print_name:function(e){print(make_name(e))},print_string:function(e,t,n){var i=encode_string(e,t);if(n===true&&!i.includes("\\")){if(!un.test(u)){force_semicolon()}force_semicolon()}print(i)},print_template_string_chars:function(e){var t=encode_string(e,"`").replace(/\${/g,"\\${");return print(t.substr(1,t.length-2))},encode_string:encode_string,next_indent:next_indent,with_indent:x,with_block:with_block,with_parens:with_parens,with_square:with_square,add_mapping:w,option:function(t){return e[t]},printed_comments:l,prepend_comments:t?noop:prepend_comments,append_comments:t||n===return_false?noop:append_comments,line:function(){return o},col:function(){return a},pos:function(){return s},push_node:function(e){O.push(e)},pop_node:function(){return O.pop()},parent:function(e){return O[O.length-2-(e||0)]}}}(function(){function DEFPRINT(e,t){e.DEFMETHOD("_codegen",t)}V.DEFMETHOD("print",(function(e,t){var n=this,i=n._codegen;if(n instanceof ie){e.active_scope=n}else if(!e.use_asm&&n instanceof K&&n.value=="use asm"){e.use_asm=e.active_scope}function doit(){e.prepend_comments(n);n.add_source_map(e);i(n,e);e.append_comments(n)}e.push_node(n);if(t||n.needs_parens(e)){e.with_parens(doit)}else{doit()}e.pop_node();if(n===e.use_asm){e.use_asm=null}}));V.DEFMETHOD("_print",V.prototype.print);V.DEFMETHOD("print_to_string",(function(e){var t=OutputStream(e);this.print(t);return t.get()}));function PARENS(e,t){if(Array.isArray(e)){e.forEach((function(e){PARENS(e,t)}))}else{e.DEFMETHOD("needs_parens",t)}}PARENS(V,return_false);PARENS(ue,(function(e){if(!e.has_parens()&&first_in_statement(e)){return true}if(e.option("webkit")){var t=e.parent();if(t instanceof He&&t.expression===this){return true}}if(e.option("wrap_iife")){var t=e.parent();if(t instanceof ze&&t.expression===this){return true}}if(e.option("wrap_func_args")){var t=e.parent();if(t instanceof ze&&t.args.includes(this)){return true}}return false}));PARENS(le,(function(e){var t=e.parent();if(e.option("wrap_func_args")&&t instanceof ze&&t.args.includes(this)){return true}return t instanceof He&&t.expression===this}));PARENS(it,(function(e){return!e.has_parens()&&first_in_statement(e)}));PARENS(Et,first_in_statement);PARENS(je,(function(e){var t=e.parent();return t instanceof He&&t.expression===this||t instanceof ze&&t.expression===this||t instanceof Qe&&t.operator==="**"&&this instanceof $e&&t.left===this&&this.operator!=="++"&&this.operator!=="--"}));PARENS(ye,(function(e){var t=e.parent();return t instanceof He&&t.expression===this||t instanceof ze&&t.expression===this||t instanceof Qe&&t.operator==="**"&&t.left===this||e.option("safari10")&&t instanceof $e}));PARENS(Ge,(function(e){var t=e.parent();return t instanceof ze||t instanceof je||t instanceof Qe||t instanceof Pe||t instanceof He||t instanceof nt||t instanceof rt||t instanceof Je||t instanceof le||t instanceof tt||t instanceof ae||t instanceof te&&this===t.object||t instanceof Se||t instanceof Ue}));PARENS(Qe,(function(e){var t=e.parent();if(t instanceof ze&&t.expression===this)return true;if(t instanceof je)return true;if(t instanceof He&&t.expression===this)return true;if(t instanceof Qe){const e=t.operator;const n=this.operator;if(n==="??"&&(e==="||"||e==="&&")){return true}if(e==="??"&&(n==="||"||n==="&&")){return true}const i=M[e];const r=M[n];if(i>r||i==r&&(this===t.right||e=="**")){return true}}}));PARENS(Se,(function(e){var t=e.parent();if(t instanceof Qe&&t.operator!=="=")return true;if(t instanceof ze&&t.expression===this)return true;if(t instanceof Je&&t.condition===this)return true;if(t instanceof je)return true;if(t instanceof He&&t.expression===this)return true}));PARENS(He,(function(e){var t=e.parent();if(t instanceof Ke&&t.expression===this){return walk(this,(e=>{if(e instanceof ie)return true;if(e instanceof ze){return nn}}))}}));PARENS(ze,(function(e){var t=e.parent(),n;if(t instanceof Ke&&t.expression===this||t instanceof Ue&&t.is_default&&this.expression instanceof ue)return true;return this.expression instanceof ue&&t instanceof He&&t.expression===this&&(n=e.parent(1))instanceof et&&n.left===t}));PARENS(Ke,(function(e){var t=e.parent();if(this.args.length===0&&(t instanceof He||t instanceof ze&&t.expression===this))return true}));PARENS(Ht,(function(e){var t=e.parent();if(t instanceof He&&t.expression===this){var n=this.getValue();if(n<0||/^0/.test(make_num(n))){return true}}}));PARENS(Xt,(function(e){var t=e.parent();if(t instanceof He&&t.expression===this){var n=this.getValue();if(n.startsWith("-")){return true}}}));PARENS([et,Je],(function(e){var t=e.parent();if(t instanceof je)return true;if(t instanceof Qe&&!(t instanceof et))return true;if(t instanceof ze&&t.expression===this)return true;if(t instanceof Je&&t.condition===this)return true;if(t instanceof He&&t.expression===this)return true;if(this instanceof et&&this.left instanceof fe&&this.left.is_array===false)return true}));DEFPRINT(K,(function(e,t){t.print_string(e.value,e.quote);t.semicolon()}));DEFPRINT(ae,(function(e,t){t.print("...");e.expression.print(t)}));DEFPRINT(fe,(function(e,t){t.print(e.is_array?"[":"{");var n=e.names.length;e.names.forEach((function(e,i){if(i>0)t.comma();e.print(t);if(i==n-1&&e instanceof Zt)t.comma()}));t.print(e.is_array?"]":"}")}));DEFPRINT(z,(function(e,t){t.print("debugger");t.semicolon()}));function display_body(e,t,n,i){var r=e.length-1;n.in_directive=i;e.forEach((function(e,i){if(n.in_directive===true&&!(e instanceof K||e instanceof W||e instanceof G&&e.body instanceof Gt)){n.in_directive=false}if(!(e instanceof W)){n.indent();e.print(n);if(!(i==r&&t)){n.newline();if(t)n.newline()}}if(n.in_directive===true&&e instanceof G&&e.body instanceof Gt){n.in_directive=false}}));n.in_directive=false}q.DEFMETHOD("_do_print_body",(function(e){force_statement(this.body,e)}));DEFPRINT(U,(function(e,t){e.body.print(t);t.semicolon()}));DEFPRINT(re,(function(e,t){display_body(e.body,true,t,true);t.print("")}));DEFPRINT(Y,(function(e,t){e.label.print(t);t.colon();e.body.print(t)}));DEFPRINT(G,(function(e,t){e.body.print(t);t.semicolon()}));function print_braced_empty(e,t){t.print("{");t.with_indent(t.next_indent(),(function(){t.append_comments(e,true)}));t.print("}")}function print_braced(e,t,n){if(e.body.length>0){t.with_block((function(){display_body(e.body,false,t,n)}))}else print_braced_empty(e,t)}DEFPRINT(X,(function(e,t){print_braced(e,t)}));DEFPRINT(W,(function(e,t){t.semicolon()}));DEFPRINT(Z,(function(e,t){t.print("do");t.space();make_block(e.body,t);t.space();t.print("while");t.space();t.with_parens((function(){e.condition.print(t)}));t.semicolon()}));DEFPRINT(Q,(function(e,t){t.print("while");t.space();t.with_parens((function(){e.condition.print(t)}));t.space();e._do_print_body(t)}));DEFPRINT(J,(function(e,t){t.print("for");t.space();t.with_parens((function(){if(e.init){if(e.init instanceof Fe){e.init.print(t)}else{parenthesize_for_noin(e.init,t,true)}t.print(";");t.space()}else{t.print(";")}if(e.condition){e.condition.print(t);t.print(";");t.space()}else{t.print(";")}if(e.step){e.step.print(t)}}));t.space();e._do_print_body(t)}));DEFPRINT(ee,(function(e,t){t.print("for");if(e.await){t.space();t.print("await")}t.space();t.with_parens((function(){e.init.print(t);t.space();t.print(e instanceof te?"of":"in");t.space();e.object.print(t)}));t.space();e._do_print_body(t)}));DEFPRINT(ne,(function(e,t){t.print("with");t.space();t.with_parens((function(){e.expression.print(t)}));t.space();e._do_print_body(t)}));oe.DEFMETHOD("_do_print",(function(e,t){var n=this;if(!t){if(n.async){e.print("async");e.space()}e.print("function");if(n.is_generator){e.star()}if(n.name){e.space()}}if(n.name instanceof gt){n.name.print(e)}else if(t&&n.name instanceof V){e.with_square((function(){n.name.print(e)}))}e.with_parens((function(){n.argnames.forEach((function(t,n){if(n)e.comma();t.print(e)}))}));e.space();print_braced(n,e,true)}));DEFPRINT(oe,(function(e,t){e._do_print(t)}));DEFPRINT(pe,(function(e,t){var n=e.prefix;var i=n instanceof oe||n instanceof Qe||n instanceof Je||n instanceof Ge||n instanceof je||n instanceof Xe&&n.expression instanceof it;if(i)t.print("(");e.prefix.print(t);if(i)t.print(")");e.template_string.print(t)}));DEFPRINT(_e,(function(e,t){var n=t.parent()instanceof pe;t.print("`");for(var i=0;i");e.space();const r=t.body[0];if(t.body.length===1&&r instanceof Ee){const t=r.value;if(!t){e.print("{}")}else if(left_is_object(t)){e.print("(");t.print(e);e.print(")")}else{t.print(e)}}else{print_braced(t,e)}if(i){e.print(")")}}));me.DEFMETHOD("_do_print",(function(e,t){e.print(t);if(this.value){e.space();const t=this.value.start.comments_before;if(t&&t.length&&!e.printed_comments.has(t)){e.print("(");this.value.print(e);e.print(")")}else{this.value.print(e)}}e.semicolon()}));DEFPRINT(Ee,(function(e,t){e._do_print(t,"return")}));DEFPRINT(ge,(function(e,t){e._do_print(t,"throw")}));DEFPRINT(Se,(function(e,t){var n=e.is_star?"*":"";t.print("yield"+n);if(e.expression){t.space();e.expression.print(t)}}));DEFPRINT(ye,(function(e,t){t.print("await");t.space();var n=e.expression;var i=!(n instanceof ze||n instanceof Pt||n instanceof He||n instanceof je||n instanceof Kt||n instanceof ye||n instanceof it);if(i)t.print("(");e.expression.print(t);if(i)t.print(")")}));ve.DEFMETHOD("_do_print",(function(e,t){e.print(t);if(this.label){e.space();this.label.print(e)}e.semicolon()}));DEFPRINT(be,(function(e,t){e._do_print(t,"break")}));DEFPRINT(De,(function(e,t){e._do_print(t,"continue")}));function make_then(e,t){var n=e.body;if(t.option("braces")||t.option("ie8")&&n instanceof Z)return make_block(n,t);if(!n)return t.force_semicolon();while(true){if(n instanceof Ae){if(!n.alternative){make_block(e.body,t);return}n=n.alternative}else if(n instanceof q){n=n.body}else break}force_statement(e.body,t)}DEFPRINT(Ae,(function(e,t){t.print("if");t.space();t.with_parens((function(){e.condition.print(t)}));t.space();if(e.alternative){make_then(e,t);t.space();t.print("else");t.space();if(e.alternative instanceof Ae)e.alternative.print(t);else force_statement(e.alternative,t)}else{e._do_print_body(t)}}));DEFPRINT(ke,(function(e,t){t.print("switch");t.space();t.with_parens((function(){e.expression.print(t)}));t.space();var n=e.body.length-1;if(n<0)print_braced_empty(e,t);else t.with_block((function(){e.body.forEach((function(e,i){t.indent(true);e.print(t);if(i0)t.newline()}))}))}));Te.DEFMETHOD("_do_print_body",(function(e){e.newline();this.body.forEach((function(t){e.indent();t.print(e);e.newline()}))}));DEFPRINT(xe,(function(e,t){t.print("default:");e._do_print_body(t)}));DEFPRINT(Ce,(function(e,t){t.print("case");t.space();e.expression.print(t);t.print(":");e._do_print_body(t)}));DEFPRINT(Re,(function(e,t){t.print("try");t.space();print_braced(e,t);if(e.bcatch){t.space();e.bcatch.print(t)}if(e.bfinally){t.space();e.bfinally.print(t)}}));DEFPRINT(we,(function(e,t){t.print("catch");if(e.argname){t.space();t.with_parens((function(){e.argname.print(t)}))}t.space();print_braced(e,t)}));DEFPRINT(Oe,(function(e,t){t.print("finally");t.space();print_braced(e,t)}));Fe.DEFMETHOD("_do_print",(function(e,t){e.print(t);e.space();this.definitions.forEach((function(t,n){if(n)e.comma();t.print(e)}));var n=e.parent();var i=n instanceof J||n instanceof ee;var r=!i||n&&n.init!==this;if(r)e.semicolon()}));DEFPRINT(Me,(function(e,t){e._do_print(t,"let")}));DEFPRINT(Ne,(function(e,t){e._do_print(t,"var")}));DEFPRINT(Ie,(function(e,t){e._do_print(t,"const")}));DEFPRINT(Be,(function(e,t){t.print("import");t.space();if(e.imported_name){e.imported_name.print(t)}if(e.imported_name&&e.imported_names){t.print(",");t.space()}if(e.imported_names){if(e.imported_names.length===1&&e.imported_names[0].foreign_name.name==="*"){e.imported_names[0].print(t)}else{t.print("{");e.imported_names.forEach((function(n,i){t.space();n.print(t);if(i{if(e instanceof ie)return true;if(e instanceof Qe&&e.operator=="in"){return nn}}))}e.print(t,i)}DEFPRINT(Pe,(function(e,t){e.name.print(t);if(e.value){t.space();t.print("=");t.space();var n=t.parent(1);var i=n instanceof J||n instanceof ee;parenthesize_for_noin(e.value,t,i)}}));DEFPRINT(ze,(function(e,t){e.expression.print(t);if(e instanceof Ke&&e.args.length===0)return;if(e.expression instanceof ze||e.expression instanceof oe){t.add_mapping(e.start)}if(e.optional)t.print("?.");t.with_parens((function(){e.args.forEach((function(e,n){if(n)t.comma();e.print(t)}))}))}));DEFPRINT(Ke,(function(e,t){t.print("new");t.space();ze.prototype._codegen(e,t)}));Ge.DEFMETHOD("_do_print",(function(e){this.expressions.forEach((function(t,n){if(n>0){e.comma();if(e.should_break()){e.newline();e.indent()}}t.print(e)}))}));DEFPRINT(Ge,(function(e,t){e._do_print(t)}));DEFPRINT(Xe,(function(e,t){var n=e.expression;n.print(t);var i=e.property;var r=f.has(i)?t.option("ie8"):!is_identifier_string(i,t.option("ecma")>=2015||t.option("safari10"));if(e.optional)t.print("?.");if(r){t.print("[");t.add_mapping(e.end);t.print_string(i);t.print("]")}else{if(n instanceof Ht&&n.getValue()>=0){if(!/[xa-f.)]/i.test(t.last())){t.print(".")}}if(!e.optional)t.print(".");t.add_mapping(e.end);t.print_name(i)}}));DEFPRINT(We,(function(e,t){var n=e.expression;n.print(t);var i=e.property;if(e.optional)t.print("?");t.print(".#");t.print_name(i)}));DEFPRINT(qe,(function(e,t){e.expression.print(t);if(e.optional)t.print("?.");t.print("[");e.property.print(t);t.print("]")}));DEFPRINT(Ye,(function(e,t){e.expression.print(t)}));DEFPRINT($e,(function(e,t){var n=e.operator;t.print(n);if(/^[a-z]/i.test(n)||/[+-]$/.test(n)&&e.expression instanceof $e&&/^[+-]/.test(e.expression.operator)){t.space()}e.expression.print(t)}));DEFPRINT(Ze,(function(e,t){e.expression.print(t);t.print(e.operator)}));DEFPRINT(Qe,(function(e,t){var n=e.operator;e.left.print(t);if(n[0]==">"&&e.left instanceof Ze&&e.left.operator=="--"){t.print(" ")}else{t.space()}t.print(n);if((n=="<"||n=="<<")&&e.right instanceof $e&&e.right.operator=="!"&&e.right.expression instanceof $e&&e.right.expression.operator=="--"){t.print(" ")}else{t.space()}e.right.print(t)}));DEFPRINT(Je,(function(e,t){e.condition.print(t);t.space();t.print("?");t.space();e.consequent.print(t);t.space();t.colon();e.alternative.print(t)}));DEFPRINT(nt,(function(e,t){t.with_square((function(){var n=e.elements,i=n.length;if(i>0)t.space();n.forEach((function(e,n){if(n)t.comma();e.print(t);if(n===i-1&&e instanceof Zt)t.comma()}));if(i>0)t.space()}))}));DEFPRINT(it,(function(e,t){if(e.properties.length>0)t.with_block((function(){e.properties.forEach((function(e,n){if(n){t.print(",");t.newline()}t.indent();e.print(t)}));t.newline()}));else print_braced_empty(e,t)}));DEFPRINT(_t,(function(e,t){t.print("class");t.space();if(e.name){e.name.print(t);t.space()}if(e.extends){var n=!(e.extends instanceof Pt)&&!(e.extends instanceof He)&&!(e.extends instanceof Et)&&!(e.extends instanceof ue);t.print("extends");if(n){t.print("(")}else{t.space()}e.extends.print(t);if(n){t.print(")")}else{t.space()}}if(e.properties.length>0)t.with_block((function(){e.properties.forEach((function(e,n){if(n){t.newline()}t.indent();e.print(t)}));t.newline()}));else t.print("{}")}));DEFPRINT(vt,(function(e,t){t.print("new.target")}));function print_property_name(e,t,n){if(n.option("quote_keys")){return n.print_string(e)}if(""+ +e==e&&e>=0){if(n.option("keep_numbers")){return n.print(e)}return n.print(make_num(e))}var i=f.has(e)?n.option("ie8"):n.option("ecma")<2015||n.option("safari10")?!is_basic_identifier_string(e):!is_identifier_string(e,true);if(i||t&&n.option("keep_quoted_props")){return n.print_string(e,t)}return n.print_name(e)}DEFPRINT(ot,(function(e,t){function get_name(e){var t=e.definition();return t?t.mangled_name||t.name:e.name}var n=t.option("shorthand");if(n&&e.value instanceof gt&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value)===e.key&&!f.has(e.key)){print_property_name(e.key,e.quote,t)}else if(n&&e.value instanceof tt&&e.value.left instanceof gt&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value.left)===e.key){print_property_name(e.key,e.quote,t);t.space();t.print("=");t.space();e.value.right.print(t)}else{if(!(e.key instanceof V)){print_property_name(e.key,e.quote,t)}else{t.with_square((function(){e.key.print(t)}))}t.colon();e.value.print(t)}}));DEFPRINT(ht,((e,t)=>{if(e.static){t.print("static");t.space()}t.print("#");print_property_name(e.key.name,e.quote,t);if(e.value){t.print("=");e.value.print(t)}t.semicolon()}));DEFPRINT(dt,((e,t)=>{if(e.static){t.print("static");t.space()}if(e.key instanceof Ct){print_property_name(e.key.name,e.quote,t)}else{t.print("[");e.key.print(t);t.print("]")}if(e.value){t.print("=");e.value.print(t)}t.semicolon()}));rt.DEFMETHOD("_print_getter_setter",(function(e,t,n){var i=this;if(i.static){n.print("static");n.space()}if(e){n.print(e);n.space()}if(i.key instanceof xt){if(t)n.print("#");print_property_name(i.key.name,i.quote,n)}else{n.with_square((function(){i.key.print(n)}))}i.value._do_print(n,true)}));DEFPRINT(lt,(function(e,t){e._print_getter_setter("set",false,t)}));DEFPRINT(ct,(function(e,t){e._print_getter_setter("get",false,t)}));DEFPRINT(st,(function(e,t){e._print_getter_setter("set",true,t)}));DEFPRINT(ut,(function(e,t){e._print_getter_setter("get",true,t)}));DEFPRINT(pt,(function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,true,t)}));DEFPRINT(ft,(function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,false,t)}));gt.DEFMETHOD("_do_print",(function(e){var t=this.definition();e.print_name(t?t.mangled_name||t.name:this.name)}));DEFPRINT(gt,(function(e,t){e._do_print(t)}));DEFPRINT(Zt,noop);DEFPRINT(Ut,(function(e,t){t.print("this")}));DEFPRINT(zt,(function(e,t){t.print("super")}));DEFPRINT(Kt,(function(e,t){t.print(e.getValue())}));DEFPRINT(Gt,(function(e,t){t.print_string(e.getValue(),e.quote,t.in_directive)}));DEFPRINT(Ht,(function(e,t){if((t.option("keep_numbers")||t.use_asm)&&e.raw){t.print(e.raw)}else{t.print(make_num(e.getValue()))}}));DEFPRINT(Xt,(function(e,t){t.print(e.getValue()+"n")}));const e=/(<\s*\/\s*script)/i;const slash_script_replace=(e,t)=>t.replace("/","\\/");DEFPRINT(Wt,(function(t,n){let{source:i,flags:r}=t.getValue();i=regexp_source_fix(i);r=r?sort_regexp_flags(r):"";i=i.replace(e,slash_script_replace);n.print(n.to_utf8(`/${i}/${r}`));const a=n.parent();if(a instanceof Qe&&/^\w/.test(a.operator)&&a.left===t){n.print(" ")}}));function force_statement(e,t){if(t.option("braces")){make_block(e,t)}else{if(!e||e instanceof W)t.force_semicolon();else e.print(t)}}function best_of(e){var t=e[0],n=t.length;for(var i=1;ie===null&&t===null||e.TYPE===t.TYPE&&e.shallow_cmp(t);const equivalent_to=(e,t)=>{if(!shallow_cmp(e,t))return false;const n=[e];const i=[t];const r=n.push.bind(n);const a=i.push.bind(i);while(n.length&&i.length){const e=n.pop();const t=i.pop();if(!shallow_cmp(e,t))return false;e._children_backwards(r);t._children_backwards(a);if(n.length!==i.length){return false}}return n.length==0&&i.length==0};const mkshallow=e=>{const t=Object.keys(e).map((t=>{if(e[t]==="eq"){return`this.${t} === other.${t}`}else if(e[t]==="exist"){return`(this.${t} == null ? other.${t} == null : this.${t} === other.${t})`}else{throw new Error(`mkshallow: Unexpected instruction: ${e[t]}`)}})).join(" && ");return new Function("other","return "+t)};const pass_through=()=>true;V.prototype.shallow_cmp=function(){throw new Error("did not find a shallow_cmp function for "+this.constructor.name)};z.prototype.shallow_cmp=pass_through;K.prototype.shallow_cmp=mkshallow({value:"eq"});G.prototype.shallow_cmp=pass_through;H.prototype.shallow_cmp=pass_through;W.prototype.shallow_cmp=pass_through;Y.prototype.shallow_cmp=mkshallow({"label.name":"eq"});Z.prototype.shallow_cmp=pass_through;Q.prototype.shallow_cmp=pass_through;J.prototype.shallow_cmp=mkshallow({init:"exist",condition:"exist",step:"exist"});ee.prototype.shallow_cmp=pass_through;te.prototype.shallow_cmp=pass_through;ne.prototype.shallow_cmp=pass_through;re.prototype.shallow_cmp=pass_through;ae.prototype.shallow_cmp=pass_through;oe.prototype.shallow_cmp=mkshallow({is_generator:"eq",async:"eq"});fe.prototype.shallow_cmp=mkshallow({is_array:"eq"});pe.prototype.shallow_cmp=pass_through;_e.prototype.shallow_cmp=pass_through;de.prototype.shallow_cmp=mkshallow({value:"eq"});he.prototype.shallow_cmp=pass_through;ve.prototype.shallow_cmp=pass_through;ye.prototype.shallow_cmp=pass_through;Se.prototype.shallow_cmp=mkshallow({is_star:"eq"});Ae.prototype.shallow_cmp=mkshallow({alternative:"exist"});ke.prototype.shallow_cmp=pass_through;Te.prototype.shallow_cmp=pass_through;Re.prototype.shallow_cmp=mkshallow({bcatch:"exist",bfinally:"exist"});we.prototype.shallow_cmp=mkshallow({argname:"exist"});Oe.prototype.shallow_cmp=pass_through;Fe.prototype.shallow_cmp=pass_through;Pe.prototype.shallow_cmp=mkshallow({value:"exist"});Le.prototype.shallow_cmp=pass_through;Be.prototype.shallow_cmp=mkshallow({imported_name:"exist",imported_names:"exist"});Ve.prototype.shallow_cmp=pass_through;Ue.prototype.shallow_cmp=mkshallow({exported_definition:"exist",exported_value:"exist",exported_names:"exist",module_name:"eq",is_default:"eq"});ze.prototype.shallow_cmp=pass_through;Ge.prototype.shallow_cmp=pass_through;He.prototype.shallow_cmp=pass_through;Ye.prototype.shallow_cmp=pass_through;Xe.prototype.shallow_cmp=mkshallow({property:"eq"});We.prototype.shallow_cmp=mkshallow({property:"eq"});je.prototype.shallow_cmp=mkshallow({operator:"eq"});Qe.prototype.shallow_cmp=mkshallow({operator:"eq"});Je.prototype.shallow_cmp=pass_through;nt.prototype.shallow_cmp=pass_through;it.prototype.shallow_cmp=pass_through;rt.prototype.shallow_cmp=pass_through;ot.prototype.shallow_cmp=mkshallow({key:"eq"});lt.prototype.shallow_cmp=mkshallow({static:"eq"});ct.prototype.shallow_cmp=mkshallow({static:"eq"});ft.prototype.shallow_cmp=mkshallow({static:"eq",is_generator:"eq",async:"eq"});_t.prototype.shallow_cmp=mkshallow({name:"exist",extends:"exist"});dt.prototype.shallow_cmp=mkshallow({static:"eq"});gt.prototype.shallow_cmp=mkshallow({name:"eq"});vt.prototype.shallow_cmp=pass_through;Ut.prototype.shallow_cmp=pass_through;zt.prototype.shallow_cmp=pass_through;Gt.prototype.shallow_cmp=mkshallow({value:"eq"});Ht.prototype.shallow_cmp=mkshallow({value:"eq"});Xt.prototype.shallow_cmp=mkshallow({value:"eq"});Wt.prototype.shallow_cmp=function(e){return this.value.flags===e.value.flags&&this.value.source===e.value.source};qt.prototype.shallow_cmp=pass_through;const _n=1<<0;const dn=1<<1;let hn=null;let mn=null;class SymbolDef{constructor(e,t,n){this.name=t.name;this.orig=[t];this.init=n;this.eliminated=0;this.assignments=0;this.scope=e;this.replaced=0;this.global=false;this.export=0;this.mangled_name=null;this.undeclared=false;this.id=SymbolDef.next_id++;this.chained=false;this.direct_access=false;this.escaped=0;this.recursive_refs=0;this.references=[];this.should_replace=undefined;this.single_use=false;this.fixed=false;Object.seal(this)}fixed_value(){if(!this.fixed||this.fixed instanceof V)return this.fixed;return this.fixed()}unmangleable(e){if(!e)e={};if(hn&&hn.has(this.id)&&keep_name(e.keep_fnames,this.orig[0].name))return true;return this.global&&!e.toplevel||this.export&_n||this.undeclared||!e.eval&&this.scope.pinned()||(this.orig[0]instanceof Rt||this.orig[0]instanceof Tt)&&keep_name(e.keep_fnames,this.orig[0].name)||this.orig[0]instanceof xt||(this.orig[0]instanceof Ot||this.orig[0]instanceof wt)&&keep_name(e.keep_classnames,this.orig[0].name)}mangle(e){const t=e.cache&&e.cache.props;if(this.global&&t&&t.has(this.name)){this.mangled_name=t.get(this.name)}else if(!this.mangled_name&&!this.unmangleable(e)){var n=this.scope;var i=this.orig[0];if(e.ie8&&i instanceof Rt)n=n.parent_scope;const r=redefined_catch_def(this);this.mangled_name=r?r.mangled_name||r.name:n.next_mangled(e,this);if(this.global&&t){t.set(this.name,this.mangled_name)}}}}SymbolDef.next_id=1;function redefined_catch_def(e){if(e.orig[0]instanceof Ft&&e.scope.is_block_scope()){return e.scope.get_defun_scope().variables.get(e.name)}}ie.DEFMETHOD("figure_out_scope",(function(e,{parent_scope:t=null,toplevel:n=this}={}){e=defaults(e,{cache:null,ie8:false,safari10:false});if(!(n instanceof re)){throw new Error("Invalid toplevel scope")}var i=this.parent_scope=t;var r=new Map;var a=null;var o=null;var s=[];var u=new TreeWalker(((t,n)=>{if(t.is_block_scope()){const r=i;t.block_scope=i=new ie(t);i._block_scope=true;const a=t instanceof we?r.parent_scope:r;i.init_scope_vars(a);i.uses_with=r.uses_with;i.uses_eval=r.uses_eval;if(e.safari10){if(t instanceof J||t instanceof ee){s.push(i)}}if(t instanceof ke){const e=i;i=r;t.expression.walk(u);i=e;for(let e=0;e{if(e===t)return true;if(t instanceof yt){return e instanceof Rt}return!(e instanceof At||e instanceof St)}))){js_error(`"${t.name}" is redeclared`,t.start.file,t.start.line,t.start.col,t.start.pos)}if(!(t instanceof kt))mark_export(d,2);if(a!==i){t.mark_enclosed();var d=i.find_variable(t);if(t.thedef!==d){t.thedef=d;t.reference()}}}else if(t instanceof Vt){var h=r.get(t.name);if(!h)throw new Error(string_template("Undefined label {name} [{line},{col}]",{name:t.name,line:t.start.line,col:t.start.col}));t.thedef=h}if(!(i instanceof re)&&(t instanceof Ue||t instanceof Be)){js_error(`"${t.TYPE}" statement may only appear at the top level`,t.start.file,t.start.line,t.start.col,t.start.pos)}}));this.walk(u);function mark_export(e,t){if(o){var n=0;do{t++}while(u.parent(n++)!==o)}var i=u.parent(t);if(e.export=i instanceof Ue?_n:0){var r=i.exported_definition;if((r instanceof ce||r instanceof mt)&&i.is_default){e.export=dn}}}const l=this instanceof re;if(l){this.globals=new Map}var u=new TreeWalker((e=>{if(e instanceof ve&&e.label){e.label.thedef.references.push(e);return true}if(e instanceof Pt){var t=e.name;if(t=="eval"&&u.parent()instanceof ze){for(var i=e.scope;i&&!i.uses_eval;i=i.parent_scope){i.uses_eval=true}}var r;if(u.parent()instanceof Le&&u.parent(1).module_name||!(r=e.scope.find_variable(t))){r=n.def_global(e);if(e instanceof Lt)r.export=_n}else if(r.scope instanceof oe&&t=="arguments"){r.scope.uses_arguments=true}e.thedef=r;e.reference();if(e.scope.is_block_scope()&&!(r.orig[0]instanceof yt)){e.scope=e.scope.get_defun_scope()}return true}var a;if(e instanceof Ft&&(a=redefined_catch_def(e.definition()))){var i=e.scope;while(i){push_uniq(i.enclosed,a);if(i===a.scope)break;i=i.parent_scope}}}));this.walk(u);if(e.ie8||e.safari10){walk(this,(e=>{if(e instanceof Ft){var t=e.name;var i=e.thedef.references;var r=e.scope.get_defun_scope();var a=r.find_variable(t)||n.globals.get(t)||r.def_variable(e);i.forEach((function(e){e.thedef=a;e.reference()}));e.thedef=a;e.reference();return true}}))}if(e.safari10){for(const e of s){e.parent_scope.variables.forEach((function(t){push_uniq(e.enclosed,t)}))}}}));re.DEFMETHOD("def_global",(function(e){var t=this.globals,n=e.name;if(t.has(n)){return t.get(n)}else{var i=new SymbolDef(this,e);i.undeclared=true;i.global=true;t.set(n,i);return i}}));ie.DEFMETHOD("init_scope_vars",(function(e){this.variables=new Map;this.uses_with=false;this.uses_eval=false;this.parent_scope=e;this.enclosed=[];this.cname=-1}));ie.DEFMETHOD("conflicting_def",(function(e){return this.enclosed.find((t=>t.name===e))||this.variables.has(e)||this.parent_scope&&this.parent_scope.conflicting_def(e)}));ie.DEFMETHOD("conflicting_def_shallow",(function(e){return this.enclosed.find((t=>t.name===e))||this.variables.has(e)}));ie.DEFMETHOD("add_child_scope",(function(e){if(e.parent_scope===this)return;e.parent_scope=this;const t=(()=>{const e=[];let t=this;do{e.push(t)}while(t=t.parent_scope);e.reverse();return e})();const n=new Set(e.enclosed);const i=[];for(const e of t){i.forEach((t=>push_uniq(e.enclosed,t)));for(const t of e.variables.values()){if(n.has(t)){push_uniq(i,t);push_uniq(e.enclosed,t)}}}}));function find_scopes_visible_from(e){const t=new Set;for(const n of new Set(e)){(function bubble_up(e){if(e==null||t.has(e))return;t.add(e);bubble_up(e.parent_scope)})(n)}return[...t]}ie.DEFMETHOD("create_symbol",(function(e,{source:t,tentative_name:n,scope:i,conflict_scopes:r=[i],init:a=null}={}){let o;r=find_scopes_visible_from(r);if(n){n=o=n.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/gi,"_");let e=0;while(r.find((e=>e.conflicting_def_shallow(o)))){o=n+"$"+e++}}if(!o){throw new Error("No symbol name could be generated in create_symbol()")}const s=make_node(e,t,{name:o,scope:i});this.def_variable(s,a||null);s.mark_enclosed();return s}));V.DEFMETHOD("is_block_scope",return_false);_t.DEFMETHOD("is_block_scope",return_false);oe.DEFMETHOD("is_block_scope",return_false);re.DEFMETHOD("is_block_scope",return_false);Te.DEFMETHOD("is_block_scope",return_false);H.DEFMETHOD("is_block_scope",return_true);ie.DEFMETHOD("is_block_scope",(function(){return this._block_scope||false}));j.DEFMETHOD("is_block_scope",return_true);oe.DEFMETHOD("init_scope_vars",(function(){ie.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false;this.def_variable(new kt({name:"arguments",start:this.start,end:this.end}))}));le.DEFMETHOD("init_scope_vars",(function(){ie.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false}));gt.DEFMETHOD("mark_enclosed",(function(){var e=this.definition();var t=this.scope;while(t){push_uniq(t.enclosed,e);if(t===e.scope)break;t=t.parent_scope}}));gt.DEFMETHOD("reference",(function(){this.definition().references.push(this);this.mark_enclosed()}));ie.DEFMETHOD("find_variable",(function(e){if(e instanceof gt)e=e.name;return this.variables.get(e)||this.parent_scope&&this.parent_scope.find_variable(e)}));ie.DEFMETHOD("def_function",(function(e,t){var n=this.def_variable(e,t);if(!n.init||n.init instanceof ce)n.init=t;return n}));ie.DEFMETHOD("def_variable",(function(e,t){var n=this.variables.get(e.name);if(n){n.orig.push(e);if(n.init&&(n.scope!==e.scope||n.init instanceof ue)){n.init=t}}else{n=new SymbolDef(this,e,t);this.variables.set(e.name,n);n.global=!this.parent_scope}return e.thedef=n}));function next_mangled(e,t){var n=e.enclosed;e:while(true){var i=En(++e.cname);if(f.has(i))continue;if(t.reserved.has(i))continue;if(mn&&mn.has(i))continue e;for(let e=n.length;--e>=0;){const r=n[e];const a=r.mangled_name||r.unmangleable(t)&&r.name;if(i==a)continue e}return i}}ie.DEFMETHOD("next_mangled",(function(e){return next_mangled(this,e)}));re.DEFMETHOD("next_mangled",(function(e){let t;const n=this.mangled_names;do{t=next_mangled(this,e)}while(n.has(t));return t}));ue.DEFMETHOD("next_mangled",(function(e,t){var n=t.orig[0]instanceof kt&&this.name&&this.name.definition();var i=n?n.mangled_name||n.name:null;while(true){var r=next_mangled(this,e);if(!i||i!=r)return r}}));gt.DEFMETHOD("unmangleable",(function(e){var t=this.definition();return!t||t.unmangleable(e)}));It.DEFMETHOD("unmangleable",return_false);gt.DEFMETHOD("unreferenced",(function(){return!this.definition().references.length&&!this.scope.pinned()}));gt.DEFMETHOD("definition",(function(){return this.thedef}));gt.DEFMETHOD("global",(function(){return this.thedef.global}));re.DEFMETHOD("_default_mangler_options",(function(e){e=defaults(e,{eval:false,ie8:false,keep_classnames:false,keep_fnames:false,module:false,reserved:[],toplevel:false});if(e.module)e.toplevel=true;if(!Array.isArray(e.reserved)&&!(e.reserved instanceof Set)){e.reserved=[]}e.reserved=new Set(e.reserved);e.reserved.add("arguments");return e}));re.DEFMETHOD("mangle_names",(function(e){e=this._default_mangler_options(e);var t=-1;var n=[];if(e.keep_fnames){hn=new Set}const i=this.mangled_names=new Set;if(e.cache){this.globals.forEach(collect);if(e.cache.props){e.cache.props.forEach((function(e){i.add(e)}))}}var r=new TreeWalker((function(i,r){if(i instanceof Y){var a=t;r();t=a;return true}if(i instanceof ie){i.variables.forEach(collect);return}if(i.is_block_scope()){i.block_scope.variables.forEach(collect);return}if(hn&&i instanceof Pe&&i.value instanceof oe&&!i.value.name&&keep_name(e.keep_fnames,i.name.name)){hn.add(i.name.definition().id);return}if(i instanceof It){let e;do{e=En(++t)}while(f.has(e));i.mangled_name=e;return true}if(!(e.ie8||e.safari10)&&i instanceof Ft){n.push(i.definition());return}}));this.walk(r);if(e.keep_fnames||e.keep_classnames){mn=new Set;n.forEach((t=>{if(t.name.length<6&&t.unmangleable(e)){mn.add(t.name)}}))}n.forEach((t=>{t.mangle(e)}));hn=null;mn=null;function collect(t){const i=!e.reserved.has(t.name)&&!(t.export&_n);if(i){n.push(t)}}}));re.DEFMETHOD("find_colliding_names",(function(e){const t=e.cache&&e.cache.props;const n=new Set;e.reserved.forEach(to_avoid);this.globals.forEach(add_def);this.walk(new TreeWalker((function(e){if(e instanceof ie)e.variables.forEach(add_def);if(e instanceof Ft)add_def(e.definition())})));return n;function to_avoid(e){n.add(e)}function add_def(n){var i=n.name;if(n.global&&t&&t.has(i))i=t.get(i);else if(!n.unmangleable(e))return;to_avoid(i)}}));re.DEFMETHOD("expand_names",(function(e){En.reset();En.sort();e=this._default_mangler_options(e);var t=this.find_colliding_names(e);var n=0;this.globals.forEach(rename);this.walk(new TreeWalker((function(e){if(e instanceof ie)e.variables.forEach(rename);if(e instanceof Ft)rename(e.definition())})));function next_name(){var e;do{e=En(n++)}while(t.has(e)||f.has(e));return e}function rename(t){if(t.global&&e.cache)return;if(t.unmangleable(e))return;if(e.reserved.has(t.name))return;const n=redefined_catch_def(t);const i=t.name=n?n.name:next_name();t.orig.forEach((function(e){e.name=i}));t.references.forEach((function(e){e.name=i}))}}));V.DEFMETHOD("tail_node",return_this);Ge.DEFMETHOD("tail_node",(function(){return this.expressions[this.expressions.length-1]}));re.DEFMETHOD("compute_char_frequency",(function(e){e=this._default_mangler_options(e);try{V.prototype.print=function(t,n){this._print(t,n);if(this instanceof gt&&!this.unmangleable(e)){En.consider(this.name,-1)}else if(e.properties){if(this instanceof We){En.consider("#"+this.property,-1)}else if(this instanceof Xe){En.consider(this.property,-1)}else if(this instanceof qe){skip_string(this.property)}}};En.consider(this.print_to_string(),1)}finally{V.prototype.print=V.prototype._print}En.sort();function skip_string(e){if(e instanceof Gt){En.consider(e.value,-1)}else if(e instanceof Je){skip_string(e.consequent);skip_string(e.alternative)}else if(e instanceof Ge){skip_string(e.tail_node())}}}));const En=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");const t="0123456789".split("");let n;let i;function reset(){i=new Map;e.forEach((function(e){i.set(e,0)}));t.forEach((function(e){i.set(e,0)}))}base54.consider=function(e,t){for(var n=e.length;--n>=0;){i.set(e[n],i.get(e[n])+t)}};function compare(e,t){return i.get(t)-i.get(e)}base54.sort=function(){n=mergeSort(e,compare).concat(mergeSort(t,compare))};base54.reset=reset;reset();function base54(e){var t="",i=54;e++;do{e--;t+=n[e%i];e=Math.floor(e/i);i=64}while(e>0);return t}return base54})();let gn=undefined;V.prototype.size=function(e,t){gn=e&&e.mangle_options;let n=0;walk_parent(this,((e,t)=>{n+=e._size(t);if(e instanceof le&&e.is_braceless()){n+=e.body[0].value._size(t);return true}}),t||e&&e.stack);gn=undefined;return n};V.prototype._size=()=>0;z.prototype._size=()=>8;K.prototype._size=function(){return 2+this.value.length};const list_overhead=e=>e.length&&e.length-1;H.prototype._size=function(){return 2+list_overhead(this.body)};re.prototype._size=function(){return list_overhead(this.body)};W.prototype._size=()=>1;Y.prototype._size=()=>2;Z.prototype._size=()=>9;Q.prototype._size=()=>7;J.prototype._size=()=>8;ee.prototype._size=()=>8;ne.prototype._size=()=>6;ae.prototype._size=()=>3;const lambda_modifiers=e=>(e.is_generator?1:0)+(e.async?6:0);se.prototype._size=function(){return lambda_modifiers(this)+4+list_overhead(this.argnames)+list_overhead(this.body)};ue.prototype._size=function(e){const t=!!first_in_statement(e);return t*2+lambda_modifiers(this)+12+list_overhead(this.argnames)+list_overhead(this.body)};ce.prototype._size=function(){return lambda_modifiers(this)+13+list_overhead(this.argnames)+list_overhead(this.body)};le.prototype._size=function(){let e=2+list_overhead(this.argnames);if(!(this.argnames.length===1&&this.argnames[0]instanceof gt)){e+=2}const t=this.is_braceless()?0:list_overhead(this.body)+2;return lambda_modifiers(this)+e+t};fe.prototype._size=()=>2;_e.prototype._size=function(){return 2+Math.floor(this.segments.length/2)*3};de.prototype._size=function(){return this.value.length};Ee.prototype._size=function(){return this.value?7:6};ge.prototype._size=()=>6;be.prototype._size=function(){return this.label?6:5};De.prototype._size=function(){return this.label?9:8};Ae.prototype._size=()=>4;ke.prototype._size=function(){return 8+list_overhead(this.body)};Ce.prototype._size=function(){return 5+list_overhead(this.body)};xe.prototype._size=function(){return 8+list_overhead(this.body)};Re.prototype._size=function(){return 3+list_overhead(this.body)};we.prototype._size=function(){let e=7+list_overhead(this.body);if(this.argname){e+=2}return e};Oe.prototype._size=function(){return 7+list_overhead(this.body)};const def_size=(e,t)=>e+list_overhead(t.definitions);Ne.prototype._size=function(){return def_size(4,this)};Me.prototype._size=function(){return def_size(4,this)};Ie.prototype._size=function(){return def_size(6,this)};Pe.prototype._size=function(){return this.value?1:0};Le.prototype._size=function(){return this.name?4:0};Be.prototype._size=function(){let e=6;if(this.imported_name)e+=1;if(this.imported_name||this.imported_names)e+=5;if(this.imported_names){e+=2+list_overhead(this.imported_names)}return e};Ve.prototype._size=()=>11;Ue.prototype._size=function(){let e=7+(this.is_default?8:0);if(this.exported_value){e+=this.exported_value._size()}if(this.exported_names){e+=2+list_overhead(this.exported_names)}if(this.module_name){e+=5}return e};ze.prototype._size=function(){if(this.optional){return 4+list_overhead(this.args)}return 2+list_overhead(this.args)};Ke.prototype._size=function(){return 6+list_overhead(this.args)};Ge.prototype._size=function(){return list_overhead(this.expressions)};Xe.prototype._size=function(){if(this.optional){return this.property.length+2}return this.property.length+1};We.prototype._size=function(){if(this.optional){return this.property.length+3}return this.property.length+2};qe.prototype._size=function(){return this.optional?4:2};je.prototype._size=function(){if(this.operator==="typeof")return 7;if(this.operator==="void")return 5;return this.operator.length};Qe.prototype._size=function(e){if(this.operator==="in")return 4;let t=this.operator.length;if((this.operator==="+"||this.operator==="-")&&this.right instanceof je&&this.right.operator===this.operator){t+=1}if(this.needs_parens(e)){t+=2}return t};Je.prototype._size=()=>3;nt.prototype._size=function(){return 2+list_overhead(this.elements)};it.prototype._size=function(e){let t=2;if(first_in_statement(e)){t+=2}return t+list_overhead(this.properties)};const key_size=e=>typeof e==="string"?e.length:0;ot.prototype._size=function(){return key_size(this.key)+1};const static_size=e=>e?7:0;ct.prototype._size=function(){return 5+static_size(this.static)+key_size(this.key)};lt.prototype._size=function(){return 5+static_size(this.static)+key_size(this.key)};ft.prototype._size=function(){return static_size(this.static)+key_size(this.key)+lambda_modifiers(this)};pt.prototype._size=function(){return ft.prototype._size.call(this)+1};ut.prototype._size=st.prototype._size=function(){return ft.prototype._size.call(this)+4};_t.prototype._size=function(){return(this.name?8:7)+(this.extends?8:0)};dt.prototype._size=function(){return static_size(this.static)+(typeof this.key==="string"?this.key.length+2:0)+(this.value?1:0)};ht.prototype._size=function(){return dt.prototype._size.call(this)+1};gt.prototype._size=function(){return!gn||this.definition().unmangleable(gn)?this.name.length:1};Ct.prototype._size=function(){return this.name.length};Pt.prototype._size=bt.prototype._size=function(){const{name:e,thedef:t}=this;if(t&&t.global)return e.length;if(e==="arguments")return 9;return gt.prototype._size.call(this)};vt.prototype._size=()=>10;Mt.prototype._size=function(){return this.name.length};Bt.prototype._size=function(){return this.name.length};Ut.prototype._size=()=>4;zt.prototype._size=()=>5;Gt.prototype._size=function(){return this.value.length+2};Ht.prototype._size=function(){const{value:e}=this;if(e===0)return 1;if(e>0&&Math.floor(e)===e){return Math.floor(Math.log10(e)+1)}return e.toString().length};Xt.prototype._size=function(){return this.value.length};Wt.prototype._size=function(){return this.value.toString().length};Yt.prototype._size=()=>4;jt.prototype._size=()=>3;$t.prototype._size=()=>6;Zt.prototype._size=()=>0;Qt.prototype._size=()=>8;tn.prototype._size=()=>4;en.prototype._size=()=>5;ye.prototype._size=()=>6;Se.prototype._size=()=>6;const vn=1;const bn=2;const Dn=4;const yn=8;const Sn=16;const An=32;const kn=256;const Tn=512;const xn=1024;const Cn=kn|Tn|xn;const has_flag=(e,t)=>e.flags&t;const set_flag=(e,t)=>{e.flags|=t};const clear_flag=(e,t)=>{e.flags&=~t};class Compressor extends TreeWalker{constructor(e,{false_by_default:t=false,mangle_options:n=false}){super();if(e.defaults!==undefined&&!e.defaults)t=true;this.options=defaults(e,{arguments:false,arrows:!t,booleans:!t,booleans_as_integers:false,collapse_vars:!t,comparisons:!t,computed_props:!t,conditionals:!t,dead_code:!t,defaults:true,directives:!t,drop_console:false,drop_debugger:!t,ecma:5,evaluate:!t,expression:false,global_defs:false,hoist_funs:false,hoist_props:!t,hoist_vars:false,ie8:false,if_return:!t,inline:!t,join_vars:!t,keep_classnames:false,keep_fargs:true,keep_fnames:false,keep_infinity:false,loops:!t,module:false,negate_iife:!t,passes:1,properties:!t,pure_getters:!t&&"strict",pure_funcs:null,reduce_funcs:!t,reduce_vars:!t,sequences:!t,side_effects:!t,switches:!t,top_retain:null,toplevel:!!(e&&e["top_retain"]),typeofs:!t,unsafe:false,unsafe_arrows:false,unsafe_comps:false,unsafe_Function:false,unsafe_math:false,unsafe_symbols:false,unsafe_methods:false,unsafe_proto:false,unsafe_regexp:false,unsafe_undefined:false,unused:!t,warnings:false},true);var i=this.options["global_defs"];if(typeof i=="object")for(var r in i){if(r[0]==="@"&&HOP(i,r)){i[r.slice(1)]=parse(i[r],{expression:true})}}if(this.options["inline"]===true)this.options["inline"]=3;var a=this.options["pure_funcs"];if(typeof a=="function"){this.pure_funcs=a}else{this.pure_funcs=a?function(e){return!a.includes(e.expression.print_to_string())}:return_true}var o=this.options["top_retain"];if(o instanceof RegExp){this.top_retain=function(e){return o.test(e.name)}}else if(typeof o=="function"){this.top_retain=o}else if(o){if(typeof o=="string"){o=o.split(/,/)}this.top_retain=function(e){return o.includes(e.name)}}if(this.options["module"]){this.directives["use strict"]=true;this.options["toplevel"]=true}var s=this.options["toplevel"];this.toplevel=typeof s=="string"?{funcs:/funcs/.test(s),vars:/vars/.test(s)}:{funcs:s,vars:s};var u=this.options["sequences"];this.sequences_limit=u==1?800:u|0;this.evaluated_regexps=new Map;this._toplevel=undefined;this.mangle_options=n}option(e){return this.options[e]}exposed(e){if(e.export)return true;if(e.global)for(var t=0,n=e.orig.length;t0||this.option("reduce_vars")){this._toplevel.reset_opt_flags(this)}this._toplevel=this._toplevel.transform(this);if(t>1){let e=0;walk(this._toplevel,(()=>{e++}));if(e=0){r.body[o]=r.body[o].transform(i)}}else if(r instanceof Ae){r.body=r.body.transform(i);if(r.alternative){r.alternative=r.alternative.transform(i)}}else if(r instanceof ne){r.body=r.body.transform(i)}return r}));n.transform(i)}));function read_property(e,t){t=get_value(t);if(t instanceof V)return;var n;if(e instanceof nt){var i=e.elements;if(t=="length")return make_node_from_constant(i.length,e);if(typeof t=="number"&&t in i)n=i[t]}else if(e instanceof it){t=""+t;var r=e.properties;for(var a=r.length;--a>=0;){var o=r[a];if(!(o instanceof ot))return;if(!n&&r[a].key===t)n=r[a].value}}return n instanceof Pt&&n.fixed_value()||n}function is_modified(e,t,n,i,r,a){var o=t.parent(r);var s=is_lhs(n,o);if(s)return s;if(!a&&o instanceof ze&&o.expression===n&&!(i instanceof le)&&!(i instanceof _t)&&!o.is_callee_pure(e)&&(!(i instanceof ue)||!(o instanceof Ke)&&i.contains_this())){return true}if(o instanceof nt){return is_modified(e,t,o,o,r+1)}if(o instanceof ot&&n===o.value){var u=t.parent(r+1);return is_modified(e,t,u,u,r+2)}if(o instanceof He&&o.expression===n){var l=read_property(i,o.property);return!a&&is_modified(e,t,o,l,r+1)}}(function(e){e(V,noop);function reset_def(e,t){t.assignments=0;t.chained=false;t.direct_access=false;t.escaped=0;t.recursive_refs=0;t.references=[];t.single_use=undefined;if(t.scope.pinned()){t.fixed=false}else if(t.orig[0]instanceof St||!e.exposed(t)){t.fixed=t.init}else{t.fixed=false}}function reset_variables(e,t,n){n.variables.forEach((function(n){reset_def(t,n);if(n.fixed===null){e.defs_to_safe_ids.set(n.id,e.safe_ids);mark(e,n,true)}else if(n.fixed){e.loop_ids.set(n.id,e.in_loop);mark(e,n,true)}}))}function reset_block_variables(e,t){if(t.block_scope)t.block_scope.variables.forEach((t=>{reset_def(e,t)}))}function push(e){e.safe_ids=Object.create(e.safe_ids)}function pop(e){e.safe_ids=Object.getPrototypeOf(e.safe_ids)}function mark(e,t,n){e.safe_ids[t.id]=n}function safe_to_read(e,t){if(t.single_use=="m")return false;if(e.safe_ids[t.id]){if(t.fixed==null){var n=t.orig[0];if(n instanceof kt||n.name=="arguments")return false;t.fixed=make_node($t,n)}return true}return t.fixed instanceof ce}function safe_to_assign(e,t,n,i){if(t.fixed===undefined)return true;let r;if(t.fixed===null&&(r=e.defs_to_safe_ids.get(t.id))){r[t.id]=false;e.defs_to_safe_ids.delete(t.id);return true}if(!HOP(e.safe_ids,t.id))return false;if(!safe_to_read(e,t))return false;if(t.fixed===false)return false;if(t.fixed!=null&&(!i||t.references.length>t.assignments))return false;if(t.fixed instanceof ce){return i instanceof V&&t.fixed.parent_scope===n}return t.orig.every((e=>!(e instanceof St||e instanceof Tt||e instanceof Rt)))}function ref_once(e,t,n){return t.option("unused")&&!n.scope.pinned()&&n.references.length-n.recursive_refs==1&&e.loop_ids.get(n.id)===e.in_loop}function is_immutable(e){if(!e)return false;return e.is_constant()||e instanceof oe||e instanceof Ut}function mark_escaped(e,t,n,i,r,a=0,o=1){var s=e.parent(a);if(r){if(r.is_constant())return;if(r instanceof Et)return}if(s instanceof et&&(s.operator==="="||s.logical)&&i===s.right||s instanceof ze&&(i!==s.expression||s instanceof Ke)||s instanceof me&&i===s.value&&i.scope!==t.scope||s instanceof Pe&&i===s.value||s instanceof Se&&i===s.value&&i.scope!==t.scope){if(o>1&&!(r&&r.is_constant_expression(n)))o=1;if(!t.escaped||t.escaped>o)t.escaped=o;return}else if(s instanceof nt||s instanceof ye||s instanceof Qe&&On.has(s.operator)||s instanceof Je&&i!==s.condition||s instanceof ae||s instanceof Ge&&i===s.tail_node()){mark_escaped(e,t,n,s,s,a+1,o)}else if(s instanceof ot&&i===s.value){var u=e.parent(a+1);mark_escaped(e,t,n,u,u,a+2,o)}else if(s instanceof He&&i===s.expression){r=read_property(r,s.property);mark_escaped(e,t,n,s,r,a+1,o+1);if(r)return}if(a>0)return;if(s instanceof Ge&&i!==s.tail_node())return;if(s instanceof G)return;t.direct_access=true}const suppress=e=>walk(e,(e=>{if(!(e instanceof gt))return;var t=e.definition();if(!t)return;if(e instanceof Pt)t.references.push(e);t.fixed=false}));e(se,(function(e,t,n){push(e);reset_variables(e,n,this);t();pop(e);return true}));e(et,(function(e,t,n){var i=this;if(i.left instanceof fe){suppress(i.left);return}const finish_walk=()=>{if(i.logical){i.left.walk(e);push(e);i.right.walk(e);pop(e);return true}};var r=i.left;if(!(r instanceof Pt))return finish_walk();var a=r.definition();var o=safe_to_assign(e,a,r.scope,i.right);a.assignments++;if(!o)return finish_walk();var s=a.fixed;if(!s&&i.operator!="="&&!i.logical)return finish_walk();var u=i.operator=="=";var l=u?i.right:i;if(is_modified(n,e,i,l,0))return finish_walk();a.references.push(r);if(!i.logical){if(!u)a.chained=true;a.fixed=u?function(){return i.right}:function(){return make_node(Qe,i,{operator:i.operator.slice(0,-1),left:s instanceof V?s:s(),right:i.right})}}if(i.logical){mark(e,a,false);push(e);i.right.walk(e);pop(e);return true}mark(e,a,false);i.right.walk(e);mark(e,a,true);mark_escaped(e,a,r.scope,i,l,0,1);return true}));e(Qe,(function(e){if(!On.has(this.operator))return;this.left.walk(e);push(e);this.right.walk(e);pop(e);return true}));e(H,(function(e,t,n){reset_block_variables(n,this)}));e(Ce,(function(e){push(e);this.expression.walk(e);pop(e);push(e);walk_body(this,e);pop(e);return true}));e(_t,(function(e,t){clear_flag(this,Sn);push(e);t();pop(e);return true}));e(Je,(function(e){this.condition.walk(e);push(e);this.consequent.walk(e);pop(e);push(e);this.alternative.walk(e);pop(e);return true}));e(Ye,(function(e,t){const n=e.safe_ids;t();e.safe_ids=n;return true}));e(ze,(function(e){this.expression.walk(e);if(this.optional){push(e)}for(const t of this.args)t.walk(e);return true}));e(He,(function(e){if(!this.optional)return;this.expression.walk(e);push(e);if(this.property instanceof V)this.property.walk(e);return true}));e(xe,(function(e,t){push(e);t();pop(e);return true}));function mark_lambda(e,t,n){clear_flag(this,Sn);push(e);reset_variables(e,n,this);if(this.uses_arguments){t();pop(e);return}var i;if(!this.name&&(i=e.parent())instanceof ze&&i.expression===this&&!i.args.some((e=>e instanceof ae))&&this.argnames.every((e=>e instanceof gt))){this.argnames.forEach(((t,n)=>{if(!t.definition)return;var r=t.definition();if(r.orig.length>1)return;if(r.fixed===undefined&&(!this.uses_arguments||e.has_directive("use strict"))){r.fixed=function(){return i.args[n]||make_node($t,i)};e.loop_ids.set(r.id,e.in_loop);mark(e,r,true)}else{r.fixed=false}}))}t();pop(e);return true}e(oe,mark_lambda);e(Z,(function(e,t,n){reset_block_variables(n,this);const i=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);if(has_break_or_continue(this)){pop(e);push(e)}this.condition.walk(e);pop(e);e.in_loop=i;return true}));e(J,(function(e,t,n){reset_block_variables(n,this);if(this.init)this.init.walk(e);const i=e.in_loop;e.in_loop=this;push(e);if(this.condition)this.condition.walk(e);this.body.walk(e);if(this.step){if(has_break_or_continue(this)){pop(e);push(e)}this.step.walk(e)}pop(e);e.in_loop=i;return true}));e(ee,(function(e,t,n){reset_block_variables(n,this);suppress(this.init);this.object.walk(e);const i=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);pop(e);e.in_loop=i;return true}));e(Ae,(function(e){this.condition.walk(e);push(e);this.body.walk(e);pop(e);if(this.alternative){push(e);this.alternative.walk(e);pop(e)}return true}));e(Y,(function(e){push(e);this.body.walk(e);pop(e);return true}));e(Ft,(function(){this.definition().fixed=false}));e(Pt,(function(e,t,n){var i=this.definition();i.references.push(this);if(i.references.length==1&&!i.fixed&&i.orig[0]instanceof Tt){e.loop_ids.set(i.id,e.in_loop)}var r;if(i.fixed===undefined||!safe_to_read(e,i)){i.fixed=false}else if(i.fixed){r=this.fixed_value();if(r instanceof oe&&recursive_ref(e,i)){i.recursive_refs++}else if(r&&!n.exposed(i)&&ref_once(e,n,i)){i.single_use=r instanceof oe&&!r.pinned()||r instanceof _t||i.scope===this.scope&&r.is_constant_expression()}else{i.single_use=false}if(is_modified(n,e,this,r,0,is_immutable(r))){if(i.single_use){i.single_use="m"}else{i.fixed=false}}}mark_escaped(e,i,this.scope,this,r,0,1)}));e(re,(function(e,t,n){this.globals.forEach((function(e){reset_def(n,e)}));reset_variables(e,n,this)}));e(Re,(function(e,t,n){reset_block_variables(n,this);push(e);walk_body(this,e);pop(e);if(this.bcatch){push(e);this.bcatch.walk(e);pop(e)}if(this.bfinally)this.bfinally.walk(e);return true}));e(je,(function(e){var t=this;if(t.operator!=="++"&&t.operator!=="--")return;var n=t.expression;if(!(n instanceof Pt))return;var i=n.definition();var r=safe_to_assign(e,i,n.scope,true);i.assignments++;if(!r)return;var a=i.fixed;if(!a)return;i.references.push(n);i.chained=true;i.fixed=function(){return make_node(Qe,t,{operator:t.operator.slice(0,-1),left:make_node($e,t,{operator:"+",expression:a instanceof V?a:a()}),right:make_node(Ht,t,{value:1})})};mark(e,i,true);return true}));e(Pe,(function(e,t){var n=this;if(n.name instanceof fe){suppress(n.name);return}var i=n.name.definition();if(n.value){if(safe_to_assign(e,i,n.name.scope,n.value)){i.fixed=function(){return n.value};e.loop_ids.set(i.id,e.in_loop);mark(e,i,false);t();mark(e,i,true);return true}else{i.fixed=false}}}));e(Q,(function(e,t,n){reset_block_variables(n,this);const i=e.in_loop;e.in_loop=this;push(e);t();pop(e);e.in_loop=i;return true}))})((function(e,t){e.DEFMETHOD("reduce_vars",t)}));re.DEFMETHOD("reset_opt_flags",(function(e){const t=this;const n=e.option("reduce_vars");const i=new TreeWalker((function(r,a){clear_flag(r,Cn);if(n){if(e.top_retain&&r instanceof ce&&i.parent()===t){set_flag(r,xn)}return r.reduce_vars(i,a,e)}}));i.safe_ids=Object.create(null);i.in_loop=null;i.loop_ids=new Map;i.defs_to_safe_ids=new Map;t.walk(i)}));gt.DEFMETHOD("fixed_value",(function(){var e=this.thedef.fixed;if(!e||e instanceof V)return e;return e()}));Pt.DEFMETHOD("is_immutable",(function(){var e=this.definition().orig;return e.length==1&&e[0]instanceof Rt}));function is_func_expr(e){return e instanceof le||e instanceof ue}function is_lhs_read_only(e){if(e instanceof Ut)return true;if(e instanceof Pt)return e.definition().orig[0]instanceof Rt;if(e instanceof He){e=e.expression;if(e instanceof Pt){if(e.is_immutable())return false;e=e.fixed_value()}if(!e)return true;if(e instanceof Wt)return false;if(e instanceof Kt)return true;return is_lhs_read_only(e)}return false}function is_ref_of(e,t){if(!(e instanceof Pt))return false;var n=e.definition().orig;for(var i=n.length;--i>=0;){if(n[i]instanceof t)return true}}function find_scope(e){for(let t=0;;t++){const n=e.parent(t);if(n instanceof re)return n;if(n instanceof oe)return n;if(n.block_scope)return n.block_scope}}function find_variable(e,t){var n,i=0;while(n=e.parent(i++)){if(n instanceof ie)break;if(n instanceof we&&n.argname){n=n.argname.definition().scope;break}}return n.find_variable(t)}function make_sequence(e,t){if(t.length==1)return t[0];if(t.length==0)throw new Error("trying to create a sequence with length zero!");return make_node(Ge,e,{expressions:t.reduce(merge_sequence,[])})}function make_node_from_constant(e,t){switch(typeof e){case"string":return make_node(Gt,t,{value:e});case"number":if(isNaN(e))return make_node(jt,t);if(isFinite(e)){return 1/e<0?make_node($e,t,{operator:"-",expression:make_node(Ht,t,{value:-e})}):make_node(Ht,t,{value:e})}return e<0?make_node($e,t,{operator:"-",expression:make_node(Qt,t)}):make_node(Qt,t);case"boolean":return make_node(e?tn:en,t);case"undefined":return make_node($t,t);default:if(e===null){return make_node(Yt,t,{value:null})}if(e instanceof RegExp){return make_node(Wt,t,{value:{source:regexp_source_fix(e.source),flags:e.flags}})}throw new Error(string_template("Can't handle constant of type: {type}",{type:typeof e}))}}function maintain_this_binding(e,t,n){if(e instanceof $e&&e.operator=="delete"||e instanceof ze&&e.expression===t&&(n instanceof He||n instanceof Pt&&n.name=="eval")){return make_sequence(t,[make_node(Ht,t,{value:0}),n])}return n}function merge_sequence(e,t){if(t instanceof Ge){e.push(...t.expressions)}else{e.push(t)}return e}function as_statement_array(e){if(e===null)return[];if(e instanceof X)return e.body;if(e instanceof W)return[];if(e instanceof U)return[e];throw new Error("Can't convert thing to statement array")}function is_empty(e){if(e===null)return true;if(e instanceof W)return true;if(e instanceof X)return e.body.length==0;return false}function can_be_evicted_from_block(e){return!(e instanceof mt||e instanceof ce||e instanceof Me||e instanceof Ie||e instanceof Ue||e instanceof Be)}function loop_body(e){if(e instanceof j){return e.body instanceof X?e.body:e}return e}function is_iife_call(e){if(e.TYPE!="Call")return false;return e.expression instanceof ue||is_iife_call(e.expression)}function is_undeclared_ref(e){return e instanceof Pt&&e.definition().undeclared}var Rn=makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");Pt.DEFMETHOD("is_declared",(function(e){return!this.definition().undeclared||e.option("unsafe")&&Rn.has(this.name)}));var wn=makePredicate("Infinity NaN undefined");function is_identifier_atom(e){return e instanceof Qt||e instanceof jt||e instanceof $t}function tighten_body(e,t){var n,i;var a=t.find_parent(ie).get_defun_scope();find_loop_scope_try();var o,s=10;do{o=false;eliminate_spurious_blocks(e);if(t.option("dead_code")){eliminate_dead_code(e,t)}if(t.option("if_return")){handle_if_return(e,t)}if(t.sequences_limit>0){sequencesize(e,t);sequencesize_2(e,t)}if(t.option("join_vars")){join_consecutive_vars(e)}if(t.option("collapse_vars")){collapse(e,t)}}while(o&&s-- >0);function find_loop_scope_try(){var e=t.self(),r=0;do{if(e instanceof we||e instanceof Oe){r++}else if(e instanceof j){n=true}else if(e instanceof ie){a=e;break}else if(e instanceof Re){i=true}}while(e=t.parent(r++))}function collapse(e,t){if(a.pinned())return e;var s;var u=[];var l=e.length;var c=new TreeTransformer((function(e){if(T)return e;if(!k){if(e!==p[_])return e;_++;if(_1)||e instanceof j&&!(e instanceof J)||e instanceof ve||e instanceof Re||e instanceof ne||e instanceof Se||e instanceof Ue||e instanceof _t||n instanceof J&&e!==n.init||!y&&(e instanceof Pt&&!e.is_declared(t)&&!Ln.has(e))||e instanceof Pt&&n instanceof ze&&has_annotation(n,on)){T=true;return e}if(!E&&(!b||!y)&&(n instanceof Qe&&On.has(n.operator)&&n.left!==e||n instanceof Je&&n.condition!==e||n instanceof Ae&&n.condition!==e)){E=n}if(C&&!(e instanceof bt)&&g.equivalent_to(e)){if(E){T=true;return e}if(is_lhs(e,n)){if(h)x++;return e}else{x++;if(h&&d instanceof Pe)return e}o=T=true;if(d instanceof Ze){return make_node($e,d,d)}if(d instanceof Pe){var r=d.name.definition();var a=d.value;if(r.references.length-r.replaced==1&&!t.exposed(r)){r.replaced++;if(A&&is_identifier_atom(a)){return a.transform(t)}else{return maintain_this_binding(n,e,a)}}return make_node(et,d,{operator:"=",logical:false,left:make_node(Pt,d.name,d.name),right:a})}clear_flag(d,An);return d}var s;if(e instanceof ze||e instanceof me&&(D||g instanceof He||may_modify(g))||e instanceof He&&(D||e.expression.may_throw_on_access(t))||e instanceof Pt&&(v.get(e.name)||D&&may_modify(e))||e instanceof Pe&&e.value&&(v.has(e.name.name)||D&&may_modify(e.name))||(s=is_lhs(e.left,e))&&(s instanceof He||v.has(s.name))||S&&(i?e.has_side_effects(t):side_effects_external(e))){m=e;if(e instanceof ie)T=true}return handle_custom_scan_order(e)}),(function(e){if(T)return;if(m===e)T=true;if(E===e)E=null}));var f=new TreeTransformer((function(e){if(T)return e;if(!k){if(e!==p[_])return e;_++;if(_=0){if(l==0&&t.option("unused"))extract_args();var p=[];extract_candidates(e[l]);while(u.length>0){p=u.pop();var _=0;var d=p[p.length-1];var h=null;var m=null;var E=null;var g=get_lhs(d);if(!g||is_lhs_read_only(g)||g.has_side_effects(t))continue;var v=get_lvalues(d);var b=is_lhs_local(g);if(g instanceof Pt)v.set(g.name,false);var D=value_has_side_effects(d);var y=replace_all_symbols();var S=d.may_throw(t);var A=d.name instanceof kt;var k=A;var T=false,x=0,C=!s||!k;if(!C){for(var R=t.self().argnames.lastIndexOf(d.name)+1;!T&&Rx)x=false;else{T=false;_=0;k=A;for(var w=l;!T&&w!(e instanceof ae)))){var i=t.has_directive("use strict");if(i&&!member(i,n.body))i=false;var r=n.argnames.length;s=e.args.slice(r);var a=new Set;for(var o=r;--o>=0;){var l=n.argnames[o];var c=e.args[o];const r=l.definition&&l.definition();const p=r&&r.orig.length>1;if(p)continue;s.unshift(make_node(Pe,l,{name:l,value:c}));if(a.has(l.name))continue;a.add(l.name);if(l instanceof ae){var f=e.args.slice(o);if(f.every((e=>!has_overlapping_symbol(n,e,i)))){u.unshift([make_node(Pe,l,{name:l.expression,value:make_node(nt,e,{elements:f})})])}}else{if(!c){c=make_node($t,l).transform(t)}else if(c instanceof oe&&c.pinned()||has_overlapping_symbol(n,c,i)){c=null}if(c)u.unshift([make_node(Pe,l,{name:l,value:c})])}}}}function extract_candidates(e){p.push(e);if(e instanceof et){if(!e.left.has_side_effects(t)&&!(e.right instanceof Ye)){u.push(p.slice())}extract_candidates(e.right)}else if(e instanceof Qe){extract_candidates(e.left);extract_candidates(e.right)}else if(e instanceof ze&&!has_annotation(e,on)){extract_candidates(e.expression);e.args.forEach(extract_candidates)}else if(e instanceof Ce){extract_candidates(e.expression)}else if(e instanceof Je){extract_candidates(e.condition);extract_candidates(e.consequent);extract_candidates(e.alternative)}else if(e instanceof Fe){var n=e.definitions.length;var i=n-200;if(i<0)i=0;for(;i1&&!(e.name instanceof kt)||(i>1?mangleable_var(e):!t.exposed(n))){return make_node(Pt,e.name,e.name)}}else{const t=e instanceof et?e.left:e.expression;return!is_ref_of(t,St)&&!is_ref_of(t,At)&&t}}function get_rvalue(e){if(e instanceof et){return e.right}else{return e.value}}function get_lvalues(e){var n=new Map;if(e instanceof je)return n;var i=new TreeWalker((function(e){var r=e;while(r instanceof He)r=r.expression;if(r instanceof Pt||r instanceof Ut){n.set(r.name,n.get(r.name)||is_modified(t,i,e,e,0))}}));get_rvalue(e).walk(i);return n}function remove_candidate(n){if(n.name instanceof kt){var i=t.parent(),a=t.self().argnames;var o=a.indexOf(n.name);if(o<0){i.args.length=Math.min(i.args.length,a.length-1)}else{var s=i.args;if(s[o])s[o]=make_node(Ht,s[o],{value:0})}return true}var u=false;return e[l].transform(new TreeTransformer((function(e,t,i){if(u)return e;if(e===n||e.body===n){u=true;if(e instanceof Pe){e.value=e.name instanceof St?make_node($t,e.value):null;return e}return i?r.skip:null}}),(function(e){if(e instanceof Ge)switch(e.expressions.length){case 0:return null;case 1:return e.expressions[0]}})))}function is_lhs_local(e){while(e instanceof He)e=e.expression;return e instanceof Pt&&e.definition().scope===a&&!(n&&(v.has(e.name)||d instanceof je||d instanceof et&&!d.logical&&d.operator!="="))}function value_has_side_effects(e){if(e instanceof je)return Fn.has(e.operator);return get_rvalue(e).has_side_effects(t)}function replace_all_symbols(){if(D)return false;if(h)return true;if(g instanceof Pt){var e=g.definition();if(e.references.length-e.replaced==(d instanceof Pe?1:2)){return true}}return false}function may_modify(e){if(!e.definition)return true;var t=e.definition();if(t.orig.length==1&&t.orig[0]instanceof Tt)return false;if(t.scope.get_defun_scope()!==a)return true;return!t.references.every((e=>{var t=e.scope.get_defun_scope();if(t.TYPE=="Scope")t=t.parent_scope;return t===a}))}function side_effects_external(e,t){if(e instanceof et)return side_effects_external(e.left,true);if(e instanceof je)return side_effects_external(e.expression,true);if(e instanceof Pe)return e.value&&side_effects_external(e.value);if(t){if(e instanceof Xe)return side_effects_external(e.expression,true);if(e instanceof qe)return side_effects_external(e.expression,true);if(e instanceof Pt)return e.definition().scope!==a}return false}}function eliminate_spurious_blocks(e){var t=[];for(var n=0;n=0;){var s=e[a];var u=next_index(a);var l=e[u];if(r&&!l&&s instanceof Ee){if(!s.value){o=true;e.splice(a,1);continue}if(s.value instanceof $e&&s.value.operator=="void"){o=true;e[a]=make_node(G,s,{body:s.value.expression});continue}}if(s instanceof Ae){var c=aborts(s.body);if(can_merge_flow(c)){if(c.label){remove(c.label.thedef.references,c)}o=true;s=s.clone();s.condition=s.condition.negate(t);var f=as_statement_array_with_return(s.body,c);s.body=make_node(X,s,{body:as_statement_array(s.alternative).concat(extract_functions())});s.alternative=make_node(X,s,{body:f});e[a]=s.transform(t);continue}var c=aborts(s.alternative);if(can_merge_flow(c)){if(c.label){remove(c.label.thedef.references,c)}o=true;s=s.clone();s.body=make_node(X,s.body,{body:as_statement_array(s.body).concat(extract_functions())});var f=as_statement_array_with_return(s.alternative,c);s.alternative=make_node(X,s.alternative,{body:f});e[a]=s.transform(t);continue}}if(s instanceof Ae&&s.body instanceof Ee){var p=s.body.value;if(!p&&!s.alternative&&(r&&!l||l instanceof Ee&&!l.value)){o=true;e[a]=make_node(G,s.condition,{body:s.condition});continue}if(p&&!s.alternative&&l instanceof Ee&&l.value){o=true;s=s.clone();s.alternative=l;e[a]=s.transform(t);e.splice(u,1);continue}if(p&&!s.alternative&&(!l&&r&&i||l instanceof Ee)){o=true;s=s.clone();s.alternative=l||make_node(Ee,s,{value:null});e[a]=s.transform(t);if(l)e.splice(u,1);continue}var _=e[prev_index(a)];if(t.option("sequences")&&r&&!s.alternative&&_ instanceof Ae&&_.body instanceof Ee&&next_index(u)==e.length&&l instanceof G){o=true;s=s.clone();s.alternative=make_node(X,l,{body:[l,make_node(Ee,l,{value:null})]});e[a]=s.transform(t);e.splice(u,1);continue}}}function has_multiple_if_returns(e){var t=0;for(var n=e.length;--n>=0;){var i=e[n];if(i instanceof Ae&&i.body instanceof Ee){if(++t>1)return true}}return false}function is_return_void(e){return!e||e instanceof $e&&e.operator=="void"}function can_merge_flow(i){if(!i)return false;for(var o=a+1,s=e.length;o=0;){var i=e[n];if(!(i instanceof Ne&&declarations_only(i))){break}}return n}}function eliminate_dead_code(e,t){var n;var i=t.self();for(var r=0,a=0,s=e.length;r!e.value))}function sequencesize(e,t){if(e.length<2)return;var n=[],i=0;function push_seq(){if(!n.length)return;var t=make_sequence(n[0],n);e[i++]=make_node(G,t,{body:t});n=[]}for(var r=0,a=e.length;r=t.sequences_limit)push_seq();var u=s.body;if(n.length>0)u=u.drop_side_effect_free(t);if(u)merge_sequence(n,u)}else if(s instanceof Fe&&declarations_only(s)||s instanceof ce){e[i++]=s}else{push_seq();e[i++]=s}}push_seq();e.length=i;if(i!=a)o=true}function to_simple_statement(e,t){if(!(e instanceof X))return e;var n=null;for(var i=0,r=e.body.length;i{if(e instanceof ie)return true;if(e instanceof Qe&&e.operator==="in"){return nn}}));if(!e){if(a.init)a.init=cons_seq(a.init);else{a.init=i.body;n--;o=true}}}}else if(a instanceof ee){if(!(a.init instanceof Ie)&&!(a.init instanceof Me)){a.object=cons_seq(a.object)}}else if(a instanceof Ae){a.condition=cons_seq(a.condition)}else if(a instanceof ke){a.expression=cons_seq(a.expression)}else if(a instanceof ne){a.expression=cons_seq(a.expression)}}if(t.option("conditionals")&&a instanceof Ae){var s=[];var u=to_simple_statement(a.body,s);var l=to_simple_statement(a.alternative,s);if(u!==false&&l!==false&&s.length>0){var c=s.length;s.push(make_node(Ae,a,{condition:a.condition,body:u||make_node(W,a.body),alternative:l}));s.unshift(n,1);[].splice.apply(e,s);r+=c;n+=c+1;i=null;o=true;continue}}e[n++]=a;i=a instanceof G?a:null}e.length=n}function join_object_assignments(e,n){if(!(e instanceof Fe))return;var i=e.definitions[e.definitions.length-1];if(!(i.value instanceof it))return;var r;if(n instanceof et&&!n.logical){r=[n]}else if(n instanceof Ge){r=n.expressions.slice()}if(!r)return;var o=false;do{var s=r[0];if(!(s instanceof et))break;if(s.operator!="=")break;if(!(s.left instanceof He))break;var u=s.left.expression;if(!(u instanceof Pt))break;if(i.name.name!=u.name)break;if(!s.right.is_constant_expression(a))break;var l=s.left.property;if(l instanceof V){l=l.evaluate(t)}if(l instanceof V)break;l=""+l;var c=t.option("ecma")<2015&&t.has_directive("use strict")?function(e){return e.key!=l&&(e.key&&e.key.name!=l)}:function(e){return e.key&&e.key.name!=l};if(!i.value.properties.every(c))break;var f=i.value.properties.filter((function(e){return e.key===l}))[0];if(!f){i.value.properties.push(make_node(ot,s,{key:l,value:s.right}))}else{f.value=new Ge({start:f.start,expressions:[f.value.clone(),s.right.clone()],end:f.end})}r.shift();o=true}while(r.length);return o&&r}function join_consecutive_vars(e){var t;for(var n=0,i=-1,r=e.length;n{if(i instanceof Ne){i.remove_initializers();n.push(i);return true}if(i instanceof ce&&(i===t||!e.has_directive("use strict"))){n.push(i===t?i:make_node(Ne,i,{definitions:[make_node(Pe,i,{name:make_node(Dt,i.name,i.name),value:null})]}));return true}if(i instanceof Ue||i instanceof Be){n.push(i);return true}if(i instanceof ie){return true}}))}function get_value(e){if(e instanceof Kt){return e.getValue()}if(e instanceof $e&&e.operator=="void"&&e.expression instanceof Kt){return}return e}function is_undefined(e,t){return has_flag(e,yn)||e instanceof $t||e instanceof $e&&e.operator=="void"&&!e.expression.has_side_effects(t)}(function(e){V.DEFMETHOD("may_throw_on_access",(function(e){return!e.option("pure_getters")||this._dot_throw(e)}));function is_strict(e){return/strict/.test(e.option("pure_getters"))}e(V,is_strict);e(Yt,return_true);e($t,return_true);e(Kt,return_false);e(nt,return_false);e(it,(function(e){if(!is_strict(e))return false;for(var t=this.properties.length;--t>=0;)if(this.properties[t]._dot_throw(e))return true;return false}));e(_t,return_false);e(rt,return_false);e(ct,return_true);e(ae,(function(e){return this.expression._dot_throw(e)}));e(ue,return_false);e(le,return_false);e(Ze,return_false);e($e,(function(){return this.operator=="void"}));e(Qe,(function(e){return(this.operator=="&&"||this.operator=="||"||this.operator=="??")&&(this.left._dot_throw(e)||this.right._dot_throw(e))}));e(et,(function(e){if(this.logical)return true;return this.operator=="="&&this.right._dot_throw(e)}));e(Je,(function(e){return this.consequent._dot_throw(e)||this.alternative._dot_throw(e)}));e(Xe,(function(e){if(!is_strict(e))return false;if(this.property=="prototype"){return!(this.expression instanceof ue||this.expression instanceof _t)}return true}));e(Ye,(function(e){return this.expression._dot_throw(e)}));e(Ge,(function(e){return this.tail_node()._dot_throw(e)}));e(Pt,(function(e){if(this.name==="arguments")return false;if(has_flag(this,yn))return true;if(!is_strict(e))return false;if(is_undeclared_ref(this)&&this.is_declared(e))return false;if(this.is_immutable())return false;var t=this.fixed_value();return!t||t._dot_throw(e)}))})((function(e,t){e.DEFMETHOD("_dot_throw",t)}));(function(e){const t=makePredicate("! delete");const n=makePredicate("in instanceof == != === !== < <= >= >");e(V,return_false);e($e,(function(){return t.has(this.operator)}));e(Qe,(function(){return n.has(this.operator)||On.has(this.operator)&&this.left.is_boolean()&&this.right.is_boolean()}));e(Je,(function(){return this.consequent.is_boolean()&&this.alternative.is_boolean()}));e(et,(function(){return this.operator=="="&&this.right.is_boolean()}));e(Ge,(function(){return this.tail_node().is_boolean()}));e(tn,return_true);e(en,return_true)})((function(e,t){e.DEFMETHOD("is_boolean",t)}));(function(e){e(V,return_false);e(Ht,return_true);var t=makePredicate("+ - ~ ++ --");e(je,(function(){return t.has(this.operator)}));var n=makePredicate("- * / % & | ^ << >> >>>");e(Qe,(function(e){return n.has(this.operator)||this.operator=="+"&&this.left.is_number(e)&&this.right.is_number(e)}));e(et,(function(e){return n.has(this.operator.slice(0,-1))||this.operator=="="&&this.right.is_number(e)}));e(Ge,(function(e){return this.tail_node().is_number(e)}));e(Je,(function(e){return this.consequent.is_number(e)&&this.alternative.is_number(e)}))})((function(e,t){e.DEFMETHOD("is_number",t)}));(function(e){e(V,return_false);e(Gt,return_true);e(_e,return_true);e($e,(function(){return this.operator=="typeof"}));e(Qe,(function(e){return this.operator=="+"&&(this.left.is_string(e)||this.right.is_string(e))}));e(et,(function(e){return(this.operator=="="||this.operator=="+=")&&this.right.is_string(e)}));e(Ge,(function(e){return this.tail_node().is_string(e)}));e(Je,(function(e){return this.consequent.is_string(e)&&this.alternative.is_string(e)}))})((function(e,t){e.DEFMETHOD("is_string",t)}));var On=makePredicate("&& || ??");var Fn=makePredicate("delete ++ --");function is_lhs(e,t){if(t instanceof je&&Fn.has(t.operator))return t.expression;if(t instanceof et&&t.left===e)return e}(function(e){function to_node(e,t){if(e instanceof V)return make_node(e.CTOR,t,e);if(Array.isArray(e))return make_node(nt,t,{elements:e.map((function(e){return to_node(e,t)}))});if(e&&typeof e=="object"){var n=[];for(var i in e)if(HOP(e,i)){n.push(make_node(ot,t,{key:i,value:to_node(e[i],t)}))}return make_node(it,t,{properties:n})}return make_node_from_constant(e,t)}re.DEFMETHOD("resolve_defines",(function(e){if(!e.option("global_defs"))return this;this.figure_out_scope({ie8:e.option("ie8")});return this.transform(new TreeTransformer((function(t){var n=t._find_defs(e,"");if(!n)return;var i=0,r=t,a;while(a=this.parent(i++)){if(!(a instanceof He))break;if(a.expression!==r)break;r=a}if(is_lhs(r,a)){return}return n})))}));e(V,noop);e(Ye,(function(e,t){return this.expression._find_defs(e,t)}));e(Xe,(function(e,t){return this.expression._find_defs(e,"."+this.property+t)}));e(bt,(function(){if(!this.global())return}));e(Pt,(function(e,t){if(!this.global())return;var n=e.option("global_defs");var i=this.name+t;if(HOP(n,i))return to_node(n[i],this)}))})((function(e,t){e.DEFMETHOD("_find_defs",t)}));function best_of_expression(e,t){return e.size()>t.size()?t:e}function best_of_statement(e,t){return best_of_expression(make_node(G,e,{body:e}),make_node(G,t,{body:t})).body}function best_of(e,t,n){return(first_in_statement(e)?best_of_statement:best_of_expression)(t,n)}function convert_to_predicate(e){const t=new Map;for(var n of Object.keys(e)){t.set(n,makePredicate(e[n]))}return t}var Nn=["constructor","toString","valueOf"];var Mn=convert_to_predicate({Array:["indexOf","join","lastIndexOf","slice"].concat(Nn),Boolean:Nn,Function:Nn,Number:["toExponential","toFixed","toPrecision"].concat(Nn),Object:Nn,RegExp:["test"].concat(Nn),String:["charAt","charCodeAt","concat","indexOf","italics","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","trim"].concat(Nn)});var In=convert_to_predicate({Array:["isArray"],Math:["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","atan2","pow","max","min"],Number:["isFinite","isNaN"],Object:["create","getOwnPropertyDescriptor","getOwnPropertyNames","getPrototypeOf","isExtensible","isFrozen","isSealed","keys"],String:["fromCharCode"]});(function(e){V.DEFMETHOD("evaluate",(function(e){if(!e.option("evaluate"))return this;var t=this._eval(e,1);if(!t||t instanceof RegExp)return t;if(typeof t=="function"||typeof t=="object")return this;return t}));var t=makePredicate("! ~ - + void");V.DEFMETHOD("is_constant",(function(){if(this instanceof Kt){return!(this instanceof Wt)}else{return this instanceof $e&&this.expression instanceof Kt&&t.has(this.operator)}}));e(U,(function(){throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]",this.start))}));e(oe,return_this);e(_t,return_this);e(V,return_this);e(Kt,(function(){return this.getValue()}));e(Xt,return_this);e(Wt,(function(e){let t=e.evaluated_regexps.get(this);if(t===undefined){try{t=(0,eval)(this.print_to_string())}catch(e){t=null}e.evaluated_regexps.set(this,t)}return t||this}));e(_e,(function(){if(this.segments.length!==1)return this;return this.segments[0].value}));e(ue,(function(e){if(e.option("unsafe")){var fn=function(){};fn.node=this;fn.toString=()=>this.print_to_string();return fn}return this}));e(nt,(function(e,t){if(e.option("unsafe")){var n=[];for(var i=0,r=this.elements.length;itypeof e==="object"||typeof e==="function"||typeof e==="symbol";e(Qe,(function(e,t){if(!i.has(this.operator))t++;var n=this.left._eval(e,t);if(n===this.left)return this;var a=this.right._eval(e,t);if(a===this.right)return this;var o;if(n!=null&&a!=null&&r.has(this.operator)&&has_identity(n)&&has_identity(a)&&typeof n===typeof a){return this}switch(this.operator){case"&&":o=n&&a;break;case"||":o=n||a;break;case"??":o=n!=null?n:a;break;case"|":o=n|a;break;case"&":o=n&a;break;case"^":o=n^a;break;case"+":o=n+a;break;case"*":o=n*a;break;case"**":o=Math.pow(n,a);break;case"/":o=n/a;break;case"%":o=n%a;break;case"-":o=n-a;break;case"<<":o=n<>":o=n>>a;break;case">>>":o=n>>>a;break;case"==":o=n==a;break;case"===":o=n===a;break;case"!=":o=n!=a;break;case"!==":o=n!==a;break;case"<":o=n":o=n>a;break;case">=":o=n>=a;break;default:return this}if(isNaN(o)&&e.find_parent(ne)){return this}return o}));e(Je,(function(e,t){var n=this.condition._eval(e,t);if(n===this.condition)return this;var i=n?this.consequent:this.alternative;var r=i._eval(e,t);return r===i?this:r}));const a=new Set;e(Pt,(function(e,t){if(a.has(this))return this;var n=this.fixed_value();if(!n)return this;a.add(this);const i=n._eval(e,t);a.delete(this);if(i===n)return this;if(i&&typeof i=="object"){var r=this.definition().escaped;if(r&&t>r)return this}return i}));var o={Array:Array,Math:Math,Number:Number,Object:Object,String:String};var s=convert_to_predicate({Math:["E","LN10","LN2","LOG2E","LOG10E","PI","SQRT1_2","SQRT2"],Number:["MAX_VALUE","MIN_VALUE","NaN","NEGATIVE_INFINITY","POSITIVE_INFINITY"]});const u=new Set(["dotAll","global","ignoreCase","multiline","sticky","unicode"]);e(He,(function(e,t){if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")){var n=this.property;if(n instanceof V){n=n._eval(e,t);if(n===this.property)return this}var i=this.expression;var r;if(is_undeclared_ref(i)){var a;var l=i.name==="hasOwnProperty"&&n==="call"&&(a=e.parent()&&e.parent().args)&&(a&&a[0]&&a[0].evaluate(e));l=l instanceof Xe?l.expression:l;if(l==null||l.thedef&&l.thedef.undeclared){return this.clone()}var c=s.get(i.name);if(!c||!c.has(n))return this;r=o[i.name]}else{r=i._eval(e,t+1);if(r instanceof RegExp){if(n=="source"){return regexp_source_fix(r.source)}else if(n=="flags"||u.has(n)){return r[n]}}if(!r||r===i||!HOP(r,n))return this;if(typeof r=="function")switch(n){case"name":return r.node.name?r.node.name.name:"";case"length":return r.node.length_property();default:return this}}return r[n]}return this}));e(Ye,(function(e,t){const n=this.expression._eval(e,t);return n===this.expression?this:n}));e(ze,(function(e,t){var n=this.expression;if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")&&n instanceof He){var i=n.property;if(i instanceof V){i=i._eval(e,t);if(i===n.property)return this}var r;var a=n.expression;if(is_undeclared_ref(a)){var s=a.name==="hasOwnProperty"&&i==="call"&&(this.args[0]&&this.args[0].evaluate(e));s=s instanceof Xe?s.expression:s;if(s==null||s.thedef&&s.thedef.undeclared){return this.clone()}var u=In.get(a.name);if(!u||!u.has(i))return this;r=o[a.name]}else{r=a._eval(e,t+1);if(r===a||!r)return this;var l=Mn.get(r.constructor.name);if(!l||!l.has(i))return this}var c=[];for(var f=0,p=this.args.length;f";return n;case"<":n.operator=">=";return n;case">=":n.operator="<";return n;case">":n.operator="<=";return n}}switch(i){case"==":n.operator="!=";return n;case"!=":n.operator="==";return n;case"===":n.operator="!==";return n;case"!==":n.operator="===";return n;case"&&":n.operator="||";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"||":n.operator="&&";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"??":n.right=n.right.negate(e);return best(this,n,t)}return basic_negation(this)}))})((function(e,t){e.DEFMETHOD("negate",(function(e,n){return t.call(this,e,n)}))}));var Pn=makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");ze.DEFMETHOD("is_callee_pure",(function(e){if(e.option("unsafe")){var t=this.expression;var n=this.args&&this.args[0]&&this.args[0].evaluate(e);if(t.expression&&t.expression.name==="hasOwnProperty"&&(n==null||n.thedef&&n.thedef.undeclared)){return false}if(is_undeclared_ref(t)&&Pn.has(t.name))return true;let i;if(t instanceof Xe&&is_undeclared_ref(t.expression)&&(i=In.get(t.expression.name))&&i.has(t.property)){return true}}return!!has_annotation(this,rn)||!e.pure_funcs(this)}));V.DEFMETHOD("is_call_pure",return_false);Xe.DEFMETHOD("is_call_pure",(function(e){if(!e.option("unsafe"))return;const t=this.expression;let n;if(t instanceof nt){n=Mn.get("Array")}else if(t.is_boolean()){n=Mn.get("Boolean")}else if(t.is_number(e)){n=Mn.get("Number")}else if(t instanceof Wt){n=Mn.get("RegExp")}else if(t.is_string(e)){n=Mn.get("String")}else if(!this.may_throw_on_access(e)){n=Mn.get("Object")}return n&&n.has(this.property)}));const Ln=new Set(["Number","String","Array","Object","Function","Promise"]);(function(e){e(V,return_true);e(W,return_false);e(Kt,return_false);e(Ut,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].has_side_effects(t))return true;return false}e(H,(function(e){return any(this.body,e)}));e(ze,(function(e){if(!this.is_callee_pure(e)&&(!this.expression.is_call_pure(e)||this.expression.has_side_effects(e))){return true}return any(this.args,e)}));e(ke,(function(e){return this.expression.has_side_effects(e)||any(this.body,e)}));e(Ce,(function(e){return this.expression.has_side_effects(e)||any(this.body,e)}));e(Re,(function(e){return any(this.body,e)||this.bcatch&&this.bcatch.has_side_effects(e)||this.bfinally&&this.bfinally.has_side_effects(e)}));e(Ae,(function(e){return this.condition.has_side_effects(e)||this.body&&this.body.has_side_effects(e)||this.alternative&&this.alternative.has_side_effects(e)}));e(Y,(function(e){return this.body.has_side_effects(e)}));e(G,(function(e){return this.body.has_side_effects(e)}));e(oe,return_false);e(_t,(function(e){if(this.extends&&this.extends.has_side_effects(e)){return true}return any(this.properties,e)}));e(Qe,(function(e){return this.left.has_side_effects(e)||this.right.has_side_effects(e)}));e(et,return_true);e(Je,(function(e){return this.condition.has_side_effects(e)||this.consequent.has_side_effects(e)||this.alternative.has_side_effects(e)}));e(je,(function(e){return Fn.has(this.operator)||this.expression.has_side_effects(e)}));e(Pt,(function(e){return!this.is_declared(e)&&!Ln.has(this.name)}));e(Ct,return_false);e(bt,return_false);e(it,(function(e){return any(this.properties,e)}));e(rt,(function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.value&&this.value.has_side_effects(e)}));e(dt,(function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.static&&this.value&&this.value.has_side_effects(e)}));e(ft,(function(e){return this.computed_key()&&this.key.has_side_effects(e)}));e(ct,(function(e){return this.computed_key()&&this.key.has_side_effects(e)}));e(lt,(function(e){return this.computed_key()&&this.key.has_side_effects(e)}));e(nt,(function(e){return any(this.elements,e)}));e(Xe,(function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)}));e(qe,(function(e){if(this.optional&&is_nullish(this.expression,e)){return false}return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)||this.property.has_side_effects(e)}));e(Ye,(function(e){return this.expression.has_side_effects(e)}));e(Ge,(function(e){return any(this.expressions,e)}));e(Fe,(function(e){return any(this.definitions,e)}));e(Pe,(function(){return this.value}));e(de,return_false);e(_e,(function(e){return any(this.segments,e)}))})((function(e,t){e.DEFMETHOD("has_side_effects",t)}));(function(e){e(V,return_true);e(Kt,return_false);e(W,return_false);e(oe,return_false);e(bt,return_false);e(Ut,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].may_throw(t))return true;return false}e(_t,(function(e){if(this.extends&&this.extends.may_throw(e))return true;return any(this.properties,e)}));e(nt,(function(e){return any(this.elements,e)}));e(et,(function(e){if(this.right.may_throw(e))return true;if(!e.has_directive("use strict")&&this.operator=="="&&this.left instanceof Pt){return false}return this.left.may_throw(e)}));e(Qe,(function(e){return this.left.may_throw(e)||this.right.may_throw(e)}));e(H,(function(e){return any(this.body,e)}));e(ze,(function(e){if(this.optional&&is_nullish(this.expression,e))return false;if(any(this.args,e))return true;if(this.is_callee_pure(e))return false;if(this.expression.may_throw(e))return true;return!(this.expression instanceof oe)||any(this.expression.body,e)}));e(Ce,(function(e){return this.expression.may_throw(e)||any(this.body,e)}));e(Je,(function(e){return this.condition.may_throw(e)||this.consequent.may_throw(e)||this.alternative.may_throw(e)}));e(Fe,(function(e){return any(this.definitions,e)}));e(Ae,(function(e){return this.condition.may_throw(e)||this.body&&this.body.may_throw(e)||this.alternative&&this.alternative.may_throw(e)}));e(Y,(function(e){return this.body.may_throw(e)}));e(it,(function(e){return any(this.properties,e)}));e(rt,(function(e){return this.value?this.value.may_throw(e):false}));e(dt,(function(e){return this.computed_key()&&this.key.may_throw(e)||this.static&&this.value&&this.value.may_throw(e)}));e(ft,(function(e){return this.computed_key()&&this.key.may_throw(e)}));e(ct,(function(e){return this.computed_key()&&this.key.may_throw(e)}));e(lt,(function(e){return this.computed_key()&&this.key.may_throw(e)}));e(Ee,(function(e){return this.value&&this.value.may_throw(e)}));e(Ge,(function(e){return any(this.expressions,e)}));e(G,(function(e){return this.body.may_throw(e)}));e(Xe,(function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)}));e(qe,(function(e){if(this.optional&&is_nullish(this.expression,e))return false;return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)||this.property.may_throw(e)}));e(Ye,(function(e){return this.expression.may_throw(e)}));e(ke,(function(e){return this.expression.may_throw(e)||any(this.body,e)}));e(Pt,(function(e){return!this.is_declared(e)&&!Ln.has(this.name)}));e(Ct,return_false);e(Re,(function(e){return this.bcatch?this.bcatch.may_throw(e):any(this.body,e)||this.bfinally&&this.bfinally.may_throw(e)}));e(je,(function(e){if(this.operator=="typeof"&&this.expression instanceof Pt)return false;return this.expression.may_throw(e)}));e(Pe,(function(e){if(!this.value)return false;return this.value.may_throw(e)}))})((function(e,t){e.DEFMETHOD("may_throw",t)}));(function(e){function all_refs_local(e){let t=true;walk(this,(n=>{if(n instanceof Pt){if(has_flag(this,Sn)){t=false;return nn}var i=n.definition();if(member(i,this.enclosed)&&!this.variables.has(i.name)){if(e){var r=e.find_variable(n);if(i.undeclared?!r:r===i){t="f";return true}}t=false;return nn}return true}if(n instanceof Ut&&this instanceof le){t=false;return nn}}));return t}e(V,return_false);e(Kt,return_true);e(_t,(function(e){if(this.extends&&!this.extends.is_constant_expression(e)){return false}for(const t of this.properties){if(t.computed_key()&&!t.key.is_constant_expression(e)){return false}if(t.static&&t.value&&!t.value.is_constant_expression(e)){return false}}return all_refs_local.call(this,e)}));e(oe,all_refs_local);e(je,(function(){return this.expression.is_constant_expression()}));e(Qe,(function(){return this.left.is_constant_expression()&&this.right.is_constant_expression()}));e(nt,(function(){return this.elements.every((e=>e.is_constant_expression()))}));e(it,(function(){return this.properties.every((e=>e.is_constant_expression()))}));e(rt,(function(){return!!(!(this.key instanceof V)&&this.value&&this.value.is_constant_expression())}))})((function(e,t){e.DEFMETHOD("is_constant_expression",t)}));function aborts(e){return e&&e.aborts()}(function(e){e(U,return_null);e(he,return_this);function block_aborts(){for(var e=0;e{if(e instanceof bt){const n=e.definition();if((t||n.global)&&!o.has(n.id)){o.set(n.id,n)}}}))}if(n.value){if(n.name instanceof fe){n.walk(f)}else{var r=n.name.definition();map_add(l,r.id,n.value);if(!r.chained&&n.name.fixed_value()===n.value){s.set(r.id,n)}}if(n.value.has_side_effects(e)){n.value.walk(f)}}}));return true}return scan_ref_scoped(r,a)}));t.walk(f);f=new TreeWalker(scan_ref_scoped);o.forEach((function(e){var t=l.get(e.id);if(t)t.forEach((function(e){e.walk(f)}))}));var p=new TreeTransformer((function before(l,f,_){var d=p.parent();if(i){const e=a(l);if(e instanceof Pt){var h=e.definition();var m=o.has(h.id);if(l instanceof et){if(!m||s.has(h.id)&&s.get(h.id)!==l){return maintain_this_binding(d,l,l.right.transform(p))}}else if(!m)return _?r.skip:make_node(Ht,l,{value:0})}}if(c!==t)return;var h;if(l.name&&(l instanceof Et&&!keep_name(e.option("keep_classnames"),(h=l.name.definition()).name)||l instanceof ue&&!keep_name(e.option("keep_fnames"),(h=l.name.definition()).name))){if(!o.has(h.id)||h.orig.length>1)l.name=null}if(l instanceof oe&&!(l instanceof se)){var E=!e.option("keep_fargs");for(var g=l.argnames,v=g.length;--v>=0;){var b=g[v];if(b instanceof ae){b=b.expression}if(b instanceof tt){b=b.left}if(!(b instanceof fe)&&!o.has(b.definition().id)){set_flag(b,vn);if(E){g.pop()}}else{E=false}}}if((l instanceof ce||l instanceof mt)&&l!==t){const t=l.name.definition();let i=t.global&&!n||o.has(t.id);if(!i){t.eliminated++;if(l instanceof mt){const t=l.drop_side_effect_free(e);if(t){return make_node(G,l,{body:t})}}return _?r.skip:make_node(W,l)}}if(l instanceof Fe&&!(d instanceof ee&&d.init===l)){var D=!(d instanceof re)&&!(l instanceof Ne);var y=[],S=[],A=[];var k=[];l.definitions.forEach((function(t){if(t.value)t.value=t.value.transform(p);var n=t.name instanceof fe;var r=n?new SymbolDef(null,{name:""}):t.name.definition();if(D&&r.global)return A.push(t);if(!(i||D)||n&&(t.name.names.length||t.name.is_array||e.option("pure_getters")!=true)||o.has(r.id)){if(t.value&&s.has(r.id)&&s.get(r.id)!==t){t.value=t.value.drop_side_effect_free(e)}if(t.name instanceof Dt){var a=u.get(r.id);if(a.length>1&&(!t.value||r.orig.indexOf(t.name)>r.eliminated)){if(t.value){var c=make_node(Pt,t.name,t.name);r.references.push(c);var f=make_node(et,t,{operator:"=",logical:false,left:c,right:t.value});if(s.get(r.id)===t){s.set(r.id,f)}k.push(f.transform(p))}remove(a,t);r.eliminated++;return}}if(t.value){if(k.length>0){if(A.length>0){k.push(t.value);t.value=make_sequence(t.value,k)}else{y.push(make_node(G,l,{body:make_sequence(l,k)}))}k=[]}A.push(t)}else{S.push(t)}}else if(r.orig[0]instanceof Ft){var _=t.value&&t.value.drop_side_effect_free(e);if(_)k.push(_);t.value=null;S.push(t)}else{var _=t.value&&t.value.drop_side_effect_free(e);if(_){k.push(_)}r.eliminated++}}));if(S.length>0||A.length>0){l.definitions=S.concat(A);y.push(l)}if(k.length>0){y.push(make_node(G,l,{body:make_sequence(l,k)}))}switch(y.length){case 0:return _?r.skip:make_node(W,l);case 1:return y[0];default:return _?r.splice(y):make_node(X,l,{body:y})}}if(l instanceof J){f(l,this);var T;if(l.init instanceof X){T=l.init;l.init=T.body.pop();T.body.push(l)}if(l.init instanceof G){l.init=l.init.body}else if(is_empty(l.init)){l.init=null}return!T?l:_?r.splice(T.body):T}if(l instanceof Y&&l.body instanceof J){f(l,this);if(l.body instanceof X){var T=l.body;l.body=T.body.pop();T.body.push(l);return _?r.splice(T.body):T}return l}if(l instanceof X){f(l,this);if(_&&l.body.every(can_be_evicted_from_block)){return r.splice(l.body)}return l}if(l instanceof ie){const e=c;c=l;f(l,this);c=e;return l}}));t.transform(p);function scan_ref_scoped(e,n){var i;const r=a(e);if(r instanceof Pt&&!is_ref_of(e.left,yt)&&t.variables.get(r.name)===(i=r.definition())){if(e instanceof et){e.right.walk(f);if(!i.chained&&e.left.fixed_value()===e.right){s.set(i.id,e)}}return true}if(e instanceof Pt){i=e.definition();if(!o.has(i.id)){o.set(i.id,i);if(i.orig[0]instanceof Ft){const e=i.scope.is_block_scope()&&i.scope.get_defun_scope().variables.get(i.name);if(e)o.set(e.id,e)}}return true}if(e instanceof ie){var u=c;c=e;n();c=u;return true}}}));ie.DEFMETHOD("hoist_declarations",(function(e){var t=this;if(e.has_directive("use asm"))return t;if(!Array.isArray(t.body))return t;var n=e.option("hoist_funs");var i=e.option("hoist_vars");if(n||i){var r=[];var a=[];var o=new Map,s=0,u=0;walk(t,(e=>{if(e instanceof ie&&e!==t)return true;if(e instanceof Ne){++u;return true}}));i=i&&u>1;var l=new TreeTransformer((function before(u){if(u!==t){if(u instanceof K){r.push(u);return make_node(W,u)}if(n&&u instanceof ce&&!(l.parent()instanceof Ue)&&l.parent()===t){a.push(u);return make_node(W,u)}if(i&&u instanceof Ne&&!u.definitions.some((e=>e.name instanceof fe))){u.definitions.forEach((function(e){o.set(e.name.name,e);++s}));var c=u.to_assignments(e);var f=l.parent();if(f instanceof ee&&f.init===u){if(c==null){var p=u.definitions[0].name;return make_node(Pt,p,p)}return c}if(f instanceof J&&f.init===u){return c}if(!c)return make_node(W,u);return make_node(G,u,{body:c})}if(u instanceof ie)return u}}));t=t.transform(l);if(s>0){var c=[];const e=t instanceof oe;const n=e?t.args_as_names():null;o.forEach(((t,i)=>{if(e&&n.some((e=>e.name===t.name.name))){o.delete(i)}else{t=t.clone();t.value=null;c.push(t);o.set(i,t)}}));if(c.length>0){for(var f=0;fe instanceof ae||e.computed_key()))){s(o,this);const e=new Map;const n=[];c.properties.forEach((({key:i,value:r})=>{const s=find_scope(a);const l=t.create_symbol(u.CTOR,{source:u,scope:s,conflict_scopes:new Set([s,...u.definition().references.map((e=>e.scope))]),tentative_name:u.name+"_"+i});e.set(String(i),l.definition());n.push(make_node(Pe,o,{name:l,value:r}))}));i.set(l.id,e);return r.splice(n)}}else if(o instanceof He&&o.expression instanceof Pt){const e=i.get(o.expression.definition().id);if(e){const t=e.get(String(get_value(o.property)));const n=make_node(Pt,o,{name:t.name,scope:o.expression.scope,thedef:t});n.reference({});return n}}}));return t.transform(a)}));(function(e){function trim(e,t,n){var i=e.length;if(!i)return null;var r=[],a=false;for(var o=0;o0){o[0].body=a.concat(o[0].body)}e.body=o;while(n=o[o.length-1]){var d=n.body[n.body.length-1];if(d instanceof be&&t.loopcontrol_target(d)===e)n.body.pop();if(n.body.length||n instanceof Ce&&(s||n.expression.has_side_effects(t)))break;if(o.pop()===s)s=null}if(o.length==0){return make_node(X,e,{body:a.concat(make_node(G,e.expression,{body:e.expression}))}).optimize(t)}if(o.length==1&&(o[0]===u||o[0]===s)){var h=false;var m=new TreeWalker((function(t){if(h||t instanceof oe||t instanceof G)return true;if(t instanceof be&&m.loopcontrol_target(t)===e)h=true}));e.walk(m);if(!h){var E=o[0].body.slice();var f=o[0].expression;if(f)E.unshift(make_node(G,f,{body:f}));E.unshift(make_node(G,e.expression,{body:e.expression}));return make_node(X,e,{body:E}).optimize(t)}}return e;function eliminate_branch(e,n){if(n&&!aborts(n)){n.body=n.body.concat(e.body)}else{trim_unreachable_code(t,e,a)}}}));def_optimize(Re,(function(e,t){tighten_body(e.body,t);if(e.bcatch&&e.bfinally&&e.bfinally.body.every(is_empty))e.bfinally=null;if(t.option("dead_code")&&e.body.every(is_empty)){var n=[];if(e.bcatch){trim_unreachable_code(t,e.bcatch,n)}if(e.bfinally)n.push(...e.bfinally.body);return make_node(X,e,{body:n}).optimize(t)}return e}));Fe.DEFMETHOD("remove_initializers",(function(){var e=[];this.definitions.forEach((function(t){if(t.name instanceof bt){t.value=null;e.push(t)}else{walk(t.name,(n=>{if(n instanceof bt){e.push(make_node(Pe,t,{name:n,value:null}))}}))}}));this.definitions=e}));Fe.DEFMETHOD("to_assignments",(function(e){var t=e.option("reduce_vars");var n=[];for(const e of this.definitions){if(e.value){var i=make_node(Pt,e.name,e.name);n.push(make_node(et,e,{operator:"=",logical:false,left:i,right:e.value}));if(t)i.definition().fixed=false}else if(e.value){var r=make_node(Pe,e,{name:e.name,value:e.value});var a=make_node(Ne,e,{definitions:[r]});n.push(a)}const o=e.name.definition();o.eliminated++;o.replaced--}if(n.length==0)return null;return make_sequence(this,n)}));def_optimize(Fe,(function(e){if(e.definitions.length==0)return make_node(W,e);return e}));def_optimize(Pe,(function(e,t){if(e.name instanceof At&&e.value!=null&&is_undefined(e.value,t)){e.value=null}return e}));def_optimize(Be,(function(e){return e}));function retain_top_func(e,t){return t.top_retain&&e instanceof ce&&has_flag(e,xn)&&e.name&&t.top_retain(e.name)}def_optimize(ze,(function(e,t){var n=e.expression;var i=n;inline_array_like_spread(e.args);var r=e.args.every((e=>!(e instanceof ae)));if(t.option("reduce_vars")&&i instanceof Pt&&!has_annotation(e,on)){const e=i.fixed_value();if(!retain_top_func(e,t)){i=e}}if(e.optional&&is_nullish(i,t)){return make_node($t,e)}var a=i instanceof oe;if(a&&i.pinned())return e;if(t.option("unused")&&r&&a&&!i.uses_arguments){var o=0,s=0;for(var u=0,l=e.args.length;u=i.argnames.length;if(f||has_flag(i.argnames[u],vn)){var c=e.args[u].drop_side_effect_free(t);if(c){e.args[o++]=c}else if(!f){e.args[o++]=make_node(Ht,e.args[u],{value:0});continue}}else{e.args[o++]=e.args[u]}s=o}e.args.length=s}if(t.option("unsafe")){if(is_undeclared_ref(n))switch(n.name){case"Array":if(e.args.length!=1){return make_node(nt,e,{elements:e.args}).optimize(t)}else if(e.args[0]instanceof Ht&&e.args[0].value<=11){const t=[];for(let n=0;n=1&&e.args.length<=2&&e.args.every((e=>{var n=e.evaluate(t);p.push(n);return e!==n}))){let[n,i]=p;n=regexp_source_fix(new RegExp(n).source);const r=make_node(Wt,e,{value:{source:n,flags:i}});if(r._eval(t)!==r){return r}}break}else if(n instanceof Xe)switch(n.property){case"toString":if(e.args.length==0&&!n.expression.may_throw_on_access(t)){return make_node(Qe,e,{left:make_node(Gt,e,{value:""}),operator:"+",right:n.expression}).optimize(t)}break;case"join":if(n.expression instanceof nt)e:{var _;if(e.args.length>0){_=e.args[0].evaluate(t);if(_===e.args[0])break e}var d=[];var h=[];for(var u=0,l=n.expression.elements.length;u0){d.push(make_node(Gt,e,{value:h.join(_)}));h.length=0}d.push(m)}}if(h.length>0){d.push(make_node(Gt,e,{value:h.join(_)}))}if(d.length==0)return make_node(Gt,e,{value:""});if(d.length==1){if(d[0].is_string(t)){return d[0]}return make_node(Qe,d[0],{operator:"+",left:make_node(Gt,e,{value:""}),right:d[0]})}if(_==""){var g;if(d[0].is_string(t)||d[1].is_string(t)){g=d.shift()}else{g=make_node(Gt,e,{value:""})}return d.reduce((function(e,t){return make_node(Qe,t,{operator:"+",left:e,right:t})}),g).optimize(t)}var c=e.clone();c.expression=c.expression.clone();c.expression.expression=c.expression.expression.clone();c.expression.expression.elements=d;return best_of(t,e,c)}break;case"charAt":if(n.expression.is_string(t)){var v=e.args[0];var b=v?v.evaluate(t):0;if(b!==v){return make_node(qe,n,{expression:n.expression,property:make_node_from_constant(b|0,v||n)}).optimize(t)}}break;case"apply":if(e.args.length==2&&e.args[1]instanceof nt){var D=e.args[1].elements.slice();D.unshift(e.args[0]);return make_node(ze,e,{expression:make_node(Xe,n,{expression:n.expression,optional:false,property:"call"}),args:D}).optimize(t)}break;case"call":var y=n.expression;if(y instanceof Pt){y=y.fixed_value()}if(y instanceof oe&&!y.contains_this()){return(e.args.length?make_sequence(this,[e.args[0],make_node(ze,e,{expression:n.expression,args:e.args.slice(1)})]):make_node(ze,e,{expression:n.expression,args:[]})).optimize(t)}break}}if(t.option("unsafe_Function")&&is_undeclared_ref(n)&&n.name=="Function"){if(e.args.length==0)return make_node(ue,e,{argnames:[],body:[]}).optimize(t);if(e.args.every((e=>e instanceof Gt))){try{var S="n(function("+e.args.slice(0,-1).map((function(e){return e.value})).join(",")+"){"+e.args[e.args.length-1].value+"})";var A=parse(S);var k={ie8:t.option("ie8")};A.figure_out_scope(k);var T=new Compressor(t.options,{mangle_options:t.mangle_options});A=A.transform(T);A.figure_out_scope(k);En.reset();A.compute_char_frequency(k);A.mangle_names(k);var x;walk(A,(e=>{if(is_func_expr(e)){x=e;return nn}}));var S=OutputStream();X.prototype._codegen.call(x,x,S);e.args=[make_node(Gt,e,{value:x.argnames.map((function(e){return e.print_to_string()})).join(",")}),make_node(Gt,e.args[e.args.length-1],{value:S.get().replace(/^{|}$/g,"")})];return e}catch(e){if(!(e instanceof JS_Parse_Error)){throw e}}}}var C=a&&i.body[0];var R=a&&!i.is_generator&&!i.async;var w=R&&t.option("inline")&&!e.is_callee_pure(t);if(w&&C instanceof Ee){let n=C.value;if(!n||n.is_constant_expression()){if(n){n=n.clone(true)}else{n=make_node($t,e)}const i=e.args.concat(n);return make_sequence(e,i).optimize(t)}if(i.argnames.length===1&&i.argnames[0]instanceof kt&&e.args.length<2&&n instanceof Pt&&n.name===i.argnames[0].name){const n=(e.args[0]||make_node($t)).optimize(t);let i;if(n instanceof He&&(i=t.parent())instanceof ze&&i.expression===e){return make_sequence(e,[make_node(Ht,e,{value:0}),n])}return n}}if(w){var O,F,N=-1;let a;let o;let s;if(r&&!i.uses_arguments&&!(t.parent()instanceof _t)&&!(i.name&&i instanceof ue)&&(o=can_flatten_body(C))&&(n===i||has_annotation(e,an)||t.option("unused")&&(a=n.definition()).references.length==1&&!recursive_ref(t,a)&&i.is_constant_expression(n.scope))&&!has_annotation(e,rn|on)&&!i.contains_this()&&can_inject_symbols()&&(s=find_scope(t))&&!scope_encloses_variables_in_this_scope(s,i)&&!function in_default_assign(){let e=0;let n;while(n=t.parent(e++)){if(n instanceof tt)return true;if(n instanceof H)break}return false}()&&!(O instanceof _t)){set_flag(i,kn);s.add_child_scope(i);return make_sequence(e,flatten_fn(o)).optimize(t)}}if(w&&has_annotation(e,an)){set_flag(i,kn);i=make_node(i.CTOR===ce?ue:i.CTOR,i,i);i.figure_out_scope({},{parent_scope:find_scope(t),toplevel:t.get_toplevel()});return make_node(ze,e,{expression:i,args:e.args}).optimize(t)}const M=R&&t.option("side_effects")&&i.body.every(is_empty);if(M){var D=e.args.concat(make_node($t,e));return make_sequence(e,D).optimize(t)}if(t.option("negate_iife")&&t.parent()instanceof G&&is_iife_call(e)){return e.negate(t,true)}var I=e.evaluate(t);if(I!==e){I=make_node_from_constant(I,e).optimize(t);return best_of(t,I,e)}return e;function return_value(t){if(!t)return make_node($t,e);if(t instanceof Ee){if(!t.value)return make_node($t,e);return t.value.clone(true)}if(t instanceof G){return make_node($e,t,{operator:"void",expression:t.body.clone(true)})}}function can_flatten_body(e){var n=i.body;var r=n.length;if(t.option("inline")<3){return r==1&&return_value(e)}e=null;for(var a=0;a!e.value))){return false}}else if(e){return false}else if(!(o instanceof W)){e=o}}return return_value(e)}function can_inject_args(e,t){for(var n=0,r=i.argnames.length;n=0;){var s=a.definitions[o].name;if(s instanceof fe||e.has(s.name)||wn.has(s.name)||O.conflicting_def(s.name)){return false}if(F)F.push(s.definition())}}return true}function can_inject_symbols(){var e=new Set;do{O=t.parent(++N);if(O.is_block_scope()&&O.block_scope){O.block_scope.variables.forEach((function(t){e.add(t.name)}))}if(O instanceof we){if(O.argname){e.add(O.argname.name)}}else if(O instanceof j){F=[]}else if(O instanceof Pt){if(O.fixed_value()instanceof ie)return false}}while(!(O instanceof ie));var n=!(O instanceof re)||t.toplevel.vars;var r=t.option("inline");if(!can_inject_vars(e,r>=3&&n))return false;if(!can_inject_args(e,r>=2&&n))return false;return!F||F.length==0||!is_reachable(i,F)}function append_var(t,n,i,r){var a=i.definition();const o=O.variables.has(i.name);if(!o){O.variables.set(i.name,a);O.enclosed.push(a);t.push(make_node(Pe,i,{name:i,value:null}))}var s=make_node(Pt,i,i);a.references.push(s);if(r)n.push(make_node(et,e,{operator:"=",logical:false,left:s,right:r.clone()}))}function flatten_args(t,n){var r=i.argnames.length;for(var a=e.args.length;--a>=r;){n.push(e.args[a])}for(a=r;--a>=0;){var o=i.argnames[a];var s=e.args[a];if(has_flag(o,vn)||!o.name||O.conflicting_def(o.name)){if(s)n.push(s)}else{var u=make_node(Dt,o,o);o.definition().orig.push(u);if(!s&&F)s=make_node($t,e);append_var(t,n,u,s)}}t.reverse();n.reverse()}function flatten_vars(e,t){var n=t.length;for(var r=0,a=i.body.length;re.name!=c.name))){var f=i.variables.get(c.name);var p=make_node(Pt,c,c);f.references.push(p);t.splice(n++,0,make_node(et,l,{operator:"=",logical:false,left:p,right:make_node($t,c)}))}}}}function flatten_fn(e){var n=[];var r=[];flatten_args(n,r);flatten_vars(n,r);r.push(e);if(n.length){const e=O.body.indexOf(t.parent(N-1))+1;O.body.splice(e,0,make_node(Ne,i,{definitions:n}))}return r.map((e=>e.clone(true)))}}));def_optimize(Ke,(function(e,t){if(t.option("unsafe")&&is_undeclared_ref(e.expression)&&["Object","RegExp","Function","Error","Array"].includes(e.expression.name))return make_node(ze,e,e).transform(t);return e}));def_optimize(Ge,(function(e,t){if(!t.option("side_effects"))return e;var n=[];filter_for_side_effects();var i=n.length-1;trim_right_for_undefined();if(i==0){e=maintain_this_binding(t.parent(),t.self(),n[0]);if(!(e instanceof Ge))e=e.optimize(t);return e}e.expressions=n;return e;function filter_for_side_effects(){var i=first_in_statement(t);var r=e.expressions.length-1;e.expressions.forEach((function(e,a){if(a0&&is_undefined(n[i],t))i--;if(i0){var n=this.clone();n.right=make_sequence(this.right,t.slice(a));t=t.slice(0,a);t.push(n);return make_sequence(this,t).optimize(e)}}}return this}));var Un=makePredicate("== === != !== * & | ^");function is_object(e){return e instanceof nt||e instanceof oe||e instanceof it||e instanceof _t}def_optimize(Qe,(function(e,t){function reversible(){return e.left.is_constant()||e.right.is_constant()||!e.left.has_side_effects(t)&&!e.right.has_side_effects(t)}function reverse(t){if(reversible()){if(t)e.operator=t;var n=e.left;e.left=e.right;e.right=n}}if(Un.has(e.operator)){if(e.right.is_constant()&&!e.left.is_constant()){if(!(e.left instanceof Qe&&M[e.left.operator]>=M[e.operator])){reverse()}}}e=e.lift_sequences(t);if(t.option("comparisons"))switch(e.operator){case"===":case"!==":var n=true;if(e.left.is_string(t)&&e.right.is_string(t)||e.left.is_number(t)&&e.right.is_number(t)||e.left.is_boolean()&&e.right.is_boolean()||e.left.equivalent_to(e.right)){e.operator=e.operator.substr(0,2)}case"==":case"!=":if(!n&&is_undefined(e.left,t)){e.left=make_node(Yt,e.left)}else if(t.option("typeofs")&&e.left instanceof Gt&&e.left.value=="undefined"&&e.right instanceof $e&&e.right.operator=="typeof"){var i=e.right.expression;if(i instanceof Pt?i.is_declared(t):!(i instanceof He&&t.option("ie8"))){e.right=i;e.left=make_node($t,e.left).optimize(t);if(e.operator.length==2)e.operator+="="}}else if(e.left instanceof Pt&&e.right instanceof Pt&&e.left.definition()===e.right.definition()&&is_object(e.left.fixed_value())){return make_node(e.operator[0]=="="?tn:en,e)}break;case"&&":case"||":var r=e.left;if(r.operator==e.operator){r=r.right}if(r instanceof Qe&&r.operator==(e.operator=="&&"?"!==":"===")&&e.right instanceof Qe&&r.operator==e.right.operator&&(is_undefined(r.left,t)&&e.right.left instanceof Yt||r.left instanceof Yt&&is_undefined(e.right.left,t))&&!r.right.has_side_effects(t)&&r.right.equivalent_to(e.right.right)){var a=make_node(Qe,e,{operator:r.operator.slice(0,-1),left:make_node(Yt,e),right:r.right});if(r!==e.left){a=make_node(Qe,e,{operator:e.operator,left:e.left.left,right:a})}return a}break}if(e.operator=="+"&&t.in_boolean_context()){var o=e.left.evaluate(t);var s=e.right.evaluate(t);if(o&&typeof o=="string"){return make_sequence(e,[e.right,make_node(tn,e)]).optimize(t)}if(s&&typeof s=="string"){return make_sequence(e,[e.left,make_node(tn,e)]).optimize(t)}}if(t.option("comparisons")&&e.is_boolean()){if(!(t.parent()instanceof Qe)||t.parent()instanceof et){var u=make_node($e,e,{operator:"!",expression:e.negate(t,first_in_statement(t))});e=best_of(t,e,u)}if(t.option("unsafe_comps")){switch(e.operator){case"<":reverse(">");break;case"<=":reverse(">=");break}}}if(e.operator=="+"){if(e.right instanceof Gt&&e.right.getValue()==""&&e.left.is_string(t)){return e.left}if(e.left instanceof Gt&&e.left.getValue()==""&&e.right.is_string(t)){return e.right}if(e.left instanceof Qe&&e.left.operator=="+"&&e.left.left instanceof Gt&&e.left.left.getValue()==""&&e.right.is_string(t)){e.left=e.left.right;return e}}if(t.option("evaluate")){switch(e.operator){case"&&":var o=has_flag(e.left,bn)?true:has_flag(e.left,Dn)?false:e.left.evaluate(t);if(!o){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}else if(!(o instanceof V)){return make_sequence(e,[e.left,e.right]).optimize(t)}var s=e.right.evaluate(t);if(!s){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(en,e)]).optimize(t)}else{set_flag(e,Dn)}}else if(!(s instanceof V)){var l=t.parent();if(l.operator=="&&"&&l.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}if(e.left.operator=="||"){var c=e.left.right.evaluate(t);if(!c)return make_node(Je,e,{condition:e.left.left,consequent:e.right,alternative:e.left.right}).optimize(t)}break;case"||":var o=has_flag(e.left,bn)?true:has_flag(e.left,Dn)?false:e.left.evaluate(t);if(!o){return make_sequence(e,[e.left,e.right]).optimize(t)}else if(!(o instanceof V)){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}var s=e.right.evaluate(t);if(!s){var l=t.parent();if(l.operator=="||"&&l.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}else if(!(s instanceof V)){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(tn,e)]).optimize(t)}else{set_flag(e,bn)}}if(e.left.operator=="&&"){var c=e.left.right.evaluate(t);if(c&&!(c instanceof V))return make_node(Je,e,{condition:e.left.left,consequent:e.left.right,alternative:e.right}).optimize(t)}break;case"??":if(is_nullish(e.left,t)){return e.right}var o=e.left.evaluate(t);if(!(o instanceof V)){return o==null?e.right:e.left}if(t.in_boolean_context()){const n=e.right.evaluate(t);if(!(n instanceof V)&&!n){return e.left}}}var f=true;switch(e.operator){case"+":if(e.right instanceof Kt&&e.left instanceof Qe&&e.left.operator=="+"&&e.left.is_string(t)){var p=make_node(Qe,e,{operator:"+",left:e.left.right,right:e.right});var _=p.optimize(t);if(p!==_){e=make_node(Qe,e,{operator:"+",left:e.left.left,right:_})}}if(e.left instanceof Qe&&e.left.operator=="+"&&e.left.is_string(t)&&e.right instanceof Qe&&e.right.operator=="+"&&e.right.is_string(t)){var p=make_node(Qe,e,{operator:"+",left:e.left.right,right:e.right.left});var d=p.optimize(t);if(p!==d){e=make_node(Qe,e,{operator:"+",left:make_node(Qe,e.left,{operator:"+",left:e.left.left,right:d}),right:e.right.right})}}if(e.right instanceof $e&&e.right.operator=="-"&&e.left.is_number(t)){e=make_node(Qe,e,{operator:"-",left:e.left,right:e.right.expression});break}if(e.left instanceof $e&&e.left.operator=="-"&&reversible()&&e.right.is_number(t)){e=make_node(Qe,e,{operator:"-",left:e.right,right:e.left.expression});break}if(e.left instanceof _e){var h=e.left;var _=e.right.evaluate(t);if(_!=e.right){h.segments[h.segments.length-1].value+=String(_);return h}}if(e.right instanceof _e){var _=e.right;var h=e.left.evaluate(t);if(h!=e.left){_.segments[0].value=String(h)+_.segments[0].value;return _}}if(e.left instanceof _e&&e.right instanceof _e){var h=e.left;var m=h.segments;var _=e.right;m[m.length-1].value+=_.segments[0].value;for(var E=1;E<_.segments.length;E++){m.push(_.segments[E])}return h}case"*":f=t.option("unsafe_math");case"&":case"|":case"^":if(e.left.is_number(t)&&e.right.is_number(t)&&reversible()&&!(e.left instanceof Qe&&e.left.operator!=e.operator&&M[e.left.operator]>=M[e.operator])){var g=make_node(Qe,e,{operator:e.operator,left:e.right,right:e.left});if(e.right instanceof Kt&&!(e.left instanceof Kt)){e=best_of(t,g,e)}else{e=best_of(t,e,g)}}if(f&&e.is_number(t)){if(e.right instanceof Qe&&e.right.operator==e.operator){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left,right:e.right.left,start:e.left.start,end:e.right.left.end}),right:e.right.right})}if(e.right instanceof Kt&&e.left instanceof Qe&&e.left.operator==e.operator){if(e.left.left instanceof Kt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left.left,right:e.right,start:e.left.left.start,end:e.right.end}),right:e.left.right})}else if(e.left.right instanceof Kt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left.right,right:e.right,start:e.left.right.start,end:e.right.end}),right:e.left.left})}}if(e.left instanceof Qe&&e.left.operator==e.operator&&e.left.right instanceof Kt&&e.right instanceof Qe&&e.right.operator==e.operator&&e.right.left instanceof Kt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:make_node(Qe,e.left.left,{operator:e.operator,left:e.left.right,right:e.right.left,start:e.left.right.start,end:e.right.left.end}),right:e.left.left}),right:e.right.right})}}}}if(e.right instanceof Qe&&e.right.operator==e.operator&&(On.has(e.operator)||e.operator=="+"&&(e.right.left.is_string(t)||e.left.is_string(t)&&e.right.right.is_string(t)))){e.left=make_node(Qe,e.left,{operator:e.operator,left:e.left.transform(t),right:e.right.left.transform(t)});e.right=e.right.right.transform(t);return e.transform(t)}var v=e.evaluate(t);if(v!==e){v=make_node_from_constant(v,e).optimize(t);return best_of(t,v,e)}return e}));def_optimize(Lt,(function(e){return e}));function recursive_ref(e,t){var n;for(var i=0;n=e.parent(i);i++){if(n instanceof oe||n instanceof _t){var r=n.name;if(r&&r.definition()===t)break}}return n}function within_array_or_object_literal(e){var t,n=0;while(t=e.parent(n++)){if(t instanceof U)return false;if(t instanceof nt||t instanceof ot||t instanceof it){return true}}return false}def_optimize(Pt,(function(e,t){if(!t.option("ie8")&&is_undeclared_ref(e)&&!t.find_parent(ne)){switch(e.name){case"undefined":return make_node($t,e).optimize(t);case"NaN":return make_node(jt,e).optimize(t);case"Infinity":return make_node(Qt,e).optimize(t)}}const n=t.parent();if(t.option("reduce_vars")&&is_lhs(e,n)!==e){const a=e.definition();const o=find_scope(t);if(t.top_retain&&a.global&&t.top_retain(a)){a.fixed=false;a.single_use=false;return e}let s=e.fixed_value();let u=a.single_use&&!(n instanceof ze&&n.is_callee_pure(t)||has_annotation(n,on))&&!(n instanceof Ue&&s instanceof oe&&s.name);if(u&&s instanceof V){u=!s.has_side_effects(t)&&!s.may_throw(t)}if(u&&(s instanceof oe||s instanceof _t)){if(retain_top_func(s,t)){u=false}else if(a.scope!==e.scope&&(a.escaped==1||has_flag(s,Sn)||within_array_or_object_literal(t)||!t.option("reduce_funcs"))){u=false}else if(recursive_ref(t,a)){u=false}else if(a.scope!==e.scope||a.orig[0]instanceof kt){u=s.is_constant_expression(e.scope);if(u=="f"){var i=e.scope;do{if(i instanceof ce||is_func_expr(i)){set_flag(i,Sn)}}while(i=i.parent_scope)}}}if(u&&s instanceof oe){u=a.scope===e.scope&&!scope_encloses_variables_in_this_scope(o,s)||n instanceof ze&&n.expression===e&&!scope_encloses_variables_in_this_scope(o,s)&&!(s.name&&s.name.definition().recursive_refs>0)}if(u&&s){if(s instanceof mt){set_flag(s,kn);s=make_node(Et,s,s)}if(s instanceof ce){set_flag(s,kn);s=make_node(ue,s,s)}if(a.recursive_refs>0&&s.name instanceof Tt){const e=s.name.definition();let t=s.variables.get(s.name.name);let n=t&&t.orig[0];if(!(n instanceof Rt)){n=make_node(Rt,s.name,s.name);n.scope=s;s.name=n;t=s.def_function(n)}walk(s,(n=>{if(n instanceof Pt&&n.definition()===e){n.thedef=t;t.references.push(n)}}))}if((s instanceof oe||s instanceof _t)&&s.parent_scope!==o){s=s.clone(true,t.get_toplevel());o.add_child_scope(s)}return s.optimize(t)}if(s){let n;if(s instanceof Ut){if(!(a.orig[0]instanceof kt)&&a.references.every((e=>a.scope===e.scope))){n=s}}else{var r=s.evaluate(t);if(r!==s&&(t.option("unsafe_regexp")||!(r instanceof RegExp))){n=make_node_from_constant(r,s)}}if(n){const i=e.size(t);const r=n.size(t);let o=0;if(t.option("unused")&&!t.exposed(a)){o=(i+2+r)/(a.references.length-a.assignments)}if(r<=i+o){return n}}}}return e}));function scope_encloses_variables_in_this_scope(e,t){for(const n of t.enclosed){if(t.variables.has(n.name)){continue}const i=e.find_variable(n.name);if(i){if(i===n)continue;return true}}return false}function is_atomic(e,t){return e instanceof Pt||e.TYPE===t.TYPE}def_optimize($t,(function(e,t){if(t.option("unsafe_undefined")){var n=find_variable(t,"undefined");if(n){var i=make_node(Pt,e,{name:"undefined",scope:n.scope,thedef:n});set_flag(i,yn);return i}}var r=is_lhs(t.self(),t.parent());if(r&&is_atomic(r,e))return e;return make_node($e,e,{operator:"void",expression:make_node(Ht,e,{value:0})})}));def_optimize(Qt,(function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&is_atomic(n,e))return e;if(t.option("keep_infinity")&&!(n&&!is_atomic(n,e))&&!find_variable(t,"Infinity")){return e}return make_node(Qe,e,{operator:"/",left:make_node(Ht,e,{value:1}),right:make_node(Ht,e,{value:0})})}));def_optimize(jt,(function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&!is_atomic(n,e)||find_variable(t,"NaN")){return make_node(Qe,e,{operator:"/",left:make_node(Ht,e,{value:0}),right:make_node(Ht,e,{value:0})})}return e}));function is_reachable(e,t){const find_ref=e=>{if(e instanceof Pt&&member(e.definition(),t)){return nn}};return walk_parent(e,((t,n)=>{if(t instanceof ie&&t!==e){var i=n.parent();if(i instanceof ze&&i.expression===t)return;if(walk(t,find_ref))return nn;return true}}))}const zn=makePredicate("+ - / * % >> << >>> | ^ &");const Kn=makePredicate("* | ^ &");def_optimize(et,(function(e,t){if(e.logical){return e.lift_sequences(t)}var n;if(t.option("dead_code")&&e.left instanceof Pt&&(n=e.left.definition()).scope===t.find_parent(oe)){var i=0,r,a=e;do{r=a;a=t.parent(i++);if(a instanceof me){if(in_try(i,a))break;if(is_reachable(n.scope,[n]))break;if(e.operator=="=")return e.right;n.fixed=false;return make_node(Qe,e,{operator:e.operator.slice(0,-1),left:e.left,right:e.right}).optimize(t)}}while(a instanceof Qe&&a.right===r||a instanceof Ge&&a.tail_node()===r)}e=e.lift_sequences(t);if(e.operator=="="&&e.left instanceof Pt&&e.right instanceof Qe){if(e.right.left instanceof Pt&&e.right.left.name==e.left.name&&zn.has(e.right.operator)){e.operator=e.right.operator+"=";e.right=e.right.right}else if(e.right.right instanceof Pt&&e.right.right.name==e.left.name&&Kn.has(e.right.operator)&&!e.right.left.has_side_effects(t)){e.operator=e.right.operator+"=";e.right=e.right.left}}return e;function in_try(n,i){var r=e.right;e.right=make_node(Yt,r);var a=i.may_throw(t);e.right=r;var o=e.left.definition().scope;var s;while((s=t.parent(n++))!==o){if(s instanceof Re){if(s.bfinally)return true;if(a&&s.bcatch)return true}}}}));def_optimize(tt,(function(e,t){if(!t.option("evaluate")){return e}var n=e.right.evaluate(t);if(n===undefined){e=e.left}else if(n!==e.right){n=make_node_from_constant(n,e.right);e.right=best_of_expression(n,e.right)}return e}));function is_nullish(e,t){let n;return e instanceof Yt||is_undefined(e,t)||e instanceof Pt&&(n=e.definition().fixed)instanceof V&&is_nullish(n,t)||e instanceof He&&e.optional&&is_nullish(e.expression,t)||e instanceof ze&&e.optional&&is_nullish(e.expression,t)||e instanceof Ye&&is_nullish(e.expression,t)}function is_nullish_check(e,t,n){if(t.may_throw(n))return false;let i;if(e instanceof Qe&&e.operator==="=="&&((i=is_nullish(e.left,n)&&e.left)||(i=is_nullish(e.right,n)&&e.right))&&(i===e.left?e.right:e.left).equivalent_to(t)){return true}if(e instanceof Qe&&e.operator==="||"){let i;let r;const find_comparison=e=>{if(!(e instanceof Qe&&(e.operator==="==="||e.operator==="=="))){return false}let a=0;let o;if(e.left instanceof Yt){a++;i=e;o=e.right}if(e.right instanceof Yt){a++;i=e;o=e.left}if(is_undefined(e.left,n)){a++;r=e;o=e.right}if(is_undefined(e.right,n)){a++;r=e;o=e.left}if(a!==1){return false}if(!o.equivalent_to(t)){return false}return true};if(!find_comparison(e.left))return false;if(!find_comparison(e.right))return false;if(i&&r&&i!==r){return true}}return false}def_optimize(Je,(function(e,t){if(!t.option("conditionals"))return e;if(e.condition instanceof Ge){var n=e.condition.expressions.slice();e.condition=n.pop();n.push(e);return make_sequence(e,n)}var i=e.condition.evaluate(t);if(i!==e.condition){if(i){return maintain_this_binding(t.parent(),t.self(),e.consequent)}else{return maintain_this_binding(t.parent(),t.self(),e.alternative)}}var r=i.negate(t,first_in_statement(t));if(best_of(t,i,r)===r){e=make_node(Je,e,{condition:r,consequent:e.alternative,alternative:e.consequent})}var a=e.condition;var o=e.consequent;var s=e.alternative;if(a instanceof Pt&&o instanceof Pt&&a.definition()===o.definition()){return make_node(Qe,e,{operator:"||",left:a,right:s})}if(o instanceof et&&s instanceof et&&o.operator===s.operator&&o.logical===s.logical&&o.left.equivalent_to(s.left)&&(!e.condition.has_side_effects(t)||o.operator=="="&&!o.left.has_side_effects(t))){return make_node(et,e,{operator:o.operator,left:o.left,logical:o.logical,right:make_node(Je,e,{condition:e.condition,consequent:o.right,alternative:s.right})})}var u;if(o instanceof ze&&s.TYPE===o.TYPE&&o.args.length>0&&o.args.length==s.args.length&&o.expression.equivalent_to(s.expression)&&!e.condition.has_side_effects(t)&&!o.expression.has_side_effects(t)&&typeof(u=single_arg_diff())=="number"){var l=o.clone();l.args[u]=make_node(Je,e,{condition:e.condition,consequent:o.args[u],alternative:s.args[u]});return l}if(s instanceof Je&&o.equivalent_to(s.consequent)){return make_node(Je,e,{condition:make_node(Qe,e,{operator:"||",left:a,right:s.condition}),consequent:o,alternative:s.alternative}).optimize(t)}if(t.option("ecma")>=2020&&is_nullish_check(a,s,t)){return make_node(Qe,e,{operator:"??",left:s,right:o}).optimize(t)}if(s instanceof Ge&&o.equivalent_to(s.expressions[s.expressions.length-1])){return make_sequence(e,[make_node(Qe,e,{operator:"||",left:a,right:make_sequence(e,s.expressions.slice(0,-1))}),o]).optimize(t)}if(s instanceof Qe&&s.operator=="&&"&&o.equivalent_to(s.right)){return make_node(Qe,e,{operator:"&&",left:make_node(Qe,e,{operator:"||",left:a,right:s.left}),right:o}).optimize(t)}if(o instanceof Je&&o.alternative.equivalent_to(s)){return make_node(Je,e,{condition:make_node(Qe,e,{left:e.condition,operator:"&&",right:o.condition}),consequent:o.consequent,alternative:s})}if(o.equivalent_to(s)){return make_sequence(e,[e.condition,o]).optimize(t)}if(o instanceof Qe&&o.operator=="||"&&o.right.equivalent_to(s)){return make_node(Qe,e,{operator:"||",left:make_node(Qe,e,{operator:"&&",left:e.condition,right:o.left}),right:s}).optimize(t)}var c=t.in_boolean_context();if(is_true(e.consequent)){if(is_false(e.alternative)){return booleanize(e.condition)}return make_node(Qe,e,{operator:"||",left:booleanize(e.condition),right:e.alternative})}if(is_false(e.consequent)){if(is_true(e.alternative)){return booleanize(e.condition.negate(t))}return make_node(Qe,e,{operator:"&&",left:booleanize(e.condition.negate(t)),right:e.alternative})}if(is_true(e.alternative)){return make_node(Qe,e,{operator:"||",left:booleanize(e.condition.negate(t)),right:e.consequent})}if(is_false(e.alternative)){return make_node(Qe,e,{operator:"&&",left:booleanize(e.condition),right:e.consequent})}return e;function booleanize(e){if(e.is_boolean())return e;return make_node($e,e,{operator:"!",expression:e.negate(t)})}function is_true(e){return e instanceof tn||c&&e instanceof Kt&&e.getValue()||e instanceof $e&&e.operator=="!"&&e.expression instanceof Kt&&!e.expression.getValue()}function is_false(e){return e instanceof en||c&&e instanceof Kt&&!e.getValue()||e instanceof $e&&e.operator=="!"&&e.expression instanceof Kt&&e.expression.getValue()}function single_arg_diff(){var e=o.args;var t=s.args;for(var n=0,i=e.length;n=2015;var i=this.expression;if(i instanceof it){var r=i.properties;for(var a=r.length;--a>=0;){var o=r[a];if(""+(o instanceof ft?o.key.name:o.key)==e){const e=r.every((e=>(e instanceof ot||n&&e instanceof ft&&!e.is_generator)&&!e.computed_key()));if(!e)return;if(!safe_to_flatten(o.value,t))return;return make_node(qe,this,{expression:make_node(nt,i,{elements:r.map((function(e){var t=e.value;if(t instanceof se){t=make_node(ue,t,t)}var n=e.key;if(n instanceof V&&!(n instanceof xt)){return make_sequence(e,[n,t])}return t}))}),property:make_node(Ht,this,{value:a})})}}}}));def_optimize(qe,(function(e,t){var n=e.expression;var i=e.property;if(t.option("properties")){var r=i.evaluate(t);if(r!==i){if(typeof r=="string"){if(r=="undefined"){r=undefined}else{var a=parseFloat(r);if(a.toString()==r){r=a}}}i=e.property=best_of_expression(i,make_node_from_constant(r,i).transform(t));var o=""+r;if(is_basic_identifier_string(o)&&o.length<=i.size()+1){return make_node(Xe,e,{expression:n,optional:e.optional,property:o,quote:i.quote}).optimize(t)}}}var s;e:if(t.option("arguments")&&n instanceof Pt&&n.name=="arguments"&&n.definition().orig.length==1&&(s=n.scope)instanceof oe&&s.uses_arguments&&!(s instanceof le)&&i instanceof Ht){var u=i.getValue();var l=new Set;var c=s.argnames;for(var f=0;f1){_=null}}else if(!_&&!t.option("keep_fargs")&&u=s.argnames.length){_=s.create_symbol(kt,{source:s,scope:s,tentative_name:"argument_"+s.argnames.length});s.argnames.push(_)}}if(_){var h=make_node(Pt,e,_);h.reference({});clear_flag(_,vn);return h}}if(is_lhs(e,t.parent()))return e;if(r!==i){var m=e.flatten_object(o,t);if(m){n=e.expression=m.expression;i=e.property=m.property}}if(t.option("properties")&&t.option("side_effects")&&i instanceof Ht&&n instanceof nt){var u=i.getValue();var E=n.elements;var g=E[u];e:if(safe_to_flatten(g,t)){var v=true;var b=[];for(var D=E.length;--D>u;){var a=E[D].drop_side_effect_free(t);if(a){b.unshift(a);if(v&&a.has_side_effects(t))v=false}}if(g instanceof ae)break e;g=g instanceof Zt?make_node($t,g):g;if(!v)b.unshift(g);while(--D>=0){var a=E[D];if(a instanceof ae)break e;a=a.drop_side_effect_free(t);if(a)b.unshift(a);else u--}if(v){b.push(g);return make_sequence(e,b).optimize(t)}else return make_node(qe,e,{expression:make_node(nt,n,{elements:b}),property:make_node(Ht,i,{value:u})})}}var y=e.evaluate(t);if(y!==e){y=make_node_from_constant(y,e).optimize(t);return best_of(t,y,e)}if(e.optional&&is_nullish(e.expression,t)){return make_node($t,e)}return e}));def_optimize(Ye,(function(e,t){e.expression=e.expression.optimize(t);return e}));oe.DEFMETHOD("contains_this",(function(){return walk(this,(e=>{if(e instanceof Ut)return nn;if(e!==this&&e instanceof ie&&!(e instanceof le)){return true}}))}));def_optimize(Xe,(function(e,t){const n=t.parent();if(is_lhs(e,n))return e;if(t.option("unsafe_proto")&&e.expression instanceof Xe&&e.expression.property=="prototype"){var i=e.expression.expression;if(is_undeclared_ref(i))switch(i.name){case"Array":e.expression=make_node(nt,e.expression,{elements:[]});break;case"Function":e.expression=make_node(ue,e.expression,{argnames:[],body:[]});break;case"Number":e.expression=make_node(Ht,e.expression,{value:0});break;case"Object":e.expression=make_node(it,e.expression,{properties:[]});break;case"RegExp":e.expression=make_node(Wt,e.expression,{value:{source:"t",flags:""}});break;case"String":e.expression=make_node(Gt,e.expression,{value:""});break}}if(!(n instanceof ze)||!has_annotation(n,on)){const n=e.flatten_object(e.property,t);if(n)return n.optimize(t)}let r=e.evaluate(t);if(r!==e){r=make_node_from_constant(r,e).optimize(t);return best_of(t,r,e)}if(e.optional&&is_nullish(e.expression,t)){return make_node($t,e)}return e}));function literals_in_boolean_context(e,t){if(t.in_boolean_context()){return best_of(t,e,make_sequence(e,[e,make_node(tn,e)]).optimize(t))}return e}function inline_array_like_spread(e){for(var t=0;te instanceof Zt))){e.splice(t,1,...i.elements);t--}}}}def_optimize(nt,(function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_array_like_spread(e.elements);return e}));function inline_object_prop_spread(e,t){for(var n=0;ne instanceof ot))){e.splice(n,1,...r.properties);n--}else if(r instanceof Kt&&!(r instanceof Gt)){e.splice(n,1)}else if(is_nullish(r,t)){e.splice(n,1)}}}}def_optimize(it,(function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_object_prop_spread(e.properties,t);return e}));def_optimize(Wt,literals_in_boolean_context);def_optimize(Ee,(function(e,t){if(e.value&&is_undefined(e.value,t)){e.value=null}return e}));def_optimize(le,opt_AST_Lambda);def_optimize(ue,(function(e,t){e=opt_AST_Lambda(e,t);if(t.option("unsafe_arrows")&&t.option("ecma")>=2015&&!e.name&&!e.is_generator&&!e.uses_arguments&&!e.pinned()){const n=walk(e,(e=>{if(e instanceof Ut)return nn}));if(!n)return make_node(le,e,e).optimize(t)}return e}));def_optimize(_t,(function(e){return e}));def_optimize(Se,(function(e,t){if(e.expression&&!e.is_star&&is_undefined(e.expression,t)){e.expression=null}return e}));def_optimize(_e,(function(e,t){if(!t.option("evaluate")||t.parent()instanceof pe){return e}var n=[];for(var i=0;i=2015&&(!(n instanceof RegExp)||n.test(e.key+""))){var i=e.key;var r=e.value;var a=r instanceof le&&Array.isArray(r.body)&&!r.contains_this();if((a||r instanceof ue)&&!r.name){return make_node(ft,e,{async:r.async,is_generator:r.is_generator,key:i instanceof V?i:make_node(xt,e,{name:i}),value:make_node(se,r,r),quote:e.quote})}}return e}));def_optimize(fe,(function(e,t){if(t.option("pure_getters")==true&&t.option("unused")&&!e.is_array&&Array.isArray(e.names)&&!is_destructuring_export_decl(t)&&!(e.names[e.names.length-1]instanceof ae)){var n=[];for(var i=0;i1)throw new Error("inline source map only works with singular input");t.sourceMap.content=read_source_map(e[a])}}}r=t.parse.toplevel}if(i&&t.mangle.properties.keep_quoted!=="strict"){reserve_quoted_keys(r,i)}if(t.wrap){r=r.wrap_commonjs(t.wrap)}if(t.enclose){r=r.wrap_enclose(t.enclose)}if(n)n.rename=Date.now();if(n)n.compress=Date.now();if(t.compress){r=new Compressor(t.compress,{mangle_options:t.mangle}).compress(r)}if(n)n.scope=Date.now();if(t.mangle)r.figure_out_scope(t.mangle);if(n)n.mangle=Date.now();if(t.mangle){En.reset();r.compute_char_frequency(t.mangle);r.mangle_names(t.mangle)}if(n)n.properties=Date.now();if(t.mangle&&t.mangle.properties){r=mangle_properties(r,t.mangle.properties)}if(n)n.format=Date.now();var o={};if(t.format.ast){o.ast=r}if(t.format.spidermonkey){o.ast=r.to_mozilla_ast()}if(!HOP(t.format,"code")||t.format.code){if(t.sourceMap){t.format.source_map=await SourceMap({file:t.sourceMap.filename,orig:t.sourceMap.content,root:t.sourceMap.root});if(t.sourceMap.includeSources){if(e instanceof re){throw new Error("original source content unavailable")}else for(var a in e)if(HOP(e,a)){t.format.source_map.get().setSourceContent(a,e[a])}}}delete t.format.ast;delete t.format.code;delete t.format.spidermonkey;var s=OutputStream(t.format);r.print(s);o.code=s.get();if(t.sourceMap){if(t.sourceMap.asObject){o.map=t.format.source_map.get().toJSON()}else{o.map=t.format.source_map.toString()}if(t.sourceMap.url=="inline"){var u=typeof o.map==="object"?JSON.stringify(o.map):o.map;o.code+="\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,"+Xn(u)}else if(t.sourceMap.url){o.code+="\n//# sourceMappingURL="+t.sourceMap.url}}}if(t.nameCache&&t.mangle){if(t.mangle.cache)t.nameCache.vars=cache_to_json(t.mangle.cache);if(t.mangle.properties&&t.mangle.properties.cache){t.nameCache.props=cache_to_json(t.mangle.properties.cache)}}if(t.format&&t.format.source_map){t.format.source_map.destroy()}if(n){n.end=Date.now();o.timings={parse:.001*(n.rename-n.parse),rename:.001*(n.compress-n.rename),compress:.001*(n.scope-n.compress),scope:.001*(n.mangle-n.scope),mangle:.001*(n.properties-n.mangle),properties:.001*(n.format-n.properties),format:.001*(n.end-n.format),total:.001*(n.end-n.start)}}return o}async function run_cli({program:e,packageJson:t,fs:i,path:r}){const a=new Set(["cname","parent_scope","scope","uses_eval","uses_with"]);var o={};var s={compress:false,mangle:false};const u=await _default_options();e.version(t.name+" "+t.version);e.parseArgv=e.parse;e.parse=undefined;if(process.argv.includes("ast"))e.helpInformation=describe_ast;else if(process.argv.includes("options"))e.helpInformation=function(){var e=[];for(var t in u){e.push("--"+(t==="sourceMap"?"source-map":t)+" options:");e.push(format_object(u[t]));e.push("")}return e.join("\n")};e.option("-p, --parse ","Specify parser options.",parse_js());e.option("-c, --compress [options]","Enable compressor/specify compressor options.",parse_js());e.option("-m, --mangle [options]","Mangle names/specify mangler options.",parse_js());e.option("--mangle-props [options]","Mangle properties/specify mangler options.",parse_js());e.option("-f, --format [options]","Format options.",parse_js());e.option("-b, --beautify [options]","Alias for --format.",parse_js());e.option("-o, --output ","Output file (default STDOUT).");e.option("--comments [filter]","Preserve copyright comments in the output.");e.option("--config-file ","Read minify() options from JSON file.");e.option("-d, --define [=value]","Global definitions.",parse_js("define"));e.option("--ecma ","Specify ECMAScript release: 5, 2015, 2016 or 2017...");e.option("-e, --enclose [arg[,...][:value[,...]]]","Embed output in a big function with configurable arguments and values.");e.option("--ie8","Support non-standard Internet Explorer 8.");e.option("--keep-classnames","Do not mangle/drop class names.");e.option("--keep-fnames","Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");e.option("--module","Input is an ES6 module");e.option("--name-cache ","File to hold mangled name mappings.");e.option("--rename","Force symbol expansion.");e.option("--no-rename","Disable symbol expansion.");e.option("--safari10","Support non-standard Safari 10.");e.option("--source-map [options]","Enable source map/specify source map options.",parse_js());e.option("--timings","Display operations run time on STDERR.");e.option("--toplevel","Compress and/or mangle variables in toplevel scope.");e.option("--wrap ","Embed everything as a function with “exports” corresponding to “name” globally.");e.arguments("[files...]").parseArgv(process.argv);if(e.configFile){s=JSON.parse(read_file(e.configFile))}if(!e.output&&e.sourceMap&&e.sourceMap.url!="inline"){fatal("ERROR: cannot write source map to STDOUT")}["compress","enclose","ie8","mangle","module","safari10","sourceMap","toplevel","wrap"].forEach((function(t){if(t in e){s[t]=e[t]}}));if("ecma"in e){if(e.ecma!=(e.ecma|0))fatal("ERROR: ecma must be an integer");const t=e.ecma|0;if(t>5&&t<2015)s.ecma=t+2009;else s.ecma=t}if(e.format||e.beautify){const t=e.format||e.beautify;s.format=typeof t==="object"?t:{}}if(e.comments){if(typeof s.format!="object")s.format={};s.format.comments=typeof e.comments=="string"?e.comments=="false"?false:e.comments:"some"}if(e.define){if(typeof s.compress!="object")s.compress={};if(typeof s.compress.global_defs!="object")s.compress.global_defs={};for(var l in e.define){s.compress.global_defs[l]=e.define[l]}}if(e.keepClassnames){s.keep_classnames=true}if(e.keepFnames){s.keep_fnames=true}if(e.mangleProps){if(e.mangleProps.domprops){delete e.mangleProps.domprops}else{if(typeof e.mangleProps!="object")e.mangleProps={};if(!Array.isArray(e.mangleProps.reserved))e.mangleProps.reserved=[]}if(typeof s.mangle!="object")s.mangle={};s.mangle.properties=e.mangleProps}if(e.nameCache){s.nameCache=JSON.parse(read_file(e.nameCache,"{}"))}if(e.output=="ast"){s.format={ast:true,code:false}}if(e.parse){if(!e.parse.acorn&&!e.parse.spidermonkey){s.parse=e.parse}else if(e.sourceMap&&e.sourceMap.content=="inline"){fatal("ERROR: inline source map only works with built-in parser")}}if(~e.rawArgs.indexOf("--rename")){s.rename=true}else if(!e.rename){s.rename=false}let convert_path=e=>e;if(typeof e.sourceMap=="object"&&"base"in e.sourceMap){convert_path=function(){var t=e.sourceMap.base;delete s.sourceMap.base;return function(e){return r.relative(t,e)}}()}let c;if(s.files&&s.files.length){c=s.files;delete s.files}else if(e.args.length){c=e.args}if(c){simple_glob(c).forEach((function(e){o[convert_path(e)]=read_file(e)}))}else{await new Promise((e=>{var t=[];process.stdin.setEncoding("utf8");process.stdin.on("data",(function(e){t.push(e)})).on("end",(function(){o=[t.join("")];e()}));process.stdin.resume()}))}await run_cli();function convert_ast(e){return V.from_mozilla_ast(Object.keys(o).reduce(e,null))}async function run_cli(){var t=e.sourceMap&&e.sourceMap.content;if(t&&t!=="inline"){s.sourceMap.content=read_file(t,t)}if(e.timings)s.timings=true;try{if(e.parse){if(e.parse.acorn){o=convert_ast((function(t,i){return n(108).parse(o[i],{ecmaVersion:2018,locations:true,program:t,sourceFile:i,sourceType:s.module||e.parse.module?"module":"script"})}))}else if(e.parse.spidermonkey){o=convert_ast((function(e,t){var n=JSON.parse(o[t]);if(!e)return n;e.body=e.body.concat(n.body);return e}))}}}catch(e){fatal(e)}let r;try{r=await minify(o,s)}catch(e){if(e.name=="SyntaxError"){print_error("Parse error at "+e.filename+":"+e.line+","+e.col);var u=e.col;var l=o[e.filename].split(/\r?\n/);var c=l[e.line-1];if(!c&&!u){c=l[e.line-2];u=c.length}if(c){var f=70;if(u>f){c=c.slice(u-f);u=f}print_error(c.slice(0,80));print_error(c.slice(0,u).replace(/\S/g," ")+"^")}}if(e.defs){print_error("Supported options:");print_error(format_object(e.defs))}fatal(e);return}if(e.output=="ast"){if(!s.compress&&!s.mangle){r.ast.figure_out_scope({})}console.log(JSON.stringify(r.ast,(function(e,t){if(t)switch(e){case"thedef":return symdef(t);case"enclosed":return t.length?t.map(symdef):undefined;case"variables":case"globals":return t.size?collect_from_map(t,symdef):undefined}if(a.has(e))return;if(t instanceof AST_Token)return;if(t instanceof Map)return;if(t instanceof V){var n={_class:"AST_"+t.TYPE};if(t.block_scope){n.variables=t.block_scope.variables;n.enclosed=t.block_scope.enclosed}t.CTOR.PROPS.forEach((function(e){n[e]=t[e]}));return n}return t}),2))}else if(e.output=="spidermonkey"){try{const e=await minify(r.code,{compress:false,mangle:false,format:{ast:true,code:false}});console.log(JSON.stringify(e.ast.to_mozilla_ast(),null,2))}catch(e){fatal(e);return}}else if(e.output){i.writeFileSync(e.output,r.code);if(s.sourceMap&&s.sourceMap.url!=="inline"&&r.map){i.writeFileSync(e.output+".map",r.map)}}else{console.log(r.code)}if(e.nameCache){i.writeFileSync(e.nameCache,JSON.stringify(s.nameCache))}if(r.timings)for(var p in r.timings){print_error("- "+p+": "+r.timings[p].toFixed(3)+"s")}}function fatal(e){if(e instanceof Error)e=e.stack.replace(/^\S*?Error:/,"ERROR:");print_error(e);process.exit(1)}function simple_glob(e){if(Array.isArray(e)){return[].concat.apply([],e.map(simple_glob))}if(e&&e.match(/[*?]/)){var t=r.dirname(e);try{var n=i.readdirSync(t)}catch(e){}if(n){var a="^"+r.basename(e).replace(/[.+^$[\]\\(){}]/g,"\\$&").replace(/\*/g,"[^/\\\\]*").replace(/\?/g,"[^/\\\\]")+"$";var o=process.platform==="win32"?"i":"";var s=new RegExp(a,o);var u=n.filter((function(e){return s.test(e)})).map((function(e){return r.join(t,e)}));if(u.length)return u}}return[e]}function read_file(e,t){try{return i.readFileSync(e,"utf8")}catch(e){if((e.code=="ENOENT"||e.code=="ENAMETOOLONG")&&t!=null)return t;fatal(e)}}function parse_js(e){return function(t,n){n=n||{};try{walk(parse(t,{expression:true}),(t=>{if(t instanceof et){var i=t.left.print_to_string();var r=t.right;if(e){n[i]=r}else if(r instanceof nt){n[i]=r.elements.map(to_string)}else if(r instanceof Wt){r=r.value;n[i]=new RegExp(r.source,r.flags)}else{n[i]=to_string(r)}return true}if(t instanceof gt||t instanceof He){var i=t.print_to_string();n[i]=true;return true}if(!(t instanceof Ge))throw t;function to_string(e){return e instanceof Kt?e.getValue():e.print_to_string({quote_keys:true})}}))}catch(i){if(e){fatal("Error parsing arguments for '"+e+"': "+t)}else{n[t]=null}}return n}}function symdef(e){var t=1e6+e.id+" "+e.name;if(e.mangled_name)t+=" "+e.mangled_name;return t}function collect_from_map(e,t){var n=[];e.forEach((function(e){n.push(t(e))}));return n}function format_object(e){var t=[];var n="";Object.keys(e).map((function(t){if(n.length!/^\$/.test(e)));if(n.length>0){e.space();e.with_parens((function(){n.forEach((function(t,n){if(n)e.space();e.print(t)}))}))}if(t.documentation){e.space();e.print_string(t.documentation)}if(t.SUBCLASSES.length>0){e.space();e.with_block((function(){t.SUBCLASSES.forEach((function(t){e.indent();doitem(t);e.newline()}))}))}}doitem(V);return e+"\n"}}async function _default_options(){const e={};Object.keys(infer_options({0:0})).forEach((t=>{const n=infer_options({[t]:{0:0}});if(n)e[t]=n}));return e}async function infer_options(e){try{await minify("",e)}catch(e){return e.defs}}e._default_options=_default_options;e._run_cli=run_cli;e.minify=minify}))}};var t={};function __nccwpck_require__(n){var i=t[n];if(i!==undefined){return i.exports}var r=t[n]={exports:{}};var a=true;try{e[n].call(r.exports,r,r.exports,__nccwpck_require__);a=false}finally{if(a)delete t[n]}return r.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var n=__nccwpck_require__(405);module.exports=n})(); \ No newline at end of file +(()=>{var e={988:e=>{"use strict";e.exports=require("next/dist/compiled/acorn")},749:e=>{"use strict";e.exports=require("next/dist/compiled/source-map")},405:function(e,t,n){(function(e,r){true?r(t,n(749)):0})(this,(function(e,t){"use strict";function _interopDefaultLegacy(e){return e&&typeof e==="object"&&"default"in e?e:{default:e}}var r=_interopDefaultLegacy(t);function characters(e){return e.split("")}function member(e,t){return t.includes(e)}class DefaultsError extends Error{constructor(e,t){super();this.name="DefaultsError";this.message=e;this.defs=t}}function defaults(e,t,n){if(e===true){e={}}else if(e!=null&&typeof e==="object"){e={...e}}const r=e||{};if(n)for(const e in r)if(HOP(r,e)&&!HOP(t,e)){throw new DefaultsError("`"+e+"` is not a supported option",t)}for(const n in t)if(HOP(t,n)){if(!e||!HOP(e,n)){r[n]=t[n]}else if(n==="ecma"){let t=e[n]|0;if(t>5&&t<2015)t+=2009;r[n]=t}else{r[n]=e&&HOP(e,n)?e[n]:t[n]}}return r}function noop(){}function return_false(){return false}function return_true(){return true}function return_this(){return this}function return_null(){return null}var i=function(){function MAP(t,n,r){var i=[],o=[],a;function doit(){var s=n(t[a],a);var u=s instanceof Last;if(u)s=s.v;if(s instanceof AtTop){s=s.v;if(s instanceof Splice){o.push.apply(o,r?s.v.slice().reverse():s.v)}else{o.push(s)}}else if(s!==e){if(s instanceof Splice){i.push.apply(i,r?s.v.slice().reverse():s.v)}else{i.push(s)}}return u}if(Array.isArray(t)){if(r){for(a=t.length;--a>=0;)if(doit())break;i.reverse();o.reverse()}else{for(a=0;a=0;){if(e[n]===t)e.splice(n,1)}}function mergeSort(e,t){if(e.length<2)return e.slice();function merge(e,n){var r=[],i=0,o=0,a=0;while(i{n+=e}))}return n}function has_annotation(e,t){return e._annotations&t}function set_annotation(e,t){e._annotations|=t}var s="";var u=true;var l="break case catch class const continue debugger default delete do else export extends finally for function if in instanceof let new return switch throw try typeof var void while with";var c="false null true";var f="enum implements import interface package private protected public static super this "+c+" "+l;var _="return new delete throw else case yield await";l=makePredicate(l);f=makePredicate(f);_=makePredicate(_);c=makePredicate(c);var p=makePredicate(characters("+-*&%=<>!?|~^"));var d=/[0-9a-f]/i;var m=/^0x[0-9a-f]+$/i;var h=/^0[0-7]+$/;var E=/^0o[0-7]+$/i;var g=/^0b[01]+$/i;var v=/^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;var D=/^(0[xob])?[0-9a-f]+n$/i;var b=makePredicate(["in","instanceof","typeof","new","void","delete","++","--","+","-","!","~","&","|","^","*","**","/","%",">>","<<",">>>","<",">","<=",">=","==","===","!=","!==","?","=","+=","-=","||=","&&=","??=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&=","&&","??","||"]);var S=makePredicate(characters("  \n\r\t\f\v​           \u2028\u2029   \ufeff"));var A=makePredicate(characters("\n\r\u2028\u2029"));var y=makePredicate(characters(";]),:"));var T=makePredicate(characters("[{(,;:"));var k=makePredicate(characters("[]{}(),;:"));var C={ID_Start:/[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/(?:[$0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF])+/};function get_full_char(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){if(is_surrogate_pair_tail(e.charCodeAt(t+1))){return e.charAt(t)+e.charAt(t+1)}}else if(is_surrogate_pair_tail(e.charCodeAt(t))){if(is_surrogate_pair_head(e.charCodeAt(t-1))){return e.charAt(t-1)+e.charAt(t)}}return e.charAt(t)}function get_full_char_code(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){return 65536+(e.charCodeAt(t)-55296<<10)+e.charCodeAt(t+1)-56320}return e.charCodeAt(t)}function get_full_char_length(e){var t=0;for(var n=0;n65535){e-=65536;return String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)}return String.fromCharCode(e)}function is_surrogate_pair_head(e){return e>=55296&&e<=56319}function is_surrogate_pair_tail(e){return e>=56320&&e<=57343}function is_digit(e){return e>=48&&e<=57}function is_identifier_start(e){return C.ID_Start.test(e)}function is_identifier_char(e){return C.ID_Continue.test(e)}const R=/^[a-z_$][a-z0-9_$]*$/i;function is_basic_identifier_string(e){return R.test(e)}function is_identifier_string(e,t){if(R.test(e)){return true}if(!t&&/[\ud800-\udfff]/.test(e)){return false}var n=C.ID_Start.exec(e);if(!n||n.index!==0){return false}e=e.slice(n[0].length);if(!e){return true}n=C.ID_Continue.exec(e);return!!n&&n[0].length===e.length}function parse_js_number(e,t=true){if(!t&&e.includes("e")){return NaN}if(m.test(e)){return parseInt(e.substr(2),16)}else if(h.test(e)){return parseInt(e.substr(1),8)}else if(E.test(e)){return parseInt(e.substr(2),8)}else if(g.test(e)){return parseInt(e.substr(2),2)}else if(v.test(e)){return parseFloat(e)}else{var n=parseFloat(e);if(n==e)return n}}class JS_Parse_Error extends Error{constructor(e,t,n,r,i){super();this.name="SyntaxError";this.message=e;this.filename=t;this.line=n;this.col=r;this.pos=i}}function js_error(e,t,n,r,i){throw new JS_Parse_Error(e,t,n,r,i)}function is_token(e,t,n){return e.type==t&&(n==null||e.value==n)}var F={};function tokenizer(e,t,n,r){var i={text:e,filename:t,pos:0,tokpos:0,line:1,tokline:0,col:0,tokcol:0,newline_before:false,regex_allowed:false,brace_counter:0,template_braces:[],comments_before:[],directives:{},directive_stack:[]};function peek(){return get_full_char(i.text,i.pos)}function is_option_chain_op(){const e=i.text.charCodeAt(i.pos+1)===46;if(!e)return false;const t=i.text.charCodeAt(i.pos+2);return t<48||t>57}function next(e,t){var n=get_full_char(i.text,i.pos++);if(e&&!n)throw F;if(A.has(n)){i.newline_before=i.newline_before||!t;++i.line;i.col=0;if(n=="\r"&&peek()=="\n"){++i.pos;n="\n"}}else{if(n.length>1){++i.pos;++i.col}++i.col}return n}function forward(e){while(e--)next()}function looking_at(e){return i.text.substr(i.pos,e.length)==e}function find_eol(){var e=i.text;for(var t=i.pos,n=i.text.length;t="0"&&e<="7"}function read_escaped_char(e,t,n){var r=next(true,e);switch(r.charCodeAt(0)){case 110:return"\n";case 114:return"\r";case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 120:return String.fromCharCode(hex_bytes(2,t));case 117:if(peek()=="{"){next(true);if(peek()==="}")parse_error("Expecting hex-character between {}");while(peek()=="0")next(true);var o,a=find("}",true)-i.pos;if(a>6||(o=hex_bytes(a,t))>1114111){parse_error("Unicode reference out of bounds")}next(true);return from_char_code(o)}return String.fromCharCode(hex_bytes(4,t));case 10:return"";case 13:if(peek()=="\n"){next(true,e);return""}}if(is_octal(r)){if(n&&t){const e=r==="0"&&!is_octal(peek());if(!e){parse_error("Octal escape sequences are not allowed in template strings")}}return read_octal_escape_sequence(r,t)}return r}function read_octal_escape_sequence(e,t){var n=peek();if(n>="0"&&n<="7"){e+=next(true);if(e[0]<="3"&&(n=peek())>="0"&&n<="7")e+=next(true)}if(e==="0")return"\0";if(e.length>0&&next_token.has_directive("use strict")&&t)parse_error("Legacy octal escape sequences are not allowed in strict mode");return String.fromCharCode(parseInt(e,8))}function hex_bytes(e,t){var n=0;for(;e>0;--e){if(!t&&isNaN(parseInt(peek(),16))){return parseInt(n,16)||""}var r=next(true);if(isNaN(parseInt(r,16)))parse_error("Invalid hex-character pattern in string");n+=r}return parseInt(n,16)}var E=with_eof_error("Unterminated string constant",(function(){const e=i.pos;var t=next(),n=[];for(;;){var r=next(true,true);if(r=="\\")r=read_escaped_char(true,true);else if(r=="\r"||r=="\n")parse_error("Unterminated string constant");else if(r==t)break;n.push(r)}var o=token("string",n.join(""));s=i.text.slice(e,i.pos);o.quote=t;return o}));var g=with_eof_error("Unterminated template",(function(e){if(e){i.template_braces.push(i.brace_counter)}var t="",n="",r,o;next(true,true);while((r=next(true,true))!="`"){if(r=="\r"){if(peek()=="\n")++i.pos;r="\n"}else if(r=="$"&&peek()=="{"){next(true,true);i.brace_counter++;o=token(e?"template_head":"template_substitution",t);s=n;u=false;return o}n+=r;if(r=="\\"){var l=i.pos;var c=a&&(a.type==="name"||a.type==="punc"&&(a.value===")"||a.value==="]"));r=read_escaped_char(true,!c,true);n+=i.text.substr(l,i.pos-l)}t+=r}i.template_braces.pop();o=token(e?"template_head":"template_substitution",t);s=n;u=true;return o}));function skip_line_comment(e){var t=i.regex_allowed;var n=find_eol(),r;if(n==-1){r=i.text.substr(i.pos);i.pos=i.text.length}else{r=i.text.substring(i.pos,n);i.pos=n}i.col=i.tokcol+(i.pos-i.tokpos);i.comments_before.push(token(e,r,true));i.regex_allowed=t;return next_token}var v=with_eof_error("Unterminated multiline comment",(function(){var e=i.regex_allowed;var t=find("*/",true);var n=i.text.substring(i.pos,t).replace(/\r\n|\r|\u2028|\u2029/g,"\n");forward(get_full_char_length(n)+2);i.comments_before.push(token("comment2",n,true));i.newline_before=i.newline_before||n.includes("\n");i.regex_allowed=e;return next_token}));var y=with_eof_error("Unterminated identifier name",(function(){var e=[],t,n=false;var read_escaped_identifier_char=function(){n=true;next();if(peek()!=="u"){parse_error("Expecting UnicodeEscapeSequence -- uXXXX or u{XXXX}")}return read_escaped_char(false,true)};if((t=peek())==="\\"){t=read_escaped_identifier_char();if(!is_identifier_start(t)){parse_error("First identifier char is an invalid identifier char")}}else if(is_identifier_start(t)){next()}else{return""}e.push(t);while((t=peek())!=null){if((t=peek())==="\\"){t=read_escaped_identifier_char();if(!is_identifier_char(t)){parse_error("Invalid escaped identifier char")}}else{if(!is_identifier_char(t)){break}next()}e.push(t)}const r=e.join("");if(f.has(r)&&n){parse_error("Escaped characters are not allowed in keywords")}return r}));var C=with_eof_error("Unterminated regular expression",(function(e){var t=false,n,r=false;while(n=next(true))if(A.has(n)){parse_error("Unexpected line terminator")}else if(t){e+="\\"+n;t=false}else if(n=="["){r=true;e+=n}else if(n=="]"&&r){r=false;e+=n}else if(n=="/"&&!r){break}else if(n=="\\"){t=true}else{e+=n}const i=y();return token("regexp","/"+e+"/"+i)}));function read_operator(e){function grow(e){if(!peek())return e;var t=e+peek();if(b.has(t)){next();return grow(t)}else{return e}}return token("operator",grow(e||next()))}function handle_slash(){next();switch(peek()){case"/":next();return skip_line_comment("comment1");case"*":next();return v()}return i.regex_allowed?C(""):read_operator("/")}function handle_eq_sign(){next();if(peek()===">"){next();return token("arrow","=>")}else{return read_operator("=")}}function handle_dot(){next();if(is_digit(peek().charCodeAt(0))){return read_num(".")}if(peek()==="."){next();next();return token("expand","...")}return token("punc",".")}function read_word(){var e=y();if(o)return token("name",e);return c.has(e)?token("atom",e):!l.has(e)?token("name",e):b.has(e)?token("operator",e):token("keyword",e)}function read_private_word(){next();return token("privatename",y())}function with_eof_error(e,t){return function(n){try{return t(n)}catch(t){if(t===F)parse_error(e);else throw t}}}function next_token(e){if(e!=null)return C(e);if(r&&i.pos==0&&looking_at("#!")){start_token();forward(2);skip_line_comment("comment5")}for(;;){skip_whitespace();start_token();if(n){if(looking_at("\x3c!--")){forward(4);skip_line_comment("comment3");continue}if(looking_at("--\x3e")&&i.newline_before){forward(3);skip_line_comment("comment4");continue}}var t=peek();if(!t)return token("eof");var o=t.charCodeAt(0);switch(o){case 34:case 39:return E();case 46:return handle_dot();case 47:{var a=handle_slash();if(a===next_token)continue;return a}case 61:return handle_eq_sign();case 63:{if(!is_option_chain_op())break;next();next();return token("punc","?.")}case 96:return g(true);case 123:i.brace_counter++;break;case 125:i.brace_counter--;if(i.template_braces.length>0&&i.template_braces[i.template_braces.length-1]===i.brace_counter)return g(false);break}if(is_digit(o))return read_num();if(k.has(t))return token("punc",next());if(p.has(t))return read_operator();if(o==92||is_identifier_start(t))return read_word();if(o==35)return read_private_word();break}parse_error("Unexpected character '"+t+"'")}next_token.next=next;next_token.peek=peek;next_token.context=function(e){if(e)i=e;return i};next_token.add_directive=function(e){i.directive_stack[i.directive_stack.length-1].push(e);if(i.directives[e]===undefined){i.directives[e]=1}else{i.directives[e]++}};next_token.push_directives_stack=function(){i.directive_stack.push([])};next_token.pop_directives_stack=function(){var e=i.directive_stack[i.directive_stack.length-1];for(var t=0;t0};return next_token}var O=makePredicate(["typeof","void","delete","--","++","!","~","-","+"]);var M=makePredicate(["--","++"]);var x=makePredicate(["=","+=","-=","??=","&&=","||=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&="]);var N=makePredicate(["??=","&&=","||="]);var w=function(e,t){for(var n=0;n","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],{});var I=makePredicate(["atom","num","big_int","string","regexp","name"]);function parse(e,t){const n=new WeakMap;t=defaults(t,{bare_returns:false,ecma:null,expression:false,filename:null,html5_comments:true,module:false,shebang:true,strict:false,toplevel:null},true);var r={input:typeof e=="string"?tokenizer(e,t.filename,t.html5_comments,t.shebang):e,token:null,prev:null,peeked:null,in_function:0,in_async:-1,in_generator:-1,in_directives:true,in_loop:0,labels:[]};r.token=next();function is(e,t){return is_token(r.token,e,t)}function peek(){return r.peeked||(r.peeked=r.input())}function next(){r.prev=r.token;if(!r.peeked)peek();r.token=r.peeked;r.peeked=null;r.in_directives=r.in_directives&&(r.token.type=="string"||is("punc",";"));return r.token}function prev(){return r.prev}function croak(e,t,n,i){var o=r.input.context();js_error(e,o.filename,t!=null?t:o.tokline,n!=null?n:o.tokcol,i!=null?i:o.tokpos)}function token_error(e,t){croak(t,e.line,e.col)}function unexpected(e){if(e==null)e=r.token;token_error(e,"Unexpected token: "+e.type+" ("+e.value+")")}function expect_token(e,t){if(is(e,t)){return next()}token_error(r.token,"Unexpected token "+r.token.type+" «"+r.token.value+"»"+", expected "+e+" «"+t+"»")}function expect(e){return expect_token("punc",e)}function has_newline_before(e){return e.nlb||!e.comments_before.every((e=>!e.nlb))}function can_insert_semicolon(){return!t.strict&&(is("eof")||is("punc","}")||has_newline_before(r.token))}function is_in_generator(){return r.in_generator===r.in_function}function is_in_async(){return r.in_async===r.in_function}function can_await(){return r.in_async===r.in_function||r.in_function===0&&r.input.has_directive("use strict")}function semicolon(e){if(is("punc",";"))next();else if(!e&&!can_insert_semicolon())unexpected()}function parenthesised(){expect("(");var e=expression(true);expect(")");return e}function embed_tokens(e){return function _embed_tokens_wrapper(...t){const n=r.token;const i=e(...t);i.start=n;i.end=prev();return i}}function handle_regexp(){if(is("operator","/")||is("operator","/=")){r.peeked=null;r.token=r.input(r.token.value.substr(1))}}var i=embed_tokens((function statement(e,n,i){handle_regexp();switch(r.token.type){case"string":if(r.in_directives){var o=peek();if(!s.includes("\\")&&(is_token(o,"punc",";")||is_token(o,"punc","}")||has_newline_before(o)||is_token(o,"eof"))){r.input.add_directive(r.token.value)}else{r.in_directives=false}}var a=r.in_directives,u=simple_statement();return a&&u.body instanceof Kt?new K(u.body):u;case"template_head":case"num":case"big_int":case"regexp":case"operator":case"atom":return simple_statement();case"name":if(r.token.value=="async"&&is_token(peek(),"keyword","function")){next();next();if(n){croak("functions are not allowed as the body of a loop")}return function_(ce,false,true,e)}if(r.token.value=="import"&&!is_token(peek(),"punc","(")&&!is_token(peek(),"punc",".")){next();var l=import_();semicolon();return l}return is_token(peek(),"punc",":")?labeled_statement():simple_statement();case"punc":switch(r.token.value){case"{":return new X({start:r.token,body:block_(),end:prev()});case"[":case"(":return simple_statement();case";":r.in_directives=false;next();return new W;default:unexpected()}case"keyword":switch(r.token.value){case"break":next();return break_cont(De);case"continue":next();return break_cont(be);case"debugger":next();semicolon();return new z;case"do":next();var c=in_loop(statement);expect_token("keyword","while");var f=parenthesised();semicolon(true);return new Z({body:c,condition:f});case"while":next();return new Q({condition:parenthesised(),body:in_loop((function(){return statement(false,true)}))});case"for":next();return for_();case"class":next();if(n){croak("classes are not allowed as the body of a loop")}if(i){croak("classes are not allowed as the body of an if")}return class_(mt,e);case"function":next();if(n){croak("functions are not allowed as the body of a loop")}return function_(ce,false,false,e);case"if":next();return if_();case"return":if(r.in_function==0&&!t.bare_returns)croak("'return' outside of function");next();var _=null;if(is("punc",";")){next()}else if(!can_insert_semicolon()){_=expression(true);semicolon()}return new Ee({value:_});case"switch":next();return new Te({expression:parenthesised(),body:in_loop(switch_body_)});case"throw":next();if(has_newline_before(r.token))croak("Illegal newline after 'throw'");var _=expression(true);semicolon();return new ge({value:_});case"try":next();return try_();case"var":next();var l=var_();semicolon();return l;case"let":next();var l=let_();semicolon();return l;case"const":next();var l=const_();semicolon();return l;case"with":if(r.input.has_directive("use strict")){croak("Strict mode may not include a with statement")}next();return new ne({expression:parenthesised(),body:statement()});case"export":if(!is_token(peek(),"punc","(")){next();var l=export_();if(is("punc",";"))semicolon();return l}}}unexpected()}));function labeled_statement(){var e=as_symbol(wt);if(e.name==="await"&&is_in_async()){token_error(r.prev,"await cannot be used as label inside async function")}if(r.labels.some((t=>t.name===e.name))){croak("Label "+e.name+" defined twice")}expect(":");r.labels.push(e);var t=i();r.labels.pop();if(!(t instanceof j)){e.references.forEach((function(t){if(t instanceof be){t=t.label.start;croak("Continue label `"+e.name+"` refers to non-IterationStatement.",t.line,t.col,t.pos)}}))}return new Y({body:t,label:e})}function simple_statement(e){return new G({body:(e=expression(true),semicolon(),e)})}function break_cont(e){var t=null,n;if(!can_insert_semicolon()){t=as_symbol(Lt,true)}if(t!=null){n=r.labels.find((e=>e.name===t.name));if(!n)croak("Undefined label "+t.name);t.thedef=n}else if(r.in_loop==0)croak(e.TYPE+" not inside a loop or switch");semicolon();var i=new e({label:t});if(n)n.references.push(i);return i}function for_(){var e="`for await` invalid in this context";var t=r.token;if(t.type=="name"&&t.value=="await"){if(!can_await()){token_error(t,e)}next()}else{t=false}expect("(");var n=null;if(!is("punc",";")){n=is("keyword","var")?(next(),var_(true)):is("keyword","let")?(next(),let_(true)):is("keyword","const")?(next(),const_(true)):expression(true,true);var i=is("operator","in");var o=is("name","of");if(t&&!o){token_error(t,e)}if(i||o){if(n instanceof xe){if(n.definitions.length>1)token_error(n.start,"Only one variable declaration allowed in for..in loop")}else if(!(is_assignable(n)||(n=to_destructuring(n))instanceof fe)){token_error(n.start,"Invalid left-hand side in for..in loop")}next();if(i){return for_in(n)}else{return for_of(n,!!t)}}}else if(t){token_error(t,e)}return regular_for(n)}function regular_for(e){expect(";");var t=is("punc",";")?null:expression(true);expect(";");var n=is("punc",")")?null:expression(true);expect(")");return new J({init:e,condition:t,step:n,body:in_loop((function(){return i(false,true)}))})}function for_of(e,t){var n=e instanceof xe?e.definitions[0].name:null;var r=expression(true);expect(")");return new te({await:t,init:e,name:n,object:r,body:in_loop((function(){return i(false,true)}))})}function for_in(e){var t=expression(true);expect(")");return new ee({init:e,object:t,body:in_loop((function(){return i(false,true)}))})}var arrow_function=function(e,t,n){if(has_newline_before(r.token)){croak("Unexpected newline before arrow (=>)")}expect_token("arrow","=>");var i=_function_body(is("punc","{"),false,n);var o=i instanceof Array&&i.length?i[i.length-1].end:i instanceof Array?e:i.end;return new le({start:e,end:o,async:n,argnames:t,body:i})};var function_=function(e,t,n,r){var i=e===ce;var o=is("operator","*");if(o){next()}var a=is("name")?as_symbol(i?Tt:Rt):null;if(i&&!a){if(r){e=ue}else{unexpected()}}if(a&&e!==se&&!(a instanceof vt))unexpected(prev());var s=[];var u=_function_body(true,o||t,n,a,s);return new e({start:s.start,end:u.end,is_generator:o,async:n,name:a,argnames:s,body:u})};function track_used_binding_identifiers(e,t){var n=new Set;var r=false;var i=false;var o=false;var a=!!t;var s={add_parameter:function(t){if(n.has(t.value)){if(r===false){r=t}s.check_strict()}else{n.add(t.value);if(e){switch(t.value){case"arguments":case"eval":case"yield":if(a){token_error(t,"Unexpected "+t.value+" identifier as parameter inside strict mode")}break;default:if(f.has(t.value)){unexpected()}}}}},mark_default_assignment:function(e){if(i===false){i=e}},mark_spread:function(e){if(o===false){o=e}},mark_strict_mode:function(){a=true},is_strict:function(){return i!==false||o!==false||a},check_strict:function(){if(s.is_strict()&&r!==false){token_error(r,"Parameter "+r.value+" was used already")}}};return s}function parameters(e){var t=track_used_binding_identifiers(true,r.input.has_directive("use strict"));expect("(");while(!is("punc",")")){var n=parameter(t);e.push(n);if(!is("punc",")")){expect(",")}if(n instanceof oe){break}}next()}function parameter(e,t){var n;var i=false;if(e===undefined){e=track_used_binding_identifiers(true,r.input.has_directive("use strict"))}if(is("expand","...")){i=r.token;e.mark_spread(r.token);next()}n=binding_element(e,t);if(is("operator","=")&&i===false){e.mark_default_assignment(r.token);next();n=new tt({start:n.start,left:n,operator:"=",right:expression(false),end:r.token})}if(i!==false){if(!is("punc",")")){unexpected()}n=new oe({start:i,expression:n,end:i})}e.check_strict();return n}function binding_element(e,t){var n=[];var i=true;var o=false;var a;var s=r.token;if(e===undefined){e=track_used_binding_identifiers(false,r.input.has_directive("use strict"))}t=t===undefined?yt:t;if(is("punc","[")){next();while(!is("punc","]")){if(i){i=false}else{expect(",")}if(is("expand","...")){o=true;a=r.token;e.mark_spread(r.token);next()}if(is("punc")){switch(r.token.value){case",":n.push(new $t({start:r.token,end:r.token}));continue;case"]":break;case"[":case"{":n.push(binding_element(e,t));break;default:unexpected()}}else if(is("name")){e.add_parameter(r.token);n.push(as_symbol(t))}else{croak("Invalid function parameter")}if(is("operator","=")&&o===false){e.mark_default_assignment(r.token);next();n[n.length-1]=new tt({start:n[n.length-1].start,left:n[n.length-1],operator:"=",right:expression(false),end:r.token})}if(o){if(!is("punc","]")){croak("Rest element must be last element")}n[n.length-1]=new oe({start:a,expression:n[n.length-1],end:a})}}expect("]");e.check_strict();return new fe({start:s,names:n,is_array:true,end:prev()})}else if(is("punc","{")){next();while(!is("punc","}")){if(i){i=false}else{expect(",")}if(is("expand","...")){o=true;a=r.token;e.mark_spread(r.token);next()}if(is("name")&&(is_token(peek(),"punc")||is_token(peek(),"operator"))&&[",","}","="].includes(peek().value)){e.add_parameter(r.token);var u=prev();var l=as_symbol(t);if(o){n.push(new oe({start:a,expression:l,end:l.end}))}else{n.push(new ot({start:u,key:l.name,value:l,end:l.end}))}}else if(is("punc","}")){continue}else{var c=r.token;var f=as_property_name();if(f===null){unexpected(prev())}else if(prev().type==="name"&&!is("punc",":")){n.push(new ot({start:prev(),key:f,value:new t({start:prev(),name:f,end:prev()}),end:prev()}))}else{expect(":");n.push(new ot({start:c,quote:c.quote,key:f,value:binding_element(e,t),end:prev()}))}}if(o){if(!is("punc","}")){croak("Rest element must be last element")}}else if(is("operator","=")){e.mark_default_assignment(r.token);next();n[n.length-1].value=new tt({start:n[n.length-1].value.start,left:n[n.length-1].value,operator:"=",right:expression(false),end:r.token})}}expect("}");e.check_strict();return new fe({start:s,names:n,is_array:false,end:prev()})}else if(is("name")){e.add_parameter(r.token);return as_symbol(t)}else{croak("Invalid function parameter")}}function params_or_seq_(e,t){var n;var i;var o;var a=[];expect("(");while(!is("punc",")")){if(n)unexpected(n);if(is("expand","...")){n=r.token;if(t)i=r.token;next();a.push(new oe({start:prev(),expression:expression(),end:r.token}))}else{a.push(expression())}if(!is("punc",")")){expect(",");if(is("punc",")")){o=prev();if(t)i=o}}}expect(")");if(e&&is("arrow","=>")){if(n&&o)unexpected(o)}else if(i){unexpected(i)}return a}function _function_body(e,t,n,i,o){var a=r.in_loop;var s=r.labels;var u=r.in_generator;var l=r.in_async;++r.in_function;if(t)r.in_generator=r.in_function;if(n)r.in_async=r.in_function;if(o)parameters(o);if(e)r.in_directives=true;r.in_loop=0;r.labels=[];if(e){r.input.push_directives_stack();var c=block_();if(i)_verify_symbol(i);if(o)o.forEach(_verify_symbol);r.input.pop_directives_stack()}else{var c=[new Ee({start:r.token,value:expression(false),end:r.token})]}--r.in_function;r.in_loop=a;r.labels=s;r.in_generator=u;r.in_async=l;return c}function _await_expression(){if(!can_await()){croak("Unexpected await expression outside async function",r.prev.line,r.prev.col,r.prev.pos)}return new Se({start:prev(),end:r.token,expression:maybe_unary(true)})}function _yield_expression(){if(!is_in_generator()){croak("Unexpected yield expression outside generator function",r.prev.line,r.prev.col,r.prev.pos)}var e=r.token;var t=false;var n=true;if(can_insert_semicolon()||is("punc")&&y.has(r.token.value)){n=false}else if(is("operator","*")){t=true;next()}return new Ae({start:e,is_star:t,expression:n?expression():null,end:prev()})}function if_(){var e=parenthesised(),t=i(false,false,true),n=null;if(is("keyword","else")){next();n=i(false,false,true)}return new ye({condition:e,body:t,alternative:n})}function block_(){expect("{");var e=[];while(!is("punc","}")){if(is("eof"))unexpected();e.push(i())}next();return e}function switch_body_(){expect("{");var e=[],t=null,n=null,o;while(!is("punc","}")){if(is("eof"))unexpected();if(is("keyword","case")){if(n)n.end=prev();t=[];n=new Re({start:(o=r.token,next(),o),expression:expression(true),body:t});e.push(n);expect(":")}else if(is("keyword","default")){if(n)n.end=prev();t=[];n=new Ce({start:(o=r.token,next(),expect(":"),o),body:t});e.push(n)}else{if(!t)unexpected();t.push(i())}}if(n)n.end=prev();next();return e}function try_(){var e=block_(),t=null,n=null;if(is("keyword","catch")){var i=r.token;next();if(is("punc","{")){var o=null}else{expect("(");var o=parameter(undefined,Mt);expect(")")}t=new Oe({start:i,argname:o,body:block_(),end:prev()})}if(is("keyword","finally")){var i=r.token;next();n=new Me({start:i,body:block_(),end:prev()})}if(!t&&!n)croak("Missing catch/finally blocks");return new Fe({body:e,bcatch:t,bfinally:n})}function vardefs(e,t){var n=[];var i;for(;;){var o=t==="var"?Dt:t==="const"?St:t==="let"?At:null;if(is("punc","{")||is("punc","[")){i=new Pe({start:r.token,name:binding_element(undefined,o),value:is("operator","=")?(expect_token("operator","="),expression(false,e)):null,end:prev()})}else{i=new Pe({start:r.token,name:as_symbol(o),value:is("operator","=")?(next(),expression(false,e)):!e&&t==="const"?croak("Missing initializer in const declaration"):null,end:prev()});if(i.name.name=="import")croak("Unexpected token: import")}n.push(i);if(!is("punc",","))break;next()}return n}var var_=function(e){return new Ne({start:prev(),definitions:vardefs(e,"var"),end:prev()})};var let_=function(e){return new we({start:prev(),definitions:vardefs(e,"let"),end:prev()})};var const_=function(e){return new Ie({start:prev(),definitions:vardefs(e,"const"),end:prev()})};var new_=function(e){var t=r.token;expect_token("operator","new");if(is("punc",".")){next();expect_token("name","target");return subscripts(new gt({start:t,end:prev()}),e)}var n=expr_atom(false),i;if(is("punc","(")){next();i=expr_list(")",true)}else{i=[]}var o=new Ke({start:t,expression:n,args:i,end:prev()});annotate(o);return subscripts(o,e)};function as_atom_node(){var e=r.token,t;switch(e.type){case"name":t=_make_symbol(It);break;case"num":t=new Gt({start:e,end:e,value:e.value,raw:s});break;case"big_int":t=new Ht({start:e,end:e,value:e.value});break;case"string":t=new Kt({start:e,end:e,value:e.value,quote:e.quote});break;case"regexp":const[n,r,i]=e.value.match(/^\/(.*)\/(\w*)$/);t=new Xt({start:e,end:e,value:{source:r,flags:i}});break;case"atom":switch(e.value){case"false":t=new Jt({start:e,end:e});break;case"true":t=new en({start:e,end:e});break;case"null":t=new qt({start:e,end:e});break}break}next();return t}function to_fun_args(e,t){var insert_default=function(e,t){if(t){return new tt({start:e.start,left:e,operator:"=",right:t,end:t.end})}return e};if(e instanceof rt){return insert_default(new fe({start:e.start,end:e.end,is_array:false,names:e.properties.map((e=>to_fun_args(e)))}),t)}else if(e instanceof ot){e.value=to_fun_args(e.value);return insert_default(e,t)}else if(e instanceof $t){return e}else if(e instanceof fe){e.names=e.names.map((e=>to_fun_args(e)));return insert_default(e,t)}else if(e instanceof It){return insert_default(new yt({name:e.name,start:e.start,end:e.end}),t)}else if(e instanceof oe){e.expression=to_fun_args(e.expression);return insert_default(e,t)}else if(e instanceof nt){return insert_default(new fe({start:e.start,end:e.end,is_array:true,names:e.elements.map((e=>to_fun_args(e)))}),t)}else if(e instanceof et){return insert_default(to_fun_args(e.left,e.right),t)}else if(e instanceof tt){e.left=to_fun_args(e.left);return e}else{croak("Invalid function parameter",e.start.line,e.start.col)}}var expr_atom=function(e,t){if(is("operator","new")){return new_(e)}if(is("operator","import")){return import_meta()}var i=r.token;var a;var s=is("name","async")&&(a=peek()).value!="["&&a.type!="arrow"&&as_atom_node();if(is("punc")){switch(r.token.value){case"(":if(s&&!e)break;var u=params_or_seq_(t,!s);if(t&&is("arrow","=>")){return arrow_function(i,u.map((e=>to_fun_args(e))),!!s)}var c=s?new ze({expression:s,args:u}):u.length==1?u[0]:new Ge({expressions:u});if(c.start){const e=i.comments_before.length;n.set(i,e);c.start.comments_before.unshift(...i.comments_before);i.comments_before=c.start.comments_before;if(e==0&&i.comments_before.length>0){var f=i.comments_before[0];if(!f.nlb){f.nlb=i.nlb;i.nlb=false}}i.comments_after=c.start.comments_after}c.start=i;var _=prev();if(c.end){_.comments_before=c.end.comments_before;c.end.comments_after.push(..._.comments_after);_.comments_after=c.end.comments_after}c.end=_;if(c instanceof ze)annotate(c);return subscripts(c,e);case"[":return subscripts(o(),e);case"{":return subscripts(l(),e)}if(!s)unexpected()}if(t&&is("name")&&is_token(peek(),"arrow")){var p=new yt({name:r.token.value,start:i,end:i});next();return arrow_function(i,[p],!!s)}if(is("keyword","function")){next();var d=function_(ue,false,!!s);d.start=i;d.end=prev();return subscripts(d,e)}if(s)return subscripts(s,e);if(is("keyword","class")){next();var m=class_(ht);m.start=i;m.end=prev();return subscripts(m,e)}if(is("template_head")){return subscripts(template_string(),e)}if(I.has(r.token.type)){return subscripts(as_atom_node(),e)}unexpected()};function template_string(){var e=[],t=r.token;e.push(new de({start:r.token,raw:s,value:r.token.value,end:r.token}));while(!u){next();handle_regexp();e.push(expression(true));e.push(new de({start:r.token,raw:s,value:r.token.value,end:r.token}))}next();return new pe({start:t,segments:e,end:r.token})}function expr_list(e,t,n){var i=true,o=[];while(!is("punc",e)){if(i)i=false;else expect(",");if(t&&is("punc",e))break;if(is("punc",",")&&n){o.push(new $t({start:r.token,end:r.token}))}else if(is("expand","...")){next();o.push(new oe({start:prev(),expression:expression(),end:r.token}))}else{o.push(expression(false))}}next();return o}var o=embed_tokens((function(){expect("[");return new nt({elements:expr_list("]",!t.strict,true)})}));var a=embed_tokens(((e,t)=>function_(se,e,t)));var l=embed_tokens((function object_or_destructuring_(){var e=r.token,n=true,i=[];expect("{");while(!is("punc","}")){if(n)n=false;else expect(",");if(!t.strict&&is("punc","}"))break;e=r.token;if(e.type=="expand"){next();i.push(new oe({start:e,expression:expression(false),end:prev()}));continue}var o=as_property_name();var a;if(!is("punc",":")){var s=concise_method_or_getset(o,e);if(s){i.push(s);continue}a=new It({start:prev(),name:o,end:prev()})}else if(o===null){unexpected(prev())}else{next();a=expression(false)}if(is("operator","=")){next();a=new et({start:e,left:a,operator:"=",right:expression(false),logical:false,end:prev()})}i.push(new ot({start:e,quote:e.quote,key:o instanceof V?o:""+o,value:a,end:prev()}))}next();return new rt({properties:i})}));function class_(e,t){var n,i,o,a,s=[];r.input.push_directives_stack();r.input.add_directive("use strict");if(r.token.type=="name"&&r.token.value!="extends"){o=as_symbol(e===mt?Ft:Ot)}if(e===mt&&!o){if(t){e=ht}else{unexpected()}}if(r.token.value=="extends"){next();a=expression(true)}expect("{");while(is("punc",";")){next()}while(!is("punc","}")){n=r.token;i=concise_method_or_getset(as_property_name(),n,true);if(!i){unexpected()}s.push(i);while(is("punc",";")){next()}}r.input.pop_directives_stack();next();return new e({start:n,name:o,extends:a,properties:s,end:prev()})}function concise_method_or_getset(e,t,n){const get_symbol_ast=(e,n=kt)=>{if(typeof e==="string"||typeof e==="number"){return new n({start:t,name:""+e,end:prev()})}else if(e===null){unexpected()}return e};const is_not_method_start=()=>!is("punc","(")&&!is("punc",",")&&!is("punc","}")&&!is("operator","=");var r=false;var i=false;var o=false;var s=false;var u=null;if(n&&e==="static"&&is_not_method_start()){i=true;e=as_property_name()}if(e==="async"&&is_not_method_start()){r=true;e=as_property_name()}if(prev().type==="operator"&&prev().value==="*"){o=true;e=as_property_name()}if((e==="get"||e==="set")&&is_not_method_start()){u=e;e=as_property_name()}if(prev().type==="privatename"){s=true}const l=prev();if(u!=null){if(!s){const n=u==="get"?lt:ut;e=get_symbol_ast(e);return new n({start:t,static:i,key:e,quote:e instanceof kt?l.quote:undefined,value:a(),end:prev()})}else{const n=u==="get"?st:at;return new n({start:t,static:i,key:get_symbol_ast(e),value:a(),end:prev()})}}if(is("punc","(")){e=get_symbol_ast(e);const n=s?ft:ct;var c=new n({start:t,static:i,is_generator:o,async:r,key:e,quote:e instanceof kt?l.quote:undefined,value:a(o,r),end:prev()});return c}if(n){const n=get_symbol_ast(e,Ct);const r=n instanceof Ct?l.quote:undefined;const o=s?dt:pt;if(is("operator","=")){next();return new o({start:t,static:i,quote:r,key:n,value:expression(false),end:prev()})}else if(is("name")||is("privatename")||is("operator","*")||is("punc",";")||is("punc","}")){return new o({start:t,static:i,quote:r,key:n,end:prev()})}}}function import_(){var e=prev();var t;var n;if(is("name")){t=as_symbol(xt)}if(is("punc",",")){next()}n=map_names(true);if(n||t){expect_token("name","from")}var i=r.token;if(i.type!=="string"){unexpected()}next();return new Le({start:e,imported_name:t,imported_names:n,module_name:new Kt({start:i,value:i.value,quote:i.quote,end:i}),end:r.token})}function import_meta(){var e=r.token;expect_token("operator","import");expect_token("punc",".");expect_token("name","meta");return subscripts(new Ve({start:e,end:prev()}),false)}function map_name(e){function make_symbol(e){return new e({name:as_property_name(),start:prev(),end:prev()})}var t=e?Nt:Bt;var n=e?xt:Pt;var i=r.token;var o;var a;if(e){o=make_symbol(t)}else{a=make_symbol(n)}if(is("name","as")){next();if(e){a=make_symbol(n)}else{o=make_symbol(t)}}else if(e){a=new n(o)}else{o=new t(a)}return new Be({start:i,foreign_name:o,name:a,end:prev()})}function map_nameAsterisk(e,t){var n=e?Nt:Bt;var i=e?xt:Pt;var o=r.token;var a;var s=prev();t=t||new i({name:"*",start:o,end:s});a=new n({name:"*",start:o,end:s});return new Be({start:o,foreign_name:a,name:t,end:s})}function map_names(e){var t;if(is("punc","{")){next();t=[];while(!is("punc","}")){t.push(map_name(e));if(is("punc",",")){next()}}next()}else if(is("operator","*")){var n;next();if(e&&is("name","as")){next();n=as_symbol(e?xt:Bt)}t=[map_nameAsterisk(e,n)]}return t}function export_(){var e=r.token;var t;var n;if(is("keyword","default")){t=true;next()}else if(n=map_names(false)){if(is("name","from")){next();var o=r.token;if(o.type!=="string"){unexpected()}next();return new Ue({start:e,is_default:t,exported_names:n,module_name:new Kt({start:o,value:o.value,quote:o.quote,end:o}),end:prev()})}else{return new Ue({start:e,is_default:t,exported_names:n,end:prev()})}}var a;var s;var u;if(is("punc","{")||t&&(is("keyword","class")||is("keyword","function"))&&is_token(peek(),"punc")){s=expression(false);semicolon()}else if((a=i(t))instanceof xe&&t){unexpected(a.start)}else if(a instanceof xe||a instanceof ce||a instanceof mt){u=a}else if(a instanceof ht||a instanceof ue){s=a}else if(a instanceof G){s=a.body}else{unexpected(a.start)}return new Ue({start:e,is_default:t,exported_value:s,exported_definition:u,end:prev()})}function as_property_name(){var e=r.token;switch(e.type){case"punc":if(e.value==="["){next();var t=expression(false);expect("]");return t}else unexpected(e);case"operator":if(e.value==="*"){next();return null}if(!["delete","in","instanceof","new","typeof","void"].includes(e.value)){unexpected(e)}case"name":case"privatename":case"string":case"num":case"big_int":case"keyword":case"atom":next();return e.value;default:unexpected(e)}}function as_name(){var e=r.token;if(e.type!="name"&&e.type!="privatename")unexpected();next();return e.value}function _make_symbol(e){var t=r.token.value;return new(t=="this"?Vt:t=="super"?Ut:e)({name:String(t),start:r.token,end:r.token})}function _verify_symbol(e){var t=e.name;if(is_in_generator()&&t=="yield"){token_error(e.start,"Yield cannot be used as identifier inside generators")}if(r.input.has_directive("use strict")){if(t=="yield"){token_error(e.start,"Unexpected yield identifier inside strict mode")}if(e instanceof vt&&(t=="arguments"||t=="eval")){token_error(e.start,"Unexpected "+t+" in strict mode")}}}function as_symbol(e,t){if(!is("name")){if(!t)croak("Name expected");return null}var n=_make_symbol(e);_verify_symbol(n);next();return n}function annotate(e){var t=e.start;var r=t.comments_before;const i=n.get(t);var o=i!=null?i:r.length;while(--o>=0){var a=r[o];if(/[@#]__/.test(a.value)){if(/[@#]__PURE__/.test(a.value)){set_annotation(e,nn);break}if(/[@#]__INLINE__/.test(a.value)){set_annotation(e,rn);break}if(/[@#]__NOINLINE__/.test(a.value)){set_annotation(e,on);break}}}}var subscripts=function(e,t,n){var r=e.start;if(is("punc",".")){next();const i=is("privatename")?We:Xe;return subscripts(new i({start:r,expression:e,optional:false,property:as_name(),end:prev()}),t,n)}if(is("punc","[")){next();var i=expression(true);expect("]");return subscripts(new qe({start:r,expression:e,optional:false,property:i,end:prev()}),t,n)}if(t&&is("punc","(")){next();var o=new ze({start:r,expression:e,optional:false,args:call_args(),end:prev()});annotate(o);return subscripts(o,true,n)}if(is("punc","?.")){next();let n;if(t&&is("punc","(")){next();const t=new ze({start:r,optional:true,expression:e,args:call_args(),end:prev()});annotate(t);n=subscripts(t,true,true)}else if(is("name")||is("privatename")){const i=is("privatename")?We:Xe;n=subscripts(new i({start:r,expression:e,optional:true,property:as_name(),end:prev()}),t,true)}else if(is("punc","[")){next();const i=expression(true);expect("]");n=subscripts(new qe({start:r,expression:e,optional:true,property:i,end:prev()}),t,true)}if(!n)unexpected();if(n instanceof Ye)return n;return new Ye({start:r,expression:n,end:prev()})}if(is("template_head")){if(n){unexpected()}return subscripts(new _e({start:r,prefix:e,template_string:template_string(),end:prev()}),t)}return e};function call_args(){var e=[];while(!is("punc",")")){if(is("expand","...")){next();e.push(new oe({start:prev(),expression:expression(false),end:prev()}))}else{e.push(expression(false))}if(!is("punc",")")){expect(",")}}next();return e}var maybe_unary=function(e,t){var n=r.token;if(n.type=="name"&&n.value=="await"&&can_await()){next();return _await_expression()}if(is("operator")&&O.has(n.value)){next();handle_regexp();var i=make_unary($e,n,maybe_unary(e));i.start=n;i.end=prev();return i}var o=expr_atom(e,t);while(is("operator")&&M.has(r.token.value)&&!has_newline_before(r.token)){if(o instanceof le)unexpected();o=make_unary(Ze,r.token,o);o.start=n;o.end=r.token;next()}return o};function make_unary(e,t,n){var i=t.value;switch(i){case"++":case"--":if(!is_assignable(n))croak("Invalid use of "+i+" operator",t.line,t.col,t.pos);break;case"delete":if(n instanceof It&&r.input.has_directive("use strict"))croak("Calling delete on expression not allowed in strict mode",n.start.line,n.start.col,n.start.pos);break}return new e({operator:i,expression:n})}var expr_op=function(e,t,n){var i=is("operator")?r.token.value:null;if(i=="in"&&n)i=null;if(i=="**"&&e instanceof $e&&!is_token(e.start,"punc","(")&&e.operator!=="--"&&e.operator!=="++")unexpected(e.start);var o=i!=null?w[i]:null;if(o!=null&&(o>t||i==="**"&&t===o)){next();var a=expr_op(maybe_unary(true),o,n);return expr_op(new Qe({start:e.start,left:e,operator:i,right:a,end:a.end}),t,n)}return e};function expr_ops(e){return expr_op(maybe_unary(true,true),0,e)}var maybe_conditional=function(e){var t=r.token;var n=expr_ops(e);if(is("operator","?")){next();var i=expression(false);expect(":");return new Je({start:t,condition:n,consequent:i,alternative:expression(false,e),end:prev()})}return n};function is_assignable(e){return e instanceof He||e instanceof It}function to_destructuring(e){if(e instanceof rt){e=new fe({start:e.start,names:e.properties.map(to_destructuring),is_array:false,end:e.end})}else if(e instanceof nt){var t=[];for(var n=0;n=0;){o+="this."+t[a]+" = props."+t[a]+";"}const s=r&&Object.create(r.prototype);if(s&&s.initialize||n&&n.initialize)o+="this.initialize();";o+="}";o+="this.flags = 0;";o+="}";var u=new Function(o)();if(s){u.prototype=s;u.BASE=r}if(r)r.SUBCLASSES.push(u);u.prototype.CTOR=u;u.prototype.constructor=u;u.PROPS=t||null;u.SELF_PROPS=i;u.SUBCLASSES=[];if(e){u.prototype.TYPE=u.TYPE=e}if(n)for(a in n)if(HOP(n,a)){if(a[0]==="$"){u[a.substr(1)]=n[a]}else{u.prototype[a]=n[a]}}u.DEFMETHOD=function(e,t){this.prototype[e]=t};return u}const has_tok_flag=(e,t)=>Boolean(e.flags&t);const set_tok_flag=(e,t,n)=>{if(n){e.flags|=t}else{e.flags&=~t}};const P=1;const B=2;const L=4;class AST_Token{constructor(e,t,n,r,i,o,a,s,u){this.flags=o?1:0;this.type=e;this.value=t;this.line=n;this.col=r;this.pos=i;this.comments_before=a;this.comments_after=s;this.file=u;Object.seal(this)}get nlb(){return has_tok_flag(this,P)}set nlb(e){set_tok_flag(this,P,e)}get quote(){return!has_tok_flag(this,L)?"":has_tok_flag(this,B)?"'":'"'}set quote(e){set_tok_flag(this,B,e==="'");set_tok_flag(this,L,!!e)}}var V=DEFNODE("Node","start end",{_clone:function(e){if(e){var t=this.clone();return t.transform(new TreeTransformer((function(e){if(e!==t){return e.clone(true)}})))}return new this.CTOR(this)},clone:function(e){return this._clone(e)},$documentation:"Base class of all AST nodes",$propdoc:{start:"[AST_Token] The first token of this node",end:"[AST_Token] The last token of this node"},_walk:function(e){return e._visit(this)},walk:function(e){return this._walk(e)},_children_backwards:()=>{}},null);var U=DEFNODE("Statement",null,{$documentation:"Base class of all statements"});var z=DEFNODE("Debugger",null,{$documentation:"Represents a debugger statement"},U);var K=DEFNODE("Directive","value quote",{$documentation:'Represents a directive, like "use strict";',$propdoc:{value:"[string] The value of this directive as a plain string (it's not an AST_String!)",quote:"[string] the original quote character"}},U);var G=DEFNODE("SimpleStatement","body",{$documentation:"A statement consisting of an expression, i.e. a = 1 + 2",$propdoc:{body:"[AST_Node] an expression node (should not be instanceof AST_Statement)"},_walk:function(e){return e._visit(this,(function(){this.body._walk(e)}))},_children_backwards(e){e(this.body)}},U);function walk_body(e,t){const n=e.body;for(var r=0,i=n.length;r SymbolDef for all variables/functions defined in this scope",uses_with:"[boolean/S] tells whether this scope uses the `with` statement",uses_eval:"[boolean/S] tells whether this scope contains a direct call to the global `eval`",parent_scope:"[AST_Scope?/S] link to the parent scope",enclosed:"[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",cname:"[integer/S] current index for mangling variables (used internally by the mangler)"},get_defun_scope:function(){var e=this;while(e.is_block_scope()){e=e.parent_scope}return e},clone:function(e,t){var n=this._clone(e);if(e&&this.variables&&t&&!this._block_scope){n.figure_out_scope({},{toplevel:t,parent_scope:this.parent_scope})}else{if(this.variables)n.variables=new Map(this.variables);if(this.enclosed)n.enclosed=this.enclosed.slice();if(this._block_scope)n._block_scope=this._block_scope}return n},pinned:function(){return this.uses_eval||this.uses_with}},H);var ie=DEFNODE("Toplevel","globals",{$documentation:"The toplevel scope",$propdoc:{globals:"[Map/S] a map of name -> SymbolDef for all undeclared names"},wrap_commonjs:function(e){var t=this.body;var n="(function(exports){'$ORIG';})(typeof "+e+"=='undefined'?("+e+"={}):"+e+");";n=parse(n);n=n.transform(new TreeTransformer((function(e){if(e instanceof K&&e.value=="$ORIG"){return i.splice(t)}})));return n},wrap_enclose:function(e){if(typeof e!="string")e="";var t=e.indexOf(":");if(t<0)t=e.length;var n=this.body;return parse(["(function(",e.slice(0,t),'){"$ORIG"})(',e.slice(t+1),")"].join("")).transform(new TreeTransformer((function(e){if(e instanceof K&&e.value=="$ORIG"){return i.splice(n)}})))}},re);var oe=DEFNODE("Expansion","expression",{$documentation:"An expandible argument, such as ...rest, a splat, such as [1,2,...all], or an expansion in a variable declaration, such as var [first, ...rest] = list",$propdoc:{expression:"[AST_Node] the thing to be expanded"},_walk:function(e){return e._visit(this,(function(){this.expression.walk(e)}))},_children_backwards(e){e(this.expression)}});var ae=DEFNODE("Lambda","name argnames uses_arguments is_generator async",{$documentation:"Base class for functions",$propdoc:{name:"[AST_SymbolDeclaration?] the name of this function",argnames:"[AST_SymbolFunarg|AST_Destructuring|AST_Expansion|AST_DefaultAssign*] array of function arguments, destructurings, or expanding arguments",uses_arguments:"[boolean/S] tells whether this function accesses the arguments array",is_generator:"[boolean] is this a generator method",async:"[boolean] is this method async"},args_as_names:function(){var e=[];for(var t=0;t b)"},ae);var ce=DEFNODE("Defun",null,{$documentation:"A function definition"},ae);var fe=DEFNODE("Destructuring","names is_array",{$documentation:"A destructuring of several names. Used in destructuring assignment and with destructuring function argument names",$propdoc:{names:"[AST_Node*] Array of properties or elements",is_array:"[Boolean] Whether the destructuring represents an object or array"},_walk:function(e){return e._visit(this,(function(){this.names.forEach((function(t){t._walk(e)}))}))},_children_backwards(e){let t=this.names.length;while(t--)e(this.names[t])},all_symbols:function(){var e=[];this.walk(new TreeWalker((function(t){if(t instanceof Et){e.push(t)}})));return e}});var _e=DEFNODE("PrefixedTemplateString","template_string prefix",{$documentation:"A templatestring with a prefix, such as String.raw`foobarbaz`",$propdoc:{template_string:"[AST_TemplateString] The template string",prefix:"[AST_Node] The prefix, which will get called."},_walk:function(e){return e._visit(this,(function(){this.prefix._walk(e);this.template_string._walk(e)}))},_children_backwards(e){e(this.template_string);e(this.prefix)}});var pe=DEFNODE("TemplateString","segments",{$documentation:"A template string literal",$propdoc:{segments:"[AST_Node*] One or more segments, starting with AST_TemplateSegment. AST_Node may follow AST_TemplateSegment, but each AST_Node must be followed by AST_TemplateSegment."},_walk:function(e){return e._visit(this,(function(){this.segments.forEach((function(t){t._walk(e)}))}))},_children_backwards(e){let t=this.segments.length;while(t--)e(this.segments[t])}});var de=DEFNODE("TemplateSegment","value raw",{$documentation:"A segment of a template string literal",$propdoc:{value:"Content of the segment",raw:"Raw source of the segment"}});var me=DEFNODE("Jump",null,{$documentation:"Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"},U);var he=DEFNODE("Exit","value",{$documentation:"Base class for “exits” (`return` and `throw`)",$propdoc:{value:"[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"},_walk:function(e){return e._visit(this,this.value&&function(){this.value._walk(e)})},_children_backwards(e){if(this.value)e(this.value)}},me);var Ee=DEFNODE("Return",null,{$documentation:"A `return` statement"},he);var ge=DEFNODE("Throw",null,{$documentation:"A `throw` statement"},he);var ve=DEFNODE("LoopControl","label",{$documentation:"Base class for loop control statements (`break` and `continue`)",$propdoc:{label:"[AST_LabelRef?] the label, or null if none"},_walk:function(e){return e._visit(this,this.label&&function(){this.label._walk(e)})},_children_backwards(e){if(this.label)e(this.label)}},me);var De=DEFNODE("Break",null,{$documentation:"A `break` statement"},ve);var be=DEFNODE("Continue",null,{$documentation:"A `continue` statement"},ve);var Se=DEFNODE("Await","expression",{$documentation:"An `await` statement",$propdoc:{expression:"[AST_Node] the mandatory expression being awaited"},_walk:function(e){return e._visit(this,(function(){this.expression._walk(e)}))},_children_backwards(e){e(this.expression)}});var Ae=DEFNODE("Yield","expression is_star",{$documentation:"A `yield` statement",$propdoc:{expression:"[AST_Node?] the value returned or thrown by this statement; could be null (representing undefined) but only when is_star is set to false",is_star:"[Boolean] Whether this is a yield or yield* statement"},_walk:function(e){return e._visit(this,this.expression&&function(){this.expression._walk(e)})},_children_backwards(e){if(this.expression)e(this.expression)}});var ye=DEFNODE("If","condition alternative",{$documentation:"A `if` statement",$propdoc:{condition:"[AST_Node] the `if` condition",alternative:"[AST_Statement?] the `else` part, or null if not present"},_walk:function(e){return e._visit(this,(function(){this.condition._walk(e);this.body._walk(e);if(this.alternative)this.alternative._walk(e)}))},_children_backwards(e){if(this.alternative){e(this.alternative)}e(this.body);e(this.condition)}},q);var Te=DEFNODE("Switch","expression",{$documentation:"A `switch` statement",$propdoc:{expression:"[AST_Node] the `switch` “discriminant”"},_walk:function(e){return e._visit(this,(function(){this.expression._walk(e);walk_body(this,e)}))},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},H);var ke=DEFNODE("SwitchBranch",null,{$documentation:"Base class for `switch` branches"},H);var Ce=DEFNODE("Default",null,{$documentation:"A `default` switch branch"},ke);var Re=DEFNODE("Case","expression",{$documentation:"A `case` switch branch",$propdoc:{expression:"[AST_Node] the `case` expression"},_walk:function(e){return e._visit(this,(function(){this.expression._walk(e);walk_body(this,e)}))},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},ke);var Fe=DEFNODE("Try","bcatch bfinally",{$documentation:"A `try` statement",$propdoc:{bcatch:"[AST_Catch?] the catch block, or null if not present",bfinally:"[AST_Finally?] the finally block, or null if not present"},_walk:function(e){return e._visit(this,(function(){walk_body(this,e);if(this.bcatch)this.bcatch._walk(e);if(this.bfinally)this.bfinally._walk(e)}))},_children_backwards(e){if(this.bfinally)e(this.bfinally);if(this.bcatch)e(this.bcatch);let t=this.body.length;while(t--)e(this.body[t])}},H);var Oe=DEFNODE("Catch","argname",{$documentation:"A `catch` node; only makes sense as part of a `try` statement",$propdoc:{argname:"[AST_SymbolCatch|AST_Destructuring|AST_Expansion|AST_DefaultAssign] symbol for the exception"},_walk:function(e){return e._visit(this,(function(){if(this.argname)this.argname._walk(e);walk_body(this,e)}))},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);if(this.argname)e(this.argname)}},H);var Me=DEFNODE("Finally",null,{$documentation:"A `finally` node; only makes sense as part of a `try` statement"},H);var xe=DEFNODE("Definitions","definitions",{$documentation:"Base class for `var` or `const` nodes (variable declarations/initializations)",$propdoc:{definitions:"[AST_VarDef*] array of variable definitions"},_walk:function(e){return e._visit(this,(function(){var t=this.definitions;for(var n=0,r=t.length;n a`"},Qe);var nt=DEFNODE("Array","elements",{$documentation:"An array literal",$propdoc:{elements:"[AST_Node*] array of elements"},_walk:function(e){return e._visit(this,(function(){var t=this.elements;for(var n=0,r=t.length;nt._walk(e)))}))},_children_backwards(e){let t=this.properties.length;while(t--)e(this.properties[t]);if(this.extends)e(this.extends);if(this.name)e(this.name)}},re);var pt=DEFNODE("ClassProperty","static quote",{$documentation:"A class property",$propdoc:{static:"[boolean] whether this is a static key",quote:"[string] which quote is being used"},_walk:function(e){return e._visit(this,(function(){if(this.key instanceof V)this.key._walk(e);if(this.value instanceof V)this.value._walk(e)}))},_children_backwards(e){if(this.value instanceof V)e(this.value);if(this.key instanceof V)e(this.key)},computed_key(){return!(this.key instanceof Ct)}},it);var dt=DEFNODE("ClassProperty","",{$documentation:"A class property for a private property"},pt);var mt=DEFNODE("DefClass",null,{$documentation:"A class definition"},_t);var ht=DEFNODE("ClassExpression",null,{$documentation:"A class expression."},_t);var Et=DEFNODE("Symbol","scope name thedef",{$propdoc:{name:"[string] name of this symbol",scope:"[AST_Scope/S] the current scope (not necessarily the definition scope)",thedef:"[SymbolDef/S] the definition of this symbol"},$documentation:"Base class for all symbols"});var gt=DEFNODE("NewTarget",null,{$documentation:"A reference to new.target"});var vt=DEFNODE("SymbolDeclaration","init",{$documentation:"A declaration symbol (symbol in var/const, function name or argument, symbol in catch)"},Et);var Dt=DEFNODE("SymbolVar",null,{$documentation:"Symbol defining a variable"},vt);var bt=DEFNODE("SymbolBlockDeclaration",null,{$documentation:"Base class for block-scoped declaration symbols"},vt);var St=DEFNODE("SymbolConst",null,{$documentation:"A constant declaration"},bt);var At=DEFNODE("SymbolLet",null,{$documentation:"A block-scoped `let` declaration"},bt);var yt=DEFNODE("SymbolFunarg",null,{$documentation:"Symbol naming a function argument"},Dt);var Tt=DEFNODE("SymbolDefun",null,{$documentation:"Symbol defining a function"},vt);var kt=DEFNODE("SymbolMethod",null,{$documentation:"Symbol in an object defining a method"},Et);var Ct=DEFNODE("SymbolClassProperty",null,{$documentation:"Symbol for a class property"},Et);var Rt=DEFNODE("SymbolLambda",null,{$documentation:"Symbol naming a function expression"},vt);var Ft=DEFNODE("SymbolDefClass",null,{$documentation:"Symbol naming a class's name in a class declaration. Lexically scoped to its containing scope, and accessible within the class."},bt);var Ot=DEFNODE("SymbolClass",null,{$documentation:"Symbol naming a class's name. Lexically scoped to the class."},vt);var Mt=DEFNODE("SymbolCatch",null,{$documentation:"Symbol naming the exception in catch"},bt);var xt=DEFNODE("SymbolImport",null,{$documentation:"Symbol referring to an imported name"},bt);var Nt=DEFNODE("SymbolImportForeign",null,{$documentation:"A symbol imported from a module, but it is defined in the other module, and its real name is irrelevant for this module's purposes"},Et);var wt=DEFNODE("Label","references",{$documentation:"Symbol naming a label (declaration)",$propdoc:{references:"[AST_LoopControl*] a list of nodes referring to this label"},initialize:function(){this.references=[];this.thedef=this}},Et);var It=DEFNODE("SymbolRef",null,{$documentation:"Reference to some symbol (not definition/declaration)"},Et);var Pt=DEFNODE("SymbolExport",null,{$documentation:"Symbol referring to a name to export"},It);var Bt=DEFNODE("SymbolExportForeign",null,{$documentation:"A symbol exported from this module, but it is used in the other module, and its real name is irrelevant for this module's purposes"},Et);var Lt=DEFNODE("LabelRef",null,{$documentation:"Reference to a label symbol"},Et);var Vt=DEFNODE("This",null,{$documentation:"The `this` symbol"},Et);var Ut=DEFNODE("Super",null,{$documentation:"The `super` symbol"},Vt);var zt=DEFNODE("Constant",null,{$documentation:"Base class for all constants",getValue:function(){return this.value}});var Kt=DEFNODE("String","value quote",{$documentation:"A string literal",$propdoc:{value:"[string] the contents of this string",quote:"[string] the original quote character"}},zt);var Gt=DEFNODE("Number","value raw",{$documentation:"A number literal",$propdoc:{value:"[number] the numeric value",raw:"[string] numeric value as string"}},zt);var Ht=DEFNODE("BigInt","value",{$documentation:"A big int literal",$propdoc:{value:"[string] big int value"}},zt);var Xt=DEFNODE("RegExp","value",{$documentation:"A regexp literal",$propdoc:{value:"[RegExp] the actual regexp"}},zt);var Wt=DEFNODE("Atom",null,{$documentation:"Base class for atoms"},zt);var qt=DEFNODE("Null",null,{$documentation:"The `null` atom",value:null},Wt);var Yt=DEFNODE("NaN",null,{$documentation:"The impossible value",value:0/0},Wt);var jt=DEFNODE("Undefined",null,{$documentation:"The `undefined` value",value:function(){}()},Wt);var $t=DEFNODE("Hole",null,{$documentation:"A hole in an array",value:function(){}()},Wt);var Zt=DEFNODE("Infinity",null,{$documentation:"The `Infinity` value",value:1/0},Wt);var Qt=DEFNODE("Boolean",null,{$documentation:"Base class for booleans"},Wt);var Jt=DEFNODE("False",null,{$documentation:"The `false` atom",value:false},Qt);var en=DEFNODE("True",null,{$documentation:"The `true` atom",value:true},Qt);function walk(e,t,n=[e]){const r=n.push.bind(n);while(n.length){const e=n.pop();const i=t(e,n);if(i){if(i===tn)return true;continue}e._children_backwards(r)}return false}function walk_parent(e,t,n){const r=[e];const i=r.push.bind(r);const o=n?n.slice():[];const a=[];let s;const u={parent:(e=0)=>{if(e===-1){return s}if(n&&e>=o.length){e-=o.length;return n[n.length-(e+1)]}return o[o.length-(1+e)]}};while(r.length){s=r.pop();while(a.length&&r.length==a[a.length-1]){o.pop();a.pop()}const e=t(s,u);if(e){if(e===tn)return true;continue}const n=r.length;s._children_backwards(i);if(r.length>n){o.push(s);a.push(n-1)}}return false}const tn=Symbol("abort walk");class TreeWalker{constructor(e){this.visit=e;this.stack=[];this.directives=Object.create(null)}_visit(e,t){this.push(e);var n=this.visit(e,t?function(){t.call(e)}:noop);if(!n&&t){t.call(e)}this.pop();return n}parent(e){return this.stack[this.stack.length-2-(e||0)]}push(e){if(e instanceof ae){this.directives=Object.create(this.directives)}else if(e instanceof K&&!this.directives[e.value]){this.directives[e.value]=e}else if(e instanceof _t){this.directives=Object.create(this.directives);if(!this.directives["use strict"]){this.directives["use strict"]=e}}this.stack.push(e)}pop(){var e=this.stack.pop();if(e instanceof ae||e instanceof _t){this.directives=Object.getPrototypeOf(this.directives)}}self(){return this.stack[this.stack.length-1]}find_parent(e){var t=this.stack;for(var n=t.length;--n>=0;){var r=t[n];if(r instanceof e)return r}}has_directive(e){var t=this.directives[e];if(t)return t;var n=this.stack[this.stack.length-1];if(n instanceof re&&n.body){for(var r=0;r=0;){var r=t[n];if(r instanceof Y&&r.label.name==e.label.name)return r.body}else for(var n=t.length;--n>=0;){var r=t[n];if(r instanceof j||e instanceof De&&r instanceof Te)return r}}}class TreeTransformer extends TreeWalker{constructor(e,t){super();this.before=e;this.after=t}}const nn=1;const rn=2;const on=4;var an=Object.freeze({__proto__:null,AST_Accessor:se,AST_Array:nt,AST_Arrow:le,AST_Assign:et,AST_Atom:Wt,AST_Await:Se,AST_BigInt:Ht,AST_Binary:Qe,AST_Block:H,AST_BlockStatement:X,AST_Boolean:Qt,AST_Break:De,AST_Call:ze,AST_Case:Re,AST_Catch:Oe,AST_Chain:Ye,AST_Class:_t,AST_ClassExpression:ht,AST_ClassPrivateProperty:dt,AST_ClassProperty:pt,AST_ConciseMethod:ct,AST_Conditional:Je,AST_Const:Ie,AST_Constant:zt,AST_Continue:be,AST_Debugger:z,AST_Default:Ce,AST_DefaultAssign:tt,AST_DefClass:mt,AST_Definitions:xe,AST_Defun:ce,AST_Destructuring:fe,AST_Directive:K,AST_Do:Z,AST_Dot:Xe,AST_DotHash:We,AST_DWLoop:$,AST_EmptyStatement:W,AST_Exit:he,AST_Expansion:oe,AST_Export:Ue,AST_False:Jt,AST_Finally:Me,AST_For:J,AST_ForIn:ee,AST_ForOf:te,AST_Function:ue,AST_Hole:$t,AST_If:ye,AST_Import:Le,AST_ImportMeta:Ve,AST_Infinity:Zt,AST_IterationStatement:j,AST_Jump:me,AST_Label:wt,AST_LabeledStatement:Y,AST_LabelRef:Lt,AST_Lambda:ae,AST_Let:we,AST_LoopControl:ve,AST_NameMapping:Be,AST_NaN:Yt,AST_New:Ke,AST_NewTarget:gt,AST_Node:V,AST_Null:qt,AST_Number:Gt,AST_Object:rt,AST_ObjectGetter:lt,AST_ObjectKeyVal:ot,AST_ObjectProperty:it,AST_ObjectSetter:ut,AST_PrefixedTemplateString:_e,AST_PrivateGetter:st,AST_PrivateMethod:ft,AST_PrivateSetter:at,AST_PropAccess:He,AST_RegExp:Xt,AST_Return:Ee,AST_Scope:re,AST_Sequence:Ge,AST_SimpleStatement:G,AST_Statement:U,AST_StatementWithBody:q,AST_String:Kt,AST_Sub:qe,AST_Super:Ut,AST_Switch:Te,AST_SwitchBranch:ke,AST_Symbol:Et,AST_SymbolBlockDeclaration:bt,AST_SymbolCatch:Mt,AST_SymbolClass:Ot,AST_SymbolClassProperty:Ct,AST_SymbolConst:St,AST_SymbolDeclaration:vt,AST_SymbolDefClass:Ft,AST_SymbolDefun:Tt,AST_SymbolExport:Pt,AST_SymbolExportForeign:Bt,AST_SymbolFunarg:yt,AST_SymbolImport:xt,AST_SymbolImportForeign:Nt,AST_SymbolLambda:Rt,AST_SymbolLet:At,AST_SymbolMethod:kt,AST_SymbolRef:It,AST_SymbolVar:Dt,AST_TemplateSegment:de,AST_TemplateString:pe,AST_This:Vt,AST_Throw:ge,AST_Token:AST_Token,AST_Toplevel:ie,AST_True:en,AST_Try:Fe,AST_Unary:je,AST_UnaryPostfix:Ze,AST_UnaryPrefix:$e,AST_Undefined:jt,AST_Var:Ne,AST_VarDef:Pe,AST_While:Q,AST_With:ne,AST_Yield:Ae,TreeTransformer:TreeTransformer,TreeWalker:TreeWalker,walk:walk,walk_abort:tn,walk_body:walk_body,walk_parent:walk_parent,_INLINE:rn,_NOINLINE:on,_PURE:nn});function def_transform(e,t){e.DEFMETHOD("transform",(function(e,n){let r=undefined;e.push(this);if(e.before)r=e.before(this,t,n);if(r===undefined){r=this;t(r,e);if(e.after){const t=e.after(r,n);if(t!==undefined)r=t}}e.pop();return r}))}function do_list(e,t){return i(e,(function(e){return e.transform(t,true)}))}def_transform(V,noop);def_transform(Y,(function(e,t){e.label=e.label.transform(t);e.body=e.body.transform(t)}));def_transform(G,(function(e,t){e.body=e.body.transform(t)}));def_transform(H,(function(e,t){e.body=do_list(e.body,t)}));def_transform(Z,(function(e,t){e.body=e.body.transform(t);e.condition=e.condition.transform(t)}));def_transform(Q,(function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t)}));def_transform(J,(function(e,t){if(e.init)e.init=e.init.transform(t);if(e.condition)e.condition=e.condition.transform(t);if(e.step)e.step=e.step.transform(t);e.body=e.body.transform(t)}));def_transform(ee,(function(e,t){e.init=e.init.transform(t);e.object=e.object.transform(t);e.body=e.body.transform(t)}));def_transform(ne,(function(e,t){e.expression=e.expression.transform(t);e.body=e.body.transform(t)}));def_transform(he,(function(e,t){if(e.value)e.value=e.value.transform(t)}));def_transform(ve,(function(e,t){if(e.label)e.label=e.label.transform(t)}));def_transform(ye,(function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t);if(e.alternative)e.alternative=e.alternative.transform(t)}));def_transform(Te,(function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)}));def_transform(Re,(function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)}));def_transform(Fe,(function(e,t){e.body=do_list(e.body,t);if(e.bcatch)e.bcatch=e.bcatch.transform(t);if(e.bfinally)e.bfinally=e.bfinally.transform(t)}));def_transform(Oe,(function(e,t){if(e.argname)e.argname=e.argname.transform(t);e.body=do_list(e.body,t)}));def_transform(xe,(function(e,t){e.definitions=do_list(e.definitions,t)}));def_transform(Pe,(function(e,t){e.name=e.name.transform(t);if(e.value)e.value=e.value.transform(t)}));def_transform(fe,(function(e,t){e.names=do_list(e.names,t)}));def_transform(ae,(function(e,t){if(e.name)e.name=e.name.transform(t);e.argnames=do_list(e.argnames,t);if(e.body instanceof V){e.body=e.body.transform(t)}else{e.body=do_list(e.body,t)}}));def_transform(ze,(function(e,t){e.expression=e.expression.transform(t);e.args=do_list(e.args,t)}));def_transform(Ge,(function(e,t){const n=do_list(e.expressions,t);e.expressions=n.length?n:[new Gt({value:0})]}));def_transform(Xe,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(qe,(function(e,t){e.expression=e.expression.transform(t);e.property=e.property.transform(t)}));def_transform(Ye,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(Ae,(function(e,t){if(e.expression)e.expression=e.expression.transform(t)}));def_transform(Se,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(je,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(Qe,(function(e,t){e.left=e.left.transform(t);e.right=e.right.transform(t)}));def_transform(Je,(function(e,t){e.condition=e.condition.transform(t);e.consequent=e.consequent.transform(t);e.alternative=e.alternative.transform(t)}));def_transform(nt,(function(e,t){e.elements=do_list(e.elements,t)}));def_transform(rt,(function(e,t){e.properties=do_list(e.properties,t)}));def_transform(it,(function(e,t){if(e.key instanceof V){e.key=e.key.transform(t)}if(e.value)e.value=e.value.transform(t)}));def_transform(_t,(function(e,t){if(e.name)e.name=e.name.transform(t);if(e.extends)e.extends=e.extends.transform(t);e.properties=do_list(e.properties,t)}));def_transform(oe,(function(e,t){e.expression=e.expression.transform(t)}));def_transform(Be,(function(e,t){e.foreign_name=e.foreign_name.transform(t);e.name=e.name.transform(t)}));def_transform(Le,(function(e,t){if(e.imported_name)e.imported_name=e.imported_name.transform(t);if(e.imported_names)do_list(e.imported_names,t);e.module_name=e.module_name.transform(t)}));def_transform(Ue,(function(e,t){if(e.exported_definition)e.exported_definition=e.exported_definition.transform(t);if(e.exported_value)e.exported_value=e.exported_value.transform(t);if(e.exported_names)do_list(e.exported_names,t);if(e.module_name)e.module_name=e.module_name.transform(t)}));def_transform(pe,(function(e,t){e.segments=do_list(e.segments,t)}));def_transform(_e,(function(e,t){e.prefix=e.prefix.transform(t);e.template_string=e.template_string.transform(t)}));(function(){var normalize_directives=function(e){var t=true;for(var n=0;n1||e.guardedHandlers&&e.guardedHandlers.length){throw new Error("Multiple catch clauses are not supported.")}return new Fe({start:my_start_token(e),end:my_end_token(e),body:from_moz(e.block).body,bcatch:from_moz(t[0]),bfinally:e.finalizer?new Me(from_moz(e.finalizer)):null})},Property:function(e){var t=e.key;var n={start:my_start_token(t||e.value),end:my_end_token(e.value),key:t.type=="Identifier"?t.name:t.value,value:from_moz(e.value)};if(e.computed){n.key=from_moz(e.key)}if(e.method){n.is_generator=e.value.generator;n.async=e.value.async;if(!e.computed){n.key=new kt({name:n.key})}else{n.key=from_moz(e.key)}return new ct(n)}if(e.kind=="init"){if(t.type!="Identifier"&&t.type!="Literal"){n.key=from_moz(t)}return new ot(n)}if(typeof n.key==="string"||typeof n.key==="number"){n.key=new kt({name:n.key})}n.value=new se(n.value);if(e.kind=="get")return new lt(n);if(e.kind=="set")return new ut(n);if(e.kind=="method"){n.async=e.value.async;n.is_generator=e.value.generator;n.quote=e.computed?'"':null;return new ct(n)}},MethodDefinition:function(e){var t={start:my_start_token(e),end:my_end_token(e),key:e.computed?from_moz(e.key):new kt({name:e.key.name||e.key.value}),value:from_moz(e.value),static:e.static};if(e.kind=="get"){return new lt(t)}if(e.kind=="set"){return new ut(t)}t.is_generator=e.value.generator;t.async=e.value.async;return new ct(t)},FieldDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in FieldDefinition");t=from_moz(e.key)}return new pt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},PropertyDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in PropertyDefinition");t=from_moz(e.key)}return new pt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},ArrayExpression:function(e){return new nt({start:my_start_token(e),end:my_end_token(e),elements:e.elements.map((function(e){return e===null?new $t:from_moz(e)}))})},ObjectExpression:function(e){return new rt({start:my_start_token(e),end:my_end_token(e),properties:e.properties.map((function(e){if(e.type==="SpreadElement"){return from_moz(e)}e.type="Property";return from_moz(e)}))})},SequenceExpression:function(e){return new Ge({start:my_start_token(e),end:my_end_token(e),expressions:e.expressions.map(from_moz)})},MemberExpression:function(e){return new(e.computed?qe:Xe)({start:my_start_token(e),end:my_end_token(e),property:e.computed?from_moz(e.property):e.property.name,expression:from_moz(e.object),optional:e.optional||false})},ChainExpression:function(e){return new Ye({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.expression)})},SwitchCase:function(e){return new(e.test?Re:Ce)({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.test),body:e.consequent.map(from_moz)})},VariableDeclaration:function(e){return new(e.kind==="const"?Ie:e.kind==="let"?we:Ne)({start:my_start_token(e),end:my_end_token(e),definitions:e.declarations.map(from_moz)})},ImportDeclaration:function(e){var t=null;var n=null;e.specifiers.forEach((function(e){if(e.type==="ImportSpecifier"){if(!n){n=[]}n.push(new Be({start:my_start_token(e),end:my_end_token(e),foreign_name:from_moz(e.imported),name:from_moz(e.local)}))}else if(e.type==="ImportDefaultSpecifier"){t=from_moz(e.local)}else if(e.type==="ImportNamespaceSpecifier"){if(!n){n=[]}n.push(new Be({start:my_start_token(e),end:my_end_token(e),foreign_name:new Nt({name:"*"}),name:from_moz(e.local)}))}}));return new Le({start:my_start_token(e),end:my_end_token(e),imported_name:t,imported_names:n,module_name:from_moz(e.source)})},ExportAllDeclaration:function(e){return new Ue({start:my_start_token(e),end:my_end_token(e),exported_names:[new Be({name:new Bt({name:"*"}),foreign_name:new Bt({name:"*"})})],module_name:from_moz(e.source)})},ExportNamedDeclaration:function(e){return new Ue({start:my_start_token(e),end:my_end_token(e),exported_definition:from_moz(e.declaration),exported_names:e.specifiers&&e.specifiers.length?e.specifiers.map((function(e){return new Be({foreign_name:from_moz(e.exported),name:from_moz(e.local)})})):null,module_name:from_moz(e.source)})},ExportDefaultDeclaration:function(e){return new Ue({start:my_start_token(e),end:my_end_token(e),exported_value:from_moz(e.declaration),is_default:true})},Literal:function(e){var t=e.value,n={start:my_start_token(e),end:my_end_token(e)};var r=e.regex;if(r&&r.pattern){n.value={source:r.pattern,flags:r.flags};return new Xt(n)}else if(r){const r=e.raw||t;const i=r.match(/^\/(.*)\/(\w*)$/);if(!i)throw new Error("Invalid regex source "+r);const[o,a,s]=i;n.value={source:a,flags:s};return new Xt(n)}if(t===null)return new qt(n);switch(typeof t){case"string":n.value=t;return new Kt(n);case"number":n.value=t;n.raw=e.raw||t.toString();return new Gt(n);case"boolean":return new(t?en:Jt)(n)}},MetaProperty:function(e){if(e.meta.name==="new"&&e.property.name==="target"){return new gt({start:my_start_token(e),end:my_end_token(e)})}else if(e.meta.name==="import"&&e.property.name==="meta"){return new Ve({start:my_start_token(e),end:my_end_token(e)})}},Identifier:function(e){var n=t[t.length-2];return new(n.type=="LabeledStatement"?wt:n.type=="VariableDeclarator"&&n.id===e?n.kind=="const"?St:n.kind=="let"?At:Dt:/Import.*Specifier/.test(n.type)?n.local===e?xt:Nt:n.type=="ExportSpecifier"?n.local===e?Pt:Bt:n.type=="FunctionExpression"?n.id===e?Rt:yt:n.type=="FunctionDeclaration"?n.id===e?Tt:yt:n.type=="ArrowFunctionExpression"?n.params.includes(e)?yt:It:n.type=="ClassExpression"?n.id===e?Ot:It:n.type=="Property"?n.key===e&&n.computed||n.value===e?It:kt:n.type=="PropertyDefinition"||n.type==="FieldDefinition"?n.key===e&&n.computed||n.value===e?It:Ct:n.type=="ClassDeclaration"?n.id===e?Ft:It:n.type=="MethodDefinition"?n.computed?It:kt:n.type=="CatchClause"?Mt:n.type=="BreakStatement"||n.type=="ContinueStatement"?Lt:It)({start:my_start_token(e),end:my_end_token(e),name:e.name})},BigIntLiteral(e){return new Ht({start:my_start_token(e),end:my_end_token(e),value:e.value})}};e.UpdateExpression=e.UnaryExpression=function To_Moz_Unary(e){var t="prefix"in e?e.prefix:e.type=="UnaryExpression"?true:false;return new(t?$e:Ze)({start:my_start_token(e),end:my_end_token(e),operator:e.operator,expression:from_moz(e.argument)})};e.ClassDeclaration=e.ClassExpression=function From_Moz_Class(e){return new(e.type==="ClassDeclaration"?mt:ht)({start:my_start_token(e),end:my_end_token(e),name:from_moz(e.id),extends:from_moz(e.superClass),properties:e.body.body.map(from_moz)})};map("EmptyStatement",W);map("BlockStatement",X,"body@body");map("IfStatement",ye,"test>condition, consequent>body, alternate>alternative");map("LabeledStatement",Y,"label>label, body>body");map("BreakStatement",De,"label>label");map("ContinueStatement",be,"label>label");map("WithStatement",ne,"object>expression, body>body");map("SwitchStatement",Te,"discriminant>expression, cases@body");map("ReturnStatement",Ee,"argument>value");map("ThrowStatement",ge,"argument>value");map("WhileStatement",Q,"test>condition, body>body");map("DoWhileStatement",Z,"test>condition, body>body");map("ForStatement",J,"init>init, test>condition, update>step, body>body");map("ForInStatement",ee,"left>init, right>object, body>body");map("ForOfStatement",te,"left>init, right>object, body>body, await=await");map("AwaitExpression",Se,"argument>expression");map("YieldExpression",Ae,"argument>expression, delegate=is_star");map("DebuggerStatement",z);map("VariableDeclarator",Pe,"id>name, init>value");map("CatchClause",Oe,"param>argname, body%body");map("ThisExpression",Vt);map("Super",Ut);map("BinaryExpression",Qe,"operator=operator, left>left, right>right");map("LogicalExpression",Qe,"operator=operator, left>left, right>right");map("AssignmentExpression",et,"operator=operator, left>left, right>right");map("ConditionalExpression",Je,"test>condition, consequent>consequent, alternate>alternative");map("NewExpression",Ke,"callee>expression, arguments@args");map("CallExpression",ze,"callee>expression, optional=optional, arguments@args");def_to_moz(ie,(function To_Moz_Program(e){return to_moz_scope("Program",e)}));def_to_moz(oe,(function To_Moz_Spread(e){return{type:to_moz_in_destructuring()?"RestElement":"SpreadElement",argument:to_moz(e.expression)}}));def_to_moz(_e,(function To_Moz_TaggedTemplateExpression(e){return{type:"TaggedTemplateExpression",tag:to_moz(e.prefix),quasi:to_moz(e.template_string)}}));def_to_moz(pe,(function To_Moz_TemplateLiteral(e){var t=[];var n=[];for(var r=0;r({type:"BigIntLiteral",value:e.value})));Qt.DEFMETHOD("to_mozilla_ast",zt.prototype.to_mozilla_ast);qt.DEFMETHOD("to_mozilla_ast",zt.prototype.to_mozilla_ast);$t.DEFMETHOD("to_mozilla_ast",(function To_Moz_ArrayHole(){return null}));H.DEFMETHOD("to_mozilla_ast",X.prototype.to_mozilla_ast);ae.DEFMETHOD("to_mozilla_ast",ue.prototype.to_mozilla_ast);function my_start_token(e){var t=e.loc,n=t&&t.start;var r=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,r?r[0]:e.start,false,[],[],t&&t.source)}function my_end_token(e){var t=e.loc,n=t&&t.end;var r=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,r?r[0]:e.end,false,[],[],t&&t.source)}function map(t,n,r){var i="function From_Moz_"+t+"(M){\n";i+="return new U2."+n.name+"({\n"+"start: my_start_token(M),\n"+"end: my_end_token(M)";var o="function To_Moz_"+t+"(M){\n";o+="return {\n"+"type: "+JSON.stringify(t);if(r)r.split(/\s*,\s*/).forEach((function(e){var t=/([a-z0-9$_]+)([=@>%])([a-z0-9$_]+)/i.exec(e);if(!t)throw new Error("Can't understand property map: "+e);var n=t[1],r=t[2],a=t[3];i+=",\n"+a+": ";o+=",\n"+n+": ";switch(r){case"@":i+="M."+n+".map(from_moz)";o+="M."+a+".map(to_moz)";break;case">":i+="from_moz(M."+n+")";o+="to_moz(M."+a+")";break;case"=":i+="M."+n;o+="M."+a;break;case"%":i+="from_moz(M."+n+").body";o+="to_moz_block(M)";break;default:throw new Error("Can't understand operator in propmap: "+e)}}));i+="\n})\n}";o+="\n}\n}";i=new Function("U2","my_start_token","my_end_token","from_moz","return("+i+")")(an,my_start_token,my_end_token,from_moz);o=new Function("to_moz","to_moz_block","to_moz_scope","return("+o+")")(to_moz,to_moz_block,to_moz_scope);e[t]=i;def_to_moz(n,o)}var t=null;function from_moz(n){t.push(n);var r=n!=null?e[n.type](n):null;t.pop();return r}V.from_mozilla_ast=function(e){var n=t;t=[];var r=from_moz(e);t=n;return r};function set_moz_loc(e,t){var n=e.start;var r=e.end;if(!(n&&r)){return t}if(n.pos!=null&&r.endpos!=null){t.range=[n.pos,r.endpos]}if(n.line){t.loc={start:{line:n.line,column:n.col},end:r.endline?{line:r.endline,column:r.endcol}:null};if(n.file){t.loc.source=n.file}}return t}function def_to_moz(e,t){e.DEFMETHOD("to_mozilla_ast",(function(e){return set_moz_loc(this,t(this,e))}))}var n=null;function to_moz(e){if(n===null){n=[]}n.push(e);var t=e!=null?e.to_mozilla_ast(n[n.length-2]):null;n.pop();if(n.length===0){n=null}return t}function to_moz_in_destructuring(){var e=n.length;while(e--){if(n[e]instanceof fe){return true}}return false}function to_moz_block(e){return{type:"BlockStatement",body:e.body.map(to_moz)}}function to_moz_scope(e,t){var n=t.body.map(to_moz);if(t.body[0]instanceof G&&t.body[0].body instanceof Kt){n.unshift(to_moz(new W(t.body[0])))}return{type:e,body:n}}})();function first_in_statement(e){let t=e.parent(-1);for(let n=0,r;r=e.parent(n);n++){if(r instanceof U&&r.body===t)return true;if(r instanceof Ge&&r.expressions[0]===t||r.TYPE==="Call"&&r.expression===t||r instanceof _e&&r.prefix===t||r instanceof Xe&&r.expression===t||r instanceof qe&&r.expression===t||r instanceof Je&&r.condition===t||r instanceof Qe&&r.left===t||r instanceof Ze&&r.expression===t){t=r}else{return false}}}function left_is_object(e){if(e instanceof rt)return true;if(e instanceof Ge)return left_is_object(e.expressions[0]);if(e.TYPE==="Call")return left_is_object(e.expression);if(e instanceof _e)return left_is_object(e.prefix);if(e instanceof Xe||e instanceof qe)return left_is_object(e.expression);if(e instanceof Je)return left_is_object(e.condition);if(e instanceof Qe)return left_is_object(e.left);if(e instanceof Ze)return left_is_object(e.expression);return false}const sn=/^$|[;{][\s\n]*$/;const un=10;const ln=32;const cn=/[@#]__(PURE|INLINE|NOINLINE)__/g;function is_some_comments(e){return(e.type==="comment2"||e.type==="comment1")&&/@preserve|@lic|@cc_on|^\**!/i.test(e.value)}function OutputStream(e){var t=!e;e=defaults(e,{ascii_only:false,beautify:false,braces:false,comments:"some",ecma:5,ie8:false,indent_level:4,indent_start:0,inline_script:true,keep_numbers:false,keep_quoted_props:false,max_line_len:false,preamble:null,preserve_annotations:false,quote_keys:false,quote_style:0,safari10:false,semicolons:true,shebang:true,shorthand:undefined,source_map:null,webkit:false,width:80,wrap_iife:false,wrap_func_args:true},true);if(e.shorthand===undefined)e.shorthand=e.ecma>5;var n=return_false;if(e.comments){let t=e.comments;if(typeof e.comments==="string"&&/^\/.*\/[a-zA-Z]*$/.test(e.comments)){var r=e.comments.lastIndexOf("/");t=new RegExp(e.comments.substr(1,r-1),e.comments.substr(r+1))}if(t instanceof RegExp){n=function(e){return e.type!="comment5"&&t.test(e.value)}}else if(typeof t==="function"){n=function(e){return e.type!="comment5"&&t(this,e)}}else if(t==="some"){n=is_some_comments}else{n=return_true}}var i=0;var o=0;var a=1;var s=0;var u="";let l=new Set;var c=e.ascii_only?function(t,n){if(e.ecma>=2015&&!e.safari10){t=t.replace(/[\ud800-\udbff][\udc00-\udfff]/g,(function(e){var t=get_full_char_code(e,0).toString(16);return"\\u{"+t+"}"}))}return t.replace(/[\u0000-\u001f\u007f-\uffff]/g,(function(e){var t=e.charCodeAt(0).toString(16);if(t.length<=2&&!n){while(t.length<2)t="0"+t;return"\\x"+t}else{while(t.length<4)t="0"+t;return"\\u"+t}}))}:function(e){return e.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g,(function(e,t){if(t){return"\\u"+t.charCodeAt(0).toString(16)}return e}))};function make_string(t,n){var r=0,i=0;t=t.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,(function(n,o){switch(n){case'"':++r;return'"';case"'":++i;return"'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\t":return"\\t";case"\b":return"\\b";case"\f":return"\\f";case"\v":return e.ie8?"\\x0B":"\\v";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";case"\ufeff":return"\\ufeff";case"\0":return/[0-9]/.test(get_full_char(t,o+1))?"\\x00":"\\0"}return n}));function quote_single(){return"'"+t.replace(/\x27/g,"\\'")+"'"}function quote_double(){return'"'+t.replace(/\x22/g,'\\"')+'"'}function quote_template(){return"`"+t.replace(/`/g,"\\`")+"`"}t=c(t);if(n==="`")return quote_template();switch(e.quote_style){case 1:return quote_single();case 2:return quote_double();case 3:return n=="'"?quote_single():quote_double();default:return r>i?quote_single():quote_double()}}function encode_string(t,n){var r=make_string(t,n);if(e.inline_script){r=r.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi,"<\\/$1$2");r=r.replace(/\x3c!--/g,"\\x3c!--");r=r.replace(/--\x3e/g,"--\\x3e")}return r}function make_name(e){e=e.toString();e=c(e,true);return e}function make_indent(t){return" ".repeat(e.indent_start+i-t*e.indent_level)}var f=false;var _=false;var p=false;var d=0;var m=false;var h=false;var E=-1;var g="";var v,D,b=e.source_map&&[];var S=b?function(){b.forEach((function(t){try{let n=!t.name&&t.token.type=="name"?t.token.value:t.name;if(n instanceof Et){n=n.name}e.source_map.add(t.token.file,t.line,t.col,t.token.line,t.token.col,is_basic_identifier_string(n)?n:undefined)}catch(e){}}));b=[]}:noop;var A=e.max_line_len?function(){if(o>e.max_line_len){if(d){var t=u.slice(0,d);var n=u.slice(d);if(b){var r=n.length-o;b.forEach((function(e){e.line++;e.col+=r}))}u=t+"\n"+n;a++;s++;o=n.length}}if(d){d=0;S()}}:noop;var y=makePredicate("( [ + * / - , . `");function print(t){t=String(t);var n=get_full_char(t,0);if(m&&n){m=false;if(n!=="\n"){print("\n");k()}}if(h&&n){h=false;if(!/[\s;})]/.test(n)){T()}}E=-1;var r=g.charAt(g.length-1);if(p){p=false;if(r===":"&&n==="}"||(!n||!";}".includes(n))&&r!==";"){if(e.semicolons||y.has(n)){u+=";";o++;s++}else{A();if(o>0){u+="\n";s++;a++;o=0}if(/^\s+$/.test(t)){p=true}}if(!e.beautify)_=false}}if(_){if(is_identifier_char(r)&&(is_identifier_char(n)||n=="\\")||n=="/"&&n==r||(n=="+"||n=="-")&&n==g){u+=" ";o++;s++}_=false}if(v){b.push({token:v,name:D,line:a,col:o});v=false;if(!d)S()}u+=t;f=t[t.length-1]=="(";s+=t.length;var i=t.split(/\r?\n/),l=i.length-1;a+=l;o+=i[0].length;if(l>0){A();o=i[l].length}g=t}var star=function(){print("*")};var T=e.beautify?function(){print(" ")}:function(){_=true};var k=e.beautify?function(t){if(e.beautify){print(make_indent(t?.5:0))}}:noop;var C=e.beautify?function(e,t){if(e===true)e=next_indent();var n=i;i=e;var r=t();i=n;return r}:function(e,t){return t()};var R=e.beautify?function(){if(E<0)return print("\n");if(u[E]!="\n"){u=u.slice(0,E)+"\n"+u.slice(E);s++;a++}E++}:e.max_line_len?function(){A();d=u.length}:noop;var F=e.beautify?function(){print(";")}:function(){p=true};function force_semicolon(){p=false;print(";")}function next_indent(){return i+e.indent_level}function with_block(e){var t;print("{");R();C(next_indent(),(function(){t=e()}));k();print("}");return t}function with_parens(e){print("(");var t=e();print(")");return t}function with_square(e){print("[");var t=e();print("]");return t}function comma(){print(",");T()}function colon(){print(":");T()}var O=b?function(e,t){v=e;D=t}:noop;function get(){if(d){A()}return u}function has_nlb(){let e=u.length-1;while(e>=0){const t=u.charCodeAt(e);if(t===un){return true}if(t!==ln){return false}e--}return true}function filter_comment(t){if(!e.preserve_annotations){t=t.replace(cn," ")}if(/^\s*$/.test(t)){return""}return t.replace(/(<\s*\/\s*)(script)/i,"<\\/$2")}function prepend_comments(t){var r=this;var i=t.start;if(!i)return;var o=r.printed_comments;const a=t instanceof he&&t.value;if(i.comments_before&&o.has(i.comments_before)){if(a){i.comments_before=[]}else{return}}var u=i.comments_before;if(!u){u=i.comments_before=[]}o.add(u);if(a){var l=new TreeWalker((function(e){var t=l.parent();if(t instanceof he||t instanceof Qe&&t.left===e||t.TYPE=="Call"&&t.expression===e||t instanceof Je&&t.condition===e||t instanceof Xe&&t.expression===e||t instanceof Ge&&t.expressions[0]===e||t instanceof qe&&t.expression===e||t instanceof Ze){if(!e.start)return;var n=e.start.comments_before;if(n&&!o.has(n)){o.add(n);u=u.concat(n)}}else{return true}}));l.push(t);t.value.walk(l)}if(s==0){if(u.length>0&&e.shebang&&u[0].type==="comment5"&&!o.has(u[0])){print("#!"+u.shift().value+"\n");k()}var c=e.preamble;if(c){print(c.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g,"\n"))}}u=u.filter(n,t).filter((e=>!o.has(e)));if(u.length==0)return;var f=has_nlb();u.forEach((function(e,t){o.add(e);if(!f){if(e.nlb){print("\n");k();f=true}else if(t>0){T()}}if(/comment[134]/.test(e.type)){var n=filter_comment(e.value);if(n){print("//"+n+"\n");k()}f=true}else if(e.type=="comment2"){var n=filter_comment(e.value);if(n){print("/*"+n+"*/")}f=false}}));if(!f){if(i.nlb){print("\n");k()}else{T()}}}function append_comments(e,t){var r=this;var i=e.end;if(!i)return;var o=r.printed_comments;var a=i[t?"comments_before":"comments_after"];if(!a||o.has(a))return;if(!(e instanceof U||a.every((e=>!/comment[134]/.test(e.type)))))return;o.add(a);var s=u.length;a.filter(n,e).forEach((function(e,n){if(o.has(e))return;o.add(e);h=false;if(m){print("\n");k();m=false}else if(e.nlb&&(n>0||!has_nlb())){print("\n");k()}else if(n>0||!t){T()}if(/comment[134]/.test(e.type)){const t=filter_comment(e.value);if(t){print("//"+t)}m=true}else if(e.type=="comment2"){const t=filter_comment(e.value);if(t){print("/*"+t+"*/")}h=true}}));if(u.length>s)E=s}var M=[];return{get:get,toString:get,indent:k,in_directive:false,use_asm:null,active_scope:null,indentation:function(){return i},current_width:function(){return o-i},should_break:function(){return e.width&&this.current_width()>=e.width},has_parens:function(){return f},newline:R,print:print,star:star,space:T,comma:comma,colon:colon,last:function(){return g},semicolon:F,force_semicolon:force_semicolon,to_utf8:c,print_name:function(e){print(make_name(e))},print_string:function(e,t,n){var r=encode_string(e,t);if(n===true&&!r.includes("\\")){if(!sn.test(u)){force_semicolon()}force_semicolon()}print(r)},print_template_string_chars:function(e){var t=encode_string(e,"`").replace(/\${/g,"\\${");return print(t.substr(1,t.length-2))},encode_string:encode_string,next_indent:next_indent,with_indent:C,with_block:with_block,with_parens:with_parens,with_square:with_square,add_mapping:O,option:function(t){return e[t]},printed_comments:l,prepend_comments:t?noop:prepend_comments,append_comments:t||n===return_false?noop:append_comments,line:function(){return a},col:function(){return o},pos:function(){return s},push_node:function(e){M.push(e)},pop_node:function(){return M.pop()},parent:function(e){return M[M.length-2-(e||0)]}}}(function(){function DEFPRINT(e,t){e.DEFMETHOD("_codegen",t)}V.DEFMETHOD("print",(function(e,t){var n=this,r=n._codegen;if(n instanceof re){e.active_scope=n}else if(!e.use_asm&&n instanceof K&&n.value=="use asm"){e.use_asm=e.active_scope}function doit(){e.prepend_comments(n);n.add_source_map(e);r(n,e);e.append_comments(n)}e.push_node(n);if(t||n.needs_parens(e)){e.with_parens(doit)}else{doit()}e.pop_node();if(n===e.use_asm){e.use_asm=null}}));V.DEFMETHOD("_print",V.prototype.print);V.DEFMETHOD("print_to_string",(function(e){var t=OutputStream(e);this.print(t);return t.get()}));function PARENS(e,t){if(Array.isArray(e)){e.forEach((function(e){PARENS(e,t)}))}else{e.DEFMETHOD("needs_parens",t)}}PARENS(V,return_false);PARENS(ue,(function(e){if(!e.has_parens()&&first_in_statement(e)){return true}if(e.option("webkit")){var t=e.parent();if(t instanceof He&&t.expression===this){return true}}if(e.option("wrap_iife")){var t=e.parent();if(t instanceof ze&&t.expression===this){return true}}if(e.option("wrap_func_args")){var t=e.parent();if(t instanceof ze&&t.args.includes(this)){return true}}return false}));PARENS(le,(function(e){var t=e.parent();if(e.option("wrap_func_args")&&t instanceof ze&&t.args.includes(this)){return true}return t instanceof He&&t.expression===this}));PARENS(rt,(function(e){return!e.has_parens()&&first_in_statement(e)}));PARENS(ht,first_in_statement);PARENS(je,(function(e){var t=e.parent();return t instanceof He&&t.expression===this||t instanceof ze&&t.expression===this||t instanceof Qe&&t.operator==="**"&&this instanceof $e&&t.left===this&&this.operator!=="++"&&this.operator!=="--"}));PARENS(Se,(function(e){var t=e.parent();return t instanceof He&&t.expression===this||t instanceof ze&&t.expression===this||t instanceof Qe&&t.operator==="**"&&t.left===this||e.option("safari10")&&t instanceof $e}));PARENS(Ge,(function(e){var t=e.parent();return t instanceof ze||t instanceof je||t instanceof Qe||t instanceof Pe||t instanceof He||t instanceof nt||t instanceof it||t instanceof Je||t instanceof le||t instanceof tt||t instanceof oe||t instanceof te&&this===t.object||t instanceof Ae||t instanceof Ue}));PARENS(Qe,(function(e){var t=e.parent();if(t instanceof ze&&t.expression===this)return true;if(t instanceof je)return true;if(t instanceof He&&t.expression===this)return true;if(t instanceof Qe){const e=t.operator;const n=this.operator;if(n==="??"&&(e==="||"||e==="&&")){return true}if(e==="??"&&(n==="||"||n==="&&")){return true}const r=w[e];const i=w[n];if(r>i||r==i&&(this===t.right||e=="**")){return true}}}));PARENS(Ae,(function(e){var t=e.parent();if(t instanceof Qe&&t.operator!=="=")return true;if(t instanceof ze&&t.expression===this)return true;if(t instanceof Je&&t.condition===this)return true;if(t instanceof je)return true;if(t instanceof He&&t.expression===this)return true}));PARENS(He,(function(e){var t=e.parent();if(t instanceof Ke&&t.expression===this){return walk(this,(e=>{if(e instanceof re)return true;if(e instanceof ze){return tn}}))}}));PARENS(ze,(function(e){var t=e.parent(),n;if(t instanceof Ke&&t.expression===this||t instanceof Ue&&t.is_default&&this.expression instanceof ue)return true;return this.expression instanceof ue&&t instanceof He&&t.expression===this&&(n=e.parent(1))instanceof et&&n.left===t}));PARENS(Ke,(function(e){var t=e.parent();if(this.args.length===0&&(t instanceof He||t instanceof ze&&t.expression===this))return true}));PARENS(Gt,(function(e){var t=e.parent();if(t instanceof He&&t.expression===this){var n=this.getValue();if(n<0||/^0/.test(make_num(n))){return true}}}));PARENS(Ht,(function(e){var t=e.parent();if(t instanceof He&&t.expression===this){var n=this.getValue();if(n.startsWith("-")){return true}}}));PARENS([et,Je],(function(e){var t=e.parent();if(t instanceof je)return true;if(t instanceof Qe&&!(t instanceof et))return true;if(t instanceof ze&&t.expression===this)return true;if(t instanceof Je&&t.condition===this)return true;if(t instanceof He&&t.expression===this)return true;if(this instanceof et&&this.left instanceof fe&&this.left.is_array===false)return true}));DEFPRINT(K,(function(e,t){t.print_string(e.value,e.quote);t.semicolon()}));DEFPRINT(oe,(function(e,t){t.print("...");e.expression.print(t)}));DEFPRINT(fe,(function(e,t){t.print(e.is_array?"[":"{");var n=e.names.length;e.names.forEach((function(e,r){if(r>0)t.comma();e.print(t);if(r==n-1&&e instanceof $t)t.comma()}));t.print(e.is_array?"]":"}")}));DEFPRINT(z,(function(e,t){t.print("debugger");t.semicolon()}));function display_body(e,t,n,r){var i=e.length-1;n.in_directive=r;e.forEach((function(e,r){if(n.in_directive===true&&!(e instanceof K||e instanceof W||e instanceof G&&e.body instanceof Kt)){n.in_directive=false}if(!(e instanceof W)){n.indent();e.print(n);if(!(r==i&&t)){n.newline();if(t)n.newline()}}if(n.in_directive===true&&e instanceof G&&e.body instanceof Kt){n.in_directive=false}}));n.in_directive=false}q.DEFMETHOD("_do_print_body",(function(e){force_statement(this.body,e)}));DEFPRINT(U,(function(e,t){e.body.print(t);t.semicolon()}));DEFPRINT(ie,(function(e,t){display_body(e.body,true,t,true);t.print("")}));DEFPRINT(Y,(function(e,t){e.label.print(t);t.colon();e.body.print(t)}));DEFPRINT(G,(function(e,t){e.body.print(t);t.semicolon()}));function print_braced_empty(e,t){t.print("{");t.with_indent(t.next_indent(),(function(){t.append_comments(e,true)}));t.print("}")}function print_braced(e,t,n){if(e.body.length>0){t.with_block((function(){display_body(e.body,false,t,n)}))}else print_braced_empty(e,t)}DEFPRINT(X,(function(e,t){print_braced(e,t)}));DEFPRINT(W,(function(e,t){t.semicolon()}));DEFPRINT(Z,(function(e,t){t.print("do");t.space();make_block(e.body,t);t.space();t.print("while");t.space();t.with_parens((function(){e.condition.print(t)}));t.semicolon()}));DEFPRINT(Q,(function(e,t){t.print("while");t.space();t.with_parens((function(){e.condition.print(t)}));t.space();e._do_print_body(t)}));DEFPRINT(J,(function(e,t){t.print("for");t.space();t.with_parens((function(){if(e.init){if(e.init instanceof xe){e.init.print(t)}else{parenthesize_for_noin(e.init,t,true)}t.print(";");t.space()}else{t.print(";")}if(e.condition){e.condition.print(t);t.print(";");t.space()}else{t.print(";")}if(e.step){e.step.print(t)}}));t.space();e._do_print_body(t)}));DEFPRINT(ee,(function(e,t){t.print("for");if(e.await){t.space();t.print("await")}t.space();t.with_parens((function(){e.init.print(t);t.space();t.print(e instanceof te?"of":"in");t.space();e.object.print(t)}));t.space();e._do_print_body(t)}));DEFPRINT(ne,(function(e,t){t.print("with");t.space();t.with_parens((function(){e.expression.print(t)}));t.space();e._do_print_body(t)}));ae.DEFMETHOD("_do_print",(function(e,t){var n=this;if(!t){if(n.async){e.print("async");e.space()}e.print("function");if(n.is_generator){e.star()}if(n.name){e.space()}}if(n.name instanceof Et){n.name.print(e)}else if(t&&n.name instanceof V){e.with_square((function(){n.name.print(e)}))}e.with_parens((function(){n.argnames.forEach((function(t,n){if(n)e.comma();t.print(e)}))}));e.space();print_braced(n,e,true)}));DEFPRINT(ae,(function(e,t){e._do_print(t)}));DEFPRINT(_e,(function(e,t){var n=e.prefix;var r=n instanceof ae||n instanceof Qe||n instanceof Je||n instanceof Ge||n instanceof je||n instanceof Xe&&n.expression instanceof rt;if(r)t.print("(");e.prefix.print(t);if(r)t.print(")");e.template_string.print(t)}));DEFPRINT(pe,(function(e,t){var n=t.parent()instanceof _e;t.print("`");for(var r=0;r");e.space();const i=t.body[0];if(t.body.length===1&&i instanceof Ee){const t=i.value;if(!t){e.print("{}")}else if(left_is_object(t)){e.print("(");t.print(e);e.print(")")}else{t.print(e)}}else{print_braced(t,e)}if(r){e.print(")")}}));he.DEFMETHOD("_do_print",(function(e,t){e.print(t);if(this.value){e.space();const t=this.value.start.comments_before;if(t&&t.length&&!e.printed_comments.has(t)){e.print("(");this.value.print(e);e.print(")")}else{this.value.print(e)}}e.semicolon()}));DEFPRINT(Ee,(function(e,t){e._do_print(t,"return")}));DEFPRINT(ge,(function(e,t){e._do_print(t,"throw")}));DEFPRINT(Ae,(function(e,t){var n=e.is_star?"*":"";t.print("yield"+n);if(e.expression){t.space();e.expression.print(t)}}));DEFPRINT(Se,(function(e,t){t.print("await");t.space();var n=e.expression;var r=!(n instanceof ze||n instanceof It||n instanceof He||n instanceof je||n instanceof zt||n instanceof Se||n instanceof rt);if(r)t.print("(");e.expression.print(t);if(r)t.print(")")}));ve.DEFMETHOD("_do_print",(function(e,t){e.print(t);if(this.label){e.space();this.label.print(e)}e.semicolon()}));DEFPRINT(De,(function(e,t){e._do_print(t,"break")}));DEFPRINT(be,(function(e,t){e._do_print(t,"continue")}));function make_then(e,t){var n=e.body;if(t.option("braces")||t.option("ie8")&&n instanceof Z)return make_block(n,t);if(!n)return t.force_semicolon();while(true){if(n instanceof ye){if(!n.alternative){make_block(e.body,t);return}n=n.alternative}else if(n instanceof q){n=n.body}else break}force_statement(e.body,t)}DEFPRINT(ye,(function(e,t){t.print("if");t.space();t.with_parens((function(){e.condition.print(t)}));t.space();if(e.alternative){make_then(e,t);t.space();t.print("else");t.space();if(e.alternative instanceof ye)e.alternative.print(t);else force_statement(e.alternative,t)}else{e._do_print_body(t)}}));DEFPRINT(Te,(function(e,t){t.print("switch");t.space();t.with_parens((function(){e.expression.print(t)}));t.space();var n=e.body.length-1;if(n<0)print_braced_empty(e,t);else t.with_block((function(){e.body.forEach((function(e,r){t.indent(true);e.print(t);if(r0)t.newline()}))}))}));ke.DEFMETHOD("_do_print_body",(function(e){e.newline();this.body.forEach((function(t){e.indent();t.print(e);e.newline()}))}));DEFPRINT(Ce,(function(e,t){t.print("default:");e._do_print_body(t)}));DEFPRINT(Re,(function(e,t){t.print("case");t.space();e.expression.print(t);t.print(":");e._do_print_body(t)}));DEFPRINT(Fe,(function(e,t){t.print("try");t.space();print_braced(e,t);if(e.bcatch){t.space();e.bcatch.print(t)}if(e.bfinally){t.space();e.bfinally.print(t)}}));DEFPRINT(Oe,(function(e,t){t.print("catch");if(e.argname){t.space();t.with_parens((function(){e.argname.print(t)}))}t.space();print_braced(e,t)}));DEFPRINT(Me,(function(e,t){t.print("finally");t.space();print_braced(e,t)}));xe.DEFMETHOD("_do_print",(function(e,t){e.print(t);e.space();this.definitions.forEach((function(t,n){if(n)e.comma();t.print(e)}));var n=e.parent();var r=n instanceof J||n instanceof ee;var i=!r||n&&n.init!==this;if(i)e.semicolon()}));DEFPRINT(we,(function(e,t){e._do_print(t,"let")}));DEFPRINT(Ne,(function(e,t){e._do_print(t,"var")}));DEFPRINT(Ie,(function(e,t){e._do_print(t,"const")}));DEFPRINT(Le,(function(e,t){t.print("import");t.space();if(e.imported_name){e.imported_name.print(t)}if(e.imported_name&&e.imported_names){t.print(",");t.space()}if(e.imported_names){if(e.imported_names.length===1&&e.imported_names[0].foreign_name.name==="*"){e.imported_names[0].print(t)}else{t.print("{");e.imported_names.forEach((function(n,r){t.space();n.print(t);if(r{if(e instanceof re)return true;if(e instanceof Qe&&e.operator=="in"){return tn}}))}e.print(t,r)}DEFPRINT(Pe,(function(e,t){e.name.print(t);if(e.value){t.space();t.print("=");t.space();var n=t.parent(1);var r=n instanceof J||n instanceof ee;parenthesize_for_noin(e.value,t,r)}}));DEFPRINT(ze,(function(e,t){e.expression.print(t);if(e instanceof Ke&&e.args.length===0)return;if(e.expression instanceof ze||e.expression instanceof ae){t.add_mapping(e.start)}if(e.optional)t.print("?.");t.with_parens((function(){e.args.forEach((function(e,n){if(n)t.comma();e.print(t)}))}))}));DEFPRINT(Ke,(function(e,t){t.print("new");t.space();ze.prototype._codegen(e,t)}));Ge.DEFMETHOD("_do_print",(function(e){this.expressions.forEach((function(t,n){if(n>0){e.comma();if(e.should_break()){e.newline();e.indent()}}t.print(e)}))}));DEFPRINT(Ge,(function(e,t){e._do_print(t)}));DEFPRINT(Xe,(function(e,t){var n=e.expression;n.print(t);var r=e.property;var i=f.has(r)?t.option("ie8"):!is_identifier_string(r,t.option("ecma")>=2015||t.option("safari10"));if(e.optional)t.print("?.");if(i){t.print("[");t.add_mapping(e.end);t.print_string(r);t.print("]")}else{if(n instanceof Gt&&n.getValue()>=0){if(!/[xa-f.)]/i.test(t.last())){t.print(".")}}if(!e.optional)t.print(".");t.add_mapping(e.end);t.print_name(r)}}));DEFPRINT(We,(function(e,t){var n=e.expression;n.print(t);var r=e.property;if(e.optional)t.print("?");t.print(".#");t.print_name(r)}));DEFPRINT(qe,(function(e,t){e.expression.print(t);if(e.optional)t.print("?.");t.print("[");e.property.print(t);t.print("]")}));DEFPRINT(Ye,(function(e,t){e.expression.print(t)}));DEFPRINT($e,(function(e,t){var n=e.operator;t.print(n);if(/^[a-z]/i.test(n)||/[+-]$/.test(n)&&e.expression instanceof $e&&/^[+-]/.test(e.expression.operator)){t.space()}e.expression.print(t)}));DEFPRINT(Ze,(function(e,t){e.expression.print(t);t.print(e.operator)}));DEFPRINT(Qe,(function(e,t){var n=e.operator;e.left.print(t);if(n[0]==">"&&e.left instanceof Ze&&e.left.operator=="--"){t.print(" ")}else{t.space()}t.print(n);if((n=="<"||n=="<<")&&e.right instanceof $e&&e.right.operator=="!"&&e.right.expression instanceof $e&&e.right.expression.operator=="--"){t.print(" ")}else{t.space()}e.right.print(t)}));DEFPRINT(Je,(function(e,t){e.condition.print(t);t.space();t.print("?");t.space();e.consequent.print(t);t.space();t.colon();e.alternative.print(t)}));DEFPRINT(nt,(function(e,t){t.with_square((function(){var n=e.elements,r=n.length;if(r>0)t.space();n.forEach((function(e,n){if(n)t.comma();e.print(t);if(n===r-1&&e instanceof $t)t.comma()}));if(r>0)t.space()}))}));DEFPRINT(rt,(function(e,t){if(e.properties.length>0)t.with_block((function(){e.properties.forEach((function(e,n){if(n){t.print(",");t.newline()}t.indent();e.print(t)}));t.newline()}));else print_braced_empty(e,t)}));DEFPRINT(_t,(function(e,t){t.print("class");t.space();if(e.name){e.name.print(t);t.space()}if(e.extends){var n=!(e.extends instanceof It)&&!(e.extends instanceof He)&&!(e.extends instanceof ht)&&!(e.extends instanceof ue);t.print("extends");if(n){t.print("(")}else{t.space()}e.extends.print(t);if(n){t.print(")")}else{t.space()}}if(e.properties.length>0)t.with_block((function(){e.properties.forEach((function(e,n){if(n){t.newline()}t.indent();e.print(t)}));t.newline()}));else t.print("{}")}));DEFPRINT(gt,(function(e,t){t.print("new.target")}));function print_property_name(e,t,n){if(n.option("quote_keys")){return n.print_string(e)}if(""+ +e==e&&e>=0){if(n.option("keep_numbers")){return n.print(e)}return n.print(make_num(e))}var r=f.has(e)?n.option("ie8"):n.option("ecma")<2015||n.option("safari10")?!is_basic_identifier_string(e):!is_identifier_string(e,true);if(r||t&&n.option("keep_quoted_props")){return n.print_string(e,t)}return n.print_name(e)}DEFPRINT(ot,(function(e,t){function get_name(e){var t=e.definition();return t?t.mangled_name||t.name:e.name}var n=t.option("shorthand");if(n&&e.value instanceof Et&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value)===e.key&&!f.has(e.key)){print_property_name(e.key,e.quote,t)}else if(n&&e.value instanceof tt&&e.value.left instanceof Et&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value.left)===e.key){print_property_name(e.key,e.quote,t);t.space();t.print("=");t.space();e.value.right.print(t)}else{if(!(e.key instanceof V)){print_property_name(e.key,e.quote,t)}else{t.with_square((function(){e.key.print(t)}))}t.colon();e.value.print(t)}}));DEFPRINT(dt,((e,t)=>{if(e.static){t.print("static");t.space()}t.print("#");print_property_name(e.key.name,e.quote,t);if(e.value){t.print("=");e.value.print(t)}t.semicolon()}));DEFPRINT(pt,((e,t)=>{if(e.static){t.print("static");t.space()}if(e.key instanceof Ct){print_property_name(e.key.name,e.quote,t)}else{t.print("[");e.key.print(t);t.print("]")}if(e.value){t.print("=");e.value.print(t)}t.semicolon()}));it.DEFMETHOD("_print_getter_setter",(function(e,t,n){var r=this;if(r.static){n.print("static");n.space()}if(e){n.print(e);n.space()}if(r.key instanceof kt){if(t)n.print("#");print_property_name(r.key.name,r.quote,n)}else{n.with_square((function(){r.key.print(n)}))}r.value._do_print(n,true)}));DEFPRINT(ut,(function(e,t){e._print_getter_setter("set",false,t)}));DEFPRINT(lt,(function(e,t){e._print_getter_setter("get",false,t)}));DEFPRINT(at,(function(e,t){e._print_getter_setter("set",true,t)}));DEFPRINT(st,(function(e,t){e._print_getter_setter("get",true,t)}));DEFPRINT(ft,(function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,true,t)}));DEFPRINT(ct,(function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,false,t)}));Et.DEFMETHOD("_do_print",(function(e){var t=this.definition();e.print_name(t?t.mangled_name||t.name:this.name)}));DEFPRINT(Et,(function(e,t){e._do_print(t)}));DEFPRINT($t,noop);DEFPRINT(Vt,(function(e,t){t.print("this")}));DEFPRINT(Ut,(function(e,t){t.print("super")}));DEFPRINT(zt,(function(e,t){t.print(e.getValue())}));DEFPRINT(Kt,(function(e,t){t.print_string(e.getValue(),e.quote,t.in_directive)}));DEFPRINT(Gt,(function(e,t){if((t.option("keep_numbers")||t.use_asm)&&e.raw){t.print(e.raw)}else{t.print(make_num(e.getValue()))}}));DEFPRINT(Ht,(function(e,t){t.print(e.getValue()+"n")}));const e=/(<\s*\/\s*script)/i;const slash_script_replace=(e,t)=>t.replace("/","\\/");DEFPRINT(Xt,(function(t,n){let{source:r,flags:i}=t.getValue();r=regexp_source_fix(r);i=i?sort_regexp_flags(i):"";r=r.replace(e,slash_script_replace);n.print(n.to_utf8(`/${r}/${i}`));const o=n.parent();if(o instanceof Qe&&/^\w/.test(o.operator)&&o.left===t){n.print(" ")}}));function force_statement(e,t){if(t.option("braces")){make_block(e,t)}else{if(!e||e instanceof W)t.force_semicolon();else e.print(t)}}function best_of(e){var t=e[0],n=t.length;for(var r=1;re===null&&t===null||e.TYPE===t.TYPE&&e.shallow_cmp(t);const equivalent_to=(e,t)=>{if(!shallow_cmp(e,t))return false;const n=[e];const r=[t];const i=n.push.bind(n);const o=r.push.bind(r);while(n.length&&r.length){const e=n.pop();const t=r.pop();if(!shallow_cmp(e,t))return false;e._children_backwards(i);t._children_backwards(o);if(n.length!==r.length){return false}}return n.length==0&&r.length==0};const mkshallow=e=>{const t=Object.keys(e).map((t=>{if(e[t]==="eq"){return`this.${t} === other.${t}`}else if(e[t]==="exist"){return`(this.${t} == null ? other.${t} == null : this.${t} === other.${t})`}else{throw new Error(`mkshallow: Unexpected instruction: ${e[t]}`)}})).join(" && ");return new Function("other","return "+t)};const pass_through=()=>true;V.prototype.shallow_cmp=function(){throw new Error("did not find a shallow_cmp function for "+this.constructor.name)};z.prototype.shallow_cmp=pass_through;K.prototype.shallow_cmp=mkshallow({value:"eq"});G.prototype.shallow_cmp=pass_through;H.prototype.shallow_cmp=pass_through;W.prototype.shallow_cmp=pass_through;Y.prototype.shallow_cmp=mkshallow({"label.name":"eq"});Z.prototype.shallow_cmp=pass_through;Q.prototype.shallow_cmp=pass_through;J.prototype.shallow_cmp=mkshallow({init:"exist",condition:"exist",step:"exist"});ee.prototype.shallow_cmp=pass_through;te.prototype.shallow_cmp=pass_through;ne.prototype.shallow_cmp=pass_through;ie.prototype.shallow_cmp=pass_through;oe.prototype.shallow_cmp=pass_through;ae.prototype.shallow_cmp=mkshallow({is_generator:"eq",async:"eq"});fe.prototype.shallow_cmp=mkshallow({is_array:"eq"});_e.prototype.shallow_cmp=pass_through;pe.prototype.shallow_cmp=pass_through;de.prototype.shallow_cmp=mkshallow({value:"eq"});me.prototype.shallow_cmp=pass_through;ve.prototype.shallow_cmp=pass_through;Se.prototype.shallow_cmp=pass_through;Ae.prototype.shallow_cmp=mkshallow({is_star:"eq"});ye.prototype.shallow_cmp=mkshallow({alternative:"exist"});Te.prototype.shallow_cmp=pass_through;ke.prototype.shallow_cmp=pass_through;Fe.prototype.shallow_cmp=mkshallow({bcatch:"exist",bfinally:"exist"});Oe.prototype.shallow_cmp=mkshallow({argname:"exist"});Me.prototype.shallow_cmp=pass_through;xe.prototype.shallow_cmp=pass_through;Pe.prototype.shallow_cmp=mkshallow({value:"exist"});Be.prototype.shallow_cmp=pass_through;Le.prototype.shallow_cmp=mkshallow({imported_name:"exist",imported_names:"exist"});Ve.prototype.shallow_cmp=pass_through;Ue.prototype.shallow_cmp=mkshallow({exported_definition:"exist",exported_value:"exist",exported_names:"exist",module_name:"eq",is_default:"eq"});ze.prototype.shallow_cmp=pass_through;Ge.prototype.shallow_cmp=pass_through;He.prototype.shallow_cmp=pass_through;Ye.prototype.shallow_cmp=pass_through;Xe.prototype.shallow_cmp=mkshallow({property:"eq"});We.prototype.shallow_cmp=mkshallow({property:"eq"});je.prototype.shallow_cmp=mkshallow({operator:"eq"});Qe.prototype.shallow_cmp=mkshallow({operator:"eq"});Je.prototype.shallow_cmp=pass_through;nt.prototype.shallow_cmp=pass_through;rt.prototype.shallow_cmp=pass_through;it.prototype.shallow_cmp=pass_through;ot.prototype.shallow_cmp=mkshallow({key:"eq"});ut.prototype.shallow_cmp=mkshallow({static:"eq"});lt.prototype.shallow_cmp=mkshallow({static:"eq"});ct.prototype.shallow_cmp=mkshallow({static:"eq",is_generator:"eq",async:"eq"});_t.prototype.shallow_cmp=mkshallow({name:"exist",extends:"exist"});pt.prototype.shallow_cmp=mkshallow({static:"eq"});Et.prototype.shallow_cmp=mkshallow({name:"eq"});gt.prototype.shallow_cmp=pass_through;Vt.prototype.shallow_cmp=pass_through;Ut.prototype.shallow_cmp=pass_through;Kt.prototype.shallow_cmp=mkshallow({value:"eq"});Gt.prototype.shallow_cmp=mkshallow({value:"eq"});Ht.prototype.shallow_cmp=mkshallow({value:"eq"});Xt.prototype.shallow_cmp=function(e){return this.value.flags===e.value.flags&&this.value.source===e.value.source};Wt.prototype.shallow_cmp=pass_through;const _n=1<<0;const pn=1<<1;let dn=null;let mn=null;class SymbolDef{constructor(e,t,n){this.name=t.name;this.orig=[t];this.init=n;this.eliminated=0;this.assignments=0;this.scope=e;this.replaced=0;this.global=false;this.export=0;this.mangled_name=null;this.undeclared=false;this.id=SymbolDef.next_id++;this.chained=false;this.direct_access=false;this.escaped=0;this.recursive_refs=0;this.references=[];this.should_replace=undefined;this.single_use=false;this.fixed=false;Object.seal(this)}fixed_value(){if(!this.fixed||this.fixed instanceof V)return this.fixed;return this.fixed()}unmangleable(e){if(!e)e={};if(dn&&dn.has(this.id)&&keep_name(e.keep_fnames,this.orig[0].name))return true;return this.global&&!e.toplevel||this.export&_n||this.undeclared||!e.eval&&this.scope.pinned()||(this.orig[0]instanceof Rt||this.orig[0]instanceof Tt)&&keep_name(e.keep_fnames,this.orig[0].name)||this.orig[0]instanceof kt||(this.orig[0]instanceof Ot||this.orig[0]instanceof Ft)&&keep_name(e.keep_classnames,this.orig[0].name)}mangle(e){const t=e.cache&&e.cache.props;if(this.global&&t&&t.has(this.name)){this.mangled_name=t.get(this.name)}else if(!this.mangled_name&&!this.unmangleable(e)){var n=this.scope;var r=this.orig[0];if(e.ie8&&r instanceof Rt)n=n.parent_scope;const i=redefined_catch_def(this);this.mangled_name=i?i.mangled_name||i.name:n.next_mangled(e,this);if(this.global&&t){t.set(this.name,this.mangled_name)}}}}SymbolDef.next_id=1;function redefined_catch_def(e){if(e.orig[0]instanceof Mt&&e.scope.is_block_scope()){return e.scope.get_defun_scope().variables.get(e.name)}}re.DEFMETHOD("figure_out_scope",(function(e,{parent_scope:t=null,toplevel:n=this}={}){e=defaults(e,{cache:null,ie8:false,safari10:false});if(!(n instanceof ie)){throw new Error("Invalid toplevel scope")}var r=this.parent_scope=t;var i=new Map;var o=null;var a=null;var s=[];var u=new TreeWalker(((t,n)=>{if(t.is_block_scope()){const i=r;t.block_scope=r=new re(t);r._block_scope=true;const o=t instanceof Oe?i.parent_scope:i;r.init_scope_vars(o);r.uses_with=i.uses_with;r.uses_eval=i.uses_eval;if(e.safari10){if(t instanceof J||t instanceof ee){s.push(r)}}if(t instanceof Te){const e=r;r=i;t.expression.walk(u);r=e;for(let e=0;e{if(e===t)return true;if(t instanceof bt){return e instanceof Rt}return!(e instanceof At||e instanceof St)}))){js_error(`"${t.name}" is redeclared`,t.start.file,t.start.line,t.start.col,t.start.pos)}if(!(t instanceof yt))mark_export(d,2);if(o!==r){t.mark_enclosed();var d=r.find_variable(t);if(t.thedef!==d){t.thedef=d;t.reference()}}}else if(t instanceof Lt){var m=i.get(t.name);if(!m)throw new Error(string_template("Undefined label {name} [{line},{col}]",{name:t.name,line:t.start.line,col:t.start.col}));t.thedef=m}if(!(r instanceof ie)&&(t instanceof Ue||t instanceof Le)){js_error(`"${t.TYPE}" statement may only appear at the top level`,t.start.file,t.start.line,t.start.col,t.start.pos)}}));this.walk(u);function mark_export(e,t){if(a){var n=0;do{t++}while(u.parent(n++)!==a)}var r=u.parent(t);if(e.export=r instanceof Ue?_n:0){var i=r.exported_definition;if((i instanceof ce||i instanceof mt)&&r.is_default){e.export=pn}}}const l=this instanceof ie;if(l){this.globals=new Map}var u=new TreeWalker((e=>{if(e instanceof ve&&e.label){e.label.thedef.references.push(e);return true}if(e instanceof It){var t=e.name;if(t=="eval"&&u.parent()instanceof ze){for(var r=e.scope;r&&!r.uses_eval;r=r.parent_scope){r.uses_eval=true}}var i;if(u.parent()instanceof Be&&u.parent(1).module_name||!(i=e.scope.find_variable(t))){i=n.def_global(e);if(e instanceof Pt)i.export=_n}else if(i.scope instanceof ae&&t=="arguments"){i.scope.uses_arguments=true}e.thedef=i;e.reference();if(e.scope.is_block_scope()&&!(i.orig[0]instanceof bt)){e.scope=e.scope.get_defun_scope()}return true}var o;if(e instanceof Mt&&(o=redefined_catch_def(e.definition()))){var r=e.scope;while(r){push_uniq(r.enclosed,o);if(r===o.scope)break;r=r.parent_scope}}}));this.walk(u);if(e.ie8||e.safari10){walk(this,(e=>{if(e instanceof Mt){var t=e.name;var r=e.thedef.references;var i=e.scope.get_defun_scope();var o=i.find_variable(t)||n.globals.get(t)||i.def_variable(e);r.forEach((function(e){e.thedef=o;e.reference()}));e.thedef=o;e.reference();return true}}))}if(e.safari10){for(const e of s){e.parent_scope.variables.forEach((function(t){push_uniq(e.enclosed,t)}))}}}));ie.DEFMETHOD("def_global",(function(e){var t=this.globals,n=e.name;if(t.has(n)){return t.get(n)}else{var r=new SymbolDef(this,e);r.undeclared=true;r.global=true;t.set(n,r);return r}}));re.DEFMETHOD("init_scope_vars",(function(e){this.variables=new Map;this.uses_with=false;this.uses_eval=false;this.parent_scope=e;this.enclosed=[];this.cname=-1}));re.DEFMETHOD("conflicting_def",(function(e){return this.enclosed.find((t=>t.name===e))||this.variables.has(e)||this.parent_scope&&this.parent_scope.conflicting_def(e)}));re.DEFMETHOD("conflicting_def_shallow",(function(e){return this.enclosed.find((t=>t.name===e))||this.variables.has(e)}));re.DEFMETHOD("add_child_scope",(function(e){if(e.parent_scope===this)return;e.parent_scope=this;const t=(()=>{const e=[];let t=this;do{e.push(t)}while(t=t.parent_scope);e.reverse();return e})();const n=new Set(e.enclosed);const r=[];for(const e of t){r.forEach((t=>push_uniq(e.enclosed,t)));for(const t of e.variables.values()){if(n.has(t)){push_uniq(r,t);push_uniq(e.enclosed,t)}}}}));function find_scopes_visible_from(e){const t=new Set;for(const n of new Set(e)){(function bubble_up(e){if(e==null||t.has(e))return;t.add(e);bubble_up(e.parent_scope)})(n)}return[...t]}re.DEFMETHOD("create_symbol",(function(e,{source:t,tentative_name:n,scope:r,conflict_scopes:i=[r],init:o=null}={}){let a;i=find_scopes_visible_from(i);if(n){n=a=n.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/gi,"_");let e=0;while(i.find((e=>e.conflicting_def_shallow(a)))){a=n+"$"+e++}}if(!a){throw new Error("No symbol name could be generated in create_symbol()")}const s=make_node(e,t,{name:a,scope:r});this.def_variable(s,o||null);s.mark_enclosed();return s}));V.DEFMETHOD("is_block_scope",return_false);_t.DEFMETHOD("is_block_scope",return_false);ae.DEFMETHOD("is_block_scope",return_false);ie.DEFMETHOD("is_block_scope",return_false);ke.DEFMETHOD("is_block_scope",return_false);H.DEFMETHOD("is_block_scope",return_true);re.DEFMETHOD("is_block_scope",(function(){return this._block_scope||false}));j.DEFMETHOD("is_block_scope",return_true);ae.DEFMETHOD("init_scope_vars",(function(){re.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false;this.def_variable(new yt({name:"arguments",start:this.start,end:this.end}))}));le.DEFMETHOD("init_scope_vars",(function(){re.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false}));Et.DEFMETHOD("mark_enclosed",(function(){var e=this.definition();var t=this.scope;while(t){push_uniq(t.enclosed,e);if(t===e.scope)break;t=t.parent_scope}}));Et.DEFMETHOD("reference",(function(){this.definition().references.push(this);this.mark_enclosed()}));re.DEFMETHOD("find_variable",(function(e){if(e instanceof Et)e=e.name;return this.variables.get(e)||this.parent_scope&&this.parent_scope.find_variable(e)}));re.DEFMETHOD("def_function",(function(e,t){var n=this.def_variable(e,t);if(!n.init||n.init instanceof ce)n.init=t;return n}));re.DEFMETHOD("def_variable",(function(e,t){var n=this.variables.get(e.name);if(n){n.orig.push(e);if(n.init&&(n.scope!==e.scope||n.init instanceof ue)){n.init=t}}else{n=new SymbolDef(this,e,t);this.variables.set(e.name,n);n.global=!this.parent_scope}return e.thedef=n}));function next_mangled(e,t){var n=e.enclosed;e:while(true){var r=hn(++e.cname);if(f.has(r))continue;if(t.reserved.has(r))continue;if(mn&&mn.has(r))continue e;for(let e=n.length;--e>=0;){const i=n[e];const o=i.mangled_name||i.unmangleable(t)&&i.name;if(r==o)continue e}return r}}re.DEFMETHOD("next_mangled",(function(e){return next_mangled(this,e)}));ie.DEFMETHOD("next_mangled",(function(e){let t;const n=this.mangled_names;do{t=next_mangled(this,e)}while(n.has(t));return t}));ue.DEFMETHOD("next_mangled",(function(e,t){var n=t.orig[0]instanceof yt&&this.name&&this.name.definition();var r=n?n.mangled_name||n.name:null;while(true){var i=next_mangled(this,e);if(!r||r!=i)return i}}));Et.DEFMETHOD("unmangleable",(function(e){var t=this.definition();return!t||t.unmangleable(e)}));wt.DEFMETHOD("unmangleable",return_false);Et.DEFMETHOD("unreferenced",(function(){return!this.definition().references.length&&!this.scope.pinned()}));Et.DEFMETHOD("definition",(function(){return this.thedef}));Et.DEFMETHOD("global",(function(){return this.thedef.global}));ie.DEFMETHOD("_default_mangler_options",(function(e){e=defaults(e,{eval:false,ie8:false,keep_classnames:false,keep_fnames:false,module:false,reserved:[],toplevel:false});if(e.module)e.toplevel=true;if(!Array.isArray(e.reserved)&&!(e.reserved instanceof Set)){e.reserved=[]}e.reserved=new Set(e.reserved);e.reserved.add("arguments");return e}));ie.DEFMETHOD("mangle_names",(function(e){e=this._default_mangler_options(e);var t=-1;var n=[];if(e.keep_fnames){dn=new Set}const r=this.mangled_names=new Set;if(e.cache){this.globals.forEach(collect);if(e.cache.props){e.cache.props.forEach((function(e){r.add(e)}))}}var i=new TreeWalker((function(r,i){if(r instanceof Y){var o=t;i();t=o;return true}if(r instanceof re){r.variables.forEach(collect);return}if(r.is_block_scope()){r.block_scope.variables.forEach(collect);return}if(dn&&r instanceof Pe&&r.value instanceof ae&&!r.value.name&&keep_name(e.keep_fnames,r.name.name)){dn.add(r.name.definition().id);return}if(r instanceof wt){let e;do{e=hn(++t)}while(f.has(e));r.mangled_name=e;return true}if(!(e.ie8||e.safari10)&&r instanceof Mt){n.push(r.definition());return}}));this.walk(i);if(e.keep_fnames||e.keep_classnames){mn=new Set;n.forEach((t=>{if(t.name.length<6&&t.unmangleable(e)){mn.add(t.name)}}))}n.forEach((t=>{t.mangle(e)}));dn=null;mn=null;function collect(t){const r=!e.reserved.has(t.name)&&!(t.export&_n);if(r){n.push(t)}}}));ie.DEFMETHOD("find_colliding_names",(function(e){const t=e.cache&&e.cache.props;const n=new Set;e.reserved.forEach(to_avoid);this.globals.forEach(add_def);this.walk(new TreeWalker((function(e){if(e instanceof re)e.variables.forEach(add_def);if(e instanceof Mt)add_def(e.definition())})));return n;function to_avoid(e){n.add(e)}function add_def(n){var r=n.name;if(n.global&&t&&t.has(r))r=t.get(r);else if(!n.unmangleable(e))return;to_avoid(r)}}));ie.DEFMETHOD("expand_names",(function(e){hn.reset();hn.sort();e=this._default_mangler_options(e);var t=this.find_colliding_names(e);var n=0;this.globals.forEach(rename);this.walk(new TreeWalker((function(e){if(e instanceof re)e.variables.forEach(rename);if(e instanceof Mt)rename(e.definition())})));function next_name(){var e;do{e=hn(n++)}while(t.has(e)||f.has(e));return e}function rename(t){if(t.global&&e.cache)return;if(t.unmangleable(e))return;if(e.reserved.has(t.name))return;const n=redefined_catch_def(t);const r=t.name=n?n.name:next_name();t.orig.forEach((function(e){e.name=r}));t.references.forEach((function(e){e.name=r}))}}));V.DEFMETHOD("tail_node",return_this);Ge.DEFMETHOD("tail_node",(function(){return this.expressions[this.expressions.length-1]}));ie.DEFMETHOD("compute_char_frequency",(function(e){e=this._default_mangler_options(e);try{V.prototype.print=function(t,n){this._print(t,n);if(this instanceof Et&&!this.unmangleable(e)){hn.consider(this.name,-1)}else if(e.properties){if(this instanceof We){hn.consider("#"+this.property,-1)}else if(this instanceof Xe){hn.consider(this.property,-1)}else if(this instanceof qe){skip_string(this.property)}}};hn.consider(this.print_to_string(),1)}finally{V.prototype.print=V.prototype._print}hn.sort();function skip_string(e){if(e instanceof Kt){hn.consider(e.value,-1)}else if(e instanceof Je){skip_string(e.consequent);skip_string(e.alternative)}else if(e instanceof Ge){skip_string(e.tail_node())}}}));const hn=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");const t="0123456789".split("");let n;let r;function reset(){r=new Map;e.forEach((function(e){r.set(e,0)}));t.forEach((function(e){r.set(e,0)}))}base54.consider=function(e,t){for(var n=e.length;--n>=0;){r.set(e[n],r.get(e[n])+t)}};function compare(e,t){return r.get(t)-r.get(e)}base54.sort=function(){n=mergeSort(e,compare).concat(mergeSort(t,compare))};base54.reset=reset;reset();function base54(e){var t="",r=54;e++;do{e--;t+=n[e%r];e=Math.floor(e/r);r=64}while(e>0);return t}return base54})();let En=undefined;V.prototype.size=function(e,t){En=e&&e.mangle_options;let n=0;walk_parent(this,((e,t)=>{n+=e._size(t);if(e instanceof le&&e.is_braceless()){n+=e.body[0].value._size(t);return true}}),t||e&&e.stack);En=undefined;return n};V.prototype._size=()=>0;z.prototype._size=()=>8;K.prototype._size=function(){return 2+this.value.length};const list_overhead=e=>e.length&&e.length-1;H.prototype._size=function(){return 2+list_overhead(this.body)};ie.prototype._size=function(){return list_overhead(this.body)};W.prototype._size=()=>1;Y.prototype._size=()=>2;Z.prototype._size=()=>9;Q.prototype._size=()=>7;J.prototype._size=()=>8;ee.prototype._size=()=>8;ne.prototype._size=()=>6;oe.prototype._size=()=>3;const lambda_modifiers=e=>(e.is_generator?1:0)+(e.async?6:0);se.prototype._size=function(){return lambda_modifiers(this)+4+list_overhead(this.argnames)+list_overhead(this.body)};ue.prototype._size=function(e){const t=!!first_in_statement(e);return t*2+lambda_modifiers(this)+12+list_overhead(this.argnames)+list_overhead(this.body)};ce.prototype._size=function(){return lambda_modifiers(this)+13+list_overhead(this.argnames)+list_overhead(this.body)};le.prototype._size=function(){let e=2+list_overhead(this.argnames);if(!(this.argnames.length===1&&this.argnames[0]instanceof Et)){e+=2}const t=this.is_braceless()?0:list_overhead(this.body)+2;return lambda_modifiers(this)+e+t};fe.prototype._size=()=>2;pe.prototype._size=function(){return 2+Math.floor(this.segments.length/2)*3};de.prototype._size=function(){return this.value.length};Ee.prototype._size=function(){return this.value?7:6};ge.prototype._size=()=>6;De.prototype._size=function(){return this.label?6:5};be.prototype._size=function(){return this.label?9:8};ye.prototype._size=()=>4;Te.prototype._size=function(){return 8+list_overhead(this.body)};Re.prototype._size=function(){return 5+list_overhead(this.body)};Ce.prototype._size=function(){return 8+list_overhead(this.body)};Fe.prototype._size=function(){return 3+list_overhead(this.body)};Oe.prototype._size=function(){let e=7+list_overhead(this.body);if(this.argname){e+=2}return e};Me.prototype._size=function(){return 7+list_overhead(this.body)};const def_size=(e,t)=>e+list_overhead(t.definitions);Ne.prototype._size=function(){return def_size(4,this)};we.prototype._size=function(){return def_size(4,this)};Ie.prototype._size=function(){return def_size(6,this)};Pe.prototype._size=function(){return this.value?1:0};Be.prototype._size=function(){return this.name?4:0};Le.prototype._size=function(){let e=6;if(this.imported_name)e+=1;if(this.imported_name||this.imported_names)e+=5;if(this.imported_names){e+=2+list_overhead(this.imported_names)}return e};Ve.prototype._size=()=>11;Ue.prototype._size=function(){let e=7+(this.is_default?8:0);if(this.exported_value){e+=this.exported_value._size()}if(this.exported_names){e+=2+list_overhead(this.exported_names)}if(this.module_name){e+=5}return e};ze.prototype._size=function(){if(this.optional){return 4+list_overhead(this.args)}return 2+list_overhead(this.args)};Ke.prototype._size=function(){return 6+list_overhead(this.args)};Ge.prototype._size=function(){return list_overhead(this.expressions)};Xe.prototype._size=function(){if(this.optional){return this.property.length+2}return this.property.length+1};We.prototype._size=function(){if(this.optional){return this.property.length+3}return this.property.length+2};qe.prototype._size=function(){return this.optional?4:2};je.prototype._size=function(){if(this.operator==="typeof")return 7;if(this.operator==="void")return 5;return this.operator.length};Qe.prototype._size=function(e){if(this.operator==="in")return 4;let t=this.operator.length;if((this.operator==="+"||this.operator==="-")&&this.right instanceof je&&this.right.operator===this.operator){t+=1}if(this.needs_parens(e)){t+=2}return t};Je.prototype._size=()=>3;nt.prototype._size=function(){return 2+list_overhead(this.elements)};rt.prototype._size=function(e){let t=2;if(first_in_statement(e)){t+=2}return t+list_overhead(this.properties)};const key_size=e=>typeof e==="string"?e.length:0;ot.prototype._size=function(){return key_size(this.key)+1};const static_size=e=>e?7:0;lt.prototype._size=function(){return 5+static_size(this.static)+key_size(this.key)};ut.prototype._size=function(){return 5+static_size(this.static)+key_size(this.key)};ct.prototype._size=function(){return static_size(this.static)+key_size(this.key)+lambda_modifiers(this)};ft.prototype._size=function(){return ct.prototype._size.call(this)+1};st.prototype._size=at.prototype._size=function(){return ct.prototype._size.call(this)+4};_t.prototype._size=function(){return(this.name?8:7)+(this.extends?8:0)};pt.prototype._size=function(){return static_size(this.static)+(typeof this.key==="string"?this.key.length+2:0)+(this.value?1:0)};dt.prototype._size=function(){return pt.prototype._size.call(this)+1};Et.prototype._size=function(){return!En||this.definition().unmangleable(En)?this.name.length:1};Ct.prototype._size=function(){return this.name.length};It.prototype._size=vt.prototype._size=function(){const{name:e,thedef:t}=this;if(t&&t.global)return e.length;if(e==="arguments")return 9;return Et.prototype._size.call(this)};gt.prototype._size=()=>10;Nt.prototype._size=function(){return this.name.length};Bt.prototype._size=function(){return this.name.length};Vt.prototype._size=()=>4;Ut.prototype._size=()=>5;Kt.prototype._size=function(){return this.value.length+2};Gt.prototype._size=function(){const{value:e}=this;if(e===0)return 1;if(e>0&&Math.floor(e)===e){return Math.floor(Math.log10(e)+1)}return e.toString().length};Ht.prototype._size=function(){return this.value.length};Xt.prototype._size=function(){return this.value.toString().length};qt.prototype._size=()=>4;Yt.prototype._size=()=>3;jt.prototype._size=()=>6;$t.prototype._size=()=>0;Zt.prototype._size=()=>8;en.prototype._size=()=>4;Jt.prototype._size=()=>5;Se.prototype._size=()=>6;Ae.prototype._size=()=>6;const gn=1;const vn=2;const Dn=4;const bn=8;const Sn=16;const An=32;const yn=256;const Tn=512;const kn=1024;const Cn=yn|Tn|kn;const has_flag=(e,t)=>e.flags&t;const set_flag=(e,t)=>{e.flags|=t};const clear_flag=(e,t)=>{e.flags&=~t};class Compressor extends TreeWalker{constructor(e,{false_by_default:t=false,mangle_options:n=false}){super();if(e.defaults!==undefined&&!e.defaults)t=true;this.options=defaults(e,{arguments:false,arrows:!t,booleans:!t,booleans_as_integers:false,collapse_vars:!t,comparisons:!t,computed_props:!t,conditionals:!t,dead_code:!t,defaults:true,directives:!t,drop_console:false,drop_debugger:!t,ecma:5,evaluate:!t,expression:false,global_defs:false,hoist_funs:false,hoist_props:!t,hoist_vars:false,ie8:false,if_return:!t,inline:!t,join_vars:!t,keep_classnames:false,keep_fargs:true,keep_fnames:false,keep_infinity:false,loops:!t,module:false,negate_iife:!t,passes:1,properties:!t,pure_getters:!t&&"strict",pure_funcs:null,reduce_funcs:!t,reduce_vars:!t,sequences:!t,side_effects:!t,switches:!t,top_retain:null,toplevel:!!(e&&e["top_retain"]),typeofs:!t,unsafe:false,unsafe_arrows:false,unsafe_comps:false,unsafe_Function:false,unsafe_math:false,unsafe_symbols:false,unsafe_methods:false,unsafe_proto:false,unsafe_regexp:false,unsafe_undefined:false,unused:!t,warnings:false},true);var r=this.options["global_defs"];if(typeof r=="object")for(var i in r){if(i[0]==="@"&&HOP(r,i)){r[i.slice(1)]=parse(r[i],{expression:true})}}if(this.options["inline"]===true)this.options["inline"]=3;var o=this.options["pure_funcs"];if(typeof o=="function"){this.pure_funcs=o}else{this.pure_funcs=o?function(e){return!o.includes(e.expression.print_to_string())}:return_true}var a=this.options["top_retain"];if(a instanceof RegExp){this.top_retain=function(e){return a.test(e.name)}}else if(typeof a=="function"){this.top_retain=a}else if(a){if(typeof a=="string"){a=a.split(/,/)}this.top_retain=function(e){return a.includes(e.name)}}if(this.options["module"]){this.directives["use strict"]=true;this.options["toplevel"]=true}var s=this.options["toplevel"];this.toplevel=typeof s=="string"?{funcs:/funcs/.test(s),vars:/vars/.test(s)}:{funcs:s,vars:s};var u=this.options["sequences"];this.sequences_limit=u==1?800:u|0;this.evaluated_regexps=new Map;this._toplevel=undefined;this.mangle_options=n}option(e){return this.options[e]}exposed(e){if(e.export)return true;if(e.global)for(var t=0,n=e.orig.length;t0||this.option("reduce_vars")){this._toplevel.reset_opt_flags(this)}this._toplevel=this._toplevel.transform(this);if(t>1){let e=0;walk(this._toplevel,(()=>{e++}));if(e=0){i.body[a]=i.body[a].transform(r)}}else if(i instanceof ye){i.body=i.body.transform(r);if(i.alternative){i.alternative=i.alternative.transform(r)}}else if(i instanceof ne){i.body=i.body.transform(r)}return i}));n.transform(r)}));function read_property(e,t){t=get_value(t);if(t instanceof V)return;var n;if(e instanceof nt){var r=e.elements;if(t=="length")return make_node_from_constant(r.length,e);if(typeof t=="number"&&t in r)n=r[t]}else if(e instanceof rt){t=""+t;var i=e.properties;for(var o=i.length;--o>=0;){var a=i[o];if(!(a instanceof ot))return;if(!n&&i[o].key===t)n=i[o].value}}return n instanceof It&&n.fixed_value()||n}function is_modified(e,t,n,r,i,o){var a=t.parent(i);var s=is_lhs(n,a);if(s)return s;if(!o&&a instanceof ze&&a.expression===n&&!(r instanceof le)&&!(r instanceof _t)&&!a.is_callee_pure(e)&&(!(r instanceof ue)||!(a instanceof Ke)&&r.contains_this())){return true}if(a instanceof nt){return is_modified(e,t,a,a,i+1)}if(a instanceof ot&&n===a.value){var u=t.parent(i+1);return is_modified(e,t,u,u,i+2)}if(a instanceof He&&a.expression===n){var l=read_property(r,a.property);return!o&&is_modified(e,t,a,l,i+1)}}(function(e){e(V,noop);function reset_def(e,t){t.assignments=0;t.chained=false;t.direct_access=false;t.escaped=0;t.recursive_refs=0;t.references=[];t.single_use=undefined;if(t.scope.pinned()){t.fixed=false}else if(t.orig[0]instanceof St||!e.exposed(t)){t.fixed=t.init}else{t.fixed=false}}function reset_variables(e,t,n){n.variables.forEach((function(n){reset_def(t,n);if(n.fixed===null){e.defs_to_safe_ids.set(n.id,e.safe_ids);mark(e,n,true)}else if(n.fixed){e.loop_ids.set(n.id,e.in_loop);mark(e,n,true)}}))}function reset_block_variables(e,t){if(t.block_scope)t.block_scope.variables.forEach((t=>{reset_def(e,t)}))}function push(e){e.safe_ids=Object.create(e.safe_ids)}function pop(e){e.safe_ids=Object.getPrototypeOf(e.safe_ids)}function mark(e,t,n){e.safe_ids[t.id]=n}function safe_to_read(e,t){if(t.single_use=="m")return false;if(e.safe_ids[t.id]){if(t.fixed==null){var n=t.orig[0];if(n instanceof yt||n.name=="arguments")return false;t.fixed=make_node(jt,n)}return true}return t.fixed instanceof ce}function safe_to_assign(e,t,n,r){if(t.fixed===undefined)return true;let i;if(t.fixed===null&&(i=e.defs_to_safe_ids.get(t.id))){i[t.id]=false;e.defs_to_safe_ids.delete(t.id);return true}if(!HOP(e.safe_ids,t.id))return false;if(!safe_to_read(e,t))return false;if(t.fixed===false)return false;if(t.fixed!=null&&(!r||t.references.length>t.assignments))return false;if(t.fixed instanceof ce){return r instanceof V&&t.fixed.parent_scope===n}return t.orig.every((e=>!(e instanceof St||e instanceof Tt||e instanceof Rt)))}function ref_once(e,t,n){return t.option("unused")&&!n.scope.pinned()&&n.references.length-n.recursive_refs==1&&e.loop_ids.get(n.id)===e.in_loop}function is_immutable(e){if(!e)return false;return e.is_constant()||e instanceof ae||e instanceof Vt}function mark_escaped(e,t,n,r,i,o=0,a=1){var s=e.parent(o);if(i){if(i.is_constant())return;if(i instanceof ht)return}if(s instanceof et&&(s.operator==="="||s.logical)&&r===s.right||s instanceof ze&&(r!==s.expression||s instanceof Ke)||s instanceof he&&r===s.value&&r.scope!==t.scope||s instanceof Pe&&r===s.value||s instanceof Ae&&r===s.value&&r.scope!==t.scope){if(a>1&&!(i&&i.is_constant_expression(n)))a=1;if(!t.escaped||t.escaped>a)t.escaped=a;return}else if(s instanceof nt||s instanceof Se||s instanceof Qe&&On.has(s.operator)||s instanceof Je&&r!==s.condition||s instanceof oe||s instanceof Ge&&r===s.tail_node()){mark_escaped(e,t,n,s,s,o+1,a)}else if(s instanceof ot&&r===s.value){var u=e.parent(o+1);mark_escaped(e,t,n,u,u,o+2,a)}else if(s instanceof He&&r===s.expression){i=read_property(i,s.property);mark_escaped(e,t,n,s,i,o+1,a+1);if(i)return}if(o>0)return;if(s instanceof Ge&&r!==s.tail_node())return;if(s instanceof G)return;t.direct_access=true}const suppress=e=>walk(e,(e=>{if(!(e instanceof Et))return;var t=e.definition();if(!t)return;if(e instanceof It)t.references.push(e);t.fixed=false}));e(se,(function(e,t,n){push(e);reset_variables(e,n,this);t();pop(e);return true}));e(et,(function(e,t,n){var r=this;if(r.left instanceof fe){suppress(r.left);return}const finish_walk=()=>{if(r.logical){r.left.walk(e);push(e);r.right.walk(e);pop(e);return true}};var i=r.left;if(!(i instanceof It))return finish_walk();var o=i.definition();var a=safe_to_assign(e,o,i.scope,r.right);o.assignments++;if(!a)return finish_walk();var s=o.fixed;if(!s&&r.operator!="="&&!r.logical)return finish_walk();var u=r.operator=="=";var l=u?r.right:r;if(is_modified(n,e,r,l,0))return finish_walk();o.references.push(i);if(!r.logical){if(!u)o.chained=true;o.fixed=u?function(){return r.right}:function(){return make_node(Qe,r,{operator:r.operator.slice(0,-1),left:s instanceof V?s:s(),right:r.right})}}if(r.logical){mark(e,o,false);push(e);r.right.walk(e);pop(e);return true}mark(e,o,false);r.right.walk(e);mark(e,o,true);mark_escaped(e,o,i.scope,r,l,0,1);return true}));e(Qe,(function(e){if(!On.has(this.operator))return;this.left.walk(e);push(e);this.right.walk(e);pop(e);return true}));e(H,(function(e,t,n){reset_block_variables(n,this)}));e(Re,(function(e){push(e);this.expression.walk(e);pop(e);push(e);walk_body(this,e);pop(e);return true}));e(_t,(function(e,t){clear_flag(this,Sn);push(e);t();pop(e);return true}));e(Je,(function(e){this.condition.walk(e);push(e);this.consequent.walk(e);pop(e);push(e);this.alternative.walk(e);pop(e);return true}));e(Ye,(function(e,t){const n=e.safe_ids;t();e.safe_ids=n;return true}));e(ze,(function(e){this.expression.walk(e);if(this.optional){push(e)}for(const t of this.args)t.walk(e);return true}));e(He,(function(e){if(!this.optional)return;this.expression.walk(e);push(e);if(this.property instanceof V)this.property.walk(e);return true}));e(Ce,(function(e,t){push(e);t();pop(e);return true}));function mark_lambda(e,t,n){clear_flag(this,Sn);push(e);reset_variables(e,n,this);if(this.uses_arguments){t();pop(e);return}var r;if(!this.name&&(r=e.parent())instanceof ze&&r.expression===this&&!r.args.some((e=>e instanceof oe))&&this.argnames.every((e=>e instanceof Et))){this.argnames.forEach(((t,n)=>{if(!t.definition)return;var i=t.definition();if(i.orig.length>1)return;if(i.fixed===undefined&&(!this.uses_arguments||e.has_directive("use strict"))){i.fixed=function(){return r.args[n]||make_node(jt,r)};e.loop_ids.set(i.id,e.in_loop);mark(e,i,true)}else{i.fixed=false}}))}t();pop(e);return true}e(ae,mark_lambda);e(Z,(function(e,t,n){reset_block_variables(n,this);const r=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);if(has_break_or_continue(this)){pop(e);push(e)}this.condition.walk(e);pop(e);e.in_loop=r;return true}));e(J,(function(e,t,n){reset_block_variables(n,this);if(this.init)this.init.walk(e);const r=e.in_loop;e.in_loop=this;push(e);if(this.condition)this.condition.walk(e);this.body.walk(e);if(this.step){if(has_break_or_continue(this)){pop(e);push(e)}this.step.walk(e)}pop(e);e.in_loop=r;return true}));e(ee,(function(e,t,n){reset_block_variables(n,this);suppress(this.init);this.object.walk(e);const r=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);pop(e);e.in_loop=r;return true}));e(ye,(function(e){this.condition.walk(e);push(e);this.body.walk(e);pop(e);if(this.alternative){push(e);this.alternative.walk(e);pop(e)}return true}));e(Y,(function(e){push(e);this.body.walk(e);pop(e);return true}));e(Mt,(function(){this.definition().fixed=false}));e(It,(function(e,t,n){var r=this.definition();r.references.push(this);if(r.references.length==1&&!r.fixed&&r.orig[0]instanceof Tt){e.loop_ids.set(r.id,e.in_loop)}var i;if(r.fixed===undefined||!safe_to_read(e,r)){r.fixed=false}else if(r.fixed){i=this.fixed_value();if(i instanceof ae&&recursive_ref(e,r)){r.recursive_refs++}else if(i&&!n.exposed(r)&&ref_once(e,n,r)){r.single_use=i instanceof ae&&!i.pinned()||i instanceof _t||r.scope===this.scope&&i.is_constant_expression()}else{r.single_use=false}if(is_modified(n,e,this,i,0,is_immutable(i))){if(r.single_use){r.single_use="m"}else{r.fixed=false}}}mark_escaped(e,r,this.scope,this,i,0,1)}));e(ie,(function(e,t,n){this.globals.forEach((function(e){reset_def(n,e)}));reset_variables(e,n,this)}));e(Fe,(function(e,t,n){reset_block_variables(n,this);push(e);walk_body(this,e);pop(e);if(this.bcatch){push(e);this.bcatch.walk(e);pop(e)}if(this.bfinally)this.bfinally.walk(e);return true}));e(je,(function(e){var t=this;if(t.operator!=="++"&&t.operator!=="--")return;var n=t.expression;if(!(n instanceof It))return;var r=n.definition();var i=safe_to_assign(e,r,n.scope,true);r.assignments++;if(!i)return;var o=r.fixed;if(!o)return;r.references.push(n);r.chained=true;r.fixed=function(){return make_node(Qe,t,{operator:t.operator.slice(0,-1),left:make_node($e,t,{operator:"+",expression:o instanceof V?o:o()}),right:make_node(Gt,t,{value:1})})};mark(e,r,true);return true}));e(Pe,(function(e,t){var n=this;if(n.name instanceof fe){suppress(n.name);return}var r=n.name.definition();if(n.value){if(safe_to_assign(e,r,n.name.scope,n.value)){r.fixed=function(){return n.value};e.loop_ids.set(r.id,e.in_loop);mark(e,r,false);t();mark(e,r,true);return true}else{r.fixed=false}}}));e(Q,(function(e,t,n){reset_block_variables(n,this);const r=e.in_loop;e.in_loop=this;push(e);t();pop(e);e.in_loop=r;return true}))})((function(e,t){e.DEFMETHOD("reduce_vars",t)}));ie.DEFMETHOD("reset_opt_flags",(function(e){const t=this;const n=e.option("reduce_vars");const r=new TreeWalker((function(i,o){clear_flag(i,Cn);if(n){if(e.top_retain&&i instanceof ce&&r.parent()===t){set_flag(i,kn)}return i.reduce_vars(r,o,e)}}));r.safe_ids=Object.create(null);r.in_loop=null;r.loop_ids=new Map;r.defs_to_safe_ids=new Map;t.walk(r)}));Et.DEFMETHOD("fixed_value",(function(){var e=this.thedef.fixed;if(!e||e instanceof V)return e;return e()}));It.DEFMETHOD("is_immutable",(function(){var e=this.definition().orig;return e.length==1&&e[0]instanceof Rt}));function is_func_expr(e){return e instanceof le||e instanceof ue}function is_lhs_read_only(e){if(e instanceof Vt)return true;if(e instanceof It)return e.definition().orig[0]instanceof Rt;if(e instanceof He){e=e.expression;if(e instanceof It){if(e.is_immutable())return false;e=e.fixed_value()}if(!e)return true;if(e instanceof Xt)return false;if(e instanceof zt)return true;return is_lhs_read_only(e)}return false}function is_ref_of(e,t){if(!(e instanceof It))return false;var n=e.definition().orig;for(var r=n.length;--r>=0;){if(n[r]instanceof t)return true}}function find_scope(e){for(let t=0;;t++){const n=e.parent(t);if(n instanceof ie)return n;if(n instanceof ae)return n;if(n.block_scope)return n.block_scope}}function find_variable(e,t){var n,r=0;while(n=e.parent(r++)){if(n instanceof re)break;if(n instanceof Oe&&n.argname){n=n.argname.definition().scope;break}}return n.find_variable(t)}function make_sequence(e,t){if(t.length==1)return t[0];if(t.length==0)throw new Error("trying to create a sequence with length zero!");return make_node(Ge,e,{expressions:t.reduce(merge_sequence,[])})}function make_node_from_constant(e,t){switch(typeof e){case"string":return make_node(Kt,t,{value:e});case"number":if(isNaN(e))return make_node(Yt,t);if(isFinite(e)){return 1/e<0?make_node($e,t,{operator:"-",expression:make_node(Gt,t,{value:-e})}):make_node(Gt,t,{value:e})}return e<0?make_node($e,t,{operator:"-",expression:make_node(Zt,t)}):make_node(Zt,t);case"boolean":return make_node(e?en:Jt,t);case"undefined":return make_node(jt,t);default:if(e===null){return make_node(qt,t,{value:null})}if(e instanceof RegExp){return make_node(Xt,t,{value:{source:regexp_source_fix(e.source),flags:e.flags}})}throw new Error(string_template("Can't handle constant of type: {type}",{type:typeof e}))}}function maintain_this_binding(e,t,n){if(e instanceof $e&&e.operator=="delete"||e instanceof ze&&e.expression===t&&(n instanceof He||n instanceof It&&n.name=="eval")){return make_sequence(t,[make_node(Gt,t,{value:0}),n])}return n}function merge_sequence(e,t){if(t instanceof Ge){e.push(...t.expressions)}else{e.push(t)}return e}function as_statement_array(e){if(e===null)return[];if(e instanceof X)return e.body;if(e instanceof W)return[];if(e instanceof U)return[e];throw new Error("Can't convert thing to statement array")}function is_empty(e){if(e===null)return true;if(e instanceof W)return true;if(e instanceof X)return e.body.length==0;return false}function can_be_evicted_from_block(e){return!(e instanceof mt||e instanceof ce||e instanceof we||e instanceof Ie||e instanceof Ue||e instanceof Le)}function loop_body(e){if(e instanceof j){return e.body instanceof X?e.body:e}return e}function is_iife_call(e){if(e.TYPE!="Call")return false;return e.expression instanceof ue||is_iife_call(e.expression)}function is_undeclared_ref(e){return e instanceof It&&e.definition().undeclared}var Rn=makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");It.DEFMETHOD("is_declared",(function(e){return!this.definition().undeclared||e.option("unsafe")&&Rn.has(this.name)}));var Fn=makePredicate("Infinity NaN undefined");function is_identifier_atom(e){return e instanceof Zt||e instanceof Yt||e instanceof jt}function tighten_body(e,t){var n,r;var o=t.find_parent(re).get_defun_scope();find_loop_scope_try();var a,s=10;do{a=false;eliminate_spurious_blocks(e);if(t.option("dead_code")){eliminate_dead_code(e,t)}if(t.option("if_return")){handle_if_return(e,t)}if(t.sequences_limit>0){sequencesize(e,t);sequencesize_2(e,t)}if(t.option("join_vars")){join_consecutive_vars(e)}if(t.option("collapse_vars")){collapse(e,t)}}while(a&&s-- >0);function find_loop_scope_try(){var e=t.self(),i=0;do{if(e instanceof Oe||e instanceof Me){i++}else if(e instanceof j){n=true}else if(e instanceof re){o=e;break}else if(e instanceof Fe){r=true}}while(e=t.parent(i++))}function collapse(e,t){if(o.pinned())return e;var s;var u=[];var l=e.length;var c=new TreeTransformer((function(e){if(k)return e;if(!T){if(e!==_[p])return e;p++;if(p<_.length)return handle_custom_scan_order(e);T=true;h=find_stop(e,0);if(h===e)k=true;return e}var n=c.parent();if(e instanceof et&&(e.logical||e.operator!="="&&g.equivalent_to(e.left))||e instanceof Se||e instanceof ze&&g instanceof He&&g.equivalent_to(e.expression)||e instanceof z||e instanceof fe||e instanceof oe&&e.expression instanceof Et&&(e.expression instanceof Vt||e.expression.definition().references.length>1)||e instanceof j&&!(e instanceof J)||e instanceof ve||e instanceof Fe||e instanceof ne||e instanceof Ae||e instanceof Ue||e instanceof _t||n instanceof J&&e!==n.init||!S&&(e instanceof It&&!e.is_declared(t)&&!Pn.has(e))||e instanceof It&&n instanceof ze&&has_annotation(n,on)){k=true;return e}if(!E&&(!D||!S)&&(n instanceof Qe&&On.has(n.operator)&&n.left!==e||n instanceof Je&&n.condition!==e||n instanceof ye&&n.condition!==e)){E=n}if(R&&!(e instanceof vt)&&g.equivalent_to(e)){if(E){k=true;return e}if(is_lhs(e,n)){if(m)C++;return e}else{C++;if(m&&d instanceof Pe)return e}a=k=true;if(d instanceof Ze){return make_node($e,d,d)}if(d instanceof Pe){var i=d.name.definition();var o=d.value;if(i.references.length-i.replaced==1&&!t.exposed(i)){i.replaced++;if(y&&is_identifier_atom(o)){return o.transform(t)}else{return maintain_this_binding(n,e,o)}}return make_node(et,d,{operator:"=",logical:false,left:make_node(It,d.name,d.name),right:o})}clear_flag(d,An);return d}var s;if(e instanceof ze||e instanceof he&&(b||g instanceof He||may_modify(g))||e instanceof He&&(b||e.expression.may_throw_on_access(t))||e instanceof It&&(v.get(e.name)||b&&may_modify(e))||e instanceof Pe&&e.value&&(v.has(e.name.name)||b&&may_modify(e.name))||(s=is_lhs(e.left,e))&&(s instanceof He||v.has(s.name))||A&&(r?e.has_side_effects(t):side_effects_external(e))){h=e;if(e instanceof re)k=true}return handle_custom_scan_order(e)}),(function(e){if(k)return;if(h===e)k=true;if(E===e)E=null}));var f=new TreeTransformer((function(e){if(k)return e;if(!T){if(e!==_[p])return e;p++;if(p<_.length)return;T=true;return e}if(e instanceof It&&e.name==M.name){if(!--C)k=true;if(is_lhs(e,f.parent()))return e;M.replaced++;m.replaced--;return d.value}if(e instanceof Ce||e instanceof re)return e}));while(--l>=0){if(l==0&&t.option("unused"))extract_args();var _=[];extract_candidates(e[l]);while(u.length>0){_=u.pop();var p=0;var d=_[_.length-1];var m=null;var h=null;var E=null;var g=get_lhs(d);if(!g||is_lhs_read_only(g)||g.has_side_effects(t))continue;var v=get_lvalues(d);var D=is_lhs_local(g);if(g instanceof It)v.set(g.name,false);var b=value_has_side_effects(d);var S=replace_all_symbols();var A=d.may_throw(t);var y=d.name instanceof yt;var T=y;var k=false,C=0,R=!s||!T;if(!R){for(var F=t.self().argnames.lastIndexOf(d.name)+1;!k&&FC)C=false;else{k=false;p=0;T=y;for(var O=l;!k&&O!(e instanceof oe)))){var r=t.has_directive("use strict");if(r&&!member(r,n.body))r=false;var i=n.argnames.length;s=e.args.slice(i);var o=new Set;for(var a=i;--a>=0;){var l=n.argnames[a];var c=e.args[a];const i=l.definition&&l.definition();const _=i&&i.orig.length>1;if(_)continue;s.unshift(make_node(Pe,l,{name:l,value:c}));if(o.has(l.name))continue;o.add(l.name);if(l instanceof oe){var f=e.args.slice(a);if(f.every((e=>!has_overlapping_symbol(n,e,r)))){u.unshift([make_node(Pe,l,{name:l.expression,value:make_node(nt,e,{elements:f})})])}}else{if(!c){c=make_node(jt,l).transform(t)}else if(c instanceof ae&&c.pinned()||has_overlapping_symbol(n,c,r)){c=null}if(c)u.unshift([make_node(Pe,l,{name:l,value:c})])}}}}function extract_candidates(e){_.push(e);if(e instanceof et){if(!e.left.has_side_effects(t)&&!(e.right instanceof Ye)){u.push(_.slice())}extract_candidates(e.right)}else if(e instanceof Qe){extract_candidates(e.left);extract_candidates(e.right)}else if(e instanceof ze&&!has_annotation(e,on)){extract_candidates(e.expression);e.args.forEach(extract_candidates)}else if(e instanceof Re){extract_candidates(e.expression)}else if(e instanceof Je){extract_candidates(e.condition);extract_candidates(e.consequent);extract_candidates(e.alternative)}else if(e instanceof xe){var n=e.definitions.length;var r=n-200;if(r<0)r=0;for(;r1&&!(e.name instanceof yt)||(r>1?mangleable_var(e):!t.exposed(n))){return make_node(It,e.name,e.name)}}else{const t=e instanceof et?e.left:e.expression;return!is_ref_of(t,St)&&!is_ref_of(t,At)&&t}}function get_rvalue(e){if(e instanceof et){return e.right}else{return e.value}}function get_lvalues(e){var n=new Map;if(e instanceof je)return n;var r=new TreeWalker((function(e){var i=e;while(i instanceof He)i=i.expression;if(i instanceof It||i instanceof Vt){n.set(i.name,n.get(i.name)||is_modified(t,r,e,e,0))}}));get_rvalue(e).walk(r);return n}function remove_candidate(n){if(n.name instanceof yt){var r=t.parent(),o=t.self().argnames;var a=o.indexOf(n.name);if(a<0){r.args.length=Math.min(r.args.length,o.length-1)}else{var s=r.args;if(s[a])s[a]=make_node(Gt,s[a],{value:0})}return true}var u=false;return e[l].transform(new TreeTransformer((function(e,t,r){if(u)return e;if(e===n||e.body===n){u=true;if(e instanceof Pe){e.value=e.name instanceof St?make_node(jt,e.value):null;return e}return r?i.skip:null}}),(function(e){if(e instanceof Ge)switch(e.expressions.length){case 0:return null;case 1:return e.expressions[0]}})))}function is_lhs_local(e){while(e instanceof He)e=e.expression;return e instanceof It&&e.definition().scope===o&&!(n&&(v.has(e.name)||d instanceof je||d instanceof et&&!d.logical&&d.operator!="="))}function value_has_side_effects(e){if(e instanceof je)return Mn.has(e.operator);return get_rvalue(e).has_side_effects(t)}function replace_all_symbols(){if(b)return false;if(m)return true;if(g instanceof It){var e=g.definition();if(e.references.length-e.replaced==(d instanceof Pe?1:2)){return true}}return false}function may_modify(e){if(!e.definition)return true;var t=e.definition();if(t.orig.length==1&&t.orig[0]instanceof Tt)return false;if(t.scope.get_defun_scope()!==o)return true;return!t.references.every((e=>{var t=e.scope.get_defun_scope();if(t.TYPE=="Scope")t=t.parent_scope;return t===o}))}function side_effects_external(e,t){if(e instanceof et)return side_effects_external(e.left,true);if(e instanceof je)return side_effects_external(e.expression,true);if(e instanceof Pe)return e.value&&side_effects_external(e.value);if(t){if(e instanceof Xe)return side_effects_external(e.expression,true);if(e instanceof qe)return side_effects_external(e.expression,true);if(e instanceof It)return e.definition().scope!==o}return false}}function eliminate_spurious_blocks(e){var t=[];for(var n=0;n=0;){var s=e[o];var u=next_index(o);var l=e[u];if(i&&!l&&s instanceof Ee){if(!s.value){a=true;e.splice(o,1);continue}if(s.value instanceof $e&&s.value.operator=="void"){a=true;e[o]=make_node(G,s,{body:s.value.expression});continue}}if(s instanceof ye){var c=aborts(s.body);if(can_merge_flow(c)){if(c.label){remove(c.label.thedef.references,c)}a=true;s=s.clone();s.condition=s.condition.negate(t);var f=as_statement_array_with_return(s.body,c);s.body=make_node(X,s,{body:as_statement_array(s.alternative).concat(extract_functions())});s.alternative=make_node(X,s,{body:f});e[o]=s.transform(t);continue}var c=aborts(s.alternative);if(can_merge_flow(c)){if(c.label){remove(c.label.thedef.references,c)}a=true;s=s.clone();s.body=make_node(X,s.body,{body:as_statement_array(s.body).concat(extract_functions())});var f=as_statement_array_with_return(s.alternative,c);s.alternative=make_node(X,s.alternative,{body:f});e[o]=s.transform(t);continue}}if(s instanceof ye&&s.body instanceof Ee){var _=s.body.value;if(!_&&!s.alternative&&(i&&!l||l instanceof Ee&&!l.value)){a=true;e[o]=make_node(G,s.condition,{body:s.condition});continue}if(_&&!s.alternative&&l instanceof Ee&&l.value){a=true;s=s.clone();s.alternative=l;e[o]=s.transform(t);e.splice(u,1);continue}if(_&&!s.alternative&&(!l&&i&&r||l instanceof Ee)){a=true;s=s.clone();s.alternative=l||make_node(Ee,s,{value:null});e[o]=s.transform(t);if(l)e.splice(u,1);continue}var p=e[prev_index(o)];if(t.option("sequences")&&i&&!s.alternative&&p instanceof ye&&p.body instanceof Ee&&next_index(u)==e.length&&l instanceof G){a=true;s=s.clone();s.alternative=make_node(X,l,{body:[l,make_node(Ee,l,{value:null})]});e[o]=s.transform(t);e.splice(u,1);continue}}}function has_multiple_if_returns(e){var t=0;for(var n=e.length;--n>=0;){var r=e[n];if(r instanceof ye&&r.body instanceof Ee){if(++t>1)return true}}return false}function is_return_void(e){return!e||e instanceof $e&&e.operator=="void"}function can_merge_flow(r){if(!r)return false;for(var a=o+1,s=e.length;a=0;){var r=e[n];if(!(r instanceof Ne&&declarations_only(r))){break}}return n}}function eliminate_dead_code(e,t){var n;var r=t.self();for(var i=0,o=0,s=e.length;i!e.value))}function sequencesize(e,t){if(e.length<2)return;var n=[],r=0;function push_seq(){if(!n.length)return;var t=make_sequence(n[0],n);e[r++]=make_node(G,t,{body:t});n=[]}for(var i=0,o=e.length;i=t.sequences_limit)push_seq();var u=s.body;if(n.length>0)u=u.drop_side_effect_free(t);if(u)merge_sequence(n,u)}else if(s instanceof xe&&declarations_only(s)||s instanceof ce){e[r++]=s}else{push_seq();e[r++]=s}}push_seq();e.length=r;if(r!=o)a=true}function to_simple_statement(e,t){if(!(e instanceof X))return e;var n=null;for(var r=0,i=e.body.length;r{if(e instanceof re)return true;if(e instanceof Qe&&e.operator==="in"){return tn}}));if(!e){if(o.init)o.init=cons_seq(o.init);else{o.init=r.body;n--;a=true}}}}else if(o instanceof ee){if(!(o.init instanceof Ie)&&!(o.init instanceof we)){o.object=cons_seq(o.object)}}else if(o instanceof ye){o.condition=cons_seq(o.condition)}else if(o instanceof Te){o.expression=cons_seq(o.expression)}else if(o instanceof ne){o.expression=cons_seq(o.expression)}}if(t.option("conditionals")&&o instanceof ye){var s=[];var u=to_simple_statement(o.body,s);var l=to_simple_statement(o.alternative,s);if(u!==false&&l!==false&&s.length>0){var c=s.length;s.push(make_node(ye,o,{condition:o.condition,body:u||make_node(W,o.body),alternative:l}));s.unshift(n,1);[].splice.apply(e,s);i+=c;n+=c+1;r=null;a=true;continue}}e[n++]=o;r=o instanceof G?o:null}e.length=n}function join_object_assignments(e,n){if(!(e instanceof xe))return;var r=e.definitions[e.definitions.length-1];if(!(r.value instanceof rt))return;var i;if(n instanceof et&&!n.logical){i=[n]}else if(n instanceof Ge){i=n.expressions.slice()}if(!i)return;var a=false;do{var s=i[0];if(!(s instanceof et))break;if(s.operator!="=")break;if(!(s.left instanceof He))break;var u=s.left.expression;if(!(u instanceof It))break;if(r.name.name!=u.name)break;if(!s.right.is_constant_expression(o))break;var l=s.left.property;if(l instanceof V){l=l.evaluate(t)}if(l instanceof V)break;l=""+l;var c=t.option("ecma")<2015&&t.has_directive("use strict")?function(e){return e.key!=l&&(e.key&&e.key.name!=l)}:function(e){return e.key&&e.key.name!=l};if(!r.value.properties.every(c))break;var f=r.value.properties.filter((function(e){return e.key===l}))[0];if(!f){r.value.properties.push(make_node(ot,s,{key:l,value:s.right}))}else{f.value=new Ge({start:f.start,expressions:[f.value.clone(),s.right.clone()],end:f.end})}i.shift();a=true}while(i.length);return a&&i}function join_consecutive_vars(e){var t;for(var n=0,r=-1,i=e.length;n{if(r instanceof Ne){r.remove_initializers();n.push(r);return true}if(r instanceof ce&&(r===t||!e.has_directive("use strict"))){n.push(r===t?r:make_node(Ne,r,{definitions:[make_node(Pe,r,{name:make_node(Dt,r.name,r.name),value:null})]}));return true}if(r instanceof Ue||r instanceof Le){n.push(r);return true}if(r instanceof re){return true}}))}function get_value(e){if(e instanceof zt){return e.getValue()}if(e instanceof $e&&e.operator=="void"&&e.expression instanceof zt){return}return e}function is_undefined(e,t){return has_flag(e,bn)||e instanceof jt||e instanceof $e&&e.operator=="void"&&!e.expression.has_side_effects(t)}(function(e){V.DEFMETHOD("may_throw_on_access",(function(e){return!e.option("pure_getters")||this._dot_throw(e)}));function is_strict(e){return/strict/.test(e.option("pure_getters"))}e(V,is_strict);e(qt,return_true);e(jt,return_true);e(zt,return_false);e(nt,return_false);e(rt,(function(e){if(!is_strict(e))return false;for(var t=this.properties.length;--t>=0;)if(this.properties[t]._dot_throw(e))return true;return false}));e(_t,return_false);e(it,return_false);e(lt,return_true);e(oe,(function(e){return this.expression._dot_throw(e)}));e(ue,return_false);e(le,return_false);e(Ze,return_false);e($e,(function(){return this.operator=="void"}));e(Qe,(function(e){return(this.operator=="&&"||this.operator=="||"||this.operator=="??")&&(this.left._dot_throw(e)||this.right._dot_throw(e))}));e(et,(function(e){if(this.logical)return true;return this.operator=="="&&this.right._dot_throw(e)}));e(Je,(function(e){return this.consequent._dot_throw(e)||this.alternative._dot_throw(e)}));e(Xe,(function(e){if(!is_strict(e))return false;if(this.property=="prototype"){return!(this.expression instanceof ue||this.expression instanceof _t)}return true}));e(Ye,(function(e){return this.expression._dot_throw(e)}));e(Ge,(function(e){return this.tail_node()._dot_throw(e)}));e(It,(function(e){if(this.name==="arguments")return false;if(has_flag(this,bn))return true;if(!is_strict(e))return false;if(is_undeclared_ref(this)&&this.is_declared(e))return false;if(this.is_immutable())return false;var t=this.fixed_value();return!t||t._dot_throw(e)}))})((function(e,t){e.DEFMETHOD("_dot_throw",t)}));(function(e){const t=makePredicate("! delete");const n=makePredicate("in instanceof == != === !== < <= >= >");e(V,return_false);e($e,(function(){return t.has(this.operator)}));e(Qe,(function(){return n.has(this.operator)||On.has(this.operator)&&this.left.is_boolean()&&this.right.is_boolean()}));e(Je,(function(){return this.consequent.is_boolean()&&this.alternative.is_boolean()}));e(et,(function(){return this.operator=="="&&this.right.is_boolean()}));e(Ge,(function(){return this.tail_node().is_boolean()}));e(en,return_true);e(Jt,return_true)})((function(e,t){e.DEFMETHOD("is_boolean",t)}));(function(e){e(V,return_false);e(Gt,return_true);var t=makePredicate("+ - ~ ++ --");e(je,(function(){return t.has(this.operator)}));var n=makePredicate("- * / % & | ^ << >> >>>");e(Qe,(function(e){return n.has(this.operator)||this.operator=="+"&&this.left.is_number(e)&&this.right.is_number(e)}));e(et,(function(e){return n.has(this.operator.slice(0,-1))||this.operator=="="&&this.right.is_number(e)}));e(Ge,(function(e){return this.tail_node().is_number(e)}));e(Je,(function(e){return this.consequent.is_number(e)&&this.alternative.is_number(e)}))})((function(e,t){e.DEFMETHOD("is_number",t)}));(function(e){e(V,return_false);e(Kt,return_true);e(pe,return_true);e($e,(function(){return this.operator=="typeof"}));e(Qe,(function(e){return this.operator=="+"&&(this.left.is_string(e)||this.right.is_string(e))}));e(et,(function(e){return(this.operator=="="||this.operator=="+=")&&this.right.is_string(e)}));e(Ge,(function(e){return this.tail_node().is_string(e)}));e(Je,(function(e){return this.consequent.is_string(e)&&this.alternative.is_string(e)}))})((function(e,t){e.DEFMETHOD("is_string",t)}));var On=makePredicate("&& || ??");var Mn=makePredicate("delete ++ --");function is_lhs(e,t){if(t instanceof je&&Mn.has(t.operator))return t.expression;if(t instanceof et&&t.left===e)return e}(function(e){function to_node(e,t){if(e instanceof V)return make_node(e.CTOR,t,e);if(Array.isArray(e))return make_node(nt,t,{elements:e.map((function(e){return to_node(e,t)}))});if(e&&typeof e=="object"){var n=[];for(var r in e)if(HOP(e,r)){n.push(make_node(ot,t,{key:r,value:to_node(e[r],t)}))}return make_node(rt,t,{properties:n})}return make_node_from_constant(e,t)}ie.DEFMETHOD("resolve_defines",(function(e){if(!e.option("global_defs"))return this;this.figure_out_scope({ie8:e.option("ie8")});return this.transform(new TreeTransformer((function(t){var n=t._find_defs(e,"");if(!n)return;var r=0,i=t,o;while(o=this.parent(r++)){if(!(o instanceof He))break;if(o.expression!==i)break;i=o}if(is_lhs(i,o)){return}return n})))}));e(V,noop);e(Ye,(function(e,t){return this.expression._find_defs(e,t)}));e(Xe,(function(e,t){return this.expression._find_defs(e,"."+this.property+t)}));e(vt,(function(){if(!this.global())return}));e(It,(function(e,t){if(!this.global())return;var n=e.option("global_defs");var r=this.name+t;if(HOP(n,r))return to_node(n[r],this)}))})((function(e,t){e.DEFMETHOD("_find_defs",t)}));function best_of_expression(e,t){return e.size()>t.size()?t:e}function best_of_statement(e,t){return best_of_expression(make_node(G,e,{body:e}),make_node(G,t,{body:t})).body}function best_of(e,t,n){return(first_in_statement(e)?best_of_statement:best_of_expression)(t,n)}function convert_to_predicate(e){const t=new Map;for(var n of Object.keys(e)){t.set(n,makePredicate(e[n]))}return t}var xn=["constructor","toString","valueOf"];var Nn=convert_to_predicate({Array:["indexOf","join","lastIndexOf","slice"].concat(xn),Boolean:xn,Function:xn,Number:["toExponential","toFixed","toPrecision"].concat(xn),Object:xn,RegExp:["test"].concat(xn),String:["charAt","charCodeAt","concat","indexOf","italics","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","trim"].concat(xn)});var wn=convert_to_predicate({Array:["isArray"],Math:["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","atan2","pow","max","min"],Number:["isFinite","isNaN"],Object:["create","getOwnPropertyDescriptor","getOwnPropertyNames","getPrototypeOf","isExtensible","isFrozen","isSealed","keys"],String:["fromCharCode"]});(function(e){V.DEFMETHOD("evaluate",(function(e){if(!e.option("evaluate"))return this;var t=this._eval(e,1);if(!t||t instanceof RegExp)return t;if(typeof t=="function"||typeof t=="object")return this;return t}));var t=makePredicate("! ~ - + void");V.DEFMETHOD("is_constant",(function(){if(this instanceof zt){return!(this instanceof Xt)}else{return this instanceof $e&&this.expression instanceof zt&&t.has(this.operator)}}));e(U,(function(){throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]",this.start))}));e(ae,return_this);e(_t,return_this);e(V,return_this);e(zt,(function(){return this.getValue()}));e(Ht,return_this);e(Xt,(function(e){let t=e.evaluated_regexps.get(this);if(t===undefined){try{t=(0,eval)(this.print_to_string())}catch(e){t=null}e.evaluated_regexps.set(this,t)}return t||this}));e(pe,(function(){if(this.segments.length!==1)return this;return this.segments[0].value}));e(ue,(function(e){if(e.option("unsafe")){var fn=function(){};fn.node=this;fn.toString=()=>this.print_to_string();return fn}return this}));e(nt,(function(e,t){if(e.option("unsafe")){var n=[];for(var r=0,i=this.elements.length;rtypeof e==="object"||typeof e==="function"||typeof e==="symbol";e(Qe,(function(e,t){if(!r.has(this.operator))t++;var n=this.left._eval(e,t);if(n===this.left)return this;var o=this.right._eval(e,t);if(o===this.right)return this;var a;if(n!=null&&o!=null&&i.has(this.operator)&&has_identity(n)&&has_identity(o)&&typeof n===typeof o){return this}switch(this.operator){case"&&":a=n&&o;break;case"||":a=n||o;break;case"??":a=n!=null?n:o;break;case"|":a=n|o;break;case"&":a=n&o;break;case"^":a=n^o;break;case"+":a=n+o;break;case"*":a=n*o;break;case"**":a=Math.pow(n,o);break;case"/":a=n/o;break;case"%":a=n%o;break;case"-":a=n-o;break;case"<<":a=n<>":a=n>>o;break;case">>>":a=n>>>o;break;case"==":a=n==o;break;case"===":a=n===o;break;case"!=":a=n!=o;break;case"!==":a=n!==o;break;case"<":a=n":a=n>o;break;case">=":a=n>=o;break;default:return this}if(isNaN(a)&&e.find_parent(ne)){return this}return a}));e(Je,(function(e,t){var n=this.condition._eval(e,t);if(n===this.condition)return this;var r=n?this.consequent:this.alternative;var i=r._eval(e,t);return i===r?this:i}));const o=new Set;e(It,(function(e,t){if(o.has(this))return this;var n=this.fixed_value();if(!n)return this;o.add(this);const r=n._eval(e,t);o.delete(this);if(r===n)return this;if(r&&typeof r=="object"){var i=this.definition().escaped;if(i&&t>i)return this}return r}));var a={Array:Array,Math:Math,Number:Number,Object:Object,String:String};var s=convert_to_predicate({Math:["E","LN10","LN2","LOG2E","LOG10E","PI","SQRT1_2","SQRT2"],Number:["MAX_VALUE","MIN_VALUE","NaN","NEGATIVE_INFINITY","POSITIVE_INFINITY"]});const u=new Set(["dotAll","global","ignoreCase","multiline","sticky","unicode"]);e(He,(function(e,t){if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")){var n=this.property;if(n instanceof V){n=n._eval(e,t);if(n===this.property)return this}var r=this.expression;var i;if(is_undeclared_ref(r)){var o;var l=r.name==="hasOwnProperty"&&n==="call"&&(o=e.parent()&&e.parent().args)&&(o&&o[0]&&o[0].evaluate(e));l=l instanceof Xe?l.expression:l;if(l==null||l.thedef&&l.thedef.undeclared){return this.clone()}var c=s.get(r.name);if(!c||!c.has(n))return this;i=a[r.name]}else{i=r._eval(e,t+1);if(i instanceof RegExp){if(n=="source"){return regexp_source_fix(i.source)}else if(n=="flags"||u.has(n)){return i[n]}}if(!i||i===r||!HOP(i,n))return this;if(typeof i=="function")switch(n){case"name":return i.node.name?i.node.name.name:"";case"length":return i.node.length_property();default:return this}}return i[n]}return this}));e(Ye,(function(e,t){const n=this.expression._eval(e,t);return n===this.expression?this:n}));e(ze,(function(e,t){var n=this.expression;if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")&&n instanceof He){var r=n.property;if(r instanceof V){r=r._eval(e,t);if(r===n.property)return this}var i;var o=n.expression;if(is_undeclared_ref(o)){var s=o.name==="hasOwnProperty"&&r==="call"&&(this.args[0]&&this.args[0].evaluate(e));s=s instanceof Xe?s.expression:s;if(s==null||s.thedef&&s.thedef.undeclared){return this.clone()}var u=wn.get(o.name);if(!u||!u.has(r))return this;i=a[o.name]}else{i=o._eval(e,t+1);if(i===o||!i)return this;var l=Nn.get(i.constructor.name);if(!l||!l.has(r))return this}var c=[];for(var f=0,_=this.args.length;f<_;f++){var p=this.args[f];var d=p._eval(e,t);if(p===d)return this;if(p instanceof ae)return this;c.push(d)}try{return i[r].apply(i,c)}catch(e){}}return this}));e(Ke,return_this)})((function(e,t){e.DEFMETHOD("_eval",t)}));(function(e){function basic_negation(e){return make_node($e,e,{operator:"!",expression:e})}function best(e,t,n){var r=basic_negation(e);if(n){var i=make_node(G,t,{body:t});return best_of_expression(r,i)===i?t:r}return best_of_expression(r,t)}e(V,(function(){return basic_negation(this)}));e(U,(function(){throw new Error("Cannot negate a statement")}));e(ue,(function(){return basic_negation(this)}));e(le,(function(){return basic_negation(this)}));e($e,(function(){if(this.operator=="!")return this.expression;return basic_negation(this)}));e(Ge,(function(e){var t=this.expressions.slice();t.push(t.pop().negate(e));return make_sequence(this,t)}));e(Je,(function(e,t){var n=this.clone();n.consequent=n.consequent.negate(e);n.alternative=n.alternative.negate(e);return best(this,n,t)}));e(Qe,(function(e,t){var n=this.clone(),r=this.operator;if(e.option("unsafe_comps")){switch(r){case"<=":n.operator=">";return n;case"<":n.operator=">=";return n;case">=":n.operator="<";return n;case">":n.operator="<=";return n}}switch(r){case"==":n.operator="!=";return n;case"!=":n.operator="==";return n;case"===":n.operator="!==";return n;case"!==":n.operator="===";return n;case"&&":n.operator="||";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"||":n.operator="&&";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"??":n.right=n.right.negate(e);return best(this,n,t)}return basic_negation(this)}))})((function(e,t){e.DEFMETHOD("negate",(function(e,n){return t.call(this,e,n)}))}));var In=makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");ze.DEFMETHOD("is_callee_pure",(function(e){if(e.option("unsafe")){var t=this.expression;var n=this.args&&this.args[0]&&this.args[0].evaluate(e);if(t.expression&&t.expression.name==="hasOwnProperty"&&(n==null||n.thedef&&n.thedef.undeclared)){return false}if(is_undeclared_ref(t)&&In.has(t.name))return true;let r;if(t instanceof Xe&&is_undeclared_ref(t.expression)&&(r=wn.get(t.expression.name))&&r.has(t.property)){return true}}return!!has_annotation(this,nn)||!e.pure_funcs(this)}));V.DEFMETHOD("is_call_pure",return_false);Xe.DEFMETHOD("is_call_pure",(function(e){if(!e.option("unsafe"))return;const t=this.expression;let n;if(t instanceof nt){n=Nn.get("Array")}else if(t.is_boolean()){n=Nn.get("Boolean")}else if(t.is_number(e)){n=Nn.get("Number")}else if(t instanceof Xt){n=Nn.get("RegExp")}else if(t.is_string(e)){n=Nn.get("String")}else if(!this.may_throw_on_access(e)){n=Nn.get("Object")}return n&&n.has(this.property)}));const Pn=new Set(["Number","String","Array","Object","Function","Promise"]);(function(e){e(V,return_true);e(W,return_false);e(zt,return_false);e(Vt,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].has_side_effects(t))return true;return false}e(H,(function(e){return any(this.body,e)}));e(ze,(function(e){if(!this.is_callee_pure(e)&&(!this.expression.is_call_pure(e)||this.expression.has_side_effects(e))){return true}return any(this.args,e)}));e(Te,(function(e){return this.expression.has_side_effects(e)||any(this.body,e)}));e(Re,(function(e){return this.expression.has_side_effects(e)||any(this.body,e)}));e(Fe,(function(e){return any(this.body,e)||this.bcatch&&this.bcatch.has_side_effects(e)||this.bfinally&&this.bfinally.has_side_effects(e)}));e(ye,(function(e){return this.condition.has_side_effects(e)||this.body&&this.body.has_side_effects(e)||this.alternative&&this.alternative.has_side_effects(e)}));e(Y,(function(e){return this.body.has_side_effects(e)}));e(G,(function(e){return this.body.has_side_effects(e)}));e(ae,return_false);e(_t,(function(e){if(this.extends&&this.extends.has_side_effects(e)){return true}return any(this.properties,e)}));e(Qe,(function(e){return this.left.has_side_effects(e)||this.right.has_side_effects(e)}));e(et,return_true);e(Je,(function(e){return this.condition.has_side_effects(e)||this.consequent.has_side_effects(e)||this.alternative.has_side_effects(e)}));e(je,(function(e){return Mn.has(this.operator)||this.expression.has_side_effects(e)}));e(It,(function(e){return!this.is_declared(e)&&!Pn.has(this.name)}));e(Ct,return_false);e(vt,return_false);e(rt,(function(e){return any(this.properties,e)}));e(it,(function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.value&&this.value.has_side_effects(e)}));e(pt,(function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.static&&this.value&&this.value.has_side_effects(e)}));e(ct,(function(e){return this.computed_key()&&this.key.has_side_effects(e)}));e(lt,(function(e){return this.computed_key()&&this.key.has_side_effects(e)}));e(ut,(function(e){return this.computed_key()&&this.key.has_side_effects(e)}));e(nt,(function(e){return any(this.elements,e)}));e(Xe,(function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)}));e(qe,(function(e){if(this.optional&&is_nullish(this.expression,e)){return false}return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)||this.property.has_side_effects(e)}));e(Ye,(function(e){return this.expression.has_side_effects(e)}));e(Ge,(function(e){return any(this.expressions,e)}));e(xe,(function(e){return any(this.definitions,e)}));e(Pe,(function(){return this.value}));e(de,return_false);e(pe,(function(e){return any(this.segments,e)}))})((function(e,t){e.DEFMETHOD("has_side_effects",t)}));(function(e){e(V,return_true);e(zt,return_false);e(W,return_false);e(ae,return_false);e(vt,return_false);e(Vt,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].may_throw(t))return true;return false}e(_t,(function(e){if(this.extends&&this.extends.may_throw(e))return true;return any(this.properties,e)}));e(nt,(function(e){return any(this.elements,e)}));e(et,(function(e){if(this.right.may_throw(e))return true;if(!e.has_directive("use strict")&&this.operator=="="&&this.left instanceof It){return false}return this.left.may_throw(e)}));e(Qe,(function(e){return this.left.may_throw(e)||this.right.may_throw(e)}));e(H,(function(e){return any(this.body,e)}));e(ze,(function(e){if(this.optional&&is_nullish(this.expression,e))return false;if(any(this.args,e))return true;if(this.is_callee_pure(e))return false;if(this.expression.may_throw(e))return true;return!(this.expression instanceof ae)||any(this.expression.body,e)}));e(Re,(function(e){return this.expression.may_throw(e)||any(this.body,e)}));e(Je,(function(e){return this.condition.may_throw(e)||this.consequent.may_throw(e)||this.alternative.may_throw(e)}));e(xe,(function(e){return any(this.definitions,e)}));e(ye,(function(e){return this.condition.may_throw(e)||this.body&&this.body.may_throw(e)||this.alternative&&this.alternative.may_throw(e)}));e(Y,(function(e){return this.body.may_throw(e)}));e(rt,(function(e){return any(this.properties,e)}));e(it,(function(e){return this.value?this.value.may_throw(e):false}));e(pt,(function(e){return this.computed_key()&&this.key.may_throw(e)||this.static&&this.value&&this.value.may_throw(e)}));e(ct,(function(e){return this.computed_key()&&this.key.may_throw(e)}));e(lt,(function(e){return this.computed_key()&&this.key.may_throw(e)}));e(ut,(function(e){return this.computed_key()&&this.key.may_throw(e)}));e(Ee,(function(e){return this.value&&this.value.may_throw(e)}));e(Ge,(function(e){return any(this.expressions,e)}));e(G,(function(e){return this.body.may_throw(e)}));e(Xe,(function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)}));e(qe,(function(e){if(this.optional&&is_nullish(this.expression,e))return false;return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)||this.property.may_throw(e)}));e(Ye,(function(e){return this.expression.may_throw(e)}));e(Te,(function(e){return this.expression.may_throw(e)||any(this.body,e)}));e(It,(function(e){return!this.is_declared(e)&&!Pn.has(this.name)}));e(Ct,return_false);e(Fe,(function(e){return this.bcatch?this.bcatch.may_throw(e):any(this.body,e)||this.bfinally&&this.bfinally.may_throw(e)}));e(je,(function(e){if(this.operator=="typeof"&&this.expression instanceof It)return false;return this.expression.may_throw(e)}));e(Pe,(function(e){if(!this.value)return false;return this.value.may_throw(e)}))})((function(e,t){e.DEFMETHOD("may_throw",t)}));(function(e){function all_refs_local(e){let t=true;walk(this,(n=>{if(n instanceof It){if(has_flag(this,Sn)){t=false;return tn}var r=n.definition();if(member(r,this.enclosed)&&!this.variables.has(r.name)){if(e){var i=e.find_variable(n);if(r.undeclared?!i:i===r){t="f";return true}}t=false;return tn}return true}if(n instanceof Vt&&this instanceof le){t=false;return tn}}));return t}e(V,return_false);e(zt,return_true);e(_t,(function(e){if(this.extends&&!this.extends.is_constant_expression(e)){return false}for(const t of this.properties){if(t.computed_key()&&!t.key.is_constant_expression(e)){return false}if(t.static&&t.value&&!t.value.is_constant_expression(e)){return false}}return all_refs_local.call(this,e)}));e(ae,all_refs_local);e(je,(function(){return this.expression.is_constant_expression()}));e(Qe,(function(){return this.left.is_constant_expression()&&this.right.is_constant_expression()}));e(nt,(function(){return this.elements.every((e=>e.is_constant_expression()))}));e(rt,(function(){return this.properties.every((e=>e.is_constant_expression()))}));e(it,(function(){return!!(!(this.key instanceof V)&&this.value&&this.value.is_constant_expression())}))})((function(e,t){e.DEFMETHOD("is_constant_expression",t)}));function aborts(e){return e&&e.aborts()}(function(e){e(U,return_null);e(me,return_this);function block_aborts(){for(var e=0;e{if(e instanceof vt){const n=e.definition();if((t||n.global)&&!a.has(n.id)){a.set(n.id,n)}}}))}if(n.value){if(n.name instanceof fe){n.walk(f)}else{var i=n.name.definition();map_add(l,i.id,n.value);if(!i.chained&&n.name.fixed_value()===n.value){s.set(i.id,n)}}if(n.value.has_side_effects(e)){n.value.walk(f)}}}));return true}return scan_ref_scoped(i,o)}));t.walk(f);f=new TreeWalker(scan_ref_scoped);a.forEach((function(e){var t=l.get(e.id);if(t)t.forEach((function(e){e.walk(f)}))}));var _=new TreeTransformer((function before(l,f,p){var d=_.parent();if(r){const e=o(l);if(e instanceof It){var m=e.definition();var h=a.has(m.id);if(l instanceof et){if(!h||s.has(m.id)&&s.get(m.id)!==l){return maintain_this_binding(d,l,l.right.transform(_))}}else if(!h)return p?i.skip:make_node(Gt,l,{value:0})}}if(c!==t)return;var m;if(l.name&&(l instanceof ht&&!keep_name(e.option("keep_classnames"),(m=l.name.definition()).name)||l instanceof ue&&!keep_name(e.option("keep_fnames"),(m=l.name.definition()).name))){if(!a.has(m.id)||m.orig.length>1)l.name=null}if(l instanceof ae&&!(l instanceof se)){var E=!e.option("keep_fargs");for(var g=l.argnames,v=g.length;--v>=0;){var D=g[v];if(D instanceof oe){D=D.expression}if(D instanceof tt){D=D.left}if(!(D instanceof fe)&&!a.has(D.definition().id)){set_flag(D,gn);if(E){g.pop()}}else{E=false}}}if((l instanceof ce||l instanceof mt)&&l!==t){const t=l.name.definition();let r=t.global&&!n||a.has(t.id);if(!r){t.eliminated++;if(l instanceof mt){const t=l.drop_side_effect_free(e);if(t){return make_node(G,l,{body:t})}}return p?i.skip:make_node(W,l)}}if(l instanceof xe&&!(d instanceof ee&&d.init===l)){var b=!(d instanceof ie)&&!(l instanceof Ne);var S=[],A=[],y=[];var T=[];l.definitions.forEach((function(t){if(t.value)t.value=t.value.transform(_);var n=t.name instanceof fe;var i=n?new SymbolDef(null,{name:""}):t.name.definition();if(b&&i.global)return y.push(t);if(!(r||b)||n&&(t.name.names.length||t.name.is_array||e.option("pure_getters")!=true)||a.has(i.id)){if(t.value&&s.has(i.id)&&s.get(i.id)!==t){t.value=t.value.drop_side_effect_free(e)}if(t.name instanceof Dt){var o=u.get(i.id);if(o.length>1&&(!t.value||i.orig.indexOf(t.name)>i.eliminated)){if(t.value){var c=make_node(It,t.name,t.name);i.references.push(c);var f=make_node(et,t,{operator:"=",logical:false,left:c,right:t.value});if(s.get(i.id)===t){s.set(i.id,f)}T.push(f.transform(_))}remove(o,t);i.eliminated++;return}}if(t.value){if(T.length>0){if(y.length>0){T.push(t.value);t.value=make_sequence(t.value,T)}else{S.push(make_node(G,l,{body:make_sequence(l,T)}))}T=[]}y.push(t)}else{A.push(t)}}else if(i.orig[0]instanceof Mt){var p=t.value&&t.value.drop_side_effect_free(e);if(p)T.push(p);t.value=null;A.push(t)}else{var p=t.value&&t.value.drop_side_effect_free(e);if(p){T.push(p)}i.eliminated++}}));if(A.length>0||y.length>0){l.definitions=A.concat(y);S.push(l)}if(T.length>0){S.push(make_node(G,l,{body:make_sequence(l,T)}))}switch(S.length){case 0:return p?i.skip:make_node(W,l);case 1:return S[0];default:return p?i.splice(S):make_node(X,l,{body:S})}}if(l instanceof J){f(l,this);var k;if(l.init instanceof X){k=l.init;l.init=k.body.pop();k.body.push(l)}if(l.init instanceof G){l.init=l.init.body}else if(is_empty(l.init)){l.init=null}return!k?l:p?i.splice(k.body):k}if(l instanceof Y&&l.body instanceof J){f(l,this);if(l.body instanceof X){var k=l.body;l.body=k.body.pop();k.body.push(l);return p?i.splice(k.body):k}return l}if(l instanceof X){f(l,this);if(p&&l.body.every(can_be_evicted_from_block)){return i.splice(l.body)}return l}if(l instanceof re){const e=c;c=l;f(l,this);c=e;return l}}));t.transform(_);function scan_ref_scoped(e,n){var r;const i=o(e);if(i instanceof It&&!is_ref_of(e.left,bt)&&t.variables.get(i.name)===(r=i.definition())){if(e instanceof et){e.right.walk(f);if(!r.chained&&e.left.fixed_value()===e.right){s.set(r.id,e)}}return true}if(e instanceof It){r=e.definition();if(!a.has(r.id)){a.set(r.id,r);if(r.orig[0]instanceof Mt){const e=r.scope.is_block_scope()&&r.scope.get_defun_scope().variables.get(r.name);if(e)a.set(e.id,e)}}return true}if(e instanceof re){var u=c;c=e;n();c=u;return true}}}));re.DEFMETHOD("hoist_declarations",(function(e){var t=this;if(e.has_directive("use asm"))return t;if(!Array.isArray(t.body))return t;var n=e.option("hoist_funs");var r=e.option("hoist_vars");if(n||r){var i=[];var o=[];var a=new Map,s=0,u=0;walk(t,(e=>{if(e instanceof re&&e!==t)return true;if(e instanceof Ne){++u;return true}}));r=r&&u>1;var l=new TreeTransformer((function before(u){if(u!==t){if(u instanceof K){i.push(u);return make_node(W,u)}if(n&&u instanceof ce&&!(l.parent()instanceof Ue)&&l.parent()===t){o.push(u);return make_node(W,u)}if(r&&u instanceof Ne&&!u.definitions.some((e=>e.name instanceof fe))){u.definitions.forEach((function(e){a.set(e.name.name,e);++s}));var c=u.to_assignments(e);var f=l.parent();if(f instanceof ee&&f.init===u){if(c==null){var _=u.definitions[0].name;return make_node(It,_,_)}return c}if(f instanceof J&&f.init===u){return c}if(!c)return make_node(W,u);return make_node(G,u,{body:c})}if(u instanceof re)return u}}));t=t.transform(l);if(s>0){var c=[];const e=t instanceof ae;const n=e?t.args_as_names():null;a.forEach(((t,r)=>{if(e&&n.some((e=>e.name===t.name.name))){a.delete(r)}else{t=t.clone();t.value=null;c.push(t);a.set(r,t)}}));if(c.length>0){for(var f=0;fe instanceof oe||e.computed_key()))){s(a,this);const e=new Map;const n=[];c.properties.forEach((({key:r,value:i})=>{const s=find_scope(o);const l=t.create_symbol(u.CTOR,{source:u,scope:s,conflict_scopes:new Set([s,...u.definition().references.map((e=>e.scope))]),tentative_name:u.name+"_"+r});e.set(String(r),l.definition());n.push(make_node(Pe,a,{name:l,value:i}))}));r.set(l.id,e);return i.splice(n)}}else if(a instanceof He&&a.expression instanceof It){const e=r.get(a.expression.definition().id);if(e){const t=e.get(String(get_value(a.property)));const n=make_node(It,a,{name:t.name,scope:a.expression.scope,thedef:t});n.reference({});return n}}}));return t.transform(o)}));(function(e){function trim(e,t,n){var r=e.length;if(!r)return null;var i=[],o=false;for(var a=0;a0){a[0].body=o.concat(a[0].body)}e.body=a;while(n=a[a.length-1]){var d=n.body[n.body.length-1];if(d instanceof De&&t.loopcontrol_target(d)===e)n.body.pop();if(n.body.length||n instanceof Re&&(s||n.expression.has_side_effects(t)))break;if(a.pop()===s)s=null}if(a.length==0){return make_node(X,e,{body:o.concat(make_node(G,e.expression,{body:e.expression}))}).optimize(t)}if(a.length==1&&(a[0]===u||a[0]===s)){var m=false;var h=new TreeWalker((function(t){if(m||t instanceof ae||t instanceof G)return true;if(t instanceof De&&h.loopcontrol_target(t)===e)m=true}));e.walk(h);if(!m){var E=a[0].body.slice();var f=a[0].expression;if(f)E.unshift(make_node(G,f,{body:f}));E.unshift(make_node(G,e.expression,{body:e.expression}));return make_node(X,e,{body:E}).optimize(t)}}return e;function eliminate_branch(e,n){if(n&&!aborts(n)){n.body=n.body.concat(e.body)}else{trim_unreachable_code(t,e,o)}}}));def_optimize(Fe,(function(e,t){tighten_body(e.body,t);if(e.bcatch&&e.bfinally&&e.bfinally.body.every(is_empty))e.bfinally=null;if(t.option("dead_code")&&e.body.every(is_empty)){var n=[];if(e.bcatch){trim_unreachable_code(t,e.bcatch,n)}if(e.bfinally)n.push(...e.bfinally.body);return make_node(X,e,{body:n}).optimize(t)}return e}));xe.DEFMETHOD("remove_initializers",(function(){var e=[];this.definitions.forEach((function(t){if(t.name instanceof vt){t.value=null;e.push(t)}else{walk(t.name,(n=>{if(n instanceof vt){e.push(make_node(Pe,t,{name:n,value:null}))}}))}}));this.definitions=e}));xe.DEFMETHOD("to_assignments",(function(e){var t=e.option("reduce_vars");var n=[];for(const e of this.definitions){if(e.value){var r=make_node(It,e.name,e.name);n.push(make_node(et,e,{operator:"=",logical:false,left:r,right:e.value}));if(t)r.definition().fixed=false}else if(e.value){var i=make_node(Pe,e,{name:e.name,value:e.value});var o=make_node(Ne,e,{definitions:[i]});n.push(o)}const a=e.name.definition();a.eliminated++;a.replaced--}if(n.length==0)return null;return make_sequence(this,n)}));def_optimize(xe,(function(e){if(e.definitions.length==0)return make_node(W,e);return e}));def_optimize(Pe,(function(e,t){if(e.name instanceof At&&e.value!=null&&is_undefined(e.value,t)){e.value=null}return e}));def_optimize(Le,(function(e){return e}));function retain_top_func(e,t){return t.top_retain&&e instanceof ce&&has_flag(e,kn)&&e.name&&t.top_retain(e.name)}def_optimize(ze,(function(e,t){var n=e.expression;var r=n;inline_array_like_spread(e.args);var i=e.args.every((e=>!(e instanceof oe)));if(t.option("reduce_vars")&&r instanceof It&&!has_annotation(e,on)){const e=r.fixed_value();if(!retain_top_func(e,t)){r=e}}if(e.optional&&is_nullish(r,t)){return make_node(jt,e)}var o=r instanceof ae;if(o&&r.pinned())return e;if(t.option("unused")&&i&&o&&!r.uses_arguments){var a=0,s=0;for(var u=0,l=e.args.length;u=r.argnames.length;if(f||has_flag(r.argnames[u],gn)){var c=e.args[u].drop_side_effect_free(t);if(c){e.args[a++]=c}else if(!f){e.args[a++]=make_node(Gt,e.args[u],{value:0});continue}}else{e.args[a++]=e.args[u]}s=a}e.args.length=s}if(t.option("unsafe")){if(is_undeclared_ref(n))switch(n.name){case"Array":if(e.args.length!=1){return make_node(nt,e,{elements:e.args}).optimize(t)}else if(e.args[0]instanceof Gt&&e.args[0].value<=11){const t=[];for(let n=0;n=1&&e.args.length<=2&&e.args.every((e=>{var n=e.evaluate(t);_.push(n);return e!==n}))){let[n,r]=_;n=regexp_source_fix(new RegExp(n).source);const i=make_node(Xt,e,{value:{source:n,flags:r}});if(i._eval(t)!==i){return i}}break}else if(n instanceof Xe)switch(n.property){case"toString":if(e.args.length==0&&!n.expression.may_throw_on_access(t)){return make_node(Qe,e,{left:make_node(Kt,e,{value:""}),operator:"+",right:n.expression}).optimize(t)}break;case"join":if(n.expression instanceof nt)e:{var p;if(e.args.length>0){p=e.args[0].evaluate(t);if(p===e.args[0])break e}var d=[];var m=[];for(var u=0,l=n.expression.elements.length;u0){d.push(make_node(Kt,e,{value:m.join(p)}));m.length=0}d.push(h)}}if(m.length>0){d.push(make_node(Kt,e,{value:m.join(p)}))}if(d.length==0)return make_node(Kt,e,{value:""});if(d.length==1){if(d[0].is_string(t)){return d[0]}return make_node(Qe,d[0],{operator:"+",left:make_node(Kt,e,{value:""}),right:d[0]})}if(p==""){var g;if(d[0].is_string(t)||d[1].is_string(t)){g=d.shift()}else{g=make_node(Kt,e,{value:""})}return d.reduce((function(e,t){return make_node(Qe,t,{operator:"+",left:e,right:t})}),g).optimize(t)}var c=e.clone();c.expression=c.expression.clone();c.expression.expression=c.expression.expression.clone();c.expression.expression.elements=d;return best_of(t,e,c)}break;case"charAt":if(n.expression.is_string(t)){var v=e.args[0];var D=v?v.evaluate(t):0;if(D!==v){return make_node(qe,n,{expression:n.expression,property:make_node_from_constant(D|0,v||n)}).optimize(t)}}break;case"apply":if(e.args.length==2&&e.args[1]instanceof nt){var b=e.args[1].elements.slice();b.unshift(e.args[0]);return make_node(ze,e,{expression:make_node(Xe,n,{expression:n.expression,optional:false,property:"call"}),args:b}).optimize(t)}break;case"call":var S=n.expression;if(S instanceof It){S=S.fixed_value()}if(S instanceof ae&&!S.contains_this()){return(e.args.length?make_sequence(this,[e.args[0],make_node(ze,e,{expression:n.expression,args:e.args.slice(1)})]):make_node(ze,e,{expression:n.expression,args:[]})).optimize(t)}break}}if(t.option("unsafe_Function")&&is_undeclared_ref(n)&&n.name=="Function"){if(e.args.length==0)return make_node(ue,e,{argnames:[],body:[]}).optimize(t);if(e.args.every((e=>e instanceof Kt))){try{var A="n(function("+e.args.slice(0,-1).map((function(e){return e.value})).join(",")+"){"+e.args[e.args.length-1].value+"})";var y=parse(A);var T={ie8:t.option("ie8")};y.figure_out_scope(T);var k=new Compressor(t.options,{mangle_options:t.mangle_options});y=y.transform(k);y.figure_out_scope(T);hn.reset();y.compute_char_frequency(T);y.mangle_names(T);var C;walk(y,(e=>{if(is_func_expr(e)){C=e;return tn}}));var A=OutputStream();X.prototype._codegen.call(C,C,A);e.args=[make_node(Kt,e,{value:C.argnames.map((function(e){return e.print_to_string()})).join(",")}),make_node(Kt,e.args[e.args.length-1],{value:A.get().replace(/^{|}$/g,"")})];return e}catch(e){if(!(e instanceof JS_Parse_Error)){throw e}}}}var R=o&&r.body[0];var F=o&&!r.is_generator&&!r.async;var O=F&&t.option("inline")&&!e.is_callee_pure(t);if(O&&R instanceof Ee){let n=R.value;if(!n||n.is_constant_expression()){if(n){n=n.clone(true)}else{n=make_node(jt,e)}const r=e.args.concat(n);return make_sequence(e,r).optimize(t)}if(r.argnames.length===1&&r.argnames[0]instanceof yt&&e.args.length<2&&n instanceof It&&n.name===r.argnames[0].name){const n=(e.args[0]||make_node(jt)).optimize(t);let r;if(n instanceof He&&(r=t.parent())instanceof ze&&r.expression===e){return make_sequence(e,[make_node(Gt,e,{value:0}),n])}return n}}if(O){var M,x,N=-1;let o;let a;let s;if(i&&!r.uses_arguments&&!(t.parent()instanceof _t)&&!(r.name&&r instanceof ue)&&(a=can_flatten_body(R))&&(n===r||has_annotation(e,rn)||t.option("unused")&&(o=n.definition()).references.length==1&&!recursive_ref(t,o)&&r.is_constant_expression(n.scope))&&!has_annotation(e,nn|on)&&!r.contains_this()&&can_inject_symbols()&&(s=find_scope(t))&&!scope_encloses_variables_in_this_scope(s,r)&&!function in_default_assign(){let e=0;let n;while(n=t.parent(e++)){if(n instanceof tt)return true;if(n instanceof H)break}return false}()&&!(M instanceof _t)){set_flag(r,yn);s.add_child_scope(r);return make_sequence(e,flatten_fn(a)).optimize(t)}}if(O&&has_annotation(e,rn)){set_flag(r,yn);r=make_node(r.CTOR===ce?ue:r.CTOR,r,r);r.figure_out_scope({},{parent_scope:find_scope(t),toplevel:t.get_toplevel()});return make_node(ze,e,{expression:r,args:e.args}).optimize(t)}const w=F&&t.option("side_effects")&&r.body.every(is_empty);if(w){var b=e.args.concat(make_node(jt,e));return make_sequence(e,b).optimize(t)}if(t.option("negate_iife")&&t.parent()instanceof G&&is_iife_call(e)){return e.negate(t,true)}var I=e.evaluate(t);if(I!==e){I=make_node_from_constant(I,e).optimize(t);return best_of(t,I,e)}return e;function return_value(t){if(!t)return make_node(jt,e);if(t instanceof Ee){if(!t.value)return make_node(jt,e);return t.value.clone(true)}if(t instanceof G){return make_node($e,t,{operator:"void",expression:t.body.clone(true)})}}function can_flatten_body(e){var n=r.body;var i=n.length;if(t.option("inline")<3){return i==1&&return_value(e)}e=null;for(var o=0;o!e.value))){return false}}else if(e){return false}else if(!(a instanceof W)){e=a}}return return_value(e)}function can_inject_args(e,t){for(var n=0,i=r.argnames.length;n=0;){var s=o.definitions[a].name;if(s instanceof fe||e.has(s.name)||Fn.has(s.name)||M.conflicting_def(s.name)){return false}if(x)x.push(s.definition())}}return true}function can_inject_symbols(){var e=new Set;do{M=t.parent(++N);if(M.is_block_scope()&&M.block_scope){M.block_scope.variables.forEach((function(t){e.add(t.name)}))}if(M instanceof Oe){if(M.argname){e.add(M.argname.name)}}else if(M instanceof j){x=[]}else if(M instanceof It){if(M.fixed_value()instanceof re)return false}}while(!(M instanceof re));var n=!(M instanceof ie)||t.toplevel.vars;var i=t.option("inline");if(!can_inject_vars(e,i>=3&&n))return false;if(!can_inject_args(e,i>=2&&n))return false;return!x||x.length==0||!is_reachable(r,x)}function append_var(t,n,r,i){var o=r.definition();const a=M.variables.has(r.name);if(!a){M.variables.set(r.name,o);M.enclosed.push(o);t.push(make_node(Pe,r,{name:r,value:null}))}var s=make_node(It,r,r);o.references.push(s);if(i)n.push(make_node(et,e,{operator:"=",logical:false,left:s,right:i.clone()}))}function flatten_args(t,n){var i=r.argnames.length;for(var o=e.args.length;--o>=i;){n.push(e.args[o])}for(o=i;--o>=0;){var a=r.argnames[o];var s=e.args[o];if(has_flag(a,gn)||!a.name||M.conflicting_def(a.name)){if(s)n.push(s)}else{var u=make_node(Dt,a,a);a.definition().orig.push(u);if(!s&&x)s=make_node(jt,e);append_var(t,n,u,s)}}t.reverse();n.reverse()}function flatten_vars(e,t){var n=t.length;for(var i=0,o=r.body.length;ie.name!=c.name))){var f=r.variables.get(c.name);var _=make_node(It,c,c);f.references.push(_);t.splice(n++,0,make_node(et,l,{operator:"=",logical:false,left:_,right:make_node(jt,c)}))}}}}function flatten_fn(e){var n=[];var i=[];flatten_args(n,i);flatten_vars(n,i);i.push(e);if(n.length){const e=M.body.indexOf(t.parent(N-1))+1;M.body.splice(e,0,make_node(Ne,r,{definitions:n}))}return i.map((e=>e.clone(true)))}}));def_optimize(Ke,(function(e,t){if(t.option("unsafe")&&is_undeclared_ref(e.expression)&&["Object","RegExp","Function","Error","Array"].includes(e.expression.name))return make_node(ze,e,e).transform(t);return e}));def_optimize(Ge,(function(e,t){if(!t.option("side_effects"))return e;var n=[];filter_for_side_effects();var r=n.length-1;trim_right_for_undefined();if(r==0){e=maintain_this_binding(t.parent(),t.self(),n[0]);if(!(e instanceof Ge))e=e.optimize(t);return e}e.expressions=n;return e;function filter_for_side_effects(){var r=first_in_statement(t);var i=e.expressions.length-1;e.expressions.forEach((function(e,o){if(o0&&is_undefined(n[r],t))r--;if(r0){var n=this.clone();n.right=make_sequence(this.right,t.slice(o));t=t.slice(0,o);t.push(n);return make_sequence(this,t).optimize(e)}}}return this}));var Vn=makePredicate("== === != !== * & | ^");function is_object(e){return e instanceof nt||e instanceof ae||e instanceof rt||e instanceof _t}def_optimize(Qe,(function(e,t){function reversible(){return e.left.is_constant()||e.right.is_constant()||!e.left.has_side_effects(t)&&!e.right.has_side_effects(t)}function reverse(t){if(reversible()){if(t)e.operator=t;var n=e.left;e.left=e.right;e.right=n}}if(Vn.has(e.operator)){if(e.right.is_constant()&&!e.left.is_constant()){if(!(e.left instanceof Qe&&w[e.left.operator]>=w[e.operator])){reverse()}}}e=e.lift_sequences(t);if(t.option("comparisons"))switch(e.operator){case"===":case"!==":var n=true;if(e.left.is_string(t)&&e.right.is_string(t)||e.left.is_number(t)&&e.right.is_number(t)||e.left.is_boolean()&&e.right.is_boolean()||e.left.equivalent_to(e.right)){e.operator=e.operator.substr(0,2)}case"==":case"!=":if(!n&&is_undefined(e.left,t)){e.left=make_node(qt,e.left)}else if(t.option("typeofs")&&e.left instanceof Kt&&e.left.value=="undefined"&&e.right instanceof $e&&e.right.operator=="typeof"){var r=e.right.expression;if(r instanceof It?r.is_declared(t):!(r instanceof He&&t.option("ie8"))){e.right=r;e.left=make_node(jt,e.left).optimize(t);if(e.operator.length==2)e.operator+="="}}else if(e.left instanceof It&&e.right instanceof It&&e.left.definition()===e.right.definition()&&is_object(e.left.fixed_value())){return make_node(e.operator[0]=="="?en:Jt,e)}break;case"&&":case"||":var i=e.left;if(i.operator==e.operator){i=i.right}if(i instanceof Qe&&i.operator==(e.operator=="&&"?"!==":"===")&&e.right instanceof Qe&&i.operator==e.right.operator&&(is_undefined(i.left,t)&&e.right.left instanceof qt||i.left instanceof qt&&is_undefined(e.right.left,t))&&!i.right.has_side_effects(t)&&i.right.equivalent_to(e.right.right)){var o=make_node(Qe,e,{operator:i.operator.slice(0,-1),left:make_node(qt,e),right:i.right});if(i!==e.left){o=make_node(Qe,e,{operator:e.operator,left:e.left.left,right:o})}return o}break}if(e.operator=="+"&&t.in_boolean_context()){var a=e.left.evaluate(t);var s=e.right.evaluate(t);if(a&&typeof a=="string"){return make_sequence(e,[e.right,make_node(en,e)]).optimize(t)}if(s&&typeof s=="string"){return make_sequence(e,[e.left,make_node(en,e)]).optimize(t)}}if(t.option("comparisons")&&e.is_boolean()){if(!(t.parent()instanceof Qe)||t.parent()instanceof et){var u=make_node($e,e,{operator:"!",expression:e.negate(t,first_in_statement(t))});e=best_of(t,e,u)}if(t.option("unsafe_comps")){switch(e.operator){case"<":reverse(">");break;case"<=":reverse(">=");break}}}if(e.operator=="+"){if(e.right instanceof Kt&&e.right.getValue()==""&&e.left.is_string(t)){return e.left}if(e.left instanceof Kt&&e.left.getValue()==""&&e.right.is_string(t)){return e.right}if(e.left instanceof Qe&&e.left.operator=="+"&&e.left.left instanceof Kt&&e.left.left.getValue()==""&&e.right.is_string(t)){e.left=e.left.right;return e}}if(t.option("evaluate")){switch(e.operator){case"&&":var a=has_flag(e.left,vn)?true:has_flag(e.left,Dn)?false:e.left.evaluate(t);if(!a){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}else if(!(a instanceof V)){return make_sequence(e,[e.left,e.right]).optimize(t)}var s=e.right.evaluate(t);if(!s){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(Jt,e)]).optimize(t)}else{set_flag(e,Dn)}}else if(!(s instanceof V)){var l=t.parent();if(l.operator=="&&"&&l.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}if(e.left.operator=="||"){var c=e.left.right.evaluate(t);if(!c)return make_node(Je,e,{condition:e.left.left,consequent:e.right,alternative:e.left.right}).optimize(t)}break;case"||":var a=has_flag(e.left,vn)?true:has_flag(e.left,Dn)?false:e.left.evaluate(t);if(!a){return make_sequence(e,[e.left,e.right]).optimize(t)}else if(!(a instanceof V)){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}var s=e.right.evaluate(t);if(!s){var l=t.parent();if(l.operator=="||"&&l.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}else if(!(s instanceof V)){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(en,e)]).optimize(t)}else{set_flag(e,vn)}}if(e.left.operator=="&&"){var c=e.left.right.evaluate(t);if(c&&!(c instanceof V))return make_node(Je,e,{condition:e.left.left,consequent:e.left.right,alternative:e.right}).optimize(t)}break;case"??":if(is_nullish(e.left,t)){return e.right}var a=e.left.evaluate(t);if(!(a instanceof V)){return a==null?e.right:e.left}if(t.in_boolean_context()){const n=e.right.evaluate(t);if(!(n instanceof V)&&!n){return e.left}}}var f=true;switch(e.operator){case"+":if(e.right instanceof zt&&e.left instanceof Qe&&e.left.operator=="+"&&e.left.is_string(t)){var _=make_node(Qe,e,{operator:"+",left:e.left.right,right:e.right});var p=_.optimize(t);if(_!==p){e=make_node(Qe,e,{operator:"+",left:e.left.left,right:p})}}if(e.left instanceof Qe&&e.left.operator=="+"&&e.left.is_string(t)&&e.right instanceof Qe&&e.right.operator=="+"&&e.right.is_string(t)){var _=make_node(Qe,e,{operator:"+",left:e.left.right,right:e.right.left});var d=_.optimize(t);if(_!==d){e=make_node(Qe,e,{operator:"+",left:make_node(Qe,e.left,{operator:"+",left:e.left.left,right:d}),right:e.right.right})}}if(e.right instanceof $e&&e.right.operator=="-"&&e.left.is_number(t)){e=make_node(Qe,e,{operator:"-",left:e.left,right:e.right.expression});break}if(e.left instanceof $e&&e.left.operator=="-"&&reversible()&&e.right.is_number(t)){e=make_node(Qe,e,{operator:"-",left:e.right,right:e.left.expression});break}if(e.left instanceof pe){var m=e.left;var p=e.right.evaluate(t);if(p!=e.right){m.segments[m.segments.length-1].value+=String(p);return m}}if(e.right instanceof pe){var p=e.right;var m=e.left.evaluate(t);if(m!=e.left){p.segments[0].value=String(m)+p.segments[0].value;return p}}if(e.left instanceof pe&&e.right instanceof pe){var m=e.left;var h=m.segments;var p=e.right;h[h.length-1].value+=p.segments[0].value;for(var E=1;E=w[e.operator])){var g=make_node(Qe,e,{operator:e.operator,left:e.right,right:e.left});if(e.right instanceof zt&&!(e.left instanceof zt)){e=best_of(t,g,e)}else{e=best_of(t,e,g)}}if(f&&e.is_number(t)){if(e.right instanceof Qe&&e.right.operator==e.operator){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left,right:e.right.left,start:e.left.start,end:e.right.left.end}),right:e.right.right})}if(e.right instanceof zt&&e.left instanceof Qe&&e.left.operator==e.operator){if(e.left.left instanceof zt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left.left,right:e.right,start:e.left.left.start,end:e.right.end}),right:e.left.right})}else if(e.left.right instanceof zt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:e.left.right,right:e.right,start:e.left.right.start,end:e.right.end}),right:e.left.left})}}if(e.left instanceof Qe&&e.left.operator==e.operator&&e.left.right instanceof zt&&e.right instanceof Qe&&e.right.operator==e.operator&&e.right.left instanceof zt){e=make_node(Qe,e,{operator:e.operator,left:make_node(Qe,e.left,{operator:e.operator,left:make_node(Qe,e.left.left,{operator:e.operator,left:e.left.right,right:e.right.left,start:e.left.right.start,end:e.right.left.end}),right:e.left.left}),right:e.right.right})}}}}if(e.right instanceof Qe&&e.right.operator==e.operator&&(On.has(e.operator)||e.operator=="+"&&(e.right.left.is_string(t)||e.left.is_string(t)&&e.right.right.is_string(t)))){e.left=make_node(Qe,e.left,{operator:e.operator,left:e.left.transform(t),right:e.right.left.transform(t)});e.right=e.right.right.transform(t);return e.transform(t)}var v=e.evaluate(t);if(v!==e){v=make_node_from_constant(v,e).optimize(t);return best_of(t,v,e)}return e}));def_optimize(Pt,(function(e){return e}));function recursive_ref(e,t){var n;for(var r=0;n=e.parent(r);r++){if(n instanceof ae||n instanceof _t){var i=n.name;if(i&&i.definition()===t)break}}return n}function within_array_or_object_literal(e){var t,n=0;while(t=e.parent(n++)){if(t instanceof U)return false;if(t instanceof nt||t instanceof ot||t instanceof rt){return true}}return false}def_optimize(It,(function(e,t){if(!t.option("ie8")&&is_undeclared_ref(e)&&!t.find_parent(ne)){switch(e.name){case"undefined":return make_node(jt,e).optimize(t);case"NaN":return make_node(Yt,e).optimize(t);case"Infinity":return make_node(Zt,e).optimize(t)}}const n=t.parent();if(t.option("reduce_vars")&&is_lhs(e,n)!==e){const o=e.definition();const a=find_scope(t);if(t.top_retain&&o.global&&t.top_retain(o)){o.fixed=false;o.single_use=false;return e}let s=e.fixed_value();let u=o.single_use&&!(n instanceof ze&&n.is_callee_pure(t)||has_annotation(n,on))&&!(n instanceof Ue&&s instanceof ae&&s.name);if(u&&s instanceof V){u=!s.has_side_effects(t)&&!s.may_throw(t)}if(u&&(s instanceof ae||s instanceof _t)){if(retain_top_func(s,t)){u=false}else if(o.scope!==e.scope&&(o.escaped==1||has_flag(s,Sn)||within_array_or_object_literal(t)||!t.option("reduce_funcs"))){u=false}else if(recursive_ref(t,o)){u=false}else if(o.scope!==e.scope||o.orig[0]instanceof yt){u=s.is_constant_expression(e.scope);if(u=="f"){var r=e.scope;do{if(r instanceof ce||is_func_expr(r)){set_flag(r,Sn)}}while(r=r.parent_scope)}}}if(u&&s instanceof ae){u=o.scope===e.scope&&!scope_encloses_variables_in_this_scope(a,s)||n instanceof ze&&n.expression===e&&!scope_encloses_variables_in_this_scope(a,s)&&!(s.name&&s.name.definition().recursive_refs>0)}if(u&&s){if(s instanceof mt){set_flag(s,yn);s=make_node(ht,s,s)}if(s instanceof ce){set_flag(s,yn);s=make_node(ue,s,s)}if(o.recursive_refs>0&&s.name instanceof Tt){const e=s.name.definition();let t=s.variables.get(s.name.name);let n=t&&t.orig[0];if(!(n instanceof Rt)){n=make_node(Rt,s.name,s.name);n.scope=s;s.name=n;t=s.def_function(n)}walk(s,(n=>{if(n instanceof It&&n.definition()===e){n.thedef=t;t.references.push(n)}}))}if((s instanceof ae||s instanceof _t)&&s.parent_scope!==a){s=s.clone(true,t.get_toplevel());a.add_child_scope(s)}return s.optimize(t)}if(s){let n;if(s instanceof Vt){if(!(o.orig[0]instanceof yt)&&o.references.every((e=>o.scope===e.scope))){n=s}}else{var i=s.evaluate(t);if(i!==s&&(t.option("unsafe_regexp")||!(i instanceof RegExp))){n=make_node_from_constant(i,s)}}if(n){const r=e.size(t);const i=n.size(t);let a=0;if(t.option("unused")&&!t.exposed(o)){a=(r+2+i)/(o.references.length-o.assignments)}if(i<=r+a){return n}}}}return e}));function scope_encloses_variables_in_this_scope(e,t){for(const n of t.enclosed){if(t.variables.has(n.name)){continue}const r=e.find_variable(n.name);if(r){if(r===n)continue;return true}}return false}function is_atomic(e,t){return e instanceof It||e.TYPE===t.TYPE}def_optimize(jt,(function(e,t){if(t.option("unsafe_undefined")){var n=find_variable(t,"undefined");if(n){var r=make_node(It,e,{name:"undefined",scope:n.scope,thedef:n});set_flag(r,bn);return r}}var i=is_lhs(t.self(),t.parent());if(i&&is_atomic(i,e))return e;return make_node($e,e,{operator:"void",expression:make_node(Gt,e,{value:0})})}));def_optimize(Zt,(function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&is_atomic(n,e))return e;if(t.option("keep_infinity")&&!(n&&!is_atomic(n,e))&&!find_variable(t,"Infinity")){return e}return make_node(Qe,e,{operator:"/",left:make_node(Gt,e,{value:1}),right:make_node(Gt,e,{value:0})})}));def_optimize(Yt,(function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&!is_atomic(n,e)||find_variable(t,"NaN")){return make_node(Qe,e,{operator:"/",left:make_node(Gt,e,{value:0}),right:make_node(Gt,e,{value:0})})}return e}));function is_reachable(e,t){const find_ref=e=>{if(e instanceof It&&member(e.definition(),t)){return tn}};return walk_parent(e,((t,n)=>{if(t instanceof re&&t!==e){var r=n.parent();if(r instanceof ze&&r.expression===t)return;if(walk(t,find_ref))return tn;return true}}))}const Un=makePredicate("+ - / * % >> << >>> | ^ &");const zn=makePredicate("* | ^ &");def_optimize(et,(function(e,t){if(e.logical){return e.lift_sequences(t)}var n;if(t.option("dead_code")&&e.left instanceof It&&(n=e.left.definition()).scope===t.find_parent(ae)){var r=0,i,o=e;do{i=o;o=t.parent(r++);if(o instanceof he){if(in_try(r,o))break;if(is_reachable(n.scope,[n]))break;if(e.operator=="=")return e.right;n.fixed=false;return make_node(Qe,e,{operator:e.operator.slice(0,-1),left:e.left,right:e.right}).optimize(t)}}while(o instanceof Qe&&o.right===i||o instanceof Ge&&o.tail_node()===i)}e=e.lift_sequences(t);if(e.operator=="="&&e.left instanceof It&&e.right instanceof Qe){if(e.right.left instanceof It&&e.right.left.name==e.left.name&&Un.has(e.right.operator)){e.operator=e.right.operator+"=";e.right=e.right.right}else if(e.right.right instanceof It&&e.right.right.name==e.left.name&&zn.has(e.right.operator)&&!e.right.left.has_side_effects(t)){e.operator=e.right.operator+"=";e.right=e.right.left}}return e;function in_try(n,r){var i=e.right;e.right=make_node(qt,i);var o=r.may_throw(t);e.right=i;var a=e.left.definition().scope;var s;while((s=t.parent(n++))!==a){if(s instanceof Fe){if(s.bfinally)return true;if(o&&s.bcatch)return true}}}}));def_optimize(tt,(function(e,t){if(!t.option("evaluate")){return e}var n=e.right.evaluate(t);if(n===undefined){e=e.left}else if(n!==e.right){n=make_node_from_constant(n,e.right);e.right=best_of_expression(n,e.right)}return e}));function is_nullish(e,t){let n;return e instanceof qt||is_undefined(e,t)||e instanceof It&&(n=e.definition().fixed)instanceof V&&is_nullish(n,t)||e instanceof He&&e.optional&&is_nullish(e.expression,t)||e instanceof ze&&e.optional&&is_nullish(e.expression,t)||e instanceof Ye&&is_nullish(e.expression,t)}function is_nullish_check(e,t,n){if(t.may_throw(n))return false;let r;if(e instanceof Qe&&e.operator==="=="&&((r=is_nullish(e.left,n)&&e.left)||(r=is_nullish(e.right,n)&&e.right))&&(r===e.left?e.right:e.left).equivalent_to(t)){return true}if(e instanceof Qe&&e.operator==="||"){let r;let i;const find_comparison=e=>{if(!(e instanceof Qe&&(e.operator==="==="||e.operator==="=="))){return false}let o=0;let a;if(e.left instanceof qt){o++;r=e;a=e.right}if(e.right instanceof qt){o++;r=e;a=e.left}if(is_undefined(e.left,n)){o++;i=e;a=e.right}if(is_undefined(e.right,n)){o++;i=e;a=e.left}if(o!==1){return false}if(!a.equivalent_to(t)){return false}return true};if(!find_comparison(e.left))return false;if(!find_comparison(e.right))return false;if(r&&i&&r!==i){return true}}return false}def_optimize(Je,(function(e,t){if(!t.option("conditionals"))return e;if(e.condition instanceof Ge){var n=e.condition.expressions.slice();e.condition=n.pop();n.push(e);return make_sequence(e,n)}var r=e.condition.evaluate(t);if(r!==e.condition){if(r){return maintain_this_binding(t.parent(),t.self(),e.consequent)}else{return maintain_this_binding(t.parent(),t.self(),e.alternative)}}var i=r.negate(t,first_in_statement(t));if(best_of(t,r,i)===i){e=make_node(Je,e,{condition:i,consequent:e.alternative,alternative:e.consequent})}var o=e.condition;var a=e.consequent;var s=e.alternative;if(o instanceof It&&a instanceof It&&o.definition()===a.definition()){return make_node(Qe,e,{operator:"||",left:o,right:s})}if(a instanceof et&&s instanceof et&&a.operator===s.operator&&a.logical===s.logical&&a.left.equivalent_to(s.left)&&(!e.condition.has_side_effects(t)||a.operator=="="&&!a.left.has_side_effects(t))){return make_node(et,e,{operator:a.operator,left:a.left,logical:a.logical,right:make_node(Je,e,{condition:e.condition,consequent:a.right,alternative:s.right})})}var u;if(a instanceof ze&&s.TYPE===a.TYPE&&a.args.length>0&&a.args.length==s.args.length&&a.expression.equivalent_to(s.expression)&&!e.condition.has_side_effects(t)&&!a.expression.has_side_effects(t)&&typeof(u=single_arg_diff())=="number"){var l=a.clone();l.args[u]=make_node(Je,e,{condition:e.condition,consequent:a.args[u],alternative:s.args[u]});return l}if(s instanceof Je&&a.equivalent_to(s.consequent)){return make_node(Je,e,{condition:make_node(Qe,e,{operator:"||",left:o,right:s.condition}),consequent:a,alternative:s.alternative}).optimize(t)}if(t.option("ecma")>=2020&&is_nullish_check(o,s,t)){return make_node(Qe,e,{operator:"??",left:s,right:a}).optimize(t)}if(s instanceof Ge&&a.equivalent_to(s.expressions[s.expressions.length-1])){return make_sequence(e,[make_node(Qe,e,{operator:"||",left:o,right:make_sequence(e,s.expressions.slice(0,-1))}),a]).optimize(t)}if(s instanceof Qe&&s.operator=="&&"&&a.equivalent_to(s.right)){return make_node(Qe,e,{operator:"&&",left:make_node(Qe,e,{operator:"||",left:o,right:s.left}),right:a}).optimize(t)}if(a instanceof Je&&a.alternative.equivalent_to(s)){return make_node(Je,e,{condition:make_node(Qe,e,{left:e.condition,operator:"&&",right:a.condition}),consequent:a.consequent,alternative:s})}if(a.equivalent_to(s)){return make_sequence(e,[e.condition,a]).optimize(t)}if(a instanceof Qe&&a.operator=="||"&&a.right.equivalent_to(s)){return make_node(Qe,e,{operator:"||",left:make_node(Qe,e,{operator:"&&",left:e.condition,right:a.left}),right:s}).optimize(t)}var c=t.in_boolean_context();if(is_true(e.consequent)){if(is_false(e.alternative)){return booleanize(e.condition)}return make_node(Qe,e,{operator:"||",left:booleanize(e.condition),right:e.alternative})}if(is_false(e.consequent)){if(is_true(e.alternative)){return booleanize(e.condition.negate(t))}return make_node(Qe,e,{operator:"&&",left:booleanize(e.condition.negate(t)),right:e.alternative})}if(is_true(e.alternative)){return make_node(Qe,e,{operator:"||",left:booleanize(e.condition.negate(t)),right:e.consequent})}if(is_false(e.alternative)){return make_node(Qe,e,{operator:"&&",left:booleanize(e.condition),right:e.consequent})}return e;function booleanize(e){if(e.is_boolean())return e;return make_node($e,e,{operator:"!",expression:e.negate(t)})}function is_true(e){return e instanceof en||c&&e instanceof zt&&e.getValue()||e instanceof $e&&e.operator=="!"&&e.expression instanceof zt&&!e.expression.getValue()}function is_false(e){return e instanceof Jt||c&&e instanceof zt&&!e.getValue()||e instanceof $e&&e.operator=="!"&&e.expression instanceof zt&&e.expression.getValue()}function single_arg_diff(){var e=a.args;var t=s.args;for(var n=0,r=e.length;n=2015;var r=this.expression;if(r instanceof rt){var i=r.properties;for(var o=i.length;--o>=0;){var a=i[o];if(""+(a instanceof ct?a.key.name:a.key)==e){const e=i.every((e=>(e instanceof ot||n&&e instanceof ct&&!e.is_generator)&&!e.computed_key()));if(!e)return;if(!safe_to_flatten(a.value,t))return;return make_node(qe,this,{expression:make_node(nt,r,{elements:i.map((function(e){var t=e.value;if(t instanceof se){t=make_node(ue,t,t)}var n=e.key;if(n instanceof V&&!(n instanceof kt)){return make_sequence(e,[n,t])}return t}))}),property:make_node(Gt,this,{value:o})})}}}}));def_optimize(qe,(function(e,t){var n=e.expression;var r=e.property;if(t.option("properties")){var i=r.evaluate(t);if(i!==r){if(typeof i=="string"){if(i=="undefined"){i=undefined}else{var o=parseFloat(i);if(o.toString()==i){i=o}}}r=e.property=best_of_expression(r,make_node_from_constant(i,r).transform(t));var a=""+i;if(is_basic_identifier_string(a)&&a.length<=r.size()+1){return make_node(Xe,e,{expression:n,optional:e.optional,property:a,quote:r.quote}).optimize(t)}}}var s;e:if(t.option("arguments")&&n instanceof It&&n.name=="arguments"&&n.definition().orig.length==1&&(s=n.scope)instanceof ae&&s.uses_arguments&&!(s instanceof le)&&r instanceof Gt){var u=r.getValue();var l=new Set;var c=s.argnames;for(var f=0;f1){p=null}}else if(!p&&!t.option("keep_fargs")&&u=s.argnames.length){p=s.create_symbol(yt,{source:s,scope:s,tentative_name:"argument_"+s.argnames.length});s.argnames.push(p)}}if(p){var m=make_node(It,e,p);m.reference({});clear_flag(p,gn);return m}}if(is_lhs(e,t.parent()))return e;if(i!==r){var h=e.flatten_object(a,t);if(h){n=e.expression=h.expression;r=e.property=h.property}}if(t.option("properties")&&t.option("side_effects")&&r instanceof Gt&&n instanceof nt){var u=r.getValue();var E=n.elements;var g=E[u];e:if(safe_to_flatten(g,t)){var v=true;var D=[];for(var b=E.length;--b>u;){var o=E[b].drop_side_effect_free(t);if(o){D.unshift(o);if(v&&o.has_side_effects(t))v=false}}if(g instanceof oe)break e;g=g instanceof $t?make_node(jt,g):g;if(!v)D.unshift(g);while(--b>=0){var o=E[b];if(o instanceof oe)break e;o=o.drop_side_effect_free(t);if(o)D.unshift(o);else u--}if(v){D.push(g);return make_sequence(e,D).optimize(t)}else return make_node(qe,e,{expression:make_node(nt,n,{elements:D}),property:make_node(Gt,r,{value:u})})}}var S=e.evaluate(t);if(S!==e){S=make_node_from_constant(S,e).optimize(t);return best_of(t,S,e)}if(e.optional&&is_nullish(e.expression,t)){return make_node(jt,e)}return e}));def_optimize(Ye,(function(e,t){e.expression=e.expression.optimize(t);return e}));ae.DEFMETHOD("contains_this",(function(){return walk(this,(e=>{if(e instanceof Vt)return tn;if(e!==this&&e instanceof re&&!(e instanceof le)){return true}}))}));def_optimize(Xe,(function(e,t){const n=t.parent();if(is_lhs(e,n))return e;if(t.option("unsafe_proto")&&e.expression instanceof Xe&&e.expression.property=="prototype"){var r=e.expression.expression;if(is_undeclared_ref(r))switch(r.name){case"Array":e.expression=make_node(nt,e.expression,{elements:[]});break;case"Function":e.expression=make_node(ue,e.expression,{argnames:[],body:[]});break;case"Number":e.expression=make_node(Gt,e.expression,{value:0});break;case"Object":e.expression=make_node(rt,e.expression,{properties:[]});break;case"RegExp":e.expression=make_node(Xt,e.expression,{value:{source:"t",flags:""}});break;case"String":e.expression=make_node(Kt,e.expression,{value:""});break}}if(!(n instanceof ze)||!has_annotation(n,on)){const n=e.flatten_object(e.property,t);if(n)return n.optimize(t)}let i=e.evaluate(t);if(i!==e){i=make_node_from_constant(i,e).optimize(t);return best_of(t,i,e)}if(e.optional&&is_nullish(e.expression,t)){return make_node(jt,e)}return e}));function literals_in_boolean_context(e,t){if(t.in_boolean_context()){return best_of(t,e,make_sequence(e,[e,make_node(en,e)]).optimize(t))}return e}function inline_array_like_spread(e){for(var t=0;te instanceof $t))){e.splice(t,1,...r.elements);t--}}}}def_optimize(nt,(function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_array_like_spread(e.elements);return e}));function inline_object_prop_spread(e,t){for(var n=0;ne instanceof ot))){e.splice(n,1,...i.properties);n--}else if(i instanceof zt&&!(i instanceof Kt)){e.splice(n,1)}else if(is_nullish(i,t)){e.splice(n,1)}}}}def_optimize(rt,(function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_object_prop_spread(e.properties,t);return e}));def_optimize(Xt,literals_in_boolean_context);def_optimize(Ee,(function(e,t){if(e.value&&is_undefined(e.value,t)){e.value=null}return e}));def_optimize(le,opt_AST_Lambda);def_optimize(ue,(function(e,t){e=opt_AST_Lambda(e,t);if(t.option("unsafe_arrows")&&t.option("ecma")>=2015&&!e.name&&!e.is_generator&&!e.uses_arguments&&!e.pinned()){const n=walk(e,(e=>{if(e instanceof Vt)return tn}));if(!n)return make_node(le,e,e).optimize(t)}return e}));def_optimize(_t,(function(e){return e}));def_optimize(Ae,(function(e,t){if(e.expression&&!e.is_star&&is_undefined(e.expression,t)){e.expression=null}return e}));def_optimize(pe,(function(e,t){if(!t.option("evaluate")||t.parent()instanceof _e){return e}var n=[];for(var r=0;r=2015&&(!(n instanceof RegExp)||n.test(e.key+""))){var r=e.key;var i=e.value;var o=i instanceof le&&Array.isArray(i.body)&&!i.contains_this();if((o||i instanceof ue)&&!i.name){return make_node(ct,e,{async:i.async,is_generator:i.is_generator,key:r instanceof V?r:make_node(kt,e,{name:r}),value:make_node(se,i,i),quote:e.quote})}}return e}));def_optimize(fe,(function(e,t){if(t.option("pure_getters")==true&&t.option("unused")&&!e.is_array&&Array.isArray(e.names)&&!is_destructuring_export_decl(t)&&!(e.names[e.names.length-1]instanceof oe)){var n=[];for(var r=0;r1)throw new Error("inline source map only works with singular input");t.sourceMap.content=read_source_map(e[o])}}}i=t.parse.toplevel}if(r&&t.mangle.properties.keep_quoted!=="strict"){reserve_quoted_keys(i,r)}if(t.wrap){i=i.wrap_commonjs(t.wrap)}if(t.enclose){i=i.wrap_enclose(t.enclose)}if(n)n.rename=Date.now();if(n)n.compress=Date.now();if(t.compress){i=new Compressor(t.compress,{mangle_options:t.mangle}).compress(i)}if(n)n.scope=Date.now();if(t.mangle)i.figure_out_scope(t.mangle);if(n)n.mangle=Date.now();if(t.mangle){hn.reset();i.compute_char_frequency(t.mangle);i.mangle_names(t.mangle)}if(n)n.properties=Date.now();if(t.mangle&&t.mangle.properties){i=mangle_properties(i,t.mangle.properties)}if(n)n.format=Date.now();var a={};if(t.format.ast){a.ast=i}if(t.format.spidermonkey){a.ast=i.to_mozilla_ast()}if(!HOP(t.format,"code")||t.format.code){if(t.sourceMap){t.format.source_map=await SourceMap({file:t.sourceMap.filename,orig:t.sourceMap.content,root:t.sourceMap.root});if(t.sourceMap.includeSources){if(e instanceof ie){throw new Error("original source content unavailable")}else for(var o in e)if(HOP(e,o)){t.format.source_map.get().setSourceContent(o,e[o])}}}delete t.format.ast;delete t.format.code;delete t.format.spidermonkey;var s=OutputStream(t.format);i.print(s);a.code=s.get();if(t.sourceMap){if(t.sourceMap.asObject){a.map=t.format.source_map.get().toJSON()}else{a.map=t.format.source_map.toString()}if(t.sourceMap.url=="inline"){var u=typeof a.map==="object"?JSON.stringify(a.map):a.map;a.code+="\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,"+Hn(u)}else if(t.sourceMap.url){a.code+="\n//# sourceMappingURL="+t.sourceMap.url}}}if(t.nameCache&&t.mangle){if(t.mangle.cache)t.nameCache.vars=cache_to_json(t.mangle.cache);if(t.mangle.properties&&t.mangle.properties.cache){t.nameCache.props=cache_to_json(t.mangle.properties.cache)}}if(t.format&&t.format.source_map){t.format.source_map.destroy()}if(n){n.end=Date.now();a.timings={parse:.001*(n.rename-n.parse),rename:.001*(n.compress-n.rename),compress:.001*(n.scope-n.compress),scope:.001*(n.mangle-n.scope),mangle:.001*(n.properties-n.mangle),properties:.001*(n.format-n.properties),format:.001*(n.end-n.format),total:.001*(n.end-n.start)}}return a}async function run_cli({program:e,packageJson:t,fs:r,path:i}){const o=new Set(["cname","parent_scope","scope","uses_eval","uses_with"]);var a={};var s={compress:false,mangle:false};const u=await _default_options();e.version(t.name+" "+t.version);e.parseArgv=e.parse;e.parse=undefined;if(process.argv.includes("ast"))e.helpInformation=describe_ast;else if(process.argv.includes("options"))e.helpInformation=function(){var e=[];for(var t in u){e.push("--"+(t==="sourceMap"?"source-map":t)+" options:");e.push(format_object(u[t]));e.push("")}return e.join("\n")};e.option("-p, --parse ","Specify parser options.",parse_js());e.option("-c, --compress [options]","Enable compressor/specify compressor options.",parse_js());e.option("-m, --mangle [options]","Mangle names/specify mangler options.",parse_js());e.option("--mangle-props [options]","Mangle properties/specify mangler options.",parse_js());e.option("-f, --format [options]","Format options.",parse_js());e.option("-b, --beautify [options]","Alias for --format.",parse_js());e.option("-o, --output ","Output file (default STDOUT).");e.option("--comments [filter]","Preserve copyright comments in the output.");e.option("--config-file ","Read minify() options from JSON file.");e.option("-d, --define [=value]","Global definitions.",parse_js("define"));e.option("--ecma ","Specify ECMAScript release: 5, 2015, 2016 or 2017...");e.option("-e, --enclose [arg[,...][:value[,...]]]","Embed output in a big function with configurable arguments and values.");e.option("--ie8","Support non-standard Internet Explorer 8.");e.option("--keep-classnames","Do not mangle/drop class names.");e.option("--keep-fnames","Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");e.option("--module","Input is an ES6 module");e.option("--name-cache ","File to hold mangled name mappings.");e.option("--rename","Force symbol expansion.");e.option("--no-rename","Disable symbol expansion.");e.option("--safari10","Support non-standard Safari 10.");e.option("--source-map [options]","Enable source map/specify source map options.",parse_js());e.option("--timings","Display operations run time on STDERR.");e.option("--toplevel","Compress and/or mangle variables in toplevel scope.");e.option("--wrap ","Embed everything as a function with “exports” corresponding to “name” globally.");e.arguments("[files...]").parseArgv(process.argv);if(e.configFile){s=JSON.parse(read_file(e.configFile))}if(!e.output&&e.sourceMap&&e.sourceMap.url!="inline"){fatal("ERROR: cannot write source map to STDOUT")}["compress","enclose","ie8","mangle","module","safari10","sourceMap","toplevel","wrap"].forEach((function(t){if(t in e){s[t]=e[t]}}));if("ecma"in e){if(e.ecma!=(e.ecma|0))fatal("ERROR: ecma must be an integer");const t=e.ecma|0;if(t>5&&t<2015)s.ecma=t+2009;else s.ecma=t}if(e.format||e.beautify){const t=e.format||e.beautify;s.format=typeof t==="object"?t:{}}if(e.comments){if(typeof s.format!="object")s.format={};s.format.comments=typeof e.comments=="string"?e.comments=="false"?false:e.comments:"some"}if(e.define){if(typeof s.compress!="object")s.compress={};if(typeof s.compress.global_defs!="object")s.compress.global_defs={};for(var l in e.define){s.compress.global_defs[l]=e.define[l]}}if(e.keepClassnames){s.keep_classnames=true}if(e.keepFnames){s.keep_fnames=true}if(e.mangleProps){if(e.mangleProps.domprops){delete e.mangleProps.domprops}else{if(typeof e.mangleProps!="object")e.mangleProps={};if(!Array.isArray(e.mangleProps.reserved))e.mangleProps.reserved=[]}if(typeof s.mangle!="object")s.mangle={};s.mangle.properties=e.mangleProps}if(e.nameCache){s.nameCache=JSON.parse(read_file(e.nameCache,"{}"))}if(e.output=="ast"){s.format={ast:true,code:false}}if(e.parse){if(!e.parse.acorn&&!e.parse.spidermonkey){s.parse=e.parse}else if(e.sourceMap&&e.sourceMap.content=="inline"){fatal("ERROR: inline source map only works with built-in parser")}}if(~e.rawArgs.indexOf("--rename")){s.rename=true}else if(!e.rename){s.rename=false}let convert_path=e=>e;if(typeof e.sourceMap=="object"&&"base"in e.sourceMap){convert_path=function(){var t=e.sourceMap.base;delete s.sourceMap.base;return function(e){return i.relative(t,e)}}()}let c;if(s.files&&s.files.length){c=s.files;delete s.files}else if(e.args.length){c=e.args}if(c){simple_glob(c).forEach((function(e){a[convert_path(e)]=read_file(e)}))}else{await new Promise((e=>{var t=[];process.stdin.setEncoding("utf8");process.stdin.on("data",(function(e){t.push(e)})).on("end",(function(){a=[t.join("")];e()}));process.stdin.resume()}))}await run_cli();function convert_ast(e){return V.from_mozilla_ast(Object.keys(a).reduce(e,null))}async function run_cli(){var t=e.sourceMap&&e.sourceMap.content;if(t&&t!=="inline"){s.sourceMap.content=read_file(t,t)}if(e.timings)s.timings=true;try{if(e.parse){if(e.parse.acorn){a=convert_ast((function(t,r){return n(988).parse(a[r],{ecmaVersion:2018,locations:true,program:t,sourceFile:r,sourceType:s.module||e.parse.module?"module":"script"})}))}else if(e.parse.spidermonkey){a=convert_ast((function(e,t){var n=JSON.parse(a[t]);if(!e)return n;e.body=e.body.concat(n.body);return e}))}}}catch(e){fatal(e)}let i;try{i=await minify(a,s)}catch(e){if(e.name=="SyntaxError"){print_error("Parse error at "+e.filename+":"+e.line+","+e.col);var u=e.col;var l=a[e.filename].split(/\r?\n/);var c=l[e.line-1];if(!c&&!u){c=l[e.line-2];u=c.length}if(c){var f=70;if(u>f){c=c.slice(u-f);u=f}print_error(c.slice(0,80));print_error(c.slice(0,u).replace(/\S/g," ")+"^")}}if(e.defs){print_error("Supported options:");print_error(format_object(e.defs))}fatal(e);return}if(e.output=="ast"){if(!s.compress&&!s.mangle){i.ast.figure_out_scope({})}console.log(JSON.stringify(i.ast,(function(e,t){if(t)switch(e){case"thedef":return symdef(t);case"enclosed":return t.length?t.map(symdef):undefined;case"variables":case"globals":return t.size?collect_from_map(t,symdef):undefined}if(o.has(e))return;if(t instanceof AST_Token)return;if(t instanceof Map)return;if(t instanceof V){var n={_class:"AST_"+t.TYPE};if(t.block_scope){n.variables=t.block_scope.variables;n.enclosed=t.block_scope.enclosed}t.CTOR.PROPS.forEach((function(e){n[e]=t[e]}));return n}return t}),2))}else if(e.output=="spidermonkey"){try{const e=await minify(i.code,{compress:false,mangle:false,format:{ast:true,code:false}});console.log(JSON.stringify(e.ast.to_mozilla_ast(),null,2))}catch(e){fatal(e);return}}else if(e.output){r.writeFileSync(e.output,i.code);if(s.sourceMap&&s.sourceMap.url!=="inline"&&i.map){r.writeFileSync(e.output+".map",i.map)}}else{console.log(i.code)}if(e.nameCache){r.writeFileSync(e.nameCache,JSON.stringify(s.nameCache))}if(i.timings)for(var _ in i.timings){print_error("- "+_+": "+i.timings[_].toFixed(3)+"s")}}function fatal(e){if(e instanceof Error)e=e.stack.replace(/^\S*?Error:/,"ERROR:");print_error(e);process.exit(1)}function simple_glob(e){if(Array.isArray(e)){return[].concat.apply([],e.map(simple_glob))}if(e&&e.match(/[*?]/)){var t=i.dirname(e);try{var n=r.readdirSync(t)}catch(e){}if(n){var o="^"+i.basename(e).replace(/[.+^$[\]\\(){}]/g,"\\$&").replace(/\*/g,"[^/\\\\]*").replace(/\?/g,"[^/\\\\]")+"$";var a=process.platform==="win32"?"i":"";var s=new RegExp(o,a);var u=n.filter((function(e){return s.test(e)})).map((function(e){return i.join(t,e)}));if(u.length)return u}}return[e]}function read_file(e,t){try{return r.readFileSync(e,"utf8")}catch(e){if((e.code=="ENOENT"||e.code=="ENAMETOOLONG")&&t!=null)return t;fatal(e)}}function parse_js(e){return function(t,n){n=n||{};try{walk(parse(t,{expression:true}),(t=>{if(t instanceof et){var r=t.left.print_to_string();var i=t.right;if(e){n[r]=i}else if(i instanceof nt){n[r]=i.elements.map(to_string)}else if(i instanceof Xt){i=i.value;n[r]=new RegExp(i.source,i.flags)}else{n[r]=to_string(i)}return true}if(t instanceof Et||t instanceof He){var r=t.print_to_string();n[r]=true;return true}if(!(t instanceof Ge))throw t;function to_string(e){return e instanceof zt?e.getValue():e.print_to_string({quote_keys:true})}}))}catch(r){if(e){fatal("Error parsing arguments for '"+e+"': "+t)}else{n[t]=null}}return n}}function symdef(e){var t=1e6+e.id+" "+e.name;if(e.mangled_name)t+=" "+e.mangled_name;return t}function collect_from_map(e,t){var n=[];e.forEach((function(e){n.push(t(e))}));return n}function format_object(e){var t=[];var n="";Object.keys(e).map((function(t){if(n.length!/^\$/.test(e)));if(n.length>0){e.space();e.with_parens((function(){n.forEach((function(t,n){if(n)e.space();e.print(t)}))}))}if(t.documentation){e.space();e.print_string(t.documentation)}if(t.SUBCLASSES.length>0){e.space();e.with_block((function(){t.SUBCLASSES.forEach((function(t){e.indent();doitem(t);e.newline()}))}))}}doitem(V);return e+"\n"}}async function _default_options(){const e={};Object.keys(infer_options({0:0})).forEach((t=>{const n=infer_options({[t]:{0:0}});if(n)e[t]=n}));return e}async function infer_options(e){try{await minify("",e)}catch(e){return e.defs}}e._default_options=_default_options;e._run_cli=run_cli;e.minify=minify}))}};var t={};function __nccwpck_require__(n){var r=t[n];if(r!==undefined){return r.exports}var i=t[n]={exports:{}};var o=true;try{e[n].call(i.exports,i,i.exports,__nccwpck_require__);o=false}finally{if(o)delete t[n]}return i.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var n=__nccwpck_require__(405);module.exports=n})(); \ No newline at end of file diff --git a/packages/next/compiled/webpack/bundle5.js b/packages/next/compiled/webpack/bundle5.js index e83999145ae4..6eb20466a67e 100644 --- a/packages/next/compiled/webpack/bundle5.js +++ b/packages/next/compiled/webpack/bundle5.js @@ -9383,7 +9383,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports.importAssertions = importAssertions; -var _acorn = _interopRequireWildcard(__webpack_require__(70108)); +var _acorn = _interopRequireWildcard(__webpack_require__(31988)); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } @@ -9669,5584 +9669,6 @@ function importAssertions(Parser) { }; } -/***/ }), - -/***/ 70108: -/***/ (function(__unused_webpack_module, exports) { - -(function (global, factory) { - true ? factory(exports) : - 0; -}(this, (function (exports) { 'use strict'; - - // Reserved word lists for various dialects of the language - - var reservedWords = { - 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", - 5: "class enum extends super const export import", - 6: "enum", - strict: "implements interface let package private protected public static yield", - strictBind: "eval arguments" - }; - - // And the keywords - - var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; - - var keywords = { - 5: ecma5AndLessKeywords, - "5module": ecma5AndLessKeywords + " export import", - 6: ecma5AndLessKeywords + " const class extends export import super" - }; - - var keywordRelationalOperator = /^in(stanceof)?$/; - - // ## Character categories - - // Big ugly regular expressions that match characters in the - // whitespace, identifier, and identifier-start categories. These - // are only applied when a character is found to actually have a - // code point above 128. - // Generated by `bin/generate-identifier-regex.js`. - var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; - var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; - - var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); - var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); - - nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; - - // These are a run-length and offset encoded representation of the - // >0xffff code points that are a valid part of identifiers. The - // offset starts at 0x10000, and each pair of numbers represents an - // offset to the next range, and then a size of the range. They were - // generated by bin/generate-identifier-regex.js - - // eslint-disable-next-line comma-spacing - var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938]; - - // eslint-disable-next-line comma-spacing - var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239]; - - // This has a complexity linear to the value of the code. The - // assumption is that looking up astral identifier characters is - // rare. - function isInAstralSet(code, set) { - var pos = 0x10000; - for (var i = 0; i < set.length; i += 2) { - pos += set[i]; - if (pos > code) { return false } - pos += set[i + 1]; - if (pos >= code) { return true } - } - } - - // Test whether a given character code starts an identifier. - - function isIdentifierStart(code, astral) { - if (code < 65) { return code === 36 } - if (code < 91) { return true } - if (code < 97) { return code === 95 } - if (code < 123) { return true } - if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } - if (astral === false) { return false } - return isInAstralSet(code, astralIdentifierStartCodes) - } - - // Test whether a given character is part of an identifier. - - function isIdentifierChar(code, astral) { - if (code < 48) { return code === 36 } - if (code < 58) { return true } - if (code < 65) { return false } - if (code < 91) { return true } - if (code < 97) { return code === 95 } - if (code < 123) { return true } - if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } - if (astral === false) { return false } - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) - } - - // ## Token types - - // The assignment of fine-grained, information-carrying type objects - // allows the tokenizer to store the information it has about a - // token in a way that is very cheap for the parser to look up. - - // All token type variables start with an underscore, to make them - // easy to recognize. - - // The `beforeExpr` property is used to disambiguate between regular - // expressions and divisions. It is set on all token types that can - // be followed by an expression (thus, a slash after them would be a - // regular expression). - // - // The `startsExpr` property is used to check if the token ends a - // `yield` expression. It is set on all token types that either can - // directly start an expression (like a quotation mark) or can - // continue an expression (like the body of a string). - // - // `isLoop` marks a keyword as starting a loop, which is important - // to know when parsing a label, in order to allow or disallow - // continue jumps to that label. - - var TokenType = function TokenType(label, conf) { - if ( conf === void 0 ) conf = {}; - - this.label = label; - this.keyword = conf.keyword; - this.beforeExpr = !!conf.beforeExpr; - this.startsExpr = !!conf.startsExpr; - this.isLoop = !!conf.isLoop; - this.isAssign = !!conf.isAssign; - this.prefix = !!conf.prefix; - this.postfix = !!conf.postfix; - this.binop = conf.binop || null; - this.updateContext = null; - }; - - function binop(name, prec) { - return new TokenType(name, {beforeExpr: true, binop: prec}) - } - var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; - - // Map keyword names to token types. - - var keywords$1 = {}; - - // Succinct definitions of keyword token types - function kw(name, options) { - if ( options === void 0 ) options = {}; - - options.keyword = name; - return keywords$1[name] = new TokenType(name, options) - } - - var types = { - num: new TokenType("num", startsExpr), - regexp: new TokenType("regexp", startsExpr), - string: new TokenType("string", startsExpr), - name: new TokenType("name", startsExpr), - privateId: new TokenType("privateId", startsExpr), - eof: new TokenType("eof"), - - // Punctuation token types. - bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), - bracketR: new TokenType("]"), - braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), - braceR: new TokenType("}"), - parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), - parenR: new TokenType(")"), - comma: new TokenType(",", beforeExpr), - semi: new TokenType(";", beforeExpr), - colon: new TokenType(":", beforeExpr), - dot: new TokenType("."), - question: new TokenType("?", beforeExpr), - questionDot: new TokenType("?."), - arrow: new TokenType("=>", beforeExpr), - template: new TokenType("template"), - invalidTemplate: new TokenType("invalidTemplate"), - ellipsis: new TokenType("...", beforeExpr), - backQuote: new TokenType("`", startsExpr), - dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), - - // Operators. These carry several kinds of properties to help the - // parser use them properly (the presence of these properties is - // what categorizes them as operators). - // - // `binop`, when present, specifies that this operator is a binary - // operator, and will refer to its precedence. - // - // `prefix` and `postfix` mark the operator as a prefix or postfix - // unary operator. - // - // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as - // binary operators with a very low precedence, that should result - // in AssignmentExpression nodes. - - eq: new TokenType("=", {beforeExpr: true, isAssign: true}), - assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), - incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), - prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), - logicalOR: binop("||", 1), - logicalAND: binop("&&", 2), - bitwiseOR: binop("|", 3), - bitwiseXOR: binop("^", 4), - bitwiseAND: binop("&", 5), - equality: binop("==/!=/===/!==", 6), - relational: binop("/<=/>=", 7), - bitShift: binop("<>/>>>", 8), - plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), - modulo: binop("%", 10), - star: binop("*", 10), - slash: binop("/", 10), - starstar: new TokenType("**", {beforeExpr: true}), - coalesce: binop("??", 1), - - // Keyword token types. - _break: kw("break"), - _case: kw("case", beforeExpr), - _catch: kw("catch"), - _continue: kw("continue"), - _debugger: kw("debugger"), - _default: kw("default", beforeExpr), - _do: kw("do", {isLoop: true, beforeExpr: true}), - _else: kw("else", beforeExpr), - _finally: kw("finally"), - _for: kw("for", {isLoop: true}), - _function: kw("function", startsExpr), - _if: kw("if"), - _return: kw("return", beforeExpr), - _switch: kw("switch"), - _throw: kw("throw", beforeExpr), - _try: kw("try"), - _var: kw("var"), - _const: kw("const"), - _while: kw("while", {isLoop: true}), - _with: kw("with"), - _new: kw("new", {beforeExpr: true, startsExpr: true}), - _this: kw("this", startsExpr), - _super: kw("super", startsExpr), - _class: kw("class", startsExpr), - _extends: kw("extends", beforeExpr), - _export: kw("export"), - _import: kw("import", startsExpr), - _null: kw("null", startsExpr), - _true: kw("true", startsExpr), - _false: kw("false", startsExpr), - _in: kw("in", {beforeExpr: true, binop: 7}), - _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), - _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), - _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), - _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) - }; - - // Matches a whole line break (where CRLF is considered a single - // line break). Used to count lines. - - var lineBreak = /\r\n?|\n|\u2028|\u2029/; - var lineBreakG = new RegExp(lineBreak.source, "g"); - - function isNewLine(code) { - return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 - } - - var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; - - var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; - - var ref = Object.prototype; - var hasOwnProperty = ref.hasOwnProperty; - var toString = ref.toString; - - // Checks if an object has a property. - - function has(obj, propName) { - return hasOwnProperty.call(obj, propName) - } - - var isArray = Array.isArray || (function (obj) { return ( - toString.call(obj) === "[object Array]" - ); }); - - function wordsRegexp(words) { - return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") - } - - // These are used when `options.locations` is on, for the - // `startLoc` and `endLoc` properties. - - var Position = function Position(line, col) { - this.line = line; - this.column = col; - }; - - Position.prototype.offset = function offset (n) { - return new Position(this.line, this.column + n) - }; - - var SourceLocation = function SourceLocation(p, start, end) { - this.start = start; - this.end = end; - if (p.sourceFile !== null) { this.source = p.sourceFile; } - }; - - // The `getLineInfo` function is mostly useful when the - // `locations` option is off (for performance reasons) and you - // want to find the line/column position for a given character - // offset. `input` should be the code string that the offset refers - // into. - - function getLineInfo(input, offset) { - for (var line = 1, cur = 0;;) { - lineBreakG.lastIndex = cur; - var match = lineBreakG.exec(input); - if (match && match.index < offset) { - ++line; - cur = match.index + match[0].length; - } else { - return new Position(line, offset - cur) - } - } - } - - // A second argument must be given to configure the parser process. - // These options are recognized (only `ecmaVersion` is required): - - var defaultOptions = { - // `ecmaVersion` indicates the ECMAScript version to parse. Must be - // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 - // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the - // latest version the library supports). This influences support - // for strict mode, the set of reserved words, and support for - // new syntax features. - ecmaVersion: null, - // `sourceType` indicates the mode the code should be parsed in. - // Can be either `"script"` or `"module"`. This influences global - // strict mode and parsing of `import` and `export` declarations. - sourceType: "script", - // `onInsertedSemicolon` can be a callback that will be called - // when a semicolon is automatically inserted. It will be passed - // the position of the comma as an offset, and if `locations` is - // enabled, it is given the location as a `{line, column}` object - // as second argument. - onInsertedSemicolon: null, - // `onTrailingComma` is similar to `onInsertedSemicolon`, but for - // trailing commas. - onTrailingComma: null, - // By default, reserved words are only enforced if ecmaVersion >= 5. - // Set `allowReserved` to a boolean value to explicitly turn this on - // an off. When this option has the value "never", reserved words - // and keywords can also not be used as property names. - allowReserved: null, - // When enabled, a return at the top level is not considered an - // error. - allowReturnOutsideFunction: false, - // When enabled, import/export statements are not constrained to - // appearing at the top of the program, and an import.meta expression - // in a script isn't considered an error. - allowImportExportEverywhere: false, - // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. - // When enabled, await identifiers are allowed to appear at the top-level scope, - // but they are still not allowed in non-async functions. - allowAwaitOutsideFunction: null, - // When enabled, super identifiers are not constrained to - // appearing in methods and do not raise an error when they appear elsewhere. - allowSuperOutsideMethod: null, - // When enabled, hashbang directive in the beginning of file - // is allowed and treated as a line comment. - allowHashBang: false, - // When `locations` is on, `loc` properties holding objects with - // `start` and `end` properties in `{line, column}` form (with - // line being 1-based and column 0-based) will be attached to the - // nodes. - locations: false, - // A function can be passed as `onToken` option, which will - // cause Acorn to call that function with object in the same - // format as tokens returned from `tokenizer().getToken()`. Note - // that you are not allowed to call the parser from the - // callback—that will corrupt its internal state. - onToken: null, - // A function can be passed as `onComment` option, which will - // cause Acorn to call that function with `(block, text, start, - // end)` parameters whenever a comment is skipped. `block` is a - // boolean indicating whether this is a block (`/* */`) comment, - // `text` is the content of the comment, and `start` and `end` are - // character offsets that denote the start and end of the comment. - // When the `locations` option is on, two more parameters are - // passed, the full `{line, column}` locations of the start and - // end of the comments. Note that you are not allowed to call the - // parser from the callback—that will corrupt its internal state. - onComment: null, - // Nodes have their start and end characters offsets recorded in - // `start` and `end` properties (directly on the node, rather than - // the `loc` object, which holds line/column data. To also add a - // [semi-standardized][range] `range` property holding a `[start, - // end]` array with the same numbers, set the `ranges` option to - // `true`. - // - // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 - ranges: false, - // It is possible to parse multiple files into a single AST by - // passing the tree produced by parsing the first file as - // `program` option in subsequent parses. This will add the - // toplevel forms of the parsed file to the `Program` (top) node - // of an existing parse tree. - program: null, - // When `locations` is on, you can pass this to record the source - // file in every node's `loc` object. - sourceFile: null, - // This value, if given, is stored in every node, whether - // `locations` is on or off. - directSourceFile: null, - // When enabled, parenthesized expressions are represented by - // (non-standard) ParenthesizedExpression nodes - preserveParens: false - }; - - // Interpret and default an options object - - var warnedAboutEcmaVersion = false; - - function getOptions(opts) { - var options = {}; - - for (var opt in defaultOptions) - { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; } - - if (options.ecmaVersion === "latest") { - options.ecmaVersion = 1e8; - } else if (options.ecmaVersion == null) { - if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { - warnedAboutEcmaVersion = true; - console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); - } - options.ecmaVersion = 11; - } else if (options.ecmaVersion >= 2015) { - options.ecmaVersion -= 2009; - } - - if (options.allowReserved == null) - { options.allowReserved = options.ecmaVersion < 5; } - - if (isArray(options.onToken)) { - var tokens = options.onToken; - options.onToken = function (token) { return tokens.push(token); }; - } - if (isArray(options.onComment)) - { options.onComment = pushComment(options, options.onComment); } - - return options - } - - function pushComment(options, array) { - return function(block, text, start, end, startLoc, endLoc) { - var comment = { - type: block ? "Block" : "Line", - value: text, - start: start, - end: end - }; - if (options.locations) - { comment.loc = new SourceLocation(this, startLoc, endLoc); } - if (options.ranges) - { comment.range = [start, end]; } - array.push(comment); - } - } - - // Each scope gets a bitset that may contain these flags - var - SCOPE_TOP = 1, - SCOPE_FUNCTION = 2, - SCOPE_ASYNC = 4, - SCOPE_GENERATOR = 8, - SCOPE_ARROW = 16, - SCOPE_SIMPLE_CATCH = 32, - SCOPE_SUPER = 64, - SCOPE_DIRECT_SUPER = 128, - SCOPE_CLASS_STATIC_BLOCK = 256, - SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; - - function functionFlags(async, generator) { - return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) - } - - // Used in checkLVal* and declareName to determine the type of a binding - var - BIND_NONE = 0, // Not a binding - BIND_VAR = 1, // Var-style binding - BIND_LEXICAL = 2, // Let- or const-style binding - BIND_FUNCTION = 3, // Function declaration - BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding - BIND_OUTSIDE = 5; // Special case for function names as bound inside the function - - var Parser = function Parser(options, input, startPos) { - this.options = options = getOptions(options); - this.sourceFile = options.sourceFile; - this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); - var reserved = ""; - if (options.allowReserved !== true) { - reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; - if (options.sourceType === "module") { reserved += " await"; } - } - this.reservedWords = wordsRegexp(reserved); - var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; - this.reservedWordsStrict = wordsRegexp(reservedStrict); - this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); - this.input = String(input); - - // Used to signal to callers of `readWord1` whether the word - // contained any escape sequences. This is needed because words with - // escape sequences must not be interpreted as keywords. - this.containsEsc = false; - - // Set up token state - - // The current position of the tokenizer in the input. - if (startPos) { - this.pos = startPos; - this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; - this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; - } else { - this.pos = this.lineStart = 0; - this.curLine = 1; - } - - // Properties of the current token: - // Its type - this.type = types.eof; - // For tokens that include more information than their type, the value - this.value = null; - // Its start and end offset - this.start = this.end = this.pos; - // And, if locations are used, the {line, column} object - // corresponding to those offsets - this.startLoc = this.endLoc = this.curPosition(); - - // Position information for the previous token - this.lastTokEndLoc = this.lastTokStartLoc = null; - this.lastTokStart = this.lastTokEnd = this.pos; - - // The context stack is used to superficially track syntactic - // context to predict whether a regular expression is allowed in a - // given position. - this.context = this.initialContext(); - this.exprAllowed = true; - - // Figure out if it's a module code. - this.inModule = options.sourceType === "module"; - this.strict = this.inModule || this.strictDirective(this.pos); - - // Used to signify the start of a potential arrow function - this.potentialArrowAt = -1; - this.potentialArrowInForAwait = false; - - // Positions to delayed-check that yield/await does not exist in default parameters. - this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; - // Labels in scope. - this.labels = []; - // Thus-far undefined exports. - this.undefinedExports = Object.create(null); - - // If enabled, skip leading hashbang line. - if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") - { this.skipLineComment(2); } - - // Scope tracking for duplicate variable names (see scope.js) - this.scopeStack = []; - this.enterScope(SCOPE_TOP); - - // For RegExp validation - this.regexpState = null; - - // The stack of private names. - // Each element has two properties: 'declared' and 'used'. - // When it exited from the outermost class definition, all used private names must be declared. - this.privateNameStack = []; - }; - - var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; - - Parser.prototype.parse = function parse () { - var node = this.options.program || this.startNode(); - this.nextToken(); - return this.parseTopLevel(node) - }; - - prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; - prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }; - prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; - prototypeAccessors.canAwait.get = function () { - for (var i = this.scopeStack.length - 1; i >= 0; i--) { - var scope = this.scopeStack[i]; - if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false } - if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } - } - return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction - }; - prototypeAccessors.allowSuper.get = function () { - var ref = this.currentThisScope(); - var flags = ref.flags; - var inClassFieldInit = ref.inClassFieldInit; - return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod - }; - prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; - prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; - prototypeAccessors.allowNewDotTarget.get = function () { - var ref = this.currentThisScope(); - var flags = ref.flags; - var inClassFieldInit = ref.inClassFieldInit; - return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit - }; - prototypeAccessors.inClassStaticBlock.get = function () { - return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 - }; - - Parser.extend = function extend () { - var plugins = [], len = arguments.length; - while ( len-- ) plugins[ len ] = arguments[ len ]; - - var cls = this; - for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } - return cls - }; - - Parser.parse = function parse (input, options) { - return new this(options, input).parse() - }; - - Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { - var parser = new this(options, input, pos); - parser.nextToken(); - return parser.parseExpression() - }; - - Parser.tokenizer = function tokenizer (input, options) { - return new this(options, input) - }; - - Object.defineProperties( Parser.prototype, prototypeAccessors ); - - var pp = Parser.prototype; - - // ## Parser utilities - - var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; - pp.strictDirective = function(start) { - for (;;) { - // Try to find string literal. - skipWhiteSpace.lastIndex = start; - start += skipWhiteSpace.exec(this.input)[0].length; - var match = literal.exec(this.input.slice(start)); - if (!match) { return false } - if ((match[1] || match[2]) === "use strict") { - skipWhiteSpace.lastIndex = start + match[0].length; - var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; - var next = this.input.charAt(end); - return next === ";" || next === "}" || - (lineBreak.test(spaceAfter[0]) && - !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) - } - start += match[0].length; - - // Skip semicolon, if any. - skipWhiteSpace.lastIndex = start; - start += skipWhiteSpace.exec(this.input)[0].length; - if (this.input[start] === ";") - { start++; } - } - }; - - // Predicate that tests whether the next token is of the given - // type, and if yes, consumes it as a side effect. - - pp.eat = function(type) { - if (this.type === type) { - this.next(); - return true - } else { - return false - } - }; - - // Tests whether parsed token is a contextual keyword. - - pp.isContextual = function(name) { - return this.type === types.name && this.value === name && !this.containsEsc - }; - - // Consumes contextual keyword if possible. - - pp.eatContextual = function(name) { - if (!this.isContextual(name)) { return false } - this.next(); - return true - }; - - // Asserts that following token is given contextual keyword. - - pp.expectContextual = function(name) { - if (!this.eatContextual(name)) { this.unexpected(); } - }; - - // Test whether a semicolon can be inserted at the current position. - - pp.canInsertSemicolon = function() { - return this.type === types.eof || - this.type === types.braceR || - lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) - }; - - pp.insertSemicolon = function() { - if (this.canInsertSemicolon()) { - if (this.options.onInsertedSemicolon) - { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } - return true - } - }; - - // Consume a semicolon, or, failing that, see if we are allowed to - // pretend that there is a semicolon at this position. - - pp.semicolon = function() { - if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } - }; - - pp.afterTrailingComma = function(tokType, notNext) { - if (this.type === tokType) { - if (this.options.onTrailingComma) - { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } - if (!notNext) - { this.next(); } - return true - } - }; - - // Expect a token of a given type. If found, consume it, otherwise, - // raise an unexpected token error. - - pp.expect = function(type) { - this.eat(type) || this.unexpected(); - }; - - // Raise an unexpected token error. - - pp.unexpected = function(pos) { - this.raise(pos != null ? pos : this.start, "Unexpected token"); - }; - - function DestructuringErrors() { - this.shorthandAssign = - this.trailingComma = - this.parenthesizedAssign = - this.parenthesizedBind = - this.doubleProto = - -1; - } - - pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { - if (!refDestructuringErrors) { return } - if (refDestructuringErrors.trailingComma > -1) - { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } - var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; - if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } - }; - - pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { - if (!refDestructuringErrors) { return false } - var shorthandAssign = refDestructuringErrors.shorthandAssign; - var doubleProto = refDestructuringErrors.doubleProto; - if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } - if (shorthandAssign >= 0) - { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } - if (doubleProto >= 0) - { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } - }; - - pp.checkYieldAwaitInDefaultParams = function() { - if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) - { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } - if (this.awaitPos) - { this.raise(this.awaitPos, "Await expression cannot be a default value"); } - }; - - pp.isSimpleAssignTarget = function(expr) { - if (expr.type === "ParenthesizedExpression") - { return this.isSimpleAssignTarget(expr.expression) } - return expr.type === "Identifier" || expr.type === "MemberExpression" - }; - - var pp$1 = Parser.prototype; - - // ### Statement parsing - - // Parse a program. Initializes the parser, reads any number of - // statements, and wraps them in a Program node. Optionally takes a - // `program` argument. If present, the statements will be appended - // to its body instead of creating a new node. - - pp$1.parseTopLevel = function(node) { - var exports = Object.create(null); - if (!node.body) { node.body = []; } - while (this.type !== types.eof) { - var stmt = this.parseStatement(null, true, exports); - node.body.push(stmt); - } - if (this.inModule) - { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) - { - var name = list[i]; - - this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); - } } - this.adaptDirectivePrologue(node.body); - this.next(); - node.sourceType = this.options.sourceType; - return this.finishNode(node, "Program") - }; - - var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; - - pp$1.isLet = function(context) { - if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } - skipWhiteSpace.lastIndex = this.pos; - var skip = skipWhiteSpace.exec(this.input); - var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); - // For ambiguous cases, determine if a LexicalDeclaration (or only a - // Statement) is allowed here. If context is not empty then only a Statement - // is allowed. However, `let [` is an explicit negative lookahead for - // ExpressionStatement, so special-case it first. - if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral - if (context) { return false } - - if (nextCh === 123) { return true } // '{' - if (isIdentifierStart(nextCh, true)) { - var pos = next + 1; - while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } - if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } - var ident = this.input.slice(next, pos); - if (!keywordRelationalOperator.test(ident)) { return true } - } - return false - }; - - // check 'async [no LineTerminator here] function' - // - 'async /*foo*/ function' is OK. - // - 'async /*\n*/ function' is invalid. - pp$1.isAsyncFunction = function() { - if (this.options.ecmaVersion < 8 || !this.isContextual("async")) - { return false } - - skipWhiteSpace.lastIndex = this.pos; - var skip = skipWhiteSpace.exec(this.input); - var next = this.pos + skip[0].length, after; - return !lineBreak.test(this.input.slice(this.pos, next)) && - this.input.slice(next, next + 8) === "function" && - (next + 8 === this.input.length || - !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) - }; - - // Parse a single statement. - // - // If expecting a statement and finding a slash operator, parse a - // regular expression literal. This is to handle cases like - // `if (foo) /blah/.exec(foo)`, where looking at the previous token - // does not help. - - pp$1.parseStatement = function(context, topLevel, exports) { - var starttype = this.type, node = this.startNode(), kind; - - if (this.isLet(context)) { - starttype = types._var; - kind = "let"; - } - - // Most types of statements are recognized by the keyword they - // start with. Many are trivial to parse, some require a bit of - // complexity. - - switch (starttype) { - case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword) - case types._debugger: return this.parseDebuggerStatement(node) - case types._do: return this.parseDoStatement(node) - case types._for: return this.parseForStatement(node) - case types._function: - // Function as sole body of either an if statement or a labeled statement - // works, but not when it is part of a labeled statement that is the sole - // body of an if statement. - if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } - return this.parseFunctionStatement(node, false, !context) - case types._class: - if (context) { this.unexpected(); } - return this.parseClass(node, true) - case types._if: return this.parseIfStatement(node) - case types._return: return this.parseReturnStatement(node) - case types._switch: return this.parseSwitchStatement(node) - case types._throw: return this.parseThrowStatement(node) - case types._try: return this.parseTryStatement(node) - case types._const: case types._var: - kind = kind || this.value; - if (context && kind !== "var") { this.unexpected(); } - return this.parseVarStatement(node, kind) - case types._while: return this.parseWhileStatement(node) - case types._with: return this.parseWithStatement(node) - case types.braceL: return this.parseBlock(true, node) - case types.semi: return this.parseEmptyStatement(node) - case types._export: - case types._import: - if (this.options.ecmaVersion > 10 && starttype === types._import) { - skipWhiteSpace.lastIndex = this.pos; - var skip = skipWhiteSpace.exec(this.input); - var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); - if (nextCh === 40 || nextCh === 46) // '(' or '.' - { return this.parseExpressionStatement(node, this.parseExpression()) } - } - - if (!this.options.allowImportExportEverywhere) { - if (!topLevel) - { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } - if (!this.inModule) - { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } - } - return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports) - - // If the statement does not start with a statement keyword or a - // brace, it's an ExpressionStatement or LabeledStatement. We - // simply start parsing an expression, and afterwards, if the - // next token is a colon and the expression was a simple - // Identifier node, we switch to interpreting it as a label. - default: - if (this.isAsyncFunction()) { - if (context) { this.unexpected(); } - this.next(); - return this.parseFunctionStatement(node, true, !context) - } - - var maybeName = this.value, expr = this.parseExpression(); - if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) - { return this.parseLabeledStatement(node, maybeName, expr, context) } - else { return this.parseExpressionStatement(node, expr) } - } - }; - - pp$1.parseBreakContinueStatement = function(node, keyword) { - var isBreak = keyword === "break"; - this.next(); - if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; } - else if (this.type !== types.name) { this.unexpected(); } - else { - node.label = this.parseIdent(); - this.semicolon(); - } - - // Verify that there is an actual destination to break or - // continue to. - var i = 0; - for (; i < this.labels.length; ++i) { - var lab = this.labels[i]; - if (node.label == null || lab.name === node.label.name) { - if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } - if (node.label && isBreak) { break } - } - } - if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } - return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") - }; - - pp$1.parseDebuggerStatement = function(node) { - this.next(); - this.semicolon(); - return this.finishNode(node, "DebuggerStatement") - }; - - pp$1.parseDoStatement = function(node) { - this.next(); - this.labels.push(loopLabel); - node.body = this.parseStatement("do"); - this.labels.pop(); - this.expect(types._while); - node.test = this.parseParenExpression(); - if (this.options.ecmaVersion >= 6) - { this.eat(types.semi); } - else - { this.semicolon(); } - return this.finishNode(node, "DoWhileStatement") - }; - - // Disambiguating between a `for` and a `for`/`in` or `for`/`of` - // loop is non-trivial. Basically, we have to parse the init `var` - // statement or expression, disallowing the `in` operator (see - // the second parameter to `parseExpression`), and then check - // whether the next token is `in` or `of`. When there is no init - // part (semicolon immediately after the opening parenthesis), it - // is a regular `for` loop. - - pp$1.parseForStatement = function(node) { - this.next(); - var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; - this.labels.push(loopLabel); - this.enterScope(0); - this.expect(types.parenL); - if (this.type === types.semi) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, null) - } - var isLet = this.isLet(); - if (this.type === types._var || this.type === types._const || isLet) { - var init$1 = this.startNode(), kind = isLet ? "let" : this.value; - this.next(); - this.parseVar(init$1, true, kind); - this.finishNode(init$1, "VariableDeclaration"); - if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { - if (this.options.ecmaVersion >= 9) { - if (this.type === types._in) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - } else { node.await = awaitAt > -1; } - } - return this.parseForIn(node, init$1) - } - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, init$1) - } - var startsWithLet = this.isContextual("let"), isForOf = false; - var refDestructuringErrors = new DestructuringErrors; - var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); - if (this.type === types._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { - if (this.options.ecmaVersion >= 9) { - if (this.type === types._in) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - } else { node.await = awaitAt > -1; } - } - if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } - this.toAssignable(init, false, refDestructuringErrors); - this.checkLValPattern(init); - return this.parseForIn(node, init) - } else { - this.checkExpressionErrors(refDestructuringErrors, true); - } - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, init) - }; - - pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { - this.next(); - return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) - }; - - pp$1.parseIfStatement = function(node) { - this.next(); - node.test = this.parseParenExpression(); - // allow function declarations in branches, but only in non-strict mode - node.consequent = this.parseStatement("if"); - node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; - return this.finishNode(node, "IfStatement") - }; - - pp$1.parseReturnStatement = function(node) { - if (!this.inFunction && !this.options.allowReturnOutsideFunction) - { this.raise(this.start, "'return' outside of function"); } - this.next(); - - // In `return` (and `break`/`continue`), the keywords with - // optional arguments, we eagerly look for a semicolon or the - // possibility to insert one. - - if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; } - else { node.argument = this.parseExpression(); this.semicolon(); } - return this.finishNode(node, "ReturnStatement") - }; - - pp$1.parseSwitchStatement = function(node) { - this.next(); - node.discriminant = this.parseParenExpression(); - node.cases = []; - this.expect(types.braceL); - this.labels.push(switchLabel); - this.enterScope(0); - - // Statements under must be grouped (by label) in SwitchCase - // nodes. `cur` is used to keep the node that we are currently - // adding statements to. - - var cur; - for (var sawDefault = false; this.type !== types.braceR;) { - if (this.type === types._case || this.type === types._default) { - var isCase = this.type === types._case; - if (cur) { this.finishNode(cur, "SwitchCase"); } - node.cases.push(cur = this.startNode()); - cur.consequent = []; - this.next(); - if (isCase) { - cur.test = this.parseExpression(); - } else { - if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } - sawDefault = true; - cur.test = null; - } - this.expect(types.colon); - } else { - if (!cur) { this.unexpected(); } - cur.consequent.push(this.parseStatement(null)); - } - } - this.exitScope(); - if (cur) { this.finishNode(cur, "SwitchCase"); } - this.next(); // Closing brace - this.labels.pop(); - return this.finishNode(node, "SwitchStatement") - }; - - pp$1.parseThrowStatement = function(node) { - this.next(); - if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) - { this.raise(this.lastTokEnd, "Illegal newline after throw"); } - node.argument = this.parseExpression(); - this.semicolon(); - return this.finishNode(node, "ThrowStatement") - }; - - // Reused empty array added for node fields that are always empty. - - var empty = []; - - pp$1.parseTryStatement = function(node) { - this.next(); - node.block = this.parseBlock(); - node.handler = null; - if (this.type === types._catch) { - var clause = this.startNode(); - this.next(); - if (this.eat(types.parenL)) { - clause.param = this.parseBindingAtom(); - var simple = clause.param.type === "Identifier"; - this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); - this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); - this.expect(types.parenR); - } else { - if (this.options.ecmaVersion < 10) { this.unexpected(); } - clause.param = null; - this.enterScope(0); - } - clause.body = this.parseBlock(false); - this.exitScope(); - node.handler = this.finishNode(clause, "CatchClause"); - } - node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; - if (!node.handler && !node.finalizer) - { this.raise(node.start, "Missing catch or finally clause"); } - return this.finishNode(node, "TryStatement") - }; - - pp$1.parseVarStatement = function(node, kind) { - this.next(); - this.parseVar(node, false, kind); - this.semicolon(); - return this.finishNode(node, "VariableDeclaration") - }; - - pp$1.parseWhileStatement = function(node) { - this.next(); - node.test = this.parseParenExpression(); - this.labels.push(loopLabel); - node.body = this.parseStatement("while"); - this.labels.pop(); - return this.finishNode(node, "WhileStatement") - }; - - pp$1.parseWithStatement = function(node) { - if (this.strict) { this.raise(this.start, "'with' in strict mode"); } - this.next(); - node.object = this.parseParenExpression(); - node.body = this.parseStatement("with"); - return this.finishNode(node, "WithStatement") - }; - - pp$1.parseEmptyStatement = function(node) { - this.next(); - return this.finishNode(node, "EmptyStatement") - }; - - pp$1.parseLabeledStatement = function(node, maybeName, expr, context) { - for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) - { - var label = list[i$1]; - - if (label.name === maybeName) - { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); - } } - var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; - for (var i = this.labels.length - 1; i >= 0; i--) { - var label$1 = this.labels[i]; - if (label$1.statementStart === node.start) { - // Update information about previous labels on this node - label$1.statementStart = this.start; - label$1.kind = kind; - } else { break } - } - this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); - node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); - this.labels.pop(); - node.label = expr; - return this.finishNode(node, "LabeledStatement") - }; - - pp$1.parseExpressionStatement = function(node, expr) { - node.expression = expr; - this.semicolon(); - return this.finishNode(node, "ExpressionStatement") - }; - - // Parse a semicolon-enclosed block of statements, handling `"use - // strict"` declarations when `allowStrict` is true (used for - // function bodies). - - pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) { - if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; - if ( node === void 0 ) node = this.startNode(); - - node.body = []; - this.expect(types.braceL); - if (createNewLexicalScope) { this.enterScope(0); } - while (this.type !== types.braceR) { - var stmt = this.parseStatement(null); - node.body.push(stmt); - } - if (exitStrict) { this.strict = false; } - this.next(); - if (createNewLexicalScope) { this.exitScope(); } - return this.finishNode(node, "BlockStatement") - }; - - // Parse a regular `for` loop. The disambiguation code in - // `parseStatement` will already have parsed the init statement or - // expression. - - pp$1.parseFor = function(node, init) { - node.init = init; - this.expect(types.semi); - node.test = this.type === types.semi ? null : this.parseExpression(); - this.expect(types.semi); - node.update = this.type === types.parenR ? null : this.parseExpression(); - this.expect(types.parenR); - node.body = this.parseStatement("for"); - this.exitScope(); - this.labels.pop(); - return this.finishNode(node, "ForStatement") - }; - - // Parse a `for`/`in` and `for`/`of` loop, which are almost - // same from parser's perspective. - - pp$1.parseForIn = function(node, init) { - var isForIn = this.type === types._in; - this.next(); - - if ( - init.type === "VariableDeclaration" && - init.declarations[0].init != null && - ( - !isForIn || - this.options.ecmaVersion < 8 || - this.strict || - init.kind !== "var" || - init.declarations[0].id.type !== "Identifier" - ) - ) { - this.raise( - init.start, - ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") - ); - } - node.left = init; - node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); - this.expect(types.parenR); - node.body = this.parseStatement("for"); - this.exitScope(); - this.labels.pop(); - return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") - }; - - // Parse a list of variable declarations. - - pp$1.parseVar = function(node, isFor, kind) { - node.declarations = []; - node.kind = kind; - for (;;) { - var decl = this.startNode(); - this.parseVarId(decl, kind); - if (this.eat(types.eq)) { - decl.init = this.parseMaybeAssign(isFor); - } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { - this.unexpected(); - } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) { - this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); - } else { - decl.init = null; - } - node.declarations.push(this.finishNode(decl, "VariableDeclarator")); - if (!this.eat(types.comma)) { break } - } - return node - }; - - pp$1.parseVarId = function(decl, kind) { - decl.id = this.parseBindingAtom(); - this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); - }; - - var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; - - // Parse a function declaration or literal (depending on the - // `statement & FUNC_STATEMENT`). - - // Remove `allowExpressionBody` for 7.0.0, as it is only called with false - pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { - this.initFunction(node); - if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { - if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT)) - { this.unexpected(); } - node.generator = this.eat(types.star); - } - if (this.options.ecmaVersion >= 8) - { node.async = !!isAsync; } - - if (statement & FUNC_STATEMENT) { - node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent(); - if (node.id && !(statement & FUNC_HANGING_STATEMENT)) - // If it is a regular function declaration in sloppy mode, then it is - // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding - // mode depends on properties of the current scope (see - // treatFunctionsAsVar). - { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } - } - - var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - this.enterScope(functionFlags(node.async, node.generator)); - - if (!(statement & FUNC_STATEMENT)) - { node.id = this.type === types.name ? this.parseIdent() : null; } - - this.parseFunctionParams(node); - this.parseFunctionBody(node, allowExpressionBody, false, forInit); - - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") - }; - - pp$1.parseFunctionParams = function(node) { - this.expect(types.parenL); - node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); - this.checkYieldAwaitInDefaultParams(); - }; - - // Parse a class declaration or literal (depending on the - // `isStatement` parameter). - - pp$1.parseClass = function(node, isStatement) { - this.next(); - - // ecma-262 14.6 Class Definitions - // A class definition is always strict mode code. - var oldStrict = this.strict; - this.strict = true; - - this.parseClassId(node, isStatement); - this.parseClassSuper(node); - var privateNameMap = this.enterClassBody(); - var classBody = this.startNode(); - var hadConstructor = false; - classBody.body = []; - this.expect(types.braceL); - while (this.type !== types.braceR) { - var element = this.parseClassElement(node.superClass !== null); - if (element) { - classBody.body.push(element); - if (element.type === "MethodDefinition" && element.kind === "constructor") { - if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); } - hadConstructor = true; - } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { - this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); - } - } - } - this.strict = oldStrict; - this.next(); - node.body = this.finishNode(classBody, "ClassBody"); - this.exitClassBody(); - return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") - }; - - pp$1.parseClassElement = function(constructorAllowsSuper) { - if (this.eat(types.semi)) { return null } - - var ecmaVersion = this.options.ecmaVersion; - var node = this.startNode(); - var keyName = ""; - var isGenerator = false; - var isAsync = false; - var kind = "method"; - var isStatic = false; - - if (this.eatContextual("static")) { - // Parse static init block - if (ecmaVersion >= 13 && this.eat(types.braceL)) { - this.parseClassStaticBlock(node); - return node - } - if (this.isClassElementNameStart() || this.type === types.star) { - isStatic = true; - } else { - keyName = "static"; - } - } - node.static = isStatic; - if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { - if ((this.isClassElementNameStart() || this.type === types.star) && !this.canInsertSemicolon()) { - isAsync = true; - } else { - keyName = "async"; - } - } - if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types.star)) { - isGenerator = true; - } - if (!keyName && !isAsync && !isGenerator) { - var lastValue = this.value; - if (this.eatContextual("get") || this.eatContextual("set")) { - if (this.isClassElementNameStart()) { - kind = lastValue; - } else { - keyName = lastValue; - } - } - } - - // Parse element name - if (keyName) { - // 'async', 'get', 'set', or 'static' were not a keyword contextually. - // The last token is any of those. Make it the element name. - node.computed = false; - node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); - node.key.name = keyName; - this.finishNode(node.key, "Identifier"); - } else { - this.parseClassElementName(node); - } - - // Parse element value - if (ecmaVersion < 13 || this.type === types.parenL || kind !== "method" || isGenerator || isAsync) { - var isConstructor = !node.static && checkKeyName(node, "constructor"); - var allowsDirectSuper = isConstructor && constructorAllowsSuper; - // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. - if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } - node.kind = isConstructor ? "constructor" : kind; - this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); - } else { - this.parseClassField(node); - } - - return node - }; - - pp$1.isClassElementNameStart = function() { - return ( - this.type === types.name || - this.type === types.privateId || - this.type === types.num || - this.type === types.string || - this.type === types.bracketL || - this.type.keyword - ) - }; - - pp$1.parseClassElementName = function(element) { - if (this.type === types.privateId) { - if (this.value === "constructor") { - this.raise(this.start, "Classes can't have an element named '#constructor'"); - } - element.computed = false; - element.key = this.parsePrivateIdent(); - } else { - this.parsePropertyName(element); - } - }; - - pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { - // Check key and flags - var key = method.key; - if (method.kind === "constructor") { - if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } - if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } - } else if (method.static && checkKeyName(method, "prototype")) { - this.raise(key.start, "Classes may not have a static property named prototype"); - } - - // Parse value - var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); - - // Check value - if (method.kind === "get" && value.params.length !== 0) - { this.raiseRecoverable(value.start, "getter should have no params"); } - if (method.kind === "set" && value.params.length !== 1) - { this.raiseRecoverable(value.start, "setter should have exactly one param"); } - if (method.kind === "set" && value.params[0].type === "RestElement") - { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } - - return this.finishNode(method, "MethodDefinition") - }; - - pp$1.parseClassField = function(field) { - if (checkKeyName(field, "constructor")) { - this.raise(field.key.start, "Classes can't have a field named 'constructor'"); - } else if (field.static && checkKeyName(field, "prototype")) { - this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); - } - - if (this.eat(types.eq)) { - // To raise SyntaxError if 'arguments' exists in the initializer. - var scope = this.currentThisScope(); - var inClassFieldInit = scope.inClassFieldInit; - scope.inClassFieldInit = true; - field.value = this.parseMaybeAssign(); - scope.inClassFieldInit = inClassFieldInit; - } else { - field.value = null; - } - this.semicolon(); - - return this.finishNode(field, "PropertyDefinition") - }; - - pp$1.parseClassStaticBlock = function(node) { - node.body = []; - - var oldLabels = this.labels; - this.labels = []; - this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); - while (this.type !== types.braceR) { - var stmt = this.parseStatement(null); - node.body.push(stmt); - } - this.next(); - this.exitScope(); - this.labels = oldLabels; - - return this.finishNode(node, "StaticBlock") - }; - - pp$1.parseClassId = function(node, isStatement) { - if (this.type === types.name) { - node.id = this.parseIdent(); - if (isStatement) - { this.checkLValSimple(node.id, BIND_LEXICAL, false); } - } else { - if (isStatement === true) - { this.unexpected(); } - node.id = null; - } - }; - - pp$1.parseClassSuper = function(node) { - node.superClass = this.eat(types._extends) ? this.parseExprSubscripts(false) : null; - }; - - pp$1.enterClassBody = function() { - var element = {declared: Object.create(null), used: []}; - this.privateNameStack.push(element); - return element.declared - }; - - pp$1.exitClassBody = function() { - var ref = this.privateNameStack.pop(); - var declared = ref.declared; - var used = ref.used; - var len = this.privateNameStack.length; - var parent = len === 0 ? null : this.privateNameStack[len - 1]; - for (var i = 0; i < used.length; ++i) { - var id = used[i]; - if (!has(declared, id.name)) { - if (parent) { - parent.used.push(id); - } else { - this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); - } - } - } - }; - - function isPrivateNameConflicted(privateNameMap, element) { - var name = element.key.name; - var curr = privateNameMap[name]; - - var next = "true"; - if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { - next = (element.static ? "s" : "i") + element.kind; - } - - // `class { get #a(){}; static set #a(_){} }` is also conflict. - if ( - curr === "iget" && next === "iset" || - curr === "iset" && next === "iget" || - curr === "sget" && next === "sset" || - curr === "sset" && next === "sget" - ) { - privateNameMap[name] = "true"; - return false - } else if (!curr) { - privateNameMap[name] = next; - return false - } else { - return true - } - } - - function checkKeyName(node, name) { - var computed = node.computed; - var key = node.key; - return !computed && ( - key.type === "Identifier" && key.name === name || - key.type === "Literal" && key.value === name - ) - } - - // Parses module export declaration. - - pp$1.parseExport = function(node, exports) { - this.next(); - // export * from '...' - if (this.eat(types.star)) { - if (this.options.ecmaVersion >= 11) { - if (this.eatContextual("as")) { - node.exported = this.parseIdent(true); - this.checkExport(exports, node.exported.name, this.lastTokStart); - } else { - node.exported = null; - } - } - this.expectContextual("from"); - if (this.type !== types.string) { this.unexpected(); } - node.source = this.parseExprAtom(); - this.semicolon(); - return this.finishNode(node, "ExportAllDeclaration") - } - if (this.eat(types._default)) { // export default ... - this.checkExport(exports, "default", this.lastTokStart); - var isAsync; - if (this.type === types._function || (isAsync = this.isAsyncFunction())) { - var fNode = this.startNode(); - this.next(); - if (isAsync) { this.next(); } - node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); - } else if (this.type === types._class) { - var cNode = this.startNode(); - node.declaration = this.parseClass(cNode, "nullableID"); - } else { - node.declaration = this.parseMaybeAssign(); - this.semicolon(); - } - return this.finishNode(node, "ExportDefaultDeclaration") - } - // export var|const|let|function|class ... - if (this.shouldParseExportStatement()) { - node.declaration = this.parseStatement(null); - if (node.declaration.type === "VariableDeclaration") - { this.checkVariableExport(exports, node.declaration.declarations); } - else - { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } - node.specifiers = []; - node.source = null; - } else { // export { x, y as z } [from '...'] - node.declaration = null; - node.specifiers = this.parseExportSpecifiers(exports); - if (this.eatContextual("from")) { - if (this.type !== types.string) { this.unexpected(); } - node.source = this.parseExprAtom(); - } else { - for (var i = 0, list = node.specifiers; i < list.length; i += 1) { - // check for keywords used as local names - var spec = list[i]; - - this.checkUnreserved(spec.local); - // check if export is defined - this.checkLocalExport(spec.local); - } - - node.source = null; - } - this.semicolon(); - } - return this.finishNode(node, "ExportNamedDeclaration") - }; - - pp$1.checkExport = function(exports, name, pos) { - if (!exports) { return } - if (has(exports, name)) - { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } - exports[name] = true; - }; - - pp$1.checkPatternExport = function(exports, pat) { - var type = pat.type; - if (type === "Identifier") - { this.checkExport(exports, pat.name, pat.start); } - else if (type === "ObjectPattern") - { for (var i = 0, list = pat.properties; i < list.length; i += 1) - { - var prop = list[i]; - - this.checkPatternExport(exports, prop); - } } - else if (type === "ArrayPattern") - { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { - var elt = list$1[i$1]; - - if (elt) { this.checkPatternExport(exports, elt); } - } } - else if (type === "Property") - { this.checkPatternExport(exports, pat.value); } - else if (type === "AssignmentPattern") - { this.checkPatternExport(exports, pat.left); } - else if (type === "RestElement") - { this.checkPatternExport(exports, pat.argument); } - else if (type === "ParenthesizedExpression") - { this.checkPatternExport(exports, pat.expression); } - }; - - pp$1.checkVariableExport = function(exports, decls) { - if (!exports) { return } - for (var i = 0, list = decls; i < list.length; i += 1) - { - var decl = list[i]; - - this.checkPatternExport(exports, decl.id); - } - }; - - pp$1.shouldParseExportStatement = function() { - return this.type.keyword === "var" || - this.type.keyword === "const" || - this.type.keyword === "class" || - this.type.keyword === "function" || - this.isLet() || - this.isAsyncFunction() - }; - - // Parses a comma-separated list of module exports. - - pp$1.parseExportSpecifiers = function(exports) { - var nodes = [], first = true; - // export { x, y as z } [from '...'] - this.expect(types.braceL); - while (!this.eat(types.braceR)) { - if (!first) { - this.expect(types.comma); - if (this.afterTrailingComma(types.braceR)) { break } - } else { first = false; } - - var node = this.startNode(); - node.local = this.parseIdent(true); - node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local; - this.checkExport(exports, node.exported.name, node.exported.start); - nodes.push(this.finishNode(node, "ExportSpecifier")); - } - return nodes - }; - - // Parses import declaration. - - pp$1.parseImport = function(node) { - this.next(); - // import '...' - if (this.type === types.string) { - node.specifiers = empty; - node.source = this.parseExprAtom(); - } else { - node.specifiers = this.parseImportSpecifiers(); - this.expectContextual("from"); - node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected(); - } - this.semicolon(); - return this.finishNode(node, "ImportDeclaration") - }; - - // Parses a comma-separated list of module imports. - - pp$1.parseImportSpecifiers = function() { - var nodes = [], first = true; - if (this.type === types.name) { - // import defaultObj, { x, y as z } from '...' - var node = this.startNode(); - node.local = this.parseIdent(); - this.checkLValSimple(node.local, BIND_LEXICAL); - nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); - if (!this.eat(types.comma)) { return nodes } - } - if (this.type === types.star) { - var node$1 = this.startNode(); - this.next(); - this.expectContextual("as"); - node$1.local = this.parseIdent(); - this.checkLValSimple(node$1.local, BIND_LEXICAL); - nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); - return nodes - } - this.expect(types.braceL); - while (!this.eat(types.braceR)) { - if (!first) { - this.expect(types.comma); - if (this.afterTrailingComma(types.braceR)) { break } - } else { first = false; } - - var node$2 = this.startNode(); - node$2.imported = this.parseIdent(true); - if (this.eatContextual("as")) { - node$2.local = this.parseIdent(); - } else { - this.checkUnreserved(node$2.imported); - node$2.local = node$2.imported; - } - this.checkLValSimple(node$2.local, BIND_LEXICAL); - nodes.push(this.finishNode(node$2, "ImportSpecifier")); - } - return nodes - }; - - // Set `ExpressionStatement#directive` property for directive prologues. - pp$1.adaptDirectivePrologue = function(statements) { - for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { - statements[i].directive = statements[i].expression.raw.slice(1, -1); - } - }; - pp$1.isDirectiveCandidate = function(statement) { - return ( - statement.type === "ExpressionStatement" && - statement.expression.type === "Literal" && - typeof statement.expression.value === "string" && - // Reject parenthesized strings. - (this.input[statement.start] === "\"" || this.input[statement.start] === "'") - ) - }; - - var pp$2 = Parser.prototype; - - // Convert existing expression atom to assignable pattern - // if possible. - - pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { - if (this.options.ecmaVersion >= 6 && node) { - switch (node.type) { - case "Identifier": - if (this.inAsync && node.name === "await") - { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } - break - - case "ObjectPattern": - case "ArrayPattern": - case "AssignmentPattern": - case "RestElement": - break - - case "ObjectExpression": - node.type = "ObjectPattern"; - if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - for (var i = 0, list = node.properties; i < list.length; i += 1) { - var prop = list[i]; - - this.toAssignable(prop, isBinding); - // Early error: - // AssignmentRestProperty[Yield, Await] : - // `...` DestructuringAssignmentTarget[Yield, Await] - // - // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. - if ( - prop.type === "RestElement" && - (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") - ) { - this.raise(prop.argument.start, "Unexpected token"); - } - } - break - - case "Property": - // AssignmentProperty has type === "Property" - if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } - this.toAssignable(node.value, isBinding); - break - - case "ArrayExpression": - node.type = "ArrayPattern"; - if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - this.toAssignableList(node.elements, isBinding); - break - - case "SpreadElement": - node.type = "RestElement"; - this.toAssignable(node.argument, isBinding); - if (node.argument.type === "AssignmentPattern") - { this.raise(node.argument.start, "Rest elements cannot have a default value"); } - break - - case "AssignmentExpression": - if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } - node.type = "AssignmentPattern"; - delete node.operator; - this.toAssignable(node.left, isBinding); - break - - case "ParenthesizedExpression": - this.toAssignable(node.expression, isBinding, refDestructuringErrors); - break - - case "ChainExpression": - this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); - break - - case "MemberExpression": - if (!isBinding) { break } - - default: - this.raise(node.start, "Assigning to rvalue"); - } - } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - return node - }; - - // Convert list of expression atoms to binding list. - - pp$2.toAssignableList = function(exprList, isBinding) { - var end = exprList.length; - for (var i = 0; i < end; i++) { - var elt = exprList[i]; - if (elt) { this.toAssignable(elt, isBinding); } - } - if (end) { - var last = exprList[end - 1]; - if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") - { this.unexpected(last.argument.start); } - } - return exprList - }; - - // Parses spread element. - - pp$2.parseSpread = function(refDestructuringErrors) { - var node = this.startNode(); - this.next(); - node.argument = this.parseMaybeAssign(false, refDestructuringErrors); - return this.finishNode(node, "SpreadElement") - }; - - pp$2.parseRestBinding = function() { - var node = this.startNode(); - this.next(); - - // RestElement inside of a function parameter must be an identifier - if (this.options.ecmaVersion === 6 && this.type !== types.name) - { this.unexpected(); } - - node.argument = this.parseBindingAtom(); - - return this.finishNode(node, "RestElement") - }; - - // Parses lvalue (assignable) atom. - - pp$2.parseBindingAtom = function() { - if (this.options.ecmaVersion >= 6) { - switch (this.type) { - case types.bracketL: - var node = this.startNode(); - this.next(); - node.elements = this.parseBindingList(types.bracketR, true, true); - return this.finishNode(node, "ArrayPattern") - - case types.braceL: - return this.parseObj(true) - } - } - return this.parseIdent() - }; - - pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { - var elts = [], first = true; - while (!this.eat(close)) { - if (first) { first = false; } - else { this.expect(types.comma); } - if (allowEmpty && this.type === types.comma) { - elts.push(null); - } else if (allowTrailingComma && this.afterTrailingComma(close)) { - break - } else if (this.type === types.ellipsis) { - var rest = this.parseRestBinding(); - this.parseBindingListItem(rest); - elts.push(rest); - if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } - this.expect(close); - break - } else { - var elem = this.parseMaybeDefault(this.start, this.startLoc); - this.parseBindingListItem(elem); - elts.push(elem); - } - } - return elts - }; - - pp$2.parseBindingListItem = function(param) { - return param - }; - - // Parses assignment pattern around given atom if possible. - - pp$2.parseMaybeDefault = function(startPos, startLoc, left) { - left = left || this.parseBindingAtom(); - if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left } - var node = this.startNodeAt(startPos, startLoc); - node.left = left; - node.right = this.parseMaybeAssign(); - return this.finishNode(node, "AssignmentPattern") - }; - - // The following three functions all verify that a node is an lvalue — - // something that can be bound, or assigned to. In order to do so, they perform - // a variety of checks: - // - // - Check that none of the bound/assigned-to identifiers are reserved words. - // - Record name declarations for bindings in the appropriate scope. - // - Check duplicate argument names, if checkClashes is set. - // - // If a complex binding pattern is encountered (e.g., object and array - // destructuring), the entire pattern is recursively checked. - // - // There are three versions of checkLVal*() appropriate for different - // circumstances: - // - // - checkLValSimple() shall be used if the syntactic construct supports - // nothing other than identifiers and member expressions. Parenthesized - // expressions are also correctly handled. This is generally appropriate for - // constructs for which the spec says - // - // > It is a Syntax Error if AssignmentTargetType of [the production] is not - // > simple. - // - // It is also appropriate for checking if an identifier is valid and not - // defined elsewhere, like import declarations or function/class identifiers. - // - // Examples where this is used include: - // a += …; - // import a from '…'; - // where a is the node to be checked. - // - // - checkLValPattern() shall be used if the syntactic construct supports - // anything checkLValSimple() supports, as well as object and array - // destructuring patterns. This is generally appropriate for constructs for - // which the spec says - // - // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor - // > an ArrayLiteral and AssignmentTargetType of [the production] is not - // > simple. - // - // Examples where this is used include: - // (a = …); - // const a = …; - // try { … } catch (a) { … } - // where a is the node to be checked. - // - // - checkLValInnerPattern() shall be used if the syntactic construct supports - // anything checkLValPattern() supports, as well as default assignment - // patterns, rest elements, and other constructs that may appear within an - // object or array destructuring pattern. - // - // As a special case, function parameters also use checkLValInnerPattern(), - // as they also support defaults and rest constructs. - // - // These functions deliberately support both assignment and binding constructs, - // as the logic for both is exceedingly similar. If the node is the target of - // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it - // should be set to the appropriate BIND_* constant, like BIND_VAR or - // BIND_LEXICAL. - // - // If the function is called with a non-BIND_NONE bindingType, then - // additionally a checkClashes object may be specified to allow checking for - // duplicate argument names. checkClashes is ignored if the provided construct - // is an assignment (i.e., bindingType is BIND_NONE). - - pp$2.checkLValSimple = function(expr, bindingType, checkClashes) { - if ( bindingType === void 0 ) bindingType = BIND_NONE; - - var isBind = bindingType !== BIND_NONE; - - switch (expr.type) { - case "Identifier": - if (this.strict && this.reservedWordsStrictBind.test(expr.name)) - { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } - if (isBind) { - if (bindingType === BIND_LEXICAL && expr.name === "let") - { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } - if (checkClashes) { - if (has(checkClashes, expr.name)) - { this.raiseRecoverable(expr.start, "Argument name clash"); } - checkClashes[expr.name] = true; - } - if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } - } - break - - case "ChainExpression": - this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); - break - - case "MemberExpression": - if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } - break - - case "ParenthesizedExpression": - if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } - return this.checkLValSimple(expr.expression, bindingType, checkClashes) - - default: - this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); - } - }; - - pp$2.checkLValPattern = function(expr, bindingType, checkClashes) { - if ( bindingType === void 0 ) bindingType = BIND_NONE; - - switch (expr.type) { - case "ObjectPattern": - for (var i = 0, list = expr.properties; i < list.length; i += 1) { - var prop = list[i]; - - this.checkLValInnerPattern(prop, bindingType, checkClashes); - } - break - - case "ArrayPattern": - for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { - var elem = list$1[i$1]; - - if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } - } - break - - default: - this.checkLValSimple(expr, bindingType, checkClashes); - } - }; - - pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) { - if ( bindingType === void 0 ) bindingType = BIND_NONE; - - switch (expr.type) { - case "Property": - // AssignmentProperty has type === "Property" - this.checkLValInnerPattern(expr.value, bindingType, checkClashes); - break - - case "AssignmentPattern": - this.checkLValPattern(expr.left, bindingType, checkClashes); - break - - case "RestElement": - this.checkLValPattern(expr.argument, bindingType, checkClashes); - break - - default: - this.checkLValPattern(expr, bindingType, checkClashes); - } - }; - - // The algorithm used to determine whether a regexp can appear at a - - var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { - this.token = token; - this.isExpr = !!isExpr; - this.preserveSpace = !!preserveSpace; - this.override = override; - this.generator = !!generator; - }; - - var types$1 = { - b_stat: new TokContext("{", false), - b_expr: new TokContext("{", true), - b_tmpl: new TokContext("${", false), - p_stat: new TokContext("(", false), - p_expr: new TokContext("(", true), - q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), - f_stat: new TokContext("function", false), - f_expr: new TokContext("function", true), - f_expr_gen: new TokContext("function", true, false, null, true), - f_gen: new TokContext("function", false, false, null, true) - }; - - var pp$3 = Parser.prototype; - - pp$3.initialContext = function() { - return [types$1.b_stat] - }; - - pp$3.curContext = function() { - return this.context[this.context.length - 1] - }; - - pp$3.braceIsBlock = function(prevType) { - var parent = this.curContext(); - if (parent === types$1.f_expr || parent === types$1.f_stat) - { return true } - if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) - { return !parent.isExpr } - - // The check for `tt.name && exprAllowed` detects whether we are - // after a `yield` or `of` construct. See the `updateContext` for - // `tt.name`. - if (prevType === types._return || prevType === types.name && this.exprAllowed) - { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } - if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) - { return true } - if (prevType === types.braceL) - { return parent === types$1.b_stat } - if (prevType === types._var || prevType === types._const || prevType === types.name) - { return false } - return !this.exprAllowed - }; - - pp$3.inGeneratorContext = function() { - for (var i = this.context.length - 1; i >= 1; i--) { - var context = this.context[i]; - if (context.token === "function") - { return context.generator } - } - return false - }; - - pp$3.updateContext = function(prevType) { - var update, type = this.type; - if (type.keyword && prevType === types.dot) - { this.exprAllowed = false; } - else if (update = type.updateContext) - { update.call(this, prevType); } - else - { this.exprAllowed = type.beforeExpr; } - }; - - // Used to handle egde case when token context could not be inferred correctly in tokenize phase - pp$3.overrideContext = function(tokenCtx) { - if (this.curContext() !== tokenCtx) { - this.context[this.context.length - 1] = tokenCtx; - } - }; - - // Token-specific context update code - - types.parenR.updateContext = types.braceR.updateContext = function() { - if (this.context.length === 1) { - this.exprAllowed = true; - return - } - var out = this.context.pop(); - if (out === types$1.b_stat && this.curContext().token === "function") { - out = this.context.pop(); - } - this.exprAllowed = !out.isExpr; - }; - - types.braceL.updateContext = function(prevType) { - this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); - this.exprAllowed = true; - }; - - types.dollarBraceL.updateContext = function() { - this.context.push(types$1.b_tmpl); - this.exprAllowed = true; - }; - - types.parenL.updateContext = function(prevType) { - var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; - this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); - this.exprAllowed = true; - }; - - types.incDec.updateContext = function() { - // tokExprAllowed stays unchanged - }; - - types._function.updateContext = types._class.updateContext = function(prevType) { - if (prevType.beforeExpr && prevType !== types._else && - !(prevType === types.semi && this.curContext() !== types$1.p_stat) && - !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && - !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) - { this.context.push(types$1.f_expr); } - else - { this.context.push(types$1.f_stat); } - this.exprAllowed = false; - }; - - types.backQuote.updateContext = function() { - if (this.curContext() === types$1.q_tmpl) - { this.context.pop(); } - else - { this.context.push(types$1.q_tmpl); } - this.exprAllowed = false; - }; - - types.star.updateContext = function(prevType) { - if (prevType === types._function) { - var index = this.context.length - 1; - if (this.context[index] === types$1.f_expr) - { this.context[index] = types$1.f_expr_gen; } - else - { this.context[index] = types$1.f_gen; } - } - this.exprAllowed = true; - }; - - types.name.updateContext = function(prevType) { - var allowed = false; - if (this.options.ecmaVersion >= 6 && prevType !== types.dot) { - if (this.value === "of" && !this.exprAllowed || - this.value === "yield" && this.inGeneratorContext()) - { allowed = true; } - } - this.exprAllowed = allowed; - }; - - // A recursive descent parser operates by defining functions for all - - var pp$4 = Parser.prototype; - - // Check if property name clashes with already added. - // Object/class getters and setters are not allowed to clash — - // either with each other or with an init property — and in - // strict mode, init properties are also not allowed to be repeated. - - pp$4.checkPropClash = function(prop, propHash, refDestructuringErrors) { - if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") - { return } - if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) - { return } - var key = prop.key; - var name; - switch (key.type) { - case "Identifier": name = key.name; break - case "Literal": name = String(key.value); break - default: return - } - var kind = prop.kind; - if (this.options.ecmaVersion >= 6) { - if (name === "__proto__" && kind === "init") { - if (propHash.proto) { - if (refDestructuringErrors) { - if (refDestructuringErrors.doubleProto < 0) - { refDestructuringErrors.doubleProto = key.start; } - // Backwards-compat kludge. Can be removed in version 6.0 - } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } - } - propHash.proto = true; - } - return - } - name = "$" + name; - var other = propHash[name]; - if (other) { - var redefinition; - if (kind === "init") { - redefinition = this.strict && other.init || other.get || other.set; - } else { - redefinition = other.init || other[kind]; - } - if (redefinition) - { this.raiseRecoverable(key.start, "Redefinition of property"); } - } else { - other = propHash[name] = { - init: false, - get: false, - set: false - }; - } - other[kind] = true; - }; - - // ### Expression parsing - - // These nest, from the most general expression type at the top to - // 'atomic', nondivisible expression types at the bottom. Most of - // the functions will simply let the function(s) below them parse, - // and, *if* the syntactic construct they handle is present, wrap - // the AST node that the inner parser gave them in another node. - - // Parse a full expression. The optional arguments are used to - // forbid the `in` operator (in for loops initalization expressions) - // and provide reference for storing '=' operator inside shorthand - // property assignment in contexts where both object expression - // and object pattern might appear (so it's possible to raise - // delayed syntax error at correct position). - - pp$4.parseExpression = function(forInit, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); - if (this.type === types.comma) { - var node = this.startNodeAt(startPos, startLoc); - node.expressions = [expr]; - while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } - return this.finishNode(node, "SequenceExpression") - } - return expr - }; - - // Parse an assignment expression. This includes applications of - // operators like `+=`. - - pp$4.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { - if (this.isContextual("yield")) { - if (this.inGenerator) { return this.parseYield(forInit) } - // The tokenizer will assume an expression is allowed after - // `yield`, but this isn't that kind of yield - else { this.exprAllowed = false; } - } - - var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1; - if (refDestructuringErrors) { - oldParenAssign = refDestructuringErrors.parenthesizedAssign; - oldTrailingComma = refDestructuringErrors.trailingComma; - refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; - } else { - refDestructuringErrors = new DestructuringErrors; - ownDestructuringErrors = true; - } - - var startPos = this.start, startLoc = this.startLoc; - if (this.type === types.parenL || this.type === types.name) { - this.potentialArrowAt = this.start; - this.potentialArrowInForAwait = forInit === "await"; - } - var left = this.parseMaybeConditional(forInit, refDestructuringErrors); - if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } - if (this.type.isAssign) { - var node = this.startNodeAt(startPos, startLoc); - node.operator = this.value; - if (this.type === types.eq) - { left = this.toAssignable(left, false, refDestructuringErrors); } - if (!ownDestructuringErrors) { - refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; - } - if (refDestructuringErrors.shorthandAssign >= left.start) - { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly - if (this.type === types.eq) - { this.checkLValPattern(left); } - else - { this.checkLValSimple(left); } - node.left = left; - this.next(); - node.right = this.parseMaybeAssign(forInit); - return this.finishNode(node, "AssignmentExpression") - } else { - if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } - } - if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } - if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } - return left - }; - - // Parse a ternary conditional (`?:`) operator. - - pp$4.parseMaybeConditional = function(forInit, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseExprOps(forInit, refDestructuringErrors); - if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } - if (this.eat(types.question)) { - var node = this.startNodeAt(startPos, startLoc); - node.test = expr; - node.consequent = this.parseMaybeAssign(); - this.expect(types.colon); - node.alternate = this.parseMaybeAssign(forInit); - return this.finishNode(node, "ConditionalExpression") - } - return expr - }; - - // Start the precedence parser. - - pp$4.parseExprOps = function(forInit, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); - if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } - return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) - }; - - // Parse binary operators with the operator precedence parsing - // algorithm. `left` is the left-hand side of the operator. - // `minPrec` provides context that allows the function to stop and - // defer further parser to one of its callers when it encounters an - // operator that has a lower precedence than the set it is parsing. - - pp$4.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { - var prec = this.type.binop; - if (prec != null && (!forInit || this.type !== types._in)) { - if (prec > minPrec) { - var logical = this.type === types.logicalOR || this.type === types.logicalAND; - var coalesce = this.type === types.coalesce; - if (coalesce) { - // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. - // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. - prec = types.logicalAND.binop; - } - var op = this.value; - this.next(); - var startPos = this.start, startLoc = this.startLoc; - var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); - var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); - if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) { - this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); - } - return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) - } - } - return left - }; - - pp$4.buildBinary = function(startPos, startLoc, left, right, op, logical) { - var node = this.startNodeAt(startPos, startLoc); - node.left = left; - node.operator = op; - node.right = right; - return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") - }; - - // Parse unary operators, both prefix and postfix. - - pp$4.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { - var startPos = this.start, startLoc = this.startLoc, expr; - if (this.isContextual("await") && this.canAwait) { - expr = this.parseAwait(forInit); - sawUnary = true; - } else if (this.type.prefix) { - var node = this.startNode(), update = this.type === types.incDec; - node.operator = this.value; - node.prefix = true; - this.next(); - node.argument = this.parseMaybeUnary(null, true, update, forInit); - this.checkExpressionErrors(refDestructuringErrors, true); - if (update) { this.checkLValSimple(node.argument); } - else if (this.strict && node.operator === "delete" && - node.argument.type === "Identifier") - { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } - else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) - { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } - else { sawUnary = true; } - expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); - } else { - expr = this.parseExprSubscripts(refDestructuringErrors, forInit); - if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } - while (this.type.postfix && !this.canInsertSemicolon()) { - var node$1 = this.startNodeAt(startPos, startLoc); - node$1.operator = this.value; - node$1.prefix = false; - node$1.argument = expr; - this.checkLValSimple(expr); - this.next(); - expr = this.finishNode(node$1, "UpdateExpression"); - } - } - - if (!incDec && this.eat(types.starstar)) { - if (sawUnary) - { this.unexpected(this.lastTokStart); } - else - { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } - } else { - return expr - } - }; - - function isPrivateFieldAccess(node) { - return ( - node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || - node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) - ) - } - - // Parse call, dot, and `[]`-subscript expressions. - - pp$4.parseExprSubscripts = function(refDestructuringErrors, forInit) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseExprAtom(refDestructuringErrors, forInit); - if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") - { return expr } - var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); - if (refDestructuringErrors && result.type === "MemberExpression") { - if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } - if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } - if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } - } - return result - }; - - pp$4.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { - var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && - this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && - this.potentialArrowAt === base.start; - var optionalChained = false; - - while (true) { - var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); - - if (element.optional) { optionalChained = true; } - if (element === base || element.type === "ArrowFunctionExpression") { - if (optionalChained) { - var chainNode = this.startNodeAt(startPos, startLoc); - chainNode.expression = element; - element = this.finishNode(chainNode, "ChainExpression"); - } - return element - } - - base = element; - } - }; - - pp$4.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { - var optionalSupported = this.options.ecmaVersion >= 11; - var optional = optionalSupported && this.eat(types.questionDot); - if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } - - var computed = this.eat(types.bracketL); - if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) { - var node = this.startNodeAt(startPos, startLoc); - node.object = base; - if (computed) { - node.property = this.parseExpression(); - this.expect(types.bracketR); - } else if (this.type === types.privateId && base.type !== "Super") { - node.property = this.parsePrivateIdent(); - } else { - node.property = this.parseIdent(this.options.allowReserved !== "never"); - } - node.computed = !!computed; - if (optionalSupported) { - node.optional = optional; - } - base = this.finishNode(node, "MemberExpression"); - } else if (!noCalls && this.eat(types.parenL)) { - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); - if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) { - this.checkPatternErrors(refDestructuringErrors, false); - this.checkYieldAwaitInDefaultParams(); - if (this.awaitIdentPos > 0) - { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) - } - this.checkExpressionErrors(refDestructuringErrors, true); - this.yieldPos = oldYieldPos || this.yieldPos; - this.awaitPos = oldAwaitPos || this.awaitPos; - this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; - var node$1 = this.startNodeAt(startPos, startLoc); - node$1.callee = base; - node$1.arguments = exprList; - if (optionalSupported) { - node$1.optional = optional; - } - base = this.finishNode(node$1, "CallExpression"); - } else if (this.type === types.backQuote) { - if (optional || optionalChained) { - this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); - } - var node$2 = this.startNodeAt(startPos, startLoc); - node$2.tag = base; - node$2.quasi = this.parseTemplate({isTagged: true}); - base = this.finishNode(node$2, "TaggedTemplateExpression"); - } - return base - }; - - // Parse an atomic expression — either a single token that is an - // expression, an expression started by a keyword like `function` or - // `new`, or an expression wrapped in punctuation like `()`, `[]`, - // or `{}`. - - pp$4.parseExprAtom = function(refDestructuringErrors, forInit) { - // If a division operator appears in an expression position, the - // tokenizer got confused, and we force it to read a regexp instead. - if (this.type === types.slash) { this.readRegexp(); } - - var node, canBeArrow = this.potentialArrowAt === this.start; - switch (this.type) { - case types._super: - if (!this.allowSuper) - { this.raise(this.start, "'super' keyword outside a method"); } - node = this.startNode(); - this.next(); - if (this.type === types.parenL && !this.allowDirectSuper) - { this.raise(node.start, "super() call outside constructor of a subclass"); } - // The `super` keyword can appear at below: - // SuperProperty: - // super [ Expression ] - // super . IdentifierName - // SuperCall: - // super ( Arguments ) - if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) - { this.unexpected(); } - return this.finishNode(node, "Super") - - case types._this: - node = this.startNode(); - this.next(); - return this.finishNode(node, "ThisExpression") - - case types.name: - var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; - var id = this.parseIdent(false); - if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) { - this.overrideContext(types$1.f_expr); - return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) - } - if (canBeArrow && !this.canInsertSemicolon()) { - if (this.eat(types.arrow)) - { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } - if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc && - (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { - id = this.parseIdent(false); - if (this.canInsertSemicolon() || !this.eat(types.arrow)) - { this.unexpected(); } - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) - } - } - return id - - case types.regexp: - var value = this.value; - node = this.parseLiteral(value.value); - node.regex = {pattern: value.pattern, flags: value.flags}; - return node - - case types.num: case types.string: - return this.parseLiteral(this.value) - - case types._null: case types._true: case types._false: - node = this.startNode(); - node.value = this.type === types._null ? null : this.type === types._true; - node.raw = this.type.keyword; - this.next(); - return this.finishNode(node, "Literal") - - case types.parenL: - var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); - if (refDestructuringErrors) { - if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) - { refDestructuringErrors.parenthesizedAssign = start; } - if (refDestructuringErrors.parenthesizedBind < 0) - { refDestructuringErrors.parenthesizedBind = start; } - } - return expr - - case types.bracketL: - node = this.startNode(); - this.next(); - node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); - return this.finishNode(node, "ArrayExpression") - - case types.braceL: - this.overrideContext(types$1.b_expr); - return this.parseObj(false, refDestructuringErrors) - - case types._function: - node = this.startNode(); - this.next(); - return this.parseFunction(node, 0) - - case types._class: - return this.parseClass(this.startNode(), false) - - case types._new: - return this.parseNew() - - case types.backQuote: - return this.parseTemplate() - - case types._import: - if (this.options.ecmaVersion >= 11) { - return this.parseExprImport() - } else { - return this.unexpected() - } - - default: - this.unexpected(); - } - }; - - pp$4.parseExprImport = function() { - var node = this.startNode(); - - // Consume `import` as an identifier for `import.meta`. - // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. - if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } - var meta = this.parseIdent(true); - - switch (this.type) { - case types.parenL: - return this.parseDynamicImport(node) - case types.dot: - node.meta = meta; - return this.parseImportMeta(node) - default: - this.unexpected(); - } - }; - - pp$4.parseDynamicImport = function(node) { - this.next(); // skip `(` - - // Parse node.source. - node.source = this.parseMaybeAssign(); - - // Verify ending. - if (!this.eat(types.parenR)) { - var errorPos = this.start; - if (this.eat(types.comma) && this.eat(types.parenR)) { - this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); - } else { - this.unexpected(errorPos); - } - } - - return this.finishNode(node, "ImportExpression") - }; - - pp$4.parseImportMeta = function(node) { - this.next(); // skip `.` - - var containsEsc = this.containsEsc; - node.property = this.parseIdent(true); - - if (node.property.name !== "meta") - { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } - if (containsEsc) - { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } - if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) - { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } - - return this.finishNode(node, "MetaProperty") - }; - - pp$4.parseLiteral = function(value) { - var node = this.startNode(); - node.value = value; - node.raw = this.input.slice(this.start, this.end); - if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } - this.next(); - return this.finishNode(node, "Literal") - }; - - pp$4.parseParenExpression = function() { - this.expect(types.parenL); - var val = this.parseExpression(); - this.expect(types.parenR); - return val - }; - - pp$4.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { - var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; - if (this.options.ecmaVersion >= 6) { - this.next(); - - var innerStartPos = this.start, innerStartLoc = this.startLoc; - var exprList = [], first = true, lastIsComma = false; - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; - this.yieldPos = 0; - this.awaitPos = 0; - // Do not save awaitIdentPos to allow checking awaits nested in parameters - while (this.type !== types.parenR) { - first ? first = false : this.expect(types.comma); - if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) { - lastIsComma = true; - break - } else if (this.type === types.ellipsis) { - spreadStart = this.start; - exprList.push(this.parseParenItem(this.parseRestBinding())); - if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } - break - } else { - exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); - } - } - var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; - this.expect(types.parenR); - - if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { - this.checkPatternErrors(refDestructuringErrors, false); - this.checkYieldAwaitInDefaultParams(); - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - return this.parseParenArrowList(startPos, startLoc, exprList, forInit) - } - - if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } - if (spreadStart) { this.unexpected(spreadStart); } - this.checkExpressionErrors(refDestructuringErrors, true); - this.yieldPos = oldYieldPos || this.yieldPos; - this.awaitPos = oldAwaitPos || this.awaitPos; - - if (exprList.length > 1) { - val = this.startNodeAt(innerStartPos, innerStartLoc); - val.expressions = exprList; - this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); - } else { - val = exprList[0]; - } - } else { - val = this.parseParenExpression(); - } - - if (this.options.preserveParens) { - var par = this.startNodeAt(startPos, startLoc); - par.expression = val; - return this.finishNode(par, "ParenthesizedExpression") - } else { - return val - } - }; - - pp$4.parseParenItem = function(item) { - return item - }; - - pp$4.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, forInit) - }; - - // New's precedence is slightly tricky. It must allow its argument to - // be a `[]` or dot subscript expression, but not a call — at least, - // not without wrapping it in parentheses. Thus, it uses the noCalls - // argument to parseSubscripts to prevent it from consuming the - // argument list. - - var empty$1 = []; - - pp$4.parseNew = function() { - if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } - var node = this.startNode(); - var meta = this.parseIdent(true); - if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) { - node.meta = meta; - var containsEsc = this.containsEsc; - node.property = this.parseIdent(true); - if (node.property.name !== "target") - { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } - if (containsEsc) - { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } - if (!this.allowNewDotTarget) - { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } - return this.finishNode(node, "MetaProperty") - } - var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import; - node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false); - if (isImport && node.callee.type === "ImportExpression") { - this.raise(startPos, "Cannot use new with import()"); - } - if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); } - else { node.arguments = empty$1; } - return this.finishNode(node, "NewExpression") - }; - - // Parse template expression. - - pp$4.parseTemplateElement = function(ref) { - var isTagged = ref.isTagged; - - var elem = this.startNode(); - if (this.type === types.invalidTemplate) { - if (!isTagged) { - this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); - } - elem.value = { - raw: this.value, - cooked: null - }; - } else { - elem.value = { - raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), - cooked: this.value - }; - } - this.next(); - elem.tail = this.type === types.backQuote; - return this.finishNode(elem, "TemplateElement") - }; - - pp$4.parseTemplate = function(ref) { - if ( ref === void 0 ) ref = {}; - var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; - - var node = this.startNode(); - this.next(); - node.expressions = []; - var curElt = this.parseTemplateElement({isTagged: isTagged}); - node.quasis = [curElt]; - while (!curElt.tail) { - if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); } - this.expect(types.dollarBraceL); - node.expressions.push(this.parseExpression()); - this.expect(types.braceR); - node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); - } - this.next(); - return this.finishNode(node, "TemplateLiteral") - }; - - pp$4.isAsyncProp = function(prop) { - return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && - (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) && - !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) - }; - - // Parse an object literal or binding pattern. - - pp$4.parseObj = function(isPattern, refDestructuringErrors) { - var node = this.startNode(), first = true, propHash = {}; - node.properties = []; - this.next(); - while (!this.eat(types.braceR)) { - if (!first) { - this.expect(types.comma); - if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break } - } else { first = false; } - - var prop = this.parseProperty(isPattern, refDestructuringErrors); - if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } - node.properties.push(prop); - } - return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") - }; - - pp$4.parseProperty = function(isPattern, refDestructuringErrors) { - var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; - if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { - if (isPattern) { - prop.argument = this.parseIdent(false); - if (this.type === types.comma) { - this.raise(this.start, "Comma is not permitted after the rest element"); - } - return this.finishNode(prop, "RestElement") - } - // To disallow parenthesized identifier via `this.toAssignable()`. - if (this.type === types.parenL && refDestructuringErrors) { - if (refDestructuringErrors.parenthesizedAssign < 0) { - refDestructuringErrors.parenthesizedAssign = this.start; - } - if (refDestructuringErrors.parenthesizedBind < 0) { - refDestructuringErrors.parenthesizedBind = this.start; - } - } - // Parse argument. - prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); - // To disallow trailing comma via `this.toAssignable()`. - if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { - refDestructuringErrors.trailingComma = this.start; - } - // Finish - return this.finishNode(prop, "SpreadElement") - } - if (this.options.ecmaVersion >= 6) { - prop.method = false; - prop.shorthand = false; - if (isPattern || refDestructuringErrors) { - startPos = this.start; - startLoc = this.startLoc; - } - if (!isPattern) - { isGenerator = this.eat(types.star); } - } - var containsEsc = this.containsEsc; - this.parsePropertyName(prop); - if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { - isAsync = true; - isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); - this.parsePropertyName(prop, refDestructuringErrors); - } else { - isAsync = false; - } - this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); - return this.finishNode(prop, "Property") - }; - - pp$4.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { - if ((isGenerator || isAsync) && this.type === types.colon) - { this.unexpected(); } - - if (this.eat(types.colon)) { - prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); - prop.kind = "init"; - } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) { - if (isPattern) { this.unexpected(); } - prop.kind = "init"; - prop.method = true; - prop.value = this.parseMethod(isGenerator, isAsync); - } else if (!isPattern && !containsEsc && - this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && - (prop.key.name === "get" || prop.key.name === "set") && - (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) { - if (isGenerator || isAsync) { this.unexpected(); } - prop.kind = prop.key.name; - this.parsePropertyName(prop); - prop.value = this.parseMethod(false); - var paramCount = prop.kind === "get" ? 0 : 1; - if (prop.value.params.length !== paramCount) { - var start = prop.value.start; - if (prop.kind === "get") - { this.raiseRecoverable(start, "getter should have no params"); } - else - { this.raiseRecoverable(start, "setter should have exactly one param"); } - } else { - if (prop.kind === "set" && prop.value.params[0].type === "RestElement") - { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } - } - } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { - if (isGenerator || isAsync) { this.unexpected(); } - this.checkUnreserved(prop.key); - if (prop.key.name === "await" && !this.awaitIdentPos) - { this.awaitIdentPos = startPos; } - prop.kind = "init"; - if (isPattern) { - prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); - } else if (this.type === types.eq && refDestructuringErrors) { - if (refDestructuringErrors.shorthandAssign < 0) - { refDestructuringErrors.shorthandAssign = this.start; } - prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); - } else { - prop.value = this.copyNode(prop.key); - } - prop.shorthand = true; - } else { this.unexpected(); } - }; - - pp$4.parsePropertyName = function(prop) { - if (this.options.ecmaVersion >= 6) { - if (this.eat(types.bracketL)) { - prop.computed = true; - prop.key = this.parseMaybeAssign(); - this.expect(types.bracketR); - return prop.key - } else { - prop.computed = false; - } - } - return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") - }; - - // Initialize empty function node. - - pp$4.initFunction = function(node) { - node.id = null; - if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } - if (this.options.ecmaVersion >= 8) { node.async = false; } - }; - - // Parse object or class method. - - pp$4.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { - var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - - this.initFunction(node); - if (this.options.ecmaVersion >= 6) - { node.generator = isGenerator; } - if (this.options.ecmaVersion >= 8) - { node.async = !!isAsync; } - - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); - - this.expect(types.parenL); - node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); - this.checkYieldAwaitInDefaultParams(); - this.parseFunctionBody(node, false, true, false); - - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, "FunctionExpression") - }; - - // Parse arrow function expression with given parameters. - - pp$4.parseArrowExpression = function(node, params, isAsync, forInit) { - var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - - this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); - this.initFunction(node); - if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } - - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - - node.params = this.toAssignableList(params, true); - this.parseFunctionBody(node, true, false, forInit); - - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, "ArrowFunctionExpression") - }; - - // Parse function body and check parameters. - - pp$4.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { - var isExpression = isArrowFunction && this.type !== types.braceL; - var oldStrict = this.strict, useStrict = false; - - if (isExpression) { - node.body = this.parseMaybeAssign(forInit); - node.expression = true; - this.checkParams(node, false); - } else { - var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); - if (!oldStrict || nonSimple) { - useStrict = this.strictDirective(this.end); - // If this is a strict mode function, verify that argument names - // are not repeated, and it does not try to bind the words `eval` - // or `arguments`. - if (useStrict && nonSimple) - { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } - } - // Start a new scope with regard to labels and the `inFunction` - // flag (restore them to their old value afterwards). - var oldLabels = this.labels; - this.labels = []; - if (useStrict) { this.strict = true; } - - // Add the params to varDeclaredNames to ensure that an error is thrown - // if a let/const declaration in the function clashes with one of the params. - this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); - // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' - if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } - node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); - node.expression = false; - this.adaptDirectivePrologue(node.body.body); - this.labels = oldLabels; - } - this.exitScope(); - }; - - pp$4.isSimpleParamList = function(params) { - for (var i = 0, list = params; i < list.length; i += 1) - { - var param = list[i]; - - if (param.type !== "Identifier") { return false - } } - return true - }; - - // Checks function params for various disallowed patterns such as using "eval" - // or "arguments" and duplicate parameters. - - pp$4.checkParams = function(node, allowDuplicates) { - var nameHash = Object.create(null); - for (var i = 0, list = node.params; i < list.length; i += 1) - { - var param = list[i]; - - this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); - } - }; - - // Parses a comma-separated list of expressions, and returns them as - // an array. `close` is the token type that ends the list, and - // `allowEmpty` can be turned on to allow subsequent commas with - // nothing in between them to be parsed as `null` (which is needed - // for array literals). - - pp$4.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { - var elts = [], first = true; - while (!this.eat(close)) { - if (!first) { - this.expect(types.comma); - if (allowTrailingComma && this.afterTrailingComma(close)) { break } - } else { first = false; } - - var elt = (void 0); - if (allowEmpty && this.type === types.comma) - { elt = null; } - else if (this.type === types.ellipsis) { - elt = this.parseSpread(refDestructuringErrors); - if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0) - { refDestructuringErrors.trailingComma = this.start; } - } else { - elt = this.parseMaybeAssign(false, refDestructuringErrors); - } - elts.push(elt); - } - return elts - }; - - pp$4.checkUnreserved = function(ref) { - var start = ref.start; - var end = ref.end; - var name = ref.name; - - if (this.inGenerator && name === "yield") - { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } - if (this.inAsync && name === "await") - { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } - if (this.currentThisScope().inClassFieldInit && name === "arguments") - { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } - if (this.inClassStaticBlock && (name === "arguments" || name === "await")) - { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } - if (this.keywords.test(name)) - { this.raise(start, ("Unexpected keyword '" + name + "'")); } - if (this.options.ecmaVersion < 6 && - this.input.slice(start, end).indexOf("\\") !== -1) { return } - var re = this.strict ? this.reservedWordsStrict : this.reservedWords; - if (re.test(name)) { - if (!this.inAsync && name === "await") - { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } - this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); - } - }; - - // Parse the next token as an identifier. If `liberal` is true (used - // when parsing properties), it will also convert keywords into - // identifiers. - - pp$4.parseIdent = function(liberal, isBinding) { - var node = this.startNode(); - if (this.type === types.name) { - node.name = this.value; - } else if (this.type.keyword) { - node.name = this.type.keyword; - - // To fix https://github.com/acornjs/acorn/issues/575 - // `class` and `function` keywords push new context into this.context. - // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. - // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword - if ((node.name === "class" || node.name === "function") && - (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { - this.context.pop(); - } - } else { - this.unexpected(); - } - this.next(!!liberal); - this.finishNode(node, "Identifier"); - if (!liberal) { - this.checkUnreserved(node); - if (node.name === "await" && !this.awaitIdentPos) - { this.awaitIdentPos = node.start; } - } - return node - }; - - pp$4.parsePrivateIdent = function() { - var node = this.startNode(); - if (this.type === types.privateId) { - node.name = this.value; - } else { - this.unexpected(); - } - this.next(); - this.finishNode(node, "PrivateIdentifier"); - - // For validating existence - if (this.privateNameStack.length === 0) { - this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); - } else { - this.privateNameStack[this.privateNameStack.length - 1].used.push(node); - } - - return node - }; - - // Parses yield expression inside generator. - - pp$4.parseYield = function(forInit) { - if (!this.yieldPos) { this.yieldPos = this.start; } - - var node = this.startNode(); - this.next(); - if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) { - node.delegate = false; - node.argument = null; - } else { - node.delegate = this.eat(types.star); - node.argument = this.parseMaybeAssign(forInit); - } - return this.finishNode(node, "YieldExpression") - }; - - pp$4.parseAwait = function(forInit) { - if (!this.awaitPos) { this.awaitPos = this.start; } - - var node = this.startNode(); - this.next(); - node.argument = this.parseMaybeUnary(null, true, false, forInit); - return this.finishNode(node, "AwaitExpression") - }; - - var pp$5 = Parser.prototype; - - // This function is used to raise exceptions on parse errors. It - // takes an offset integer (into the current `input`) to indicate - // the location of the error, attaches the position to the end - // of the error message, and then raises a `SyntaxError` with that - // message. - - pp$5.raise = function(pos, message) { - var loc = getLineInfo(this.input, pos); - message += " (" + loc.line + ":" + loc.column + ")"; - var err = new SyntaxError(message); - err.pos = pos; err.loc = loc; err.raisedAt = this.pos; - throw err - }; - - pp$5.raiseRecoverable = pp$5.raise; - - pp$5.curPosition = function() { - if (this.options.locations) { - return new Position(this.curLine, this.pos - this.lineStart) - } - }; - - var pp$6 = Parser.prototype; - - var Scope = function Scope(flags) { - this.flags = flags; - // A list of var-declared names in the current lexical scope - this.var = []; - // A list of lexically-declared names in the current lexical scope - this.lexical = []; - // A list of lexically-declared FunctionDeclaration names in the current lexical scope - this.functions = []; - // A switch to disallow the identifier reference 'arguments' - this.inClassFieldInit = false; - }; - - // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. - - pp$6.enterScope = function(flags) { - this.scopeStack.push(new Scope(flags)); - }; - - pp$6.exitScope = function() { - this.scopeStack.pop(); - }; - - // The spec says: - // > At the top level of a function, or script, function declarations are - // > treated like var declarations rather than like lexical declarations. - pp$6.treatFunctionsAsVarInScope = function(scope) { - return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) - }; - - pp$6.declareName = function(name, bindingType, pos) { - var redeclared = false; - if (bindingType === BIND_LEXICAL) { - var scope = this.currentScope(); - redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; - scope.lexical.push(name); - if (this.inModule && (scope.flags & SCOPE_TOP)) - { delete this.undefinedExports[name]; } - } else if (bindingType === BIND_SIMPLE_CATCH) { - var scope$1 = this.currentScope(); - scope$1.lexical.push(name); - } else if (bindingType === BIND_FUNCTION) { - var scope$2 = this.currentScope(); - if (this.treatFunctionsAsVar) - { redeclared = scope$2.lexical.indexOf(name) > -1; } - else - { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } - scope$2.functions.push(name); - } else { - for (var i = this.scopeStack.length - 1; i >= 0; --i) { - var scope$3 = this.scopeStack[i]; - if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || - !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { - redeclared = true; - break - } - scope$3.var.push(name); - if (this.inModule && (scope$3.flags & SCOPE_TOP)) - { delete this.undefinedExports[name]; } - if (scope$3.flags & SCOPE_VAR) { break } - } - } - if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } - }; - - pp$6.checkLocalExport = function(id) { - // scope.functions must be empty as Module code is always strict. - if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && - this.scopeStack[0].var.indexOf(id.name) === -1) { - this.undefinedExports[id.name] = id; - } - }; - - pp$6.currentScope = function() { - return this.scopeStack[this.scopeStack.length - 1] - }; - - pp$6.currentVarScope = function() { - for (var i = this.scopeStack.length - 1;; i--) { - var scope = this.scopeStack[i]; - if (scope.flags & SCOPE_VAR) { return scope } - } - }; - - // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. - pp$6.currentThisScope = function() { - for (var i = this.scopeStack.length - 1;; i--) { - var scope = this.scopeStack[i]; - if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } - } - }; - - var Node = function Node(parser, pos, loc) { - this.type = ""; - this.start = pos; - this.end = 0; - if (parser.options.locations) - { this.loc = new SourceLocation(parser, loc); } - if (parser.options.directSourceFile) - { this.sourceFile = parser.options.directSourceFile; } - if (parser.options.ranges) - { this.range = [pos, 0]; } - }; - - // Start an AST node, attaching a start offset. - - var pp$7 = Parser.prototype; - - pp$7.startNode = function() { - return new Node(this, this.start, this.startLoc) - }; - - pp$7.startNodeAt = function(pos, loc) { - return new Node(this, pos, loc) - }; - - // Finish an AST node, adding `type` and `end` properties. - - function finishNodeAt(node, type, pos, loc) { - node.type = type; - node.end = pos; - if (this.options.locations) - { node.loc.end = loc; } - if (this.options.ranges) - { node.range[1] = pos; } - return node - } - - pp$7.finishNode = function(node, type) { - return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) - }; - - // Finish node at given position - - pp$7.finishNodeAt = function(node, type, pos, loc) { - return finishNodeAt.call(this, node, type, pos, loc) - }; - - pp$7.copyNode = function(node) { - var newNode = new Node(this, node.start, this.startLoc); - for (var prop in node) { newNode[prop] = node[prop]; } - return newNode - }; - - // This file contains Unicode properties extracted from the ECMAScript - // specification. The lists are extracted like so: - // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) - - // #table-binary-unicode-properties - var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; - var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; - var ecma11BinaryProperties = ecma10BinaryProperties; - var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; - var unicodeBinaryProperties = { - 9: ecma9BinaryProperties, - 10: ecma10BinaryProperties, - 11: ecma11BinaryProperties, - 12: ecma12BinaryProperties - }; - - // #table-unicode-general-category-values - var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; - - // #table-unicode-script-values - var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; - var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; - var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; - var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; - var unicodeScriptValues = { - 9: ecma9ScriptValues, - 10: ecma10ScriptValues, - 11: ecma11ScriptValues, - 12: ecma12ScriptValues - }; - - var data = {}; - function buildUnicodeData(ecmaVersion) { - var d = data[ecmaVersion] = { - binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), - nonBinary: { - General_Category: wordsRegexp(unicodeGeneralCategoryValues), - Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) - } - }; - d.nonBinary.Script_Extensions = d.nonBinary.Script; - - d.nonBinary.gc = d.nonBinary.General_Category; - d.nonBinary.sc = d.nonBinary.Script; - d.nonBinary.scx = d.nonBinary.Script_Extensions; - } - buildUnicodeData(9); - buildUnicodeData(10); - buildUnicodeData(11); - buildUnicodeData(12); - - var pp$8 = Parser.prototype; - - var RegExpValidationState = function RegExpValidationState(parser) { - this.parser = parser; - this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : ""); - this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion]; - this.source = ""; - this.flags = ""; - this.start = 0; - this.switchU = false; - this.switchN = false; - this.pos = 0; - this.lastIntValue = 0; - this.lastStringValue = ""; - this.lastAssertionIsQuantifiable = false; - this.numCapturingParens = 0; - this.maxBackReference = 0; - this.groupNames = []; - this.backReferenceNames = []; - }; - - RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { - var unicode = flags.indexOf("u") !== -1; - this.start = start | 0; - this.source = pattern + ""; - this.flags = flags; - this.switchU = unicode && this.parser.options.ecmaVersion >= 6; - this.switchN = unicode && this.parser.options.ecmaVersion >= 9; - }; - - RegExpValidationState.prototype.raise = function raise (message) { - this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); - }; - - // If u flag is given, this returns the code point at the index (it combines a surrogate pair). - // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). - RegExpValidationState.prototype.at = function at (i, forceU) { - if ( forceU === void 0 ) forceU = false; - - var s = this.source; - var l = s.length; - if (i >= l) { - return -1 - } - var c = s.charCodeAt(i); - if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { - return c - } - var next = s.charCodeAt(i + 1); - return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c - }; - - RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { - if ( forceU === void 0 ) forceU = false; - - var s = this.source; - var l = s.length; - if (i >= l) { - return l - } - var c = s.charCodeAt(i), next; - if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || - (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { - return i + 1 - } - return i + 2 - }; - - RegExpValidationState.prototype.current = function current (forceU) { - if ( forceU === void 0 ) forceU = false; - - return this.at(this.pos, forceU) - }; - - RegExpValidationState.prototype.lookahead = function lookahead (forceU) { - if ( forceU === void 0 ) forceU = false; - - return this.at(this.nextIndex(this.pos, forceU), forceU) - }; - - RegExpValidationState.prototype.advance = function advance (forceU) { - if ( forceU === void 0 ) forceU = false; - - this.pos = this.nextIndex(this.pos, forceU); - }; - - RegExpValidationState.prototype.eat = function eat (ch, forceU) { - if ( forceU === void 0 ) forceU = false; - - if (this.current(forceU) === ch) { - this.advance(forceU); - return true - } - return false - }; - - function codePointToString(ch) { - if (ch <= 0xFFFF) { return String.fromCharCode(ch) } - ch -= 0x10000; - return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) - } - - /** - * Validate the flags part of a given RegExpLiteral. - * - * @param {RegExpValidationState} state The state to validate RegExp. - * @returns {void} - */ - pp$8.validateRegExpFlags = function(state) { - var validFlags = state.validFlags; - var flags = state.flags; - - for (var i = 0; i < flags.length; i++) { - var flag = flags.charAt(i); - if (validFlags.indexOf(flag) === -1) { - this.raise(state.start, "Invalid regular expression flag"); - } - if (flags.indexOf(flag, i + 1) > -1) { - this.raise(state.start, "Duplicate regular expression flag"); - } - } - }; - - /** - * Validate the pattern part of a given RegExpLiteral. - * - * @param {RegExpValidationState} state The state to validate RegExp. - * @returns {void} - */ - pp$8.validateRegExpPattern = function(state) { - this.regexp_pattern(state); - - // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of - // parsing contains a |GroupName|, reparse with the goal symbol - // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* - // exception if _P_ did not conform to the grammar, if any elements of _P_ - // were not matched by the parse, or if any Early Error conditions exist. - if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { - state.switchN = true; - this.regexp_pattern(state); - } - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern - pp$8.regexp_pattern = function(state) { - state.pos = 0; - state.lastIntValue = 0; - state.lastStringValue = ""; - state.lastAssertionIsQuantifiable = false; - state.numCapturingParens = 0; - state.maxBackReference = 0; - state.groupNames.length = 0; - state.backReferenceNames.length = 0; - - this.regexp_disjunction(state); - - if (state.pos !== state.source.length) { - // Make the same messages as V8. - if (state.eat(0x29 /* ) */)) { - state.raise("Unmatched ')'"); - } - if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { - state.raise("Lone quantifier brackets"); - } - } - if (state.maxBackReference > state.numCapturingParens) { - state.raise("Invalid escape"); - } - for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { - var name = list[i]; - - if (state.groupNames.indexOf(name) === -1) { - state.raise("Invalid named capture referenced"); - } - } - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction - pp$8.regexp_disjunction = function(state) { - this.regexp_alternative(state); - while (state.eat(0x7C /* | */)) { - this.regexp_alternative(state); - } - - // Make the same message as V8. - if (this.regexp_eatQuantifier(state, true)) { - state.raise("Nothing to repeat"); - } - if (state.eat(0x7B /* { */)) { - state.raise("Lone quantifier brackets"); - } - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative - pp$8.regexp_alternative = function(state) { - while (state.pos < state.source.length && this.regexp_eatTerm(state)) - { } - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term - pp$8.regexp_eatTerm = function(state) { - if (this.regexp_eatAssertion(state)) { - // Handle `QuantifiableAssertion Quantifier` alternative. - // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion - // is a QuantifiableAssertion. - if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { - // Make the same message as V8. - if (state.switchU) { - state.raise("Invalid quantifier"); - } - } - return true - } - - if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { - this.regexp_eatQuantifier(state); - return true - } - - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion - pp$8.regexp_eatAssertion = function(state) { - var start = state.pos; - state.lastAssertionIsQuantifiable = false; - - // ^, $ - if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { - return true - } - - // \b \B - if (state.eat(0x5C /* \ */)) { - if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { - return true - } - state.pos = start; - } - - // Lookahead / Lookbehind - if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { - var lookbehind = false; - if (this.options.ecmaVersion >= 9) { - lookbehind = state.eat(0x3C /* < */); - } - if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { - this.regexp_disjunction(state); - if (!state.eat(0x29 /* ) */)) { - state.raise("Unterminated group"); - } - state.lastAssertionIsQuantifiable = !lookbehind; - return true - } - } - - state.pos = start; - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier - pp$8.regexp_eatQuantifier = function(state, noError) { - if ( noError === void 0 ) noError = false; - - if (this.regexp_eatQuantifierPrefix(state, noError)) { - state.eat(0x3F /* ? */); - return true - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix - pp$8.regexp_eatQuantifierPrefix = function(state, noError) { - return ( - state.eat(0x2A /* * */) || - state.eat(0x2B /* + */) || - state.eat(0x3F /* ? */) || - this.regexp_eatBracedQuantifier(state, noError) - ) - }; - pp$8.regexp_eatBracedQuantifier = function(state, noError) { - var start = state.pos; - if (state.eat(0x7B /* { */)) { - var min = 0, max = -1; - if (this.regexp_eatDecimalDigits(state)) { - min = state.lastIntValue; - if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { - max = state.lastIntValue; - } - if (state.eat(0x7D /* } */)) { - // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term - if (max !== -1 && max < min && !noError) { - state.raise("numbers out of order in {} quantifier"); - } - return true - } - } - if (state.switchU && !noError) { - state.raise("Incomplete quantifier"); - } - state.pos = start; - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom - pp$8.regexp_eatAtom = function(state) { - return ( - this.regexp_eatPatternCharacters(state) || - state.eat(0x2E /* . */) || - this.regexp_eatReverseSolidusAtomEscape(state) || - this.regexp_eatCharacterClass(state) || - this.regexp_eatUncapturingGroup(state) || - this.regexp_eatCapturingGroup(state) - ) - }; - pp$8.regexp_eatReverseSolidusAtomEscape = function(state) { - var start = state.pos; - if (state.eat(0x5C /* \ */)) { - if (this.regexp_eatAtomEscape(state)) { - return true - } - state.pos = start; - } - return false - }; - pp$8.regexp_eatUncapturingGroup = function(state) { - var start = state.pos; - if (state.eat(0x28 /* ( */)) { - if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { - this.regexp_disjunction(state); - if (state.eat(0x29 /* ) */)) { - return true - } - state.raise("Unterminated group"); - } - state.pos = start; - } - return false - }; - pp$8.regexp_eatCapturingGroup = function(state) { - if (state.eat(0x28 /* ( */)) { - if (this.options.ecmaVersion >= 9) { - this.regexp_groupSpecifier(state); - } else if (state.current() === 0x3F /* ? */) { - state.raise("Invalid group"); - } - this.regexp_disjunction(state); - if (state.eat(0x29 /* ) */)) { - state.numCapturingParens += 1; - return true - } - state.raise("Unterminated group"); - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom - pp$8.regexp_eatExtendedAtom = function(state) { - return ( - state.eat(0x2E /* . */) || - this.regexp_eatReverseSolidusAtomEscape(state) || - this.regexp_eatCharacterClass(state) || - this.regexp_eatUncapturingGroup(state) || - this.regexp_eatCapturingGroup(state) || - this.regexp_eatInvalidBracedQuantifier(state) || - this.regexp_eatExtendedPatternCharacter(state) - ) - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier - pp$8.regexp_eatInvalidBracedQuantifier = function(state) { - if (this.regexp_eatBracedQuantifier(state, true)) { - state.raise("Nothing to repeat"); - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter - pp$8.regexp_eatSyntaxCharacter = function(state) { - var ch = state.current(); - if (isSyntaxCharacter(ch)) { - state.lastIntValue = ch; - state.advance(); - return true - } - return false - }; - function isSyntaxCharacter(ch) { - return ( - ch === 0x24 /* $ */ || - ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || - ch === 0x2E /* . */ || - ch === 0x3F /* ? */ || - ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || - ch >= 0x7B /* { */ && ch <= 0x7D /* } */ - ) - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter - // But eat eager. - pp$8.regexp_eatPatternCharacters = function(state) { - var start = state.pos; - var ch = 0; - while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { - state.advance(); - } - return state.pos !== start - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter - pp$8.regexp_eatExtendedPatternCharacter = function(state) { - var ch = state.current(); - if ( - ch !== -1 && - ch !== 0x24 /* $ */ && - !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && - ch !== 0x2E /* . */ && - ch !== 0x3F /* ? */ && - ch !== 0x5B /* [ */ && - ch !== 0x5E /* ^ */ && - ch !== 0x7C /* | */ - ) { - state.advance(); - return true - } - return false - }; - - // GroupSpecifier :: - // [empty] - // `?` GroupName - pp$8.regexp_groupSpecifier = function(state) { - if (state.eat(0x3F /* ? */)) { - if (this.regexp_eatGroupName(state)) { - if (state.groupNames.indexOf(state.lastStringValue) !== -1) { - state.raise("Duplicate capture group name"); - } - state.groupNames.push(state.lastStringValue); - return - } - state.raise("Invalid group"); - } - }; - - // GroupName :: - // `<` RegExpIdentifierName `>` - // Note: this updates `state.lastStringValue` property with the eaten name. - pp$8.regexp_eatGroupName = function(state) { - state.lastStringValue = ""; - if (state.eat(0x3C /* < */)) { - if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { - return true - } - state.raise("Invalid capture group name"); - } - return false - }; - - // RegExpIdentifierName :: - // RegExpIdentifierStart - // RegExpIdentifierName RegExpIdentifierPart - // Note: this updates `state.lastStringValue` property with the eaten name. - pp$8.regexp_eatRegExpIdentifierName = function(state) { - state.lastStringValue = ""; - if (this.regexp_eatRegExpIdentifierStart(state)) { - state.lastStringValue += codePointToString(state.lastIntValue); - while (this.regexp_eatRegExpIdentifierPart(state)) { - state.lastStringValue += codePointToString(state.lastIntValue); - } - return true - } - return false - }; - - // RegExpIdentifierStart :: - // UnicodeIDStart - // `$` - // `_` - // `\` RegExpUnicodeEscapeSequence[+U] - pp$8.regexp_eatRegExpIdentifierStart = function(state) { - var start = state.pos; - var forceU = this.options.ecmaVersion >= 11; - var ch = state.current(forceU); - state.advance(forceU); - - if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { - ch = state.lastIntValue; - } - if (isRegExpIdentifierStart(ch)) { - state.lastIntValue = ch; - return true - } - - state.pos = start; - return false - }; - function isRegExpIdentifierStart(ch) { - return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ - } - - // RegExpIdentifierPart :: - // UnicodeIDContinue - // `$` - // `_` - // `\` RegExpUnicodeEscapeSequence[+U] - // - // - pp$8.regexp_eatRegExpIdentifierPart = function(state) { - var start = state.pos; - var forceU = this.options.ecmaVersion >= 11; - var ch = state.current(forceU); - state.advance(forceU); - - if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { - ch = state.lastIntValue; - } - if (isRegExpIdentifierPart(ch)) { - state.lastIntValue = ch; - return true - } - - state.pos = start; - return false - }; - function isRegExpIdentifierPart(ch) { - return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape - pp$8.regexp_eatAtomEscape = function(state) { - if ( - this.regexp_eatBackReference(state) || - this.regexp_eatCharacterClassEscape(state) || - this.regexp_eatCharacterEscape(state) || - (state.switchN && this.regexp_eatKGroupName(state)) - ) { - return true - } - if (state.switchU) { - // Make the same message as V8. - if (state.current() === 0x63 /* c */) { - state.raise("Invalid unicode escape"); - } - state.raise("Invalid escape"); - } - return false - }; - pp$8.regexp_eatBackReference = function(state) { - var start = state.pos; - if (this.regexp_eatDecimalEscape(state)) { - var n = state.lastIntValue; - if (state.switchU) { - // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape - if (n > state.maxBackReference) { - state.maxBackReference = n; - } - return true - } - if (n <= state.numCapturingParens) { - return true - } - state.pos = start; - } - return false - }; - pp$8.regexp_eatKGroupName = function(state) { - if (state.eat(0x6B /* k */)) { - if (this.regexp_eatGroupName(state)) { - state.backReferenceNames.push(state.lastStringValue); - return true - } - state.raise("Invalid named reference"); - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape - pp$8.regexp_eatCharacterEscape = function(state) { - return ( - this.regexp_eatControlEscape(state) || - this.regexp_eatCControlLetter(state) || - this.regexp_eatZero(state) || - this.regexp_eatHexEscapeSequence(state) || - this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || - (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || - this.regexp_eatIdentityEscape(state) - ) - }; - pp$8.regexp_eatCControlLetter = function(state) { - var start = state.pos; - if (state.eat(0x63 /* c */)) { - if (this.regexp_eatControlLetter(state)) { - return true - } - state.pos = start; - } - return false - }; - pp$8.regexp_eatZero = function(state) { - if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { - state.lastIntValue = 0; - state.advance(); - return true - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape - pp$8.regexp_eatControlEscape = function(state) { - var ch = state.current(); - if (ch === 0x74 /* t */) { - state.lastIntValue = 0x09; /* \t */ - state.advance(); - return true - } - if (ch === 0x6E /* n */) { - state.lastIntValue = 0x0A; /* \n */ - state.advance(); - return true - } - if (ch === 0x76 /* v */) { - state.lastIntValue = 0x0B; /* \v */ - state.advance(); - return true - } - if (ch === 0x66 /* f */) { - state.lastIntValue = 0x0C; /* \f */ - state.advance(); - return true - } - if (ch === 0x72 /* r */) { - state.lastIntValue = 0x0D; /* \r */ - state.advance(); - return true - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter - pp$8.regexp_eatControlLetter = function(state) { - var ch = state.current(); - if (isControlLetter(ch)) { - state.lastIntValue = ch % 0x20; - state.advance(); - return true - } - return false - }; - function isControlLetter(ch) { - return ( - (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || - (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) - ) - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence - pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { - if ( forceU === void 0 ) forceU = false; - - var start = state.pos; - var switchU = forceU || state.switchU; - - if (state.eat(0x75 /* u */)) { - if (this.regexp_eatFixedHexDigits(state, 4)) { - var lead = state.lastIntValue; - if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { - var leadSurrogateEnd = state.pos; - if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { - var trail = state.lastIntValue; - if (trail >= 0xDC00 && trail <= 0xDFFF) { - state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; - return true - } - } - state.pos = leadSurrogateEnd; - state.lastIntValue = lead; - } - return true - } - if ( - switchU && - state.eat(0x7B /* { */) && - this.regexp_eatHexDigits(state) && - state.eat(0x7D /* } */) && - isValidUnicode(state.lastIntValue) - ) { - return true - } - if (switchU) { - state.raise("Invalid unicode escape"); - } - state.pos = start; - } - - return false - }; - function isValidUnicode(ch) { - return ch >= 0 && ch <= 0x10FFFF - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape - pp$8.regexp_eatIdentityEscape = function(state) { - if (state.switchU) { - if (this.regexp_eatSyntaxCharacter(state)) { - return true - } - if (state.eat(0x2F /* / */)) { - state.lastIntValue = 0x2F; /* / */ - return true - } - return false - } - - var ch = state.current(); - if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { - state.lastIntValue = ch; - state.advance(); - return true - } - - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape - pp$8.regexp_eatDecimalEscape = function(state) { - state.lastIntValue = 0; - var ch = state.current(); - if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { - do { - state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); - state.advance(); - } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) - return true - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape - pp$8.regexp_eatCharacterClassEscape = function(state) { - var ch = state.current(); - - if (isCharacterClassEscape(ch)) { - state.lastIntValue = -1; - state.advance(); - return true - } - - if ( - state.switchU && - this.options.ecmaVersion >= 9 && - (ch === 0x50 /* P */ || ch === 0x70 /* p */) - ) { - state.lastIntValue = -1; - state.advance(); - if ( - state.eat(0x7B /* { */) && - this.regexp_eatUnicodePropertyValueExpression(state) && - state.eat(0x7D /* } */) - ) { - return true - } - state.raise("Invalid property name"); - } - - return false - }; - function isCharacterClassEscape(ch) { - return ( - ch === 0x64 /* d */ || - ch === 0x44 /* D */ || - ch === 0x73 /* s */ || - ch === 0x53 /* S */ || - ch === 0x77 /* w */ || - ch === 0x57 /* W */ - ) - } - - // UnicodePropertyValueExpression :: - // UnicodePropertyName `=` UnicodePropertyValue - // LoneUnicodePropertyNameOrValue - pp$8.regexp_eatUnicodePropertyValueExpression = function(state) { - var start = state.pos; - - // UnicodePropertyName `=` UnicodePropertyValue - if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { - var name = state.lastStringValue; - if (this.regexp_eatUnicodePropertyValue(state)) { - var value = state.lastStringValue; - this.regexp_validateUnicodePropertyNameAndValue(state, name, value); - return true - } - } - state.pos = start; - - // LoneUnicodePropertyNameOrValue - if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { - var nameOrValue = state.lastStringValue; - this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); - return true - } - return false - }; - pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { - if (!has(state.unicodeProperties.nonBinary, name)) - { state.raise("Invalid property name"); } - if (!state.unicodeProperties.nonBinary[name].test(value)) - { state.raise("Invalid property value"); } - }; - pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { - if (!state.unicodeProperties.binary.test(nameOrValue)) - { state.raise("Invalid property name"); } - }; - - // UnicodePropertyName :: - // UnicodePropertyNameCharacters - pp$8.regexp_eatUnicodePropertyName = function(state) { - var ch = 0; - state.lastStringValue = ""; - while (isUnicodePropertyNameCharacter(ch = state.current())) { - state.lastStringValue += codePointToString(ch); - state.advance(); - } - return state.lastStringValue !== "" - }; - function isUnicodePropertyNameCharacter(ch) { - return isControlLetter(ch) || ch === 0x5F /* _ */ - } - - // UnicodePropertyValue :: - // UnicodePropertyValueCharacters - pp$8.regexp_eatUnicodePropertyValue = function(state) { - var ch = 0; - state.lastStringValue = ""; - while (isUnicodePropertyValueCharacter(ch = state.current())) { - state.lastStringValue += codePointToString(ch); - state.advance(); - } - return state.lastStringValue !== "" - }; - function isUnicodePropertyValueCharacter(ch) { - return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) - } - - // LoneUnicodePropertyNameOrValue :: - // UnicodePropertyValueCharacters - pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { - return this.regexp_eatUnicodePropertyValue(state) - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass - pp$8.regexp_eatCharacterClass = function(state) { - if (state.eat(0x5B /* [ */)) { - state.eat(0x5E /* ^ */); - this.regexp_classRanges(state); - if (state.eat(0x5D /* ] */)) { - return true - } - // Unreachable since it threw "unterminated regular expression" error before. - state.raise("Unterminated character class"); - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges - // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges - // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash - pp$8.regexp_classRanges = function(state) { - while (this.regexp_eatClassAtom(state)) { - var left = state.lastIntValue; - if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { - var right = state.lastIntValue; - if (state.switchU && (left === -1 || right === -1)) { - state.raise("Invalid character class"); - } - if (left !== -1 && right !== -1 && left > right) { - state.raise("Range out of order in character class"); - } - } - } - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom - // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash - pp$8.regexp_eatClassAtom = function(state) { - var start = state.pos; - - if (state.eat(0x5C /* \ */)) { - if (this.regexp_eatClassEscape(state)) { - return true - } - if (state.switchU) { - // Make the same message as V8. - var ch$1 = state.current(); - if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { - state.raise("Invalid class escape"); - } - state.raise("Invalid escape"); - } - state.pos = start; - } - - var ch = state.current(); - if (ch !== 0x5D /* ] */) { - state.lastIntValue = ch; - state.advance(); - return true - } - - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape - pp$8.regexp_eatClassEscape = function(state) { - var start = state.pos; - - if (state.eat(0x62 /* b */)) { - state.lastIntValue = 0x08; /* */ - return true - } - - if (state.switchU && state.eat(0x2D /* - */)) { - state.lastIntValue = 0x2D; /* - */ - return true - } - - if (!state.switchU && state.eat(0x63 /* c */)) { - if (this.regexp_eatClassControlLetter(state)) { - return true - } - state.pos = start; - } - - return ( - this.regexp_eatCharacterClassEscape(state) || - this.regexp_eatCharacterEscape(state) - ) - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter - pp$8.regexp_eatClassControlLetter = function(state) { - var ch = state.current(); - if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { - state.lastIntValue = ch % 0x20; - state.advance(); - return true - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence - pp$8.regexp_eatHexEscapeSequence = function(state) { - var start = state.pos; - if (state.eat(0x78 /* x */)) { - if (this.regexp_eatFixedHexDigits(state, 2)) { - return true - } - if (state.switchU) { - state.raise("Invalid escape"); - } - state.pos = start; - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits - pp$8.regexp_eatDecimalDigits = function(state) { - var start = state.pos; - var ch = 0; - state.lastIntValue = 0; - while (isDecimalDigit(ch = state.current())) { - state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); - state.advance(); - } - return state.pos !== start - }; - function isDecimalDigit(ch) { - return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits - pp$8.regexp_eatHexDigits = function(state) { - var start = state.pos; - var ch = 0; - state.lastIntValue = 0; - while (isHexDigit(ch = state.current())) { - state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); - state.advance(); - } - return state.pos !== start - }; - function isHexDigit(ch) { - return ( - (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || - (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || - (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) - ) - } - function hexToInt(ch) { - if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { - return 10 + (ch - 0x41 /* A */) - } - if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { - return 10 + (ch - 0x61 /* a */) - } - return ch - 0x30 /* 0 */ - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence - // Allows only 0-377(octal) i.e. 0-255(decimal). - pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) { - if (this.regexp_eatOctalDigit(state)) { - var n1 = state.lastIntValue; - if (this.regexp_eatOctalDigit(state)) { - var n2 = state.lastIntValue; - if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { - state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; - } else { - state.lastIntValue = n1 * 8 + n2; - } - } else { - state.lastIntValue = n1; - } - return true - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit - pp$8.regexp_eatOctalDigit = function(state) { - var ch = state.current(); - if (isOctalDigit(ch)) { - state.lastIntValue = ch - 0x30; /* 0 */ - state.advance(); - return true - } - state.lastIntValue = 0; - return false - }; - function isOctalDigit(ch) { - return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits - // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit - // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence - pp$8.regexp_eatFixedHexDigits = function(state, length) { - var start = state.pos; - state.lastIntValue = 0; - for (var i = 0; i < length; ++i) { - var ch = state.current(); - if (!isHexDigit(ch)) { - state.pos = start; - return false - } - state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); - state.advance(); - } - return true - }; - - // Object type used to represent tokens. Note that normally, tokens - // simply exist as properties on the parser object. This is only - // used for the onToken callback and the external tokenizer. - - var Token = function Token(p) { - this.type = p.type; - this.value = p.value; - this.start = p.start; - this.end = p.end; - if (p.options.locations) - { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } - if (p.options.ranges) - { this.range = [p.start, p.end]; } - }; - - // ## Tokenizer - - var pp$9 = Parser.prototype; - - // Move to the next token - - pp$9.next = function(ignoreEscapeSequenceInKeyword) { - if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) - { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } - if (this.options.onToken) - { this.options.onToken(new Token(this)); } - - this.lastTokEnd = this.end; - this.lastTokStart = this.start; - this.lastTokEndLoc = this.endLoc; - this.lastTokStartLoc = this.startLoc; - this.nextToken(); - }; - - pp$9.getToken = function() { - this.next(); - return new Token(this) - }; - - // If we're in an ES6 environment, make parsers iterable - if (typeof Symbol !== "undefined") - { pp$9[Symbol.iterator] = function() { - var this$1 = this; - - return { - next: function () { - var token = this$1.getToken(); - return { - done: token.type === types.eof, - value: token - } - } - } - }; } - - // Toggle strict mode. Re-reads the next number or string to please - // pedantic tests (`"use strict"; 010;` should fail). - - // Read a single token, updating the parser object's token-related - // properties. - - pp$9.nextToken = function() { - var curContext = this.curContext(); - if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } - - this.start = this.pos; - if (this.options.locations) { this.startLoc = this.curPosition(); } - if (this.pos >= this.input.length) { return this.finishToken(types.eof) } - - if (curContext.override) { return curContext.override(this) } - else { this.readToken(this.fullCharCodeAtPos()); } - }; - - pp$9.readToken = function(code) { - // Identifier or keyword. '\uXXXX' sequences are allowed in - // identifiers, so '\' also dispatches to that. - if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) - { return this.readWord() } - - return this.getTokenFromCode(code) - }; - - pp$9.fullCharCodeAtPos = function() { - var code = this.input.charCodeAt(this.pos); - if (code <= 0xd7ff || code >= 0xdc00) { return code } - var next = this.input.charCodeAt(this.pos + 1); - return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 - }; - - pp$9.skipBlockComment = function() { - var startLoc = this.options.onComment && this.curPosition(); - var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); - if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } - this.pos = end + 2; - if (this.options.locations) { - lineBreakG.lastIndex = start; - var match; - while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { - ++this.curLine; - this.lineStart = match.index + match[0].length; - } - } - if (this.options.onComment) - { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, - startLoc, this.curPosition()); } - }; - - pp$9.skipLineComment = function(startSkip) { - var start = this.pos; - var startLoc = this.options.onComment && this.curPosition(); - var ch = this.input.charCodeAt(this.pos += startSkip); - while (this.pos < this.input.length && !isNewLine(ch)) { - ch = this.input.charCodeAt(++this.pos); - } - if (this.options.onComment) - { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, - startLoc, this.curPosition()); } - }; - - // Called at the start of the parse and after every token. Skips - // whitespace and comments, and. - - pp$9.skipSpace = function() { - loop: while (this.pos < this.input.length) { - var ch = this.input.charCodeAt(this.pos); - switch (ch) { - case 32: case 160: // ' ' - ++this.pos; - break - case 13: - if (this.input.charCodeAt(this.pos + 1) === 10) { - ++this.pos; - } - case 10: case 8232: case 8233: - ++this.pos; - if (this.options.locations) { - ++this.curLine; - this.lineStart = this.pos; - } - break - case 47: // '/' - switch (this.input.charCodeAt(this.pos + 1)) { - case 42: // '*' - this.skipBlockComment(); - break - case 47: - this.skipLineComment(2); - break - default: - break loop - } - break - default: - if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { - ++this.pos; - } else { - break loop - } - } - } - }; - - // Called at the end of every token. Sets `end`, `val`, and - // maintains `context` and `exprAllowed`, and skips the space after - // the token, so that the next one's `start` will point at the - // right position. - - pp$9.finishToken = function(type, val) { - this.end = this.pos; - if (this.options.locations) { this.endLoc = this.curPosition(); } - var prevType = this.type; - this.type = type; - this.value = val; - - this.updateContext(prevType); - }; - - // ### Token reading - - // This is the function that is called to fetch the next token. It - // is somewhat obscure, because it works in character codes rather - // than characters, and because operator parsing has been inlined - // into it. - // - // All in the name of speed. - // - pp$9.readToken_dot = function() { - var next = this.input.charCodeAt(this.pos + 1); - if (next >= 48 && next <= 57) { return this.readNumber(true) } - var next2 = this.input.charCodeAt(this.pos + 2); - if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' - this.pos += 3; - return this.finishToken(types.ellipsis) - } else { - ++this.pos; - return this.finishToken(types.dot) - } - }; - - pp$9.readToken_slash = function() { // '/' - var next = this.input.charCodeAt(this.pos + 1); - if (this.exprAllowed) { ++this.pos; return this.readRegexp() } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.slash, 1) - }; - - pp$9.readToken_mult_modulo_exp = function(code) { // '%*' - var next = this.input.charCodeAt(this.pos + 1); - var size = 1; - var tokentype = code === 42 ? types.star : types.modulo; - - // exponentiation operator ** and **= - if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { - ++size; - tokentype = types.starstar; - next = this.input.charCodeAt(this.pos + 2); - } - - if (next === 61) { return this.finishOp(types.assign, size + 1) } - return this.finishOp(tokentype, size) - }; - - pp$9.readToken_pipe_amp = function(code) { // '|&' - var next = this.input.charCodeAt(this.pos + 1); - if (next === code) { - if (this.options.ecmaVersion >= 12) { - var next2 = this.input.charCodeAt(this.pos + 2); - if (next2 === 61) { return this.finishOp(types.assign, 3) } - } - return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) - } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) - }; - - pp$9.readToken_caret = function() { // '^' - var next = this.input.charCodeAt(this.pos + 1); - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.bitwiseXOR, 1) - }; - - pp$9.readToken_plus_min = function(code) { // '+-' - var next = this.input.charCodeAt(this.pos + 1); - if (next === code) { - if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && - (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { - // A `-->` line comment - this.skipLineComment(3); - this.skipSpace(); - return this.nextToken() - } - return this.finishOp(types.incDec, 2) - } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.plusMin, 1) - }; - - pp$9.readToken_lt_gt = function(code) { // '<>' - var next = this.input.charCodeAt(this.pos + 1); - var size = 1; - if (next === code) { - size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; - if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } - return this.finishOp(types.bitShift, size) - } - if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && - this.input.charCodeAt(this.pos + 3) === 45) { - // ` SYNC --[event loop tick]--> ASYNC_ACTIVE --[interval tick]-> ASYNC_PASSIVE - ^ | - +---------[insert data]-------+ -*/ + Property(property) { -const STORAGE_MODE_IDLE = 0; -const STORAGE_MODE_SYNC = 1; -const STORAGE_MODE_ASYNC = 2; + // Computed property's key is a right hand node. + if (property.computed) { + this.rightHandNodes.push(property.key); + } -class CacheBackend { - /** - * @param {number} duration max cache duration of items - * @param {any} provider async method - * @param {any} syncProvider sync method - * @param {any} providerContext call context for the provider methods - */ - constructor(duration, provider, syncProvider, providerContext) { - this._duration = duration; - this._provider = provider; - this._syncProvider = syncProvider; - this._providerContext = providerContext; - /** @type {Map} */ - this._activeAsyncOperations = new Map(); - /** @type {Map }>} */ - this._data = new Map(); - /** @type {Set[]} */ - this._levels = []; - for (let i = 0; i < 10; i++) this._levels.push(new Set()); - for (let i = 5000; i < duration; i += 500) this._levels.push(new Set()); - this._currentLevel = 0; - this._tickInterval = Math.floor(duration / this._levels.length); - /** @type {STORAGE_MODE_IDLE | STORAGE_MODE_SYNC | STORAGE_MODE_ASYNC} */ - this._mode = STORAGE_MODE_IDLE; + // If it's shorthand, its key is same as its value. + // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). + // If it's not shorthand, the name of new variable is its value's. + this.visit(property.value); + } - /** @type {NodeJS.Timeout | undefined} */ - this._timeout = undefined; - /** @type {number | undefined} */ - this._nextDecay = undefined; + ArrayPattern(pattern) { + for (let i = 0, iz = pattern.elements.length; i < iz; ++i) { + const element = pattern.elements[i]; - this.provide = provider ? this.provide.bind(this) : null; - this.provideSync = syncProvider ? this.provideSync.bind(this) : null; - } + this.visit(element); + } + } - provide(path, options, callback) { - if (typeof options === "function") { - callback = options; - options = undefined; - } - if (typeof path !== "string") { - callback(new TypeError("path must be a string")); - return; - } - if (options) { - return this._provider.call( - this._providerContext, - path, - options, - callback - ); - } + AssignmentPattern(pattern) { + this.assignments.push(pattern); + this.visit(pattern.left); + this.rightHandNodes.push(pattern.right); + this.assignments.pop(); + } - // When in sync mode we can move to async mode - if (this._mode === STORAGE_MODE_SYNC) { - this._enterAsyncMode(); - } + RestElement(pattern) { + this.restElements.push(pattern); + this.visit(pattern.argument); + this.restElements.pop(); + } - // Check in cache - let cacheEntry = this._data.get(path); - if (cacheEntry !== undefined) { - if (cacheEntry.err) return nextTick(callback, cacheEntry.err); - return nextTick(callback, null, cacheEntry.result); - } + MemberExpression(node) { - // Check if there is already the same operation running - let callbacks = this._activeAsyncOperations.get(path); - if (callbacks !== undefined) { - callbacks.push(callback); - return; - } - this._activeAsyncOperations.set(path, (callbacks = [callback])); + // Computed property's key is a right hand node. + if (node.computed) { + this.rightHandNodes.push(node.property); + } - // Run the operation - this._provider.call(this._providerContext, path, (err, result) => { - this._activeAsyncOperations.delete(path); - this._storeResult(path, err, result); + // the object is only read, write to its property. + this.rightHandNodes.push(node.object); + } - // Enter async mode if not yet done - this._enterAsyncMode(); + // + // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression. + // By spec, LeftHandSideExpression is Pattern or MemberExpression. + // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758) + // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc... + // - runCallbacks(callbacks, err, result); - }); - } + SpreadElement(node) { + this.visit(node.argument); + } - provideSync(path, options) { - if (typeof path !== "string") { - throw new TypeError("path must be a string"); - } - if (options) { - return this._syncProvider.call(this._providerContext, path, options); - } - - // In sync mode we may have to decay some cache items - if (this._mode === STORAGE_MODE_SYNC) { - this._runDecays(); - } - - // Check in cache - let cacheEntry = this._data.get(path); - if (cacheEntry !== undefined) { - if (cacheEntry.err) throw cacheEntry.err; - return cacheEntry.result; - } - - // Get all active async operations - // This sync operation will also complete them - const callbacks = this._activeAsyncOperations.get(path); - this._activeAsyncOperations.delete(path); - - // Run the operation - // When in idle mode, we will enter sync mode - let result; - try { - result = this._syncProvider.call(this._providerContext, path); - } catch (err) { - this._storeResult(path, err, undefined); - this._enterSyncModeWhenIdle(); - if (callbacks) runCallbacks(callbacks, err, undefined); - throw err; - } - this._storeResult(path, undefined, result); - this._enterSyncModeWhenIdle(); - if (callbacks) runCallbacks(callbacks, undefined, result); - return result; - } - - purge(what) { - if (!what) { - if (this._mode !== STORAGE_MODE_IDLE) { - this._data.clear(); - for (const level of this._levels) { - level.clear(); - } - this._enterIdleMode(); - } - } else if (typeof what === "string") { - for (let [key, data] of this._data) { - if (key.startsWith(what)) { - this._data.delete(key); - data.level.delete(key); - } - } - if (this._data.size === 0) { - this._enterIdleMode(); - } - } else { - for (let [key, data] of this._data) { - for (const item of what) { - if (key.startsWith(item)) { - this._data.delete(key); - data.level.delete(key); - break; - } - } - } - if (this._data.size === 0) { - this._enterIdleMode(); - } - } - } - - purgeParent(what) { - if (!what) { - this.purge(); - } else if (typeof what === "string") { - this.purge(dirname(what)); - } else { - const set = new Set(); - for (const item of what) { - set.add(dirname(item)); - } - this.purge(set); - } - } - - _storeResult(path, err, result) { - if (this._data.has(path)) return; - const level = this._levels[this._currentLevel]; - this._data.set(path, { err, result, level }); - level.add(path); - } + ArrayExpression(node) { + node.elements.forEach(this.visit, this); + } - _decayLevel() { - const nextLevel = (this._currentLevel + 1) % this._levels.length; - const decay = this._levels[nextLevel]; - this._currentLevel = nextLevel; - for (let item of decay) { - this._data.delete(item); - } - decay.clear(); - if (this._data.size === 0) { - this._enterIdleMode(); - } else { - // @ts-ignore _nextDecay is always a number in sync mode - this._nextDecay += this._tickInterval; - } - } + AssignmentExpression(node) { + this.assignments.push(node); + this.visit(node.left); + this.rightHandNodes.push(node.right); + this.assignments.pop(); + } - _runDecays() { - while ( - /** @type {number} */ (this._nextDecay) <= Date.now() && - this._mode !== STORAGE_MODE_IDLE - ) { - this._decayLevel(); - } - } + CallExpression(node) { - _enterAsyncMode() { - let timeout = 0; - switch (this._mode) { - case STORAGE_MODE_ASYNC: - return; - case STORAGE_MODE_IDLE: - this._nextDecay = Date.now() + this._tickInterval; - timeout = this._tickInterval; - break; - case STORAGE_MODE_SYNC: - this._runDecays(); - // @ts-ignore _runDecays may change the mode - if (this._mode === STORAGE_MODE_IDLE) return; - timeout = Math.max( - 0, - /** @type {number} */ (this._nextDecay) - Date.now() - ); - break; - } - this._mode = STORAGE_MODE_ASYNC; - const ref = setTimeout(() => { - this._mode = STORAGE_MODE_SYNC; - this._runDecays(); - }, timeout); - if (ref.unref) ref.unref(); - this._timeout = ref; - } + // arguments are right hand nodes. + node.arguments.forEach(a => { + this.rightHandNodes.push(a); + }); + this.visit(node.callee); + } +} - _enterSyncModeWhenIdle() { - if (this._mode === STORAGE_MODE_IDLE) { - this._mode = STORAGE_MODE_SYNC; - this._nextDecay = Date.now() + this._tickInterval; - } - } +module.exports = PatternVisitor; - _enterIdleMode() { - this._mode = STORAGE_MODE_IDLE; - this._nextDecay = undefined; - if (this._timeout) clearTimeout(this._timeout); - } -} +/* vim: set sw=4 ts=4 et tw=80 : */ -const createBackend = (duration, provider, syncProvider, providerContext) => { - if (duration > 0) { - return new CacheBackend(duration, provider, syncProvider, providerContext); - } - return new OperationMergerBackend(provider, syncProvider, providerContext); -}; -module.exports = class CachedInputFileSystem { - constructor(fileSystem, duration) { - this.fileSystem = fileSystem; +/***/ }), - this._lstatBackend = createBackend( - duration, - this.fileSystem.lstat, - this.fileSystem.lstatSync, - this.fileSystem - ); - const lstat = this._lstatBackend.provide; - this.lstat = /** @type {FileSystem["lstat"]} */ (lstat); - const lstatSync = this._lstatBackend.provideSync; - this.lstatSync = /** @type {SyncFileSystem["lstatSync"]} */ (lstatSync); +/***/ 64945: +/***/ (function(module) { - this._statBackend = createBackend( - duration, - this.fileSystem.stat, - this.fileSystem.statSync, - this.fileSystem - ); - const stat = this._statBackend.provide; - this.stat = /** @type {FileSystem["stat"]} */ (stat); - const statSync = this._statBackend.provideSync; - this.statSync = /** @type {SyncFileSystem["statSync"]} */ (statSync); +"use strict"; +/* + Copyright (C) 2015 Yusuke Suzuki - this._readdirBackend = createBackend( - duration, - this.fileSystem.readdir, - this.fileSystem.readdirSync, - this.fileSystem - ); - const readdir = this._readdirBackend.provide; - this.readdir = /** @type {FileSystem["readdir"]} */ (readdir); - const readdirSync = this._readdirBackend.provideSync; - this.readdirSync = /** @type {SyncFileSystem["readdirSync"]} */ (readdirSync); + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: - this._readFileBackend = createBackend( - duration, - this.fileSystem.readFile, - this.fileSystem.readFileSync, - this.fileSystem - ); - const readFile = this._readFileBackend.provide; - this.readFile = /** @type {FileSystem["readFile"]} */ (readFile); - const readFileSync = this._readFileBackend.provideSync; - this.readFileSync = /** @type {SyncFileSystem["readFileSync"]} */ (readFileSync); + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. - this._readJsonBackend = createBackend( - duration, - this.fileSystem.readJson || - (this.readFile && - ((path, callback) => { - // @ts-ignore - this.readFile(path, (err, buffer) => { - if (err) return callback(err); - if (!buffer || buffer.length === 0) - return callback(new Error("No file content")); - let data; - try { - data = JSON.parse(buffer.toString("utf-8")); - } catch (e) { - return callback(e); - } - callback(null, data); - }); - })), - this.fileSystem.readJsonSync || - (this.readFileSync && - (path => { - const buffer = this.readFileSync(path); - const data = JSON.parse(buffer.toString("utf-8")); - return data; - })), - this.fileSystem - ); - const readJson = this._readJsonBackend.provide; - this.readJson = /** @type {FileSystem["readJson"]} */ (readJson); - const readJsonSync = this._readJsonBackend.provideSync; - this.readJsonSync = /** @type {SyncFileSystem["readJsonSync"]} */ (readJsonSync); + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ - this._readlinkBackend = createBackend( - duration, - this.fileSystem.readlink, - this.fileSystem.readlinkSync, - this.fileSystem - ); - const readlink = this._readlinkBackend.provide; - this.readlink = /** @type {FileSystem["readlink"]} */ (readlink); - const readlinkSync = this._readlinkBackend.provideSync; - this.readlinkSync = /** @type {SyncFileSystem["readlinkSync"]} */ (readlinkSync); - } - purge(what) { - this._statBackend.purge(what); - this._lstatBackend.purge(what); - this._readdirBackend.purgeParent(what); - this._readFileBackend.purge(what); - this._readlinkBackend.purge(what); - this._readJsonBackend.purge(what); - } -}; +const READ = 0x1; +const WRITE = 0x2; +const RW = READ | WRITE; +/** + * A Reference represents a single occurrence of an identifier in code. + * @class Reference + */ +class Reference { + constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) { -/***/ }), + /** + * Identifier syntax node. + * @member {espreeIdentifier} Reference#identifier + */ + this.identifier = ident; -/***/ 2020: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * Reference to the enclosing Scope. + * @member {Scope} Reference#from + */ + this.from = scope; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * Whether the reference comes from a dynamic scope (such as 'eval', + * 'with', etc.), and may be trapped by dynamic scopes. + * @member {boolean} Reference#tainted + */ + this.tainted = false; + /** + * The variable this reference is resolved with. + * @member {Variable} Reference#resolved + */ + this.resolved = null; + /** + * The read-write mode of the reference. (Value is one of {@link + * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). + * @member {number} Reference#flag + * @private + */ + this.flag = flag; + if (this.isWrite()) { -const basename = (__webpack_require__(48608).basename); + /** + * If reference is writeable, this is the tree being written to it. + * @member {espreeNode} Reference#writeExpr + */ + this.writeExpr = writeExpr; -/** @typedef {import("./Resolver")} Resolver */ + /** + * Whether the Reference might refer to a partial value of writeExpr. + * @member {boolean} Reference#partial + */ + this.partial = partial; -module.exports = class CloneBasenamePlugin { - constructor(source, target) { - this.source = source; - this.target = target; - } + /** + * Whether the Reference is to write of initialization. + * @member {boolean} Reference#init + */ + this.init = init; + } + this.__maybeImplicitGlobal = maybeImplicitGlobal; + } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("CloneBasenamePlugin", (request, resolveContext, callback) => { - const filename = basename(request.path); - const filePath = resolver.join(request.path, filename); - const obj = { - ...request, - path: filePath, - relativePath: - request.relativePath && - resolver.join(request.relativePath, filename) - }; - resolver.doResolve( - target, - obj, - "using path: " + filePath, - resolveContext, - callback - ); - }); - } -}; + /** + * Whether the reference is static. + * @method Reference#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + } + /** + * Whether the reference is writeable. + * @method Reference#isWrite + * @returns {boolean} write + */ + isWrite() { + return !!(this.flag & Reference.WRITE); + } -/***/ }), + /** + * Whether the reference is readable. + * @method Reference#isRead + * @returns {boolean} read + */ + isRead() { + return !!(this.flag & Reference.READ); + } -/***/ 44193: -/***/ (function(module) { + /** + * Whether the reference is read-only. + * @method Reference#isReadOnly + * @returns {boolean} read only + */ + isReadOnly() { + return this.flag === Reference.READ; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * Whether the reference is write-only. + * @method Reference#isWriteOnly + * @returns {boolean} write only + */ + isWriteOnly() { + return this.flag === Reference.WRITE; + } + /** + * Whether the reference is read-write. + * @method Reference#isReadWrite + * @returns {boolean} read write + */ + isReadWrite() { + return this.flag === Reference.RW; + } +} +/** + * @constant Reference.READ + * @private + */ +Reference.READ = READ; -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** + * @constant Reference.WRITE + * @private + */ +Reference.WRITE = WRITE; -module.exports = class ConditionalPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {Partial} test compare object - * @param {string | null} message log message - * @param {boolean} allowAlternatives when false, do not continue with the current step when "test" matches - * @param {string | ResolveStepHook} target target - */ - constructor(source, test, message, allowAlternatives, target) { - this.source = source; - this.test = test; - this.message = message; - this.allowAlternatives = allowAlternatives; - this.target = target; - } +/** + * @constant Reference.RW + * @private + */ +Reference.RW = RW; - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - const { test, message, allowAlternatives } = this; - const keys = Object.keys(test); - resolver - .getHook(this.source) - .tapAsync("ConditionalPlugin", (request, resolveContext, callback) => { - for (const prop of keys) { - if (request[prop] !== test[prop]) return callback(); - } - resolver.doResolve( - target, - request, - message, - resolveContext, - allowAlternatives - ? callback - : (err, result) => { - if (err) return callback(err); +module.exports = Reference; - // Don't allow other alternatives - if (result === undefined) return callback(null, null); - callback(null, result); - } - ); - }); - } -}; +/* vim: set sw=4 ts=4 et tw=80 : */ /***/ }), -/***/ 66826: +/***/ 44585: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - + Copyright (C) 2015 Yusuke Suzuki -const DescriptionFileUtils = __webpack_require__(702); + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. -module.exports = class DescriptionFilePlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string[]} filenames filenames - * @param {boolean} pathIsFile pathIsFile - * @param {string | ResolveStepHook} target target - */ - constructor(source, filenames, pathIsFile, target) { - this.source = source; - this.filenames = filenames; - this.pathIsFile = pathIsFile; - this.target = target; - } + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync( - "DescriptionFilePlugin", - (request, resolveContext, callback) => { - const path = request.path; - if (!path) return callback(); - const directory = this.pathIsFile - ? DescriptionFileUtils.cdUp(path) - : path; - if (!directory) return callback(); - DescriptionFileUtils.loadDescriptionFile( - resolver, - directory, - this.filenames, - request.descriptionFilePath - ? { - path: request.descriptionFilePath, - content: request.descriptionFileData, - directory: /** @type {string} */ (request.descriptionFileRoot) - } - : undefined, - resolveContext, - (err, result) => { - if (err) return callback(err); - if (!result) { - if (resolveContext.log) - resolveContext.log( - `No description file found in ${directory} or above` - ); - return callback(); - } - const relativePath = - "." + path.substr(result.directory.length).replace(/\\/g, "/"); - const obj = { - ...request, - descriptionFilePath: result.path, - descriptionFileData: result.content, - descriptionFileRoot: result.directory, - relativePath: relativePath - }; - resolver.doResolve( - target, - obj, - "using description file: " + - result.path + - " (relative path: " + - relativePath + - ")", - resolveContext, - (err, result) => { - if (err) return callback(err); - // Don't allow other processing - if (result === undefined) return callback(null, null); - callback(null, result); - } - ); - } - ); - } - ); - } -}; +/* eslint-disable no-underscore-dangle */ +/* eslint-disable no-undefined */ +const Syntax = (__webpack_require__(18350).Syntax); +const esrecurse = __webpack_require__(81217); +const Reference = __webpack_require__(64945); +const Variable = __webpack_require__(82971); +const PatternVisitor = __webpack_require__(54162); +const definition = __webpack_require__(70665); +const assert = __webpack_require__(39491); -/***/ }), +const ParameterDefinition = definition.ParameterDefinition; +const Definition = definition.Definition; -/***/ 702: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/** + * Traverse identifier in pattern + * @param {Object} options - options + * @param {pattern} rootPattern - root pattern + * @param {Refencer} referencer - referencer + * @param {callback} callback - callback + * @returns {void} + */ +function traverseIdentifierInPattern(options, rootPattern, referencer, callback) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // Call the callback at left hand identifier nodes, and Collect right hand nodes. + const visitor = new PatternVisitor(options, rootPattern, callback); + visitor.visit(rootPattern); + // Process the right hand nodes recursively. + if (referencer !== null && referencer !== undefined) { + visitor.rightHandNodes.forEach(referencer.visit, referencer); + } +} -const forEachBail = __webpack_require__(8266); +// Importing ImportDeclaration. +// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation +// https://github.com/estree/estree/blob/master/es6.md#importdeclaration +// FIXME: Now, we don't create module environment, because the context is +// implementation dependent. -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +class Importer extends esrecurse.Visitor { + constructor(declaration, referencer) { + super(null, referencer.options); + this.declaration = declaration; + this.referencer = referencer; + } -/** - * @typedef {Object} DescriptionFileInfo - * @property {any=} content - * @property {string} path - * @property {string} directory - */ + visitImport(id, specifier) { + this.referencer.visitPattern(id, pattern => { + this.referencer.currentScope().__define(pattern, + new Definition( + Variable.ImportBinding, + pattern, + specifier, + this.declaration, + null, + null + )); + }); + } -/** - * @callback ErrorFirstCallback - * @param {Error|null=} error - * @param {DescriptionFileInfo=} result - */ + ImportNamespaceSpecifier(node) { + const local = (node.local || node.id); -/** - * @param {Resolver} resolver resolver - * @param {string} directory directory - * @param {string[]} filenames filenames - * @param {DescriptionFileInfo|undefined} oldInfo oldInfo - * @param {ResolveContext} resolveContext resolveContext - * @param {ErrorFirstCallback} callback callback - */ -function loadDescriptionFile( - resolver, - directory, - filenames, - oldInfo, - resolveContext, - callback -) { - (function findDescriptionFile() { - if (oldInfo && oldInfo.directory === directory) { - // We already have info for this directory and can reuse it - return callback(null, oldInfo); - } - forEachBail( - filenames, - (filename, callback) => { - const descriptionFilePath = resolver.join(directory, filename); - if (resolver.fileSystem.readJson) { - resolver.fileSystem.readJson(descriptionFilePath, (err, content) => { - if (err) { - if (typeof err.code !== "undefined") { - if (resolveContext.missingDependencies) { - resolveContext.missingDependencies.add(descriptionFilePath); - } - return callback(); - } - if (resolveContext.fileDependencies) { - resolveContext.fileDependencies.add(descriptionFilePath); - } - return onJson(err); - } - if (resolveContext.fileDependencies) { - resolveContext.fileDependencies.add(descriptionFilePath); - } - onJson(null, content); - }); - } else { - resolver.fileSystem.readFile(descriptionFilePath, (err, content) => { - if (err) { - if (resolveContext.missingDependencies) { - resolveContext.missingDependencies.add(descriptionFilePath); - } - return callback(); - } - if (resolveContext.fileDependencies) { - resolveContext.fileDependencies.add(descriptionFilePath); - } - let json; + if (local) { + this.visitImport(local, node); + } + } - if (content) { - try { - json = JSON.parse(content.toString()); - } catch (e) { - return onJson(e); - } - } else { - return onJson(new Error("No content in file")); - } + ImportDefaultSpecifier(node) { + const local = (node.local || node.id); - onJson(null, json); - }); - } + this.visitImport(local, node); + } - function onJson(err, content) { - if (err) { - if (resolveContext.log) - resolveContext.log( - descriptionFilePath + " (directory description file): " + err - ); - else - err.message = - descriptionFilePath + " (directory description file): " + err; - return callback(err); - } - callback(null, { - content, - directory, - path: descriptionFilePath - }); - } - }, - (err, result) => { - if (err) return callback(err); - if (result) { - return callback(null, result); - } else { - const dir = cdUp(directory); - if (!dir) { - return callback(); - } else { - directory = dir; - return findDescriptionFile(); - } - } - } - ); - })(); -} + ImportSpecifier(node) { + const local = (node.local || node.id); -/** - * @param {any} content content - * @param {string|string[]} field field - * @returns {object|string|number|boolean|undefined} field data - */ -function getField(content, field) { - if (!content) return undefined; - if (Array.isArray(field)) { - let current = content; - for (let j = 0; j < field.length; j++) { - if (current === null || typeof current !== "object") { - current = null; - break; - } - current = current[field[j]]; - } - return current; - } else { - return content[field]; - } + if (node.name) { + this.visitImport(node.name, node); + } else { + this.visitImport(local, node); + } + } } -/** - * @param {string} directory directory - * @returns {string|null} parent directory or null - */ -function cdUp(directory) { - if (directory === "/") return null; - const i = directory.lastIndexOf("/"), - j = directory.lastIndexOf("\\"); - const p = i < 0 ? j : j < 0 ? i : i < j ? j : i; - if (p < 0) return null; - return directory.substr(0, p || 1); -} +// Referencing variables and creating bindings. +class Referencer extends esrecurse.Visitor { + constructor(options, scopeManager) { + super(null, options); + this.options = options; + this.scopeManager = scopeManager; + this.parent = null; + this.isInnerMethodDefinition = false; + } -exports.loadDescriptionFile = loadDescriptionFile; -exports.getField = getField; -exports.cdUp = cdUp; + currentScope() { + return this.scopeManager.__currentScope; + } + close(node) { + while (this.currentScope() && node === this.currentScope().block) { + this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); + } + } -/***/ }), + pushInnerMethodDefinition(isInnerMethodDefinition) { + const previous = this.isInnerMethodDefinition; -/***/ 73688: -/***/ (function(module) { + this.isInnerMethodDefinition = isInnerMethodDefinition; + return previous; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + popInnerMethodDefinition(isInnerMethodDefinition) { + this.isInnerMethodDefinition = isInnerMethodDefinition; + } + referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { + const scope = this.currentScope(); + assignments.forEach(assignment => { + scope.__referencing( + pattern, + Reference.WRITE, + assignment.right, + maybeImplicitGlobal, + pattern !== assignment.left, + init + ); + }); + } -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + visitPattern(node, options, callback) { + let visitPatternOptions = options; + let visitPatternCallback = callback; -module.exports = class DirectoryExistsPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | ResolveStepHook} target target - */ - constructor(source, target) { - this.source = source; - this.target = target; - } + if (typeof options === "function") { + visitPatternCallback = options; + visitPatternOptions = { processRightHandNodes: false }; + } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync( - "DirectoryExistsPlugin", - (request, resolveContext, callback) => { - const fs = resolver.fileSystem; - const directory = request.path; - if (!directory) return callback(); - fs.stat(directory, (err, stat) => { - if (err || !stat) { - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(directory); - if (resolveContext.log) - resolveContext.log(directory + " doesn't exist"); - return callback(); - } - if (!stat.isDirectory()) { - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(directory); - if (resolveContext.log) - resolveContext.log(directory + " is not a directory"); - return callback(); - } - if (resolveContext.fileDependencies) - resolveContext.fileDependencies.add(directory); - resolver.doResolve( - target, - request, - `existing directory ${directory}`, - resolveContext, - callback - ); - }); - } - ); - } -}; + traverseIdentifierInPattern( + this.options, + node, + visitPatternOptions.processRightHandNodes ? this : null, + visitPatternCallback + ); + } + visitFunction(node) { + let i, iz; -/***/ }), + // FunctionDeclaration name is defined in upper scope + // NOTE: Not referring variableScope. It is intended. + // Since + // in ES5, FunctionDeclaration should be in FunctionBody. + // in ES6, FunctionDeclaration should be block scoped. -/***/ 80163: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (node.type === Syntax.FunctionDeclaration) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ + // id is defined in upper scope + this.currentScope().__define(node.id, + new Definition( + Variable.FunctionName, + node.id, + node, + null, + null, + null + )); + } + // FunctionExpression with name creates its special scope; + // FunctionExpressionNameScope. + if (node.type === Syntax.FunctionExpression && node.id) { + this.scopeManager.__nestFunctionExpressionNameScope(node); + } + // Consider this function is in the MethodDefinition. + this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); -const path = __webpack_require__(71017); -const DescriptionFileUtils = __webpack_require__(702); -const forEachBail = __webpack_require__(8266); -const { processExportsField } = __webpack_require__(28348); -const { parseIdentifier } = __webpack_require__(7780); -const { checkExportsFieldTarget } = __webpack_require__(3011); + const that = this; -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {import("./util/entrypoints").ExportsField} ExportsField */ -/** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ + /** + * Visit pattern callback + * @param {pattern} pattern - pattern + * @param {Object} info - info + * @returns {void} + */ + function visitPatternCallback(pattern, info) { + that.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + i, + info.rest + )); -module.exports = class ExportsFieldPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {Set} conditionNames condition names - * @param {string | string[]} fieldNamePath name path - * @param {string | ResolveStepHook} target target - */ - constructor(source, conditionNames, fieldNamePath, target) { - this.source = source; - this.target = target; - this.conditionNames = conditionNames; - this.fieldName = fieldNamePath; - /** @type {WeakMap} */ - this.fieldProcessorCache = new WeakMap(); - } - - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("ExportsFieldPlugin", (request, resolveContext, callback) => { - // When there is no description file, abort - if (!request.descriptionFilePath) return callback(); - if ( - // When the description file is inherited from parent, abort - // (There is no description file inside of this package) - request.relativePath !== "." || - request.request === undefined - ) - return callback(); - - const remainingRequest = - request.query || request.fragment - ? (request.request === "." ? "./" : request.request) + - request.query + - request.fragment - : request.request; - /** @type {ExportsField|null} */ - const exportsField = DescriptionFileUtils.getField( - request.descriptionFileData, - this.fieldName - ); - if (!exportsField) return callback(); + that.referencingDefaultValue(pattern, info.assignments, null, true); + } - if (request.directory) { - return callback( - new Error( - `Resolving to directories is not possible with the exports field (request was ${remainingRequest}/)` - ) - ); - } + // Process parameter declarations. + for (i = 0, iz = node.params.length; i < iz; ++i) { + this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback); + } - let paths; + // if there's a rest argument, add that + if (node.rest) { + this.visitPattern({ + type: "RestElement", + argument: node.rest + }, pattern => { + this.currentScope().__define(pattern, + new ParameterDefinition( + pattern, + node, + node.params.length, + true + )); + }); + } - try { - // We attach the cache to the description file instead of the exportsField value - // because we use a WeakMap and the exportsField could be a string too. - // Description file is always an object when exports field can be accessed. - let fieldProcessor = this.fieldProcessorCache.get( - request.descriptionFileData - ); - if (fieldProcessor === undefined) { - fieldProcessor = processExportsField(exportsField); - this.fieldProcessorCache.set( - request.descriptionFileData, - fieldProcessor - ); - } - paths = fieldProcessor(remainingRequest, this.conditionNames); - } catch (err) { - if (resolveContext.log) { - resolveContext.log( - `Exports field in ${request.descriptionFilePath} can't be processed: ${err}` - ); - } - return callback(err); - } + // In TypeScript there are a number of function-like constructs which have no body, + // so check it exists before traversing + if (node.body) { - if (paths.length === 0) { - return callback( - new Error( - `Package path ${remainingRequest} is not exported from package ${request.descriptionFileRoot} (see exports field in ${request.descriptionFilePath})` - ) - ); - } + // Skip BlockStatement to prevent creating BlockStatement scope. + if (node.body.type === Syntax.BlockStatement) { + this.visitChildren(node.body); + } else { + this.visit(node.body); + } + } - forEachBail( - paths, - (p, callback) => { - const parsedIdentifier = parseIdentifier(p); + this.close(node); + } - if (!parsedIdentifier) return callback(); + visitClass(node) { + if (node.type === Syntax.ClassDeclaration) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node, + null, + null, + null + )); + } - const [relativePath, query, fragment] = parsedIdentifier; + this.visit(node.superClass); - const error = checkExportsFieldTarget(relativePath); + this.scopeManager.__nestClassScope(node); - if (error) { - return callback(error); - } + if (node.id) { + this.currentScope().__define(node.id, + new Definition( + Variable.ClassName, + node.id, + node + )); + } + this.visit(node.body); - const obj = { - ...request, - request: undefined, - path: path.join( - /** @type {string} */ (request.descriptionFileRoot), - relativePath - ), - relativePath, - query, - fragment - }; + this.close(node); + } - resolver.doResolve( - target, - obj, - "using exports field: " + p, - resolveContext, - callback - ); - }, - (err, result) => callback(err, result || null) - ); - }); - } -}; + visitProperty(node) { + let previous; + if (node.computed) { + this.visit(node.key); + } -/***/ }), + const isMethodDefinition = node.type === Syntax.MethodDefinition; -/***/ 98699: -/***/ (function(module) { + if (isMethodDefinition) { + previous = this.pushInnerMethodDefinition(true); + } + this.visit(node.value); + if (isMethodDefinition) { + this.popInnerMethodDefinition(previous); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + visitForIn(node) { + if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") { + this.scopeManager.__nestForScope(node); + } + if (node.left.type === Syntax.VariableDeclaration) { + this.visit(node.left); + this.visitPattern(node.left.declarations[0].id, pattern => { + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true); + }); + } else { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false); + }); + } + this.visit(node.right); + this.visit(node.body); -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + this.close(node); + } -module.exports = class FileExistsPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | ResolveStepHook} target target - */ - constructor(source, target) { - this.source = source; - this.target = target; - } + visitVariableDeclaration(variableTargetScope, type, node, index) { - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - const fs = resolver.fileSystem; - resolver - .getHook(this.source) - .tapAsync("FileExistsPlugin", (request, resolveContext, callback) => { - const file = request.path; - if (!file) return callback(); - fs.stat(file, (err, stat) => { - if (err || !stat) { - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(file); - if (resolveContext.log) resolveContext.log(file + " doesn't exist"); - return callback(); - } - if (!stat.isFile()) { - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(file); - if (resolveContext.log) resolveContext.log(file + " is not a file"); - return callback(); - } - if (resolveContext.fileDependencies) - resolveContext.fileDependencies.add(file); - resolver.doResolve( - target, - request, - "existing file: " + file, - resolveContext, - callback - ); - }); - }); - } -}; + const decl = node.declarations[index]; + const init = decl.init; + this.visitPattern(decl.id, { processRightHandNodes: true }, (pattern, info) => { + variableTargetScope.__define( + pattern, + new Definition( + type, + pattern, + decl, + node, + index, + node.kind + ) + ); -/***/ }), + this.referencingDefaultValue(pattern, info.assignments, null, true); + if (init) { + this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true); + } + }); + } -/***/ 86058: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + AssignmentExpression(node) { + if (PatternVisitor.isPattern(node.left)) { + if (node.operator === "=") { + this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { + let maybeImplicitGlobal = null; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ + if (!this.currentScope().isStrict) { + maybeImplicitGlobal = { + pattern, + node + }; + } + this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); + this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false); + }); + } else { + this.currentScope().__referencing(node.left, Reference.RW, node.right); + } + } else { + this.visit(node.left); + } + this.visit(node.right); + } + CatchClause(node) { + this.scopeManager.__nestCatchScope(node); + this.visitPattern(node.param, { processRightHandNodes: true }, (pattern, info) => { + this.currentScope().__define(pattern, + new Definition( + Variable.CatchClause, + node.param, + node, + null, + null, + null + )); + this.referencingDefaultValue(pattern, info.assignments, null, true); + }); + this.visit(node.body); -const path = __webpack_require__(71017); -const DescriptionFileUtils = __webpack_require__(702); -const forEachBail = __webpack_require__(8266); -const { processImportsField } = __webpack_require__(28348); -const { parseIdentifier } = __webpack_require__(7780); + this.close(node); + } -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ -/** @typedef {import("./util/entrypoints").ImportsField} ImportsField */ + Program(node) { + this.scopeManager.__nestGlobalScope(node); -const dotCode = ".".charCodeAt(0); + if (this.scopeManager.__isNodejsScope()) { -module.exports = class ImportsFieldPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {Set} conditionNames condition names - * @param {string | string[]} fieldNamePath name path - * @param {string | ResolveStepHook} targetFile target file - * @param {string | ResolveStepHook} targetPackage target package - */ - constructor( - source, - conditionNames, - fieldNamePath, - targetFile, - targetPackage - ) { - this.source = source; - this.targetFile = targetFile; - this.targetPackage = targetPackage; - this.conditionNames = conditionNames; - this.fieldName = fieldNamePath; - /** @type {WeakMap} */ - this.fieldProcessorCache = new WeakMap(); - } + // Force strictness of GlobalScope to false when using node.js scope. + this.currentScope().isStrict = false; + this.scopeManager.__nestFunctionScope(node, false); + } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const targetFile = resolver.ensureHook(this.targetFile); - const targetPackage = resolver.ensureHook(this.targetPackage); + if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { + this.scopeManager.__nestModuleScope(node); + } - resolver - .getHook(this.source) - .tapAsync("ImportsFieldPlugin", (request, resolveContext, callback) => { - // When there is no description file, abort - if (!request.descriptionFilePath || request.request === undefined) { - return callback(); - } + if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) { + this.currentScope().isStrict = true; + } - const remainingRequest = - request.request + request.query + request.fragment; - /** @type {ImportsField|null} */ - const importsField = DescriptionFileUtils.getField( - request.descriptionFileData, - this.fieldName - ); - if (!importsField) return callback(); + this.visitChildren(node); + this.close(node); + } - if (request.directory) { - return callback( - new Error( - `Resolving to directories is not possible with the imports field (request was ${remainingRequest}/)` - ) - ); - } + Identifier(node) { + this.currentScope().__referencing(node); + } - let paths; + UpdateExpression(node) { + if (PatternVisitor.isPattern(node.argument)) { + this.currentScope().__referencing(node.argument, Reference.RW, null); + } else { + this.visitChildren(node); + } + } - try { - // We attach the cache to the description file instead of the importsField value - // because we use a WeakMap and the importsField could be a string too. - // Description file is always an object when exports field can be accessed. - let fieldProcessor = this.fieldProcessorCache.get( - request.descriptionFileData - ); - if (fieldProcessor === undefined) { - fieldProcessor = processImportsField(importsField); - this.fieldProcessorCache.set( - request.descriptionFileData, - fieldProcessor - ); - } - paths = fieldProcessor(remainingRequest, this.conditionNames); - } catch (err) { - if (resolveContext.log) { - resolveContext.log( - `Imports field in ${request.descriptionFilePath} can't be processed: ${err}` - ); - } - return callback(err); - } + MemberExpression(node) { + this.visit(node.object); + if (node.computed) { + this.visit(node.property); + } + } - if (paths.length === 0) { - return callback( - new Error( - `Package import ${remainingRequest} is not imported from package ${request.descriptionFileRoot} (see imports field in ${request.descriptionFilePath})` - ) - ); - } + Property(node) { + this.visitProperty(node); + } - forEachBail( - paths, - (p, callback) => { - const parsedIdentifier = parseIdentifier(p); + MethodDefinition(node) { + this.visitProperty(node); + } - if (!parsedIdentifier) return callback(); + BreakStatement() {} // eslint-disable-line class-methods-use-this - const [path_, query, fragment] = parsedIdentifier; + ContinueStatement() {} // eslint-disable-line class-methods-use-this - switch (path_.charCodeAt(0)) { - // should be relative - case dotCode: { - const obj = { - ...request, - request: undefined, - path: path.join( - /** @type {string} */ (request.descriptionFileRoot), - path_ - ), - relativePath: path_, - query, - fragment - }; + LabeledStatement(node) { + this.visit(node.body); + } - resolver.doResolve( - targetFile, - obj, - "using imports field: " + p, - resolveContext, - callback - ); - break; - } + ForStatement(node) { - // package resolving - default: { - const obj = { - ...request, - request: path_, - relativePath: path_, - fullySpecified: true, - query, - fragment - }; + // Create ForStatement declaration. + // NOTE: In ES6, ForStatement dynamically generates + // per iteration environment. However, escope is + // a static analyzer, we only generate one scope for ForStatement. + if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") { + this.scopeManager.__nestForScope(node); + } - resolver.doResolve( - targetPackage, - obj, - "using imports field: " + p, - resolveContext, - callback - ); - } - } - }, - (err, result) => callback(err, result || null) - ); - }); - } -}; + this.visitChildren(node); + this.close(node); + } -/***/ }), + ClassExpression(node) { + this.visitClass(node); + } -/***/ 20879: -/***/ (function(module) { + ClassDeclaration(node) { + this.visitClass(node); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + CallExpression(node) { + // Check this is direct call to eval + if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") { + // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and + // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. + this.currentScope().variableScope.__detectEval(); + } + this.visitChildren(node); + } -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } -const namespaceStartCharCode = "@".charCodeAt(0); + this.visitChildren(node); -module.exports = class JoinRequestPartPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | ResolveStepHook} target target - */ - constructor(source, target) { - this.source = source; - this.target = target; - } + this.close(node); + } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync( - "JoinRequestPartPlugin", - (request, resolveContext, callback) => { - const req = request.request || ""; - let i = req.indexOf("/", 3); + ThisExpression() { + this.currentScope().variableScope.__detectThis(); + } - if (i >= 0 && req.charCodeAt(2) === namespaceStartCharCode) { - i = req.indexOf("/", i + 1); - } + WithStatement(node) { + this.visit(node.object); - let moduleName, remainingRequest, fullySpecified; - if (i < 0) { - moduleName = req; - remainingRequest = "."; - fullySpecified = false; - } else { - moduleName = req.slice(0, i); - remainingRequest = "." + req.slice(i); - fullySpecified = request.fullySpecified; - } - const obj = { - ...request, - path: resolver.join(request.path, moduleName), - relativePath: - request.relativePath && - resolver.join(request.relativePath, moduleName), - request: remainingRequest, - fullySpecified - }; - resolver.doResolve(target, obj, null, resolveContext, callback); - } - ); - } -}; + // Then nest scope for WithStatement. + this.scopeManager.__nestWithScope(node); + this.visit(node.body); -/***/ }), + this.close(node); + } -/***/ 71474: -/***/ (function(module) { + VariableDeclaration(node) { + const variableTargetScope = (node.kind === "var") ? this.currentScope().variableScope : this.currentScope(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + for (let i = 0, iz = node.declarations.length; i < iz; ++i) { + const decl = node.declarations[i]; + this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i); + if (decl.init) { + this.visit(decl.init); + } + } + } + // sec 13.11.8 + SwitchStatement(node) { + this.visit(node.discriminant); -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestSwitchScope(node); + } -module.exports = class JoinRequestPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | ResolveStepHook} target target - */ - constructor(source, target) { - this.source = source; - this.target = target; - } + for (let i = 0, iz = node.cases.length; i < iz; ++i) { + this.visit(node.cases[i]); + } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("JoinRequestPlugin", (request, resolveContext, callback) => { - const obj = { - ...request, - path: resolver.join(request.path, request.request), - relativePath: - request.relativePath && - resolver.join(request.relativePath, request.request), - request: undefined - }; - resolver.doResolve(target, obj, null, resolveContext, callback); - }); - } -}; + this.close(node); + } + FunctionDeclaration(node) { + this.visitFunction(node); + } -/***/ }), + FunctionExpression(node) { + this.visitFunction(node); + } -/***/ 47032: -/***/ (function(module) { + ForOfStatement(node) { + this.visitForIn(node); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + ForInStatement(node) { + this.visitForIn(node); + } + ArrowFunctionExpression(node) { + this.visitFunction(node); + } + ImportDeclaration(node) { + assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context."); -/** @typedef {import("./Resolver")} Resolver */ + const importer = new Importer(node, this); -module.exports = class LogInfoPlugin { - constructor(source) { - this.source = source; - } + importer.visit(node); + } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const source = this.source; - resolver - .getHook(this.source) - .tapAsync("LogInfoPlugin", (request, resolveContext, callback) => { - if (!resolveContext.log) return callback(); - const log = resolveContext.log; - const prefix = "[" + source + "] "; - if (request.path) - log(prefix + "Resolving in directory: " + request.path); - if (request.request) - log(prefix + "Resolving request: " + request.request); - if (request.module) log(prefix + "Request is an module request."); - if (request.directory) log(prefix + "Request is a directory request."); - if (request.query) - log(prefix + "Resolving request query: " + request.query); - if (request.fragment) - log(prefix + "Resolving request fragment: " + request.fragment); - if (request.descriptionFilePath) - log( - prefix + "Has description data from " + request.descriptionFilePath - ); - if (request.relativePath) - log( - prefix + - "Relative path from description file is: " + - request.relativePath - ); - callback(); - }); - } -}; + visitExportDeclaration(node) { + if (node.source) { + return; + } + if (node.declaration) { + this.visit(node.declaration); + return; + } + this.visitChildren(node); + } -/***/ }), + // TODO: ExportDeclaration doesn't exist. for bc? + ExportDeclaration(node) { + this.visitExportDeclaration(node); + } -/***/ 73507: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + ExportAllDeclaration(node) { + this.visitExportDeclaration(node); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + ExportDefaultDeclaration(node) { + this.visitExportDeclaration(node); + } + ExportNamedDeclaration(node) { + this.visitExportDeclaration(node); + } + ExportSpecifier(node) { -const path = __webpack_require__(71017); -const DescriptionFileUtils = __webpack_require__(702); + // TODO: `node.id` doesn't exist. for bc? + const local = (node.id || node.local); -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {{name: string|Array, forceRelative: boolean}} MainFieldOptions */ + this.visit(local); + } -const alreadyTriedMainField = Symbol("alreadyTriedMainField"); + MetaProperty() { // eslint-disable-line class-methods-use-this -module.exports = class MainFieldPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {MainFieldOptions} options options - * @param {string | ResolveStepHook} target target - */ - constructor(source, options, target) { - this.source = source; - this.options = options; - this.target = target; - } + // do nothing. + } +} - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("MainFieldPlugin", (request, resolveContext, callback) => { - if ( - request.path !== request.descriptionFileRoot || - request[alreadyTriedMainField] === request.descriptionFilePath || - !request.descriptionFilePath - ) - return callback(); - const filename = path.basename(request.descriptionFilePath); - let mainModule = DescriptionFileUtils.getField( - request.descriptionFileData, - this.options.name - ); +module.exports = Referencer; - if ( - !mainModule || - typeof mainModule !== "string" || - mainModule === "." || - mainModule === "./" - ) { - return callback(); - } - if (this.options.forceRelative && !/^\.\.?\//.test(mainModule)) - mainModule = "./" + mainModule; - const obj = { - ...request, - request: mainModule, - module: false, - directory: mainModule.endsWith("/"), - [alreadyTriedMainField]: request.descriptionFilePath - }; - return resolver.doResolve( - target, - obj, - "use " + - mainModule + - " from " + - this.options.name + - " in " + - filename, - resolveContext, - callback - ); - }); - } -}; +/* vim: set sw=4 ts=4 et tw=80 : */ /***/ }), -/***/ 3688: +/***/ 96988: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + Copyright (C) 2015 Yusuke Suzuki + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. -const forEachBail = __webpack_require__(8266); -const getPaths = __webpack_require__(48608); + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -module.exports = class ModulesInHierachicDirectoriesPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | Array} directories directories - * @param {string | ResolveStepHook} target target - */ - constructor(source, directories, target) { - this.source = source; - this.directories = /** @type {Array} */ ([]).concat(directories); - this.target = target; - } +/* eslint-disable no-underscore-dangle */ - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync( - "ModulesInHierachicDirectoriesPlugin", - (request, resolveContext, callback) => { - const fs = resolver.fileSystem; - const addrs = getPaths(request.path) - .paths.map(p => { - return this.directories.map(d => resolver.join(p, d)); - }) - .reduce((array, p) => { - array.push.apply(array, p); - return array; - }, []); - forEachBail( - addrs, - (addr, callback) => { - fs.stat(addr, (err, stat) => { - if (!err && stat && stat.isDirectory()) { - const obj = { - ...request, - path: addr, - request: "./" + request.request, - module: false - }; - const message = "looking for modules in " + addr; - return resolver.doResolve( - target, - obj, - message, - resolveContext, - callback - ); - } - if (resolveContext.log) - resolveContext.log( - addr + " doesn't exist or is not a directory" - ); - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(addr); - return callback(); - }); - }, - callback - ); - } - ); - } -}; +const Scope = __webpack_require__(16313); +const assert = __webpack_require__(39491); +const GlobalScope = Scope.GlobalScope; +const CatchScope = Scope.CatchScope; +const WithScope = Scope.WithScope; +const ModuleScope = Scope.ModuleScope; +const ClassScope = Scope.ClassScope; +const SwitchScope = Scope.SwitchScope; +const FunctionScope = Scope.FunctionScope; +const ForScope = Scope.ForScope; +const FunctionExpressionNameScope = Scope.FunctionExpressionNameScope; +const BlockScope = Scope.BlockScope; -/***/ }), +/** + * @class ScopeManager + */ +class ScopeManager { + constructor(options) { + this.scopes = []; + this.globalScope = null; + this.__nodeToScope = new WeakMap(); + this.__currentScope = null; + this.__options = options; + this.__declaredVariables = new WeakMap(); + } -/***/ 48952: -/***/ (function(module) { + __useDirective() { + return this.__options.directive; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + __isOptimistic() { + return this.__options.optimistic; + } + __ignoreEval() { + return this.__options.ignoreEval; + } + __isNodejsScope() { + return this.__options.nodejsScope; + } -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + isModule() { + return this.__options.sourceType === "module"; + } -module.exports = class ModulesInRootPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string} path path - * @param {string | ResolveStepHook} target target - */ - constructor(source, path, target) { - this.source = source; - this.path = path; - this.target = target; - } + isImpliedStrict() { + return this.__options.impliedStrict; + } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("ModulesInRootPlugin", (request, resolveContext, callback) => { - const obj = { - ...request, - path: this.path, - request: "./" + request.request, - module: false - }; - resolver.doResolve( - target, - obj, - "looking for modules in " + this.path, - resolveContext, - callback - ); - }); - } -}; - - -/***/ }), - -/***/ 79135: -/***/ (function(module) { + isStrictModeSupported() { + return this.__options.ecmaVersion >= 5; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // Returns appropriate scope for this node. + __get(node) { + return this.__nodeToScope.get(node); + } + /** + * Get variables that are declared by the node. + * + * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`. + * If the node declares nothing, this method returns an empty array. + * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details. + * + * @param {Espree.Node} node - a node to get. + * @returns {Variable[]} variables that declared by the node. + */ + getDeclaredVariables(node) { + return this.__declaredVariables.get(node) || []; + } + /** + * acquire scope from node. + * @method ScopeManager#acquire + * @param {Espree.Node} node - node for the acquired scope. + * @param {boolean=} inner - look up the most inner scope, default value is false. + * @returns {Scope?} Scope from node + */ + acquire(node, inner) { -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + /** + * predicate + * @param {Scope} testScope - scope to test + * @returns {boolean} predicate + */ + function predicate(testScope) { + if (testScope.type === "function" && testScope.functionExpressionScope) { + return false; + } + return true; + } -module.exports = class NextPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | ResolveStepHook} target target - */ - constructor(source, target) { - this.source = source; - this.target = target; - } + const scopes = this.__get(node); - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("NextPlugin", (request, resolveContext, callback) => { - resolver.doResolve(target, request, null, resolveContext, callback); - }); - } -}; + if (!scopes || scopes.length === 0) { + return null; + } + // Heuristic selection from all scopes. + // If you would like to get all scopes, please use ScopeManager#acquireAll. + if (scopes.length === 1) { + return scopes[0]; + } -/***/ }), + if (inner) { + for (let i = scopes.length - 1; i >= 0; --i) { + const scope = scopes[i]; -/***/ 15234: -/***/ (function(module) { + if (predicate(scope)) { + return scope; + } + } + } else { + for (let i = 0, iz = scopes.length; i < iz; ++i) { + const scope = scopes[i]; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (predicate(scope)) { + return scope; + } + } + } + return null; + } + /** + * acquire all scopes from node. + * @method ScopeManager#acquireAll + * @param {Espree.Node} node - node for the acquired scope. + * @returns {Scopes?} Scope array + */ + acquireAll(node) { + return this.__get(node); + } -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + /** + * release the node. + * @method ScopeManager#release + * @param {Espree.Node} node - releasing node. + * @param {boolean=} inner - look up the most inner scope, default value is false. + * @returns {Scope?} upper scope for the node. + */ + release(node, inner) { + const scopes = this.__get(node); -module.exports = class ParsePlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {Partial} requestOptions request options - * @param {string | ResolveStepHook} target target - */ - constructor(source, requestOptions, target) { - this.source = source; - this.requestOptions = requestOptions; - this.target = target; - } + if (scopes && scopes.length) { + const scope = scopes[0].upper; - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("ParsePlugin", (request, resolveContext, callback) => { - const parsed = resolver.parse(/** @type {string} */ (request.request)); - const obj = { ...request, ...parsed, ...this.requestOptions }; - if (request.query && !parsed.query) { - obj.query = request.query; - } - if (request.fragment && !parsed.fragment) { - obj.fragment = request.fragment; - } - if (parsed && resolveContext.log) { - if (parsed.module) resolveContext.log("Parsed request is a module"); - if (parsed.directory) - resolveContext.log("Parsed request is a directory"); - } - // There is an edge-case where a request with # can be a path or a fragment -> try both - if (obj.request && !obj.query && obj.fragment) { - const directory = obj.fragment.endsWith("/"); - const alternative = { - ...obj, - directory, - request: - obj.request + - (obj.directory ? "/" : "") + - (directory ? obj.fragment.slice(0, -1) : obj.fragment), - fragment: "" - }; - resolver.doResolve( - target, - alternative, - null, - resolveContext, - (err, result) => { - if (err) return callback(err); - if (result) return callback(null, result); - resolver.doResolve(target, obj, null, resolveContext, callback); - } - ); - return; - } - resolver.doResolve(target, obj, null, resolveContext, callback); - }); - } -}; + if (!scope) { + return null; + } + return this.acquire(scope.block, inner); + } + return null; + } + attach() { } // eslint-disable-line class-methods-use-this -/***/ }), + detach() { } // eslint-disable-line class-methods-use-this -/***/ 71488: -/***/ (function(module) { + __nestScope(scope) { + if (scope instanceof GlobalScope) { + assert(this.__currentScope === null); + this.globalScope = scope; + } + this.__currentScope = scope; + return scope; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Maël Nison @arcanis -*/ + __nestGlobalScope(node) { + return this.__nestScope(new GlobalScope(this, node)); + } + __nestBlockScope(node) { + return this.__nestScope(new BlockScope(this, this.__currentScope, node)); + } + __nestFunctionScope(node, isMethodDefinition) { + return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + } -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** - * @typedef {Object} PnpApiImpl - * @property {function(string, string, object): string} resolveToUnqualified - */ + __nestForScope(node) { + return this.__nestScope(new ForScope(this, this.__currentScope, node)); + } -module.exports = class PnpPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {PnpApiImpl} pnpApi pnpApi - * @param {string | ResolveStepHook} target target - */ - constructor(source, pnpApi, target) { - this.source = source; - this.pnpApi = pnpApi; - this.target = target; - } + __nestCatchScope(node) { + return this.__nestScope(new CatchScope(this, this.__currentScope, node)); + } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("PnpPlugin", (request, resolveContext, callback) => { - const req = request.request; - if (!req) return callback(); + __nestWithScope(node) { + return this.__nestScope(new WithScope(this, this.__currentScope, node)); + } - // The trailing slash indicates to PnP that this value is a folder rather than a file - const issuer = `${request.path}/`; + __nestClassScope(node) { + return this.__nestScope(new ClassScope(this, this.__currentScope, node)); + } - const packageMatch = /^(@[^/]+\/)?[^/]+/.exec(req); - if (!packageMatch) return callback(); + __nestSwitchScope(node) { + return this.__nestScope(new SwitchScope(this, this.__currentScope, node)); + } - const packageName = packageMatch[0]; - const innerRequest = `.${req.slice(packageName.length)}`; + __nestModuleScope(node) { + return this.__nestScope(new ModuleScope(this, this.__currentScope, node)); + } - let resolution; - let apiResolution; - try { - resolution = this.pnpApi.resolveToUnqualified(packageName, issuer, { - considerBuiltins: false - }); - if (resolveContext.fileDependencies) { - apiResolution = this.pnpApi.resolveToUnqualified("pnpapi", issuer, { - considerBuiltins: false - }); - } - } catch (error) { - if ( - error.code === "MODULE_NOT_FOUND" && - error.pnpCode === "UNDECLARED_DEPENDENCY" - ) { - // This is not a PnP managed dependency. - // Try to continue resolving with our alternatives - if (resolveContext.log) { - resolveContext.log(`request is not managed by the pnpapi`); - for (const line of error.message.split("\n").filter(Boolean)) - resolveContext.log(` ${line}`); - } - return callback(); - } - return callback(error); - } + __nestFunctionExpressionNameScope(node) { + return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node)); + } - if (resolution === packageName) return callback(); + __isES6() { + return this.__options.ecmaVersion >= 6; + } +} - if (apiResolution && resolveContext.fileDependencies) { - resolveContext.fileDependencies.add(apiResolution); - } +module.exports = ScopeManager; - const obj = { - ...request, - path: resolution, - request: innerRequest, - ignoreSymlinks: true, - fullySpecified: request.fullySpecified && innerRequest !== "." - }; - resolver.doResolve( - target, - obj, - `resolved by pnp to ${resolution}`, - resolveContext, - (err, result) => { - if (err) return callback(err); - if (result) return callback(null, result); - // Skip alternatives - return callback(null, null); - } - ); - }); - } -}; +/* vim: set sw=4 ts=4 et tw=80 : */ /***/ }), -/***/ 37432: +/***/ 16313: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Copyright (C) 2015 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +/* eslint-disable no-underscore-dangle */ +/* eslint-disable no-undefined */ -const { AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } = __webpack_require__(41242); -const createInnerContext = __webpack_require__(95478); -const { parseIdentifier } = __webpack_require__(7780); -const { - normalize, - cachedJoin: join, - getType, - PathType -} = __webpack_require__(3011); +const Syntax = (__webpack_require__(18350).Syntax); -/** @typedef {import("./ResolverFactory").ResolveOptions} ResolveOptions */ +const Reference = __webpack_require__(64945); +const Variable = __webpack_require__(82971); +const Definition = (__webpack_require__(70665).Definition); +const assert = __webpack_require__(39491); /** - * @typedef {Object} FileSystemStats - * @property {function(): boolean} isDirectory - * @property {function(): boolean} isFile + * Test if scope is struct + * @param {Scope} scope - scope + * @param {Block} block - block + * @param {boolean} isMethodDefinition - is method definition + * @param {boolean} useDirective - use directive + * @returns {boolean} is strict scope */ +function isStrictScope(scope, block, isMethodDefinition, useDirective) { + let body; -/** - * @typedef {Object} FileSystemDirent - * @property {Buffer | string} name - * @property {function(): boolean} isDirectory - * @property {function(): boolean} isFile - */ + // When upper scope is exists and strict, inner scope is also strict. + if (scope.upper && scope.upper.isStrict) { + return true; + } -/** - * @typedef {Object} PossibleFileSystemError - * @property {string=} code - * @property {number=} errno - * @property {string=} path - * @property {string=} syscall - */ + if (isMethodDefinition) { + return true; + } -/** - * @template T - * @callback FileSystemCallback - * @param {PossibleFileSystemError & Error | null | undefined} err - * @param {T=} result - */ + if (scope.type === "class" || scope.type === "module") { + return true; + } -/** - * @typedef {Object} FileSystem - * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} readFile - * @property {(function(string, FileSystemCallback<(Buffer | string)[] | FileSystemDirent[]>): void) & function(string, object, FileSystemCallback<(Buffer | string)[] | FileSystemDirent[]>): void} readdir - * @property {((function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void)=} readJson - * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} readlink - * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void=} lstat - * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} stat - */ + if (scope.type === "block" || scope.type === "switch") { + return false; + } -/** - * @typedef {Object} SyncFileSystem - * @property {function(string, object=): Buffer | string} readFileSync - * @property {function(string, object=): (Buffer | string)[] | FileSystemDirent[]} readdirSync - * @property {(function(string, object=): object)=} readJsonSync - * @property {function(string, object=): Buffer | string} readlinkSync - * @property {function(string, object=): FileSystemStats=} lstatSync - * @property {function(string, object=): FileSystemStats} statSync - */ + if (scope.type === "function") { + if (block.type === Syntax.ArrowFunctionExpression && block.body.type !== Syntax.BlockStatement) { + return false; + } -/** - * @typedef {Object} ParsedIdentifier - * @property {string} request - * @property {string} query - * @property {string} fragment - * @property {boolean} directory - * @property {boolean} module - * @property {boolean} file - * @property {boolean} internal - */ + if (block.type === Syntax.Program) { + body = block; + } else { + body = block.body; + } -/** - * @typedef {Object} BaseResolveRequest - * @property {string | false} path - * @property {string=} descriptionFilePath - * @property {string=} descriptionFileRoot - * @property {object=} descriptionFileData - * @property {string=} relativePath - * @property {boolean=} ignoreSymlinks - * @property {boolean=} fullySpecified - */ + if (!body) { + return false; + } + } else if (scope.type === "global") { + body = block; + } else { + return false; + } -/** @typedef {BaseResolveRequest & Partial} ResolveRequest */ + // Search 'use strict' directive. + if (useDirective) { + for (let i = 0, iz = body.body.length; i < iz; ++i) { + const stmt = body.body[i]; -/** - * String with special formatting - * @typedef {string} StackEntry - */ + if (stmt.type !== Syntax.DirectiveStatement) { + break; + } + if (stmt.raw === "\"use strict\"" || stmt.raw === "'use strict'") { + return true; + } + } + } else { + for (let i = 0, iz = body.body.length; i < iz; ++i) { + const stmt = body.body[i]; -/** @template T @typedef {{ add: (T) => void }} WriteOnlySet */ + if (stmt.type !== Syntax.ExpressionStatement) { + break; + } + const expr = stmt.expression; + + if (expr.type !== Syntax.Literal || typeof expr.value !== "string") { + break; + } + if (expr.raw !== null && expr.raw !== undefined) { + if (expr.raw === "\"use strict\"" || expr.raw === "'use strict'") { + return true; + } + } else { + if (expr.value === "use strict") { + return true; + } + } + } + } + return false; +} /** - * Resolve context - * @typedef {Object} ResolveContext - * @property {WriteOnlySet=} contextDependencies - * @property {WriteOnlySet=} fileDependencies files that was found on file system - * @property {WriteOnlySet=} missingDependencies dependencies that was not found on file system - * @property {Set=} stack set of hooks' calls. For instance, `resolve → parsedResolve → describedResolve`, - * @property {(function(string): void)=} log log function + * Register scope + * @param {ScopeManager} scopeManager - scope manager + * @param {Scope} scope - scope + * @returns {void} */ +function registerScope(scopeManager, scope) { + scopeManager.scopes.push(scope); -/** @typedef {AsyncSeriesBailHook<[ResolveRequest, ResolveContext], ResolveRequest | null>} ResolveStepHook */ + const scopes = scopeManager.__nodeToScope.get(scope.block); + + if (scopes) { + scopes.push(scope); + } else { + scopeManager.__nodeToScope.set(scope.block, [scope]); + } +} /** - * @param {string} str input string - * @returns {string} in camel case + * Should be statically + * @param {Object} def - def + * @returns {boolean} should be statically */ -function toCamelCase(str) { - return str.replace(/-([a-z])/g, str => str.substr(1).toUpperCase()); +function shouldBeStatically(def) { + return ( + (def.type === Variable.ClassName) || + (def.type === Variable.Variable && def.parent.kind !== "var") + ); } -class Resolver { - /** - * @param {ResolveStepHook} hook hook - * @param {ResolveRequest} request request - * @returns {StackEntry} stack entry - */ - static createStackEntry(hook, request) { - return ( - hook.name + - ": (" + - request.path + - ") " + - (request.request || "") + - (request.query || "") + - (request.fragment || "") + - (request.directory ? " directory" : "") + - (request.module ? " module" : "") - ); - } - - /** - * @param {FileSystem} fileSystem a filesystem - * @param {ResolveOptions} options options - */ - constructor(fileSystem, options) { - this.fileSystem = fileSystem; - this.options = options; - this.hooks = { - /** @type {SyncHook<[ResolveStepHook, ResolveRequest], void>} */ - resolveStep: new SyncHook(["hook", "request"], "resolveStep"), - /** @type {SyncHook<[ResolveRequest, Error]>} */ - noResolve: new SyncHook(["request", "error"], "noResolve"), - /** @type {ResolveStepHook} */ - resolve: new AsyncSeriesBailHook( - ["request", "resolveContext"], - "resolve" - ), - /** @type {AsyncSeriesHook<[ResolveRequest, ResolveContext]>} */ - result: new AsyncSeriesHook(["result", "resolveContext"], "result") - }; - } - - /** - * @param {string | ResolveStepHook} name hook name or hook itself - * @returns {ResolveStepHook} the hook - */ - ensureHook(name) { - if (typeof name !== "string") { - return name; - } - name = toCamelCase(name); - if (/^before/.test(name)) { - return /** @type {ResolveStepHook} */ (this.ensureHook( - name[6].toLowerCase() + name.substr(7) - ).withOptions({ - stage: -10 - })); - } - if (/^after/.test(name)) { - return /** @type {ResolveStepHook} */ (this.ensureHook( - name[5].toLowerCase() + name.substr(6) - ).withOptions({ - stage: 10 - })); - } - const hook = this.hooks[name]; - if (!hook) { - return (this.hooks[name] = new AsyncSeriesBailHook( - ["request", "resolveContext"], - name - )); - } - return hook; - } +/** + * @class Scope + */ +class Scope { + constructor(scopeManager, type, upperScope, block, isMethodDefinition) { - /** - * @param {string | ResolveStepHook} name hook name or hook itself - * @returns {ResolveStepHook} the hook - */ - getHook(name) { - if (typeof name !== "string") { - return name; - } - name = toCamelCase(name); - if (/^before/.test(name)) { - return /** @type {ResolveStepHook} */ (this.getHook( - name[6].toLowerCase() + name.substr(7) - ).withOptions({ - stage: -10 - })); - } - if (/^after/.test(name)) { - return /** @type {ResolveStepHook} */ (this.getHook( - name[5].toLowerCase() + name.substr(6) - ).withOptions({ - stage: 10 - })); - } - const hook = this.hooks[name]; - if (!hook) { - throw new Error(`Hook ${name} doesn't exist`); - } - return hook; - } + /** + * One of 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'. + * @member {String} Scope#type + */ + this.type = type; - /** - * @param {object} context context information object - * @param {string} path context path - * @param {string} request request string - * @returns {string | false} result - */ - resolveSync(context, path, request) { - /** @type {Error | null | undefined} */ - let err = undefined; - /** @type {string | false | undefined} */ - let result = undefined; - let sync = false; - this.resolve(context, path, request, {}, (e, r) => { - err = e; - result = r; - sync = true; - }); - if (!sync) { - throw new Error( - "Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!" - ); - } - if (err) throw err; - if (result === undefined) throw new Error("No result"); - return result; - } + /** + * The scoped {@link Variable}s of this scope, as { Variable.name + * : Variable }. + * @member {Map} Scope#set + */ + this.set = new Map(); - /** - * @param {object} context context information object - * @param {string} path context path - * @param {string} request request string - * @param {ResolveContext} resolveContext resolve context - * @param {function(Error | null, (string|false)=, ResolveRequest=): void} callback callback function - * @returns {void} - */ - resolve(context, path, request, resolveContext, callback) { - if (!context || typeof context !== "object") - return callback(new Error("context argument is not an object")); - if (typeof path !== "string") - return callback(new Error("path argument is not a string")); - if (typeof request !== "string") - return callback(new Error("path argument is not a string")); - if (!resolveContext) - return callback(new Error("resolveContext argument is not set")); + /** + * The tainted variables of this scope, as { Variable.name : + * boolean }. + * @member {Map} Scope#taints */ + this.taints = new Map(); - const obj = { - context: context, - path: path, - request: request - }; + /** + * Generally, through the lexical scoping of JS you can always know + * which variable an identifier in the source code refers to. There are + * a few exceptions to this rule. With 'global' and 'with' scopes you + * can only decide at runtime which variable a reference refers to. + * Moreover, if 'eval()' is used in a scope, it might introduce new + * bindings in this or its parent scopes. + * All those scopes are considered 'dynamic'. + * @member {boolean} Scope#dynamic + */ + this.dynamic = this.type === "global" || this.type === "with"; - const message = `resolve '${request}' in '${path}'`; + /** + * A reference to the scope-defining syntax node. + * @member {espree.Node} Scope#block + */ + this.block = block; - const finishResolved = result => { - return callback( - null, - result.path === false - ? false - : `${result.path.replace(/#/g, "\0#")}${ - result.query ? result.query.replace(/#/g, "\0#") : "" - }${result.fragment || ""}`, - result - ); - }; + /** + * The {@link Reference|references} that are not resolved with this scope. + * @member {Reference[]} Scope#through + */ + this.through = []; - const finishWithoutResolve = log => { - /** - * @type {Error & {details?: string}} - */ - const error = new Error("Can't " + message); - error.details = log.join("\n"); - this.hooks.noResolve.call(obj, error); - return callback(error); - }; + /** + * The scoped {@link Variable}s of this scope. In the case of a + * 'function' scope this includes the automatic argument arguments as + * its first element, as well as all further formal arguments. + * @member {Variable[]} Scope#variables + */ + this.variables = []; - if (resolveContext.log) { - // We need log anyway to capture it in case of an error - const parentLog = resolveContext.log; - const log = []; - return this.doResolve( - this.hooks.resolve, - obj, - message, - { - log: msg => { - parentLog(msg); - log.push(msg); - }, - fileDependencies: resolveContext.fileDependencies, - contextDependencies: resolveContext.contextDependencies, - missingDependencies: resolveContext.missingDependencies, - stack: resolveContext.stack - }, - (err, result) => { - if (err) return callback(err); + /** + * Any variable {@link Reference|reference} found in this scope. This + * includes occurrences of local variables as well as variables from + * parent scopes (including the global scope). For local variables + * this also includes defining occurrences (like in a 'var' statement). + * In a 'function' scope this does not include the occurrences of the + * formal parameter in the parameter list. + * @member {Reference[]} Scope#references + */ + this.references = []; - if (result) return finishResolved(result); + /** + * For 'global' and 'function' scopes, this is a self-reference. For + * other scope types this is the variableScope value of the + * parent scope. + * @member {Scope} Scope#variableScope + */ + this.variableScope = + (this.type === "global" || this.type === "function" || this.type === "module") ? this : upperScope.variableScope; - return finishWithoutResolve(log); - } - ); - } else { - // Try to resolve assuming there is no error - // We don't log stuff in this case - return this.doResolve( - this.hooks.resolve, - obj, - message, - { - log: undefined, - fileDependencies: resolveContext.fileDependencies, - contextDependencies: resolveContext.contextDependencies, - missingDependencies: resolveContext.missingDependencies, - stack: resolveContext.stack - }, - (err, result) => { - if (err) return callback(err); + /** + * Whether this scope is created by a FunctionExpression. + * @member {boolean} Scope#functionExpressionScope + */ + this.functionExpressionScope = false; - if (result) return finishResolved(result); + /** + * Whether this is a scope that contains an 'eval()' invocation. + * @member {boolean} Scope#directCallToEvalScope + */ + this.directCallToEvalScope = false; - // log is missing for the error details - // so we redo the resolving for the log info - // this is more expensive to the success case - // is assumed by default + /** + * @member {boolean} Scope#thisFound + */ + this.thisFound = false; - const log = []; + this.__left = []; - return this.doResolve( - this.hooks.resolve, - obj, - message, - { - log: msg => log.push(msg), - stack: resolveContext.stack - }, - (err, result) => { - if (err) return callback(err); + /** + * Reference to the parent {@link Scope|scope}. + * @member {Scope} Scope#upper + */ + this.upper = upperScope; - return finishWithoutResolve(log); - } - ); - } - ); - } - } + /** + * Whether 'use strict' is in effect in this scope. + * @member {boolean} Scope#isStrict + */ + this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective()); - doResolve(hook, request, message, resolveContext, callback) { - const stackEntry = Resolver.createStackEntry(hook, request); + /** + * List of nested {@link Scope}s. + * @member {Scope[]} Scope#childScopes + */ + this.childScopes = []; + if (this.upper) { + this.upper.childScopes.push(this); + } - let newStack; - if (resolveContext.stack) { - newStack = new Set(resolveContext.stack); - if (resolveContext.stack.has(stackEntry)) { - /** - * Prevent recursion - * @type {Error & {recursion?: boolean}} - */ - const recursionError = new Error( - "Recursion in resolving\nStack:\n " + - Array.from(newStack).join("\n ") - ); - recursionError.recursion = true; - if (resolveContext.log) - resolveContext.log("abort resolving because of recursion"); - return callback(recursionError); - } - newStack.add(stackEntry); - } else { - newStack = new Set([stackEntry]); - } - this.hooks.resolveStep.call(hook, request); + this.__declaredVariables = scopeManager.__declaredVariables; - if (hook.isUsed()) { - const innerContext = createInnerContext( - { - log: resolveContext.log, - fileDependencies: resolveContext.fileDependencies, - contextDependencies: resolveContext.contextDependencies, - missingDependencies: resolveContext.missingDependencies, - stack: newStack - }, - message - ); - return hook.callAsync(request, innerContext, (err, result) => { - if (err) return callback(err); - if (result) return callback(null, result); - callback(); - }); - } else { - callback(); - } - } + registerScope(scopeManager, this); + } - /** - * @param {string} identifier identifier - * @returns {ParsedIdentifier} parsed identifier - */ - parse(identifier) { - const part = { - request: "", - query: "", - fragment: "", - module: false, - directory: false, - file: false, - internal: false - }; + __shouldStaticallyClose(scopeManager) { + return (!this.dynamic || scopeManager.__isOptimistic()); + } - const parsedIdentifier = parseIdentifier(identifier); + __shouldStaticallyCloseForGlobal(ref) { - if (!parsedIdentifier) return part; + // On global scope, let/const/class declarations should be resolved statically. + const name = ref.identifier.name; - [part.request, part.query, part.fragment] = parsedIdentifier; + if (!this.set.has(name)) { + return false; + } - if (part.request.length > 0) { - part.internal = this.isPrivate(identifier); - part.module = this.isModule(part.request); - part.directory = this.isDirectory(part.request); - if (part.directory) { - part.request = part.request.substr(0, part.request.length - 1); - } - } + const variable = this.set.get(name); + const defs = variable.defs; - return part; - } + return defs.length > 0 && defs.every(shouldBeStatically); + } - isModule(path) { - return getType(path) === PathType.Normal; - } + __staticCloseRef(ref) { + if (!this.__resolve(ref)) { + this.__delegateToUpperScope(ref); + } + } - isPrivate(path) { - return getType(path) === PathType.Internal; - } + __dynamicCloseRef(ref) { - /** - * @param {string} path a path - * @returns {boolean} true, if the path is a directory path - */ - isDirectory(path) { - return path.endsWith("/"); - } + // notify all names are through to global + let current = this; - join(path, request) { - return join(path, request); - } + do { + current.through.push(ref); + current = current.upper; + } while (current); + } - normalize(path) { - return normalize(path); - } -} + __globalCloseRef(ref) { -module.exports = Resolver; + // let/const/class declarations should be resolved statically. + // others should be resolved dynamically. + if (this.__shouldStaticallyCloseForGlobal(ref)) { + this.__staticCloseRef(ref); + } else { + this.__dynamicCloseRef(ref); + } + } + __close(scopeManager) { + let closeRef; -/***/ }), + if (this.__shouldStaticallyClose(scopeManager)) { + closeRef = this.__staticCloseRef; + } else if (this.type !== "global") { + closeRef = this.__dynamicCloseRef; + } else { + closeRef = this.__globalCloseRef; + } -/***/ 53990: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // Try Resolving all references in this scope. + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + closeRef.call(this, ref); + } + this.__left = null; + return this.upper; + } + // To override by function scopes. + // References in default parameters isn't resolved to variables which are in their function body. + __isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars + return true; + } -const versions = (__webpack_require__(77282).versions); -const Resolver = __webpack_require__(37432); -const { getType, PathType } = __webpack_require__(3011); - -const SyncAsyncFileSystemDecorator = __webpack_require__(57746); - -const AliasFieldPlugin = __webpack_require__(42752); -const AliasPlugin = __webpack_require__(51547); -const AppendPlugin = __webpack_require__(66477); -const ConditionalPlugin = __webpack_require__(44193); -const DescriptionFilePlugin = __webpack_require__(66826); -const DirectoryExistsPlugin = __webpack_require__(73688); -const ExportsFieldPlugin = __webpack_require__(80163); -const FileExistsPlugin = __webpack_require__(98699); -const ImportsFieldPlugin = __webpack_require__(86058); -const JoinRequestPartPlugin = __webpack_require__(20879); -const JoinRequestPlugin = __webpack_require__(71474); -const MainFieldPlugin = __webpack_require__(73507); -const ModulesInHierachicDirectoriesPlugin = __webpack_require__(3688); -const ModulesInRootPlugin = __webpack_require__(48952); -const NextPlugin = __webpack_require__(79135); -const ParsePlugin = __webpack_require__(15234); -const PnpPlugin = __webpack_require__(71488); -const RestrictionsPlugin = __webpack_require__(39222); -const ResultPlugin = __webpack_require__(10615); -const RootsPlugin = __webpack_require__(34403); -const SelfReferencePlugin = __webpack_require__(32317); -const SymlinkPlugin = __webpack_require__(21300); -const TryNextPlugin = __webpack_require__(16442); -const UnsafeCachePlugin = __webpack_require__(3501); -const UseFilePlugin = __webpack_require__(50318); + __resolve(ref) { + const name = ref.identifier.name; -/** @typedef {import("./AliasPlugin").AliasOption} AliasOptionEntry */ -/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ -/** @typedef {import("./Resolver").FileSystem} FileSystem */ -/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ -/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ + if (!this.set.has(name)) { + return false; + } + const variable = this.set.get(name); -/** @typedef {string|string[]|false} AliasOptionNewRequest */ -/** @typedef {{[k: string]: AliasOptionNewRequest}} AliasOptions */ -/** @typedef {{apply: function(Resolver): void} | function(this: Resolver, Resolver): void} Plugin */ + if (!this.__isValidResolution(ref, variable)) { + return false; + } + variable.references.push(ref); + variable.stack = variable.stack && ref.from.variableScope === this.variableScope; + if (ref.tainted) { + variable.tainted = true; + this.taints.set(variable.name, true); + } + ref.resolved = variable; -/** - * @typedef {Object} UserResolveOptions - * @property {(AliasOptions | AliasOptionEntry[])=} alias A list of module alias configurations or an object which maps key to value - * @property {(AliasOptions | AliasOptionEntry[])=} fallback A list of module alias configurations or an object which maps key to value, applied only after modules option - * @property {(string | string[])[]=} aliasFields A list of alias fields in description files - * @property {(function(ResolveRequest): boolean)=} cachePredicate A function which decides whether a request should be cached or not. An object is passed with at least `path` and `request` properties. - * @property {boolean=} cacheWithContext Whether or not the unsafeCache should include request context as part of the cache key. - * @property {string[]=} descriptionFiles A list of description files to read from - * @property {string[]=} conditionNames A list of exports field condition names. - * @property {boolean=} enforceExtension Enforce that a extension from extensions must be used - * @property {(string | string[])[]=} exportsFields A list of exports fields in description files - * @property {(string | string[])[]=} importsFields A list of imports fields in description files - * @property {string[]=} extensions A list of extensions which should be tried for files - * @property {FileSystem} fileSystem The file system which should be used - * @property {(object | boolean)=} unsafeCache Use this cache object to unsafely cache the successful requests - * @property {boolean=} symlinks Resolve symlinks to their symlinked location - * @property {Resolver=} resolver A prepared Resolver to which the plugins are attached - * @property {string[] | string=} modules A list of directories to resolve modules from, can be absolute path or folder name - * @property {(string | string[] | {name: string | string[], forceRelative: boolean})[]=} mainFields A list of main fields in description files - * @property {string[]=} mainFiles A list of main files in directories - * @property {Plugin[]=} plugins A list of additional resolve plugins which should be applied - * @property {PnpApi | null=} pnpApi A PnP API that should be used - null is "never", undefined is "auto" - * @property {string[]=} roots A list of root paths - * @property {boolean=} fullySpecified The request is already fully specified and no extensions or directories are resolved for it - * @property {boolean=} resolveToContext Resolve to a context instead of a file - * @property {(string|RegExp)[]=} restrictions A list of resolve restrictions - * @property {boolean=} useSyncFileSystemCalls Use only the sync constiants of the file system calls - * @property {boolean=} preferRelative Prefer to resolve module requests as relative requests before falling back to modules - * @property {boolean=} preferAbsolute Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots - */ + return true; + } -/** - * @typedef {Object} ResolveOptions - * @property {AliasOptionEntry[]} alias - * @property {AliasOptionEntry[]} fallback - * @property {Set} aliasFields - * @property {(function(ResolveRequest): boolean)} cachePredicate - * @property {boolean} cacheWithContext - * @property {Set} conditionNames A list of exports field condition names. - * @property {string[]} descriptionFiles - * @property {boolean} enforceExtension - * @property {Set} exportsFields - * @property {Set} importsFields - * @property {Set} extensions - * @property {FileSystem} fileSystem - * @property {object | false} unsafeCache - * @property {boolean} symlinks - * @property {Resolver=} resolver - * @property {Array} modules - * @property {{name: string[], forceRelative: boolean}[]} mainFields - * @property {Set} mainFiles - * @property {Plugin[]} plugins - * @property {PnpApi | null} pnpApi - * @property {Set} roots - * @property {boolean} fullySpecified - * @property {boolean} resolveToContext - * @property {Set} restrictions - * @property {boolean} preferRelative - * @property {boolean} preferAbsolute - */ + __delegateToUpperScope(ref) { + if (this.upper) { + this.upper.__left.push(ref); + } + this.through.push(ref); + } -/** - * @param {PnpApi | null=} option option - * @returns {PnpApi | null} processed option - */ -function processPnpApiOption(option) { - if ( - option === undefined && - /** @type {NodeJS.ProcessVersions & {pnp: string}} */ versions.pnp - ) { - // @ts-ignore - return __webpack_require__(35125); // eslint-disable-line node/no-missing-require - } + __addDeclaredVariablesOfNode(variable, node) { + if (node === null || node === undefined) { + return; + } - return option || null; -} + let variables = this.__declaredVariables.get(node); -/** - * @param {AliasOptions | AliasOptionEntry[] | undefined} alias alias - * @returns {AliasOptionEntry[]} normalized aliases - */ -function normalizeAlias(alias) { - return typeof alias === "object" && !Array.isArray(alias) && alias !== null - ? Object.keys(alias).map(key => { - /** @type {AliasOptionEntry} */ - const obj = { name: key, onlyModule: false, alias: alias[key] }; + if (variables === null || variables === undefined) { + variables = []; + this.__declaredVariables.set(node, variables); + } + if (variables.indexOf(variable) === -1) { + variables.push(variable); + } + } - if (/\$$/.test(key)) { - obj.onlyModule = true; - obj.name = key.substr(0, key.length - 1); - } + __defineGeneric(name, set, variables, node, def) { + let variable; - return obj; - }) - : /** @type {Array} */ (alias) || []; -} + variable = set.get(name); + if (!variable) { + variable = new Variable(name, this); + set.set(name, variable); + variables.push(variable); + } -/** - * @param {UserResolveOptions} options input options - * @returns {ResolveOptions} output options - */ -function createOptions(options) { - const mainFieldsSet = new Set(options.mainFields || ["main"]); - const mainFields = []; + if (def) { + variable.defs.push(def); + this.__addDeclaredVariablesOfNode(variable, def.node); + this.__addDeclaredVariablesOfNode(variable, def.parent); + } + if (node) { + variable.identifiers.push(node); + } + } - for (const item of mainFieldsSet) { - if (typeof item === "string") { - mainFields.push({ - name: [item], - forceRelative: true - }); - } else if (Array.isArray(item)) { - mainFields.push({ - name: item, - forceRelative: true - }); - } else { - mainFields.push({ - name: Array.isArray(item.name) ? item.name : [item.name], - forceRelative: item.forceRelative - }); - } - } + __define(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.set, + this.variables, + node, + def + ); + } + } - return { - alias: normalizeAlias(options.alias), - fallback: normalizeAlias(options.fallback), - aliasFields: new Set(options.aliasFields), - cachePredicate: - options.cachePredicate || - function () { - return true; - }, - cacheWithContext: - typeof options.cacheWithContext !== "undefined" - ? options.cacheWithContext - : true, - exportsFields: new Set(options.exportsFields || ["exports"]), - importsFields: new Set(options.importsFields || ["imports"]), - conditionNames: new Set(options.conditionNames), - descriptionFiles: Array.from( - new Set(options.descriptionFiles || ["package.json"]) - ), - enforceExtension: - options.enforceExtension === undefined - ? options.extensions && options.extensions.includes("") - ? true - : false - : options.enforceExtension, - extensions: new Set(options.extensions || [".js", ".json", ".node"]), - fileSystem: options.useSyncFileSystemCalls - ? new SyncAsyncFileSystemDecorator( - /** @type {SyncFileSystem} */ ( - /** @type {unknown} */ (options.fileSystem) - ) - ) - : options.fileSystem, - unsafeCache: - options.unsafeCache && typeof options.unsafeCache !== "object" - ? {} - : options.unsafeCache || false, - symlinks: typeof options.symlinks !== "undefined" ? options.symlinks : true, - resolver: options.resolver, - modules: mergeFilteredToArray( - Array.isArray(options.modules) - ? options.modules - : options.modules - ? [options.modules] - : ["node_modules"], - item => { - const type = getType(item); - return type === PathType.Normal || type === PathType.Relative; - } - ), - mainFields, - mainFiles: new Set(options.mainFiles || ["index"]), - plugins: options.plugins || [], - pnpApi: processPnpApiOption(options.pnpApi), - roots: new Set(options.roots || undefined), - fullySpecified: options.fullySpecified || false, - resolveToContext: options.resolveToContext || false, - preferRelative: options.preferRelative || false, - preferAbsolute: options.preferAbsolute || false, - restrictions: new Set(options.restrictions) - }; -} + __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) { -/** - * @param {UserResolveOptions} options resolve options - * @returns {Resolver} created resolver - */ -exports.createResolver = function (options) { - const normalizedOptions = createOptions(options); + // because Array element may be null + if (!node || node.type !== Syntax.Identifier) { + return; + } - const { - alias, - fallback, - aliasFields, - cachePredicate, - cacheWithContext, - conditionNames, - descriptionFiles, - enforceExtension, - exportsFields, - importsFields, - extensions, - fileSystem, - fullySpecified, - mainFields, - mainFiles, - modules, - plugins: userPlugins, - pnpApi, - resolveToContext, - preferRelative, - preferAbsolute, - symlinks, - unsafeCache, - resolver: customResolver, - restrictions, - roots - } = normalizedOptions; + // Specially handle like `this`. + if (node.name === "super") { + return; + } - const plugins = userPlugins.slice(); + const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init); - const resolver = customResolver - ? customResolver - : new Resolver(fileSystem, normalizedOptions); + this.references.push(ref); + this.__left.push(ref); + } - //// pipeline //// + __detectEval() { + let current = this; - resolver.ensureHook("resolve"); - resolver.ensureHook("internalResolve"); - resolver.ensureHook("newInteralResolve"); - resolver.ensureHook("parsedResolve"); - resolver.ensureHook("describedResolve"); - resolver.ensureHook("internal"); - resolver.ensureHook("rawModule"); - resolver.ensureHook("module"); - resolver.ensureHook("resolveAsModule"); - resolver.ensureHook("undescribedResolveInPackage"); - resolver.ensureHook("resolveInPackage"); - resolver.ensureHook("resolveInExistingDirectory"); - resolver.ensureHook("relative"); - resolver.ensureHook("describedRelative"); - resolver.ensureHook("directory"); - resolver.ensureHook("undescribedExistingDirectory"); - resolver.ensureHook("existingDirectory"); - resolver.ensureHook("undescribedRawFile"); - resolver.ensureHook("rawFile"); - resolver.ensureHook("file"); - resolver.ensureHook("finalFile"); - resolver.ensureHook("existingFile"); - resolver.ensureHook("resolved"); + this.directCallToEvalScope = true; + do { + current.dynamic = true; + current = current.upper; + } while (current); + } - // resolve - for (const { source, resolveOptions } of [ - { source: "resolve", resolveOptions: { fullySpecified } }, - { source: "internal-resolve", resolveOptions: { fullySpecified: false } } - ]) { - if (unsafeCache) { - plugins.push( - new UnsafeCachePlugin( - source, - cachePredicate, - unsafeCache, - cacheWithContext, - `new-${source}` - ) - ); - plugins.push( - new ParsePlugin(`new-${source}`, resolveOptions, "parsed-resolve") - ); - } else { - plugins.push(new ParsePlugin(source, resolveOptions, "parsed-resolve")); - } - } + __detectThis() { + this.thisFound = true; + } - // parsed-resolve - plugins.push( - new DescriptionFilePlugin( - "parsed-resolve", - descriptionFiles, - false, - "described-resolve" - ) - ); - plugins.push(new NextPlugin("after-parsed-resolve", "described-resolve")); + __isClosed() { + return this.__left === null; + } - // described-resolve - plugins.push(new NextPlugin("described-resolve", "normal-resolve")); - if (fallback.length > 0) { - plugins.push( - new AliasPlugin("described-resolve", fallback, "internal-resolve") - ); - } + /** + * returns resolved {Reference} + * @method Scope#resolve + * @param {Espree.Identifier} ident - identifier to be resolved. + * @returns {Reference} reference + */ + resolve(ident) { + let ref, i, iz; - // normal-resolve - if (alias.length > 0) - plugins.push(new AliasPlugin("normal-resolve", alias, "internal-resolve")); - aliasFields.forEach(item => { - plugins.push( - new AliasFieldPlugin("normal-resolve", item, "internal-resolve") - ); - }); - if (preferRelative) { - plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); - } - plugins.push( - new ConditionalPlugin( - "after-normal-resolve", - { module: true }, - "resolve as module", - false, - "raw-module" - ) - ); - plugins.push( - new ConditionalPlugin( - "after-normal-resolve", - { internal: true }, - "resolve as internal import", - false, - "internal" - ) - ); - if (preferAbsolute) { - plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); - } - if (roots.size > 0) { - plugins.push(new RootsPlugin("after-normal-resolve", roots, "relative")); - } - if (!preferRelative && !preferAbsolute) { - plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); - } + assert(this.__isClosed(), "Scope should be closed."); + assert(ident.type === Syntax.Identifier, "Target should be identifier."); + for (i = 0, iz = this.references.length; i < iz; ++i) { + ref = this.references[i]; + if (ref.identifier === ident) { + return ref; + } + } + return null; + } - // internal - importsFields.forEach(importsField => { - plugins.push( - new ImportsFieldPlugin( - "internal", - conditionNames, - importsField, - "relative", - "internal-resolve" - ) - ); - }); + /** + * returns this scope is static + * @method Scope#isStatic + * @returns {boolean} static + */ + isStatic() { + return !this.dynamic; + } - // raw-module - exportsFields.forEach(exportsField => { - plugins.push( - new SelfReferencePlugin("raw-module", exportsField, "resolve-as-module") - ); - }); - modules.forEach(item => { - if (Array.isArray(item)) { - if (item.includes("node_modules") && pnpApi) { - plugins.push( - new ModulesInHierachicDirectoriesPlugin( - "raw-module", - item.filter(i => i !== "node_modules"), - "module" - ) - ); - plugins.push( - new PnpPlugin("raw-module", pnpApi, "undescribed-resolve-in-package") - ); - } else { - plugins.push( - new ModulesInHierachicDirectoriesPlugin("raw-module", item, "module") - ); - } - } else { - plugins.push(new ModulesInRootPlugin("raw-module", item, "module")); - } - }); + /** + * returns this scope has materialized arguments + * @method Scope#isArgumentsMaterialized + * @returns {boolean} arguemnts materialized + */ + isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this + return true; + } - // module - plugins.push(new JoinRequestPartPlugin("module", "resolve-as-module")); + /** + * returns this scope has materialized `this` reference + * @method Scope#isThisMaterialized + * @returns {boolean} this materialized + */ + isThisMaterialized() { // eslint-disable-line class-methods-use-this + return true; + } - // resolve-as-module - if (!resolveToContext) { - plugins.push( - new ConditionalPlugin( - "resolve-as-module", - { directory: false, request: "." }, - "single file module", - true, - "undescribed-raw-file" - ) - ); - } - plugins.push( - new DirectoryExistsPlugin( - "resolve-as-module", - "undescribed-resolve-in-package" - ) - ); + isUsedName(name) { + if (this.set.has(name)) { + return true; + } + for (let i = 0, iz = this.through.length; i < iz; ++i) { + if (this.through[i].identifier.name === name) { + return true; + } + } + return false; + } +} - // undescribed-resolve-in-package - plugins.push( - new DescriptionFilePlugin( - "undescribed-resolve-in-package", - descriptionFiles, - false, - "resolve-in-package" - ) - ); - plugins.push( - new NextPlugin("after-undescribed-resolve-in-package", "resolve-in-package") - ); +class GlobalScope extends Scope { + constructor(scopeManager, block) { + super(scopeManager, "global", null, block, false); + this.implicit = { + set: new Map(), + variables: [], - // resolve-in-package - exportsFields.forEach(exportsField => { - plugins.push( - new ExportsFieldPlugin( - "resolve-in-package", - conditionNames, - exportsField, - "relative" - ) - ); - }); - plugins.push( - new NextPlugin("resolve-in-package", "resolve-in-existing-directory") - ); + /** + * List of {@link Reference}s that are left to be resolved (i.e. which + * need to be linked to the variable they refer to). + * @member {Reference[]} Scope#implicit#left + */ + left: [] + }; + } - // resolve-in-existing-directory - plugins.push( - new JoinRequestPlugin("resolve-in-existing-directory", "relative") - ); + __close(scopeManager) { + const implicit = []; - // relative - plugins.push( - new DescriptionFilePlugin( - "relative", - descriptionFiles, - true, - "described-relative" - ) - ); - plugins.push(new NextPlugin("after-relative", "described-relative")); + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; - // described-relative - if (resolveToContext) { - plugins.push(new NextPlugin("described-relative", "directory")); - } else { - plugins.push( - new ConditionalPlugin( - "described-relative", - { directory: false }, - null, - true, - "raw-file" - ) - ); - plugins.push( - new ConditionalPlugin( - "described-relative", - { fullySpecified: false }, - "as directory", - true, - "directory" - ) - ); - } + if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { + implicit.push(ref.__maybeImplicitGlobal); + } + } - // directory - plugins.push( - new DirectoryExistsPlugin("directory", "undescribed-existing-directory") - ); + // create an implicit global variable from assignment expression + for (let i = 0, iz = implicit.length; i < iz; ++i) { + const info = implicit[i]; - if (resolveToContext) { - // undescribed-existing-directory - plugins.push(new NextPlugin("undescribed-existing-directory", "resolved")); - } else { - // undescribed-existing-directory - plugins.push( - new DescriptionFilePlugin( - "undescribed-existing-directory", - descriptionFiles, - false, - "existing-directory" - ) - ); - mainFiles.forEach(item => { - plugins.push( - new UseFilePlugin( - "undescribed-existing-directory", - item, - "undescribed-raw-file" - ) - ); - }); + this.__defineImplicit(info.pattern, + new Definition( + Variable.ImplicitGlobalVariable, + info.pattern, + info.node, + null, + null, + null + )); - // described-existing-directory - mainFields.forEach(item => { - plugins.push( - new MainFieldPlugin( - "existing-directory", - item, - "resolve-in-existing-directory" - ) - ); - }); - mainFiles.forEach(item => { - plugins.push( - new UseFilePlugin("existing-directory", item, "undescribed-raw-file") - ); - }); + } - // undescribed-raw-file - plugins.push( - new DescriptionFilePlugin( - "undescribed-raw-file", - descriptionFiles, - true, - "raw-file" - ) - ); - plugins.push(new NextPlugin("after-undescribed-raw-file", "raw-file")); + this.implicit.left = this.__left; - // raw-file - plugins.push( - new ConditionalPlugin( - "raw-file", - { fullySpecified: true }, - null, - false, - "file" - ) - ); - if (!enforceExtension) { - plugins.push(new TryNextPlugin("raw-file", "no extension", "file")); - } - extensions.forEach(item => { - plugins.push(new AppendPlugin("raw-file", item, "file")); - }); + return super.__close(scopeManager); + } - // file - if (alias.length > 0) - plugins.push(new AliasPlugin("file", alias, "internal-resolve")); - aliasFields.forEach(item => { - plugins.push(new AliasFieldPlugin("file", item, "internal-resolve")); - }); - plugins.push(new NextPlugin("file", "final-file")); + __defineImplicit(node, def) { + if (node && node.type === Syntax.Identifier) { + this.__defineGeneric( + node.name, + this.implicit.set, + this.implicit.variables, + node, + def + ); + } + } +} - // final-file - plugins.push(new FileExistsPlugin("final-file", "existing-file")); +class ModuleScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "module", upperScope, block, false); + } +} - // existing-file - if (symlinks) - plugins.push(new SymlinkPlugin("existing-file", "existing-file")); - plugins.push(new NextPlugin("existing-file", "resolved")); - } +class FunctionExpressionNameScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "function-expression-name", upperScope, block, false); + this.__define(block.id, + new Definition( + Variable.FunctionName, + block.id, + block, + null, + null, + null + )); + this.functionExpressionScope = true; + } +} - // resolved - if (restrictions.size > 0) { - plugins.push(new RestrictionsPlugin(resolver.hooks.resolved, restrictions)); - } - plugins.push(new ResultPlugin(resolver.hooks.resolved)); +class CatchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "catch", upperScope, block, false); + } +} - //// RESOLVER //// +class WithScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "with", upperScope, block, false); + } - for (const plugin of plugins) { - if (typeof plugin === "function") { - plugin.call(resolver, resolver); - } else { - plugin.apply(resolver); - } - } + __close(scopeManager) { + if (this.__shouldStaticallyClose(scopeManager)) { + return super.__close(scopeManager); + } - return resolver; -}; + for (let i = 0, iz = this.__left.length; i < iz; ++i) { + const ref = this.__left[i]; -/** - * Merging filtered elements - * @param {string[]} array source array - * @param {function(string): boolean} filter predicate - * @returns {Array} merge result - */ -function mergeFilteredToArray(array, filter) { - /** @type {Array} */ - const result = []; - const set = new Set(array); + ref.tainted = true; + this.__delegateToUpperScope(ref); + } + this.__left = null; - for (const item of set) { - if (filter(item)) { - const lastElement = - result.length > 0 ? result[result.length - 1] : undefined; - if (Array.isArray(lastElement)) { - lastElement.push(item); - } else { - result.push([item]); - } - } else { - result.push(item); - } - } + return this.upper; + } +} - return result; +class BlockScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "block", upperScope, block, false); + } } +class SwitchScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "switch", upperScope, block, false); + } +} -/***/ }), +class FunctionScope extends Scope { + constructor(scopeManager, upperScope, block, isMethodDefinition) { + super(scopeManager, "function", upperScope, block, isMethodDefinition); -/***/ 39222: -/***/ (function(module) { + // section 9.2.13, FunctionDeclarationInstantiation. + // NOTE Arrow functions never have an arguments objects. + if (this.block.type !== Syntax.ArrowFunctionExpression) { + this.__defineArguments(); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ + isArgumentsMaterialized() { + // TODO(Constellation) + // We can more aggressive on this condition like this. + // + // function t() { + // // arguments of t is always hidden. + // function arguments() { + // } + // } + if (this.block.type === Syntax.ArrowFunctionExpression) { + return false; + } + if (!this.isStatic()) { + return true; + } -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + const variable = this.set.get("arguments"); -const slashCode = "/".charCodeAt(0); -const backslashCode = "\\".charCodeAt(0); + assert(variable, "Always have arguments variable."); + return variable.tainted || variable.references.length !== 0; + } -const isInside = (path, parent) => { - if (!path.startsWith(parent)) return false; - if (path.length === parent.length) return true; - const charCode = path.charCodeAt(parent.length); - return charCode === slashCode || charCode === backslashCode; -}; + isThisMaterialized() { + if (!this.isStatic()) { + return true; + } + return this.thisFound; + } -module.exports = class RestrictionsPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {Set} restrictions restrictions - */ - constructor(source, restrictions) { - this.source = source; - this.restrictions = restrictions; - } + __defineArguments() { + this.__defineGeneric( + "arguments", + this.set, + this.variables, + null, + null + ); + this.taints.set("arguments", true); + } - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - resolver - .getHook(this.source) - .tapAsync("RestrictionsPlugin", (request, resolveContext, callback) => { - if (typeof request.path === "string") { - const path = request.path; - for (const rule of this.restrictions) { - if (typeof rule === "string") { - if (!isInside(path, rule)) { - if (resolveContext.log) { - resolveContext.log( - `${path} is not inside of the restriction ${rule}` - ); - } - return callback(null, null); - } - } else if (!rule.test(path)) { - if (resolveContext.log) { - resolveContext.log( - `${path} doesn't match the restriction ${rule}` - ); - } - return callback(null, null); - } - } - } + // References in default parameters isn't resolved to variables which are in their function body. + // const x = 1 + // function f(a = x) { // This `x` is resolved to the `x` in the outer scope. + // const x = 2 + // console.log(a) + // } + __isValidResolution(ref, variable) { - callback(); - }); - } + // If `options.nodejsScope` is true, `this.block` becomes a Program node. + if (this.block.type === "Program") { + return true; + } + + const bodyStart = this.block.body.range[0]; + + // It's invalid resolution in the following case: + return !( + variable.scope === this && + ref.identifier.range[0] < bodyStart && // the reference is in the parameter part. + variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body. + ); + } +} + +class ForScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "for", upperScope, block, false); + } +} + +class ClassScope extends Scope { + constructor(scopeManager, upperScope, block) { + super(scopeManager, "class", upperScope, block, false); + } +} + +module.exports = { + Scope, + GlobalScope, + ModuleScope, + FunctionExpressionNameScope, + CatchScope, + WithScope, + BlockScope, + SwitchScope, + FunctionScope, + ForScope, + ClassScope }; +/* vim: set sw=4 ts=4 et tw=80 : */ + /***/ }), -/***/ 10615: +/***/ 82971: /***/ (function(module) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + Copyright (C) 2015 Yusuke Suzuki + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - -module.exports = class ResultPlugin { - /** - * @param {ResolveStepHook} source source - */ - constructor(source) { - this.source = source; - } - - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - this.source.tapAsync( - "ResultPlugin", - (request, resolverContext, callback) => { - const obj = { ...request }; - if (resolverContext.log) - resolverContext.log("reporting result " + obj.path); - resolver.hooks.result.callAsync(obj, resolverContext, err => { - if (err) return callback(err); - callback(null, obj); - }); - } - ); - } -}; + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ -/***/ }), -/***/ 34403: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * A Variable represents a locally scoped identifier. These include arguments to + * functions. + * @class Variable + */ +class Variable { + constructor(name, scope) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ + /** + * The variable name, as given in the source code. + * @member {String} Variable#name + */ + this.name = name; + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as AST nodes. + * @member {espree.Identifier[]} Variable#identifiers + */ + this.identifiers = []; + /** + * List of {@link Reference|references} of this variable (excluding parameter entries) + * in its defining scope and all nested scopes. For defining + * occurrences only see {@link Variable#defs}. + * @member {Reference[]} Variable#references + */ + this.references = []; -const forEachBail = __webpack_require__(8266); + /** + * List of defining occurrences of this variable (like in 'var ...' + * statements or as parameter), as custom objects. + * @member {Definition[]} Variable#defs + */ + this.defs = []; -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + this.tainted = false; -class RootsPlugin { - /** - * @param {string | ResolveStepHook} source source hook - * @param {Set} roots roots - * @param {string | ResolveStepHook} target target hook - */ - constructor(source, roots, target) { - this.roots = Array.from(roots); - this.source = source; - this.target = target; - } + /** + * Whether this is a stack variable. + * @member {boolean} Variable#stack + */ + this.stack = true; - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); + /** + * Reference to the enclosing Scope. + * @member {Scope} Variable#scope + */ + this.scope = scope; + } +} - resolver - .getHook(this.source) - .tapAsync("RootsPlugin", (request, resolveContext, callback) => { - const req = request.request; - if (!req) return callback(); - if (!req.startsWith("/")) return callback(); +Variable.CatchClause = "CatchClause"; +Variable.Parameter = "Parameter"; +Variable.FunctionName = "FunctionName"; +Variable.ClassName = "ClassName"; +Variable.Variable = "Variable"; +Variable.ImportBinding = "ImportBinding"; +Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable"; - forEachBail( - this.roots, - (root, callback) => { - const path = resolver.join(root, req.slice(1)); - const obj = { - ...request, - path, - relativePath: request.relativePath && path - }; - resolver.doResolve( - target, - obj, - `root path ${root}`, - resolveContext, - callback - ); - }, - callback - ); - }); - } -} +module.exports = Variable; -module.exports = RootsPlugin; +/* vim: set sw=4 ts=4 et tw=80 : */ /***/ }), -/***/ 32317: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 81217: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -"use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Copyright (C) 2014 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +(function () { + 'use strict'; + var estraverse = __webpack_require__(50165); + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } -const DescriptionFileUtils = __webpack_require__(702); + function isProperty(nodeType, key) { + return (nodeType === estraverse.Syntax.ObjectExpression || nodeType === estraverse.Syntax.ObjectPattern) && key === 'properties'; + } -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + function Visitor(visitor, options) { + options = options || {}; -const slashCode = "/".charCodeAt(0); + this.__visitor = visitor || this; + this.__childVisitorKeys = options.childVisitorKeys + ? Object.assign({}, estraverse.VisitorKeys, options.childVisitorKeys) + : estraverse.VisitorKeys; + if (options.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof options.fallback === 'function') { + this.__fallback = options.fallback; + } + } -module.exports = class SelfReferencePlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | string[]} fieldNamePath name path - * @param {string | ResolveStepHook} target target - */ - constructor(source, fieldNamePath, target) { - this.source = source; - this.target = target; - this.fieldName = fieldNamePath; - } + /* Default method for visiting children. + * When you need to call default visiting operation inside custom visiting + * operation, you can use it with `this.visitChildren(node)`. + */ + Visitor.prototype.visitChildren = function (node) { + var type, children, i, iz, j, jz, child; - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("SelfReferencePlugin", (request, resolveContext, callback) => { - if (!request.descriptionFilePath) return callback(); + if (node == null) { + return; + } - const req = request.request; - if (!req) return callback(); + type = node.type || estraverse.Syntax.Property; - // Feature is only enabled when an exports field is present - const exportsField = DescriptionFileUtils.getField( - request.descriptionFileData, - this.fieldName - ); - if (!exportsField) return callback(); + children = this.__childVisitorKeys[type]; + if (!children) { + if (this.__fallback) { + children = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + type + '.'); + } + } - const name = DescriptionFileUtils.getField( - request.descriptionFileData, - "name" - ); - if (typeof name !== "string") return callback(); + for (i = 0, iz = children.length; i < iz; ++i) { + child = node[children[i]]; + if (child) { + if (Array.isArray(child)) { + for (j = 0, jz = child.length; j < jz; ++j) { + if (child[j]) { + if (isNode(child[j]) || isProperty(type, children[i])) { + this.visit(child[j]); + } + } + } + } else if (isNode(child)) { + this.visit(child); + } + } + } + }; - if ( - req.startsWith(name) && - (req.length === name.length || - req.charCodeAt(name.length) === slashCode) - ) { - const remainingRequest = `.${req.slice(name.length)}`; + /* Dispatching node. */ + Visitor.prototype.visit = function (node) { + var type; - const obj = { - ...request, - request: remainingRequest, - path: /** @type {string} */ (request.descriptionFileRoot), - relativePath: "." - }; + if (node == null) { + return; + } - resolver.doResolve( - target, - obj, - "self reference", - resolveContext, - callback - ); - } else { - return callback(); - } - }); - } -}; + type = node.type || estraverse.Syntax.Property; + if (this.__visitor[type]) { + this.__visitor[type].call(this, node); + return; + } + this.visitChildren(node); + }; + + exports.version = __webpack_require__(12166).version; + exports.Visitor = Visitor; + exports.visit = function (node, visitor, options) { + var v = new Visitor(visitor, options); + v.visit(node); + }; +}()); +/* vim: set sw=4 ts=4 et tw=80 : */ /***/ }), -/***/ 21300: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 50165: +/***/ (function(__unused_webpack_module, exports) { -"use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true*/ +(function clone(exports) { + 'use strict'; + var Syntax, + VisitorOption, + VisitorKeys, + BREAK, + SKIP, + REMOVE; + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } -const forEachBail = __webpack_require__(8266); -const getPaths = __webpack_require__(48608); -const { getType, PathType } = __webpack_require__(3011); + // based on LLVM libc++ upper_bound / lower_bound + // MIT License -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + function upperBound(array, func) { + var diff, len, i, current; -module.exports = class SymlinkPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string | ResolveStepHook} target target - */ - constructor(source, target) { - this.source = source; - this.target = target; - } + len = array.length; + i = 0; - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - const fs = resolver.fileSystem; - resolver - .getHook(this.source) - .tapAsync("SymlinkPlugin", (request, resolveContext, callback) => { - if (request.ignoreSymlinks) return callback(); - const pathsResult = getPaths(request.path); - const pathSeqments = pathsResult.seqments; - const paths = pathsResult.paths; + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } - let containsSymlink = false; - let idx = -1; - forEachBail( - paths, - (path, callback) => { - idx++; - if (resolveContext.fileDependencies) - resolveContext.fileDependencies.add(path); - fs.readlink(path, (err, result) => { - if (!err && result) { - pathSeqments[idx] = result; - containsSymlink = true; - // Shortcut when absolute symlink found - const resultType = getType(result.toString()); - if ( - resultType === PathType.AbsoluteWin || - resultType === PathType.AbsolutePosix - ) { - return callback(null, idx); - } - } - callback(); - }); - }, - (err, idx) => { - if (!containsSymlink) return callback(); - const resultSeqments = - typeof idx === "number" - ? pathSeqments.slice(0, idx + 1) - : pathSeqments.slice(); - const result = resultSeqments.reduceRight((a, b) => { - return resolver.join(a, b); - }); - const obj = { - ...request, - path: result - }; - resolver.doResolve( - target, - obj, - "resolved symlink to " + result, - resolveContext, - callback - ); - } - ); - }); - } -}; + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ChainExpression: 'ChainExpression', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportExpression: 'ImportExpression', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ChainExpression: ['expression'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportExpression: ['source'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: ['key', 'value'], + RestElement: [ 'argument' ], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; -/***/ }), + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; -/***/ 57746: -/***/ (function(module) { + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; + Reference.prototype.remove = function remove() { + if (Array.isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; -/** @typedef {import("./Resolver").FileSystem} FileSystem */ -/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } -/** - * @param {SyncFileSystem} fs file system implementation - * @constructor - */ -function SyncAsyncFileSystemDecorator(fs) { - this.fs = fs; + function Controller() { } - this.lstat = undefined; - this.lstatSync = undefined; - const lstatSync = fs.lstatSync; - if (lstatSync) { - this.lstat = (arg, options, callback) => { - let result; - try { - result = lstatSync.call(fs, arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.lstatSync = (arg, options) => lstatSync.call(fs, arg, options); - } + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; - this.stat = (arg, options, callback) => { - let result; - try { - result = callback ? fs.statSync(arg, options) : fs.statSync(arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.statSync = (arg, options) => fs.statSync(arg, options); + function addToPath(result, path) { + if (Array.isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } - this.readdir = (arg, options, callback) => { - let result; - try { - result = fs.readdirSync(arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.readdirSync = (arg, options) => fs.readdirSync(arg, options); + // root node + if (!this.__current.path) { + return null; + } - this.readFile = (arg, options, callback) => { - let result; - try { - result = fs.readFileSync(arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.readFileSync = (arg, options) => fs.readFileSync(arg, options); + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; - this.readlink = (arg, options, callback) => { - let result; - try { - result = fs.readlinkSync(arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.readlinkSync = (arg, options) => fs.readlinkSync(arg, options); + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; - this.readJson = undefined; - this.readJsonSync = undefined; - const readJsonSync = fs.readJsonSync; - if (readJsonSync) { - this.readJson = (arg, options, callback) => { - let result; - try { - result = readJsonSync.call(fs, arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; - this.readJsonSync = (arg, options) => readJsonSync.call(fs, arg, options); - } -} -module.exports = SyncAsyncFileSystemDecorator; + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } + return result; + }; -/***/ }), + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; -/***/ 16442: -/***/ (function(module) { + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + result = undefined; + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; + return result; + }; -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; -module.exports = class TryNextPlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string} message message - * @param {string | ResolveStepHook} target target - */ - constructor(source, message, target) { - this.source = source; - this.message = message; - this.target = target; - } + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("TryNextPlugin", (request, resolveContext, callback) => { - resolver.doResolve( - target, - request, - this.message, - resolveContext, - callback - ); - }); - } -}; + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; -/***/ }), + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } -/***/ 3501: -/***/ (function(module) { + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); + } + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } + + function candidateExistsInLeaveList(leavelist, candidate) { + for (var i = leavelist.length - 1; i >= 0; --i) { + if (leavelist[i].node === candidate) { + return true; + } + } + return false; + } + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {{[k: string]: any}} Cache */ + this.__initialize(root, visitor); -function getCacheId(request, withContext) { - return JSON.stringify({ - context: withContext ? request.context : "", - path: request.path, - query: request.query, - fragment: request.fragment, - request: request.request - }); -} + sentinel = {}; -module.exports = class UnsafeCachePlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {function(ResolveRequest): boolean} filterPredicate filterPredicate - * @param {Cache} cache cache - * @param {boolean} withContext withContext - * @param {string | ResolveStepHook} target target - */ - constructor(source, filterPredicate, cache, withContext, target) { - this.source = source; - this.filterPredicate = filterPredicate; - this.withContext = withContext; - this.cache = cache; - this.target = target; - } + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("UnsafeCachePlugin", (request, resolveContext, callback) => { - if (!this.filterPredicate(request)) return callback(); - const cacheId = getCacheId(request, this.withContext); - const cacheEntry = this.cache[cacheId]; - if (cacheEntry) { - return callback(null, cacheEntry); - } - resolver.doResolve( - target, - request, - null, - resolveContext, - (err, result) => { - if (err) return callback(err); - if (result) return callback(null, (this.cache[cacheId] = result)); - callback(); - } - ); - }); - } -}; + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); + while (worklist.length) { + element = worklist.pop(); -/***/ }), + if (element === sentinel) { + element = leavelist.pop(); -/***/ 50318: -/***/ (function(module) { + ret = this.__execute(visitor.leave, element); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } + if (element.node) { + ret = this.__execute(visitor.enter, element); -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + if (this.__state === BREAK || ret === BREAK) { + return; + } -module.exports = class UseFilePlugin { - /** - * @param {string | ResolveStepHook} source source - * @param {string} filename filename - * @param {string | ResolveStepHook} target target - */ - constructor(source, filename, target) { - this.source = source; - this.filename = filename; - this.target = target; - } + worklist.push(sentinel); + leavelist.push(element); - /** - * @param {Resolver} resolver the resolver - * @returns {void} - */ - apply(resolver) { - const target = resolver.ensureHook(this.target); - resolver - .getHook(this.source) - .tapAsync("UseFilePlugin", (request, resolveContext, callback) => { - const filePath = resolver.join(request.path, this.filename); - const obj = { - ...request, - path: filePath, - relativePath: - request.relativePath && - resolver.join(request.relativePath, this.filename) - }; - resolver.doResolve( - target, - obj, - "using path: " + filePath, - resolveContext, - callback - ); - }); - } -}; + if (this.__state === SKIP || ret === SKIP) { + continue; + } + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } -/***/ }), + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } -/***/ 95478: -/***/ (function(module) { + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (candidateExistsInLeaveList(leavelist, candidate[current2])) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + if (candidateExistsInLeaveList(leavelist, candidate)) { + continue; + } + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; -module.exports = function createInnerContext( - options, - message, - messageOptional -) { - let messageReported = false; - let innerLog = undefined; - if (options.log) { - if (message) { - innerLog = msg => { - if (!messageReported) { - options.log(message); - messageReported = true; - } - options.log(" " + msg); - }; - } else { - innerLog = options.log; - } - } - const childContext = { - log: innerLog, - fileDependencies: options.fileDependencies, - contextDependencies: options.contextDependencies, - missingDependencies: options.missingDependencies, - stack: options.stack - }; - return childContext; -}; + Controller.prototype.replace = function replace(root, visitor) { + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; + function removeElem(element) { + var i, + key, + nextElem, + parent; -/***/ }), + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; -/***/ 8266: -/***/ (function(module) { + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.__initialize(root, visitor); + sentinel = {}; + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; -module.exports = function forEachBail(array, iterator, callback) { - if (array.length === 0) return callback(); + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); - let i = 0; - const next = () => { - let loop = undefined; - iterator(array[i++], (err, result) => { - if (err || result !== undefined || i >= array.length) { - return callback(err, result); - } - if (loop === false) while (next()); - loop = true; - }); - if (!loop) loop = false; - return loop; - }; - while (next()); -}; + while (worklist.length) { + element = worklist.pop(); + if (element === sentinel) { + element = leavelist.pop(); -/***/ }), + target = this.__execute(visitor.leave, element); -/***/ 50290: -/***/ (function(module) { + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } + target = this.__execute(visitor.enter, element); -module.exports = function getInnerRequest(resolver, request) { - if ( - typeof request.__innerRequest === "string" && - request.__innerRequest_request === request.request && - request.__innerRequest_relativePath === request.relativePath - ) - return request.__innerRequest; - let innerRequest; - if (request.request) { - innerRequest = request.request; - if (/^\.\.?(?:\/|$)/.test(innerRequest) && request.relativePath) { - innerRequest = resolver.join(request.relativePath, innerRequest); - } - } else { - innerRequest = request.relativePath; - } - request.__innerRequest_request = request.request; - request.__innerRequest_relativePath = request.relativePath; - return (request.__innerRequest = innerRequest); -}; + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } -/***/ }), + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } -/***/ 48608: -/***/ (function(module) { + // node may be null + node = element.node; + if (!node) { + continue; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + worklist.push(sentinel); + leavelist.push(element); + if (this.__state === SKIP || target === SKIP) { + continue; + } + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } -module.exports = function getPaths(path) { - const parts = path.split(/(.*?[\\/]+)/); - const paths = [path]; - const seqments = [parts[parts.length - 1]]; - let part = parts[parts.length - 1]; - path = path.substr(0, path.length - part.length - 1); - for (let i = parts.length - 2; i > 2; i -= 2) { - paths.push(path); - part = parts[i]; - path = path.substr(0, path.length - part.length) || "/"; - seqments.push(part.substr(0, part.length - 1)); - } - part = parts[1]; - seqments.push(part); - paths.push(part); - return { - paths: paths, - seqments: seqments - }; -}; + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } -module.exports.basename = function basename(path) { - const i = path.lastIndexOf("/"), - j = path.lastIndexOf("\\"); - const p = i < 0 ? j : j < 0 ? i : i < j ? j : i; - if (p < 0) return null; - const s = path.substr(p + 1); - return s; -}; + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } + return outer.root; + }; -/***/ }), + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } -/***/ 30662: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + function extendCommentRange(comment, tokens) { + var target; + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); + comment.extendedRange = [comment.range[0], comment.range[1]]; -const fs = __webpack_require__(90552); -const CachedInputFileSystem = __webpack_require__(89429); -const ResolverFactory = __webpack_require__(53990); + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } -/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ -/** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").FileSystem} FileSystem */ -/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ -/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ -/** @typedef {import("./ResolverFactory").Plugin} Plugin */ -/** @typedef {import("./ResolverFactory").UserResolveOptions} ResolveOptions */ + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } -const nodeFileSystem = new CachedInputFileSystem(fs, 4000); + return comment; + } -const nodeContext = { - environments: ["node+es3+es5+process+native"] -}; + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; -const asyncResolver = ResolverFactory.createResolver({ - conditionNames: ["node"], - extensions: [".js", ".json", ".node"], - fileSystem: nodeFileSystem -}); -function resolve(context, path, request, resolveContext, callback) { - if (typeof context === "string") { - callback = resolveContext; - resolveContext = request; - request = path; - path = context; - context = nodeContext; - } - if (typeof callback !== "function") { - callback = resolveContext; - } - asyncResolver.resolve(context, path, request, resolveContext, callback); -} + if (!tree.range) { + throw new Error('attachComments needs range information'); + } -const syncResolver = ResolverFactory.createResolver({ - conditionNames: ["node"], - extensions: [".js", ".json", ".node"], - useSyncFileSystemCalls: true, - fileSystem: nodeFileSystem -}); -function resolveSync(context, path, request) { - if (typeof context === "string") { - request = path; - path = context; - context = nodeContext; - } - return syncResolver.resolveSync(context, path, request); -} + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } -function create(options) { - options = { - fileSystem: nodeFileSystem, - ...options - }; - const resolver = ResolverFactory.createResolver(options); - return function (context, path, request, resolveContext, callback) { - if (typeof context === "string") { - callback = resolveContext; - resolveContext = request; - request = path; - path = context; - context = nodeContext; - } - if (typeof callback !== "function") { - callback = resolveContext; - } - resolver.resolve(context, path, request, resolveContext, callback); - }; -} + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } -function createSync(options) { - options = { - useSyncFileSystemCalls: true, - fileSystem: nodeFileSystem, - ...options - }; - const resolver = ResolverFactory.createResolver(options); - return function (context, path, request) { - if (typeof context === "string") { - request = path; - path = context; - context = nodeContext; - } - return resolver.resolveSync(context, path, request); - }; -} + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; -/** - * @template A - * @template B - * @param {A} obj input a - * @param {B} exports input b - * @returns {A & B} merged - */ -const mergeExports = (obj, exports) => { - const descriptors = Object.getOwnPropertyDescriptors(exports); - Object.defineProperties(obj, descriptors); - return /** @type {A & B} */ (Object.freeze(obj)); -}; + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } -module.exports = mergeExports(resolve, { - get sync() { - return resolveSync; - }, - create: mergeExports(create, { - get sync() { - return createSync; - } - }), - ResolverFactory, - CachedInputFileSystem, - get CloneBasenamePlugin() { - return __webpack_require__(2020); - }, - get LogInfoPlugin() { - return __webpack_require__(47032); - }, - get forEachBail() { - return __webpack_require__(8266); - } -}); + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } -/***/ }), + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); -/***/ 28348: -/***/ (function(module) { + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } -/** @typedef {string|(string|ConditionalMapping)[]} DirectMapping */ -/** @typedef {{[k: string]: MappingValue}} ConditionalMapping */ -/** @typedef {ConditionalMapping|DirectMapping|null} MappingValue */ -/** @typedef {Record|ConditionalMapping|DirectMapping} ExportsField */ -/** @typedef {Record} ImportsField */ + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); -/** - * @typedef {Object} PathTreeNode - * @property {Map|null} children - * @property {MappingValue} folder - * @property {Map|null} wildcards - * @property {Map} files - */ + return tree; + } -/** - * Processing exports/imports field - * @callback FieldProcessor - * @param {string} request request - * @param {Set} conditionNames condition names - * @returns {string[]} resolved paths - */ + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { return clone({}); }; -/* -Example exports field: -{ - ".": "./main.js", - "./feature": { - "browser": "./feature-browser.js", - "default": "./feature.js" - } -} -Terminology: + return exports; +}(exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ -Enhanced-resolve name keys ("." and "./feature") as exports field keys. -If value is string or string[], mapping is called as a direct mapping -and value called as a direct export. +/***/ }), -If value is key-value object, mapping is called as a conditional mapping -and value called as a conditional export. +/***/ 18350: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -Key in conditional mapping is called condition name. +/* + Copyright (C) 2012-2013 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat -Conditional mapping nested in another conditional mapping is called nested mapping. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: ----------- + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. -Example imports field: -{ - "#a": "./main.js", - "#moment": { - "browser": "./moment/index.js", - "default": "moment" - }, - "#moment/": { - "browser": "./moment/", - "default": "moment/" - } -} -Terminology: + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/*jslint vars:false, bitwise:true*/ +/*jshint indent:4*/ +/*global exports:true*/ +(function clone(exports) { + 'use strict'; -Enhanced-resolve name keys ("#a" and "#moment/", "#moment") as imports field keys. + var Syntax, + VisitorOption, + VisitorKeys, + BREAK, + SKIP, + REMOVE; -If value is string or string[], mapping is called as a direct mapping -and value called as a direct export. + function deepCopy(obj) { + var ret = {}, key, val; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + val = obj[key]; + if (typeof val === 'object' && val !== null) { + ret[key] = deepCopy(val); + } else { + ret[key] = val; + } + } + } + return ret; + } -If value is key-value object, mapping is called as a conditional mapping -and value called as a conditional export. + // based on LLVM libc++ upper_bound / lower_bound + // MIT License -Key in conditional mapping is called condition name. + function upperBound(array, func) { + var diff, len, i, current; -Conditional mapping nested in another conditional mapping is called nested mapping. + len = array.length; + i = 0; -*/ + while (len) { + diff = len >>> 1; + current = i + diff; + if (func(array[current])) { + len = diff; + } else { + i = current + 1; + len -= diff + 1; + } + } + return i; + } -const slashCode = "/".charCodeAt(0); -const dotCode = ".".charCodeAt(0); -const hashCode = "#".charCodeAt(0); + Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. + ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DebuggerStatement: 'DebuggerStatement', + DirectiveStatement: 'DirectiveStatement', + DoWhileStatement: 'DoWhileStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + ForOfStatement: 'ForOfStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportExpression: 'ImportExpression', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + ModuleSpecifier: 'ModuleSpecifier', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; -/** - * @param {ExportsField} exportsField the exports field - * @returns {FieldProcessor} process callback - */ -module.exports.processExportsField = function processExportsField( - exportsField -) { - return createFieldProcessor( - buildExportsFieldPathTree(exportsField), - assertExportsFieldRequest, - assertExportTarget - ); -}; + VisitorKeys = { + AssignmentExpression: ['left', 'right'], + AssignmentPattern: ['left', 'right'], + ArrayExpression: ['elements'], + ArrayPattern: ['elements'], + ArrowFunctionExpression: ['params', 'body'], + AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. + BlockStatement: ['body'], + BinaryExpression: ['left', 'right'], + BreakStatement: ['label'], + CallExpression: ['callee', 'arguments'], + CatchClause: ['param', 'body'], + ClassBody: ['body'], + ClassDeclaration: ['id', 'superClass', 'body'], + ClassExpression: ['id', 'superClass', 'body'], + ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. + ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + ConditionalExpression: ['test', 'consequent', 'alternate'], + ContinueStatement: ['label'], + DebuggerStatement: [], + DirectiveStatement: [], + DoWhileStatement: ['body', 'test'], + EmptyStatement: [], + ExportAllDeclaration: ['source'], + ExportDefaultDeclaration: ['declaration'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], + ExportSpecifier: ['exported', 'local'], + ExpressionStatement: ['expression'], + ForStatement: ['init', 'test', 'update', 'body'], + ForInStatement: ['left', 'right', 'body'], + ForOfStatement: ['left', 'right', 'body'], + FunctionDeclaration: ['id', 'params', 'body'], + FunctionExpression: ['id', 'params', 'body'], + GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. + Identifier: [], + IfStatement: ['test', 'consequent', 'alternate'], + ImportExpression: ['source'], + ImportDeclaration: ['specifiers', 'source'], + ImportDefaultSpecifier: ['local'], + ImportNamespaceSpecifier: ['local'], + ImportSpecifier: ['imported', 'local'], + Literal: [], + LabeledStatement: ['label', 'body'], + LogicalExpression: ['left', 'right'], + MemberExpression: ['object', 'property'], + MetaProperty: ['meta', 'property'], + MethodDefinition: ['key', 'value'], + ModuleSpecifier: [], + NewExpression: ['callee', 'arguments'], + ObjectExpression: ['properties'], + ObjectPattern: ['properties'], + Program: ['body'], + Property: ['key', 'value'], + RestElement: [ 'argument' ], + ReturnStatement: ['argument'], + SequenceExpression: ['expressions'], + SpreadElement: ['argument'], + Super: [], + SwitchStatement: ['discriminant', 'cases'], + SwitchCase: ['test', 'consequent'], + TaggedTemplateExpression: ['tag', 'quasi'], + TemplateElement: [], + TemplateLiteral: ['quasis', 'expressions'], + ThisExpression: [], + ThrowStatement: ['argument'], + TryStatement: ['block', 'handler', 'finalizer'], + UnaryExpression: ['argument'], + UpdateExpression: ['argument'], + VariableDeclaration: ['declarations'], + VariableDeclarator: ['id', 'init'], + WhileStatement: ['test', 'body'], + WithStatement: ['object', 'body'], + YieldExpression: ['argument'] + }; -/** - * @param {ImportsField} importsField the exports field - * @returns {FieldProcessor} process callback - */ -module.exports.processImportsField = function processImportsField( - importsField -) { - return createFieldProcessor( - buildImportsFieldPathTree(importsField), - assertImportsFieldRequest, - assertImportTarget - ); -}; + // unique id + BREAK = {}; + SKIP = {}; + REMOVE = {}; -/** - * @param {PathTreeNode} treeRoot root - * @param {(s: string) => string} assertRequest assertRequest - * @param {(s: string, f: boolean) => void} assertTarget assertTarget - * @returns {FieldProcessor} field processor - */ -function createFieldProcessor(treeRoot, assertRequest, assertTarget) { - return function fieldProcessor(request, conditionNames) { - request = assertRequest(request); + VisitorOption = { + Break: BREAK, + Skip: SKIP, + Remove: REMOVE + }; - const match = findMatch(request, treeRoot); + function Reference(parent, key) { + this.parent = parent; + this.key = key; + } - if (match === null) return []; + Reference.prototype.replace = function replace(node) { + this.parent[this.key] = node; + }; - const [mapping, remainRequestIndex] = match; + Reference.prototype.remove = function remove() { + if (Array.isArray(this.parent)) { + this.parent.splice(this.key, 1); + return true; + } else { + this.replace(null); + return false; + } + }; - /** @type {DirectMapping|null} */ - let direct = null; + function Element(node, path, wrap, ref) { + this.node = node; + this.path = path; + this.wrap = wrap; + this.ref = ref; + } - if (isConditionalMapping(mapping)) { - direct = conditionalMapping( - /** @type {ConditionalMapping} */ (mapping), - conditionNames - ); + function Controller() { } - // matching not found - if (direct === null) return []; - } else { - direct = /** @type {DirectMapping} */ (mapping); - } + // API: + // return property path array from root to current node + Controller.prototype.path = function path() { + var i, iz, j, jz, result, element; - const remainingRequest = - remainRequestIndex === request.length + 1 - ? undefined - : remainRequestIndex < 0 - ? request.slice(-remainRequestIndex - 1) - : request.slice(remainRequestIndex); + function addToPath(result, path) { + if (Array.isArray(path)) { + for (j = 0, jz = path.length; j < jz; ++j) { + result.push(path[j]); + } + } else { + result.push(path); + } + } - return directMapping( - remainingRequest, - remainRequestIndex < 0, - direct, - conditionNames, - assertTarget - ); - }; -} + // root node + if (!this.__current.path) { + return null; + } -/** - * @param {string} request request - * @returns {string} updated request - */ -function assertExportsFieldRequest(request) { - if (request.charCodeAt(0) !== dotCode) { - throw new Error('Request should be relative path and start with "."'); - } - if (request.length === 1) return ""; - if (request.charCodeAt(1) !== slashCode) { - throw new Error('Request should be relative path and start with "./"'); - } - if (request.charCodeAt(request.length - 1) === slashCode) { - throw new Error("Only requesting file allowed"); - } + // first node is sentinel, second node is root element + result = []; + for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { + element = this.__leavelist[i]; + addToPath(result, element.path); + } + addToPath(result, this.__current.path); + return result; + }; - return request.slice(2); -} + // API: + // return type of current node + Controller.prototype.type = function () { + var node = this.current(); + return node.type || this.__current.wrap; + }; -/** - * @param {string} request request - * @returns {string} updated request - */ -function assertImportsFieldRequest(request) { - if (request.charCodeAt(0) !== hashCode) { - throw new Error('Request should start with "#"'); - } - if (request.length === 1) { - throw new Error("Request should have at least 2 characters"); - } - if (request.charCodeAt(1) === slashCode) { - throw new Error('Request should not start with "#/"'); - } - if (request.charCodeAt(request.length - 1) === slashCode) { - throw new Error("Only requesting file allowed"); - } + // API: + // return array of parent elements + Controller.prototype.parents = function parents() { + var i, iz, result; - return request.slice(1); -} + // first node is sentinel + result = []; + for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { + result.push(this.__leavelist[i].node); + } -/** - * @param {string} exp export target - * @param {boolean} expectFolder is folder expected - */ -function assertExportTarget(exp, expectFolder) { - if ( - exp.charCodeAt(0) === slashCode || - (exp.charCodeAt(0) === dotCode && exp.charCodeAt(1) !== slashCode) - ) { - throw new Error( - `Export should be relative path and start with "./", got ${JSON.stringify( - exp - )}.` - ); - } + return result; + }; - const isFolder = exp.charCodeAt(exp.length - 1) === slashCode; + // API: + // return current node + Controller.prototype.current = function current() { + return this.__current.node; + }; - if (isFolder !== expectFolder) { - throw new Error( - expectFolder - ? `Expecting folder to folder mapping. ${JSON.stringify( - exp - )} should end with "/"` - : `Expecting file to file mapping. ${JSON.stringify( - exp - )} should not end with "/"` - ); - } -} + Controller.prototype.__execute = function __execute(callback, element) { + var previous, result; -/** - * @param {string} imp import target - * @param {boolean} expectFolder is folder expected - */ -function assertImportTarget(imp, expectFolder) { - const isFolder = imp.charCodeAt(imp.length - 1) === slashCode; + result = undefined; - if (isFolder !== expectFolder) { - throw new Error( - expectFolder - ? `Expecting folder to folder mapping. ${JSON.stringify( - imp - )} should end with "/"` - : `Expecting file to file mapping. ${JSON.stringify( - imp - )} should not end with "/"` - ); - } -} + previous = this.__current; + this.__current = element; + this.__state = null; + if (callback) { + result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); + } + this.__current = previous; -/** - * Trying to match request to field - * @param {string} request request - * @param {PathTreeNode} treeRoot path tree root - * @returns {[MappingValue, number]|null} match or null, number is negative and one less when it's a folder mapping, number is request.length + 1 for direct mappings - */ -function findMatch(request, treeRoot) { - if (request.length === 0) { - const value = treeRoot.files.get(""); + return result; + }; - return value ? [value, 1] : null; - } + // API: + // notify control skip / break + Controller.prototype.notify = function notify(flag) { + this.__state = flag; + }; - if ( - treeRoot.children === null && - treeRoot.folder === null && - treeRoot.wildcards === null - ) { - const value = treeRoot.files.get(request); + // API: + // skip child nodes of current node + Controller.prototype.skip = function () { + this.notify(SKIP); + }; - return value ? [value, request.length + 1] : null; - } + // API: + // break traversals + Controller.prototype['break'] = function () { + this.notify(BREAK); + }; - let node = treeRoot; - let lastNonSlashIndex = 0; - let slashIndex = request.indexOf("/", 0); + // API: + // remove node + Controller.prototype.remove = function () { + this.notify(REMOVE); + }; - /** @type {[MappingValue, number]|null} */ - let lastFolderMatch = null; + Controller.prototype.__initialize = function(root, visitor) { + this.visitor = visitor; + this.root = root; + this.__worklist = []; + this.__leavelist = []; + this.__current = null; + this.__state = null; + this.__fallback = null; + if (visitor.fallback === 'iteration') { + this.__fallback = Object.keys; + } else if (typeof visitor.fallback === 'function') { + this.__fallback = visitor.fallback; + } - const applyFolderMapping = () => { - const folderMapping = node.folder; - if (folderMapping) { - if (lastFolderMatch) { - lastFolderMatch[0] = folderMapping; - lastFolderMatch[1] = -lastNonSlashIndex - 1; - } else { - lastFolderMatch = [folderMapping, -lastNonSlashIndex - 1]; - } - } - }; + this.__keys = VisitorKeys; + if (visitor.keys) { + this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); + } + }; - const applyWildcardMappings = (wildcardMappings, remainingRequest) => { - if (wildcardMappings) { - for (const [key, target] of wildcardMappings) { - if (remainingRequest.startsWith(key)) { - if (!lastFolderMatch) { - lastFolderMatch = [target, lastNonSlashIndex + key.length]; - } else if (lastFolderMatch[1] < lastNonSlashIndex + key.length) { - lastFolderMatch[0] = target; - lastFolderMatch[1] = lastNonSlashIndex + key.length; - } - } - } - } - }; + function isNode(node) { + if (node == null) { + return false; + } + return typeof node === 'object' && typeof node.type === 'string'; + } - while (slashIndex !== -1) { - applyFolderMapping(); + function isProperty(nodeType, key) { + return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; + } - const wildcardMappings = node.wildcards; + Controller.prototype.traverse = function traverse(root, visitor) { + var worklist, + leavelist, + element, + node, + nodeType, + ret, + key, + current, + current2, + candidates, + candidate, + sentinel; - if (!wildcardMappings && node.children === null) return lastFolderMatch; + this.__initialize(root, visitor); - const folder = request.slice(lastNonSlashIndex, slashIndex); + sentinel = {}; - applyWildcardMappings(wildcardMappings, folder); + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; - if (node.children === null) return lastFolderMatch; + // initialize + worklist.push(new Element(root, null, null, null)); + leavelist.push(new Element(null, null, null, null)); - const newNode = node.children.get(folder); + while (worklist.length) { + element = worklist.pop(); - if (!newNode) { - return lastFolderMatch; - } + if (element === sentinel) { + element = leavelist.pop(); - node = newNode; - lastNonSlashIndex = slashIndex + 1; - slashIndex = request.indexOf("/", lastNonSlashIndex); - } + ret = this.__execute(visitor.leave, element); - const remainingRequest = - lastNonSlashIndex > 0 ? request.slice(lastNonSlashIndex) : request; + if (this.__state === BREAK || ret === BREAK) { + return; + } + continue; + } - const value = node.files.get(remainingRequest); + if (element.node) { - if (value) { - return [value, request.length + 1]; - } + ret = this.__execute(visitor.enter, element); - applyFolderMapping(); + if (this.__state === BREAK || ret === BREAK) { + return; + } - applyWildcardMappings(node.wildcards, remainingRequest); + worklist.push(sentinel); + leavelist.push(element); - return lastFolderMatch; -} + if (this.__state === SKIP || ret === SKIP) { + continue; + } -/** - * @param {ConditionalMapping|DirectMapping|null} mapping mapping - * @returns {boolean} is conditional mapping - */ -function isConditionalMapping(mapping) { - return ( - mapping !== null && typeof mapping === "object" && !Array.isArray(mapping) - ); -} + node = element.node; + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } -/** - * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings - * @param {boolean} subpathMapping true, for subpath mappings - * @param {DirectMapping|null} mappingTarget direct export - * @param {Set} conditionNames condition names - * @param {(d: string, f: boolean) => void} assert asserting direct value - * @returns {string[]} mapping result - */ -function directMapping( - remainingRequest, - subpathMapping, - mappingTarget, - conditionNames, - assert -) { - if (mappingTarget === null) return []; + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } - if (typeof mappingTarget === "string") { - return [ - targetMapping(remainingRequest, subpathMapping, mappingTarget, assert) - ]; - } + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', null); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, null); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, null)); + } + } + } + } + }; - const targets = []; + Controller.prototype.replace = function replace(root, visitor) { + var worklist, + leavelist, + node, + nodeType, + target, + element, + current, + current2, + candidates, + candidate, + sentinel, + outer, + key; - for (const exp of mappingTarget) { - if (typeof exp === "string") { - targets.push( - targetMapping(remainingRequest, subpathMapping, exp, assert) - ); - continue; - } + function removeElem(element) { + var i, + key, + nextElem, + parent; - const mapping = conditionalMapping(exp, conditionNames); - if (!mapping) continue; - const innerExports = directMapping( - remainingRequest, - subpathMapping, - mapping, - conditionNames, - assert - ); - for (const innerExport of innerExports) { - targets.push(innerExport); - } - } + if (element.ref.remove()) { + // When the reference is an element of an array. + key = element.ref.key; + parent = element.ref.parent; - return targets; -} + // If removed from array, then decrease following items' keys. + i = worklist.length; + while (i--) { + nextElem = worklist[i]; + if (nextElem.ref && nextElem.ref.parent === parent) { + if (nextElem.ref.key < key) { + break; + } + --nextElem.ref.key; + } + } + } + } -/** - * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings - * @param {boolean} subpathMapping true, for subpath mappings - * @param {string} mappingTarget direct export - * @param {(d: string, f: boolean) => void} assert asserting direct value - * @returns {string} mapping result - */ -function targetMapping( - remainingRequest, - subpathMapping, - mappingTarget, - assert -) { - if (remainingRequest === undefined) { - assert(mappingTarget, false); - return mappingTarget; - } - if (subpathMapping) { - assert(mappingTarget, true); - return mappingTarget + remainingRequest; - } - assert(mappingTarget, false); - return mappingTarget.replace(/\*/g, remainingRequest.replace(/\$/g, "$$")); -} + this.__initialize(root, visitor); -/** - * @param {ConditionalMapping} conditionalMapping_ conditional mapping - * @param {Set} conditionNames condition names - * @returns {DirectMapping|null} direct mapping if found - */ -function conditionalMapping(conditionalMapping_, conditionNames) { - /** @type {[ConditionalMapping, string[], number][]} */ - let lookup = [[conditionalMapping_, Object.keys(conditionalMapping_), 0]]; + sentinel = {}; - loop: while (lookup.length > 0) { - const [mapping, conditions, j] = lookup[lookup.length - 1]; - const last = conditions.length - 1; + // reference + worklist = this.__worklist; + leavelist = this.__leavelist; - for (let i = j; i < conditions.length; i++) { - const condition = conditions[i]; + // initialize + outer = { + root: root + }; + element = new Element(root, null, null, new Reference(outer, 'root')); + worklist.push(element); + leavelist.push(element); - // assert default. Could be last only - if (i !== last) { - if (condition === "default") { - throw new Error("Default condition should be last one"); - } - } else if (condition === "default") { - const innerMapping = mapping[condition]; - // is nested - if (isConditionalMapping(innerMapping)) { - const conditionalMapping = /** @type {ConditionalMapping} */ (innerMapping); - lookup[lookup.length - 1][2] = i + 1; - lookup.push([conditionalMapping, Object.keys(conditionalMapping), 0]); - continue loop; - } + while (worklist.length) { + element = worklist.pop(); - return /** @type {DirectMapping} */ (innerMapping); - } + if (element === sentinel) { + element = leavelist.pop(); - if (conditionNames.has(condition)) { - const innerMapping = mapping[condition]; - // is nested - if (isConditionalMapping(innerMapping)) { - const conditionalMapping = /** @type {ConditionalMapping} */ (innerMapping); - lookup[lookup.length - 1][2] = i + 1; - lookup.push([conditionalMapping, Object.keys(conditionalMapping), 0]); - continue loop; - } + target = this.__execute(visitor.leave, element); - return /** @type {DirectMapping} */ (innerMapping); - } - } + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + } - lookup.pop(); - } + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + } - return null; -} + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } + continue; + } -/** - * Internal helper to create path tree node - * to ensure that each node gets the same hidden class - * @returns {PathTreeNode} node - */ -function createNode() { - return { - children: null, - folder: null, - wildcards: null, - files: new Map() - }; -} + target = this.__execute(visitor.enter, element); -/** - * Internal helper for building path tree - * @param {PathTreeNode} root root - * @param {string} path path - * @param {MappingValue} target target - */ -function walkPath(root, path, target) { - if (path.length === 0) { - root.folder = target; - return; - } + // node may be replaced with null, + // so distinguish between undefined and null in this place + if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { + // replace + element.ref.replace(target); + element.node = target; + } - let node = root; - // Typical path tree can looks like - // root - // - files: ["a.js", "b.js"] - // - children: - // node1: - // - files: ["a.js", "b.js"] - let lastNonSlashIndex = 0; - let slashIndex = path.indexOf("/", 0); + if (this.__state === REMOVE || target === REMOVE) { + removeElem(element); + element.node = null; + } - while (slashIndex !== -1) { - const folder = path.slice(lastNonSlashIndex, slashIndex); - let newNode; + if (this.__state === BREAK || target === BREAK) { + return outer.root; + } - if (node.children === null) { - newNode = createNode(); - node.children = new Map(); - node.children.set(folder, newNode); - } else { - newNode = node.children.get(folder); + // node may be null + node = element.node; + if (!node) { + continue; + } - if (!newNode) { - newNode = createNode(); - node.children.set(folder, newNode); - } - } + worklist.push(sentinel); + leavelist.push(element); - node = newNode; - lastNonSlashIndex = slashIndex + 1; - slashIndex = path.indexOf("/", lastNonSlashIndex); - } + if (this.__state === SKIP || target === SKIP) { + continue; + } - if (lastNonSlashIndex >= path.length) { - node.folder = target; - } else { - const file = lastNonSlashIndex > 0 ? path.slice(lastNonSlashIndex) : path; - if (file.endsWith("*")) { - if (node.wildcards === null) node.wildcards = new Map(); - node.wildcards.set(file.slice(0, -1), target); - } else { - node.files.set(file, target); - } - } -} + nodeType = node.type || element.wrap; + candidates = this.__keys[nodeType]; + if (!candidates) { + if (this.__fallback) { + candidates = this.__fallback(node); + } else { + throw new Error('Unknown node type ' + nodeType + '.'); + } + } -/** - * @param {ExportsField} field exports field - * @returns {PathTreeNode} tree root - */ -function buildExportsFieldPathTree(field) { - const root = createNode(); + current = candidates.length; + while ((current -= 1) >= 0) { + key = candidates[current]; + candidate = node[key]; + if (!candidate) { + continue; + } - // handle syntax sugar, if exports field is direct mapping for "." - if (typeof field === "string") { - root.files.set("", field); + if (Array.isArray(candidate)) { + current2 = candidate.length; + while ((current2 -= 1) >= 0) { + if (!candidate[current2]) { + continue; + } + if (isProperty(nodeType, candidates[current])) { + element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); + } else if (isNode(candidate[current2])) { + element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); + } else { + continue; + } + worklist.push(element); + } + } else if (isNode(candidate)) { + worklist.push(new Element(candidate, key, null, new Reference(node, key))); + } + } + } - return root; - } else if (Array.isArray(field)) { - root.files.set("", field.slice()); + return outer.root; + }; - return root; - } + function traverse(root, visitor) { + var controller = new Controller(); + return controller.traverse(root, visitor); + } - const keys = Object.keys(field); + function replace(root, visitor) { + var controller = new Controller(); + return controller.replace(root, visitor); + } - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; + function extendCommentRange(comment, tokens) { + var target; - if (key.charCodeAt(0) !== dotCode) { - // handle syntax sugar, if exports field is conditional mapping for "." - if (i === 0) { - while (i < keys.length) { - const charCode = keys[i].charCodeAt(0); - if (charCode === dotCode || charCode === slashCode) { - throw new Error( - `Exports field key should be relative path and start with "." (key: ${JSON.stringify( - key - )})` - ); - } - i++; - } + target = upperBound(tokens, function search(token) { + return token.range[0] > comment.range[0]; + }); - root.files.set("", field); - return root; - } + comment.extendedRange = [comment.range[0], comment.range[1]]; - throw new Error( - `Exports field key should be relative path and start with "." (key: ${JSON.stringify( - key - )})` - ); - } + if (target !== tokens.length) { + comment.extendedRange[1] = tokens[target].range[0]; + } - if (key.length === 1) { - root.files.set("", field[key]); - continue; - } + target -= 1; + if (target >= 0) { + comment.extendedRange[0] = tokens[target].range[1]; + } - if (key.charCodeAt(1) !== slashCode) { - throw new Error( - `Exports field key should be relative path and start with "./" (key: ${JSON.stringify( - key - )})` - ); - } + return comment; + } - walkPath(root, key.slice(2), field[key]); - } + function attachComments(tree, providedComments, tokens) { + // At first, we should calculate extended comment ranges. + var comments = [], comment, len, i, cursor; - return root; -} + if (!tree.range) { + throw new Error('attachComments needs range information'); + } -/** - * @param {ImportsField} field imports field - * @returns {PathTreeNode} root - */ -function buildImportsFieldPathTree(field) { - const root = createNode(); + // tokens array is empty, we attach comments to tree as 'leadingComments' + if (!tokens.length) { + if (providedComments.length) { + for (i = 0, len = providedComments.length; i < len; i += 1) { + comment = deepCopy(providedComments[i]); + comment.extendedRange = [0, tree.range[0]]; + comments.push(comment); + } + tree.leadingComments = comments; + } + return tree; + } - const keys = Object.keys(field); + for (i = 0, len = providedComments.length; i < len; i += 1) { + comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); + } - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; + // This is based on John Freeman's implementation. + cursor = 0; + traverse(tree, { + enter: function (node) { + var comment; - if (key.charCodeAt(0) !== hashCode) { - throw new Error( - `Imports field key should start with "#" (key: ${JSON.stringify(key)})` - ); - } + while (cursor < comments.length) { + comment = comments[cursor]; + if (comment.extendedRange[1] > node.range[0]) { + break; + } - if (key.length === 1) { - throw new Error( - `Imports field key should have at least 2 characters (key: ${JSON.stringify( - key - )})` - ); - } + if (comment.extendedRange[1] === node.range[0]) { + if (!node.leadingComments) { + node.leadingComments = []; + } + node.leadingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } - if (key.charCodeAt(1) === slashCode) { - throw new Error( - `Imports field key should not start with "#/" (key: ${JSON.stringify( - key - )})` - ); - } + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } - walkPath(root, key.slice(1), field[key]); - } + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); - return root; -} + cursor = 0; + traverse(tree, { + leave: function (node) { + var comment; + + while (cursor < comments.length) { + comment = comments[cursor]; + if (node.range[1] < comment.extendedRange[0]) { + break; + } + + if (node.range[1] === comment.extendedRange[0]) { + if (!node.trailingComments) { + node.trailingComments = []; + } + node.trailingComments.push(comment); + comments.splice(cursor, 1); + } else { + cursor += 1; + } + } + + // already out of owned node + if (cursor === comments.length) { + return VisitorOption.Break; + } + + if (comments[cursor].extendedRange[0] > node.range[1]) { + return VisitorOption.Skip; + } + } + }); + + return tree; + } + + exports.version = (__webpack_require__(15535)/* .version */ .i8); + exports.Syntax = Syntax; + exports.traverse = traverse; + exports.replace = replace; + exports.attachComments = attachComments; + exports.VisitorKeys = VisitorKeys; + exports.VisitorOption = VisitorOption; + exports.Controller = Controller; + exports.cloneEnvironment = function () { return clone({}); }; + + return exports; +}(exports)); +/* vim: set sw=4 ts=4 et tw=80 : */ /***/ }), -/***/ 7780: +/***/ 86140: /***/ (function(module) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ +module.exports = function (glob, opts) { + if (typeof glob !== 'string') { + throw new TypeError('Expected a string'); + } + var str = String(glob); + // The regexp we are building, as a string. + var reStr = ""; -const PATH_QUERY_FRAGMENT_REGEXP = /^(#?(?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; + // Whether we are matching so called "extended" globs (like bash) and should + // support single character matching, matching ranges of characters, group + // matching, etc. + var extended = opts ? !!opts.extended : false; -/** - * @param {string} identifier identifier - * @returns {[string, string, string]|null} parsed identifier - */ -function parseIdentifier(identifier) { - const match = PATH_QUERY_FRAGMENT_REGEXP.exec(identifier); + // When globstar is _false_ (default), '/foo/*' is translated a regexp like + // '^\/foo\/.*$' which will match any string beginning with '/foo/' + // When globstar is _true_, '/foo/*' is translated to regexp like + // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT + // which does not have a '/' to the right of it. + // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but + // these will not '/foo/bar/baz', '/foo/bar/baz.txt' + // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when + // globstar is _false_ + var globstar = opts ? !!opts.globstar : false; - if (!match) return null; + // If we are doing extended matching, this boolean is true when we are inside + // a group (eg {*.html,*.js}), and false otherwise. + var inGroup = false; - return [ - match[1].replace(/\0(.)/g, "$1"), - match[2] ? match[2].replace(/\0(.)/g, "$1") : "", - match[3] || "" - ]; -} + // RegExp flags (eg "i" ) to pass in to RegExp constructor. + var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; -module.exports.parseIdentifier = parseIdentifier; + var c; + for (var i = 0, len = str.length; i < len; i++) { + c = str[i]; + switch (c) { + case "/": + case "$": + case "^": + case "+": + case ".": + case "(": + case ")": + case "=": + case "!": + case "|": + reStr += "\\" + c; + break; -/***/ }), + case "?": + if (extended) { + reStr += "."; + break; + } -/***/ 3011: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + case "[": + case "]": + if (extended) { + reStr += c; + break; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + case "{": + if (extended) { + inGroup = true; + reStr += "("; + break; + } + case "}": + if (extended) { + inGroup = false; + reStr += ")"; + break; + } + case ",": + if (inGroup) { + reStr += "|"; + break; + } + reStr += "\\" + c; + break; -const path = __webpack_require__(71017); + case "*": + // Move over all consecutive "*"'s. + // Also store the previous and next characters + var prevChar = str[i - 1]; + var starCount = 1; + while(str[i + 1] === "*") { + starCount++; + i++; + } + var nextChar = str[i + 1]; -const CHAR_HASH = "#".charCodeAt(0); -const CHAR_SLASH = "/".charCodeAt(0); -const CHAR_BACKSLASH = "\\".charCodeAt(0); -const CHAR_A = "A".charCodeAt(0); -const CHAR_Z = "Z".charCodeAt(0); -const CHAR_LOWER_A = "a".charCodeAt(0); -const CHAR_LOWER_Z = "z".charCodeAt(0); -const CHAR_DOT = ".".charCodeAt(0); -const CHAR_COLON = ":".charCodeAt(0); + if (!globstar) { + // globstar is disabled, so treat any number of "*" as one + reStr += ".*"; + } else { + // globstar is enabled, so determine if this is a globstar segment + var isGlobstar = starCount > 1 // multiple "*"'s + && (prevChar === "/" || prevChar === undefined) // from the start of the segment + && (nextChar === "/" || nextChar === undefined) // to the end of the segment -const posixNormalize = path.posix.normalize; -const winNormalize = path.win32.normalize; + if (isGlobstar) { + // it's a globstar, so match zero or more path segments + reStr += "((?:[^/]*(?:\/|$))*)"; + i++; // move over the "/" + } else { + // it's not a globstar, so only match one path segment + reStr += "([^/]*)"; + } + } + break; -/** - * @enum {number} - */ -const PathType = Object.freeze({ - Empty: 0, - Normal: 1, - Relative: 2, - AbsoluteWin: 3, - AbsolutePosix: 4, - Internal: 5 -}); -exports.PathType = PathType; + default: + reStr += c; + } + } -/** - * @param {string} p a path - * @returns {PathType} type of path - */ -const getType = p => { - switch (p.length) { - case 0: - return PathType.Empty; - case 1: { - const c0 = p.charCodeAt(0); - switch (c0) { - case CHAR_DOT: - return PathType.Relative; - case CHAR_SLASH: - return PathType.AbsolutePosix; - case CHAR_HASH: - return PathType.Internal; - } - return PathType.Normal; - } - case 2: { - const c0 = p.charCodeAt(0); - switch (c0) { - case CHAR_DOT: { - const c1 = p.charCodeAt(1); - switch (c1) { - case CHAR_DOT: - case CHAR_SLASH: - return PathType.Relative; - } - return PathType.Normal; - } - case CHAR_SLASH: - return PathType.AbsolutePosix; - case CHAR_HASH: - return PathType.Internal; - } - const c1 = p.charCodeAt(1); - if (c1 === CHAR_COLON) { - if ( - (c0 >= CHAR_A && c0 <= CHAR_Z) || - (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z) - ) { - return PathType.AbsoluteWin; - } - } - return PathType.Normal; - } - } - const c0 = p.charCodeAt(0); - switch (c0) { - case CHAR_DOT: { - const c1 = p.charCodeAt(1); - switch (c1) { - case CHAR_SLASH: - return PathType.Relative; - case CHAR_DOT: { - const c2 = p.charCodeAt(2); - if (c2 === CHAR_SLASH) return PathType.Relative; - return PathType.Normal; - } - } - return PathType.Normal; - } - case CHAR_SLASH: - return PathType.AbsolutePosix; - case CHAR_HASH: - return PathType.Internal; - } - const c1 = p.charCodeAt(1); - if (c1 === CHAR_COLON) { - const c2 = p.charCodeAt(2); - if ( - (c2 === CHAR_BACKSLASH || c2 === CHAR_SLASH) && - ((c0 >= CHAR_A && c0 <= CHAR_Z) || - (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z)) - ) { - return PathType.AbsoluteWin; - } - } - return PathType.Normal; -}; -exports.getType = getType; + // When regexp 'g' flag is specified don't + // constrain the regular expression with ^ & $ + if (!flags || !~flags.indexOf('g')) { + reStr = "^" + reStr + "$"; + } -/** - * @param {string} p a path - * @returns {string} the normalized path - */ -const normalize = p => { - switch (getType(p)) { - case PathType.Empty: - return p; - case PathType.AbsoluteWin: - return winNormalize(p); - case PathType.Relative: { - const r = posixNormalize(p); - return getType(r) === PathType.Relative ? r : `./${r}`; - } - } - return posixNormalize(p); + return new RegExp(reStr, flags); }; -exports.normalize = normalize; -/** - * @param {string} rootPath the root path - * @param {string | undefined} request the request path - * @returns {string} the joined path - */ -const join = (rootPath, request) => { - if (!request) return normalize(rootPath); - const requestType = getType(request); - switch (requestType) { - case PathType.AbsolutePosix: - return posixNormalize(request); - case PathType.AbsoluteWin: - return winNormalize(request); - } - switch (getType(rootPath)) { - case PathType.Normal: - case PathType.Relative: - case PathType.AbsolutePosix: - return posixNormalize(`${rootPath}/${request}`); - case PathType.AbsoluteWin: - return winNormalize(`${rootPath}\\${request}`); - } - switch (requestType) { - case PathType.Empty: - return rootPath; - case PathType.Relative: { - const r = posixNormalize(rootPath); - return getType(r) === PathType.Relative ? r : `./${r}`; - } - } - return posixNormalize(rootPath); -}; -exports.join = join; -const joinCache = new Map(); +/***/ }), -/** - * @param {string} rootPath the root path - * @param {string | undefined} request the request path - * @returns {string} the joined path - */ -const cachedJoin = (rootPath, request) => { - let cacheEntry; - let cache = joinCache.get(rootPath); - if (cache === undefined) { - joinCache.set(rootPath, (cache = new Map())); - } else { - cacheEntry = cache.get(request); - if (cacheEntry !== undefined) return cacheEntry; - } - cacheEntry = join(rootPath, request); - cache.set(request, cacheEntry); - return cacheEntry; -}; -exports.cachedJoin = cachedJoin; +/***/ 89132: +/***/ (function(module) { -const checkExportsFieldTarget = relativePath => { - let lastNonSlashIndex = 2; - let slashIndex = relativePath.indexOf("/", 2); - let cd = 0; +"use strict"; - while (slashIndex !== -1) { - const folder = relativePath.slice(lastNonSlashIndex, slashIndex); - switch (folder) { - case "..": { - cd--; - if (cd < 0) - return new Error( - `Trying to access out of package scope. Requesting ${relativePath}` - ); - break; - } - default: - cd++; - break; - } +module.exports = clone - lastNonSlashIndex = slashIndex + 1; - slashIndex = relativePath.indexOf("/", lastNonSlashIndex); - } -}; -exports.checkExportsFieldTarget = checkExportsFieldTarget; +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +} +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj -/***/ }), + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) -/***/ 70665: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki + return copy +} - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. +/***/ }), - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +/***/ 90552: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +var fs = __webpack_require__(57147) +var polyfills = __webpack_require__(11290) +var legacy = __webpack_require__(54410) +var clone = __webpack_require__(89132) -const Variable = __webpack_require__(82971); +var util = __webpack_require__(73837) -/** - * @class Definition - */ -class Definition { - constructor(type, name, node, parent, index, kind) { +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol - /** - * @member {String} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...). - */ - this.type = type; +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} - /** - * @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence. - */ - this.name = name; +function noop () {} - /** - * @member {espree.Node} Definition#node - the enclosing node of the identifier. - */ - this.node = node; +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} - /** - * @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier. - */ - this.parent = parent; +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } - /** - * @member {Number?} Definition#index - the index in the declaration statement. - */ - this.index = index; +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) - /** - * @member {String?} Definition#kind - the kind of the declaration statement. - */ - this.kind = kind; + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } + + if (typeof cb === 'function') + cb.apply(this, arguments) + }) } -} -/** - * @class ParameterDefinition - */ -class ParameterDefinition extends Definition { - constructor(name, node, index, rest) { - super(Variable.Parameter, name, node, null, index, null); + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) - /** - * Whether the parameter definition is a part of a rest parameter. - * @member {boolean} ParameterDefinition#rest - */ - this.rest = rest; + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() } -} - -module.exports = { - ParameterDefinition, - Definition -}; -/* vim: set sw=4 ts=4 et tw=80 : */ + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + __webpack_require__(39491).equal(fs[gracefulQueue].length, 0) + }) + } +} -/***/ }), +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} -/***/ 36007: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} -"use strict"; -/* - Copyright (C) 2012-2014 Yusuke Suzuki - Copyright (C) 2013 Alex Seville - Copyright (C) 2014 Thiago de Arruda +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + return go$readFile(path, options, cb) - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } -/** - * Escope (escope) is an ECMAScript - * scope analyzer extracted from the esmangle project. - *

- * escope finds lexical scopes in a source program, i.e. areas of that - * program where different occurrences of the same identifier refer to the same - * variable. With each scope the contained variables are collected, and each - * identifier reference in code is linked to its corresponding variable (if - * possible). - *

- * escope works on a syntax tree of the parsed source code which has - * to adhere to the - * Mozilla Parser API. E.g. espree is a parser - * that produces such syntax trees. - *

- * The main interface is the {@link analyze} function. - * @module escope - */ + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + return go$writeFile(path, data, options, cb) -/* eslint no-underscore-dangle: ["error", { "allow": ["__currentScope"] }] */ + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } -const assert = __webpack_require__(39491); + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null -const ScopeManager = __webpack_require__(96988); -const Referencer = __webpack_require__(44585); -const Reference = __webpack_require__(64945); -const Variable = __webpack_require__(82971); -const Scope = (__webpack_require__(16313).Scope); -const version = (__webpack_require__(30290)/* .version */ .i8); + return go$appendFile(path, data, options, cb) -/** - * Set the default options - * @returns {Object} options - */ -function defaultOptions() { - return { - optimistic: false, - directive: false, - nodejsScope: false, - impliedStrict: false, - sourceType: "script", // one of ['script', 'module'] - ecmaVersion: 5, - childVisitorKeys: null, - fallback: "iteration" - }; -} + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } -/** - * Preform deep update on option object - * @param {Object} target - Options - * @param {Object} override - Updates - * @returns {Object} Updated options - */ -function updateDeeply(target, override) { + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 + } + return go$copyFile(src, dest, flags, cb) - /** - * Is hash object - * @param {Object} value - Test value - * @returns {boolean} Result - */ - function isHashObject(value) { - return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp); + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) } + } - for (const key in override) { - if (Object.prototype.hasOwnProperty.call(override, key)) { - const val = override[key]; + var fs$readdir = fs.readdir + fs.readdir = readdir + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - if (isHashObject(val)) { - if (isHashObject(target[key])) { - updateDeeply(target[key], val); - } else { - target[key] = updateDeeply({}, val); - } - } else { - target[key] = val; - } + return go$readdir(path, options, cb) + + function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (files && files.sort) + files.sort() + + if (typeof cb === 'function') + cb.call(this, err, files) } + }) } - return target; -} + } -/** - * Main interface function. Takes an Espree syntax tree and returns the - * analyzed scopes. - * @function analyze - * @param {espree.Tree} tree - Abstract Syntax Tree - * @param {Object} providedOptions - Options that tailor the scope analysis - * @param {boolean} [providedOptions.optimistic=false] - the optimistic flag - * @param {boolean} [providedOptions.directive=false]- the directive flag - * @param {boolean} [providedOptions.ignoreEval=false]- whether to check 'eval()' calls - * @param {boolean} [providedOptions.nodejsScope=false]- whether the whole - * script is executed under node.js environment. When enabled, escope adds - * a function scope immediately following the global scope. - * @param {boolean} [providedOptions.impliedStrict=false]- implied strict mode - * (if ecmaVersion >= 5). - * @param {string} [providedOptions.sourceType='script']- the source type of the script. one of 'script' and 'module' - * @param {number} [providedOptions.ecmaVersion=5]- which ECMAScript version is considered - * @param {Object} [providedOptions.childVisitorKeys=null] - Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option. - * @param {string} [providedOptions.fallback='iteration'] - A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option. - * @returns {ScopeManager} ScopeManager - */ -function analyze(tree, providedOptions) { - const options = updateDeeply(defaultOptions(), providedOptions); - const scopeManager = new ScopeManager(options); - const referencer = new Referencer(options, scopeManager); + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } - referencer.visit(tree); + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } - assert(scopeManager.__currentScope === null, "currentScope should be null."); + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } - return scopeManager; -} + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) -module.exports = { + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) - /** @name module:escope.version */ - version, + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } - /** @name module:escope.Reference */ - Reference, + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() - /** @name module:escope.Variable */ - Variable, + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } - /** @name module:escope.Scope */ - Scope, + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } - /** @name module:escope.ScopeManager */ - ScopeManager, - analyze -}; + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } -/* vim: set sw=4 ts=4 et tw=80 : */ + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null -/***/ }), + return go$open(path, flags, mode, cb) -/***/ 54162: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki + return fs +} - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() +} - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. +// keep track of the timeout between retry() calls +var retryTimer - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime + } + } + // call retry to make sure we're actively processing the queue + retry() +} +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined -/* eslint-disable no-undefined */ + if (fs[gracefulQueue].length === 0) + return -const Syntax = (__webpack_require__(18350).Syntax); -const esrecurse = __webpack_require__(81217); + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] -/** - * Get last array element - * @param {array} xs - array - * @returns {any} Last elment - */ -function getLast(xs) { - return xs[xs.length - 1] || null; + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) + } + } + + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) + } } -class PatternVisitor extends esrecurse.Visitor { - static isPattern(node) { - const nodeType = node.type; - return ( - nodeType === Syntax.Identifier || - nodeType === Syntax.ObjectPattern || - nodeType === Syntax.ArrayPattern || - nodeType === Syntax.SpreadElement || - nodeType === Syntax.RestElement || - nodeType === Syntax.AssignmentPattern - ); - } +/***/ }), - constructor(options, rootPattern, callback) { - super(null, options); - this.rootPattern = rootPattern; - this.callback = callback; - this.assignments = []; - this.rightHandNodes = []; - this.restElements = []; - } +/***/ 54410: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - Identifier(pattern) { - const lastRestElement = getLast(this.restElements); +var Stream = (__webpack_require__(12781).Stream) - this.callback(pattern, { - topLevel: pattern === this.rootPattern, - rest: lastRestElement !== null && lastRestElement !== undefined && lastRestElement.argument === pattern, - assignments: this.assignments - }); - } +module.exports = legacy - Property(property) { +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } - // Computed property's key is a right hand node. - if (property.computed) { - this.rightHandNodes.push(property.key); - } + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); - // If it's shorthand, its key is same as its value. - // If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern). - // If it's not shorthand, the name of new variable is its value's. - this.visit(property.value); - } + Stream.call(this); - ArrayPattern(pattern) { - for (let i = 0, iz = pattern.elements.length; i < iz; ++i) { - const element = pattern.elements[i]; + var self = this; - this.visit(element); - } + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; } - AssignmentPattern(pattern) { - this.assignments.push(pattern); - this.visit(pattern.left); - this.rightHandNodes.push(pattern.right); - this.assignments.pop(); + if (this.encoding) this.setEncoding(this.encoding); + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } + + if (this.start > this.end) { + throw new Error('start must be <= end'); + } + + this.pos = this.start; } - RestElement(pattern) { - this.restElements.push(pattern); - this.visit(pattern.argument); - this.restElements.pop(); + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; } - MemberExpression(node) { + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } - // Computed property's key is a right hand node. - if (node.computed) { - this.rightHandNodes.push(node.property); - } + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } - // the object is only read, write to its property. - this.rightHandNodes.push(node.object); - } + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); - // - // ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression. - // By spec, LeftHandSideExpression is Pattern or MemberExpression. - // (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758) - // But espree 2.0 parses to ArrayExpression, ObjectExpression, etc... - // + Stream.call(this); - SpreadElement(node) { - this.visit(node.argument); - } + this.path = path; + this.fd = null; + this.writable = true; - ArrayExpression(node) { - node.elements.forEach(this.visit, this); + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; } - AssignmentExpression(node) { - this.assignments.push(node); - this.visit(node.left); - this.rightHandNodes.push(node.right); - this.assignments.pop(); + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } + + this.pos = this.start; } - CallExpression(node) { + this.busy = false; + this._queue = []; - // arguments are right hand nodes. - node.arguments.forEach(a => { - this.rightHandNodes.push(a); - }); - this.visit(node.callee); + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); } + } } -module.exports = PatternVisitor; -/* vim: set sw=4 ts=4 et tw=80 : */ +/***/ }), +/***/ 11290: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/***/ }), +var constants = __webpack_require__(22057) -/***/ 64945: -/***/ (function(module) { +var origCwd = process.cwd +var cwd = null -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) +} - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ +module.exports = patch +function patch (fs) { + // (re-)implement some things that are known busted or missing. -const READ = 0x1; -const WRITE = 0x2; -const RW = READ | WRITE; + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } -/** - * A Reference represents a single occurrence of an identifier in code. - * @class Reference - */ -class Reference { - constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) { + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } - /** - * Identifier syntax node. - * @member {espreeIdentifier} Reference#identifier - */ - this.identifier = ident; + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. - /** - * Reference to the enclosing Scope. - * @member {Scope} Reference#from - */ - this.from = scope; + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) - /** - * Whether the reference comes from a dynamic scope (such as 'eval', - * 'with', etc.), and may be trapped by dynamic scopes. - * @member {boolean} Reference#tainted - */ - this.tainted = false; + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) - /** - * The variable this reference is resolved with. - * @member {Variable} Reference#resolved - */ - this.resolved = null; + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) - /** - * The read-write mode of the reference. (Value is one of {@link - * Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}). - * @member {number} Reference#flag - * @private - */ - this.flag = flag; - if (this.isWrite()) { + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) - /** - * If reference is writeable, this is the tree being written to it. - * @member {espreeNode} Reference#writeExpr - */ - this.writeExpr = writeExpr; + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) - /** - * Whether the Reference might refer to a partial value of writeExpr. - * @member {boolean} Reference#partial - */ - this.partial = partial; + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) - /** - * Whether the Reference is to write of initialization. - * @member {boolean} Reference#init - */ - this.init = init; - } - this.__maybeImplicitGlobal = maybeImplicitGlobal; + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) } - - /** - * Whether the reference is static. - * @method Reference#isStatic - * @returns {boolean} static - */ - isStatic() { - return !this.tainted && this.resolved && this.resolved.scope.isStatic(); + fs.lchmodSync = function () {} + } + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) } + fs.lchownSync = function () {} + } - /** - * Whether the reference is writeable. - * @method Reference#isWrite - * @returns {boolean} write - */ - isWrite() { - return !!(this.flag & Reference.WRITE); - } + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. - /** - * Whether the reference is readable. - * @method Reference#isRead - * @returns {boolean} read - */ - isRead() { - return !!(this.flag & Reference.READ); + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + }})(fs.rename) + } + + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) } - /** - * Whether the reference is read-only. - * @method Reference#isReadOnly - * @returns {boolean} read only - */ - isReadOnly() { - return this.flag === Reference.READ; + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) + + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } } + }})(fs.readSync) - /** - * Whether the reference is write-only. - * @method Reference#isWriteOnly - * @returns {boolean} write only - */ - isWriteOnly() { - return this.flag === Reference.WRITE; + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) } - /** - * Whether the reference is read-write. - * @method Reference#isReadWrite - * @returns {boolean} read write - */ - isReadWrite() { - return this.flag === Reference.RW; + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret } -} + } -/** - * @constant Reference.READ - * @private - */ -Reference.READ = READ; + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } -/** - * @constant Reference.WRITE - * @private - */ -Reference.WRITE = WRITE; + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } -/** - * @constant Reference.RW - * @private - */ -Reference.RW = RW; + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } + } -module.exports = Reference; + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } -/* vim: set sw=4 ts=4 et tw=80 : */ + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } -/***/ }), + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } -/***/ 44585: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; + } + } - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + if (er.code === "ENOSYS") + return true + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } -/* eslint-disable no-underscore-dangle */ -/* eslint-disable no-undefined */ + return false + } +} -const Syntax = (__webpack_require__(18350).Syntax); -const esrecurse = __webpack_require__(81217); -const Reference = __webpack_require__(64945); -const Variable = __webpack_require__(82971); -const PatternVisitor = __webpack_require__(54162); -const definition = __webpack_require__(70665); -const assert = __webpack_require__(39491); -const ParameterDefinition = definition.ParameterDefinition; -const Definition = definition.Definition; +/***/ }), -/** - * Traverse identifier in pattern - * @param {Object} options - options - * @param {pattern} rootPattern - root pattern - * @param {Refencer} referencer - referencer - * @param {callback} callback - callback - * @returns {void} - */ -function traverseIdentifierInPattern(options, rootPattern, referencer, callback) { +/***/ 15235: +/***/ (function(module) { - // Call the callback at left hand identifier nodes, and Collect right hand nodes. - const visitor = new PatternVisitor(options, rootPattern, callback); +"use strict"; - visitor.visit(rootPattern); - // Process the right hand nodes recursively. - if (referencer !== null && referencer !== undefined) { - visitor.rightHandNodes.forEach(referencer.visit, referencer); +module.exports = parseJson +function parseJson (txt, reviver, context) { + context = context || 20 + try { + return JSON.parse(txt, reviver) + } catch (e) { + if (typeof txt !== 'string') { + const isEmptyArray = Array.isArray(txt) && txt.length === 0 + const errorMessage = 'Cannot parse ' + + (isEmptyArray ? 'an empty array' : String(txt)) + throw new TypeError(errorMessage) + } + const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) + const errIdx = syntaxErr + ? +syntaxErr[1] + : e.message.match(/^Unexpected end of JSON.*/i) + ? txt.length - 1 + : null + if (errIdx != null) { + const start = errIdx <= context + ? 0 + : errIdx - context + const end = errIdx + context >= txt.length + ? txt.length + : errIdx + context + e.message += ` while parsing near '${ + start === 0 ? '' : '...' + }${txt.slice(start, end)}${ + end === txt.length ? '' : '...' + }'` + } else { + e.message += ` while parsing '${txt.slice(0, context * 2)}'` } + throw e + } } -// Importing ImportDeclaration. -// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation -// https://github.com/estree/estree/blob/master/es6.md#importdeclaration -// FIXME: Now, we don't create module environment, because the context is -// implementation dependent. -class Importer extends esrecurse.Visitor { - constructor(declaration, referencer) { - super(null, referencer.options); - this.declaration = declaration; - this.referencer = referencer; - } +/***/ }), - visitImport(id, specifier) { - this.referencer.visitPattern(id, pattern => { - this.referencer.currentScope().__define(pattern, - new Definition( - Variable.ImportBinding, - pattern, - specifier, - this.declaration, - null, - null - )); - }); - } +/***/ 54983: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - ImportNamespaceSpecifier(node) { - const local = (node.local || node.id); +"use strict"; +var __webpack_unused_export__; - if (local) { - this.visitImport(local, node); - } - } - ImportDefaultSpecifier(node) { - const local = (node.local || node.id); +__webpack_unused_export__ = ({ + value: true +}); +exports.Z = void 0; - this.visitImport(local, node); - } +const { + stringHints, + numberHints +} = __webpack_require__(79926); +/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */ - ImportSpecifier(node) { - const local = (node.local || node.id); +/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */ - if (node.name) { - this.visitImport(node.name, node); - } else { - this.visitImport(local, node); - } - } -} +/** @typedef {import("./validate").Schema} Schema */ -// Referencing variables and creating bindings. -class Referencer extends esrecurse.Visitor { - constructor(options, scopeManager) { - super(null, options); - this.options = options; - this.scopeManager = scopeManager; - this.parent = null; - this.isInnerMethodDefinition = false; - } +/** @typedef {import("./validate").ValidationErrorConfiguration} ValidationErrorConfiguration */ - currentScope() { - return this.scopeManager.__currentScope; - } +/** @typedef {import("./validate").PostFormatter} PostFormatter */ - close(node) { - while (this.currentScope() && node === this.currentScope().block) { - this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager); - } - } +/** @typedef {import("./validate").SchemaUtilErrorObject} SchemaUtilErrorObject */ - pushInnerMethodDefinition(isInnerMethodDefinition) { - const previous = this.isInnerMethodDefinition; +/** @enum {number} */ - this.isInnerMethodDefinition = isInnerMethodDefinition; - return previous; - } - popInnerMethodDefinition(isInnerMethodDefinition) { - this.isInnerMethodDefinition = isInnerMethodDefinition; - } +const SPECIFICITY = { + type: 1, + not: 1, + oneOf: 1, + anyOf: 1, + if: 1, + enum: 1, + const: 1, + instanceof: 1, + required: 2, + pattern: 2, + patternRequired: 2, + format: 2, + formatMinimum: 2, + formatMaximum: 2, + minimum: 2, + exclusiveMinimum: 2, + maximum: 2, + exclusiveMaximum: 2, + multipleOf: 2, + uniqueItems: 2, + contains: 2, + minLength: 2, + maxLength: 2, + minItems: 2, + maxItems: 2, + minProperties: 2, + maxProperties: 2, + dependencies: 2, + propertyNames: 2, + additionalItems: 2, + additionalProperties: 2, + absolutePath: 2 +}; +/** + * + * @param {Array} array + * @param {(item: SchemaUtilErrorObject) => number} fn + * @returns {Array} + */ - referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) { - const scope = this.currentScope(); +function filterMax(array, fn) { + const evaluatedMax = array.reduce((max, item) => Math.max(max, fn(item)), 0); + return array.filter(item => fn(item) === evaluatedMax); +} +/** + * + * @param {Array} children + * @returns {Array} + */ - assignments.forEach(assignment => { - scope.__referencing( - pattern, - Reference.WRITE, - assignment.right, - maybeImplicitGlobal, - pattern !== assignment.left, - init - ); - }); - } - visitPattern(node, options, callback) { - let visitPatternOptions = options; - let visitPatternCallback = callback; +function filterChildren(children) { + let newChildren = children; + newChildren = filterMax(newChildren, + /** + * + * @param {SchemaUtilErrorObject} error + * @returns {number} + */ + error => error.dataPath ? error.dataPath.length : 0); + newChildren = filterMax(newChildren, + /** + * @param {SchemaUtilErrorObject} error + * @returns {number} + */ + error => SPECIFICITY[ + /** @type {keyof typeof SPECIFICITY} */ + error.keyword] || 2); + return newChildren; +} +/** + * Find all children errors + * @param {Array} children + * @param {Array} schemaPaths + * @return {number} returns index of first child + */ - if (typeof options === "function") { - visitPatternCallback = options; - visitPatternOptions = { processRightHandNodes: false }; - } - traverseIdentifierInPattern( - this.options, - node, - visitPatternOptions.processRightHandNodes ? this : null, - visitPatternCallback - ); +function findAllChildren(children, schemaPaths) { + let i = children.length - 1; + + const predicate = + /** + * @param {string} schemaPath + * @returns {boolean} + */ + schemaPath => children[i].schemaPath.indexOf(schemaPath) !== 0; + + while (i > -1 && !schemaPaths.every(predicate)) { + if (children[i].keyword === "anyOf" || children[i].keyword === "oneOf") { + const refs = extractRefs(children[i]); + const childrenStart = findAllChildren(children.slice(0, i), refs.concat(children[i].schemaPath)); + i = childrenStart - 1; + } else { + i -= 1; } + } - visitFunction(node) { - let i, iz; + return i + 1; +} +/** + * Extracts all refs from schema + * @param {SchemaUtilErrorObject} error + * @return {Array} + */ - // FunctionDeclaration name is defined in upper scope - // NOTE: Not referring variableScope. It is intended. - // Since - // in ES5, FunctionDeclaration should be in FunctionBody. - // in ES6, FunctionDeclaration should be block scoped. - if (node.type === Syntax.FunctionDeclaration) { +function extractRefs(error) { + const { + schema + } = error; - // id is defined in upper scope - this.currentScope().__define(node.id, - new Definition( - Variable.FunctionName, - node.id, - node, - null, - null, - null - )); - } + if (!Array.isArray(schema)) { + return []; + } - // FunctionExpression with name creates its special scope; - // FunctionExpressionNameScope. - if (node.type === Syntax.FunctionExpression && node.id) { - this.scopeManager.__nestFunctionExpressionNameScope(node); - } + return schema.map(({ + $ref + }) => $ref).filter(s => s); +} +/** + * Groups children by their first level parent (assuming that error is root) + * @param {Array} children + * @return {Array} + */ - // Consider this function is in the MethodDefinition. - this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition); - const that = this; +function groupChildrenByFirstChild(children) { + const result = []; + let i = children.length - 1; - /** - * Visit pattern callback - * @param {pattern} pattern - pattern - * @param {Object} info - info - * @returns {void} - */ - function visitPatternCallback(pattern, info) { - that.currentScope().__define(pattern, - new ParameterDefinition( - pattern, - node, - i, - info.rest - )); + while (i > 0) { + const child = children[i]; - that.referencingDefaultValue(pattern, info.assignments, null, true); - } + if (child.keyword === "anyOf" || child.keyword === "oneOf") { + const refs = extractRefs(child); + const childrenStart = findAllChildren(children.slice(0, i), refs.concat(child.schemaPath)); - // Process parameter declarations. - for (i = 0, iz = node.params.length; i < iz; ++i) { - this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback); - } + if (childrenStart !== i) { + result.push(Object.assign({}, child, { + children: children.slice(childrenStart, i) + })); + i = childrenStart; + } else { + result.push(child); + } + } else { + result.push(child); + } - // if there's a rest argument, add that - if (node.rest) { - this.visitPattern({ - type: "RestElement", - argument: node.rest - }, pattern => { - this.currentScope().__define(pattern, - new ParameterDefinition( - pattern, - node, - node.params.length, - true - )); - }); - } + i -= 1; + } - // In TypeScript there are a number of function-like constructs which have no body, - // so check it exists before traversing - if (node.body) { + if (i === 0) { + result.push(children[i]); + } - // Skip BlockStatement to prevent creating BlockStatement scope. - if (node.body.type === Syntax.BlockStatement) { - this.visitChildren(node.body); - } else { - this.visit(node.body); - } - } + return result.reverse(); +} +/** + * @param {string} str + * @param {string} prefix + * @returns {string} + */ - this.close(node); - } - visitClass(node) { - if (node.type === Syntax.ClassDeclaration) { - this.currentScope().__define(node.id, - new Definition( - Variable.ClassName, - node.id, - node, - null, - null, - null - )); - } +function indent(str, prefix) { + return str.replace(/\n(?!$)/g, `\n${prefix}`); +} +/** + * @param {Schema} schema + * @returns {schema is (Schema & {not: Schema})} + */ - this.visit(node.superClass); - this.scopeManager.__nestClassScope(node); +function hasNotInSchema(schema) { + return !!schema.not; +} +/** + * @param {Schema} schema + * @return {Schema} + */ - if (node.id) { - this.currentScope().__define(node.id, - new Definition( - Variable.ClassName, - node.id, - node - )); - } - this.visit(node.body); - this.close(node); - } +function findFirstTypedSchema(schema) { + if (hasNotInSchema(schema)) { + return findFirstTypedSchema(schema.not); + } - visitProperty(node) { - let previous; + return schema; +} +/** + * @param {Schema} schema + * @return {boolean} + */ - if (node.computed) { - this.visit(node.key); - } - const isMethodDefinition = node.type === Syntax.MethodDefinition; +function canApplyNot(schema) { + const typedSchema = findFirstTypedSchema(schema); + return likeNumber(typedSchema) || likeInteger(typedSchema) || likeString(typedSchema) || likeNull(typedSchema) || likeBoolean(typedSchema); +} +/** + * @param {any} maybeObj + * @returns {boolean} + */ - if (isMethodDefinition) { - previous = this.pushInnerMethodDefinition(true); - } - this.visit(node.value); - if (isMethodDefinition) { - this.popInnerMethodDefinition(previous); - } - } - visitForIn(node) { - if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") { - this.scopeManager.__nestForScope(node); - } +function isObject(maybeObj) { + return typeof maybeObj === "object" && maybeObj !== null; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ - if (node.left.type === Syntax.VariableDeclaration) { - this.visit(node.left); - this.visitPattern(node.left.declarations[0].id, pattern => { - this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true); - }); - } else { - this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { - let maybeImplicitGlobal = null; - if (!this.currentScope().isStrict) { - maybeImplicitGlobal = { - pattern, - node - }; - } - this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); - this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false); - }); - } - this.visit(node.right); - this.visit(node.body); +function likeNumber(schema) { + return schema.type === "number" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ - this.close(node); - } - visitVariableDeclaration(variableTargetScope, type, node, index) { +function likeInteger(schema) { + return schema.type === "integer" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ - const decl = node.declarations[index]; - const init = decl.init; - this.visitPattern(decl.id, { processRightHandNodes: true }, (pattern, info) => { - variableTargetScope.__define( - pattern, - new Definition( - type, - pattern, - decl, - node, - index, - node.kind - ) - ); +function likeString(schema) { + return schema.type === "string" || typeof schema.minLength !== "undefined" || typeof schema.maxLength !== "undefined" || typeof schema.pattern !== "undefined" || typeof schema.format !== "undefined" || typeof schema.formatMinimum !== "undefined" || typeof schema.formatMaximum !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ - this.referencingDefaultValue(pattern, info.assignments, null, true); - if (init) { - this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true); - } - }); - } - AssignmentExpression(node) { - if (PatternVisitor.isPattern(node.left)) { - if (node.operator === "=") { - this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => { - let maybeImplicitGlobal = null; +function likeBoolean(schema) { + return schema.type === "boolean"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ - if (!this.currentScope().isStrict) { - maybeImplicitGlobal = { - pattern, - node - }; - } - this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false); - this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false); - }); - } else { - this.currentScope().__referencing(node.left, Reference.RW, node.right); - } - } else { - this.visit(node.left); - } - this.visit(node.right); - } - CatchClause(node) { - this.scopeManager.__nestCatchScope(node); +function likeArray(schema) { + return schema.type === "array" || typeof schema.minItems === "number" || typeof schema.maxItems === "number" || typeof schema.uniqueItems !== "undefined" || typeof schema.items !== "undefined" || typeof schema.additionalItems !== "undefined" || typeof schema.contains !== "undefined"; +} +/** + * @param {Schema & {patternRequired?: Array}} schema + * @returns {boolean} + */ - this.visitPattern(node.param, { processRightHandNodes: true }, (pattern, info) => { - this.currentScope().__define(pattern, - new Definition( - Variable.CatchClause, - node.param, - node, - null, - null, - null - )); - this.referencingDefaultValue(pattern, info.assignments, null, true); - }); - this.visit(node.body); - this.close(node); - } +function likeObject(schema) { + return schema.type === "object" || typeof schema.minProperties !== "undefined" || typeof schema.maxProperties !== "undefined" || typeof schema.required !== "undefined" || typeof schema.properties !== "undefined" || typeof schema.patternProperties !== "undefined" || typeof schema.additionalProperties !== "undefined" || typeof schema.dependencies !== "undefined" || typeof schema.propertyNames !== "undefined" || typeof schema.patternRequired !== "undefined"; +} +/** + * @param {Schema} schema + * @returns {boolean} + */ - Program(node) { - this.scopeManager.__nestGlobalScope(node); - if (this.scopeManager.__isNodejsScope()) { +function likeNull(schema) { + return schema.type === "null"; +} +/** + * @param {string} type + * @returns {string} + */ - // Force strictness of GlobalScope to false when using node.js scope. - this.currentScope().isStrict = false; - this.scopeManager.__nestFunctionScope(node, false); - } - if (this.scopeManager.__isES6() && this.scopeManager.isModule()) { - this.scopeManager.__nestModuleScope(node); - } +function getArticle(type) { + if (/^[aeiou]/i.test(type)) { + return "an"; + } - if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) { - this.currentScope().isStrict = true; - } + return "a"; +} +/** + * @param {Schema=} schema + * @returns {string} + */ - this.visitChildren(node); - this.close(node); - } - Identifier(node) { - this.currentScope().__referencing(node); - } +function getSchemaNonTypes(schema) { + if (!schema) { + return ""; + } - UpdateExpression(node) { - if (PatternVisitor.isPattern(node.argument)) { - this.currentScope().__referencing(node.argument, Reference.RW, null); - } else { - this.visitChildren(node); - } + if (!schema.type) { + if (likeNumber(schema) || likeInteger(schema)) { + return " | should be any non-number"; } - MemberExpression(node) { - this.visit(node.object); - if (node.computed) { - this.visit(node.property); - } + if (likeString(schema)) { + return " | should be any non-string"; } - Property(node) { - this.visitProperty(node); + if (likeArray(schema)) { + return " | should be any non-array"; } - MethodDefinition(node) { - this.visitProperty(node); + if (likeObject(schema)) { + return " | should be any non-object"; } + } - BreakStatement() {} // eslint-disable-line class-methods-use-this - - ContinueStatement() {} // eslint-disable-line class-methods-use-this - - LabeledStatement(node) { - this.visit(node.body); - } + return ""; +} +/** + * @param {Array} hints + * @returns {string} + */ - ForStatement(node) { - // Create ForStatement declaration. - // NOTE: In ES6, ForStatement dynamically generates - // per iteration environment. However, escope is - // a static analyzer, we only generate one scope for ForStatement. - if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") { - this.scopeManager.__nestForScope(node); - } +function formatHints(hints) { + return hints.length > 0 ? `(${hints.join(", ")})` : ""; +} +/** + * @param {Schema} schema + * @param {boolean} logic + * @returns {string[]} + */ - this.visitChildren(node); - this.close(node); - } +function getHints(schema, logic) { + if (likeNumber(schema) || likeInteger(schema)) { + return numberHints(schema, logic); + } else if (likeString(schema)) { + return stringHints(schema, logic); + } - ClassExpression(node) { - this.visitClass(node); - } + return []; +} - ClassDeclaration(node) { - this.visitClass(node); - } +class ValidationError extends Error { + /** + * @param {Array} errors + * @param {Schema} schema + * @param {ValidationErrorConfiguration} configuration + */ + constructor(errors, schema, configuration = {}) { + super(); + /** @type {string} */ - CallExpression(node) { + this.name = "ValidationError"; + /** @type {Array} */ - // Check this is direct call to eval - if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") { + this.errors = errors; + /** @type {Schema} */ - // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and - // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. - this.currentScope().variableScope.__detectEval(); + this.schema = schema; + let headerNameFromSchema; + let baseDataPathFromSchema; + + if (schema.title && (!configuration.name || !configuration.baseDataPath)) { + const splittedTitleFromSchema = schema.title.match(/^(.+) (.+)$/); + + if (splittedTitleFromSchema) { + if (!configuration.name) { + [, headerNameFromSchema] = splittedTitleFromSchema; } - this.visitChildren(node); - } - BlockStatement(node) { - if (this.scopeManager.__isES6()) { - this.scopeManager.__nestBlockScope(node); + if (!configuration.baseDataPath) { + [,, baseDataPathFromSchema] = splittedTitleFromSchema; } + } + } + /** @type {string} */ - this.visitChildren(node); - this.close(node); - } + this.headerName = configuration.name || headerNameFromSchema || "Object"; + /** @type {string} */ - ThisExpression() { - this.currentScope().variableScope.__detectThis(); - } + this.baseDataPath = configuration.baseDataPath || baseDataPathFromSchema || "configuration"; + /** @type {PostFormatter | null} */ - WithStatement(node) { - this.visit(node.object); + this.postFormatter = configuration.postFormatter || null; + const header = `Invalid ${this.baseDataPath} object. ${this.headerName} has been initialized using ${getArticle(this.baseDataPath)} ${this.baseDataPath} object that does not match the API schema.\n`; + /** @type {string} */ - // Then nest scope for WithStatement. - this.scopeManager.__nestWithScope(node); + this.message = `${header}${this.formatValidationErrors(errors)}`; + Error.captureStackTrace(this, this.constructor); + } + /** + * @param {string} path + * @returns {Schema} + */ - this.visit(node.body); - this.close(node); - } + getSchemaPart(path) { + const newPath = path.split("/"); + let schemaPart = this.schema; - VariableDeclaration(node) { - const variableTargetScope = (node.kind === "var") ? this.currentScope().variableScope : this.currentScope(); + for (let i = 1; i < newPath.length; i++) { + const inner = schemaPart[ + /** @type {keyof Schema} */ + newPath[i]]; - for (let i = 0, iz = node.declarations.length; i < iz; ++i) { - const decl = node.declarations[i]; + if (!inner) { + break; + } - this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i); - if (decl.init) { - this.visit(decl.init); - } - } + schemaPart = inner; } - // sec 13.11.8 - SwitchStatement(node) { - this.visit(node.discriminant); + return schemaPart; + } + /** + * @param {Schema} schema + * @param {boolean} logic + * @param {Array} prevSchemas + * @returns {string} + */ - if (this.scopeManager.__isES6()) { - this.scopeManager.__nestSwitchScope(node); - } - for (let i = 0, iz = node.cases.length; i < iz; ++i) { - this.visit(node.cases[i]); - } + formatSchema(schema, logic = true, prevSchemas = []) { + let newLogic = logic; - this.close(node); - } + const formatInnerSchema = + /** + * + * @param {Object} innerSchema + * @param {boolean=} addSelf + * @returns {string} + */ + (innerSchema, addSelf) => { + if (!addSelf) { + return this.formatSchema(innerSchema, newLogic, prevSchemas); + } - FunctionDeclaration(node) { - this.visitFunction(node); - } + if (prevSchemas.includes(innerSchema)) { + return "(recursive)"; + } - FunctionExpression(node) { - this.visitFunction(node); - } + return this.formatSchema(innerSchema, newLogic, prevSchemas.concat(schema)); + }; - ForOfStatement(node) { - this.visitForIn(node); - } + if (hasNotInSchema(schema) && !likeObject(schema)) { + if (canApplyNot(schema.not)) { + newLogic = !logic; + return formatInnerSchema(schema.not); + } - ForInStatement(node) { - this.visitForIn(node); + const needApplyLogicHere = !schema.not.not; + const prefix = logic ? "" : "non "; + newLogic = !logic; + return needApplyLogicHere ? prefix + formatInnerSchema(schema.not) : formatInnerSchema(schema.not); } - ArrowFunctionExpression(node) { - this.visitFunction(node); + if ( + /** @type {Schema & {instanceof: string | Array}} */ + schema.instanceof) { + const { + instanceof: value + } = + /** @type {Schema & {instanceof: string | Array}} */ + schema; + const values = !Array.isArray(value) ? [value] : value; + return values.map( + /** + * @param {string} item + * @returns {string} + */ + item => item === "Function" ? "function" : item).join(" | "); } - ImportDeclaration(node) { - assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context."); - - const importer = new Importer(node, this); - - importer.visit(node); + if (schema.enum) { + return ( + /** @type {Array} */ + schema.enum.map(item => JSON.stringify(item)).join(" | ") + ); } - visitExportDeclaration(node) { - if (node.source) { - return; - } - if (node.declaration) { - this.visit(node.declaration); - return; - } - - this.visitChildren(node); + if (typeof schema.const !== "undefined") { + return JSON.stringify(schema.const); } - // TODO: ExportDeclaration doesn't exist. for bc? - ExportDeclaration(node) { - this.visitExportDeclaration(node); + if (schema.oneOf) { + return ( + /** @type {Array} */ + schema.oneOf.map(item => formatInnerSchema(item, true)).join(" | ") + ); } - ExportAllDeclaration(node) { - this.visitExportDeclaration(node); + if (schema.anyOf) { + return ( + /** @type {Array} */ + schema.anyOf.map(item => formatInnerSchema(item, true)).join(" | ") + ); } - ExportDefaultDeclaration(node) { - this.visitExportDeclaration(node); + if (schema.allOf) { + return ( + /** @type {Array} */ + schema.allOf.map(item => formatInnerSchema(item, true)).join(" & ") + ); } - ExportNamedDeclaration(node) { - this.visitExportDeclaration(node); + if ( + /** @type {JSONSchema7} */ + schema.if) { + const { + if: ifValue, + then: thenValue, + else: elseValue + } = + /** @type {JSONSchema7} */ + schema; + return `${ifValue ? `if ${formatInnerSchema(ifValue)}` : ""}${thenValue ? ` then ${formatInnerSchema(thenValue)}` : ""}${elseValue ? ` else ${formatInnerSchema(elseValue)}` : ""}`; } - ExportSpecifier(node) { - - // TODO: `node.id` doesn't exist. for bc? - const local = (node.id || node.local); + if (schema.$ref) { + return formatInnerSchema(this.getSchemaPart(schema.$ref), true); + } - this.visit(local); + if (likeNumber(schema) || likeInteger(schema)) { + const [type, ...hints] = getHints(schema, logic); + const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; + return logic ? str : hints.length > 0 ? `non-${type} | ${str}` : `non-${type}`; } - MetaProperty() { // eslint-disable-line class-methods-use-this + if (likeString(schema)) { + const [type, ...hints] = getHints(schema, logic); + const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; + return logic ? str : str === "string" ? "non-string" : `non-string | ${str}`; + } - // do nothing. + if (likeBoolean(schema)) { + return `${logic ? "" : "non-"}boolean`; } -} -module.exports = Referencer; + if (likeArray(schema)) { + // not logic already applied in formatValidationError + newLogic = true; + const hints = []; -/* vim: set sw=4 ts=4 et tw=80 : */ + if (typeof schema.minItems === "number") { + hints.push(`should not have fewer than ${schema.minItems} item${schema.minItems > 1 ? "s" : ""}`); + } + if (typeof schema.maxItems === "number") { + hints.push(`should not have more than ${schema.maxItems} item${schema.maxItems > 1 ? "s" : ""}`); + } -/***/ }), + if (schema.uniqueItems) { + hints.push("should not have duplicate items"); + } -/***/ 96988: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const hasAdditionalItems = typeof schema.additionalItems === "undefined" || Boolean(schema.additionalItems); + let items = ""; -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki + if (schema.items) { + if (Array.isArray(schema.items) && schema.items.length > 0) { + items = `${ + /** @type {Array} */ + schema.items.map(item => formatInnerSchema(item)).join(", ")}`; - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + if (hasAdditionalItems) { + if (schema.additionalItems && isObject(schema.additionalItems) && Object.keys(schema.additionalItems).length > 0) { + hints.push(`additional items should be ${formatInnerSchema(schema.additionalItems)}`); + } + } + } else if (schema.items && Object.keys(schema.items).length > 0) { + // "additionalItems" is ignored + items = `${formatInnerSchema(schema.items)}`; + } else { + // Fallback for empty `items` value + items = "any"; + } + } else { + // "additionalItems" is ignored + items = "any"; + } - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + if (schema.contains && Object.keys(schema.contains).length > 0) { + hints.push(`should contains at least one ${this.formatSchema(schema.contains)} item`); + } - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + return `[${items}${hasAdditionalItems ? ", ..." : ""}]${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; + } + if (likeObject(schema)) { + // not logic already applied in formatValidationError + newLogic = true; + const hints = []; -/* eslint-disable no-underscore-dangle */ + if (typeof schema.minProperties === "number") { + hints.push(`should not have fewer than ${schema.minProperties} ${schema.minProperties > 1 ? "properties" : "property"}`); + } -const Scope = __webpack_require__(16313); -const assert = __webpack_require__(39491); + if (typeof schema.maxProperties === "number") { + hints.push(`should not have more than ${schema.maxProperties} ${schema.minProperties && schema.minProperties > 1 ? "properties" : "property"}`); + } -const GlobalScope = Scope.GlobalScope; -const CatchScope = Scope.CatchScope; -const WithScope = Scope.WithScope; -const ModuleScope = Scope.ModuleScope; -const ClassScope = Scope.ClassScope; -const SwitchScope = Scope.SwitchScope; -const FunctionScope = Scope.FunctionScope; -const ForScope = Scope.ForScope; -const FunctionExpressionNameScope = Scope.FunctionExpressionNameScope; -const BlockScope = Scope.BlockScope; + if (schema.patternProperties && Object.keys(schema.patternProperties).length > 0) { + const patternProperties = Object.keys(schema.patternProperties); + hints.push(`additional property names should match pattern${patternProperties.length > 1 ? "s" : ""} ${patternProperties.map(pattern => JSON.stringify(pattern)).join(" | ")}`); + } -/** - * @class ScopeManager - */ -class ScopeManager { - constructor(options) { - this.scopes = []; - this.globalScope = null; - this.__nodeToScope = new WeakMap(); - this.__currentScope = null; - this.__options = options; - this.__declaredVariables = new WeakMap(); - } + const properties = schema.properties ? Object.keys(schema.properties) : []; + const required = schema.required ? schema.required : []; + const allProperties = [...new Set( + /** @type {Array} */ + [].concat(required).concat(properties))]; + const objectStructure = allProperties.map(property => { + const isRequired = required.includes(property); // Some properties need quotes, maybe we should add check + // Maybe we should output type of property (`foo: string`), but it is looks very unreadable - __useDirective() { - return this.__options.directive; - } + return `${property}${isRequired ? "" : "?"}`; + }).concat(typeof schema.additionalProperties === "undefined" || Boolean(schema.additionalProperties) ? schema.additionalProperties && isObject(schema.additionalProperties) ? [`: ${formatInnerSchema(schema.additionalProperties)}`] : ["…"] : []).join(", "); + const { + dependencies, + propertyNames, + patternRequired + } = + /** @type {Schema & {patternRequired?: Array;}} */ + schema; - __isOptimistic() { - return this.__options.optimistic; - } + if (dependencies) { + Object.keys(dependencies).forEach(dependencyName => { + const dependency = dependencies[dependencyName]; - __ignoreEval() { - return this.__options.ignoreEval; - } + if (Array.isArray(dependency)) { + hints.push(`should have ${dependency.length > 1 ? "properties" : "property"} ${dependency.map(dep => `'${dep}'`).join(", ")} when property '${dependencyName}' is present`); + } else { + hints.push(`should be valid according to the schema ${formatInnerSchema(dependency)} when property '${dependencyName}' is present`); + } + }); + } - __isNodejsScope() { - return this.__options.nodejsScope; - } + if (propertyNames && Object.keys(propertyNames).length > 0) { + hints.push(`each property name should match format ${JSON.stringify(schema.propertyNames.format)}`); + } - isModule() { - return this.__options.sourceType === "module"; - } + if (patternRequired && patternRequired.length > 0) { + hints.push(`should have property matching pattern ${patternRequired.map( + /** + * @param {string} item + * @returns {string} + */ + item => JSON.stringify(item))}`); + } - isImpliedStrict() { - return this.__options.impliedStrict; + return `object {${objectStructure ? ` ${objectStructure} ` : ""}}${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; } - isStrictModeSupported() { - return this.__options.ecmaVersion >= 5; + if (likeNull(schema)) { + return `${logic ? "" : "non-"}null`; } - // Returns appropriate scope for this node. - __get(node) { - return this.__nodeToScope.get(node); - } + if (Array.isArray(schema.type)) { + // not logic already applied in formatValidationError + return `${schema.type.join(" | ")}`; + } // Fallback for unknown keywords + // not logic already applied in formatValidationError - /** - * Get variables that are declared by the node. - * - * "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`. - * If the node declares nothing, this method returns an empty array. - * CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details. - * - * @param {Espree.Node} node - a node to get. - * @returns {Variable[]} variables that declared by the node. - */ - getDeclaredVariables(node) { - return this.__declaredVariables.get(node) || []; - } + /* istanbul ignore next */ - /** - * acquire scope from node. - * @method ScopeManager#acquire - * @param {Espree.Node} node - node for the acquired scope. - * @param {boolean=} inner - look up the most inner scope, default value is false. - * @returns {Scope?} Scope from node - */ - acquire(node, inner) { - /** - * predicate - * @param {Scope} testScope - scope to test - * @returns {boolean} predicate - */ - function predicate(testScope) { - if (testScope.type === "function" && testScope.functionExpressionScope) { - return false; - } - return true; - } + return JSON.stringify(schema, null, 2); + } + /** + * @param {Schema=} schemaPart + * @param {(boolean | Array)=} additionalPath + * @param {boolean=} needDot + * @param {boolean=} logic + * @returns {string} + */ - const scopes = this.__get(node); - if (!scopes || scopes.length === 0) { - return null; - } + getSchemaPartText(schemaPart, additionalPath, needDot = false, logic = true) { + if (!schemaPart) { + return ""; + } - // Heuristic selection from all scopes. - // If you would like to get all scopes, please use ScopeManager#acquireAll. - if (scopes.length === 1) { - return scopes[0]; - } + if (Array.isArray(additionalPath)) { + for (let i = 0; i < additionalPath.length; i++) { + /** @type {Schema | undefined} */ + const inner = schemaPart[ + /** @type {keyof Schema} */ + additionalPath[i]]; if (inner) { - for (let i = scopes.length - 1; i >= 0; --i) { - const scope = scopes[i]; - - if (predicate(scope)) { - return scope; - } - } + // eslint-disable-next-line no-param-reassign + schemaPart = inner; } else { - for (let i = 0, iz = scopes.length; i < iz; ++i) { - const scope = scopes[i]; - - if (predicate(scope)) { - return scope; - } - } + break; } - - return null; + } } - /** - * acquire all scopes from node. - * @method ScopeManager#acquireAll - * @param {Espree.Node} node - node for the acquired scope. - * @returns {Scopes?} Scope array - */ - acquireAll(node) { - return this.__get(node); + while (schemaPart.$ref) { + // eslint-disable-next-line no-param-reassign + schemaPart = this.getSchemaPart(schemaPart.$ref); } - /** - * release the node. - * @method ScopeManager#release - * @param {Espree.Node} node - releasing node. - * @param {boolean=} inner - look up the most inner scope, default value is false. - * @returns {Scope?} upper scope for the node. - */ - release(node, inner) { - const scopes = this.__get(node); + let schemaText = `${this.formatSchema(schemaPart, logic)}${needDot ? "." : ""}`; - if (scopes && scopes.length) { - const scope = scopes[0].upper; + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } - if (!scope) { - return null; - } - return this.acquire(scope.block, inner); - } - return null; + if (schemaPart.link) { + schemaText += `\n-> Read more at ${schemaPart.link}`; } - attach() { } // eslint-disable-line class-methods-use-this + return schemaText; + } + /** + * @param {Schema=} schemaPart + * @returns {string} + */ - detach() { } // eslint-disable-line class-methods-use-this - __nestScope(scope) { - if (scope instanceof GlobalScope) { - assert(this.__currentScope === null); - this.globalScope = scope; - } - this.__currentScope = scope; - return scope; + getSchemaPartDescription(schemaPart) { + if (!schemaPart) { + return ""; } - __nestGlobalScope(node) { - return this.__nestScope(new GlobalScope(this, node)); + while (schemaPart.$ref) { + // eslint-disable-next-line no-param-reassign + schemaPart = this.getSchemaPart(schemaPart.$ref); } - __nestBlockScope(node) { - return this.__nestScope(new BlockScope(this, this.__currentScope, node)); - } + let schemaText = ""; - __nestFunctionScope(node, isMethodDefinition) { - return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition)); + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; } - __nestForScope(node) { - return this.__nestScope(new ForScope(this, this.__currentScope, node)); + if (schemaPart.link) { + schemaText += `\n-> Read more at ${schemaPart.link}`; } - __nestCatchScope(node) { - return this.__nestScope(new CatchScope(this, this.__currentScope, node)); - } + return schemaText; + } + /** + * @param {SchemaUtilErrorObject} error + * @returns {string} + */ - __nestWithScope(node) { - return this.__nestScope(new WithScope(this, this.__currentScope, node)); - } - __nestClassScope(node) { - return this.__nestScope(new ClassScope(this, this.__currentScope, node)); - } + formatValidationError(error) { + const { + keyword, + dataPath: errorDataPath + } = error; + const dataPath = `${this.baseDataPath}${errorDataPath}`; - __nestSwitchScope(node) { - return this.__nestScope(new SwitchScope(this, this.__currentScope, node)); - } + switch (keyword) { + case "type": + { + const { + parentSchema, + params + } = error; // eslint-disable-next-line default-case - __nestModuleScope(node) { - return this.__nestScope(new ModuleScope(this, this.__currentScope, node)); - } + switch ( + /** @type {import("ajv").TypeParams} */ + params.type) { + case "number": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; - __nestFunctionExpressionNameScope(node) { - return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node)); - } + case "integer": + return `${dataPath} should be an ${this.getSchemaPartText(parentSchema, false, true)}`; - __isES6() { - return this.__options.ecmaVersion >= 6; - } -} + case "string": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; -module.exports = ScopeManager; + case "boolean": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; -/* vim: set sw=4 ts=4 et tw=80 : */ + case "array": + return `${dataPath} should be an array:\n${this.getSchemaPartText(parentSchema)}`; + case "object": + return `${dataPath} should be an object:\n${this.getSchemaPartText(parentSchema)}`; -/***/ }), + case "null": + return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; -/***/ 16313: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + default: + return `${dataPath} should be:\n${this.getSchemaPartText(parentSchema)}`; + } + } -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki + case "instanceof": + { + const { + parentSchema + } = error; + return `${dataPath} should be an instance of ${this.getSchemaPartText(parentSchema, false, true)}`; + } - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + case "pattern": + { + const { + params, + parentSchema + } = error; + const { + pattern + } = + /** @type {import("ajv").PatternParams} */ + params; + return `${dataPath} should match pattern ${JSON.stringify(pattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + case "format": + { + const { + params, + parentSchema + } = error; + const { + format + } = + /** @type {import("ajv").FormatParams} */ + params; + return `${dataPath} should match format ${JSON.stringify(format)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + case "formatMinimum": + case "formatMaximum": + { + const { + params, + parentSchema + } = error; + const { + comparison, + limit + } = + /** @type {import("ajv").ComparisonParams} */ + params; + return `${dataPath} should be ${comparison} ${JSON.stringify(limit)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } + case "minimum": + case "maximum": + case "exclusiveMinimum": + case "exclusiveMaximum": + { + const { + parentSchema, + params + } = error; + const { + comparison, + limit + } = + /** @type {import("ajv").ComparisonParams} */ + params; + const [, ...hints] = getHints( + /** @type {Schema} */ + parentSchema, true); -/* eslint-disable no-underscore-dangle */ -/* eslint-disable no-undefined */ + if (hints.length === 0) { + hints.push(`should be ${comparison} ${limit}`); + } -const Syntax = (__webpack_require__(18350).Syntax); + return `${dataPath} ${hints.join(" ")}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } -const Reference = __webpack_require__(64945); -const Variable = __webpack_require__(82971); -const Definition = (__webpack_require__(70665).Definition); -const assert = __webpack_require__(39491); + case "multipleOf": + { + const { + params, + parentSchema + } = error; + const { + multipleOf + } = + /** @type {import("ajv").MultipleOfParams} */ + params; + return `${dataPath} should be multiple of ${multipleOf}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } -/** - * Test if scope is struct - * @param {Scope} scope - scope - * @param {Block} block - block - * @param {boolean} isMethodDefinition - is method definition - * @param {boolean} useDirective - use directive - * @returns {boolean} is strict scope - */ -function isStrictScope(scope, block, isMethodDefinition, useDirective) { - let body; + case "patternRequired": + { + const { + params, + parentSchema + } = error; + const { + missingPattern + } = + /** @type {import("ajv").PatternRequiredParams} */ + params; + return `${dataPath} should have property matching pattern ${JSON.stringify(missingPattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - // When upper scope is exists and strict, inner scope is also strict. - if (scope.upper && scope.upper.isStrict) { - return true; - } + case "minLength": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; - if (isMethodDefinition) { - return true; - } + if (limit === 1) { + return `${dataPath} should be a non-empty string${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - if (scope.type === "class" || scope.type === "module") { - return true; - } + const length = limit - 1; + return `${dataPath} should be longer than ${length} character${length > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - if (scope.type === "block" || scope.type === "switch") { - return false; - } + case "minItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; - if (scope.type === "function") { - if (block.type === Syntax.ArrowFunctionExpression && block.body.type !== Syntax.BlockStatement) { - return false; - } + if (limit === 1) { + return `${dataPath} should be a non-empty array${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - if (block.type === Syntax.Program) { - body = block; - } else { - body = block.body; + return `${dataPath} should not have fewer than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; } - if (!body) { - return false; - } - } else if (scope.type === "global") { - body = block; - } else { - return false; - } + case "minProperties": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; - // Search 'use strict' directive. - if (useDirective) { - for (let i = 0, iz = body.body.length; i < iz; ++i) { - const stmt = body.body[i]; + if (limit === 1) { + return `${dataPath} should be a non-empty object${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - if (stmt.type !== Syntax.DirectiveStatement) { - break; - } - if (stmt.raw === "\"use strict\"" || stmt.raw === "'use strict'") { - return true; - } + return `${dataPath} should not have fewer than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; } - } else { - for (let i = 0, iz = body.body.length; i < iz; ++i) { - const stmt = body.body[i]; - - if (stmt.type !== Syntax.ExpressionStatement) { - break; - } - const expr = stmt.expression; - if (expr.type !== Syntax.Literal || typeof expr.value !== "string") { - break; - } - if (expr.raw !== null && expr.raw !== undefined) { - if (expr.raw === "\"use strict\"" || expr.raw === "'use strict'") { - return true; - } - } else { - if (expr.value === "use strict") { - return true; - } - } + case "maxLength": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + const max = limit + 1; + return `${dataPath} should be shorter than ${max} character${max > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; } - } - return false; -} -/** - * Register scope - * @param {ScopeManager} scopeManager - scope manager - * @param {Scope} scope - scope - * @returns {void} - */ -function registerScope(scopeManager, scope) { - scopeManager.scopes.push(scope); + case "maxItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - const scopes = scopeManager.__nodeToScope.get(scope.block); + case "maxProperties": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + return `${dataPath} should not have more than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } - if (scopes) { - scopes.push(scope); - } else { - scopeManager.__nodeToScope.set(scope.block, [scope]); - } -} + case "uniqueItems": + { + const { + params, + parentSchema + } = error; + const { + i + } = + /** @type {import("ajv").UniqueItemsParams} */ + params; + return `${dataPath} should not contain the item '${error.data[i]}' twice${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; + } -/** - * Should be statically - * @param {Object} def - def - * @returns {boolean} should be statically - */ -function shouldBeStatically(def) { - return ( - (def.type === Variable.ClassName) || - (def.type === Variable.Variable && def.parent.kind !== "var") - ); -} + case "additionalItems": + { + const { + params, + parentSchema + } = error; + const { + limit + } = + /** @type {import("ajv").LimitParams} */ + params; + return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}. These items are valid:\n${this.getSchemaPartText(parentSchema)}`; + } -/** - * @class Scope - */ -class Scope { - constructor(scopeManager, type, upperScope, block, isMethodDefinition) { + case "contains": + { + const { + parentSchema + } = error; + return `${dataPath} should contains at least one ${this.getSchemaPartText(parentSchema, ["contains"])} item${getSchemaNonTypes(parentSchema)}.`; + } - /** - * One of 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'. - * @member {String} Scope#type - */ - this.type = type; - - /** - * The scoped {@link Variable}s of this scope, as { Variable.name - * : Variable }. - * @member {Map} Scope#set - */ - this.set = new Map(); - - /** - * The tainted variables of this scope, as { Variable.name : - * boolean }. - * @member {Map} Scope#taints */ - this.taints = new Map(); - - /** - * Generally, through the lexical scoping of JS you can always know - * which variable an identifier in the source code refers to. There are - * a few exceptions to this rule. With 'global' and 'with' scopes you - * can only decide at runtime which variable a reference refers to. - * Moreover, if 'eval()' is used in a scope, it might introduce new - * bindings in this or its parent scopes. - * All those scopes are considered 'dynamic'. - * @member {boolean} Scope#dynamic - */ - this.dynamic = this.type === "global" || this.type === "with"; - - /** - * A reference to the scope-defining syntax node. - * @member {espree.Node} Scope#block - */ - this.block = block; - - /** - * The {@link Reference|references} that are not resolved with this scope. - * @member {Reference[]} Scope#through - */ - this.through = []; - - /** - * The scoped {@link Variable}s of this scope. In the case of a - * 'function' scope this includes the automatic argument arguments as - * its first element, as well as all further formal arguments. - * @member {Variable[]} Scope#variables - */ - this.variables = []; - - /** - * Any variable {@link Reference|reference} found in this scope. This - * includes occurrences of local variables as well as variables from - * parent scopes (including the global scope). For local variables - * this also includes defining occurrences (like in a 'var' statement). - * In a 'function' scope this does not include the occurrences of the - * formal parameter in the parameter list. - * @member {Reference[]} Scope#references - */ - this.references = []; - - /** - * For 'global' and 'function' scopes, this is a self-reference. For - * other scope types this is the variableScope value of the - * parent scope. - * @member {Scope} Scope#variableScope - */ - this.variableScope = - (this.type === "global" || this.type === "function" || this.type === "module") ? this : upperScope.variableScope; - - /** - * Whether this scope is created by a FunctionExpression. - * @member {boolean} Scope#functionExpressionScope - */ - this.functionExpressionScope = false; - - /** - * Whether this is a scope that contains an 'eval()' invocation. - * @member {boolean} Scope#directCallToEvalScope - */ - this.directCallToEvalScope = false; - - /** - * @member {boolean} Scope#thisFound - */ - this.thisFound = false; - - this.__left = []; - - /** - * Reference to the parent {@link Scope|scope}. - * @member {Scope} Scope#upper - */ - this.upper = upperScope; - - /** - * Whether 'use strict' is in effect in this scope. - * @member {boolean} Scope#isStrict - */ - this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective()); - - /** - * List of nested {@link Scope}s. - * @member {Scope[]} Scope#childScopes - */ - this.childScopes = []; - if (this.upper) { - this.upper.childScopes.push(this); + case "required": + { + const { + parentSchema, + params + } = error; + const missingProperty = + /** @type {import("ajv").DependenciesParams} */ + params.missingProperty.replace(/^\./, ""); + const hasProperty = parentSchema && Boolean( + /** @type {Schema} */ + parentSchema.properties && + /** @type {Schema} */ + parentSchema.properties[missingProperty]); + return `${dataPath} misses the property '${missingProperty}'${getSchemaNonTypes(parentSchema)}.${hasProperty ? ` Should be:\n${this.getSchemaPartText(parentSchema, ["properties", missingProperty])}` : this.getSchemaPartDescription(parentSchema)}`; } - this.__declaredVariables = scopeManager.__declaredVariables; - - registerScope(scopeManager, this); - } - - __shouldStaticallyClose(scopeManager) { - return (!this.dynamic || scopeManager.__isOptimistic()); - } - - __shouldStaticallyCloseForGlobal(ref) { - - // On global scope, let/const/class declarations should be resolved statically. - const name = ref.identifier.name; - - if (!this.set.has(name)) { - return false; + case "additionalProperties": + { + const { + params, + parentSchema + } = error; + const { + additionalProperty + } = + /** @type {import("ajv").AdditionalPropertiesParams} */ + params; + return `${dataPath} has an unknown property '${additionalProperty}'${getSchemaNonTypes(parentSchema)}. These properties are valid:\n${this.getSchemaPartText(parentSchema)}`; } - const variable = this.set.get(name); - const defs = variable.defs; - - return defs.length > 0 && defs.every(shouldBeStatically); - } - - __staticCloseRef(ref) { - if (!this.__resolve(ref)) { - this.__delegateToUpperScope(ref); + case "dependencies": + { + const { + params, + parentSchema + } = error; + const { + property, + deps + } = + /** @type {import("ajv").DependenciesParams} */ + params; + const dependencies = deps.split(",").map( + /** + * @param {string} dep + * @returns {string} + */ + dep => `'${dep.trim()}'`).join(", "); + return `${dataPath} should have properties ${dependencies} when property '${property}' is present${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; } - } - - __dynamicCloseRef(ref) { - // notify all names are through to global - let current = this; + case "propertyNames": + { + const { + params, + parentSchema, + schema + } = error; + const { + propertyName + } = + /** @type {import("ajv").PropertyNamesParams} */ + params; + return `${dataPath} property name '${propertyName}' is invalid${getSchemaNonTypes(parentSchema)}. Property names should be match format ${JSON.stringify(schema.format)}.${this.getSchemaPartDescription(parentSchema)}`; + } - do { - current.through.push(ref); - current = current.upper; - } while (current); - } + case "enum": + { + const { + parentSchema + } = error; - __globalCloseRef(ref) { + if (parentSchema && + /** @type {Schema} */ + parentSchema.enum && + /** @type {Schema} */ + parentSchema.enum.length === 1) { + return `${dataPath} should be ${this.getSchemaPartText(parentSchema, false, true)}`; + } - // let/const/class declarations should be resolved statically. - // others should be resolved dynamically. - if (this.__shouldStaticallyCloseForGlobal(ref)) { - this.__staticCloseRef(ref); - } else { - this.__dynamicCloseRef(ref); + return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; } - } - - __close(scopeManager) { - let closeRef; - if (this.__shouldStaticallyClose(scopeManager)) { - closeRef = this.__staticCloseRef; - } else if (this.type !== "global") { - closeRef = this.__dynamicCloseRef; - } else { - closeRef = this.__globalCloseRef; + case "const": + { + const { + parentSchema + } = error; + return `${dataPath} should be equal to constant ${this.getSchemaPartText(parentSchema, false, true)}`; } - // Try Resolving all references in this scope. - for (let i = 0, iz = this.__left.length; i < iz; ++i) { - const ref = this.__left[i]; + case "not": + { + const postfix = likeObject( + /** @type {Schema} */ + error.parentSchema) ? `\n${this.getSchemaPartText(error.parentSchema)}` : ""; + const schemaOutput = this.getSchemaPartText(error.schema, false, false, false); - closeRef.call(this, ref); - } - this.__left = null; + if (canApplyNot(error.schema)) { + return `${dataPath} should be any ${schemaOutput}${postfix}.`; + } - return this.upper; - } + const { + schema, + parentSchema + } = error; + return `${dataPath} should not be ${this.getSchemaPartText(schema, false, true)}${parentSchema && likeObject(parentSchema) ? `\n${this.getSchemaPartText(parentSchema)}` : ""}`; + } - // To override by function scopes. - // References in default parameters isn't resolved to variables which are in their function body. - __isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars - return true; - } + case "oneOf": + case "anyOf": + { + const { + parentSchema, + children + } = error; - __resolve(ref) { - const name = ref.identifier.name; + if (children && children.length > 0) { + if (error.schema.length === 1) { + const lastChild = children[children.length - 1]; + const remainingChildren = children.slice(0, children.length - 1); + return this.formatValidationError(Object.assign({}, lastChild, { + children: remainingChildren, + parentSchema: Object.assign({}, parentSchema, lastChild.parentSchema) + })); + } - if (!this.set.has(name)) { - return false; - } - const variable = this.set.get(name); + let filteredChildren = filterChildren(children); - if (!this.__isValidResolution(ref, variable)) { - return false; - } - variable.references.push(ref); - variable.stack = variable.stack && ref.from.variableScope === this.variableScope; - if (ref.tainted) { - variable.tainted = true; - this.taints.set(variable.name, true); - } - ref.resolved = variable; + if (filteredChildren.length === 1) { + return this.formatValidationError(filteredChildren[0]); + } - return true; - } + filteredChildren = groupChildrenByFirstChild(filteredChildren); + return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}\nDetails:\n${filteredChildren.map( + /** + * @param {SchemaUtilErrorObject} nestedError + * @returns {string} + */ + nestedError => ` * ${indent(this.formatValidationError(nestedError), " ")}`).join("\n")}`; + } - __delegateToUpperScope(ref) { - if (this.upper) { - this.upper.__left.push(ref); + return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; } - this.through.push(ref); - } - __addDeclaredVariablesOfNode(variable, node) { - if (node === null || node === undefined) { - return; + case "if": + { + const { + params, + parentSchema + } = error; + const { + failingKeyword + } = + /** @type {import("ajv").IfParams} */ + params; + return `${dataPath} should match "${failingKeyword}" schema:\n${this.getSchemaPartText(parentSchema, [failingKeyword])}`; } - let variables = this.__declaredVariables.get(node); - - if (variables === null || variables === undefined) { - variables = []; - this.__declaredVariables.set(node, variables); - } - if (variables.indexOf(variable) === -1) { - variables.push(variable); + case "absolutePath": + { + const { + message, + parentSchema + } = error; + return `${dataPath}: ${message}${this.getSchemaPartDescription(parentSchema)}`; } - } - __defineGeneric(name, set, variables, node, def) { - let variable; + /* istanbul ignore next */ - variable = set.get(name); - if (!variable) { - variable = new Variable(name, this); - set.set(name, variable); - variables.push(variable); - } + default: + { + const { + message, + parentSchema + } = error; + const ErrorInJSON = JSON.stringify(error, null, 2); // For `custom`, `false schema`, `$ref` keywords + // Fallback for unknown keywords - if (def) { - variable.defs.push(def); - this.__addDeclaredVariablesOfNode(variable, def.node); - this.__addDeclaredVariablesOfNode(variable, def.parent); - } - if (node) { - variable.identifiers.push(node); + return `${dataPath} ${message} (${ErrorInJSON}).\n${this.getSchemaPartText(parentSchema, false)}`; } } + } + /** + * @param {Array} errors + * @returns {string} + */ - __define(node, def) { - if (node && node.type === Syntax.Identifier) { - this.__defineGeneric( - node.name, - this.set, - this.variables, - node, - def - ); - } - } - __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) { + formatValidationErrors(errors) { + return errors.map(error => { + let formattedError = this.formatValidationError(error); - // because Array element may be null - if (!node || node.type !== Syntax.Identifier) { - return; - } + if (this.postFormatter) { + formattedError = this.postFormatter(formattedError, error); + } - // Specially handle like `this`. - if (node.name === "super") { - return; - } + return ` - ${indent(formattedError, " ")}`; + }).join("\n"); + } - const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init); +} - this.references.push(ref); - this.__left.push(ref); - } +var _default = ValidationError; +exports.Z = _default; - __detectEval() { - let current = this; +/***/ }), - this.directCallToEvalScope = true; - do { - current.dynamic = true; - current = current.upper; - } while (current); - } +/***/ 81184: +/***/ (function(module) { - __detectThis() { - this.thisFound = true; - } +"use strict"; - __isClosed() { - return this.__left === null; - } - /** - * returns resolved {Reference} - * @method Scope#resolve - * @param {Espree.Identifier} ident - identifier to be resolved. - * @returns {Reference} reference - */ - resolve(ident) { - let ref, i, iz; +/** + * @typedef {[number, boolean]} RangeValue + */ - assert(this.__isClosed(), "Scope should be closed."); - assert(ident.type === Syntax.Identifier, "Target should be identifier."); - for (i = 0, iz = this.references.length; i < iz; ++i) { - ref = this.references[i]; - if (ref.identifier === ident) { - return ref; - } - } - return null; +/** + * @callback RangeValueCallback + * @param {RangeValue} rangeValue + * @returns {boolean} + */ +class Range { + /** + * @param {"left" | "right"} side + * @param {boolean} exclusive + * @returns {">" | ">=" | "<" | "<="} + */ + static getOperator(side, exclusive) { + if (side === "left") { + return exclusive ? ">" : ">="; } - /** - * returns this scope is static - * @method Scope#isStatic - * @returns {boolean} static - */ - isStatic() { - return !this.dynamic; - } + return exclusive ? "<" : "<="; + } + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ - /** - * returns this scope has materialized arguments - * @method Scope#isArgumentsMaterialized - * @returns {boolean} arguemnts materialized - */ - isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this - return true; - } - /** - * returns this scope has materialized `this` reference - * @method Scope#isThisMaterialized - * @returns {boolean} this materialized - */ - isThisMaterialized() { // eslint-disable-line class-methods-use-this - return true; + static formatRight(value, logic, exclusive) { + if (logic === false) { + return Range.formatLeft(value, !logic, !exclusive); } - isUsedName(name) { - if (this.set.has(name)) { - return true; - } - for (let i = 0, iz = this.through.length; i < iz; ++i) { - if (this.through[i].identifier.name === name) { - return true; - } - } - return false; - } -} + return `should be ${Range.getOperator("right", exclusive)} ${value}`; + } + /** + * @param {number} value + * @param {boolean} logic is not logic applied + * @param {boolean} exclusive is range exclusive + * @returns {string} + */ -class GlobalScope extends Scope { - constructor(scopeManager, block) { - super(scopeManager, "global", null, block, false); - this.implicit = { - set: new Map(), - variables: [], - /** - * List of {@link Reference}s that are left to be resolved (i.e. which - * need to be linked to the variable they refer to). - * @member {Reference[]} Scope#implicit#left - */ - left: [] - }; + static formatLeft(value, logic, exclusive) { + if (logic === false) { + return Range.formatRight(value, !logic, !exclusive); } - __close(scopeManager) { - const implicit = []; - - for (let i = 0, iz = this.__left.length; i < iz; ++i) { - const ref = this.__left[i]; - - if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) { - implicit.push(ref.__maybeImplicitGlobal); - } - } + return `should be ${Range.getOperator("left", exclusive)} ${value}`; + } + /** + * @param {number} start left side value + * @param {number} end right side value + * @param {boolean} startExclusive is range exclusive from left side + * @param {boolean} endExclusive is range exclusive from right side + * @param {boolean} logic is not logic applied + * @returns {string} + */ - // create an implicit global variable from assignment expression - for (let i = 0, iz = implicit.length; i < iz; ++i) { - const info = implicit[i]; - this.__defineImplicit(info.pattern, - new Definition( - Variable.ImplicitGlobalVariable, - info.pattern, - info.node, - null, - null, - null - )); + static formatRange(start, end, startExclusive, endExclusive, logic) { + let result = "should be"; + result += ` ${Range.getOperator(logic ? "left" : "right", logic ? startExclusive : !startExclusive)} ${start} `; + result += logic ? "and" : "or"; + result += ` ${Range.getOperator(logic ? "right" : "left", logic ? endExclusive : !endExclusive)} ${end}`; + return result; + } + /** + * @param {Array} values + * @param {boolean} logic is not logic applied + * @return {RangeValue} computed value and it's exclusive flag + */ - } - this.implicit.left = this.__left; + static getRangeValue(values, logic) { + let minMax = logic ? Infinity : -Infinity; + let j = -1; + const predicate = logic ? + /** @type {RangeValueCallback} */ + ([value]) => value <= minMax : + /** @type {RangeValueCallback} */ + ([value]) => value >= minMax; - return super.__close(scopeManager); + for (let i = 0; i < values.length; i++) { + if (predicate(values[i])) { + [minMax] = values[i]; + j = i; + } } - __defineImplicit(node, def) { - if (node && node.type === Syntax.Identifier) { - this.__defineGeneric( - node.name, - this.implicit.set, - this.implicit.variables, - node, - def - ); - } + if (j > -1) { + return values[j]; } -} -class ModuleScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "module", upperScope, block, false); - } -} + return [Infinity, true]; + } -class FunctionExpressionNameScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "function-expression-name", upperScope, block, false); - this.__define(block.id, - new Definition( - Variable.FunctionName, - block.id, - block, - null, - null, - null - )); - this.functionExpressionScope = true; - } -} + constructor() { + /** @type {Array} */ + this._left = []; + /** @type {Array} */ -class CatchScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "catch", upperScope, block, false); - } -} + this._right = []; + } + /** + * @param {number} value + * @param {boolean=} exclusive + */ -class WithScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "with", upperScope, block, false); - } - __close(scopeManager) { - if (this.__shouldStaticallyClose(scopeManager)) { - return super.__close(scopeManager); - } + left(value, exclusive = false) { + this._left.push([value, exclusive]); + } + /** + * @param {number} value + * @param {boolean=} exclusive + */ - for (let i = 0, iz = this.__left.length; i < iz; ++i) { - const ref = this.__left[i]; - ref.tainted = true; - this.__delegateToUpperScope(ref); - } - this.__left = null; + right(value, exclusive = false) { + this._right.push([value, exclusive]); + } + /** + * @param {boolean} logic is not logic applied + * @return {string} "smart" range string representation + */ - return this.upper; - } -} -class BlockScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "block", upperScope, block, false); - } -} + format(logic = true) { + const [start, leftExclusive] = Range.getRangeValue(this._left, logic); + const [end, rightExclusive] = Range.getRangeValue(this._right, !logic); -class SwitchScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "switch", upperScope, block, false); + if (!Number.isFinite(start) && !Number.isFinite(end)) { + return ""; } -} - -class FunctionScope extends Scope { - constructor(scopeManager, upperScope, block, isMethodDefinition) { - super(scopeManager, "function", upperScope, block, isMethodDefinition); - // section 9.2.13, FunctionDeclarationInstantiation. - // NOTE Arrow functions never have an arguments objects. - if (this.block.type !== Syntax.ArrowFunctionExpression) { - this.__defineArguments(); - } - } + const realStart = leftExclusive ? start + 1 : start; + const realEnd = rightExclusive ? end - 1 : end; // e.g. 5 < x < 7, 5 < x <= 6, 6 <= x <= 6 - isArgumentsMaterialized() { + if (realStart === realEnd) { + return `should be ${logic ? "" : "!"}= ${realStart}`; + } // e.g. 4 < x < ∞ - // TODO(Constellation) - // We can more aggressive on this condition like this. - // - // function t() { - // // arguments of t is always hidden. - // function arguments() { - // } - // } - if (this.block.type === Syntax.ArrowFunctionExpression) { - return false; - } - if (!this.isStatic()) { - return true; - } + if (Number.isFinite(start) && !Number.isFinite(end)) { + return Range.formatLeft(start, logic, leftExclusive); + } // e.g. ∞ < x < 4 - const variable = this.set.get("arguments"); - assert(variable, "Always have arguments variable."); - return variable.tainted || variable.references.length !== 0; + if (!Number.isFinite(start) && Number.isFinite(end)) { + return Range.formatRight(end, logic, rightExclusive); } - isThisMaterialized() { - if (!this.isStatic()) { - return true; - } - return this.thisFound; - } + return Range.formatRange(start, end, leftExclusive, rightExclusive, logic); + } - __defineArguments() { - this.__defineGeneric( - "arguments", - this.set, - this.variables, - null, - null - ); - this.taints.set("arguments", true); - } +} - // References in default parameters isn't resolved to variables which are in their function body. - // const x = 1 - // function f(a = x) { // This `x` is resolved to the `x` in the outer scope. - // const x = 2 - // console.log(a) - // } - __isValidResolution(ref, variable) { +module.exports = Range; - // If `options.nodejsScope` is true, `this.block` becomes a Program node. - if (this.block.type === "Program") { - return true; - } +/***/ }), - const bodyStart = this.block.body.range[0]; +/***/ 79926: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // It's invalid resolution in the following case: - return !( - variable.scope === this && - ref.identifier.range[0] < bodyStart && // the reference is in the parameter part. - variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body. - ); - } -} +"use strict"; -class ForScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "for", upperScope, block, false); - } -} -class ClassScope extends Scope { - constructor(scopeManager, upperScope, block) { - super(scopeManager, "class", upperScope, block, false); - } -} +const Range = __webpack_require__(81184); +/** @typedef {import("../validate").Schema} Schema */ -module.exports = { - Scope, - GlobalScope, - ModuleScope, - FunctionExpressionNameScope, - CatchScope, - WithScope, - BlockScope, - SwitchScope, - FunctionScope, - ForScope, - ClassScope -}; +/** + * @param {Schema} schema + * @param {boolean} logic + * @return {string[]} + */ -/* vim: set sw=4 ts=4 et tw=80 : */ +module.exports.stringHints = function stringHints(schema, logic) { + const hints = []; + let type = "string"; + const currentSchema = { ...schema + }; -/***/ }), + if (!logic) { + const tmpLength = currentSchema.minLength; + const tmpFormat = currentSchema.formatMinimum; + const tmpExclusive = currentSchema.formatExclusiveMaximum; + currentSchema.minLength = currentSchema.maxLength; + currentSchema.maxLength = tmpLength; + currentSchema.formatMinimum = currentSchema.formatMaximum; + currentSchema.formatMaximum = tmpFormat; + currentSchema.formatExclusiveMaximum = !currentSchema.formatExclusiveMinimum; + currentSchema.formatExclusiveMinimum = !tmpExclusive; + } -/***/ 82971: -/***/ (function(module) { + if (typeof currentSchema.minLength === "number") { + if (currentSchema.minLength === 1) { + type = "non-empty string"; + } else { + const length = Math.max(currentSchema.minLength - 1, 0); + hints.push(`should be longer than ${length} character${length > 1 ? "s" : ""}`); + } + } -"use strict"; -/* - Copyright (C) 2015 Yusuke Suzuki + if (typeof currentSchema.maxLength === "number") { + if (currentSchema.maxLength === 0) { + type = "empty string"; + } else { + const length = currentSchema.maxLength + 1; + hints.push(`should be shorter than ${length} character${length > 1 ? "s" : ""}`); + } + } - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + if (currentSchema.pattern) { + hints.push(`should${logic ? "" : " not"} match pattern ${JSON.stringify(currentSchema.pattern)}`); + } - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + if (currentSchema.format) { + hints.push(`should${logic ? "" : " not"} match format ${JSON.stringify(currentSchema.format)}`); + } - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + if (currentSchema.formatMinimum) { + hints.push(`should be ${currentSchema.formatExclusiveMinimum ? ">" : ">="} ${JSON.stringify(currentSchema.formatMinimum)}`); + } + if (currentSchema.formatMaximum) { + hints.push(`should be ${currentSchema.formatExclusiveMaximum ? "<" : "<="} ${JSON.stringify(currentSchema.formatMaximum)}`); + } + return [type].concat(hints); +}; /** - * A Variable represents a locally scoped identifier. These include arguments to - * functions. - * @class Variable + * @param {Schema} schema + * @param {boolean} logic + * @return {string[]} */ -class Variable { - constructor(name, scope) { - - /** - * The variable name, as given in the source code. - * @member {String} Variable#name - */ - this.name = name; - /** - * List of defining occurrences of this variable (like in 'var ...' - * statements or as parameter), as AST nodes. - * @member {espree.Identifier[]} Variable#identifiers - */ - this.identifiers = []; - /** - * List of {@link Reference|references} of this variable (excluding parameter entries) - * in its defining scope and all nested scopes. For defining - * occurrences only see {@link Variable#defs}. - * @member {Reference[]} Variable#references - */ - this.references = []; +module.exports.numberHints = function numberHints(schema, logic) { + const hints = [schema.type === "integer" ? "integer" : "number"]; + const range = new Range(); - /** - * List of defining occurrences of this variable (like in 'var ...' - * statements or as parameter), as custom objects. - * @member {Definition[]} Variable#defs - */ - this.defs = []; + if (typeof schema.minimum === "number") { + range.left(schema.minimum); + } - this.tainted = false; + if (typeof schema.exclusiveMinimum === "number") { + range.left(schema.exclusiveMinimum, true); + } - /** - * Whether this is a stack variable. - * @member {boolean} Variable#stack - */ - this.stack = true; + if (typeof schema.maximum === "number") { + range.right(schema.maximum); + } - /** - * Reference to the enclosing Scope. - * @member {Scope} Variable#scope - */ - this.scope = scope; - } -} + if (typeof schema.exclusiveMaximum === "number") { + range.right(schema.exclusiveMaximum, true); + } -Variable.CatchClause = "CatchClause"; -Variable.Parameter = "Parameter"; -Variable.FunctionName = "FunctionName"; -Variable.ClassName = "ClassName"; -Variable.Variable = "Variable"; -Variable.ImportBinding = "ImportBinding"; -Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable"; + const rangeFormat = range.format(logic); -module.exports = Variable; + if (rangeFormat) { + hints.push(rangeFormat); + } -/* vim: set sw=4 ts=4 et tw=80 : */ + if (typeof schema.multipleOf === "number") { + hints.push(`should${logic ? "" : " not"} be multiple of ${schema.multipleOf}`); + } + return hints; +}; /***/ }), -/***/ 81217: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 74315: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +"use strict"; /* - Copyright (C) 2014 Yusuke Suzuki - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -(function () { - 'use strict'; - - var estraverse = __webpack_require__(50165); - function isNode(node) { - if (node == null) { - return false; - } - return typeof node === 'object' && typeof node.type === 'string'; - } - function isProperty(nodeType, key) { - return (nodeType === estraverse.Syntax.ObjectExpression || nodeType === estraverse.Syntax.ObjectPattern) && key === 'properties'; - } - function Visitor(visitor, options) { - options = options || {}; +const RuntimeGlobals = __webpack_require__(16475); +const WebpackError = __webpack_require__(53799); +const ConstDependency = __webpack_require__(76911); +const BasicEvaluatedExpression = __webpack_require__(950); +const { + toConstantDependency, + evaluateToString +} = __webpack_require__(93998); +const ChunkNameRuntimeModule = __webpack_require__(84519); +const GetFullHashRuntimeModule = __webpack_require__(88732); - this.__visitor = visitor || this; - this.__childVisitorKeys = options.childVisitorKeys - ? Object.assign({}, estraverse.VisitorKeys, options.childVisitorKeys) - : estraverse.VisitorKeys; - if (options.fallback === 'iteration') { - this.__fallback = Object.keys; - } else if (typeof options.fallback === 'function') { - this.__fallback = options.fallback; - } - } +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ - /* Default method for visiting children. - * When you need to call default visiting operation inside custom visiting - * operation, you can use it with `this.visitChildren(node)`. - */ - Visitor.prototype.visitChildren = function (node) { - var type, children, i, iz, j, jz, child; - - if (node == null) { - return; - } +/* 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 */ - type = node.type || estraverse.Syntax.Property; +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() + ); - children = this.__childVisitorKeys[type]; - if (!children) { - if (this.__fallback) { - children = this.__fallback(node); - } else { - throw new Error('Unknown node type ' + type + '.'); - } - } + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.chunkName) + .tap("APIPlugin", chunk => { + compilation.addRuntimeModule( + chunk, + new ChunkNameRuntimeModule(chunk.name) + ); + return true; + }); - for (i = 0, iz = children.length; i < iz; ++i) { - child = node[children[i]]; - if (child) { - if (Array.isArray(child)) { - for (j = 0, jz = child.length; j < jz; ++j) { - if (child[j]) { - if (isNode(child[j]) || isProperty(type, children[i])) { - this.visit(child[j]); - } - } - } - } else if (isNode(child)) { - this.visit(child); - } - } - } - }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getFullHash) + .tap("APIPlugin", (chunk, set) => { + compilation.addRuntimeModule(chunk, new GetFullHashRuntimeModule()); + return true; + }); - /* Dispatching node. */ - Visitor.prototype.visit = function (node) { - var type; + /** + * @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)); + } + }); - if (node == null) { - return; - } + 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) + ); + }; - type = node.type || estraverse.Syntax.Property; - if (this.__visitor[type]) { - this.__visitor[type].call(this, node); - return; - } - this.visitChildren(node); - }; + 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); + } + ); + } +} - exports.version = __webpack_require__(12166).version; - exports.Visitor = Visitor; - exports.visit = function (node, visitor, options) { - var v = new Visitor(visitor, options); - v.visit(node); - }; -}()); -/* vim: set sw=4 ts=4 et tw=80 : */ +module.exports = APIPlugin; /***/ }), -/***/ 50165: -/***/ (function(__unused_webpack_module, exports) { +/***/ 77198: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +"use strict"; /* - Copyright (C) 2012-2013 Yusuke Suzuki - Copyright (C) 2012 Ariya Hidayat - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop */ -/*jslint vars:false, bitwise:true*/ -/*jshint indent:4*/ -/*global exports:true*/ -(function clone(exports) { - 'use strict'; - - var Syntax, - VisitorOption, - VisitorKeys, - BREAK, - SKIP, - REMOVE; - - function deepCopy(obj) { - var ret = {}, key, val; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - val = obj[key]; - if (typeof val === 'object' && val !== null) { - ret[key] = deepCopy(val); - } else { - ret[key] = val; - } - } - } - return ret; - } - // based on LLVM libc++ upper_bound / lower_bound - // MIT License - function upperBound(array, func) { - var diff, len, i, current; - len = array.length; - i = 0; +const WebpackError = __webpack_require__(53799); +const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/; - while (len) { - diff = len >>> 1; - current = i + diff; - if (func(array[current])) { - len = diff; - } else { - i = current + 1; - len -= diff + 1; - } - } - return i; - } +/** + * @param {string=} method method name + * @returns {string} message + */ +function createMessage(method) { + return `Abstract method${method ? " " + method : ""}. Must be overridden.`; +} - Syntax = { - AssignmentExpression: 'AssignmentExpression', - AssignmentPattern: 'AssignmentPattern', - ArrayExpression: 'ArrayExpression', - ArrayPattern: 'ArrayPattern', - ArrowFunctionExpression: 'ArrowFunctionExpression', - AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. - BlockStatement: 'BlockStatement', - BinaryExpression: 'BinaryExpression', - BreakStatement: 'BreakStatement', - CallExpression: 'CallExpression', - CatchClause: 'CatchClause', - ChainExpression: 'ChainExpression', - ClassBody: 'ClassBody', - ClassDeclaration: 'ClassDeclaration', - ClassExpression: 'ClassExpression', - ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. - ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. - ConditionalExpression: 'ConditionalExpression', - ContinueStatement: 'ContinueStatement', - DebuggerStatement: 'DebuggerStatement', - DirectiveStatement: 'DirectiveStatement', - DoWhileStatement: 'DoWhileStatement', - EmptyStatement: 'EmptyStatement', - ExportAllDeclaration: 'ExportAllDeclaration', - ExportDefaultDeclaration: 'ExportDefaultDeclaration', - ExportNamedDeclaration: 'ExportNamedDeclaration', - ExportSpecifier: 'ExportSpecifier', - ExpressionStatement: 'ExpressionStatement', - ForStatement: 'ForStatement', - ForInStatement: 'ForInStatement', - ForOfStatement: 'ForOfStatement', - FunctionDeclaration: 'FunctionDeclaration', - FunctionExpression: 'FunctionExpression', - GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. - Identifier: 'Identifier', - IfStatement: 'IfStatement', - ImportExpression: 'ImportExpression', - ImportDeclaration: 'ImportDeclaration', - ImportDefaultSpecifier: 'ImportDefaultSpecifier', - ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', - ImportSpecifier: 'ImportSpecifier', - Literal: 'Literal', - LabeledStatement: 'LabeledStatement', - LogicalExpression: 'LogicalExpression', - MemberExpression: 'MemberExpression', - MetaProperty: 'MetaProperty', - MethodDefinition: 'MethodDefinition', - ModuleSpecifier: 'ModuleSpecifier', - NewExpression: 'NewExpression', - ObjectExpression: 'ObjectExpression', - ObjectPattern: 'ObjectPattern', - Program: 'Program', - Property: 'Property', - RestElement: 'RestElement', - ReturnStatement: 'ReturnStatement', - SequenceExpression: 'SequenceExpression', - SpreadElement: 'SpreadElement', - Super: 'Super', - SwitchStatement: 'SwitchStatement', - SwitchCase: 'SwitchCase', - TaggedTemplateExpression: 'TaggedTemplateExpression', - TemplateElement: 'TemplateElement', - TemplateLiteral: 'TemplateLiteral', - ThisExpression: 'ThisExpression', - ThrowStatement: 'ThrowStatement', - TryStatement: 'TryStatement', - UnaryExpression: 'UnaryExpression', - UpdateExpression: 'UpdateExpression', - VariableDeclaration: 'VariableDeclaration', - VariableDeclarator: 'VariableDeclarator', - WhileStatement: 'WhileStatement', - WithStatement: 'WithStatement', - YieldExpression: 'YieldExpression' - }; +/** + * @constructor + */ +function Message() { + /** @type {string} */ + this.stack = undefined; + Error.captureStackTrace(this); + /** @type {RegExpMatchArray} */ + const match = this.stack.split("\n")[3].match(CURRENT_METHOD_REGEXP); - VisitorKeys = { - AssignmentExpression: ['left', 'right'], - AssignmentPattern: ['left', 'right'], - ArrayExpression: ['elements'], - ArrayPattern: ['elements'], - ArrowFunctionExpression: ['params', 'body'], - AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. - BlockStatement: ['body'], - BinaryExpression: ['left', 'right'], - BreakStatement: ['label'], - CallExpression: ['callee', 'arguments'], - CatchClause: ['param', 'body'], - ChainExpression: ['expression'], - ClassBody: ['body'], - ClassDeclaration: ['id', 'superClass', 'body'], - ClassExpression: ['id', 'superClass', 'body'], - ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. - ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. - ConditionalExpression: ['test', 'consequent', 'alternate'], - ContinueStatement: ['label'], - DebuggerStatement: [], - DirectiveStatement: [], - DoWhileStatement: ['body', 'test'], - EmptyStatement: [], - ExportAllDeclaration: ['source'], - ExportDefaultDeclaration: ['declaration'], - ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], - ExportSpecifier: ['exported', 'local'], - ExpressionStatement: ['expression'], - ForStatement: ['init', 'test', 'update', 'body'], - ForInStatement: ['left', 'right', 'body'], - ForOfStatement: ['left', 'right', 'body'], - FunctionDeclaration: ['id', 'params', 'body'], - FunctionExpression: ['id', 'params', 'body'], - GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. - Identifier: [], - IfStatement: ['test', 'consequent', 'alternate'], - ImportExpression: ['source'], - ImportDeclaration: ['specifiers', 'source'], - ImportDefaultSpecifier: ['local'], - ImportNamespaceSpecifier: ['local'], - ImportSpecifier: ['imported', 'local'], - Literal: [], - LabeledStatement: ['label', 'body'], - LogicalExpression: ['left', 'right'], - MemberExpression: ['object', 'property'], - MetaProperty: ['meta', 'property'], - MethodDefinition: ['key', 'value'], - ModuleSpecifier: [], - NewExpression: ['callee', 'arguments'], - ObjectExpression: ['properties'], - ObjectPattern: ['properties'], - Program: ['body'], - Property: ['key', 'value'], - RestElement: [ 'argument' ], - ReturnStatement: ['argument'], - SequenceExpression: ['expressions'], - SpreadElement: ['argument'], - Super: [], - SwitchStatement: ['discriminant', 'cases'], - SwitchCase: ['test', 'consequent'], - TaggedTemplateExpression: ['tag', 'quasi'], - TemplateElement: [], - TemplateLiteral: ['quasis', 'expressions'], - ThisExpression: [], - ThrowStatement: ['argument'], - TryStatement: ['block', 'handler', 'finalizer'], - UnaryExpression: ['argument'], - UpdateExpression: ['argument'], - VariableDeclaration: ['declarations'], - VariableDeclarator: ['id', 'init'], - WhileStatement: ['test', 'body'], - WithStatement: ['object', 'body'], - YieldExpression: ['argument'] - }; + this.message = match && match[1] ? createMessage(match[1]) : createMessage(); +} - // unique id - BREAK = {}; - SKIP = {}; - REMOVE = {}; +/** + * 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"; + } +} - VisitorOption = { - Break: BREAK, - Skip: SKIP, - Remove: REMOVE - }; +module.exports = AbstractMethodError; - function Reference(parent, key) { - this.parent = parent; - this.key = key; - } - Reference.prototype.replace = function replace(node) { - this.parent[this.key] = node; - }; +/***/ }), - Reference.prototype.remove = function remove() { - if (Array.isArray(this.parent)) { - this.parent.splice(this.key, 1); - return true; - } else { - this.replace(null); - return false; - } - }; +/***/ 47736: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - function Element(node, path, wrap, ref) { - this.node = node; - this.path = path; - this.wrap = wrap; - this.ref = ref; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - function Controller() { } - // API: - // return property path array from root to current node - Controller.prototype.path = function path() { - var i, iz, j, jz, result, element; - function addToPath(result, path) { - if (Array.isArray(path)) { - for (j = 0, jz = path.length; j < jz; ++j) { - result.push(path[j]); - } - } else { - result.push(path); - } - } +const DependenciesBlock = __webpack_require__(71040); +const makeSerializable = __webpack_require__(33032); - // root node - if (!this.__current.path) { - return null; - } +/** @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 */ - // first node is sentinel, second node is root element - result = []; - for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { - element = this.__leavelist[i]; - addToPath(result, element.path); - } - addToPath(result, this.__current.path); - return result; - }; +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; + this._stringifiedGroupOptions = undefined; + } - // API: - // return type of current node - Controller.prototype.type = function () { - var node = this.current(); - return node.type || this.__current.wrap; - }; + /** + * @returns {string} The name of the chunk + */ + get chunkName() { + return this.groupOptions.name; + } - // API: - // return array of parent elements - Controller.prototype.parents = function parents() { - var i, iz, result; + /** + * @param {string} value The new chunk name + * @returns {void} + */ + set chunkName(value) { + if (this.groupOptions.name !== value) { + this.groupOptions.name = value; + this._stringifiedGroupOptions = undefined; + } + } - // first node is sentinel - result = []; - for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { - result.push(this.__leavelist[i].node); - } + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + const { chunkGraph } = context; + if (this._stringifiedGroupOptions === undefined) { + this._stringifiedGroupOptions = JSON.stringify(this.groupOptions); + } + const chunkGroup = chunkGraph.getBlockChunkGroup(this); + hash.update( + `${this._stringifiedGroupOptions}${chunkGroup ? chunkGroup.id : ""}` + ); + super.updateHash(hash, context); + } - return result; - }; + serialize(context) { + const { write } = context; + write(this.groupOptions); + write(this.loc); + write(this.request); + super.serialize(context); + } - // API: - // return current node - Controller.prototype.current = function current() { - return this.__current.node; - }; + deserialize(context) { + const { read } = context; + this.groupOptions = read(); + this.loc = read(); + this.request = read(); + super.deserialize(context); + } +} - Controller.prototype.__execute = function __execute(callback, element) { - var previous, result; +makeSerializable(AsyncDependenciesBlock, "webpack/lib/AsyncDependenciesBlock"); - result = undefined; +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)" + ); + } +}); - previous = this.__current; - this.__current = element; - this.__state = null; - if (callback) { - result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); - } - this.__current = previous; +module.exports = AsyncDependenciesBlock; - return result; - }; - // API: - // notify control skip / break - Controller.prototype.notify = function notify(flag) { - this.__state = flag; - }; +/***/ }), - // API: - // skip child nodes of current node - Controller.prototype.skip = function () { - this.notify(SKIP); - }; +/***/ 30111: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // API: - // break traversals - Controller.prototype['break'] = function () { - this.notify(BREAK); - }; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ - // API: - // remove node - Controller.prototype.remove = function () { - this.notify(REMOVE); - }; - Controller.prototype.__initialize = function(root, visitor) { - this.visitor = visitor; - this.root = root; - this.__worklist = []; - this.__leavelist = []; - this.__current = null; - this.__state = null; - this.__fallback = null; - if (visitor.fallback === 'iteration') { - this.__fallback = Object.keys; - } else if (typeof visitor.fallback === 'function') { - this.__fallback = visitor.fallback; - } - this.__keys = VisitorKeys; - if (visitor.keys) { - this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); - } - }; +const WebpackError = __webpack_require__(53799); - function isNode(node) { - if (node == null) { - return false; - } - return typeof node === 'object' && typeof node.type === 'string'; - } +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ - function isProperty(nodeType, key) { - return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; - } - - function candidateExistsInLeaveList(leavelist, candidate) { - for (var i = leavelist.length - 1; i >= 0; --i) { - if (leavelist[i].node === candidate) { - return true; - } - } - return false; - } +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.` + ); - Controller.prototype.traverse = function traverse(root, visitor) { - var worklist, - leavelist, - element, - node, - nodeType, - ret, - key, - current, - current2, - candidates, - candidate, - sentinel; + this.name = "AsyncDependencyToInitialChunkError"; + this.module = module; + this.loc = loc; + } +} - this.__initialize(root, visitor); +module.exports = AsyncDependencyToInitialChunkError; - sentinel = {}; - // reference - worklist = this.__worklist; - leavelist = this.__leavelist; +/***/ }), - // initialize - worklist.push(new Element(root, null, null, null)); - leavelist.push(new Element(null, null, null, null)); +/***/ 17714: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - while (worklist.length) { - element = worklist.pop(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (element === sentinel) { - element = leavelist.pop(); - ret = this.__execute(visitor.leave, element); - if (this.__state === BREAK || ret === BREAK) { - return; - } - continue; - } +const asyncLib = __webpack_require__(78175); +const NormalModule = __webpack_require__(39); +const PrefetchDependency = __webpack_require__(31618); - if (element.node) { +/** @typedef {import("./Compiler")} Compiler */ - ret = this.__execute(visitor.enter, element); +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 = []; - if (this.__state === BREAK || ret === BREAK) { - return; - } + 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; - worklist.push(sentinel); - leavelist.push(element); - if (this.__state === SKIP || ret === SKIP) { - continue; - } +/***/ }), - node = element.node; - nodeType = node.type || element.wrap; - candidates = this.__keys[nodeType]; - if (!candidates) { - if (this.__fallback) { - candidates = this.__fallback(node); - } else { - throw new Error('Unknown node type ' + nodeType + '.'); - } - } +/***/ 21242: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - current = candidates.length; - while ((current -= 1) >= 0) { - key = candidates[current]; - candidate = node[key]; - if (!candidate) { - continue; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (Array.isArray(candidate)) { - current2 = candidate.length; - while ((current2 -= 1) >= 0) { - if (!candidate[current2]) { - continue; - } - if (candidateExistsInLeaveList(leavelist, candidate[current2])) { - continue; - } - if (isProperty(nodeType, candidates[current])) { - element = new Element(candidate[current2], [key, current2], 'Property', null); - } else if (isNode(candidate[current2])) { - element = new Element(candidate[current2], [key, current2], null, null); - } else { - continue; - } - worklist.push(element); - } - } else if (isNode(candidate)) { - if (candidateExistsInLeaveList(leavelist, candidate)) { - continue; - } +const { ConcatSource } = __webpack_require__(51255); +const Compilation = __webpack_require__(85720); +const ModuleFilenameHelpers = __webpack_require__(88821); +const Template = __webpack_require__(1626); +const createSchemaValidation = __webpack_require__(32540); - worklist.push(new Element(candidate, key, null, null)); - } - } - } - } - }; +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */ +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ - Controller.prototype.replace = function replace(root, visitor) { - var worklist, - leavelist, - node, - nodeType, - target, - element, - current, - current2, - candidates, - candidate, - sentinel, - outer, - key; +const validate = createSchemaValidation( + __webpack_require__(42173), + () => __webpack_require__(49052), + { + name: "Banner Plugin", + baseDataPath: "options" + } +); - function removeElem(element) { - var i, - key, - nextElem, - parent; +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 */`; +}; - if (element.ref.remove()) { - // When the reference is an element of an array. - key = element.ref.key; - parent = element.ref.parent; +class BannerPlugin { + /** + * @param {BannerPluginArgument} options options object + */ + constructor(options) { + if (typeof options === "string" || typeof options === "function") { + options = { + banner: options + }; + } - // If removed from array, then decrease following items' keys. - i = worklist.length; - while (i--) { - nextElem = worklist[i]; - if (nextElem.ref && nextElem.ref.parent === parent) { - if (nextElem.ref.key < key) { - break; - } - --nextElem.ref.key; - } - } - } - } + validate(options); - this.__initialize(root, visitor); + this.options = options; - sentinel = {}; + 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; + } + } - // reference - worklist = this.__worklist; - leavelist = this.__leavelist; + /** + * 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 + ); - // initialize - outer = { - root: root - }; - element = new Element(root, null, null, new Reference(outer, 'root')); - worklist.push(element); - leavelist.push(element); + 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; + } - while (worklist.length) { - element = worklist.pop(); + for (const file of chunk.files) { + if (!matchObject(file)) { + continue; + } - if (element === sentinel) { - element = leavelist.pop(); + const data = { + chunk, + filename: file + }; - target = this.__execute(visitor.leave, element); + const comment = compilation.getPath(banner, data); - // node may be replaced with null, - // so distinguish between undefined and null in this place - if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { - // replace - element.ref.replace(target); - } + compilation.updateAsset( + file, + old => new ConcatSource(comment, "\n", old) + ); + } + } + } + ); + }); + } +} - if (this.__state === REMOVE || target === REMOVE) { - removeElem(element); - } +module.exports = BannerPlugin; - if (this.__state === BREAK || target === BREAK) { - return outer.root; - } - continue; - } - target = this.__execute(visitor.enter, element); +/***/ }), - // node may be replaced with null, - // so distinguish between undefined and null in this place - if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { - // replace - element.ref.replace(target); - element.node = target; - } +/***/ 7592: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (this.__state === REMOVE || target === REMOVE) { - removeElem(element); - element.node = null; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (this.__state === BREAK || target === BREAK) { - return outer.root; - } - // node may be null - node = element.node; - if (!node) { - continue; - } - worklist.push(sentinel); - leavelist.push(element); +const { AsyncParallelHook, AsyncSeriesBailHook, SyncHook } = __webpack_require__(6967); +const { + makeWebpackError, + makeWebpackErrorCallback +} = __webpack_require__(11351); - if (this.__state === SKIP || target === SKIP) { - continue; - } +/** @typedef {import("./WebpackError")} WebpackError */ - nodeType = node.type || element.wrap; - candidates = this.__keys[nodeType]; - if (!candidates) { - if (this.__fallback) { - candidates = this.__fallback(node); - } else { - throw new Error('Unknown node type ' + nodeType + '.'); - } - } +/** + * @typedef {Object} Etag + * @property {function(): string} toString + */ - current = candidates.length; - while ((current -= 1) >= 0) { - key = candidates[current]; - candidate = node[key]; - if (!candidate) { - continue; - } +/** + * @template T + * @callback CallbackCache + * @param {(WebpackError | null)=} err + * @param {T=} result + * @returns {void} + */ - if (Array.isArray(candidate)) { - current2 = candidate.length; - while ((current2 -= 1) >= 0) { - if (!candidate[current2]) { - continue; - } - if (isProperty(nodeType, candidates[current])) { - element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); - } else if (isNode(candidate[current2])) { - element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); - } else { - continue; - } - worklist.push(element); - } - } else if (isNode(candidate)) { - worklist.push(new Element(candidate, key, null, new Reference(node, key))); - } - } - } +/** + * @callback GotHandler + * @param {any} result + * @param {function(Error=): void} callback + * @returns {void} + */ - return outer.root; - }; +const needCalls = (times, callback) => { + return err => { + if (--times === 0) { + return callback(err); + } + if (err && times > 0) { + times = 0; + return callback(err); + } + }; +}; - function traverse(root, visitor) { - var controller = new Controller(); - return controller.traverse(root, visitor); - } +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]>} */ + storeBuildDependencies: new AsyncParallelHook(["dependencies"]), + /** @type {SyncHook<[]>} */ + beginIdle: new SyncHook([]), + /** @type {AsyncParallelHook<[]>} */ + endIdle: new AsyncParallelHook([]), + /** @type {AsyncParallelHook<[]>} */ + shutdown: new AsyncParallelHook([]) + }; + } - function replace(root, visitor) { - var controller = new Controller(); - return controller.replace(root, visitor); - } + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {CallbackCache} 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); + } + }); + } - function extendCommentRange(comment, tokens) { - var target; + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {T} data the value to store + * @param {CallbackCache} 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") + ); + } - target = upperBound(tokens, function search(token) { - return token.range[0] > comment.range[0]; - }); + /** + * After this method has succeeded the cache can only be restored when build dependencies are + * @param {Iterable} dependencies list of all build dependencies + * @param {CallbackCache} callback signals when the dependencies are stored + * @returns {void} + */ + storeBuildDependencies(dependencies, callback) { + this.hooks.storeBuildDependencies.callAsync( + dependencies, + makeWebpackErrorCallback(callback, "Cache.hooks.storeBuildDependencies") + ); + } - comment.extendedRange = [comment.range[0], comment.range[1]]; + /** + * @returns {void} + */ + beginIdle() { + this.hooks.beginIdle.call(); + } - if (target !== tokens.length) { - comment.extendedRange[1] = tokens[target].range[0]; - } + /** + * @param {CallbackCache} callback signals when the call finishes + * @returns {void} + */ + endIdle(callback) { + this.hooks.endIdle.callAsync( + makeWebpackErrorCallback(callback, "Cache.hooks.endIdle") + ); + } - target -= 1; - if (target >= 0) { - comment.extendedRange[0] = tokens[target].range[1]; - } + /** + * @param {CallbackCache} callback signals when the call finishes + * @returns {void} + */ + shutdown(callback) { + this.hooks.shutdown.callAsync( + makeWebpackErrorCallback(callback, "Cache.hooks.shutdown") + ); + } +} - return comment; - } +Cache.STAGE_MEMORY = -10; +Cache.STAGE_DEFAULT = 0; +Cache.STAGE_DISK = 10; +Cache.STAGE_NETWORK = 20; - function attachComments(tree, providedComments, tokens) { - // At first, we should calculate extended comment ranges. - var comments = [], comment, len, i, cursor; +module.exports = Cache; - if (!tree.range) { - throw new Error('attachComments needs range information'); - } - // tokens array is empty, we attach comments to tree as 'leadingComments' - if (!tokens.length) { - if (providedComments.length) { - for (i = 0, len = providedComments.length; i < len; i += 1) { - comment = deepCopy(providedComments[i]); - comment.extendedRange = [0, tree.range[0]]; - comments.push(comment); - } - tree.leadingComments = comments; - } - return tree; - } +/***/ }), - for (i = 0, len = providedComments.length; i < len; i += 1) { - comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); - } +/***/ 55392: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // This is based on John Freeman's implementation. - cursor = 0; - traverse(tree, { - enter: function (node) { - var comment; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - while (cursor < comments.length) { - comment = comments[cursor]; - if (comment.extendedRange[1] > node.range[0]) { - break; - } - if (comment.extendedRange[1] === node.range[0]) { - if (!node.leadingComments) { - node.leadingComments = []; - } - node.leadingComments.push(comment); - comments.splice(cursor, 1); - } else { - cursor += 1; - } - } - // already out of owned node - if (cursor === comments.length) { - return VisitorOption.Break; - } +const { forEachBail } = __webpack_require__(9256); +const asyncLib = __webpack_require__(78175); +const getLazyHashedEtag = __webpack_require__(94075); +const mergeEtags = __webpack_require__(54980); - if (comments[cursor].extendedRange[0] > node.range[1]) { - return VisitorOption.Skip; - } - } - }); +/** @typedef {import("./Cache")} Cache */ +/** @typedef {import("./Cache").Etag} Etag */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./cache/getLazyHashedEtag").HashableObject} HashableObject */ +/** @typedef {typeof import("./util/Hash")} HashConstructor */ - cursor = 0; - traverse(tree, { - leave: function (node) { - var comment; +/** + * @template T + * @callback CallbackCache + * @param {(WebpackError | null)=} err + * @param {T=} result + * @returns {void} + */ - while (cursor < comments.length) { - comment = comments[cursor]; - if (node.range[1] < comment.extendedRange[0]) { - break; - } +/** + * @template T + * @callback CallbackNormalErrorCache + * @param {(Error | null)=} err + * @param {T=} result + * @returns {void} + */ - if (node.range[1] === comment.extendedRange[0]) { - if (!node.trailingComments) { - node.trailingComments = []; - } - node.trailingComments.push(comment); - comments.splice(cursor, 1); - } else { - cursor += 1; - } - } +class MultiItemCache { + /** + * @param {ItemCacheFacade[]} items item caches + */ + constructor(items) { + this._items = items; + if (items.length === 1) return /** @type {any} */ (items[0]); + } - // already out of owned node - if (cursor === comments.length) { - return VisitorOption.Break; - } + /** + * @template T + * @param {CallbackCache} callback signals when the value is retrieved + * @returns {void} + */ + get(callback) { + forEachBail(this._items, (item, callback) => item.get(callback), callback); + } - if (comments[cursor].extendedRange[0] > node.range[1]) { - return VisitorOption.Skip; - } - } - }); + /** + * @template T + * @returns {Promise} 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); + } - return tree; - } + /** + * @template T + * @param {T} data the value to store + * @param {CallbackCache} callback signals when the value is stored + * @returns {void} + */ + store(data, callback) { + asyncLib.each( + this._items, + (item, callback) => item.store(data, callback), + callback + ); + } - exports.Syntax = Syntax; - exports.traverse = traverse; - exports.replace = replace; - exports.attachComments = attachComments; - exports.VisitorKeys = VisitorKeys; - exports.VisitorOption = VisitorOption; - exports.Controller = Controller; - exports.cloneEnvironment = function () { return clone({}); }; + /** + * @template T + * @param {T} data the value to store + * @returns {Promise} promise signals when the value is stored + */ + storePromise(data) { + return Promise.all(this._items.map(item => item.storePromise(data))).then( + () => {} + ); + } +} - return exports; -}(exports)); -/* vim: set sw=4 ts=4 et tw=80 : */ +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} callback signals when the value is retrieved + * @returns {void} + */ + get(callback) { + this._cache.get(this._name, this._etag, callback); + } -/***/ }), + /** + * @template T + * @returns {Promise} 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); + } + }); + }); + } -/***/ 18350: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /** + * @template T + * @param {T} data the value to store + * @param {CallbackCache} callback signals when the value is stored + * @returns {void} + */ + store(data, callback) { + this._cache.store(this._name, this._etag, data, callback); + } -/* - Copyright (C) 2012-2013 Yusuke Suzuki - Copyright (C) 2012 Ariya Hidayat + /** + * @template T + * @param {T} data the value to store + * @returns {Promise} 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(); + } + }); + }); + } - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: + /** + * @template T + * @param {function(CallbackNormalErrorCache): void} computer function to compute the value if not cached + * @param {CallbackNormalErrorCache} 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); + }); + }); + }); + } - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. + /** + * @template T + * @param {function(): Promise | T} computer function to compute the value if not cached + * @returns {Promise} 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; + } +} - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/*jslint vars:false, bitwise:true*/ -/*jshint indent:4*/ -/*global exports:true*/ -(function clone(exports) { - 'use strict'; +class CacheFacade { + /** + * @param {Cache} cache the root cache + * @param {string} name the child cache name + * @param {string | HashConstructor} hashFunction the hash function to use + */ + constructor(cache, name, hashFunction) { + this._cache = cache; + this._name = name; + this._hashFunction = hashFunction; + } - var Syntax, - VisitorOption, - VisitorKeys, - BREAK, - SKIP, - REMOVE; + /** + * @param {string} name the child cache name# + * @returns {CacheFacade} child cache + */ + getChildCache(name) { + return new CacheFacade( + this._cache, + `${this._name}|${name}`, + this._hashFunction + ); + } - function deepCopy(obj) { - var ret = {}, key, val; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - val = obj[key]; - if (typeof val === 'object' && val !== null) { - ret[key] = deepCopy(val); - } else { - ret[key] = val; - } - } - } - return ret; - } + /** + * @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 + ); + } - // based on LLVM libc++ upper_bound / lower_bound - // MIT License + /** + * @param {HashableObject} obj an hashable object + * @returns {Etag} an etag that is lazy hashed + */ + getLazyHashedEtag(obj) { + return getLazyHashedEtag(obj, this._hashFunction); + } - function upperBound(array, func) { - var diff, len, i, current; + /** + * @param {Etag} a an etag + * @param {Etag} b another etag + * @returns {Etag} an etag that represents both + */ + mergeEtags(a, b) { + return mergeEtags(a, b); + } - len = array.length; - i = 0; + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {CallbackCache} callback signals when the value is retrieved + * @returns {void} + */ + get(identifier, etag, callback) { + this._cache.get(`${this._name}|${identifier}`, etag, callback); + } - while (len) { - diff = len >>> 1; - current = i + diff; - if (func(array[current])) { - len = diff; - } else { - i = current + 1; - len -= diff + 1; - } - } - return i; - } + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @returns {Promise} 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); + } + }); + }); + } - Syntax = { - AssignmentExpression: 'AssignmentExpression', - AssignmentPattern: 'AssignmentPattern', - ArrayExpression: 'ArrayExpression', - ArrayPattern: 'ArrayPattern', - ArrowFunctionExpression: 'ArrowFunctionExpression', - AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. - BlockStatement: 'BlockStatement', - BinaryExpression: 'BinaryExpression', - BreakStatement: 'BreakStatement', - CallExpression: 'CallExpression', - CatchClause: 'CatchClause', - ClassBody: 'ClassBody', - ClassDeclaration: 'ClassDeclaration', - ClassExpression: 'ClassExpression', - ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. - ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. - ConditionalExpression: 'ConditionalExpression', - ContinueStatement: 'ContinueStatement', - DebuggerStatement: 'DebuggerStatement', - DirectiveStatement: 'DirectiveStatement', - DoWhileStatement: 'DoWhileStatement', - EmptyStatement: 'EmptyStatement', - ExportAllDeclaration: 'ExportAllDeclaration', - ExportDefaultDeclaration: 'ExportDefaultDeclaration', - ExportNamedDeclaration: 'ExportNamedDeclaration', - ExportSpecifier: 'ExportSpecifier', - ExpressionStatement: 'ExpressionStatement', - ForStatement: 'ForStatement', - ForInStatement: 'ForInStatement', - ForOfStatement: 'ForOfStatement', - FunctionDeclaration: 'FunctionDeclaration', - FunctionExpression: 'FunctionExpression', - GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. - Identifier: 'Identifier', - IfStatement: 'IfStatement', - ImportExpression: 'ImportExpression', - ImportDeclaration: 'ImportDeclaration', - ImportDefaultSpecifier: 'ImportDefaultSpecifier', - ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', - ImportSpecifier: 'ImportSpecifier', - Literal: 'Literal', - LabeledStatement: 'LabeledStatement', - LogicalExpression: 'LogicalExpression', - MemberExpression: 'MemberExpression', - MetaProperty: 'MetaProperty', - MethodDefinition: 'MethodDefinition', - ModuleSpecifier: 'ModuleSpecifier', - NewExpression: 'NewExpression', - ObjectExpression: 'ObjectExpression', - ObjectPattern: 'ObjectPattern', - Program: 'Program', - Property: 'Property', - RestElement: 'RestElement', - ReturnStatement: 'ReturnStatement', - SequenceExpression: 'SequenceExpression', - SpreadElement: 'SpreadElement', - Super: 'Super', - SwitchStatement: 'SwitchStatement', - SwitchCase: 'SwitchCase', - TaggedTemplateExpression: 'TaggedTemplateExpression', - TemplateElement: 'TemplateElement', - TemplateLiteral: 'TemplateLiteral', - ThisExpression: 'ThisExpression', - ThrowStatement: 'ThrowStatement', - TryStatement: 'TryStatement', - UnaryExpression: 'UnaryExpression', - UpdateExpression: 'UpdateExpression', - VariableDeclaration: 'VariableDeclaration', - VariableDeclarator: 'VariableDeclarator', - WhileStatement: 'WhileStatement', - WithStatement: 'WithStatement', - YieldExpression: 'YieldExpression' - }; + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {T} data the value to store + * @param {CallbackCache} callback signals when the value is stored + * @returns {void} + */ + store(identifier, etag, data, callback) { + this._cache.store(`${this._name}|${identifier}`, etag, data, callback); + } - VisitorKeys = { - AssignmentExpression: ['left', 'right'], - AssignmentPattern: ['left', 'right'], - ArrayExpression: ['elements'], - ArrayPattern: ['elements'], - ArrowFunctionExpression: ['params', 'body'], - AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. - BlockStatement: ['body'], - BinaryExpression: ['left', 'right'], - BreakStatement: ['label'], - CallExpression: ['callee', 'arguments'], - CatchClause: ['param', 'body'], - ClassBody: ['body'], - ClassDeclaration: ['id', 'superClass', 'body'], - ClassExpression: ['id', 'superClass', 'body'], - ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. - ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. - ConditionalExpression: ['test', 'consequent', 'alternate'], - ContinueStatement: ['label'], - DebuggerStatement: [], - DirectiveStatement: [], - DoWhileStatement: ['body', 'test'], - EmptyStatement: [], - ExportAllDeclaration: ['source'], - ExportDefaultDeclaration: ['declaration'], - ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], - ExportSpecifier: ['exported', 'local'], - ExpressionStatement: ['expression'], - ForStatement: ['init', 'test', 'update', 'body'], - ForInStatement: ['left', 'right', 'body'], - ForOfStatement: ['left', 'right', 'body'], - FunctionDeclaration: ['id', 'params', 'body'], - FunctionExpression: ['id', 'params', 'body'], - GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. - Identifier: [], - IfStatement: ['test', 'consequent', 'alternate'], - ImportExpression: ['source'], - ImportDeclaration: ['specifiers', 'source'], - ImportDefaultSpecifier: ['local'], - ImportNamespaceSpecifier: ['local'], - ImportSpecifier: ['imported', 'local'], - Literal: [], - LabeledStatement: ['label', 'body'], - LogicalExpression: ['left', 'right'], - MemberExpression: ['object', 'property'], - MetaProperty: ['meta', 'property'], - MethodDefinition: ['key', 'value'], - ModuleSpecifier: [], - NewExpression: ['callee', 'arguments'], - ObjectExpression: ['properties'], - ObjectPattern: ['properties'], - Program: ['body'], - Property: ['key', 'value'], - RestElement: [ 'argument' ], - ReturnStatement: ['argument'], - SequenceExpression: ['expressions'], - SpreadElement: ['argument'], - Super: [], - SwitchStatement: ['discriminant', 'cases'], - SwitchCase: ['test', 'consequent'], - TaggedTemplateExpression: ['tag', 'quasi'], - TemplateElement: [], - TemplateLiteral: ['quasis', 'expressions'], - ThisExpression: [], - ThrowStatement: ['argument'], - TryStatement: ['block', 'handler', 'finalizer'], - UnaryExpression: ['argument'], - UpdateExpression: ['argument'], - VariableDeclaration: ['declarations'], - VariableDeclarator: ['id', 'init'], - WhileStatement: ['test', 'body'], - WithStatement: ['object', 'body'], - YieldExpression: ['argument'] - }; + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {T} data the value to store + * @returns {Promise} 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(); + } + }); + }); + } - // unique id - BREAK = {}; - SKIP = {}; - REMOVE = {}; + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {function(CallbackNormalErrorCache): void} computer function to compute the value if not cached + * @param {CallbackNormalErrorCache} 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); + }); + }); + }); + } - VisitorOption = { - Break: BREAK, - Skip: SKIP, - Remove: REMOVE - }; + /** + * @template T + * @param {string} identifier the cache identifier + * @param {Etag | null} etag the etag + * @param {function(): Promise | T} computer function to compute the value if not cached + * @returns {Promise} 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; + } +} - function Reference(parent, key) { - this.parent = parent; - this.key = key; - } +module.exports = CacheFacade; +module.exports.ItemCacheFacade = ItemCacheFacade; +module.exports.MultiItemCache = MultiItemCache; - Reference.prototype.replace = function replace(node) { - this.parent[this.key] = node; - }; - Reference.prototype.remove = function remove() { - if (Array.isArray(this.parent)) { - this.parent.splice(this.key, 1); - return true; - } else { - this.replace(null); - return false; - } - }; +/***/ }), - function Element(node, path, wrap, ref) { - this.node = node; - this.path = path; - this.wrap = wrap; - this.ref = ref; - } +/***/ 77975: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - function Controller() { } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // API: - // return property path array from root to current node - Controller.prototype.path = function path() { - var i, iz, j, jz, result, element; - function addToPath(result, path) { - if (Array.isArray(path)) { - for (j = 0, jz = path.length; j < jz; ++j) { - result.push(path[j]); - } - } else { - result.push(path); - } - } - // root node - if (!this.__current.path) { - return null; - } +const WebpackError = __webpack_require__(53799); - // first node is sentinel, second node is root element - result = []; - for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { - element = this.__leavelist[i]; - addToPath(result, element.path); - } - addToPath(result, this.__current.path); - return result; - }; +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ - // API: - // return type of current node - Controller.prototype.type = function () { - var node = this.current(); - return node.type || this.__current.wrap; - }; +/** + * @param {Module[]} modules the modules to be sorted + * @returns {Module[]} sorted version of original modules + */ +const sortModules = modules => { + return modules.sort((a, b) => { + const aIdent = a.identifier(); + const bIdent = b.identifier(); + /* istanbul ignore next */ + if (aIdent < bIdent) return -1; + /* istanbul ignore next */ + if (aIdent > bIdent) return 1; + /* istanbul ignore next */ + return 0; + }); +}; - // API: - // return array of parent elements - Controller.prototype.parents = function parents() { - var i, iz, result; - - // first node is sentinel - result = []; - for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { - result.push(this.__leavelist[i].node); - } - - return result; - }; - - // API: - // return current node - Controller.prototype.current = function current() { - return this.__current.node; - }; - - Controller.prototype.__execute = function __execute(callback, element) { - var previous, result; +/** + * @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); - result = undefined; + if (validReasons.length > 0) { + message += `\n Used by ${validReasons.length} module(s), i. e.`; + message += `\n ${validReasons[0].identifier()}`; + } + return message; + }) + .join("\n"); +}; - previous = this.__current; - this.__current = element; - this.__state = null; - if (callback) { - result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); - } - this.__current = previous; +class CaseSensitiveModulesWarning extends WebpackError { + /** + * Creates an instance of CaseSensitiveModulesWarning. + * @param {Iterable} modules modules that were detected + * @param {ModuleGraph} moduleGraph the module graph + */ + constructor(modules, moduleGraph) { + const sortedModules = sortModules(Array.from(modules)); + const modulesList = createModulesListMessage(sortedModules, moduleGraph); + super(`There are multiple modules with names that only differ in casing. +This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. +Use equal casing. Compare these module identifiers: +${modulesList}`); - return result; - }; + this.name = "CaseSensitiveModulesWarning"; + this.module = sortedModules[0]; + } +} - // API: - // notify control skip / break - Controller.prototype.notify = function notify(flag) { - this.__state = flag; - }; +module.exports = CaseSensitiveModulesWarning; - // API: - // skip child nodes of current node - Controller.prototype.skip = function () { - this.notify(SKIP); - }; - // API: - // break traversals - Controller.prototype['break'] = function () { - this.notify(BREAK); - }; +/***/ }), - // API: - // remove node - Controller.prototype.remove = function () { - this.notify(REMOVE); - }; +/***/ 39385: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - Controller.prototype.__initialize = function(root, visitor) { - this.visitor = visitor; - this.root = root; - this.__worklist = []; - this.__leavelist = []; - this.__current = null; - this.__state = null; - this.__fallback = null; - if (visitor.fallback === 'iteration') { - this.__fallback = Object.keys; - } else if (typeof visitor.fallback === 'function') { - this.__fallback = visitor.fallback; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - this.__keys = VisitorKeys; - if (visitor.keys) { - this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); - } - }; - function isNode(node) { - if (node == null) { - return false; - } - return typeof node === 'object' && typeof node.type === 'string'; - } - function isProperty(nodeType, key) { - return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; - } +const ChunkGraph = __webpack_require__(64971); +const Entrypoint = __webpack_require__(13795); +const { intersect } = __webpack_require__(93347); +const SortableSet = __webpack_require__(13098); +const StringXor = __webpack_require__(40293); +const { + compareModulesByIdentifier, + compareChunkGroupsByIndex, + compareModulesById +} = __webpack_require__(29579); +const { createArrayToSetDeprecationSet } = __webpack_require__(64518); +const { mergeRuntime } = __webpack_require__(17156); - Controller.prototype.traverse = function traverse(root, visitor) { - var worklist, - leavelist, - element, - node, - nodeType, - ret, - key, - current, - current2, - candidates, - candidate, - sentinel; +/** @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 */ - this.__initialize(root, visitor); +const ChunkFilesSet = createArrayToSetDeprecationSet("chunk.files"); - sentinel = {}; +/** + * @typedef {Object} WithId an object who has an id property * + * @property {string | number} id the id of the object + */ - // reference - worklist = this.__worklist; - leavelist = this.__leavelist; +/** + * @deprecated + * @typedef {Object} ChunkMaps + * @property {Record} hash + * @property {Record>} contentHash + * @property {Record} name + */ - // initialize - worklist.push(new Element(root, null, null, null)); - leavelist.push(new Element(null, null, null, null)); +/** + * @deprecated + * @typedef {Object} ChunkModuleMaps + * @property {Record} id + * @property {Record} hash + */ - while (worklist.length) { - element = worklist.pop(); +let debugId = 1000; - if (element === sentinel) { - element = leavelist.pop(); +/** + * A Chunk is a unit of encapsulation for Modules. + * Chunks are "rendered" into bundles that get emitted when the build completes. + */ +class Chunk { + /** + * @param {string=} name of chunk being created, is optional (for subclasses) + * @param {boolean} backCompat enable backward-compatibility + */ + constructor(name, backCompat = true) { + /** @type {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} */ + this.idNameHints = new SortableSet(); + /** @type {boolean} */ + this.preventIntegration = false; + /** @type {(string | function(PathData, AssetInfo=): string)?} */ + this.filenameTemplate = undefined; + /** @type {(string | function(PathData, AssetInfo=): string)?} */ + this.cssFilenameTemplate = undefined; + /** @private @type {SortableSet} */ + this._groups = new SortableSet(undefined, compareChunkGroupsByIndex); + /** @type {RuntimeSpec} */ + this.runtime = undefined; + /** @type {Set} */ + this.files = backCompat ? new ChunkFilesSet() : new Set(); + /** @type {Set} */ + this.auxiliaryFiles = new Set(); + /** @type {boolean} */ + this.rendered = false; + /** @type {string=} */ + this.hash = undefined; + /** @type {Record} */ + this.contentHash = Object.create(null); + /** @type {string=} */ + this.renderedHash = undefined; + /** @type {string=} */ + this.chunkReason = undefined; + /** @type {boolean} */ + this.extraAsync = false; + } - ret = this.__execute(visitor.leave, element); + // 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)" + ); + } + } - if (this.__state === BREAK || ret === BREAK) { - return; - } - continue; - } + /** + * @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 + ); + } - if (element.node) { + /** + * @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; + } - ret = this.__execute(visitor.enter, element); + /** + * @param {Module} module the module + * @returns {void} + */ + removeModule(module) { + ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.removeModule", + "DEP_WEBPACK_CHUNK_REMOVE_MODULE" + ).disconnectChunkAndModule(this, module); + } - if (this.__state === BREAK || ret === BREAK) { - return; - } + /** + * @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); + } - worklist.push(sentinel); - leavelist.push(element); + get modulesIterable() { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.modulesIterable", + "DEP_WEBPACK_CHUNK_MODULES_ITERABLE" + ); + return chunkGraph.getOrderedChunkModulesIterable( + this, + compareModulesByIdentifier + ); + } - if (this.__state === SKIP || ret === SKIP) { - continue; - } + /** + * @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); + } - node = element.node; - nodeType = node.type || element.wrap; - candidates = this.__keys[nodeType]; - if (!candidates) { - if (this.__fallback) { - candidates = this.__fallback(node); - } else { - throw new Error('Unknown node type ' + nodeType + '.'); - } - } + /** + * @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); + } - current = candidates.length; - while ((current -= 1) >= 0) { - key = candidates[current]; - candidate = node[key]; - if (!candidate) { - continue; - } + /** + * @returns {Module[]} the modules for this chunk + */ + getModules() { + return ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.getModules", + "DEP_WEBPACK_CHUNK_GET_MODULES" + ).getChunkModules(this); + } - if (Array.isArray(candidate)) { - current2 = candidate.length; - while ((current2 -= 1) >= 0) { - if (!candidate[current2]) { - continue; - } - if (isProperty(nodeType, candidates[current])) { - element = new Element(candidate[current2], [key, current2], 'Property', null); - } else if (isNode(candidate[current2])) { - element = new Element(candidate[current2], [key, current2], null, null); - } else { - continue; - } - worklist.push(element); - } - } else if (isNode(candidate)) { - worklist.push(new Element(candidate, key, null, null)); - } - } - } - } - }; + /** + * @returns {void} + */ + remove() { + const chunkGraph = ChunkGraph.getChunkGraphForChunk( + this, + "Chunk.remove", + "DEP_WEBPACK_CHUNK_REMOVE" + ); + chunkGraph.disconnectChunk(this); + this.disconnectFromGroups(); + } - Controller.prototype.replace = function replace(root, visitor) { - var worklist, - leavelist, - node, - nodeType, - target, - element, - current, - current2, - candidates, - candidate, - sentinel, - outer, - key; + /** + * @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); + } - function removeElem(element) { - var i, - key, - nextElem, - parent; + /** + * @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; + } + } - if (element.ref.remove()) { - // When the reference is an element of an array. - key = element.ref.key; - parent = element.ref.parent; + /** + * @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); + } - // If removed from array, then decrease following items' keys. - i = worklist.length; - while (i--) { - nextElem = worklist[i]; - if (nextElem.ref && nextElem.ref.parent === parent) { - if (nextElem.ref.key < key) { - break; - } - --nextElem.ref.key; - } - } - } - } + /** + * @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; + } - this.__initialize(root, visitor); + /** + * @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); + } - sentinel = {}; + /** + * @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); + } - // reference - worklist = this.__worklist; - leavelist = this.__leavelist; + /** + * @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); + } - // initialize - outer = { - root: root - }; - element = new Element(root, null, null, new Reference(outer, 'root')); - worklist.push(element); - leavelist.push(element); + /** + * @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} */ + const chunkModuleIdMap = Object.create(null); + /** @type {Record} */ + const chunkModuleHashMap = Object.create(null); - while (worklist.length) { - element = worklist.pop(); + 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 + ); + } + } + } - if (element === sentinel) { - element = leavelist.pop(); + return { + id: chunkModuleIdMap, + hash: chunkModuleHashMap + }; + } - target = this.__execute(visitor.leave, element); + /** + * @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); + } - // node may be replaced with null, - // so distinguish between undefined and null in this place - if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { - // replace - element.ref.replace(target); - } + /** + * @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} */ + const chunkHashMap = Object.create(null); + /** @type {Record>} */ + const chunkContentHashMap = Object.create(null); + /** @type {Record} */ + const chunkNameMap = Object.create(null); - if (this.__state === REMOVE || target === REMOVE) { - removeElem(element); - } + 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; + } + } - if (this.__state === BREAK || target === BREAK) { - return outer.root; - } - continue; - } + return { + hash: chunkHashMap, + contentHash: chunkContentHashMap, + name: chunkNameMap + }; + } + // BACKWARD-COMPAT END - target = this.__execute(visitor.enter, element); + /** + * @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; + } - // node may be replaced with null, - // so distinguish between undefined and null in this place - if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { - // replace - element.ref.replace(target); - element.node = target; - } + /** + * @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; + } - if (this.__state === REMOVE || target === REMOVE) { - removeElem(element); - element.node = null; - } + /** + * @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; + } - if (this.__state === BREAK || target === BREAK) { - return outer.root; - } + /** + * @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; + } - // node may be null - node = element.node; - if (!node) { - continue; - } + /** + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being added + * @returns {void} + */ + addGroup(chunkGroup) { + this._groups.add(chunkGroup); + } - worklist.push(sentinel); - leavelist.push(element); + /** + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being removed from + * @returns {void} + */ + removeGroup(chunkGroup) { + this._groups.delete(chunkGroup); + } - if (this.__state === SKIP || target === SKIP) { - continue; - } + /** + * @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); + } - nodeType = node.type || element.wrap; - candidates = this.__keys[nodeType]; - if (!candidates) { - if (this.__fallback) { - candidates = this.__fallback(node); - } else { - throw new Error('Unknown node type ' + nodeType + '.'); - } - } + /** + * @returns {number} the amount of groups that the said chunk is in + */ + getNumberOfGroups() { + return this._groups.size; + } - current = candidates.length; - while ((current -= 1) >= 0) { - key = candidates[current]; - candidate = node[key]; - if (!candidate) { - continue; - } + /** + * @returns {Iterable} the chunkGroups that the said chunk is referenced in + */ + get groupsIterable() { + this._groups.sort(); + return this._groups; + } - if (Array.isArray(candidate)) { - current2 = candidate.length; - while ((current2 -= 1) >= 0) { - if (!candidate[current2]) { - continue; - } - if (isProperty(nodeType, candidates[current])) { - element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); - } else if (isNode(candidate[current2])) { - element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); - } else { - continue; - } - worklist.push(element); - } - } else if (isNode(candidate)) { - worklist.push(new Element(candidate, key, null, new Reference(node, key))); - } - } - } + /** + * @returns {void} + */ + disconnectFromGroups() { + for (const chunkGroup of this._groups) { + chunkGroup.removeChunk(this); + } + } - return outer.root; - }; + /** + * @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); + } - function traverse(root, visitor) { - var controller = new Controller(); - return controller.traverse(root, visitor); - } + /** + * @param {Hash} hash hash (will be modified) + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} + */ + updateHash(hash, chunkGraph) { + hash.update( + `${this.id} ${this.ids ? this.ids.join() : ""} ${this.name || ""} ` + ); + const xor = new StringXor(); + for (const m of chunkGraph.getChunkModulesIterable(this)) { + xor.add(chunkGraph.getModuleHash(m, this.runtime)); + } + xor.updateHash(hash); + const entryModules = + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(this); + for (const [m, chunkGroup] of entryModules) { + hash.update(`entry${chunkGraph.getModuleId(m)}${chunkGroup.id}`); + } + } - function replace(root, visitor) { - var controller = new Controller(); - return controller.replace(root, visitor); - } + /** + * @returns {Set} a set of all the async chunks + */ + getAllAsyncChunks() { + const queue = new Set(); + const chunks = new Set(); - function extendCommentRange(comment, tokens) { - var target; + const initialChunks = intersect( + Array.from(this.groupsIterable, g => new Set(g.chunks)) + ); - target = upperBound(tokens, function search(token) { - return token.range[0] > comment.range[0]; - }); + const initialQueue = new Set(this.groupsIterable); - comment.extendedRange = [comment.range[0], comment.range[1]]; + for (const chunkGroup of initialQueue) { + for (const child of chunkGroup.childrenIterable) { + if (child instanceof Entrypoint) { + initialQueue.add(child); + } else { + queue.add(child); + } + } + } - if (target !== tokens.length) { - comment.extendedRange[1] = tokens[target].range[0]; - } + 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); + } + } - target -= 1; - if (target >= 0) { - comment.extendedRange[0] = tokens[target].range[1]; - } + return chunks; + } - return comment; - } + /** + * @returns {Set} a set of all the initial chunks (including itself) + */ + getAllInitialChunks() { + const chunks = new Set(); + const queue = new Set(this.groupsIterable); + for (const group of queue) { + if (group.isInitial()) { + for (const c of group.chunks) chunks.add(c); + for (const g of group.childrenIterable) queue.add(g); + } + } + return chunks; + } - function attachComments(tree, providedComments, tokens) { - // At first, we should calculate extended comment ranges. - var comments = [], comment, len, i, cursor; + /** + * @returns {Set} a set of all the referenced chunks (including itself) + */ + getAllReferencedChunks() { + const queue = new Set(this.groupsIterable); + const chunks = new Set(); - if (!tree.range) { - throw new Error('attachComments needs range information'); - } + for (const chunkGroup of queue) { + for (const chunk of chunkGroup.chunks) { + chunks.add(chunk); + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } - // tokens array is empty, we attach comments to tree as 'leadingComments' - if (!tokens.length) { - if (providedComments.length) { - for (i = 0, len = providedComments.length; i < len; i += 1) { - comment = deepCopy(providedComments[i]); - comment.extendedRange = [0, tree.range[0]]; - comments.push(comment); - } - tree.leadingComments = comments; - } - return tree; - } + return chunks; + } - for (i = 0, len = providedComments.length; i < len; i += 1) { - comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); - } + /** + * @returns {Set} a set of all the referenced entrypoints + */ + getAllReferencedAsyncEntrypoints() { + const queue = new Set(this.groupsIterable); + const entrypoints = new Set(); - // This is based on John Freeman's implementation. - cursor = 0; - traverse(tree, { - enter: function (node) { - var comment; + for (const chunkGroup of queue) { + for (const entrypoint of chunkGroup.asyncEntrypointsIterable) { + entrypoints.add(entrypoint); + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } - while (cursor < comments.length) { - comment = comments[cursor]; - if (comment.extendedRange[1] > node.range[0]) { - break; - } + return entrypoints; + } - if (comment.extendedRange[1] === node.range[0]) { - if (!node.leadingComments) { - node.leadingComments = []; - } - node.leadingComments.push(comment); - comments.splice(cursor, 1); - } else { - cursor += 1; - } - } + /** + * @returns {boolean} true, if the chunk references async chunks + */ + hasAsyncChunks() { + const queue = new Set(); - // already out of owned node - if (cursor === comments.length) { - return VisitorOption.Break; - } + const initialChunks = intersect( + Array.from(this.groupsIterable, g => new Set(g.chunks)) + ); - if (comments[cursor].extendedRange[0] > node.range[1]) { - return VisitorOption.Skip; - } - } - }); + for (const chunkGroup of this.groupsIterable) { + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } - cursor = 0; - traverse(tree, { - leave: function (node) { - var comment; + 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); + } + } - while (cursor < comments.length) { - comment = comments[cursor]; - if (node.range[1] < comment.extendedRange[0]) { - break; - } + return false; + } - if (node.range[1] === comment.extendedRange[0]) { - if (!node.trailingComments) { - node.trailingComments = []; - } - node.trailingComments.push(comment); - comments.splice(cursor, 1); - } else { - cursor += 1; - } - } - - // already out of owned node - if (cursor === comments.length) { - return VisitorOption.Break; - } - - if (comments[cursor].extendedRange[0] > node.range[1]) { - return VisitorOption.Skip; - } - } - }); - - return tree; - } + /** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {ChunkFilterPredicate=} filterFn function used to filter chunks + * @returns {Record} a record object of names to lists of child ids(?) + */ + getChildIdsByOrders(chunkGraph, filterFn) { + /** @type {Map} */ + 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} */ + 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} */ + 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; + } - exports.version = (__webpack_require__(15535)/* .version */ .i8); - exports.Syntax = Syntax; - exports.traverse = traverse; - exports.replace = replace; - exports.attachComments = attachComments; - exports.VisitorKeys = VisitorKeys; - exports.VisitorOption = VisitorOption; - exports.Controller = Controller; - exports.cloneEnvironment = function () { return clone({}); }; + /** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} type option name + * @returns {{ onChunks: Chunk[], chunks: Set }[]} 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; + } - return exports; -}(exports)); -/* vim: set sw=4 ts=4 et tw=80 : */ + /** + * @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>} a record object of names to lists of child ids(?) by chunk id + */ + getChildIdsByOrdersMap(chunkGraph, includeDirectChildren, filterFn) { + /** @type {Record>} */ + 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} */ + 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); + } + } -/***/ 86140: -/***/ (function(module) { + for (const chunk of this.getAllAsyncChunks()) { + addChildIdsByOrdersToMap(chunk); + } -module.exports = function (glob, opts) { - if (typeof glob !== 'string') { - throw new TypeError('Expected a string'); - } + return chunkMaps; + } +} - var str = String(glob); +module.exports = Chunk; - // The regexp we are building, as a string. - var reStr = ""; - // Whether we are matching so called "extended" globs (like bash) and should - // support single character matching, matching ranges of characters, group - // matching, etc. - var extended = opts ? !!opts.extended : false; +/***/ }), - // When globstar is _false_ (default), '/foo/*' is translated a regexp like - // '^\/foo\/.*$' which will match any string beginning with '/foo/' - // When globstar is _true_, '/foo/*' is translated to regexp like - // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT - // which does not have a '/' to the right of it. - // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but - // these will not '/foo/bar/baz', '/foo/bar/baz.txt' - // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when - // globstar is _false_ - var globstar = opts ? !!opts.globstar : false; +/***/ 64971: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // If we are doing extended matching, this boolean is true when we are inside - // a group (eg {*.html,*.js}), and false otherwise. - var inGroup = false; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // RegExp flags (eg "i" ) to pass in to RegExp constructor. - var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; - var c; - for (var i = 0, len = str.length; i < len; i++) { - c = str[i]; - switch (c) { - case "/": - case "$": - case "^": - case "+": - case ".": - case "(": - case ")": - case "=": - case "!": - case "|": - reStr += "\\" + c; - break; +const util = __webpack_require__(73837); +const Entrypoint = __webpack_require__(13795); +const ModuleGraphConnection = __webpack_require__(40639); +const { first } = __webpack_require__(93347); +const SortableSet = __webpack_require__(13098); +const { + compareModulesById, + compareIterables, + compareModulesByIdentifier, + concatComparators, + compareSelect, + compareIds +} = __webpack_require__(29579); +const createHash = __webpack_require__(49835); +const findGraphRoots = __webpack_require__(6261); +const { + RuntimeSpecMap, + RuntimeSpecSet, + runtimeToString, + mergeRuntime, + forEachRuntime +} = __webpack_require__(17156); - case "?": - if (extended) { - reStr += "."; - break; - } +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./RuntimeModule")} RuntimeModule */ +/** @typedef {typeof import("./util/Hash")} Hash */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ - case "[": - case "]": - if (extended) { - reStr += c; - break; - } +/** @type {ReadonlySet} */ +const EMPTY_SET = new Set(); - case "{": - if (extended) { - inGroup = true; - reStr += "("; - break; - } +const ZERO_BIG_INT = BigInt(0); - case "}": - if (extended) { - inGroup = false; - reStr += ")"; - break; - } +const compareModuleIterables = compareIterables(compareModulesByIdentifier); - case ",": - if (inGroup) { - reStr += "|"; - break; - } - reStr += "\\" + c; - break; +/** @typedef {(c: Chunk, chunkGraph: ChunkGraph) => boolean} ChunkFilterPredicate */ +/** @typedef {(m: Module) => boolean} ModuleFilterPredicate */ - case "*": - // Move over all consecutive "*"'s. - // Also store the previous and next characters - var prevChar = str[i - 1]; - var starCount = 1; - while(str[i + 1] === "*") { - starCount++; - i++; - } - var nextChar = str[i + 1]; +/** + * @typedef {Object} ChunkSizeOptions + * @property {number=} chunkOverhead constant overhead for a chunk + * @property {number=} entryChunkMultiplicator multiplicator for initial chunks + */ - if (!globstar) { - // globstar is disabled, so treat any number of "*" as one - reStr += ".*"; - } else { - // globstar is enabled, so determine if this is a globstar segment - var isGlobstar = starCount > 1 // multiple "*"'s - && (prevChar === "/" || prevChar === undefined) // from the start of the segment - && (nextChar === "/" || nextChar === undefined) // to the end of the segment +class ModuleHashInfo { + constructor(hash, renderedHash) { + this.hash = hash; + this.renderedHash = renderedHash; + } +} - if (isGlobstar) { - // it's a globstar, so match zero or more path segments - reStr += "((?:[^/]*(?:\/|$))*)"; - i++; // move over the "/" - } else { - // it's not a globstar, so only match one path segment - reStr += "([^/]*)"; - } - } - break; +/** @template T @typedef {(set: SortableSet) => T[]} SetToArrayFunction */ - default: - reStr += c; - } - } +/** + * @template T + * @param {SortableSet} set the set + * @returns {T[]} set as array + */ +const getArray = set => { + return Array.from(set); +}; - // When regexp 'g' flag is specified don't - // constrain the regular expression with ^ & $ - if (!flags || !~flags.indexOf('g')) { - reStr = "^" + reStr + "$"; - } +/** + * @param {SortableSet} chunks the chunks + * @returns {RuntimeSpecSet} runtimes + */ +const getModuleRuntimes = chunks => { + const runtimes = new RuntimeSpecSet(); + for (const chunk of chunks) { + runtimes.add(chunk.runtime); + } + return runtimes; +}; - return new RegExp(reStr, flags); +/** + * @param {SortableSet} set the set + * @returns {Map>} modules by source type + */ +const modulesBySourceType = set => { + /** @type {Map>} */ + const map = new Map(); + for (const module of set) { + for (const sourceType of module.getSourceTypes()) { + let innerSet = map.get(sourceType); + if (innerSet === undefined) { + innerSet = new SortableSet(); + map.set(sourceType, innerSet); + } + innerSet.add(module); + } + } + for (const [key, innerSet] of map) { + // When all modules have the source type, we reuse the original SortableSet + // to benefit from the shared cache (especially for sorting) + if (innerSet.size === set.size) { + map.set(key, set); + } + } + return map; }; +/** @type {WeakMap} */ +const createOrderedArrayFunctionMap = new WeakMap(); -/***/ }), +/** + * @template T + * @param {function(T, T): -1|0|1} comparator comparator function + * @returns {SetToArrayFunction} set as ordered array + */ +const createOrderedArrayFunction = comparator => { + /** @type {SetToArrayFunction} */ + let fn = createOrderedArrayFunctionMap.get(comparator); + if (fn !== undefined) return fn; + fn = set => { + set.sortWith(comparator); + return Array.from(set); + }; + createOrderedArrayFunctionMap.set(comparator, fn); + return fn; +}; -/***/ 89132: -/***/ (function(module) { +/** + * @param {Iterable} modules the modules to get the count/size of + * @returns {number} the size of the modules + */ +const getModulesSize = modules => { + let size = 0; + for (const module of modules) { + for (const type of module.getSourceTypes()) { + size += module.size(type); + } + } + return size; +}; -"use strict"; +/** + * @param {Iterable} modules the sortable Set to get the size of + * @returns {Record} the sizes of the modules + */ +const getModulesSizes = modules => { + let sizes = Object.create(null); + for (const module of modules) { + for (const type of module.getSourceTypes()) { + sizes[type] = (sizes[type] || 0) + module.size(type); + } + } + return sizes; +}; +/** + * @param {Chunk} a chunk + * @param {Chunk} b chunk + * @returns {boolean} true, if a is always a parent of b + */ +const isAvailableChunk = (a, b) => { + const queue = new Set(b.groupsIterable); + for (const chunkGroup of queue) { + if (a.isInGroup(chunkGroup)) continue; + if (chunkGroup.isInitial()) return false; + for (const parent of chunkGroup.parentsIterable) { + queue.add(parent); + } + } + return true; +}; -module.exports = clone +class ChunkGraphModule { + constructor() { + /** @type {SortableSet} */ + this.chunks = new SortableSet(); + /** @type {Set | undefined} */ + this.entryInChunks = undefined; + /** @type {Set | undefined} */ + this.runtimeInChunks = undefined; + /** @type {RuntimeSpecMap} */ + this.hashes = undefined; + /** @type {string | number} */ + this.id = null; + /** @type {RuntimeSpecMap> | undefined} */ + this.runtimeRequirements = undefined; + /** @type {RuntimeSpecMap} */ + this.graphHashes = undefined; + /** @type {RuntimeSpecMap} */ + this.graphHashesWithConnections = undefined; + } +} -var getPrototypeOf = Object.getPrototypeOf || function (obj) { - return obj.__proto__ +class ChunkGraphChunk { + constructor() { + /** @type {SortableSet} */ + this.modules = new SortableSet(); + /** @type {Map} */ + this.entryModules = new Map(); + /** @type {SortableSet} */ + this.runtimeModules = new SortableSet(); + /** @type {Set | undefined} */ + this.fullHashModules = undefined; + /** @type {Set | undefined} */ + this.dependentHashModules = undefined; + /** @type {Set | undefined} */ + this.runtimeRequirements = undefined; + /** @type {Set} */ + this.runtimeRequirementsInTree = new Set(); + } } -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj +class ChunkGraph { + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {string | Hash} hashFunction the hash function to use + */ + constructor(moduleGraph, hashFunction = "md4") { + /** @private @type {WeakMap} */ + this._modules = new WeakMap(); + /** @private @type {WeakMap} */ + this._chunks = new WeakMap(); + /** @private @type {WeakMap} */ + this._blockChunkGroups = new WeakMap(); + /** @private @type {Map} */ + this._runtimeIds = new Map(); + /** @type {ModuleGraph} */ + this.moduleGraph = moduleGraph; - if (obj instanceof Object) - var copy = { __proto__: getPrototypeOf(obj) } - else - var copy = Object.create(null) + this._hashFunction = hashFunction; - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) + this._getGraphRoots = this._getGraphRoots.bind(this); + } - return copy -} + /** + * @private + * @param {Module} module the module + * @returns {ChunkGraphModule} internal module + */ + _getChunkGraphModule(module) { + let cgm = this._modules.get(module); + if (cgm === undefined) { + cgm = new ChunkGraphModule(); + this._modules.set(module, cgm); + } + return cgm; + } + /** + * @private + * @param {Chunk} chunk the chunk + * @returns {ChunkGraphChunk} internal chunk + */ + _getChunkGraphChunk(chunk) { + let cgc = this._chunks.get(chunk); + if (cgc === undefined) { + cgc = new ChunkGraphChunk(); + this._chunks.set(chunk, cgc); + } + return cgc; + } -/***/ }), + /** + * @param {SortableSet} set the sortable Set to get the roots of + * @returns {Module[]} the graph roots + */ + _getGraphRoots(set) { + const { moduleGraph } = this; + return Array.from( + findGraphRoots(set, module => { + /** @type {Set} */ + const set = new Set(); + const addDependencies = module => { + for (const connection of moduleGraph.getOutgoingConnections(module)) { + if (!connection.module) continue; + const activeState = connection.getActiveState(undefined); + if (activeState === false) continue; + if (activeState === ModuleGraphConnection.TRANSITIVE_ONLY) { + addDependencies(connection.module); + continue; + } + set.add(connection.module); + } + }; + addDependencies(module); + return set; + }) + ).sort(compareModulesByIdentifier); + } -/***/ 90552: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {Chunk} chunk the new chunk + * @param {Module} module the module + * @returns {void} + */ + connectChunkAndModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + cgm.chunks.add(chunk); + cgc.modules.add(module); + } -var fs = __webpack_require__(57147) -var polyfills = __webpack_require__(11290) -var legacy = __webpack_require__(54410) -var clone = __webpack_require__(89132) + /** + * @param {Chunk} chunk the chunk + * @param {Module} module the module + * @returns {void} + */ + disconnectChunkAndModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + cgc.modules.delete(module); + cgm.chunks.delete(chunk); + } -var util = __webpack_require__(73837) + /** + * @param {Chunk} chunk the chunk which will be disconnected + * @returns {void} + */ + disconnectChunk(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + for (const module of cgc.modules) { + const cgm = this._getChunkGraphModule(module); + cgm.chunks.delete(chunk); + } + cgc.modules.clear(); + chunk.disconnectFromGroups(); + ChunkGraph.clearChunkGraphForChunk(chunk); + } -/* istanbul ignore next - node 0.x polyfill */ -var gracefulQueue -var previousSymbol + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} modules the modules + * @returns {void} + */ + attachModules(chunk, modules) { + const cgc = this._getChunkGraphChunk(chunk); + for (const module of modules) { + cgc.modules.add(module); + } + } -/* istanbul ignore else - node 0.x polyfill */ -if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { - gracefulQueue = Symbol.for('graceful-fs.queue') - // This is used in testing by future versions - previousSymbol = Symbol.for('graceful-fs.previous') -} else { - gracefulQueue = '___graceful-fs.queue' - previousSymbol = '___graceful-fs.previous' -} + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} modules the runtime modules + * @returns {void} + */ + attachRuntimeModules(chunk, modules) { + const cgc = this._getChunkGraphChunk(chunk); + for (const module of modules) { + cgc.runtimeModules.add(module); + } + } -function noop () {} + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} modules the modules that require a full hash + * @returns {void} + */ + attachFullHashModules(chunk, modules) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.fullHashModules === undefined) cgc.fullHashModules = new Set(); + for (const module of modules) { + cgc.fullHashModules.add(module); + } + } -function publishQueue(context, queue) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue - } - }) -} + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} modules the modules that require a full hash + * @returns {void} + */ + attachDependentHashModules(chunk, modules) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.dependentHashModules === undefined) + cgc.dependentHashModules = new Set(); + for (const module of modules) { + cgc.dependentHashModules.add(module); + } + } -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } + /** + * @param {Module} oldModule the replaced module + * @param {Module} newModule the replacing module + * @returns {void} + */ + replaceModule(oldModule, newModule) { + const oldCgm = this._getChunkGraphModule(oldModule); + const newCgm = this._getChunkGraphModule(newModule); -// Once time initialization -if (!fs[gracefulQueue]) { - // This queue can be shared by multiple loaded instances - var queue = global[gracefulQueue] || [] - publishQueue(fs, queue) + for (const chunk of oldCgm.chunks) { + const cgc = this._getChunkGraphChunk(chunk); + cgc.modules.delete(oldModule); + cgc.modules.add(newModule); + newCgm.chunks.add(chunk); + } + oldCgm.chunks.clear(); - // Patch fs.close/closeSync to shared queue version, because we need - // to retry() whenever a close happens *anywhere* in the program. - // This is essential when multiple graceful-fs instances are - // in play at the same time. - fs.close = (function (fs$close) { - function close (fd, cb) { - return fs$close.call(fs, fd, function (err) { - // This function uses the graceful-fs shared queue - if (!err) { - resetQueue() - } + if (oldCgm.entryInChunks !== undefined) { + if (newCgm.entryInChunks === undefined) { + newCgm.entryInChunks = new Set(); + } + for (const chunk of oldCgm.entryInChunks) { + const cgc = this._getChunkGraphChunk(chunk); + const old = cgc.entryModules.get(oldModule); + /** @type {Map} */ + const newEntryModules = new Map(); + for (const [m, cg] of cgc.entryModules) { + if (m === oldModule) { + newEntryModules.set(newModule, old); + } else { + newEntryModules.set(m, cg); + } + } + cgc.entryModules = newEntryModules; + newCgm.entryInChunks.add(chunk); + } + oldCgm.entryInChunks = undefined; + } - if (typeof cb === 'function') - cb.apply(this, arguments) - }) - } + if (oldCgm.runtimeInChunks !== undefined) { + if (newCgm.runtimeInChunks === undefined) { + newCgm.runtimeInChunks = new Set(); + } + for (const chunk of oldCgm.runtimeInChunks) { + const cgc = this._getChunkGraphChunk(chunk); + cgc.runtimeModules.delete(/** @type {RuntimeModule} */ (oldModule)); + cgc.runtimeModules.add(/** @type {RuntimeModule} */ (newModule)); + newCgm.runtimeInChunks.add(chunk); + if ( + cgc.fullHashModules !== undefined && + cgc.fullHashModules.has(/** @type {RuntimeModule} */ (oldModule)) + ) { + cgc.fullHashModules.delete(/** @type {RuntimeModule} */ (oldModule)); + cgc.fullHashModules.add(/** @type {RuntimeModule} */ (newModule)); + } + if ( + cgc.dependentHashModules !== undefined && + cgc.dependentHashModules.has(/** @type {RuntimeModule} */ (oldModule)) + ) { + cgc.dependentHashModules.delete( + /** @type {RuntimeModule} */ (oldModule) + ); + cgc.dependentHashModules.add( + /** @type {RuntimeModule} */ (newModule) + ); + } + } + oldCgm.runtimeInChunks = undefined; + } + } - Object.defineProperty(close, previousSymbol, { - value: fs$close - }) - return close - })(fs.close) + /** + * @param {Module} module the checked module + * @param {Chunk} chunk the checked chunk + * @returns {boolean} true, if the chunk contains the module + */ + isModuleInChunk(module, chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.has(module); + } - fs.closeSync = (function (fs$closeSync) { - function closeSync (fd) { - // This function uses the graceful-fs shared queue - fs$closeSync.apply(fs, arguments) - resetQueue() - } + /** + * @param {Module} module the checked module + * @param {ChunkGroup} chunkGroup the checked chunk group + * @returns {boolean} true, if the chunk contains the module + */ + isModuleInChunkGroup(module, chunkGroup) { + for (const chunk of chunkGroup.chunks) { + if (this.isModuleInChunk(module, chunk)) return true; + } + return false; + } - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }) - return closeSync - })(fs.closeSync) + /** + * @param {Module} module the checked module + * @returns {boolean} true, if the module is entry of any chunk + */ + isEntryModule(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.entryInChunks !== undefined; + } - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(fs[gracefulQueue]) - __webpack_require__(39491).equal(fs[gracefulQueue].length, 0) - }) - } -} + /** + * @param {Module} module the module + * @returns {Iterable} iterable of chunks (do not modify) + */ + getModuleChunksIterable(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.chunks; + } -if (!global[gracefulQueue]) { - publishQueue(global, fs[gracefulQueue]); -} + /** + * @param {Module} module the module + * @param {function(Chunk, Chunk): -1|0|1} sortFn sort function + * @returns {Iterable} iterable of chunks (do not modify) + */ + getOrderedModuleChunksIterable(module, sortFn) { + const cgm = this._getChunkGraphModule(module); + cgm.chunks.sortWith(sortFn); + return cgm.chunks; + } -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} + /** + * @param {Module} module the module + * @returns {Chunk[]} array of chunks (cached, do not modify) + */ + getModuleChunks(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.chunks.getFromCache(getArray); + } -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch + /** + * @param {Module} module the module + * @returns {number} the number of chunk which contain the module + */ + getNumberOfModuleChunks(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.chunks.size; + } - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null + /** + * @param {Module} module the module + * @returns {RuntimeSpecSet} runtimes + */ + getModuleRuntimes(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.chunks.getFromUnorderedCache(getModuleRuntimes); + } - return go$readFile(path, options, cb) + /** + * @param {Chunk} chunk the chunk + * @returns {number} the number of modules which are contained in this chunk + */ + getNumberOfChunkModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.size; + } - function go$readFile (path, options, cb, startTime) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + /** + * @param {Chunk} chunk the chunk + * @returns {number} the number of full hash modules which are contained in this chunk + */ + getNumberOfChunkFullHashModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.fullHashModules === undefined ? 0 : cgc.fullHashModules.size; + } - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} return the modules for this chunk + */ + getChunkModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules; + } - return go$writeFile(path, data, options, cb) + /** + * @param {Chunk} chunk the chunk + * @param {string} sourceType source type + * @returns {Iterable | undefined} return the modules for this chunk + */ + getChunkModulesIterableBySourceType(chunk, sourceType) { + const cgc = this._getChunkGraphChunk(chunk); + const modulesWithSourceType = cgc.modules + .getFromUnorderedCache(modulesBySourceType) + .get(sourceType); + return modulesWithSourceType; + } - function go$writeFile (path, data, options, cb, startTime) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + /** + * @param {Chunk} chunk the chunk + * @param {function(Module, Module): -1|0|1} comparator comparator function + * @returns {Iterable} return the modules for this chunk + */ + getOrderedChunkModulesIterable(chunk, comparator) { + const cgc = this._getChunkGraphChunk(chunk); + cgc.modules.sortWith(comparator); + return cgc.modules; + } - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + /** + * @param {Chunk} chunk the chunk + * @param {string} sourceType source type + * @param {function(Module, Module): -1|0|1} comparator comparator function + * @returns {Iterable | undefined} return the modules for this chunk + */ + getOrderedChunkModulesIterableBySourceType(chunk, sourceType, comparator) { + const cgc = this._getChunkGraphChunk(chunk); + const modulesWithSourceType = cgc.modules + .getFromUnorderedCache(modulesBySourceType) + .get(sourceType); + if (modulesWithSourceType === undefined) return undefined; + modulesWithSourceType.sortWith(comparator); + return modulesWithSourceType; + } - return go$appendFile(path, data, options, cb) + /** + * @param {Chunk} chunk the chunk + * @returns {Module[]} return the modules for this chunk (cached, do not modify) + */ + getChunkModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.getFromUnorderedCache(getArray); + } - function go$appendFile (path, data, options, cb, startTime) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + /** + * @param {Chunk} chunk the chunk + * @param {function(Module, Module): -1|0|1} comparator comparator function + * @returns {Module[]} return the modules for this chunk (cached, do not modify) + */ + getOrderedChunkModules(chunk, comparator) { + const cgc = this._getChunkGraphChunk(chunk); + const arrayFunction = createOrderedArrayFunction(comparator); + return cgc.modules.getFromUnorderedCache(arrayFunction); + } - var fs$copyFile = fs.copyFile - if (fs$copyFile) - fs.copyFile = copyFile - function copyFile (src, dest, flags, cb) { - if (typeof flags === 'function') { - cb = flags - flags = 0 - } - return go$copyFile(src, dest, flags, cb) - - function go$copyFile (src, dest, flags, cb, startTime) { - return fs$copyFile(src, dest, flags, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } - - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null + /** + * @param {Chunk} chunk the chunk + * @param {ModuleFilterPredicate} filterFn function used to filter modules + * @param {boolean} includeAllChunks all chunks or only async chunks + * @returns {Record} chunk to module ids object + */ + getChunkModuleIdMap(chunk, filterFn, includeAllChunks = false) { + /** @type {Record} */ + const chunkModuleIdMap = Object.create(null); - return go$readdir(path, options, cb) + for (const asyncChunk of includeAllChunks + ? chunk.getAllReferencedChunks() + : chunk.getAllAsyncChunks()) { + /** @type {(string|number)[]} */ + let array; + for (const module of this.getOrderedChunkModulesIterable( + asyncChunk, + compareModulesById(this) + )) { + if (filterFn(module)) { + if (array === undefined) { + array = []; + chunkModuleIdMap[asyncChunk.id] = array; + } + const moduleId = this.getModuleId(module); + array.push(moduleId); + } + } + } - function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, options, function (err, files) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (files && files.sort) - files.sort() + return chunkModuleIdMap; + } - if (typeof cb === 'function') - cb.call(this, err, files) - } - }) - } - } + /** + * @param {Chunk} chunk the chunk + * @param {ModuleFilterPredicate} filterFn function used to filter modules + * @param {number} hashLength length of the hash + * @param {boolean} includeAllChunks all chunks or only async chunks + * @returns {Record>} chunk to module id to module hash object + */ + getChunkModuleRenderedHashMap( + chunk, + filterFn, + hashLength = 0, + includeAllChunks = false + ) { + /** @type {Record>} */ + const chunkModuleHashMap = Object.create(null); - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } + for (const asyncChunk of includeAllChunks + ? chunk.getAllReferencedChunks() + : chunk.getAllAsyncChunks()) { + /** @type {Record} */ + let idToHashMap; + for (const module of this.getOrderedChunkModulesIterable( + asyncChunk, + compareModulesById(this) + )) { + if (filterFn(module)) { + if (idToHashMap === undefined) { + idToHashMap = Object.create(null); + chunkModuleHashMap[asyncChunk.id] = idToHashMap; + } + const moduleId = this.getModuleId(module); + const hash = this.getRenderedModuleHash(module, asyncChunk.runtime); + idToHashMap[moduleId] = hashLength ? hash.slice(0, hashLength) : hash; + } + } + } - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } + return chunkModuleHashMap; + } - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } + /** + * @param {Chunk} chunk the chunk + * @param {ChunkFilterPredicate} filterFn function used to filter chunks + * @returns {Record} chunk map + */ + getChunkConditionMap(chunk, filterFn) { + const map = Object.create(null); + for (const c of chunk.getAllReferencedChunks()) { + map[c.id] = filterFn(c, this); + } + return map; + } - Object.defineProperty(fs, 'ReadStream', { - get: function () { - return ReadStream - }, - set: function (val) { - ReadStream = val - }, - enumerable: true, - configurable: true - }) - Object.defineProperty(fs, 'WriteStream', { - get: function () { - return WriteStream - }, - set: function (val) { - WriteStream = val - }, - enumerable: true, - configurable: true - }) + /** + * @param {Chunk} chunk the chunk + * @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(chunk, filterFn, filterChunkFn) { + const queue = new Set(chunk.groupsIterable); + const chunksProcessed = new Set(); - // legacy names - var FileReadStream = ReadStream - Object.defineProperty(fs, 'FileReadStream', { - get: function () { - return FileReadStream - }, - set: function (val) { - FileReadStream = val - }, - enumerable: true, - configurable: true - }) - var FileWriteStream = WriteStream - Object.defineProperty(fs, 'FileWriteStream', { - get: function () { - return FileWriteStream - }, - set: function (val) { - FileWriteStream = val - }, - enumerable: true, - configurable: true - }) + for (const chunkGroup of queue) { + for (const innerChunk of chunkGroup.chunks) { + if (!chunksProcessed.has(innerChunk)) { + chunksProcessed.add(innerChunk); + if (!filterChunkFn || filterChunkFn(innerChunk, this)) { + for (const module of this.getChunkModulesIterable(innerChunk)) { + if (filterFn(module)) { + return true; + } + } + } + } + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + return false; + } - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } + /** + * @param {Chunk} chunkA first chunk + * @param {Chunk} chunkB second chunk + * @returns {-1|0|1} this is a comparator function like sort and returns -1, 0, or 1 based on sort order + */ + compareChunks(chunkA, chunkB) { + const cgcA = this._getChunkGraphChunk(chunkA); + const cgcB = this._getChunkGraphChunk(chunkB); + if (cgcA.modules.size > cgcB.modules.size) return -1; + if (cgcA.modules.size < cgcB.modules.size) return 1; + cgcA.modules.sortWith(compareModulesByIdentifier); + cgcB.modules.sortWith(compareModulesByIdentifier); + return compareModuleIterables(cgcA.modules, cgcB.modules); + } - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() + /** + * @param {Chunk} chunk the chunk + * @returns {number} total size of all modules in the chunk + */ + getChunkModulesSize(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.getFromUnorderedCache(getModulesSize); + } - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } + /** + * @param {Chunk} chunk the chunk + * @returns {Record} total sizes of all modules in the chunk by source type + */ + getChunkModulesSizes(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.getFromUnorderedCache(getModulesSizes); + } - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } + /** + * @param {Chunk} chunk the chunk + * @returns {Module[]} root modules of the chunks (ordered by identifier) + */ + getChunkRootModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.modules.getFromUnorderedCache(this._getGraphRoots); + } - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } + /** + * @param {Chunk} chunk the chunk + * @param {ChunkSizeOptions} options options object + * @returns {number} total size of the chunk + */ + getChunkSize(chunk, options = {}) { + const cgc = this._getChunkGraphChunk(chunk); + const modulesSize = cgc.modules.getFromUnorderedCache(getModulesSize); + const chunkOverhead = + typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; + const entryChunkMultiplicator = + typeof options.entryChunkMultiplicator === "number" + ? options.entryChunkMultiplicator + : 10; + return ( + chunkOverhead + + modulesSize * (chunk.canBeInitial() ? entryChunkMultiplicator : 1) + ); + } - function createReadStream (path, options) { - return new fs.ReadStream(path, options) - } + /** + * @param {Chunk} chunkA chunk + * @param {Chunk} chunkB chunk + * @param {ChunkSizeOptions} options options object + * @returns {number} total size of the chunk or false if chunks can't be integrated + */ + getIntegratedChunksSize(chunkA, chunkB, options = {}) { + const cgcA = this._getChunkGraphChunk(chunkA); + const cgcB = this._getChunkGraphChunk(chunkB); + const allModules = new Set(cgcA.modules); + for (const m of cgcB.modules) allModules.add(m); + let modulesSize = getModulesSize(allModules); + const chunkOverhead = + typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; + const entryChunkMultiplicator = + typeof options.entryChunkMultiplicator === "number" + ? options.entryChunkMultiplicator + : 10; + return ( + chunkOverhead + + modulesSize * + (chunkA.canBeInitial() || chunkB.canBeInitial() + ? entryChunkMultiplicator + : 1) + ); + } - function createWriteStream (path, options) { - return new fs.WriteStream(path, options) - } + /** + * @param {Chunk} chunkA chunk + * @param {Chunk} chunkB chunk + * @returns {boolean} true, if chunks could be integrated + */ + canChunksBeIntegrated(chunkA, chunkB) { + if (chunkA.preventIntegration || chunkB.preventIntegration) { + return false; + } - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null + const hasRuntimeA = chunkA.hasRuntime(); + const hasRuntimeB = chunkB.hasRuntime(); - return go$open(path, flags, mode, cb) + if (hasRuntimeA !== hasRuntimeB) { + if (hasRuntimeA) { + return isAvailableChunk(chunkA, chunkB); + } else if (hasRuntimeB) { + return isAvailableChunk(chunkB, chunkA); + } else { + return false; + } + } - function go$open (path, flags, mode, cb, startTime) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } + if ( + this.getNumberOfEntryModules(chunkA) > 0 || + this.getNumberOfEntryModules(chunkB) > 0 + ) { + return false; + } - return fs -} + return true; + } -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - fs[gracefulQueue].push(elem) - retry() -} + /** + * @param {Chunk} chunkA the target chunk + * @param {Chunk} chunkB the chunk to integrate + * @returns {void} + */ + integrateChunks(chunkA, chunkB) { + // Decide for one name (deterministic) + if (chunkA.name && chunkB.name) { + if ( + this.getNumberOfEntryModules(chunkA) > 0 === + this.getNumberOfEntryModules(chunkB) > 0 + ) { + // When both chunks have entry modules or none have one, use + // shortest name + if (chunkA.name.length !== chunkB.name.length) { + chunkA.name = + chunkA.name.length < chunkB.name.length ? chunkA.name : chunkB.name; + } else { + chunkA.name = chunkA.name < chunkB.name ? chunkA.name : chunkB.name; + } + } else if (this.getNumberOfEntryModules(chunkB) > 0) { + // Pick the name of the chunk with the entry module + chunkA.name = chunkB.name; + } + } else if (chunkB.name) { + chunkA.name = chunkB.name; + } -// keep track of the timeout between retry() calls -var retryTimer + // Merge id name hints + for (const hint of chunkB.idNameHints) { + chunkA.idNameHints.add(hint); + } -// reset the startTime and lastTime to now -// this resets the start of the 60 second overall timeout as well as the -// delay between attempts so that we'll retry these jobs sooner -function resetQueue () { - var now = Date.now() - for (var i = 0; i < fs[gracefulQueue].length; ++i) { - // entries that are only a length of 2 are from an older version, don't - // bother modifying those since they'll be retried anyway. - if (fs[gracefulQueue][i].length > 2) { - fs[gracefulQueue][i][3] = now // startTime - fs[gracefulQueue][i][4] = now // lastTime - } - } - // call retry to make sure we're actively processing the queue - retry() -} + // Merge runtime + chunkA.runtime = mergeRuntime(chunkA.runtime, chunkB.runtime); -function retry () { - // clear the timer and remove it to help prevent unintended concurrency - clearTimeout(retryTimer) - retryTimer = undefined + // getChunkModules is used here to create a clone, because disconnectChunkAndModule modifies + for (const module of this.getChunkModules(chunkB)) { + this.disconnectChunkAndModule(chunkB, module); + this.connectChunkAndModule(chunkA, module); + } - if (fs[gracefulQueue].length === 0) - return + for (const [module, chunkGroup] of Array.from( + this.getChunkEntryModulesWithChunkGroupIterable(chunkB) + )) { + this.disconnectChunkAndEntryModule(chunkB, module); + this.connectChunkAndEntryModule(chunkA, module, chunkGroup); + } - var elem = fs[gracefulQueue].shift() - var fn = elem[0] - var args = elem[1] - // these items may be unset if they were added by an older graceful-fs - var err = elem[2] - var startTime = elem[3] - var lastTime = elem[4] + for (const chunkGroup of chunkB.groupsIterable) { + chunkGroup.replaceChunk(chunkB, chunkA); + chunkA.addGroup(chunkGroup); + chunkB.removeGroup(chunkGroup); + } + ChunkGraph.clearChunkGraphForChunk(chunkB); + } - // if we don't have a startTime we have no way of knowing if we've waited - // long enough, so go ahead and retry this item now - if (startTime === undefined) { - debug('RETRY', fn.name, args) - fn.apply(null, args) - } else if (Date.now() - startTime >= 60000) { - // it's been more than 60 seconds total, bail now - debug('TIMEOUT', fn.name, args) - var cb = args.pop() - if (typeof cb === 'function') - cb.call(null, err) - } else { - // the amount of time between the last attempt and right now - var sinceAttempt = Date.now() - lastTime - // the amount of time between when we first tried, and when we last tried - // rounded up to at least 1 - var sinceStart = Math.max(lastTime - startTime, 1) - // backoff. wait longer than the total time we've been retrying, but only - // up to a maximum of 100ms - var desiredDelay = Math.min(sinceStart * 1.2, 100) - // it's been long enough since the last retry, do it again - if (sinceAttempt >= desiredDelay) { - debug('RETRY', fn.name, args) - fn.apply(null, args.concat([startTime])) - } else { - // if we can't do this job yet, push it to the end of the queue - // and let the next iteration check again - fs[gracefulQueue].push(elem) - } - } + /** + * @param {Chunk} chunk the chunk to upgrade + * @returns {void} + */ + upgradeDependentToFullHashModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.dependentHashModules === undefined) return; + if (cgc.fullHashModules === undefined) { + cgc.fullHashModules = cgc.dependentHashModules; + } else { + for (const m of cgc.dependentHashModules) { + cgc.fullHashModules.add(m); + } + cgc.dependentHashModules = undefined; + } + } - // schedule our next run if one isn't already scheduled - if (retryTimer === undefined) { - retryTimer = setTimeout(retry, 0) - } -} + /** + * @param {Module} module the checked module + * @param {Chunk} chunk the checked chunk + * @returns {boolean} true, if the chunk contains the module as entry + */ + isEntryModuleInChunk(module, chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.entryModules.has(module); + } + /** + * @param {Chunk} chunk the new chunk + * @param {Module} module the entry module + * @param {Entrypoint=} entrypoint the chunk group which must be loaded before the module is executed + * @returns {void} + */ + connectChunkAndEntryModule(chunk, module, entrypoint) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + if (cgm.entryInChunks === undefined) { + cgm.entryInChunks = new Set(); + } + cgm.entryInChunks.add(chunk); + cgc.entryModules.set(module, entrypoint); + } -/***/ }), + /** + * @param {Chunk} chunk the new chunk + * @param {RuntimeModule} module the runtime module + * @returns {void} + */ + connectChunkAndRuntimeModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + if (cgm.runtimeInChunks === undefined) { + cgm.runtimeInChunks = new Set(); + } + cgm.runtimeInChunks.add(chunk); + cgc.runtimeModules.add(module); + } -/***/ 54410: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {Chunk} chunk the new chunk + * @param {RuntimeModule} module the module that require a full hash + * @returns {void} + */ + addFullHashModuleToChunk(chunk, module) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.fullHashModules === undefined) cgc.fullHashModules = new Set(); + cgc.fullHashModules.add(module); + } -var Stream = (__webpack_require__(12781).Stream) + /** + * @param {Chunk} chunk the new chunk + * @param {RuntimeModule} module the module that require a full hash + * @returns {void} + */ + addDependentHashModuleToChunk(chunk, module) { + const cgc = this._getChunkGraphChunk(chunk); + if (cgc.dependentHashModules === undefined) + cgc.dependentHashModules = new Set(); + cgc.dependentHashModules.add(module); + } -module.exports = legacy + /** + * @param {Chunk} chunk the new chunk + * @param {Module} module the entry module + * @returns {void} + */ + disconnectChunkAndEntryModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + cgm.entryInChunks.delete(chunk); + if (cgm.entryInChunks.size === 0) { + cgm.entryInChunks = undefined; + } + cgc.entryModules.delete(module); + } -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } + /** + * @param {Chunk} chunk the new chunk + * @param {RuntimeModule} module the runtime module + * @returns {void} + */ + disconnectChunkAndRuntimeModule(chunk, module) { + const cgm = this._getChunkGraphModule(module); + const cgc = this._getChunkGraphChunk(chunk); + cgm.runtimeInChunks.delete(chunk); + if (cgm.runtimeInChunks.size === 0) { + cgm.runtimeInChunks = undefined; + } + cgc.runtimeModules.delete(module); + } - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); + /** + * @param {Module} module the entry module, it will no longer be entry + * @returns {void} + */ + disconnectEntryModule(module) { + const cgm = this._getChunkGraphModule(module); + for (const chunk of cgm.entryInChunks) { + const cgc = this._getChunkGraphChunk(chunk); + cgc.entryModules.delete(module); + } + cgm.entryInChunks = undefined; + } - Stream.call(this); + /** + * @param {Chunk} chunk the chunk, for which all entries will be removed + * @returns {void} + */ + disconnectEntries(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + for (const module of cgc.entryModules.keys()) { + const cgm = this._getChunkGraphModule(module); + cgm.entryInChunks.delete(chunk); + if (cgm.entryInChunks.size === 0) { + cgm.entryInChunks = undefined; + } + } + cgc.entryModules.clear(); + } - var self = this; + /** + * @param {Chunk} chunk the chunk + * @returns {number} the amount of entry modules in chunk + */ + getNumberOfEntryModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.entryModules.size; + } - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; + /** + * @param {Chunk} chunk the chunk + * @returns {number} the amount of entry modules in chunk + */ + getNumberOfRuntimeModules(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.runtimeModules.size; + } - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of modules (do not modify) + */ + getChunkEntryModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.entryModules.keys(); + } - options = options || {}; + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of chunks + */ + getChunkEntryDependentChunksIterable(chunk) { + /** @type {Set} */ + const set = new Set(); + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup instanceof Entrypoint) { + const entrypointChunk = chunkGroup.getEntrypointChunk(); + const cgc = this._getChunkGraphChunk(entrypointChunk); + for (const chunkGroup of cgc.entryModules.values()) { + for (const c of chunkGroup.chunks) { + if (c !== chunk && c !== entrypointChunk && !c.hasRuntime()) { + set.add(c); + } + } + } + } + } - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } + return set; + } - if (this.encoding) this.setEncoding(this.encoding); + /** + * @param {Chunk} chunk the chunk + * @returns {boolean} true, when it has dependent chunks + */ + hasChunkEntryDependentChunks(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + for (const chunkGroup of cgc.entryModules.values()) { + for (const c of chunkGroup.chunks) { + if (c !== chunk) { + return true; + } + } + } + return false; + } - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of modules (do not modify) + */ + getChunkRuntimeModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.runtimeModules; + } - if (this.start > this.end) { - throw new Error('start must be <= end'); - } + /** + * @param {Chunk} chunk the chunk + * @returns {RuntimeModule[]} array of modules in order of execution + */ + getChunkRuntimeModulesInOrder(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + const array = Array.from(cgc.runtimeModules); + array.sort( + concatComparators( + compareSelect( + /** + * @param {RuntimeModule} r runtime module + * @returns {number=} stage + */ + r => r.stage, + compareIds + ), + compareModulesByIdentifier + ) + ); + return array; + } - this.pos = this.start; - } + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable | undefined} iterable of modules (do not modify) + */ + getChunkFullHashModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.fullHashModules; + } - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } + /** + * @param {Chunk} chunk the chunk + * @returns {ReadonlySet | undefined} set of modules (do not modify) + */ + getChunkFullHashModulesSet(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.fullHashModules; + } - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable | undefined} iterable of modules (do not modify) + */ + getChunkDependentHashModulesIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.dependentHashModules; + } - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } + /** @typedef {[Module, Entrypoint | undefined]} EntryModuleWithChunkGroup */ - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); + /** + * @param {Chunk} chunk the chunk + * @returns {Iterable} iterable of modules (do not modify) + */ + getChunkEntryModulesWithChunkGroupIterable(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.entryModules; + } - Stream.call(this); + /** + * @param {AsyncDependenciesBlock} depBlock the async block + * @returns {ChunkGroup} the chunk group + */ + getBlockChunkGroup(depBlock) { + return this._blockChunkGroups.get(depBlock); + } - this.path = path; - this.fd = null; - this.writable = true; + /** + * @param {AsyncDependenciesBlock} depBlock the async block + * @param {ChunkGroup} chunkGroup the chunk group + * @returns {void} + */ + connectBlockAndChunkGroup(depBlock, chunkGroup) { + this._blockChunkGroups.set(depBlock, chunkGroup); + chunkGroup.addBlock(depBlock); + } - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; + /** + * @param {ChunkGroup} chunkGroup the chunk group + * @returns {void} + */ + disconnectChunkGroup(chunkGroup) { + for (const block of chunkGroup.blocksIterable) { + this._blockChunkGroups.delete(block); + } + // TODO refactor by moving blocks list into ChunkGraph + chunkGroup._blocks.clear(); + } - options = options || {}; + /** + * @param {Module} module the module + * @returns {string | number} the id of the module + */ + getModuleId(module) { + const cgm = this._getChunkGraphModule(module); + return cgm.id; + } - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } + /** + * @param {Module} module the module + * @param {string | number} id the id of the module + * @returns {void} + */ + setModuleId(module, id) { + const cgm = this._getChunkGraphModule(module); + cgm.id = id; + } - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } + /** + * @param {string} runtime runtime + * @returns {string | number} the id of the runtime + */ + getRuntimeId(runtime) { + return this._runtimeIds.get(runtime); + } - this.pos = this.start; - } + /** + * @param {string} runtime runtime + * @param {string | number} id the id of the runtime + * @returns {void} + */ + setRuntimeId(runtime, id) { + this._runtimeIds.set(runtime, id); + } - this.busy = false; - this._queue = []; + /** + * @template T + * @param {Module} module the module + * @param {RuntimeSpecMap} hashes hashes data + * @param {RuntimeSpec} runtime the runtime + * @returns {T} hash + */ + _getModuleHashInfo(module, hashes, runtime) { + if (!hashes) { + throw new Error( + `Module ${module.identifier()} has no hash info for runtime ${runtimeToString( + runtime + )} (hashes not set at all)` + ); + } else if (runtime === undefined) { + const hashInfoItems = new Set(hashes.values()); + if (hashInfoItems.size !== 1) { + throw new Error( + `No unique hash info entry for unspecified runtime for ${module.identifier()} (existing runtimes: ${Array.from( + hashes.keys(), + r => runtimeToString(r) + ).join(", ")}). +Caller might not support runtime-dependent code generation (opt-out via optimization.usedExports: "global").` + ); + } + return first(hashInfoItems); + } else { + const hashInfo = hashes.get(runtime); + if (!hashInfo) { + throw new Error( + `Module ${module.identifier()} has no hash info for runtime ${runtimeToString( + runtime + )} (available runtimes ${Array.from( + hashes.keys(), + runtimeToString + ).join(", ")})` + ); + } + return hashInfo; + } + } - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } - } -} + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, if the module has hashes for this runtime + */ + hasModuleHashes(module, runtime) { + const cgm = this._getChunkGraphModule(module); + const hashes = cgm.hashes; + return hashes && hashes.has(runtime); + } + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {string} hash + */ + getModuleHash(module, runtime) { + const cgm = this._getChunkGraphModule(module); + const hashes = cgm.hashes; + return this._getModuleHashInfo(module, hashes, runtime).hash; + } -/***/ }), + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {string} hash + */ + getRenderedModuleHash(module, runtime) { + const cgm = this._getChunkGraphModule(module); + const hashes = cgm.hashes; + return this._getModuleHashInfo(module, hashes, runtime).renderedHash; + } -/***/ 11290: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @param {string} hash the full hash + * @param {string} renderedHash the shortened hash for rendering + * @returns {void} + */ + setModuleHashes(module, runtime, hash, renderedHash) { + const cgm = this._getChunkGraphModule(module); + if (cgm.hashes === undefined) { + cgm.hashes = new RuntimeSpecMap(); + } + cgm.hashes.set(runtime, new ModuleHashInfo(hash, renderedHash)); + } -var constants = __webpack_require__(22057) + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @param {Set} items runtime requirements to be added (ownership of this Set is given to ChunkGraph when transferOwnership not false) + * @param {boolean} transferOwnership true: transfer ownership of the items object, false: items is immutable and shared and won't be modified + * @returns {void} + */ + addModuleRuntimeRequirements( + module, + runtime, + items, + transferOwnership = true + ) { + const cgm = this._getChunkGraphModule(module); + const runtimeRequirementsMap = cgm.runtimeRequirements; + if (runtimeRequirementsMap === undefined) { + const map = new RuntimeSpecMap(); + // TODO avoid cloning item and track ownership instead + map.set(runtime, transferOwnership ? items : new Set(items)); + cgm.runtimeRequirements = map; + return; + } + runtimeRequirementsMap.update(runtime, runtimeRequirements => { + if (runtimeRequirements === undefined) { + return transferOwnership ? items : new Set(items); + } else if (!transferOwnership || runtimeRequirements.size >= items.size) { + for (const item of items) runtimeRequirements.add(item); + return runtimeRequirements; + } else { + for (const item of runtimeRequirements) items.add(item); + return items; + } + }); + } -var origCwd = process.cwd -var cwd = null - -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + /** + * @param {Chunk} chunk the chunk + * @param {Set} items runtime requirements to be added (ownership of this Set is given to ChunkGraph) + * @returns {void} + */ + addChunkRuntimeRequirements(chunk, items) { + const cgc = this._getChunkGraphChunk(chunk); + const runtimeRequirements = cgc.runtimeRequirements; + if (runtimeRequirements === undefined) { + cgc.runtimeRequirements = items; + } else if (runtimeRequirements.size >= items.size) { + for (const item of items) runtimeRequirements.add(item); + } else { + for (const item of runtimeRequirements) items.add(item); + cgc.runtimeRequirements = items; + } + } -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} + /** + * @param {Chunk} chunk the chunk + * @param {Iterable} items runtime requirements to be added + * @returns {void} + */ + addTreeRuntimeRequirements(chunk, items) { + const cgc = this._getChunkGraphChunk(chunk); + const runtimeRequirements = cgc.runtimeRequirementsInTree; + for (const item of items) runtimeRequirements.add(item); + } -// This check is needed until node.js 12 is required -if (typeof process.chdir === 'function') { - var chdir = process.chdir - process.chdir = function (d) { - cwd = null - chdir.call(process, d) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) -} + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {ReadonlySet} runtime requirements + */ + getModuleRuntimeRequirements(module, runtime) { + const cgm = this._getChunkGraphModule(module); + const runtimeRequirements = + cgm.runtimeRequirements && cgm.runtimeRequirements.get(runtime); + return runtimeRequirements === undefined ? EMPTY_SET : runtimeRequirements; + } -module.exports = patch + /** + * @param {Chunk} chunk the chunk + * @returns {ReadonlySet} runtime requirements + */ + getChunkRuntimeRequirements(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + const runtimeRequirements = cgc.runtimeRequirements; + return runtimeRequirements === undefined ? EMPTY_SET : runtimeRequirements; + } -function patch (fs) { - // (re-)implement some things that are known busted or missing. + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @param {boolean} withConnections include connections + * @returns {string} hash + */ + getModuleGraphHash(module, runtime, withConnections = true) { + const cgm = this._getChunkGraphModule(module); + return withConnections + ? this._getModuleGraphHashWithConnections(cgm, module, runtime) + : this._getModuleGraphHashBigInt(cgm, module, runtime).toString(16); + } - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @param {boolean} withConnections include connections + * @returns {bigint} hash + */ + getModuleGraphHashBigInt(module, runtime, withConnections = true) { + const cgm = this._getChunkGraphModule(module); + return withConnections + ? BigInt( + `0x${this._getModuleGraphHashWithConnections(cgm, module, runtime)}` + ) + : this._getModuleGraphHashBigInt(cgm, module, runtime); + } - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } + /** + * @param {ChunkGraphModule} cgm the ChunkGraphModule + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {bigint} hash as big int + */ + _getModuleGraphHashBigInt(cgm, module, runtime) { + if (cgm.graphHashes === undefined) { + cgm.graphHashes = new RuntimeSpecMap(); + } + const graphHash = cgm.graphHashes.provide(runtime, () => { + const hash = createHash(this._hashFunction); + hash.update(`${cgm.id}${this.moduleGraph.isAsync(module)}`); + this.moduleGraph.getExportsInfo(module).updateHash(hash, runtime); + return BigInt(`0x${/** @type {string} */ (hash.digest("hex"))}`); + }); + return graphHash; + } - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. + /** + * @param {ChunkGraphModule} cgm the ChunkGraphModule + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {string} hash + */ + _getModuleGraphHashWithConnections(cgm, module, runtime) { + if (cgm.graphHashesWithConnections === undefined) { + cgm.graphHashesWithConnections = new RuntimeSpecMap(); + } + const activeStateToString = state => { + if (state === false) return "F"; + if (state === true) return "T"; + if (state === ModuleGraphConnection.TRANSITIVE_ONLY) return "O"; + throw new Error("Not implemented active state"); + }; + const strict = module.buildMeta && module.buildMeta.strictHarmonyModule; + return cgm.graphHashesWithConnections.provide(runtime, () => { + const graphHash = this._getModuleGraphHashBigInt( + cgm, + module, + runtime + ).toString(16); + const connections = this.moduleGraph.getOutgoingConnections(module); + /** @type {Set} */ + const activeNamespaceModules = new Set(); + /** @type {Map>} */ + const connectedModules = new Map(); + const processConnection = (connection, stateInfo) => { + const module = connection.module; + stateInfo += module.getExportsType(this.moduleGraph, strict); + // cspell:word Tnamespace + if (stateInfo === "Tnamespace") activeNamespaceModules.add(module); + else { + const oldModule = connectedModules.get(stateInfo); + if (oldModule === undefined) { + connectedModules.set(stateInfo, module); + } else if (oldModule instanceof Set) { + oldModule.add(module); + } else if (oldModule !== module) { + connectedModules.set(stateInfo, new Set([oldModule, module])); + } + } + }; + if (runtime === undefined || typeof runtime === "string") { + for (const connection of connections) { + const state = connection.getActiveState(runtime); + if (state === false) continue; + processConnection(connection, state === true ? "T" : "O"); + } + } else { + // cspell:word Tnamespace + for (const connection of connections) { + const states = new Set(); + let stateInfo = ""; + forEachRuntime( + runtime, + runtime => { + const state = connection.getActiveState(runtime); + states.add(state); + stateInfo += activeStateToString(state) + runtime; + }, + true + ); + if (states.size === 1) { + const state = first(states); + if (state === false) continue; + stateInfo = activeStateToString(state); + } + processConnection(connection, stateInfo); + } + } + // cspell:word Tnamespace + if (activeNamespaceModules.size === 0 && connectedModules.size === 0) + return graphHash; + const connectedModulesInOrder = + connectedModules.size > 1 + ? Array.from(connectedModules).sort(([a], [b]) => (a < b ? -1 : 1)) + : connectedModules; + const hash = createHash(this._hashFunction); + const addModuleToHash = module => { + hash.update( + this._getModuleGraphHashBigInt( + this._getChunkGraphModule(module), + module, + runtime + ).toString(16) + ); + }; + const addModulesToHash = modules => { + let xor = ZERO_BIG_INT; + for (const m of modules) { + xor = + xor ^ + this._getModuleGraphHashBigInt( + this._getChunkGraphModule(m), + m, + runtime + ); + } + hash.update(xor.toString(16)); + }; + if (activeNamespaceModules.size === 1) + addModuleToHash(activeNamespaceModules.values().next().value); + else if (activeNamespaceModules.size > 1) + addModulesToHash(activeNamespaceModules); + for (const [stateInfo, modules] of connectedModulesInOrder) { + hash.update(stateInfo); + if (modules instanceof Set) { + addModulesToHash(modules); + } else { + addModuleToHash(modules); + } + } + hash.update(graphHash); + return /** @type {string} */ (hash.digest("hex")); + }); + } - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) + /** + * @param {Chunk} chunk the chunk + * @returns {ReadonlySet} runtime requirements + */ + getTreeRuntimeRequirements(chunk) { + const cgc = this._getChunkGraphChunk(chunk); + return cgc.runtimeRequirementsInTree; + } - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) + // 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 {ChunkGraph} the chunk graph + */ + static getChunkGraphForModule(module, deprecateMessage, deprecationCode) { + const fn = deprecateGetChunkGraphForModuleMap.get(deprecateMessage); + if (fn) return fn(module); + const newFn = util.deprecate( + /** + * @param {Module} module the module + * @returns {ChunkGraph} the chunk graph + */ + module => { + const chunkGraph = chunkGraphForModuleMap.get(module); + if (!chunkGraph) + throw new Error( + deprecateMessage + + ": There was no ChunkGraph assigned to the Module for backward-compat (Use the new API)" + ); + return chunkGraph; + }, + deprecateMessage + ": Use new ChunkGraph API", + deprecationCode + ); + deprecateGetChunkGraphForModuleMap.set(deprecateMessage, newFn); + return newFn(module); + } - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) + // TODO remove in webpack 6 + /** + * @param {Module} module the module + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} + */ + static setChunkGraphForModule(module, chunkGraph) { + chunkGraphForModuleMap.set(module, chunkGraph); + } - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) + // TODO remove in webpack 6 + /** + * @param {Module} module the module + * @returns {void} + */ + static clearChunkGraphForModule(module) { + chunkGraphForModuleMap.delete(module); + } - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) + // TODO remove in webpack 6 + /** + * @param {Chunk} chunk the chunk + * @param {string} deprecateMessage message for the deprecation message + * @param {string} deprecationCode code for the deprecation + * @returns {ChunkGraph} the chunk graph + */ + static getChunkGraphForChunk(chunk, deprecateMessage, deprecationCode) { + const fn = deprecateGetChunkGraphForChunkMap.get(deprecateMessage); + if (fn) return fn(chunk); + const newFn = util.deprecate( + /** + * @param {Chunk} chunk the chunk + * @returns {ChunkGraph} the chunk graph + */ + chunk => { + const chunkGraph = chunkGraphForChunkMap.get(chunk); + if (!chunkGraph) + throw new Error( + deprecateMessage + + "There was no ChunkGraph assigned to the Chunk for backward-compat (Use the new API)" + ); + return chunkGraph; + }, + deprecateMessage + ": Use new ChunkGraph API", + deprecationCode + ); + deprecateGetChunkGraphForChunkMap.set(deprecateMessage, newFn); + return newFn(chunk); + } - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) + // TODO remove in webpack 6 + /** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} + */ + static setChunkGraphForChunk(chunk, chunkGraph) { + chunkGraphForChunkMap.set(chunk, chunkGraph); + } - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } + // TODO remove in webpack 6 + /** + * @param {Chunk} chunk the chunk + * @returns {void} + */ + static clearChunkGraphForChunk(chunk) { + chunkGraphForChunkMap.delete(chunk); + } +} - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. +// TODO remove in webpack 6 +/** @type {WeakMap} */ +const chunkGraphForModuleMap = new WeakMap(); - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) - } +// TODO remove in webpack 6 +/** @type {WeakMap} */ +const chunkGraphForChunkMap = new WeakMap(); - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } +// TODO remove in webpack 6 +/** @type {Map ChunkGraph>} */ +const deprecateGetChunkGraphForModuleMap = new Map(); - // This ensures `util.promisify` works as it does for native `fs.read`. - if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) - return read - })(fs.read) +// TODO remove in webpack 6 +/** @type {Map ChunkGraph>} */ +const deprecateGetChunkGraphForChunkMap = new Map(); - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) +module.exports = ChunkGraph; - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) +/***/ }), - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } +/***/ 15626: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +const util = __webpack_require__(73837); +const SortableSet = __webpack_require__(13098); +const { + compareLocations, + compareChunks, + compareIterables +} = __webpack_require__(29579); - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } +/** @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 */ - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +/** + * @typedef {Object} RawChunkGroupOptions + * @property {number=} preloadOrder + * @property {number=} prefetchOrder + */ - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } +/** @typedef {RawChunkGroupOptions & { name?: string }} ChunkGroupOptions */ - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) - } - } +let debugId = 5000; - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - return stats; - } - } +/** + * @template T + * @param {SortableSet} set set to convert to array. + * @returns {T[]} the array format of existing set + */ +const getArray = set => Array.from(set); - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true +/** + * 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; +}; - if (er.code === "ENOSYS") - return true +/** + * @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); +}; - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } +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} */ + this._children = new SortableSet(undefined, sortById); + /** @type {SortableSet} */ + this._parents = new SortableSet(undefined, sortById); + /** @type {SortableSet} */ + 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} */ + this._modulePreOrderIndices = new Map(); + /** Indices in bottom-up order */ + /** @private @type {Map} */ + this._modulePostOrderIndices = new Map(); + /** @type {number} */ + this.index = undefined; + } - return false - } -} + /** + * 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; + } -/***/ 15235: -/***/ (function(module) { + /* 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("+"); + } -"use strict"; + /** + * 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; + } -module.exports = parseJson -function parseJson (txt, reviver, context) { - context = context || 20 - try { - return JSON.parse(txt, reviver) - } catch (e) { - if (typeof txt !== 'string') { - const isEmptyArray = Array.isArray(txt) && txt.length === 0 - const errorMessage = 'Cannot parse ' + - (isEmptyArray ? 'an empty array' : String(txt)) - throw new TypeError(errorMessage) - } - const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) - const errIdx = syntaxErr - ? +syntaxErr[1] - : e.message.match(/^Unexpected end of JSON.*/i) - ? txt.length - 1 - : null - if (errIdx != null) { - const start = errIdx <= context - ? 0 - : errIdx - context - const end = errIdx + context >= txt.length - ? txt.length - : errIdx + context - e.message += ` while parsing near '${ - start === 0 ? '' : '...' - }${txt.slice(start, end)}${ - end === txt.length ? '' : '...' - }'` - } else { - e.message += ` while parsing '${txt.slice(0, context * 2)}'` - } - throw e - } -} + /** + * 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; + } + } -/***/ 49448: -/***/ (function(module) { + /** + * @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; + } -"use strict"; + /** + * @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; + } -class LoadingLoaderError extends Error { - constructor(message) { - super(message); - this.name = "LoaderRunnerError"; - Error.captureStackTrace(this, this.constructor); + /** + * @returns {ChunkGroup[]} returns the children of this group + */ + getChildren() { + return this._children.getFromCache(getArray); } -} -module.exports = LoadingLoaderError; + 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; + } -/***/ 68318: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + this._children.delete(group); + group.removeParent(this); + return true; + } -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -var fs = __webpack_require__(57147); -var readFile = fs.readFile.bind(fs); -var loadLoader = __webpack_require__(55102); + /** + * @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; + } -function utf8BufferToString(buf) { - var str = buf.toString("utf-8"); - if(str.charCodeAt(0) === 0xFEFF) { - return str.substr(1); - } else { - return str; + /** + * @returns {ChunkGroup[]} returns the parents of this group + */ + getParents() { + return this._parents.getFromCache(getArray); } -} -const PATH_QUERY_FRAGMENT_REGEXP = /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; + getNumberOfParents() { + return this._parents.size; + } -/** - * @param {string} str the path with query and fragment - * @returns {{ path: string, query: string, fragment: string }} parsed parts - */ -function parsePathQueryFragment(str) { - var match = PATH_QUERY_FRAGMENT_REGEXP.exec(str); - return { - path: match[1].replace(/\0(.)/g, "$1"), - query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "", - fragment: match[3] || "" - }; -} + /** + * @param {ChunkGroup} parent the parent group + * @returns {boolean} returns true if the parent group contains this group + */ + hasParent(parent) { + return this._parents.has(parent); + } -function dirname(path) { - if(path === "/") return "/"; - var i = path.lastIndexOf("/"); - var j = path.lastIndexOf("\\"); - var i2 = path.indexOf("/"); - var j2 = path.indexOf("\\"); - var idx = i > j ? i : j; - var idx2 = i > j ? i2 : j2; - if(idx < 0) return path; - if(idx === idx2) return path.substr(0, idx + 1); - return path.substr(0, idx); -} + get parentsIterable() { + return this._parents; + } -function createLoaderObject(loader) { - var obj = { - path: null, - query: null, - fragment: null, - options: null, - ident: null, - normal: null, - pitch: null, - raw: null, - data: null, - pitchExecuted: false, - normalExecuted: false - }; - Object.defineProperty(obj, "request", { - enumerable: true, - get: function() { - return obj.path.replace(/#/g, "\0#") + obj.query.replace(/#/g, "\0#") + obj.fragment; - }, - set: function(value) { - if(typeof value === "string") { - var splittedRequest = parsePathQueryFragment(value); - obj.path = splittedRequest.path; - obj.query = splittedRequest.query; - obj.fragment = splittedRequest.fragment; - obj.options = undefined; - obj.ident = undefined; - } else { - if(!value.loader) - throw new Error("request should be a string or object with loader and options (" + JSON.stringify(value) + ")"); - obj.path = value.loader; - obj.fragment = value.fragment || ""; - obj.type = value.type; - obj.options = value.options; - obj.ident = value.ident; - if(obj.options === null) - obj.query = ""; - else if(obj.options === undefined) - obj.query = ""; - else if(typeof obj.options === "string") - obj.query = "?" + obj.options; - else if(obj.ident) - obj.query = "??" + obj.ident; - else if(typeof obj.options === "object" && obj.options.ident) - obj.query = "??" + obj.options.ident; - else - obj.query = "?" + JSON.stringify(obj.options); - } + /** + * @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; } - }); - obj.request = loader; - if(Object.preventExtensions) { - Object.preventExtensions(obj); + return false; } - return obj; -} -function runSyncOrAsync(fn, context, args, callback) { - var isSync = true; - var isDone = false; - var isError = false; // internal error - var reportedError = false; - context.async = function async() { - if(isDone) { - if(reportedError) return; // ignore - throw new Error("async(): The callback was already called."); - } - isSync = false; - return innerCallback; - }; - var innerCallback = context.callback = function() { - if(isDone) { - if(reportedError) return; // ignore - throw new Error("callback(): The callback was already called."); - } - isDone = true; - isSync = false; - try { - callback.apply(null, arguments); - } catch(e) { - isError = true; - throw e; - } - }; - try { - var result = (function LOADER_EXECUTION() { - return fn.apply(context, args); - }()); - if(isSync) { - isDone = true; - if(result === undefined) - return callback(); - if(result && typeof result === "object" && typeof result.then === "function") { - return result.then(function(r) { - callback(null, r); - }, callback); - } - return callback(null, result); - } - } catch(e) { - if(isError) throw e; - if(isDone) { - // loader is already "done", so we cannot use the callback function - // for better debugging we print the error on the console - if(typeof e === "object" && e.stack) console.error(e.stack); - else console.error(e); - return; - } - isDone = true; - reportedError = true; - callback(e); + /** + * @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; + } -function convertArgs(args, raw) { - if(!raw && Buffer.isBuffer(args[0])) - args[0] = utf8BufferToString(args[0]); - else if(raw && typeof args[0] === "string") - args[0] = Buffer.from(args[0], "utf-8"); -} + /** + * @returns {Array} an array containing the blocks + */ + getBlocks() { + return this._blocks.getFromCache(getArray); + } -function iteratePitchingLoaders(options, loaderContext, callback) { - // abort after last loader - if(loaderContext.loaderIndex >= loaderContext.loaders.length) - return processResource(options, loaderContext, callback); + getNumberOfBlocks() { + return this._blocks.size; + } - var currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex]; + hasBlock(block) { + return this._blocks.has(block); + } - // iterate - if(currentLoaderObject.pitchExecuted) { - loaderContext.loaderIndex++; - return iteratePitchingLoaders(options, loaderContext, callback); + /** + * @returns {Iterable} blocks + */ + get blocksIterable() { + return this._blocks; } - // load loader module - loadLoader(currentLoaderObject, function(err) { - if(err) { - loaderContext.cacheable(false); - return callback(err); + /** + * @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; } - var fn = currentLoaderObject.pitch; - currentLoaderObject.pitchExecuted = true; - if(!fn) return iteratePitchingLoaders(options, loaderContext, callback); - - runSyncOrAsync( - fn, - loaderContext, [loaderContext.remainingRequest, loaderContext.previousRequest, currentLoaderObject.data = {}], - function(err) { - if(err) return callback(err); - var args = Array.prototype.slice.call(arguments, 1); - // Determine whether to continue the pitching process based on - // argument values (as opposed to argument presence) in order - // to support synchronous and asynchronous usages. - var hasArg = args.some(function(value) { - return value !== undefined; - }); - if(hasArg) { - loaderContext.loaderIndex--; - iterateNormalLoaders(options, loaderContext, args, callback); - } else { - iteratePitchingLoaders(options, loaderContext, callback); - } - } - ); - }); -} - -function processResource(options, loaderContext, callback) { - // set loader index to last loader - loaderContext.loaderIndex = loaderContext.loaders.length - 1; + return false; + } - var resourcePath = loaderContext.resourcePath; - if(resourcePath) { - options.processResource(loaderContext, resourcePath, function(err, buffer) { - if(err) return callback(err); - options.resourceBuffer = buffer; - iterateNormalLoaders(options, loaderContext, [buffer], callback); + /** + * @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 }); - } else { - iterateNormalLoaders(options, loaderContext, [null], callback); } -} - -function iterateNormalLoaders(options, loaderContext, args, callback) { - if(loaderContext.loaderIndex < 0) - return callback(null, args); - var currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex]; + /** + * @returns {string[]} the files contained this chunk group + */ + getFiles() { + const files = new Set(); - // iterate - if(currentLoaderObject.normalExecuted) { - loaderContext.loaderIndex--; - return iterateNormalLoaders(options, loaderContext, args, callback); - } + for (const chunk of this.chunks) { + for (const file of chunk.files) { + files.add(file); + } + } - var fn = currentLoaderObject.normal; - currentLoaderObject.normalExecuted = true; - if(!fn) { - return iterateNormalLoaders(options, loaderContext, args, callback); + return Array.from(files); } - convertArgs(args, currentLoaderObject.raw); - - runSyncOrAsync(fn, loaderContext, args, function(err) { - if(err) return callback(err); - - var args = Array.prototype.slice.call(arguments, 1); - iterateNormalLoaders(options, loaderContext, args, callback); - }); -} - -exports.getContext = function getContext(resource) { - var path = parsePathQueryFragment(resource).path; - return dirname(path); -}; - -exports.runLoaders = function runLoaders(options, callback) { - // read options - var resource = options.resource || ""; - var loaders = options.loaders || []; - var loaderContext = options.context || {}; - var processResource = options.processResource || ((readResource, context, resource, callback) => { - context.addDependency(resource); - readResource(resource, callback); - }).bind(null, options.readResource || readFile); - - // - var splittedResource = resource && parsePathQueryFragment(resource); - var resourcePath = splittedResource ? splittedResource.path : undefined; - var resourceQuery = splittedResource ? splittedResource.query : undefined; - var resourceFragment = splittedResource ? splittedResource.fragment : undefined; - var contextDirectory = resourcePath ? dirname(resourcePath) : null; - - // execution state - var requestCacheable = true; - var fileDependencies = []; - var contextDependencies = []; - var missingDependencies = []; - - // prepare loader objects - loaders = loaders.map(createLoaderObject); + /** + * @returns {void} + */ + remove() { + // cleanup parents + for (const parentChunkGroup of this._parents) { + // remove this chunk from its parents + parentChunkGroup._children.delete(this); - loaderContext.context = contextDirectory; - loaderContext.loaderIndex = 0; - loaderContext.loaders = loaders; - loaderContext.resourcePath = resourcePath; - loaderContext.resourceQuery = resourceQuery; - loaderContext.resourceFragment = resourceFragment; - loaderContext.async = null; - loaderContext.callback = null; - loaderContext.cacheable = function cacheable(flag) { - if(flag === false) { - requestCacheable = false; - } - }; - loaderContext.dependency = loaderContext.addDependency = function addDependency(file) { - fileDependencies.push(file); - }; - loaderContext.addContextDependency = function addContextDependency(context) { - contextDependencies.push(context); - }; - loaderContext.addMissingDependency = function addMissingDependency(context) { - missingDependencies.push(context); - }; - loaderContext.getDependencies = function getDependencies() { - return fileDependencies.slice(); - }; - loaderContext.getContextDependencies = function getContextDependencies() { - return contextDependencies.slice(); - }; - loaderContext.getMissingDependencies = function getMissingDependencies() { - return missingDependencies.slice(); - }; - loaderContext.clearDependencies = function clearDependencies() { - fileDependencies.length = 0; - contextDependencies.length = 0; - missingDependencies.length = 0; - requestCacheable = true; - }; - Object.defineProperty(loaderContext, "resource", { - enumerable: true, - get: function() { - if(loaderContext.resourcePath === undefined) - return undefined; - return loaderContext.resourcePath.replace(/#/g, "\0#") + loaderContext.resourceQuery.replace(/#/g, "\0#") + loaderContext.resourceFragment; - }, - set: function(value) { - var splittedResource = value && parsePathQueryFragment(value); - loaderContext.resourcePath = splittedResource ? splittedResource.path : undefined; - loaderContext.resourceQuery = splittedResource ? splittedResource.query : undefined; - loaderContext.resourceFragment = splittedResource ? splittedResource.fragment : undefined; - } - }); - Object.defineProperty(loaderContext, "request", { - enumerable: true, - get: function() { - return loaderContext.loaders.map(function(o) { - return o.request; - }).concat(loaderContext.resource || "").join("!"); - } - }); - Object.defineProperty(loaderContext, "remainingRequest", { - enumerable: true, - get: function() { - if(loaderContext.loaderIndex >= loaderContext.loaders.length - 1 && !loaderContext.resource) - return ""; - return loaderContext.loaders.slice(loaderContext.loaderIndex + 1).map(function(o) { - return o.request; - }).concat(loaderContext.resource || "").join("!"); - } - }); - Object.defineProperty(loaderContext, "currentRequest", { - enumerable: true, - get: function() { - return loaderContext.loaders.slice(loaderContext.loaderIndex).map(function(o) { - return o.request; - }).concat(loaderContext.resource || "").join("!"); - } - }); - Object.defineProperty(loaderContext, "previousRequest", { - enumerable: true, - get: function() { - return loaderContext.loaders.slice(0, loaderContext.loaderIndex).map(function(o) { - return o.request; - }).join("!"); + // 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); + } } - }); - Object.defineProperty(loaderContext, "query", { - enumerable: true, - get: function() { - var entry = loaderContext.loaders[loaderContext.loaderIndex]; - return entry.options && typeof entry.options === "object" ? entry.options : entry.query; + + /** + * 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); } - }); - Object.defineProperty(loaderContext, "data", { - enumerable: true, - get: function() { - return loaderContext.loaders[loaderContext.loaderIndex].data; + + // remove chunks + for (const chunk of this.chunks) { + chunk.removeGroup(this); } - }); + } - // finish loader context - if(Object.preventExtensions) { - Object.preventExtensions(loaderContext); + sortItems() { + this.origins.sort(sortOrigin); } - var processOptions = { - resourceBuffer: null, - processResource: processResource - }; - iteratePitchingLoaders(processOptions, loaderContext, function(err, result) { - if(err) { - return callback(err, { - cacheable: requestCacheable, - fileDependencies: fileDependencies, - contextDependencies: contextDependencies, - missingDependencies: missingDependencies + /** + * 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} mapping from children type to ordered list of ChunkGroups + */ + getChildrenByOrders(moduleGraph, chunkGraph) { + /** @type {Map} */ + 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} */ + 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); } - callback(null, { - result: result, - resourceBuffer: processOptions.resourceBuffer, - cacheable: requestCacheable, - fileDependencies: fileDependencies, - contextDependencies: contextDependencies, - missingDependencies: missingDependencies - }); - }); -}; + 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); + } -/***/ 55102: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * 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); + } -var LoaderLoadingError = __webpack_require__(49448); -var url; + /** + * 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); + } -module.exports = function loadLoader(loader, callback) { - if(loader.type === "module") { - try { - if(url === undefined) url = __webpack_require__(57310); - var loaderUrl = url.pathToFileURL(loader.path); - var modulePromise = eval("import(" + JSON.stringify(loaderUrl.toString()) + ")"); - modulePromise.then(function(module) { - handleResult(loader, module, callback); - }, callback); - return; - } catch(e) { - callback(e); + /* 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}` + ); + } } - } else { - try { - var module = require(loader.path); - } catch(e) { - // it is possible for node to choke on a require if the FD descriptor - // limit has been reached. give it a chance to recover. - if(e instanceof Error && e.code === "EMFILE") { - var retry = loadLoader.bind(null, loader, callback); - if(typeof setImmediate === "function") { - // node >= 0.9.0 - return setImmediate(retry); - } else { - // node < 0.9.0 - return process.nextTick(retry); - } + for (const parentChunk of chunk._parents) { + if (!parentChunk._children.has(chunk)) { + throw new Error( + `checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}` + ); } - return callback(e); } - return handleResult(loader, module, callback); - } -}; - -function handleResult(loader, module, callback) { - if(typeof module !== "function" && typeof module !== "object") { - return callback(new LoaderLoadingError( - "Module '" + loader.path + "' is not a loader (export function or es6 module)" - )); - } - loader.normal = typeof module === "function" ? module : module.default; - loader.pitch = module.pitch; - loader.raw = module.raw; - if(typeof loader.normal !== "function" && typeof loader.pitch !== "function") { - return callback(new LoaderLoadingError( - "Module '" + loader.path + "' is not a loader (must have normal or pitch function)" - )); } - callback(); } +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" +); -/***/ 54983: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +module.exports = ChunkGroup; -"use strict"; -var __webpack_unused_export__; +/***/ }), -__webpack_unused_export__ = ({ - value: true -}); -exports.Z = void 0; +/***/ 918: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const { - stringHints, - numberHints -} = __webpack_require__(79926); -/** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */ -/** @typedef {import("./validate").Schema} Schema */ -/** @typedef {import("./validate").ValidationErrorConfiguration} ValidationErrorConfiguration */ +const WebpackError = __webpack_require__(53799); -/** @typedef {import("./validate").PostFormatter} PostFormatter */ +/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./validate").SchemaUtilErrorObject} SchemaUtilErrorObject */ +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(); -/** @enum {number} */ + this.name = "ChunkRenderError"; + this.error = error; + this.message = error.message; + this.details = error.stack; + this.file = file; + this.chunk = chunk; + } +} +module.exports = ChunkRenderError; -const SPECIFICITY = { - type: 1, - not: 1, - oneOf: 1, - anyOf: 1, - if: 1, - enum: 1, - const: 1, - instanceof: 1, - required: 2, - pattern: 2, - patternRequired: 2, - format: 2, - formatMinimum: 2, - formatMaximum: 2, - minimum: 2, - exclusiveMinimum: 2, - maximum: 2, - exclusiveMaximum: 2, - multipleOf: 2, - uniqueItems: 2, - contains: 2, - minLength: 2, - maxLength: 2, - minItems: 2, - maxItems: 2, - minProperties: 2, - maxProperties: 2, - dependencies: 2, - propertyNames: 2, - additionalItems: 2, - additionalProperties: 2, - absolutePath: 2 -}; -/** - * - * @param {Array} array - * @param {(item: SchemaUtilErrorObject) => number} fn - * @returns {Array} - */ -function filterMax(array, fn) { - const evaluatedMax = array.reduce((max, item) => Math.max(max, fn(item)), 0); - return array.filter(item => fn(item) === evaluatedMax); -} -/** - * - * @param {Array} children - * @returns {Array} - */ +/***/ }), +/***/ 46341: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -function filterChildren(children) { - let newChildren = children; - newChildren = filterMax(newChildren, - /** - * - * @param {SchemaUtilErrorObject} error - * @returns {number} - */ - error => error.dataPath ? error.dataPath.length : 0); - newChildren = filterMax(newChildren, - /** - * @param {SchemaUtilErrorObject} error - * @returns {number} - */ - error => SPECIFICITY[ - /** @type {keyof typeof SPECIFICITY} */ - error.keyword] || 2); - return newChildren; -} -/** - * Find all children errors - * @param {Array} children - * @param {Array} schemaPaths - * @return {number} returns index of first child - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -function findAllChildren(children, schemaPaths) { - let i = children.length - 1; - const predicate = - /** - * @param {string} schemaPath - * @returns {boolean} - */ - schemaPath => children[i].schemaPath.indexOf(schemaPath) !== 0; +const util = __webpack_require__(73837); +const memoize = __webpack_require__(78676); - while (i > -1 && !schemaPaths.every(predicate)) { - if (children[i].keyword === "anyOf" || children[i].keyword === "oneOf") { - const refs = extractRefs(children[i]); - const childrenStart = findAllChildren(children.slice(0, i), refs.concat(children[i].schemaPath)); - i = childrenStart - 1; - } else { - i -= 1; - } - } +/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */ +/** @typedef {import("./Compilation")} Compilation */ - return i + 1; +const getJavascriptModulesPlugin = memoize(() => + __webpack_require__(89464) +); + +// 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" + ) + } + }); + } } -/** - * Extracts all refs from schema - * @param {SchemaUtilErrorObject} error - * @return {Array} - */ +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" + ) +}); -function extractRefs(error) { - const { - schema - } = error; +module.exports = ChunkTemplate; - if (!Array.isArray(schema)) { - return []; - } - return schema.map(({ - $ref - }) => $ref).filter(s => s); -} -/** - * Groups children by their first level parent (assuming that error is root) - * @param {Array} children - * @return {Array} - */ +/***/ }), +/***/ 31085: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -function groupChildrenByFirstChild(children) { - const result = []; - let i = children.length - 1; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ - while (i > 0) { - const child = children[i]; - if (child.keyword === "anyOf" || child.keyword === "oneOf") { - const refs = extractRefs(child); - const childrenStart = findAllChildren(children.slice(0, i), refs.concat(child.schemaPath)); - if (childrenStart !== i) { - result.push(Object.assign({}, child, { - children: children.slice(childrenStart, i) - })); - i = childrenStart; - } else { - result.push(child); - } - } else { - result.push(child); - } +const asyncLib = __webpack_require__(78175); +const { SyncBailHook } = __webpack_require__(6967); +const Compilation = __webpack_require__(85720); +const createSchemaValidation = __webpack_require__(32540); +const { join } = __webpack_require__(17139); +const processAsyncTree = __webpack_require__(42791); - i -= 1; - } +/** @typedef {import("../declarations/WebpackOptions").CleanOptions} CleanOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./logging/Logger").Logger} Logger */ +/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ +/** @typedef {import("./util/fs").StatsCallback} StatsCallback */ - if (i === 0) { - result.push(children[i]); - } +/** @typedef {(function(string):boolean)|RegExp} IgnoreItem */ +/** @typedef {function(IgnoreItem): void} AddToIgnoreCallback */ - return result.reverse(); -} /** - * @param {string} str - * @param {string} prefix - * @returns {string} + * @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 validate = createSchemaValidation( + undefined, + () => { + const { definitions } = __webpack_require__(73342); + return { + definitions, + oneOf: [{ $ref: "#/definitions/CleanOptions" }] + }; + }, + { + name: "Clean Plugin", + baseDataPath: "options" + } +); -function indent(str, prefix) { - return str.replace(/\n(?!$)/g, `\n${prefix}`); -} /** - * @param {Schema} schema - * @returns {schema is (Schema & {not: Schema})} + * @param {OutputFileSystem} fs filesystem + * @param {string} outputPath output path + * @param {Set} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator) + * @param {function((Error | null)=, Set=): 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); + } + ); +}; -function hasNotInSchema(schema) { - return !!schema.not; -} /** - * @param {Schema} schema - * @return {Schema} + * @param {Set} currentAssets assets list + * @param {Set} oldAssets old assets list + * @returns {Set} diff */ +const getDiffToOldAssets = (currentAssets, oldAssets) => { + const diff = new Set(); + for (const asset of oldAssets) { + if (!currentAssets.has(asset)) diff.add(asset); + } + return diff; +}; - -function findFirstTypedSchema(schema) { - if (hasNotInSchema(schema)) { - return findFirstTypedSchema(schema.not); - } - - return schema; -} /** - * @param {Schema} schema - * @return {boolean} + * @param {OutputFileSystem} fs filesystem + * @param {string} filename path to file + * @param {StatsCallback} callback callback for provided filename + * @returns {void} */ +const doStat = (fs, filename, callback) => { + if ("lstat" in fs) { + fs.lstat(filename, callback); + } else { + fs.stat(filename, callback); + } +}; - -function canApplyNot(schema) { - const typedSchema = findFirstTypedSchema(schema); - return likeNumber(typedSchema) || likeInteger(typedSchema) || likeString(typedSchema) || likeNull(typedSchema) || likeBoolean(typedSchema); -} /** - * @param {any} maybeObj - * @returns {boolean} + * @param {OutputFileSystem} fs filesystem + * @param {string} outputPath output path + * @param {boolean} dry only log instead of fs modification + * @param {Logger} logger logger + * @param {Set} 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); + } + doStat(fs, 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} */ +const compilationHooksMap = new WeakMap(); -function isObject(maybeObj) { - return typeof maybeObj === "object" && maybeObj !== null; -} -/** - * @param {Schema} schema - * @returns {boolean} - */ - +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; + } -function likeNumber(schema) { - return schema.type === "number" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; -} -/** - * @param {Schema} schema - * @returns {boolean} - */ + /** @param {CleanOptions} options options */ + constructor(options = {}) { + validate(options); + this.options = { dry: false, ...options }; + } + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { dry, keep } = this.options; -function likeInteger(schema) { - return schema.type === "integer" || typeof schema.minimum !== "undefined" || typeof schema.exclusiveMinimum !== "undefined" || typeof schema.maximum !== "undefined" || typeof schema.exclusiveMaximum !== "undefined" || typeof schema.multipleOf !== "undefined"; -} -/** - * @param {Schema} schema - * @returns {boolean} - */ + 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; -function likeString(schema) { - return schema.type === "string" || typeof schema.minLength !== "undefined" || typeof schema.maxLength !== "undefined" || typeof schema.pattern !== "undefined" || typeof schema.format !== "undefined" || typeof schema.formatMinimum !== "undefined" || typeof schema.formatMaximum !== "undefined"; -} -/** - * @param {Schema} schema - * @returns {boolean} - */ + 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)" + ) + ); + } -function likeBoolean(schema) { - return schema.type === "boolean"; -} -/** - * @param {Schema} schema - * @returns {boolean} - */ + 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, {}); -function likeArray(schema) { - return schema.type === "array" || typeof schema.minItems === "number" || typeof schema.maxItems === "number" || typeof schema.uniqueItems !== "undefined" || typeof schema.items !== "undefined" || typeof schema.additionalItems !== "undefined" || typeof schema.contains !== "undefined"; -} -/** - * @param {Schema & {patternRequired?: Array}} schema - * @returns {boolean} - */ + 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); + }); + }; -function likeObject(schema) { - return schema.type === "object" || typeof schema.minProperties !== "undefined" || typeof schema.maxProperties !== "undefined" || typeof schema.required !== "undefined" || typeof schema.properties !== "undefined" || typeof schema.patternProperties !== "undefined" || typeof schema.additionalProperties !== "undefined" || typeof schema.dependencies !== "undefined" || typeof schema.propertyNames !== "undefined" || typeof schema.patternRequired !== "undefined"; + if (oldAssets) { + diffCallback(null, getDiffToOldAssets(currentAssets, oldAssets)); + } else { + getDiffToFs(fs, outputPath, currentAssets, diffCallback); + } + } + ); + } } -/** - * @param {Schema} schema - * @returns {boolean} - */ - -function likeNull(schema) { - return schema.type === "null"; -} -/** - * @param {string} type - * @returns {string} - */ +module.exports = CleanPlugin; -function getArticle(type) { - if (/^[aeiou]/i.test(type)) { - return "an"; - } +/***/ }), - return "a"; -} -/** - * @param {Schema=} schema - * @returns {string} - */ +/***/ 2102: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -function getSchemaNonTypes(schema) { - if (!schema) { - return ""; - } - if (!schema.type) { - if (likeNumber(schema) || likeInteger(schema)) { - return " | should be any non-number"; - } - if (likeString(schema)) { - return " | should be any non-string"; - } +const WebpackError = __webpack_require__(53799); - if (likeArray(schema)) { - return " | should be any non-array"; - } +/** @typedef {import("./Module")} Module */ - if (likeObject(schema)) { - return " | should be any non-object"; - } - } +class CodeGenerationError extends WebpackError { + /** + * Create a new CodeGenerationError + * @param {Module} module related module + * @param {Error} error Original error + */ + constructor(module, error) { + super(); - return ""; + this.name = "CodeGenerationError"; + this.error = error; + this.message = error.message; + this.details = error.stack; + this.module = module; + } } -/** - * @param {Array} hints - * @returns {string} - */ - -function formatHints(hints) { - return hints.length > 0 ? `(${hints.join(", ")})` : ""; -} -/** - * @param {Schema} schema - * @param {boolean} logic - * @returns {string[]} - */ +module.exports = CodeGenerationError; -function getHints(schema, logic) { - if (likeNumber(schema) || likeInteger(schema)) { - return numberHints(schema, logic); - } else if (likeString(schema)) { - return stringHints(schema, logic); - } +/***/ }), - return []; -} +/***/ 71426: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -class ValidationError extends Error { - /** - * @param {Array} errors - * @param {Schema} schema - * @param {ValidationErrorConfiguration} configuration - */ - constructor(errors, schema, configuration = {}) { - super(); - /** @type {string} */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - this.name = "ValidationError"; - /** @type {Array} */ - this.errors = errors; - /** @type {Schema} */ - this.schema = schema; - let headerNameFromSchema; - let baseDataPathFromSchema; +const { provide } = __webpack_require__(82482); +const { first } = __webpack_require__(93347); +const createHash = __webpack_require__(49835); +const { runtimeToString, RuntimeSpecMap } = __webpack_require__(17156); - if (schema.title && (!configuration.name || !configuration.baseDataPath)) { - const splittedTitleFromSchema = schema.title.match(/^(.+) (.+)$/); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {typeof import("./util/Hash")} Hash */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ - if (splittedTitleFromSchema) { - if (!configuration.name) { - [, headerNameFromSchema] = splittedTitleFromSchema; - } +class CodeGenerationResults { + /** + * @param {string | Hash} hashFunction the hash function to use + */ + constructor(hashFunction = "md4") { + /** @type {Map>} */ + this.map = new Map(); + this._hashFunction = hashFunction; + } - if (!configuration.baseDataPath) { - [,, baseDataPathFromSchema] = splittedTitleFromSchema; - } - } - } - /** @type {string} */ + /** + * @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; + } + } - this.headerName = configuration.name || headerNameFromSchema || "Object"; - /** @type {string} */ + /** + * @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); + } - this.baseDataPath = configuration.baseDataPath || baseDataPathFromSchema || "configuration"; - /** @type {PostFormatter | null} */ + /** + * @param {Module} module the module + * @param {RuntimeSpec} runtime runtime(s) + * @returns {ReadonlySet} runtime requirements + */ + getRuntimeRequirements(module, runtime) { + return this.get(module, runtime).runtimeRequirements; + } - this.postFormatter = configuration.postFormatter || null; - const header = `Invalid ${this.baseDataPath} object. ${this.headerName} has been initialized using ${getArticle(this.baseDataPath)} ${this.baseDataPath} object that does not match the API schema.\n`; - /** @type {string} */ + /** + * @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); + } - this.message = `${header}${this.formatValidationErrors(errors)}`; - Error.captureStackTrace(this, this.constructor); - } - /** - * @param {string} path - * @returns {Schema} - */ + /** + * @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(this._hashFunction); + 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); + } +} - getSchemaPart(path) { - const newPath = path.split("/"); - let schemaPart = this.schema; +module.exports = CodeGenerationResults; - for (let i = 1; i < newPath.length; i++) { - const inner = schemaPart[ - /** @type {keyof Schema} */ - newPath[i]]; - if (!inner) { - break; - } +/***/ }), - schemaPart = inner; - } +/***/ 98427: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return schemaPart; - } - /** - * @param {Schema} schema - * @param {boolean} logic - * @param {Array} prevSchemas - * @returns {string} - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - formatSchema(schema, logic = true, prevSchemas = []) { - let newLogic = logic; - const formatInnerSchema = - /** - * - * @param {Object} innerSchema - * @param {boolean=} addSelf - * @returns {string} - */ - (innerSchema, addSelf) => { - if (!addSelf) { - return this.formatSchema(innerSchema, newLogic, prevSchemas); - } +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); - if (prevSchemas.includes(innerSchema)) { - return "(recursive)"; - } +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ - return this.formatSchema(innerSchema, newLogic, prevSchemas.concat(schema)); - }; +class CommentCompilationWarning extends WebpackError { + /** + * + * @param {string} message warning message + * @param {DependencyLocation} loc affected lines of code + */ + constructor(message, loc) { + super(message); - if (hasNotInSchema(schema) && !likeObject(schema)) { - if (canApplyNot(schema.not)) { - newLogic = !logic; - return formatInnerSchema(schema.not); - } + this.name = "CommentCompilationWarning"; - const needApplyLogicHere = !schema.not.not; - const prefix = logic ? "" : "non "; - newLogic = !logic; - return needApplyLogicHere ? prefix + formatInnerSchema(schema.not) : formatInnerSchema(schema.not); - } + this.loc = loc; + } +} - if ( - /** @type {Schema & {instanceof: string | Array}} */ - schema.instanceof) { - const { - instanceof: value - } = - /** @type {Schema & {instanceof: string | Array}} */ - schema; - const values = !Array.isArray(value) ? [value] : value; - return values.map( - /** - * @param {string} item - * @returns {string} - */ - item => item === "Function" ? "function" : item).join(" | "); - } +makeSerializable( + CommentCompilationWarning, + "webpack/lib/CommentCompilationWarning" +); - if (schema.enum) { - return ( - /** @type {Array} */ - schema.enum.map(item => JSON.stringify(item)).join(" | ") - ); - } +module.exports = CommentCompilationWarning; - if (typeof schema.const !== "undefined") { - return JSON.stringify(schema.const); - } - if (schema.oneOf) { - return ( - /** @type {Array} */ - schema.oneOf.map(item => formatInnerSchema(item, true)).join(" | ") - ); - } +/***/ }), - if (schema.anyOf) { - return ( - /** @type {Array} */ - schema.anyOf.map(item => formatInnerSchema(item, true)).join(" | ") - ); - } +/***/ 94258: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (schema.allOf) { - return ( - /** @type {Array} */ - schema.allOf.map(item => formatInnerSchema(item, true)).join(" & ") - ); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if ( - /** @type {JSONSchema7} */ - schema.if) { - const { - if: ifValue, - then: thenValue, - else: elseValue - } = - /** @type {JSONSchema7} */ - schema; - return `${ifValue ? `if ${formatInnerSchema(ifValue)}` : ""}${thenValue ? ` then ${formatInnerSchema(thenValue)}` : ""}${elseValue ? ` else ${formatInnerSchema(elseValue)}` : ""}`; - } - if (schema.$ref) { - return formatInnerSchema(this.getSchemaPart(schema.$ref), true); - } - if (likeNumber(schema) || likeInteger(schema)) { - const [type, ...hints] = getHints(schema, logic); - const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; - return logic ? str : hints.length > 0 ? `non-${type} | ${str}` : `non-${type}`; - } +const ConstDependency = __webpack_require__(76911); - if (likeString(schema)) { - const [type, ...hints] = getHints(schema, logic); - const str = `${type}${hints.length > 0 ? ` ${formatHints(hints)}` : ""}`; - return logic ? str : str === "string" ? "non-string" : `non-string | ${str}`; - } +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ - if (likeBoolean(schema)) { - return `${logic ? "" : "non-"}boolean`; - } +const nestedWebpackRequireTag = Symbol("nested __webpack_require__"); - if (likeArray(schema)) { - // not logic already applied in formatValidationError - newLogic = true; - const hints = []; +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() + ); - if (typeof schema.minItems === "number") { - hints.push(`should not have fewer than ${schema.minItems} item${schema.minItems > 1 ? "s" : ""}`); - } + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CompatibilityPlugin", (parser, parserOptions) => { + if ( + parserOptions.browserify !== undefined && + !parserOptions.browserify + ) + return; - if (typeof schema.maxItems === "number") { - hints.push(`should not have more than ${schema.maxItems} item${schema.maxItems > 1 ? "s" : ""}`); - } + 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; + }); + }); - if (schema.uniqueItems) { - hints.push("should not have duplicate items"); - } + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + const handler = parser => { + // Handle nested requires + 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; + }); - const hasAdditionalItems = typeof schema.additionalItems === "undefined" || Boolean(schema.additionalItems); - let items = ""; + // Handle hashbang + parser.hooks.program.tap( + "CompatibilityPlugin", + (program, comments) => { + if (comments.length === 0) return; + const c = comments[0]; + if (c.type === "Line" && c.range[0] === 0) { + if (parser.state.source.slice(0, 2).toString() !== "#!") return; + // this is a hashbang comment + const dep = new ConstDependency("//", 0); + dep.loc = c.loc; + parser.state.module.addPresentationalDependency(dep); + } + } + ); + }; - if (schema.items) { - if (Array.isArray(schema.items) && schema.items.length > 0) { - items = `${ - /** @type {Array} */ - schema.items.map(item => formatInnerSchema(item)).join(", ")}`; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CompatibilityPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("CompatibilityPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("CompatibilityPlugin", handler); + } + ); + } +} +module.exports = CompatibilityPlugin; - if (hasAdditionalItems) { - if (schema.additionalItems && isObject(schema.additionalItems) && Object.keys(schema.additionalItems).length > 0) { - hints.push(`additional items should be ${formatInnerSchema(schema.additionalItems)}`); - } - } - } else if (schema.items && Object.keys(schema.items).length > 0) { - // "additionalItems" is ignored - items = `${formatInnerSchema(schema.items)}`; - } else { - // Fallback for empty `items` value - items = "any"; - } - } else { - // "additionalItems" is ignored - items = "any"; - } - if (schema.contains && Object.keys(schema.contains).length > 0) { - hints.push(`should contains at least one ${this.formatSchema(schema.contains)} item`); - } +/***/ }), - return `[${items}${hasAdditionalItems ? ", ..." : ""}]${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; - } +/***/ 85720: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (likeObject(schema)) { - // not logic already applied in formatValidationError - newLogic = true; - const hints = []; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (typeof schema.minProperties === "number") { - hints.push(`should not have fewer than ${schema.minProperties} ${schema.minProperties > 1 ? "properties" : "property"}`); - } - if (typeof schema.maxProperties === "number") { - hints.push(`should not have more than ${schema.maxProperties} ${schema.minProperties && schema.minProperties > 1 ? "properties" : "property"}`); - } - if (schema.patternProperties && Object.keys(schema.patternProperties).length > 0) { - const patternProperties = Object.keys(schema.patternProperties); - hints.push(`additional property names should match pattern${patternProperties.length > 1 ? "s" : ""} ${patternProperties.map(pattern => JSON.stringify(pattern)).join(" | ")}`); - } +const asyncLib = __webpack_require__(78175); +const { + HookMap, + SyncHook, + SyncBailHook, + SyncWaterfallHook, + AsyncSeriesHook, + AsyncSeriesBailHook, + AsyncParallelHook +} = __webpack_require__(6967); +const util = __webpack_require__(73837); +const { CachedSource } = __webpack_require__(51255); +const { MultiItemCache } = __webpack_require__(55392); +const Chunk = __webpack_require__(39385); +const ChunkGraph = __webpack_require__(64971); +const ChunkGroup = __webpack_require__(15626); +const ChunkRenderError = __webpack_require__(918); +const ChunkTemplate = __webpack_require__(46341); +const CodeGenerationError = __webpack_require__(2102); +const CodeGenerationResults = __webpack_require__(71426); +const Dependency = __webpack_require__(54912); +const DependencyTemplates = __webpack_require__(9163); +const Entrypoint = __webpack_require__(13795); +const ErrorHelpers = __webpack_require__(59985); +const FileSystemInfo = __webpack_require__(79453); +const { + connectChunkGroupAndChunk, + connectChunkGroupParentAndChild +} = __webpack_require__(37234); +const { + makeWebpackError, + tryRunOrWebpackError +} = __webpack_require__(11351); +const MainTemplate = __webpack_require__(12856); +const Module = __webpack_require__(73208); +const ModuleDependencyError = __webpack_require__(67409); +const ModuleDependencyWarning = __webpack_require__(29656); +const ModuleGraph = __webpack_require__(99988); +const ModuleNotFoundError = __webpack_require__(32882); +const ModuleProfile = __webpack_require__(36418); +const ModuleRestoreError = __webpack_require__(94560); +const ModuleStoreError = __webpack_require__(59001); +const ModuleTemplate = __webpack_require__(62677); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeTemplate = __webpack_require__(18777); +const Stats = __webpack_require__(31743); +const WebpackError = __webpack_require__(53799); +const buildChunkGraph = __webpack_require__(79233); +const BuildCycleError = __webpack_require__(22273); +const { Logger, LogType } = __webpack_require__(32597); +const StatsFactory = __webpack_require__(92629); +const StatsPrinter = __webpack_require__(30198); +const { equals: arrayEquals } = __webpack_require__(84953); +const AsyncQueue = __webpack_require__(12260); +const LazySet = __webpack_require__(38938); +const { provide } = __webpack_require__(82482); +const WeakTupleMap = __webpack_require__(28745); +const { cachedCleverMerge } = __webpack_require__(60839); +const { + compareLocations, + concatComparators, + compareSelect, + compareIds, + compareStringsNumeric, + compareModulesByIdentifier +} = __webpack_require__(29579); +const createHash = __webpack_require__(49835); +const { + arrayToSetDeprecation, + soonFrozenObjectDeprecation, + createFakeHook +} = __webpack_require__(64518); +const processAsyncTree = __webpack_require__(42791); +const { getRuntimeKey } = __webpack_require__(17156); +const { isSourceEqual } = __webpack_require__(41245); - const properties = schema.properties ? Object.keys(schema.properties) : []; - const required = schema.required ? schema.required : []; - const allProperties = [...new Set( - /** @type {Array} */ - [].concat(required).concat(properties))]; - const objectStructure = allProperties.map(property => { - const isRequired = required.includes(property); // Some properties need quotes, maybe we should add check - // Maybe we should output type of property (`foo: string`), but it is looks very unreadable +/** @template T @typedef {import("tapable").AsArray} AsArray */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ +/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Cache")} Cache */ +/** @typedef {import("./CacheFacade")} CacheFacade */ +/** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Compiler").CompilationParams} CompilationParams */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ +/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./ModuleFactory")} ModuleFactory */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */ +/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./RuntimeModule")} RuntimeModule */ +/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry */ +/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */ +/** @typedef {import("./util/Hash")} Hash */ +/** @template T @typedef {import("./util/deprecation").FakeHook} FakeHook */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ - return `${property}${isRequired ? "" : "?"}`; - }).concat(typeof schema.additionalProperties === "undefined" || Boolean(schema.additionalProperties) ? schema.additionalProperties && isObject(schema.additionalProperties) ? [`: ${formatInnerSchema(schema.additionalProperties)}`] : ["…"] : []).join(", "); - const { - dependencies, - propertyNames, - patternRequired - } = - /** @type {Schema & {patternRequired?: Array;}} */ - schema; +/** + * @callback Callback + * @param {(WebpackError | null)=} err + * @returns {void} + */ - if (dependencies) { - Object.keys(dependencies).forEach(dependencyName => { - const dependency = dependencies[dependencyName]; +/** + * @callback ModuleCallback + * @param {(WebpackError | null)=} err + * @param {Module=} result + * @returns {void} + */ - if (Array.isArray(dependency)) { - hints.push(`should have ${dependency.length > 1 ? "properties" : "property"} ${dependency.map(dep => `'${dep}'`).join(", ")} when property '${dependencyName}' is present`); - } else { - hints.push(`should be valid according to the schema ${formatInnerSchema(dependency)} when property '${dependencyName}' is present`); - } - }); - } +/** + * @callback ModuleFactoryResultCallback + * @param {(WebpackError | null)=} err + * @param {ModuleFactoryResult=} result + * @returns {void} + */ - if (propertyNames && Object.keys(propertyNames).length > 0) { - hints.push(`each property name should match format ${JSON.stringify(schema.propertyNames.format)}`); - } +/** + * @callback ModuleOrFactoryResultCallback + * @param {(WebpackError | null)=} err + * @param {Module | ModuleFactoryResult=} result + * @returns {void} + */ - if (patternRequired && patternRequired.length > 0) { - hints.push(`should have property matching pattern ${patternRequired.map( - /** - * @param {string} item - * @returns {string} - */ - item => JSON.stringify(item))}`); - } +/** + * @callback ExecuteModuleCallback + * @param {(WebpackError | null)=} err + * @param {ExecuteModuleResult=} result + * @returns {void} + */ - return `object {${objectStructure ? ` ${objectStructure} ` : ""}}${hints.length > 0 ? ` (${hints.join(", ")})` : ""}`; - } +/** + * @callback DepBlockVarDependenciesCallback + * @param {Dependency} dependency + * @returns {any} + */ - if (likeNull(schema)) { - return `${logic ? "" : "non-"}null`; - } +/** @typedef {new (...args: any[]) => Dependency} DepConstructor */ +/** @typedef {Record} CompilationAssets */ - if (Array.isArray(schema.type)) { - // not logic already applied in formatValidationError - return `${schema.type.join(" | ")}`; - } // Fallback for unknown keywords - // not logic already applied in formatValidationError +/** + * @typedef {Object} AvailableModulesChunkGroupMapping + * @property {ChunkGroup} chunkGroup + * @property {Set} availableModules + * @property {boolean} needCopy + */ - /* istanbul ignore next */ +/** + * @typedef {Object} DependenciesBlockLike + * @property {Dependency[]} dependencies + * @property {AsyncDependenciesBlock[]} blocks + */ +/** + * @typedef {Object} ChunkPathData + * @property {string|number} id + * @property {string=} name + * @property {string} hash + * @property {function(number): string=} hashWithLength + * @property {(Record)=} contentHash + * @property {(Record string>)=} contentHashWithLength + */ - return JSON.stringify(schema, null, 2); - } - /** - * @param {Schema=} schemaPart - * @param {(boolean | Array)=} additionalPath - * @param {boolean=} needDot - * @param {boolean=} logic - * @returns {string} - */ +/** + * @typedef {Object} ChunkHashContext + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + */ +/** + * @typedef {Object} RuntimeRequirementsContext + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {CodeGenerationResults} codeGenerationResults the code generation results + */ - getSchemaPartText(schemaPart, additionalPath, needDot = false, logic = true) { - if (!schemaPart) { - return ""; - } +/** + * @typedef {Object} ExecuteModuleOptions + * @property {EntryOptions=} entryOptions + */ - if (Array.isArray(additionalPath)) { - for (let i = 0; i < additionalPath.length; i++) { - /** @type {Schema | undefined} */ - const inner = schemaPart[ - /** @type {keyof Schema} */ - additionalPath[i]]; +/** + * @typedef {Object} ExecuteModuleResult + * @property {any} exports + * @property {boolean} cacheable + * @property {Map} assets + * @property {LazySet} fileDependencies + * @property {LazySet} contextDependencies + * @property {LazySet} missingDependencies + * @property {LazySet} buildDependencies + */ - if (inner) { - // eslint-disable-next-line no-param-reassign - schemaPart = inner; - } else { - break; - } - } - } +/** + * @typedef {Object} ExecuteModuleArgument + * @property {Module} module + * @property {{ id: string, exports: any, loaded: boolean }=} moduleObject + * @property {any} preparedInfo + * @property {CodeGenerationResult} codeGenerationResult + */ - while (schemaPart.$ref) { - // eslint-disable-next-line no-param-reassign - schemaPart = this.getSchemaPart(schemaPart.$ref); - } +/** + * @typedef {Object} ExecuteModuleContext + * @property {Map} assets + * @property {Chunk} chunk + * @property {ChunkGraph} chunkGraph + * @property {function(string): any=} __webpack_require__ + */ - let schemaText = `${this.formatSchema(schemaPart, logic)}${needDot ? "." : ""}`; +/** + * @typedef {Object} EntryData + * @property {Dependency[]} dependencies dependencies of the entrypoint that should be evaluated at startup + * @property {Dependency[]} includeDependencies dependencies of the entrypoint that should be included but not evaluated + * @property {EntryOptions} options options of the entrypoint + */ - if (schemaPart.description) { - schemaText += `\n-> ${schemaPart.description}`; - } +/** + * @typedef {Object} LogEntry + * @property {string} type + * @property {any[]} args + * @property {number} time + * @property {string[]=} trace + */ - if (schemaPart.link) { - schemaText += `\n-> Read more at ${schemaPart.link}`; - } +/** + * @typedef {Object} KnownAssetInfo + * @property {boolean=} immutable true, if the asset can be long term cached forever (contains a hash) + * @property {boolean=} minimized whether the asset is minimized + * @property {string | string[]=} fullhash the value(s) of the full hash used for this asset + * @property {string | string[]=} chunkhash the value(s) of the chunk hash used for this asset + * @property {string | string[]=} modulehash the value(s) of the module hash used for this asset + * @property {string | string[]=} contenthash the value(s) of the content hash used for this asset + * @property {string=} sourceFilename when asset was created from a source file (potentially transformed), the original filename relative to compilation context + * @property {number=} size size in bytes, only set after asset has been emitted + * @property {boolean=} development true, when asset is only used for development and doesn't count towards user-facing assets + * @property {boolean=} hotModuleReplacement true, when asset ships data for updating an existing application (HMR) + * @property {boolean=} javascriptModule true, when asset is javascript and an ESM + * @property {Record=} related object of pointers to other assets, keyed by type of relation (only points from parent to child) + */ - return schemaText; - } - /** - * @param {Schema=} schemaPart - * @returns {string} - */ +/** @typedef {KnownAssetInfo & Record} AssetInfo */ +/** + * @typedef {Object} Asset + * @property {string} name the filename of the asset + * @property {Source} source source of the asset + * @property {AssetInfo} info info about the asset + */ - getSchemaPartDescription(schemaPart) { - if (!schemaPart) { - return ""; - } +/** + * @typedef {Object} ModulePathData + * @property {string|number} id + * @property {string} hash + * @property {function(number): string=} hashWithLength + */ - while (schemaPart.$ref) { - // eslint-disable-next-line no-param-reassign - schemaPart = this.getSchemaPart(schemaPart.$ref); - } +/** + * @typedef {Object} PathData + * @property {ChunkGraph=} chunkGraph + * @property {string=} hash + * @property {function(number): string=} hashWithLength + * @property {(Chunk|ChunkPathData)=} chunk + * @property {(Module|ModulePathData)=} module + * @property {RuntimeSpec=} runtime + * @property {string=} filename + * @property {string=} basename + * @property {string=} query + * @property {string=} contentHashType + * @property {string=} contentHash + * @property {function(number): string=} contentHashWithLength + * @property {boolean=} noChunkHash + * @property {string=} url + */ - let schemaText = ""; +/** + * @typedef {Object} KnownNormalizedStatsOptions + * @property {string} context + * @property {RequestShortener} requestShortener + * @property {string} chunksSort + * @property {string} modulesSort + * @property {string} chunkModulesSort + * @property {string} nestedModulesSort + * @property {string} assetsSort + * @property {boolean} ids + * @property {boolean} cachedAssets + * @property {boolean} groupAssetsByEmitStatus + * @property {boolean} groupAssetsByPath + * @property {boolean} groupAssetsByExtension + * @property {number} assetsSpace + * @property {((value: string, asset: StatsAsset) => boolean)[]} excludeAssets + * @property {((name: string, module: StatsModule, type: "module" | "chunk" | "root-of-chunk" | "nested") => boolean)[]} excludeModules + * @property {((warning: StatsError, textValue: string) => boolean)[]} warningsFilter + * @property {boolean} cachedModules + * @property {boolean} orphanModules + * @property {boolean} dependentModules + * @property {boolean} runtimeModules + * @property {boolean} groupModulesByCacheStatus + * @property {boolean} groupModulesByLayer + * @property {boolean} groupModulesByAttributes + * @property {boolean} groupModulesByPath + * @property {boolean} groupModulesByExtension + * @property {boolean} groupModulesByType + * @property {boolean | "auto"} entrypoints + * @property {boolean} chunkGroups + * @property {boolean} chunkGroupAuxiliary + * @property {boolean} chunkGroupChildren + * @property {number} chunkGroupMaxAssets + * @property {number} modulesSpace + * @property {number} chunkModulesSpace + * @property {number} nestedModulesSpace + * @property {false|"none"|"error"|"warn"|"info"|"log"|"verbose"} logging + * @property {((value: string) => boolean)[]} loggingDebug + * @property {boolean} loggingTrace + * @property {any} _env + */ - if (schemaPart.description) { - schemaText += `\n-> ${schemaPart.description}`; - } +/** @typedef {KnownNormalizedStatsOptions & Omit & Record} NormalizedStatsOptions */ - if (schemaPart.link) { - schemaText += `\n-> Read more at ${schemaPart.link}`; - } +/** + * @typedef {Object} KnownCreateStatsOptionsContext + * @property {boolean=} forToString + */ - return schemaText; - } - /** - * @param {SchemaUtilErrorObject} error - * @returns {string} - */ +/** @typedef {KnownCreateStatsOptionsContext & Record} CreateStatsOptionsContext */ +/** @type {AssetInfo} */ +const EMPTY_ASSET_INFO = Object.freeze({}); - formatValidationError(error) { - const { - keyword, - dataPath: errorDataPath - } = error; - const dataPath = `${this.baseDataPath}${errorDataPath}`; +const esmDependencyCategory = "esm"; +// TODO webpack 6: remove +const deprecatedNormalModuleLoaderHook = util.deprecate( + compilation => { + return (__webpack_require__(39).getCompilationHooks)(compilation).loader; + }, + "Compilation.hooks.normalModuleLoader was moved to NormalModule.getCompilationHooks(compilation).loader", + "DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK" +); - switch (keyword) { - case "type": - { - const { - parentSchema, - params - } = error; // eslint-disable-next-line default-case +// TODO webpack 6: remove +const defineRemovedModuleTemplates = moduleTemplates => { + Object.defineProperties(moduleTemplates, { + asset: { + enumerable: false, + configurable: false, + get: () => { + throw new WebpackError( + "Compilation.moduleTemplates.asset has been removed" + ); + } + }, + webassembly: { + enumerable: false, + configurable: false, + get: () => { + throw new WebpackError( + "Compilation.moduleTemplates.webassembly has been removed" + ); + } + } + }); + moduleTemplates = undefined; +}; - switch ( - /** @type {import("ajv").TypeParams} */ - params.type) { - case "number": - return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; +const byId = compareSelect( + /** + * @param {Chunk} c chunk + * @returns {number | string} id + */ c => c.id, + compareIds +); - case "integer": - return `${dataPath} should be an ${this.getSchemaPartText(parentSchema, false, true)}`; +const byNameOrHash = concatComparators( + compareSelect( + /** + * @param {Compilation} c compilation + * @returns {string} name + */ + c => c.name, + compareIds + ), + compareSelect( + /** + * @param {Compilation} c compilation + * @returns {string} hash + */ c => c.fullHash, + compareIds + ) +); - case "string": - return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; +const byMessage = compareSelect(err => `${err.message}`, compareStringsNumeric); - case "boolean": - return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; +const byModule = compareSelect( + err => (err.module && err.module.identifier()) || "", + compareStringsNumeric +); - case "array": - return `${dataPath} should be an array:\n${this.getSchemaPartText(parentSchema)}`; +const byLocation = compareSelect(err => err.loc, compareLocations); - case "object": - return `${dataPath} should be an object:\n${this.getSchemaPartText(parentSchema)}`; +const compareErrors = concatComparators(byModule, byLocation, byMessage); - case "null": - return `${dataPath} should be a ${this.getSchemaPartText(parentSchema, false, true)}`; +/** @type {WeakMap} */ +const unsafeCacheDependencies = new WeakMap(); - default: - return `${dataPath} should be:\n${this.getSchemaPartText(parentSchema)}`; - } - } +/** @type {WeakMap} */ +const unsafeCacheData = new WeakMap(); - case "instanceof": - { - const { - parentSchema - } = error; - return `${dataPath} should be an instance of ${this.getSchemaPartText(parentSchema, false, true)}`; - } +class Compilation { + /** + * Creates an instance of Compilation. + * @param {Compiler} compiler the compiler which created the compilation + * @param {CompilationParams} params the compilation parameters + */ + constructor(compiler, params) { + this._backCompat = compiler._backCompat; - case "pattern": - { - const { - params, - parentSchema - } = error; - const { - pattern - } = - /** @type {import("ajv").PatternParams} */ - params; - return `${dataPath} should match pattern ${JSON.stringify(pattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + const getNormalModuleLoader = () => deprecatedNormalModuleLoaderHook(this); + /** @typedef {{ additionalAssets?: true | Function }} ProcessAssetsAdditionalOptions */ + /** @type {AsyncSeriesHook<[CompilationAssets], ProcessAssetsAdditionalOptions>} */ + const processAssetsHook = new AsyncSeriesHook(["assets"]); - case "format": - { - const { - params, - parentSchema - } = error; - const { - format - } = - /** @type {import("ajv").FormatParams} */ - params; - return `${dataPath} should match format ${JSON.stringify(format)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + let savedAssets = new Set(); + const popNewAssets = assets => { + let newAssets = undefined; + for (const file of Object.keys(assets)) { + if (savedAssets.has(file)) continue; + if (newAssets === undefined) { + newAssets = Object.create(null); + } + newAssets[file] = assets[file]; + savedAssets.add(file); + } + return newAssets; + }; + processAssetsHook.intercept({ + name: "Compilation", + call: () => { + savedAssets = new Set(Object.keys(this.assets)); + }, + register: tap => { + const { type, name } = tap; + const { fn, additionalAssets, ...remainingTap } = tap; + const additionalAssetsFn = + additionalAssets === true ? fn : additionalAssets; + const processedAssets = additionalAssetsFn ? new WeakSet() : undefined; + switch (type) { + case "sync": + if (additionalAssetsFn) { + this.hooks.processAdditionalAssets.tap(name, assets => { + if (processedAssets.has(this.assets)) + additionalAssetsFn(assets); + }); + } + return { + ...remainingTap, + type: "async", + fn: (assets, callback) => { + try { + fn(assets); + } catch (e) { + return callback(e); + } + if (processedAssets !== undefined) + processedAssets.add(this.assets); + const newAssets = popNewAssets(assets); + if (newAssets !== undefined) { + this.hooks.processAdditionalAssets.callAsync( + newAssets, + callback + ); + return; + } + callback(); + } + }; + case "async": + if (additionalAssetsFn) { + this.hooks.processAdditionalAssets.tapAsync( + name, + (assets, callback) => { + if (processedAssets.has(this.assets)) + return additionalAssetsFn(assets, callback); + callback(); + } + ); + } + return { + ...remainingTap, + fn: (assets, callback) => { + fn(assets, err => { + if (err) return callback(err); + if (processedAssets !== undefined) + processedAssets.add(this.assets); + const newAssets = popNewAssets(assets); + if (newAssets !== undefined) { + this.hooks.processAdditionalAssets.callAsync( + newAssets, + callback + ); + return; + } + callback(); + }); + } + }; + case "promise": + if (additionalAssetsFn) { + this.hooks.processAdditionalAssets.tapPromise(name, assets => { + if (processedAssets.has(this.assets)) + return additionalAssetsFn(assets); + return Promise.resolve(); + }); + } + return { + ...remainingTap, + fn: assets => { + const p = fn(assets); + if (!p || !p.then) return p; + return p.then(() => { + if (processedAssets !== undefined) + processedAssets.add(this.assets); + const newAssets = popNewAssets(assets); + if (newAssets !== undefined) { + return this.hooks.processAdditionalAssets.promise( + newAssets + ); + } + }); + } + }; + } + } + }); - case "formatMinimum": - case "formatMaximum": - { - const { - params, - parentSchema - } = error; - const { - comparison, - limit - } = - /** @type {import("ajv").ComparisonParams} */ - params; - return `${dataPath} should be ${comparison} ${JSON.stringify(limit)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {SyncHook<[CompilationAssets]>} */ + const afterProcessAssetsHook = new SyncHook(["assets"]); - case "minimum": - case "maximum": - case "exclusiveMinimum": - case "exclusiveMaximum": - { - const { - parentSchema, - params - } = error; - const { - comparison, - limit - } = - /** @type {import("ajv").ComparisonParams} */ - params; - const [, ...hints] = getHints( - /** @type {Schema} */ - parentSchema, true); + /** + * @template T + * @param {string} name name of the hook + * @param {number} stage new stage + * @param {function(): AsArray} getArgs get old hook function args + * @param {string=} code deprecation code (not deprecated when unset) + * @returns {FakeHook, "tap" | "tapAsync" | "tapPromise" | "name">>} fake hook which redirects + */ + const createProcessAssetsHook = (name, stage, getArgs, code) => { + if (!this._backCompat && code) return undefined; + const errorMessage = + reason => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}. +BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a single Compilation.hooks.processAssets hook.`; + const getOptions = options => { + if (typeof options === "string") options = { name: options }; + if (options.stage) { + throw new Error(errorMessage("it's using the 'stage' option")); + } + return { ...options, stage: stage }; + }; + return createFakeHook( + { + name, + /** @type {AsyncSeriesHook["intercept"]} */ + intercept(interceptor) { + throw new Error(errorMessage("it's using 'intercept'")); + }, + /** @type {AsyncSeriesHook["tap"]} */ + tap: (options, fn) => { + processAssetsHook.tap(getOptions(options), () => fn(...getArgs())); + }, + /** @type {AsyncSeriesHook["tapAsync"]} */ + tapAsync: (options, fn) => { + processAssetsHook.tapAsync( + getOptions(options), + (assets, callback) => + /** @type {any} */ (fn)(...getArgs(), callback) + ); + }, + /** @type {AsyncSeriesHook["tapPromise"]} */ + tapPromise: (options, fn) => { + processAssetsHook.tapPromise(getOptions(options), () => + fn(...getArgs()) + ); + } + }, + `${name} is deprecated (use Compilation.hooks.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)`, + code + ); + }; + this.hooks = Object.freeze({ + /** @type {SyncHook<[Module]>} */ + buildModule: new SyncHook(["module"]), + /** @type {SyncHook<[Module]>} */ + rebuildModule: new SyncHook(["module"]), + /** @type {SyncHook<[Module, WebpackError]>} */ + failedModule: new SyncHook(["module", "error"]), + /** @type {SyncHook<[Module]>} */ + succeedModule: new SyncHook(["module"]), + /** @type {SyncHook<[Module]>} */ + stillValidModule: new SyncHook(["module"]), - if (hints.length === 0) { - hints.push(`should be ${comparison} ${limit}`); - } + /** @type {SyncHook<[Dependency, EntryOptions]>} */ + addEntry: new SyncHook(["entry", "options"]), + /** @type {SyncHook<[Dependency, EntryOptions, Error]>} */ + failedEntry: new SyncHook(["entry", "options", "error"]), + /** @type {SyncHook<[Dependency, EntryOptions, Module]>} */ + succeedEntry: new SyncHook(["entry", "options", "module"]), - return `${dataPath} ${hints.join(" ")}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {SyncWaterfallHook<[(string[] | ReferencedExport)[], Dependency, RuntimeSpec]>} */ + dependencyReferencedExports: new SyncWaterfallHook([ + "referencedExports", + "dependency", + "runtime" + ]), - case "multipleOf": - { - const { - params, - parentSchema - } = error; - const { - multipleOf - } = - /** @type {import("ajv").MultipleOfParams} */ - params; - return `${dataPath} should be multiple of ${multipleOf}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {SyncHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */ + executeModule: new SyncHook(["options", "context"]), + /** @type {AsyncParallelHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */ + prepareModuleExecution: new AsyncParallelHook(["options", "context"]), - case "patternRequired": - { - const { - params, - parentSchema - } = error; - const { - missingPattern - } = - /** @type {import("ajv").PatternRequiredParams} */ - params; - return `${dataPath} should have property matching pattern ${JSON.stringify(missingPattern)}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {AsyncSeriesHook<[Iterable]>} */ + finishModules: new AsyncSeriesHook(["modules"]), + /** @type {AsyncSeriesHook<[Module]>} */ + finishRebuildingModule: new AsyncSeriesHook(["module"]), + /** @type {SyncHook<[]>} */ + unseal: new SyncHook([]), + /** @type {SyncHook<[]>} */ + seal: new SyncHook([]), - case "minLength": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; + /** @type {SyncHook<[]>} */ + beforeChunks: new SyncHook([]), + /** @type {SyncHook<[Iterable]>} */ + afterChunks: new SyncHook(["chunks"]), - if (limit === 1) { - return `${dataPath} should be a non-empty string${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {SyncBailHook<[Iterable]>} */ + optimizeDependencies: new SyncBailHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + afterOptimizeDependencies: new SyncHook(["modules"]), - const length = limit - 1; - return `${dataPath} should be longer than ${length} character${length > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {SyncHook<[]>} */ + optimize: new SyncHook([]), + /** @type {SyncBailHook<[Iterable]>} */ + optimizeModules: new SyncBailHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + afterOptimizeModules: new SyncHook(["modules"]), - case "minItems": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; + /** @type {SyncBailHook<[Iterable, ChunkGroup[]]>} */ + optimizeChunks: new SyncBailHook(["chunks", "chunkGroups"]), + /** @type {SyncHook<[Iterable, ChunkGroup[]]>} */ + afterOptimizeChunks: new SyncHook(["chunks", "chunkGroups"]), - if (limit === 1) { - return `${dataPath} should be a non-empty array${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {AsyncSeriesHook<[Iterable, Iterable]>} */ + optimizeTree: new AsyncSeriesHook(["chunks", "modules"]), + /** @type {SyncHook<[Iterable, Iterable]>} */ + afterOptimizeTree: new SyncHook(["chunks", "modules"]), - return `${dataPath} should not have fewer than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {AsyncSeriesBailHook<[Iterable, Iterable]>} */ + optimizeChunkModules: new AsyncSeriesBailHook(["chunks", "modules"]), + /** @type {SyncHook<[Iterable, Iterable]>} */ + afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]), + /** @type {SyncBailHook<[], boolean>} */ + shouldRecord: new SyncBailHook([]), - case "minProperties": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; + /** @type {SyncHook<[Chunk, Set, RuntimeRequirementsContext]>} */ + additionalChunkRuntimeRequirements: new SyncHook([ + "chunk", + "runtimeRequirements", + "context" + ]), + /** @type {HookMap, RuntimeRequirementsContext]>>} */ + runtimeRequirementInChunk: new HookMap( + () => new SyncBailHook(["chunk", "runtimeRequirements", "context"]) + ), + /** @type {SyncHook<[Module, Set, RuntimeRequirementsContext]>} */ + additionalModuleRuntimeRequirements: new SyncHook([ + "module", + "runtimeRequirements", + "context" + ]), + /** @type {HookMap, RuntimeRequirementsContext]>>} */ + runtimeRequirementInModule: new HookMap( + () => new SyncBailHook(["module", "runtimeRequirements", "context"]) + ), + /** @type {SyncHook<[Chunk, Set, RuntimeRequirementsContext]>} */ + additionalTreeRuntimeRequirements: new SyncHook([ + "chunk", + "runtimeRequirements", + "context" + ]), + /** @type {HookMap, RuntimeRequirementsContext]>>} */ + runtimeRequirementInTree: new HookMap( + () => new SyncBailHook(["chunk", "runtimeRequirements", "context"]) + ), - if (limit === 1) { - return `${dataPath} should be a non-empty object${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {SyncHook<[RuntimeModule, Chunk]>} */ + runtimeModule: new SyncHook(["module", "chunk"]), - return `${dataPath} should not have fewer than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {SyncHook<[Iterable, any]>} */ + reviveModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook<[Iterable]>} */ + beforeModuleIds: new SyncHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + moduleIds: new SyncHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + optimizeModuleIds: new SyncHook(["modules"]), + /** @type {SyncHook<[Iterable]>} */ + afterOptimizeModuleIds: new SyncHook(["modules"]), - case "maxLength": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; - const max = limit + 1; - return `${dataPath} should be shorter than ${max} character${max > 1 ? "s" : ""}${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {SyncHook<[Iterable, any]>} */ + reviveChunks: new SyncHook(["chunks", "records"]), + /** @type {SyncHook<[Iterable]>} */ + beforeChunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook<[Iterable]>} */ + chunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook<[Iterable]>} */ + optimizeChunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook<[Iterable]>} */ + afterOptimizeChunkIds: new SyncHook(["chunks"]), - case "maxItems": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; - return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {SyncHook<[Iterable, any]>} */ + recordModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook<[Iterable, any]>} */ + recordChunks: new SyncHook(["chunks", "records"]), - case "maxProperties": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; - return `${dataPath} should not have more than ${limit} properties${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {SyncHook<[Iterable]>} */ + optimizeCodeGeneration: new SyncHook(["modules"]), - case "uniqueItems": - { - const { - params, - parentSchema - } = error; - const { - i - } = - /** @type {import("ajv").UniqueItemsParams} */ - params; - return `${dataPath} should not contain the item '${error.data[i]}' twice${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {SyncHook<[]>} */ + beforeModuleHash: new SyncHook([]), + /** @type {SyncHook<[]>} */ + afterModuleHash: new SyncHook([]), - case "additionalItems": - { - const { - params, - parentSchema - } = error; - const { - limit - } = - /** @type {import("ajv").LimitParams} */ - params; - return `${dataPath} should not have more than ${limit} items${getSchemaNonTypes(parentSchema)}. These items are valid:\n${this.getSchemaPartText(parentSchema)}`; - } + /** @type {SyncHook<[]>} */ + beforeCodeGeneration: new SyncHook([]), + /** @type {SyncHook<[]>} */ + afterCodeGeneration: new SyncHook([]), - case "contains": - { - const { - parentSchema - } = error; - return `${dataPath} should contains at least one ${this.getSchemaPartText(parentSchema, ["contains"])} item${getSchemaNonTypes(parentSchema)}.`; - } + /** @type {SyncHook<[]>} */ + beforeRuntimeRequirements: new SyncHook([]), + /** @type {SyncHook<[]>} */ + afterRuntimeRequirements: new SyncHook([]), - case "required": - { - const { - parentSchema, - params - } = error; - const missingProperty = - /** @type {import("ajv").DependenciesParams} */ - params.missingProperty.replace(/^\./, ""); - const hasProperty = parentSchema && Boolean( - /** @type {Schema} */ - parentSchema.properties && - /** @type {Schema} */ - parentSchema.properties[missingProperty]); - return `${dataPath} misses the property '${missingProperty}'${getSchemaNonTypes(parentSchema)}.${hasProperty ? ` Should be:\n${this.getSchemaPartText(parentSchema, ["properties", missingProperty])}` : this.getSchemaPartDescription(parentSchema)}`; - } + /** @type {SyncHook<[]>} */ + beforeHash: new SyncHook([]), + /** @type {SyncHook<[Chunk]>} */ + contentHash: new SyncHook(["chunk"]), + /** @type {SyncHook<[]>} */ + afterHash: new SyncHook([]), + /** @type {SyncHook<[any]>} */ + recordHash: new SyncHook(["records"]), + /** @type {SyncHook<[Compilation, any]>} */ + record: new SyncHook(["compilation", "records"]), - case "additionalProperties": - { - const { - params, - parentSchema - } = error; - const { - additionalProperty - } = - /** @type {import("ajv").AdditionalPropertiesParams} */ - params; - return `${dataPath} has an unknown property '${additionalProperty}'${getSchemaNonTypes(parentSchema)}. These properties are valid:\n${this.getSchemaPartText(parentSchema)}`; - } + /** @type {SyncHook<[]>} */ + beforeModuleAssets: new SyncHook([]), + /** @type {SyncBailHook<[], boolean>} */ + shouldGenerateChunkAssets: new SyncBailHook([]), + /** @type {SyncHook<[]>} */ + beforeChunkAssets: new SyncHook([]), + // TODO webpack 6 remove + /** @deprecated */ + additionalChunkAssets: createProcessAssetsHook( + "additionalChunkAssets", + Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, + () => [this.chunks], + "DEP_WEBPACK_COMPILATION_ADDITIONAL_CHUNK_ASSETS" + ), - case "dependencies": - { - const { - params, - parentSchema - } = error; - const { - property, - deps - } = - /** @type {import("ajv").DependenciesParams} */ - params; - const dependencies = deps.split(",").map( - /** - * @param {string} dep - * @returns {string} - */ - dep => `'${dep.trim()}'`).join(", "); - return `${dataPath} should have properties ${dependencies} when property '${property}' is present${getSchemaNonTypes(parentSchema)}.${this.getSchemaPartDescription(parentSchema)}`; - } - - case "propertyNames": - { - const { - params, - parentSchema, - schema - } = error; - const { - propertyName - } = - /** @type {import("ajv").PropertyNamesParams} */ - params; - return `${dataPath} property name '${propertyName}' is invalid${getSchemaNonTypes(parentSchema)}. Property names should be match format ${JSON.stringify(schema.format)}.${this.getSchemaPartDescription(parentSchema)}`; - } - - case "enum": - { - const { - parentSchema - } = error; - - if (parentSchema && - /** @type {Schema} */ - parentSchema.enum && - /** @type {Schema} */ - parentSchema.enum.length === 1) { - return `${dataPath} should be ${this.getSchemaPartText(parentSchema, false, true)}`; - } - - return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; - } - - case "const": - { - const { - parentSchema - } = error; - return `${dataPath} should be equal to constant ${this.getSchemaPartText(parentSchema, false, true)}`; - } - - case "not": - { - const postfix = likeObject( - /** @type {Schema} */ - error.parentSchema) ? `\n${this.getSchemaPartText(error.parentSchema)}` : ""; - const schemaOutput = this.getSchemaPartText(error.schema, false, false, false); - - if (canApplyNot(error.schema)) { - return `${dataPath} should be any ${schemaOutput}${postfix}.`; - } - - const { - schema, - parentSchema - } = error; - return `${dataPath} should not be ${this.getSchemaPartText(schema, false, true)}${parentSchema && likeObject(parentSchema) ? `\n${this.getSchemaPartText(parentSchema)}` : ""}`; - } - - case "oneOf": - case "anyOf": - { - const { - parentSchema, - children - } = error; - - if (children && children.length > 0) { - if (error.schema.length === 1) { - const lastChild = children[children.length - 1]; - const remainingChildren = children.slice(0, children.length - 1); - return this.formatValidationError(Object.assign({}, lastChild, { - children: remainingChildren, - parentSchema: Object.assign({}, parentSchema, lastChild.parentSchema) - })); - } - - let filteredChildren = filterChildren(children); - - if (filteredChildren.length === 1) { - return this.formatValidationError(filteredChildren[0]); - } - - filteredChildren = groupChildrenByFirstChild(filteredChildren); - return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}\nDetails:\n${filteredChildren.map( - /** - * @param {SchemaUtilErrorObject} nestedError - * @returns {string} - */ - nestedError => ` * ${indent(this.formatValidationError(nestedError), " ")}`).join("\n")}`; - } - - return `${dataPath} should be one of these:\n${this.getSchemaPartText(parentSchema)}`; - } - - case "if": - { - const { - params, - parentSchema - } = error; - const { - failingKeyword - } = - /** @type {import("ajv").IfParams} */ - params; - return `${dataPath} should match "${failingKeyword}" schema:\n${this.getSchemaPartText(parentSchema, [failingKeyword])}`; - } - - case "absolutePath": - { - const { - message, - parentSchema - } = error; - return `${dataPath}: ${message}${this.getSchemaPartDescription(parentSchema)}`; - } - - /* istanbul ignore next */ - - default: - { - const { - message, - parentSchema - } = error; - const ErrorInJSON = JSON.stringify(error, null, 2); // For `custom`, `false schema`, `$ref` keywords - // Fallback for unknown keywords - - return `${dataPath} ${message} (${ErrorInJSON}).\n${this.getSchemaPartText(parentSchema, false)}`; - } - } - } - /** - * @param {Array} errors - * @returns {string} - */ - - - formatValidationErrors(errors) { - return errors.map(error => { - let formattedError = this.formatValidationError(error); - - if (this.postFormatter) { - formattedError = this.postFormatter(formattedError, error); - } - - return ` - ${indent(formattedError, " ")}`; - }).join("\n"); - } - -} + // TODO webpack 6 deprecate + /** @deprecated */ + additionalAssets: createProcessAssetsHook( + "additionalAssets", + Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, + () => [] + ), + // TODO webpack 6 remove + /** @deprecated */ + optimizeChunkAssets: createProcessAssetsHook( + "optimizeChunkAssets", + Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE, + () => [this.chunks], + "DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS" + ), + // TODO webpack 6 remove + /** @deprecated */ + afterOptimizeChunkAssets: createProcessAssetsHook( + "afterOptimizeChunkAssets", + Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE + 1, + () => [this.chunks], + "DEP_WEBPACK_COMPILATION_AFTER_OPTIMIZE_CHUNK_ASSETS" + ), + // TODO webpack 6 deprecate + /** @deprecated */ + optimizeAssets: processAssetsHook, + // TODO webpack 6 deprecate + /** @deprecated */ + afterOptimizeAssets: afterProcessAssetsHook, -var _default = ValidationError; -exports.Z = _default; + processAssets: processAssetsHook, + afterProcessAssets: afterProcessAssetsHook, + /** @type {AsyncSeriesHook<[CompilationAssets]>} */ + processAdditionalAssets: new AsyncSeriesHook(["assets"]), -/***/ }), + /** @type {SyncBailHook<[], boolean>} */ + needAdditionalSeal: new SyncBailHook([]), + /** @type {AsyncSeriesHook<[]>} */ + afterSeal: new AsyncSeriesHook([]), -/***/ 81184: -/***/ (function(module) { + /** @type {SyncWaterfallHook<[RenderManifestEntry[], RenderManifestOptions]>} */ + renderManifest: new SyncWaterfallHook(["result", "options"]), -"use strict"; + /** @type {SyncHook<[Hash]>} */ + fullHash: new SyncHook(["hash"]), + /** @type {SyncHook<[Chunk, Hash, ChunkHashContext]>} */ + chunkHash: new SyncHook(["chunk", "chunkHash", "ChunkHashContext"]), + /** @type {SyncHook<[Module, string]>} */ + moduleAsset: new SyncHook(["module", "filename"]), + /** @type {SyncHook<[Chunk, string]>} */ + chunkAsset: new SyncHook(["chunk", "filename"]), -/** - * @typedef {[number, boolean]} RangeValue - */ + /** @type {SyncWaterfallHook<[string, object, AssetInfo]>} */ + assetPath: new SyncWaterfallHook(["path", "options", "assetInfo"]), -/** - * @callback RangeValueCallback - * @param {RangeValue} rangeValue - * @returns {boolean} - */ -class Range { - /** - * @param {"left" | "right"} side - * @param {boolean} exclusive - * @returns {">" | ">=" | "<" | "<="} - */ - static getOperator(side, exclusive) { - if (side === "left") { - return exclusive ? ">" : ">="; - } + /** @type {SyncBailHook<[], boolean>} */ + needAdditionalPass: new SyncBailHook([]), - return exclusive ? "<" : "<="; - } - /** - * @param {number} value - * @param {boolean} logic is not logic applied - * @param {boolean} exclusive is range exclusive - * @returns {string} - */ + /** @type {SyncHook<[Compiler, string, number]>} */ + childCompiler: new SyncHook([ + "childCompiler", + "compilerName", + "compilerIndex" + ]), + /** @type {SyncBailHook<[string, LogEntry], true>} */ + log: new SyncBailHook(["origin", "logEntry"]), - static formatRight(value, logic, exclusive) { - if (logic === false) { - return Range.formatLeft(value, !logic, !exclusive); - } + /** @type {SyncWaterfallHook<[WebpackError[]]>} */ + processWarnings: new SyncWaterfallHook(["warnings"]), + /** @type {SyncWaterfallHook<[WebpackError[]]>} */ + processErrors: new SyncWaterfallHook(["errors"]), - return `should be ${Range.getOperator("right", exclusive)} ${value}`; - } - /** - * @param {number} value - * @param {boolean} logic is not logic applied - * @param {boolean} exclusive is range exclusive - * @returns {string} - */ + /** @type {HookMap, CreateStatsOptionsContext]>>} */ + statsPreset: new HookMap(() => new SyncHook(["options", "context"])), + /** @type {SyncHook<[Partial, CreateStatsOptionsContext]>} */ + statsNormalize: new SyncHook(["options", "context"]), + /** @type {SyncHook<[StatsFactory, NormalizedStatsOptions]>} */ + statsFactory: new SyncHook(["statsFactory", "options"]), + /** @type {SyncHook<[StatsPrinter, NormalizedStatsOptions]>} */ + statsPrinter: new SyncHook(["statsPrinter", "options"]), + get normalModuleLoader() { + return getNormalModuleLoader(); + } + }); + /** @type {string=} */ + this.name = undefined; + this.startTime = undefined; + this.endTime = undefined; + /** @type {Compiler} */ + this.compiler = compiler; + this.resolverFactory = compiler.resolverFactory; + this.inputFileSystem = compiler.inputFileSystem; + this.fileSystemInfo = new FileSystemInfo(this.inputFileSystem, { + managedPaths: compiler.managedPaths, + immutablePaths: compiler.immutablePaths, + logger: this.getLogger("webpack.FileSystemInfo"), + hashFunction: compiler.options.output.hashFunction + }); + if (compiler.fileTimestamps) { + this.fileSystemInfo.addFileTimestamps(compiler.fileTimestamps, true); + } + if (compiler.contextTimestamps) { + this.fileSystemInfo.addContextTimestamps( + compiler.contextTimestamps, + true + ); + } + /** @type {Map>} */ + this.valueCacheVersions = new Map(); + this.requestShortener = compiler.requestShortener; + this.compilerPath = compiler.compilerPath; - static formatLeft(value, logic, exclusive) { - if (logic === false) { - return Range.formatRight(value, !logic, !exclusive); - } + this.logger = this.getLogger("webpack.Compilation"); - return `should be ${Range.getOperator("left", exclusive)} ${value}`; - } - /** - * @param {number} start left side value - * @param {number} end right side value - * @param {boolean} startExclusive is range exclusive from left side - * @param {boolean} endExclusive is range exclusive from right side - * @param {boolean} logic is not logic applied - * @returns {string} - */ + const options = compiler.options; + this.options = options; + this.outputOptions = options && options.output; + /** @type {boolean} */ + this.bail = (options && options.bail) || false; + /** @type {boolean} */ + this.profile = (options && options.profile) || false; + this.params = params; + this.mainTemplate = new MainTemplate(this.outputOptions, this); + this.chunkTemplate = new ChunkTemplate(this.outputOptions, this); + this.runtimeTemplate = new RuntimeTemplate( + this, + this.outputOptions, + this.requestShortener + ); + /** @type {{javascript: ModuleTemplate}} */ + this.moduleTemplates = { + javascript: new ModuleTemplate(this.runtimeTemplate, this) + }; + defineRemovedModuleTemplates(this.moduleTemplates); - static formatRange(start, end, startExclusive, endExclusive, logic) { - let result = "should be"; - result += ` ${Range.getOperator(logic ? "left" : "right", logic ? startExclusive : !startExclusive)} ${start} `; - result += logic ? "and" : "or"; - result += ` ${Range.getOperator(logic ? "right" : "left", logic ? endExclusive : !endExclusive)} ${end}`; - return result; - } - /** - * @param {Array} values - * @param {boolean} logic is not logic applied - * @return {RangeValue} computed value and it's exclusive flag - */ + /** @type {Map> | undefined} */ + this.moduleMemCaches = undefined; + /** @type {Map> | undefined} */ + this.moduleMemCaches2 = undefined; + this.moduleGraph = new ModuleGraph(); + /** @type {ChunkGraph} */ + this.chunkGraph = undefined; + /** @type {CodeGenerationResults} */ + this.codeGenerationResults = undefined; + /** @type {AsyncQueue} */ + this.processDependenciesQueue = new AsyncQueue({ + name: "processDependencies", + parallelism: options.parallelism || 100, + processor: this._processModuleDependencies.bind(this) + }); + /** @type {AsyncQueue} */ + this.addModuleQueue = new AsyncQueue({ + name: "addModule", + parent: this.processDependenciesQueue, + getKey: module => module.identifier(), + processor: this._addModule.bind(this) + }); + /** @type {AsyncQueue} */ + this.factorizeQueue = new AsyncQueue({ + name: "factorize", + parent: this.addModuleQueue, + processor: this._factorizeModule.bind(this) + }); + /** @type {AsyncQueue} */ + this.buildQueue = new AsyncQueue({ + name: "build", + parent: this.factorizeQueue, + processor: this._buildModule.bind(this) + }); + /** @type {AsyncQueue} */ + this.rebuildQueue = new AsyncQueue({ + name: "rebuild", + parallelism: options.parallelism || 100, + processor: this._rebuildModule.bind(this) + }); - static getRangeValue(values, logic) { - let minMax = logic ? Infinity : -Infinity; - let j = -1; - const predicate = logic ? - /** @type {RangeValueCallback} */ - ([value]) => value <= minMax : - /** @type {RangeValueCallback} */ - ([value]) => value >= minMax; + /** + * Modules in value are building during the build of Module in key. + * Means value blocking key from finishing. + * Needed to detect build cycles. + * @type {WeakMap>} + */ + this.creatingModuleDuringBuild = new WeakMap(); - for (let i = 0; i < values.length; i++) { - if (predicate(values[i])) { - [minMax] = values[i]; - j = i; - } - } + /** @type {Map} */ + this.entries = new Map(); + /** @type {EntryData} */ + this.globalEntry = { + dependencies: [], + includeDependencies: [], + options: { + name: undefined + } + }; + /** @type {Map} */ + this.entrypoints = new Map(); + /** @type {Entrypoint[]} */ + this.asyncEntrypoints = []; + /** @type {Set} */ + this.chunks = new Set(); + /** @type {ChunkGroup[]} */ + this.chunkGroups = []; + /** @type {Map} */ + this.namedChunkGroups = new Map(); + /** @type {Map} */ + this.namedChunks = new Map(); + /** @type {Set} */ + this.modules = new Set(); + if (this._backCompat) { + arrayToSetDeprecation(this.chunks, "Compilation.chunks"); + arrayToSetDeprecation(this.modules, "Compilation.modules"); + } + /** @private @type {Map} */ + this._modules = new Map(); + this.records = null; + /** @type {string[]} */ + this.additionalChunkAssets = []; + /** @type {CompilationAssets} */ + this.assets = {}; + /** @type {Map} */ + this.assetsInfo = new Map(); + /** @type {Map>>} */ + this._assetsRelatedIn = new Map(); + /** @type {WebpackError[]} */ + this.errors = []; + /** @type {WebpackError[]} */ + this.warnings = []; + /** @type {Compilation[]} */ + this.children = []; + /** @type {Map} */ + this.logging = new Map(); + /** @type {Map} */ + this.dependencyFactories = new Map(); + /** @type {DependencyTemplates} */ + this.dependencyTemplates = new DependencyTemplates( + this.outputOptions.hashFunction + ); + this.childrenCounters = {}; + /** @type {Set} */ + this.usedChunkIds = null; + /** @type {Set} */ + this.usedModuleIds = null; + /** @type {boolean} */ + this.needAdditionalPass = false; + /** @type {Set} */ + this._restoredUnsafeCacheModuleEntries = new Set(); + /** @type {Map} */ + this._restoredUnsafeCacheEntries = new Map(); + /** @type {WeakSet} */ + this.builtModules = new WeakSet(); + /** @type {WeakSet} */ + this.codeGeneratedModules = new WeakSet(); + /** @type {WeakSet} */ + this.buildTimeExecutedModules = new WeakSet(); + /** @private @type {Map} */ + this._rebuildingModules = new Map(); + /** @type {Set} */ + this.emittedAssets = new Set(); + /** @type {Set} */ + this.comparedForEmitAssets = new Set(); + /** @type {LazySet} */ + this.fileDependencies = new LazySet(); + /** @type {LazySet} */ + this.contextDependencies = new LazySet(); + /** @type {LazySet} */ + this.missingDependencies = new LazySet(); + /** @type {LazySet} */ + this.buildDependencies = new LazySet(); + // TODO webpack 6 remove + this.compilationDependencies = { + add: util.deprecate( + item => this.fileDependencies.add(item), + "Compilation.compilationDependencies is deprecated (used Compilation.fileDependencies instead)", + "DEP_WEBPACK_COMPILATION_COMPILATION_DEPENDENCIES" + ) + }; - if (j > -1) { - return values[j]; - } + this._modulesCache = this.getCache("Compilation/modules"); + this._assetsCache = this.getCache("Compilation/assets"); + this._codeGenerationCache = this.getCache("Compilation/codeGeneration"); - return [Infinity, true]; - } + const unsafeCache = options.module.unsafeCache; + this._unsafeCache = !!unsafeCache; + this._unsafeCachePredicate = + typeof unsafeCache === "function" ? unsafeCache : () => true; + } - constructor() { - /** @type {Array} */ - this._left = []; - /** @type {Array} */ + getStats() { + return new Stats(this); + } - this._right = []; - } - /** - * @param {number} value - * @param {boolean=} exclusive - */ + /** + * @param {StatsOptions | string} optionsOrPreset stats option value + * @param {CreateStatsOptionsContext} context context + * @returns {NormalizedStatsOptions} normalized options + */ + createStatsOptions(optionsOrPreset, context = {}) { + if ( + typeof optionsOrPreset === "boolean" || + typeof optionsOrPreset === "string" + ) { + optionsOrPreset = { preset: optionsOrPreset }; + } + if (typeof optionsOrPreset === "object" && optionsOrPreset !== null) { + // We use this method of shallow cloning this object to include + // properties in the prototype chain + /** @type {Partial} */ + const options = {}; + for (const key in optionsOrPreset) { + options[key] = optionsOrPreset[key]; + } + if (options.preset !== undefined) { + this.hooks.statsPreset.for(options.preset).call(options, context); + } + this.hooks.statsNormalize.call(options, context); + return /** @type {NormalizedStatsOptions} */ (options); + } else { + /** @type {Partial} */ + const options = {}; + this.hooks.statsNormalize.call(options, context); + return /** @type {NormalizedStatsOptions} */ (options); + } + } + createStatsFactory(options) { + const statsFactory = new StatsFactory(); + this.hooks.statsFactory.call(statsFactory, options); + return statsFactory; + } - left(value, exclusive = false) { - this._left.push([value, exclusive]); - } - /** - * @param {number} value - * @param {boolean=} exclusive - */ + createStatsPrinter(options) { + const statsPrinter = new StatsPrinter(); + this.hooks.statsPrinter.call(statsPrinter, options); + return statsPrinter; + } + /** + * @param {string} name cache name + * @returns {CacheFacade} the cache facade instance + */ + getCache(name) { + return this.compiler.getCache(name); + } - right(value, exclusive = false) { - this._right.push([value, exclusive]); - } - /** - * @param {boolean} logic is not logic applied - * @return {string} "smart" range string representation - */ + /** + * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name + * @returns {Logger} a logger with that name + */ + getLogger(name) { + if (!name) { + throw new TypeError("Compilation.getLogger(name) called without a name"); + } + /** @type {LogEntry[] | undefined} */ + let logEntries; + return new Logger( + (type, args) => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compilation.getLogger(name) called with a function not returning a name" + ); + } + } + let trace; + switch (type) { + case LogType.warn: + case LogType.error: + case LogType.trace: + trace = ErrorHelpers.cutOffLoaderExecution(new Error("Trace").stack) + .split("\n") + .slice(3); + break; + } + /** @type {LogEntry} */ + const logEntry = { + time: Date.now(), + type, + args, + trace + }; + if (this.hooks.log.call(name, logEntry) === undefined) { + if (logEntry.type === LogType.profileEnd) { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.profileEnd === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.profileEnd(`[${name}] ${logEntry.args[0]}`); + } + } + if (logEntries === undefined) { + logEntries = this.logging.get(name); + if (logEntries === undefined) { + logEntries = []; + this.logging.set(name, logEntries); + } + } + logEntries.push(logEntry); + if (logEntry.type === LogType.profile) { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.profile === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.profile(`[${name}] ${logEntry.args[0]}`); + } + } + } + }, + childName => { + if (typeof name === "function") { + if (typeof childName === "function") { + return this.getLogger(() => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compilation.getLogger(name) called with a function not returning a name" + ); + } + } + if (typeof childName === "function") { + childName = childName(); + if (!childName) { + throw new TypeError( + "Logger.getChildLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } else { + return this.getLogger(() => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compilation.getLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } + } else { + if (typeof childName === "function") { + return this.getLogger(() => { + if (typeof childName === "function") { + childName = childName(); + if (!childName) { + throw new TypeError( + "Logger.getChildLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } else { + return this.getLogger(`${name}/${childName}`); + } + } + } + ); + } + /** + * @param {Module} module module to be added that was created + * @param {ModuleCallback} callback returns the module in the compilation, + * it could be the passed one (if new), or an already existing in the compilation + * @returns {void} + */ + addModule(module, callback) { + this.addModuleQueue.add(module, callback); + } - format(logic = true) { - const [start, leftExclusive] = Range.getRangeValue(this._left, logic); - const [end, rightExclusive] = Range.getRangeValue(this._right, !logic); + /** + * @param {Module} module module to be added that was created + * @param {ModuleCallback} callback returns the module in the compilation, + * it could be the passed one (if new), or an already existing in the compilation + * @returns {void} + */ + _addModule(module, callback) { + const identifier = module.identifier(); + const alreadyAddedModule = this._modules.get(identifier); + if (alreadyAddedModule) { + return callback(null, alreadyAddedModule); + } - if (!Number.isFinite(start) && !Number.isFinite(end)) { - return ""; - } + const currentProfile = this.profile + ? this.moduleGraph.getProfile(module) + : undefined; + if (currentProfile !== undefined) { + currentProfile.markRestoringStart(); + } - const realStart = leftExclusive ? start + 1 : start; - const realEnd = rightExclusive ? end - 1 : end; // e.g. 5 < x < 7, 5 < x <= 6, 6 <= x <= 6 + this._modulesCache.get(identifier, null, (err, cacheModule) => { + if (err) return callback(new ModuleRestoreError(module, err)); - if (realStart === realEnd) { - return `should be ${logic ? "" : "!"}= ${realStart}`; - } // e.g. 4 < x < ∞ + if (currentProfile !== undefined) { + currentProfile.markRestoringEnd(); + currentProfile.markIntegrationStart(); + } + if (cacheModule) { + cacheModule.updateCacheModule(module); - if (Number.isFinite(start) && !Number.isFinite(end)) { - return Range.formatLeft(start, logic, leftExclusive); - } // e.g. ∞ < x < 4 + module = cacheModule; + } + this._modules.set(identifier, module); + this.modules.add(module); + if (this._backCompat) + ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); + if (currentProfile !== undefined) { + currentProfile.markIntegrationEnd(); + } + callback(null, module); + }); + } + /** + * Fetches a module from a compilation by its identifier + * @param {Module} module the module provided + * @returns {Module} the module requested + */ + getModule(module) { + const identifier = module.identifier(); + return this._modules.get(identifier); + } - if (!Number.isFinite(start) && Number.isFinite(end)) { - return Range.formatRight(end, logic, rightExclusive); - } + /** + * Attempts to search for a module by its identifier + * @param {string} identifier identifier (usually path) for module + * @returns {Module|undefined} attempt to search for module and return it, else undefined + */ + findModule(identifier) { + return this._modules.get(identifier); + } - return Range.formatRange(start, end, leftExclusive, rightExclusive, logic); - } + /** + * Schedules a build of the module object + * + * @param {Module} module module to be built + * @param {ModuleCallback} callback the callback + * @returns {void} + */ + buildModule(module, callback) { + this.buildQueue.add(module, callback); + } -} + /** + * Builds the module object + * + * @param {Module} module module to be built + * @param {ModuleCallback} callback the callback + * @returns {void} + */ + _buildModule(module, callback) { + const currentProfile = this.profile + ? this.moduleGraph.getProfile(module) + : undefined; + if (currentProfile !== undefined) { + currentProfile.markBuildingStart(); + } -module.exports = Range; + module.needBuild( + { + compilation: this, + fileSystemInfo: this.fileSystemInfo, + valueCacheVersions: this.valueCacheVersions + }, + (err, needBuild) => { + if (err) return callback(err); -/***/ }), + if (!needBuild) { + if (currentProfile !== undefined) { + currentProfile.markBuildingEnd(); + } + this.hooks.stillValidModule.call(module); + return callback(); + } -/***/ 79926: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.hooks.buildModule.call(module); + this.builtModules.add(module); + module.build( + this.options, + this, + this.resolverFactory.get("normal", module.resolveOptions), + this.inputFileSystem, + err => { + if (currentProfile !== undefined) { + currentProfile.markBuildingEnd(); + } + if (err) { + this.hooks.failedModule.call(module, err); + return callback(err); + } + if (currentProfile !== undefined) { + currentProfile.markStoringStart(); + } + this._modulesCache.store(module.identifier(), null, module, err => { + if (currentProfile !== undefined) { + currentProfile.markStoringEnd(); + } + if (err) { + this.hooks.failedModule.call(module, err); + return callback(new ModuleStoreError(module, err)); + } + this.hooks.succeedModule.call(module); + return callback(); + }); + } + ); + } + ); + } -"use strict"; + /** + * @param {Module} module to be processed for deps + * @param {ModuleCallback} callback callback to be triggered + * @returns {void} + */ + processModuleDependencies(module, callback) { + this.processDependenciesQueue.add(module, callback); + } + /** + * @param {Module} module to be processed for deps + * @returns {void} + */ + processModuleDependenciesNonRecursive(module) { + const processDependenciesBlock = block => { + if (block.dependencies) { + let i = 0; + for (const dep of block.dependencies) { + this.moduleGraph.setParents(dep, block, module, i++); + } + } + if (block.blocks) { + for (const b of block.blocks) processDependenciesBlock(b); + } + }; -const Range = __webpack_require__(81184); -/** @typedef {import("../validate").Schema} Schema */ + processDependenciesBlock(module); + } -/** - * @param {Schema} schema - * @param {boolean} logic - * @return {string[]} - */ + /** + * @param {Module} module to be processed for deps + * @param {ModuleCallback} callback callback to be triggered + * @returns {void} + */ + _processModuleDependencies(module, callback) { + /** @type {Array<{factory: ModuleFactory, dependencies: Dependency[], originModule: Module|null}>} */ + const sortedDependencies = []; + /** @type {DependenciesBlock} */ + let currentBlock; -module.exports.stringHints = function stringHints(schema, logic) { - const hints = []; - let type = "string"; - const currentSchema = { ...schema - }; + /** @type {Map>} */ + let dependencies; + /** @type {DepConstructor} */ + let factoryCacheKey; + /** @type {ModuleFactory} */ + let factoryCacheKey2; + /** @type {Map} */ + let factoryCacheValue; + /** @type {string} */ + let listCacheKey1; + /** @type {string} */ + let listCacheKey2; + /** @type {Dependency[]} */ + let listCacheValue; - if (!logic) { - const tmpLength = currentSchema.minLength; - const tmpFormat = currentSchema.formatMinimum; - const tmpExclusive = currentSchema.formatExclusiveMaximum; - currentSchema.minLength = currentSchema.maxLength; - currentSchema.maxLength = tmpLength; - currentSchema.formatMinimum = currentSchema.formatMaximum; - currentSchema.formatMaximum = tmpFormat; - currentSchema.formatExclusiveMaximum = !currentSchema.formatExclusiveMinimum; - currentSchema.formatExclusiveMinimum = !tmpExclusive; - } + let inProgressSorting = 1; + let inProgressTransitive = 1; - if (typeof currentSchema.minLength === "number") { - if (currentSchema.minLength === 1) { - type = "non-empty string"; - } else { - const length = Math.max(currentSchema.minLength - 1, 0); - hints.push(`should be longer than ${length} character${length > 1 ? "s" : ""}`); - } - } + const onDependenciesSorted = err => { + if (err) return callback(err); - if (typeof currentSchema.maxLength === "number") { - if (currentSchema.maxLength === 0) { - type = "empty string"; - } else { - const length = currentSchema.maxLength + 1; - hints.push(`should be shorter than ${length} character${length > 1 ? "s" : ""}`); - } - } + // early exit without changing parallelism back and forth + if (sortedDependencies.length === 0 && inProgressTransitive === 1) { + return callback(); + } - if (currentSchema.pattern) { - hints.push(`should${logic ? "" : " not"} match pattern ${JSON.stringify(currentSchema.pattern)}`); - } + // This is nested so we need to allow one additional task + this.processDependenciesQueue.increaseParallelism(); - if (currentSchema.format) { - hints.push(`should${logic ? "" : " not"} match format ${JSON.stringify(currentSchema.format)}`); - } + for (const item of sortedDependencies) { + inProgressTransitive++; + this.handleModuleCreation(item, err => { + // In V8, the Error objects keep a reference to the functions on the stack. These warnings & + // errors are created inside closures that keep a reference to the Compilation, so errors are + // leaking the Compilation object. + if (err && this.bail) { + if (inProgressTransitive <= 0) return; + inProgressTransitive = -1; + // eslint-disable-next-line no-self-assign + err.stack = err.stack; + onTransitiveTasksFinished(err); + return; + } + if (--inProgressTransitive === 0) onTransitiveTasksFinished(); + }); + } + if (--inProgressTransitive === 0) onTransitiveTasksFinished(); + }; - if (currentSchema.formatMinimum) { - hints.push(`should be ${currentSchema.formatExclusiveMinimum ? ">" : ">="} ${JSON.stringify(currentSchema.formatMinimum)}`); - } + const onTransitiveTasksFinished = err => { + if (err) return callback(err); + this.processDependenciesQueue.decreaseParallelism(); - if (currentSchema.formatMaximum) { - hints.push(`should be ${currentSchema.formatExclusiveMaximum ? "<" : "<="} ${JSON.stringify(currentSchema.formatMaximum)}`); - } + return callback(); + }; - return [type].concat(hints); -}; -/** - * @param {Schema} schema - * @param {boolean} logic - * @return {string[]} - */ - - -module.exports.numberHints = function numberHints(schema, logic) { - const hints = [schema.type === "integer" ? "integer" : "number"]; - const range = new Range(); + /** + * @param {Dependency} dep dependency + * @param {number} index index in block + * @returns {void} + */ + const processDependency = (dep, index) => { + this.moduleGraph.setParents(dep, currentBlock, module, index); + if (this._unsafeCache) { + try { + const unsafeCachedModule = unsafeCacheDependencies.get(dep); + if (unsafeCachedModule === null) return; + if (unsafeCachedModule !== undefined) { + if ( + this._restoredUnsafeCacheModuleEntries.has(unsafeCachedModule) + ) { + this._handleExistingModuleFromUnsafeCache( + module, + dep, + unsafeCachedModule + ); + return; + } + const identifier = unsafeCachedModule.identifier(); + const cachedModule = + this._restoredUnsafeCacheEntries.get(identifier); + if (cachedModule !== undefined) { + // update unsafe cache to new module + unsafeCacheDependencies.set(dep, cachedModule); + this._handleExistingModuleFromUnsafeCache( + module, + dep, + cachedModule + ); + return; + } + inProgressSorting++; + this._modulesCache.get(identifier, null, (err, cachedModule) => { + if (err) { + if (inProgressSorting <= 0) return; + inProgressSorting = -1; + onDependenciesSorted(err); + return; + } + try { + if (!this._restoredUnsafeCacheEntries.has(identifier)) { + const data = unsafeCacheData.get(cachedModule); + if (data === undefined) { + processDependencyForResolving(dep); + if (--inProgressSorting === 0) onDependenciesSorted(); + return; + } + if (cachedModule !== unsafeCachedModule) { + unsafeCacheDependencies.set(dep, cachedModule); + } + cachedModule.restoreFromUnsafeCache( + data, + this.params.normalModuleFactory, + this.params + ); + this._restoredUnsafeCacheEntries.set( + identifier, + cachedModule + ); + this._restoredUnsafeCacheModuleEntries.add(cachedModule); + if (!this.modules.has(cachedModule)) { + inProgressTransitive++; + this._handleNewModuleFromUnsafeCache( + module, + dep, + cachedModule, + err => { + if (err) { + if (inProgressTransitive <= 0) return; + inProgressTransitive = -1; + onTransitiveTasksFinished(err); + } + if (--inProgressTransitive === 0) + return onTransitiveTasksFinished(); + } + ); + if (--inProgressSorting === 0) onDependenciesSorted(); + return; + } + } + if (unsafeCachedModule !== cachedModule) { + unsafeCacheDependencies.set(dep, cachedModule); + } + this._handleExistingModuleFromUnsafeCache( + module, + dep, + cachedModule + ); // a3 + } catch (err) { + if (inProgressSorting <= 0) return; + inProgressSorting = -1; + onDependenciesSorted(err); + return; + } + if (--inProgressSorting === 0) onDependenciesSorted(); + }); + return; + } + } catch (e) { + console.error(e); + } + } + processDependencyForResolving(dep); + }; - if (typeof schema.minimum === "number") { - range.left(schema.minimum); - } + /** + * @param {Dependency} dep dependency + * @returns {void} + */ + const processDependencyForResolving = dep => { + const resourceIdent = dep.getResourceIdentifier(); + if (resourceIdent !== undefined && resourceIdent !== null) { + const category = dep.category; + const constructor = /** @type {DepConstructor} */ (dep.constructor); + if (factoryCacheKey === constructor) { + // Fast path 1: same constructor as prev item + if (listCacheKey1 === category && listCacheKey2 === resourceIdent) { + // Super fast path 1: also same resource + listCacheValue.push(dep); + return; + } + } else { + const factory = this.dependencyFactories.get(constructor); + if (factory === undefined) { + throw new Error( + `No module factory available for dependency type: ${constructor.name}` + ); + } + if (factoryCacheKey2 === factory) { + // Fast path 2: same factory as prev item + factoryCacheKey = constructor; + if (listCacheKey1 === category && listCacheKey2 === resourceIdent) { + // Super fast path 2: also same resource + listCacheValue.push(dep); + return; + } + } else { + // Slow path + if (factoryCacheKey2 !== undefined) { + // Archive last cache entry + if (dependencies === undefined) dependencies = new Map(); + dependencies.set(factoryCacheKey2, factoryCacheValue); + factoryCacheValue = dependencies.get(factory); + if (factoryCacheValue === undefined) { + factoryCacheValue = new Map(); + } + } else { + factoryCacheValue = new Map(); + } + factoryCacheKey = constructor; + factoryCacheKey2 = factory; + } + } + // Here webpack is using heuristic that assumes + // mostly esm dependencies would be used + // so we don't allocate extra string for them + const cacheKey = + category === esmDependencyCategory + ? resourceIdent + : `${category}${resourceIdent}`; + let list = factoryCacheValue.get(cacheKey); + if (list === undefined) { + factoryCacheValue.set(cacheKey, (list = [])); + sortedDependencies.push({ + factory: factoryCacheKey2, + dependencies: list, + originModule: module + }); + } + list.push(dep); + listCacheKey1 = category; + listCacheKey2 = resourceIdent; + listCacheValue = list; + } + }; - if (typeof schema.exclusiveMinimum === "number") { - range.left(schema.exclusiveMinimum, true); - } + try { + /** @type {DependenciesBlock[]} */ + const queue = [module]; + do { + const block = queue.pop(); + if (block.dependencies) { + currentBlock = block; + let i = 0; + for (const dep of block.dependencies) processDependency(dep, i++); + } + if (block.blocks) { + for (const b of block.blocks) queue.push(b); + } + } while (queue.length !== 0); + } catch (e) { + return callback(e); + } - if (typeof schema.maximum === "number") { - range.right(schema.maximum); - } + if (--inProgressSorting === 0) onDependenciesSorted(); + } - if (typeof schema.exclusiveMaximum === "number") { - range.right(schema.exclusiveMaximum, true); - } + _handleNewModuleFromUnsafeCache(originModule, dependency, module, callback) { + const moduleGraph = this.moduleGraph; - const rangeFormat = range.format(logic); + moduleGraph.setResolvedModule(originModule, dependency, module); - if (rangeFormat) { - hints.push(rangeFormat); - } + moduleGraph.setIssuerIfUnset( + module, + originModule !== undefined ? originModule : null + ); - if (typeof schema.multipleOf === "number") { - hints.push(`should${logic ? "" : " not"} be multiple of ${schema.multipleOf}`); - } + this._modules.set(module.identifier(), module); + this.modules.add(module); + if (this._backCompat) + ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); - return hints; -}; + this._handleModuleBuildAndDependencies( + originModule, + module, + true, + callback + ); + } -/***/ }), + _handleExistingModuleFromUnsafeCache(originModule, dependency, module) { + const moduleGraph = this.moduleGraph; -/***/ 18151: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + moduleGraph.setResolvedModule(originModule, dependency, module); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @typedef {Object} HandleModuleCreationOptions + * @property {ModuleFactory} factory + * @property {Dependency[]} dependencies + * @property {Module | null} originModule + * @property {Partial=} contextInfo + * @property {string=} context + * @property {boolean=} recursive recurse into dependencies of the created module + * @property {boolean=} connectOrigin connect the resolved module with the origin module + */ + /** + * @param {HandleModuleCreationOptions} options options object + * @param {ModuleCallback} callback callback + * @returns {void} + */ + handleModuleCreation( + { + factory, + dependencies, + originModule, + contextInfo, + context, + recursive = true, + connectOrigin = recursive + }, + callback + ) { + const moduleGraph = this.moduleGraph; -const Hook = __webpack_require__(21468); -const HookCodeFactory = __webpack_require__(66443); + const currentProfile = this.profile ? new ModuleProfile() : undefined; -class AsyncParallelBailHookCodeFactory extends HookCodeFactory { - content({ onError, onResult, onDone }) { - let code = ""; - code += `var _results = new Array(${this.options.taps.length});\n`; - code += "var _checkDone = function() {\n"; - code += "for(var i = 0; i < _results.length; i++) {\n"; - code += "var item = _results[i];\n"; - code += "if(item === undefined) return false;\n"; - code += "if(item.result !== undefined) {\n"; - code += onResult("item.result"); - code += "return true;\n"; - code += "}\n"; - code += "if(item.error) {\n"; - code += onError("item.error"); - code += "return true;\n"; - code += "}\n"; - code += "}\n"; - code += "return false;\n"; - code += "}\n"; - code += this.callTapsParallel({ - onError: (i, err, done, doneBreak) => { - let code = ""; - code += `if(${i} < _results.length && ((_results.length = ${i + - 1}), (_results[${i}] = { error: ${err} }), _checkDone())) {\n`; - code += doneBreak(true); - code += "} else {\n"; - code += done(); - code += "}\n"; - return code; - }, - onResult: (i, result, done, doneBreak) => { - let code = ""; - code += `if(${i} < _results.length && (${result} !== undefined && (_results.length = ${i + - 1}), (_results[${i}] = { result: ${result} }), _checkDone())) {\n`; - code += doneBreak(true); - code += "} else {\n"; - code += done(); - code += "}\n"; - return code; + this.factorizeModule( + { + currentProfile, + factory, + dependencies, + factoryResult: true, + originModule, + contextInfo, + context }, - onTap: (i, run, done, doneBreak) => { - let code = ""; - if (i > 0) { - code += `if(${i} >= _results.length) {\n`; - code += done(); - code += "} else {\n"; + (err, factoryResult) => { + const applyFactoryResultDependencies = () => { + const { fileDependencies, contextDependencies, missingDependencies } = + factoryResult; + if (fileDependencies) { + this.fileDependencies.addAll(fileDependencies); + } + if (contextDependencies) { + this.contextDependencies.addAll(contextDependencies); + } + if (missingDependencies) { + this.missingDependencies.addAll(missingDependencies); + } + }; + if (err) { + if (factoryResult) applyFactoryResultDependencies(); + if (dependencies.every(d => d.optional)) { + this.warnings.push(err); + return callback(); + } else { + this.errors.push(err); + return callback(err); + } } - code += run(); - if (i > 0) code += "}\n"; - return code; - }, - onDone - }); - return code; - } -} - -const factory = new AsyncParallelBailHookCodeFactory(); - -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; - -function AsyncParallelBailHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = AsyncParallelBailHook; - hook.compile = COMPILE; - hook._call = undefined; - hook.call = undefined; - return hook; -} - -AsyncParallelBailHook.prototype = null; -module.exports = AsyncParallelBailHook; + const newModule = factoryResult.module; + if (!newModule) { + applyFactoryResultDependencies(); + return callback(); + } -/***/ }), + if (currentProfile !== undefined) { + moduleGraph.setProfile(newModule, currentProfile); + } -/***/ 31684: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.addModule(newModule, (err, module) => { + if (err) { + applyFactoryResultDependencies(); + if (!err.module) { + err.module = module; + } + this.errors.push(err); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return callback(err); + } + if ( + this._unsafeCache && + factoryResult.cacheable !== false && + /** @type {any} */ (module).restoreFromUnsafeCache && + this._unsafeCachePredicate(module) + ) { + const unsafeCacheableModule = + /** @type {Module & { restoreFromUnsafeCache: Function }} */ ( + module + ); + for (let i = 0; i < dependencies.length; i++) { + const dependency = dependencies[i]; + moduleGraph.setResolvedModule( + connectOrigin ? originModule : null, + dependency, + unsafeCacheableModule + ); + unsafeCacheDependencies.set(dependency, unsafeCacheableModule); + } + if (!unsafeCacheData.has(unsafeCacheableModule)) { + unsafeCacheData.set( + unsafeCacheableModule, + unsafeCacheableModule.getUnsafeCacheData() + ); + } + } else { + applyFactoryResultDependencies(); + for (let i = 0; i < dependencies.length; i++) { + const dependency = dependencies[i]; + moduleGraph.setResolvedModule( + connectOrigin ? originModule : null, + dependency, + module + ); + } + } -const Hook = __webpack_require__(21468); -const HookCodeFactory = __webpack_require__(66443); + moduleGraph.setIssuerIfUnset( + module, + originModule !== undefined ? originModule : null + ); + if (module !== newModule) { + if (currentProfile !== undefined) { + const otherProfile = moduleGraph.getProfile(module); + if (otherProfile !== undefined) { + currentProfile.mergeInto(otherProfile); + } else { + moduleGraph.setProfile(module, currentProfile); + } + } + } -class AsyncParallelHookCodeFactory extends HookCodeFactory { - content({ onError, onDone }) { - return this.callTapsParallel({ - onError: (i, err, done, doneBreak) => onError(err) + doneBreak(true), - onDone - }); + this._handleModuleBuildAndDependencies( + originModule, + module, + recursive, + callback + ); + }); + } + ); } -} - -const factory = new AsyncParallelHookCodeFactory(); - -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; - -function AsyncParallelHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = AsyncParallelHook; - hook.compile = COMPILE; - hook._call = undefined; - hook.call = undefined; - return hook; -} - -AsyncParallelHook.prototype = null; - -module.exports = AsyncParallelHook; + _handleModuleBuildAndDependencies(originModule, module, recursive, callback) { + // Check for cycles when build is trigger inside another build + let creatingModuleDuringBuildSet = undefined; + if (!recursive && this.buildQueue.isProcessing(originModule)) { + // Track build dependency + creatingModuleDuringBuildSet = + this.creatingModuleDuringBuild.get(originModule); + if (creatingModuleDuringBuildSet === undefined) { + creatingModuleDuringBuildSet = new Set(); + this.creatingModuleDuringBuild.set( + originModule, + creatingModuleDuringBuildSet + ); + } + creatingModuleDuringBuildSet.add(module); -/***/ }), + // When building is blocked by another module + // search for a cycle, cancel the cycle by throwing + // an error (otherwise this would deadlock) + const blockReasons = this.creatingModuleDuringBuild.get(module); + if (blockReasons !== undefined) { + const set = new Set(blockReasons); + for (const item of set) { + const blockReasons = this.creatingModuleDuringBuild.get(item); + if (blockReasons !== undefined) { + for (const m of blockReasons) { + if (m === module) { + return callback(new BuildCycleError(module)); + } + set.add(m); + } + } + } + } + } -/***/ 95734: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.buildModule(module, err => { + if (creatingModuleDuringBuildSet !== undefined) { + creatingModuleDuringBuildSet.delete(module); + } + if (err) { + if (!err.module) { + err.module = module; + } + this.errors.push(err); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return callback(err); + } + if (!recursive) { + this.processModuleDependenciesNonRecursive(module); + callback(null, module); + return; + } -const Hook = __webpack_require__(21468); -const HookCodeFactory = __webpack_require__(66443); + // This avoids deadlocks for circular dependencies + if (this.processDependenciesQueue.isProcessing(module)) { + return callback(); + } -class AsyncSeriesBailHookCodeFactory extends HookCodeFactory { - content({ onError, onResult, resultReturns, onDone }) { - return this.callTapsSeries({ - onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), - onResult: (i, result, next) => - `if(${result} !== undefined) {\n${onResult( - result - )}\n} else {\n${next()}}\n`, - resultReturns, - onDone + this.processModuleDependencies(module, err => { + if (err) { + return callback(err); + } + callback(null, module); + }); }); } -} - -const factory = new AsyncSeriesBailHookCodeFactory(); - -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; - -function AsyncSeriesBailHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = AsyncSeriesBailHook; - hook.compile = COMPILE; - hook._call = undefined; - hook.call = undefined; - return hook; -} - -AsyncSeriesBailHook.prototype = null; - -module.exports = AsyncSeriesBailHook; - - -/***/ }), - -/***/ 96496: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {FactorizeModuleOptions} options options object + * @param {ModuleOrFactoryResultCallback} callback callback + * @returns {void} + */ + _factorizeModule( + { + currentProfile, + factory, + dependencies, + originModule, + factoryResult, + contextInfo, + context + }, + callback + ) { + if (currentProfile !== undefined) { + currentProfile.markFactoryStart(); + } + factory.create( + { + contextInfo: { + issuer: originModule ? originModule.nameForCondition() : "", + issuerLayer: originModule ? originModule.layer : null, + compiler: this.compiler.name, + ...contextInfo + }, + resolveOptions: originModule ? originModule.resolveOptions : undefined, + context: context + ? context + : originModule + ? originModule.context + : this.compiler.context, + dependencies: dependencies + }, + (err, result) => { + if (result) { + // TODO webpack 6: remove + // For backward-compat + if (result.module === undefined && result instanceof Module) { + result = { + module: result + }; + } + if (!factoryResult) { + const { + fileDependencies, + contextDependencies, + missingDependencies + } = result; + if (fileDependencies) { + this.fileDependencies.addAll(fileDependencies); + } + if (contextDependencies) { + this.contextDependencies.addAll(contextDependencies); + } + if (missingDependencies) { + this.missingDependencies.addAll(missingDependencies); + } + } + } + if (err) { + const notFoundError = new ModuleNotFoundError( + originModule, + err, + dependencies.map(d => d.loc).filter(Boolean)[0] + ); + return callback(notFoundError, factoryResult ? result : undefined); + } + if (!result) { + return callback(); + } -const Hook = __webpack_require__(21468); -const HookCodeFactory = __webpack_require__(66443); + if (currentProfile !== undefined) { + currentProfile.markFactoryEnd(); + } -class AsyncSeriesHookCodeFactory extends HookCodeFactory { - content({ onError, onDone }) { - return this.callTapsSeries({ - onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), - onDone - }); + callback(null, factoryResult ? result : result.module); + } + ); } -} -const factory = new AsyncSeriesHookCodeFactory(); + /** + * @param {string} context context string path + * @param {Dependency} dependency dependency used to create Module chain + * @param {ModuleCallback} callback callback for when module chain is complete + * @returns {void} will throw if dependency instance is not a valid Dependency + */ + addModuleChain(context, dependency, callback) { + return this.addModuleTree({ context, dependency }, callback); + } -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; + /** + * @param {Object} options options + * @param {string} options.context context string path + * @param {Dependency} options.dependency dependency used to create Module chain + * @param {Partial=} options.contextInfo additional context info for the root module + * @param {ModuleCallback} callback callback for when module chain is complete + * @returns {void} will throw if dependency instance is not a valid Dependency + */ + addModuleTree({ context, dependency, contextInfo }, callback) { + if ( + typeof dependency !== "object" || + dependency === null || + !dependency.constructor + ) { + return callback( + new WebpackError("Parameter 'dependency' must be a Dependency") + ); + } + const Dep = /** @type {DepConstructor} */ (dependency.constructor); + const moduleFactory = this.dependencyFactories.get(Dep); + if (!moduleFactory) { + return callback( + new WebpackError( + `No dependency factory available for this dependency type: ${dependency.constructor.name}` + ) + ); + } -function AsyncSeriesHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = AsyncSeriesHook; - hook.compile = COMPILE; - hook._call = undefined; - hook.call = undefined; - return hook; -} + this.handleModuleCreation( + { + factory: moduleFactory, + dependencies: [dependency], + originModule: null, + contextInfo, + context + }, + (err, result) => { + if (err && this.bail) { + callback(err); + this.buildQueue.stop(); + this.rebuildQueue.stop(); + this.processDependenciesQueue.stop(); + this.factorizeQueue.stop(); + } else if (!err && result) { + callback(null, result); + } else { + callback(); + } + } + ); + } -AsyncSeriesHook.prototype = null; + /** + * @param {string} context context path for entry + * @param {Dependency} entry entry dependency that should be followed + * @param {string | EntryOptions} optionsOrName options or deprecated name of entry + * @param {ModuleCallback} callback callback function + * @returns {void} returns + */ + addEntry(context, entry, optionsOrName, callback) { + // TODO webpack 6 remove + const options = + typeof optionsOrName === "object" + ? optionsOrName + : { name: optionsOrName }; -module.exports = AsyncSeriesHook; + this._addEntryItem(context, entry, "dependencies", options, callback); + } + /** + * @param {string} context context path for entry + * @param {Dependency} dependency dependency that should be followed + * @param {EntryOptions} options options + * @param {ModuleCallback} callback callback function + * @returns {void} returns + */ + addInclude(context, dependency, options, callback) { + this._addEntryItem( + context, + dependency, + "includeDependencies", + options, + callback + ); + } -/***/ }), + /** + * @param {string} context context path for entry + * @param {Dependency} entry entry dependency that should be followed + * @param {"dependencies" | "includeDependencies"} target type of entry + * @param {EntryOptions} options options + * @param {ModuleCallback} callback callback function + * @returns {void} returns + */ + _addEntryItem(context, entry, target, options, callback) { + const { name } = options; + let entryData = + name !== undefined ? this.entries.get(name) : this.globalEntry; + if (entryData === undefined) { + entryData = { + dependencies: [], + includeDependencies: [], + options: { + name: undefined, + ...options + } + }; + entryData[target].push(entry); + this.entries.set(name, entryData); + } else { + entryData[target].push(entry); + for (const key of Object.keys(options)) { + if (options[key] === undefined) continue; + if (entryData.options[key] === options[key]) continue; + if ( + Array.isArray(entryData.options[key]) && + Array.isArray(options[key]) && + arrayEquals(entryData.options[key], options[key]) + ) { + continue; + } + if (entryData.options[key] === undefined) { + entryData.options[key] = options[key]; + } else { + return callback( + new WebpackError( + `Conflicting entry option ${key} = ${entryData.options[key]} vs ${options[key]}` + ) + ); + } + } + } -/***/ 95999: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.hooks.addEntry.call(entry, options); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.addModuleTree( + { + context, + dependency: entry, + contextInfo: entryData.options.layer + ? { issuerLayer: entryData.options.layer } + : undefined + }, + (err, module) => { + if (err) { + this.hooks.failedEntry.call(entry, options, err); + return callback(err); + } + this.hooks.succeedEntry.call(entry, options, module); + return callback(null, module); + } + ); + } + /** + * @param {Module} module module to be rebuilt + * @param {ModuleCallback} callback callback when module finishes rebuilding + * @returns {void} + */ + rebuildModule(module, callback) { + this.rebuildQueue.add(module, callback); + } -const Hook = __webpack_require__(21468); -const HookCodeFactory = __webpack_require__(66443); + /** + * @param {Module} module module to be rebuilt + * @param {ModuleCallback} callback callback when module finishes rebuilding + * @returns {void} + */ + _rebuildModule(module, callback) { + this.hooks.rebuildModule.call(module); + const oldDependencies = module.dependencies.slice(); + const oldBlocks = module.blocks.slice(); + module.invalidateBuild(); + this.buildQueue.invalidate(module); + this.buildModule(module, err => { + if (err) { + return this.hooks.finishRebuildingModule.callAsync(module, err2 => { + if (err2) { + callback( + makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule") + ); + return; + } + callback(err); + }); + } -class AsyncSeriesLoopHookCodeFactory extends HookCodeFactory { - content({ onError, onDone }) { - return this.callTapsLooping({ - onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), - onDone + this.processDependenciesQueue.invalidate(module); + this.moduleGraph.unfreeze(); + this.processModuleDependencies(module, err => { + if (err) return callback(err); + this.removeReasonsOfDependencyBlock(module, { + dependencies: oldDependencies, + blocks: oldBlocks + }); + this.hooks.finishRebuildingModule.callAsync(module, err2 => { + if (err2) { + callback( + makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule") + ); + return; + } + callback(null, module); + }); + }); }); } -} - -const factory = new AsyncSeriesLoopHookCodeFactory(); -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; - -function AsyncSeriesLoopHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = AsyncSeriesLoopHook; - hook.compile = COMPILE; - hook._call = undefined; - hook.call = undefined; - return hook; -} + _computeAffectedModules(modules) { + const moduleMemCacheCache = this.compiler.moduleMemCaches; + if (!moduleMemCacheCache) return; + if (!this.moduleMemCaches) { + this.moduleMemCaches = new Map(); + this.moduleGraph.setModuleMemCaches(this.moduleMemCaches); + } + const { moduleGraph, moduleMemCaches } = this; + const affectedModules = new Set(); + const infectedModules = new Set(); + let statNew = 0; + let statChanged = 0; + let statUnchanged = 0; + let statReferencesChanged = 0; + let statWithoutBuild = 0; -AsyncSeriesLoopHook.prototype = null; + const computeReferences = module => { + /** @type {WeakMap} */ + let references = undefined; + for (const connection of moduleGraph.getOutgoingConnections(module)) { + const d = connection.dependency; + const m = connection.module; + if (!d || !m || unsafeCacheDependencies.has(d)) continue; + if (references === undefined) references = new WeakMap(); + references.set(d, m); + } + return references; + }; -module.exports = AsyncSeriesLoopHook; + /** + * @param {Module} module the module + * @param {WeakMap} references references + * @returns {boolean} true, when the references differ + */ + const compareReferences = (module, references) => { + if (references === undefined) return true; + for (const connection of moduleGraph.getOutgoingConnections(module)) { + const d = connection.dependency; + if (!d) continue; + const entry = references.get(d); + if (entry === undefined) continue; + if (entry !== connection.module) return false; + } + return true; + }; + const modulesWithoutCache = new Set(modules); + for (const [module, cachedMemCache] of moduleMemCacheCache) { + if (modulesWithoutCache.has(module)) { + const buildInfo = module.buildInfo; + if (buildInfo) { + if (cachedMemCache.buildInfo !== buildInfo) { + // use a new one + const memCache = new WeakTupleMap(); + moduleMemCaches.set(module, memCache); + affectedModules.add(module); + cachedMemCache.buildInfo = buildInfo; + cachedMemCache.references = computeReferences(module); + cachedMemCache.memCache = memCache; + statChanged++; + } else if (!compareReferences(module, cachedMemCache.references)) { + // use a new one + const memCache = new WeakTupleMap(); + moduleMemCaches.set(module, memCache); + affectedModules.add(module); + cachedMemCache.references = computeReferences(module); + cachedMemCache.memCache = memCache; + statReferencesChanged++; + } else { + // keep the old mem cache + moduleMemCaches.set(module, cachedMemCache.memCache); + statUnchanged++; + } + } else { + infectedModules.add(module); + moduleMemCacheCache.delete(module); + statWithoutBuild++; + } + modulesWithoutCache.delete(module); + } else { + moduleMemCacheCache.delete(module); + } + } -/***/ }), - -/***/ 58118: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + for (const module of modulesWithoutCache) { + const buildInfo = module.buildInfo; + if (buildInfo) { + // create a new entry + const memCache = new WeakTupleMap(); + moduleMemCacheCache.set(module, { + buildInfo, + references: computeReferences(module), + memCache + }); + moduleMemCaches.set(module, memCache); + affectedModules.add(module); + statNew++; + } else { + infectedModules.add(module); + statWithoutBuild++; + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const reduceAffectType = connections => { + let affected = false; + for (const { dependency } of connections) { + if (!dependency) continue; + const type = dependency.couldAffectReferencingModule(); + if (type === Dependency.TRANSITIVE) return Dependency.TRANSITIVE; + if (type === false) continue; + affected = true; + } + return affected; + }; + const directOnlyInfectedModules = new Set(); + for (const module of infectedModules) { + for (const [ + referencingModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if (!referencingModule) continue; + if (infectedModules.has(referencingModule)) continue; + const type = reduceAffectType(connections); + if (!type) continue; + if (type === true) { + directOnlyInfectedModules.add(referencingModule); + } else { + infectedModules.add(referencingModule); + } + } + } + for (const module of directOnlyInfectedModules) infectedModules.add(module); + const directOnlyAffectModules = new Set(); + for (const module of affectedModules) { + for (const [ + referencingModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if (!referencingModule) continue; + if (infectedModules.has(referencingModule)) continue; + if (affectedModules.has(referencingModule)) continue; + const type = reduceAffectType(connections); + if (!type) continue; + if (type === true) { + directOnlyAffectModules.add(referencingModule); + } else { + affectedModules.add(referencingModule); + } + const memCache = new WeakTupleMap(); + const cache = moduleMemCacheCache.get(referencingModule); + cache.memCache = memCache; + moduleMemCaches.set(referencingModule, memCache); + } + } + for (const module of directOnlyAffectModules) affectedModules.add(module); + this.logger.log( + `${Math.round( + (100 * (affectedModules.size + infectedModules.size)) / + this.modules.size + )}% (${affectedModules.size} affected + ${ + infectedModules.size + } infected of ${ + this.modules.size + }) modules flagged as affected (${statNew} new modules, ${statChanged} changed, ${statReferencesChanged} references changed, ${statUnchanged} unchanged, ${statWithoutBuild} were not built)` + ); + } + _computeAffectedModulesWithChunkGraph() { + const { moduleMemCaches } = this; + if (!moduleMemCaches) return; + const moduleMemCaches2 = (this.moduleMemCaches2 = new Map()); + const { moduleGraph, chunkGraph } = this; + const key = "memCache2"; + let statUnchanged = 0; + let statChanged = 0; + let statNew = 0; + /** + * @param {Module} module module + * @returns {{ id: string | number, modules?: Map, blocks?: (string | number)[] }} references + */ + const computeReferences = module => { + const id = chunkGraph.getModuleId(module); + /** @type {Map} */ + let modules = undefined; + /** @type {(string | number)[] | undefined} */ + let blocks = undefined; + const outgoing = moduleGraph.getOutgoingConnectionsByModule(module); + if (outgoing !== undefined) { + for (const m of outgoing.keys()) { + if (!m) continue; + if (modules === undefined) modules = new Map(); + modules.set(m, chunkGraph.getModuleId(m)); + } + } + if (module.blocks.length > 0) { + blocks = []; + const queue = Array.from(module.blocks); + for (const block of queue) { + const chunkGroup = chunkGraph.getBlockChunkGroup(block); + if (chunkGroup) { + for (const chunk of chunkGroup.chunks) { + blocks.push(chunk.id); + } + } else { + blocks.push(null); + } + queue.push.apply(queue, block.blocks); + } + } + return { id, modules, blocks }; + }; + /** + * @param {Module} module module + * @param {Object} references references + * @param {string | number} references.id id + * @param {Map=} references.modules modules + * @param {(string | number)[]=} references.blocks blocks + * @returns {boolean} ok? + */ + const compareReferences = (module, { id, modules, blocks }) => { + if (id !== chunkGraph.getModuleId(module)) return false; + if (modules !== undefined) { + for (const [module, id] of modules) { + if (chunkGraph.getModuleId(module) !== id) return false; + } + } + if (blocks !== undefined) { + const queue = Array.from(module.blocks); + let i = 0; + for (const block of queue) { + const chunkGroup = chunkGraph.getBlockChunkGroup(block); + if (chunkGroup) { + for (const chunk of chunkGroup.chunks) { + if (i >= blocks.length || blocks[i++] !== chunk.id) return false; + } + } else { + if (i >= blocks.length || blocks[i++] !== null) return false; + } + queue.push.apply(queue, block.blocks); + } + if (i !== blocks.length) return false; + } + return true; + }; -const Hook = __webpack_require__(21468); -const HookCodeFactory = __webpack_require__(66443); + for (const [module, memCache] of moduleMemCaches) { + /** @type {{ references: { id: string | number, modules?: Map, blocks?: (string | number)[]}, memCache: WeakTupleMap }} */ + const cache = memCache.get(key); + if (cache === undefined) { + const memCache2 = new WeakTupleMap(); + memCache.set(key, { + references: computeReferences(module), + memCache: memCache2 + }); + moduleMemCaches2.set(module, memCache2); + statNew++; + } else if (!compareReferences(module, cache.references)) { + const memCache = new WeakTupleMap(); + cache.references = computeReferences(module); + cache.memCache = memCache; + moduleMemCaches2.set(module, memCache); + statChanged++; + } else { + moduleMemCaches2.set(module, cache.memCache); + statUnchanged++; + } + } -class AsyncSeriesWaterfallHookCodeFactory extends HookCodeFactory { - content({ onError, onResult, onDone }) { - return this.callTapsSeries({ - onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), - onResult: (i, result, next) => { - let code = ""; - code += `if(${result} !== undefined) {\n`; - code += `${this._args[0]} = ${result};\n`; - code += `}\n`; - code += next(); - return code; - }, - onDone: () => onResult(this._args[0]) - }); + this.logger.log( + `${Math.round( + (100 * statChanged) / (statNew + statChanged + statUnchanged) + )}% modules flagged as affected by chunk graph (${statNew} new modules, ${statChanged} changed, ${statUnchanged} unchanged)` + ); } -} -const factory = new AsyncSeriesWaterfallHookCodeFactory(); + finish(callback) { + this.factorizeQueue.clear(); + if (this.profile) { + this.logger.time("finish module profiles"); + const ParallelismFactorCalculator = __webpack_require__(50780); + const p = new ParallelismFactorCalculator(); + const moduleGraph = this.moduleGraph; + const modulesWithProfiles = new Map(); + for (const module of this.modules) { + const profile = moduleGraph.getProfile(module); + if (!profile) continue; + modulesWithProfiles.set(module, profile); + p.range( + profile.buildingStartTime, + profile.buildingEndTime, + f => (profile.buildingParallelismFactor = f) + ); + p.range( + profile.factoryStartTime, + profile.factoryEndTime, + f => (profile.factoryParallelismFactor = f) + ); + p.range( + profile.integrationStartTime, + profile.integrationEndTime, + f => (profile.integrationParallelismFactor = f) + ); + p.range( + profile.storingStartTime, + profile.storingEndTime, + f => (profile.storingParallelismFactor = f) + ); + p.range( + profile.restoringStartTime, + profile.restoringEndTime, + f => (profile.restoringParallelismFactor = f) + ); + if (profile.additionalFactoryTimes) { + for (const { start, end } of profile.additionalFactoryTimes) { + const influence = (end - start) / profile.additionalFactories; + p.range( + start, + end, + f => + (profile.additionalFactoriesParallelismFactor += f * influence) + ); + } + } + } + p.calculate(); -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; + const logger = this.getLogger("webpack.Compilation.ModuleProfile"); + const logByValue = (value, msg) => { + if (value > 1000) { + logger.error(msg); + } else if (value > 500) { + logger.warn(msg); + } else if (value > 200) { + logger.info(msg); + } else if (value > 30) { + logger.log(msg); + } else { + logger.debug(msg); + } + }; + const logNormalSummary = (category, getDuration, getParallelism) => { + let sum = 0; + let max = 0; + for (const [module, profile] of modulesWithProfiles) { + const p = getParallelism(profile); + const d = getDuration(profile); + if (d === 0 || p === 0) continue; + const t = d / p; + sum += t; + if (t <= 10) continue; + logByValue( + t, + ` | ${Math.round(t)} ms${ + p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : "" + } ${category} > ${module.readableIdentifier(this.requestShortener)}` + ); + max = Math.max(max, t); + } + if (sum <= 10) return; + logByValue( + Math.max(sum / 10, max), + `${Math.round(sum)} ms ${category}` + ); + }; + const logByLoadersSummary = (category, getDuration, getParallelism) => { + const map = new Map(); + for (const [module, profile] of modulesWithProfiles) { + const list = provide( + map, + module.type + "!" + module.identifier().replace(/(!|^)[^!]*$/, ""), + () => [] + ); + list.push({ module, profile }); + } -function AsyncSeriesWaterfallHook(args = [], name = undefined) { - if (args.length < 1) - throw new Error("Waterfall hooks must have at least one argument"); - const hook = new Hook(args, name); - hook.constructor = AsyncSeriesWaterfallHook; - hook.compile = COMPILE; - hook._call = undefined; - hook.call = undefined; - return hook; -} + let sum = 0; + let max = 0; + for (const [key, modules] of map) { + let innerSum = 0; + let innerMax = 0; + for (const { module, profile } of modules) { + const p = getParallelism(profile); + const d = getDuration(profile); + if (d === 0 || p === 0) continue; + const t = d / p; + innerSum += t; + if (t <= 10) continue; + logByValue( + t, + ` | | ${Math.round(t)} ms${ + p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : "" + } ${category} > ${module.readableIdentifier( + this.requestShortener + )}` + ); + innerMax = Math.max(innerMax, t); + } + sum += innerSum; + if (innerSum <= 10) continue; + const idx = key.indexOf("!"); + const loaders = key.slice(idx + 1); + const moduleType = key.slice(0, idx); + const t = Math.max(innerSum / 10, innerMax); + logByValue( + t, + ` | ${Math.round(innerSum)} ms ${category} > ${ + loaders + ? `${ + modules.length + } x ${moduleType} with ${this.requestShortener.shorten( + loaders + )}` + : `${modules.length} x ${moduleType}` + }` + ); + max = Math.max(max, t); + } + if (sum <= 10) return; + logByValue( + Math.max(sum / 10, max), + `${Math.round(sum)} ms ${category}` + ); + }; + logNormalSummary( + "resolve to new modules", + p => p.factory, + p => p.factoryParallelismFactor + ); + logNormalSummary( + "resolve to existing modules", + p => p.additionalFactories, + p => p.additionalFactoriesParallelismFactor + ); + logNormalSummary( + "integrate modules", + p => p.restoring, + p => p.restoringParallelismFactor + ); + logByLoadersSummary( + "build modules", + p => p.building, + p => p.buildingParallelismFactor + ); + logNormalSummary( + "store modules", + p => p.storing, + p => p.storingParallelismFactor + ); + logNormalSummary( + "restore modules", + p => p.restoring, + p => p.restoringParallelismFactor + ); + this.logger.timeEnd("finish module profiles"); + } + this.logger.time("compute affected modules"); + this._computeAffectedModules(this.modules); + this.logger.timeEnd("compute affected modules"); + this.logger.time("finish modules"); + const { modules, moduleMemCaches } = this; + this.hooks.finishModules.callAsync(modules, err => { + this.logger.timeEnd("finish modules"); + if (err) return callback(err); -AsyncSeriesWaterfallHook.prototype = null; + // extract warnings and errors from modules + this.moduleGraph.freeze("dependency errors"); + // TODO keep a cacheToken (= {}) for each module in the graph + // create a new one per compilation and flag all updated files + // and parents with it + this.logger.time("report dependency errors and warnings"); + for (const module of modules) { + // TODO only run for modules with changed cacheToken + // global WeakMap> to keep modules without errors/warnings + const memCache = moduleMemCaches && moduleMemCaches.get(module); + if (memCache && memCache.get("noWarningsOrErrors")) continue; + let hasProblems = this.reportDependencyErrorsAndWarnings(module, [ + module + ]); + const errors = module.getErrors(); + if (errors !== undefined) { + for (const error of errors) { + if (!error.module) { + error.module = module; + } + this.errors.push(error); + hasProblems = true; + } + } + const warnings = module.getWarnings(); + if (warnings !== undefined) { + for (const warning of warnings) { + if (!warning.module) { + warning.module = module; + } + this.warnings.push(warning); + hasProblems = true; + } + } + if (!hasProblems && memCache) memCache.set("noWarningsOrErrors", true); + } + this.moduleGraph.unfreeze(); + this.logger.timeEnd("report dependency errors and warnings"); -module.exports = AsyncSeriesWaterfallHook; + callback(); + }); + } + unseal() { + this.hooks.unseal.call(); + this.chunks.clear(); + this.chunkGroups.length = 0; + this.namedChunks.clear(); + this.namedChunkGroups.clear(); + this.entrypoints.clear(); + this.additionalChunkAssets.length = 0; + this.assets = {}; + this.assetsInfo.clear(); + this.moduleGraph.removeAllModuleAttributes(); + this.moduleGraph.unfreeze(); + this.moduleMemCaches2 = undefined; + } -/***/ }), + /** + * @param {Callback} callback signals when the call finishes + * @returns {void} + */ + seal(callback) { + const finalCallback = err => { + this.factorizeQueue.clear(); + this.buildQueue.clear(); + this.rebuildQueue.clear(); + this.processDependenciesQueue.clear(); + this.addModuleQueue.clear(); + return callback(err); + }; + const chunkGraph = new ChunkGraph( + this.moduleGraph, + this.outputOptions.hashFunction + ); + this.chunkGraph = chunkGraph; -/***/ 21468: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (this._backCompat) { + for (const module of this.modules) { + ChunkGraph.setChunkGraphForModule(module, chunkGraph); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.hooks.seal.call(); + this.logger.time("optimize dependencies"); + while (this.hooks.optimizeDependencies.call(this.modules)) { + /* empty */ + } + this.hooks.afterOptimizeDependencies.call(this.modules); + this.logger.timeEnd("optimize dependencies"); -const util = __webpack_require__(73837); + this.logger.time("create chunks"); + this.hooks.beforeChunks.call(); + this.moduleGraph.freeze("seal"); + /** @type {Map} */ + const chunkGraphInit = new Map(); + for (const [name, { dependencies, includeDependencies, options }] of this + .entries) { + const chunk = this.addChunk(name); + if (options.filename) { + chunk.filenameTemplate = options.filename; + } + const entrypoint = new Entrypoint(options); + if (!options.dependOn && !options.runtime) { + entrypoint.setRuntimeChunk(chunk); + } + entrypoint.setEntrypointChunk(chunk); + this.namedChunkGroups.set(name, entrypoint); + this.entrypoints.set(name, entrypoint); + this.chunkGroups.push(entrypoint); + connectChunkGroupAndChunk(entrypoint, chunk); -const deprecateContext = util.deprecate(() => {}, -"Hook.context is deprecated and will be removed"); + const entryModules = new Set(); + for (const dep of [...this.globalEntry.dependencies, ...dependencies]) { + entrypoint.addOrigin(null, { name }, /** @type {any} */ (dep).request); -const CALL_DELEGATE = function(...args) { - this.call = this._createCall("sync"); - return this.call(...args); -}; -const CALL_ASYNC_DELEGATE = function(...args) { - this.callAsync = this._createCall("async"); - return this.callAsync(...args); -}; -const PROMISE_DELEGATE = function(...args) { - this.promise = this._createCall("promise"); - return this.promise(...args); -}; + const module = this.moduleGraph.getModule(dep); + if (module) { + chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint); + entryModules.add(module); + const modulesList = chunkGraphInit.get(entrypoint); + if (modulesList === undefined) { + chunkGraphInit.set(entrypoint, [module]); + } else { + modulesList.push(module); + } + } + } -class Hook { - constructor(args = [], name = undefined) { - this._args = args; - this.name = name; - this.taps = []; - this.interceptors = []; - this._call = CALL_DELEGATE; - this.call = CALL_DELEGATE; - this._callAsync = CALL_ASYNC_DELEGATE; - this.callAsync = CALL_ASYNC_DELEGATE; - this._promise = PROMISE_DELEGATE; - this.promise = PROMISE_DELEGATE; - this._x = undefined; + this.assignDepths(entryModules); - this.compile = this.compile; - this.tap = this.tap; - this.tapAsync = this.tapAsync; - this.tapPromise = this.tapPromise; - } + const mapAndSort = deps => + deps + .map(dep => this.moduleGraph.getModule(dep)) + .filter(Boolean) + .sort(compareModulesByIdentifier); + const includedModules = [ + ...mapAndSort(this.globalEntry.includeDependencies), + ...mapAndSort(includeDependencies) + ]; - compile(options) { - throw new Error("Abstract: should be overridden"); - } + let modulesList = chunkGraphInit.get(entrypoint); + if (modulesList === undefined) { + chunkGraphInit.set(entrypoint, (modulesList = [])); + } + for (const module of includedModules) { + this.assignDepth(module); + modulesList.push(module); + } + } + const runtimeChunks = new Set(); + outer: for (const [ + name, + { + options: { dependOn, runtime } + } + ] of this.entries) { + if (dependOn && runtime) { + const err = + new WebpackError(`Entrypoint '${name}' has 'dependOn' and 'runtime' specified. This is not valid. +Entrypoints that depend on other entrypoints do not have their own runtime. +They will use the runtime(s) from referenced entrypoints instead. +Remove the 'runtime' option from the entrypoint.`); + const entry = this.entrypoints.get(name); + err.chunk = entry.getEntrypointChunk(); + this.errors.push(err); + } + if (dependOn) { + const entry = this.entrypoints.get(name); + const referencedChunks = entry + .getEntrypointChunk() + .getAllReferencedChunks(); + const dependOnEntries = []; + for (const dep of dependOn) { + const dependency = this.entrypoints.get(dep); + if (!dependency) { + throw new Error( + `Entry ${name} depends on ${dep}, but this entry was not found` + ); + } + if (referencedChunks.has(dependency.getEntrypointChunk())) { + const err = new WebpackError( + `Entrypoints '${name}' and '${dep}' use 'dependOn' to depend on each other in a circular way.` + ); + const entryChunk = entry.getEntrypointChunk(); + err.chunk = entryChunk; + this.errors.push(err); + entry.setRuntimeChunk(entryChunk); + continue outer; + } + dependOnEntries.push(dependency); + } + for (const dependency of dependOnEntries) { + connectChunkGroupParentAndChild(dependency, entry); + } + } else if (runtime) { + const entry = this.entrypoints.get(name); + let chunk = this.namedChunks.get(runtime); + if (chunk) { + if (!runtimeChunks.has(chunk)) { + const err = + new WebpackError(`Entrypoint '${name}' has a 'runtime' option which points to another entrypoint named '${runtime}'. +It's not valid to use other entrypoints as runtime chunk. +Did you mean to use 'dependOn: ${JSON.stringify( + runtime + )}' instead to allow using entrypoint '${name}' within the runtime of entrypoint '${runtime}'? For this '${runtime}' must always be loaded when '${name}' is used. +Or do you want to use the entrypoints '${name}' and '${runtime}' independently on the same page with a shared runtime? In this case give them both the same value for the 'runtime' option. It must be a name not already used by an entrypoint.`); + const entryChunk = entry.getEntrypointChunk(); + err.chunk = entryChunk; + this.errors.push(err); + entry.setRuntimeChunk(entryChunk); + continue; + } + } else { + chunk = this.addChunk(runtime); + chunk.preventIntegration = true; + runtimeChunks.add(chunk); + } + entry.unshiftChunk(chunk); + chunk.addGroup(entry); + entry.setRuntimeChunk(chunk); + } + } + buildChunkGraph(this, chunkGraphInit); + this.hooks.afterChunks.call(this.chunks); + this.logger.timeEnd("create chunks"); - _createCall(type) { - return this.compile({ - taps: this.taps, - interceptors: this.interceptors, - args: this._args, - type: type - }); - } + this.logger.time("optimize"); + this.hooks.optimize.call(); - _tap(type, options, fn) { - if (typeof options === "string") { - options = { - name: options.trim() - }; - } else if (typeof options !== "object" || options === null) { - throw new Error("Invalid tap options"); - } - if (typeof options.name !== "string" || options.name === "") { - throw new Error("Missing name for tap"); + while (this.hooks.optimizeModules.call(this.modules)) { + /* empty */ } - if (typeof options.context !== "undefined") { - deprecateContext(); + this.hooks.afterOptimizeModules.call(this.modules); + + while (this.hooks.optimizeChunks.call(this.chunks, this.chunkGroups)) { + /* empty */ } - options = Object.assign({ type, fn }, options); - options = this._runRegisterInterceptors(options); - this._insert(options); - } + this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups); - tap(options, fn) { - this._tap("sync", options, fn); - } + this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => { + if (err) { + return finalCallback( + makeWebpackError(err, "Compilation.hooks.optimizeTree") + ); + } - tapAsync(options, fn) { - this._tap("async", options, fn); - } + this.hooks.afterOptimizeTree.call(this.chunks, this.modules); - tapPromise(options, fn) { - this._tap("promise", options, fn); - } + this.hooks.optimizeChunkModules.callAsync( + this.chunks, + this.modules, + err => { + if (err) { + return finalCallback( + makeWebpackError(err, "Compilation.hooks.optimizeChunkModules") + ); + } - _runRegisterInterceptors(options) { - for (const interceptor of this.interceptors) { - if (interceptor.register) { - const newOptions = interceptor.register(options); - if (newOptions !== undefined) { - options = newOptions; - } - } - } - return options; - } + this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules); - withOptions(options) { - const mergeOptions = opt => - Object.assign({}, options, typeof opt === "string" ? { name: opt } : opt); + const shouldRecord = this.hooks.shouldRecord.call() !== false; - return { - name: this.name, - tap: (opt, fn) => this.tap(mergeOptions(opt), fn), - tapAsync: (opt, fn) => this.tapAsync(mergeOptions(opt), fn), - tapPromise: (opt, fn) => this.tapPromise(mergeOptions(opt), fn), - intercept: interceptor => this.intercept(interceptor), - isUsed: () => this.isUsed(), - withOptions: opt => this.withOptions(mergeOptions(opt)) - }; - } + this.hooks.reviveModules.call(this.modules, this.records); + this.hooks.beforeModuleIds.call(this.modules); + this.hooks.moduleIds.call(this.modules); + this.hooks.optimizeModuleIds.call(this.modules); + this.hooks.afterOptimizeModuleIds.call(this.modules); - isUsed() { - return this.taps.length > 0 || this.interceptors.length > 0; - } + this.hooks.reviveChunks.call(this.chunks, this.records); + this.hooks.beforeChunkIds.call(this.chunks); + this.hooks.chunkIds.call(this.chunks); + this.hooks.optimizeChunkIds.call(this.chunks); + this.hooks.afterOptimizeChunkIds.call(this.chunks); - intercept(interceptor) { - this._resetCompilation(); - this.interceptors.push(Object.assign({}, interceptor)); - if (interceptor.register) { - for (let i = 0; i < this.taps.length; i++) { - this.taps[i] = interceptor.register(this.taps[i]); - } - } - } + this.assignRuntimeIds(); - _resetCompilation() { - this.call = this._call; - this.callAsync = this._callAsync; - this.promise = this._promise; - } + this.logger.time("compute affected modules with chunk graph"); + this._computeAffectedModulesWithChunkGraph(); + this.logger.timeEnd("compute affected modules with chunk graph"); - _insert(item) { - this._resetCompilation(); - let before; - if (typeof item.before === "string") { - before = new Set([item.before]); - } else if (Array.isArray(item.before)) { - before = new Set(item.before); - } - let stage = 0; - if (typeof item.stage === "number") { - stage = item.stage; - } - let i = this.taps.length; - while (i > 0) { - i--; - const x = this.taps[i]; - this.taps[i + 1] = x; - const xStage = x.stage || 0; - if (before) { - if (before.has(x.name)) { - before.delete(x.name); - continue; - } - if (before.size > 0) { - continue; - } - } - if (xStage > stage) { - continue; - } - i++; - break; - } - this.taps[i] = item; - } -} + this.sortItemsWithChunkIds(); -Object.setPrototypeOf(Hook.prototype, null); + if (shouldRecord) { + this.hooks.recordModules.call(this.modules, this.records); + this.hooks.recordChunks.call(this.chunks, this.records); + } -module.exports = Hook; + this.hooks.optimizeCodeGeneration.call(this.modules); + this.logger.timeEnd("optimize"); + this.logger.time("module hashing"); + this.hooks.beforeModuleHash.call(); + this.createModuleHashes(); + this.hooks.afterModuleHash.call(); + this.logger.timeEnd("module hashing"); -/***/ }), + this.logger.time("code generation"); + this.hooks.beforeCodeGeneration.call(); + this.codeGeneration(err => { + if (err) { + return finalCallback(err); + } + this.hooks.afterCodeGeneration.call(); + this.logger.timeEnd("code generation"); -/***/ 66443: -/***/ (function(module) { + this.logger.time("runtime requirements"); + this.hooks.beforeRuntimeRequirements.call(); + this.processRuntimeRequirements(); + this.hooks.afterRuntimeRequirements.call(); + this.logger.timeEnd("runtime requirements"); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.logger.time("hashing"); + this.hooks.beforeHash.call(); + const codeGenerationJobs = this.createHash(); + this.hooks.afterHash.call(); + this.logger.timeEnd("hashing"); + this._runCodeGenerationJobs(codeGenerationJobs, err => { + if (err) { + return finalCallback(err); + } -class HookCodeFactory { - constructor(config) { - this.config = config; - this.options = undefined; - this._args = undefined; - } + if (shouldRecord) { + this.logger.time("record hash"); + this.hooks.recordHash.call(this.records); + this.logger.timeEnd("record hash"); + } - create(options) { - this.init(options); - let fn; - switch (this.options.type) { - case "sync": - fn = new Function( - this.args(), - '"use strict";\n' + - this.header() + - this.contentWithInterceptors({ - onError: err => `throw ${err};\n`, - onResult: result => `return ${result};\n`, - resultReturns: true, - onDone: () => "", - rethrowIfPossible: true - }) - ); - break; - case "async": - fn = new Function( - this.args({ - after: "_callback" - }), - '"use strict";\n' + - this.header() + - this.contentWithInterceptors({ - onError: err => `_callback(${err});\n`, - onResult: result => `_callback(null, ${result});\n`, - onDone: () => "_callback();\n" - }) - ); - break; - case "promise": - let errorHelperUsed = false; - const content = this.contentWithInterceptors({ - onError: err => { - errorHelperUsed = true; - return `_error(${err});\n`; - }, - onResult: result => `_resolve(${result});\n`, - onDone: () => "_resolve();\n" - }); - let code = ""; - code += '"use strict";\n'; - code += this.header(); - code += "return new Promise((function(_resolve, _reject) {\n"; - if (errorHelperUsed) { - code += "var _sync = true;\n"; - code += "function _error(_err) {\n"; - code += "if(_sync)\n"; - code += - "_resolve(Promise.resolve().then((function() { throw _err; })));\n"; - code += "else\n"; - code += "_reject(_err);\n"; - code += "};\n"; - } - code += content; - if (errorHelperUsed) { - code += "_sync = false;\n"; - } - code += "}));\n"; - fn = new Function(this.args(), code); - break; - } - this.deinit(); - return fn; - } + this.logger.time("module assets"); + this.clearAssets(); - setup(instance, options) { - instance._x = options.taps.map(t => t.fn); + this.hooks.beforeModuleAssets.call(); + this.createModuleAssets(); + this.logger.timeEnd("module assets"); + + const cont = () => { + this.logger.time("process assets"); + this.hooks.processAssets.callAsync(this.assets, err => { + if (err) { + return finalCallback( + makeWebpackError(err, "Compilation.hooks.processAssets") + ); + } + this.hooks.afterProcessAssets.call(this.assets); + this.logger.timeEnd("process assets"); + this.assets = this._backCompat + ? soonFrozenObjectDeprecation( + this.assets, + "Compilation.assets", + "DEP_WEBPACK_COMPILATION_ASSETS", + `BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation. + Do changes to assets earlier, e. g. in Compilation.hooks.processAssets. + Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.` + ) + : Object.freeze(this.assets); + + this.summarizeDependencies(); + if (shouldRecord) { + this.hooks.record.call(this, this.records); + } + + if (this.hooks.needAdditionalSeal.call()) { + this.unseal(); + return this.seal(callback); + } + return this.hooks.afterSeal.callAsync(err => { + if (err) { + return finalCallback( + makeWebpackError(err, "Compilation.hooks.afterSeal") + ); + } + this.fileSystemInfo.logStatistics(); + finalCallback(); + }); + }); + }; + + this.logger.time("create chunk assets"); + if (this.hooks.shouldGenerateChunkAssets.call() !== false) { + this.hooks.beforeChunkAssets.call(); + this.createChunkAssets(err => { + this.logger.timeEnd("create chunk assets"); + if (err) { + return finalCallback(err); + } + cont(); + }); + } else { + this.logger.timeEnd("create chunk assets"); + cont(); + } + }); + }); + } + ); + }); } /** - * @param {{ type: "sync" | "promise" | "async", taps: Array, interceptors: Array }} options + * @param {Module} module module to report from + * @param {DependenciesBlock[]} blocks blocks to report from + * @returns {boolean} true, when it has warnings or errors */ - init(options) { - this.options = options; - this._args = options.args.slice(); - } + reportDependencyErrorsAndWarnings(module, blocks) { + let hasProblems = false; + for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { + const block = blocks[indexBlock]; + const dependencies = block.dependencies; - deinit() { - this.options = undefined; - this._args = undefined; - } + for (let indexDep = 0; indexDep < dependencies.length; indexDep++) { + const d = dependencies[indexDep]; - contentWithInterceptors(options) { - if (this.options.interceptors.length > 0) { - const onError = options.onError; - const onResult = options.onResult; - const onDone = options.onDone; - let code = ""; - for (let i = 0; i < this.options.interceptors.length; i++) { - const interceptor = this.options.interceptors[i]; - if (interceptor.call) { - code += `${this.getInterceptor(i)}.call(${this.args({ - before: interceptor.context ? "_context" : undefined - })});\n`; + const warnings = d.getWarnings(this.moduleGraph); + if (warnings) { + for (let indexWar = 0; indexWar < warnings.length; indexWar++) { + const w = warnings[indexWar]; + + const warning = new ModuleDependencyWarning(module, w, d.loc); + this.warnings.push(warning); + hasProblems = true; + } + } + const errors = d.getErrors(this.moduleGraph); + if (errors) { + for (let indexErr = 0; indexErr < errors.length; indexErr++) { + const e = errors[indexErr]; + + const error = new ModuleDependencyError(module, e, d.loc); + this.errors.push(error); + hasProblems = true; + } } } - code += this.content( - Object.assign(options, { - onError: - onError && - (err => { - let code = ""; - for (let i = 0; i < this.options.interceptors.length; i++) { - const interceptor = this.options.interceptors[i]; - if (interceptor.error) { - code += `${this.getInterceptor(i)}.error(${err});\n`; - } - } - code += onError(err); - return code; - }), - onResult: - onResult && - (result => { - let code = ""; - for (let i = 0; i < this.options.interceptors.length; i++) { - const interceptor = this.options.interceptors[i]; - if (interceptor.result) { - code += `${this.getInterceptor(i)}.result(${result});\n`; - } - } - code += onResult(result); - return code; - }), - onDone: - onDone && - (() => { - let code = ""; - for (let i = 0; i < this.options.interceptors.length; i++) { - const interceptor = this.options.interceptors[i]; - if (interceptor.done) { - code += `${this.getInterceptor(i)}.done();\n`; - } - } - code += onDone(); - return code; - }) - }) - ); - return code; - } else { - return this.content(options); + + if (this.reportDependencyErrorsAndWarnings(module, block.blocks)) + hasProblems = true; } + return hasProblems; } - header() { - let code = ""; - if (this.needContext()) { - code += "var _context = {};\n"; - } else { - code += "var _context;\n"; - } - code += "var _x = this._x;\n"; - if (this.options.interceptors.length > 0) { - code += "var _taps = this.taps;\n"; - code += "var _interceptors = this.interceptors;\n"; + codeGeneration(callback) { + const { chunkGraph } = this; + this.codeGenerationResults = new CodeGenerationResults( + this.outputOptions.hashFunction + ); + /** @type {{module: Module, hash: string, runtime: RuntimeSpec, runtimes: RuntimeSpec[]}[]} */ + const jobs = []; + for (const module of this.modules) { + const runtimes = chunkGraph.getModuleRuntimes(module); + if (runtimes.size === 1) { + for (const runtime of runtimes) { + const hash = chunkGraph.getModuleHash(module, runtime); + jobs.push({ module, hash, runtime, runtimes: [runtime] }); + } + } else if (runtimes.size > 1) { + /** @type {Map} */ + const map = new Map(); + for (const runtime of runtimes) { + const hash = chunkGraph.getModuleHash(module, runtime); + const job = map.get(hash); + if (job === undefined) { + const newJob = { module, hash, runtime, runtimes: [runtime] }; + jobs.push(newJob); + map.set(hash, newJob); + } else { + job.runtimes.push(runtime); + } + } + } } - return code; + + this._runCodeGenerationJobs(jobs, callback); } - needContext() { - for (const tap of this.options.taps) if (tap.context) return true; - return false; + _runCodeGenerationJobs(jobs, callback) { + let statModulesFromCache = 0; + let statModulesGenerated = 0; + const { chunkGraph, moduleGraph, dependencyTemplates, runtimeTemplate } = + this; + const results = this.codeGenerationResults; + const errors = []; + /** @type {Set | undefined} */ + let notCodeGeneratedModules = undefined; + const runIteration = () => { + let delayedJobs = []; + let delayedModules = new Set(); + asyncLib.eachLimit( + jobs, + this.options.parallelism, + (job, callback) => { + const { module } = job; + const { codeGenerationDependencies } = module; + if (codeGenerationDependencies !== undefined) { + if ( + notCodeGeneratedModules === undefined || + codeGenerationDependencies.some(dep => { + const referencedModule = moduleGraph.getModule(dep); + return notCodeGeneratedModules.has(referencedModule); + }) + ) { + delayedJobs.push(job); + delayedModules.add(module); + return callback(); + } + } + const { hash, runtime, runtimes } = job; + this._codeGenerationModule( + module, + runtime, + runtimes, + hash, + dependencyTemplates, + chunkGraph, + moduleGraph, + runtimeTemplate, + errors, + results, + (err, codeGenerated) => { + if (codeGenerated) statModulesGenerated++; + else statModulesFromCache++; + callback(err); + } + ); + }, + err => { + if (err) return callback(err); + if (delayedJobs.length > 0) { + if (delayedJobs.length === jobs.length) { + return callback( + new Error( + `Unable to make progress during code generation because of circular code generation dependency: ${Array.from( + delayedModules, + m => m.identifier() + ).join(", ")}` + ) + ); + } + jobs = delayedJobs; + delayedJobs = []; + notCodeGeneratedModules = delayedModules; + delayedModules = new Set(); + return runIteration(); + } + if (errors.length > 0) { + errors.sort( + compareSelect(err => err.module, compareModulesByIdentifier) + ); + for (const error of errors) { + this.errors.push(error); + } + } + this.logger.log( + `${Math.round( + (100 * statModulesGenerated) / + (statModulesGenerated + statModulesFromCache) + )}% code generated (${statModulesGenerated} generated, ${statModulesFromCache} from cache)` + ); + callback(); + } + ); + }; + runIteration(); } - callTap(tapIndex, { onError, onResult, onDone, rethrowIfPossible }) { - let code = ""; - let hasTapCached = false; - for (let i = 0; i < this.options.interceptors.length; i++) { - const interceptor = this.options.interceptors[i]; - if (interceptor.tap) { - if (!hasTapCached) { - code += `var _tap${tapIndex} = ${this.getTap(tapIndex)};\n`; - hasTapCached = true; + /** + * @param {Module} module module + * @param {RuntimeSpec} runtime runtime + * @param {RuntimeSpec[]} runtimes runtimes + * @param {string} hash hash + * @param {DependencyTemplates} dependencyTemplates dependencyTemplates + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate + * @param {WebpackError[]} errors errors + * @param {CodeGenerationResults} results results + * @param {function(WebpackError=, boolean=): void} callback callback + */ + _codeGenerationModule( + module, + runtime, + runtimes, + hash, + dependencyTemplates, + chunkGraph, + moduleGraph, + runtimeTemplate, + errors, + results, + callback + ) { + let codeGenerated = false; + const cache = new MultiItemCache( + runtimes.map(runtime => + this._codeGenerationCache.getItemCache( + `${module.identifier()}|${getRuntimeKey(runtime)}`, + `${hash}|${dependencyTemplates.getHash()}` + ) + ) + ); + cache.get((err, cachedResult) => { + if (err) return callback(err); + let result; + if (!cachedResult) { + try { + codeGenerated = true; + this.codeGeneratedModules.add(module); + result = module.codeGeneration({ + chunkGraph, + moduleGraph, + dependencyTemplates, + runtimeTemplate, + runtime, + codeGenerationResults: results + }); + } catch (err) { + errors.push(new CodeGenerationError(module, err)); + result = cachedResult = { + sources: new Map(), + runtimeRequirements: null + }; } - code += `${this.getInterceptor(i)}.tap(${ - interceptor.context ? "_context, " : "" - }_tap${tapIndex});\n`; + } else { + result = cachedResult; + } + for (const runtime of runtimes) { + results.add(module, runtime, result); + } + if (!cachedResult) { + cache.store(result, err => callback(err, codeGenerated)); + } else { + callback(null, codeGenerated); } + }); + } + + _getChunkGraphEntries() { + /** @type {Set} */ + const treeEntries = new Set(); + for (const ep of this.entrypoints.values()) { + const chunk = ep.getRuntimeChunk(); + if (chunk) treeEntries.add(chunk); } - code += `var _fn${tapIndex} = ${this.getTapFn(tapIndex)};\n`; - const tap = this.options.taps[tapIndex]; - switch (tap.type) { - case "sync": - if (!rethrowIfPossible) { - code += `var _hasError${tapIndex} = false;\n`; - code += "try {\n"; - } - if (onResult) { - code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({ - before: tap.context ? "_context" : undefined - })});\n`; - } else { - code += `_fn${tapIndex}(${this.args({ - before: tap.context ? "_context" : undefined - })});\n`; - } - if (!rethrowIfPossible) { - code += "} catch(_err) {\n"; - code += `_hasError${tapIndex} = true;\n`; - code += onError("_err"); - code += "}\n"; - code += `if(!_hasError${tapIndex}) {\n`; - } - if (onResult) { - code += onResult(`_result${tapIndex}`); - } - if (onDone) { - code += onDone(); - } - if (!rethrowIfPossible) { - code += "}\n"; - } - break; - case "async": - let cbCode = ""; - if (onResult) - cbCode += `(function(_err${tapIndex}, _result${tapIndex}) {\n`; - else cbCode += `(function(_err${tapIndex}) {\n`; - cbCode += `if(_err${tapIndex}) {\n`; - cbCode += onError(`_err${tapIndex}`); - cbCode += "} else {\n"; - if (onResult) { - cbCode += onResult(`_result${tapIndex}`); - } - if (onDone) { - cbCode += onDone(); - } - cbCode += "}\n"; - cbCode += "})"; - code += `_fn${tapIndex}(${this.args({ - before: tap.context ? "_context" : undefined, - after: cbCode - })});\n`; - break; - case "promise": - code += `var _hasResult${tapIndex} = false;\n`; - code += `var _promise${tapIndex} = _fn${tapIndex}(${this.args({ - before: tap.context ? "_context" : undefined - })});\n`; - code += `if (!_promise${tapIndex} || !_promise${tapIndex}.then)\n`; - code += ` throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise${tapIndex} + ')');\n`; - code += `_promise${tapIndex}.then((function(_result${tapIndex}) {\n`; - code += `_hasResult${tapIndex} = true;\n`; - if (onResult) { - code += onResult(`_result${tapIndex}`); - } - if (onDone) { - code += onDone(); - } - code += `}), function(_err${tapIndex}) {\n`; - code += `if(_hasResult${tapIndex}) throw _err${tapIndex};\n`; - code += onError(`_err${tapIndex}`); - code += "});\n"; - break; + for (const ep of this.asyncEntrypoints) { + const chunk = ep.getRuntimeChunk(); + if (chunk) treeEntries.add(chunk); } - return code; + return treeEntries; } - callTapsSeries({ - onError, - onResult, - resultReturns, - onDone, - doneReturns, - rethrowIfPossible - }) { - if (this.options.taps.length === 0) return onDone(); - const firstAsync = this.options.taps.findIndex(t => t.type !== "sync"); - const somethingReturns = resultReturns || doneReturns; - let code = ""; - let current = onDone; - let unrollCounter = 0; - for (let j = this.options.taps.length - 1; j >= 0; j--) { - const i = j; - const unroll = - current !== onDone && - (this.options.taps[i].type !== "sync" || unrollCounter++ > 20); - if (unroll) { - unrollCounter = 0; - code += `function _next${i}() {\n`; - code += current(); - code += `}\n`; - current = () => `${somethingReturns ? "return " : ""}_next${i}();\n`; + /** + * @param {Object} options options + * @param {ChunkGraph=} options.chunkGraph the chunk graph + * @param {Iterable=} options.modules modules + * @param {Iterable=} options.chunks chunks + * @param {CodeGenerationResults=} options.codeGenerationResults codeGenerationResults + * @param {Iterable=} options.chunkGraphEntries chunkGraphEntries + * @returns {void} + */ + processRuntimeRequirements({ + chunkGraph = this.chunkGraph, + modules = this.modules, + chunks = this.chunks, + codeGenerationResults = this.codeGenerationResults, + chunkGraphEntries = this._getChunkGraphEntries() + } = {}) { + const context = { chunkGraph, codeGenerationResults }; + const { moduleMemCaches2 } = this; + this.logger.time("runtime requirements.modules"); + const additionalModuleRuntimeRequirements = + this.hooks.additionalModuleRuntimeRequirements; + const runtimeRequirementInModule = this.hooks.runtimeRequirementInModule; + for (const module of modules) { + if (chunkGraph.getNumberOfModuleChunks(module) > 0) { + const memCache = moduleMemCaches2 && moduleMemCaches2.get(module); + for (const runtime of chunkGraph.getModuleRuntimes(module)) { + if (memCache) { + const cached = memCache.get( + `moduleRuntimeRequirements-${getRuntimeKey(runtime)}` + ); + if (cached !== undefined) { + if (cached !== null) { + chunkGraph.addModuleRuntimeRequirements( + module, + runtime, + cached, + false + ); + } + continue; + } + } + let set; + const runtimeRequirements = + codeGenerationResults.getRuntimeRequirements(module, runtime); + if (runtimeRequirements && runtimeRequirements.size > 0) { + set = new Set(runtimeRequirements); + } else if (additionalModuleRuntimeRequirements.isUsed()) { + set = new Set(); + } else { + if (memCache) { + memCache.set( + `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, + null + ); + } + continue; + } + additionalModuleRuntimeRequirements.call(module, set, context); + + for (const r of set) { + const hook = runtimeRequirementInModule.get(r); + if (hook !== undefined) hook.call(module, set, context); + } + if (set.size === 0) { + if (memCache) { + memCache.set( + `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, + null + ); + } + } else { + if (memCache) { + memCache.set( + `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, + set + ); + chunkGraph.addModuleRuntimeRequirements( + module, + runtime, + set, + false + ); + } else { + chunkGraph.addModuleRuntimeRequirements(module, runtime, set); + } + } + } } - const done = current; - const doneBreak = skipDone => { - if (skipDone) return ""; - return onDone(); - }; - const content = this.callTap(i, { - onError: error => onError(i, error, done, doneBreak), - onResult: - onResult && - (result => { - return onResult(i, result, done, doneBreak); - }), - onDone: !onResult && done, - rethrowIfPossible: - rethrowIfPossible && (firstAsync < 0 || i < firstAsync) - }); - current = () => content; } - code += current(); - return code; - } + this.logger.timeEnd("runtime requirements.modules"); - callTapsLooping({ onError, onDone, rethrowIfPossible }) { - if (this.options.taps.length === 0) return onDone(); - const syncOnly = this.options.taps.every(t => t.type === "sync"); - let code = ""; - if (!syncOnly) { - code += "var _looper = (function() {\n"; - code += "var _loopAsync = false;\n"; - } - code += "var _loop;\n"; - code += "do {\n"; - code += "_loop = false;\n"; - for (let i = 0; i < this.options.interceptors.length; i++) { - const interceptor = this.options.interceptors[i]; - if (interceptor.loop) { - code += `${this.getInterceptor(i)}.loop(${this.args({ - before: interceptor.context ? "_context" : undefined - })});\n`; + this.logger.time("runtime requirements.chunks"); + for (const chunk of chunks) { + const set = new Set(); + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( + module, + chunk.runtime + ); + for (const r of runtimeRequirements) set.add(r); } - } - code += this.callTapsSeries({ - onError, - onResult: (i, result, next, doneBreak) => { - let code = ""; - code += `if(${result} !== undefined) {\n`; - code += "_loop = true;\n"; - if (!syncOnly) code += "if(_loopAsync) _looper();\n"; - code += doneBreak(true); - code += `} else {\n`; - code += next(); - code += `}\n`; - return code; - }, - onDone: - onDone && - (() => { - let code = ""; - code += "if(!_loop) {\n"; - code += onDone(); - code += "}\n"; - return code; - }), - rethrowIfPossible: rethrowIfPossible && syncOnly - }); - code += "} while(_loop);\n"; - if (!syncOnly) { - code += "_loopAsync = true;\n"; - code += "});\n"; - code += "_looper();\n"; - } - return code; - } + this.hooks.additionalChunkRuntimeRequirements.call(chunk, set, context); - callTapsParallel({ - onError, - onResult, - onDone, - rethrowIfPossible, - onTap = (i, run) => run() - }) { - if (this.options.taps.length <= 1) { - return this.callTapsSeries({ - onError, - onResult, - onDone, - rethrowIfPossible - }); - } - let code = ""; - code += "do {\n"; - code += `var _counter = ${this.options.taps.length};\n`; - if (onDone) { - code += "var _done = (function() {\n"; - code += onDone(); - code += "});\n"; - } - for (let i = 0; i < this.options.taps.length; i++) { - const done = () => { - if (onDone) return "if(--_counter === 0) _done();\n"; - else return "--_counter;"; - }; - const doneBreak = skipDone => { - if (skipDone || !onDone) return "_counter = 0;\n"; - else return "_counter = 0;\n_done();\n"; - }; - code += "if(_counter <= 0) break;\n"; - code += onTap( - i, - () => - this.callTap(i, { - onError: error => { - let code = ""; - code += "if(_counter > 0) {\n"; - code += onError(i, error, done, doneBreak); - code += "}\n"; - return code; - }, - onResult: - onResult && - (result => { - let code = ""; - code += "if(_counter > 0) {\n"; - code += onResult(i, result, done, doneBreak); - code += "}\n"; - return code; - }), - onDone: - !onResult && - (() => { - return done(); - }), - rethrowIfPossible - }), - done, - doneBreak - ); - } - code += "} while(false);\n"; - return code; - } + for (const r of set) { + this.hooks.runtimeRequirementInChunk.for(r).call(chunk, set, context); + } - args({ before, after } = {}) { - let allArgs = this._args; - if (before) allArgs = [before].concat(allArgs); - if (after) allArgs = allArgs.concat(after); - if (allArgs.length === 0) { - return ""; - } else { - return allArgs.join(", "); + chunkGraph.addChunkRuntimeRequirements(chunk, set); } - } + this.logger.timeEnd("runtime requirements.chunks"); - getTapFn(idx) { - return `_x[${idx}]`; - } + this.logger.time("runtime requirements.entries"); + for (const treeEntry of chunkGraphEntries) { + const set = new Set(); + for (const chunk of treeEntry.getAllReferencedChunks()) { + const runtimeRequirements = + chunkGraph.getChunkRuntimeRequirements(chunk); + for (const r of runtimeRequirements) set.add(r); + } - getTap(idx) { - return `_taps[${idx}]`; - } + this.hooks.additionalTreeRuntimeRequirements.call( + treeEntry, + set, + context + ); - getInterceptor(idx) { - return `_interceptors[${idx}]`; + for (const r of set) { + this.hooks.runtimeRequirementInTree + .for(r) + .call(treeEntry, set, context); + } + + chunkGraph.addTreeRuntimeRequirements(treeEntry, set); + } + this.logger.timeEnd("runtime requirements.entries"); } -} -module.exports = HookCodeFactory; + // TODO webpack 6 make chunkGraph argument non-optional + /** + * @param {Chunk} chunk target chunk + * @param {RuntimeModule} module runtime module + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {void} + */ + addRuntimeModule(chunk, module, chunkGraph = this.chunkGraph) { + // Deprecated ModuleGraph association + if (this._backCompat) + ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); + // add it to the list + this.modules.add(module); + this._modules.set(module.identifier(), module); -/***/ }), + // connect to the chunk graph + chunkGraph.connectChunkAndModule(chunk, module); + chunkGraph.connectChunkAndRuntimeModule(chunk, module); + if (module.fullHash) { + chunkGraph.addFullHashModuleToChunk(chunk, module); + } else if (module.dependentHash) { + chunkGraph.addDependentHashModuleToChunk(chunk, module); + } -/***/ 77079: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // attach runtime module + module.attach(this, chunk, chunkGraph); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // Setup internals + const exportsInfo = this.moduleGraph.getExportsInfo(module); + exportsInfo.setHasProvideInfo(); + if (typeof chunk.runtime === "string") { + exportsInfo.setUsedForSideEffectsOnly(chunk.runtime); + } else if (chunk.runtime === undefined) { + exportsInfo.setUsedForSideEffectsOnly(undefined); + } else { + for (const runtime of chunk.runtime) { + exportsInfo.setUsedForSideEffectsOnly(runtime); + } + } + chunkGraph.addModuleRuntimeRequirements( + module, + chunk.runtime, + new Set([RuntimeGlobals.requireScope]) + ); + // runtime modules don't need ids + chunkGraph.setModuleId(module, ""); -const util = __webpack_require__(73837); + // Call hook + this.hooks.runtimeModule.call(module, chunk); + } -const defaultFactory = (key, hook) => hook; + /** + * If `module` is passed, `loc` and `request` must also be passed. + * @param {string | ChunkGroupOptions} groupOptions options for the chunk group + * @param {Module=} module the module the references the chunk group + * @param {DependencyLocation=} loc the location from with the chunk group is referenced (inside of module) + * @param {string=} request the request from which the the chunk group is referenced + * @returns {ChunkGroup} the new or existing chunk group + */ + addChunkInGroup(groupOptions, module, loc, request) { + if (typeof groupOptions === "string") { + groupOptions = { name: groupOptions }; + } + const name = groupOptions.name; -class HookMap { - constructor(factory, name = undefined) { - this._map = new Map(); - this.name = name; - this._factory = factory; - this._interceptors = []; - } + if (name) { + const chunkGroup = this.namedChunkGroups.get(name); + if (chunkGroup !== undefined) { + chunkGroup.addOptions(groupOptions); + if (module) { + chunkGroup.addOrigin(module, loc, request); + } + return chunkGroup; + } + } + const chunkGroup = new ChunkGroup(groupOptions); + if (module) chunkGroup.addOrigin(module, loc, request); + const chunk = this.addChunk(name); - get(key) { - return this._map.get(key); + connectChunkGroupAndChunk(chunkGroup, chunk); + + this.chunkGroups.push(chunkGroup); + if (name) { + this.namedChunkGroups.set(name, chunkGroup); + } + return chunkGroup; } - for(key) { - const hook = this.get(key); - if (hook !== undefined) { - return hook; + /** + * @param {EntryOptions} options options for the entrypoint + * @param {Module} module the module the references the chunk group + * @param {DependencyLocation} loc the location from with the chunk group is referenced (inside of module) + * @param {string} request the request from which the the chunk group is referenced + * @returns {Entrypoint} the new or existing entrypoint + */ + addAsyncEntrypoint(options, module, loc, request) { + const name = options.name; + if (name) { + const entrypoint = this.namedChunkGroups.get(name); + if (entrypoint instanceof Entrypoint) { + if (entrypoint !== undefined) { + if (module) { + entrypoint.addOrigin(module, loc, request); + } + return entrypoint; + } + } else if (entrypoint) { + throw new Error( + `Cannot add an async entrypoint with the name '${name}', because there is already an chunk group with this name` + ); + } } - let newHook = this._factory(key); - const interceptors = this._interceptors; - for (let i = 0; i < interceptors.length; i++) { - newHook = interceptors[i].factory(key, newHook); + const chunk = this.addChunk(name); + if (options.filename) { + chunk.filenameTemplate = options.filename; } - this._map.set(key, newHook); - return newHook; + const entrypoint = new Entrypoint(options, false); + entrypoint.setRuntimeChunk(chunk); + entrypoint.setEntrypointChunk(chunk); + if (name) { + this.namedChunkGroups.set(name, entrypoint); + } + this.chunkGroups.push(entrypoint); + this.asyncEntrypoints.push(entrypoint); + connectChunkGroupAndChunk(entrypoint, chunk); + if (module) { + entrypoint.addOrigin(module, loc, request); + } + return entrypoint; } - intercept(interceptor) { - this._interceptors.push( - Object.assign( - { - factory: defaultFactory - }, - interceptor - ) - ); + /** + * This method first looks to see if a name is provided for a new chunk, + * and first looks to see if any named chunks already exist and reuse that chunk instead. + * + * @param {string=} name optional chunk name to be provided + * @returns {Chunk} create a chunk (invoked during seal event) + */ + addChunk(name) { + if (name) { + const chunk = this.namedChunks.get(name); + if (chunk !== undefined) { + return chunk; + } + } + const chunk = new Chunk(name, this._backCompat); + this.chunks.add(chunk); + if (this._backCompat) + ChunkGraph.setChunkGraphForChunk(chunk, this.chunkGraph); + if (name) { + this.namedChunks.set(name, chunk); + } + return chunk; } -} - -HookMap.prototype.tap = util.deprecate(function(key, options, fn) { - return this.for(key).tap(options, fn); -}, "HookMap#tap(key,…) is deprecated. Use HookMap#for(key).tap(…) instead."); - -HookMap.prototype.tapAsync = util.deprecate(function(key, options, fn) { - return this.for(key).tapAsync(options, fn); -}, "HookMap#tapAsync(key,…) is deprecated. Use HookMap#for(key).tapAsync(…) instead."); -HookMap.prototype.tapPromise = util.deprecate(function(key, options, fn) { - return this.for(key).tapPromise(options, fn); -}, "HookMap#tapPromise(key,…) is deprecated. Use HookMap#for(key).tapPromise(…) instead."); + /** + * @deprecated + * @param {Module} module module to assign depth + * @returns {void} + */ + assignDepth(module) { + const moduleGraph = this.moduleGraph; -module.exports = HookMap; + const queue = new Set([module]); + let depth; + moduleGraph.setDepth(module, 0); -/***/ }), + /** + * @param {Module} module module for processing + * @returns {void} + */ + const processModule = module => { + if (!moduleGraph.setDepthIfLower(module, depth)) return; + queue.add(module); + }; -/***/ 13103: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + for (module of queue) { + queue.delete(module); + depth = moduleGraph.getDepth(module) + 1; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + for (const connection of moduleGraph.getOutgoingConnections(module)) { + const refModule = connection.module; + if (refModule) { + processModule(refModule); + } + } + } + } + /** + * @param {Set} modules module to assign depth + * @returns {void} + */ + assignDepths(modules) { + const moduleGraph = this.moduleGraph; -const Hook = __webpack_require__(21468); + /** @type {Set} */ + const queue = new Set(modules); + queue.add(1); + let depth = 0; -class MultiHook { - constructor(hooks, name = undefined) { - this.hooks = hooks; - this.name = name; + let i = 0; + for (const module of queue) { + i++; + if (typeof module === "number") { + depth = module; + if (queue.size === i) return; + queue.add(depth + 1); + } else { + moduleGraph.setDepth(module, depth); + for (const { module: refModule } of moduleGraph.getOutgoingConnections( + module + )) { + if (refModule) { + queue.add(refModule); + } + } + } + } } - tap(options, fn) { - for (const hook of this.hooks) { - hook.tap(options, fn); - } + /** + * @param {Dependency} dependency the dependency + * @param {RuntimeSpec} runtime the runtime + * @returns {(string[] | ReferencedExport)[]} referenced exports + */ + getDependencyReferencedExports(dependency, runtime) { + const referencedExports = dependency.getReferencedExports( + this.moduleGraph, + runtime + ); + return this.hooks.dependencyReferencedExports.call( + referencedExports, + dependency, + runtime + ); } - tapAsync(options, fn) { - for (const hook of this.hooks) { - hook.tapAsync(options, fn); + /** + * + * @param {Module} module module relationship for removal + * @param {DependenciesBlockLike} block //TODO: good description + * @returns {void} + */ + removeReasonsOfDependencyBlock(module, block) { + if (block.blocks) { + for (const b of block.blocks) { + this.removeReasonsOfDependencyBlock(module, b); + } } - } - tapPromise(options, fn) { - for (const hook of this.hooks) { - hook.tapPromise(options, fn); + if (block.dependencies) { + for (const dep of block.dependencies) { + const originalModule = this.moduleGraph.getModule(dep); + if (originalModule) { + this.moduleGraph.removeConnection(dep); + + if (this.chunkGraph) { + for (const chunk of this.chunkGraph.getModuleChunks( + originalModule + )) { + this.patchChunksAfterReasonRemoval(originalModule, chunk); + } + } + } + } } } - isUsed() { - for (const hook of this.hooks) { - if (hook.isUsed()) return true; + /** + * @param {Module} module module to patch tie + * @param {Chunk} chunk chunk to patch tie + * @returns {void} + */ + patchChunksAfterReasonRemoval(module, chunk) { + if (!module.hasReasons(this.moduleGraph, chunk.runtime)) { + this.removeReasonsOfDependencyBlock(module, module); + } + if (!module.hasReasonForChunk(chunk, this.moduleGraph, this.chunkGraph)) { + if (this.chunkGraph.isModuleInChunk(module, chunk)) { + this.chunkGraph.disconnectChunkAndModule(chunk, module); + this.removeChunkFromDependencies(module, chunk); + } } - return false; } - intercept(interceptor) { - for (const hook of this.hooks) { - hook.intercept(interceptor); + /** + * + * @param {DependenciesBlock} block block tie for Chunk + * @param {Chunk} chunk chunk to remove from dep + * @returns {void} + */ + removeChunkFromDependencies(block, chunk) { + /** + * @param {Dependency} d dependency to (maybe) patch up + */ + const iteratorDependency = d => { + const depModule = this.moduleGraph.getModule(d); + if (!depModule) { + return; + } + this.patchChunksAfterReasonRemoval(depModule, chunk); + }; + + const blocks = block.blocks; + for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { + const asyncBlock = blocks[indexBlock]; + const chunkGroup = this.chunkGraph.getBlockChunkGroup(asyncBlock); + // Grab all chunks from the first Block's AsyncDepBlock + const chunks = chunkGroup.chunks; + // For each chunk in chunkGroup + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const iteratedChunk = chunks[indexChunk]; + chunkGroup.removeChunk(iteratedChunk); + // Recurse + this.removeChunkFromDependencies(block, iteratedChunk); + } } - } - withOptions(options) { - return new MultiHook( - this.hooks.map(h => h.withOptions(options)), - this.name - ); + if (block.dependencies) { + for (const dep of block.dependencies) iteratorDependency(dep); + } } -} -module.exports = MultiHook; + assignRuntimeIds() { + const { chunkGraph } = this; + const processEntrypoint = ep => { + const runtime = ep.options.runtime || ep.name; + const chunk = ep.getRuntimeChunk(); + chunkGraph.setRuntimeId(runtime, chunk.id); + }; + for (const ep of this.entrypoints.values()) { + processEntrypoint(ep); + } + for (const ep of this.asyncEntrypoints) { + processEntrypoint(ep); + } + } + sortItemsWithChunkIds() { + for (const chunkGroup of this.chunkGroups) { + chunkGroup.sortItems(); + } -/***/ }), + this.errors.sort(compareErrors); + this.warnings.sort(compareErrors); + this.children.sort(byNameOrHash); + } -/***/ 1626: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + summarizeDependencies() { + for ( + let indexChildren = 0; + indexChildren < this.children.length; + indexChildren++ + ) { + const child = this.children[indexChildren]; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.fileDependencies.addAll(child.fileDependencies); + this.contextDependencies.addAll(child.contextDependencies); + this.missingDependencies.addAll(child.missingDependencies); + this.buildDependencies.addAll(child.buildDependencies); + } + for (const module of this.modules) { + module.addCacheDependencies( + this.fileDependencies, + this.contextDependencies, + this.missingDependencies, + this.buildDependencies + ); + } + } -const Hook = __webpack_require__(21468); -const HookCodeFactory = __webpack_require__(66443); + createModuleHashes() { + let statModulesHashed = 0; + let statModulesFromCache = 0; + const { chunkGraph, runtimeTemplate, moduleMemCaches2 } = this; + const { hashFunction, hashDigest, hashDigestLength } = this.outputOptions; + for (const module of this.modules) { + const memCache = moduleMemCaches2 && moduleMemCaches2.get(module); + for (const runtime of chunkGraph.getModuleRuntimes(module)) { + if (memCache) { + const digest = memCache.get(`moduleHash-${getRuntimeKey(runtime)}`); + if (digest !== undefined) { + chunkGraph.setModuleHashes( + module, + runtime, + digest, + digest.substr(0, hashDigestLength) + ); + statModulesFromCache++; + continue; + } + } + statModulesHashed++; + const digest = this._createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength + ); + if (memCache) { + memCache.set(`moduleHash-${getRuntimeKey(runtime)}`, digest); + } + } + } + this.logger.log( + `${statModulesHashed} modules hashed, ${statModulesFromCache} from cache (${ + Math.round( + (100 * (statModulesHashed + statModulesFromCache)) / this.modules.size + ) / 100 + } variants per module in average)` + ); + } -class SyncBailHookCodeFactory extends HookCodeFactory { - content({ onError, onResult, resultReturns, onDone, rethrowIfPossible }) { - return this.callTapsSeries({ - onError: (i, err) => onError(err), - onResult: (i, result, next) => - `if(${result} !== undefined) {\n${onResult( - result - )};\n} else {\n${next()}}\n`, - resultReturns, - onDone, - rethrowIfPossible + _createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength + ) { + const moduleHash = createHash(hashFunction); + module.updateHash(moduleHash, { + chunkGraph, + runtime, + runtimeTemplate }); + const moduleHashDigest = /** @type {string} */ ( + moduleHash.digest(hashDigest) + ); + chunkGraph.setModuleHashes( + module, + runtime, + moduleHashDigest, + moduleHashDigest.substr(0, hashDigestLength) + ); + return moduleHashDigest; } -} -const factory = new SyncBailHookCodeFactory(); + createHash() { + this.logger.time("hashing: initialize hash"); + const chunkGraph = this.chunkGraph; + const runtimeTemplate = this.runtimeTemplate; + const outputOptions = this.outputOptions; + const hashFunction = outputOptions.hashFunction; + const hashDigest = outputOptions.hashDigest; + const hashDigestLength = outputOptions.hashDigestLength; + const hash = createHash(hashFunction); + if (outputOptions.hashSalt) { + hash.update(outputOptions.hashSalt); + } + this.logger.timeEnd("hashing: initialize hash"); + if (this.children.length > 0) { + this.logger.time("hashing: hash child compilations"); + for (const child of this.children) { + hash.update(child.hash); + } + this.logger.timeEnd("hashing: hash child compilations"); + } + if (this.warnings.length > 0) { + this.logger.time("hashing: hash warnings"); + for (const warning of this.warnings) { + hash.update(`${warning.message}`); + } + this.logger.timeEnd("hashing: hash warnings"); + } + if (this.errors.length > 0) { + this.logger.time("hashing: hash errors"); + for (const error of this.errors) { + hash.update(`${error.message}`); + } + this.logger.timeEnd("hashing: hash errors"); + } -const TAP_ASYNC = () => { - throw new Error("tapAsync is not supported on a SyncBailHook"); -}; + this.logger.time("hashing: sort chunks"); + /* + * all non-runtime chunks need to be hashes first, + * since runtime chunk might use their hashes. + * runtime chunks need to be hashed in the correct order + * since they may depend on each other (for async entrypoints). + * So we put all non-runtime chunks first and hash them in any order. + * And order runtime chunks according to referenced between each other. + * Chunks need to be in deterministic order since we add hashes to full chunk + * during these hashing. + */ + /** @type {Chunk[]} */ + const unorderedRuntimeChunks = []; + /** @type {Chunk[]} */ + const otherChunks = []; + for (const c of this.chunks) { + if (c.hasRuntime()) { + unorderedRuntimeChunks.push(c); + } else { + otherChunks.push(c); + } + } + unorderedRuntimeChunks.sort(byId); + otherChunks.sort(byId); -const TAP_PROMISE = () => { - throw new Error("tapPromise is not supported on a SyncBailHook"); -}; + /** @typedef {{ chunk: Chunk, referencedBy: RuntimeChunkInfo[], remaining: number }} RuntimeChunkInfo */ + /** @type {Map} */ + const runtimeChunksMap = new Map(); + for (const chunk of unorderedRuntimeChunks) { + runtimeChunksMap.set(chunk, { + chunk, + referencedBy: [], + remaining: 0 + }); + } + let remaining = 0; + for (const info of runtimeChunksMap.values()) { + for (const other of new Set( + Array.from(info.chunk.getAllReferencedAsyncEntrypoints()).map( + e => e.chunks[e.chunks.length - 1] + ) + )) { + const otherInfo = runtimeChunksMap.get(other); + otherInfo.referencedBy.push(info); + info.remaining++; + remaining++; + } + } + /** @type {Chunk[]} */ + const runtimeChunks = []; + for (const info of runtimeChunksMap.values()) { + if (info.remaining === 0) { + runtimeChunks.push(info.chunk); + } + } + // If there are any references between chunks + // make sure to follow these chains + if (remaining > 0) { + const readyChunks = []; + for (const chunk of runtimeChunks) { + const hasFullHashModules = + chunkGraph.getNumberOfChunkFullHashModules(chunk) !== 0; + const info = runtimeChunksMap.get(chunk); + for (const otherInfo of info.referencedBy) { + if (hasFullHashModules) { + chunkGraph.upgradeDependentToFullHashModules(otherInfo.chunk); + } + remaining--; + if (--otherInfo.remaining === 0) { + readyChunks.push(otherInfo.chunk); + } + } + if (readyChunks.length > 0) { + // This ensures deterministic ordering, since referencedBy is non-deterministic + readyChunks.sort(byId); + for (const c of readyChunks) runtimeChunks.push(c); + readyChunks.length = 0; + } + } + } + // If there are still remaining references we have cycles and want to create a warning + if (remaining > 0) { + let circularRuntimeChunkInfo = []; + for (const info of runtimeChunksMap.values()) { + if (info.remaining !== 0) { + circularRuntimeChunkInfo.push(info); + } + } + circularRuntimeChunkInfo.sort(compareSelect(i => i.chunk, byId)); + const err = + new WebpackError(`Circular dependency between chunks with runtime (${Array.from( + circularRuntimeChunkInfo, + c => c.chunk.name || c.chunk.id + ).join(", ")}) +This prevents using hashes of each other and should be avoided.`); + err.chunk = circularRuntimeChunkInfo[0].chunk; + this.warnings.push(err); + for (const i of circularRuntimeChunkInfo) runtimeChunks.push(i.chunk); + } + this.logger.timeEnd("hashing: sort chunks"); -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; + const fullHashChunks = new Set(); + /** @type {{module: Module, hash: string, runtime: RuntimeSpec, runtimes: RuntimeSpec[]}[]} */ + const codeGenerationJobs = []; + /** @type {Map>} */ + const codeGenerationJobsMap = new Map(); -function SyncBailHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = SyncBailHook; - hook.tapAsync = TAP_ASYNC; - hook.tapPromise = TAP_PROMISE; - hook.compile = COMPILE; - return hook; -} + const processChunk = chunk => { + // Last minute module hash generation for modules that depend on chunk hashes + this.logger.time("hashing: hash runtime modules"); + const runtime = chunk.runtime; + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (!chunkGraph.hasModuleHashes(module, runtime)) { + const hash = this._createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength + ); + let hashMap = codeGenerationJobsMap.get(hash); + if (hashMap) { + const moduleJob = hashMap.get(module); + if (moduleJob) { + moduleJob.runtimes.push(runtime); + continue; + } + } else { + hashMap = new Map(); + codeGenerationJobsMap.set(hash, hashMap); + } + const job = { + module, + hash, + runtime, + runtimes: [runtime] + }; + hashMap.set(module, job); + codeGenerationJobs.push(job); + } + } + this.logger.timeAggregate("hashing: hash runtime modules"); + this.logger.time("hashing: hash chunks"); + const chunkHash = createHash(hashFunction); + try { + if (outputOptions.hashSalt) { + chunkHash.update(outputOptions.hashSalt); + } + chunk.updateHash(chunkHash, chunkGraph); + this.hooks.chunkHash.call(chunk, chunkHash, { + chunkGraph, + moduleGraph: this.moduleGraph, + runtimeTemplate: this.runtimeTemplate + }); + const chunkHashDigest = /** @type {string} */ ( + chunkHash.digest(hashDigest) + ); + hash.update(chunkHashDigest); + chunk.hash = chunkHashDigest; + chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); + const fullHashModules = + chunkGraph.getChunkFullHashModulesIterable(chunk); + if (fullHashModules) { + fullHashChunks.add(chunk); + } else { + this.hooks.contentHash.call(chunk); + } + } catch (err) { + this.errors.push(new ChunkRenderError(chunk, "", err)); + } + this.logger.timeAggregate("hashing: hash chunks"); + }; + otherChunks.forEach(processChunk); + for (const chunk of runtimeChunks) processChunk(chunk); -SyncBailHook.prototype = null; + this.logger.timeAggregateEnd("hashing: hash runtime modules"); + this.logger.timeAggregateEnd("hashing: hash chunks"); + this.logger.time("hashing: hash digest"); + this.hooks.fullHash.call(hash); + this.fullHash = /** @type {string} */ (hash.digest(hashDigest)); + this.hash = this.fullHash.substr(0, hashDigestLength); + this.logger.timeEnd("hashing: hash digest"); -module.exports = SyncBailHook; + this.logger.time("hashing: process full hash modules"); + for (const chunk of fullHashChunks) { + for (const module of chunkGraph.getChunkFullHashModulesIterable(chunk)) { + const moduleHash = createHash(hashFunction); + module.updateHash(moduleHash, { + chunkGraph, + runtime: chunk.runtime, + runtimeTemplate + }); + const moduleHashDigest = /** @type {string} */ ( + moduleHash.digest(hashDigest) + ); + const oldHash = chunkGraph.getModuleHash(module, chunk.runtime); + chunkGraph.setModuleHashes( + module, + chunk.runtime, + moduleHashDigest, + moduleHashDigest.substr(0, hashDigestLength) + ); + codeGenerationJobsMap.get(oldHash).get(module).hash = moduleHashDigest; + } + const chunkHash = createHash(hashFunction); + chunkHash.update(chunk.hash); + chunkHash.update(this.hash); + const chunkHashDigest = /** @type {string} */ ( + chunkHash.digest(hashDigest) + ); + chunk.hash = chunkHashDigest; + chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); + this.hooks.contentHash.call(chunk); + } + this.logger.timeEnd("hashing: process full hash modules"); + return codeGenerationJobs; + } + /** + * @param {string} file file name + * @param {Source} source asset source + * @param {AssetInfo} assetInfo extra asset information + * @returns {void} + */ + emitAsset(file, source, assetInfo = {}) { + if (this.assets[file]) { + if (!isSourceEqual(this.assets[file], source)) { + this.errors.push( + new WebpackError( + `Conflict: Multiple assets emit different content to the same filename ${file}` + ) + ); + this.assets[file] = source; + this._setAssetInfo(file, assetInfo); + return; + } + const oldInfo = this.assetsInfo.get(file); + const newInfo = Object.assign({}, oldInfo, assetInfo); + this._setAssetInfo(file, newInfo, oldInfo); + return; + } + this.assets[file] = source; + this._setAssetInfo(file, assetInfo, undefined); + } -/***/ }), + _setAssetInfo(file, newInfo, oldInfo = this.assetsInfo.get(file)) { + if (newInfo === undefined) { + this.assetsInfo.delete(file); + } else { + this.assetsInfo.set(file, newInfo); + } + const oldRelated = oldInfo && oldInfo.related; + const newRelated = newInfo && newInfo.related; + if (oldRelated) { + for (const key of Object.keys(oldRelated)) { + const remove = name => { + const relatedIn = this._assetsRelatedIn.get(name); + if (relatedIn === undefined) return; + const entry = relatedIn.get(key); + if (entry === undefined) return; + entry.delete(file); + if (entry.size !== 0) return; + relatedIn.delete(key); + if (relatedIn.size === 0) this._assetsRelatedIn.delete(name); + }; + const entry = oldRelated[key]; + if (Array.isArray(entry)) { + entry.forEach(remove); + } else if (entry) { + remove(entry); + } + } + } + if (newRelated) { + for (const key of Object.keys(newRelated)) { + const add = name => { + let relatedIn = this._assetsRelatedIn.get(name); + if (relatedIn === undefined) { + this._assetsRelatedIn.set(name, (relatedIn = new Map())); + } + let entry = relatedIn.get(key); + if (entry === undefined) { + relatedIn.set(key, (entry = new Set())); + } + entry.add(file); + }; + const entry = newRelated[key]; + if (Array.isArray(entry)) { + entry.forEach(add); + } else if (entry) { + add(entry); + } + } + } + } -/***/ 69689: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {string} file file name + * @param {Source | function(Source): Source} newSourceOrFunction new asset source or function converting old to new + * @param {AssetInfo | function(AssetInfo | undefined): AssetInfo} assetInfoUpdateOrFunction new asset info or function converting old to new + */ + updateAsset( + file, + newSourceOrFunction, + assetInfoUpdateOrFunction = undefined + ) { + if (!this.assets[file]) { + throw new Error( + `Called Compilation.updateAsset for not existing filename ${file}` + ); + } + if (typeof newSourceOrFunction === "function") { + this.assets[file] = newSourceOrFunction(this.assets[file]); + } else { + this.assets[file] = newSourceOrFunction; + } + if (assetInfoUpdateOrFunction !== undefined) { + const oldInfo = this.assetsInfo.get(file) || EMPTY_ASSET_INFO; + if (typeof assetInfoUpdateOrFunction === "function") { + this._setAssetInfo(file, assetInfoUpdateOrFunction(oldInfo), oldInfo); + } else { + this._setAssetInfo( + file, + cachedCleverMerge(oldInfo, assetInfoUpdateOrFunction), + oldInfo + ); + } + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + renameAsset(file, newFile) { + const source = this.assets[file]; + if (!source) { + throw new Error( + `Called Compilation.renameAsset for not existing filename ${file}` + ); + } + if (this.assets[newFile]) { + if (!isSourceEqual(this.assets[file], source)) { + this.errors.push( + new WebpackError( + `Conflict: Called Compilation.renameAsset for already existing filename ${newFile} with different content` + ) + ); + } + } + const assetInfo = this.assetsInfo.get(file); + // Update related in all other assets + const relatedInInfo = this._assetsRelatedIn.get(file); + if (relatedInInfo) { + for (const [key, assets] of relatedInInfo) { + for (const name of assets) { + const info = this.assetsInfo.get(name); + if (!info) continue; + const related = info.related; + if (!related) continue; + const entry = related[key]; + let newEntry; + if (Array.isArray(entry)) { + newEntry = entry.map(x => (x === file ? newFile : x)); + } else if (entry === file) { + newEntry = newFile; + } else continue; + this.assetsInfo.set(name, { + ...info, + related: { + ...related, + [key]: newEntry + } + }); + } + } + } + this._setAssetInfo(file, undefined, assetInfo); + this._setAssetInfo(newFile, assetInfo); + delete this.assets[file]; + this.assets[newFile] = source; + for (const chunk of this.chunks) { + { + const size = chunk.files.size; + chunk.files.delete(file); + if (size !== chunk.files.size) { + chunk.files.add(newFile); + } + } + { + const size = chunk.auxiliaryFiles.size; + chunk.auxiliaryFiles.delete(file); + if (size !== chunk.auxiliaryFiles.size) { + chunk.auxiliaryFiles.add(newFile); + } + } + } + } + /** + * @param {string} file file name + */ + deleteAsset(file) { + if (!this.assets[file]) { + return; + } + delete this.assets[file]; + const assetInfo = this.assetsInfo.get(file); + this._setAssetInfo(file, undefined, assetInfo); + const related = assetInfo && assetInfo.related; + if (related) { + for (const key of Object.keys(related)) { + const checkUsedAndDelete = file => { + if (!this._assetsRelatedIn.has(file)) { + this.deleteAsset(file); + } + }; + const items = related[key]; + if (Array.isArray(items)) { + items.forEach(checkUsedAndDelete); + } else if (items) { + checkUsedAndDelete(items); + } + } + } + // TODO If this becomes a performance problem + // store a reverse mapping from asset to chunk + for (const chunk of this.chunks) { + chunk.files.delete(file); + chunk.auxiliaryFiles.delete(file); + } + } -const Hook = __webpack_require__(21468); -const HookCodeFactory = __webpack_require__(66443); + getAssets() { + /** @type {Readonly[]} */ + const array = []; + for (const assetName of Object.keys(this.assets)) { + if (Object.prototype.hasOwnProperty.call(this.assets, assetName)) { + array.push({ + name: assetName, + source: this.assets[assetName], + info: this.assetsInfo.get(assetName) || EMPTY_ASSET_INFO + }); + } + } + return array; + } -class SyncHookCodeFactory extends HookCodeFactory { - content({ onError, onDone, rethrowIfPossible }) { - return this.callTapsSeries({ - onError: (i, err) => onError(err), - onDone, - rethrowIfPossible - }); + /** + * @param {string} name the name of the asset + * @returns {Readonly | undefined} the asset or undefined when not found + */ + getAsset(name) { + if (!Object.prototype.hasOwnProperty.call(this.assets, name)) + return undefined; + return { + name, + source: this.assets[name], + info: this.assetsInfo.get(name) || EMPTY_ASSET_INFO + }; } -} -const factory = new SyncHookCodeFactory(); + clearAssets() { + for (const chunk of this.chunks) { + chunk.files.clear(); + chunk.auxiliaryFiles.clear(); + } + } -const TAP_ASYNC = () => { - throw new Error("tapAsync is not supported on a SyncHook"); -}; + createModuleAssets() { + const { chunkGraph } = this; + for (const module of this.modules) { + if (module.buildInfo.assets) { + const assetsInfo = module.buildInfo.assetsInfo; + for (const assetName of Object.keys(module.buildInfo.assets)) { + const fileName = this.getPath(assetName, { + chunkGraph: this.chunkGraph, + module + }); + for (const chunk of chunkGraph.getModuleChunksIterable(module)) { + chunk.auxiliaryFiles.add(fileName); + } + this.emitAsset( + fileName, + module.buildInfo.assets[assetName], + assetsInfo ? assetsInfo.get(assetName) : undefined + ); + this.hooks.moduleAsset.call(module, fileName); + } + } + } + } -const TAP_PROMISE = () => { - throw new Error("tapPromise is not supported on a SyncHook"); -}; + /** + * @param {RenderManifestOptions} options options object + * @returns {RenderManifestEntry[]} manifest entries + */ + getRenderManifest(options) { + return this.hooks.renderManifest.call([], options); + } -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; + /** + * @param {Callback} callback signals when the call finishes + * @returns {void} + */ + createChunkAssets(callback) { + const outputOptions = this.outputOptions; + const cachedSourceMap = new WeakMap(); + /** @type {Map} */ + const alreadyWrittenFiles = new Map(); -function SyncHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = SyncHook; - hook.tapAsync = TAP_ASYNC; - hook.tapPromise = TAP_PROMISE; - hook.compile = COMPILE; - return hook; -} + asyncLib.forEachLimit( + this.chunks, + 15, + (chunk, callback) => { + /** @type {RenderManifestEntry[]} */ + let manifest; + try { + manifest = this.getRenderManifest({ + chunk, + hash: this.hash, + fullHash: this.fullHash, + outputOptions, + codeGenerationResults: this.codeGenerationResults, + moduleTemplates: this.moduleTemplates, + dependencyTemplates: this.dependencyTemplates, + chunkGraph: this.chunkGraph, + moduleGraph: this.moduleGraph, + runtimeTemplate: this.runtimeTemplate + }); + } catch (err) { + this.errors.push(new ChunkRenderError(chunk, "", err)); + return callback(); + } + asyncLib.forEach( + manifest, + (fileManifest, callback) => { + const ident = fileManifest.identifier; + const usedHash = fileManifest.hash; -SyncHook.prototype = null; + const assetCacheItem = this._assetsCache.getItemCache( + ident, + usedHash + ); -module.exports = SyncHook; + assetCacheItem.get((err, sourceFromCache) => { + /** @type {string | function(PathData, AssetInfo=): string} */ + let filenameTemplate; + /** @type {string} */ + let file; + /** @type {AssetInfo} */ + let assetInfo; + let inTry = true; + const errorAndCallback = err => { + const filename = + file || + (typeof file === "string" + ? file + : typeof filenameTemplate === "string" + ? filenameTemplate + : ""); -/***/ }), + this.errors.push(new ChunkRenderError(chunk, filename, err)); + inTry = false; + return callback(); + }; -/***/ 50179: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + try { + if ("filename" in fileManifest) { + file = fileManifest.filename; + assetInfo = fileManifest.info; + } else { + filenameTemplate = fileManifest.filenameTemplate; + const pathAndInfo = this.getPathWithInfo( + filenameTemplate, + fileManifest.pathOptions + ); + file = pathAndInfo.path; + assetInfo = fileManifest.info + ? { + ...pathAndInfo.info, + ...fileManifest.info + } + : pathAndInfo.info; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (err) { + return errorAndCallback(err); + } + let source = sourceFromCache; -const Hook = __webpack_require__(21468); -const HookCodeFactory = __webpack_require__(66443); + // check if the same filename was already written by another chunk + const alreadyWritten = alreadyWrittenFiles.get(file); + if (alreadyWritten !== undefined) { + if (alreadyWritten.hash !== usedHash) { + inTry = false; + return callback( + new WebpackError( + `Conflict: Multiple chunks emit assets to the same filename ${file}` + + ` (chunks ${alreadyWritten.chunk.id} and ${chunk.id})` + ) + ); + } else { + source = alreadyWritten.source; + } + } else if (!source) { + // render the asset + source = fileManifest.render(); -class SyncLoopHookCodeFactory extends HookCodeFactory { - content({ onError, onDone, rethrowIfPossible }) { - return this.callTapsLooping({ - onError: (i, err) => onError(err), - onDone, - rethrowIfPossible - }); + // Ensure that source is a cached source to avoid additional cost because of repeated access + if (!(source instanceof CachedSource)) { + const cacheEntry = cachedSourceMap.get(source); + if (cacheEntry) { + source = cacheEntry; + } else { + const cachedSource = new CachedSource(source); + cachedSourceMap.set(source, cachedSource); + source = cachedSource; + } + } + } + this.emitAsset(file, source, assetInfo); + if (fileManifest.auxiliary) { + chunk.auxiliaryFiles.add(file); + } else { + chunk.files.add(file); + } + this.hooks.chunkAsset.call(chunk, file); + alreadyWrittenFiles.set(file, { + hash: usedHash, + source, + chunk + }); + if (source !== sourceFromCache) { + assetCacheItem.store(source, err => { + if (err) return errorAndCallback(err); + inTry = false; + return callback(); + }); + } else { + inTry = false; + callback(); + } + } catch (err) { + if (!inTry) throw err; + errorAndCallback(err); + } + }); + }, + callback + ); + }, + callback + ); } -} - -const factory = new SyncLoopHookCodeFactory(); - -const TAP_ASYNC = () => { - throw new Error("tapAsync is not supported on a SyncLoopHook"); -}; - -const TAP_PROMISE = () => { - throw new Error("tapPromise is not supported on a SyncLoopHook"); -}; - -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; - -function SyncLoopHook(args = [], name = undefined) { - const hook = new Hook(args, name); - hook.constructor = SyncLoopHook; - hook.tapAsync = TAP_ASYNC; - hook.tapPromise = TAP_PROMISE; - hook.compile = COMPILE; - return hook; -} - -SyncLoopHook.prototype = null; - -module.exports = SyncLoopHook; - - -/***/ }), -/***/ 36093: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash + * @param {PathData} data context data + * @returns {string} interpolated path + */ + getPath(filename, data = {}) { + if (!data.hash) { + data = { + hash: this.hash, + ...data + }; + } + return this.getAssetPath(filename, data); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash + * @param {PathData} data context data + * @returns {{ path: string, info: AssetInfo }} interpolated path and asset info + */ + getPathWithInfo(filename, data = {}) { + if (!data.hash) { + data = { + hash: this.hash, + ...data + }; + } + return this.getAssetPathWithInfo(filename, data); + } + /** + * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash + * @param {PathData} data context data + * @returns {string} interpolated path + */ + getAssetPath(filename, data) { + return this.hooks.assetPath.call( + typeof filename === "function" ? filename(data) : filename, + data, + undefined + ); + } -const Hook = __webpack_require__(21468); -const HookCodeFactory = __webpack_require__(66443); + /** + * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash + * @param {PathData} data context data + * @returns {{ path: string, info: AssetInfo }} interpolated path and asset info + */ + getAssetPathWithInfo(filename, data) { + const assetInfo = {}; + // TODO webpack 5: refactor assetPath hook to receive { path, info } object + const newPath = this.hooks.assetPath.call( + typeof filename === "function" ? filename(data, assetInfo) : filename, + data, + assetInfo + ); + return { path: newPath, info: assetInfo }; + } -class SyncWaterfallHookCodeFactory extends HookCodeFactory { - content({ onError, onResult, resultReturns, rethrowIfPossible }) { - return this.callTapsSeries({ - onError: (i, err) => onError(err), - onResult: (i, result, next) => { - let code = ""; - code += `if(${result} !== undefined) {\n`; - code += `${this._args[0]} = ${result};\n`; - code += `}\n`; - code += next(); - return code; - }, - onDone: () => onResult(this._args[0]), - doneReturns: resultReturns, - rethrowIfPossible - }); + getWarnings() { + return this.hooks.processWarnings.call(this.warnings); } -} -const factory = new SyncWaterfallHookCodeFactory(); + getErrors() { + return this.hooks.processErrors.call(this.errors); + } -const TAP_ASYNC = () => { - throw new Error("tapAsync is not supported on a SyncWaterfallHook"); -}; + /** + * This function allows you to run another instance of webpack inside of webpack however as + * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins + * from parent (or top level compiler) and creates a child Compilation + * + * @param {string} name name of the child compiler + * @param {OutputOptions=} outputOptions // Need to convert config schema to types for this + * @param {Array=} plugins webpack plugins that will be applied + * @returns {Compiler} creates a child Compiler instance + */ + createChildCompiler(name, outputOptions, plugins) { + const idx = this.childrenCounters[name] || 0; + this.childrenCounters[name] = idx + 1; + return this.compiler.createChildCompiler( + this, + name, + idx, + outputOptions, + plugins + ); + } -const TAP_PROMISE = () => { - throw new Error("tapPromise is not supported on a SyncWaterfallHook"); -}; + /** + * @param {Module} module the module + * @param {ExecuteModuleOptions} options options + * @param {ExecuteModuleCallback} callback callback + */ + executeModule(module, options, callback) { + // Aggregate all referenced modules and ensure they are ready + const modules = new Set([module]); + processAsyncTree( + modules, + 10, + /** + * @param {Module} module the module + * @param {function(Module): void} push push more jobs + * @param {Callback} callback callback + * @returns {void} + */ + (module, push, callback) => { + this.buildQueue.waitFor(module, err => { + if (err) return callback(err); + this.processDependenciesQueue.waitFor(module, err => { + if (err) return callback(err); + for (const { module: m } of this.moduleGraph.getOutgoingConnections( + module + )) { + const size = modules.size; + modules.add(m); + if (modules.size !== size) push(m); + } + callback(); + }); + }); + }, + err => { + if (err) return callback(err); -const COMPILE = function(options) { - factory.setup(this, options); - return factory.create(options); -}; + // Create new chunk graph, chunk and entrypoint for the build time execution + const chunkGraph = new ChunkGraph( + this.moduleGraph, + this.outputOptions.hashFunction + ); + const runtime = "build time"; + const { hashFunction, hashDigest, hashDigestLength } = + this.outputOptions; + const runtimeTemplate = this.runtimeTemplate; -function SyncWaterfallHook(args = [], name = undefined) { - if (args.length < 1) - throw new Error("Waterfall hooks must have at least one argument"); - const hook = new Hook(args, name); - hook.constructor = SyncWaterfallHook; - hook.tapAsync = TAP_ASYNC; - hook.tapPromise = TAP_PROMISE; - hook.compile = COMPILE; - return hook; -} + const chunk = new Chunk("build time chunk", this._backCompat); + chunk.id = chunk.name; + chunk.ids = [chunk.id]; + chunk.runtime = runtime; -SyncWaterfallHook.prototype = null; + const entrypoint = new Entrypoint({ + runtime, + chunkLoading: false, + ...options.entryOptions + }); + chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint); + connectChunkGroupAndChunk(entrypoint, chunk); + entrypoint.setRuntimeChunk(chunk); + entrypoint.setEntrypointChunk(chunk); -module.exports = SyncWaterfallHook; + const chunks = new Set([chunk]); + // Assign ids to modules and modules to the chunk + for (const module of modules) { + const id = module.identifier(); + chunkGraph.setModuleId(module, id); + chunkGraph.connectChunkAndModule(chunk, module); + } -/***/ }), + // Hash modules + for (const module of modules) { + this._createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength + ); + } -/***/ 41242: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + const codeGenerationResults = new CodeGenerationResults( + this.outputOptions.hashFunction + ); + /** @type {WebpackError[]} */ + const errors = []; + /** + * @param {Module} module the module + * @param {Callback} callback callback + * @returns {void} + */ + const codeGen = (module, callback) => { + this._codeGenerationModule( + module, + runtime, + [runtime], + chunkGraph.getModuleHash(module, runtime), + this.dependencyTemplates, + chunkGraph, + this.moduleGraph, + runtimeTemplate, + errors, + codeGenerationResults, + (err, codeGenerated) => { + callback(err); + } + ); + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const reportErrors = () => { + if (errors.length > 0) { + errors.sort( + compareSelect(err => err.module, compareModulesByIdentifier) + ); + for (const error of errors) { + this.errors.push(error); + } + errors.length = 0; + } + }; + // Generate code for all aggregated modules + asyncLib.eachLimit(modules, 10, codeGen, err => { + if (err) return callback(err); + reportErrors(); -exports.__esModule = true; -exports.SyncHook = __webpack_require__(69689); -exports.SyncBailHook = __webpack_require__(1626); -exports.SyncWaterfallHook = __webpack_require__(36093); -exports.SyncLoopHook = __webpack_require__(50179); -exports.AsyncParallelHook = __webpack_require__(31684); -exports.AsyncParallelBailHook = __webpack_require__(18151); -exports.AsyncSeriesHook = __webpack_require__(96496); -exports.AsyncSeriesBailHook = __webpack_require__(95734); -exports.AsyncSeriesLoopHook = __webpack_require__(95999); -exports.AsyncSeriesWaterfallHook = __webpack_require__(58118); -exports.HookMap = __webpack_require__(77079); -exports.MultiHook = __webpack_require__(13103); + // for backward-compat temporary set the chunk graph + // TODO webpack 6 + const old = this.chunkGraph; + this.chunkGraph = chunkGraph; + this.processRuntimeRequirements({ + chunkGraph, + modules, + chunks, + codeGenerationResults, + chunkGraphEntries: chunks + }); + this.chunkGraph = old; + const runtimeModules = + chunkGraph.getChunkRuntimeModulesIterable(chunk); -/***/ }), + // Hash runtime modules + for (const module of runtimeModules) { + modules.add(module); + this._createModuleHash( + module, + chunkGraph, + runtime, + hashFunction, + runtimeTemplate, + hashDigest, + hashDigestLength + ); + } -/***/ 74315: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Generate code for all runtime modules + asyncLib.eachLimit(runtimeModules, 10, codeGen, err => { + if (err) return callback(err); + reportErrors(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** @type {Map} */ + const moduleArgumentsMap = new Map(); + /** @type {Map} */ + const moduleArgumentsById = new Map(); + /** @type {ExecuteModuleResult["fileDependencies"]} */ + const fileDependencies = new LazySet(); + /** @type {ExecuteModuleResult["contextDependencies"]} */ + const contextDependencies = new LazySet(); + /** @type {ExecuteModuleResult["missingDependencies"]} */ + const missingDependencies = new LazySet(); + /** @type {ExecuteModuleResult["buildDependencies"]} */ + const buildDependencies = new LazySet(); + /** @type {ExecuteModuleResult["assets"]} */ + const assets = new Map(); -const RuntimeGlobals = __webpack_require__(16475); -const WebpackError = __webpack_require__(53799); -const ConstDependency = __webpack_require__(76911); -const BasicEvaluatedExpression = __webpack_require__(950); -const { - toConstantDependency, - evaluateToString -} = __webpack_require__(93998); -const ChunkNameRuntimeModule = __webpack_require__(84519); -const GetFullHashRuntimeModule = __webpack_require__(88732); + let cacheable = true; -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ + /** @type {ExecuteModuleContext} */ + const context = { + assets, + __webpack_require__: undefined, + chunk, + chunkGraph + }; -/* 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 */ + // Prepare execution + asyncLib.eachLimit( + modules, + 10, + (module, callback) => { + const codeGenerationResult = codeGenerationResults.get( + module, + runtime + ); + /** @type {ExecuteModuleArgument} */ + const moduleArgument = { + module, + codeGenerationResult, + preparedInfo: undefined, + moduleObject: undefined + }; + moduleArgumentsMap.set(module, moduleArgument); + moduleArgumentsById.set(module.identifier(), moduleArgument); + module.addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ); + if (module.buildInfo.cacheable === false) { + cacheable = false; + } + if (module.buildInfo && module.buildInfo.assets) { + const { assets: moduleAssets, assetsInfo } = module.buildInfo; + for (const assetName of Object.keys(moduleAssets)) { + assets.set(assetName, { + source: moduleAssets[assetName], + info: assetsInfo ? assetsInfo.get(assetName) : undefined + }); + } + } + this.hooks.prepareModuleExecution.callAsync( + moduleArgument, + context, + callback + ); + }, + err => { + if (err) return callback(err); -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() - ); + let exports; + try { + const { + strictModuleErrorHandling, + strictModuleExceptionHandling + } = this.outputOptions; + const __nested_webpack_require_152290__ = id => { + const cached = moduleCache[id]; + if (cached !== undefined) { + if (cached.error) throw cached.error; + return cached.exports; + } + const moduleArgument = moduleArgumentsById.get(id); + return __webpack_require_module__(moduleArgument, id); + }; + const interceptModuleExecution = (__nested_webpack_require_152290__[ + RuntimeGlobals.interceptModuleExecution.replace( + "__webpack_require__.", + "" + ) + ] = []); + const moduleCache = (__nested_webpack_require_152290__[ + RuntimeGlobals.moduleCache.replace( + "__webpack_require__.", + "" + ) + ] = {}); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.chunkName) - .tap("APIPlugin", chunk => { - compilation.addRuntimeModule( - chunk, - new ChunkNameRuntimeModule(chunk.name) - ); - return true; - }); + context.__webpack_require__ = __nested_webpack_require_152290__; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.getFullHash) - .tap("APIPlugin", (chunk, set) => { - compilation.addRuntimeModule(chunk, new GetFullHashRuntimeModule()); - return true; - }); + /** + * @param {ExecuteModuleArgument} moduleArgument the module argument + * @param {string=} id id + * @returns {any} exports + */ + const __webpack_require_module__ = (moduleArgument, id) => { + var execOptions = { + id, + module: { + id, + exports: {}, + loaded: false, + error: undefined + }, + require: __nested_webpack_require_152290__ + }; + interceptModuleExecution.forEach(handler => + handler(execOptions) + ); + const module = moduleArgument.module; + this.buildTimeExecutedModules.add(module); + const moduleObject = execOptions.module; + moduleArgument.moduleObject = moduleObject; + try { + if (id) moduleCache[id] = moduleObject; - /** - * @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)); - } - }); + tryRunOrWebpackError( + () => + this.hooks.executeModule.call( + moduleArgument, + context + ), + "Compilation.hooks.executeModule" + ); + moduleObject.loaded = true; + return moduleObject.exports; + } catch (e) { + if (strictModuleExceptionHandling) { + if (id) delete moduleCache[id]; + } else if (strictModuleErrorHandling) { + moduleObject.error = e; + } + if (!e.module) e.module = module; + throw e; + } + }; - 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) - ); - }; + for (const runtimeModule of chunkGraph.getChunkRuntimeModulesInOrder( + chunk + )) { + __webpack_require_module__( + moduleArgumentsMap.get(runtimeModule) + ); + } + exports = __nested_webpack_require_152290__(module.identifier()); + } catch (e) { + const err = new WebpackError( + `Execution of module code from module graph (${module.readableIdentifier( + this.requestShortener + )}) failed: ${e.message}` + ); + err.stack = e.stack; + err.module = e.module; + return callback(err); + } - 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); + callback(null, { + exports, + assets, + cacheable, + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + }); + } + ); + }); + }); } ); } -} - -module.exports = APIPlugin; - - -/***/ }), -/***/ 77198: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ + checkConstraints() { + const chunkGraph = this.chunkGraph; + /** @type {Set} */ + const usedIds = new Set(); + for (const module of this.modules) { + if (module.type === "runtime") continue; + const moduleId = chunkGraph.getModuleId(module); + if (moduleId === null) continue; + if (usedIds.has(moduleId)) { + throw new Error(`checkConstraints: duplicate module id ${moduleId}`); + } + usedIds.add(moduleId); + } -const WebpackError = __webpack_require__(53799); -const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/; + for (const chunk of this.chunks) { + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (!this.modules.has(module)) { + throw new Error( + "checkConstraints: module in chunk but not in compilation " + + ` ${chunk.debugId} ${module.debugId}` + ); + } + } + for (const module of chunkGraph.getChunkEntryModulesIterable(chunk)) { + if (!this.modules.has(module)) { + throw new Error( + "checkConstraints: entry module in chunk but not in compilation " + + ` ${chunk.debugId} ${module.debugId}` + ); + } + } + } -/** - * @param {string=} method method name - * @returns {string} message - */ -function createMessage(method) { - return `Abstract method${method ? " " + method : ""}. Must be overridden.`; + for (const chunkGroup of this.chunkGroups) { + chunkGroup.checkConstraints(); + } + } } /** - * @constructor + * @typedef {Object} FactorizeModuleOptions + * @property {ModuleProfile} currentProfile + * @property {ModuleFactory} factory + * @property {Dependency[]} dependencies + * @property {boolean=} factoryResult return full ModuleFactoryResult instead of only module + * @property {Module | null} originModule + * @property {Partial=} contextInfo + * @property {string=} context */ -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. - * } - * } - * + * @param {FactorizeModuleOptions} options options object + * @param {ModuleCallback | ModuleFactoryResultCallback} callback callback + * @returns {void} */ -class AbstractMethodError extends WebpackError { - constructor() { - super(new Message().message); - this.name = "AbstractMethodError"; + +// Workaround for typescript as it doesn't support function overloading in jsdoc within a class +Compilation.prototype.factorizeModule = /** @type {{ + (options: FactorizeModuleOptions & { factoryResult?: false }, callback: ModuleCallback): void; + (options: FactorizeModuleOptions & { factoryResult: true }, callback: ModuleFactoryResultCallback): void; +}} */ ( + function (options, callback) { + this.factorizeQueue.add(options, callback); } -} +); -module.exports = AbstractMethodError; +// Hide from typescript +const compilationPrototype = Compilation.prototype; +// TODO webpack 6 remove +Object.defineProperty(compilationPrototype, "modifyHash", { + writable: false, + enumerable: false, + configurable: false, + value: () => { + throw new Error( + "Compilation.modifyHash was removed in favor of Compilation.hooks.fullHash" + ); + } +}); -/***/ }), +// TODO webpack 6 remove +Object.defineProperty(compilationPrototype, "cache", { + enumerable: false, + configurable: false, + get: util.deprecate( + /** + * @this {Compilation} the compilation + * @returns {Cache} the cache + */ + function () { + return this.compiler.cache; + }, + "Compilation.cache was removed in favor of Compilation.getCache()", + "DEP_WEBPACK_COMPILATION_CACHE" + ), + set: util.deprecate( + v => {}, + "Compilation.cache was removed in favor of Compilation.getCache()", + "DEP_WEBPACK_COMPILATION_CACHE" + ) +}); -/***/ 47736: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * Add additional assets to the compilation. + */ +Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL = -2000; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * Basic preprocessing of assets. + */ +Compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS = -1000; +/** + * Derive new assets from existing assets. + * Existing assets should not be treated as complete. + */ +Compilation.PROCESS_ASSETS_STAGE_DERIVED = -200; +/** + * Add additional sections to existing assets, like a banner or initialization code. + */ +Compilation.PROCESS_ASSETS_STAGE_ADDITIONS = -100; -const DependenciesBlock = __webpack_require__(71040); -const makeSerializable = __webpack_require__(33032); +/** + * Optimize existing assets in a general way. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE = 100; -/** @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 */ +/** + * Optimize the count of existing assets, e. g. by merging them. + * Only assets of the same type should be merged. + * For assets of different types see PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT = 200; -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; - this._stringifiedGroupOptions = undefined; - } +/** + * Optimize the compatibility of existing assets, e. g. add polyfills or vendor-prefixes. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY = 300; - /** - * @returns {string} The name of the chunk - */ - get chunkName() { - return this.groupOptions.name; - } +/** + * Optimize the size of existing assets, e. g. by minimizing or omitting whitespace. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE = 400; - /** - * @param {string} value The new chunk name - * @returns {void} - */ - set chunkName(value) { - if (this.groupOptions.name !== value) { - this.groupOptions.name = value; - this._stringifiedGroupOptions = undefined; - } - } +/** + * Add development tooling to assets, e. g. by extracting a SourceMap. + */ +Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING = 500; - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - const { chunkGraph } = context; - if (this._stringifiedGroupOptions === undefined) { - this._stringifiedGroupOptions = JSON.stringify(this.groupOptions); - } - const chunkGroup = chunkGraph.getBlockChunkGroup(this); - hash.update( - `${this._stringifiedGroupOptions}${chunkGroup ? chunkGroup.id : ""}` - ); - super.updateHash(hash, context); - } +/** + * Optimize the count of existing assets, e. g. by inlining assets of into other assets. + * Only assets of different types should be inlined. + * For assets of the same type see PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE = 700; - serialize(context) { - const { write } = context; - write(this.groupOptions); - write(this.loc); - write(this.request); - super.serialize(context); - } +/** + * Summarize the list of existing assets + * e. g. creating an assets manifest of Service Workers. + */ +Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE = 1000; - deserialize(context) { - const { read } = context; - this.groupOptions = read(); - this.loc = read(); - this.request = read(); - super.deserialize(context); - } -} +/** + * Optimize the hashes of the assets, e. g. by generating real hashes of the asset content. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH = 2500; -makeSerializable(AsyncDependenciesBlock, "webpack/lib/AsyncDependenciesBlock"); +/** + * Optimize the transfer of existing assets, e. g. by preparing a compressed (gzip) file as separate asset. + */ +Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER = 3000; -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)" - ); - } -}); +/** + * Analyse existing assets. + */ +Compilation.PROCESS_ASSETS_STAGE_ANALYSE = 4000; -module.exports = AsyncDependenciesBlock; +/** + * Creating assets for reporting purposes. + */ +Compilation.PROCESS_ASSETS_STAGE_REPORT = 5000; + +module.exports = Compilation; /***/ }), -/***/ 30111: +/***/ 70845: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn + Author Tobias Koppers @sokra */ +const parseJson = __webpack_require__(15235); +const asyncLib = __webpack_require__(78175); +const { + SyncHook, + SyncBailHook, + AsyncParallelHook, + AsyncSeriesHook +} = __webpack_require__(6967); +const { SizeOnlySource } = __webpack_require__(51255); +const webpack = __webpack_require__(91919); +const Cache = __webpack_require__(7592); +const CacheFacade = __webpack_require__(55392); +const ChunkGraph = __webpack_require__(64971); +const Compilation = __webpack_require__(85720); +const ConcurrentCompilationError = __webpack_require__(95735); +const ContextModuleFactory = __webpack_require__(62471); +const ModuleGraph = __webpack_require__(99988); +const NormalModuleFactory = __webpack_require__(68860); +const RequestShortener = __webpack_require__(73406); +const ResolverFactory = __webpack_require__(30217); +const Stats = __webpack_require__(31743); +const Watching = __webpack_require__(84275); const WebpackError = __webpack_require__(53799); +const { Logger } = __webpack_require__(32597); +const { join, dirname, mkdirp } = __webpack_require__(17139); +const { makePathsRelative } = __webpack_require__(82186); +const { isSourceEqual } = __webpack_require__(41245); -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} Entry */ +/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ /** @typedef {import("./Module")} Module */ +/** @typedef {import("./util/WeakTupleMap")} WeakTupleMap */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */ +/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ +/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */ -class AsyncDependencyToInitialChunkError extends WebpackError { - /** - * Creates an instance of AsyncDependencyToInitialChunkError. - * @param {string} chunkName Name of Chunk - * @param {Module} module module tied to dependency - * @param {DependencyLocation} loc location of dependency - */ - constructor(chunkName, module, loc) { - super( - `It's not allowed to load an initial chunk on demand. The chunk name "${chunkName}" is already used by an entrypoint.` - ); - - this.name = "AsyncDependencyToInitialChunkError"; - this.module = module; - this.loc = loc; - } -} - -module.exports = AsyncDependencyToInitialChunkError; - - -/***/ }), +/** + * @typedef {Object} CompilationParams + * @property {NormalModuleFactory} normalModuleFactory + * @property {ContextModuleFactory} contextModuleFactory + */ -/***/ 17714: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @template T + * @callback Callback + * @param {(Error | null)=} err + * @param {T=} result + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @callback RunAsChildCallback + * @param {(Error | null)=} err + * @param {Chunk[]=} entries + * @param {Compilation=} compilation + */ +/** + * @typedef {Object} AssetEmittedInfo + * @property {Buffer} content + * @property {Source} source + * @property {Compilation} compilation + * @property {string} outputPath + * @property {string} targetPath + */ +/** + * @param {string[]} array an array + * @returns {boolean} true, if the array is sorted + */ +const isSorted = array => { + for (let i = 1; i < array.length; i++) { + if (array[i - 1] > array[i]) return false; + } + return true; +}; -const asyncLib = __webpack_require__(78175); -const NormalModule = __webpack_require__(39); -const PrefetchDependency = __webpack_require__(31618); +/** + * @param {Object} obj an object + * @param {string[]} keys the keys of the object + * @returns {Object} the object with properties sorted by property name + */ +const sortObject = (obj, keys) => { + const o = {}; + for (const k of keys.sort()) { + o[k] = obj[k]; + } + return o; +}; -/** @typedef {import("./Compiler")} Compiler */ +/** + * @param {string} filename filename + * @param {string | string[] | undefined} hashes list of hashes + * @returns {boolean} true, if the filename contains any hash + */ +const includesHash = (filename, hashes) => { + if (!hashes) return false; + if (Array.isArray(hashes)) { + return hashes.some(hash => filename.includes(hash)); + } else { + return filename.includes(hashes); + } +}; -class AutomaticPrefetchPlugin { +class Compiler { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {string} context the compilation path + * @param {WebpackOptions} options options */ - 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; - - -/***/ }), - -/***/ 21242: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { ConcatSource } = __webpack_require__(51255); -const Compilation = __webpack_require__(85720); -const ModuleFilenameHelpers = __webpack_require__(88821); -const Template = __webpack_require__(39722); -const createSchemaValidation = __webpack_require__(32540); - -/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */ -/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */ -/** @typedef {import("./Compiler")} Compiler */ + constructor(context, options = /** @type {WebpackOptions} */ ({})) { + this.hooks = Object.freeze({ + /** @type {SyncHook<[]>} */ + initialize: new SyncHook([]), -const validate = createSchemaValidation( - __webpack_require__(42173), - () => __webpack_require__(49052), - { - name: "Banner Plugin", - baseDataPath: "options" - } -); + /** @type {SyncBailHook<[Compilation], boolean>} */ + shouldEmit: new SyncBailHook(["compilation"]), + /** @type {AsyncSeriesHook<[Stats]>} */ + done: new AsyncSeriesHook(["stats"]), + /** @type {SyncHook<[Stats]>} */ + afterDone: new SyncHook(["stats"]), + /** @type {AsyncSeriesHook<[]>} */ + additionalPass: new AsyncSeriesHook([]), + /** @type {AsyncSeriesHook<[Compiler]>} */ + beforeRun: new AsyncSeriesHook(["compiler"]), + /** @type {AsyncSeriesHook<[Compiler]>} */ + run: new AsyncSeriesHook(["compiler"]), + /** @type {AsyncSeriesHook<[Compilation]>} */ + emit: new AsyncSeriesHook(["compilation"]), + /** @type {AsyncSeriesHook<[string, AssetEmittedInfo]>} */ + assetEmitted: new AsyncSeriesHook(["file", "info"]), + /** @type {AsyncSeriesHook<[Compilation]>} */ + afterEmit: new AsyncSeriesHook(["compilation"]), -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 */`; -}; + /** @type {SyncHook<[Compilation, CompilationParams]>} */ + thisCompilation: new SyncHook(["compilation", "params"]), + /** @type {SyncHook<[Compilation, CompilationParams]>} */ + compilation: new SyncHook(["compilation", "params"]), + /** @type {SyncHook<[NormalModuleFactory]>} */ + normalModuleFactory: new SyncHook(["normalModuleFactory"]), + /** @type {SyncHook<[ContextModuleFactory]>} */ + contextModuleFactory: new SyncHook(["contextModuleFactory"]), -class BannerPlugin { - /** - * @param {BannerPluginArgument} options options object - */ - constructor(options) { - if (typeof options === "string" || typeof options === "function") { - options = { - banner: options - }; - } + /** @type {AsyncSeriesHook<[CompilationParams]>} */ + beforeCompile: new AsyncSeriesHook(["params"]), + /** @type {SyncHook<[CompilationParams]>} */ + compile: new SyncHook(["params"]), + /** @type {AsyncParallelHook<[Compilation]>} */ + make: new AsyncParallelHook(["compilation"]), + /** @type {AsyncParallelHook<[Compilation]>} */ + finishMake: new AsyncSeriesHook(["compilation"]), + /** @type {AsyncSeriesHook<[Compilation]>} */ + afterCompile: new AsyncSeriesHook(["compilation"]), - validate(options); + /** @type {AsyncSeriesHook<[]>} */ + readRecords: new AsyncSeriesHook([]), + /** @type {AsyncSeriesHook<[]>} */ + emitRecords: new AsyncSeriesHook([]), - this.options = options; + /** @type {AsyncSeriesHook<[Compiler]>} */ + watchRun: new AsyncSeriesHook(["compiler"]), + /** @type {SyncHook<[Error]>} */ + failed: new SyncHook(["error"]), + /** @type {SyncHook<[string | null, number]>} */ + invalid: new SyncHook(["filename", "changeTime"]), + /** @type {SyncHook<[]>} */ + watchClose: new SyncHook([]), + /** @type {AsyncSeriesHook<[]>} */ + shutdown: new AsyncSeriesHook([]), - 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; - } - } + /** @type {SyncBailHook<[string, string, any[]], true>} */ + infrastructureLog: new SyncBailHook(["origin", "type", "args"]), - /** - * 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 - ); + // TODO the following hooks are weirdly located here + // TODO move them for webpack 5 + /** @type {SyncHook<[]>} */ + environment: new SyncHook([]), + /** @type {SyncHook<[]>} */ + afterEnvironment: new SyncHook([]), + /** @type {SyncHook<[Compiler]>} */ + afterPlugins: new SyncHook(["compiler"]), + /** @type {SyncHook<[Compiler]>} */ + afterResolvers: new SyncHook(["compiler"]), + /** @type {SyncBailHook<[string, Entry], boolean>} */ + entryOption: new SyncBailHook(["context", "entry"]) + }); - 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; - } + this.webpack = webpack; - for (const file of chunk.files) { - if (!matchObject(file)) { - continue; - } + /** @type {string=} */ + this.name = undefined; + /** @type {Compilation=} */ + this.parentCompilation = undefined; + /** @type {Compiler} */ + this.root = this; + /** @type {string} */ + this.outputPath = ""; + /** @type {Watching} */ + this.watching = undefined; - const data = { - chunk, - filename: file - }; + /** @type {OutputFileSystem} */ + this.outputFileSystem = null; + /** @type {IntermediateFileSystem} */ + this.intermediateFileSystem = null; + /** @type {InputFileSystem} */ + this.inputFileSystem = null; + /** @type {WatchFileSystem} */ + this.watchFileSystem = null; - const comment = compilation.getPath(banner, data); + /** @type {string|null} */ + this.recordsInputPath = null; + /** @type {string|null} */ + this.recordsOutputPath = null; + this.records = {}; + /** @type {Set} */ + this.managedPaths = new Set(); + /** @type {Set} */ + this.immutablePaths = new Set(); - compilation.updateAsset( - file, - old => new ConcatSource(comment, "\n", old) - ); - } - } - } - ); - }); - } -} + /** @type {ReadonlySet} */ + this.modifiedFiles = undefined; + /** @type {ReadonlySet} */ + this.removedFiles = undefined; + /** @type {ReadonlyMap} */ + this.fileTimestamps = undefined; + /** @type {ReadonlyMap} */ + this.contextTimestamps = undefined; + /** @type {number} */ + this.fsStartTime = undefined; -module.exports = BannerPlugin; + /** @type {ResolverFactory} */ + this.resolverFactory = new ResolverFactory(); + this.infrastructureLogger = undefined; -/***/ }), + this.options = options; -/***/ 7592: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.context = context; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.requestShortener = new RequestShortener(context, this.root); + this.cache = new Cache(); + /** @type {Map, memCache: WeakTupleMap }> | undefined} */ + this.moduleMemCaches = undefined; -const { AsyncParallelHook, AsyncSeriesBailHook, SyncHook } = __webpack_require__(41242); -const { - makeWebpackError, - makeWebpackErrorCallback -} = __webpack_require__(11351); + this.compilerPath = ""; -/** @typedef {import("./WebpackError")} WebpackError */ + /** @type {boolean} */ + this.running = false; -/** - * @typedef {Object} Etag - * @property {function(): string} toString - */ + /** @type {boolean} */ + this.idle = false; -/** - * @template T - * @callback CallbackCache - * @param {(WebpackError | null)=} err - * @param {T=} result - * @returns {void} - */ + /** @type {boolean} */ + this.watchMode = false; -/** - * @callback GotHandler - * @param {any} result - * @param {function(Error=): void} callback - * @returns {void} - */ + this._backCompat = this.options.experiments.backCompat !== false; -const needCalls = (times, callback) => { - return err => { - if (--times === 0) { - return callback(err); - } - if (err && times > 0) { - times = 0; - return callback(err); - } - }; -}; + /** @type {Compilation} */ + this._lastCompilation = undefined; + /** @type {NormalModuleFactory} */ + this._lastNormalModuleFactory = undefined; -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]>} */ - storeBuildDependencies: new AsyncParallelHook(["dependencies"]), - /** @type {SyncHook<[]>} */ - beginIdle: new SyncHook([]), - /** @type {AsyncParallelHook<[]>} */ - endIdle: new AsyncParallelHook([]), - /** @type {AsyncParallelHook<[]>} */ - shutdown: new AsyncParallelHook([]) - }; + /** @private @type {WeakMap }>} */ + this._assetEmittingSourceCache = new WeakMap(); + /** @private @type {Map} */ + this._assetEmittingWrittenFiles = new Map(); + /** @private @type {Set} */ + this._assetEmittingPreviousFiles = new Set(); } /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @param {CallbackCache} callback signals when the value is retrieved - * @returns {void} + * @param {string} name cache name + * @returns {CacheFacade} the cache facade instance */ - 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); - } - }); + getCache(name) { + return new CacheFacade( + this.cache, + `${this.compilerPath}${name}`, + this.options.output.hashFunction + ); } /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @param {T} data the value to store - * @param {CallbackCache} callback signals when the value is stored - * @returns {void} + * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name + * @returns {Logger} a logger with that name */ - store(identifier, etag, data, callback) { - this.hooks.store.callAsync( - identifier, - etag, - data, - makeWebpackErrorCallback(callback, "Cache.hooks.store") + getInfrastructureLogger(name) { + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called without a name" + ); + } + return new Logger( + (type, args) => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called with a function not returning a name" + ); + } + } + if (this.hooks.infrastructureLog.call(name, type, args) === undefined) { + if (this.infrastructureLogger !== undefined) { + this.infrastructureLogger(name, type, args); + } + } + }, + childName => { + if (typeof name === "function") { + if (typeof childName === "function") { + return this.getInfrastructureLogger(() => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called with a function not returning a name" + ); + } + } + if (typeof childName === "function") { + childName = childName(); + if (!childName) { + throw new TypeError( + "Logger.getChildLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } else { + return this.getInfrastructureLogger(() => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } + } else { + if (typeof childName === "function") { + return this.getInfrastructureLogger(() => { + if (typeof childName === "function") { + childName = childName(); + if (!childName) { + throw new TypeError( + "Logger.getChildLogger(name) called with a function not returning a name" + ); + } + } + return `${name}/${childName}`; + }); + } else { + return this.getInfrastructureLogger(`${name}/${childName}`); + } + } + } ); } - /** - * After this method has succeeded the cache can only be restored when build dependencies are - * @param {Iterable} dependencies list of all build dependencies - * @param {CallbackCache} callback signals when the dependencies are stored - * @returns {void} - */ - storeBuildDependencies(dependencies, callback) { - this.hooks.storeBuildDependencies.callAsync( - dependencies, - makeWebpackErrorCallback(callback, "Cache.hooks.storeBuildDependencies") - ); + // TODO webpack 6: solve this in a better way + // e.g. move compilation specific info from Modules into ModuleGraph + _cleanupLastCompilation() { + if (this._lastCompilation !== undefined) { + for (const module of this._lastCompilation.modules) { + ChunkGraph.clearChunkGraphForModule(module); + ModuleGraph.clearModuleGraphForModule(module); + module.cleanupForCache(); + } + for (const chunk of this._lastCompilation.chunks) { + ChunkGraph.clearChunkGraphForChunk(chunk); + } + this._lastCompilation = undefined; + } } - /** - * @returns {void} - */ - beginIdle() { - this.hooks.beginIdle.call(); + // TODO webpack 6: solve this in a better way + _cleanupLastNormalModuleFactory() { + if (this._lastNormalModuleFactory !== undefined) { + this._lastNormalModuleFactory.cleanupForCache(); + this._lastNormalModuleFactory = undefined; + } } /** - * @param {CallbackCache} callback signals when the call finishes - * @returns {void} + * @param {WatchOptions} watchOptions the watcher's options + * @param {Callback} handler signals when the call finishes + * @returns {Watching} a compiler watcher */ - endIdle(callback) { - this.hooks.endIdle.callAsync( - makeWebpackErrorCallback(callback, "Cache.hooks.endIdle") - ); + watch(watchOptions, handler) { + if (this.running) { + return handler(new ConcurrentCompilationError()); + } + + this.running = true; + this.watchMode = true; + this.watching = new Watching(this, watchOptions, handler); + return this.watching; } /** - * @param {CallbackCache} callback signals when the call finishes + * @param {Callback} 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; - + run(callback) { + if (this.running) { + return callback(new ConcurrentCompilationError()); + } -/***/ }), + let logger; -/***/ 55392: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const finalCallback = (err, stats) => { + if (logger) logger.time("beginIdle"); + this.idle = true; + this.cache.beginIdle(); + this.idle = true; + if (logger) logger.timeEnd("beginIdle"); + this.running = false; + if (err) { + this.hooks.failed.call(err); + } + if (callback !== undefined) callback(err, stats); + this.hooks.afterDone.call(stats); + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const startTime = Date.now(); + this.running = true; + const onCompiled = (err, compilation) => { + if (err) return finalCallback(err); -const { forEachBail } = __webpack_require__(30662); -const asyncLib = __webpack_require__(78175); -const getLazyHashedEtag = __webpack_require__(94075); -const mergeEtags = __webpack_require__(54980); + if (this.hooks.shouldEmit.call(compilation) === false) { + compilation.startTime = startTime; + compilation.endTime = Date.now(); + const stats = new Stats(compilation); + this.hooks.done.callAsync(stats, err => { + if (err) return finalCallback(err); + return finalCallback(null, stats); + }); + return; + } -/** @typedef {import("./Cache")} Cache */ -/** @typedef {import("./Cache").Etag} Etag */ -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./cache/getLazyHashedEtag").HashableObject} HashableObject */ -/** @typedef {typeof import("./util/Hash")} HashConstructor */ + process.nextTick(() => { + logger = compilation.getLogger("webpack.Compiler"); + logger.time("emitAssets"); + this.emitAssets(compilation, err => { + logger.timeEnd("emitAssets"); + if (err) return finalCallback(err); -/** - * @template T - * @callback CallbackCache - * @param {(WebpackError | null)=} err - * @param {T=} result - * @returns {void} - */ + if (compilation.hooks.needAdditionalPass.call()) { + compilation.needAdditionalPass = true; -/** - * @template T - * @callback CallbackNormalErrorCache - * @param {(Error | null)=} err - * @param {T=} result - * @returns {void} - */ + compilation.startTime = startTime; + compilation.endTime = Date.now(); + logger.time("done hook"); + const stats = new Stats(compilation); + this.hooks.done.callAsync(stats, err => { + logger.timeEnd("done hook"); + if (err) return finalCallback(err); -class MultiItemCache { - /** - * @param {ItemCacheFacade[]} items item caches - */ - constructor(items) { - this._items = items; - if (items.length === 1) return /** @type {any} */ (items[0]); - } + this.hooks.additionalPass.callAsync(err => { + if (err) return finalCallback(err); + this.compile(onCompiled); + }); + }); + return; + } - /** - * @template T - * @param {CallbackCache} callback signals when the value is retrieved - * @returns {void} - */ - get(callback) { - forEachBail(this._items, (item, callback) => item.get(callback), callback); - } + logger.time("emitRecords"); + this.emitRecords(err => { + logger.timeEnd("emitRecords"); + if (err) return finalCallback(err); - /** - * @template T - * @returns {Promise} 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); + compilation.startTime = startTime; + compilation.endTime = Date.now(); + logger.time("done hook"); + const stats = new Stats(compilation); + this.hooks.done.callAsync(stats, err => { + logger.timeEnd("done hook"); + if (err) return finalCallback(err); + this.cache.storeBuildDependencies( + compilation.buildDependencies, + err => { + if (err) return finalCallback(err); + return finalCallback(null, stats); + } + ); + }); + }); + }); }); }; - return next(0); - } - - /** - * @template T - * @param {T} data the value to store - * @param {CallbackCache} 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} promise signals when the value is stored - */ - storePromise(data) { - return Promise.all(this._items.map(item => item.storePromise(data))).then( - () => {} - ); - } -} + const run = () => { + this.hooks.beforeRun.callAsync(this, err => { + if (err) return finalCallback(err); -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; - } + this.hooks.run.callAsync(this, err => { + if (err) return finalCallback(err); - /** - * @template T - * @param {CallbackCache} callback signals when the value is retrieved - * @returns {void} - */ - get(callback) { - this._cache.get(this._name, this._etag, callback); - } + this.readRecords(err => { + if (err) return finalCallback(err); - /** - * @template T - * @returns {Promise} 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); - } + this.compile(onCompiled); + }); + }); }); - }); - } + }; - /** - * @template T - * @param {T} data the value to store - * @param {CallbackCache} callback signals when the value is stored - * @returns {void} - */ - store(data, callback) { - this._cache.store(this._name, this._etag, data, callback); - } + if (this.idle) { + this.cache.endIdle(err => { + if (err) return finalCallback(err); - /** - * @template T - * @param {T} data the value to store - * @returns {Promise} 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(); - } + this.idle = false; + run(); }); - }); + } else { + run(); + } } /** - * @template T - * @param {function(CallbackNormalErrorCache): void} computer function to compute the value if not cached - * @param {CallbackNormalErrorCache} callback signals when the value is retrieved + * @param {RunAsChildCallback} callback signals when the call finishes * @returns {void} */ - provide(computer, callback) { - this.get((err, cacheEntry) => { + runAsChild(callback) { + const startTime = Date.now(); + this.compile((err, compilation) => { 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} computer function to compute the value if not cached - * @returns {Promise} 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 - * @param {string | HashConstructor} hashFunction the hash function to use - */ - constructor(cache, name, hashFunction) { - this._cache = cache; - this._name = name; - this._hashFunction = hashFunction; - } - - /** - * @param {string} name the child cache name# - * @returns {CacheFacade} child cache - */ - getChildCache(name) { - return new CacheFacade( - this._cache, - `${this._name}|${name}`, - this._hashFunction - ); - } - - /** - * @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, this._hashFunction); - } + this.parentCompilation.children.push(compilation); + for (const { name, source, info } of compilation.getAssets()) { + this.parentCompilation.emitAsset(name, source, info); + } - /** - * @param {Etag} a an etag - * @param {Etag} b another etag - * @returns {Etag} an etag that represents both - */ - mergeEtags(a, b) { - return mergeEtags(a, b); - } + const entries = []; + for (const ep of compilation.entrypoints.values()) { + entries.push(...ep.chunks); + } - /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @param {CallbackCache} callback signals when the value is retrieved - * @returns {void} - */ - get(identifier, etag, callback) { - this._cache.get(`${this._name}|${identifier}`, etag, callback); - } + compilation.startTime = startTime; + compilation.endTime = Date.now(); - /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @returns {Promise} 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); - } - }); + return callback(null, entries, compilation); }); } - /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @param {T} data the value to store - * @param {CallbackCache} 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} 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(); - } - }); - }); + purgeInputFileSystem() { + if (this.inputFileSystem && this.inputFileSystem.purge) { + this.inputFileSystem.purge(); + } } /** - * @template T - * @param {string} identifier the cache identifier - * @param {Etag | null} etag the etag - * @param {function(CallbackNormalErrorCache): void} computer function to compute the value if not cached - * @param {CallbackNormalErrorCache} callback signals when the value is retrieved + * @param {Compilation} compilation the compilation + * @param {Callback} callback signals when the assets are emitted * @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} computer function to compute the value if not cached - * @returns {Promise} 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; - + emitAssets(compilation, callback) { + let outputPath; -/***/ }), + const emitFiles = err => { + if (err) return callback(err); -/***/ 77975: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const assets = compilation.getAssets(); + compilation.assets = { ...compilation.assets }; + /** @type {Map} */ + const caseInsensitiveMap = new Map(); + /** @type {Set} */ + const allTargetPaths = new Set(); + asyncLib.forEachLimit( + assets, + 15, + ({ name: file, source, info }, callback) => { + let targetFile = file; + let immutable = info.immutable; + const queryStringIdx = targetFile.indexOf("?"); + if (queryStringIdx >= 0) { + targetFile = targetFile.substr(0, queryStringIdx); + // We may remove the hash, which is in the query string + // So we recheck if the file is immutable + // This doesn't cover all cases, but immutable is only a performance optimization anyway + immutable = + immutable && + (includesHash(targetFile, info.contenthash) || + includesHash(targetFile, info.chunkhash) || + includesHash(targetFile, info.modulehash) || + includesHash(targetFile, info.fullhash)); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const writeOut = err => { + if (err) return callback(err); + const targetPath = join( + this.outputFileSystem, + outputPath, + targetFile + ); + allTargetPaths.add(targetPath); + // check if the target file has already been written by this Compiler + const targetFileGeneration = + this._assetEmittingWrittenFiles.get(targetPath); + // create an cache entry for this Source if not already existing + let cacheEntry = this._assetEmittingSourceCache.get(source); + if (cacheEntry === undefined) { + cacheEntry = { + sizeOnlySource: undefined, + writtenTo: new Map() + }; + this._assetEmittingSourceCache.set(source, cacheEntry); + } -const WebpackError = __webpack_require__(53799); + let similarEntry; -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ + const checkSimilarFile = () => { + const caseInsensitiveTargetPath = targetPath.toLowerCase(); + similarEntry = caseInsensitiveMap.get(caseInsensitiveTargetPath); + if (similarEntry !== undefined) { + const { path: other, source: otherSource } = similarEntry; + if (isSourceEqual(otherSource, source)) { + // Size may or may not be available at this point. + // If it's not available add to "waiting" list and it will be updated once available + if (similarEntry.size !== undefined) { + updateWithReplacementSource(similarEntry.size); + } else { + if (!similarEntry.waiting) similarEntry.waiting = []; + similarEntry.waiting.push({ file, cacheEntry }); + } + alreadyWritten(); + } else { + const err = + new WebpackError(`Prevent writing to file that only differs in casing or query string from already written file. +This will lead to a race-condition and corrupted files on case-insensitive file systems. +${targetPath} +${other}`); + err.file = file; + callback(err); + } + return true; + } else { + caseInsensitiveMap.set( + caseInsensitiveTargetPath, + (similarEntry = { + path: targetPath, + source, + size: undefined, + waiting: undefined + }) + ); + return false; + } + }; -/** - * @param {Module[]} modules the modules to be sorted - * @returns {Module[]} sorted version of original modules - */ -const sortModules = modules => { - return modules.sort((a, b) => { - const aIdent = a.identifier(); - const bIdent = b.identifier(); - /* istanbul ignore next */ - if (aIdent < bIdent) return -1; - /* istanbul ignore next */ - if (aIdent > bIdent) return 1; - /* istanbul ignore next */ - return 0; - }); -}; + /** + * get the binary (Buffer) content from the Source + * @returns {Buffer} content for the source + */ + const getContent = () => { + if (typeof source.buffer === "function") { + return source.buffer(); + } else { + const bufferOrString = source.source(); + if (Buffer.isBuffer(bufferOrString)) { + return bufferOrString; + } else { + return Buffer.from(bufferOrString, "utf8"); + } + } + }; -/** - * @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); + const alreadyWritten = () => { + // cache the information that the Source has been already been written to that location + if (targetFileGeneration === undefined) { + const newGeneration = 1; + this._assetEmittingWrittenFiles.set(targetPath, newGeneration); + cacheEntry.writtenTo.set(targetPath, newGeneration); + } else { + cacheEntry.writtenTo.set(targetPath, targetFileGeneration); + } + callback(); + }; - if (validReasons.length > 0) { - message += `\n Used by ${validReasons.length} module(s), i. e.`; - message += `\n ${validReasons[0].identifier()}`; - } - return message; - }) - .join("\n"); -}; + /** + * Write the file to output file system + * @param {Buffer} content content to be written + * @returns {void} + */ + const doWrite = content => { + this.outputFileSystem.writeFile(targetPath, content, err => { + if (err) return callback(err); -class CaseSensitiveModulesWarning extends WebpackError { - /** - * Creates an instance of CaseSensitiveModulesWarning. - * @param {Iterable} modules modules that were detected - * @param {ModuleGraph} moduleGraph the module graph - */ - constructor(modules, moduleGraph) { - const sortedModules = sortModules(Array.from(modules)); - const modulesList = createModulesListMessage(sortedModules, moduleGraph); - super(`There are multiple modules with names that only differ in casing. -This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. -Use equal casing. Compare these module identifiers: -${modulesList}`); + // information marker that the asset has been emitted + compilation.emittedAssets.add(file); - this.name = "CaseSensitiveModulesWarning"; - this.module = sortedModules[0]; - } -} + // cache the information that the Source has been written to that location + const newGeneration = + targetFileGeneration === undefined + ? 1 + : targetFileGeneration + 1; + cacheEntry.writtenTo.set(targetPath, newGeneration); + this._assetEmittingWrittenFiles.set(targetPath, newGeneration); + this.hooks.assetEmitted.callAsync( + file, + { + content, + source, + outputPath, + compilation, + targetPath + }, + callback + ); + }); + }; -module.exports = CaseSensitiveModulesWarning; + const updateWithReplacementSource = size => { + updateFileWithReplacementSource(file, cacheEntry, size); + similarEntry.size = size; + if (similarEntry.waiting !== undefined) { + for (const { file, cacheEntry } of similarEntry.waiting) { + updateFileWithReplacementSource(file, cacheEntry, size); + } + } + }; + const updateFileWithReplacementSource = ( + file, + cacheEntry, + size + ) => { + // Create a replacement resource which only allows to ask for size + // This allows to GC all memory allocated by the Source + // (expect when the Source is stored in any other cache) + if (!cacheEntry.sizeOnlySource) { + cacheEntry.sizeOnlySource = new SizeOnlySource(size); + } + compilation.updateAsset(file, cacheEntry.sizeOnlySource, { + size + }); + }; -/***/ }), + const processExistingFile = stats => { + // skip emitting if it's already there and an immutable file + if (immutable) { + updateWithReplacementSource(stats.size); + return alreadyWritten(); + } -/***/ 39385: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const content = getContent(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + updateWithReplacementSource(content.length); + // if it exists and content on disk matches content + // skip writing the same content again + // (to keep mtime and don't trigger watchers) + // for a fast negative match file size is compared first + if (content.length === stats.size) { + compilation.comparedForEmitAssets.add(file); + return this.outputFileSystem.readFile( + targetPath, + (err, existingContent) => { + if ( + err || + !content.equals(/** @type {Buffer} */ (existingContent)) + ) { + return doWrite(content); + } else { + return alreadyWritten(); + } + } + ); + } + return doWrite(content); + }; -const ChunkGraph = __webpack_require__(64971); -const Entrypoint = __webpack_require__(13795); -const { intersect } = __webpack_require__(93347); -const SortableSet = __webpack_require__(13098); -const StringXor = __webpack_require__(40293); -const { - compareModulesByIdentifier, - compareChunkGroupsByIndex, - compareModulesById -} = __webpack_require__(29579); -const { createArrayToSetDeprecationSet } = __webpack_require__(64518); -const { mergeRuntime } = __webpack_require__(17156); + const processMissingFile = () => { + const content = getContent(); -/** @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 */ + updateWithReplacementSource(content.length); -const ChunkFilesSet = createArrayToSetDeprecationSet("chunk.files"); + return doWrite(content); + }; -/** - * @typedef {Object} WithId an object who has an id property * - * @property {string | number} id the id of the object - */ + // if the target file has already been written + if (targetFileGeneration !== undefined) { + // check if the Source has been written to this target file + const writtenGeneration = cacheEntry.writtenTo.get(targetPath); + if (writtenGeneration === targetFileGeneration) { + // if yes, we may skip writing the file + // if it's already there + // (we assume one doesn't modify files while the Compiler is running, other then removing them) -/** - * @deprecated - * @typedef {Object} ChunkMaps - * @property {Record} hash - * @property {Record>} contentHash - * @property {Record} name - */ + if (this._assetEmittingPreviousFiles.has(targetPath)) { + // We assume that assets from the last compilation say intact on disk (they are not removed) + compilation.updateAsset(file, cacheEntry.sizeOnlySource, { + size: cacheEntry.sizeOnlySource.size() + }); -/** - * @deprecated - * @typedef {Object} ChunkModuleMaps - * @property {Record} id - * @property {Record} hash - */ + return callback(); + } else { + // Settings immutable will make it accept file content without comparing when file exist + immutable = true; + } + } else if (!immutable) { + if (checkSimilarFile()) return; + // We wrote to this file before which has very likely a different content + // skip comparing and assume content is different for performance + // This case happens often during watch mode. + return processMissingFile(); + } + } -let debugId = 1000; + if (checkSimilarFile()) return; + if (this.options.output.compareBeforeEmit) { + this.outputFileSystem.stat(targetPath, (err, stats) => { + const exists = !err && stats.isFile(); -/** - * A Chunk is a unit of encapsulation for Modules. - * Chunks are "rendered" into bundles that get emitted when the build completes. - */ -class Chunk { - /** - * @param {string=} name of chunk being created, is optional (for subclasses) - * @param {boolean} backCompat enable backward-compatibility - */ - constructor(name, backCompat = true) { - /** @type {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} */ - this.idNameHints = new SortableSet(); - /** @type {boolean} */ - this.preventIntegration = false; - /** @type {(string | function(PathData, AssetInfo=): string)?} */ - this.filenameTemplate = undefined; - /** @type {(string | function(PathData, AssetInfo=): string)?} */ - this.cssFilenameTemplate = undefined; - /** @private @type {SortableSet} */ - this._groups = new SortableSet(undefined, compareChunkGroupsByIndex); - /** @type {RuntimeSpec} */ - this.runtime = undefined; - /** @type {Set} */ - this.files = backCompat ? new ChunkFilesSet() : new Set(); - /** @type {Set} */ - this.auxiliaryFiles = new Set(); - /** @type {boolean} */ - this.rendered = false; - /** @type {string=} */ - this.hash = undefined; - /** @type {Record} */ - this.contentHash = Object.create(null); - /** @type {string=} */ - this.renderedHash = undefined; - /** @type {string=} */ - this.chunkReason = undefined; - /** @type {boolean} */ - this.extraAsync = false; - } + if (exists) { + processExistingFile(stats); + } else { + processMissingFile(); + } + }); + } else { + processMissingFile(); + } + }; - // 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)" + if (targetFile.match(/\/|\\/)) { + const fs = this.outputFileSystem; + const dir = dirname(fs, join(fs, outputPath, targetFile)); + mkdirp(fs, dir, writeOut); + } else { + writeOut(); + } + }, + err => { + // Clear map to free up memory + caseInsensitiveMap.clear(); + if (err) { + this._assetEmittingPreviousFiles.clear(); + return callback(err); + } + + this._assetEmittingPreviousFiles = allTargetPaths; + + this.hooks.afterEmit.callAsync(compilation, err => { + if (err) return callback(err); + + return callback(); + }); + } ); - } + }; + + this.hooks.emit.callAsync(compilation, err => { + if (err) return callback(err); + outputPath = compilation.getPath(this.outputPath, {}); + mkdirp(this.outputFileSystem, outputPath, emitFiles); + }); } /** - * @returns {boolean} true, if the chunk contains an entry module + * @param {Callback} callback signals when the call finishes + * @returns {void} */ - hasEntryModule() { - return ( - ChunkGraph.getChunkGraphForChunk( - this, - "Chunk.hasEntryModule", - "DEP_WEBPACK_CHUNK_HAS_ENTRY_MODULE" - ).getNumberOfEntryModules(this) > 0 - ); + emitRecords(callback) { + if (this.hooks.emitRecords.isUsed()) { + if (this.recordsOutputPath) { + asyncLib.parallel( + [ + cb => this.hooks.emitRecords.callAsync(cb), + this._emitRecords.bind(this) + ], + err => callback(err) + ); + } else { + this.hooks.emitRecords.callAsync(callback); + } + } else { + if (this.recordsOutputPath) { + this._emitRecords(callback); + } else { + callback(); + } + } } /** - * @param {Module} module the module - * @returns {boolean} true, if the chunk could be added + * @param {Callback} callback signals when the call finishes + * @returns {void} */ - addModule(module) { - const chunkGraph = ChunkGraph.getChunkGraphForChunk( - this, - "Chunk.addModule", - "DEP_WEBPACK_CHUNK_ADD_MODULE" + _emitRecords(callback) { + const writeFile = () => { + this.outputFileSystem.writeFile( + this.recordsOutputPath, + JSON.stringify( + this.records, + (n, value) => { + if ( + typeof value === "object" && + value !== null && + !Array.isArray(value) + ) { + const keys = Object.keys(value); + if (!isSorted(keys)) { + return sortObject(value, keys); + } + } + return value; + }, + 2 + ), + callback + ); + }; + + const recordsOutputPathDirectory = dirname( + this.outputFileSystem, + this.recordsOutputPath ); - if (chunkGraph.isModuleInChunk(module, this)) return false; - chunkGraph.connectChunkAndModule(this, module); - return true; + if (!recordsOutputPathDirectory) { + return writeFile(); + } + mkdirp(this.outputFileSystem, recordsOutputPathDirectory, err => { + if (err) return callback(err); + writeFile(); + }); } /** - * @param {Module} module the module + * @param {Callback} callback signals when the call finishes * @returns {void} */ - removeModule(module) { - ChunkGraph.getChunkGraphForChunk( - this, - "Chunk.removeModule", - "DEP_WEBPACK_CHUNK_REMOVE_MODULE" - ).disconnectChunkAndModule(this, module); + readRecords(callback) { + if (this.hooks.readRecords.isUsed()) { + if (this.recordsInputPath) { + asyncLib.parallel([ + cb => this.hooks.readRecords.callAsync(cb), + this._readRecords.bind(this) + ]); + } else { + this.records = {}; + this.hooks.readRecords.callAsync(callback); + } + } else { + if (this.recordsInputPath) { + this._readRecords(callback); + } else { + this.records = {}; + callback(); + } + } } /** - * @returns {number} the number of module which are contained in this chunk + * @param {Callback} callback signals when the call finishes + * @returns {void} */ - getNumberOfModules() { - return ChunkGraph.getChunkGraphForChunk( - this, - "Chunk.getNumberOfModules", - "DEP_WEBPACK_CHUNK_GET_NUMBER_OF_MODULES" - ).getNumberOfChunkModules(this); - } + _readRecords(callback) { + if (!this.recordsInputPath) { + this.records = {}; + return callback(); + } + this.inputFileSystem.stat(this.recordsInputPath, err => { + // It doesn't exist + // We can ignore this. + if (err) return callback(); - get modulesIterable() { - const chunkGraph = ChunkGraph.getChunkGraphForChunk( - this, - "Chunk.modulesIterable", - "DEP_WEBPACK_CHUNK_MODULES_ITERABLE" - ); - return chunkGraph.getOrderedChunkModulesIterable( - this, - compareModulesByIdentifier - ); - } + this.inputFileSystem.readFile(this.recordsInputPath, (err, content) => { + if (err) return callback(err); - /** - * @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); - } + try { + this.records = parseJson(content.toString("utf-8")); + } catch (e) { + e.message = "Cannot parse records: " + e.message; + return callback(e); + } - /** - * @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); + return callback(); + }); + }); } /** - * @returns {Module[]} the modules for this chunk + * @param {Compilation} compilation the compilation + * @param {string} compilerName the compiler's name + * @param {number} compilerIndex the compiler's index + * @param {OutputOptions=} outputOptions the output options + * @param {WebpackPluginInstance[]=} plugins the plugins to apply + * @returns {Compiler} a child compiler */ - getModules() { - return ChunkGraph.getChunkGraphForChunk( - this, - "Chunk.getModules", - "DEP_WEBPACK_CHUNK_GET_MODULES" - ).getChunkModules(this); - } + createChildCompiler( + compilation, + compilerName, + compilerIndex, + outputOptions, + plugins + ) { + const childCompiler = new Compiler(this.context, { + ...this.options, + output: { + ...this.options.output, + ...outputOptions + } + }); + childCompiler.name = compilerName; + childCompiler.outputPath = this.outputPath; + childCompiler.inputFileSystem = this.inputFileSystem; + childCompiler.outputFileSystem = null; + childCompiler.resolverFactory = this.resolverFactory; + childCompiler.modifiedFiles = this.modifiedFiles; + childCompiler.removedFiles = this.removedFiles; + childCompiler.fileTimestamps = this.fileTimestamps; + childCompiler.contextTimestamps = this.contextTimestamps; + childCompiler.fsStartTime = this.fsStartTime; + childCompiler.cache = this.cache; + childCompiler.compilerPath = `${this.compilerPath}${compilerName}|${compilerIndex}|`; + childCompiler._backCompat = this._backCompat; - /** - * @returns {void} - */ - remove() { - const chunkGraph = ChunkGraph.getChunkGraphForChunk( - this, - "Chunk.remove", - "DEP_WEBPACK_CHUNK_REMOVE" + const relativeCompilerName = makePathsRelative( + this.context, + compilerName, + this.root ); - chunkGraph.disconnectChunk(this); - this.disconnectFromGroups(); - } + if (!this.records[relativeCompilerName]) { + this.records[relativeCompilerName] = []; + } + if (this.records[relativeCompilerName][compilerIndex]) { + childCompiler.records = this.records[relativeCompilerName][compilerIndex]; + } else { + this.records[relativeCompilerName].push((childCompiler.records = {})); + } - /** - * @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" + childCompiler.parentCompilation = compilation; + childCompiler.root = this.root; + if (Array.isArray(plugins)) { + for (const plugin of plugins) { + plugin.apply(childCompiler); + } + } + for (const name in this.hooks) { + if ( + ![ + "make", + "compile", + "emit", + "afterEmit", + "invalid", + "done", + "thisCompilation" + ].includes(name) + ) { + if (childCompiler.hooks[name]) { + childCompiler.hooks[name].taps = this.hooks[name].taps.slice(); + } + } + } + + compilation.hooks.childCompiler.call( + childCompiler, + compilerName, + compilerIndex ); - chunkGraph.disconnectChunkAndModule(this, module); - chunkGraph.connectChunkAndModule(otherChunk, module); + + return childCompiler; } - /** - * @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; - } + isChild() { + return !!this.parentCompilation; } - /** - * @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); + createCompilation(params) { + this._cleanupLastCompilation(); + return (this._lastCompilation = new Compilation(this, params)); } /** - * @returns {boolean} true, if this chunk contains no module + * @param {CompilationParams} params the compilation parameters + * @returns {Compilation} the created compilation */ - isEmpty() { - const chunkGraph = ChunkGraph.getChunkGraphForChunk( - this, - "Chunk.isEmpty", - "DEP_WEBPACK_CHUNK_IS_EMPTY" - ); - return chunkGraph.getNumberOfChunkModules(this) === 0; + newCompilation(params) { + const compilation = this.createCompilation(params); + compilation.name = this.name; + compilation.records = this.records; + this.hooks.thisCompilation.call(compilation, params); + this.hooks.compilation.call(compilation, params); + return compilation; } - /** - * @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); + createNormalModuleFactory() { + this._cleanupLastNormalModuleFactory(); + const normalModuleFactory = new NormalModuleFactory({ + context: this.options.context, + fs: this.inputFileSystem, + resolverFactory: this.resolverFactory, + options: this.options.module, + associatedObjectForCache: this.root, + layers: this.options.experiments.layers + }); + this._lastNormalModuleFactory = normalModuleFactory; + this.hooks.normalModuleFactory.call(normalModuleFactory); + return normalModuleFactory; } - /** - * @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); + createContextModuleFactory() { + const contextModuleFactory = new ContextModuleFactory(this.resolverFactory); + this.hooks.contextModuleFactory.call(contextModuleFactory); + return contextModuleFactory; } - /** - * @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); + newCompilationParams() { + const params = { + normalModuleFactory: this.createNormalModuleFactory(), + contextModuleFactory: this.createContextModuleFactory() + }; + return params; } /** - * @param {ModuleFilterPredicate} filterFn function used to filter modules - * @returns {ChunkModuleMaps} module map information + * @param {Callback} callback signals when the compilation finishes + * @returns {void} */ - getChunkModuleMaps(filterFn) { - const chunkGraph = ChunkGraph.getChunkGraphForChunk( - this, - "Chunk.getChunkModuleMaps", - "DEP_WEBPACK_CHUNK_GET_CHUNK_MODULE_MAPS" - ); - /** @type {Record} */ - const chunkModuleIdMap = Object.create(null); - /** @type {Record} */ - const chunkModuleHashMap = Object.create(null); + compile(callback) { + const params = this.newCompilationParams(); + this.hooks.beforeCompile.callAsync(params, err => { + if (err) return callback(err); - 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 - ); - } - } - } + this.hooks.compile.call(params); - return { - id: chunkModuleIdMap, - hash: chunkModuleHashMap - }; + const compilation = this.newCompilation(params); + + const logger = compilation.getLogger("webpack.Compiler"); + + logger.time("make hook"); + this.hooks.make.callAsync(compilation, err => { + logger.timeEnd("make hook"); + if (err) return callback(err); + + logger.time("finish make hook"); + this.hooks.finishMake.callAsync(compilation, err => { + logger.timeEnd("finish make hook"); + if (err) return callback(err); + + process.nextTick(() => { + logger.time("finish compilation"); + compilation.finish(err => { + logger.timeEnd("finish compilation"); + if (err) return callback(err); + + logger.time("seal compilation"); + compilation.seal(err => { + logger.timeEnd("seal compilation"); + if (err) return callback(err); + + logger.time("afterCompile hook"); + this.hooks.afterCompile.callAsync(compilation, err => { + logger.timeEnd("afterCompile hook"); + if (err) return callback(err); + + return callback(null, compilation); + }); + }); + }); + }); + }); + }); + }); } /** - * @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 + * @param {Callback} callback signals when the compiler closes + * @returns {void} */ - hasModuleInGraph(filterFn, filterChunkFn) { - const chunkGraph = ChunkGraph.getChunkGraphForChunk( - this, - "Chunk.hasModuleInGraph", - "DEP_WEBPACK_CHUNK_HAS_MODULE_IN_GRAPH" - ); - return chunkGraph.hasModuleInGraph(this, filterFn, filterChunkFn); + close(callback) { + if (this.watching) { + // When there is still an active watching, close this first + this.watching.close(err => { + this.close(callback); + }); + return; + } + this.hooks.shutdown.callAsync(err => { + if (err) return callback(err); + // Get rid of reference to last compilation to avoid leaking memory + // We can't run this._cleanupLastCompilation() as the Stats to this compilation + // might be still in use. We try to get rid of the reference to the cache instead. + this._lastCompilation = undefined; + this._lastNormalModuleFactory = undefined; + this.cache.shutdown(callback); + }); } +} + +module.exports = Compiler; + + +/***/ }), + +/***/ 98229: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @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} exportMap mapping from export name to symbol + * @property {Map} 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 { /** - * @deprecated - * @param {boolean} realHash whether the full hash or the rendered hash is to be used - * @returns {ChunkMaps} the chunk map information + * @param {ModuleInfo[] | Map} modulesMap all module info by module + * @param {ConcatenatedModuleInfo} currentModule the current module info */ - getChunkMaps(realHash) { - /** @type {Record} */ - const chunkHashMap = Object.create(null); - /** @type {Record>} */ - const chunkContentHashMap = Object.create(null); - /** @type {Record} */ - 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; + 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; } - - return { - hash: chunkHashMap, - contentHash: chunkContentHashMap, - name: chunkNameMap - }; + this._modulesMap = modulesMap; } - // BACKWARD-COMPAT END /** - * @returns {boolean} whether or not the Chunk will have a runtime + * @param {Module} module the referenced module + * @returns {boolean} true, when it's in the scope */ - hasRuntime() { - for (const chunkGroup of this._groups) { - if ( - chunkGroup instanceof Entrypoint && - chunkGroup.getRuntimeChunk() === this - ) { - return true; - } - } - return false; + isModuleInScope(module) { + return this._modulesMap.has(module); } /** - * @returns {boolean} whether or not this chunk can be an initial chunk + * + * @param {string} exportName name of the export + * @param {string} symbol identifier of the export in source code */ - canBeInitial() { - for (const chunkGroup of this._groups) { - if (chunkGroup.isInitial()) return true; + registerExport(exportName, symbol) { + if (!this._currentModule.exportMap) { + this._currentModule.exportMap = new Map(); + } + if (!this._currentModule.exportMap.has(exportName)) { + this._currentModule.exportMap.set(exportName, symbol); } - return false; } /** - * @returns {boolean} whether this chunk can only be an initial chunk + * + * @param {string} exportName name of the export + * @param {string} expression expression to be used */ - isOnlyInitial() { - if (this._groups.size <= 0) return false; - for (const chunkGroup of this._groups) { - if (!chunkGroup.isInitial()) return false; + registerRawExport(exportName, expression) { + if (!this._currentModule.rawExportMap) { + this._currentModule.rawExportMap = new Map(); + } + if (!this._currentModule.rawExportMap.has(exportName)) { + this._currentModule.rawExportMap.set(exportName, expression); } - return true; } /** - * @returns {EntryOptions | undefined} the entry options for this chunk + * @param {string} symbol identifier of the export in source code */ - getEntryOptions() { - for (const chunkGroup of this._groups) { - if (chunkGroup instanceof Entrypoint) { - return chunkGroup.options; - } - } - return undefined; + registerNamespaceExport(symbol) { + this._currentModule.namespaceExportSymbol = symbol; } /** - * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being added - * @returns {void} + * + * @param {Module} module the referenced module + * @param {Partial} options options + * @returns {string} the reference as identifier */ - addGroup(chunkGroup) { - this._groups.add(chunkGroup); + 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 {ChunkGroup} chunkGroup the chunkGroup the chunk is being removed from - * @returns {void} + * @param {string} name the identifier + * @returns {boolean} true, when it's an module reference */ - removeGroup(chunkGroup) { - this._groups.delete(chunkGroup); + static isModuleReference(name) { + return MODULE_REFERENCE_REGEXP.test(name); } /** - * @param {ChunkGroup} chunkGroup the chunkGroup to check - * @returns {boolean} returns true if chunk has chunkGroup reference and exists in chunkGroup + * @param {string} name the identifier + * @returns {ModuleReferenceOptions & { index: number }} parsed options and index */ - isInGroup(chunkGroup) { - return this._groups.has(chunkGroup); + 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 + }; } +} - /** - * @returns {number} the amount of groups that the said chunk is in - */ - getNumberOfGroups() { - return this._groups.size; - } +ConcatenationScope.DEFAULT_EXPORT = DEFAULT_EXPORT; +ConcatenationScope.NAMESPACE_OBJECT_EXPORT = NAMESPACE_OBJECT_EXPORT; - /** - * @returns {Iterable} the chunkGroups that the said chunk is referenced in - */ - get groupsIterable() { - this._groups.sort(); - return this._groups; - } +module.exports = ConcatenationScope; - /** - * @returns {void} - */ - disconnectFromGroups() { - for (const chunkGroup of this._groups) { - chunkGroup.removeChunk(this); - } - } - /** - * @param {Chunk} newChunk the new chunk that will be split out of - * @returns {void} - */ - split(newChunk) { - for (const chunkGroup of this._groups) { - chunkGroup.insertChunk(newChunk, this); - newChunk.addGroup(chunkGroup); - } - for (const idHint of this.idNameHints) { - newChunk.idNameHints.add(idHint); - } - newChunk.runtime = mergeRuntime(newChunk.runtime, this.runtime); - } +/***/ }), - /** - * @param {Hash} hash hash (will be modified) - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {void} - */ - updateHash(hash, chunkGraph) { - hash.update( - `${this.id} ${this.ids ? this.ids.join() : ""} ${this.name || ""} ` - ); - const xor = new StringXor(); - for (const m of chunkGraph.getChunkModulesIterable(this)) { - xor.add(chunkGraph.getModuleHash(m, this.runtime)); - } - xor.updateHash(hash); - const entryModules = - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(this); - for (const [m, chunkGroup] of entryModules) { - hash.update(`entry${chunkGraph.getModuleId(m)}${chunkGroup.id}`); - } +/***/ 95735: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Maksim Nazarjev @acupofspirt +*/ + + + +const WebpackError = __webpack_require__(53799); + +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."; } +}; - /** - * @returns {Set} a set of all the async chunks - */ - getAllAsyncChunks() { - const queue = new Set(); - const chunks = new Set(); - const initialChunks = intersect( - Array.from(this.groupsIterable, g => new Set(g.chunks)) - ); +/***/ }), - const initialQueue = new Set(this.groupsIterable); +/***/ 61333: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - for (const chunkGroup of initialQueue) { - for (const child of chunkGroup.childrenIterable) { - if (child instanceof Entrypoint) { - initialQueue.add(child); - } else { - queue.add(child); - } - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - 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; + +const { ConcatSource, PrefixSource } = __webpack_require__(51255); +const InitFragment = __webpack_require__(55870); +const Template = __webpack_require__(1626); +const { mergeRuntime } = __webpack_require__(17156); + +/** @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" + ); } +}; +/** + * @typedef {GenerateContext} Context + */ +class ConditionalInitFragment extends InitFragment { /** - * @returns {Set} a set of all the initial chunks (including itself) + * @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 */ - getAllInitialChunks() { - const chunks = new Set(); - const queue = new Set(this.groupsIterable); - for (const group of queue) { - if (group.isInitial()) { - for (const c of group.chunks) chunks.add(c); - for (const g of group.childrenIterable) queue.add(g); - } - } - return chunks; + constructor( + content, + stage, + position, + key, + runtimeCondition = true, + endContent + ) { + super(content, stage, position, key, endContent); + this.runtimeCondition = runtimeCondition; } /** - * @returns {Set} a set of all the referenced chunks (including itself) + * @param {Context} context context + * @returns {string|Source} the source code that will be included as initialization code */ - 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; + getContent(context) { + if (this.runtimeCondition === false || !this.content) return ""; + if (this.runtimeCondition === true) return this.content; + const expr = context.runtimeTemplate.runtimeConditionExpression({ + chunkGraph: context.chunkGraph, + runtimeRequirements: context.runtimeRequirements, + runtime: context.runtime, + runtimeCondition: this.runtimeCondition + }); + if (expr === "true") return this.content; + return wrapInCondition(expr, this.content); } /** - * @returns {Set} a set of all the referenced entrypoints + * @param {Context} context context + * @returns {string|Source=} the source code that will be included at the end of the module */ - 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); - } - } + getEndContent(context) { + if (this.runtimeCondition === false || !this.endContent) return ""; + if (this.runtimeCondition === true) return this.endContent; + const expr = context.runtimeTemplate.runtimeConditionExpression({ + chunkGraph: context.chunkGraph, + runtimeRequirements: context.runtimeRequirements, + runtime: context.runtime, + runtimeCondition: this.runtimeCondition + }); + if (expr === "true") return this.endContent; + return wrapInCondition(expr, this.endContent); + } - return entrypoints; + 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 + ); } +} - /** - * @returns {boolean} true, if the chunk references async chunks - */ - hasAsyncChunks() { - const queue = new Set(); +module.exports = ConditionalInitFragment; - 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; +/***/ 11146: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const CachedConstDependency = __webpack_require__(57403); +const ConstDependency = __webpack_require__(76911); +const { evaluateToString } = __webpack_require__(93998); +const { parseResource } = __webpack_require__(82186); + +/** @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); + } } - } - for (const child of chunkGroup.childrenIterable) { - queue.add(child); - } + 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; } - - return false; } +}; - /** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {ChunkFilterPredicate=} filterFn function used to filter chunks - * @returns {Record} a record object of names to lists of child ids(?) - */ - getChildIdsByOrders(chunkGraph, filterFn) { - /** @type {Map} */ - 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 - }); - } +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); } } - } - } - /** @type {Record} */ - 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} */ - 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); + break; + case "TryStatement": + stack.push(node.block); + if (node.handler) { + stack.push(node.handler.body); } - } - if (chunkIdSet.size > 0) { - result[name] = Array.from(chunkIdSet); - } + 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 result; } + return Array.from(declarations); +}; +class ConstPlugin { /** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {string} type option name - * @returns {{ onChunks: Chunk[], chunks: Set }[]} referenced chunks for a specific type + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - 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) - }) + 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); } - } - 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>} a record object of names to lists of child ids(?) by chunk id - */ - getChildIdsByOrdersMap(chunkGraph, includeDirectChildren, filterFn) { - /** @type {Record>} */ - const chunkMaps = Object.create(null); +module.exports = ConstPlugin; - /** - * @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} */ - 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); - } +/***/ 21411: +/***/ (function(module) { - return chunkMaps; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +/** @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 = Chunk; +module.exports = ContextExclusionPlugin; /***/ }), -/***/ 64971: +/***/ 76729: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -26166,1732 +29327,1488 @@ module.exports = Chunk; -const util = __webpack_require__(73837); -const Entrypoint = __webpack_require__(13795); -const ModuleGraphConnection = __webpack_require__(40639); -const { first } = __webpack_require__(93347); -const SortableSet = __webpack_require__(13098); +const { OriginalSource, RawSource } = __webpack_require__(51255); +const AsyncDependenciesBlock = __webpack_require__(47736); +const { makeWebpackError } = __webpack_require__(11351); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const WebpackError = __webpack_require__(53799); const { - compareModulesById, - compareIterables, - compareModulesByIdentifier, + compareLocations, concatComparators, compareSelect, - compareIds + keepOriginalOrder, + compareModulesById } = __webpack_require__(29579); -const createHash = __webpack_require__(49835); -const findGraphRoots = __webpack_require__(6261); -const { - RuntimeSpecMap, - RuntimeSpecSet, - runtimeToString, - mergeRuntime, - forEachRuntime -} = __webpack_require__(17156); +const { contextify, parseResource } = __webpack_require__(82186); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./Module")} Module */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Module").BuildMeta} BuildMeta */ +/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./RuntimeModule")} RuntimeModule */ -/** @typedef {typeof import("./util/Hash")} Hash */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ - -/** @type {ReadonlySet} */ -const EMPTY_SET = new Set(); - -const ZERO_BIG_INT = BigInt(0); - -const compareModuleIterables = compareIterables(compareModulesByIdentifier); +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */ +/** @template T @typedef {import("./util/LazySet")} LazySet */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {(c: Chunk, chunkGraph: ChunkGraph) => boolean} ChunkFilterPredicate */ -/** @typedef {(m: Module) => boolean} ModuleFilterPredicate */ +/** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */ /** - * @typedef {Object} ChunkSizeOptions - * @property {number=} chunkOverhead constant overhead for a chunk - * @property {number=} entryChunkMultiplicator multiplicator for initial chunks + * @typedef {Object} ContextOptions + * @property {ContextMode} mode + * @property {boolean} recursive + * @property {RegExp} regExp + * @property {"strict"|boolean=} namespaceObject + * @property {string=} addon + * @property {string=} chunkName + * @property {RegExp=} include + * @property {RegExp=} exclude + * @property {RawChunkGroupOptions=} groupOptions + * @property {string=} typePrefix + * @property {string=} category + * @property {string[][]=} referencedExports exports referenced from modules (won't be mangled) */ -class ModuleHashInfo { - constructor(hash, renderedHash) { - this.hash = hash; - this.renderedHash = renderedHash; - } -} - -/** @template T @typedef {(set: SortableSet) => T[]} SetToArrayFunction */ - /** - * @template T - * @param {SortableSet} set the set - * @returns {T[]} set as array + * @typedef {Object} ContextModuleOptionsExtras + * @property {string} resource + * @property {string=} resourceQuery + * @property {string=} resourceFragment + * @property {TODO} resolveOptions */ -const getArray = set => { - return Array.from(set); -}; + +/** @typedef {ContextOptions & ContextModuleOptionsExtras} ContextModuleOptions */ /** - * @param {SortableSet} chunks the chunks - * @returns {RuntimeSpecSet} runtimes + * @callback ResolveDependenciesCallback + * @param {(Error | null)=} err + * @param {ContextElementDependency[]=} dependencies */ -const getModuleRuntimes = chunks => { - const runtimes = new RuntimeSpecSet(); - for (const chunk of chunks) { - runtimes.add(chunk.runtime); - } - return runtimes; -}; /** - * @param {SortableSet} set the set - * @returns {Map>} modules by source type + * @callback ResolveDependencies + * @param {InputFileSystem} fs + * @param {ContextModuleOptions} options + * @param {ResolveDependenciesCallback} callback */ -const modulesBySourceType = set => { - /** @type {Map>} */ - const map = new Map(); - for (const module of set) { - for (const sourceType of module.getSourceTypes()) { - let innerSet = map.get(sourceType); - if (innerSet === undefined) { - innerSet = new SortableSet(); - map.set(sourceType, innerSet); - } - innerSet.add(module); - } - } - for (const [key, innerSet] of map) { - // When all modules have the source type, we reuse the original SortableSet - // to benefit from the shared cache (especially for sorting) - if (innerSet.size === set.size) { - map.set(key, set); - } - } - return map; -}; -/** @type {WeakMap} */ -const createOrderedArrayFunctionMap = new WeakMap(); +const SNAPSHOT_OPTIONS = { timestamp: true }; -/** - * @template T - * @param {function(T, T): -1|0|1} comparator comparator function - * @returns {SetToArrayFunction} set as ordered array - */ -const createOrderedArrayFunction = comparator => { - /** @type {SetToArrayFunction} */ - let fn = createOrderedArrayFunctionMap.get(comparator); - if (fn !== undefined) return fn; - fn = set => { - set.sortWith(comparator); - return Array.from(set); - }; - createOrderedArrayFunctionMap.set(comparator, fn); - return fn; -}; +const TYPES = new Set(["javascript"]); -/** - * @param {Iterable} modules the modules to get the count/size of - * @returns {number} the size of the modules - */ -const getModulesSize = modules => { - let size = 0; - for (const module of modules) { - for (const type of module.getSourceTypes()) { - size += module.size(type); - } - } - return size; -}; +class ContextModule extends Module { + /** + * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context + * @param {ContextModuleOptions} options options object + */ + constructor(resolveDependencies, options) { + const parsed = parseResource(options ? options.resource : ""); + const resource = parsed.path; + const resourceQuery = (options && options.resourceQuery) || parsed.query; + const resourceFragment = + (options && options.resourceFragment) || parsed.fragment; -/** - * @param {Iterable} modules the sortable Set to get the size of - * @returns {Record} the sizes of the modules - */ -const getModulesSizes = modules => { - let sizes = Object.create(null); - for (const module of modules) { - for (const type of module.getSourceTypes()) { - sizes[type] = (sizes[type] || 0) + module.size(type); - } - } - return sizes; -}; + super("javascript/dynamic", resource); -/** - * @param {Chunk} a chunk - * @param {Chunk} b chunk - * @returns {boolean} true, if a is always a parent of b - */ -const isAvailableChunk = (a, b) => { - const queue = new Set(b.groupsIterable); - for (const chunkGroup of queue) { - if (a.isInGroup(chunkGroup)) continue; - if (chunkGroup.isInitial()) return false; - for (const parent of chunkGroup.parentsIterable) { - queue.add(parent); + // Info from Factory + this.resolveDependencies = resolveDependencies; + /** @type {ContextModuleOptions} */ + this.options = { + ...options, + resource, + resourceQuery, + resourceFragment + }; + if (options && options.resolveOptions !== undefined) { + this.resolveOptions = options.resolveOptions; } - } - return true; -}; -class ChunkGraphModule { - constructor() { - /** @type {SortableSet} */ - this.chunks = new SortableSet(); - /** @type {Set | undefined} */ - this.entryInChunks = undefined; - /** @type {Set | undefined} */ - this.runtimeInChunks = undefined; - /** @type {RuntimeSpecMap} */ - this.hashes = undefined; - /** @type {string | number} */ - this.id = null; - /** @type {RuntimeSpecMap> | undefined} */ - this.runtimeRequirements = undefined; - /** @type {RuntimeSpecMap} */ - this.graphHashes = undefined; - /** @type {RuntimeSpecMap} */ - this.graphHashesWithConnections = undefined; - } -} + if (options && typeof options.mode !== "string") { + throw new Error("options.mode is a required option"); + } -class ChunkGraphChunk { - constructor() { - /** @type {SortableSet} */ - this.modules = new SortableSet(); - /** @type {Map} */ - this.entryModules = new Map(); - /** @type {SortableSet} */ - this.runtimeModules = new SortableSet(); - /** @type {Set | undefined} */ - this.fullHashModules = undefined; - /** @type {Set | undefined} */ - this.dependentHashModules = undefined; - /** @type {Set | undefined} */ - this.runtimeRequirements = undefined; - /** @type {Set} */ - this.runtimeRequirementsInTree = new Set(); + this._identifier = this._createIdentifier(); + this._forceBuild = true; } -} -class ChunkGraph { /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {string | Hash} hashFunction the hash function to use + * @returns {Set} types available (do not mutate) */ - constructor(moduleGraph, hashFunction = "md4") { - /** @private @type {WeakMap} */ - this._modules = new WeakMap(); - /** @private @type {WeakMap} */ - this._chunks = new WeakMap(); - /** @private @type {WeakMap} */ - this._blockChunkGroups = new WeakMap(); - /** @private @type {Map} */ - this._runtimeIds = new Map(); - /** @type {ModuleGraph} */ - this.moduleGraph = moduleGraph; - - this._hashFunction = hashFunction; - - this._getGraphRoots = this._getGraphRoots.bind(this); + getSourceTypes() { + return TYPES; } /** - * @private - * @param {Module} module the module - * @returns {ChunkGraphModule} internal module + * 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} */ - _getChunkGraphModule(module) { - let cgm = this._modules.get(module); - if (cgm === undefined) { - cgm = new ChunkGraphModule(); - this._modules.set(module, cgm); - } - return cgm; + updateCacheModule(module) { + const m = /** @type {ContextModule} */ (module); + this.resolveDependencies = m.resolveDependencies; + this.options = m.options; } /** - * @private - * @param {Chunk} chunk the chunk - * @returns {ChunkGraphChunk} internal chunk + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. */ - _getChunkGraphChunk(chunk) { - let cgc = this._chunks.get(chunk); - if (cgc === undefined) { - cgc = new ChunkGraphChunk(); - this._chunks.set(chunk, cgc); - } - return cgc; + cleanupForCache() { + super.cleanupForCache(); + this.resolveDependencies = undefined; } - /** - * @param {SortableSet} set the sortable Set to get the roots of - * @returns {Module[]} the graph roots - */ - _getGraphRoots(set) { - const { moduleGraph } = this; - return Array.from( - findGraphRoots(set, module => { - /** @type {Set} */ - const set = new Set(); - const addDependencies = module => { - for (const connection of moduleGraph.getOutgoingConnections(module)) { - if (!connection.module) continue; - const activeState = connection.getActiveState(undefined); - if (activeState === false) continue; - if (activeState === ModuleGraphConnection.TRANSITIVE_ONLY) { - addDependencies(connection.module); - continue; - } - set.add(connection.module); - } - }; - addDependencies(module); - return set; - }) - ).sort(compareModulesByIdentifier); + _prettyRegExp(regexString, stripSlash = true) { + const str = (regexString + "").replace(/!/g, "%21").replace(/\|/g, "%7C"); + return stripSlash ? str.substring(1, str.length - 1) : str; } - /** - * @param {Chunk} chunk the new chunk - * @param {Module} module the module - * @returns {void} - */ - connectChunkAndModule(chunk, module) { - const cgm = this._getChunkGraphModule(module); - const cgc = this._getChunkGraphChunk(chunk); - cgm.chunks.add(chunk); - cgc.modules.add(module); - } + _createIdentifier() { + let identifier = this.context; + if (this.options.resourceQuery) { + identifier += `|${this.options.resourceQuery}`; + } + if (this.options.resourceFragment) { + identifier += `|${this.options.resourceFragment}`; + } + if (this.options.mode) { + identifier += `|${this.options.mode}`; + } + if (!this.options.recursive) { + identifier += "|nonrecursive"; + } + if (this.options.addon) { + identifier += `|${this.options.addon}`; + } + if (this.options.regExp) { + identifier += `|${this._prettyRegExp(this.options.regExp, false)}`; + } + if (this.options.include) { + identifier += `|include: ${this._prettyRegExp( + this.options.include, + false + )}`; + } + if (this.options.exclude) { + identifier += `|exclude: ${this._prettyRegExp( + this.options.exclude, + false + )}`; + } + if (this.options.referencedExports) { + identifier += `|referencedExports: ${JSON.stringify( + this.options.referencedExports + )}`; + } + if (this.options.chunkName) { + identifier += `|chunkName: ${this.options.chunkName}`; + } + if (this.options.groupOptions) { + identifier += `|groupOptions: ${JSON.stringify( + this.options.groupOptions + )}`; + } + if (this.options.namespaceObject === "strict") { + identifier += "|strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += "|namespace object"; + } - /** - * @param {Chunk} chunk the chunk - * @param {Module} module the module - * @returns {void} - */ - disconnectChunkAndModule(chunk, module) { - const cgm = this._getChunkGraphModule(module); - const cgc = this._getChunkGraphChunk(chunk); - cgc.modules.delete(module); - cgm.chunks.delete(chunk); + return identifier; } /** - * @param {Chunk} chunk the chunk which will be disconnected - * @returns {void} + * @returns {string} a unique identifier of the module */ - disconnectChunk(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - for (const module of cgc.modules) { - const cgm = this._getChunkGraphModule(module); - cgm.chunks.delete(chunk); - } - cgc.modules.clear(); - chunk.disconnectFromGroups(); - ChunkGraph.clearChunkGraphForChunk(chunk); + identifier() { + return this._identifier; } /** - * @param {Chunk} chunk the chunk - * @param {Iterable} modules the modules - * @returns {void} + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module */ - attachModules(chunk, modules) { - const cgc = this._getChunkGraphChunk(chunk); - for (const module of modules) { - cgc.modules.add(module); + readableIdentifier(requestShortener) { + let identifier = requestShortener.shorten(this.context) + "/"; + if (this.options.resourceQuery) { + identifier += ` ${this.options.resourceQuery}`; + } + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (!this.options.recursive) { + identifier += " nonrecursive"; + } + if (this.options.addon) { + identifier += ` ${requestShortener.shorten(this.options.addon)}`; + } + if (this.options.regExp) { + identifier += ` ${this._prettyRegExp(this.options.regExp)}`; + } + if (this.options.include) { + identifier += ` include: ${this._prettyRegExp(this.options.include)}`; } + if (this.options.exclude) { + identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`; + } + if (this.options.referencedExports) { + identifier += ` referencedExports: ${this.options.referencedExports + .map(e => e.join(".")) + .join(", ")}`; + } + if (this.options.chunkName) { + identifier += ` chunkName: ${this.options.chunkName}`; + } + if (this.options.groupOptions) { + const groupOptions = this.options.groupOptions; + for (const key of Object.keys(groupOptions)) { + identifier += ` ${key}: ${groupOptions[key]}`; + } + } + if (this.options.namespaceObject === "strict") { + identifier += " strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += " namespace object"; + } + + return identifier; } /** - * @param {Chunk} chunk the chunk - * @param {Iterable} modules the runtime modules - * @returns {void} + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion */ - attachRuntimeModules(chunk, modules) { - const cgc = this._getChunkGraphChunk(chunk); - for (const module of modules) { - cgc.runtimeModules.add(module); + libIdent(options) { + let identifier = contextify( + options.context, + this.context, + options.associatedObjectForCache + ); + if (this.layer) identifier = `(${this.layer})/${identifier}`; + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (this.options.recursive) { + identifier += " recursive"; + } + if (this.options.addon) { + identifier += ` ${contextify( + options.context, + this.options.addon, + options.associatedObjectForCache + )}`; + } + if (this.options.regExp) { + identifier += ` ${this._prettyRegExp(this.options.regExp)}`; + } + if (this.options.include) { + identifier += ` include: ${this._prettyRegExp(this.options.include)}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`; + } + if (this.options.referencedExports) { + identifier += ` referencedExports: ${this.options.referencedExports + .map(e => e.join(".")) + .join(", ")}`; } + + return identifier; } /** - * @param {Chunk} chunk the chunk - * @param {Iterable} modules the modules that require a full hash * @returns {void} */ - attachFullHashModules(chunk, modules) { - const cgc = this._getChunkGraphChunk(chunk); - if (cgc.fullHashModules === undefined) cgc.fullHashModules = new Set(); - for (const module of modules) { - cgc.fullHashModules.add(module); - } + invalidateBuild() { + this._forceBuild = true; } /** - * @param {Chunk} chunk the chunk - * @param {Iterable} modules the modules that require a full hash + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild * @returns {void} */ - attachDependentHashModules(chunk, modules) { - const cgc = this._getChunkGraphChunk(chunk); - if (cgc.dependentHashModules === undefined) - cgc.dependentHashModules = new Set(); - for (const module of modules) { - cgc.dependentHashModules.add(module); - } + needBuild({ fileSystemInfo }, callback) { + // build if enforced + if (this._forceBuild) return callback(null, true); + + // always build when we have no snapshot + if (!this.buildInfo.snapshot) return callback(null, true); + + fileSystemInfo.checkSnapshotValid(this.buildInfo.snapshot, (err, valid) => { + callback(err, !valid); + }); } /** - * @param {Module} oldModule the replaced module - * @param {Module} newModule the replacing module + * @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} */ - replaceModule(oldModule, newModule) { - const oldCgm = this._getChunkGraphModule(oldModule); - const newCgm = this._getChunkGraphModule(newModule); + build(options, compilation, resolver, fs, callback) { + this._forceBuild = false; + /** @type {BuildMeta} */ + this.buildMeta = { + exportsType: "default", + defaultObject: "redirect-warn" + }; + this.buildInfo = { + snapshot: undefined + }; + this.dependencies.length = 0; + this.blocks.length = 0; + const startTime = Date.now(); + this.resolveDependencies(fs, this.options, (err, dependencies) => { + if (err) { + return callback( + makeWebpackError(err, "ContextModule.resolveDependencies") + ); + } - for (const chunk of oldCgm.chunks) { - const cgc = this._getChunkGraphChunk(chunk); - cgc.modules.delete(oldModule); - cgc.modules.add(newModule); - newCgm.chunks.add(chunk); - } - oldCgm.chunks.clear(); + // abort if something failed + // this will create an empty context + if (!dependencies) { + callback(); + return; + } - if (oldCgm.entryInChunks !== undefined) { - if (newCgm.entryInChunks === undefined) { - newCgm.entryInChunks = new Set(); + // enhance dependencies with meta info + for (const dep of dependencies) { + dep.loc = { + name: dep.userRequest + }; + dep.request = this.options.addon + dep.request; } - for (const chunk of oldCgm.entryInChunks) { - const cgc = this._getChunkGraphChunk(chunk); - const old = cgc.entryModules.get(oldModule); - /** @type {Map} */ - const newEntryModules = new Map(); - for (const [m, cg] of cgc.entryModules) { - if (m === oldModule) { - newEntryModules.set(newModule, old); - } else { - newEntryModules.set(m, cg); + dependencies.sort( + concatComparators( + compareSelect(a => a.loc, compareLocations), + keepOriginalOrder(this.dependencies) + ) + ); + + if (this.options.mode === "sync" || this.options.mode === "eager") { + // if we have an sync or eager context + // just add all dependencies and continue + this.dependencies = dependencies; + } else if (this.options.mode === "lazy-once") { + // for the lazy-once mode create a new async dependency block + // and add that block to this context + if (dependencies.length > 0) { + const block = new AsyncDependenciesBlock({ + ...this.options.groupOptions, + name: this.options.chunkName + }); + for (const dep of dependencies) { + block.addDependency(dep); } + this.addBlock(block); } - cgc.entryModules = newEntryModules; - newCgm.entryInChunks.add(chunk); - } - oldCgm.entryInChunks = undefined; - } - - if (oldCgm.runtimeInChunks !== undefined) { - if (newCgm.runtimeInChunks === undefined) { - newCgm.runtimeInChunks = new Set(); - } - for (const chunk of oldCgm.runtimeInChunks) { - const cgc = this._getChunkGraphChunk(chunk); - cgc.runtimeModules.delete(/** @type {RuntimeModule} */ (oldModule)); - cgc.runtimeModules.add(/** @type {RuntimeModule} */ (newModule)); - newCgm.runtimeInChunks.add(chunk); - if ( - cgc.fullHashModules !== undefined && - cgc.fullHashModules.has(/** @type {RuntimeModule} */ (oldModule)) - ) { - cgc.fullHashModules.delete(/** @type {RuntimeModule} */ (oldModule)); - cgc.fullHashModules.add(/** @type {RuntimeModule} */ (newModule)); + } else if ( + this.options.mode === "weak" || + this.options.mode === "async-weak" + ) { + // we mark all dependencies as weak + for (const dep of dependencies) { + dep.weak = true; } - if ( - cgc.dependentHashModules !== undefined && - cgc.dependentHashModules.has(/** @type {RuntimeModule} */ (oldModule)) - ) { - cgc.dependentHashModules.delete( - /** @type {RuntimeModule} */ (oldModule) - ); - cgc.dependentHashModules.add( - /** @type {RuntimeModule} */ (newModule) + this.dependencies = dependencies; + } else if (this.options.mode === "lazy") { + // if we are lazy create a new async dependency block per dependency + // and add all blocks to this context + let index = 0; + for (const dep of dependencies) { + let chunkName = this.options.chunkName; + if (chunkName) { + if (!/\[(index|request)\]/.test(chunkName)) { + chunkName += "[index]"; + } + chunkName = chunkName.replace(/\[index\]/g, `${index++}`); + chunkName = chunkName.replace( + /\[request\]/g, + Template.toPath(dep.userRequest) + ); + } + const block = new AsyncDependenciesBlock( + { + ...this.options.groupOptions, + name: chunkName + }, + dep.loc, + dep.userRequest ); + block.addDependency(dep); + this.addBlock(block); } + } else { + callback( + new WebpackError(`Unsupported mode "${this.options.mode}" in context`) + ); + return; } - oldCgm.runtimeInChunks = undefined; - } + compilation.fileSystemInfo.createSnapshot( + startTime, + null, + [this.context], + null, + SNAPSHOT_OPTIONS, + (err, snapshot) => { + if (err) return callback(err); + this.buildInfo.snapshot = snapshot; + callback(); + } + ); + }); } /** - * @param {Module} module the checked module - * @param {Chunk} chunk the checked chunk - * @returns {boolean} true, if the chunk contains the module + * @param {LazySet} fileDependencies set where file dependencies are added to + * @param {LazySet} contextDependencies set where context dependencies are added to + * @param {LazySet} missingDependencies set where missing dependencies are added to + * @param {LazySet} buildDependencies set where build dependencies are added to */ - isModuleInChunk(module, chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules.has(module); + addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ) { + contextDependencies.add(this.context); } /** - * @param {Module} module the checked module - * @param {ChunkGroup} chunkGroup the checked chunk group - * @returns {boolean} true, if the chunk contains the module + * @param {ContextElementDependency[]} dependencies all dependencies + * @param {ChunkGraph} chunkGraph chunk graph + * @returns {TODO} TODO */ - isModuleInChunkGroup(module, chunkGroup) { - for (const chunk of chunkGroup.chunks) { - if (this.isModuleInChunk(module, chunk)) return true; + getUserRequestMap(dependencies, chunkGraph) { + const moduleGraph = chunkGraph.moduleGraph; + // if we filter first we get a new array + // therefore we don't need to create a clone of dependencies explicitly + // therefore the order of this is !important! + const sortedDependencies = dependencies + .filter(dependency => moduleGraph.getModule(dependency)) + .sort((a, b) => { + if (a.userRequest === b.userRequest) { + return 0; + } + return a.userRequest < b.userRequest ? -1 : 1; + }); + const map = Object.create(null); + for (const dep of sortedDependencies) { + const module = moduleGraph.getModule(dep); + map[dep.userRequest] = chunkGraph.getModuleId(module); } - return false; + return map; } /** - * @param {Module} module the checked module - * @returns {boolean} true, if the module is entry of any chunk + * @param {ContextElementDependency[]} dependencies all dependencies + * @param {ChunkGraph} chunkGraph chunk graph + * @returns {TODO} TODO */ - isEntryModule(module) { - const cgm = this._getChunkGraphModule(module); - return cgm.entryInChunks !== undefined; + getFakeMap(dependencies, chunkGraph) { + if (!this.options.namespaceObject) { + return 9; + } + const moduleGraph = chunkGraph.moduleGraph; + // bitfield + let hasType = 0; + const comparator = compareModulesById(chunkGraph); + // if we filter first we get a new array + // therefore we don't need to create a clone of dependencies explicitly + // therefore the order of this is !important! + const sortedModules = dependencies + .map(dependency => moduleGraph.getModule(dependency)) + .filter(Boolean) + .sort(comparator); + const fakeMap = Object.create(null); + for (const module of sortedModules) { + const exportsType = module.getExportsType( + moduleGraph, + this.options.namespaceObject === "strict" + ); + const id = chunkGraph.getModuleId(module); + switch (exportsType) { + case "namespace": + fakeMap[id] = 9; + hasType |= 1; + break; + case "dynamic": + fakeMap[id] = 7; + hasType |= 2; + break; + case "default-only": + fakeMap[id] = 1; + hasType |= 4; + break; + case "default-with-named": + fakeMap[id] = 3; + hasType |= 8; + break; + default: + throw new Error(`Unexpected exports type ${exportsType}`); + } + } + if (hasType === 1) { + return 9; + } + if (hasType === 2) { + return 7; + } + if (hasType === 4) { + return 1; + } + if (hasType === 8) { + return 3; + } + if (hasType === 0) { + return 9; + } + return fakeMap; } - /** - * @param {Module} module the module - * @returns {Iterable} iterable of chunks (do not modify) - */ - getModuleChunksIterable(module) { - const cgm = this._getChunkGraphModule(module); - return cgm.chunks; + getFakeMapInitStatement(fakeMap) { + return typeof fakeMap === "object" + ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` + : ""; } - /** - * @param {Module} module the module - * @param {function(Chunk, Chunk): -1|0|1} sortFn sort function - * @returns {Iterable} iterable of chunks (do not modify) - */ - getOrderedModuleChunksIterable(module, sortFn) { - const cgm = this._getChunkGraphModule(module); - cgm.chunks.sortWith(sortFn); - return cgm.chunks; + getReturn(type, asyncModule) { + if (type === 9) { + return "__webpack_require__(id)"; + } + return `${RuntimeGlobals.createFakeNamespaceObject}(id, ${type}${ + asyncModule ? " | 16" : "" + })`; } - /** - * @param {Module} module the module - * @returns {Chunk[]} array of chunks (cached, do not modify) - */ - getModuleChunks(module) { - const cgm = this._getChunkGraphModule(module); - return cgm.chunks.getFromCache(getArray); + getReturnModuleObjectSource( + fakeMap, + asyncModule, + fakeMapDataExpression = "fakeMap[id]" + ) { + if (typeof fakeMap === "number") { + return `return ${this.getReturn(fakeMap, asyncModule)};`; + } + return `return ${ + RuntimeGlobals.createFakeNamespaceObject + }(id, ${fakeMapDataExpression}${asyncModule ? " | 16" : ""})`; } /** - * @param {Module} module the module - * @returns {number} the number of chunk which contain the module + * @param {TODO} dependencies TODO + * @param {TODO} id TODO + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {string} source code */ - getNumberOfModuleChunks(module) { - const cgm = this._getChunkGraphModule(module); - return cgm.chunks.size; - } + getSyncSource(dependencies, id, chunkGraph) { + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); - /** - * @param {Module} module the module - * @returns {RuntimeSpecSet} runtimes - */ - getModuleRuntimes(module) { - const cgm = this._getChunkGraphModule(module); - return cgm.chunks.getFromUnorderedCache(getModuleRuntimes); - } + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} - /** - * @param {Chunk} chunk the chunk - * @returns {number} the number of modules which are contained in this chunk - */ - getNumberOfChunkModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules.size; +function webpackContext(req) { + var id = webpackContextResolve(req); + ${returnModuleObject} +} +function webpackContextResolve(req) { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; } - - /** - * @param {Chunk} chunk the chunk - * @returns {number} the number of full hash modules which are contained in this chunk - */ - getNumberOfChunkFullHashModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.fullHashModules === undefined ? 0 : cgc.fullHashModules.size; + return map[req]; +} +webpackContext.keys = function webpackContextKeys() { + return Object.keys(map); +}; +webpackContext.resolve = webpackContextResolve; +module.exports = webpackContext; +webpackContext.id = ${JSON.stringify(id)};`; } /** - * @param {Chunk} chunk the chunk - * @returns {Iterable} return the modules for this chunk + * @param {TODO} dependencies TODO + * @param {TODO} id TODO + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {string} source code */ - getChunkModulesIterable(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules; - } + getWeakSyncSource(dependencies, id, chunkGraph) { + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); - /** - * @param {Chunk} chunk the chunk - * @param {string} sourceType source type - * @returns {Iterable | undefined} return the modules for this chunk - */ - getChunkModulesIterableBySourceType(chunk, sourceType) { - const cgc = this._getChunkGraphChunk(chunk); - const modulesWithSourceType = cgc.modules - .getFromUnorderedCache(modulesBySourceType) - .get(sourceType); - return modulesWithSourceType; - } + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} - /** - * @param {Chunk} chunk the chunk - * @param {function(Module, Module): -1|0|1} comparator comparator function - * @returns {Iterable} return the modules for this chunk - */ - getOrderedChunkModulesIterable(chunk, comparator) { - const cgc = this._getChunkGraphChunk(chunk); - cgc.modules.sortWith(comparator); - return cgc.modules; +function webpackContext(req) { + var id = webpackContextResolve(req); + if(!${RuntimeGlobals.moduleFactories}[id]) { + var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); + e.code = 'MODULE_NOT_FOUND'; + throw e; } - - /** - * @param {Chunk} chunk the chunk - * @param {string} sourceType source type - * @param {function(Module, Module): -1|0|1} comparator comparator function - * @returns {Iterable | undefined} return the modules for this chunk - */ - getOrderedChunkModulesIterableBySourceType(chunk, sourceType, comparator) { - const cgc = this._getChunkGraphChunk(chunk); - const modulesWithSourceType = cgc.modules - .getFromUnorderedCache(modulesBySourceType) - .get(sourceType); - if (modulesWithSourceType === undefined) return undefined; - modulesWithSourceType.sortWith(comparator); - return modulesWithSourceType; + ${returnModuleObject} +} +function webpackContextResolve(req) { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; } - - /** - * @param {Chunk} chunk the chunk - * @returns {Module[]} return the modules for this chunk (cached, do not modify) - */ - getChunkModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules.getFromUnorderedCache(getArray); + return map[req]; +} +webpackContext.keys = function webpackContextKeys() { + return Object.keys(map); +}; +webpackContext.resolve = webpackContextResolve; +webpackContext.id = ${JSON.stringify(id)}; +module.exports = webpackContext;`; } /** - * @param {Chunk} chunk the chunk - * @param {function(Module, Module): -1|0|1} comparator comparator function - * @returns {Module[]} return the modules for this chunk (cached, do not modify) + * @param {TODO} dependencies TODO + * @param {TODO} id TODO + * @param {Object} context context + * @param {ChunkGraph} context.chunkGraph the chunk graph + * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph + * @returns {string} source code */ - getOrderedChunkModules(chunk, comparator) { - const cgc = this._getChunkGraphChunk(chunk); - const arrayFunction = createOrderedArrayFunction(comparator); - return cgc.modules.getFromUnorderedCache(arrayFunction); - } + getAsyncWeakSource(dependencies, id, { chunkGraph, runtimeTemplate }) { + const arrow = runtimeTemplate.supportsArrowFunction(); + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap, true); - /** - * @param {Chunk} chunk the chunk - * @param {ModuleFilterPredicate} filterFn function used to filter modules - * @param {boolean} includeAllChunks all chunks or only async chunks - * @returns {Record} chunk to module ids object - */ - getChunkModuleIdMap(chunk, filterFn, includeAllChunks = false) { - /** @type {Record} */ - const chunkModuleIdMap = Object.create(null); + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} - for (const asyncChunk of includeAllChunks - ? chunk.getAllReferencedChunks() - : chunk.getAllAsyncChunks()) { - /** @type {(string|number)[]} */ - let array; - for (const module of this.getOrderedChunkModulesIterable( - asyncChunk, - compareModulesById(this) - )) { - if (filterFn(module)) { - if (array === undefined) { - array = []; - chunkModuleIdMap[asyncChunk.id] = array; - } - const moduleId = this.getModuleId(module); - array.push(moduleId); - } - } - } - - return chunkModuleIdMap; - } - - /** - * @param {Chunk} chunk the chunk - * @param {ModuleFilterPredicate} filterFn function used to filter modules - * @param {number} hashLength length of the hash - * @param {boolean} includeAllChunks all chunks or only async chunks - * @returns {Record>} chunk to module id to module hash object - */ - getChunkModuleRenderedHashMap( - chunk, - filterFn, - hashLength = 0, - includeAllChunks = false - ) { - /** @type {Record>} */ - const chunkModuleHashMap = Object.create(null); - - for (const asyncChunk of includeAllChunks - ? chunk.getAllReferencedChunks() - : chunk.getAllAsyncChunks()) { - /** @type {Record} */ - let idToHashMap; - for (const module of this.getOrderedChunkModulesIterable( - asyncChunk, - compareModulesById(this) - )) { - if (filterFn(module)) { - if (idToHashMap === undefined) { - idToHashMap = Object.create(null); - chunkModuleHashMap[asyncChunk.id] = idToHashMap; - } - const moduleId = this.getModuleId(module); - const hash = this.getRenderedModuleHash(module, asyncChunk.runtime); - idToHashMap[moduleId] = hashLength ? hash.slice(0, hashLength) : hash; - } - } +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${ + arrow ? "id =>" : "function(id)" + } { + if(!${RuntimeGlobals.moduleFactories}[id]) { + var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); + e.code = 'MODULE_NOT_FOUND'; + throw e; } - - return chunkModuleHashMap; - } - - /** - * @param {Chunk} chunk the chunk - * @param {ChunkFilterPredicate} filterFn function used to filter chunks - * @returns {Record} chunk map - */ - getChunkConditionMap(chunk, filterFn) { - const map = Object.create(null); - for (const c of chunk.getAllReferencedChunks()) { - map[c.id] = filterFn(c, this); + ${returnModuleObject} + }); +} +function webpackAsyncContextResolve(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; } - return map; + return map[req]; + }); +} +webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( + "Object.keys(map)" + )}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; } /** - * @param {Chunk} chunk the chunk - * @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 + * @param {TODO} dependencies TODO + * @param {TODO} id TODO + * @param {Object} context context + * @param {ChunkGraph} context.chunkGraph the chunk graph + * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph + * @returns {string} source code */ - hasModuleInGraph(chunk, filterFn, filterChunkFn) { - const queue = new Set(chunk.groupsIterable); - const chunksProcessed = new Set(); + getEagerSource(dependencies, id, { chunkGraph, runtimeTemplate }) { + const arrow = runtimeTemplate.supportsArrowFunction(); + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const thenFunction = + fakeMap !== 9 + ? `${arrow ? "id =>" : "function(id)"} { + ${this.getReturnModuleObjectSource(fakeMap)} + }` + : "__webpack_require__"; + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} - for (const chunkGroup of queue) { - for (const innerChunk of chunkGroup.chunks) { - if (!chunksProcessed.has(innerChunk)) { - chunksProcessed.add(innerChunk); - if (!filterChunkFn || filterChunkFn(innerChunk, this)) { - for (const module of this.getChunkModulesIterable(innerChunk)) { - if (filterFn(module)) { - return true; - } - } - } - } - } - for (const child of chunkGroup.childrenIterable) { - queue.add(child); - } +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${thenFunction}); +} +function webpackAsyncContextResolve(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; } - return false; - } - - /** - * @param {Chunk} chunkA first chunk - * @param {Chunk} chunkB second chunk - * @returns {-1|0|1} this is a comparator function like sort and returns -1, 0, or 1 based on sort order - */ - compareChunks(chunkA, chunkB) { - const cgcA = this._getChunkGraphChunk(chunkA); - const cgcB = this._getChunkGraphChunk(chunkB); - if (cgcA.modules.size > cgcB.modules.size) return -1; - if (cgcA.modules.size < cgcB.modules.size) return 1; - cgcA.modules.sortWith(compareModulesByIdentifier); - cgcB.modules.sortWith(compareModulesByIdentifier); - return compareModuleIterables(cgcA.modules, cgcB.modules); - } - - /** - * @param {Chunk} chunk the chunk - * @returns {number} total size of all modules in the chunk - */ - getChunkModulesSize(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules.getFromUnorderedCache(getModulesSize); + return map[req]; + }); +} +webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( + "Object.keys(map)" + )}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; } /** - * @param {Chunk} chunk the chunk - * @returns {Record} total sizes of all modules in the chunk by source type + * @param {TODO} block TODO + * @param {TODO} dependencies TODO + * @param {TODO} id TODO + * @param {Object} options options object + * @param {RuntimeTemplate} options.runtimeTemplate the runtime template + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @returns {string} source code */ - getChunkModulesSizes(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules.getFromUnorderedCache(getModulesSizes); - } + getLazyOnceSource(block, dependencies, id, { runtimeTemplate, chunkGraph }) { + const promise = runtimeTemplate.blockPromise({ + chunkGraph, + block, + message: "lazy-once context", + runtimeRequirements: new Set() + }); + const arrow = runtimeTemplate.supportsArrowFunction(); + const map = this.getUserRequestMap(dependencies, chunkGraph); + const fakeMap = this.getFakeMap(dependencies, chunkGraph); + const thenFunction = + fakeMap !== 9 + ? `${arrow ? "id =>" : "function(id)"} { + ${this.getReturnModuleObjectSource(fakeMap, true)}; + }` + : "__webpack_require__"; - /** - * @param {Chunk} chunk the chunk - * @returns {Module[]} root modules of the chunks (ordered by identifier) - */ - getChunkRootModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.modules.getFromUnorderedCache(this._getGraphRoots); - } + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} - /** - * @param {Chunk} chunk the chunk - * @param {ChunkSizeOptions} options options object - * @returns {number} total size of the chunk - */ - getChunkSize(chunk, options = {}) { - const cgc = this._getChunkGraphChunk(chunk); - const modulesSize = cgc.modules.getFromUnorderedCache(getModulesSize); - const chunkOverhead = - typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; - const entryChunkMultiplicator = - typeof options.entryChunkMultiplicator === "number" - ? options.entryChunkMultiplicator - : 10; - return ( - chunkOverhead + - modulesSize * (chunk.canBeInitial() ? entryChunkMultiplicator : 1) - ); +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${thenFunction}); +} +function webpackAsyncContextResolve(req) { + return ${promise}.then(${arrow ? "() =>" : "function()"} { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; + }); +} +webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( + "Object.keys(map)" + )}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; } /** - * @param {Chunk} chunkA chunk - * @param {Chunk} chunkB chunk - * @param {ChunkSizeOptions} options options object - * @returns {number} total size of the chunk or false if chunks can't be integrated + * @param {TODO} blocks TODO + * @param {TODO} id TODO + * @param {Object} context context + * @param {ChunkGraph} context.chunkGraph the chunk graph + * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph + * @returns {string} source code */ - getIntegratedChunksSize(chunkA, chunkB, options = {}) { - const cgcA = this._getChunkGraphChunk(chunkA); - const cgcB = this._getChunkGraphChunk(chunkB); - const allModules = new Set(cgcA.modules); - for (const m of cgcB.modules) allModules.add(m); - let modulesSize = getModulesSize(allModules); - const chunkOverhead = - typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; - const entryChunkMultiplicator = - typeof options.entryChunkMultiplicator === "number" - ? options.entryChunkMultiplicator - : 10; - return ( - chunkOverhead + - modulesSize * - (chunkA.canBeInitial() || chunkB.canBeInitial() - ? entryChunkMultiplicator - : 1) + getLazySource(blocks, id, { chunkGraph, runtimeTemplate }) { + const moduleGraph = chunkGraph.moduleGraph; + const arrow = runtimeTemplate.supportsArrowFunction(); + let hasMultipleOrNoChunks = false; + let hasNoChunk = true; + const fakeMap = this.getFakeMap( + blocks.map(b => b.dependencies[0]), + chunkGraph ); - } - - /** - * @param {Chunk} chunkA chunk - * @param {Chunk} chunkB chunk - * @returns {boolean} true, if chunks could be integrated - */ - canChunksBeIntegrated(chunkA, chunkB) { - if (chunkA.preventIntegration || chunkB.preventIntegration) { - return false; - } - - const hasRuntimeA = chunkA.hasRuntime(); - const hasRuntimeB = chunkB.hasRuntime(); - - if (hasRuntimeA !== hasRuntimeB) { - if (hasRuntimeA) { - return isAvailableChunk(chunkA, chunkB); - } else if (hasRuntimeB) { - return isAvailableChunk(chunkB, chunkA); - } else { - return false; + const hasFakeMap = typeof fakeMap === "object"; + const items = blocks + .map(block => { + const dependency = block.dependencies[0]; + return { + dependency: dependency, + module: moduleGraph.getModule(dependency), + block: block, + userRequest: dependency.userRequest, + chunks: undefined + }; + }) + .filter(item => item.module); + for (const item of items) { + const chunkGroup = chunkGraph.getBlockChunkGroup(item.block); + const chunks = (chunkGroup && chunkGroup.chunks) || []; + item.chunks = chunks; + if (chunks.length > 0) { + hasNoChunk = false; + } + if (chunks.length !== 1) { + hasMultipleOrNoChunks = true; } } - - if ( - this.getNumberOfEntryModules(chunkA) > 0 || - this.getNumberOfEntryModules(chunkB) > 0 - ) { - return false; - } - - return true; - } - - /** - * @param {Chunk} chunkA the target chunk - * @param {Chunk} chunkB the chunk to integrate - * @returns {void} - */ - integrateChunks(chunkA, chunkB) { - // Decide for one name (deterministic) - if (chunkA.name && chunkB.name) { - if ( - this.getNumberOfEntryModules(chunkA) > 0 === - this.getNumberOfEntryModules(chunkB) > 0 - ) { - // When both chunks have entry modules or none have one, use - // shortest name - if (chunkA.name.length !== chunkB.name.length) { - chunkA.name = - chunkA.name.length < chunkB.name.length ? chunkA.name : chunkB.name; - } else { - chunkA.name = chunkA.name < chunkB.name ? chunkA.name : chunkB.name; + const shortMode = hasNoChunk && !hasFakeMap; + const sortedItems = items.sort((a, b) => { + if (a.userRequest === b.userRequest) return 0; + return a.userRequest < b.userRequest ? -1 : 1; + }); + const map = Object.create(null); + for (const item of sortedItems) { + const moduleId = chunkGraph.getModuleId(item.module); + if (shortMode) { + map[item.userRequest] = moduleId; + } else { + const arrayStart = [moduleId]; + if (hasFakeMap) { + arrayStart.push(fakeMap[moduleId]); } - } else if (this.getNumberOfEntryModules(chunkB) > 0) { - // Pick the name of the chunk with the entry module - chunkA.name = chunkB.name; + map[item.userRequest] = arrayStart.concat( + item.chunks.map(chunk => chunk.id) + ); } - } else if (chunkB.name) { - chunkA.name = chunkB.name; - } - - // Merge id name hints - for (const hint of chunkB.idNameHints) { - chunkA.idNameHints.add(hint); - } - - // Merge runtime - chunkA.runtime = mergeRuntime(chunkA.runtime, chunkB.runtime); - - // getChunkModules is used here to create a clone, because disconnectChunkAndModule modifies - for (const module of this.getChunkModules(chunkB)) { - this.disconnectChunkAndModule(chunkB, module); - this.connectChunkAndModule(chunkA, module); - } - - for (const [module, chunkGroup] of Array.from( - this.getChunkEntryModulesWithChunkGroupIterable(chunkB) - )) { - this.disconnectChunkAndEntryModule(chunkB, module); - this.connectChunkAndEntryModule(chunkA, module, chunkGroup); } - for (const chunkGroup of chunkB.groupsIterable) { - chunkGroup.replaceChunk(chunkB, chunkA); - chunkA.addGroup(chunkGroup); - chunkB.removeGroup(chunkGroup); - } - ChunkGraph.clearChunkGraphForChunk(chunkB); - } + const chunksStartPosition = hasFakeMap ? 2 : 1; + const requestPrefix = hasNoChunk + ? "Promise.resolve()" + : hasMultipleOrNoChunks + ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))` + : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`; + const returnModuleObject = this.getReturnModuleObjectSource( + fakeMap, + true, + shortMode ? "invalid" : "ids[1]" + ); - /** - * @param {Chunk} chunk the chunk to upgrade - * @returns {void} - */ - upgradeDependentToFullHashModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - if (cgc.dependentHashModules === undefined) return; - if (cgc.fullHashModules === undefined) { - cgc.fullHashModules = cgc.dependentHashModules; - } else { - for (const m of cgc.dependentHashModules) { - cgc.fullHashModules.add(m); - } - cgc.dependentHashModules = undefined; + const webpackAsyncContext = + requestPrefix === "Promise.resolve()" + ? ` +function webpackAsyncContext(req) { + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; } - } - /** - * @param {Module} module the checked module - * @param {Chunk} chunk the checked chunk - * @returns {boolean} true, if the chunk contains the module as entry - */ - isEntryModuleInChunk(module, chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.entryModules.has(module); + ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"} + ${returnModuleObject} + }); +}` + : `function webpackAsyncContext(req) { + if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); } - /** - * @param {Chunk} chunk the new chunk - * @param {Module} module the entry module - * @param {Entrypoint=} entrypoint the chunk group which must be loaded before the module is executed - * @returns {void} - */ - connectChunkAndEntryModule(chunk, module, entrypoint) { - const cgm = this._getChunkGraphModule(module); - const cgc = this._getChunkGraphChunk(chunk); - if (cgm.entryInChunks === undefined) { - cgm.entryInChunks = new Set(); - } - cgm.entryInChunks.add(chunk); - cgc.entryModules.set(module, entrypoint); - } + var ids = map[req], id = ids[0]; + return ${requestPrefix}.then(${arrow ? "() =>" : "function()"} { + ${returnModuleObject} + }); +}`; - /** - * @param {Chunk} chunk the new chunk - * @param {RuntimeModule} module the runtime module - * @returns {void} - */ - connectChunkAndRuntimeModule(chunk, module) { - const cgm = this._getChunkGraphModule(module); - const cgc = this._getChunkGraphChunk(chunk); - if (cgm.runtimeInChunks === undefined) { - cgm.runtimeInChunks = new Set(); - } - cgm.runtimeInChunks.add(chunk); - cgc.runtimeModules.add(module); + return `var map = ${JSON.stringify(map, null, "\t")}; +${webpackAsyncContext} +webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( + "Object.keys(map)" + )}; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; } - /** - * @param {Chunk} chunk the new chunk - * @param {RuntimeModule} module the module that require a full hash - * @returns {void} - */ - addFullHashModuleToChunk(chunk, module) { - const cgc = this._getChunkGraphChunk(chunk); - if (cgc.fullHashModules === undefined) cgc.fullHashModules = new Set(); - cgc.fullHashModules.add(module); + getSourceForEmptyContext(id, runtimeTemplate) { + return `function webpackEmptyContext(req) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; +} +webpackEmptyContext.keys = ${runtimeTemplate.returningFunction("[]")}; +webpackEmptyContext.resolve = webpackEmptyContext; +webpackEmptyContext.id = ${JSON.stringify(id)}; +module.exports = webpackEmptyContext;`; } - /** - * @param {Chunk} chunk the new chunk - * @param {RuntimeModule} module the module that require a full hash - * @returns {void} - */ - addDependentHashModuleToChunk(chunk, module) { - const cgc = this._getChunkGraphChunk(chunk); - if (cgc.dependentHashModules === undefined) - cgc.dependentHashModules = new Set(); - cgc.dependentHashModules.add(module); + getSourceForEmptyAsyncContext(id, runtimeTemplate) { + const arrow = runtimeTemplate.supportsArrowFunction(); + return `function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(${arrow ? "() =>" : "function()"} { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); +} +webpackEmptyAsyncContext.keys = ${runtimeTemplate.returningFunction("[]")}; +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackEmptyAsyncContext;`; } /** - * @param {Chunk} chunk the new chunk - * @param {Module} module the entry module - * @returns {void} + * @param {string} asyncMode module mode + * @param {CodeGenerationContext} context context info + * @returns {string} the source code */ - disconnectChunkAndEntryModule(chunk, module) { - const cgm = this._getChunkGraphModule(module); - const cgc = this._getChunkGraphChunk(chunk); - cgm.entryInChunks.delete(chunk); - if (cgm.entryInChunks.size === 0) { - cgm.entryInChunks = undefined; + getSourceString(asyncMode, { runtimeTemplate, chunkGraph }) { + const id = chunkGraph.getModuleId(this); + if (asyncMode === "lazy") { + if (this.blocks && this.blocks.length > 0) { + return this.getLazySource(this.blocks, id, { + runtimeTemplate, + chunkGraph + }); + } + return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); } - cgc.entryModules.delete(module); - } - - /** - * @param {Chunk} chunk the new chunk - * @param {RuntimeModule} module the runtime module - * @returns {void} - */ - disconnectChunkAndRuntimeModule(chunk, module) { - const cgm = this._getChunkGraphModule(module); - const cgc = this._getChunkGraphChunk(chunk); - cgm.runtimeInChunks.delete(chunk); - if (cgm.runtimeInChunks.size === 0) { - cgm.runtimeInChunks = undefined; + if (asyncMode === "eager") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getEagerSource(this.dependencies, id, { + chunkGraph, + runtimeTemplate + }); + } + return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); } - cgc.runtimeModules.delete(module); - } - - /** - * @param {Module} module the entry module, it will no longer be entry - * @returns {void} - */ - disconnectEntryModule(module) { - const cgm = this._getChunkGraphModule(module); - for (const chunk of cgm.entryInChunks) { - const cgc = this._getChunkGraphChunk(chunk); - cgc.entryModules.delete(module); + if (asyncMode === "lazy-once") { + const block = this.blocks[0]; + if (block) { + return this.getLazyOnceSource(block, block.dependencies, id, { + runtimeTemplate, + chunkGraph + }); + } + return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); } - cgm.entryInChunks = undefined; - } - - /** - * @param {Chunk} chunk the chunk, for which all entries will be removed - * @returns {void} - */ - disconnectEntries(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - for (const module of cgc.entryModules.keys()) { - const cgm = this._getChunkGraphModule(module); - cgm.entryInChunks.delete(chunk); - if (cgm.entryInChunks.size === 0) { - cgm.entryInChunks = undefined; + if (asyncMode === "async-weak") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getAsyncWeakSource(this.dependencies, id, { + chunkGraph, + runtimeTemplate + }); } + return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); } - cgc.entryModules.clear(); - } - - /** - * @param {Chunk} chunk the chunk - * @returns {number} the amount of entry modules in chunk - */ - getNumberOfEntryModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.entryModules.size; - } - - /** - * @param {Chunk} chunk the chunk - * @returns {number} the amount of entry modules in chunk - */ - getNumberOfRuntimeModules(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.runtimeModules.size; + if (asyncMode === "weak") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getWeakSyncSource(this.dependencies, id, chunkGraph); + } + } + if (this.dependencies && this.dependencies.length > 0) { + return this.getSyncSource(this.dependencies, id, chunkGraph); + } + return this.getSourceForEmptyContext(id, runtimeTemplate); } - /** - * @param {Chunk} chunk the chunk - * @returns {Iterable} iterable of modules (do not modify) - */ - getChunkEntryModulesIterable(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.entryModules.keys(); + getSource(sourceString) { + if (this.useSourceMap || this.useSimpleSourceMap) { + return new OriginalSource(sourceString, this.identifier()); + } + return new RawSource(sourceString); } /** - * @param {Chunk} chunk the chunk - * @returns {Iterable} iterable of chunks + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - getChunkEntryDependentChunksIterable(chunk) { - /** @type {Set} */ + codeGeneration(context) { + const { chunkGraph } = context; + const sources = new Map(); + sources.set( + "javascript", + this.getSource(this.getSourceString(this.options.mode, context)) + ); const set = new Set(); - for (const chunkGroup of chunk.groupsIterable) { - if (chunkGroup instanceof Entrypoint) { - const entrypointChunk = chunkGroup.getEntrypointChunk(); - const cgc = this._getChunkGraphChunk(entrypointChunk); - for (const chunkGroup of cgc.entryModules.values()) { - for (const c of chunkGroup.chunks) { - if (c !== chunk && c !== entrypointChunk && !c.hasRuntime()) { - set.add(c); - } - } - } + const allDeps = /** @type {ContextElementDependency[]} */ ( + this.dependencies.concat(this.blocks.map(b => b.dependencies[0])) + ); + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.hasOwnProperty); + if (allDeps.length > 0) { + const asyncMode = this.options.mode; + set.add(RuntimeGlobals.require); + if (asyncMode === "weak") { + set.add(RuntimeGlobals.moduleFactories); + } else if (asyncMode === "async-weak") { + set.add(RuntimeGlobals.moduleFactories); + set.add(RuntimeGlobals.ensureChunk); + } else if (asyncMode === "lazy" || asyncMode === "lazy-once") { + set.add(RuntimeGlobals.ensureChunk); } - } - - return set; - } - - /** - * @param {Chunk} chunk the chunk - * @returns {boolean} true, when it has dependent chunks - */ - hasChunkEntryDependentChunks(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - for (const chunkGroup of cgc.entryModules.values()) { - for (const c of chunkGroup.chunks) { - if (c !== chunk) { - return true; - } + if (this.getFakeMap(allDeps, chunkGraph) !== 9) { + set.add(RuntimeGlobals.createFakeNamespaceObject); } } - return false; - } - - /** - * @param {Chunk} chunk the chunk - * @returns {Iterable} iterable of modules (do not modify) - */ - getChunkRuntimeModulesIterable(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.runtimeModules; + return { + sources, + runtimeRequirements: set + }; } /** - * @param {Chunk} chunk the chunk - * @returns {RuntimeModule[]} array of modules in order of execution + * @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) */ - getChunkRuntimeModulesInOrder(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - const array = Array.from(cgc.runtimeModules); - array.sort( - concatComparators( - compareSelect( - /** - * @param {RuntimeModule} r runtime module - * @returns {number=} stage - */ - r => r.stage, - compareIds - ), - compareModulesByIdentifier - ) - ); - return array; - } + size(type) { + // base penalty + let size = 160; - /** - * @param {Chunk} chunk the chunk - * @returns {Iterable | undefined} iterable of modules (do not modify) - */ - getChunkFullHashModulesIterable(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.fullHashModules; + // if we don't have dependencies we stop here. + for (const dependency of this.dependencies) { + const element = /** @type {ContextElementDependency} */ (dependency); + size += 5 + element.userRequest.length; + } + return size; } - /** - * @param {Chunk} chunk the chunk - * @returns {ReadonlySet | undefined} set of modules (do not modify) - */ - getChunkFullHashModulesSet(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.fullHashModules; + serialize(context) { + const { write } = context; + write(this._identifier); + write(this._forceBuild); + super.serialize(context); } - /** - * @param {Chunk} chunk the chunk - * @returns {Iterable | undefined} iterable of modules (do not modify) - */ - getChunkDependentHashModulesIterable(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.dependentHashModules; + deserialize(context) { + const { read } = context; + this._identifier = read(); + this._forceBuild = read(); + super.deserialize(context); } +} - /** @typedef {[Module, Entrypoint | undefined]} EntryModuleWithChunkGroup */ - - /** - * @param {Chunk} chunk the chunk - * @returns {Iterable} iterable of modules (do not modify) - */ - getChunkEntryModulesWithChunkGroupIterable(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.entryModules; - } +makeSerializable(ContextModule, "webpack/lib/ContextModule"); - /** - * @param {AsyncDependenciesBlock} depBlock the async block - * @returns {ChunkGroup} the chunk group - */ - getBlockChunkGroup(depBlock) { - return this._blockChunkGroups.get(depBlock); - } +module.exports = ContextModule; - /** - * @param {AsyncDependenciesBlock} depBlock the async block - * @param {ChunkGroup} chunkGroup the chunk group - * @returns {void} - */ - connectBlockAndChunkGroup(depBlock, chunkGroup) { - this._blockChunkGroups.set(depBlock, chunkGroup); - chunkGroup.addBlock(depBlock); - } - /** - * @param {ChunkGroup} chunkGroup the chunk group - * @returns {void} - */ - disconnectChunkGroup(chunkGroup) { - for (const block of chunkGroup.blocksIterable) { - this._blockChunkGroups.delete(block); - } - // TODO refactor by moving blocks list into ChunkGraph - chunkGroup._blocks.clear(); - } +/***/ }), - /** - * @param {Module} module the module - * @returns {string | number} the id of the module - */ - getModuleId(module) { - const cgm = this._getChunkGraphModule(module); - return cgm.id; - } +/***/ 62471: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @param {Module} module the module - * @param {string | number} id the id of the module - * @returns {void} - */ - setModuleId(module, id) { - const cgm = this._getChunkGraphModule(module); - cgm.id = id; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @param {string} runtime runtime - * @returns {string | number} the id of the runtime - */ - getRuntimeId(runtime) { - return this._runtimeIds.get(runtime); - } - /** - * @param {string} runtime runtime - * @param {string | number} id the id of the runtime - * @returns {void} - */ - setRuntimeId(runtime, id) { - this._runtimeIds.set(runtime, id); - } - /** - * @template T - * @param {Module} module the module - * @param {RuntimeSpecMap} hashes hashes data - * @param {RuntimeSpec} runtime the runtime - * @returns {T} hash - */ - _getModuleHashInfo(module, hashes, runtime) { - if (!hashes) { - throw new Error( - `Module ${module.identifier()} has no hash info for runtime ${runtimeToString( - runtime - )} (hashes not set at all)` - ); - } else if (runtime === undefined) { - const hashInfoItems = new Set(hashes.values()); - if (hashInfoItems.size !== 1) { - throw new Error( - `No unique hash info entry for unspecified runtime for ${module.identifier()} (existing runtimes: ${Array.from( - hashes.keys(), - r => runtimeToString(r) - ).join(", ")}). -Caller might not support runtime-dependent code generation (opt-out via optimization.usedExports: "global").` - ); - } - return first(hashInfoItems); - } else { - const hashInfo = hashes.get(runtime); - if (!hashInfo) { - throw new Error( - `Module ${module.identifier()} has no hash info for runtime ${runtimeToString( - runtime - )} (available runtimes ${Array.from( - hashes.keys(), - runtimeToString - ).join(", ")})` - ); - } - return hashInfo; - } - } +const asyncLib = __webpack_require__(78175); +const { AsyncSeriesWaterfallHook, SyncWaterfallHook } = __webpack_require__(6967); +const ContextModule = __webpack_require__(76729); +const ModuleFactory = __webpack_require__(51010); +const ContextElementDependency = __webpack_require__(58477); +const LazySet = __webpack_require__(38938); +const { cachedSetProperty } = __webpack_require__(60839); +const { createFakeHook } = __webpack_require__(64518); +const { join } = __webpack_require__(17139); - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, if the module has hashes for this runtime - */ - hasModuleHashes(module, runtime) { - const cgm = this._getChunkGraphModule(module); - const hashes = cgm.hashes; - return hashes && hashes.has(runtime); - } +/** @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} FakeHook */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {string} hash - */ - getModuleHash(module, runtime) { - const cgm = this._getChunkGraphModule(module); - const hashes = cgm.hashes; - return this._getModuleHashInfo(module, hashes, runtime).hash; - } +const EMPTY_RESOLVE_OPTIONS = {}; +module.exports = class ContextModuleFactory extends ModuleFactory { /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {string} hash + * @param {ResolverFactory} resolverFactory resolverFactory */ - getRenderedModuleHash(module, runtime) { - const cgm = this._getChunkGraphModule(module); - const hashes = cgm.hashes; - return this._getModuleHashInfo(module, hashes, runtime).renderedHash; + 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, "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 {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @param {string} hash the full hash - * @param {string} renderedHash the shortened hash for rendering + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback * @returns {void} */ - setModuleHashes(module, runtime, hash, renderedHash) { - const cgm = this._getChunkGraphModule(module); - if (cgm.hashes === undefined) { - cgm.hashes = new RuntimeSpecMap(); - } - cgm.hashes.set(runtime, new ModuleHashInfo(hash, renderedHash)); - } - - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @param {Set} items runtime requirements to be added (ownership of this Set is given to ChunkGraph when transferOwnership not false) - * @param {boolean} transferOwnership true: transfer ownership of the items object, false: items is immutable and shared and won't be modified - * @returns {void} - */ - addModuleRuntimeRequirements( - module, - runtime, - items, - transferOwnership = true - ) { - const cgm = this._getChunkGraphModule(module); - const runtimeRequirementsMap = cgm.runtimeRequirements; - if (runtimeRequirementsMap === undefined) { - const map = new RuntimeSpecMap(); - // TODO avoid cloning item and track ownership instead - map.set(runtime, transferOwnership ? items : new Set(items)); - cgm.runtimeRequirements = map; - return; - } - runtimeRequirementsMap.update(runtime, runtimeRequirements => { - if (runtimeRequirements === undefined) { - return transferOwnership ? items : new Set(items); - } else if (!transferOwnership || runtimeRequirements.size >= items.size) { - for (const item of items) runtimeRequirements.add(item); - return runtimeRequirements; - } else { - for (const item of runtimeRequirements) items.add(item); - return items; - } - }); - } + create(data, callback) { + const context = data.context; + const dependencies = data.dependencies; + const resolveOptions = data.resolveOptions; + const dependency = /** @type {ContextDependency} */ (dependencies[0]); + const fileDependencies = new LazySet(); + const missingDependencies = new LazySet(); + const contextDependencies = new LazySet(); + this.hooks.beforeResolve.callAsync( + { + context: context, + dependencies: dependencies, + resolveOptions, + fileDependencies, + missingDependencies, + contextDependencies, + ...dependency.options + }, + (err, beforeResolveResult) => { + if (err) { + return callback(err, { + fileDependencies, + missingDependencies, + contextDependencies + }); + } - /** - * @param {Chunk} chunk the chunk - * @param {Set} items runtime requirements to be added (ownership of this Set is given to ChunkGraph) - * @returns {void} - */ - addChunkRuntimeRequirements(chunk, items) { - const cgc = this._getChunkGraphChunk(chunk); - const runtimeRequirements = cgc.runtimeRequirements; - if (runtimeRequirements === undefined) { - cgc.runtimeRequirements = items; - } else if (runtimeRequirements.size >= items.size) { - for (const item of items) runtimeRequirements.add(item); - } else { - for (const item of runtimeRequirements) items.add(item); - cgc.runtimeRequirements = items; - } - } + // Ignored + if (!beforeResolveResult) { + return callback(null, { + fileDependencies, + missingDependencies, + contextDependencies + }); + } - /** - * @param {Chunk} chunk the chunk - * @param {Iterable} items runtime requirements to be added - * @returns {void} - */ - addTreeRuntimeRequirements(chunk, items) { - const cgc = this._getChunkGraphChunk(chunk); - const runtimeRequirements = cgc.runtimeRequirementsInTree; - for (const item of items) runtimeRequirements.add(item); - } + const context = beforeResolveResult.context; + const request = beforeResolveResult.request; + const resolveOptions = beforeResolveResult.resolveOptions; - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {ReadonlySet} runtime requirements - */ - getModuleRuntimeRequirements(module, runtime) { - const cgm = this._getChunkGraphModule(module); - const runtimeRequirements = - cgm.runtimeRequirements && cgm.runtimeRequirements.get(runtime); - return runtimeRequirements === undefined ? EMPTY_SET : runtimeRequirements; - } + 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; + } - /** - * @param {Chunk} chunk the chunk - * @returns {ReadonlySet} runtime requirements - */ - getChunkRuntimeRequirements(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - const runtimeRequirements = cgc.runtimeRequirements; - return runtimeRequirements === undefined ? EMPTY_SET : runtimeRequirements; - } + 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"); - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @param {boolean} withConnections include connections - * @returns {string} hash - */ - getModuleGraphHash(module, runtime, withConnections = true) { - const cgm = this._getChunkGraphModule(module); - return withConnections - ? this._getModuleGraphHashWithConnections(cgm, module, runtime) - : this._getModuleGraphHashBigInt(cgm, module, runtime).toString(16); - } + 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 + }); + } - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @param {boolean} withConnections include connections - * @returns {bigint} hash - */ - getModuleGraphHashBigInt(module, runtime, withConnections = true) { - const cgm = this._getChunkGraphModule(module); - return withConnections - ? BigInt( - `0x${this._getModuleGraphHashWithConnections(cgm, module, runtime)}` - ) - : this._getModuleGraphHashBigInt(cgm, module, runtime); - } + 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 + }); + } - /** - * @param {ChunkGraphModule} cgm the ChunkGraphModule - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {bigint} hash as big int - */ - _getModuleGraphHashBigInt(cgm, module, runtime) { - if (cgm.graphHashes === undefined) { - cgm.graphHashes = new RuntimeSpecMap(); - } - const graphHash = cgm.graphHashes.provide(runtime, () => { - const hash = createHash(this._hashFunction); - hash.update(`${cgm.id}${this.moduleGraph.isAsync(module)}`); - this.moduleGraph.getExportsInfo(module).updateHash(hash, runtime); - return BigInt(`0x${/** @type {string} */ (hash.digest("hex"))}`); - }); - return graphHash; - } + // Ignored + if (!result) { + return callback(null, { + fileDependencies, + missingDependencies, + contextDependencies + }); + } - /** - * @param {ChunkGraphModule} cgm the ChunkGraphModule - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {string} hash - */ - _getModuleGraphHashWithConnections(cgm, module, runtime) { - if (cgm.graphHashesWithConnections === undefined) { - cgm.graphHashesWithConnections = new RuntimeSpecMap(); - } - const activeStateToString = state => { - if (state === false) return "F"; - if (state === true) return "T"; - if (state === ModuleGraphConnection.TRANSITIVE_ONLY) return "O"; - throw new Error("Not implemented active state"); - }; - const strict = module.buildMeta && module.buildMeta.strictHarmonyModule; - return cgm.graphHashesWithConnections.provide(runtime, () => { - const graphHash = this._getModuleGraphHashBigInt( - cgm, - module, - runtime - ).toString(16); - const connections = this.moduleGraph.getOutgoingConnections(module); - /** @type {Set} */ - const activeNamespaceModules = new Set(); - /** @type {Map>} */ - const connectedModules = new Map(); - const processConnection = (connection, stateInfo) => { - const module = connection.module; - stateInfo += module.getExportsType(this.moduleGraph, strict); - // cspell:word Tnamespace - if (stateInfo === "Tnamespace") activeNamespaceModules.add(module); - else { - const oldModule = connectedModules.get(stateInfo); - if (oldModule === undefined) { - connectedModules.set(stateInfo, module); - } else if (oldModule instanceof Set) { - oldModule.add(module); - } else if (oldModule !== module) { - connectedModules.set(stateInfo, new Set([oldModule, module])); - } - } - }; - if (runtime === undefined || typeof runtime === "string") { - for (const connection of connections) { - const state = connection.getActiveState(runtime); - if (state === false) continue; - processConnection(connection, state === true ? "T" : "O"); - } - } else { - // cspell:word Tnamespace - for (const connection of connections) { - const states = new Set(); - let stateInfo = ""; - forEachRuntime( - runtime, - runtime => { - const state = connection.getActiveState(runtime); - states.add(state); - stateInfo += activeStateToString(state) + runtime; - }, - true - ); - if (states.size === 1) { - const state = first(states); - if (state === false) continue; - stateInfo = activeStateToString(state); + return callback(null, { + module: new ContextModule(result.resolveDependencies, result), + fileDependencies, + missingDependencies, + contextDependencies + }); + } + ); } - processConnection(connection, stateInfo); - } - } - // cspell:word Tnamespace - if (activeNamespaceModules.size === 0 && connectedModules.size === 0) - return graphHash; - const connectedModulesInOrder = - connectedModules.size > 1 - ? Array.from(connectedModules).sort(([a], [b]) => (a < b ? -1 : 1)) - : connectedModules; - const hash = createHash(this._hashFunction); - const addModuleToHash = module => { - hash.update( - this._getModuleGraphHashBigInt( - this._getChunkGraphModule(module), - module, - runtime - ).toString(16) ); - }; - const addModulesToHash = modules => { - let xor = ZERO_BIG_INT; - for (const m of modules) { - xor = - xor ^ - this._getModuleGraphHashBigInt( - this._getChunkGraphModule(m), - m, - runtime - ); - } - hash.update(xor.toString(16)); - }; - if (activeNamespaceModules.size === 1) - addModuleToHash(activeNamespaceModules.values().next().value); - else if (activeNamespaceModules.size > 1) - addModulesToHash(activeNamespaceModules); - for (const [stateInfo, modules] of connectedModulesInOrder) { - hash.update(stateInfo); - if (modules instanceof Set) { - addModulesToHash(modules); - } else { - addModuleToHash(modules); - } } - hash.update(graphHash); - return /** @type {string} */ (hash.digest("hex")); - }); - } - - /** - * @param {Chunk} chunk the chunk - * @returns {ReadonlySet} runtime requirements - */ - getTreeRuntimeRequirements(chunk) { - const cgc = this._getChunkGraphChunk(chunk); - return cgc.runtimeRequirementsInTree; - } - - // 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 {ChunkGraph} the chunk graph - */ - static getChunkGraphForModule(module, deprecateMessage, deprecationCode) { - const fn = deprecateGetChunkGraphForModuleMap.get(deprecateMessage); - if (fn) return fn(module); - const newFn = util.deprecate( - /** - * @param {Module} module the module - * @returns {ChunkGraph} the chunk graph - */ - module => { - const chunkGraph = chunkGraphForModuleMap.get(module); - if (!chunkGraph) - throw new Error( - deprecateMessage + - ": There was no ChunkGraph assigned to the Module for backward-compat (Use the new API)" - ); - return chunkGraph; - }, - deprecateMessage + ": Use new ChunkGraph API", - deprecationCode ); - deprecateGetChunkGraphForModuleMap.set(deprecateMessage, newFn); - return newFn(module); } - // TODO remove in webpack 6 /** - * @param {Module} module the module - * @param {ChunkGraph} chunkGraph the chunk graph + * @param {InputFileSystem} fs file system + * @param {ContextModuleOptions} options options + * @param {ResolveDependenciesCallback} callback callback function * @returns {void} */ - static setChunkGraphForModule(module, chunkGraph) { - chunkGraphForModuleMap.set(module, chunkGraph); - } + resolveDependencies(fs, options, callback) { + const cmf = this; + const { + resource, + resourceQuery, + resourceFragment, + recursive, + regExp, + include, + exclude, + referencedExports, + category, + typePrefix + } = options; + if (!regExp || !resource) return callback(null, []); - // TODO remove in webpack 6 - /** - * @param {Module} module the module - * @returns {void} - */ - static clearChunkGraphForModule(module) { - chunkGraphForModuleMap.delete(module); - } + 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 + ); + }); + }; - // TODO remove in webpack 6 - /** - * @param {Chunk} chunk the chunk - * @param {string} deprecateMessage message for the deprecation message - * @param {string} deprecationCode code for the deprecation - * @returns {ChunkGraph} the chunk graph - */ - static getChunkGraphForChunk(chunk, deprecateMessage, deprecationCode) { - const fn = deprecateGetChunkGraphForChunkMap.get(deprecateMessage); - if (fn) return fn(chunk); - const newFn = util.deprecate( - /** - * @param {Chunk} chunk the chunk - * @returns {ChunkGraph} the chunk graph - */ - chunk => { - const chunkGraph = chunkGraphForChunkMap.get(chunk); - if (!chunkGraph) - throw new Error( - deprecateMessage + - "There was no ChunkGraph assigned to the Chunk for backward-compat (Use the new API)" - ); - return chunkGraph; - }, - deprecateMessage + ": Use new ChunkGraph API", - deprecationCode - ); - deprecateGetChunkGraphForChunkMap.set(deprecateMessage, newFn); - return newFn(chunk); - } + 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); - // TODO remove in webpack 6 - /** - * @param {Chunk} chunk the chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {void} - */ - static setChunkGraphForChunk(chunk, chunkGraph) { - chunkGraphForChunkMap.set(chunk, chunkGraph); - } + 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); + } + } - // TODO remove in webpack 6 - /** - * @param {Chunk} chunk the chunk - * @returns {void} - */ - static clearChunkGraphForChunk(chunk) { - chunkGraphForChunkMap.delete(chunk); - } -} + 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, "/") + }; -// TODO remove in webpack 6 -/** @type {WeakMap} */ -const chunkGraphForModuleMap = new WeakMap(); + 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, + typePrefix, + category, + referencedExports + ); + dep.optional = true; + return dep; + }); + callback(null, alternatives); + } + ); + } else { + callback(); + } + }); + } else { + callback(); + } + }, + (err, result) => { + if (err) return callback(err); -// TODO remove in webpack 6 -/** @type {WeakMap} */ -const chunkGraphForChunkMap = new WeakMap(); + if (!result) return callback(null, []); -// TODO remove in webpack 6 -/** @type {Map ChunkGraph>} */ -const deprecateGetChunkGraphForModuleMap = new Map(); + const flattenedResult = []; -// TODO remove in webpack 6 -/** @type {Map ChunkGraph>} */ -const deprecateGetChunkGraphForChunkMap = new Map(); + for (const item of result) { + if (item) flattenedResult.push(...item); + } -module.exports = ChunkGraph; + 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); + } + } +}; /***/ }), -/***/ 15626: +/***/ 12206: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -27902,588 +30819,1017 @@ module.exports = ChunkGraph; -const util = __webpack_require__(73837); -const SortableSet = __webpack_require__(13098); -const { - compareLocations, - compareChunks, - compareIterables -} = __webpack_require__(29579); +const ContextElementDependency = __webpack_require__(58477); +const { join } = __webpack_require__(17139); -/** @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 */ +class ContextReplacementPlugin { + constructor( + resourceRegExp, + newContentResource, + newContentRecursive, + newContentRegExp + ) { + this.resourceRegExp = resourceRegExp; -/** @typedef {{id: number}} HasId */ -/** @typedef {{module: Module, loc: DependencyLocation, request: string}} OriginRecord */ + 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; + } + } -/** - * @typedef {Object} RawChunkGroupOptions - * @property {number=} preloadOrder - * @property {number=} prefetchOrder - */ + 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; -/** @typedef {RawChunkGroupOptions & { name?: string }} ChunkGroupOptions */ + 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; + }); + }); + } +} -let debugId = 5000; +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; +}; -/** - * @template T - * @param {SortableSet} set set to convert to array. - * @returns {T[]} the array format of existing set - */ -const getArray = set => Array.from(set); +module.exports = ContextReplacementPlugin; -/** - * 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; -}; + +/***/ }), + +/***/ 79065: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const WebpackError = __webpack_require__(53799); +const ConstDependency = __webpack_require__(76911); +const BasicEvaluatedExpression = __webpack_require__(950); +const { + evaluateToString, + toConstantDependency +} = __webpack_require__(93998); +const createHash = __webpack_require__(49835); + +/** @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} CodeValue */ /** - * @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 + * @typedef {Object} RuntimeValueOptions + * @property {string[]=} fileDependencies + * @property {string[]=} contextDependencies + * @property {string[]=} missingDependencies + * @property {string[]=} buildDependencies + * @property {string|function(): string=} version */ -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 { +class RuntimeValue { /** - * Creates an instance of ChunkGroup. - * @param {string|ChunkGroupOptions=} options chunk group options passed to chunkGroup + * @param {function({ module: NormalModule, key: string, readonly version: string | undefined }): CodeValuePrimitive} fn generator function + * @param {true | string[] | RuntimeValueOptions=} options options */ - constructor(options) { - if (typeof options === "string") { - options = { name: options }; - } else if (!options) { - options = { name: undefined }; + constructor(fn, options) { + this.fn = fn; + if (Array.isArray(options)) { + options = { + fileDependencies: options + }; } - /** @type {number} */ - this.groupDebugId = debugId++; - this.options = options; - /** @type {SortableSet} */ - this._children = new SortableSet(undefined, sortById); - /** @type {SortableSet} */ - this._parents = new SortableSet(undefined, sortById); - /** @type {SortableSet} */ - 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} */ - this._modulePreOrderIndices = new Map(); - /** Indices in bottom-up order */ - /** @private @type {Map} */ - this._modulePostOrderIndices = new Map(); - /** @type {number} */ - this.index = undefined; + this.options = options || {}; + } + + get fileDependencies() { + return this.options === true ? true : this.options.fileDependencies; } /** - * when a new chunk is added to a chunkGroup, addingOptions will occur. - * @param {ChunkGroupOptions} options the chunkGroup options passed to addOptions - * @returns {void} + * @param {JavascriptParser} parser the parser + * @param {Map>} valueCacheVersions valueCacheVersions + * @param {string} key the defined key + * @returns {CodeValuePrimitive} code */ - 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}` - ); + 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 /** @type {string} */ ( + valueCacheVersions.get(VALUE_DEP_PREFIX + key) + ); + } + }); } - /** - * returns the name of current ChunkGroup - * @returns {string|undefined} returns the ChunkGroup name - */ - get name() { - return this.options.name; + getCacheVersion() { + return this.options === true + ? undefined + : (typeof this.options.version === "function" + ? this.options.version() + : this.options.version) || "unset"; } +} - /** - * sets a new name for current ChunkGroup - * @param {string} value the new name for ChunkGroup - * @returns {void} - */ - set name(value) { - this.options.name = value; +/** + * @param {any[]|{[k: string]: any}} obj obj + * @param {JavascriptParser} parser Parser + * @param {Map>} 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(",")}}`; } - /* 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("+"); + switch (asiSafe) { + case null: + return code; + case true: + return arr ? code : `(${code})`; + case false: + return arr ? `;${code}` : `;(${code})`; + default: + return `/*#__PURE__*/Object(${code})`; } +}; - /** - * 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("+"); +/** + * Convert code to a string that evaluates + * @param {CodeValue} code Code to evaluate + * @param {JavascriptParser} parser Parser + * @param {Map>} 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"; } - - /** - * 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; + if (code === undefined) { + return "undefined"; } - - /** - * 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; + if (Object.is(code, -0)) { + return "-0"; } - - /** - * 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; + if (code instanceof RuntimeValue) { + return toCode( + code.exec(parser, valueCacheVersions, key), + parser, + valueCacheVersions, + key, + runtimeTemplate, + asiSafe + ); } - - /** - * @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; - } + 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 + ""; +}; - /** - * @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; +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 "; +const VALUE_DEP_MAIN = "webpack/DefinePlugin_hash"; +class DefinePlugin { /** - * @returns {boolean} true, when this chunk group will be loaded on initial page load + * Create a new define plugin + * @param {Record} definitions A map of global object definitions */ - isInitial() { - return false; + constructor(definitions) { + this.definitions = definitions; } /** - * @param {ChunkGroup} group chunk group to add - * @returns {boolean} returns true if chunk group was added + * @param {function({ module: NormalModule, key: string, readonly version: string | undefined }): CodeValuePrimitive} fn generator function + * @param {true | string[] | RuntimeValueOptions=} options options + * @returns {RuntimeValue} runtime value */ - addChild(group) { - const size = this._children.size; - this._children.add(group); - return size !== this._children.size; + static runtimeValue(fn, options) { + return new RuntimeValue(fn, options); } /** - * @returns {ChunkGroup[]} returns the children of this group + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - getChildren() { - return this._children.getFromCache(getArray); - } + apply(compiler) { + const definitions = this.definitions; + compiler.hooks.compilation.tap( + "DefinePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + const { runtimeTemplate } = compilation; - getNumberOfChildren() { - return this._children.size; - } + const mainHash = createHash(compilation.outputOptions.hashFunction); + mainHash.update( + /** @type {string} */ ( + compilation.valueCacheVersions.get(VALUE_DEP_MAIN) + ) || "" + ); - get childrenIterable() { - return this._children; - } + /** + * Handler + * @param {JavascriptParser} parser Parser + * @returns {void} + */ + const handler = parser => { + const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN); + parser.hooks.program.tap("DefinePlugin", () => { + const { buildInfo } = parser.state.module; + if (!buildInfo.valueDependencies) + buildInfo.valueDependencies = new Map(); + buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue); + }); - /** - * @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; - } + const addValueDependency = key => { + const { buildInfo } = parser.state.module; + buildInfo.valueDependencies.set( + VALUE_DEP_PREFIX + key, + compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key) + ); + }; - this._children.delete(group); - group.removeParent(this); - return true; - } + const withValueDependency = + (key, fn) => + (...args) => { + addValueDependency(key); + return fn(...args); + }; - /** - * @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; - } + /** + * 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); + }); + }; - /** - * @returns {ChunkGroup[]} returns the parents of this group - */ - getParents() { - return this._parents.getFromCache(getArray); - } + /** + * 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; + }); + }); + }; - getNumberOfParents() { - return this._parents.size; - } + /** + * 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); + }); + }; - /** - * @param {ChunkGroup} parent the parent group - * @returns {boolean} returns true if the parent group contains this group - */ - hasParent(parent) { - return this._parents.has(parent); - } + /** + * 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]) + ); - get parentsIterable() { - return this._parents; - } + 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")) + ) + ); + }; - /** - * @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; - } + walkDefinitions(definitions, ""); + }; - /** - * @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; + 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; + mainHash.update("|" + prefix + key); + const oldVersion = compilation.valueCacheVersions.get(name); + if (oldVersion === undefined) { + compilation.valueCacheVersions.set(name, version); + } else if (oldVersion !== version) { + const warning = new WebpackError( + `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, ""); + + compilation.valueCacheVersions.set( + VALUE_DEP_MAIN, + /** @type {string} */ (mainHash.digest("hex").slice(0, 8)) + ); + } + ); } +} +module.exports = DefinePlugin; - get asyncEntrypointsIterable() { - return this._asyncEntrypoints; + +/***/ }), + +/***/ 28623: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { OriginalSource, RawSource } = __webpack_require__(51255); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const DelegatedSourceDependency = __webpack_require__(22914); +const StaticExportsDependency = __webpack_require__(91418); +const makeSerializable = __webpack_require__(33032); + +/** @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 {Array} an array containing the blocks + * @returns {Set} types available (do not mutate) */ - getBlocks() { - return this._blocks.getFromCache(getArray); - } - - getNumberOfBlocks() { - return this._blocks.size; + getSourceTypes() { + return TYPES; } - hasBlock(block) { - return this._blocks.has(block); + /** + * @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 {Iterable} blocks + * @returns {string} a unique identifier of the module */ - get blocksIterable() { - return this._blocks; + identifier() { + return `delegated ${JSON.stringify(this.request)} from ${ + this.sourceRequest + }`; } /** - * @param {AsyncDependenciesBlock} block a block - * @returns {boolean} false, if block was already added + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module */ - addBlock(block) { - if (!this._blocks.has(block)) { - this._blocks.add(block); - return true; - } - return false; + readableIdentifier(requestShortener) { + return `delegated ${this.userRequest} from ${this.sourceRequest}`; } /** - * @param {Module} module origin module - * @param {DependencyLocation} loc location of the reference in the origin module - * @param {string} request request name of the reference + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild * @returns {void} */ - addOrigin(module, loc, request) { - this.origins.push({ - module, - loc, - request - }); + needBuild(context, callback) { + return callback(null, !this.buildMeta); } /** - * @returns {string[]} the files contained this chunk group + * @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} */ - getFiles() { - const files = new Set(); - - for (const chunk of this.chunks) { - for (const file of chunk.files) { - files.add(file); - } - } - - return Array.from(files); + 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(); } /** - * @returns {void} + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - remove() { - // cleanup parents - for (const parentChunkGroup of this._parents) { - // remove this chunk from its parents - parentChunkGroup._children.delete(this); + codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { + const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]); + const sourceModule = moduleGraph.getModule(dep); + let str; - // 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); + 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; } - } - /** - * 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); + str += ";"; } - // remove chunks - for (const chunk of this.chunks) { - chunk.removeGroup(this); + const sources = new Map(); + if (this.useSourceMap || this.useSimpleSourceMap) { + sources.set("javascript", new OriginalSource(str, this.identifier())); + } else { + sources.set("javascript", new RawSource(str)); } - } - sortItems() { - this.origins.sort(sortOrigin); + return { + sources, + runtimeRequirements: RUNTIME_REQUIREMENTS + }; } /** - * 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 + * @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) */ - 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 - ); + size(type) { + return 42; } /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {Record} mapping from children type to ordered list of ChunkGroups + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} */ - getChildrenByOrders(moduleGraph, chunkGraph) { - /** @type {Map} */ - 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} */ - 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; + updateHash(hash, context) { + hash.update(this.delegationType); + hash.update(JSON.stringify(this.request)); + super.updateHash(hash, context); } - /** - * 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); + serialize(context) { + const { write } = context; + // constructor + write(this.sourceRequest); + write(this.delegateData); + write(this.delegationType); + write(this.userRequest); + write(this.originalRequest); + super.serialize(context); } - /** - * 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); + 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; } /** - * 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 + * 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} */ - setModulePostOrderIndex(module, index) { - this._modulePostOrderIndices.set(module, index); + 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; } /** - * Gets the bottom-up index of a module in this ChunkGroup - * @param {Module} module the module - * @returns {number} index + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. */ - 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}` - ); - } - } + cleanupForCache() { + super.cleanupForCache(); + this.delegateData = undefined; } } -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" -); +makeSerializable(DelegatedModule, "webpack/lib/DelegatedModule"); -module.exports = ChunkGroup; +module.exports = DelegatedModule; /***/ }), -/***/ 918: +/***/ 51387: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -28494,563 +31840,261 @@ module.exports = ChunkGroup; -const WebpackError = __webpack_require__(53799); - -/** @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(); +const DelegatedModule = __webpack_require__(28623); - this.name = "ChunkRenderError"; - this.error = error; - this.message = error.message; - this.details = error.stack; - this.file = file; - this.chunk = chunk; +// 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"]; } -} - -module.exports = ChunkRenderError; - - -/***/ }), - -/***/ 46341: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const util = __webpack_require__(73837); -const memoize = __webpack_require__(78676); - -/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */ -/** @typedef {import("./Compilation")} Compilation */ - -const getJavascriptModulesPlugin = memoize(() => - __webpack_require__(89464) -); -// 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 + 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 ) ); - }, - "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 - ) + } + 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 ); - }, - "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" - ) - } - }); + } + } + return module; + } + ); + } } } - -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; +module.exports = DelegatedModuleFactoryPlugin; /***/ }), -/***/ 31085: +/***/ 80632: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov + Author Tobias Koppers @sokra */ -const asyncLib = __webpack_require__(78175); -const { SyncBailHook } = __webpack_require__(41242); -const Compilation = __webpack_require__(85720); -const createSchemaValidation = __webpack_require__(32540); -const { join } = __webpack_require__(17139); -const processAsyncTree = __webpack_require__(42791); +const DelegatedModuleFactoryPlugin = __webpack_require__(51387); +const DelegatedSourceDependency = __webpack_require__(22914); -/** @typedef {import("../declarations/WebpackOptions").CleanOptions} CleanOptions */ /** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./logging/Logger").Logger} Logger */ -/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ -/** @typedef {import("./util/fs").StatsCallback} StatsCallback */ -/** @typedef {(function(string):boolean)|RegExp} IgnoreItem */ -/** @typedef {function(IgnoreItem): void} AddToIgnoreCallback */ +class DelegatedPlugin { + constructor(options) { + this.options = options; + } -/** - * @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 - */ + /** + * 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 + ); + } + ); -const validate = createSchemaValidation( - undefined, - () => { - const { definitions } = __webpack_require__(73342); - return { - definitions, - oneOf: [{ $ref: "#/definitions/CleanOptions" }] - }; - }, - { - name: "Clean Plugin", - baseDataPath: "options" + compiler.hooks.compile.tap("DelegatedPlugin", ({ normalModuleFactory }) => { + new DelegatedModuleFactoryPlugin({ + associatedObjectForCache: compiler.root, + ...this.options + }).apply(normalModuleFactory); + }); } -); +} -/** - * @param {OutputFileSystem} fs filesystem - * @param {string} outputPath output path - * @param {Set} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator) - * @param {function((Error | null)=, Set=): 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); +module.exports = DelegatedPlugin; - callback(null, diff); - } - ); -}; -/** - * @param {Set} currentAssets assets list - * @param {Set} oldAssets old assets list - * @returns {Set} diff - */ -const getDiffToOldAssets = (currentAssets, oldAssets) => { - const diff = new Set(); - for (const asset of oldAssets) { - if (!currentAssets.has(asset)) diff.add(asset); +/***/ }), + +/***/ 71040: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); + +/** @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 = []; + /** @type {DependenciesBlock} */ + this.parent = undefined; } - return diff; -}; -/** - * @param {OutputFileSystem} fs filesystem - * @param {string} filename path to file - * @param {StatsCallback} callback callback for provided filename - * @returns {void} - */ -const doStat = (fs, filename, callback) => { - if ("lstat" in fs) { - fs.lstat(filename, callback); - } else { - fs.stat(filename, callback); + getRootBlock() { + /** @type {DependenciesBlock} */ + let current = this; + while (current.parent) current = current.parent; + return current; } -}; -/** - * @param {OutputFileSystem} fs filesystem - * @param {string} outputPath output path - * @param {boolean} dry only log instead of fs modification - * @param {Logger} logger logger - * @param {Set} 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); - } - doStat(fs, 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 - ); -}; + /** + * 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; + } -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); + /** + * @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); + } -class CleanPlugin { /** - * @param {Compilation} compilation the compilation - * @returns {CleanPluginCompilationHooks} the attached hooks + * @param {Dependency} dependency dependency being removed + * @returns {void} */ - 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); + removeDependency(dependency) { + const idx = this.dependencies.indexOf(dependency); + if (idx >= 0) { + this.dependencies.splice(idx, 1); } - return hooks; } - /** @param {CleanOptions} options options */ - constructor(options = {}) { - validate(options); - this.options = { dry: false, ...options }; + /** + * Removes all dependencies and blocks + * @returns {void} + */ + clearDependenciesAndBlocks() { + this.dependencies.length = 0; + this.blocks.length = 0; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context * @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); - }; + updateHash(hash, context) { + for (const dep of this.dependencies) { + dep.updateHash(hash, context); + } + for (const block of this.blocks) { + block.updateHash(hash, context); + } + } - 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); - }); - }; + serialize({ write }) { + write(this.dependencies); + write(this.blocks); + } - if (oldAssets) { - diffCallback(null, getDiffToOldAssets(currentAssets, oldAssets)); - } else { - getDiffToFs(fs, outputPath, currentAssets, diffCallback); - } - } - ); + deserialize({ read }) { + this.dependencies = read(); + this.blocks = read(); + for (const block of this.blocks) { + block.parent = this; + } } } -module.exports = CleanPlugin; +makeSerializable(DependenciesBlock, "webpack/lib/DependenciesBlock"); + +module.exports = DependenciesBlock; /***/ }), -/***/ 2102: +/***/ 54912: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -29061,237 +32105,352 @@ module.exports = CleanPlugin; -const WebpackError = __webpack_require__(53799); +const memoize = __webpack_require__(78676); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ /** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ -class CodeGenerationError extends WebpackError { - /** - * Create a new CodeGenerationError - * @param {Module} module related module - * @param {Error} error Original error - */ - constructor(module, error) { - super(); +/** + * @typedef {Object} UpdateHashContext + * @property {ChunkGraph} chunkGraph + * @property {RuntimeSpec} runtime + * @property {RuntimeTemplate=} runtimeTemplate + */ - this.name = "CodeGenerationError"; - this.error = error; - this.message = error.message; - this.details = error.stack; - this.module = module; - } -} +/** + * @typedef {Object} SourcePosition + * @property {number} line + * @property {number=} column + */ -module.exports = CodeGenerationError; +/** + * @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 */ -/***/ 71426: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @typedef {Object} ExportSpec + * @property {string} name the name of the export + * @property {boolean=} canMangle can the export be renamed (defaults to true) + * @property {boolean=} terminalBinding is the export a terminal binding that should be checked for export star conflicts + * @property {(string | ExportSpec)[]=} exports nested exports + * @property {ModuleGraphConnection=} from when reexported: from which module + * @property {string[] | null=} export when reexported: from which export + * @property {number=} priority when reexported: with which priority + * @property {boolean=} hidden export is not visible, because another export blends over it + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @typedef {Object} ExportsSpec + * @property {(string | ExportSpec)[] | true | null} exports exported names, true for unknown exports or null for no exports + * @property {Set=} excludeExports when exports = true, list of unaffected exports + * @property {Set=} hideExports list of maybe prior exposed, but now hidden exports + * @property {ModuleGraphConnection=} from when reexported: from which module + * @property {number=} priority when reexported: with which priority + * @property {boolean=} canMangle can the export be renamed (defaults to true) + * @property {boolean=} terminalBinding are the exports terminal bindings that should be checked for export star conflicts + * @property {Module[]=} dependencies module on which the result depends on + */ +/** + * @typedef {Object} ReferencedExport + * @property {string[]} name name of the referenced export + * @property {boolean=} canMangle when false, referenced export can not be mangled, defaults to true + */ +const TRANSITIVE = Symbol("transitive"); -const { provide } = __webpack_require__(82482); -const { first } = __webpack_require__(93347); -const createHash = __webpack_require__(49835); -const { runtimeToString, RuntimeSpecMap } = __webpack_require__(17156); +const getIgnoredModule = memoize(() => { + const RawModule = __webpack_require__(84929); + return new RawModule("/* (ignored) */", `ignored`, `(ignored)`); +}); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {typeof import("./util/Hash")} Hash */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +class Dependency { + constructor() { + /** @type {Module} */ + this._parentModule = undefined; + /** @type {DependenciesBlock} */ + this._parentDependenciesBlock = undefined; + /** @type {number} */ + this._parentDependenciesBlockIndex = -1; + // TODO check if this can be moved into ModuleDependency + /** @type {boolean} */ + this.weak = false; + // TODO check if this can be moved into ModuleDependency + /** @type {boolean} */ + this.optional = false; + this._locSL = 0; + this._locSC = 0; + this._locEL = 0; + this._locEC = 0; + this._locI = undefined; + this._locN = undefined; + this._loc = undefined; + } -class CodeGenerationResults { /** - * @param {string | Hash} hashFunction the hash function to use + * @returns {string} a display name for the type of dependency */ - constructor(hashFunction = "md4") { - /** @type {Map>} */ - this.map = new Map(); - this._hashFunction = hashFunction; + get type() { + return "unknown"; } /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime runtime(s) - * @returns {CodeGenerationResult} the CodeGenerationResult + * @returns {string} a dependency category, typical categories are "commonjs", "amd", "esm" */ - 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(", ")})` - ); + get category() { + return "unknown"; + } + + /** + * @returns {DependencyLocation} location + */ + get loc() { + if (this._loc !== undefined) return this._loc; + /** @type {SyntheticDependencyLocation & RealDependencyLocation} */ + const loc = {}; + if (this._locSL > 0) { + loc.start = { line: this._locSL, column: this._locSC }; } - if (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; + if (this._locEL > 0) { + loc.end = { line: this._locEL, column: this._locEC }; } - 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(", ")})` - ); + if (this._locN !== undefined) { + loc.name = this._locN; } - return result; + if (this._locI !== undefined) { + loc.index = this._locI; + } + return (this._loc = loc); } - /** - * @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; + set loc(loc) { + if ("start" in loc && typeof loc.start === "object") { + this._locSL = loc.start.line || 0; + this._locSC = loc.start.column || 0; + } else { + this._locSL = 0; + this._locSC = 0; } - if (runtime !== undefined) { - return entry.has(runtime); - } else if (entry.size > 1) { - const results = new Set(entry.values()); - return results.size === 1; + if ("end" in loc && typeof loc.end === "object") { + this._locEL = loc.end.line || 0; + this._locEC = loc.end.column || 0; } else { - return entry.size === 1; + this._locEL = 0; + this._locEC = 0; + } + if ("index" in loc) { + this._locI = loc.index; + } else { + this._locI = undefined; } + if ("name" in loc) { + this._locN = loc.name; + } else { + this._locN = undefined; + } + this._loc = loc; + } + + setLoc(startLine, startColumn, endLine, endColumn) { + this._locSL = startLine; + this._locSC = startColumn; + this._locEL = endLine; + this._locEC = endColumn; + this._locI = undefined; + this._locN = undefined; + this._loc = undefined; } /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime runtime(s) - * @param {string} sourceType the source type - * @returns {Source} a source + * @returns {string | null} an identifier to merge equal requests */ - getSource(module, runtime, sourceType) { - return this.get(module, runtime).sources.get(sourceType); + getResourceIdentifier() { + return null; } /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime runtime(s) - * @returns {ReadonlySet} runtime requirements + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module */ - getRuntimeRequirements(module, runtime) { - return this.get(module, runtime).runtimeRequirements; + couldAffectReferencingModule() { + return TRANSITIVE; } /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime runtime(s) - * @param {string} key data key - * @returns {any} data generated by code generation + * Returns the referenced module and export + * @deprecated + * @param {ModuleGraph} moduleGraph module graph + * @returns {never} throws error */ - getData(module, runtime, key) { - const data = this.get(module, runtime).data; - return data === undefined ? undefined : data.get(key); + getReference(moduleGraph) { + throw new Error( + "Dependency.getReference was removed in favor of Dependency.getReferencedExports, ModuleGraph.getModule and ModuleGraph.getConnection().active" + ); } /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime runtime(s) - * @returns {any} hash of the code generation + * 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 */ - getHash(module, runtime) { - const info = this.get(module, runtime); - if (info.hash !== undefined) return info.hash; - const hash = createHash(this._hashFunction); - 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"))); + getReferencedExports(moduleGraph, runtime) { + return Dependency.EXPORTS_OBJECT_REFERENCED; } /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime runtime(s) - * @param {CodeGenerationResult} result result from module - * @returns {void} + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active */ - add(module, runtime, result) { - const map = provide(this.map, module, () => new RuntimeSpecMap()); - map.set(runtime, result); + getCondition(moduleGraph) { + return null; } -} - -module.exports = CodeGenerationResults; - - -/***/ }), - -/***/ 98427: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * 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; + } -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); + /** + * Returns errors + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} errors + */ + getErrors(moduleGraph) { + return null; + } -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) {} -class CommentCompilationWarning extends WebpackError { /** - * - * @param {string} message warning message - * @param {DependencyLocation} loc affected lines of code + * implement this method to allow the occurrence order plugin to count correctly + * @returns {number} count how often the id is used in this dependency */ - constructor(message, loc) { - super(message); + getNumberOfIdOccurrences() { + return 1; + } - this.name = "CommentCompilationWarning"; + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return true; + } - this.loc = loc; + /** + * @param {string} context context directory + * @returns {Module} a module + */ + createIgnoredModule(context) { + return getIgnoredModule(); } -} -makeSerializable( - CommentCompilationWarning, - "webpack/lib/CommentCompilationWarning" -); + serialize({ write }) { + write(this.weak); + write(this.optional); + write(this._locSL); + write(this._locSC); + write(this._locEL); + write(this._locEC); + write(this._locI); + write(this._locN); + } -module.exports = CommentCompilationWarning; + deserialize({ read }) { + this.weak = read(); + this.optional = read(); + this._locSL = read(); + this._locSC = read(); + this._locEL = read(); + this._locEC = read(); + this._locI = read(); + this._locN = read(); + } +} + +/** @type {string[][]} */ +Dependency.NO_EXPORTS_REFERENCED = []; +/** @type {string[][]} */ +Dependency.EXPORTS_OBJECT_REFERENCED = [[]]; + +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)" + ); + } +}); + +Dependency.TRANSITIVE = TRANSITIVE; + +module.exports = Dependency; /***/ }), -/***/ 94258: +/***/ 5160: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -29302,156 +32461,199 @@ module.exports = CommentCompilationWarning; -const ConstDependency = __webpack_require__(76911); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Generator").GenerateContext} GenerateContext */ +/** @template T @typedef {import("./InitFragment")} InitFragment */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** + * @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} 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 + * @property {CodeGenerationResults} codeGenerationResults the code generation results + */ -const nestedWebpackRequireTag = Symbol("nested __webpack_require__"); +/** + * @typedef {Object} CssDependencyTemplateContextExtras + * @property {Map} cssExports the css exports + */ -class CompatibilityPlugin { +/** @typedef {DependencyTemplateContext & CssDependencyTemplateContextExtras} CssDependencyTemplateContext */ + +class DependencyTemplate { + /* istanbul ignore next */ /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - compiler.hooks.compilation.tap( - "CompatibilityPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); + apply(dependency, source, templateContext) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); + } +} - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("CompatibilityPlugin", (parser, parserOptions) => { - if ( - parserOptions.browserify !== undefined && - !parserOptions.browserify - ) - return; +module.exports = DependencyTemplate; - 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 handler = parser => { - // Handle nested requires - 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; - }); +/***/ }), - // Handle hashbang - parser.hooks.program.tap( - "CompatibilityPlugin", - (program, comments) => { - if (comments.length === 0) return; - const c = comments[0]; - if (c.type === "Line" && c.range[0] === 0) { - if (parser.state.source.slice(0, 2).toString() !== "#!") return; - // this is a hashbang comment - const dep = new ConstDependency("//", 0); - dep.loc = c.loc; - parser.state.module.addPresentationalDependency(dep); - } - } - ); - }; +/***/ 9163: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("CompatibilityPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("CompatibilityPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("CompatibilityPlugin", handler); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const createHash = __webpack_require__(49835); + +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ +/** @typedef {typeof import("./util/Hash")} Hash */ + +/** @typedef {new (...args: any[]) => Dependency} DependencyConstructor */ + +class DependencyTemplates { + /** + * @param {string | Hash} hashFunction the hash function to use + */ + constructor(hashFunction = "md4") { + /** @type {Map} */ + this._map = new Map(); + /** @type {string} */ + this._hash = "31d6cfe0d16ae931b73c59d7e0c089c0"; + this._hashFunction = hashFunction; + } + + /** + * @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(this._hashFunction); + hash.update(`${this._hash}${part}`); + this._hash = /** @type {string} */ (hash.digest("hex")); + } + + getHash() { + return this._hash; + } + + clone() { + const newInstance = new DependencyTemplates(this._hashFunction); + newInstance._map = new Map(this._map); + newInstance._hash = this._hash; + return newInstance; + } +} + +module.exports = DependencyTemplates; + + +/***/ }), + +/***/ 62790: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const DllModuleFactory = __webpack_require__(68703); +const DllEntryDependency = __webpack_require__(95666); +const EntryDependency = __webpack_require__(3979); + +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 = CompatibilityPlugin; + +module.exports = DllEntryPlugin; /***/ }), -/***/ 85720: +/***/ 28280: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -29462,5270 +32664,3985 @@ module.exports = CompatibilityPlugin; -const asyncLib = __webpack_require__(78175); -const { - HookMap, - SyncHook, - SyncBailHook, - SyncWaterfallHook, - AsyncSeriesHook, - AsyncSeriesBailHook, - AsyncParallelHook -} = __webpack_require__(41242); -const util = __webpack_require__(73837); -const { CachedSource } = __webpack_require__(51255); -const { MultiItemCache } = __webpack_require__(55392); -const Chunk = __webpack_require__(39385); -const ChunkGraph = __webpack_require__(64971); -const ChunkGroup = __webpack_require__(15626); -const ChunkRenderError = __webpack_require__(918); -const ChunkTemplate = __webpack_require__(46341); -const CodeGenerationError = __webpack_require__(2102); -const CodeGenerationResults = __webpack_require__(71426); -const Dependency = __webpack_require__(54912); -const DependencyTemplates = __webpack_require__(9163); -const Entrypoint = __webpack_require__(13795); -const ErrorHelpers = __webpack_require__(59985); -const FileSystemInfo = __webpack_require__(79453); -const { - connectChunkGroupAndChunk, - connectChunkGroupParentAndChild -} = __webpack_require__(37234); -const { - makeWebpackError, - tryRunOrWebpackError -} = __webpack_require__(11351); -const MainTemplate = __webpack_require__(12856); +const { RawSource } = __webpack_require__(51255); const Module = __webpack_require__(73208); -const ModuleDependencyError = __webpack_require__(67409); -const ModuleDependencyWarning = __webpack_require__(29656); -const ModuleGraph = __webpack_require__(99988); -const ModuleNotFoundError = __webpack_require__(32882); -const ModuleProfile = __webpack_require__(36418); -const ModuleRestoreError = __webpack_require__(94560); -const ModuleStoreError = __webpack_require__(59001); -const ModuleTemplate = __webpack_require__(62677); const RuntimeGlobals = __webpack_require__(16475); -const RuntimeTemplate = __webpack_require__(18777); -const Stats = __webpack_require__(31743); -const WebpackError = __webpack_require__(53799); -const buildChunkGraph = __webpack_require__(79233); -const BuildCycleError = __webpack_require__(22273); -const { Logger, LogType } = __webpack_require__(32597); -const StatsFactory = __webpack_require__(92629); -const StatsPrinter = __webpack_require__(30198); -const { equals: arrayEquals } = __webpack_require__(84953); -const AsyncQueue = __webpack_require__(12260); -const LazySet = __webpack_require__(38938); -const { provide } = __webpack_require__(82482); -const WeakTupleMap = __webpack_require__(28745); -const { cachedCleverMerge } = __webpack_require__(60839); -const { - compareLocations, - concatComparators, - compareSelect, - compareIds, - compareStringsNumeric, - compareModulesByIdentifier -} = __webpack_require__(29579); -const createHash = __webpack_require__(49835); -const { - arrayToSetDeprecation, - soonFrozenObjectDeprecation, - createFakeHook -} = __webpack_require__(64518); -const processAsyncTree = __webpack_require__(42791); -const { getRuntimeKey } = __webpack_require__(17156); -const { isSourceEqual } = __webpack_require__(41245); +const makeSerializable = __webpack_require__(33032); -/** @template T @typedef {import("tapable").AsArray} AsArray */ /** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ -/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ -/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ -/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ -/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("./Cache")} Cache */ -/** @typedef {import("./CacheFacade")} CacheFacade */ -/** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Compiler").CompilationParams} CompilationParams */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ -/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ +/** @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("./ModuleFactory")} ModuleFactory */ -/** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */ -/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./Module").SourceContext} SourceContext */ /** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./RuntimeModule")} RuntimeModule */ -/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry */ -/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ /** @typedef {import("./util/Hash")} Hash */ -/** @template T @typedef {import("./util/deprecation").FakeHook} FakeHook */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -/** - * @callback Callback - * @param {(WebpackError | null)=} err - * @returns {void} - */ +const TYPES = new Set(["javascript"]); +const RUNTIME_REQUIREMENTS = new Set([ + RuntimeGlobals.require, + RuntimeGlobals.module +]); -/** - * @callback ModuleCallback - * @param {(WebpackError | null)=} err - * @param {Module=} result - * @returns {void} - */ +class DllModule extends Module { + constructor(context, dependencies, name) { + super("javascript/dynamic", context); -/** - * @callback ModuleFactoryResultCallback - * @param {(WebpackError | null)=} err - * @param {ModuleFactoryResult=} result - * @returns {void} - */ + // Info from Factory + this.dependencies = dependencies; + this.name = name; + } -/** - * @callback ModuleOrFactoryResultCallback - * @param {(WebpackError | null)=} err - * @param {Module | ModuleFactoryResult=} result - * @returns {void} - */ + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; + } -/** - * @callback ExecuteModuleCallback - * @param {(WebpackError | null)=} err - * @param {ExecuteModuleResult=} result - * @returns {void} - */ + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `dll ${this.name}`; + } -/** - * @callback DepBlockVarDependenciesCallback - * @param {Dependency} dependency - * @returns {any} - */ + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `dll ${this.name}`; + } -/** @typedef {new (...args: any[]) => Dependency} DepConstructor */ -/** @typedef {Record} CompilationAssets */ + /** + * @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(); + } -/** - * @typedef {Object} AvailableModulesChunkGroupMapping - * @property {ChunkGroup} chunkGroup - * @property {Set} availableModules - * @property {boolean} needCopy - */ + /** + * @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 + }; + } -/** - * @typedef {Object} DependenciesBlockLike - * @property {Dependency[]} dependencies - * @property {AsyncDependenciesBlock[]} blocks - */ + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, !this.buildMeta); + } -/** - * @typedef {Object} ChunkPathData - * @property {string|number} id - * @property {string=} name - * @property {string} hash - * @property {function(number): string=} hashWithLength - * @property {(Record)=} contentHash - * @property {(Record string>)=} contentHashWithLength - */ + /** + * @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; + } -/** - * @typedef {Object} ChunkHashContext - * @property {RuntimeTemplate} runtimeTemplate the runtime template - * @property {ModuleGraph} moduleGraph the module graph - * @property {ChunkGraph} chunkGraph the chunk graph - */ + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + hash.update(`dll module${this.name || ""}`); + super.updateHash(hash, context); + } -/** - * @typedef {Object} RuntimeRequirementsContext - * @property {ChunkGraph} chunkGraph the chunk graph - * @property {CodeGenerationResults} codeGenerationResults the code generation results - */ + serialize(context) { + context.write(this.name); + super.serialize(context); + } -/** - * @typedef {Object} ExecuteModuleOptions - * @property {EntryOptions=} entryOptions - */ + deserialize(context) { + this.name = context.read(); + super.deserialize(context); + } -/** - * @typedef {Object} ExecuteModuleResult - * @property {any} exports - * @property {boolean} cacheable - * @property {Map} assets - * @property {LazySet} fileDependencies - * @property {LazySet} contextDependencies - * @property {LazySet} missingDependencies - * @property {LazySet} buildDependencies - */ + /** + * 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; + } -/** - * @typedef {Object} ExecuteModuleArgument - * @property {Module} module - * @property {{ id: string, exports: any, loaded: boolean }=} moduleObject - * @property {any} preparedInfo - * @property {CodeGenerationResult} codeGenerationResult - */ + /** + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. + */ + cleanupForCache() { + super.cleanupForCache(); + this.dependencies = undefined; + } +} -/** - * @typedef {Object} ExecuteModuleContext - * @property {Map} assets - * @property {Chunk} chunk - * @property {ChunkGraph} chunkGraph - * @property {function(string): any=} __webpack_require__ - */ +makeSerializable(DllModule, "webpack/lib/DllModule"); -/** - * @typedef {Object} EntryData - * @property {Dependency[]} dependencies dependencies of the entrypoint that should be evaluated at startup - * @property {Dependency[]} includeDependencies dependencies of the entrypoint that should be included but not evaluated - * @property {EntryOptions} options options of the entrypoint - */ +module.exports = DllModule; -/** - * @typedef {Object} LogEntry - * @property {string} type - * @property {any[]} args - * @property {number} time - * @property {string[]=} trace - */ -/** - * @typedef {Object} KnownAssetInfo - * @property {boolean=} immutable true, if the asset can be long term cached forever (contains a hash) - * @property {boolean=} minimized whether the asset is minimized - * @property {string | string[]=} fullhash the value(s) of the full hash used for this asset - * @property {string | string[]=} chunkhash the value(s) of the chunk hash used for this asset - * @property {string | string[]=} modulehash the value(s) of the module hash used for this asset - * @property {string | string[]=} contenthash the value(s) of the content hash used for this asset - * @property {string=} sourceFilename when asset was created from a source file (potentially transformed), the original filename relative to compilation context - * @property {number=} size size in bytes, only set after asset has been emitted - * @property {boolean=} development true, when asset is only used for development and doesn't count towards user-facing assets - * @property {boolean=} hotModuleReplacement true, when asset ships data for updating an existing application (HMR) - * @property {boolean=} javascriptModule true, when asset is javascript and an ESM - * @property {Record=} related object of pointers to other assets, keyed by type of relation (only points from parent to child) - */ +/***/ }), -/** @typedef {KnownAssetInfo & Record} AssetInfo */ +/***/ 68703: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * @typedef {Object} Asset - * @property {string} name the filename of the asset - * @property {Source} source source of the asset - * @property {AssetInfo} info info about the asset - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * @typedef {Object} ModulePathData - * @property {string|number} id - * @property {string} hash - * @property {function(number): string=} hashWithLength - */ -/** - * @typedef {Object} PathData - * @property {ChunkGraph=} chunkGraph - * @property {string=} hash - * @property {function(number): string=} hashWithLength - * @property {(Chunk|ChunkPathData)=} chunk - * @property {(Module|ModulePathData)=} module - * @property {RuntimeSpec=} runtime - * @property {string=} filename - * @property {string=} basename - * @property {string=} query - * @property {string=} contentHashType - * @property {string=} contentHash - * @property {function(number): string=} contentHashWithLength - * @property {boolean=} noChunkHash - * @property {string=} url - */ -/** - * @typedef {Object} KnownNormalizedStatsOptions - * @property {string} context - * @property {RequestShortener} requestShortener - * @property {string} chunksSort - * @property {string} modulesSort - * @property {string} chunkModulesSort - * @property {string} nestedModulesSort - * @property {string} assetsSort - * @property {boolean} ids - * @property {boolean} cachedAssets - * @property {boolean} groupAssetsByEmitStatus - * @property {boolean} groupAssetsByPath - * @property {boolean} groupAssetsByExtension - * @property {number} assetsSpace - * @property {((value: string, asset: StatsAsset) => boolean)[]} excludeAssets - * @property {((name: string, module: StatsModule, type: "module" | "chunk" | "root-of-chunk" | "nested") => boolean)[]} excludeModules - * @property {((warning: StatsError, textValue: string) => boolean)[]} warningsFilter - * @property {boolean} cachedModules - * @property {boolean} orphanModules - * @property {boolean} dependentModules - * @property {boolean} runtimeModules - * @property {boolean} groupModulesByCacheStatus - * @property {boolean} groupModulesByLayer - * @property {boolean} groupModulesByAttributes - * @property {boolean} groupModulesByPath - * @property {boolean} groupModulesByExtension - * @property {boolean} groupModulesByType - * @property {boolean | "auto"} entrypoints - * @property {boolean} chunkGroups - * @property {boolean} chunkGroupAuxiliary - * @property {boolean} chunkGroupChildren - * @property {number} chunkGroupMaxAssets - * @property {number} modulesSpace - * @property {number} chunkModulesSpace - * @property {number} nestedModulesSpace - * @property {false|"none"|"error"|"warn"|"info"|"log"|"verbose"} logging - * @property {((value: string) => boolean)[]} loggingDebug - * @property {boolean} loggingTrace - * @property {any} _env - */ +const DllModule = __webpack_require__(28280); +const ModuleFactory = __webpack_require__(51010); -/** @typedef {KnownNormalizedStatsOptions & Omit & Record} NormalizedStatsOptions */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./dependencies/DllEntryDependency")} DllEntryDependency */ -/** - * @typedef {Object} KnownCreateStatsOptionsContext - * @property {boolean=} forToString - */ +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 + ) + }); + } +} -/** @typedef {KnownCreateStatsOptionsContext & Record} CreateStatsOptionsContext */ +module.exports = DllModuleFactory; -/** @type {AssetInfo} */ -const EMPTY_ASSET_INFO = Object.freeze({}); -const esmDependencyCategory = "esm"; -// TODO webpack 6: remove -const deprecatedNormalModuleLoaderHook = util.deprecate( - compilation => { - return (__webpack_require__(39).getCompilationHooks)(compilation).loader; - }, - "Compilation.hooks.normalModuleLoader was moved to NormalModule.getCompilationHooks(compilation).loader", - "DEP_WEBPACK_COMPILATION_NORMAL_MODULE_LOADER_HOOK" +/***/ }), + +/***/ 40038: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const DllEntryPlugin = __webpack_require__(62790); +const FlagAllModulesAsUsedPlugin = __webpack_require__(58727); +const LibManifestPlugin = __webpack_require__(93837); +const createSchemaValidation = __webpack_require__(32540); + +/** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ + +const validate = createSchemaValidation( + __webpack_require__(9667), + () => __webpack_require__(99926), + { + name: "Dll Plugin", + baseDataPath: "options" + } ); -// TODO webpack 6: remove -const defineRemovedModuleTemplates = moduleTemplates => { - Object.defineProperties(moduleTemplates, { - asset: { - enumerable: false, - configurable: false, - get: () => { - throw new WebpackError( - "Compilation.moduleTemplates.asset has been removed" - ); - } - }, - webassembly: { - enumerable: false, - configurable: false, - get: () => { - throw new WebpackError( - "Compilation.moduleTemplates.webassembly has been removed" +class DllPlugin { + /** + * @param {DllPluginOptions} options options object + */ + constructor(options) { + validate(options); + this.options = { + ...options, + entryOnly: options.entryOnly !== false + }; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.entryOption.tap("DllPlugin", (context, entry) => { + if (typeof entry !== "function") { + for (const name of Object.keys(entry)) { + 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); } - }); - moduleTemplates = undefined; -}; + } +} -const byId = compareSelect( - /** - * @param {Chunk} c chunk - * @returns {number | string} id - */ c => c.id, - compareIds -); +module.exports = DllPlugin; -const byNameOrHash = concatComparators( - compareSelect( - /** - * @param {Compilation} c compilation - * @returns {string} name - */ - c => c.name, - compareIds - ), - compareSelect( - /** - * @param {Compilation} c compilation - * @returns {string} hash - */ c => c.fullHash, - compareIds - ) -); -const byMessage = compareSelect(err => `${err.message}`, compareStringsNumeric); +/***/ }), -const byModule = compareSelect( - err => (err.module && err.module.identifier()) || "", - compareStringsNumeric -); +/***/ 90999: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const byLocation = compareSelect(err => err.loc, compareLocations); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -const compareErrors = concatComparators(byModule, byLocation, byMessage); -/** @type {WeakMap} */ -const unsafeCacheDependencies = new WeakMap(); -/** @type {WeakMap} */ -const unsafeCacheData = new WeakMap(); +const parseJson = __webpack_require__(15235); +const DelegatedModuleFactoryPlugin = __webpack_require__(51387); +const ExternalModuleFactoryPlugin = __webpack_require__(62153); +const WebpackError = __webpack_require__(53799); +const DelegatedSourceDependency = __webpack_require__(22914); +const createSchemaValidation = __webpack_require__(32540); +const makePathsRelative = (__webpack_require__(82186).makePathsRelative); -class Compilation { +/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ + +const validate = createSchemaValidation( + __webpack_require__(28534), + () => __webpack_require__(46552), + { + name: "Dll Reference Plugin", + baseDataPath: "options" + } +); + +class DllReferencePlugin { /** - * Creates an instance of Compilation. - * @param {Compiler} compiler the compiler which created the compilation - * @param {CompilationParams} params the compilation parameters + * @param {DllReferencePluginOptions} options options object */ - constructor(compiler, params) { - this._backCompat = compiler._backCompat; + constructor(options) { + validate(options); + this.options = options; + /** @type {WeakMap} */ + this._compilationData = new WeakMap(); + } - const getNormalModuleLoader = () => deprecatedNormalModuleLoaderHook(this); - /** @typedef {{ additionalAssets?: true | Function }} ProcessAssetsAdditionalOptions */ - /** @type {AsyncSeriesHook<[CompilationAssets], ProcessAssetsAdditionalOptions>} */ - const processAssetsHook = new AsyncSeriesHook(["assets"]); + apply(compiler) { + compiler.hooks.compilation.tap( + "DllReferencePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + DelegatedSourceDependency, + normalModuleFactory + ); + } + ); - let savedAssets = new Set(); - const popNewAssets = assets => { - let newAssets = undefined; - for (const file of Object.keys(assets)) { - if (savedAssets.has(file)) continue; - if (newAssets === undefined) { - newAssets = Object.create(null); + 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; + } } - newAssets[file] = assets[file]; - savedAssets.add(file); + return callback(); } - return newAssets; - }; - processAssetsHook.intercept({ - name: "Compilation", - call: () => { - savedAssets = new Set(Object.keys(this.assets)); - }, - register: tap => { - const { type, name } = tap; - const { fn, additionalAssets, ...remainingTap } = tap; - const additionalAssetsFn = - additionalAssets === true ? fn : additionalAssets; - const processedAssets = additionalAssetsFn ? new WeakSet() : undefined; - switch (type) { - case "sync": - if (additionalAssetsFn) { - this.hooks.processAdditionalAssets.tap(name, assets => { - if (processedAssets.has(this.assets)) - additionalAssetsFn(assets); - }); - } - return { - ...remainingTap, - type: "async", - fn: (assets, callback) => { - try { - fn(assets); - } catch (e) { - return callback(e); - } - if (processedAssets !== undefined) - processedAssets.add(this.assets); - const newAssets = popNewAssets(assets); - if (newAssets !== undefined) { - this.hooks.processAdditionalAssets.callAsync( - newAssets, - callback - ); - return; - } - callback(); - } - }; - case "async": - if (additionalAssetsFn) { - this.hooks.processAdditionalAssets.tapAsync( - name, - (assets, callback) => { - if (processedAssets.has(this.assets)) - return additionalAssetsFn(assets, callback); - callback(); - } - ); - } - return { - ...remainingTap, - fn: (assets, callback) => { - fn(assets, err => { - if (err) return callback(err); - if (processedAssets !== undefined) - processedAssets.add(this.assets); - const newAssets = popNewAssets(assets); - if (newAssets !== undefined) { - this.hooks.processAdditionalAssets.callAsync( - newAssets, - callback - ); - return; - } - callback(); - }); - } - }; - case "promise": - if (additionalAssetsFn) { - this.hooks.processAdditionalAssets.tapPromise(name, assets => { - if (processedAssets.has(this.assets)) - return additionalAssetsFn(assets); - return Promise.resolve(); - }); - } - return { - ...remainingTap, - fn: assets => { - const p = fn(assets); - if (!p || !p.then) return p; - return p.then(() => { - if (processedAssets !== undefined) - processedAssets.add(this.assets); - const newAssets = popNewAssets(assets); - if (newAssets !== undefined) { - return this.hooks.processAdditionalAssets.promise( - newAssets - ); - } - }); - } - }; + ); + + 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); }); - /** @type {SyncHook<[CompilationAssets]>} */ - const afterProcessAssetsHook = new SyncHook(["assets"]); - - /** - * @template T - * @param {string} name name of the hook - * @param {number} stage new stage - * @param {function(): AsArray} getArgs get old hook function args - * @param {string=} code deprecation code (not deprecated when unset) - * @returns {FakeHook, "tap" | "tapAsync" | "tapPromise" | "name">>} fake hook which redirects - */ - const createProcessAssetsHook = (name, stage, getArgs, code) => { - if (!this._backCompat && code) return undefined; - const errorMessage = - reason => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}. -BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a single Compilation.hooks.processAssets hook.`; - const getOptions = options => { - if (typeof options === "string") options = { name: options }; - if (options.stage) { - throw new Error(errorMessage("it's using the 'stage' option")); - } - return { ...options, stage: stage }; - }; - return createFakeHook( - { - name, - /** @type {AsyncSeriesHook["intercept"]} */ - intercept(interceptor) { - throw new Error(errorMessage("it's using 'intercept'")); - }, - /** @type {AsyncSeriesHook["tap"]} */ - tap: (options, fn) => { - processAssetsHook.tap(getOptions(options), () => fn(...getArgs())); - }, - /** @type {AsyncSeriesHook["tapAsync"]} */ - tapAsync: (options, fn) => { - processAssetsHook.tapAsync( - getOptions(options), - (assets, callback) => - /** @type {any} */ (fn)(...getArgs(), callback) - ); - }, - /** @type {AsyncSeriesHook["tapPromise"]} */ - tapPromise: (options, fn) => { - processAssetsHook.tapPromise(getOptions(options), () => - fn(...getArgs()) - ); + 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); } - }, - `${name} is deprecated (use Compilation.hooks.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)`, - code - ); - }; - this.hooks = Object.freeze({ - /** @type {SyncHook<[Module]>} */ - buildModule: new SyncHook(["module"]), - /** @type {SyncHook<[Module]>} */ - rebuildModule: new SyncHook(["module"]), - /** @type {SyncHook<[Module, WebpackError]>} */ - failedModule: new SyncHook(["module", "error"]), - /** @type {SyncHook<[Module]>} */ - succeedModule: new SyncHook(["module"]), - /** @type {SyncHook<[Module]>} */ - stillValidModule: new SyncHook(["module"]), + } + } + ); + } +} - /** @type {SyncHook<[Dependency, EntryOptions]>} */ - addEntry: new SyncHook(["entry", "options"]), - /** @type {SyncHook<[Dependency, EntryOptions, Error]>} */ - failedEntry: new SyncHook(["entry", "options", "error"]), - /** @type {SyncHook<[Dependency, EntryOptions, Module]>} */ - succeedEntry: new SyncHook(["entry", "options", "module"]), +class DllManifestError extends WebpackError { + constructor(filename, message) { + super(); - /** @type {SyncWaterfallHook<[(string[] | ReferencedExport)[], Dependency, RuntimeSpec]>} */ - dependencyReferencedExports: new SyncWaterfallHook([ - "referencedExports", - "dependency", - "runtime" - ]), + this.name = "DllManifestError"; + this.message = `Dll manifest ${filename}\n${message}`; + } +} - /** @type {SyncHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */ - executeModule: new SyncHook(["options", "context"]), - /** @type {AsyncParallelHook<[ExecuteModuleArgument, ExecuteModuleContext]>} */ - prepareModuleExecution: new AsyncParallelHook(["options", "context"]), +module.exports = DllReferencePlugin; - /** @type {AsyncSeriesHook<[Iterable]>} */ - finishModules: new AsyncSeriesHook(["modules"]), - /** @type {AsyncSeriesHook<[Module]>} */ - finishRebuildingModule: new AsyncSeriesHook(["module"]), - /** @type {SyncHook<[]>} */ - unseal: new SyncHook([]), - /** @type {SyncHook<[]>} */ - seal: new SyncHook([]), - /** @type {SyncHook<[]>} */ - beforeChunks: new SyncHook([]), - /** @type {SyncHook<[Iterable]>} */ - afterChunks: new SyncHook(["chunks"]), +/***/ }), - /** @type {SyncBailHook<[Iterable]>} */ - optimizeDependencies: new SyncBailHook(["modules"]), - /** @type {SyncHook<[Iterable]>} */ - afterOptimizeDependencies: new SyncHook(["modules"]), +/***/ 96475: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {SyncHook<[]>} */ - optimize: new SyncHook([]), - /** @type {SyncBailHook<[Iterable]>} */ - optimizeModules: new SyncBailHook(["modules"]), - /** @type {SyncHook<[Iterable]>} */ - afterOptimizeModules: new SyncHook(["modules"]), +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Naoyuki Kanezawa @nkzawa +*/ - /** @type {SyncBailHook<[Iterable, ChunkGroup[]]>} */ - optimizeChunks: new SyncBailHook(["chunks", "chunkGroups"]), - /** @type {SyncHook<[Iterable, ChunkGroup[]]>} */ - afterOptimizeChunks: new SyncHook(["chunks", "chunkGroups"]), - /** @type {AsyncSeriesHook<[Iterable, Iterable]>} */ - optimizeTree: new AsyncSeriesHook(["chunks", "modules"]), - /** @type {SyncHook<[Iterable, Iterable]>} */ - afterOptimizeTree: new SyncHook(["chunks", "modules"]), - /** @type {AsyncSeriesBailHook<[Iterable, Iterable]>} */ - optimizeChunkModules: new AsyncSeriesBailHook(["chunks", "modules"]), - /** @type {SyncHook<[Iterable, Iterable]>} */ - afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]), - /** @type {SyncBailHook<[], boolean>} */ - shouldRecord: new SyncBailHook([]), +const EntryOptionPlugin = __webpack_require__(9909); +const EntryPlugin = __webpack_require__(96953); +const EntryDependency = __webpack_require__(3979); - /** @type {SyncHook<[Chunk, Set, RuntimeRequirementsContext]>} */ - additionalChunkRuntimeRequirements: new SyncHook([ - "chunk", - "runtimeRequirements", - "context" - ]), - /** @type {HookMap, RuntimeRequirementsContext]>>} */ - runtimeRequirementInChunk: new HookMap( - () => new SyncBailHook(["chunk", "runtimeRequirements", "context"]) - ), - /** @type {SyncHook<[Module, Set, RuntimeRequirementsContext]>} */ - additionalModuleRuntimeRequirements: new SyncHook([ - "module", - "runtimeRequirements", - "context" - ]), - /** @type {HookMap, RuntimeRequirementsContext]>>} */ - runtimeRequirementInModule: new HookMap( - () => new SyncBailHook(["module", "runtimeRequirements", "context"]) - ), - /** @type {SyncHook<[Chunk, Set, RuntimeRequirementsContext]>} */ - additionalTreeRuntimeRequirements: new SyncHook([ - "chunk", - "runtimeRequirements", - "context" - ]), - /** @type {HookMap, RuntimeRequirementsContext]>>} */ - runtimeRequirementInTree: new HookMap( - () => new SyncBailHook(["chunk", "runtimeRequirements", "context"]) - ), +/** @typedef {import("../declarations/WebpackOptions").EntryDynamicNormalized} EntryDynamic */ +/** @typedef {import("../declarations/WebpackOptions").EntryItem} EntryItem */ +/** @typedef {import("../declarations/WebpackOptions").EntryStaticNormalized} EntryStatic */ +/** @typedef {import("./Compiler")} Compiler */ - /** @type {SyncHook<[RuntimeModule, Chunk]>} */ - runtimeModule: new SyncHook(["module", "chunk"]), +class DynamicEntryPlugin { + /** + * @param {string} context the context path + * @param {EntryDynamic} entry the entry value + */ + constructor(context, entry) { + this.context = context; + this.entry = entry; + } - /** @type {SyncHook<[Iterable, any]>} */ - reviveModules: new SyncHook(["modules", "records"]), - /** @type {SyncHook<[Iterable]>} */ - beforeModuleIds: new SyncHook(["modules"]), - /** @type {SyncHook<[Iterable]>} */ - moduleIds: new SyncHook(["modules"]), - /** @type {SyncHook<[Iterable]>} */ - optimizeModuleIds: new SyncHook(["modules"]), - /** @type {SyncHook<[Iterable]>} */ - afterOptimizeModuleIds: new SyncHook(["modules"]), + /** + * 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 + ); + } + ); - /** @type {SyncHook<[Iterable, any]>} */ - reviveChunks: new SyncHook(["chunks", "records"]), - /** @type {SyncHook<[Iterable]>} */ - beforeChunkIds: new SyncHook(["chunks"]), - /** @type {SyncHook<[Iterable]>} */ - chunkIds: new SyncHook(["chunks"]), - /** @type {SyncHook<[Iterable]>} */ - optimizeChunkIds: new SyncHook(["chunks"]), - /** @type {SyncHook<[Iterable]>} */ - afterOptimizeChunkIds: new SyncHook(["chunks"]), + 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 => {}) + ); + } +} - /** @type {SyncHook<[Iterable, any]>} */ - recordModules: new SyncHook(["modules", "records"]), - /** @type {SyncHook<[Iterable, any]>} */ - recordChunks: new SyncHook(["chunks", "records"]), +module.exports = DynamicEntryPlugin; - /** @type {SyncHook<[Iterable]>} */ - optimizeCodeGeneration: new SyncHook(["modules"]), - /** @type {SyncHook<[]>} */ - beforeModuleHash: new SyncHook([]), - /** @type {SyncHook<[]>} */ - afterModuleHash: new SyncHook([]), +/***/ }), - /** @type {SyncHook<[]>} */ - beforeCodeGeneration: new SyncHook([]), - /** @type {SyncHook<[]>} */ - afterCodeGeneration: new SyncHook([]), +/***/ 9909: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {SyncHook<[]>} */ - beforeRuntimeRequirements: new SyncHook([]), - /** @type {SyncHook<[]>} */ - afterRuntimeRequirements: new SyncHook([]), +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {SyncHook<[]>} */ - beforeHash: new SyncHook([]), - /** @type {SyncHook<[Chunk]>} */ - contentHash: new SyncHook(["chunk"]), - /** @type {SyncHook<[]>} */ - afterHash: new SyncHook([]), - /** @type {SyncHook<[any]>} */ - recordHash: new SyncHook(["records"]), - /** @type {SyncHook<[Compilation, any]>} */ - record: new SyncHook(["compilation", "records"]), - /** @type {SyncHook<[]>} */ - beforeModuleAssets: new SyncHook([]), - /** @type {SyncBailHook<[], boolean>} */ - shouldGenerateChunkAssets: new SyncBailHook([]), - /** @type {SyncHook<[]>} */ - beforeChunkAssets: new SyncHook([]), - // TODO webpack 6 remove - /** @deprecated */ - additionalChunkAssets: createProcessAssetsHook( - "additionalChunkAssets", - Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, - () => [this.chunks], - "DEP_WEBPACK_COMPILATION_ADDITIONAL_CHUNK_ASSETS" - ), - // TODO webpack 6 deprecate - /** @deprecated */ - additionalAssets: createProcessAssetsHook( - "additionalAssets", - Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, - () => [] - ), - // TODO webpack 6 remove - /** @deprecated */ - optimizeChunkAssets: createProcessAssetsHook( - "optimizeChunkAssets", - Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE, - () => [this.chunks], - "DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS" - ), - // TODO webpack 6 remove - /** @deprecated */ - afterOptimizeChunkAssets: createProcessAssetsHook( - "afterOptimizeChunkAssets", - Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE + 1, - () => [this.chunks], - "DEP_WEBPACK_COMPILATION_AFTER_OPTIMIZE_CHUNK_ASSETS" - ), - // TODO webpack 6 deprecate - /** @deprecated */ - optimizeAssets: processAssetsHook, - // TODO webpack 6 deprecate - /** @deprecated */ - afterOptimizeAssets: afterProcessAssetsHook, +/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ +/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} Entry */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ - processAssets: processAssetsHook, - afterProcessAssets: afterProcessAssetsHook, - /** @type {AsyncSeriesHook<[CompilationAssets]>} */ - processAdditionalAssets: new AsyncSeriesHook(["assets"]), +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; + }); + } - /** @type {SyncBailHook<[], boolean>} */ - needAdditionalSeal: new SyncBailHook([]), - /** @type {AsyncSeriesHook<[]>} */ - afterSeal: new AsyncSeriesHook([]), + /** + * @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 = __webpack_require__(96475); + new DynamicEntryPlugin(context, entry).apply(compiler); + } else { + const EntryPlugin = __webpack_require__(96953); + 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); + } + } + } + } - /** @type {SyncWaterfallHook<[RenderManifestEntry[], RenderManifestOptions]>} */ - renderManifest: new SyncWaterfallHook(["result", "options"]), + /** + * @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, + publicPath: desc.publicPath, + chunkLoading: desc.chunkLoading, + asyncChunks: desc.asyncChunks, + wasmLoading: desc.wasmLoading, + library: desc.library + }; + if (desc.layer !== undefined && !compiler.options.experiments.layers) { + throw new Error( + "'entryOptions.layer' is only allowed when 'experiments.layers' is enabled" + ); + } + if (desc.chunkLoading) { + const EnableChunkLoadingPlugin = __webpack_require__(61291); + EnableChunkLoadingPlugin.checkEnabled(compiler, desc.chunkLoading); + } + if (desc.wasmLoading) { + const EnableWasmLoadingPlugin = __webpack_require__(78613); + EnableWasmLoadingPlugin.checkEnabled(compiler, desc.wasmLoading); + } + if (desc.library) { + const EnableLibraryPlugin = __webpack_require__(91452); + EnableLibraryPlugin.checkEnabled(compiler, desc.library.type); + } + return options; + } +} - /** @type {SyncHook<[Hash]>} */ - fullHash: new SyncHook(["hash"]), - /** @type {SyncHook<[Chunk, Hash, ChunkHashContext]>} */ - chunkHash: new SyncHook(["chunk", "chunkHash", "ChunkHashContext"]), +module.exports = EntryOptionPlugin; - /** @type {SyncHook<[Module, string]>} */ - moduleAsset: new SyncHook(["module", "filename"]), - /** @type {SyncHook<[Chunk, string]>} */ - chunkAsset: new SyncHook(["chunk", "filename"]), - /** @type {SyncWaterfallHook<[string, object, AssetInfo]>} */ - assetPath: new SyncWaterfallHook(["path", "options", "assetInfo"]), +/***/ }), - /** @type {SyncBailHook<[], boolean>} */ - needAdditionalPass: new SyncBailHook([]), +/***/ 96953: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {SyncHook<[Compiler, string, number]>} */ - childCompiler: new SyncHook([ - "childCompiler", - "compilerName", - "compilerIndex" - ]), +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {SyncBailHook<[string, LogEntry], true>} */ - log: new SyncBailHook(["origin", "logEntry"]), - /** @type {SyncWaterfallHook<[WebpackError[]]>} */ - processWarnings: new SyncWaterfallHook(["warnings"]), - /** @type {SyncWaterfallHook<[WebpackError[]]>} */ - processErrors: new SyncWaterfallHook(["errors"]), - /** @type {HookMap, CreateStatsOptionsContext]>>} */ - statsPreset: new HookMap(() => new SyncHook(["options", "context"])), - /** @type {SyncHook<[Partial, CreateStatsOptionsContext]>} */ - statsNormalize: new SyncHook(["options", "context"]), - /** @type {SyncHook<[StatsFactory, NormalizedStatsOptions]>} */ - statsFactory: new SyncHook(["statsFactory", "options"]), - /** @type {SyncHook<[StatsPrinter, NormalizedStatsOptions]>} */ - statsPrinter: new SyncHook(["statsPrinter", "options"]), +const EntryDependency = __webpack_require__(3979); - get normalModuleLoader() { - return getNormalModuleLoader(); +/** @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 + ); } + ); + + const { entry, options, context } = this; + const dep = EntryPlugin.createDependency(entry, options); + + compiler.hooks.make.tapAsync("EntryPlugin", (compilation, callback) => { + compilation.addEntry(context, dep, options, err => { + callback(err); + }); }); - /** @type {string=} */ - this.name = undefined; - this.startTime = undefined; - this.endTime = undefined; - /** @type {Compiler} */ - this.compiler = compiler; - this.resolverFactory = compiler.resolverFactory; - this.inputFileSystem = compiler.inputFileSystem; - this.fileSystemInfo = new FileSystemInfo(this.inputFileSystem, { - managedPaths: compiler.managedPaths, - immutablePaths: compiler.immutablePaths, - logger: this.getLogger("webpack.FileSystemInfo"), - hashFunction: compiler.options.output.hashFunction - }); - if (compiler.fileTimestamps) { - this.fileSystemInfo.addFileTimestamps(compiler.fileTimestamps, true); - } - if (compiler.contextTimestamps) { - this.fileSystemInfo.addContextTimestamps( - compiler.contextTimestamps, - true - ); - } - /** @type {Map>} */ - this.valueCacheVersions = new Map(); - this.requestShortener = compiler.requestShortener; - this.compilerPath = compiler.compilerPath; + } - this.logger = this.getLogger("webpack.Compilation"); + /** + * @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; + } +} - const options = compiler.options; - this.options = options; - this.outputOptions = options && options.output; - /** @type {boolean} */ - this.bail = (options && options.bail) || false; - /** @type {boolean} */ - this.profile = (options && options.profile) || false; +module.exports = EntryPlugin; - this.params = params; - this.mainTemplate = new MainTemplate(this.outputOptions, this); - this.chunkTemplate = new ChunkTemplate(this.outputOptions, this); - this.runtimeTemplate = new RuntimeTemplate( - this, - this.outputOptions, - this.requestShortener - ); - /** @type {{javascript: ModuleTemplate}} */ - this.moduleTemplates = { - javascript: new ModuleTemplate(this.runtimeTemplate, this) - }; - defineRemovedModuleTemplates(this.moduleTemplates); - /** @type {Map> | undefined} */ - this.moduleMemCaches = undefined; - /** @type {Map> | undefined} */ - this.moduleMemCaches2 = undefined; - this.moduleGraph = new ModuleGraph(); - /** @type {ChunkGraph} */ - this.chunkGraph = undefined; - /** @type {CodeGenerationResults} */ - this.codeGenerationResults = undefined; +/***/ }), - /** @type {AsyncQueue} */ - this.processDependenciesQueue = new AsyncQueue({ - name: "processDependencies", - parallelism: options.parallelism || 100, - processor: this._processModuleDependencies.bind(this) - }); - /** @type {AsyncQueue} */ - this.addModuleQueue = new AsyncQueue({ - name: "addModule", - parent: this.processDependenciesQueue, - getKey: module => module.identifier(), - processor: this._addModule.bind(this) - }); - /** @type {AsyncQueue} */ - this.factorizeQueue = new AsyncQueue({ - name: "factorize", - parent: this.addModuleQueue, - processor: this._factorizeModule.bind(this) - }); - /** @type {AsyncQueue} */ - this.buildQueue = new AsyncQueue({ - name: "build", - parent: this.factorizeQueue, - processor: this._buildModule.bind(this) - }); - /** @type {AsyncQueue} */ - this.rebuildQueue = new AsyncQueue({ - name: "rebuild", - parallelism: options.parallelism || 100, - processor: this._rebuildModule.bind(this) - }); +/***/ 13795: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * Modules in value are building during the build of Module in key. - * Means value blocking key from finishing. - * Needed to detect build cycles. - * @type {WeakMap>} - */ - this.creatingModuleDuringBuild = new WeakMap(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {Map} */ - this.entries = new Map(); - /** @type {EntryData} */ - this.globalEntry = { - dependencies: [], - includeDependencies: [], - options: { - name: undefined - } - }; - /** @type {Map} */ - this.entrypoints = new Map(); - /** @type {Entrypoint[]} */ - this.asyncEntrypoints = []; - /** @type {Set} */ - this.chunks = new Set(); - /** @type {ChunkGroup[]} */ - this.chunkGroups = []; - /** @type {Map} */ - this.namedChunkGroups = new Map(); - /** @type {Map} */ - this.namedChunks = new Map(); - /** @type {Set} */ - this.modules = new Set(); - if (this._backCompat) { - arrayToSetDeprecation(this.chunks, "Compilation.chunks"); - arrayToSetDeprecation(this.modules, "Compilation.modules"); - } - /** @private @type {Map} */ - this._modules = new Map(); - this.records = null; - /** @type {string[]} */ - this.additionalChunkAssets = []; - /** @type {CompilationAssets} */ - this.assets = {}; - /** @type {Map} */ - this.assetsInfo = new Map(); - /** @type {Map>>} */ - this._assetsRelatedIn = new Map(); - /** @type {WebpackError[]} */ - this.errors = []; - /** @type {WebpackError[]} */ - this.warnings = []; - /** @type {Compilation[]} */ - this.children = []; - /** @type {Map} */ - this.logging = new Map(); - /** @type {Map} */ - this.dependencyFactories = new Map(); - /** @type {DependencyTemplates} */ - this.dependencyTemplates = new DependencyTemplates( - this.outputOptions.hashFunction - ); - this.childrenCounters = {}; - /** @type {Set} */ - this.usedChunkIds = null; - /** @type {Set} */ - this.usedModuleIds = null; - /** @type {boolean} */ - this.needAdditionalPass = false; - /** @type {Set} */ - this._restoredUnsafeCacheModuleEntries = new Set(); - /** @type {Map} */ - this._restoredUnsafeCacheEntries = new Map(); - /** @type {WeakSet} */ - this.builtModules = new WeakSet(); - /** @type {WeakSet} */ - this.codeGeneratedModules = new WeakSet(); - /** @type {WeakSet} */ - this.buildTimeExecutedModules = new WeakSet(); - /** @private @type {Map} */ - this._rebuildingModules = new Map(); - /** @type {Set} */ - this.emittedAssets = new Set(); - /** @type {Set} */ - this.comparedForEmitAssets = new Set(); - /** @type {LazySet} */ - this.fileDependencies = new LazySet(); - /** @type {LazySet} */ - this.contextDependencies = new LazySet(); - /** @type {LazySet} */ - this.missingDependencies = new LazySet(); - /** @type {LazySet} */ - this.buildDependencies = new LazySet(); - // TODO webpack 6 remove - this.compilationDependencies = { - add: util.deprecate( - item => this.fileDependencies.add(item), - "Compilation.compilationDependencies is deprecated (used Compilation.fileDependencies instead)", - "DEP_WEBPACK_COMPILATION_COMPILATION_DEPENDENCIES" - ) - }; - this._modulesCache = this.getCache("Compilation/modules"); - this._assetsCache = this.getCache("Compilation/assets"); - this._codeGenerationCache = this.getCache("Compilation/codeGeneration"); - const unsafeCache = options.module.unsafeCache; - this._unsafeCache = !!unsafeCache; - this._unsafeCachePredicate = - typeof unsafeCache === "function" ? unsafeCache : () => true; - } +const ChunkGroup = __webpack_require__(15626); - getStats() { - return new Stats(this); - } +/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ +/** @typedef {import("./Chunk")} Chunk */ + +/** @typedef {{ name?: string } & Omit} 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 { /** - * @param {StatsOptions | string} optionsOrPreset stats option value - * @param {CreateStatsOptionsContext} context context - * @returns {NormalizedStatsOptions} normalized options + * 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 */ - createStatsOptions(optionsOrPreset, context = {}) { - if ( - typeof optionsOrPreset === "boolean" || - typeof optionsOrPreset === "string" - ) { - optionsOrPreset = { preset: optionsOrPreset }; - } - if (typeof optionsOrPreset === "object" && optionsOrPreset !== null) { - // We use this method of shallow cloning this object to include - // properties in the prototype chain - /** @type {Partial} */ - const options = {}; - for (const key in optionsOrPreset) { - options[key] = optionsOrPreset[key]; - } - if (options.preset !== undefined) { - this.hooks.statsPreset.for(options.preset).call(options, context); - } - this.hooks.statsNormalize.call(options, context); - return /** @type {NormalizedStatsOptions} */ (options); - } else { - /** @type {Partial} */ - const options = {}; - this.hooks.statsNormalize.call(options, context); - return /** @type {NormalizedStatsOptions} */ (options); + 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; } - createStatsFactory(options) { - const statsFactory = new StatsFactory(); - this.hooks.statsFactory.call(statsFactory, options); - return statsFactory; + /** + * @returns {boolean} true, when this chunk group will be loaded on initial page load + */ + isInitial() { + return this._initial; } - createStatsPrinter(options) { - const statsPrinter = new StatsPrinter(); - this.hooks.statsPrinter.call(statsPrinter, options); - return statsPrinter; + /** + * Sets the runtimeChunk for an entrypoint. + * @param {Chunk} chunk the chunk being set as the runtime chunk. + * @returns {void} + */ + setRuntimeChunk(chunk) { + this._runtimeChunk = chunk; } /** - * @param {string} name cache name - * @returns {CacheFacade} the cache facade instance + * Fetches the chunk reference containing the webpack bootstrap code + * @returns {Chunk | null} returns the runtime chunk or null if there is none */ - getCache(name) { - return this.compiler.getCache(name); + getRuntimeChunk() { + if (this._runtimeChunk) return this._runtimeChunk; + for (const parent of this.parentsIterable) { + if (parent instanceof Entrypoint) return parent.getRuntimeChunk(); + } + return null; } /** - * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name - * @returns {Logger} a logger with that name + * Sets the chunk with the entrypoint modules for an entrypoint. + * @param {Chunk} chunk the chunk being set as the entrypoint chunk. + * @returns {void} */ - getLogger(name) { - if (!name) { - throw new TypeError("Compilation.getLogger(name) called without a name"); - } - /** @type {LogEntry[] | undefined} */ - let logEntries; - return new Logger( - (type, args) => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compilation.getLogger(name) called with a function not returning a name" - ); - } - } - let trace; - switch (type) { - case LogType.warn: - case LogType.error: - case LogType.trace: - trace = ErrorHelpers.cutOffLoaderExecution(new Error("Trace").stack) - .split("\n") - .slice(3); - break; - } - /** @type {LogEntry} */ - const logEntry = { - time: Date.now(), - type, - args, - trace - }; - if (this.hooks.log.call(name, logEntry) === undefined) { - if (logEntry.type === LogType.profileEnd) { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.profileEnd === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.profileEnd(`[${name}] ${logEntry.args[0]}`); - } - } - if (logEntries === undefined) { - logEntries = this.logging.get(name); - if (logEntries === undefined) { - logEntries = []; - this.logging.set(name, logEntries); - } - } - logEntries.push(logEntry); - if (logEntry.type === LogType.profile) { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.profile === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.profile(`[${name}] ${logEntry.args[0]}`); - } - } - } - }, - childName => { - if (typeof name === "function") { - if (typeof childName === "function") { - return this.getLogger(() => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compilation.getLogger(name) called with a function not returning a name" - ); - } - } - if (typeof childName === "function") { - childName = childName(); - if (!childName) { - throw new TypeError( - "Logger.getChildLogger(name) called with a function not returning a name" - ); - } - } - return `${name}/${childName}`; - }); - } else { - return this.getLogger(() => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compilation.getLogger(name) called with a function not returning a name" - ); - } - } - return `${name}/${childName}`; - }); - } - } else { - if (typeof childName === "function") { - return this.getLogger(() => { - if (typeof childName === "function") { - childName = childName(); - if (!childName) { - throw new TypeError( - "Logger.getChildLogger(name) called with a function not returning a name" - ); - } - } - return `${name}/${childName}`; - }); - } else { - return this.getLogger(`${name}/${childName}`); - } - } - } - ); + setEntrypointChunk(chunk) { + this._entrypointChunk = chunk; } /** - * @param {Module} module module to be added that was created - * @param {ModuleCallback} callback returns the module in the compilation, - * it could be the passed one (if new), or an already existing in the compilation - * @returns {void} + * Returns the chunk which contains the entrypoint modules + * (or at least the execution of them) + * @returns {Chunk} chunk */ - addModule(module, callback) { - this.addModuleQueue.add(module, callback); + getEntrypointChunk() { + return this._entrypointChunk; } /** - * @param {Module} module module to be added that was created - * @param {ModuleCallback} callback returns the module in the compilation, - * it could be the passed one (if new), or an already existing in the compilation - * @returns {void} + * @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 */ - _addModule(module, callback) { - const identifier = module.identifier(); - const alreadyAddedModule = this._modules.get(identifier); - if (alreadyAddedModule) { - return callback(null, alreadyAddedModule); - } - - const currentProfile = this.profile - ? this.moduleGraph.getProfile(module) - : undefined; - if (currentProfile !== undefined) { - currentProfile.markRestoringStart(); - } - - this._modulesCache.get(identifier, null, (err, cacheModule) => { - if (err) return callback(new ModuleRestoreError(module, err)); + replaceChunk(oldChunk, newChunk) { + if (this._runtimeChunk === oldChunk) this._runtimeChunk = newChunk; + if (this._entrypointChunk === oldChunk) this._entrypointChunk = newChunk; + return super.replaceChunk(oldChunk, newChunk); + } +} - if (currentProfile !== undefined) { - currentProfile.markRestoringEnd(); - currentProfile.markIntegrationStart(); - } +module.exports = Entrypoint; - if (cacheModule) { - cacheModule.updateCacheModule(module); - module = cacheModule; - } - this._modules.set(identifier, module); - this.modules.add(module); - if (this._backCompat) - ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); - if (currentProfile !== undefined) { - currentProfile.markIntegrationEnd(); - } - callback(null, module); - }); - } +/***/ }), - /** - * Fetches a module from a compilation by its identifier - * @param {Module} module the module provided - * @returns {Module} the module requested - */ - getModule(module) { - const identifier = module.identifier(); - return this._modules.get(identifier); - } +/***/ 22070: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * Attempts to search for a module by its identifier - * @param {string} identifier identifier (usually path) for module - * @returns {Module|undefined} attempt to search for module and return it, else undefined - */ - findModule(identifier) { - return this._modules.get(identifier); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Authors Simen Brekken @simenbrekken, Einar Löve @einarlove +*/ - /** - * Schedules a build of the module object - * - * @param {Module} module module to be built - * @param {ModuleCallback} callback the callback - * @returns {void} - */ - buildModule(module, callback) { - this.buildQueue.add(module, callback); - } - /** - * Builds the module object - * - * @param {Module} module module to be built - * @param {ModuleCallback} callback the callback - * @returns {void} - */ - _buildModule(module, callback) { - const currentProfile = this.profile - ? this.moduleGraph.getProfile(module) - : undefined; - if (currentProfile !== undefined) { - currentProfile.markBuildingStart(); - } - module.needBuild( - { - compilation: this, - fileSystemInfo: this.fileSystemInfo, - valueCacheVersions: this.valueCacheVersions - }, - (err, needBuild) => { - if (err) return callback(err); +const DefinePlugin = __webpack_require__(79065); +const WebpackError = __webpack_require__(53799); - if (!needBuild) { - if (currentProfile !== undefined) { - currentProfile.markBuildingEnd(); - } - this.hooks.stillValidModule.call(module); - return callback(); - } +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./DefinePlugin").CodeValue} CodeValue */ - this.hooks.buildModule.call(module); - this.builtModules.add(module); - module.build( - this.options, - this, - this.resolverFactory.get("normal", module.resolveOptions), - this.inputFileSystem, - err => { - if (currentProfile !== undefined) { - currentProfile.markBuildingEnd(); - } - if (err) { - this.hooks.failedModule.call(module, err); - return callback(err); - } - if (currentProfile !== undefined) { - currentProfile.markStoringStart(); - } - this._modulesCache.store(module.identifier(), null, module, err => { - if (currentProfile !== undefined) { - currentProfile.markStoringEnd(); - } - if (err) { - this.hooks.failedModule.call(module, err); - return callback(new ModuleStoreError(module, err)); - } - this.hooks.succeedModule.call(module); - return callback(); - }); - } - ); - } - ); +class EnvironmentPlugin { + constructor(...keys) { + if (keys.length === 1 && Array.isArray(keys[0])) { + this.keys = keys[0]; + this.defaultValues = {}; + } else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") { + this.keys = Object.keys(keys[0]); + this.defaultValues = keys[0]; + } else { + this.keys = keys; + this.defaultValues = {}; + } } /** - * @param {Module} module to be processed for deps - * @param {ModuleCallback} callback callback to be triggered + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - processModuleDependencies(module, callback) { - this.processDependenciesQueue.add(module, callback); - } + apply(compiler) { + /** @type {Record} */ + const definitions = {}; + for (const key of this.keys) { + const value = + process.env[key] !== undefined + ? process.env[key] + : this.defaultValues[key]; - /** - * @param {Module} module to be processed for deps - * @returns {void} - */ - processModuleDependenciesNonRecursive(module) { - const processDependenciesBlock = block => { - if (block.dependencies) { - let i = 0; - for (const dep of block.dependencies) { - this.moduleGraph.setParents(dep, block, module, i++); - } - } - if (block.blocks) { - for (const b of block.blocks) processDependenciesBlock(b); + 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); + }); } - }; - processDependenciesBlock(module); + definitions[`process.env.${key}`] = + value === undefined ? "undefined" : JSON.stringify(value); + } + + new DefinePlugin(definitions).apply(compiler); } +} - /** - * @param {Module} module to be processed for deps - * @param {ModuleCallback} callback callback to be triggered - * @returns {void} - */ - _processModuleDependencies(module, callback) { - /** @type {Array<{factory: ModuleFactory, dependencies: Dependency[], originModule: Module|null}>} */ - const sortedDependencies = []; +module.exports = EnvironmentPlugin; - /** @type {DependenciesBlock} */ - let currentBlock; - /** @type {Map>} */ - let dependencies; - /** @type {DepConstructor} */ - let factoryCacheKey; - /** @type {ModuleFactory} */ - let factoryCacheKey2; - /** @type {Map} */ - let factoryCacheValue; - /** @type {string} */ - let listCacheKey1; - /** @type {string} */ - let listCacheKey2; - /** @type {Dependency[]} */ - let listCacheValue; +/***/ }), - let inProgressSorting = 1; - let inProgressTransitive = 1; +/***/ 59985: +/***/ (function(__unused_webpack_module, exports) { - const onDependenciesSorted = err => { - if (err) return callback(err); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // early exit without changing parallelism back and forth - if (sortedDependencies.length === 0 && inProgressTransitive === 1) { - return callback(); - } - // This is nested so we need to allow one additional task - this.processDependenciesQueue.increaseParallelism(); - for (const item of sortedDependencies) { - inProgressTransitive++; - this.handleModuleCreation(item, err => { - // In V8, the Error objects keep a reference to the functions on the stack. These warnings & - // errors are created inside closures that keep a reference to the Compilation, so errors are - // leaking the Compilation object. - if (err && this.bail) { - if (inProgressTransitive <= 0) return; - inProgressTransitive = -1; - // eslint-disable-next-line no-self-assign - err.stack = err.stack; - onTransitiveTasksFinished(err); - return; - } - if (--inProgressTransitive === 0) onTransitiveTasksFinished(); - }); - } - if (--inProgressTransitive === 0) onTransitiveTasksFinished(); - }; +const loaderFlag = "LOADER_EXECUTION"; - const onTransitiveTasksFinished = err => { - if (err) return callback(err); - this.processDependenciesQueue.decreaseParallelism(); +const webpackOptionsFlag = "WEBPACK_OPTIONS"; - return callback(); - }; +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"); +}; - /** - * @param {Dependency} dep dependency - * @param {number} index index in block - * @returns {void} - */ - const processDependency = (dep, index) => { - this.moduleGraph.setParents(dep, currentBlock, module, index); - if (this._unsafeCache) { - try { - const unsafeCachedModule = unsafeCacheDependencies.get(dep); - if (unsafeCachedModule === null) return; - if (unsafeCachedModule !== undefined) { - if ( - this._restoredUnsafeCacheModuleEntries.has(unsafeCachedModule) - ) { - this._handleExistingModuleFromUnsafeCache( - module, - dep, - unsafeCachedModule - ); - return; - } - const identifier = unsafeCachedModule.identifier(); - const cachedModule = - this._restoredUnsafeCacheEntries.get(identifier); - if (cachedModule !== undefined) { - // update unsafe cache to new module - unsafeCacheDependencies.set(dep, cachedModule); - this._handleExistingModuleFromUnsafeCache( - module, - dep, - cachedModule - ); - return; - } - inProgressSorting++; - this._modulesCache.get(identifier, null, (err, cachedModule) => { - if (err) { - if (inProgressSorting <= 0) return; - inProgressSorting = -1; - onDependenciesSorted(err); - return; - } - try { - if (!this._restoredUnsafeCacheEntries.has(identifier)) { - const data = unsafeCacheData.get(cachedModule); - if (data === undefined) { - processDependencyForResolving(dep); - if (--inProgressSorting === 0) onDependenciesSorted(); - return; - } - if (cachedModule !== unsafeCachedModule) { - unsafeCacheDependencies.set(dep, cachedModule); - } - cachedModule.restoreFromUnsafeCache( - data, - this.params.normalModuleFactory, - this.params - ); - this._restoredUnsafeCacheEntries.set( - identifier, - cachedModule - ); - this._restoredUnsafeCacheModuleEntries.add(cachedModule); - if (!this.modules.has(cachedModule)) { - inProgressTransitive++; - this._handleNewModuleFromUnsafeCache( - module, - dep, - cachedModule, - err => { - if (err) { - if (inProgressTransitive <= 0) return; - inProgressTransitive = -1; - onTransitiveTasksFinished(err); - } - if (--inProgressTransitive === 0) - return onTransitiveTasksFinished(); - } - ); - if (--inProgressSorting === 0) onDependenciesSorted(); - return; - } - } - if (unsafeCachedModule !== cachedModule) { - unsafeCacheDependencies.set(dep, cachedModule); - } - this._handleExistingModuleFromUnsafeCache( - module, - dep, - cachedModule - ); // a3 - } catch (err) { - if (inProgressSorting <= 0) return; - inProgressSorting = -1; - onDependenciesSorted(err); - return; - } - if (--inProgressSorting === 0) onDependenciesSorted(); - }); - return; - } - } catch (e) { - console.error(e); - } - } - processDependencyForResolving(dep); - }; +exports.cutOffLoaderExecution = stack => + exports.cutOffByFlag(stack, loaderFlag); - /** - * @param {Dependency} dep dependency - * @returns {void} - */ - const processDependencyForResolving = dep => { - const resourceIdent = dep.getResourceIdentifier(); - if (resourceIdent !== undefined && resourceIdent !== null) { - const category = dep.category; - const constructor = /** @type {DepConstructor} */ (dep.constructor); - if (factoryCacheKey === constructor) { - // Fast path 1: same constructor as prev item - if (listCacheKey1 === category && listCacheKey2 === resourceIdent) { - // Super fast path 1: also same resource - listCacheValue.push(dep); - return; - } - } else { - const factory = this.dependencyFactories.get(constructor); - if (factory === undefined) { - throw new Error( - `No module factory available for dependency type: ${constructor.name}` - ); - } - if (factoryCacheKey2 === factory) { - // Fast path 2: same factory as prev item - factoryCacheKey = constructor; - if (listCacheKey1 === category && listCacheKey2 === resourceIdent) { - // Super fast path 2: also same resource - listCacheValue.push(dep); - return; - } - } else { - // Slow path - if (factoryCacheKey2 !== undefined) { - // Archive last cache entry - if (dependencies === undefined) dependencies = new Map(); - dependencies.set(factoryCacheKey2, factoryCacheValue); - factoryCacheValue = dependencies.get(factory); - if (factoryCacheValue === undefined) { - factoryCacheValue = new Map(); - } - } else { - factoryCacheValue = new Map(); - } - factoryCacheKey = constructor; - factoryCacheKey2 = factory; - } - } - // Here webpack is using heuristic that assumes - // mostly esm dependencies would be used - // so we don't allocate extra string for them - const cacheKey = - category === esmDependencyCategory - ? resourceIdent - : `${category}${resourceIdent}`; - let list = factoryCacheValue.get(cacheKey); - if (list === undefined) { - factoryCacheValue.set(cacheKey, (list = [])); - sortedDependencies.push({ - factory: factoryCacheKey2, - dependencies: list, - originModule: module - }); - } - list.push(dep); - listCacheKey1 = category; - listCacheKey2 = resourceIdent; - listCacheValue = list; - } - }; +exports.cutOffWebpackOptions = stack => + exports.cutOffByFlag(stack, webpackOptionsFlag); - try { - /** @type {DependenciesBlock[]} */ - const queue = [module]; - do { - const block = queue.pop(); - if (block.dependencies) { - currentBlock = block; - let i = 0; - for (const dep of block.dependencies) processDependency(dep, i++); - } - if (block.blocks) { - for (const b of block.blocks) queue.push(b); - } - } while (queue.length !== 0); - } catch (e) { - return callback(e); - } +exports.cutOffMultilineMessage = (stack, message) => { + stack = stack.split("\n"); + message = message.split("\n"); - if (--inProgressSorting === 0) onDependenciesSorted(); - } + const result = []; - _handleNewModuleFromUnsafeCache(originModule, dependency, module, callback) { - const moduleGraph = this.moduleGraph; + stack.forEach((line, idx) => { + if (!line.includes(message[idx])) result.push(line); + }); - moduleGraph.setResolvedModule(originModule, dependency, module); + return result.join("\n"); +}; - moduleGraph.setIssuerIfUnset( - module, - originModule !== undefined ? originModule : null - ); +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; + } +}; - this._modules.set(module.identifier(), module); - this.modules.add(module); - if (this._backCompat) - ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); +exports.cleanUp = (stack, message) => { + stack = exports.cutOffLoaderExecution(stack); + stack = exports.cutOffMessage(stack, message); + return stack; +}; - this._handleModuleBuildAndDependencies( - originModule, - module, - true, - callback - ); - } +exports.cleanUpWebpackOptions = (stack, message) => { + stack = exports.cutOffWebpackOptions(stack); + stack = exports.cutOffMultilineMessage(stack, message); + return stack; +}; - _handleExistingModuleFromUnsafeCache(originModule, dependency, module) { - const moduleGraph = this.moduleGraph; - moduleGraph.setResolvedModule(originModule, dependency, module); - } +/***/ }), - /** - * @typedef {Object} HandleModuleCreationOptions - * @property {ModuleFactory} factory - * @property {Dependency[]} dependencies - * @property {Module | null} originModule - * @property {Partial=} contextInfo - * @property {string=} context - * @property {boolean=} recursive recurse into dependencies of the created module - * @property {boolean=} connectOrigin connect the resolved module with the origin module - */ +/***/ 65218: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @param {HandleModuleCreationOptions} options options object - * @param {ModuleCallback} callback callback - * @returns {void} - */ - handleModuleCreation( - { - factory, - dependencies, - originModule, - contextInfo, - context, - recursive = true, - connectOrigin = recursive - }, - callback - ) { - const moduleGraph = this.moduleGraph; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const currentProfile = this.profile ? new ModuleProfile() : undefined; - this.factorizeModule( - { - currentProfile, - factory, - dependencies, - factoryResult: true, - originModule, - contextInfo, - context - }, - (err, factoryResult) => { - const applyFactoryResultDependencies = () => { - const { fileDependencies, contextDependencies, missingDependencies } = - factoryResult; - if (fileDependencies) { - this.fileDependencies.addAll(fileDependencies); - } - if (contextDependencies) { - this.contextDependencies.addAll(contextDependencies); - } - if (missingDependencies) { - this.missingDependencies.addAll(missingDependencies); - } - }; - if (err) { - if (factoryResult) applyFactoryResultDependencies(); - if (dependencies.every(d => d.optional)) { - this.warnings.push(err); - return callback(); - } else { - this.errors.push(err); - return callback(err); - } - } - const newModule = factoryResult.module; +const { ConcatSource, RawSource } = __webpack_require__(51255); +const ExternalModule = __webpack_require__(73071); +const ModuleFilenameHelpers = __webpack_require__(88821); +const RuntimeGlobals = __webpack_require__(16475); +const JavascriptModulesPlugin = __webpack_require__(89464); - if (!newModule) { - applyFactoryResultDependencies(); - return callback(); - } +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Compiler")} Compiler */ - if (currentProfile !== undefined) { - moduleGraph.setProfile(newModule, currentProfile); - } +/** @type {WeakMap} */ +const cache = new WeakMap(); - this.addModule(newModule, (err, module) => { - if (err) { - applyFactoryResultDependencies(); - if (!err.module) { - err.module = module; - } - this.errors.push(err); +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/). + */ +`); - return callback(err); - } +class EvalDevToolModulePlugin { + constructor(options) { + this.namespace = options.namespace || ""; + this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]"; + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || + "webpack://[namespace]/[resourcePath]?[loaders]"; + } - if ( - this._unsafeCache && - factoryResult.cacheable !== false && - /** @type {any} */ (module).restoreFromUnsafeCache && - this._unsafeCachePredicate(module) - ) { - const unsafeCacheableModule = - /** @type {Module & { restoreFromUnsafeCache: Function }} */ ( - module - ); - for (let i = 0; i < dependencies.length; i++) { - const dependency = dependencies[i]; - moduleGraph.setResolvedModule( - connectOrigin ? originModule : null, - dependency, - unsafeCacheableModule - ); - unsafeCacheDependencies.set(dependency, unsafeCacheableModule); - } - if (!unsafeCacheData.has(unsafeCacheableModule)) { - unsafeCacheData.set( - unsafeCacheableModule, - unsafeCacheableModule.getUnsafeCacheData() - ); - } - } else { - applyFactoryResultDependencies(); - for (let i = 0; i < dependencies.length; i++) { - const dependency = dependencies[i]; - moduleGraph.setResolvedModule( - connectOrigin ? originModule : null, - dependency, - module - ); - } + /** + * 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; } - - moduleGraph.setIssuerIfUnset( + const content = source.source(); + const str = ModuleFilenameHelpers.createFilename( module, - originModule !== undefined ? originModule : null - ); - if (module !== newModule) { - if (currentProfile !== undefined) { - const otherProfile = moduleGraph.getProfile(module); - if (otherProfile !== undefined) { - currentProfile.mergeInto(otherProfile); - } else { - moduleGraph.setProfile(module, currentProfile); - } + { + moduleFilenameTemplate: this.moduleFilenameTemplate, + namespace: this.namespace + }, + { + requestShortener: runtimeTemplate.requestShortener, + chunkGraph, + hashFunction: compilation.outputOptions.hashFunction } - } - - this._handleModuleBuildAndDependencies( - originModule, - module, - recursive, - callback ); - }); + const footer = + "\n" + + this.sourceUrlComment.replace( + /\[url\]/g, + encodeURI(str) + .replace(/%2F/g, "/") + .replace(/%20/g, "_") + .replace(/%5E/g, "^") + .replace(/%5C/g, "\\") + .replace(/^\//, "") + ); + const result = new RawSource( + `eval(${ + compilation.outputOptions.trustedTypes + ? `${RuntimeGlobals.createScript}(${JSON.stringify( + content + footer + )})` + : JSON.stringify(content + footer) + });` + ); + cache.set(source, result); + return result; + } + ); + hooks.inlineInRuntimeBailout.tap( + "EvalDevToolModulePlugin", + () => "the eval devtool is used." + ); + hooks.render.tap( + "EvalDevToolModulePlugin", + source => new ConcatSource(devtoolWarning, source) + ); + hooks.chunkHash.tap("EvalDevToolModulePlugin", (chunk, hash) => { + hash.update("EvalDevToolModulePlugin"); + hash.update("2"); + }); + if (compilation.outputOptions.trustedTypes) { + compilation.hooks.additionalModuleRuntimeRequirements.tap( + "EvalDevToolModulePlugin", + (module, set, context) => { + set.add(RuntimeGlobals.createScript); + } + ); } - ); + }); } +} - _handleModuleBuildAndDependencies(originModule, module, recursive, callback) { - // Check for cycles when build is trigger inside another build - let creatingModuleDuringBuildSet = undefined; - if (!recursive && this.buildQueue.isProcessing(originModule)) { - // Track build dependency - creatingModuleDuringBuildSet = - this.creatingModuleDuringBuild.get(originModule); - if (creatingModuleDuringBuildSet === undefined) { - creatingModuleDuringBuildSet = new Set(); - this.creatingModuleDuringBuild.set( - originModule, - creatingModuleDuringBuildSet - ); - } - creatingModuleDuringBuildSet.add(module); +module.exports = EvalDevToolModulePlugin; - // When building is blocked by another module - // search for a cycle, cancel the cycle by throwing - // an error (otherwise this would deadlock) - const blockReasons = this.creatingModuleDuringBuild.get(module); - if (blockReasons !== undefined) { - const set = new Set(blockReasons); - for (const item of set) { - const blockReasons = this.creatingModuleDuringBuild.get(item); - if (blockReasons !== undefined) { - for (const m of blockReasons) { - if (m === module) { - return callback(new BuildCycleError(module)); - } - set.add(m); - } - } - } - } - } - this.buildModule(module, err => { - if (creatingModuleDuringBuildSet !== undefined) { - creatingModuleDuringBuildSet.delete(module); - } - if (err) { - if (!err.module) { - err.module = module; - } - this.errors.push(err); +/***/ }), - return callback(err); - } +/***/ 14790: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (!recursive) { - this.processModuleDependenciesNonRecursive(module); - callback(null, module); - return; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // This avoids deadlocks for circular dependencies - if (this.processDependenciesQueue.isProcessing(module)) { - return callback(); - } - this.processModuleDependencies(module, err => { - if (err) { - return callback(err); - } - callback(null, module); - }); - }); + +const { ConcatSource, RawSource } = __webpack_require__(51255); +const ModuleFilenameHelpers = __webpack_require__(88821); +const NormalModule = __webpack_require__(39); +const RuntimeGlobals = __webpack_require__(16475); +const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(97513); +const JavascriptModulesPlugin = __webpack_require__(89464); +const ConcatenatedModule = __webpack_require__(97198); +const { makePathsAbsolute } = __webpack_require__(82186); + +/** @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} */ +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; } /** - * @param {FactorizeModuleOptions} options options object - * @param {ModuleOrFactoryResultCallback} callback callback + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - _factorizeModule( - { - currentProfile, - factory, - dependencies, - originModule, - factoryResult, - contextInfo, - context - }, - callback - ) { - if (currentProfile !== undefined) { - currentProfile.markFactoryStart(); - } - factory.create( - { - contextInfo: { - issuer: originModule ? originModule.nameForCondition() : "", - issuerLayer: originModule ? originModule.layer : null, - compiler: this.compiler.name, - ...contextInfo - }, - resolveOptions: originModule ? originModule.resolveOptions : undefined, - context: context - ? context - : originModule - ? originModule.context - : this.compiler.context, - dependencies: dependencies - }, - (err, result) => { - if (result) { - // TODO webpack 6: remove - // For backward-compat - if (result.module === undefined && result instanceof Module) { - result = { - module: result + 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 (!factoryResult) { - const { - fileDependencies, - contextDependencies, - missingDependencies - } = result; - if (fileDependencies) { - this.fileDependencies.addAll(fileDependencies); + + 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); } - if (contextDependencies) { - this.contextDependencies.addAll(contextDependencies); + + /** @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 (missingDependencies) { - this.missingDependencies.addAll(missingDependencies); + 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 = makePathsAbsolute(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, + hashFunction: compilation.outputOptions.hashFunction + } + ); + }); + 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(${ + compilation.outputOptions.trustedTypes + ? `${RuntimeGlobals.createScript}(${JSON.stringify( + content + footer + )})` + : JSON.stringify(content + footer) + });` + ) + ); } - } - if (err) { - const notFoundError = new ModuleNotFoundError( - originModule, - err, - dependencies.map(d => d.loc).filter(Boolean)[0] + ); + hooks.inlineInRuntimeBailout.tap( + "EvalDevToolModulePlugin", + () => "the eval-source-map devtool is used." + ); + hooks.render.tap( + "EvalSourceMapDevToolPlugin", + source => new ConcatSource(devtoolWarning, source) + ); + hooks.chunkHash.tap("EvalSourceMapDevToolPlugin", (chunk, hash) => { + hash.update("EvalSourceMapDevToolPlugin"); + hash.update("2"); + }); + if (compilation.outputOptions.trustedTypes) { + compilation.hooks.additionalModuleRuntimeRequirements.tap( + "EvalSourceMapDevToolPlugin", + (module, set, context) => { + set.add(RuntimeGlobals.createScript); + } ); - return callback(notFoundError, factoryResult ? result : undefined); - } - if (!result) { - return callback(); - } - - if (currentProfile !== undefined) { - currentProfile.markFactoryEnd(); } - - callback(null, factoryResult ? result : result.module); } ); } +} + +module.exports = EvalSourceMapDevToolPlugin; + + +/***/ }), + +/***/ 63686: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { equals } = __webpack_require__(84953); +const SortableSet = __webpack_require__(13098); +const makeSerializable = __webpack_require__(33032); +const { forEachRuntime } = __webpack_require__(17156); + +/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("./util/Hash")} Hash */ + +/** @typedef {typeof UsageState.OnlyPropertiesUsed | typeof UsageState.NoInfo | typeof UsageState.Unknown | typeof UsageState.Used} RuntimeUsageStateType */ +/** @typedef {typeof UsageState.Unused | RuntimeUsageStateType} UsageStateType */ + +const UsageState = Object.freeze({ + Unused: /** @type {0} */ (0), + OnlyPropertiesUsed: /** @type {1} */ (1), + NoInfo: /** @type {2} */ (2), + Unknown: /** @type {3} */ (3), + Used: /** @type {4} */ (4) +}); + +const RETURNS_TRUE = () => true; + +const CIRCULAR = Symbol("circular target"); + +class RestoreProvidedData { + constructor( + exports, + otherProvided, + otherCanMangleProvide, + otherTerminalBinding + ) { + this.exports = exports; + this.otherProvided = otherProvided; + this.otherCanMangleProvide = otherCanMangleProvide; + this.otherTerminalBinding = otherTerminalBinding; + } + + serialize({ write }) { + write(this.exports); + write(this.otherProvided); + write(this.otherCanMangleProvide); + write(this.otherTerminalBinding); + } + + static deserialize({ read }) { + return new RestoreProvidedData(read(), read(), read(), read()); + } +} + +makeSerializable( + RestoreProvidedData, + "webpack/lib/ModuleGraph", + "RestoreProvidedData" +); + +class ExportsInfo { + constructor() { + /** @type {Map} */ + this._exports = new Map(); + this._otherExportsInfo = new ExportInfo(null); + this._sideEffectsOnlyInfo = new ExportInfo("*side effects only*"); + this._exportsAreOrdered = false; + /** @type {ExportsInfo=} */ + this._redirectTo = undefined; + } /** - * @param {string} context context string path - * @param {Dependency} dependency dependency used to create Module chain - * @param {ModuleCallback} callback callback for when module chain is complete - * @returns {void} will throw if dependency instance is not a valid Dependency + * @returns {Iterable} all owned exports in any order */ - addModuleChain(context, dependency, callback) { - return this.addModuleTree({ context, dependency }, callback); + get ownedExports() { + return this._exports.values(); } /** - * @param {Object} options options - * @param {string} options.context context string path - * @param {Dependency} options.dependency dependency used to create Module chain - * @param {Partial=} options.contextInfo additional context info for the root module - * @param {ModuleCallback} callback callback for when module chain is complete - * @returns {void} will throw if dependency instance is not a valid Dependency + * @returns {Iterable} all owned exports in order */ - addModuleTree({ context, dependency, contextInfo }, callback) { - if ( - typeof dependency !== "object" || - dependency === null || - !dependency.constructor - ) { - return callback( - new WebpackError("Parameter 'dependency' must be a Dependency") - ); - } - const Dep = /** @type {DepConstructor} */ (dependency.constructor); - const moduleFactory = this.dependencyFactories.get(Dep); - if (!moduleFactory) { - return callback( - new WebpackError( - `No dependency factory available for this dependency type: ${dependency.constructor.name}` - ) - ); + get orderedOwnedExports() { + if (!this._exportsAreOrdered) { + this._sortExports(); } - - this.handleModuleCreation( - { - factory: moduleFactory, - dependencies: [dependency], - originModule: null, - contextInfo, - context - }, - (err, result) => { - if (err && this.bail) { - callback(err); - this.buildQueue.stop(); - this.rebuildQueue.stop(); - this.processDependenciesQueue.stop(); - this.factorizeQueue.stop(); - } else if (!err && result) { - callback(null, result); - } else { - callback(); - } - } - ); + return this._exports.values(); } /** - * @param {string} context context path for entry - * @param {Dependency} entry entry dependency that should be followed - * @param {string | EntryOptions} optionsOrName options or deprecated name of entry - * @param {ModuleCallback} callback callback function - * @returns {void} returns + * @returns {Iterable} all exports in any order */ - addEntry(context, entry, optionsOrName, callback) { - // TODO webpack 6 remove - const options = - typeof optionsOrName === "object" - ? optionsOrName - : { name: optionsOrName }; - - this._addEntryItem(context, entry, "dependencies", options, callback); + get exports() { + if (this._redirectTo !== undefined) { + const map = new Map(this._redirectTo._exports); + for (const [key, value] of this._exports) { + map.set(key, value); + } + return map.values(); + } + return this._exports.values(); } /** - * @param {string} context context path for entry - * @param {Dependency} dependency dependency that should be followed - * @param {EntryOptions} options options - * @param {ModuleCallback} callback callback function - * @returns {void} returns + * @returns {Iterable} all exports in order */ - addInclude(context, dependency, options, callback) { - this._addEntryItem( - context, - dependency, - "includeDependencies", - options, - callback - ); + get orderedExports() { + if (!this._exportsAreOrdered) { + this._sortExports(); + } + if (this._redirectTo !== undefined) { + const map = new Map( + Array.from(this._redirectTo.orderedExports, item => [item.name, item]) + ); + for (const [key, value] of this._exports) { + map.set(key, value); + } + // sorting should be pretty fast as map contains + // a lot of presorted items + this._sortExportsMap(map); + return map.values(); + } + return this._exports.values(); } /** - * @param {string} context context path for entry - * @param {Dependency} entry entry dependency that should be followed - * @param {"dependencies" | "includeDependencies"} target type of entry - * @param {EntryOptions} options options - * @param {ModuleCallback} callback callback function - * @returns {void} returns + * @returns {ExportInfo} the export info of unlisted exports */ - _addEntryItem(context, entry, target, options, callback) { - const { name } = options; - let entryData = - name !== undefined ? this.entries.get(name) : this.globalEntry; - if (entryData === undefined) { - entryData = { - dependencies: [], - includeDependencies: [], - options: { - name: undefined, - ...options - } - }; - entryData[target].push(entry); - this.entries.set(name, entryData); - } else { - entryData[target].push(entry); - for (const key of Object.keys(options)) { - if (options[key] === undefined) continue; - if (entryData.options[key] === options[key]) continue; - if ( - Array.isArray(entryData.options[key]) && - Array.isArray(options[key]) && - arrayEquals(entryData.options[key], options[key]) - ) { - continue; - } - if (entryData.options[key] === undefined) { - entryData.options[key] = options[key]; - } else { - return callback( - new WebpackError( - `Conflicting entry option ${key} = ${entryData.options[key]} vs ${options[key]}` - ) - ); - } + get otherExportsInfo() { + if (this._redirectTo !== undefined) + return this._redirectTo.otherExportsInfo; + return this._otherExportsInfo; + } + + _sortExportsMap(exports) { + if (exports.size > 1) { + const namesInOrder = []; + for (const entry of exports.values()) { + namesInOrder.push(entry.name); + } + namesInOrder.sort(); + let i = 0; + for (const entry of exports.values()) { + const name = namesInOrder[i]; + if (entry.name !== name) break; + i++; + } + for (; i < namesInOrder.length; i++) { + const name = namesInOrder[i]; + const correctEntry = exports.get(name); + exports.delete(name); + exports.set(name, correctEntry); } } + } - this.hooks.addEntry.call(entry, options); + _sortExports() { + this._sortExportsMap(this._exports); + this._exportsAreOrdered = true; + } - this.addModuleTree( - { - context, - dependency: entry, - contextInfo: entryData.options.layer - ? { issuerLayer: entryData.options.layer } - : undefined - }, - (err, module) => { - if (err) { - this.hooks.failedEntry.call(entry, options, err); - return callback(err); - } - this.hooks.succeedEntry.call(entry, options, module); - return callback(null, module); + setRedirectNamedTo(exportsInfo) { + if (this._redirectTo === exportsInfo) return false; + this._redirectTo = exportsInfo; + return true; + } + + setHasProvideInfo() { + for (const exportInfo of this._exports.values()) { + if (exportInfo.provided === undefined) { + exportInfo.provided = false; } - ); + if (exportInfo.canMangleProvide === undefined) { + exportInfo.canMangleProvide = true; + } + } + if (this._redirectTo !== undefined) { + this._redirectTo.setHasProvideInfo(); + } else { + if (this._otherExportsInfo.provided === undefined) { + this._otherExportsInfo.provided = false; + } + if (this._otherExportsInfo.canMangleProvide === undefined) { + this._otherExportsInfo.canMangleProvide = true; + } + } + } + + setHasUseInfo() { + for (const exportInfo of this._exports.values()) { + exportInfo.setHasUseInfo(); + } + this._sideEffectsOnlyInfo.setHasUseInfo(); + if (this._redirectTo !== undefined) { + this._redirectTo.setHasUseInfo(); + } else { + this._otherExportsInfo.setHasUseInfo(); + if (this._otherExportsInfo.canMangleUse === undefined) { + this._otherExportsInfo.canMangleUse = true; + } + } } /** - * @param {Module} module module to be rebuilt - * @param {ModuleCallback} callback callback when module finishes rebuilding - * @returns {void} + * @param {string} name export name + * @returns {ExportInfo} export info for this name */ - rebuildModule(module, callback) { - this.rebuildQueue.add(module, callback); + getOwnExportInfo(name) { + const info = this._exports.get(name); + if (info !== undefined) return info; + const newInfo = new ExportInfo(name, this._otherExportsInfo); + this._exports.set(name, newInfo); + this._exportsAreOrdered = false; + return newInfo; } /** - * @param {Module} module module to be rebuilt - * @param {ModuleCallback} callback callback when module finishes rebuilding - * @returns {void} + * @param {string} name export name + * @returns {ExportInfo} export info for this name */ - _rebuildModule(module, callback) { - this.hooks.rebuildModule.call(module); - const oldDependencies = module.dependencies.slice(); - const oldBlocks = module.blocks.slice(); - module.invalidateBuild(); - this.buildQueue.invalidate(module); - this.buildModule(module, err => { - if (err) { - return this.hooks.finishRebuildingModule.callAsync(module, err2 => { - if (err2) { - callback( - makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule") - ); - return; - } - callback(err); - }); - } + getExportInfo(name) { + const info = this._exports.get(name); + if (info !== undefined) return info; + if (this._redirectTo !== undefined) + return this._redirectTo.getExportInfo(name); + const newInfo = new ExportInfo(name, this._otherExportsInfo); + this._exports.set(name, newInfo); + this._exportsAreOrdered = false; + return newInfo; + } - this.processDependenciesQueue.invalidate(module); - this.moduleGraph.unfreeze(); - this.processModuleDependencies(module, err => { - if (err) return callback(err); - this.removeReasonsOfDependencyBlock(module, { - dependencies: oldDependencies, - blocks: oldBlocks - }); - this.hooks.finishRebuildingModule.callAsync(module, err2 => { - if (err2) { - callback( - makeWebpackError(err2, "Compilation.hooks.finishRebuildingModule") - ); - return; - } - callback(null, module); - }); - }); - }); + /** + * @param {string} name export name + * @returns {ExportInfo} export info for this name + */ + getReadOnlyExportInfo(name) { + const info = this._exports.get(name); + if (info !== undefined) return info; + if (this._redirectTo !== undefined) + return this._redirectTo.getReadOnlyExportInfo(name); + return this._otherExportsInfo; } - _computeAffectedModules(modules) { - const moduleMemCacheCache = this.compiler.moduleMemCaches; - if (!moduleMemCacheCache) return; - if (!this.moduleMemCaches) { - this.moduleMemCaches = new Map(); - this.moduleGraph.setModuleMemCaches(this.moduleMemCaches); + /** + * @param {string[]} name export name + * @returns {ExportInfo | undefined} export info for this name + */ + getReadOnlyExportInfoRecursive(name) { + const exportInfo = this.getReadOnlyExportInfo(name[0]); + if (name.length === 1) return exportInfo; + if (!exportInfo.exportsInfo) return undefined; + return exportInfo.exportsInfo.getReadOnlyExportInfoRecursive(name.slice(1)); + } + + /** + * @param {string[]=} name the export name + * @returns {ExportsInfo | undefined} the nested exports info + */ + getNestedExportsInfo(name) { + if (Array.isArray(name) && name.length > 0) { + const info = this.getReadOnlyExportInfo(name[0]); + if (!info.exportsInfo) return undefined; + return info.exportsInfo.getNestedExportsInfo(name.slice(1)); } - const { moduleGraph, moduleMemCaches } = this; - const affectedModules = new Set(); - const infectedModules = new Set(); - let statNew = 0; - let statChanged = 0; - let statUnchanged = 0; - let statReferencesChanged = 0; - let statWithoutBuild = 0; + return this; + } - const computeReferences = module => { - /** @type {WeakMap} */ - let references = undefined; - for (const connection of moduleGraph.getOutgoingConnections(module)) { - const d = connection.dependency; - const m = connection.module; - if (!d || !m || unsafeCacheDependencies.has(d)) continue; - if (references === undefined) references = new WeakMap(); - references.set(d, m); + /** + * @param {boolean=} canMangle true, if exports can still be mangled (defaults to false) + * @param {Set=} excludeExports list of unaffected exports + * @param {any=} targetKey use this as key for the target + * @param {ModuleGraphConnection=} targetModule set this module as target + * @param {number=} priority priority + * @returns {boolean} true, if this call changed something + */ + setUnknownExportsProvided( + canMangle, + excludeExports, + targetKey, + targetModule, + priority + ) { + let changed = false; + if (excludeExports) { + for (const name of excludeExports) { + // Make sure these entries exist, so they can get different info + this.getExportInfo(name); } - return references; - }; - - /** - * @param {Module} module the module - * @param {WeakMap} references references - * @returns {boolean} true, when the references differ - */ - const compareReferences = (module, references) => { - if (references === undefined) return true; - for (const connection of moduleGraph.getOutgoingConnections(module)) { - const d = connection.dependency; - if (!d) continue; - const entry = references.get(d); - if (entry === undefined) continue; - if (entry !== connection.module) return false; + } + for (const exportInfo of this._exports.values()) { + if (excludeExports && excludeExports.has(exportInfo.name)) continue; + if (exportInfo.provided !== true && exportInfo.provided !== null) { + exportInfo.provided = null; + changed = true; } - return true; - }; - - const modulesWithoutCache = new Set(modules); - for (const [module, cachedMemCache] of moduleMemCacheCache) { - if (modulesWithoutCache.has(module)) { - const buildInfo = module.buildInfo; - if (buildInfo) { - if (cachedMemCache.buildInfo !== buildInfo) { - // use a new one - const memCache = new WeakTupleMap(); - moduleMemCaches.set(module, memCache); - affectedModules.add(module); - cachedMemCache.buildInfo = buildInfo; - cachedMemCache.references = computeReferences(module); - cachedMemCache.memCache = memCache; - statChanged++; - } else if (!compareReferences(module, cachedMemCache.references)) { - // use a new one - const memCache = new WeakTupleMap(); - moduleMemCaches.set(module, memCache); - affectedModules.add(module); - cachedMemCache.references = computeReferences(module); - cachedMemCache.memCache = memCache; - statReferencesChanged++; - } else { - // keep the old mem cache - moduleMemCaches.set(module, cachedMemCache.memCache); - statUnchanged++; - } - } else { - infectedModules.add(module); - moduleMemCacheCache.delete(module); - statWithoutBuild++; - } - modulesWithoutCache.delete(module); - } else { - moduleMemCacheCache.delete(module); + if (!canMangle && exportInfo.canMangleProvide !== false) { + exportInfo.canMangleProvide = false; + changed = true; + } + if (targetKey) { + exportInfo.setTarget(targetKey, targetModule, [exportInfo.name], -1); } } - - for (const module of modulesWithoutCache) { - const buildInfo = module.buildInfo; - if (buildInfo) { - // create a new entry - const memCache = new WeakTupleMap(); - moduleMemCacheCache.set(module, { - buildInfo, - references: computeReferences(module), - memCache - }); - moduleMemCaches.set(module, memCache); - affectedModules.add(module); - statNew++; - } else { - infectedModules.add(module); - statWithoutBuild++; + if (this._redirectTo !== undefined) { + if ( + this._redirectTo.setUnknownExportsProvided( + canMangle, + excludeExports, + targetKey, + targetModule, + priority + ) + ) { + changed = true; + } + } else { + if ( + this._otherExportsInfo.provided !== true && + this._otherExportsInfo.provided !== null + ) { + this._otherExportsInfo.provided = null; + changed = true; + } + if (!canMangle && this._otherExportsInfo.canMangleProvide !== false) { + this._otherExportsInfo.canMangleProvide = false; + changed = true; + } + if (targetKey) { + this._otherExportsInfo.setTarget( + targetKey, + targetModule, + undefined, + priority + ); } } + return changed; + } - const reduceAffectType = connections => { - let affected = false; - for (const { dependency } of connections) { - if (!dependency) continue; - const type = dependency.couldAffectReferencingModule(); - if (type === Dependency.TRANSITIVE) return Dependency.TRANSITIVE; - if (type === false) continue; - affected = true; - } - return affected; - }; - const directOnlyInfectedModules = new Set(); - for (const module of infectedModules) { - for (const [ - referencingModule, - connections - ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { - if (!referencingModule) continue; - if (infectedModules.has(referencingModule)) continue; - const type = reduceAffectType(connections); - if (!type) continue; - if (type === true) { - directOnlyInfectedModules.add(referencingModule); - } else { - infectedModules.add(referencingModule); - } + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when something changed + */ + setUsedInUnknownWay(runtime) { + let changed = false; + for (const exportInfo of this._exports.values()) { + if (exportInfo.setUsedInUnknownWay(runtime)) { + changed = true; } } - for (const module of directOnlyInfectedModules) infectedModules.add(module); - const directOnlyAffectModules = new Set(); - for (const module of affectedModules) { - for (const [ - referencingModule, - connections - ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { - if (!referencingModule) continue; - if (infectedModules.has(referencingModule)) continue; - if (affectedModules.has(referencingModule)) continue; - const type = reduceAffectType(connections); - if (!type) continue; - if (type === true) { - directOnlyAffectModules.add(referencingModule); - } else { - affectedModules.add(referencingModule); - } - const memCache = new WeakTupleMap(); - const cache = moduleMemCacheCache.get(referencingModule); - cache.memCache = memCache; - moduleMemCaches.set(referencingModule, memCache); + if (this._redirectTo !== undefined) { + if (this._redirectTo.setUsedInUnknownWay(runtime)) { + changed = true; + } + } else { + if ( + this._otherExportsInfo.setUsedConditionally( + used => used < UsageState.Unknown, + UsageState.Unknown, + runtime + ) + ) { + changed = true; + } + if (this._otherExportsInfo.canMangleUse !== false) { + this._otherExportsInfo.canMangleUse = false; + changed = true; } } - for (const module of directOnlyAffectModules) affectedModules.add(module); - this.logger.log( - `${Math.round( - (100 * (affectedModules.size + infectedModules.size)) / - this.modules.size - )}% (${affectedModules.size} affected + ${ - infectedModules.size - } infected of ${ - this.modules.size - }) modules flagged as affected (${statNew} new modules, ${statChanged} changed, ${statReferencesChanged} references changed, ${statUnchanged} unchanged, ${statWithoutBuild} were not built)` - ); + return changed; } - _computeAffectedModulesWithChunkGraph() { - const { moduleMemCaches } = this; - if (!moduleMemCaches) return; - const moduleMemCaches2 = (this.moduleMemCaches2 = new Map()); - const { moduleGraph, chunkGraph } = this; - const key = "memCache2"; - let statUnchanged = 0; - let statChanged = 0; - let statNew = 0; - /** - * @param {Module} module module - * @returns {{ id: string | number, modules?: Map, blocks?: (string | number)[] }} references - */ - const computeReferences = module => { - const id = chunkGraph.getModuleId(module); - /** @type {Map} */ - let modules = undefined; - /** @type {(string | number)[] | undefined} */ - let blocks = undefined; - const outgoing = moduleGraph.getOutgoingConnectionsByModule(module); - if (outgoing !== undefined) { - for (const m of outgoing.keys()) { - if (!m) continue; - if (modules === undefined) modules = new Map(); - modules.set(m, chunkGraph.getModuleId(m)); - } + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when something changed + */ + setUsedWithoutInfo(runtime) { + let changed = false; + for (const exportInfo of this._exports.values()) { + if (exportInfo.setUsedWithoutInfo(runtime)) { + changed = true; } - if (module.blocks.length > 0) { - blocks = []; - const queue = Array.from(module.blocks); - for (const block of queue) { - const chunkGroup = chunkGraph.getBlockChunkGroup(block); - if (chunkGroup) { - for (const chunk of chunkGroup.chunks) { - blocks.push(chunk.id); - } - } else { - blocks.push(null); - } - queue.push.apply(queue, block.blocks); - } + } + if (this._redirectTo !== undefined) { + if (this._redirectTo.setUsedWithoutInfo(runtime)) { + changed = true; } - return { id, modules, blocks }; - }; - /** - * @param {Module} module module - * @param {Object} references references - * @param {string | number} references.id id - * @param {Map=} references.modules modules - * @param {(string | number)[]=} references.blocks blocks - * @returns {boolean} ok? - */ - const compareReferences = (module, { id, modules, blocks }) => { - if (id !== chunkGraph.getModuleId(module)) return false; - if (modules !== undefined) { - for (const [module, id] of modules) { - if (chunkGraph.getModuleId(module) !== id) return false; - } + } else { + if (this._otherExportsInfo.setUsed(UsageState.NoInfo, runtime)) { + changed = true; } - if (blocks !== undefined) { - const queue = Array.from(module.blocks); - let i = 0; - for (const block of queue) { - const chunkGroup = chunkGraph.getBlockChunkGroup(block); - if (chunkGroup) { - for (const chunk of chunkGroup.chunks) { - if (i >= blocks.length || blocks[i++] !== chunk.id) return false; - } - } else { - if (i >= blocks.length || blocks[i++] !== null) return false; - } - queue.push.apply(queue, block.blocks); - } - if (i !== blocks.length) return false; + if (this._otherExportsInfo.canMangleUse !== false) { + this._otherExportsInfo.canMangleUse = false; + changed = true; } - return true; - }; + } + return changed; + } - for (const [module, memCache] of moduleMemCaches) { - /** @type {{ references: { id: string | number, modules?: Map, blocks?: (string | number)[]}, memCache: WeakTupleMap }} */ - const cache = memCache.get(key); - if (cache === undefined) { - const memCache2 = new WeakTupleMap(); - memCache.set(key, { - references: computeReferences(module), - memCache: memCache2 - }); - moduleMemCaches2.set(module, memCache2); - statNew++; - } else if (!compareReferences(module, cache.references)) { - const memCache = new WeakTupleMap(); - cache.references = computeReferences(module); - cache.memCache = memCache; - moduleMemCaches2.set(module, memCache); - statChanged++; - } else { - moduleMemCaches2.set(module, cache.memCache); - statUnchanged++; + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when something changed + */ + setAllKnownExportsUsed(runtime) { + let changed = false; + for (const exportInfo of this._exports.values()) { + if (!exportInfo.provided) continue; + if (exportInfo.setUsed(UsageState.Used, runtime)) { + changed = true; } } + return changed; + } - this.logger.log( - `${Math.round( - (100 * statChanged) / (statNew + statChanged + statUnchanged) - )}% modules flagged as affected by chunk graph (${statNew} new modules, ${statChanged} changed, ${statUnchanged} unchanged)` + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when something changed + */ + setUsedForSideEffectsOnly(runtime) { + return this._sideEffectsOnlyInfo.setUsedConditionally( + used => used === UsageState.Unused, + UsageState.Used, + runtime ); } - finish(callback) { - this.factorizeQueue.clear(); - if (this.profile) { - this.logger.time("finish module profiles"); - const ParallelismFactorCalculator = __webpack_require__(50780); - const p = new ParallelismFactorCalculator(); - const moduleGraph = this.moduleGraph; - const modulesWithProfiles = new Map(); - for (const module of this.modules) { - const profile = moduleGraph.getProfile(module); - if (!profile) continue; - modulesWithProfiles.set(module, profile); - p.range( - profile.buildingStartTime, - profile.buildingEndTime, - f => (profile.buildingParallelismFactor = f) - ); - p.range( - profile.factoryStartTime, - profile.factoryEndTime, - f => (profile.factoryParallelismFactor = f) - ); - p.range( - profile.integrationStartTime, - profile.integrationEndTime, - f => (profile.integrationParallelismFactor = f) - ); - p.range( - profile.storingStartTime, - profile.storingEndTime, - f => (profile.storingParallelismFactor = f) - ); - p.range( - profile.restoringStartTime, - profile.restoringEndTime, - f => (profile.restoringParallelismFactor = f) - ); - if (profile.additionalFactoryTimes) { - for (const { start, end } of profile.additionalFactoryTimes) { - const influence = (end - start) / profile.additionalFactories; - p.range( - start, - end, - f => - (profile.additionalFactoriesParallelismFactor += f * influence) - ); - } - } + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when the module exports are used in any way + */ + isUsed(runtime) { + if (this._redirectTo !== undefined) { + if (this._redirectTo.isUsed(runtime)) { + return true; + } + } else { + if (this._otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { + return true; } - p.calculate(); - - const logger = this.getLogger("webpack.Compilation.ModuleProfile"); - const logByValue = (value, msg) => { - if (value > 1000) { - logger.error(msg); - } else if (value > 500) { - logger.warn(msg); - } else if (value > 200) { - logger.info(msg); - } else if (value > 30) { - logger.log(msg); - } else { - logger.debug(msg); - } - }; - const logNormalSummary = (category, getDuration, getParallelism) => { - let sum = 0; - let max = 0; - for (const [module, profile] of modulesWithProfiles) { - const p = getParallelism(profile); - const d = getDuration(profile); - if (d === 0 || p === 0) continue; - const t = d / p; - sum += t; - if (t <= 10) continue; - logByValue( - t, - ` | ${Math.round(t)} ms${ - p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : "" - } ${category} > ${module.readableIdentifier(this.requestShortener)}` - ); - max = Math.max(max, t); - } - if (sum <= 10) return; - logByValue( - Math.max(sum / 10, max), - `${Math.round(sum)} ms ${category}` - ); - }; - const logByLoadersSummary = (category, getDuration, getParallelism) => { - const map = new Map(); - for (const [module, profile] of modulesWithProfiles) { - const list = provide( - map, - module.type + "!" + module.identifier().replace(/(!|^)[^!]*$/, ""), - () => [] - ); - list.push({ module, profile }); - } - - let sum = 0; - let max = 0; - for (const [key, modules] of map) { - let innerSum = 0; - let innerMax = 0; - for (const { module, profile } of modules) { - const p = getParallelism(profile); - const d = getDuration(profile); - if (d === 0 || p === 0) continue; - const t = d / p; - innerSum += t; - if (t <= 10) continue; - logByValue( - t, - ` | | ${Math.round(t)} ms${ - p >= 1.1 ? ` (parallelism ${Math.round(p * 10) / 10})` : "" - } ${category} > ${module.readableIdentifier( - this.requestShortener - )}` - ); - innerMax = Math.max(innerMax, t); - } - sum += innerSum; - if (innerSum <= 10) continue; - const idx = key.indexOf("!"); - const loaders = key.slice(idx + 1); - const moduleType = key.slice(0, idx); - const t = Math.max(innerSum / 10, innerMax); - logByValue( - t, - ` | ${Math.round(innerSum)} ms ${category} > ${ - loaders - ? `${ - modules.length - } x ${moduleType} with ${this.requestShortener.shorten( - loaders - )}` - : `${modules.length} x ${moduleType}` - }` - ); - max = Math.max(max, t); - } - if (sum <= 10) return; - logByValue( - Math.max(sum / 10, max), - `${Math.round(sum)} ms ${category}` - ); - }; - logNormalSummary( - "resolve to new modules", - p => p.factory, - p => p.factoryParallelismFactor - ); - logNormalSummary( - "resolve to existing modules", - p => p.additionalFactories, - p => p.additionalFactoriesParallelismFactor - ); - logNormalSummary( - "integrate modules", - p => p.restoring, - p => p.restoringParallelismFactor - ); - logByLoadersSummary( - "build modules", - p => p.building, - p => p.buildingParallelismFactor - ); - logNormalSummary( - "store modules", - p => p.storing, - p => p.storingParallelismFactor - ); - logNormalSummary( - "restore modules", - p => p.restoring, - p => p.restoringParallelismFactor - ); - this.logger.timeEnd("finish module profiles"); } - this.logger.time("compute affected modules"); - this._computeAffectedModules(this.modules); - this.logger.timeEnd("compute affected modules"); - this.logger.time("finish modules"); - const { modules, moduleMemCaches } = this; - this.hooks.finishModules.callAsync(modules, err => { - this.logger.timeEnd("finish modules"); - if (err) return callback(err); - - // extract warnings and errors from modules - this.moduleGraph.freeze("dependency errors"); - // TODO keep a cacheToken (= {}) for each module in the graph - // create a new one per compilation and flag all updated files - // and parents with it - this.logger.time("report dependency errors and warnings"); - for (const module of modules) { - // TODO only run for modules with changed cacheToken - // global WeakMap> to keep modules without errors/warnings - const memCache = moduleMemCaches && moduleMemCaches.get(module); - if (memCache && memCache.get("noWarningsOrErrors")) continue; - let hasProblems = this.reportDependencyErrorsAndWarnings(module, [ - module - ]); - const errors = module.getErrors(); - if (errors !== undefined) { - for (const error of errors) { - if (!error.module) { - error.module = module; - } - this.errors.push(error); - hasProblems = true; - } - } - const warnings = module.getWarnings(); - if (warnings !== undefined) { - for (const warning of warnings) { - if (!warning.module) { - warning.module = module; - } - this.warnings.push(warning); - hasProblems = true; - } - } - if (!hasProblems && memCache) memCache.set("noWarningsOrErrors", true); + for (const exportInfo of this._exports.values()) { + if (exportInfo.getUsed(runtime) !== UsageState.Unused) { + return true; } - this.moduleGraph.unfreeze(); - this.logger.timeEnd("report dependency errors and warnings"); - - callback(); - }); + } + return false; } - unseal() { - this.hooks.unseal.call(); - this.chunks.clear(); - this.chunkGroups.length = 0; - this.namedChunks.clear(); - this.namedChunkGroups.clear(); - this.entrypoints.clear(); - this.additionalChunkAssets.length = 0; - this.assets = {}; - this.assetsInfo.clear(); - this.moduleGraph.removeAllModuleAttributes(); - this.moduleGraph.unfreeze(); - this.moduleMemCaches2 = undefined; + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true, when the module is used in any way + */ + isModuleUsed(runtime) { + if (this.isUsed(runtime)) return true; + if (this._sideEffectsOnlyInfo.getUsed(runtime) !== UsageState.Unused) + return true; + return false; } /** - * @param {Callback} callback signals when the call finishes - * @returns {void} + * @param {RuntimeSpec} runtime the runtime + * @returns {SortableSet | boolean | null} set of used exports, or true (when namespace object is used), or false (when unused), or null (when unknown) */ - seal(callback) { - const finalCallback = err => { - this.factorizeQueue.clear(); - this.buildQueue.clear(); - this.rebuildQueue.clear(); - this.processDependenciesQueue.clear(); - this.addModuleQueue.clear(); - return callback(err); - }; - const chunkGraph = new ChunkGraph( - this.moduleGraph, - this.outputOptions.hashFunction - ); - this.chunkGraph = chunkGraph; - - if (this._backCompat) { - for (const module of this.modules) { - ChunkGraph.setChunkGraphForModule(module, chunkGraph); + getUsedExports(runtime) { + if (!this._redirectTo !== undefined) { + switch (this._otherExportsInfo.getUsed(runtime)) { + case UsageState.NoInfo: + return null; + case UsageState.Unknown: + case UsageState.OnlyPropertiesUsed: + case UsageState.Used: + return true; } } - - this.hooks.seal.call(); - - this.logger.time("optimize dependencies"); - while (this.hooks.optimizeDependencies.call(this.modules)) { - /* empty */ - } - this.hooks.afterOptimizeDependencies.call(this.modules); - this.logger.timeEnd("optimize dependencies"); - - this.logger.time("create chunks"); - this.hooks.beforeChunks.call(); - this.moduleGraph.freeze("seal"); - /** @type {Map} */ - const chunkGraphInit = new Map(); - for (const [name, { dependencies, includeDependencies, options }] of this - .entries) { - const chunk = this.addChunk(name); - if (options.filename) { - chunk.filenameTemplate = options.filename; - } - const entrypoint = new Entrypoint(options); - if (!options.dependOn && !options.runtime) { - entrypoint.setRuntimeChunk(chunk); + const array = []; + if (!this._exportsAreOrdered) this._sortExports(); + for (const exportInfo of this._exports.values()) { + switch (exportInfo.getUsed(runtime)) { + case UsageState.NoInfo: + return null; + case UsageState.Unknown: + return true; + case UsageState.OnlyPropertiesUsed: + case UsageState.Used: + array.push(exportInfo.name); } - entrypoint.setEntrypointChunk(chunk); - this.namedChunkGroups.set(name, entrypoint); - this.entrypoints.set(name, entrypoint); - this.chunkGroups.push(entrypoint); - connectChunkGroupAndChunk(entrypoint, chunk); - - const entryModules = new Set(); - for (const dep of [...this.globalEntry.dependencies, ...dependencies]) { - entrypoint.addOrigin(null, { name }, /** @type {any} */ (dep).request); - - const module = this.moduleGraph.getModule(dep); - if (module) { - chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint); - entryModules.add(module); - const modulesList = chunkGraphInit.get(entrypoint); - if (modulesList === undefined) { - chunkGraphInit.set(entrypoint, [module]); - } else { - modulesList.push(module); - } + } + if (this._redirectTo !== undefined) { + const inner = this._redirectTo.getUsedExports(runtime); + if (inner === null) return null; + if (inner === true) return true; + if (inner !== false) { + for (const item of inner) { + array.push(item); } } - - this.assignDepths(entryModules); - - const mapAndSort = deps => - deps - .map(dep => this.moduleGraph.getModule(dep)) - .filter(Boolean) - .sort(compareModulesByIdentifier); - const includedModules = [ - ...mapAndSort(this.globalEntry.includeDependencies), - ...mapAndSort(includeDependencies) - ]; - - let modulesList = chunkGraphInit.get(entrypoint); - if (modulesList === undefined) { - chunkGraphInit.set(entrypoint, (modulesList = [])); - } - for (const module of includedModules) { - this.assignDepth(module); - modulesList.push(module); + } + if (array.length === 0) { + switch (this._sideEffectsOnlyInfo.getUsed(runtime)) { + case UsageState.NoInfo: + return null; + case UsageState.Unused: + return false; } } - const runtimeChunks = new Set(); - outer: for (const [ - name, - { - options: { dependOn, runtime } + return new SortableSet(array); + } + + /** + * @returns {null | true | string[]} list of exports when known + */ + getProvidedExports() { + if (!this._redirectTo !== undefined) { + switch (this._otherExportsInfo.provided) { + case undefined: + return null; + case null: + return true; + case true: + return true; } - ] of this.entries) { - if (dependOn && runtime) { - const err = - new WebpackError(`Entrypoint '${name}' has 'dependOn' and 'runtime' specified. This is not valid. -Entrypoints that depend on other entrypoints do not have their own runtime. -They will use the runtime(s) from referenced entrypoints instead. -Remove the 'runtime' option from the entrypoint.`); - const entry = this.entrypoints.get(name); - err.chunk = entry.getEntrypointChunk(); - this.errors.push(err); + } + const array = []; + if (!this._exportsAreOrdered) this._sortExports(); + for (const exportInfo of this._exports.values()) { + switch (exportInfo.provided) { + case undefined: + return null; + case null: + return true; + case true: + array.push(exportInfo.name); } - if (dependOn) { - const entry = this.entrypoints.get(name); - const referencedChunks = entry - .getEntrypointChunk() - .getAllReferencedChunks(); - const dependOnEntries = []; - for (const dep of dependOn) { - const dependency = this.entrypoints.get(dep); - if (!dependency) { - throw new Error( - `Entry ${name} depends on ${dep}, but this entry was not found` - ); - } - if (referencedChunks.has(dependency.getEntrypointChunk())) { - const err = new WebpackError( - `Entrypoints '${name}' and '${dep}' use 'dependOn' to depend on each other in a circular way.` - ); - const entryChunk = entry.getEntrypointChunk(); - err.chunk = entryChunk; - this.errors.push(err); - entry.setRuntimeChunk(entryChunk); - continue outer; - } - dependOnEntries.push(dependency); - } - for (const dependency of dependOnEntries) { - connectChunkGroupParentAndChild(dependency, entry); - } - } else if (runtime) { - const entry = this.entrypoints.get(name); - let chunk = this.namedChunks.get(runtime); - if (chunk) { - if (!runtimeChunks.has(chunk)) { - const err = - new WebpackError(`Entrypoint '${name}' has a 'runtime' option which points to another entrypoint named '${runtime}'. -It's not valid to use other entrypoints as runtime chunk. -Did you mean to use 'dependOn: ${JSON.stringify( - runtime - )}' instead to allow using entrypoint '${name}' within the runtime of entrypoint '${runtime}'? For this '${runtime}' must always be loaded when '${name}' is used. -Or do you want to use the entrypoints '${name}' and '${runtime}' independently on the same page with a shared runtime? In this case give them both the same value for the 'runtime' option. It must be a name not already used by an entrypoint.`); - const entryChunk = entry.getEntrypointChunk(); - err.chunk = entryChunk; - this.errors.push(err); - entry.setRuntimeChunk(entryChunk); - continue; - } - } else { - chunk = this.addChunk(runtime); - chunk.preventIntegration = true; - runtimeChunks.add(chunk); + } + if (this._redirectTo !== undefined) { + const inner = this._redirectTo.getProvidedExports(); + if (inner === null) return null; + if (inner === true) return true; + for (const item of inner) { + if (!array.includes(item)) { + array.push(item); } - entry.unshiftChunk(chunk); - chunk.addGroup(entry); - entry.setRuntimeChunk(chunk); } } - buildChunkGraph(this, chunkGraphInit); - this.hooks.afterChunks.call(this.chunks); - this.logger.timeEnd("create chunks"); - - this.logger.time("optimize"); - this.hooks.optimize.call(); - - while (this.hooks.optimizeModules.call(this.modules)) { - /* empty */ - } - this.hooks.afterOptimizeModules.call(this.modules); + return array; + } - while (this.hooks.optimizeChunks.call(this.chunks, this.chunkGroups)) { - /* empty */ + /** + * @param {RuntimeSpec} runtime the runtime + * @returns {ExportInfo[]} exports that are relevant (not unused and potential provided) + */ + getRelevantExports(runtime) { + const list = []; + for (const exportInfo of this._exports.values()) { + const used = exportInfo.getUsed(runtime); + if (used === UsageState.Unused) continue; + if (exportInfo.provided === false) continue; + list.push(exportInfo); } - this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups); - - this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => { - if (err) { - return finalCallback( - makeWebpackError(err, "Compilation.hooks.optimizeTree") - ); + if (this._redirectTo !== undefined) { + for (const exportInfo of this._redirectTo.getRelevantExports(runtime)) { + if (!this._exports.has(exportInfo.name)) list.push(exportInfo); } - - this.hooks.afterOptimizeTree.call(this.chunks, this.modules); - - this.hooks.optimizeChunkModules.callAsync( - this.chunks, - this.modules, - err => { - if (err) { - return finalCallback( - makeWebpackError(err, "Compilation.hooks.optimizeChunkModules") - ); - } - - this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules); - - const shouldRecord = this.hooks.shouldRecord.call() !== false; - - this.hooks.reviveModules.call(this.modules, this.records); - this.hooks.beforeModuleIds.call(this.modules); - this.hooks.moduleIds.call(this.modules); - this.hooks.optimizeModuleIds.call(this.modules); - this.hooks.afterOptimizeModuleIds.call(this.modules); - - this.hooks.reviveChunks.call(this.chunks, this.records); - this.hooks.beforeChunkIds.call(this.chunks); - this.hooks.chunkIds.call(this.chunks); - this.hooks.optimizeChunkIds.call(this.chunks); - this.hooks.afterOptimizeChunkIds.call(this.chunks); - - this.assignRuntimeIds(); - - this.logger.time("compute affected modules with chunk graph"); - this._computeAffectedModulesWithChunkGraph(); - this.logger.timeEnd("compute affected modules with chunk graph"); - - this.sortItemsWithChunkIds(); - - if (shouldRecord) { - this.hooks.recordModules.call(this.modules, this.records); - this.hooks.recordChunks.call(this.chunks, this.records); - } - - this.hooks.optimizeCodeGeneration.call(this.modules); - this.logger.timeEnd("optimize"); - - this.logger.time("module hashing"); - this.hooks.beforeModuleHash.call(); - this.createModuleHashes(); - this.hooks.afterModuleHash.call(); - this.logger.timeEnd("module hashing"); - - this.logger.time("code generation"); - this.hooks.beforeCodeGeneration.call(); - this.codeGeneration(err => { - if (err) { - return finalCallback(err); - } - this.hooks.afterCodeGeneration.call(); - this.logger.timeEnd("code generation"); - - this.logger.time("runtime requirements"); - this.hooks.beforeRuntimeRequirements.call(); - this.processRuntimeRequirements(); - this.hooks.afterRuntimeRequirements.call(); - this.logger.timeEnd("runtime requirements"); - - this.logger.time("hashing"); - this.hooks.beforeHash.call(); - const codeGenerationJobs = this.createHash(); - this.hooks.afterHash.call(); - this.logger.timeEnd("hashing"); - - this._runCodeGenerationJobs(codeGenerationJobs, err => { - if (err) { - return finalCallback(err); - } - - if (shouldRecord) { - this.logger.time("record hash"); - this.hooks.recordHash.call(this.records); - this.logger.timeEnd("record hash"); - } - - this.logger.time("module assets"); - this.clearAssets(); - - this.hooks.beforeModuleAssets.call(); - this.createModuleAssets(); - this.logger.timeEnd("module assets"); - - const cont = () => { - this.logger.time("process assets"); - this.hooks.processAssets.callAsync(this.assets, err => { - if (err) { - return finalCallback( - makeWebpackError(err, "Compilation.hooks.processAssets") - ); - } - this.hooks.afterProcessAssets.call(this.assets); - this.logger.timeEnd("process assets"); - this.assets = this._backCompat - ? soonFrozenObjectDeprecation( - this.assets, - "Compilation.assets", - "DEP_WEBPACK_COMPILATION_ASSETS", - `BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation. - Do changes to assets earlier, e. g. in Compilation.hooks.processAssets. - Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.` - ) - : Object.freeze(this.assets); - - this.summarizeDependencies(); - if (shouldRecord) { - this.hooks.record.call(this, this.records); - } - - if (this.hooks.needAdditionalSeal.call()) { - this.unseal(); - return this.seal(callback); - } - return this.hooks.afterSeal.callAsync(err => { - if (err) { - return finalCallback( - makeWebpackError(err, "Compilation.hooks.afterSeal") - ); - } - this.fileSystemInfo.logStatistics(); - finalCallback(); - }); - }); - }; - - this.logger.time("create chunk assets"); - if (this.hooks.shouldGenerateChunkAssets.call() !== false) { - this.hooks.beforeChunkAssets.call(); - this.createChunkAssets(err => { - this.logger.timeEnd("create chunk assets"); - if (err) { - return finalCallback(err); - } - cont(); - }); - } else { - this.logger.timeEnd("create chunk assets"); - cont(); - } - }); - }); - } - ); - }); + } + if ( + this._otherExportsInfo.provided !== false && + this._otherExportsInfo.getUsed(runtime) !== UsageState.Unused + ) { + list.push(this._otherExportsInfo); + } + return list; } /** - * @param {Module} module module to report from - * @param {DependenciesBlock[]} blocks blocks to report from - * @returns {boolean} true, when it has warnings or errors + * @param {string | string[]} name the name of the export + * @returns {boolean | undefined | null} if the export is provided */ - reportDependencyErrorsAndWarnings(module, blocks) { - let hasProblems = false; - for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { - const block = blocks[indexBlock]; - const dependencies = block.dependencies; - - for (let indexDep = 0; indexDep < dependencies.length; indexDep++) { - const d = dependencies[indexDep]; - - const warnings = d.getWarnings(this.moduleGraph); - if (warnings) { - for (let indexWar = 0; indexWar < warnings.length; indexWar++) { - const w = warnings[indexWar]; - - const warning = new ModuleDependencyWarning(module, w, d.loc); - this.warnings.push(warning); - hasProblems = true; - } - } - const errors = d.getErrors(this.moduleGraph); - if (errors) { - for (let indexErr = 0; indexErr < errors.length; indexErr++) { - const e = errors[indexErr]; - - const error = new ModuleDependencyError(module, e, d.loc); - this.errors.push(error); - hasProblems = true; - } - } + isExportProvided(name) { + if (Array.isArray(name)) { + const info = this.getReadOnlyExportInfo(name[0]); + if (info.exportsInfo && name.length > 1) { + return info.exportsInfo.isExportProvided(name.slice(1)); } + return info.provided; + } + const info = this.getReadOnlyExportInfo(name); + return info.provided; + } - if (this.reportDependencyErrorsAndWarnings(module, block.blocks)) - hasProblems = true; + /** + * @param {RuntimeSpec} runtime runtime + * @returns {string} key representing the usage + */ + getUsageKey(runtime) { + const key = []; + if (this._redirectTo !== undefined) { + key.push(this._redirectTo.getUsageKey(runtime)); + } else { + key.push(this._otherExportsInfo.getUsed(runtime)); } - return hasProblems; + key.push(this._sideEffectsOnlyInfo.getUsed(runtime)); + for (const exportInfo of this.orderedOwnedExports) { + key.push(exportInfo.getUsed(runtime)); + } + return key.join("|"); } - codeGeneration(callback) { - const { chunkGraph } = this; - this.codeGenerationResults = new CodeGenerationResults( - this.outputOptions.hashFunction - ); - /** @type {{module: Module, hash: string, runtime: RuntimeSpec, runtimes: RuntimeSpec[]}[]} */ - const jobs = []; - for (const module of this.modules) { - const runtimes = chunkGraph.getModuleRuntimes(module); - if (runtimes.size === 1) { - for (const runtime of runtimes) { - const hash = chunkGraph.getModuleHash(module, runtime); - jobs.push({ module, hash, runtime, runtimes: [runtime] }); - } - } else if (runtimes.size > 1) { - /** @type {Map} */ - const map = new Map(); - for (const runtime of runtimes) { - const hash = chunkGraph.getModuleHash(module, runtime); - const job = map.get(hash); - if (job === undefined) { - const newJob = { module, hash, runtime, runtimes: [runtime] }; - jobs.push(newJob); - map.set(hash, newJob); - } else { - job.runtimes.push(runtime); - } - } + /** + * @param {RuntimeSpec} runtimeA first runtime + * @param {RuntimeSpec} runtimeB second runtime + * @returns {boolean} true, when equally used + */ + isEquallyUsed(runtimeA, runtimeB) { + if (this._redirectTo !== undefined) { + if (!this._redirectTo.isEquallyUsed(runtimeA, runtimeB)) return false; + } else { + if ( + this._otherExportsInfo.getUsed(runtimeA) !== + this._otherExportsInfo.getUsed(runtimeB) + ) { + return false; } } - - this._runCodeGenerationJobs(jobs, callback); + if ( + this._sideEffectsOnlyInfo.getUsed(runtimeA) !== + this._sideEffectsOnlyInfo.getUsed(runtimeB) + ) { + return false; + } + for (const exportInfo of this.ownedExports) { + if (exportInfo.getUsed(runtimeA) !== exportInfo.getUsed(runtimeB)) + return false; + } + return true; } - _runCodeGenerationJobs(jobs, callback) { - let statModulesFromCache = 0; - let statModulesGenerated = 0; - const { chunkGraph, moduleGraph, dependencyTemplates, runtimeTemplate } = - this; - const results = this.codeGenerationResults; - const errors = []; - /** @type {Set | undefined} */ - let notCodeGeneratedModules = undefined; - const runIteration = () => { - let delayedJobs = []; - let delayedModules = new Set(); - asyncLib.eachLimit( - jobs, - this.options.parallelism, - (job, callback) => { - const { module } = job; - const { codeGenerationDependencies } = module; - if (codeGenerationDependencies !== undefined) { - if ( - notCodeGeneratedModules === undefined || - codeGenerationDependencies.some(dep => { - const referencedModule = moduleGraph.getModule(dep); - return notCodeGeneratedModules.has(referencedModule); - }) - ) { - delayedJobs.push(job); - delayedModules.add(module); - return callback(); - } - } - const { hash, runtime, runtimes } = job; - this._codeGenerationModule( - module, - runtime, - runtimes, - hash, - dependencyTemplates, - chunkGraph, - moduleGraph, - runtimeTemplate, - errors, - results, - (err, codeGenerated) => { - if (codeGenerated) statModulesGenerated++; - else statModulesFromCache++; - callback(err); - } - ); - }, - err => { - if (err) return callback(err); - if (delayedJobs.length > 0) { - if (delayedJobs.length === jobs.length) { - return callback( - new Error( - `Unable to make progress during code generation because of circular code generation dependency: ${Array.from( - delayedModules, - m => m.identifier() - ).join(", ")}` - ) - ); - } - jobs = delayedJobs; - delayedJobs = []; - notCodeGeneratedModules = delayedModules; - delayedModules = new Set(); - return runIteration(); - } - if (errors.length > 0) { - errors.sort( - compareSelect(err => err.module, compareModulesByIdentifier) - ); - for (const error of errors) { - this.errors.push(error); - } - } - this.logger.log( - `${Math.round( - (100 * statModulesGenerated) / - (statModulesGenerated + statModulesFromCache) - )}% code generated (${statModulesGenerated} generated, ${statModulesFromCache} from cache)` - ); - callback(); - } - ); - }; - runIteration(); + /** + * @param {string | string[]} name export name + * @param {RuntimeSpec} runtime check usage for this runtime only + * @returns {UsageStateType} usage status + */ + getUsed(name, runtime) { + if (Array.isArray(name)) { + if (name.length === 0) return this.otherExportsInfo.getUsed(runtime); + let info = this.getReadOnlyExportInfo(name[0]); + if (info.exportsInfo && name.length > 1) { + return info.exportsInfo.getUsed(name.slice(1), runtime); + } + return info.getUsed(runtime); + } + let info = this.getReadOnlyExportInfo(name); + return info.getUsed(runtime); } /** - * @param {Module} module module - * @param {RuntimeSpec} runtime runtime - * @param {RuntimeSpec[]} runtimes runtimes - * @param {string} hash hash - * @param {DependencyTemplates} dependencyTemplates dependencyTemplates - * @param {ChunkGraph} chunkGraph chunkGraph - * @param {ModuleGraph} moduleGraph moduleGraph - * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate - * @param {WebpackError[]} errors errors - * @param {CodeGenerationResults} results results - * @param {function(WebpackError=, boolean=): void} callback callback + * @param {string | string[]} name the export name + * @param {RuntimeSpec} runtime check usage for this runtime only + * @returns {string | string[] | false} the used name */ - _codeGenerationModule( - module, - runtime, - runtimes, - hash, - dependencyTemplates, - chunkGraph, - moduleGraph, - runtimeTemplate, - errors, - results, - callback - ) { - let codeGenerated = false; - const cache = new MultiItemCache( - runtimes.map(runtime => - this._codeGenerationCache.getItemCache( - `${module.identifier()}|${getRuntimeKey(runtime)}`, - `${hash}|${dependencyTemplates.getHash()}` - ) - ) - ); - cache.get((err, cachedResult) => { - if (err) return callback(err); - let result; - if (!cachedResult) { - try { - codeGenerated = true; - this.codeGeneratedModules.add(module); - result = module.codeGeneration({ - chunkGraph, - moduleGraph, - dependencyTemplates, - runtimeTemplate, - runtime, - codeGenerationResults: results - }); - } catch (err) { - errors.push(new CodeGenerationError(module, err)); - result = cachedResult = { - sources: new Map(), - runtimeRequirements: null - }; - } - } else { - result = cachedResult; + getUsedName(name, runtime) { + if (Array.isArray(name)) { + // TODO improve this + if (name.length === 0) { + if (!this.isUsed(runtime)) return false; + return name; } - for (const runtime of runtimes) { - results.add(module, runtime, result); + let info = this.getReadOnlyExportInfo(name[0]); + const x = info.getUsedName(name[0], runtime); + if (x === false) return false; + const arr = x === name[0] && name.length === 1 ? name : [x]; + if (name.length === 1) { + return arr; } - if (!cachedResult) { - cache.store(result, err => callback(err, codeGenerated)); + if ( + info.exportsInfo && + info.getUsed(runtime) === UsageState.OnlyPropertiesUsed + ) { + const nested = info.exportsInfo.getUsedName(name.slice(1), runtime); + if (!nested) return false; + return arr.concat(nested); } else { - callback(null, codeGenerated); + return arr.concat(name.slice(1)); } - }); + } else { + let info = this.getReadOnlyExportInfo(name); + const usedName = info.getUsedName(name, runtime); + return usedName; + } } - _getChunkGraphEntries() { - /** @type {Set} */ - const treeEntries = new Set(); - for (const ep of this.entrypoints.values()) { - const chunk = ep.getRuntimeChunk(); - if (chunk) treeEntries.add(chunk); - } - for (const ep of this.asyncEntrypoints) { - const chunk = ep.getRuntimeChunk(); - if (chunk) treeEntries.add(chunk); - } - return treeEntries; + /** + * @param {Hash} hash the hash + * @param {RuntimeSpec} runtime the runtime + * @returns {void} + */ + updateHash(hash, runtime) { + this._updateHash(hash, runtime, new Set()); } /** - * @param {Object} options options - * @param {ChunkGraph=} options.chunkGraph the chunk graph - * @param {Iterable=} options.modules modules - * @param {Iterable=} options.chunks chunks - * @param {CodeGenerationResults=} options.codeGenerationResults codeGenerationResults - * @param {Iterable=} options.chunkGraphEntries chunkGraphEntries + * @param {Hash} hash the hash + * @param {RuntimeSpec} runtime the runtime + * @param {Set} alreadyVisitedExportsInfo for circular references * @returns {void} */ - processRuntimeRequirements({ - chunkGraph = this.chunkGraph, - modules = this.modules, - chunks = this.chunks, - codeGenerationResults = this.codeGenerationResults, - chunkGraphEntries = this._getChunkGraphEntries() - } = {}) { - const context = { chunkGraph, codeGenerationResults }; - const { moduleMemCaches2 } = this; - this.logger.time("runtime requirements.modules"); - const additionalModuleRuntimeRequirements = - this.hooks.additionalModuleRuntimeRequirements; - const runtimeRequirementInModule = this.hooks.runtimeRequirementInModule; - for (const module of modules) { - if (chunkGraph.getNumberOfModuleChunks(module) > 0) { - const memCache = moduleMemCaches2 && moduleMemCaches2.get(module); - for (const runtime of chunkGraph.getModuleRuntimes(module)) { - if (memCache) { - const cached = memCache.get( - `moduleRuntimeRequirements-${getRuntimeKey(runtime)}` - ); - if (cached !== undefined) { - if (cached !== null) { - chunkGraph.addModuleRuntimeRequirements( - module, - runtime, - cached, - false - ); - } - continue; - } - } - let set; - const runtimeRequirements = - codeGenerationResults.getRuntimeRequirements(module, runtime); - if (runtimeRequirements && runtimeRequirements.size > 0) { - set = new Set(runtimeRequirements); - } else if (additionalModuleRuntimeRequirements.isUsed()) { - set = new Set(); - } else { - if (memCache) { - memCache.set( - `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, - null - ); - } - continue; - } - additionalModuleRuntimeRequirements.call(module, set, context); - - for (const r of set) { - const hook = runtimeRequirementInModule.get(r); - if (hook !== undefined) hook.call(module, set, context); - } - if (set.size === 0) { - if (memCache) { - memCache.set( - `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, - null - ); - } - } else { - if (memCache) { - memCache.set( - `moduleRuntimeRequirements-${getRuntimeKey(runtime)}`, - set - ); - chunkGraph.addModuleRuntimeRequirements( - module, - runtime, - set, - false - ); - } else { - chunkGraph.addModuleRuntimeRequirements(module, runtime, set); - } - } - } + _updateHash(hash, runtime, alreadyVisitedExportsInfo) { + const set = new Set(alreadyVisitedExportsInfo); + set.add(this); + for (const exportInfo of this.orderedExports) { + if (exportInfo.hasInfo(this._otherExportsInfo, runtime)) { + exportInfo._updateHash(hash, runtime, set); } } - this.logger.timeEnd("runtime requirements.modules"); - - this.logger.time("runtime requirements.chunks"); - for (const chunk of chunks) { - const set = new Set(); - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( - module, - chunk.runtime - ); - for (const r of runtimeRequirements) set.add(r); - } - this.hooks.additionalChunkRuntimeRequirements.call(chunk, set, context); - - for (const r of set) { - this.hooks.runtimeRequirementInChunk.for(r).call(chunk, set, context); - } - - chunkGraph.addChunkRuntimeRequirements(chunk, set); + this._sideEffectsOnlyInfo._updateHash(hash, runtime, set); + this._otherExportsInfo._updateHash(hash, runtime, set); + if (this._redirectTo !== undefined) { + this._redirectTo._updateHash(hash, runtime, set); } - this.logger.timeEnd("runtime requirements.chunks"); + } - this.logger.time("runtime requirements.entries"); - for (const treeEntry of chunkGraphEntries) { - const set = new Set(); - for (const chunk of treeEntry.getAllReferencedChunks()) { - const runtimeRequirements = - chunkGraph.getChunkRuntimeRequirements(chunk); - for (const r of runtimeRequirements) set.add(r); + getRestoreProvidedData() { + const otherProvided = this._otherExportsInfo.provided; + const otherCanMangleProvide = this._otherExportsInfo.canMangleProvide; + const otherTerminalBinding = this._otherExportsInfo.terminalBinding; + const exports = []; + for (const exportInfo of this.orderedExports) { + if ( + exportInfo.provided !== otherProvided || + exportInfo.canMangleProvide !== otherCanMangleProvide || + exportInfo.terminalBinding !== otherTerminalBinding || + exportInfo.exportsInfoOwned + ) { + exports.push({ + name: exportInfo.name, + provided: exportInfo.provided, + canMangleProvide: exportInfo.canMangleProvide, + terminalBinding: exportInfo.terminalBinding, + exportsInfo: exportInfo.exportsInfoOwned + ? exportInfo.exportsInfo.getRestoreProvidedData() + : undefined + }); } + } + return new RestoreProvidedData( + exports, + otherProvided, + otherCanMangleProvide, + otherTerminalBinding + ); + } - this.hooks.additionalTreeRuntimeRequirements.call( - treeEntry, - set, - context - ); - - for (const r of set) { - this.hooks.runtimeRequirementInTree - .for(r) - .call(treeEntry, set, context); + restoreProvided({ + otherProvided, + otherCanMangleProvide, + otherTerminalBinding, + exports + }) { + let wasEmpty = true; + for (const exportInfo of this._exports.values()) { + wasEmpty = false; + exportInfo.provided = otherProvided; + exportInfo.canMangleProvide = otherCanMangleProvide; + exportInfo.terminalBinding = otherTerminalBinding; + } + this._otherExportsInfo.provided = otherProvided; + this._otherExportsInfo.canMangleProvide = otherCanMangleProvide; + this._otherExportsInfo.terminalBinding = otherTerminalBinding; + for (const exp of exports) { + const exportInfo = this.getExportInfo(exp.name); + exportInfo.provided = exp.provided; + exportInfo.canMangleProvide = exp.canMangleProvide; + exportInfo.terminalBinding = exp.terminalBinding; + if (exp.exportsInfo) { + const exportsInfo = exportInfo.createNestedExportsInfo(); + exportsInfo.restoreProvided(exp.exportsInfo); } - - chunkGraph.addTreeRuntimeRequirements(treeEntry, set); } - this.logger.timeEnd("runtime requirements.entries"); + if (wasEmpty) this._exportsAreOrdered = true; } +} - // TODO webpack 6 make chunkGraph argument non-optional +class ExportInfo { /** - * @param {Chunk} chunk target chunk - * @param {RuntimeModule} module runtime module - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {void} + * @param {string} name the original name of the export + * @param {ExportInfo=} initFrom init values from this ExportInfo */ - addRuntimeModule(chunk, module, chunkGraph = this.chunkGraph) { - // Deprecated ModuleGraph association - if (this._backCompat) - ModuleGraph.setModuleGraphForModule(module, this.moduleGraph); - - // add it to the list - this.modules.add(module); - this._modules.set(module.identifier(), module); - - // connect to the chunk graph - chunkGraph.connectChunkAndModule(chunk, module); - chunkGraph.connectChunkAndRuntimeModule(chunk, module); - if (module.fullHash) { - chunkGraph.addFullHashModuleToChunk(chunk, module); - } else if (module.dependentHash) { - chunkGraph.addDependentHashModuleToChunk(chunk, module); + constructor(name, initFrom) { + /** @type {string} */ + this.name = name; + /** @private @type {string | null} */ + this._usedName = initFrom ? initFrom._usedName : null; + /** @private @type {UsageStateType} */ + this._globalUsed = initFrom ? initFrom._globalUsed : undefined; + /** @private @type {Map} */ + this._usedInRuntime = + initFrom && initFrom._usedInRuntime + ? new Map(initFrom._usedInRuntime) + : undefined; + /** @private @type {boolean} */ + this._hasUseInRuntimeInfo = initFrom + ? initFrom._hasUseInRuntimeInfo + : false; + /** + * true: it is provided + * false: it is not provided + * null: only the runtime knows if it is provided + * undefined: it was not determined if it is provided + * @type {boolean | null | undefined} + */ + this.provided = initFrom ? initFrom.provided : undefined; + /** + * is the export a terminal binding that should be checked for export star conflicts + * @type {boolean} + */ + this.terminalBinding = initFrom ? initFrom.terminalBinding : false; + /** + * true: it can be mangled + * false: is can not be mangled + * undefined: it was not determined if it can be mangled + * @type {boolean | undefined} + */ + this.canMangleProvide = initFrom ? initFrom.canMangleProvide : undefined; + /** + * true: it can be mangled + * false: is can not be mangled + * undefined: it was not determined if it can be mangled + * @type {boolean | undefined} + */ + this.canMangleUse = initFrom ? initFrom.canMangleUse : undefined; + /** @type {boolean} */ + this.exportsInfoOwned = false; + /** @type {ExportsInfo=} */ + this.exportsInfo = undefined; + /** @type {Map=} */ + this._target = undefined; + if (initFrom && initFrom._target) { + this._target = new Map(); + for (const [key, value] of initFrom._target) { + this._target.set(key, { + connection: value.connection, + export: value.export || [name], + priority: value.priority + }); + } } + /** @type {Map=} */ + this._maxTarget = undefined; + } - // attach runtime module - module.attach(this, chunk, chunkGraph); + // TODO webpack 5 remove + /** @private */ + get used() { + throw new Error("REMOVED"); + } + /** @private */ + get usedName() { + throw new Error("REMOVED"); + } + /** + * @private + * @param {*} v v + */ + set used(v) { + throw new Error("REMOVED"); + } + /** + * @private + * @param {*} v v + */ + set usedName(v) { + throw new Error("REMOVED"); + } - // Setup internals - const exportsInfo = this.moduleGraph.getExportsInfo(module); - exportsInfo.setHasProvideInfo(); - if (typeof chunk.runtime === "string") { - exportsInfo.setUsedForSideEffectsOnly(chunk.runtime); - } else if (chunk.runtime === undefined) { - exportsInfo.setUsedForSideEffectsOnly(undefined); - } else { - for (const runtime of chunk.runtime) { - exportsInfo.setUsedForSideEffectsOnly(runtime); - } + get canMangle() { + switch (this.canMangleProvide) { + case undefined: + return this.canMangleUse === false ? false : undefined; + case false: + return false; + case true: + switch (this.canMangleUse) { + case undefined: + return undefined; + case false: + return false; + case true: + return true; + } } - chunkGraph.addModuleRuntimeRequirements( - module, - chunk.runtime, - new Set([RuntimeGlobals.requireScope]) + throw new Error( + `Unexpected flags for canMangle ${this.canMangleProvide} ${this.canMangleUse}` ); - - // runtime modules don't need ids - chunkGraph.setModuleId(module, ""); - - // Call hook - this.hooks.runtimeModule.call(module, chunk); } /** - * If `module` is passed, `loc` and `request` must also be passed. - * @param {string | ChunkGroupOptions} groupOptions options for the chunk group - * @param {Module=} module the module the references the chunk group - * @param {DependencyLocation=} loc the location from with the chunk group is referenced (inside of module) - * @param {string=} request the request from which the the chunk group is referenced - * @returns {ChunkGroup} the new or existing chunk group + * @param {RuntimeSpec} runtime only apply to this runtime + * @returns {boolean} true, when something changed */ - addChunkInGroup(groupOptions, module, loc, request) { - if (typeof groupOptions === "string") { - groupOptions = { name: groupOptions }; + setUsedInUnknownWay(runtime) { + let changed = false; + if ( + this.setUsedConditionally( + used => used < UsageState.Unknown, + UsageState.Unknown, + runtime + ) + ) { + changed = true; } - const name = groupOptions.name; - - if (name) { - const chunkGroup = this.namedChunkGroups.get(name); - if (chunkGroup !== undefined) { - chunkGroup.addOptions(groupOptions); - if (module) { - chunkGroup.addOrigin(module, loc, request); - } - return chunkGroup; - } + if (this.canMangleUse !== false) { + this.canMangleUse = false; + changed = true; } - const chunkGroup = new ChunkGroup(groupOptions); - if (module) chunkGroup.addOrigin(module, loc, request); - const chunk = this.addChunk(name); + return changed; + } - connectChunkGroupAndChunk(chunkGroup, chunk); + /** + * @param {RuntimeSpec} runtime only apply to this runtime + * @returns {boolean} true, when something changed + */ + setUsedWithoutInfo(runtime) { + let changed = false; + if (this.setUsed(UsageState.NoInfo, runtime)) { + changed = true; + } + if (this.canMangleUse !== false) { + this.canMangleUse = false; + changed = true; + } + return changed; + } - this.chunkGroups.push(chunkGroup); - if (name) { - this.namedChunkGroups.set(name, chunkGroup); + setHasUseInfo() { + if (!this._hasUseInRuntimeInfo) { + this._hasUseInRuntimeInfo = true; + } + if (this.canMangleUse === undefined) { + this.canMangleUse = true; + } + if (this.exportsInfoOwned) { + this.exportsInfo.setHasUseInfo(); } - return chunkGroup; } /** - * @param {EntryOptions} options options for the entrypoint - * @param {Module} module the module the references the chunk group - * @param {DependencyLocation} loc the location from with the chunk group is referenced (inside of module) - * @param {string} request the request from which the the chunk group is referenced - * @returns {Entrypoint} the new or existing entrypoint + * @param {function(UsageStateType): boolean} condition compare with old value + * @param {UsageStateType} newValue set when condition is true + * @param {RuntimeSpec} runtime only apply to this runtime + * @returns {boolean} true when something has changed */ - addAsyncEntrypoint(options, module, loc, request) { - const name = options.name; - if (name) { - const entrypoint = this.namedChunkGroups.get(name); - if (entrypoint instanceof Entrypoint) { - if (entrypoint !== undefined) { - if (module) { - entrypoint.addOrigin(module, loc, request); - } - return entrypoint; + setUsedConditionally(condition, newValue, runtime) { + if (runtime === undefined) { + if (this._globalUsed === undefined) { + this._globalUsed = newValue; + return true; + } else { + if (this._globalUsed !== newValue && condition(this._globalUsed)) { + this._globalUsed = newValue; + return true; } - } else if (entrypoint) { - throw new Error( - `Cannot add an async entrypoint with the name '${name}', because there is already an chunk group with this name` + } + } else if (this._usedInRuntime === undefined) { + if (newValue !== UsageState.Unused && condition(UsageState.Unused)) { + this._usedInRuntime = new Map(); + forEachRuntime(runtime, runtime => + this._usedInRuntime.set(runtime, newValue) ); + return true; + } + } else { + let changed = false; + forEachRuntime(runtime, runtime => { + /** @type {UsageStateType} */ + let oldValue = this._usedInRuntime.get(runtime); + if (oldValue === undefined) oldValue = UsageState.Unused; + if (newValue !== oldValue && condition(oldValue)) { + if (newValue === UsageState.Unused) { + this._usedInRuntime.delete(runtime); + } else { + this._usedInRuntime.set(runtime, newValue); + } + changed = true; + } + }); + if (changed) { + if (this._usedInRuntime.size === 0) this._usedInRuntime = undefined; + return true; } } - const chunk = this.addChunk(name); - if (options.filename) { - chunk.filenameTemplate = options.filename; - } - const entrypoint = new Entrypoint(options, false); - entrypoint.setRuntimeChunk(chunk); - entrypoint.setEntrypointChunk(chunk); - if (name) { - this.namedChunkGroups.set(name, entrypoint); - } - this.chunkGroups.push(entrypoint); - this.asyncEntrypoints.push(entrypoint); - connectChunkGroupAndChunk(entrypoint, chunk); - if (module) { - entrypoint.addOrigin(module, loc, request); - } - return entrypoint; + return false; } /** - * This method first looks to see if a name is provided for a new chunk, - * and first looks to see if any named chunks already exist and reuse that chunk instead. - * - * @param {string=} name optional chunk name to be provided - * @returns {Chunk} create a chunk (invoked during seal event) + * @param {UsageStateType} newValue new value of the used state + * @param {RuntimeSpec} runtime only apply to this runtime + * @returns {boolean} true when something has changed */ - addChunk(name) { - if (name) { - const chunk = this.namedChunks.get(name); - if (chunk !== undefined) { - return chunk; + setUsed(newValue, runtime) { + if (runtime === undefined) { + if (this._globalUsed !== newValue) { + this._globalUsed = newValue; + return true; + } + } else if (this._usedInRuntime === undefined) { + if (newValue !== UsageState.Unused) { + this._usedInRuntime = new Map(); + forEachRuntime(runtime, runtime => + this._usedInRuntime.set(runtime, newValue) + ); + return true; + } + } else { + let changed = false; + forEachRuntime(runtime, runtime => { + /** @type {UsageStateType} */ + let oldValue = this._usedInRuntime.get(runtime); + if (oldValue === undefined) oldValue = UsageState.Unused; + if (newValue !== oldValue) { + if (newValue === UsageState.Unused) { + this._usedInRuntime.delete(runtime); + } else { + this._usedInRuntime.set(runtime, newValue); + } + changed = true; + } + }); + if (changed) { + if (this._usedInRuntime.size === 0) this._usedInRuntime = undefined; + return true; } } - const chunk = new Chunk(name, this._backCompat); - this.chunks.add(chunk); - if (this._backCompat) - ChunkGraph.setChunkGraphForChunk(chunk, this.chunkGraph); - if (name) { - this.namedChunks.set(name, chunk); - } - return chunk; + return false; } /** - * @deprecated - * @param {Module} module module to assign depth - * @returns {void} + * @param {any} key the key + * @returns {boolean} true, if something has changed */ - assignDepth(module) { - const moduleGraph = this.moduleGraph; - - const queue = new Set([module]); - let depth; - - moduleGraph.setDepth(module, 0); - - /** - * @param {Module} module module for processing - * @returns {void} - */ - const processModule = module => { - if (!moduleGraph.setDepthIfLower(module, depth)) return; - queue.add(module); - }; + unsetTarget(key) { + if (!this._target) return false; + if (this._target.delete(key)) { + this._maxTarget = undefined; + return true; + } + return false; + } - for (module of queue) { - queue.delete(module); - depth = moduleGraph.getDepth(module) + 1; + /** + * @param {any} key the key + * @param {ModuleGraphConnection} connection the target module if a single one + * @param {string[]=} exportName the exported name + * @param {number=} priority priority + * @returns {boolean} true, if something has changed + */ + setTarget(key, connection, exportName, priority = 0) { + if (exportName) exportName = [...exportName]; + if (!this._target) { + this._target = new Map(); + this._target.set(key, { connection, export: exportName, priority }); + return true; + } + const oldTarget = this._target.get(key); + if (!oldTarget) { + if (oldTarget === null && !connection) return false; + this._target.set(key, { connection, export: exportName, priority }); + this._maxTarget = undefined; + return true; + } + if ( + oldTarget.connection !== connection || + oldTarget.priority !== priority || + (exportName + ? !oldTarget.export || !equals(oldTarget.export, exportName) + : oldTarget.export) + ) { + oldTarget.connection = connection; + oldTarget.export = exportName; + oldTarget.priority = priority; + this._maxTarget = undefined; + return true; + } + return false; + } - for (const connection of moduleGraph.getOutgoingConnections(module)) { - const refModule = connection.module; - if (refModule) { - processModule(refModule); + /** + * @param {RuntimeSpec} runtime for this runtime + * @returns {UsageStateType} usage state + */ + getUsed(runtime) { + if (!this._hasUseInRuntimeInfo) return UsageState.NoInfo; + if (this._globalUsed !== undefined) return this._globalUsed; + if (this._usedInRuntime === undefined) { + return UsageState.Unused; + } else if (typeof runtime === "string") { + const value = this._usedInRuntime.get(runtime); + return value === undefined ? UsageState.Unused : value; + } else if (runtime === undefined) { + /** @type {UsageStateType} */ + let max = UsageState.Unused; + for (const value of this._usedInRuntime.values()) { + if (value === UsageState.Used) { + return UsageState.Used; + } + if (max < value) max = value; + } + return max; + } else { + /** @type {UsageStateType} */ + let max = UsageState.Unused; + for (const item of runtime) { + const value = this._usedInRuntime.get(item); + if (value !== undefined) { + if (value === UsageState.Used) { + return UsageState.Used; + } + if (max < value) max = value; } } + return max; } } /** - * @param {Set} modules module to assign depth - * @returns {void} + * get used name + * @param {string | undefined} fallbackName fallback name for used exports with no name + * @param {RuntimeSpec} runtime check usage for this runtime only + * @returns {string | false} used name */ - assignDepths(modules) { - const moduleGraph = this.moduleGraph; - - /** @type {Set} */ - const queue = new Set(modules); - queue.add(1); - let depth = 0; - - let i = 0; - for (const module of queue) { - i++; - if (typeof module === "number") { - depth = module; - if (queue.size === i) return; - queue.add(depth + 1); + getUsedName(fallbackName, runtime) { + if (this._hasUseInRuntimeInfo) { + if (this._globalUsed !== undefined) { + if (this._globalUsed === UsageState.Unused) return false; } else { - moduleGraph.setDepth(module, depth); - for (const { module: refModule } of moduleGraph.getOutgoingConnections( - module - )) { - if (refModule) { - queue.add(refModule); + if (this._usedInRuntime === undefined) return false; + if (typeof runtime === "string") { + if (!this._usedInRuntime.has(runtime)) { + return false; + } + } else if (runtime !== undefined) { + if ( + Array.from(runtime).every( + runtime => !this._usedInRuntime.has(runtime) + ) + ) { + return false; } } } } + if (this._usedName !== null) return this._usedName; + return this.name || fallbackName; } /** - * @param {Dependency} dependency the dependency - * @param {RuntimeSpec} runtime the runtime - * @returns {(string[] | ReferencedExport)[]} referenced exports + * @returns {boolean} true, when a mangled name of this export is set */ - getDependencyReferencedExports(dependency, runtime) { - const referencedExports = dependency.getReferencedExports( - this.moduleGraph, - runtime - ); - return this.hooks.dependencyReferencedExports.call( - referencedExports, - dependency, - runtime - ); + hasUsedName() { + return this._usedName !== null; } /** - * - * @param {Module} module module relationship for removal - * @param {DependenciesBlockLike} block //TODO: good description + * Sets the mangled name of this export + * @param {string} name the new name * @returns {void} */ - removeReasonsOfDependencyBlock(module, block) { - if (block.blocks) { - for (const b of block.blocks) { - this.removeReasonsOfDependencyBlock(module, b); - } - } + setUsedName(name) { + this._usedName = name; + } - if (block.dependencies) { - for (const dep of block.dependencies) { - const originalModule = this.moduleGraph.getModule(dep); - if (originalModule) { - this.moduleGraph.removeConnection(dep); + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target + * @returns {ExportInfo | ExportsInfo | undefined} the terminal binding export(s) info if known + */ + getTerminalBinding(moduleGraph, resolveTargetFilter = RETURNS_TRUE) { + if (this.terminalBinding) return this; + const target = this.getTarget(moduleGraph, resolveTargetFilter); + if (!target) return undefined; + const exportsInfo = moduleGraph.getExportsInfo(target.module); + if (!target.export) return exportsInfo; + return exportsInfo.getReadOnlyExportInfoRecursive(target.export); + } - if (this.chunkGraph) { - for (const chunk of this.chunkGraph.getModuleChunks( - originalModule - )) { - this.patchChunksAfterReasonRemoval(originalModule, chunk); - } - } - } + isReexport() { + return !this.terminalBinding && this._target && this._target.size > 0; + } + + _getMaxTarget() { + if (this._maxTarget !== undefined) return this._maxTarget; + if (this._target.size <= 1) return (this._maxTarget = this._target); + let maxPriority = -Infinity; + let minPriority = Infinity; + for (const { priority } of this._target.values()) { + if (maxPriority < priority) maxPriority = priority; + if (minPriority > priority) minPriority = priority; + } + // This should be very common + if (maxPriority === minPriority) return (this._maxTarget = this._target); + + // This is an edge case + const map = new Map(); + for (const [key, value] of this._target) { + if (maxPriority === value.priority) { + map.set(key, value); } } + this._maxTarget = map; + return map; } /** - * @param {Module} module module to patch tie - * @param {Chunk} chunk chunk to patch tie - * @returns {void} + * @param {ModuleGraph} moduleGraph the module graph + * @param {function(Module): boolean} validTargetModuleFilter a valid target module + * @returns {{ module: Module, export: string[] | undefined } | undefined | false} the target, undefined when there is no target, false when no target is valid */ - patchChunksAfterReasonRemoval(module, chunk) { - if (!module.hasReasons(this.moduleGraph, chunk.runtime)) { - this.removeReasonsOfDependencyBlock(module, module); - } - if (!module.hasReasonForChunk(chunk, this.moduleGraph, this.chunkGraph)) { - if (this.chunkGraph.isModuleInChunk(module, chunk)) { - this.chunkGraph.disconnectChunkAndModule(chunk, module); - this.removeChunkFromDependencies(module, chunk); + findTarget(moduleGraph, validTargetModuleFilter) { + return this._findTarget(moduleGraph, validTargetModuleFilter, new Set()); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {function(Module): boolean} validTargetModuleFilter a valid target module + * @param {Set | undefined} alreadyVisited set of already visited export info to avoid circular references + * @returns {{ module: Module, export: string[] | undefined } | undefined | false} the target, undefined when there is no target, false when no target is valid + */ + _findTarget(moduleGraph, validTargetModuleFilter, alreadyVisited) { + if (!this._target || this._target.size === 0) return undefined; + let rawTarget = this._getMaxTarget().values().next().value; + if (!rawTarget) return undefined; + /** @type {{ module: Module, export: string[] | undefined }} */ + let target = { + module: rawTarget.connection.module, + export: rawTarget.export + }; + for (;;) { + if (validTargetModuleFilter(target.module)) return target; + const exportsInfo = moduleGraph.getExportsInfo(target.module); + const exportInfo = exportsInfo.getExportInfo(target.export[0]); + if (alreadyVisited.has(exportInfo)) return null; + const newTarget = exportInfo._findTarget( + moduleGraph, + validTargetModuleFilter, + alreadyVisited + ); + if (!newTarget) return false; + if (target.export.length === 1) { + target = newTarget; + } else { + target = { + module: newTarget.module, + export: newTarget.export + ? newTarget.export.concat(target.export.slice(1)) + : target.export.slice(1) + }; } } } /** - * - * @param {DependenciesBlock} block block tie for Chunk - * @param {Chunk} chunk chunk to remove from dep - * @returns {void} + * @param {ModuleGraph} moduleGraph the module graph + * @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target + * @returns {{ module: Module, export: string[] | undefined } | undefined} the target */ - removeChunkFromDependencies(block, chunk) { + getTarget(moduleGraph, resolveTargetFilter = RETURNS_TRUE) { + const result = this._getTarget(moduleGraph, resolveTargetFilter, undefined); + if (result === CIRCULAR) return undefined; + return result; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {function({ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target + * @param {Set | undefined} alreadyVisited set of already visited export info to avoid circular references + * @returns {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined } | CIRCULAR | undefined} the target + */ + _getTarget(moduleGraph, resolveTargetFilter, alreadyVisited) { /** - * @param {Dependency} d dependency to (maybe) patch up + * @param {{ connection: ModuleGraphConnection, export: string[] | undefined } | null} inputTarget unresolved target + * @param {Set} alreadyVisited set of already visited export info to avoid circular references + * @returns {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined } | CIRCULAR | null} resolved target */ - const iteratorDependency = d => { - const depModule = this.moduleGraph.getModule(d); - if (!depModule) { - return; + const resolveTarget = (inputTarget, alreadyVisited) => { + if (!inputTarget) return null; + if (!inputTarget.export) { + return { + module: inputTarget.connection.module, + connection: inputTarget.connection, + export: undefined + }; } - this.patchChunksAfterReasonRemoval(depModule, chunk); - }; - - const blocks = block.blocks; - for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { - const asyncBlock = blocks[indexBlock]; - const chunkGroup = this.chunkGraph.getBlockChunkGroup(asyncBlock); - // Grab all chunks from the first Block's AsyncDepBlock - const chunks = chunkGroup.chunks; - // For each chunk in chunkGroup - for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { - const iteratedChunk = chunks[indexChunk]; - chunkGroup.removeChunk(iteratedChunk); - // Recurse - this.removeChunkFromDependencies(block, iteratedChunk); + /** @type {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }} */ + let target = { + module: inputTarget.connection.module, + connection: inputTarget.connection, + export: inputTarget.export + }; + if (!resolveTargetFilter(target)) return target; + let alreadyVisitedOwned = false; + for (;;) { + const exportsInfo = moduleGraph.getExportsInfo(target.module); + const exportInfo = exportsInfo.getExportInfo(target.export[0]); + if (!exportInfo) return target; + if (alreadyVisited.has(exportInfo)) return CIRCULAR; + const newTarget = exportInfo._getTarget( + moduleGraph, + resolveTargetFilter, + alreadyVisited + ); + if (newTarget === CIRCULAR) return CIRCULAR; + if (!newTarget) return target; + if (target.export.length === 1) { + target = newTarget; + if (!target.export) return target; + } else { + target = { + module: newTarget.module, + connection: newTarget.connection, + export: newTarget.export + ? newTarget.export.concat(target.export.slice(1)) + : target.export.slice(1) + }; + } + if (!resolveTargetFilter(target)) return target; + if (!alreadyVisitedOwned) { + alreadyVisited = new Set(alreadyVisited); + alreadyVisitedOwned = true; + } + alreadyVisited.add(exportInfo); } - } + }; - if (block.dependencies) { - for (const dep of block.dependencies) iteratorDependency(dep); + if (!this._target || this._target.size === 0) return undefined; + if (alreadyVisited && alreadyVisited.has(this)) return CIRCULAR; + const newAlreadyVisited = new Set(alreadyVisited); + newAlreadyVisited.add(this); + const values = this._getMaxTarget().values(); + const target = resolveTarget(values.next().value, newAlreadyVisited); + if (target === CIRCULAR) return CIRCULAR; + if (target === null) return undefined; + let result = values.next(); + while (!result.done) { + const t = resolveTarget(result.value, newAlreadyVisited); + if (t === CIRCULAR) return CIRCULAR; + if (t === null) return undefined; + if (t.module !== target.module) return undefined; + if (!t.export !== !target.export) return undefined; + if (target.export && !equals(t.export, target.export)) return undefined; + result = values.next(); } + return target; } - assignRuntimeIds() { - const { chunkGraph } = this; - const processEntrypoint = ep => { - const runtime = ep.options.runtime || ep.name; - const chunk = ep.getRuntimeChunk(); - chunkGraph.setRuntimeId(runtime, chunk.id); - }; - for (const ep of this.entrypoints.values()) { - processEntrypoint(ep); - } - for (const ep of this.asyncEntrypoints) { - processEntrypoint(ep); + /** + * Move the target forward as long resolveTargetFilter is fulfilled + * @param {ModuleGraph} moduleGraph the module graph + * @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target + * @param {function({ module: Module, export: string[] | undefined }): ModuleGraphConnection=} updateOriginalConnection updates the original connection instead of using the target connection + * @returns {{ module: Module, export: string[] | undefined } | undefined} the resolved target when moved + */ + moveTarget(moduleGraph, resolveTargetFilter, updateOriginalConnection) { + const target = this._getTarget(moduleGraph, resolveTargetFilter, undefined); + if (target === CIRCULAR) return undefined; + if (!target) return undefined; + const originalTarget = this._getMaxTarget().values().next().value; + if ( + originalTarget.connection === target.connection && + originalTarget.export === target.export + ) { + return undefined; } + this._target.clear(); + this._target.set(undefined, { + connection: updateOriginalConnection + ? updateOriginalConnection(target) + : target.connection, + export: target.export, + priority: 0 + }); + return target; } - sortItemsWithChunkIds() { - for (const chunkGroup of this.chunkGroups) { - chunkGroup.sortItems(); + createNestedExportsInfo() { + if (this.exportsInfoOwned) return this.exportsInfo; + this.exportsInfoOwned = true; + const oldExportsInfo = this.exportsInfo; + this.exportsInfo = new ExportsInfo(); + this.exportsInfo.setHasProvideInfo(); + if (oldExportsInfo) { + this.exportsInfo.setRedirectNamedTo(oldExportsInfo); } + return this.exportsInfo; + } - this.errors.sort(compareErrors); - this.warnings.sort(compareErrors); - this.children.sort(byNameOrHash); + getNestedExportsInfo() { + return this.exportsInfo; } - summarizeDependencies() { - for ( - let indexChildren = 0; - indexChildren < this.children.length; - indexChildren++ - ) { - const child = this.children[indexChildren]; + hasInfo(baseInfo, runtime) { + return ( + (this._usedName && this._usedName !== this.name) || + this.provided || + this.terminalBinding || + this.getUsed(runtime) !== baseInfo.getUsed(runtime) + ); + } - this.fileDependencies.addAll(child.fileDependencies); - this.contextDependencies.addAll(child.contextDependencies); - this.missingDependencies.addAll(child.missingDependencies); - this.buildDependencies.addAll(child.buildDependencies); - } + updateHash(hash, runtime) { + this._updateHash(hash, runtime, new Set()); + } - for (const module of this.modules) { - module.addCacheDependencies( - this.fileDependencies, - this.contextDependencies, - this.missingDependencies, - this.buildDependencies - ); + _updateHash(hash, runtime, alreadyVisitedExportsInfo) { + hash.update( + `${this._usedName || this.name}${this.getUsed(runtime)}${this.provided}${ + this.terminalBinding + }` + ); + if (this.exportsInfo && !alreadyVisitedExportsInfo.has(this.exportsInfo)) { + this.exportsInfo._updateHash(hash, runtime, alreadyVisitedExportsInfo); } } - createModuleHashes() { - let statModulesHashed = 0; - let statModulesFromCache = 0; - const { chunkGraph, runtimeTemplate, moduleMemCaches2 } = this; - const { hashFunction, hashDigest, hashDigestLength } = this.outputOptions; - for (const module of this.modules) { - const memCache = moduleMemCaches2 && moduleMemCaches2.get(module); - for (const runtime of chunkGraph.getModuleRuntimes(module)) { - if (memCache) { - const digest = memCache.get(`moduleHash-${getRuntimeKey(runtime)}`); - if (digest !== undefined) { - chunkGraph.setModuleHashes( - module, - runtime, - digest, - digest.substr(0, hashDigestLength) - ); - statModulesFromCache++; - continue; - } - } - statModulesHashed++; - const digest = this._createModuleHash( - module, - chunkGraph, - runtime, - hashFunction, - runtimeTemplate, - hashDigest, - hashDigestLength - ); - if (memCache) { - memCache.set(`moduleHash-${getRuntimeKey(runtime)}`, digest); - } - } - } - this.logger.log( - `${statModulesHashed} modules hashed, ${statModulesFromCache} from cache (${ - Math.round( - (100 * (statModulesHashed + statModulesFromCache)) / this.modules.size - ) / 100 - } variants per module in average)` - ); - } - - _createModuleHash( - module, - chunkGraph, - runtime, - hashFunction, - runtimeTemplate, - hashDigest, - hashDigestLength - ) { - const moduleHash = createHash(hashFunction); - module.updateHash(moduleHash, { - chunkGraph, - runtime, - runtimeTemplate - }); - const moduleHashDigest = /** @type {string} */ ( - moduleHash.digest(hashDigest) - ); - chunkGraph.setModuleHashes( - module, - runtime, - moduleHashDigest, - moduleHashDigest.substr(0, hashDigestLength) - ); - return moduleHashDigest; - } - - createHash() { - this.logger.time("hashing: initialize hash"); - const chunkGraph = this.chunkGraph; - const runtimeTemplate = this.runtimeTemplate; - const outputOptions = this.outputOptions; - const hashFunction = outputOptions.hashFunction; - const hashDigest = outputOptions.hashDigest; - const hashDigestLength = outputOptions.hashDigestLength; - const hash = createHash(hashFunction); - if (outputOptions.hashSalt) { - hash.update(outputOptions.hashSalt); - } - this.logger.timeEnd("hashing: initialize hash"); - if (this.children.length > 0) { - this.logger.time("hashing: hash child compilations"); - for (const child of this.children) { - hash.update(child.hash); + getUsedInfo() { + if (this._globalUsed !== undefined) { + switch (this._globalUsed) { + case UsageState.Unused: + return "unused"; + case UsageState.NoInfo: + return "no usage info"; + case UsageState.Unknown: + return "maybe used (runtime-defined)"; + case UsageState.Used: + return "used"; + case UsageState.OnlyPropertiesUsed: + return "only properties used"; } - this.logger.timeEnd("hashing: hash child compilations"); - } - if (this.warnings.length > 0) { - this.logger.time("hashing: hash warnings"); - for (const warning of this.warnings) { - hash.update(`${warning.message}`); + } else if (this._usedInRuntime !== undefined) { + /** @type {Map} */ + const map = new Map(); + for (const [runtime, used] of this._usedInRuntime) { + const list = map.get(used); + if (list !== undefined) list.push(runtime); + else map.set(used, [runtime]); } - this.logger.timeEnd("hashing: hash warnings"); - } - if (this.errors.length > 0) { - this.logger.time("hashing: hash errors"); - for (const error of this.errors) { - hash.update(`${error.message}`); + const specificInfo = Array.from(map, ([used, runtimes]) => { + switch (used) { + case UsageState.NoInfo: + return `no usage info in ${runtimes.join(", ")}`; + case UsageState.Unknown: + return `maybe used in ${runtimes.join(", ")} (runtime-defined)`; + case UsageState.Used: + return `used in ${runtimes.join(", ")}`; + case UsageState.OnlyPropertiesUsed: + return `only properties used in ${runtimes.join(", ")}`; + } + }); + if (specificInfo.length > 0) { + return specificInfo.join("; "); } - this.logger.timeEnd("hashing: hash errors"); } + return this._hasUseInRuntimeInfo ? "unused" : "no usage info"; + } - this.logger.time("hashing: sort chunks"); - /* - * all non-runtime chunks need to be hashes first, - * since runtime chunk might use their hashes. - * runtime chunks need to be hashed in the correct order - * since they may depend on each other (for async entrypoints). - * So we put all non-runtime chunks first and hash them in any order. - * And order runtime chunks according to referenced between each other. - * Chunks need to be in deterministic order since we add hashes to full chunk - * during these hashing. - */ - /** @type {Chunk[]} */ - const unorderedRuntimeChunks = []; - /** @type {Chunk[]} */ - const otherChunks = []; - for (const c of this.chunks) { - if (c.hasRuntime()) { - unorderedRuntimeChunks.push(c); - } else { - otherChunks.push(c); - } + getProvidedInfo() { + switch (this.provided) { + case undefined: + return "no provided info"; + case null: + return "maybe provided (runtime-defined)"; + case true: + return "provided"; + case false: + return "not provided"; } - unorderedRuntimeChunks.sort(byId); - otherChunks.sort(byId); + } - /** @typedef {{ chunk: Chunk, referencedBy: RuntimeChunkInfo[], remaining: number }} RuntimeChunkInfo */ - /** @type {Map} */ - const runtimeChunksMap = new Map(); - for (const chunk of unorderedRuntimeChunks) { - runtimeChunksMap.set(chunk, { - chunk, - referencedBy: [], - remaining: 0 - }); - } - let remaining = 0; - for (const info of runtimeChunksMap.values()) { - for (const other of new Set( - Array.from(info.chunk.getAllReferencedAsyncEntrypoints()).map( - e => e.chunks[e.chunks.length - 1] - ) - )) { - const otherInfo = runtimeChunksMap.get(other); - otherInfo.referencedBy.push(info); - info.remaining++; - remaining++; - } - } - /** @type {Chunk[]} */ - const runtimeChunks = []; - for (const info of runtimeChunksMap.values()) { - if (info.remaining === 0) { - runtimeChunks.push(info.chunk); - } + getRenameInfo() { + if (this._usedName !== null && this._usedName !== this.name) { + return `renamed to ${JSON.stringify(this._usedName).slice(1, -1)}`; } - // If there are any references between chunks - // make sure to follow these chains - if (remaining > 0) { - const readyChunks = []; - for (const chunk of runtimeChunks) { - const hasFullHashModules = - chunkGraph.getNumberOfChunkFullHashModules(chunk) !== 0; - const info = runtimeChunksMap.get(chunk); - for (const otherInfo of info.referencedBy) { - if (hasFullHashModules) { - chunkGraph.upgradeDependentToFullHashModules(otherInfo.chunk); - } - remaining--; - if (--otherInfo.remaining === 0) { - readyChunks.push(otherInfo.chunk); - } + switch (this.canMangleProvide) { + case undefined: + switch (this.canMangleUse) { + case undefined: + return "missing provision and use info prevents renaming"; + case false: + return "usage prevents renaming (no provision info)"; + case true: + return "missing provision info prevents renaming"; } - if (readyChunks.length > 0) { - // This ensures deterministic ordering, since referencedBy is non-deterministic - readyChunks.sort(byId); - for (const c of readyChunks) runtimeChunks.push(c); - readyChunks.length = 0; + break; + case true: + switch (this.canMangleUse) { + case undefined: + return "missing usage info prevents renaming"; + case false: + return "usage prevents renaming"; + case true: + return "could be renamed"; } - } - } - // If there are still remaining references we have cycles and want to create a warning - if (remaining > 0) { - let circularRuntimeChunkInfo = []; - for (const info of runtimeChunksMap.values()) { - if (info.remaining !== 0) { - circularRuntimeChunkInfo.push(info); + break; + case false: + switch (this.canMangleUse) { + case undefined: + return "provision prevents renaming (no use info)"; + case false: + return "usage and provision prevents renaming"; + case true: + return "provision prevents renaming"; } - } - circularRuntimeChunkInfo.sort(compareSelect(i => i.chunk, byId)); - const err = - new WebpackError(`Circular dependency between chunks with runtime (${Array.from( - circularRuntimeChunkInfo, - c => c.chunk.name || c.chunk.id - ).join(", ")}) -This prevents using hashes of each other and should be avoided.`); - err.chunk = circularRuntimeChunkInfo[0].chunk; - this.warnings.push(err); - for (const i of circularRuntimeChunkInfo) runtimeChunks.push(i.chunk); + break; } - this.logger.timeEnd("hashing: sort chunks"); + throw new Error( + `Unexpected flags for getRenameInfo ${this.canMangleProvide} ${this.canMangleUse}` + ); + } +} - const fullHashChunks = new Set(); - /** @type {{module: Module, hash: string, runtime: RuntimeSpec, runtimes: RuntimeSpec[]}[]} */ - const codeGenerationJobs = []; - /** @type {Map>} */ - const codeGenerationJobsMap = new Map(); +module.exports = ExportsInfo; +module.exports.ExportInfo = ExportInfo; +module.exports.UsageState = UsageState; - const processChunk = chunk => { - // Last minute module hash generation for modules that depend on chunk hashes - this.logger.time("hashing: hash runtime modules"); - const runtime = chunk.runtime; - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - if (!chunkGraph.hasModuleHashes(module, runtime)) { - const hash = this._createModuleHash( - module, - chunkGraph, - runtime, - hashFunction, - runtimeTemplate, - hashDigest, - hashDigestLength - ); - let hashMap = codeGenerationJobsMap.get(hash); - if (hashMap) { - const moduleJob = hashMap.get(module); - if (moduleJob) { - moduleJob.runtimes.push(runtime); - continue; - } - } else { - hashMap = new Map(); - codeGenerationJobsMap.set(hash, hashMap); - } - const job = { - module, - hash, - runtime, - runtimes: [runtime] - }; - hashMap.set(module, job); - codeGenerationJobs.push(job); - } - } - this.logger.timeAggregate("hashing: hash runtime modules"); - this.logger.time("hashing: hash chunks"); - const chunkHash = createHash(hashFunction); - try { - if (outputOptions.hashSalt) { - chunkHash.update(outputOptions.hashSalt); - } - chunk.updateHash(chunkHash, chunkGraph); - this.hooks.chunkHash.call(chunk, chunkHash, { - chunkGraph, - moduleGraph: this.moduleGraph, - runtimeTemplate: this.runtimeTemplate - }); - const chunkHashDigest = /** @type {string} */ ( - chunkHash.digest(hashDigest) - ); - hash.update(chunkHashDigest); - chunk.hash = chunkHashDigest; - chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); - const fullHashModules = - chunkGraph.getChunkFullHashModulesIterable(chunk); - if (fullHashModules) { - fullHashChunks.add(chunk); - } else { - this.hooks.contentHash.call(chunk); - } - } catch (err) { - this.errors.push(new ChunkRenderError(chunk, "", err)); - } - this.logger.timeAggregate("hashing: hash chunks"); - }; - otherChunks.forEach(processChunk); - for (const chunk of runtimeChunks) processChunk(chunk); - this.logger.timeAggregateEnd("hashing: hash runtime modules"); - this.logger.timeAggregateEnd("hashing: hash chunks"); - this.logger.time("hashing: hash digest"); - this.hooks.fullHash.call(hash); - this.fullHash = /** @type {string} */ (hash.digest(hashDigest)); - this.hash = this.fullHash.substr(0, hashDigestLength); - this.logger.timeEnd("hashing: hash digest"); +/***/ }), + +/***/ 7145: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - this.logger.time("hashing: process full hash modules"); - for (const chunk of fullHashChunks) { - for (const module of chunkGraph.getChunkFullHashModulesIterable(chunk)) { - const moduleHash = createHash(hashFunction); - module.updateHash(moduleHash, { - chunkGraph, - runtime: chunk.runtime, - runtimeTemplate - }); - const moduleHashDigest = /** @type {string} */ ( - moduleHash.digest(hashDigest) - ); - const oldHash = chunkGraph.getModuleHash(module, chunk.runtime); - chunkGraph.setModuleHashes( - module, - chunk.runtime, - moduleHashDigest, - moduleHashDigest.substr(0, hashDigestLength) - ); - codeGenerationJobsMap.get(oldHash).get(module).hash = moduleHashDigest; - } - const chunkHash = createHash(hashFunction); - chunkHash.update(chunk.hash); - chunkHash.update(this.hash); - const chunkHashDigest = /** @type {string} */ ( - chunkHash.digest(hashDigest) - ); - chunk.hash = chunkHashDigest; - chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); - this.hooks.contentHash.call(chunk); - } - this.logger.timeEnd("hashing: process full hash modules"); - return codeGenerationJobs; - } + +const ConstDependency = __webpack_require__(76911); +const ExportsInfoDependency = __webpack_require__(78988); + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ + +class ExportsInfoApiPlugin { /** - * @param {string} file file name - * @param {Source} source asset source - * @param {AssetInfo} assetInfo extra asset information + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - emitAsset(file, source, assetInfo = {}) { - if (this.assets[file]) { - if (!isSourceEqual(this.assets[file], source)) { - this.errors.push( - new WebpackError( - `Conflict: Multiple assets emit different content to the same filename ${file}` - ) + apply(compiler) { + compiler.hooks.compilation.tap( + "ExportsInfoApiPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ExportsInfoDependency, + new ExportsInfoDependency.Template() ); - this.assets[file] = source; - this._setAssetInfo(file, assetInfo); - return; + /** + * @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); } - const oldInfo = this.assetsInfo.get(file); - const newInfo = Object.assign({}, oldInfo, assetInfo); - this._setAssetInfo(file, newInfo, oldInfo); - return; - } - this.assets[file] = source; - this._setAssetInfo(file, assetInfo, undefined); + ); } +} - _setAssetInfo(file, newInfo, oldInfo = this.assetsInfo.get(file)) { - if (newInfo === undefined) { - this.assetsInfo.delete(file); - } else { - this.assetsInfo.set(file, newInfo); - } - const oldRelated = oldInfo && oldInfo.related; - const newRelated = newInfo && newInfo.related; - if (oldRelated) { - for (const key of Object.keys(oldRelated)) { - const remove = name => { - const relatedIn = this._assetsRelatedIn.get(name); - if (relatedIn === undefined) return; - const entry = relatedIn.get(key); - if (entry === undefined) return; - entry.delete(file); - if (entry.size !== 0) return; - relatedIn.delete(key); - if (relatedIn.size === 0) this._assetsRelatedIn.delete(name); - }; - const entry = oldRelated[key]; - if (Array.isArray(entry)) { - entry.forEach(remove); - } else if (entry) { - remove(entry); - } - } - } - if (newRelated) { - for (const key of Object.keys(newRelated)) { - const add = name => { - let relatedIn = this._assetsRelatedIn.get(name); - if (relatedIn === undefined) { - this._assetsRelatedIn.set(name, (relatedIn = new Map())); - } - let entry = relatedIn.get(key); - if (entry === undefined) { - relatedIn.set(key, (entry = new Set())); - } - entry.add(file); - }; - const entry = newRelated[key]; - if (Array.isArray(entry)) { - entry.forEach(add); - } else if (entry) { - add(entry); - } - } - } +module.exports = ExportsInfoApiPlugin; + + +/***/ }), + +/***/ 73071: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { OriginalSource, RawSource } = __webpack_require__(51255); +const ConcatenationScope = __webpack_require__(98229); +const { UsageState } = __webpack_require__(63686); +const InitFragment = __webpack_require__(55870); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const StaticExportsDependency = __webpack_require__(91418); +const createHash = __webpack_require__(49835); +const extractUrlAndGlobal = __webpack_require__(11850); +const makeSerializable = __webpack_require__(33032); +const propertyAccess = __webpack_require__(54190); +const { register } = __webpack_require__(8282); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./ExportsInfo")} ExportsInfo */ +/** @typedef {import("./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("./NormalModuleFactory")} NormalModuleFactory */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {typeof import("./util/Hash")} HashConstructor */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @typedef {Object} SourceData + * @property {boolean=} iife + * @property {string=} init + * @property {string} expression + * @property {InitFragment[]=} chunkInitFragments + * @property {ReadonlySet=} runtimeRequirements + */ + +const TYPES = new Set(["javascript"]); +const CSS_TYPES = new Set(["css-import"]); +const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); +const RUNTIME_REQUIREMENTS_FOR_SCRIPT = new Set([RuntimeGlobals.loadScript]); +const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([ + RuntimeGlobals.definePropertyGetters +]); +const EMPTY_RUNTIME_REQUIREMENTS = new Set([]); + +/** + * @param {string|string[]} variableName the variable name or path + * @param {string} type the module system + * @returns {SourceData} the generated source + */ +const getSourceForGlobalVariableExternal = (variableName, type) => { + if (!Array.isArray(variableName)) { + // make it an array as the look up works the same basically + variableName = [variableName]; } - /** - * @param {string} file file name - * @param {Source | function(Source): Source} newSourceOrFunction new asset source or function converting old to new - * @param {AssetInfo | function(AssetInfo | undefined): AssetInfo} assetInfoUpdateOrFunction new asset info or function converting old to new - */ - updateAsset( - file, - newSourceOrFunction, - assetInfoUpdateOrFunction = undefined - ) { - if (!this.assets[file]) { - throw new Error( - `Called Compilation.updateAsset for not existing filename ${file}` - ); - } - if (typeof newSourceOrFunction === "function") { - this.assets[file] = newSourceOrFunction(this.assets[file]); - } else { - this.assets[file] = newSourceOrFunction; - } - if (assetInfoUpdateOrFunction !== undefined) { - const oldInfo = this.assetsInfo.get(file) || EMPTY_ASSET_INFO; - if (typeof assetInfoUpdateOrFunction === "function") { - this._setAssetInfo(file, assetInfoUpdateOrFunction(oldInfo), oldInfo); - } else { - this._setAssetInfo( - file, - cachedCleverMerge(oldInfo, assetInfoUpdateOrFunction), - oldInfo - ); - } - } + // 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 + )}` + }; +}; - renameAsset(file, newFile) { - const source = this.assets[file]; - if (!source) { - throw new Error( - `Called Compilation.renameAsset for not existing filename ${file}` - ); - } - if (this.assets[newFile]) { - if (!isSourceEqual(this.assets[file], source)) { - this.errors.push( - new WebpackError( - `Conflict: Called Compilation.renameAsset for already existing filename ${newFile} with different content` - ) - ); - } - } - const assetInfo = this.assetsInfo.get(file); - // Update related in all other assets - const relatedInInfo = this._assetsRelatedIn.get(file); - if (relatedInInfo) { - for (const [key, assets] of relatedInInfo) { - for (const name of assets) { - const info = this.assetsInfo.get(name); - if (!info) continue; - const related = info.related; - if (!related) continue; - const entry = related[key]; - let newEntry; - if (Array.isArray(entry)) { - newEntry = entry.map(x => (x === file ? newFile : x)); - } else if (entry === file) { - newEntry = newFile; - } else continue; - this.assetsInfo.set(name, { - ...info, - related: { - ...related, - [key]: newEntry - } - }); - } - } - } - this._setAssetInfo(file, undefined, assetInfo); - this._setAssetInfo(newFile, assetInfo); - delete this.assets[file]; - this.assets[newFile] = source; - for (const chunk of this.chunks) { - { - const size = chunk.files.size; - chunk.files.delete(file); - if (size !== chunk.files.size) { - chunk.files.add(newFile); - } - } - { - const size = chunk.auxiliaryFiles.size; - chunk.auxiliaryFiles.delete(file); - if (size !== chunk.auxiliaryFiles.size) { - chunk.auxiliaryFiles.add(newFile); - } - } - } +/** + * @param {string|string[]} moduleAndSpecifiers the module request + * @returns {SourceData} the generated source + */ +const getSourceForCommonJsExternalInNodeModule = moduleAndSpecifiers => { + const chunkInitFragments = [ + new InitFragment( + 'import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module";\n', + InitFragment.STAGE_HARMONY_IMPORTS, + 0, + "external module node-commonjs" + ) + ]; + if (!Array.isArray(moduleAndSpecifiers)) { + return { + expression: `__WEBPACK_EXTERNAL_createRequire(import.meta.url)(${JSON.stringify( + moduleAndSpecifiers + )})`, + chunkInitFragments + }; } + const moduleName = moduleAndSpecifiers[0]; + return { + expression: `__WEBPACK_EXTERNAL_createRequire(import.meta.url)(${JSON.stringify( + moduleName + )})${propertyAccess(moduleAndSpecifiers, 1)}`, + chunkInitFragments + }; +}; - /** - * @param {string} file file name - */ - deleteAsset(file) { - if (!this.assets[file]) { - return; - } - delete this.assets[file]; - const assetInfo = this.assetsInfo.get(file); - this._setAssetInfo(file, undefined, assetInfo); - const related = assetInfo && assetInfo.related; - if (related) { - for (const key of Object.keys(related)) { - const checkUsedAndDelete = file => { - if (!this._assetsRelatedIn.has(file)) { - this.deleteAsset(file); - } - }; - const items = related[key]; - if (Array.isArray(items)) { - items.forEach(checkUsedAndDelete); - } else if (items) { - checkUsedAndDelete(items); - } - } - } - // TODO If this becomes a performance problem - // store a reverse mapping from asset to chunk - for (const chunk of this.chunks) { - chunk.files.delete(file); - chunk.auxiliaryFiles.delete(file); - } +/** + * @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" + )});` + }; +}; - getAssets() { - /** @type {Readonly[]} */ - const array = []; - for (const assetName of Object.keys(this.assets)) { - if (Object.prototype.hasOwnProperty.call(this.assets, assetName)) { - array.push({ - name: assetName, - source: this.assets[assetName], - info: this.assetsInfo.get(assetName) || EMPTY_ASSET_INFO - }); +class ModuleExternalInitFragment extends InitFragment { + /** + * @param {string} request import source + * @param {string=} ident recomputed ident + * @param {string | HashConstructor=} hashFunction the hash function to use + */ + constructor(request, ident, hashFunction = "md4") { + if (ident === undefined) { + ident = Template.toIdentifier(request); + if (ident !== request) { + ident += `_${createHash(hashFunction) + .update(request) + .digest("hex") + .slice(0, 8)}`; } } - return array; + const identifier = `__WEBPACK_EXTERNAL_MODULE_${ident}__`; + super( + `import * as ${identifier} from ${JSON.stringify(request)};\n`, + InitFragment.STAGE_HARMONY_IMPORTS, + 0, + `external module import ${ident}` + ); + this._ident = ident; + this._identifier = identifier; + this._request = request; } - /** - * @param {string} name the name of the asset - * @returns {Readonly | undefined} the asset or undefined when not found - */ - getAsset(name) { - if (!Object.prototype.hasOwnProperty.call(this.assets, name)) - return undefined; - return { - name, - source: this.assets[name], - info: this.assetsInfo.get(name) || EMPTY_ASSET_INFO - }; + getNamespaceIdentifier() { + return this._identifier; } +} - clearAssets() { - for (const chunk of this.chunks) { - chunk.files.clear(); - chunk.auxiliaryFiles.clear(); +register( + ModuleExternalInitFragment, + "webpack/lib/ExternalModule", + "ModuleExternalInitFragment", + { + serialize(obj, { write }) { + write(obj._request); + write(obj._ident); + }, + deserialize({ read }) { + return new ModuleExternalInitFragment(read(), read()); } } +); - createModuleAssets() { - const { chunkGraph } = this; - for (const module of this.modules) { - if (module.buildInfo.assets) { - const assetsInfo = module.buildInfo.assetsInfo; - for (const assetName of Object.keys(module.buildInfo.assets)) { - const fileName = this.getPath(assetName, { - chunkGraph: this.chunkGraph, - module - }); - for (const chunk of chunkGraph.getModuleChunksIterable(module)) { - chunk.auxiliaryFiles.add(fileName); - } - this.emitAsset( - fileName, - module.buildInfo.assets[assetName], - assetsInfo ? assetsInfo.get(assetName) : undefined - ); - this.hooks.moduleAsset.call(module, fileName); +const generateModuleRemapping = (input, exportsInfo, runtime) => { + if (exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused) { + const properties = []; + for (const exportInfo of exportsInfo.orderedExports) { + const used = exportInfo.getUsedName(exportInfo.name, runtime); + if (!used) continue; + const nestedInfo = exportInfo.getNestedExportsInfo(); + if (nestedInfo) { + const nestedExpr = generateModuleRemapping( + `${input}${propertyAccess([exportInfo.name])}`, + nestedInfo + ); + if (nestedExpr) { + properties.push(`[${JSON.stringify(used)}]: y(${nestedExpr})`); + continue; } } + properties.push( + `[${JSON.stringify(used)}]: () => ${input}${propertyAccess([ + exportInfo.name + ])}` + ); } + return `x({ ${properties.join(", ")} })`; } +}; - /** - * @param {RenderManifestOptions} options options object - * @returns {RenderManifestEntry[]} manifest entries - */ - getRenderManifest(options) { - return this.hooks.renderManifest.call([], options); +/** + * @param {string|string[]} moduleAndSpecifiers the module request + * @param {ExportsInfo} exportsInfo exports info of this module + * @param {RuntimeSpec} runtime the runtime + * @param {string | HashConstructor=} hashFunction the hash function to use + * @returns {SourceData} the generated source + */ +const getSourceForModuleExternal = ( + moduleAndSpecifiers, + exportsInfo, + runtime, + hashFunction +) => { + if (!Array.isArray(moduleAndSpecifiers)) + moduleAndSpecifiers = [moduleAndSpecifiers]; + const initFragment = new ModuleExternalInitFragment( + moduleAndSpecifiers[0], + undefined, + hashFunction + ); + const baseAccess = `${initFragment.getNamespaceIdentifier()}${propertyAccess( + moduleAndSpecifiers, + 1 + )}`; + const moduleRemapping = generateModuleRemapping( + baseAccess, + exportsInfo, + runtime + ); + let expression = moduleRemapping || baseAccess; + return { + expression, + init: `var x = y => { var x = {}; ${RuntimeGlobals.definePropertyGetters}(x, y); return x; }\nvar y = x => () => x`, + runtimeRequirements: moduleRemapping + ? RUNTIME_REQUIREMENTS_FOR_MODULE + : undefined, + chunkInitFragments: [initFragment] + }; +}; + +/** + * @param {string|string[]} urlAndGlobal the script request + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @returns {SourceData} the generated source + */ +const getSourceForScriptExternal = (urlAndGlobal, runtimeTemplate) => { + if (typeof urlAndGlobal === "string") { + urlAndGlobal = extractUrlAndGlobal(urlAndGlobal); } + const url = urlAndGlobal[0]; + const globalName = urlAndGlobal[1]; + return { + init: "var __webpack_error__ = new Error();", + expression: `new Promise(${runtimeTemplate.basicFunction( + "resolve, reject", + [ + `if(typeof ${globalName} !== "undefined") return resolve();`, + `${RuntimeGlobals.loadScript}(${JSON.stringify( + url + )}, ${runtimeTemplate.basicFunction("event", [ + `if(typeof ${globalName} !== "undefined") return resolve();`, + "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", + "var realSrc = event && event.target && event.target.src;", + "__webpack_error__.message = 'Loading script failed.\\n(' + errorType + ': ' + realSrc + ')';", + "__webpack_error__.name = 'ScriptExternalLoadError';", + "__webpack_error__.type = errorType;", + "__webpack_error__.request = realSrc;", + "reject(__webpack_error__);" + ])}, ${JSON.stringify(globalName)});` + ] + )}).then(${runtimeTemplate.returningFunction( + `${globalName}${propertyAccess(urlAndGlobal, 2)}` + )})`, + runtimeRequirements: RUNTIME_REQUIREMENTS_FOR_SCRIPT + }; +}; - /** - * @param {Callback} callback signals when the call finishes - * @returns {void} - */ - createChunkAssets(callback) { - const outputOptions = this.outputOptions; - const cachedSourceMap = new WeakMap(); - /** @type {Map} */ - const alreadyWrittenFiles = new Map(); +/** + * @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`; +}; - asyncLib.forEachLimit( - this.chunks, - 15, - (chunk, callback) => { - /** @type {RenderManifestEntry[]} */ - let manifest; - try { - manifest = this.getRenderManifest({ - chunk, - hash: this.hash, - fullHash: this.fullHash, - outputOptions, - codeGenerationResults: this.codeGenerationResults, - moduleTemplates: this.moduleTemplates, - dependencyTemplates: this.dependencyTemplates, - chunkGraph: this.chunkGraph, - moduleGraph: this.moduleGraph, - runtimeTemplate: this.runtimeTemplate - }); - } catch (err) { - this.errors.push(new ChunkRenderError(chunk, "", err)); - return callback(); - } - asyncLib.forEach( - manifest, - (fileManifest, callback) => { - const ident = fileManifest.identifier; - const usedHash = fileManifest.hash; - - const assetCacheItem = this._assetsCache.getItemCache( - ident, - usedHash - ); - - assetCacheItem.get((err, sourceFromCache) => { - /** @type {string | function(PathData, AssetInfo=): string} */ - let filenameTemplate; - /** @type {string} */ - let file; - /** @type {AssetInfo} */ - let assetInfo; - - let inTry = true; - const errorAndCallback = err => { - const filename = - file || - (typeof file === "string" - ? file - : typeof filenameTemplate === "string" - ? filenameTemplate - : ""); - - this.errors.push(new ChunkRenderError(chunk, filename, err)); - inTry = false; - return callback(); - }; - - try { - if ("filename" in fileManifest) { - file = fileManifest.filename; - assetInfo = fileManifest.info; - } else { - filenameTemplate = fileManifest.filenameTemplate; - const pathAndInfo = this.getPathWithInfo( - filenameTemplate, - fileManifest.pathOptions - ); - file = pathAndInfo.path; - assetInfo = fileManifest.info - ? { - ...pathAndInfo.info, - ...fileManifest.info - } - : pathAndInfo.info; - } +/** + * @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 + }; +}; - if (err) { - return errorAndCallback(err); - } +/** + * @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]; + } - let source = sourceFromCache; + const variableName = request[0]; + const objectLookup = propertyAccess(request, 1); + return { + init: optional + ? checkExternalVariable(variableName, request.join("."), runtimeTemplate) + : undefined, + expression: `${variableName}${objectLookup}` + }; +}; - // check if the same filename was already written by another chunk - const alreadyWritten = alreadyWrittenFiles.get(file); - if (alreadyWritten !== undefined) { - if (alreadyWritten.hash !== usedHash) { - inTry = false; - return callback( - new WebpackError( - `Conflict: Multiple chunks emit assets to the same filename ${file}` + - ` (chunks ${alreadyWritten.chunk.id} and ${chunk.id})` - ) - ); - } else { - source = alreadyWritten.source; - } - } else if (!source) { - // render the asset - source = fileManifest.render(); +class ExternalModule extends Module { + constructor(request, type, userRequest) { + super("javascript/dynamic", null); - // Ensure that source is a cached source to avoid additional cost because of repeated access - if (!(source instanceof CachedSource)) { - const cacheEntry = cachedSourceMap.get(source); - if (cacheEntry) { - source = cacheEntry; - } else { - const cachedSource = new CachedSource(source); - cachedSourceMap.set(source, cachedSource); - source = cachedSource; - } - } - } - this.emitAsset(file, source, assetInfo); - if (fileManifest.auxiliary) { - chunk.auxiliaryFiles.add(file); - } else { - chunk.files.add(file); - } - this.hooks.chunkAsset.call(chunk, file); - alreadyWrittenFiles.set(file, { - hash: usedHash, - source, - chunk - }); - if (source !== sourceFromCache) { - assetCacheItem.store(source, err => { - if (err) return errorAndCallback(err); - inTry = false; - return callback(); - }); - } else { - inTry = false; - callback(); - } - } catch (err) { - if (!inTry) throw err; - errorAndCallback(err); - } - }); - }, - callback - ); - }, - callback - ); + // Info from Factory + /** @type {string | string[] | Record} */ + this.request = request; + /** @type {string} */ + this.externalType = type; + /** @type {string} */ + this.userRequest = userRequest; } /** - * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash - * @param {PathData} data context data - * @returns {string} interpolated path + * @returns {Set} types available (do not mutate) */ - getPath(filename, data = {}) { - if (!data.hash) { - data = { - hash: this.hash, - ...data - }; - } - return this.getAssetPath(filename, data); + getSourceTypes() { + return this.externalType === "css-import" ? CSS_TYPES : TYPES; } /** - * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash - * @param {PathData} data context data - * @returns {{ path: string, info: AssetInfo }} interpolated path and asset info + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion */ - getPathWithInfo(filename, data = {}) { - if (!data.hash) { - data = { - hash: this.hash, - ...data - }; - } - return this.getAssetPathWithInfo(filename, data); + libIdent(options) { + return this.userRequest; } /** - * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash - * @param {PathData} data context data - * @returns {string} interpolated path + * @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 */ - getAssetPath(filename, data) { - return this.hooks.assetPath.call( - typeof filename === "function" ? filename(data) : filename, - data, - undefined - ); + chunkCondition(chunk, { chunkGraph }) { + return this.externalType === "css-import" + ? true + : chunkGraph.getNumberOfEntryModules(chunk) > 0; } /** - * @param {string | function(PathData, AssetInfo=): string} filename used to get asset path with hash - * @param {PathData} data context data - * @returns {{ path: string, info: AssetInfo }} interpolated path and asset info + * @returns {string} a unique identifier of the module */ - getAssetPathWithInfo(filename, data) { - const assetInfo = {}; - // TODO webpack 5: refactor assetPath hook to receive { path, info } object - const newPath = this.hooks.assetPath.call( - typeof filename === "function" ? filename(data, assetInfo) : filename, - data, - assetInfo - ); - return { path: newPath, info: assetInfo }; - } - - getWarnings() { - return this.hooks.processWarnings.call(this.warnings); + identifier() { + return `external ${this.externalType} ${JSON.stringify(this.request)}`; } - getErrors() { - return this.hooks.processErrors.call(this.errors); + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return "external " + JSON.stringify(this.request); } /** - * This function allows you to run another instance of webpack inside of webpack however as - * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins - * from parent (or top level compiler) and creates a child Compilation - * - * @param {string} name name of the child compiler - * @param {OutputOptions=} outputOptions // Need to convert config schema to types for this - * @param {Array=} plugins webpack plugins that will be applied - * @returns {Compiler} creates a child Compiler instance + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} */ - createChildCompiler(name, outputOptions, plugins) { - const idx = this.childrenCounters[name] || 0; - this.childrenCounters[name] = idx + 1; - return this.compiler.createChildCompiler( - this, - name, - idx, - outputOptions, - plugins - ); + needBuild(context, callback) { + return callback(null, !this.buildMeta); } /** - * @param {Module} module the module - * @param {ExecuteModuleOptions} options options - * @param {ExecuteModuleCallback} callback callback + * @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} */ - executeModule(module, options, callback) { - // Aggregate all referenced modules and ensure they are ready - const modules = new Set([module]); - processAsyncTree( - modules, - 10, - /** - * @param {Module} module the module - * @param {function(Module): void} push push more jobs - * @param {Callback} callback callback - * @returns {void} - */ - (module, push, callback) => { - this.buildQueue.waitFor(module, err => { - if (err) return callback(err); - this.processDependenciesQueue.waitFor(module, err => { - if (err) return callback(err); - for (const { module: m } of this.moduleGraph.getOutgoingConnections( - module - )) { - const size = modules.size; - modules.add(m); - if (modules.size !== size) push(m); - } - callback(); - }); - }); - }, - err => { - if (err) return callback(err); - - // Create new chunk graph, chunk and entrypoint for the build time execution - const chunkGraph = new ChunkGraph( - this.moduleGraph, - this.outputOptions.hashFunction - ); - const runtime = "build time"; - const { hashFunction, hashDigest, hashDigestLength } = - this.outputOptions; - const runtimeTemplate = this.runtimeTemplate; + build(options, compilation, resolver, fs, callback) { + this.buildMeta = { + async: false, + exportsType: undefined + }; + this.buildInfo = { + strict: true, + topLevelDeclarations: new Set(), + module: compilation.outputOptions.module + }; + const { request, externalType } = this._getRequestAndExternalType(); + this.buildMeta.exportsType = "dynamic"; + let canMangle = false; + this.clearDependenciesAndBlocks(); + switch (externalType) { + case "this": + this.buildInfo.strict = false; + break; + case "system": + if (!Array.isArray(request) || request.length === 1) { + this.buildMeta.exportsType = "namespace"; + canMangle = true; + } + break; + case "module": + if (this.buildInfo.module) { + if (!Array.isArray(request) || request.length === 1) { + this.buildMeta.exportsType = "namespace"; + canMangle = true; + } + } else { + this.buildMeta.async = true; + if (!Array.isArray(request) || request.length === 1) { + this.buildMeta.exportsType = "namespace"; + canMangle = false; + } + } + break; + case "script": + case "promise": + this.buildMeta.async = true; + break; + case "import": + this.buildMeta.async = true; + if (!Array.isArray(request) || request.length === 1) { + this.buildMeta.exportsType = "namespace"; + canMangle = false; + } + break; + } + this.addDependency(new StaticExportsDependency(true, canMangle)); + callback(); + } - const chunk = new Chunk("build time chunk", this._backCompat); - chunk.id = chunk.name; - chunk.ids = [chunk.id]; - chunk.runtime = runtime; + restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { + this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); + } - const entrypoint = new Entrypoint({ - runtime, - chunkLoading: false, - ...options.entryOptions - }); - chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint); - connectChunkGroupAndChunk(entrypoint, chunk); - entrypoint.setRuntimeChunk(chunk); - entrypoint.setEntrypointChunk(chunk); + /** + * @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; + } - const chunks = new Set([chunk]); + _getRequestAndExternalType() { + let { request, externalType } = this; + if (typeof request === "object" && !Array.isArray(request)) + request = request[externalType]; + return { request, externalType }; + } - // Assign ids to modules and modules to the chunk - for (const module of modules) { - const id = module.identifier(); - chunkGraph.setModuleId(module, id); - chunkGraph.connectChunkAndModule(chunk, module); + _getSourceData( + request, + externalType, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime + ) { + switch (externalType) { + case "this": + case "window": + case "self": + return getSourceForGlobalVariableExternal(request, this.externalType); + case "global": + return getSourceForGlobalVariableExternal( + request, + runtimeTemplate.globalObject + ); + case "commonjs": + case "commonjs2": + case "commonjs-module": + case "commonjs-static": + return getSourceForCommonJsExternal(request); + case "node-commonjs": + return this.buildInfo.module + ? getSourceForCommonJsExternalInNodeModule(request) + : getSourceForCommonJsExternal(request); + case "amd": + case "amd-require": + case "umd": + case "umd2": + case "system": + case "jsonp": { + const id = chunkGraph.getModuleId(this); + return getSourceForAmdOrUmdExternal( + id !== null ? id : this.identifier(), + this.isOptional(moduleGraph), + request, + runtimeTemplate + ); + } + case "import": + return getSourceForImportExternal(request, runtimeTemplate); + case "script": + return getSourceForScriptExternal(request, runtimeTemplate); + case "module": { + if (!this.buildInfo.module) { + if (!runtimeTemplate.supportsDynamicImport()) { + throw new Error( + "The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script" + + (runtimeTemplate.supportsEcmaScriptModuleSyntax() + ? "\nDid you mean to build a EcmaScript Module ('output.module: true')?" + : "") + ); + } + return getSourceForImportExternal(request, runtimeTemplate); } - - // Hash modules - for (const module of modules) { - this._createModuleHash( - module, - chunkGraph, - runtime, - hashFunction, - runtimeTemplate, - hashDigest, - hashDigestLength + if (!runtimeTemplate.supportsEcmaScriptModuleSyntax()) { + throw new Error( + "The target environment doesn't support EcmaScriptModule syntax so it's not possible to use external type 'module'" ); } - - const codeGenerationResults = new CodeGenerationResults( - this.outputOptions.hashFunction + return getSourceForModuleExternal( + request, + moduleGraph.getExportsInfo(this), + runtime, + runtimeTemplate.outputOptions.hashFunction ); - /** @type {WebpackError[]} */ - const errors = []; - /** - * @param {Module} module the module - * @param {Callback} callback callback - * @returns {void} - */ - const codeGen = (module, callback) => { - this._codeGenerationModule( - module, - runtime, - [runtime], - chunkGraph.getModuleHash(module, runtime), - this.dependencyTemplates, - chunkGraph, - this.moduleGraph, - runtimeTemplate, - errors, - codeGenerationResults, - (err, codeGenerated) => { - callback(err); - } - ); - }; + } + case "var": + case "promise": + case "const": + case "let": + case "assign": + default: + return getSourceForDefaultCase( + this.isOptional(moduleGraph), + request, + runtimeTemplate + ); + } + } - const reportErrors = () => { - if (errors.length > 0) { - errors.sort( - compareSelect(err => err.module, compareModulesByIdentifier) - ); - for (const error of errors) { - this.errors.push(error); - } - errors.length = 0; - } + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + concatenationScope + }) { + const { request, externalType } = this._getRequestAndExternalType(); + switch (externalType) { + case "asset": { + const sources = new Map(); + sources.set( + "javascript", + new RawSource(`module.exports = ${JSON.stringify(request)};`) + ); + const data = new Map(); + data.set("url", request); + return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS, data }; + } + case "css-import": { + const sources = new Map(); + sources.set( + "css-import", + new RawSource(`@import url(${JSON.stringify(request)});`) + ); + return { + sources, + runtimeRequirements: EMPTY_RUNTIME_REQUIREMENTS }; + } + default: { + const sourceData = this._getSourceData( + request, + externalType, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime + ); - // Generate code for all aggregated modules - asyncLib.eachLimit(modules, 10, codeGen, err => { - if (err) return callback(err); - reportErrors(); + 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}`; - // for backward-compat temporary set the chunk graph - // TODO webpack 6 - const old = this.chunkGraph; - this.chunkGraph = chunkGraph; - this.processRuntimeRequirements({ - chunkGraph, - modules, - chunks, - codeGenerationResults, - chunkGraphEntries: chunks - }); - this.chunkGraph = old; + let data = undefined; + if (sourceData.chunkInitFragments) { + data = new Map(); + data.set("chunkInitFragments", sourceData.chunkInitFragments); + } - const runtimeModules = - chunkGraph.getChunkRuntimeModulesIterable(chunk); + const sources = new Map(); + if (this.useSourceMap || this.useSimpleSourceMap) { + sources.set( + "javascript", + new OriginalSource(sourceString, this.identifier()) + ); + } else { + sources.set("javascript", new RawSource(sourceString)); + } - // Hash runtime modules - for (const module of runtimeModules) { - modules.add(module); - this._createModuleHash( - module, - chunkGraph, - runtime, - hashFunction, - runtimeTemplate, - hashDigest, - hashDigestLength - ); + let runtimeRequirements = sourceData.runtimeRequirements; + if (!concatenationScope) { + if (!runtimeRequirements) { + runtimeRequirements = RUNTIME_REQUIREMENTS; + } else { + const set = new Set(runtimeRequirements); + set.add(RuntimeGlobals.module); + runtimeRequirements = set; } + } - // Generate code for all runtime modules - asyncLib.eachLimit(runtimeModules, 10, codeGen, err => { - if (err) return callback(err); - reportErrors(); + return { + sources, + runtimeRequirements: + runtimeRequirements || EMPTY_RUNTIME_REQUIREMENTS, + data + }; + } + } + } - /** @type {Map} */ - const moduleArgumentsMap = new Map(); - /** @type {Map} */ - const moduleArgumentsById = new Map(); + /** + * @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; + } - /** @type {ExecuteModuleResult["fileDependencies"]} */ - const fileDependencies = new LazySet(); - /** @type {ExecuteModuleResult["contextDependencies"]} */ - const contextDependencies = new LazySet(); - /** @type {ExecuteModuleResult["missingDependencies"]} */ - const missingDependencies = new LazySet(); - /** @type {ExecuteModuleResult["buildDependencies"]} */ - const buildDependencies = new LazySet(); + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + const { chunkGraph } = context; + hash.update( + `${this.externalType}${JSON.stringify(this.request)}${this.isOptional( + chunkGraph.moduleGraph + )}` + ); + super.updateHash(hash, context); + } - /** @type {ExecuteModuleResult["assets"]} */ - const assets = new Map(); + serialize(context) { + const { write } = context; - let cacheable = true; + write(this.request); + write(this.externalType); + write(this.userRequest); - /** @type {ExecuteModuleContext} */ - const context = { - assets, - __webpack_require__: undefined, - chunk, - chunkGraph - }; + super.serialize(context); + } - // Prepare execution - asyncLib.eachLimit( - modules, - 10, - (module, callback) => { - const codeGenerationResult = codeGenerationResults.get( - module, - runtime - ); - /** @type {ExecuteModuleArgument} */ - const moduleArgument = { - module, - codeGenerationResult, - preparedInfo: undefined, - moduleObject: undefined - }; - moduleArgumentsMap.set(module, moduleArgument); - moduleArgumentsById.set(module.identifier(), moduleArgument); - module.addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ); - if (module.buildInfo.cacheable === false) { - cacheable = false; - } - if (module.buildInfo && module.buildInfo.assets) { - const { assets: moduleAssets, assetsInfo } = module.buildInfo; - for (const assetName of Object.keys(moduleAssets)) { - assets.set(assetName, { - source: moduleAssets[assetName], - info: assetsInfo ? assetsInfo.get(assetName) : undefined - }); - } - } - this.hooks.prepareModuleExecution.callAsync( - moduleArgument, - context, - callback - ); - }, - err => { - if (err) return callback(err); + deserialize(context) { + const { read } = context; - let exports; - try { - const { - strictModuleErrorHandling, - strictModuleExceptionHandling - } = this.outputOptions; - const __nested_webpack_require_152290__ = id => { - const cached = moduleCache[id]; - if (cached !== undefined) { - if (cached.error) throw cached.error; - return cached.exports; - } - const moduleArgument = moduleArgumentsById.get(id); - return __webpack_require_module__(moduleArgument, id); - }; - const interceptModuleExecution = (__nested_webpack_require_152290__[ - RuntimeGlobals.interceptModuleExecution.replace( - "__webpack_require__.", - "" - ) - ] = []); - const moduleCache = (__nested_webpack_require_152290__[ - RuntimeGlobals.moduleCache.replace( - "__webpack_require__.", - "" - ) - ] = {}); + this.request = read(); + this.externalType = read(); + this.userRequest = read(); - context.__webpack_require__ = __nested_webpack_require_152290__; + super.deserialize(context); + } +} - /** - * @param {ExecuteModuleArgument} moduleArgument the module argument - * @param {string=} id id - * @returns {any} exports - */ - const __webpack_require_module__ = (moduleArgument, id) => { - var execOptions = { - id, - module: { - id, - exports: {}, - loaded: false, - error: undefined - }, - require: __nested_webpack_require_152290__ - }; - interceptModuleExecution.forEach(handler => - handler(execOptions) - ); - const module = moduleArgument.module; - this.buildTimeExecutedModules.add(module); - const moduleObject = execOptions.module; - moduleArgument.moduleObject = moduleObject; - try { - if (id) moduleCache[id] = moduleObject; +makeSerializable(ExternalModule, "webpack/lib/ExternalModule"); - tryRunOrWebpackError( - () => - this.hooks.executeModule.call( - moduleArgument, - context - ), - "Compilation.hooks.executeModule" - ); - moduleObject.loaded = true; - return moduleObject.exports; - } catch (e) { - if (strictModuleExceptionHandling) { - if (id) delete moduleCache[id]; - } else if (strictModuleErrorHandling) { - moduleObject.error = e; - } - if (!e.module) e.module = module; - throw e; - } - }; +module.exports = ExternalModule; - for (const runtimeModule of chunkGraph.getChunkRuntimeModulesInOrder( - chunk - )) { - __webpack_require_module__( - moduleArgumentsMap.get(runtimeModule) - ); - } - exports = __nested_webpack_require_152290__(module.identifier()); - } catch (e) { - const err = new WebpackError( - `Execution of module code from module graph (${module.readableIdentifier( - this.requestShortener - )}) failed: ${e.message}` - ); - err.stack = e.stack; - err.module = e.module; - return callback(err); - } - callback(null, { - exports, - assets, - cacheable, - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - }); - } - ); - }); - }); - } - ); - } +/***/ }), - checkConstraints() { - const chunkGraph = this.chunkGraph; +/***/ 62153: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {Set} */ - const usedIds = new Set(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - for (const module of this.modules) { - if (module.type === "runtime") continue; - const moduleId = chunkGraph.getModuleId(module); - if (moduleId === null) continue; - if (usedIds.has(moduleId)) { - throw new Error(`checkConstraints: duplicate module id ${moduleId}`); - } - usedIds.add(moduleId); - } - for (const chunk of this.chunks) { - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - if (!this.modules.has(module)) { - throw new Error( - "checkConstraints: module in chunk but not in compilation " + - ` ${chunk.debugId} ${module.debugId}` - ); - } - } - for (const module of chunkGraph.getChunkEntryModulesIterable(chunk)) { - if (!this.modules.has(module)) { - throw new Error( - "checkConstraints: entry module in chunk but not in compilation " + - ` ${chunk.debugId} ${module.debugId}` - ); - } - } - } - for (const chunkGroup of this.chunkGroups) { - chunkGroup.checkConstraints(); - } - } -} +const util = __webpack_require__(73837); +const ExternalModule = __webpack_require__(73071); +const { resolveByProperty, cachedSetProperty } = __webpack_require__(60839); -/** - * @typedef {Object} FactorizeModuleOptions - * @property {ModuleProfile} currentProfile - * @property {ModuleFactory} factory - * @property {Dependency[]} dependencies - * @property {boolean=} factoryResult return full ModuleFactoryResult instead of only module - * @property {Module | null} originModule - * @property {Partial=} contextInfo - * @property {string=} context - */ +/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ -/** - * @param {FactorizeModuleOptions} options options object - * @param {ModuleCallback | ModuleFactoryResultCallback} callback callback - * @returns {void} - */ +const UNSPECIFIED_EXTERNAL_TYPE_REGEXP = /^[a-z0-9-]+ /; +const EMPTY_RESOLVE_OPTIONS = {}; -// Workaround for typescript as it doesn't support function overloading in jsdoc within a class -Compilation.prototype.factorizeModule = /** @type {{ - (options: FactorizeModuleOptions & { factoryResult?: false }, callback: ModuleCallback): void; - (options: FactorizeModuleOptions & { factoryResult: true }, callback: ModuleFactoryResultCallback): void; -}} */ ( - function (options, callback) { - this.factorizeQueue.add(options, callback); - } +// 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" ); -// Hide from typescript -const compilationPrototype = Compilation.prototype; +const cache = new WeakMap(); -// TODO webpack 6 remove -Object.defineProperty(compilationPrototype, "modifyHash", { - writable: false, - enumerable: false, - configurable: false, - value: () => { - throw new Error( - "Compilation.modifyHash was removed in favor of Compilation.hooks.fullHash" - ); +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; } -}); - -// TODO webpack 6 remove -Object.defineProperty(compilationPrototype, "cache", { - enumerable: false, - configurable: false, - get: util.deprecate( - /** - * @this {Compilation} the compilation - * @returns {Cache} the cache - */ - function () { - return this.compiler.cache; - }, - "Compilation.cache was removed in favor of Compilation.getCache()", - "DEP_WEBPACK_COMPILATION_CACHE" - ), - set: util.deprecate( - v => {}, - "Compilation.cache was removed in favor of Compilation.getCache()", - "DEP_WEBPACK_COMPILATION_CACHE" - ) -}); - -/** - * Add additional assets to the compilation. - */ -Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL = -2000; + const result = resolveByProperty(obj, "byLayer", layer); + map.set(layer, result); + return result; +}; -/** - * Basic preprocessing of assets. - */ -Compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS = -1000; +class ExternalModuleFactoryPlugin { + /** + * @param {string | undefined} type default external type + * @param {Externals} externals externals config + */ + constructor(type, externals) { + this.type = type; + this.externals = externals; + } -/** - * Derive new assets from existing assets. - * Existing assets should not be treated as complete. - */ -Compilation.PROCESS_ASSETS_STAGE_DERIVED = -200; + /** + * @param {NormalModuleFactory} normalModuleFactory the normal module factory + * @returns {void} + */ + apply(normalModuleFactory) { + const globalType = this.type; + normalModuleFactory.hooks.factorize.tapAsync( + "ExternalModuleFactoryPlugin", + (data, callback) => { + const context = data.context; + const contextInfo = data.contextInfo; + const dependency = data.dependencies[0]; + const dependencyType = data.dependencyType; -/** - * Add additional sections to existing assets, like a banner or initialization code. - */ -Compilation.PROCESS_ASSETS_STAGE_ADDITIONS = -100; + /** + * @param {string|string[]|boolean|Record} 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} */ + 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 + ) + ); + }; -/** - * Optimize existing assets in a general way. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE = 100; + /** + * @param {Externals} externals externals config + * @param {function((Error | null)=, ExternalModule=): void} callback callback + * @returns {void} + */ + const handleExternals = (externals, callback) => { + if (typeof externals === "string") { + if (externals === dependency.request) { + return handleExternal(dependency.request, undefined, callback); + } + } else if (Array.isArray(externals)) { + let i = 0; + const next = () => { + let asyncFlag; + const handleExternalsAndCallback = (err, module) => { + if (err) return callback(err); + if (!module) { + if (asyncFlag) { + asyncFlag = false; + return; + } + return next(); + } + callback(null, module); + }; -/** - * Optimize the count of existing assets, e. g. by merging them. - * Only assets of the same type should be merged. - * For assets of different types see PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT = 200; + do { + asyncFlag = true; + if (i >= externals.length) return callback(); + handleExternals(externals[i++], handleExternalsAndCallback); + } while (!asyncFlag); + asyncFlag = false; + }; -/** - * Optimize the compatibility of existing assets, e. g. add polyfills or vendor-prefixes. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY = 300; + next(); + return; + } else if (externals instanceof RegExp) { + if (externals.test(dependency.request)) { + return handleExternal(dependency.request, undefined, callback); + } + } else if (typeof externals === "function") { + const cb = (err, value, type) => { + if (err) return callback(err); + if (value !== undefined) { + handleExternal(value, type, callback); + } else { + callback(); + } + }; + if (externals.length === 3) { + // TODO webpack 6 remove this + callDeprecatedExternals( + externals, + context, + dependency.request, + cb + ); + } else { + const promise = externals( + { + context, + request: dependency.request, + dependencyType, + contextInfo, + getResolve: options => (context, request, callback) => { + const resolveContext = { + fileDependencies: data.fileDependencies, + missingDependencies: data.missingDependencies, + contextDependencies: data.contextDependencies + }; + let resolver = normalModuleFactory.getResolver( + "normal", + dependencyType + ? cachedSetProperty( + data.resolveOptions || EMPTY_RESOLVE_OPTIONS, + "dependencyType", + dependencyType + ) + : data.resolveOptions + ); + if (options) resolver = resolver.withOptions(options); + if (callback) { + resolver.resolve( + {}, + context, + request, + resolveContext, + callback + ); + } else { + return new Promise((resolve, reject) => { + resolver.resolve( + {}, + context, + request, + resolveContext, + (err, result) => { + if (err) reject(err); + else resolve(result); + } + ); + }); + } + } + }, + cb + ); + if (promise && promise.then) promise.then(r => cb(null, r), cb); + } + return; + } else if (typeof externals === "object") { + const resolvedExternals = resolveLayer( + externals, + contextInfo.issuerLayer + ); + if ( + Object.prototype.hasOwnProperty.call( + resolvedExternals, + dependency.request + ) + ) { + return handleExternal( + resolvedExternals[dependency.request], + undefined, + callback + ); + } + } + callback(); + }; -/** - * Optimize the size of existing assets, e. g. by minimizing or omitting whitespace. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE = 400; + handleExternals(this.externals, callback); + } + ); + } +} +module.exports = ExternalModuleFactoryPlugin; -/** - * Add development tooling to assets, e. g. by extracting a SourceMap. - */ -Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING = 500; -/** - * Optimize the count of existing assets, e. g. by inlining assets of into other assets. - * Only assets of different types should be inlined. - * For assets of the same type see PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE = 700; +/***/ }), -/** - * Summarize the list of existing assets - * e. g. creating an assets manifest of Service Workers. - */ -Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE = 1000; +/***/ 6652: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * Optimize the hashes of the assets, e. g. by generating real hashes of the asset content. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH = 2500; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * Optimize the transfer of existing assets, e. g. by preparing a compressed (gzip) file as separate asset. - */ -Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER = 3000; -/** - * Analyse existing assets. - */ -Compilation.PROCESS_ASSETS_STAGE_ANALYSE = 4000; -/** - * Creating assets for reporting purposes. - */ -Compilation.PROCESS_ASSETS_STAGE_REPORT = 5000; +const ExternalModuleFactoryPlugin = __webpack_require__(62153); -module.exports = Compilation; +/** @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; /***/ }), -/***/ 70845: +/***/ 79453: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -34736,3571 +36653,3563 @@ module.exports = Compilation; -const parseJson = __webpack_require__(15235); +const { create: createResolver } = __webpack_require__(9256); const asyncLib = __webpack_require__(78175); -const { - SyncHook, - SyncBailHook, - AsyncParallelHook, - AsyncSeriesHook -} = __webpack_require__(41242); -const { SizeOnlySource } = __webpack_require__(51255); -const webpack = __webpack_require__(91919); -const Cache = __webpack_require__(7592); -const CacheFacade = __webpack_require__(55392); -const ChunkGraph = __webpack_require__(64971); -const Compilation = __webpack_require__(85720); -const ConcurrentCompilationError = __webpack_require__(95735); -const ContextModuleFactory = __webpack_require__(62471); -const ModuleGraph = __webpack_require__(99988); -const NormalModuleFactory = __webpack_require__(68860); -const RequestShortener = __webpack_require__(73406); -const ResolverFactory = __webpack_require__(30217); -const Stats = __webpack_require__(31743); -const Watching = __webpack_require__(84275); -const WebpackError = __webpack_require__(53799); -const { Logger } = __webpack_require__(32597); -const { join, dirname, mkdirp } = __webpack_require__(17139); -const { makePathsRelative } = __webpack_require__(82186); -const { isSourceEqual } = __webpack_require__(41245); +const AsyncQueue = __webpack_require__(12260); +const StackedCacheMap = __webpack_require__(64985); +const createHash = __webpack_require__(49835); +const { join, dirname, relative, lstatReadlinkAbsolute } = __webpack_require__(17139); +const makeSerializable = __webpack_require__(33032); +const processAsyncTree = __webpack_require__(42791); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} Entry */ -/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ -/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./util/WeakTupleMap")} WeakTupleMap */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./logging/Logger").Logger} Logger */ +/** @typedef {typeof import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").IStats} IStats */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */ -/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */ -/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */ + +const supportsEsm = +process.versions.modules >= 83; + +let FS_ACCURACY = 2000; + +const EMPTY_SET = new Set(); + +const RBDT_RESOLVE_CJS = 0; +const RBDT_RESOLVE_ESM = 1; +const RBDT_RESOLVE_DIRECTORY = 2; +const RBDT_RESOLVE_CJS_FILE = 3; +const RBDT_RESOLVE_CJS_FILE_AS_CHILD = 4; +const RBDT_RESOLVE_ESM_FILE = 5; +const RBDT_DIRECTORY = 6; +const RBDT_FILE = 7; +const RBDT_DIRECTORY_DEPENDENCIES = 8; +const RBDT_FILE_DEPENDENCIES = 9; + +const INVALID = Symbol("invalid"); /** - * @typedef {Object} CompilationParams - * @property {NormalModuleFactory} normalModuleFactory - * @property {ContextModuleFactory} contextModuleFactory + * @typedef {Object} FileSystemInfoEntry + * @property {number} safeTime + * @property {number=} timestamp */ /** - * @template T - * @callback Callback - * @param {(Error | null)=} err - * @param {T=} result + * @typedef {Object} ResolvedContextFileSystemInfoEntry + * @property {number} safeTime + * @property {string=} timestampHash */ /** - * @callback RunAsChildCallback - * @param {(Error | null)=} err - * @param {Chunk[]=} entries - * @param {Compilation=} compilation + * @typedef {Object} ContextFileSystemInfoEntry + * @property {number} safeTime + * @property {string=} timestampHash + * @property {ResolvedContextFileSystemInfoEntry=} resolved + * @property {Set=} symlinks */ /** - * @typedef {Object} AssetEmittedInfo - * @property {Buffer} content - * @property {Source} source - * @property {Compilation} compilation - * @property {string} outputPath - * @property {string} targetPath + * @typedef {Object} TimestampAndHash + * @property {number} safeTime + * @property {number=} timestamp + * @property {string} hash */ /** - * @param {string[]} array an array - * @returns {boolean} true, if the array is sorted + * @typedef {Object} ResolvedContextTimestampAndHash + * @property {number} safeTime + * @property {string=} timestampHash + * @property {string} hash */ -const isSorted = array => { - for (let i = 1; i < array.length; i++) { - if (array[i - 1] > array[i]) return false; - } - return true; -}; /** - * @param {Object} obj an object - * @param {string[]} keys the keys of the object - * @returns {Object} the object with properties sorted by property name + * @typedef {Object} ContextTimestampAndHash + * @property {number} safeTime + * @property {string=} timestampHash + * @property {string} hash + * @property {ResolvedContextTimestampAndHash=} resolved + * @property {Set=} symlinks */ -const sortObject = (obj, keys) => { - const o = {}; - for (const k of keys.sort()) { - o[k] = obj[k]; - } - return o; -}; /** - * @param {string} filename filename - * @param {string | string[] | undefined} hashes list of hashes - * @returns {boolean} true, if the filename contains any hash + * @typedef {Object} ContextHash + * @property {string} hash + * @property {string=} resolved + * @property {Set=} symlinks */ -const includesHash = (filename, hashes) => { - if (!hashes) return false; - if (Array.isArray(hashes)) { - return hashes.some(hash => filename.includes(hash)); - } else { - return filename.includes(hashes); + +/** + * @typedef {Object} SnapshotOptimizationEntry + * @property {Snapshot} snapshot + * @property {number} shared + * @property {Set} snapshotContent + * @property {Set} children + */ + +/** + * @typedef {Object} ResolveBuildDependenciesResult + * @property {Set} files list of files + * @property {Set} directories list of directories + * @property {Set} missing list of missing entries + * @property {Map} resolveResults stored resolve results + * @property {Object} resolveDependencies dependencies of the resolving + * @property {Set} resolveDependencies.files list of files + * @property {Set} resolveDependencies.directories list of directories + * @property {Set} resolveDependencies.missing list of missing entries + */ + +const DONE_ITERATOR_RESULT = new Set().keys().next(); + +// cspell:word tshs +// Tsh = Timestamp + Hash +// Tshs = Timestamp + Hash combinations + +class SnapshotIterator { + constructor(next) { + this.next = next; } -}; +} -class Compiler { - /** - * @param {string} context the compilation path - * @param {WebpackOptions} options options - */ - constructor(context, options = /** @type {WebpackOptions} */ ({})) { - this.hooks = Object.freeze({ - /** @type {SyncHook<[]>} */ - initialize: new SyncHook([]), +class SnapshotIterable { + constructor(snapshot, getMaps) { + this.snapshot = snapshot; + this.getMaps = getMaps; + } - /** @type {SyncBailHook<[Compilation], boolean>} */ - shouldEmit: new SyncBailHook(["compilation"]), - /** @type {AsyncSeriesHook<[Stats]>} */ - done: new AsyncSeriesHook(["stats"]), - /** @type {SyncHook<[Stats]>} */ - afterDone: new SyncHook(["stats"]), - /** @type {AsyncSeriesHook<[]>} */ - additionalPass: new AsyncSeriesHook([]), - /** @type {AsyncSeriesHook<[Compiler]>} */ - beforeRun: new AsyncSeriesHook(["compiler"]), - /** @type {AsyncSeriesHook<[Compiler]>} */ - run: new AsyncSeriesHook(["compiler"]), - /** @type {AsyncSeriesHook<[Compilation]>} */ - emit: new AsyncSeriesHook(["compilation"]), - /** @type {AsyncSeriesHook<[string, AssetEmittedInfo]>} */ - assetEmitted: new AsyncSeriesHook(["file", "info"]), - /** @type {AsyncSeriesHook<[Compilation]>} */ - afterEmit: new AsyncSeriesHook(["compilation"]), + [Symbol.iterator]() { + let state = 0; + /** @type {IterableIterator} */ + let it; + /** @type {(Snapshot) => (Map | Set)[]} */ + let getMaps; + /** @type {(Map | Set)[]} */ + let maps; + /** @type {Snapshot} */ + let snapshot; + let queue; + return new SnapshotIterator(() => { + for (;;) { + switch (state) { + case 0: + snapshot = this.snapshot; + getMaps = this.getMaps; + maps = getMaps(snapshot); + state = 1; + /* falls through */ + case 1: + if (maps.length > 0) { + const map = maps.pop(); + if (map !== undefined) { + it = map.keys(); + state = 2; + } else { + break; + } + } else { + state = 3; + break; + } + /* falls through */ + case 2: { + const result = it.next(); + if (!result.done) return result; + state = 1; + break; + } + case 3: { + const children = snapshot.children; + if (children !== undefined) { + if (children.size === 1) { + // shortcut for a single child + // avoids allocation of queue + for (const child of children) snapshot = child; + maps = getMaps(snapshot); + state = 1; + break; + } + if (queue === undefined) queue = []; + for (const child of children) { + queue.push(child); + } + } + if (queue !== undefined && queue.length > 0) { + snapshot = queue.pop(); + maps = getMaps(snapshot); + state = 1; + break; + } else { + state = 4; + } + } + /* falls through */ + case 4: + return DONE_ITERATOR_RESULT; + } + } + }); + } +} - /** @type {SyncHook<[Compilation, CompilationParams]>} */ - thisCompilation: new SyncHook(["compilation", "params"]), - /** @type {SyncHook<[Compilation, CompilationParams]>} */ - compilation: new SyncHook(["compilation", "params"]), - /** @type {SyncHook<[NormalModuleFactory]>} */ - normalModuleFactory: new SyncHook(["normalModuleFactory"]), - /** @type {SyncHook<[ContextModuleFactory]>} */ - contextModuleFactory: new SyncHook(["contextModuleFactory"]), +class Snapshot { + constructor() { + this._flags = 0; + /** @type {number | undefined} */ + this.startTime = undefined; + /** @type {Map | undefined} */ + this.fileTimestamps = undefined; + /** @type {Map | undefined} */ + this.fileHashes = undefined; + /** @type {Map | undefined} */ + this.fileTshs = undefined; + /** @type {Map | undefined} */ + this.contextTimestamps = undefined; + /** @type {Map | undefined} */ + this.contextHashes = undefined; + /** @type {Map | undefined} */ + this.contextTshs = undefined; + /** @type {Map | undefined} */ + this.missingExistence = undefined; + /** @type {Map | undefined} */ + this.managedItemInfo = undefined; + /** @type {Set | undefined} */ + this.managedFiles = undefined; + /** @type {Set | undefined} */ + this.managedContexts = undefined; + /** @type {Set | undefined} */ + this.managedMissing = undefined; + /** @type {Set | undefined} */ + this.children = undefined; + } - /** @type {AsyncSeriesHook<[CompilationParams]>} */ - beforeCompile: new AsyncSeriesHook(["params"]), - /** @type {SyncHook<[CompilationParams]>} */ - compile: new SyncHook(["params"]), - /** @type {AsyncParallelHook<[Compilation]>} */ - make: new AsyncParallelHook(["compilation"]), - /** @type {AsyncParallelHook<[Compilation]>} */ - finishMake: new AsyncSeriesHook(["compilation"]), - /** @type {AsyncSeriesHook<[Compilation]>} */ - afterCompile: new AsyncSeriesHook(["compilation"]), + hasStartTime() { + return (this._flags & 1) !== 0; + } - /** @type {AsyncSeriesHook<[]>} */ - readRecords: new AsyncSeriesHook([]), - /** @type {AsyncSeriesHook<[]>} */ - emitRecords: new AsyncSeriesHook([]), + setStartTime(value) { + this._flags = this._flags | 1; + this.startTime = value; + } - /** @type {AsyncSeriesHook<[Compiler]>} */ - watchRun: new AsyncSeriesHook(["compiler"]), - /** @type {SyncHook<[Error]>} */ - failed: new SyncHook(["error"]), - /** @type {SyncHook<[string | null, number]>} */ - invalid: new SyncHook(["filename", "changeTime"]), - /** @type {SyncHook<[]>} */ - watchClose: new SyncHook([]), - /** @type {AsyncSeriesHook<[]>} */ - shutdown: new AsyncSeriesHook([]), + setMergedStartTime(value, snapshot) { + if (value) { + if (snapshot.hasStartTime()) { + this.setStartTime(Math.min(value, snapshot.startTime)); + } else { + this.setStartTime(value); + } + } else { + if (snapshot.hasStartTime()) this.setStartTime(snapshot.startTime); + } + } - /** @type {SyncBailHook<[string, string, any[]], true>} */ - infrastructureLog: new SyncBailHook(["origin", "type", "args"]), + hasFileTimestamps() { + return (this._flags & 2) !== 0; + } - // TODO the following hooks are weirdly located here - // TODO move them for webpack 5 - /** @type {SyncHook<[]>} */ - environment: new SyncHook([]), - /** @type {SyncHook<[]>} */ - afterEnvironment: new SyncHook([]), - /** @type {SyncHook<[Compiler]>} */ - afterPlugins: new SyncHook(["compiler"]), - /** @type {SyncHook<[Compiler]>} */ - afterResolvers: new SyncHook(["compiler"]), - /** @type {SyncBailHook<[string, Entry], boolean>} */ - entryOption: new SyncBailHook(["context", "entry"]) - }); + setFileTimestamps(value) { + this._flags = this._flags | 2; + this.fileTimestamps = value; + } - this.webpack = webpack; + hasFileHashes() { + return (this._flags & 4) !== 0; + } - /** @type {string=} */ - this.name = undefined; - /** @type {Compilation=} */ - this.parentCompilation = undefined; - /** @type {Compiler} */ - this.root = this; - /** @type {string} */ - this.outputPath = ""; - /** @type {Watching} */ - this.watching = undefined; + setFileHashes(value) { + this._flags = this._flags | 4; + this.fileHashes = value; + } - /** @type {OutputFileSystem} */ - this.outputFileSystem = null; - /** @type {IntermediateFileSystem} */ - this.intermediateFileSystem = null; - /** @type {InputFileSystem} */ - this.inputFileSystem = null; - /** @type {WatchFileSystem} */ - this.watchFileSystem = null; + hasFileTshs() { + return (this._flags & 8) !== 0; + } - /** @type {string|null} */ - this.recordsInputPath = null; - /** @type {string|null} */ - this.recordsOutputPath = null; - this.records = {}; - /** @type {Set} */ - this.managedPaths = new Set(); - /** @type {Set} */ - this.immutablePaths = new Set(); + setFileTshs(value) { + this._flags = this._flags | 8; + this.fileTshs = value; + } - /** @type {ReadonlySet} */ - this.modifiedFiles = undefined; - /** @type {ReadonlySet} */ - this.removedFiles = undefined; - /** @type {ReadonlyMap} */ - this.fileTimestamps = undefined; - /** @type {ReadonlyMap} */ - this.contextTimestamps = undefined; - /** @type {number} */ - this.fsStartTime = undefined; + hasContextTimestamps() { + return (this._flags & 0x10) !== 0; + } - /** @type {ResolverFactory} */ - this.resolverFactory = new ResolverFactory(); + setContextTimestamps(value) { + this._flags = this._flags | 0x10; + this.contextTimestamps = value; + } - this.infrastructureLogger = undefined; + hasContextHashes() { + return (this._flags & 0x20) !== 0; + } - this.options = options; + setContextHashes(value) { + this._flags = this._flags | 0x20; + this.contextHashes = value; + } - this.context = context; + hasContextTshs() { + return (this._flags & 0x40) !== 0; + } - this.requestShortener = new RequestShortener(context, this.root); + setContextTshs(value) { + this._flags = this._flags | 0x40; + this.contextTshs = value; + } - this.cache = new Cache(); + hasMissingExistence() { + return (this._flags & 0x80) !== 0; + } - /** @type {Map, memCache: WeakTupleMap }> | undefined} */ - this.moduleMemCaches = undefined; + setMissingExistence(value) { + this._flags = this._flags | 0x80; + this.missingExistence = value; + } - this.compilerPath = ""; + hasManagedItemInfo() { + return (this._flags & 0x100) !== 0; + } - /** @type {boolean} */ - this.running = false; + setManagedItemInfo(value) { + this._flags = this._flags | 0x100; + this.managedItemInfo = value; + } - /** @type {boolean} */ - this.idle = false; + hasManagedFiles() { + return (this._flags & 0x200) !== 0; + } - /** @type {boolean} */ - this.watchMode = false; + setManagedFiles(value) { + this._flags = this._flags | 0x200; + this.managedFiles = value; + } - this._backCompat = this.options.experiments.backCompat !== false; + hasManagedContexts() { + return (this._flags & 0x400) !== 0; + } - /** @type {Compilation} */ - this._lastCompilation = undefined; - /** @type {NormalModuleFactory} */ - this._lastNormalModuleFactory = undefined; + setManagedContexts(value) { + this._flags = this._flags | 0x400; + this.managedContexts = value; + } - /** @private @type {WeakMap }>} */ - this._assetEmittingSourceCache = new WeakMap(); - /** @private @type {Map} */ - this._assetEmittingWrittenFiles = new Map(); - /** @private @type {Set} */ - this._assetEmittingPreviousFiles = new Set(); + hasManagedMissing() { + return (this._flags & 0x800) !== 0; } - /** - * @param {string} name cache name - * @returns {CacheFacade} the cache facade instance - */ - getCache(name) { - return new CacheFacade( - this.cache, - `${this.compilerPath}${name}`, - this.options.output.hashFunction - ); + setManagedMissing(value) { + this._flags = this._flags | 0x800; + this.managedMissing = value; } - /** - * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name - * @returns {Logger} a logger with that name - */ - getInfrastructureLogger(name) { - if (!name) { - throw new TypeError( - "Compiler.getInfrastructureLogger(name) called without a name" - ); - } - return new Logger( - (type, args) => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compiler.getInfrastructureLogger(name) called with a function not returning a name" - ); - } - } - if (this.hooks.infrastructureLog.call(name, type, args) === undefined) { - if (this.infrastructureLogger !== undefined) { - this.infrastructureLogger(name, type, args); - } - } - }, - childName => { - if (typeof name === "function") { - if (typeof childName === "function") { - return this.getInfrastructureLogger(() => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compiler.getInfrastructureLogger(name) called with a function not returning a name" - ); - } - } - if (typeof childName === "function") { - childName = childName(); - if (!childName) { - throw new TypeError( - "Logger.getChildLogger(name) called with a function not returning a name" - ); - } - } - return `${name}/${childName}`; - }); - } else { - return this.getInfrastructureLogger(() => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compiler.getInfrastructureLogger(name) called with a function not returning a name" - ); - } - } - return `${name}/${childName}`; - }); - } - } else { - if (typeof childName === "function") { - return this.getInfrastructureLogger(() => { - if (typeof childName === "function") { - childName = childName(); - if (!childName) { - throw new TypeError( - "Logger.getChildLogger(name) called with a function not returning a name" - ); - } - } - return `${name}/${childName}`; - }); - } else { - return this.getInfrastructureLogger(`${name}/${childName}`); - } - } - } - ); + hasChildren() { + return (this._flags & 0x1000) !== 0; } - // TODO webpack 6: solve this in a better way - // e.g. move compilation specific info from Modules into ModuleGraph - _cleanupLastCompilation() { - if (this._lastCompilation !== undefined) { - for (const module of this._lastCompilation.modules) { - ChunkGraph.clearChunkGraphForModule(module); - ModuleGraph.clearModuleGraphForModule(module); - module.cleanupForCache(); - } - for (const chunk of this._lastCompilation.chunks) { - ChunkGraph.clearChunkGraphForChunk(chunk); - } - this._lastCompilation = undefined; - } + setChildren(value) { + this._flags = this._flags | 0x1000; + this.children = value; } - // TODO webpack 6: solve this in a better way - _cleanupLastNormalModuleFactory() { - if (this._lastNormalModuleFactory !== undefined) { - this._lastNormalModuleFactory.cleanupForCache(); - this._lastNormalModuleFactory = undefined; + addChild(child) { + if (!this.hasChildren()) { + this.setChildren(new Set()); } + this.children.add(child); + } + + serialize({ write }) { + write(this._flags); + if (this.hasStartTime()) write(this.startTime); + if (this.hasFileTimestamps()) write(this.fileTimestamps); + if (this.hasFileHashes()) write(this.fileHashes); + if (this.hasFileTshs()) write(this.fileTshs); + if (this.hasContextTimestamps()) write(this.contextTimestamps); + if (this.hasContextHashes()) write(this.contextHashes); + if (this.hasContextTshs()) write(this.contextTshs); + if (this.hasMissingExistence()) write(this.missingExistence); + if (this.hasManagedItemInfo()) write(this.managedItemInfo); + if (this.hasManagedFiles()) write(this.managedFiles); + if (this.hasManagedContexts()) write(this.managedContexts); + if (this.hasManagedMissing()) write(this.managedMissing); + if (this.hasChildren()) write(this.children); + } + + deserialize({ read }) { + this._flags = read(); + if (this.hasStartTime()) this.startTime = read(); + if (this.hasFileTimestamps()) this.fileTimestamps = read(); + if (this.hasFileHashes()) this.fileHashes = read(); + if (this.hasFileTshs()) this.fileTshs = read(); + if (this.hasContextTimestamps()) this.contextTimestamps = read(); + if (this.hasContextHashes()) this.contextHashes = read(); + if (this.hasContextTshs()) this.contextTshs = read(); + if (this.hasMissingExistence()) this.missingExistence = read(); + if (this.hasManagedItemInfo()) this.managedItemInfo = read(); + if (this.hasManagedFiles()) this.managedFiles = read(); + if (this.hasManagedContexts()) this.managedContexts = read(); + if (this.hasManagedMissing()) this.managedMissing = read(); + if (this.hasChildren()) this.children = read(); } /** - * @param {WatchOptions} watchOptions the watcher's options - * @param {Callback} handler signals when the call finishes - * @returns {Watching} a compiler watcher + * @param {function(Snapshot): (ReadonlyMap | ReadonlySet)[]} getMaps first + * @returns {Iterable} iterable */ - watch(watchOptions, handler) { - if (this.running) { - return handler(new ConcurrentCompilationError()); - } + _createIterable(getMaps) { + return new SnapshotIterable(this, getMaps); + } - this.running = true; - this.watchMode = true; - this.watching = new Watching(this, watchOptions, handler); - return this.watching; + /** + * @returns {Iterable} iterable + */ + getFileIterable() { + return this._createIterable(s => [ + s.fileTimestamps, + s.fileHashes, + s.fileTshs, + s.managedFiles + ]); } /** - * @param {Callback} callback signals when the call finishes - * @returns {void} + * @returns {Iterable} iterable */ - run(callback) { - if (this.running) { - return callback(new ConcurrentCompilationError()); - } + getContextIterable() { + return this._createIterable(s => [ + s.contextTimestamps, + s.contextHashes, + s.contextTshs, + s.managedContexts + ]); + } - let logger; + /** + * @returns {Iterable} iterable + */ + getMissingIterable() { + return this._createIterable(s => [s.missingExistence, s.managedMissing]); + } +} - const finalCallback = (err, stats) => { - if (logger) logger.time("beginIdle"); - this.idle = true; - this.cache.beginIdle(); - this.idle = true; - if (logger) logger.timeEnd("beginIdle"); - this.running = false; - if (err) { - this.hooks.failed.call(err); - } - if (callback !== undefined) callback(err, stats); - this.hooks.afterDone.call(stats); - }; +makeSerializable(Snapshot, "webpack/lib/FileSystemInfo", "Snapshot"); - const startTime = Date.now(); - - this.running = true; - - const onCompiled = (err, compilation) => { - if (err) return finalCallback(err); - - if (this.hooks.shouldEmit.call(compilation) === false) { - compilation.startTime = startTime; - compilation.endTime = Date.now(); - const stats = new Stats(compilation); - this.hooks.done.callAsync(stats, err => { - if (err) return finalCallback(err); - return finalCallback(null, stats); - }); - return; - } - - process.nextTick(() => { - logger = compilation.getLogger("webpack.Compiler"); - logger.time("emitAssets"); - this.emitAssets(compilation, err => { - logger.timeEnd("emitAssets"); - if (err) return finalCallback(err); - - if (compilation.hooks.needAdditionalPass.call()) { - compilation.needAdditionalPass = true; - - compilation.startTime = startTime; - compilation.endTime = Date.now(); - logger.time("done hook"); - const stats = new Stats(compilation); - this.hooks.done.callAsync(stats, err => { - logger.timeEnd("done hook"); - if (err) return finalCallback(err); - - this.hooks.additionalPass.callAsync(err => { - if (err) return finalCallback(err); - this.compile(onCompiled); - }); - }); - return; - } - - logger.time("emitRecords"); - this.emitRecords(err => { - logger.timeEnd("emitRecords"); - if (err) return finalCallback(err); - - compilation.startTime = startTime; - compilation.endTime = Date.now(); - logger.time("done hook"); - const stats = new Stats(compilation); - this.hooks.done.callAsync(stats, err => { - logger.timeEnd("done hook"); - if (err) return finalCallback(err); - this.cache.storeBuildDependencies( - compilation.buildDependencies, - err => { - if (err) return finalCallback(err); - return finalCallback(null, stats); - } - ); - }); - }); - }); - }); - }; - - const run = () => { - this.hooks.beforeRun.callAsync(this, err => { - if (err) return finalCallback(err); - - this.hooks.run.callAsync(this, err => { - if (err) return finalCallback(err); - - this.readRecords(err => { - if (err) return finalCallback(err); - - this.compile(onCompiled); - }); - }); - }); - }; - - if (this.idle) { - this.cache.endIdle(err => { - if (err) return finalCallback(err); - - this.idle = false; - run(); - }); - } else { - run(); - } - } +const MIN_COMMON_SNAPSHOT_SIZE = 3; +/** + * @template T + */ +class SnapshotOptimization { /** - * @param {RunAsChildCallback} callback signals when the call finishes - * @returns {void} + * @param {function(Snapshot): boolean} has has value + * @param {function(Snapshot): Map | Set} get get value + * @param {function(Snapshot, Map | Set): void} set set value + * @param {boolean=} useStartTime use the start time of snapshots + * @param {boolean=} isSet value is an Set instead of a Map */ - runAsChild(callback) { - const startTime = Date.now(); - this.compile((err, compilation) => { - if (err) return callback(err); - - this.parentCompilation.children.push(compilation); - for (const { name, source, info } of compilation.getAssets()) { - this.parentCompilation.emitAsset(name, source, info); - } - - const entries = []; - for (const ep of compilation.entrypoints.values()) { - entries.push(...ep.chunks); - } - - compilation.startTime = startTime; - compilation.endTime = Date.now(); + constructor(has, get, set, useStartTime = true, isSet = false) { + this._has = has; + this._get = get; + this._set = set; + this._useStartTime = useStartTime; + this._isSet = isSet; + /** @type {Map} */ + this._map = new Map(); + this._statItemsShared = 0; + this._statItemsUnshared = 0; + this._statSharedSnapshots = 0; + this._statReusedSharedSnapshots = 0; + } - return callback(null, entries, compilation); - }); + getStatisticMessage() { + const total = this._statItemsShared + this._statItemsUnshared; + if (total === 0) return undefined; + return `${ + this._statItemsShared && Math.round((this._statItemsShared * 100) / total) + }% (${this._statItemsShared}/${total}) entries shared via ${ + this._statSharedSnapshots + } shared snapshots (${ + this._statReusedSharedSnapshots + this._statSharedSnapshots + } times referenced)`; } - purgeInputFileSystem() { - if (this.inputFileSystem && this.inputFileSystem.purge) { - this.inputFileSystem.purge(); - } + clear() { + this._map.clear(); + this._statItemsShared = 0; + this._statItemsUnshared = 0; + this._statSharedSnapshots = 0; + this._statReusedSharedSnapshots = 0; } /** - * @param {Compilation} compilation the compilation - * @param {Callback} callback signals when the assets are emitted + * @param {Snapshot} newSnapshot snapshot + * @param {Set} capturedFiles files to snapshot/share * @returns {void} */ - emitAssets(compilation, callback) { - let outputPath; + optimize(newSnapshot, capturedFiles) { + /** + * @param {SnapshotOptimizationEntry} entry optimization entry + * @returns {void} + */ + const increaseSharedAndStoreOptimizationEntry = entry => { + if (entry.children !== undefined) { + entry.children.forEach(increaseSharedAndStoreOptimizationEntry); + } + entry.shared++; + storeOptimizationEntry(entry); + }; + /** + * @param {SnapshotOptimizationEntry} entry optimization entry + * @returns {void} + */ + const storeOptimizationEntry = entry => { + for (const path of entry.snapshotContent) { + const old = this._map.get(path); + if (old.shared < entry.shared) { + this._map.set(path, entry); + } + capturedFiles.delete(path); + } + }; - const emitFiles = err => { - if (err) return callback(err); + /** @type {SnapshotOptimizationEntry} */ + let newOptimizationEntry = undefined; - const assets = compilation.getAssets(); - compilation.assets = { ...compilation.assets }; - /** @type {Map} */ - const caseInsensitiveMap = new Map(); - /** @type {Set} */ - const allTargetPaths = new Set(); - asyncLib.forEachLimit( - assets, - 15, - ({ name: file, source, info }, callback) => { - let targetFile = file; - let immutable = info.immutable; - const queryStringIdx = targetFile.indexOf("?"); - if (queryStringIdx >= 0) { - targetFile = targetFile.substr(0, queryStringIdx); - // We may remove the hash, which is in the query string - // So we recheck if the file is immutable - // This doesn't cover all cases, but immutable is only a performance optimization anyway - immutable = - immutable && - (includesHash(targetFile, info.contenthash) || - includesHash(targetFile, info.chunkhash) || - includesHash(targetFile, info.modulehash) || - includesHash(targetFile, info.fullhash)); - } + const capturedFilesSize = capturedFiles.size; - const writeOut = err => { - if (err) return callback(err); - const targetPath = join( - this.outputFileSystem, - outputPath, - targetFile - ); - allTargetPaths.add(targetPath); + /** @type {Set | undefined} */ + const optimizationEntries = new Set(); - // check if the target file has already been written by this Compiler - const targetFileGeneration = - this._assetEmittingWrittenFiles.get(targetPath); + for (const path of capturedFiles) { + const optimizationEntry = this._map.get(path); + if (optimizationEntry === undefined) { + if (newOptimizationEntry === undefined) { + newOptimizationEntry = { + snapshot: newSnapshot, + shared: 0, + snapshotContent: undefined, + children: undefined + }; + } + this._map.set(path, newOptimizationEntry); + continue; + } else { + optimizationEntries.add(optimizationEntry); + } + } - // create an cache entry for this Source if not already existing - let cacheEntry = this._assetEmittingSourceCache.get(source); - if (cacheEntry === undefined) { - cacheEntry = { - sizeOnlySource: undefined, - writtenTo: new Map() - }; - this._assetEmittingSourceCache.set(source, cacheEntry); + optimizationEntries: for (const optimizationEntry of optimizationEntries) { + const snapshot = optimizationEntry.snapshot; + if (optimizationEntry.shared > 0) { + // It's a shared snapshot + // We can't change it, so we can only use it when all files match + // and startTime is compatible + if ( + this._useStartTime && + newSnapshot.startTime && + (!snapshot.startTime || snapshot.startTime > newSnapshot.startTime) + ) { + continue; + } + const nonSharedFiles = new Set(); + const snapshotContent = optimizationEntry.snapshotContent; + const snapshotEntries = this._get(snapshot); + for (const path of snapshotContent) { + if (!capturedFiles.has(path)) { + if (!snapshotEntries.has(path)) { + // File is not shared and can't be removed from the snapshot + // because it's in a child of the snapshot + continue optimizationEntries; } - - let similarEntry; - - const checkSimilarFile = () => { - const caseInsensitiveTargetPath = targetPath.toLowerCase(); - similarEntry = caseInsensitiveMap.get(caseInsensitiveTargetPath); - if (similarEntry !== undefined) { - const { path: other, source: otherSource } = similarEntry; - if (isSourceEqual(otherSource, source)) { - // Size may or may not be available at this point. - // If it's not available add to "waiting" list and it will be updated once available - if (similarEntry.size !== undefined) { - updateWithReplacementSource(similarEntry.size); - } else { - if (!similarEntry.waiting) similarEntry.waiting = []; - similarEntry.waiting.push({ file, cacheEntry }); - } - alreadyWritten(); - } else { - const err = - new WebpackError(`Prevent writing to file that only differs in casing or query string from already written file. -This will lead to a race-condition and corrupted files on case-insensitive file systems. -${targetPath} -${other}`); - err.file = file; - callback(err); - } - return true; - } else { - caseInsensitiveMap.set( - caseInsensitiveTargetPath, - (similarEntry = { - path: targetPath, - source, - size: undefined, - waiting: undefined - }) - ); - return false; - } - }; - - /** - * get the binary (Buffer) content from the Source - * @returns {Buffer} content for the source - */ - const getContent = () => { - if (typeof source.buffer === "function") { - return source.buffer(); - } else { - const bufferOrString = source.source(); - if (Buffer.isBuffer(bufferOrString)) { - return bufferOrString; - } else { - return Buffer.from(bufferOrString, "utf8"); - } - } - }; - - const alreadyWritten = () => { - // cache the information that the Source has been already been written to that location - if (targetFileGeneration === undefined) { - const newGeneration = 1; - this._assetEmittingWrittenFiles.set(targetPath, newGeneration); - cacheEntry.writtenTo.set(targetPath, newGeneration); - } else { - cacheEntry.writtenTo.set(targetPath, targetFileGeneration); - } - callback(); - }; - - /** - * Write the file to output file system - * @param {Buffer} content content to be written - * @returns {void} - */ - const doWrite = content => { - this.outputFileSystem.writeFile(targetPath, content, err => { - if (err) return callback(err); - - // information marker that the asset has been emitted - compilation.emittedAssets.add(file); - - // cache the information that the Source has been written to that location - const newGeneration = - targetFileGeneration === undefined - ? 1 - : targetFileGeneration + 1; - cacheEntry.writtenTo.set(targetPath, newGeneration); - this._assetEmittingWrittenFiles.set(targetPath, newGeneration); - this.hooks.assetEmitted.callAsync( - file, - { - content, - source, - outputPath, - compilation, - targetPath - }, - callback - ); - }); - }; - - const updateWithReplacementSource = size => { - updateFileWithReplacementSource(file, cacheEntry, size); - similarEntry.size = size; - if (similarEntry.waiting !== undefined) { - for (const { file, cacheEntry } of similarEntry.waiting) { - updateFileWithReplacementSource(file, cacheEntry, size); - } - } - }; - - const updateFileWithReplacementSource = ( - file, - cacheEntry, - size - ) => { - // Create a replacement resource which only allows to ask for size - // This allows to GC all memory allocated by the Source - // (expect when the Source is stored in any other cache) - if (!cacheEntry.sizeOnlySource) { - cacheEntry.sizeOnlySource = new SizeOnlySource(size); - } - compilation.updateAsset(file, cacheEntry.sizeOnlySource, { - size - }); - }; - - const processExistingFile = stats => { - // skip emitting if it's already there and an immutable file - if (immutable) { - updateWithReplacementSource(stats.size); - return alreadyWritten(); - } - - const content = getContent(); - - updateWithReplacementSource(content.length); - - // if it exists and content on disk matches content - // skip writing the same content again - // (to keep mtime and don't trigger watchers) - // for a fast negative match file size is compared first - if (content.length === stats.size) { - compilation.comparedForEmitAssets.add(file); - return this.outputFileSystem.readFile( - targetPath, - (err, existingContent) => { - if ( - err || - !content.equals(/** @type {Buffer} */ (existingContent)) - ) { - return doWrite(content); - } else { - return alreadyWritten(); - } - } - ); - } - - return doWrite(content); - }; - - const processMissingFile = () => { - const content = getContent(); - - updateWithReplacementSource(content.length); - - return doWrite(content); - }; - - // if the target file has already been written - if (targetFileGeneration !== undefined) { - // check if the Source has been written to this target file - const writtenGeneration = cacheEntry.writtenTo.get(targetPath); - if (writtenGeneration === targetFileGeneration) { - // if yes, we may skip writing the file - // if it's already there - // (we assume one doesn't modify files while the Compiler is running, other then removing them) - - if (this._assetEmittingPreviousFiles.has(targetPath)) { - // We assume that assets from the last compilation say intact on disk (they are not removed) - compilation.updateAsset(file, cacheEntry.sizeOnlySource, { - size: cacheEntry.sizeOnlySource.size() - }); - - return callback(); - } else { - // Settings immutable will make it accept file content without comparing when file exist - immutable = true; - } - } else if (!immutable) { - if (checkSimilarFile()) return; - // We wrote to this file before which has very likely a different content - // skip comparing and assume content is different for performance - // This case happens often during watch mode. - return processMissingFile(); - } + nonSharedFiles.add(path); + continue; + } + } + if (nonSharedFiles.size === 0) { + // The complete snapshot is shared + // add it as child + newSnapshot.addChild(snapshot); + increaseSharedAndStoreOptimizationEntry(optimizationEntry); + this._statReusedSharedSnapshots++; + } else { + // Only a part of the snapshot is shared + const sharedCount = snapshotContent.size - nonSharedFiles.size; + if (sharedCount < MIN_COMMON_SNAPSHOT_SIZE) { + // Common part it too small + continue optimizationEntries; + } + // Extract common timestamps from both snapshots + let commonMap; + if (this._isSet) { + commonMap = new Set(); + for (const path of /** @type {Set} */ (snapshotEntries)) { + if (nonSharedFiles.has(path)) continue; + commonMap.add(path); + snapshotEntries.delete(path); } - - if (checkSimilarFile()) return; - if (this.options.output.compareBeforeEmit) { - this.outputFileSystem.stat(targetPath, (err, stats) => { - const exists = !err && stats.isFile(); - - if (exists) { - processExistingFile(stats); - } else { - processMissingFile(); - } - }); - } else { - processMissingFile(); + } else { + commonMap = new Map(); + const map = /** @type {Map} */ (snapshotEntries); + for (const [path, value] of map) { + if (nonSharedFiles.has(path)) continue; + commonMap.set(path, value); + snapshotEntries.delete(path); } + } + // Create and attach snapshot + const commonSnapshot = new Snapshot(); + if (this._useStartTime) { + commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot); + } + this._set(commonSnapshot, commonMap); + newSnapshot.addChild(commonSnapshot); + snapshot.addChild(commonSnapshot); + // Create optimization entry + const newEntry = { + snapshot: commonSnapshot, + shared: optimizationEntry.shared + 1, + snapshotContent: new Set(commonMap.keys()), + children: undefined }; - - if (targetFile.match(/\/|\\/)) { - const fs = this.outputFileSystem; - const dir = dirname(fs, join(fs, outputPath, targetFile)); - mkdirp(fs, dir, writeOut); + if (optimizationEntry.children === undefined) + optimizationEntry.children = new Set(); + optimizationEntry.children.add(newEntry); + storeOptimizationEntry(newEntry); + this._statSharedSnapshots++; + } + } else { + // It's a unshared snapshot + // We can extract a common shared snapshot + // with all common files + const snapshotEntries = this._get(snapshot); + if (snapshotEntries === undefined) { + // Incomplete snapshot, that can't be used + continue optimizationEntries; + } + let commonMap; + if (this._isSet) { + commonMap = new Set(); + const set = /** @type {Set} */ (snapshotEntries); + if (capturedFiles.size < set.size) { + for (const path of capturedFiles) { + if (set.has(path)) commonMap.add(path); + } } else { - writeOut(); + for (const path of set) { + if (capturedFiles.has(path)) commonMap.add(path); + } } - }, - err => { - // Clear map to free up memory - caseInsensitiveMap.clear(); - if (err) { - this._assetEmittingPreviousFiles.clear(); - return callback(err); + } else { + commonMap = new Map(); + const map = /** @type {Map} */ (snapshotEntries); + for (const path of capturedFiles) { + const ts = map.get(path); + if (ts === undefined) continue; + commonMap.set(path, ts); } - - this._assetEmittingPreviousFiles = allTargetPaths; - - this.hooks.afterEmit.callAsync(compilation, err => { - if (err) return callback(err); - - return callback(); - }); } - ); - }; - - this.hooks.emit.callAsync(compilation, err => { - if (err) return callback(err); - outputPath = compilation.getPath(this.outputPath, {}); - mkdirp(this.outputFileSystem, outputPath, emitFiles); - }); - } - /** - * @param {Callback} callback signals when the call finishes - * @returns {void} - */ - emitRecords(callback) { - if (this.hooks.emitRecords.isUsed()) { - if (this.recordsOutputPath) { - asyncLib.parallel( - [ - cb => this.hooks.emitRecords.callAsync(cb), - this._emitRecords.bind(this) - ], - err => callback(err) - ); - } else { - this.hooks.emitRecords.callAsync(callback); - } - } else { - if (this.recordsOutputPath) { - this._emitRecords(callback); - } else { - callback(); + if (commonMap.size < MIN_COMMON_SNAPSHOT_SIZE) { + // Common part it too small + continue optimizationEntries; + } + // Create and attach snapshot + const commonSnapshot = new Snapshot(); + if (this._useStartTime) { + commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot); + } + this._set(commonSnapshot, commonMap); + newSnapshot.addChild(commonSnapshot); + snapshot.addChild(commonSnapshot); + // Remove files from snapshot + for (const path of commonMap.keys()) snapshotEntries.delete(path); + const sharedCount = commonMap.size; + this._statItemsUnshared -= sharedCount; + this._statItemsShared += sharedCount; + // Create optimization entry + storeOptimizationEntry({ + snapshot: commonSnapshot, + shared: 2, + snapshotContent: new Set(commonMap.keys()), + children: undefined + }); + this._statSharedSnapshots++; } } + const unshared = capturedFiles.size; + this._statItemsUnshared += unshared; + this._statItemsShared += capturedFilesSize - unshared; } +} - /** - * @param {Callback} callback signals when the call finishes - * @returns {void} - */ - _emitRecords(callback) { - const writeFile = () => { - this.outputFileSystem.writeFile( - this.recordsOutputPath, - JSON.stringify( - this.records, - (n, value) => { - if ( - typeof value === "object" && - value !== null && - !Array.isArray(value) - ) { - const keys = Object.keys(value); - if (!isSorted(keys)) { - return sortObject(value, keys); - } - } - return value; - }, - 2 - ), - callback - ); - }; +const parseString = str => { + if (str[0] === "'") str = `"${str.slice(1, -1).replace(/"/g, '\\"')}"`; + return JSON.parse(str); +}; - const recordsOutputPathDirectory = dirname( - this.outputFileSystem, - this.recordsOutputPath - ); - if (!recordsOutputPathDirectory) { - return writeFile(); - } - mkdirp(this.outputFileSystem, recordsOutputPathDirectory, err => { - if (err) return callback(err); - writeFile(); - }); +/* istanbul ignore next */ +/** + * @param {number} mtime mtime + */ +const applyMtime = mtime => { + if (FS_ACCURACY > 1 && mtime % 2 !== 0) FS_ACCURACY = 1; + else if (FS_ACCURACY > 10 && mtime % 20 !== 0) FS_ACCURACY = 10; + else if (FS_ACCURACY > 100 && mtime % 200 !== 0) FS_ACCURACY = 100; + else if (FS_ACCURACY > 1000 && mtime % 2000 !== 0) FS_ACCURACY = 1000; +}; + +/** + * @template T + * @template K + * @param {Map} a source map + * @param {Map} b joining map + * @returns {Map} joined map + */ +const mergeMaps = (a, b) => { + if (!b || b.size === 0) return a; + if (!a || a.size === 0) return b; + const map = new Map(a); + for (const [key, value] of b) { + map.set(key, value); } + return map; +}; - /** - * @param {Callback} callback signals when the call finishes - * @returns {void} - */ - readRecords(callback) { - if (this.hooks.readRecords.isUsed()) { - if (this.recordsInputPath) { - asyncLib.parallel([ - cb => this.hooks.readRecords.callAsync(cb), - this._readRecords.bind(this) - ]); - } else { - this.records = {}; - this.hooks.readRecords.callAsync(callback); - } - } else { - if (this.recordsInputPath) { - this._readRecords(callback); - } else { - this.records = {}; - callback(); - } - } +/** + * @template T + * @template K + * @param {Set} a source map + * @param {Set} b joining map + * @returns {Set} joined map + */ +const mergeSets = (a, b) => { + if (!b || b.size === 0) return a; + if (!a || a.size === 0) return b; + const map = new Set(a); + for (const item of b) { + map.add(item); } + return map; +}; - /** - * @param {Callback} callback signals when the call finishes - * @returns {void} - */ - _readRecords(callback) { - if (!this.recordsInputPath) { - this.records = {}; - return callback(); +/** + * Finding file or directory to manage + * @param {string} managedPath path that is managing by {@link FileSystemInfo} + * @param {string} path path to file or directory + * @returns {string|null} managed item + * @example + * getManagedItem( + * '/Users/user/my-project/node_modules/', + * '/Users/user/my-project/node_modules/package/index.js' + * ) === '/Users/user/my-project/node_modules/package' + * getManagedItem( + * '/Users/user/my-project/node_modules/', + * '/Users/user/my-project/node_modules/package1/node_modules/package2' + * ) === '/Users/user/my-project/node_modules/package1/node_modules/package2' + * getManagedItem( + * '/Users/user/my-project/node_modules/', + * '/Users/user/my-project/node_modules/.bin/script.js' + * ) === null // hidden files are disallowed as managed items + * getManagedItem( + * '/Users/user/my-project/node_modules/', + * '/Users/user/my-project/node_modules/package' + * ) === '/Users/user/my-project/node_modules/package' + */ +const getManagedItem = (managedPath, path) => { + let i = managedPath.length; + let slashes = 1; + let startingPosition = true; + loop: while (i < path.length) { + switch (path.charCodeAt(i)) { + case 47: // slash + case 92: // backslash + if (--slashes === 0) break loop; + startingPosition = true; + break; + case 46: // . + // hidden files are disallowed as managed items + // it's probably .yarn-integrity or .cache + if (startingPosition) return null; + break; + case 64: // @ + if (!startingPosition) return null; + slashes++; + break; + default: + startingPosition = false; + break; } - this.inputFileSystem.stat(this.recordsInputPath, err => { - // It doesn't exist - // We can ignore this. - if (err) return callback(); - - this.inputFileSystem.readFile(this.recordsInputPath, (err, content) => { - if (err) return callback(err); - - try { - this.records = parseJson(content.toString("utf-8")); - } catch (e) { - e.message = "Cannot parse records: " + e.message; - return callback(e); - } - - return callback(); - }); - }); + i++; } - - /** - * @param {Compilation} compilation the compilation - * @param {string} compilerName the compiler's name - * @param {number} compilerIndex the compiler's index - * @param {OutputOptions=} outputOptions the output options - * @param {WebpackPluginInstance[]=} plugins the plugins to apply - * @returns {Compiler} a child compiler - */ - createChildCompiler( - compilation, - compilerName, - compilerIndex, - outputOptions, - plugins + if (i === path.length) slashes--; + // return null when path is incomplete + if (slashes !== 0) return null; + // if (path.slice(i + 1, i + 13) === "node_modules") + if ( + path.length >= i + 13 && + path.charCodeAt(i + 1) === 110 && + path.charCodeAt(i + 2) === 111 && + path.charCodeAt(i + 3) === 100 && + path.charCodeAt(i + 4) === 101 && + path.charCodeAt(i + 5) === 95 && + path.charCodeAt(i + 6) === 109 && + path.charCodeAt(i + 7) === 111 && + path.charCodeAt(i + 8) === 100 && + path.charCodeAt(i + 9) === 117 && + path.charCodeAt(i + 10) === 108 && + path.charCodeAt(i + 11) === 101 && + path.charCodeAt(i + 12) === 115 ) { - const childCompiler = new Compiler(this.context, { - ...this.options, - output: { - ...this.options.output, - ...outputOptions - } - }); - childCompiler.name = compilerName; - childCompiler.outputPath = this.outputPath; - childCompiler.inputFileSystem = this.inputFileSystem; - childCompiler.outputFileSystem = null; - childCompiler.resolverFactory = this.resolverFactory; - childCompiler.modifiedFiles = this.modifiedFiles; - childCompiler.removedFiles = this.removedFiles; - childCompiler.fileTimestamps = this.fileTimestamps; - childCompiler.contextTimestamps = this.contextTimestamps; - childCompiler.fsStartTime = this.fsStartTime; - childCompiler.cache = this.cache; - childCompiler.compilerPath = `${this.compilerPath}${compilerName}|${compilerIndex}|`; - childCompiler._backCompat = this._backCompat; - - const relativeCompilerName = makePathsRelative( - this.context, - compilerName, - this.root - ); - if (!this.records[relativeCompilerName]) { - this.records[relativeCompilerName] = []; - } - if (this.records[relativeCompilerName][compilerIndex]) { - childCompiler.records = this.records[relativeCompilerName][compilerIndex]; - } else { - this.records[relativeCompilerName].push((childCompiler.records = {})); - } - - childCompiler.parentCompilation = compilation; - childCompiler.root = this.root; - if (Array.isArray(plugins)) { - for (const plugin of plugins) { - plugin.apply(childCompiler); - } + // if this is the end of the path + if (path.length === i + 13) { + // return the node_modules directory + // it's special + return path; } - for (const name in this.hooks) { - if ( - ![ - "make", - "compile", - "emit", - "afterEmit", - "invalid", - "done", - "thisCompilation" - ].includes(name) - ) { - if (childCompiler.hooks[name]) { - childCompiler.hooks[name].taps = this.hooks[name].taps.slice(); - } - } + const c = path.charCodeAt(i + 13); + // if next symbol is slash or backslash + if (c === 47 || c === 92) { + // Managed subpath + return getManagedItem(path.slice(0, i + 14), path); } - - compilation.hooks.childCompiler.call( - childCompiler, - compilerName, - compilerIndex - ); - - return childCompiler; - } - - isChild() { - return !!this.parentCompilation; - } - - createCompilation(params) { - this._cleanupLastCompilation(); - return (this._lastCompilation = new Compilation(this, params)); - } - - /** - * @param {CompilationParams} params the compilation parameters - * @returns {Compilation} the created compilation - */ - newCompilation(params) { - const compilation = this.createCompilation(params); - compilation.name = this.name; - compilation.records = this.records; - this.hooks.thisCompilation.call(compilation, params); - this.hooks.compilation.call(compilation, params); - return compilation; } + return path.slice(0, i); +}; - createNormalModuleFactory() { - this._cleanupLastNormalModuleFactory(); - const normalModuleFactory = new NormalModuleFactory({ - context: this.options.context, - fs: this.inputFileSystem, - resolverFactory: this.resolverFactory, - options: this.options.module, - associatedObjectForCache: this.root, - layers: this.options.experiments.layers - }); - this._lastNormalModuleFactory = normalModuleFactory; - this.hooks.normalModuleFactory.call(normalModuleFactory); - return normalModuleFactory; - } +/** + * @template {ContextFileSystemInfoEntry | ContextTimestampAndHash} T + * @param {T} entry entry + * @returns {T["resolved"] | undefined} the resolved entry + */ +const getResolvedTimestamp = entry => { + if (entry === null) return null; + if (entry.resolved !== undefined) return entry.resolved; + return entry.symlinks === undefined ? entry : undefined; +}; - createContextModuleFactory() { - const contextModuleFactory = new ContextModuleFactory(this.resolverFactory); - this.hooks.contextModuleFactory.call(contextModuleFactory); - return contextModuleFactory; - } +/** + * @param {ContextHash} entry entry + * @returns {string | undefined} the resolved entry + */ +const getResolvedHash = entry => { + if (entry === null) return null; + if (entry.resolved !== undefined) return entry.resolved; + return entry.symlinks === undefined ? entry.hash : undefined; +}; - newCompilationParams() { - const params = { - normalModuleFactory: this.createNormalModuleFactory(), - contextModuleFactory: this.createContextModuleFactory() - }; - return params; - } +const addAll = (source, target) => { + for (const key of source) target.add(key); +}; +/** + * Used to access information about the filesystem in a cached way + */ +class FileSystemInfo { /** - * @param {Callback} callback signals when the compilation finishes - * @returns {void} - */ - compile(callback) { - const params = this.newCompilationParams(); - this.hooks.beforeCompile.callAsync(params, err => { - if (err) return callback(err); - - this.hooks.compile.call(params); - - const compilation = this.newCompilation(params); - - const logger = compilation.getLogger("webpack.Compiler"); - - logger.time("make hook"); - this.hooks.make.callAsync(compilation, err => { - logger.timeEnd("make hook"); - if (err) return callback(err); + * @param {InputFileSystem} fs file system + * @param {Object} options options + * @param {Iterable=} options.managedPaths paths that are only managed by a package manager + * @param {Iterable=} options.immutablePaths paths that are immutable + * @param {Logger=} options.logger logger used to log invalid snapshots + * @param {string | Hash=} options.hashFunction the hash function to use + */ + constructor( + fs, + { + managedPaths = [], + immutablePaths = [], + logger, + hashFunction = "md4" + } = {} + ) { + this.fs = fs; + this.logger = logger; + this._remainingLogs = logger ? 40 : 0; + this._loggedPaths = logger ? new Set() : undefined; + this._hashFunction = hashFunction; + /** @type {WeakMap} */ + this._snapshotCache = new WeakMap(); + this._fileTimestampsOptimization = new SnapshotOptimization( + s => s.hasFileTimestamps(), + s => s.fileTimestamps, + (s, v) => s.setFileTimestamps(v) + ); + this._fileHashesOptimization = new SnapshotOptimization( + s => s.hasFileHashes(), + s => s.fileHashes, + (s, v) => s.setFileHashes(v), + false + ); + this._fileTshsOptimization = new SnapshotOptimization( + s => s.hasFileTshs(), + s => s.fileTshs, + (s, v) => s.setFileTshs(v) + ); + this._contextTimestampsOptimization = new SnapshotOptimization( + s => s.hasContextTimestamps(), + s => s.contextTimestamps, + (s, v) => s.setContextTimestamps(v) + ); + this._contextHashesOptimization = new SnapshotOptimization( + s => s.hasContextHashes(), + s => s.contextHashes, + (s, v) => s.setContextHashes(v), + false + ); + this._contextTshsOptimization = new SnapshotOptimization( + s => s.hasContextTshs(), + s => s.contextTshs, + (s, v) => s.setContextTshs(v) + ); + this._missingExistenceOptimization = new SnapshotOptimization( + s => s.hasMissingExistence(), + s => s.missingExistence, + (s, v) => s.setMissingExistence(v), + false + ); + this._managedItemInfoOptimization = new SnapshotOptimization( + s => s.hasManagedItemInfo(), + s => s.managedItemInfo, + (s, v) => s.setManagedItemInfo(v), + false + ); + this._managedFilesOptimization = new SnapshotOptimization( + s => s.hasManagedFiles(), + s => s.managedFiles, + (s, v) => s.setManagedFiles(v), + false, + true + ); + this._managedContextsOptimization = new SnapshotOptimization( + s => s.hasManagedContexts(), + s => s.managedContexts, + (s, v) => s.setManagedContexts(v), + false, + true + ); + this._managedMissingOptimization = new SnapshotOptimization( + s => s.hasManagedMissing(), + s => s.managedMissing, + (s, v) => s.setManagedMissing(v), + false, + true + ); + /** @type {StackedCacheMap} */ + this._fileTimestamps = new StackedCacheMap(); + /** @type {Map} */ + this._fileHashes = new Map(); + /** @type {Map} */ + this._fileTshs = new Map(); + /** @type {StackedCacheMap} */ + this._contextTimestamps = new StackedCacheMap(); + /** @type {Map} */ + this._contextHashes = new Map(); + /** @type {Map} */ + this._contextTshs = new Map(); + /** @type {Map} */ + this._managedItems = new Map(); + /** @type {AsyncQueue} */ + this.fileTimestampQueue = new AsyncQueue({ + name: "file timestamp", + parallelism: 30, + processor: this._readFileTimestamp.bind(this) + }); + /** @type {AsyncQueue} */ + this.fileHashQueue = new AsyncQueue({ + name: "file hash", + parallelism: 10, + processor: this._readFileHash.bind(this) + }); + /** @type {AsyncQueue} */ + this.contextTimestampQueue = new AsyncQueue({ + name: "context timestamp", + parallelism: 2, + processor: this._readContextTimestamp.bind(this) + }); + /** @type {AsyncQueue} */ + this.contextHashQueue = new AsyncQueue({ + name: "context hash", + parallelism: 2, + processor: this._readContextHash.bind(this) + }); + /** @type {AsyncQueue} */ + this.contextTshQueue = new AsyncQueue({ + name: "context hash and timestamp", + parallelism: 2, + processor: this._readContextTimestampAndHash.bind(this) + }); + /** @type {AsyncQueue} */ + this.managedItemQueue = new AsyncQueue({ + name: "managed item info", + parallelism: 10, + processor: this._getManagedItemInfo.bind(this) + }); + /** @type {AsyncQueue>} */ + this.managedItemDirectoryQueue = new AsyncQueue({ + name: "managed item directory info", + parallelism: 10, + processor: this._getManagedItemDirectoryInfo.bind(this) + }); + this.managedPaths = Array.from(managedPaths); + this.managedPathsWithSlash = /** @type {string[]} */ ( + this.managedPaths.filter(p => typeof p === "string") + ).map(p => join(fs, p, "_").slice(0, -1)); - logger.time("finish make hook"); - this.hooks.finishMake.callAsync(compilation, err => { - logger.timeEnd("finish make hook"); - if (err) return callback(err); + this.managedPathsRegExps = /** @type {RegExp[]} */ ( + this.managedPaths.filter(p => typeof p !== "string") + ); + this.immutablePaths = Array.from(immutablePaths); + this.immutablePathsWithSlash = /** @type {string[]} */ ( + this.immutablePaths.filter(p => typeof p === "string") + ).map(p => join(fs, p, "_").slice(0, -1)); + this.immutablePathsRegExps = /** @type {RegExp[]} */ ( + this.immutablePaths.filter(p => typeof p !== "string") + ); - process.nextTick(() => { - logger.time("finish compilation"); - compilation.finish(err => { - logger.timeEnd("finish compilation"); - if (err) return callback(err); + this._cachedDeprecatedFileTimestamps = undefined; + this._cachedDeprecatedContextTimestamps = undefined; - logger.time("seal compilation"); - compilation.seal(err => { - logger.timeEnd("seal compilation"); - if (err) return callback(err); + this._warnAboutExperimentalEsmTracking = false; - logger.time("afterCompile hook"); - this.hooks.afterCompile.callAsync(compilation, err => { - logger.timeEnd("afterCompile hook"); - if (err) return callback(err); + this._statCreatedSnapshots = 0; + this._statTestedSnapshotsCached = 0; + this._statTestedSnapshotsNotCached = 0; + this._statTestedChildrenCached = 0; + this._statTestedChildrenNotCached = 0; + this._statTestedEntries = 0; + } - return callback(null, compilation); - }); - }); - }); - }); - }); - }); - }); + logStatistics() { + const logWhenMessage = (header, message) => { + if (message) { + this.logger.log(`${header}: ${message}`); + } + }; + this.logger.log(`${this._statCreatedSnapshots} new snapshots created`); + this.logger.log( + `${ + this._statTestedSnapshotsNotCached && + Math.round( + (this._statTestedSnapshotsNotCached * 100) / + (this._statTestedSnapshotsCached + + this._statTestedSnapshotsNotCached) + ) + }% root snapshot uncached (${this._statTestedSnapshotsNotCached} / ${ + this._statTestedSnapshotsCached + this._statTestedSnapshotsNotCached + })` + ); + this.logger.log( + `${ + this._statTestedChildrenNotCached && + Math.round( + (this._statTestedChildrenNotCached * 100) / + (this._statTestedChildrenCached + this._statTestedChildrenNotCached) + ) + }% children snapshot uncached (${this._statTestedChildrenNotCached} / ${ + this._statTestedChildrenCached + this._statTestedChildrenNotCached + })` + ); + this.logger.log(`${this._statTestedEntries} entries tested`); + this.logger.log( + `File info in cache: ${this._fileTimestamps.size} timestamps ${this._fileHashes.size} hashes ${this._fileTshs.size} timestamp hash combinations` + ); + logWhenMessage( + `File timestamp snapshot optimization`, + this._fileTimestampsOptimization.getStatisticMessage() + ); + logWhenMessage( + `File hash snapshot optimization`, + this._fileHashesOptimization.getStatisticMessage() + ); + logWhenMessage( + `File timestamp hash combination snapshot optimization`, + this._fileTshsOptimization.getStatisticMessage() + ); + this.logger.log( + `Directory info in cache: ${this._contextTimestamps.size} timestamps ${this._contextHashes.size} hashes ${this._contextTshs.size} timestamp hash combinations` + ); + logWhenMessage( + `Directory timestamp snapshot optimization`, + this._contextTimestampsOptimization.getStatisticMessage() + ); + logWhenMessage( + `Directory hash snapshot optimization`, + this._contextHashesOptimization.getStatisticMessage() + ); + logWhenMessage( + `Directory timestamp hash combination snapshot optimization`, + this._contextTshsOptimization.getStatisticMessage() + ); + logWhenMessage( + `Missing items snapshot optimization`, + this._missingExistenceOptimization.getStatisticMessage() + ); + this.logger.log( + `Managed items info in cache: ${this._managedItems.size} items` + ); + logWhenMessage( + `Managed items snapshot optimization`, + this._managedItemInfoOptimization.getStatisticMessage() + ); + logWhenMessage( + `Managed files snapshot optimization`, + this._managedFilesOptimization.getStatisticMessage() + ); + logWhenMessage( + `Managed contexts snapshot optimization`, + this._managedContextsOptimization.getStatisticMessage() + ); + logWhenMessage( + `Managed missing snapshot optimization`, + this._managedMissingOptimization.getStatisticMessage() + ); } - /** - * @param {Callback} callback signals when the compiler closes - * @returns {void} - */ - close(callback) { - if (this.watching) { - // When there is still an active watching, close this first - this.watching.close(err => { - this.close(callback); - }); - return; + _log(path, reason, ...args) { + const key = path + reason; + if (this._loggedPaths.has(key)) return; + this._loggedPaths.add(key); + this.logger.debug(`${path} invalidated because ${reason}`, ...args); + if (--this._remainingLogs === 0) { + this.logger.debug( + "Logging limit has been reached and no further logging will be emitted by FileSystemInfo" + ); } - this.hooks.shutdown.callAsync(err => { - if (err) return callback(err); - // Get rid of reference to last compilation to avoid leaking memory - // We can't run this._cleanupLastCompilation() as the Stats to this compilation - // might be still in use. We try to get rid of the reference to the cache instead. - this._lastCompilation = undefined; - this._lastNormalModuleFactory = undefined; - this.cache.shutdown(callback); - }); } -} - -module.exports = Compiler; + clear() { + this._remainingLogs = this.logger ? 40 : 0; + if (this._loggedPaths !== undefined) this._loggedPaths.clear(); -/***/ }), - -/***/ 98229: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @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} exportMap mapping from export name to symbol - * @property {Map} rawExportMap mapping from export name to symbol - * @property {string=} namespaceExportSymbol - */ - -/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo} ModuleInfo */ + this._snapshotCache = new WeakMap(); + this._fileTimestampsOptimization.clear(); + this._fileHashesOptimization.clear(); + this._fileTshsOptimization.clear(); + this._contextTimestampsOptimization.clear(); + this._contextHashesOptimization.clear(); + this._contextTshsOptimization.clear(); + this._missingExistenceOptimization.clear(); + this._managedItemInfoOptimization.clear(); + this._managedFilesOptimization.clear(); + this._managedContextsOptimization.clear(); + this._managedMissingOptimization.clear(); + this._fileTimestamps.clear(); + this._fileHashes.clear(); + this._fileTshs.clear(); + this._contextTimestamps.clear(); + this._contextHashes.clear(); + this._contextTshs.clear(); + this._managedItems.clear(); + this._managedItems.clear(); -/** - * @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 - */ + this._cachedDeprecatedFileTimestamps = undefined; + this._cachedDeprecatedContextTimestamps = undefined; -class ConcatenationScope { - /** - * @param {ModuleInfo[] | Map} 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; + this._statCreatedSnapshots = 0; + this._statTestedSnapshotsCached = 0; + this._statTestedSnapshotsNotCached = 0; + this._statTestedChildrenCached = 0; + this._statTestedChildrenNotCached = 0; + this._statTestedEntries = 0; } /** - * @param {Module} module the referenced module - * @returns {boolean} true, when it's in the scope + * @param {ReadonlyMap} map timestamps + * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it + * @returns {void} */ - isModuleInScope(module) { - return this._modulesMap.has(module); + addFileTimestamps(map, immutable) { + this._fileTimestamps.addAll(map, immutable); + this._cachedDeprecatedFileTimestamps = undefined; } /** - * - * @param {string} exportName name of the export - * @param {string} symbol identifier of the export in source code + * @param {ReadonlyMap} map timestamps + * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it + * @returns {void} */ - registerExport(exportName, symbol) { - if (!this._currentModule.exportMap) { - this._currentModule.exportMap = new Map(); - } - if (!this._currentModule.exportMap.has(exportName)) { - this._currentModule.exportMap.set(exportName, symbol); - } + addContextTimestamps(map, immutable) { + this._contextTimestamps.addAll(map, immutable); + this._cachedDeprecatedContextTimestamps = undefined; } /** - * - * @param {string} exportName name of the export - * @param {string} expression expression to be used + * @param {string} path file path + * @param {function((WebpackError | null)=, (FileSystemInfoEntry | "ignore" | null)=): void} callback callback function + * @returns {void} */ - registerRawExport(exportName, expression) { - if (!this._currentModule.rawExportMap) { - this._currentModule.rawExportMap = new Map(); - } - if (!this._currentModule.rawExportMap.has(exportName)) { - this._currentModule.rawExportMap.set(exportName, expression); - } + getFileTimestamp(path, callback) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) return callback(null, cache); + this.fileTimestampQueue.add(path, callback); } /** - * @param {string} symbol identifier of the export in source code + * @param {string} path context path + * @param {function((WebpackError | null)=, (ResolvedContextFileSystemInfoEntry | "ignore" | null)=): void} callback callback function + * @returns {void} */ - registerNamespaceExport(symbol) { - this._currentModule.namespaceExportSymbol = symbol; + getContextTimestamp(path, callback) { + const cache = this._contextTimestamps.get(path); + if (cache !== undefined) { + if (cache === "ignore") return callback(null, "ignore"); + const resolved = getResolvedTimestamp(cache); + if (resolved !== undefined) return callback(null, resolved); + return this._resolveContextTimestamp(cache, callback); + } + this.contextTimestampQueue.add(path, (err, entry) => { + if (err) return callback(err); + const resolved = getResolvedTimestamp(entry); + if (resolved !== undefined) return callback(null, resolved); + this._resolveContextTimestamp(entry, callback); + }); } /** - * - * @param {Module} module the referenced module - * @param {Partial} options options - * @returns {string} the reference as identifier + * @param {string} path context path + * @param {function((WebpackError | null)=, (ContextFileSystemInfoEntry | "ignore" | null)=): void} callback callback function + * @returns {void} */ - 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}__._`; + _getUnresolvedContextTimestamp(path, callback) { + const cache = this._contextTimestamps.get(path); + if (cache !== undefined) return callback(null, cache); + this.contextTimestampQueue.add(path, callback); } /** - * @param {string} name the identifier - * @returns {boolean} true, when it's an module reference + * @param {string} path file path + * @param {function((WebpackError | null)=, string=): void} callback callback function + * @returns {void} */ - static isModuleReference(name) { - return MODULE_REFERENCE_REGEXP.test(name); + getFileHash(path, callback) { + const cache = this._fileHashes.get(path); + if (cache !== undefined) return callback(null, cache); + this.fileHashQueue.add(path, callback); } /** - * @param {string} name the identifier - * @returns {ModuleReferenceOptions & { index: number }} parsed options and index + * @param {string} path context path + * @param {function((WebpackError | null)=, string=): void} callback callback function + * @returns {void} */ - 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; - - -/***/ }), - -/***/ 95735: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Maksim Nazarjev @acupofspirt -*/ - - - -const WebpackError = __webpack_require__(53799); - -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."; - } -}; - - -/***/ }), - -/***/ 61333: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { ConcatSource, PrefixSource } = __webpack_require__(51255); -const InitFragment = __webpack_require__(55870); -const Template = __webpack_require__(39722); -const { mergeRuntime } = __webpack_require__(17156); - -/** @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" - ); + getContextHash(path, callback) { + const cache = this._contextHashes.get(path); + if (cache !== undefined) { + const resolved = getResolvedHash(cache); + if (resolved !== undefined) return callback(null, resolved); + return this._resolveContextHash(cache, callback); + } + this.contextHashQueue.add(path, (err, entry) => { + if (err) return callback(err); + const resolved = getResolvedHash(entry); + if (resolved !== undefined) return callback(null, resolved); + this._resolveContextHash(entry, callback); + }); } -}; -/** - * @typedef {GenerateContext} Context - */ -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 + * @param {string} path context path + * @param {function((WebpackError | null)=, ContextHash=): void} callback callback function + * @returns {void} */ - constructor( - content, - stage, - position, - key, - runtimeCondition = true, - endContent - ) { - super(content, stage, position, key, endContent); - this.runtimeCondition = runtimeCondition; + _getUnresolvedContextHash(path, callback) { + const cache = this._contextHashes.get(path); + if (cache !== undefined) return callback(null, cache); + this.contextHashQueue.add(path, callback); } /** - * @param {Context} context context - * @returns {string|Source} the source code that will be included as initialization code + * @param {string} path context path + * @param {function((WebpackError | null)=, ResolvedContextTimestampAndHash=): void} callback callback function + * @returns {void} */ - getContent(context) { - if (this.runtimeCondition === false || !this.content) return ""; - if (this.runtimeCondition === true) return this.content; - const expr = context.runtimeTemplate.runtimeConditionExpression({ - chunkGraph: context.chunkGraph, - runtimeRequirements: context.runtimeRequirements, - runtime: context.runtime, - runtimeCondition: this.runtimeCondition + getContextTsh(path, callback) { + const cache = this._contextTshs.get(path); + if (cache !== undefined) { + const resolved = getResolvedTimestamp(cache); + if (resolved !== undefined) return callback(null, resolved); + return this._resolveContextTsh(cache, callback); + } + this.contextTshQueue.add(path, (err, entry) => { + if (err) return callback(err); + const resolved = getResolvedTimestamp(entry); + if (resolved !== undefined) return callback(null, resolved); + this._resolveContextTsh(entry, callback); }); - if (expr === "true") return this.content; - return wrapInCondition(expr, this.content); } /** - * @param {Context} context context - * @returns {string|Source=} the source code that will be included at the end of the module + * @param {string} path context path + * @param {function((WebpackError | null)=, ContextTimestampAndHash=): void} callback callback function + * @returns {void} */ - getEndContent(context) { - if (this.runtimeCondition === false || !this.endContent) return ""; - if (this.runtimeCondition === true) return this.endContent; - const expr = context.runtimeTemplate.runtimeConditionExpression({ - chunkGraph: context.chunkGraph, - runtimeRequirements: context.runtimeRequirements, - runtime: context.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; - - -/***/ }), - -/***/ 11146: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const CachedConstDependency = __webpack_require__(57403); -const ConstDependency = __webpack_require__(76911); -const { evaluateToString } = __webpack_require__(93998); -const { parseResource } = __webpack_require__(82186); - -/** @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; - } + _getUnresolvedContextTsh(path, callback) { + const cache = this._contextTshs.get(path); + if (cache !== undefined) return callback(null, cache); + this.contextTshQueue.add(path, callback); } -}; -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; - } + _createBuildDependenciesResolvers() { + const resolveContext = createResolver({ + resolveToContext: true, + exportsFields: [], + fileSystem: this.fs + }); + const resolveCjs = createResolver({ + extensions: [".js", ".json", ".node"], + conditionNames: ["require", "node"], + exportsFields: ["exports"], + fileSystem: this.fs + }); + const resolveCjsAsChild = createResolver({ + extensions: [".js", ".json", ".node"], + conditionNames: ["require", "node"], + exportsFields: [], + fileSystem: this.fs + }); + const resolveEsm = createResolver({ + extensions: [".js", ".json", ".node"], + fullySpecified: true, + conditionNames: ["import", "node"], + exportsFields: ["exports"], + fileSystem: this.fs + }); + return { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild }; } - return Array.from(declarations); -}; -class ConstPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {string} context context directory + * @param {Iterable} deps dependencies + * @param {function((Error | null)=, ResolveBuildDependenciesResult=): void} callback callback function * @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() - ); + resolveBuildDependencies(context, deps, callback) { + const { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild } = + this._createBuildDependenciesResolvers(); - 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); + /** @type {Set} */ + const files = new Set(); + /** @type {Set} */ + const fileSymlinks = new Set(); + /** @type {Set} */ + const directories = new Set(); + /** @type {Set} */ + const directorySymlinks = new Set(); + /** @type {Set} */ + const missing = new Set(); + /** @type {Set} */ + const resolveFiles = new Set(); + /** @type {Set} */ + const resolveDirectories = new Set(); + /** @type {Set} */ + const resolveMissing = new Set(); + /** @type {Map} */ + const resolveResults = new Map(); + const invalidResolveResults = new Set(); + const resolverContext = { + fileDependencies: resolveFiles, + contextDependencies: resolveDirectories, + missingDependencies: resolveMissing + }; + const expectedToString = expected => { + return expected ? ` (expected ${expected})` : ""; + }; + const jobToString = job => { + switch (job.type) { + case RBDT_RESOLVE_CJS: + return `resolve commonjs ${job.path}${expectedToString( + job.expected + )}`; + case RBDT_RESOLVE_ESM: + return `resolve esm ${job.path}${expectedToString(job.expected)}`; + case RBDT_RESOLVE_DIRECTORY: + return `resolve directory ${job.path}`; + case RBDT_RESOLVE_CJS_FILE: + return `resolve commonjs file ${job.path}${expectedToString( + job.expected + )}`; + case RBDT_RESOLVE_ESM_FILE: + return `resolve esm file ${job.path}${expectedToString( + job.expected + )}`; + case RBDT_DIRECTORY: + return `directory ${job.path}`; + case RBDT_FILE: + return `file ${job.path}`; + case RBDT_DIRECTORY_DEPENDENCIES: + return `directory dependencies ${job.path}`; + case RBDT_FILE_DEPENDENCIES: + return `file dependencies ${job.path}`; + } + return `unknown ${job.type} ${job.path}`; + }; + const pathToString = job => { + let result = ` at ${jobToString(job)}`; + job = job.issuer; + while (job !== undefined) { + result += `\n at ${jobToString(job)}`; + job = job.issuer; + } + return result; + }; + processAsyncTree( + Array.from(deps, dep => ({ + type: RBDT_RESOLVE_CJS, + context, + path: dep, + expected: undefined, + issuer: undefined + })), + 20, + (job, push, callback) => { + const { type, context, path, expected } = job; + const resolveDirectory = path => { + const key = `d\n${context}\n${path}`; + if (resolveResults.has(key)) { + return callback(); + } + resolveResults.set(key, undefined); + resolveContext(context, path, resolverContext, (err, _, result) => { + if (err) { + if (expected === false) { + resolveResults.set(key, false); + return callback(); + } + invalidResolveResults.add(key); + err.message += `\nwhile resolving '${path}' in ${context} to a directory`; + return callback(err); + } + const resultPath = result.path; + resolveResults.set(key, resultPath); + push({ + type: RBDT_DIRECTORY, + context: undefined, + path: resultPath, + expected: undefined, + issuer: job + }); + callback(); + }); + }; + const resolveFile = (path, symbol, resolve) => { + const key = `${symbol}\n${context}\n${path}`; + if (resolveResults.has(key)) { + return callback(); + } + resolveResults.set(key, undefined); + resolve(context, path, resolverContext, (err, _, result) => { + if (typeof expected === "string") { + if (!err && result && result.path === expected) { + resolveResults.set(key, result.path); } else { - parser.walkExpression(statement.test); + invalidResolveResults.add(key); + this.logger.warn( + `Resolving '${path}' in ${context} for build dependencies doesn't lead to expected result '${expected}', but to '${ + err || (result && result.path) + }' instead. Resolving dependencies are ignored for this path.\n${pathToString( + job + )}` + ); } - 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 = "{}"; + } else { + if (err) { + if (expected === false) { + resolveResults.set(key, false); + return callback(); } - const dep = new ConstDependency( - replacement, - branchToRemove.range - ); - dep.loc = branchToRemove.loc; - parser.state.module.addPresentationalDependency(dep); + invalidResolveResults.add(key); + err.message += `\nwhile resolving '${path}' in ${context} as file\n${pathToString( + job + )}`; + return callback(err); } - return bool; + const resultPath = result.path; + resolveResults.set(key, resultPath); + push({ + type: RBDT_FILE, + context: undefined, + path: resultPath, + expected: undefined, + issuer: job + }); } + callback(); }); - 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; + }; + switch (type) { + case RBDT_RESOLVE_CJS: { + const isDirectory = /[\\/]$/.test(path); + if (isDirectory) { + resolveDirectory(path.slice(0, path.length - 1)); + } else { + resolveFile(path, "f", resolveCjs); + } + break; + } + case RBDT_RESOLVE_ESM: { + const isDirectory = /[\\/]$/.test(path); + if (isDirectory) { + resolveDirectory(path.slice(0, path.length - 1)); + } else { + resolveFile(path); + } + break; + } + case RBDT_RESOLVE_DIRECTORY: { + resolveDirectory(path); + break; + } + case RBDT_RESOLVE_CJS_FILE: { + resolveFile(path, "f", resolveCjs); + break; + } + case RBDT_RESOLVE_CJS_FILE_AS_CHILD: { + resolveFile(path, "c", resolveCjsAsChild); + break; + } + case RBDT_RESOLVE_ESM_FILE: { + resolveFile(path, "e", resolveEsm); + break; + } + case RBDT_FILE: { + if (files.has(path)) { + callback(); + break; + } + files.add(path); + this.fs.realpath(path, (err, _realPath) => { + if (err) return callback(err); + const realPath = /** @type {string} */ (_realPath); + if (realPath !== path) { + fileSymlinks.add(path); + resolveFiles.add(path); + if (files.has(realPath)) return callback(); + files.add(realPath); } + push({ + type: RBDT_FILE_DEPENDENCIES, + context: undefined, + path: realPath, + expected: undefined, + issuer: job + }); + callback(); + }); + break; + } + case RBDT_DIRECTORY: { + if (directories.has(path)) { + callback(); + break; } - ); - 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); + directories.add(path); + this.fs.realpath(path, (err, _realPath) => { + if (err) return callback(err); + const realPath = /** @type {string} */ (_realPath); + if (realPath !== path) { + directorySymlinks.add(path); + resolveFiles.add(path); + if (directories.has(realPath)) return callback(); + directories.add(realPath); + } + push({ + type: RBDT_DIRECTORY_DEPENDENCIES, + context: undefined, + path: realPath, + expected: undefined, + issuer: job + }); + callback(); + }); + break; + } + case RBDT_FILE_DEPENDENCIES: { + // Check for known files without dependencies + if (/\.json5?$|\.yarn-integrity$|yarn\.lock$|\.ya?ml/.test(path)) { + process.nextTick(callback); + break; + } + // Check commonjs cache for the module + /** @type {NodeModule} */ + const module = require.cache[path]; + if (module && Array.isArray(module.children)) { + children: for (const child of module.children) { + let childPath = child.filename; + if (childPath) { + push({ + type: RBDT_FILE, + context: undefined, + path: childPath, + expected: undefined, + issuer: job + }); + const context = dirname(this.fs, path); + for (const modulePath of module.paths) { + if (childPath.startsWith(modulePath)) { + let subPath = childPath.slice(modulePath.length + 1); + const packageMatch = /^(@[^\\/]+[\\/])[^\\/]+/.exec( + subPath + ); + if (packageMatch) { + push({ + type: RBDT_FILE, + context: undefined, + path: + modulePath + + childPath[modulePath.length] + + packageMatch[0] + + childPath[modulePath.length] + + "package.json", + expected: false, + issuer: job + }); + } + let request = subPath.replace(/\\/g, "/"); + if (request.endsWith(".js")) + request = request.slice(0, -3); + push({ + type: RBDT_RESOLVE_CJS_FILE_AS_CHILD, + context, + path: request, + expected: child.filename, + issuer: job + }); + continue children; + } } - return keepRight; + let request = relative(this.fs, context, childPath); + if (request.endsWith(".js")) request = request.slice(0, -3); + request = request.replace(/\\/g, "/"); + if (!request.startsWith("../")) request = `./${request}`; + push({ + type: RBDT_RESOLVE_CJS_FILE, + context, + path: request, + expected: child.filename, + issuer: job + }); } - } 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 + } + } else if (supportsEsm && /\.m?js$/.test(path)) { + if (!this._warnAboutExperimentalEsmTracking) { + this.logger.log( + "Node.js doesn't offer a (nice) way to introspect the ESM dependency graph yet.\n" + + "Until a full solution is available webpack uses an experimental ESM tracking based on parsing.\n" + + "As best effort webpack parses the ESM files to guess dependencies. But this can lead to expensive and incorrect tracking." + ); + this._warnAboutExperimentalEsmTracking = true; + } + const lexer = __webpack_require__(54392); + lexer.init.then(() => { + this.fs.readFile(path, (err, content) => { + if (err) return callback(err); + try { + const context = dirname(this.fs, path); + const source = content.toString(); + const [imports] = lexer.parse(source); + for (const imp of imports) { + try { + let dependency; + if (imp.d === -1) { + // import ... from "..." + dependency = parseString( + source.substring(imp.s - 1, imp.e + 1) + ); + } else if (imp.d > -1) { + // import() + let expr = source.substring(imp.s, imp.e).trim(); + dependency = parseString(expr); + } else { + // e.g. import.meta + continue; + } + push({ + type: RBDT_RESOLVE_ESM_FILE, + context, + path: dependency, + expected: undefined, + issuer: job + }); + } catch (e) { + this.logger.warn( + `Parsing of ${path} for build dependencies failed at 'import(${source.substring( + imp.s, + imp.e + )})'.\n` + + "Build dependencies behind this expression are ignored and might cause incorrect cache invalidation." + ); + this.logger.debug(pathToString(job)); + this.logger.debug(e.stack); + } + } + } catch (e) { + this.logger.warn( + `Parsing of ${path} for build dependencies failed and all dependencies of this file are ignored, which might cause incorrect cache invalidation..` ); - dep.loc = expression.loc; - parser.state.module.addPresentationalDependency(dep); - parser.walkExpression(expression.left); + this.logger.debug(pathToString(job)); + this.logger.debug(e.stack); } - - return keepRight; + process.nextTick(callback); + }); + }, callback); + break; + } else { + this.logger.log( + `Assuming ${path} has no dependencies as we were unable to assign it to any module system.` + ); + this.logger.debug(pathToString(job)); + } + process.nextTick(callback); + break; + } + case RBDT_DIRECTORY_DEPENDENCIES: { + const match = + /(^.+[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+)/.exec(path); + const packagePath = match ? match[1] : path; + const packageJson = join(this.fs, packagePath, "package.json"); + this.fs.readFile(packageJson, (err, content) => { + if (err) { + if (err.code === "ENOENT") { + resolveMissing.add(packageJson); + const parent = dirname(this.fs, packagePath); + if (parent !== packagePath) { + push({ + type: RBDT_DIRECTORY_DEPENDENCIES, + context: undefined, + path: parent, + expected: undefined, + issuer: job + }); + } + callback(); + return; } + return callback(err); } - } - ); - 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) - ); + resolveFiles.add(packageJson); + let packageData; + try { + packageData = JSON.parse(content.toString("utf-8")); + } catch (e) { + return callback(e); + } + const depsObject = packageData.dependencies; + const optionalDepsObject = packageData.optionalDependencies; + const allDeps = new Set(); + const optionalDeps = new Set(); + if (typeof depsObject === "object" && depsObject) { + for (const dep of Object.keys(depsObject)) { + allDeps.add(dep); } - next = next.object; - } else { - if (next.optional) { - // SuperNode can not be optional - optionalExpressionsStack.push( - /** @type {ExpressionNode} */ (next.callee) - ); + } + if ( + typeof optionalDepsObject === "object" && + optionalDepsObject + ) { + for (const dep of Object.keys(optionalDepsObject)) { + allDeps.add(dep); + optionalDeps.add(dep); } - 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; + for (const dep of allDeps) { + push({ + type: RBDT_RESOLVE_DIRECTORY, + context: packagePath, + path: dep, + expected: !optionalDeps.has(dep), + issuer: job + }); } - } - }); - 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; + callback(); }); - }; - - 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); + break; + } + } + }, + err => { + if (err) return callback(err); + for (const l of fileSymlinks) files.delete(l); + for (const l of directorySymlinks) directories.delete(l); + for (const k of invalidResolveResults) resolveResults.delete(k); + callback(null, { + files, + directories, + missing, + resolveResults, + resolveDependencies: { + files: resolveFiles, + directories: resolveDirectories, + missing: resolveMissing + } + }); } ); } -} - -module.exports = ConstPlugin; - - -/***/ }), - -/***/ 21411: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./ContextModuleFactory")} ContextModuleFactory */ -class ContextExclusionPlugin { /** - * @param {RegExp} negativeMatcher Matcher regular expression + * @param {Map} resolveResults results from resolving + * @param {function((Error | null)=, boolean=): void} callback callback with true when resolveResults resolve the same way + * @returns {void} */ - constructor(negativeMatcher) { - this.negativeMatcher = negativeMatcher; + checkResolveResultsValid(resolveResults, callback) { + const { resolveCjs, resolveCjsAsChild, resolveEsm, resolveContext } = + this._createBuildDependenciesResolvers(); + asyncLib.eachLimit( + resolveResults, + 20, + ([key, expectedResult], callback) => { + const [type, context, path] = key.split("\n"); + switch (type) { + case "d": + resolveContext(context, path, {}, (err, _, result) => { + if (expectedResult === false) + return callback(err ? undefined : INVALID); + if (err) return callback(err); + const resultPath = result.path; + if (resultPath !== expectedResult) return callback(INVALID); + callback(); + }); + break; + case "f": + resolveCjs(context, path, {}, (err, _, result) => { + if (expectedResult === false) + return callback(err ? undefined : INVALID); + if (err) return callback(err); + const resultPath = result.path; + if (resultPath !== expectedResult) return callback(INVALID); + callback(); + }); + break; + case "c": + resolveCjsAsChild(context, path, {}, (err, _, result) => { + if (expectedResult === false) + return callback(err ? undefined : INVALID); + if (err) return callback(err); + const resultPath = result.path; + if (resultPath !== expectedResult) return callback(INVALID); + callback(); + }); + break; + case "e": + resolveEsm(context, path, {}, (err, _, result) => { + if (expectedResult === false) + return callback(err ? undefined : INVALID); + if (err) return callback(err); + const resultPath = result.path; + if (resultPath !== expectedResult) return callback(INVALID); + callback(); + }); + break; + default: + callback(new Error("Unexpected type in resolve result key")); + break; + } + }, + /** + * @param {Error | typeof INVALID=} err error or invalid flag + * @returns {void} + */ + err => { + if (err === INVALID) { + return callback(null, false); + } + if (err) { + return callback(err); + } + return callback(null, true); + } + ); } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * + * @param {number} startTime when processing the files has started + * @param {Iterable} files all files + * @param {Iterable} directories all directories + * @param {Iterable} missing all missing files or directories + * @param {Object} options options object (for future extensions) + * @param {boolean=} options.hash should use hash to snapshot + * @param {boolean=} options.timestamp should use timestamp to snapshot + * @param {function((WebpackError | null)=, (Snapshot | null)=): void} callback callback function * @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; - - -/***/ }), - -/***/ 76729: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { OriginalSource, RawSource } = __webpack_require__(51255); -const AsyncDependenciesBlock = __webpack_require__(47736); -const { makeWebpackError } = __webpack_require__(11351); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const WebpackError = __webpack_require__(53799); -const { - compareLocations, - concatComparators, - compareSelect, - keepOriginalOrder, - compareModulesById -} = __webpack_require__(29579); -const { contextify, parseResource } = __webpack_require__(82186); -const makeSerializable = __webpack_require__(33032); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./Module").BuildMeta} BuildMeta */ -/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */ -/** @template T @typedef {import("./util/LazySet")} LazySet */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ - -/** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */ - -/** - * @typedef {Object} ContextOptions - * @property {ContextMode} mode - * @property {boolean} recursive - * @property {RegExp} regExp - * @property {"strict"|boolean=} namespaceObject - * @property {string=} addon - * @property {string=} chunkName - * @property {RegExp=} include - * @property {RegExp=} exclude - * @property {RawChunkGroupOptions=} groupOptions - * @property {string=} typePrefix - * @property {string=} category - * @property {string[][]=} referencedExports exports referenced from modules (won't be mangled) - */ - -/** - * @typedef {Object} ContextModuleOptionsExtras - * @property {string} resource - * @property {string=} resourceQuery - * @property {string=} resourceFragment - * @property {TODO} resolveOptions - */ - -/** @typedef {ContextOptions & ContextModuleOptionsExtras} ContextModuleOptions */ - -/** - * @callback ResolveDependenciesCallback - * @param {(Error | null)=} err - * @param {ContextElementDependency[]=} dependencies - */ - -/** - * @callback ResolveDependencies - * @param {InputFileSystem} fs - * @param {ContextModuleOptions} options - * @param {ResolveDependenciesCallback} callback - */ + createSnapshot(startTime, files, directories, missing, options, callback) { + /** @type {Map} */ + const fileTimestamps = new Map(); + /** @type {Map} */ + const fileHashes = new Map(); + /** @type {Map} */ + const fileTshs = new Map(); + /** @type {Map} */ + const contextTimestamps = new Map(); + /** @type {Map} */ + const contextHashes = new Map(); + /** @type {Map} */ + const contextTshs = new Map(); + /** @type {Map} */ + const missingExistence = new Map(); + /** @type {Map} */ + const managedItemInfo = new Map(); + /** @type {Set} */ + const managedFiles = new Set(); + /** @type {Set} */ + const managedContexts = new Set(); + /** @type {Set} */ + const managedMissing = new Set(); + /** @type {Set} */ + const children = new Set(); -const SNAPSHOT_OPTIONS = { timestamp: true }; + const snapshot = new Snapshot(); + if (startTime) snapshot.setStartTime(startTime); -const TYPES = new Set(["javascript"]); + /** @type {Set} */ + const managedItems = new Set(); -class ContextModule extends Module { - /** - * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context - * @param {ContextModuleOptions} options options object - */ - constructor(resolveDependencies, options) { - const parsed = parseResource(options ? options.resource : ""); - const resource = parsed.path; - const resourceQuery = (options && options.resourceQuery) || parsed.query; - const resourceFragment = - (options && options.resourceFragment) || parsed.fragment; + /** 1 = timestamp, 2 = hash, 3 = timestamp + hash */ + const mode = options && options.hash ? (options.timestamp ? 3 : 2) : 1; - super("javascript/dynamic", resource); + let jobs = 1; + const jobDone = () => { + if (--jobs === 0) { + if (fileTimestamps.size !== 0) { + snapshot.setFileTimestamps(fileTimestamps); + } + if (fileHashes.size !== 0) { + snapshot.setFileHashes(fileHashes); + } + if (fileTshs.size !== 0) { + snapshot.setFileTshs(fileTshs); + } + if (contextTimestamps.size !== 0) { + snapshot.setContextTimestamps(contextTimestamps); + } + if (contextHashes.size !== 0) { + snapshot.setContextHashes(contextHashes); + } + if (contextTshs.size !== 0) { + snapshot.setContextTshs(contextTshs); + } + if (missingExistence.size !== 0) { + snapshot.setMissingExistence(missingExistence); + } + if (managedItemInfo.size !== 0) { + snapshot.setManagedItemInfo(managedItemInfo); + } + this._managedFilesOptimization.optimize(snapshot, managedFiles); + if (managedFiles.size !== 0) { + snapshot.setManagedFiles(managedFiles); + } + this._managedContextsOptimization.optimize(snapshot, managedContexts); + if (managedContexts.size !== 0) { + snapshot.setManagedContexts(managedContexts); + } + this._managedMissingOptimization.optimize(snapshot, managedMissing); + if (managedMissing.size !== 0) { + snapshot.setManagedMissing(managedMissing); + } + if (children.size !== 0) { + snapshot.setChildren(children); + } + this._snapshotCache.set(snapshot, true); + this._statCreatedSnapshots++; - // Info from Factory - this.resolveDependencies = resolveDependencies; - /** @type {ContextModuleOptions} */ - this.options = { - ...options, - resource, - resourceQuery, - resourceFragment + callback(null, snapshot); + } }; - if (options && options.resolveOptions !== undefined) { - this.resolveOptions = options.resolveOptions; - } - - if (options && typeof options.mode !== "string") { - throw new Error("options.mode is a required option"); - } - - this._identifier = this._createIdentifier(); - this._forceBuild = true; - } - - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; - } - - /** - * 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) { - const m = /** @type {ContextModule} */ (module); - this.resolveDependencies = m.resolveDependencies; - this.options = m.options; - } - - /** - * Assuming this module is in the cache. Remove internal references to allow freeing some memory. - */ - cleanupForCache() { - super.cleanupForCache(); - this.resolveDependencies = undefined; - } - - _prettyRegExp(regexString, stripSlash = true) { - const str = (regexString + "").replace(/!/g, "%21").replace(/\|/g, "%7C"); - return stripSlash ? str.substring(1, str.length - 1) : str; - } - - _createIdentifier() { - let identifier = this.context; - if (this.options.resourceQuery) { - identifier += `|${this.options.resourceQuery}`; - } - if (this.options.resourceFragment) { - identifier += `|${this.options.resourceFragment}`; - } - if (this.options.mode) { - identifier += `|${this.options.mode}`; - } - if (!this.options.recursive) { - identifier += "|nonrecursive"; - } - if (this.options.addon) { - identifier += `|${this.options.addon}`; - } - if (this.options.regExp) { - identifier += `|${this._prettyRegExp(this.options.regExp, false)}`; - } - if (this.options.include) { - identifier += `|include: ${this._prettyRegExp( - this.options.include, - false - )}`; - } - if (this.options.exclude) { - identifier += `|exclude: ${this._prettyRegExp( - this.options.exclude, - false - )}`; - } - if (this.options.referencedExports) { - identifier += `|referencedExports: ${JSON.stringify( - this.options.referencedExports - )}`; - } - if (this.options.chunkName) { - identifier += `|chunkName: ${this.options.chunkName}`; - } - if (this.options.groupOptions) { - identifier += `|groupOptions: ${JSON.stringify( - this.options.groupOptions - )}`; - } - if (this.options.namespaceObject === "strict") { - identifier += "|strict namespace object"; - } else if (this.options.namespaceObject) { - identifier += "|namespace object"; + const jobError = () => { + if (jobs > 0) { + // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8) + jobs = -100000000; + callback(null, null); + } + }; + const checkManaged = (path, managedSet) => { + for (const immutablePath of this.immutablePathsRegExps) { + if (immutablePath.test(path)) { + managedSet.add(path); + return true; + } + } + for (const immutablePath of this.immutablePathsWithSlash) { + if (path.startsWith(immutablePath)) { + managedSet.add(path); + return true; + } + } + for (const managedPath of this.managedPathsRegExps) { + const match = managedPath.exec(path); + if (match) { + const managedItem = getManagedItem(match[1], path); + if (managedItem) { + managedItems.add(managedItem); + managedSet.add(path); + return true; + } + } + } + for (const managedPath of this.managedPathsWithSlash) { + if (path.startsWith(managedPath)) { + const managedItem = getManagedItem(managedPath, path); + if (managedItem) { + managedItems.add(managedItem); + managedSet.add(path); + return true; + } + } + } + return false; + }; + const captureNonManaged = (items, managedSet) => { + const capturedItems = new Set(); + for (const path of items) { + if (!checkManaged(path, managedSet)) capturedItems.add(path); + } + return capturedItems; + }; + const processCapturedFiles = capturedFiles => { + switch (mode) { + case 3: + this._fileTshsOptimization.optimize(snapshot, capturedFiles); + for (const path of capturedFiles) { + const cache = this._fileTshs.get(path); + if (cache !== undefined) { + fileTshs.set(path, cache); + } else { + jobs++; + this._getFileTimestampAndHash(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting file timestamp hash combination of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + fileTshs.set(path, entry); + jobDone(); + } + }); + } + } + break; + case 2: + this._fileHashesOptimization.optimize(snapshot, capturedFiles); + for (const path of capturedFiles) { + const cache = this._fileHashes.get(path); + if (cache !== undefined) { + fileHashes.set(path, cache); + } else { + jobs++; + this.fileHashQueue.add(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting file hash of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + fileHashes.set(path, entry); + jobDone(); + } + }); + } + } + break; + case 1: + this._fileTimestampsOptimization.optimize(snapshot, capturedFiles); + for (const path of capturedFiles) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache !== "ignore") { + fileTimestamps.set(path, cache); + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting file timestamp of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + fileTimestamps.set(path, entry); + jobDone(); + } + }); + } + } + break; + } + }; + if (files) { + processCapturedFiles(captureNonManaged(files, managedFiles)); } - - return identifier; - } - - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return this._identifier; + const processCapturedDirectories = capturedDirectories => { + switch (mode) { + case 3: + this._contextTshsOptimization.optimize(snapshot, capturedDirectories); + for (const path of capturedDirectories) { + const cache = this._contextTshs.get(path); + /** @type {ResolvedContextTimestampAndHash} */ + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedTimestamp(cache)) !== undefined + ) { + contextTshs.set(path, resolved); + } else { + jobs++; + /** + * @param {Error=} err error + * @param {ResolvedContextTimestampAndHash=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting context timestamp hash combination of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + contextTshs.set(path, entry); + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextTsh(cache, callback); + } else { + this.getContextTsh(path, callback); + } + } + } + break; + case 2: + this._contextHashesOptimization.optimize( + snapshot, + capturedDirectories + ); + for (const path of capturedDirectories) { + const cache = this._contextHashes.get(path); + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedHash(cache)) !== undefined + ) { + contextHashes.set(path, resolved); + } else { + jobs++; + const callback = (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting context hash of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + contextHashes.set(path, entry); + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextHash(cache, callback); + } else { + this.getContextHash(path, callback); + } + } + } + break; + case 1: + this._contextTimestampsOptimization.optimize( + snapshot, + capturedDirectories + ); + for (const path of capturedDirectories) { + const cache = this._contextTimestamps.get(path); + if (cache === "ignore") continue; + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedTimestamp(cache)) !== undefined + ) { + contextTimestamps.set(path, resolved); + } else { + jobs++; + /** + * @param {Error=} err error + * @param {ResolvedContextFileSystemInfoEntry=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting context timestamp of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + contextTimestamps.set(path, entry); + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextTimestamp(cache, callback); + } else { + this.getContextTimestamp(path, callback); + } + } + } + break; + } + }; + if (directories) { + processCapturedDirectories( + captureNonManaged(directories, managedContexts) + ); + } + const processCapturedMissing = capturedMissing => { + this._missingExistenceOptimization.optimize(snapshot, capturedMissing); + for (const path of capturedMissing) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache !== "ignore") { + missingExistence.set(path, Boolean(cache)); + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting missing timestamp of ${path}: ${err.stack}` + ); + } + jobError(); + } else { + missingExistence.set(path, Boolean(entry)); + jobDone(); + } + }); + } + } + }; + if (missing) { + processCapturedMissing(captureNonManaged(missing, managedMissing)); + } + this._managedItemInfoOptimization.optimize(snapshot, managedItems); + for (const path of managedItems) { + const cache = this._managedItems.get(path); + if (cache !== undefined) { + if (!cache.startsWith("*")) { + managedFiles.add(join(this.fs, path, "package.json")); + } else if (cache === "*nested") { + managedMissing.add(join(this.fs, path, "package.json")); + } + managedItemInfo.set(path, cache); + } else { + jobs++; + this.managedItemQueue.add(path, (err, entry) => { + if (err) { + if (this.logger) { + this.logger.debug( + `Error snapshotting managed item ${path}: ${err.stack}` + ); + } + jobError(); + } else if (entry) { + if (!entry.startsWith("*")) { + managedFiles.add(join(this.fs, path, "package.json")); + } else if (cache === "*nested") { + managedMissing.add(join(this.fs, path, "package.json")); + } + managedItemInfo.set(path, entry); + jobDone(); + } else { + // Fallback to normal snapshotting + const process = (set, fn) => { + if (set.size === 0) return; + const captured = new Set(); + for (const file of set) { + if (file.startsWith(path)) captured.add(file); + } + if (captured.size > 0) fn(captured); + }; + process(managedFiles, processCapturedFiles); + process(managedContexts, processCapturedDirectories); + process(managedMissing, processCapturedMissing); + jobDone(); + } + }); + } + } + jobDone(); } /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module + * @param {Snapshot} snapshot1 a snapshot + * @param {Snapshot} snapshot2 a snapshot + * @returns {Snapshot} merged snapshot */ - readableIdentifier(requestShortener) { - let identifier = requestShortener.shorten(this.context) + "/"; - if (this.options.resourceQuery) { - identifier += ` ${this.options.resourceQuery}`; - } - if (this.options.mode) { - identifier += ` ${this.options.mode}`; - } - if (!this.options.recursive) { - identifier += " nonrecursive"; - } - if (this.options.addon) { - identifier += ` ${requestShortener.shorten(this.options.addon)}`; - } - if (this.options.regExp) { - identifier += ` ${this._prettyRegExp(this.options.regExp)}`; - } - if (this.options.include) { - identifier += ` include: ${this._prettyRegExp(this.options.include)}`; + mergeSnapshots(snapshot1, snapshot2) { + const snapshot = new Snapshot(); + if (snapshot1.hasStartTime() && snapshot2.hasStartTime()) + snapshot.setStartTime(Math.min(snapshot1.startTime, snapshot2.startTime)); + else if (snapshot2.hasStartTime()) snapshot.startTime = snapshot2.startTime; + else if (snapshot1.hasStartTime()) snapshot.startTime = snapshot1.startTime; + if (snapshot1.hasFileTimestamps() || snapshot2.hasFileTimestamps()) { + snapshot.setFileTimestamps( + mergeMaps(snapshot1.fileTimestamps, snapshot2.fileTimestamps) + ); } - if (this.options.exclude) { - identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`; + if (snapshot1.hasFileHashes() || snapshot2.hasFileHashes()) { + snapshot.setFileHashes( + mergeMaps(snapshot1.fileHashes, snapshot2.fileHashes) + ); } - if (this.options.referencedExports) { - identifier += ` referencedExports: ${this.options.referencedExports - .map(e => e.join(".")) - .join(", ")}`; + if (snapshot1.hasFileTshs() || snapshot2.hasFileTshs()) { + snapshot.setFileTshs(mergeMaps(snapshot1.fileTshs, snapshot2.fileTshs)); } - if (this.options.chunkName) { - identifier += ` chunkName: ${this.options.chunkName}`; + if (snapshot1.hasContextTimestamps() || snapshot2.hasContextTimestamps()) { + snapshot.setContextTimestamps( + mergeMaps(snapshot1.contextTimestamps, snapshot2.contextTimestamps) + ); } - if (this.options.groupOptions) { - const groupOptions = this.options.groupOptions; - for (const key of Object.keys(groupOptions)) { - identifier += ` ${key}: ${groupOptions[key]}`; - } + if (snapshot1.hasContextHashes() || snapshot2.hasContextHashes()) { + snapshot.setContextHashes( + mergeMaps(snapshot1.contextHashes, snapshot2.contextHashes) + ); } - if (this.options.namespaceObject === "strict") { - identifier += " strict namespace object"; - } else if (this.options.namespaceObject) { - identifier += " namespace object"; + if (snapshot1.hasContextTshs() || snapshot2.hasContextTshs()) { + snapshot.setContextTshs( + mergeMaps(snapshot1.contextTshs, snapshot2.contextTshs) + ); } - - return identifier; - } - - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - let identifier = contextify( - options.context, - this.context, - options.associatedObjectForCache - ); - if (this.layer) identifier = `(${this.layer})/${identifier}`; - if (this.options.mode) { - identifier += ` ${this.options.mode}`; + if (snapshot1.hasMissingExistence() || snapshot2.hasMissingExistence()) { + snapshot.setMissingExistence( + mergeMaps(snapshot1.missingExistence, snapshot2.missingExistence) + ); } - if (this.options.recursive) { - identifier += " recursive"; + if (snapshot1.hasManagedItemInfo() || snapshot2.hasManagedItemInfo()) { + snapshot.setManagedItemInfo( + mergeMaps(snapshot1.managedItemInfo, snapshot2.managedItemInfo) + ); } - if (this.options.addon) { - identifier += ` ${contextify( - options.context, - this.options.addon, - options.associatedObjectForCache - )}`; + if (snapshot1.hasManagedFiles() || snapshot2.hasManagedFiles()) { + snapshot.setManagedFiles( + mergeSets(snapshot1.managedFiles, snapshot2.managedFiles) + ); } - if (this.options.regExp) { - identifier += ` ${this._prettyRegExp(this.options.regExp)}`; + if (snapshot1.hasManagedContexts() || snapshot2.hasManagedContexts()) { + snapshot.setManagedContexts( + mergeSets(snapshot1.managedContexts, snapshot2.managedContexts) + ); } - if (this.options.include) { - identifier += ` include: ${this._prettyRegExp(this.options.include)}`; + if (snapshot1.hasManagedMissing() || snapshot2.hasManagedMissing()) { + snapshot.setManagedMissing( + mergeSets(snapshot1.managedMissing, snapshot2.managedMissing) + ); } - if (this.options.exclude) { - identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`; + if (snapshot1.hasChildren() || snapshot2.hasChildren()) { + snapshot.setChildren(mergeSets(snapshot1.children, snapshot2.children)); } - if (this.options.referencedExports) { - identifier += ` referencedExports: ${this.options.referencedExports - .map(e => e.join(".")) - .join(", ")}`; + if ( + this._snapshotCache.get(snapshot1) === true && + this._snapshotCache.get(snapshot2) === true + ) { + this._snapshotCache.set(snapshot, true); } - - return identifier; - } - - /** - * @returns {void} - */ - invalidateBuild() { - this._forceBuild = true; + return snapshot; } /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @param {Snapshot} snapshot the snapshot made + * @param {function((WebpackError | null)=, boolean=): void} callback callback function * @returns {void} */ - needBuild({ fileSystemInfo }, callback) { - // build if enforced - if (this._forceBuild) return callback(null, true); - - // always build when we have no snapshot - if (!this.buildInfo.snapshot) return callback(null, true); - - fileSystemInfo.checkSnapshotValid(this.buildInfo.snapshot, (err, valid) => { - callback(err, !valid); - }); + checkSnapshotValid(snapshot, callback) { + const cachedResult = this._snapshotCache.get(snapshot); + if (cachedResult !== undefined) { + this._statTestedSnapshotsCached++; + if (typeof cachedResult === "boolean") { + callback(null, cachedResult); + } else { + cachedResult.push(callback); + } + return; + } + this._statTestedSnapshotsNotCached++; + this._checkSnapshotValidNoCache(snapshot, callback); } /** - * @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 + * @param {Snapshot} snapshot the snapshot made + * @param {function((WebpackError | null)=, boolean=): void} callback callback function * @returns {void} */ - build(options, compilation, resolver, fs, callback) { - this._forceBuild = false; - /** @type {BuildMeta} */ - this.buildMeta = { - exportsType: "default", - defaultObject: "redirect-warn" + _checkSnapshotValidNoCache(snapshot, callback) { + /** @type {number | undefined} */ + let startTime = undefined; + if (snapshot.hasStartTime()) { + startTime = snapshot.startTime; + } + let jobs = 1; + const jobDone = () => { + if (--jobs === 0) { + this._snapshotCache.set(snapshot, true); + callback(null, true); + } }; - this.buildInfo = { - snapshot: undefined + const invalid = () => { + if (jobs > 0) { + // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8) + jobs = -100000000; + this._snapshotCache.set(snapshot, false); + callback(null, false); + } }; - this.dependencies.length = 0; - this.blocks.length = 0; - const startTime = Date.now(); - this.resolveDependencies(fs, this.options, (err, dependencies) => { - if (err) { - return callback( - makeWebpackError(err, "ContextModule.resolveDependencies") - ); + const invalidWithError = (path, err) => { + if (this._remainingLogs > 0) { + this._log(path, `error occurred: %s`, err); } - - // abort if something failed - // this will create an empty context - if (!dependencies) { - callback(); - return; + invalid(); + }; + /** + * @param {string} path file path + * @param {string} current current hash + * @param {string} snap snapshot hash + * @returns {boolean} true, if ok + */ + const checkHash = (path, current, snap) => { + if (current !== snap) { + // If hash differ it's invalid + if (this._remainingLogs > 0) { + this._log(path, `hashes differ (%s != %s)`, current, snap); + } + return false; } - - // enhance dependencies with meta info - for (const dep of dependencies) { - dep.loc = { - name: dep.userRequest - }; - dep.request = this.options.addon + dep.request; + return true; + }; + /** + * @param {string} path file path + * @param {boolean} current current entry + * @param {boolean} snap entry from snapshot + * @returns {boolean} true, if ok + */ + const checkExistence = (path, current, snap) => { + if (!current !== !snap) { + // If existence of item differs + // it's invalid + if (this._remainingLogs > 0) { + this._log( + path, + current ? "it didn't exist before" : "it does no longer exist" + ); + } + return false; } - dependencies.sort( - concatComparators( - compareSelect(a => a.loc, compareLocations), - keepOriginalOrder(this.dependencies) - ) - ); - - if (this.options.mode === "sync" || this.options.mode === "eager") { - // if we have an sync or eager context - // just add all dependencies and continue - this.dependencies = dependencies; - } else if (this.options.mode === "lazy-once") { - // for the lazy-once mode create a new async dependency block - // and add that block to this context - if (dependencies.length > 0) { - const block = new AsyncDependenciesBlock({ - ...this.options.groupOptions, - name: this.options.chunkName - }); - for (const dep of dependencies) { - block.addDependency(dep); + return true; + }; + /** + * @param {string} path file path + * @param {FileSystemInfoEntry} current current entry + * @param {FileSystemInfoEntry} snap entry from snapshot + * @param {boolean} log log reason + * @returns {boolean} true, if ok + */ + const checkFile = (path, current, snap, log = true) => { + if (current === snap) return true; + if (!checkExistence(path, Boolean(current), Boolean(snap))) return false; + if (current) { + // For existing items only + if (typeof startTime === "number" && current.safeTime > startTime) { + // If a change happened after starting reading the item + // this may no longer be valid + if (log && this._remainingLogs > 0) { + this._log( + path, + `it may have changed (%d) after the start time of the snapshot (%d)`, + current.safeTime, + startTime + ); } - this.addBlock(block); - } - } else if ( - this.options.mode === "weak" || - this.options.mode === "async-weak" - ) { - // we mark all dependencies as weak - for (const dep of dependencies) { - dep.weak = true; + return false; } - this.dependencies = dependencies; - } else if (this.options.mode === "lazy") { - // if we are lazy create a new async dependency block per dependency - // and add all blocks to this context - let index = 0; - for (const dep of dependencies) { - let chunkName = this.options.chunkName; - if (chunkName) { - if (!/\[(index|request)\]/.test(chunkName)) { - chunkName += "[index]"; - } - chunkName = chunkName.replace(/\[index\]/g, `${index++}`); - chunkName = chunkName.replace( - /\[request\]/g, - Template.toPath(dep.userRequest) + if ( + snap.timestamp !== undefined && + current.timestamp !== snap.timestamp + ) { + // If we have a timestamp (it was a file or symlink) and it differs from current timestamp + // it's invalid + if (log && this._remainingLogs > 0) { + this._log( + path, + `timestamps differ (%d != %d)`, + current.timestamp, + snap.timestamp ); } - const block = new AsyncDependenciesBlock( - { - ...this.options.groupOptions, - name: chunkName - }, - dep.loc, - dep.userRequest - ); - block.addDependency(dep); - this.addBlock(block); + return false; } - } else { - callback( - new WebpackError(`Unsupported mode "${this.options.mode}" in context`) - ); - return; } - compilation.fileSystemInfo.createSnapshot( - startTime, - null, - [this.context], - null, - SNAPSHOT_OPTIONS, - (err, snapshot) => { - if (err) return callback(err); - this.buildInfo.snapshot = snapshot; - callback(); + return true; + }; + /** + * @param {string} path file path + * @param {ResolvedContextFileSystemInfoEntry} current current entry + * @param {ResolvedContextFileSystemInfoEntry} snap entry from snapshot + * @param {boolean} log log reason + * @returns {boolean} true, if ok + */ + const checkContext = (path, current, snap, log = true) => { + if (current === snap) return true; + if (!checkExistence(path, Boolean(current), Boolean(snap))) return false; + if (current) { + // For existing items only + if (typeof startTime === "number" && current.safeTime > startTime) { + // If a change happened after starting reading the item + // this may no longer be valid + if (log && this._remainingLogs > 0) { + this._log( + path, + `it may have changed (%d) after the start time of the snapshot (%d)`, + current.safeTime, + startTime + ); + } + return false; } - ); - }); - } - - /** - * @param {LazySet} fileDependencies set where file dependencies are added to - * @param {LazySet} contextDependencies set where context dependencies are added to - * @param {LazySet} missingDependencies set where missing dependencies are added to - * @param {LazySet} buildDependencies set where build dependencies are added to - */ - addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ) { - contextDependencies.add(this.context); - } - - /** - * @param {ContextElementDependency[]} dependencies all dependencies - * @param {ChunkGraph} chunkGraph chunk graph - * @returns {TODO} TODO - */ - getUserRequestMap(dependencies, chunkGraph) { - const moduleGraph = chunkGraph.moduleGraph; - // if we filter first we get a new array - // therefore we don't need to create a clone of dependencies explicitly - // therefore the order of this is !important! - const sortedDependencies = dependencies - .filter(dependency => moduleGraph.getModule(dependency)) - .sort((a, b) => { - if (a.userRequest === b.userRequest) { - return 0; + if ( + snap.timestampHash !== undefined && + current.timestampHash !== snap.timestampHash + ) { + // If we have a timestampHash (it was a directory) and it differs from current timestampHash + // it's invalid + if (log && this._remainingLogs > 0) { + this._log( + path, + `timestamps hashes differ (%s != %s)`, + current.timestampHash, + snap.timestampHash + ); + } + return false; + } + } + return true; + }; + if (snapshot.hasChildren()) { + const childCallback = (err, result) => { + if (err || !result) return invalid(); + else jobDone(); + }; + for (const child of snapshot.children) { + const cache = this._snapshotCache.get(child); + if (cache !== undefined) { + this._statTestedChildrenCached++; + /* istanbul ignore else */ + if (typeof cache === "boolean") { + if (cache === false) { + invalid(); + return; + } + } else { + jobs++; + cache.push(childCallback); + } + } else { + this._statTestedChildrenNotCached++; + jobs++; + this._checkSnapshotValidNoCache(child, childCallback); } - return a.userRequest < b.userRequest ? -1 : 1; - }); - const map = Object.create(null); - for (const dep of sortedDependencies) { - const module = moduleGraph.getModule(dep); - map[dep.userRequest] = chunkGraph.getModuleId(module); - } - return map; - } - - /** - * @param {ContextElementDependency[]} dependencies all dependencies - * @param {ChunkGraph} chunkGraph chunk graph - * @returns {TODO} TODO - */ - getFakeMap(dependencies, chunkGraph) { - if (!this.options.namespaceObject) { - return 9; - } - const moduleGraph = chunkGraph.moduleGraph; - // bitfield - let hasType = 0; - const comparator = compareModulesById(chunkGraph); - // if we filter first we get a new array - // therefore we don't need to create a clone of dependencies explicitly - // therefore the order of this is !important! - const sortedModules = dependencies - .map(dependency => moduleGraph.getModule(dependency)) - .filter(Boolean) - .sort(comparator); - const fakeMap = Object.create(null); - for (const module of sortedModules) { - const exportsType = module.getExportsType( - moduleGraph, - this.options.namespaceObject === "strict" - ); - const id = chunkGraph.getModuleId(module); - switch (exportsType) { - case "namespace": - fakeMap[id] = 9; - hasType |= 1; - break; - case "dynamic": - fakeMap[id] = 7; - hasType |= 2; - break; - case "default-only": - fakeMap[id] = 1; - hasType |= 4; - break; - case "default-with-named": - fakeMap[id] = 3; - hasType |= 8; - break; - default: - throw new Error(`Unexpected exports type ${exportsType}`); } } - if (hasType === 1) { - return 9; + if (snapshot.hasFileTimestamps()) { + const { fileTimestamps } = snapshot; + this._statTestedEntries += fileTimestamps.size; + for (const [path, ts] of fileTimestamps) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache !== "ignore" && !checkFile(path, cache, ts)) { + invalid(); + return; + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkFile(path, entry, ts)) { + invalid(); + } else { + jobDone(); + } + }); + } + } } - if (hasType === 2) { - return 7; + const processFileHashSnapshot = (path, hash) => { + const cache = this._fileHashes.get(path); + if (cache !== undefined) { + if (cache !== "ignore" && !checkHash(path, cache, hash)) { + invalid(); + return; + } + } else { + jobs++; + this.fileHashQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkHash(path, entry, hash)) { + invalid(); + } else { + jobDone(); + } + }); + } + }; + if (snapshot.hasFileHashes()) { + const { fileHashes } = snapshot; + this._statTestedEntries += fileHashes.size; + for (const [path, hash] of fileHashes) { + processFileHashSnapshot(path, hash); + } } - if (hasType === 4) { - return 1; + if (snapshot.hasFileTshs()) { + const { fileTshs } = snapshot; + this._statTestedEntries += fileTshs.size; + for (const [path, tsh] of fileTshs) { + if (typeof tsh === "string") { + processFileHashSnapshot(path, tsh); + } else { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache === "ignore" || !checkFile(path, cache, tsh, false)) { + processFileHashSnapshot(path, tsh && tsh.hash); + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkFile(path, entry, tsh, false)) { + processFileHashSnapshot(path, tsh && tsh.hash); + } + jobDone(); + }); + } + } + } } - if (hasType === 8) { - return 3; + if (snapshot.hasContextTimestamps()) { + const { contextTimestamps } = snapshot; + this._statTestedEntries += contextTimestamps.size; + for (const [path, ts] of contextTimestamps) { + const cache = this._contextTimestamps.get(path); + if (cache === "ignore") continue; + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedTimestamp(cache)) !== undefined + ) { + if (!checkContext(path, resolved, ts)) { + invalid(); + return; + } + } else { + jobs++; + /** + * @param {Error=} err error + * @param {ResolvedContextFileSystemInfoEntry=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkContext(path, entry, ts)) { + invalid(); + } else { + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextTimestamp(cache, callback); + } else { + this.getContextTimestamp(path, callback); + } + } + } } - if (hasType === 0) { - return 9; + const processContextHashSnapshot = (path, hash) => { + const cache = this._contextHashes.get(path); + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedHash(cache)) !== undefined + ) { + if (!checkHash(path, resolved, hash)) { + invalid(); + return; + } + } else { + jobs++; + const callback = (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkHash(path, entry, hash)) { + invalid(); + } else { + jobDone(); + } + }; + if (cache !== undefined) { + this._resolveContextHash(cache, callback); + } else { + this.getContextHash(path, callback); + } + } + }; + if (snapshot.hasContextHashes()) { + const { contextHashes } = snapshot; + this._statTestedEntries += contextHashes.size; + for (const [path, hash] of contextHashes) { + processContextHashSnapshot(path, hash); + } } - return fakeMap; - } - - getFakeMapInitStatement(fakeMap) { - return typeof fakeMap === "object" - ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` - : ""; - } - - getReturn(type, asyncModule) { - if (type === 9) { - return "__webpack_require__(id)"; - } - return `${RuntimeGlobals.createFakeNamespaceObject}(id, ${type}${ - asyncModule ? " | 16" : "" - })`; - } - - getReturnModuleObjectSource( - fakeMap, - asyncModule, - fakeMapDataExpression = "fakeMap[id]" - ) { - if (typeof fakeMap === "number") { - return `return ${this.getReturn(fakeMap, asyncModule)};`; + if (snapshot.hasContextTshs()) { + const { contextTshs } = snapshot; + this._statTestedEntries += contextTshs.size; + for (const [path, tsh] of contextTshs) { + if (typeof tsh === "string") { + processContextHashSnapshot(path, tsh); + } else { + const cache = this._contextTimestamps.get(path); + if (cache === "ignore") continue; + let resolved; + if ( + cache !== undefined && + (resolved = getResolvedTimestamp(cache)) !== undefined + ) { + if (!checkContext(path, resolved, tsh, false)) { + processContextHashSnapshot(path, tsh && tsh.hash); + } + } else { + jobs++; + /** + * @param {Error=} err error + * @param {ResolvedContextFileSystemInfoEntry=} entry entry + * @returns {void} + */ + const callback = (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkContext(path, entry, tsh, false)) { + processContextHashSnapshot(path, tsh && tsh.hash); + } + jobDone(); + }; + if (cache !== undefined) { + this._resolveContextTimestamp(cache, callback); + } else { + this.getContextTimestamp(path, callback); + } + } + } + } } - return `return ${ - RuntimeGlobals.createFakeNamespaceObject - }(id, ${fakeMapDataExpression}${asyncModule ? " | 16" : ""})`; - } - - /** - * @param {TODO} dependencies TODO - * @param {TODO} id TODO - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {string} source code - */ - getSyncSource(dependencies, id, chunkGraph) { - const map = this.getUserRequestMap(dependencies, chunkGraph); - const fakeMap = this.getFakeMap(dependencies, chunkGraph); - const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); - - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} - -function webpackContext(req) { - var id = webpackContextResolve(req); - ${returnModuleObject} -} -function webpackContextResolve(req) { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; -} -webpackContext.keys = function webpackContextKeys() { - return Object.keys(map); -}; -webpackContext.resolve = webpackContextResolve; -module.exports = webpackContext; -webpackContext.id = ${JSON.stringify(id)};`; - } - - /** - * @param {TODO} dependencies TODO - * @param {TODO} id TODO - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {string} source code - */ - getWeakSyncSource(dependencies, id, chunkGraph) { - const map = this.getUserRequestMap(dependencies, chunkGraph); - const fakeMap = this.getFakeMap(dependencies, chunkGraph); - const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); - - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} - -function webpackContext(req) { - var id = webpackContextResolve(req); - if(!${RuntimeGlobals.moduleFactories}[id]) { - var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - ${returnModuleObject} -} -function webpackContextResolve(req) { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; -} -webpackContext.keys = function webpackContextKeys() { - return Object.keys(map); -}; -webpackContext.resolve = webpackContextResolve; -webpackContext.id = ${JSON.stringify(id)}; -module.exports = webpackContext;`; - } - - /** - * @param {TODO} dependencies TODO - * @param {TODO} id TODO - * @param {Object} context context - * @param {ChunkGraph} context.chunkGraph the chunk graph - * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph - * @returns {string} source code - */ - getAsyncWeakSource(dependencies, id, { chunkGraph, runtimeTemplate }) { - const arrow = runtimeTemplate.supportsArrowFunction(); - const map = this.getUserRequestMap(dependencies, chunkGraph); - const fakeMap = this.getFakeMap(dependencies, chunkGraph); - const returnModuleObject = this.getReturnModuleObjectSource(fakeMap, true); - - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} - -function webpackAsyncContext(req) { - return webpackAsyncContextResolve(req).then(${ - arrow ? "id =>" : "function(id)" - } { - if(!${RuntimeGlobals.moduleFactories}[id]) { - var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); - e.code = 'MODULE_NOT_FOUND'; - throw e; + if (snapshot.hasMissingExistence()) { + const { missingExistence } = snapshot; + this._statTestedEntries += missingExistence.size; + for (const [path, existence] of missingExistence) { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if ( + cache !== "ignore" && + !checkExistence(path, Boolean(cache), Boolean(existence)) + ) { + invalid(); + return; + } + } else { + jobs++; + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkExistence(path, Boolean(entry), Boolean(existence))) { + invalid(); + } else { + jobDone(); + } + }); + } + } } - ${returnModuleObject} - }); -} -function webpackAsyncContextResolve(req) { - // Here Promise.resolve().then() is used instead of new Promise() to prevent - // uncaught exception popping up in devtools - return Promise.resolve().then(${arrow ? "() =>" : "function()"} { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; + if (snapshot.hasManagedItemInfo()) { + const { managedItemInfo } = snapshot; + this._statTestedEntries += managedItemInfo.size; + for (const [path, info] of managedItemInfo) { + const cache = this._managedItems.get(path); + if (cache !== undefined) { + if (!checkHash(path, cache, info)) { + invalid(); + return; + } + } else { + jobs++; + this.managedItemQueue.add(path, (err, entry) => { + if (err) return invalidWithError(path, err); + if (!checkHash(path, entry, info)) { + invalid(); + } else { + jobDone(); + } + }); + } + } } - return map[req]; - }); -} -webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( - "Object.keys(map)" - )}; -webpackAsyncContext.resolve = webpackAsyncContextResolve; -webpackAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackAsyncContext;`; - } - - /** - * @param {TODO} dependencies TODO - * @param {TODO} id TODO - * @param {Object} context context - * @param {ChunkGraph} context.chunkGraph the chunk graph - * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph - * @returns {string} source code - */ - getEagerSource(dependencies, id, { chunkGraph, runtimeTemplate }) { - const arrow = runtimeTemplate.supportsArrowFunction(); - const map = this.getUserRequestMap(dependencies, chunkGraph); - const fakeMap = this.getFakeMap(dependencies, chunkGraph); - const thenFunction = - fakeMap !== 9 - ? `${arrow ? "id =>" : "function(id)"} { - ${this.getReturnModuleObjectSource(fakeMap)} - }` - : "__webpack_require__"; - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} + jobDone(); -function webpackAsyncContext(req) { - return webpackAsyncContextResolve(req).then(${thenFunction}); -} -function webpackAsyncContextResolve(req) { - // Here Promise.resolve().then() is used instead of new Promise() to prevent - // uncaught exception popping up in devtools - return Promise.resolve().then(${arrow ? "() =>" : "function()"} { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; + // if there was an async action + // try to join multiple concurrent request for this snapshot + if (jobs > 0) { + const callbacks = [callback]; + callback = (err, result) => { + for (const callback of callbacks) callback(err, result); + }; + this._snapshotCache.set(snapshot, callbacks); } - return map[req]; - }); -} -webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( - "Object.keys(map)" - )}; -webpackAsyncContext.resolve = webpackAsyncContextResolve; -webpackAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackAsyncContext;`; } - /** - * @param {TODO} block TODO - * @param {TODO} dependencies TODO - * @param {TODO} id TODO - * @param {Object} options options object - * @param {RuntimeTemplate} options.runtimeTemplate the runtime template - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @returns {string} source code - */ - getLazyOnceSource(block, dependencies, id, { runtimeTemplate, chunkGraph }) { - const promise = runtimeTemplate.blockPromise({ - chunkGraph, - block, - message: "lazy-once context", - runtimeRequirements: new Set() - }); - const arrow = runtimeTemplate.supportsArrowFunction(); - const map = this.getUserRequestMap(dependencies, chunkGraph); - const fakeMap = this.getFakeMap(dependencies, chunkGraph); - const thenFunction = - fakeMap !== 9 - ? `${arrow ? "id =>" : "function(id)"} { - ${this.getReturnModuleObjectSource(fakeMap, true)}; - }` - : "__webpack_require__"; + _readFileTimestamp(path, callback) { + this.fs.stat(path, (err, stat) => { + if (err) { + if (err.code === "ENOENT") { + this._fileTimestamps.set(path, null); + this._cachedDeprecatedFileTimestamps = undefined; + return callback(null, null); + } + return callback(err); + } - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} + let ts; + if (stat.isDirectory()) { + ts = { + safeTime: 0, + timestamp: undefined + }; + } else { + const mtime = +stat.mtime; -function webpackAsyncContext(req) { - return webpackAsyncContextResolve(req).then(${thenFunction}); -} -function webpackAsyncContextResolve(req) { - return ${promise}.then(${arrow ? "() =>" : "function()"} { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; - }); -} -webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( - "Object.keys(map)" - )}; -webpackAsyncContext.resolve = webpackAsyncContextResolve; -webpackAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackAsyncContext;`; - } + if (mtime) applyMtime(mtime); - /** - * @param {TODO} blocks TODO - * @param {TODO} id TODO - * @param {Object} context context - * @param {ChunkGraph} context.chunkGraph the chunk graph - * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph - * @returns {string} source code - */ - getLazySource(blocks, id, { chunkGraph, runtimeTemplate }) { - const moduleGraph = chunkGraph.moduleGraph; - const arrow = runtimeTemplate.supportsArrowFunction(); - let hasMultipleOrNoChunks = false; - let hasNoChunk = true; - const fakeMap = this.getFakeMap( - blocks.map(b => b.dependencies[0]), - chunkGraph - ); - const hasFakeMap = typeof fakeMap === "object"; - const items = blocks - .map(block => { - const dependency = block.dependencies[0]; - return { - dependency: dependency, - module: moduleGraph.getModule(dependency), - block: block, - userRequest: dependency.userRequest, - chunks: undefined + ts = { + safeTime: mtime ? mtime + FS_ACCURACY : Infinity, + timestamp: mtime }; - }) - .filter(item => item.module); - for (const item of items) { - const chunkGroup = chunkGraph.getBlockChunkGroup(item.block); - const chunks = (chunkGroup && chunkGroup.chunks) || []; - item.chunks = chunks; - if (chunks.length > 0) { - hasNoChunk = false; - } - if (chunks.length !== 1) { - hasMultipleOrNoChunks = true; - } - } - const shortMode = hasNoChunk && !hasFakeMap; - const sortedItems = items.sort((a, b) => { - if (a.userRequest === b.userRequest) return 0; - return a.userRequest < b.userRequest ? -1 : 1; - }); - const map = Object.create(null); - for (const item of sortedItems) { - const moduleId = chunkGraph.getModuleId(item.module); - if (shortMode) { - map[item.userRequest] = moduleId; - } else { - const arrayStart = [moduleId]; - if (hasFakeMap) { - arrayStart.push(fakeMap[moduleId]); - } - map[item.userRequest] = arrayStart.concat( - item.chunks.map(chunk => chunk.id) - ); } - } - - const chunksStartPosition = hasFakeMap ? 2 : 1; - const requestPrefix = hasNoChunk - ? "Promise.resolve()" - : hasMultipleOrNoChunks - ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))` - : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`; - const returnModuleObject = this.getReturnModuleObjectSource( - fakeMap, - true, - shortMode ? "invalid" : "ids[1]" - ); - const webpackAsyncContext = - requestPrefix === "Promise.resolve()" - ? ` -function webpackAsyncContext(req) { - return Promise.resolve().then(${arrow ? "() =>" : "function()"} { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } + this._fileTimestamps.set(path, ts); + this._cachedDeprecatedFileTimestamps = undefined; - ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"} - ${returnModuleObject} - }); -}` - : `function webpackAsyncContext(req) { - if(!${RuntimeGlobals.hasOwnProperty}(map, req)) { - return Promise.resolve().then(${arrow ? "() =>" : "function()"} { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; + callback(null, ts); }); } - var ids = map[req], id = ids[0]; - return ${requestPrefix}.then(${arrow ? "() =>" : "function()"} { - ${returnModuleObject} - }); -}`; + _readFileHash(path, callback) { + this.fs.readFile(path, (err, content) => { + if (err) { + if (err.code === "EISDIR") { + this._fileHashes.set(path, "directory"); + return callback(null, "directory"); + } + if (err.code === "ENOENT") { + this._fileHashes.set(path, null); + return callback(null, null); + } + if (err.code === "ERR_FS_FILE_TOO_LARGE") { + this.logger.warn(`Ignoring ${path} for hashing as it's very large`); + this._fileHashes.set(path, "too large"); + return callback(null, "too large"); + } + return callback(err); + } - return `var map = ${JSON.stringify(map, null, "\t")}; -${webpackAsyncContext} -webpackAsyncContext.keys = ${runtimeTemplate.returningFunction( - "Object.keys(map)" - )}; -webpackAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackAsyncContext;`; - } + const hash = createHash(this._hashFunction); - getSourceForEmptyContext(id, runtimeTemplate) { - return `function webpackEmptyContext(req) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; -} -webpackEmptyContext.keys = ${runtimeTemplate.returningFunction("[]")}; -webpackEmptyContext.resolve = webpackEmptyContext; -webpackEmptyContext.id = ${JSON.stringify(id)}; -module.exports = webpackEmptyContext;`; - } + hash.update(content); - getSourceForEmptyAsyncContext(id, runtimeTemplate) { - const arrow = runtimeTemplate.supportsArrowFunction(); - return `function webpackEmptyAsyncContext(req) { - // Here Promise.resolve().then() is used instead of new Promise() to prevent - // uncaught exception popping up in devtools - return Promise.resolve().then(${arrow ? "() =>" : "function()"} { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - }); -} -webpackEmptyAsyncContext.keys = ${runtimeTemplate.returningFunction("[]")}; -webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; -webpackEmptyAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackEmptyAsyncContext;`; + const digest = /** @type {string} */ (hash.digest("hex")); + + this._fileHashes.set(path, digest); + + callback(null, digest); + }); } - /** - * @param {string} asyncMode module mode - * @param {CodeGenerationContext} context context info - * @returns {string} the source code - */ - getSourceString(asyncMode, { runtimeTemplate, chunkGraph }) { - const id = chunkGraph.getModuleId(this); - if (asyncMode === "lazy") { - if (this.blocks && this.blocks.length > 0) { - return this.getLazySource(this.blocks, id, { - runtimeTemplate, - chunkGraph - }); - } - return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); - } - if (asyncMode === "eager") { - if (this.dependencies && this.dependencies.length > 0) { - return this.getEagerSource(this.dependencies, id, { - chunkGraph, - runtimeTemplate - }); - } - return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); - } - if (asyncMode === "lazy-once") { - const block = this.blocks[0]; - if (block) { - return this.getLazyOnceSource(block, block.dependencies, id, { - runtimeTemplate, - chunkGraph - }); - } - return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); - } - if (asyncMode === "async-weak") { - if (this.dependencies && this.dependencies.length > 0) { - return this.getAsyncWeakSource(this.dependencies, id, { - chunkGraph, - runtimeTemplate + _getFileTimestampAndHash(path, callback) { + const continueWithHash = hash => { + const cache = this._fileTimestamps.get(path); + if (cache !== undefined) { + if (cache !== "ignore") { + const result = { + ...cache, + hash + }; + this._fileTshs.set(path, result); + return callback(null, result); + } else { + this._fileTshs.set(path, hash); + return callback(null, hash); + } + } else { + this.fileTimestampQueue.add(path, (err, entry) => { + if (err) { + return callback(err); + } + const result = { + ...entry, + hash + }; + this._fileTshs.set(path, result); + return callback(null, result); }); } - return this.getSourceForEmptyAsyncContext(id, runtimeTemplate); - } - if (asyncMode === "weak") { - if (this.dependencies && this.dependencies.length > 0) { - return this.getWeakSyncSource(this.dependencies, id, chunkGraph); - } - } - if (this.dependencies && this.dependencies.length > 0) { - return this.getSyncSource(this.dependencies, id, chunkGraph); - } - return this.getSourceForEmptyContext(id, runtimeTemplate); - } + }; - getSource(sourceString) { - if (this.useSourceMap || this.useSimpleSourceMap) { - return new OriginalSource(sourceString, this.identifier()); + const cache = this._fileHashes.get(path); + if (cache !== undefined) { + continueWithHash(cache); + } else { + this.fileHashQueue.add(path, (err, entry) => { + if (err) { + return callback(err); + } + continueWithHash(entry); + }); } - return new RawSource(sourceString); } /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result + * @template T + * @template ItemType + * @param {Object} options options + * @param {string} options.path path + * @param {function(string): ItemType} options.fromImmutablePath called when context item is an immutable path + * @param {function(string): ItemType} options.fromManagedItem called when context item is a managed path + * @param {function(string, string, function(Error=, ItemType=): void): void} options.fromSymlink called when context item is a symlink + * @param {function(string, IStats, function(Error=, ItemType=): void): void} options.fromFile called when context item is a file + * @param {function(string, IStats, function(Error=, ItemType=): void): void} options.fromDirectory called when context item is a directory + * @param {function(string[], ItemType[]): T} options.reduce called from all context items + * @param {function((Error | null)=, (T)=): void} callback callback */ - codeGeneration(context) { - const { chunkGraph } = context; - const sources = new Map(); - sources.set( - "javascript", - this.getSource(this.getSourceString(this.options.mode, context)) - ); - const set = new Set(); - const allDeps = /** @type {ContextElementDependency[]} */ ( - this.dependencies.concat(this.blocks.map(b => b.dependencies[0])) - ); - set.add(RuntimeGlobals.module); - set.add(RuntimeGlobals.hasOwnProperty); - if (allDeps.length > 0) { - const asyncMode = this.options.mode; - set.add(RuntimeGlobals.require); - if (asyncMode === "weak") { - set.add(RuntimeGlobals.moduleFactories); - } else if (asyncMode === "async-weak") { - set.add(RuntimeGlobals.moduleFactories); - set.add(RuntimeGlobals.ensureChunk); - } else if (asyncMode === "lazy" || asyncMode === "lazy-once") { - set.add(RuntimeGlobals.ensureChunk); - } - if (this.getFakeMap(allDeps, chunkGraph) !== 9) { - set.add(RuntimeGlobals.createFakeNamespaceObject); + _readContext( + { + path, + fromImmutablePath, + fromManagedItem, + fromSymlink, + fromFile, + fromDirectory, + reduce + }, + callback + ) { + this.fs.readdir(path, (err, _files) => { + if (err) { + if (err.code === "ENOENT") { + return callback(null, null); + } + return callback(err); } - } - return { - sources, - runtimeRequirements: set - }; - } - - /** - * @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) { - // base penalty - let size = 160; + const files = /** @type {string[]} */ (_files) + .map(file => file.normalize("NFC")) + .filter(file => !/^\./.test(file)) + .sort(); + asyncLib.map( + files, + (file, callback) => { + const child = join(this.fs, path, file); + for (const immutablePath of this.immutablePathsRegExps) { + if (immutablePath.test(path)) { + // ignore any immutable path for timestamping + return callback(null, fromImmutablePath(path)); + } + } + for (const immutablePath of this.immutablePathsWithSlash) { + if (path.startsWith(immutablePath)) { + // ignore any immutable path for timestamping + return callback(null, fromImmutablePath(path)); + } + } + for (const managedPath of this.managedPathsRegExps) { + const match = managedPath.exec(path); + if (match) { + const managedItem = getManagedItem(match[1], path); + if (managedItem) { + // construct timestampHash from managed info + return this.managedItemQueue.add(managedItem, (err, info) => { + if (err) return callback(err); + return callback(null, fromManagedItem(info)); + }); + } + } + } + for (const managedPath of this.managedPathsWithSlash) { + if (path.startsWith(managedPath)) { + const managedItem = getManagedItem(managedPath, child); + if (managedItem) { + // construct timestampHash from managed info + return this.managedItemQueue.add(managedItem, (err, info) => { + if (err) return callback(err); + return callback(null, fromManagedItem(info)); + }); + } + } + } - // if we don't have dependencies we stop here. - for (const dependency of this.dependencies) { - const element = /** @type {ContextElementDependency} */ (dependency); - size += 5 + element.userRequest.length; - } - return size; - } + lstatReadlinkAbsolute(this.fs, child, (err, stat) => { + if (err) return callback(err); - serialize(context) { - const { write } = context; - write(this._identifier); - write(this._forceBuild); - super.serialize(context); - } + if (typeof stat === "string") { + return fromSymlink(child, stat, callback); + } - deserialize(context) { - const { read } = context; - this._identifier = read(); - this._forceBuild = read(); - super.deserialize(context); + if (stat.isFile()) { + return fromFile(child, stat, callback); + } + if (stat.isDirectory()) { + return fromDirectory(child, stat, callback); + } + callback(null, null); + }); + }, + (err, results) => { + if (err) return callback(err); + const result = reduce(files, results); + callback(null, result); + } + ); + }); } -} - -makeSerializable(ContextModule, "webpack/lib/ContextModule"); - -module.exports = ContextModule; + _readContextTimestamp(path, callback) { + this._readContext( + { + path, + fromImmutablePath: () => null, + fromManagedItem: info => ({ + safeTime: 0, + timestampHash: info + }), + fromSymlink: (file, target, callback) => { + callback(null, { + timestampHash: target, + symlinks: new Set([target]) + }); + }, + fromFile: (file, stat, callback) => { + // Prefer the cached value over our new stat to report consistent results + const cache = this._fileTimestamps.get(file); + if (cache !== undefined) + return callback(null, cache === "ignore" ? null : cache); -/***/ }), + const mtime = +stat.mtime; -/***/ 62471: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (mtime) applyMtime(mtime); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const ts = { + safeTime: mtime ? mtime + FS_ACCURACY : Infinity, + timestamp: mtime + }; + this._fileTimestamps.set(file, ts); + this._cachedDeprecatedFileTimestamps = undefined; + callback(null, ts); + }, + fromDirectory: (directory, stat, callback) => { + this.contextTimestampQueue.increaseParallelism(); + this._getUnresolvedContextTimestamp(directory, (err, tsEntry) => { + this.contextTimestampQueue.decreaseParallelism(); + callback(err, tsEntry); + }); + }, + reduce: (files, tsEntries) => { + let symlinks = undefined; + const hash = createHash(this._hashFunction); -const asyncLib = __webpack_require__(78175); -const { AsyncSeriesWaterfallHook, SyncWaterfallHook } = __webpack_require__(41242); -const ContextModule = __webpack_require__(76729); -const ModuleFactory = __webpack_require__(51010); -const ContextElementDependency = __webpack_require__(58477); -const LazySet = __webpack_require__(38938); -const { cachedSetProperty } = __webpack_require__(60839); -const { createFakeHook } = __webpack_require__(64518); -const { join } = __webpack_require__(17139); + for (const file of files) hash.update(file); + let safeTime = 0; + for (const entry of tsEntries) { + if (!entry) { + hash.update("n"); + continue; + } + if (entry.timestamp) { + hash.update("f"); + hash.update(`${entry.timestamp}`); + } else if (entry.timestampHash) { + hash.update("d"); + hash.update(`${entry.timestampHash}`); + } + if (entry.symlinks !== undefined) { + if (symlinks === undefined) symlinks = new Set(); + addAll(entry.symlinks, symlinks); + } + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + } -/** @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} FakeHook */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + const digest = /** @type {string} */ (hash.digest("hex")); -const EMPTY_RESOLVE_OPTIONS = {}; + const result = { + safeTime, + timestampHash: digest + }; + if (symlinks) result.symlinks = symlinks; + return result; + } + }, + (err, result) => { + if (err) return callback(err); + this._contextTimestamps.set(path, result); + this._cachedDeprecatedContextTimestamps = undefined; -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, "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; + callback(null, result); + } + ); } /** - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * @param {ContextFileSystemInfoEntry} entry entry + * @param {function((Error | null)=, ResolvedContextFileSystemInfoEntry=): void} callback callback * @returns {void} */ - create(data, callback) { - const context = data.context; - const dependencies = data.dependencies; - const resolveOptions = data.resolveOptions; - const dependency = /** @type {ContextDependency} */ (dependencies[0]); - const fileDependencies = new LazySet(); - const missingDependencies = new LazySet(); - const contextDependencies = new LazySet(); - this.hooks.beforeResolve.callAsync( - { - context: context, - dependencies: dependencies, - resolveOptions, - fileDependencies, - missingDependencies, - contextDependencies, - ...dependency.options + _resolveContextTimestamp(entry, callback) { + const hashes = []; + let safeTime = 0; + processAsyncTree( + entry.symlinks, + 10, + (target, push, callback) => { + this._getUnresolvedContextTimestamp(target, (err, entry) => { + if (err) return callback(err); + if (entry && entry !== "ignore") { + hashes.push(entry.timestampHash); + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + if (entry.symlinks !== undefined) { + for (const target of entry.symlinks) push(target); + } + } + callback(); + }); }, - (err, beforeResolveResult) => { - if (err) { - return callback(err, { - fileDependencies, - missingDependencies, - contextDependencies - }); + err => { + if (err) return callback(err); + const hash = createHash(this._hashFunction); + hash.update(entry.timestampHash); + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + hashes.sort(); + for (const h of hashes) { + hash.update(h); } + callback( + null, + (entry.resolved = { + safeTime, + timestampHash: /** @type {string} */ (hash.digest("hex")) + }) + ); + } + ); + } - // Ignored - if (!beforeResolveResult) { - return callback(null, { - fileDependencies, - missingDependencies, - contextDependencies + _readContextHash(path, callback) { + this._readContext( + { + path, + fromImmutablePath: () => "", + fromManagedItem: info => info || "", + fromSymlink: (file, target, callback) => { + callback(null, { + hash: target, + symlinks: new Set([target]) }); - } + }, + fromFile: (file, stat, callback) => + this.getFileHash(file, (err, hash) => { + callback(err, hash || ""); + }), + fromDirectory: (directory, stat, callback) => { + this.contextHashQueue.increaseParallelism(); + this._getUnresolvedContextHash(directory, (err, hash) => { + this.contextHashQueue.decreaseParallelism(); + callback(err, hash || ""); + }); + }, + /** + * @param {string[]} files files + * @param {(string | ContextHash)[]} fileHashes hashes + * @returns {ContextHash} reduced hash + */ + reduce: (files, fileHashes) => { + let symlinks = undefined; + const hash = createHash(this._hashFunction); - 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("!"); + for (const file of files) hash.update(file); + for (const entry of fileHashes) { + if (typeof entry === "string") { + hash.update(entry); + } else { + hash.update(entry.hash); + if (entry.symlinks) { + if (symlinks === undefined) symlinks = new Set(); + addAll(entry.symlinks, symlinks); + } + } } - resource = request.substr(idx + 1); - } else { - loaders = []; - resource = request; + + const result = { + hash: /** @type {string} */ (hash.digest("hex")) + }; + if (symlinks) result.symlinks = symlinks; + return result; } + }, + (err, result) => { + if (err) return callback(err); + this._contextHashes.set(path, result); + return callback(null, result); + } + ); + } - const contextResolver = this.resolverFactory.get( - "context", - dependencies.length > 0 - ? cachedSetProperty( - resolveOptions || EMPTY_RESOLVE_OPTIONS, - "dependencyType", - dependencies[0].category - ) - : resolveOptions + /** + * @param {ContextHash} entry context hash + * @param {function((Error | null)=, string=): void} callback callback + * @returns {void} + */ + _resolveContextHash(entry, callback) { + const hashes = []; + processAsyncTree( + entry.symlinks, + 10, + (target, push, callback) => { + this._getUnresolvedContextHash(target, (err, hash) => { + if (err) return callback(err); + if (hash) { + hashes.push(hash.hash); + if (hash.symlinks !== undefined) { + for (const target of hash.symlinks) push(target); + } + } + callback(); + }); + }, + err => { + if (err) return callback(err); + const hash = createHash(this._hashFunction); + hash.update(entry.hash); + hashes.sort(); + for (const h of hashes) { + hash.update(h); + } + callback( + null, + (entry.resolved = /** @type {string} */ (hash.digest("hex"))) ); - 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); - } - ); + _readContextTimestampAndHash(path, callback) { + const finalize = (timestamp, hash) => { + const result = + timestamp === "ignore" + ? hash + : { + ...timestamp, + ...hash + }; + this._contextTshs.set(path, result); + callback(null, result); + }; + const cachedHash = this._contextHashes.get(path); + const cachedTimestamp = this._contextTimestamps.get(path); + if (cachedHash !== undefined) { + if (cachedTimestamp !== undefined) { + finalize(cachedTimestamp, cachedHash); + } else { + this.contextTimestampQueue.add(path, (err, entry) => { + if (err) return callback(err); + finalize(entry, cachedHash); + }); + } + } else { + if (cachedTimestamp !== undefined) { + this.contextHashQueue.add(path, (err, entry) => { + if (err) return callback(err); + finalize(cachedTimestamp, entry); + }); + } else { + this._readContext( + { + path, + fromImmutablePath: () => null, + fromManagedItem: info => ({ + safeTime: 0, + timestampHash: info, + hash: info || "" + }), + fromSymlink: (fle, target, callback) => { + callback(null, { + timestampHash: target, + hash: target, + symlinks: new Set([target]) + }); }, - 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 + fromFile: (file, stat, callback) => { + this._getFileTimestampAndHash(file, callback); + }, + fromDirectory: (directory, stat, callback) => { + this.contextTshQueue.increaseParallelism(); + this.contextTshQueue.add(directory, (err, result) => { + this.contextTshQueue.decreaseParallelism(); + callback(err, result); }); - } + }, + /** + * @param {string[]} files files + * @param {(Partial & Partial | string | null)[]} results results + * @returns {ContextTimestampAndHash} tsh + */ + reduce: (files, results) => { + let symlinks = undefined; - 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 - }); - } + const tsHash = createHash(this._hashFunction); + const hash = createHash(this._hashFunction); - // Ignored - if (!result) { - return callback(null, { - fileDependencies, - missingDependencies, - contextDependencies - }); + for (const file of files) { + tsHash.update(file); + hash.update(file); + } + let safeTime = 0; + for (const entry of results) { + if (!entry) { + tsHash.update("n"); + continue; } - - return callback(null, { - module: new ContextModule(result.resolveDependencies, result), - fileDependencies, - missingDependencies, - contextDependencies - }); + if (typeof entry === "string") { + tsHash.update("n"); + hash.update(entry); + continue; + } + if (entry.timestamp) { + tsHash.update("f"); + tsHash.update(`${entry.timestamp}`); + } else if (entry.timestampHash) { + tsHash.update("d"); + tsHash.update(`${entry.timestampHash}`); + } + if (entry.symlinks !== undefined) { + if (symlinks === undefined) symlinks = new Set(); + addAll(entry.symlinks, symlinks); + } + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + hash.update(entry.hash); } - ); + + const result = { + safeTime, + timestampHash: /** @type {string} */ (tsHash.digest("hex")), + hash: /** @type {string} */ (hash.digest("hex")) + }; + if (symlinks) result.symlinks = symlinks; + return result; + } + }, + (err, result) => { + if (err) return callback(err); + this._contextTshs.set(path, result); + return callback(null, result); } ); } - ); + } } /** - * @param {InputFileSystem} fs file system - * @param {ContextModuleOptions} options options - * @param {ResolveDependenciesCallback} callback callback function + * @param {ContextTimestampAndHash} entry entry + * @param {function((Error | null)=, ResolvedContextTimestampAndHash=): void} callback callback * @returns {void} */ - resolveDependencies(fs, options, callback) { - const cmf = this; - const { - resource, - resourceQuery, - resourceFragment, - recursive, - regExp, - include, - exclude, - referencedExports, - category, - typePrefix - } = 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); + _resolveContextTsh(entry, callback) { + const hashes = []; + const tsHashes = []; + let safeTime = 0; + processAsyncTree( + entry.symlinks, + 10, + (target, push, callback) => { + this._getUnresolvedContextTsh(target, (err, entry) => { + if (err) return callback(err); + if (entry) { + hashes.push(entry.hash); + if (entry.timestampHash) tsHashes.push(entry.timestampHash); + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); } - addDirectoryChecked(dir, recursionStack, callback); - }, - callback - ); - }); - }; - - const addDirectory = (directory, addSubDirectory, callback) => { - fs.readdir(directory, (err, files) => { + if (entry.symlinks !== undefined) { + for (const target of entry.symlinks) push(target); + } + } + callback(); + }); + }, + err => { if (err) return callback(err); - const processedFiles = cmf.hooks.contextModuleFiles.call( - /** @type {string[]} */ (files).map(file => file.normalize("NFC")) + const hash = createHash(this._hashFunction); + const tsHash = createHash(this._hashFunction); + hash.update(entry.hash); + if (entry.timestampHash) tsHash.update(entry.timestampHash); + if (entry.safeTime) { + safeTime = Math.max(safeTime, entry.safeTime); + } + hashes.sort(); + for (const h of hashes) { + hash.update(h); + } + tsHashes.sort(); + for (const h of tsHashes) { + tsHash.update(h); + } + callback( + null, + (entry.resolved = { + safeTime, + timestampHash: /** @type {string} */ (tsHash.digest("hex")), + hash: /** @type {string} */ (hash.digest("hex")) + }) ); - 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, - typePrefix, - 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 = []; + _getManagedItemDirectoryInfo(path, callback) { + this.fs.readdir(path, (err, elements) => { + if (err) { + if (err.code === "ENOENT" || err.code === "ENOTDIR") { + return callback(null, EMPTY_SET); + } + return callback(err); + } + const set = new Set( + /** @type {string[]} */ (elements).map(element => + join(this.fs, path, element) + ) + ); + callback(null, set); + }); + } - for (const item of result) { - if (item) flattenedResult.push(...item); - } + _getManagedItemInfo(path, callback) { + const dir = dirname(this.fs, path); + this.managedItemDirectoryQueue.add(dir, (err, elements) => { + if (err) { + return callback(err); + } + if (!elements.has(path)) { + // file or directory doesn't exist + this._managedItems.set(path, "*missing"); + return callback(null, "*missing"); + } + // something exists + // it may be a file or directory + if ( + path.endsWith("node_modules") && + (path.endsWith("/node_modules") || path.endsWith("\\node_modules")) + ) { + // we are only interested in existence of this special directory + this._managedItems.set(path, "*node_modules"); + return callback(null, "*node_modules"); + } - callback(null, flattenedResult); + // we assume it's a directory, as files shouldn't occur in managed paths + const packageJsonPath = join(this.fs, path, "package.json"); + this.fs.readFile(packageJsonPath, (err, content) => { + if (err) { + if (err.code === "ENOENT" || err.code === "ENOTDIR") { + // no package.json or path is not a directory + this.fs.readdir(path, (err, elements) => { + if ( + !err && + elements.length === 1 && + elements[0] === "node_modules" + ) { + // This is only a grouping folder e. g. used by yarn + // we are only interested in existence of this special directory + this._managedItems.set(path, "*nested"); + return callback(null, "*nested"); + } + this.logger.warn( + `Managed item ${path} isn't a directory or doesn't contain a package.json (see snapshot.managedPaths option)` + ); + return callback(); + }); + return; } - ); + return callback(err); + } + let data; + try { + data = JSON.parse(content.toString("utf-8")); + } catch (e) { + return callback(e); + } + if (!data.name) { + this.logger.warn( + `${packageJsonPath} doesn't contain a "name" property (see snapshot.managedPaths option)` + ); + return callback(); + } + const info = `${data.name || ""}@${data.version || ""}`; + this._managedItems.set(path, info); + callback(null, info); }); - }; + }); + } - if (typeof fs.realpath === "function") { - addDirectoryChecked(resource, new Set(), callback); - } else { - const addSubDirectory = (dir, callback) => - addDirectory(dir, addSubDirectory, callback); - addDirectory(resource, addSubDirectory, callback); + getDeprecatedFileTimestamps() { + if (this._cachedDeprecatedFileTimestamps !== undefined) + return this._cachedDeprecatedFileTimestamps; + const map = new Map(); + for (const [path, info] of this._fileTimestamps) { + if (info) map.set(path, typeof info === "object" ? info.safeTime : null); } + return (this._cachedDeprecatedFileTimestamps = map); } -}; + + getDeprecatedContextTimestamps() { + if (this._cachedDeprecatedContextTimestamps !== undefined) + return this._cachedDeprecatedContextTimestamps; + const map = new Map(); + for (const [path, info] of this._contextTimestamps) { + if (info) map.set(path, typeof info === "object" ? info.safeTime : null); + } + return (this._cachedDeprecatedContextTimestamps = map); + } +} + +module.exports = FileSystemInfo; +module.exports.Snapshot = Snapshot; /***/ }), -/***/ 12206: +/***/ 58727: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -38311,161 +40220,59 @@ module.exports = class ContextModuleFactory extends ModuleFactory { -const ContextElementDependency = __webpack_require__(58477); -const { join } = __webpack_require__(17139); +const { getEntryRuntime, mergeRuntimeOwned } = __webpack_require__(17156); -class ContextReplacementPlugin { - constructor( - resourceRegExp, - newContentResource, - newContentRecursive, - newContentRegExp - ) { - this.resourceRegExp = resourceRegExp; +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ - 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; - } +class FlagAllModulesAsUsedPlugin { + constructor(explanation) { + this.explanation = explanation; } + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ apply(compiler) { - const resourceRegExp = this.resourceRegExp; - const newContentCallback = this.newContentCallback; - const newContentResource = this.newContentResource; - const newContentRecursive = this.newContentRecursive; - const newContentRegExp = this.newContentRegExp; - const newContentCreateContextMap = this.newContentCreateContextMap; - - compiler.hooks.contextModuleFactory.tap("ContextReplacementPlugin", cmf => { - cmf.hooks.beforeResolve.tap("ContextReplacementPlugin", result => { - if (!result) return; - if (resourceRegExp.test(result.request)) { - if (newContentResource !== undefined) { - result.request = newContentResource; - } - if (newContentRecursive !== undefined) { - result.recursive = newContentRecursive; - } - if (newContentRegExp !== undefined) { - result.regExp = newContentRegExp; - } - if (typeof newContentCallback === "function") { - newContentCallback(result); - } else { - for (const d of result.dependencies) { - if (d.critical) d.critical = false; - } - } - } - return result; - }); - cmf.hooks.afterResolve.tap("ContextReplacementPlugin", result => { - if (!result) return; - if (resourceRegExp.test(result.resource)) { - if (newContentResource !== undefined) { - if ( - newContentResource.startsWith("/") || - (newContentResource.length > 1 && newContentResource[1] === ":") - ) { - result.resource = newContentResource; - } else { - result.resource = join( - 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 + 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) ); } - } else { - for (const d of result.dependencies) { - if (d.critical) d.critical = false; + 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; } } - } - 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; +module.exports = FlagAllModulesAsUsedPlugin; /***/ }), -/***/ 79065: +/***/ 84506: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -38476,269 +40283,456 @@ module.exports = ContextReplacementPlugin; -const RuntimeGlobals = __webpack_require__(16475); -const WebpackError = __webpack_require__(53799); -const ConstDependency = __webpack_require__(76911); -const BasicEvaluatedExpression = __webpack_require__(950); -const { - evaluateToString, - toConstantDependency -} = __webpack_require__(93998); -const createHash = __webpack_require__(49835); +const asyncLib = __webpack_require__(78175); +const Queue = __webpack_require__(65930); -/** @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} CodeValue */ - -/** - * @typedef {Object} RuntimeValueOptions - * @property {string[]=} fileDependencies - * @property {string[]=} contextDependencies - * @property {string[]=} missingDependencies - * @property {string[]=} buildDependencies - * @property {string|function(): string=} version - */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").ExportSpec} ExportSpec */ +/** @typedef {import("./Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("./ExportsInfo")} ExportsInfo */ +/** @typedef {import("./Module")} Module */ -class RuntimeValue { +class FlagDependencyExportsPlugin { /** - * @param {function({ module: NormalModule, key: string, readonly version: string | undefined }): CodeValuePrimitive} fn generator function - * @param {true | string[] | RuntimeValueOptions=} options options + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - constructor(fn, options) { - this.fn = fn; - if (Array.isArray(options)) { - options = { - fileDependencies: options - }; - } - this.options = options || {}; - } + 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 statRestoredFromMemCache = 0; + let statRestoredFromCache = 0; + let statNoExports = 0; + let statFlaggedUncached = 0; + let statNotCached = 0; + let statQueueItemsProcessed = 0; - get fileDependencies() { - return this.options === true ? true : this.options.fileDependencies; - } + const { moduleMemCaches } = compilation; - /** - * @param {JavascriptParser} parser the parser - * @param {Map>} 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); - } - } - } + /** @type {Queue} */ + const queue = new Queue(); - return this.fn({ - module: parser.state.module, - key, - get version() { - return /** @type {string} */ ( - valueCacheVersions.get(VALUE_DEP_PREFIX + key) - ); - } - }); - } + // Step 1: Try to restore cached provided export info from cache + logger.time("restore cached provided exports"); + asyncLib.each( + modules, + (module, callback) => { + const exportsInfo = moduleGraph.getExportsInfo(module); + if (!module.buildMeta || !module.buildMeta.exportsType) { + if (exportsInfo.otherExportsInfo.provided !== null) { + // It's a module without declared exports + statNoExports++; + exportsInfo.setHasProvideInfo(); + exportsInfo.setUnknownExportsProvided(); + return callback(); + } + } + if (typeof module.buildInfo.hash !== "string") { + statFlaggedUncached++; + // Enqueue uncacheable module for determining the exports + queue.enqueue(module); + exportsInfo.setHasProvideInfo(); + return callback(); + } + const memCache = moduleMemCaches && moduleMemCaches.get(module); + const memCacheValue = memCache && memCache.get(this); + if (memCacheValue !== undefined) { + statRestoredFromMemCache++; + exportsInfo.restoreProvided(memCacheValue); + return callback(); + } + cache.get( + module.identifier(), + module.buildInfo.hash, + (err, result) => { + if (err) return callback(err); - getCacheVersion() { - return this.options === true - ? undefined - : (typeof this.options.version === "function" - ? this.options.version() - : this.options.version) || "unset"; - } -} + if (result !== undefined) { + statRestoredFromCache++; + exportsInfo.restoreProvided(result); + } else { + statNotCached++; + // Without cached info enqueue module for determining the exports + queue.enqueue(module); + exportsInfo.setHasProvideInfo(); + } + callback(); + } + ); + }, + err => { + logger.timeEnd("restore cached provided exports"); + if (err) return callback(err); -/** - * @param {any[]|{[k: string]: any}} obj obj - * @param {JavascriptParser} parser Parser - * @param {Map>} 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(",")}}`; - } + /** @type {Set} */ + const modulesToStore = new Set(); - switch (asiSafe) { - case null: - return code; - case true: - return arr ? code : `(${code})`; - case false: - return arr ? `;${code}` : `;(${code})`; - default: - return `/*#__PURE__*/Object(${code})`; - } -}; + /** @type {Map>} */ + const dependencies = new Map(); -/** - * Convert code to a string that evaluates - * @param {CodeValue} code Code to evaluate - * @param {JavascriptParser} parser Parser - * @param {Map>} 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 + ""; -}; + /** @type {Module} */ + let module; -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 + ""; -}; + /** @type {ExportsInfo} */ + let exportsInfo; -const VALUE_DEP_PREFIX = "webpack/DefinePlugin "; -const VALUE_DEP_MAIN = "webpack/DefinePlugin_hash"; + /** @type {Map} */ + const exportsSpecsFromDependencies = new Map(); -class DefinePlugin { - /** - * Create a new define plugin - * @param {Record} definitions A map of global object definitions - */ - constructor(definitions) { - this.definitions = definitions; + let cacheable = true; + let changed = false; + + /** + * @param {DependenciesBlock} depBlock the dependencies block + * @returns {void} + */ + const processDependenciesBlock = depBlock => { + for (const dep of depBlock.dependencies) { + processDependency(dep); + } + for (const block of depBlock.blocks) { + processDependenciesBlock(block); + } + }; + + /** + * @param {Dependency} dep the dependency + * @returns {void} + */ + const processDependency = dep => { + const exportDesc = dep.getExports(moduleGraph); + if (!exportDesc) return; + exportsSpecsFromDependencies.set(dep, exportDesc); + }; + + /** + * @param {Dependency} dep dependency + * @param {ExportsSpec} exportDesc info + * @returns {void} + */ + const processExportsSpec = (dep, exportDesc) => { + const exports = exportDesc.exports; + const globalCanMangle = exportDesc.canMangle; + const globalFrom = exportDesc.from; + const globalPriority = exportDesc.priority; + const globalTerminalBinding = + exportDesc.terminalBinding || false; + const exportDeps = exportDesc.dependencies; + if (exportDesc.hideExports) { + for (const name of exportDesc.hideExports) { + const exportInfo = exportsInfo.getExportInfo(name); + exportInfo.unsetTarget(dep); + } + } + if (exports === true) { + // unknown exports + if ( + exportsInfo.setUnknownExportsProvided( + globalCanMangle, + exportDesc.excludeExports, + globalFrom && dep, + globalFrom, + globalPriority + ) + ) { + changed = true; + } + } else if (Array.isArray(exports)) { + /** + * merge in new exports + * @param {ExportsInfo} exportsInfo own exports info + * @param {(ExportSpec | string)[]} exports list of exports + */ + const mergeExports = (exportsInfo, exports) => { + for (const exportNameOrSpec of exports) { + let name; + let canMangle = globalCanMangle; + let terminalBinding = globalTerminalBinding; + let exports = undefined; + let from = globalFrom; + let fromExport = undefined; + let priority = globalPriority; + let hidden = false; + if (typeof exportNameOrSpec === "string") { + name = exportNameOrSpec; + } else { + name = exportNameOrSpec.name; + if (exportNameOrSpec.canMangle !== undefined) + canMangle = exportNameOrSpec.canMangle; + if (exportNameOrSpec.export !== undefined) + fromExport = exportNameOrSpec.export; + if (exportNameOrSpec.exports !== undefined) + exports = exportNameOrSpec.exports; + if (exportNameOrSpec.from !== undefined) + from = exportNameOrSpec.from; + if (exportNameOrSpec.priority !== undefined) + priority = exportNameOrSpec.priority; + if (exportNameOrSpec.terminalBinding !== undefined) + terminalBinding = exportNameOrSpec.terminalBinding; + if (exportNameOrSpec.hidden !== undefined) + hidden = exportNameOrSpec.hidden; + } + const exportInfo = exportsInfo.getExportInfo(name); + + if ( + exportInfo.provided === false || + exportInfo.provided === null + ) { + exportInfo.provided = true; + changed = true; + } + + if ( + exportInfo.canMangleProvide !== false && + canMangle === false + ) { + exportInfo.canMangleProvide = false; + changed = true; + } + + if (terminalBinding && !exportInfo.terminalBinding) { + exportInfo.terminalBinding = true; + changed = true; + } + + if (exports) { + const nestedExportsInfo = + exportInfo.createNestedExportsInfo(); + mergeExports(nestedExportsInfo, exports); + } + + if ( + from && + (hidden + ? exportInfo.unsetTarget(dep) + : exportInfo.setTarget( + dep, + from, + fromExport === undefined ? [name] : fromExport, + priority + )) + ) { + changed = true; + } + + // Recalculate target exportsInfo + const target = exportInfo.getTarget(moduleGraph); + let targetExportsInfo = 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); + + cacheable = true; + changed = false; + + exportsSpecsFromDependencies.clear(); + moduleGraph.freeze(); + processDependenciesBlock(module); + moduleGraph.unfreeze(); + for (const [ + dep, + exportsSpec + ] of exportsSpecsFromDependencies) { + processExportsSpec(dep, exportsSpec); + } + + if (cacheable) { + modulesToStore.add(module); + } + + if (changed) { + notifyDependencies(); + } + } + logger.timeEnd("figure out provided exports"); + + logger.log( + `${Math.round( + (100 * (statFlaggedUncached + statNotCached)) / + (statRestoredFromMemCache + + statRestoredFromCache + + statNotCached + + statFlaggedUncached + + statNoExports) + )}% of exports of modules have been determined (${statNoExports} no declared exports, ${statNotCached} not cached, ${statFlaggedUncached} flagged uncacheable, ${statRestoredFromCache} from cache, ${statRestoredFromMemCache} from mem cache, ${ + statQueueItemsProcessed - + statNotCached - + statFlaggedUncached + } additional calculations due to dependencies)` + ); + + logger.time("store provided exports into cache"); + asyncLib.each( + modulesToStore, + (module, callback) => { + if (typeof module.buildInfo.hash !== "string") { + // not cacheable + return callback(); + } + const cachedData = moduleGraph + .getExportsInfo(module) + .getRestoreProvidedData(); + const memCache = + moduleMemCaches && moduleMemCaches.get(module); + if (memCache) { + memCache.set(this, cachedData); + } + cache.store( + module.identifier(), + module.buildInfo.hash, + cachedData, + callback + ); + }, + err => { + logger.timeEnd("store provided exports into cache"); + callback(err); + } + ); + } + ); + } + ); + + /** @type {WeakMap} */ + 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; + + +/***/ }), + +/***/ 58812: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const Dependency = __webpack_require__(54912); +const { UsageState } = __webpack_require__(63686); +const ModuleGraphConnection = __webpack_require__(40639); +const { STAGE_DEFAULT } = __webpack_require__(80057); +const ArrayQueue = __webpack_require__(41792); +const TupleQueue = __webpack_require__(38415); +const { getEntryRuntime, mergeRuntimeOwned } = __webpack_require__(17156); + +/** @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 {function({ module: NormalModule, key: string, readonly version: string | undefined }): CodeValuePrimitive} fn generator function - * @param {true | string[] | RuntimeValueOptions=} options options - * @returns {RuntimeValue} runtime value + * @param {boolean} global do a global analysis instead of per runtime */ - static runtimeValue(fn, options) { - return new RuntimeValue(fn, options); + constructor(global) { + this.global = global; } /** @@ -38747,334 +40741,318 @@ class DefinePlugin { * @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; - - const mainHash = createHash(compilation.outputOptions.hashFunction); - mainHash.update( - /** @type {string} */ ( - compilation.valueCacheVersions.get(VALUE_DEP_MAIN) - ) || "" - ); - - /** - * Handler - * @param {JavascriptParser} parser Parser - * @returns {void} - */ - const handler = parser => { - const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN); - parser.hooks.program.tap("DefinePlugin", () => { - const { buildInfo } = parser.state.module; - if (!buildInfo.valueDependencies) - buildInfo.valueDependencies = new Map(); - buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue); - }); - - const addValueDependency = key => { - const { buildInfo } = parser.state.module; - buildInfo.valueDependencies.set( - VALUE_DEP_PREFIX + key, - compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key) + compiler.hooks.compilation.tap("FlagDependencyUsagePlugin", compilation => { + const moduleGraph = compilation.moduleGraph; + compilation.hooks.optimizeDependencies.tap( + { + name: "FlagDependencyUsagePlugin", + stage: STAGE_DEFAULT + }, + modules => { + if (compilation.moduleMemCaches) { + throw new Error( + "optimization.usedExports can't be used with cacheUnaffected as export usage is a global effect" ); - }; + } - const withValueDependency = - (key, fn) => - (...args) => { - addValueDependency(key); - return fn(...args); - }; + const logger = compilation.getLogger( + "webpack.FlagDependencyUsagePlugin" + ); + /** @type {Map} */ + const exportInfoToModuleMap = new Map(); + + /** @type {TupleQueue<[Module, RuntimeSpec]>} */ + const queue = new TupleQueue(); /** - * Walk definitions - * @param {Object} definitions Definitions map - * @param {string} prefix Prefix string + * @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 walkDefinitions = (definitions, prefix) => { - Object.keys(definitions).forEach(key => { - const code = definitions[key]; + 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 ( - code && - typeof code === "object" && - !(code instanceof RuntimeValue) && - !(code instanceof RegExp) + !forceSideEffects && + module.factoryMeta !== undefined && + module.factoryMeta.sideEffectFree ) { - walkDefinitions(code, prefix + key + "."); - applyObjectDefine(prefix + key, code); return; } - applyDefineKey(prefix, key); - applyDefine(prefix + key, code); - }); + if (exportsInfo.setUsedForSideEffectsOnly(runtime)) { + queue.enqueue(module, runtime); + } + } }; /** - * Apply define key - * @param {string} prefix Prefix - * @param {string} key Key + * @param {DependenciesBlock} module the module + * @param {RuntimeSpec} runtime part of which runtime + * @param {boolean} forceSideEffects always apply side effects * @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; - }); - }); - }; + const processModule = (module, runtime, forceSideEffects) => { + /** @type {Map>} */ + const map = new Map(); - /** - * 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 - ) + /** @type {ArrayQueue} */ + const queue = new ArrayQueue(); + queue.enqueue(module); + for (;;) { + const block = queue.dequeue(); + if (block === undefined) break; + for (const b of block.blocks) { + if ( + !this.global && + b.groupOptions && + b.groupOptions.entryOptions + ) { + processModule( + b, + b.groupOptions.entryOptions.runtime || undefined, + true ); - 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); + 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 + }); + } + } + } + } + } } - 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); + for (const [module, referencedExports] of map) { + if (Array.isArray(referencedExports)) { + processReferencedModule( + module, + referencedExports, + runtime, + forceSideEffects + ); } else { - return toConstantDependency(parser, strCode)(expr); + processReferencedModule( + module, + Array.from(referencedExports.values()), + runtime, + forceSideEffects + ); } - }); - parser.hooks.typeof - .for(key) - .tap( - "DefinePlugin", - withValueDependency( - key, - toConstantDependency(parser, JSON.stringify("object")) - ) - ); + } }; - walkDefinitions(definitions, ""); - }; + 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"); - 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); + logger.time("trace exports usage in graph"); - /** - * 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; - mainHash.update("|" + prefix + key); - const oldVersion = compilation.valueCacheVersions.get(name); - if (oldVersion === undefined) { - compilation.valueCacheVersions.set(name, version); - } else if (oldVersion !== version) { - const warning = new WebpackError( - `DefinePlugin\nConflicting values for '${prefix + key}'` + /** + * @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 ); - 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 + "."); + }; + /** @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); } - }); - }; - - walkDefinitionsForValues(definitions, ""); + 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); + } - compilation.valueCacheVersions.set( - VALUE_DEP_MAIN, - /** @type {string} */ (mainHash.digest("hex").slice(0, 8)) - ); - } - ); + while (queue.length) { + const [module, runtime] = queue.dequeue(); + processModule(module, runtime, false); + } + logger.timeEnd("trace exports usage in graph"); + } + ); + }); } } -module.exports = DefinePlugin; + +module.exports = FlagDependencyUsagePlugin; /***/ }), -/***/ 28623: +/***/ 93401: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -39085,244 +41063,153 @@ module.exports = DefinePlugin; -const { OriginalSource, RawSource } = __webpack_require__(51255); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const DelegatedSourceDependency = __webpack_require__(22914); -const StaticExportsDependency = __webpack_require__(91418); -const makeSerializable = __webpack_require__(33032); - /** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ /** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ /** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ +/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ /** @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("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./NormalModule")} NormalModule */ /** @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 -]); +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ -class DelegatedModule extends Module { - constructor(sourceRequest, data, type, userRequest, originalRequest) { - super("javascript/dynamic", null); +/** + * @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} runtimeRequirements the requirements for runtime + * @property {RuntimeSpec} runtime the runtime + * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules + * @property {CodeGenerationResults=} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that) + * @property {string} type which kind of code should be generated + * @property {function(): Map=} getData get access to the code generation data + */ - // Info from Factory - this.sourceRequest = sourceRequest; - this.request = data.id; - this.delegationType = type; - this.userRequest = userRequest; - this.originalRequest = originalRequest; - /** @type {ManifestModuleData} */ - this.delegateData = data; +/** + * @typedef {Object} UpdateHashContext + * @property {NormalModule} module the module + * @property {ChunkGraph} chunkGraph + * @property {RuntimeSpec} runtime + */ - // Build info - this.delegatedSourceDependency = undefined; - } - - /** - * @returns {Set} 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); +/** + * + */ +class Generator { + static byType(map) { + return new ByTypeGenerator(map); } + /* istanbul ignore next */ /** - * @returns {string} a unique identifier of the module + * @abstract + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - identifier() { - return `delegated ${JSON.stringify(this.request)} from ${ - this.sourceRequest - }`; + getTypes(module) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } + /* istanbul ignore next */ /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module + * @abstract + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - readableIdentifier(requestShortener) { - return `delegated ${this.userRequest} from ${this.sourceRequest}`; + getSize(module, type) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } + /* istanbul ignore next */ /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} + * @abstract + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code */ - needBuild(context, callback) { - return callback(null, !this.buildMeta); + generate( + module, + { dependencyTemplates, runtimeTemplate, moduleGraph, type } + ) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } /** - * @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} + * @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 */ - 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(); + getConcatenationBailoutReason(module, context) { + return `Module Concatenation is not implemented for ${this.constructor.name}`; } /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result + * @param {Hash} hash hash that will be modified + * @param {UpdateHashContext} updateHashContext context for updating hash */ - 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 - }; + updateHash(hash, { module, runtime }) { + // no nothing } +} - /** - * @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; +class ByTypeGenerator extends Generator { + constructor(map) { + super(); + this.map = map; + this._types = new Set(Object.keys(map)); } /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - 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; + getTypes(module) { + return this._types; } /** - * 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} + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - 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; + getSize(module, type) { + const t = type || "javascript"; + const generator = this.map[t]; + return generator ? generator.getSize(module, t) : 0; } /** - * Assuming this module is in the cache. Remove internal references to allow freeing some memory. + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code */ - cleanupForCache() { - super.cleanupForCache(); - this.delegateData = undefined; + 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); } } -makeSerializable(DelegatedModule, "webpack/lib/DelegatedModule"); - -module.exports = DelegatedModule; +module.exports = Generator; /***/ }), -/***/ 51387: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 37234: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -39332,261 +41219,166 @@ module.exports = DelegatedModule; -const DelegatedModule = __webpack_require__(28623); +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Module")} Module */ -// 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"]; +/** + * @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); } +}; - 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; - } - ); - } +/** + * @param {ChunkGroup} parent parent ChunkGroup to connect + * @param {ChunkGroup} child child ChunkGroup to connect + * @returns {void} + */ +const connectChunkGroupParentAndChild = (parent, child) => { + if (parent.addChild(child)) { + child.addParent(parent); } -} -module.exports = DelegatedModuleFactoryPlugin; +}; + +exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk; +exports.connectChunkGroupParentAndChild = connectChunkGroupParentAndChild; /***/ }), -/***/ 80632: +/***/ 97511: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const DelegatedModuleFactoryPlugin = __webpack_require__(51387); -const DelegatedSourceDependency = __webpack_require__(22914); - -/** @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 - ); - } - ); +const WebpackError = __webpack_require__(53799); - compiler.hooks.compile.tap("DelegatedPlugin", ({ normalModuleFactory }) => { - new DelegatedModuleFactoryPlugin({ - associatedObjectForCache: compiler.root, - ...this.options - }).apply(normalModuleFactory); - }); +module.exports = class HarmonyLinkingError extends WebpackError { + /** @param {string} message Error message */ + constructor(message) { + super(message); + this.name = "HarmonyLinkingError"; + this.hideStack = true; } -} - -module.exports = DelegatedPlugin; +}; /***/ }), -/***/ 71040: +/***/ 11351: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sean Larkin @thelarkinn */ -const makeSerializable = __webpack_require__(33032); - -/** @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 */ +const WebpackError = __webpack_require__(53799); -class DependenciesBlock { - constructor() { - /** @type {Dependency[]} */ - this.dependencies = []; - /** @type {AsyncDependenciesBlock[]} */ - this.blocks = []; - /** @type {DependenciesBlock} */ - this.parent = undefined; - } +/** @typedef {import("./Module")} Module */ - getRootBlock() { - /** @type {DependenciesBlock} */ - let current = this; - while (current.parent) current = current.parent; - return current; - } +/** + * @template T + * @callback Callback + * @param {Error=} err + * @param {T=} stats + * @returns {void} + */ +class HookWebpackError extends WebpackError { /** - * 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} + * Creates an instance of HookWebpackError. + * @param {Error} error inner error + * @param {string} hook name of hook */ - addBlock(block) { - this.blocks.push(block); - block.parent = this; - } + constructor(error, hook) { + super(error.message); - /** - * @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); - } + this.name = "HookWebpackError"; + this.hook = hook; + this.error = error; + this.hideStack = true; + this.details = `caused by plugins in ${hook}\n${error.stack}`; - /** - * @param {Dependency} dependency dependency being removed - * @returns {void} - */ - removeDependency(dependency) { - const idx = this.dependencies.indexOf(dependency); - if (idx >= 0) { - this.dependencies.splice(idx, 1); - } + this.stack += `\n-- inner error --\n${error.stack}`; } +} - /** - * Removes all dependencies and blocks - * @returns {void} - */ - clearDependenciesAndBlocks() { - this.dependencies.length = 0; - this.blocks.length = 0; - } +module.exports = HookWebpackError; - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - for (const dep of this.dependencies) { - dep.updateHash(hash, context); - } - for (const block of this.blocks) { - block.updateHash(hash, context); +/** + * @param {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 | null)=, T=): void} callback webpack error callback + * @param {string} hook name of hook + * @returns {Callback} 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); + }; +}; - serialize({ write }) { - write(this.dependencies); - write(this.blocks); - } +module.exports.makeWebpackErrorCallback = makeWebpackErrorCallback; - deserialize({ read }) { - this.dependencies = read(); - this.blocks = read(); - for (const block of this.blocks) { - block.parent = this; +/** + * @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); } -} - -makeSerializable(DependenciesBlock, "webpack/lib/DependenciesBlock"); + return r; +}; -module.exports = DependenciesBlock; +module.exports.tryRunOrWebpackError = tryRunOrWebpackError; /***/ }), -/***/ 54912: +/***/ 6404: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -39597,352 +41389,782 @@ module.exports = DependenciesBlock; -const memoize = __webpack_require__(78676); +const { SyncBailHook } = __webpack_require__(6967); +const { RawSource } = __webpack_require__(51255); +const ChunkGraph = __webpack_require__(64971); +const Compilation = __webpack_require__(85720); +const HotUpdateChunk = __webpack_require__(9597); +const NormalModule = __webpack_require__(39); +const RuntimeGlobals = __webpack_require__(16475); +const WebpackError = __webpack_require__(53799); +const ConstDependency = __webpack_require__(76911); +const ImportMetaHotAcceptDependency = __webpack_require__(51274); +const ImportMetaHotDeclineDependency = __webpack_require__(53141); +const ModuleHotAcceptDependency = __webpack_require__(47511); +const ModuleHotDeclineDependency = __webpack_require__(86301); +const HotModuleReplacementRuntimeModule = __webpack_require__(27899); +const JavascriptParser = __webpack_require__(29050); +const { + evaluateToIdentifier +} = __webpack_require__(93998); +const { find, isSubset } = __webpack_require__(93347); +const TupleSet = __webpack_require__(76455); +const { compareModulesById } = __webpack_require__(29579); +const { + getRuntimeKey, + keyToRuntime, + forEachRuntime, + mergeRuntimeOwned, + subtractRuntime, + intersectRuntime +} = __webpack_require__(17156); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compiler")} Compiler */ /** @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("./RuntimeModule")} RuntimeModule */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** - * @typedef {Object} UpdateHashContext - * @property {ChunkGraph} chunkGraph - * @property {RuntimeSpec} runtime - * @property {RuntimeTemplate=} runtimeTemplate - */ - -/** - * @typedef {Object} SourcePosition - * @property {number} line - * @property {number=} column - */ - -/** - * @typedef {Object} RealDependencyLocation - * @property {SourcePosition} start - * @property {SourcePosition=} end - * @property {number=} index - */ - -/** - * @typedef {Object} SyntheticDependencyLocation - * @property {string} name - * @property {number=} index - */ - -/** @typedef {SyntheticDependencyLocation|RealDependencyLocation} DependencyLocation */ - -/** - * @typedef {Object} ExportSpec - * @property {string} name the name of the export - * @property {boolean=} canMangle can the export be renamed (defaults to true) - * @property {boolean=} terminalBinding is the export a terminal binding that should be checked for export star conflicts - * @property {(string | ExportSpec)[]=} exports nested exports - * @property {ModuleGraphConnection=} from when reexported: from which module - * @property {string[] | null=} export when reexported: from which export - * @property {number=} priority when reexported: with which priority - * @property {boolean=} hidden export is not visible, because another export blends over it - */ - -/** - * @typedef {Object} ExportsSpec - * @property {(string | ExportSpec)[] | true | null} exports exported names, true for unknown exports or null for no exports - * @property {Set=} excludeExports when exports = true, list of unaffected exports - * @property {Set=} hideExports list of maybe prior exposed, but now hidden exports - * @property {ModuleGraphConnection=} from when reexported: from which module - * @property {number=} priority when reexported: with which priority - * @property {boolean=} canMangle can the export be renamed (defaults to true) - * @property {boolean=} terminalBinding are the exports terminal bindings that should be checked for export star conflicts - * @property {Module[]=} dependencies module on which the result depends on - */ - -/** - * @typedef {Object} ReferencedExport - * @property {string[]} name name of the referenced export - * @property {boolean=} canMangle when false, referenced export can not be mangled, defaults to true + * @typedef {Object} HMRJavascriptParserHooks + * @property {SyncBailHook<[TODO, string[]], void>} hotAcceptCallback + * @property {SyncBailHook<[TODO, string[]], void>} hotAcceptWithoutCallback */ -const TRANSITIVE = Symbol("transitive"); - -const getIgnoredModule = memoize(() => { - const RawModule = __webpack_require__(84929); - return new RawModule("/* (ignored) */", `ignored`, `(ignored)`); -}); - -class Dependency { - constructor() { - /** @type {Module} */ - this._parentModule = undefined; - /** @type {DependenciesBlock} */ - this._parentDependenciesBlock = undefined; - /** @type {number} */ - this._parentDependenciesBlockIndex = -1; - // TODO check if this can be moved into ModuleDependency - /** @type {boolean} */ - this.weak = false; - // TODO check if this can be moved into ModuleDependency - /** @type {boolean} */ - this.optional = false; - this._locSL = 0; - this._locSC = 0; - this._locEL = 0; - this._locEC = 0; - this._locI = undefined; - this._locN = undefined; - this._loc = undefined; - } - - /** - * @returns {string} a display name for the type of dependency - */ - get type() { - return "unknown"; - } - - /** - * @returns {string} a dependency category, typical categories are "commonjs", "amd", "esm" - */ - get category() { - return "unknown"; - } +/** @type {WeakMap} */ +const parserHooksMap = new WeakMap(); +class HotModuleReplacementPlugin { /** - * @returns {DependencyLocation} location + * @param {JavascriptParser} parser the parser + * @returns {HMRJavascriptParserHooks} the attached hooks */ - get loc() { - if (this._loc !== undefined) return this._loc; - /** @type {SyntheticDependencyLocation & RealDependencyLocation} */ - const loc = {}; - if (this._locSL > 0) { - loc.start = { line: this._locSL, column: this._locSC }; - } - if (this._locEL > 0) { - loc.end = { line: this._locEL, column: this._locEC }; - } - if (this._locN !== undefined) { - loc.name = this._locN; - } - if (this._locI !== undefined) { - loc.index = this._locI; - } - return (this._loc = loc); - } - - set loc(loc) { - if ("start" in loc && typeof loc.start === "object") { - this._locSL = loc.start.line || 0; - this._locSC = loc.start.column || 0; - } else { - this._locSL = 0; - this._locSC = 0; - } - if ("end" in loc && typeof loc.end === "object") { - this._locEL = loc.end.line || 0; - this._locEC = loc.end.column || 0; - } else { - this._locEL = 0; - this._locEC = 0; - } - if ("index" in loc) { - this._locI = loc.index; - } else { - this._locI = undefined; + static getParserHooks(parser) { + if (!(parser instanceof JavascriptParser)) { + throw new TypeError( + "The 'parser' argument must be an instance of JavascriptParser" + ); } - if ("name" in loc) { - this._locN = loc.name; - } else { - this._locN = undefined; + let hooks = parserHooksMap.get(parser); + if (hooks === undefined) { + hooks = { + hotAcceptCallback: new SyncBailHook(["expression", "requests"]), + hotAcceptWithoutCallback: new SyncBailHook(["expression", "requests"]) + }; + parserHooksMap.set(parser, hooks); } - this._loc = loc; + return hooks; } - setLoc(startLine, startColumn, endLine, endColumn) { - this._locSL = startLine; - this._locSC = startColumn; - this._locEL = endLine; - this._locEC = endColumn; - this._locI = undefined; - this._locN = undefined; - this._loc = undefined; + constructor(options) { + this.options = options || {}; } /** - * @returns {string | null} an identifier to merge equal requests + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - getResourceIdentifier() { - return null; - } + apply(compiler) { + const { _backCompat: backCompat } = compiler; + if (compiler.options.output.strictModuleErrorHandling === undefined) + compiler.options.output.strictModuleErrorHandling = true; + const runtimeRequirements = [RuntimeGlobals.module]; - /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module - */ - couldAffectReferencingModule() { - return TRANSITIVE; - } + const createAcceptHandler = (parser, ParamDependency) => { + const { hotAcceptCallback, hotAcceptWithoutCallback } = + HotModuleReplacementPlugin.getParserHooks(parser); - /** - * 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" - ); - } + 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; + }; + }; - /** - * 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; - } + 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; + }; - /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active - */ - getCondition(moduleGraph) { - return null; - } + 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; + }; - /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names - */ - getExports(moduleGraph) { - return undefined; - } + 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)); + }; - /** - * Returns warnings - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} warnings - */ - getWarnings(moduleGraph) { - return null; - } + 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)); + }; - /** - * Returns errors - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} errors - */ - getErrors(moduleGraph) { - return null; - } + 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; - /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) {} + //#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 - /** - * 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; - } + //#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 - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules - */ - getModuleEvaluationSideEffectsState(moduleGraph) { - return true; - } + let hotIndex = 0; + const fullHashChunkModuleHashes = {}; + const chunkModuleHashes = {}; - /** - * @param {string} context context directory - * @returns {Module} a module - */ - createIgnoredModule(context) { - return getIgnoredModule(); - } + 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.chunkHashes = {}; + records.chunkRuntime = {}; + for (const chunk of compilation.chunks) { + records.chunkHashes[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; + } + } + } + } + } - serialize({ write }) { - write(this.weak); - write(this.optional); - write(this._locSL); - write(this._locSC); - write(this._locEL); - write(this._locEC); - write(this._locI); - write(this._locN); - } + hotIndex = records.hotIndex || 0; + if (updatedModules.size > 0) hotIndex++; - deserialize({ read }) { - this.weak = read(); - this.optional = read(); - this._locSL = read(); - this._locSC = read(); - this._locEL = read(); - this._locEC = read(); - this._locI = read(); - this._locN = read(); - } -} + 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.chunkHashes || + !records.chunkModuleIds + ) { + return; + } + for (const [module, chunk] of fullHashModules) { + const key = `${chunk.id}|${module.identifier()}`; + const hash = nonCodeGeneratedModules.has(module, chunk.runtime) + ? chunkGraph.getModuleHash(module, chunk.runtime) + : compilation.codeGenerationResults.getHash( + module, + chunk.runtime + ); + if (records.chunkModuleHashes[key] !== hash) { + updatedModules.add(module, chunk); + } + chunkModuleHashes[key] = hash; + } -/** @type {string[][]} */ -Dependency.NO_EXPORTS_REFERENCED = []; -/** @type {string[][]} */ -Dependency.EXPORTS_OBJECT_REFERENCED = [[]]; + /** @type {Map, removedChunkIds: Set, removedModules: Set, 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; -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)" - ); - }, + // Create a list of all active modules to verify which modules are removed completely + /** @type {Map} */ + const allModules = new Map(); + for (const module of compilation.modules) { + const id = chunkGraph.getModuleId(module); + allModules.set(id, module); + } - /** - * @deprecated - * @returns {never} throws - */ - set() { - throw new Error( - "module property was removed from Dependency (use compilation.moduleGraph.updateModule(dependency, module) instead)" - ); - } -}); + // List of completely removed modules + /** @type {Set} */ + const completelyRemovedModules = new Set(); -Object.defineProperty(Dependency.prototype, "disconnect", { - get() { - throw new Error( - "disconnect was removed from Dependency (Dependency no longer carries graph specific information)" + for (const key of Object.keys(records.chunkHashes)) { + const oldRuntime = keyToRuntime(records.chunkRuntime[key]); + /** @type {Module[]} */ + const remainingModules = []; + // Check which modules are removed + for (const id of records.chunkModuleIds[key]) { + const module = allModules.get(id); + if (module === undefined) { + completelyRemovedModules.add(id); + } else { + remainingModules.push(module); + } + } + + let chunkId; + let newModules; + let newRuntimeModules; + let newFullHashModules; + let newDependentHashModules; + let newRuntime; + let removedFromRuntime; + const currentChunk = find( + compilation.chunks, + chunk => `${chunk.id}` === key + ); + if (currentChunk) { + chunkId = currentChunk.id; + newRuntime = intersectRuntime( + currentChunk.runtime, + allOldRuntime + ); + if (newRuntime === undefined) continue; + newModules = chunkGraph + .getChunkModules(currentChunk) + .filter(module => updatedModules.has(module, currentChunk)); + newRuntimeModules = Array.from( + chunkGraph.getChunkRuntimeModulesIterable(currentChunk) + ).filter(module => updatedModules.has(module, currentChunk)); + const fullHashModules = + chunkGraph.getChunkFullHashModulesIterable(currentChunk); + newFullHashModules = + fullHashModules && + Array.from(fullHashModules).filter(module => + updatedModules.has(module, currentChunk) + ); + const dependentHashModules = + chunkGraph.getChunkDependentHashModulesIterable(currentChunk); + newDependentHashModules = + dependentHashModules && + Array.from(dependentHashModules).filter(module => + updatedModules.has(module, currentChunk) + ); + removedFromRuntime = subtractRuntime(oldRuntime, newRuntime); + } else { + // chunk has completely removed + chunkId = `${+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(); + if (backCompat) + ChunkGraph.setChunkGraphForChunk(hotUpdateChunk, chunkGraph); + hotUpdateChunk.id = chunkId; + hotUpdateChunk.runtime = newRuntime; + if (currentChunk) { + for (const group of currentChunk.groupsIterable) + hotUpdateChunk.addGroup(group); + } + chunkGraph.attachModules(hotUpdateChunk, newModules || []); + chunkGraph.attachRuntimeModules( + hotUpdateChunk, + newRuntimeModules || [] + ); + if (newFullHashModules) { + chunkGraph.attachFullHashModules( + hotUpdateChunk, + newFullHashModules + ); + } + if (newDependentHashModules) { + chunkGraph.attachDependentHashModules( + hotUpdateChunk, + newDependentHashModules + ); + } + const renderManifest = compilation.getRenderManifest({ + chunk: hotUpdateChunk, + hash: records.hash, + fullHash: records.hash, + outputOptions: compilation.outputOptions, + moduleTemplates: compilation.moduleTemplates, + dependencyTemplates: compilation.dependencyTemplates, + codeGenerationResults: compilation.codeGenerationResults, + runtimeTemplate: compilation.runtimeTemplate, + moduleGraph: compilation.moduleGraph, + chunkGraph + }); + for (const entry of renderManifest) { + /** @type {string} */ + let filename; + /** @type {AssetInfo} */ + let assetInfo; + if ("filename" in entry) { + filename = entry.filename; + assetInfo = entry.info; + } else { + ({ path: filename, info: assetInfo } = + compilation.getPathWithInfo( + entry.filenameTemplate, + entry.pathOptions + )); + } + const source = entry.render(); + compilation.additionalChunkAssets.push(filename); + compilation.emitAsset(filename, source, { + hotModuleReplacement: true, + ...assetInfo + }); + if (currentChunk) { + currentChunk.files.add(filename); + compilation.hooks.chunkAsset.call(currentChunk, filename); + } + } + forEachRuntime(newRuntime, runtime => { + 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; + } + ); + } ); } -}); - -Dependency.TRANSITIVE = TRANSITIVE; +} -module.exports = Dependency; +module.exports = HotModuleReplacementPlugin; /***/ }), -/***/ 5160: +/***/ 9597: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -39953,61 +42175,70 @@ module.exports = Dependency; -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +const Chunk = __webpack_require__(39385); + /** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./Generator").GenerateContext} GenerateContext */ -/** @template T @typedef {import("./InitFragment")} InitFragment */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./util/Hash")} Hash */ -/** - * @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} 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 - * @property {CodeGenerationResults} codeGenerationResults the code generation results - */ +class HotUpdateChunk extends Chunk { + constructor() { + super(); + } +} + +module.exports = HotUpdateChunk; + + +/***/ }), + +/***/ 3: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +const ModuleFactory = __webpack_require__(51010); + +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ /** - * @typedef {Object} CssDependencyTemplateContextExtras - * @property {Map} cssExports the css exports + * Ignores error when module is unresolved */ +class IgnoreErrorModuleFactory extends ModuleFactory { + /** + * @param {NormalModuleFactory} normalModuleFactory normalModuleFactory instance + */ + constructor(normalModuleFactory) { + super(); -/** @typedef {DependencyTemplateContext & CssDependencyTemplateContextExtras} CssDependencyTemplateContext */ + this.normalModuleFactory = normalModuleFactory; + } -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 + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback * @returns {void} */ - apply(dependency, source, templateContext) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + create(data, callback) { + this.normalModuleFactory.create(data, (err, result) => { + return callback(null, result); + }); } } -module.exports = DependencyTemplate; +module.exports = IgnoreErrorModuleFactory; /***/ }), -/***/ 9163: +/***/ 84808: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -40018,72 +42249,88 @@ module.exports = DependencyTemplate; -const createHash = __webpack_require__(49835); - -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ -/** @typedef {typeof import("./util/Hash")} Hash */ +const createSchemaValidation = __webpack_require__(32540); -/** @typedef {new (...args: any[]) => Dependency} DependencyConstructor */ +/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./NormalModuleFactory").ResolveData} ResolveData */ -class DependencyTemplates { - /** - * @param {string | Hash} hashFunction the hash function to use - */ - constructor(hashFunction = "md4") { - /** @type {Map} */ - this._map = new Map(); - /** @type {string} */ - this._hash = "31d6cfe0d16ae931b73c59d7e0c089c0"; - this._hashFunction = hashFunction; +const validate = createSchemaValidation( + __webpack_require__(20858), + () => __webpack_require__(3098), + { + name: "Ignore Plugin", + baseDataPath: "options" } +); +class IgnorePlugin { /** - * @param {DependencyConstructor} dependency Constructor of Dependency - * @returns {DependencyTemplate} template for this dependency + * @param {IgnorePluginOptions} options IgnorePlugin options */ - get(dependency) { - return this._map.get(dependency); + constructor(options) { + validate(options); + this.options = options; + + /** @private @type {Function} */ + this.checkIgnore = this.checkIgnore.bind(this); } /** - * @param {DependencyConstructor} dependency Constructor of Dependency - * @param {DependencyTemplate} dependencyTemplate template for this dependency - * @returns {void} + * 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 */ - set(dependency, dependencyTemplate) { - this._map.set(dependency, dependencyTemplate); + 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; + } + } } /** - * @param {string} part additional hash contributor + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - updateHash(part) { - const hash = createHash(this._hashFunction); - hash.update(`${this._hash}${part}`); - this._hash = /** @type {string} */ (hash.digest("hex")); - } - - getHash() { - return this._hash; - } - - clone() { - const newInstance = new DependencyTemplates(this._hashFunction); - newInstance._map = new Map(this._map); - newInstance._hash = this._hash; - return newInstance; + 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 = DependencyTemplates; +module.exports = IgnorePlugin; /***/ }), -/***/ 62790: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 7373: +/***/ (function(module) { "use strict"; /* @@ -40093,224 +42340,212 @@ module.exports = DependencyTemplates; -const DllModuleFactory = __webpack_require__(68703); -const DllEntryDependency = __webpack_require__(95666); -const EntryDependency = __webpack_require__(3979); +/** @typedef {import("../declarations/WebpackOptions").IgnoreWarningsNormalized} IgnoreWarningsNormalized */ +/** @typedef {import("./Compiler")} Compiler */ -class DllEntryPlugin { - constructor(context, entries, options) { - this.context = context; - this.entries = entries; - this.options = options; +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( - "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 + 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 = DllEntryPlugin; +module.exports = IgnoreWarningsPlugin; /***/ }), -/***/ 28280: +/***/ 55870: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Florent Cailhol @ooflorent */ -const { RawSource } = __webpack_require__(51255); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); +const { ConcatSource } = __webpack_require__(51255); const makeSerializable = __webpack_require__(33032); /** @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); +/** @typedef {import("./Generator").GenerateContext} GenerateContext */ - // Info from Factory - this.dependencies = dependencies; - this.name = name; - } +/** + * @param {InitFragment} fragment the init fragment + * @param {number} index index + * @returns {[InitFragment, number]} tuple with both + */ +const extractFragmentIndex = (fragment, index) => [fragment, index]; - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; - } +/** + * @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; +}; +/** + * @template Context + */ +class InitFragment { /** - * @returns {string} a unique identifier of the module + * @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 */ - identifier() { - return `dll ${this.name}`; + constructor(content, stage, position, key, endContent) { + this.content = content; + this.stage = stage; + this.position = position; + this.key = key; + this.endContent = endContent; } /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module + * @param {Context} context context + * @returns {string|Source} the source code that will be included as initialization code */ - readableIdentifier(requestShortener) { - return `dll ${this.name}`; + getContent(context) { + return this.content; } /** - * @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} + * @param {Context} context context + * @returns {string|Source=} the source code that will be included at the end of the module */ - build(options, compilation, resolver, fs, callback) { - this.buildMeta = {}; - this.buildInfo = {}; - return callback(); + getEndContent(context) { + return this.endContent; } - /** - * @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 - }; - } + static addToSource(source, initFragments, context) { + 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); - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - return callback(null, !this.buildMeta); - } + // Deduplicate fragments. If a fragment has no key, it is always included. + const keyedFragments = new Map(); + for (const [fragment] of sortedFragments) { + if (typeof fragment.mergeAll === "function") { + if (!fragment.key) { + throw new Error( + `InitFragment with mergeAll function must have a valid key: ${fragment.constructor.name}` + ); + } + const oldValue = keyedFragments.get(fragment.key); + if (oldValue === undefined) { + keyedFragments.set(fragment.key, fragment); + } else if (Array.isArray(oldValue)) { + oldValue.push(fragment); + } else { + keyedFragments.set(fragment.key, [oldValue, fragment]); + } + continue; + } else if (typeof fragment.merge === "function") { + const oldValue = keyedFragments.get(fragment.key); + if (oldValue !== undefined) { + keyedFragments.set(fragment.key, fragment.merge(oldValue)); + continue; + } + } + keyedFragments.set(fragment.key || Symbol(), fragment); + } - /** - * @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; - } + const concatSource = new ConcatSource(); + const endContents = []; + for (let fragment of keyedFragments.values()) { + if (Array.isArray(fragment)) { + fragment = fragment[0].mergeAll(fragment); + } + concatSource.add(fragment.getContent(context)); + const endContent = fragment.getEndContent(context); + if (endContent) { + endContents.push(endContent); + } + } - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - hash.update(`dll module${this.name || ""}`); - super.updateHash(hash, context); + concatSource.add(source); + for (const content of endContents.reverse()) { + concatSource.add(content); + } + return concatSource; + } else { + return source; + } } serialize(context) { - context.write(this.name); - super.serialize(context); - } + const { write } = context; - deserialize(context) { - this.name = context.read(); - super.deserialize(context); + write(this.content); + write(this.stage); + write(this.position); + write(this.key); + write(this.endContent); } - /** - * 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; - } + deserialize(context) { + const { read } = context; - /** - * Assuming this module is in the cache. Remove internal references to allow freeing some memory. - */ - cleanupForCache() { - super.cleanupForCache(); - this.dependencies = undefined; + this.content = read(); + this.stage = read(); + this.position = read(); + this.key = read(); + this.endContent = read(); } } -makeSerializable(DllModule, "webpack/lib/DllModule"); +makeSerializable(InitFragment, "webpack/lib/InitFragment"); -module.exports = DllModule; +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; /***/ }), -/***/ 68703: +/***/ 68257: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -40321,314 +42556,152 @@ module.exports = DllModule; -const DllModule = __webpack_require__(28280); -const ModuleFactory = __webpack_require__(51010); +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("./dependencies/DllEntryDependency")} DllEntryDependency */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ -class DllModuleFactory extends ModuleFactory { - constructor() { - super(); - this.hooks = Object.freeze({}); - } +class InvalidDependenciesModuleWarning extends WebpackError { /** - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback - * @returns {void} + * @param {Module} module module tied to dependency + * @param {Iterable} deps invalid dependencies */ - create(data, callback) { - const dependency = /** @type {DllEntryDependency} */ (data.dependencies[0]); - callback(null, { - module: new DllModule( - data.context, - dependency.dependencies, - dependency.name - ) - }); + 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; } } -module.exports = DllModuleFactory; +makeSerializable( + InvalidDependenciesModuleWarning, + "webpack/lib/InvalidDependenciesModuleWarning" +); + +module.exports = InvalidDependenciesModuleWarning; /***/ }), -/***/ 40038: +/***/ 52329: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sergey Melyukov @smelukov */ -const DllEntryPlugin = __webpack_require__(62790); -const FlagAllModulesAsUsedPlugin = __webpack_require__(58727); -const LibManifestPlugin = __webpack_require__(93837); -const createSchemaValidation = __webpack_require__(32540); +const InnerGraph = __webpack_require__(38988); -/** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */ /** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ -const validate = createSchemaValidation( - __webpack_require__(9667), - () => __webpack_require__(99926), - { - name: "Dll Plugin", - baseDataPath: "options" - } -); - -class DllPlugin { - /** - * @param {DllPluginOptions} options options object - */ - constructor(options) { - validate(options); - this.options = { - ...options, - entryOnly: options.entryOnly !== false - }; - } - +class JavascriptMetaInfoPlugin { /** * 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; - - -/***/ }), - -/***/ 90999: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const parseJson = __webpack_require__(15235); -const DelegatedModuleFactoryPlugin = __webpack_require__(51387); -const ExternalModuleFactoryPlugin = __webpack_require__(62153); -const WebpackError = __webpack_require__(53799); -const DelegatedSourceDependency = __webpack_require__(22914); -const createSchemaValidation = __webpack_require__(32540); -const makePathsRelative = (__webpack_require__(82186).makePathsRelative); - -/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ -/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ -/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ - -const validate = createSchemaValidation( - __webpack_require__(28534), - () => __webpack_require__(46552), - { - name: "Dll Reference Plugin", - baseDataPath: "options" - } -); - -class DllReferencePlugin { - /** - * @param {DllReferencePluginOptions} options options object - */ - constructor(options) { - validate(options); - this.options = options; - /** @type {WeakMap} */ - this._compilationData = new WeakMap(); - } - apply(compiler) { compiler.hooks.compilation.tap( - "DllReferencePlugin", + "JavascriptMetaInfoPlugin", (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); + /** + * @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; + const currentSymbol = InnerGraph.getTopLevelSymbol(parser.state); + if (currentSymbol) { + InnerGraph.addUsage(parser.state, null, currentSymbol); + } else { + 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); } - 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); - } - } + }); + }; + + 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); } ); } } -class DllManifestError extends WebpackError { - constructor(filename, message) { - super(); - - this.name = "DllManifestError"; - this.message = `Dll manifest ${filename}\n${message}`; - } -} - -module.exports = DllReferencePlugin; +module.exports = JavascriptMetaInfoPlugin; /***/ }), -/***/ 96475: +/***/ 93837: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Naoyuki Kanezawa @nkzawa + Author Tobias Koppers @sokra */ -const EntryOptionPlugin = __webpack_require__(9909); -const EntryPlugin = __webpack_require__(96953); +const asyncLib = __webpack_require__(78175); const EntryDependency = __webpack_require__(3979); +const { someInIterable } = __webpack_require__(39104); +const { compareModulesById } = __webpack_require__(29579); +const { dirname, mkdirp } = __webpack_require__(17139); -/** @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; +/** + * @typedef {Object} ManifestModuleData + * @property {string | number} id + * @property {Object} buildMeta + * @property {boolean | string[]} exports + */ + +class LibManifestPlugin { + constructor(options) { + this.options = options; } /** @@ -40637,158 +42710,93 @@ class DynamicEntryPlugin { * @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(); - } - ); - }) - ); + 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; } } - return Promise.all(promises); - }) - .then(x => {}) - ); - } -} - -module.exports = DynamicEntryPlugin; - - -/***/ }), - -/***/ 9909: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @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 = __webpack_require__(96475); - new DynamicEntryPlugin(context, entry).apply(compiler); - } else { - const EntryPlugin = __webpack_require__(96953); - for (const name of Object.keys(entry)) { - const desc = entry[name]; - const options = EntryOptionPlugin.entryDescriptionToOptions( - compiler, - name, - desc + 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 ); - 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, - publicPath: desc.publicPath, - chunkLoading: desc.chunkLoading, - asyncChunks: desc.asyncChunks, - wasmLoading: desc.wasmLoading, - library: desc.library - }; - if (desc.layer !== undefined && !compiler.options.experiments.layers) { - throw new Error( - "'entryOptions.layer' is only allowed when 'experiments.layers' is enabled" - ); - } - if (desc.chunkLoading) { - const EnableChunkLoadingPlugin = __webpack_require__(61291); - EnableChunkLoadingPlugin.checkEnabled(compiler, desc.chunkLoading); - } - if (desc.wasmLoading) { - const EnableWasmLoadingPlugin = __webpack_require__(78613); - EnableWasmLoadingPlugin.checkEnabled(compiler, desc.wasmLoading); - } - if (desc.library) { - const EnableLibraryPlugin = __webpack_require__(91452); - EnableLibraryPlugin.checkEnabled(compiler, desc.library.type); - } - return options; + ); } } - -module.exports = EntryOptionPlugin; +module.exports = LibManifestPlugin; /***/ }), -/***/ 96953: +/***/ 14157: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -40799,24 +42807,32 @@ module.exports = EntryOptionPlugin; -const EntryDependency = __webpack_require__(3979); +const EnableLibraryPlugin = __webpack_require__(91452); +/** @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 */ -/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */ -class EntryPlugin { +// TODO webpack 6 remove +class LibraryTemplatePlugin { /** - * 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) + * @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(context, entry, options) { - this.context = context; - this.entry = entry; - this.options = options || ""; + constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) { + this.library = { + type: target || "var", + name, + umdNamedDefine, + auxiliaryComment, + export: exportProperty + }; } /** @@ -40825,45 +42841,18 @@ class EntryPlugin { * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap( - "EntryPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - EntryDependency, - normalModuleFactory - ); - } - ); - - const { entry, options, context } = this; - const dep = EntryPlugin.createDependency(entry, options); - - compiler.hooks.make.tapAsync("EntryPlugin", (compilation, callback) => { - 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; + const { output } = compiler.options; + output.library = this.library; + new EnableLibraryPlugin(this.library.type).apply(compiler); } } -module.exports = EntryPlugin; +module.exports = LibraryTemplatePlugin; /***/ }), -/***/ 13795: +/***/ 22078: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -40874,133 +42863,34 @@ module.exports = EntryPlugin; -const ChunkGroup = __webpack_require__(15626); - -/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */ -/** @typedef {import("./Chunk")} Chunk */ - -/** @typedef {{ name?: string } & Omit} 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; - } +const ModuleFilenameHelpers = __webpack_require__(88821); +const NormalModule = __webpack_require__(39); +const createSchemaValidation = __webpack_require__(32540); - /** - * 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; - } +/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ - /** - * Returns the chunk which contains the entrypoint modules - * (or at least the execution of them) - * @returns {Chunk} chunk - */ - getEntrypointChunk() { - return this._entrypointChunk; +const validate = createSchemaValidation( + __webpack_require__(24160), + () => __webpack_require__(15965), + { + name: "Loader Options Plugin", + baseDataPath: "options" } - +); +class LoaderOptionsPlugin { /** - * @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 + * @param {LoaderOptionsPluginOptions} options options object */ - 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; - - -/***/ }), - -/***/ 22070: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Authors Simen Brekken @simenbrekken, Einar Löve @einarlove -*/ - - - -const DefinePlugin = __webpack_require__(79065); -const WebpackError = __webpack_require__(53799); - -/** @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 = {}; + constructor(options = {}) { + validate(options); + if (typeof options !== "object") options = {}; + if (!options.test) { + options.test = { + test: () => true + }; } + this.options = options; } /** @@ -41009,110 +42899,39 @@ class EnvironmentPlugin { * @returns {void} */ apply(compiler) { - /** @type {Record} */ - 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); + 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 = EnvironmentPlugin; - - -/***/ }), - -/***/ 59985: -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -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; -}; +module.exports = LoaderOptionsPlugin; /***/ }), -/***/ 65218: +/***/ 86738: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -41123,35 +42942,16 @@ exports.cleanUpWebpackOptions = (stack, message) => { -const { ConcatSource, RawSource } = __webpack_require__(51255); -const ExternalModule = __webpack_require__(73071); -const ModuleFilenameHelpers = __webpack_require__(88821); -const RuntimeGlobals = __webpack_require__(16475); -const JavascriptModulesPlugin = __webpack_require__(89464); +const NormalModule = __webpack_require__(39); -/** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("./Compiler")} Compiler */ -/** @type {WeakMap} */ -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]"; +class LoaderTargetPlugin { + /** + * @param {string} target the target + */ + constructor(target) { + this.target = target; } /** @@ -41160,84 +42960,23 @@ class EvalDevToolModulePlugin { * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap("EvalDevToolModulePlugin", compilation => { - const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); - hooks.renderModuleContent.tap( - "EvalDevToolModulePlugin", - (source, module, { runtimeTemplate, chunkGraph }) => { - const cacheEntry = cache.get(source); - if (cacheEntry !== undefined) return cacheEntry; - if (module instanceof ExternalModule) { - cache.set(source, source); - return source; - } - const content = source.source(); - const str = ModuleFilenameHelpers.createFilename( - module, - { - moduleFilenameTemplate: this.moduleFilenameTemplate, - namespace: this.namespace - }, - { - requestShortener: runtimeTemplate.requestShortener, - chunkGraph, - hashFunction: compilation.outputOptions.hashFunction - } - ); - const footer = - "\n" + - this.sourceUrlComment.replace( - /\[url\]/g, - encodeURI(str) - .replace(/%2F/g, "/") - .replace(/%20/g, "_") - .replace(/%5E/g, "^") - .replace(/%5C/g, "\\") - .replace(/^\//, "") - ); - const result = new RawSource( - `eval(${ - compilation.outputOptions.trustedTypes - ? `${RuntimeGlobals.createScript}(${JSON.stringify( - content + footer - )})` - : JSON.stringify(content + footer) - });` - ); - cache.set(source, result); - return result; + compiler.hooks.compilation.tap("LoaderTargetPlugin", compilation => { + NormalModule.getCompilationHooks(compilation).loader.tap( + "LoaderTargetPlugin", + loaderContext => { + loaderContext.target = this.target; } ); - hooks.inlineInRuntimeBailout.tap( - "EvalDevToolModulePlugin", - () => "the eval devtool is used." - ); - hooks.render.tap( - "EvalDevToolModulePlugin", - source => new ConcatSource(devtoolWarning, source) - ); - hooks.chunkHash.tap("EvalDevToolModulePlugin", (chunk, hash) => { - hash.update("EvalDevToolModulePlugin"); - hash.update("2"); - }); - if (compilation.outputOptions.trustedTypes) { - compilation.hooks.additionalModuleRuntimeRequirements.tap( - "EvalDevToolModulePlugin", - (module, set, context) => { - set.add(RuntimeGlobals.createScript); - } - ); - } }); } } -module.exports = EvalDevToolModulePlugin; +module.exports = LoaderTargetPlugin; /***/ }), -/***/ 14790: +/***/ 12856: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -41248,210 +42987,333 @@ module.exports = EvalDevToolModulePlugin; -const { ConcatSource, RawSource } = __webpack_require__(51255); -const ModuleFilenameHelpers = __webpack_require__(88821); -const NormalModule = __webpack_require__(39); +const { SyncWaterfallHook } = __webpack_require__(6967); +const util = __webpack_require__(73837); const RuntimeGlobals = __webpack_require__(16475); -const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(97513); -const JavascriptModulesPlugin = __webpack_require__(89464); -const ConcatenatedModule = __webpack_require__(97198); -const { makePathsAbsolute } = __webpack_require__(82186); +const memoize = __webpack_require__(78676); +/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ /** @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} */ -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/). - */ -`); +/** @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("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext} */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate} */ +/** @typedef {import("./ModuleGraph")} ModuleGraph} */ +/** @typedef {import("./ChunkGraph")} ChunkGraph} */ +/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions} */ +/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry} */ -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; - } +const getJavascriptModulesPlugin = memoize(() => + __webpack_require__(89464) +); +const getJsonpTemplatePlugin = memoize(() => + __webpack_require__(4607) +); +const getLoadScriptRuntimeModule = memoize(() => + __webpack_require__(19942) +); +// TODO webpack 6 remove this class +class MainTemplate { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * + * @param {OutputOptions} outputOptions output options for the MainTemplate + * @param {Compilation} compilation the compilation */ - 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); + 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); } - } else if (m instanceof ConcatenatedModule) { - const concatModule = /** @type {ConcatenatedModule} */ (m); - if (concatModule.rootModule instanceof NormalModule) { - const module = /** @type {NormalModule} */ ( - concatModule.rootModule + ); + }, + "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 ); - if (!matchModule(module.resource)) { - return result(source); + }); + }, + "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; } - } 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); - } + 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)" + ); + } + }, - // 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 = makePathsAbsolute(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, - hashFunction: compilation.outputOptions.hashFunction - } - ); - }); - 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`; + // 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; + } + }); - 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 + 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" + ); - return result( - new RawSource( - `eval(${ - compilation.outputOptions.trustedTypes - ? `${RuntimeGlobals.createScript}(${JSON.stringify( - content + footer - )})` - : JSON.stringify(content + footer) - });` - ) - ); - } - ); - hooks.inlineInRuntimeBailout.tap( - "EvalDevToolModulePlugin", - () => "the eval-source-map devtool is used." - ); - hooks.render.tap( - "EvalSourceMapDevToolPlugin", - source => new ConcatSource(devtoolWarning, source) + this.getPublicPath = util.deprecate( + /** + * + * @param {object} options get public path options + * @returns {string} hook call + */ options => { + return compilation.getAssetPath( + compilation.outputOptions.publicPath, + options ); - hooks.chunkHash.tap("EvalSourceMapDevToolPlugin", (chunk, hash) => { - hash.update("EvalSourceMapDevToolPlugin"); - hash.update("2"); - }); - if (compilation.outputOptions.trustedTypes) { - compilation.hooks.additionalModuleRuntimeRequirements.tap( - "EvalSourceMapDevToolPlugin", - (module, set, context) => { - set.add(RuntimeGlobals.createScript); - } - ); - } - } + }, + "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" ); } } -module.exports = EvalSourceMapDevToolPlugin; +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; /***/ }), -/***/ 63686: +/***/ 73208: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -41462,1527 +43324,1230 @@ module.exports = EvalSourceMapDevToolPlugin; -const { equals } = __webpack_require__(84953); -const SortableSet = __webpack_require__(13098); +const util = __webpack_require__(73837); +const ChunkGraph = __webpack_require__(64971); +const DependenciesBlock = __webpack_require__(71040); +const ModuleGraph = __webpack_require__(99988); +const RuntimeGlobals = __webpack_require__(16475); +const { first } = __webpack_require__(93347); +const { compareChunksById } = __webpack_require__(29579); const makeSerializable = __webpack_require__(33032); -const { forEachRuntime } = __webpack_require__(17156); -/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./ExportsInfo").UsageStateType} UsageStateType */ +/** @typedef {import("./FileSystemInfo")} FileSystemInfo */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./WebpackError")} WebpackError */ /** @typedef {import("./util/Hash")} Hash */ +/** @template T @typedef {import("./util/LazySet")} LazySet */ +/** @template T @typedef {import("./util/SortableSet")} SortableSet */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ -/** @typedef {typeof UsageState.OnlyPropertiesUsed | typeof UsageState.NoInfo | typeof UsageState.Unknown | typeof UsageState.Used} RuntimeUsageStateType */ -/** @typedef {typeof UsageState.Unused | RuntimeUsageStateType} UsageStateType */ +/** + * @typedef {Object} SourceContext + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {RuntimeSpec} runtime the runtimes code should be generated for + * @property {string=} type the type of source that should be generated + */ -const UsageState = Object.freeze({ - Unused: /** @type {0} */ (0), - OnlyPropertiesUsed: /** @type {1} */ (1), - NoInfo: /** @type {2} */ (2), - Unknown: /** @type {3} */ (3), - Used: /** @type {4} */ (4) -}); +/** + * @typedef {Object} CodeGenerationContext + * @property {DependencyTemplates} dependencyTemplates the dependency templates + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {RuntimeSpec} runtime the runtimes code should be generated for + * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules + * @property {CodeGenerationResults} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that) + */ -const RETURNS_TRUE = () => true; +/** + * @typedef {Object} ConcatenationBailoutReasonContext + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + */ -const CIRCULAR = Symbol("circular target"); +/** + * @typedef {Object} CodeGenerationResult + * @property {Map} sources the resulting sources for all source types + * @property {Map=} data the resulting data for all source types + * @property {ReadonlySet} runtimeRequirements the runtime requirements + * @property {string=} hash a hash of the code generation result (will be automatically calculated from sources and runtimeRequirements if not provided) + */ -class RestoreProvidedData { - constructor( - exports, - otherProvided, - otherCanMangleProvide, - otherTerminalBinding - ) { - this.exports = exports; - this.otherProvided = otherProvided; - this.otherCanMangleProvide = otherCanMangleProvide; - this.otherTerminalBinding = otherTerminalBinding; - } +/** + * @typedef {Object} LibIdentOptions + * @property {string} context absolute context path to which lib ident is relative to + * @property {Object=} associatedObjectForCache object for caching + */ - serialize({ write }) { - write(this.exports); - write(this.otherProvided); - write(this.otherCanMangleProvide); - write(this.otherTerminalBinding); - } +/** + * @typedef {Object} KnownBuildMeta + * @property {string=} moduleArgument + * @property {string=} exportsArgument + * @property {boolean=} strict + * @property {string=} moduleConcatenationBailout + * @property {("default" | "namespace" | "flagged" | "dynamic")=} exportsType + * @property {(false | "redirect" | "redirect-warn")=} defaultObject + * @property {boolean=} strictHarmonyModule + * @property {boolean=} async + * @property {boolean=} sideEffectFree + */ - static deserialize({ read }) { - return new RestoreProvidedData(read(), read(), read(), read()); - } -} +/** + * @typedef {Object} NeedBuildContext + * @property {Compilation} compilation + * @property {FileSystemInfo} fileSystemInfo + * @property {Map>} valueCacheVersions + */ -makeSerializable( - RestoreProvidedData, - "webpack/lib/ModuleGraph", - "RestoreProvidedData" +/** @typedef {KnownBuildMeta & Record} BuildMeta */ + +const EMPTY_RESOLVE_OPTIONS = {}; + +let debugId = 1000; + +const DEFAULT_TYPES_UNKNOWN = new Set(["unknown"]); +const DEFAULT_TYPES_JS = new Set(["javascript"]); + +const deprecatedNeedRebuild = util.deprecate( + (module, context) => { + return module.needRebuild( + context.fileSystemInfo.getDeprecatedFileTimestamps(), + context.fileSystemInfo.getDeprecatedContextTimestamps() + ); + }, + "Module.needRebuild is deprecated in favor of Module.needBuild", + "DEP_WEBPACK_MODULE_NEED_REBUILD" ); -class ExportsInfo { - constructor() { - /** @type {Map} */ - this._exports = new Map(); - this._otherExportsInfo = new ExportInfo(null); - this._sideEffectsOnlyInfo = new ExportInfo("*side effects only*"); - this._exportsAreOrdered = false; - /** @type {ExportsInfo=} */ - this._redirectTo = undefined; - } +/** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ +class Module extends DependenciesBlock { /** - * @returns {Iterable} all owned exports in any order + * @param {string} type the module type + * @param {string=} context an optional context + * @param {string=} layer an optional layer in which the module is */ - get ownedExports() { - return this._exports.values(); + constructor(type, context = null, layer = null) { + super(); + + /** @type {string} */ + this.type = type; + /** @type {string | null} */ + this.context = context; + /** @type {string | null} */ + this.layer = layer; + /** @type {boolean} */ + this.needId = true; + + // Unique Id + /** @type {number} */ + this.debugId = debugId++; + + // Info from Factory + /** @type {ResolveOptions} */ + this.resolveOptions = EMPTY_RESOLVE_OPTIONS; + /** @type {object | undefined} */ + this.factoryMeta = undefined; + // TODO refactor this -> options object filled from Factory + // TODO webpack 6: use an enum + /** @type {boolean} */ + this.useSourceMap = false; + /** @type {boolean} */ + this.useSimpleSourceMap = false; + + // Info from Build + /** @type {WebpackError[] | undefined} */ + this._warnings = undefined; + /** @type {WebpackError[] | undefined} */ + this._errors = undefined; + /** @type {BuildMeta} */ + this.buildMeta = undefined; + /** @type {Record} */ + this.buildInfo = undefined; + /** @type {Dependency[] | undefined} */ + this.presentationalDependencies = undefined; + /** @type {Dependency[] | undefined} */ + this.codeGenerationDependencies = undefined; } - /** - * @returns {Iterable} all owned exports in order - */ - get orderedOwnedExports() { - if (!this._exportsAreOrdered) { - this._sortExports(); - } - return this._exports.values(); + // TODO remove in webpack 6 + // BACKWARD-COMPAT START + get id() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.id", + "DEP_WEBPACK_MODULE_ID" + ).getModuleId(this); } - /** - * @returns {Iterable} all exports in any order - */ - get exports() { - if (this._redirectTo !== undefined) { - const map = new Map(this._redirectTo._exports); - for (const [key, value] of this._exports) { - map.set(key, value); - } - return map.values(); + set id(value) { + if (value === "") { + this.needId = false; + return; } - return this._exports.values(); + ChunkGraph.getChunkGraphForModule( + this, + "Module.id", + "DEP_WEBPACK_MODULE_ID" + ).setModuleId(this, value); } /** - * @returns {Iterable} all exports in order + * @returns {string} the hash of the module */ - get orderedExports() { - if (!this._exportsAreOrdered) { - this._sortExports(); - } - if (this._redirectTo !== undefined) { - const map = new Map( - Array.from(this._redirectTo.orderedExports, item => [item.name, item]) - ); - for (const [key, value] of this._exports) { - map.set(key, value); - } - // sorting should be pretty fast as map contains - // a lot of presorted items - this._sortExportsMap(map); - return map.values(); - } - return this._exports.values(); + get hash() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.hash", + "DEP_WEBPACK_MODULE_HASH" + ).getModuleHash(this, undefined); } /** - * @returns {ExportInfo} the export info of unlisted exports + * @returns {string} the shortened hash of the module */ - get otherExportsInfo() { - if (this._redirectTo !== undefined) - return this._redirectTo.otherExportsInfo; - return this._otherExportsInfo; + get renderedHash() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.renderedHash", + "DEP_WEBPACK_MODULE_RENDERED_HASH" + ).getRenderedModuleHash(this, undefined); } - _sortExportsMap(exports) { - if (exports.size > 1) { - const namesInOrder = []; - for (const entry of exports.values()) { - namesInOrder.push(entry.name); - } - namesInOrder.sort(); - let i = 0; - for (const entry of exports.values()) { - const name = namesInOrder[i]; - if (entry.name !== name) break; - i++; - } - for (; i < namesInOrder.length; i++) { - const name = namesInOrder[i]; - const correctEntry = exports.get(name); - exports.delete(name); - exports.set(name, correctEntry); - } - } + get profile() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.profile", + "DEP_WEBPACK_MODULE_PROFILE" + ).getProfile(this); } - _sortExports() { - this._sortExportsMap(this._exports); - this._exportsAreOrdered = true; + set profile(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.profile", + "DEP_WEBPACK_MODULE_PROFILE" + ).setProfile(this, value); } - setRedirectNamedTo(exportsInfo) { - if (this._redirectTo === exportsInfo) return false; - this._redirectTo = exportsInfo; - return true; + get index() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.index", + "DEP_WEBPACK_MODULE_INDEX" + ).getPreOrderIndex(this); } - setHasProvideInfo() { - for (const exportInfo of this._exports.values()) { - if (exportInfo.provided === undefined) { - exportInfo.provided = false; - } - if (exportInfo.canMangleProvide === undefined) { - exportInfo.canMangleProvide = true; - } - } - if (this._redirectTo !== undefined) { - this._redirectTo.setHasProvideInfo(); - } else { - if (this._otherExportsInfo.provided === undefined) { - this._otherExportsInfo.provided = false; - } - if (this._otherExportsInfo.canMangleProvide === undefined) { - this._otherExportsInfo.canMangleProvide = true; - } - } + set index(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.index", + "DEP_WEBPACK_MODULE_INDEX" + ).setPreOrderIndex(this, value); } - setHasUseInfo() { - for (const exportInfo of this._exports.values()) { - exportInfo.setHasUseInfo(); - } - this._sideEffectsOnlyInfo.setHasUseInfo(); - if (this._redirectTo !== undefined) { - this._redirectTo.setHasUseInfo(); - } else { - this._otherExportsInfo.setHasUseInfo(); - if (this._otherExportsInfo.canMangleUse === undefined) { - this._otherExportsInfo.canMangleUse = true; - } - } + get index2() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.index2", + "DEP_WEBPACK_MODULE_INDEX2" + ).getPostOrderIndex(this); } - /** - * @param {string} name export name - * @returns {ExportInfo} export info for this name - */ - getOwnExportInfo(name) { - const info = this._exports.get(name); - if (info !== undefined) return info; - const newInfo = new ExportInfo(name, this._otherExportsInfo); - this._exports.set(name, newInfo); - this._exportsAreOrdered = false; - return newInfo; + set index2(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.index2", + "DEP_WEBPACK_MODULE_INDEX2" + ).setPostOrderIndex(this, value); + } + + get depth() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.depth", + "DEP_WEBPACK_MODULE_DEPTH" + ).getDepth(this); + } + + set depth(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.depth", + "DEP_WEBPACK_MODULE_DEPTH" + ).setDepth(this, value); + } + + get issuer() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.issuer", + "DEP_WEBPACK_MODULE_ISSUER" + ).getIssuer(this); + } + + set issuer(value) { + ModuleGraph.getModuleGraphForModule( + this, + "Module.issuer", + "DEP_WEBPACK_MODULE_ISSUER" + ).setIssuer(this, value); + } + + get usedExports() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.usedExports", + "DEP_WEBPACK_MODULE_USED_EXPORTS" + ).getUsedExports(this, undefined); } /** - * @param {string} name export name - * @returns {ExportInfo} export info for this name + * @deprecated + * @returns {(string | OptimizationBailoutFunction)[]} list */ - getExportInfo(name) { - const info = this._exports.get(name); - if (info !== undefined) return info; - if (this._redirectTo !== undefined) - return this._redirectTo.getExportInfo(name); - const newInfo = new ExportInfo(name, this._otherExportsInfo); - this._exports.set(name, newInfo); - this._exportsAreOrdered = false; - return newInfo; + get optimizationBailout() { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.optimizationBailout", + "DEP_WEBPACK_MODULE_OPTIMIZATION_BAILOUT" + ).getOptimizationBailout(this); + } + + get optional() { + return this.isOptional( + ModuleGraph.getModuleGraphForModule( + this, + "Module.optional", + "DEP_WEBPACK_MODULE_OPTIONAL" + ) + ); + } + + addChunk(chunk) { + const chunkGraph = ChunkGraph.getChunkGraphForModule( + this, + "Module.addChunk", + "DEP_WEBPACK_MODULE_ADD_CHUNK" + ); + if (chunkGraph.isModuleInChunk(this, chunk)) return false; + chunkGraph.connectChunkAndModule(chunk, this); + return true; + } + + removeChunk(chunk) { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.removeChunk", + "DEP_WEBPACK_MODULE_REMOVE_CHUNK" + ).disconnectChunkAndModule(chunk, this); + } + + isInChunk(chunk) { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.isInChunk", + "DEP_WEBPACK_MODULE_IS_IN_CHUNK" + ).isModuleInChunk(this, chunk); + } + + isEntryModule() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.isEntryModule", + "DEP_WEBPACK_MODULE_IS_ENTRY_MODULE" + ).isEntryModule(this); + } + + getChunks() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.getChunks", + "DEP_WEBPACK_MODULE_GET_CHUNKS" + ).getModuleChunks(this); + } + + getNumberOfChunks() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.getNumberOfChunks", + "DEP_WEBPACK_MODULE_GET_NUMBER_OF_CHUNKS" + ).getNumberOfModuleChunks(this); + } + + get chunksIterable() { + return ChunkGraph.getChunkGraphForModule( + this, + "Module.chunksIterable", + "DEP_WEBPACK_MODULE_CHUNKS_ITERABLE" + ).getOrderedModuleChunksIterable(this, compareChunksById); } /** - * @param {string} name export name - * @returns {ExportInfo} export info for this name + * @param {string} exportName a name of an export + * @returns {boolean | null} true, if the export is provided why the module. + * null, if it's unknown. + * false, if it's not provided. */ - getReadOnlyExportInfo(name) { - const info = this._exports.get(name); - if (info !== undefined) return info; - if (this._redirectTo !== undefined) - return this._redirectTo.getReadOnlyExportInfo(name); - return this._otherExportsInfo; + isProvided(exportName) { + return ModuleGraph.getModuleGraphForModule( + this, + "Module.usedExports", + "DEP_WEBPACK_MODULE_USED_EXPORTS" + ).isExportProvided(this, exportName); } + // BACKWARD-COMPAT END /** - * @param {string[]} name export name - * @returns {ExportInfo | undefined} export info for this name + * @deprecated moved to .buildInfo.exportsArgument + * @returns {string} name of the exports argument */ - getReadOnlyExportInfoRecursive(name) { - const exportInfo = this.getReadOnlyExportInfo(name[0]); - if (name.length === 1) return exportInfo; - if (!exportInfo.exportsInfo) return undefined; - return exportInfo.exportsInfo.getReadOnlyExportInfoRecursive(name.slice(1)); + get exportsArgument() { + return (this.buildInfo && this.buildInfo.exportsArgument) || "exports"; } /** - * @param {string[]=} name the export name - * @returns {ExportsInfo | undefined} the nested exports info + * @deprecated moved to .buildInfo.moduleArgument + * @returns {string} name of the module argument */ - getNestedExportsInfo(name) { - if (Array.isArray(name) && name.length > 0) { - const info = this.getReadOnlyExportInfo(name[0]); - if (!info.exportsInfo) return undefined; - return info.exportsInfo.getNestedExportsInfo(name.slice(1)); - } - return this; + get moduleArgument() { + return (this.buildInfo && this.buildInfo.moduleArgument) || "module"; } /** - * @param {boolean=} canMangle true, if exports can still be mangled (defaults to false) - * @param {Set=} excludeExports list of unaffected exports - * @param {any=} targetKey use this as key for the target - * @param {ModuleGraphConnection=} targetModule set this module as target - * @param {number=} priority priority - * @returns {boolean} true, if this call changed something + * @param {ModuleGraph} moduleGraph the module graph + * @param {boolean} strict the importing module is strict + * @returns {"namespace" | "default-only" | "default-with-named" | "dynamic"} export type + * "namespace": Exports is already a namespace object. namespace = exports. + * "dynamic": Check at runtime if __esModule is set. When set: namespace = { ...exports, default: exports }. When not set: namespace = { default: exports }. + * "default-only": Provide a namespace object with only default export. namespace = { default: exports } + * "default-with-named": Provide a namespace object with named and default export. namespace = { ...exports, default: exports } */ - setUnknownExportsProvided( - canMangle, - excludeExports, - targetKey, - targetModule, - priority - ) { - let changed = false; - if (excludeExports) { - for (const name of excludeExports) { - // Make sure these entries exist, so they can get different info - this.getExportInfo(name); - } - } - for (const exportInfo of this._exports.values()) { - if (excludeExports && excludeExports.has(exportInfo.name)) continue; - if (exportInfo.provided !== true && exportInfo.provided !== null) { - exportInfo.provided = null; - changed = true; - } - if (!canMangle && exportInfo.canMangleProvide !== false) { - exportInfo.canMangleProvide = false; - changed = true; - } - if (targetKey) { - exportInfo.setTarget(targetKey, targetModule, [exportInfo.name], -1); - } - } - if (this._redirectTo !== undefined) { - if ( - this._redirectTo.setUnknownExportsProvided( - canMangle, - excludeExports, - targetKey, - targetModule, - priority - ) - ) { - changed = true; - } - } else { - if ( - this._otherExportsInfo.provided !== true && - this._otherExportsInfo.provided !== null - ) { - this._otherExportsInfo.provided = null; - changed = true; - } - if (!canMangle && this._otherExportsInfo.canMangleProvide !== false) { - this._otherExportsInfo.canMangleProvide = false; - changed = true; - } - if (targetKey) { - this._otherExportsInfo.setTarget( - targetKey, - targetModule, - undefined, - priority + getExportsType(moduleGraph, strict) { + switch (this.buildMeta && this.buildMeta.exportsType) { + case "flagged": + return strict ? "default-with-named" : "namespace"; + case "namespace": + return "namespace"; + case "default": + switch (this.buildMeta.defaultObject) { + case "redirect": + return "default-with-named"; + case "redirect-warn": + return strict ? "default-only" : "default-with-named"; + default: + return "default-only"; + } + case "dynamic": { + if (strict) return "default-with-named"; + // Try to figure out value of __esModule by following reexports + const handleDefault = () => { + switch (this.buildMeta.defaultObject) { + case "redirect": + case "redirect-warn": + return "default-with-named"; + default: + return "default-only"; + } + }; + const exportInfo = moduleGraph.getReadOnlyExportInfo( + this, + "__esModule" ); + if (exportInfo.provided === false) { + return handleDefault(); + } + const target = exportInfo.getTarget(moduleGraph); + if ( + !target || + !target.export || + target.export.length !== 1 || + target.export[0] !== "__esModule" + ) { + return "dynamic"; + } + switch ( + target.module.buildMeta && + target.module.buildMeta.exportsType + ) { + case "flagged": + case "namespace": + return "namespace"; + case "default": + return handleDefault(); + default: + return "dynamic"; + } } + default: + return strict ? "default-with-named" : "dynamic"; } - return changed; } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, when something changed + * @param {Dependency} presentationalDependency dependency being tied to module. + * This is a Dependency without edge in the module graph. It's only for presentation. + * @returns {void} */ - setUsedInUnknownWay(runtime) { - let changed = false; - for (const exportInfo of this._exports.values()) { - if (exportInfo.setUsedInUnknownWay(runtime)) { - changed = true; - } + addPresentationalDependency(presentationalDependency) { + if (this.presentationalDependencies === undefined) { + this.presentationalDependencies = []; } - if (this._redirectTo !== undefined) { - if (this._redirectTo.setUsedInUnknownWay(runtime)) { - changed = true; - } - } else { - if ( - this._otherExportsInfo.setUsedConditionally( - used => used < UsageState.Unknown, - UsageState.Unknown, - runtime - ) - ) { - changed = true; - } - if (this._otherExportsInfo.canMangleUse !== false) { - this._otherExportsInfo.canMangleUse = false; - changed = true; - } + this.presentationalDependencies.push(presentationalDependency); + } + + /** + * @param {Dependency} codeGenerationDependency dependency being tied to module. + * This is a Dependency where the code generation result of the referenced module is needed during code generation. + * The Dependency should also be added to normal dependencies via addDependency. + * @returns {void} + */ + addCodeGenerationDependency(codeGenerationDependency) { + if (this.codeGenerationDependencies === undefined) { + this.codeGenerationDependencies = []; } - return changed; + this.codeGenerationDependencies.push(codeGenerationDependency); } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, when something changed + * Removes all dependencies and blocks + * @returns {void} */ - setUsedWithoutInfo(runtime) { - let changed = false; - for (const exportInfo of this._exports.values()) { - if (exportInfo.setUsedWithoutInfo(runtime)) { - changed = true; - } + clearDependenciesAndBlocks() { + if (this.presentationalDependencies !== undefined) { + this.presentationalDependencies.length = 0; } - if (this._redirectTo !== undefined) { - if (this._redirectTo.setUsedWithoutInfo(runtime)) { - changed = true; - } - } else { - if (this._otherExportsInfo.setUsed(UsageState.NoInfo, runtime)) { - changed = true; - } - if (this._otherExportsInfo.canMangleUse !== false) { - this._otherExportsInfo.canMangleUse = false; - changed = true; - } + if (this.codeGenerationDependencies !== undefined) { + this.codeGenerationDependencies.length = 0; } - return changed; + super.clearDependenciesAndBlocks(); } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, when something changed + * @param {WebpackError} warning the warning + * @returns {void} */ - setAllKnownExportsUsed(runtime) { - let changed = false; - for (const exportInfo of this._exports.values()) { - if (!exportInfo.provided) continue; - if (exportInfo.setUsed(UsageState.Used, runtime)) { - changed = true; - } + addWarning(warning) { + if (this._warnings === undefined) { + this._warnings = []; } - return changed; + this._warnings.push(warning); } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, when something changed + * @returns {Iterable | undefined} list of warnings if any */ - setUsedForSideEffectsOnly(runtime) { - return this._sideEffectsOnlyInfo.setUsedConditionally( - used => used === UsageState.Unused, - UsageState.Used, - runtime - ); + getWarnings() { + return this._warnings; } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, when the module exports are used in any way + * @returns {number} number of warnings */ - isUsed(runtime) { - if (this._redirectTo !== undefined) { - if (this._redirectTo.isUsed(runtime)) { - return true; - } - } else { - if (this._otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { - return true; - } - } - for (const exportInfo of this._exports.values()) { - if (exportInfo.getUsed(runtime) !== UsageState.Unused) { - return true; - } - } - return false; + getNumberOfWarnings() { + return this._warnings !== undefined ? this._warnings.length : 0; } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true, when the module is used in any way + * @param {WebpackError} error the error + * @returns {void} */ - isModuleUsed(runtime) { - if (this.isUsed(runtime)) return true; - if (this._sideEffectsOnlyInfo.getUsed(runtime) !== UsageState.Unused) - return true; - return false; + addError(error) { + if (this._errors === undefined) { + this._errors = []; + } + this._errors.push(error); } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {SortableSet | boolean | null} set of used exports, or true (when namespace object is used), or false (when unused), or null (when unknown) + * @returns {Iterable | undefined} list of errors if any */ - getUsedExports(runtime) { - if (!this._redirectTo !== undefined) { - switch (this._otherExportsInfo.getUsed(runtime)) { - case UsageState.NoInfo: - return null; - case UsageState.Unknown: - case UsageState.OnlyPropertiesUsed: - case UsageState.Used: - return true; - } - } - const array = []; - if (!this._exportsAreOrdered) this._sortExports(); - for (const exportInfo of this._exports.values()) { - switch (exportInfo.getUsed(runtime)) { - case UsageState.NoInfo: - return null; - case UsageState.Unknown: - return true; - case UsageState.OnlyPropertiesUsed: - case UsageState.Used: - array.push(exportInfo.name); - } - } - if (this._redirectTo !== undefined) { - const inner = this._redirectTo.getUsedExports(runtime); - if (inner === null) return null; - if (inner === true) return true; - if (inner !== false) { - for (const item of inner) { - array.push(item); - } - } - } - if (array.length === 0) { - switch (this._sideEffectsOnlyInfo.getUsed(runtime)) { - case UsageState.NoInfo: - return null; - case UsageState.Unused: - return false; - } - } - return new SortableSet(array); + getErrors() { + return this._errors; } /** - * @returns {null | true | string[]} list of exports when known + * @returns {number} number of errors */ - getProvidedExports() { - if (!this._redirectTo !== undefined) { - switch (this._otherExportsInfo.provided) { - case undefined: - return null; - case null: - return true; - case true: - return true; - } - } - const array = []; - if (!this._exportsAreOrdered) this._sortExports(); - for (const exportInfo of this._exports.values()) { - switch (exportInfo.provided) { - case undefined: - return null; - case null: - return true; - case true: - array.push(exportInfo.name); - } - } - if (this._redirectTo !== undefined) { - const inner = this._redirectTo.getProvidedExports(); - if (inner === null) return null; - if (inner === true) return true; - for (const item of inner) { - if (!array.includes(item)) { - array.push(item); - } - } - } - return array; + getNumberOfErrors() { + return this._errors !== undefined ? this._errors.length : 0; } /** - * @param {RuntimeSpec} runtime the runtime - * @returns {ExportInfo[]} exports that are relevant (not unused and potential provided) + * removes all warnings and errors + * @returns {void} */ - getRelevantExports(runtime) { - const list = []; - for (const exportInfo of this._exports.values()) { - const used = exportInfo.getUsed(runtime); - if (used === UsageState.Unused) continue; - if (exportInfo.provided === false) continue; - list.push(exportInfo); - } - if (this._redirectTo !== undefined) { - for (const exportInfo of this._redirectTo.getRelevantExports(runtime)) { - if (!this._exports.has(exportInfo.name)) list.push(exportInfo); - } + clearWarningsAndErrors() { + if (this._warnings !== undefined) { + this._warnings.length = 0; } - if ( - this._otherExportsInfo.provided !== false && - this._otherExportsInfo.getUsed(runtime) !== UsageState.Unused - ) { - list.push(this._otherExportsInfo); + if (this._errors !== undefined) { + this._errors.length = 0; } - return list; } /** - * @param {string | string[]} name the name of the export - * @returns {boolean | undefined | null} if the export is provided + * @param {ModuleGraph} moduleGraph the module graph + * @returns {boolean} true, if the module is optional */ - isExportProvided(name) { - if (Array.isArray(name)) { - const info = this.getReadOnlyExportInfo(name[0]); - if (info.exportsInfo && name.length > 1) { - return info.exportsInfo.isExportProvided(name.slice(1)); + isOptional(moduleGraph) { + let hasConnections = false; + for (const r of moduleGraph.getIncomingConnections(this)) { + if ( + !r.dependency || + !r.dependency.optional || + !r.isTargetActive(undefined) + ) { + return false; } - return info.provided; + hasConnections = true; } - const info = this.getReadOnlyExportInfo(name); - return info.provided; + return hasConnections; } /** - * @param {RuntimeSpec} runtime runtime - * @returns {string} key representing the usage + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk} chunk a chunk + * @param {Chunk=} ignoreChunk chunk to be ignored + * @returns {boolean} true, if the module is accessible from "chunk" when ignoring "ignoreChunk" */ - getUsageKey(runtime) { - const key = []; - if (this._redirectTo !== undefined) { - key.push(this._redirectTo.getUsageKey(runtime)); - } else { - key.push(this._otherExportsInfo.getUsed(runtime)); - } - key.push(this._sideEffectsOnlyInfo.getUsed(runtime)); - for (const exportInfo of this.orderedOwnedExports) { - key.push(exportInfo.getUsed(runtime)); + isAccessibleInChunk(chunkGraph, chunk, ignoreChunk) { + // Check if module is accessible in ALL chunk groups + for (const chunkGroup of chunk.groupsIterable) { + if (!this.isAccessibleInChunkGroup(chunkGraph, chunkGroup)) return false; } - return key.join("|"); + return true; } /** - * @param {RuntimeSpec} runtimeA first runtime - * @param {RuntimeSpec} runtimeB second runtime - * @returns {boolean} true, when equally used + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {ChunkGroup} chunkGroup a chunk group + * @param {Chunk=} ignoreChunk chunk to be ignored + * @returns {boolean} true, if the module is accessible from "chunkGroup" when ignoring "ignoreChunk" */ - isEquallyUsed(runtimeA, runtimeB) { - if (this._redirectTo !== undefined) { - if (!this._redirectTo.isEquallyUsed(runtimeA, runtimeB)) return false; - } else { - if ( - this._otherExportsInfo.getUsed(runtimeA) !== - this._otherExportsInfo.getUsed(runtimeB) - ) { - return false; + isAccessibleInChunkGroup(chunkGraph, chunkGroup, ignoreChunk) { + const queue = new Set([chunkGroup]); + + // Check if module is accessible from all items of the queue + queueFor: for (const cg of queue) { + // 1. If module is in one of the chunks of the group we can continue checking the next items + // because it's accessible. + for (const chunk of cg.chunks) { + if (chunk !== ignoreChunk && chunkGraph.isModuleInChunk(this, chunk)) + continue queueFor; } + // 2. If the chunk group is initial, we can break here because it's not accessible. + if (chunkGroup.isInitial()) return false; + // 3. Enqueue all parents because it must be accessible from ALL parents + for (const parent of chunkGroup.parentsIterable) queue.add(parent); } - if ( - this._sideEffectsOnlyInfo.getUsed(runtimeA) !== - this._sideEffectsOnlyInfo.getUsed(runtimeB) - ) { - return false; - } - for (const exportInfo of this.ownedExports) { - if (exportInfo.getUsed(runtimeA) !== exportInfo.getUsed(runtimeB)) - return false; - } + // When we processed through the whole list and we didn't bailout, the module is accessible return true; } /** - * @param {string | string[]} name export name - * @param {RuntimeSpec} runtime check usage for this runtime only - * @returns {UsageStateType} usage status + * @param {Chunk} chunk a chunk + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {boolean} true, if the module has any reason why "chunk" should be included */ - getUsed(name, runtime) { - if (Array.isArray(name)) { - if (name.length === 0) return this.otherExportsInfo.getUsed(runtime); - let info = this.getReadOnlyExportInfo(name[0]); - if (info.exportsInfo && name.length > 1) { - return info.exportsInfo.getUsed(name.slice(1), runtime); + hasReasonForChunk(chunk, moduleGraph, chunkGraph) { + // check for each reason if we need the chunk + for (const [ + fromModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(this)) { + if (!connections.some(c => c.isTargetActive(chunk.runtime))) continue; + for (const originChunk of chunkGraph.getModuleChunksIterable( + fromModule + )) { + // return true if module this is not reachable from originChunk when ignoring chunk + if (!this.isAccessibleInChunk(chunkGraph, originChunk, chunk)) + return true; } - return info.getUsed(runtime); } - let info = this.getReadOnlyExportInfo(name); - return info.getUsed(runtime); + return false; } /** - * @param {string | string[]} name the export name - * @param {RuntimeSpec} runtime check usage for this runtime only - * @returns {string | string[] | false} the used name + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @returns {boolean} true if at least one other module depends on this module */ - getUsedName(name, runtime) { - if (Array.isArray(name)) { - // TODO improve this - if (name.length === 0) { - if (!this.isUsed(runtime)) return false; - return name; - } - let info = this.getReadOnlyExportInfo(name[0]); - const x = info.getUsedName(name[0], runtime); - if (x === false) return false; - const arr = x === name[0] && name.length === 1 ? name : [x]; - if (name.length === 1) { - return arr; - } - if ( - info.exportsInfo && - info.getUsed(runtime) === UsageState.OnlyPropertiesUsed - ) { - const nested = info.exportsInfo.getUsedName(name.slice(1), runtime); - if (!nested) return false; - return arr.concat(nested); - } else { - return arr.concat(name.slice(1)); - } - } else { - let info = this.getReadOnlyExportInfo(name); - const usedName = info.getUsedName(name, runtime); - return usedName; + hasReasons(moduleGraph, runtime) { + for (const c of moduleGraph.getIncomingConnections(this)) { + if (c.isTargetActive(runtime)) return true; } + return false; } /** - * @param {Hash} hash the hash - * @param {RuntimeSpec} runtime the runtime - * @returns {void} + * @returns {string} for debugging */ - updateHash(hash, runtime) { - this._updateHash(hash, runtime, new Set()); + toString() { + return `Module[${this.debugId}: ${this.identifier()}]`; } /** - * @param {Hash} hash the hash - * @param {RuntimeSpec} runtime the runtime - * @param {Set} alreadyVisitedExportsInfo for circular references + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild * @returns {void} */ - _updateHash(hash, runtime, alreadyVisitedExportsInfo) { - const set = new Set(alreadyVisitedExportsInfo); - set.add(this); - for (const exportInfo of this.orderedExports) { - if (exportInfo.hasInfo(this._otherExportsInfo, runtime)) { - exportInfo._updateHash(hash, runtime, set); - } - } - this._sideEffectsOnlyInfo._updateHash(hash, runtime, set); - this._otherExportsInfo._updateHash(hash, runtime, set); - if (this._redirectTo !== undefined) { - this._redirectTo._updateHash(hash, runtime, set); - } + needBuild(context, callback) { + callback( + null, + !this.buildMeta || + this.needRebuild === Module.prototype.needRebuild || + deprecatedNeedRebuild(this, context) + ); } - getRestoreProvidedData() { - const otherProvided = this._otherExportsInfo.provided; - const otherCanMangleProvide = this._otherExportsInfo.canMangleProvide; - const otherTerminalBinding = this._otherExportsInfo.terminalBinding; - const exports = []; - for (const exportInfo of this.orderedExports) { - if ( - exportInfo.provided !== otherProvided || - exportInfo.canMangleProvide !== otherCanMangleProvide || - exportInfo.terminalBinding !== otherTerminalBinding || - exportInfo.exportsInfoOwned - ) { - exports.push({ - name: exportInfo.name, - provided: exportInfo.provided, - canMangleProvide: exportInfo.canMangleProvide, - terminalBinding: exportInfo.terminalBinding, - exportsInfo: exportInfo.exportsInfoOwned - ? exportInfo.exportsInfo.getRestoreProvidedData() - : undefined - }); - } - } - return new RestoreProvidedData( - exports, - otherProvided, - otherCanMangleProvide, - otherTerminalBinding - ); + /** + * @deprecated Use needBuild instead + * @param {Map} fileTimestamps timestamps of files + * @param {Map} contextTimestamps timestamps of directories + * @returns {boolean} true, if the module needs a rebuild + */ + needRebuild(fileTimestamps, contextTimestamps) { + return true; } - restoreProvided({ - otherProvided, - otherCanMangleProvide, - otherTerminalBinding, - exports - }) { - let wasEmpty = true; - for (const exportInfo of this._exports.values()) { - wasEmpty = false; - exportInfo.provided = otherProvided; - exportInfo.canMangleProvide = otherCanMangleProvide; - exportInfo.terminalBinding = otherTerminalBinding; + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash( + hash, + context = { + chunkGraph: ChunkGraph.getChunkGraphForModule( + this, + "Module.updateHash", + "DEP_WEBPACK_MODULE_UPDATE_HASH" + ), + runtime: undefined } - this._otherExportsInfo.provided = otherProvided; - this._otherExportsInfo.canMangleProvide = otherCanMangleProvide; - this._otherExportsInfo.terminalBinding = otherTerminalBinding; - for (const exp of exports) { - const exportInfo = this.getExportInfo(exp.name); - exportInfo.provided = exp.provided; - exportInfo.canMangleProvide = exp.canMangleProvide; - exportInfo.terminalBinding = exp.terminalBinding; - if (exp.exportsInfo) { - const exportsInfo = exportInfo.createNestedExportsInfo(); - exportsInfo.restoreProvided(exp.exportsInfo); + ) { + const { chunkGraph, runtime } = context; + hash.update(chunkGraph.getModuleGraphHash(this, runtime)); + if (this.presentationalDependencies !== undefined) { + for (const dep of this.presentationalDependencies) { + dep.updateHash(hash, context); } } - if (wasEmpty) this._exportsAreOrdered = true; + super.updateHash(hash, context); } -} -class ExportInfo { /** - * @param {string} name the original name of the export - * @param {ExportInfo=} initFrom init values from this ExportInfo + * @returns {void} */ - constructor(name, initFrom) { - /** @type {string} */ - this.name = name; - /** @private @type {string | null} */ - this._usedName = initFrom ? initFrom._usedName : null; - /** @private @type {UsageStateType} */ - this._globalUsed = initFrom ? initFrom._globalUsed : undefined; - /** @private @type {Map} */ - this._usedInRuntime = - initFrom && initFrom._usedInRuntime - ? new Map(initFrom._usedInRuntime) - : undefined; - /** @private @type {boolean} */ - this._hasUseInRuntimeInfo = initFrom - ? initFrom._hasUseInRuntimeInfo - : false; - /** - * true: it is provided - * false: it is not provided - * null: only the runtime knows if it is provided - * undefined: it was not determined if it is provided - * @type {boolean | null | undefined} - */ - this.provided = initFrom ? initFrom.provided : undefined; - /** - * is the export a terminal binding that should be checked for export star conflicts - * @type {boolean} - */ - this.terminalBinding = initFrom ? initFrom.terminalBinding : false; - /** - * true: it can be mangled - * false: is can not be mangled - * undefined: it was not determined if it can be mangled - * @type {boolean | undefined} - */ - this.canMangleProvide = initFrom ? initFrom.canMangleProvide : undefined; - /** - * true: it can be mangled - * false: is can not be mangled - * undefined: it was not determined if it can be mangled - * @type {boolean | undefined} - */ - this.canMangleUse = initFrom ? initFrom.canMangleUse : undefined; - /** @type {boolean} */ - this.exportsInfoOwned = false; - /** @type {ExportsInfo=} */ - this.exportsInfo = undefined; - /** @type {Map=} */ - this._target = undefined; - if (initFrom && initFrom._target) { - this._target = new Map(); - for (const [key, value] of initFrom._target) { - this._target.set(key, { - connection: value.connection, - export: value.export || [name], - priority: value.priority - }); - } - } - /** @type {Map=} */ - this._maxTarget = undefined; + invalidateBuild() { + // should be overridden to support this feature } - // TODO webpack 5 remove - /** @private */ - get used() { - throw new Error("REMOVED"); + /* istanbul ignore next */ + /** + * @abstract + * @returns {string} a unique identifier of the module + */ + identifier() { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } - /** @private */ - get usedName() { - throw new Error("REMOVED"); + + /* istanbul ignore next */ + /** + * @abstract + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } + + /* istanbul ignore next */ /** - * @private - * @param {*} v v + * @abstract + * @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} */ - set used(v) { - throw new Error("REMOVED"); + build(options, compilation, resolver, fs, callback) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } + /** - * @private - * @param {*} v v + * @abstract + * @returns {Set} types available (do not mutate) */ - set usedName(v) { - throw new Error("REMOVED"); + getSourceTypes() { + // Better override this method to return the correct types + if (this.source === Module.prototype.source) { + return DEFAULT_TYPES_UNKNOWN; + } else { + return DEFAULT_TYPES_JS; + } } - get canMangle() { - switch (this.canMangleProvide) { - case undefined: - return this.canMangleUse === false ? false : undefined; - case false: - return false; - case true: - switch (this.canMangleUse) { - case undefined: - return undefined; - case false: - return false; - case true: - return true; - } + /** + * @abstract + * @deprecated Use codeGeneration() instead + * @param {DependencyTemplates} dependencyTemplates the dependency templates + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {string=} type the type of source that should be generated + * @returns {Source} generated source + */ + source(dependencyTemplates, runtimeTemplate, type = "javascript") { + if (this.codeGeneration === Module.prototype.codeGeneration) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } - throw new Error( - `Unexpected flags for canMangle ${this.canMangleProvide} ${this.canMangleUse}` + const chunkGraph = ChunkGraph.getChunkGraphForModule( + this, + "Module.source() is deprecated. Use Compilation.codeGenerationResults.getSource(module, runtime, type) instead", + "DEP_WEBPACK_MODULE_SOURCE" ); + /** @type {CodeGenerationContext} */ + const codeGenContext = { + dependencyTemplates, + runtimeTemplate, + moduleGraph: chunkGraph.moduleGraph, + chunkGraph, + runtime: undefined, + codeGenerationResults: undefined + }; + const sources = this.codeGeneration(codeGenContext).sources; + return type ? sources.get(type) : sources.get(first(this.getSourceTypes())); } + /* istanbul ignore next */ /** - * @param {RuntimeSpec} runtime only apply to this runtime - * @returns {boolean} true, when something changed + * @abstract + * @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) */ - setUsedInUnknownWay(runtime) { - let changed = false; - if ( - this.setUsedConditionally( - used => used < UsageState.Unknown, - UsageState.Unknown, - runtime - ) - ) { - changed = true; - } - if (this.canMangleUse !== false) { - this.canMangleUse = false; - changed = true; - } - return changed; + size(type) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } /** - * @param {RuntimeSpec} runtime only apply to this runtime - * @returns {boolean} true, when something changed + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion */ - setUsedWithoutInfo(runtime) { - let changed = false; - if (this.setUsed(UsageState.NoInfo, runtime)) { - changed = true; - } - if (this.canMangleUse !== false) { - this.canMangleUse = false; - changed = true; - } - return changed; + libIdent(options) { + return null; } - setHasUseInfo() { - if (!this._hasUseInRuntimeInfo) { - this._hasUseInRuntimeInfo = true; - } - if (this.canMangleUse === undefined) { - this.canMangleUse = true; - } - if (this.exportsInfoOwned) { - this.exportsInfo.setHasUseInfo(); - } + /** + * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + */ + nameForCondition() { + return null; } /** - * @param {function(UsageStateType): boolean} condition compare with old value - * @param {UsageStateType} newValue set when condition is true - * @param {RuntimeSpec} runtime only apply to this runtime - * @returns {boolean} true when something has changed + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated */ - setUsedConditionally(condition, newValue, runtime) { - if (runtime === undefined) { - if (this._globalUsed === undefined) { - this._globalUsed = newValue; - return true; - } else { - if (this._globalUsed !== newValue && condition(this._globalUsed)) { - this._globalUsed = newValue; - return true; - } - } - } else if (this._usedInRuntime === undefined) { - if (newValue !== UsageState.Unused && condition(UsageState.Unused)) { - this._usedInRuntime = new Map(); - forEachRuntime(runtime, runtime => - this._usedInRuntime.set(runtime, newValue) - ); - return true; - } - } else { - let changed = false; - forEachRuntime(runtime, runtime => { - /** @type {UsageStateType} */ - let oldValue = this._usedInRuntime.get(runtime); - if (oldValue === undefined) oldValue = UsageState.Unused; - if (newValue !== oldValue && condition(oldValue)) { - if (newValue === UsageState.Unused) { - this._usedInRuntime.delete(runtime); - } else { - this._usedInRuntime.set(runtime, newValue); - } - changed = true; - } - }); - if (changed) { - if (this._usedInRuntime.size === 0) this._usedInRuntime = undefined; - return true; - } - } - return false; + getConcatenationBailoutReason(context) { + return `Module Concatenation is not implemented for ${this.constructor.name}`; } /** - * @param {UsageStateType} newValue new value of the used state - * @param {RuntimeSpec} runtime only apply to this runtime - * @returns {boolean} true when something has changed + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only */ - setUsed(newValue, runtime) { - if (runtime === undefined) { - if (this._globalUsed !== newValue) { - this._globalUsed = newValue; - return true; - } - } else if (this._usedInRuntime === undefined) { - if (newValue !== UsageState.Unused) { - this._usedInRuntime = new Map(); - forEachRuntime(runtime, runtime => - this._usedInRuntime.set(runtime, newValue) + getSideEffectsConnectionState(moduleGraph) { + return true; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration(context) { + // Best override this method + const sources = new Map(); + for (const type of this.getSourceTypes()) { + if (type !== "unknown") { + sources.set( + type, + this.source( + context.dependencyTemplates, + context.runtimeTemplate, + type + ) ); - return true; - } - } else { - let changed = false; - forEachRuntime(runtime, runtime => { - /** @type {UsageStateType} */ - let oldValue = this._usedInRuntime.get(runtime); - if (oldValue === undefined) oldValue = UsageState.Unused; - if (newValue !== oldValue) { - if (newValue === UsageState.Unused) { - this._usedInRuntime.delete(runtime); - } else { - this._usedInRuntime.set(runtime, newValue); - } - changed = true; - } - }); - if (changed) { - if (this._usedInRuntime.size === 0) this._usedInRuntime = undefined; - return true; } } - return false; + return { + sources, + runtimeRequirements: new Set([ + RuntimeGlobals.module, + RuntimeGlobals.exports, + RuntimeGlobals.require + ]) + }; } /** - * @param {any} key the key - * @returns {boolean} true, if something has changed + * @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 */ - unsetTarget(key) { - if (!this._target) return false; - if (this._target.delete(key)) { - this._maxTarget = undefined; - return true; - } - return false; + chunkCondition(chunk, compilation) { + return true; + } + + hasChunkCondition() { + return this.chunkCondition !== Module.prototype.chunkCondition; } /** - * @param {any} key the key - * @param {ModuleGraphConnection} connection the target module if a single one - * @param {string[]=} exportName the exported name - * @param {number=} priority priority - * @returns {boolean} true, if something has changed + * 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} */ - setTarget(key, connection, exportName, priority = 0) { - if (exportName) exportName = [...exportName]; - if (!this._target) { - this._target = new Map(); - this._target.set(key, { connection, export: exportName, priority }); - return true; - } - const oldTarget = this._target.get(key); - if (!oldTarget) { - if (oldTarget === null && !connection) return false; - this._target.set(key, { connection, export: exportName, priority }); - this._maxTarget = undefined; - return true; - } - if ( - oldTarget.connection !== connection || - oldTarget.priority !== priority || - (exportName - ? !oldTarget.export || !equals(oldTarget.export, exportName) - : oldTarget.export) - ) { - oldTarget.connection = connection; - oldTarget.export = exportName; - oldTarget.priority = priority; - this._maxTarget = undefined; - return true; - } - return false; + updateCacheModule(module) { + this.type = module.type; + this.layer = module.layer; + this.context = module.context; + this.factoryMeta = module.factoryMeta; + this.resolveOptions = module.resolveOptions; } /** - * @param {RuntimeSpec} runtime for this runtime - * @returns {UsageStateType} usage state + * Module should be unsafe cached. Get data that's needed for that. + * This data will be passed to restoreFromUnsafeCache later. + * @returns {object} cached data */ - getUsed(runtime) { - if (!this._hasUseInRuntimeInfo) return UsageState.NoInfo; - if (this._globalUsed !== undefined) return this._globalUsed; - if (this._usedInRuntime === undefined) { - return UsageState.Unused; - } else if (typeof runtime === "string") { - const value = this._usedInRuntime.get(runtime); - return value === undefined ? UsageState.Unused : value; - } else if (runtime === undefined) { - /** @type {UsageStateType} */ - let max = UsageState.Unused; - for (const value of this._usedInRuntime.values()) { - if (value === UsageState.Used) { - return UsageState.Used; - } - if (max < value) max = value; - } - return max; - } else { - /** @type {UsageStateType} */ - let max = UsageState.Unused; - for (const item of runtime) { - const value = this._usedInRuntime.get(item); - if (value !== undefined) { - if (value === UsageState.Used) { - return UsageState.Used; - } - if (max < value) max = value; - } - } - return max; - } + getUnsafeCacheData() { + return { + factoryMeta: this.factoryMeta, + resolveOptions: this.resolveOptions + }; } /** - * get used name - * @param {string | undefined} fallbackName fallback name for used exports with no name - * @param {RuntimeSpec} runtime check usage for this runtime only - * @returns {string | false} used name + * restore unsafe cache data + * @param {object} unsafeCacheData data from getUnsafeCacheData + * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching */ - getUsedName(fallbackName, runtime) { - if (this._hasUseInRuntimeInfo) { - if (this._globalUsed !== undefined) { - if (this._globalUsed === UsageState.Unused) return false; - } else { - if (this._usedInRuntime === undefined) return false; - if (typeof runtime === "string") { - if (!this._usedInRuntime.has(runtime)) { - return false; - } - } else if (runtime !== undefined) { - if ( - Array.from(runtime).every( - runtime => !this._usedInRuntime.has(runtime) - ) - ) { - return false; - } - } - } - } - if (this._usedName !== null) return this._usedName; - return this.name || fallbackName; + _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { + this.factoryMeta = unsafeCacheData.factoryMeta; + this.resolveOptions = unsafeCacheData.resolveOptions; } /** - * @returns {boolean} true, when a mangled name of this export is set + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. */ - hasUsedName() { - return this._usedName !== null; + cleanupForCache() { + this.factoryMeta = undefined; + this.resolveOptions = undefined; } /** - * Sets the mangled name of this export - * @param {string} name the new name - * @returns {void} + * @returns {Source | null} the original source for the module before webpack transformation */ - setUsedName(name) { - this._usedName = name; + originalSource() { + return null; } /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target - * @returns {ExportInfo | ExportsInfo | undefined} the terminal binding export(s) info if known + * @param {LazySet} fileDependencies set where file dependencies are added to + * @param {LazySet} contextDependencies set where context dependencies are added to + * @param {LazySet} missingDependencies set where missing dependencies are added to + * @param {LazySet} buildDependencies set where build dependencies are added to */ - getTerminalBinding(moduleGraph, resolveTargetFilter = RETURNS_TRUE) { - if (this.terminalBinding) return this; - const target = this.getTarget(moduleGraph, resolveTargetFilter); - if (!target) return undefined; - const exportsInfo = moduleGraph.getExportsInfo(target.module); - if (!target.export) return exportsInfo; - return exportsInfo.getReadOnlyExportInfoRecursive(target.export); - } + addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ) {} - isReexport() { - return !this.terminalBinding && this._target && this._target.size > 0; + serialize(context) { + const { write } = context; + write(this.type); + write(this.layer); + write(this.context); + write(this.resolveOptions); + write(this.factoryMeta); + write(this.useSourceMap); + write(this.useSimpleSourceMap); + write( + this._warnings !== undefined && this._warnings.length === 0 + ? undefined + : this._warnings + ); + write( + this._errors !== undefined && this._errors.length === 0 + ? undefined + : this._errors + ); + write(this.buildMeta); + write(this.buildInfo); + write(this.presentationalDependencies); + write(this.codeGenerationDependencies); + super.serialize(context); } - _getMaxTarget() { - if (this._maxTarget !== undefined) return this._maxTarget; - if (this._target.size <= 1) return (this._maxTarget = this._target); - let maxPriority = -Infinity; - let minPriority = Infinity; - for (const { priority } of this._target.values()) { - if (maxPriority < priority) maxPriority = priority; - if (minPriority > priority) minPriority = priority; - } - // This should be very common - if (maxPriority === minPriority) return (this._maxTarget = this._target); - - // This is an edge case - const map = new Map(); - for (const [key, value] of this._target) { - if (maxPriority === value.priority) { - map.set(key, value); - } - } - this._maxTarget = map; - return map; + deserialize(context) { + const { read } = context; + this.type = read(); + this.layer = read(); + this.context = read(); + this.resolveOptions = read(); + this.factoryMeta = read(); + this.useSourceMap = read(); + this.useSimpleSourceMap = read(); + this._warnings = read(); + this._errors = read(); + this.buildMeta = read(); + this.buildInfo = read(); + this.presentationalDependencies = read(); + this.codeGenerationDependencies = read(); + super.deserialize(context); } +} - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {function(Module): boolean} validTargetModuleFilter a valid target module - * @returns {{ module: Module, export: string[] | undefined } | undefined | false} the target, undefined when there is no target, false when no target is valid - */ - findTarget(moduleGraph, validTargetModuleFilter) { - return this._findTarget(moduleGraph, validTargetModuleFilter, new Set()); - } +makeSerializable(Module, "webpack/lib/Module"); - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {function(Module): boolean} validTargetModuleFilter a valid target module - * @param {Set | undefined} alreadyVisited set of already visited export info to avoid circular references - * @returns {{ module: Module, export: string[] | undefined } | undefined | false} the target, undefined when there is no target, false when no target is valid - */ - _findTarget(moduleGraph, validTargetModuleFilter, alreadyVisited) { - if (!this._target || this._target.size === 0) return undefined; - let rawTarget = this._getMaxTarget().values().next().value; - if (!rawTarget) return undefined; - /** @type {{ module: Module, export: string[] | undefined }} */ - let target = { - module: rawTarget.connection.module, - export: rawTarget.export - }; - for (;;) { - if (validTargetModuleFilter(target.module)) return target; - const exportsInfo = moduleGraph.getExportsInfo(target.module); - const exportInfo = exportsInfo.getExportInfo(target.export[0]); - if (alreadyVisited.has(exportInfo)) return null; - const newTarget = exportInfo._findTarget( - moduleGraph, - validTargetModuleFilter, - alreadyVisited - ); - if (!newTarget) return false; - if (target.export.length === 1) { - target = newTarget; - } else { - target = { - module: newTarget.module, - export: newTarget.export - ? newTarget.export.concat(target.export.slice(1)) - : target.export.slice(1) - }; - } - } +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "hasEqualsChunks", { + get() { + throw new Error( + "Module.hasEqualsChunks was renamed (use hasEqualChunks instead)" + ); } +}); - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target - * @returns {{ module: Module, export: string[] | undefined } | undefined} the target - */ - getTarget(moduleGraph, resolveTargetFilter = RETURNS_TRUE) { - const result = this._getTarget(moduleGraph, resolveTargetFilter, undefined); - if (result === CIRCULAR) return undefined; - return result; +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "isUsed", { + get() { + throw new Error( + "Module.isUsed was renamed (use getUsedName, isExportUsed or isModuleUsed instead)" + ); } +}); - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {function({ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target - * @param {Set | undefined} alreadyVisited set of already visited export info to avoid circular references - * @returns {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined } | CIRCULAR | undefined} the target - */ - _getTarget(moduleGraph, resolveTargetFilter, alreadyVisited) { +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "errors", { + get: util.deprecate( /** - * @param {{ connection: ModuleGraphConnection, export: string[] | undefined } | null} inputTarget unresolved target - * @param {Set} alreadyVisited set of already visited export info to avoid circular references - * @returns {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined } | CIRCULAR | null} resolved target + * @this {Module} + * @returns {WebpackError[]} array */ - const resolveTarget = (inputTarget, alreadyVisited) => { - if (!inputTarget) return null; - if (!inputTarget.export) { - return { - module: inputTarget.connection.module, - connection: inputTarget.connection, - export: undefined - }; + function () { + if (this._errors === undefined) { + this._errors = []; } - /** @type {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }} */ - let target = { - module: inputTarget.connection.module, - connection: inputTarget.connection, - export: inputTarget.export - }; - if (!resolveTargetFilter(target)) return target; - let alreadyVisitedOwned = false; - for (;;) { - const exportsInfo = moduleGraph.getExportsInfo(target.module); - const exportInfo = exportsInfo.getExportInfo(target.export[0]); - if (!exportInfo) return target; - if (alreadyVisited.has(exportInfo)) return CIRCULAR; - const newTarget = exportInfo._getTarget( - moduleGraph, - resolveTargetFilter, - alreadyVisited - ); - if (newTarget === CIRCULAR) return CIRCULAR; - if (!newTarget) return target; - if (target.export.length === 1) { - target = newTarget; - if (!target.export) return target; - } else { - target = { - module: newTarget.module, - connection: newTarget.connection, - export: newTarget.export - ? newTarget.export.concat(target.export.slice(1)) - : target.export.slice(1) - }; - } - if (!resolveTargetFilter(target)) return target; - if (!alreadyVisitedOwned) { - alreadyVisited = new Set(alreadyVisited); - alreadyVisitedOwned = true; - } - alreadyVisited.add(exportInfo); + return this._errors; + }, + "Module.errors was removed (use getErrors instead)", + "DEP_WEBPACK_MODULE_ERRORS" + ) +}); + +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "warnings", { + get: util.deprecate( + /** + * @this {Module} + * @returns {WebpackError[]} array + */ + function () { + if (this._warnings === undefined) { + this._warnings = []; } - }; + return this._warnings; + }, + "Module.warnings was removed (use getWarnings instead)", + "DEP_WEBPACK_MODULE_WARNINGS" + ) +}); - if (!this._target || this._target.size === 0) return undefined; - if (alreadyVisited && alreadyVisited.has(this)) return CIRCULAR; - const newAlreadyVisited = new Set(alreadyVisited); - newAlreadyVisited.add(this); - const values = this._getMaxTarget().values(); - const target = resolveTarget(values.next().value, newAlreadyVisited); - if (target === CIRCULAR) return CIRCULAR; - if (target === null) return undefined; - let result = values.next(); - while (!result.done) { - const t = resolveTarget(result.value, newAlreadyVisited); - if (t === CIRCULAR) return CIRCULAR; - if (t === null) return undefined; - if (t.module !== target.module) return undefined; - if (!t.export !== !target.export) return undefined; - if (target.export && !equals(t.export, target.export)) return undefined; - result = values.next(); - } - return target; +// TODO remove in webpack 6 +Object.defineProperty(Module.prototype, "used", { + get() { + throw new Error( + "Module.used was refactored (use ModuleGraph.getUsedExports instead)" + ); + }, + set(value) { + throw new Error( + "Module.used was refactored (use ModuleGraph.setUsedExports instead)" + ); } +}); + +module.exports = Module; + + +/***/ }), + +/***/ 21305: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { cutOffLoaderExecution } = __webpack_require__(59985); +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); +class ModuleBuildError extends WebpackError { /** - * Move the target forward as long resolveTargetFilter is fulfilled - * @param {ModuleGraph} moduleGraph the module graph - * @param {function({ module: Module, export: string[] | undefined }): boolean} resolveTargetFilter filter function to further resolve target - * @param {function({ module: Module, export: string[] | undefined }): ModuleGraphConnection=} updateOriginalConnection updates the original connection instead of using the target connection - * @returns {{ module: Module, export: string[] | undefined } | undefined} the resolved target when moved + * @param {string | Error&any} err error thrown + * @param {{from?: string|null}} info additional info */ - moveTarget(moduleGraph, resolveTargetFilter, updateOriginalConnection) { - const target = this._getTarget(moduleGraph, resolveTargetFilter, undefined); - if (target === CIRCULAR) return undefined; - if (!target) return undefined; - const originalTarget = this._getMaxTarget().values().next().value; - if ( - originalTarget.connection === target.connection && - originalTarget.export === target.export - ) { - return undefined; + constructor(err, { from = null } = {}) { + let message = "Module build failed"; + let details = undefined; + + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; } - this._target.clear(); - this._target.set(undefined, { - connection: updateOriginalConnection - ? updateOriginalConnection(target) - : target.connection, - export: target.export, - priority: 0 - }); - return target; - } - createNestedExportsInfo() { - if (this.exportsInfoOwned) return this.exportsInfo; - this.exportsInfoOwned = true; - const oldExportsInfo = this.exportsInfo; - this.exportsInfo = new ExportsInfo(); - this.exportsInfo.setHasProvideInfo(); - if (oldExportsInfo) { - this.exportsInfo.setRedirectNamedTo(oldExportsInfo); + 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); } - return this.exportsInfo; - } - getNestedExportsInfo() { - return this.exportsInfo; - } + super(message); - hasInfo(baseInfo, runtime) { - return ( - (this._usedName && this._usedName !== this.name) || - this.provided || - this.terminalBinding || - this.getUsed(runtime) !== baseInfo.getUsed(runtime) - ); + this.name = "ModuleBuildError"; + this.details = details; + this.error = err; } - updateHash(hash, runtime) { - this._updateHash(hash, runtime, new Set()); - } + serialize(context) { + const { write } = context; - _updateHash(hash, runtime, alreadyVisitedExportsInfo) { - hash.update( - `${this._usedName || this.name}${this.getUsed(runtime)}${this.provided}${ - this.terminalBinding - }` - ); - if (this.exportsInfo && !alreadyVisitedExportsInfo.has(this.exportsInfo)) { - this.exportsInfo._updateHash(hash, runtime, alreadyVisitedExportsInfo); - } - } + write(this.error); - getUsedInfo() { - if (this._globalUsed !== undefined) { - switch (this._globalUsed) { - case UsageState.Unused: - return "unused"; - case UsageState.NoInfo: - return "no usage info"; - case UsageState.Unknown: - return "maybe used (runtime-defined)"; - case UsageState.Used: - return "used"; - case UsageState.OnlyPropertiesUsed: - return "only properties used"; - } - } else if (this._usedInRuntime !== undefined) { - /** @type {Map} */ - const map = new Map(); - for (const [runtime, used] of this._usedInRuntime) { - const list = map.get(used); - if (list !== undefined) list.push(runtime); - else map.set(used, [runtime]); - } - const specificInfo = Array.from(map, ([used, runtimes]) => { - switch (used) { - case UsageState.NoInfo: - return `no usage info in ${runtimes.join(", ")}`; - case UsageState.Unknown: - return `maybe used in ${runtimes.join(", ")} (runtime-defined)`; - case UsageState.Used: - return `used in ${runtimes.join(", ")}`; - case UsageState.OnlyPropertiesUsed: - return `only properties used in ${runtimes.join(", ")}`; - } - }); - if (specificInfo.length > 0) { - return specificInfo.join("; "); - } - } - return this._hasUseInRuntimeInfo ? "unused" : "no usage info"; + super.serialize(context); } - getProvidedInfo() { - switch (this.provided) { - case undefined: - return "no provided info"; - case null: - return "maybe provided (runtime-defined)"; - case true: - return "provided"; - case false: - return "not provided"; - } + deserialize(context) { + const { read } = context; + + this.error = read(); + + super.deserialize(context); } +} - getRenameInfo() { - if (this._usedName !== null && this._usedName !== this.name) { - return `renamed to ${JSON.stringify(this._usedName).slice(1, -1)}`; - } - switch (this.canMangleProvide) { - case undefined: - switch (this.canMangleUse) { - case undefined: - return "missing provision and use info prevents renaming"; - case false: - return "usage prevents renaming (no provision info)"; - case true: - return "missing provision info prevents renaming"; - } - break; - case true: - switch (this.canMangleUse) { - case undefined: - return "missing usage info prevents renaming"; - case false: - return "usage prevents renaming"; - case true: - return "could be renamed"; - } - break; - case false: - switch (this.canMangleUse) { - case undefined: - return "provision prevents renaming (no use info)"; - case false: - return "usage and provision prevents renaming"; - case true: - return "provision prevents renaming"; - } - break; +makeSerializable(ModuleBuildError, "webpack/lib/ModuleBuildError"); + +module.exports = ModuleBuildError; + + +/***/ }), + +/***/ 67409: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const WebpackError = __webpack_require__(53799); + +/** @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; + + if (err && /** @type {any} */ (err).hideStack) { + this.stack = + err.stack.split("\n").slice(1).join("\n") + "\n\n" + this.stack; } - throw new Error( - `Unexpected flags for getRenameInfo ${this.canMangleProvide} ${this.canMangleUse}` - ); } } -module.exports = ExportsInfo; -module.exports.ExportInfo = ExportInfo; -module.exports.UsageState = UsageState; +module.exports = ModuleDependencyError; /***/ }), -/***/ 7145: +/***/ 29656: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -42993,75 +44558,49 @@ module.exports.UsageState = UsageState; -const ConstDependency = __webpack_require__(76911); -const ExportsInfoDependency = __webpack_require__(78988); +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ -class ExportsInfoApiPlugin { +class ModuleDependencyWarning extends WebpackError { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {Module} module module tied to dependency + * @param {Error} err error thrown + * @param {DependencyLocation} loc location of dependency */ - 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); - } - ); + 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; + + if (err && /** @type {any} */ (err).hideStack) { + this.stack = + err.stack.split("\n").slice(1).join("\n") + "\n\n" + this.stack; + } } } -module.exports = ExportsInfoApiPlugin; +makeSerializable( + ModuleDependencyWarning, + "webpack/lib/ModuleDependencyWarning" +); + +module.exports = ModuleDependencyWarning; /***/ }), -/***/ 73071: +/***/ 23744: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -43072,1070 +44611,1273 @@ module.exports = ExportsInfoApiPlugin; -const { OriginalSource, RawSource } = __webpack_require__(51255); -const ConcatenationScope = __webpack_require__(98229); -const { UsageState } = __webpack_require__(63686); -const InitFragment = __webpack_require__(55870); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const StaticExportsDependency = __webpack_require__(91418); -const createHash = __webpack_require__(49835); -const extractUrlAndGlobal = __webpack_require__(11850); +const { cleanUp } = __webpack_require__(59985); +const WebpackError = __webpack_require__(53799); const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const { register } = __webpack_require__(8282); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./ExportsInfo")} ExportsInfo */ -/** @typedef {import("./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("./NormalModuleFactory")} NormalModuleFactory */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ -/** @typedef {import("./util/Hash")} Hash */ -/** @typedef {typeof import("./util/Hash")} HashConstructor */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +class ModuleError extends WebpackError { + /** + * @param {Error} err error thrown + * @param {{from?: string|null}} info additional info + */ + constructor(err, { from = null } = {}) { + let message = "Module Error"; -/** - * @typedef {Object} SourceData - * @property {boolean=} iife - * @property {string=} init - * @property {string} expression - * @property {InitFragment[]=} chunkInitFragments - * @property {ReadonlySet=} runtimeRequirements - */ + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } -const TYPES = new Set(["javascript"]); -const CSS_TYPES = new Set(["css-import"]); -const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); -const RUNTIME_REQUIREMENTS_FOR_SCRIPT = new Set([RuntimeGlobals.loadScript]); -const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([ - RuntimeGlobals.definePropertyGetters -]); -const EMPTY_RUNTIME_REQUIREMENTS = new Set([]); + if (err && typeof err === "object" && err.message) { + message += err.message; + } else if (err) { + message += err; + } -/** - * @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]; + super(message); + + this.name = "ModuleError"; + this.error = err; + this.details = + err && typeof err === "object" && err.stack + ? cleanUp(err.stack, this.message) + : undefined; } - // needed for e.g. window["some"]["thing"] - const objectLookup = variableName.map(r => `[${JSON.stringify(r)}]`).join(""); - return { - iife: type === "this", - expression: `${type}${objectLookup}` - }; -}; + 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; + + +/***/ }), + +/***/ 51010: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Module")} Module */ /** - * @param {string|string[]} moduleAndSpecifiers the module request - * @returns {SourceData} the generated source + * @typedef {Object} ModuleFactoryResult + * @property {Module=} module the created module or unset if no module was created + * @property {Set=} fileDependencies + * @property {Set=} contextDependencies + * @property {Set=} missingDependencies + * @property {boolean=} cacheable allow to use the unsafe cache */ -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 - * @returns {SourceData} the generated source + * @typedef {Object} ModuleFactoryCreateDataContextInfo + * @property {string} issuer + * @property {string | null=} issuerLayer + * @property {string} compiler */ -const getSourceForCommonJsExternalInNodeModule = moduleAndSpecifiers => { - const chunkInitFragments = [ - new InitFragment( - 'import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module";\n', - InitFragment.STAGE_HARMONY_IMPORTS, - 0, - "external module node-commonjs" - ) - ]; - if (!Array.isArray(moduleAndSpecifiers)) { - return { - expression: `__WEBPACK_EXTERNAL_createRequire(import.meta.url)(${JSON.stringify( - moduleAndSpecifiers - )})`, - chunkInitFragments - }; - } - const moduleName = moduleAndSpecifiers[0]; - return { - expression: `__WEBPACK_EXTERNAL_createRequire(import.meta.url)(${JSON.stringify( - moduleName - )})${propertyAccess(moduleAndSpecifiers, 1)}`, - chunkInitFragments - }; -}; /** - * @param {string|string[]} moduleAndSpecifiers the module request - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @returns {SourceData} the generated source + * @typedef {Object} ModuleFactoryCreateData + * @property {ModuleFactoryCreateDataContextInfo} contextInfo + * @property {ResolveOptions=} resolveOptions + * @property {string} context + * @property {Dependency[]} dependencies */ -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" - )});` - }; -}; -class ModuleExternalInitFragment extends InitFragment { +class ModuleFactory { + /* istanbul ignore next */ /** - * @param {string} request import source - * @param {string=} ident recomputed ident - * @param {string | HashConstructor=} hashFunction the hash function to use + * @abstract + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * @returns {void} */ - constructor(request, ident, hashFunction = "md4") { - if (ident === undefined) { - ident = Template.toIdentifier(request); - if (ident !== request) { - ident += `_${createHash(hashFunction) - .update(request) - .digest("hex") - .slice(0, 8)}`; - } - } - const identifier = `__WEBPACK_EXTERNAL_MODULE_${ident}__`; - super( - `import * as ${identifier} from ${JSON.stringify(request)};\n`, - InitFragment.STAGE_HARMONY_IMPORTS, - 0, - `external module import ${ident}` - ); - this._ident = ident; - this._identifier = identifier; - this._request = request; - } - - getNamespaceIdentifier() { - return this._identifier; + create(data, callback) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } } -register( - ModuleExternalInitFragment, - "webpack/lib/ExternalModule", - "ModuleExternalInitFragment", - { - serialize(obj, { write }) { - write(obj._request); - write(obj._ident); - }, - deserialize({ read }) { - return new ModuleExternalInitFragment(read(), read()); - } - } -); +module.exports = ModuleFactory; -const generateModuleRemapping = (input, exportsInfo, runtime) => { - if (exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused) { - const properties = []; - for (const exportInfo of exportsInfo.orderedExports) { - const used = exportInfo.getUsedName(exportInfo.name, runtime); - if (!used) continue; - const nestedInfo = exportInfo.getNestedExportsInfo(); - if (nestedInfo) { - const nestedExpr = generateModuleRemapping( - `${input}${propertyAccess([exportInfo.name])}`, - nestedInfo - ); - if (nestedExpr) { - properties.push(`[${JSON.stringify(used)}]: y(${nestedExpr})`); - continue; - } - } - properties.push( - `[${JSON.stringify(used)}]: () => ${input}${propertyAccess([ - exportInfo.name - ])}` - ); - } - return `x({ ${properties.join(", ")} })`; + +/***/ }), + +/***/ 88821: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const NormalModule = __webpack_require__(39); +const createHash = __webpack_require__(49835); +const memoize = __webpack_require__(78676); + +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {typeof import("./util/Hash")} Hash */ + +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, hashFunction) => { + return () => { + const hash = createHash(hashFunction); + 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; + /** - * @param {string|string[]} moduleAndSpecifiers the module request - * @param {ExportsInfo} exportsInfo exports info of this module - * @param {RuntimeSpec} runtime the runtime - * @param {string | HashConstructor=} hashFunction the hash function to use - * @returns {SourceData} the generated source + * + * @param {Module | string} module the module + * @param {TODO} options options + * @param {Object} contextInfo context info + * @param {RequestShortener} contextInfo.requestShortener requestShortener + * @param {ChunkGraph} contextInfo.chunkGraph chunk graph + * @param {string | Hash} contextInfo.hashFunction the hash function to use + * @returns {string} the filename */ -const getSourceForModuleExternal = ( - moduleAndSpecifiers, - exportsInfo, - runtime, - hashFunction +ModuleFilenameHelpers.createFilename = ( + module = "", + options, + { requestShortener, chunkGraph, hashFunction = "md4" } ) => { - if (!Array.isArray(moduleAndSpecifiers)) - moduleAndSpecifiers = [moduleAndSpecifiers]; - const initFragment = new ModuleExternalInitFragment( - moduleAndSpecifiers[0], - undefined, - hashFunction - ); - const baseAccess = `${initFragment.getNamespaceIdentifier()}${propertyAccess( - moduleAndSpecifiers, - 1 - )}`; - const moduleRemapping = generateModuleRemapping( - baseAccess, - exportsInfo, - runtime - ); - let expression = moduleRemapping || baseAccess; - return { - expression, - init: `var x = y => { var x = {}; ${RuntimeGlobals.definePropertyGetters}(x, y); return x; }\nvar y = x => () => x`, - runtimeRequirements: moduleRemapping - ? RUNTIME_REQUIREMENTS_FOR_MODULE - : undefined, - chunkInitFragments: [initFragment] + const opts = { + namespace: "", + moduleFilenameTemplate: "", + ...(typeof options === "object" + ? options + : { + moduleFilenameTemplate: options + }) }; -}; -/** - * @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); + let absoluteResourcePath; + let hash; + let identifier; + let moduleId; + let shortIdentifier; + if (typeof module === "string") { + shortIdentifier = memoize(() => requestShortener.shorten(module)); + identifier = shortIdentifier; + moduleId = () => ""; + absoluteResourcePath = () => module.split("!").pop(); + hash = getHash(identifier, hashFunction); + } else { + shortIdentifier = memoize(() => + module.readableIdentifier(requestShortener) + ); + identifier = memoize(() => requestShortener.shorten(module.identifier())); + moduleId = () => chunkGraph.getModuleId(module); + absoluteResourcePath = () => + module instanceof NormalModule + ? module.resource + : module.identifier().split("!").pop(); + hash = getHash(identifier, hashFunction); } - const url = urlAndGlobal[0]; - const globalName = urlAndGlobal[1]; - return { - init: "var __webpack_error__ = new Error();", - expression: `new Promise(${runtimeTemplate.basicFunction( - "resolve, reject", - [ - `if(typeof ${globalName} !== "undefined") return resolve();`, - `${RuntimeGlobals.loadScript}(${JSON.stringify( - url - )}, ${runtimeTemplate.basicFunction("event", [ - `if(typeof ${globalName} !== "undefined") return resolve();`, - "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", - "var realSrc = event && event.target && event.target.src;", - "__webpack_error__.message = 'Loading script failed.\\n(' + errorType + ': ' + realSrc + ')';", - "__webpack_error__.name = 'ScriptExternalLoadError';", - "__webpack_error__.type = errorType;", - "__webpack_error__.request = realSrc;", - "reject(__webpack_error__);" - ])}, ${JSON.stringify(globalName)});` - ] - )}).then(${runtimeTemplate.returningFunction( - `${globalName}${propertyAccess(urlAndGlobal, 2)}` - )})`, - runtimeRequirements: RUNTIME_REQUIREMENTS_FOR_SCRIPT + 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} */ + 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; }; + +/***/ }), + +/***/ 99988: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const util = __webpack_require__(73837); +const ExportsInfo = __webpack_require__(63686); +const ModuleGraphConnection = __webpack_require__(40639); +const SortableSet = __webpack_require__(13098); +const WeakTupleMap = __webpack_require__(28745); + +/** @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 */ + /** - * @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 + * @callback OptimizationBailoutFunction + * @param {RequestShortener} requestShortener + * @returns {string} */ -const checkExternalVariable = (variableName, request, runtimeTemplate) => { - return `if(typeof ${variableName} === 'undefined') { ${runtimeTemplate.throwMissingModuleErrorBlock( - { request } - )} }\n`; -}; + +const EMPTY_SET = new Set(); /** - * @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 + * @param {SortableSet} set input + * @returns {readonly Map} mapped by origin module */ -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 - }; +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; }; /** - * @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 + * @param {SortableSet} set input + * @returns {readonly Map} mapped by module */ -const getSourceForDefaultCase = (optional, request, runtimeTemplate) => { - if (!Array.isArray(request)) { - // make it an array as the look up works the same basically - request = [request]; +const getConnectionsByModule = set => { + const map = new Map(); + /** @type {Module | 0} */ + let lastModule = 0; + /** @type {ModuleGraphConnection[]} */ + let lastList = undefined; + for (const connection of set) { + const { module } = connection; + if (lastModule === module) { + lastList.push(connection); + } else { + lastModule = module; + const list = map.get(module); + if (list !== undefined) { + lastList = list; + list.push(connection); + } else { + const list = [connection]; + lastList = list; + map.set(module, list); + } + } } - - const variableName = request[0]; - const objectLookup = propertyAccess(request, 1); - return { - init: optional - ? checkExternalVariable(variableName, request.join("."), runtimeTemplate) - : undefined, - expression: `${variableName}${objectLookup}` - }; + return map; }; -class ExternalModule extends Module { - constructor(request, type, userRequest) { - super("javascript/dynamic", null); +class ModuleGraphModule { + constructor() { + /** @type {SortableSet} */ + this.incomingConnections = new SortableSet(); + /** @type {SortableSet | 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; + /** @type {ModuleGraphConnection[]} */ + this._unassignedConnections = undefined; + } +} - // Info from Factory - /** @type {string | string[] | Record} */ - this.request = request; - /** @type {string} */ - this.externalType = type; - /** @type {string} */ - this.userRequest = userRequest; +class ModuleGraph { + constructor() { + /** @type {WeakMap} */ + this._dependencyMap = new WeakMap(); + /** @type {Map} */ + this._moduleMap = new Map(); + /** @type {WeakMap} */ + this._metaMap = new WeakMap(); + + /** @type {WeakTupleMap} */ + this._cache = undefined; + + /** @type {Map>} */ + this._moduleMemCaches = undefined; } /** - * @returns {Set} types available (do not mutate) + * @param {Module} module the module + * @returns {ModuleGraphModule} the internal module */ - getSourceTypes() { - return this.externalType === "css-import" ? CSS_TYPES : TYPES; + _getModuleGraphModule(module) { + let mgm = this._moduleMap.get(module); + if (mgm === undefined) { + mgm = new ModuleGraphModule(); + this._moduleMap.set(module, mgm); + } + return mgm; } /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @param {Dependency} dependency the dependency + * @param {DependenciesBlock} block parent block + * @param {Module} module parent module + * @param {number=} indexInBlock position in block + * @returns {void} */ - libIdent(options) { - return this.userRequest; + setParents(dependency, block, module, indexInBlock = -1) { + dependency._parentDependenciesBlockIndex = indexInBlock; + dependency._parentDependenciesBlock = block; + dependency._parentModule = module; } /** - * @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 + * @param {Dependency} dependency the dependency + * @returns {Module} parent module */ - chunkCondition(chunk, { chunkGraph }) { - return this.externalType === "css-import" - ? true - : chunkGraph.getNumberOfEntryModules(chunk) > 0; + getParentModule(dependency) { + return dependency._parentModule; } /** - * @returns {string} a unique identifier of the module + * @param {Dependency} dependency the dependency + * @returns {DependenciesBlock} parent block */ - identifier() { - return `external ${this.externalType} ${JSON.stringify(this.request)}`; + getParentBlock(dependency) { + return dependency._parentDependenciesBlock; } /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module + * @param {Dependency} dependency the dependency + * @returns {number} index */ - readableIdentifier(requestShortener) { - return "external " + JSON.stringify(this.request); + getParentBlockIndex(dependency) { + return dependency._parentDependenciesBlockIndex; } /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @param {Module} originModule the referencing module + * @param {Dependency} dependency the referencing dependency + * @param {Module} module the referenced module * @returns {void} */ - needBuild(context, callback) { - return callback(null, !this.buildMeta); + setResolvedModule(originModule, dependency, module) { + const connection = new ModuleGraphConnection( + originModule, + dependency, + module, + undefined, + dependency.weak, + dependency.getCondition(this) + ); + const connections = this._getModuleGraphModule(module).incomingConnections; + connections.add(connection); + if (originModule) { + const mgm = this._getModuleGraphModule(originModule); + if (mgm._unassignedConnections === undefined) { + mgm._unassignedConnections = []; + } + mgm._unassignedConnections.push(connection); + if (mgm.outgoingConnections === undefined) { + mgm.outgoingConnections = new SortableSet(); + } + mgm.outgoingConnections.add(connection); + } else { + this._dependencyMap.set(dependency, connection); + } } /** - * @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 + * @param {Dependency} dependency the referencing dependency + * @param {Module} module the referenced module * @returns {void} */ - build(options, compilation, resolver, fs, callback) { - this.buildMeta = { - async: false, - exportsType: undefined - }; - this.buildInfo = { - strict: true, - topLevelDeclarations: new Set(), - module: compilation.outputOptions.module - }; - const { request, externalType } = this._getRequestAndExternalType(); - this.buildMeta.exportsType = "dynamic"; - let canMangle = false; - this.clearDependenciesAndBlocks(); - switch (externalType) { - case "this": - this.buildInfo.strict = false; - break; - case "system": - if (!Array.isArray(request) || request.length === 1) { - this.buildMeta.exportsType = "namespace"; - canMangle = true; - } - break; - case "module": - if (this.buildInfo.module) { - if (!Array.isArray(request) || request.length === 1) { - this.buildMeta.exportsType = "namespace"; - canMangle = true; - } - } else { - this.buildMeta.async = true; - if (!Array.isArray(request) || request.length === 1) { - this.buildMeta.exportsType = "namespace"; - canMangle = false; - } - } - break; - case "script": - case "promise": - this.buildMeta.async = true; - break; - case "import": - this.buildMeta.async = true; - if (!Array.isArray(request) || request.length === 1) { - this.buildMeta.exportsType = "namespace"; - canMangle = false; - } - break; - } - this.addDependency(new StaticExportsDependency(true, canMangle)); - callback(); + updateModule(dependency, module) { + const connection = this.getConnection(dependency); + if (connection.module === module) return; + const newConnection = connection.clone(); + newConnection.module = module; + this._dependencyMap.set(dependency, newConnection); + connection.setActive(false); + const originMgm = this._getModuleGraphModule(connection.originModule); + originMgm.outgoingConnections.add(newConnection); + const targetMgm = this._getModuleGraphModule(module); + targetMgm.incomingConnections.add(newConnection); } - restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { - this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); + /** + * @param {Dependency} dependency the referencing dependency + * @returns {void} + */ + removeConnection(dependency) { + const connection = this.getConnection(dependency); + const targetMgm = this._getModuleGraphModule(connection.module); + targetMgm.incomingConnections.delete(connection); + const originMgm = this._getModuleGraphModule(connection.originModule); + originMgm.outgoingConnections.delete(connection); + this._dependencyMap.set(dependency, null); } /** - * @param {ConcatenationBailoutReasonContext} context context - * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + * @param {Dependency} dependency the referencing dependency + * @param {string} explanation an explanation + * @returns {void} */ - 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; + addExplanation(dependency, explanation) { + const connection = this.getConnection(dependency); + connection.addExplanation(explanation); } - _getRequestAndExternalType() { - let { request, externalType } = this; - if (typeof request === "object" && !Array.isArray(request)) - request = request[externalType]; - return { request, externalType }; + /** + * @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; } - _getSourceData( - request, - externalType, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime - ) { - switch (externalType) { - case "this": - case "window": - case "self": - return getSourceForGlobalVariableExternal(request, this.externalType); - case "global": - return getSourceForGlobalVariableExternal( - request, - runtimeTemplate.globalObject - ); - case "commonjs": - case "commonjs2": - case "commonjs-module": - case "commonjs-static": - return getSourceForCommonJsExternal(request); - case "node-commonjs": - return this.buildInfo.module - ? getSourceForCommonJsExternalInNodeModule(request) - : getSourceForCommonJsExternal(request); - case "amd": - case "amd-require": - case "umd": - case "umd2": - case "system": - case "jsonp": { - const id = chunkGraph.getModuleId(this); - return getSourceForAmdOrUmdExternal( - id !== null ? id : this.identifier(), - this.isOptional(moduleGraph), - request, - runtimeTemplate - ); + /** + * @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 SortableSet(); } - case "import": - return getSourceForImportExternal(request, runtimeTemplate); - case "script": - return getSourceForScriptExternal(request, runtimeTemplate); - case "module": { - if (!this.buildInfo.module) { - if (!runtimeTemplate.supportsDynamicImport()) { - throw new Error( - "The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script" + - (runtimeTemplate.supportsEcmaScriptModuleSyntax() - ? "\nDid you mean to build a EcmaScript Module ('output.module: true')?" - : "") - ); - } - return getSourceForImportExternal(request, runtimeTemplate); - } - if (!runtimeTemplate.supportsEcmaScriptModuleSyntax()) { - throw new Error( - "The target environment doesn't support EcmaScriptModule syntax so it's not possible to use external type 'module'" - ); + const newConnections = newMgm.outgoingConnections; + for (const connection of oldConnections) { + if (filterConnection(connection)) { + connection.originModule = newModule; + newConnections.add(connection); + oldConnections.delete(connection); } - return getSourceForModuleExternal( - request, - moduleGraph.getExportsInfo(this), - runtime, - runtimeTemplate.outputOptions.hashFunction - ); } - case "var": - case "promise": - case "const": - case "let": - case "assign": - default: - return getSourceForDefaultCase( - this.isOptional(moduleGraph), - request, - runtimeTemplate - ); + } + // 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 {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result + * @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} */ - codeGeneration({ - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime, - concatenationScope - }) { - const { request, externalType } = this._getRequestAndExternalType(); - switch (externalType) { - case "asset": { - const sources = new Map(); - sources.set( - "javascript", - new RawSource(`module.exports = ${JSON.stringify(request)};`) - ); - const data = new Map(); - data.set("url", request); - return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS, data }; - } - case "css-import": { - const sources = new Map(); - sources.set( - "css-import", - new RawSource(`@import url(${JSON.stringify(request)});`) - ); - return { - sources, - runtimeRequirements: EMPTY_RUNTIME_REQUIREMENTS - }; + 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 SortableSet(); } - default: { - const sourceData = this._getSourceData( - request, - externalType, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime - ); - - let sourceString = sourceData.expression; - if (sourceData.iife) - sourceString = `(function() { return ${sourceString}; }())`; - if (concatenationScope) { - sourceString = `${ - runtimeTemplate.supportsConst() ? "const" : "var" - } ${ConcatenationScope.NAMESPACE_OBJECT_EXPORT} = ${sourceString};`; - concatenationScope.registerNamespaceExport( - ConcatenationScope.NAMESPACE_OBJECT_EXPORT - ); - } else { - sourceString = `module.exports = ${sourceString};`; - } - if (sourceData.init) - sourceString = `${sourceData.init}\n${sourceString}`; - - let data = undefined; - if (sourceData.chunkInitFragments) { - data = new Map(); - data.set("chunkInitFragments", sourceData.chunkInitFragments); - } - - const sources = new Map(); - if (this.useSourceMap || this.useSimpleSourceMap) { - sources.set( - "javascript", - new OriginalSource(sourceString, this.identifier()) - ); - } else { - sources.set("javascript", new RawSource(sourceString)); - } - - let runtimeRequirements = sourceData.runtimeRequirements; - if (!concatenationScope) { - if (!runtimeRequirements) { - runtimeRequirements = RUNTIME_REQUIREMENTS; - } else { - const set = new Set(runtimeRequirements); - set.add(RuntimeGlobals.module); - runtimeRequirements = set; + 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); } } - - return { - sources, - runtimeRequirements: - runtimeRequirements || EMPTY_RUNTIME_REQUIREMENTS, - data - }; } } } /** - * @param {string=} type the source type for which the size should be estimated - * @returns {number} the estimated size of the module (must be non-zero) + * @param {Module} module the referenced module + * @param {string} explanation an explanation why it's referenced + * @returns {void} */ - size(type) { - return 42; + addExtraReason(module, explanation) { + const connections = this._getModuleGraphModule(module).incomingConnections; + connections.add(new ModuleGraphConnection(null, null, module, explanation)); } /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} + * @param {Dependency} dependency the dependency to look for a referenced module + * @returns {Module} the referenced module */ - updateHash(hash, context) { - const { chunkGraph } = context; - hash.update( - `${this.externalType}${JSON.stringify(this.request)}${this.isOptional( - chunkGraph.moduleGraph - )}` - ); - super.updateHash(hash, context); + getResolvedModule(dependency) { + const connection = this.getConnection(dependency); + return connection !== undefined ? connection.resolvedModule : null; } - serialize(context) { - const { write } = context; - - write(this.request); - write(this.externalType); - write(this.userRequest); + /** + * @param {Dependency} dependency the dependency to look for a referenced module + * @returns {ModuleGraphConnection | undefined} the connection + */ + getConnection(dependency) { + const connection = this._dependencyMap.get(dependency); + if (connection === undefined) { + const module = this.getParentModule(dependency); + if (module !== undefined) { + const mgm = this._getModuleGraphModule(module); + if ( + mgm._unassignedConnections && + mgm._unassignedConnections.length !== 0 + ) { + let foundConnection; + for (const connection of mgm._unassignedConnections) { + this._dependencyMap.set(connection.dependency, connection); + if (connection.dependency === dependency) + foundConnection = connection; + } + mgm._unassignedConnections.length = 0; + if (foundConnection !== undefined) { + return foundConnection; + } + } + } + this._dependencyMap.set(dependency, null); + return undefined; + } + return connection === null ? undefined : connection; + } - super.serialize(context); + /** + * @param {Dependency} dependency the dependency to look for a referenced module + * @returns {Module} the referenced module + */ + getModule(dependency) { + const connection = this.getConnection(dependency); + return connection !== undefined ? connection.module : null; } - deserialize(context) { - const { read } = context; + /** + * @param {Dependency} dependency the dependency to look for a referencing module + * @returns {Module} the referencing module + */ + getOrigin(dependency) { + const connection = this.getConnection(dependency); + return connection !== undefined ? connection.originModule : null; + } - this.request = read(); - this.externalType = read(); - this.userRequest = read(); + /** + * @param {Dependency} dependency the dependency to look for a referencing module + * @returns {Module} the original referencing module + */ + getResolvedOrigin(dependency) { + const connection = this.getConnection(dependency); + return connection !== undefined ? connection.resolvedOriginModule : null; + } - super.deserialize(context); + /** + * @param {Module} module the module + * @returns {Iterable} reasons why a module is included + */ + getIncomingConnections(module) { + const connections = this._getModuleGraphModule(module).incomingConnections; + return connections; } -} -makeSerializable(ExternalModule, "webpack/lib/ExternalModule"); + /** + * @param {Module} module the module + * @returns {Iterable} list of outgoing connections + */ + getOutgoingConnections(module) { + const connections = this._getModuleGraphModule(module).outgoingConnections; + return connections === undefined ? EMPTY_SET : connections; + } -module.exports = ExternalModule; + /** + * @param {Module} module the module + * @returns {readonly Map} 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 {readonly Map | undefined} connections to modules, in a map by module + */ + getOutgoingConnectionsByModule(module) { + const connections = this._getModuleGraphModule(module).outgoingConnections; + return connections === undefined + ? undefined + : connections.getFromUnorderedCache(getConnectionsByModule); + } -/***/ }), + /** + * @param {Module} module the module + * @returns {ModuleProfile | null} the module profile + */ + getProfile(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.profile; + } -/***/ 62153: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @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; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @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; + } -const util = __webpack_require__(73837); -const ExternalModule = __webpack_require__(73071); -const { resolveByProperty, cachedSetProperty } = __webpack_require__(60839); + /** + * @param {Module} module the module + * @returns {(string | OptimizationBailoutFunction)[]} optimization bailouts + */ + getOptimizationBailout(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.optimizationBailout; + } -/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ -/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ + /** + * @param {Module} module the module + * @returns {true | string[] | null} the provided exports + */ + getProvidedExports(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.exports.getProvidedExports(); + } -const UNSPECIFIED_EXTERNAL_TYPE_REGEXP = /^[a-z0-9-]+ /; -const EMPTY_RESOLVE_OPTIONS = {}; + /** + * @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; + } -// 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" -); + /** + * @param {Module} module the module + * @returns {ExportsInfo} info about the exports + */ + getExportsInfo(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.exports; + } -const cache = new WeakMap(); + /** + * @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); + } -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; + /** + * @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); } - 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 + * @param {Module} module the module + * @param {RuntimeSpec} runtime the runtime + * @returns {false | true | SortableSet | null} the used exports + * false: module is not used at all. + * true: the module namespace/object export is used. + * SortableSet: these export names are used. + * empty SortableSet: module is used but no export. + * null: unknown, worst case should be assumed. */ - constructor(type, externals) { - this.type = type; - this.externals = externals; + getUsedExports(module, runtime) { + const mgm = this._getModuleGraphModule(module); + return mgm.exports.getUsedExports(runtime); } /** - * @param {NormalModuleFactory} normalModuleFactory the normal module factory + * @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} */ - apply(normalModuleFactory) { - const globalType = this.type; - normalModuleFactory.hooks.factorize.tapAsync( - "ExternalModuleFactoryPlugin", - (data, callback) => { - const context = data.context; - const contextInfo = data.contextInfo; - const dependency = data.dependencies[0]; - const dependencyType = data.dependencyType; + setPreOrderIndex(module, index) { + const mgm = this._getModuleGraphModule(module); + mgm.preOrderIndex = index; + } - /** - * @param {string|string[]|boolean|Record} 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} */ - 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 {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 {Externals} externals externals config - * @param {function((Error | null)=, ExternalModule=): void} callback callback - * @returns {void} - */ - const handleExternals = (externals, callback) => { - if (typeof externals === "string") { - if (externals === dependency.request) { - return handleExternal(dependency.request, undefined, callback); - } - } else if (Array.isArray(externals)) { - let i = 0; - const next = () => { - let asyncFlag; - const handleExternalsAndCallback = (err, module) => { - if (err) return callback(err); - if (!module) { - if (asyncFlag) { - asyncFlag = false; - return; - } - return next(); - } - callback(null, module); - }; + /** + * @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; + } - do { - asyncFlag = true; - if (i >= externals.length) return callback(); - handleExternals(externals[i++], handleExternalsAndCallback); - } while (!asyncFlag); - asyncFlag = false; - }; + /** + * @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; + } - next(); - return; - } else if (externals instanceof RegExp) { - if (externals.test(dependency.request)) { - return handleExternal(dependency.request, undefined, callback); - } - } else if (typeof externals === "function") { - const cb = (err, value, type) => { - if (err) return callback(err); - if (value !== undefined) { - handleExternal(value, type, callback); - } else { - callback(); - } - }; - if (externals.length === 3) { - // TODO webpack 6 remove this - callDeprecatedExternals( - externals, - context, - dependency.request, - cb - ); - } else { - const promise = externals( - { - context, - request: dependency.request, - dependencyType, - contextInfo, - getResolve: options => (context, request, callback) => { - const resolveContext = { - fileDependencies: data.fileDependencies, - missingDependencies: data.missingDependencies, - contextDependencies: data.contextDependencies - }; - let resolver = normalModuleFactory.getResolver( - "normal", - dependencyType - ? cachedSetProperty( - data.resolveOptions || EMPTY_RESOLVE_OPTIONS, - "dependencyType", - dependencyType - ) - : data.resolveOptions - ); - if (options) resolver = resolver.withOptions(options); - if (callback) { - resolver.resolve( - {}, - context, - request, - resolveContext, - callback - ); - } else { - return new Promise((resolve, reject) => { - resolver.resolve( - {}, - context, - request, - resolveContext, - (err, result) => { - if (err) reject(err); - else resolve(result); - } - ); - }); - } - } - }, - cb - ); - if (promise && promise.then) promise.then(r => cb(null, r), cb); - } - return; - } else if (typeof externals === "object") { - const resolvedExternals = resolveLayer( - externals, - contextInfo.issuerLayer - ); - if ( - Object.prototype.hasOwnProperty.call( - resolvedExternals, - dependency.request - ) - ) { - return handleExternal( - resolvedExternals[dependency.request], - undefined, - callback - ); - } - } - callback(); - }; + /** + * @param {Module} module the module + * @returns {number} the depth of the module + */ + getDepth(module) { + const mgm = this._getModuleGraphModule(module); + return mgm.depth; + } - handleExternals(this.externals, callback); - } - ); + /** + * @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; } -} -module.exports = ExternalModuleFactoryPlugin; + /** + * @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; + } -/***/ 6652: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {Module} module the module + * @returns {void} + */ + setAsync(module) { + const mgm = this._getModuleGraphModule(module); + mgm.async = true; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @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); + } + /** + * @param {string=} cacheStage a persistent stage name for caching + */ + freeze(cacheStage) { + this._cache = new WeakTupleMap(); + this._cacheStage = cacheStage; + } -const ExternalModuleFactoryPlugin = __webpack_require__(62153); + unfreeze() { + this._cache = undefined; + this._cacheStage = undefined; + } -/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */ -/** @typedef {import("./Compiler")} Compiler */ + /** + * @template {any[]} T + * @template V + * @param {(moduleGraph: ModuleGraph, ...args: T) => V} fn computer + * @param {T} args arguments + * @returns {V} computed value or cached + */ + cached(fn, ...args) { + if (this._cache === undefined) return fn(this, ...args); + return this._cache.provide(fn, ...args, () => fn(this, ...args)); + } -class ExternalsPlugin { /** - * @param {string | undefined} type default external type - * @param {Externals} externals externals config + * @param {Map>} moduleMemCaches mem caches for modules for better caching */ - constructor(type, externals) { - this.type = type; - this.externals = externals; + setModuleMemCaches(moduleMemCaches) { + this._moduleMemCaches = moduleMemCaches; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {Dependency} dependency dependency + * @param {...any} args arguments, last argument is a function called with moduleGraph, dependency, ...args + * @returns {any} computed value or cached */ - apply(compiler) { - compiler.hooks.compile.tap("ExternalsPlugin", ({ normalModuleFactory }) => { - new ExternalModuleFactoryPlugin(this.type, this.externals).apply( - normalModuleFactory + dependencyCacheProvide(dependency, ...args) { + /** @type {(moduleGraph: ModuleGraph, dependency: Dependency, ...args: any[]) => any} */ + const fn = args.pop(); + if (this._moduleMemCaches && this._cacheStage) { + const memCache = this._moduleMemCaches.get( + this.getParentModule(dependency) ); - }); + if (memCache !== undefined) { + return memCache.provide(dependency, this._cacheStage, ...args, () => + fn(this, dependency, ...args) + ); + } + } + if (this._cache === undefined) return fn(this, dependency, ...args); + return this._cache.provide(dependency, ...args, () => + fn(this, dependency, ...args) + ); + } + + // 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); } } -module.exports = ExternalsPlugin; +// TODO remove in webpack 6 +/** @type {WeakMap} */ +const moduleGraphForModuleMap = new WeakMap(); + +// TODO remove in webpack 6 +/** @type {Map ModuleGraph>} */ +const deprecateMap = new Map(); + +module.exports = ModuleGraph; +module.exports.ModuleGraphConnection = ModuleGraphConnection; /***/ }), -/***/ 79453: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 40639: +/***/ (function(module) { "use strict"; /* @@ -44145,3563 +45887,2060 @@ module.exports = ExternalsPlugin; -const { create: createResolver } = __webpack_require__(30662); -const asyncLib = __webpack_require__(78175); -const AsyncQueue = __webpack_require__(12260); -const StackedCacheMap = __webpack_require__(64985); -const createHash = __webpack_require__(49835); -const { join, dirname, relative, lstatReadlinkAbsolute } = __webpack_require__(17139); -const makeSerializable = __webpack_require__(33032); -const processAsyncTree = __webpack_require__(42791); - -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./logging/Logger").Logger} Logger */ -/** @typedef {typeof import("./util/Hash")} Hash */ -/** @typedef {import("./util/fs").IStats} IStats */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ - -const supportsEsm = +process.versions.modules >= 83; - -let FS_ACCURACY = 2000; - -const EMPTY_SET = new Set(); - -const RBDT_RESOLVE_CJS = 0; -const RBDT_RESOLVE_ESM = 1; -const RBDT_RESOLVE_DIRECTORY = 2; -const RBDT_RESOLVE_CJS_FILE = 3; -const RBDT_RESOLVE_CJS_FILE_AS_CHILD = 4; -const RBDT_RESOLVE_ESM_FILE = 5; -const RBDT_DIRECTORY = 6; -const RBDT_FILE = 7; -const RBDT_DIRECTORY_DEPENDENCIES = 8; -const RBDT_FILE_DEPENDENCIES = 9; - -const INVALID = Symbol("invalid"); - -/** - * @typedef {Object} FileSystemInfoEntry - * @property {number} safeTime - * @property {number=} timestamp - */ - -/** - * @typedef {Object} ResolvedContextFileSystemInfoEntry - * @property {number} safeTime - * @property {string=} timestampHash - */ - -/** - * @typedef {Object} ContextFileSystemInfoEntry - * @property {number} safeTime - * @property {string=} timestampHash - * @property {ResolvedContextFileSystemInfoEntry=} resolved - * @property {Set=} symlinks - */ - -/** - * @typedef {Object} TimestampAndHash - * @property {number} safeTime - * @property {number=} timestamp - * @property {string} hash - */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ /** - * @typedef {Object} ResolvedContextTimestampAndHash - * @property {number} safeTime - * @property {string=} timestampHash - * @property {string} hash + * Module itself is not connected, but transitive modules are connected transitively. */ +const TRANSITIVE_ONLY = Symbol("transitive only"); /** - * @typedef {Object} ContextTimestampAndHash - * @property {number} safeTime - * @property {string=} timestampHash - * @property {string} hash - * @property {ResolvedContextTimestampAndHash=} resolved - * @property {Set=} symlinks + * While determining the active state, this flag is used to signal a circular connection. */ +const CIRCULAR_CONNECTION = Symbol("circular connection"); -/** - * @typedef {Object} ContextHash - * @property {string} hash - * @property {string=} resolved - * @property {Set=} symlinks - */ +/** @typedef {boolean | typeof TRANSITIVE_ONLY | typeof CIRCULAR_CONNECTION} ConnectionState */ /** - * @typedef {Object} SnapshotOptimizationEntry - * @property {Snapshot} snapshot - * @property {number} shared - * @property {Set} snapshotContent - * @property {Set} children + * @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; +}; /** - * @typedef {Object} ResolveBuildDependenciesResult - * @property {Set} files list of files - * @property {Set} directories list of directories - * @property {Set} missing list of missing entries - * @property {Map} resolveResults stored resolve results - * @property {Object} resolveDependencies dependencies of the resolving - * @property {Set} resolveDependencies.files list of files - * @property {Set} resolveDependencies.directories list of directories - * @property {Set} resolveDependencies.missing list of missing entries + * @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; +}; -const DONE_ITERATOR_RESULT = new Set().keys().next(); - -// cspell:word tshs -// Tsh = Timestamp + Hash -// Tshs = Timestamp + Hash combinations +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} */ + this.explanations = undefined; + if (explanation) { + this.explanations = new Set(); + this.explanations.add(explanation); + } + } -class SnapshotIterator { - constructor(next) { - this.next = next; + 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; } -} -class SnapshotIterable { - constructor(snapshot, getMaps) { - this.snapshot = snapshot; - this.getMaps = getMaps; + /** + * @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; + } } - [Symbol.iterator]() { - let state = 0; - /** @type {IterableIterator} */ - let it; - /** @type {(Snapshot) => (Map | Set)[]} */ - let getMaps; - /** @type {(Map | Set)[]} */ - let maps; - /** @type {Snapshot} */ - let snapshot; - let queue; - return new SnapshotIterator(() => { - for (;;) { - switch (state) { - case 0: - snapshot = this.snapshot; - getMaps = this.getMaps; - maps = getMaps(snapshot); - state = 1; - /* falls through */ - case 1: - if (maps.length > 0) { - const map = maps.pop(); - if (map !== undefined) { - it = map.keys(); - state = 2; - } else { - break; - } - } else { - state = 3; - break; - } - /* falls through */ - case 2: { - const result = it.next(); - if (!result.done) return result; - state = 1; - break; - } - case 3: { - const children = snapshot.children; - if (children !== undefined) { - if (children.size === 1) { - // shortcut for a single child - // avoids allocation of queue - for (const child of children) snapshot = child; - maps = getMaps(snapshot); - state = 1; - break; - } - if (queue === undefined) queue = []; - for (const child of children) { - queue.push(child); - } - } - if (queue !== undefined && queue.length > 0) { - snapshot = queue.pop(); - maps = getMaps(snapshot); - state = 1; - break; - } else { - state = 4; - } - } - /* falls through */ - case 4: - return DONE_ITERATOR_RESULT; - } - } - }); + /** + * @param {string} explanation the explanation to add + * @returns {void} + */ + addExplanation(explanation) { + if (this.explanations === undefined) { + this.explanations = new Set(); + } + this.explanations.add(explanation); } -} -class Snapshot { - constructor() { - this._flags = 0; - /** @type {number | undefined} */ - this.startTime = undefined; - /** @type {Map | undefined} */ - this.fileTimestamps = undefined; - /** @type {Map | undefined} */ - this.fileHashes = undefined; - /** @type {Map | undefined} */ - this.fileTshs = undefined; - /** @type {Map | undefined} */ - this.contextTimestamps = undefined; - /** @type {Map | undefined} */ - this.contextHashes = undefined; - /** @type {Map | undefined} */ - this.contextTshs = undefined; - /** @type {Map | undefined} */ - this.missingExistence = undefined; - /** @type {Map | undefined} */ - this.managedItemInfo = undefined; - /** @type {Set | undefined} */ - this.managedFiles = undefined; - /** @type {Set | undefined} */ - this.managedContexts = undefined; - /** @type {Set | undefined} */ - this.managedMissing = undefined; - /** @type {Set | undefined} */ - this.children = undefined; + get explanation() { + if (this.explanations === undefined) return ""; + return Array.from(this.explanations).join(" "); } - hasStartTime() { - return (this._flags & 1) !== 0; + // TODO webpack 5 remove + get active() { + throw new Error("Use getActiveState instead"); } - setStartTime(value) { - this._flags = this._flags | 1; - this.startTime = value; + /** + * @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; } - setMergedStartTime(value, snapshot) { - if (value) { - if (snapshot.hasStartTime()) { - this.setStartTime(Math.min(value, snapshot.startTime)); - } else { - this.setStartTime(value); - } - } else { - if (snapshot.hasStartTime()) this.setStartTime(snapshot.startTime); - } + /** + * @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; } - hasFileTimestamps() { - return (this._flags & 2) !== 0; + /** + * @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); } - setFileTimestamps(value) { - this._flags = this._flags | 2; - this.fileTimestamps = value; + /** + * @param {boolean} value active or not + * @returns {void} + */ + setActive(value) { + this.conditional = false; + this._active = value; } - hasFileHashes() { - return (this._flags & 4) !== 0; + set active(value) { + throw new Error("Use setActive instead"); } +} - setFileHashes(value) { - this._flags = this._flags | 4; - this.fileHashes = value; - } +/** @typedef {typeof TRANSITIVE_ONLY} TRANSITIVE_ONLY */ +/** @typedef {typeof CIRCULAR_CONNECTION} CIRCULAR_CONNECTION */ - hasFileTshs() { - return (this._flags & 8) !== 0; - } +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 +); - setFileTshs(value) { - this._flags = this._flags | 8; - this.fileTshs = value; - } - hasContextTimestamps() { - return (this._flags & 0x10) !== 0; - } +/***/ }), - setContextTimestamps(value) { - this._flags = this._flags | 0x10; - this.contextTimestamps = value; - } +/***/ 3454: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - hasContextHashes() { - return (this._flags & 0x20) !== 0; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - setContextHashes(value) { - this._flags = this._flags | 0x20; - this.contextHashes = value; + + +const { ConcatSource, RawSource, CachedSource } = __webpack_require__(51255); +const { UsageState } = __webpack_require__(63686); +const Template = __webpack_require__(1626); +const JavascriptModulesPlugin = __webpack_require__(89464); + +/** @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; +}; - hasContextTshs() { - return (this._flags & 0x40) !== 0; +/** + * @param {ConcatSource} source output + * @param {string} indent spacing + * @param {ExportsInfo} exportsInfo data + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {RequestShortener} requestShortener requestShortener + * @param {Set} 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++; } - setContextTshs(value) { - this._flags = this._flags | 0x40; - this.contextTshs = value; + // 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 + ); + } } - hasMissingExistence() { - return (this._flags & 0x80) !== 0; + if (alreadyPrintedExports) { + source.add( + Template.toComment( + `${indent}... (${alreadyPrintedExports} already listed exports)` + ) + "\n" + ); } - setMissingExistence(value) { - this._flags = this._flags | 0x80; - this.missingExistence = value; + 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" + ); + } } +}; - hasManagedItemInfo() { - return (this._flags & 0x100) !== 0; +/** @type {WeakMap }>>} */ +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; - setManagedItemInfo(value) { - this._flags = this._flags | 0x100; - this.managedItemInfo = value; + +/***/ }), + +/***/ 32882: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const WebpackError = __webpack_require__(53799); + +/** @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; } +} - hasManagedFiles() { - return (this._flags & 0x200) !== 0; +module.exports = ModuleNotFoundError; + + +/***/ }), + +/***/ 58443: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); + +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; } - setManagedFiles(value) { - this._flags = this._flags | 0x200; - this.managedFiles = value; + serialize(context) { + const { write } = context; + + write(this.error); + + super.serialize(context); } - hasManagedContexts() { - return (this._flags & 0x400) !== 0; + deserialize(context) { + const { read } = context; + + this.error = read(); + + super.deserialize(context); } +} - setManagedContexts(value) { - this._flags = this._flags | 0x400; - this.managedContexts = value; +makeSerializable(ModuleParseError, "webpack/lib/ModuleParseError"); + +module.exports = ModuleParseError; + + +/***/ }), + +/***/ 36418: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +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; } - hasManagedMissing() { - return (this._flags & 0x800) !== 0; + markFactoryStart() { + this.factoryStartTime = Date.now(); } - setManagedMissing(value) { - this._flags = this._flags | 0x800; - this.managedMissing = value; + markFactoryEnd() { + this.factoryEndTime = Date.now(); + this.factory = this.factoryEndTime - this.factoryStartTime; } - hasChildren() { - return (this._flags & 0x1000) !== 0; + markRestoringStart() { + this.restoringStartTime = Date.now(); } - setChildren(value) { - this._flags = this._flags | 0x1000; - this.children = value; + markRestoringEnd() { + this.restoringEndTime = Date.now(); + this.restoring = this.restoringEndTime - this.restoringStartTime; } - addChild(child) { - if (!this.hasChildren()) { - this.setChildren(new Set()); - } - this.children.add(child); + markIntegrationStart() { + this.integrationStartTime = Date.now(); } - serialize({ write }) { - write(this._flags); - if (this.hasStartTime()) write(this.startTime); - if (this.hasFileTimestamps()) write(this.fileTimestamps); - if (this.hasFileHashes()) write(this.fileHashes); - if (this.hasFileTshs()) write(this.fileTshs); - if (this.hasContextTimestamps()) write(this.contextTimestamps); - if (this.hasContextHashes()) write(this.contextHashes); - if (this.hasContextTshs()) write(this.contextTshs); - if (this.hasMissingExistence()) write(this.missingExistence); - if (this.hasManagedItemInfo()) write(this.managedItemInfo); - if (this.hasManagedFiles()) write(this.managedFiles); - if (this.hasManagedContexts()) write(this.managedContexts); - if (this.hasManagedMissing()) write(this.managedMissing); - if (this.hasChildren()) write(this.children); + markIntegrationEnd() { + this.integrationEndTime = Date.now(); + this.integration = this.integrationEndTime - this.integrationStartTime; } - deserialize({ read }) { - this._flags = read(); - if (this.hasStartTime()) this.startTime = read(); - if (this.hasFileTimestamps()) this.fileTimestamps = read(); - if (this.hasFileHashes()) this.fileHashes = read(); - if (this.hasFileTshs()) this.fileTshs = read(); - if (this.hasContextTimestamps()) this.contextTimestamps = read(); - if (this.hasContextHashes()) this.contextHashes = read(); - if (this.hasContextTshs()) this.contextTshs = read(); - if (this.hasMissingExistence()) this.missingExistence = read(); - if (this.hasManagedItemInfo()) this.managedItemInfo = read(); - if (this.hasManagedFiles()) this.managedFiles = read(); - if (this.hasManagedContexts()) this.managedContexts = read(); - if (this.hasManagedMissing()) this.managedMissing = read(); - if (this.hasChildren()) this.children = read(); + markBuildingStart() { + this.buildingStartTime = Date.now(); } - /** - * @param {function(Snapshot): (ReadonlyMap | ReadonlySet)[]} getMaps first - * @returns {Iterable} iterable - */ - _createIterable(getMaps) { - return new SnapshotIterable(this, getMaps); + markBuildingEnd() { + this.buildingEndTime = Date.now(); + this.building = this.buildingEndTime - this.buildingStartTime; } - /** - * @returns {Iterable} iterable - */ - getFileIterable() { - return this._createIterable(s => [ - s.fileTimestamps, - s.fileHashes, - s.fileTshs, - s.managedFiles - ]); + markStoringStart() { + this.storingStartTime = Date.now(); } - /** - * @returns {Iterable} iterable - */ - getContextIterable() { - return this._createIterable(s => [ - s.contextTimestamps, - s.contextHashes, - s.contextTshs, - s.managedContexts - ]); + markStoringEnd() { + this.storingEndTime = Date.now(); + this.storing = this.storingEndTime - this.storingStartTime; } + // This depends on timing so we ignore it for coverage + /* istanbul ignore next */ /** - * @returns {Iterable} iterable + * Merge this profile into another one + * @param {ModuleProfile} realProfile the profile to merge into + * @returns {void} */ - getMissingIterable() { - return this._createIterable(s => [s.missingExistence, s.managedMissing]); + mergeInto(realProfile) { + realProfile.additionalFactories = this.factory; + (realProfile.additionalFactoryTimes = + realProfile.additionalFactoryTimes || []).push({ + start: this.factoryStartTime, + end: this.factoryEndTime + }); } } -makeSerializable(Snapshot, "webpack/lib/FileSystemInfo", "Snapshot"); +module.exports = ModuleProfile; -const MIN_COMMON_SNAPSHOT_SIZE = 3; -/** - * @template T - */ -class SnapshotOptimization { - /** - * @param {function(Snapshot): boolean} has has value - * @param {function(Snapshot): Map | Set} get get value - * @param {function(Snapshot, Map | Set): void} set set value - * @param {boolean=} useStartTime use the start time of snapshots - * @param {boolean=} isSet value is an Set instead of a Map - */ - constructor(has, get, set, useStartTime = true, isSet = false) { - this._has = has; - this._get = get; - this._set = set; - this._useStartTime = useStartTime; - this._isSet = isSet; - /** @type {Map} */ - this._map = new Map(); - this._statItemsShared = 0; - this._statItemsUnshared = 0; - this._statSharedSnapshots = 0; - this._statReusedSharedSnapshots = 0; - } +/***/ }), - getStatisticMessage() { - const total = this._statItemsShared + this._statItemsUnshared; - if (total === 0) return undefined; - return `${ - this._statItemsShared && Math.round((this._statItemsShared * 100) / total) - }% (${this._statItemsShared}/${total}) entries shared via ${ - this._statSharedSnapshots - } shared snapshots (${ - this._statReusedSharedSnapshots + this._statSharedSnapshots - } times referenced)`; - } +/***/ 94560: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - clear() { - this._map.clear(); - this._statItemsShared = 0; - this._statItemsUnshared = 0; - this._statSharedSnapshots = 0; - this._statReusedSharedSnapshots = 0; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @param {Snapshot} newSnapshot snapshot - * @param {Set} capturedFiles files to snapshot/share - * @returns {void} - */ - optimize(newSnapshot, capturedFiles) { - /** - * @param {SnapshotOptimizationEntry} entry optimization entry - * @returns {void} - */ - const increaseSharedAndStoreOptimizationEntry = entry => { - if (entry.children !== undefined) { - entry.children.forEach(increaseSharedAndStoreOptimizationEntry); - } - entry.shared++; - storeOptimizationEntry(entry); - }; - /** - * @param {SnapshotOptimizationEntry} entry optimization entry - * @returns {void} - */ - const storeOptimizationEntry = entry => { - for (const path of entry.snapshotContent) { - const old = this._map.get(path); - if (old.shared < entry.shared) { - this._map.set(path, entry); - } - capturedFiles.delete(path); - } - }; - /** @type {SnapshotOptimizationEntry} */ - let newOptimizationEntry = undefined; - const capturedFilesSize = capturedFiles.size; +const WebpackError = __webpack_require__(53799); - /** @type {Set | undefined} */ - const optimizationEntries = new Set(); +/** @typedef {import("./Module")} Module */ - for (const path of capturedFiles) { - const optimizationEntry = this._map.get(path); - if (optimizationEntry === undefined) { - if (newOptimizationEntry === undefined) { - newOptimizationEntry = { - snapshot: newSnapshot, - shared: 0, - snapshotContent: undefined, - children: undefined - }; - } - this._map.set(path, newOptimizationEntry); - continue; +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 { - optimizationEntries.add(optimizationEntry); + message += err; } + } else { + message += String(err); } - optimizationEntries: for (const optimizationEntry of optimizationEntries) { - const snapshot = optimizationEntry.snapshot; - if (optimizationEntry.shared > 0) { - // It's a shared snapshot - // We can't change it, so we can only use it when all files match - // and startTime is compatible - if ( - this._useStartTime && - newSnapshot.startTime && - (!snapshot.startTime || snapshot.startTime > newSnapshot.startTime) - ) { - continue; - } - const nonSharedFiles = new Set(); - const snapshotContent = optimizationEntry.snapshotContent; - const snapshotEntries = this._get(snapshot); - for (const path of snapshotContent) { - if (!capturedFiles.has(path)) { - if (!snapshotEntries.has(path)) { - // File is not shared and can't be removed from the snapshot - // because it's in a child of the snapshot - continue optimizationEntries; - } - nonSharedFiles.add(path); - continue; - } - } - if (nonSharedFiles.size === 0) { - // The complete snapshot is shared - // add it as child - newSnapshot.addChild(snapshot); - increaseSharedAndStoreOptimizationEntry(optimizationEntry); - this._statReusedSharedSnapshots++; - } else { - // Only a part of the snapshot is shared - const sharedCount = snapshotContent.size - nonSharedFiles.size; - if (sharedCount < MIN_COMMON_SNAPSHOT_SIZE) { - // Common part it too small - continue optimizationEntries; - } - // Extract common timestamps from both snapshots - let commonMap; - if (this._isSet) { - commonMap = new Set(); - for (const path of /** @type {Set} */ (snapshotEntries)) { - if (nonSharedFiles.has(path)) continue; - commonMap.add(path); - snapshotEntries.delete(path); - } - } else { - commonMap = new Map(); - const map = /** @type {Map} */ (snapshotEntries); - for (const [path, value] of map) { - if (nonSharedFiles.has(path)) continue; - commonMap.set(path, value); - snapshotEntries.delete(path); - } - } - // Create and attach snapshot - const commonSnapshot = new Snapshot(); - if (this._useStartTime) { - commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot); - } - this._set(commonSnapshot, commonMap); - newSnapshot.addChild(commonSnapshot); - snapshot.addChild(commonSnapshot); - // Create optimization entry - const newEntry = { - snapshot: commonSnapshot, - shared: optimizationEntry.shared + 1, - snapshotContent: new Set(commonMap.keys()), - children: undefined - }; - if (optimizationEntry.children === undefined) - optimizationEntry.children = new Set(); - optimizationEntry.children.add(newEntry); - storeOptimizationEntry(newEntry); - this._statSharedSnapshots++; - } - } else { - // It's a unshared snapshot - // We can extract a common shared snapshot - // with all common files - const snapshotEntries = this._get(snapshot); - if (snapshotEntries === undefined) { - // Incomplete snapshot, that can't be used - continue optimizationEntries; - } - let commonMap; - if (this._isSet) { - commonMap = new Set(); - const set = /** @type {Set} */ (snapshotEntries); - if (capturedFiles.size < set.size) { - for (const path of capturedFiles) { - if (set.has(path)) commonMap.add(path); - } - } else { - for (const path of set) { - if (capturedFiles.has(path)) commonMap.add(path); - } - } - } else { - commonMap = new Map(); - const map = /** @type {Map} */ (snapshotEntries); - for (const path of capturedFiles) { - const ts = map.get(path); - if (ts === undefined) continue; - commonMap.set(path, ts); - } - } + super(message); - if (commonMap.size < MIN_COMMON_SNAPSHOT_SIZE) { - // Common part it too small - continue optimizationEntries; - } - // Create and attach snapshot - const commonSnapshot = new Snapshot(); - if (this._useStartTime) { - commonSnapshot.setMergedStartTime(newSnapshot.startTime, snapshot); - } - this._set(commonSnapshot, commonMap); - newSnapshot.addChild(commonSnapshot); - snapshot.addChild(commonSnapshot); - // Remove files from snapshot - for (const path of commonMap.keys()) snapshotEntries.delete(path); - const sharedCount = commonMap.size; - this._statItemsUnshared -= sharedCount; - this._statItemsShared += sharedCount; - // Create optimization entry - storeOptimizationEntry({ - snapshot: commonSnapshot, - shared: 2, - snapshotContent: new Set(commonMap.keys()), - children: undefined - }); - this._statSharedSnapshots++; - } - } - const unshared = capturedFiles.size; - this._statItemsUnshared += unshared; - this._statItemsShared += capturedFilesSize - unshared; + this.name = "ModuleRestoreError"; + this.details = details; + this.module = module; + this.error = err; } } -const parseString = str => { - if (str[0] === "'") str = `"${str.slice(1, -1).replace(/"/g, '\\"')}"`; - return JSON.parse(str); -}; +module.exports = ModuleRestoreError; -/* istanbul ignore next */ -/** - * @param {number} mtime mtime - */ -const applyMtime = mtime => { - if (FS_ACCURACY > 1 && mtime % 2 !== 0) FS_ACCURACY = 1; - else if (FS_ACCURACY > 10 && mtime % 20 !== 0) FS_ACCURACY = 10; - else if (FS_ACCURACY > 100 && mtime % 200 !== 0) FS_ACCURACY = 100; - else if (FS_ACCURACY > 1000 && mtime % 2000 !== 0) FS_ACCURACY = 1000; -}; -/** - * @template T - * @template K - * @param {Map} a source map - * @param {Map} b joining map - * @returns {Map} joined map - */ -const mergeMaps = (a, b) => { - if (!b || b.size === 0) return a; - if (!a || a.size === 0) return b; - const map = new Map(a); - for (const [key, value] of b) { - map.set(key, value); - } - return map; -}; +/***/ }), -/** - * @template T - * @template K - * @param {Set} a source map - * @param {Set} b joining map - * @returns {Set} joined map - */ -const mergeSets = (a, b) => { - if (!b || b.size === 0) return a; - if (!a || a.size === 0) return b; - const map = new Set(a); - for (const item of b) { - map.add(item); - } - return map; -}; +/***/ 59001: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * Finding file or directory to manage - * @param {string} managedPath path that is managing by {@link FileSystemInfo} - * @param {string} path path to file or directory - * @returns {string|null} managed item - * @example - * getManagedItem( - * '/Users/user/my-project/node_modules/', - * '/Users/user/my-project/node_modules/package/index.js' - * ) === '/Users/user/my-project/node_modules/package' - * getManagedItem( - * '/Users/user/my-project/node_modules/', - * '/Users/user/my-project/node_modules/package1/node_modules/package2' - * ) === '/Users/user/my-project/node_modules/package1/node_modules/package2' - * getManagedItem( - * '/Users/user/my-project/node_modules/', - * '/Users/user/my-project/node_modules/.bin/script.js' - * ) === null // hidden files are disallowed as managed items - * getManagedItem( - * '/Users/user/my-project/node_modules/', - * '/Users/user/my-project/node_modules/package' - * ) === '/Users/user/my-project/node_modules/package' - */ -const getManagedItem = (managedPath, path) => { - let i = managedPath.length; - let slashes = 1; - let startingPosition = true; - loop: while (i < path.length) { - switch (path.charCodeAt(i)) { - case 47: // slash - case 92: // backslash - if (--slashes === 0) break loop; - startingPosition = true; - break; - case 46: // . - // hidden files are disallowed as managed items - // it's probably .yarn-integrity or .cache - if (startingPosition) return null; - break; - case 64: // @ - if (!startingPosition) return null; - slashes++; - break; - default: - startingPosition = false; - break; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const WebpackError = __webpack_require__(53799); + +/** @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); } - i++; + + super(message); + + this.name = "ModuleStoreError"; + this.details = details; + this.module = module; + this.error = err; } - if (i === path.length) slashes--; - // return null when path is incomplete - if (slashes !== 0) return null; - // if (path.slice(i + 1, i + 13) === "node_modules") - if ( - path.length >= i + 13 && - path.charCodeAt(i + 1) === 110 && - path.charCodeAt(i + 2) === 111 && - path.charCodeAt(i + 3) === 100 && - path.charCodeAt(i + 4) === 101 && - path.charCodeAt(i + 5) === 95 && - path.charCodeAt(i + 6) === 109 && - path.charCodeAt(i + 7) === 111 && - path.charCodeAt(i + 8) === 100 && - path.charCodeAt(i + 9) === 117 && - path.charCodeAt(i + 10) === 108 && - path.charCodeAt(i + 11) === 101 && - path.charCodeAt(i + 12) === 115 - ) { - // if this is the end of the path - if (path.length === i + 13) { - // return the node_modules directory - // it's special - return path; +} + +module.exports = ModuleStoreError; + + +/***/ }), + +/***/ 62677: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const util = __webpack_require__(73837); +const memoize = __webpack_require__(78676); + +/** @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(() => + __webpack_require__(89464) +); + +// 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; + + +/***/ }), + +/***/ 11234: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { cleanUp } = __webpack_require__(59985); +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); + +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 += ": "; } - const c = path.charCodeAt(i + 13); - // if next symbol is slash or backslash - if (c === 47 || c === 92) { - // Managed subpath - return getManagedItem(path.slice(0, i + 14), path); + + 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; } - return path.slice(0, i); -}; + + 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; + + +/***/ }), + +/***/ 33370: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const asyncLib = __webpack_require__(78175); +const { SyncHook, MultiHook } = __webpack_require__(6967); + +const ConcurrentCompilationError = __webpack_require__(95735); +const MultiStats = __webpack_require__(24170); +const MultiWatching = __webpack_require__(81128); +const ArrayQueue = __webpack_require__(41792); + +/** @template T @typedef {import("tapable").AsyncSeriesHook} AsyncSeriesHook */ +/** @template T @template R @typedef {import("tapable").SyncBailHook} SyncBailHook */ +/** @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 {ContextFileSystemInfoEntry | ContextTimestampAndHash} T - * @param {T} entry entry - * @returns {T["resolved"] | undefined} the resolved entry + * @template T + * @callback Callback + * @param {(Error | null)=} err + * @param {T=} result */ -const getResolvedTimestamp = entry => { - if (entry === null) return null; - if (entry.resolved !== undefined) return entry.resolved; - return entry.symlinks === undefined ? entry : undefined; -}; /** - * @param {ContextHash} entry entry - * @returns {string | undefined} the resolved entry + * @callback RunWithDependenciesHandler + * @param {Compiler} compiler + * @param {Callback} callback */ -const getResolvedHash = entry => { - if (entry === null) return null; - if (entry.resolved !== undefined) return entry.resolved; - return entry.symlinks === undefined ? entry.hash : undefined; -}; - -const addAll = (source, target) => { - for (const key of source) target.add(key); -}; /** - * Used to access information about the filesystem in a cached way + * @typedef {Object} MultiCompilerOptions + * @property {number=} parallelism how many Compilers are allows to run at the same time in parallel */ -class FileSystemInfo { + +module.exports = class MultiCompiler { /** - * @param {InputFileSystem} fs file system - * @param {Object} options options - * @param {Iterable=} options.managedPaths paths that are only managed by a package manager - * @param {Iterable=} options.immutablePaths paths that are immutable - * @param {Logger=} options.logger logger used to log invalid snapshots - * @param {string | Hash=} options.hashFunction the hash function to use + * @param {Compiler[] | Record} compilers child compilers + * @param {MultiCompilerOptions} options options */ - constructor( - fs, - { - managedPaths = [], - immutablePaths = [], - logger, - hashFunction = "md4" - } = {} - ) { - this.fs = fs; - this.logger = logger; - this._remainingLogs = logger ? 40 : 0; - this._loggedPaths = logger ? new Set() : undefined; - this._hashFunction = hashFunction; - /** @type {WeakMap} */ - this._snapshotCache = new WeakMap(); - this._fileTimestampsOptimization = new SnapshotOptimization( - s => s.hasFileTimestamps(), - s => s.fileTimestamps, - (s, v) => s.setFileTimestamps(v) - ); - this._fileHashesOptimization = new SnapshotOptimization( - s => s.hasFileHashes(), - s => s.fileHashes, - (s, v) => s.setFileHashes(v), - false - ); - this._fileTshsOptimization = new SnapshotOptimization( - s => s.hasFileTshs(), - s => s.fileTshs, - (s, v) => s.setFileTshs(v) - ); - this._contextTimestampsOptimization = new SnapshotOptimization( - s => s.hasContextTimestamps(), - s => s.contextTimestamps, - (s, v) => s.setContextTimestamps(v) - ); - this._contextHashesOptimization = new SnapshotOptimization( - s => s.hasContextHashes(), - s => s.contextHashes, - (s, v) => s.setContextHashes(v), - false - ); - this._contextTshsOptimization = new SnapshotOptimization( - s => s.hasContextTshs(), - s => s.contextTshs, - (s, v) => s.setContextTshs(v) - ); - this._missingExistenceOptimization = new SnapshotOptimization( - s => s.hasMissingExistence(), - s => s.missingExistence, - (s, v) => s.setMissingExistence(v), - false - ); - this._managedItemInfoOptimization = new SnapshotOptimization( - s => s.hasManagedItemInfo(), - s => s.managedItemInfo, - (s, v) => s.setManagedItemInfo(v), - false - ); - this._managedFilesOptimization = new SnapshotOptimization( - s => s.hasManagedFiles(), - s => s.managedFiles, - (s, v) => s.setManagedFiles(v), - false, - true - ); - this._managedContextsOptimization = new SnapshotOptimization( - s => s.hasManagedContexts(), - s => s.managedContexts, - (s, v) => s.setManagedContexts(v), - false, - true - ); - this._managedMissingOptimization = new SnapshotOptimization( - s => s.hasManagedMissing(), - s => s.managedMissing, - (s, v) => s.setManagedMissing(v), - false, - true - ); - /** @type {StackedCacheMap} */ - this._fileTimestamps = new StackedCacheMap(); - /** @type {Map} */ - this._fileHashes = new Map(); - /** @type {Map} */ - this._fileTshs = new Map(); - /** @type {StackedCacheMap} */ - this._contextTimestamps = new StackedCacheMap(); - /** @type {Map} */ - this._contextHashes = new Map(); - /** @type {Map} */ - this._contextTshs = new Map(); - /** @type {Map} */ - this._managedItems = new Map(); - /** @type {AsyncQueue} */ - this.fileTimestampQueue = new AsyncQueue({ - name: "file timestamp", - parallelism: 30, - processor: this._readFileTimestamp.bind(this) - }); - /** @type {AsyncQueue} */ - this.fileHashQueue = new AsyncQueue({ - name: "file hash", - parallelism: 10, - processor: this._readFileHash.bind(this) - }); - /** @type {AsyncQueue} */ - this.contextTimestampQueue = new AsyncQueue({ - name: "context timestamp", - parallelism: 2, - processor: this._readContextTimestamp.bind(this) - }); - /** @type {AsyncQueue} */ - this.contextHashQueue = new AsyncQueue({ - name: "context hash", - parallelism: 2, - processor: this._readContextHash.bind(this) - }); - /** @type {AsyncQueue} */ - this.contextTshQueue = new AsyncQueue({ - name: "context hash and timestamp", - parallelism: 2, - processor: this._readContextTimestampAndHash.bind(this) - }); - /** @type {AsyncQueue} */ - this.managedItemQueue = new AsyncQueue({ - name: "managed item info", - parallelism: 10, - processor: this._getManagedItemInfo.bind(this) - }); - /** @type {AsyncQueue>} */ - this.managedItemDirectoryQueue = new AsyncQueue({ - name: "managed item directory info", - parallelism: 10, - processor: this._getManagedItemDirectoryInfo.bind(this) - }); - this.managedPaths = Array.from(managedPaths); - this.managedPathsWithSlash = /** @type {string[]} */ ( - this.managedPaths.filter(p => typeof p === "string") - ).map(p => join(fs, p, "_").slice(0, -1)); - - this.managedPathsRegExps = /** @type {RegExp[]} */ ( - this.managedPaths.filter(p => typeof p !== "string") - ); - this.immutablePaths = Array.from(immutablePaths); - this.immutablePathsWithSlash = /** @type {string[]} */ ( - this.immutablePaths.filter(p => typeof p === "string") - ).map(p => join(fs, p, "_").slice(0, -1)); - this.immutablePathsRegExps = /** @type {RegExp[]} */ ( - this.immutablePaths.filter(p => typeof p !== "string") - ); - - this._cachedDeprecatedFileTimestamps = undefined; - this._cachedDeprecatedContextTimestamps = undefined; + constructor(compilers, options) { + if (!Array.isArray(compilers)) { + compilers = Object.keys(compilers).map(name => { + compilers[name].name = name; + return compilers[name]; + }); + } - this._warnAboutExperimentalEsmTracking = false; + this.hooks = Object.freeze({ + /** @type {SyncHook<[MultiStats]>} */ + done: new SyncHook(["stats"]), + /** @type {MultiHook>} */ + invalid: new MultiHook(compilers.map(c => c.hooks.invalid)), + /** @type {MultiHook>} */ + run: new MultiHook(compilers.map(c => c.hooks.run)), + /** @type {SyncHook<[]>} */ + watchClose: new SyncHook([]), + /** @type {MultiHook>} */ + watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)), + /** @type {MultiHook>} */ + infrastructureLog: new MultiHook( + compilers.map(c => c.hooks.infrastructureLog) + ) + }); + this.compilers = compilers; + /** @type {MultiCompilerOptions} */ + this._options = { + parallelism: options.parallelism || Infinity + }; + /** @type {WeakMap} */ + this.dependencies = new WeakMap(); + this.running = false; - this._statCreatedSnapshots = 0; - this._statTestedSnapshotsCached = 0; - this._statTestedSnapshotsNotCached = 0; - this._statTestedChildrenCached = 0; - this._statTestedChildrenNotCached = 0; - this._statTestedEntries = 0; + /** @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; + 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)); + } + }); + compiler.hooks.invalid.tap("MultiCompiler", () => { + if (compilerDone) { + compilerDone = false; + doneCompilers--; + } + }); + } } - logStatistics() { - const logWhenMessage = (header, message) => { - if (message) { - this.logger.log(`${header}: ${message}`); - } - }; - this.logger.log(`${this._statCreatedSnapshots} new snapshots created`); - this.logger.log( - `${ - this._statTestedSnapshotsNotCached && - Math.round( - (this._statTestedSnapshotsNotCached * 100) / - (this._statTestedSnapshotsCached + - this._statTestedSnapshotsNotCached) - ) - }% root snapshot uncached (${this._statTestedSnapshotsNotCached} / ${ - this._statTestedSnapshotsCached + this._statTestedSnapshotsNotCached - })` - ); - this.logger.log( - `${ - this._statTestedChildrenNotCached && - Math.round( - (this._statTestedChildrenNotCached * 100) / - (this._statTestedChildrenCached + this._statTestedChildrenNotCached) - ) - }% children snapshot uncached (${this._statTestedChildrenNotCached} / ${ - this._statTestedChildrenCached + this._statTestedChildrenNotCached - })` - ); - this.logger.log(`${this._statTestedEntries} entries tested`); - this.logger.log( - `File info in cache: ${this._fileTimestamps.size} timestamps ${this._fileHashes.size} hashes ${this._fileTshs.size} timestamp hash combinations` - ); - logWhenMessage( - `File timestamp snapshot optimization`, - this._fileTimestampsOptimization.getStatisticMessage() - ); - logWhenMessage( - `File hash snapshot optimization`, - this._fileHashesOptimization.getStatisticMessage() - ); - logWhenMessage( - `File timestamp hash combination snapshot optimization`, - this._fileTshsOptimization.getStatisticMessage() - ); - this.logger.log( - `Directory info in cache: ${this._contextTimestamps.size} timestamps ${this._contextHashes.size} hashes ${this._contextTshs.size} timestamp hash combinations` - ); - logWhenMessage( - `Directory timestamp snapshot optimization`, - this._contextTimestampsOptimization.getStatisticMessage() - ); - logWhenMessage( - `Directory hash snapshot optimization`, - this._contextHashesOptimization.getStatisticMessage() - ); - logWhenMessage( - `Directory timestamp hash combination snapshot optimization`, - this._contextTshsOptimization.getStatisticMessage() - ); - logWhenMessage( - `Missing items snapshot optimization`, - this._missingExistenceOptimization.getStatisticMessage() - ); - this.logger.log( - `Managed items info in cache: ${this._managedItems.size} items` - ); - logWhenMessage( - `Managed items snapshot optimization`, - this._managedItemInfoOptimization.getStatisticMessage() - ); - logWhenMessage( - `Managed files snapshot optimization`, - this._managedFilesOptimization.getStatisticMessage() - ); - logWhenMessage( - `Managed contexts snapshot optimization`, - this._managedContextsOptimization.getStatisticMessage() - ); - logWhenMessage( - `Managed missing snapshot optimization`, - this._managedMissingOptimization.getStatisticMessage() + get options() { + return Object.assign( + this.compilers.map(c => c.options), + this._options ); } - _log(path, reason, ...args) { - const key = path + reason; - if (this._loggedPaths.has(key)) return; - this._loggedPaths.add(key); - this.logger.debug(`${path} invalidated because ${reason}`, ...args); - if (--this._remainingLogs === 0) { - this.logger.debug( - "Logging limit has been reached and no further logging will be emitted by FileSystemInfo" - ); + 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; } - clear() { - this._remainingLogs = this.logger ? 40 : 0; - if (this._loggedPaths !== undefined) this._loggedPaths.clear(); + get inputFileSystem() { + throw new Error("Cannot read inputFileSystem of a MultiCompiler"); + } - this._snapshotCache = new WeakMap(); - this._fileTimestampsOptimization.clear(); - this._fileHashesOptimization.clear(); - this._fileTshsOptimization.clear(); - this._contextTimestampsOptimization.clear(); - this._contextHashesOptimization.clear(); - this._contextTshsOptimization.clear(); - this._missingExistenceOptimization.clear(); - this._managedItemInfoOptimization.clear(); - this._managedFilesOptimization.clear(); - this._managedContextsOptimization.clear(); - this._managedMissingOptimization.clear(); - this._fileTimestamps.clear(); - this._fileHashes.clear(); - this._fileTshs.clear(); - this._contextTimestamps.clear(); - this._contextHashes.clear(); - this._contextTshs.clear(); - this._managedItems.clear(); - this._managedItems.clear(); + get outputFileSystem() { + throw new Error("Cannot read outputFileSystem of a MultiCompiler"); + } - this._cachedDeprecatedFileTimestamps = undefined; - this._cachedDeprecatedContextTimestamps = undefined; + get watchFileSystem() { + throw new Error("Cannot read watchFileSystem of a MultiCompiler"); + } - this._statCreatedSnapshots = 0; - this._statTestedSnapshotsCached = 0; - this._statTestedSnapshotsNotCached = 0; - this._statTestedChildrenCached = 0; - this._statTestedChildrenNotCached = 0; - this._statTestedEntries = 0; + get intermediateFileSystem() { + throw new Error("Cannot read outputFileSystem of a MultiCompiler"); } /** - * @param {ReadonlyMap} map timestamps - * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it - * @returns {void} + * @param {InputFileSystem} value the new input file system */ - addFileTimestamps(map, immutable) { - this._fileTimestamps.addAll(map, immutable); - this._cachedDeprecatedFileTimestamps = undefined; + set inputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.inputFileSystem = value; + } } /** - * @param {ReadonlyMap} map timestamps - * @param {boolean=} immutable if 'map' is immutable and FileSystemInfo can keep referencing it - * @returns {void} + * @param {OutputFileSystem} value the new output file system */ - addContextTimestamps(map, immutable) { - this._contextTimestamps.addAll(map, immutable); - this._cachedDeprecatedContextTimestamps = undefined; + set outputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.outputFileSystem = value; + } } /** - * @param {string} path file path - * @param {function((WebpackError | null)=, (FileSystemInfoEntry | "ignore" | null)=): void} callback callback function - * @returns {void} + * @param {WatchFileSystem} value the new watch file system */ - getFileTimestamp(path, callback) { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) return callback(null, cache); - this.fileTimestampQueue.add(path, callback); + set watchFileSystem(value) { + for (const compiler of this.compilers) { + compiler.watchFileSystem = value; + } } /** - * @param {string} path context path - * @param {function((WebpackError | null)=, (ResolvedContextFileSystemInfoEntry | "ignore" | null)=): void} callback callback function - * @returns {void} + * @param {IntermediateFileSystem} value the new intermediate file system */ - getContextTimestamp(path, callback) { - const cache = this._contextTimestamps.get(path); - if (cache !== undefined) { - if (cache === "ignore") return callback(null, "ignore"); - const resolved = getResolvedTimestamp(cache); - if (resolved !== undefined) return callback(null, resolved); - return this._resolveContextTimestamp(cache, callback); + set intermediateFileSystem(value) { + for (const compiler of this.compilers) { + compiler.intermediateFileSystem = value; } - this.contextTimestampQueue.add(path, (err, entry) => { - if (err) return callback(err); - const resolved = getResolvedTimestamp(entry); - if (resolved !== undefined) return callback(null, resolved); - this._resolveContextTimestamp(entry, callback); - }); } - /** - * @param {string} path context path - * @param {function((WebpackError | null)=, (ContextFileSystemInfoEntry | "ignore" | null)=): void} callback callback function - * @returns {void} - */ - _getUnresolvedContextTimestamp(path, callback) { - const cache = this._contextTimestamps.get(path); - if (cache !== undefined) return callback(null, cache); - this.contextTimestampQueue.add(path, callback); + getInfrastructureLogger(name) { + return this.compilers[0].getInfrastructureLogger(name); } /** - * @param {string} path file path - * @param {function((WebpackError | null)=, string=): void} callback callback function + * @param {Compiler} compiler the child compiler + * @param {string[]} dependencies its dependencies * @returns {void} */ - getFileHash(path, callback) { - const cache = this._fileHashes.get(path); - if (cache !== undefined) return callback(null, cache); - this.fileHashQueue.add(path, callback); + setDependencies(compiler, dependencies) { + this.dependencies.set(compiler, dependencies); } /** - * @param {string} path context path - * @param {function((WebpackError | null)=, string=): void} callback callback function - * @returns {void} + * @param {Callback} callback signals when the validation is complete + * @returns {boolean} true if the dependencies are valid */ - getContextHash(path, callback) { - const cache = this._contextHashes.get(path); - if (cache !== undefined) { - const resolved = getResolvedHash(cache); - if (resolved !== undefined) return callback(null, resolved); - return this._resolveContextHash(cache, callback); + 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 + }); + } + } + } } - this.contextHashQueue.add(path, (err, entry) => { - if (err) return callback(err); - const resolved = getResolvedHash(entry); - if (resolved !== undefined) return callback(null, resolved); - this._resolveContextHash(entry, callback); - }); + /** @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 /** - * @param {string} path context path - * @param {function((WebpackError | null)=, ContextHash=): void} callback callback function + * @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} callback the compiler's handler * @returns {void} */ - _getUnresolvedContextHash(path, callback) { - const cache = this._contextHashes.get(path); - if (cache !== undefined) return callback(null, cache); - this.contextHashQueue.add(path, callback); + 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); } /** - * @param {string} path context path - * @param {function((WebpackError | null)=, ResolvedContextTimestampAndHash=): void} callback callback function - * @returns {void} + * @template SetupResult + * @param {function(Compiler, number, Callback, function(): boolean, function(): void, function(): void): SetupResult} setup setup a single compiler + * @param {function(Compiler, SetupResult, Callback): void} run run/continue a single compiler + * @param {Callback} callback callback when all compilers are done, result includes Stats of all changed compilers + * @returns {SetupResult[]} result of setup */ - getContextTsh(path, callback) { - const cache = this._contextTshs.get(path); - if (cache !== undefined) { - const resolved = getResolvedTimestamp(cache); - if (resolved !== undefined) return callback(null, resolved); - return this._resolveContextTsh(cache, callback); - } - this.contextTshQueue.add(path, (err, entry) => { - if (err) return callback(err); - const resolved = getResolvedTimestamp(entry); - if (resolved !== undefined) return callback(null, resolved); - this._resolveContextTsh(entry, callback); - }); - } + _runGraph(setup, run, callback) { + /** @typedef {{ compiler: Compiler, setupResult: SetupResult, result: Stats, state: "pending" | "blocked" | "queued" | "starting" | "running" | "running-outdated" | "done", children: Node[], parents: Node[] }} Node */ - /** - * @param {string} path context path - * @param {function((WebpackError | null)=, ContextTimestampAndHash=): void} callback callback function - * @returns {void} - */ - _getUnresolvedContextTsh(path, callback) { - const cache = this._contextTshs.get(path); - if (cache !== undefined) return callback(null, cache); - this.contextTshQueue.add(path, callback); - } + // State transitions for nodes: + // -> blocked (initial) + // blocked -> starting [running++] (when all parents done) + // queued -> starting [running++] (when processing the queue) + // starting -> running (when run has been called) + // running -> done [running--] (when compilation is done) + // done -> pending (when invalidated from file change) + // pending -> blocked [add to queue] (when invalidated from aggregated changes) + // done -> blocked [add to queue] (when invalidated, from parent invalidation) + // running -> running-outdated (when invalidated, either from change or parent invalidation) + // running-outdated -> blocked [running--] (when compilation is done) - _createBuildDependenciesResolvers() { - const resolveContext = createResolver({ - resolveToContext: true, - exportsFields: [], - fileSystem: this.fs - }); - const resolveCjs = createResolver({ - extensions: [".js", ".json", ".node"], - conditionNames: ["require", "node"], - exportsFields: ["exports"], - fileSystem: this.fs - }); - const resolveCjsAsChild = createResolver({ - extensions: [".js", ".json", ".node"], - conditionNames: ["require", "node"], - exportsFields: [], - fileSystem: this.fs - }); - const resolveEsm = createResolver({ - extensions: [".js", ".json", ".node"], - fullySpecified: true, - conditionNames: ["import", "node"], - exportsFields: ["exports"], - fileSystem: this.fs - }); - return { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild }; - } - - /** - * @param {string} context context directory - * @param {Iterable} deps dependencies - * @param {function((Error | null)=, ResolveBuildDependenciesResult=): void} callback callback function - * @returns {void} - */ - resolveBuildDependencies(context, deps, callback) { - const { resolveContext, resolveEsm, resolveCjs, resolveCjsAsChild } = - this._createBuildDependenciesResolvers(); - - /** @type {Set} */ - const files = new Set(); - /** @type {Set} */ - const fileSymlinks = new Set(); - /** @type {Set} */ - const directories = new Set(); - /** @type {Set} */ - const directorySymlinks = new Set(); - /** @type {Set} */ - const missing = new Set(); - /** @type {Set} */ - const resolveFiles = new Set(); - /** @type {Set} */ - const resolveDirectories = new Set(); - /** @type {Set} */ - const resolveMissing = new Set(); - /** @type {Map} */ - const resolveResults = new Map(); - const invalidResolveResults = new Set(); - const resolverContext = { - fileDependencies: resolveFiles, - contextDependencies: resolveDirectories, - missingDependencies: resolveMissing + /** @type {Node[]} */ + const nodes = this.compilers.map(compiler => ({ + compiler, + setupResult: undefined, + result: undefined, + state: "blocked", + children: [], + parents: [] + })); + /** @type {Map} */ + 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); + } + } + /** @type {ArrayQueue} */ + 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) { + if (child.state === "blocked") queue.enqueue(child); + } + } else if (node.state === "running-outdated") { + node.state = "blocked"; + queue.enqueue(node); + } + processQueue(); }; - const expectedToString = expected => { - return expected ? ` (expected ${expected})` : ""; + /** + * @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); + } }; - const jobToString = job => { - switch (job.type) { - case RBDT_RESOLVE_CJS: - return `resolve commonjs ${job.path}${expectedToString( - job.expected - )}`; - case RBDT_RESOLVE_ESM: - return `resolve esm ${job.path}${expectedToString(job.expected)}`; - case RBDT_RESOLVE_DIRECTORY: - return `resolve directory ${job.path}`; - case RBDT_RESOLVE_CJS_FILE: - return `resolve commonjs file ${job.path}${expectedToString( - job.expected - )}`; - case RBDT_RESOLVE_ESM_FILE: - return `resolve esm file ${job.path}${expectedToString( - job.expected - )}`; - case RBDT_DIRECTORY: - return `directory ${job.path}`; - case RBDT_FILE: - return `file ${job.path}`; - case RBDT_DIRECTORY_DEPENDENCIES: - return `directory dependencies ${job.path}`; - case RBDT_FILE_DEPENDENCIES: - return `file dependencies ${job.path}`; + /** + * @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); } - return `unknown ${job.type} ${job.path}`; }; - const pathToString = job => { - let result = ` at ${jobToString(job)}`; - job = job.issuer; - while (job !== undefined) { - result += `\n at ${jobToString(job)}`; - job = job.issuer; + /** + * @param {Node} node node + * @returns {void} + */ + const nodeChange = node => { + nodeInvalid(node); + if (node.state === "pending") { + node.state = "blocked"; + } + if (node.state === "blocked") { + queue.enqueue(node); + processQueue(); } - return result; }; - processAsyncTree( - Array.from(deps, dep => ({ - type: RBDT_RESOLVE_CJS, - context, - path: dep, - expected: undefined, - issuer: undefined - })), - 20, - (job, push, callback) => { - const { type, context, path, expected } = job; - const resolveDirectory = path => { - const key = `d\n${context}\n${path}`; - if (resolveResults.has(key)) { - return callback(); - } - resolveResults.set(key, undefined); - resolveContext(context, path, resolverContext, (err, _, result) => { - if (err) { - if (expected === false) { - resolveResults.set(key, false); - return callback(); - } - invalidResolveResults.add(key); - err.message += `\nwhile resolving '${path}' in ${context} to a directory`; - return callback(err); - } - const resultPath = result.path; - resolveResults.set(key, resultPath); - push({ - type: RBDT_DIRECTORY, - context: undefined, - path: resultPath, - expected: undefined, - issuer: job - }); - callback(); - }); - }; - const resolveFile = (path, symbol, resolve) => { - const key = `${symbol}\n${context}\n${path}`; - if (resolveResults.has(key)) { - return callback(); - } - resolveResults.set(key, undefined); - resolve(context, path, resolverContext, (err, _, result) => { - if (typeof expected === "string") { - if (!err && result && result.path === expected) { - resolveResults.set(key, result.path); - } else { - invalidResolveResults.add(key); - this.logger.warn( - `Resolving '${path}' in ${context} for build dependencies doesn't lead to expected result '${expected}', but to '${ - err || (result && result.path) - }' instead. Resolving dependencies are ignored for this path.\n${pathToString( - job - )}` - ); - } - } else { - if (err) { - if (expected === false) { - resolveResults.set(key, false); - return callback(); - } - invalidResolveResults.add(key); - err.message += `\nwhile resolving '${path}' in ${context} as file\n${pathToString( - job - )}`; - return callback(err); - } - const resultPath = result.path; - resolveResults.set(key, resultPath); - push({ - type: RBDT_FILE, - context: undefined, - path: resultPath, - expected: undefined, - issuer: job - }); - } - callback(); - }); - }; - switch (type) { - case RBDT_RESOLVE_CJS: { - const isDirectory = /[\\/]$/.test(path); - if (isDirectory) { - resolveDirectory(path.slice(0, path.length - 1)); - } else { - resolveFile(path, "f", resolveCjs); - } - break; - } - case RBDT_RESOLVE_ESM: { - const isDirectory = /[\\/]$/.test(path); - if (isDirectory) { - resolveDirectory(path.slice(0, path.length - 1)); - } else { - resolveFile(path); - } - break; - } - case RBDT_RESOLVE_DIRECTORY: { - resolveDirectory(path); - break; - } - case RBDT_RESOLVE_CJS_FILE: { - resolveFile(path, "f", resolveCjs); - break; - } - case RBDT_RESOLVE_CJS_FILE_AS_CHILD: { - resolveFile(path, "c", resolveCjsAsChild); - break; - } - case RBDT_RESOLVE_ESM_FILE: { - resolveFile(path, "e", resolveEsm); - break; - } - case RBDT_FILE: { - if (files.has(path)) { - callback(); - break; - } - files.add(path); - this.fs.realpath(path, (err, _realPath) => { - if (err) return callback(err); - const realPath = /** @type {string} */ (_realPath); - if (realPath !== path) { - fileSymlinks.add(path); - resolveFiles.add(path); - if (files.has(realPath)) return callback(); - files.add(realPath); - } - push({ - type: RBDT_FILE_DEPENDENCIES, - context: undefined, - path: realPath, - expected: undefined, - issuer: job - }); - callback(); - }); - break; - } - case RBDT_DIRECTORY: { - if (directories.has(path)) { - callback(); - break; - } - directories.add(path); - this.fs.realpath(path, (err, _realPath) => { - if (err) return callback(err); - const realPath = /** @type {string} */ (_realPath); - if (realPath !== path) { - directorySymlinks.add(path); - resolveFiles.add(path); - if (directories.has(realPath)) return callback(); - directories.add(realPath); - } - push({ - type: RBDT_DIRECTORY_DEPENDENCIES, - context: undefined, - path: realPath, - expected: undefined, - issuer: job - }); - callback(); - }); - break; - } - case RBDT_FILE_DEPENDENCIES: { - // Check for known files without dependencies - if (/\.json5?$|\.yarn-integrity$|yarn\.lock$|\.ya?ml/.test(path)) { - process.nextTick(callback); - break; - } - // Check commonjs cache for the module - /** @type {NodeModule} */ - const module = require.cache[path]; - if (module && Array.isArray(module.children)) { - children: for (const child of module.children) { - let childPath = child.filename; - if (childPath) { - push({ - type: RBDT_FILE, - context: undefined, - path: childPath, - expected: undefined, - issuer: job - }); - const context = dirname(this.fs, path); - for (const modulePath of module.paths) { - if (childPath.startsWith(modulePath)) { - let subPath = childPath.slice(modulePath.length + 1); - const packageMatch = /^(@[^\\/]+[\\/])[^\\/]+/.exec( - subPath - ); - if (packageMatch) { - push({ - type: RBDT_FILE, - context: undefined, - path: - modulePath + - childPath[modulePath.length] + - packageMatch[0] + - childPath[modulePath.length] + - "package.json", - expected: false, - issuer: job - }); - } - let request = subPath.replace(/\\/g, "/"); - if (request.endsWith(".js")) - request = request.slice(0, -3); - push({ - type: RBDT_RESOLVE_CJS_FILE_AS_CHILD, - context, - path: request, - expected: child.filename, - issuer: job - }); - continue children; - } - } - let request = relative(this.fs, context, childPath); - if (request.endsWith(".js")) request = request.slice(0, -3); - request = request.replace(/\\/g, "/"); - if (!request.startsWith("../")) request = `./${request}`; - push({ - type: RBDT_RESOLVE_CJS_FILE, - context, - path: request, - expected: child.filename, - issuer: job - }); - } - } - } else if (supportsEsm && /\.m?js$/.test(path)) { - if (!this._warnAboutExperimentalEsmTracking) { - this.logger.log( - "Node.js doesn't offer a (nice) way to introspect the ESM dependency graph yet.\n" + - "Until a full solution is available webpack uses an experimental ESM tracking based on parsing.\n" + - "As best effort webpack parses the ESM files to guess dependencies. But this can lead to expensive and incorrect tracking." - ); - this._warnAboutExperimentalEsmTracking = true; - } - const lexer = __webpack_require__(54392); - lexer.init.then(() => { - this.fs.readFile(path, (err, content) => { - if (err) return callback(err); - try { - const context = dirname(this.fs, path); - const source = content.toString(); - const [imports] = lexer.parse(source); - for (const imp of imports) { - try { - let dependency; - if (imp.d === -1) { - // import ... from "..." - dependency = parseString( - source.substring(imp.s - 1, imp.e + 1) - ); - } else if (imp.d > -1) { - // import() - let expr = source.substring(imp.s, imp.e).trim(); - dependency = parseString(expr); - } else { - // e.g. import.meta - continue; - } - push({ - type: RBDT_RESOLVE_ESM_FILE, - context, - path: dependency, - expected: undefined, - issuer: job - }); - } catch (e) { - this.logger.warn( - `Parsing of ${path} for build dependencies failed at 'import(${source.substring( - imp.s, - imp.e - )})'.\n` + - "Build dependencies behind this expression are ignored and might cause incorrect cache invalidation." - ); - this.logger.debug(pathToString(job)); - this.logger.debug(e.stack); - } - } - } catch (e) { - this.logger.warn( - `Parsing of ${path} for build dependencies failed and all dependencies of this file are ignored, which might cause incorrect cache invalidation..` - ); - this.logger.debug(pathToString(job)); - this.logger.debug(e.stack); - } - process.nextTick(callback); - }); - }, callback); - break; - } else { - this.logger.log( - `Assuming ${path} has no dependencies as we were unable to assign it to any module system.` - ); - this.logger.debug(pathToString(job)); - } - process.nextTick(callback); - break; - } - case RBDT_DIRECTORY_DEPENDENCIES: { - const match = - /(^.+[\\/]node_modules[\\/](?:@[^\\/]+[\\/])?[^\\/]+)/.exec(path); - const packagePath = match ? match[1] : path; - const packageJson = join(this.fs, packagePath, "package.json"); - this.fs.readFile(packageJson, (err, content) => { - if (err) { - if (err.code === "ENOENT") { - resolveMissing.add(packageJson); - const parent = dirname(this.fs, packagePath); - if (parent !== packagePath) { - push({ - type: RBDT_DIRECTORY_DEPENDENCIES, - context: undefined, - path: parent, - expected: undefined, - issuer: job - }); - } - callback(); - return; - } - return callback(err); - } - resolveFiles.add(packageJson); - let packageData; - try { - packageData = JSON.parse(content.toString("utf-8")); - } catch (e) { - return callback(e); - } - const depsObject = packageData.dependencies; - const optionalDepsObject = packageData.optionalDependencies; - const allDeps = new Set(); - const optionalDeps = new Set(); - if (typeof depsObject === "object" && depsObject) { - for (const dep of Object.keys(depsObject)) { - allDeps.add(dep); - } - } - if ( - typeof optionalDepsObject === "object" && - optionalDepsObject - ) { - for (const dep of Object.keys(optionalDepsObject)) { - allDeps.add(dep); - optionalDeps.add(dep); - } - } - for (const dep of allDeps) { - push({ - type: RBDT_RESOLVE_DIRECTORY, - context: packagePath, - path: dep, - expected: !optionalDeps.has(dep), - issuer: job - }); - } - callback(); - }); - break; - } + + const setupResults = []; + nodes.forEach((node, i) => { + setupResults.push( + (node.setupResult = setup( + node.compiler, + i, + nodeDone.bind(null, node), + () => node.state !== "starting" && node.state !== "running", + () => nodeChange(node), + () => nodeInvalid(node) + )) + ); + }); + let processing = true; + const processQueue = () => { + if (processing) return; + processing = true; + process.nextTick(processQueueWorker); + }; + const processQueueWorker = () => { + while (running < parallelism && queue.length > 0 && !errored) { + const node = queue.dequeue(); + if ( + node.state === "queued" || + (node.state === "blocked" && + node.parents.every(p => p.state === "done")) + ) { + running++; + node.state = "starting"; + run(node.compiler, node.setupResult, nodeDone.bind(null, node)); + node.state = "running"; } - }, - err => { - if (err) return callback(err); - for (const l of fileSymlinks) files.delete(l); - for (const l of directorySymlinks) directories.delete(l); - for (const k of invalidResolveResults) resolveResults.delete(k); - callback(null, { - files, - directories, - missing, - resolveResults, - resolveDependencies: { - files: resolveFiles, - directories: resolveDirectories, - missing: resolveMissing + } + processing = false; + if ( + !errored && + running === 0 && + nodes.every(node => node.state === "done") + ) { + const stats = []; + for (const node of nodes) { + const result = node.result; + if (result) { + node.result = undefined; + stats.push(result); } - }); + } + if (stats.length > 0) { + callback(null, new MultiStats(stats)); + } } - ); + }; + processQueueWorker(); + return setupResults; } /** - * @param {Map} resolveResults results from resolving - * @param {function((Error | null)=, boolean=): void} callback callback with true when resolveResults resolve the same way + * @param {WatchOptions|WatchOptions[]} watchOptions the watcher's options + * @param {Callback} handler signals when the call finishes + * @returns {MultiWatching} a compiler watcher + */ + watch(watchOptions, handler) { + if (this.running) { + return handler(new ConcurrentCompilationError()); + } + this.running = true; + + if (this.validateDependencies(handler)) { + const watchings = this._runGraph( + (compiler, idx, callback, isBlocked, setChanged, setInvalid) => { + const watching = compiler.watch( + Array.isArray(watchOptions) ? watchOptions[idx] : watchOptions, + callback + ); + if (watching) { + watching._onInvalid = setInvalid; + watching._onChange = setChanged; + watching._isBlocked = isBlocked; + } + return watching; + }, + (compiler, watching, callback) => { + if (compiler.watching !== watching) return; + if (!watching.running) watching.invalidate(); + }, + handler + ); + return new MultiWatching(watchings, this); + } + + return new MultiWatching([], this); + } + + /** + * @param {Callback} callback signals when the call finishes * @returns {void} */ - checkResolveResultsValid(resolveResults, callback) { - const { resolveCjs, resolveCjsAsChild, resolveEsm, resolveContext } = - this._createBuildDependenciesResolvers(); - asyncLib.eachLimit( - resolveResults, - 20, - ([key, expectedResult], callback) => { - const [type, context, path] = key.split("\n"); - switch (type) { - case "d": - resolveContext(context, path, {}, (err, _, result) => { - if (expectedResult === false) - return callback(err ? undefined : INVALID); - if (err) return callback(err); - const resultPath = result.path; - if (resultPath !== expectedResult) return callback(INVALID); - callback(); - }); - break; - case "f": - resolveCjs(context, path, {}, (err, _, result) => { - if (expectedResult === false) - return callback(err ? undefined : INVALID); - if (err) return callback(err); - const resultPath = result.path; - if (resultPath !== expectedResult) return callback(INVALID); - callback(); - }); - break; - case "c": - resolveCjsAsChild(context, path, {}, (err, _, result) => { - if (expectedResult === false) - return callback(err ? undefined : INVALID); - if (err) return callback(err); - const resultPath = result.path; - if (resultPath !== expectedResult) return callback(INVALID); - callback(); - }); - break; - case "e": - resolveEsm(context, path, {}, (err, _, result) => { - if (expectedResult === false) - return callback(err ? undefined : INVALID); - if (err) return callback(err); - const resultPath = result.path; - if (resultPath !== expectedResult) return callback(INVALID); - callback(); - }); - break; - default: - callback(new Error("Unexpected type in resolve result key")); - break; - } - }, - /** - * @param {Error | typeof INVALID=} err error or invalid flag - * @returns {void} - */ - err => { - if (err === INVALID) { - return callback(null, false); - } - if (err) { - return callback(err); + run(callback) { + if (this.running) { + return callback(new ConcurrentCompilationError()); + } + this.running = true; + + if (this.validateDependencies(callback)) { + this._runGraph( + () => {}, + (compiler, setupResult, callback) => compiler.run(callback), + (err, stats) => { + this.running = false; + + if (callback !== undefined) { + return callback(err, stats); + } } - return callback(null, true); + ); + } + } + + purgeInputFileSystem() { + for (const compiler of this.compilers) { + if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { + compiler.inputFileSystem.purge(); } - ); + } } /** - * - * @param {number} startTime when processing the files has started - * @param {Iterable} files all files - * @param {Iterable} directories all directories - * @param {Iterable} missing all missing files or directories - * @param {Object} options options object (for future extensions) - * @param {boolean=} options.hash should use hash to snapshot - * @param {boolean=} options.timestamp should use timestamp to snapshot - * @param {function((WebpackError | null)=, (Snapshot | null)=): void} callback callback function + * @param {Callback} callback signals when the compiler closes * @returns {void} */ - createSnapshot(startTime, files, directories, missing, options, callback) { - /** @type {Map} */ - const fileTimestamps = new Map(); - /** @type {Map} */ - const fileHashes = new Map(); - /** @type {Map} */ - const fileTshs = new Map(); - /** @type {Map} */ - const contextTimestamps = new Map(); - /** @type {Map} */ - const contextHashes = new Map(); - /** @type {Map} */ - const contextTshs = new Map(); - /** @type {Map} */ - const missingExistence = new Map(); - /** @type {Map} */ - const managedItemInfo = new Map(); - /** @type {Set} */ - const managedFiles = new Set(); - /** @type {Set} */ - const managedContexts = new Set(); - /** @type {Set} */ - const managedMissing = new Set(); - /** @type {Set} */ - const children = new Set(); + close(callback) { + asyncLib.each( + this.compilers, + (compiler, callback) => { + compiler.close(callback); + }, + callback + ); + } +}; - const snapshot = new Snapshot(); - if (startTime) snapshot.setStartTime(startTime); - /** @type {Set} */ - const managedItems = new Set(); +/***/ }), - /** 1 = timestamp, 2 = hash, 3 = timestamp + hash */ - const mode = options && options.hash ? (options.timestamp ? 3 : 2) : 1; +/***/ 24170: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - let jobs = 1; - const jobDone = () => { - if (--jobs === 0) { - if (fileTimestamps.size !== 0) { - snapshot.setFileTimestamps(fileTimestamps); - } - if (fileHashes.size !== 0) { - snapshot.setFileHashes(fileHashes); - } - if (fileTshs.size !== 0) { - snapshot.setFileTshs(fileTshs); - } - if (contextTimestamps.size !== 0) { - snapshot.setContextTimestamps(contextTimestamps); - } - if (contextHashes.size !== 0) { - snapshot.setContextHashes(contextHashes); - } - if (contextTshs.size !== 0) { - snapshot.setContextTshs(contextTshs); - } - if (missingExistence.size !== 0) { - snapshot.setMissingExistence(missingExistence); - } - if (managedItemInfo.size !== 0) { - snapshot.setManagedItemInfo(managedItemInfo); - } - this._managedFilesOptimization.optimize(snapshot, managedFiles); - if (managedFiles.size !== 0) { - snapshot.setManagedFiles(managedFiles); - } - this._managedContextsOptimization.optimize(snapshot, managedContexts); - if (managedContexts.size !== 0) { - snapshot.setManagedContexts(managedContexts); - } - this._managedMissingOptimization.optimize(snapshot, managedMissing); - if (managedMissing.size !== 0) { - snapshot.setManagedMissing(managedMissing); - } - if (children.size !== 0) { - snapshot.setChildren(children); - } - this._snapshotCache.set(snapshot, true); - this._statCreatedSnapshots++; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - callback(null, snapshot); - } + + +const identifierUtils = __webpack_require__(82186); + +/** @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 }; - const jobError = () => { - if (jobs > 0) { - // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8) - jobs = -100000000; - callback(null, null); - } + } + + /** + * @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 + }; }; - const checkManaged = (path, managedSet) => { - for (const immutablePath of this.immutablePathsRegExps) { - if (immutablePath.test(path)) { - managedSet.add(path); - return true; + if (options.errors) { + obj.errors = []; + for (const j of obj.children) { + for (const i of j.errors) { + obj.errors.push(mapError(j, i)); } } - for (const immutablePath of this.immutablePathsWithSlash) { - if (path.startsWith(immutablePath)) { - managedSet.add(path); - return true; + } + if (options.warnings) { + obj.warnings = []; + for (const j of obj.children) { + for (const i of j.warnings) { + obj.warnings.push(mapError(j, i)); } } - for (const managedPath of this.managedPathsRegExps) { - const match = managedPath.exec(path); - if (match) { - const managedItem = getManagedItem(match[1], path); - if (managedItem) { - managedItems.add(managedItem); - managedSet.add(path); - return true; - } - } + } + if (options.errorsCount) { + obj.errorsCount = 0; + for (const j of obj.children) { + obj.errorsCount += j.errorsCount; } - for (const managedPath of this.managedPathsWithSlash) { - if (path.startsWith(managedPath)) { - const managedItem = getManagedItem(managedPath, path); - if (managedItem) { - managedItems.add(managedItem); - managedSet.add(path); - return true; - } - } - } - return false; - }; - const captureNonManaged = (items, managedSet) => { - const capturedItems = new Set(); - for (const path of items) { - if (!checkManaged(path, managedSet)) capturedItems.add(path); - } - return capturedItems; - }; - const processCapturedFiles = capturedFiles => { - switch (mode) { - case 3: - this._fileTshsOptimization.optimize(snapshot, capturedFiles); - for (const path of capturedFiles) { - const cache = this._fileTshs.get(path); - if (cache !== undefined) { - fileTshs.set(path, cache); - } else { - jobs++; - this._getFileTimestampAndHash(path, (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting file timestamp hash combination of ${path}: ${err.stack}` - ); - } - jobError(); - } else { - fileTshs.set(path, entry); - jobDone(); - } - }); - } - } - break; - case 2: - this._fileHashesOptimization.optimize(snapshot, capturedFiles); - for (const path of capturedFiles) { - const cache = this._fileHashes.get(path); - if (cache !== undefined) { - fileHashes.set(path, cache); - } else { - jobs++; - this.fileHashQueue.add(path, (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting file hash of ${path}: ${err.stack}` - ); - } - jobError(); - } else { - fileHashes.set(path, entry); - jobDone(); - } - }); - } - } - break; - case 1: - this._fileTimestampsOptimization.optimize(snapshot, capturedFiles); - for (const path of capturedFiles) { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) { - if (cache !== "ignore") { - fileTimestamps.set(path, cache); - } - } else { - jobs++; - this.fileTimestampQueue.add(path, (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting file timestamp of ${path}: ${err.stack}` - ); - } - jobError(); - } else { - fileTimestamps.set(path, entry); - jobDone(); - } - }); - } - } - break; - } - }; - if (files) { - processCapturedFiles(captureNonManaged(files, managedFiles)); - } - const processCapturedDirectories = capturedDirectories => { - switch (mode) { - case 3: - this._contextTshsOptimization.optimize(snapshot, capturedDirectories); - for (const path of capturedDirectories) { - const cache = this._contextTshs.get(path); - /** @type {ResolvedContextTimestampAndHash} */ - let resolved; - if ( - cache !== undefined && - (resolved = getResolvedTimestamp(cache)) !== undefined - ) { - contextTshs.set(path, resolved); - } else { - jobs++; - /** - * @param {Error=} err error - * @param {ResolvedContextTimestampAndHash=} entry entry - * @returns {void} - */ - const callback = (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting context timestamp hash combination of ${path}: ${err.stack}` - ); - } - jobError(); - } else { - contextTshs.set(path, entry); - jobDone(); - } - }; - if (cache !== undefined) { - this._resolveContextTsh(cache, callback); - } else { - this.getContextTsh(path, callback); - } - } - } - break; - case 2: - this._contextHashesOptimization.optimize( - snapshot, - capturedDirectories - ); - for (const path of capturedDirectories) { - const cache = this._contextHashes.get(path); - let resolved; - if ( - cache !== undefined && - (resolved = getResolvedHash(cache)) !== undefined - ) { - contextHashes.set(path, resolved); - } else { - jobs++; - const callback = (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting context hash of ${path}: ${err.stack}` - ); - } - jobError(); - } else { - contextHashes.set(path, entry); - jobDone(); - } - }; - if (cache !== undefined) { - this._resolveContextHash(cache, callback); - } else { - this.getContextHash(path, callback); - } - } - } - break; - case 1: - this._contextTimestampsOptimization.optimize( - snapshot, - capturedDirectories - ); - for (const path of capturedDirectories) { - const cache = this._contextTimestamps.get(path); - if (cache === "ignore") continue; - let resolved; - if ( - cache !== undefined && - (resolved = getResolvedTimestamp(cache)) !== undefined - ) { - contextTimestamps.set(path, resolved); - } else { - jobs++; - /** - * @param {Error=} err error - * @param {ResolvedContextFileSystemInfoEntry=} entry entry - * @returns {void} - */ - const callback = (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting context timestamp of ${path}: ${err.stack}` - ); - } - jobError(); - } else { - contextTimestamps.set(path, entry); - jobDone(); - } - }; - if (cache !== undefined) { - this._resolveContextTimestamp(cache, callback); - } else { - this.getContextTimestamp(path, callback); - } - } - } - break; - } - }; - if (directories) { - processCapturedDirectories( - captureNonManaged(directories, managedContexts) - ); - } - const processCapturedMissing = capturedMissing => { - this._missingExistenceOptimization.optimize(snapshot, capturedMissing); - for (const path of capturedMissing) { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) { - if (cache !== "ignore") { - missingExistence.set(path, Boolean(cache)); - } - } else { - jobs++; - this.fileTimestampQueue.add(path, (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting missing timestamp of ${path}: ${err.stack}` - ); - } - jobError(); - } else { - missingExistence.set(path, Boolean(entry)); - jobDone(); - } - }); - } - } - }; - if (missing) { - processCapturedMissing(captureNonManaged(missing, managedMissing)); } - this._managedItemInfoOptimization.optimize(snapshot, managedItems); - for (const path of managedItems) { - const cache = this._managedItems.get(path); - if (cache !== undefined) { - if (!cache.startsWith("*")) { - managedFiles.add(join(this.fs, path, "package.json")); - } else if (cache === "*nested") { - managedMissing.add(join(this.fs, path, "package.json")); - } - managedItemInfo.set(path, cache); - } else { - jobs++; - this.managedItemQueue.add(path, (err, entry) => { - if (err) { - if (this.logger) { - this.logger.debug( - `Error snapshotting managed item ${path}: ${err.stack}` - ); - } - jobError(); - } else if (entry) { - if (!entry.startsWith("*")) { - managedFiles.add(join(this.fs, path, "package.json")); - } else if (cache === "*nested") { - managedMissing.add(join(this.fs, path, "package.json")); - } - managedItemInfo.set(path, entry); - jobDone(); - } else { - // Fallback to normal snapshotting - const process = (set, fn) => { - if (set.size === 0) return; - const captured = new Set(); - for (const file of set) { - if (file.startsWith(path)) captured.add(file); - } - if (captured.size > 0) fn(captured); - }; - process(managedFiles, processCapturedFiles); - process(managedContexts, processCapturedDirectories); - process(managedMissing, processCapturedMissing); - jobDone(); - } - }); + if (options.warningsCount) { + obj.warningsCount = 0; + for (const j of obj.children) { + obj.warningsCount += j.warningsCount; } } - jobDone(); + 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; + +/***/ }), + +/***/ 81128: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const asyncLib = __webpack_require__(78175); + +/** @typedef {import("./MultiCompiler")} MultiCompiler */ +/** @typedef {import("./Watching")} Watching */ + +/** + * @template T + * @callback Callback + * @param {(Error | null)=} err + * @param {T=} result + */ + +class MultiWatching { /** - * @param {Snapshot} snapshot1 a snapshot - * @param {Snapshot} snapshot2 a snapshot - * @returns {Snapshot} merged snapshot + * @param {Watching[]} watchings child compilers' watchers + * @param {MultiCompiler} compiler the compiler */ - mergeSnapshots(snapshot1, snapshot2) { - const snapshot = new Snapshot(); - if (snapshot1.hasStartTime() && snapshot2.hasStartTime()) - snapshot.setStartTime(Math.min(snapshot1.startTime, snapshot2.startTime)); - else if (snapshot2.hasStartTime()) snapshot.startTime = snapshot2.startTime; - else if (snapshot1.hasStartTime()) snapshot.startTime = snapshot1.startTime; - if (snapshot1.hasFileTimestamps() || snapshot2.hasFileTimestamps()) { - snapshot.setFileTimestamps( - mergeMaps(snapshot1.fileTimestamps, snapshot2.fileTimestamps) - ); - } - if (snapshot1.hasFileHashes() || snapshot2.hasFileHashes()) { - snapshot.setFileHashes( - mergeMaps(snapshot1.fileHashes, snapshot2.fileHashes) - ); - } - if (snapshot1.hasFileTshs() || snapshot2.hasFileTshs()) { - snapshot.setFileTshs(mergeMaps(snapshot1.fileTshs, snapshot2.fileTshs)); - } - if (snapshot1.hasContextTimestamps() || snapshot2.hasContextTimestamps()) { - snapshot.setContextTimestamps( - mergeMaps(snapshot1.contextTimestamps, snapshot2.contextTimestamps) - ); - } - if (snapshot1.hasContextHashes() || snapshot2.hasContextHashes()) { - snapshot.setContextHashes( - mergeMaps(snapshot1.contextHashes, snapshot2.contextHashes) - ); - } - if (snapshot1.hasContextTshs() || snapshot2.hasContextTshs()) { - snapshot.setContextTshs( - mergeMaps(snapshot1.contextTshs, snapshot2.contextTshs) - ); - } - if (snapshot1.hasMissingExistence() || snapshot2.hasMissingExistence()) { - snapshot.setMissingExistence( - mergeMaps(snapshot1.missingExistence, snapshot2.missingExistence) - ); - } - if (snapshot1.hasManagedItemInfo() || snapshot2.hasManagedItemInfo()) { - snapshot.setManagedItemInfo( - mergeMaps(snapshot1.managedItemInfo, snapshot2.managedItemInfo) - ); - } - if (snapshot1.hasManagedFiles() || snapshot2.hasManagedFiles()) { - snapshot.setManagedFiles( - mergeSets(snapshot1.managedFiles, snapshot2.managedFiles) - ); - } - if (snapshot1.hasManagedContexts() || snapshot2.hasManagedContexts()) { - snapshot.setManagedContexts( - mergeSets(snapshot1.managedContexts, snapshot2.managedContexts) - ); - } - if (snapshot1.hasManagedMissing() || snapshot2.hasManagedMissing()) { - snapshot.setManagedMissing( - mergeSets(snapshot1.managedMissing, snapshot2.managedMissing) + 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(); + } } - if (snapshot1.hasChildren() || snapshot2.hasChildren()) { - snapshot.setChildren(mergeSets(snapshot1.children, snapshot2.children)); - } - if ( - this._snapshotCache.get(snapshot1) === true && - this._snapshotCache.get(snapshot2) === true - ) { - this._snapshotCache.set(snapshot, true); + } + + suspend() { + for (const watching of this.watchings) { + watching.suspend(); } - return snapshot; } - /** - * @param {Snapshot} snapshot the snapshot made - * @param {function((WebpackError | null)=, boolean=): void} callback callback function - * @returns {void} - */ - checkSnapshotValid(snapshot, callback) { - const cachedResult = this._snapshotCache.get(snapshot); - if (cachedResult !== undefined) { - this._statTestedSnapshotsCached++; - if (typeof cachedResult === "boolean") { - callback(null, cachedResult); - } else { - cachedResult.push(callback); - } - return; + resume() { + for (const watching of this.watchings) { + watching.resume(); } - this._statTestedSnapshotsNotCached++; - this._checkSnapshotValidNoCache(snapshot, callback); } /** - * @param {Snapshot} snapshot the snapshot made - * @param {function((WebpackError | null)=, boolean=): void} callback callback function + * @param {Callback} callback signals when the watcher is closed * @returns {void} */ - _checkSnapshotValidNoCache(snapshot, callback) { - /** @type {number | undefined} */ - let startTime = undefined; - if (snapshot.hasStartTime()) { - startTime = snapshot.startTime; - } - let jobs = 1; - const jobDone = () => { - if (--jobs === 0) { - this._snapshotCache.set(snapshot, true); - callback(null, true); - } - }; - const invalid = () => { - if (jobs > 0) { - // large negative number instead of NaN or something else to keep jobs to stay a SMI (v8) - jobs = -100000000; - this._snapshotCache.set(snapshot, false); - callback(null, false); - } - }; - const invalidWithError = (path, err) => { - if (this._remainingLogs > 0) { - this._log(path, `error occurred: %s`, err); - } - invalid(); - }; - /** - * @param {string} path file path - * @param {string} current current hash - * @param {string} snap snapshot hash - * @returns {boolean} true, if ok - */ - const checkHash = (path, current, snap) => { - if (current !== snap) { - // If hash differ it's invalid - if (this._remainingLogs > 0) { - this._log(path, `hashes differ (%s != %s)`, current, snap); - } - return false; - } - return true; - }; - /** - * @param {string} path file path - * @param {boolean} current current entry - * @param {boolean} snap entry from snapshot - * @returns {boolean} true, if ok - */ - const checkExistence = (path, current, snap) => { - if (!current !== !snap) { - // If existence of item differs - // it's invalid - if (this._remainingLogs > 0) { - this._log( - path, - current ? "it didn't exist before" : "it does no longer exist" - ); - } - return false; - } - return true; - }; - /** - * @param {string} path file path - * @param {FileSystemInfoEntry} current current entry - * @param {FileSystemInfoEntry} snap entry from snapshot - * @param {boolean} log log reason - * @returns {boolean} true, if ok - */ - const checkFile = (path, current, snap, log = true) => { - if (current === snap) return true; - if (!checkExistence(path, Boolean(current), Boolean(snap))) return false; - if (current) { - // For existing items only - if (typeof startTime === "number" && current.safeTime > startTime) { - // If a change happened after starting reading the item - // this may no longer be valid - if (log && this._remainingLogs > 0) { - this._log( - path, - `it may have changed (%d) after the start time of the snapshot (%d)`, - current.safeTime, - startTime - ); - } - return false; - } - if ( - snap.timestamp !== undefined && - current.timestamp !== snap.timestamp - ) { - // If we have a timestamp (it was a file or symlink) and it differs from current timestamp - // it's invalid - if (log && this._remainingLogs > 0) { - this._log( - path, - `timestamps differ (%d != %d)`, - current.timestamp, - snap.timestamp - ); - } - return false; - } - } - return true; - }; - /** - * @param {string} path file path - * @param {ResolvedContextFileSystemInfoEntry} current current entry - * @param {ResolvedContextFileSystemInfoEntry} snap entry from snapshot - * @param {boolean} log log reason - * @returns {boolean} true, if ok - */ - const checkContext = (path, current, snap, log = true) => { - if (current === snap) return true; - if (!checkExistence(path, Boolean(current), Boolean(snap))) return false; - if (current) { - // For existing items only - if (typeof startTime === "number" && current.safeTime > startTime) { - // If a change happened after starting reading the item - // this may no longer be valid - if (log && this._remainingLogs > 0) { - this._log( - path, - `it may have changed (%d) after the start time of the snapshot (%d)`, - current.safeTime, - startTime - ); - } - return false; - } - if ( - snap.timestampHash !== undefined && - current.timestampHash !== snap.timestampHash - ) { - // If we have a timestampHash (it was a directory) and it differs from current timestampHash - // it's invalid - if (log && this._remainingLogs > 0) { - this._log( - path, - `timestamps hashes differ (%s != %s)`, - current.timestampHash, - snap.timestampHash - ); - } - return false; - } - } - return true; - }; - if (snapshot.hasChildren()) { - const childCallback = (err, result) => { - if (err || !result) return invalid(); - else jobDone(); - }; - for (const child of snapshot.children) { - const cache = this._snapshotCache.get(child); - if (cache !== undefined) { - this._statTestedChildrenCached++; - /* istanbul ignore else */ - if (typeof cache === "boolean") { - if (cache === false) { - invalid(); - return; - } - } else { - jobs++; - cache.push(childCallback); - } - } else { - this._statTestedChildrenNotCached++; - jobs++; - this._checkSnapshotValidNoCache(child, childCallback); - } - } - } - if (snapshot.hasFileTimestamps()) { - const { fileTimestamps } = snapshot; - this._statTestedEntries += fileTimestamps.size; - for (const [path, ts] of fileTimestamps) { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) { - if (cache !== "ignore" && !checkFile(path, cache, ts)) { - invalid(); - return; - } - } else { - jobs++; - this.fileTimestampQueue.add(path, (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkFile(path, entry, ts)) { - invalid(); - } else { - jobDone(); - } - }); - } - } - } - const processFileHashSnapshot = (path, hash) => { - const cache = this._fileHashes.get(path); - if (cache !== undefined) { - if (cache !== "ignore" && !checkHash(path, cache, hash)) { - invalid(); - return; - } - } else { - jobs++; - this.fileHashQueue.add(path, (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkHash(path, entry, hash)) { - invalid(); - } else { - jobDone(); - } - }); - } - }; - if (snapshot.hasFileHashes()) { - const { fileHashes } = snapshot; - this._statTestedEntries += fileHashes.size; - for (const [path, hash] of fileHashes) { - processFileHashSnapshot(path, hash); - } - } - if (snapshot.hasFileTshs()) { - const { fileTshs } = snapshot; - this._statTestedEntries += fileTshs.size; - for (const [path, tsh] of fileTshs) { - if (typeof tsh === "string") { - processFileHashSnapshot(path, tsh); - } else { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) { - if (cache === "ignore" || !checkFile(path, cache, tsh, false)) { - processFileHashSnapshot(path, tsh && tsh.hash); - } - } else { - jobs++; - this.fileTimestampQueue.add(path, (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkFile(path, entry, tsh, false)) { - processFileHashSnapshot(path, tsh && tsh.hash); - } - jobDone(); - }); - } - } - } - } - if (snapshot.hasContextTimestamps()) { - const { contextTimestamps } = snapshot; - this._statTestedEntries += contextTimestamps.size; - for (const [path, ts] of contextTimestamps) { - const cache = this._contextTimestamps.get(path); - if (cache === "ignore") continue; - let resolved; - if ( - cache !== undefined && - (resolved = getResolvedTimestamp(cache)) !== undefined - ) { - if (!checkContext(path, resolved, ts)) { - invalid(); - return; - } - } else { - jobs++; - /** - * @param {Error=} err error - * @param {ResolvedContextFileSystemInfoEntry=} entry entry - * @returns {void} - */ - const callback = (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkContext(path, entry, ts)) { - invalid(); - } else { - jobDone(); - } - }; - if (cache !== undefined) { - this._resolveContextTimestamp(cache, callback); - } else { - this.getContextTimestamp(path, callback); - } - } - } - } - const processContextHashSnapshot = (path, hash) => { - const cache = this._contextHashes.get(path); - let resolved; - if ( - cache !== undefined && - (resolved = getResolvedHash(cache)) !== undefined - ) { - if (!checkHash(path, resolved, hash)) { - invalid(); - return; - } - } else { - jobs++; - const callback = (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkHash(path, entry, hash)) { - invalid(); - } else { - jobDone(); - } - }; - if (cache !== undefined) { - this._resolveContextHash(cache, callback); - } else { - this.getContextHash(path, callback); - } - } - }; - if (snapshot.hasContextHashes()) { - const { contextHashes } = snapshot; - this._statTestedEntries += contextHashes.size; - for (const [path, hash] of contextHashes) { - processContextHashSnapshot(path, hash); - } - } - if (snapshot.hasContextTshs()) { - const { contextTshs } = snapshot; - this._statTestedEntries += contextTshs.size; - for (const [path, tsh] of contextTshs) { - if (typeof tsh === "string") { - processContextHashSnapshot(path, tsh); - } else { - const cache = this._contextTimestamps.get(path); - if (cache === "ignore") continue; - let resolved; - if ( - cache !== undefined && - (resolved = getResolvedTimestamp(cache)) !== undefined - ) { - if (!checkContext(path, resolved, tsh, false)) { - processContextHashSnapshot(path, tsh && tsh.hash); - } - } else { - jobs++; - /** - * @param {Error=} err error - * @param {ResolvedContextFileSystemInfoEntry=} entry entry - * @returns {void} - */ - const callback = (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkContext(path, entry, tsh, false)) { - processContextHashSnapshot(path, tsh && tsh.hash); - } - jobDone(); - }; - if (cache !== undefined) { - this._resolveContextTimestamp(cache, callback); - } else { - this.getContextTimestamp(path, callback); - } - } - } - } - } - if (snapshot.hasMissingExistence()) { - const { missingExistence } = snapshot; - this._statTestedEntries += missingExistence.size; - for (const [path, existence] of missingExistence) { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) { - if ( - cache !== "ignore" && - !checkExistence(path, Boolean(cache), Boolean(existence)) - ) { - invalid(); - return; - } - } else { - jobs++; - this.fileTimestampQueue.add(path, (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkExistence(path, Boolean(entry), Boolean(existence))) { - invalid(); - } else { - jobDone(); - } - }); - } - } - } - if (snapshot.hasManagedItemInfo()) { - const { managedItemInfo } = snapshot; - this._statTestedEntries += managedItemInfo.size; - for (const [path, info] of managedItemInfo) { - const cache = this._managedItems.get(path); - if (cache !== undefined) { - if (!checkHash(path, cache, info)) { - invalid(); - return; - } - } else { - jobs++; - this.managedItemQueue.add(path, (err, entry) => { - if (err) return invalidWithError(path, err); - if (!checkHash(path, entry, info)) { - invalid(); - } else { - jobDone(); - } - }); + 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); } } - } - jobDone(); - - // if there was an async action - // try to join multiple concurrent request for this snapshot - if (jobs > 0) { - const callbacks = [callback]; - callback = (err, result) => { - for (const callback of callbacks) callback(err, result); - }; - this._snapshotCache.set(snapshot, callbacks); - } + ); } +} - _readFileTimestamp(path, callback) { - this.fs.stat(path, (err, stat) => { - if (err) { - if (err.code === "ENOENT") { - this._fileTimestamps.set(path, null); - this._cachedDeprecatedFileTimestamps = undefined; - return callback(null, null); - } - return callback(err); - } +module.exports = MultiWatching; - let ts; - if (stat.isDirectory()) { - ts = { - safeTime: 0, - timestamp: undefined - }; - } else { - const mtime = +stat.mtime; - if (mtime) applyMtime(mtime); +/***/ }), - ts = { - safeTime: mtime ? mtime + FS_ACCURACY : Infinity, - timestamp: mtime - }; - } +/***/ 50169: +/***/ (function(module) { - this._fileTimestamps.set(path, ts); - this._cachedDeprecatedFileTimestamps = undefined; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - callback(null, ts); + + +/** @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; + }); }); } +} - _readFileHash(path, callback) { - this.fs.readFile(path, (err, content) => { - if (err) { - if (err.code === "EISDIR") { - this._fileHashes.set(path, "directory"); - return callback(null, "directory"); - } - if (err.code === "ENOENT") { - this._fileHashes.set(path, null); - return callback(null, null); - } - if (err.code === "ERR_FS_FILE_TOO_LARGE") { - this.logger.warn(`Ignoring ${path} for hashing as it's very large`); - this._fileHashes.set(path, "too large"); - return callback(null, "too large"); - } - return callback(err); - } +module.exports = NoEmitOnErrorsPlugin; - const hash = createHash(this._hashFunction); - hash.update(content); +/***/ }), - const digest = /** @type {string} */ (hash.digest("hex")); +/***/ 80832: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - this._fileHashes.set(path, digest); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - callback(null, digest); - }); - } - _getFileTimestampAndHash(path, callback) { - const continueWithHash = hash => { - const cache = this._fileTimestamps.get(path); - if (cache !== undefined) { - if (cache !== "ignore") { - const result = { - ...cache, - hash - }; - this._fileTshs.set(path, result); - return callback(null, result); - } else { - this._fileTshs.set(path, hash); - return callback(null, hash); - } - } else { - this.fileTimestampQueue.add(path, (err, entry) => { - if (err) { - return callback(err); - } - const result = { - ...entry, - hash - }; - this._fileTshs.set(path, result); - return callback(null, result); - }); - } - }; - const cache = this._fileHashes.get(path); - if (cache !== undefined) { - continueWithHash(cache); - } else { - this.fileHashQueue.add(path, (err, entry) => { - if (err) { - return callback(err); - } - continueWithHash(entry); - }); - } - } - - /** - * @template T - * @template ItemType - * @param {Object} options options - * @param {string} options.path path - * @param {function(string): ItemType} options.fromImmutablePath called when context item is an immutable path - * @param {function(string): ItemType} options.fromManagedItem called when context item is a managed path - * @param {function(string, string, function(Error=, ItemType=): void): void} options.fromSymlink called when context item is a symlink - * @param {function(string, IStats, function(Error=, ItemType=): void): void} options.fromFile called when context item is a file - * @param {function(string, IStats, function(Error=, ItemType=): void): void} options.fromDirectory called when context item is a directory - * @param {function(string[], ItemType[]): T} options.reduce called from all context items - * @param {function((Error | null)=, (T)=): void} callback callback - */ - _readContext( - { - path, - fromImmutablePath, - fromManagedItem, - fromSymlink, - fromFile, - fromDirectory, - reduce - }, - callback - ) { - this.fs.readdir(path, (err, _files) => { - if (err) { - if (err.code === "ENOENT") { - return callback(null, null); - } - return callback(err); - } - const files = /** @type {string[]} */ (_files) - .map(file => file.normalize("NFC")) - .filter(file => !/^\./.test(file)) - .sort(); - asyncLib.map( - files, - (file, callback) => { - const child = join(this.fs, path, file); - for (const immutablePath of this.immutablePathsRegExps) { - if (immutablePath.test(path)) { - // ignore any immutable path for timestamping - return callback(null, fromImmutablePath(path)); - } - } - for (const immutablePath of this.immutablePathsWithSlash) { - if (path.startsWith(immutablePath)) { - // ignore any immutable path for timestamping - return callback(null, fromImmutablePath(path)); - } - } - for (const managedPath of this.managedPathsRegExps) { - const match = managedPath.exec(path); - if (match) { - const managedItem = getManagedItem(match[1], path); - if (managedItem) { - // construct timestampHash from managed info - return this.managedItemQueue.add(managedItem, (err, info) => { - if (err) return callback(err); - return callback(null, fromManagedItem(info)); - }); - } - } - } - for (const managedPath of this.managedPathsWithSlash) { - if (path.startsWith(managedPath)) { - const managedItem = getManagedItem(managedPath, child); - if (managedItem) { - // construct timestampHash from managed info - return this.managedItemQueue.add(managedItem, (err, info) => { - if (err) return callback(err); - return callback(null, fromManagedItem(info)); - }); - } - } - } - - lstatReadlinkAbsolute(this.fs, child, (err, stat) => { - if (err) return callback(err); - - if (typeof stat === "string") { - return fromSymlink(child, stat, callback); - } - - if (stat.isFile()) { - return fromFile(child, stat, callback); - } - if (stat.isDirectory()) { - return fromDirectory(child, stat, callback); - } - callback(null, null); - }); - }, - (err, results) => { - if (err) return callback(err); - const result = reduce(files, results); - callback(null, result); - } - ); - }); - } - - _readContextTimestamp(path, callback) { - this._readContext( - { - path, - fromImmutablePath: () => null, - fromManagedItem: info => ({ - safeTime: 0, - timestampHash: info - }), - fromSymlink: (file, target, callback) => { - callback(null, { - timestampHash: target, - symlinks: new Set([target]) - }); - }, - fromFile: (file, stat, callback) => { - // Prefer the cached value over our new stat to report consistent results - const cache = this._fileTimestamps.get(file); - if (cache !== undefined) - return callback(null, cache === "ignore" ? null : cache); - - const mtime = +stat.mtime; - - if (mtime) applyMtime(mtime); - - const ts = { - safeTime: mtime ? mtime + FS_ACCURACY : Infinity, - timestamp: mtime - }; - - this._fileTimestamps.set(file, ts); - this._cachedDeprecatedFileTimestamps = undefined; - callback(null, ts); - }, - fromDirectory: (directory, stat, callback) => { - this.contextTimestampQueue.increaseParallelism(); - this._getUnresolvedContextTimestamp(directory, (err, tsEntry) => { - this.contextTimestampQueue.decreaseParallelism(); - callback(err, tsEntry); - }); - }, - reduce: (files, tsEntries) => { - let symlinks = undefined; - - const hash = createHash(this._hashFunction); - - for (const file of files) hash.update(file); - let safeTime = 0; - for (const entry of tsEntries) { - if (!entry) { - hash.update("n"); - continue; - } - if (entry.timestamp) { - hash.update("f"); - hash.update(`${entry.timestamp}`); - } else if (entry.timestampHash) { - hash.update("d"); - hash.update(`${entry.timestampHash}`); - } - if (entry.symlinks !== undefined) { - if (symlinks === undefined) symlinks = new Set(); - addAll(entry.symlinks, symlinks); - } - if (entry.safeTime) { - safeTime = Math.max(safeTime, entry.safeTime); - } - } - - const digest = /** @type {string} */ (hash.digest("hex")); - - const result = { - safeTime, - timestampHash: digest - }; - if (symlinks) result.symlinks = symlinks; - return result; - } - }, - (err, result) => { - if (err) return callback(err); - this._contextTimestamps.set(path, result); - this._cachedDeprecatedContextTimestamps = undefined; +const WebpackError = __webpack_require__(53799); - callback(null, result); - } - ); - } +module.exports = class NoModeWarning extends WebpackError { + constructor() { + super(); - /** - * @param {ContextFileSystemInfoEntry} entry entry - * @param {function((Error | null)=, ResolvedContextFileSystemInfoEntry=): void} callback callback - * @returns {void} - */ - _resolveContextTimestamp(entry, callback) { - const hashes = []; - let safeTime = 0; - processAsyncTree( - entry.symlinks, - 10, - (target, push, callback) => { - this._getUnresolvedContextTimestamp(target, (err, entry) => { - if (err) return callback(err); - if (entry && entry !== "ignore") { - hashes.push(entry.timestampHash); - if (entry.safeTime) { - safeTime = Math.max(safeTime, entry.safeTime); - } - if (entry.symlinks !== undefined) { - for (const target of entry.symlinks) push(target); - } - } - callback(); - }); - }, - err => { - if (err) return callback(err); - const hash = createHash(this._hashFunction); - hash.update(entry.timestampHash); - if (entry.safeTime) { - safeTime = Math.max(safeTime, entry.safeTime); - } - hashes.sort(); - for (const h of hashes) { - hash.update(h); - } - callback( - null, - (entry.resolved = { - safeTime, - timestampHash: /** @type {string} */ (hash.digest("hex")) - }) - ); - } - ); + 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/"; } +}; - _readContextHash(path, callback) { - this._readContext( - { - path, - fromImmutablePath: () => "", - fromManagedItem: info => info || "", - fromSymlink: (file, target, callback) => { - callback(null, { - hash: target, - symlinks: new Set([target]) - }); - }, - fromFile: (file, stat, callback) => - this.getFileHash(file, (err, hash) => { - callback(err, hash || ""); - }), - fromDirectory: (directory, stat, callback) => { - this.contextHashQueue.increaseParallelism(); - this._getUnresolvedContextHash(directory, (err, hash) => { - this.contextHashQueue.decreaseParallelism(); - callback(err, hash || ""); - }); - }, - /** - * @param {string[]} files files - * @param {(string | ContextHash)[]} fileHashes hashes - * @returns {ContextHash} reduced hash - */ - reduce: (files, fileHashes) => { - let symlinks = undefined; - const hash = createHash(this._hashFunction); - for (const file of files) hash.update(file); - for (const entry of fileHashes) { - if (typeof entry === "string") { - hash.update(entry); - } else { - hash.update(entry.hash); - if (entry.symlinks) { - if (symlinks === undefined) symlinks = new Set(); - addAll(entry.symlinks, symlinks); - } - } - } +/***/ }), - const result = { - hash: /** @type {string} */ (hash.digest("hex")) - }; - if (symlinks) result.symlinks = symlinks; - return result; - } - }, - (err, result) => { - if (err) return callback(err); - this._contextHashes.set(path, result); - return callback(null, result); - } - ); - } +/***/ 6325: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @param {ContextHash} entry context hash - * @param {function((Error | null)=, string=): void} callback callback - * @returns {void} - */ - _resolveContextHash(entry, callback) { - const hashes = []; - processAsyncTree( - entry.symlinks, - 10, - (target, push, callback) => { - this._getUnresolvedContextHash(target, (err, hash) => { - if (err) return callback(err); - if (hash) { - hashes.push(hash.hash); - if (hash.symlinks !== undefined) { - for (const target of hash.symlinks) push(target); - } - } - callback(); - }); - }, - err => { - if (err) return callback(err); - const hash = createHash(this._hashFunction); - hash.update(entry.hash); - hashes.sort(); - for (const h of hashes) { - hash.update(h); - } - callback( - null, - (entry.resolved = /** @type {string} */ (hash.digest("hex"))) - ); - } - ); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - _readContextTimestampAndHash(path, callback) { - const finalize = (timestamp, hash) => { - const result = - timestamp === "ignore" - ? hash - : { - ...timestamp, - ...hash - }; - this._contextTshs.set(path, result); - callback(null, result); - }; - const cachedHash = this._contextHashes.get(path); - const cachedTimestamp = this._contextTimestamps.get(path); - if (cachedHash !== undefined) { - if (cachedTimestamp !== undefined) { - finalize(cachedTimestamp, cachedHash); - } else { - this.contextTimestampQueue.add(path, (err, entry) => { - if (err) return callback(err); - finalize(entry, cachedHash); - }); - } - } else { - if (cachedTimestamp !== undefined) { - this.contextHashQueue.add(path, (err, entry) => { - if (err) return callback(err); - finalize(cachedTimestamp, entry); - }); - } else { - this._readContext( - { - path, - fromImmutablePath: () => null, - fromManagedItem: info => ({ - safeTime: 0, - timestampHash: info, - hash: info || "" - }), - fromSymlink: (fle, target, callback) => { - callback(null, { - timestampHash: target, - hash: target, - symlinks: new Set([target]) - }); - }, - fromFile: (file, stat, callback) => { - this._getFileTimestampAndHash(file, callback); - }, - fromDirectory: (directory, stat, callback) => { - this.contextTshQueue.increaseParallelism(); - this.contextTshQueue.add(directory, (err, result) => { - this.contextTshQueue.decreaseParallelism(); - callback(err, result); - }); - }, - /** - * @param {string[]} files files - * @param {(Partial & Partial | string | null)[]} results results - * @returns {ContextTimestampAndHash} tsh - */ - reduce: (files, results) => { - let symlinks = undefined; - const tsHash = createHash(this._hashFunction); - const hash = createHash(this._hashFunction); - for (const file of files) { - tsHash.update(file); - hash.update(file); - } - let safeTime = 0; - for (const entry of results) { - if (!entry) { - tsHash.update("n"); - continue; - } - if (typeof entry === "string") { - tsHash.update("n"); - hash.update(entry); - continue; - } - if (entry.timestamp) { - tsHash.update("f"); - tsHash.update(`${entry.timestamp}`); - } else if (entry.timestampHash) { - tsHash.update("d"); - tsHash.update(`${entry.timestampHash}`); - } - if (entry.symlinks !== undefined) { - if (symlinks === undefined) symlinks = new Set(); - addAll(entry.symlinks, symlinks); - } - if (entry.safeTime) { - safeTime = Math.max(safeTime, entry.safeTime); - } - hash.update(entry.hash); - } +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); - const result = { - safeTime, - timestampHash: /** @type {string} */ (tsHash.digest("hex")), - hash: /** @type {string} */ (hash.digest("hex")) - }; - if (symlinks) result.symlinks = symlinks; - return result; - } - }, - (err, result) => { - if (err) return callback(err); - this._contextTshs.set(path, result); - return callback(null, result); - } - ); - } - } - } +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +class NodeStuffInWebError extends WebpackError { /** - * @param {ContextTimestampAndHash} entry entry - * @param {function((Error | null)=, ResolvedContextTimestampAndHash=): void} callback callback - * @returns {void} + * @param {DependencyLocation} loc loc + * @param {string} expression expression + * @param {string} description description */ - _resolveContextTsh(entry, callback) { - const hashes = []; - const tsHashes = []; - let safeTime = 0; - processAsyncTree( - entry.symlinks, - 10, - (target, push, callback) => { - this._getUnresolvedContextTsh(target, (err, entry) => { - if (err) return callback(err); - if (entry) { - hashes.push(entry.hash); - if (entry.timestampHash) tsHashes.push(entry.timestampHash); - if (entry.safeTime) { - safeTime = Math.max(safeTime, entry.safeTime); - } - if (entry.symlinks !== undefined) { - for (const target of entry.symlinks) push(target); - } - } - callback(); - }); - }, - err => { - if (err) return callback(err); - const hash = createHash(this._hashFunction); - const tsHash = createHash(this._hashFunction); - hash.update(entry.hash); - if (entry.timestampHash) tsHash.update(entry.timestampHash); - if (entry.safeTime) { - safeTime = Math.max(safeTime, entry.safeTime); - } - hashes.sort(); - for (const h of hashes) { - hash.update(h); - } - tsHashes.sort(); - for (const h of tsHashes) { - tsHash.update(h); - } - callback( - null, - (entry.resolved = { - safeTime, - timestampHash: /** @type {string} */ (tsHash.digest("hex")), - hash: /** @type {string} */ (hash.digest("hex")) - }) - ); - } + constructor(loc, expression, description) { + super( + `${JSON.stringify( + expression + )} has been used, it will be undefined in next major version. +${description}` ); - } - - _getManagedItemDirectoryInfo(path, callback) { - this.fs.readdir(path, (err, elements) => { - if (err) { - if (err.code === "ENOENT" || err.code === "ENOTDIR") { - return callback(null, EMPTY_SET); - } - return callback(err); - } - const set = new Set( - /** @type {string[]} */ (elements).map(element => - join(this.fs, path, element) - ) - ); - callback(null, set); - }); - } - - _getManagedItemInfo(path, callback) { - const dir = dirname(this.fs, path); - this.managedItemDirectoryQueue.add(dir, (err, elements) => { - if (err) { - return callback(err); - } - if (!elements.has(path)) { - // file or directory doesn't exist - this._managedItems.set(path, "*missing"); - return callback(null, "*missing"); - } - // something exists - // it may be a file or directory - if ( - path.endsWith("node_modules") && - (path.endsWith("/node_modules") || path.endsWith("\\node_modules")) - ) { - // we are only interested in existence of this special directory - this._managedItems.set(path, "*node_modules"); - return callback(null, "*node_modules"); - } - - // we assume it's a directory, as files shouldn't occur in managed paths - const packageJsonPath = join(this.fs, path, "package.json"); - this.fs.readFile(packageJsonPath, (err, content) => { - if (err) { - if (err.code === "ENOENT" || err.code === "ENOTDIR") { - // no package.json or path is not a directory - this.fs.readdir(path, (err, elements) => { - if ( - !err && - elements.length === 1 && - elements[0] === "node_modules" - ) { - // This is only a grouping folder e. g. used by yarn - // we are only interested in existence of this special directory - this._managedItems.set(path, "*nested"); - return callback(null, "*nested"); - } - this.logger.warn( - `Managed item ${path} isn't a directory or doesn't contain a package.json (see snapshot.managedPaths option)` - ); - return callback(); - }); - return; - } - return callback(err); - } - let data; - try { - data = JSON.parse(content.toString("utf-8")); - } catch (e) { - return callback(e); - } - if (!data.name) { - this.logger.warn( - `${packageJsonPath} doesn't contain a "name" property (see snapshot.managedPaths option)` - ); - return callback(); - } - const info = `${data.name || ""}@${data.version || ""}`; - this._managedItems.set(path, info); - callback(null, info); - }); - }); - } - - getDeprecatedFileTimestamps() { - if (this._cachedDeprecatedFileTimestamps !== undefined) - return this._cachedDeprecatedFileTimestamps; - const map = new Map(); - for (const [path, info] of this._fileTimestamps) { - if (info) map.set(path, typeof info === "object" ? info.safeTime : null); - } - return (this._cachedDeprecatedFileTimestamps = map); - } - getDeprecatedContextTimestamps() { - if (this._cachedDeprecatedContextTimestamps !== undefined) - return this._cachedDeprecatedContextTimestamps; - const map = new Map(); - for (const [path, info] of this._contextTimestamps) { - if (info) map.set(path, typeof info === "object" ? info.safeTime : null); - } - return (this._cachedDeprecatedContextTimestamps = map); + this.name = "NodeStuffInWebError"; + this.loc = loc; } } -module.exports = FileSystemInfo; -module.exports.Snapshot = Snapshot; +makeSerializable(NodeStuffInWebError, "webpack/lib/NodeStuffInWebError"); + +module.exports = NodeStuffInWebError; /***/ }), -/***/ 58727: +/***/ 95287: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -47712,14 +47951,26 @@ module.exports.Snapshot = Snapshot; -const { getEntryRuntime, mergeRuntimeOwned } = __webpack_require__(17156); +const NodeStuffInWebError = __webpack_require__(6325); +const RuntimeGlobals = __webpack_require__(16475); +const CachedConstDependency = __webpack_require__(57403); +const ConstDependency = __webpack_require__(76911); +const { + evaluateToString, + expressionIsUnsupported +} = __webpack_require__(93998); +const { relative } = __webpack_require__(17139); +const { parseResource } = __webpack_require__(82186); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -class FlagAllModulesAsUsedPlugin { - constructor(explanation) { - this.explanation = explanation; +class NodeStuffPlugin { + constructor(options) { + this.options = options; } /** @@ -47728,43 +47979,152 @@ class FlagAllModulesAsUsedPlugin { * @returns {void} */ apply(compiler) { + const options = this.options; 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) - ); + "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 !== false) { + const withWarning = localOptions.global === "warn"; + 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); + + // TODO webpack 6 remove + if (withWarning) { + parser.state.module.addWarning( + new NodeStuffInWebError( + dep.loc, + "global", + "The global namespace object is Node.js feature and doesn't present in browser." + ) + ); + } + }); + } + + const setModuleConstant = (expressionName, fn, warning) => { + 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); + + // TODO webpack 6 remove + if (warning) { + parser.state.module.addWarning( + new NodeStuffInWebError(dep.loc, expressionName, warning) + ); + } + + return true; + }); + }; + + const setConstant = (expressionName, value, warning) => + setModuleConstant(expressionName, () => value, warning); + + const context = compiler.context; + if (localOptions.__filename) { + switch (localOptions.__filename) { + case "mock": + setConstant("__filename", "/index.js"); + break; + case "warn-mock": + setConstant( + "__filename", + "/index.js", + "The __filename is Node.js feature and doesn't present in browser." + ); + break; + case true: + setModuleConstant("__filename", module => + relative(compiler.inputFileSystem, context, module.resource) + ); + break; } - 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; + + 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) { + switch (localOptions.__dirname) { + case "mock": + setConstant("__dirname", "/"); + break; + case "warn-mock": + setConstant( + "__dirname", + "/", + "The __dirname is Node.js feature and doesn't present in browser." + ); + break; + case true: + setModuleConstant("__dirname", module => + relative(compiler.inputFileSystem, context, module.context) + ); + break; } + + 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 = FlagAllModulesAsUsedPlugin; +module.exports = NodeStuffPlugin; /***/ }), -/***/ 84506: +/***/ 39: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -47775,3037 +48135,2531 @@ module.exports = FlagAllModulesAsUsedPlugin; -const asyncLib = __webpack_require__(78175); -const Queue = __webpack_require__(65930); +const parseJson = __webpack_require__(15235); +const { getContext, runLoaders } = __webpack_require__(8255); +const querystring = __webpack_require__(63477); +const { HookMap, SyncHook, AsyncSeriesBailHook } = __webpack_require__(6967); +const { + CachedSource, + OriginalSource, + RawSource, + SourceMapSource +} = __webpack_require__(51255); +const Compilation = __webpack_require__(85720); +const HookWebpackError = __webpack_require__(11351); +const Module = __webpack_require__(73208); +const ModuleBuildError = __webpack_require__(21305); +const ModuleError = __webpack_require__(23744); +const ModuleGraphConnection = __webpack_require__(40639); +const ModuleParseError = __webpack_require__(58443); +const ModuleWarning = __webpack_require__(11234); +const RuntimeGlobals = __webpack_require__(16475); +const UnhandledSchemeError = __webpack_require__(68099); +const WebpackError = __webpack_require__(53799); +const formatLocation = __webpack_require__(16734); +const LazySet = __webpack_require__(38938); +const { isSubset } = __webpack_require__(93347); +const { getScheme } = __webpack_require__(54500); +const { + compareLocations, + concatComparators, + compareSelect, + keepOriginalOrder +} = __webpack_require__(29579); +const createHash = __webpack_require__(49835); +const { createFakeHook } = __webpack_require__(64518); +const { join } = __webpack_require__(17139); +const { + contextify, + absolutify, + makePathsRelative +} = __webpack_require__(82186); +const makeSerializable = __webpack_require__(33032); +const memoize = __webpack_require__(78676); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/LoaderContext").NormalModuleLoaderContext} NormalModuleLoaderContext */ +/** @typedef {import("../declarations/WebpackOptions").Mode} Mode */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ /** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Dependency").ExportSpec} ExportSpec */ -/** @typedef {import("./Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("./ExportsInfo")} ExportsInfo */ -/** @typedef {import("./Module")} Module */ - -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 statRestoredFromMemCache = 0; - let statRestoredFromCache = 0; - let statNoExports = 0; - let statFlaggedUncached = 0; - let statNotCached = 0; - let statQueueItemsProcessed = 0; - - const { moduleMemCaches } = compilation; - - /** @type {Queue} */ - const queue = new Queue(); - - // Step 1: Try to restore cached provided export info from cache - logger.time("restore cached provided exports"); - asyncLib.each( - modules, - (module, callback) => { - const exportsInfo = moduleGraph.getExportsInfo(module); - if (!module.buildMeta || !module.buildMeta.exportsType) { - if (exportsInfo.otherExportsInfo.provided !== null) { - // It's a module without declared exports - statNoExports++; - exportsInfo.setHasProvideInfo(); - exportsInfo.setUnknownExportsProvided(); - return callback(); - } - } - if (typeof module.buildInfo.hash !== "string") { - statFlaggedUncached++; - // Enqueue uncacheable module for determining the exports - queue.enqueue(module); - exportsInfo.setHasProvideInfo(); - return callback(); - } - const memCache = moduleMemCaches && moduleMemCaches.get(module); - const memCacheValue = memCache && memCache.get(this); - if (memCacheValue !== undefined) { - statRestoredFromMemCache++; - exportsInfo.restoreProvided(memCacheValue); - return callback(); - } - cache.get( - module.identifier(), - module.buildInfo.hash, - (err, result) => { - if (err) return callback(err); - - if (result !== undefined) { - statRestoredFromCache++; - exportsInfo.restoreProvided(result); - } else { - statNotCached++; - // Without cached info enqueue module for determining the exports - queue.enqueue(module); - exportsInfo.setHasProvideInfo(); - } - callback(); - } - ); - }, - err => { - logger.timeEnd("restore cached provided exports"); - if (err) return callback(err); - - /** @type {Set} */ - const modulesToStore = new Set(); +/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("./Generator")} Generator */ +/** @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("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ +/** @typedef {import("./Parser")} Parser */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./logging/Logger").Logger} WebpackLogger */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ - /** @type {Map>} */ - const dependencies = new Map(); +/** + * @typedef {Object} SourceMap + * @property {number} version + * @property {string[]} sources + * @property {string} mappings + * @property {string=} file + * @property {string=} sourceRoot + * @property {string[]=} sourcesContent + * @property {string[]=} names + */ - /** @type {Module} */ - let module; +const getInvalidDependenciesModuleWarning = memoize(() => + __webpack_require__(68257) +); +const getValidate = memoize(() => (__webpack_require__(38476).validate)); - /** @type {ExportsInfo} */ - let exportsInfo; +const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/; - /** @type {Map} */ - const exportsSpecsFromDependencies = new Map(); +/** + * @typedef {Object} LoaderItem + * @property {string} loader + * @property {any} options + * @property {string?} ident + * @property {string?} type + */ - let cacheable = true; - let changed = false; +/** + * @param {string} context absolute context path + * @param {string} source a source path + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} new source path + */ +const contextifySourceUrl = (context, source, associatedObjectForCache) => { + if (source.startsWith("webpack://")) return source; + return `webpack://${makePathsRelative( + context, + source, + associatedObjectForCache + )}`; +}; - /** - * @param {DependenciesBlock} depBlock the dependencies block - * @returns {void} - */ - const processDependenciesBlock = depBlock => { - for (const dep of depBlock.dependencies) { - processDependency(dep); - } - for (const block of depBlock.blocks) { - processDependenciesBlock(block); - } - }; - - /** - * @param {Dependency} dep the dependency - * @returns {void} - */ - const processDependency = dep => { - const exportDesc = dep.getExports(moduleGraph); - if (!exportDesc) return; - exportsSpecsFromDependencies.set(dep, exportDesc); - }; - - /** - * @param {Dependency} dep dependency - * @param {ExportsSpec} exportDesc info - * @returns {void} - */ - const processExportsSpec = (dep, exportDesc) => { - const exports = exportDesc.exports; - const globalCanMangle = exportDesc.canMangle; - const globalFrom = exportDesc.from; - const globalPriority = exportDesc.priority; - const globalTerminalBinding = - exportDesc.terminalBinding || false; - const exportDeps = exportDesc.dependencies; - if (exportDesc.hideExports) { - for (const name of exportDesc.hideExports) { - const exportInfo = exportsInfo.getExportInfo(name); - exportInfo.unsetTarget(dep); - } - } - if (exports === true) { - // unknown exports - if ( - exportsInfo.setUnknownExportsProvided( - globalCanMangle, - exportDesc.excludeExports, - globalFrom && dep, - globalFrom, - globalPriority - ) - ) { - changed = true; - } - } else if (Array.isArray(exports)) { - /** - * merge in new exports - * @param {ExportsInfo} exportsInfo own exports info - * @param {(ExportSpec | string)[]} exports list of exports - */ - const mergeExports = (exportsInfo, exports) => { - for (const exportNameOrSpec of exports) { - let name; - let canMangle = globalCanMangle; - let terminalBinding = globalTerminalBinding; - let exports = undefined; - let from = globalFrom; - let fromExport = undefined; - let priority = globalPriority; - let hidden = false; - if (typeof exportNameOrSpec === "string") { - name = exportNameOrSpec; - } else { - name = exportNameOrSpec.name; - if (exportNameOrSpec.canMangle !== undefined) - canMangle = exportNameOrSpec.canMangle; - if (exportNameOrSpec.export !== undefined) - fromExport = exportNameOrSpec.export; - if (exportNameOrSpec.exports !== undefined) - exports = exportNameOrSpec.exports; - if (exportNameOrSpec.from !== undefined) - from = exportNameOrSpec.from; - if (exportNameOrSpec.priority !== undefined) - priority = exportNameOrSpec.priority; - if (exportNameOrSpec.terminalBinding !== undefined) - terminalBinding = exportNameOrSpec.terminalBinding; - if (exportNameOrSpec.hidden !== undefined) - hidden = exportNameOrSpec.hidden; - } - const exportInfo = exportsInfo.getExportInfo(name); - - if ( - exportInfo.provided === false || - exportInfo.provided === null - ) { - exportInfo.provided = true; - changed = true; - } - - if ( - exportInfo.canMangleProvide !== false && - canMangle === false - ) { - exportInfo.canMangleProvide = false; - changed = true; - } - - if (terminalBinding && !exportInfo.terminalBinding) { - exportInfo.terminalBinding = true; - changed = true; - } - - if (exports) { - const nestedExportsInfo = - exportInfo.createNestedExportsInfo(); - mergeExports(nestedExportsInfo, exports); - } - - if ( - from && - (hidden - ? exportInfo.unsetTarget(dep) - : exportInfo.setTarget( - dep, - from, - fromExport === undefined ? [name] : fromExport, - priority - )) - ) { - changed = true; - } - - // Recalculate target exportsInfo - const target = exportInfo.getTarget(moduleGraph); - let targetExportsInfo = 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); - - cacheable = true; - changed = false; - - exportsSpecsFromDependencies.clear(); - moduleGraph.freeze(); - processDependenciesBlock(module); - moduleGraph.unfreeze(); - for (const [ - dep, - exportsSpec - ] of exportsSpecsFromDependencies) { - processExportsSpec(dep, exportsSpec); - } - - if (cacheable) { - modulesToStore.add(module); - } +/** + * @param {string} context absolute context path + * @param {SourceMap} sourceMap a source map + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {SourceMap} new source map + */ +const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => { + if (!Array.isArray(sourceMap.sources)) return sourceMap; + const { sourceRoot } = sourceMap; + /** @type {function(string): string} */ + const mapper = !sourceRoot + ? source => source + : sourceRoot.endsWith("/") + ? source => + source.startsWith("/") + ? `${sourceRoot.slice(0, -1)}${source}` + : `${sourceRoot}${source}` + : source => + source.startsWith("/") + ? `${sourceRoot}${source}` + : `${sourceRoot}/${source}`; + const newSources = sourceMap.sources.map(source => + contextifySourceUrl(context, mapper(source), associatedObjectForCache) + ); + return { + ...sourceMap, + file: "x", + sourceRoot: undefined, + sources: newSources + }; +}; - if (changed) { - notifyDependencies(); - } - } - logger.timeEnd("figure out provided exports"); +/** + * @param {string | Buffer} input the input + * @returns {string} the converted string + */ +const asString = input => { + if (Buffer.isBuffer(input)) { + return input.toString("utf-8"); + } + return input; +}; - logger.log( - `${Math.round( - (100 * (statFlaggedUncached + statNotCached)) / - (statRestoredFromMemCache + - statRestoredFromCache + - statNotCached + - statFlaggedUncached + - statNoExports) - )}% of exports of modules have been determined (${statNoExports} no declared exports, ${statNotCached} not cached, ${statFlaggedUncached} flagged uncacheable, ${statRestoredFromCache} from cache, ${statRestoredFromMemCache} from mem cache, ${ - statQueueItemsProcessed - - statNotCached - - statFlaggedUncached - } additional calculations due to dependencies)` - ); +/** + * @param {string | Buffer} input the input + * @returns {Buffer} the converted buffer + */ +const asBuffer = input => { + if (!Buffer.isBuffer(input)) { + return Buffer.from(input, "utf-8"); + } + return input; +}; - logger.time("store provided exports into cache"); - asyncLib.each( - modulesToStore, - (module, callback) => { - if (typeof module.buildInfo.hash !== "string") { - // not cacheable - return callback(); - } - const cachedData = moduleGraph - .getExportsInfo(module) - .getRestoreProvidedData(); - const memCache = - moduleMemCaches && moduleMemCaches.get(module); - if (memCache) { - memCache.set(this, cachedData); - } - cache.store( - module.identifier(), - module.buildInfo.hash, - cachedData, - callback - ); - }, - err => { - logger.timeEnd("store provided exports into cache"); - callback(err); - } - ); - } - ); - } - ); +class NonErrorEmittedError extends WebpackError { + constructor(error) { + super(); - /** @type {WeakMap} */ - 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)); - } - ); - } - ); + this.name = "NonErrorEmittedError"; + this.message = "(Emitted value instead of an instance of Error) " + error; } } -module.exports = FlagDependencyExportsPlugin; - - -/***/ }), - -/***/ 58812: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Dependency = __webpack_require__(54912); -const { UsageState } = __webpack_require__(63686); -const ModuleGraphConnection = __webpack_require__(40639); -const { STAGE_DEFAULT } = __webpack_require__(80057); -const ArrayQueue = __webpack_require__(41792); -const TupleQueue = __webpack_require__(38415); -const { getEntryRuntime, mergeRuntimeOwned } = __webpack_require__(17156); +makeSerializable( + NonErrorEmittedError, + "webpack/lib/NormalModule", + "NonErrorEmittedError" +); -/** @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 */ +/** + * @typedef {Object} NormalModuleCompilationHooks + * @property {SyncHook<[object, NormalModule]>} loader + * @property {SyncHook<[LoaderItem[], NormalModule, object]>} beforeLoaders + * @property {SyncHook<[NormalModule]>} beforeParse + * @property {SyncHook<[NormalModule]>} beforeSnapshot + * @property {HookMap>} readResourceForScheme + * @property {HookMap>} readResource + * @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild + */ -const { NO_EXPORTS_REFERENCED, EXPORTS_OBJECT_REFERENCED } = Dependency; +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); -class FlagDependencyUsagePlugin { +class NormalModule extends Module { /** - * @param {boolean} global do a global analysis instead of per runtime + * @param {Compilation} compilation the compilation + * @returns {NormalModuleCompilationHooks} the attached hooks */ - constructor(global) { - this.global = global; + 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 = { + loader: new SyncHook(["loaderContext", "module"]), + beforeLoaders: new SyncHook(["loaders", "module", "loaderContext"]), + beforeParse: new SyncHook(["module"]), + beforeSnapshot: new SyncHook(["module"]), + // TODO webpack 6 deprecate + readResourceForScheme: new HookMap(scheme => { + const hook = hooks.readResource.for(scheme); + return createFakeHook( + /** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer>} */ ({ + tap: (options, fn) => + hook.tap(options, loaderContext => + fn(loaderContext.resource, loaderContext._module) + ), + tapAsync: (options, fn) => + hook.tapAsync(options, (loaderContext, callback) => + fn(loaderContext.resource, loaderContext._module, callback) + ), + tapPromise: (options, fn) => + hook.tapPromise(options, loaderContext => + fn(loaderContext.resource, loaderContext._module) + ) + }) + ); + }), + readResource: new HookMap( + () => new AsyncSeriesBailHook(["loaderContext"]) + ), + needBuild: new AsyncSeriesBailHook(["module", "context"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {Object} options options object + * @param {string=} options.layer an optional layer in which the module is + * @param {string} options.type module type + * @param {string} options.request request string + * @param {string} options.userRequest request intended by user (without loaders from config) + * @param {string} options.rawRequest request without resolving + * @param {LoaderItem[]} options.loaders list of loaders + * @param {string} options.resource path + query of the real resource + * @param {Record=} options.resourceResolveData resource resolve data + * @param {string} options.context context directory for resolving + * @param {string | undefined} options.matchResource path + query of the matched resource (virtual) + * @param {Parser} options.parser the parser used + * @param {object} options.parserOptions the options of the parser used + * @param {Generator} options.generator the generator used + * @param {object} options.generatorOptions the options of the generator used + * @param {Object} options.resolveOptions options used for resolving requests from this module */ - apply(compiler) { - compiler.hooks.compilation.tap("FlagDependencyUsagePlugin", compilation => { - const moduleGraph = compilation.moduleGraph; - compilation.hooks.optimizeDependencies.tap( - { - name: "FlagDependencyUsagePlugin", - stage: STAGE_DEFAULT - }, - modules => { - if (compilation.moduleMemCaches) { - throw new Error( - "optimization.usedExports can't be used with cacheUnaffected as export usage is a global effect" - ); - } - - const logger = compilation.getLogger( - "webpack.FlagDependencyUsagePlugin" - ); - /** @type {Map} */ - 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>} */ - const map = new Map(); - - /** @type {ArrayQueue} */ - const queue = new ArrayQueue(); - queue.enqueue(module); - for (;;) { - const block = queue.dequeue(); - if (block === undefined) break; - for (const b of block.blocks) { - if ( - !this.global && - b.groupOptions && - b.groupOptions.entryOptions - ) { - processModule( - b, - b.groupOptions.entryOptions.runtime || undefined, - true - ); - } else { - queue.enqueue(b); - } - } - for (const dep of block.dependencies) { - const connection = moduleGraph.getConnection(dep); - if (!connection || !connection.module) { - continue; - } - const activeState = connection.getActiveState(runtime); - if (activeState === false) continue; - const { module } = connection; - if (activeState === ModuleGraphConnection.TRANSITIVE_ONLY) { - processModule(module, runtime, false); - continue; - } - const oldReferencedExports = map.get(module); - if (oldReferencedExports === EXPORTS_OBJECT_REFERENCED) { - continue; - } - const referencedExports = - compilation.getDependencyReferencedExports(dep, runtime); - if ( - oldReferencedExports === undefined || - oldReferencedExports === NO_EXPORTS_REFERENCED || - referencedExports === EXPORTS_OBJECT_REFERENCED - ) { - map.set(module, referencedExports); - } else if ( - oldReferencedExports !== undefined && - referencedExports === NO_EXPORTS_REFERENCED - ) { - continue; - } else { - let exportsMap; - if (Array.isArray(oldReferencedExports)) { - exportsMap = new Map(); - for (const item of oldReferencedExports) { - if (Array.isArray(item)) { - exportsMap.set(item.join("\n"), item); - } else { - exportsMap.set(item.name.join("\n"), item); - } - } - map.set(module, exportsMap); - } else { - exportsMap = oldReferencedExports; - } - for (const item of referencedExports) { - if (Array.isArray(item)) { - const key = item.join("\n"); - const oldItem = exportsMap.get(key); - if (oldItem === undefined) { - exportsMap.set(key, item); - } - // if oldItem is already an array we have to do nothing - // if oldItem is an ReferencedExport object, we don't have to do anything - // as canMangle defaults to true for arrays - } else { - const key = item.name.join("\n"); - const oldItem = exportsMap.get(key); - if (oldItem === undefined || Array.isArray(oldItem)) { - exportsMap.set(key, item); - } else { - exportsMap.set(key, { - name: item.name, - canMangle: item.canMangle && oldItem.canMangle - }); - } - } - } - } - } - } - - for (const [module, referencedExports] of map) { - if (Array.isArray(referencedExports)) { - processReferencedModule( - module, - referencedExports, - runtime, - forceSideEffects - ); - } else { - processReferencedModule( - module, - Array.from(referencedExports.values()), - runtime, - forceSideEffects - ); - } - } - }; - - logger.time("initialize exports usage"); - for (const module of modules) { - const exportsInfo = moduleGraph.getExportsInfo(module); - exportInfoToModuleMap.set(exportsInfo, module); - exportsInfo.setHasUseInfo(); - } - logger.timeEnd("initialize exports usage"); - - logger.time("trace exports usage in graph"); - - /** - * @param {Dependency} dep dependency - * @param {RuntimeSpec} runtime runtime - */ - const processEntryDependency = (dep, runtime) => { - const module = moduleGraph.getModule(dep); - if (module) { - processReferencedModule( - module, - NO_EXPORTS_REFERENCED, - runtime, - true - ); - } - }; - /** @type {RuntimeSpec} */ - let globalRuntime = 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; - - -/***/ }), - -/***/ 93401: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ -/** @typedef {import("./DependencyTemplate")} DependencyTemplate */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./NormalModule")} NormalModule */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./util/Hash")} Hash */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + constructor({ + layer, + type, + request, + userRequest, + rawRequest, + loaders, + resource, + resourceResolveData, + context, + matchResource, + parser, + parserOptions, + generator, + generatorOptions, + resolveOptions + }) { + super(type, context || getContext(resource), layer); -/** - * @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} runtimeRequirements the requirements for runtime - * @property {RuntimeSpec} runtime the runtime - * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules - * @property {CodeGenerationResults=} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that) - * @property {string} type which kind of code should be generated - * @property {function(): Map=} getData get access to the code generation data - */ + // Info from Factory + /** @type {string} */ + this.request = request; + /** @type {string} */ + this.userRequest = userRequest; + /** @type {string} */ + this.rawRequest = rawRequest; + /** @type {boolean} */ + this.binary = /^(asset|webassembly)\b/.test(type); + /** @type {Parser} */ + this.parser = parser; + this.parserOptions = parserOptions; + /** @type {Generator} */ + this.generator = generator; + this.generatorOptions = generatorOptions; + /** @type {string} */ + this.resource = resource; + this.resourceResolveData = resourceResolveData; + /** @type {string | undefined} */ + this.matchResource = matchResource; + /** @type {LoaderItem[]} */ + this.loaders = loaders; + if (resolveOptions !== undefined) { + // already declared in super class + this.resolveOptions = resolveOptions; + } -/** - * @typedef {Object} UpdateHashContext - * @property {NormalModule} module the module - * @property {ChunkGraph} chunkGraph - * @property {RuntimeSpec} runtime - */ + // Info from Build + /** @type {(WebpackError | null)=} */ + this.error = null; + /** @private @type {Source=} */ + this._source = null; + /** @private @type {Map | undefined} **/ + this._sourceSizes = undefined; + /** @private @type {Set} */ + this._sourceTypes = undefined; -/** - * - */ -class Generator { - static byType(map) { - return new ByTypeGenerator(map); + // Cache + this._lastSuccessfulBuildMeta = {}; + this._forceBuild = true; + this._isEvaluatingSideEffects = false; + /** @type {WeakSet | undefined} */ + this._addedSideEffectsBailout = undefined; } - /* istanbul ignore next */ /** - * @abstract - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) + * @returns {string} a unique identifier of the module */ - getTypes(module) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + identifier() { + if (this.layer === null) { + if (this.type === "javascript/auto") { + return this.request; + } else { + return `${this.type}|${this.request}`; + } + } else { + return `${this.type}|${this.request}|${this.layer}`; + } } - /* istanbul ignore next */ /** - * @abstract - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module */ - getSize(module, type) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.userRequest); } - /* 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 + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion */ - generate( - module, - { dependencyTemplates, runtimeTemplate, moduleGraph, type } - ) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + libIdent(options) { + let ident = contextify( + options.context, + this.userRequest, + options.associatedObjectForCache + ); + if (this.layer) ident = `(${this.layer})/${ident}`; + return ident; } /** - * @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 + * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) */ - getConcatenationBailoutReason(module, context) { - return `Module Concatenation is not implemented for ${this.constructor.name}`; + nameForCondition() { + const resource = this.matchResource || this.resource; + const idx = resource.indexOf("?"); + if (idx >= 0) return resource.substr(0, idx); + return resource; } /** - * @param {Hash} hash hash that will be modified - * @param {UpdateHashContext} updateHashContext context for updating hash + * 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} */ - updateHash(hash, { module, runtime }) { - // no nothing - } -} - -class ByTypeGenerator extends Generator { - constructor(map) { - super(); - this.map = map; - this._types = new Set(Object.keys(map)); + updateCacheModule(module) { + super.updateCacheModule(module); + const m = /** @type {NormalModule} */ (module); + this.binary = m.binary; + this.request = m.request; + this.userRequest = m.userRequest; + this.rawRequest = m.rawRequest; + this.parser = m.parser; + this.parserOptions = m.parserOptions; + this.generator = m.generator; + this.generatorOptions = m.generatorOptions; + this.resource = m.resource; + this.resourceResolveData = m.resourceResolveData; + this.context = m.context; + this.matchResource = m.matchResource; + this.loaders = m.loaders; } /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) + * Assuming this module is in the cache. Remove internal references to allow freeing some memory. */ - getTypes(module) { - return this._types; + cleanupForCache() { + // Make sure to cache types and sizes before cleanup when this module has been built + // They are accessed by the stats and we don't want them to crash after cleanup + // TODO reconsider this for webpack 6 + if (this.buildInfo) { + if (this._sourceTypes === undefined) this.getSourceTypes(); + for (const type of this._sourceTypes) { + this.size(type); + } + } + super.cleanupForCache(); + this.parser = undefined; + this.parserOptions = undefined; + this.generator = undefined; + this.generatorOptions = undefined; } /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module + * Module should be unsafe cached. Get data that's needed for that. + * This data will be passed to restoreFromUnsafeCache later. + * @returns {object} cached data */ - getSize(module, type) { - const t = type || "javascript"; - const generator = this.map[t]; - return generator ? generator.getSize(module, t) : 0; + getUnsafeCacheData() { + const data = super.getUnsafeCacheData(); + data.parserOptions = this.parserOptions; + data.generatorOptions = this.generatorOptions; + return data; + } + + restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { + this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); } /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code + * restore unsafe cache data + * @param {object} unsafeCacheData data from getUnsafeCacheData + * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching */ - 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); + _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { + super._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); + this.parserOptions = unsafeCacheData.parserOptions; + this.parser = normalModuleFactory.getParser(this.type, this.parserOptions); + this.generatorOptions = unsafeCacheData.generatorOptions; + this.generator = normalModuleFactory.getGenerator( + this.type, + this.generatorOptions + ); + // we assume the generator behaves identically and keep cached sourceTypes/Sizes } -} -module.exports = Generator; + /** + * @param {string} context the compilation context + * @param {string} name the asset name + * @param {string} content the content + * @param {string | TODO} sourceMap an optional source map + * @param {Object=} associatedObjectForCache object for caching + * @returns {Source} the created source + */ + createSourceForAsset( + context, + name, + content, + sourceMap, + associatedObjectForCache + ) { + if (sourceMap) { + if ( + typeof sourceMap === "string" && + (this.useSourceMap || this.useSimpleSourceMap) + ) { + return new OriginalSource( + content, + contextifySourceUrl(context, sourceMap, associatedObjectForCache) + ); + } + if (this.useSourceMap) { + return new SourceMapSource( + content, + name, + contextifySourceMap(context, sourceMap, associatedObjectForCache) + ); + } + } -/***/ }), + return new RawSource(content); + } -/***/ 37234: -/***/ (function(__unused_webpack_module, exports) { + /** + * @param {ResolverWithOptions} resolver a resolver + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {InputFileSystem} fs file system from reading + * @param {NormalModuleCompilationHooks} hooks the hooks + * @returns {NormalModuleLoaderContext} loader context + */ + _createLoaderContext(resolver, options, compilation, fs, hooks) { + const { requestShortener } = compilation.runtimeTemplate; + const getCurrentLoaderName = () => { + const currentLoader = this.getCurrentLoader(loaderContext); + if (!currentLoader) return "(not in loader scope)"; + return requestShortener.shorten(currentLoader.loader); + }; + const getResolveContext = () => { + return { + fileDependencies: { + add: d => loaderContext.addDependency(d) + }, + contextDependencies: { + add: d => loaderContext.addContextDependency(d) + }, + missingDependencies: { + add: d => loaderContext.addMissingDependency(d) + } + }; + }; + const getAbsolutify = memoize(() => + absolutify.bindCache(compilation.compiler.root) + ); + const getAbsolutifyInContext = memoize(() => + absolutify.bindContextCache(this.context, compilation.compiler.root) + ); + const getContextify = memoize(() => + contextify.bindCache(compilation.compiler.root) + ); + const getContextifyInContext = memoize(() => + contextify.bindContextCache(this.context, compilation.compiler.root) + ); + const utils = { + absolutify: (context, request) => { + return context === this.context + ? getAbsolutifyInContext()(request) + : getAbsolutify()(context, request); + }, + contextify: (context, request) => { + return context === this.context + ? getContextifyInContext()(request) + : getContextify()(context, request); + }, + createHash: type => { + return createHash(type || compilation.outputOptions.hashFunction); + } + }; + const loaderContext = { + version: 2, + getOptions: schema => { + const loader = this.getCurrentLoader(loaderContext); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + let { options } = loader; + if (typeof options === "string") { + if (options.substr(0, 1) === "{" && options.substr(-1) === "}") { + try { + options = parseJson(options); + } catch (e) { + throw new Error(`Cannot parse string options: ${e.message}`); + } + } else { + options = querystring.parse(options, "&", "=", { + maxKeys: 0 + }); + } + } + if (options === null || options === undefined) { + options = {}; + } -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./Module")} Module */ + if (schema) { + let name = "Loader"; + let baseDataPath = "options"; + let match; + if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) { + [, name, baseDataPath] = match; + } + getValidate()(schema, options, { + name, + baseDataPath + }); + } -/** - * @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); - } -}; + return options; + }, + emitWarning: warning => { + if (!(warning instanceof Error)) { + warning = new NonErrorEmittedError(warning); + } + this.addWarning( + new ModuleWarning(warning, { + from: getCurrentLoaderName() + }) + ); + }, + emitError: error => { + if (!(error instanceof Error)) { + error = new NonErrorEmittedError(error); + } + this.addError( + new ModuleError(error, { + from: getCurrentLoaderName() + }) + ); + }, + getLogger: name => { + const currentLoader = this.getCurrentLoader(loaderContext); + return compilation.getLogger(() => + [currentLoader && currentLoader.loader, name, this.identifier()] + .filter(Boolean) + .join("|") + ); + }, + resolve(context, request, callback) { + resolver.resolve({}, context, request, getResolveContext(), callback); + }, + getResolve(options) { + const child = options ? resolver.withOptions(options) : resolver; + return (context, request, callback) => { + if (callback) { + child.resolve({}, context, request, getResolveContext(), callback); + } else { + return new Promise((resolve, reject) => { + child.resolve( + {}, + context, + request, + getResolveContext(), + (err, result) => { + if (err) reject(err); + else resolve(result); + } + ); + }); + } + }; + }, + emitFile: (name, content, sourceMap, assetInfo) => { + if (!this.buildInfo.assets) { + this.buildInfo.assets = Object.create(null); + this.buildInfo.assetsInfo = new Map(); + } + this.buildInfo.assets[name] = this.createSourceForAsset( + options.context, + name, + content, + sourceMap, + compilation.compiler.root + ); + this.buildInfo.assetsInfo.set(name, assetInfo); + }, + addBuildDependency: dep => { + if (this.buildInfo.buildDependencies === undefined) { + this.buildInfo.buildDependencies = new LazySet(); + } + this.buildInfo.buildDependencies.add(dep); + }, + utils, + rootContext: options.context, + webpack: true, + sourceMap: !!this.useSourceMap, + mode: options.mode || "production", + _module: this, + _compilation: compilation, + _compiler: compilation.compiler, + fs: fs + }; -/** - * @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); - } -}; + Object.assign(loaderContext, options.loader); -exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk; -exports.connectChunkGroupParentAndChild = connectChunkGroupParentAndChild; + hooks.loader.call(loaderContext, this); + return loaderContext; + } -/***/ }), + getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) { + if ( + this.loaders && + this.loaders.length && + index < this.loaders.length && + index >= 0 && + this.loaders[index] + ) { + return this.loaders[index]; + } + return null; + } -/***/ 97511: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {string} context the compilation context + * @param {string | Buffer} content the content + * @param {string | TODO} sourceMap an optional source map + * @param {Object=} associatedObjectForCache object for caching + * @returns {Source} the created source + */ + createSource(context, content, sourceMap, associatedObjectForCache) { + if (Buffer.isBuffer(content)) { + return new RawSource(content); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + // if there is no identifier return raw source + if (!this.identifier) { + return new RawSource(content); + } + // from here on we assume we have an identifier + const identifier = this.identifier(); + if (this.useSourceMap && sourceMap) { + return new SourceMapSource( + content, + contextifySourceUrl(context, identifier, associatedObjectForCache), + contextifySourceMap(context, sourceMap, associatedObjectForCache) + ); + } -const WebpackError = __webpack_require__(53799); + if (this.useSourceMap || this.useSimpleSourceMap) { + return new OriginalSource( + content, + contextifySourceUrl(context, identifier, associatedObjectForCache) + ); + } -module.exports = class HarmonyLinkingError extends WebpackError { - /** @param {string} message Error message */ - constructor(message) { - super(message); - this.name = "HarmonyLinkingError"; - this.hideStack = true; + return new RawSource(content); } -}; + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {NormalModuleCompilationHooks} hooks the hooks + * @param {function((WebpackError | null)=): void} callback callback function + * @returns {void} + */ + _doBuild(options, compilation, resolver, fs, hooks, callback) { + const loaderContext = this._createLoaderContext( + resolver, + options, + compilation, + fs, + hooks + ); -/***/ }), + const processResult = (err, result) => { + if (err) { + if (!(err instanceof Error)) { + err = new NonErrorEmittedError(err); + } + const currentLoader = this.getCurrentLoader(loaderContext); + const error = new ModuleBuildError(err, { + from: + currentLoader && + compilation.runtimeTemplate.requestShortener.shorten( + currentLoader.loader + ) + }); + return callback(error); + } -/***/ 11351: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const source = result[0]; + const sourceMap = result.length >= 1 ? result[1] : null; + const extraInfo = result.length >= 2 ? result[2] : null; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ + if (!Buffer.isBuffer(source) && typeof source !== "string") { + const currentLoader = this.getCurrentLoader(loaderContext, 0); + const err = new Error( + `Final loader (${ + currentLoader + ? compilation.runtimeTemplate.requestShortener.shorten( + currentLoader.loader + ) + : "unknown" + }) didn't return a Buffer or String` + ); + const error = new ModuleBuildError(err); + return callback(error); + } + + this._source = this.createSource( + options.context, + this.binary ? asBuffer(source) : asString(source), + sourceMap, + compilation.compiler.root + ); + if (this._sourceSizes !== undefined) this._sourceSizes.clear(); + this._ast = + typeof extraInfo === "object" && + extraInfo !== null && + extraInfo.webpackAST !== undefined + ? extraInfo.webpackAST + : null; + return callback(); + }; + this.buildInfo.fileDependencies = new LazySet(); + this.buildInfo.contextDependencies = new LazySet(); + this.buildInfo.missingDependencies = new LazySet(); + this.buildInfo.cacheable = true; + try { + hooks.beforeLoaders.call(this.loaders, this, loaderContext); + } catch (err) { + processResult(err); + return; + } -const WebpackError = __webpack_require__(53799); + if (this.loaders.length > 0) { + this.buildInfo.buildDependencies = new LazySet(); + } -/** @typedef {import("./Module")} Module */ + runLoaders( + { + resource: this.resource, + loaders: this.loaders, + context: loaderContext, + processResource: (loaderContext, resourcePath, callback) => { + const resource = loaderContext.resource; + const scheme = getScheme(resource); + hooks.readResource + .for(scheme) + .callAsync(loaderContext, (err, result) => { + if (err) return callback(err); + if (typeof result !== "string" && !result) { + return callback(new UnhandledSchemeError(scheme, resource)); + } + return callback(null, result); + }); + } + }, + (err, result) => { + // Cleanup loaderContext to avoid leaking memory in ICs + loaderContext._compilation = + loaderContext._compiler = + loaderContext._module = + loaderContext.fs = + undefined; -/** - * @template T - * @callback Callback - * @param {Error=} err - * @param {T=} stats - * @returns {void} - */ + if (!result) { + this.buildInfo.cacheable = false; + return processResult( + err || new Error("No result from loader-runner processing"), + null + ); + } + this.buildInfo.fileDependencies.addAll(result.fileDependencies); + this.buildInfo.contextDependencies.addAll(result.contextDependencies); + this.buildInfo.missingDependencies.addAll(result.missingDependencies); + for (const loader of this.loaders) { + this.buildInfo.buildDependencies.add(loader.loader); + } + this.buildInfo.cacheable = this.buildInfo.cacheable && result.cacheable; + processResult(err, result.result); + } + ); + } -class HookWebpackError extends WebpackError { /** - * Creates an instance of HookWebpackError. - * @param {Error} error inner error - * @param {string} hook name of hook + * @param {WebpackError} error the error + * @returns {void} */ - constructor(error, hook) { - super(error.message); - - this.name = "HookWebpackError"; - this.hook = hook; + markModuleAsErrored(error) { + // Restore build meta from successful build to keep importing state + this.buildMeta = { ...this._lastSuccessfulBuildMeta }; this.error = error; - this.hideStack = true; - this.details = `caused by plugins in ${hook}\n${error.stack}`; + this.addError(error); + } - this.stack += `\n-- inner error --\n${error.stack}`; + applyNoParseRule(rule, content) { + // must start with "rule" if rule is a string + if (typeof rule === "string") { + return content.startsWith(rule); + } + + if (typeof rule === "function") { + return rule(content); + } + // we assume rule is a regexp + return rule.test(content); } -} -module.exports = HookWebpackError; + // check if module should not be parsed + // returns "true" if the module should !not! be parsed + // returns "false" if the module !must! be parsed + shouldPreventParsing(noParseRule, request) { + // if no noParseRule exists, return false + // the module !must! be parsed. + if (!noParseRule) { + return false; + } -/** - * @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; + // we only have one rule to check + if (!Array.isArray(noParseRule)) { + // returns "true" if the module is !not! to be parsed + return this.applyNoParseRule(noParseRule, request); + } -/** - * @template T - * @param {function((WebpackError | null)=, T=): void} callback webpack error callback - * @param {string} hook name of hook - * @returns {Callback} generic callback - */ -const makeWebpackErrorCallback = (callback, hook) => { - return (err, result) => { - if (err) { - if (err instanceof WebpackError) { - callback(err); - return; + for (let i = 0; i < noParseRule.length; i++) { + const rule = noParseRule[i]; + // early exit on first truthy match + // this module is !not! to be parsed + if (this.applyNoParseRule(rule, request)) { + return true; } - callback(new HookWebpackError(err, hook)); - return; } - callback(null, result); - }; -}; - -module.exports.makeWebpackErrorCallback = makeWebpackErrorCallback; + // no match found, so this module !should! be parsed + return false; + } -/** - * @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; + _initBuildHash(compilation) { + const hash = createHash(compilation.outputOptions.hashFunction); + if (this._source) { + hash.update("source"); + this._source.updateHash(hash); } - throw new HookWebpackError(err, hook); + hash.update("meta"); + hash.update(JSON.stringify(this.buildMeta)); + this.buildInfo.hash = /** @type {string} */ (hash.digest("hex")); } - return r; -}; -module.exports.tryRunOrWebpackError = tryRunOrWebpackError; + /** + * @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._forceBuild = false; + this._source = null; + if (this._sourceSizes !== undefined) this._sourceSizes.clear(); + this._sourceTypes = undefined; + this._ast = null; + this.error = null; + this.clearWarningsAndErrors(); + this.clearDependenciesAndBlocks(); + this.buildMeta = {}; + this.buildInfo = { + cacheable: false, + parsed: true, + fileDependencies: undefined, + contextDependencies: undefined, + missingDependencies: undefined, + buildDependencies: undefined, + valueDependencies: undefined, + hash: undefined, + assets: undefined, + assetsInfo: undefined + }; + const startTime = compilation.compiler.fsStartTime || Date.now(); -/***/ }), + const hooks = NormalModule.getCompilationHooks(compilation); -/***/ 6404: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + return this._doBuild(options, compilation, resolver, fs, hooks, err => { + // if we have an error mark module as failed and exit + if (err) { + this.markModuleAsErrored(err); + this._initBuildHash(compilation); + return callback(); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const handleParseError = e => { + const source = this._source.source(); + const loaders = this.loaders.map(item => + contextify(options.context, item.loader, compilation.compiler.root) + ); + const error = new ModuleParseError(source, e, loaders, this.type); + this.markModuleAsErrored(error); + this._initBuildHash(compilation); + return callback(); + }; + const handleParseResult = result => { + this.dependencies.sort( + concatComparators( + compareSelect(a => a.loc, compareLocations), + keepOriginalOrder(this.dependencies) + ) + ); + this._initBuildHash(compilation); + this._lastSuccessfulBuildMeta = this.buildMeta; + return handleBuildDone(); + }; + const handleBuildDone = () => { + try { + hooks.beforeSnapshot.call(this); + } catch (err) { + this.markModuleAsErrored(err); + return callback(); + } -const { SyncBailHook } = __webpack_require__(41242); -const { RawSource } = __webpack_require__(51255); -const ChunkGraph = __webpack_require__(64971); -const Compilation = __webpack_require__(85720); -const HotUpdateChunk = __webpack_require__(9597); -const NormalModule = __webpack_require__(39); -const RuntimeGlobals = __webpack_require__(16475); -const WebpackError = __webpack_require__(53799); -const ConstDependency = __webpack_require__(76911); -const ImportMetaHotAcceptDependency = __webpack_require__(51274); -const ImportMetaHotDeclineDependency = __webpack_require__(53141); -const ModuleHotAcceptDependency = __webpack_require__(47511); -const ModuleHotDeclineDependency = __webpack_require__(86301); -const HotModuleReplacementRuntimeModule = __webpack_require__(27899); -const JavascriptParser = __webpack_require__(29050); -const { - evaluateToIdentifier -} = __webpack_require__(93998); -const { find, isSubset } = __webpack_require__(93347); -const TupleSet = __webpack_require__(76455); -const { compareModulesById } = __webpack_require__(29579); -const { - getRuntimeKey, - keyToRuntime, - forEachRuntime, - mergeRuntimeOwned, - subtractRuntime, - intersectRuntime -} = __webpack_require__(17156); + const snapshotOptions = compilation.options.snapshot.module; + if (!this.buildInfo.cacheable || !snapshotOptions) { + return callback(); + } + // add warning for all non-absolute paths in fileDependencies, etc + // This makes it easier to find problems with watching and/or caching + let nonAbsoluteDependencies = undefined; + const checkDependencies = deps => { + for (const dep of deps) { + if (!ABSOLUTE_PATH_REGEX.test(dep)) { + if (nonAbsoluteDependencies === undefined) + nonAbsoluteDependencies = new Set(); + nonAbsoluteDependencies.add(dep); + deps.delete(dep); + try { + const depWithoutGlob = dep.replace(/[\\/]?\*.*$/, ""); + const absolute = join( + compilation.fileSystemInfo.fs, + this.context, + depWithoutGlob + ); + if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) { + (depWithoutGlob !== dep + ? this.buildInfo.contextDependencies + : deps + ).add(absolute); + } + } catch (e) { + // ignore + } + } + } + }; + checkDependencies(this.buildInfo.fileDependencies); + checkDependencies(this.buildInfo.missingDependencies); + checkDependencies(this.buildInfo.contextDependencies); + if (nonAbsoluteDependencies !== undefined) { + const InvalidDependenciesModuleWarning = + getInvalidDependenciesModuleWarning(); + this.addWarning( + new InvalidDependenciesModuleWarning(this, nonAbsoluteDependencies) + ); + } + // convert file/context/missingDependencies into filesystem snapshot + compilation.fileSystemInfo.createSnapshot( + startTime, + this.buildInfo.fileDependencies, + this.buildInfo.contextDependencies, + this.buildInfo.missingDependencies, + snapshotOptions, + (err, snapshot) => { + if (err) { + this.markModuleAsErrored(err); + return; + } + this.buildInfo.fileDependencies = undefined; + this.buildInfo.contextDependencies = undefined; + this.buildInfo.missingDependencies = undefined; + this.buildInfo.snapshot = snapshot; + return callback(); + } + ); + }; -/** @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 */ + try { + hooks.beforeParse.call(this); + } catch (err) { + this.markModuleAsErrored(err); + this._initBuildHash(compilation); + return callback(); + } -/** - * @typedef {Object} HMRJavascriptParserHooks - * @property {SyncBailHook<[TODO, string[]], void>} hotAcceptCallback - * @property {SyncBailHook<[TODO, string[]], void>} hotAcceptWithoutCallback - */ + // check if this module should !not! be parsed. + // if so, exit here; + const noParseRule = options.module && options.module.noParse; + if (this.shouldPreventParsing(noParseRule, this.request)) { + // We assume that we need module and exports + this.buildInfo.parsed = false; + this._initBuildHash(compilation); + return handleBuildDone(); + } -/** @type {WeakMap} */ -const parserHooksMap = new WeakMap(); + let result; + try { + const source = this._source.source(); + result = this.parser.parse(this._ast || source, { + source, + current: this, + module: this, + compilation: compilation, + options: options + }); + } catch (e) { + handleParseError(e); + return; + } + handleParseResult(result); + }); + } -class HotModuleReplacementPlugin { /** - * @param {JavascriptParser} parser the parser - * @returns {HMRJavascriptParserHooks} the attached hooks + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated */ - static getParserHooks(parser) { - if (!(parser instanceof JavascriptParser)) { - throw new TypeError( - "The 'parser' argument must be an instance of JavascriptParser" - ); + getConcatenationBailoutReason(context) { + return this.generator.getConcatenationBailoutReason(this, context); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only + */ + getSideEffectsConnectionState(moduleGraph) { + if (this.factoryMeta !== undefined) { + if (this.factoryMeta.sideEffectFree) return false; + if (this.factoryMeta.sideEffectFree === false) return true; } - let hooks = parserHooksMap.get(parser); - if (hooks === undefined) { - hooks = { - hotAcceptCallback: new SyncBailHook(["expression", "requests"]), - hotAcceptWithoutCallback: new SyncBailHook(["expression", "requests"]) - }; - parserHooksMap.set(parser, hooks); + if (this.buildMeta !== undefined && this.buildMeta.sideEffectFree) { + if (this._isEvaluatingSideEffects) + return ModuleGraphConnection.CIRCULAR_CONNECTION; + this._isEvaluatingSideEffects = true; + /** @type {ConnectionState} */ + let current = false; + for (const dep of this.dependencies) { + const state = dep.getModuleEvaluationSideEffectsState(moduleGraph); + if (state === true) { + if ( + this._addedSideEffectsBailout === undefined + ? ((this._addedSideEffectsBailout = new WeakSet()), true) + : !this._addedSideEffectsBailout.has(moduleGraph) + ) { + this._addedSideEffectsBailout.add(moduleGraph); + moduleGraph + .getOptimizationBailout(this) + .push( + () => + `Dependency (${ + dep.type + }) with side effects at ${formatLocation(dep.loc)}` + ); + } + this._isEvaluatingSideEffects = false; + return true; + } else if (state !== ModuleGraphConnection.CIRCULAR_CONNECTION) { + current = ModuleGraphConnection.addConnectionStates(current, state); + } + } + this._isEvaluatingSideEffects = false; + // When caching is implemented here, make sure to not cache when + // at least one circular connection was in the loop above + return current; + } else { + return true; } - return hooks; } - constructor(options) { - this.options = options || {}; + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + if (this._sourceTypes === undefined) { + this._sourceTypes = this.generator.getTypes(this); + } + return this._sourceTypes; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - apply(compiler) { - const { _backCompat: backCompat } = compiler; - if (compiler.options.output.strictModuleErrorHandling === undefined) - compiler.options.output.strictModuleErrorHandling = true; - const runtimeRequirements = [RuntimeGlobals.module]; + codeGeneration({ + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + concatenationScope, + codeGenerationResults + }) { + /** @type {Set} */ + const runtimeRequirements = new Set(); - const createAcceptHandler = (parser, ParamDependency) => { - const { hotAcceptCallback, hotAcceptWithoutCallback } = - HotModuleReplacementPlugin.getParserHooks(parser); + if (!this.buildInfo.parsed) { + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.thisAsExports); + } - 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; - }; + /** @type {Map} */ + let data; + const getData = () => { + if (data === undefined) data = new Map(); + return data; }; - 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); - }); + const sources = new Map(); + for (const type of this.generator.getTypes(this)) { + const source = this.error + ? new RawSource( + "throw new Error(" + JSON.stringify(this.error.message) + ");" + ) + : this.generator.generate(this, { + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtimeRequirements, + runtime, + concatenationScope, + codeGenerationResults, + getData, + type + }); + + if (source) { + sources.set(type, new CachedSource(source)); } - 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; + /** @type {CodeGenerationResult} */ + const resultEntry = { + sources, + runtimeRequirements, + data }; + return resultEntry; + } - 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.chunkHashes = {}; - records.chunkRuntime = {}; - for (const chunk of compilation.chunks) { - records.chunkHashes[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.chunkHashes || - !records.chunkModuleIds - ) { - return; - } - for (const [module, chunk] of fullHashModules) { - const key = `${chunk.id}|${module.identifier()}`; - const hash = nonCodeGeneratedModules.has(module, chunk.runtime) - ? chunkGraph.getModuleHash(module, chunk.runtime) - : compilation.codeGenerationResults.getHash( - module, - chunk.runtime - ); - if (records.chunkModuleHashes[key] !== hash) { - updatedModules.add(module, chunk); - } - chunkModuleHashes[key] = hash; - } - - /** @type {Map, removedChunkIds: Set, removedModules: Set, 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} */ - 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} */ - const completelyRemovedModules = new Set(); - - for (const key of Object.keys(records.chunkHashes)) { - const oldRuntime = keyToRuntime(records.chunkRuntime[key]); - /** @type {Module[]} */ - const remainingModules = []; - // Check which modules are removed - for (const id of records.chunkModuleIds[key]) { - const module = allModules.get(id); - if (module === undefined) { - completelyRemovedModules.add(id); - } else { - remainingModules.push(module); - } - } - - let chunkId; - let newModules; - let newRuntimeModules; - let newFullHashModules; - let newDependentHashModules; - let newRuntime; - let removedFromRuntime; - const currentChunk = find( - compilation.chunks, - chunk => `${chunk.id}` === key - ); - if (currentChunk) { - chunkId = currentChunk.id; - newRuntime = intersectRuntime( - currentChunk.runtime, - allOldRuntime - ); - if (newRuntime === undefined) continue; - newModules = chunkGraph - .getChunkModules(currentChunk) - .filter(module => updatedModules.has(module, currentChunk)); - newRuntimeModules = Array.from( - chunkGraph.getChunkRuntimeModulesIterable(currentChunk) - ).filter(module => updatedModules.has(module, currentChunk)); - const fullHashModules = - chunkGraph.getChunkFullHashModulesIterable(currentChunk); - newFullHashModules = - fullHashModules && - Array.from(fullHashModules).filter(module => - updatedModules.has(module, currentChunk) - ); - const dependentHashModules = - chunkGraph.getChunkDependentHashModulesIterable(currentChunk); - newDependentHashModules = - dependentHashModules && - Array.from(dependentHashModules).filter(module => - updatedModules.has(module, currentChunk) - ); - removedFromRuntime = subtractRuntime(oldRuntime, newRuntime); - } else { - // chunk has completely removed - chunkId = `${+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(); - if (backCompat) - ChunkGraph.setChunkGraphForChunk(hotUpdateChunk, chunkGraph); - hotUpdateChunk.id = chunkId; - hotUpdateChunk.runtime = newRuntime; - if (currentChunk) { - for (const group of currentChunk.groupsIterable) - hotUpdateChunk.addGroup(group); - } - chunkGraph.attachModules(hotUpdateChunk, newModules || []); - chunkGraph.attachRuntimeModules( - hotUpdateChunk, - newRuntimeModules || [] - ); - if (newFullHashModules) { - chunkGraph.attachFullHashModules( - hotUpdateChunk, - newFullHashModules - ); - } - if (newDependentHashModules) { - chunkGraph.attachDependentHashModules( - hotUpdateChunk, - newDependentHashModules - ); - } - const renderManifest = compilation.getRenderManifest({ - chunk: hotUpdateChunk, - hash: records.hash, - fullHash: records.hash, - outputOptions: compilation.outputOptions, - moduleTemplates: compilation.moduleTemplates, - dependencyTemplates: compilation.dependencyTemplates, - codeGenerationResults: compilation.codeGenerationResults, - runtimeTemplate: compilation.runtimeTemplate, - moduleGraph: compilation.moduleGraph, - chunkGraph - }); - for (const entry of renderManifest) { - /** @type {string} */ - let filename; - /** @type {AssetInfo} */ - let assetInfo; - if ("filename" in entry) { - filename = entry.filename; - assetInfo = entry.info; - } else { - ({ path: filename, info: assetInfo } = - compilation.getPathWithInfo( - entry.filenameTemplate, - entry.pathOptions - )); - } - const source = entry.render(); - compilation.additionalChunkAssets.push(filename); - compilation.emitAsset(filename, source, { - hotModuleReplacement: true, - ...assetInfo - }); - if (currentChunk) { - currentChunk.files.add(filename); - compilation.hooks.chunkAsset.call(currentChunk, filename); - } - } - forEachRuntime(newRuntime, runtime => { - 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; - - -/***/ }), - -/***/ 9597: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Chunk = __webpack_require__(39385); - -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./util/Hash")} Hash */ - -class HotUpdateChunk extends Chunk { - constructor() { - super(); - } -} - -module.exports = HotUpdateChunk; - - -/***/ }), - -/***/ 3: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - - - -const ModuleFactory = __webpack_require__(51010); - -/** @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 + * @returns {Source | null} the original source for the module before webpack transformation */ - constructor(normalModuleFactory) { - super(); - - this.normalModuleFactory = normalModuleFactory; + originalSource() { + return this._source; } /** - * @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); - }); + invalidateBuild() { + this._forceBuild = true; } -} - -module.exports = IgnoreErrorModuleFactory; - - -/***/ }), - -/***/ 84808: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + const { fileSystemInfo, compilation, valueCacheVersions } = context; + // build if enforced + if (this._forceBuild) return callback(null, true); + // always try to build in case of an error + if (this.error) return callback(null, true); + // always build when module is not cacheable + if (!this.buildInfo.cacheable) return callback(null, true); -const createSchemaValidation = __webpack_require__(32540); + // build when there is no snapshot to check + if (!this.buildInfo.snapshot) return callback(null, true); -/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./NormalModuleFactory").ResolveData} ResolveData */ + // build when valueDependencies have changed + /** @type {Map>} */ + const valueDependencies = this.buildInfo.valueDependencies; + if (valueDependencies) { + if (!valueCacheVersions) return callback(null, true); + for (const [key, value] of valueDependencies) { + if (value === undefined) return callback(null, true); + const current = valueCacheVersions.get(key); + if ( + value !== current && + (typeof value === "string" || + typeof current === "string" || + current === undefined || + !isSubset(value, current)) + ) { + return callback(null, true); + } + } + } -const validate = createSchemaValidation( - __webpack_require__(20858), - () => __webpack_require__(3098), - { - name: "Ignore Plugin", - baseDataPath: "options" + // check snapshot for validity + fileSystemInfo.checkSnapshotValid(this.buildInfo.snapshot, (err, valid) => { + if (err) return callback(err); + if (!valid) return callback(null, true); + const hooks = NormalModule.getCompilationHooks(compilation); + hooks.needBuild.callAsync(this, context, (err, needBuild) => { + if (err) { + return callback( + HookWebpackError.makeWebpackError( + err, + "NormalModule.getCompilationHooks().needBuild" + ) + ); + } + callback(null, !!needBuild); + }); + }); } -); -class IgnorePlugin { /** - * @param {IgnorePluginOptions} options IgnorePlugin options + * @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) */ - constructor(options) { - validate(options); - this.options = options; - - /** @private @type {Function} */ - this.checkIgnore = this.checkIgnore.bind(this); + size(type) { + const cachedSize = + this._sourceSizes === undefined ? undefined : this._sourceSizes.get(type); + if (cachedSize !== undefined) { + return cachedSize; + } + const size = Math.max(1, this.generator.getSize(this, type)); + if (this._sourceSizes === undefined) { + this._sourceSizes = new Map(); + } + this._sourceSizes.set(type, size); + return size; } /** - * Note that if "contextRegExp" is given, both the "resourceRegExp" - * and "contextRegExp" have to match. - * - * @param {ResolveData} resolveData resolve data - * @returns {false|undefined} returns false when the request should be ignored, otherwise undefined + * @param {LazySet} fileDependencies set where file dependencies are added to + * @param {LazySet} contextDependencies set where context dependencies are added to + * @param {LazySet} missingDependencies set where missing dependencies are added to + * @param {LazySet} buildDependencies set where build dependencies are added to */ - checkIgnore(resolveData) { - if ( - "checkResource" in this.options && - this.options.checkResource && - this.options.checkResource(resolveData.request, resolveData.context) - ) { - return false; + addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ) { + const { snapshot, buildDependencies: buildDeps } = this.buildInfo; + if (snapshot) { + fileDependencies.addAll(snapshot.getFileIterable()); + contextDependencies.addAll(snapshot.getContextIterable()); + missingDependencies.addAll(snapshot.getMissingIterable()); + } else { + const { + fileDependencies: fileDeps, + contextDependencies: contextDeps, + missingDependencies: missingDeps + } = this.buildInfo; + if (fileDeps !== undefined) fileDependencies.addAll(fileDeps); + if (contextDeps !== undefined) contextDependencies.addAll(contextDeps); + if (missingDeps !== undefined) missingDependencies.addAll(missingDeps); } - - 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; - } + if (buildDeps !== undefined) { + buildDependencies.addAll(buildDeps); } } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context * @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); + updateHash(hash, context) { + hash.update(this.buildInfo.hash); + this.generator.updateHash(hash, { + module: this, + ...context }); + super.updateHash(hash, context); } -} - -module.exports = IgnorePlugin; - - -/***/ }), -/***/ 41606: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @typedef {import("../declarations/WebpackOptions").IgnoreWarningsNormalized} IgnoreWarningsNormalized */ -/** @typedef {import("./Compiler")} Compiler */ - -class IgnoreWarningsPlugin { - /** - * @param {IgnoreWarningsNormalized} ignoreWarnings conditions to ignore warnings - */ - constructor(ignoreWarnings) { - this._ignoreWarnings = ignoreWarnings; + serialize(context) { + const { write } = context; + // deserialize + write(this._source); + write(this.error); + write(this._lastSuccessfulBuildMeta); + write(this._forceBuild); + super.serialize(context); } - /** - * 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) - ); - }); - } - ); + + static deserialize(context) { + const obj = new NormalModule({ + // will be deserialized by Module + layer: null, + type: "", + // will be filled by updateCacheModule + resource: "", + context: "", + request: null, + userRequest: null, + rawRequest: null, + loaders: null, + matchResource: null, + parser: null, + parserOptions: null, + generator: null, + generatorOptions: null, + resolveOptions: null }); + obj.deserialize(context); + return obj; + } + + deserialize(context) { + const { read } = context; + this._source = read(); + this.error = read(); + this._lastSuccessfulBuildMeta = read(); + this._forceBuild = read(); + super.deserialize(context); } } -module.exports = IgnoreWarningsPlugin; +makeSerializable(NormalModule, "webpack/lib/NormalModule"); + +module.exports = NormalModule; /***/ }), -/***/ 55870: +/***/ 68860: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent + Author Tobias Koppers @sokra */ -const { ConcatSource } = __webpack_require__(51255); -const makeSerializable = __webpack_require__(33032); +const { getContext } = __webpack_require__(8255); +const asyncLib = __webpack_require__(78175); +const { + AsyncSeriesBailHook, + SyncWaterfallHook, + SyncBailHook, + SyncHook, + HookMap +} = __webpack_require__(6967); +const ChunkGraph = __webpack_require__(64971); +const Module = __webpack_require__(73208); +const ModuleFactory = __webpack_require__(51010); +const ModuleGraph = __webpack_require__(99988); +const NormalModule = __webpack_require__(39); +const BasicEffectRulePlugin = __webpack_require__(30318); +const BasicMatcherRulePlugin = __webpack_require__(94215); +const ObjectMatcherRulePlugin = __webpack_require__(72021); +const RuleSetCompiler = __webpack_require__(83349); +const UseEffectRulePlugin = __webpack_require__(84977); +const LazySet = __webpack_require__(38938); +const { getScheme } = __webpack_require__(54500); +const { cachedCleverMerge, cachedSetProperty } = __webpack_require__(60839); +const { join } = __webpack_require__(17139); +const { parseResource } = __webpack_require__(82186); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ +/** @typedef {import("./Generator")} Generator */ +/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./Parser")} Parser */ +/** @typedef {import("./ResolverFactory")} ResolverFactory */ +/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ /** - * @param {InitFragment} fragment the init fragment - * @param {number} index index - * @returns {[InitFragment, number]} tuple with both + * @typedef {Object} ResolveData + * @property {ModuleFactoryCreateData["contextInfo"]} contextInfo + * @property {ModuleFactoryCreateData["resolveOptions"]} resolveOptions + * @property {string} context + * @property {string} request + * @property {Record | undefined} assertions + * @property {ModuleDependency[]} dependencies + * @property {string} dependencyType + * @property {Object} createData + * @property {LazySet} fileDependencies + * @property {LazySet} missingDependencies + * @property {LazySet} contextDependencies + * @property {boolean} cacheable allow to use the unsafe cache */ -const extractFragmentIndex = (fragment, index) => [fragment, index]; /** - * @param {[InitFragment, number]} a first pair - * @param {[InitFragment, number]} b second pair - * @returns {number} sort value + * @typedef {Object} ResourceData + * @property {string} resource + * @property {string} path + * @property {string} query + * @property {string} fragment + * @property {string=} context */ -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; -}; -/** - * @template Context - */ -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; - } +/** @typedef {ResourceData & { data: Record }} ResourceDataWithData */ - /** - * @param {Context} context context - * @returns {string|Source} the source code that will be included as initialization code - */ - getContent(context) { - return this.content; +const EMPTY_RESOLVE_OPTIONS = {}; +const EMPTY_PARSER_OPTIONS = {}; +const EMPTY_GENERATOR_OPTIONS = {}; +const EMPTY_ELEMENTS = []; + +const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; + +const loaderToIdent = data => { + if (!data.options) { + return data.loader; + } + if (typeof data.options === "string") { + return data.loader + "?" + data.options; + } + if (typeof data.options !== "object") { + throw new Error("loader options must be string or object"); + } + if (data.ident) { + return data.loader + "??" + data.ident; } + return data.loader + "?" + JSON.stringify(data.options); +}; - /** - * @param {Context} context context - * @returns {string|Source=} the source code that will be included at the end of the module - */ - getEndContent(context) { - return this.endContent; +const stringifyLoadersAndResource = (loaders, resource) => { + let str = ""; + for (const loader of loaders) { + str += loaderToIdent(loader) + "!"; } + return str + resource; +}; - static addToSource(source, initFragments, context) { - 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.mergeAll === "function") { - if (!fragment.key) { - throw new Error( - `InitFragment with mergeAll function must have a valid key: ${fragment.constructor.name}` - ); - } - const oldValue = keyedFragments.get(fragment.key); - if (oldValue === undefined) { - keyedFragments.set(fragment.key, fragment); - } else if (Array.isArray(oldValue)) { - oldValue.push(fragment); - } else { - keyedFragments.set(fragment.key, [oldValue, fragment]); - } - continue; - } else if (typeof fragment.merge === "function") { - const oldValue = keyedFragments.get(fragment.key); - if (oldValue !== undefined) { - keyedFragments.set(fragment.key, fragment.merge(oldValue)); - continue; - } - } - keyedFragments.set(fragment.key || Symbol(), fragment); - } +/** + * @param {string} resultString resultString + * @returns {{loader: string, options: string|undefined}} parsed loader request + */ +const identToLoaderRequest = resultString => { + const idx = resultString.indexOf("?"); + if (idx >= 0) { + const loader = resultString.substr(0, idx); + const options = resultString.substr(idx + 1); + return { + loader, + options + }; + } else { + return { + loader: resultString, + options: undefined + }; + } +}; - const concatSource = new ConcatSource(); - const endContents = []; - for (let fragment of keyedFragments.values()) { - if (Array.isArray(fragment)) { - fragment = fragment[0].mergeAll(fragment); - } - concatSource.add(fragment.getContent(context)); - const endContent = fragment.getEndContent(context); - if (endContent) { - endContents.push(endContent); - } - } +const needCalls = (times, callback) => { + return err => { + if (--times === 0) { + return callback(err); + } + if (err && times > 0) { + times = NaN; + return callback(err); + } + }; +}; - concatSource.add(source); - for (const content of endContents.reverse()) { - concatSource.add(content); +const mergeGlobalOptions = (globalOptions, type, localOptions) => { + const parts = type.split("/"); + let result; + let current = ""; + for (const part of parts) { + current = current ? `${current}/${part}` : part; + const options = globalOptions[current]; + if (typeof options === "object") { + if (result === undefined) { + result = options; + } else { + result = cachedCleverMerge(result, options); } - return concatSource; - } else { - return source; } } - - serialize(context) { - const { write } = context; - - write(this.content); - write(this.stage); - write(this.position); - write(this.key); - write(this.endContent); - } - - deserialize(context) { - const { read } = context; - - this.content = read(); - this.stage = read(); - this.position = read(); - this.key = read(); - this.endContent = read(); + if (result === undefined) { + return localOptions; + } else { + return cachedCleverMerge(result, localOptions); } -} - -makeSerializable(InitFragment, "webpack/lib/InitFragment"); - -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; - - -/***/ }), - -/***/ 68257: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - +}; +// TODO webpack 6 remove +const deprecationChangedHookMessage = (name, hook) => { + const names = hook.taps + .map(tapped => { + return tapped.name; + }) + .join(", "); -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); + return ( + `NormalModuleFactory.${name} (${names}) is no longer a waterfall hook, but a bailing hook instead. ` + + "Do not return the passed object, but modify it instead. " + + "Returning false will ignore the request and results in no module created." + ); +}; -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Module")} Module */ +const ruleSetCompiler = new RuleSetCompiler([ + new BasicMatcherRulePlugin("test", "resource"), + new BasicMatcherRulePlugin("scheme"), + new BasicMatcherRulePlugin("mimetype"), + new BasicMatcherRulePlugin("dependency"), + new BasicMatcherRulePlugin("include", "resource"), + new BasicMatcherRulePlugin("exclude", "resource", true), + new BasicMatcherRulePlugin("resource"), + new BasicMatcherRulePlugin("resourceQuery"), + new BasicMatcherRulePlugin("resourceFragment"), + new BasicMatcherRulePlugin("realResource"), + new BasicMatcherRulePlugin("issuer"), + new BasicMatcherRulePlugin("compiler"), + new BasicMatcherRulePlugin("issuerLayer"), + new ObjectMatcherRulePlugin("assert", "assertions"), + new ObjectMatcherRulePlugin("descriptionData"), + new BasicEffectRulePlugin("type"), + new BasicEffectRulePlugin("sideEffects"), + new BasicEffectRulePlugin("parser"), + new BasicEffectRulePlugin("resolve"), + new BasicEffectRulePlugin("generator"), + new BasicEffectRulePlugin("layer"), + new UseEffectRulePlugin() +]); -class InvalidDependenciesModuleWarning extends WebpackError { +class NormalModuleFactory extends ModuleFactory { /** - * @param {Module} module module tied to dependency - * @param {Iterable} deps invalid dependencies + * @param {Object} param params + * @param {string=} param.context context + * @param {InputFileSystem} param.fs file system + * @param {ResolverFactory} param.resolverFactory resolverFactory + * @param {ModuleOptions} param.options options + * @param {Object=} param.associatedObjectForCache an object to which the cache will be attached + * @param {boolean=} param.layers enable layers */ - 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 ..." : "" - }`); + constructor({ + context, + fs, + resolverFactory, + options, + associatedObjectForCache, + layers = false + }) { + super(); + this.hooks = Object.freeze({ + /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ + resolve: new AsyncSeriesBailHook(["resolveData"]), + /** @type {HookMap>} */ + resolveForScheme: new HookMap( + () => new AsyncSeriesBailHook(["resourceData", "resolveData"]) + ), + /** @type {HookMap>} */ + resolveInScheme: new HookMap( + () => new AsyncSeriesBailHook(["resourceData", "resolveData"]) + ), + /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ + factorize: new AsyncSeriesBailHook(["resolveData"]), + /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ + beforeResolve: new AsyncSeriesBailHook(["resolveData"]), + /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ + afterResolve: new AsyncSeriesBailHook(["resolveData"]), + /** @type {AsyncSeriesBailHook<[ResolveData["createData"], ResolveData], TODO>} */ + createModule: new AsyncSeriesBailHook(["createData", "resolveData"]), + /** @type {SyncWaterfallHook<[Module, ResolveData["createData"], ResolveData], TODO>} */ + module: new SyncWaterfallHook(["module", "createData", "resolveData"]), + createParser: new HookMap(() => new SyncBailHook(["parserOptions"])), + parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])), + createGenerator: new HookMap( + () => new SyncBailHook(["generatorOptions"]) + ), + generator: new HookMap( + () => new SyncHook(["generator", "generatorOptions"]) + ) + }); + this.resolverFactory = resolverFactory; + this.ruleSet = ruleSetCompiler.compile([ + { + rules: options.defaultRules + }, + { + rules: options.rules + } + ]); + this.context = context || ""; + this.fs = fs; + this._globalParserOptions = options.parser; + this._globalGeneratorOptions = options.generator; + /** @type {Map>} */ + this.parserCache = new Map(); + /** @type {Map>} */ + this.generatorCache = new Map(); + /** @type {Set} */ + this._restoredUnsafeCacheEntries = new Set(); - this.name = "InvalidDependenciesModuleWarning"; - this.details = depsList.slice(3).join("\n"); - this.module = module; - } -} + const cacheParseResource = parseResource.bindCache( + associatedObjectForCache + ); -makeSerializable( - InvalidDependenciesModuleWarning, - "webpack/lib/InvalidDependenciesModuleWarning" -); + this.hooks.factorize.tapAsync( + { + name: "NormalModuleFactory", + stage: 100 + }, + (resolveData, callback) => { + this.hooks.resolve.callAsync(resolveData, (err, result) => { + if (err) return callback(err); -module.exports = InvalidDependenciesModuleWarning; + // Ignored + if (result === false) return callback(); + // direct module + if (result instanceof Module) return callback(null, result); -/***/ }), + if (typeof result === "object") + throw new Error( + deprecationChangedHookMessage("resolve", this.hooks.resolve) + + " Returning a Module object will result in this module used as result." + ); -/***/ 52329: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.hooks.afterResolve.callAsync(resolveData, (err, result) => { + if (err) return callback(err); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov -*/ + if (typeof result === "object") + throw new Error( + deprecationChangedHookMessage( + "afterResolve", + this.hooks.afterResolve + ) + ); + + // Ignored + if (result === false) return callback(); + const createData = resolveData.createData; + this.hooks.createModule.callAsync( + createData, + resolveData, + (err, createdModule) => { + if (!createdModule) { + if (!resolveData.request) { + return callback(new Error("Empty dependency (no request)")); + } -const InnerGraph = __webpack_require__(38988); + createdModule = new NormalModule(createData); + } -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ + createdModule = this.hooks.module.call( + createdModule, + createData, + resolveData + ); -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; - const currentSymbol = InnerGraph.getTopLevelSymbol(parser.state); - if (currentSymbol) { - InnerGraph.addUsage(parser.state, null, currentSymbol); - } else { - 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); + return callback(null, createdModule); } - } + ); }); - }; - - 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; - - -/***/ }), - -/***/ 93837: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const asyncLib = __webpack_require__(78175); -const EntryDependency = __webpack_require__(3979); -const { someInIterable } = __webpack_require__(39104); -const { compareModulesById } = __webpack_require__(29579); -const { dirname, mkdirp } = __webpack_require__(17139); - -/** @typedef {import("./Compiler")} Compiler */ + this.hooks.resolve.tapAsync( + { + name: "NormalModuleFactory", + stage: 100 + }, + (data, callback) => { + const { + contextInfo, + context, + dependencies, + dependencyType, + request, + assertions, + resolveOptions, + fileDependencies, + missingDependencies, + contextDependencies + } = data; + const loaderResolver = this.getResolver("loader"); -/** - * @typedef {Object} ManifestModuleData - * @property {string | number} id - * @property {Object} buildMeta - * @property {boolean | string[]} exports - */ + /** @type {ResourceData | undefined} */ + let matchResourceData = undefined; + /** @type {string} */ + let unresolvedResource; + /** @type {{loader: string, options: string|undefined}[]} */ + let elements; + let noPreAutoLoaders = false; + let noAutoLoaders = false; + let noPrePostAutoLoaders = false; -class LibManifestPlugin { - constructor(options) { - this.options = options; - } + const contextScheme = getScheme(context); + /** @type {string | undefined} */ + let scheme = getScheme(request); - /** - * 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 (!scheme) { + /** @type {string} */ + let requestWithoutMatchResource = request; + const matchResourceMatch = MATCH_RESOURCE_REGEX.exec(request); + if (matchResourceMatch) { + let matchResource = matchResourceMatch[1]; + if (matchResource.charCodeAt(0) === 46) { + // 46 === ".", 47 === "/" + const secondChar = matchResource.charCodeAt(1); if ( - this.options.entryOnly && - !someInIterable( - moduleGraph.getIncomingConnections(module), - c => c.dependency instanceof EntryDependency - ) + secondChar === 47 || + (secondChar === 46 && matchResource.charCodeAt(2) === 47) ) { - 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; + // if matchResources startsWith ../ or ./ + matchResource = join(this.fs, context, matchResource); } } - const manifest = { - name, - type: this.options.type, - content + matchResourceData = { + resource: matchResource, + ...cacheParseResource(matchResource) }; - // 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 - ); - } + requestWithoutMatchResource = request.substr( + matchResourceMatch[0].length ); - }, - callback - ); - } - ); - } -} -module.exports = LibManifestPlugin; - - -/***/ }), - -/***/ 14157: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const EnableLibraryPlugin = __webpack_require__(91452); - -/** @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; + scheme = getScheme(requestWithoutMatchResource); + if (!scheme && !contextScheme) { + const firstChar = requestWithoutMatchResource.charCodeAt(0); + const secondChar = requestWithoutMatchResource.charCodeAt(1); + noPreAutoLoaders = firstChar === 45 && secondChar === 33; // startsWith "-!" + noAutoLoaders = noPreAutoLoaders || firstChar === 33; // startsWith "!" + noPrePostAutoLoaders = firstChar === 33 && secondChar === 33; // startsWith "!!"; + const rawElements = requestWithoutMatchResource + .slice( + noPreAutoLoaders || noPrePostAutoLoaders + ? 2 + : noAutoLoaders + ? 1 + : 0 + ) + .split(/!+/); + unresolvedResource = rawElements.pop(); + elements = rawElements.map(identToLoaderRequest); + scheme = getScheme(unresolvedResource); + } else { + unresolvedResource = requestWithoutMatchResource; + elements = EMPTY_ELEMENTS; + } + } else { + unresolvedResource = request; + elements = EMPTY_ELEMENTS; + } -/***/ }), + const resolveContext = { + fileDependencies, + missingDependencies, + contextDependencies + }; -/***/ 22078: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {ResourceDataWithData} */ + let resourceData; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + let loaders; + const continueCallback = needCalls(2, err => { + if (err) return callback(err); + // translate option idents + try { + for (const item of loaders) { + if (typeof item.options === "string" && item.options[0] === "?") { + const ident = item.options.substr(1); + if (ident === "[[missing ident]]") { + throw new Error( + "No ident is provided by referenced loader. " + + "When using a function for Rule.use in config you need to " + + "provide an 'ident' property for referenced loader options." + ); + } + item.options = this.ruleSet.references.get(ident); + if (item.options === undefined) { + throw new Error( + "Invalid ident is provided by referenced loader" + ); + } + item.ident = ident; + } + } + } catch (e) { + return callback(e); + } -const ModuleFilenameHelpers = __webpack_require__(88821); -const NormalModule = __webpack_require__(39); -const createSchemaValidation = __webpack_require__(32540); + if (!resourceData) { + // ignored + return callback(null, dependencies[0].createIgnoredModule(context)); + } -/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */ -/** @typedef {import("./Compiler")} Compiler */ + const userRequest = + (matchResourceData !== undefined + ? `${matchResourceData.resource}!=!` + : "") + + stringifyLoadersAndResource(loaders, resourceData.resource); -const validate = createSchemaValidation( - __webpack_require__(24160), - () => __webpack_require__(15965), - { - name: "Loader Options Plugin", - baseDataPath: "options" - } -); -class LoaderOptionsPlugin { - /** - * @param {LoaderOptionsPluginOptions} options options object - */ - constructor(options = {}) { - validate(options); - if (typeof options !== "object") options = {}; - if (!options.test) { - options.test = { - test: () => true - }; - } - this.options = options; - } + const settings = {}; + const useLoadersPost = []; + const useLoaders = []; + const useLoadersPre = []; - /** - * 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("?"); + // handle .webpack[] suffix + let resource; + let match; if ( - ModuleFilenameHelpers.matchObject( - options, - i < 0 ? resource : resource.substr(0, i) - ) + matchResourceData && + typeof (resource = matchResourceData.resource) === "string" && + (match = /\.webpack\[([^\]]+)\]$/.exec(resource)) ) { - for (const key of Object.keys(options)) { - if (key === "include" || key === "exclude" || key === "test") { - continue; + settings.type = match[1]; + matchResourceData.resource = matchResourceData.resource.slice( + 0, + -settings.type.length - 10 + ); + } else { + settings.type = "javascript/auto"; + const resourceDataForRules = matchResourceData || resourceData; + const result = this.ruleSet.exec({ + resource: resourceDataForRules.path, + realResource: resourceData.path, + resourceQuery: resourceDataForRules.query, + resourceFragment: resourceDataForRules.fragment, + scheme, + assertions, + mimetype: matchResourceData + ? "" + : resourceData.data.mimetype || "", + dependency: dependencyType, + descriptionData: matchResourceData + ? undefined + : resourceData.data.descriptionFileData, + issuer: contextInfo.issuer, + compiler: contextInfo.compiler, + issuerLayer: contextInfo.issuerLayer || "" + }); + for (const r of result) { + if (r.type === "use") { + if (!noAutoLoaders && !noPrePostAutoLoaders) { + useLoaders.push(r.value); + } + } else if (r.type === "use-post") { + if (!noPrePostAutoLoaders) { + useLoadersPost.push(r.value); + } + } else if (r.type === "use-pre") { + if (!noPreAutoLoaders && !noPrePostAutoLoaders) { + useLoadersPre.push(r.value); + } + } else if ( + typeof r.value === "object" && + r.value !== null && + typeof settings[r.type] === "object" && + settings[r.type] !== null + ) { + settings[r.type] = cachedCleverMerge(settings[r.type], r.value); + } else { + settings[r.type] = r.value; } - context[key] = options[key]; } } - } - ); - }); - } -} - -module.exports = LoaderOptionsPlugin; + let postLoaders, normalLoaders, preLoaders; -/***/ }), + const continueCallback = needCalls(3, err => { + if (err) { + return callback(err); + } + const allLoaders = postLoaders; + if (matchResourceData === undefined) { + for (const loader of loaders) allLoaders.push(loader); + for (const loader of normalLoaders) allLoaders.push(loader); + } else { + for (const loader of normalLoaders) allLoaders.push(loader); + for (const loader of loaders) allLoaders.push(loader); + } + for (const loader of preLoaders) allLoaders.push(loader); + let type = settings.type; + const resolveOptions = settings.resolve; + const layer = settings.layer; + if (layer !== undefined && !layers) { + return callback( + new Error( + "'Rule.layer' is only allowed when 'experiments.layers' is enabled" + ) + ); + } + try { + Object.assign(data.createData, { + layer: + layer === undefined ? contextInfo.issuerLayer || null : layer, + request: stringifyLoadersAndResource( + allLoaders, + resourceData.resource + ), + userRequest, + rawRequest: request, + loaders: allLoaders, + resource: resourceData.resource, + context: + resourceData.context || getContext(resourceData.resource), + matchResource: matchResourceData + ? matchResourceData.resource + : undefined, + resourceResolveData: resourceData.data, + settings, + type, + parser: this.getParser(type, settings.parser), + parserOptions: settings.parser, + generator: this.getGenerator(type, settings.generator), + generatorOptions: settings.generator, + resolveOptions + }); + } catch (e) { + return callback(e); + } + callback(); + }); + this.resolveRequestArray( + contextInfo, + this.context, + useLoadersPost, + loaderResolver, + resolveContext, + (err, result) => { + postLoaders = result; + continueCallback(err); + } + ); + this.resolveRequestArray( + contextInfo, + this.context, + useLoaders, + loaderResolver, + resolveContext, + (err, result) => { + normalLoaders = result; + continueCallback(err); + } + ); + this.resolveRequestArray( + contextInfo, + this.context, + useLoadersPre, + loaderResolver, + resolveContext, + (err, result) => { + preLoaders = result; + continueCallback(err); + } + ); + }); -/***/ 86738: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.resolveRequestArray( + contextInfo, + contextScheme ? this.context : context, + elements, + loaderResolver, + resolveContext, + (err, result) => { + if (err) return continueCallback(err); + loaders = result; + continueCallback(); + } + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const defaultResolve = context => { + if (/^($|\?)/.test(unresolvedResource)) { + resourceData = { + resource: unresolvedResource, + data: {}, + ...cacheParseResource(unresolvedResource) + }; + continueCallback(); + } + // resource without scheme and with path + else { + const normalResolver = this.getResolver( + "normal", + dependencyType + ? cachedSetProperty( + resolveOptions || EMPTY_RESOLVE_OPTIONS, + "dependencyType", + dependencyType + ) + : resolveOptions + ); + this.resolveResource( + contextInfo, + context, + unresolvedResource, + normalResolver, + resolveContext, + (err, resolvedResource, resolvedResourceResolveData) => { + if (err) return continueCallback(err); + if (resolvedResource !== false) { + resourceData = { + resource: resolvedResource, + data: resolvedResourceResolveData, + ...cacheParseResource(resolvedResource) + }; + } + continueCallback(); + } + ); + } + }; + // resource with scheme + if (scheme) { + resourceData = { + resource: unresolvedResource, + data: {}, + path: undefined, + query: undefined, + fragment: undefined, + context: undefined + }; + this.hooks.resolveForScheme + .for(scheme) + .callAsync(resourceData, data, err => { + if (err) return continueCallback(err); + continueCallback(); + }); + } -const NormalModule = __webpack_require__(39); + // resource within scheme + else if (contextScheme) { + resourceData = { + resource: unresolvedResource, + data: {}, + path: undefined, + query: undefined, + fragment: undefined, + context: undefined + }; + this.hooks.resolveInScheme + .for(contextScheme) + .callAsync(resourceData, data, (err, handled) => { + if (err) return continueCallback(err); + if (!handled) return defaultResolve(this.context); + continueCallback(); + }); + } -/** @typedef {import("./Compiler")} Compiler */ + // resource without scheme and without path + else defaultResolve(context); + } + ); + } -class LoaderTargetPlugin { - /** - * @param {string} target the target - */ - constructor(target) { - this.target = target; + cleanupForCache() { + for (const module of this._restoredUnsafeCacheEntries) { + ChunkGraph.clearChunkGraphForModule(module); + ModuleGraph.clearModuleGraphForModule(module); + module.cleanupForCache(); + } } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback * @returns {void} */ - apply(compiler) { - compiler.hooks.compilation.tap("LoaderTargetPlugin", compilation => { - NormalModule.getCompilationHooks(compilation).loader.tap( - "LoaderTargetPlugin", - loaderContext => { - loaderContext.target = this.target; - } - ); - }); - } -} - -module.exports = LoaderTargetPlugin; - - -/***/ }), - -/***/ 12856: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + create(data, callback) { + const dependencies = /** @type {ModuleDependency[]} */ (data.dependencies); + const context = data.context || this.context; + const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS; + const dependency = dependencies[0]; + const request = dependency.request; + const assertions = dependency.assertions; + const contextInfo = data.contextInfo; + const fileDependencies = new LazySet(); + const missingDependencies = new LazySet(); + const contextDependencies = new LazySet(); + const dependencyType = + (dependencies.length > 0 && dependencies[0].category) || ""; + /** @type {ResolveData} */ + const resolveData = { + contextInfo, + resolveOptions, + context, + request, + assertions, + dependencies, + dependencyType, + fileDependencies, + missingDependencies, + contextDependencies, + createData: {}, + cacheable: true + }; + this.hooks.beforeResolve.callAsync(resolveData, (err, result) => { + if (err) { + return callback(err, { + fileDependencies, + missingDependencies, + contextDependencies, + cacheable: false + }); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // Ignored + if (result === false) { + return callback(null, { + fileDependencies, + missingDependencies, + contextDependencies, + cacheable: resolveData.cacheable + }); + } + if (typeof result === "object") + throw new Error( + deprecationChangedHookMessage( + "beforeResolve", + this.hooks.beforeResolve + ) + ); + this.hooks.factorize.callAsync(resolveData, (err, module) => { + if (err) { + return callback(err, { + fileDependencies, + missingDependencies, + contextDependencies, + cacheable: false + }); + } -const { SyncWaterfallHook } = __webpack_require__(41242); -const util = __webpack_require__(73837); -const RuntimeGlobals = __webpack_require__(16475); -const memoize = __webpack_require__(78676); + const factoryResult = { + module, + fileDependencies, + missingDependencies, + contextDependencies, + cacheable: resolveData.cacheable + }; -/** @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("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext} */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate} */ -/** @typedef {import("./ModuleGraph")} ModuleGraph} */ -/** @typedef {import("./ChunkGraph")} ChunkGraph} */ -/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions} */ -/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry} */ + callback(null, factoryResult); + }); + }); + } -const getJavascriptModulesPlugin = memoize(() => - __webpack_require__(89464) -); -const getJsonpTemplatePlugin = memoize(() => - __webpack_require__(4607) -); -const getLoadScriptRuntimeModule = memoize(() => - __webpack_require__(19942) -); + resolveResource( + contextInfo, + context, + unresolvedResource, + resolver, + resolveContext, + callback + ) { + resolver.resolve( + contextInfo, + context, + unresolvedResource, + resolveContext, + (err, resolvedResource, resolvedResourceResolveData) => { + if (err) { + return this._resolveResourceErrorHints( + err, + contextInfo, + context, + unresolvedResource, + resolver, + resolveContext, + (err2, hints) => { + if (err2) { + err.message += ` +An fatal error happened during resolving additional hints for this error: ${err2.message}`; + err.stack += ` -// 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); +An fatal error happened during resolving additional hints for this error: +${err2.stack}`; + return callback(err); } - ); - }, - "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)" + if (hints && hints.length > 0) { + err.message += ` +${hints.join("\n\n")}`; + } + callback(err); + } ); } - }, - 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; + callback(err, resolvedResource, resolvedResourceResolveData); + } + ); + } + + _resolveResourceErrorHints( + error, + contextInfo, + context, + unresolvedResource, + resolver, + resolveContext, + callback + ) { + asyncLib.parallel( + [ + callback => { + if (!resolver.options.fullySpecified) return callback(); + resolver + .withOptions({ + fullySpecified: false + }) + .resolve( + contextInfo, + context, + unresolvedResource, + resolveContext, + (err, resolvedResource) => { + if (!err && resolvedResource) { + const resource = parseResource(resolvedResource).path.replace( + /^.*[\\/]/, + "" + ); + return callback( + null, + `Did you mean '${resource}'? +BREAKING CHANGE: The request '${unresolvedResource}' failed to resolve only because it was resolved as fully specified +(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"'). +The extension in the request is mandatory for it to be fully specified. +Add the extension to the request.` + ); } - 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; + callback(); + } + ); + }, + callback => { + if (!resolver.options.enforceExtension) return callback(); + resolver + .withOptions({ + enforceExtension: false, + extensions: [] + }) + .resolve( + contextInfo, + context, + unresolvedResource, + resolveContext, + (err, resolvedResource) => { + if (!err && resolvedResource) { + let hint = ""; + const match = /(\.[^.]+)(\?|$)/.exec(unresolvedResource); + if (match) { + const fixedRequest = unresolvedResource.replace( + /(\.[^.]+)(\?|$)/, + "$2" + ); + if (resolver.options.extensions.has(match[1])) { + hint = `Did you mean '${fixedRequest}'?`; + } else { + hint = `Did you mean '${fixedRequest}'? Also note that '${match[1]}' is not in 'resolve.extensions' yet and need to be added for this to work?`; + } + } else { + hint = `Did you mean to omit the extension or to remove 'resolve.enforceExtension'?`; + } + return callback( + null, + `The request '${unresolvedResource}' failed to resolve only because 'resolve.enforceExtension' was specified. +${hint} +Including the extension in the request is no longer possible. Did you mean to enforce including the extension in requests with 'resolve.extensions: []' instead?` + ); } - 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)" + callback(); + } + ); + }, + callback => { + if ( + /^\.\.?\//.test(unresolvedResource) || + resolver.options.preferRelative + ) { + return callback(); + } + resolver.resolve( + contextInfo, + context, + `./${unresolvedResource}`, + resolveContext, + (err, resolvedResource) => { + if (err || !resolvedResource) return callback(); + const moduleDirectories = resolver.options.modules + .map(m => (Array.isArray(m) ? m.join(", ") : m)) + .join(", "); + callback( + null, + `Did you mean './${unresolvedResource}'? +Requests that should resolve in the current directory need to start with './'. +Requests that start with a name are treated as module requests and resolve within module directories (${moduleDirectories}). +If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.` + ); + } ); } - }, - - // 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; + ], + (err, hints) => { + if (err) return callback(err); + callback(null, hints.filter(Boolean)); } - }); - - 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 + resolveRequestArray( + contextInfo, + context, + array, + resolver, + resolveContext, + callback + ) { + if (array.length === 0) return callback(null, array); + asyncLib.map( + array, + (item, callback) => { + resolver.resolve( + contextInfo, + context, + item.loader, + resolveContext, + (err, result) => { + if ( + err && + /^[^/]*$/.test(item.loader) && + !/-loader$/.test(item.loader) + ) { + return resolver.resolve( + contextInfo, + context, + item.loader + "-loader", + resolveContext, + err2 => { + if (!err2) { + err.message = + err.message + + "\n" + + "BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" + + ` You need to specify '${item.loader}-loader' instead of '${item.loader}',\n` + + " see https://webpack.js.org/migrate/3/#automatic-loader-module-name-extension-removed"; + } + callback(err); + } + ); + } + if (err) return callback(err); + + const parsedResult = identToLoaderRequest(result); + const resolved = { + loader: parsedResult.loader, + options: + item.options === undefined + ? parsedResult.options + : item.options, + ident: item.options === undefined ? undefined : item.ident + }; + return callback(null, resolved); + } ); }, - "MainTemplate.getPublicPath is deprecated (use Compilation.getAssetPath(compilation.outputOptions.publicPath, options) instead)", - "DEP_WEBPACK_MAIN_TEMPLATE_GET_PUBLIC_PATH" + callback ); + } - 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" - ); + getParser(type, parserOptions = EMPTY_PARSER_OPTIONS) { + let cache = this.parserCache.get(type); - 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" + if (cache === undefined) { + cache = new WeakMap(); + this.parserCache.set(type, cache); + } + + let parser = cache.get(parserOptions); + + if (parser === undefined) { + parser = this.createParser(type, parserOptions); + cache.set(parserOptions, parser); + } + + return parser; + } + + /** + * @param {string} type type + * @param {{[k: string]: any}} parserOptions parser options + * @returns {Parser} parser + */ + createParser(type, parserOptions = {}) { + parserOptions = mergeGlobalOptions( + this._globalParserOptions, + type, + parserOptions ); + const parser = this.hooks.createParser.for(type).call(parserOptions); + if (!parser) { + throw new Error(`No parser registered for ${type}`); + } + this.hooks.parser.for(type).call(parser, parserOptions); + return parser; } -} -Object.defineProperty(MainTemplate.prototype, "requireFn", { - get: util.deprecate( - () => "__webpack_require__", - 'MainTemplate.requireFn is deprecated (use "__webpack_require__")', - "DEP_WEBPACK_MAIN_TEMPLATE_REQUIRE_FN" - ) -}); + getGenerator(type, generatorOptions = EMPTY_GENERATOR_OPTIONS) { + let cache = this.generatorCache.get(type); -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" - ) -}); + if (cache === undefined) { + cache = new WeakMap(); + this.generatorCache.set(type, cache); + } -module.exports = MainTemplate; + let generator = cache.get(generatorOptions); + + if (generator === undefined) { + generator = this.createGenerator(type, generatorOptions); + cache.set(generatorOptions, generator); + } + + return generator; + } + + createGenerator(type, generatorOptions = {}) { + generatorOptions = mergeGlobalOptions( + this._globalGeneratorOptions, + type, + generatorOptions + ); + const generator = this.hooks.createGenerator + .for(type) + .call(generatorOptions); + if (!generator) { + throw new Error(`No generator registered for ${type}`); + } + this.hooks.generator.for(type).call(generator, generatorOptions); + return generator; + } + + getResolver(type, resolveOptions) { + return this.resolverFactory.get(type, resolveOptions); + } +} + +module.exports = NormalModuleFactory; /***/ }), -/***/ 73208: +/***/ 30633: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -50816,712 +50670,1042 @@ module.exports = MainTemplate; -const util = __webpack_require__(73837); -const ChunkGraph = __webpack_require__(64971); -const DependenciesBlock = __webpack_require__(71040); -const ModuleGraph = __webpack_require__(99988); -const RuntimeGlobals = __webpack_require__(16475); -const { first } = __webpack_require__(93347); -const { compareChunksById } = __webpack_require__(29579); -const makeSerializable = __webpack_require__(33032); +const { join, dirname } = __webpack_require__(17139); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./ConcatenationScope")} ConcatenationScope */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./ExportsInfo").UsageStateType} UsageStateType */ -/** @typedef {import("./FileSystemInfo")} FileSystemInfo */ -/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./util/Hash")} Hash */ -/** @template T @typedef {import("./util/LazySet")} LazySet */ -/** @template T @typedef {import("./util/SortableSet")} SortableSet */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {function(TODO): void} ModuleReplacer */ -/** - * @typedef {Object} SourceContext - * @property {DependencyTemplates} dependencyTemplates the dependency templates - * @property {RuntimeTemplate} runtimeTemplate the runtime template - * @property {ModuleGraph} moduleGraph the module graph - * @property {ChunkGraph} chunkGraph the chunk graph - * @property {RuntimeSpec} runtime the runtimes code should be generated for - * @property {string=} type the type of source that should be generated - */ +class NormalModuleReplacementPlugin { + /** + * Create an instance of the plugin + * @param {RegExp} resourceRegExp the resource matcher + * @param {string|ModuleReplacer} newResource the resource replacement + */ + constructor(resourceRegExp, newResource) { + this.resourceRegExp = resourceRegExp; + this.newResource = newResource; + } -/** - * @typedef {Object} CodeGenerationContext - * @property {DependencyTemplates} dependencyTemplates the dependency templates - * @property {RuntimeTemplate} runtimeTemplate the runtime template - * @property {ModuleGraph} moduleGraph the module graph - * @property {ChunkGraph} chunkGraph the chunk graph - * @property {RuntimeSpec} runtime the runtimes code should be generated for - * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules - * @property {CodeGenerationResults} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that) - */ + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const resourceRegExp = this.resourceRegExp; + const newResource = this.newResource; + compiler.hooks.normalModuleFactory.tap( + "NormalModuleReplacementPlugin", + nmf => { + nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => { + if (resourceRegExp.test(result.request)) { + if (typeof newResource === "function") { + newResource(result); + } else { + result.request = newResource; + } + } + }); + nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => { + const createData = result.createData; + if (resourceRegExp.test(createData.resource)) { + if (typeof newResource === "function") { + newResource(result); + } else { + const fs = compiler.inputFileSystem; + if ( + newResource.startsWith("/") || + (newResource.length > 1 && newResource[1] === ":") + ) { + createData.resource = newResource; + } else { + createData.resource = join( + fs, + dirname(fs, createData.resource), + newResource + ); + } + } + } + }); + } + ); + } +} -/** - * @typedef {Object} ConcatenationBailoutReasonContext - * @property {ModuleGraph} moduleGraph the module graph - * @property {ChunkGraph} chunkGraph the chunk graph - */ +module.exports = NormalModuleReplacementPlugin; -/** - * @typedef {Object} CodeGenerationResult - * @property {Map} sources the resulting sources for all source types - * @property {Map=} data the resulting data for all source types - * @property {ReadonlySet} runtimeRequirements the runtime requirements - * @property {string=} hash a hash of the code generation result (will be automatically calculated from sources and runtimeRequirements if not provided) - */ -/** - * @typedef {Object} LibIdentOptions - * @property {string} context absolute context path to which lib ident is relative to - * @property {Object=} associatedObjectForCache object for caching - */ +/***/ }), -/** - * @typedef {Object} KnownBuildMeta - * @property {string=} moduleArgument - * @property {string=} exportsArgument - * @property {boolean=} strict - * @property {string=} moduleConcatenationBailout - * @property {("default" | "namespace" | "flagged" | "dynamic")=} exportsType - * @property {(false | "redirect" | "redirect-warn")=} defaultObject - * @property {boolean=} strictHarmonyModule - * @property {boolean=} async - * @property {boolean=} sideEffectFree - */ +/***/ 80057: +/***/ (function(__unused_webpack_module, exports) { -/** - * @typedef {Object} NeedBuildContext - * @property {Compilation} compilation - * @property {FileSystemInfo} fileSystemInfo - * @property {Map>} valueCacheVersions - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ -/** @typedef {KnownBuildMeta & Record} BuildMeta */ -const EMPTY_RESOLVE_OPTIONS = {}; -let debugId = 1000; +exports.STAGE_BASIC = -10; +exports.STAGE_DEFAULT = 0; +exports.STAGE_ADVANCED = 10; -const DEFAULT_TYPES_UNKNOWN = new Set(["unknown"]); -const DEFAULT_TYPES_JS = new Set(["javascript"]); -const deprecatedNeedRebuild = util.deprecate( - (module, context) => { - return module.needRebuild( - context.fileSystemInfo.getDeprecatedFileTimestamps(), - context.fileSystemInfo.getDeprecatedContextTimestamps() - ); - }, - "Module.needRebuild is deprecated in favor of Module.needBuild", - "DEP_WEBPACK_MODULE_NEED_REBUILD" -); +/***/ }), -/** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ +/***/ 81426: +/***/ (function(module) { -class Module extends DependenciesBlock { - /** - * @param {string} type the module type - * @param {string=} context an optional context - * @param {string=} layer an optional layer in which the module is - */ - constructor(type, context = null, layer = null) { - super(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {string} */ - this.type = type; - /** @type {string | null} */ - this.context = context; - /** @type {string | null} */ - this.layer = layer; - /** @type {boolean} */ - this.needId = true; - // Unique Id - /** @type {number} */ - this.debugId = debugId++; - // Info from Factory - /** @type {ResolveOptions} */ - this.resolveOptions = EMPTY_RESOLVE_OPTIONS; - /** @type {object | undefined} */ - this.factoryMeta = undefined; - // TODO refactor this -> options object filled from Factory - // TODO webpack 6: use an enum - /** @type {boolean} */ - this.useSourceMap = false; - /** @type {boolean} */ - this.useSimpleSourceMap = false; +class OptionsApply { + process(options, compiler) {} +} +module.exports = OptionsApply; - // Info from Build - /** @type {WebpackError[] | undefined} */ - this._warnings = undefined; - /** @type {WebpackError[] | undefined} */ - this._errors = undefined; - /** @type {BuildMeta} */ - this.buildMeta = undefined; - /** @type {Record} */ - this.buildInfo = undefined; - /** @type {Dependency[] | undefined} */ - this.presentationalDependencies = undefined; - /** @type {Dependency[] | undefined} */ - this.codeGenerationDependencies = undefined; - } - // TODO remove in webpack 6 - // BACKWARD-COMPAT START - get id() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.id", - "DEP_WEBPACK_MODULE_ID" - ).getModuleId(this); - } +/***/ }), - set id(value) { - if (value === "") { - this.needId = false; - return; - } - ChunkGraph.getChunkGraphForModule( - this, - "Module.id", - "DEP_WEBPACK_MODULE_ID" - ).setModuleId(this, value); - } +/***/ 11715: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @returns {string} the hash of the module - */ - get hash() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.hash", - "DEP_WEBPACK_MODULE_HASH" - ).getModuleHash(this, undefined); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./NormalModule")} NormalModule */ + +/** @typedef {Record} PreparsedAst */ + +/** + * @typedef {Object} ParserStateBase + * @property {string | Buffer} source + * @property {NormalModule} current + * @property {NormalModule} module + * @property {Compilation} compilation + * @property {{[k: string]: any}} options + */ + +/** @typedef {Record & ParserStateBase} ParserState */ +class Parser { + /* istanbul ignore next */ /** - * @returns {string} the shortened hash of the module + * @abstract + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state */ - get renderedHash() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.renderedHash", - "DEP_WEBPACK_MODULE_RENDERED_HASH" - ).getRenderedModuleHash(this, undefined); + parse(source, state) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } +} - get profile() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.profile", - "DEP_WEBPACK_MODULE_PROFILE" - ).getProfile(this); - } +module.exports = Parser; - set profile(value) { - ModuleGraph.getModuleGraphForModule( - this, - "Module.profile", - "DEP_WEBPACK_MODULE_PROFILE" - ).setProfile(this, value); - } - get index() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.index", - "DEP_WEBPACK_MODULE_INDEX" - ).getPreOrderIndex(this); - } +/***/ }), - set index(value) { - ModuleGraph.getModuleGraphForModule( - this, - "Module.index", - "DEP_WEBPACK_MODULE_INDEX" - ).setPreOrderIndex(this, value); - } +/***/ 73850: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - get index2() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.index2", - "DEP_WEBPACK_MODULE_INDEX2" - ).getPostOrderIndex(this); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - set index2(value) { - ModuleGraph.getModuleGraphForModule( - this, - "Module.index2", - "DEP_WEBPACK_MODULE_INDEX2" - ).setPostOrderIndex(this, value); - } - get depth() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.depth", - "DEP_WEBPACK_MODULE_DEPTH" - ).getDepth(this); - } - set depth(value) { - ModuleGraph.getModuleGraphForModule( - this, - "Module.depth", - "DEP_WEBPACK_MODULE_DEPTH" - ).setDepth(this, value); - } - - get issuer() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.issuer", - "DEP_WEBPACK_MODULE_ISSUER" - ).getIssuer(this); - } +const PrefetchDependency = __webpack_require__(31618); - set issuer(value) { - ModuleGraph.getModuleGraphForModule( - this, - "Module.issuer", - "DEP_WEBPACK_MODULE_ISSUER" - ).setIssuer(this, value); - } +/** @typedef {import("./Compiler")} Compiler */ - get usedExports() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.usedExports", - "DEP_WEBPACK_MODULE_USED_EXPORTS" - ).getUsedExports(this, undefined); +class PrefetchPlugin { + constructor(context, request) { + if (request) { + this.context = context; + this.request = request; + } else { + this.context = null; + this.request = context; + } } /** - * @deprecated - * @returns {(string | OptimizationBailoutFunction)[]} list + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - get optimizationBailout() { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.optimizationBailout", - "DEP_WEBPACK_MODULE_OPTIMIZATION_BAILOUT" - ).getOptimizationBailout(this); - } - - get optional() { - return this.isOptional( - ModuleGraph.getModuleGraphForModule( - this, - "Module.optional", - "DEP_WEBPACK_MODULE_OPTIONAL" - ) + apply(compiler) { + compiler.hooks.compilation.tap( + "PrefetchPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + PrefetchDependency, + normalModuleFactory + ); + } ); + compiler.hooks.make.tapAsync("PrefetchPlugin", (compilation, callback) => { + compilation.addModuleChain( + this.context || compiler.context, + new PrefetchDependency(this.request), + err => { + callback(err); + } + ); + }); } +} - addChunk(chunk) { - const chunkGraph = ChunkGraph.getChunkGraphForModule( - this, - "Module.addChunk", - "DEP_WEBPACK_MODULE_ADD_CHUNK" - ); - if (chunkGraph.isModuleInChunk(this, chunk)) return false; - chunkGraph.connectChunkAndModule(chunk, this); - return true; - } +module.exports = PrefetchPlugin; - removeChunk(chunk) { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.removeChunk", - "DEP_WEBPACK_MODULE_REMOVE_CHUNK" - ).disconnectChunkAndModule(chunk, this); - } - isInChunk(chunk) { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.isInChunk", - "DEP_WEBPACK_MODULE_IS_IN_CHUNK" - ).isModuleInChunk(this, chunk); - } +/***/ }), - isEntryModule() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.isEntryModule", - "DEP_WEBPACK_MODULE_IS_ENTRY_MODULE" - ).isEntryModule(this); - } +/***/ 13216: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - getChunks() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.getChunks", - "DEP_WEBPACK_MODULE_GET_CHUNKS" - ).getModuleChunks(this); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - getNumberOfChunks() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.getNumberOfChunks", - "DEP_WEBPACK_MODULE_GET_NUMBER_OF_CHUNKS" - ).getNumberOfModuleChunks(this); + + +const Compiler = __webpack_require__(70845); +const MultiCompiler = __webpack_require__(33370); +const NormalModule = __webpack_require__(39); +const createSchemaValidation = __webpack_require__(32540); +const { contextify } = __webpack_require__(82186); + +/** @typedef {import("../declarations/plugins/ProgressPlugin").HandlerFunction} HandlerFunction */ +/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */ +/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */ + +const validate = createSchemaValidation( + __webpack_require__(57647), + () => __webpack_require__(75202), + { + name: "Progress Plugin", + baseDataPath: "options" } +); +const median3 = (a, b, c) => { + return a + b + c - Math.max(a, b, c) - Math.min(a, b, c); +}; - get chunksIterable() { - return ChunkGraph.getChunkGraphForModule( - this, - "Module.chunksIterable", - "DEP_WEBPACK_MODULE_CHUNKS_ITERABLE" - ).getOrderedModuleChunksIterable(this, compareChunksById); +const createDefaultHandler = (profile, logger) => { + /** @type {{ value: string, time: number }[]} */ + const lastStateInfo = []; + + const defaultHandler = (percentage, msg, ...args) => { + if (profile) { + if (percentage === 0) { + lastStateInfo.length = 0; + } + const fullState = [msg, ...args]; + const state = fullState.map(s => s.replace(/\d+\/\d+ /g, "")); + const now = Date.now(); + const len = Math.max(state.length, lastStateInfo.length); + for (let i = len; i >= 0; i--) { + const stateItem = i < state.length ? state[i] : undefined; + const lastStateItem = + i < lastStateInfo.length ? lastStateInfo[i] : undefined; + if (lastStateItem) { + if (stateItem !== lastStateItem.value) { + const diff = now - lastStateItem.time; + if (lastStateItem.value) { + let reportState = lastStateItem.value; + if (i > 0) { + reportState = lastStateInfo[i - 1].value + " > " + reportState; + } + const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`; + const d = diff; + // This depends on timing so we ignore it for coverage + /* istanbul ignore next */ + { + if (d > 10000) { + logger.error(stateMsg); + } else if (d > 1000) { + logger.warn(stateMsg); + } else if (d > 10) { + logger.info(stateMsg); + } else if (d > 5) { + logger.log(stateMsg); + } else { + logger.debug(stateMsg); + } + } + } + if (stateItem === undefined) { + lastStateInfo.length = i; + } else { + lastStateItem.value = stateItem; + lastStateItem.time = now; + lastStateInfo.length = i + 1; + } + } + } else { + lastStateInfo[i] = { + value: stateItem, + time: now + }; + } + } + } + logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args); + if (percentage === 1 || (!msg && args.length === 0)) logger.status(); + }; + + return defaultHandler; +}; + +/** + * @callback ReportProgress + * @param {number} p + * @param {...string[]} [args] + * @returns {void} + */ + +/** @type {WeakMap} */ +const progressReporters = new WeakMap(); + +class ProgressPlugin { + /** + * @param {Compiler} compiler the current compiler + * @returns {ReportProgress} a progress reporter, if any + */ + static getReporter(compiler) { + return progressReporters.get(compiler); } /** - * @param {string} exportName a name of an export - * @returns {boolean | null} true, if the export is provided why the module. - * null, if it's unknown. - * false, if it's not provided. + * @param {ProgressPluginArgument} options options */ - isProvided(exportName) { - return ModuleGraph.getModuleGraphForModule( - this, - "Module.usedExports", - "DEP_WEBPACK_MODULE_USED_EXPORTS" - ).isExportProvided(this, exportName); + constructor(options = {}) { + if (typeof options === "function") { + options = { + handler: options + }; + } + + validate(options); + options = { ...ProgressPlugin.defaultOptions, ...options }; + + this.profile = options.profile; + this.handler = options.handler; + this.modulesCount = options.modulesCount; + this.dependenciesCount = options.dependenciesCount; + this.showEntries = options.entries; + this.showModules = options.modules; + this.showDependencies = options.dependencies; + this.showActiveModules = options.activeModules; + this.percentBy = options.percentBy; } - // BACKWARD-COMPAT END /** - * @deprecated moved to .buildInfo.exportsArgument - * @returns {string} name of the exports argument + * @param {Compiler | MultiCompiler} compiler webpack compiler + * @returns {void} */ - get exportsArgument() { - return (this.buildInfo && this.buildInfo.exportsArgument) || "exports"; + apply(compiler) { + const handler = + this.handler || + createDefaultHandler( + this.profile, + compiler.getInfrastructureLogger("webpack.Progress") + ); + if (compiler instanceof MultiCompiler) { + this._applyOnMultiCompiler(compiler, handler); + } else if (compiler instanceof Compiler) { + this._applyOnCompiler(compiler, handler); + } } /** - * @deprecated moved to .buildInfo.moduleArgument - * @returns {string} name of the module argument + * @param {MultiCompiler} compiler webpack multi-compiler + * @param {HandlerFunction} handler function that executes for every progress step + * @returns {void} */ - get moduleArgument() { - return (this.buildInfo && this.buildInfo.moduleArgument) || "module"; + _applyOnMultiCompiler(compiler, handler) { + const states = compiler.compilers.map( + () => /** @type {[number, ...string[]]} */ ([0]) + ); + compiler.compilers.forEach((compiler, idx) => { + new ProgressPlugin((p, msg, ...args) => { + states[idx] = [p, msg, ...args]; + let sum = 0; + for (const [p] of states) sum += p; + handler(sum / states.length, `[${idx}] ${msg}`, ...args); + }).apply(compiler); + }); } /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {boolean} strict the importing module is strict - * @returns {"namespace" | "default-only" | "default-with-named" | "dynamic"} export type - * "namespace": Exports is already a namespace object. namespace = exports. - * "dynamic": Check at runtime if __esModule is set. When set: namespace = { ...exports, default: exports }. When not set: namespace = { default: exports }. - * "default-only": Provide a namespace object with only default export. namespace = { default: exports } - * "default-with-named": Provide a namespace object with named and default export. namespace = { ...exports, default: exports } + * @param {Compiler} compiler webpack compiler + * @param {HandlerFunction} handler function that executes for every progress step + * @returns {void} */ - getExportsType(moduleGraph, strict) { - switch (this.buildMeta && this.buildMeta.exportsType) { - case "flagged": - return strict ? "default-with-named" : "namespace"; - case "namespace": - return "namespace"; - case "default": - switch (this.buildMeta.defaultObject) { - case "redirect": - return "default-with-named"; - case "redirect-warn": - return strict ? "default-only" : "default-with-named"; - default: - return "default-only"; + _applyOnCompiler(compiler, handler) { + const showEntries = this.showEntries; + const showModules = this.showModules; + const showDependencies = this.showDependencies; + const showActiveModules = this.showActiveModules; + let lastActiveModule = ""; + let currentLoader = ""; + let lastModulesCount = 0; + let lastDependenciesCount = 0; + let lastEntriesCount = 0; + let modulesCount = 0; + let dependenciesCount = 0; + let entriesCount = 1; + let doneModules = 0; + let doneDependencies = 0; + let doneEntries = 0; + const activeModules = new Set(); + let lastUpdate = 0; + + const updateThrottled = () => { + if (lastUpdate + 500 < Date.now()) update(); + }; + + const update = () => { + /** @type {string[]} */ + const items = []; + const percentByModules = + doneModules / + Math.max(lastModulesCount || this.modulesCount || 1, modulesCount); + const percentByEntries = + doneEntries / + Math.max(lastEntriesCount || this.dependenciesCount || 1, entriesCount); + const percentByDependencies = + doneDependencies / + Math.max(lastDependenciesCount || 1, dependenciesCount); + let percentageFactor; + + switch (this.percentBy) { + case "entries": + percentageFactor = percentByEntries; + break; + case "dependencies": + percentageFactor = percentByDependencies; + break; + case "modules": + percentageFactor = percentByModules; + break; + default: + percentageFactor = median3( + percentByModules, + percentByEntries, + percentByDependencies + ); + } + + const percentage = 0.1 + percentageFactor * 0.55; + + if (currentLoader) { + items.push( + `import loader ${contextify( + compiler.context, + currentLoader, + compiler.root + )}` + ); + } else { + const statItems = []; + if (showEntries) { + statItems.push(`${doneEntries}/${entriesCount} entries`); } - case "dynamic": { - if (strict) return "default-with-named"; - // Try to figure out value of __esModule by following reexports - const handleDefault = () => { - switch (this.buildMeta.defaultObject) { - case "redirect": - case "redirect-warn": - return "default-with-named"; - default: - return "default-only"; + if (showDependencies) { + statItems.push( + `${doneDependencies}/${dependenciesCount} dependencies` + ); + } + if (showModules) { + statItems.push(`${doneModules}/${modulesCount} modules`); + } + if (showActiveModules) { + statItems.push(`${activeModules.size} active`); + } + if (statItems.length > 0) { + items.push(statItems.join(" ")); + } + if (showActiveModules) { + items.push(lastActiveModule); + } + } + handler(percentage, "building", ...items); + lastUpdate = Date.now(); + }; + + const factorizeAdd = () => { + dependenciesCount++; + if (dependenciesCount < 50 || dependenciesCount % 100 === 0) + updateThrottled(); + }; + + const factorizeDone = () => { + doneDependencies++; + if (doneDependencies < 50 || doneDependencies % 100 === 0) + updateThrottled(); + }; + + const moduleAdd = () => { + modulesCount++; + if (modulesCount < 50 || modulesCount % 100 === 0) updateThrottled(); + }; + + // only used when showActiveModules is set + const moduleBuild = module => { + const ident = module.identifier(); + if (ident) { + activeModules.add(ident); + lastActiveModule = ident; + update(); + } + }; + + const entryAdd = (entry, options) => { + entriesCount++; + if (entriesCount < 5 || entriesCount % 10 === 0) updateThrottled(); + }; + + const moduleDone = module => { + doneModules++; + if (showActiveModules) { + const ident = module.identifier(); + if (ident) { + activeModules.delete(ident); + if (lastActiveModule === ident) { + lastActiveModule = ""; + for (const m of activeModules) { + lastActiveModule = m; + } + update(); + return; } - }; - const exportInfo = moduleGraph.getReadOnlyExportInfo( - this, - "__esModule" - ); - if (exportInfo.provided === false) { - return handleDefault(); } - const target = exportInfo.getTarget(moduleGraph); + } + if (doneModules < 50 || doneModules % 100 === 0) updateThrottled(); + }; + + const entryDone = (entry, options) => { + doneEntries++; + update(); + }; + + const cache = compiler + .getCache("ProgressPlugin") + .getItemCache("counts", null); + + let cacheGetPromise; + + compiler.hooks.beforeCompile.tap("ProgressPlugin", () => { + if (!cacheGetPromise) { + cacheGetPromise = cache.getPromise().then( + data => { + if (data) { + lastModulesCount = lastModulesCount || data.modulesCount; + lastDependenciesCount = + lastDependenciesCount || data.dependenciesCount; + } + return data; + }, + err => { + // Ignore error + } + ); + } + }); + + compiler.hooks.afterCompile.tapPromise("ProgressPlugin", compilation => { + if (compilation.compiler.isChild()) return Promise.resolve(); + return cacheGetPromise.then(async oldData => { if ( - !target || - !target.export || - target.export.length !== 1 || - target.export[0] !== "__esModule" + !oldData || + oldData.modulesCount !== modulesCount || + oldData.dependenciesCount !== dependenciesCount ) { - return "dynamic"; + await cache.storePromise({ modulesCount, dependenciesCount }); } - switch ( - target.module.buildMeta && - target.module.buildMeta.exportsType - ) { - case "flagged": - case "namespace": - return "namespace"; - case "default": - return handleDefault(); - default: - return "dynamic"; + }); + }); + + compiler.hooks.compilation.tap("ProgressPlugin", compilation => { + if (compilation.compiler.isChild()) return; + lastModulesCount = modulesCount; + lastEntriesCount = entriesCount; + lastDependenciesCount = dependenciesCount; + modulesCount = dependenciesCount = entriesCount = 0; + doneModules = doneDependencies = doneEntries = 0; + + compilation.factorizeQueue.hooks.added.tap( + "ProgressPlugin", + factorizeAdd + ); + compilation.factorizeQueue.hooks.result.tap( + "ProgressPlugin", + factorizeDone + ); + + compilation.addModuleQueue.hooks.added.tap("ProgressPlugin", moduleAdd); + compilation.processDependenciesQueue.hooks.result.tap( + "ProgressPlugin", + moduleDone + ); + + if (showActiveModules) { + compilation.hooks.buildModule.tap("ProgressPlugin", moduleBuild); + } + + compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd); + compilation.hooks.failedEntry.tap("ProgressPlugin", entryDone); + compilation.hooks.succeedEntry.tap("ProgressPlugin", entryDone); + + // avoid dynamic require if bundled with webpack + // @ts-expect-error + if (false) {} + + const hooks = { + finishModules: "finish module graph", + seal: "plugins", + optimizeDependencies: "dependencies optimization", + afterOptimizeDependencies: "after dependencies optimization", + beforeChunks: "chunk graph", + afterChunks: "after chunk graph", + optimize: "optimizing", + optimizeModules: "module optimization", + afterOptimizeModules: "after module optimization", + optimizeChunks: "chunk optimization", + afterOptimizeChunks: "after chunk optimization", + optimizeTree: "module and chunk tree optimization", + afterOptimizeTree: "after module and chunk tree optimization", + optimizeChunkModules: "chunk modules optimization", + afterOptimizeChunkModules: "after chunk modules optimization", + reviveModules: "module reviving", + beforeModuleIds: "before module ids", + moduleIds: "module ids", + optimizeModuleIds: "module id optimization", + afterOptimizeModuleIds: "module id optimization", + reviveChunks: "chunk reviving", + beforeChunkIds: "before chunk ids", + chunkIds: "chunk ids", + optimizeChunkIds: "chunk id optimization", + afterOptimizeChunkIds: "after chunk id optimization", + recordModules: "record modules", + recordChunks: "record chunks", + beforeModuleHash: "module hashing", + beforeCodeGeneration: "code generation", + beforeRuntimeRequirements: "runtime requirements", + beforeHash: "hashing", + afterHash: "after hashing", + recordHash: "record hash", + beforeModuleAssets: "module assets processing", + beforeChunkAssets: "chunk assets processing", + processAssets: "asset processing", + afterProcessAssets: "after asset optimization", + record: "recording", + afterSeal: "after seal" + }; + const numberOfHooks = Object.keys(hooks).length; + Object.keys(hooks).forEach((name, idx) => { + const title = hooks[name]; + const percentage = (idx / numberOfHooks) * 0.25 + 0.7; + compilation.hooks[name].intercept({ + name: "ProgressPlugin", + call() { + handler(percentage, "sealing", title); + }, + done() { + progressReporters.set(compiler, undefined); + handler(percentage, "sealing", title); + }, + result() { + handler(percentage, "sealing", title); + }, + error() { + handler(percentage, "sealing", title); + }, + tap(tap) { + // p is percentage from 0 to 1 + // args is any number of messages in a hierarchical matter + progressReporters.set(compilation.compiler, (p, ...args) => { + handler(percentage, "sealing", title, tap.name, ...args); + }); + handler(percentage, "sealing", title, tap.name); + } + }); + }); + }); + compiler.hooks.make.intercept({ + name: "ProgressPlugin", + call() { + handler(0.1, "building"); + }, + done() { + handler(0.65, "building"); + } + }); + const interceptHook = (hook, progress, category, name) => { + hook.intercept({ + name: "ProgressPlugin", + call() { + handler(progress, category, name); + }, + done() { + progressReporters.set(compiler, undefined); + handler(progress, category, name); + }, + result() { + handler(progress, category, name); + }, + error() { + handler(progress, category, name); + }, + tap(tap) { + progressReporters.set(compiler, (p, ...args) => { + handler(progress, category, name, tap.name, ...args); + }); + handler(progress, category, name, tap.name); } + }); + }; + compiler.cache.hooks.endIdle.intercept({ + name: "ProgressPlugin", + call() { + handler(0, ""); } - default: - return strict ? "default-with-named" : "dynamic"; - } + }); + interceptHook(compiler.cache.hooks.endIdle, 0.01, "cache", "end idle"); + compiler.hooks.initialize.intercept({ + name: "ProgressPlugin", + call() { + handler(0, ""); + } + }); + interceptHook(compiler.hooks.initialize, 0.01, "setup", "initialize"); + interceptHook(compiler.hooks.beforeRun, 0.02, "setup", "before run"); + interceptHook(compiler.hooks.run, 0.03, "setup", "run"); + interceptHook(compiler.hooks.watchRun, 0.03, "setup", "watch run"); + interceptHook( + compiler.hooks.normalModuleFactory, + 0.04, + "setup", + "normal module factory" + ); + interceptHook( + compiler.hooks.contextModuleFactory, + 0.05, + "setup", + "context module factory" + ); + interceptHook( + compiler.hooks.beforeCompile, + 0.06, + "setup", + "before compile" + ); + interceptHook(compiler.hooks.compile, 0.07, "setup", "compile"); + interceptHook(compiler.hooks.thisCompilation, 0.08, "setup", "compilation"); + interceptHook(compiler.hooks.compilation, 0.09, "setup", "compilation"); + interceptHook(compiler.hooks.finishMake, 0.69, "building", "finish"); + interceptHook(compiler.hooks.emit, 0.95, "emitting", "emit"); + interceptHook(compiler.hooks.afterEmit, 0.98, "emitting", "after emit"); + interceptHook(compiler.hooks.done, 0.99, "done", "plugins"); + compiler.hooks.done.intercept({ + name: "ProgressPlugin", + done() { + handler(0.99, ""); + } + }); + interceptHook( + compiler.cache.hooks.storeBuildDependencies, + 0.99, + "cache", + "store build dependencies" + ); + interceptHook(compiler.cache.hooks.shutdown, 0.99, "cache", "shutdown"); + interceptHook(compiler.cache.hooks.beginIdle, 0.99, "cache", "begin idle"); + interceptHook( + compiler.hooks.watchClose, + 0.99, + "end", + "closing watch compilation" + ); + compiler.cache.hooks.beginIdle.intercept({ + name: "ProgressPlugin", + done() { + handler(1, ""); + } + }); + compiler.cache.hooks.shutdown.intercept({ + name: "ProgressPlugin", + done() { + handler(1, ""); + } + }); } +} + +ProgressPlugin.defaultOptions = { + profile: false, + modulesCount: 5000, + dependenciesCount: 10000, + modules: true, + dependencies: true, + activeModules: false, + entries: true +}; + +module.exports = ProgressPlugin; + + +/***/ }), + +/***/ 38309: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const ConstDependency = __webpack_require__(76911); +const ProvidedDependency = __webpack_require__(95770); +const { approve } = __webpack_require__(93998); +/** @typedef {import("./Compiler")} Compiler */ + +class ProvidePlugin { /** - * @param {Dependency} presentationalDependency dependency being tied to module. - * This is a Dependency without edge in the module graph. It's only for presentation. - * @returns {void} + * @param {Record} definitions the provided identifiers */ - addPresentationalDependency(presentationalDependency) { - if (this.presentationalDependencies === undefined) { - this.presentationalDependencies = []; - } - this.presentationalDependencies.push(presentationalDependency); + constructor(definitions) { + this.definitions = definitions; } /** - * @param {Dependency} codeGenerationDependency dependency being tied to module. - * This is a Dependency where the code generation result of the referenced module is needed during code generation. - * The Dependency should also be added to normal dependencies via addDependency. + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - addCodeGenerationDependency(codeGenerationDependency) { - if (this.codeGenerationDependencies === undefined) { - this.codeGenerationDependencies = []; - } - this.codeGenerationDependencies.push(codeGenerationDependency); + apply(compiler) { + const definitions = this.definitions; + compiler.hooks.compilation.tap( + "ProvidePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + compilation.dependencyFactories.set( + ProvidedDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ProvidedDependency, + new ProvidedDependency.Template() + ); + const handler = (parser, parserOptions) => { + Object.keys(definitions).forEach(name => { + const request = [].concat(definitions[name]); + const splittedName = name.split("."); + if (splittedName.length > 0) { + splittedName.slice(1).forEach((_, i) => { + const name = splittedName.slice(0, i + 1).join("."); + parser.hooks.canRename.for(name).tap("ProvidePlugin", approve); + }); + } + + parser.hooks.expression.for(name).tap("ProvidePlugin", expr => { + const nameIdentifier = name.includes(".") + ? `__webpack_provided_${name.replace(/\./g, "_dot_")}` + : name; + const dep = new ProvidedDependency( + request[0], + nameIdentifier, + request.slice(1), + expr.range + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return true; + }); + + parser.hooks.call.for(name).tap("ProvidePlugin", expr => { + const nameIdentifier = name.includes(".") + ? `__webpack_provided_${name.replace(/\./g, "_dot_")}` + : name; + const dep = new ProvidedDependency( + request[0], + nameIdentifier, + request.slice(1), + expr.callee.range + ); + dep.loc = expr.callee.loc; + parser.state.module.addDependency(dep); + parser.walkExpressions(expr.arguments); + return true; + }); + }); + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ProvidePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ProvidePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ProvidePlugin", handler); + } + ); } +} + +module.exports = ProvidePlugin; + + +/***/ }), + +/***/ 84929: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { OriginalSource, RawSource } = __webpack_require__(51255); +const Module = __webpack_require__(73208); +const makeSerializable = __webpack_require__(33032); + +/** @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("./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"]); + +class RawModule extends Module { /** - * Removes all dependencies and blocks - * @returns {void} + * @param {string} source source code + * @param {string} identifier unique identifier + * @param {string=} readableIdentifier readable identifier + * @param {ReadonlySet=} runtimeRequirements runtime requirements needed for the source code */ - clearDependenciesAndBlocks() { - if (this.presentationalDependencies !== undefined) { - this.presentationalDependencies.length = 0; - } - if (this.codeGenerationDependencies !== undefined) { - this.codeGenerationDependencies.length = 0; - } - super.clearDependenciesAndBlocks(); + constructor(source, identifier, readableIdentifier, runtimeRequirements) { + super("javascript/dynamic", null); + this.sourceStr = source; + this.identifierStr = identifier || this.sourceStr; + this.readableIdentifierStr = readableIdentifier || this.identifierStr; + this.runtimeRequirements = runtimeRequirements || null; } /** - * @param {WebpackError} warning the warning - * @returns {void} + * @returns {Set} types available (do not mutate) */ - addWarning(warning) { - if (this._warnings === undefined) { - this._warnings = []; - } - this._warnings.push(warning); + getSourceTypes() { + return TYPES; } /** - * @returns {Iterable | undefined} list of warnings if any + * @returns {string} a unique identifier of the module */ - getWarnings() { - return this._warnings; + identifier() { + return this.identifierStr; } /** - * @returns {number} number of warnings + * @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) */ - getNumberOfWarnings() { - return this._warnings !== undefined ? this._warnings.length : 0; + size(type) { + return Math.max(1, this.sourceStr.length); } /** - * @param {WebpackError} error the error - * @returns {void} + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module */ - addError(error) { - if (this._errors === undefined) { - this._errors = []; - } - this._errors.push(error); + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.readableIdentifierStr); } /** - * @returns {Iterable | undefined} list of errors if any + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} */ - getErrors() { - return this._errors; + needBuild(context, callback) { + return callback(null, !this.buildMeta); } /** - * @returns {number} number of errors + * @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} */ - getNumberOfErrors() { - return this._errors !== undefined ? this._errors.length : 0; + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = { + cacheable: true + }; + callback(); } /** - * removes all warnings and errors - * @returns {void} + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - clearWarningsAndErrors() { - if (this._warnings !== undefined) { - this._warnings.length = 0; - } - if (this._errors !== undefined) { - this._errors.length = 0; + codeGeneration(context) { + const sources = new Map(); + if (this.useSourceMap || this.useSimpleSourceMap) { + sources.set( + "javascript", + new OriginalSource(this.sourceStr, this.identifier()) + ); + } else { + sources.set("javascript", new RawSource(this.sourceStr)); } - } - - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {boolean} true, if the module is optional - */ - isOptional(moduleGraph) { - let hasConnections = false; - for (const r of moduleGraph.getIncomingConnections(this)) { - if ( - !r.dependency || - !r.dependency.optional || - !r.isTargetActive(undefined) - ) { - return false; - } - hasConnections = true; - } - return hasConnections; - } - - /** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {Chunk} chunk a chunk - * @param {Chunk=} ignoreChunk chunk to be ignored - * @returns {boolean} true, if the module is accessible from "chunk" when ignoring "ignoreChunk" - */ - isAccessibleInChunk(chunkGraph, chunk, ignoreChunk) { - // Check if module is accessible in ALL chunk groups - for (const chunkGroup of chunk.groupsIterable) { - if (!this.isAccessibleInChunkGroup(chunkGraph, chunkGroup)) return false; - } - return true; - } - - /** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {ChunkGroup} chunkGroup a chunk group - * @param {Chunk=} ignoreChunk chunk to be ignored - * @returns {boolean} true, if the module is accessible from "chunkGroup" when ignoring "ignoreChunk" - */ - isAccessibleInChunkGroup(chunkGraph, chunkGroup, ignoreChunk) { - const queue = new Set([chunkGroup]); - - // Check if module is accessible from all items of the queue - queueFor: for (const cg of queue) { - // 1. If module is in one of the chunks of the group we can continue checking the next items - // because it's accessible. - for (const chunk of cg.chunks) { - if (chunk !== ignoreChunk && chunkGraph.isModuleInChunk(this, chunk)) - continue queueFor; - } - // 2. If the chunk group is initial, we can break here because it's not accessible. - if (chunkGroup.isInitial()) return false; - // 3. Enqueue all parents because it must be accessible from ALL parents - for (const parent of chunkGroup.parentsIterable) queue.add(parent); - } - // When we processed through the whole list and we didn't bailout, the module is accessible - return true; - } - - /** - * @param {Chunk} chunk a chunk - * @param {ModuleGraph} moduleGraph the module graph - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {boolean} true, if the module has any reason why "chunk" should be included - */ - hasReasonForChunk(chunk, moduleGraph, chunkGraph) { - // check for each reason if we need the chunk - for (const [ - fromModule, - connections - ] of moduleGraph.getIncomingConnectionsByOriginModule(this)) { - if (!connections.some(c => c.isTargetActive(chunk.runtime))) continue; - for (const originChunk of chunkGraph.getModuleChunksIterable( - fromModule - )) { - // return true if module this is not reachable from originChunk when ignoring chunk - if (!this.isAccessibleInChunk(chunkGraph, originChunk, chunk)) - return true; - } - } - return false; - } - - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {RuntimeSpec} runtime the runtime - * @returns {boolean} true if at least one other module depends on this module - */ - hasReasons(moduleGraph, runtime) { - for (const c of moduleGraph.getIncomingConnections(this)) { - if (c.isTargetActive(runtime)) return true; - } - return false; - } - - /** - * @returns {string} for debugging - */ - toString() { - return `Module[${this.debugId}: ${this.identifier()}]`; - } - - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - callback( - null, - !this.buildMeta || - this.needRebuild === Module.prototype.needRebuild || - deprecatedNeedRebuild(this, context) - ); - } - - /** - * @deprecated Use needBuild instead - * @param {Map} fileTimestamps timestamps of files - * @param {Map} contextTimestamps timestamps of directories - * @returns {boolean} true, if the module needs a rebuild - */ - needRebuild(fileTimestamps, contextTimestamps) { - return true; + return { sources, runtimeRequirements: this.runtimeRequirements }; } /** @@ -51529,384 +51713,42 @@ class Module extends DependenciesBlock { * @param {UpdateHashContext} context context * @returns {void} */ - updateHash( - hash, - context = { - chunkGraph: ChunkGraph.getChunkGraphForModule( - this, - "Module.updateHash", - "DEP_WEBPACK_MODULE_UPDATE_HASH" - ), - runtime: undefined - } - ) { - const { chunkGraph, runtime } = context; - hash.update(chunkGraph.getModuleGraphHash(this, runtime)); - if (this.presentationalDependencies !== undefined) { - for (const dep of this.presentationalDependencies) { - dep.updateHash(hash, context); - } - } + updateHash(hash, context) { + hash.update(this.sourceStr); super.updateHash(hash, context); } - /** - * @returns {void} - */ - invalidateBuild() { - // should be overridden to support this feature - } - - /* istanbul ignore next */ - /** - * @abstract - * @returns {string} a unique identifier of the module - */ - identifier() { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); - } - - /* istanbul ignore next */ - /** - * @abstract - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); - } - - /* istanbul ignore next */ - /** - * @abstract - * @param {WebpackOptions} options webpack options - * @param {Compilation} compilation the compilation - * @param {ResolverWithOptions} resolver the resolver - * @param {InputFileSystem} fs the file system - * @param {function(WebpackError=): void} callback callback function - * @returns {void} - */ - build(options, compilation, resolver, fs, callback) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); - } - - /** - * @abstract - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - // Better override this method to return the correct types - if (this.source === Module.prototype.source) { - return DEFAULT_TYPES_UNKNOWN; - } else { - return DEFAULT_TYPES_JS; - } - } - - /** - * @abstract - * @deprecated Use codeGeneration() instead - * @param {DependencyTemplates} dependencyTemplates the dependency templates - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {string=} type the type of source that should be generated - * @returns {Source} generated source - */ - source(dependencyTemplates, runtimeTemplate, type = "javascript") { - if (this.codeGeneration === Module.prototype.codeGeneration) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); - } - const chunkGraph = ChunkGraph.getChunkGraphForModule( - this, - "Module.source() is deprecated. Use Compilation.codeGenerationResults.getSource(module, runtime, type) instead", - "DEP_WEBPACK_MODULE_SOURCE" - ); - /** @type {CodeGenerationContext} */ - const codeGenContext = { - dependencyTemplates, - runtimeTemplate, - moduleGraph: chunkGraph.moduleGraph, - chunkGraph, - runtime: undefined, - codeGenerationResults: undefined - }; - const sources = this.codeGeneration(codeGenContext).sources; - return type ? sources.get(type) : sources.get(first(this.getSourceTypes())); - } - - /* istanbul ignore next */ - /** - * @abstract - * @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) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); - } - - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - return null; - } - - /** - * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) - */ - nameForCondition() { - return null; - } - - /** - * @param {ConcatenationBailoutReasonContext} context context - * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated - */ - getConcatenationBailoutReason(context) { - return `Module Concatenation is not implemented for ${this.constructor.name}`; - } - - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only - */ - getSideEffectsConnectionState(moduleGraph) { - return true; - } - - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration(context) { - // Best override this method - const sources = new Map(); - for (const type of this.getSourceTypes()) { - if (type !== "unknown") { - sources.set( - type, - this.source( - context.dependencyTemplates, - context.runtimeTemplate, - type - ) - ); - } - } - return { - sources, - runtimeRequirements: new Set([ - RuntimeGlobals.module, - RuntimeGlobals.exports, - RuntimeGlobals.require - ]) - }; - } - - /** - * @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, compilation) { - return true; - } - - hasChunkCondition() { - return this.chunkCondition !== Module.prototype.chunkCondition; - } - - /** - * 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) { - this.type = module.type; - this.layer = module.layer; - this.context = module.context; - this.factoryMeta = module.factoryMeta; - this.resolveOptions = module.resolveOptions; - } - - /** - * Module should be unsafe cached. Get data that's needed for that. - * This data will be passed to restoreFromUnsafeCache later. - * @returns {object} cached data - */ - getUnsafeCacheData() { - return { - factoryMeta: this.factoryMeta, - resolveOptions: this.resolveOptions - }; - } - - /** - * restore unsafe cache data - * @param {object} unsafeCacheData data from getUnsafeCacheData - * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching - */ - _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { - this.factoryMeta = unsafeCacheData.factoryMeta; - this.resolveOptions = unsafeCacheData.resolveOptions; - } - - /** - * Assuming this module is in the cache. Remove internal references to allow freeing some memory. - */ - cleanupForCache() { - this.factoryMeta = undefined; - this.resolveOptions = undefined; - } - - /** - * @returns {Source | null} the original source for the module before webpack transformation - */ - originalSource() { - return null; - } - - /** - * @param {LazySet} fileDependencies set where file dependencies are added to - * @param {LazySet} contextDependencies set where context dependencies are added to - * @param {LazySet} missingDependencies set where missing dependencies are added to - * @param {LazySet} buildDependencies set where build dependencies are added to - */ - addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ) {} - serialize(context) { const { write } = context; - write(this.type); - write(this.layer); - write(this.context); - write(this.resolveOptions); - write(this.factoryMeta); - write(this.useSourceMap); - write(this.useSimpleSourceMap); - write( - this._warnings !== undefined && this._warnings.length === 0 - ? undefined - : this._warnings - ); - write( - this._errors !== undefined && this._errors.length === 0 - ? undefined - : this._errors - ); - write(this.buildMeta); - write(this.buildInfo); - write(this.presentationalDependencies); - write(this.codeGenerationDependencies); + + write(this.sourceStr); + write(this.identifierStr); + write(this.readableIdentifierStr); + write(this.runtimeRequirements); + super.serialize(context); } deserialize(context) { const { read } = context; - this.type = read(); - this.layer = read(); - this.context = read(); - this.resolveOptions = read(); - this.factoryMeta = read(); - this.useSourceMap = read(); - this.useSimpleSourceMap = read(); - this._warnings = read(); - this._errors = read(); - this.buildMeta = read(); - this.buildInfo = read(); - this.presentationalDependencies = read(); - this.codeGenerationDependencies = read(); - super.deserialize(context); - } -} - -makeSerializable(Module, "webpack/lib/Module"); -// TODO remove in webpack 6 -Object.defineProperty(Module.prototype, "hasEqualsChunks", { - get() { - throw new Error( - "Module.hasEqualsChunks was renamed (use hasEqualChunks instead)" - ); - } -}); + this.sourceStr = read(); + this.identifierStr = read(); + this.readableIdentifierStr = read(); + this.runtimeRequirements = read(); -// TODO remove in webpack 6 -Object.defineProperty(Module.prototype, "isUsed", { - get() { - throw new Error( - "Module.isUsed was renamed (use getUsedName, isExportUsed or isModuleUsed instead)" - ); + super.deserialize(context); } -}); - -// TODO remove in webpack 6 -Object.defineProperty(Module.prototype, "errors", { - get: util.deprecate( - /** - * @this {Module} - * @returns {WebpackError[]} array - */ - function () { - if (this._errors === undefined) { - this._errors = []; - } - return this._errors; - }, - "Module.errors was removed (use getErrors instead)", - "DEP_WEBPACK_MODULE_ERRORS" - ) -}); - -// TODO remove in webpack 6 -Object.defineProperty(Module.prototype, "warnings", { - get: util.deprecate( - /** - * @this {Module} - * @returns {WebpackError[]} array - */ - function () { - if (this._warnings === undefined) { - this._warnings = []; - } - return this._warnings; - }, - "Module.warnings was removed (use getWarnings instead)", - "DEP_WEBPACK_MODULE_WARNINGS" - ) -}); +} -// TODO remove in webpack 6 -Object.defineProperty(Module.prototype, "used", { - get() { - throw new Error( - "Module.used was refactored (use ModuleGraph.getUsedExports instead)" - ); - }, - set(value) { - throw new Error( - "Module.used was refactored (use ModuleGraph.setUsedExports instead)" - ); - } -}); +makeSerializable(RawModule, "webpack/lib/RawModule"); -module.exports = Module; +module.exports = RawModule; /***/ }), -/***/ 21305: +/***/ 11094: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -51917,81 +51759,242 @@ module.exports = Module; -const { cutOffLoaderExecution } = __webpack_require__(59985); -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); - -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 += ": "; - } +const { compareNumbers } = __webpack_require__(29579); +const identifierUtils = __webpack_require__(82186); - if (err !== null && typeof err === "object") { - if (typeof err.stack === "string" && err.stack) { - const stack = cutOffLoaderExecution(err.stack); +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ - if (!err.hideStack) { - message += stack; - } else { - details = stack; +/** + * @typedef {Object} RecordsChunks + * @property {Record=} byName + * @property {Record=} bySource + * @property {number[]=} usedIds + */ - 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); - } +/** + * @typedef {Object} RecordsModules + * @property {Record=} byIdentifier + * @property {Record=} bySource + * @property {number[]=} usedIds + */ - super(message); +/** + * @typedef {Object} Records + * @property {RecordsChunks=} chunks + * @property {RecordsModules=} modules + */ - this.name = "ModuleBuildError"; - this.details = details; - this.error = err; +class RecordIdsPlugin { + /** + * @param {Object} options Options object + * @param {boolean=} options.portableIds true, when ids need to be portable + */ + constructor(options) { + this.options = options || {}; } - serialize(context) { - const { write } = context; + /** + * @param {Compiler} compiler the Compiler + * @returns {void} + */ + apply(compiler) { + const portableIds = this.options.portableIds; - write(this.error); + const makePathsRelative = + identifierUtils.makePathsRelative.bindContextCache( + compiler.context, + compiler.root + ); - super.serialize(context); - } + /** + * @param {Module} module the module + * @returns {string} the (portable) identifier + */ + const getModuleIdentifier = module => { + if (portableIds) { + return makePathsRelative(module.identifier()); + } + return module.identifier(); + }; - deserialize(context) { - const { read } = context; + compiler.hooks.compilation.tap("RecordIdsPlugin", compilation => { + compilation.hooks.recordModules.tap( + "RecordIdsPlugin", + /** + * @param {Module[]} modules the modules array + * @param {Records} records the records object + * @returns {void} + */ + (modules, records) => { + const chunkGraph = compilation.chunkGraph; + if (!records.modules) records.modules = {}; + if (!records.modules.byIdentifier) records.modules.byIdentifier = {}; + /** @type {Set} */ + const usedIds = new Set(); + for (const module of modules) { + const moduleId = chunkGraph.getModuleId(module); + if (typeof moduleId !== "number") continue; + const identifier = getModuleIdentifier(module); + records.modules.byIdentifier[identifier] = moduleId; + usedIds.add(moduleId); + } + records.modules.usedIds = Array.from(usedIds).sort(compareNumbers); + } + ); + compilation.hooks.reviveModules.tap( + "RecordIdsPlugin", + /** + * @param {Module[]} modules the modules array + * @param {Records} records the records object + * @returns {void} + */ + (modules, records) => { + if (!records.modules) return; + if (records.modules.byIdentifier) { + const chunkGraph = compilation.chunkGraph; + /** @type {Set} */ + const usedIds = new Set(); + for (const module of modules) { + const moduleId = chunkGraph.getModuleId(module); + if (moduleId !== null) continue; + const identifier = getModuleIdentifier(module); + const id = records.modules.byIdentifier[identifier]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunkGraph.setModuleId(module, id); + } + } + if (Array.isArray(records.modules.usedIds)) { + compilation.usedModuleIds = new Set(records.modules.usedIds); + } + } + ); - this.error = read(); + /** + * @param {Chunk} chunk the chunk + * @returns {string[]} sources of the chunk + */ + const getChunkSources = chunk => { + /** @type {string[]} */ + const sources = []; + for (const chunkGroup of chunk.groupsIterable) { + const index = chunkGroup.chunks.indexOf(chunk); + if (chunkGroup.name) { + sources.push(`${index} ${chunkGroup.name}`); + } else { + for (const origin of chunkGroup.origins) { + if (origin.module) { + if (origin.request) { + sources.push( + `${index} ${getModuleIdentifier(origin.module)} ${ + origin.request + }` + ); + } else if (typeof origin.loc === "string") { + sources.push( + `${index} ${getModuleIdentifier(origin.module)} ${ + origin.loc + }` + ); + } else if ( + origin.loc && + typeof origin.loc === "object" && + "start" in origin.loc + ) { + sources.push( + `${index} ${getModuleIdentifier( + origin.module + )} ${JSON.stringify(origin.loc.start)}` + ); + } + } + } + } + } + return sources; + }; - super.deserialize(context); + compilation.hooks.recordChunks.tap( + "RecordIdsPlugin", + /** + * @param {Chunk[]} chunks the chunks array + * @param {Records} records the records object + * @returns {void} + */ + (chunks, records) => { + if (!records.chunks) records.chunks = {}; + if (!records.chunks.byName) records.chunks.byName = {}; + if (!records.chunks.bySource) records.chunks.bySource = {}; + /** @type {Set} */ + const usedIds = new Set(); + for (const chunk of chunks) { + if (typeof chunk.id !== "number") continue; + const name = chunk.name; + if (name) records.chunks.byName[name] = chunk.id; + const sources = getChunkSources(chunk); + for (const source of sources) { + records.chunks.bySource[source] = chunk.id; + } + usedIds.add(chunk.id); + } + records.chunks.usedIds = Array.from(usedIds).sort(compareNumbers); + } + ); + compilation.hooks.reviveChunks.tap( + "RecordIdsPlugin", + /** + * @param {Chunk[]} chunks the chunks array + * @param {Records} records the records object + * @returns {void} + */ + (chunks, records) => { + if (!records.chunks) return; + /** @type {Set} */ + const usedIds = new Set(); + if (records.chunks.byName) { + for (const chunk of chunks) { + if (chunk.id !== null) continue; + if (!chunk.name) continue; + const id = records.chunks.byName[chunk.name]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunk.id = id; + chunk.ids = [id]; + } + } + if (records.chunks.bySource) { + for (const chunk of chunks) { + if (chunk.id !== null) continue; + const sources = getChunkSources(chunk); + for (const source of sources) { + const id = records.chunks.bySource[source]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunk.id = id; + chunk.ids = [id]; + break; + } + } + } + if (Array.isArray(records.chunks.usedIds)) { + compilation.usedChunkIds = new Set(records.chunks.usedIds); + } + } + ); + }); } } - -makeSerializable(ModuleBuildError, "webpack/lib/ModuleBuildError"); - -module.exports = ModuleBuildError; +module.exports = RecordIdsPlugin; /***/ }), -/***/ 67409: +/***/ 73406: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -52002,44 +52005,38 @@ module.exports = ModuleBuildError; -const WebpackError = __webpack_require__(53799); - -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Module")} Module */ +const { contextify } = __webpack_require__(82186); -class ModuleDependencyError extends WebpackError { +class RequestShortener { /** - * Creates an instance of ModuleDependencyError. - * @param {Module} module module tied to dependency - * @param {Error} err error thrown - * @param {DependencyLocation} loc location of dependency + * @param {string} dir the directory + * @param {object=} associatedObjectForCache an object to which the cache will be attached */ - 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; + constructor(dir, associatedObjectForCache) { + this.contextify = contextify.bindContextCache( + dir, + associatedObjectForCache + ); + } - if (err && /** @type {any} */ (err).hideStack) { - this.stack = - err.stack.split("\n").slice(1).join("\n") + "\n\n" + this.stack; + /** + * @param {string | undefined | null} request the request to shorten + * @returns {string | undefined | null} the shortened request + */ + shorten(request) { + if (!request) { + return request; } + return this.contextify(request); } } -module.exports = ModuleDependencyError; +module.exports = RequestShortener; /***/ }), -/***/ 29656: +/***/ 88846: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -52050,49 +52047,81 @@ module.exports = ModuleDependencyError; -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); +const RuntimeGlobals = __webpack_require__(16475); +const ConstDependency = __webpack_require__(76911); +const { + toConstantDependency +} = __webpack_require__(93998); -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Compiler")} Compiler */ -class ModuleDependencyWarning extends WebpackError { +module.exports = class RequireJsStuffPlugin { /** - * @param {Module} module module tied to dependency - * @param {Error} err error thrown - * @param {DependencyLocation} loc location of dependency + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - constructor(module, err, loc) { - super(err ? err.message : ""); + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireJsStuffPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireJs === undefined || + !parserOptions.requireJs + ) { + return; + } - 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; + parser.hooks.call + .for("require.config") + .tap( + "RequireJsStuffPlugin", + toConstantDependency(parser, "undefined") + ); + parser.hooks.call + .for("requirejs.config") + .tap( + "RequireJsStuffPlugin", + toConstantDependency(parser, "undefined") + ); - if (err && /** @type {any} */ (err).hideStack) { - this.stack = - err.stack.split("\n").slice(1).join("\n") + "\n\n" + this.stack; - } + parser.hooks.expression + .for("require.version") + .tap( + "RequireJsStuffPlugin", + toConstantDependency(parser, JSON.stringify("0.0.0")) + ); + parser.hooks.expression + .for("requirejs.onError") + .tap( + "RequireJsStuffPlugin", + toConstantDependency( + parser, + RuntimeGlobals.uncaughtErrorHandler, + [RuntimeGlobals.uncaughtErrorHandler] + ) + ); + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireJsStuffPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireJsStuffPlugin", handler); + } + ); } -} - -makeSerializable( - ModuleDependencyWarning, - "webpack/lib/ModuleDependencyWarning" -); - -module.exports = ModuleDependencyWarning; +}; /***/ }), -/***/ 23744: +/***/ 30217: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -52103,66 +52132,156 @@ module.exports = ModuleDependencyWarning; -const { cleanUp } = __webpack_require__(59985); -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); - -class ModuleError extends WebpackError { - /** - * @param {Error} err error thrown - * @param {{from?: string|null}} info additional info - */ - constructor(err, { from = null } = {}) { - let message = "Module Error"; +const Factory = (__webpack_require__(9256).ResolverFactory); +const { HookMap, SyncHook, SyncWaterfallHook } = __webpack_require__(6967); +const { + cachedCleverMerge, + removeOperations, + resolveByProperty +} = __webpack_require__(60839); - if (from) { - message += ` (from ${from}):\n`; - } else { - message += ": "; - } +/** @typedef {import("enhanced-resolve").ResolveOptions} ResolveOptions */ +/** @typedef {import("enhanced-resolve").Resolver} Resolver */ +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */ +/** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */ - if (err && typeof err === "object" && err.message) { - message += err.message; - } else if (err) { - message += err; - } +/** @typedef {WebpackResolveOptions & {dependencyType?: string, resolveToContext?: boolean }} ResolveOptionsWithDependencyType */ +/** + * @typedef {Object} WithOptions + * @property {function(Partial): ResolverWithOptions} withOptions create a resolver with additional/different options + */ - super(message); +/** @typedef {Resolver & WithOptions} ResolverWithOptions */ - this.name = "ModuleError"; - this.error = err; - this.details = - err && typeof err === "object" && err.stack - ? cleanUp(err.stack, this.message) - : undefined; - } +// need to be hoisted on module level for caching identity +const EMPTY_RESOLVE_OPTIONS = {}; - serialize(context) { - const { write } = context; +/** + * @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType enhanced options + * @returns {ResolveOptions} merged options + */ +const convertToResolveOptions = resolveOptionsWithDepType => { + const { dependencyType, plugins, ...remaining } = resolveOptionsWithDepType; - write(this.error); + // check type compat + /** @type {Partial} */ + const partialOptions = { + ...remaining, + plugins: + plugins && + /** @type {ResolvePluginInstance[]} */ ( + plugins.filter(item => item !== "...") + ) + }; - super.serialize(context); + if (!partialOptions.fileSystem) { + throw new Error( + "fileSystem is missing in resolveOptions, but it's required for enhanced-resolve" + ); } + // These weird types validate that we checked all non-optional properties + const options = + /** @type {Partial & Pick} */ ( + partialOptions + ); - deserialize(context) { - const { read } = context; + return removeOperations( + resolveByProperty(options, "byDependency", dependencyType) + ); +}; - this.error = read(); +/** + * @typedef {Object} ResolverCache + * @property {WeakMap} direct + * @property {Map} stringified + */ - super.deserialize(context); +module.exports = class ResolverFactory { + constructor() { + this.hooks = Object.freeze({ + /** @type {HookMap>} */ + resolveOptions: new HookMap( + () => new SyncWaterfallHook(["resolveOptions"]) + ), + /** @type {HookMap>} */ + resolver: new HookMap( + () => new SyncHook(["resolver", "resolveOptions", "userResolveOptions"]) + ) + }); + /** @type {Map} */ + this.cache = new Map(); } -} - -makeSerializable(ModuleError, "webpack/lib/ModuleError"); -module.exports = ModuleError; + /** + * @param {string} type type of resolver + * @param {ResolveOptionsWithDependencyType=} resolveOptions options + * @returns {ResolverWithOptions} the resolver + */ + get(type, resolveOptions = EMPTY_RESOLVE_OPTIONS) { + let typedCaches = this.cache.get(type); + if (!typedCaches) { + typedCaches = { + direct: new WeakMap(), + stringified: new Map() + }; + this.cache.set(type, typedCaches); + } + const cachedResolver = typedCaches.direct.get(resolveOptions); + if (cachedResolver) { + return cachedResolver; + } + const ident = JSON.stringify(resolveOptions); + const resolver = typedCaches.stringified.get(ident); + if (resolver) { + typedCaches.direct.set(resolveOptions, resolver); + return resolver; + } + const newResolver = this._create(type, resolveOptions); + typedCaches.direct.set(resolveOptions, newResolver); + typedCaches.stringified.set(ident, newResolver); + return newResolver; + } + + /** + * @param {string} type type of resolver + * @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType options + * @returns {ResolverWithOptions} the resolver + */ + _create(type, resolveOptionsWithDepType) { + /** @type {ResolveOptionsWithDependencyType} */ + const originalResolveOptions = { ...resolveOptionsWithDepType }; + + const resolveOptions = convertToResolveOptions( + this.hooks.resolveOptions.for(type).call(resolveOptionsWithDepType) + ); + const resolver = /** @type {ResolverWithOptions} */ ( + Factory.createResolver(resolveOptions) + ); + if (!resolver) { + throw new Error("No resolver created"); + } + /** @type {WeakMap, ResolverWithOptions>} */ + const childCache = new WeakMap(); + resolver.withOptions = options => { + const cacheEntry = childCache.get(options); + if (cacheEntry !== undefined) return cacheEntry; + const mergedOptions = cachedCleverMerge(originalResolveOptions, options); + const resolver = this.get(type, mergedOptions); + childCache.set(options, resolver); + return resolver; + }; + this.hooks.resolver + .for(type) + .call(resolver, resolveOptions, originalResolveOptions); + return resolver; + } +}; /***/ }), -/***/ 51010: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 16475: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -52172,1203 +52291,2106 @@ module.exports = ModuleError; -/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Module")} Module */ +/** + * the internal require function + */ +exports.require = "__webpack_require__"; /** - * @typedef {Object} ModuleFactoryResult - * @property {Module=} module the created module or unset if no module was created - * @property {Set=} fileDependencies - * @property {Set=} contextDependencies - * @property {Set=} missingDependencies - * @property {boolean=} cacheable allow to use the unsafe cache + * access to properties of the internal require function/object */ +exports.requireScope = "__webpack_require__.*"; /** - * @typedef {Object} ModuleFactoryCreateDataContextInfo - * @property {string} issuer - * @property {string | null=} issuerLayer - * @property {string} compiler + * the internal exports object */ +exports.exports = "__webpack_exports__"; /** - * @typedef {Object} ModuleFactoryCreateData - * @property {ModuleFactoryCreateDataContextInfo} contextInfo - * @property {ResolveOptions=} resolveOptions - * @property {string} context - * @property {Dependency[]} dependencies + * top-level this need to be the exports object */ +exports.thisAsExports = "top-level-this-exports"; -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 = __webpack_require__(77198); - throw new AbstractMethodError(); - } -} +/** + * runtime need to return the exports of the last entry module + */ +exports.returnExportsFromRuntime = "return-exports-from-runtime"; -module.exports = ModuleFactory; +/** + * the internal module object + */ +exports.module = "module"; +/** + * the internal module object + */ +exports.moduleId = "module.id"; -/***/ }), +/** + * the internal module object + */ +exports.moduleLoaded = "module.loaded"; -/***/ 88821: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/** + * the bundle public path + */ +exports.publicPath = "__webpack_require__.p"; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * the module id of the entry point + */ +exports.entryModuleId = "__webpack_require__.s"; +/** + * the module cache + */ +exports.moduleCache = "__webpack_require__.c"; +/** + * the module functions + */ +exports.moduleFactories = "__webpack_require__.m"; -const NormalModule = __webpack_require__(39); -const createHash = __webpack_require__(49835); -const memoize = __webpack_require__(78676); +/** + * the module functions, with only write access + */ +exports.moduleFactoriesAddOnly = "__webpack_require__.m (add only)"; -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {typeof import("./util/Hash")} Hash */ +/** + * the chunk ensure function + */ +exports.ensureChunk = "__webpack_require__.e"; -const ModuleFilenameHelpers = exports; +/** + * an object with handlers to ensure a chunk + */ +exports.ensureChunkHandlers = "__webpack_require__.f"; -// 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; +/** + * a runtime requirement if ensureChunkHandlers should include loading of chunk needed for entries + */ +exports.ensureChunkIncludeEntries = "__webpack_require__.f (include entries)"; -const getAfter = (strFn, token) => { - return () => { - const str = strFn(); - const idx = str.indexOf(token); - return idx < 0 ? "" : str.substr(idx); - }; -}; +/** + * the chunk prefetch function + */ +exports.prefetchChunk = "__webpack_require__.E"; -const getBefore = (strFn, token) => { - return () => { - const str = strFn(); - const idx = str.lastIndexOf(token); - return idx < 0 ? "" : str.substr(0, idx); - }; -}; +/** + * an object with handlers to prefetch a chunk + */ +exports.prefetchChunkHandlers = "__webpack_require__.F"; -const getHash = (strFn, hashFunction) => { - return () => { - const hash = createHash(hashFunction); - hash.update(strFn()); - const digest = /** @type {string} */ (hash.digest("hex")); - return digest.substr(0, 4); - }; -}; +/** + * the chunk preload function + */ +exports.preloadChunk = "__webpack_require__.G"; -const asRegExp = test => { - if (typeof test === "string") { - test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); - } - return test; -}; +/** + * an object with handlers to preload a chunk + */ +exports.preloadChunkHandlers = "__webpack_require__.H"; -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; -}; +/** + * the exported property define getters function + */ +exports.definePropertyGetters = "__webpack_require__.d"; -const REGEXP = /\[\\*([\w-]+)\\*\]/gi; +/** + * define compatibility on export + */ +exports.makeNamespaceObject = "__webpack_require__.r"; /** - * - * @param {Module | string} module the module - * @param {TODO} options options - * @param {Object} contextInfo context info - * @param {RequestShortener} contextInfo.requestShortener requestShortener - * @param {ChunkGraph} contextInfo.chunkGraph chunk graph - * @param {string | Hash} contextInfo.hashFunction the hash function to use - * @returns {string} the filename + * create a fake namespace object */ -ModuleFilenameHelpers.createFilename = ( - module = "", - options, - { requestShortener, chunkGraph, hashFunction = "md4" } -) => { - const opts = { - namespace: "", - moduleFilenameTemplate: "", - ...(typeof options === "object" - ? options - : { - moduleFilenameTemplate: options - }) - }; +exports.createFakeNamespaceObject = "__webpack_require__.t"; - let absoluteResourcePath; - let hash; - let identifier; - let moduleId; - let shortIdentifier; - if (typeof module === "string") { - shortIdentifier = memoize(() => requestShortener.shorten(module)); - identifier = shortIdentifier; - moduleId = () => ""; - absoluteResourcePath = () => module.split("!").pop(); - hash = getHash(identifier, hashFunction); - } else { - shortIdentifier = memoize(() => - module.readableIdentifier(requestShortener) - ); - identifier = memoize(() => requestShortener.shorten(module.identifier())); - moduleId = () => chunkGraph.getModuleId(module); - absoluteResourcePath = () => - module instanceof NormalModule - ? module.resource - : module.identifier().split("!").pop(); - hash = getHash(identifier, hashFunction); - } - const resource = memoize(() => shortIdentifier().split("!").pop()); +/** + * compatibility get default export + */ +exports.compatGetDefaultExport = "__webpack_require__.n"; - 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 - }) - ); - } +/** + * harmony module decorator + */ +exports.harmonyModuleDecorator = "__webpack_require__.hmd"; - // TODO webpack 6: consider removing alternatives without dashes - /** @type {Map} */ - 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] - ]); +/** + * node.js module decorator + */ +exports.nodeModuleDecorator = "__webpack_require__.nmd"; - // 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; - }); -}; +/** + * the webpack hash + */ +exports.getFullHash = "__webpack_require__.h"; -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; - } - }); -}; +/** + * an object containing all installed WebAssembly.Instance export objects keyed by module id + */ +exports.wasmInstances = "__webpack_require__.w"; -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); - } -}; +/** + * instantiate a wasm instance from module exports object, id, hash and importsObject + */ +exports.instantiateWasm = "__webpack_require__.v"; -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; -}; +/** + * the uncaught error handler for the webpack runtime + */ +exports.uncaughtErrorHandler = "__webpack_require__.oe"; +/** + * the script nonce + */ +exports.scriptNonce = "__webpack_require__.nc"; -/***/ }), +/** + * function to load a script tag. + * Arguments: (url: string, done: (event) => void), key?: string | number, chunkId?: string | number) => void + * done function is called when loading has finished or timeout occurred. + * It will attach to existing script tags with data-webpack == uniqueName + ":" + key or src == url. + */ +exports.loadScript = "__webpack_require__.l"; -/***/ 99988: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * function to promote a string to a TrustedScript using webpack's Trusted + * Types policy + * Arguments: (script: string) => TrustedScript + */ +exports.createScript = "__webpack_require__.ts"; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * function to promote a string to a TrustedScriptURL using webpack's Trusted + * Types policy + * Arguments: (url: string) => TrustedScriptURL + */ +exports.createScriptUrl = "__webpack_require__.tu"; + +/** + * function to return webpack's Trusted Types policy + * Arguments: () => TrustedTypePolicy + */ +exports.getTrustedTypesPolicy = "__webpack_require__.tt"; + +/** + * the chunk name of the chunk with the runtime + */ +exports.chunkName = "__webpack_require__.cn"; +/** + * the runtime id of the current runtime + */ +exports.runtimeId = "__webpack_require__.j"; +/** + * the filename of the script part of the chunk + */ +exports.getChunkScriptFilename = "__webpack_require__.u"; -const util = __webpack_require__(73837); -const ExportsInfo = __webpack_require__(63686); -const ModuleGraphConnection = __webpack_require__(40639); -const SortableSet = __webpack_require__(13098); -const WeakTupleMap = __webpack_require__(28745); +/** + * the filename of the css part of the chunk + */ +exports.getChunkCssFilename = "__webpack_require__.k"; -/** @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 */ +/** + * a flag when a module/chunk/tree has css modules + */ +exports.hasCssModules = "has css modules"; /** - * @callback OptimizationBailoutFunction - * @param {RequestShortener} requestShortener - * @returns {string} + * the filename of the script part of the hot update chunk */ +exports.getChunkUpdateScriptFilename = "__webpack_require__.hu"; -const EMPTY_SET = new Set(); +/** + * the filename of the css part of the hot update chunk + */ +exports.getChunkUpdateCssFilename = "__webpack_require__.hk"; /** - * @param {SortableSet} set input - * @returns {readonly Map} mapped by origin module + * startup signal from runtime + * This will be called when the runtime chunk has been loaded. */ -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; -}; +exports.startup = "__webpack_require__.x"; /** - * @param {SortableSet} set input - * @returns {readonly Map} mapped by module + * @deprecated + * creating a default startup function with the entry modules */ -const getConnectionsByModule = set => { - const map = new Map(); - /** @type {Module | 0} */ - let lastModule = 0; - /** @type {ModuleGraphConnection[]} */ - let lastList = undefined; - for (const connection of set) { - const { module } = connection; - if (lastModule === module) { - lastList.push(connection); - } else { - lastModule = module; - const list = map.get(module); - if (list !== undefined) { - lastList = list; - list.push(connection); - } else { - const list = [connection]; - lastList = list; - map.set(module, list); - } - } - } - return map; -}; +exports.startupNoDefault = "__webpack_require__.x (no default handler)"; -class ModuleGraphModule { - constructor() { - /** @type {SortableSet} */ - this.incomingConnections = new SortableSet(); - /** @type {SortableSet | 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; - /** @type {ModuleGraphConnection[]} */ - this._unassignedConnections = undefined; - } -} +/** + * startup signal from runtime but only used to add logic after the startup + */ +exports.startupOnlyAfter = "__webpack_require__.x (only after)"; -class ModuleGraph { - constructor() { - /** @type {WeakMap} */ - this._dependencyMap = new WeakMap(); - /** @type {Map} */ - this._moduleMap = new Map(); - /** @type {WeakMap} */ - this._metaMap = new WeakMap(); +/** + * startup signal from runtime but only used to add sync logic before the startup + */ +exports.startupOnlyBefore = "__webpack_require__.x (only before)"; - /** @type {WeakTupleMap} */ - this._cache = undefined; +/** + * global callback functions for installing chunks + */ +exports.chunkCallback = "webpackChunk"; - /** @type {Map>} */ - this._moduleMemCaches = undefined; - } +/** + * method to startup an entrypoint with needed chunks. + * Signature: (moduleId: Id, chunkIds: Id[]) => any. + * Returns the exports of the module or a Promise + */ +exports.startupEntrypoint = "__webpack_require__.X"; + +/** + * register deferred code, which will run when certain + * chunks are loaded. + * Signature: (chunkIds: Id[], fn: () => any, priority: int >= 0 = 0) => any + * Returned value will be returned directly when all chunks are already loaded + * When (priority & 1) it will wait for all other handlers with lower priority to + * be executed before itself is executed + */ +exports.onChunksLoaded = "__webpack_require__.O"; + +/** + * method to install a chunk that was loaded somehow + * Signature: ({ id, ids, modules, runtime }) => void + */ +exports.externalInstallChunk = "__webpack_require__.C"; + +/** + * interceptor for module executions + */ +exports.interceptModuleExecution = "__webpack_require__.i"; + +/** + * the global object + */ +exports.global = "__webpack_require__.g"; + +/** + * an object with all share scopes + */ +exports.shareScopeMap = "__webpack_require__.S"; + +/** + * The sharing init sequence function (only runs once per share scope). + * Has one argument, the name of the share scope. + * Creates a share scope if not existing + */ +exports.initializeSharing = "__webpack_require__.I"; + +/** + * The current scope when getting a module from a remote + */ +exports.currentRemoteGetScope = "__webpack_require__.R"; + +/** + * the filename of the HMR manifest + */ +exports.getUpdateManifestFilename = "__webpack_require__.hmrF"; + +/** + * function downloading the update manifest + */ +exports.hmrDownloadManifest = "__webpack_require__.hmrM"; + +/** + * array with handler functions to download chunk updates + */ +exports.hmrDownloadUpdateHandlers = "__webpack_require__.hmrC"; + +/** + * object with all hmr module data for all modules + */ +exports.hmrModuleData = "__webpack_require__.hmrD"; + +/** + * array with handler functions when a module should be invalidated + */ +exports.hmrInvalidateModuleHandlers = "__webpack_require__.hmrI"; + +/** + * the prefix for storing state of runtime modules when hmr is enabled + */ +exports.hmrRuntimeStatePrefix = "__webpack_require__.hmrS"; + +/** + * the AMD define function + */ +exports.amdDefine = "__webpack_require__.amdD"; + +/** + * the AMD options + */ +exports.amdOptions = "__webpack_require__.amdO"; + +/** + * the System polyfill object + */ +exports.system = "__webpack_require__.System"; + +/** + * the shorthand for Object.prototype.hasOwnProperty + * using of it decreases the compiled bundle size + */ +exports.hasOwnProperty = "__webpack_require__.o"; + +/** + * the System.register context object + */ +exports.systemContext = "__webpack_require__.y"; +/** + * the baseURI of current document + */ +exports.baseURI = "__webpack_require__.b"; + +/** + * a RelativeURL class when relative URLs are used + */ +exports.relativeUrl = "__webpack_require__.U"; + +/** + * Creates an async module. The body function must be a async function. + * "module.exports" will be decorated with an AsyncModulePromise. + * The body function will be called. + * To handle async dependencies correctly do this: "([a, b, c] = await handleDependencies([a, b, c]));". + * If "hasAwaitAfterDependencies" is truthy, "handleDependencies()" must be called at the end of the body function. + * Signature: function( + * module: Module, + * body: (handleDependencies: (deps: AsyncModulePromise[]) => Promise & () => void, + * hasAwaitAfterDependencies?: boolean + * ) => void + */ +exports.asyncModule = "__webpack_require__.a"; + + +/***/ }), + +/***/ 16963: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { RawSource } = __webpack_require__(51255); +const OriginalSource = (__webpack_require__(51255).OriginalSource); +const Module = __webpack_require__(73208); + +/** @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("./Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("./WebpackError")} WebpackError */ +/** @typedef {import("./util/Hash")} Hash */ +/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ + +const TYPES = new Set(["runtime"]); + +class RuntimeModule extends Module { /** - * @param {Module} module the module - * @returns {ModuleGraphModule} the internal module + * @param {string} name a readable name + * @param {number=} stage an optional stage */ - _getModuleGraphModule(module) { - let mgm = this._moduleMap.get(module); - if (mgm === undefined) { - mgm = new ModuleGraphModule(); - this._moduleMap.set(module, mgm); - } - return mgm; + constructor(name, stage = 0) { + super("runtime"); + this.name = name; + this.stage = stage; + this.buildMeta = {}; + this.buildInfo = {}; + /** @type {Compilation} */ + this.compilation = undefined; + /** @type {Chunk} */ + this.chunk = undefined; + /** @type {ChunkGraph} */ + this.chunkGraph = undefined; + this.fullHash = false; + this.dependentHash = false; + /** @type {string} */ + this._cachedGeneratedCode = undefined; } /** - * @param {Dependency} dependency the dependency - * @param {DependenciesBlock} block parent block - * @param {Module} module parent module - * @param {number=} indexInBlock position in block + * @param {Compilation} compilation the compilation + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph * @returns {void} */ - setParents(dependency, block, module, indexInBlock = -1) { - dependency._parentDependenciesBlockIndex = indexInBlock; - dependency._parentDependenciesBlock = block; - dependency._parentModule = module; + attach(compilation, chunk, chunkGraph = compilation.chunkGraph) { + this.compilation = compilation; + this.chunk = chunk; + this.chunkGraph = chunkGraph; } /** - * @param {Dependency} dependency the dependency - * @returns {Module} parent module + * @returns {string} a unique identifier of the module */ - getParentModule(dependency) { - return dependency._parentModule; + identifier() { + return `webpack/runtime/${this.name}`; } /** - * @param {Dependency} dependency the dependency - * @returns {DependenciesBlock} parent block + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module */ - getParentBlock(dependency) { - return dependency._parentDependenciesBlock; + readableIdentifier(requestShortener) { + return `webpack/runtime/${this.name}`; } /** - * @param {Dependency} dependency the dependency - * @returns {number} index + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} */ - getParentBlockIndex(dependency) { - return dependency._parentDependenciesBlockIndex; + needBuild(context, callback) { + return callback(null, false); } /** - * @param {Module} originModule the referencing module - * @param {Dependency} dependency the referencing dependency - * @param {Module} module the referenced module + * @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} */ - setResolvedModule(originModule, dependency, module) { - const connection = new ModuleGraphConnection( - originModule, - dependency, - module, - undefined, - dependency.weak, - dependency.getCondition(this) - ); - const connections = this._getModuleGraphModule(module).incomingConnections; - connections.add(connection); - if (originModule) { - const mgm = this._getModuleGraphModule(originModule); - if (mgm._unassignedConnections === undefined) { - mgm._unassignedConnections = []; - } - mgm._unassignedConnections.push(connection); - if (mgm.outgoingConnections === undefined) { - mgm.outgoingConnections = new SortableSet(); - } - mgm.outgoingConnections.add(connection); - } else { - this._dependencyMap.set(dependency, connection); - } + build(options, compilation, resolver, fs, callback) { + // do nothing + // should not be called as runtime modules are added later to the compilation + callback(); } /** - * @param {Dependency} dependency the referencing dependency - * @param {Module} module the referenced module + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context * @returns {void} */ - updateModule(dependency, module) { - const connection = this.getConnection(dependency); - if (connection.module === module) return; - const newConnection = connection.clone(); - newConnection.module = module; - this._dependencyMap.set(dependency, newConnection); - connection.setActive(false); - const originMgm = this._getModuleGraphModule(connection.originModule); - originMgm.outgoingConnections.add(newConnection); - const targetMgm = this._getModuleGraphModule(module); - targetMgm.incomingConnections.add(newConnection); + updateHash(hash, context) { + hash.update(this.name); + hash.update(`${this.stage}`); + try { + if (this.fullHash || this.dependentHash) { + // Do not use getGeneratedCode here, because i. e. compilation hash might be not + // ready at this point. We will cache it later instead. + hash.update(this.generate()); + } else { + hash.update(this.getGeneratedCode()); + } + } catch (err) { + hash.update(err.message); + } + super.updateHash(hash, context); } /** - * @param {Dependency} dependency the referencing dependency - * @returns {void} + * @returns {Set} types available (do not mutate) */ - removeConnection(dependency) { - const connection = this.getConnection(dependency); - const targetMgm = this._getModuleGraphModule(connection.module); - targetMgm.incomingConnections.delete(connection); - const originMgm = this._getModuleGraphModule(connection.originModule); - originMgm.outgoingConnections.delete(connection); - this._dependencyMap.set(dependency, null); + getSourceTypes() { + return TYPES; } /** - * @param {Dependency} dependency the referencing dependency - * @param {string} explanation an explanation - * @returns {void} + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - addExplanation(dependency, explanation) { - const connection = this.getConnection(dependency); - connection.addExplanation(explanation); + codeGeneration(context) { + const sources = new Map(); + const generatedCode = this.getGeneratedCode(); + if (generatedCode) { + sources.set( + "runtime", + this.useSourceMap || this.useSimpleSourceMap + ? new OriginalSource(generatedCode, this.identifier()) + : new RawSource(generatedCode) + ); + } + return { + sources, + runtimeRequirements: null + }; } /** - * @param {Module} sourceModule the source module - * @param {Module} targetModule the target module - * @returns {void} + * @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) */ - 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; + size(type) { + try { + const source = this.getGeneratedCode(); + return source ? source.length : 0; + } catch (e) { + return 0; + } } + /* istanbul ignore next */ /** - * @param {Module} module the module - * @returns {void} + * @abstract + * @returns {string} runtime code */ - removeModuleAttributes(module) { - const mgm = this._getModuleGraphModule(module); - mgm.postOrderIndex = null; - mgm.preOrderIndex = null; - mgm.depth = null; - mgm.async = false; + generate() { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } /** - * @returns {void} + * @returns {string} runtime code */ - removeAllModuleAttributes() { - for (const mgm of this._moduleMap.values()) { - mgm.postOrderIndex = null; - mgm.preOrderIndex = null; - mgm.depth = null; - mgm.async = false; + getGeneratedCode() { + if (this._cachedGeneratedCode) { + return this._cachedGeneratedCode; } + return (this._cachedGeneratedCode = this.generate()); } /** - * @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} + * @returns {boolean} true, if the runtime module should get it's own scope */ - 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 SortableSet(); - } - 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); - } - } + shouldIsolate() { + return true; } +} + +/** + * Runtime modules without any dependencies to other runtime modules + */ +RuntimeModule.STAGE_NORMAL = 0; + +/** + * Runtime modules with simple dependencies on other runtime modules + */ +RuntimeModule.STAGE_BASIC = 5; + +/** + * Runtime modules which attach to handlers of other runtime modules + */ +RuntimeModule.STAGE_ATTACH = 10; + +/** + * Runtime modules which trigger actions on bootstrap + */ +RuntimeModule.STAGE_TRIGGER = 20; + +module.exports = RuntimeModule; + + +/***/ }), + +/***/ 2307: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const { getChunkFilenameTemplate } = __webpack_require__(47283); +const RuntimeRequirementsDependency = __webpack_require__(24187); +const JavascriptModulesPlugin = __webpack_require__(89464); +const AsyncModuleRuntimeModule = __webpack_require__(63672); +const AutoPublicPathRuntimeModule = __webpack_require__(66532); +const CompatGetDefaultExportRuntimeModule = __webpack_require__(44793); +const CompatRuntimeModule = __webpack_require__(88234); +const CreateFakeNamespaceObjectRuntimeModule = __webpack_require__(94669); +const CreateScriptRuntimeModule = __webpack_require__(2759); +const CreateScriptUrlRuntimeModule = __webpack_require__(21213); +const DefinePropertyGettersRuntimeModule = __webpack_require__(75481); +const EnsureChunkRuntimeModule = __webpack_require__(71519); +const GetChunkFilenameRuntimeModule = __webpack_require__(34277); +const GetMainFilenameRuntimeModule = __webpack_require__(10029); +const GetTrustedTypesPolicyRuntimeModule = __webpack_require__(38713); +const GlobalRuntimeModule = __webpack_require__(23255); +const HasOwnPropertyRuntimeModule = __webpack_require__(8011); +const LoadScriptRuntimeModule = __webpack_require__(19942); +const MakeNamespaceObjectRuntimeModule = __webpack_require__(65714); +const OnChunksLoadedRuntimeModule = __webpack_require__(44518); +const PublicPathRuntimeModule = __webpack_require__(56030); +const RelativeUrlRuntimeModule = __webpack_require__(4537); +const RuntimeIdRuntimeModule = __webpack_require__(97115); +const SystemContextRuntimeModule = __webpack_require__(80655); +const ShareRuntimeModule = __webpack_require__(96066); +const StringXor = __webpack_require__(40293); + +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ + +const GLOBALS_ON_REQUIRE = [ + RuntimeGlobals.chunkName, + RuntimeGlobals.runtimeId, + RuntimeGlobals.compatGetDefaultExport, + RuntimeGlobals.createFakeNamespaceObject, + RuntimeGlobals.createScript, + RuntimeGlobals.createScriptUrl, + RuntimeGlobals.getTrustedTypesPolicy, + RuntimeGlobals.definePropertyGetters, + RuntimeGlobals.ensureChunk, + RuntimeGlobals.entryModuleId, + RuntimeGlobals.getFullHash, + RuntimeGlobals.global, + RuntimeGlobals.makeNamespaceObject, + RuntimeGlobals.moduleCache, + RuntimeGlobals.moduleFactories, + RuntimeGlobals.moduleFactoriesAddOnly, + RuntimeGlobals.interceptModuleExecution, + RuntimeGlobals.publicPath, + RuntimeGlobals.baseURI, + RuntimeGlobals.relativeUrl, + RuntimeGlobals.scriptNonce, + RuntimeGlobals.uncaughtErrorHandler, + RuntimeGlobals.asyncModule, + RuntimeGlobals.wasmInstances, + RuntimeGlobals.instantiateWasm, + RuntimeGlobals.shareScopeMap, + RuntimeGlobals.initializeSharing, + RuntimeGlobals.loadScript, + RuntimeGlobals.systemContext, + RuntimeGlobals.onChunksLoaded +]; + +const MODULE_DEPENDENCIES = { + [RuntimeGlobals.moduleLoaded]: [RuntimeGlobals.module], + [RuntimeGlobals.moduleId]: [RuntimeGlobals.module] +}; +const TREE_DEPENDENCIES = { + [RuntimeGlobals.definePropertyGetters]: [RuntimeGlobals.hasOwnProperty], + [RuntimeGlobals.compatGetDefaultExport]: [ + RuntimeGlobals.definePropertyGetters + ], + [RuntimeGlobals.createFakeNamespaceObject]: [ + RuntimeGlobals.definePropertyGetters, + RuntimeGlobals.makeNamespaceObject, + RuntimeGlobals.require + ], + [RuntimeGlobals.initializeSharing]: [RuntimeGlobals.shareScopeMap], + [RuntimeGlobals.shareScopeMap]: [RuntimeGlobals.hasOwnProperty] +}; + +class RuntimePlugin { /** - * @param {Module} oldModule the old referencing module - * @param {Module} newModule the new referencing module - * @param {function(ModuleGraphConnection): boolean} filterConnection filter predicate for replacement + * @param {Compiler} compiler the Compiler * @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 SortableSet(); + apply(compiler) { + compiler.hooks.compilation.tap("RuntimePlugin", compilation => { + compilation.dependencyTemplates.set( + RuntimeRequirementsDependency, + new RuntimeRequirementsDependency.Template() + ); + for (const req of GLOBALS_ON_REQUIRE) { + compilation.hooks.runtimeRequirementInModule + .for(req) + .tap("RuntimePlugin", (module, set) => { + set.add(RuntimeGlobals.requireScope); + }); + compilation.hooks.runtimeRequirementInTree + .for(req) + .tap("RuntimePlugin", (module, set) => { + set.add(RuntimeGlobals.requireScope); + }); } - 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); + for (const req of Object.keys(TREE_DEPENDENCIES)) { + const deps = TREE_DEPENDENCIES[req]; + compilation.hooks.runtimeRequirementInTree + .for(req) + .tap("RuntimePlugin", (chunk, set) => { + for (const dep of deps) set.add(dep); + }); + } + for (const req of Object.keys(MODULE_DEPENDENCIES)) { + const deps = MODULE_DEPENDENCIES[req]; + compilation.hooks.runtimeRequirementInModule + .for(req) + .tap("RuntimePlugin", (chunk, set) => { + for (const dep of deps) set.add(dep); + }); + } + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.definePropertyGetters) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule( + chunk, + new DefinePropertyGettersRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.makeNamespaceObject) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule( + chunk, + new MakeNamespaceObjectRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.createFakeNamespaceObject) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule( + chunk, + new CreateFakeNamespaceObjectRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hasOwnProperty) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule( + chunk, + new HasOwnPropertyRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.compatGetDefaultExport) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule( + chunk, + new CompatGetDefaultExportRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.runtimeId) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule(chunk, new RuntimeIdRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.publicPath) + .tap("RuntimePlugin", (chunk, set) => { + const { outputOptions } = compilation; + const { publicPath: globalPublicPath, scriptType } = outputOptions; + const entryOptions = chunk.getEntryOptions(); + const publicPath = + entryOptions && entryOptions.publicPath !== undefined + ? entryOptions.publicPath + : globalPublicPath; + + if (publicPath === "auto") { + const module = new AutoPublicPathRuntimeModule(); + if (scriptType !== "module") set.add(RuntimeGlobals.global); + compilation.addRuntimeModule(chunk, module); + } else { + const module = new PublicPathRuntimeModule(publicPath); + + if ( + typeof publicPath !== "string" || + /\[(full)?hash\]/.test(publicPath) + ) { + module.fullHash = true; + } + + compilation.addRuntimeModule(chunk, module); + } + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.global) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule(chunk, new GlobalRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.asyncModule) + .tap("RuntimePlugin", chunk => { + compilation.addRuntimeModule(chunk, new AsyncModuleRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.systemContext) + .tap("RuntimePlugin", chunk => { + const { outputOptions } = compilation; + const { library: globalLibrary } = outputOptions; + const entryOptions = chunk.getEntryOptions(); + const libraryType = + entryOptions && entryOptions.library !== undefined + ? entryOptions.library.type + : globalLibrary.type; + + if (libraryType === "system") { + compilation.addRuntimeModule( + chunk, + new SystemContextRuntimeModule() + ); + } + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getChunkScriptFilename) + .tap("RuntimePlugin", (chunk, set) => { + if ( + typeof compilation.outputOptions.chunkFilename === "string" && + /\[(full)?hash(:\d+)?\]/.test( + compilation.outputOptions.chunkFilename + ) + ) { + set.add(RuntimeGlobals.getFullHash); + } + compilation.addRuntimeModule( + chunk, + new GetChunkFilenameRuntimeModule( + "javascript", + "javascript", + RuntimeGlobals.getChunkScriptFilename, + chunk => + chunk.filenameTemplate || + (chunk.canBeInitial() + ? compilation.outputOptions.filename + : compilation.outputOptions.chunkFilename), + false + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getChunkCssFilename) + .tap("RuntimePlugin", (chunk, set) => { + if ( + typeof compilation.outputOptions.cssChunkFilename === "string" && + /\[(full)?hash(:\d+)?\]/.test( + compilation.outputOptions.cssChunkFilename + ) + ) { + set.add(RuntimeGlobals.getFullHash); + } + compilation.addRuntimeModule( + chunk, + new GetChunkFilenameRuntimeModule( + "css", + "css", + RuntimeGlobals.getChunkCssFilename, + chunk => + getChunkFilenameTemplate(chunk, compilation.outputOptions), + set.has(RuntimeGlobals.hmrDownloadUpdateHandlers) + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getChunkUpdateScriptFilename) + .tap("RuntimePlugin", (chunk, set) => { + if ( + /\[(full)?hash(:\d+)?\]/.test( + compilation.outputOptions.hotUpdateChunkFilename + ) + ) + set.add(RuntimeGlobals.getFullHash); + compilation.addRuntimeModule( + chunk, + new GetChunkFilenameRuntimeModule( + "javascript", + "javascript update", + RuntimeGlobals.getChunkUpdateScriptFilename, + c => compilation.outputOptions.hotUpdateChunkFilename, + true + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getUpdateManifestFilename) + .tap("RuntimePlugin", (chunk, set) => { + if ( + /\[(full)?hash(:\d+)?\]/.test( + compilation.outputOptions.hotUpdateMainFilename + ) + ) { + set.add(RuntimeGlobals.getFullHash); + } + compilation.addRuntimeModule( + chunk, + new GetMainFilenameRuntimeModule( + "update manifest", + RuntimeGlobals.getUpdateManifestFilename, + compilation.outputOptions.hotUpdateMainFilename + ) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunk) + .tap("RuntimePlugin", (chunk, set) => { + const hasAsyncChunks = chunk.hasAsyncChunks(); + if (hasAsyncChunks) { + set.add(RuntimeGlobals.ensureChunkHandlers); + } + compilation.addRuntimeModule( + chunk, + new EnsureChunkRuntimeModule(set) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkIncludeEntries) + .tap("RuntimePlugin", (chunk, set) => { + set.add(RuntimeGlobals.ensureChunkHandlers); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.shareScopeMap) + .tap("RuntimePlugin", (chunk, set) => { + compilation.addRuntimeModule(chunk, new ShareRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.loadScript) + .tap("RuntimePlugin", (chunk, set) => { + const withCreateScriptUrl = !!compilation.outputOptions.trustedTypes; + if (withCreateScriptUrl) { + set.add(RuntimeGlobals.createScriptUrl); + } + compilation.addRuntimeModule( + chunk, + new LoadScriptRuntimeModule(withCreateScriptUrl) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.createScript) + .tap("RuntimePlugin", (chunk, set) => { + if (compilation.outputOptions.trustedTypes) { + set.add(RuntimeGlobals.getTrustedTypesPolicy); + } + compilation.addRuntimeModule(chunk, new CreateScriptRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.createScriptUrl) + .tap("RuntimePlugin", (chunk, set) => { + if (compilation.outputOptions.trustedTypes) { + set.add(RuntimeGlobals.getTrustedTypesPolicy); + } + compilation.addRuntimeModule( + chunk, + new CreateScriptUrlRuntimeModule() + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.getTrustedTypesPolicy) + .tap("RuntimePlugin", (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new GetTrustedTypesPolicyRuntimeModule(set) + ); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.relativeUrl) + .tap("RuntimePlugin", (chunk, set) => { + compilation.addRuntimeModule(chunk, new RelativeUrlRuntimeModule()); + return true; + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap("RuntimePlugin", (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new OnChunksLoadedRuntimeModule() + ); + return true; + }); + // TODO webpack 6: remove CompatRuntimeModule + compilation.hooks.additionalTreeRuntimeRequirements.tap( + "RuntimePlugin", + (chunk, set) => { + const { mainTemplate } = compilation; + if ( + mainTemplate.hooks.bootstrap.isUsed() || + mainTemplate.hooks.localVars.isUsed() || + mainTemplate.hooks.requireEnsure.isUsed() || + mainTemplate.hooks.requireExtensions.isUsed() + ) { + compilation.addRuntimeModule(chunk, new CompatRuntimeModule()); } } - } - } + ); + JavascriptModulesPlugin.getCompilationHooks(compilation).chunkHash.tap( + "RuntimePlugin", + (chunk, hash, { chunkGraph }) => { + const xor = new StringXor(); + for (const m of chunkGraph.getChunkRuntimeModulesIterable(chunk)) { + xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); + } + xor.updateHash(hash); + } + ); + }); } +} +module.exports = RuntimePlugin; + + +/***/ }), + +/***/ 18777: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const { equals } = __webpack_require__(84953); +const compileBooleanMatcher = __webpack_require__(29404); +const propertyAccess = __webpack_require__(54190); +const { forEachRuntime, subtractRuntime } = __webpack_require__(17156); + +/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @param {Module} module the module + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {string} error message + */ +const noModuleIdErrorMessage = (module, chunkGraph) => { + return `Module ${module.identifier()} has no id assigned. +This should not happen. +It's in these chunks: ${ + Array.from( + chunkGraph.getModuleChunksIterable(module), + c => c.name || c.id || c.debugId + ).join(", ") || "none" + } (If module is in no chunk this indicates a bug in some chunk/module optimization logic) +Module has these incoming connections: ${Array.from( + chunkGraph.moduleGraph.getIncomingConnections(module), + connection => + `\n - ${ + connection.originModule && connection.originModule.identifier() + } ${connection.dependency && connection.dependency.type} ${ + (connection.explanations && + Array.from(connection.explanations).join(", ")) || + "" + }` + ).join("")}`; +}; + +/** + * @param {string|undefined} definition global object definition + * @returns {string} save to use global object + */ +function getGlobalObject(definition) { + if (!definition) return definition; + const trimmed = definition.trim(); + + if ( + // identifier, we do not need real identifier regarding ECMAScript/Unicode + trimmed.match(/^[_\p{L}][_0-9\p{L}]*$/iu) || + // iife + // call expression + // expression in parentheses + trimmed.match(/^([_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu) + ) + return trimmed; + return `Object(${trimmed})`; +} + +class RuntimeTemplate { /** - * @param {Module} module the referenced module - * @param {string} explanation an explanation why it's referenced - * @returns {void} + * @param {Compilation} compilation the compilation + * @param {OutputOptions} outputOptions the compilation output options + * @param {RequestShortener} requestShortener the request shortener */ - addExtraReason(module, explanation) { - const connections = this._getModuleGraphModule(module).incomingConnections; - connections.add(new ModuleGraphConnection(null, null, module, explanation)); + constructor(compilation, outputOptions, requestShortener) { + this.compilation = compilation; + this.outputOptions = outputOptions || {}; + this.requestShortener = requestShortener; + this.globalObject = getGlobalObject(outputOptions.globalObject); } - /** - * @param {Dependency} dependency the dependency to look for a referenced module - * @returns {Module} the referenced module - */ - getResolvedModule(dependency) { - const connection = this.getConnection(dependency); - return connection !== undefined ? connection.resolvedModule : null; + isIIFE() { + return this.outputOptions.iife; } - /** - * @param {Dependency} dependency the dependency to look for a referenced module - * @returns {ModuleGraphConnection | undefined} the connection - */ - getConnection(dependency) { - const connection = this._dependencyMap.get(dependency); - if (connection === undefined) { - const module = this.getParentModule(dependency); - if (module !== undefined) { - const mgm = this._getModuleGraphModule(module); - if ( - mgm._unassignedConnections && - mgm._unassignedConnections.length !== 0 - ) { - let foundConnection; - for (const connection of mgm._unassignedConnections) { - this._dependencyMap.set(connection.dependency, connection); - if (connection.dependency === dependency) - foundConnection = connection; - } - mgm._unassignedConnections.length = 0; - if (foundConnection !== undefined) { - return foundConnection; - } - } - } - this._dependencyMap.set(dependency, null); - return undefined; - } - return connection === null ? undefined : connection; + isModule() { + return this.outputOptions.module; } - /** - * @param {Dependency} dependency the dependency to look for a referenced module - * @returns {Module} the referenced module - */ - getModule(dependency) { - const connection = this.getConnection(dependency); - return connection !== undefined ? connection.module : null; + supportsConst() { + return this.outputOptions.environment.const; } - /** - * @param {Dependency} dependency the dependency to look for a referencing module - * @returns {Module} the referencing module - */ - getOrigin(dependency) { - const connection = this.getConnection(dependency); - return connection !== undefined ? connection.originModule : null; + supportsArrowFunction() { + return this.outputOptions.environment.arrowFunction; } - /** - * @param {Dependency} dependency the dependency to look for a referencing module - * @returns {Module} the original referencing module - */ - getResolvedOrigin(dependency) { - const connection = this.getConnection(dependency); - return connection !== undefined ? connection.resolvedOriginModule : null; + supportsOptionalChaining() { + return this.outputOptions.environment.optionalChaining; } - /** - * @param {Module} module the module - * @returns {Iterable} reasons why a module is included - */ - getIncomingConnections(module) { - const connections = this._getModuleGraphModule(module).incomingConnections; - return connections; + supportsForOf() { + return this.outputOptions.environment.forOf; } - /** - * @param {Module} module the module - * @returns {Iterable} list of outgoing connections - */ - getOutgoingConnections(module) { - const connections = this._getModuleGraphModule(module).outgoingConnections; - return connections === undefined ? EMPTY_SET : connections; + supportsDestructuring() { + return this.outputOptions.environment.destructuring; } - /** - * @param {Module} module the module - * @returns {readonly Map} reasons why a module is included, in a map by source module - */ - getIncomingConnectionsByOriginModule(module) { - const connections = this._getModuleGraphModule(module).incomingConnections; - return connections.getFromUnorderedCache(getConnectionsByOriginModule); + supportsBigIntLiteral() { + return this.outputOptions.environment.bigIntLiteral; } - /** - * @param {Module} module the module - * @returns {readonly Map | undefined} connections to modules, in a map by module - */ - getOutgoingConnectionsByModule(module) { - const connections = this._getModuleGraphModule(module).outgoingConnections; - return connections === undefined - ? undefined - : connections.getFromUnorderedCache(getConnectionsByModule); + supportsDynamicImport() { + return this.outputOptions.environment.dynamicImport; } - /** - * @param {Module} module the module - * @returns {ModuleProfile | null} the module profile - */ - getProfile(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.profile; + supportsEcmaScriptModuleSyntax() { + return this.outputOptions.environment.module; } - /** - * @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; + supportTemplateLiteral() { + return this.outputOptions.environment.templateLiteral; } - /** - * @param {Module} module the module - * @returns {Module | null} the issuer module - */ - getIssuer(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.issuer; + returningFunction(returnValue, args = "") { + return this.supportsArrowFunction() + ? `(${args}) => (${returnValue})` + : `function(${args}) { return ${returnValue}; }`; } - /** - * @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; + basicFunction(args, body) { + return this.supportsArrowFunction() + ? `(${args}) => {\n${Template.indent(body)}\n}` + : `function(${args}) {\n${Template.indent(body)}\n}`; } /** - * @param {Module} module the module - * @param {Module | null} issuer the issuer module - * @returns {void} + * @param {Array} args args + * @returns {string} result expression */ - setIssuerIfUnset(module, issuer) { - const mgm = this._getModuleGraphModule(module); - if (mgm.issuer === undefined) mgm.issuer = issuer; + concatenation(...args) { + const len = args.length; + + if (len === 2) return this._es5Concatenation(args); + if (len === 0) return '""'; + if (len === 1) { + return typeof args[0] === "string" + ? JSON.stringify(args[0]) + : `"" + ${args[0].expr}`; + } + if (!this.supportTemplateLiteral()) return this._es5Concatenation(args); + + // cost comparison between template literal and concatenation: + // both need equal surroundings: `xxx` vs "xxx" + // template literal has constant cost of 3 chars for each expression + // es5 concatenation has cost of 3 + n chars for n expressions in row + // when a es5 concatenation ends with an expression it reduces cost by 3 + // when a es5 concatenation starts with an single expression it reduces cost by 3 + // e. g. `${a}${b}${c}` (3*3 = 9) is longer than ""+a+b+c ((3+3)-3 = 3) + // e. g. `x${a}x${b}x${c}x` (3*3 = 9) is shorter than "x"+a+"x"+b+"x"+c+"x" (4+4+4 = 12) + + let templateCost = 0; + let concatenationCost = 0; + + let lastWasExpr = false; + for (const arg of args) { + const isExpr = typeof arg !== "string"; + if (isExpr) { + templateCost += 3; + concatenationCost += lastWasExpr ? 1 : 4; + } + lastWasExpr = isExpr; + } + if (lastWasExpr) concatenationCost -= 3; + if (typeof args[0] !== "string" && typeof args[1] === "string") + concatenationCost -= 3; + + if (concatenationCost <= templateCost) return this._es5Concatenation(args); + + return `\`${args + .map(arg => (typeof arg === "string" ? arg : `\${${arg.expr}}`)) + .join("")}\``; } /** - * @param {Module} module the module - * @returns {(string | OptimizationBailoutFunction)[]} optimization bailouts + * @param {Array} args args (len >= 2) + * @returns {string} result expression + * @private */ - getOptimizationBailout(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.optimizationBailout; + _es5Concatenation(args) { + const str = args + .map(arg => (typeof arg === "string" ? JSON.stringify(arg) : arg.expr)) + .join(" + "); + + // when the first two args are expression, we need to prepend "" + to force string + // concatenation instead of number addition. + return typeof args[0] !== "string" && typeof args[1] !== "string" + ? `"" + ${str}` + : str; } - /** - * @param {Module} module the module - * @returns {true | string[] | null} the provided exports - */ - getProvidedExports(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.exports.getProvidedExports(); + expressionFunction(expression, args = "") { + return this.supportsArrowFunction() + ? `(${args}) => (${expression})` + : `function(${args}) { ${expression}; }`; } - /** - * @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; + emptyFunction() { + return this.supportsArrowFunction() ? "x => {}" : "function() {}"; } - /** - * @param {Module} module the module - * @returns {ExportsInfo} info about the exports - */ - getExportsInfo(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.exports; + destructureArray(items, value) { + return this.supportsDestructuring() + ? `var [${items.join(", ")}] = ${value};` + : Template.asString( + items.map((item, i) => `var ${item} = ${value}[${i}];`) + ); } - /** - * @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); + destructureObject(items, value) { + return this.supportsDestructuring() + ? `var {${items.join(", ")}} = ${value};` + : Template.asString( + items.map(item => `var ${item} = ${value}${propertyAccess([item])};`) + ); } - /** - * @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); + iife(args, body) { + return `(${this.basicFunction(args, body)})()`; } - /** - * @param {Module} module the module - * @param {RuntimeSpec} runtime the runtime - * @returns {false | true | SortableSet | null} the used exports - * false: module is not used at all. - * true: the module namespace/object export is used. - * SortableSet: these export names are used. - * empty SortableSet: 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); + forEach(variable, array, body) { + return this.supportsForOf() + ? `for(const ${variable} of ${array}) {\n${Template.indent(body)}\n}` + : `${array}.forEach(function(${variable}) {\n${Template.indent( + body + )}\n});`; } /** - * @param {Module} module the module - * @returns {number} the index of the module + * Add a comment + * @param {object} options Information content of the comment + * @param {string=} options.request request string used originally + * @param {string=} options.chunkName name of the chunk referenced + * @param {string=} options.chunkReason reason information of the chunk + * @param {string=} options.message additional message + * @param {string=} options.exportName name of the export + * @returns {string} comment */ - getPreOrderIndex(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.preOrderIndex; + comment({ request, chunkName, chunkReason, message, exportName }) { + let content; + if (this.outputOptions.pathinfo) { + content = [message, request, chunkName, chunkReason] + .filter(Boolean) + .map(item => this.requestShortener.shorten(item)) + .join(" | "); + } else { + content = [message, chunkName, chunkReason] + .filter(Boolean) + .map(item => this.requestShortener.shorten(item)) + .join(" | "); + } + if (!content) return ""; + if (this.outputOptions.pathinfo) { + return Template.toComment(content) + " "; + } else { + return Template.toNormalComment(content) + " "; + } } /** - * @param {Module} module the module - * @returns {number} the index of the module + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error block */ - getPostOrderIndex(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.postOrderIndex; + throwMissingModuleErrorBlock({ request }) { + const err = `Cannot find module '${request}'`; + return `var e = new Error(${JSON.stringify( + err + )}); e.code = 'MODULE_NOT_FOUND'; throw e;`; } /** - * @param {Module} module the module - * @param {number} index the index of the module - * @returns {void} + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error function */ - setPreOrderIndex(module, index) { - const mgm = this._getModuleGraphModule(module); - mgm.preOrderIndex = index; + throwMissingModuleErrorFunction({ request }) { + return `function webpackMissingModule() { ${this.throwMissingModuleErrorBlock( + { request } + )} }`; } /** - * @param {Module} module the module - * @param {number} index the index of the module - * @returns {boolean} true, if the index was set + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error IIFE */ - setPreOrderIndexIfUnset(module, index) { - const mgm = this._getModuleGraphModule(module); - if (mgm.preOrderIndex === null) { - mgm.preOrderIndex = index; - return true; - } - return false; + missingModule({ request }) { + return `Object(${this.throwMissingModuleErrorFunction({ request })}())`; } /** - * @param {Module} module the module - * @param {number} index the index of the module - * @returns {void} + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error statement */ - setPostOrderIndex(module, index) { - const mgm = this._getModuleGraphModule(module); - mgm.postOrderIndex = index; + missingModuleStatement({ request }) { + return `${this.missingModule({ request })};\n`; } /** - * @param {Module} module the module - * @param {number} index the index of the module - * @returns {boolean} true, if the index was set + * @param {object} options generation options + * @param {string=} options.request request string used originally + * @returns {string} generated error code */ - setPostOrderIndexIfUnset(module, index) { - const mgm = this._getModuleGraphModule(module); - if (mgm.postOrderIndex === null) { - mgm.postOrderIndex = index; - return true; - } - return false; + missingModulePromise({ request }) { + return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({ + request + })})`; } /** - * @param {Module} module the module - * @returns {number} the depth of the module + * @param {Object} options options object + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {Module} options.module the module + * @param {string} options.request the request that should be printed as comment + * @param {string=} options.idExpr expression to use as id expression + * @param {"expression" | "promise" | "statements"} options.type which kind of code should be returned + * @returns {string} the code */ - getDepth(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.depth; + weakError({ module, chunkGraph, request, idExpr, type }) { + const moduleId = chunkGraph.getModuleId(module); + const errorMessage = + moduleId === null + ? JSON.stringify("Module is not available (weak dependency)") + : idExpr + ? `"Module '" + ${idExpr} + "' is not available (weak dependency)"` + : JSON.stringify( + `Module '${moduleId}' is not available (weak dependency)` + ); + const comment = request ? Template.toNormalComment(request) + " " : ""; + const errorStatements = + `var e = new Error(${errorMessage}); ` + + comment + + "e.code = 'MODULE_NOT_FOUND'; throw e;"; + switch (type) { + case "statements": + return errorStatements; + case "promise": + return `Promise.resolve().then(${this.basicFunction( + "", + errorStatements + )})`; + case "expression": + return this.iife("", errorStatements); + } } /** - * @param {Module} module the module - * @param {number} depth the depth of the module - * @returns {void} + * @param {Object} options options object + * @param {Module} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @returns {string} the expression */ - setDepth(module, depth) { - const mgm = this._getModuleGraphModule(module); - mgm.depth = depth; + moduleId({ module, chunkGraph, request, weak }) { + if (!module) { + return this.missingModule({ + request + }); + } + const moduleId = chunkGraph.getModuleId(module); + if (moduleId === null) { + if (weak) { + return "null /* weak dependency, without id */"; + } + throw new Error( + `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` + ); + } + return `${this.comment({ request })}${JSON.stringify(moduleId)}`; } /** - * @param {Module} module the module - * @param {number} depth the depth of the module - * @returns {boolean} true, if the depth was set + * @param {Object} options options object + * @param {Module} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} the expression */ - setDepthIfLower(module, depth) { - const mgm = this._getModuleGraphModule(module); - if (mgm.depth === null || mgm.depth > depth) { - mgm.depth = depth; - return true; + moduleRaw({ module, chunkGraph, request, weak, runtimeRequirements }) { + if (!module) { + return this.missingModule({ + request + }); } - return false; + const moduleId = chunkGraph.getModuleId(module); + if (moduleId === null) { + if (weak) { + // only weak referenced modules don't get an id + // we can always emit an error emitting code here + return this.weakError({ + module, + chunkGraph, + request, + type: "expression" + }); + } + throw new Error( + `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` + ); + } + runtimeRequirements.add(RuntimeGlobals.require); + return `__webpack_require__(${this.moduleId({ + module, + chunkGraph, + request, + weak + })})`; } /** - * @param {Module} module the module - * @returns {boolean} true, if the module is async + * @param {Object} options options object + * @param {Module} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} the expression */ - isAsync(module) { - const mgm = this._getModuleGraphModule(module); - return mgm.async; + moduleExports({ module, chunkGraph, request, weak, runtimeRequirements }) { + return this.moduleRaw({ + module, + chunkGraph, + request, + weak, + runtimeRequirements + }); } /** - * @param {Module} module the module - * @returns {void} + * @param {Object} options options object + * @param {Module} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {boolean=} options.strict if the current module is in strict esm mode + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} the expression */ - setAsync(module) { - const mgm = this._getModuleGraphModule(module); - mgm.async = true; + moduleNamespace({ + module, + chunkGraph, + request, + strict, + weak, + runtimeRequirements + }) { + if (!module) { + return this.missingModule({ + request + }); + } + if (chunkGraph.getModuleId(module) === null) { + if (weak) { + // only weak referenced modules don't get an id + // we can always emit an error emitting code here + return this.weakError({ + module, + chunkGraph, + request, + type: "expression" + }); + } + throw new Error( + `RuntimeTemplate.moduleNamespace(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` + ); + } + const moduleId = this.moduleId({ + module, + chunkGraph, + request, + weak + }); + const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict); + switch (exportsType) { + case "namespace": + return this.moduleRaw({ + module, + chunkGraph, + request, + weak, + runtimeRequirements + }); + case "default-with-named": + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 3)`; + case "default-only": + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 1)`; + case "dynamic": + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 7)`; + } } /** - * @param {any} thing any thing - * @returns {Object} metadata + * @param {Object} options options object + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {AsyncDependenciesBlock=} options.block the current dependencies block + * @param {Module} options.module the module + * @param {string} options.request the request that should be printed as comment + * @param {string} options.message a message for the comment + * @param {boolean=} options.strict if the current module is in strict esm mode + * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} the promise expression */ - getMeta(thing) { - let meta = this._metaMap.get(thing); - if (meta === undefined) { - meta = Object.create(null); - this._metaMap.set(thing, meta); + moduleNamespacePromise({ + chunkGraph, + block, + module, + request, + message, + strict, + weak, + runtimeRequirements + }) { + if (!module) { + return this.missingModulePromise({ + request + }); } - return meta; + const moduleId = chunkGraph.getModuleId(module); + if (moduleId === null) { + if (weak) { + // only weak referenced modules don't get an id + // we can always emit an error emitting code here + return this.weakError({ + module, + chunkGraph, + request, + type: "promise" + }); + } + throw new Error( + `RuntimeTemplate.moduleNamespacePromise(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` + ); + } + const promise = this.blockPromise({ + chunkGraph, + block, + message, + runtimeRequirements + }); + + let appending; + let idExpr = JSON.stringify(chunkGraph.getModuleId(module)); + const comment = this.comment({ + request + }); + let header = ""; + if (weak) { + if (idExpr.length > 8) { + // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"' + header += `var id = ${idExpr}; `; + idExpr = "id"; + } + runtimeRequirements.add(RuntimeGlobals.moduleFactories); + header += `if(!${ + RuntimeGlobals.moduleFactories + }[${idExpr}]) { ${this.weakError({ + module, + chunkGraph, + request, + idExpr, + type: "statements" + })} } `; + } + const moduleIdExpr = this.moduleId({ + module, + chunkGraph, + request, + weak + }); + const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict); + let fakeType = 16; + switch (exportsType) { + case "namespace": + if (header) { + const rawModule = this.moduleRaw({ + module, + chunkGraph, + request, + weak, + runtimeRequirements + }); + appending = `.then(${this.basicFunction( + "", + `${header}return ${rawModule};` + )})`; + } else { + runtimeRequirements.add(RuntimeGlobals.require); + appending = `.then(__webpack_require__.bind(__webpack_require__, ${comment}${idExpr}))`; + } + break; + case "dynamic": + fakeType |= 4; + /* fall through */ + case "default-with-named": + fakeType |= 2; + /* fall through */ + case "default-only": + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + if (chunkGraph.moduleGraph.isAsync(module)) { + if (header) { + const rawModule = this.moduleRaw({ + module, + chunkGraph, + request, + weak, + runtimeRequirements + }); + appending = `.then(${this.basicFunction( + "", + `${header}return ${rawModule};` + )})`; + } else { + runtimeRequirements.add(RuntimeGlobals.require); + appending = `.then(__webpack_require__.bind(__webpack_require__, ${comment}${idExpr}))`; + } + appending += `.then(${this.returningFunction( + `${RuntimeGlobals.createFakeNamespaceObject}(m, ${fakeType})`, + "m" + )})`; + } else { + fakeType |= 1; + if (header) { + const returnExpression = `${RuntimeGlobals.createFakeNamespaceObject}(${moduleIdExpr}, ${fakeType})`; + appending = `.then(${this.basicFunction( + "", + `${header}return ${returnExpression};` + )})`; + } else { + appending = `.then(${RuntimeGlobals.createFakeNamespaceObject}.bind(__webpack_require__, ${comment}${idExpr}, ${fakeType}))`; + } + } + break; + } + + return `${promise || "Promise.resolve()"}${appending}`; } /** - * @param {any} thing any thing - * @returns {Object} metadata + * @param {Object} options options object + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {RuntimeSpec=} options.runtime runtime for which this code will be generated + * @param {RuntimeSpec | boolean=} options.runtimeCondition only execute the statement in some runtimes + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} expression */ - getMetaIfExisting(thing) { - return this._metaMap.get(thing); + runtimeConditionExpression({ + chunkGraph, + runtimeCondition, + runtime, + runtimeRequirements + }) { + if (runtimeCondition === undefined) return "true"; + if (typeof runtimeCondition === "boolean") return `${runtimeCondition}`; + /** @type {Set} */ + const positiveRuntimeIds = new Set(); + forEachRuntime(runtimeCondition, runtime => + positiveRuntimeIds.add(`${chunkGraph.getRuntimeId(runtime)}`) + ); + /** @type {Set} */ + const negativeRuntimeIds = new Set(); + forEachRuntime(subtractRuntime(runtime, runtimeCondition), runtime => + negativeRuntimeIds.add(`${chunkGraph.getRuntimeId(runtime)}`) + ); + runtimeRequirements.add(RuntimeGlobals.runtimeId); + return compileBooleanMatcher.fromLists( + Array.from(positiveRuntimeIds), + Array.from(negativeRuntimeIds) + )(RuntimeGlobals.runtimeId); } /** - * @param {string=} cacheStage a persistent stage name for caching + * + * @param {Object} options options object + * @param {boolean=} options.update whether a new variable should be created or the existing one updated + * @param {Module} options.module the module + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {string} options.request the request that should be printed as comment + * @param {string} options.importVar name of the import variable + * @param {Module} options.originModule module in which the statement is emitted + * @param {boolean=} options.weak true, if this is a weak dependency + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {[string, string]} the import statement and the compat statement */ - freeze(cacheStage) { - this._cache = new WeakTupleMap(); - this._cacheStage = cacheStage; - } + importStatement({ + update, + module, + chunkGraph, + request, + importVar, + originModule, + weak, + runtimeRequirements + }) { + if (!module) { + return [ + this.missingModuleStatement({ + request + }), + "" + ]; + } + if (chunkGraph.getModuleId(module) === null) { + if (weak) { + // only weak referenced modules don't get an id + // we can always emit an error emitting code here + return [ + this.weakError({ + module, + chunkGraph, + request, + type: "statements" + }), + "" + ]; + } + throw new Error( + `RuntimeTemplate.importStatement(): ${noModuleIdErrorMessage( + module, + chunkGraph + )}` + ); + } + const moduleId = this.moduleId({ + module, + chunkGraph, + request, + weak + }); + const optDeclaration = update ? "" : "var "; - unfreeze() { - this._cache = undefined; - this._cacheStage = undefined; + const exportsType = module.getExportsType( + chunkGraph.moduleGraph, + originModule.buildMeta.strictHarmonyModule + ); + runtimeRequirements.add(RuntimeGlobals.require); + const importContent = `/* harmony import */ ${optDeclaration}${importVar} = __webpack_require__(${moduleId});\n`; + + if (exportsType === "dynamic") { + runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport); + return [ + importContent, + `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${importVar});\n` + ]; + } + return [importContent, ""]; } /** - * @template {any[]} T - * @template V - * @param {(moduleGraph: ModuleGraph, ...args: T) => V} fn computer - * @param {T} args arguments - * @returns {V} computed value or cached + * @param {Object} options options + * @param {ModuleGraph} options.moduleGraph the module graph + * @param {Module} options.module the module + * @param {string} options.request the request + * @param {string | string[]} options.exportName the export name + * @param {Module} options.originModule the origin module + * @param {boolean|undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted + * @param {boolean} options.isCall true, if expression will be called + * @param {boolean} options.callContext when false, call context will not be preserved + * @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated + * @param {string} options.importVar the identifier name of the import variable + * @param {InitFragment[]} options.initFragments init fragments will be added here + * @param {RuntimeSpec} options.runtime runtime for which this code will be generated + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} expression */ - cached(fn, ...args) { - if (this._cache === undefined) return fn(this, ...args); - return this._cache.provide(fn, ...args, () => fn(this, ...args)); + exportFromImport({ + moduleGraph, + module, + request, + exportName, + originModule, + asiSafe, + isCall, + callContext, + defaultInterop, + importVar, + initFragments, + runtime, + runtimeRequirements + }) { + if (!module) { + return this.missingModule({ + request + }); + } + if (!Array.isArray(exportName)) { + exportName = exportName ? [exportName] : []; + } + const exportsType = module.getExportsType( + moduleGraph, + originModule.buildMeta.strictHarmonyModule + ); + + if (defaultInterop) { + if (exportName.length > 0 && exportName[0] === "default") { + switch (exportsType) { + case "dynamic": + if (isCall) { + return `${importVar}_default()${propertyAccess(exportName, 1)}`; + } else { + return asiSafe + ? `(${importVar}_default()${propertyAccess(exportName, 1)})` + : asiSafe === false + ? `;(${importVar}_default()${propertyAccess(exportName, 1)})` + : `${importVar}_default.a${propertyAccess(exportName, 1)}`; + } + case "default-only": + case "default-with-named": + exportName = exportName.slice(1); + break; + } + } else if (exportName.length > 0) { + if (exportsType === "default-only") { + return ( + "/* non-default import from non-esm module */undefined" + + propertyAccess(exportName, 1) + ); + } else if ( + exportsType !== "namespace" && + exportName[0] === "__esModule" + ) { + return "/* __esModule */true"; + } + } else if ( + exportsType === "default-only" || + exportsType === "default-with-named" + ) { + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + initFragments.push( + new InitFragment( + `var ${importVar}_namespace_cache;\n`, + InitFragment.STAGE_CONSTANTS, + -1, + `${importVar}_namespace_cache` + ) + ); + return `/*#__PURE__*/ ${ + asiSafe ? "" : asiSafe === false ? ";" : "Object" + }(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${ + RuntimeGlobals.createFakeNamespaceObject + }(${importVar}${exportsType === "default-only" ? "" : ", 2"})))`; + } + } + + if (exportName.length > 0) { + const exportsInfo = moduleGraph.getExportsInfo(module); + const used = exportsInfo.getUsedName(exportName, runtime); + if (!used) { + const comment = Template.toNormalComment( + `unused export ${propertyAccess(exportName)}` + ); + return `${comment} undefined`; + } + const comment = equals(used, exportName) + ? "" + : Template.toNormalComment(propertyAccess(exportName)) + " "; + const access = `${importVar}${comment}${propertyAccess(used)}`; + if (isCall && callContext === false) { + return asiSafe + ? `(0,${access})` + : asiSafe === false + ? `;(0,${access})` + : `/*#__PURE__*/Object(${access})`; + } + return access; + } else { + return importVar; + } } /** - * @param {Map>} moduleMemCaches mem caches for modules for better caching + * @param {Object} options options + * @param {AsyncDependenciesBlock} options.block the async block + * @param {string} options.message the message + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} expression */ - setModuleMemCaches(moduleMemCaches) { - this._moduleMemCaches = moduleMemCaches; + blockPromise({ block, message, chunkGraph, runtimeRequirements }) { + if (!block) { + const comment = this.comment({ + message + }); + return `Promise.resolve(${comment.trim()})`; + } + const chunkGroup = chunkGraph.getBlockChunkGroup(block); + if (!chunkGroup || chunkGroup.chunks.length === 0) { + const comment = this.comment({ + message + }); + return `Promise.resolve(${comment.trim()})`; + } + const chunks = chunkGroup.chunks.filter( + chunk => !chunk.hasRuntime() && chunk.id !== null + ); + const comment = this.comment({ + message, + chunkName: block.chunkName + }); + if (chunks.length === 1) { + const chunkId = JSON.stringify(chunks[0].id); + runtimeRequirements.add(RuntimeGlobals.ensureChunk); + return `${RuntimeGlobals.ensureChunk}(${comment}${chunkId})`; + } else if (chunks.length > 0) { + runtimeRequirements.add(RuntimeGlobals.ensureChunk); + const requireChunkId = chunk => + `${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)})`; + return `Promise.all(${comment.trim()}[${chunks + .map(requireChunkId) + .join(", ")}])`; + } else { + return `Promise.resolve(${comment.trim()})`; + } } /** - * @param {Dependency} dependency dependency - * @param {...any} args arguments, last argument is a function called with moduleGraph, dependency, ...args - * @returns {any} computed value or cached + * @param {Object} options options + * @param {AsyncDependenciesBlock} options.block the async block + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @param {string=} options.request request string used originally + * @returns {string} expression */ - dependencyCacheProvide(dependency, ...args) { - /** @type {(moduleGraph: ModuleGraph, dependency: Dependency, ...args: any[]) => any} */ - const fn = args.pop(); - if (this._moduleMemCaches && this._cacheStage) { - const memCache = this._moduleMemCaches.get( - this.getParentModule(dependency) - ); - if (memCache !== undefined) { - return memCache.provide(dependency, this._cacheStage, ...args, () => - fn(this, dependency, ...args) - ); - } - } - if (this._cache === undefined) return fn(this, dependency, ...args); - return this._cache.provide(dependency, ...args, () => - fn(this, dependency, ...args) + asyncModuleFactory({ block, chunkGraph, runtimeRequirements, request }) { + const dep = block.dependencies[0]; + const module = chunkGraph.moduleGraph.getModule(dep); + const ensureChunk = this.blockPromise({ + block, + message: "", + chunkGraph, + runtimeRequirements + }); + const factory = this.returningFunction( + this.moduleRaw({ + module, + chunkGraph, + request, + runtimeRequirements + }) + ); + return this.returningFunction( + ensureChunk.startsWith("Promise.resolve(") + ? `${factory}` + : `${ensureChunk}.then(${this.returningFunction(factory)})` ); } - // 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 + * @param {Object} options options + * @param {Dependency} options.dependency the dependency + * @param {ChunkGraph} options.chunkGraph the chunk graph + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @param {string=} options.request request string used originally + * @returns {string} expression */ - 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 + syncModuleFactory({ dependency, chunkGraph, runtimeRequirements, request }) { + const module = chunkGraph.moduleGraph.getModule(dependency); + const factory = this.returningFunction( + this.moduleRaw({ + module, + chunkGraph, + request, + runtimeRequirements + }) ); - deprecateMap.set(deprecateMessage, newFn); - return newFn(module); + return this.returningFunction(factory); } - // TODO remove in webpack 6 /** - * @param {Module} module the module - * @param {ModuleGraph} moduleGraph the module graph - * @returns {void} + * @param {Object} options options + * @param {string} options.exportsArgument the name of the exports object + * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements + * @returns {string} statement */ - static setModuleGraphForModule(module, moduleGraph) { - moduleGraphForModuleMap.set(module, moduleGraph); + defineEsModuleFlagStatement({ exportsArgument, runtimeRequirements }) { + runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); + runtimeRequirements.add(RuntimeGlobals.exports); + return `${RuntimeGlobals.makeNamespaceObject}(${exportsArgument});\n`; } - // TODO remove in webpack 6 /** - * @param {Module} module the module - * @returns {void} + * @param {Object} options options object + * @param {Module} options.module the module + * @param {string} options.publicPath the public path + * @param {RuntimeSpec=} options.runtime runtime + * @param {CodeGenerationResults} options.codeGenerationResults the code generation results + * @returns {string} the url of the asset */ - static clearModuleGraphForModule(module) { - moduleGraphForModuleMap.delete(module); + assetUrl({ publicPath, runtime, module, codeGenerationResults }) { + if (!module) { + return "data:,"; + } + const codeGen = codeGenerationResults.get(module, runtime); + const { data } = codeGen; + const url = data.get("url"); + if (url) return url.toString(); + const filename = data.get("filename"); + return publicPath + filename; } } -// TODO remove in webpack 6 -/** @type {WeakMap} */ -const moduleGraphForModuleMap = new WeakMap(); - -// TODO remove in webpack 6 -/** @type {Map ModuleGraph>} */ -const deprecateMap = new Map(); - -module.exports = ModuleGraph; -module.exports.ModuleGraphConnection = ModuleGraphConnection; +module.exports = RuntimeTemplate; /***/ }), -/***/ 40639: +/***/ 63560: /***/ (function(module) { "use strict"; @@ -53379,195 +54401,76 @@ module.exports.ModuleGraphConnection = ModuleGraphConnection; -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +class SelfModuleFactory { + constructor(moduleGraph) { + this.moduleGraph = moduleGraph; + } -/** - * Module itself is not connected, but transitive modules are connected transitively. - */ -const TRANSITIVE_ONLY = Symbol("transitive only"); + create(data, callback) { + const module = this.moduleGraph.getParentModule(data.dependencies[0]); + callback(null, { + module + }); + } +} -/** - * While determining the active state, this flag is used to signal a circular connection. - */ -const CIRCULAR_CONNECTION = Symbol("circular connection"); +module.exports = SelfModuleFactory; -/** @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; -}; +/***/ 48076: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -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} */ - this.explanations = undefined; - if (explanation) { - this.explanations = new Set(); - this.explanations.add(explanation); - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ - 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); - } +module.exports = __webpack_require__(96953); - 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; - } +/***/ 71070: +/***/ (function(__unused_webpack_module, exports) { - /** - * @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; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ - /** - * @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; + +/** + * @param {number} size the size in bytes + * @returns {string} the formatted size + */ +exports.formatSize = size => { + if (typeof size !== "number" || Number.isNaN(size) === true) { + return "unknown size"; } - set active(value) { - throw new Error("Use setActive instead"); + if (size <= 0) { + return "0 bytes"; } -} -/** @typedef {typeof TRANSITIVE_ONLY} TRANSITIVE_ONLY */ -/** @typedef {typeof CIRCULAR_CONNECTION} CIRCULAR_CONNECTION */ + const abbreviations = ["bytes", "KiB", "MiB", "GiB"]; + const index = Math.floor(Math.log(size) / Math.log(1024)); -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 -); + return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${ + abbreviations[index] + }`; +}; /***/ }), -/***/ 3454: +/***/ 97513: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -53578,259 +54481,61 @@ module.exports.CIRCULAR_CONNECTION = /** @type {typeof CIRCULAR_CONNECTION} */ ( -const { ConcatSource, RawSource, CachedSource } = __webpack_require__(51255); -const { UsageState } = __webpack_require__(63686); -const Template = __webpack_require__(39722); const JavascriptModulesPlugin = __webpack_require__(89464); -/** @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 */ +/** @typedef {import("./Compilation")} Compilation */ -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} 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" - ); - } +class SourceMapDevToolModuleOptionsPlugin { + constructor(options) { + this.options = options; } -}; -/** @type {WeakMap }>>} */ -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 + * @param {Compilation} compilation the compiler instance * @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; - } + apply(compilation) { + const options = this.options; + if (options.module !== false) { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.useSourceMap = true; } ); - hooks.chunkHash.tap("ModuleInfoHeaderPlugin", (chunk, hash) => { - hash.update("ModuleInfoHeaderPlugin"); - hash.update("1"); - }); - }); + compilation.hooks.runtimeModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.useSourceMap = true; + } + ); + } else { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.useSimpleSourceMap = true; + } + ); + compilation.hooks.runtimeModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.useSimpleSourceMap = true; + } + ); + } + JavascriptModulesPlugin.getCompilationHooks(compilation).useSourceMap.tap( + "SourceMapDevToolModuleOptionsPlugin", + () => true + ); } } -module.exports = ModuleInfoHeaderPlugin; + +module.exports = SourceMapDevToolModuleOptionsPlugin; /***/ }), -/***/ 32882: +/***/ 63872: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -53841,207 +54546,564 @@ module.exports = ModuleInfoHeaderPlugin; -const WebpackError = __webpack_require__(53799); +const asyncLib = __webpack_require__(78175); +const { ConcatSource, RawSource } = __webpack_require__(51255); +const Compilation = __webpack_require__(85720); +const ModuleFilenameHelpers = __webpack_require__(88821); +const ProgressPlugin = __webpack_require__(13216); +const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(97513); +const createSchemaValidation = __webpack_require__(32540); +const createHash = __webpack_require__(49835); +const { relative, dirname } = __webpack_require__(17139); +const { makePathsAbsolute } = __webpack_require__(82186); -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("webpack-sources").MapOptions} MapOptions */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ +/** @typedef {import("./Cache").Etag} Etag */ +/** @typedef {import("./CacheFacade").ItemCacheFacade} ItemCacheFacade */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Module")} Module */ +/** @typedef {import("./NormalModule").SourceMap} SourceMap */ +/** @typedef {import("./util/Hash")} Hash */ -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" +const validate = createSchemaValidation( + __webpack_require__(2885), + () => __webpack_require__(30501), + { + name: "SourceMap DevTool Plugin", + baseDataPath: "options" + } +); +/** + * @typedef {object} SourceMapTask + * @property {Source} asset + * @property {AssetInfo} assetInfo + * @property {(string | Module)[]} modules + * @property {string} source + * @property {string} file + * @property {SourceMap} sourceMap + * @property {ItemCacheFacade} cacheItem cache item + */ + +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string + */ +const quoteMeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); }; -class ModuleNotFoundError extends WebpackError { +/** + * Creating {@link SourceMapTask} for given file + * @param {string} file current compiled file + * @param {Source} asset the asset + * @param {AssetInfo} assetInfo the asset info + * @param {MapOptions} options source map options + * @param {Compilation} compilation compilation instance + * @param {ItemCacheFacade} cacheItem cache item + * @returns {SourceMapTask | undefined} created task instance or `undefined` + */ +const getTaskForFile = ( + file, + asset, + assetInfo, + options, + compilation, + cacheItem +) => { + let source; + /** @type {SourceMap} */ + let sourceMap; /** - * @param {Module} module module tied to dependency - * @param {Error&any} err error thrown - * @param {DependencyLocation} loc location of dependency + * Check if asset can build source map */ - constructor(module, err, loc) { - let message = `Module not found: ${err.toString()}`; + if (asset.sourceAndMap) { + const sourceAndMap = asset.sourceAndMap(options); + sourceMap = /** @type {SourceMap} */ (sourceAndMap.map); + source = sourceAndMap.source; + } else { + sourceMap = /** @type {SourceMap} */ (asset.map(options)); + source = asset.source(); + } + if (!sourceMap || typeof source !== "string") return; + const context = compilation.options.context; + const root = compilation.compiler.root; + const cachedAbsolutify = makePathsAbsolute.bindContextCache(context, root); + const modules = sourceMap.sources.map(source => { + if (!source.startsWith("webpack://")) return source; + source = cachedAbsolutify(source.slice(10)); + const module = compilation.findModule(source); + return module || source; + }); - // 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 }`; - } - } + return { + file, + asset, + source, + assetInfo, + sourceMap, + modules, + cacheItem + }; +}; - super(message); +class SourceMapDevToolPlugin { + /** + * @param {SourceMapDevToolPluginOptions} [options] options object + * @throws {Error} throws error, if got more than 1 arguments + */ + constructor(options = {}) { + validate(options); - this.name = "ModuleNotFoundError"; - this.details = err.details; - this.module = module; - this.error = err; - this.loc = loc; + /** @type {string | false} */ + this.sourceMapFilename = options.filename; + /** @type {string | false} */ + this.sourceMappingURLComment = + options.append === false + ? false + : options.append || "\n//# source" + "MappingURL=[url]"; + /** @type {string | Function} */ + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]"; + /** @type {string | Function} */ + this.fallbackModuleFilenameTemplate = + options.fallbackModuleFilenameTemplate || + "webpack://[namespace]/[resourcePath]?[hash]"; + /** @type {string} */ + this.namespace = options.namespace || ""; + /** @type {SourceMapDevToolPluginOptions} */ + this.options = options; } -} -module.exports = ModuleNotFoundError; + /** + * Apply the plugin + * @param {Compiler} compiler compiler instance + * @returns {void} + */ + apply(compiler) { + const outputFs = compiler.outputFileSystem; + const sourceMapFilename = this.sourceMapFilename; + const sourceMappingURLComment = this.sourceMappingURLComment; + const moduleFilenameTemplate = this.moduleFilenameTemplate; + const namespace = this.namespace; + const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate; + const requestShortener = compiler.requestShortener; + const options = this.options; + options.test = options.test || /\.((c|m)?js|css)($|\?)/i; + const matchObject = ModuleFilenameHelpers.matchObject.bind( + undefined, + options + ); -/***/ }), + compiler.hooks.compilation.tap("SourceMapDevToolPlugin", compilation => { + new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); -/***/ 58443: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + compilation.hooks.processAssets.tapAsync( + { + name: "SourceMapDevToolPlugin", + stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING, + additionalAssets: true + }, + (assets, callback) => { + const chunkGraph = compilation.chunkGraph; + const cache = compilation.getCache("SourceMapDevToolPlugin"); + /** @type {Map} */ + const moduleToSourceNameMapping = new Map(); + /** + * @type {Function} + * @returns {void} + */ + const reportProgress = + ProgressPlugin.getReporter(compilation.compiler) || (() => {}); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** @type {Map} */ + const fileToChunk = new Map(); + for (const chunk of compilation.chunks) { + for (const file of chunk.files) { + fileToChunk.set(file, chunk); + } + for (const file of chunk.auxiliaryFiles) { + fileToChunk.set(file, chunk); + } + } + /** @type {string[]} */ + const files = []; + for (const file of Object.keys(assets)) { + if (matchObject(file)) { + files.push(file); + } + } + reportProgress(0.0); + /** @type {SourceMapTask[]} */ + const tasks = []; + let fileIndex = 0; -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); + asyncLib.each( + files, + (file, callback) => { + const asset = compilation.getAsset(file); + if (asset.info.related && asset.info.related.sourceMap) { + fileIndex++; + return callback(); + } + const cacheItem = cache.getItemCache( + file, + cache.mergeEtags( + cache.getLazyHashedEtag(asset.source), + namespace + ) + ); -const WASM_HEADER = Buffer.from([0x00, 0x61, 0x73, 0x6d]); + cacheItem.get((err, cacheEntry) => { + if (err) { + return callback(err); + } + /** + * If presented in cache, reassigns assets. Cache assets already have source maps. + */ + if (cacheEntry) { + const { assets, assetsInfo } = cacheEntry; + for (const cachedFile of Object.keys(assets)) { + if (cachedFile === file) { + compilation.updateAsset( + cachedFile, + assets[cachedFile], + assetsInfo[cachedFile] + ); + } else { + compilation.emitAsset( + cachedFile, + assets[cachedFile], + assetsInfo[cachedFile] + ); + } + /** + * Add file to chunk, if not presented there + */ + if (cachedFile !== file) { + const chunk = fileToChunk.get(file); + if (chunk !== undefined) + chunk.auxiliaryFiles.add(cachedFile); + } + } -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; + reportProgress( + (0.5 * ++fileIndex) / files.length, + file, + "restored cached SourceMap" + ); - 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"; - } + return callback(); + } - if ( - err && - err.loc && - typeof err.loc === "object" && - typeof err.loc.line === "number" - ) { - var lineNumber = err.loc.line; + reportProgress( + (0.5 * fileIndex) / files.length, + file, + "generate SourceMap" + ); - 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); + /** @type {SourceMapTask | undefined} */ + const task = getTaskForFile( + file, + asset.source, + asset.info, + { + module: options.module, + columns: options.columns + }, + compilation, + cacheItem + ); - message += - linesBefore.map(l => `\n| ${l}`).join("") + - `\n> ${theLine}` + - linesAfter.map(l => `\n| ${l}`).join(""); - } + if (task) { + const modules = task.modules; - loc = { start: err.loc }; - } else if (err && err.stack) { - message += "\n" + err.stack; - } + for (let idx = 0; idx < modules.length; idx++) { + const module = modules[idx]; + if (!moduleToSourceNameMapping.get(module)) { + moduleToSourceNameMapping.set( + module, + ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: moduleFilenameTemplate, + namespace: namespace + }, + { + requestShortener, + chunkGraph, + hashFunction: compilation.outputOptions.hashFunction + } + ) + ); + } + } - super(message); + tasks.push(task); + } - this.name = "ModuleParseError"; - this.loc = loc; - this.error = err; - } + reportProgress( + (0.5 * ++fileIndex) / files.length, + file, + "generated SourceMap" + ); - serialize(context) { - const { write } = context; + callback(); + }); + }, + err => { + if (err) { + return callback(err); + } - write(this.error); + reportProgress(0.5, "resolve sources"); + /** @type {Set} */ + const usedNamesSet = new Set(moduleToSourceNameMapping.values()); + /** @type {Set} */ + const conflictDetectionSet = new Set(); - super.serialize(context); - } + /** + * all modules in defined order (longest identifier first) + * @type {Array} + */ + const allModules = Array.from( + moduleToSourceNameMapping.keys() + ).sort((a, b) => { + const ai = typeof a === "string" ? a : a.identifier(); + const bi = typeof b === "string" ? b : b.identifier(); + return ai.length - bi.length; + }); - deserialize(context) { - const { read } = context; + // find modules with conflicting source names + for (let idx = 0; idx < allModules.length; idx++) { + const module = allModules[idx]; + let sourceName = moduleToSourceNameMapping.get(module); + let hasName = conflictDetectionSet.has(sourceName); + if (!hasName) { + conflictDetectionSet.add(sourceName); + continue; + } - this.error = read(); + // try the fallback name first + sourceName = ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: fallbackModuleFilenameTemplate, + namespace: namespace + }, + { + requestShortener, + chunkGraph, + hashFunction: compilation.outputOptions.hashFunction + } + ); + hasName = usedNamesSet.has(sourceName); + if (!hasName) { + moduleToSourceNameMapping.set(module, sourceName); + usedNamesSet.add(sourceName); + continue; + } - super.deserialize(context); + // otherwise just append stars until we have a valid name + while (hasName) { + sourceName += "*"; + hasName = usedNamesSet.has(sourceName); + } + moduleToSourceNameMapping.set(module, sourceName); + usedNamesSet.add(sourceName); + } + + let taskIndex = 0; + + asyncLib.each( + tasks, + (task, callback) => { + const assets = Object.create(null); + const assetsInfo = Object.create(null); + const file = task.file; + const chunk = fileToChunk.get(file); + const sourceMap = task.sourceMap; + const source = task.source; + const modules = task.modules; + + reportProgress( + 0.5 + (0.5 * taskIndex) / tasks.length, + file, + "attach SourceMap" + ); + + const moduleFilenames = modules.map(m => + moduleToSourceNameMapping.get(m) + ); + sourceMap.sources = moduleFilenames; + if (options.noSources) { + sourceMap.sourcesContent = undefined; + } + sourceMap.sourceRoot = options.sourceRoot || ""; + sourceMap.file = file; + const usesContentHash = + sourceMapFilename && + /\[contenthash(:\w+)?\]/.test(sourceMapFilename); + + // If SourceMap and asset uses contenthash, avoid a circular dependency by hiding hash in `file` + if (usesContentHash && task.assetInfo.contenthash) { + const contenthash = task.assetInfo.contenthash; + let pattern; + if (Array.isArray(contenthash)) { + pattern = contenthash.map(quoteMeta).join("|"); + } else { + pattern = quoteMeta(contenthash); + } + sourceMap.file = sourceMap.file.replace( + new RegExp(pattern, "g"), + m => "x".repeat(m.length) + ); + } + + /** @type {string | false} */ + let currentSourceMappingURLComment = sourceMappingURLComment; + if ( + currentSourceMappingURLComment !== false && + /\.css($|\?)/i.test(file) + ) { + currentSourceMappingURLComment = + currentSourceMappingURLComment.replace( + /^\n\/\/(.*)$/, + "\n/*$1*/" + ); + } + const sourceMapString = JSON.stringify(sourceMap); + if (sourceMapFilename) { + let filename = file; + const sourceMapContentHash = + usesContentHash && + /** @type {string} */ ( + createHash(compilation.outputOptions.hashFunction) + .update(sourceMapString) + .digest("hex") + ); + const pathParams = { + chunk, + filename: options.fileContext + ? relative( + outputFs, + `/${options.fileContext}`, + `/${filename}` + ) + : filename, + contentHash: sourceMapContentHash + }; + const { path: sourceMapFile, info: sourceMapInfo } = + compilation.getPathWithInfo( + sourceMapFilename, + pathParams + ); + const sourceMapUrl = options.publicPath + ? options.publicPath + sourceMapFile + : relative( + outputFs, + dirname(outputFs, `/${file}`), + `/${sourceMapFile}` + ); + /** @type {Source} */ + let asset = new RawSource(source); + if (currentSourceMappingURLComment !== false) { + // Add source map url to compilation asset, if currentSourceMappingURLComment is set + asset = new ConcatSource( + asset, + compilation.getPath( + currentSourceMappingURLComment, + Object.assign({ url: sourceMapUrl }, pathParams) + ) + ); + } + const assetInfo = { + related: { sourceMap: sourceMapFile } + }; + assets[file] = asset; + assetsInfo[file] = assetInfo; + compilation.updateAsset(file, asset, assetInfo); + // Add source map file to compilation assets and chunk files + const sourceMapAsset = new RawSource(sourceMapString); + const sourceMapAssetInfo = { + ...sourceMapInfo, + development: true + }; + assets[sourceMapFile] = sourceMapAsset; + assetsInfo[sourceMapFile] = sourceMapAssetInfo; + compilation.emitAsset( + sourceMapFile, + sourceMapAsset, + sourceMapAssetInfo + ); + if (chunk !== undefined) + chunk.auxiliaryFiles.add(sourceMapFile); + } else { + if (currentSourceMappingURLComment === false) { + throw new Error( + "SourceMapDevToolPlugin: append can't be false when no filename is provided" + ); + } + /** + * Add source map as data url to asset + */ + const asset = new ConcatSource( + new RawSource(source), + currentSourceMappingURLComment + .replace(/\[map\]/g, () => sourceMapString) + .replace( + /\[url\]/g, + () => + `data:application/json;charset=utf-8;base64,${Buffer.from( + sourceMapString, + "utf-8" + ).toString("base64")}` + ) + ); + assets[file] = asset; + assetsInfo[file] = undefined; + compilation.updateAsset(file, asset); + } + + task.cacheItem.store({ assets, assetsInfo }, err => { + reportProgress( + 0.5 + (0.5 * ++taskIndex) / tasks.length, + task.file, + "attached SourceMap" + ); + + if (err) { + return callback(err); + } + callback(); + }); + }, + err => { + reportProgress(1.0); + callback(err); + } + ); + } + ); + } + ); + }); } } -makeSerializable(ModuleParseError, "webpack/lib/ModuleParseError"); - -module.exports = ModuleParseError; +module.exports = SourceMapDevToolPlugin; /***/ }), -/***/ 36418: +/***/ 31743: /***/ (function(module) { "use strict"; @@ -54052,111 +55114,88 @@ module.exports = ModuleParseError; -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; +/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ - /** @deprecated */ - this.additionalIntegration = 0; +class Stats { + /** + * @param {Compilation} compilation webpack compilation + */ + constructor(compilation) { + this.compilation = compilation; } - markFactoryStart() { - this.factoryStartTime = Date.now(); + get hash() { + return this.compilation.hash; } - markFactoryEnd() { - this.factoryEndTime = Date.now(); - this.factory = this.factoryEndTime - this.factoryStartTime; + get startTime() { + return this.compilation.startTime; } - markRestoringStart() { - this.restoringStartTime = Date.now(); + get endTime() { + return this.compilation.endTime; } - markRestoringEnd() { - this.restoringEndTime = Date.now(); - this.restoring = this.restoringEndTime - this.restoringStartTime; + /** + * @returns {boolean} true if the compilation had a warning + */ + hasWarnings() { + return ( + this.compilation.warnings.length > 0 || + this.compilation.children.some(child => child.getStats().hasWarnings()) + ); } - markIntegrationStart() { - this.integrationStartTime = Date.now(); + /** + * @returns {boolean} true if the compilation encountered an error + */ + hasErrors() { + return ( + this.compilation.errors.length > 0 || + this.compilation.children.some(child => child.getStats().hasErrors()) + ); } - markIntegrationEnd() { - this.integrationEndTime = Date.now(); - this.integration = this.integrationEndTime - this.integrationStartTime; - } + /** + * @param {(string|StatsOptions)=} options stats options + * @returns {StatsCompilation} json output + */ + toJson(options) { + options = this.compilation.createStatsOptions(options, { + forToString: false + }); - markBuildingStart() { - this.buildingStartTime = Date.now(); + const statsFactory = this.compilation.createStatsFactory(options); + + return statsFactory.create("compilation", this.compilation, { + compilation: this.compilation + }); } - markBuildingEnd() { - this.buildingEndTime = Date.now(); - this.building = this.buildingEndTime - this.buildingStartTime; - } - - markStoringStart() { - this.storingStartTime = Date.now(); - } + toString(options) { + options = this.compilation.createStatsOptions(options, { + forToString: true + }); - markStoringEnd() { - this.storingEndTime = Date.now(); - this.storing = this.storingEndTime - this.storingStartTime; - } + const statsFactory = this.compilation.createStatsFactory(options); + const statsPrinter = this.compilation.createStatsPrinter(options); - // 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 + const data = statsFactory.create("compilation", this.compilation, { + compilation: this.compilation }); + const result = statsPrinter.print("compilation", data); + return result === undefined ? "" : result; } } -module.exports = ModuleProfile; +module.exports = Stats; /***/ }), -/***/ 94560: +/***/ 1626: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -54167,315 +55206,833 @@ module.exports = ModuleProfile; -const WebpackError = __webpack_require__(53799); +const { ConcatSource, PrefixSource } = __webpack_require__(51255); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compilation").PathData} PathData */ +/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ /** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("./RuntimeModule")} RuntimeModule */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ +/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -class ModuleRestoreError extends WebpackError { +const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0); +const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0); +const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1; +const NUMBER_OF_IDENTIFIER_START_CHARS = DELTA_A_TO_Z * 2 + 2; // a-z A-Z _ $ +const NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS = + NUMBER_OF_IDENTIFIER_START_CHARS + 10; // a-z A-Z _ $ 0-9 +const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g; +const INDENT_MULTILINE_REGEX = /^\t/gm; +const LINE_SEPARATOR_REGEX = /\r?\n/g; +const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/; +const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g; +const COMMENT_END_REGEX = /\*\//g; +const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g; +const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; + +/** + * @typedef {Object} RenderManifestOptions + * @property {Chunk} chunk the chunk used to render + * @property {string} hash + * @property {string} fullHash + * @property {OutputOptions} outputOptions + * @property {CodeGenerationResults} codeGenerationResults + * @property {{javascript: ModuleTemplate}} moduleTemplates + * @property {DependencyTemplates} dependencyTemplates + * @property {RuntimeTemplate} runtimeTemplate + * @property {ModuleGraph} moduleGraph + * @property {ChunkGraph} chunkGraph + */ + +/** @typedef {RenderManifestEntryTemplated | RenderManifestEntryStatic} RenderManifestEntry */ + +/** + * @typedef {Object} RenderManifestEntryTemplated + * @property {function(): Source} render + * @property {string | function(PathData, AssetInfo=): string} filenameTemplate + * @property {PathData=} pathOptions + * @property {AssetInfo=} info + * @property {string} identifier + * @property {string=} hash + * @property {boolean=} auxiliary + */ + +/** + * @typedef {Object} RenderManifestEntryStatic + * @property {function(): Source} render + * @property {string} filename + * @property {AssetInfo} info + * @property {string} identifier + * @property {string=} hash + * @property {boolean=} auxiliary + */ + +/** + * @typedef {Object} HasId + * @property {number | string} id + */ + +/** + * @typedef {function(Module, number): boolean} ModuleFilterPredicate + */ + +class Template { /** - * @param {Module} module module tied to dependency - * @param {string | Error} err error thrown + * + * @param {Function} fn a runtime function (.runtime.js) "template" + * @returns {string} the updated and normalized function string */ - 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); + static getFunctionContent(fn) { + return fn + .toString() + .replace(FUNCTION_CONTENT_REGEX, "") + .replace(INDENT_MULTILINE_REGEX, "") + .replace(LINE_SEPARATOR_REGEX, "\n"); + } + + /** + * @param {string} str the string converted to identifier + * @returns {string} created identifier + */ + static toIdentifier(str) { + if (typeof str !== "string") return ""; + return str + .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1") + .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_"); + } + /** + * + * @param {string} str string to be converted to commented in bundle code + * @returns {string} returns a commented version of string + */ + static toComment(str) { + if (!str) return ""; + return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`; + } + + /** + * + * @param {string} str string to be converted to "normal comment" + * @returns {string} returns a commented version of string + */ + static toNormalComment(str) { + if (!str) return ""; + return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`; + } + + /** + * @param {string} str string path to be normalized + * @returns {string} normalized bundle-safe path + */ + static toPath(str) { + if (typeof str !== "string") return ""; + return str + .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-") + .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, ""); + } + + // map number to a single character a-z, A-Z or multiple characters if number is too big + /** + * @param {number} n number to convert to ident + * @returns {string} returns single character ident + */ + static numberToIdentifier(n) { + if (n >= NUMBER_OF_IDENTIFIER_START_CHARS) { + // use multiple letters + return ( + Template.numberToIdentifier(n % NUMBER_OF_IDENTIFIER_START_CHARS) + + Template.numberToIdentifierContinuation( + Math.floor(n / NUMBER_OF_IDENTIFIER_START_CHARS) + ) + ); } - super(message); + // lower case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); + } + n -= DELTA_A_TO_Z; - this.name = "ModuleRestoreError"; - this.details = details; - this.module = module; - this.error = err; + // upper case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); + } + + if (n === DELTA_A_TO_Z) return "_"; + return "$"; } -} -module.exports = ModuleRestoreError; + /** + * @param {number} n number to convert to ident + * @returns {string} returns single character ident + */ + static numberToIdentifierContinuation(n) { + if (n >= NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) { + // use multiple letters + return ( + Template.numberToIdentifierContinuation( + n % NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS + ) + + Template.numberToIdentifierContinuation( + Math.floor(n / NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) + ) + ); + } + // lower case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); + } + n -= DELTA_A_TO_Z; -/***/ }), + // upper case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); + } + n -= DELTA_A_TO_Z; -/***/ 59001: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // numbers + if (n < 10) { + return `${n}`; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (n === 10) return "_"; + return "$"; + } + /** + * + * @param {string | string[]} s string to convert to identity + * @returns {string} converted identity + */ + static indent(s) { + if (Array.isArray(s)) { + return s.map(Template.indent).join("\n"); + } else { + const str = s.trimRight(); + if (!str) return ""; + const ind = str[0] === "\n" ? "" : "\t"; + return ind + str.replace(/\n([^\n])/g, "\n\t$1"); + } + } + /** + * + * @param {string|string[]} s string to create prefix for + * @param {string} prefix prefix to compose + * @returns {string} returns new prefix string + */ + static prefix(s, prefix) { + const str = Template.asString(s).trim(); + if (!str) return ""; + const ind = str[0] === "\n" ? "" : prefix; + return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); + } -const WebpackError = __webpack_require__(53799); + /** + * + * @param {string|string[]} str string or string collection + * @returns {string} returns a single string from array + */ + static asString(str) { + if (Array.isArray(str)) { + return str.join("\n"); + } + return str; + } -/** @typedef {import("./Module")} Module */ + /** + * @typedef {Object} WithId + * @property {string|number} id + */ -class ModuleStoreError extends WebpackError { /** - * @param {Module} module module tied to dependency - * @param {string | Error} err error thrown + * @param {WithId[]} modules a collection of modules to get array bounds for + * @returns {[number, number] | false} returns the upper and lower array bounds + * or false if not every module has a number based id */ - 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; + static getModulesArrayBounds(modules) { + let maxId = -Infinity; + let minId = Infinity; + for (const module of modules) { + const moduleId = module.id; + if (typeof moduleId !== "number") return false; + if (maxId < moduleId) maxId = moduleId; + if (minId > moduleId) minId = moduleId; + } + if (minId < 16 + ("" + minId).length) { + // add minId x ',' instead of 'Array(minId).concat(…)' + minId = 0; + } + // start with -1 because the first module needs no comma + let objectOverhead = -1; + for (const module of modules) { + // module id + colon + comma + objectOverhead += `${module.id}`.length + 2; + } + // number of commas, or when starting non-zero the length of Array(minId).concat() + const arrayOverhead = minId === 0 ? maxId : 16 + `${minId}`.length + maxId; + return arrayOverhead < objectOverhead ? [minId, maxId] : false; + } + + /** + * @param {ChunkRenderContext} renderContext render context + * @param {Module[]} modules modules to render (should be ordered by identifier) + * @param {function(Module): Source} renderModule function to render a module + * @param {string=} prefix applying prefix strings + * @returns {Source} rendered chunk modules in a Source object + */ + static renderChunkModules(renderContext, modules, renderModule, prefix = "") { + const { chunkGraph } = renderContext; + var source = new ConcatSource(); + if (modules.length === 0) { + return null; + } + /** @type {{id: string|number, source: Source|string}[]} */ + const allModules = modules.map(module => { + return { + id: chunkGraph.getModuleId(module), + source: renderModule(module) || "false" + }; + }); + const bounds = Template.getModulesArrayBounds(allModules); + if (bounds) { + // Render a spare array + const minId = bounds[0]; + const maxId = bounds[1]; + if (minId !== 0) { + source.add(`Array(${minId}).concat(`); + } + source.add("[\n"); + /** @type {Map} */ + const modules = new Map(); + for (const module of allModules) { + modules.set(module.id, module); + } + for (let idx = minId; idx <= maxId; idx++) { + const module = modules.get(idx); + if (idx !== minId) { + source.add(",\n"); + } + source.add(`/* ${idx} */`); + if (module) { + source.add("\n"); + source.add(module.source); + } + } + source.add("\n" + prefix + "]"); + if (minId !== 0) { + source.add(")"); } } else { - message += String(err); + // Render an object + source.add("{\n"); + for (let i = 0; i < allModules.length; i++) { + const module = allModules[i]; + if (i !== 0) { + source.add(",\n"); + } + source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`); + source.add(module.source); + } + source.add(`\n\n${prefix}}`); } + return source; + } - super(message); + /** + * @param {RuntimeModule[]} runtimeModules array of runtime modules in order + * @param {RenderContext & { codeGenerationResults?: CodeGenerationResults }} renderContext render context + * @returns {Source} rendered runtime modules in a Source object + */ + static renderRuntimeModules(runtimeModules, renderContext) { + const source = new ConcatSource(); + for (const module of runtimeModules) { + const codeGenerationResults = renderContext.codeGenerationResults; + let runtimeSource; + if (codeGenerationResults) { + runtimeSource = codeGenerationResults.getSource( + module, + renderContext.chunk.runtime, + "runtime" + ); + } else { + const codeGenResult = module.codeGeneration({ + chunkGraph: renderContext.chunkGraph, + dependencyTemplates: renderContext.dependencyTemplates, + moduleGraph: renderContext.moduleGraph, + runtimeTemplate: renderContext.runtimeTemplate, + runtime: renderContext.chunk.runtime, + codeGenerationResults + }); + if (!codeGenResult) continue; + runtimeSource = codeGenResult.sources.get("runtime"); + } + if (runtimeSource) { + source.add(Template.toNormalComment(module.identifier()) + "\n"); + if (!module.shouldIsolate()) { + source.add(runtimeSource); + source.add("\n\n"); + } else if (renderContext.runtimeTemplate.supportsArrowFunction()) { + source.add("(() => {\n"); + source.add(new PrefixSource("\t", runtimeSource)); + source.add("\n})();\n\n"); + } else { + source.add("!function() {\n"); + source.add(new PrefixSource("\t", runtimeSource)); + source.add("\n}();\n\n"); + } + } + } + return source; + } - this.name = "ModuleStoreError"; - this.details = details; - this.module = module; - this.error = err; + /** + * @param {RuntimeModule[]} runtimeModules array of runtime modules in order + * @param {RenderContext} renderContext render context + * @returns {Source} rendered chunk runtime modules in a Source object + */ + static renderChunkRuntimeModules(runtimeModules, renderContext) { + return new PrefixSource( + "/******/ ", + new ConcatSource( + "function(__webpack_require__) { // webpackRuntimeModules\n", + this.renderRuntimeModules(runtimeModules, renderContext), + "}\n" + ) + ); } } -module.exports = ModuleStoreError; +module.exports = Template; +module.exports.NUMBER_OF_IDENTIFIER_START_CHARS = + NUMBER_OF_IDENTIFIER_START_CHARS; +module.exports.NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS = + NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS; /***/ }), -/***/ 62677: +/***/ 80734: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Jason Anderson @diurnalist */ +const { basename, extname } = __webpack_require__(71017); const util = __webpack_require__(73837); -const memoize = __webpack_require__(78676); +const Chunk = __webpack_require__(39385); +const Module = __webpack_require__(73208); +const { parseResource } = __webpack_require__(82186); -/** @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 */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./Compilation").PathData} PathData */ +/** @typedef {import("./Compiler")} Compiler */ -const getJavascriptModulesPlugin = memoize(() => - __webpack_require__(89464) -); +const REGEXP = /\[\\*([\w:]+)\\*\]/gi; -// TODO webpack 6: remove this class -class ModuleTemplate { +const prepareId = id => { + if (typeof id !== "string") return id; + + if (/^"\s\+*.*\+\s*"$/.test(id)) { + const match = /^"\s\+*\s*(.*)\s*\+\s*"$/.exec(id); + + return `" + (${match[1]} + "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_") + "`; + } + + return id.replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_"); +}; + +const hashLength = (replacer, handler, assetInfo, hashName) => { + const fn = (match, arg, input) => { + let result; + const length = arg && parseInt(arg, 10); + + if (length && handler) { + result = handler(length); + } else { + const hash = replacer(match, arg, input); + + result = length ? hash.slice(0, length) : hash; + } + if (assetInfo) { + assetInfo.immutable = true; + if (Array.isArray(assetInfo[hashName])) { + assetInfo[hashName] = [...assetInfo[hashName], result]; + } else if (assetInfo[hashName]) { + assetInfo[hashName] = [assetInfo[hashName], result]; + } else { + assetInfo[hashName] = result; + } + } + return result; + }; + + return fn; +}; + +const replacer = (value, allowEmpty) => { + const fn = (match, arg, input) => { + if (typeof value === "function") { + value = value(); + } + if (value === null || value === undefined) { + if (!allowEmpty) { + throw new Error( + `Path variable ${match} not implemented in this context: ${input}` + ); + } + + return ""; + } else { + return `${value}`; + } + }; + + return fn; +}; + +const deprecationCache = new Map(); +const deprecatedFunction = (() => () => {})(); +const deprecated = (fn, message, code) => { + let d = deprecationCache.get(message); + if (d === undefined) { + d = util.deprecate(deprecatedFunction, message, code); + deprecationCache.set(message, d); + } + return (...args) => { + d(); + return fn(...args); + }; +}; + +/** + * @param {string | function(PathData, AssetInfo=): string} path the raw path + * @param {PathData} data context data + * @param {AssetInfo} assetInfo extra info about the asset (will be written to) + * @returns {string} the interpolated path + */ +const replacePathVariables = (path, data, assetInfo) => { + const chunkGraph = data.chunkGraph; + + /** @type {Map} */ + const replacements = new Map(); + + // Filename context + // + // Placeholders + // + // for /some/path/file.js?query#fragment: + // [file] - /some/path/file.js + // [query] - ?query + // [fragment] - #fragment + // [base] - file.js + // [path] - /some/path/ + // [name] - file + // [ext] - .js + if (typeof data.filename === "string") { + const { path: file, query, fragment } = parseResource(data.filename); + + const ext = extname(file); + const base = basename(file); + const name = base.slice(0, base.length - ext.length); + const path = file.slice(0, file.length - base.length); + + replacements.set("file", replacer(file)); + replacements.set("query", replacer(query, true)); + replacements.set("fragment", replacer(fragment, true)); + replacements.set("path", replacer(path, true)); + replacements.set("base", replacer(base)); + replacements.set("name", replacer(name)); + replacements.set("ext", replacer(ext, true)); + // Legacy + replacements.set( + "filebase", + deprecated( + replacer(base), + "[filebase] is now [base]", + "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME" + ) + ); + } + + // Compilation context + // + // Placeholders + // + // [fullhash] - data.hash (3a4b5c6e7f) + // + // Legacy Placeholders + // + // [hash] - data.hash (3a4b5c6e7f) + if (data.hash) { + const hashReplacer = hashLength( + replacer(data.hash), + data.hashWithLength, + assetInfo, + "fullhash" + ); + + replacements.set("fullhash", hashReplacer); + + // Legacy + replacements.set( + "hash", + deprecated( + hashReplacer, + "[hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)", + "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH" + ) + ); + } + + // Chunk Context + // + // Placeholders + // + // [id] - chunk.id (0.js) + // [name] - chunk.name (app.js) + // [chunkhash] - chunk.hash (7823t4t4.js) + // [contenthash] - chunk.contentHash[type] (3256u3zg.js) + if (data.chunk) { + const chunk = data.chunk; + + const contentHashType = data.contentHashType; + + const idReplacer = replacer(chunk.id); + const nameReplacer = replacer(chunk.name || chunk.id); + const chunkhashReplacer = hashLength( + replacer(chunk instanceof Chunk ? chunk.renderedHash : chunk.hash), + "hashWithLength" in chunk ? chunk.hashWithLength : undefined, + assetInfo, + "chunkhash" + ); + const contenthashReplacer = hashLength( + replacer( + data.contentHash || + (contentHashType && + chunk.contentHash && + chunk.contentHash[contentHashType]) + ), + data.contentHashWithLength || + ("contentHashWithLength" in chunk && chunk.contentHashWithLength + ? chunk.contentHashWithLength[contentHashType] + : undefined), + assetInfo, + "contenthash" + ); + + replacements.set("id", idReplacer); + replacements.set("name", nameReplacer); + replacements.set("chunkhash", chunkhashReplacer); + replacements.set("contenthash", contenthashReplacer); + } + + // Module Context + // + // Placeholders + // + // [id] - module.id (2.png) + // [hash] - module.hash (6237543873.png) + // + // Legacy Placeholders + // + // [moduleid] - module.id (2.png) + // [modulehash] - module.hash (6237543873.png) + if (data.module) { + const module = data.module; + + const idReplacer = replacer(() => + prepareId( + module instanceof Module ? chunkGraph.getModuleId(module) : module.id + ) + ); + const moduleHashReplacer = hashLength( + replacer(() => + module instanceof Module + ? chunkGraph.getRenderedModuleHash(module, data.runtime) + : module.hash + ), + "hashWithLength" in module ? module.hashWithLength : undefined, + assetInfo, + "modulehash" + ); + const contentHashReplacer = hashLength( + replacer(data.contentHash), + undefined, + assetInfo, + "contenthash" + ); + + replacements.set("id", idReplacer); + replacements.set("modulehash", moduleHashReplacer); + replacements.set("contenthash", contentHashReplacer); + replacements.set( + "hash", + data.contentHash ? contentHashReplacer : moduleHashReplacer + ); + // Legacy + replacements.set( + "moduleid", + deprecated( + idReplacer, + "[moduleid] is now [id]", + "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_MODULE_ID" + ) + ); + } + + // Other things + if (data.url) { + replacements.set("url", replacer(data.url)); + } + if (typeof data.runtime === "string") { + replacements.set( + "runtime", + replacer(() => prepareId(data.runtime)) + ); + } else { + replacements.set("runtime", replacer("_")); + } + + if (typeof path === "function") { + path = path(data, assetInfo); + } + + path = path.replace(REGEXP, (match, content) => { + if (content.length + 2 === match.length) { + const contentMatch = /^(\w+)(?::(\w+))?$/.exec(content); + if (!contentMatch) return match; + const [, kind, arg] = contentMatch; + const replacer = replacements.get(kind); + if (replacer !== undefined) { + return replacer(match, arg, path); + } + } else if (match.startsWith("[\\") && match.endsWith("\\]")) { + return `[${match.slice(2, -2)}]`; + } + return match; + }); + + return path; +}; + +const plugin = "TemplatedPathPlugin"; + +class TemplatedPathPlugin { /** - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {Compilation} compilation the compilation + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - 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" - ) - } + apply(compiler) { + compiler.hooks.compilation.tap(plugin, compilation => { + compilation.hooks.assetPath.tap(plugin, replacePathVariables); }); } } -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; +module.exports = TemplatedPathPlugin; /***/ }), -/***/ 11234: +/***/ 68099: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const { cleanUp } = __webpack_require__(59985); const WebpackError = __webpack_require__(53799); const makeSerializable = __webpack_require__(33032); -class ModuleWarning extends WebpackError { +class UnhandledSchemeError extends WebpackError { /** - * @param {Error} warning error thrown - * @param {{from?: string|null}} info additional info + * @param {string} scheme scheme + * @param {string} resource resource */ - constructor(warning, { from = null } = {}) { - let message = "Module Warning"; + constructor(scheme, resource) { + super( + `Reading from "${resource}" is not handled by plugins (Unhandled scheme).` + + '\nWebpack supports "data:" and "file:" URIs by default.' + + `\nYou may need an additional plugin to handle "${scheme}:" URIs.` + ); + this.file = resource; + this.name = "UnhandledSchemeError"; + } +} - if (from) { - message += ` (from ${from}):\n`; - } else { - message += ": "; - } +makeSerializable( + UnhandledSchemeError, + "webpack/lib/UnhandledSchemeError", + "UnhandledSchemeError" +); - if (warning && typeof warning === "object" && warning.message) { - message += warning.message; - } else if (warning) { - message += String(warning); - } +module.exports = UnhandledSchemeError; - super(message); - this.name = "ModuleWarning"; - this.warning = warning; - this.details = - warning && typeof warning === "object" && warning.stack - ? cleanUp(warning.stack, this.message) - : undefined; - } +/***/ }), - serialize(context) { - const { write } = context; +/***/ 42495: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - write(this.warning); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - super.serialize(context); - } - deserialize(context) { - const { read } = context; - this.warning = read(); +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); - super.deserialize(context); +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + +class UnsupportedFeatureWarning extends WebpackError { + /** + * @param {string} message description of warning + * @param {DependencyLocation} loc location start and end positions of the module + */ + constructor(message, loc) { + super(message); + + this.name = "UnsupportedFeatureWarning"; + this.loc = loc; + this.hideStack = true; } } -makeSerializable(ModuleWarning, "webpack/lib/ModuleWarning"); +makeSerializable( + UnsupportedFeatureWarning, + "webpack/lib/UnsupportedFeatureWarning" +); -module.exports = ModuleWarning; +module.exports = UnsupportedFeatureWarning; /***/ }), -/***/ 33370: +/***/ 36803: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -54486,586 +56043,183 @@ module.exports = ModuleWarning; -const asyncLib = __webpack_require__(78175); -const { SyncHook, MultiHook } = __webpack_require__(41242); - -const ConcurrentCompilationError = __webpack_require__(95735); -const MultiStats = __webpack_require__(24170); -const MultiWatching = __webpack_require__(81128); -const ArrayQueue = __webpack_require__(41792); +const ConstDependency = __webpack_require__(76911); -/** @template T @typedef {import("tapable").AsyncSeriesHook} AsyncSeriesHook */ -/** @template T @template R @typedef {import("tapable").SyncBailHook} SyncBailHook */ -/** @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 | null)=} err - * @param {T=} result - */ -/** - * @callback RunWithDependenciesHandler - * @param {Compiler} compiler - * @param {Callback} callback - */ - -/** - * @typedef {Object} MultiCompilerOptions - * @property {number=} parallelism how many Compilers are allows to run at the same time in parallel - */ - -module.exports = class MultiCompiler { +class UseStrictPlugin { /** - * @param {Compiler[] | Record} compilers child compilers - * @param {MultiCompilerOptions} options options + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - 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>} */ - invalid: new MultiHook(compilers.map(c => c.hooks.invalid)), - /** @type {MultiHook>} */ - run: new MultiHook(compilers.map(c => c.hooks.run)), - /** @type {SyncHook<[]>} */ - watchClose: new SyncHook([]), - /** @type {MultiHook>} */ - watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)), - /** @type {MultiHook>} */ - infrastructureLog: new MultiHook( - compilers.map(c => c.hooks.infrastructureLog) - ) - }); - this.compilers = compilers; - /** @type {MultiCompilerOptions} */ - this._options = { - parallelism: options.parallelism || Infinity - }; - /** @type {WeakMap} */ - 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; - 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)); - } - }); - compiler.hooks.invalid.tap("MultiCompiler", () => { - if (compilerDone) { - compilerDone = false; - doneCompilers--; - } - }); - } - } - - get options() { - return Object.assign( - this.compilers.map(c => c.options), - this._options - ); - } + apply(compiler) { + compiler.hooks.compilation.tap( + "UseStrictPlugin", + (compilation, { normalModuleFactory }) => { + const handler = parser => { + parser.hooks.program.tap("UseStrictPlugin", ast => { + const firstNode = ast.body[0]; + if ( + firstNode && + firstNode.type === "ExpressionStatement" && + firstNode.expression.type === "Literal" && + firstNode.expression.value === "use strict" + ) { + // Remove "use strict" expression. It will be added later by the renderer again. + // This is necessary in order to not break the strict mode when webpack prepends code. + // @see https://github.com/webpack/webpack/issues/1970 + const dep = new ConstDependency("", firstNode.range); + dep.loc = firstNode.loc; + parser.state.module.addPresentationalDependency(dep); + parser.state.module.buildInfo.strict = true; + } + }); + }; - 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(/[/\\][^/\\]*$/, ""); + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("UseStrictPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("UseStrictPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("UseStrictPlugin", handler); } - } - - if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/"; - return commonPath; + ); } +} - get inputFileSystem() { - throw new Error("Cannot read inputFileSystem of a MultiCompiler"); - } +module.exports = UseStrictPlugin; - 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"); - } +/***/ 56504: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @param {InputFileSystem} value the new input file system - */ - set inputFileSystem(value) { - for (const compiler of this.compilers) { - compiler.inputFileSystem = value; - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @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; - } - } +const CaseSensitiveModulesWarning = __webpack_require__(77975); - getInfrastructureLogger(name) { - return this.compilers[0].getInfrastructureLogger(name); - } +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ +class WarnCaseSensitiveModulesPlugin { /** - * @param {Compiler} compiler the child compiler - * @param {string[]} dependencies its dependencies + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - setDependencies(compiler, dependencies) { - this.dependencies.set(compiler, dependencies); - } - - /** - * @param {Callback} 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 - }); + apply(compiler) { + compiler.hooks.compilation.tap( + "WarnCaseSensitiveModulesPlugin", + compilation => { + compilation.hooks.seal.tap("WarnCaseSensitiveModulesPlugin", () => { + /** @type {Map>} */ + const moduleWithoutCase = new Map(); + for (const module of compilation.modules) { + const identifier = module.identifier(); + const lowerIdentifier = identifier.toLowerCase(); + let map = moduleWithoutCase.get(lowerIdentifier); + if (map === undefined) { + map = new Map(); + moduleWithoutCase.set(lowerIdentifier, map); + } + map.set(identifier, module); } - } - } - } - /** @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); + for (const pair of moduleWithoutCase) { + const map = pair[1]; + if (map.size > 1) { + compilation.warnings.push( + new CaseSensitiveModulesWarning( + map.values(), + compilation.moduleGraph + ) + ); + } } - } + }); } - } - 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} 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); - } +module.exports = WarnCaseSensitiveModulesPlugin; - /** - * @template SetupResult - * @param {function(Compiler, number, Callback, function(): boolean, function(): void, function(): void): SetupResult} setup setup a single compiler - * @param {function(Compiler, SetupResult, Callback): void} run run/continue a single compiler - * @param {Callback} callback callback when all compilers are done, result includes Stats of all changed compilers - * @returns {SetupResult[]} result of setup - */ - _runGraph(setup, run, callback) { - /** @typedef {{ compiler: Compiler, setupResult: SetupResult, result: Stats, state: "pending" | "blocked" | "queued" | "starting" | "running" | "running-outdated" | "done", children: Node[], parents: Node[] }} Node */ - // State transitions for nodes: - // -> blocked (initial) - // blocked -> starting [running++] (when all parents done) - // queued -> starting [running++] (when processing the queue) - // starting -> running (when run has been called) - // running -> done [running--] (when compilation is done) - // done -> pending (when invalidated from file change) - // pending -> blocked [add to queue] (when invalidated from aggregated changes) - // done -> blocked [add to queue] (when invalidated, from parent invalidation) - // running -> running-outdated (when invalidated, either from change or parent invalidation) - // running-outdated -> blocked [running--] (when compilation is done) +/***/ }), - /** @type {Node[]} */ - const nodes = this.compilers.map(compiler => ({ - compiler, - setupResult: undefined, - result: undefined, - state: "blocked", - children: [], - parents: [] - })); - /** @type {Map} */ - 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); - } - } - /** @type {ArrayQueue} */ - 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) { - if (child.state === "blocked") queue.enqueue(child); - } - } else if (node.state === "running-outdated") { - node.state = "blocked"; - queue.enqueue(node); - } - processQueue(); - }; - /** - * @param {Node} node node - * @returns {void} - */ - const nodeInvalidFromParent = node => { - if (node.state === "done") { - node.state = "blocked"; - } else if (node.state === "running") { - node.state = "running-outdated"; - } - for (const child of node.children) { - nodeInvalidFromParent(child); - } - }; - /** - * @param {Node} node node - * @returns {void} - */ - const nodeInvalid = node => { - if (node.state === "done") { - node.state = "pending"; - } else if (node.state === "running") { - node.state = "running-outdated"; - } - for (const child of node.children) { - nodeInvalidFromParent(child); - } - }; - /** - * @param {Node} node node - * @returns {void} - */ - const nodeChange = node => { - nodeInvalid(node); - if (node.state === "pending") { - node.state = "blocked"; - } - if (node.state === "blocked") { - queue.enqueue(node); - processQueue(); - } - }; +/***/ 76537: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const setupResults = []; - nodes.forEach((node, i) => { - setupResults.push( - (node.setupResult = setup( - node.compiler, - i, - nodeDone.bind(null, node), - () => node.state !== "starting" && node.state !== "running", - () => nodeChange(node), - () => nodeInvalid(node) - )) - ); - }); - let processing = true; - const processQueue = () => { - if (processing) return; - processing = true; - process.nextTick(processQueueWorker); - }; - const processQueueWorker = () => { - while (running < parallelism && queue.length > 0 && !errored) { - const node = queue.dequeue(); - if ( - node.state === "queued" || - (node.state === "blocked" && - node.parents.every(p => p.state === "done")) - ) { - running++; - node.state = "starting"; - run(node.compiler, node.setupResult, nodeDone.bind(null, node)); - node.state = "running"; - } - } - processing = false; - if ( - !errored && - running === 0 && - nodes.every(node => node.state === "done") - ) { - const stats = []; - for (const node of nodes) { - const result = node.result; - if (result) { - node.result = undefined; - stats.push(result); - } - } - if (stats.length > 0) { - callback(null, new MultiStats(stats)); - } - } - }; - processQueueWorker(); - return setupResults; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ - /** - * @param {WatchOptions|WatchOptions[]} watchOptions the watcher's options - * @param {Callback} handler signals when the call finishes - * @returns {MultiWatching} a compiler watcher - */ - watch(watchOptions, handler) { - if (this.running) { - return handler(new ConcurrentCompilationError()); - } - this.running = true; - if (this.validateDependencies(handler)) { - const watchings = this._runGraph( - (compiler, idx, callback, isBlocked, setChanged, setInvalid) => { - const watching = compiler.watch( - Array.isArray(watchOptions) ? watchOptions[idx] : watchOptions, - callback - ); - if (watching) { - watching._onInvalid = setInvalid; - watching._onChange = setChanged; - watching._isBlocked = isBlocked; - } - return watching; - }, - (compiler, watching, callback) => { - if (compiler.watching !== watching) return; - if (!watching.running) watching.invalidate(); - }, - handler - ); - return new MultiWatching(watchings, this); - } - return new MultiWatching([], this); - } +const WebpackError = __webpack_require__(53799); + +/** @typedef {import("./Compiler")} Compiler */ +class WarnDeprecatedOptionPlugin { /** - * @param {Callback} callback signals when the call finishes - * @returns {void} + * Create an instance of the plugin + * @param {string} option the target option + * @param {string | number} value the deprecated option value + * @param {string} suggestion the suggestion replacement */ - run(callback) { - if (this.running) { - return callback(new ConcurrentCompilationError()); - } - this.running = true; - - if (this.validateDependencies(callback)) { - this._runGraph( - () => {}, - (compiler, setupResult, callback) => compiler.run(callback), - (err, stats) => { - this.running = false; - - if (callback !== undefined) { - return callback(err, stats); - } - } - ); - } - } - - purgeInputFileSystem() { - for (const compiler of this.compilers) { - if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { - compiler.inputFileSystem.purge(); - } - } + constructor(option, value, suggestion) { + this.option = option; + this.value = value; + this.suggestion = suggestion; } /** - * @param {Callback} callback signals when the compiler closes + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - close(callback) { - asyncLib.each( - this.compilers, - (compiler, callback) => { - compiler.close(callback); - }, - callback + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "WarnDeprecatedOptionPlugin", + compilation => { + compilation.warnings.push( + new DeprecatedOptionWarning(this.option, this.value, this.suggestion) + ); + } ); } -}; +} + +class DeprecatedOptionWarning extends WebpackError { + constructor(option, value, suggestion) { + super(); + + this.name = "DeprecatedOptionWarning"; + this.message = + "configuration\n" + + `The value '${value}' for option '${option}' is deprecated. ` + + `Use '${suggestion}' instead.`; + } +} + +module.exports = WarnDeprecatedOptionPlugin; /***/ }), -/***/ 24170: +/***/ 25295: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -55076,170 +56230,29 @@ module.exports = class MultiCompiler { -const identifierUtils = __webpack_require__(82186); - -/** @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()); - } +const NoModeWarning = __webpack_require__(80832); - _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 - }; - } +/** @typedef {import("./Compiler")} Compiler */ +class WarnNoModeSetPlugin { /** - * @param {any} options stats options - * @returns {StatsCompilation} json output + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - 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; + apply(compiler) { + compiler.hooks.thisCompilation.tap("WarnNoModeSetPlugin", compilation => { + compilation.warnings.push(new NoModeWarning()); }); - return results.filter(Boolean).join("\n\n"); } } -module.exports = MultiStats; +module.exports = WarnNoModeSetPlugin; /***/ }), -/***/ 81128: +/***/ 65193: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -55250,117 +56263,136 @@ module.exports = MultiStats; -const asyncLib = __webpack_require__(78175); +const { groupBy } = __webpack_require__(84953); +const createSchemaValidation = __webpack_require__(32540); -/** @typedef {import("./MultiCompiler")} MultiCompiler */ -/** @typedef {import("./Watching")} Watching */ +/** @typedef {import("../declarations/plugins/WatchIgnorePlugin").WatchIgnorePluginOptions} WatchIgnorePluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */ -/** - * @template T - * @callback Callback - * @param {(Error | null)=} err - * @param {T=} result - */ +const validate = createSchemaValidation( + __webpack_require__(16711), + () => __webpack_require__(44246), + { + name: "Watch Ignore Plugin", + baseDataPath: "options" + } +); -class MultiWatching { +const IGNORE_TIME_ENTRY = "ignore"; + +class IgnoringWatchFileSystem { /** - * @param {Watching[]} watchings child compilers' watchers - * @param {MultiCompiler} compiler the compiler + * @param {WatchFileSystem} wfs original file system + * @param {(string|RegExp)[]} paths ignored paths */ - constructor(watchings, compiler) { - this.watchings = watchings; - this.compiler = compiler; + constructor(wfs, paths) { + this.wfs = wfs; + this.paths = paths; } - invalidate(callback) { - if (callback) { - asyncLib.each( - this.watchings, - (watching, callback) => watching.invalidate(callback), - callback + watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { + files = Array.from(files); + dirs = Array.from(dirs); + const ignored = path => + this.paths.some(p => + p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0 ); - } else { - for (const watching of this.watchings) { - watching.invalidate(); - } - } - } - suspend() { - for (const watching of this.watchings) { - watching.suspend(); - } - } + const [ignoredFiles, notIgnoredFiles] = groupBy(files, ignored); + const [ignoredDirs, notIgnoredDirs] = groupBy(dirs, ignored); - resume() { - for (const watching of this.watchings) { - watching.resume(); - } - } + const watcher = this.wfs.watch( + notIgnoredFiles, + notIgnoredDirs, + missing, + startTime, + options, + (err, fileTimestamps, dirTimestamps, changedFiles, removedFiles) => { + if (err) return callback(err); + for (const path of ignoredFiles) { + fileTimestamps.set(path, IGNORE_TIME_ENTRY); + } - /** - * @param {Callback} 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); + for (const path of ignoredDirs) { + dirTimestamps.set(path, IGNORE_TIME_ENTRY); } - } + + callback( + err, + fileTimestamps, + dirTimestamps, + changedFiles, + removedFiles + ); + }, + callbackUndelayed ); + + return { + close: () => watcher.close(), + pause: () => watcher.pause(), + getContextTimeInfoEntries: () => { + const dirTimestamps = watcher.getContextTimeInfoEntries(); + for (const path of ignoredDirs) { + dirTimestamps.set(path, IGNORE_TIME_ENTRY); + } + return dirTimestamps; + }, + getFileTimeInfoEntries: () => { + const fileTimestamps = watcher.getFileTimeInfoEntries(); + for (const path of ignoredFiles) { + fileTimestamps.set(path, IGNORE_TIME_ENTRY); + } + return fileTimestamps; + }, + getInfo: + watcher.getInfo && + (() => { + const info = watcher.getInfo(); + const { fileTimeInfoEntries, contextTimeInfoEntries } = info; + for (const path of ignoredFiles) { + fileTimeInfoEntries.set(path, IGNORE_TIME_ENTRY); + } + for (const path of ignoredDirs) { + contextTimeInfoEntries.set(path, IGNORE_TIME_ENTRY); + } + return info; + }) + }; } } -module.exports = MultiWatching; - - -/***/ }), - -/***/ 50169: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @typedef {import("./Compiler")} Compiler */ +class WatchIgnorePlugin { + /** + * @param {WatchIgnorePluginOptions} options options + */ + constructor(options) { + validate(options); + this.paths = options.paths; + } -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; - }); + compiler.hooks.afterEnvironment.tap("WatchIgnorePlugin", () => { + compiler.watchFileSystem = new IgnoringWatchFileSystem( + compiler.watchFileSystem, + this.paths + ); }); } } -module.exports = NoEmitOnErrorsPlugin; +module.exports = WatchIgnorePlugin; /***/ }), -/***/ 80832: +/***/ 84275: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -55371,252 +56403,645 @@ module.exports = NoEmitOnErrorsPlugin; -const WebpackError = __webpack_require__(53799); - -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/"; - } -}; - - -/***/ }), - -/***/ 6325: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - - +const Stats = __webpack_require__(31743); -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); +/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** + * @template T + * @callback Callback + * @param {(Error | null)=} err + * @param {T=} result + */ -class NodeStuffInWebError extends WebpackError { +class Watching { /** - * @param {DependencyLocation} loc loc - * @param {string} expression expression - * @param {string} description description + * @param {Compiler} compiler the compiler + * @param {WatchOptions} watchOptions options + * @param {Callback} handler completion handler */ - constructor(loc, expression, description) { - super( - `${JSON.stringify( - expression - )} has been used, it will be undefined in next major version. -${description}` + constructor(compiler, watchOptions, handler) { + this.startTime = null; + this.invalid = false; + this.handler = handler; + /** @type {Callback[]} */ + this.callbacks = []; + /** @type {Callback[] | undefined} */ + this._closeCallbacks = undefined; + this.closed = false; + this.suspended = false; + this.blocked = false; + this._isBlocked = () => false; + this._onChange = () => {}; + this._onInvalid = () => {}; + if (typeof watchOptions === "number") { + this.watchOptions = { + aggregateTimeout: watchOptions + }; + } else if (watchOptions && typeof watchOptions === "object") { + this.watchOptions = { ...watchOptions }; + } else { + this.watchOptions = {}; + } + if (typeof this.watchOptions.aggregateTimeout !== "number") { + this.watchOptions.aggregateTimeout = 20; + } + this.compiler = compiler; + this.running = false; + this._initial = true; + this._invalidReported = true; + this._needRecords = true; + this.watcher = undefined; + this.pausedWatcher = undefined; + /** @type {Set} */ + this._collectedChangedFiles = undefined; + /** @type {Set} */ + this._collectedRemovedFiles = undefined; + this._done = this._done.bind(this); + process.nextTick(() => { + if (this._initial) this._invalidate(); + }); + } + + /** + * @param {ReadonlySet} changedFiles changed files + * @param {ReadonlySet} removedFiles removed files + */ + _mergeWithCollected(changedFiles, removedFiles) { + if (!changedFiles) return; + if (!this._collectedChangedFiles) { + this._collectedChangedFiles = new Set(changedFiles); + this._collectedRemovedFiles = new Set(removedFiles); + } else { + for (const file of changedFiles) { + this._collectedChangedFiles.add(file); + this._collectedRemovedFiles.delete(file); + } + for (const file of removedFiles) { + this._collectedChangedFiles.delete(file); + this._collectedRemovedFiles.add(file); + } + } + } + + /** + * @param {ReadonlyMap=} fileTimeInfoEntries info for files + * @param {ReadonlyMap=} contextTimeInfoEntries info for directories + * @param {ReadonlySet=} changedFiles changed files + * @param {ReadonlySet=} removedFiles removed files + * @returns {void} + */ + _go(fileTimeInfoEntries, contextTimeInfoEntries, changedFiles, removedFiles) { + this._initial = false; + if (this.startTime === null) this.startTime = Date.now(); + this.running = true; + if (this.watcher) { + this.pausedWatcher = this.watcher; + this.lastWatcherStartTime = Date.now(); + this.watcher.pause(); + this.watcher = null; + } else if (!this.lastWatcherStartTime) { + this.lastWatcherStartTime = Date.now(); + } + this.compiler.fsStartTime = Date.now(); + if ( + changedFiles && + removedFiles && + fileTimeInfoEntries && + contextTimeInfoEntries + ) { + this._mergeWithCollected(changedFiles, removedFiles); + this.compiler.fileTimestamps = fileTimeInfoEntries; + this.compiler.contextTimestamps = contextTimeInfoEntries; + } else if (this.pausedWatcher) { + if (this.pausedWatcher.getInfo) { + const { + changes, + removals, + fileTimeInfoEntries, + contextTimeInfoEntries + } = this.pausedWatcher.getInfo(); + this._mergeWithCollected(changes, removals); + this.compiler.fileTimestamps = fileTimeInfoEntries; + this.compiler.contextTimestamps = contextTimeInfoEntries; + } else { + this._mergeWithCollected( + this.pausedWatcher.getAggregatedChanges && + this.pausedWatcher.getAggregatedChanges(), + this.pausedWatcher.getAggregatedRemovals && + this.pausedWatcher.getAggregatedRemovals() + ); + this.compiler.fileTimestamps = + this.pausedWatcher.getFileTimeInfoEntries(); + this.compiler.contextTimestamps = + this.pausedWatcher.getContextTimeInfoEntries(); + } + } + this.compiler.modifiedFiles = this._collectedChangedFiles; + this._collectedChangedFiles = undefined; + this.compiler.removedFiles = this._collectedRemovedFiles; + this._collectedRemovedFiles = undefined; + + const run = () => { + if (this.compiler.idle) { + return this.compiler.cache.endIdle(err => { + if (err) return this._done(err); + this.compiler.idle = false; + run(); + }); + } + if (this._needRecords) { + return this.compiler.readRecords(err => { + if (err) return this._done(err); + + this._needRecords = false; + run(); + }); + } + this.invalid = false; + this._invalidReported = false; + this.compiler.hooks.watchRun.callAsync(this.compiler, err => { + if (err) return this._done(err); + const onCompiled = (err, compilation) => { + if (err) return this._done(err, compilation); + if (this.invalid) return this._done(null, compilation); + + if (this.compiler.hooks.shouldEmit.call(compilation) === false) { + return this._done(null, compilation); + } + + process.nextTick(() => { + const logger = compilation.getLogger("webpack.Compiler"); + logger.time("emitAssets"); + this.compiler.emitAssets(compilation, err => { + logger.timeEnd("emitAssets"); + if (err) return this._done(err, compilation); + if (this.invalid) return this._done(null, compilation); + + logger.time("emitRecords"); + this.compiler.emitRecords(err => { + logger.timeEnd("emitRecords"); + if (err) return this._done(err, compilation); + + if (compilation.hooks.needAdditionalPass.call()) { + compilation.needAdditionalPass = true; + + compilation.startTime = this.startTime; + compilation.endTime = Date.now(); + logger.time("done hook"); + const stats = new Stats(compilation); + this.compiler.hooks.done.callAsync(stats, err => { + logger.timeEnd("done hook"); + if (err) return this._done(err, compilation); + + this.compiler.hooks.additionalPass.callAsync(err => { + if (err) return this._done(err, compilation); + this.compiler.compile(onCompiled); + }); + }); + return; + } + return this._done(null, compilation); + }); + }); + }); + }; + this.compiler.compile(onCompiled); + }); + }; + + run(); + } + + /** + * @param {Compilation} compilation the compilation + * @returns {Stats} the compilation stats + */ + _getStats(compilation) { + const stats = new Stats(compilation); + return stats; + } + + /** + * @param {Error=} err an optional error + * @param {Compilation=} compilation the compilation + * @returns {void} + */ + _done(err, compilation) { + this.running = false; + + const logger = compilation && compilation.getLogger("webpack.Watching"); + + let stats = null; + + const handleError = (err, cbs) => { + this.compiler.hooks.failed.call(err); + this.compiler.cache.beginIdle(); + this.compiler.idle = true; + this.handler(err, stats); + if (!cbs) { + cbs = this.callbacks; + this.callbacks = []; + } + for (const cb of cbs) cb(err); + }; + + if ( + this.invalid && + !this.suspended && + !this.blocked && + !(this._isBlocked() && (this.blocked = true)) + ) { + if (compilation) { + logger.time("storeBuildDependencies"); + this.compiler.cache.storeBuildDependencies( + compilation.buildDependencies, + err => { + logger.timeEnd("storeBuildDependencies"); + if (err) return handleError(err); + this._go(); + } + ); + } else { + this._go(); + } + return; + } + + if (compilation) { + compilation.startTime = this.startTime; + compilation.endTime = Date.now(); + stats = new Stats(compilation); + } + this.startTime = null; + if (err) return handleError(err); + + const cbs = this.callbacks; + this.callbacks = []; + logger.time("done hook"); + this.compiler.hooks.done.callAsync(stats, err => { + logger.timeEnd("done hook"); + if (err) return handleError(err, cbs); + this.handler(null, stats); + logger.time("storeBuildDependencies"); + this.compiler.cache.storeBuildDependencies( + compilation.buildDependencies, + err => { + logger.timeEnd("storeBuildDependencies"); + if (err) return handleError(err, cbs); + logger.time("beginIdle"); + this.compiler.cache.beginIdle(); + this.compiler.idle = true; + logger.timeEnd("beginIdle"); + process.nextTick(() => { + if (!this.closed) { + this.watch( + compilation.fileDependencies, + compilation.contextDependencies, + compilation.missingDependencies + ); + } + }); + for (const cb of cbs) cb(null); + this.compiler.hooks.afterDone.call(stats); + } + ); + }); + } + + /** + * @param {Iterable} files watched files + * @param {Iterable} dirs watched directories + * @param {Iterable} missing watched existence entries + * @returns {void} + */ + watch(files, dirs, missing) { + this.pausedWatcher = null; + this.watcher = this.compiler.watchFileSystem.watch( + files, + dirs, + missing, + this.lastWatcherStartTime, + this.watchOptions, + ( + err, + fileTimeInfoEntries, + contextTimeInfoEntries, + changedFiles, + removedFiles + ) => { + if (err) { + this.compiler.modifiedFiles = undefined; + this.compiler.removedFiles = undefined; + this.compiler.fileTimestamps = undefined; + this.compiler.contextTimestamps = undefined; + this.compiler.fsStartTime = undefined; + return this.handler(err); + } + this._invalidate( + fileTimeInfoEntries, + contextTimeInfoEntries, + changedFiles, + removedFiles + ); + this._onChange(); + }, + (fileName, changeTime) => { + if (!this._invalidReported) { + this._invalidReported = true; + this.compiler.hooks.invalid.call(fileName, changeTime); + } + this._onInvalid(); + } ); + } - this.name = "NodeStuffInWebError"; - this.loc = loc; + /** + * @param {Callback=} callback signals when the build has completed again + * @returns {void} + */ + invalidate(callback) { + if (callback) { + this.callbacks.push(callback); + } + if (!this._invalidReported) { + this._invalidReported = true; + this.compiler.hooks.invalid.call(null, Date.now()); + } + this._onChange(); + this._invalidate(); + } + + _invalidate( + fileTimeInfoEntries, + contextTimeInfoEntries, + changedFiles, + removedFiles + ) { + if (this.suspended || (this._isBlocked() && (this.blocked = true))) { + this._mergeWithCollected(changedFiles, removedFiles); + return; + } + + if (this.running) { + this._mergeWithCollected(changedFiles, removedFiles); + this.invalid = true; + } else { + this._go( + fileTimeInfoEntries, + contextTimeInfoEntries, + changedFiles, + removedFiles + ); + } + } + + suspend() { + this.suspended = true; + } + + resume() { + if (this.suspended) { + this.suspended = false; + this._invalidate(); + } + } + + /** + * @param {Callback} callback signals when the watcher is closed + * @returns {void} + */ + close(callback) { + if (this._closeCallbacks) { + if (callback) { + this._closeCallbacks.push(callback); + } + return; + } + const finalCallback = (err, compilation) => { + this.running = false; + this.compiler.running = false; + this.compiler.watching = undefined; + this.compiler.watchMode = false; + this.compiler.modifiedFiles = undefined; + this.compiler.removedFiles = undefined; + this.compiler.fileTimestamps = undefined; + this.compiler.contextTimestamps = undefined; + this.compiler.fsStartTime = undefined; + const shutdown = err => { + this.compiler.hooks.watchClose.call(); + const closeCallbacks = this._closeCallbacks; + this._closeCallbacks = undefined; + for (const cb of closeCallbacks) cb(err); + }; + if (compilation) { + const logger = compilation.getLogger("webpack.Watching"); + logger.time("storeBuildDependencies"); + this.compiler.cache.storeBuildDependencies( + compilation.buildDependencies, + err2 => { + logger.timeEnd("storeBuildDependencies"); + shutdown(err || err2); + } + ); + } else { + shutdown(err); + } + }; + + this.closed = true; + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + if (this.pausedWatcher) { + this.pausedWatcher.close(); + this.pausedWatcher = null; + } + this._closeCallbacks = []; + if (callback) { + this._closeCallbacks.push(callback); + } + if (this.running) { + this.invalid = true; + this._done = finalCallback; + } else { + finalCallback(); + } } } -makeSerializable(NodeStuffInWebError, "webpack/lib/NodeStuffInWebError"); +module.exports = Watching; -module.exports = NodeStuffInWebError; + +/***/ }), + +/***/ 53799: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Jarid Margolin @jaridmargolin +*/ + + + +const inspect = (__webpack_require__(73837).inspect.custom); +const makeSerializable = __webpack_require__(33032); + +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Module")} Module */ + +class WebpackError extends Error { + /** + * Creates an instance of WebpackError. + * @param {string=} message error message + */ + constructor(message) { + super(message); + + this.details = undefined; + /** @type {Module} */ + this.module = undefined; + /** @type {DependencyLocation} */ + this.loc = undefined; + /** @type {boolean} */ + this.hideStack = undefined; + /** @type {Chunk} */ + this.chunk = undefined; + /** @type {string} */ + this.file = undefined; + } + + [inspect]() { + return this.stack + (this.details ? `\n${this.details}` : ""); + } + + serialize({ write }) { + write(this.name); + write(this.message); + write(this.stack); + write(this.details); + write(this.loc); + write(this.hideStack); + } + + deserialize({ read }) { + this.name = read(); + this.message = read(); + this.stack = read(); + this.details = read(); + this.loc = read(); + this.hideStack = read(); + } +} + +makeSerializable(WebpackError, "webpack/lib/WebpackError"); + +module.exports = WebpackError; /***/ }), -/***/ 95287: +/***/ 97017: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const NodeStuffInWebError = __webpack_require__(6325); -const RuntimeGlobals = __webpack_require__(16475); -const CachedConstDependency = __webpack_require__(57403); -const ConstDependency = __webpack_require__(76911); +const IgnoreErrorModuleFactory = __webpack_require__(3); +const WebpackIsIncludedDependency = __webpack_require__(26505); const { - evaluateToString, - expressionIsUnsupported + toConstantDependency } = __webpack_require__(93998); -const { relative } = __webpack_require__(17139); -const { parseResource } = __webpack_require__(82186); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("enhanced-resolve/lib/Resolver")} Resolver */ /** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ - -class NodeStuffPlugin { - constructor(options) { - this.options = options; - } +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +class WebpackIsIncludedPlugin { /** - * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - const options = this.options; compiler.hooks.compilation.tap( - "NodeStuffPlugin", + "WebpackIsIncludedPlugin", (compilation, { normalModuleFactory }) => { - const handler = (parser, parserOptions) => { - if (parserOptions.node === false) return; - - let localOptions = options; - if (parserOptions.node) { - localOptions = { ...localOptions, ...parserOptions.node }; - } - - if (localOptions.global !== false) { - const withWarning = localOptions.global === "warn"; - parser.hooks.expression - .for("global") - .tap("NodeStuffPlugin", expr => { - const dep = new ConstDependency( - RuntimeGlobals.global, - expr.range, - [RuntimeGlobals.global] - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - - // TODO webpack 6 remove - if (withWarning) { - parser.state.module.addWarning( - new NodeStuffInWebError( - dep.loc, - "global", - "The global namespace object is Node.js feature and doesn't present in browser." - ) - ); - } - }); - } - - const setModuleConstant = (expressionName, fn, warning) => { - 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); - - // TODO webpack 6 remove - if (warning) { - parser.state.module.addWarning( - new NodeStuffInWebError(dep.loc, expressionName, warning) - ); - } - - return true; - }); - }; + compilation.dependencyFactories.set( + WebpackIsIncludedDependency, + new IgnoreErrorModuleFactory(normalModuleFactory) + ); + compilation.dependencyTemplates.set( + WebpackIsIncludedDependency, + new WebpackIsIncludedDependency.Template() + ); - const setConstant = (expressionName, value, warning) => - setModuleConstant(expressionName, () => value, warning); + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + const handler = parser => { + parser.hooks.call + .for("__webpack_is_included__") + .tap("WebpackIsIncludedPlugin", expr => { + if ( + expr.type !== "CallExpression" || + expr.arguments.length !== 1 || + expr.arguments[0].type === "SpreadElement" + ) + return; - const context = compiler.context; - if (localOptions.__filename) { - switch (localOptions.__filename) { - case "mock": - setConstant("__filename", "/index.js"); - break; - case "warn-mock": - setConstant( - "__filename", - "/index.js", - "The __filename is Node.js feature and doesn't present in browser." - ); - break; - case true: - setModuleConstant("__filename", module => - relative(compiler.inputFileSystem, context, module.resource) - ); - break; - } + const request = parser.evaluateExpression(expr.arguments[0]); - 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) { - switch (localOptions.__dirname) { - case "mock": - setConstant("__dirname", "/"); - break; - case "warn-mock": - setConstant( - "__dirname", - "/", - "The __dirname is Node.js feature and doesn't present in browser." - ); - break; - case true: - setModuleConstant("__dirname", module => - relative(compiler.inputFileSystem, context, module.context) - ); - break; - } + if (!request.isString()) return; - 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") + const dep = new WebpackIsIncludedDependency( + request.string, + expr.range + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return true; + }); + parser.hooks.typeof + .for("__webpack_is_included__") .tap( - "NodeStuffPlugin", - expressionIsUnsupported( - parser, - "require.extensions is not supported by webpack. Use a loader instead." - ) + "WebpackIsIncludedPlugin", + toConstantDependency(parser, JSON.stringify("function")) ); }; - normalModuleFactory.hooks.parser .for("javascript/auto") - .tap("NodeStuffPlugin", handler); + .tap("WebpackIsIncludedPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") - .tap("NodeStuffPlugin", handler); + .tap("WebpackIsIncludedPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("WebpackIsIncludedPlugin", handler); } ); } } -module.exports = NodeStuffPlugin; +module.exports = WebpackIsIncludedPlugin; /***/ }), -/***/ 39: +/***/ 88422: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -55627,2531 +57052,1521 @@ module.exports = NodeStuffPlugin; -const parseJson = __webpack_require__(15235); -const { getContext, runLoaders } = __webpack_require__(68318); -const querystring = __webpack_require__(63477); -const { HookMap, SyncHook, AsyncSeriesBailHook } = __webpack_require__(41242); -const { - CachedSource, - OriginalSource, - RawSource, - SourceMapSource -} = __webpack_require__(51255); -const Compilation = __webpack_require__(85720); -const HookWebpackError = __webpack_require__(11351); -const Module = __webpack_require__(73208); -const ModuleBuildError = __webpack_require__(21305); -const ModuleError = __webpack_require__(23744); -const ModuleGraphConnection = __webpack_require__(40639); -const ModuleParseError = __webpack_require__(58443); -const ModuleWarning = __webpack_require__(11234); -const RuntimeGlobals = __webpack_require__(16475); -const UnhandledSchemeError = __webpack_require__(68099); -const WebpackError = __webpack_require__(53799); -const formatLocation = __webpack_require__(16734); -const LazySet = __webpack_require__(38938); -const { isSubset } = __webpack_require__(93347); -const { getScheme } = __webpack_require__(54500); -const { - compareLocations, - concatComparators, - compareSelect, - keepOriginalOrder -} = __webpack_require__(29579); -const createHash = __webpack_require__(49835); -const { createFakeHook } = __webpack_require__(64518); -const { join } = __webpack_require__(17139); -const { - contextify, - absolutify, - makePathsRelative -} = __webpack_require__(82186); -const makeSerializable = __webpack_require__(33032); -const memoize = __webpack_require__(78676); +const OptionsApply = __webpack_require__(81426); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/LoaderContext").NormalModuleLoaderContext} NormalModuleLoaderContext */ -/** @typedef {import("../declarations/WebpackOptions").Mode} Mode */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./Generator")} Generator */ -/** @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("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */ -/** @typedef {import("./Parser")} Parser */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./logging/Logger").Logger} WebpackLogger */ -/** @typedef {import("./util/Hash")} Hash */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +const AssetModulesPlugin = __webpack_require__(16109); +const JavascriptModulesPlugin = __webpack_require__(89464); +const JsonModulesPlugin = __webpack_require__(86770); -/** - * @typedef {Object} SourceMap - * @property {number} version - * @property {string[]} sources - * @property {string} mappings - * @property {string=} file - * @property {string=} sourceRoot - * @property {string[]=} sourcesContent - * @property {string[]=} names - */ +const ChunkPrefetchPreloadPlugin = __webpack_require__(33895); -const getInvalidDependenciesModuleWarning = memoize(() => - __webpack_require__(68257) -); -const getValidate = memoize(() => (__webpack_require__(38476).validate)); +const EntryOptionPlugin = __webpack_require__(9909); +const RecordIdsPlugin = __webpack_require__(11094); -const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/; +const RuntimePlugin = __webpack_require__(2307); -/** - * @typedef {Object} LoaderItem - * @property {string} loader - * @property {any} options - * @property {string?} ident - * @property {string?} type - */ +const APIPlugin = __webpack_require__(74315); +const CompatibilityPlugin = __webpack_require__(94258); +const ConstPlugin = __webpack_require__(11146); +const ExportsInfoApiPlugin = __webpack_require__(7145); +const WebpackIsIncludedPlugin = __webpack_require__(97017); -/** - * @param {string} context absolute context path - * @param {string} source a source path - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} new source path - */ -const contextifySourceUrl = (context, source, associatedObjectForCache) => { - if (source.startsWith("webpack://")) return source; - return `webpack://${makePathsRelative( - context, - source, - associatedObjectForCache - )}`; -}; +const TemplatedPathPlugin = __webpack_require__(80734); +const UseStrictPlugin = __webpack_require__(36803); +const WarnCaseSensitiveModulesPlugin = __webpack_require__(56504); -/** - * @param {string} context absolute context path - * @param {SourceMap} sourceMap a source map - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {SourceMap} new source map - */ -const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => { - if (!Array.isArray(sourceMap.sources)) return sourceMap; - const { sourceRoot } = sourceMap; - /** @type {function(string): string} */ - const mapper = !sourceRoot - ? source => source - : sourceRoot.endsWith("/") - ? source => - source.startsWith("/") - ? `${sourceRoot.slice(0, -1)}${source}` - : `${sourceRoot}${source}` - : source => - source.startsWith("/") - ? `${sourceRoot}${source}` - : `${sourceRoot}/${source}`; - const newSources = sourceMap.sources.map(source => - contextifySourceUrl(context, mapper(source), associatedObjectForCache) - ); - return { - ...sourceMap, - file: "x", - sourceRoot: undefined, - sources: newSources - }; -}; +const DataUriPlugin = __webpack_require__(64820); +const FileUriPlugin = __webpack_require__(57637); -/** - * @param {string | Buffer} input the input - * @returns {string} the converted string - */ -const asString = input => { - if (Buffer.isBuffer(input)) { - return input.toString("utf-8"); - } - return input; -}; +const ResolverCachePlugin = __webpack_require__(97347); -/** - * @param {string | Buffer} input the input - * @returns {Buffer} the converted buffer - */ -const asBuffer = input => { - if (!Buffer.isBuffer(input)) { - return Buffer.from(input, "utf-8"); - } - return input; -}; +const CommonJsPlugin = __webpack_require__(32406); +const HarmonyModulesPlugin = __webpack_require__(39029); +const ImportMetaPlugin = __webpack_require__(17228); +const ImportPlugin = __webpack_require__(41293); +const LoaderPlugin = __webpack_require__(24721); +const RequireContextPlugin = __webpack_require__(2928); +const RequireEnsurePlugin = __webpack_require__(8434); +const RequireIncludePlugin = __webpack_require__(37378); +const SystemPlugin = __webpack_require__(97981); +const URLPlugin = __webpack_require__(14412); +const WorkerPlugin = __webpack_require__(82509); -class NonErrorEmittedError extends WebpackError { - constructor(error) { - super(); +const InferAsyncModulesPlugin = __webpack_require__(59498); - this.name = "NonErrorEmittedError"; - this.message = "(Emitted value instead of an instance of Error) " + error; - } -} +const JavascriptMetaInfoPlugin = __webpack_require__(52329); +const DefaultStatsFactoryPlugin = __webpack_require__(71760); +const DefaultStatsPresetPlugin = __webpack_require__(55442); +const DefaultStatsPrinterPlugin = __webpack_require__(58692); -makeSerializable( - NonErrorEmittedError, - "webpack/lib/NormalModule", - "NonErrorEmittedError" -); +const { cleverMerge } = __webpack_require__(60839); -/** - * @typedef {Object} NormalModuleCompilationHooks - * @property {SyncHook<[object, NormalModule]>} loader - * @property {SyncHook<[LoaderItem[], NormalModule, object]>} beforeLoaders - * @property {SyncHook<[NormalModule]>} beforeParse - * @property {SyncHook<[NormalModule]>} beforeSnapshot - * @property {HookMap>} readResourceForScheme - * @property {HookMap>} readResource - * @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild - */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./Compiler")} Compiler */ -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); +class WebpackOptionsApply extends OptionsApply { + constructor() { + super(); + } -class NormalModule extends Module { /** - * @param {Compilation} compilation the compilation - * @returns {NormalModuleCompilationHooks} the attached hooks + * @param {WebpackOptions} options options object + * @param {Compiler} compiler compiler object + * @returns {WebpackOptions} options object */ - static getCompilationHooks(compilation) { - if (!(compilation instanceof Compilation)) { - throw new TypeError( - "The 'compilation' argument must be an instance of Compilation" + process(options, compiler) { + compiler.outputPath = options.output.path; + compiler.recordsInputPath = options.recordsInputPath || null; + compiler.recordsOutputPath = options.recordsOutputPath || null; + compiler.name = options.name; + + if (options.externals) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = __webpack_require__(6652); + new ExternalsPlugin(options.externalsType, options.externals).apply( + compiler ); } - let hooks = compilationHooksMap.get(compilation); - if (hooks === undefined) { - hooks = { - loader: new SyncHook(["loaderContext", "module"]), - beforeLoaders: new SyncHook(["loaders", "module", "loaderContext"]), - beforeParse: new SyncHook(["module"]), - beforeSnapshot: new SyncHook(["module"]), - // TODO webpack 6 deprecate - readResourceForScheme: new HookMap(scheme => { - const hook = hooks.readResource.for(scheme); - return createFakeHook( - /** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer>} */ ({ - tap: (options, fn) => - hook.tap(options, loaderContext => - fn(loaderContext.resource, loaderContext._module) - ), - tapAsync: (options, fn) => - hook.tapAsync(options, (loaderContext, callback) => - fn(loaderContext.resource, loaderContext._module, callback) - ), - tapPromise: (options, fn) => - hook.tapPromise(options, loaderContext => - fn(loaderContext.resource, loaderContext._module) - ) - }) - ); - }), - readResource: new HookMap( - () => new AsyncSeriesBailHook(["loaderContext"]) - ), - needBuild: new AsyncSeriesBailHook(["module", "context"]) - }; - compilationHooksMap.set(compilation, hooks); - } - return hooks; - } - /** - * @param {Object} options options object - * @param {string=} options.layer an optional layer in which the module is - * @param {string} options.type module type - * @param {string} options.request request string - * @param {string} options.userRequest request intended by user (without loaders from config) - * @param {string} options.rawRequest request without resolving - * @param {LoaderItem[]} options.loaders list of loaders - * @param {string} options.resource path + query of the real resource - * @param {Record=} options.resourceResolveData resource resolve data - * @param {string} options.context context directory for resolving - * @param {string | undefined} options.matchResource path + query of the matched resource (virtual) - * @param {Parser} options.parser the parser used - * @param {object} options.parserOptions the options of the parser used - * @param {Generator} options.generator the generator used - * @param {object} options.generatorOptions the options of the generator used - * @param {Object} options.resolveOptions options used for resolving requests from this module - */ - constructor({ - layer, - type, - request, - userRequest, - rawRequest, - loaders, - resource, - resourceResolveData, - context, - matchResource, - parser, - parserOptions, - generator, - generatorOptions, - resolveOptions - }) { - super(type, context || getContext(resource), layer); - - // Info from Factory - /** @type {string} */ - this.request = request; - /** @type {string} */ - this.userRequest = userRequest; - /** @type {string} */ - this.rawRequest = rawRequest; - /** @type {boolean} */ - this.binary = /^(asset|webassembly)\b/.test(type); - /** @type {Parser} */ - this.parser = parser; - this.parserOptions = parserOptions; - /** @type {Generator} */ - this.generator = generator; - this.generatorOptions = generatorOptions; - /** @type {string} */ - this.resource = resource; - this.resourceResolveData = resourceResolveData; - /** @type {string | undefined} */ - this.matchResource = matchResource; - /** @type {LoaderItem[]} */ - this.loaders = loaders; - if (resolveOptions !== undefined) { - // already declared in super class - this.resolveOptions = resolveOptions; + if (options.externalsPresets.node) { + const NodeTargetPlugin = __webpack_require__(17916); + new NodeTargetPlugin().apply(compiler); } - - // Info from Build - /** @type {(WebpackError | null)=} */ - this.error = null; - /** @private @type {Source=} */ - this._source = null; - /** @private @type {Map | undefined} **/ - this._sourceSizes = undefined; - /** @private @type {Set} */ - this._sourceTypes = undefined; - - // Cache - this._lastSuccessfulBuildMeta = {}; - this._forceBuild = true; - this._isEvaluatingSideEffects = false; - /** @type {WeakSet | undefined} */ - this._addedSideEffectsBailout = undefined; - } - - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - if (this.layer === null) { - if (this.type === "javascript/auto") { - return this.request; - } else { - return `${this.type}|${this.request}`; - } - } else { - return `${this.type}|${this.request}|${this.layer}`; + if (options.externalsPresets.electronMain) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ElectronTargetPlugin = __webpack_require__(32277); + new ElectronTargetPlugin("main").apply(compiler); + } + if (options.externalsPresets.electronPreload) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ElectronTargetPlugin = __webpack_require__(32277); + new ElectronTargetPlugin("preload").apply(compiler); + } + if (options.externalsPresets.electronRenderer) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ElectronTargetPlugin = __webpack_require__(32277); + new ElectronTargetPlugin("renderer").apply(compiler); + } + if ( + options.externalsPresets.electron && + !options.externalsPresets.electronMain && + !options.externalsPresets.electronPreload && + !options.externalsPresets.electronRenderer + ) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ElectronTargetPlugin = __webpack_require__(32277); + new ElectronTargetPlugin().apply(compiler); + } + if (options.externalsPresets.nwjs) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = __webpack_require__(6652); + new ExternalsPlugin("node-commonjs", "nw.gui").apply(compiler); + } + if (options.externalsPresets.webAsync) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = __webpack_require__(6652); + new ExternalsPlugin( + "import", + options.experiments.css + ? ({ request, dependencyType }, callback) => { + if (dependencyType === "url") { + if (/^(\/\/|https?:\/\/)/.test(request)) + return callback(null, `asset ${request}`); + } else if (dependencyType === "css-import") { + if (/^(\/\/|https?:\/\/)/.test(request)) + return callback(null, `css-import ${request}`); + } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) { + if (/^\.css(\?|$)/.test(request)) + return callback(null, `css-import ${request}`); + return callback(null, `import ${request}`); + } + callback(); + } + : /^(\/\/|https?:\/\/|std:)/ + ).apply(compiler); + } else if (options.externalsPresets.web) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const ExternalsPlugin = __webpack_require__(6652); + new ExternalsPlugin( + "module", + options.experiments.css + ? ({ request, dependencyType }, callback) => { + if (dependencyType === "url") { + if (/^(\/\/|https?:\/\/)/.test(request)) + return callback(null, `asset ${request}`); + } else if (dependencyType === "css-import") { + if (/^(\/\/|https?:\/\/)/.test(request)) + return callback(null, `css-import ${request}`); + } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) { + if (/^\.css(\?|$)/.test(request)) + return callback(null, `css-import ${request}`); + return callback(null, `module ${request}`); + } + callback(); + } + : /^(\/\/|https?:\/\/|std:)/ + ).apply(compiler); } - } - - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return requestShortener.shorten(this.userRequest); - } - - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - let ident = contextify( - options.context, - this.userRequest, - options.associatedObjectForCache - ); - if (this.layer) ident = `(${this.layer})/${ident}`; - return ident; - } - - /** - * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) - */ - nameForCondition() { - const resource = this.matchResource || this.resource; - const idx = resource.indexOf("?"); - if (idx >= 0) return resource.substr(0, idx); - return resource; - } - /** - * 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 {NormalModule} */ (module); - this.binary = m.binary; - this.request = m.request; - this.userRequest = m.userRequest; - this.rawRequest = m.rawRequest; - this.parser = m.parser; - this.parserOptions = m.parserOptions; - this.generator = m.generator; - this.generatorOptions = m.generatorOptions; - this.resource = m.resource; - this.resourceResolveData = m.resourceResolveData; - this.context = m.context; - this.matchResource = m.matchResource; - this.loaders = m.loaders; - } + new ChunkPrefetchPreloadPlugin().apply(compiler); - /** - * Assuming this module is in the cache. Remove internal references to allow freeing some memory. - */ - cleanupForCache() { - // Make sure to cache types and sizes before cleanup when this module has been built - // They are accessed by the stats and we don't want them to crash after cleanup - // TODO reconsider this for webpack 6 - if (this.buildInfo) { - if (this._sourceTypes === undefined) this.getSourceTypes(); - for (const type of this._sourceTypes) { - this.size(type); + if (typeof options.output.chunkFormat === "string") { + switch (options.output.chunkFormat) { + case "array-push": { + const ArrayPushCallbackChunkFormatPlugin = __webpack_require__(18535); + new ArrayPushCallbackChunkFormatPlugin().apply(compiler); + break; + } + case "commonjs": { + const CommonJsChunkFormatPlugin = __webpack_require__(84508); + new CommonJsChunkFormatPlugin().apply(compiler); + break; + } + case "module": { + const ModuleChunkFormatPlugin = __webpack_require__(68927); + new ModuleChunkFormatPlugin().apply(compiler); + break; + } + default: + throw new Error( + "Unsupported chunk format '" + options.output.chunkFormat + "'." + ); } } - super.cleanupForCache(); - this.parser = undefined; - this.parserOptions = undefined; - this.generator = undefined; - this.generatorOptions = undefined; - } - - /** - * Module should be unsafe cached. Get data that's needed for that. - * This data will be passed to restoreFromUnsafeCache later. - * @returns {object} cached data - */ - getUnsafeCacheData() { - const data = super.getUnsafeCacheData(); - data.parserOptions = this.parserOptions; - data.generatorOptions = this.generatorOptions; - return data; - } - restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { - this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); - } - - /** - * restore unsafe cache data - * @param {object} unsafeCacheData data from getUnsafeCacheData - * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching - */ - _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) { - super._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory); - this.parserOptions = unsafeCacheData.parserOptions; - this.parser = normalModuleFactory.getParser(this.type, this.parserOptions); - this.generatorOptions = unsafeCacheData.generatorOptions; - this.generator = normalModuleFactory.getGenerator( - this.type, - this.generatorOptions - ); - // we assume the generator behaves identically and keep cached sourceTypes/Sizes - } - - /** - * @param {string} context the compilation context - * @param {string} name the asset name - * @param {string} content the content - * @param {string | TODO} sourceMap an optional source map - * @param {Object=} associatedObjectForCache object for caching - * @returns {Source} the created source - */ - createSourceForAsset( - context, - name, - content, - sourceMap, - associatedObjectForCache - ) { - if (sourceMap) { - if ( - typeof sourceMap === "string" && - (this.useSourceMap || this.useSimpleSourceMap) - ) { - return new OriginalSource( - content, - contextifySourceUrl(context, sourceMap, associatedObjectForCache) - ); + if (options.output.enabledChunkLoadingTypes.length > 0) { + for (const type of options.output.enabledChunkLoadingTypes) { + const EnableChunkLoadingPlugin = __webpack_require__(61291); + new EnableChunkLoadingPlugin(type).apply(compiler); } + } - if (this.useSourceMap) { - return new SourceMapSource( - content, - name, - contextifySourceMap(context, sourceMap, associatedObjectForCache) - ); + if (options.output.enabledWasmLoadingTypes.length > 0) { + for (const type of options.output.enabledWasmLoadingTypes) { + const EnableWasmLoadingPlugin = __webpack_require__(78613); + new EnableWasmLoadingPlugin(type).apply(compiler); } } - return new RawSource(content); - } - - /** - * @param {ResolverWithOptions} resolver a resolver - * @param {WebpackOptions} options webpack options - * @param {Compilation} compilation the compilation - * @param {InputFileSystem} fs file system from reading - * @param {NormalModuleCompilationHooks} hooks the hooks - * @returns {NormalModuleLoaderContext} loader context - */ - _createLoaderContext(resolver, options, compilation, fs, hooks) { - const { requestShortener } = compilation.runtimeTemplate; - const getCurrentLoaderName = () => { - const currentLoader = this.getCurrentLoader(loaderContext); - if (!currentLoader) return "(not in loader scope)"; - return requestShortener.shorten(currentLoader.loader); - }; - const getResolveContext = () => { - return { - fileDependencies: { - add: d => loaderContext.addDependency(d) - }, - contextDependencies: { - add: d => loaderContext.addContextDependency(d) - }, - missingDependencies: { - add: d => loaderContext.addMissingDependency(d) - } - }; - }; - const getAbsolutify = memoize(() => - absolutify.bindCache(compilation.compiler.root) - ); - const getAbsolutifyInContext = memoize(() => - absolutify.bindContextCache(this.context, compilation.compiler.root) - ); - const getContextify = memoize(() => - contextify.bindCache(compilation.compiler.root) - ); - const getContextifyInContext = memoize(() => - contextify.bindContextCache(this.context, compilation.compiler.root) - ); - const utils = { - absolutify: (context, request) => { - return context === this.context - ? getAbsolutifyInContext()(request) - : getAbsolutify()(context, request); - }, - contextify: (context, request) => { - return context === this.context - ? getContextifyInContext()(request) - : getContextify()(context, request); - }, - createHash: type => { - return createHash(type || compilation.outputOptions.hashFunction); + if (options.output.enabledLibraryTypes.length > 0) { + for (const type of options.output.enabledLibraryTypes) { + const EnableLibraryPlugin = __webpack_require__(91452); + new EnableLibraryPlugin(type).apply(compiler); } - }; - const loaderContext = { - version: 2, - getOptions: schema => { - const loader = this.getCurrentLoader(loaderContext); + } - let { options } = loader; + if (options.output.pathinfo) { + const ModuleInfoHeaderPlugin = __webpack_require__(3454); + new ModuleInfoHeaderPlugin(options.output.pathinfo !== true).apply( + compiler + ); + } - if (typeof options === "string") { - if (options.substr(0, 1) === "{" && options.substr(-1) === "}") { - try { - options = parseJson(options); - } catch (e) { - throw new Error(`Cannot parse string options: ${e.message}`); - } - } else { - options = querystring.parse(options, "&", "=", { - maxKeys: 0 - }); - } - } + if (options.output.clean) { + const CleanPlugin = __webpack_require__(31085); + new CleanPlugin( + options.output.clean === true ? {} : options.output.clean + ).apply(compiler); + } - if (options === null || options === undefined) { - options = {}; - } + if (options.devtool) { + if (options.devtool.includes("source-map")) { + const hidden = options.devtool.includes("hidden"); + const inline = options.devtool.includes("inline"); + const evalWrapped = options.devtool.includes("eval"); + const cheap = options.devtool.includes("cheap"); + const moduleMaps = options.devtool.includes("module"); + const noSources = options.devtool.includes("nosources"); + const Plugin = evalWrapped + ? __webpack_require__(14790) + : __webpack_require__(63872); + new Plugin({ + filename: inline ? null : options.output.sourceMapFilename, + moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, + fallbackModuleFilenameTemplate: + options.output.devtoolFallbackModuleFilenameTemplate, + append: hidden ? false : undefined, + module: moduleMaps ? true : cheap ? false : true, + columns: cheap ? false : true, + noSources: noSources, + namespace: options.output.devtoolNamespace + }).apply(compiler); + } else if (options.devtool.includes("eval")) { + const EvalDevToolModulePlugin = __webpack_require__(65218); + new EvalDevToolModulePlugin({ + moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, + namespace: options.output.devtoolNamespace + }).apply(compiler); + } + } - if (schema) { - let name = "Loader"; - let baseDataPath = "options"; - let match; - if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) { - [, name, baseDataPath] = match; - } - getValidate()(schema, options, { - name, - baseDataPath - }); - } + new JavascriptModulesPlugin().apply(compiler); + new JsonModulesPlugin().apply(compiler); + new AssetModulesPlugin().apply(compiler); - return options; - }, - emitWarning: warning => { - if (!(warning instanceof Error)) { - warning = new NonErrorEmittedError(warning); - } - this.addWarning( - new ModuleWarning(warning, { - from: getCurrentLoaderName() - }) - ); - }, - emitError: error => { - if (!(error instanceof Error)) { - error = new NonErrorEmittedError(error); - } - this.addError( - new ModuleError(error, { - from: getCurrentLoaderName() - }) + if (!options.experiments.outputModule) { + if (options.output.module) { + throw new Error( + "'output.module: true' is only allowed when 'experiments.outputModule' is enabled" ); - }, - getLogger: name => { - const currentLoader = this.getCurrentLoader(loaderContext); - return compilation.getLogger(() => - [currentLoader && currentLoader.loader, name, this.identifier()] - .filter(Boolean) - .join("|") + } + if (options.output.enabledLibraryTypes.includes("module")) { + throw new Error( + "library type \"module\" is only allowed when 'experiments.outputModule' is enabled" ); - }, - resolve(context, request, callback) { - resolver.resolve({}, context, request, getResolveContext(), callback); - }, - getResolve(options) { - const child = options ? resolver.withOptions(options) : resolver; - return (context, request, callback) => { - if (callback) { - child.resolve({}, context, request, getResolveContext(), callback); - } else { - return new Promise((resolve, reject) => { - child.resolve( - {}, - context, - request, - getResolveContext(), - (err, result) => { - if (err) reject(err); - else resolve(result); - } - ); - }); - } - }; - }, - emitFile: (name, content, sourceMap, assetInfo) => { - if (!this.buildInfo.assets) { - this.buildInfo.assets = Object.create(null); - this.buildInfo.assetsInfo = new Map(); - } - this.buildInfo.assets[name] = this.createSourceForAsset( - options.context, - name, - content, - sourceMap, - compilation.compiler.root + } + if (options.externalsType === "module") { + throw new Error( + "'externalsType: \"module\"' is only allowed when 'experiments.outputModule' is enabled" ); - this.buildInfo.assetsInfo.set(name, assetInfo); - }, - addBuildDependency: dep => { - if (this.buildInfo.buildDependencies === undefined) { - this.buildInfo.buildDependencies = new LazySet(); - } - this.buildInfo.buildDependencies.add(dep); - }, - utils, - rootContext: options.context, - webpack: true, - sourceMap: !!this.useSourceMap, - mode: options.mode || "production", - _module: this, - _compilation: compilation, - _compiler: compilation.compiler, - fs: fs - }; - - Object.assign(loaderContext, options.loader); - - hooks.loader.call(loaderContext, this); - - return loaderContext; - } - - getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) { - if ( - this.loaders && - this.loaders.length && - index < this.loaders.length && - index >= 0 && - this.loaders[index] - ) { - return this.loaders[index]; + } } - return null; - } - /** - * @param {string} context the compilation context - * @param {string | Buffer} content the content - * @param {string | TODO} sourceMap an optional source map - * @param {Object=} associatedObjectForCache object for caching - * @returns {Source} the created source - */ - createSource(context, content, sourceMap, associatedObjectForCache) { - if (Buffer.isBuffer(content)) { - return new RawSource(content); + if (options.experiments.syncWebAssembly) { + const WebAssemblyModulesPlugin = __webpack_require__(53639); + new WebAssemblyModulesPlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); } - // if there is no identifier return raw source - if (!this.identifier) { - return new RawSource(content); + if (options.experiments.asyncWebAssembly) { + const AsyncWebAssemblyModulesPlugin = __webpack_require__(7538); + new AsyncWebAssemblyModulesPlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); } - // from here on we assume we have an identifier - const identifier = this.identifier(); + if (options.experiments.css) { + const CssModulesPlugin = __webpack_require__(47283); + new CssModulesPlugin(options.experiments.css).apply(compiler); + } - if (this.useSourceMap && sourceMap) { - return new SourceMapSource( - content, - contextifySourceUrl(context, identifier, associatedObjectForCache), - contextifySourceMap(context, sourceMap, associatedObjectForCache) - ); + if (options.experiments.lazyCompilation) { + const LazyCompilationPlugin = __webpack_require__(79040); + const lazyOptions = + typeof options.experiments.lazyCompilation === "object" + ? options.experiments.lazyCompilation + : null; + new LazyCompilationPlugin({ + backend: + typeof lazyOptions.backend === "function" + ? lazyOptions.backend + : __webpack_require__(17781)({ + ...lazyOptions.backend, + client: + (lazyOptions.backend && lazyOptions.backend.client) || + options.externalsPresets.node ? __webpack_require__.ab + "lazy-compilation-node.js" : __webpack_require__.ab + "lazy-compilation-web.js" + }), + entries: !lazyOptions || lazyOptions.entries !== false, + imports: !lazyOptions || lazyOptions.imports !== false, + test: (lazyOptions && lazyOptions.test) || undefined + }).apply(compiler); } - if (this.useSourceMap || this.useSimpleSourceMap) { - return new OriginalSource( - content, - contextifySourceUrl(context, identifier, associatedObjectForCache) - ); + if (options.experiments.buildHttp) { + const HttpUriPlugin = __webpack_require__(42110); + const httpOptions = options.experiments.buildHttp; + new HttpUriPlugin(httpOptions).apply(compiler); } - return new RawSource(content); - } + new EntryOptionPlugin().apply(compiler); + compiler.hooks.entryOption.call(options.context, options.entry); - /** - * @param {WebpackOptions} options webpack options - * @param {Compilation} compilation the compilation - * @param {ResolverWithOptions} resolver the resolver - * @param {InputFileSystem} fs the file system - * @param {NormalModuleCompilationHooks} hooks the hooks - * @param {function((WebpackError | null)=): void} callback callback function - * @returns {void} - */ - _doBuild(options, compilation, resolver, fs, hooks, callback) { - const loaderContext = this._createLoaderContext( - resolver, - options, - compilation, - fs, - hooks - ); + new RuntimePlugin().apply(compiler); - const processResult = (err, result) => { - if (err) { - if (!(err instanceof Error)) { - err = new NonErrorEmittedError(err); - } - const currentLoader = this.getCurrentLoader(loaderContext); - const error = new ModuleBuildError(err, { - from: - currentLoader && - compilation.runtimeTemplate.requestShortener.shorten( - currentLoader.loader - ) - }); - return callback(error); - } + new InferAsyncModulesPlugin().apply(compiler); - const source = result[0]; - const sourceMap = result.length >= 1 ? result[1] : null; - const extraInfo = result.length >= 2 ? result[2] : null; + new DataUriPlugin().apply(compiler); + new FileUriPlugin().apply(compiler); - if (!Buffer.isBuffer(source) && typeof source !== "string") { - const currentLoader = this.getCurrentLoader(loaderContext, 0); - const err = new Error( - `Final loader (${ - currentLoader - ? compilation.runtimeTemplate.requestShortener.shorten( - currentLoader.loader - ) - : "unknown" - }) didn't return a Buffer or String` - ); - const error = new ModuleBuildError(err); - return callback(error); - } + new CompatibilityPlugin().apply(compiler); + new HarmonyModulesPlugin({ + topLevelAwait: options.experiments.topLevelAwait + }).apply(compiler); + if (options.amd !== false) { + const AMDPlugin = __webpack_require__(50067); + const RequireJsStuffPlugin = __webpack_require__(88846); + new AMDPlugin(options.amd || {}).apply(compiler); + new RequireJsStuffPlugin().apply(compiler); + } + new CommonJsPlugin().apply(compiler); + new LoaderPlugin({}).apply(compiler); + if (options.node !== false) { + const NodeStuffPlugin = __webpack_require__(95287); + new NodeStuffPlugin(options.node).apply(compiler); + } + new APIPlugin().apply(compiler); + new ExportsInfoApiPlugin().apply(compiler); + new WebpackIsIncludedPlugin().apply(compiler); + new ConstPlugin().apply(compiler); + new UseStrictPlugin().apply(compiler); + new RequireIncludePlugin().apply(compiler); + new RequireEnsurePlugin().apply(compiler); + new RequireContextPlugin().apply(compiler); + new ImportPlugin().apply(compiler); + new SystemPlugin().apply(compiler); + new ImportMetaPlugin().apply(compiler); + new URLPlugin().apply(compiler); + new WorkerPlugin( + options.output.workerChunkLoading, + options.output.workerWasmLoading, + options.output.module + ).apply(compiler); - this._source = this.createSource( - options.context, - this.binary ? asBuffer(source) : asString(source), - sourceMap, - compilation.compiler.root - ); - if (this._sourceSizes !== undefined) this._sourceSizes.clear(); - this._ast = - typeof extraInfo === "object" && - extraInfo !== null && - extraInfo.webpackAST !== undefined - ? extraInfo.webpackAST - : null; - return callback(); - }; + new DefaultStatsFactoryPlugin().apply(compiler); + new DefaultStatsPresetPlugin().apply(compiler); + new DefaultStatsPrinterPlugin().apply(compiler); - this.buildInfo.fileDependencies = new LazySet(); - this.buildInfo.contextDependencies = new LazySet(); - this.buildInfo.missingDependencies = new LazySet(); - this.buildInfo.cacheable = true; + new JavascriptMetaInfoPlugin().apply(compiler); - try { - hooks.beforeLoaders.call(this.loaders, this, loaderContext); - } catch (err) { - processResult(err); - return; + if (typeof options.mode !== "string") { + const WarnNoModeSetPlugin = __webpack_require__(25295); + new WarnNoModeSetPlugin().apply(compiler); } - if (this.loaders.length > 0) { - this.buildInfo.buildDependencies = new LazySet(); + const EnsureChunkConditionsPlugin = __webpack_require__(96260); + new EnsureChunkConditionsPlugin().apply(compiler); + if (options.optimization.removeAvailableModules) { + const RemoveParentModulesPlugin = __webpack_require__(7081); + new RemoveParentModulesPlugin().apply(compiler); } - - runLoaders( - { - resource: this.resource, - loaders: this.loaders, - context: loaderContext, - processResource: (loaderContext, resourcePath, callback) => { - const resource = loaderContext.resource; - const scheme = getScheme(resource); - hooks.readResource - .for(scheme) - .callAsync(loaderContext, (err, result) => { - if (err) return callback(err); - if (typeof result !== "string" && !result) { - return callback(new UnhandledSchemeError(scheme, resource)); - } - return callback(null, result); - }); + if (options.optimization.removeEmptyChunks) { + const RemoveEmptyChunksPlugin = __webpack_require__(84760); + new RemoveEmptyChunksPlugin().apply(compiler); + } + if (options.optimization.mergeDuplicateChunks) { + const MergeDuplicateChunksPlugin = __webpack_require__(85067); + new MergeDuplicateChunksPlugin().apply(compiler); + } + if (options.optimization.flagIncludedChunks) { + const FlagIncludedChunksPlugin = __webpack_require__(50089); + new FlagIncludedChunksPlugin().apply(compiler); + } + if (options.optimization.sideEffects) { + const SideEffectsFlagPlugin = __webpack_require__(84800); + new SideEffectsFlagPlugin( + options.optimization.sideEffects === true + ).apply(compiler); + } + if (options.optimization.providedExports) { + const FlagDependencyExportsPlugin = __webpack_require__(84506); + new FlagDependencyExportsPlugin().apply(compiler); + } + if (options.optimization.usedExports) { + const FlagDependencyUsagePlugin = __webpack_require__(58812); + new FlagDependencyUsagePlugin( + options.optimization.usedExports === "global" + ).apply(compiler); + } + if (options.optimization.innerGraph) { + const InnerGraphPlugin = __webpack_require__(28758); + new InnerGraphPlugin().apply(compiler); + } + if (options.optimization.mangleExports) { + const MangleExportsPlugin = __webpack_require__(27868); + new MangleExportsPlugin( + options.optimization.mangleExports !== "size" + ).apply(compiler); + } + if (options.optimization.concatenateModules) { + const ModuleConcatenationPlugin = __webpack_require__(74844); + new ModuleConcatenationPlugin().apply(compiler); + } + if (options.optimization.splitChunks) { + const SplitChunksPlugin = __webpack_require__(21478); + new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler); + } + if (options.optimization.runtimeChunk) { + const RuntimeChunkPlugin = __webpack_require__(2837); + new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler); + } + if (!options.optimization.emitOnErrors) { + const NoEmitOnErrorsPlugin = __webpack_require__(50169); + new NoEmitOnErrorsPlugin().apply(compiler); + } + if (options.optimization.realContentHash) { + const RealContentHashPlugin = __webpack_require__(46043); + new RealContentHashPlugin({ + hashFunction: options.output.hashFunction, + hashDigest: options.output.hashDigest + }).apply(compiler); + } + if (options.optimization.checkWasmTypes) { + const WasmFinalizeExportsPlugin = __webpack_require__(19810); + new WasmFinalizeExportsPlugin().apply(compiler); + } + const moduleIds = options.optimization.moduleIds; + if (moduleIds) { + switch (moduleIds) { + case "natural": { + const NaturalModuleIdsPlugin = __webpack_require__(83366); + new NaturalModuleIdsPlugin().apply(compiler); + break; } - }, - (err, result) => { - // Cleanup loaderContext to avoid leaking memory in ICs - loaderContext._compilation = - loaderContext._compiler = - loaderContext._module = - loaderContext.fs = - undefined; - - if (!result) { - this.buildInfo.cacheable = false; - return processResult( - err || new Error("No result from loader-runner processing"), - null + case "named": { + const NamedModuleIdsPlugin = __webpack_require__(24339); + new NamedModuleIdsPlugin().apply(compiler); + break; + } + case "hashed": { + const WarnDeprecatedOptionPlugin = __webpack_require__(76537); + const HashedModuleIdsPlugin = __webpack_require__(21825); + new WarnDeprecatedOptionPlugin( + "optimization.moduleIds", + "hashed", + "deterministic" + ).apply(compiler); + new HashedModuleIdsPlugin({ + hashFunction: options.output.hashFunction + }).apply(compiler); + break; + } + case "deterministic": { + const DeterministicModuleIdsPlugin = __webpack_require__(76692); + new DeterministicModuleIdsPlugin().apply(compiler); + break; + } + case "size": { + const OccurrenceModuleIdsPlugin = __webpack_require__(35371); + new OccurrenceModuleIdsPlugin({ + prioritiseInitial: true + }).apply(compiler); + break; + } + default: + throw new Error( + `webpack bug: moduleIds: ${moduleIds} is not implemented` ); + } + } + const chunkIds = options.optimization.chunkIds; + if (chunkIds) { + switch (chunkIds) { + case "natural": { + const NaturalChunkIdsPlugin = __webpack_require__(86221); + new NaturalChunkIdsPlugin().apply(compiler); + break; } - this.buildInfo.fileDependencies.addAll(result.fileDependencies); - this.buildInfo.contextDependencies.addAll(result.contextDependencies); - this.buildInfo.missingDependencies.addAll(result.missingDependencies); - for (const loader of this.loaders) { - this.buildInfo.buildDependencies.add(loader.loader); + case "named": { + const NamedChunkIdsPlugin = __webpack_require__(6454); + new NamedChunkIdsPlugin().apply(compiler); + break; } - this.buildInfo.cacheable = this.buildInfo.cacheable && result.cacheable; - processResult(err, result.result); + case "deterministic": { + const DeterministicChunkIdsPlugin = __webpack_require__(8747); + new DeterministicChunkIdsPlugin().apply(compiler); + break; + } + case "size": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const OccurrenceChunkIdsPlugin = __webpack_require__(51020); + new OccurrenceChunkIdsPlugin({ + prioritiseInitial: true + }).apply(compiler); + break; + } + case "total-size": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const OccurrenceChunkIdsPlugin = __webpack_require__(51020); + new OccurrenceChunkIdsPlugin({ + prioritiseInitial: false + }).apply(compiler); + break; + } + default: + throw new Error( + `webpack bug: chunkIds: ${chunkIds} is not implemented` + ); } - ); - } - - /** - * @param {WebpackError} error the error - * @returns {void} - */ - markModuleAsErrored(error) { - // Restore build meta from successful build to keep importing state - this.buildMeta = { ...this._lastSuccessfulBuildMeta }; - this.error = error; - this.addError(error); - } - - applyNoParseRule(rule, content) { - // must start with "rule" if rule is a string - if (typeof rule === "string") { - return content.startsWith(rule); } - - if (typeof rule === "function") { - return rule(content); + if (options.optimization.nodeEnv) { + const DefinePlugin = __webpack_require__(79065); + new DefinePlugin({ + "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv) + }).apply(compiler); } - // we assume rule is a regexp - return rule.test(content); - } - - // check if module should not be parsed - // returns "true" if the module should !not! be parsed - // returns "false" if the module !must! be parsed - shouldPreventParsing(noParseRule, request) { - // if no noParseRule exists, return false - // the module !must! be parsed. - if (!noParseRule) { - return false; + if (options.optimization.minimize) { + for (const minimizer of options.optimization.minimizer) { + if (typeof minimizer === "function") { + minimizer.call(compiler, compiler); + } else if (minimizer !== "...") { + minimizer.apply(compiler); + } + } } - // we only have one rule to check - if (!Array.isArray(noParseRule)) { - // returns "true" if the module is !not! to be parsed - return this.applyNoParseRule(noParseRule, request); + if (options.performance) { + const SizeLimitsPlugin = __webpack_require__(32557); + new SizeLimitsPlugin(options.performance).apply(compiler); } - for (let i = 0; i < noParseRule.length; i++) { - const rule = noParseRule[i]; - // early exit on first truthy match - // this module is !not! to be parsed - if (this.applyNoParseRule(rule, request)) { - return true; - } - } - // no match found, so this module !should! be parsed - return false; - } + new TemplatedPathPlugin().apply(compiler); - _initBuildHash(compilation) { - const hash = createHash(compilation.outputOptions.hashFunction); - if (this._source) { - hash.update("source"); - this._source.updateHash(hash); - } - hash.update("meta"); - hash.update(JSON.stringify(this.buildMeta)); - this.buildInfo.hash = /** @type {string} */ (hash.digest("hex")); - } + new RecordIdsPlugin({ + portableIds: options.optimization.portableRecords + }).apply(compiler); - /** - * @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._forceBuild = false; - this._source = null; - if (this._sourceSizes !== undefined) this._sourceSizes.clear(); - this._sourceTypes = undefined; - this._ast = null; - this.error = null; - this.clearWarningsAndErrors(); - this.clearDependenciesAndBlocks(); - this.buildMeta = {}; - this.buildInfo = { - cacheable: false, - parsed: true, - fileDependencies: undefined, - contextDependencies: undefined, - missingDependencies: undefined, - buildDependencies: undefined, - valueDependencies: undefined, - hash: undefined, - assets: undefined, - assetsInfo: undefined - }; - - const startTime = compilation.compiler.fsStartTime || Date.now(); - - const hooks = NormalModule.getCompilationHooks(compilation); - - return this._doBuild(options, compilation, resolver, fs, hooks, err => { - // if we have an error mark module as failed and exit - if (err) { - this.markModuleAsErrored(err); - this._initBuildHash(compilation); - return callback(); - } - - const handleParseError = e => { - const source = this._source.source(); - const loaders = this.loaders.map(item => - contextify(options.context, item.loader, compilation.compiler.root) - ); - const error = new ModuleParseError(source, e, loaders, this.type); - this.markModuleAsErrored(error); - this._initBuildHash(compilation); - return callback(); - }; - - const handleParseResult = result => { - this.dependencies.sort( - concatComparators( - compareSelect(a => a.loc, compareLocations), - keepOriginalOrder(this.dependencies) - ) - ); - this._initBuildHash(compilation); - this._lastSuccessfulBuildMeta = this.buildMeta; - return handleBuildDone(); - }; + new WarnCaseSensitiveModulesPlugin().apply(compiler); - const handleBuildDone = () => { - try { - hooks.beforeSnapshot.call(this); - } catch (err) { - this.markModuleAsErrored(err); - return callback(); - } + const AddManagedPathsPlugin = __webpack_require__(47942); + new AddManagedPathsPlugin( + options.snapshot.managedPaths, + options.snapshot.immutablePaths + ).apply(compiler); - const snapshotOptions = compilation.options.snapshot.module; - if (!this.buildInfo.cacheable || !snapshotOptions) { - return callback(); - } - // add warning for all non-absolute paths in fileDependencies, etc - // This makes it easier to find problems with watching and/or caching - let nonAbsoluteDependencies = undefined; - const checkDependencies = deps => { - for (const dep of deps) { - if (!ABSOLUTE_PATH_REGEX.test(dep)) { - if (nonAbsoluteDependencies === undefined) - nonAbsoluteDependencies = new Set(); - nonAbsoluteDependencies.add(dep); - deps.delete(dep); - try { - const depWithoutGlob = dep.replace(/[\\/]?\*.*$/, ""); - const absolute = join( - compilation.fileSystemInfo.fs, - this.context, - depWithoutGlob - ); - if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) { - (depWithoutGlob !== dep - ? this.buildInfo.contextDependencies - : deps - ).add(absolute); - } - } catch (e) { - // ignore - } + if (options.cache && typeof options.cache === "object") { + const cacheOptions = options.cache; + switch (cacheOptions.type) { + case "memory": { + if (isFinite(cacheOptions.maxGenerations)) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const MemoryWithGcCachePlugin = __webpack_require__(99334); + new MemoryWithGcCachePlugin({ + maxGenerations: cacheOptions.maxGenerations + }).apply(compiler); + } else { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const MemoryCachePlugin = __webpack_require__(52539); + new MemoryCachePlugin().apply(compiler); + } + if (cacheOptions.cacheUnaffected) { + if (!options.experiments.cacheUnaffected) { + throw new Error( + "'cache.cacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled" + ); } + compiler.moduleMemCaches = new Map(); } - }; - checkDependencies(this.buildInfo.fileDependencies); - checkDependencies(this.buildInfo.missingDependencies); - checkDependencies(this.buildInfo.contextDependencies); - if (nonAbsoluteDependencies !== undefined) { - const InvalidDependenciesModuleWarning = - getInvalidDependenciesModuleWarning(); - this.addWarning( - new InvalidDependenciesModuleWarning(this, nonAbsoluteDependencies) - ); + break; } - // convert file/context/missingDependencies into filesystem snapshot - compilation.fileSystemInfo.createSnapshot( - startTime, - this.buildInfo.fileDependencies, - this.buildInfo.contextDependencies, - this.buildInfo.missingDependencies, - snapshotOptions, - (err, snapshot) => { - if (err) { - this.markModuleAsErrored(err); - return; + case "filesystem": { + const AddBuildDependenciesPlugin = __webpack_require__(28034); + for (const key in cacheOptions.buildDependencies) { + const list = cacheOptions.buildDependencies[key]; + new AddBuildDependenciesPlugin(list).apply(compiler); + } + if (!isFinite(cacheOptions.maxMemoryGenerations)) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const MemoryCachePlugin = __webpack_require__(52539); + new MemoryCachePlugin().apply(compiler); + } else if (cacheOptions.maxMemoryGenerations !== 0) { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const MemoryWithGcCachePlugin = __webpack_require__(99334); + new MemoryWithGcCachePlugin({ + maxGenerations: cacheOptions.maxMemoryGenerations + }).apply(compiler); + } + if (cacheOptions.memoryCacheUnaffected) { + if (!options.experiments.cacheUnaffected) { + throw new Error( + "'cache.memoryCacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled" + ); } - this.buildInfo.fileDependencies = undefined; - this.buildInfo.contextDependencies = undefined; - this.buildInfo.missingDependencies = undefined; - this.buildInfo.snapshot = snapshot; - return callback(); + compiler.moduleMemCaches = new Map(); } - ); - }; - - try { - hooks.beforeParse.call(this); - } catch (err) { - this.markModuleAsErrored(err); - this._initBuildHash(compilation); - return callback(); + switch (cacheOptions.store) { + case "pack": { + const IdleFileCachePlugin = __webpack_require__(71985); + const PackFileCacheStrategy = __webpack_require__(86180); + new IdleFileCachePlugin( + new PackFileCacheStrategy({ + compiler, + fs: compiler.intermediateFileSystem, + context: options.context, + cacheLocation: cacheOptions.cacheLocation, + version: cacheOptions.version, + logger: compiler.getInfrastructureLogger( + "webpack.cache.PackFileCacheStrategy" + ), + snapshot: options.snapshot, + maxAge: cacheOptions.maxAge, + profile: cacheOptions.profile, + allowCollectingMemory: cacheOptions.allowCollectingMemory, + compression: cacheOptions.compression + }), + cacheOptions.idleTimeout, + cacheOptions.idleTimeoutForInitialStore, + cacheOptions.idleTimeoutAfterLargeChanges + ).apply(compiler); + break; + } + default: + throw new Error("Unhandled value for cache.store"); + } + break; + } + default: + // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339) + throw new Error(`Unknown cache type ${cacheOptions.type}`); } + } + new ResolverCachePlugin().apply(compiler); - // check if this module should !not! be parsed. - // if so, exit here; - const noParseRule = options.module && options.module.noParse; - if (this.shouldPreventParsing(noParseRule, this.request)) { - // We assume that we need module and exports - this.buildInfo.parsed = false; - this._initBuildHash(compilation); - return handleBuildDone(); - } + if (options.ignoreWarnings && options.ignoreWarnings.length > 0) { + const IgnoreWarningsPlugin = __webpack_require__(7373); + new IgnoreWarningsPlugin(options.ignoreWarnings).apply(compiler); + } - let result; - try { - const source = this._source.source(); - result = this.parser.parse(this._ast || source, { - source, - current: this, - module: this, - compilation: compilation, - options: options - }); - } catch (e) { - handleParseError(e); - return; - } - handleParseResult(result); - }); + compiler.hooks.afterPlugins.call(compiler); + if (!compiler.inputFileSystem) { + throw new Error("No input filesystem provided"); + } + compiler.resolverFactory.hooks.resolveOptions + .for("normal") + .tap("WebpackOptionsApply", resolveOptions => { + resolveOptions = cleverMerge(options.resolve, resolveOptions); + resolveOptions.fileSystem = compiler.inputFileSystem; + return resolveOptions; + }); + compiler.resolverFactory.hooks.resolveOptions + .for("context") + .tap("WebpackOptionsApply", resolveOptions => { + resolveOptions = cleverMerge(options.resolve, resolveOptions); + resolveOptions.fileSystem = compiler.inputFileSystem; + resolveOptions.resolveToContext = true; + return resolveOptions; + }); + compiler.resolverFactory.hooks.resolveOptions + .for("loader") + .tap("WebpackOptionsApply", resolveOptions => { + resolveOptions = cleverMerge(options.resolveLoader, resolveOptions); + resolveOptions.fileSystem = compiler.inputFileSystem; + return resolveOptions; + }); + compiler.hooks.afterResolvers.call(compiler); + return options; } +} - /** - * @param {ConcatenationBailoutReasonContext} context context - * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated - */ - getConcatenationBailoutReason(context) { - return this.generator.getConcatenationBailoutReason(this, context); +module.exports = WebpackOptionsApply; + + +/***/ }), + +/***/ 14452: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { applyWebpackOptionsDefaults } = __webpack_require__(92988); +const { getNormalizedWebpackOptions } = __webpack_require__(26693); + +class WebpackOptionsDefaulter { + process(options) { + options = getNormalizedWebpackOptions(options); + applyWebpackOptionsDefaults(options); + return options; } +} - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only - */ - getSideEffectsConnectionState(moduleGraph) { - if (this.factoryMeta !== undefined) { - if (this.factoryMeta.sideEffectFree) return false; - if (this.factoryMeta.sideEffectFree === false) return true; - } - if (this.buildMeta !== undefined && this.buildMeta.sideEffectFree) { - if (this._isEvaluatingSideEffects) - return ModuleGraphConnection.CIRCULAR_CONNECTION; - this._isEvaluatingSideEffects = true; - /** @type {ConnectionState} */ - let current = false; - for (const dep of this.dependencies) { - const state = dep.getModuleEvaluationSideEffectsState(moduleGraph); - if (state === true) { - if ( - this._addedSideEffectsBailout === undefined - ? ((this._addedSideEffectsBailout = new WeakSet()), true) - : !this._addedSideEffectsBailout.has(moduleGraph) - ) { - this._addedSideEffectsBailout.add(moduleGraph); - moduleGraph - .getOptimizationBailout(this) - .push( - () => - `Dependency (${ - dep.type - }) with side effects at ${formatLocation(dep.loc)}` - ); - } - this._isEvaluatingSideEffects = false; - return true; - } else if (state !== ModuleGraphConnection.CIRCULAR_CONNECTION) { - current = ModuleGraphConnection.addConnectionStates(current, state); - } +module.exports = WebpackOptionsDefaulter; + + +/***/ }), + +/***/ 98421: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + + + +const mimeTypes = __webpack_require__(78585); +const path = __webpack_require__(71017); +const { RawSource } = __webpack_require__(51255); +const Generator = __webpack_require__(93401); +const RuntimeGlobals = __webpack_require__(16475); +const createHash = __webpack_require__(49835); +const { makePathsRelative } = __webpack_require__(82186); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").AssetGeneratorOptions} AssetGeneratorOptions */ +/** @typedef {import("../../declarations/WebpackOptions").AssetModuleOutputPath} AssetModuleOutputPath */ +/** @typedef {import("../../declarations/WebpackOptions").RawPublicPath} RawPublicPath */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../util/Hash")} Hash */ + +const mergeMaybeArrays = (a, b) => { + const set = new Set(); + if (Array.isArray(a)) for (const item of a) set.add(item); + else set.add(a); + if (Array.isArray(b)) for (const item of b) set.add(item); + else set.add(b); + return Array.from(set); +}; + +const mergeAssetInfo = (a, b) => { + const result = { ...a, ...b }; + for (const key of Object.keys(a)) { + if (key in b) { + if (a[key] === b[key]) continue; + switch (key) { + case "fullhash": + case "chunkhash": + case "modulehash": + case "contenthash": + result[key] = mergeMaybeArrays(a[key], b[key]); + break; + case "immutable": + case "development": + case "hotModuleReplacement": + case "javascriptModule": + result[key] = a[key] || b[key]; + break; + case "related": + result[key] = mergeRelatedInfo(a[key], b[key]); + break; + default: + throw new Error(`Can't handle conflicting asset info for ${key}`); } - this._isEvaluatingSideEffects = false; - // When caching is implemented here, make sure to not cache when - // at least one circular connection was in the loop above - return current; - } else { - return true; } } + return result; +}; - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - if (this._sourceTypes === undefined) { - this._sourceTypes = this.generator.getTypes(this); +const mergeRelatedInfo = (a, b) => { + const result = { ...a, ...b }; + for (const key of Object.keys(a)) { + if (key in b) { + if (a[key] === b[key]) continue; + result[key] = mergeMaybeArrays(a[key], b[key]); } - return this._sourceTypes; } + return result; +}; - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration({ - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime, - concatenationScope, - codeGenerationResults - }) { - /** @type {Set} */ - const runtimeRequirements = new Set(); +const encodeDataUri = (encoding, source) => { + let encodedContent; - if (!this.buildInfo.parsed) { - runtimeRequirements.add(RuntimeGlobals.module); - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.thisAsExports); + switch (encoding) { + case "base64": { + encodedContent = source.buffer().toString("base64"); + break; } + case false: { + const content = source.source(); - /** @type {Map} */ - let data; - const getData = () => { - if (data === undefined) data = new Map(); - return data; - }; - - const sources = new Map(); - for (const type of this.generator.getTypes(this)) { - const source = this.error - ? new RawSource( - "throw new Error(" + JSON.stringify(this.error.message) + ");" - ) - : this.generator.generate(this, { - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtimeRequirements, - runtime, - concatenationScope, - codeGenerationResults, - getData, - type - }); - - if (source) { - sources.set(type, new CachedSource(source)); + if (typeof content !== "string") { + encodedContent = content.toString("utf-8"); } - } - /** @type {CodeGenerationResult} */ - const resultEntry = { - sources, - runtimeRequirements, - data - }; - return resultEntry; + encodedContent = encodeURIComponent(encodedContent).replace( + /[!'()*]/g, + character => "%" + character.codePointAt(0).toString(16) + ); + break; + } + default: + throw new Error(`Unsupported encoding '${encoding}'`); } - /** - * @returns {Source | null} the original source for the module before webpack transformation - */ - originalSource() { - return this._source; - } + return encodedContent; +}; + +const decodeDataUriContent = (encoding, content) => { + const isBase64 = encoding === "base64"; + return isBase64 + ? Buffer.from(content, "base64") + : Buffer.from(decodeURIComponent(content), "ascii"); +}; + +const JS_TYPES = new Set(["javascript"]); +const JS_AND_ASSET_TYPES = new Set(["javascript", "asset"]); +class AssetGenerator extends Generator { /** - * @returns {void} + * @param {AssetGeneratorOptions["dataUrl"]=} dataUrlOptions the options for the data url + * @param {string=} filename override for output.assetModuleFilename + * @param {RawPublicPath=} publicPath override for output.assetModulePublicPath + * @param {AssetModuleOutputPath=} outputPath the output path for the emitted file which is not included in the runtime import + * @param {boolean=} emit generate output asset */ - invalidateBuild() { - this._forceBuild = true; + constructor(dataUrlOptions, filename, publicPath, outputPath, emit) { + super(); + this.dataUrlOptions = dataUrlOptions; + this.filename = filename; + this.publicPath = publicPath; + this.outputPath = outputPath; + this.emit = emit; } /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code */ - needBuild(context, callback) { - const { fileSystemInfo, compilation, valueCacheVersions } = context; - // build if enforced - if (this._forceBuild) return callback(null, true); + generate( + module, + { runtime, chunkGraph, runtimeTemplate, runtimeRequirements, type, getData } + ) { + switch (type) { + case "asset": + return module.originalSource(); + default: { + runtimeRequirements.add(RuntimeGlobals.module); - // always try to build in case of an error - if (this.error) return callback(null, true); + const originalSource = module.originalSource(); + if (module.buildInfo.dataUrl) { + let encodedSource; + if (typeof this.dataUrlOptions === "function") { + encodedSource = this.dataUrlOptions.call( + null, + originalSource.source(), + { + filename: module.matchResource || module.resource, + module + } + ); + } else { + /** @type {string | false | undefined} */ + let encoding = this.dataUrlOptions.encoding; + if (encoding === undefined) { + if ( + module.resourceResolveData && + module.resourceResolveData.encoding !== undefined + ) { + encoding = module.resourceResolveData.encoding; + } + } + if (encoding === undefined) { + encoding = "base64"; + } + let ext; + let mimeType = this.dataUrlOptions.mimetype; + if (mimeType === undefined) { + ext = path.extname(module.nameForCondition()); + if ( + module.resourceResolveData && + module.resourceResolveData.mimetype !== undefined + ) { + mimeType = + module.resourceResolveData.mimetype + + module.resourceResolveData.parameters; + } else if (ext) { + mimeType = mimeTypes.lookup(ext); + } + } + if (typeof mimeType !== "string") { + throw new Error( + "DataUrl can't be generated automatically, " + + `because there is no mimetype for "${ext}" in mimetype database. ` + + 'Either pass a mimetype via "generator.mimetype" or ' + + 'use type: "asset/resource" to create a resource file instead of a DataUrl' + ); + } - // always build when module is not cacheable - if (!this.buildInfo.cacheable) return callback(null, true); + let encodedContent; - // build when there is no snapshot to check - if (!this.buildInfo.snapshot) return callback(null, true); + if ( + module.resourceResolveData && + module.resourceResolveData.encoding === encoding && + decodeDataUriContent( + module.resourceResolveData.encoding, + module.resourceResolveData.encodedContent + ).equals(originalSource.buffer()) + ) { + encodedContent = module.resourceResolveData.encodedContent; + } else { + encodedContent = encodeDataUri(encoding, originalSource); + } - // build when valueDependencies have changed - /** @type {Map>} */ - const valueDependencies = this.buildInfo.valueDependencies; - if (valueDependencies) { - if (!valueCacheVersions) return callback(null, true); - for (const [key, value] of valueDependencies) { - if (value === undefined) return callback(null, true); - const current = valueCacheVersions.get(key); - if ( - value !== current && - (typeof value === "string" || - typeof current === "string" || - current === undefined || - !isSubset(value, current)) - ) { - return callback(null, true); - } - } - } + encodedSource = `data:${mimeType}${ + encoding ? `;${encoding}` : "" + },${encodedContent}`; + } + const data = getData(); + data.set("url", Buffer.from(encodedSource)); + return new RawSource( + `${RuntimeGlobals.module}.exports = ${JSON.stringify( + encodedSource + )};` + ); + } else { + const assetModuleFilename = + this.filename || runtimeTemplate.outputOptions.assetModuleFilename; + const hash = createHash(runtimeTemplate.outputOptions.hashFunction); + if (runtimeTemplate.outputOptions.hashSalt) { + hash.update(runtimeTemplate.outputOptions.hashSalt); + } + hash.update(originalSource.buffer()); + const fullHash = /** @type {string} */ ( + hash.digest(runtimeTemplate.outputOptions.hashDigest) + ); + const contentHash = fullHash.slice( + 0, + runtimeTemplate.outputOptions.hashDigestLength + ); + module.buildInfo.fullContentHash = fullHash; + const sourceFilename = makePathsRelative( + runtimeTemplate.compilation.compiler.context, + module.matchResource || module.resource, + runtimeTemplate.compilation.compiler.root + ).replace(/^\.\//, ""); + let { path: filename, info: assetInfo } = + runtimeTemplate.compilation.getAssetPathWithInfo( + assetModuleFilename, + { + module, + runtime, + filename: sourceFilename, + chunkGraph, + contentHash + } + ); + let assetPath; + if (this.publicPath !== undefined) { + const { path, info } = + runtimeTemplate.compilation.getAssetPathWithInfo( + this.publicPath, + { + module, + runtime, + filename: sourceFilename, + chunkGraph, + contentHash + } + ); + assetInfo = mergeAssetInfo(assetInfo, info); + assetPath = JSON.stringify(path + filename); + } else { + runtimeRequirements.add(RuntimeGlobals.publicPath); // add __webpack_require__.p + assetPath = runtimeTemplate.concatenation( + { expr: RuntimeGlobals.publicPath }, + filename + ); + } + assetInfo = { + sourceFilename, + ...assetInfo + }; + if (this.outputPath) { + const { path: outputPath, info } = + runtimeTemplate.compilation.getAssetPathWithInfo( + this.outputPath, + { + module, + runtime, + filename: sourceFilename, + chunkGraph, + contentHash + } + ); + assetInfo = mergeAssetInfo(assetInfo, info); + filename = path.posix.join(outputPath, filename); + } + module.buildInfo.filename = filename; + module.buildInfo.assetInfo = assetInfo; + if (getData) { + // Due to code generation caching module.buildInfo.XXX can't used to store such information + // It need to be stored in the code generation results instead, where it's cached too + // TODO webpack 6 For back-compat reasons we also store in on module.buildInfo + const data = getData(); + data.set("fullContentHash", fullHash); + data.set("filename", filename); + data.set("assetInfo", assetInfo); + } - // check snapshot for validity - fileSystemInfo.checkSnapshotValid(this.buildInfo.snapshot, (err, valid) => { - if (err) return callback(err); - if (!valid) return callback(null, true); - const hooks = NormalModule.getCompilationHooks(compilation); - hooks.needBuild.callAsync(this, context, (err, needBuild) => { - if (err) { - return callback( - HookWebpackError.makeWebpackError( - err, - "NormalModule.getCompilationHooks().needBuild" - ) + return new RawSource( + `${RuntimeGlobals.module}.exports = ${assetPath};` ); } - callback(null, !!needBuild); - }); - }); - } - - /** - * @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) { - const cachedSize = - this._sourceSizes === undefined ? undefined : this._sourceSizes.get(type); - if (cachedSize !== undefined) { - return cachedSize; - } - const size = Math.max(1, this.generator.getSize(this, type)); - if (this._sourceSizes === undefined) { - this._sourceSizes = new Map(); + } } - this._sourceSizes.set(type, size); - return size; } /** - * @param {LazySet} fileDependencies set where file dependencies are added to - * @param {LazySet} contextDependencies set where context dependencies are added to - * @param {LazySet} missingDependencies set where missing dependencies are added to - * @param {LazySet} buildDependencies set where build dependencies are added to + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ) { - const { snapshot, buildDependencies: buildDeps } = this.buildInfo; - if (snapshot) { - fileDependencies.addAll(snapshot.getFileIterable()); - contextDependencies.addAll(snapshot.getContextIterable()); - missingDependencies.addAll(snapshot.getMissingIterable()); + getTypes(module) { + if ((module.buildInfo && module.buildInfo.dataUrl) || this.emit === false) { + return JS_TYPES; } else { - const { - fileDependencies: fileDeps, - contextDependencies: contextDeps, - missingDependencies: missingDeps - } = this.buildInfo; - if (fileDeps !== undefined) fileDependencies.addAll(fileDeps); - if (contextDeps !== undefined) contextDependencies.addAll(contextDeps); - if (missingDeps !== undefined) missingDependencies.addAll(missingDeps); - } - if (buildDeps !== undefined) { - buildDependencies.addAll(buildDeps); + return JS_AND_ASSET_TYPES; } } /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - updateHash(hash, context) { - hash.update(this.buildInfo.hash); - this.generator.updateHash(hash, { - module: this, - ...context - }); - super.updateHash(hash, context); - } + getSize(module, type) { + switch (type) { + case "asset": { + const originalSource = module.originalSource(); - serialize(context) { - const { write } = context; - // deserialize - write(this._source); - write(this.error); - write(this._lastSuccessfulBuildMeta); - write(this._forceBuild); - super.serialize(context); - } + if (!originalSource) { + return 0; + } - static deserialize(context) { - const obj = new NormalModule({ - // will be deserialized by Module - layer: null, - type: "", - // will be filled by updateCacheModule - resource: "", - context: "", - request: null, - userRequest: null, - rawRequest: null, - loaders: null, - matchResource: null, - parser: null, - parserOptions: null, - generator: null, - generatorOptions: null, - resolveOptions: null - }); - obj.deserialize(context); - return obj; + return originalSource.size(); + } + default: + if (module.buildInfo && module.buildInfo.dataUrl) { + const originalSource = module.originalSource(); + + if (!originalSource) { + return 0; + } + + // roughly for data url + // Example: m.exports="data:image/png;base64,ag82/f+2==" + // 4/3 = base64 encoding + // 34 = ~ data url header + footer + rounding + return originalSource.size() * 1.34 + 36; + } else { + // it's only estimated so this number is probably fine + // Example: m.exports=r.p+"0123456789012345678901.ext" + return 42; + } + } } - deserialize(context) { - const { read } = context; - this._source = read(); - this.error = read(); - this._lastSuccessfulBuildMeta = read(); - this._forceBuild = read(); - super.deserialize(context); + /** + * @param {Hash} hash hash that will be modified + * @param {UpdateHashContext} updateHashContext context for updating hash + */ + updateHash(hash, { module }) { + hash.update(module.buildInfo.dataUrl ? "data-url" : "resource"); } } -makeSerializable(NormalModule, "webpack/lib/NormalModule"); - -module.exports = NormalModule; +module.exports = AssetGenerator; /***/ }), -/***/ 68860: +/***/ 16109: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Yuta Hiroto @hiroppy */ -const { getContext } = __webpack_require__(68318); -const asyncLib = __webpack_require__(78175); -const { - AsyncSeriesBailHook, - SyncWaterfallHook, - SyncBailHook, - SyncHook, - HookMap -} = __webpack_require__(41242); -const ChunkGraph = __webpack_require__(64971); -const Module = __webpack_require__(73208); -const ModuleFactory = __webpack_require__(51010); -const ModuleGraph = __webpack_require__(99988); -const NormalModule = __webpack_require__(39); -const BasicEffectRulePlugin = __webpack_require__(30318); -const BasicMatcherRulePlugin = __webpack_require__(94215); -const ObjectMatcherRulePlugin = __webpack_require__(72021); -const RuleSetCompiler = __webpack_require__(83349); -const UseEffectRulePlugin = __webpack_require__(84977); -const LazySet = __webpack_require__(38938); -const { getScheme } = __webpack_require__(54500); -const { cachedCleverMerge, cachedSetProperty } = __webpack_require__(60839); -const { join } = __webpack_require__(17139); -const { parseResource } = __webpack_require__(82186); +const { cleverMerge } = __webpack_require__(60839); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); +const memoize = __webpack_require__(78676); -/** @typedef {import("../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ -/** @typedef {import("./Generator")} Generator */ -/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("./Parser")} Parser */ -/** @typedef {import("./ResolverFactory")} ResolverFactory */ -/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ -/** - * @typedef {Object} ResolveData - * @property {ModuleFactoryCreateData["contextInfo"]} contextInfo - * @property {ModuleFactoryCreateData["resolveOptions"]} resolveOptions - * @property {string} context - * @property {string} request - * @property {Record | undefined} assertions - * @property {ModuleDependency[]} dependencies - * @property {string} dependencyType - * @property {Object} createData - * @property {LazySet} fileDependencies - * @property {LazySet} missingDependencies - * @property {LazySet} contextDependencies - * @property {boolean} cacheable allow to use the unsafe cache - */ +const getSchema = name => { + const { definitions } = __webpack_require__(73342); + return { + definitions, + oneOf: [{ $ref: `#/definitions/${name}` }] + }; +}; -/** - * @typedef {Object} ResourceData - * @property {string} resource - * @property {string} path - * @property {string} query - * @property {string} fragment - * @property {string=} context - */ +const generatorValidationOptions = { + name: "Asset Modules Plugin", + baseDataPath: "generator" +}; +const validateGeneratorOptions = { + asset: createSchemaValidation( + __webpack_require__(55125), + () => getSchema("AssetGeneratorOptions"), + generatorValidationOptions + ), + "asset/resource": createSchemaValidation( + __webpack_require__(4405), + () => getSchema("AssetResourceGeneratorOptions"), + generatorValidationOptions + ), + "asset/inline": createSchemaValidation( + __webpack_require__(62368), + () => getSchema("AssetInlineGeneratorOptions"), + generatorValidationOptions + ) +}; -/** @typedef {ResourceData & { data: Record }} ResourceDataWithData */ +const validateParserOptions = createSchemaValidation( + __webpack_require__(45020), + () => getSchema("AssetParserOptions"), + { + name: "Asset Modules Plugin", + baseDataPath: "parser" + } +); -const EMPTY_RESOLVE_OPTIONS = {}; -const EMPTY_PARSER_OPTIONS = {}; -const EMPTY_GENERATOR_OPTIONS = {}; -const EMPTY_ELEMENTS = []; +const getAssetGenerator = memoize(() => __webpack_require__(98421)); +const getAssetParser = memoize(() => __webpack_require__(91112)); +const getAssetSourceParser = memoize(() => __webpack_require__(30953)); +const getAssetSourceGenerator = memoize(() => + __webpack_require__(18749) +); -const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; +const type = "asset"; +const plugin = "AssetModulesPlugin"; -const loaderToIdent = data => { - if (!data.options) { - return data.loader; - } - if (typeof data.options === "string") { - return data.loader + "?" + data.options; - } - if (typeof data.options !== "object") { - throw new Error("loader options must be string or object"); - } - if (data.ident) { - return data.loader + "??" + data.ident; - } - return data.loader + "?" + JSON.stringify(data.options); -}; +class AssetModulesPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + plugin, + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.createParser + .for("asset") + .tap(plugin, parserOptions => { + validateParserOptions(parserOptions); + parserOptions = cleverMerge( + compiler.options.module.parser.asset, + parserOptions + ); -const stringifyLoadersAndResource = (loaders, resource) => { - let str = ""; - for (const loader of loaders) { - str += loaderToIdent(loader) + "!"; - } - return str + resource; -}; + let dataUrlCondition = parserOptions.dataUrlCondition; + if (!dataUrlCondition || typeof dataUrlCondition === "object") { + dataUrlCondition = { + maxSize: 8096, + ...dataUrlCondition + }; + } -/** - * @param {string} resultString resultString - * @returns {{loader: string, options: string|undefined}} parsed loader request - */ -const identToLoaderRequest = resultString => { - const idx = resultString.indexOf("?"); - if (idx >= 0) { - const loader = resultString.substr(0, idx); - const options = resultString.substr(idx + 1); - return { - loader, - options - }; - } else { - return { - loader: resultString, - options: undefined - }; - } -}; + const AssetParser = getAssetParser(); -const needCalls = (times, callback) => { - return err => { - if (--times === 0) { - return callback(err); - } - if (err && times > 0) { - times = NaN; - return callback(err); - } - }; -}; + return new AssetParser(dataUrlCondition); + }); + normalModuleFactory.hooks.createParser + .for("asset/inline") + .tap(plugin, parserOptions => { + const AssetParser = getAssetParser(); -const mergeGlobalOptions = (globalOptions, type, localOptions) => { - const parts = type.split("/"); - let result; - let current = ""; - for (const part of parts) { - current = current ? `${current}/${part}` : part; - const options = globalOptions[current]; - if (typeof options === "object") { - if (result === undefined) { - result = options; - } else { - result = cachedCleverMerge(result, options); - } - } - } - if (result === undefined) { - return localOptions; - } else { - return cachedCleverMerge(result, localOptions); - } -}; + return new AssetParser(true); + }); + normalModuleFactory.hooks.createParser + .for("asset/resource") + .tap(plugin, parserOptions => { + const AssetParser = getAssetParser(); -// TODO webpack 6 remove -const deprecationChangedHookMessage = (name, hook) => { - const names = hook.taps - .map(tapped => { - return tapped.name; - }) - .join(", "); + return new AssetParser(false); + }); + normalModuleFactory.hooks.createParser + .for("asset/source") + .tap(plugin, parserOptions => { + const AssetSourceParser = getAssetSourceParser(); - return ( - `NormalModuleFactory.${name} (${names}) is no longer a waterfall hook, but a bailing hook instead. ` + - "Do not return the passed object, but modify it instead. " + - "Returning false will ignore the request and results in no module created." - ); -}; + return new AssetSourceParser(); + }); -const ruleSetCompiler = new RuleSetCompiler([ - new BasicMatcherRulePlugin("test", "resource"), - new BasicMatcherRulePlugin("scheme"), - new BasicMatcherRulePlugin("mimetype"), - new BasicMatcherRulePlugin("dependency"), - new BasicMatcherRulePlugin("include", "resource"), - new BasicMatcherRulePlugin("exclude", "resource", true), - new BasicMatcherRulePlugin("resource"), - new BasicMatcherRulePlugin("resourceQuery"), - new BasicMatcherRulePlugin("resourceFragment"), - new BasicMatcherRulePlugin("realResource"), - new BasicMatcherRulePlugin("issuer"), - new BasicMatcherRulePlugin("compiler"), - new BasicMatcherRulePlugin("issuerLayer"), - new ObjectMatcherRulePlugin("assert", "assertions"), - new ObjectMatcherRulePlugin("descriptionData"), - new BasicEffectRulePlugin("type"), - new BasicEffectRulePlugin("sideEffects"), - new BasicEffectRulePlugin("parser"), - new BasicEffectRulePlugin("resolve"), - new BasicEffectRulePlugin("generator"), - new BasicEffectRulePlugin("layer"), - new UseEffectRulePlugin() -]); + for (const type of ["asset", "asset/inline", "asset/resource"]) { + normalModuleFactory.hooks.createGenerator + .for(type) + .tap(plugin, generatorOptions => { + validateGeneratorOptions[type](generatorOptions); -class NormalModuleFactory extends ModuleFactory { - /** - * @param {Object} param params - * @param {string=} param.context context - * @param {InputFileSystem} param.fs file system - * @param {ResolverFactory} param.resolverFactory resolverFactory - * @param {ModuleOptions} param.options options - * @param {Object=} param.associatedObjectForCache an object to which the cache will be attached - * @param {boolean=} param.layers enable layers - */ - constructor({ - context, - fs, - resolverFactory, - options, - associatedObjectForCache, - layers = false - }) { - super(); - this.hooks = Object.freeze({ - /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ - resolve: new AsyncSeriesBailHook(["resolveData"]), - /** @type {HookMap>} */ - resolveForScheme: new HookMap( - () => new AsyncSeriesBailHook(["resourceData", "resolveData"]) - ), - /** @type {HookMap>} */ - resolveInScheme: new HookMap( - () => new AsyncSeriesBailHook(["resourceData", "resolveData"]) - ), - /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ - factorize: new AsyncSeriesBailHook(["resolveData"]), - /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ - beforeResolve: new AsyncSeriesBailHook(["resolveData"]), - /** @type {AsyncSeriesBailHook<[ResolveData], TODO>} */ - afterResolve: new AsyncSeriesBailHook(["resolveData"]), - /** @type {AsyncSeriesBailHook<[ResolveData["createData"], ResolveData], TODO>} */ - createModule: new AsyncSeriesBailHook(["createData", "resolveData"]), - /** @type {SyncWaterfallHook<[Module, ResolveData["createData"], ResolveData], TODO>} */ - module: new SyncWaterfallHook(["module", "createData", "resolveData"]), - createParser: new HookMap(() => new SyncBailHook(["parserOptions"])), - parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])), - createGenerator: new HookMap( - () => new SyncBailHook(["generatorOptions"]) - ), - generator: new HookMap( - () => new SyncHook(["generator", "generatorOptions"]) - ) - }); - this.resolverFactory = resolverFactory; - this.ruleSet = ruleSetCompiler.compile([ - { - rules: options.defaultRules - }, - { - rules: options.rules - } - ]); - this.context = context || ""; - this.fs = fs; - this._globalParserOptions = options.parser; - this._globalGeneratorOptions = options.generator; - /** @type {Map>} */ - this.parserCache = new Map(); - /** @type {Map>} */ - this.generatorCache = new Map(); - /** @type {Set} */ - this._restoredUnsafeCacheEntries = new Set(); + let dataUrl = undefined; + if (type !== "asset/resource") { + dataUrl = generatorOptions.dataUrl; + if (!dataUrl || typeof dataUrl === "object") { + dataUrl = { + encoding: undefined, + mimetype: undefined, + ...dataUrl + }; + } + } - const cacheParseResource = parseResource.bindCache( - associatedObjectForCache - ); + let filename = undefined; + let publicPath = undefined; + let outputPath = undefined; + if (type !== "asset/inline") { + filename = generatorOptions.filename; + publicPath = generatorOptions.publicPath; + outputPath = generatorOptions.outputPath; + } - this.hooks.factorize.tapAsync( - { - name: "NormalModuleFactory", - stage: 100 - }, - (resolveData, callback) => { - this.hooks.resolve.callAsync(resolveData, (err, result) => { - if (err) return callback(err); + const AssetGenerator = getAssetGenerator(); - // Ignored - if (result === false) return callback(); + return new AssetGenerator( + dataUrl, + filename, + publicPath, + outputPath, + generatorOptions.emit !== false + ); + }); + } + normalModuleFactory.hooks.createGenerator + .for("asset/source") + .tap(plugin, () => { + const AssetSourceGenerator = getAssetSourceGenerator(); - // direct module - if (result instanceof Module) return callback(null, result); + return new AssetSourceGenerator(); + }); - if (typeof result === "object") - throw new Error( - deprecationChangedHookMessage("resolve", this.hooks.resolve) + - " Returning a Module object will result in this module used as result." - ); + compilation.hooks.renderManifest.tap(plugin, (result, options) => { + const { chunkGraph } = compilation; + const { chunk, codeGenerationResults } = options; - this.hooks.afterResolve.callAsync(resolveData, (err, result) => { - if (err) return callback(err); + const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "asset", + compareModulesByIdentifier + ); + if (modules) { + for (const module of modules) { + try { + const codeGenResult = codeGenerationResults.get( + module, + chunk.runtime + ); + result.push({ + render: () => codeGenResult.sources.get(type), + filename: + module.buildInfo.filename || + codeGenResult.data.get("filename"), + info: + module.buildInfo.assetInfo || + codeGenResult.data.get("assetInfo"), + auxiliary: true, + identifier: `assetModule${chunkGraph.getModuleId(module)}`, + hash: + module.buildInfo.fullContentHash || + codeGenResult.data.get("fullContentHash") + }); + } catch (e) { + e.message += `\nduring rendering of asset ${module.identifier()}`; + throw e; + } + } + } - if (typeof result === "object") - throw new Error( - deprecationChangedHookMessage( - "afterResolve", - this.hooks.afterResolve - ) - ); + return result; + }); - // Ignored - if (result === false) return callback(); + compilation.hooks.prepareModuleExecution.tap( + "AssetModulesPlugin", + (options, context) => { + const { codeGenerationResult } = options; + const source = codeGenerationResult.sources.get("asset"); + if (source === undefined) return; + context.assets.set(codeGenerationResult.data.get("filename"), { + source, + info: codeGenerationResult.data.get("assetInfo") + }); + } + ); + } + ); + } +} - const createData = resolveData.createData; +module.exports = AssetModulesPlugin; - this.hooks.createModule.callAsync( - createData, - resolveData, - (err, createdModule) => { - if (!createdModule) { - if (!resolveData.request) { - return callback(new Error("Empty dependency (no request)")); - } - createdModule = new NormalModule(createData); - } +/***/ }), - createdModule = this.hooks.module.call( - createdModule, - createData, - resolveData - ); +/***/ 91112: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return callback(null, createdModule); - } - ); - }); - }); - } - ); - this.hooks.resolve.tapAsync( - { - name: "NormalModuleFactory", - stage: 100 - }, - (data, callback) => { - const { - contextInfo, - context, - dependencies, - dependencyType, - request, - assertions, - resolveOptions, - fileDependencies, - missingDependencies, - contextDependencies - } = data; - const loaderResolver = this.getResolver("loader"); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Yuta Hiroto @hiroppy +*/ - /** @type {ResourceData | undefined} */ - let matchResourceData = undefined; - /** @type {string} */ - let unresolvedResource; - /** @type {{loader: string, options: string|undefined}[]} */ - let elements; - let noPreAutoLoaders = false; - let noAutoLoaders = false; - let noPrePostAutoLoaders = false; - const contextScheme = getScheme(context); - /** @type {string | undefined} */ - let scheme = getScheme(request); - if (!scheme) { - /** @type {string} */ - let requestWithoutMatchResource = request; - const matchResourceMatch = MATCH_RESOURCE_REGEX.exec(request); - if (matchResourceMatch) { - let matchResource = matchResourceMatch[1]; - if (matchResource.charCodeAt(0) === 46) { - // 46 === ".", 47 === "/" - const secondChar = matchResource.charCodeAt(1); - if ( - secondChar === 47 || - (secondChar === 46 && matchResource.charCodeAt(2) === 47) - ) { - // if matchResources startsWith ../ or ./ - matchResource = join(this.fs, context, matchResource); - } - } - matchResourceData = { - resource: matchResource, - ...cacheParseResource(matchResource) - }; - requestWithoutMatchResource = request.substr( - matchResourceMatch[0].length - ); - } +const Parser = __webpack_require__(11715); - scheme = getScheme(requestWithoutMatchResource); +/** @typedef {import("../../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ - if (!scheme && !contextScheme) { - const firstChar = requestWithoutMatchResource.charCodeAt(0); - const secondChar = requestWithoutMatchResource.charCodeAt(1); - noPreAutoLoaders = firstChar === 45 && secondChar === 33; // startsWith "-!" - noAutoLoaders = noPreAutoLoaders || firstChar === 33; // startsWith "!" - noPrePostAutoLoaders = firstChar === 33 && secondChar === 33; // startsWith "!!"; - const rawElements = requestWithoutMatchResource - .slice( - noPreAutoLoaders || noPrePostAutoLoaders - ? 2 - : noAutoLoaders - ? 1 - : 0 - ) - .split(/!+/); - unresolvedResource = rawElements.pop(); - elements = rawElements.map(identToLoaderRequest); - scheme = getScheme(unresolvedResource); - } else { - unresolvedResource = requestWithoutMatchResource; - elements = EMPTY_ELEMENTS; - } - } else { - unresolvedResource = request; - elements = EMPTY_ELEMENTS; - } +class AssetParser extends Parser { + /** + * @param {AssetParserOptions["dataUrlCondition"] | boolean} dataUrlCondition condition for inlining as DataUrl + */ + constructor(dataUrlCondition) { + super(); + this.dataUrlCondition = dataUrlCondition; + } - const resolveContext = { - fileDependencies, - missingDependencies, - contextDependencies - }; + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (typeof source === "object" && !Buffer.isBuffer(source)) { + throw new Error("AssetParser doesn't accept preparsed AST"); + } + state.module.buildInfo.strict = true; + state.module.buildMeta.exportsType = "default"; - /** @type {ResourceDataWithData} */ - let resourceData; + if (typeof this.dataUrlCondition === "function") { + state.module.buildInfo.dataUrl = this.dataUrlCondition(source, { + filename: state.module.matchResource || state.module.resource, + module: state.module + }); + } else if (typeof this.dataUrlCondition === "boolean") { + state.module.buildInfo.dataUrl = this.dataUrlCondition; + } else if ( + this.dataUrlCondition && + typeof this.dataUrlCondition === "object" + ) { + state.module.buildInfo.dataUrl = + Buffer.byteLength(source) <= this.dataUrlCondition.maxSize; + } else { + throw new Error("Unexpected dataUrlCondition type"); + } - let loaders; + return state; + } +} - const continueCallback = needCalls(2, err => { - if (err) return callback(err); +module.exports = AssetParser; - // translate option idents - try { - for (const item of loaders) { - if (typeof item.options === "string" && item.options[0] === "?") { - const ident = item.options.substr(1); - if (ident === "[[missing ident]]") { - throw new Error( - "No ident is provided by referenced loader. " + - "When using a function for Rule.use in config you need to " + - "provide an 'ident' property for referenced loader options." - ); - } - item.options = this.ruleSet.references.get(ident); - if (item.options === undefined) { - throw new Error( - "Invalid ident is provided by referenced loader" - ); - } - item.ident = ident; - } - } - } catch (e) { - return callback(e); - } - if (!resourceData) { - // ignored - return callback(null, dependencies[0].createIgnoredModule(context)); - } +/***/ }), - const userRequest = - (matchResourceData !== undefined - ? `${matchResourceData.resource}!=!` - : "") + - stringifyLoadersAndResource(loaders, resourceData.resource); +/***/ 18749: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const settings = {}; - const useLoadersPost = []; - const useLoaders = []; - const useLoadersPre = []; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ - // handle .webpack[] suffix - let resource; - let match; - if ( - matchResourceData && - typeof (resource = matchResourceData.resource) === "string" && - (match = /\.webpack\[([^\]]+)\]$/.exec(resource)) - ) { - settings.type = match[1]; - matchResourceData.resource = matchResourceData.resource.slice( - 0, - -settings.type.length - 10 - ); - } else { - settings.type = "javascript/auto"; - const resourceDataForRules = matchResourceData || resourceData; - const result = this.ruleSet.exec({ - resource: resourceDataForRules.path, - realResource: resourceData.path, - resourceQuery: resourceDataForRules.query, - resourceFragment: resourceDataForRules.fragment, - scheme, - assertions, - mimetype: matchResourceData - ? "" - : resourceData.data.mimetype || "", - dependency: dependencyType, - descriptionData: matchResourceData - ? undefined - : resourceData.data.descriptionFileData, - issuer: contextInfo.issuer, - compiler: contextInfo.compiler, - issuerLayer: contextInfo.issuerLayer || "" - }); - for (const r of result) { - if (r.type === "use") { - if (!noAutoLoaders && !noPrePostAutoLoaders) { - useLoaders.push(r.value); - } - } else if (r.type === "use-post") { - if (!noPrePostAutoLoaders) { - useLoadersPost.push(r.value); - } - } else if (r.type === "use-pre") { - if (!noPreAutoLoaders && !noPrePostAutoLoaders) { - useLoadersPre.push(r.value); - } - } else if ( - typeof r.value === "object" && - r.value !== null && - typeof settings[r.type] === "object" && - settings[r.type] !== null - ) { - settings[r.type] = cachedCleverMerge(settings[r.type], r.value); - } else { - settings[r.type] = r.value; - } - } - } - let postLoaders, normalLoaders, preLoaders; - const continueCallback = needCalls(3, err => { - if (err) { - return callback(err); - } - const allLoaders = postLoaders; - if (matchResourceData === undefined) { - for (const loader of loaders) allLoaders.push(loader); - for (const loader of normalLoaders) allLoaders.push(loader); - } else { - for (const loader of normalLoaders) allLoaders.push(loader); - for (const loader of loaders) allLoaders.push(loader); - } - for (const loader of preLoaders) allLoaders.push(loader); - let type = settings.type; - const resolveOptions = settings.resolve; - const layer = settings.layer; - if (layer !== undefined && !layers) { - return callback( - new Error( - "'Rule.layer' is only allowed when 'experiments.layers' is enabled" - ) - ); - } - try { - Object.assign(data.createData, { - layer: - layer === undefined ? contextInfo.issuerLayer || null : layer, - request: stringifyLoadersAndResource( - allLoaders, - resourceData.resource - ), - userRequest, - rawRequest: request, - loaders: allLoaders, - resource: resourceData.resource, - context: - resourceData.context || getContext(resourceData.resource), - matchResource: matchResourceData - ? matchResourceData.resource - : undefined, - resourceResolveData: resourceData.data, - settings, - type, - parser: this.getParser(type, settings.parser), - parserOptions: settings.parser, - generator: this.getGenerator(type, settings.generator), - generatorOptions: settings.generator, - resolveOptions - }); - } catch (e) { - return callback(e); - } - callback(); - }); - this.resolveRequestArray( - contextInfo, - this.context, - useLoadersPost, - loaderResolver, - resolveContext, - (err, result) => { - postLoaders = result; - continueCallback(err); - } - ); - this.resolveRequestArray( - contextInfo, - this.context, - useLoaders, - loaderResolver, - resolveContext, - (err, result) => { - normalLoaders = result; - continueCallback(err); - } - ); - this.resolveRequestArray( - contextInfo, - this.context, - useLoadersPre, - loaderResolver, - resolveContext, - (err, result) => { - preLoaders = result; - continueCallback(err); - } - ); - }); +const { RawSource } = __webpack_require__(51255); +const Generator = __webpack_require__(93401); +const RuntimeGlobals = __webpack_require__(16475); - this.resolveRequestArray( - contextInfo, - contextScheme ? this.context : context, - elements, - loaderResolver, - resolveContext, - (err, result) => { - if (err) return continueCallback(err); - loaders = result; - continueCallback(); - } - ); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../NormalModule")} NormalModule */ - const defaultResolve = context => { - if (/^($|\?)/.test(unresolvedResource)) { - resourceData = { - resource: unresolvedResource, - data: {}, - ...cacheParseResource(unresolvedResource) - }; - continueCallback(); - } +const TYPES = new Set(["javascript"]); - // resource without scheme and with path - else { - const normalResolver = this.getResolver( - "normal", - dependencyType - ? cachedSetProperty( - resolveOptions || EMPTY_RESOLVE_OPTIONS, - "dependencyType", - dependencyType - ) - : resolveOptions - ); - this.resolveResource( - contextInfo, - context, - unresolvedResource, - normalResolver, - resolveContext, - (err, resolvedResource, resolvedResourceResolveData) => { - if (err) return continueCallback(err); - if (resolvedResource !== false) { - resourceData = { - resource: resolvedResource, - data: resolvedResourceResolveData, - ...cacheParseResource(resolvedResource) - }; - } - continueCallback(); - } - ); - } - }; +class AssetSourceGenerator extends Generator { + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code + */ + generate(module, { chunkGraph, runtimeTemplate, runtimeRequirements }) { + runtimeRequirements.add(RuntimeGlobals.module); - // resource with scheme - if (scheme) { - resourceData = { - resource: unresolvedResource, - data: {}, - path: undefined, - query: undefined, - fragment: undefined, - context: undefined - }; - this.hooks.resolveForScheme - .for(scheme) - .callAsync(resourceData, data, err => { - if (err) return continueCallback(err); - continueCallback(); - }); - } + const originalSource = module.originalSource(); - // resource within scheme - else if (contextScheme) { - resourceData = { - resource: unresolvedResource, - data: {}, - path: undefined, - query: undefined, - fragment: undefined, - context: undefined - }; - this.hooks.resolveInScheme - .for(contextScheme) - .callAsync(resourceData, data, (err, handled) => { - if (err) return continueCallback(err); - if (!handled) return defaultResolve(this.context); - continueCallback(); - }); - } + if (!originalSource) { + return new RawSource(""); + } - // resource without scheme and without path - else defaultResolve(context); - } + const content = originalSource.source(); + + let encodedSource; + if (typeof content === "string") { + encodedSource = content; + } else { + encodedSource = content.toString("utf-8"); + } + return new RawSource( + `${RuntimeGlobals.module}.exports = ${JSON.stringify(encodedSource)};` ); } - cleanupForCache() { - for (const module of this._restoredUnsafeCacheEntries) { - ChunkGraph.clearChunkGraphForModule(module); - ModuleGraph.clearModuleGraphForModule(module); - module.cleanupForCache(); - } + /** + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) + */ + getTypes(module) { + return TYPES; } /** - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback - * @returns {void} + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - create(data, callback) { - const dependencies = /** @type {ModuleDependency[]} */ (data.dependencies); - const context = data.context || this.context; - const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS; - const dependency = dependencies[0]; - const request = dependency.request; - const assertions = dependency.assertions; - const contextInfo = data.contextInfo; - const fileDependencies = new LazySet(); - const missingDependencies = new LazySet(); - const contextDependencies = new LazySet(); - const dependencyType = - (dependencies.length > 0 && dependencies[0].category) || ""; - /** @type {ResolveData} */ - const resolveData = { - contextInfo, - resolveOptions, - context, - request, - assertions, - dependencies, - dependencyType, - fileDependencies, - missingDependencies, - contextDependencies, - createData: {}, - cacheable: true - }; - this.hooks.beforeResolve.callAsync(resolveData, (err, result) => { - if (err) { - return callback(err, { - fileDependencies, - missingDependencies, - contextDependencies, - cacheable: false - }); - } + getSize(module, type) { + const originalSource = module.originalSource(); - // Ignored - if (result === false) { - return callback(null, { - fileDependencies, - missingDependencies, - contextDependencies, - cacheable: resolveData.cacheable - }); - } + if (!originalSource) { + return 0; + } - if (typeof result === "object") - throw new Error( - deprecationChangedHookMessage( - "beforeResolve", - this.hooks.beforeResolve - ) - ); + // Example: m.exports="abcd" + return originalSource.size() + 12; + } +} - this.hooks.factorize.callAsync(resolveData, (err, module) => { - if (err) { - return callback(err, { - fileDependencies, - missingDependencies, - contextDependencies, - cacheable: false - }); - } +module.exports = AssetSourceGenerator; - const factoryResult = { - module, - fileDependencies, - missingDependencies, - contextDependencies, - cacheable: resolveData.cacheable - }; - callback(null, factoryResult); - }); - }); - } +/***/ }), - resolveResource( - contextInfo, - context, - unresolvedResource, - resolver, - resolveContext, - callback - ) { - resolver.resolve( - contextInfo, - context, - unresolvedResource, - resolveContext, - (err, resolvedResource, resolvedResourceResolveData) => { - if (err) { - return this._resolveResourceErrorHints( - err, - contextInfo, - context, - unresolvedResource, - resolver, - resolveContext, - (err2, hints) => { - if (err2) { - err.message += ` -An fatal error happened during resolving additional hints for this error: ${err2.message}`; - err.stack += ` +/***/ 30953: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -An fatal error happened during resolving additional hints for this error: -${err2.stack}`; - return callback(err); - } - if (hints && hints.length > 0) { - err.message += ` -${hints.join("\n\n")}`; - } - callback(err); - } - ); - } - callback(err, resolvedResource, resolvedResourceResolveData); - } - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Yuta Hiroto @hiroppy +*/ + + + +const Parser = __webpack_require__(11715); + +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ + +class AssetSourceParser extends Parser { + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (typeof source === "object" && !Buffer.isBuffer(source)) { + throw new Error("AssetSourceParser doesn't accept preparsed AST"); + } + const { module } = state; + module.buildInfo.strict = true; + module.buildMeta.exportsType = "default"; + + return state; } +} - _resolveResourceErrorHints( - error, - contextInfo, - context, - unresolvedResource, - resolver, - resolveContext, - callback - ) { - asyncLib.parallel( - [ - callback => { - if (!resolver.options.fullySpecified) return callback(); - resolver - .withOptions({ - fullySpecified: false - }) - .resolve( - contextInfo, - context, - unresolvedResource, - resolveContext, - (err, resolvedResource) => { - if (!err && resolvedResource) { - const resource = parseResource(resolvedResource).path.replace( - /^.*[\\/]/, - "" - ); - return callback( - null, - `Did you mean '${resource}'? -BREAKING CHANGE: The request '${unresolvedResource}' failed to resolve only because it was resolved as fully specified -(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"'). -The extension in the request is mandatory for it to be fully specified. -Add the extension to the request.` - ); - } - callback(); - } - ); - }, - callback => { - if (!resolver.options.enforceExtension) return callback(); - resolver - .withOptions({ - enforceExtension: false, - extensions: [] - }) - .resolve( - contextInfo, - context, - unresolvedResource, - resolveContext, - (err, resolvedResource) => { - if (!err && resolvedResource) { - let hint = ""; - const match = /(\.[^.]+)(\?|$)/.exec(unresolvedResource); - if (match) { - const fixedRequest = unresolvedResource.replace( - /(\.[^.]+)(\?|$)/, - "$2" - ); - if (resolver.options.extensions.has(match[1])) { - hint = `Did you mean '${fixedRequest}'?`; - } else { - hint = `Did you mean '${fixedRequest}'? Also note that '${match[1]}' is not in 'resolve.extensions' yet and need to be added for this to work?`; - } - } else { - hint = `Did you mean to omit the extension or to remove 'resolve.enforceExtension'?`; - } - return callback( - null, - `The request '${unresolvedResource}' failed to resolve only because 'resolve.enforceExtension' was specified. -${hint} -Including the extension in the request is no longer possible. Did you mean to enforce including the extension in requests with 'resolve.extensions: []' instead?` - ); - } - callback(); - } - ); - }, - callback => { - if ( - /^\.\.?\//.test(unresolvedResource) || - resolver.options.preferRelative - ) { - return callback(); - } - resolver.resolve( - contextInfo, - context, - `./${unresolvedResource}`, - resolveContext, - (err, resolvedResource) => { - if (err || !resolvedResource) return callback(); - const moduleDirectories = resolver.options.modules - .map(m => (Array.isArray(m) ? m.join(", ") : m)) - .join(", "); - callback( - null, - `Did you mean './${unresolvedResource}'? -Requests that should resolve in the current directory need to start with './'. -Requests that start with a name are treated as module requests and resolve within module directories (${moduleDirectories}). -If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.` - ); - } - ); - } - ], - (err, hints) => { - if (err) return callback(err); - callback(null, hints.filter(Boolean)); - } - ); - } - - resolveRequestArray( - contextInfo, - context, - array, - resolver, - resolveContext, - callback - ) { - if (array.length === 0) return callback(null, array); - asyncLib.map( - array, - (item, callback) => { - resolver.resolve( - contextInfo, - context, - item.loader, - resolveContext, - (err, result) => { - if ( - err && - /^[^/]*$/.test(item.loader) && - !/-loader$/.test(item.loader) - ) { - return resolver.resolve( - contextInfo, - context, - item.loader + "-loader", - resolveContext, - err2 => { - if (!err2) { - err.message = - err.message + - "\n" + - "BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" + - ` You need to specify '${item.loader}-loader' instead of '${item.loader}',\n` + - " see https://webpack.js.org/migrate/3/#automatic-loader-module-name-extension-removed"; - } - callback(err); - } - ); - } - if (err) return callback(err); - - const parsedResult = identToLoaderRequest(result); - const resolved = { - loader: parsedResult.loader, - options: - item.options === undefined - ? parsedResult.options - : item.options, - ident: item.options === undefined ? undefined : item.ident - }; - return callback(null, resolved); - } - ); - }, - callback - ); - } - - getParser(type, parserOptions = EMPTY_PARSER_OPTIONS) { - let cache = this.parserCache.get(type); - - if (cache === undefined) { - cache = new WeakMap(); - this.parserCache.set(type, cache); - } - - let parser = cache.get(parserOptions); - - if (parser === undefined) { - parser = this.createParser(type, parserOptions); - cache.set(parserOptions, parser); - } - - return parser; - } - - /** - * @param {string} type type - * @param {{[k: string]: any}} parserOptions parser options - * @returns {Parser} parser - */ - createParser(type, parserOptions = {}) { - parserOptions = mergeGlobalOptions( - this._globalParserOptions, - type, - parserOptions - ); - const parser = this.hooks.createParser.for(type).call(parserOptions); - if (!parser) { - throw new Error(`No parser registered for ${type}`); - } - this.hooks.parser.for(type).call(parser, parserOptions); - return parser; - } - - getGenerator(type, generatorOptions = EMPTY_GENERATOR_OPTIONS) { - let cache = this.generatorCache.get(type); - - if (cache === undefined) { - cache = new WeakMap(); - this.generatorCache.set(type, cache); - } - - let generator = cache.get(generatorOptions); - - if (generator === undefined) { - generator = this.createGenerator(type, generatorOptions); - cache.set(generatorOptions, generator); - } - - return generator; - } - - createGenerator(type, generatorOptions = {}) { - generatorOptions = mergeGlobalOptions( - this._globalGeneratorOptions, - type, - generatorOptions - ); - const generator = this.hooks.createGenerator - .for(type) - .call(generatorOptions); - if (!generator) { - throw new Error(`No generator registered for ${type}`); - } - this.hooks.generator.for(type).call(generator, generatorOptions); - return generator; - } - - getResolver(type, resolveOptions) { - return this.resolverFactory.get(type, resolveOptions); - } -} - -module.exports = NormalModuleFactory; +module.exports = AssetSourceParser; /***/ }), -/***/ 30633: +/***/ 19684: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -58162,112 +58577,152 @@ module.exports = NormalModuleFactory; -const { join, dirname } = __webpack_require__(17139); +const { RawSource } = __webpack_require__(51255); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {function(TODO): void} ModuleReplacer */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ -class NormalModuleReplacementPlugin { +const TYPES = new Set(["javascript"]); + +class RawDataUrlModule extends Module { /** - * Create an instance of the plugin - * @param {RegExp} resourceRegExp the resource matcher - * @param {string|ModuleReplacer} newResource the resource replacement + * @param {string} url raw url + * @param {string} identifier unique identifier + * @param {string=} readableIdentifier readable identifier */ - constructor(resourceRegExp, newResource) { - this.resourceRegExp = resourceRegExp; - this.newResource = newResource; + constructor(url, identifier, readableIdentifier) { + super("asset/raw-data-url", null); + this.url = url; + this.urlBuffer = url ? Buffer.from(url) : undefined; + this.identifierStr = identifier || this.url; + this.readableIdentifierStr = readableIdentifier || this.identifierStr; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @returns {Set} types available (do not mutate) */ - apply(compiler) { - const resourceRegExp = this.resourceRegExp; - const newResource = this.newResource; - compiler.hooks.normalModuleFactory.tap( - "NormalModuleReplacementPlugin", - nmf => { - nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => { - if (resourceRegExp.test(result.request)) { - if (typeof newResource === "function") { - newResource(result); - } else { - result.request = newResource; - } - } - }); - nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => { - const createData = result.createData; - if (resourceRegExp.test(createData.resource)) { - if (typeof newResource === "function") { - newResource(result); - } else { - const fs = compiler.inputFileSystem; - if ( - newResource.startsWith("/") || - (newResource.length > 1 && newResource[1] === ":") - ) { - createData.resource = newResource; - } else { - createData.resource = join( - fs, - dirname(fs, createData.resource), - newResource - ); - } - } - } - }); - } - ); + getSourceTypes() { + return TYPES; } -} -module.exports = NormalModuleReplacementPlugin; + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this.identifierStr; + } + /** + * @param {string=} type the source type for which the size should be estimated + * @returns {number} the estimated size of the module (must be non-zero) + */ + size(type) { + if (this.url === undefined) this.url = this.urlBuffer.toString(); + return Math.max(1, this.url.length); + } -/***/ }), + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.readableIdentifierStr); + } -/***/ 80057: -/***/ (function(__unused_webpack_module, exports) { + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, !this.buildMeta); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {function(WebpackError=): void} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = { + cacheable: true + }; + callback(); + } + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration(context) { + if (this.url === undefined) this.url = this.urlBuffer.toString(); + const sources = new Map(); + sources.set( + "javascript", + new RawSource(`module.exports = ${JSON.stringify(this.url)};`) + ); + const data = new Map(); + data.set("url", this.urlBuffer); + const runtimeRequirements = new Set(); + runtimeRequirements.add(RuntimeGlobals.module); + return { sources, runtimeRequirements, data }; + } + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + hash.update(this.urlBuffer); + super.updateHash(hash, context); + } -exports.STAGE_BASIC = -10; -exports.STAGE_DEFAULT = 0; -exports.STAGE_ADVANCED = 10; + serialize(context) { + const { write } = context; + write(this.urlBuffer); + write(this.identifierStr); + write(this.readableIdentifierStr); -/***/ }), + super.serialize(context); + } -/***/ 81426: -/***/ (function(module) { + deserialize(context) { + const { read } = context; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.urlBuffer = read(); + this.identifierStr = read(); + this.readableIdentifierStr = read(); + super.deserialize(context); + } +} +makeSerializable(RawDataUrlModule, "webpack/lib/asset/RawDataUrlModule"); -class OptionsApply { - process(options, compiler) {} -} -module.exports = OptionsApply; +module.exports = RawDataUrlModule; /***/ }), -/***/ 11715: +/***/ 41153: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -58278,42 +58733,73 @@ module.exports = OptionsApply; -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./NormalModule")} NormalModule */ +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); -/** @typedef {Record} PreparsedAst */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ /** - * @typedef {Object} ParserStateBase - * @property {string | Buffer} source - * @property {NormalModule} current - * @property {NormalModule} module - * @property {Compilation} compilation - * @property {{[k: string]: any}} options + * @typedef {GenerateContext} Context */ +class AwaitDependenciesInitFragment extends InitFragment { + /** + * @param {Set} promises the promises that should be awaited + */ + constructor(promises) { + super( + undefined, + InitFragment.STAGE_ASYNC_DEPENDENCIES, + 0, + "await-dependencies" + ); + this.promises = promises; + } -/** @typedef {Record & ParserStateBase} ParserState */ + merge(other) { + const promises = new Set(this.promises); + for (const p of other.promises) { + promises.add(p); + } + return new AwaitDependenciesInitFragment(promises); + } -class Parser { - /* istanbul ignore next */ /** - * @abstract - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state + * @param {Context} context context + * @returns {string|Source} the source code that will be included as initialization code */ - parse(source, state) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + getContent({ runtimeRequirements }) { + runtimeRequirements.add(RuntimeGlobals.module); + const promises = this.promises; + if (promises.size === 0) { + return ""; + } + if (promises.size === 1) { + for (const p of promises) { + return Template.asString([ + `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${p}]);`, + `${p} = (__webpack_async_dependencies__.then ? await __webpack_async_dependencies__ : __webpack_async_dependencies__)[0];`, + "" + ]); + } + } + const sepPromises = Array.from(promises).join(", "); + // TODO check if destructuring is supported + return Template.asString([ + `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${sepPromises}]);`, + `([${sepPromises}] = __webpack_async_dependencies__.then ? await __webpack_async_dependencies__ : __webpack_async_dependencies__);`, + "" + ]); } } -module.exports = Parser; +module.exports = AwaitDependenciesInitFragment; /***/ }), -/***/ 73850: +/***/ 59498: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -58324,54 +58810,59 @@ module.exports = Parser; -const PrefetchDependency = __webpack_require__(31618); - -/** @typedef {import("./Compiler")} Compiler */ +const HarmonyImportDependency = __webpack_require__(57154); -class PrefetchPlugin { - constructor(context, request) { - if (request) { - this.context = context; - this.request = request; - } else { - this.context = null; - this.request = context; - } - } +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +class InferAsyncModulesPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap( - "PrefetchPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - PrefetchDependency, - normalModuleFactory - ); - } - ); - compiler.hooks.make.tapAsync("PrefetchPlugin", (compilation, callback) => { - compilation.addModuleChain( - this.context || compiler.context, - new PrefetchDependency(this.request), - err => { - callback(err); + compiler.hooks.compilation.tap("InferAsyncModulesPlugin", compilation => { + const { moduleGraph } = compilation; + compilation.hooks.finishModules.tap( + "InferAsyncModulesPlugin", + modules => { + /** @type {Set} */ + const queue = new Set(); + for (const module of modules) { + if (module.buildMeta && module.buildMeta.async) { + queue.add(module); + } + } + for (const module of queue) { + moduleGraph.setAsync(module); + for (const [ + originModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if ( + connections.some( + c => + c.dependency instanceof HarmonyImportDependency && + c.isTargetActive(undefined) + ) + ) { + queue.add(originModule); + } + } + } } ); }); } } -module.exports = PrefetchPlugin; +module.exports = InferAsyncModulesPlugin; /***/ }), -/***/ 13216: +/***/ 79233: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -58382,1112 +58873,1406 @@ module.exports = PrefetchPlugin; -const Compiler = __webpack_require__(70845); -const MultiCompiler = __webpack_require__(33370); -const NormalModule = __webpack_require__(39); -const createSchemaValidation = __webpack_require__(32540); -const { contextify } = __webpack_require__(82186); - -/** @typedef {import("../declarations/plugins/ProgressPlugin").HandlerFunction} HandlerFunction */ -/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */ -/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */ - -const validate = createSchemaValidation( - __webpack_require__(57647), - () => __webpack_require__(75202), - { - name: "Progress Plugin", - baseDataPath: "options" - } -); -const median3 = (a, b, c) => { - return a + b + c - Math.max(a, b, c) - Math.min(a, b, c); -}; +const AsyncDependencyToInitialChunkError = __webpack_require__(30111); +const { connectChunkGroupParentAndChild } = __webpack_require__(37234); +const ModuleGraphConnection = __webpack_require__(40639); +const { getEntryRuntime, mergeRuntime } = __webpack_require__(17156); -const createDefaultHandler = (profile, logger) => { - /** @type {{ value: string, time: number }[]} */ - const lastStateInfo = []; +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Entrypoint")} Entrypoint */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleGraph")} ModuleGraph */ +/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("./logging/Logger").Logger} Logger */ +/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ - const defaultHandler = (percentage, msg, ...args) => { - if (profile) { - if (percentage === 0) { - lastStateInfo.length = 0; - } - const fullState = [msg, ...args]; - const state = fullState.map(s => s.replace(/\d+\/\d+ /g, "")); - const now = Date.now(); - const len = Math.max(state.length, lastStateInfo.length); - for (let i = len; i >= 0; i--) { - const stateItem = i < state.length ? state[i] : undefined; - const lastStateItem = - i < lastStateInfo.length ? lastStateInfo[i] : undefined; - if (lastStateItem) { - if (stateItem !== lastStateItem.value) { - const diff = now - lastStateItem.time; - if (lastStateItem.value) { - let reportState = lastStateItem.value; - if (i > 0) { - reportState = lastStateInfo[i - 1].value + " > " + reportState; - } - const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`; - const d = diff; - // This depends on timing so we ignore it for coverage - /* istanbul ignore next */ - { - if (d > 10000) { - logger.error(stateMsg); - } else if (d > 1000) { - logger.warn(stateMsg); - } else if (d > 10) { - logger.info(stateMsg); - } else if (d > 5) { - logger.log(stateMsg); - } else { - logger.debug(stateMsg); - } - } - } - if (stateItem === undefined) { - lastStateInfo.length = i; - } else { - lastStateItem.value = stateItem; - lastStateItem.time = now; - lastStateInfo.length = i + 1; - } - } - } else { - lastStateInfo[i] = { - value: stateItem, - time: now - }; - } - } - } - logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args); - if (percentage === 1 || (!msg && args.length === 0)) logger.status(); - }; +/** + * @typedef {Object} QueueItem + * @property {number} action + * @property {DependenciesBlock} block + * @property {Module} module + * @property {Chunk} chunk + * @property {ChunkGroup} chunkGroup + * @property {ChunkGroupInfo} chunkGroupInfo + */ - return defaultHandler; -}; +/** @typedef {Set & { plus: Set }} ModuleSetPlus */ /** - * @callback ReportProgress - * @param {number} p - * @param {...string[]} [args] - * @returns {void} + * @typedef {Object} ChunkGroupInfo + * @property {ChunkGroup} chunkGroup the chunk group + * @property {RuntimeSpec} runtime the runtimes + * @property {ModuleSetPlus} minAvailableModules current minimal set of modules available at this point + * @property {boolean} minAvailableModulesOwned true, if minAvailableModules is owned and can be modified + * @property {ModuleSetPlus[]} availableModulesToBeMerged enqueued updates to the minimal set of available modules + * @property {Set=} skippedItems modules that were skipped because module is already available in parent chunks (need to reconsider when minAvailableModules is shrinking) + * @property {Set<[Module, ConnectionState]>=} skippedModuleConnections referenced modules that where skipped because they were not active in this runtime + * @property {ModuleSetPlus} resultingAvailableModules set of modules available including modules from this chunk group + * @property {Set} children set of children chunk groups, that will be revisited when availableModules shrink + * @property {Set} availableSources set of chunk groups that are the source for minAvailableModules + * @property {Set} availableChildren set of chunk groups which depend on the this chunk group as availableSource + * @property {number} preOrderIndex next pre order index + * @property {number} postOrderIndex next post order index + * @property {boolean} chunkLoading has a chunk loading mechanism + * @property {boolean} asyncChunks create async chunks */ -/** @type {WeakMap} */ -const progressReporters = new WeakMap(); +/** + * @typedef {Object} BlockChunkGroupConnection + * @property {ChunkGroupInfo} originChunkGroupInfo origin chunk group + * @property {ChunkGroup} chunkGroup referenced chunk group + */ -class ProgressPlugin { - /** - * @param {Compiler} compiler the current compiler - * @returns {ReportProgress} a progress reporter, if any - */ - static getReporter(compiler) { - return progressReporters.get(compiler); - } +const EMPTY_SET = /** @type {ModuleSetPlus} */ (new Set()); +EMPTY_SET.plus = EMPTY_SET; - /** - * @param {ProgressPluginArgument} options options - */ - constructor(options = {}) { - if (typeof options === "function") { - options = { - handler: options - }; - } +/** + * @param {ModuleSetPlus} a first set + * @param {ModuleSetPlus} b second set + * @returns {number} cmp + */ +const bySetSize = (a, b) => { + return b.size + b.plus.size - a.size - a.plus.size; +}; - validate(options); - options = { ...ProgressPlugin.defaultOptions, ...options }; +const extractBlockModules = (module, moduleGraph, runtime, blockModulesMap) => { + let blockCache; + let modules; - this.profile = options.profile; - this.handler = options.handler; - this.modulesCount = options.modulesCount; - this.dependenciesCount = options.dependenciesCount; - this.showEntries = options.entries; - this.showModules = options.modules; - this.showDependencies = options.dependencies; - this.showActiveModules = options.activeModules; - this.percentBy = options.percentBy; - } + const arrays = []; - /** - * @param {Compiler | MultiCompiler} compiler webpack compiler - * @returns {void} - */ - apply(compiler) { - const handler = - this.handler || - createDefaultHandler( - this.profile, - compiler.getInfrastructureLogger("webpack.Progress") - ); - if (compiler instanceof MultiCompiler) { - this._applyOnMultiCompiler(compiler, handler); - } else if (compiler instanceof Compiler) { - this._applyOnCompiler(compiler, handler); + const queue = [module]; + while (queue.length > 0) { + const block = queue.pop(); + const arr = []; + arrays.push(arr); + blockModulesMap.set(block, arr); + for (const b of block.blocks) { + queue.push(b); } } - /** - * @param {MultiCompiler} compiler webpack multi-compiler - * @param {HandlerFunction} handler function that executes for every progress step - * @returns {void} - */ - _applyOnMultiCompiler(compiler, handler) { - const states = compiler.compilers.map( - () => /** @type {[number, ...string[]]} */ ([0]) - ); - compiler.compilers.forEach((compiler, idx) => { - new ProgressPlugin((p, msg, ...args) => { - states[idx] = [p, msg, ...args]; - let sum = 0; - for (const [p] of states) sum += p; - handler(sum / states.length, `[${idx}] ${msg}`, ...args); - }).apply(compiler); - }); - } - - /** - * @param {Compiler} compiler webpack compiler - * @param {HandlerFunction} handler function that executes for every progress step - * @returns {void} - */ - _applyOnCompiler(compiler, handler) { - const showEntries = this.showEntries; - const showModules = this.showModules; - const showDependencies = this.showDependencies; - const showActiveModules = this.showActiveModules; - let lastActiveModule = ""; - let currentLoader = ""; - let lastModulesCount = 0; - let lastDependenciesCount = 0; - let lastEntriesCount = 0; - let modulesCount = 0; - let dependenciesCount = 0; - let entriesCount = 1; - let doneModules = 0; - let doneDependencies = 0; - let doneEntries = 0; - const activeModules = new Set(); - let lastUpdate = 0; + for (const connection of moduleGraph.getOutgoingConnections(module)) { + const d = connection.dependency; + // We skip connections without dependency + if (!d) continue; + const m = connection.module; + // We skip connections without Module pointer + if (!m) continue; + // We skip weak connections + if (connection.weak) continue; + const state = connection.getActiveState(runtime); + // We skip inactive connections + if (state === false) continue; - const updateThrottled = () => { - if (lastUpdate + 500 < Date.now()) update(); - }; + const block = moduleGraph.getParentBlock(d); + let index = moduleGraph.getParentBlockIndex(d); - const update = () => { - /** @type {string[]} */ - const items = []; - const percentByModules = - doneModules / - Math.max(lastModulesCount || this.modulesCount || 1, modulesCount); - const percentByEntries = - doneEntries / - Math.max(lastEntriesCount || this.dependenciesCount || 1, entriesCount); - const percentByDependencies = - doneDependencies / - Math.max(lastDependenciesCount || 1, dependenciesCount); - let percentageFactor; + // deprecated fallback + if (index < 0) { + index = block.dependencies.indexOf(d); + } - switch (this.percentBy) { - case "entries": - percentageFactor = percentByEntries; - break; - case "dependencies": - percentageFactor = percentByDependencies; - break; - case "modules": - percentageFactor = percentByModules; - break; - default: - percentageFactor = median3( - percentByModules, - percentByEntries, - percentByDependencies - ); - } + if (blockCache !== block) { + modules = blockModulesMap.get((blockCache = block)); + } - const percentage = 0.1 + percentageFactor * 0.55; + const i = index << 2; + modules[i] = m; + modules[i + 1] = state; + } - if (currentLoader) { - items.push( - `import loader ${contextify( - compiler.context, - currentLoader, - compiler.root - )}` - ); - } else { - const statItems = []; - if (showEntries) { - statItems.push(`${doneEntries}/${entriesCount} entries`); - } - if (showDependencies) { - statItems.push( - `${doneDependencies}/${dependenciesCount} dependencies` - ); - } - if (showModules) { - statItems.push(`${doneModules}/${modulesCount} modules`); - } - if (showActiveModules) { - statItems.push(`${activeModules.size} active`); + for (const modules of arrays) { + if (modules.length === 0) continue; + let indexMap; + let length = 0; + outer: for (let j = 0; j < modules.length; j += 2) { + const m = modules[j]; + if (m === undefined) continue; + const state = modules[j + 1]; + if (indexMap === undefined) { + let i = 0; + for (; i < length; i += 2) { + if (modules[i] === m) { + const merged = modules[i + 1]; + if (merged === true) continue outer; + modules[i + 1] = ModuleGraphConnection.addConnectionStates( + merged, + state + ); + } } - if (statItems.length > 0) { - items.push(statItems.join(" ")); + modules[length] = m; + length++; + modules[length] = state; + length++; + if (length > 30) { + // To avoid worse case performance, we will use an index map for + // linear cost access, which allows to maintain O(n) complexity + // while keeping allocations down to a minimum + indexMap = new Map(); + for (let i = 0; i < length; i += 2) { + indexMap.set(modules[i], i + 1); + } } - if (showActiveModules) { - items.push(lastActiveModule); + } else { + const idx = indexMap.get(m); + if (idx !== undefined) { + const merged = modules[idx]; + if (merged === true) continue outer; + modules[idx] = ModuleGraphConnection.addConnectionStates( + merged, + state + ); + } else { + modules[length] = m; + length++; + modules[length] = state; + indexMap.set(m, length); + length++; } } - handler(percentage, "building", ...items); - lastUpdate = Date.now(); - }; + } + modules.length = length; + } +}; - const factorizeAdd = () => { - dependenciesCount++; - if (dependenciesCount < 50 || dependenciesCount % 100 === 0) - updateThrottled(); - }; +/** + * + * @param {Logger} logger a logger + * @param {Compilation} compilation the compilation + * @param {Map} inputEntrypointsAndModules chunk groups which are processed with the modules + * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules + * @param {Map} blockConnections connection for blocks + * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks + * @param {Set} allCreatedChunkGroups filled with all chunk groups that are created here + */ +const visitModules = ( + logger, + compilation, + inputEntrypointsAndModules, + chunkGroupInfoMap, + blockConnections, + blocksWithNestedBlocks, + allCreatedChunkGroups +) => { + const { moduleGraph, chunkGraph, moduleMemCaches } = compilation; - const factorizeDone = () => { - doneDependencies++; - if (doneDependencies < 50 || doneDependencies % 100 === 0) - updateThrottled(); - }; + const blockModulesRuntimeMap = new Map(); - const moduleAdd = () => { - modulesCount++; - if (modulesCount < 50 || modulesCount % 100 === 0) updateThrottled(); - }; + /** @type {RuntimeSpec | false} */ + let blockModulesMapRuntime = false; + let blockModulesMap; - // only used when showActiveModules is set - const moduleBuild = module => { - const ident = module.identifier(); - if (ident) { - activeModules.add(ident); - lastActiveModule = ident; - update(); + /** + * + * @param {DependenciesBlock} block block + * @param {RuntimeSpec} runtime runtime + * @returns {(Module | ConnectionState)[]} block modules in flatten tuples + */ + const getBlockModules = (block, runtime) => { + if (blockModulesMapRuntime !== runtime) { + blockModulesMap = blockModulesRuntimeMap.get(runtime); + if (blockModulesMap === undefined) { + blockModulesMap = new Map(); + blockModulesRuntimeMap.set(runtime, blockModulesMap); } - }; - - const entryAdd = (entry, options) => { - entriesCount++; - if (entriesCount < 5 || entriesCount % 10 === 0) updateThrottled(); - }; - - const moduleDone = module => { - doneModules++; - if (showActiveModules) { - const ident = module.identifier(); - if (ident) { - activeModules.delete(ident); - if (lastActiveModule === ident) { - lastActiveModule = ""; - for (const m of activeModules) { - lastActiveModule = m; - } - update(); - return; - } + } + let blockModules = blockModulesMap.get(block); + if (blockModules !== undefined) return blockModules; + const module = /** @type {Module} */ (block.getRootBlock()); + const memCache = moduleMemCaches && moduleMemCaches.get(module); + if (memCache !== undefined) { + const map = memCache.provide( + "bundleChunkGraph.blockModules", + runtime, + () => { + logger.time("visitModules: prepare"); + const map = new Map(); + extractBlockModules(module, moduleGraph, runtime, map); + logger.timeAggregate("visitModules: prepare"); + return map; } - } - if (doneModules < 50 || doneModules % 100 === 0) updateThrottled(); - }; - - const entryDone = (entry, options) => { - doneEntries++; - update(); - }; - - const cache = compiler - .getCache("ProgressPlugin") - .getItemCache("counts", null); - - let cacheGetPromise; + ); + for (const [block, blockModules] of map) + blockModulesMap.set(block, blockModules); + return map.get(block); + } else { + logger.time("visitModules: prepare"); + extractBlockModules(module, moduleGraph, runtime, blockModulesMap); + blockModules = blockModulesMap.get(block); + logger.timeAggregate("visitModules: prepare"); + return blockModules; + } + }; - compiler.hooks.beforeCompile.tap("ProgressPlugin", () => { - if (!cacheGetPromise) { - cacheGetPromise = cache.getPromise().then( - data => { - if (data) { - lastModulesCount = lastModulesCount || data.modulesCount; - lastDependenciesCount = - lastDependenciesCount || data.dependenciesCount; - } - return data; - }, - err => { - // Ignore error - } - ); - } - }); + let statProcessedQueueItems = 0; + let statProcessedBlocks = 0; + let statConnectedChunkGroups = 0; + let statProcessedChunkGroupsForMerging = 0; + let statMergedAvailableModuleSets = 0; + let statForkedAvailableModules = 0; + let statForkedAvailableModulesCount = 0; + let statForkedAvailableModulesCountPlus = 0; + let statForkedMergedModulesCount = 0; + let statForkedMergedModulesCountPlus = 0; + let statForkedResultModulesCount = 0; + let statChunkGroupInfoUpdated = 0; + let statChildChunkGroupsReconnected = 0; - compiler.hooks.afterCompile.tapPromise("ProgressPlugin", compilation => { - if (compilation.compiler.isChild()) return Promise.resolve(); - return cacheGetPromise.then(async oldData => { - if ( - !oldData || - oldData.modulesCount !== modulesCount || - oldData.dependenciesCount !== dependenciesCount - ) { - await cache.storePromise({ modulesCount, dependenciesCount }); - } - }); - }); + let nextChunkGroupIndex = 0; + let nextFreeModulePreOrderIndex = 0; + let nextFreeModulePostOrderIndex = 0; - compiler.hooks.compilation.tap("ProgressPlugin", compilation => { - if (compilation.compiler.isChild()) return; - lastModulesCount = modulesCount; - lastEntriesCount = entriesCount; - lastDependenciesCount = dependenciesCount; - modulesCount = dependenciesCount = entriesCount = 0; - doneModules = doneDependencies = doneEntries = 0; + /** @type {Map} */ + const blockChunkGroups = new Map(); - compilation.factorizeQueue.hooks.added.tap( - "ProgressPlugin", - factorizeAdd - ); - compilation.factorizeQueue.hooks.result.tap( - "ProgressPlugin", - factorizeDone - ); + /** @type {Map} */ + const namedChunkGroups = new Map(); - compilation.addModuleQueue.hooks.added.tap("ProgressPlugin", moduleAdd); - compilation.processDependenciesQueue.hooks.result.tap( - "ProgressPlugin", - moduleDone - ); + /** @type {Map} */ + const namedAsyncEntrypoints = new Map(); - if (showActiveModules) { - compilation.hooks.buildModule.tap("ProgressPlugin", moduleBuild); - } + const ADD_AND_ENTER_ENTRY_MODULE = 0; + const ADD_AND_ENTER_MODULE = 1; + const ENTER_MODULE = 2; + const PROCESS_BLOCK = 3; + const PROCESS_ENTRY_BLOCK = 4; + const LEAVE_MODULE = 5; - compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd); - compilation.hooks.failedEntry.tap("ProgressPlugin", entryDone); - compilation.hooks.succeedEntry.tap("ProgressPlugin", entryDone); + /** @type {QueueItem[]} */ + let queue = []; - // avoid dynamic require if bundled with webpack - // @ts-expect-error - if (false) {} + /** @type {Map>} */ + const queueConnect = new Map(); + /** @type {Set} */ + const chunkGroupsForCombining = new Set(); - const hooks = { - finishModules: "finish module graph", - seal: "plugins", - optimizeDependencies: "dependencies optimization", - afterOptimizeDependencies: "after dependencies optimization", - beforeChunks: "chunk graph", - afterChunks: "after chunk graph", - optimize: "optimizing", - optimizeModules: "module optimization", - afterOptimizeModules: "after module optimization", - optimizeChunks: "chunk optimization", - afterOptimizeChunks: "after chunk optimization", - optimizeTree: "module and chunk tree optimization", - afterOptimizeTree: "after module and chunk tree optimization", - optimizeChunkModules: "chunk modules optimization", - afterOptimizeChunkModules: "after chunk modules optimization", - reviveModules: "module reviving", - beforeModuleIds: "before module ids", - moduleIds: "module ids", - optimizeModuleIds: "module id optimization", - afterOptimizeModuleIds: "module id optimization", - reviveChunks: "chunk reviving", - beforeChunkIds: "before chunk ids", - chunkIds: "chunk ids", - optimizeChunkIds: "chunk id optimization", - afterOptimizeChunkIds: "after chunk id optimization", - recordModules: "record modules", - recordChunks: "record chunks", - beforeModuleHash: "module hashing", - beforeCodeGeneration: "code generation", - beforeRuntimeRequirements: "runtime requirements", - beforeHash: "hashing", - afterHash: "after hashing", - recordHash: "record hash", - beforeModuleAssets: "module assets processing", - beforeChunkAssets: "chunk assets processing", - processAssets: "asset processing", - afterProcessAssets: "after asset optimization", - record: "recording", - afterSeal: "after seal" - }; - const numberOfHooks = Object.keys(hooks).length; - Object.keys(hooks).forEach((name, idx) => { - const title = hooks[name]; - const percentage = (idx / numberOfHooks) * 0.25 + 0.7; - compilation.hooks[name].intercept({ - name: "ProgressPlugin", - call() { - handler(percentage, "sealing", title); - }, - done() { - progressReporters.set(compiler, undefined); - handler(percentage, "sealing", title); - }, - result() { - handler(percentage, "sealing", title); - }, - error() { - handler(percentage, "sealing", title); - }, - tap(tap) { - // p is percentage from 0 to 1 - // args is any number of messages in a hierarchical matter - progressReporters.set(compilation.compiler, (p, ...args) => { - handler(percentage, "sealing", title, tap.name, ...args); - }); - handler(percentage, "sealing", title, tap.name); - } - }); - }); - }); - compiler.hooks.make.intercept({ - name: "ProgressPlugin", - call() { - handler(0.1, "building"); - }, - done() { - handler(0.65, "building"); - } - }); - const interceptHook = (hook, progress, category, name) => { - hook.intercept({ - name: "ProgressPlugin", - call() { - handler(progress, category, name); - }, - done() { - progressReporters.set(compiler, undefined); - handler(progress, category, name); - }, - result() { - handler(progress, category, name); - }, - error() { - handler(progress, category, name); - }, - tap(tap) { - progressReporters.set(compiler, (p, ...args) => { - handler(progress, category, name, tap.name, ...args); - }); - handler(progress, category, name, tap.name); - } - }); - }; - compiler.cache.hooks.endIdle.intercept({ - name: "ProgressPlugin", - call() { - handler(0, ""); - } - }); - interceptHook(compiler.cache.hooks.endIdle, 0.01, "cache", "end idle"); - compiler.hooks.initialize.intercept({ - name: "ProgressPlugin", - call() { - handler(0, ""); - } - }); - interceptHook(compiler.hooks.initialize, 0.01, "setup", "initialize"); - interceptHook(compiler.hooks.beforeRun, 0.02, "setup", "before run"); - interceptHook(compiler.hooks.run, 0.03, "setup", "run"); - interceptHook(compiler.hooks.watchRun, 0.03, "setup", "watch run"); - interceptHook( - compiler.hooks.normalModuleFactory, - 0.04, - "setup", - "normal module factory" - ); - interceptHook( - compiler.hooks.contextModuleFactory, - 0.05, - "setup", - "context module factory" - ); - interceptHook( - compiler.hooks.beforeCompile, - 0.06, - "setup", - "before compile" + // Fill queue with entrypoint modules + // Create ChunkGroupInfo for entrypoints + for (const [chunkGroup, modules] of inputEntrypointsAndModules) { + const runtime = getEntryRuntime( + compilation, + chunkGroup.name, + chunkGroup.options ); - interceptHook(compiler.hooks.compile, 0.07, "setup", "compile"); - interceptHook(compiler.hooks.thisCompilation, 0.08, "setup", "compilation"); - interceptHook(compiler.hooks.compilation, 0.09, "setup", "compilation"); - interceptHook(compiler.hooks.finishMake, 0.69, "building", "finish"); - interceptHook(compiler.hooks.emit, 0.95, "emitting", "emit"); - interceptHook(compiler.hooks.afterEmit, 0.98, "emitting", "after emit"); - interceptHook(compiler.hooks.done, 0.99, "done", "plugins"); - compiler.hooks.done.intercept({ - name: "ProgressPlugin", - done() { - handler(0.99, ""); + /** @type {ChunkGroupInfo} */ + const chunkGroupInfo = { + chunkGroup, + runtime, + minAvailableModules: undefined, + minAvailableModulesOwned: false, + availableModulesToBeMerged: [], + skippedItems: undefined, + resultingAvailableModules: undefined, + children: undefined, + availableSources: undefined, + availableChildren: undefined, + preOrderIndex: 0, + postOrderIndex: 0, + chunkLoading: + chunkGroup.options.chunkLoading !== undefined + ? chunkGroup.options.chunkLoading !== false + : compilation.outputOptions.chunkLoading !== false, + asyncChunks: + chunkGroup.options.asyncChunks !== undefined + ? chunkGroup.options.asyncChunks + : compilation.outputOptions.asyncChunks !== false + }; + chunkGroup.index = nextChunkGroupIndex++; + if (chunkGroup.getNumberOfParents() > 0) { + // minAvailableModules for child entrypoints are unknown yet, set to undefined. + // This means no module is added until other sets are merged into + // this minAvailableModules (by the parent entrypoints) + const skippedItems = new Set(); + for (const module of modules) { + skippedItems.add(module); } - }); - interceptHook( - compiler.cache.hooks.storeBuildDependencies, - 0.99, - "cache", - "store build dependencies" - ); - interceptHook(compiler.cache.hooks.shutdown, 0.99, "cache", "shutdown"); - interceptHook(compiler.cache.hooks.beginIdle, 0.99, "cache", "begin idle"); - interceptHook( - compiler.hooks.watchClose, - 0.99, - "end", - "closing watch compilation" - ); - compiler.cache.hooks.beginIdle.intercept({ - name: "ProgressPlugin", - done() { - handler(1, ""); + chunkGroupInfo.skippedItems = skippedItems; + chunkGroupsForCombining.add(chunkGroupInfo); + } else { + // The application may start here: We start with an empty list of available modules + chunkGroupInfo.minAvailableModules = EMPTY_SET; + const chunk = chunkGroup.getEntrypointChunk(); + for (const module of modules) { + queue.push({ + action: ADD_AND_ENTER_MODULE, + block: module, + module, + chunk, + chunkGroup, + chunkGroupInfo + }); } - }); - compiler.cache.hooks.shutdown.intercept({ - name: "ProgressPlugin", - done() { - handler(1, ""); + } + chunkGroupInfoMap.set(chunkGroup, chunkGroupInfo); + if (chunkGroup.name) { + namedChunkGroups.set(chunkGroup.name, chunkGroupInfo); + } + } + // Fill availableSources with parent-child dependencies between entrypoints + for (const chunkGroupInfo of chunkGroupsForCombining) { + const { chunkGroup } = chunkGroupInfo; + chunkGroupInfo.availableSources = new Set(); + for (const parent of chunkGroup.parentsIterable) { + const parentChunkGroupInfo = chunkGroupInfoMap.get(parent); + chunkGroupInfo.availableSources.add(parentChunkGroupInfo); + if (parentChunkGroupInfo.availableChildren === undefined) { + parentChunkGroupInfo.availableChildren = new Set(); } - }); + parentChunkGroupInfo.availableChildren.add(chunkGroupInfo); + } } -} - -ProgressPlugin.defaultOptions = { - profile: false, - modulesCount: 5000, - dependenciesCount: 10000, - modules: true, - dependencies: true, - activeModules: false, - entries: true -}; - -module.exports = ProgressPlugin; - - -/***/ }), - -/***/ 38309: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - + // pop() is used to read from the queue + // so it need to be reversed to be iterated in + // correct order + queue.reverse(); -const ConstDependency = __webpack_require__(76911); -const ProvidedDependency = __webpack_require__(95770); -const { approve } = __webpack_require__(93998); + /** @type {Set} */ + const outdatedChunkGroupInfo = new Set(); + /** @type {Set} */ + const chunkGroupsForMerging = new Set(); + /** @type {QueueItem[]} */ + let queueDelayed = []; -/** @typedef {import("./Compiler")} Compiler */ + /** @type {[Module, ConnectionState][]} */ + const skipConnectionBuffer = []; + /** @type {Module[]} */ + const skipBuffer = []; + /** @type {QueueItem[]} */ + const queueBuffer = []; -class ProvidePlugin { - /** - * @param {Record} definitions the provided identifiers - */ - constructor(definitions) { - this.definitions = definitions; - } + /** @type {Module} */ + let module; + /** @type {Chunk} */ + let chunk; + /** @type {ChunkGroup} */ + let chunkGroup; + /** @type {DependenciesBlock} */ + let block; + /** @type {ChunkGroupInfo} */ + let chunkGroupInfo; + // For each async Block in graph /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {AsyncDependenciesBlock} b iterating over each Async DepBlock * @returns {void} */ - apply(compiler) { - const definitions = this.definitions; - compiler.hooks.compilation.tap( - "ProvidePlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); - compilation.dependencyFactories.set( - ProvidedDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ProvidedDependency, - new ProvidedDependency.Template() - ); - const handler = (parser, parserOptions) => { - Object.keys(definitions).forEach(name => { - const request = [].concat(definitions[name]); - const splittedName = name.split("."); - if (splittedName.length > 0) { - splittedName.slice(1).forEach((_, i) => { - const name = splittedName.slice(0, i + 1).join("."); - parser.hooks.canRename.for(name).tap("ProvidePlugin", approve); - }); - } + const iteratorBlock = b => { + // 1. We create a chunk group with single chunk in it for this Block + // but only once (blockChunkGroups map) + let cgi = blockChunkGroups.get(b); + /** @type {ChunkGroup} */ + let c; + /** @type {Entrypoint} */ + let entrypoint; + const entryOptions = b.groupOptions && b.groupOptions.entryOptions; + if (cgi === undefined) { + const chunkName = (b.groupOptions && b.groupOptions.name) || b.chunkName; + if (entryOptions) { + cgi = namedAsyncEntrypoints.get(chunkName); + if (!cgi) { + entrypoint = compilation.addAsyncEntrypoint( + entryOptions, + module, + b.loc, + b.request + ); + entrypoint.index = nextChunkGroupIndex++; + cgi = { + chunkGroup: entrypoint, + runtime: entrypoint.options.runtime || entrypoint.name, + minAvailableModules: EMPTY_SET, + minAvailableModulesOwned: false, + availableModulesToBeMerged: [], + skippedItems: undefined, + resultingAvailableModules: undefined, + children: undefined, + availableSources: undefined, + availableChildren: undefined, + preOrderIndex: 0, + postOrderIndex: 0, + chunkLoading: + entryOptions.chunkLoading !== undefined + ? entryOptions.chunkLoading !== false + : chunkGroupInfo.chunkLoading, + asyncChunks: + entryOptions.asyncChunks !== undefined + ? entryOptions.asyncChunks + : chunkGroupInfo.asyncChunks + }; + chunkGroupInfoMap.set(entrypoint, cgi); - parser.hooks.expression.for(name).tap("ProvidePlugin", expr => { - const nameIdentifier = name.includes(".") - ? `__webpack_provided_${name.replace(/\./g, "_dot_")}` - : name; - const dep = new ProvidedDependency( - request[0], - nameIdentifier, - request.slice(1), - expr.range - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return true; - }); + chunkGraph.connectBlockAndChunkGroup(b, entrypoint); + if (chunkName) { + namedAsyncEntrypoints.set(chunkName, cgi); + } + } else { + entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup); + // TODO merge entryOptions + entrypoint.addOrigin(module, b.loc, b.request); + chunkGraph.connectBlockAndChunkGroup(b, entrypoint); + } - parser.hooks.call.for(name).tap("ProvidePlugin", expr => { - const nameIdentifier = name.includes(".") - ? `__webpack_provided_${name.replace(/\./g, "_dot_")}` - : name; - const dep = new ProvidedDependency( - request[0], - nameIdentifier, - request.slice(1), - expr.callee.range - ); - dep.loc = expr.callee.loc; - parser.state.module.addDependency(dep); - parser.walkExpressions(expr.arguments); - return true; - }); - }); - }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("ProvidePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("ProvidePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("ProvidePlugin", handler); + // 2. We enqueue the DependenciesBlock for traversal + queueDelayed.push({ + action: PROCESS_ENTRY_BLOCK, + block: b, + module: module, + chunk: entrypoint.chunks[0], + chunkGroup: entrypoint, + chunkGroupInfo: cgi + }); + } else if (!chunkGroupInfo.asyncChunks || !chunkGroupInfo.chunkLoading) { + // Just queue the block into the current chunk group + queue.push({ + action: PROCESS_BLOCK, + block: b, + module: module, + chunk, + chunkGroup, + chunkGroupInfo + }); + } else { + cgi = chunkName && namedChunkGroups.get(chunkName); + if (!cgi) { + c = compilation.addChunkInGroup( + b.groupOptions || b.chunkName, + module, + b.loc, + b.request + ); + c.index = nextChunkGroupIndex++; + cgi = { + chunkGroup: c, + runtime: chunkGroupInfo.runtime, + minAvailableModules: undefined, + minAvailableModulesOwned: undefined, + availableModulesToBeMerged: [], + skippedItems: undefined, + resultingAvailableModules: undefined, + children: undefined, + availableSources: undefined, + availableChildren: undefined, + preOrderIndex: 0, + postOrderIndex: 0, + chunkLoading: chunkGroupInfo.chunkLoading, + asyncChunks: chunkGroupInfo.asyncChunks + }; + allCreatedChunkGroups.add(c); + chunkGroupInfoMap.set(c, cgi); + if (chunkName) { + namedChunkGroups.set(chunkName, cgi); + } + } else { + c = cgi.chunkGroup; + if (c.isInitial()) { + compilation.errors.push( + new AsyncDependencyToInitialChunkError(chunkName, module, b.loc) + ); + c = chunkGroup; + } + c.addOptions(b.groupOptions); + c.addOrigin(module, b.loc, b.request); + } + blockConnections.set(b, []); } - ); - } -} - -module.exports = ProvidePlugin; - - -/***/ }), - -/***/ 84929: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { OriginalSource, RawSource } = __webpack_require__(51255); -const Module = __webpack_require__(73208); -const makeSerializable = __webpack_require__(33032); - -/** @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("./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"]); - -class RawModule extends Module { - /** - * @param {string} source source code - * @param {string} identifier unique identifier - * @param {string=} readableIdentifier readable identifier - * @param {ReadonlySet=} runtimeRequirements runtime requirements needed for the source code - */ - constructor(source, identifier, readableIdentifier, runtimeRequirements) { - super("javascript/dynamic", null); - this.sourceStr = source; - this.identifierStr = identifier || this.sourceStr; - this.readableIdentifierStr = readableIdentifier || this.identifierStr; - this.runtimeRequirements = runtimeRequirements || null; - } - - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; - } + blockChunkGroups.set(b, cgi); + } else if (entryOptions) { + entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup); + } else { + c = cgi.chunkGroup; + } - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return this.identifierStr; - } + if (c !== undefined) { + // 2. We store the connection for the block + // to connect it later if needed + blockConnections.get(b).push({ + originChunkGroupInfo: chunkGroupInfo, + chunkGroup: c + }); - /** - * @param {string=} type the source type for which the size should be estimated - * @returns {number} the estimated size of the module (must be non-zero) - */ - size(type) { - return Math.max(1, this.sourceStr.length); - } + // 3. We enqueue the chunk group info creation/updating + let connectList = queueConnect.get(chunkGroupInfo); + if (connectList === undefined) { + connectList = new Set(); + queueConnect.set(chunkGroupInfo, connectList); + } + connectList.add(cgi); - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return requestShortener.shorten(this.readableIdentifierStr); - } + // TODO check if this really need to be done for each traversal + // or if it is enough when it's queued when created + // 4. We enqueue the DependenciesBlock for traversal + queueDelayed.push({ + action: PROCESS_BLOCK, + block: b, + module: module, + chunk: c.chunks[0], + chunkGroup: c, + chunkGroupInfo: cgi + }); + } else if (entrypoint !== undefined) { + chunkGroupInfo.chunkGroup.addAsyncEntrypoint(entrypoint); + } + }; /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @param {DependenciesBlock} block the block * @returns {void} */ - needBuild(context, callback) { - return callback(null, !this.buildMeta); - } + const processBlock = block => { + statProcessedBlocks++; + // get prepared block info + const blockModules = getBlockModules(block, chunkGroupInfo.runtime); - /** - * @param {WebpackOptions} options webpack options - * @param {Compilation} compilation the compilation - * @param {ResolverWithOptions} resolver the resolver - * @param {InputFileSystem} fs the file system - * @param {function(WebpackError=): void} callback callback function - * @returns {void} - */ - build(options, compilation, resolver, fs, callback) { - this.buildMeta = {}; - this.buildInfo = { - cacheable: true - }; - callback(); - } + if (blockModules !== undefined) { + const { minAvailableModules } = chunkGroupInfo; + // Buffer items because order need to be reversed to get indices correct + // Traverse all referenced modules + for (let i = 0; i < blockModules.length; i += 2) { + const refModule = /** @type {Module} */ (blockModules[i]); + if (chunkGraph.isModuleInChunk(refModule, chunk)) { + // skip early if already connected + continue; + } + const activeState = /** @type {ConnectionState} */ ( + blockModules[i + 1] + ); + if (activeState !== true) { + skipConnectionBuffer.push([refModule, activeState]); + if (activeState === false) continue; + } + if ( + activeState === true && + (minAvailableModules.has(refModule) || + minAvailableModules.plus.has(refModule)) + ) { + // already in parent chunks, skip it for now + skipBuffer.push(refModule); + continue; + } + // enqueue, then add and enter to be in the correct order + // this is relevant with circular dependencies + queueBuffer.push({ + action: activeState === true ? ADD_AND_ENTER_MODULE : PROCESS_BLOCK, + block: refModule, + module: refModule, + chunk, + chunkGroup, + chunkGroupInfo + }); + } + // Add buffered items in reverse order + if (skipConnectionBuffer.length > 0) { + let { skippedModuleConnections } = chunkGroupInfo; + if (skippedModuleConnections === undefined) { + chunkGroupInfo.skippedModuleConnections = skippedModuleConnections = + new Set(); + } + for (let i = skipConnectionBuffer.length - 1; i >= 0; i--) { + skippedModuleConnections.add(skipConnectionBuffer[i]); + } + skipConnectionBuffer.length = 0; + } + if (skipBuffer.length > 0) { + let { skippedItems } = chunkGroupInfo; + if (skippedItems === undefined) { + chunkGroupInfo.skippedItems = skippedItems = new Set(); + } + for (let i = skipBuffer.length - 1; i >= 0; i--) { + skippedItems.add(skipBuffer[i]); + } + skipBuffer.length = 0; + } + if (queueBuffer.length > 0) { + for (let i = queueBuffer.length - 1; i >= 0; i--) { + queue.push(queueBuffer[i]); + } + queueBuffer.length = 0; + } + } - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration(context) { - const sources = new Map(); - if (this.useSourceMap || this.useSimpleSourceMap) { - sources.set( - "javascript", - new OriginalSource(this.sourceStr, this.identifier()) - ); - } else { - sources.set("javascript", new RawSource(this.sourceStr)); + // Traverse all Blocks + for (const b of block.blocks) { + iteratorBlock(b); } - return { sources, runtimeRequirements: this.runtimeRequirements }; - } + + if (block.blocks.length > 0 && module !== block) { + blocksWithNestedBlocks.add(block); + } + }; /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context + * @param {DependenciesBlock} block the block * @returns {void} */ - updateHash(hash, context) { - hash.update(this.sourceStr); - super.updateHash(hash, context); - } - - serialize(context) { - const { write } = context; - - write(this.sourceStr); - write(this.identifierStr); - write(this.readableIdentifierStr); - write(this.runtimeRequirements); - - super.serialize(context); - } + const processEntryBlock = block => { + statProcessedBlocks++; + // get prepared block info + const blockModules = getBlockModules(block, chunkGroupInfo.runtime); - deserialize(context) { - const { read } = context; + if (blockModules !== undefined) { + // Traverse all referenced modules + for (let i = 0; i < blockModules.length; i += 2) { + const refModule = /** @type {Module} */ (blockModules[i]); + const activeState = /** @type {ConnectionState} */ ( + blockModules[i + 1] + ); + // enqueue, then add and enter to be in the correct order + // this is relevant with circular dependencies + queueBuffer.push({ + action: + activeState === true ? ADD_AND_ENTER_ENTRY_MODULE : PROCESS_BLOCK, + block: refModule, + module: refModule, + chunk, + chunkGroup, + chunkGroupInfo + }); + } + // Add buffered items in reverse order + if (queueBuffer.length > 0) { + for (let i = queueBuffer.length - 1; i >= 0; i--) { + queue.push(queueBuffer[i]); + } + queueBuffer.length = 0; + } + } - this.sourceStr = read(); - this.identifierStr = read(); - this.readableIdentifierStr = read(); - this.runtimeRequirements = read(); + // Traverse all Blocks + for (const b of block.blocks) { + iteratorBlock(b); + } - super.deserialize(context); - } -} + if (block.blocks.length > 0 && module !== block) { + blocksWithNestedBlocks.add(block); + } + }; -makeSerializable(RawModule, "webpack/lib/RawModule"); + const processQueue = () => { + while (queue.length) { + statProcessedQueueItems++; + const queueItem = queue.pop(); + module = queueItem.module; + block = queueItem.block; + chunk = queueItem.chunk; + chunkGroup = queueItem.chunkGroup; + chunkGroupInfo = queueItem.chunkGroupInfo; -module.exports = RawModule; + switch (queueItem.action) { + case ADD_AND_ENTER_ENTRY_MODULE: + chunkGraph.connectChunkAndEntryModule( + chunk, + module, + /** @type {Entrypoint} */ (chunkGroup) + ); + // fallthrough + case ADD_AND_ENTER_MODULE: { + if (chunkGraph.isModuleInChunk(module, chunk)) { + // already connected, skip it + break; + } + // We connect Module and Chunk + chunkGraph.connectChunkAndModule(chunk, module); + } + // fallthrough + case ENTER_MODULE: { + const index = chunkGroup.getModulePreOrderIndex(module); + if (index === undefined) { + chunkGroup.setModulePreOrderIndex( + module, + chunkGroupInfo.preOrderIndex++ + ); + } + if ( + moduleGraph.setPreOrderIndexIfUnset( + module, + nextFreeModulePreOrderIndex + ) + ) { + nextFreeModulePreOrderIndex++; + } -/***/ }), + // reuse queueItem + queueItem.action = LEAVE_MODULE; + queue.push(queueItem); + } + // fallthrough + case PROCESS_BLOCK: { + processBlock(block); + break; + } + case PROCESS_ENTRY_BLOCK: { + processEntryBlock(block); + break; + } + case LEAVE_MODULE: { + const index = chunkGroup.getModulePostOrderIndex(module); + if (index === undefined) { + chunkGroup.setModulePostOrderIndex( + module, + chunkGroupInfo.postOrderIndex++ + ); + } -/***/ 11094: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if ( + moduleGraph.setPostOrderIndexIfUnset( + module, + nextFreeModulePostOrderIndex + ) + ) { + nextFreeModulePostOrderIndex++; + } + break; + } + } + } + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const calculateResultingAvailableModules = chunkGroupInfo => { + if (chunkGroupInfo.resultingAvailableModules) + return chunkGroupInfo.resultingAvailableModules; + const minAvailableModules = chunkGroupInfo.minAvailableModules; + // Create a new Set of available modules at this point + // We want to be as lazy as possible. There are multiple ways doing this: + // Note that resultingAvailableModules is stored as "(a) + (b)" as it's a ModuleSetPlus + // - resultingAvailableModules = (modules of chunk) + (minAvailableModules + minAvailableModules.plus) + // - resultingAvailableModules = (minAvailableModules + modules of chunk) + (minAvailableModules.plus) + // We choose one depending on the size of minAvailableModules vs minAvailableModules.plus -const { compareNumbers } = __webpack_require__(29579); -const identifierUtils = __webpack_require__(82186); + let resultingAvailableModules; + if (minAvailableModules.size > minAvailableModules.plus.size) { + // resultingAvailableModules = (modules of chunk) + (minAvailableModules + minAvailableModules.plus) + resultingAvailableModules = + /** @type {Set & {plus: Set}} */ (new Set()); + for (const module of minAvailableModules.plus) + minAvailableModules.add(module); + minAvailableModules.plus = EMPTY_SET; + resultingAvailableModules.plus = minAvailableModules; + chunkGroupInfo.minAvailableModulesOwned = false; + } else { + // resultingAvailableModules = (minAvailableModules + modules of chunk) + (minAvailableModules.plus) + resultingAvailableModules = + /** @type {Set & {plus: Set}} */ ( + new Set(minAvailableModules) + ); + resultingAvailableModules.plus = minAvailableModules.plus; + } -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Module")} Module */ + // add the modules from the chunk group to the set + for (const chunk of chunkGroupInfo.chunkGroup.chunks) { + for (const m of chunkGraph.getChunkModulesIterable(chunk)) { + resultingAvailableModules.add(m); + } + } + return (chunkGroupInfo.resultingAvailableModules = + resultingAvailableModules); + }; -/** - * @typedef {Object} RecordsChunks - * @property {Record=} byName - * @property {Record=} bySource - * @property {number[]=} usedIds - */ + const processConnectQueue = () => { + // Figure out new parents for chunk groups + // to get new available modules for these children + for (const [chunkGroupInfo, targets] of queueConnect) { + // 1. Add new targets to the list of children + if (chunkGroupInfo.children === undefined) { + chunkGroupInfo.children = targets; + } else { + for (const target of targets) { + chunkGroupInfo.children.add(target); + } + } -/** - * @typedef {Object} RecordsModules - * @property {Record=} byIdentifier - * @property {Record=} bySource - * @property {number[]=} usedIds - */ + // 2. Calculate resulting available modules + const resultingAvailableModules = + calculateResultingAvailableModules(chunkGroupInfo); -/** - * @typedef {Object} Records - * @property {RecordsChunks=} chunks - * @property {RecordsModules=} modules - */ + const runtime = chunkGroupInfo.runtime; -class RecordIdsPlugin { - /** - * @param {Object} options Options object - * @param {boolean=} options.portableIds true, when ids need to be portable - */ - constructor(options) { - this.options = options || {}; - } + // 3. Update chunk group info + for (const target of targets) { + target.availableModulesToBeMerged.push(resultingAvailableModules); + chunkGroupsForMerging.add(target); + const oldRuntime = target.runtime; + const newRuntime = mergeRuntime(oldRuntime, runtime); + if (oldRuntime !== newRuntime) { + target.runtime = newRuntime; + outdatedChunkGroupInfo.add(target); + } + } - /** - * @param {Compiler} compiler the Compiler - * @returns {void} - */ - apply(compiler) { - const portableIds = this.options.portableIds; + statConnectedChunkGroups += targets.size; + } + queueConnect.clear(); + }; - const makePathsRelative = - identifierUtils.makePathsRelative.bindContextCache( - compiler.context, - compiler.root - ); + const processChunkGroupsForMerging = () => { + statProcessedChunkGroupsForMerging += chunkGroupsForMerging.size; - /** - * @param {Module} module the module - * @returns {string} the (portable) identifier - */ - const getModuleIdentifier = module => { - if (portableIds) { - return makePathsRelative(module.identifier()); - } - return module.identifier(); - }; + // Execute the merge + for (const info of chunkGroupsForMerging) { + const availableModulesToBeMerged = info.availableModulesToBeMerged; + let cachedMinAvailableModules = info.minAvailableModules; - compiler.hooks.compilation.tap("RecordIdsPlugin", compilation => { - compilation.hooks.recordModules.tap( - "RecordIdsPlugin", - /** - * @param {Module[]} modules the modules array - * @param {Records} records the records object - * @returns {void} - */ - (modules, records) => { - const chunkGraph = compilation.chunkGraph; - if (!records.modules) records.modules = {}; - if (!records.modules.byIdentifier) records.modules.byIdentifier = {}; - /** @type {Set} */ - const usedIds = new Set(); - for (const module of modules) { - const moduleId = chunkGraph.getModuleId(module); - if (typeof moduleId !== "number") continue; - const identifier = getModuleIdentifier(module); - records.modules.byIdentifier[identifier] = moduleId; - usedIds.add(moduleId); - } - records.modules.usedIds = Array.from(usedIds).sort(compareNumbers); - } - ); - compilation.hooks.reviveModules.tap( - "RecordIdsPlugin", - /** - * @param {Module[]} modules the modules array - * @param {Records} records the records object - * @returns {void} - */ - (modules, records) => { - if (!records.modules) return; - if (records.modules.byIdentifier) { - const chunkGraph = compilation.chunkGraph; - /** @type {Set} */ - const usedIds = new Set(); - for (const module of modules) { - const moduleId = chunkGraph.getModuleId(module); - if (moduleId !== null) continue; - const identifier = getModuleIdentifier(module); - const id = records.modules.byIdentifier[identifier]; - if (id === undefined) continue; - if (usedIds.has(id)) continue; - usedIds.add(id); - chunkGraph.setModuleId(module, id); - } - } - if (Array.isArray(records.modules.usedIds)) { - compilation.usedModuleIds = new Set(records.modules.usedIds); - } - } - ); + statMergedAvailableModuleSets += availableModulesToBeMerged.length; - /** - * @param {Chunk} chunk the chunk - * @returns {string[]} sources of the chunk - */ - const getChunkSources = chunk => { - /** @type {string[]} */ - const sources = []; - for (const chunkGroup of chunk.groupsIterable) { - const index = chunkGroup.chunks.indexOf(chunk); - if (chunkGroup.name) { - sources.push(`${index} ${chunkGroup.name}`); + // 1. Get minimal available modules + // It doesn't make sense to traverse a chunk again with more available modules. + // This step calculates the minimal available modules and skips traversal when + // the list didn't shrink. + if (availableModulesToBeMerged.length > 1) { + availableModulesToBeMerged.sort(bySetSize); + } + let changed = false; + merge: for (const availableModules of availableModulesToBeMerged) { + if (cachedMinAvailableModules === undefined) { + cachedMinAvailableModules = availableModules; + info.minAvailableModules = cachedMinAvailableModules; + info.minAvailableModulesOwned = false; + changed = true; + } else { + if (info.minAvailableModulesOwned) { + // We own it and can modify it + if (cachedMinAvailableModules.plus === availableModules.plus) { + for (const m of cachedMinAvailableModules) { + if (!availableModules.has(m)) { + cachedMinAvailableModules.delete(m); + changed = true; + } + } + } else { + for (const m of cachedMinAvailableModules) { + if (!availableModules.has(m) && !availableModules.plus.has(m)) { + cachedMinAvailableModules.delete(m); + changed = true; + } + } + for (const m of cachedMinAvailableModules.plus) { + if (!availableModules.has(m) && !availableModules.plus.has(m)) { + // We can't remove modules from the plus part + // so we need to merge plus into the normal part to allow modifying it + const iterator = + cachedMinAvailableModules.plus[Symbol.iterator](); + // fast forward add all modules until m + /** @type {IteratorResult} */ + let it; + while (!(it = iterator.next()).done) { + const module = it.value; + if (module === m) break; + cachedMinAvailableModules.add(module); + } + // check the remaining modules before adding + while (!(it = iterator.next()).done) { + const module = it.value; + if ( + availableModules.has(module) || + availableModules.plus.has(m) + ) { + cachedMinAvailableModules.add(module); + } + } + cachedMinAvailableModules.plus = EMPTY_SET; + changed = true; + continue merge; + } + } + } + } else if (cachedMinAvailableModules.plus === availableModules.plus) { + // Common and fast case when the plus part is shared + // We only need to care about the normal part + if (availableModules.size < cachedMinAvailableModules.size) { + // the new availableModules is smaller so it's faster to + // fork from the new availableModules + statForkedAvailableModules++; + statForkedAvailableModulesCount += availableModules.size; + statForkedMergedModulesCount += cachedMinAvailableModules.size; + // construct a new Set as intersection of cachedMinAvailableModules and availableModules + const newSet = /** @type {ModuleSetPlus} */ (new Set()); + newSet.plus = availableModules.plus; + for (const m of availableModules) { + if (cachedMinAvailableModules.has(m)) { + newSet.add(m); + } + } + statForkedResultModulesCount += newSet.size; + cachedMinAvailableModules = newSet; + info.minAvailableModulesOwned = true; + info.minAvailableModules = newSet; + changed = true; + continue merge; + } + for (const m of cachedMinAvailableModules) { + if (!availableModules.has(m)) { + // cachedMinAvailableModules need to be modified + // but we don't own it + statForkedAvailableModules++; + statForkedAvailableModulesCount += + cachedMinAvailableModules.size; + statForkedMergedModulesCount += availableModules.size; + // construct a new Set as intersection of cachedMinAvailableModules and availableModules + // as the plus part is equal we can just take over this one + const newSet = /** @type {ModuleSetPlus} */ (new Set()); + newSet.plus = availableModules.plus; + const iterator = cachedMinAvailableModules[Symbol.iterator](); + // fast forward add all modules until m + /** @type {IteratorResult} */ + let it; + while (!(it = iterator.next()).done) { + const module = it.value; + if (module === m) break; + newSet.add(module); + } + // check the remaining modules before adding + while (!(it = iterator.next()).done) { + const module = it.value; + if (availableModules.has(module)) { + newSet.add(module); + } + } + statForkedResultModulesCount += newSet.size; + cachedMinAvailableModules = newSet; + info.minAvailableModulesOwned = true; + info.minAvailableModules = newSet; + changed = true; + continue merge; + } + } } else { - for (const origin of chunkGroup.origins) { - if (origin.module) { - if (origin.request) { - sources.push( - `${index} ${getModuleIdentifier(origin.module)} ${ - origin.request - }` - ); - } else if (typeof origin.loc === "string") { - sources.push( - `${index} ${getModuleIdentifier(origin.module)} ${ - origin.loc - }` - ); - } else if ( - origin.loc && - typeof origin.loc === "object" && - "start" in origin.loc - ) { - sources.push( - `${index} ${getModuleIdentifier( - origin.module - )} ${JSON.stringify(origin.loc.start)}` - ); + for (const m of cachedMinAvailableModules) { + if (!availableModules.has(m) && !availableModules.plus.has(m)) { + // cachedMinAvailableModules need to be modified + // but we don't own it + statForkedAvailableModules++; + statForkedAvailableModulesCount += + cachedMinAvailableModules.size; + statForkedAvailableModulesCountPlus += + cachedMinAvailableModules.plus.size; + statForkedMergedModulesCount += availableModules.size; + statForkedMergedModulesCountPlus += availableModules.plus.size; + // construct a new Set as intersection of cachedMinAvailableModules and availableModules + const newSet = /** @type {ModuleSetPlus} */ (new Set()); + newSet.plus = EMPTY_SET; + const iterator = cachedMinAvailableModules[Symbol.iterator](); + // fast forward add all modules until m + /** @type {IteratorResult} */ + let it; + while (!(it = iterator.next()).done) { + const module = it.value; + if (module === m) break; + newSet.add(module); + } + // check the remaining modules before adding + while (!(it = iterator.next()).done) { + const module = it.value; + if ( + availableModules.has(module) || + availableModules.plus.has(module) + ) { + newSet.add(module); + } + } + // also check all modules in cachedMinAvailableModules.plus + for (const module of cachedMinAvailableModules.plus) { + if ( + availableModules.has(module) || + availableModules.plus.has(module) + ) { + newSet.add(module); + } + } + statForkedResultModulesCount += newSet.size; + cachedMinAvailableModules = newSet; + info.minAvailableModulesOwned = true; + info.minAvailableModules = newSet; + changed = true; + continue merge; + } + } + for (const m of cachedMinAvailableModules.plus) { + if (!availableModules.has(m) && !availableModules.plus.has(m)) { + // cachedMinAvailableModules need to be modified + // but we don't own it + statForkedAvailableModules++; + statForkedAvailableModulesCount += + cachedMinAvailableModules.size; + statForkedAvailableModulesCountPlus += + cachedMinAvailableModules.plus.size; + statForkedMergedModulesCount += availableModules.size; + statForkedMergedModulesCountPlus += availableModules.plus.size; + // construct a new Set as intersection of cachedMinAvailableModules and availableModules + // we already know that all modules directly from cachedMinAvailableModules are in availableModules too + const newSet = /** @type {ModuleSetPlus} */ ( + new Set(cachedMinAvailableModules) + ); + newSet.plus = EMPTY_SET; + const iterator = + cachedMinAvailableModules.plus[Symbol.iterator](); + // fast forward add all modules until m + /** @type {IteratorResult} */ + let it; + while (!(it = iterator.next()).done) { + const module = it.value; + if (module === m) break; + newSet.add(module); + } + // check the remaining modules before adding + while (!(it = iterator.next()).done) { + const module = it.value; + if ( + availableModules.has(module) || + availableModules.plus.has(module) + ) { + newSet.add(module); + } } + statForkedResultModulesCount += newSet.size; + cachedMinAvailableModules = newSet; + info.minAvailableModulesOwned = true; + info.minAvailableModules = newSet; + changed = true; + continue merge; } } } } - return sources; + } + availableModulesToBeMerged.length = 0; + if (changed) { + info.resultingAvailableModules = undefined; + outdatedChunkGroupInfo.add(info); + } + } + chunkGroupsForMerging.clear(); + }; + + const processChunkGroupsForCombining = () => { + for (const info of chunkGroupsForCombining) { + for (const source of info.availableSources) { + if (!source.minAvailableModules) { + chunkGroupsForCombining.delete(info); + break; + } + } + } + for (const info of chunkGroupsForCombining) { + const availableModules = /** @type {ModuleSetPlus} */ (new Set()); + availableModules.plus = EMPTY_SET; + const mergeSet = set => { + if (set.size > availableModules.plus.size) { + for (const item of availableModules.plus) availableModules.add(item); + availableModules.plus = set; + } else { + for (const item of set) availableModules.add(item); + } }; + // combine minAvailableModules from all resultingAvailableModules + for (const source of info.availableSources) { + const resultingAvailableModules = + calculateResultingAvailableModules(source); + mergeSet(resultingAvailableModules); + mergeSet(resultingAvailableModules.plus); + } + info.minAvailableModules = availableModules; + info.minAvailableModulesOwned = false; + info.resultingAvailableModules = undefined; + outdatedChunkGroupInfo.add(info); + } + chunkGroupsForCombining.clear(); + }; - compilation.hooks.recordChunks.tap( - "RecordIdsPlugin", - /** - * @param {Chunk[]} chunks the chunks array - * @param {Records} records the records object - * @returns {void} - */ - (chunks, records) => { - if (!records.chunks) records.chunks = {}; - if (!records.chunks.byName) records.chunks.byName = {}; - if (!records.chunks.bySource) records.chunks.bySource = {}; - /** @type {Set} */ - const usedIds = new Set(); - for (const chunk of chunks) { - if (typeof chunk.id !== "number") continue; - const name = chunk.name; - if (name) records.chunks.byName[name] = chunk.id; - const sources = getChunkSources(chunk); - for (const source of sources) { - records.chunks.bySource[source] = chunk.id; - } - usedIds.add(chunk.id); + const processOutdatedChunkGroupInfo = () => { + statChunkGroupInfoUpdated += outdatedChunkGroupInfo.size; + // Revisit skipped elements + for (const info of outdatedChunkGroupInfo) { + // 1. Reconsider skipped items + if (info.skippedItems !== undefined) { + const { minAvailableModules } = info; + for (const module of info.skippedItems) { + if ( + !minAvailableModules.has(module) && + !minAvailableModules.plus.has(module) + ) { + queue.push({ + action: ADD_AND_ENTER_MODULE, + block: module, + module, + chunk: info.chunkGroup.chunks[0], + chunkGroup: info.chunkGroup, + chunkGroupInfo: info + }); + info.skippedItems.delete(module); } - records.chunks.usedIds = Array.from(usedIds).sort(compareNumbers); } - ); - compilation.hooks.reviveChunks.tap( - "RecordIdsPlugin", - /** - * @param {Chunk[]} chunks the chunks array - * @param {Records} records the records object - * @returns {void} - */ - (chunks, records) => { - if (!records.chunks) return; - /** @type {Set} */ - const usedIds = new Set(); - if (records.chunks.byName) { - for (const chunk of chunks) { - if (chunk.id !== null) continue; - if (!chunk.name) continue; - const id = records.chunks.byName[chunk.name]; - if (id === undefined) continue; - if (usedIds.has(id)) continue; - usedIds.add(id); - chunk.id = id; - chunk.ids = [id]; - } + } + + // 2. Reconsider skipped connections + if (info.skippedModuleConnections !== undefined) { + const { minAvailableModules } = info; + for (const entry of info.skippedModuleConnections) { + const [module, activeState] = entry; + if (activeState === false) continue; + if (activeState === true) { + info.skippedModuleConnections.delete(entry); } - if (records.chunks.bySource) { - for (const chunk of chunks) { - if (chunk.id !== null) continue; - const sources = getChunkSources(chunk); - for (const source of sources) { - const id = records.chunks.bySource[source]; - if (id === undefined) continue; - if (usedIds.has(id)) continue; - usedIds.add(id); - chunk.id = id; - chunk.ids = [id]; - break; - } - } + if ( + activeState === true && + (minAvailableModules.has(module) || + minAvailableModules.plus.has(module)) + ) { + info.skippedItems.add(module); + continue; } - if (Array.isArray(records.chunks.usedIds)) { - compilation.usedChunkIds = new Set(records.chunks.usedIds); + queue.push({ + action: activeState === true ? ADD_AND_ENTER_MODULE : PROCESS_BLOCK, + block: module, + module, + chunk: info.chunkGroup.chunks[0], + chunkGroup: info.chunkGroup, + chunkGroupInfo: info + }); + } + } + + // 2. Reconsider children chunk groups + if (info.children !== undefined) { + statChildChunkGroupsReconnected += info.children.size; + for (const cgi of info.children) { + let connectList = queueConnect.get(info); + if (connectList === undefined) { + connectList = new Set(); + queueConnect.set(info, connectList); } + connectList.add(cgi); + } + } + + // 3. Reconsider chunk groups for combining + if (info.availableChildren !== undefined) { + for (const cgi of info.availableChildren) { + chunkGroupsForCombining.add(cgi); } + } + } + outdatedChunkGroupInfo.clear(); + }; + + // Iterative traversal of the Module graph + // Recursive would be simpler to write but could result in Stack Overflows + while (queue.length || queueConnect.size) { + logger.time("visitModules: visiting"); + processQueue(); + logger.timeAggregateEnd("visitModules: prepare"); + logger.timeEnd("visitModules: visiting"); + + if (chunkGroupsForCombining.size > 0) { + logger.time("visitModules: combine available modules"); + processChunkGroupsForCombining(); + logger.timeEnd("visitModules: combine available modules"); + } + + if (queueConnect.size > 0) { + logger.time("visitModules: calculating available modules"); + processConnectQueue(); + logger.timeEnd("visitModules: calculating available modules"); + + if (chunkGroupsForMerging.size > 0) { + logger.time("visitModules: merging available modules"); + processChunkGroupsForMerging(); + logger.timeEnd("visitModules: merging available modules"); + } + } + + if (outdatedChunkGroupInfo.size > 0) { + logger.time("visitModules: check modules for revisit"); + processOutdatedChunkGroupInfo(); + logger.timeEnd("visitModules: check modules for revisit"); + } + + // Run queueDelayed when all items of the queue are processed + // This is important to get the global indexing correct + // Async blocks should be processed after all sync blocks are processed + if (queue.length === 0) { + const tempQueue = queue; + queue = queueDelayed.reverse(); + queueDelayed = tempQueue; + } + } + + logger.log( + `${statProcessedQueueItems} queue items processed (${statProcessedBlocks} blocks)` + ); + logger.log(`${statConnectedChunkGroups} chunk groups connected`); + logger.log( + `${statProcessedChunkGroupsForMerging} chunk groups processed for merging (${statMergedAvailableModuleSets} module sets, ${statForkedAvailableModules} forked, ${statForkedAvailableModulesCount} + ${statForkedAvailableModulesCountPlus} modules forked, ${statForkedMergedModulesCount} + ${statForkedMergedModulesCountPlus} modules merged into fork, ${statForkedResultModulesCount} resulting modules)` + ); + logger.log( + `${statChunkGroupInfoUpdated} chunk group info updated (${statChildChunkGroupsReconnected} already connected chunk groups reconnected)` + ); +}; + +/** + * + * @param {Compilation} compilation the compilation + * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks + * @param {Map} blockConnections connection for blocks + * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules + */ +const connectChunkGroups = ( + compilation, + blocksWithNestedBlocks, + blockConnections, + chunkGroupInfoMap +) => { + const { chunkGraph } = compilation; + + /** + * Helper function to check if all modules of a chunk are available + * + * @param {ChunkGroup} chunkGroup the chunkGroup to scan + * @param {ModuleSetPlus} availableModules the comparator set + * @returns {boolean} return true if all modules of a chunk are available + */ + const areModulesAvailable = (chunkGroup, availableModules) => { + for (const chunk of chunkGroup.chunks) { + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (!availableModules.has(module) && !availableModules.plus.has(module)) + return false; + } + } + return true; + }; + + // For each edge in the basic chunk graph + for (const [block, connections] of blockConnections) { + // 1. Check if connection is needed + // When none of the dependencies need to be connected + // we can skip all of them + // It's not possible to filter each item so it doesn't create inconsistent + // connections and modules can only create one version + // TODO maybe decide this per runtime + if ( + // TODO is this needed? + !blocksWithNestedBlocks.has(block) && + connections.every(({ chunkGroup, originChunkGroupInfo }) => + areModulesAvailable( + chunkGroup, + originChunkGroupInfo.resultingAvailableModules + ) + ) + ) { + continue; + } + + // 2. Foreach edge + for (let i = 0; i < connections.length; i++) { + const { chunkGroup, originChunkGroupInfo } = connections[i]; + + // 3. Connect block with chunk + chunkGraph.connectBlockAndChunkGroup(block, chunkGroup); + + // 4. Connect chunk with parent + connectChunkGroupParentAndChild( + originChunkGroupInfo.chunkGroup, + chunkGroup ); - }); + } } -} -module.exports = RecordIdsPlugin; +}; + +/** + * Remove all unconnected chunk groups + * @param {Compilation} compilation the compilation + * @param {Iterable} allCreatedChunkGroups all chunk groups that where created before + */ +const cleanupUnconnectedGroups = (compilation, allCreatedChunkGroups) => { + const { chunkGraph } = compilation; + + for (const chunkGroup of allCreatedChunkGroups) { + if (chunkGroup.getNumberOfParents() === 0) { + for (const chunk of chunkGroup.chunks) { + compilation.chunks.delete(chunk); + chunkGraph.disconnectChunk(chunk); + } + chunkGraph.disconnectChunkGroup(chunkGroup); + chunkGroup.remove(); + } + } +}; + +/** + * This method creates the Chunk graph from the Module graph + * @param {Compilation} compilation the compilation + * @param {Map} inputEntrypointsAndModules chunk groups which are processed with the modules + * @returns {void} + */ +const buildChunkGraph = (compilation, inputEntrypointsAndModules) => { + const logger = compilation.getLogger("webpack.buildChunkGraph"); + + // SHARED STATE + + /** @type {Map} */ + const blockConnections = new Map(); + + /** @type {Set} */ + const allCreatedChunkGroups = new Set(); + + /** @type {Map} */ + const chunkGroupInfoMap = new Map(); + + /** @type {Set} */ + const blocksWithNestedBlocks = new Set(); + + // PART ONE + + logger.time("visitModules"); + visitModules( + logger, + compilation, + inputEntrypointsAndModules, + chunkGroupInfoMap, + blockConnections, + blocksWithNestedBlocks, + allCreatedChunkGroups + ); + logger.timeEnd("visitModules"); + + // PART TWO + + logger.time("connectChunkGroups"); + connectChunkGroups( + compilation, + blocksWithNestedBlocks, + blockConnections, + chunkGroupInfoMap + ); + logger.timeEnd("connectChunkGroups"); + + for (const [chunkGroup, chunkGroupInfo] of chunkGroupInfoMap) { + for (const chunk of chunkGroup.chunks) + chunk.runtime = mergeRuntime(chunk.runtime, chunkGroupInfo.runtime); + } + + // Cleanup work + + logger.time("cleanup"); + cleanupUnconnectedGroups(compilation, allCreatedChunkGroups); + logger.timeEnd("cleanup"); +}; + +module.exports = buildChunkGraph; /***/ }), -/***/ 73406: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 28034: +/***/ (function(module) { "use strict"; /* @@ -59497,39 +60282,38 @@ module.exports = RecordIdsPlugin; -const { contextify } = __webpack_require__(82186); +/** @typedef {import("../Compiler")} Compiler */ -class RequestShortener { +class AddBuildDependenciesPlugin { /** - * @param {string} dir the directory - * @param {object=} associatedObjectForCache an object to which the cache will be attached + * @param {Iterable} buildDependencies list of build dependencies */ - constructor(dir, associatedObjectForCache) { - this.contextify = contextify.bindContextCache( - dir, - associatedObjectForCache - ); + constructor(buildDependencies) { + this.buildDependencies = new Set(buildDependencies); } /** - * @param {string | undefined | null} request the request to shorten - * @returns {string | undefined | null} the shortened request + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - shorten(request) { - if (!request) { - return request; - } - return this.contextify(request); + apply(compiler) { + compiler.hooks.compilation.tap( + "AddBuildDependenciesPlugin", + compilation => { + compilation.buildDependencies.addAll(this.buildDependencies); + } + ); } } -module.exports = RequestShortener; +module.exports = AddBuildDependenciesPlugin; /***/ }), -/***/ 88846: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 47942: +/***/ (function(module) { "use strict"; /* @@ -59539,81 +60323,39 @@ module.exports = RequestShortener; -const RuntimeGlobals = __webpack_require__(16475); -const ConstDependency = __webpack_require__(76911); -const { - toConstantDependency -} = __webpack_require__(93998); +/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("./Compiler")} Compiler */ +class AddManagedPathsPlugin { + /** + * @param {Iterable} managedPaths list of managed paths + * @param {Iterable} immutablePaths list of immutable paths + */ + constructor(managedPaths, immutablePaths) { + this.managedPaths = new Set(managedPaths); + this.immutablePaths = new Set(immutablePaths); + } -module.exports = class RequireJsStuffPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap( - "RequireJsStuffPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); - const handler = (parser, parserOptions) => { - if ( - parserOptions.requireJs === undefined || - !parserOptions.requireJs - ) { - return; - } - - parser.hooks.call - .for("require.config") - .tap( - "RequireJsStuffPlugin", - toConstantDependency(parser, "undefined") - ); - parser.hooks.call - .for("requirejs.config") - .tap( - "RequireJsStuffPlugin", - toConstantDependency(parser, "undefined") - ); - - parser.hooks.expression - .for("require.version") - .tap( - "RequireJsStuffPlugin", - toConstantDependency(parser, JSON.stringify("0.0.0")) - ); - parser.hooks.expression - .for("requirejs.onError") - .tap( - "RequireJsStuffPlugin", - toConstantDependency( - parser, - RuntimeGlobals.uncaughtErrorHandler, - [RuntimeGlobals.uncaughtErrorHandler] - ) - ); - }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireJsStuffPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireJsStuffPlugin", handler); - } - ); + for (const managedPath of this.managedPaths) { + compiler.managedPaths.add(managedPath); + } + for (const immutablePath of this.immutablePaths) { + compiler.immutablePaths.add(immutablePath); + } } -}; +} + +module.exports = AddManagedPathsPlugin; /***/ }), -/***/ 30217: +/***/ 71985: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -59624,156 +60366,232 @@ module.exports = class RequireJsStuffPlugin { -const Factory = (__webpack_require__(30662).ResolverFactory); -const { HookMap, SyncHook, SyncWaterfallHook } = __webpack_require__(41242); -const { - cachedCleverMerge, - removeOperations, - resolveByProperty -} = __webpack_require__(60839); +const Cache = __webpack_require__(7592); +const ProgressPlugin = __webpack_require__(13216); -/** @typedef {import("enhanced-resolve").ResolveOptions} ResolveOptions */ -/** @typedef {import("enhanced-resolve").Resolver} Resolver */ -/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */ -/** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */ +/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {WebpackResolveOptions & {dependencyType?: string, resolveToContext?: boolean }} ResolveOptionsWithDependencyType */ -/** - * @typedef {Object} WithOptions - * @property {function(Partial): ResolverWithOptions} withOptions create a resolver with additional/different options - */ +const BUILD_DEPENDENCIES_KEY = Symbol(); -/** @typedef {Resolver & WithOptions} ResolverWithOptions */ +class IdleFileCachePlugin { + /** + * @param {TODO} strategy cache strategy + * @param {number} idleTimeout timeout + * @param {number} idleTimeoutForInitialStore initial timeout + * @param {number} idleTimeoutAfterLargeChanges timeout after changes + */ + constructor( + strategy, + idleTimeout, + idleTimeoutForInitialStore, + idleTimeoutAfterLargeChanges + ) { + this.strategy = strategy; + this.idleTimeout = idleTimeout; + this.idleTimeoutForInitialStore = idleTimeoutForInitialStore; + this.idleTimeoutAfterLargeChanges = idleTimeoutAfterLargeChanges; + } -// need to be hoisted on module level for caching identity -const EMPTY_RESOLVE_OPTIONS = {}; + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + let strategy = this.strategy; + const idleTimeout = this.idleTimeout; + const idleTimeoutForInitialStore = Math.min( + idleTimeout, + this.idleTimeoutForInitialStore + ); + const idleTimeoutAfterLargeChanges = this.idleTimeoutAfterLargeChanges; + const resolvedPromise = Promise.resolve(); -/** - * @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType enhanced options - * @returns {ResolveOptions} merged options - */ -const convertToResolveOptions = resolveOptionsWithDepType => { - const { dependencyType, plugins, ...remaining } = resolveOptionsWithDepType; + let timeSpendInBuild = 0; + let timeSpendInStore = 0; + let avgTimeSpendInStore = 0; - // check type compat - /** @type {Partial} */ - const partialOptions = { - ...remaining, - plugins: - plugins && - /** @type {ResolvePluginInstance[]} */ ( - plugins.filter(item => item !== "...") - ) - }; + /** @type {Map Promise>} */ + const pendingIdleTasks = new Map(); - if (!partialOptions.fileSystem) { - throw new Error( - "fileSystem is missing in resolveOptions, but it's required for enhanced-resolve" - ); - } - // These weird types validate that we checked all non-optional properties - const options = - /** @type {Partial & Pick} */ ( - partialOptions + compiler.cache.hooks.store.tap( + { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, + (identifier, etag, data) => { + pendingIdleTasks.set(identifier, () => + strategy.store(identifier, etag, data) + ); + } ); - return removeOperations( - resolveByProperty(options, "byDependency", dependencyType) - ); -}; - -/** - * @typedef {Object} ResolverCache - * @property {WeakMap} direct - * @property {Map} stringified - */ - -module.exports = class ResolverFactory { - constructor() { - this.hooks = Object.freeze({ - /** @type {HookMap>} */ - resolveOptions: new HookMap( - () => new SyncWaterfallHook(["resolveOptions"]) - ), - /** @type {HookMap>} */ - resolver: new HookMap( - () => new SyncHook(["resolver", "resolveOptions", "userResolveOptions"]) - ) - }); - /** @type {Map} */ - this.cache = new Map(); - } + compiler.cache.hooks.get.tapPromise( + { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, + (identifier, etag, gotHandlers) => { + const restore = () => + strategy.restore(identifier, etag).then(cacheEntry => { + if (cacheEntry === undefined) { + gotHandlers.push((result, callback) => { + if (result !== undefined) { + pendingIdleTasks.set(identifier, () => + strategy.store(identifier, etag, result) + ); + } + callback(); + }); + } else { + return cacheEntry; + } + }); + const pendingTask = pendingIdleTasks.get(identifier); + if (pendingTask !== undefined) { + pendingIdleTasks.delete(identifier); + return pendingTask().then(restore); + } + return restore(); + } + ); - /** - * @param {string} type type of resolver - * @param {ResolveOptionsWithDependencyType=} resolveOptions options - * @returns {ResolverWithOptions} the resolver - */ - get(type, resolveOptions = EMPTY_RESOLVE_OPTIONS) { - let typedCaches = this.cache.get(type); - if (!typedCaches) { - typedCaches = { - direct: new WeakMap(), - stringified: new Map() - }; - this.cache.set(type, typedCaches); - } - const cachedResolver = typedCaches.direct.get(resolveOptions); - if (cachedResolver) { - return cachedResolver; - } - const ident = JSON.stringify(resolveOptions); - const resolver = typedCaches.stringified.get(ident); - if (resolver) { - typedCaches.direct.set(resolveOptions, resolver); - return resolver; - } - const newResolver = this._create(type, resolveOptions); - typedCaches.direct.set(resolveOptions, newResolver); - typedCaches.stringified.set(ident, newResolver); - return newResolver; - } + compiler.cache.hooks.storeBuildDependencies.tap( + { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, + dependencies => { + pendingIdleTasks.set(BUILD_DEPENDENCIES_KEY, () => + strategy.storeBuildDependencies(dependencies) + ); + } + ); - /** - * @param {string} type type of resolver - * @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType options - * @returns {ResolverWithOptions} the resolver - */ - _create(type, resolveOptionsWithDepType) { - /** @type {ResolveOptionsWithDependencyType} */ - const originalResolveOptions = { ...resolveOptionsWithDepType }; + compiler.cache.hooks.shutdown.tapPromise( + { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, + () => { + if (idleTimer) { + clearTimeout(idleTimer); + idleTimer = undefined; + } + isIdle = false; + const reportProgress = ProgressPlugin.getReporter(compiler); + const jobs = Array.from(pendingIdleTasks.values()); + if (reportProgress) reportProgress(0, "process pending cache items"); + const promises = jobs.map(fn => fn()); + pendingIdleTasks.clear(); + promises.push(currentIdlePromise); + const promise = Promise.all(promises); + currentIdlePromise = promise.then(() => strategy.afterAllStored()); + if (reportProgress) { + currentIdlePromise = currentIdlePromise.then(() => { + reportProgress(1, `stored`); + }); + } + return currentIdlePromise.then(() => { + // Reset strategy + if (strategy.clear) strategy.clear(); + }); + } + ); - const resolveOptions = convertToResolveOptions( - this.hooks.resolveOptions.for(type).call(resolveOptionsWithDepType) + /** @type {Promise} */ + let currentIdlePromise = resolvedPromise; + let isIdle = false; + let isInitialStore = true; + const processIdleTasks = () => { + if (isIdle) { + const startTime = Date.now(); + if (pendingIdleTasks.size > 0) { + const promises = [currentIdlePromise]; + const maxTime = startTime + 100; + let maxCount = 100; + for (const [filename, factory] of pendingIdleTasks) { + pendingIdleTasks.delete(filename); + promises.push(factory()); + if (maxCount-- <= 0 || Date.now() > maxTime) break; + } + currentIdlePromise = Promise.all(promises); + currentIdlePromise.then(() => { + timeSpendInStore += Date.now() - startTime; + // Allow to exit the process between + idleTimer = setTimeout(processIdleTasks, 0); + idleTimer.unref(); + }); + return; + } + currentIdlePromise = currentIdlePromise + .then(async () => { + await strategy.afterAllStored(); + timeSpendInStore += Date.now() - startTime; + avgTimeSpendInStore = + Math.max(avgTimeSpendInStore, timeSpendInStore) * 0.9 + + timeSpendInStore * 0.1; + timeSpendInStore = 0; + timeSpendInBuild = 0; + }) + .catch(err => { + const logger = compiler.getInfrastructureLogger( + "IdleFileCachePlugin" + ); + logger.warn(`Background tasks during idle failed: ${err.message}`); + logger.debug(err.stack); + }); + isInitialStore = false; + } + }; + let idleTimer = undefined; + compiler.cache.hooks.beginIdle.tap( + { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, + () => { + const isLargeChange = timeSpendInBuild > avgTimeSpendInStore * 2; + if (isInitialStore && idleTimeoutForInitialStore < idleTimeout) { + compiler + .getInfrastructureLogger("IdleFileCachePlugin") + .log( + `Initial cache was generated and cache will be persisted in ${ + idleTimeoutForInitialStore / 1000 + }s.` + ); + } else if ( + isLargeChange && + idleTimeoutAfterLargeChanges < idleTimeout + ) { + compiler + .getInfrastructureLogger("IdleFileCachePlugin") + .log( + `Spend ${Math.round(timeSpendInBuild) / 1000}s in build and ${ + Math.round(avgTimeSpendInStore) / 1000 + }s in average in cache store. This is considered as large change and cache will be persisted in ${ + idleTimeoutAfterLargeChanges / 1000 + }s.` + ); + } + idleTimer = setTimeout(() => { + idleTimer = undefined; + isIdle = true; + resolvedPromise.then(processIdleTasks); + }, Math.min(isInitialStore ? idleTimeoutForInitialStore : Infinity, isLargeChange ? idleTimeoutAfterLargeChanges : Infinity, idleTimeout)); + idleTimer.unref(); + } ); - const resolver = /** @type {ResolverWithOptions} */ ( - Factory.createResolver(resolveOptions) + compiler.cache.hooks.endIdle.tap( + { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, + () => { + if (idleTimer) { + clearTimeout(idleTimer); + idleTimer = undefined; + } + isIdle = false; + } ); - if (!resolver) { - throw new Error("No resolver created"); - } - /** @type {WeakMap, ResolverWithOptions>} */ - const childCache = new WeakMap(); - resolver.withOptions = options => { - const cacheEntry = childCache.get(options); - if (cacheEntry !== undefined) return cacheEntry; - const mergedOptions = cachedCleverMerge(originalResolveOptions, options); - const resolver = this.get(type, mergedOptions); - childCache.set(options, resolver); - return resolver; - }; - this.hooks.resolver - .for(type) - .call(resolver, resolveOptions, originalResolveOptions); - return resolver; + compiler.hooks.done.tap("IdleFileCachePlugin", stats => { + // 10% build overhead is ignored, as it's not cacheable + timeSpendInBuild *= 0.9; + timeSpendInBuild += stats.endTime - stats.startTime; + }); } -}; +} + +module.exports = IdleFileCachePlugin; /***/ }), -/***/ 16475: -/***/ (function(__unused_webpack_module, exports) { +/***/ 52539: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -59783,385 +60601,198 @@ module.exports = class ResolverFactory { -/** - * the internal require function - */ -exports.require = "__webpack_require__"; - -/** - * access to properties of the internal require function/object - */ -exports.requireScope = "__webpack_require__.*"; - -/** - * the internal exports object - */ -exports.exports = "__webpack_exports__"; - -/** - * top-level this need to be the exports object - */ -exports.thisAsExports = "top-level-this-exports"; - -/** - * runtime need to return the exports of the last entry module - */ -exports.returnExportsFromRuntime = "return-exports-from-runtime"; - -/** - * the internal module object - */ -exports.module = "module"; - -/** - * the internal module object - */ -exports.moduleId = "module.id"; - -/** - * the internal module object - */ -exports.moduleLoaded = "module.loaded"; - -/** - * the bundle public path - */ -exports.publicPath = "__webpack_require__.p"; - -/** - * the module id of the entry point - */ -exports.entryModuleId = "__webpack_require__.s"; - -/** - * the module cache - */ -exports.moduleCache = "__webpack_require__.c"; - -/** - * the module functions - */ -exports.moduleFactories = "__webpack_require__.m"; - -/** - * the module functions, with only write access - */ -exports.moduleFactoriesAddOnly = "__webpack_require__.m (add only)"; - -/** - * the chunk ensure function - */ -exports.ensureChunk = "__webpack_require__.e"; - -/** - * an object with handlers to ensure a chunk - */ -exports.ensureChunkHandlers = "__webpack_require__.f"; - -/** - * a runtime requirement if ensureChunkHandlers should include loading of chunk needed for entries - */ -exports.ensureChunkIncludeEntries = "__webpack_require__.f (include entries)"; - -/** - * the chunk prefetch function - */ -exports.prefetchChunk = "__webpack_require__.E"; - -/** - * an object with handlers to prefetch a chunk - */ -exports.prefetchChunkHandlers = "__webpack_require__.F"; - -/** - * the chunk preload function - */ -exports.preloadChunk = "__webpack_require__.G"; - -/** - * an object with handlers to preload a chunk - */ -exports.preloadChunkHandlers = "__webpack_require__.H"; - -/** - * the exported property define getters function - */ -exports.definePropertyGetters = "__webpack_require__.d"; - -/** - * define compatibility on export - */ -exports.makeNamespaceObject = "__webpack_require__.r"; - -/** - * create a fake namespace object - */ -exports.createFakeNamespaceObject = "__webpack_require__.t"; - -/** - * compatibility get default export - */ -exports.compatGetDefaultExport = "__webpack_require__.n"; - -/** - * harmony module decorator - */ -exports.harmonyModuleDecorator = "__webpack_require__.hmd"; - -/** - * node.js module decorator - */ -exports.nodeModuleDecorator = "__webpack_require__.nmd"; - -/** - * the webpack hash - */ -exports.getFullHash = "__webpack_require__.h"; - -/** - * an object containing all installed WebAssembly.Instance export objects keyed by module id - */ -exports.wasmInstances = "__webpack_require__.w"; - -/** - * instantiate a wasm instance from module exports object, id, hash and importsObject - */ -exports.instantiateWasm = "__webpack_require__.v"; - -/** - * the uncaught error handler for the webpack runtime - */ -exports.uncaughtErrorHandler = "__webpack_require__.oe"; - -/** - * the script nonce - */ -exports.scriptNonce = "__webpack_require__.nc"; - -/** - * function to load a script tag. - * Arguments: (url: string, done: (event) => void), key?: string | number, chunkId?: string | number) => void - * done function is called when loading has finished or timeout occurred. - * It will attach to existing script tags with data-webpack == uniqueName + ":" + key or src == url. - */ -exports.loadScript = "__webpack_require__.l"; - -/** - * function to promote a string to a TrustedScript using webpack's Trusted - * Types policy - * Arguments: (script: string) => TrustedScript - */ -exports.createScript = "__webpack_require__.ts"; - -/** - * function to promote a string to a TrustedScriptURL using webpack's Trusted - * Types policy - * Arguments: (url: string) => TrustedScriptURL - */ -exports.createScriptUrl = "__webpack_require__.tu"; - -/** - * function to return webpack's Trusted Types policy - * Arguments: () => TrustedTypePolicy - */ -exports.getTrustedTypesPolicy = "__webpack_require__.tt"; - -/** - * the chunk name of the chunk with the runtime - */ -exports.chunkName = "__webpack_require__.cn"; - -/** - * the runtime id of the current runtime - */ -exports.runtimeId = "__webpack_require__.j"; - -/** - * the filename of the script part of the chunk - */ -exports.getChunkScriptFilename = "__webpack_require__.u"; - -/** - * the filename of the css part of the chunk - */ -exports.getChunkCssFilename = "__webpack_require__.k"; - -/** - * a flag when a module/chunk/tree has css modules - */ -exports.hasCssModules = "has css modules"; - -/** - * the filename of the script part of the hot update chunk - */ -exports.getChunkUpdateScriptFilename = "__webpack_require__.hu"; - -/** - * the filename of the css part of the hot update chunk - */ -exports.getChunkUpdateCssFilename = "__webpack_require__.hk"; - -/** - * startup signal from runtime - * This will be called when the runtime chunk has been loaded. - */ -exports.startup = "__webpack_require__.x"; - -/** - * @deprecated - * creating a default startup function with the entry modules - */ -exports.startupNoDefault = "__webpack_require__.x (no default handler)"; - -/** - * startup signal from runtime but only used to add logic after the startup - */ -exports.startupOnlyAfter = "__webpack_require__.x (only after)"; - -/** - * startup signal from runtime but only used to add sync logic before the startup - */ -exports.startupOnlyBefore = "__webpack_require__.x (only before)"; - -/** - * global callback functions for installing chunks - */ -exports.chunkCallback = "webpackChunk"; - -/** - * method to startup an entrypoint with needed chunks. - * Signature: (moduleId: Id, chunkIds: Id[]) => any. - * Returns the exports of the module or a Promise - */ -exports.startupEntrypoint = "__webpack_require__.X"; - -/** - * register deferred code, which will run when certain - * chunks are loaded. - * Signature: (chunkIds: Id[], fn: () => any, priority: int >= 0 = 0) => any - * Returned value will be returned directly when all chunks are already loaded - * When (priority & 1) it will wait for all other handlers with lower priority to - * be executed before itself is executed - */ -exports.onChunksLoaded = "__webpack_require__.O"; - -/** - * method to install a chunk that was loaded somehow - * Signature: ({ id, ids, modules, runtime }) => void - */ -exports.externalInstallChunk = "__webpack_require__.C"; - -/** - * interceptor for module executions - */ -exports.interceptModuleExecution = "__webpack_require__.i"; - -/** - * the global object - */ -exports.global = "__webpack_require__.g"; - -/** - * an object with all share scopes - */ -exports.shareScopeMap = "__webpack_require__.S"; - -/** - * The sharing init sequence function (only runs once per share scope). - * Has one argument, the name of the share scope. - * Creates a share scope if not existing - */ -exports.initializeSharing = "__webpack_require__.I"; - -/** - * The current scope when getting a module from a remote - */ -exports.currentRemoteGetScope = "__webpack_require__.R"; - -/** - * the filename of the HMR manifest - */ -exports.getUpdateManifestFilename = "__webpack_require__.hmrF"; - -/** - * function downloading the update manifest - */ -exports.hmrDownloadManifest = "__webpack_require__.hmrM"; +const Cache = __webpack_require__(7592); -/** - * array with handler functions to download chunk updates - */ -exports.hmrDownloadUpdateHandlers = "__webpack_require__.hmrC"; +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Cache").Etag} Etag */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ -/** - * object with all hmr module data for all modules - */ -exports.hmrModuleData = "__webpack_require__.hmrD"; +class MemoryCachePlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + /** @type {Map} */ + const cache = new Map(); + compiler.cache.hooks.store.tap( + { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, + (identifier, etag, data) => { + cache.set(identifier, { etag, data }); + } + ); + compiler.cache.hooks.get.tap( + { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, + (identifier, etag, gotHandlers) => { + const cacheEntry = cache.get(identifier); + if (cacheEntry === null) { + return null; + } else if (cacheEntry !== undefined) { + return cacheEntry.etag === etag ? cacheEntry.data : null; + } + gotHandlers.push((result, callback) => { + if (result === undefined) { + cache.set(identifier, null); + } else { + cache.set(identifier, { etag, data: result }); + } + return callback(); + }); + } + ); + compiler.cache.hooks.shutdown.tap( + { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, + () => { + cache.clear(); + } + ); + } +} +module.exports = MemoryCachePlugin; -/** - * array with handler functions when a module should be invalidated - */ -exports.hmrInvalidateModuleHandlers = "__webpack_require__.hmrI"; -/** - * the prefix for storing state of runtime modules when hmr is enabled - */ -exports.hmrRuntimeStatePrefix = "__webpack_require__.hmrS"; +/***/ }), -/** - * the AMD define function - */ -exports.amdDefine = "__webpack_require__.amdD"; +/***/ 99334: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * the AMD options - */ -exports.amdOptions = "__webpack_require__.amdO"; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * the System polyfill object - */ -exports.system = "__webpack_require__.System"; -/** - * the shorthand for Object.prototype.hasOwnProperty - * using of it decreases the compiled bundle size - */ -exports.hasOwnProperty = "__webpack_require__.o"; -/** - * the System.register context object - */ -exports.systemContext = "__webpack_require__.y"; +const Cache = __webpack_require__(7592); -/** - * the baseURI of current document - */ -exports.baseURI = "__webpack_require__.b"; +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Cache").Etag} Etag */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ -/** - * a RelativeURL class when relative URLs are used - */ -exports.relativeUrl = "__webpack_require__.U"; +class MemoryWithGcCachePlugin { + constructor({ maxGenerations }) { + this._maxGenerations = maxGenerations; + } + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const maxGenerations = this._maxGenerations; + /** @type {Map} */ + const cache = new Map(); + /** @type {Map} */ + const oldCache = new Map(); + let generation = 0; + let cachePosition = 0; + const logger = compiler.getInfrastructureLogger("MemoryWithGcCachePlugin"); + compiler.hooks.afterDone.tap("MemoryWithGcCachePlugin", () => { + generation++; + let clearedEntries = 0; + let lastClearedIdentifier; + for (const [identifier, entry] of oldCache) { + if (entry.until > generation) break; -/** - * Creates an async module. The body function must be a async function. - * "module.exports" will be decorated with an AsyncModulePromise. - * The body function will be called. - * To handle async dependencies correctly do this: "([a, b, c] = await handleDependencies([a, b, c]));". - * If "hasAwaitAfterDependencies" is truthy, "handleDependencies()" must be called at the end of the body function. - * Signature: function( - * module: Module, - * body: (handleDependencies: (deps: AsyncModulePromise[]) => Promise & () => void, - * hasAwaitAfterDependencies?: boolean - * ) => void - */ -exports.asyncModule = "__webpack_require__.a"; + oldCache.delete(identifier); + if (cache.get(identifier) === undefined) { + cache.delete(identifier); + clearedEntries++; + lastClearedIdentifier = identifier; + } + } + if (clearedEntries > 0 || oldCache.size > 0) { + logger.log( + `${cache.size - oldCache.size} active entries, ${ + oldCache.size + } recently unused cached entries${ + clearedEntries > 0 + ? `, ${clearedEntries} old unused cache entries removed e. g. ${lastClearedIdentifier}` + : "" + }` + ); + } + let i = (cache.size / maxGenerations) | 0; + let j = cachePosition >= cache.size ? 0 : cachePosition; + cachePosition = j + i; + for (const [identifier, entry] of cache) { + if (j !== 0) { + j--; + continue; + } + if (entry !== undefined) { + // We don't delete the cache entry, but set it to undefined instead + // This reserves the location in the data table and avoids rehashing + // when constantly adding and removing entries. + // It will be deleted when removed from oldCache. + cache.set(identifier, undefined); + oldCache.delete(identifier); + oldCache.set(identifier, { + entry, + until: generation + maxGenerations + }); + if (i-- === 0) break; + } + } + }); + compiler.cache.hooks.store.tap( + { name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY }, + (identifier, etag, data) => { + cache.set(identifier, { etag, data }); + } + ); + compiler.cache.hooks.get.tap( + { name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY }, + (identifier, etag, gotHandlers) => { + const cacheEntry = cache.get(identifier); + if (cacheEntry === null) { + return null; + } else if (cacheEntry !== undefined) { + return cacheEntry.etag === etag ? cacheEntry.data : null; + } + const oldCacheEntry = oldCache.get(identifier); + if (oldCacheEntry !== undefined) { + const cacheEntry = oldCacheEntry.entry; + if (cacheEntry === null) { + oldCache.delete(identifier); + cache.set(identifier, cacheEntry); + return null; + } else { + if (cacheEntry.etag !== etag) return null; + oldCache.delete(identifier); + cache.set(identifier, cacheEntry); + return cacheEntry.data; + } + } + gotHandlers.push((result, callback) => { + if (result === undefined) { + cache.set(identifier, null); + } else { + cache.set(identifier, { etag, data: result }); + } + return callback(); + }); + } + ); + compiler.cache.hooks.shutdown.tap( + { name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY }, + () => { + cache.clear(); + oldCache.clear(); + } + ); + } +} +module.exports = MemoryWithGcCachePlugin; /***/ }), -/***/ 16963: +/***/ 86180: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -60172,1718 +60803,1431 @@ exports.asyncModule = "__webpack_require__.a"; -const { RawSource } = __webpack_require__(51255); -const OriginalSource = (__webpack_require__(51255).OriginalSource); -const Module = __webpack_require__(73208); - -/** @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("./Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./util/Hash")} Hash */ -/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ +const FileSystemInfo = __webpack_require__(79453); +const ProgressPlugin = __webpack_require__(13216); +const { formatSize } = __webpack_require__(71070); +const SerializerMiddleware = __webpack_require__(83137); +const LazySet = __webpack_require__(38938); +const makeSerializable = __webpack_require__(33032); +const memoize = __webpack_require__(78676); +const { + createFileSerializer, + NOT_SERIALIZABLE +} = __webpack_require__(8282); -const TYPES = new Set(["runtime"]); +/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */ +/** @typedef {import("../Cache").Etag} Etag */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */ +/** @typedef {import("../logging/Logger").Logger} Logger */ +/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ -class RuntimeModule extends Module { +class PackContainer { /** - * @param {string} name a readable name - * @param {number=} stage an optional stage + * @param {Object} data stored data + * @param {string} version version identifier + * @param {Snapshot} buildSnapshot snapshot of all build dependencies + * @param {Set} buildDependencies list of all unresolved build dependencies captured + * @param {Map} resolveResults result of the resolved build dependencies + * @param {Snapshot} resolveBuildDependenciesSnapshot snapshot of the dependencies of the build dependencies resolving */ - constructor(name, stage = 0) { - super("runtime"); - this.name = name; - this.stage = stage; - this.buildMeta = {}; - this.buildInfo = {}; - /** @type {Compilation} */ - this.compilation = undefined; - /** @type {Chunk} */ - this.chunk = undefined; - /** @type {ChunkGraph} */ - this.chunkGraph = undefined; - this.fullHash = false; - this.dependentHash = false; - /** @type {string} */ - this._cachedGeneratedCode = undefined; + constructor( + data, + version, + buildSnapshot, + buildDependencies, + resolveResults, + resolveBuildDependenciesSnapshot + ) { + this.data = data; + this.version = version; + this.buildSnapshot = buildSnapshot; + this.buildDependencies = buildDependencies; + this.resolveResults = resolveResults; + this.resolveBuildDependenciesSnapshot = resolveBuildDependenciesSnapshot; } - /** - * @param {Compilation} compilation the compilation - * @param {Chunk} chunk the chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {void} - */ - attach(compilation, chunk, chunkGraph = compilation.chunkGraph) { - this.compilation = compilation; - this.chunk = chunk; - this.chunkGraph = chunkGraph; + serialize({ write, writeLazy }) { + write(this.version); + write(this.buildSnapshot); + write(this.buildDependencies); + write(this.resolveResults); + write(this.resolveBuildDependenciesSnapshot); + writeLazy(this.data); } - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return `webpack/runtime/${this.name}`; + deserialize({ read }) { + this.version = read(); + this.buildSnapshot = read(); + this.buildDependencies = read(); + this.resolveResults = read(); + this.resolveBuildDependenciesSnapshot = read(); + this.data = read(); } +} - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return `webpack/runtime/${this.name}`; - } +makeSerializable( + PackContainer, + "webpack/lib/cache/PackFileCacheStrategy", + "PackContainer" +); - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - return callback(null, false); - } +const MIN_CONTENT_SIZE = 1024 * 1024; // 1 MB +const CONTENT_COUNT_TO_MERGE = 10; +const MIN_ITEMS_IN_FRESH_PACK = 100; +const MAX_ITEMS_IN_FRESH_PACK = 50000; +const MAX_TIME_IN_FRESH_PACK = 1 * 60 * 1000; // 1 min +class PackItemInfo { /** - * @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} + * @param {string} identifier identifier of item + * @param {string | null} etag etag of item + * @param {any} value fresh value of item */ - build(options, compilation, resolver, fs, callback) { - // do nothing - // should not be called as runtime modules are added later to the compilation - callback(); + constructor(identifier, etag, value) { + this.identifier = identifier; + this.etag = etag; + this.location = -1; + this.lastAccess = Date.now(); + this.freshValue = value; } +} - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - hash.update(this.name); - hash.update(`${this.stage}`); - try { - if (this.fullHash || this.dependentHash) { - // Do not use getGeneratedCode here, because i. e. compilation hash might be not - // ready at this point. We will cache it later instead. - hash.update(this.generate()); - } else { - hash.update(this.getGeneratedCode()); - } - } catch (err) { - hash.update(err.message); - } - super.updateHash(hash, context); +class Pack { + constructor(logger, maxAge) { + /** @type {Map} */ + this.itemInfo = new Map(); + /** @type {string[]} */ + this.requests = []; + this.requestsTimeout = undefined; + /** @type {Map} */ + this.freshContent = new Map(); + /** @type {(undefined | PackContent)[]} */ + this.content = []; + this.invalid = false; + this.logger = logger; + this.maxAge = maxAge; } - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; + _addRequest(identifier) { + this.requests.push(identifier); + if (this.requestsTimeout === undefined) { + this.requestsTimeout = setTimeout(() => { + this.requests.push(undefined); + this.requestsTimeout = undefined; + }, MAX_TIME_IN_FRESH_PACK); + if (this.requestsTimeout.unref) this.requestsTimeout.unref(); + } } - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration(context) { - const sources = new Map(); - const generatedCode = this.getGeneratedCode(); - if (generatedCode) { - sources.set( - "runtime", - this.useSourceMap || this.useSimpleSourceMap - ? new OriginalSource(generatedCode, this.identifier()) - : new RawSource(generatedCode) - ); + stopCapturingRequests() { + if (this.requestsTimeout !== undefined) { + clearTimeout(this.requestsTimeout); + this.requestsTimeout = undefined; } - return { - sources, - runtimeRequirements: null - }; } /** - * @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) + * @param {string} identifier unique name for the resource + * @param {string | null} etag etag of the resource + * @returns {any} cached content */ - size(type) { - try { - const source = this.getGeneratedCode(); - return source ? source.length : 0; - } catch (e) { - return 0; + get(identifier, etag) { + const info = this.itemInfo.get(identifier); + this._addRequest(identifier); + if (info === undefined) { + return undefined; + } + if (info.etag !== etag) return null; + info.lastAccess = Date.now(); + const loc = info.location; + if (loc === -1) { + return info.freshValue; + } else { + if (!this.content[loc]) { + return undefined; + } + return this.content[loc].get(identifier); } } - /* istanbul ignore next */ /** - * @abstract - * @returns {string} runtime code + * @param {string} identifier unique name for the resource + * @param {string | null} etag etag of the resource + * @param {any} data cached content + * @returns {void} */ - generate() { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + set(identifier, etag, data) { + if (!this.invalid) { + this.invalid = true; + this.logger.log(`Pack got invalid because of write to: ${identifier}`); + } + const info = this.itemInfo.get(identifier); + if (info === undefined) { + const newInfo = new PackItemInfo(identifier, etag, data); + this.itemInfo.set(identifier, newInfo); + this._addRequest(identifier); + this.freshContent.set(identifier, newInfo); + } else { + const loc = info.location; + if (loc >= 0) { + this._addRequest(identifier); + this.freshContent.set(identifier, info); + const content = this.content[loc]; + content.delete(identifier); + if (content.items.size === 0) { + this.content[loc] = undefined; + this.logger.debug("Pack %d got empty and is removed", loc); + } + } + info.freshValue = data; + info.lastAccess = Date.now(); + info.etag = etag; + info.location = -1; + } } - /** - * @returns {string} runtime code - */ - getGeneratedCode() { - if (this._cachedGeneratedCode) { - return this._cachedGeneratedCode; + getContentStats() { + let count = 0; + let size = 0; + for (const content of this.content) { + if (content !== undefined) { + count++; + const s = content.getSize(); + if (s > 0) { + size += s; + } + } } - return (this._cachedGeneratedCode = this.generate()); + return { count, size }; } /** - * @returns {boolean} true, if the runtime module should get it's own scope + * @returns {number} new location of data entries */ - shouldIsolate() { - return true; + _findLocation() { + let i; + for (i = 0; i < this.content.length && this.content[i] !== undefined; i++); + return i; } -} - -/** - * Runtime modules without any dependencies to other runtime modules - */ -RuntimeModule.STAGE_NORMAL = 0; - -/** - * Runtime modules with simple dependencies on other runtime modules - */ -RuntimeModule.STAGE_BASIC = 5; - -/** - * Runtime modules which attach to handlers of other runtime modules - */ -RuntimeModule.STAGE_ATTACH = 10; - -/** - * Runtime modules which trigger actions on bootstrap - */ -RuntimeModule.STAGE_TRIGGER = 20; - -module.exports = RuntimeModule; - - -/***/ }), - -/***/ 2307: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const { getChunkFilenameTemplate } = __webpack_require__(47283); -const RuntimeRequirementsDependency = __webpack_require__(24187); -const JavascriptModulesPlugin = __webpack_require__(89464); -const AsyncModuleRuntimeModule = __webpack_require__(63672); -const AutoPublicPathRuntimeModule = __webpack_require__(66532); -const CompatGetDefaultExportRuntimeModule = __webpack_require__(44793); -const CompatRuntimeModule = __webpack_require__(88234); -const CreateFakeNamespaceObjectRuntimeModule = __webpack_require__(94669); -const CreateScriptRuntimeModule = __webpack_require__(2759); -const CreateScriptUrlRuntimeModule = __webpack_require__(21213); -const DefinePropertyGettersRuntimeModule = __webpack_require__(75481); -const EnsureChunkRuntimeModule = __webpack_require__(71519); -const GetChunkFilenameRuntimeModule = __webpack_require__(34277); -const GetMainFilenameRuntimeModule = __webpack_require__(10029); -const GetTrustedTypesPolicyRuntimeModule = __webpack_require__(38713); -const GlobalRuntimeModule = __webpack_require__(23255); -const HasOwnPropertyRuntimeModule = __webpack_require__(8011); -const LoadScriptRuntimeModule = __webpack_require__(19942); -const MakeNamespaceObjectRuntimeModule = __webpack_require__(65714); -const OnChunksLoadedRuntimeModule = __webpack_require__(44518); -const PublicPathRuntimeModule = __webpack_require__(56030); -const RelativeUrlRuntimeModule = __webpack_require__(4537); -const RuntimeIdRuntimeModule = __webpack_require__(97115); -const SystemContextRuntimeModule = __webpack_require__(80655); -const ShareRuntimeModule = __webpack_require__(96066); -const StringXor = __webpack_require__(40293); - -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Module")} Module */ - -const GLOBALS_ON_REQUIRE = [ - RuntimeGlobals.chunkName, - RuntimeGlobals.runtimeId, - RuntimeGlobals.compatGetDefaultExport, - RuntimeGlobals.createFakeNamespaceObject, - RuntimeGlobals.createScript, - RuntimeGlobals.createScriptUrl, - RuntimeGlobals.getTrustedTypesPolicy, - RuntimeGlobals.definePropertyGetters, - RuntimeGlobals.ensureChunk, - RuntimeGlobals.entryModuleId, - RuntimeGlobals.getFullHash, - RuntimeGlobals.global, - RuntimeGlobals.makeNamespaceObject, - RuntimeGlobals.moduleCache, - RuntimeGlobals.moduleFactories, - RuntimeGlobals.moduleFactoriesAddOnly, - RuntimeGlobals.interceptModuleExecution, - RuntimeGlobals.publicPath, - RuntimeGlobals.baseURI, - RuntimeGlobals.relativeUrl, - RuntimeGlobals.scriptNonce, - RuntimeGlobals.uncaughtErrorHandler, - RuntimeGlobals.asyncModule, - RuntimeGlobals.wasmInstances, - RuntimeGlobals.instantiateWasm, - RuntimeGlobals.shareScopeMap, - RuntimeGlobals.initializeSharing, - RuntimeGlobals.loadScript, - RuntimeGlobals.systemContext, - RuntimeGlobals.onChunksLoaded -]; - -const MODULE_DEPENDENCIES = { - [RuntimeGlobals.moduleLoaded]: [RuntimeGlobals.module], - [RuntimeGlobals.moduleId]: [RuntimeGlobals.module] -}; - -const TREE_DEPENDENCIES = { - [RuntimeGlobals.definePropertyGetters]: [RuntimeGlobals.hasOwnProperty], - [RuntimeGlobals.compatGetDefaultExport]: [ - RuntimeGlobals.definePropertyGetters - ], - [RuntimeGlobals.createFakeNamespaceObject]: [ - RuntimeGlobals.definePropertyGetters, - RuntimeGlobals.makeNamespaceObject, - RuntimeGlobals.require - ], - [RuntimeGlobals.initializeSharing]: [RuntimeGlobals.shareScopeMap], - [RuntimeGlobals.shareScopeMap]: [RuntimeGlobals.hasOwnProperty] -}; -class RuntimePlugin { - /** - * @param {Compiler} compiler the Compiler - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap("RuntimePlugin", compilation => { - compilation.dependencyTemplates.set( - RuntimeRequirementsDependency, - new RuntimeRequirementsDependency.Template() - ); - for (const req of GLOBALS_ON_REQUIRE) { - compilation.hooks.runtimeRequirementInModule - .for(req) - .tap("RuntimePlugin", (module, set) => { - set.add(RuntimeGlobals.requireScope); - }); - compilation.hooks.runtimeRequirementInTree - .for(req) - .tap("RuntimePlugin", (module, set) => { - set.add(RuntimeGlobals.requireScope); - }); - } - for (const req of Object.keys(TREE_DEPENDENCIES)) { - const deps = TREE_DEPENDENCIES[req]; - compilation.hooks.runtimeRequirementInTree - .for(req) - .tap("RuntimePlugin", (chunk, set) => { - for (const dep of deps) set.add(dep); - }); - } - for (const req of Object.keys(MODULE_DEPENDENCIES)) { - const deps = MODULE_DEPENDENCIES[req]; - compilation.hooks.runtimeRequirementInModule - .for(req) - .tap("RuntimePlugin", (chunk, set) => { - for (const dep of deps) set.add(dep); - }); + _gcAndUpdateLocation(items, usedItems, newLoc) { + let count = 0; + let lastGC; + const now = Date.now(); + for (const identifier of items) { + const info = this.itemInfo.get(identifier); + if (now - info.lastAccess > this.maxAge) { + this.itemInfo.delete(identifier); + items.delete(identifier); + usedItems.delete(identifier); + count++; + lastGC = identifier; + } else { + info.location = newLoc; } - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.definePropertyGetters) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule( - chunk, - new DefinePropertyGettersRuntimeModule() - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.makeNamespaceObject) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule( - chunk, - new MakeNamespaceObjectRuntimeModule() - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.createFakeNamespaceObject) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule( - chunk, - new CreateFakeNamespaceObjectRuntimeModule() - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hasOwnProperty) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule( - chunk, - new HasOwnPropertyRuntimeModule() - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.compatGetDefaultExport) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule( - chunk, - new CompatGetDefaultExportRuntimeModule() - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.runtimeId) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule(chunk, new RuntimeIdRuntimeModule()); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.publicPath) - .tap("RuntimePlugin", (chunk, set) => { - const { outputOptions } = compilation; - const { publicPath: globalPublicPath, scriptType } = outputOptions; - const entryOptions = chunk.getEntryOptions(); - const publicPath = - entryOptions && entryOptions.publicPath !== undefined - ? entryOptions.publicPath - : globalPublicPath; - - if (publicPath === "auto") { - const module = new AutoPublicPathRuntimeModule(); - if (scriptType !== "module") set.add(RuntimeGlobals.global); - compilation.addRuntimeModule(chunk, module); - } else { - const module = new PublicPathRuntimeModule(publicPath); - - if ( - typeof publicPath !== "string" || - /\[(full)?hash\]/.test(publicPath) - ) { - module.fullHash = true; - } - - compilation.addRuntimeModule(chunk, module); - } - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.global) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule(chunk, new GlobalRuntimeModule()); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.asyncModule) - .tap("RuntimePlugin", chunk => { - compilation.addRuntimeModule(chunk, new AsyncModuleRuntimeModule()); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.systemContext) - .tap("RuntimePlugin", chunk => { - const { outputOptions } = compilation; - const { library: globalLibrary } = outputOptions; - const entryOptions = chunk.getEntryOptions(); - const libraryType = - entryOptions && entryOptions.library !== undefined - ? entryOptions.library.type - : globalLibrary.type; + } + if (count > 0) { + this.logger.log( + "Garbage Collected %d old items at pack %d (%d items remaining) e. g. %s", + count, + newLoc, + items.size, + lastGC + ); + } + } - if (libraryType === "system") { - compilation.addRuntimeModule( - chunk, - new SystemContextRuntimeModule() - ); - } - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.getChunkScriptFilename) - .tap("RuntimePlugin", (chunk, set) => { - if ( - typeof compilation.outputOptions.chunkFilename === "string" && - /\[(full)?hash(:\d+)?\]/.test( - compilation.outputOptions.chunkFilename - ) - ) { - set.add(RuntimeGlobals.getFullHash); - } - compilation.addRuntimeModule( - chunk, - new GetChunkFilenameRuntimeModule( - "javascript", - "javascript", - RuntimeGlobals.getChunkScriptFilename, - chunk => - chunk.filenameTemplate || - (chunk.canBeInitial() - ? compilation.outputOptions.filename - : compilation.outputOptions.chunkFilename), - false - ) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.getChunkCssFilename) - .tap("RuntimePlugin", (chunk, set) => { - if ( - typeof compilation.outputOptions.cssChunkFilename === "string" && - /\[(full)?hash(:\d+)?\]/.test( - compilation.outputOptions.cssChunkFilename - ) - ) { - set.add(RuntimeGlobals.getFullHash); - } - compilation.addRuntimeModule( - chunk, - new GetChunkFilenameRuntimeModule( - "css", - "css", - RuntimeGlobals.getChunkCssFilename, - chunk => - getChunkFilenameTemplate(chunk, compilation.outputOptions), - set.has(RuntimeGlobals.hmrDownloadUpdateHandlers) - ) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.getChunkUpdateScriptFilename) - .tap("RuntimePlugin", (chunk, set) => { - if ( - /\[(full)?hash(:\d+)?\]/.test( - compilation.outputOptions.hotUpdateChunkFilename - ) - ) - set.add(RuntimeGlobals.getFullHash); - compilation.addRuntimeModule( - chunk, - new GetChunkFilenameRuntimeModule( - "javascript", - "javascript update", - RuntimeGlobals.getChunkUpdateScriptFilename, - c => compilation.outputOptions.hotUpdateChunkFilename, - true - ) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.getUpdateManifestFilename) - .tap("RuntimePlugin", (chunk, set) => { - if ( - /\[(full)?hash(:\d+)?\]/.test( - compilation.outputOptions.hotUpdateMainFilename - ) - ) { - set.add(RuntimeGlobals.getFullHash); - } - compilation.addRuntimeModule( - chunk, - new GetMainFilenameRuntimeModule( - "update manifest", - RuntimeGlobals.getUpdateManifestFilename, - compilation.outputOptions.hotUpdateMainFilename - ) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunk) - .tap("RuntimePlugin", (chunk, set) => { - const hasAsyncChunks = chunk.hasAsyncChunks(); - if (hasAsyncChunks) { - set.add(RuntimeGlobals.ensureChunkHandlers); - } - compilation.addRuntimeModule( - chunk, - new EnsureChunkRuntimeModule(set) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkIncludeEntries) - .tap("RuntimePlugin", (chunk, set) => { - set.add(RuntimeGlobals.ensureChunkHandlers); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.shareScopeMap) - .tap("RuntimePlugin", (chunk, set) => { - compilation.addRuntimeModule(chunk, new ShareRuntimeModule()); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.loadScript) - .tap("RuntimePlugin", (chunk, set) => { - const withCreateScriptUrl = !!compilation.outputOptions.trustedTypes; - if (withCreateScriptUrl) { - set.add(RuntimeGlobals.createScriptUrl); - } - compilation.addRuntimeModule( - chunk, - new LoadScriptRuntimeModule(withCreateScriptUrl) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.createScript) - .tap("RuntimePlugin", (chunk, set) => { - if (compilation.outputOptions.trustedTypes) { - set.add(RuntimeGlobals.getTrustedTypesPolicy); - } - compilation.addRuntimeModule(chunk, new CreateScriptRuntimeModule()); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.createScriptUrl) - .tap("RuntimePlugin", (chunk, set) => { - if (compilation.outputOptions.trustedTypes) { - set.add(RuntimeGlobals.getTrustedTypesPolicy); - } - compilation.addRuntimeModule( - chunk, - new CreateScriptUrlRuntimeModule() - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.getTrustedTypesPolicy) - .tap("RuntimePlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new GetTrustedTypesPolicyRuntimeModule(set) - ); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.relativeUrl) - .tap("RuntimePlugin", (chunk, set) => { - compilation.addRuntimeModule(chunk, new RelativeUrlRuntimeModule()); - return true; - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.onChunksLoaded) - .tap("RuntimePlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new OnChunksLoadedRuntimeModule() - ); - return true; - }); - // TODO webpack 6: remove CompatRuntimeModule - compilation.hooks.additionalTreeRuntimeRequirements.tap( - "RuntimePlugin", - (chunk, set) => { - const { mainTemplate } = compilation; - if ( - mainTemplate.hooks.bootstrap.isUsed() || - mainTemplate.hooks.localVars.isUsed() || - mainTemplate.hooks.requireEnsure.isUsed() || - mainTemplate.hooks.requireExtensions.isUsed() - ) { - compilation.addRuntimeModule(chunk, new CompatRuntimeModule()); + _persistFreshContent() { + const itemsCount = this.freshContent.size; + if (itemsCount > 0) { + const packCount = Math.ceil(itemsCount / MAX_ITEMS_IN_FRESH_PACK); + const itemsPerPack = Math.ceil(itemsCount / packCount); + const packs = []; + let i = 0; + let ignoreNextTimeTick = false; + const createNextPack = () => { + const loc = this._findLocation(); + this.content[loc] = null; // reserve + const pack = { + /** @type {Set} */ + items: new Set(), + /** @type {Map} */ + map: new Map(), + loc + }; + packs.push(pack); + return pack; + }; + let pack = createNextPack(); + if (this.requestsTimeout !== undefined) + clearTimeout(this.requestsTimeout); + for (const identifier of this.requests) { + if (identifier === undefined) { + if (ignoreNextTimeTick) { + ignoreNextTimeTick = false; + } else if (pack.items.size >= MIN_ITEMS_IN_FRESH_PACK) { + i = 0; + pack = createNextPack(); } + continue; } - ); - JavascriptModulesPlugin.getCompilationHooks(compilation).chunkHash.tap( - "RuntimePlugin", - (chunk, hash, { chunkGraph }) => { - const xor = new StringXor(); - for (const m of chunkGraph.getChunkRuntimeModulesIterable(chunk)) { - xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); - } - xor.updateHash(hash); + const info = this.freshContent.get(identifier); + if (info === undefined) continue; + pack.items.add(identifier); + pack.map.set(identifier, info.freshValue); + info.location = pack.loc; + info.freshValue = undefined; + this.freshContent.delete(identifier); + if (++i > itemsPerPack) { + i = 0; + pack = createNextPack(); + ignoreNextTimeTick = true; } + } + this.requests.length = 0; + for (const pack of packs) { + this.content[pack.loc] = new PackContent( + pack.items, + new Set(pack.items), + new PackContentItems(pack.map) + ); + } + this.logger.log( + `${itemsCount} fresh items in cache put into pack ${ + packs.length > 1 + ? packs + .map(pack => `${pack.loc} (${pack.items.size} items)`) + .join(", ") + : packs[0].loc + }` ); - }); + } } -} -module.exports = RuntimePlugin; - - -/***/ }), - -/***/ 18777: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + /** + * Merges small content files to a single content file + */ + _optimizeSmallContent() { + // 1. Find all small content files + // Treat unused content files separately to avoid + // a merge-split cycle + /** @type {number[]} */ + const smallUsedContents = []; + /** @type {number} */ + let smallUsedContentSize = 0; + /** @type {number[]} */ + const smallUnusedContents = []; + /** @type {number} */ + let smallUnusedContentSize = 0; + for (let i = 0; i < this.content.length; i++) { + const content = this.content[i]; + if (content === undefined) continue; + if (content.outdated) continue; + const size = content.getSize(); + if (size < 0 || size > MIN_CONTENT_SIZE) continue; + if (content.used.size > 0) { + smallUsedContents.push(i); + smallUsedContentSize += size; + } else { + smallUnusedContents.push(i); + smallUnusedContentSize += size; + } + } -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const { equals } = __webpack_require__(84953); -const compileBooleanMatcher = __webpack_require__(29404); -const propertyAccess = __webpack_require__(54190); -const { forEachRuntime, subtractRuntime } = __webpack_require__(17156); + // 2. Check if minimum number is reached + let mergedIndices; + if ( + smallUsedContents.length >= CONTENT_COUNT_TO_MERGE || + smallUsedContentSize > MIN_CONTENT_SIZE + ) { + mergedIndices = smallUsedContents; + } else if ( + smallUnusedContents.length >= CONTENT_COUNT_TO_MERGE || + smallUnusedContentSize > MIN_CONTENT_SIZE + ) { + mergedIndices = smallUnusedContents; + } else return; -/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */ -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ + const mergedContent = []; -/** - * @param {Module} module the module - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {string} error message - */ -const noModuleIdErrorMessage = (module, chunkGraph) => { - return `Module ${module.identifier()} has no id assigned. -This should not happen. -It's in these chunks: ${ - Array.from( - chunkGraph.getModuleChunksIterable(module), - c => c.name || c.id || c.debugId - ).join(", ") || "none" - } (If module is in no chunk this indicates a bug in some chunk/module optimization logic) -Module has these incoming connections: ${Array.from( - chunkGraph.moduleGraph.getIncomingConnections(module), - connection => - `\n - ${ - connection.originModule && connection.originModule.identifier() - } ${connection.dependency && connection.dependency.type} ${ - (connection.explanations && - Array.from(connection.explanations).join(", ")) || - "" - }` - ).join("")}`; -}; + // 3. Remove old content entries + for (const i of mergedIndices) { + mergedContent.push(this.content[i]); + this.content[i] = undefined; + } -/** - * @param {string|undefined} definition global object definition - * @returns {string} save to use global object - */ -function getGlobalObject(definition) { - if (!definition) return definition; - const trimmed = definition.trim(); + // 4. Determine merged items + /** @type {Set} */ + const mergedItems = new Set(); + /** @type {Set} */ + const mergedUsedItems = new Set(); + /** @type {(function(Map): Promise)[]} */ + const addToMergedMap = []; + for (const content of mergedContent) { + for (const identifier of content.items) { + mergedItems.add(identifier); + } + for (const identifier of content.used) { + mergedUsedItems.add(identifier); + } + addToMergedMap.push(async map => { + // unpack existing content + // after that values are accessible in .content + await content.unpack( + "it should be merged with other small pack contents" + ); + for (const [identifier, value] of content.content) { + map.set(identifier, value); + } + }); + } - if ( - // identifier, we do not need real identifier regarding ECMAScript/Unicode - trimmed.match(/^[_\p{L}][_0-9\p{L}]*$/iu) || - // iife - // call expression - // expression in parentheses - trimmed.match(/^([_\p{L}][_0-9\p{L}]*)?\(.*\)$/iu) - ) - return trimmed; + // 5. GC and update location of merged items + const newLoc = this._findLocation(); + this._gcAndUpdateLocation(mergedItems, mergedUsedItems, newLoc); - return `Object(${trimmed})`; -} + // 6. If not empty, store content somewhere + if (mergedItems.size > 0) { + this.content[newLoc] = new PackContent( + mergedItems, + mergedUsedItems, + memoize(async () => { + /** @type {Map} */ + const map = new Map(); + await Promise.all(addToMergedMap.map(fn => fn(map))); + return new PackContentItems(map); + }) + ); + this.logger.log( + "Merged %d small files with %d cache items into pack %d", + mergedContent.length, + mergedItems.size, + newLoc + ); + } + } -class RuntimeTemplate { /** - * @param {Compilation} compilation the compilation - * @param {OutputOptions} outputOptions the compilation output options - * @param {RequestShortener} requestShortener the request shortener + * Split large content files with used and unused items + * into two parts to separate used from unused items */ - constructor(compilation, outputOptions, requestShortener) { - this.compilation = compilation; - this.outputOptions = outputOptions || {}; - this.requestShortener = requestShortener; - this.globalObject = getGlobalObject(outputOptions.globalObject); - } - - isIIFE() { - return this.outputOptions.iife; - } - - isModule() { - return this.outputOptions.module; - } + _optimizeUnusedContent() { + // 1. Find a large content file with used and unused items + for (let i = 0; i < this.content.length; i++) { + const content = this.content[i]; + if (content === undefined) continue; + const size = content.getSize(); + if (size < MIN_CONTENT_SIZE) continue; + const used = content.used.size; + const total = content.items.size; + if (used > 0 && used < total) { + // 2. Remove this content + this.content[i] = undefined; - supportsConst() { - return this.outputOptions.environment.const; - } + // 3. Determine items for the used content file + const usedItems = new Set(content.used); + const newLoc = this._findLocation(); + this._gcAndUpdateLocation(usedItems, usedItems, newLoc); - supportsArrowFunction() { - return this.outputOptions.environment.arrowFunction; - } + // 4. Create content file for used items + if (usedItems.size > 0) { + this.content[newLoc] = new PackContent( + usedItems, + new Set(usedItems), + async () => { + await content.unpack( + "it should be splitted into used and unused items" + ); + const map = new Map(); + for (const identifier of usedItems) { + map.set(identifier, content.content.get(identifier)); + } + return new PackContentItems(map); + } + ); + } - supportsOptionalChaining() { - return this.outputOptions.environment.optionalChaining; - } + // 5. Determine items for the unused content file + const unusedItems = new Set(content.items); + const usedOfUnusedItems = new Set(); + for (const identifier of usedItems) { + unusedItems.delete(identifier); + } + const newUnusedLoc = this._findLocation(); + this._gcAndUpdateLocation(unusedItems, usedOfUnusedItems, newUnusedLoc); - supportsForOf() { - return this.outputOptions.environment.forOf; - } + // 6. Create content file for unused items + if (unusedItems.size > 0) { + this.content[newUnusedLoc] = new PackContent( + unusedItems, + usedOfUnusedItems, + async () => { + await content.unpack( + "it should be splitted into used and unused items" + ); + const map = new Map(); + for (const identifier of unusedItems) { + map.set(identifier, content.content.get(identifier)); + } + return new PackContentItems(map); + } + ); + } - supportsDestructuring() { - return this.outputOptions.environment.destructuring; - } + this.logger.log( + "Split pack %d into pack %d with %d used items and pack %d with %d unused items", + i, + newLoc, + usedItems.size, + newUnusedLoc, + unusedItems.size + ); - supportsBigIntLiteral() { - return this.outputOptions.environment.bigIntLiteral; + // optimizing only one of them is good enough and + // reduces the amount of serialization needed + return; + } + } } - supportsDynamicImport() { - return this.outputOptions.environment.dynamicImport; - } + /** + * Find the content with the oldest item and run GC on that. + * Only runs for one content to avoid large invalidation. + */ + _gcOldestContent() { + /** @type {PackItemInfo} */ + let oldest = undefined; + for (const info of this.itemInfo.values()) { + if (oldest === undefined || info.lastAccess < oldest.lastAccess) { + oldest = info; + } + } + if (Date.now() - oldest.lastAccess > this.maxAge) { + const loc = oldest.location; + if (loc < 0) return; + const content = this.content[loc]; + const items = new Set(content.items); + const usedItems = new Set(content.used); + this._gcAndUpdateLocation(items, usedItems, loc); - supportsEcmaScriptModuleSyntax() { - return this.outputOptions.environment.module; + this.content[loc] = + items.size > 0 + ? new PackContent(items, usedItems, async () => { + await content.unpack( + "it contains old items that should be garbage collected" + ); + const map = new Map(); + for (const identifier of items) { + map.set(identifier, content.content.get(identifier)); + } + return new PackContentItems(map); + }) + : undefined; + } } - supportTemplateLiteral() { - return this.outputOptions.environment.templateLiteral; + serialize({ write, writeSeparate }) { + this._persistFreshContent(); + this._optimizeSmallContent(); + this._optimizeUnusedContent(); + this._gcOldestContent(); + for (const identifier of this.itemInfo.keys()) { + write(identifier); + } + write(null); // null as marker of the end of keys + for (const info of this.itemInfo.values()) { + write(info.etag); + } + for (const info of this.itemInfo.values()) { + write(info.lastAccess); + } + for (let i = 0; i < this.content.length; i++) { + const content = this.content[i]; + if (content !== undefined) { + write(content.items); + content.writeLazy(lazy => writeSeparate(lazy, { name: `${i}` })); + } else { + write(undefined); // undefined marks an empty content slot + } + } + write(null); // null as marker of the end of items } - returningFunction(returnValue, args = "") { - return this.supportsArrowFunction() - ? `(${args}) => (${returnValue})` - : `function(${args}) { return ${returnValue}; }`; + deserialize({ read, logger }) { + this.logger = logger; + { + const items = []; + let item = read(); + while (item !== null) { + items.push(item); + item = read(); + } + this.itemInfo.clear(); + const infoItems = items.map(identifier => { + const info = new PackItemInfo(identifier, undefined, undefined); + this.itemInfo.set(identifier, info); + return info; + }); + for (const info of infoItems) { + info.etag = read(); + } + for (const info of infoItems) { + info.lastAccess = read(); + } + } + this.content.length = 0; + let items = read(); + while (items !== null) { + if (items === undefined) { + this.content.push(items); + } else { + const idx = this.content.length; + const lazy = read(); + this.content.push( + new PackContent( + items, + new Set(), + lazy, + logger, + `${this.content.length}` + ) + ); + for (const identifier of items) { + this.itemInfo.get(identifier).location = idx; + } + } + items = read(); + } } +} - basicFunction(args, body) { - return this.supportsArrowFunction() - ? `(${args}) => {\n${Template.indent(body)}\n}` - : `function(${args}) {\n${Template.indent(body)}\n}`; - } +makeSerializable(Pack, "webpack/lib/cache/PackFileCacheStrategy", "Pack"); +class PackContentItems { /** - * @param {Array} args args - * @returns {string} result expression + * @param {Map} map items */ - concatenation(...args) { - const len = args.length; + constructor(map) { + this.map = map; + } - if (len === 2) return this._es5Concatenation(args); - if (len === 0) return '""'; - if (len === 1) { - return typeof args[0] === "string" - ? JSON.stringify(args[0]) - : `"" + ${args[0].expr}`; + serialize({ write, snapshot, rollback, logger, profile }) { + if (profile) { + write(false); + for (const [key, value] of this.map) { + const s = snapshot(); + try { + write(key); + const start = process.hrtime(); + write(value); + const durationHr = process.hrtime(start); + const duration = durationHr[0] * 1000 + durationHr[1] / 1e6; + if (duration > 1) { + if (duration > 500) + logger.error(`Serialization of '${key}': ${duration} ms`); + else if (duration > 50) + logger.warn(`Serialization of '${key}': ${duration} ms`); + else if (duration > 10) + logger.info(`Serialization of '${key}': ${duration} ms`); + else if (duration > 5) + logger.log(`Serialization of '${key}': ${duration} ms`); + else logger.debug(`Serialization of '${key}': ${duration} ms`); + } + } catch (e) { + rollback(s); + if (e === NOT_SERIALIZABLE) continue; + logger.warn( + `Skipped not serializable cache item '${key}': ${e.message}` + ); + logger.debug(e.stack); + } + } + write(null); + return; } - if (!this.supportTemplateLiteral()) return this._es5Concatenation(args); - - // cost comparison between template literal and concatenation: - // both need equal surroundings: `xxx` vs "xxx" - // template literal has constant cost of 3 chars for each expression - // es5 concatenation has cost of 3 + n chars for n expressions in row - // when a es5 concatenation ends with an expression it reduces cost by 3 - // when a es5 concatenation starts with an single expression it reduces cost by 3 - // e. g. `${a}${b}${c}` (3*3 = 9) is longer than ""+a+b+c ((3+3)-3 = 3) - // e. g. `x${a}x${b}x${c}x` (3*3 = 9) is shorter than "x"+a+"x"+b+"x"+c+"x" (4+4+4 = 12) - - let templateCost = 0; - let concatenationCost = 0; + // Try to serialize all at once + const s = snapshot(); + try { + write(true); + write(this.map); + } catch (e) { + rollback(s); - let lastWasExpr = false; - for (const arg of args) { - const isExpr = typeof arg !== "string"; - if (isExpr) { - templateCost += 3; - concatenationCost += lastWasExpr ? 1 : 4; + // Try to serialize each item on it's own + write(false); + for (const [key, value] of this.map) { + const s = snapshot(); + try { + write(key); + write(value); + } catch (e) { + rollback(s); + if (e === NOT_SERIALIZABLE) continue; + logger.warn( + `Skipped not serializable cache item '${key}': ${e.message}` + ); + logger.debug(e.stack); + } } - lastWasExpr = isExpr; + write(null); } - if (lastWasExpr) concatenationCost -= 3; - if (typeof args[0] !== "string" && typeof args[1] === "string") - concatenationCost -= 3; - - if (concatenationCost <= templateCost) return this._es5Concatenation(args); - - return `\`${args - .map(arg => (typeof arg === "string" ? arg : `\${${arg.expr}}`)) - .join("")}\``; - } - - /** - * @param {Array} args args (len >= 2) - * @returns {string} result expression - * @private - */ - _es5Concatenation(args) { - const str = args - .map(arg => (typeof arg === "string" ? JSON.stringify(arg) : arg.expr)) - .join(" + "); - - // when the first two args are expression, we need to prepend "" + to force string - // concatenation instead of number addition. - return typeof args[0] !== "string" && typeof args[1] !== "string" - ? `"" + ${str}` - : str; - } - - expressionFunction(expression, args = "") { - return this.supportsArrowFunction() - ? `(${args}) => (${expression})` - : `function(${args}) { ${expression}; }`; - } - - emptyFunction() { - return this.supportsArrowFunction() ? "x => {}" : "function() {}"; - } - - destructureArray(items, value) { - return this.supportsDestructuring() - ? `var [${items.join(", ")}] = ${value};` - : Template.asString( - items.map((item, i) => `var ${item} = ${value}[${i}];`) - ); - } - - destructureObject(items, value) { - return this.supportsDestructuring() - ? `var {${items.join(", ")}} = ${value};` - : Template.asString( - items.map(item => `var ${item} = ${value}${propertyAccess([item])};`) - ); - } - - iife(args, body) { - return `(${this.basicFunction(args, body)})()`; - } - - forEach(variable, array, body) { - return this.supportsForOf() - ? `for(const ${variable} of ${array}) {\n${Template.indent(body)}\n}` - : `${array}.forEach(function(${variable}) {\n${Template.indent( - body - )}\n});`; } - /** - * Add a comment - * @param {object} options Information content of the comment - * @param {string=} options.request request string used originally - * @param {string=} options.chunkName name of the chunk referenced - * @param {string=} options.chunkReason reason information of the chunk - * @param {string=} options.message additional message - * @param {string=} options.exportName name of the export - * @returns {string} comment - */ - comment({ request, chunkName, chunkReason, message, exportName }) { - let content; - if (this.outputOptions.pathinfo) { - content = [message, request, chunkName, chunkReason] - .filter(Boolean) - .map(item => this.requestShortener.shorten(item)) - .join(" | "); - } else { - content = [message, chunkName, chunkReason] - .filter(Boolean) - .map(item => this.requestShortener.shorten(item)) - .join(" | "); - } - if (!content) return ""; - if (this.outputOptions.pathinfo) { - return Template.toComment(content) + " "; + deserialize({ read, logger, profile }) { + if (read()) { + this.map = read(); + } else if (profile) { + const map = new Map(); + let key = read(); + while (key !== null) { + const start = process.hrtime(); + const value = read(); + const durationHr = process.hrtime(start); + const duration = durationHr[0] * 1000 + durationHr[1] / 1e6; + if (duration > 1) { + if (duration > 100) + logger.error(`Deserialization of '${key}': ${duration} ms`); + else if (duration > 20) + logger.warn(`Deserialization of '${key}': ${duration} ms`); + else if (duration > 5) + logger.info(`Deserialization of '${key}': ${duration} ms`); + else if (duration > 2) + logger.log(`Deserialization of '${key}': ${duration} ms`); + else logger.debug(`Deserialization of '${key}': ${duration} ms`); + } + map.set(key, value); + key = read(); + } + this.map = map; } else { - return Template.toNormalComment(content) + " "; + const map = new Map(); + let key = read(); + while (key !== null) { + map.set(key, read()); + key = read(); + } + this.map = map; } } +} - /** - * @param {object} options generation options - * @param {string=} options.request request string used originally - * @returns {string} generated error block - */ - throwMissingModuleErrorBlock({ request }) { - const err = `Cannot find module '${request}'`; - return `var e = new Error(${JSON.stringify( - err - )}); e.code = 'MODULE_NOT_FOUND'; throw e;`; - } - - /** - * @param {object} options generation options - * @param {string=} options.request request string used originally - * @returns {string} generated error function - */ - throwMissingModuleErrorFunction({ request }) { - return `function webpackMissingModule() { ${this.throwMissingModuleErrorBlock( - { request } - )} }`; - } +makeSerializable( + PackContentItems, + "webpack/lib/cache/PackFileCacheStrategy", + "PackContentItems" +); - /** - * @param {object} options generation options - * @param {string=} options.request request string used originally - * @returns {string} generated error IIFE - */ - missingModule({ request }) { - return `Object(${this.throwMissingModuleErrorFunction({ request })}())`; - } +class PackContent { + /* + This class can be in these states: + | this.lazy | this.content | this.outdated | state + A1 | undefined | Map | false | fresh content + A2 | undefined | Map | true | (will not happen) + B1 | lazy () => {} | undefined | false | not deserialized + B2 | lazy () => {} | undefined | true | not deserialized, but some items has been removed + C1 | lazy* () => {} | Map | false | deserialized + C2 | lazy* () => {} | Map | true | deserialized, and some items has been removed - /** - * @param {object} options generation options - * @param {string=} options.request request string used originally - * @returns {string} generated error statement - */ - missingModuleStatement({ request }) { - return `${this.missingModule({ request })};\n`; - } + this.used is a subset of this.items. + this.items is a subset of this.content.keys() resp. this.lazy().map.keys() + When this.outdated === false, this.items === this.content.keys() resp. this.lazy().map.keys() + When this.outdated === true, this.items should be used to recreated this.lazy/this.content. + When this.lazy and this.content is set, they contain the same data. + this.get must only be called with a valid item from this.items. + In state C this.lazy is unMemoized + */ /** - * @param {object} options generation options - * @param {string=} options.request request string used originally - * @returns {string} generated error code + * @param {Set} items keys + * @param {Set} usedItems used keys + * @param {PackContentItems | function(): Promise} dataOrFn sync or async content + * @param {Logger=} logger logger for logging + * @param {string=} lazyName name of dataOrFn for logging */ - missingModulePromise({ request }) { - return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({ - request - })})`; + constructor(items, usedItems, dataOrFn, logger, lazyName) { + this.items = items; + /** @type {function(): Promise | PackContentItems} */ + this.lazy = typeof dataOrFn === "function" ? dataOrFn : undefined; + /** @type {Map} */ + this.content = typeof dataOrFn === "function" ? undefined : dataOrFn.map; + this.outdated = false; + this.used = usedItems; + this.logger = logger; + this.lazyName = lazyName; } - /** - * @param {Object} options options object - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {Module} options.module the module - * @param {string} options.request the request that should be printed as comment - * @param {string=} options.idExpr expression to use as id expression - * @param {"expression" | "promise" | "statements"} options.type which kind of code should be returned - * @returns {string} the code - */ - weakError({ module, chunkGraph, request, idExpr, type }) { - const moduleId = chunkGraph.getModuleId(module); - const errorMessage = - moduleId === null - ? JSON.stringify("Module is not available (weak dependency)") - : idExpr - ? `"Module '" + ${idExpr} + "' is not available (weak dependency)"` - : JSON.stringify( - `Module '${moduleId}' is not available (weak dependency)` - ); - const comment = request ? Template.toNormalComment(request) + " " : ""; - const errorStatements = - `var e = new Error(${errorMessage}); ` + - comment + - "e.code = 'MODULE_NOT_FOUND'; throw e;"; - switch (type) { - case "statements": - return errorStatements; - case "promise": - return `Promise.resolve().then(${this.basicFunction( - "", - errorStatements - )})`; - case "expression": - return this.iife("", errorStatements); + get(identifier) { + this.used.add(identifier); + if (this.content) { + return this.content.get(identifier); } - } - /** - * @param {Object} options options object - * @param {Module} options.module the module - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {string} options.request the request that should be printed as comment - * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) - * @returns {string} the expression - */ - moduleId({ module, chunkGraph, request, weak }) { - if (!module) { - return this.missingModule({ - request - }); + // We are in state B + const { lazyName } = this; + let timeMessage; + if (lazyName) { + // only log once + this.lazyName = undefined; + timeMessage = `restore cache content ${lazyName} (${formatSize( + this.getSize() + )})`; + this.logger.log( + `starting to restore cache content ${lazyName} (${formatSize( + this.getSize() + )}) because of request to: ${identifier}` + ); + this.logger.time(timeMessage); } - const moduleId = chunkGraph.getModuleId(module); - if (moduleId === null) { - if (weak) { - return "null /* weak dependency, without id */"; + const value = this.lazy(); + if ("then" in value) { + return value.then(data => { + const map = data.map; + if (timeMessage) { + this.logger.timeEnd(timeMessage); + } + // Move to state C + this.content = map; + this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + return map.get(identifier); + }); + } else { + const map = value.map; + if (timeMessage) { + this.logger.timeEnd(timeMessage); } - throw new Error( - `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage( - module, - chunkGraph - )}` - ); + // Move to state C + this.content = map; + this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + return map.get(identifier); } - return `${this.comment({ request })}${JSON.stringify(moduleId)}`; } /** - * @param {Object} options options object - * @param {Module} options.module the module - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {string} options.request the request that should be printed as comment - * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} the expression + * @param {string} reason explanation why unpack is necessary + * @returns {void | Promise} maybe a promise if lazy */ - moduleRaw({ module, chunkGraph, request, weak, runtimeRequirements }) { - if (!module) { - return this.missingModule({ - request - }); - } - const moduleId = chunkGraph.getModuleId(module); - if (moduleId === null) { - if (weak) { - // only weak referenced modules don't get an id - // we can always emit an error emitting code here - return this.weakError({ - module, - chunkGraph, - request, - type: "expression" + unpack(reason) { + if (this.content) return; + + // Move from state B to C + if (this.lazy) { + const { lazyName } = this; + let timeMessage; + if (lazyName) { + // only log once + this.lazyName = undefined; + timeMessage = `unpack cache content ${lazyName} (${formatSize( + this.getSize() + )})`; + this.logger.log( + `starting to unpack cache content ${lazyName} (${formatSize( + this.getSize() + )}) because ${reason}` + ); + this.logger.time(timeMessage); + } + const value = this.lazy(); + if ("then" in value) { + return value.then(data => { + if (timeMessage) { + this.logger.timeEnd(timeMessage); + } + this.content = data.map; }); + } else { + if (timeMessage) { + this.logger.timeEnd(timeMessage); + } + this.content = value.map; } - throw new Error( - `RuntimeTemplate.moduleId(): ${noModuleIdErrorMessage( - module, - chunkGraph - )}` - ); } - runtimeRequirements.add(RuntimeGlobals.require); - return `__webpack_require__(${this.moduleId({ - module, - chunkGraph, - request, - weak - })})`; } /** - * @param {Object} options options object - * @param {Module} options.module the module - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {string} options.request the request that should be printed as comment - * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} the expression + * @returns {number} size of the content or -1 if not known */ - moduleExports({ module, chunkGraph, request, weak, runtimeRequirements }) { - return this.moduleRaw({ - module, - chunkGraph, - request, - weak, - runtimeRequirements - }); + getSize() { + if (!this.lazy) return -1; + const options = /** @type {any} */ (this.lazy).options; + if (!options) return -1; + const size = options.size; + if (typeof size !== "number") return -1; + return size; } - /** - * @param {Object} options options object - * @param {Module} options.module the module - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {string} options.request the request that should be printed as comment - * @param {boolean=} options.strict if the current module is in strict esm mode - * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} the expression - */ - moduleNamespace({ - module, - chunkGraph, - request, - strict, - weak, - runtimeRequirements - }) { - if (!module) { - return this.missingModule({ - request - }); - } - if (chunkGraph.getModuleId(module) === null) { - if (weak) { - // only weak referenced modules don't get an id - // we can always emit an error emitting code here - return this.weakError({ - module, - chunkGraph, - request, - type: "expression" - }); - } - throw new Error( - `RuntimeTemplate.moduleNamespace(): ${noModuleIdErrorMessage( - module, - chunkGraph - )}` - ); - } - const moduleId = this.moduleId({ - module, - chunkGraph, - request, - weak - }); - const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict); - switch (exportsType) { - case "namespace": - return this.moduleRaw({ - module, - chunkGraph, - request, - weak, - runtimeRequirements - }); - case "default-with-named": - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 3)`; - case "default-only": - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 1)`; - case "dynamic": - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - return `${RuntimeGlobals.createFakeNamespaceObject}(${moduleId}, 7)`; - } + delete(identifier) { + this.items.delete(identifier); + this.used.delete(identifier); + this.outdated = true; } /** - * @param {Object} options options object - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {AsyncDependenciesBlock=} options.block the current dependencies block - * @param {Module} options.module the module - * @param {string} options.request the request that should be printed as comment - * @param {string} options.message a message for the comment - * @param {boolean=} options.strict if the current module is in strict esm mode - * @param {boolean=} options.weak if the dependency is weak (will create a nice error message) - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} the promise expression + * @template T + * @param {function(any): function(): Promise | PackContentItems} write write function + * @returns {void} */ - moduleNamespacePromise({ - chunkGraph, - block, - module, - request, - message, - strict, - weak, - runtimeRequirements - }) { - if (!module) { - return this.missingModulePromise({ - request - }); + writeLazy(write) { + if (!this.outdated && this.lazy) { + // State B1 or C1 + // this.lazy is still the valid deserialized version + write(this.lazy); + return; } - const moduleId = chunkGraph.getModuleId(module); - if (moduleId === null) { - if (weak) { - // only weak referenced modules don't get an id - // we can always emit an error emitting code here - return this.weakError({ - module, - chunkGraph, - request, - type: "promise" - }); - } - throw new Error( - `RuntimeTemplate.moduleNamespacePromise(): ${noModuleIdErrorMessage( - module, - chunkGraph - )}` + if (!this.outdated && this.content) { + // State A1 + const map = new Map(this.content); + // Move to state C1 + this.lazy = SerializerMiddleware.unMemoizeLazy( + write(() => new PackContentItems(map)) ); + return; } - const promise = this.blockPromise({ - chunkGraph, - block, - message, - runtimeRequirements - }); - - let appending; - let idExpr = JSON.stringify(chunkGraph.getModuleId(module)); - const comment = this.comment({ - request - }); - let header = ""; - if (weak) { - if (idExpr.length > 8) { - // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"' - header += `var id = ${idExpr}; `; - idExpr = "id"; + if (this.content) { + // State A2 or C2 + /** @type {Map} */ + const map = new Map(); + for (const item of this.items) { + map.set(item, this.content.get(item)); } - runtimeRequirements.add(RuntimeGlobals.moduleFactories); - header += `if(!${ - RuntimeGlobals.moduleFactories - }[${idExpr}]) { ${this.weakError({ - module, - chunkGraph, - request, - idExpr, - type: "statements" - })} } `; + // Move to state C1 + this.outdated = false; + this.content = map; + this.lazy = SerializerMiddleware.unMemoizeLazy( + write(() => new PackContentItems(map)) + ); + return; } - const moduleIdExpr = this.moduleId({ - module, - chunkGraph, - request, - weak - }); - const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict); - let fakeType = 16; - switch (exportsType) { - case "namespace": - if (header) { - const rawModule = this.moduleRaw({ - module, - chunkGraph, - request, - weak, - runtimeRequirements - }); - appending = `.then(${this.basicFunction( - "", - `${header}return ${rawModule};` - )})`; - } else { - runtimeRequirements.add(RuntimeGlobals.require); - appending = `.then(__webpack_require__.bind(__webpack_require__, ${comment}${idExpr}))`; - } - break; - case "dynamic": - fakeType |= 4; - /* fall through */ - case "default-with-named": - fakeType |= 2; - /* fall through */ - case "default-only": - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - if (chunkGraph.moduleGraph.isAsync(module)) { - if (header) { - const rawModule = this.moduleRaw({ - module, - chunkGraph, - request, - weak, - runtimeRequirements - }); - appending = `.then(${this.basicFunction( - "", - `${header}return ${rawModule};` - )})`; - } else { - runtimeRequirements.add(RuntimeGlobals.require); - appending = `.then(__webpack_require__.bind(__webpack_require__, ${comment}${idExpr}))`; + // State B2 + const { lazyName } = this; + let timeMessage; + if (lazyName) { + // only log once + this.lazyName = undefined; + timeMessage = `unpack cache content ${lazyName} (${formatSize( + this.getSize() + )})`; + this.logger.log( + `starting to unpack cache content ${lazyName} (${formatSize( + this.getSize() + )}) because it's outdated and need to be serialized` + ); + this.logger.time(timeMessage); + } + const value = this.lazy(); + this.outdated = false; + if ("then" in value) { + // Move to state B1 + this.lazy = write(() => + value.then(data => { + if (timeMessage) { + this.logger.timeEnd(timeMessage); } - appending += `.then(${this.returningFunction( - `${RuntimeGlobals.createFakeNamespaceObject}(m, ${fakeType})`, - "m" - )})`; - } else { - fakeType |= 1; - if (header) { - const returnExpression = `${RuntimeGlobals.createFakeNamespaceObject}(${moduleIdExpr}, ${fakeType})`; - appending = `.then(${this.basicFunction( - "", - `${header}return ${returnExpression};` - )})`; - } else { - appending = `.then(${RuntimeGlobals.createFakeNamespaceObject}.bind(__webpack_require__, ${comment}${idExpr}, ${fakeType}))`; + const oldMap = data.map; + /** @type {Map} */ + const map = new Map(); + for (const item of this.items) { + map.set(item, oldMap.get(item)); } - } - break; + // Move to state C1 (or maybe C2) + this.content = map; + this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + + return new PackContentItems(map); + }) + ); + } else { + // Move to state C1 + if (timeMessage) { + this.logger.timeEnd(timeMessage); + } + const oldMap = value.map; + /** @type {Map} */ + const map = new Map(); + for (const item of this.items) { + map.set(item, oldMap.get(item)); + } + this.content = map; + this.lazy = write(() => new PackContentItems(map)); } + } +} - return `${promise || "Promise.resolve()"}${appending}`; +const allowCollectingMemory = buf => { + const wasted = buf.buffer.byteLength - buf.byteLength; + if (wasted > 8192 && (wasted > 1048576 || wasted > buf.byteLength)) { + return Buffer.from(buf); } + return buf; +}; +class PackFileCacheStrategy { /** - * @param {Object} options options object - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {RuntimeSpec=} options.runtime runtime for which this code will be generated - * @param {RuntimeSpec | boolean=} options.runtimeCondition only execute the statement in some runtimes - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} expression + * @param {Object} options options + * @param {Compiler} options.compiler the compiler + * @param {IntermediateFileSystem} options.fs the filesystem + * @param {string} options.context the context directory + * @param {string} options.cacheLocation the location of the cache data + * @param {string} options.version version identifier + * @param {Logger} options.logger a logger + * @param {SnapshotOptions} options.snapshot options regarding snapshotting + * @param {number} options.maxAge max age of cache items + * @param {boolean} options.profile track and log detailed timing information for individual cache items + * @param {boolean} options.allowCollectingMemory allow to collect unused memory created during deserialization + * @param {false | "gzip" | "brotli"} options.compression compression used */ - runtimeConditionExpression({ - chunkGraph, - runtimeCondition, - runtime, - runtimeRequirements + constructor({ + compiler, + fs, + context, + cacheLocation, + version, + logger, + snapshot, + maxAge, + profile, + allowCollectingMemory, + compression }) { - if (runtimeCondition === undefined) return "true"; - if (typeof runtimeCondition === "boolean") return `${runtimeCondition}`; - /** @type {Set} */ - const positiveRuntimeIds = new Set(); - forEachRuntime(runtimeCondition, runtime => - positiveRuntimeIds.add(`${chunkGraph.getRuntimeId(runtime)}`) + this.fileSerializer = createFileSerializer( + fs, + compiler.options.output.hashFunction ); + this.fileSystemInfo = new FileSystemInfo(fs, { + managedPaths: snapshot.managedPaths, + immutablePaths: snapshot.immutablePaths, + logger: logger.getChildLogger("webpack.FileSystemInfo"), + hashFunction: compiler.options.output.hashFunction + }); + this.compiler = compiler; + this.context = context; + this.cacheLocation = cacheLocation; + this.version = version; + this.logger = logger; + this.maxAge = maxAge; + this.profile = profile; + this.allowCollectingMemory = allowCollectingMemory; + this.compression = compression; + this._extension = + compression === "brotli" + ? ".pack.br" + : compression === "gzip" + ? ".pack.gz" + : ".pack"; + this.snapshot = snapshot; /** @type {Set} */ - const negativeRuntimeIds = new Set(); - forEachRuntime(subtractRuntime(runtime, runtimeCondition), runtime => - negativeRuntimeIds.add(`${chunkGraph.getRuntimeId(runtime)}`) - ); - runtimeRequirements.add(RuntimeGlobals.runtimeId); - return compileBooleanMatcher.fromLists( - Array.from(positiveRuntimeIds), - Array.from(negativeRuntimeIds) - )(RuntimeGlobals.runtimeId); + this.buildDependencies = new Set(); + /** @type {LazySet} */ + this.newBuildDependencies = new LazySet(); + /** @type {Snapshot} */ + this.resolveBuildDependenciesSnapshot = undefined; + /** @type {Map} */ + this.resolveResults = undefined; + /** @type {Snapshot} */ + this.buildSnapshot = undefined; + /** @type {Promise} */ + this.packPromise = this._openPack(); + this.storePromise = Promise.resolve(); } - /** - * - * @param {Object} options options object - * @param {boolean=} options.update whether a new variable should be created or the existing one updated - * @param {Module} options.module the module - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {string} options.request the request that should be printed as comment - * @param {string} options.importVar name of the import variable - * @param {Module} options.originModule module in which the statement is emitted - * @param {boolean=} options.weak true, if this is a weak dependency - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {[string, string]} the import statement and the compat statement - */ - importStatement({ - update, - module, - chunkGraph, - request, - importVar, - originModule, - weak, - runtimeRequirements - }) { - if (!module) { - return [ - this.missingModuleStatement({ - request - }), - "" - ]; - } - if (chunkGraph.getModuleId(module) === null) { - if (weak) { - // only weak referenced modules don't get an id - // we can always emit an error emitting code here - return [ - this.weakError({ - module, - chunkGraph, - request, - type: "statements" - }), - "" - ]; - } - throw new Error( - `RuntimeTemplate.importStatement(): ${noModuleIdErrorMessage( - module, - chunkGraph - )}` - ); - } - const moduleId = this.moduleId({ - module, - chunkGraph, - request, - weak - }); - const optDeclaration = update ? "" : "var "; - - const exportsType = module.getExportsType( - chunkGraph.moduleGraph, - originModule.buildMeta.strictHarmonyModule - ); - runtimeRequirements.add(RuntimeGlobals.require); - const importContent = `/* harmony import */ ${optDeclaration}${importVar} = __webpack_require__(${moduleId});\n`; - - if (exportsType === "dynamic") { - runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport); - return [ - importContent, - `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${importVar});\n` - ]; + _getPack() { + if (this.packPromise === undefined) { + this.packPromise = this.storePromise.then(() => this._openPack()); } - return [importContent, ""]; + return this.packPromise; } /** - * @param {Object} options options - * @param {ModuleGraph} options.moduleGraph the module graph - * @param {Module} options.module the module - * @param {string} options.request the request - * @param {string | string[]} options.exportName the export name - * @param {Module} options.originModule the origin module - * @param {boolean|undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted - * @param {boolean} options.isCall true, if expression will be called - * @param {boolean} options.callContext when false, call context will not be preserved - * @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated - * @param {string} options.importVar the identifier name of the import variable - * @param {InitFragment[]} options.initFragments init fragments will be added here - * @param {RuntimeSpec} options.runtime runtime for which this code will be generated - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} expression + * @returns {Promise} the pack */ - exportFromImport({ - moduleGraph, - module, - request, - exportName, - originModule, - asiSafe, - isCall, - callContext, - defaultInterop, - importVar, - initFragments, - runtime, - runtimeRequirements - }) { - if (!module) { - return this.missingModule({ - request - }); - } - if (!Array.isArray(exportName)) { - exportName = exportName ? [exportName] : []; - } - const exportsType = module.getExportsType( - moduleGraph, - originModule.buildMeta.strictHarmonyModule - ); - - if (defaultInterop) { - if (exportName.length > 0 && exportName[0] === "default") { - switch (exportsType) { - case "dynamic": - if (isCall) { - return `${importVar}_default()${propertyAccess(exportName, 1)}`; - } else { - return asiSafe - ? `(${importVar}_default()${propertyAccess(exportName, 1)})` - : asiSafe === false - ? `;(${importVar}_default()${propertyAccess(exportName, 1)})` - : `${importVar}_default.a${propertyAccess(exportName, 1)}`; - } - case "default-only": - case "default-with-named": - exportName = exportName.slice(1); - break; - } - } else if (exportName.length > 0) { - if (exportsType === "default-only") { - return ( - "/* non-default import from non-esm module */undefined" + - propertyAccess(exportName, 1) - ); - } else if ( - exportsType !== "namespace" && - exportName[0] === "__esModule" - ) { - return "/* __esModule */true"; - } - } else if ( - exportsType === "default-only" || - exportsType === "default-with-named" - ) { - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - initFragments.push( - new InitFragment( - `var ${importVar}_namespace_cache;\n`, - InitFragment.STAGE_CONSTANTS, - -1, - `${importVar}_namespace_cache` - ) - ); - return `/*#__PURE__*/ ${ - asiSafe ? "" : asiSafe === false ? ";" : "Object" - }(${importVar}_namespace_cache || (${importVar}_namespace_cache = ${ - RuntimeGlobals.createFakeNamespaceObject - }(${importVar}${exportsType === "default-only" ? "" : ", 2"})))`; - } - } - - if (exportName.length > 0) { - const exportsInfo = moduleGraph.getExportsInfo(module); - const used = exportsInfo.getUsedName(exportName, runtime); - if (!used) { - const comment = Template.toNormalComment( - `unused export ${propertyAccess(exportName)}` + _openPack() { + const { logger, profile, cacheLocation, version } = this; + /** @type {Snapshot} */ + let buildSnapshot; + /** @type {Set} */ + let buildDependencies; + /** @type {Set} */ + let newBuildDependencies; + /** @type {Snapshot} */ + let resolveBuildDependenciesSnapshot; + /** @type {Map} */ + let resolveResults; + logger.time("restore cache container"); + return this.fileSerializer + .deserialize(null, { + filename: `${cacheLocation}/index${this._extension}`, + extension: `${this._extension}`, + logger, + profile, + retainedBuffer: this.allowCollectingMemory + ? allowCollectingMemory + : undefined + }) + .catch(err => { + if (err.code !== "ENOENT") { + logger.warn( + `Restoring pack failed from ${cacheLocation}${this._extension}: ${err}` + ); + logger.debug(err.stack); + } else { + logger.debug( + `No pack exists at ${cacheLocation}${this._extension}: ${err}` + ); + } + return undefined; + }) + .then(packContainer => { + logger.timeEnd("restore cache container"); + if (!packContainer) return undefined; + if (!(packContainer instanceof PackContainer)) { + logger.warn( + `Restored pack from ${cacheLocation}${this._extension}, but contained content is unexpected.`, + packContainer + ); + return undefined; + } + if (packContainer.version !== version) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but version doesn't match.` + ); + return undefined; + } + logger.time("check build dependencies"); + return Promise.all([ + new Promise((resolve, reject) => { + this.fileSystemInfo.checkSnapshotValid( + packContainer.buildSnapshot, + (err, valid) => { + if (err) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of build dependencies errored: ${err}.` + ); + logger.debug(err.stack); + return resolve(false); + } + if (!valid) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but build dependencies have changed.` + ); + return resolve(false); + } + buildSnapshot = packContainer.buildSnapshot; + return resolve(true); + } + ); + }), + new Promise((resolve, reject) => { + this.fileSystemInfo.checkSnapshotValid( + packContainer.resolveBuildDependenciesSnapshot, + (err, valid) => { + if (err) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of resolving of build dependencies errored: ${err}.` + ); + logger.debug(err.stack); + return resolve(false); + } + if (valid) { + resolveBuildDependenciesSnapshot = + packContainer.resolveBuildDependenciesSnapshot; + buildDependencies = packContainer.buildDependencies; + resolveResults = packContainer.resolveResults; + return resolve(true); + } + logger.log( + "resolving of build dependencies is invalid, will re-resolve build dependencies" + ); + this.fileSystemInfo.checkResolveResultsValid( + packContainer.resolveResults, + (err, valid) => { + if (err) { + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but resolving of build dependencies errored: ${err}.` + ); + logger.debug(err.stack); + return resolve(false); + } + if (valid) { + newBuildDependencies = packContainer.buildDependencies; + resolveResults = packContainer.resolveResults; + return resolve(true); + } + logger.log( + `Restored pack from ${cacheLocation}${this._extension}, but build dependencies resolve to different locations.` + ); + return resolve(false); + } + ); + } + ); + }) + ]) + .catch(err => { + logger.timeEnd("check build dependencies"); + throw err; + }) + .then(([buildSnapshotValid, resolveValid]) => { + logger.timeEnd("check build dependencies"); + if (buildSnapshotValid && resolveValid) { + logger.time("restore cache content metadata"); + const d = packContainer.data(); + logger.timeEnd("restore cache content metadata"); + return d; + } + return undefined; + }); + }) + .then(pack => { + if (pack) { + pack.maxAge = this.maxAge; + this.buildSnapshot = buildSnapshot; + if (buildDependencies) this.buildDependencies = buildDependencies; + if (newBuildDependencies) + this.newBuildDependencies.addAll(newBuildDependencies); + this.resolveResults = resolveResults; + this.resolveBuildDependenciesSnapshot = + resolveBuildDependenciesSnapshot; + return pack; + } + return new Pack(logger, this.maxAge); + }) + .catch(err => { + this.logger.warn( + `Restoring pack from ${cacheLocation}${this._extension} failed: ${err}` ); - return `${comment} undefined`; - } - const comment = equals(used, exportName) - ? "" - : Template.toNormalComment(propertyAccess(exportName)) + " "; - const access = `${importVar}${comment}${propertyAccess(used)}`; - if (isCall && callContext === false) { - return asiSafe - ? `(0,${access})` - : asiSafe === false - ? `;(0,${access})` - : `/*#__PURE__*/Object(${access})`; - } - return access; - } else { - return importVar; - } + this.logger.debug(err.stack); + return new Pack(logger, this.maxAge); + }); } /** - * @param {Object} options options - * @param {AsyncDependenciesBlock} options.block the async block - * @param {string} options.message the message - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} expression + * @param {string} identifier unique name for the resource + * @param {Etag | null} etag etag of the resource + * @param {any} data cached content + * @returns {Promise} promise */ - blockPromise({ block, message, chunkGraph, runtimeRequirements }) { - if (!block) { - const comment = this.comment({ - message - }); - return `Promise.resolve(${comment.trim()})`; - } - const chunkGroup = chunkGraph.getBlockChunkGroup(block); - if (!chunkGroup || chunkGroup.chunks.length === 0) { - const comment = this.comment({ - message - }); - return `Promise.resolve(${comment.trim()})`; - } - const chunks = chunkGroup.chunks.filter( - chunk => !chunk.hasRuntime() && chunk.id !== null - ); - const comment = this.comment({ - message, - chunkName: block.chunkName + store(identifier, etag, data) { + return this._getPack().then(pack => { + pack.set(identifier, etag === null ? null : etag.toString(), data); }); - if (chunks.length === 1) { - const chunkId = JSON.stringify(chunks[0].id); - runtimeRequirements.add(RuntimeGlobals.ensureChunk); - return `${RuntimeGlobals.ensureChunk}(${comment}${chunkId})`; - } else if (chunks.length > 0) { - runtimeRequirements.add(RuntimeGlobals.ensureChunk); - const requireChunkId = chunk => - `${RuntimeGlobals.ensureChunk}(${JSON.stringify(chunk.id)})`; - return `Promise.all(${comment.trim()}[${chunks - .map(requireChunkId) - .join(", ")}])`; - } else { - return `Promise.resolve(${comment.trim()})`; - } } /** - * @param {Object} options options - * @param {AsyncDependenciesBlock} options.block the async block - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @param {string=} options.request request string used originally - * @returns {string} expression + * @param {string} identifier unique name for the resource + * @param {Etag | null} etag etag of the resource + * @returns {Promise} promise to the cached content */ - asyncModuleFactory({ block, chunkGraph, runtimeRequirements, request }) { - const dep = block.dependencies[0]; - const module = chunkGraph.moduleGraph.getModule(dep); - const ensureChunk = this.blockPromise({ - block, - message: "", - chunkGraph, - runtimeRequirements - }); - const factory = this.returningFunction( - this.moduleRaw({ - module, - chunkGraph, - request, - runtimeRequirements - }) - ); - return this.returningFunction( - ensureChunk.startsWith("Promise.resolve(") - ? `${factory}` - : `${ensureChunk}.then(${this.returningFunction(factory)})` - ); + restore(identifier, etag) { + return this._getPack() + .then(pack => + pack.get(identifier, etag === null ? null : etag.toString()) + ) + .catch(err => { + if (err && err.code !== "ENOENT") { + this.logger.warn( + `Restoring failed for ${identifier} from pack: ${err}` + ); + this.logger.debug(err.stack); + } + }); } - /** - * @param {Object} options options - * @param {Dependency} options.dependency the dependency - * @param {ChunkGraph} options.chunkGraph the chunk graph - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @param {string=} options.request request string used originally - * @returns {string} expression - */ - syncModuleFactory({ dependency, chunkGraph, runtimeRequirements, request }) { - const module = chunkGraph.moduleGraph.getModule(dependency); - const factory = this.returningFunction( - this.moduleRaw({ - module, - chunkGraph, - request, - runtimeRequirements - }) - ); - return this.returningFunction(factory); + storeBuildDependencies(dependencies) { + this.newBuildDependencies.addAll(dependencies); } - /** - * @param {Object} options options - * @param {string} options.exportsArgument the name of the exports object - * @param {Set} options.runtimeRequirements if set, will be filled with runtime requirements - * @returns {string} statement - */ - defineEsModuleFlagStatement({ exportsArgument, runtimeRequirements }) { - runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); - runtimeRequirements.add(RuntimeGlobals.exports); - return `${RuntimeGlobals.makeNamespaceObject}(${exportsArgument});\n`; + afterAllStored() { + const packPromise = this.packPromise; + if (packPromise === undefined) return Promise.resolve(); + const reportProgress = ProgressPlugin.getReporter(this.compiler); + return (this.storePromise = packPromise + .then(pack => { + pack.stopCapturingRequests(); + if (!pack.invalid) return; + this.packPromise = undefined; + this.logger.log(`Storing pack...`); + let promise; + const newBuildDependencies = new Set(); + for (const dep of this.newBuildDependencies) { + if (!this.buildDependencies.has(dep)) { + newBuildDependencies.add(dep); + } + } + if (newBuildDependencies.size > 0 || !this.buildSnapshot) { + if (reportProgress) reportProgress(0.5, "resolve build dependencies"); + this.logger.debug( + `Capturing build dependencies... (${Array.from( + newBuildDependencies + ).join(", ")})` + ); + promise = new Promise((resolve, reject) => { + this.logger.time("resolve build dependencies"); + this.fileSystemInfo.resolveBuildDependencies( + this.context, + newBuildDependencies, + (err, result) => { + this.logger.timeEnd("resolve build dependencies"); + if (err) return reject(err); + + this.logger.time("snapshot build dependencies"); + const { + files, + directories, + missing, + resolveResults, + resolveDependencies + } = result; + if (this.resolveResults) { + for (const [key, value] of resolveResults) { + this.resolveResults.set(key, value); + } + } else { + this.resolveResults = resolveResults; + } + if (reportProgress) { + reportProgress( + 0.6, + "snapshot build dependencies", + "resolving" + ); + } + this.fileSystemInfo.createSnapshot( + undefined, + resolveDependencies.files, + resolveDependencies.directories, + resolveDependencies.missing, + this.snapshot.resolveBuildDependencies, + (err, snapshot) => { + if (err) { + this.logger.timeEnd("snapshot build dependencies"); + return reject(err); + } + if (!snapshot) { + this.logger.timeEnd("snapshot build dependencies"); + return reject( + new Error("Unable to snapshot resolve dependencies") + ); + } + if (this.resolveBuildDependenciesSnapshot) { + this.resolveBuildDependenciesSnapshot = + this.fileSystemInfo.mergeSnapshots( + this.resolveBuildDependenciesSnapshot, + snapshot + ); + } else { + this.resolveBuildDependenciesSnapshot = snapshot; + } + if (reportProgress) { + reportProgress( + 0.7, + "snapshot build dependencies", + "modules" + ); + } + this.fileSystemInfo.createSnapshot( + undefined, + files, + directories, + missing, + this.snapshot.buildDependencies, + (err, snapshot) => { + this.logger.timeEnd("snapshot build dependencies"); + if (err) return reject(err); + if (!snapshot) { + return reject( + new Error("Unable to snapshot build dependencies") + ); + } + this.logger.debug("Captured build dependencies"); + + if (this.buildSnapshot) { + this.buildSnapshot = + this.fileSystemInfo.mergeSnapshots( + this.buildSnapshot, + snapshot + ); + } else { + this.buildSnapshot = snapshot; + } + + resolve(); + } + ); + } + ); + } + ); + }); + } else { + promise = Promise.resolve(); + } + return promise.then(() => { + if (reportProgress) reportProgress(0.8, "serialize pack"); + this.logger.time(`store pack`); + const updatedBuildDependencies = new Set(this.buildDependencies); + for (const dep of newBuildDependencies) { + updatedBuildDependencies.add(dep); + } + const content = new PackContainer( + pack, + this.version, + this.buildSnapshot, + updatedBuildDependencies, + this.resolveResults, + this.resolveBuildDependenciesSnapshot + ); + return this.fileSerializer + .serialize(content, { + filename: `${this.cacheLocation}/index${this._extension}`, + extension: `${this._extension}`, + logger: this.logger, + profile: this.profile + }) + .then(() => { + for (const dep of newBuildDependencies) { + this.buildDependencies.add(dep); + } + this.newBuildDependencies.clear(); + this.logger.timeEnd(`store pack`); + const stats = pack.getContentStats(); + this.logger.log( + "Stored pack (%d items, %d files, %d MiB)", + pack.itemInfo.size, + stats.count, + Math.round(stats.size / 1024 / 1024) + ); + }) + .catch(err => { + this.logger.timeEnd(`store pack`); + this.logger.warn(`Caching failed for pack: ${err}`); + this.logger.debug(err.stack); + }); + }); + }) + .catch(err => { + this.logger.warn(`Caching failed for pack: ${err}`); + this.logger.debug(err.stack); + })); } - /** - * @param {Object} options options object - * @param {Module} options.module the module - * @param {string} options.publicPath the public path - * @param {RuntimeSpec=} options.runtime runtime - * @param {CodeGenerationResults} options.codeGenerationResults the code generation results - * @returns {string} the url of the asset - */ - assetUrl({ publicPath, runtime, module, codeGenerationResults }) { - if (!module) { - return "data:,"; - } - const codeGen = codeGenerationResults.get(module, runtime); - const { data } = codeGen; - const url = data.get("url"); - if (url) return url.toString(); - const filename = data.get("filename"); - return publicPath + filename; + clear() { + this.fileSystemInfo.clear(); + this.buildDependencies.clear(); + this.newBuildDependencies.clear(); + this.resolveBuildDependenciesSnapshot = undefined; + this.resolveResults = undefined; + this.buildSnapshot = undefined; + this.packPromise = undefined; } } -module.exports = RuntimeTemplate; +module.exports = PackFileCacheStrategy; /***/ }), -/***/ 63560: -/***/ (function(module) { +/***/ 97347: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -61893,77 +62237,387 @@ module.exports = RuntimeTemplate; -class SelfModuleFactory { - constructor(moduleGraph) { - this.moduleGraph = moduleGraph; - } +const LazySet = __webpack_require__(38938); +const makeSerializable = __webpack_require__(33032); - create(data, callback) { - const module = this.moduleGraph.getParentModule(data.dependencies[0]); - callback(null, { - module - }); +/** @typedef {import("enhanced-resolve/lib/Resolver")} Resolver */ +/** @typedef {import("../CacheFacade").ItemCacheFacade} ItemCacheFacade */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../FileSystemInfo")} FileSystemInfo */ +/** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */ + +class CacheEntry { + constructor(result, snapshot) { + this.result = result; + this.snapshot = snapshot; } -} -module.exports = SelfModuleFactory; + serialize({ write }) { + write(this.result); + write(this.snapshot); + } + deserialize({ read }) { + this.result = read(); + this.snapshot = read(); + } +} -/***/ }), +makeSerializable(CacheEntry, "webpack/lib/cache/ResolverCachePlugin"); -/***/ 48076: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @template T + * @param {Set | LazySet} set set to add items to + * @param {Set | LazySet} otherSet set to add items from + * @returns {void} + */ +const addAllToSet = (set, otherSet) => { + if (set instanceof LazySet) { + set.addAll(otherSet); + } else { + for (const item of otherSet) { + set.add(item); + } + } +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ +/** + * @param {Object} object an object + * @param {boolean} excludeContext if true, context is not included in string + * @returns {string} stringified version + */ +const objectToString = (object, excludeContext) => { + let str = ""; + for (const key in object) { + if (excludeContext && key === "context") continue; + const value = object[key]; + if (typeof value === "object" && value !== null) { + str += `|${key}=[${objectToString(value, false)}|]`; + } else { + str += `|${key}=|${value}`; + } + } + return str; +}; +class ResolverCachePlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const cache = compiler.getCache("ResolverCachePlugin"); + /** @type {FileSystemInfo} */ + let fileSystemInfo; + let snapshotOptions; + let realResolves = 0; + let cachedResolves = 0; + let cacheInvalidResolves = 0; + let concurrentResolves = 0; + compiler.hooks.thisCompilation.tap("ResolverCachePlugin", compilation => { + snapshotOptions = compilation.options.snapshot.resolve; + fileSystemInfo = compilation.fileSystemInfo; + compilation.hooks.finishModules.tap("ResolverCachePlugin", () => { + if (realResolves + cachedResolves > 0) { + const logger = compilation.getLogger("webpack.ResolverCachePlugin"); + logger.log( + `${Math.round( + (100 * realResolves) / (realResolves + cachedResolves) + )}% really resolved (${realResolves} real resolves with ${cacheInvalidResolves} cached but invalid, ${cachedResolves} cached valid, ${concurrentResolves} concurrent)` + ); + realResolves = 0; + cachedResolves = 0; + cacheInvalidResolves = 0; + concurrentResolves = 0; + } + }); + }); + /** + * @param {ItemCacheFacade} itemCache cache + * @param {Resolver} resolver the resolver + * @param {Object} resolveContext context for resolving meta info + * @param {Object} request the request info object + * @param {function((Error | null)=, Object=): void} callback callback function + * @returns {void} + */ + const doRealResolve = ( + itemCache, + resolver, + resolveContext, + request, + callback + ) => { + realResolves++; + const newRequest = { + _ResolverCachePluginCacheMiss: true, + ...request + }; + const newResolveContext = { + ...resolveContext, + stack: new Set(), + missingDependencies: new LazySet(), + fileDependencies: new LazySet(), + contextDependencies: new LazySet() + }; + const propagate = key => { + if (resolveContext[key]) { + addAllToSet(resolveContext[key], newResolveContext[key]); + } + }; + const resolveTime = Date.now(); + resolver.doResolve( + resolver.hooks.resolve, + newRequest, + "Cache miss", + newResolveContext, + (err, result) => { + propagate("fileDependencies"); + propagate("contextDependencies"); + propagate("missingDependencies"); + if (err) return callback(err); + const fileDependencies = newResolveContext.fileDependencies; + const contextDependencies = newResolveContext.contextDependencies; + const missingDependencies = newResolveContext.missingDependencies; + fileSystemInfo.createSnapshot( + resolveTime, + fileDependencies, + contextDependencies, + missingDependencies, + snapshotOptions, + (err, snapshot) => { + if (err) return callback(err); + if (!snapshot) { + if (result) return callback(null, result); + return callback(); + } + itemCache.store(new CacheEntry(result, snapshot), storeErr => { + if (storeErr) return callback(storeErr); + if (result) return callback(null, result); + callback(); + }); + } + ); + } + ); + }; + compiler.resolverFactory.hooks.resolver.intercept({ + factory(type, hook) { + /** @type {Map} */ + const activeRequests = new Map(); + hook.tap( + "ResolverCachePlugin", + /** + * @param {Resolver} resolver the resolver + * @param {Object} options resolve options + * @param {Object} userOptions resolve options passed by the user + * @returns {void} + */ + (resolver, options, userOptions) => { + if (options.cache !== true) return; + const optionsIdent = objectToString(userOptions, false); + const cacheWithContext = + options.cacheWithContext !== undefined + ? options.cacheWithContext + : false; + resolver.hooks.resolve.tapAsync( + { + name: "ResolverCachePlugin", + stage: -100 + }, + (request, resolveContext, callback) => { + if (request._ResolverCachePluginCacheMiss || !fileSystemInfo) { + return callback(); + } + const identifier = `${type}${optionsIdent}${objectToString( + request, + !cacheWithContext + )}`; + const activeRequest = activeRequests.get(identifier); + if (activeRequest) { + activeRequest.push(callback); + return; + } + const itemCache = cache.getItemCache(identifier, null); + let callbacks; + const done = (err, result) => { + if (callbacks === undefined) { + callback(err, result); + callbacks = false; + } else { + for (const callback of callbacks) { + callback(err, result); + } + activeRequests.delete(identifier); + callbacks = false; + } + }; + /** + * @param {Error=} err error if any + * @param {CacheEntry=} cacheEntry cache entry + * @returns {void} + */ + const processCacheResult = (err, cacheEntry) => { + if (err) return done(err); + if (cacheEntry) { + const { snapshot, result } = cacheEntry; + fileSystemInfo.checkSnapshotValid( + snapshot, + (err, valid) => { + if (err || !valid) { + cacheInvalidResolves++; + return doRealResolve( + itemCache, + resolver, + resolveContext, + request, + done + ); + } + cachedResolves++; + if (resolveContext.missingDependencies) { + addAllToSet( + resolveContext.missingDependencies, + snapshot.getMissingIterable() + ); + } + if (resolveContext.fileDependencies) { + addAllToSet( + resolveContext.fileDependencies, + snapshot.getFileIterable() + ); + } + if (resolveContext.contextDependencies) { + addAllToSet( + resolveContext.contextDependencies, + snapshot.getContextIterable() + ); + } + done(null, result); + } + ); + } else { + doRealResolve( + itemCache, + resolver, + resolveContext, + request, + done + ); + } + }; + itemCache.get(processCacheResult); + if (callbacks === undefined) { + callbacks = [callback]; + activeRequests.set(identifier, callbacks); + } + } + ); + } + ); + return hook; + } + }); + } +} -module.exports = __webpack_require__(96953); +module.exports = ResolverCachePlugin; /***/ }), -/***/ 71070: -/***/ (function(__unused_webpack_module, exports) { +/***/ 94075: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn + Author Tobias Koppers @sokra */ +const createHash = __webpack_require__(49835); + +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {typeof import("../util/Hash")} HashConstructor */ + /** - * @param {number} size the size in bytes - * @returns {string} the formatted size + * @typedef {Object} HashableObject + * @property {function(Hash): void} updateHash */ -exports.formatSize = size => { - if (typeof size !== "number" || Number.isNaN(size) === true) { - return "unknown size"; + +class LazyHashedEtag { + /** + * @param {HashableObject} obj object with updateHash method + * @param {string | HashConstructor} hashFunction the hash function to use + */ + constructor(obj, hashFunction = "md4") { + this._obj = obj; + this._hash = undefined; + this._hashFunction = hashFunction; } - if (size <= 0) { - return "0 bytes"; + /** + * @returns {string} hash of object + */ + toString() { + if (this._hash === undefined) { + const hash = createHash(this._hashFunction); + this._obj.updateHash(hash); + this._hash = /** @type {string} */ (hash.digest("base64")); + } + return this._hash; } +} - const abbreviations = ["bytes", "KiB", "MiB", "GiB"]; - const index = Math.floor(Math.log(size) / Math.log(1024)); +/** @type {Map>} */ +const mapStrings = new Map(); - return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${ - abbreviations[index] - }`; +/** @type {WeakMap>} */ +const mapObjects = new WeakMap(); + +/** + * @param {HashableObject} obj object with updateHash method + * @param {string | HashConstructor} hashFunction the hash function to use + * @returns {LazyHashedEtag} etag + */ +const getter = (obj, hashFunction = "md4") => { + let innerMap; + if (typeof hashFunction === "string") { + innerMap = mapStrings.get(hashFunction); + if (innerMap === undefined) { + const newHash = new LazyHashedEtag(obj, hashFunction); + innerMap = new WeakMap(); + innerMap.set(obj, newHash); + mapStrings.set(hashFunction, innerMap); + return newHash; + } + } else { + innerMap = mapObjects.get(hashFunction); + if (innerMap === undefined) { + const newHash = new LazyHashedEtag(obj, hashFunction); + innerMap = new WeakMap(); + innerMap.set(obj, newHash); + mapObjects.set(hashFunction, innerMap); + return newHash; + } + } + const hash = innerMap.get(obj); + if (hash !== undefined) return hash; + const newHash = new LazyHashedEtag(obj, hashFunction); + innerMap.set(obj, newHash); + return newHash; }; +module.exports = getter; + /***/ }), -/***/ 97513: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 54980: +/***/ (function(module) { "use strict"; /* @@ -61973,62 +62627,79 @@ exports.formatSize = size => { -const JavascriptModulesPlugin = __webpack_require__(89464); +/** @typedef {import("../Cache").Etag} Etag */ -/** @typedef {import("./Compilation")} Compilation */ +class MergedEtag { + /** + * @param {Etag} a first + * @param {Etag} b second + */ + constructor(a, b) { + this.a = a; + this.b = b; + } -class SourceMapDevToolModuleOptionsPlugin { - constructor(options) { - this.options = options; + toString() { + return `${this.a.toString()}|${this.b.toString()}`; } +} - /** - * @param {Compilation} compilation the compiler instance - * @returns {void} - */ - apply(compilation) { - const options = this.options; - if (options.module !== false) { - compilation.hooks.buildModule.tap( - "SourceMapDevToolModuleOptionsPlugin", - module => { - module.useSourceMap = true; - } - ); - compilation.hooks.runtimeModule.tap( - "SourceMapDevToolModuleOptionsPlugin", - module => { - module.useSourceMap = true; - } - ); +const dualObjectMap = new WeakMap(); +const objectStringMap = new WeakMap(); + +/** + * @param {Etag} a first + * @param {Etag} b second + * @returns {Etag} result + */ +const mergeEtags = (a, b) => { + if (typeof a === "string") { + if (typeof b === "string") { + return `${a}|${b}`; } else { - compilation.hooks.buildModule.tap( - "SourceMapDevToolModuleOptionsPlugin", - module => { - module.useSimpleSourceMap = true; - } - ); - compilation.hooks.runtimeModule.tap( - "SourceMapDevToolModuleOptionsPlugin", - module => { - module.useSimpleSourceMap = true; - } - ); + const temp = b; + b = a; + a = temp; + } + } else { + if (typeof b !== "string") { + // both a and b are objects + let map = dualObjectMap.get(a); + if (map === undefined) { + dualObjectMap.set(a, (map = new WeakMap())); + } + const mergedEtag = map.get(b); + if (mergedEtag === undefined) { + const newMergedEtag = new MergedEtag(a, b); + map.set(b, newMergedEtag); + return newMergedEtag; + } else { + return mergedEtag; + } } - JavascriptModulesPlugin.getCompilationHooks(compilation).useSourceMap.tap( - "SourceMapDevToolModuleOptionsPlugin", - () => true - ); } -} + // a is object, b is string + let map = objectStringMap.get(a); + if (map === undefined) { + objectStringMap.set(a, (map = new Map())); + } + const mergedEtag = map.get(b); + if (mergedEtag === undefined) { + const newMergedEtag = new MergedEtag(a, b); + map.set(b, newMergedEtag); + return newMergedEtag; + } else { + return mergedEtag; + } +}; -module.exports = SourceMapDevToolModuleOptionsPlugin; +module.exports = mergeEtags; /***/ }), -/***/ 63872: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 13462: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -62038,2503 +62709,2849 @@ module.exports = SourceMapDevToolModuleOptionsPlugin; -const asyncLib = __webpack_require__(78175); -const { ConcatSource, RawSource } = __webpack_require__(51255); -const Compilation = __webpack_require__(85720); -const ModuleFilenameHelpers = __webpack_require__(88821); -const ProgressPlugin = __webpack_require__(13216); -const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(97513); -const createSchemaValidation = __webpack_require__(32540); -const createHash = __webpack_require__(49835); -const { relative, dirname } = __webpack_require__(17139); -const { makePathsAbsolute } = __webpack_require__(82186); +const path = __webpack_require__(71017); +const webpackSchema = __webpack_require__(73342); -/** @typedef {import("webpack-sources").MapOptions} MapOptions */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ -/** @typedef {import("./Cache").Etag} Etag */ -/** @typedef {import("./CacheFacade").ItemCacheFacade} ItemCacheFacade */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./NormalModule").SourceMap} SourceMap */ -/** @typedef {import("./util/Hash")} Hash */ - -const validate = createSchemaValidation( - __webpack_require__(2885), - () => __webpack_require__(30501), - { - name: "SourceMap DevTool Plugin", - baseDataPath: "options" - } -); +// TODO add originPath to PathItem for better errors /** - * @typedef {object} SourceMapTask - * @property {Source} asset - * @property {AssetInfo} assetInfo - * @property {(string | Module)[]} modules - * @property {string} source - * @property {string} file - * @property {SourceMap} sourceMap - * @property {ItemCacheFacade} cacheItem cache item + * @typedef {Object} PathItem + * @property {any} schema the part of the schema + * @property {string} path the path in the config */ +/** @typedef {"unknown-argument" | "unexpected-non-array-in-path" | "unexpected-non-object-in-path" | "multiple-values-unexpected" | "invalid-value"} ProblemType */ + /** - * Escapes regular expression metacharacters - * @param {string} str String to quote - * @returns {string} Escaped string + * @typedef {Object} Problem + * @property {ProblemType} type + * @property {string} path + * @property {string} argument + * @property {any=} value + * @property {number=} index + * @property {string=} expected */ -const quoteMeta = str => { - return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); -}; /** - * Creating {@link SourceMapTask} for given file - * @param {string} file current compiled file - * @param {Source} asset the asset - * @param {AssetInfo} assetInfo the asset info - * @param {MapOptions} options source map options - * @param {Compilation} compilation compilation instance - * @param {ItemCacheFacade} cacheItem cache item - * @returns {SourceMapTask | undefined} created task instance or `undefined` + * @typedef {Object} LocalProblem + * @property {ProblemType} type + * @property {string} path + * @property {string=} expected */ -const getTaskForFile = ( - file, - asset, - assetInfo, - options, - compilation, - cacheItem -) => { - let source; - /** @type {SourceMap} */ - let sourceMap; - /** - * Check if asset can build source map - */ - if (asset.sourceAndMap) { - const sourceAndMap = asset.sourceAndMap(options); - sourceMap = /** @type {SourceMap} */ (sourceAndMap.map); - source = sourceAndMap.source; - } else { - sourceMap = /** @type {SourceMap} */ (asset.map(options)); - source = asset.source(); - } - if (!sourceMap || typeof source !== "string") return; - const context = compilation.options.context; - const root = compilation.compiler.root; - const cachedAbsolutify = makePathsAbsolute.bindContextCache(context, root); - const modules = sourceMap.sources.map(source => { - if (!source.startsWith("webpack://")) return source; - source = cachedAbsolutify(source.slice(10)); - const module = compilation.findModule(source); - return module || source; - }); - - return { - file, - asset, - source, - assetInfo, - sourceMap, - modules, - cacheItem - }; -}; - -class SourceMapDevToolPlugin { - /** - * @param {SourceMapDevToolPluginOptions} [options] options object - * @throws {Error} throws error, if got more than 1 arguments - */ - constructor(options = {}) { - validate(options); - /** @type {string | false} */ - this.sourceMapFilename = options.filename; - /** @type {string | false} */ - this.sourceMappingURLComment = - options.append === false - ? false - : options.append || "\n//# source" + "MappingURL=[url]"; - /** @type {string | Function} */ - this.moduleFilenameTemplate = - options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]"; - /** @type {string | Function} */ - this.fallbackModuleFilenameTemplate = - options.fallbackModuleFilenameTemplate || - "webpack://[namespace]/[resourcePath]?[hash]"; - /** @type {string} */ - this.namespace = options.namespace || ""; - /** @type {SourceMapDevToolPluginOptions} */ - this.options = options; - } +/** + * @typedef {Object} ArgumentConfig + * @property {string} description + * @property {string} [negatedDescription] + * @property {string} path + * @property {boolean} multiple + * @property {"enum"|"string"|"path"|"number"|"boolean"|"RegExp"|"reset"} type + * @property {any[]=} values + */ - /** - * Apply the plugin - * @param {Compiler} compiler compiler instance - * @returns {void} - */ - apply(compiler) { - const outputFs = compiler.outputFileSystem; - const sourceMapFilename = this.sourceMapFilename; - const sourceMappingURLComment = this.sourceMappingURLComment; - const moduleFilenameTemplate = this.moduleFilenameTemplate; - const namespace = this.namespace; - const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate; - const requestShortener = compiler.requestShortener; - const options = this.options; - options.test = options.test || /\.((c|m)?js|css)($|\?)/i; +/** + * @typedef {Object} Argument + * @property {string} description + * @property {"string"|"number"|"boolean"} simpleType + * @property {boolean} multiple + * @property {ArgumentConfig[]} configs + */ - const matchObject = ModuleFilenameHelpers.matchObject.bind( - undefined, - options - ); +/** + * @param {any=} schema a json schema to create arguments for (by default webpack schema is used) + * @returns {Record} object of arguments + */ +const getArguments = (schema = webpackSchema) => { + /** @type {Record} */ + const flags = {}; - compiler.hooks.compilation.tap("SourceMapDevToolPlugin", compilation => { - new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); + const pathToArgumentName = input => { + return input + .replace(/\./g, "-") + .replace(/\[\]/g, "") + .replace( + /(\p{Uppercase_Letter}+|\p{Lowercase_Letter}|\d)(\p{Uppercase_Letter}+)/gu, + "$1-$2" + ) + .replace(/-?[^\p{Uppercase_Letter}\p{Lowercase_Letter}\d]+/gu, "-") + .toLowerCase(); + }; - compilation.hooks.processAssets.tapAsync( - { - name: "SourceMapDevToolPlugin", - stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING, - additionalAssets: true - }, - (assets, callback) => { - const chunkGraph = compilation.chunkGraph; - const cache = compilation.getCache("SourceMapDevToolPlugin"); - /** @type {Map} */ - const moduleToSourceNameMapping = new Map(); - /** - * @type {Function} - * @returns {void} - */ - const reportProgress = - ProgressPlugin.getReporter(compilation.compiler) || (() => {}); + const getSchemaPart = path => { + const newPath = path.split("/"); - /** @type {Map} */ - const fileToChunk = new Map(); - for (const chunk of compilation.chunks) { - for (const file of chunk.files) { - fileToChunk.set(file, chunk); - } - for (const file of chunk.auxiliaryFiles) { - fileToChunk.set(file, chunk); - } - } + let schemaPart = schema; - /** @type {string[]} */ - const files = []; - for (const file of Object.keys(assets)) { - if (matchObject(file)) { - files.push(file); - } - } + for (let i = 1; i < newPath.length; i++) { + const inner = schemaPart[newPath[i]]; - reportProgress(0.0); - /** @type {SourceMapTask[]} */ - const tasks = []; - let fileIndex = 0; + if (!inner) { + break; + } - asyncLib.each( - files, - (file, callback) => { - const asset = compilation.getAsset(file); - if (asset.info.related && asset.info.related.sourceMap) { - fileIndex++; - return callback(); - } - const cacheItem = cache.getItemCache( - file, - cache.mergeEtags( - cache.getLazyHashedEtag(asset.source), - namespace - ) - ); + schemaPart = inner; + } - cacheItem.get((err, cacheEntry) => { - if (err) { - return callback(err); - } - /** - * If presented in cache, reassigns assets. Cache assets already have source maps. - */ - if (cacheEntry) { - const { assets, assetsInfo } = cacheEntry; - for (const cachedFile of Object.keys(assets)) { - if (cachedFile === file) { - compilation.updateAsset( - cachedFile, - assets[cachedFile], - assetsInfo[cachedFile] - ); - } else { - compilation.emitAsset( - cachedFile, - assets[cachedFile], - assetsInfo[cachedFile] - ); - } - /** - * Add file to chunk, if not presented there - */ - if (cachedFile !== file) { - const chunk = fileToChunk.get(file); - if (chunk !== undefined) - chunk.auxiliaryFiles.add(cachedFile); - } - } + return schemaPart; + }; - reportProgress( - (0.5 * ++fileIndex) / files.length, - file, - "restored cached SourceMap" - ); + /** + * + * @param {PathItem[]} path path in the schema + * @returns {string | undefined} description + */ + const getDescription = path => { + for (const { schema } of path) { + if (schema.cli) { + if (schema.cli.helper) continue; + if (schema.cli.description) return schema.cli.description; + } + if (schema.description) return schema.description; + } + }; - return callback(); - } + /** + * + * @param {PathItem[]} path path in the schema + * @returns {string | undefined} negative description + */ + const getNegatedDescription = path => { + for (const { schema } of path) { + if (schema.cli) { + if (schema.cli.helper) continue; + if (schema.cli.negatedDescription) return schema.cli.negatedDescription; + } + } + }; - reportProgress( - (0.5 * fileIndex) / files.length, - file, - "generate SourceMap" - ); + /** + * + * @param {PathItem[]} path path in the schema + * @returns {string | undefined} reset description + */ + const getResetDescription = path => { + for (const { schema } of path) { + if (schema.cli) { + if (schema.cli.helper) continue; + if (schema.cli.resetDescription) return schema.cli.resetDescription; + } + } + }; - /** @type {SourceMapTask | undefined} */ - const task = getTaskForFile( - file, - asset.source, - asset.info, - { - module: options.module, - columns: options.columns - }, - compilation, - cacheItem - ); + /** + * + * @param {any} schemaPart schema + * @returns {Pick} partial argument config + */ + const schemaToArgumentConfig = schemaPart => { + if (schemaPart.enum) { + return { + type: "enum", + values: schemaPart.enum + }; + } + switch (schemaPart.type) { + case "number": + return { + type: "number" + }; + case "string": + return { + type: schemaPart.absolutePath ? "path" : "string" + }; + case "boolean": + return { + type: "boolean" + }; + } + if (schemaPart.instanceof === "RegExp") { + return { + type: "RegExp" + }; + } + return undefined; + }; - if (task) { - const modules = task.modules; + /** + * @param {PathItem[]} path path in the schema + * @returns {void} + */ + const addResetFlag = path => { + const schemaPath = path[0].path; + const name = pathToArgumentName(`${schemaPath}.reset`); + const description = + getResetDescription(path) || + `Clear all items provided in '${schemaPath}' configuration. ${getDescription( + path + )}`; + flags[name] = { + configs: [ + { + type: "reset", + multiple: false, + description, + path: schemaPath + } + ], + description: undefined, + simpleType: undefined, + multiple: undefined + }; + }; - for (let idx = 0; idx < modules.length; idx++) { - const module = modules[idx]; - if (!moduleToSourceNameMapping.get(module)) { - moduleToSourceNameMapping.set( - module, - ModuleFilenameHelpers.createFilename( - module, - { - moduleFilenameTemplate: moduleFilenameTemplate, - namespace: namespace - }, - { - requestShortener, - chunkGraph, - hashFunction: compilation.outputOptions.hashFunction - } - ) - ); - } - } + /** + * @param {PathItem[]} path full path in schema + * @param {boolean} multiple inside of an array + * @returns {number} number of arguments added + */ + const addFlag = (path, multiple) => { + const argConfigBase = schemaToArgumentConfig(path[0].schema); + if (!argConfigBase) return 0; - tasks.push(task); - } + const negatedDescription = getNegatedDescription(path); + const name = pathToArgumentName(path[0].path); + /** @type {ArgumentConfig} */ + const argConfig = { + ...argConfigBase, + multiple, + description: getDescription(path), + path: path[0].path + }; - reportProgress( - (0.5 * ++fileIndex) / files.length, - file, - "generated SourceMap" - ); + if (negatedDescription) { + argConfig.negatedDescription = negatedDescription; + } - callback(); - }); - }, - err => { - if (err) { - return callback(err); - } + if (!flags[name]) { + flags[name] = { + configs: [], + description: undefined, + simpleType: undefined, + multiple: undefined + }; + } - reportProgress(0.5, "resolve sources"); - /** @type {Set} */ - const usedNamesSet = new Set(moduleToSourceNameMapping.values()); - /** @type {Set} */ - const conflictDetectionSet = new Set(); + if ( + flags[name].configs.some( + item => JSON.stringify(item) === JSON.stringify(argConfig) + ) + ) { + return 0; + } - /** - * all modules in defined order (longest identifier first) - * @type {Array} - */ - const allModules = Array.from( - moduleToSourceNameMapping.keys() - ).sort((a, b) => { - const ai = typeof a === "string" ? a : a.identifier(); - const bi = typeof b === "string" ? b : b.identifier(); - return ai.length - bi.length; - }); + if ( + flags[name].configs.some( + item => item.type === argConfig.type && item.multiple !== multiple + ) + ) { + if (multiple) { + throw new Error( + `Conflicting schema for ${path[0].path} with ${argConfig.type} type (array type must be before single item type)` + ); + } + return 0; + } - // find modules with conflicting source names - for (let idx = 0; idx < allModules.length; idx++) { - const module = allModules[idx]; - let sourceName = moduleToSourceNameMapping.get(module); - let hasName = conflictDetectionSet.has(sourceName); - if (!hasName) { - conflictDetectionSet.add(sourceName); - continue; - } + flags[name].configs.push(argConfig); - // try the fallback name first - sourceName = ModuleFilenameHelpers.createFilename( - module, - { - moduleFilenameTemplate: fallbackModuleFilenameTemplate, - namespace: namespace - }, - { - requestShortener, - chunkGraph, - hashFunction: compilation.outputOptions.hashFunction - } - ); - hasName = usedNamesSet.has(sourceName); - if (!hasName) { - moduleToSourceNameMapping.set(module, sourceName); - usedNamesSet.add(sourceName); - continue; - } + return 1; + }; - // otherwise just append stars until we have a valid name - while (hasName) { - sourceName += "*"; - hasName = usedNamesSet.has(sourceName); - } - moduleToSourceNameMapping.set(module, sourceName); - usedNamesSet.add(sourceName); - } + // TODO support `not` and `if/then/else` + // TODO support `const`, but we don't use it on our schema + /** + * + * @param {object} schemaPart the current schema + * @param {string} schemaPath the current path in the schema + * @param {{schema: object, path: string}[]} path all previous visited schemaParts + * @param {string | null} inArray if inside of an array, the path to the array + * @returns {number} added arguments + */ + const traverse = (schemaPart, schemaPath = "", path = [], inArray = null) => { + while (schemaPart.$ref) { + schemaPart = getSchemaPart(schemaPart.$ref); + } - let taskIndex = 0; + const repetitions = path.filter(({ schema }) => schema === schemaPart); + if ( + repetitions.length >= 2 || + repetitions.some(({ path }) => path === schemaPath) + ) { + return 0; + } - asyncLib.each( - tasks, - (task, callback) => { - const assets = Object.create(null); - const assetsInfo = Object.create(null); - const file = task.file; - const chunk = fileToChunk.get(file); - const sourceMap = task.sourceMap; - const source = task.source; - const modules = task.modules; + if (schemaPart.cli && schemaPart.cli.exclude) return 0; - reportProgress( - 0.5 + (0.5 * taskIndex) / tasks.length, - file, - "attach SourceMap" - ); + const fullPath = [{ schema: schemaPart, path: schemaPath }, ...path]; - const moduleFilenames = modules.map(m => - moduleToSourceNameMapping.get(m) - ); - sourceMap.sources = moduleFilenames; - if (options.noSources) { - sourceMap.sourcesContent = undefined; - } - sourceMap.sourceRoot = options.sourceRoot || ""; - sourceMap.file = file; - const usesContentHash = - sourceMapFilename && - /\[contenthash(:\w+)?\]/.test(sourceMapFilename); + let addedArguments = 0; - // If SourceMap and asset uses contenthash, avoid a circular dependency by hiding hash in `file` - if (usesContentHash && task.assetInfo.contenthash) { - const contenthash = task.assetInfo.contenthash; - let pattern; - if (Array.isArray(contenthash)) { - pattern = contenthash.map(quoteMeta).join("|"); - } else { - pattern = quoteMeta(contenthash); - } - sourceMap.file = sourceMap.file.replace( - new RegExp(pattern, "g"), - m => "x".repeat(m.length) - ); - } + addedArguments += addFlag(fullPath, !!inArray); - /** @type {string | false} */ - let currentSourceMappingURLComment = sourceMappingURLComment; - if ( - currentSourceMappingURLComment !== false && - /\.css($|\?)/i.test(file) - ) { - currentSourceMappingURLComment = - currentSourceMappingURLComment.replace( - /^\n\/\/(.*)$/, - "\n/*$1*/" - ); - } - const sourceMapString = JSON.stringify(sourceMap); - if (sourceMapFilename) { - let filename = file; - const sourceMapContentHash = - usesContentHash && - /** @type {string} */ ( - createHash(compilation.outputOptions.hashFunction) - .update(sourceMapString) - .digest("hex") - ); - const pathParams = { - chunk, - filename: options.fileContext - ? relative( - outputFs, - `/${options.fileContext}`, - `/${filename}` - ) - : filename, - contentHash: sourceMapContentHash - }; - const { path: sourceMapFile, info: sourceMapInfo } = - compilation.getPathWithInfo( - sourceMapFilename, - pathParams - ); - const sourceMapUrl = options.publicPath - ? options.publicPath + sourceMapFile - : relative( - outputFs, - dirname(outputFs, `/${file}`), - `/${sourceMapFile}` - ); - /** @type {Source} */ - let asset = new RawSource(source); - if (currentSourceMappingURLComment !== false) { - // Add source map url to compilation asset, if currentSourceMappingURLComment is set - asset = new ConcatSource( - asset, - compilation.getPath( - currentSourceMappingURLComment, - Object.assign({ url: sourceMapUrl }, pathParams) - ) - ); - } - const assetInfo = { - related: { sourceMap: sourceMapFile } - }; - assets[file] = asset; - assetsInfo[file] = assetInfo; - compilation.updateAsset(file, asset, assetInfo); - // Add source map file to compilation assets and chunk files - const sourceMapAsset = new RawSource(sourceMapString); - const sourceMapAssetInfo = { - ...sourceMapInfo, - development: true - }; - assets[sourceMapFile] = sourceMapAsset; - assetsInfo[sourceMapFile] = sourceMapAssetInfo; - compilation.emitAsset( - sourceMapFile, - sourceMapAsset, - sourceMapAssetInfo - ); - if (chunk !== undefined) - chunk.auxiliaryFiles.add(sourceMapFile); - } else { - if (currentSourceMappingURLComment === false) { - throw new Error( - "SourceMapDevToolPlugin: append can't be false when no filename is provided" - ); - } - /** - * Add source map as data url to asset - */ - const asset = new ConcatSource( - new RawSource(source), - currentSourceMappingURLComment - .replace(/\[map\]/g, () => sourceMapString) - .replace( - /\[url\]/g, - () => - `data:application/json;charset=utf-8;base64,${Buffer.from( - sourceMapString, - "utf-8" - ).toString("base64")}` - ) - ); - assets[file] = asset; - assetsInfo[file] = undefined; - compilation.updateAsset(file, asset); - } + if (schemaPart.type === "object") { + if (schemaPart.properties) { + for (const property of Object.keys(schemaPart.properties)) { + addedArguments += traverse( + schemaPart.properties[property], + schemaPath ? `${schemaPath}.${property}` : property, + fullPath, + inArray + ); + } + } - task.cacheItem.store({ assets, assetsInfo }, err => { - reportProgress( - 0.5 + (0.5 * ++taskIndex) / tasks.length, - task.file, - "attached SourceMap" - ); + return addedArguments; + } - if (err) { - return callback(err); - } - callback(); - }); - }, - err => { - reportProgress(1.0); - callback(err); - } - ); - } + if (schemaPart.type === "array") { + if (inArray) { + return 0; + } + if (Array.isArray(schemaPart.items)) { + let i = 0; + for (const item of schemaPart.items) { + addedArguments += traverse( + item, + `${schemaPath}.${i}`, + fullPath, + schemaPath ); } - ); - }); - } -} -module.exports = SourceMapDevToolPlugin; + return addedArguments; + } + addedArguments += traverse( + schemaPart.items, + `${schemaPath}[]`, + fullPath, + schemaPath + ); -/***/ }), + if (addedArguments > 0) { + addResetFlag(fullPath); + addedArguments++; + } -/***/ 31743: -/***/ (function(module) { + return addedArguments; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const maybeOf = schemaPart.oneOf || schemaPart.anyOf || schemaPart.allOf; + if (maybeOf) { + const items = maybeOf; + for (let i = 0; i < items.length; i++) { + addedArguments += traverse(items[i], schemaPath, fullPath, inArray); + } -/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ + return addedArguments; + } -class Stats { - /** - * @param {Compilation} compilation webpack compilation - */ - constructor(compilation) { - this.compilation = compilation; - } + return addedArguments; + }; - get hash() { - return this.compilation.hash; - } + traverse(schema); - get startTime() { - return this.compilation.startTime; + // Summarize flags + for (const name of Object.keys(flags)) { + const argument = flags[name]; + argument.description = argument.configs.reduce((desc, { description }) => { + if (!desc) return description; + if (!description) return desc; + if (desc.includes(description)) return desc; + return `${desc} ${description}`; + }, /** @type {string | undefined} */ (undefined)); + argument.simpleType = argument.configs.reduce((t, argConfig) => { + /** @type {"string" | "number" | "boolean"} */ + let type = "string"; + switch (argConfig.type) { + case "number": + type = "number"; + break; + case "reset": + case "boolean": + type = "boolean"; + break; + case "enum": + if (argConfig.values.every(v => typeof v === "boolean")) + type = "boolean"; + if (argConfig.values.every(v => typeof v === "number")) + type = "number"; + break; + } + if (t === undefined) return type; + return t === type ? t : "string"; + }, /** @type {"string" | "number" | "boolean" | undefined} */ (undefined)); + argument.multiple = argument.configs.some(c => c.multiple); } - get endTime() { - return this.compilation.endTime; - } + return flags; +}; - /** - * @returns {boolean} true if the compilation had a warning - */ - hasWarnings() { - return ( - this.compilation.warnings.length > 0 || - this.compilation.children.some(child => child.getStats().hasWarnings()) - ); - } +const cliAddedItems = new WeakMap(); - /** - * @returns {boolean} true if the compilation encountered an error - */ - hasErrors() { - return ( - this.compilation.errors.length > 0 || - this.compilation.children.some(child => child.getStats().hasErrors()) - ); +/** + * @param {any} config configuration + * @param {string} schemaPath path in the config + * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined + * @returns {{ problem?: LocalProblem, object?: any, property?: string | number, value?: any }} problem or object with property and value + */ +const getObjectAndProperty = (config, schemaPath, index = 0) => { + if (!schemaPath) return { value: config }; + const parts = schemaPath.split("."); + let property = parts.pop(); + let current = config; + let i = 0; + for (const part of parts) { + const isArray = part.endsWith("[]"); + const name = isArray ? part.slice(0, -2) : part; + let value = current[name]; + if (isArray) { + if (value === undefined) { + value = {}; + current[name] = [...Array.from({ length: index }), value]; + cliAddedItems.set(current[name], index + 1); + } else if (!Array.isArray(value)) { + return { + problem: { + type: "unexpected-non-array-in-path", + path: parts.slice(0, i).join(".") + } + }; + } else { + let addedItems = cliAddedItems.get(value) || 0; + while (addedItems <= index) { + value.push(undefined); + addedItems++; + } + cliAddedItems.set(value, addedItems); + const x = value.length - addedItems + index; + if (value[x] === undefined) { + value[x] = {}; + } else if (value[x] === null || typeof value[x] !== "object") { + return { + problem: { + type: "unexpected-non-object-in-path", + path: parts.slice(0, i).join(".") + } + }; + } + value = value[x]; + } + } else { + if (value === undefined) { + value = current[name] = {}; + } else if (value === null || typeof value !== "object") { + return { + problem: { + type: "unexpected-non-object-in-path", + path: parts.slice(0, i).join(".") + } + }; + } + } + current = value; + i++; } - - /** - * @param {(string|StatsOptions)=} options stats options - * @returns {StatsCompilation} json output - */ - toJson(options) { - options = this.compilation.createStatsOptions(options, { - forToString: false - }); - - const statsFactory = this.compilation.createStatsFactory(options); - - return statsFactory.create("compilation", this.compilation, { - compilation: this.compilation - }); + let value = current[property]; + if (property.endsWith("[]")) { + const name = property.slice(0, -2); + const value = current[name]; + if (value === undefined) { + current[name] = [...Array.from({ length: index }), undefined]; + cliAddedItems.set(current[name], index + 1); + return { object: current[name], property: index, value: undefined }; + } else if (!Array.isArray(value)) { + current[name] = [value, ...Array.from({ length: index }), undefined]; + cliAddedItems.set(current[name], index + 1); + return { object: current[name], property: index + 1, value: undefined }; + } else { + let addedItems = cliAddedItems.get(value) || 0; + while (addedItems <= index) { + value.push(undefined); + addedItems++; + } + cliAddedItems.set(value, addedItems); + const x = value.length - addedItems + index; + if (value[x] === undefined) { + value[x] = {}; + } else if (value[x] === null || typeof value[x] !== "object") { + return { + problem: { + type: "unexpected-non-object-in-path", + path: schemaPath + } + }; + } + return { + object: value, + property: x, + value: value[x] + }; + } } + return { object: current, property, value }; +}; - toString(options) { - options = this.compilation.createStatsOptions(options, { - forToString: true - }); - - const statsFactory = this.compilation.createStatsFactory(options); - const statsPrinter = this.compilation.createStatsPrinter(options); +/** + * @param {any} config configuration + * @param {string} schemaPath path in the config + * @param {any} value parsed value + * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined + * @returns {LocalProblem | null} problem or null for success + */ +const setValue = (config, schemaPath, value, index) => { + const { problem, object, property } = getObjectAndProperty( + config, + schemaPath, + index + ); + if (problem) return problem; + object[property] = value; + return null; +}; - const data = statsFactory.create("compilation", this.compilation, { - compilation: this.compilation - }); - const result = statsPrinter.print("compilation", data); - return result === undefined ? "" : result; +/** + * @param {ArgumentConfig} argConfig processing instructions + * @param {any} config configuration + * @param {any} value the value + * @param {number | undefined} index the index if multiple values provided + * @returns {LocalProblem | null} a problem if any + */ +const processArgumentConfig = (argConfig, config, value, index) => { + if (index !== undefined && !argConfig.multiple) { + return { + type: "multiple-values-unexpected", + path: argConfig.path + }; } -} - -module.exports = Stats; - - -/***/ }), - -/***/ 39722: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { ConcatSource, PrefixSource } = __webpack_require__(51255); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGraph")} ChunkGraph */ -/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("./Compilation").PathData} PathData */ -/** @typedef {import("./DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ -/** @typedef {import("./RuntimeModule")} RuntimeModule */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ -/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ - -const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0); -const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0); -const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1; -const NUMBER_OF_IDENTIFIER_START_CHARS = DELTA_A_TO_Z * 2 + 2; // a-z A-Z _ $ -const NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS = - NUMBER_OF_IDENTIFIER_START_CHARS + 10; // a-z A-Z _ $ 0-9 -const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g; -const INDENT_MULTILINE_REGEX = /^\t/gm; -const LINE_SEPARATOR_REGEX = /\r?\n/g; -const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/; -const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g; -const COMMENT_END_REGEX = /\*\//g; -const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g; -const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; - -/** - * @typedef {Object} RenderManifestOptions - * @property {Chunk} chunk the chunk used to render - * @property {string} hash - * @property {string} fullHash - * @property {OutputOptions} outputOptions - * @property {CodeGenerationResults} codeGenerationResults - * @property {{javascript: ModuleTemplate}} moduleTemplates - * @property {DependencyTemplates} dependencyTemplates - * @property {RuntimeTemplate} runtimeTemplate - * @property {ModuleGraph} moduleGraph - * @property {ChunkGraph} chunkGraph - */ - -/** @typedef {RenderManifestEntryTemplated | RenderManifestEntryStatic} RenderManifestEntry */ - -/** - * @typedef {Object} RenderManifestEntryTemplated - * @property {function(): Source} render - * @property {string | function(PathData, AssetInfo=): string} filenameTemplate - * @property {PathData=} pathOptions - * @property {AssetInfo=} info - * @property {string} identifier - * @property {string=} hash - * @property {boolean=} auxiliary - */ + const parsed = parseValueForArgumentConfig(argConfig, value); + if (parsed === undefined) { + return { + type: "invalid-value", + path: argConfig.path, + expected: getExpectedValue(argConfig) + }; + } + const problem = setValue(config, argConfig.path, parsed, index); + if (problem) return problem; + return null; +}; /** - * @typedef {Object} RenderManifestEntryStatic - * @property {function(): Source} render - * @property {string} filename - * @property {AssetInfo} info - * @property {string} identifier - * @property {string=} hash - * @property {boolean=} auxiliary + * @param {ArgumentConfig} argConfig processing instructions + * @returns {string | undefined} expected message */ +const getExpectedValue = argConfig => { + switch (argConfig.type) { + default: + return argConfig.type; + case "boolean": + return "true | false"; + case "RegExp": + return "regular expression (example: /ab?c*/)"; + case "enum": + return argConfig.values.map(v => `${v}`).join(" | "); + case "reset": + return "true (will reset the previous value to an empty array)"; + } +}; /** - * @typedef {Object} HasId - * @property {number | string} id + * @param {ArgumentConfig} argConfig processing instructions + * @param {any} value the value + * @returns {any | undefined} parsed value */ +const parseValueForArgumentConfig = (argConfig, value) => { + switch (argConfig.type) { + case "string": + if (typeof value === "string") { + return value; + } + break; + case "path": + if (typeof value === "string") { + return path.resolve(value); + } + break; + case "number": + if (typeof value === "number") return value; + if (typeof value === "string" && /^[+-]?\d*(\.\d*)[eE]\d+$/) { + const n = +value; + if (!isNaN(n)) return n; + } + break; + case "boolean": + if (typeof value === "boolean") return value; + if (value === "true") return true; + if (value === "false") return false; + break; + case "RegExp": + if (value instanceof RegExp) return value; + if (typeof value === "string") { + // cspell:word yugi + const match = /^\/(.*)\/([yugi]*)$/.exec(value); + if (match && !/[^\\]\//.test(match[1])) + return new RegExp(match[1], match[2]); + } + break; + case "enum": + if (argConfig.values.includes(value)) return value; + for (const item of argConfig.values) { + if (`${item}` === value) return item; + } + break; + case "reset": + if (value === true) return []; + break; + } +}; /** - * @typedef {function(Module, number): boolean} ModuleFilterPredicate + * @param {Record} args object of arguments + * @param {any} config configuration + * @param {Record} values object with values + * @returns {Problem[] | null} problems or null for success */ - -class Template { - /** - * - * @param {Function} fn a runtime function (.runtime.js) "template" - * @returns {string} the updated and normalized function string - */ - static getFunctionContent(fn) { - return fn - .toString() - .replace(FUNCTION_CONTENT_REGEX, "") - .replace(INDENT_MULTILINE_REGEX, "") - .replace(LINE_SEPARATOR_REGEX, "\n"); +const processArguments = (args, config, values) => { + /** @type {Problem[]} */ + const problems = []; + for (const key of Object.keys(values)) { + const arg = args[key]; + if (!arg) { + problems.push({ + type: "unknown-argument", + path: "", + argument: key + }); + continue; + } + const processValue = (value, i) => { + const currentProblems = []; + for (const argConfig of arg.configs) { + const problem = processArgumentConfig(argConfig, config, value, i); + if (!problem) { + return; + } + currentProblems.push({ + ...problem, + argument: key, + value: value, + index: i + }); + } + problems.push(...currentProblems); + }; + let value = values[key]; + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + processValue(value[i], i); + } + } else { + processValue(value, undefined); + } } + if (problems.length === 0) return null; + return problems; +}; - /** - * @param {string} str the string converted to identifier - * @returns {string} created identifier - */ - static toIdentifier(str) { - if (typeof str !== "string") return ""; - return str - .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1") - .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_"); - } - /** - * - * @param {string} str string to be converted to commented in bundle code - * @returns {string} returns a commented version of string - */ - static toComment(str) { - if (!str) return ""; - return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`; - } +exports.getArguments = getArguments; +exports.processArguments = processArguments; - /** - * - * @param {string} str string to be converted to "normal comment" - * @returns {string} returns a commented version of string - */ - static toNormalComment(str) { - if (!str) return ""; - return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`; - } - /** - * @param {string} str string path to be normalized - * @returns {string} normalized bundle-safe path - */ - static toPath(str) { - if (typeof str !== "string") return ""; - return str - .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-") - .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, ""); - } +/***/ }), - // map number to a single character a-z, A-Z or multiple characters if number is too big - /** - * @param {number} n number to convert to ident - * @returns {string} returns single character ident - */ - static numberToIdentifier(n) { - if (n >= NUMBER_OF_IDENTIFIER_START_CHARS) { - // use multiple letters - return ( - Template.numberToIdentifier(n % NUMBER_OF_IDENTIFIER_START_CHARS) + - Template.numberToIdentifierContinuation( - Math.floor(n / NUMBER_OF_IDENTIFIER_START_CHARS) - ) - ); - } +/***/ 43950: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // lower case - if (n < DELTA_A_TO_Z) { - return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); - } - n -= DELTA_A_TO_Z; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ - // upper case - if (n < DELTA_A_TO_Z) { - return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); - } - if (n === DELTA_A_TO_Z) return "_"; - return "$"; - } - /** - * @param {number} n number to convert to ident - * @returns {string} returns single character ident - */ - static numberToIdentifierContinuation(n) { - if (n >= NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) { - // use multiple letters - return ( - Template.numberToIdentifierContinuation( - n % NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS - ) + - Template.numberToIdentifierContinuation( - Math.floor(n / NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) - ) - ); - } +const browserslist = __webpack_require__(14907); +const path = __webpack_require__(71017); - // lower case - if (n < DELTA_A_TO_Z) { - return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); - } - n -= DELTA_A_TO_Z; +/** @typedef {import("./target").ApiTargetProperties} ApiTargetProperties */ +/** @typedef {import("./target").EcmaTargetProperties} EcmaTargetProperties */ +/** @typedef {import("./target").PlatformTargetProperties} PlatformTargetProperties */ - // upper case - if (n < DELTA_A_TO_Z) { - return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); - } - n -= DELTA_A_TO_Z; +// [[C:]/path/to/config][:env] +const inputRx = /^(?:((?:[A-Z]:)?[/\\].*?))?(?::(.+?))?$/i; - // numbers - if (n < 10) { - return `${n}`; - } +/** + * @typedef {Object} BrowserslistHandlerConfig + * @property {string=} configPath + * @property {string=} env + * @property {string=} query + */ - if (n === 10) return "_"; - return "$"; +/** + * @param {string} input input string + * @param {string} context the context directory + * @returns {BrowserslistHandlerConfig} config + */ +const parse = (input, context) => { + if (!input) { + return {}; } - /** - * - * @param {string | string[]} s string to convert to identity - * @returns {string} converted identity - */ - static indent(s) { - if (Array.isArray(s)) { - return s.map(Template.indent).join("\n"); - } else { - const str = s.trimRight(); - if (!str) return ""; - const ind = str[0] === "\n" ? "" : "\t"; - return ind + str.replace(/\n([^\n])/g, "\n\t$1"); - } + if (path.isAbsolute(input)) { + const [, configPath, env] = inputRx.exec(input) || []; + return { configPath, env }; } - /** - * - * @param {string|string[]} s string to create prefix for - * @param {string} prefix prefix to compose - * @returns {string} returns new prefix string - */ - static prefix(s, prefix) { - const str = Template.asString(s).trim(); - if (!str) return ""; - const ind = str[0] === "\n" ? "" : prefix; - return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); - } + const config = browserslist.findConfig(context); - /** - * - * @param {string|string[]} str string or string collection - * @returns {string} returns a single string from array - */ - static asString(str) { - if (Array.isArray(str)) { - return str.join("\n"); - } - return str; + if (config && Object.keys(config).includes(input)) { + return { env: input }; } - /** - * @typedef {Object} WithId - * @property {string|number} id - */ + return { query: input }; +}; - /** - * @param {WithId[]} modules a collection of modules to get array bounds for - * @returns {[number, number] | false} returns the upper and lower array bounds - * or false if not every module has a number based id - */ - static getModulesArrayBounds(modules) { - let maxId = -Infinity; - let minId = Infinity; - for (const module of modules) { - const moduleId = module.id; - if (typeof moduleId !== "number") return false; - if (maxId < moduleId) maxId = moduleId; - if (minId > moduleId) minId = moduleId; - } - if (minId < 16 + ("" + minId).length) { - // add minId x ',' instead of 'Array(minId).concat(…)' - minId = 0; - } - // start with -1 because the first module needs no comma - let objectOverhead = -1; - for (const module of modules) { - // module id + colon + comma - objectOverhead += `${module.id}`.length + 2; - } - // number of commas, or when starting non-zero the length of Array(minId).concat() - const arrayOverhead = minId === 0 ? maxId : 16 + `${minId}`.length + maxId; - return arrayOverhead < objectOverhead ? [minId, maxId] : false; - } +/** + * @param {string} input input string + * @param {string} context the context directory + * @returns {string[] | undefined} selected browsers + */ +const load = (input, context) => { + const { configPath, env, query } = parse(input, context); - /** - * @param {ChunkRenderContext} renderContext render context - * @param {Module[]} modules modules to render (should be ordered by identifier) - * @param {function(Module): Source} renderModule function to render a module - * @param {string=} prefix applying prefix strings - * @returns {Source} rendered chunk modules in a Source object - */ - static renderChunkModules(renderContext, modules, renderModule, prefix = "") { - const { chunkGraph } = renderContext; - var source = new ConcatSource(); - if (modules.length === 0) { - return null; - } - /** @type {{id: string|number, source: Source|string}[]} */ - const allModules = modules.map(module => { - return { - id: chunkGraph.getModuleId(module), - source: renderModule(module) || "false" - }; - }); - const bounds = Template.getModulesArrayBounds(allModules); - if (bounds) { - // Render a spare array - const minId = bounds[0]; - const maxId = bounds[1]; - if (minId !== 0) { - source.add(`Array(${minId}).concat(`); - } - source.add("[\n"); - /** @type {Map} */ - const modules = new Map(); - for (const module of allModules) { - modules.set(module.id, module); - } - for (let idx = minId; idx <= maxId; idx++) { - const module = modules.get(idx); - if (idx !== minId) { - source.add(",\n"); - } - source.add(`/* ${idx} */`); - if (module) { - source.add("\n"); - source.add(module.source); - } - } - source.add("\n" + prefix + "]"); - if (minId !== 0) { - source.add(")"); - } - } else { - // Render an object - source.add("{\n"); - for (let i = 0; i < allModules.length; i++) { - const module = allModules[i]; - if (i !== 0) { - source.add(",\n"); - } - source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`); - source.add(module.source); - } - source.add(`\n\n${prefix}}`); - } - return source; - } + // if a query is specified, then use it, else + // if a path to a config is specified then load it, else + // find a nearest config + const config = query + ? query + : configPath + ? browserslist.loadConfig({ + config: configPath, + env + }) + : browserslist.loadConfig({ path: context, env }); + + if (!config) return null; + return browserslist(config); +}; +/** + * @param {string[]} browsers supported browsers list + * @returns {EcmaTargetProperties & PlatformTargetProperties & ApiTargetProperties} target properties + */ +const resolve = browsers => { /** - * @param {RuntimeModule[]} runtimeModules array of runtime modules in order - * @param {RenderContext & { codeGenerationResults?: CodeGenerationResults }} renderContext render context - * @returns {Source} rendered runtime modules in a Source object + * Checks all against a version number + * @param {Record} versions first supported version + * @returns {boolean} true if supports */ - static renderRuntimeModules(runtimeModules, renderContext) { - const source = new ConcatSource(); - for (const module of runtimeModules) { - const codeGenerationResults = renderContext.codeGenerationResults; - let runtimeSource; - if (codeGenerationResults) { - runtimeSource = codeGenerationResults.getSource( - module, - renderContext.chunk.runtime, - "runtime" - ); - } else { - const codeGenResult = module.codeGeneration({ - chunkGraph: renderContext.chunkGraph, - dependencyTemplates: renderContext.dependencyTemplates, - moduleGraph: renderContext.moduleGraph, - runtimeTemplate: renderContext.runtimeTemplate, - runtime: renderContext.chunk.runtime, - codeGenerationResults - }); - if (!codeGenResult) continue; - runtimeSource = codeGenResult.sources.get("runtime"); - } - if (runtimeSource) { - source.add(Template.toNormalComment(module.identifier()) + "\n"); - if (!module.shouldIsolate()) { - source.add(runtimeSource); - source.add("\n\n"); - } else if (renderContext.runtimeTemplate.supportsArrowFunction()) { - source.add("(() => {\n"); - source.add(new PrefixSource("\t", runtimeSource)); - source.add("\n})();\n\n"); - } else { - source.add("!function() {\n"); - source.add(new PrefixSource("\t", runtimeSource)); - source.add("\n}();\n\n"); - } + const rawChecker = versions => { + return browsers.every(v => { + const [name, parsedVersion] = v.split(" "); + if (!name) return false; + const requiredVersion = versions[name]; + if (!requiredVersion) return false; + const [parsedMajor, parserMinor] = + // safari TP supports all features for normal safari + parsedVersion === "TP" + ? [Infinity, Infinity] + : parsedVersion.split("."); + if (typeof requiredVersion === "number") { + return +parsedMajor >= requiredVersion; } - } - return source; - } + return requiredVersion[0] === +parsedMajor + ? +parserMinor >= requiredVersion[1] + : +parsedMajor > requiredVersion[0]; + }); + }; + const anyNode = browsers.some(b => /^node /.test(b)); + const anyBrowser = browsers.some(b => /^(?!node)/.test(b)); + const browserProperty = !anyBrowser ? false : anyNode ? null : true; + const nodeProperty = !anyNode ? false : anyBrowser ? null : true; + // Internet Explorer Mobile, Blackberry browser and Opera Mini are very old browsers, they do not support new features + const es6DynamicImport = rawChecker({ + chrome: 63, + and_chr: 63, + edge: 79, + firefox: 67, + and_ff: 67, + // ie: Not supported + opera: 50, + op_mob: 46, + safari: [11, 1], + ios_saf: [11, 3], + samsung: [8, 2], + android: 63, + and_qq: [10, 4], + // baidu: Not supported + // and_uc: Not supported + // kaios: Not supported + // Since Node.js 13.14.0 no warning about usage, but it was added 8.5.0 with some limitations and it was improved in 12.0.0 and 13.2.0 + node: [13, 14] + }); - /** - * @param {RuntimeModule[]} runtimeModules array of runtime modules in order - * @param {RenderContext} renderContext render context - * @returns {Source} rendered chunk runtime modules in a Source object - */ - static renderChunkRuntimeModules(runtimeModules, renderContext) { - return new PrefixSource( - "/******/ ", - new ConcatSource( - "function(__webpack_require__) { // webpackRuntimeModules\n", - this.renderRuntimeModules(runtimeModules, renderContext), - "}\n" - ) - ); - } -} + return { + const: rawChecker({ + chrome: 49, + and_chr: 49, + edge: 12, + // Prior to Firefox 13, const is implemented, but re-assignment is not failing. + // Prior to Firefox 46, a TypeError was thrown on redeclaration instead of a SyntaxError. + firefox: 36, + and_ff: 36, + // Not supported in for-in and for-of loops + // ie: Not supported + opera: 36, + op_mob: 36, + safari: [10, 0], + ios_saf: [10, 0], + // Before 5.0 supported correctly in strict mode, otherwise supported without block scope + samsung: [5, 0], + android: 37, + and_qq: [10, 4], + // Supported correctly in strict mode, otherwise supported without block scope + // baidu: Not supported + and_uc: [12, 12], + kaios: [2, 5], + node: [6, 0] + }), + arrowFunction: rawChecker({ + chrome: 45, + and_chr: 45, + edge: 12, + // The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of 'use strict'; is now required. + // Prior to Firefox 39, a line terminator (\\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \\n => {} will now throw a SyntaxError in this and later versions. + firefox: 39, + and_ff: 39, + // ie: Not supported, + opera: 32, + op_mob: 32, + safari: 10, + ios_saf: 10, + samsung: [5, 0], + android: 45, + and_qq: [10, 4], + baidu: [7, 12], + and_uc: [12, 12], + kaios: [2, 5], + node: [6, 0] + }), + forOf: rawChecker({ + chrome: 38, + and_chr: 38, + edge: 12, + // Prior to Firefox 51, using the for...of loop construct with the const keyword threw a SyntaxError ("missing = in const declaration"). + firefox: 51, + and_ff: 51, + // ie: Not supported, + opera: 25, + op_mob: 25, + safari: 7, + ios_saf: 7, + samsung: [3, 0], + android: 38, + // and_qq: Unknown support + // baidu: Unknown support + // and_uc: Unknown support + // kaios: Unknown support + node: [0, 12] + }), + destructuring: rawChecker({ + chrome: 49, + and_chr: 49, + edge: 14, + firefox: 41, + and_ff: 41, + // ie: Not supported, + opera: 36, + op_mob: 36, + safari: 8, + ios_saf: 8, + samsung: [5, 0], + android: 49, + // and_qq: Unknown support + // baidu: Unknown support + // and_uc: Unknown support + // kaios: Unknown support + node: [6, 0] + }), + bigIntLiteral: rawChecker({ + chrome: 67, + and_chr: 67, + edge: 79, + firefox: 68, + and_ff: 68, + // ie: Not supported, + opera: 54, + op_mob: 48, + safari: 14, + ios_saf: 14, + samsung: [9, 2], + android: 67, + // and_qq: Not supported + // baidu: Not supported + // and_uc: Not supported + // kaios: Not supported + node: [10, 4] + }), + // Support syntax `import` and `export` and no limitations and bugs on Node.js + // Not include `export * as namespace` + module: rawChecker({ + chrome: 61, + and_chr: 61, + edge: 16, + firefox: 60, + and_ff: 60, + // ie: Not supported, + opera: 48, + op_mob: 45, + safari: [10, 1], + ios_saf: [10, 3], + samsung: [8, 0], + android: 61, + and_qq: [10, 4], + // baidu: Not supported + // and_uc: Not supported + // kaios: Not supported + // Since Node.js 13.14.0 no warning about usage, but it was added 8.5.0 with some limitations and it was improved in 12.0.0 and 13.2.0 + node: [13, 14] + }), + dynamicImport: es6DynamicImport, + dynamicImportInWorker: es6DynamicImport && !anyNode, + // browserslist does not have info about globalThis + // so this is based on mdn-browser-compat-data + globalThis: rawChecker({ + chrome: 71, + and_chr: 71, + edge: 79, + firefox: 65, + and_ff: 65, + // ie: Not supported, + opera: 58, + op_mob: 50, + safari: [12, 1], + ios_saf: [12, 2], + samsung: [10, 1], + android: 71, + // and_qq: Unknown support + // baidu: Unknown support + // and_uc: Unknown support + // kaios: Unknown support + node: [12, 0] + }), + optionalChaining: rawChecker({ + chrome: 80, + and_chr: 80, + edge: 80, + firefox: 74, + and_ff: 79, + // ie: Not supported, + opera: 67, + op_mob: 64, + safari: [13, 1], + ios_saf: [13, 4], + samsung: 13, + android: 80, + // and_qq: Not supported + // baidu: Not supported + // and_uc: Not supported + // kaios: Not supported + node: 14 + }), + templateLiteral: rawChecker({ + chrome: 41, + and_chr: 41, + edge: 13, + firefox: 34, + and_ff: 34, + // ie: Not supported, + opera: 29, + op_mob: 64, + safari: [9, 1], + ios_saf: 9, + samsung: 4, + android: 41, + and_qq: [10, 4], + baidu: [7, 12], + and_uc: [12, 12], + kaios: [2, 5], + node: 4 + }), + browser: browserProperty, + electron: false, + node: nodeProperty, + nwjs: false, + web: browserProperty, + webworker: false, -module.exports = Template; -module.exports.NUMBER_OF_IDENTIFIER_START_CHARS = - NUMBER_OF_IDENTIFIER_START_CHARS; -module.exports.NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS = - NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS; + document: browserProperty, + fetchWasm: browserProperty, + global: nodeProperty, + importScripts: false, + importScriptsInWorker: true, + nodeBuiltins: nodeProperty, + require: nodeProperty + }; +}; + +module.exports = { + resolve, + load +}; /***/ }), -/***/ 80734: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 92988: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Jason Anderson @diurnalist + Author Tobias Koppers @sokra */ -const { basename, extname } = __webpack_require__(71017); -const util = __webpack_require__(73837); -const Chunk = __webpack_require__(39385); -const Module = __webpack_require__(73208); -const { parseResource } = __webpack_require__(82186); - -/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("./Compilation").PathData} PathData */ -/** @typedef {import("./Compiler")} Compiler */ - -const REGEXP = /\[\\*([\w:]+)\\*\]/gi; +const fs = __webpack_require__(57147); +const path = __webpack_require__(71017); +const Template = __webpack_require__(1626); +const { cleverMerge } = __webpack_require__(60839); +const { + getTargetsProperties, + getTargetProperties, + getDefaultTarget +} = __webpack_require__(52801); -const prepareId = id => { - if (typeof id !== "string") return id; +/** @typedef {import("../../declarations/WebpackOptions").CacheOptionsNormalized} CacheOptions */ +/** @typedef {import("../../declarations/WebpackOptions").CssExperimentOptions} CssExperimentOptions */ +/** @typedef {import("../../declarations/WebpackOptions").EntryDescription} EntryDescription */ +/** @typedef {import("../../declarations/WebpackOptions").EntryNormalized} Entry */ +/** @typedef {import("../../declarations/WebpackOptions").Experiments} Experiments */ +/** @typedef {import("../../declarations/WebpackOptions").ExperimentsNormalized} ExperimentsNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").ExternalsPresets} ExternalsPresets */ +/** @typedef {import("../../declarations/WebpackOptions").ExternalsType} ExternalsType */ +/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../../declarations/WebpackOptions").Library} Library */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").Loader} Loader */ +/** @typedef {import("../../declarations/WebpackOptions").Mode} Mode */ +/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ +/** @typedef {import("../../declarations/WebpackOptions").Node} WebpackNode */ +/** @typedef {import("../../declarations/WebpackOptions").Optimization} Optimization */ +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */ +/** @typedef {import("../../declarations/WebpackOptions").Performance} Performance */ +/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../../declarations/WebpackOptions").RuleSetRules} RuleSetRules */ +/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */ +/** @typedef {import("../../declarations/WebpackOptions").Target} Target */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("./target").TargetProperties} TargetProperties */ - if (/^"\s\+*.*\+\s*"$/.test(id)) { - const match = /^"\s\+*\s*(.*)\s*\+\s*"$/.exec(id); +const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i; - return `" + (${match[1]} + "").replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_") + "`; +/** + * Sets a constant default value when undefined + * @template T + * @template {keyof T} P + * @param {T} obj an object + * @param {P} prop a property of this object + * @param {T[P]} value a default value of the property + * @returns {void} + */ +const D = (obj, prop, value) => { + if (obj[prop] === undefined) { + obj[prop] = value; } - - return id.replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_"); }; -const hashLength = (replacer, handler, assetInfo, hashName) => { - const fn = (match, arg, input) => { - let result; - const length = arg && parseInt(arg, 10); - - if (length && handler) { - result = handler(length); - } else { - const hash = replacer(match, arg, input); - - result = length ? hash.slice(0, length) : hash; - } - if (assetInfo) { - assetInfo.immutable = true; - if (Array.isArray(assetInfo[hashName])) { - assetInfo[hashName] = [...assetInfo[hashName], result]; - } else if (assetInfo[hashName]) { - assetInfo[hashName] = [assetInfo[hashName], result]; - } else { - assetInfo[hashName] = result; - } - } - return result; - }; - - return fn; +/** + * Sets a dynamic default value when undefined, by calling the factory function + * @template T + * @template {keyof T} P + * @param {T} obj an object + * @param {P} prop a property of this object + * @param {function(): T[P]} factory a default value factory for the property + * @returns {void} + */ +const F = (obj, prop, factory) => { + if (obj[prop] === undefined) { + obj[prop] = factory(); + } }; -const replacer = (value, allowEmpty) => { - const fn = (match, arg, input) => { - if (typeof value === "function") { - value = value(); - } - if (value === null || value === undefined) { - if (!allowEmpty) { - throw new Error( - `Path variable ${match} not implemented in this context: ${input}` - ); +/** + * Sets a dynamic default value when undefined, by calling the factory function. + * factory must return an array or undefined + * When the current value is already an array an contains "..." it's replaced with + * the result of the factory function + * @template T + * @template {keyof T} P + * @param {T} obj an object + * @param {P} prop a property of this object + * @param {function(): T[P]} factory a default value factory for the property + * @returns {void} + */ +const A = (obj, prop, factory) => { + const value = obj[prop]; + if (value === undefined) { + obj[prop] = factory(); + } else if (Array.isArray(value)) { + /** @type {any[]} */ + let newArray = undefined; + for (let i = 0; i < value.length; i++) { + const item = value[i]; + if (item === "...") { + if (newArray === undefined) { + newArray = value.slice(0, i); + obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray)); + } + const items = /** @type {any[]} */ (/** @type {unknown} */ (factory())); + if (items !== undefined) { + for (const item of items) { + newArray.push(item); + } + } + } else if (newArray !== undefined) { + newArray.push(item); } - - return ""; - } else { - return `${value}`; } - }; - - return fn; + } }; -const deprecationCache = new Map(); -const deprecatedFunction = (() => () => {})(); -const deprecated = (fn, message, code) => { - let d = deprecationCache.get(message); - if (d === undefined) { - d = util.deprecate(deprecatedFunction, message, code); - deprecationCache.set(message, d); - } - return (...args) => { - d(); - return fn(...args); - }; +/** + * @param {WebpackOptions} options options to be modified + * @returns {void} + */ +const applyWebpackOptionsBaseDefaults = options => { + F(options, "context", () => process.cwd()); + applyInfrastructureLoggingDefaults(options.infrastructureLogging); }; /** - * @param {string | function(PathData, AssetInfo=): string} path the raw path - * @param {PathData} data context data - * @param {AssetInfo} assetInfo extra info about the asset (will be written to) - * @returns {string} the interpolated path + * @param {WebpackOptions} options options to be modified + * @returns {void} */ -const replacePathVariables = (path, data, assetInfo) => { - const chunkGraph = data.chunkGraph; +const applyWebpackOptionsDefaults = options => { + F(options, "context", () => process.cwd()); + F(options, "target", () => { + return getDefaultTarget(options.context); + }); - /** @type {Map} */ - const replacements = new Map(); + const { mode, name, target } = options; - // Filename context - // - // Placeholders - // - // for /some/path/file.js?query#fragment: - // [file] - /some/path/file.js - // [query] - ?query - // [fragment] - #fragment - // [base] - file.js - // [path] - /some/path/ - // [name] - file - // [ext] - .js - if (typeof data.filename === "string") { - const { path: file, query, fragment } = parseResource(data.filename); + let targetProperties = + target === false + ? /** @type {false} */ (false) + : typeof target === "string" + ? getTargetProperties(target, options.context) + : getTargetsProperties(target, options.context); - const ext = extname(file); - const base = basename(file); - const name = base.slice(0, base.length - ext.length); - const path = file.slice(0, file.length - base.length); + const development = mode === "development"; + const production = mode === "production" || !mode; - replacements.set("file", replacer(file)); - replacements.set("query", replacer(query, true)); - replacements.set("fragment", replacer(fragment, true)); - replacements.set("path", replacer(path, true)); - replacements.set("base", replacer(base)); - replacements.set("name", replacer(name)); - replacements.set("ext", replacer(ext, true)); - // Legacy - replacements.set( - "filebase", - deprecated( - replacer(base), - "[filebase] is now [base]", - "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_FILENAME" - ) - ); + if (typeof options.entry !== "function") { + for (const key of Object.keys(options.entry)) { + F( + options.entry[key], + "import", + () => /** @type {[string]} */ (["./src"]) + ); + } } - // Compilation context - // - // Placeholders - // - // [fullhash] - data.hash (3a4b5c6e7f) - // - // Legacy Placeholders - // - // [hash] - data.hash (3a4b5c6e7f) - if (data.hash) { - const hashReplacer = hashLength( - replacer(data.hash), - data.hashWithLength, - assetInfo, - "fullhash" - ); + F(options, "devtool", () => (development ? "eval" : false)); + D(options, "watch", false); + D(options, "profile", false); + D(options, "parallelism", 100); + D(options, "recordsInputPath", false); + D(options, "recordsOutputPath", false); - replacements.set("fullhash", hashReplacer); + applyExperimentsDefaults(options.experiments, { + production, + development, + targetProperties + }); - // Legacy - replacements.set( - "hash", - deprecated( - hashReplacer, - "[hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)", - "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH" - ) - ); - } + const futureDefaults = options.experiments.futureDefaults; - // Chunk Context - // - // Placeholders - // - // [id] - chunk.id (0.js) - // [name] - chunk.name (app.js) - // [chunkhash] - chunk.hash (7823t4t4.js) - // [contenthash] - chunk.contentHash[type] (3256u3zg.js) - if (data.chunk) { - const chunk = data.chunk; + F(options, "cache", () => + development ? { type: /** @type {"memory"} */ ("memory") } : false + ); + applyCacheDefaults(options.cache, { + name: name || "default", + mode: mode || "production", + development, + cacheUnaffected: options.experiments.cacheUnaffected + }); + const cache = !!options.cache; - const contentHashType = data.contentHashType; + applySnapshotDefaults(options.snapshot, { + production, + futureDefaults + }); - const idReplacer = replacer(chunk.id); - const nameReplacer = replacer(chunk.name || chunk.id); - const chunkhashReplacer = hashLength( - replacer(chunk instanceof Chunk ? chunk.renderedHash : chunk.hash), - "hashWithLength" in chunk ? chunk.hashWithLength : undefined, - assetInfo, - "chunkhash" - ); - const contenthashReplacer = hashLength( - replacer( - data.contentHash || - (contentHashType && - chunk.contentHash && - chunk.contentHash[contentHashType]) - ), - data.contentHashWithLength || - ("contentHashWithLength" in chunk && chunk.contentHashWithLength - ? chunk.contentHashWithLength[contentHashType] - : undefined), - assetInfo, - "contenthash" - ); + applyModuleDefaults(options.module, { + cache, + syncWebAssembly: options.experiments.syncWebAssembly, + asyncWebAssembly: options.experiments.asyncWebAssembly, + css: options.experiments.css, + futureDefaults + }); - replacements.set("id", idReplacer); - replacements.set("name", nameReplacer); - replacements.set("chunkhash", chunkhashReplacer); - replacements.set("contenthash", contenthashReplacer); - } + applyOutputDefaults(options.output, { + context: options.context, + targetProperties, + isAffectedByBrowserslist: + target === undefined || + (typeof target === "string" && target.startsWith("browserslist")) || + (Array.isArray(target) && + target.some(target => target.startsWith("browserslist"))), + outputModule: options.experiments.outputModule, + development, + entry: options.entry, + module: options.module, + futureDefaults + }); - // Module Context - // - // Placeholders - // - // [id] - module.id (2.png) - // [hash] - module.hash (6237543873.png) - // - // Legacy Placeholders - // - // [moduleid] - module.id (2.png) - // [modulehash] - module.hash (6237543873.png) - if (data.module) { - const module = data.module; + applyExternalsPresetsDefaults(options.externalsPresets, { + targetProperties, + buildHttp: !!options.experiments.buildHttp + }); - const idReplacer = replacer(() => - prepareId( - module instanceof Module ? chunkGraph.getModuleId(module) : module.id - ) - ); - const moduleHashReplacer = hashLength( - replacer(() => - module instanceof Module - ? chunkGraph.getRenderedModuleHash(module, data.runtime) - : module.hash - ), - "hashWithLength" in module ? module.hashWithLength : undefined, - assetInfo, - "modulehash" - ); - const contentHashReplacer = hashLength( - replacer(data.contentHash), - undefined, - assetInfo, - "contenthash" - ); + applyLoaderDefaults(options.loader, { targetProperties }); - replacements.set("id", idReplacer); - replacements.set("modulehash", moduleHashReplacer); - replacements.set("contenthash", contentHashReplacer); - replacements.set( - "hash", - data.contentHash ? contentHashReplacer : moduleHashReplacer - ); - // Legacy - replacements.set( - "moduleid", - deprecated( - idReplacer, - "[moduleid] is now [id]", - "DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_MODULE_ID" - ) - ); - } + F(options, "externalsType", () => { + const validExternalTypes = (__webpack_require__(73342).definitions.ExternalsType["enum"]); + return options.output.library && + validExternalTypes.includes(options.output.library.type) + ? /** @type {ExternalsType} */ (options.output.library.type) + : options.output.module + ? "module" + : "var"; + }); - // Other things - if (data.url) { - replacements.set("url", replacer(data.url)); - } - if (typeof data.runtime === "string") { - replacements.set( - "runtime", - replacer(() => prepareId(data.runtime)) - ); - } else { - replacements.set("runtime", replacer("_")); - } + applyNodeDefaults(options.node, { + futureDefaults: options.experiments.futureDefaults, + targetProperties + }); - if (typeof path === "function") { - path = path(data, assetInfo); - } + F(options, "performance", () => + production && + targetProperties && + (targetProperties.browser || targetProperties.browser === null) + ? {} + : false + ); + applyPerformanceDefaults(options.performance, { + production + }); - path = path.replace(REGEXP, (match, content) => { - if (content.length + 2 === match.length) { - const contentMatch = /^(\w+)(?::(\w+))?$/.exec(content); - if (!contentMatch) return match; - const [, kind, arg] = contentMatch; - const replacer = replacements.get(kind); - if (replacer !== undefined) { - return replacer(match, arg, path); - } - } else if (match.startsWith("[\\") && match.endsWith("\\]")) { - return `[${match.slice(2, -2)}]`; - } - return match; + applyOptimizationDefaults(options.optimization, { + development, + production, + css: options.experiments.css, + records: !!(options.recordsInputPath || options.recordsOutputPath) }); - return path; + options.resolve = cleverMerge( + getResolveDefaults({ + cache, + context: options.context, + targetProperties, + mode: options.mode + }), + options.resolve + ); + + options.resolveLoader = cleverMerge( + getResolveLoaderDefaults({ cache }), + options.resolveLoader + ); }; -const plugin = "TemplatedPathPlugin"; +/** + * @param {ExperimentsNormalized} experiments options + * @param {Object} options options + * @param {boolean} options.production is production + * @param {boolean} options.development is development mode + * @param {TargetProperties | false} options.targetProperties target properties + * @returns {void} + */ +const applyExperimentsDefaults = ( + experiments, + { production, development, targetProperties } +) => { + D(experiments, "futureDefaults", false); + D(experiments, "backCompat", !experiments.futureDefaults); + D(experiments, "topLevelAwait", experiments.futureDefaults); + D(experiments, "syncWebAssembly", false); + D(experiments, "asyncWebAssembly", experiments.futureDefaults); + D(experiments, "outputModule", false); + D(experiments, "layers", false); + D(experiments, "lazyCompilation", undefined); + D(experiments, "buildHttp", undefined); + D(experiments, "cacheUnaffected", experiments.futureDefaults); + F(experiments, "css", () => (experiments.futureDefaults ? {} : undefined)); -class TemplatedPathPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap(plugin, compilation => { - compilation.hooks.assetPath.tap(plugin, replacePathVariables); - }); + if (typeof experiments.buildHttp === "object") { + D(experiments.buildHttp, "frozen", production); + D(experiments.buildHttp, "upgrade", false); } -} - -module.exports = TemplatedPathPlugin; - - -/***/ }), - -/***/ 68099: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - - - -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); -class UnhandledSchemeError extends WebpackError { - /** - * @param {string} scheme scheme - * @param {string} resource resource - */ - constructor(scheme, resource) { - super( - `Reading from "${resource}" is not handled by plugins (Unhandled scheme).` + - '\nWebpack supports "data:" and "file:" URIs by default.' + - `\nYou may need an additional plugin to handle "${scheme}:" URIs.` + if (typeof experiments.css === "object") { + D( + experiments.css, + "exportsOnly", + !targetProperties || !targetProperties.document ); - this.file = resource; - this.name = "UnhandledSchemeError"; } -} - -makeSerializable( - UnhandledSchemeError, - "webpack/lib/UnhandledSchemeError", - "UnhandledSchemeError" -); - -module.exports = UnhandledSchemeError; - - -/***/ }), - -/***/ 42495: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); - -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ - -class UnsupportedFeatureWarning extends WebpackError { - /** - * @param {string} message description of warning - * @param {DependencyLocation} loc location start and end positions of the module - */ - constructor(message, loc) { - super(message); +}; - this.name = "UnsupportedFeatureWarning"; - this.loc = loc; - this.hideStack = true; +/** + * @param {CacheOptions} cache options + * @param {Object} options options + * @param {string} options.name name + * @param {string} options.mode mode + * @param {boolean} options.development is development mode + * @param {boolean} options.cacheUnaffected the cacheUnaffected experiment is enabled + * @returns {void} + */ +const applyCacheDefaults = ( + cache, + { name, mode, development, cacheUnaffected } +) => { + if (cache === false) return; + switch (cache.type) { + case "filesystem": + F(cache, "name", () => name + "-" + mode); + D(cache, "version", ""); + F(cache, "cacheDirectory", () => { + const cwd = process.cwd(); + let dir = cwd; + for (;;) { + try { + if (fs.statSync(path.join(dir, "package.json")).isFile()) break; + // eslint-disable-next-line no-empty + } catch (e) {} + const parent = path.dirname(dir); + if (dir === parent) { + dir = undefined; + break; + } + dir = parent; + } + if (!dir) { + return path.resolve(cwd, ".cache/webpack"); + } else if (process.versions.pnp === "1") { + return path.resolve(dir, ".pnp/.cache/webpack"); + } else if (process.versions.pnp === "3") { + return path.resolve(dir, ".yarn/.cache/webpack"); + } else { + return path.resolve(dir, "node_modules/.cache/webpack"); + } + }); + F(cache, "cacheLocation", () => + path.resolve(cache.cacheDirectory, cache.name) + ); + D(cache, "hashAlgorithm", "md4"); + D(cache, "store", "pack"); + D(cache, "compression", false); + D(cache, "profile", false); + D(cache, "idleTimeout", 60000); + D(cache, "idleTimeoutForInitialStore", 5000); + D(cache, "idleTimeoutAfterLargeChanges", 1000); + D(cache, "maxMemoryGenerations", development ? 5 : Infinity); + D(cache, "maxAge", 1000 * 60 * 60 * 24 * 60); // 1 month + D(cache, "allowCollectingMemory", development); + D(cache, "memoryCacheUnaffected", development && cacheUnaffected); + D(cache.buildDependencies, "defaultWebpack", [ + path.resolve(__dirname, "..") + path.sep + ]); + break; + case "memory": + D(cache, "maxGenerations", Infinity); + D(cache, "cacheUnaffected", development && cacheUnaffected); + break; } -} - -makeSerializable( - UnsupportedFeatureWarning, - "webpack/lib/UnsupportedFeatureWarning" -); - -module.exports = UnsupportedFeatureWarning; - - -/***/ }), - -/***/ 36803: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const ConstDependency = __webpack_require__(76911); - -/** @typedef {import("./Compiler")} Compiler */ - -class UseStrictPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "UseStrictPlugin", - (compilation, { normalModuleFactory }) => { - const handler = parser => { - parser.hooks.program.tap("UseStrictPlugin", ast => { - const firstNode = ast.body[0]; - if ( - firstNode && - firstNode.type === "ExpressionStatement" && - firstNode.expression.type === "Literal" && - firstNode.expression.value === "use strict" - ) { - // Remove "use strict" expression. It will be added later by the renderer again. - // This is necessary in order to not break the strict mode when webpack prepends code. - // @see https://github.com/webpack/webpack/issues/1970 - const dep = new ConstDependency("", firstNode.range); - dep.loc = firstNode.loc; - parser.state.module.addPresentationalDependency(dep); - parser.state.module.buildInfo.strict = true; - } - }); - }; +}; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("UseStrictPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("UseStrictPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("UseStrictPlugin", handler); - } +/** + * @param {SnapshotOptions} snapshot options + * @param {Object} options options + * @param {boolean} options.production is production + * @param {boolean} options.futureDefaults is future defaults enabled + * @returns {void} + */ +const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => { + if (futureDefaults) { + F(snapshot, "managedPaths", () => + process.versions.pnp === "3" + ? [ + /^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/ + ] + : [/^(.+?[\\/]node_modules[\\/])/] ); - } -} - -module.exports = UseStrictPlugin; - - -/***/ }), - -/***/ 56504: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const CaseSensitiveModulesWarning = __webpack_require__(77975); - -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Module")} Module */ - -class WarnCaseSensitiveModulesPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "WarnCaseSensitiveModulesPlugin", - compilation => { - compilation.hooks.seal.tap("WarnCaseSensitiveModulesPlugin", () => { - /** @type {Map>} */ - const moduleWithoutCase = new Map(); - for (const module of compilation.modules) { - const identifier = module.identifier(); - const lowerIdentifier = identifier.toLowerCase(); - let map = moduleWithoutCase.get(lowerIdentifier); - if (map === undefined) { - map = new Map(); - moduleWithoutCase.set(lowerIdentifier, map); - } - map.set(identifier, module); - } - for (const pair of moduleWithoutCase) { - const map = pair[1]; - if (map.size > 1) { - compilation.warnings.push( - new CaseSensitiveModulesWarning( - map.values(), - compilation.moduleGraph - ) - ); - } - } - }); - } + F(snapshot, "immutablePaths", () => + process.versions.pnp === "3" + ? [/^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/] + : [] ); - } -} - -module.exports = WarnCaseSensitiveModulesPlugin; - - -/***/ }), - -/***/ 76537: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ - - - -const WebpackError = __webpack_require__(53799); - -/** @typedef {import("./Compiler")} Compiler */ - -class WarnDeprecatedOptionPlugin { - /** - * Create an instance of the plugin - * @param {string} option the target option - * @param {string | number} value the deprecated option value - * @param {string} suggestion the suggestion replacement - */ - constructor(option, value, suggestion) { - this.option = option; - this.value = value; - this.suggestion = suggestion; - } - - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "WarnDeprecatedOptionPlugin", - compilation => { - compilation.warnings.push( - new DeprecatedOptionWarning(this.option, this.value, this.suggestion) + } else { + A(snapshot, "managedPaths", () => { + if (process.versions.pnp === "3") { + const match = + /^(.+?)[\\/]cache[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec( + /*require.resolve*/(36871) + ); + if (match) { + return [path.resolve(match[1], "unplugged")]; + } + } else { + const match = /^(.+?[\\/]node_modules[\\/])/.exec( + // eslint-disable-next-line node/no-extraneous-require + /*require.resolve*/(36871) ); + if (match) { + return [match[1]]; + } } - ); - } -} - -class DeprecatedOptionWarning extends WebpackError { - constructor(option, value, suggestion) { - super(); - - this.name = "DeprecatedOptionWarning"; - this.message = - "configuration\n" + - `The value '${value}' for option '${option}' is deprecated. ` + - `Use '${suggestion}' instead.`; - } -} - -module.exports = WarnDeprecatedOptionPlugin; - - -/***/ }), - -/***/ 25295: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const NoModeWarning = __webpack_require__(80832); - -/** @typedef {import("./Compiler")} Compiler */ - -class WarnNoModeSetPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap("WarnNoModeSetPlugin", compilation => { - compilation.warnings.push(new NoModeWarning()); + return []; + }); + A(snapshot, "immutablePaths", () => { + if (process.versions.pnp === "1") { + const match = + /^(.+?[\\/]v4)[\\/]npm-watchpack-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec( + /*require.resolve*/(36871) + ); + if (match) { + return [match[1]]; + } + } else if (process.versions.pnp === "3") { + const match = + /^(.+?)[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec( + /*require.resolve*/(36871) + ); + if (match) { + return [match[1]]; + } + } + return []; }); } -} - -module.exports = WarnNoModeSetPlugin; - - -/***/ }), - -/***/ 65193: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { groupBy } = __webpack_require__(84953); -const createSchemaValidation = __webpack_require__(32540); + F(snapshot, "resolveBuildDependencies", () => ({ + timestamp: true, + hash: true + })); + F(snapshot, "buildDependencies", () => ({ timestamp: true, hash: true })); + F(snapshot, "module", () => + production ? { timestamp: true, hash: true } : { timestamp: true } + ); + F(snapshot, "resolve", () => + production ? { timestamp: true, hash: true } : { timestamp: true } + ); +}; -/** @typedef {import("../declarations/plugins/WatchIgnorePlugin").WatchIgnorePluginOptions} WatchIgnorePluginOptions */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */ +/** + * @param {JavascriptParserOptions} parserOptions parser options + * @param {Object} options options + * @param {boolean} options.futureDefaults is future defaults enabled + * @returns {void} + */ +const applyJavascriptParserOptionsDefaults = ( + parserOptions, + { futureDefaults } +) => { + D(parserOptions, "unknownContextRequest", "."); + D(parserOptions, "unknownContextRegExp", false); + D(parserOptions, "unknownContextRecursive", true); + D(parserOptions, "unknownContextCritical", true); + D(parserOptions, "exprContextRequest", "."); + D(parserOptions, "exprContextRegExp", false); + D(parserOptions, "exprContextRecursive", true); + D(parserOptions, "exprContextCritical", true); + D(parserOptions, "wrappedContextRegExp", /.*/); + D(parserOptions, "wrappedContextRecursive", true); + D(parserOptions, "wrappedContextCritical", false); + D(parserOptions, "strictThisContextOnImports", false); + if (futureDefaults) D(parserOptions, "exportsPresence", "error"); +}; -const validate = createSchemaValidation( - __webpack_require__(16711), - () => __webpack_require__(44246), - { - name: "Watch Ignore Plugin", - baseDataPath: "options" +/** + * @param {ModuleOptions} module options + * @param {Object} options options + * @param {boolean} options.cache is caching enabled + * @param {boolean} options.syncWebAssembly is syncWebAssembly enabled + * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled + * @param {CssExperimentOptions} options.css is css enabled + * @param {boolean} options.futureDefaults is future defaults enabled + * @returns {void} + */ +const applyModuleDefaults = ( + module, + { cache, syncWebAssembly, asyncWebAssembly, css, futureDefaults } +) => { + if (cache) { + D(module, "unsafeCache", module => { + const name = module.nameForCondition(); + return name && NODE_MODULES_REGEXP.test(name); + }); + } else { + D(module, "unsafeCache", false); } -); - -const IGNORE_TIME_ENTRY = "ignore"; -class IgnoringWatchFileSystem { - /** - * @param {WatchFileSystem} wfs original file system - * @param {(string|RegExp)[]} paths ignored paths - */ - constructor(wfs, paths) { - this.wfs = wfs; - this.paths = paths; + F(module.parser, "asset", () => ({})); + F(module.parser.asset, "dataUrlCondition", () => ({})); + if (typeof module.parser.asset.dataUrlCondition === "object") { + D(module.parser.asset.dataUrlCondition, "maxSize", 8096); } - watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { - files = Array.from(files); - dirs = Array.from(dirs); - const ignored = path => - this.paths.some(p => - p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0 - ); - - const [ignoredFiles, notIgnoredFiles] = groupBy(files, ignored); - const [ignoredDirs, notIgnoredDirs] = groupBy(dirs, ignored); - - const watcher = this.wfs.watch( - notIgnoredFiles, - notIgnoredDirs, - missing, - startTime, - options, - (err, fileTimestamps, dirTimestamps, changedFiles, removedFiles) => { - if (err) return callback(err); - for (const path of ignoredFiles) { - fileTimestamps.set(path, IGNORE_TIME_ENTRY); - } + F(module.parser, "javascript", () => ({})); + applyJavascriptParserOptionsDefaults(module.parser.javascript, { + futureDefaults + }); - for (const path of ignoredDirs) { - dirTimestamps.set(path, IGNORE_TIME_ENTRY); + A(module, "defaultRules", () => { + const esm = { + type: "javascript/esm", + resolve: { + byDependency: { + esm: { + fullySpecified: true + } } - - callback( - err, - fileTimestamps, - dirTimestamps, - changedFiles, - removedFiles - ); + } + }; + const commonjs = { + type: "javascript/dynamic" + }; + /** @type {RuleSetRules} */ + const rules = [ + { + mimetype: "application/node", + type: "javascript/auto" }, - callbackUndelayed - ); - - return { - close: () => watcher.close(), - pause: () => watcher.pause(), - getContextTimeInfoEntries: () => { - const dirTimestamps = watcher.getContextTimeInfoEntries(); - for (const path of ignoredDirs) { - dirTimestamps.set(path, IGNORE_TIME_ENTRY); - } - return dirTimestamps; + { + test: /\.json$/i, + type: "json" }, - getFileTimeInfoEntries: () => { - const fileTimestamps = watcher.getFileTimeInfoEntries(); - for (const path of ignoredFiles) { - fileTimestamps.set(path, IGNORE_TIME_ENTRY); - } - return fileTimestamps; + { + mimetype: "application/json", + type: "json" }, - getInfo: - watcher.getInfo && - (() => { - const info = watcher.getInfo(); - const { fileTimeInfoEntries, contextTimeInfoEntries } = info; - for (const path of ignoredFiles) { - fileTimeInfoEntries.set(path, IGNORE_TIME_ENTRY); + { + test: /\.mjs$/i, + ...esm + }, + { + test: /\.js$/i, + descriptionData: { + type: "module" + }, + ...esm + }, + { + test: /\.cjs$/i, + ...commonjs + }, + { + test: /\.js$/i, + descriptionData: { + type: "commonjs" + }, + ...commonjs + }, + { + mimetype: { + or: ["text/javascript", "application/javascript"] + }, + ...esm + } + ]; + if (asyncWebAssembly) { + const wasm = { + type: "webassembly/async", + rules: [ + { + descriptionData: { + type: "module" + }, + resolve: { + fullySpecified: true + } } - for (const path of ignoredDirs) { - contextTimeInfoEntries.set(path, IGNORE_TIME_ENTRY); + ] + }; + rules.push({ + test: /\.wasm$/i, + ...wasm + }); + rules.push({ + mimetype: "application/wasm", + ...wasm + }); + } else if (syncWebAssembly) { + const wasm = { + type: "webassembly/sync", + rules: [ + { + descriptionData: { + type: "module" + }, + resolve: { + fullySpecified: true + } } - return info; - }) - }; - } -} - -class WatchIgnorePlugin { - /** - * @param {WatchIgnorePluginOptions} options options - */ - constructor(options) { - validate(options); - this.paths = options.paths; - } - - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.afterEnvironment.tap("WatchIgnorePlugin", () => { - compiler.watchFileSystem = new IgnoringWatchFileSystem( - compiler.watchFileSystem, - this.paths - ); - }); - } -} - -module.exports = WatchIgnorePlugin; - - -/***/ }), - -/***/ 84275: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Stats = __webpack_require__(31743); - -/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ + ] + }; + rules.push({ + test: /\.wasm$/i, + ...wasm + }); + rules.push({ + mimetype: "application/wasm", + ...wasm + }); + } + if (css) { + const cssRule = { + type: "css", + resolve: { + fullySpecified: true, + preferRelative: true + } + }; + const cssModulesRule = { + type: "css/module", + resolve: { + fullySpecified: true + } + }; + rules.push({ + test: /\.css$/i, + oneOf: [ + { + test: /\.module\.css$/i, + ...cssModulesRule + }, + { + ...cssRule + } + ] + }); + rules.push({ + mimetype: "text/css+module", + ...cssModulesRule + }); + rules.push({ + mimetype: "text/css", + ...cssRule + }); + } + rules.push( + { + dependency: "url", + oneOf: [ + { + scheme: /^data$/, + type: "asset/inline" + }, + { + type: "asset/resource" + } + ] + }, + { + assert: { type: "json" }, + type: "json" + } + ); + return rules; + }); +}; /** - * @template T - * @callback Callback - * @param {(Error | null)=} err - * @param {T=} result + * @param {Output} output options + * @param {Object} options options + * @param {string} options.context context + * @param {TargetProperties | false} options.targetProperties target properties + * @param {boolean} options.isAffectedByBrowserslist is affected by browserslist + * @param {boolean} options.outputModule is outputModule experiment enabled + * @param {boolean} options.development is development mode + * @param {Entry} options.entry entry option + * @param {ModuleOptions} options.module module option + * @param {boolean} options.futureDefaults is future defaults enabled + * @returns {void} */ - -class Watching { +const applyOutputDefaults = ( + output, + { + context, + targetProperties: tp, + isAffectedByBrowserslist, + outputModule, + development, + entry, + module, + futureDefaults + } +) => { /** - * @param {Compiler} compiler the compiler - * @param {WatchOptions} watchOptions options - * @param {Callback} handler completion handler + * @param {Library=} library the library option + * @returns {string} a readable library name */ - constructor(compiler, watchOptions, handler) { - this.startTime = null; - this.invalid = false; - this.handler = handler; - /** @type {Callback[]} */ - this.callbacks = []; - /** @type {Callback[] | undefined} */ - this._closeCallbacks = undefined; - this.closed = false; - this.suspended = false; - this.blocked = false; - this._isBlocked = () => false; - this._onChange = () => {}; - this._onInvalid = () => {}; - if (typeof watchOptions === "number") { - this.watchOptions = { - aggregateTimeout: watchOptions - }; - } else if (watchOptions && typeof watchOptions === "object") { - this.watchOptions = { ...watchOptions }; - } else { - this.watchOptions = {}; - } - if (typeof this.watchOptions.aggregateTimeout !== "number") { - this.watchOptions.aggregateTimeout = 20; + const getLibraryName = library => { + const libraryName = + typeof library === "object" && + library && + !Array.isArray(library) && + "type" in library + ? library.name + : /** @type {LibraryName=} */ (library); + if (Array.isArray(libraryName)) { + return libraryName.join("."); + } else if (typeof libraryName === "object") { + return getLibraryName(libraryName.root); + } else if (typeof libraryName === "string") { + return libraryName; } - this.compiler = compiler; - this.running = false; - this._initial = true; - this._invalidReported = true; - this._needRecords = true; - this.watcher = undefined; - this.pausedWatcher = undefined; - /** @type {Set} */ - this._collectedChangedFiles = undefined; - /** @type {Set} */ - this._collectedRemovedFiles = undefined; - this._done = this._done.bind(this); - process.nextTick(() => { - if (this._initial) this._invalidate(); - }); - } + return ""; + }; - /** - * @param {ReadonlySet} changedFiles changed files - * @param {ReadonlySet} removedFiles removed files - */ - _mergeWithCollected(changedFiles, removedFiles) { - if (!changedFiles) return; - if (!this._collectedChangedFiles) { - this._collectedChangedFiles = new Set(changedFiles); - this._collectedRemovedFiles = new Set(removedFiles); - } else { - for (const file of changedFiles) { - this._collectedChangedFiles.add(file); - this._collectedRemovedFiles.delete(file); - } - for (const file of removedFiles) { - this._collectedChangedFiles.delete(file); - this._collectedRemovedFiles.add(file); + F(output, "uniqueName", () => { + const libraryName = getLibraryName(output.library); + if (libraryName) return libraryName; + const pkgPath = path.resolve(context, "package.json"); + try { + const packageInfo = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); + return packageInfo.name || ""; + } catch (e) { + if (e.code !== "ENOENT") { + e.message += `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`; + throw e; } + return ""; } - } + }); - /** - * @param {ReadonlyMap=} fileTimeInfoEntries info for files - * @param {ReadonlyMap=} contextTimeInfoEntries info for directories - * @param {ReadonlySet=} changedFiles changed files - * @param {ReadonlySet=} removedFiles removed files - * @returns {void} - */ - _go(fileTimeInfoEntries, contextTimeInfoEntries, changedFiles, removedFiles) { - this._initial = false; - if (this.startTime === null) this.startTime = Date.now(); - this.running = true; - if (this.watcher) { - this.pausedWatcher = this.watcher; - this.lastWatcherStartTime = Date.now(); - this.watcher.pause(); - this.watcher = null; - } else if (!this.lastWatcherStartTime) { - this.lastWatcherStartTime = Date.now(); + F(output, "module", () => !!outputModule); + D(output, "filename", output.module ? "[name].mjs" : "[name].js"); + F(output, "iife", () => !output.module); + D(output, "importFunctionName", "import"); + D(output, "importMetaName", "import.meta"); + F(output, "chunkFilename", () => { + const filename = output.filename; + if (typeof filename !== "function") { + const hasName = filename.includes("[name]"); + const hasId = filename.includes("[id]"); + const hasChunkHash = filename.includes("[chunkhash]"); + const hasContentHash = filename.includes("[contenthash]"); + // Anything changing depending on chunk is fine + if (hasChunkHash || hasContentHash || hasName || hasId) return filename; + // Otherwise prefix "[id]." in front of the basename to make it changing + return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2"); } - this.compiler.fsStartTime = Date.now(); - if ( - changedFiles && - removedFiles && - fileTimeInfoEntries && - contextTimeInfoEntries - ) { - this._mergeWithCollected(changedFiles, removedFiles); - this.compiler.fileTimestamps = fileTimeInfoEntries; - this.compiler.contextTimestamps = contextTimeInfoEntries; - } else if (this.pausedWatcher) { - if (this.pausedWatcher.getInfo) { - const { - changes, - removals, - fileTimeInfoEntries, - contextTimeInfoEntries - } = this.pausedWatcher.getInfo(); - this._mergeWithCollected(changes, removals); - this.compiler.fileTimestamps = fileTimeInfoEntries; - this.compiler.contextTimestamps = contextTimeInfoEntries; + return output.module ? "[id].mjs" : "[id].js"; + }); + F(output, "cssFilename", () => { + const filename = output.filename; + if (typeof filename !== "function") { + return filename.replace(/\.[mc]?js(\?|$)/, ".css$1"); + } + return "[id].css"; + }); + F(output, "cssChunkFilename", () => { + const chunkFilename = output.chunkFilename; + if (typeof chunkFilename !== "function") { + return chunkFilename.replace(/\.[mc]?js(\?|$)/, ".css$1"); + } + return "[id].css"; + }); + D(output, "assetModuleFilename", "[hash][ext][query]"); + D(output, "webassemblyModuleFilename", "[hash].module.wasm"); + D(output, "compareBeforeEmit", true); + D(output, "charset", true); + F(output, "hotUpdateGlobal", () => + Template.toIdentifier( + "webpackHotUpdate" + Template.toIdentifier(output.uniqueName) + ) + ); + F(output, "chunkLoadingGlobal", () => + Template.toIdentifier( + "webpackChunk" + Template.toIdentifier(output.uniqueName) + ) + ); + F(output, "globalObject", () => { + if (tp) { + if (tp.global) return "global"; + if (tp.globalThis) return "globalThis"; + } + return "self"; + }); + F(output, "chunkFormat", () => { + if (tp) { + const helpMessage = isAffectedByBrowserslist + ? "Make sure that your 'browserslist' includes only platforms that support these features or select an appropriate 'target' to allow selecting a chunk format by default. Alternatively specify the 'output.chunkFormat' directly." + : "Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly."; + if (output.module) { + if (tp.dynamicImport) return "module"; + if (tp.document) return "array-push"; + throw new Error( + "For the selected environment is no default ESM chunk format available:\n" + + "ESM exports can be chosen when 'import()' is available.\n" + + "JSONP Array push can be chosen when 'document' is available.\n" + + helpMessage + ); } else { - this._mergeWithCollected( - this.pausedWatcher.getAggregatedChanges && - this.pausedWatcher.getAggregatedChanges(), - this.pausedWatcher.getAggregatedRemovals && - this.pausedWatcher.getAggregatedRemovals() + if (tp.document) return "array-push"; + if (tp.require) return "commonjs"; + if (tp.nodeBuiltins) return "commonjs"; + if (tp.importScripts) return "array-push"; + throw new Error( + "For the selected environment is no default script chunk format available:\n" + + "JSONP Array push can be chosen when 'document' or 'importScripts' is available.\n" + + "CommonJs exports can be chosen when 'require' or node builtins are available.\n" + + helpMessage ); - this.compiler.fileTimestamps = - this.pausedWatcher.getFileTimeInfoEntries(); - this.compiler.contextTimestamps = - this.pausedWatcher.getContextTimeInfoEntries(); } } - this.compiler.modifiedFiles = this._collectedChangedFiles; - this._collectedChangedFiles = undefined; - this.compiler.removedFiles = this._collectedRemovedFiles; - this._collectedRemovedFiles = undefined; - - const run = () => { - if (this.compiler.idle) { - return this.compiler.cache.endIdle(err => { - if (err) return this._done(err); - this.compiler.idle = false; - run(); - }); + throw new Error( + "Chunk format can't be selected by default when no target is specified" + ); + }); + D(output, "asyncChunks", true); + F(output, "chunkLoading", () => { + if (tp) { + switch (output.chunkFormat) { + case "array-push": + if (tp.document) return "jsonp"; + if (tp.importScripts) return "import-scripts"; + break; + case "commonjs": + if (tp.require) return "require"; + if (tp.nodeBuiltins) return "async-node"; + break; + case "module": + if (tp.dynamicImport) return "import"; + break; } - if (this._needRecords) { - return this.compiler.readRecords(err => { - if (err) return this._done(err); - - this._needRecords = false; - run(); - }); + if ( + tp.require === null || + tp.nodeBuiltins === null || + tp.document === null || + tp.importScripts === null + ) { + return "universal"; } - this.invalid = false; - this._invalidReported = false; - this.compiler.hooks.watchRun.callAsync(this.compiler, err => { - if (err) return this._done(err); - const onCompiled = (err, compilation) => { - if (err) return this._done(err, compilation); - if (this.invalid) return this._done(null, compilation); - - if (this.compiler.hooks.shouldEmit.call(compilation) === false) { - return this._done(null, compilation); - } - - process.nextTick(() => { - const logger = compilation.getLogger("webpack.Compiler"); - logger.time("emitAssets"); - this.compiler.emitAssets(compilation, err => { - logger.timeEnd("emitAssets"); - if (err) return this._done(err, compilation); - if (this.invalid) return this._done(null, compilation); - - logger.time("emitRecords"); - this.compiler.emitRecords(err => { - logger.timeEnd("emitRecords"); - if (err) return this._done(err, compilation); - - if (compilation.hooks.needAdditionalPass.call()) { - compilation.needAdditionalPass = true; - - compilation.startTime = this.startTime; - compilation.endTime = Date.now(); - logger.time("done hook"); - const stats = new Stats(compilation); - this.compiler.hooks.done.callAsync(stats, err => { - logger.timeEnd("done hook"); - if (err) return this._done(err, compilation); - - this.compiler.hooks.additionalPass.callAsync(err => { - if (err) return this._done(err, compilation); - this.compiler.compile(onCompiled); - }); - }); - return; - } - return this._done(null, compilation); - }); - }); - }); - }; - this.compiler.compile(onCompiled); - }); - }; - - run(); - } - - /** - * @param {Compilation} compilation the compilation - * @returns {Stats} the compilation stats - */ - _getStats(compilation) { - const stats = new Stats(compilation); - return stats; - } - - /** - * @param {Error=} err an optional error - * @param {Compilation=} compilation the compilation - * @returns {void} - */ - _done(err, compilation) { - this.running = false; - - const logger = compilation && compilation.getLogger("webpack.Watching"); - - let stats = null; - - const handleError = (err, cbs) => { - this.compiler.hooks.failed.call(err); - this.compiler.cache.beginIdle(); - this.compiler.idle = true; - this.handler(err, stats); - if (!cbs) { - cbs = this.callbacks; - this.callbacks = []; + } + return false; + }); + F(output, "workerChunkLoading", () => { + if (tp) { + switch (output.chunkFormat) { + case "array-push": + if (tp.importScriptsInWorker) return "import-scripts"; + break; + case "commonjs": + if (tp.require) return "require"; + if (tp.nodeBuiltins) return "async-node"; + break; + case "module": + if (tp.dynamicImportInWorker) return "import"; + break; } - for (const cb of cbs) cb(err); - }; - - if ( - this.invalid && - !this.suspended && - !this.blocked && - !(this._isBlocked() && (this.blocked = true)) - ) { - if (compilation) { - logger.time("storeBuildDependencies"); - this.compiler.cache.storeBuildDependencies( - compilation.buildDependencies, - err => { - logger.timeEnd("storeBuildDependencies"); - if (err) return handleError(err); - this._go(); - } - ); - } else { - this._go(); + if ( + tp.require === null || + tp.nodeBuiltins === null || + tp.importScriptsInWorker === null + ) { + return "universal"; } - return; } - - if (compilation) { - compilation.startTime = this.startTime; - compilation.endTime = Date.now(); - stats = new Stats(compilation); + return false; + }); + F(output, "wasmLoading", () => { + if (tp) { + if (tp.fetchWasm) return "fetch"; + if (tp.nodeBuiltins) + return output.module ? "async-node-module" : "async-node"; + if (tp.nodeBuiltins === null || tp.fetchWasm === null) { + return "universal"; + } } - this.startTime = null; - if (err) return handleError(err); - - const cbs = this.callbacks; - this.callbacks = []; - logger.time("done hook"); - this.compiler.hooks.done.callAsync(stats, err => { - logger.timeEnd("done hook"); - if (err) return handleError(err, cbs); - this.handler(null, stats); - logger.time("storeBuildDependencies"); - this.compiler.cache.storeBuildDependencies( - compilation.buildDependencies, - err => { - logger.timeEnd("storeBuildDependencies"); - if (err) return handleError(err, cbs); - logger.time("beginIdle"); - this.compiler.cache.beginIdle(); - this.compiler.idle = true; - logger.timeEnd("beginIdle"); - process.nextTick(() => { - if (!this.closed) { - this.watch( - compilation.fileDependencies, - compilation.contextDependencies, - compilation.missingDependencies - ); - } - }); - for (const cb of cbs) cb(null); - this.compiler.hooks.afterDone.call(stats); - } - ); - }); + return false; + }); + F(output, "workerWasmLoading", () => output.wasmLoading); + F(output, "devtoolNamespace", () => output.uniqueName); + if (output.library) { + F(output.library, "type", () => (output.module ? "module" : "var")); } + F(output, "path", () => path.join(process.cwd(), "dist")); + F(output, "pathinfo", () => development); + D(output, "sourceMapFilename", "[file].map[query]"); + D( + output, + "hotUpdateChunkFilename", + `[id].[fullhash].hot-update.${output.module ? "mjs" : "js"}` + ); + D(output, "hotUpdateMainFilename", "[runtime].[fullhash].hot-update.json"); + D(output, "crossOriginLoading", false); + F(output, "scriptType", () => (output.module ? "module" : false)); + D( + output, + "publicPath", + (tp && (tp.document || tp.importScripts)) || output.scriptType === "module" + ? "auto" + : "" + ); + D(output, "chunkLoadTimeout", 120000); + D(output, "hashFunction", futureDefaults ? "xxhash64" : "md4"); + D(output, "hashDigest", "hex"); + D(output, "hashDigestLength", futureDefaults ? 16 : 20); + D(output, "strictModuleExceptionHandling", false); - /** - * @param {Iterable} files watched files - * @param {Iterable} dirs watched directories - * @param {Iterable} missing watched existence entries - * @returns {void} - */ - watch(files, dirs, missing) { - this.pausedWatcher = null; - this.watcher = this.compiler.watchFileSystem.watch( - files, - dirs, - missing, - this.lastWatcherStartTime, - this.watchOptions, - ( - err, - fileTimeInfoEntries, - contextTimeInfoEntries, - changedFiles, - removedFiles - ) => { - if (err) { - this.compiler.modifiedFiles = undefined; - this.compiler.removedFiles = undefined; - this.compiler.fileTimestamps = undefined; - this.compiler.contextTimestamps = undefined; - this.compiler.fsStartTime = undefined; - return this.handler(err); - } - this._invalidate( - fileTimeInfoEntries, - contextTimeInfoEntries, - changedFiles, - removedFiles - ); - this._onChange(); - }, - (fileName, changeTime) => { - if (!this._invalidReported) { - this._invalidReported = true; - this.compiler.hooks.invalid.call(fileName, changeTime); - } - this._onInvalid(); - } + const optimistic = v => v || v === undefined; + F( + output.environment, + "arrowFunction", + () => tp && optimistic(tp.arrowFunction) + ); + F(output.environment, "const", () => tp && optimistic(tp.const)); + F( + output.environment, + "destructuring", + () => tp && optimistic(tp.destructuring) + ); + F(output.environment, "forOf", () => tp && optimistic(tp.forOf)); + F(output.environment, "bigIntLiteral", () => tp && tp.bigIntLiteral); + F(output.environment, "dynamicImport", () => tp && tp.dynamicImport); + F(output.environment, "module", () => tp && tp.module); + + const { trustedTypes } = output; + if (trustedTypes) { + F( + trustedTypes, + "policyName", + () => + output.uniqueName.replace(/[^a-zA-Z0-9\-#=_/@.%]+/g, "_") || "webpack" ); } /** - * @param {Callback=} callback signals when the build has completed again + * @param {function(EntryDescription): void} fn iterator * @returns {void} */ - invalidate(callback) { - if (callback) { - this.callbacks.push(callback); + const forEachEntry = fn => { + for (const name of Object.keys(entry)) { + fn(entry[name]); } - if (!this._invalidReported) { - this._invalidReported = true; - this.compiler.hooks.invalid.call(null, Date.now()); + }; + A(output, "enabledLibraryTypes", () => { + const enabledLibraryTypes = []; + if (output.library) { + enabledLibraryTypes.push(output.library.type); } - this._onChange(); - this._invalidate(); - } + forEachEntry(desc => { + if (desc.library) { + enabledLibraryTypes.push(desc.library.type); + } + }); + return enabledLibraryTypes; + }); - _invalidate( - fileTimeInfoEntries, - contextTimeInfoEntries, - changedFiles, - removedFiles - ) { - if (this.suspended || (this._isBlocked() && (this.blocked = true))) { - this._mergeWithCollected(changedFiles, removedFiles); - return; + A(output, "enabledChunkLoadingTypes", () => { + const enabledChunkLoadingTypes = new Set(); + if (output.chunkLoading) { + enabledChunkLoadingTypes.add(output.chunkLoading); } - - if (this.running) { - this._mergeWithCollected(changedFiles, removedFiles); - this.invalid = true; - } else { - this._go( - fileTimeInfoEntries, - contextTimeInfoEntries, - changedFiles, - removedFiles - ); + if (output.workerChunkLoading) { + enabledChunkLoadingTypes.add(output.workerChunkLoading); } - } - - suspend() { - this.suspended = true; - } + forEachEntry(desc => { + if (desc.chunkLoading) { + enabledChunkLoadingTypes.add(desc.chunkLoading); + } + }); + return Array.from(enabledChunkLoadingTypes); + }); - resume() { - if (this.suspended) { - this.suspended = false; - this._invalidate(); + A(output, "enabledWasmLoadingTypes", () => { + const enabledWasmLoadingTypes = new Set(); + if (output.wasmLoading) { + enabledWasmLoadingTypes.add(output.wasmLoading); } - } - - /** - * @param {Callback} callback signals when the watcher is closed - * @returns {void} - */ - close(callback) { - if (this._closeCallbacks) { - if (callback) { - this._closeCallbacks.push(callback); - } - return; + if (output.workerWasmLoading) { + enabledWasmLoadingTypes.add(output.workerWasmLoading); } - const finalCallback = (err, compilation) => { - this.running = false; - this.compiler.running = false; - this.compiler.watching = undefined; - this.compiler.watchMode = false; - this.compiler.modifiedFiles = undefined; - this.compiler.removedFiles = undefined; - this.compiler.fileTimestamps = undefined; - this.compiler.contextTimestamps = undefined; - this.compiler.fsStartTime = undefined; - const shutdown = err => { - this.compiler.hooks.watchClose.call(); - const closeCallbacks = this._closeCallbacks; - this._closeCallbacks = undefined; - for (const cb of closeCallbacks) cb(err); - }; - if (compilation) { - const logger = compilation.getLogger("webpack.Watching"); - logger.time("storeBuildDependencies"); - this.compiler.cache.storeBuildDependencies( - compilation.buildDependencies, - err2 => { - logger.timeEnd("storeBuildDependencies"); - shutdown(err || err2); - } - ); - } else { - shutdown(err); + forEachEntry(desc => { + if (desc.wasmLoading) { + enabledWasmLoadingTypes.add(desc.wasmLoading); } - }; + }); + return Array.from(enabledWasmLoadingTypes); + }); +}; - this.closed = true; - if (this.watcher) { - this.watcher.close(); - this.watcher = null; - } - if (this.pausedWatcher) { - this.pausedWatcher.close(); - this.pausedWatcher = null; - } - this._closeCallbacks = []; - if (callback) { - this._closeCallbacks.push(callback); - } - if (this.running) { - this.invalid = true; - this._done = finalCallback; - } else { - finalCallback(); +/** + * @param {ExternalsPresets} externalsPresets options + * @param {Object} options options + * @param {TargetProperties | false} options.targetProperties target properties + * @param {boolean} options.buildHttp buildHttp experiment enabled + * @returns {void} + */ +const applyExternalsPresetsDefaults = ( + externalsPresets, + { targetProperties, buildHttp } +) => { + D( + externalsPresets, + "web", + !buildHttp && targetProperties && targetProperties.web + ); + D(externalsPresets, "node", targetProperties && targetProperties.node); + D(externalsPresets, "nwjs", targetProperties && targetProperties.nwjs); + D( + externalsPresets, + "electron", + targetProperties && targetProperties.electron + ); + D( + externalsPresets, + "electronMain", + targetProperties && + targetProperties.electron && + targetProperties.electronMain + ); + D( + externalsPresets, + "electronPreload", + targetProperties && + targetProperties.electron && + targetProperties.electronPreload + ); + D( + externalsPresets, + "electronRenderer", + targetProperties && + targetProperties.electron && + targetProperties.electronRenderer + ); +}; + +/** + * @param {Loader} loader options + * @param {Object} options options + * @param {TargetProperties | false} options.targetProperties target properties + * @returns {void} + */ +const applyLoaderDefaults = (loader, { targetProperties }) => { + F(loader, "target", () => { + if (targetProperties) { + if (targetProperties.electron) { + if (targetProperties.electronMain) return "electron-main"; + if (targetProperties.electronPreload) return "electron-preload"; + if (targetProperties.electronRenderer) return "electron-renderer"; + return "electron"; + } + if (targetProperties.nwjs) return "nwjs"; + if (targetProperties.node) return "node"; + if (targetProperties.web) return "web"; } - } -} + }); +}; -module.exports = Watching; +/** + * @param {WebpackNode} node options + * @param {Object} options options + * @param {TargetProperties | false} options.targetProperties target properties + * @param {boolean} options.futureDefaults is future defaults enabled + * @returns {void} + */ +const applyNodeDefaults = (node, { futureDefaults, targetProperties }) => { + if (node === false) return; + F(node, "global", () => { + if (targetProperties && targetProperties.global) return false; + // TODO webpack 6 should always default to false + return futureDefaults ? "warn" : true; + }); + F(node, "__filename", () => { + if (targetProperties && targetProperties.node) return "eval-only"; + // TODO webpack 6 should always default to false + return futureDefaults ? "warn-mock" : "mock"; + }); + F(node, "__dirname", () => { + if (targetProperties && targetProperties.node) return "eval-only"; + // TODO webpack 6 should always default to false + return futureDefaults ? "warn-mock" : "mock"; + }); +}; -/***/ }), +/** + * @param {Performance} performance options + * @param {Object} options options + * @param {boolean} options.production is production + * @returns {void} + */ +const applyPerformanceDefaults = (performance, { production }) => { + if (performance === false) return; + D(performance, "maxAssetSize", 250000); + D(performance, "maxEntrypointSize", 250000); + F(performance, "hints", () => (production ? "warning" : false)); +}; -/***/ 53799: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @param {Optimization} optimization options + * @param {Object} options options + * @param {boolean} options.production is production + * @param {boolean} options.development is development + * @param {CssExperimentOptions} options.css is css enabled + * @param {boolean} options.records using records + * @returns {void} + */ +const applyOptimizationDefaults = ( + optimization, + { production, development, css, records } +) => { + D(optimization, "removeAvailableModules", false); + D(optimization, "removeEmptyChunks", true); + D(optimization, "mergeDuplicateChunks", true); + D(optimization, "flagIncludedChunks", production); + F(optimization, "moduleIds", () => { + if (production) return "deterministic"; + if (development) return "named"; + return "natural"; + }); + F(optimization, "chunkIds", () => { + if (production) return "deterministic"; + if (development) return "named"; + return "natural"; + }); + F(optimization, "sideEffects", () => (production ? true : "flag")); + D(optimization, "providedExports", true); + D(optimization, "usedExports", production); + D(optimization, "innerGraph", production); + D(optimization, "mangleExports", production); + D(optimization, "concatenateModules", production); + D(optimization, "runtimeChunk", false); + D(optimization, "emitOnErrors", !production); + D(optimization, "checkWasmTypes", production); + D(optimization, "mangleWasmImports", false); + D(optimization, "portableRecords", records); + D(optimization, "realContentHash", production); + D(optimization, "minimize", production); + A(optimization, "minimizer", () => [ + { + apply: compiler => { + // Lazy load the Terser plugin + const TerserPlugin = __webpack_require__(55302); + new TerserPlugin({ + terserOptions: { + compress: { + passes: 2 + } + } + }).apply(compiler); + } + } + ]); + F(optimization, "nodeEnv", () => { + if (production) return "production"; + if (development) return "development"; + return false; + }); + const { splitChunks } = optimization; + if (splitChunks) { + A(splitChunks, "defaultSizeTypes", () => + css ? ["javascript", "css", "unknown"] : ["javascript", "unknown"] + ); + D(splitChunks, "hidePathInfo", production); + D(splitChunks, "chunks", "async"); + D(splitChunks, "usedExports", optimization.usedExports === true); + D(splitChunks, "minChunks", 1); + F(splitChunks, "minSize", () => (production ? 20000 : 10000)); + F(splitChunks, "minRemainingSize", () => (development ? 0 : undefined)); + F(splitChunks, "enforceSizeThreshold", () => (production ? 50000 : 30000)); + F(splitChunks, "maxAsyncRequests", () => (production ? 30 : Infinity)); + F(splitChunks, "maxInitialRequests", () => (production ? 30 : Infinity)); + D(splitChunks, "automaticNameDelimiter", "-"); + const { cacheGroups } = splitChunks; + F(cacheGroups, "default", () => ({ + idHint: "", + reuseExistingChunk: true, + minChunks: 2, + priority: -20 + })); + F(cacheGroups, "defaultVendors", () => ({ + idHint: "vendors", + reuseExistingChunk: true, + test: NODE_MODULES_REGEXP, + priority: -10 + })); + } +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Jarid Margolin @jaridmargolin -*/ +/** + * @param {Object} options options + * @param {boolean} options.cache is cache enable + * @param {string} options.context build context + * @param {TargetProperties | false} options.targetProperties target properties + * @param {Mode} options.mode mode + * @returns {ResolveOptions} resolve options + */ +const getResolveDefaults = ({ cache, context, targetProperties, mode }) => { + /** @type {string[]} */ + const conditions = ["webpack"]; + conditions.push(mode === "development" ? "development" : "production"); + if (targetProperties) { + if (targetProperties.webworker) conditions.push("worker"); + if (targetProperties.node) conditions.push("node"); + if (targetProperties.web) conditions.push("browser"); + if (targetProperties.electron) conditions.push("electron"); + if (targetProperties.nwjs) conditions.push("nwjs"); + } -const inspect = (__webpack_require__(73837).inspect.custom); -const makeSerializable = __webpack_require__(33032); + const jsExtensions = [".js", ".json", ".wasm"]; -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Module")} Module */ + const tp = targetProperties; + const browserField = + tp && tp.web && (!tp.node || (tp.electron && tp.electronRenderer)); -class WebpackError extends Error { - /** - * Creates an instance of WebpackError. - * @param {string=} message error message - */ - constructor(message) { - super(message); + /** @type {function(): ResolveOptions} */ + const cjsDeps = () => ({ + aliasFields: browserField ? ["browser"] : [], + mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."], + conditionNames: ["require", "module", "..."], + extensions: [...jsExtensions] + }); + /** @type {function(): ResolveOptions} */ + const esmDeps = () => ({ + aliasFields: browserField ? ["browser"] : [], + mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."], + conditionNames: ["import", "module", "..."], + extensions: [...jsExtensions] + }); - this.details = undefined; - /** @type {Module} */ - this.module = undefined; - /** @type {DependencyLocation} */ - this.loc = undefined; - /** @type {boolean} */ - this.hideStack = undefined; - /** @type {Chunk} */ - this.chunk = undefined; - /** @type {string} */ - this.file = undefined; - } + /** @type {ResolveOptions} */ + const resolveOptions = { + cache, + modules: ["node_modules"], + conditionNames: conditions, + mainFiles: ["index"], + extensions: [], + aliasFields: [], + exportsFields: ["exports"], + roots: [context], + mainFields: ["main"], + byDependency: { + wasm: esmDeps(), + esm: esmDeps(), + loaderImport: esmDeps(), + url: { + preferRelative: true + }, + worker: { + ...esmDeps(), + preferRelative: true + }, + commonjs: cjsDeps(), + amd: cjsDeps(), + // for backward-compat: loadModule + loader: cjsDeps(), + // for backward-compat: Custom Dependency + unknown: cjsDeps(), + // for backward-compat: getResolve without dependencyType + undefined: cjsDeps() + } + }; - [inspect]() { - return this.stack + (this.details ? `\n${this.details}` : ""); - } + return resolveOptions; +}; - serialize({ write }) { - write(this.name); - write(this.message); - write(this.stack); - write(this.details); - write(this.loc); - write(this.hideStack); - } +/** + * @param {Object} options options + * @param {boolean} options.cache is cache enable + * @returns {ResolveOptions} resolve options + */ +const getResolveLoaderDefaults = ({ cache }) => { + /** @type {ResolveOptions} */ + const resolveOptions = { + cache, + conditionNames: ["loader", "require", "node"], + exportsFields: ["exports"], + mainFields: ["loader", "main"], + extensions: [".js"], + mainFiles: ["index"] + }; - deserialize({ read }) { - this.name = read(); - this.message = read(); - this.stack = read(); - this.details = read(); - this.loc = read(); - this.hideStack = read(); - } -} + return resolveOptions; +}; -makeSerializable(WebpackError, "webpack/lib/WebpackError"); +/** + * @param {InfrastructureLogging} infrastructureLogging options + * @returns {void} + */ +const applyInfrastructureLoggingDefaults = infrastructureLogging => { + F(infrastructureLogging, "stream", () => process.stderr); + const tty = + /** @type {any} */ (infrastructureLogging.stream).isTTY && + process.env.TERM !== "dumb"; + D(infrastructureLogging, "level", "info"); + D(infrastructureLogging, "debug", false); + D(infrastructureLogging, "colors", tty); + D(infrastructureLogging, "appendOnly", !tty); +}; -module.exports = WebpackError; +exports.applyWebpackOptionsBaseDefaults = applyWebpackOptionsBaseDefaults; +exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults; /***/ }), -/***/ 97017: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 26693: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const IgnoreErrorModuleFactory = __webpack_require__(3); -const WebpackIsIncludedDependency = __webpack_require__(26505); -const { - toConstantDependency -} = __webpack_require__(93998); +const util = __webpack_require__(73837); -/** @typedef {import("enhanced-resolve/lib/Resolver")} Resolver */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../../declarations/WebpackOptions").EntryStatic} EntryStatic */ +/** @typedef {import("../../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunk} OptimizationRuntimeChunk */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunkNormalized} OptimizationRuntimeChunkNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputNormalized */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */ -class WebpackIsIncludedPlugin { - /** - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "WebpackIsIncludedPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - WebpackIsIncludedDependency, - new IgnoreErrorModuleFactory(normalModuleFactory) - ); - compilation.dependencyTemplates.set( - WebpackIsIncludedDependency, - new WebpackIsIncludedDependency.Template() - ); +const handledDeprecatedNoEmitOnErrors = util.deprecate( + (noEmitOnErrors, emitOnErrors) => { + if (emitOnErrors !== undefined && !noEmitOnErrors === !emitOnErrors) { + throw new Error( + "Conflicting use of 'optimization.noEmitOnErrors' and 'optimization.emitOnErrors'. Remove deprecated 'optimization.noEmitOnErrors' from config." + ); + } + return !noEmitOnErrors; + }, + "optimization.noEmitOnErrors is deprecated in favor of optimization.emitOnErrors", + "DEP_WEBPACK_CONFIGURATION_OPTIMIZATION_NO_EMIT_ON_ERRORS" +); - /** - * @param {JavascriptParser} parser the parser - * @returns {void} - */ - const handler = parser => { - parser.hooks.call - .for("__webpack_is_included__") - .tap("WebpackIsIncludedPlugin", expr => { - if ( - expr.type !== "CallExpression" || - expr.arguments.length !== 1 || - expr.arguments[0].type === "SpreadElement" - ) - return; +/** + * @template T + * @template R + * @param {T|undefined} value value or not + * @param {function(T): R} fn nested handler + * @returns {R} result value + */ +const nestedConfig = (value, fn) => + value === undefined ? fn(/** @type {T} */ ({})) : fn(value); - const request = parser.evaluateExpression(expr.arguments[0]); +/** + * @template T + * @param {T|undefined} value value or not + * @returns {T} result value + */ +const cloneObject = value => { + return /** @type {T} */ ({ ...value }); +}; - if (!request.isString()) return; +/** + * @template T + * @template R + * @param {T|undefined} value value or not + * @param {function(T): R} fn nested handler + * @returns {R|undefined} result value + */ +const optionalNestedConfig = (value, fn) => + value === undefined ? undefined : fn(value); - const dep = new WebpackIsIncludedDependency( - request.string, - expr.range - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return true; - }); - parser.hooks.typeof - .for("__webpack_is_included__") - .tap( - "WebpackIsIncludedPlugin", - toConstantDependency(parser, JSON.stringify("function")) - ); +/** + * @template T + * @template R + * @param {T[]|undefined} value array or not + * @param {function(T[]): R[]} fn nested handler + * @returns {R[]|undefined} cloned value + */ +const nestedArray = (value, fn) => (Array.isArray(value) ? fn(value) : fn([])); + +/** + * @template T + * @template R + * @param {T[]|undefined} value array or not + * @param {function(T[]): R[]} fn nested handler + * @returns {R[]|undefined} cloned value + */ +const optionalNestedArray = (value, fn) => + Array.isArray(value) ? fn(value) : undefined; + +/** + * @template T + * @template R + * @param {Record|undefined} value value or not + * @param {function(T): R} fn nested handler + * @param {Record=} customKeys custom nested handler for some keys + * @returns {Record} result value + */ +const keyedNestedConfig = (value, fn, customKeys) => { + const result = + value === undefined + ? {} + : Object.keys(value).reduce( + (obj, key) => ( + (obj[key] = ( + customKeys && key in customKeys ? customKeys[key] : fn + )(value[key])), + obj + ), + /** @type {Record} */ ({}) + ); + if (customKeys) { + for (const key of Object.keys(customKeys)) { + if (!(key in result)) { + result[key] = customKeys[key](/** @type {T} */ ({})); + } + } + } + return result; +}; + +/** + * @param {WebpackOptions} config input config + * @returns {WebpackOptionsNormalized} normalized options + */ +const getNormalizedWebpackOptions = config => { + return { + amd: config.amd, + bail: config.bail, + cache: optionalNestedConfig(config.cache, cache => { + if (cache === false) return false; + if (cache === true) { + return { + type: "memory", + maxGenerations: undefined }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("WebpackIsIncludedPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("WebpackIsIncludedPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("WebpackIsIncludedPlugin", handler); } - ); + switch (cache.type) { + case "filesystem": + return { + type: "filesystem", + allowCollectingMemory: cache.allowCollectingMemory, + maxMemoryGenerations: cache.maxMemoryGenerations, + maxAge: cache.maxAge, + profile: cache.profile, + buildDependencies: cloneObject(cache.buildDependencies), + cacheDirectory: cache.cacheDirectory, + cacheLocation: cache.cacheLocation, + hashAlgorithm: cache.hashAlgorithm, + compression: cache.compression, + idleTimeout: cache.idleTimeout, + idleTimeoutForInitialStore: cache.idleTimeoutForInitialStore, + idleTimeoutAfterLargeChanges: cache.idleTimeoutAfterLargeChanges, + name: cache.name, + store: cache.store, + version: cache.version + }; + case undefined: + case "memory": + return { + type: "memory", + maxGenerations: cache.maxGenerations + }; + default: + // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339) + throw new Error(`Not implemented cache.type ${cache.type}`); + } + }), + context: config.context, + dependencies: config.dependencies, + devServer: optionalNestedConfig(config.devServer, devServer => ({ + ...devServer + })), + devtool: config.devtool, + entry: + config.entry === undefined + ? { main: {} } + : typeof config.entry === "function" + ? ( + fn => () => + Promise.resolve().then(fn).then(getNormalizedEntryStatic) + )(config.entry) + : getNormalizedEntryStatic(config.entry), + experiments: nestedConfig(config.experiments, experiments => ({ + ...experiments, + buildHttp: optionalNestedConfig(experiments.buildHttp, options => + Array.isArray(options) ? { allowedUris: options } : options + ), + lazyCompilation: optionalNestedConfig( + experiments.lazyCompilation, + options => + options === true ? {} : options === false ? undefined : options + ), + css: optionalNestedConfig(experiments.css, options => + options === true ? {} : options === false ? undefined : options + ) + })), + externals: config.externals, + externalsPresets: cloneObject(config.externalsPresets), + externalsType: config.externalsType, + ignoreWarnings: config.ignoreWarnings + ? config.ignoreWarnings.map(ignore => { + if (typeof ignore === "function") return ignore; + const i = ignore instanceof RegExp ? { message: ignore } : ignore; + return (warning, { requestShortener }) => { + if (!i.message && !i.module && !i.file) return false; + if (i.message && !i.message.test(warning.message)) { + return false; + } + if ( + i.module && + (!warning.module || + !i.module.test( + warning.module.readableIdentifier(requestShortener) + )) + ) { + return false; + } + if (i.file && (!warning.file || !i.file.test(warning.file))) { + return false; + } + return true; + }; + }) + : undefined, + infrastructureLogging: cloneObject(config.infrastructureLogging), + loader: cloneObject(config.loader), + mode: config.mode, + module: nestedConfig(config.module, module => ({ + noParse: module.noParse, + unsafeCache: module.unsafeCache, + parser: keyedNestedConfig(module.parser, cloneObject, { + javascript: parserOptions => ({ + unknownContextRequest: module.unknownContextRequest, + unknownContextRegExp: module.unknownContextRegExp, + unknownContextRecursive: module.unknownContextRecursive, + unknownContextCritical: module.unknownContextCritical, + exprContextRequest: module.exprContextRequest, + exprContextRegExp: module.exprContextRegExp, + exprContextRecursive: module.exprContextRecursive, + exprContextCritical: module.exprContextCritical, + wrappedContextRegExp: module.wrappedContextRegExp, + wrappedContextRecursive: module.wrappedContextRecursive, + wrappedContextCritical: module.wrappedContextCritical, + // TODO webpack 6 remove + strictExportPresence: module.strictExportPresence, + strictThisContextOnImports: module.strictThisContextOnImports, + ...parserOptions + }) + }), + generator: cloneObject(module.generator), + defaultRules: optionalNestedArray(module.defaultRules, r => [...r]), + rules: nestedArray(module.rules, r => [...r]) + })), + name: config.name, + node: nestedConfig( + config.node, + node => + node && { + ...node + } + ), + optimization: nestedConfig(config.optimization, optimization => { + return { + ...optimization, + runtimeChunk: getNormalizedOptimizationRuntimeChunk( + optimization.runtimeChunk + ), + splitChunks: nestedConfig( + optimization.splitChunks, + splitChunks => + splitChunks && { + ...splitChunks, + defaultSizeTypes: splitChunks.defaultSizeTypes + ? [...splitChunks.defaultSizeTypes] + : ["..."], + cacheGroups: cloneObject(splitChunks.cacheGroups) + } + ), + emitOnErrors: + optimization.noEmitOnErrors !== undefined + ? handledDeprecatedNoEmitOnErrors( + optimization.noEmitOnErrors, + optimization.emitOnErrors + ) + : optimization.emitOnErrors + }; + }), + output: nestedConfig(config.output, output => { + const { library } = output; + const libraryAsName = /** @type {LibraryName} */ (library); + const libraryBase = + typeof library === "object" && + library && + !Array.isArray(library) && + "type" in library + ? library + : libraryAsName || output.libraryTarget + ? /** @type {LibraryOptions} */ ({ + name: libraryAsName + }) + : undefined; + /** @type {OutputNormalized} */ + const result = { + assetModuleFilename: output.assetModuleFilename, + asyncChunks: output.asyncChunks, + charset: output.charset, + chunkFilename: output.chunkFilename, + chunkFormat: output.chunkFormat, + chunkLoading: output.chunkLoading, + chunkLoadingGlobal: output.chunkLoadingGlobal, + chunkLoadTimeout: output.chunkLoadTimeout, + cssFilename: output.cssFilename, + cssChunkFilename: output.cssChunkFilename, + clean: output.clean, + compareBeforeEmit: output.compareBeforeEmit, + crossOriginLoading: output.crossOriginLoading, + devtoolFallbackModuleFilenameTemplate: + output.devtoolFallbackModuleFilenameTemplate, + devtoolModuleFilenameTemplate: output.devtoolModuleFilenameTemplate, + devtoolNamespace: output.devtoolNamespace, + environment: cloneObject(output.environment), + enabledChunkLoadingTypes: output.enabledChunkLoadingTypes + ? [...output.enabledChunkLoadingTypes] + : ["..."], + enabledLibraryTypes: output.enabledLibraryTypes + ? [...output.enabledLibraryTypes] + : ["..."], + enabledWasmLoadingTypes: output.enabledWasmLoadingTypes + ? [...output.enabledWasmLoadingTypes] + : ["..."], + filename: output.filename, + globalObject: output.globalObject, + hashDigest: output.hashDigest, + hashDigestLength: output.hashDigestLength, + hashFunction: output.hashFunction, + hashSalt: output.hashSalt, + hotUpdateChunkFilename: output.hotUpdateChunkFilename, + hotUpdateGlobal: output.hotUpdateGlobal, + hotUpdateMainFilename: output.hotUpdateMainFilename, + iife: output.iife, + importFunctionName: output.importFunctionName, + importMetaName: output.importMetaName, + scriptType: output.scriptType, + library: libraryBase && { + type: + output.libraryTarget !== undefined + ? output.libraryTarget + : libraryBase.type, + auxiliaryComment: + output.auxiliaryComment !== undefined + ? output.auxiliaryComment + : libraryBase.auxiliaryComment, + export: + output.libraryExport !== undefined + ? output.libraryExport + : libraryBase.export, + name: libraryBase.name, + umdNamedDefine: + output.umdNamedDefine !== undefined + ? output.umdNamedDefine + : libraryBase.umdNamedDefine + }, + module: output.module, + path: output.path, + pathinfo: output.pathinfo, + publicPath: output.publicPath, + sourceMapFilename: output.sourceMapFilename, + sourcePrefix: output.sourcePrefix, + strictModuleExceptionHandling: output.strictModuleExceptionHandling, + trustedTypes: optionalNestedConfig( + output.trustedTypes, + trustedTypes => { + if (trustedTypes === true) return {}; + if (typeof trustedTypes === "string") + return { policyName: trustedTypes }; + return { ...trustedTypes }; + } + ), + uniqueName: output.uniqueName, + wasmLoading: output.wasmLoading, + webassemblyModuleFilename: output.webassemblyModuleFilename, + workerChunkLoading: output.workerChunkLoading, + workerWasmLoading: output.workerWasmLoading + }; + return result; + }), + parallelism: config.parallelism, + performance: optionalNestedConfig(config.performance, performance => { + if (performance === false) return false; + return { + ...performance + }; + }), + plugins: nestedArray(config.plugins, p => [...p]), + profile: config.profile, + recordsInputPath: + config.recordsInputPath !== undefined + ? config.recordsInputPath + : config.recordsPath, + recordsOutputPath: + config.recordsOutputPath !== undefined + ? config.recordsOutputPath + : config.recordsPath, + resolve: nestedConfig(config.resolve, resolve => ({ + ...resolve, + byDependency: keyedNestedConfig(resolve.byDependency, cloneObject) + })), + resolveLoader: cloneObject(config.resolveLoader), + snapshot: nestedConfig(config.snapshot, snapshot => ({ + resolveBuildDependencies: optionalNestedConfig( + snapshot.resolveBuildDependencies, + resolveBuildDependencies => ({ + timestamp: resolveBuildDependencies.timestamp, + hash: resolveBuildDependencies.hash + }) + ), + buildDependencies: optionalNestedConfig( + snapshot.buildDependencies, + buildDependencies => ({ + timestamp: buildDependencies.timestamp, + hash: buildDependencies.hash + }) + ), + resolve: optionalNestedConfig(snapshot.resolve, resolve => ({ + timestamp: resolve.timestamp, + hash: resolve.hash + })), + module: optionalNestedConfig(snapshot.module, module => ({ + timestamp: module.timestamp, + hash: module.hash + })), + immutablePaths: optionalNestedArray(snapshot.immutablePaths, p => [...p]), + managedPaths: optionalNestedArray(snapshot.managedPaths, p => [...p]) + })), + stats: nestedConfig(config.stats, stats => { + if (stats === false) { + return { + preset: "none" + }; + } + if (stats === true) { + return { + preset: "normal" + }; + } + if (typeof stats === "string") { + return { + preset: stats + }; + } + return { + ...stats + }; + }), + target: config.target, + watch: config.watch, + watchOptions: cloneObject(config.watchOptions) + }; +}; + +/** + * @param {EntryStatic} entry static entry options + * @returns {EntryStaticNormalized} normalized static entry options + */ +const getNormalizedEntryStatic = entry => { + if (typeof entry === "string") { + return { + main: { + import: [entry] + } + }; } -} + if (Array.isArray(entry)) { + return { + main: { + import: entry + } + }; + } + /** @type {EntryStaticNormalized} */ + const result = {}; + for (const key of Object.keys(entry)) { + const value = entry[key]; + if (typeof value === "string") { + result[key] = { + import: [value] + }; + } else if (Array.isArray(value)) { + result[key] = { + import: value + }; + } else { + result[key] = { + import: + value.import && + (Array.isArray(value.import) ? value.import : [value.import]), + filename: value.filename, + layer: value.layer, + runtime: value.runtime, + publicPath: value.publicPath, + chunkLoading: value.chunkLoading, + asyncChunks: value.asyncChunks, + wasmLoading: value.wasmLoading, + dependOn: + value.dependOn && + (Array.isArray(value.dependOn) ? value.dependOn : [value.dependOn]), + library: value.library + }; + } + } + return result; +}; -module.exports = WebpackIsIncludedPlugin; +/** + * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option + * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option + */ +const getNormalizedOptimizationRuntimeChunk = runtimeChunk => { + if (runtimeChunk === undefined) return undefined; + if (runtimeChunk === false) return false; + if (runtimeChunk === "single") { + return { + name: () => "runtime" + }; + } + if (runtimeChunk === true || runtimeChunk === "multiple") { + return { + name: entrypoint => `runtime~${entrypoint.name}` + }; + } + const { name } = runtimeChunk; + return { + name: typeof name === "function" ? name : () => name + }; +}; + +exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions; /***/ }), -/***/ 88422: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 52801: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -64544,1527 +65561,1159 @@ module.exports = WebpackIsIncludedPlugin; -const OptionsApply = __webpack_require__(81426); +const memoize = __webpack_require__(78676); -const AssetModulesPlugin = __webpack_require__(16109); -const JavascriptModulesPlugin = __webpack_require__(89464); -const JsonModulesPlugin = __webpack_require__(86770); +const getBrowserslistTargetHandler = memoize(() => + __webpack_require__(43950) +); -const ChunkPrefetchPreloadPlugin = __webpack_require__(33895); +/** + * @param {string} context the context directory + * @returns {string} default target + */ +const getDefaultTarget = context => { + const browsers = getBrowserslistTargetHandler().load(null, context); + return browsers ? "browserslist" : "web"; +}; -const EntryOptionPlugin = __webpack_require__(9909); -const RecordIdsPlugin = __webpack_require__(11094); +/** + * @typedef {Object} PlatformTargetProperties + * @property {boolean | null} web web platform, importing of http(s) and std: is available + * @property {boolean | null} browser browser platform, running in a normal web browser + * @property {boolean | null} webworker (Web)Worker platform, running in a web/shared/service worker + * @property {boolean | null} node node platform, require of node built-in modules is available + * @property {boolean | null} nwjs nwjs platform, require of legacy nw.gui is available + * @property {boolean | null} electron electron platform, require of some electron built-in modules is available + */ -const RuntimePlugin = __webpack_require__(2307); +/** + * @typedef {Object} ElectronContextTargetProperties + * @property {boolean | null} electronMain in main context + * @property {boolean | null} electronPreload in preload context + * @property {boolean | null} electronRenderer in renderer context with node integration + */ -const APIPlugin = __webpack_require__(74315); -const CompatibilityPlugin = __webpack_require__(94258); -const ConstPlugin = __webpack_require__(11146); -const ExportsInfoApiPlugin = __webpack_require__(7145); -const WebpackIsIncludedPlugin = __webpack_require__(97017); +/** + * @typedef {Object} ApiTargetProperties + * @property {boolean | null} require has require function available + * @property {boolean | null} nodeBuiltins has node.js built-in modules available + * @property {boolean | null} document has document available (allows script tags) + * @property {boolean | null} importScripts has importScripts available + * @property {boolean | null} importScriptsInWorker has importScripts available when creating a worker + * @property {boolean | null} fetchWasm has fetch function available for WebAssembly + * @property {boolean | null} global has global variable available + */ -const TemplatedPathPlugin = __webpack_require__(80734); -const UseStrictPlugin = __webpack_require__(36803); -const WarnCaseSensitiveModulesPlugin = __webpack_require__(56504); +/** + * @typedef {Object} EcmaTargetProperties + * @property {boolean | null} globalThis has globalThis variable available + * @property {boolean | null} bigIntLiteral big int literal syntax is available + * @property {boolean | null} const const and let variable declarations are available + * @property {boolean | null} arrowFunction arrow functions are available + * @property {boolean | null} forOf for of iteration is available + * @property {boolean | null} destructuring destructuring is available + * @property {boolean | null} dynamicImport async import() is available + * @property {boolean | null} dynamicImportInWorker async import() is available when creating a worker + * @property {boolean | null} module ESM syntax is available (when in module) + * @property {boolean | null} optionalChaining optional chaining is available + * @property {boolean | null} templateLiteral template literal is available + */ -const DataUriPlugin = __webpack_require__(64820); -const FileUriPlugin = __webpack_require__(57637); +///** @typedef {PlatformTargetProperties | ApiTargetProperties | EcmaTargetProperties | PlatformTargetProperties & ApiTargetProperties | PlatformTargetProperties & EcmaTargetProperties | ApiTargetProperties & EcmaTargetProperties} TargetProperties */ +/** @template T @typedef {{ [P in keyof T]?: never }} Never */ +/** @template A @template B @typedef {(A & Never) | (Never & B) | (A & B)} Mix */ +/** @typedef {Mix, Mix>} TargetProperties */ -const ResolverCachePlugin = __webpack_require__(97347); +const versionDependent = (major, minor) => { + if (!major) return () => /** @type {undefined} */ (undefined); + major = +major; + minor = minor ? +minor : 0; + return (vMajor, vMinor = 0) => { + return major > vMajor || (major === vMajor && minor >= vMinor); + }; +}; -const CommonJsPlugin = __webpack_require__(32406); -const HarmonyModulesPlugin = __webpack_require__(39029); -const ImportMetaPlugin = __webpack_require__(17228); -const ImportPlugin = __webpack_require__(41293); -const LoaderPlugin = __webpack_require__(24721); -const RequireContextPlugin = __webpack_require__(2928); -const RequireEnsurePlugin = __webpack_require__(8434); -const RequireIncludePlugin = __webpack_require__(37378); -const SystemPlugin = __webpack_require__(97981); -const URLPlugin = __webpack_require__(14412); -const WorkerPlugin = __webpack_require__(82509); +/** @type {[string, string, RegExp, (...args: string[]) => TargetProperties | false][]} */ +const TARGETS = [ + [ + "browserslist / browserslist:env / browserslist:query / browserslist:path-to-config / browserslist:path-to-config:env", + "Resolve features from browserslist. Will resolve browserslist config automatically. Only browser or node queries are supported (electron is not supported). Examples: 'browserslist:modern' to use 'modern' environment from browserslist config", + /^browserslist(?::(.+))?$/, + (rest, context) => { + const browserslistTargetHandler = getBrowserslistTargetHandler(); + const browsers = browserslistTargetHandler.load( + rest ? rest.trim() : null, + context + ); + if (!browsers) { + throw new Error(`No browserslist config found to handle the 'browserslist' target. +See https://github.com/browserslist/browserslist#queries for possible ways to provide a config. +The recommended way is to add a 'browserslist' key to your package.json and list supported browsers (resp. node.js versions). +You can also more options via the 'target' option: 'browserslist' / 'browserslist:env' / 'browserslist:query' / 'browserslist:path-to-config' / 'browserslist:path-to-config:env'`); + } + return browserslistTargetHandler.resolve(browsers); + } + ], + [ + "web", + "Web browser.", + /^web$/, + () => { + return { + web: true, + browser: true, + webworker: null, + node: false, + electron: false, + nwjs: false, -const InferAsyncModulesPlugin = __webpack_require__(59498); + document: true, + importScriptsInWorker: true, + fetchWasm: true, + nodeBuiltins: false, + importScripts: false, + require: false, + global: false + }; + } + ], + [ + "webworker", + "Web Worker, SharedWorker or Service Worker.", + /^webworker$/, + () => { + return { + web: true, + browser: true, + webworker: true, + node: false, + electron: false, + nwjs: false, -const JavascriptMetaInfoPlugin = __webpack_require__(52329); -const DefaultStatsFactoryPlugin = __webpack_require__(71760); -const DefaultStatsPresetPlugin = __webpack_require__(55442); -const DefaultStatsPrinterPlugin = __webpack_require__(58692); + importScripts: true, + importScriptsInWorker: true, + fetchWasm: true, + nodeBuiltins: false, + require: false, + document: false, + global: false + }; + } + ], + [ + "[async-]node[X[.Y]]", + "Node.js in version X.Y. The 'async-' prefix will load chunks asynchronously via 'fs' and 'vm' instead of 'require()'. Examples: node14.5, async-node10.", + /^(async-)?node(\d+(?:\.(\d+))?)?$/, + (asyncFlag, major, minor) => { + const v = versionDependent(major, minor); + // see https://node.green/ + return { + node: true, + electron: false, + nwjs: false, + web: false, + webworker: false, + browser: false, -const { cleverMerge } = __webpack_require__(60839); + require: !asyncFlag, + nodeBuiltins: true, + global: true, + document: false, + fetchWasm: false, + importScripts: false, + importScriptsInWorker: false, -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("./Compiler")} Compiler */ + globalThis: v(12), + const: v(6), + templateLiteral: v(4), + optionalChaining: v(14), + arrowFunction: v(6), + forOf: v(5), + destructuring: v(6), + bigIntLiteral: v(10, 4), + dynamicImport: v(12, 17), + dynamicImportInWorker: major ? false : undefined, + module: v(12, 17) + }; + } + ], + [ + "electron[X[.Y]]-main/preload/renderer", + "Electron in version X.Y. Script is running in main, preload resp. renderer context.", + /^electron(\d+(?:\.(\d+))?)?-(main|preload|renderer)$/, + (major, minor, context) => { + const v = versionDependent(major, minor); + // see https://node.green/ + https://github.com/electron/releases + return { + node: true, + electron: true, + web: context !== "main", + webworker: false, + browser: false, + nwjs: false, -class WebpackOptionsApply extends OptionsApply { - constructor() { - super(); - } + electronMain: context === "main", + electronPreload: context === "preload", + electronRenderer: context === "renderer", - /** - * @param {WebpackOptions} options options object - * @param {Compiler} compiler compiler object - * @returns {WebpackOptions} options object - */ - process(options, compiler) { - compiler.outputPath = options.output.path; - compiler.recordsInputPath = options.recordsInputPath || null; - compiler.recordsOutputPath = options.recordsOutputPath || null; - compiler.name = options.name; + global: true, + nodeBuiltins: true, + require: true, + document: context === "renderer", + fetchWasm: context === "renderer", + importScripts: false, + importScriptsInWorker: true, - if (options.externals) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ExternalsPlugin = __webpack_require__(6652); - new ExternalsPlugin(options.externalsType, options.externals).apply( - compiler - ); + globalThis: v(5), + const: v(1, 1), + templateLiteral: v(1, 1), + optionalChaining: v(8), + arrowFunction: v(1, 1), + forOf: v(0, 36), + destructuring: v(1, 1), + bigIntLiteral: v(4), + dynamicImport: v(11), + dynamicImportInWorker: major ? false : undefined, + module: v(11) + }; } + ], + [ + "nwjs[X[.Y]] / node-webkit[X[.Y]]", + "NW.js in version X.Y.", + /^(?:nwjs|node-webkit)(\d+(?:\.(\d+))?)?$/, + (major, minor) => { + const v = versionDependent(major, minor); + // see https://node.green/ + https://github.com/nwjs/nw.js/blob/nw48/CHANGELOG.md + return { + node: true, + web: true, + nwjs: true, + webworker: null, + browser: false, + electron: false, - if (options.externalsPresets.node) { - const NodeTargetPlugin = __webpack_require__(17916); - new NodeTargetPlugin().apply(compiler); - } - if (options.externalsPresets.electronMain) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ElectronTargetPlugin = __webpack_require__(32277); - new ElectronTargetPlugin("main").apply(compiler); - } - if (options.externalsPresets.electronPreload) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ElectronTargetPlugin = __webpack_require__(32277); - new ElectronTargetPlugin("preload").apply(compiler); - } - if (options.externalsPresets.electronRenderer) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ElectronTargetPlugin = __webpack_require__(32277); - new ElectronTargetPlugin("renderer").apply(compiler); + global: true, + nodeBuiltins: true, + document: false, + importScriptsInWorker: false, + fetchWasm: false, + importScripts: false, + require: false, + + globalThis: v(0, 43), + const: v(0, 15), + templateLiteral: v(0, 13), + optionalChaining: v(0, 44), + arrowFunction: v(0, 15), + forOf: v(0, 13), + destructuring: v(0, 15), + bigIntLiteral: v(0, 32), + dynamicImport: v(0, 43), + dynamicImportInWorker: major ? false : undefined, + module: v(0, 43) + }; } - if ( - options.externalsPresets.electron && - !options.externalsPresets.electronMain && - !options.externalsPresets.electronPreload && - !options.externalsPresets.electronRenderer - ) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ElectronTargetPlugin = __webpack_require__(32277); - new ElectronTargetPlugin().apply(compiler); - } - if (options.externalsPresets.nwjs) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ExternalsPlugin = __webpack_require__(6652); - new ExternalsPlugin("node-commonjs", "nw.gui").apply(compiler); - } - if (options.externalsPresets.webAsync) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ExternalsPlugin = __webpack_require__(6652); - new ExternalsPlugin( - "import", - options.experiments.css - ? ({ request, dependencyType }, callback) => { - if (dependencyType === "url") { - if (/^(\/\/|https?:\/\/)/.test(request)) - return callback(null, `asset ${request}`); - } else if (dependencyType === "css-import") { - if (/^(\/\/|https?:\/\/)/.test(request)) - return callback(null, `css-import ${request}`); - } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) { - if (/^\.css(\?|$)/.test(request)) - return callback(null, `css-import ${request}`); - return callback(null, `import ${request}`); - } - callback(); - } - : /^(\/\/|https?:\/\/|std:)/ - ).apply(compiler); - } else if (options.externalsPresets.web) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const ExternalsPlugin = __webpack_require__(6652); - new ExternalsPlugin( - "module", - options.experiments.css - ? ({ request, dependencyType }, callback) => { - if (dependencyType === "url") { - if (/^(\/\/|https?:\/\/)/.test(request)) - return callback(null, `asset ${request}`); - } else if (dependencyType === "css-import") { - if (/^(\/\/|https?:\/\/)/.test(request)) - return callback(null, `css-import ${request}`); - } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) { - if (/^\.css(\?|$)/.test(request)) - return callback(null, `css-import ${request}`); - return callback(null, `module ${request}`); - } - callback(); - } - : /^(\/\/|https?:\/\/|std:)/ - ).apply(compiler); + ], + [ + "esX", + "EcmaScript in this version. Examples: es2020, es5.", + /^es(\d+)$/, + version => { + let v = +version; + if (v < 1000) v = v + 2009; + return { + const: v >= 2015, + templateLiteral: v >= 2015, + optionalChaining: v >= 2020, + arrowFunction: v >= 2015, + forOf: v >= 2015, + destructuring: v >= 2015, + module: v >= 2015, + globalThis: v >= 2020, + bigIntLiteral: v >= 2020, + dynamicImport: v >= 2020, + dynamicImportInWorker: v >= 2020 + }; } + ] +]; - new ChunkPrefetchPreloadPlugin().apply(compiler); +/** + * @param {string} target the target + * @param {string} context the context directory + * @returns {TargetProperties} target properties + */ +const getTargetProperties = (target, context) => { + for (const [, , regExp, handler] of TARGETS) { + const match = regExp.exec(target); + if (match) { + const [, ...args] = match; + const result = handler(...args, context); + if (result) return result; + } + } + throw new Error( + `Unknown target '${target}'. The following targets are supported:\n${TARGETS.map( + ([name, description]) => `* ${name}: ${description}` + ).join("\n")}` + ); +}; - if (typeof options.output.chunkFormat === "string") { - switch (options.output.chunkFormat) { - case "array-push": { - const ArrayPushCallbackChunkFormatPlugin = __webpack_require__(18535); - new ArrayPushCallbackChunkFormatPlugin().apply(compiler); - break; - } - case "commonjs": { - const CommonJsChunkFormatPlugin = __webpack_require__(84508); - new CommonJsChunkFormatPlugin().apply(compiler); +const mergeTargetProperties = targetProperties => { + const keys = new Set(); + for (const tp of targetProperties) { + for (const key of Object.keys(tp)) { + keys.add(key); + } + } + const result = {}; + for (const key of keys) { + let hasTrue = false; + let hasFalse = false; + for (const tp of targetProperties) { + const value = tp[key]; + switch (value) { + case true: + hasTrue = true; break; - } - case "module": { - const ModuleChunkFormatPlugin = __webpack_require__(68927); - new ModuleChunkFormatPlugin().apply(compiler); + case false: + hasFalse = true; break; - } - default: - throw new Error( - "Unsupported chunk format '" + options.output.chunkFormat + "'." - ); } } + if (hasTrue || hasFalse) + result[key] = hasFalse && hasTrue ? null : hasTrue ? true : false; + } + return /** @type {TargetProperties} */ (result); +}; - if (options.output.enabledChunkLoadingTypes.length > 0) { - for (const type of options.output.enabledChunkLoadingTypes) { - const EnableChunkLoadingPlugin = __webpack_require__(61291); - new EnableChunkLoadingPlugin(type).apply(compiler); - } - } +/** + * @param {string[]} targets the targets + * @param {string} context the context directory + * @returns {TargetProperties} target properties + */ +const getTargetsProperties = (targets, context) => { + return mergeTargetProperties( + targets.map(t => getTargetProperties(t, context)) + ); +}; - if (options.output.enabledWasmLoadingTypes.length > 0) { - for (const type of options.output.enabledWasmLoadingTypes) { - const EnableWasmLoadingPlugin = __webpack_require__(78613); - new EnableWasmLoadingPlugin(type).apply(compiler); - } - } +exports.getDefaultTarget = getDefaultTarget; +exports.getTargetProperties = getTargetProperties; +exports.getTargetsProperties = getTargetsProperties; - if (options.output.enabledLibraryTypes.length > 0) { - for (const type of options.output.enabledLibraryTypes) { - const EnableLibraryPlugin = __webpack_require__(91452); - new EnableLibraryPlugin(type).apply(compiler); - } - } - if (options.output.pathinfo) { - const ModuleInfoHeaderPlugin = __webpack_require__(3454); - new ModuleInfoHeaderPlugin(options.output.pathinfo !== true).apply( - compiler - ); - } +/***/ }), - if (options.output.clean) { - const CleanPlugin = __webpack_require__(31085); - new CleanPlugin( - options.output.clean === true ? {} : options.output.clean - ).apply(compiler); - } +/***/ 64813: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (options.devtool) { - if (options.devtool.includes("source-map")) { - const hidden = options.devtool.includes("hidden"); - const inline = options.devtool.includes("inline"); - const evalWrapped = options.devtool.includes("eval"); - const cheap = options.devtool.includes("cheap"); - const moduleMaps = options.devtool.includes("module"); - const noSources = options.devtool.includes("nosources"); - const Plugin = evalWrapped - ? __webpack_require__(14790) - : __webpack_require__(63872); - new Plugin({ - filename: inline ? null : options.output.sourceMapFilename, - moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, - fallbackModuleFilenameTemplate: - options.output.devtoolFallbackModuleFilenameTemplate, - append: hidden ? false : undefined, - module: moduleMaps ? true : cheap ? false : true, - columns: cheap ? false : true, - noSources: noSources, - namespace: options.output.devtoolNamespace - }).apply(compiler); - } else if (options.devtool.includes("eval")) { - const EvalDevToolModulePlugin = __webpack_require__(65218); - new EvalDevToolModulePlugin({ - moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, - namespace: options.output.devtoolNamespace - }).apply(compiler); - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr +*/ - new JavascriptModulesPlugin().apply(compiler); - new JsonModulesPlugin().apply(compiler); - new AssetModulesPlugin().apply(compiler); - if (!options.experiments.outputModule) { - if (options.output.module) { - throw new Error( - "'output.module: true' is only allowed when 'experiments.outputModule' is enabled" - ); - } - if (options.output.enabledLibraryTypes.includes("module")) { - throw new Error( - "library type \"module\" is only allowed when 'experiments.outputModule' is enabled" - ); - } - if (options.externalsType === "module") { - throw new Error( - "'externalsType: \"module\"' is only allowed when 'experiments.outputModule' is enabled" - ); - } - } - if (options.experiments.syncWebAssembly) { - const WebAssemblyModulesPlugin = __webpack_require__(53639); - new WebAssemblyModulesPlugin({ - mangleImports: options.optimization.mangleWasmImports - }).apply(compiler); - } +const Dependency = __webpack_require__(54912); +const makeSerializable = __webpack_require__(33032); - if (options.experiments.asyncWebAssembly) { - const AsyncWebAssemblyModulesPlugin = __webpack_require__(7538); - new AsyncWebAssemblyModulesPlugin({ - mangleImports: options.optimization.mangleWasmImports - }).apply(compiler); - } +/** @typedef {import("./ContainerEntryModule").ExposeOptions} ExposeOptions */ - if (options.experiments.css) { - const CssModulesPlugin = __webpack_require__(47283); - new CssModulesPlugin(options.experiments.css).apply(compiler); - } +class ContainerEntryDependency extends Dependency { + /** + * @param {string} name entry name + * @param {[string, ExposeOptions][]} exposes list of exposed modules + * @param {string} shareScope name of the share scope + */ + constructor(name, exposes, shareScope) { + super(); + this.name = name; + this.exposes = exposes; + this.shareScope = shareScope; + } - if (options.experiments.lazyCompilation) { - const LazyCompilationPlugin = __webpack_require__(79040); - const lazyOptions = - typeof options.experiments.lazyCompilation === "object" - ? options.experiments.lazyCompilation - : null; - new LazyCompilationPlugin({ - backend: - typeof lazyOptions.backend === "function" - ? lazyOptions.backend - : __webpack_require__(17781)({ - ...lazyOptions.backend, - client: - (lazyOptions.backend && lazyOptions.backend.client) || - options.externalsPresets.node ? __webpack_require__.ab + "lazy-compilation-node.js" : __webpack_require__.ab + "lazy-compilation-web.js" - }), - entries: !lazyOptions || lazyOptions.entries !== false, - imports: !lazyOptions || lazyOptions.imports !== false, - test: (lazyOptions && lazyOptions.test) || undefined - }).apply(compiler); - } + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return `container-entry-${this.name}`; + } - if (options.experiments.buildHttp) { - const HttpUriPlugin = __webpack_require__(42110); - const httpOptions = options.experiments.buildHttp; - new HttpUriPlugin(httpOptions).apply(compiler); - } + get type() { + return "container entry"; + } - new EntryOptionPlugin().apply(compiler); - compiler.hooks.entryOption.call(options.context, options.entry); + get category() { + return "esm"; + } +} - new RuntimePlugin().apply(compiler); +makeSerializable( + ContainerEntryDependency, + "webpack/lib/container/ContainerEntryDependency" +); - new InferAsyncModulesPlugin().apply(compiler); +module.exports = ContainerEntryDependency; - new DataUriPlugin().apply(compiler); - new FileUriPlugin().apply(compiler); - new CompatibilityPlugin().apply(compiler); - new HarmonyModulesPlugin({ - topLevelAwait: options.experiments.topLevelAwait - }).apply(compiler); - if (options.amd !== false) { - const AMDPlugin = __webpack_require__(50067); - const RequireJsStuffPlugin = __webpack_require__(88846); - new AMDPlugin(options.amd || {}).apply(compiler); - new RequireJsStuffPlugin().apply(compiler); - } - new CommonJsPlugin().apply(compiler); - new LoaderPlugin({}).apply(compiler); - if (options.node !== false) { - const NodeStuffPlugin = __webpack_require__(95287); - new NodeStuffPlugin(options.node).apply(compiler); - } - new APIPlugin().apply(compiler); - new ExportsInfoApiPlugin().apply(compiler); - new WebpackIsIncludedPlugin().apply(compiler); - new ConstPlugin().apply(compiler); - new UseStrictPlugin().apply(compiler); - new RequireIncludePlugin().apply(compiler); - new RequireEnsurePlugin().apply(compiler); - new RequireContextPlugin().apply(compiler); - new ImportPlugin().apply(compiler); - new SystemPlugin().apply(compiler); - new ImportMetaPlugin().apply(compiler); - new URLPlugin().apply(compiler); - new WorkerPlugin( - options.output.workerChunkLoading, - options.output.workerWasmLoading, - options.output.module - ).apply(compiler); +/***/ }), - new DefaultStatsFactoryPlugin().apply(compiler); - new DefaultStatsPresetPlugin().apply(compiler); - new DefaultStatsPrinterPlugin().apply(compiler); +/***/ 80580: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - new JavascriptMetaInfoPlugin().apply(compiler); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr +*/ - if (typeof options.mode !== "string") { - const WarnNoModeSetPlugin = __webpack_require__(25295); - new WarnNoModeSetPlugin().apply(compiler); - } - const EnsureChunkConditionsPlugin = __webpack_require__(96260); - new EnsureChunkConditionsPlugin().apply(compiler); - if (options.optimization.removeAvailableModules) { - const RemoveParentModulesPlugin = __webpack_require__(7081); - new RemoveParentModulesPlugin().apply(compiler); - } - if (options.optimization.removeEmptyChunks) { - const RemoveEmptyChunksPlugin = __webpack_require__(84760); - new RemoveEmptyChunksPlugin().apply(compiler); - } - if (options.optimization.mergeDuplicateChunks) { - const MergeDuplicateChunksPlugin = __webpack_require__(85067); - new MergeDuplicateChunksPlugin().apply(compiler); - } - if (options.optimization.flagIncludedChunks) { - const FlagIncludedChunksPlugin = __webpack_require__(50089); - new FlagIncludedChunksPlugin().apply(compiler); - } - if (options.optimization.sideEffects) { - const SideEffectsFlagPlugin = __webpack_require__(84800); - new SideEffectsFlagPlugin( - options.optimization.sideEffects === true - ).apply(compiler); - } - if (options.optimization.providedExports) { - const FlagDependencyExportsPlugin = __webpack_require__(84506); - new FlagDependencyExportsPlugin().apply(compiler); - } - if (options.optimization.usedExports) { - const FlagDependencyUsagePlugin = __webpack_require__(58812); - new FlagDependencyUsagePlugin( - options.optimization.usedExports === "global" - ).apply(compiler); - } - if (options.optimization.innerGraph) { - const InnerGraphPlugin = __webpack_require__(28758); - new InnerGraphPlugin().apply(compiler); - } - if (options.optimization.mangleExports) { - const MangleExportsPlugin = __webpack_require__(27868); - new MangleExportsPlugin( - options.optimization.mangleExports !== "size" - ).apply(compiler); - } - if (options.optimization.concatenateModules) { - const ModuleConcatenationPlugin = __webpack_require__(74844); - new ModuleConcatenationPlugin().apply(compiler); - } - if (options.optimization.splitChunks) { - const SplitChunksPlugin = __webpack_require__(21478); - new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler); - } - if (options.optimization.runtimeChunk) { - const RuntimeChunkPlugin = __webpack_require__(2837); - new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler); - } - if (!options.optimization.emitOnErrors) { - const NoEmitOnErrorsPlugin = __webpack_require__(50169); - new NoEmitOnErrorsPlugin().apply(compiler); - } - if (options.optimization.realContentHash) { - const RealContentHashPlugin = __webpack_require__(46043); - new RealContentHashPlugin({ - hashFunction: options.output.hashFunction, - hashDigest: options.output.hashDigest - }).apply(compiler); - } - if (options.optimization.checkWasmTypes) { - const WasmFinalizeExportsPlugin = __webpack_require__(19810); - new WasmFinalizeExportsPlugin().apply(compiler); - } - const moduleIds = options.optimization.moduleIds; - if (moduleIds) { - switch (moduleIds) { - case "natural": { - const NaturalModuleIdsPlugin = __webpack_require__(83366); - new NaturalModuleIdsPlugin().apply(compiler); - break; - } - case "named": { - const NamedModuleIdsPlugin = __webpack_require__(24339); - new NamedModuleIdsPlugin().apply(compiler); - break; - } - case "hashed": { - const WarnDeprecatedOptionPlugin = __webpack_require__(76537); - const HashedModuleIdsPlugin = __webpack_require__(21825); - new WarnDeprecatedOptionPlugin( - "optimization.moduleIds", - "hashed", - "deterministic" - ).apply(compiler); - new HashedModuleIdsPlugin({ - hashFunction: options.output.hashFunction - }).apply(compiler); - break; - } - case "deterministic": { - const DeterministicModuleIdsPlugin = __webpack_require__(76692); - new DeterministicModuleIdsPlugin().apply(compiler); - break; - } - case "size": { - const OccurrenceModuleIdsPlugin = __webpack_require__(35371); - new OccurrenceModuleIdsPlugin({ - prioritiseInitial: true - }).apply(compiler); - break; - } - default: - throw new Error( - `webpack bug: moduleIds: ${moduleIds} is not implemented` - ); - } - } - const chunkIds = options.optimization.chunkIds; - if (chunkIds) { - switch (chunkIds) { - case "natural": { - const NaturalChunkIdsPlugin = __webpack_require__(86221); - new NaturalChunkIdsPlugin().apply(compiler); - break; - } - case "named": { - const NamedChunkIdsPlugin = __webpack_require__(6454); - new NamedChunkIdsPlugin().apply(compiler); - break; - } - case "deterministic": { - const DeterministicChunkIdsPlugin = __webpack_require__(8747); - new DeterministicChunkIdsPlugin().apply(compiler); - break; - } - case "size": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const OccurrenceChunkIdsPlugin = __webpack_require__(51020); - new OccurrenceChunkIdsPlugin({ - prioritiseInitial: true - }).apply(compiler); - break; - } - case "total-size": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const OccurrenceChunkIdsPlugin = __webpack_require__(51020); - new OccurrenceChunkIdsPlugin({ - prioritiseInitial: false - }).apply(compiler); - break; - } - default: - throw new Error( - `webpack bug: chunkIds: ${chunkIds} is not implemented` - ); - } - } - if (options.optimization.nodeEnv) { - const DefinePlugin = __webpack_require__(79065); - new DefinePlugin({ - "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv) - }).apply(compiler); - } - if (options.optimization.minimize) { - for (const minimizer of options.optimization.minimizer) { - if (typeof minimizer === "function") { - minimizer.call(compiler, compiler); - } else if (minimizer !== "...") { - minimizer.apply(compiler); - } + +const { OriginalSource, RawSource } = __webpack_require__(51255); +const AsyncDependenciesBlock = __webpack_require__(47736); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const StaticExportsDependency = __webpack_require__(91418); +const makeSerializable = __webpack_require__(33032); +const ContainerExposedDependency = __webpack_require__(72374); + +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */ + +/** + * @typedef {Object} ExposeOptions + * @property {string[]} import requests to exposed modules (last one is exported) + * @property {string} name custom chunk name for the exposed module + */ + +const SOURCE_TYPES = new Set(["javascript"]); + +class ContainerEntryModule extends Module { + /** + * @param {string} name container entry name + * @param {[string, ExposeOptions][]} exposes list of exposed modules + * @param {string} shareScope name of the share scope + */ + constructor(name, exposes, shareScope) { + super("javascript/dynamic", null); + this._name = name; + this._exposes = exposes; + this._shareScope = shareScope; + } + + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return SOURCE_TYPES; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `container entry (${this._shareScope}) ${JSON.stringify( + this._exposes + )}`; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `container entry`; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `${this.layer ? `(${this.layer})/` : ""}webpack/container/entry/${ + this._name + }`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + return callback(null, !this.buildMeta); + } + + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {function(WebpackError=): void} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = { + strict: true, + topLevelDeclarations: new Set(["moduleMap", "get", "init"]) + }; + this.buildMeta.exportsType = "namespace"; + + this.clearDependenciesAndBlocks(); + + for (const [name, options] of this._exposes) { + const block = new AsyncDependenciesBlock( + { + name: options.name + }, + { name }, + options.import[options.import.length - 1] + ); + let idx = 0; + for (const request of options.import) { + const dep = new ContainerExposedDependency(name, request); + dep.loc = { + name, + index: idx++ + }; + + block.addDependency(dep); } + this.addBlock(block); } + this.addDependency(new StaticExportsDependency(["get", "init"], false)); - if (options.performance) { - const SizeLimitsPlugin = __webpack_require__(32557); - new SizeLimitsPlugin(options.performance).apply(compiler); - } + callback(); + } - new TemplatedPathPlugin().apply(compiler); + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ moduleGraph, chunkGraph, runtimeTemplate }) { + const sources = new Map(); + const runtimeRequirements = new Set([ + RuntimeGlobals.definePropertyGetters, + RuntimeGlobals.hasOwnProperty, + RuntimeGlobals.exports + ]); + const getters = []; - new RecordIdsPlugin({ - portableIds: options.optimization.portableRecords - }).apply(compiler); + for (const block of this.blocks) { + const { dependencies } = block; - new WarnCaseSensitiveModulesPlugin().apply(compiler); + const modules = dependencies.map(dependency => { + const dep = /** @type {ContainerExposedDependency} */ (dependency); + return { + name: dep.exposedName, + module: moduleGraph.getModule(dep), + request: dep.userRequest + }; + }); - const AddManagedPathsPlugin = __webpack_require__(47942); - new AddManagedPathsPlugin( - options.snapshot.managedPaths, - options.snapshot.immutablePaths - ).apply(compiler); + let str; - if (options.cache && typeof options.cache === "object") { - const cacheOptions = options.cache; - switch (cacheOptions.type) { - case "memory": { - if (isFinite(cacheOptions.maxGenerations)) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const MemoryWithGcCachePlugin = __webpack_require__(99334); - new MemoryWithGcCachePlugin({ - maxGenerations: cacheOptions.maxGenerations - }).apply(compiler); - } else { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const MemoryCachePlugin = __webpack_require__(52539); - new MemoryCachePlugin().apply(compiler); - } - if (cacheOptions.cacheUnaffected) { - if (!options.experiments.cacheUnaffected) { - throw new Error( - "'cache.cacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled" - ); - } - compiler.moduleMemCaches = new Map(); - } - break; - } - case "filesystem": { - const AddBuildDependenciesPlugin = __webpack_require__(28034); - for (const key in cacheOptions.buildDependencies) { - const list = cacheOptions.buildDependencies[key]; - new AddBuildDependenciesPlugin(list).apply(compiler); - } - if (!isFinite(cacheOptions.maxMemoryGenerations)) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const MemoryCachePlugin = __webpack_require__(52539); - new MemoryCachePlugin().apply(compiler); - } else if (cacheOptions.maxMemoryGenerations !== 0) { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const MemoryWithGcCachePlugin = __webpack_require__(99334); - new MemoryWithGcCachePlugin({ - maxGenerations: cacheOptions.maxMemoryGenerations - }).apply(compiler); - } - if (cacheOptions.memoryCacheUnaffected) { - if (!options.experiments.cacheUnaffected) { - throw new Error( - "'cache.memoryCacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled" - ); - } - compiler.moduleMemCaches = new Map(); - } - switch (cacheOptions.store) { - case "pack": { - const IdleFileCachePlugin = __webpack_require__(71985); - const PackFileCacheStrategy = __webpack_require__(86180); - new IdleFileCachePlugin( - new PackFileCacheStrategy({ - compiler, - fs: compiler.intermediateFileSystem, - context: options.context, - cacheLocation: cacheOptions.cacheLocation, - version: cacheOptions.version, - logger: compiler.getInfrastructureLogger( - "webpack.cache.PackFileCacheStrategy" - ), - snapshot: options.snapshot, - maxAge: cacheOptions.maxAge, - profile: cacheOptions.profile, - allowCollectingMemory: cacheOptions.allowCollectingMemory, - compression: cacheOptions.compression - }), - cacheOptions.idleTimeout, - cacheOptions.idleTimeoutForInitialStore, - cacheOptions.idleTimeoutAfterLargeChanges - ).apply(compiler); - break; - } - default: - throw new Error("Unhandled value for cache.store"); - } - break; - } - default: - // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339) - throw new Error(`Unknown cache type ${cacheOptions.type}`); + if (modules.some(m => !m.module)) { + str = runtimeTemplate.throwMissingModuleErrorBlock({ + request: modules.map(m => m.request).join(", ") + }); + } else { + str = `return ${runtimeTemplate.blockPromise({ + block, + message: "", + chunkGraph, + runtimeRequirements + })}.then(${runtimeTemplate.returningFunction( + runtimeTemplate.returningFunction( + `(${modules + .map(({ module, request }) => + runtimeTemplate.moduleRaw({ + module, + chunkGraph, + request, + weak: false, + runtimeRequirements + }) + ) + .join(", ")})` + ) + )});`; } - } - new ResolverCachePlugin().apply(compiler); - if (options.ignoreWarnings && options.ignoreWarnings.length > 0) { - const IgnoreWarningsPlugin = __webpack_require__(41606); - new IgnoreWarningsPlugin(options.ignoreWarnings).apply(compiler); + getters.push( + `${JSON.stringify(modules[0].name)}: ${runtimeTemplate.basicFunction( + "", + str + )}` + ); } - compiler.hooks.afterPlugins.call(compiler); - if (!compiler.inputFileSystem) { - throw new Error("No input filesystem provided"); - } - compiler.resolverFactory.hooks.resolveOptions - .for("normal") - .tap("WebpackOptionsApply", resolveOptions => { - resolveOptions = cleverMerge(options.resolve, resolveOptions); - resolveOptions.fileSystem = compiler.inputFileSystem; - return resolveOptions; - }); - compiler.resolverFactory.hooks.resolveOptions - .for("context") - .tap("WebpackOptionsApply", resolveOptions => { - resolveOptions = cleverMerge(options.resolve, resolveOptions); - resolveOptions.fileSystem = compiler.inputFileSystem; - resolveOptions.resolveToContext = true; - return resolveOptions; - }); - compiler.resolverFactory.hooks.resolveOptions - .for("loader") - .tap("WebpackOptionsApply", resolveOptions => { - resolveOptions = cleverMerge(options.resolveLoader, resolveOptions); - resolveOptions.fileSystem = compiler.inputFileSystem; - return resolveOptions; - }); - compiler.hooks.afterResolvers.call(compiler); - return options; + const source = Template.asString([ + `var moduleMap = {`, + Template.indent(getters.join(",\n")), + "};", + `var get = ${runtimeTemplate.basicFunction("module, getScope", [ + `${RuntimeGlobals.currentRemoteGetScope} = getScope;`, + // reusing the getScope variable to avoid creating a new var (and module is also used later) + "getScope = (", + Template.indent([ + `${RuntimeGlobals.hasOwnProperty}(moduleMap, module)`, + Template.indent([ + "? moduleMap[module]()", + `: Promise.resolve().then(${runtimeTemplate.basicFunction( + "", + "throw new Error('Module \"' + module + '\" does not exist in container.');" + )})` + ]) + ]), + ");", + `${RuntimeGlobals.currentRemoteGetScope} = undefined;`, + "return getScope;" + ])};`, + `var init = ${runtimeTemplate.basicFunction("shareScope, initScope", [ + `if (!${RuntimeGlobals.shareScopeMap}) return;`, + `var name = ${JSON.stringify(this._shareScope)}`, + `var oldScope = ${RuntimeGlobals.shareScopeMap}[name];`, + `if(oldScope && oldScope !== shareScope) throw new Error("Container initialization failed as it has already been initialized with a different share scope");`, + `${RuntimeGlobals.shareScopeMap}[name] = shareScope;`, + `return ${RuntimeGlobals.initializeSharing}(name, initScope);` + ])};`, + "", + "// This exports getters to disallow modifications", + `${RuntimeGlobals.definePropertyGetters}(exports, {`, + Template.indent([ + `get: ${runtimeTemplate.returningFunction("get")},`, + `init: ${runtimeTemplate.returningFunction("init")}` + ]), + "});" + ]); + + sources.set( + "javascript", + this.useSourceMap || this.useSimpleSourceMap + ? new OriginalSource(source, "webpack/container-entry") + : new RawSource(source) + ); + + return { + sources, + runtimeRequirements + }; + } + + /** + * @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; + } + + serialize(context) { + const { write } = context; + write(this._name); + write(this._exposes); + write(this._shareScope); + super.serialize(context); + } + + static deserialize(context) { + const { read } = context; + const obj = new ContainerEntryModule(read(), read(), read()); + obj.deserialize(context); + return obj; } } -module.exports = WebpackOptionsApply; +makeSerializable( + ContainerEntryModule, + "webpack/lib/container/ContainerEntryModule" +); + +module.exports = ContainerEntryModule; /***/ }), -/***/ 14452: +/***/ 76398: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr */ -const { applyWebpackOptionsDefaults } = __webpack_require__(92988); -const { getNormalizedWebpackOptions } = __webpack_require__(26693); +const ModuleFactory = __webpack_require__(51010); +const ContainerEntryModule = __webpack_require__(80580); -class WebpackOptionsDefaulter { - process(options) { - options = getNormalizedWebpackOptions(options); - applyWebpackOptionsDefaults(options); - return options; - } -} +/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */ -module.exports = WebpackOptionsDefaulter; +module.exports = class ContainerEntryModuleFactory extends ModuleFactory { + /** + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * @returns {void} + */ + create({ dependencies: [dependency] }, callback) { + const dep = /** @type {ContainerEntryDependency} */ (dependency); + callback(null, { + module: new ContainerEntryModule(dep.name, dep.exposes, dep.shareScope) + }); + } +}; /***/ }), -/***/ 98421: +/***/ 72374: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr */ -const mimeTypes = __webpack_require__(78585); -const path = __webpack_require__(71017); -const { RawSource } = __webpack_require__(51255); -const Generator = __webpack_require__(93401); -const RuntimeGlobals = __webpack_require__(16475); -const createHash = __webpack_require__(49835); -const { makePathsRelative } = __webpack_require__(82186); +const ModuleDependency = __webpack_require__(80321); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").AssetGeneratorOptions} AssetGeneratorOptions */ -/** @typedef {import("../../declarations/WebpackOptions").AssetModuleOutputPath} AssetModuleOutputPath */ -/** @typedef {import("../../declarations/WebpackOptions").RawPublicPath} RawPublicPath */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../util/Hash")} Hash */ +class ContainerExposedDependency extends ModuleDependency { + /** + * @param {string} exposedName public name + * @param {string} request request to module + */ + constructor(exposedName, request) { + super(request); + this.exposedName = exposedName; + } -const mergeMaybeArrays = (a, b) => { - const set = new Set(); - if (Array.isArray(a)) for (const item of a) set.add(item); - else set.add(a); - if (Array.isArray(b)) for (const item of b) set.add(item); - else set.add(b); - return Array.from(set); -}; + get type() { + return "container exposed"; + } -const mergeAssetInfo = (a, b) => { - const result = { ...a, ...b }; - for (const key of Object.keys(a)) { - if (key in b) { - if (a[key] === b[key]) continue; - switch (key) { - case "fullhash": - case "chunkhash": - case "modulehash": - case "contenthash": - result[key] = mergeMaybeArrays(a[key], b[key]); - break; - case "immutable": - case "development": - case "hotModuleReplacement": - case "javascriptModule": - result[key] = a[key] || b[key]; - break; - case "related": - result[key] = mergeRelatedInfo(a[key], b[key]); - break; - default: - throw new Error(`Can't handle conflicting asset info for ${key}`); - } - } + get category() { + return "esm"; } - return result; -}; -const mergeRelatedInfo = (a, b) => { - const result = { ...a, ...b }; - for (const key of Object.keys(a)) { - if (key in b) { - if (a[key] === b[key]) continue; - result[key] = mergeMaybeArrays(a[key], b[key]); - } + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return `exposed dependency ${this.exposedName}=${this.request}`; } - return result; -}; - -const encodeDataUri = (encoding, source) => { - let encodedContent; - - switch (encoding) { - case "base64": { - encodedContent = source.buffer().toString("base64"); - break; - } - case false: { - const content = source.source(); - if (typeof content !== "string") { - encodedContent = content.toString("utf-8"); - } + serialize(context) { + context.write(this.exposedName); + super.serialize(context); + } - encodedContent = encodeURIComponent(encodedContent).replace( - /[!'()*]/g, - character => "%" + character.codePointAt(0).toString(16) - ); - break; - } - default: - throw new Error(`Unsupported encoding '${encoding}'`); + deserialize(context) { + this.exposedName = context.read(); + super.deserialize(context); } +} - return encodedContent; -}; +makeSerializable( + ContainerExposedDependency, + "webpack/lib/container/ContainerExposedDependency" +); -const decodeDataUriContent = (encoding, content) => { - const isBase64 = encoding === "base64"; - return isBase64 - ? Buffer.from(content, "base64") - : Buffer.from(decodeURIComponent(content), "ascii"); -}; +module.exports = ContainerExposedDependency; -const JS_TYPES = new Set(["javascript"]); -const JS_AND_ASSET_TYPES = new Set(["javascript", "asset"]); -class AssetGenerator extends Generator { - /** - * @param {AssetGeneratorOptions["dataUrl"]=} dataUrlOptions the options for the data url - * @param {string=} filename override for output.assetModuleFilename - * @param {RawPublicPath=} publicPath override for output.assetModulePublicPath - * @param {AssetModuleOutputPath=} outputPath the output path for the emitted file which is not included in the runtime import - * @param {boolean=} emit generate output asset - */ - constructor(dataUrlOptions, filename, publicPath, outputPath, emit) { - super(); - this.dataUrlOptions = dataUrlOptions; - this.filename = filename; - this.publicPath = publicPath; - this.outputPath = outputPath; - this.emit = emit; - } +/***/ }), - /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code - */ - generate( - module, - { runtime, chunkGraph, runtimeTemplate, runtimeRequirements, type, getData } - ) { - switch (type) { - case "asset": - return module.originalSource(); - default: { - runtimeRequirements.add(RuntimeGlobals.module); +/***/ 9244: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const originalSource = module.originalSource(); - if (module.buildInfo.dataUrl) { - let encodedSource; - if (typeof this.dataUrlOptions === "function") { - encodedSource = this.dataUrlOptions.call( - null, - originalSource.source(), - { - filename: module.matchResource || module.resource, - module - } - ); - } else { - /** @type {string | false | undefined} */ - let encoding = this.dataUrlOptions.encoding; - if (encoding === undefined) { - if ( - module.resourceResolveData && - module.resourceResolveData.encoding !== undefined - ) { - encoding = module.resourceResolveData.encoding; - } - } - if (encoding === undefined) { - encoding = "base64"; - } - let ext; - let mimeType = this.dataUrlOptions.mimetype; - if (mimeType === undefined) { - ext = path.extname(module.nameForCondition()); - if ( - module.resourceResolveData && - module.resourceResolveData.mimetype !== undefined - ) { - mimeType = - module.resourceResolveData.mimetype + - module.resourceResolveData.parameters; - } else if (ext) { - mimeType = mimeTypes.lookup(ext); - } - } - if (typeof mimeType !== "string") { - throw new Error( - "DataUrl can't be generated automatically, " + - `because there is no mimetype for "${ext}" in mimetype database. ` + - 'Either pass a mimetype via "generator.mimetype" or ' + - 'use type: "asset/resource" to create a resource file instead of a DataUrl' - ); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr +*/ - let encodedContent; - if ( - module.resourceResolveData && - module.resourceResolveData.encoding === encoding && - decodeDataUriContent( - module.resourceResolveData.encoding, - module.resourceResolveData.encodedContent - ).equals(originalSource.buffer()) - ) { - encodedContent = module.resourceResolveData.encodedContent; - } else { - encodedContent = encodeDataUri(encoding, originalSource); - } - encodedSource = `data:${mimeType}${ - encoding ? `;${encoding}` : "" - },${encodedContent}`; - } - const data = getData(); - data.set("url", Buffer.from(encodedSource)); - return new RawSource( - `${RuntimeGlobals.module}.exports = ${JSON.stringify( - encodedSource - )};` - ); - } else { - const assetModuleFilename = - this.filename || runtimeTemplate.outputOptions.assetModuleFilename; - const hash = createHash(runtimeTemplate.outputOptions.hashFunction); - if (runtimeTemplate.outputOptions.hashSalt) { - hash.update(runtimeTemplate.outputOptions.hashSalt); - } - hash.update(originalSource.buffer()); - const fullHash = /** @type {string} */ ( - hash.digest(runtimeTemplate.outputOptions.hashDigest) - ); - const contentHash = fullHash.slice( - 0, - runtimeTemplate.outputOptions.hashDigestLength - ); - module.buildInfo.fullContentHash = fullHash; - const sourceFilename = makePathsRelative( - runtimeTemplate.compilation.compiler.context, - module.matchResource || module.resource, - runtimeTemplate.compilation.compiler.root - ).replace(/^\.\//, ""); - let { path: filename, info: assetInfo } = - runtimeTemplate.compilation.getAssetPathWithInfo( - assetModuleFilename, - { - module, - runtime, - filename: sourceFilename, - chunkGraph, - contentHash - } - ); - let assetPath; - if (this.publicPath !== undefined) { - const { path, info } = - runtimeTemplate.compilation.getAssetPathWithInfo( - this.publicPath, - { - module, - runtime, - filename: sourceFilename, - chunkGraph, - contentHash - } - ); - assetInfo = mergeAssetInfo(assetInfo, info); - assetPath = JSON.stringify(path + filename); - } else { - runtimeRequirements.add(RuntimeGlobals.publicPath); // add __webpack_require__.p - assetPath = runtimeTemplate.concatenation( - { expr: RuntimeGlobals.publicPath }, - filename - ); - } - assetInfo = { - sourceFilename, - ...assetInfo - }; - if (this.outputPath) { - const { path: outputPath, info } = - runtimeTemplate.compilation.getAssetPathWithInfo( - this.outputPath, - { - module, - runtime, - filename: sourceFilename, - chunkGraph, - contentHash - } - ); - assetInfo = mergeAssetInfo(assetInfo, info); - filename = path.posix.join(outputPath, filename); - } - module.buildInfo.filename = filename; - module.buildInfo.assetInfo = assetInfo; - if (getData) { - // Due to code generation caching module.buildInfo.XXX can't used to store such information - // It need to be stored in the code generation results instead, where it's cached too - // TODO webpack 6 For back-compat reasons we also store in on module.buildInfo - const data = getData(); - data.set("fullContentHash", fullHash); - data.set("filename", filename); - data.set("assetInfo", assetInfo); - } +const createSchemaValidation = __webpack_require__(32540); +const ContainerEntryDependency = __webpack_require__(64813); +const ContainerEntryModuleFactory = __webpack_require__(76398); +const ContainerExposedDependency = __webpack_require__(72374); +const { parseOptions } = __webpack_require__(3083); - return new RawSource( - `${RuntimeGlobals.module}.exports = ${assetPath};` - ); - } - } - } +/** @typedef {import("../../declarations/plugins/container/ContainerPlugin").ContainerPluginOptions} ContainerPluginOptions */ +/** @typedef {import("../Compiler")} Compiler */ + +const validate = createSchemaValidation( + __webpack_require__(9504), + () => __webpack_require__(84899), + { + name: "Container Plugin", + baseDataPath: "options" } +); +const PLUGIN_NAME = "ContainerPlugin"; + +class ContainerPlugin { /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) + * @param {ContainerPluginOptions} options options */ - getTypes(module) { - if ((module.buildInfo && module.buildInfo.dataUrl) || this.emit === false) { - return JS_TYPES; - } else { - return JS_AND_ASSET_TYPES; - } + constructor(options) { + validate(options); + + this._options = { + name: options.name, + shareScope: options.shareScope || "default", + library: options.library || { + type: "var", + name: options.name + }, + runtime: options.runtime, + filename: options.filename || undefined, + exposes: parseOptions( + options.exposes, + item => ({ + import: Array.isArray(item) ? item : [item], + name: undefined + }), + item => ({ + import: Array.isArray(item.import) ? item.import : [item.import], + name: item.name || undefined + }) + ) + }; } /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - getSize(module, type) { - switch (type) { - case "asset": { - const originalSource = module.originalSource(); - - if (!originalSource) { - return 0; - } - - return originalSource.size(); - } - default: - if (module.buildInfo && module.buildInfo.dataUrl) { - const originalSource = module.originalSource(); + apply(compiler) { + const { name, exposes, shareScope, filename, library, runtime } = + this._options; - if (!originalSource) { - return 0; - } + compiler.options.output.enabledLibraryTypes.push(library.type); - // roughly for data url - // Example: m.exports="data:image/png;base64,ag82/f+2==" - // 4/3 = base64 encoding - // 34 = ~ data url header + footer + rounding - return originalSource.size() * 1.34 + 36; - } else { - // it's only estimated so this number is probably fine - // Example: m.exports=r.p+"0123456789012345678901.ext" - return 42; + compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => { + const dep = new ContainerEntryDependency(name, exposes, shareScope); + dep.loc = { name }; + compilation.addEntry( + compilation.options.context, + dep, + { + name, + filename, + runtime, + library + }, + error => { + if (error) return callback(error); + callback(); } - } - } + ); + }); - /** - * @param {Hash} hash hash that will be modified - * @param {UpdateHashContext} updateHashContext context for updating hash - */ - updateHash(hash, { module }) { - hash.update(module.buildInfo.dataUrl ? "data-url" : "resource"); + compiler.hooks.thisCompilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + ContainerEntryDependency, + new ContainerEntryModuleFactory() + ); + + compilation.dependencyFactories.set( + ContainerExposedDependency, + normalModuleFactory + ); + } + ); } } -module.exports = AssetGenerator; +module.exports = ContainerPlugin; /***/ }), -/***/ 16109: +/***/ 95757: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Yuta Hiroto @hiroppy + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ -const { cleverMerge } = __webpack_require__(60839); -const { compareModulesByIdentifier } = __webpack_require__(29579); +const ExternalsPlugin = __webpack_require__(6652); +const RuntimeGlobals = __webpack_require__(16475); const createSchemaValidation = __webpack_require__(32540); -const memoize = __webpack_require__(78676); +const FallbackDependency = __webpack_require__(57764); +const FallbackItemDependency = __webpack_require__(29593); +const FallbackModuleFactory = __webpack_require__(4112); +const RemoteModule = __webpack_require__(62916); +const RemoteRuntimeModule = __webpack_require__(88288); +const RemoteToExternalDependency = __webpack_require__(14389); +const { parseOptions } = __webpack_require__(3083); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../../declarations/plugins/container/ContainerReferencePlugin").ContainerReferencePluginOptions} ContainerReferencePluginOptions */ +/** @typedef {import("../../declarations/plugins/container/ContainerReferencePlugin").RemotesConfig} RemotesConfig */ /** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ - -const getSchema = name => { - const { definitions } = __webpack_require__(73342); - return { - definitions, - oneOf: [{ $ref: `#/definitions/${name}` }] - }; -}; - -const generatorValidationOptions = { - name: "Asset Modules Plugin", - baseDataPath: "generator" -}; -const validateGeneratorOptions = { - asset: createSchemaValidation( - __webpack_require__(55125), - () => getSchema("AssetGeneratorOptions"), - generatorValidationOptions - ), - "asset/resource": createSchemaValidation( - __webpack_require__(4405), - () => getSchema("AssetResourceGeneratorOptions"), - generatorValidationOptions - ), - "asset/inline": createSchemaValidation( - __webpack_require__(62368), - () => getSchema("AssetInlineGeneratorOptions"), - generatorValidationOptions - ) -}; -const validateParserOptions = createSchemaValidation( - __webpack_require__(45020), - () => getSchema("AssetParserOptions"), +const validate = createSchemaValidation( + __webpack_require__(95122), + () => + __webpack_require__(66681), { - name: "Asset Modules Plugin", - baseDataPath: "parser" + name: "Container Reference Plugin", + baseDataPath: "options" } ); -const getAssetGenerator = memoize(() => __webpack_require__(98421)); -const getAssetParser = memoize(() => __webpack_require__(91112)); -const getAssetSourceParser = memoize(() => __webpack_require__(30953)); -const getAssetSourceGenerator = memoize(() => - __webpack_require__(18749) -); +const slashCode = "/".charCodeAt(0); -const type = "asset"; -const plugin = "AssetModulesPlugin"; +class ContainerReferencePlugin { + /** + * @param {ContainerReferencePluginOptions} options options + */ + constructor(options) { + validate(options); + + this._remoteType = options.remoteType; + this._remotes = parseOptions( + options.remotes, + item => ({ + external: Array.isArray(item) ? item : [item], + shareScope: options.shareScope || "default" + }), + item => ({ + external: Array.isArray(item.external) + ? item.external + : [item.external], + shareScope: item.shareScope || options.shareScope || "default" + }) + ); + } -class AssetModulesPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap( - plugin, - (compilation, { normalModuleFactory }) => { - normalModuleFactory.hooks.createParser - .for("asset") - .tap(plugin, parserOptions => { - validateParserOptions(parserOptions); - parserOptions = cleverMerge( - compiler.options.module.parser.asset, - parserOptions - ); - - let dataUrlCondition = parserOptions.dataUrlCondition; - if (!dataUrlCondition || typeof dataUrlCondition === "object") { - dataUrlCondition = { - maxSize: 8096, - ...dataUrlCondition - }; - } - - const AssetParser = getAssetParser(); + const { _remotes: remotes, _remoteType: remoteType } = this; - return new AssetParser(dataUrlCondition); - }); - normalModuleFactory.hooks.createParser - .for("asset/inline") - .tap(plugin, parserOptions => { - const AssetParser = getAssetParser(); + /** @type {Record} */ + const remoteExternals = {}; + for (const [key, config] of remotes) { + let i = 0; + for (const external of config.external) { + if (external.startsWith("internal ")) continue; + remoteExternals[ + `webpack/container/reference/${key}${i ? `/fallback-${i}` : ""}` + ] = external; + i++; + } + } - return new AssetParser(true); - }); - normalModuleFactory.hooks.createParser - .for("asset/resource") - .tap(plugin, parserOptions => { - const AssetParser = getAssetParser(); + new ExternalsPlugin(remoteType, remoteExternals).apply(compiler); - return new AssetParser(false); - }); - normalModuleFactory.hooks.createParser - .for("asset/source") - .tap(plugin, parserOptions => { - const AssetSourceParser = getAssetSourceParser(); + compiler.hooks.compilation.tap( + "ContainerReferencePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RemoteToExternalDependency, + normalModuleFactory + ); - return new AssetSourceParser(); - }); + compilation.dependencyFactories.set( + FallbackItemDependency, + normalModuleFactory + ); - for (const type of ["asset", "asset/inline", "asset/resource"]) { - normalModuleFactory.hooks.createGenerator - .for(type) - .tap(plugin, generatorOptions => { - validateGeneratorOptions[type](generatorOptions); + compilation.dependencyFactories.set( + FallbackDependency, + new FallbackModuleFactory() + ); - let dataUrl = undefined; - if (type !== "asset/resource") { - dataUrl = generatorOptions.dataUrl; - if (!dataUrl || typeof dataUrl === "object") { - dataUrl = { - encoding: undefined, - mimetype: undefined, - ...dataUrl - }; + normalModuleFactory.hooks.factorize.tap( + "ContainerReferencePlugin", + data => { + if (!data.request.includes("!")) { + for (const [key, config] of remotes) { + if ( + data.request.startsWith(`${key}`) && + (data.request.length === key.length || + data.request.charCodeAt(key.length) === slashCode) + ) { + return new RemoteModule( + data.request, + config.external.map((external, i) => + external.startsWith("internal ") + ? external.slice(9) + : `webpack/container/reference/${key}${ + i ? `/fallback-${i}` : "" + }` + ), + `.${data.request.slice(key.length)}`, + config.shareScope + ); } } - - let filename = undefined; - let publicPath = undefined; - let outputPath = undefined; - if (type !== "asset/inline") { - filename = generatorOptions.filename; - publicPath = generatorOptions.publicPath; - outputPath = generatorOptions.outputPath; - } - - const AssetGenerator = getAssetGenerator(); - - return new AssetGenerator( - dataUrl, - filename, - publicPath, - outputPath, - generatorOptions.emit !== false - ); - }); - } - normalModuleFactory.hooks.createGenerator - .for("asset/source") - .tap(plugin, () => { - const AssetSourceGenerator = getAssetSourceGenerator(); - - return new AssetSourceGenerator(); - }); - - compilation.hooks.renderManifest.tap(plugin, (result, options) => { - const { chunkGraph } = compilation; - const { chunk, codeGenerationResults } = options; - - const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( - chunk, - "asset", - compareModulesByIdentifier - ); - if (modules) { - for (const module of modules) { - try { - const codeGenResult = codeGenerationResults.get( - module, - chunk.runtime - ); - result.push({ - render: () => codeGenResult.sources.get(type), - filename: - module.buildInfo.filename || - codeGenResult.data.get("filename"), - info: - module.buildInfo.assetInfo || - codeGenResult.data.get("assetInfo"), - auxiliary: true, - identifier: `assetModule${chunkGraph.getModuleId(module)}`, - hash: - module.buildInfo.fullContentHash || - codeGenResult.data.get("fullContentHash") - }); - } catch (e) { - e.message += `\nduring rendering of asset ${module.identifier()}`; - throw e; - } } } - - return result; - }); - - compilation.hooks.prepareModuleExecution.tap( - "AssetModulesPlugin", - (options, context) => { - const { codeGenerationResult } = options; - const source = codeGenerationResult.sources.get("asset"); - if (source === undefined) return; - context.assets.set(codeGenerationResult.data.get("filename"), { - source, - info: codeGenerationResult.data.get("assetInfo") - }); - } ); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("ContainerReferencePlugin", (chunk, set) => { + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + set.add(RuntimeGlobals.initializeSharing); + set.add(RuntimeGlobals.shareScopeMap); + compilation.addRuntimeModule(chunk, new RemoteRuntimeModule()); + }); } ); } } -module.exports = AssetModulesPlugin; +module.exports = ContainerReferencePlugin; /***/ }), -/***/ 91112: +/***/ 57764: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Yuta Hiroto @hiroppy + Author Tobias Koppers @sokra */ -const Parser = __webpack_require__(11715); - -/** @typedef {import("../../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */ -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ +const Dependency = __webpack_require__(54912); +const makeSerializable = __webpack_require__(33032); -class AssetParser extends Parser { - /** - * @param {AssetParserOptions["dataUrlCondition"] | boolean} dataUrlCondition condition for inlining as DataUrl - */ - constructor(dataUrlCondition) { +class FallbackDependency extends Dependency { + constructor(requests) { super(); - this.dataUrlCondition = dataUrlCondition; + this.requests = requests; } /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state + * @returns {string | null} an identifier to merge equal requests */ - parse(source, state) { - if (typeof source === "object" && !Buffer.isBuffer(source)) { - throw new Error("AssetParser doesn't accept preparsed AST"); - } - state.module.buildInfo.strict = true; - state.module.buildMeta.exportsType = "default"; - - if (typeof this.dataUrlCondition === "function") { - state.module.buildInfo.dataUrl = this.dataUrlCondition(source, { - filename: state.module.matchResource || state.module.resource, - module: state.module - }); - } else if (typeof this.dataUrlCondition === "boolean") { - state.module.buildInfo.dataUrl = this.dataUrlCondition; - } else if ( - this.dataUrlCondition && - typeof this.dataUrlCondition === "object" - ) { - state.module.buildInfo.dataUrl = - Buffer.byteLength(source) <= this.dataUrlCondition.maxSize; - } else { - throw new Error("Unexpected dataUrlCondition type"); - } - - return state; + getResourceIdentifier() { + return `fallback ${this.requests.join(" ")}`; } -} - -module.exports = AssetParser; - - -/***/ }), - -/***/ 18749: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov -*/ - - - -const { RawSource } = __webpack_require__(51255); -const Generator = __webpack_require__(93401); -const RuntimeGlobals = __webpack_require__(16475); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../NormalModule")} NormalModule */ - -const TYPES = new Set(["javascript"]); - -class AssetSourceGenerator extends Generator { - /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code - */ - generate(module, { chunkGraph, runtimeTemplate, runtimeRequirements }) { - runtimeRequirements.add(RuntimeGlobals.module); - - const originalSource = module.originalSource(); - - if (!originalSource) { - return new RawSource(""); - } - - const content = originalSource.source(); - let encodedSource; - if (typeof content === "string") { - encodedSource = content; - } else { - encodedSource = content.toString("utf-8"); - } - return new RawSource( - `${RuntimeGlobals.module}.exports = ${JSON.stringify(encodedSource)};` - ); + get type() { + return "fallback"; } - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; + get category() { + return "esm"; } - /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module - */ - getSize(module, type) { - const originalSource = module.originalSource(); - - if (!originalSource) { - return 0; - } + serialize(context) { + const { write } = context; + write(this.requests); + super.serialize(context); + } - // Example: m.exports="abcd" - return originalSource.size() + 12; + static deserialize(context) { + const { read } = context; + const obj = new FallbackDependency(read()); + obj.deserialize(context); + return obj; } } -module.exports = AssetSourceGenerator; +makeSerializable( + FallbackDependency, + "webpack/lib/container/FallbackDependency" +); + +module.exports = FallbackDependency; /***/ }), -/***/ 30953: +/***/ 29593: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Yuta Hiroto @hiroppy + Author Tobias Koppers @sokra */ -const Parser = __webpack_require__(11715); +const ModuleDependency = __webpack_require__(80321); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ +class FallbackItemDependency extends ModuleDependency { + constructor(request) { + super(request); + } -class AssetSourceParser extends Parser { - /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state - */ - parse(source, state) { - if (typeof source === "object" && !Buffer.isBuffer(source)) { - throw new Error("AssetSourceParser doesn't accept preparsed AST"); - } - const { module } = state; - module.buildInfo.strict = true; - module.buildMeta.exportsType = "default"; + get type() { + return "fallback item"; + } - return state; + get category() { + return "esm"; } } -module.exports = AssetSourceParser; +makeSerializable( + FallbackItemDependency, + "webpack/lib/container/FallbackItemDependency" +); + +module.exports = FallbackItemDependency; /***/ }), -/***/ 19684: +/***/ 82886: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ @@ -66072,13 +66721,18 @@ module.exports = AssetSourceParser; const { RawSource } = __webpack_require__(51255); const Module = __webpack_require__(73208); const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); const makeSerializable = __webpack_require__(33032); +const FallbackItemDependency = __webpack_require__(29593); /** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ /** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ /** @typedef {import("../RequestShortener")} RequestShortener */ /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ @@ -66087,50 +66741,50 @@ const makeSerializable = __webpack_require__(33032); /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ const TYPES = new Set(["javascript"]); +const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); -class RawDataUrlModule extends Module { +class FallbackModule extends Module { /** - * @param {string} url raw url - * @param {string} identifier unique identifier - * @param {string=} readableIdentifier readable identifier + * @param {string[]} requests list of requests to choose one */ - constructor(url, identifier, readableIdentifier) { - super("asset/raw-data-url", null); - this.url = url; - this.urlBuffer = url ? Buffer.from(url) : undefined; - this.identifierStr = identifier || this.url; - this.readableIdentifierStr = readableIdentifier || this.identifierStr; + constructor(requests) { + super("fallback-module"); + this.requests = requests; + this._identifier = `fallback ${this.requests.join(" ")}`; } /** - * @returns {Set} types available (do not mutate) + * @returns {string} a unique identifier of the module */ - getSourceTypes() { - return TYPES; + identifier() { + return this._identifier; } /** - * @returns {string} a unique identifier of the module + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module */ - identifier() { - return this.identifierStr; + readableIdentifier(requestShortener) { + return this._identifier; } /** - * @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) + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion */ - size(type) { - if (this.url === undefined) this.url = this.urlBuffer.toString(); - return Math.max(1, this.url.length); + libIdent(options) { + return `${this.layer ? `(${this.layer})/` : ""}webpack/container/fallback/${ + this.requests[0] + }/and ${this.requests.length - 1} more`; } /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module + * @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 */ - readableIdentifier(requestShortener) { - return requestShortener.shorten(this.readableIdentifierStr); + chunkCondition(chunk, { chunkGraph }) { + return chunkGraph.getNumberOfEntryModules(chunk) > 0; } /** @@ -66139,7 +66793,7 @@ class RawDataUrlModule extends Module { * @returns {void} */ needBuild(context, callback) { - return callback(null, !this.buildMeta); + callback(null, !this.buildInfo); } /** @@ -66153,208 +66807,402 @@ class RawDataUrlModule extends Module { build(options, compilation, resolver, fs, callback) { this.buildMeta = {}; this.buildInfo = { - cacheable: true + strict: true }; + + this.clearDependenciesAndBlocks(); + for (const request of this.requests) + this.addDependency(new FallbackItemDependency(request)); + callback(); } /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result + * @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) */ - codeGeneration(context) { - if (this.url === undefined) this.url = this.urlBuffer.toString(); - const sources = new Map(); - sources.set( - "javascript", - new RawSource(`module.exports = ${JSON.stringify(this.url)};`) - ); - const data = new Map(); - data.set("url", this.urlBuffer); - const runtimeRequirements = new Set(); - runtimeRequirements.add(RuntimeGlobals.module); - return { sources, runtimeRequirements, data }; + size(type) { + return this.requests.length * 5 + 42; } /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} + * @returns {Set} types available (do not mutate) */ - updateHash(hash, context) { - hash.update(this.urlBuffer); - super.updateHash(hash, context); + getSourceTypes() { + return TYPES; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { + const ids = this.dependencies.map(dep => + chunkGraph.getModuleId(moduleGraph.getModule(dep)) + ); + const code = Template.asString([ + `var ids = ${JSON.stringify(ids)};`, + "var error, result, i = 0;", + `var loop = ${runtimeTemplate.basicFunction("next", [ + "while(i < ids.length) {", + Template.indent([ + "try { next = __webpack_require__(ids[i++]); } catch(e) { return handleError(e); }", + "if(next) return next.then ? next.then(handleResult, handleError) : handleResult(next);" + ]), + "}", + "if(error) throw error;" + ])}`, + `var handleResult = ${runtimeTemplate.basicFunction("result", [ + "if(result) return result;", + "return loop();" + ])};`, + `var handleError = ${runtimeTemplate.basicFunction("e", [ + "error = e;", + "return loop();" + ])};`, + "module.exports = loop();" + ]); + const sources = new Map(); + sources.set("javascript", new RawSource(code)); + return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS }; } serialize(context) { const { write } = context; - - write(this.urlBuffer); - write(this.identifierStr); - write(this.readableIdentifierStr); - + write(this.requests); super.serialize(context); } - deserialize(context) { + static deserialize(context) { const { read } = context; - - this.urlBuffer = read(); - this.identifierStr = read(); - this.readableIdentifierStr = read(); - - super.deserialize(context); + const obj = new FallbackModule(read()); + obj.deserialize(context); + return obj; } } -makeSerializable(RawDataUrlModule, "webpack/lib/asset/RawDataUrlModule"); +makeSerializable(FallbackModule, "webpack/lib/container/FallbackModule"); -module.exports = RawDataUrlModule; +module.exports = FallbackModule; /***/ }), -/***/ 41153: +/***/ 4112: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr */ -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); +const ModuleFactory = __webpack_require__(51010); +const FallbackModule = __webpack_require__(82886); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./FallbackDependency")} FallbackDependency */ -/** - * @typedef {GenerateContext} Context - */ -class AwaitDependenciesInitFragment extends InitFragment { +module.exports = class FallbackModuleFactory extends ModuleFactory { /** - * @param {Set} promises the promises that should be awaited + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * @returns {void} */ - constructor(promises) { - super( - undefined, - InitFragment.STAGE_ASYNC_DEPENDENCIES, - 0, - "await-dependencies" - ); - this.promises = promises; + create({ dependencies: [dependency] }, callback) { + const dep = /** @type {FallbackDependency} */ (dependency); + callback(null, { + module: new FallbackModule(dep.requests) + }); } +}; - merge(other) { - const promises = new Set(this.promises); - for (const p of other.promises) { - promises.add(p); - } - return new AwaitDependenciesInitFragment(promises); + +/***/ }), + +/***/ 30569: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy +*/ + + + +const isValidExternalsType = __webpack_require__(62142); +const SharePlugin = __webpack_require__(26335); +const createSchemaValidation = __webpack_require__(32540); +const ContainerPlugin = __webpack_require__(9244); +const ContainerReferencePlugin = __webpack_require__(95757); + +/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ExternalsType} ExternalsType */ +/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ModuleFederationPluginOptions} ModuleFederationPluginOptions */ +/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").Shared} Shared */ +/** @typedef {import("../Compiler")} Compiler */ + +const validate = createSchemaValidation( + __webpack_require__(7467), + () => __webpack_require__(82601), + { + name: "Module Federation Plugin", + baseDataPath: "options" + } +); +class ModuleFederationPlugin { + /** + * @param {ModuleFederationPluginOptions} options options + */ + constructor(options) { + validate(options); + + this._options = options; } /** - * @param {Context} context context - * @returns {string|Source} the source code that will be included as initialization code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - getContent({ runtimeRequirements }) { - runtimeRequirements.add(RuntimeGlobals.module); - const promises = this.promises; - if (promises.size === 0) { - return ""; + apply(compiler) { + const { _options: options } = this; + const library = options.library || { type: "var", name: options.name }; + const remoteType = + options.remoteType || + (options.library && isValidExternalsType(options.library.type) + ? /** @type {ExternalsType} */ (options.library.type) + : "script"); + if ( + library && + !compiler.options.output.enabledLibraryTypes.includes(library.type) + ) { + compiler.options.output.enabledLibraryTypes.push(library.type); } - if (promises.size === 1) { - for (const p of promises) { - return Template.asString([ - `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${p}]);`, - `${p} = (__webpack_async_dependencies__.then ? await __webpack_async_dependencies__ : __webpack_async_dependencies__)[0];`, - "" - ]); + compiler.hooks.afterPlugins.tap("ModuleFederationPlugin", () => { + if ( + options.exposes && + (Array.isArray(options.exposes) + ? options.exposes.length > 0 + : Object.keys(options.exposes).length > 0) + ) { + new ContainerPlugin({ + name: options.name, + library, + filename: options.filename, + runtime: options.runtime, + exposes: options.exposes + }).apply(compiler); } - } - const sepPromises = Array.from(promises).join(", "); - // TODO check if destructuring is supported - return Template.asString([ - `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${sepPromises}]);`, - `([${sepPromises}] = __webpack_async_dependencies__.then ? await __webpack_async_dependencies__ : __webpack_async_dependencies__);`, - "" - ]); + if ( + options.remotes && + (Array.isArray(options.remotes) + ? options.remotes.length > 0 + : Object.keys(options.remotes).length > 0) + ) { + new ContainerReferencePlugin({ + remoteType, + remotes: options.remotes + }).apply(compiler); + } + if (options.shared) { + new SharePlugin({ + shared: options.shared, + shareScope: options.shareScope + }).apply(compiler); + } + }); } } -module.exports = AwaitDependenciesInitFragment; +module.exports = ModuleFederationPlugin; /***/ }), -/***/ 59498: +/***/ 62916: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ -const HarmonyImportDependency = __webpack_require__(57154); +const { RawSource } = __webpack_require__(51255); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const FallbackDependency = __webpack_require__(57764); +const RemoteToExternalDependency = __webpack_require__(14389); -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ -class InferAsyncModulesPlugin { +const TYPES = new Set(["remote", "share-init"]); +const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); + +class RemoteModule extends Module { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {string} request request string + * @param {string[]} externalRequests list of external requests to containers + * @param {string} internalRequest name of exposed module in container + * @param {string} shareScope the used share scope name + */ + constructor(request, externalRequests, internalRequest, shareScope) { + super("remote-module"); + this.request = request; + this.externalRequests = externalRequests; + this.internalRequest = internalRequest; + this.shareScope = shareScope; + this._identifier = `remote (${shareScope}) ${this.externalRequests.join( + " " + )} ${this.internalRequest}`; + } + + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this._identifier; + } + + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `remote ${this.request}`; + } + + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `${this.layer ? `(${this.layer})/` : ""}webpack/container/remote/${ + this.request + }`; + } + + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild * @returns {void} */ - apply(compiler) { - compiler.hooks.compilation.tap("InferAsyncModulesPlugin", compilation => { - const { moduleGraph } = compilation; - compilation.hooks.finishModules.tap( - "InferAsyncModulesPlugin", - modules => { - /** @type {Set} */ - const queue = new Set(); - for (const module of modules) { - if (module.buildMeta && module.buildMeta.async) { - queue.add(module); - } - } - for (const module of queue) { - moduleGraph.setAsync(module); - for (const [ - originModule, - connections - ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { - if ( - connections.some( - c => - c.dependency instanceof HarmonyImportDependency && - c.isTargetActive(undefined) - ) - ) { - queue.add(originModule); - } - } - } - } + needBuild(context, callback) { + callback(null, !this.buildInfo); + } + + /** + * @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 = { + strict: true + }; + + this.clearDependenciesAndBlocks(); + if (this.externalRequests.length === 1) { + this.addDependency( + new RemoteToExternalDependency(this.externalRequests[0]) ); - }); + } else { + this.addDependency(new FallbackDependency(this.externalRequests)); + } + + callback(); + } + + /** + * @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 6; + } + + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; + } + + /** + * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + */ + nameForCondition() { + return this.request; + } + + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { + const module = moduleGraph.getModule(this.dependencies[0]); + const id = module && chunkGraph.getModuleId(module); + const sources = new Map(); + sources.set("remote", new RawSource("")); + const data = new Map(); + data.set("share-init", [ + { + shareScope: this.shareScope, + initStage: 20, + init: id === undefined ? "" : `initExternal(${JSON.stringify(id)});` + } + ]); + return { sources, data, runtimeRequirements: RUNTIME_REQUIREMENTS }; + } + + serialize(context) { + const { write } = context; + write(this.request); + write(this.externalRequests); + write(this.internalRequest); + write(this.shareScope); + super.serialize(context); + } + + static deserialize(context) { + const { read } = context; + const obj = new RemoteModule(read(), read(), read(), read()); + obj.deserialize(context); + return obj; } } -module.exports = InferAsyncModulesPlugin; +makeSerializable(RemoteModule, "webpack/lib/container/RemoteModule"); + +module.exports = RemoteModule; /***/ }), -/***/ 79233: +/***/ 88288: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -66365,1425 +67213,1071 @@ module.exports = InferAsyncModulesPlugin; -const AsyncDependencyToInitialChunkError = __webpack_require__(30111); -const { connectChunkGroupParentAndChild } = __webpack_require__(37234); -const ModuleGraphConnection = __webpack_require__(40639); -const { getEntryRuntime, mergeRuntime } = __webpack_require__(17156); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Entrypoint")} Entrypoint */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ModuleGraph")} ModuleGraph */ -/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("./logging/Logger").Logger} Logger */ -/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./RemoteModule")} RemoteModule */ -/** - * @typedef {Object} QueueItem - * @property {number} action - * @property {DependenciesBlock} block - * @property {Module} module - * @property {Chunk} chunk - * @property {ChunkGroup} chunkGroup - * @property {ChunkGroupInfo} chunkGroupInfo - */ +class RemoteRuntimeModule extends RuntimeModule { + constructor() { + super("remotes loading"); + } -/** @typedef {Set & { plus: Set }} ModuleSetPlus */ + /** + * @returns {string} runtime code + */ + generate() { + const { compilation, chunkGraph } = this; + const { runtimeTemplate, moduleGraph } = compilation; + const chunkToRemotesMapping = {}; + const idToExternalAndNameMapping = {}; + for (const chunk of this.chunk.getAllAsyncChunks()) { + const modules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "remote" + ); + if (!modules) continue; + const remotes = (chunkToRemotesMapping[chunk.id] = []); + for (const m of modules) { + const module = /** @type {RemoteModule} */ (m); + const name = module.internalRequest; + const id = chunkGraph.getModuleId(module); + const shareScope = module.shareScope; + const dep = module.dependencies[0]; + const externalModule = moduleGraph.getModule(dep); + const externalModuleId = + externalModule && chunkGraph.getModuleId(externalModule); + remotes.push(id); + idToExternalAndNameMapping[id] = [shareScope, name, externalModuleId]; + } + } + return Template.asString([ + `var chunkMapping = ${JSON.stringify( + chunkToRemotesMapping, + null, + "\t" + )};`, + `var idToExternalAndNameMapping = ${JSON.stringify( + idToExternalAndNameMapping, + null, + "\t" + )};`, + `${ + RuntimeGlobals.ensureChunkHandlers + }.remotes = ${runtimeTemplate.basicFunction("chunkId, promises", [ + `if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`, + Template.indent([ + `chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction("id", [ + `var getScope = ${RuntimeGlobals.currentRemoteGetScope};`, + "if(!getScope) getScope = [];", + "var data = idToExternalAndNameMapping[id];", + "if(getScope.indexOf(data) >= 0) return;", + "getScope.push(data);", + `if(data.p) return promises.push(data.p);`, + `var onError = ${runtimeTemplate.basicFunction("error", [ + 'if(!error) error = new Error("Container missing");', + 'if(typeof error.message === "string")', + Template.indent( + `error.message += '\\nwhile loading "' + data[1] + '" from ' + data[2];` + ), + `__webpack_modules__[id] = ${runtimeTemplate.basicFunction("", [ + "throw error;" + ])}`, + "data.p = 0;" + ])};`, + `var handleFunction = ${runtimeTemplate.basicFunction( + "fn, arg1, arg2, d, next, first", + [ + "try {", + Template.indent([ + "var promise = fn(arg1, arg2);", + "if(promise && promise.then) {", + Template.indent([ + `var p = promise.then(${runtimeTemplate.returningFunction( + "next(result, d)", + "result" + )}, onError);`, + `if(first) promises.push(data.p = p); else return p;` + ]), + "} else {", + Template.indent(["return next(promise, d, first);"]), + "}" + ]), + "} catch(error) {", + Template.indent(["onError(error);"]), + "}" + ] + )}`, + `var onExternal = ${runtimeTemplate.returningFunction( + `external ? handleFunction(${RuntimeGlobals.initializeSharing}, data[0], 0, external, onInitialized, first) : onError()`, + "external, _, first" + )};`, + `var onInitialized = ${runtimeTemplate.returningFunction( + `handleFunction(external.get, data[1], getScope, 0, onFactory, first)`, + "_, external, first" + )};`, + `var onFactory = ${runtimeTemplate.basicFunction("factory", [ + "data.p = 1;", + `__webpack_modules__[id] = ${runtimeTemplate.basicFunction( + "module", + ["module.exports = factory();"] + )}` + ])};`, + "handleFunction(__webpack_require__, data[2], 0, 0, onExternal, 1);" + ])});` + ]), + "}" + ])}` + ]); + } +} -/** - * @typedef {Object} ChunkGroupInfo - * @property {ChunkGroup} chunkGroup the chunk group - * @property {RuntimeSpec} runtime the runtimes - * @property {ModuleSetPlus} minAvailableModules current minimal set of modules available at this point - * @property {boolean} minAvailableModulesOwned true, if minAvailableModules is owned and can be modified - * @property {ModuleSetPlus[]} availableModulesToBeMerged enqueued updates to the minimal set of available modules - * @property {Set=} skippedItems modules that were skipped because module is already available in parent chunks (need to reconsider when minAvailableModules is shrinking) - * @property {Set<[Module, ConnectionState]>=} skippedModuleConnections referenced modules that where skipped because they were not active in this runtime - * @property {ModuleSetPlus} resultingAvailableModules set of modules available including modules from this chunk group - * @property {Set} children set of children chunk groups, that will be revisited when availableModules shrink - * @property {Set} availableSources set of chunk groups that are the source for minAvailableModules - * @property {Set} availableChildren set of chunk groups which depend on the this chunk group as availableSource - * @property {number} preOrderIndex next pre order index - * @property {number} postOrderIndex next post order index - * @property {boolean} chunkLoading has a chunk loading mechanism - * @property {boolean} asyncChunks create async chunks - */ +module.exports = RemoteRuntimeModule; -/** - * @typedef {Object} BlockChunkGroupConnection - * @property {ChunkGroupInfo} originChunkGroupInfo origin chunk group - * @property {ChunkGroup} chunkGroup referenced chunk group - */ -const EMPTY_SET = /** @type {ModuleSetPlus} */ (new Set()); -EMPTY_SET.plus = EMPTY_SET; +/***/ }), -/** - * @param {ModuleSetPlus} a first set - * @param {ModuleSetPlus} b second set - * @returns {number} cmp - */ -const bySetSize = (a, b) => { - return b.size + b.plus.size - a.size - a.plus.size; -}; +/***/ 14389: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const extractBlockModules = (module, moduleGraph, runtime, blockModulesMap) => { - let blockCache; - let modules; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const arrays = []; - const queue = [module]; - while (queue.length > 0) { - const block = queue.pop(); - const arr = []; - arrays.push(arr); - blockModulesMap.set(block, arr); - for (const b of block.blocks) { - queue.push(b); - } + +const ModuleDependency = __webpack_require__(80321); +const makeSerializable = __webpack_require__(33032); + +class RemoteToExternalDependency extends ModuleDependency { + constructor(request) { + super(request); } - for (const connection of moduleGraph.getOutgoingConnections(module)) { - const d = connection.dependency; - // We skip connections without dependency - if (!d) continue; - const m = connection.module; - // We skip connections without Module pointer - if (!m) continue; - // We skip weak connections - if (connection.weak) continue; - const state = connection.getActiveState(runtime); - // We skip inactive connections - if (state === false) continue; + get type() { + return "remote to external"; + } - const block = moduleGraph.getParentBlock(d); - let index = moduleGraph.getParentBlockIndex(d); + get category() { + return "esm"; + } +} - // deprecated fallback - if (index < 0) { - index = block.dependencies.indexOf(d); - } +makeSerializable( + RemoteToExternalDependency, + "webpack/lib/container/RemoteToExternalDependency" +); - if (blockCache !== block) { - modules = blockModulesMap.get((blockCache = block)); - } +module.exports = RemoteToExternalDependency; - const i = index << 2; - modules[i] = m; - modules[i + 1] = state; - } - for (const modules of arrays) { - if (modules.length === 0) continue; - let indexMap; - let length = 0; - outer: for (let j = 0; j < modules.length; j += 2) { - const m = modules[j]; - if (m === undefined) continue; - const state = modules[j + 1]; - if (indexMap === undefined) { - let i = 0; - for (; i < length; i += 2) { - if (modules[i] === m) { - const merged = modules[i + 1]; - if (merged === true) continue outer; - modules[i + 1] = ModuleGraphConnection.addConnectionStates( - merged, - state - ); - } - } - modules[length] = m; - length++; - modules[length] = state; - length++; - if (length > 30) { - // To avoid worse case performance, we will use an index map for - // linear cost access, which allows to maintain O(n) complexity - // while keeping allocations down to a minimum - indexMap = new Map(); - for (let i = 0; i < length; i += 2) { - indexMap.set(modules[i], i + 1); - } - } +/***/ }), + +/***/ 3083: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @template T @typedef {(string | Record)[] | Record} ContainerOptionsFormat */ + +/** + * @template T + * @template N + * @param {ContainerOptionsFormat} options options passed by the user + * @param {function(string | string[], string) : N} normalizeSimple normalize a simple item + * @param {function(T, string) : N} normalizeOptions normalize a complex item + * @param {function(string, N): void} fn processing function + * @returns {void} + */ +const process = (options, normalizeSimple, normalizeOptions, fn) => { + const array = items => { + for (const item of items) { + if (typeof item === "string") { + fn(item, normalizeSimple(item, item)); + } else if (item && typeof item === "object") { + object(item); } else { - const idx = indexMap.get(m); - if (idx !== undefined) { - const merged = modules[idx]; - if (merged === true) continue outer; - modules[idx] = ModuleGraphConnection.addConnectionStates( - merged, - state - ); - } else { - modules[length] = m; - length++; - modules[length] = state; - indexMap.set(m, length); - length++; - } + throw new Error("Unexpected options format"); } } - modules.length = length; + }; + const object = obj => { + for (const [key, value] of Object.entries(obj)) { + if (typeof value === "string" || Array.isArray(value)) { + fn(key, normalizeSimple(value, key)); + } else { + fn(key, normalizeOptions(value, key)); + } + } + }; + if (!options) { + return; + } else if (Array.isArray(options)) { + array(options); + } else if (typeof options === "object") { + object(options); + } else { + throw new Error("Unexpected options format"); } }; /** - * - * @param {Logger} logger a logger - * @param {Compilation} compilation the compilation - * @param {Map} inputEntrypointsAndModules chunk groups which are processed with the modules - * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules - * @param {Map} blockConnections connection for blocks - * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks - * @param {Set} allCreatedChunkGroups filled with all chunk groups that are created here + * @template T + * @template R + * @param {ContainerOptionsFormat} options options passed by the user + * @param {function(string | string[], string) : R} normalizeSimple normalize a simple item + * @param {function(T, string) : R} normalizeOptions normalize a complex item + * @returns {[string, R][]} parsed options */ -const visitModules = ( - logger, - compilation, - inputEntrypointsAndModules, - chunkGroupInfoMap, - blockConnections, - blocksWithNestedBlocks, - allCreatedChunkGroups -) => { - const { moduleGraph, chunkGraph, moduleMemCaches } = compilation; +const parseOptions = (options, normalizeSimple, normalizeOptions) => { + /** @type {[string, R][]} */ + const items = []; + process(options, normalizeSimple, normalizeOptions, (key, value) => { + items.push([key, value]); + }); + return items; +}; - const blockModulesRuntimeMap = new Map(); +/** + * @template T + * @param {string} scope scope name + * @param {ContainerOptionsFormat} options options passed by the user + * @returns {Record} options to spread or pass + */ +const scope = (scope, options) => { + /** @type {Record} */ + const obj = {}; + process( + options, + item => /** @type {string | string[] | T} */ (item), + item => /** @type {string | string[] | T} */ (item), + (key, value) => { + obj[ + key.startsWith("./") ? `${scope}${key.slice(1)}` : `${scope}/${key}` + ] = value; + } + ); + return obj; +}; - /** @type {RuntimeSpec | false} */ - let blockModulesMapRuntime = false; - let blockModulesMap; +exports.parseOptions = parseOptions; +exports.scope = scope; - /** - * - * @param {DependenciesBlock} block block - * @param {RuntimeSpec} runtime runtime - * @returns {(Module | ConnectionState)[]} block modules in flatten tuples - */ - const getBlockModules = (block, runtime) => { - if (blockModulesMapRuntime !== runtime) { - blockModulesMap = blockModulesRuntimeMap.get(runtime); - if (blockModulesMap === undefined) { - blockModulesMap = new Map(); - blockModulesRuntimeMap.set(runtime, blockModulesMap); - } - } - let blockModules = blockModulesMap.get(block); - if (blockModules !== undefined) return blockModules; - const module = /** @type {Module} */ (block.getRootBlock()); - const memCache = moduleMemCaches && moduleMemCaches.get(module); - if (memCache !== undefined) { - const map = memCache.provide( - "bundleChunkGraph.blockModules", - runtime, - () => { - logger.time("visitModules: prepare"); - const map = new Map(); - extractBlockModules(module, moduleGraph, runtime, map); - logger.timeAggregate("visitModules: prepare"); - return map; - } - ); - for (const [block, blockModules] of map) - blockModulesMap.set(block, blockModules); - return map.get(block); - } else { - logger.time("visitModules: prepare"); - extractBlockModules(module, moduleGraph, runtime, blockModulesMap); - blockModules = blockModulesMap.get(block); - logger.timeAggregate("visitModules: prepare"); - return blockModules; - } - }; - let statProcessedQueueItems = 0; - let statProcessedBlocks = 0; - let statConnectedChunkGroups = 0; - let statProcessedChunkGroupsForMerging = 0; - let statMergedAvailableModuleSets = 0; - let statForkedAvailableModules = 0; - let statForkedAvailableModulesCount = 0; - let statForkedAvailableModulesCountPlus = 0; - let statForkedMergedModulesCount = 0; - let statForkedMergedModulesCountPlus = 0; - let statForkedResultModulesCount = 0; - let statChunkGroupInfoUpdated = 0; - let statChildChunkGroupsReconnected = 0; +/***/ }), - let nextChunkGroupIndex = 0; - let nextFreeModulePreOrderIndex = 0; - let nextFreeModulePostOrderIndex = 0; +/***/ 91254: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {Map} */ - const blockChunkGroups = new Map(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ - /** @type {Map} */ - const namedChunkGroups = new Map(); - /** @type {Map} */ - const namedAsyncEntrypoints = new Map(); - const ADD_AND_ENTER_ENTRY_MODULE = 0; - const ADD_AND_ENTER_MODULE = 1; - const ENTER_MODULE = 2; - const PROCESS_BLOCK = 3; - const PROCESS_ENTRY_BLOCK = 4; - const LEAVE_MODULE = 5; +const { ReplaceSource, RawSource, ConcatSource } = __webpack_require__(51255); +const { UsageState } = __webpack_require__(63686); +const Generator = __webpack_require__(93401); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); - /** @type {QueueItem[]} */ - let queue = []; +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../util/Hash")} Hash */ - /** @type {Map>} */ - const queueConnect = new Map(); - /** @type {Set} */ - const chunkGroupsForCombining = new Set(); +const TYPES = new Set(["javascript"]); - // Fill queue with entrypoint modules - // Create ChunkGroupInfo for entrypoints - for (const [chunkGroup, modules] of inputEntrypointsAndModules) { - const runtime = getEntryRuntime( - compilation, - chunkGroup.name, - chunkGroup.options - ); - /** @type {ChunkGroupInfo} */ - const chunkGroupInfo = { - chunkGroup, - runtime, - minAvailableModules: undefined, - minAvailableModulesOwned: false, - availableModulesToBeMerged: [], - skippedItems: undefined, - resultingAvailableModules: undefined, - children: undefined, - availableSources: undefined, - availableChildren: undefined, - preOrderIndex: 0, - postOrderIndex: 0, - chunkLoading: - chunkGroup.options.chunkLoading !== undefined - ? chunkGroup.options.chunkLoading !== false - : compilation.outputOptions.chunkLoading !== false, - asyncChunks: - chunkGroup.options.asyncChunks !== undefined - ? chunkGroup.options.asyncChunks - : compilation.outputOptions.asyncChunks !== false +class CssExportsGenerator extends Generator { + constructor() { + super(); + } + + // TODO add getConcatenationBailoutReason to allow concatenation + // but how to make it have a module id + + /** + * @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 source = new ReplaceSource(new RawSource("")); + const initFragments = []; + const cssExports = new Map(); + + generateContext.runtimeRequirements.add(RuntimeGlobals.module); + + const runtimeRequirements = new Set(); + + const templateContext = { + runtimeTemplate: generateContext.runtimeTemplate, + dependencyTemplates: generateContext.dependencyTemplates, + moduleGraph: generateContext.moduleGraph, + chunkGraph: generateContext.chunkGraph, + module, + runtime: generateContext.runtime, + runtimeRequirements: runtimeRequirements, + concatenationScope: generateContext.concatenationScope, + codeGenerationResults: generateContext.codeGenerationResults, + initFragments, + cssExports }; - chunkGroup.index = nextChunkGroupIndex++; - if (chunkGroup.getNumberOfParents() > 0) { - // minAvailableModules for child entrypoints are unknown yet, set to undefined. - // This means no module is added until other sets are merged into - // this minAvailableModules (by the parent entrypoints) - const skippedItems = new Set(); - for (const module of modules) { - skippedItems.add(module); + + const handleDependency = dependency => { + const constructor = /** @type {new (...args: any[]) => Dependency} */ ( + dependency.constructor + ); + const template = generateContext.dependencyTemplates.get(constructor); + if (!template) { + throw new Error( + "No template for dependency: " + dependency.constructor.name + ); } - chunkGroupInfo.skippedItems = skippedItems; - chunkGroupsForCombining.add(chunkGroupInfo); + + template.apply(dependency, source, templateContext); + }; + module.dependencies.forEach(handleDependency); + + if (generateContext.concatenationScope) { + const source = new ConcatSource(); + const usedIdentifiers = new Set(); + for (const [k, v] of cssExports) { + let identifier = Template.toIdentifier(k); + let i = 0; + while (usedIdentifiers.has(identifier)) { + identifier = Template.toIdentifier(k + i); + } + usedIdentifiers.add(identifier); + generateContext.concatenationScope.registerExport(k, identifier); + source.add( + `${ + generateContext.runtimeTemplate.supportsConst ? "const" : "var" + } ${identifier} = ${JSON.stringify(v)};\n` + ); + } + return source; } else { - // The application may start here: We start with an empty list of available modules - chunkGroupInfo.minAvailableModules = EMPTY_SET; - const chunk = chunkGroup.getEntrypointChunk(); - for (const module of modules) { - queue.push({ - action: ADD_AND_ENTER_MODULE, - block: module, - module, - chunk, - chunkGroup, - chunkGroupInfo - }); + const otherUsed = + generateContext.moduleGraph + .getExportsInfo(module) + .otherExportsInfo.getUsed(generateContext.runtime) !== + UsageState.Unused; + if (otherUsed) { + generateContext.runtimeRequirements.add( + RuntimeGlobals.makeNamespaceObject + ); } - } - chunkGroupInfoMap.set(chunkGroup, chunkGroupInfo); - if (chunkGroup.name) { - namedChunkGroups.set(chunkGroup.name, chunkGroupInfo); + return new RawSource( + `${otherUsed ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${ + module.moduleArgument + }.exports = {\n${Array.from( + cssExports, + ([k, v]) => `\t${JSON.stringify(k)}: ${JSON.stringify(v)}` + ).join(",\n")}\n}${otherUsed ? ")" : ""};` + ); } } - // Fill availableSources with parent-child dependencies between entrypoints - for (const chunkGroupInfo of chunkGroupsForCombining) { - const { chunkGroup } = chunkGroupInfo; - chunkGroupInfo.availableSources = new Set(); - for (const parent of chunkGroup.parentsIterable) { - const parentChunkGroupInfo = chunkGroupInfoMap.get(parent); - chunkGroupInfo.availableSources.add(parentChunkGroupInfo); - if (parentChunkGroupInfo.availableChildren === undefined) { - parentChunkGroupInfo.availableChildren = new Set(); - } - parentChunkGroupInfo.availableChildren.add(chunkGroupInfo); - } + + /** + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) + */ + getTypes(module) { + return TYPES; } - // pop() is used to read from the queue - // so it need to be reversed to be iterated in - // correct order - queue.reverse(); - /** @type {Set} */ - const outdatedChunkGroupInfo = new Set(); - /** @type {Set} */ - const chunkGroupsForMerging = new Set(); - /** @type {QueueItem[]} */ - let queueDelayed = []; + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + return 42; + } - /** @type {[Module, ConnectionState][]} */ - const skipConnectionBuffer = []; - /** @type {Module[]} */ - const skipBuffer = []; - /** @type {QueueItem[]} */ - const queueBuffer = []; - - /** @type {Module} */ - let module; - /** @type {Chunk} */ - let chunk; - /** @type {ChunkGroup} */ - let chunkGroup; - /** @type {DependenciesBlock} */ - let block; - /** @type {ChunkGroupInfo} */ - let chunkGroupInfo; - - // For each async Block in graph /** - * @param {AsyncDependenciesBlock} b iterating over each Async DepBlock - * @returns {void} + * @param {Hash} hash hash that will be modified + * @param {UpdateHashContext} updateHashContext context for updating hash */ - const iteratorBlock = b => { - // 1. We create a chunk group with single chunk in it for this Block - // but only once (blockChunkGroups map) - let cgi = blockChunkGroups.get(b); - /** @type {ChunkGroup} */ - let c; - /** @type {Entrypoint} */ - let entrypoint; - const entryOptions = b.groupOptions && b.groupOptions.entryOptions; - if (cgi === undefined) { - const chunkName = (b.groupOptions && b.groupOptions.name) || b.chunkName; - if (entryOptions) { - cgi = namedAsyncEntrypoints.get(chunkName); - if (!cgi) { - entrypoint = compilation.addAsyncEntrypoint( - entryOptions, - module, - b.loc, - b.request - ); - entrypoint.index = nextChunkGroupIndex++; - cgi = { - chunkGroup: entrypoint, - runtime: entrypoint.options.runtime || entrypoint.name, - minAvailableModules: EMPTY_SET, - minAvailableModulesOwned: false, - availableModulesToBeMerged: [], - skippedItems: undefined, - resultingAvailableModules: undefined, - children: undefined, - availableSources: undefined, - availableChildren: undefined, - preOrderIndex: 0, - postOrderIndex: 0, - chunkLoading: - entryOptions.chunkLoading !== undefined - ? entryOptions.chunkLoading !== false - : chunkGroupInfo.chunkLoading, - asyncChunks: - entryOptions.asyncChunks !== undefined - ? entryOptions.asyncChunks - : chunkGroupInfo.asyncChunks - }; - chunkGroupInfoMap.set(entrypoint, cgi); + updateHash(hash, { module }) {} +} - chunkGraph.connectBlockAndChunkGroup(b, entrypoint); - if (chunkName) { - namedAsyncEntrypoints.set(chunkName, cgi); - } - } else { - entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup); - // TODO merge entryOptions - entrypoint.addOrigin(module, b.loc, b.request); - chunkGraph.connectBlockAndChunkGroup(b, entrypoint); - } +module.exports = CssExportsGenerator; - // 2. We enqueue the DependenciesBlock for traversal - queueDelayed.push({ - action: PROCESS_ENTRY_BLOCK, - block: b, - module: module, - chunk: entrypoint.chunks[0], - chunkGroup: entrypoint, - chunkGroupInfo: cgi - }); - } else if (!chunkGroupInfo.asyncChunks || !chunkGroupInfo.chunkLoading) { - // Just queue the block into the current chunk group - queue.push({ - action: PROCESS_BLOCK, - block: b, - module: module, - chunk, - chunkGroup, - chunkGroupInfo - }); - } else { - cgi = chunkName && namedChunkGroups.get(chunkName); - if (!cgi) { - c = compilation.addChunkInGroup( - b.groupOptions || b.chunkName, - module, - b.loc, - b.request - ); - c.index = nextChunkGroupIndex++; - cgi = { - chunkGroup: c, - runtime: chunkGroupInfo.runtime, - minAvailableModules: undefined, - minAvailableModulesOwned: undefined, - availableModulesToBeMerged: [], - skippedItems: undefined, - resultingAvailableModules: undefined, - children: undefined, - availableSources: undefined, - availableChildren: undefined, - preOrderIndex: 0, - postOrderIndex: 0, - chunkLoading: chunkGroupInfo.chunkLoading, - asyncChunks: chunkGroupInfo.asyncChunks - }; - allCreatedChunkGroups.add(c); - chunkGroupInfoMap.set(c, cgi); - if (chunkName) { - namedChunkGroups.set(chunkName, cgi); - } - } else { - c = cgi.chunkGroup; - if (c.isInitial()) { - compilation.errors.push( - new AsyncDependencyToInitialChunkError(chunkName, module, b.loc) - ); - c = chunkGroup; - } - c.addOptions(b.groupOptions); - c.addOrigin(module, b.loc, b.request); - } - blockConnections.set(b, []); - } - blockChunkGroups.set(b, cgi); - } else if (entryOptions) { - entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup); - } else { - c = cgi.chunkGroup; - } - if (c !== undefined) { - // 2. We store the connection for the block - // to connect it later if needed - blockConnections.get(b).push({ - originChunkGroupInfo: chunkGroupInfo, - chunkGroup: c - }); +/***/ }), - // 3. We enqueue the chunk group info creation/updating - let connectList = queueConnect.get(chunkGroupInfo); - if (connectList === undefined) { - connectList = new Set(); - queueConnect.set(chunkGroupInfo, connectList); - } - connectList.add(cgi); +/***/ 46061: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // TODO check if this really need to be done for each traversal - // or if it is enough when it's queued when created - // 4. We enqueue the DependenciesBlock for traversal - queueDelayed.push({ - action: PROCESS_BLOCK, - block: b, - module: module, - chunk: c.chunks[0], - chunkGroup: c, - chunkGroupInfo: cgi - }); - } else if (entrypoint !== undefined) { - chunkGroupInfo.chunkGroup.addAsyncEntrypoint(entrypoint); - } - }; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ - /** - * @param {DependenciesBlock} block the block - * @returns {void} - */ - const processBlock = block => { - statProcessedBlocks++; - // get prepared block info - const blockModules = getBlockModules(block, chunkGroupInfo.runtime); - if (blockModules !== undefined) { - const { minAvailableModules } = chunkGroupInfo; - // Buffer items because order need to be reversed to get indices correct - // Traverse all referenced modules - for (let i = 0; i < blockModules.length; i += 2) { - const refModule = /** @type {Module} */ (blockModules[i]); - if (chunkGraph.isModuleInChunk(refModule, chunk)) { - // skip early if already connected - continue; - } - const activeState = /** @type {ConnectionState} */ ( - blockModules[i + 1] - ); - if (activeState !== true) { - skipConnectionBuffer.push([refModule, activeState]); - if (activeState === false) continue; - } - if ( - activeState === true && - (minAvailableModules.has(refModule) || - minAvailableModules.plus.has(refModule)) - ) { - // already in parent chunks, skip it for now - skipBuffer.push(refModule); - continue; - } - // enqueue, then add and enter to be in the correct order - // this is relevant with circular dependencies - queueBuffer.push({ - action: activeState === true ? ADD_AND_ENTER_MODULE : PROCESS_BLOCK, - block: refModule, - module: refModule, - chunk, - chunkGroup, - chunkGroupInfo - }); - } - // Add buffered items in reverse order - if (skipConnectionBuffer.length > 0) { - let { skippedModuleConnections } = chunkGroupInfo; - if (skippedModuleConnections === undefined) { - chunkGroupInfo.skippedModuleConnections = skippedModuleConnections = - new Set(); - } - for (let i = skipConnectionBuffer.length - 1; i >= 0; i--) { - skippedModuleConnections.add(skipConnectionBuffer[i]); - } - skipConnectionBuffer.length = 0; - } - if (skipBuffer.length > 0) { - let { skippedItems } = chunkGroupInfo; - if (skippedItems === undefined) { - chunkGroupInfo.skippedItems = skippedItems = new Set(); - } - for (let i = skipBuffer.length - 1; i >= 0; i--) { - skippedItems.add(skipBuffer[i]); - } - skipBuffer.length = 0; - } - if (queueBuffer.length > 0) { - for (let i = queueBuffer.length - 1; i >= 0; i--) { - queue.push(queueBuffer[i]); - } - queueBuffer.length = 0; - } - } - // Traverse all Blocks - for (const b of block.blocks) { - iteratorBlock(b); - } +const { ReplaceSource } = __webpack_require__(51255); +const Generator = __webpack_require__(93401); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); - if (block.blocks.length > 0 && module !== block) { - blocksWithNestedBlocks.add(block); - } - }; +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../util/Hash")} Hash */ + +const TYPES = new Set(["css"]); + +class CssGenerator extends Generator { + constructor() { + super(); + } /** - * @param {DependenciesBlock} block the block - * @returns {void} + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code */ - const processEntryBlock = block => { - statProcessedBlocks++; - // get prepared block info - const blockModules = getBlockModules(block, chunkGroupInfo.runtime); + generate(module, generateContext) { + const originalSource = module.originalSource(); + const source = new ReplaceSource(originalSource); + const initFragments = []; + const cssExports = new Map(); - if (blockModules !== undefined) { - // Traverse all referenced modules - for (let i = 0; i < blockModules.length; i += 2) { - const refModule = /** @type {Module} */ (blockModules[i]); - const activeState = /** @type {ConnectionState} */ ( - blockModules[i + 1] + generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules); + + const templateContext = { + runtimeTemplate: generateContext.runtimeTemplate, + dependencyTemplates: generateContext.dependencyTemplates, + moduleGraph: generateContext.moduleGraph, + chunkGraph: generateContext.chunkGraph, + module, + runtime: generateContext.runtime, + runtimeRequirements: generateContext.runtimeRequirements, + concatenationScope: generateContext.concatenationScope, + codeGenerationResults: generateContext.codeGenerationResults, + initFragments, + cssExports + }; + + const handleDependency = dependency => { + const constructor = /** @type {new (...args: any[]) => Dependency} */ ( + dependency.constructor + ); + const template = generateContext.dependencyTemplates.get(constructor); + if (!template) { + throw new Error( + "No template for dependency: " + dependency.constructor.name ); - // enqueue, then add and enter to be in the correct order - // this is relevant with circular dependencies - queueBuffer.push({ - action: - activeState === true ? ADD_AND_ENTER_ENTRY_MODULE : PROCESS_BLOCK, - block: refModule, - module: refModule, - chunk, - chunkGroup, - chunkGroupInfo - }); - } - // Add buffered items in reverse order - if (queueBuffer.length > 0) { - for (let i = queueBuffer.length - 1; i >= 0; i--) { - queue.push(queueBuffer[i]); - } - queueBuffer.length = 0; } - } - // Traverse all Blocks - for (const b of block.blocks) { - iteratorBlock(b); - } + template.apply(dependency, source, templateContext); + }; + module.dependencies.forEach(handleDependency); + if (module.presentationalDependencies !== undefined) + module.presentationalDependencies.forEach(handleDependency); - if (block.blocks.length > 0 && module !== block) { - blocksWithNestedBlocks.add(block); + if (cssExports.size > 0) { + const data = generateContext.getData(); + data.set("css-exports", cssExports); } - }; - - const processQueue = () => { - while (queue.length) { - statProcessedQueueItems++; - const queueItem = queue.pop(); - module = queueItem.module; - block = queueItem.block; - chunk = queueItem.chunk; - chunkGroup = queueItem.chunkGroup; - chunkGroupInfo = queueItem.chunkGroupInfo; - switch (queueItem.action) { - case ADD_AND_ENTER_ENTRY_MODULE: - chunkGraph.connectChunkAndEntryModule( - chunk, - module, - /** @type {Entrypoint} */ (chunkGroup) - ); - // fallthrough - case ADD_AND_ENTER_MODULE: { - if (chunkGraph.isModuleInChunk(module, chunk)) { - // already connected, skip it - break; - } - // We connect Module and Chunk - chunkGraph.connectChunkAndModule(chunk, module); - } - // fallthrough - case ENTER_MODULE: { - const index = chunkGroup.getModulePreOrderIndex(module); - if (index === undefined) { - chunkGroup.setModulePreOrderIndex( - module, - chunkGroupInfo.preOrderIndex++ - ); - } + return InitFragment.addToSource(source, initFragments, generateContext); + } - if ( - moduleGraph.setPreOrderIndexIfUnset( - module, - nextFreeModulePreOrderIndex - ) - ) { - nextFreeModulePreOrderIndex++; - } + /** + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) + */ + getTypes(module) { + return TYPES; + } - // reuse queueItem - queueItem.action = LEAVE_MODULE; - queue.push(queueItem); - } - // fallthrough - case PROCESS_BLOCK: { - processBlock(block); - break; - } - case PROCESS_ENTRY_BLOCK: { - processEntryBlock(block); - break; - } - case LEAVE_MODULE: { - const index = chunkGroup.getModulePostOrderIndex(module); - if (index === undefined) { - chunkGroup.setModulePostOrderIndex( - module, - chunkGroupInfo.postOrderIndex++ - ); - } + /** + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module + */ + getSize(module, type) { + const originalSource = module.originalSource(); - if ( - moduleGraph.setPostOrderIndexIfUnset( - module, - nextFreeModulePostOrderIndex - ) - ) { - nextFreeModulePostOrderIndex++; - } - break; - } - } + if (!originalSource) { + return 0; } - }; - - const calculateResultingAvailableModules = chunkGroupInfo => { - if (chunkGroupInfo.resultingAvailableModules) - return chunkGroupInfo.resultingAvailableModules; - const minAvailableModules = chunkGroupInfo.minAvailableModules; + return originalSource.size(); + } - // Create a new Set of available modules at this point - // We want to be as lazy as possible. There are multiple ways doing this: - // Note that resultingAvailableModules is stored as "(a) + (b)" as it's a ModuleSetPlus - // - resultingAvailableModules = (modules of chunk) + (minAvailableModules + minAvailableModules.plus) - // - resultingAvailableModules = (minAvailableModules + modules of chunk) + (minAvailableModules.plus) - // We choose one depending on the size of minAvailableModules vs minAvailableModules.plus + /** + * @param {Hash} hash hash that will be modified + * @param {UpdateHashContext} updateHashContext context for updating hash + */ + updateHash(hash, { module }) {} +} - let resultingAvailableModules; - if (minAvailableModules.size > minAvailableModules.plus.size) { - // resultingAvailableModules = (modules of chunk) + (minAvailableModules + minAvailableModules.plus) - resultingAvailableModules = - /** @type {Set & {plus: Set}} */ (new Set()); - for (const module of minAvailableModules.plus) - minAvailableModules.add(module); - minAvailableModules.plus = EMPTY_SET; - resultingAvailableModules.plus = minAvailableModules; - chunkGroupInfo.minAvailableModulesOwned = false; - } else { - // resultingAvailableModules = (minAvailableModules + modules of chunk) + (minAvailableModules.plus) - resultingAvailableModules = - /** @type {Set & {plus: Set}} */ ( - new Set(minAvailableModules) - ); - resultingAvailableModules.plus = minAvailableModules.plus; - } +module.exports = CssGenerator; - // add the modules from the chunk group to the set - for (const chunk of chunkGroupInfo.chunkGroup.chunks) { - for (const m of chunkGraph.getChunkModulesIterable(chunk)) { - resultingAvailableModules.add(m); - } - } - return (chunkGroupInfo.resultingAvailableModules = - resultingAvailableModules); - }; - const processConnectQueue = () => { - // Figure out new parents for chunk groups - // to get new available modules for these children - for (const [chunkGroupInfo, targets] of queueConnect) { - // 1. Add new targets to the list of children - if (chunkGroupInfo.children === undefined) { - chunkGroupInfo.children = targets; - } else { - for (const target of targets) { - chunkGroupInfo.children.add(target); - } - } +/***/ }), - // 2. Calculate resulting available modules - const resultingAvailableModules = - calculateResultingAvailableModules(chunkGroupInfo); +/***/ 80806: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const runtime = chunkGroupInfo.runtime; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // 3. Update chunk group info - for (const target of targets) { - target.availableModulesToBeMerged.push(resultingAvailableModules); - chunkGroupsForMerging.add(target); - const oldRuntime = target.runtime; - const newRuntime = mergeRuntime(oldRuntime, runtime); - if (oldRuntime !== newRuntime) { - target.runtime = newRuntime; - outdatedChunkGroupInfo.add(target); - } - } - statConnectedChunkGroups += targets.size; - } - queueConnect.clear(); - }; - const processChunkGroupsForMerging = () => { - statProcessedChunkGroupsForMerging += chunkGroupsForMerging.size; +const { SyncWaterfallHook } = __webpack_require__(6967); +const Compilation = __webpack_require__(85720); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); +const compileBooleanMatcher = __webpack_require__(29404); +const { chunkHasCss } = __webpack_require__(47283); - // Execute the merge - for (const info of chunkGroupsForMerging) { - const availableModulesToBeMerged = info.availableModulesToBeMerged; - let cachedMinAvailableModules = info.minAvailableModules; +/** @typedef {import("../Chunk")} Chunk */ - statMergedAvailableModuleSets += availableModulesToBeMerged.length; +/** + * @typedef {Object} JsonpCompilationPluginHooks + * @property {SyncWaterfallHook<[string, Chunk]>} createStylesheet + */ - // 1. Get minimal available modules - // It doesn't make sense to traverse a chunk again with more available modules. - // This step calculates the minimal available modules and skips traversal when - // the list didn't shrink. - if (availableModulesToBeMerged.length > 1) { - availableModulesToBeMerged.sort(bySetSize); - } - let changed = false; - merge: for (const availableModules of availableModulesToBeMerged) { - if (cachedMinAvailableModules === undefined) { - cachedMinAvailableModules = availableModules; - info.minAvailableModules = cachedMinAvailableModules; - info.minAvailableModulesOwned = false; - changed = true; - } else { - if (info.minAvailableModulesOwned) { - // We own it and can modify it - if (cachedMinAvailableModules.plus === availableModules.plus) { - for (const m of cachedMinAvailableModules) { - if (!availableModules.has(m)) { - cachedMinAvailableModules.delete(m); - changed = true; - } - } - } else { - for (const m of cachedMinAvailableModules) { - if (!availableModules.has(m) && !availableModules.plus.has(m)) { - cachedMinAvailableModules.delete(m); - changed = true; - } - } - for (const m of cachedMinAvailableModules.plus) { - if (!availableModules.has(m) && !availableModules.plus.has(m)) { - // We can't remove modules from the plus part - // so we need to merge plus into the normal part to allow modifying it - const iterator = - cachedMinAvailableModules.plus[Symbol.iterator](); - // fast forward add all modules until m - /** @type {IteratorResult} */ - let it; - while (!(it = iterator.next()).done) { - const module = it.value; - if (module === m) break; - cachedMinAvailableModules.add(module); - } - // check the remaining modules before adding - while (!(it = iterator.next()).done) { - const module = it.value; - if ( - availableModules.has(module) || - availableModules.plus.has(m) - ) { - cachedMinAvailableModules.add(module); - } - } - cachedMinAvailableModules.plus = EMPTY_SET; - changed = true; - continue merge; - } - } - } - } else if (cachedMinAvailableModules.plus === availableModules.plus) { - // Common and fast case when the plus part is shared - // We only need to care about the normal part - if (availableModules.size < cachedMinAvailableModules.size) { - // the new availableModules is smaller so it's faster to - // fork from the new availableModules - statForkedAvailableModules++; - statForkedAvailableModulesCount += availableModules.size; - statForkedMergedModulesCount += cachedMinAvailableModules.size; - // construct a new Set as intersection of cachedMinAvailableModules and availableModules - const newSet = /** @type {ModuleSetPlus} */ (new Set()); - newSet.plus = availableModules.plus; - for (const m of availableModules) { - if (cachedMinAvailableModules.has(m)) { - newSet.add(m); - } - } - statForkedResultModulesCount += newSet.size; - cachedMinAvailableModules = newSet; - info.minAvailableModulesOwned = true; - info.minAvailableModules = newSet; - changed = true; - continue merge; - } - for (const m of cachedMinAvailableModules) { - if (!availableModules.has(m)) { - // cachedMinAvailableModules need to be modified - // but we don't own it - statForkedAvailableModules++; - statForkedAvailableModulesCount += - cachedMinAvailableModules.size; - statForkedMergedModulesCount += availableModules.size; - // construct a new Set as intersection of cachedMinAvailableModules and availableModules - // as the plus part is equal we can just take over this one - const newSet = /** @type {ModuleSetPlus} */ (new Set()); - newSet.plus = availableModules.plus; - const iterator = cachedMinAvailableModules[Symbol.iterator](); - // fast forward add all modules until m - /** @type {IteratorResult} */ - let it; - while (!(it = iterator.next()).done) { - const module = it.value; - if (module === m) break; - newSet.add(module); - } - // check the remaining modules before adding - while (!(it = iterator.next()).done) { - const module = it.value; - if (availableModules.has(module)) { - newSet.add(module); - } - } - statForkedResultModulesCount += newSet.size; - cachedMinAvailableModules = newSet; - info.minAvailableModulesOwned = true; - info.minAvailableModules = newSet; - changed = true; - continue merge; - } - } - } else { - for (const m of cachedMinAvailableModules) { - if (!availableModules.has(m) && !availableModules.plus.has(m)) { - // cachedMinAvailableModules need to be modified - // but we don't own it - statForkedAvailableModules++; - statForkedAvailableModulesCount += - cachedMinAvailableModules.size; - statForkedAvailableModulesCountPlus += - cachedMinAvailableModules.plus.size; - statForkedMergedModulesCount += availableModules.size; - statForkedMergedModulesCountPlus += availableModules.plus.size; - // construct a new Set as intersection of cachedMinAvailableModules and availableModules - const newSet = /** @type {ModuleSetPlus} */ (new Set()); - newSet.plus = EMPTY_SET; - const iterator = cachedMinAvailableModules[Symbol.iterator](); - // fast forward add all modules until m - /** @type {IteratorResult} */ - let it; - while (!(it = iterator.next()).done) { - const module = it.value; - if (module === m) break; - newSet.add(module); - } - // check the remaining modules before adding - while (!(it = iterator.next()).done) { - const module = it.value; - if ( - availableModules.has(module) || - availableModules.plus.has(module) - ) { - newSet.add(module); - } - } - // also check all modules in cachedMinAvailableModules.plus - for (const module of cachedMinAvailableModules.plus) { - if ( - availableModules.has(module) || - availableModules.plus.has(module) - ) { - newSet.add(module); - } - } - statForkedResultModulesCount += newSet.size; - cachedMinAvailableModules = newSet; - info.minAvailableModulesOwned = true; - info.minAvailableModules = newSet; - changed = true; - continue merge; - } - } - for (const m of cachedMinAvailableModules.plus) { - if (!availableModules.has(m) && !availableModules.plus.has(m)) { - // cachedMinAvailableModules need to be modified - // but we don't own it - statForkedAvailableModules++; - statForkedAvailableModulesCount += - cachedMinAvailableModules.size; - statForkedAvailableModulesCountPlus += - cachedMinAvailableModules.plus.size; - statForkedMergedModulesCount += availableModules.size; - statForkedMergedModulesCountPlus += availableModules.plus.size; - // construct a new Set as intersection of cachedMinAvailableModules and availableModules - // we already know that all modules directly from cachedMinAvailableModules are in availableModules too - const newSet = /** @type {ModuleSetPlus} */ ( - new Set(cachedMinAvailableModules) - ); - newSet.plus = EMPTY_SET; - const iterator = - cachedMinAvailableModules.plus[Symbol.iterator](); - // fast forward add all modules until m - /** @type {IteratorResult} */ - let it; - while (!(it = iterator.next()).done) { - const module = it.value; - if (module === m) break; - newSet.add(module); - } - // check the remaining modules before adding - while (!(it = iterator.next()).done) { - const module = it.value; - if ( - availableModules.has(module) || - availableModules.plus.has(module) - ) { - newSet.add(module); - } - } - statForkedResultModulesCount += newSet.size; - cachedMinAvailableModules = newSet; - info.minAvailableModulesOwned = true; - info.minAvailableModules = newSet; - changed = true; - continue merge; - } - } - } - } - } - availableModulesToBeMerged.length = 0; - if (changed) { - info.resultingAvailableModules = undefined; - outdatedChunkGroupInfo.add(info); - } - } - chunkGroupsForMerging.clear(); - }; +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); - const processChunkGroupsForCombining = () => { - for (const info of chunkGroupsForCombining) { - for (const source of info.availableSources) { - if (!source.minAvailableModules) { - chunkGroupsForCombining.delete(info); - break; - } - } +class CssLoadingRuntimeModule extends RuntimeModule { + /** + * @param {Compilation} compilation the compilation + * @returns {JsonpCompilationPluginHooks} hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); } - for (const info of chunkGroupsForCombining) { - const availableModules = /** @type {ModuleSetPlus} */ (new Set()); - availableModules.plus = EMPTY_SET; - const mergeSet = set => { - if (set.size > availableModules.plus.size) { - for (const item of availableModules.plus) availableModules.add(item); - availableModules.plus = set; - } else { - for (const item of set) availableModules.add(item); - } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + createStylesheet: new SyncWaterfallHook(["source", "chunk"]) }; - // combine minAvailableModules from all resultingAvailableModules - for (const source of info.availableSources) { - const resultingAvailableModules = - calculateResultingAvailableModules(source); - mergeSet(resultingAvailableModules); - mergeSet(resultingAvailableModules.plus); - } - info.minAvailableModules = availableModules; - info.minAvailableModulesOwned = false; - info.resultingAvailableModules = undefined; - outdatedChunkGroupInfo.add(info); + compilationHooksMap.set(compilation, hooks); } - chunkGroupsForCombining.clear(); - }; + return hooks; + } - const processOutdatedChunkGroupInfo = () => { - statChunkGroupInfoUpdated += outdatedChunkGroupInfo.size; - // Revisit skipped elements - for (const info of outdatedChunkGroupInfo) { - // 1. Reconsider skipped items - if (info.skippedItems !== undefined) { - const { minAvailableModules } = info; - for (const module of info.skippedItems) { - if ( - !minAvailableModules.has(module) && - !minAvailableModules.plus.has(module) - ) { - queue.push({ - action: ADD_AND_ENTER_MODULE, - block: module, - module, - chunk: info.chunkGroup.chunks[0], - chunkGroup: info.chunkGroup, - chunkGroupInfo: info - }); - info.skippedItems.delete(module); - } - } - } + constructor(runtimeRequirements, runtimeOptions) { + super("css loading", 10); - // 2. Reconsider skipped connections - if (info.skippedModuleConnections !== undefined) { - const { minAvailableModules } = info; - for (const entry of info.skippedModuleConnections) { - const [module, activeState] = entry; - if (activeState === false) continue; - if (activeState === true) { - info.skippedModuleConnections.delete(entry); - } - if ( - activeState === true && - (minAvailableModules.has(module) || - minAvailableModules.plus.has(module)) - ) { - info.skippedItems.add(module); - continue; - } - queue.push({ - action: activeState === true ? ADD_AND_ENTER_MODULE : PROCESS_BLOCK, - block: module, - module, - chunk: info.chunkGroup.chunks[0], - chunkGroup: info.chunkGroup, - chunkGroupInfo: info - }); - } - } + this._runtimeRequirements = runtimeRequirements; + this.runtimeOptions = runtimeOptions; + } - // 2. Reconsider children chunk groups - if (info.children !== undefined) { - statChildChunkGroupsReconnected += info.children.size; - for (const cgi of info.children) { - let connectList = queueConnect.get(info); - if (connectList === undefined) { - connectList = new Set(); - queueConnect.set(info, connectList); - } - connectList.add(cgi); - } + /** + * @returns {string} runtime code + */ + generate() { + const { compilation, chunk, _runtimeRequirements } = this; + const { + chunkGraph, + runtimeTemplate, + outputOptions: { + crossOriginLoading, + uniqueName, + chunkLoadTimeout: loadTimeout } + } = compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const conditionMap = chunkGraph.getChunkConditionMap( + chunk, + (chunk, chunkGraph) => + !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css") + ); + const hasCssMatcher = compileBooleanMatcher(conditionMap); - // 3. Reconsider chunk groups for combining - if (info.availableChildren !== undefined) { - for (const cgi of info.availableChildren) { - chunkGroupsForCombining.add(cgi); - } - } + const withLoading = + _runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) && + hasCssMatcher !== false; + const withHmr = _runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const initialChunkIdsWithCss = new Set(); + const initialChunkIdsWithoutCss = new Set(); + for (const c of chunk.getAllInitialChunks()) { + (chunkHasCss(c, chunkGraph) + ? initialChunkIdsWithCss + : initialChunkIdsWithoutCss + ).add(c.id); } - outdatedChunkGroupInfo.clear(); - }; - - // Iterative traversal of the Module graph - // Recursive would be simpler to write but could result in Stack Overflows - while (queue.length || queueConnect.size) { - logger.time("visitModules: visiting"); - processQueue(); - logger.timeAggregateEnd("visitModules: prepare"); - logger.timeEnd("visitModules: visiting"); - if (chunkGroupsForCombining.size > 0) { - logger.time("visitModules: combine available modules"); - processChunkGroupsForCombining(); - logger.timeEnd("visitModules: combine available modules"); + if (!withLoading && !withHmr && initialChunkIdsWithCss.size === 0) { + return null; } - if (queueConnect.size > 0) { - logger.time("visitModules: calculating available modules"); - processConnectQueue(); - logger.timeEnd("visitModules: calculating available modules"); - - if (chunkGroupsForMerging.size > 0) { - logger.time("visitModules: merging available modules"); - processChunkGroupsForMerging(); - logger.timeEnd("visitModules: merging available modules"); - } - } + const { createStylesheet } = + CssLoadingRuntimeModule.getCompilationHooks(compilation); - if (outdatedChunkGroupInfo.size > 0) { - logger.time("visitModules: check modules for revisit"); - processOutdatedChunkGroupInfo(); - logger.timeEnd("visitModules: check modules for revisit"); - } + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_css` + : undefined; - // Run queueDelayed when all items of the queue are processed - // This is important to get the global indexing correct - // Async blocks should be processed after all sync blocks are processed - if (queue.length === 0) { - const tempQueue = queue; - queue = queueDelayed.reverse(); - queueDelayed = tempQueue; - } - } + const code = Template.asString([ + "link = document.createElement('link');", + uniqueName + ? 'link.setAttribute("data-webpack", uniqueName + ":" + key);' + : "", + "link.setAttribute(loadingAttribute, 1);", + 'link.rel = "stylesheet";', + "link.href = url;", + crossOriginLoading + ? Template.asString([ + "if (link.src.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` + ), + "}" + ]) + : "" + ]); - logger.log( - `${statProcessedQueueItems} queue items processed (${statProcessedBlocks} blocks)` - ); - logger.log(`${statConnectedChunkGroups} chunk groups connected`); - logger.log( - `${statProcessedChunkGroupsForMerging} chunk groups processed for merging (${statMergedAvailableModuleSets} module sets, ${statForkedAvailableModules} forked, ${statForkedAvailableModulesCount} + ${statForkedAvailableModulesCountPlus} modules forked, ${statForkedMergedModulesCount} + ${statForkedMergedModulesCountPlus} modules merged into fork, ${statForkedResultModulesCount} resulting modules)` - ); - logger.log( - `${statChunkGroupInfoUpdated} chunk group info updated (${statChildChunkGroupsReconnected} already connected chunk groups reconnected)` - ); -}; + const cc = str => str.charCodeAt(0); -/** - * - * @param {Compilation} compilation the compilation - * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks - * @param {Map} blockConnections connection for blocks - * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules - */ -const connectChunkGroups = ( - compilation, - blocksWithNestedBlocks, - blockConnections, - chunkGroupInfoMap -) => { - const { chunkGraph } = compilation; - - /** - * Helper function to check if all modules of a chunk are available - * - * @param {ChunkGroup} chunkGroup the chunkGroup to scan - * @param {ModuleSetPlus} availableModules the comparator set - * @returns {boolean} return true if all modules of a chunk are available - */ - const areModulesAvailable = (chunkGroup, availableModules) => { - for (const chunk of chunkGroup.chunks) { - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - if (!availableModules.has(module) && !availableModules.plus.has(module)) - return false; - } - } - return true; - }; - - // For each edge in the basic chunk graph - for (const [block, connections] of blockConnections) { - // 1. Check if connection is needed - // When none of the dependencies need to be connected - // we can skip all of them - // It's not possible to filter each item so it doesn't create inconsistent - // connections and modules can only create one version - // TODO maybe decide this per runtime - if ( - // TODO is this needed? - !blocksWithNestedBlocks.has(block) && - connections.every(({ chunkGroup, originChunkGroupInfo }) => - areModulesAvailable( - chunkGroup, - originChunkGroupInfo.resultingAvailableModules - ) - ) - ) { - continue; - } - - // 2. Foreach edge - for (let i = 0; i < connections.length; i++) { - const { chunkGroup, originChunkGroupInfo } = connections[i]; - - // 3. Connect block with chunk - chunkGraph.connectBlockAndChunkGroup(block, chunkGroup); - - // 4. Connect chunk with parent - connectChunkGroupParentAndChild( - originChunkGroupInfo.chunkGroup, - chunkGroup - ); - } + return Template.asString([ + "// object to store loaded and loading chunks", + "// undefined = chunk not loaded, null = chunk preloaded/prefetched", + "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{${Array.from( + initialChunkIdsWithoutCss, + id => `${JSON.stringify(id)}:0` + ).join(",")}};`, + "", + uniqueName + ? `var uniqueName = ${JSON.stringify( + runtimeTemplate.outputOptions.uniqueName + )};` + : "// data-webpack is not used as build has no uniqueName", + `var loadCssChunkData = ${runtimeTemplate.basicFunction( + "target, link, chunkId", + [ + `var data, token = "", token2, exports = {}, exportsWithId = [], exportsWithDashes = [], ${ + withHmr ? "moduleIds = [], " : "" + }i = 0, cc = 1;`, + "try { if(!link) link = loadStylesheet(chunkId); data = link.sheet.cssRules; data = data[data.length - 1].style; } catch(e) { data = getComputedStyle(document.head); }", + `data = data.getPropertyValue(${ + uniqueName + ? runtimeTemplate.concatenation( + "--webpack-", + { expr: "uniqueName" }, + "-", + { expr: "chunkId" } + ) + : runtimeTemplate.concatenation("--webpack-", { expr: "chunkId" }) + });`, + "if(!data) return [];", + "for(; cc; i++) {", + Template.indent([ + "cc = data.charCodeAt(i);", + `if(cc == ${cc("(")}) { token2 = token; token = ""; }`, + `else if(cc == ${cc( + ")" + )}) { exports[token2.replace(/^_/, "")] = token.replace(/^_/, ""); token = ""; }`, + `else if(cc == ${cc("/")} || cc == ${cc( + "%" + )}) { token = token.replace(/^_/, ""); exports[token] = token; exportsWithId.push(token); if(cc == ${cc( + "%" + )}) exportsWithDashes.push(token); token = ""; }`, + `else if(!cc || cc == ${cc( + "," + )}) { token = token.replace(/^_/, ""); exportsWithId.forEach(${runtimeTemplate.expressionFunction( + `exports[x] = ${ + uniqueName + ? runtimeTemplate.concatenation( + { expr: "uniqueName" }, + "-", + { expr: "token" }, + "-", + { expr: "exports[x]" } + ) + : runtimeTemplate.concatenation({ expr: "token" }, "-", { + expr: "exports[x]" + }) + }`, + "x" + )}); exportsWithDashes.forEach(${runtimeTemplate.expressionFunction( + `exports[x] = "--" + exports[x]`, + "x" + )}); ${ + RuntimeGlobals.makeNamespaceObject + }(exports); target[token] = (${runtimeTemplate.basicFunction( + "exports, module", + `module.exports = exports;` + )}).bind(null, exports); ${ + withHmr ? "moduleIds.push(token); " : "" + }token = ""; exports = {}; exportsWithId.length = 0; }`, + `else if(cc == ${cc("\\")}) { token += data[++i] }`, + `else { token += data[i]; }` + ]), + "}", + `${ + withHmr ? `if(target == ${RuntimeGlobals.moduleFactories}) ` : "" + }installedChunks[chunkId] = 0;`, + withHmr ? "return moduleIds;" : "" + ] + )}`, + 'var loadingAttribute = "data-webpack-loading";', + `var loadStylesheet = ${runtimeTemplate.basicFunction( + "chunkId, url, done" + (withHmr ? ", hmr" : ""), + [ + 'var link, needAttach, key = "chunk-" + chunkId;', + withHmr ? "if(!hmr) {" : "", + 'var links = document.getElementsByTagName("link");', + "for(var i = 0; i < links.length; i++) {", + Template.indent([ + "var l = links[i];", + `if(l.rel == "stylesheet" && (${ + withHmr + ? 'l.href.startsWith(url) || l.getAttribute("href").startsWith(url)' + : 'l.href == url || l.getAttribute("href") == url' + }${ + uniqueName + ? ' || l.getAttribute("data-webpack") == uniqueName + ":" + key' + : "" + })) { link = l; break; }` + ]), + "}", + "if(!done) return link;", + withHmr ? "}" : "", + "if(!link) {", + Template.indent([ + "needAttach = true;", + createStylesheet.call(code, this.chunk) + ]), + "}", + `var onLinkComplete = ${runtimeTemplate.basicFunction( + "prev, event", + Template.asString([ + "link.onerror = link.onload = null;", + "link.removeAttribute(loadingAttribute);", + "clearTimeout(timeout);", + 'if(event && event.type != "load") link.parentNode.removeChild(link)', + "done(event);", + "if(prev) return prev(event);" + ]) + )};`, + "if(link.getAttribute(loadingAttribute)) {", + Template.indent([ + `var timeout = setTimeout(onLinkComplete.bind(null, undefined, { type: 'timeout', target: link }), ${loadTimeout});`, + "link.onerror = onLinkComplete.bind(null, link.onerror);", + "link.onload = onLinkComplete.bind(null, link.onload);" + ]), + "} else onLinkComplete(undefined, { type: 'load', target: link });", // We assume any existing stylesheet is render blocking + withHmr ? "hmr ? document.head.insertBefore(link, hmr) :" : "", + "needAttach && document.head.appendChild(link);", + "return link;" + ] + )};`, + initialChunkIdsWithCss.size > 2 + ? `${JSON.stringify( + Array.from(initialChunkIdsWithCss) + )}.forEach(loadCssChunkData.bind(null, ${ + RuntimeGlobals.moduleFactories + }, 0));` + : initialChunkIdsWithCss.size > 0 + ? `${Array.from( + initialChunkIdsWithCss, + id => + `loadCssChunkData(${ + RuntimeGlobals.moduleFactories + }, 0, ${JSON.stringify(id)});` + ).join("")}` + : "// no initial css", + "", + withLoading + ? Template.asString([ + `${fn}.css = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasCssMatcher !== false + ? [ + "// css chunk loading", + `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + "", + '// a Promise means "currently loading".', + "if(installedChunkData) {", + Template.indent([ + "promises.push(installedChunkData[2]);" + ]), + "} else {", + Template.indent([ + hasCssMatcher === true + ? "if(true) { // all chunks have CSS" + : `if(${hasCssMatcher("chunkId")}) {`, + Template.indent([ + "// setup Promise in chunk cache", + `var promise = new Promise(${runtimeTemplate.expressionFunction( + `installedChunkData = installedChunks[chunkId] = [resolve, reject]`, + "resolve, reject" + )});`, + "promises.push(installedChunkData[2] = promise);", + "", + "// start chunk loading", + `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, + "// create error before stack unwound to get useful stacktrace later", + "var error = new Error();", + `var loadingEnded = ${runtimeTemplate.basicFunction( + "event", + [ + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`, + Template.indent([ + "installedChunkData = installedChunks[chunkId];", + "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;", + "if(installedChunkData) {", + Template.indent([ + 'if(event.type !== "load") {', + Template.indent([ + "var errorType = event && event.type;", + "var realSrc = event && event.target && event.target.src;", + "error.message = 'Loading css chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realSrc;", + "installedChunkData[1](error);" + ]), + "} else {", + Template.indent([ + `loadCssChunkData(${RuntimeGlobals.moduleFactories}, link, chunkId);`, + "installedChunkData[0]();" + ]), + "}" + ]), + "}" + ]), + "}" + ] + )};`, + "var link = loadStylesheet(chunkId, url, loadingEnded);" + ]), + "} else installedChunks[chunkId] = 0;" + ]), + "}" + ]), + "}" + ] + : "installedChunks[chunkId] = 0;" + )};` + ]) + : "// no chunk loading", + "", + withHmr + ? Template.asString([ + "var oldTags = [];", + "var newTags = [];", + `var applyHandler = ${runtimeTemplate.basicFunction("options", [ + `return { dispose: ${runtimeTemplate.basicFunction( + "", + [] + )}, apply: ${runtimeTemplate.basicFunction("", [ + "var moduleIds = [];", + `newTags.forEach(${runtimeTemplate.expressionFunction( + "info[1].sheet.disabled = false", + "info" + )});`, + "while(oldTags.length) {", + Template.indent([ + "var oldTag = oldTags.pop();", + "if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);" + ]), + "}", + "while(newTags.length) {", + Template.indent([ + `var info = newTags.pop();`, + `var chunkModuleIds = loadCssChunkData(${RuntimeGlobals.moduleFactories}, info[1], info[0]);`, + `chunkModuleIds.forEach(${runtimeTemplate.expressionFunction( + "moduleIds.push(id)", + "id" + )});` + ]), + "}", + "return moduleIds;" + ])} };` + ])}`, + `var cssTextKey = ${runtimeTemplate.returningFunction( + `Array.from(link.sheet.cssRules, ${runtimeTemplate.returningFunction( + "r.cssText", + "r" + )}).join()`, + "link" + )}`, + `${ + RuntimeGlobals.hmrDownloadUpdateHandlers + }.css = ${runtimeTemplate.basicFunction( + "chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList", + [ + "applyHandlers.push(applyHandler);", + `chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [ + `var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, + `var url = ${RuntimeGlobals.publicPath} + filename;`, + "var oldTag = loadStylesheet(chunkId, url);", + "if(!oldTag) return;", + `promises.push(new Promise(${runtimeTemplate.basicFunction( + "resolve, reject", + [ + `var link = loadStylesheet(chunkId, url + (url.indexOf("?") < 0 ? "?" : "&") + "hmr=" + Date.now(), ${runtimeTemplate.basicFunction( + "event", + [ + 'if(event.type !== "load") {', + Template.indent([ + "var errorType = event && event.type;", + "var realSrc = event && event.target && event.target.src;", + "error.message = 'Loading css hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realSrc;", + "reject(error);" + ]), + "} else {", + Template.indent([ + "try { if(cssTextKey(oldTag) == cssTextKey(link)) { if(link.parentNode) link.parentNode.removeChild(link); return resolve(); } } catch(e) {}", + "var factories = {};", + "loadCssChunkData(factories, link, chunkId);", + `Object.keys(factories).forEach(${runtimeTemplate.expressionFunction( + "updatedModulesList.push(id)", + "id" + )})`, + "link.sheet.disabled = true;", + "oldTags.push(oldTag);", + "newTags.push([chunkId, link]);", + "resolve();" + ]), + "}" + ] + )}, oldTag);` + ] + )}));` + ])});` + ] + )}` + ]) + : "// no hmr" + ]); } -}; - -/** - * Remove all unconnected chunk groups - * @param {Compilation} compilation the compilation - * @param {Iterable} allCreatedChunkGroups all chunk groups that where created before - */ -const cleanupUnconnectedGroups = (compilation, allCreatedChunkGroups) => { - const { chunkGraph } = compilation; +} - for (const chunkGroup of allCreatedChunkGroups) { - if (chunkGroup.getNumberOfParents() === 0) { - for (const chunk of chunkGroup.chunks) { - compilation.chunks.delete(chunk); - chunkGraph.disconnectChunk(chunk); - } - chunkGraph.disconnectChunkGroup(chunkGroup); - chunkGroup.remove(); - } - } -}; +module.exports = CssLoadingRuntimeModule; -/** - * This method creates the Chunk graph from the Module graph - * @param {Compilation} compilation the compilation - * @param {Map} inputEntrypointsAndModules chunk groups which are processed with the modules - * @returns {void} - */ -const buildChunkGraph = (compilation, inputEntrypointsAndModules) => { - const logger = compilation.getLogger("webpack.buildChunkGraph"); - // SHARED STATE +/***/ }), - /** @type {Map} */ - const blockConnections = new Map(); +/***/ 47283: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {Set} */ - const allCreatedChunkGroups = new Set(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {Map} */ - const chunkGroupInfoMap = new Map(); - /** @type {Set} */ - const blocksWithNestedBlocks = new Set(); - // PART ONE +const { ConcatSource } = __webpack_require__(51255); +const HotUpdateChunk = __webpack_require__(9597); +const RuntimeGlobals = __webpack_require__(16475); +const SelfModuleFactory = __webpack_require__(63560); +const CssExportDependency = __webpack_require__(76760); +const CssImportDependency = __webpack_require__(90542); +const CssLocalIdentifierDependency = __webpack_require__(92328); +const CssSelfLocalIdentifierDependency = __webpack_require__(29094); +const CssUrlDependency = __webpack_require__(70749); +const StaticExportsDependency = __webpack_require__(91418); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); +const createHash = __webpack_require__(49835); +const memoize = __webpack_require__(78676); +const CssExportsGenerator = __webpack_require__(91254); +const CssGenerator = __webpack_require__(46061); +const CssParser = __webpack_require__(98305); - logger.time("visitModules"); - visitModules( - logger, - compilation, - inputEntrypointsAndModules, - chunkGroupInfoMap, - blockConnections, - blocksWithNestedBlocks, - allCreatedChunkGroups - ); - logger.timeEnd("visitModules"); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").CssExperimentOptions} CssExperimentOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ - // PART TWO +const getCssLoadingRuntimeModule = memoize(() => + __webpack_require__(80806) +); - logger.time("connectChunkGroups"); - connectChunkGroups( - compilation, - blocksWithNestedBlocks, - blockConnections, - chunkGroupInfoMap - ); - logger.timeEnd("connectChunkGroups"); +const getSchema = name => { + const { definitions } = __webpack_require__(73342); + return { + definitions, + oneOf: [{ $ref: `#/definitions/${name}` }] + }; +}; - for (const [chunkGroup, chunkGroupInfo] of chunkGroupInfoMap) { - for (const chunk of chunkGroup.chunks) - chunk.runtime = mergeRuntime(chunk.runtime, chunkGroupInfo.runtime); +const validateGeneratorOptions = createSchemaValidation( + __webpack_require__(59170), + () => getSchema("CssGeneratorOptions"), + { + name: "Css Modules Plugin", + baseDataPath: "parser" } +); +const validateParserOptions = createSchemaValidation( + __webpack_require__(38542), + () => getSchema("CssParserOptions"), + { + name: "Css Modules Plugin", + baseDataPath: "parser" + } +); - // Cleanup work - - logger.time("cleanup"); - cleanupUnconnectedGroups(compilation, allCreatedChunkGroups); - logger.timeEnd("cleanup"); +const escapeCss = (str, omitOptionalUnderscore) => { + const escaped = `${str}`.replace( + // cspell:word uffff + /[^a-zA-Z0-9_\u0081-\uffff-]/g, + s => `\\${s}` + ); + return !omitOptionalUnderscore && /^(?!--)[0-9_-]/.test(escaped) + ? `_${escaped}` + : escaped; }; -module.exports = buildChunkGraph; - - -/***/ }), - -/***/ 28034: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @typedef {import("../Compiler")} Compiler */ +const plugin = "CssModulesPlugin"; -class AddBuildDependenciesPlugin { +class CssModulesPlugin { /** - * @param {Iterable} buildDependencies list of build dependencies + * @param {CssExperimentOptions} options options */ - constructor(buildDependencies) { - this.buildDependencies = new Set(buildDependencies); + constructor({ exportsOnly = false }) { + this._exportsOnly = exportsOnly; } - /** * Apply the plugin * @param {Compiler} compiler the compiler instance @@ -67791,63 +68285,385 @@ class AddBuildDependenciesPlugin { */ apply(compiler) { compiler.hooks.compilation.tap( - "AddBuildDependenciesPlugin", - compilation => { - compilation.buildDependencies.addAll(this.buildDependencies); + plugin, + (compilation, { normalModuleFactory }) => { + const selfFactory = new SelfModuleFactory(compilation.moduleGraph); + compilation.dependencyFactories.set( + CssUrlDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CssUrlDependency, + new CssUrlDependency.Template() + ); + compilation.dependencyTemplates.set( + CssLocalIdentifierDependency, + new CssLocalIdentifierDependency.Template() + ); + compilation.dependencyFactories.set( + CssSelfLocalIdentifierDependency, + selfFactory + ); + compilation.dependencyTemplates.set( + CssSelfLocalIdentifierDependency, + new CssSelfLocalIdentifierDependency.Template() + ); + compilation.dependencyTemplates.set( + CssExportDependency, + new CssExportDependency.Template() + ); + compilation.dependencyFactories.set( + CssImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CssImportDependency, + new CssImportDependency.Template() + ); + compilation.dependencyTemplates.set( + StaticExportsDependency, + new StaticExportsDependency.Template() + ); + normalModuleFactory.hooks.createParser + .for("css") + .tap(plugin, parserOptions => { + validateParserOptions(parserOptions); + return new CssParser(); + }); + normalModuleFactory.hooks.createParser + .for("css/global") + .tap(plugin, parserOptions => { + validateParserOptions(parserOptions); + return new CssParser({ + allowPseudoBlocks: false, + allowModeSwitch: false + }); + }); + normalModuleFactory.hooks.createParser + .for("css/module") + .tap(plugin, parserOptions => { + validateParserOptions(parserOptions); + return new CssParser({ + defaultMode: "local" + }); + }); + normalModuleFactory.hooks.createGenerator + .for("css") + .tap(plugin, generatorOptions => { + validateGeneratorOptions(generatorOptions); + return this._exportsOnly + ? new CssExportsGenerator() + : new CssGenerator(); + }); + normalModuleFactory.hooks.createGenerator + .for("css/global") + .tap(plugin, generatorOptions => { + validateGeneratorOptions(generatorOptions); + return this._exportsOnly + ? new CssExportsGenerator() + : new CssGenerator(); + }); + normalModuleFactory.hooks.createGenerator + .for("css/module") + .tap(plugin, generatorOptions => { + validateGeneratorOptions(generatorOptions); + return this._exportsOnly + ? new CssExportsGenerator() + : new CssGenerator(); + }); + const orderedCssModulesPerChunk = new WeakMap(); + compilation.hooks.afterCodeGeneration.tap("CssModulesPlugin", () => { + const { chunkGraph } = compilation; + for (const chunk of compilation.chunks) { + if (CssModulesPlugin.chunkHasCss(chunk, chunkGraph)) { + orderedCssModulesPerChunk.set( + chunk, + this.getOrderedChunkCssModules(chunk, chunkGraph, compilation) + ); + } + } + }); + compilation.hooks.contentHash.tap("CssModulesPlugin", chunk => { + const { + chunkGraph, + outputOptions: { + hashSalt, + hashDigest, + hashDigestLength, + hashFunction + } + } = compilation; + const modules = orderedCssModulesPerChunk.get(chunk); + if (modules === undefined) return; + const hash = createHash(hashFunction); + if (hashSalt) hash.update(hashSalt); + for (const module of modules) { + hash.update(chunkGraph.getModuleHash(module, chunk.runtime)); + } + const digest = /** @type {string} */ (hash.digest(hashDigest)); + chunk.contentHash.css = digest.substr(0, hashDigestLength); + }); + compilation.hooks.renderManifest.tap(plugin, (result, options) => { + const { chunkGraph } = compilation; + const { hash, chunk, codeGenerationResults } = options; + + if (chunk instanceof HotUpdateChunk) return result; + + const modules = orderedCssModulesPerChunk.get(chunk); + if (modules !== undefined) { + result.push({ + render: () => + this.renderChunk({ + chunk, + chunkGraph, + codeGenerationResults, + uniqueName: compilation.outputOptions.uniqueName, + modules + }), + filenameTemplate: CssModulesPlugin.getChunkFilenameTemplate( + chunk, + compilation.outputOptions + ), + pathOptions: { + hash, + runtime: chunk.runtime, + chunk, + contentHashType: "css" + }, + identifier: `css${chunk.id}`, + hash: chunk.contentHash.css + }); + } + return result; + }); + const enabledChunks = new WeakSet(); + const handler = (chunk, set) => { + if (enabledChunks.has(chunk)) { + return; + } + enabledChunks.add(chunk); + + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getChunkCssFilename); + set.add(RuntimeGlobals.hasOwnProperty); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.makeNamespaceObject); + + const CssLoadingRuntimeModule = getCssLoadingRuntimeModule(); + compilation.addRuntimeModule(chunk, new CssLoadingRuntimeModule(set)); + }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hasCssModules) + .tap(plugin, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(plugin, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap(plugin, handler); } ); } -} -module.exports = AddBuildDependenciesPlugin; + getModulesInOrder(chunk, modules, compilation) { + if (!modules) return []; + const modulesList = [...modules]; -/***/ }), + // Get ordered list of modules per chunk group + // Lists are in reverse order to allow to use Array.pop() + const modulesByChunkGroup = Array.from(chunk.groupsIterable, chunkGroup => { + const sortedModules = modulesList + .map(module => { + return { + module, + index: chunkGroup.getModulePostOrderIndex(module) + }; + }) + .filter(item => item.index !== undefined) + .sort((a, b) => b.index - a.index) + .map(item => item.module); -/***/ 47942: -/***/ (function(module) { + return { list: sortedModules, set: new Set(sortedModules) }; + }); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (modulesByChunkGroup.length === 1) + return modulesByChunkGroup[0].list.reverse(); + const compareModuleLists = ({ list: a }, { list: b }) => { + if (a.length === 0) { + return b.length === 0 ? 0 : 1; + } else { + if (b.length === 0) return -1; + return compareModulesByIdentifier(a[a.length - 1], b[b.length - 1]); + } + }; + modulesByChunkGroup.sort(compareModuleLists); -/** @typedef {import("../Compiler")} Compiler */ + const finalModules = []; -class AddManagedPathsPlugin { - /** - * @param {Iterable} managedPaths list of managed paths - * @param {Iterable} immutablePaths list of immutable paths - */ - constructor(managedPaths, immutablePaths) { - this.managedPaths = new Set(managedPaths); - this.immutablePaths = new Set(immutablePaths); + for (;;) { + const failedModules = new Set(); + const list = modulesByChunkGroup[0].list; + if (list.length === 0) { + // done, everything empty + break; + } + let selectedModule = list[list.length - 1]; + let hasFailed = undefined; + outer: for (;;) { + for (const { list, set } of modulesByChunkGroup) { + if (list.length === 0) continue; + const lastModule = list[list.length - 1]; + if (lastModule === selectedModule) continue; + if (!set.has(selectedModule)) continue; + failedModules.add(selectedModule); + if (failedModules.has(lastModule)) { + // There is a conflict, try other alternatives + hasFailed = lastModule; + continue; + } + selectedModule = lastModule; + hasFailed = false; + continue outer; // restart + } + break; + } + if (hasFailed) { + // There is a not resolve-able conflict with the selectedModule + if (compilation) { + // TODO print better warning + compilation.warnings.push( + new Error( + `chunk ${ + chunk.name || chunk.id + }\nConflicting order between ${hasFailed.readableIdentifier( + compilation.requestShortener + )} and ${selectedModule.readableIdentifier( + compilation.requestShortener + )}` + ) + ); + } + selectedModule = hasFailed; + } + // Insert the selected module into the final modules list + finalModules.push(selectedModule); + // Remove the selected module from all lists + for (const { list, set } of modulesByChunkGroup) { + const lastModule = list[list.length - 1]; + if (lastModule === selectedModule) list.pop(); + else if (hasFailed && set.has(selectedModule)) { + const idx = list.indexOf(selectedModule); + if (idx >= 0) list.splice(idx, 1); + } + } + modulesByChunkGroup.sort(compareModuleLists); + } + return finalModules; } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - for (const managedPath of this.managedPaths) { - compiler.managedPaths.add(managedPath); + getOrderedChunkCssModules(chunk, chunkGraph, compilation) { + return [ + ...this.getModulesInOrder( + chunk, + chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "css-import", + compareModulesByIdentifier + ), + compilation + ), + ...this.getModulesInOrder( + chunk, + chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "css", + compareModulesByIdentifier + ), + compilation + ) + ]; + } + + renderChunk({ + uniqueName, + chunk, + chunkGraph, + codeGenerationResults, + modules + }) { + const source = new ConcatSource(); + const metaData = []; + for (const module of modules) { + try { + const codeGenResult = codeGenerationResults.get(module, chunk.runtime); + + const s = + codeGenResult.sources.get("css") || + codeGenResult.sources.get("css-import"); + if (s) { + source.add(s); + source.add("\n"); + } + const exports = + codeGenResult.data && codeGenResult.data.get("css-exports"); + const moduleId = chunkGraph.getModuleId(module) + ""; + metaData.push( + `${ + exports + ? Array.from(exports, ([n, v]) => { + const shortcutValue = `${ + uniqueName ? uniqueName + "-" : "" + }${moduleId}-${n}`; + return v === shortcutValue + ? `${escapeCss(n)}/` + : v === "--" + shortcutValue + ? `${escapeCss(n)}%` + : `${escapeCss(n)}(${escapeCss(v)})`; + }).join("") + : "" + }${escapeCss(moduleId)}` + ); + } catch (e) { + e.message += `\nduring rendering of css ${module.identifier()}`; + throw e; + } } - for (const immutablePath of this.immutablePaths) { - compiler.immutablePaths.add(immutablePath); + source.add( + `head{--webpack-${escapeCss( + (uniqueName ? uniqueName + "-" : "") + chunk.id, + true + )}:${metaData.join(",")};}` + ); + return source; + } + + static getChunkFilenameTemplate(chunk, outputOptions) { + if (chunk.cssFilenameTemplate) { + return chunk.cssFilenameTemplate; + } else if (chunk.canBeInitial()) { + return outputOptions.cssFilename; + } else { + return outputOptions.cssChunkFilename; } } + + static chunkHasCss(chunk, chunkGraph) { + return ( + !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css") || + !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css-import") + ); + } } -module.exports = AddManagedPathsPlugin; +module.exports = CssModulesPlugin; /***/ }), -/***/ 71985: +/***/ 98305: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -67858,434 +68674,623 @@ module.exports = AddManagedPathsPlugin; -const Cache = __webpack_require__(7592); -const ProgressPlugin = __webpack_require__(13216); - -/** @typedef {import("../Compiler")} Compiler */ - -const BUILD_DEPENDENCIES_KEY = Symbol(); - -class IdleFileCachePlugin { - /** - * @param {TODO} strategy cache strategy - * @param {number} idleTimeout timeout - * @param {number} idleTimeoutForInitialStore initial timeout - * @param {number} idleTimeoutAfterLargeChanges timeout after changes - */ - constructor( - strategy, - idleTimeout, - idleTimeoutForInitialStore, - idleTimeoutAfterLargeChanges - ) { - this.strategy = strategy; - this.idleTimeout = idleTimeout; - this.idleTimeoutForInitialStore = idleTimeoutForInitialStore; - this.idleTimeoutAfterLargeChanges = idleTimeoutAfterLargeChanges; - } +const Parser = __webpack_require__(11715); +const ConstDependency = __webpack_require__(76911); +const CssExportDependency = __webpack_require__(76760); +const CssImportDependency = __webpack_require__(90542); +const CssLocalIdentifierDependency = __webpack_require__(92328); +const CssSelfLocalIdentifierDependency = __webpack_require__(29094); +const CssUrlDependency = __webpack_require__(70749); +const StaticExportsDependency = __webpack_require__(91418); +const walkCssTokens = __webpack_require__(44124); - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - let strategy = this.strategy; - const idleTimeout = this.idleTimeout; - const idleTimeoutForInitialStore = Math.min( - idleTimeout, - this.idleTimeoutForInitialStore - ); - const idleTimeoutAfterLargeChanges = this.idleTimeoutAfterLargeChanges; - const resolvedPromise = Promise.resolve(); +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ - let timeSpendInBuild = 0; - let timeSpendInStore = 0; - let avgTimeSpendInStore = 0; +const CC_LEFT_CURLY = "{".charCodeAt(0); +const CC_RIGHT_CURLY = "}".charCodeAt(0); +const CC_COLON = ":".charCodeAt(0); +const CC_SLASH = "/".charCodeAt(0); +const CC_SEMICOLON = ";".charCodeAt(0); - /** @type {Map Promise>} */ - const pendingIdleTasks = new Map(); +const cssUnescape = str => { + return str.replace(/\\([0-9a-fA-F]{1,6}[ \t\n\r\f]?|[\s\S])/g, match => { + if (match.length > 2) { + return String.fromCharCode(parseInt(match.slice(1).trim(), 16)); + } else { + return match[1]; + } + }); +}; - compiler.cache.hooks.store.tap( - { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, - (identifier, etag, data) => { - pendingIdleTasks.set(identifier, () => - strategy.store(identifier, etag, data) - ); - } - ); +class LocConverter { + constructor(input) { + this._input = input; + this.line = 1; + this.column = 0; + this.pos = 0; + } - compiler.cache.hooks.get.tapPromise( - { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, - (identifier, etag, gotHandlers) => { - const restore = () => - strategy.restore(identifier, etag).then(cacheEntry => { - if (cacheEntry === undefined) { - gotHandlers.push((result, callback) => { - if (result !== undefined) { - pendingIdleTasks.set(identifier, () => - strategy.store(identifier, etag, result) - ); - } - callback(); - }); - } else { - return cacheEntry; - } - }); - const pendingTask = pendingIdleTasks.get(identifier); - if (pendingTask !== undefined) { - pendingIdleTasks.delete(identifier); - return pendingTask().then(restore); - } - return restore(); - } - ); - - compiler.cache.hooks.storeBuildDependencies.tap( - { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, - dependencies => { - pendingIdleTasks.set(BUILD_DEPENDENCIES_KEY, () => - strategy.storeBuildDependencies(dependencies) - ); - } - ); - - compiler.cache.hooks.shutdown.tapPromise( - { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, - () => { - if (idleTimer) { - clearTimeout(idleTimer); - idleTimer = undefined; - } - isIdle = false; - const reportProgress = ProgressPlugin.getReporter(compiler); - const jobs = Array.from(pendingIdleTasks.values()); - if (reportProgress) reportProgress(0, "process pending cache items"); - const promises = jobs.map(fn => fn()); - pendingIdleTasks.clear(); - promises.push(currentIdlePromise); - const promise = Promise.all(promises); - currentIdlePromise = promise.then(() => strategy.afterAllStored()); - if (reportProgress) { - currentIdlePromise = currentIdlePromise.then(() => { - reportProgress(1, `stored`); - }); - } - return currentIdlePromise.then(() => { - // Reset strategy - if (strategy.clear) strategy.clear(); - }); - } - ); - - /** @type {Promise} */ - let currentIdlePromise = resolvedPromise; - let isIdle = false; - let isInitialStore = true; - const processIdleTasks = () => { - if (isIdle) { - const startTime = Date.now(); - if (pendingIdleTasks.size > 0) { - const promises = [currentIdlePromise]; - const maxTime = startTime + 100; - let maxCount = 100; - for (const [filename, factory] of pendingIdleTasks) { - pendingIdleTasks.delete(filename); - promises.push(factory()); - if (maxCount-- <= 0 || Date.now() > maxTime) break; - } - currentIdlePromise = Promise.all(promises); - currentIdlePromise.then(() => { - timeSpendInStore += Date.now() - startTime; - // Allow to exit the process between - idleTimer = setTimeout(processIdleTasks, 0); - idleTimer.unref(); - }); - return; - } - currentIdlePromise = currentIdlePromise - .then(async () => { - await strategy.afterAllStored(); - timeSpendInStore += Date.now() - startTime; - avgTimeSpendInStore = - Math.max(avgTimeSpendInStore, timeSpendInStore) * 0.9 + - timeSpendInStore * 0.1; - timeSpendInStore = 0; - timeSpendInBuild = 0; - }) - .catch(err => { - const logger = compiler.getInfrastructureLogger( - "IdleFileCachePlugin" - ); - logger.warn(`Background tasks during idle failed: ${err.message}`); - logger.debug(err.stack); - }); - isInitialStore = false; - } - }; - let idleTimer = undefined; - compiler.cache.hooks.beginIdle.tap( - { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, - () => { - const isLargeChange = timeSpendInBuild > avgTimeSpendInStore * 2; - if (isInitialStore && idleTimeoutForInitialStore < idleTimeout) { - compiler - .getInfrastructureLogger("IdleFileCachePlugin") - .log( - `Initial cache was generated and cache will be persisted in ${ - idleTimeoutForInitialStore / 1000 - }s.` - ); - } else if ( - isLargeChange && - idleTimeoutAfterLargeChanges < idleTimeout - ) { - compiler - .getInfrastructureLogger("IdleFileCachePlugin") - .log( - `Spend ${Math.round(timeSpendInBuild) / 1000}s in build and ${ - Math.round(avgTimeSpendInStore) / 1000 - }s in average in cache store. This is considered as large change and cache will be persisted in ${ - idleTimeoutAfterLargeChanges / 1000 - }s.` - ); + get(pos) { + if (this.pos !== pos) { + if (this.pos < pos) { + const str = this._input.slice(this.pos, pos); + let i = str.lastIndexOf("\n"); + if (i === -1) { + this.column += str.length; + } else { + this.column = str.length - i - 1; + this.line++; + while (i > 0 && (i = str.lastIndexOf("\n", i - 1)) !== -1) + this.line++; } - idleTimer = setTimeout(() => { - idleTimer = undefined; - isIdle = true; - resolvedPromise.then(processIdleTasks); - }, Math.min(isInitialStore ? idleTimeoutForInitialStore : Infinity, isLargeChange ? idleTimeoutAfterLargeChanges : Infinity, idleTimeout)); - idleTimer.unref(); - } - ); - compiler.cache.hooks.endIdle.tap( - { name: "IdleFileCachePlugin", stage: Cache.STAGE_DISK }, - () => { - if (idleTimer) { - clearTimeout(idleTimer); - idleTimer = undefined; + } else { + let i = this._input.lastIndexOf("\n", this.pos); + while (i >= pos) { + this.line--; + i = i > 0 ? this._input.lastIndexOf("\n", i - 1) : -1; } - isIdle = false; + this.column = pos - i; } - ); - compiler.hooks.done.tap("IdleFileCachePlugin", stats => { - // 10% build overhead is ignored, as it's not cacheable - timeSpendInBuild *= 0.9; - timeSpendInBuild += stats.endTime - stats.startTime; - }); + this.pos = pos; + } + return this; } } -module.exports = IdleFileCachePlugin; - - -/***/ }), - -/***/ 52539: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const CSS_MODE_TOP_LEVEL = 0; +const CSS_MODE_IN_RULE = 1; +const CSS_MODE_IN_LOCAL_RULE = 2; +const CSS_MODE_AT_IMPORT_EXPECT_URL = 3; +// TODO implement layer and supports for @import +const CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS = 4; +const CSS_MODE_AT_IMPORT_EXPECT_MEDIA = 5; +const CSS_MODE_AT_OTHER = 6; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const explainMode = mode => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: + return "parsing top level css"; + case CSS_MODE_IN_RULE: + return "parsing css rule content (global)"; + case CSS_MODE_IN_LOCAL_RULE: + return "parsing css rule content (local)"; + case CSS_MODE_AT_IMPORT_EXPECT_URL: + return "parsing @import (expecting url)"; + case CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS: + return "parsing @import (expecting optionally supports or media query)"; + case CSS_MODE_AT_IMPORT_EXPECT_MEDIA: + return "parsing @import (expecting optionally media query)"; + case CSS_MODE_AT_OTHER: + return "parsing at-rule"; + default: + return mode; + } +}; +class CssParser extends Parser { + constructor({ + allowPseudoBlocks = true, + allowModeSwitch = true, + defaultMode = "global" + } = {}) { + super(); + this.allowPseudoBlocks = allowPseudoBlocks; + this.allowModeSwitch = allowModeSwitch; + this.defaultMode = defaultMode; + } + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (Buffer.isBuffer(source)) { + source = source.toString("utf-8"); + } else if (typeof source === "object") { + throw new Error("webpackAst is unexpected for the CssParser"); + } + if (source[0] === "\ufeff") { + source = source.slice(1); + } -const Cache = __webpack_require__(7592); + const module = state.module; -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Cache").Etag} Etag */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ + const declaredCssVariables = new Set(); -class MemoryCachePlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - /** @type {Map} */ - const cache = new Map(); - compiler.cache.hooks.store.tap( - { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, - (identifier, etag, data) => { - cache.set(identifier, { etag, data }); + const locConverter = new LocConverter(source); + let mode = CSS_MODE_TOP_LEVEL; + let modePos = 0; + let modeNestingLevel = 0; + let modeData = undefined; + let singleClassSelector = undefined; + let lastIdentifier = undefined; + const modeStack = []; + const isTopLevelLocal = () => + modeData === "local" || + (this.defaultMode === "local" && modeData === undefined); + const eatWhiteLine = (input, pos) => { + for (;;) { + const cc = input.charCodeAt(pos); + if (cc === 32 || cc === 9) { + pos++; + continue; + } + if (cc === 10) pos++; + break; } - ); - compiler.cache.hooks.get.tap( - { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, - (identifier, etag, gotHandlers) => { - const cacheEntry = cache.get(identifier); - if (cacheEntry === null) { - return null; - } else if (cacheEntry !== undefined) { - return cacheEntry.etag === etag ? cacheEntry.data : null; + return pos; + }; + const eatUntil = chars => { + const charCodes = Array.from({ length: chars.length }, (_, i) => + chars.charCodeAt(i) + ); + const arr = Array.from( + { length: charCodes.reduce((a, b) => Math.max(a, b), 0) + 1 }, + () => false + ); + charCodes.forEach(cc => (arr[cc] = true)); + return (input, pos) => { + for (;;) { + const cc = input.charCodeAt(pos); + if (cc < arr.length && arr[cc]) { + return pos; + } + pos++; + if (pos === input.length) return pos; } - gotHandlers.push((result, callback) => { - if (result === undefined) { - cache.set(identifier, null); + }; + }; + const eatText = (input, pos, eater) => { + let text = ""; + for (;;) { + if (input.charCodeAt(pos) === CC_SLASH) { + const newPos = walkCssTokens.eatComments(input, pos); + if (pos !== newPos) { + pos = newPos; + if (pos === input.length) break; } else { - cache.set(identifier, { etag, data: result }); + text += "/"; + pos++; + if (pos === input.length) break; } - return callback(); - }); - } - ); - compiler.cache.hooks.shutdown.tap( - { name: "MemoryCachePlugin", stage: Cache.STAGE_MEMORY }, - () => { - cache.clear(); - } - ); - } -} -module.exports = MemoryCachePlugin; - - -/***/ }), - -/***/ 99334: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Cache = __webpack_require__(7592); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Cache").Etag} Etag */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ - -class MemoryWithGcCachePlugin { - constructor({ maxGenerations }) { - this._maxGenerations = maxGenerations; - } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const maxGenerations = this._maxGenerations; - /** @type {Map} */ - const cache = new Map(); - /** @type {Map} */ - const oldCache = new Map(); - let generation = 0; - let cachePosition = 0; - const logger = compiler.getInfrastructureLogger("MemoryWithGcCachePlugin"); - compiler.hooks.afterDone.tap("MemoryWithGcCachePlugin", () => { - generation++; - let clearedEntries = 0; - let lastClearedIdentifier; - for (const [identifier, entry] of oldCache) { - if (entry.until > generation) break; - - oldCache.delete(identifier); - if (cache.get(identifier) === undefined) { - cache.delete(identifier); - clearedEntries++; - lastClearedIdentifier = identifier; } + const newPos = eater(input, pos); + if (pos !== newPos) { + text += input.slice(pos, newPos); + pos = newPos; + } else { + break; + } + if (pos === input.length) break; } - if (clearedEntries > 0 || oldCache.size > 0) { - logger.log( - `${cache.size - oldCache.size} active entries, ${ - oldCache.size - } recently unused cached entries${ - clearedEntries > 0 - ? `, ${clearedEntries} old unused cache entries removed e. g. ${lastClearedIdentifier}` - : "" - }` + return [pos, text.trimRight()]; + }; + const eatExportName = eatUntil(":};/"); + const eatExportValue = eatUntil("};/"); + const parseExports = (input, pos) => { + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + const cc = input.charCodeAt(pos); + if (cc !== CC_LEFT_CURLY) + throw new Error( + `Unexpected ${input[pos]} at ${pos} during parsing of ':export' (expected '{')` ); - } - let i = (cache.size / maxGenerations) | 0; - let j = cachePosition >= cache.size ? 0 : cachePosition; - cachePosition = j + i; - for (const [identifier, entry] of cache) { - if (j !== 0) { - j--; - continue; + pos++; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + for (;;) { + if (input.charCodeAt(pos) === CC_RIGHT_CURLY) break; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + if (pos === input.length) return pos; + let start = pos; + let name; + [pos, name] = eatText(input, pos, eatExportName); + if (pos === input.length) return pos; + if (input.charCodeAt(pos) !== CC_COLON) { + throw new Error( + `Unexpected ${input[pos]} at ${pos} during parsing of export name in ':export' (expected ':')` + ); } - if (entry !== undefined) { - // We don't delete the cache entry, but set it to undefined instead - // This reserves the location in the data table and avoids rehashing - // when constantly adding and removing entries. - // It will be deleted when removed from oldCache. - cache.set(identifier, undefined); - oldCache.delete(identifier); - oldCache.set(identifier, { - entry, - until: generation + maxGenerations - }); - if (i-- === 0) break; + pos++; + if (pos === input.length) return pos; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + if (pos === input.length) return pos; + let value; + [pos, value] = eatText(input, pos, eatExportValue); + if (pos === input.length) return pos; + const cc = input.charCodeAt(pos); + if (cc === CC_SEMICOLON) { + pos++; + if (pos === input.length) return pos; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + if (pos === input.length) return pos; + } else if (cc !== CC_RIGHT_CURLY) { + throw new Error( + `Unexpected ${input[pos]} at ${pos} during parsing of export value in ':export' (expected ';' or '}')` + ); } + const dep = new CssExportDependency(name, value); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(pos); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); } - }); - compiler.cache.hooks.store.tap( - { name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY }, - (identifier, etag, data) => { - cache.set(identifier, { etag, data }); + pos++; + if (pos === input.length) return pos; + pos = eatWhiteLine(input, pos); + return pos; + }; + const eatPropertyName = eatUntil(":{};"); + const processLocalDeclaration = (input, pos) => { + modeData = undefined; + const start = pos; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + const propertyNameStart = pos; + const [propertyNameEnd, propertyName] = eatText( + input, + pos, + eatPropertyName + ); + if (input.charCodeAt(propertyNameEnd) !== CC_COLON) return start; + pos = propertyNameEnd + 1; + if (propertyName.startsWith("--")) { + // CSS Variable + const { line: sl, column: sc } = locConverter.get(propertyNameStart); + const { line: el, column: ec } = locConverter.get(propertyNameEnd); + const name = propertyName.slice(2); + const dep = new CssLocalIdentifierDependency( + name, + [propertyNameStart, propertyNameEnd], + "--" + ); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + declaredCssVariables.add(name); + } else if ( + propertyName === "animation-name" || + propertyName === "animation" + ) { + modeData = "animation"; + lastIdentifier = undefined; } - ); - compiler.cache.hooks.get.tap( - { name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY }, - (identifier, etag, gotHandlers) => { - const cacheEntry = cache.get(identifier); - if (cacheEntry === null) { - return null; - } else if (cacheEntry !== undefined) { - return cacheEntry.etag === etag ? cacheEntry.data : null; + return pos; + }; + const processDeclarationValueDone = (input, pos) => { + if (modeData === "animation" && lastIdentifier) { + const { line: sl, column: sc } = locConverter.get(lastIdentifier[0]); + const { line: el, column: ec } = locConverter.get(lastIdentifier[1]); + const name = input.slice(lastIdentifier[0], lastIdentifier[1]); + const dep = new CssSelfLocalIdentifierDependency(name, lastIdentifier); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + } + }; + const eatKeyframes = eatUntil("{};/"); + const eatNameInVar = eatUntil(",)};/"); + walkCssTokens(source, { + isSelector: () => { + return mode !== CSS_MODE_IN_RULE && mode !== CSS_MODE_IN_LOCAL_RULE; + }, + url: (input, start, end, contentStart, contentEnd) => { + const value = cssUnescape(input.slice(contentStart, contentEnd)); + switch (mode) { + case CSS_MODE_AT_IMPORT_EXPECT_URL: { + modeData.url = value; + mode = CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS; + break; + } + case CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS: + case CSS_MODE_AT_IMPORT_EXPECT_MEDIA: + throw new Error( + `Unexpected ${input.slice( + start, + end + )} at ${start} during ${explainMode(mode)}` + ); + default: { + const dep = new CssUrlDependency(value, [start, end], "url"); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + module.addCodeGenerationDependency(dep); + break; + } } - const oldCacheEntry = oldCache.get(identifier); - if (oldCacheEntry !== undefined) { - const cacheEntry = oldCacheEntry.entry; - if (cacheEntry === null) { - oldCache.delete(identifier); - cache.set(identifier, cacheEntry); - return null; - } else { - if (cacheEntry.etag !== etag) return null; - oldCache.delete(identifier); - cache.set(identifier, cacheEntry); - return cacheEntry.data; + return end; + }, + string: (input, start, end) => { + switch (mode) { + case CSS_MODE_AT_IMPORT_EXPECT_URL: { + modeData.url = cssUnescape(input.slice(start + 1, end - 1)); + mode = CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS; + break; } } - gotHandlers.push((result, callback) => { - if (result === undefined) { - cache.set(identifier, null); - } else { - cache.set(identifier, { etag, data: result }); + return end; + }, + atKeyword: (input, start, end) => { + const name = input.slice(start, end); + if (name === "@namespace") { + throw new Error("@namespace is not supported in bundled CSS"); + } + if (name === "@import") { + if (mode !== CSS_MODE_TOP_LEVEL) { + throw new Error( + `Unexpected @import at ${start} during ${explainMode(mode)}` + ); } - return callback(); - }); - } - ); - compiler.cache.hooks.shutdown.tap( - { name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY }, - () => { - cache.clear(); - oldCache.clear(); + mode = CSS_MODE_AT_IMPORT_EXPECT_URL; + modePos = end; + modeData = { + start: start, + url: undefined, + supports: undefined + }; + } + if (name === "@keyframes") { + let pos = end; + pos = walkCssTokens.eatWhitespaceAndComments(input, pos); + if (pos === input.length) return pos; + const [newPos, name] = eatText(input, pos, eatKeyframes); + const { line: sl, column: sc } = locConverter.get(pos); + const { line: el, column: ec } = locConverter.get(newPos); + const dep = new CssLocalIdentifierDependency(name, [pos, newPos]); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + pos = newPos; + if (pos === input.length) return pos; + if (input.charCodeAt(pos) !== CC_LEFT_CURLY) { + throw new Error( + `Unexpected ${input[pos]} at ${pos} during parsing of @keyframes (expected '{')` + ); + } + mode = CSS_MODE_IN_LOCAL_RULE; + modeNestingLevel = 1; + return pos + 1; + } + return end; + }, + semicolon: (input, start, end) => { + switch (mode) { + case CSS_MODE_AT_IMPORT_EXPECT_URL: + throw new Error(`Expected URL for @import at ${start}`); + case CSS_MODE_AT_IMPORT_EXPECT_MEDIA: + case CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS: { + const { line: sl, column: sc } = locConverter.get(modeData.start); + const { line: el, column: ec } = locConverter.get(end); + end = eatWhiteLine(input, end); + const media = input.slice(modePos, start).trim(); + const dep = new CssImportDependency( + modeData.url, + [modeData.start, end], + modeData.supports, + media + ); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + break; + } + case CSS_MODE_IN_LOCAL_RULE: { + processDeclarationValueDone(input, start); + return processLocalDeclaration(input, end); + } + case CSS_MODE_IN_RULE: { + return end; + } + } + mode = CSS_MODE_TOP_LEVEL; + modeData = undefined; + singleClassSelector = undefined; + return end; + }, + leftCurlyBracket: (input, start, end) => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: + mode = isTopLevelLocal() + ? CSS_MODE_IN_LOCAL_RULE + : CSS_MODE_IN_RULE; + modeNestingLevel = 1; + if (mode === CSS_MODE_IN_LOCAL_RULE) + return processLocalDeclaration(input, end); + break; + case CSS_MODE_IN_RULE: + case CSS_MODE_IN_LOCAL_RULE: + modeNestingLevel++; + break; + } + return end; + }, + rightCurlyBracket: (input, start, end) => { + switch (mode) { + case CSS_MODE_IN_LOCAL_RULE: + processDeclarationValueDone(input, start); + /* falls through */ + case CSS_MODE_IN_RULE: + if (--modeNestingLevel === 0) { + mode = CSS_MODE_TOP_LEVEL; + modeData = undefined; + singleClassSelector = undefined; + } + break; + } + return end; + }, + id: (input, start, end) => { + singleClassSelector = false; + switch (mode) { + case CSS_MODE_TOP_LEVEL: + if (isTopLevelLocal()) { + const name = input.slice(start + 1, end); + const dep = new CssLocalIdentifierDependency(name, [ + start + 1, + end + ]); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + } + break; + } + return end; + }, + identifier: (input, start, end) => { + singleClassSelector = false; + switch (mode) { + case CSS_MODE_IN_LOCAL_RULE: + if (modeData === "animation") { + lastIdentifier = [start, end]; + } + break; + } + return end; + }, + class: (input, start, end) => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: { + if (isTopLevelLocal()) { + const name = input.slice(start + 1, end); + const dep = new CssLocalIdentifierDependency(name, [ + start + 1, + end + ]); + const { line: sl, column: sc } = locConverter.get(start); + const { line: el, column: ec } = locConverter.get(end); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + if (singleClassSelector === undefined) singleClassSelector = name; + } else { + singleClassSelector = false; + } + break; + } + } + return end; + }, + leftParenthesis: (input, start, end) => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: { + modeStack.push(false); + break; + } + } + return end; + }, + rightParenthesis: (input, start, end) => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: { + const newModeData = modeStack.pop(); + if (newModeData !== false) { + modeData = newModeData; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + } + break; + } + } + return end; + }, + pseudoClass: (input, start, end) => { + singleClassSelector = false; + switch (mode) { + case CSS_MODE_TOP_LEVEL: { + const name = input.slice(start, end); + if (this.allowModeSwitch && name === ":global") { + modeData = "global"; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + } else if (this.allowModeSwitch && name === ":local") { + modeData = "local"; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + } else if (this.allowPseudoBlocks && name === ":export") { + const pos = parseExports(input, end); + const dep = new ConstDependency("", [start, pos]); + module.addPresentationalDependency(dep); + return pos; + } + break; + } + } + return end; + }, + pseudoFunction: (input, start, end) => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: { + const name = input.slice(start, end - 1); + if (this.allowModeSwitch && name === ":global") { + modeStack.push(modeData); + modeData = "global"; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + } else if (this.allowModeSwitch && name === ":local") { + modeStack.push(modeData); + modeData = "local"; + const dep = new ConstDependency("", [start, end]); + module.addPresentationalDependency(dep); + } else { + modeStack.push(false); + } + break; + } + } + return end; + }, + function: (input, start, end) => { + switch (mode) { + case CSS_MODE_IN_LOCAL_RULE: { + const name = input.slice(start, end - 1); + if (name === "var") { + let pos = walkCssTokens.eatWhitespaceAndComments(input, end); + if (pos === input.length) return pos; + const [newPos, name] = eatText(input, pos, eatNameInVar); + if (!name.startsWith("--")) return end; + const { line: sl, column: sc } = locConverter.get(pos); + const { line: el, column: ec } = locConverter.get(newPos); + const dep = new CssSelfLocalIdentifierDependency( + name.slice(2), + [pos, newPos], + "--", + declaredCssVariables + ); + dep.setLoc(sl, sc, el, ec); + module.addDependency(dep); + return newPos; + } + break; + } + } + return end; + }, + comma: (input, start, end) => { + switch (mode) { + case CSS_MODE_TOP_LEVEL: + modeData = undefined; + modeStack.length = 0; + break; + case CSS_MODE_IN_LOCAL_RULE: + processDeclarationValueDone(input, start); + break; + } + return end; } - ); + }); + + module.buildInfo.strict = true; + module.buildMeta.exportsType = "namespace"; + module.addDependency(new StaticExportsDependency([], true)); + return state; } } -module.exports = MemoryWithGcCachePlugin; + +module.exports = CssParser; /***/ }), -/***/ 86180: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 44124: +/***/ (function(module) { "use strict"; /* @@ -68295,1731 +69300,1126 @@ module.exports = MemoryWithGcCachePlugin; -const FileSystemInfo = __webpack_require__(79453); -const ProgressPlugin = __webpack_require__(13216); -const { formatSize } = __webpack_require__(71070); -const SerializerMiddleware = __webpack_require__(83137); -const LazySet = __webpack_require__(38938); -const makeSerializable = __webpack_require__(33032); -const memoize = __webpack_require__(78676); -const { - createFileSerializer, - NOT_SERIALIZABLE -} = __webpack_require__(8282); - -/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */ -/** @typedef {import("../Cache").Etag} Etag */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */ -/** @typedef {import("../logging/Logger").Logger} Logger */ -/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ +/** + * @typedef {Object} CssTokenCallbacks + * @property {function(string, number): boolean} isSelector + * @property {function(string, number, number, number, number): number=} url + * @property {function(string, number, number): number=} string + * @property {function(string, number, number): number=} leftParenthesis + * @property {function(string, number, number): number=} rightParenthesis + * @property {function(string, number, number): number=} pseudoFunction + * @property {function(string, number, number): number=} function + * @property {function(string, number, number): number=} pseudoClass + * @property {function(string, number, number): number=} atKeyword + * @property {function(string, number, number): number=} class + * @property {function(string, number, number): number=} identifier + * @property {function(string, number, number): number=} id + * @property {function(string, number, number): number=} leftCurlyBracket + * @property {function(string, number, number): number=} rightCurlyBracket + * @property {function(string, number, number): number=} semicolon + * @property {function(string, number, number): number=} comma + */ -class PackContainer { - /** - * @param {Object} data stored data - * @param {string} version version identifier - * @param {Snapshot} buildSnapshot snapshot of all build dependencies - * @param {Set} buildDependencies list of all unresolved build dependencies captured - * @param {Map} resolveResults result of the resolved build dependencies - * @param {Snapshot} resolveBuildDependenciesSnapshot snapshot of the dependencies of the build dependencies resolving - */ - constructor( - data, - version, - buildSnapshot, - buildDependencies, - resolveResults, - resolveBuildDependenciesSnapshot - ) { - this.data = data; - this.version = version; - this.buildSnapshot = buildSnapshot; - this.buildDependencies = buildDependencies; - this.resolveResults = resolveResults; - this.resolveBuildDependenciesSnapshot = resolveBuildDependenciesSnapshot; - } +/** @typedef {function(string, number, CssTokenCallbacks): number} CharHandler */ - serialize({ write, writeLazy }) { - write(this.version); - write(this.buildSnapshot); - write(this.buildDependencies); - write(this.resolveResults); - write(this.resolveBuildDependenciesSnapshot); - writeLazy(this.data); - } +// spec: https://drafts.csswg.org/css-syntax/ - deserialize({ read }) { - this.version = read(); - this.buildSnapshot = read(); - this.buildDependencies = read(); - this.resolveResults = read(); - this.resolveBuildDependenciesSnapshot = read(); - this.data = read(); - } -} +const CC_LINE_FEED = "\n".charCodeAt(0); +const CC_CARRIAGE_RETURN = "\r".charCodeAt(0); +const CC_FORM_FEED = "\f".charCodeAt(0); -makeSerializable( - PackContainer, - "webpack/lib/cache/PackFileCacheStrategy", - "PackContainer" -); +const CC_TAB = "\t".charCodeAt(0); +const CC_SPACE = " ".charCodeAt(0); -const MIN_CONTENT_SIZE = 1024 * 1024; // 1 MB -const CONTENT_COUNT_TO_MERGE = 10; -const MIN_ITEMS_IN_FRESH_PACK = 100; -const MAX_ITEMS_IN_FRESH_PACK = 50000; -const MAX_TIME_IN_FRESH_PACK = 1 * 60 * 1000; // 1 min +const CC_SLASH = "/".charCodeAt(0); +const CC_BACK_SLASH = "\\".charCodeAt(0); +const CC_ASTERISK = "*".charCodeAt(0); -class PackItemInfo { - /** - * @param {string} identifier identifier of item - * @param {string | null} etag etag of item - * @param {any} value fresh value of item - */ - constructor(identifier, etag, value) { - this.identifier = identifier; - this.etag = etag; - this.location = -1; - this.lastAccess = Date.now(); - this.freshValue = value; - } -} +const CC_LEFT_PARENTHESIS = "(".charCodeAt(0); +const CC_RIGHT_PARENTHESIS = ")".charCodeAt(0); +const CC_LEFT_CURLY = "{".charCodeAt(0); +const CC_RIGHT_CURLY = "}".charCodeAt(0); -class Pack { - constructor(logger, maxAge) { - /** @type {Map} */ - this.itemInfo = new Map(); - /** @type {string[]} */ - this.requests = []; - this.requestsTimeout = undefined; - /** @type {Map} */ - this.freshContent = new Map(); - /** @type {(undefined | PackContent)[]} */ - this.content = []; - this.invalid = false; - this.logger = logger; - this.maxAge = maxAge; - } +const CC_QUOTATION_MARK = '"'.charCodeAt(0); +const CC_APOSTROPHE = "'".charCodeAt(0); - _addRequest(identifier) { - this.requests.push(identifier); - if (this.requestsTimeout === undefined) { - this.requestsTimeout = setTimeout(() => { - this.requests.push(undefined); - this.requestsTimeout = undefined; - }, MAX_TIME_IN_FRESH_PACK); - if (this.requestsTimeout.unref) this.requestsTimeout.unref(); - } - } +const CC_FULL_STOP = ".".charCodeAt(0); +const CC_COLON = ":".charCodeAt(0); +const CC_SEMICOLON = ";".charCodeAt(0); +const CC_COMMA = ",".charCodeAt(0); +const CC_PERCENTAGE = "%".charCodeAt(0); +const CC_AT_SIGN = "@".charCodeAt(0); - stopCapturingRequests() { - if (this.requestsTimeout !== undefined) { - clearTimeout(this.requestsTimeout); - this.requestsTimeout = undefined; +const CC_LOW_LINE = "_".charCodeAt(0); +const CC_LOWER_A = "a".charCodeAt(0); +const CC_LOWER_U = "u".charCodeAt(0); +const CC_LOWER_E = "e".charCodeAt(0); +const CC_LOWER_Z = "z".charCodeAt(0); +const CC_UPPER_A = "A".charCodeAt(0); +const CC_UPPER_E = "E".charCodeAt(0); +const CC_UPPER_Z = "Z".charCodeAt(0); +const CC_0 = "0".charCodeAt(0); +const CC_9 = "9".charCodeAt(0); + +const CC_NUMBER_SIGN = "#".charCodeAt(0); +const CC_PLUS_SIGN = "+".charCodeAt(0); +const CC_HYPHEN_MINUS = "-".charCodeAt(0); + +const CC_LESS_THAN_SIGN = "<".charCodeAt(0); +const CC_GREATER_THAN_SIGN = ">".charCodeAt(0); + +const _isNewLine = cc => { + return ( + cc === CC_LINE_FEED || cc === CC_CARRIAGE_RETURN || cc === CC_FORM_FEED + ); +}; + +/** @type {CharHandler} */ +const consumeSpace = (input, pos, callbacks) => { + let cc; + do { + pos++; + cc = input.charCodeAt(pos); + } while (_isWhiteSpace(cc)); + return pos; +}; + +const _isWhiteSpace = cc => { + return ( + cc === CC_LINE_FEED || + cc === CC_CARRIAGE_RETURN || + cc === CC_FORM_FEED || + cc === CC_TAB || + cc === CC_SPACE + ); +}; + +/** @type {CharHandler} */ +const consumeSingleCharToken = (input, pos, callbacks) => { + return pos + 1; +}; + +/** @type {CharHandler} */ +const consumePotentialComment = (input, pos, callbacks) => { + pos++; + if (pos === input.length) return pos; + let cc = input.charCodeAt(pos); + if (cc !== CC_ASTERISK) return pos; + for (;;) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + while (cc === CC_ASTERISK) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + if (cc === CC_SLASH) return pos + 1; } } +}; - /** - * @param {string} identifier unique name for the resource - * @param {string | null} etag etag of the resource - * @returns {any} cached content - */ - get(identifier, etag) { - const info = this.itemInfo.get(identifier); - this._addRequest(identifier); - if (info === undefined) { - return undefined; - } - if (info.etag !== etag) return null; - info.lastAccess = Date.now(); - const loc = info.location; - if (loc === -1) { - return info.freshValue; - } else { - if (!this.content[loc]) { - return undefined; - } - return this.content[loc].get(identifier); - } +/** @type {function(number): CharHandler} */ +const consumeString = end => (input, pos, callbacks) => { + const start = pos; + pos = _consumeString(input, pos, end); + if (callbacks.string !== undefined) { + pos = callbacks.string(input, start, pos); } + return pos; +}; - /** - * @param {string} identifier unique name for the resource - * @param {string | null} etag etag of the resource - * @param {any} data cached content - * @returns {void} - */ - set(identifier, etag, data) { - if (!this.invalid) { - this.invalid = true; - this.logger.log(`Pack got invalid because of write to: ${identifier}`); +const _consumeString = (input, pos, end) => { + pos++; + for (;;) { + if (pos === input.length) return pos; + const cc = input.charCodeAt(pos); + if (cc === end) return pos + 1; + if (_isNewLine(cc)) { + // bad string + return pos; } - const info = this.itemInfo.get(identifier); - if (info === undefined) { - const newInfo = new PackItemInfo(identifier, etag, data); - this.itemInfo.set(identifier, newInfo); - this._addRequest(identifier); - this.freshContent.set(identifier, newInfo); + if (cc === CC_BACK_SLASH) { + // we don't need to fully parse the escaped code point + // just skip over a potential new line + pos++; + if (pos === input.length) return pos; + pos++; } else { - const loc = info.location; - if (loc >= 0) { - this._addRequest(identifier); - this.freshContent.set(identifier, info); - const content = this.content[loc]; - content.delete(identifier); - if (content.items.size === 0) { - this.content[loc] = undefined; - this.logger.debug("Pack %d got empty and is removed", loc); - } - } - info.freshValue = data; - info.lastAccess = Date.now(); - info.etag = etag; - info.location = -1; + pos++; } } +}; - getContentStats() { - let count = 0; - let size = 0; - for (const content of this.content) { - if (content !== undefined) { - count++; - const s = content.getSize(); - if (s > 0) { - size += s; - } - } - } - return { count, size }; - } +const _isIdentifierStartCode = cc => { + return ( + cc === CC_LOW_LINE || + (cc >= CC_LOWER_A && cc <= CC_LOWER_Z) || + (cc >= CC_UPPER_A && cc <= CC_UPPER_Z) || + cc > 0x80 + ); +}; - /** - * @returns {number} new location of data entries - */ - _findLocation() { - let i; - for (i = 0; i < this.content.length && this.content[i] !== undefined; i++); - return i; - } +const _isDigit = cc => { + return cc >= CC_0 && cc <= CC_9; +}; - _gcAndUpdateLocation(items, usedItems, newLoc) { - let count = 0; - let lastGC; - const now = Date.now(); - for (const identifier of items) { - const info = this.itemInfo.get(identifier); - if (now - info.lastAccess > this.maxAge) { - this.itemInfo.delete(identifier); - items.delete(identifier); - usedItems.delete(identifier); - count++; - lastGC = identifier; - } else { - info.location = newLoc; - } - } - if (count > 0) { - this.logger.log( - "Garbage Collected %d old items at pack %d (%d items remaining) e. g. %s", - count, - newLoc, - items.size, - lastGC - ); +const _startsIdentifier = (input, pos) => { + const cc = input.charCodeAt(pos); + if (cc === CC_HYPHEN_MINUS) { + if (pos === input.length) return false; + const cc = input.charCodeAt(pos + 1); + if (cc === CC_HYPHEN_MINUS) return true; + if (cc === CC_BACK_SLASH) { + const cc = input.charCodeAt(pos + 2); + return !_isNewLine(cc); } + return _isIdentifierStartCode(cc); + } + if (cc === CC_BACK_SLASH) { + const cc = input.charCodeAt(pos + 1); + return !_isNewLine(cc); } + return _isIdentifierStartCode(cc); +}; - _persistFreshContent() { - const itemsCount = this.freshContent.size; - if (itemsCount > 0) { - const packCount = Math.ceil(itemsCount / MAX_ITEMS_IN_FRESH_PACK); - const itemsPerPack = Math.ceil(itemsCount / packCount); - const packs = []; - let i = 0; - let ignoreNextTimeTick = false; - const createNextPack = () => { - const loc = this._findLocation(); - this.content[loc] = null; // reserve - const pack = { - /** @type {Set} */ - items: new Set(), - /** @type {Map} */ - map: new Map(), - loc - }; - packs.push(pack); - return pack; - }; - let pack = createNextPack(); - if (this.requestsTimeout !== undefined) - clearTimeout(this.requestsTimeout); - for (const identifier of this.requests) { - if (identifier === undefined) { - if (ignoreNextTimeTick) { - ignoreNextTimeTick = false; - } else if (pack.items.size >= MIN_ITEMS_IN_FRESH_PACK) { - i = 0; - pack = createNextPack(); - } - continue; - } - const info = this.freshContent.get(identifier); - if (info === undefined) continue; - pack.items.add(identifier); - pack.map.set(identifier, info.freshValue); - info.location = pack.loc; - info.freshValue = undefined; - this.freshContent.delete(identifier); - if (++i > itemsPerPack) { - i = 0; - pack = createNextPack(); - ignoreNextTimeTick = true; - } - } - this.requests.length = 0; - for (const pack of packs) { - this.content[pack.loc] = new PackContent( - pack.items, - new Set(pack.items), - new PackContentItems(pack.map) - ); - } - this.logger.log( - `${itemsCount} fresh items in cache put into pack ${ - packs.length > 1 - ? packs - .map(pack => `${pack.loc} (${pack.items.size} items)`) - .join(", ") - : packs[0].loc - }` - ); +/** @type {CharHandler} */ +const consumeNumberSign = (input, pos, callbacks) => { + const start = pos; + pos++; + if (pos === input.length) return pos; + if (callbacks.isSelector(input, pos) && _startsIdentifier(input, pos)) { + pos = _consumeIdentifier(input, pos); + if (callbacks.id !== undefined) { + return callbacks.id(input, start, pos); } } + return pos; +}; - /** - * Merges small content files to a single content file - */ - _optimizeSmallContent() { - // 1. Find all small content files - // Treat unused content files separately to avoid - // a merge-split cycle - /** @type {number[]} */ - const smallUsedContents = []; - /** @type {number} */ - let smallUsedContentSize = 0; - /** @type {number[]} */ - const smallUnusedContents = []; - /** @type {number} */ - let smallUnusedContentSize = 0; - for (let i = 0; i < this.content.length; i++) { - const content = this.content[i]; - if (content === undefined) continue; - if (content.outdated) continue; - const size = content.getSize(); - if (size < 0 || size > MIN_CONTENT_SIZE) continue; - if (content.used.size > 0) { - smallUsedContents.push(i); - smallUsedContentSize += size; - } else { - smallUnusedContents.push(i); - smallUnusedContentSize += size; +/** @type {CharHandler} */ +const consumeMinus = (input, pos, callbacks) => { + const start = pos; + pos++; + if (pos === input.length) return pos; + const cc = input.charCodeAt(pos); + if (cc === CC_FULL_STOP || _isDigit(cc)) { + return consumeNumericToken(input, pos, callbacks); + } else if (cc === CC_HYPHEN_MINUS) { + pos++; + if (pos === input.length) return pos; + const cc = input.charCodeAt(pos); + if (cc === CC_GREATER_THAN_SIGN) { + return pos + 1; + } else { + pos = _consumeIdentifier(input, pos); + if (callbacks.identifier !== undefined) { + return callbacks.identifier(input, start, pos); } } + } else if (cc === CC_BACK_SLASH) { + if (pos + 1 === input.length) return pos; + const cc = input.charCodeAt(pos + 1); + if (_isNewLine(cc)) return pos; + pos = _consumeIdentifier(input, pos); + if (callbacks.identifier !== undefined) { + return callbacks.identifier(input, start, pos); + } + } else if (_isIdentifierStartCode(cc)) { + pos++; + pos = _consumeIdentifier(input, pos); + if (callbacks.identifier !== undefined) { + return callbacks.identifier(input, start, pos); + } + } + return pos; +}; - // 2. Check if minimum number is reached - let mergedIndices; - if ( - smallUsedContents.length >= CONTENT_COUNT_TO_MERGE || - smallUsedContentSize > MIN_CONTENT_SIZE - ) { - mergedIndices = smallUsedContents; - } else if ( - smallUnusedContents.length >= CONTENT_COUNT_TO_MERGE || - smallUnusedContentSize > MIN_CONTENT_SIZE - ) { - mergedIndices = smallUnusedContents; - } else return; +/** @type {CharHandler} */ +const consumeDot = (input, pos, callbacks) => { + const start = pos; + pos++; + if (pos === input.length) return pos; + const cc = input.charCodeAt(pos); + if (_isDigit(cc)) return consumeNumericToken(input, pos - 2, callbacks); + if (!callbacks.isSelector(input, pos) || !_startsIdentifier(input, pos)) + return pos; + pos = _consumeIdentifier(input, pos); + if (callbacks.class !== undefined) return callbacks.class(input, start, pos); + return pos; +}; - const mergedContent = []; +/** @type {CharHandler} */ +const consumeNumericToken = (input, pos, callbacks) => { + pos = _consumeNumber(input, pos); + if (pos === input.length) return pos; + if (_startsIdentifier(input, pos)) return _consumeIdentifier(input, pos); + const cc = input.charCodeAt(pos); + if (cc === CC_PERCENTAGE) return pos + 1; + return pos; +}; - // 3. Remove old content entries - for (const i of mergedIndices) { - mergedContent.push(this.content[i]); - this.content[i] = undefined; +/** @type {CharHandler} */ +const consumeOtherIdentifier = (input, pos, callbacks) => { + const start = pos; + pos = _consumeIdentifier(input, pos); + if ( + pos !== input.length && + !callbacks.isSelector(input, pos) && + input.charCodeAt(pos) === CC_LEFT_PARENTHESIS + ) { + pos++; + if (callbacks.function !== undefined) { + return callbacks.function(input, start, pos); + } + } else { + if (callbacks.identifier !== undefined) { + return callbacks.identifier(input, start, pos); } + } + return pos; +}; - // 4. Determine merged items - /** @type {Set} */ - const mergedItems = new Set(); - /** @type {Set} */ - const mergedUsedItems = new Set(); - /** @type {(function(Map): Promise)[]} */ - const addToMergedMap = []; - for (const content of mergedContent) { - for (const identifier of content.items) { - mergedItems.add(identifier); - } - for (const identifier of content.used) { - mergedUsedItems.add(identifier); +/** @type {CharHandler} */ +const consumePotentialUrl = (input, pos, callbacks) => { + const start = pos; + pos = _consumeIdentifier(input, pos); + if (pos === start + 3 && input.slice(start, pos + 1) === "url(") { + pos++; + let cc = input.charCodeAt(pos); + while (_isWhiteSpace(cc)) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + } + if (cc === CC_QUOTATION_MARK || cc === CC_APOSTROPHE) { + pos++; + const contentStart = pos; + pos = _consumeString(input, pos, cc); + const contentEnd = pos - 1; + cc = input.charCodeAt(pos); + while (_isWhiteSpace(cc)) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); } - addToMergedMap.push(async map => { - // unpack existing content - // after that values are accessible in .content - await content.unpack( - "it should be merged with other small pack contents" - ); - for (const [identifier, value] of content.content) { - map.set(identifier, value); + if (cc !== CC_RIGHT_PARENTHESIS) return pos; + pos++; + if (callbacks.url !== undefined) + return callbacks.url(input, start, pos, contentStart, contentEnd); + return pos; + } else { + const contentStart = pos; + let contentEnd; + for (;;) { + if (cc === CC_BACK_SLASH) { + pos++; + if (pos === input.length) return pos; + pos++; + } else if (_isWhiteSpace(cc)) { + contentEnd = pos; + do { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + } while (_isWhiteSpace(cc)); + if (cc !== CC_RIGHT_PARENTHESIS) return pos; + pos++; + if (callbacks.url !== undefined) { + return callbacks.url(input, start, pos, contentStart, contentEnd); + } + return pos; + } else if (cc === CC_RIGHT_PARENTHESIS) { + contentEnd = pos; + pos++; + if (callbacks.url !== undefined) { + return callbacks.url(input, start, pos, contentStart, contentEnd); + } + return pos; + } else if (cc === CC_LEFT_PARENTHESIS) { + return pos; + } else { + pos++; } - }); + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + } } + } else { + if (callbacks.identifier !== undefined) { + return callbacks.identifier(input, start, pos); + } + return pos; + } +}; - // 5. GC and update location of merged items - const newLoc = this._findLocation(); - this._gcAndUpdateLocation(mergedItems, mergedUsedItems, newLoc); - - // 6. If not empty, store content somewhere - if (mergedItems.size > 0) { - this.content[newLoc] = new PackContent( - mergedItems, - mergedUsedItems, - memoize(async () => { - /** @type {Map} */ - const map = new Map(); - await Promise.all(addToMergedMap.map(fn => fn(map))); - return new PackContentItems(map); - }) - ); - this.logger.log( - "Merged %d small files with %d cache items into pack %d", - mergedContent.length, - mergedItems.size, - newLoc - ); +/** @type {CharHandler} */ +const consumePotentialPseudo = (input, pos, callbacks) => { + const start = pos; + pos++; + if (!callbacks.isSelector(input, pos) || !_startsIdentifier(input, pos)) + return pos; + pos = _consumeIdentifier(input, pos); + let cc = input.charCodeAt(pos); + if (cc === CC_LEFT_PARENTHESIS) { + pos++; + if (callbacks.pseudoFunction !== undefined) { + return callbacks.pseudoFunction(input, start, pos); } + return pos; + } + if (callbacks.pseudoClass !== undefined) { + return callbacks.pseudoClass(input, start, pos); } + return pos; +}; - /** - * Split large content files with used and unused items - * into two parts to separate used from unused items - */ - _optimizeUnusedContent() { - // 1. Find a large content file with used and unused items - for (let i = 0; i < this.content.length; i++) { - const content = this.content[i]; - if (content === undefined) continue; - const size = content.getSize(); - if (size < MIN_CONTENT_SIZE) continue; - const used = content.used.size; - const total = content.items.size; - if (used > 0 && used < total) { - // 2. Remove this content - this.content[i] = undefined; +/** @type {CharHandler} */ +const consumeLeftParenthesis = (input, pos, callbacks) => { + pos++; + if (callbacks.leftParenthesis !== undefined) { + return callbacks.leftParenthesis(input, pos - 1, pos); + } + return pos; +}; - // 3. Determine items for the used content file - const usedItems = new Set(content.used); - const newLoc = this._findLocation(); - this._gcAndUpdateLocation(usedItems, usedItems, newLoc); +/** @type {CharHandler} */ +const consumeRightParenthesis = (input, pos, callbacks) => { + pos++; + if (callbacks.rightParenthesis !== undefined) { + return callbacks.rightParenthesis(input, pos - 1, pos); + } + return pos; +}; - // 4. Create content file for used items - if (usedItems.size > 0) { - this.content[newLoc] = new PackContent( - usedItems, - new Set(usedItems), - async () => { - await content.unpack( - "it should be splitted into used and unused items" - ); - const map = new Map(); - for (const identifier of usedItems) { - map.set(identifier, content.content.get(identifier)); - } - return new PackContentItems(map); - } - ); - } +/** @type {CharHandler} */ +const consumeLeftCurlyBracket = (input, pos, callbacks) => { + pos++; + if (callbacks.leftCurlyBracket !== undefined) { + return callbacks.leftCurlyBracket(input, pos - 1, pos); + } + return pos; +}; - // 5. Determine items for the unused content file - const unusedItems = new Set(content.items); - const usedOfUnusedItems = new Set(); - for (const identifier of usedItems) { - unusedItems.delete(identifier); - } - const newUnusedLoc = this._findLocation(); - this._gcAndUpdateLocation(unusedItems, usedOfUnusedItems, newUnusedLoc); +/** @type {CharHandler} */ +const consumeRightCurlyBracket = (input, pos, callbacks) => { + pos++; + if (callbacks.rightCurlyBracket !== undefined) { + return callbacks.rightCurlyBracket(input, pos - 1, pos); + } + return pos; +}; - // 6. Create content file for unused items - if (unusedItems.size > 0) { - this.content[newUnusedLoc] = new PackContent( - unusedItems, - usedOfUnusedItems, - async () => { - await content.unpack( - "it should be splitted into used and unused items" - ); - const map = new Map(); - for (const identifier of unusedItems) { - map.set(identifier, content.content.get(identifier)); - } - return new PackContentItems(map); - } - ); - } +/** @type {CharHandler} */ +const consumeSemicolon = (input, pos, callbacks) => { + pos++; + if (callbacks.semicolon !== undefined) { + return callbacks.semicolon(input, pos - 1, pos); + } + return pos; +}; - this.logger.log( - "Split pack %d into pack %d with %d used items and pack %d with %d unused items", - i, - newLoc, - usedItems.size, - newUnusedLoc, - unusedItems.size - ); +/** @type {CharHandler} */ +const consumeComma = (input, pos, callbacks) => { + pos++; + if (callbacks.comma !== undefined) { + return callbacks.comma(input, pos - 1, pos); + } + return pos; +}; - // optimizing only one of them is good enough and - // reduces the amount of serialization needed - return; - } +const _consumeIdentifier = (input, pos) => { + for (;;) { + const cc = input.charCodeAt(pos); + if (cc === CC_BACK_SLASH) { + pos++; + if (pos === input.length) return pos; + pos++; + } else if ( + _isIdentifierStartCode(cc) || + _isDigit(cc) || + cc === CC_HYPHEN_MINUS + ) { + pos++; + } else { + return pos; } } +}; - /** - * Find the content with the oldest item and run GC on that. - * Only runs for one content to avoid large invalidation. - */ - _gcOldestContent() { - /** @type {PackItemInfo} */ - let oldest = undefined; - for (const info of this.itemInfo.values()) { - if (oldest === undefined || info.lastAccess < oldest.lastAccess) { - oldest = info; +const _consumeNumber = (input, pos) => { + pos++; + if (pos === input.length) return pos; + let cc = input.charCodeAt(pos); + while (_isDigit(cc)) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + } + if (cc === CC_FULL_STOP && pos + 1 !== input.length) { + const next = input.charCodeAt(pos + 1); + if (_isDigit(next)) { + pos += 2; + cc = input.charCodeAt(pos); + while (_isDigit(cc)) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); } } - if (Date.now() - oldest.lastAccess > this.maxAge) { - const loc = oldest.location; - if (loc < 0) return; - const content = this.content[loc]; - const items = new Set(content.items); - const usedItems = new Set(content.used); - this._gcAndUpdateLocation(items, usedItems, loc); - - this.content[loc] = - items.size > 0 - ? new PackContent(items, usedItems, async () => { - await content.unpack( - "it contains old items that should be garbage collected" - ); - const map = new Map(); - for (const identifier of items) { - map.set(identifier, content.content.get(identifier)); - } - return new PackContentItems(map); - }) - : undefined; - } } - - serialize({ write, writeSeparate }) { - this._persistFreshContent(); - this._optimizeSmallContent(); - this._optimizeUnusedContent(); - this._gcOldestContent(); - for (const identifier of this.itemInfo.keys()) { - write(identifier); - } - write(null); // null as marker of the end of keys - for (const info of this.itemInfo.values()) { - write(info.etag); - } - for (const info of this.itemInfo.values()) { - write(info.lastAccess); - } - for (let i = 0; i < this.content.length; i++) { - const content = this.content[i]; - if (content !== undefined) { - write(content.items); - content.writeLazy(lazy => writeSeparate(lazy, { name: `${i}` })); + if (cc === CC_LOWER_E || cc === CC_UPPER_E) { + if (pos + 1 !== input.length) { + const next = input.charCodeAt(pos + 2); + if (_isDigit(next)) { + pos += 2; + } else if ( + (next === CC_HYPHEN_MINUS || next === CC_PLUS_SIGN) && + pos + 2 !== input.length + ) { + const next = input.charCodeAt(pos + 2); + if (_isDigit(next)) { + pos += 3; + } else { + return pos; + } } else { - write(undefined); // undefined marks an empty content slot + return pos; } } - write(null); // null as marker of the end of items + } else { + return pos; } + cc = input.charCodeAt(pos); + while (_isDigit(cc)) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + } + return pos; +}; - deserialize({ read, logger }) { - this.logger = logger; - { - const items = []; - let item = read(); - while (item !== null) { - items.push(item); - item = read(); - } - this.itemInfo.clear(); - const infoItems = items.map(identifier => { - const info = new PackItemInfo(identifier, undefined, undefined); - this.itemInfo.set(identifier, info); - return info; - }); - for (const info of infoItems) { - info.etag = read(); - } - for (const info of infoItems) { - info.lastAccess = read(); - } - } - this.content.length = 0; - let items = read(); - while (items !== null) { - if (items === undefined) { - this.content.push(items); - } else { - const idx = this.content.length; - const lazy = read(); - this.content.push( - new PackContent( - items, - new Set(), - lazy, - logger, - `${this.content.length}` - ) - ); - for (const identifier of items) { - this.itemInfo.get(identifier).location = idx; - } - } - items = read(); +/** @type {CharHandler} */ +const consumeLessThan = (input, pos, callbacks) => { + if (input.slice(pos + 1, pos + 4) === "!--") return pos + 4; + return pos + 1; +}; + +/** @type {CharHandler} */ +const consumeAt = (input, pos, callbacks) => { + const start = pos; + pos++; + if (pos === input.length) return pos; + if (_startsIdentifier(input, pos)) { + pos = _consumeIdentifier(input, pos); + if (callbacks.atKeyword !== undefined) { + pos = callbacks.atKeyword(input, start, pos); } } -} + return pos; +}; -makeSerializable(Pack, "webpack/lib/cache/PackFileCacheStrategy", "Pack"); +const CHAR_MAP = Array.from({ length: 0x80 }, (_, cc) => { + // https://drafts.csswg.org/css-syntax/#consume-token + switch (cc) { + case CC_LINE_FEED: + case CC_CARRIAGE_RETURN: + case CC_FORM_FEED: + case CC_TAB: + case CC_SPACE: + return consumeSpace; + case CC_QUOTATION_MARK: + case CC_APOSTROPHE: + return consumeString(cc); + case CC_NUMBER_SIGN: + return consumeNumberSign; + case CC_SLASH: + return consumePotentialComment; + // case CC_LEFT_SQUARE: + // case CC_RIGHT_SQUARE: + // case CC_COMMA: + // case CC_COLON: + // return consumeSingleCharToken; + case CC_COMMA: + return consumeComma; + case CC_SEMICOLON: + return consumeSemicolon; + case CC_LEFT_PARENTHESIS: + return consumeLeftParenthesis; + case CC_RIGHT_PARENTHESIS: + return consumeRightParenthesis; + case CC_LEFT_CURLY: + return consumeLeftCurlyBracket; + case CC_RIGHT_CURLY: + return consumeRightCurlyBracket; + case CC_COLON: + return consumePotentialPseudo; + case CC_PLUS_SIGN: + return consumeNumericToken; + case CC_FULL_STOP: + return consumeDot; + case CC_HYPHEN_MINUS: + return consumeMinus; + case CC_LESS_THAN_SIGN: + return consumeLessThan; + case CC_AT_SIGN: + return consumeAt; + case CC_LOWER_U: + return consumePotentialUrl; + case CC_LOW_LINE: + return consumeOtherIdentifier; + default: + if (_isDigit(cc)) return consumeNumericToken; + if ( + (cc >= CC_LOWER_A && cc <= CC_LOWER_Z) || + (cc >= CC_UPPER_A && cc <= CC_UPPER_Z) + ) { + return consumeOtherIdentifier; + } + return consumeSingleCharToken; + } +}); -class PackContentItems { - /** - * @param {Map} map items - */ - constructor(map) { - this.map = map; +/** + * @param {string} input input css + * @param {CssTokenCallbacks} callbacks callbacks + * @returns {void} + */ +module.exports = (input, callbacks) => { + let pos = 0; + while (pos < input.length) { + const cc = input.charCodeAt(pos); + if (cc < 0x80) { + pos = CHAR_MAP[cc](input, pos, callbacks); + } else { + pos++; + } } +}; - serialize({ write, snapshot, rollback, logger, profile }) { - if (profile) { - write(false); - for (const [key, value] of this.map) { - const s = snapshot(); - try { - write(key); - const start = process.hrtime(); - write(value); - const durationHr = process.hrtime(start); - const duration = durationHr[0] * 1000 + durationHr[1] / 1e6; - if (duration > 1) { - if (duration > 500) - logger.error(`Serialization of '${key}': ${duration} ms`); - else if (duration > 50) - logger.warn(`Serialization of '${key}': ${duration} ms`); - else if (duration > 10) - logger.info(`Serialization of '${key}': ${duration} ms`); - else if (duration > 5) - logger.log(`Serialization of '${key}': ${duration} ms`); - else logger.debug(`Serialization of '${key}': ${duration} ms`); +module.exports.eatComments = (input, pos) => { + loop: for (;;) { + const cc = input.charCodeAt(pos); + if (cc === CC_SLASH) { + if (pos === input.length) return pos; + let cc = input.charCodeAt(pos + 1); + if (cc !== CC_ASTERISK) return pos; + pos++; + for (;;) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + while (cc === CC_ASTERISK) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + if (cc === CC_SLASH) { + pos++; + continue loop; } - } catch (e) { - rollback(s); - if (e === NOT_SERIALIZABLE) continue; - logger.warn( - `Skipped not serializable cache item '${key}': ${e.message}` - ); - logger.debug(e.stack); } } - write(null); - return; } - // Try to serialize all at once - const s = snapshot(); - try { - write(true); - write(this.map); - } catch (e) { - rollback(s); + return pos; + } +}; - // Try to serialize each item on it's own - write(false); - for (const [key, value] of this.map) { - const s = snapshot(); - try { - write(key); - write(value); - } catch (e) { - rollback(s); - if (e === NOT_SERIALIZABLE) continue; - logger.warn( - `Skipped not serializable cache item '${key}': ${e.message}` - ); - logger.debug(e.stack); +module.exports.eatWhitespaceAndComments = (input, pos) => { + loop: for (;;) { + const cc = input.charCodeAt(pos); + if (cc === CC_SLASH) { + if (pos === input.length) return pos; + let cc = input.charCodeAt(pos + 1); + if (cc !== CC_ASTERISK) return pos; + pos++; + for (;;) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + while (cc === CC_ASTERISK) { + pos++; + if (pos === input.length) return pos; + cc = input.charCodeAt(pos); + if (cc === CC_SLASH) { + pos++; + continue loop; + } } } - write(null); - } - } - - deserialize({ read, logger, profile }) { - if (read()) { - this.map = read(); - } else if (profile) { - const map = new Map(); - let key = read(); - while (key !== null) { - const start = process.hrtime(); - const value = read(); - const durationHr = process.hrtime(start); - const duration = durationHr[0] * 1000 + durationHr[1] / 1e6; - if (duration > 1) { - if (duration > 100) - logger.error(`Deserialization of '${key}': ${duration} ms`); - else if (duration > 20) - logger.warn(`Deserialization of '${key}': ${duration} ms`); - else if (duration > 5) - logger.info(`Deserialization of '${key}': ${duration} ms`); - else if (duration > 2) - logger.log(`Deserialization of '${key}': ${duration} ms`); - else logger.debug(`Deserialization of '${key}': ${duration} ms`); - } - map.set(key, value); - key = read(); - } - this.map = map; - } else { - const map = new Map(); - let key = read(); - while (key !== null) { - map.set(key, read()); - key = read(); - } - this.map = map; + } else if (_isWhiteSpace(cc)) { + pos++; + continue; } + return pos; } -} +}; -makeSerializable( - PackContentItems, - "webpack/lib/cache/PackFileCacheStrategy", - "PackContentItems" + +/***/ }), + +/***/ 2757: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const { Tracer } = __webpack_require__(5787); +const createSchemaValidation = __webpack_require__(32540); +const { dirname, mkdirpSync } = __webpack_require__(17139); + +/** @typedef {import("../../declarations/plugins/debug/ProfilingPlugin").ProfilingPluginOptions} ProfilingPluginOptions */ +/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ + +const validate = createSchemaValidation( + __webpack_require__(37134), + () => __webpack_require__(50686), + { + name: "Profiling Plugin", + baseDataPath: "options" + } ); +let inspector = undefined; -class PackContent { - /* - This class can be in these states: - | this.lazy | this.content | this.outdated | state - A1 | undefined | Map | false | fresh content - A2 | undefined | Map | true | (will not happen) - B1 | lazy () => {} | undefined | false | not deserialized - B2 | lazy () => {} | undefined | true | not deserialized, but some items has been removed - C1 | lazy* () => {} | Map | false | deserialized - C2 | lazy* () => {} | Map | true | deserialized, and some items has been removed +try { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + inspector = __webpack_require__(31405); +} catch (e) { + console.log("Unable to CPU profile in < node 8.0"); +} - this.used is a subset of this.items. - this.items is a subset of this.content.keys() resp. this.lazy().map.keys() - When this.outdated === false, this.items === this.content.keys() resp. this.lazy().map.keys() - When this.outdated === true, this.items should be used to recreated this.lazy/this.content. - When this.lazy and this.content is set, they contain the same data. - this.get must only be called with a valid item from this.items. - In state C this.lazy is unMemoized - */ +class Profiler { + constructor(inspector) { + this.session = undefined; + this.inspector = inspector; + this._startTime = 0; + } - /** - * @param {Set} items keys - * @param {Set} usedItems used keys - * @param {PackContentItems | function(): Promise} dataOrFn sync or async content - * @param {Logger=} logger logger for logging - * @param {string=} lazyName name of dataOrFn for logging - */ - constructor(items, usedItems, dataOrFn, logger, lazyName) { - this.items = items; - /** @type {function(): Promise | PackContentItems} */ - this.lazy = typeof dataOrFn === "function" ? dataOrFn : undefined; - /** @type {Map} */ - this.content = typeof dataOrFn === "function" ? undefined : dataOrFn.map; - this.outdated = false; - this.used = usedItems; - this.logger = logger; - this.lazyName = lazyName; + hasSession() { + return this.session !== undefined; } - get(identifier) { - this.used.add(identifier); - if (this.content) { - return this.content.get(identifier); + startProfiling() { + if (this.inspector === undefined) { + return Promise.resolve(); } - // We are in state B - const { lazyName } = this; - let timeMessage; - if (lazyName) { - // only log once - this.lazyName = undefined; - timeMessage = `restore cache content ${lazyName} (${formatSize( - this.getSize() - )})`; - this.logger.log( - `starting to restore cache content ${lazyName} (${formatSize( - this.getSize() - )}) because of request to: ${identifier}` - ); - this.logger.time(timeMessage); + try { + this.session = new inspector.Session(); + this.session.connect(); + } catch (_) { + this.session = undefined; + return Promise.resolve(); } - const value = this.lazy(); - if ("then" in value) { - return value.then(data => { - const map = data.map; - if (timeMessage) { - this.logger.timeEnd(timeMessage); - } - // Move to state C - this.content = map; - this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); - return map.get(identifier); + + const hrtime = process.hrtime(); + this._startTime = hrtime[0] * 1000000 + Math.round(hrtime[1] / 1000); + + return Promise.all([ + this.sendCommand("Profiler.setSamplingInterval", { + interval: 100 + }), + this.sendCommand("Profiler.enable"), + this.sendCommand("Profiler.start") + ]); + } + + sendCommand(method, params) { + if (this.hasSession()) { + return new Promise((res, rej) => { + return this.session.post(method, params, (err, params) => { + if (err !== null) { + rej(err); + } else { + res(params); + } + }); }); } else { - const map = value.map; - if (timeMessage) { - this.logger.timeEnd(timeMessage); - } - // Move to state C - this.content = map; - this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); - return map.get(identifier); + return Promise.resolve(); } } - /** - * @param {string} reason explanation why unpack is necessary - * @returns {void | Promise} maybe a promise if lazy - */ - unpack(reason) { - if (this.content) return; - - // Move from state B to C - if (this.lazy) { - const { lazyName } = this; - let timeMessage; - if (lazyName) { - // only log once - this.lazyName = undefined; - timeMessage = `unpack cache content ${lazyName} (${formatSize( - this.getSize() - )})`; - this.logger.log( - `starting to unpack cache content ${lazyName} (${formatSize( - this.getSize() - )}) because ${reason}` - ); - this.logger.time(timeMessage); - } - const value = this.lazy(); - if ("then" in value) { - return value.then(data => { - if (timeMessage) { - this.logger.timeEnd(timeMessage); - } - this.content = data.map; - }); - } else { - if (timeMessage) { - this.logger.timeEnd(timeMessage); - } - this.content = value.map; - } + destroy() { + if (this.hasSession()) { + this.session.disconnect(); } + + return Promise.resolve(); } - /** - * @returns {number} size of the content or -1 if not known - */ - getSize() { - if (!this.lazy) return -1; - const options = /** @type {any} */ (this.lazy).options; - if (!options) return -1; - const size = options.size; - if (typeof size !== "number") return -1; - return size; + stopProfiling() { + return this.sendCommand("Profiler.stop").then(({ profile }) => { + const hrtime = process.hrtime(); + const endTime = hrtime[0] * 1000000 + Math.round(hrtime[1] / 1000); + if (profile.startTime < this._startTime || profile.endTime > endTime) { + // In some cases timestamps mismatch and we need to adjust them + // Both process.hrtime and the inspector timestamps claim to be relative + // to a unknown point in time. But they do not guarantee that this is the + // same point in time. + const duration = profile.endTime - profile.startTime; + const ownDuration = endTime - this._startTime; + const untracked = Math.max(0, ownDuration - duration); + profile.startTime = this._startTime + untracked / 2; + profile.endTime = endTime - untracked / 2; + } + return { profile }; + }); } +} - delete(identifier) { - this.items.delete(identifier); - this.used.delete(identifier); - this.outdated = true; +/** + * an object that wraps Tracer and Profiler with a counter + * @typedef {Object} Trace + * @property {Tracer} trace instance of Tracer + * @property {number} counter Counter + * @property {Profiler} profiler instance of Profiler + * @property {Function} end the end function + */ + +/** + * @param {IntermediateFileSystem} fs filesystem used for output + * @param {string} outputPath The location where to write the log. + * @returns {Trace} The trace object + */ +const createTrace = (fs, outputPath) => { + const trace = new Tracer(); + const profiler = new Profiler(inspector); + if (/\/|\\/.test(outputPath)) { + const dirPath = dirname(fs, outputPath); + mkdirpSync(fs, dirPath); } + const fsStream = fs.createWriteStream(outputPath); - /** - * @template T - * @param {function(any): function(): Promise | PackContentItems} write write function - * @returns {void} - */ - writeLazy(write) { - if (!this.outdated && this.lazy) { - // State B1 or C1 - // this.lazy is still the valid deserialized version - write(this.lazy); - return; - } - if (!this.outdated && this.content) { - // State A1 - const map = new Map(this.content); - // Move to state C1 - this.lazy = SerializerMiddleware.unMemoizeLazy( - write(() => new PackContentItems(map)) - ); - return; - } - if (this.content) { - // State A2 or C2 - /** @type {Map} */ - const map = new Map(); - for (const item of this.items) { - map.set(item, this.content.get(item)); + let counter = 0; + + trace.pipe(fsStream); + // These are critical events that need to be inserted so that tools like + // chrome dev tools can load the profile. + trace.instantEvent({ + name: "TracingStartedInPage", + id: ++counter, + cat: ["disabled-by-default-devtools.timeline"], + args: { + data: { + sessionId: "-1", + page: "0xfff", + frames: [ + { + frame: "0xfff", + url: "webpack", + name: "" + } + ] } - // Move to state C1 - this.outdated = false; - this.content = map; - this.lazy = SerializerMiddleware.unMemoizeLazy( - write(() => new PackContentItems(map)) - ); - return; - } - // State B2 - const { lazyName } = this; - let timeMessage; - if (lazyName) { - // only log once - this.lazyName = undefined; - timeMessage = `unpack cache content ${lazyName} (${formatSize( - this.getSize() - )})`; - this.logger.log( - `starting to unpack cache content ${lazyName} (${formatSize( - this.getSize() - )}) because it's outdated and need to be serialized` - ); - this.logger.time(timeMessage); } - const value = this.lazy(); - this.outdated = false; - if ("then" in value) { - // Move to state B1 - this.lazy = write(() => - value.then(data => { - if (timeMessage) { - this.logger.timeEnd(timeMessage); - } - const oldMap = data.map; - /** @type {Map} */ - const map = new Map(); - for (const item of this.items) { - map.set(item, oldMap.get(item)); - } - // Move to state C1 (or maybe C2) - this.content = map; - this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy); + }); - return new PackContentItems(map); - }) - ); - } else { - // Move to state C1 - if (timeMessage) { - this.logger.timeEnd(timeMessage); - } - const oldMap = value.map; - /** @type {Map} */ - const map = new Map(); - for (const item of this.items) { - map.set(item, oldMap.get(item)); + trace.instantEvent({ + name: "TracingStartedInBrowser", + id: ++counter, + cat: ["disabled-by-default-devtools.timeline"], + args: { + data: { + sessionId: "-1" } - this.content = map; - this.lazy = write(() => new PackContentItems(map)); } - } -} + }); -const allowCollectingMemory = buf => { - const wasted = buf.buffer.byteLength - buf.byteLength; - if (wasted > 8192 && (wasted > 1048576 || wasted > buf.byteLength)) { - return Buffer.from(buf); - } - return buf; + return { + trace, + counter, + profiler, + end: callback => { + trace.push("]"); + // Wait until the write stream finishes. + fsStream.on("close", () => { + callback(); + }); + // Tear down the readable trace stream. + trace.push(null); + } + }; }; -class PackFileCacheStrategy { - /** - * @param {Object} options options - * @param {Compiler} options.compiler the compiler - * @param {IntermediateFileSystem} options.fs the filesystem - * @param {string} options.context the context directory - * @param {string} options.cacheLocation the location of the cache data - * @param {string} options.version version identifier - * @param {Logger} options.logger a logger - * @param {SnapshotOptions} options.snapshot options regarding snapshotting - * @param {number} options.maxAge max age of cache items - * @param {boolean} options.profile track and log detailed timing information for individual cache items - * @param {boolean} options.allowCollectingMemory allow to collect unused memory created during deserialization - * @param {false | "gzip" | "brotli"} options.compression compression used - */ - constructor({ - compiler, - fs, - context, - cacheLocation, - version, - logger, - snapshot, - maxAge, - profile, - allowCollectingMemory, - compression - }) { - this.fileSerializer = createFileSerializer( - fs, - compiler.options.output.hashFunction - ); - this.fileSystemInfo = new FileSystemInfo(fs, { - managedPaths: snapshot.managedPaths, - immutablePaths: snapshot.immutablePaths, - logger: logger.getChildLogger("webpack.FileSystemInfo"), - hashFunction: compiler.options.output.hashFunction - }); - this.compiler = compiler; - this.context = context; - this.cacheLocation = cacheLocation; - this.version = version; - this.logger = logger; - this.maxAge = maxAge; - this.profile = profile; - this.allowCollectingMemory = allowCollectingMemory; - this.compression = compression; - this._extension = - compression === "brotli" - ? ".pack.br" - : compression === "gzip" - ? ".pack.gz" - : ".pack"; - this.snapshot = snapshot; - /** @type {Set} */ - this.buildDependencies = new Set(); - /** @type {LazySet} */ - this.newBuildDependencies = new LazySet(); - /** @type {Snapshot} */ - this.resolveBuildDependenciesSnapshot = undefined; - /** @type {Map} */ - this.resolveResults = undefined; - /** @type {Snapshot} */ - this.buildSnapshot = undefined; - /** @type {Promise} */ - this.packPromise = this._openPack(); - this.storePromise = Promise.resolve(); - } - - _getPack() { - if (this.packPromise === undefined) { - this.packPromise = this.storePromise.then(() => this._openPack()); - } - return this.packPromise; - } +const pluginName = "ProfilingPlugin"; +class ProfilingPlugin { /** - * @returns {Promise} the pack + * @param {ProfilingPluginOptions=} options options object */ - _openPack() { - const { logger, profile, cacheLocation, version } = this; - /** @type {Snapshot} */ - let buildSnapshot; - /** @type {Set} */ - let buildDependencies; - /** @type {Set} */ - let newBuildDependencies; - /** @type {Snapshot} */ - let resolveBuildDependenciesSnapshot; - /** @type {Map} */ - let resolveResults; - logger.time("restore cache container"); - return this.fileSerializer - .deserialize(null, { - filename: `${cacheLocation}/index${this._extension}`, - extension: `${this._extension}`, - logger, - profile, - retainedBuffer: this.allowCollectingMemory - ? allowCollectingMemory - : undefined - }) - .catch(err => { - if (err.code !== "ENOENT") { - logger.warn( - `Restoring pack failed from ${cacheLocation}${this._extension}: ${err}` - ); - logger.debug(err.stack); - } else { - logger.debug( - `No pack exists at ${cacheLocation}${this._extension}: ${err}` - ); - } - return undefined; - }) - .then(packContainer => { - logger.timeEnd("restore cache container"); - if (!packContainer) return undefined; - if (!(packContainer instanceof PackContainer)) { - logger.warn( - `Restored pack from ${cacheLocation}${this._extension}, but contained content is unexpected.`, - packContainer - ); - return undefined; - } - if (packContainer.version !== version) { - logger.log( - `Restored pack from ${cacheLocation}${this._extension}, but version doesn't match.` - ); - return undefined; - } - logger.time("check build dependencies"); - return Promise.all([ - new Promise((resolve, reject) => { - this.fileSystemInfo.checkSnapshotValid( - packContainer.buildSnapshot, - (err, valid) => { - if (err) { - logger.log( - `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of build dependencies errored: ${err}.` - ); - logger.debug(err.stack); - return resolve(false); - } - if (!valid) { - logger.log( - `Restored pack from ${cacheLocation}${this._extension}, but build dependencies have changed.` - ); - return resolve(false); - } - buildSnapshot = packContainer.buildSnapshot; - return resolve(true); - } - ); - }), - new Promise((resolve, reject) => { - this.fileSystemInfo.checkSnapshotValid( - packContainer.resolveBuildDependenciesSnapshot, - (err, valid) => { - if (err) { - logger.log( - `Restored pack from ${cacheLocation}${this._extension}, but checking snapshot of resolving of build dependencies errored: ${err}.` - ); - logger.debug(err.stack); - return resolve(false); - } - if (valid) { - resolveBuildDependenciesSnapshot = - packContainer.resolveBuildDependenciesSnapshot; - buildDependencies = packContainer.buildDependencies; - resolveResults = packContainer.resolveResults; - return resolve(true); - } - logger.log( - "resolving of build dependencies is invalid, will re-resolve build dependencies" - ); - this.fileSystemInfo.checkResolveResultsValid( - packContainer.resolveResults, - (err, valid) => { - if (err) { - logger.log( - `Restored pack from ${cacheLocation}${this._extension}, but resolving of build dependencies errored: ${err}.` - ); - logger.debug(err.stack); - return resolve(false); - } - if (valid) { - newBuildDependencies = packContainer.buildDependencies; - resolveResults = packContainer.resolveResults; - return resolve(true); - } - logger.log( - `Restored pack from ${cacheLocation}${this._extension}, but build dependencies resolve to different locations.` - ); - return resolve(false); - } - ); - } - ); - }) - ]) - .catch(err => { - logger.timeEnd("check build dependencies"); - throw err; - }) - .then(([buildSnapshotValid, resolveValid]) => { - logger.timeEnd("check build dependencies"); - if (buildSnapshotValid && resolveValid) { - logger.time("restore cache content metadata"); - const d = packContainer.data(); - logger.timeEnd("restore cache content metadata"); - return d; - } - return undefined; - }); - }) - .then(pack => { - if (pack) { - pack.maxAge = this.maxAge; - this.buildSnapshot = buildSnapshot; - if (buildDependencies) this.buildDependencies = buildDependencies; - if (newBuildDependencies) - this.newBuildDependencies.addAll(newBuildDependencies); - this.resolveResults = resolveResults; - this.resolveBuildDependenciesSnapshot = - resolveBuildDependenciesSnapshot; - return pack; - } - return new Pack(logger, this.maxAge); - }) - .catch(err => { - this.logger.warn( - `Restoring pack from ${cacheLocation}${this._extension} failed: ${err}` - ); - this.logger.debug(err.stack); - return new Pack(logger, this.maxAge); - }); + constructor(options = {}) { + validate(options); + this.outputPath = options.outputPath || "events.json"; } - /** - * @param {string} identifier unique name for the resource - * @param {Etag | null} etag etag of the resource - * @param {any} data cached content - * @returns {Promise} promise - */ - store(identifier, etag, data) { - return this._getPack().then(pack => { - pack.set(identifier, etag === null ? null : etag.toString(), data); + apply(compiler) { + const tracer = createTrace( + compiler.intermediateFileSystem, + this.outputPath + ); + tracer.profiler.startProfiling(); + + // Compiler Hooks + Object.keys(compiler.hooks).forEach(hookName => { + const hook = compiler.hooks[hookName]; + if (hook) { + hook.intercept(makeInterceptorFor("Compiler", tracer)(hookName)); + } }); - } - /** - * @param {string} identifier unique name for the resource - * @param {Etag | null} etag etag of the resource - * @returns {Promise} promise to the cached content - */ - restore(identifier, etag) { - return this._getPack() - .then(pack => - pack.get(identifier, etag === null ? null : etag.toString()) - ) - .catch(err => { - if (err && err.code !== "ENOENT") { - this.logger.warn( - `Restoring failed for ${identifier} from pack: ${err}` - ); - this.logger.debug(err.stack); - } - }); - } + Object.keys(compiler.resolverFactory.hooks).forEach(hookName => { + const hook = compiler.resolverFactory.hooks[hookName]; + if (hook) { + hook.intercept(makeInterceptorFor("Resolver", tracer)(hookName)); + } + }); - storeBuildDependencies(dependencies) { - this.newBuildDependencies.addAll(dependencies); - } + compiler.hooks.compilation.tap( + pluginName, + (compilation, { normalModuleFactory, contextModuleFactory }) => { + interceptAllHooksFor(compilation, tracer, "Compilation"); + interceptAllHooksFor( + normalModuleFactory, + tracer, + "Normal Module Factory" + ); + interceptAllHooksFor( + contextModuleFactory, + tracer, + "Context Module Factory" + ); + interceptAllParserHooks(normalModuleFactory, tracer); + interceptAllJavascriptModulesPluginHooks(compilation, tracer); + } + ); - afterAllStored() { - const packPromise = this.packPromise; - if (packPromise === undefined) return Promise.resolve(); - const reportProgress = ProgressPlugin.getReporter(this.compiler); - return (this.storePromise = packPromise - .then(pack => { - pack.stopCapturingRequests(); - if (!pack.invalid) return; - this.packPromise = undefined; - this.logger.log(`Storing pack...`); - let promise; - const newBuildDependencies = new Set(); - for (const dep of this.newBuildDependencies) { - if (!this.buildDependencies.has(dep)) { - newBuildDependencies.add(dep); + // We need to write out the CPU profile when we are all done. + compiler.hooks.done.tapAsync( + { + name: pluginName, + stage: Infinity + }, + (stats, callback) => { + if (compiler.watchMode) return callback(); + tracer.profiler.stopProfiling().then(parsedResults => { + if (parsedResults === undefined) { + tracer.profiler.destroy(); + tracer.end(callback); + return; } - } - if (newBuildDependencies.size > 0 || !this.buildSnapshot) { - if (reportProgress) reportProgress(0.5, "resolve build dependencies"); - this.logger.debug( - `Capturing build dependencies... (${Array.from( - newBuildDependencies - ).join(", ")})` - ); - promise = new Promise((resolve, reject) => { - this.logger.time("resolve build dependencies"); - this.fileSystemInfo.resolveBuildDependencies( - this.context, - newBuildDependencies, - (err, result) => { - this.logger.timeEnd("resolve build dependencies"); - if (err) return reject(err); - this.logger.time("snapshot build dependencies"); - const { - files, - directories, - missing, - resolveResults, - resolveDependencies - } = result; - if (this.resolveResults) { - for (const [key, value] of resolveResults) { - this.resolveResults.set(key, value); - } - } else { - this.resolveResults = resolveResults; - } - if (reportProgress) { - reportProgress( - 0.6, - "snapshot build dependencies", - "resolving" - ); - } - this.fileSystemInfo.createSnapshot( - undefined, - resolveDependencies.files, - resolveDependencies.directories, - resolveDependencies.missing, - this.snapshot.resolveBuildDependencies, - (err, snapshot) => { - if (err) { - this.logger.timeEnd("snapshot build dependencies"); - return reject(err); - } - if (!snapshot) { - this.logger.timeEnd("snapshot build dependencies"); - return reject( - new Error("Unable to snapshot resolve dependencies") - ); - } - if (this.resolveBuildDependenciesSnapshot) { - this.resolveBuildDependenciesSnapshot = - this.fileSystemInfo.mergeSnapshots( - this.resolveBuildDependenciesSnapshot, - snapshot - ); - } else { - this.resolveBuildDependenciesSnapshot = snapshot; - } - if (reportProgress) { - reportProgress( - 0.7, - "snapshot build dependencies", - "modules" - ); - } - this.fileSystemInfo.createSnapshot( - undefined, - files, - directories, - missing, - this.snapshot.buildDependencies, - (err, snapshot) => { - this.logger.timeEnd("snapshot build dependencies"); - if (err) return reject(err); - if (!snapshot) { - return reject( - new Error("Unable to snapshot build dependencies") - ); - } - this.logger.debug("Captured build dependencies"); + const cpuStartTime = parsedResults.profile.startTime; + const cpuEndTime = parsedResults.profile.endTime; - if (this.buildSnapshot) { - this.buildSnapshot = - this.fileSystemInfo.mergeSnapshots( - this.buildSnapshot, - snapshot - ); - } else { - this.buildSnapshot = snapshot; - } + tracer.trace.completeEvent({ + name: "TaskQueueManager::ProcessTaskFromWorkQueue", + id: ++tracer.counter, + cat: ["toplevel"], + ts: cpuStartTime, + args: { + src_file: "../../ipc/ipc_moji_bootstrap.cc", + src_func: "Accept" + } + }); - resolve(); - } - ); - } - ); + tracer.trace.completeEvent({ + name: "EvaluateScript", + id: ++tracer.counter, + cat: ["devtools.timeline"], + ts: cpuStartTime, + dur: cpuEndTime - cpuStartTime, + args: { + data: { + url: "webpack", + lineNumber: 1, + columnNumber: 1, + frame: "0xFFF" } - ); + } }); - } else { - promise = Promise.resolve(); - } - return promise.then(() => { - if (reportProgress) reportProgress(0.8, "serialize pack"); - this.logger.time(`store pack`); - const updatedBuildDependencies = new Set(this.buildDependencies); - for (const dep of newBuildDependencies) { - updatedBuildDependencies.add(dep); - } - const content = new PackContainer( - pack, - this.version, - this.buildSnapshot, - updatedBuildDependencies, - this.resolveResults, - this.resolveBuildDependenciesSnapshot - ); - return this.fileSerializer - .serialize(content, { - filename: `${this.cacheLocation}/index${this._extension}`, - extension: `${this._extension}`, - logger: this.logger, - profile: this.profile - }) - .then(() => { - for (const dep of newBuildDependencies) { - this.buildDependencies.add(dep); + + tracer.trace.instantEvent({ + name: "CpuProfile", + id: ++tracer.counter, + cat: ["disabled-by-default-devtools.timeline"], + ts: cpuEndTime, + args: { + data: { + cpuProfile: parsedResults.profile } - this.newBuildDependencies.clear(); - this.logger.timeEnd(`store pack`); - const stats = pack.getContentStats(); - this.logger.log( - "Stored pack (%d items, %d files, %d MiB)", - pack.itemInfo.size, - stats.count, - Math.round(stats.size / 1024 / 1024) - ); - }) - .catch(err => { - this.logger.timeEnd(`store pack`); - this.logger.warn(`Caching failed for pack: ${err}`); - this.logger.debug(err.stack); - }); + } + }); + + tracer.profiler.destroy(); + tracer.end(callback); }); - }) - .catch(err => { - this.logger.warn(`Caching failed for pack: ${err}`); - this.logger.debug(err.stack); - })); + } + ); } +} - clear() { - this.fileSystemInfo.clear(); - this.buildDependencies.clear(); - this.newBuildDependencies.clear(); - this.resolveBuildDependenciesSnapshot = undefined; - this.resolveResults = undefined; - this.buildSnapshot = undefined; - this.packPromise = undefined; +const interceptAllHooksFor = (instance, tracer, logLabel) => { + if (Reflect.has(instance, "hooks")) { + Object.keys(instance.hooks).forEach(hookName => { + const hook = instance.hooks[hookName]; + if (hook && !hook._fakeHook) { + hook.intercept(makeInterceptorFor(logLabel, tracer)(hookName)); + } + }); } -} +}; -module.exports = PackFileCacheStrategy; +const interceptAllParserHooks = (moduleFactory, tracer) => { + const moduleTypes = [ + "javascript/auto", + "javascript/dynamic", + "javascript/esm", + "json", + "webassembly/async", + "webassembly/sync" + ]; + moduleTypes.forEach(moduleType => { + moduleFactory.hooks.parser + .for(moduleType) + .tap("ProfilingPlugin", (parser, parserOpts) => { + interceptAllHooksFor(parser, tracer, "Parser"); + }); + }); +}; -/***/ }), +const interceptAllJavascriptModulesPluginHooks = (compilation, tracer) => { + interceptAllHooksFor( + { + hooks: + (__webpack_require__(89464).getCompilationHooks)( + compilation + ) + }, + tracer, + "JavascriptModulesPlugin" + ); +}; -/***/ 97347: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const makeInterceptorFor = (instance, tracer) => hookName => ({ + register: ({ name, type, context, fn }) => { + const newFn = + // Don't tap our own hooks to ensure stream can close cleanly + name === pluginName + ? fn + : makeNewProfiledTapFn(hookName, tracer, { + name, + type, + fn + }); + return { + name, + type, + context, + fn: newFn + }; + } +}); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const LazySet = __webpack_require__(38938); -const makeSerializable = __webpack_require__(33032); - -/** @typedef {import("enhanced-resolve/lib/Resolver")} Resolver */ -/** @typedef {import("../CacheFacade").ItemCacheFacade} ItemCacheFacade */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../FileSystemInfo")} FileSystemInfo */ -/** @typedef {import("../FileSystemInfo").Snapshot} Snapshot */ - -class CacheEntry { - constructor(result, snapshot) { - this.result = result; - this.snapshot = snapshot; - } - - serialize({ write }) { - write(this.result); - write(this.snapshot); - } - - deserialize({ read }) { - this.result = read(); - this.snapshot = read(); - } -} - -makeSerializable(CacheEntry, "webpack/lib/cache/ResolverCachePlugin"); - -/** - * @template T - * @param {Set | LazySet} set set to add items to - * @param {Set | LazySet} otherSet set to add items from - * @returns {void} - */ -const addAllToSet = (set, otherSet) => { - if (set instanceof LazySet) { - set.addAll(otherSet); - } else { - for (const item of otherSet) { - set.add(item); - } - } -}; +// TODO improve typing +/** @typedef {(...args: TODO[]) => void | Promise} PluginFunction */ /** - * @param {Object} object an object - * @param {boolean} excludeContext if true, context is not included in string - * @returns {string} stringified version + * @param {string} hookName Name of the hook to profile. + * @param {Trace} tracer The trace object. + * @param {object} options Options for the profiled fn. + * @param {string} options.name Plugin name + * @param {string} options.type Plugin type (sync | async | promise) + * @param {PluginFunction} options.fn Plugin function + * @returns {PluginFunction} Chainable hooked function. */ -const objectToString = (object, excludeContext) => { - let str = ""; - for (const key in object) { - if (excludeContext && key === "context") continue; - const value = object[key]; - if (typeof value === "object" && value !== null) { - str += `|${key}=[${objectToString(value, false)}|]`; - } else { - str += `|${key}=|${value}`; - } - } - return str; -}; +const makeNewProfiledTapFn = (hookName, tracer, { name, type, fn }) => { + const defaultCategory = ["blink.user_timing"]; -class ResolverCachePlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const cache = compiler.getCache("ResolverCachePlugin"); - /** @type {FileSystemInfo} */ - let fileSystemInfo; - let snapshotOptions; - let realResolves = 0; - let cachedResolves = 0; - let cacheInvalidResolves = 0; - let concurrentResolves = 0; - compiler.hooks.thisCompilation.tap("ResolverCachePlugin", compilation => { - snapshotOptions = compilation.options.snapshot.resolve; - fileSystemInfo = compilation.fileSystemInfo; - compilation.hooks.finishModules.tap("ResolverCachePlugin", () => { - if (realResolves + cachedResolves > 0) { - const logger = compilation.getLogger("webpack.ResolverCachePlugin"); - logger.log( - `${Math.round( - (100 * realResolves) / (realResolves + cachedResolves) - )}% really resolved (${realResolves} real resolves with ${cacheInvalidResolves} cached but invalid, ${cachedResolves} cached valid, ${concurrentResolves} concurrent)` - ); - realResolves = 0; - cachedResolves = 0; - cacheInvalidResolves = 0; - concurrentResolves = 0; - } - }); - }); - /** - * @param {ItemCacheFacade} itemCache cache - * @param {Resolver} resolver the resolver - * @param {Object} resolveContext context for resolving meta info - * @param {Object} request the request info object - * @param {function((Error | null)=, Object=): void} callback callback function - * @returns {void} - */ - const doRealResolve = ( - itemCache, - resolver, - resolveContext, - request, - callback - ) => { - realResolves++; - const newRequest = { - _ResolverCachePluginCacheMiss: true, - ...request - }; - const newResolveContext = { - ...resolveContext, - stack: new Set(), - missingDependencies: new LazySet(), - fileDependencies: new LazySet(), - contextDependencies: new LazySet() + switch (type) { + case "promise": + return (...args) => { + const id = ++tracer.counter; + tracer.trace.begin({ + name, + id, + cat: defaultCategory + }); + const promise = /** @type {Promise<*>} */ (fn(...args)); + return promise.then(r => { + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + return r; + }); }; - const propagate = key => { - if (resolveContext[key]) { - addAllToSet(resolveContext[key], newResolveContext[key]); - } + case "async": + return (...args) => { + const id = ++tracer.counter; + tracer.trace.begin({ + name, + id, + cat: defaultCategory + }); + const callback = args.pop(); + fn(...args, (...r) => { + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + callback(...r); + }); }; - const resolveTime = Date.now(); - resolver.doResolve( - resolver.hooks.resolve, - newRequest, - "Cache miss", - newResolveContext, - (err, result) => { - propagate("fileDependencies"); - propagate("contextDependencies"); - propagate("missingDependencies"); - if (err) return callback(err); - const fileDependencies = newResolveContext.fileDependencies; - const contextDependencies = newResolveContext.contextDependencies; - const missingDependencies = newResolveContext.missingDependencies; - fileSystemInfo.createSnapshot( - resolveTime, - fileDependencies, - contextDependencies, - missingDependencies, - snapshotOptions, - (err, snapshot) => { - if (err) return callback(err); - if (!snapshot) { - if (result) return callback(null, result); - return callback(); - } - itemCache.store(new CacheEntry(result, snapshot), storeErr => { - if (storeErr) return callback(storeErr); - if (result) return callback(null, result); - callback(); - }); - } - ); + case "sync": + return (...args) => { + const id = ++tracer.counter; + // Do not instrument ourself due to the CPU + // profile needing to be the last event in the trace. + if (name === pluginName) { + return fn(...args); } - ); - }; - compiler.resolverFactory.hooks.resolver.intercept({ - factory(type, hook) { - /** @type {Map} */ - const activeRequests = new Map(); - hook.tap( - "ResolverCachePlugin", - /** - * @param {Resolver} resolver the resolver - * @param {Object} options resolve options - * @param {Object} userOptions resolve options passed by the user - * @returns {void} - */ - (resolver, options, userOptions) => { - if (options.cache !== true) return; - const optionsIdent = objectToString(userOptions, false); - const cacheWithContext = - options.cacheWithContext !== undefined - ? options.cacheWithContext - : false; - resolver.hooks.resolve.tapAsync( - { - name: "ResolverCachePlugin", - stage: -100 - }, - (request, resolveContext, callback) => { - if (request._ResolverCachePluginCacheMiss || !fileSystemInfo) { - return callback(); - } - const identifier = `${type}${optionsIdent}${objectToString( - request, - !cacheWithContext - )}`; - const activeRequest = activeRequests.get(identifier); - if (activeRequest) { - activeRequest.push(callback); - return; - } - const itemCache = cache.getItemCache(identifier, null); - let callbacks; - const done = (err, result) => { - if (callbacks === undefined) { - callback(err, result); - callbacks = false; - } else { - for (const callback of callbacks) { - callback(err, result); - } - activeRequests.delete(identifier); - callbacks = false; - } - }; - /** - * @param {Error=} err error if any - * @param {CacheEntry=} cacheEntry cache entry - * @returns {void} - */ - const processCacheResult = (err, cacheEntry) => { - if (err) return done(err); - if (cacheEntry) { - const { snapshot, result } = cacheEntry; - fileSystemInfo.checkSnapshotValid( - snapshot, - (err, valid) => { - if (err || !valid) { - cacheInvalidResolves++; - return doRealResolve( - itemCache, - resolver, - resolveContext, - request, - done - ); - } - cachedResolves++; - if (resolveContext.missingDependencies) { - addAllToSet( - resolveContext.missingDependencies, - snapshot.getMissingIterable() - ); - } - if (resolveContext.fileDependencies) { - addAllToSet( - resolveContext.fileDependencies, - snapshot.getFileIterable() - ); - } - if (resolveContext.contextDependencies) { - addAllToSet( - resolveContext.contextDependencies, - snapshot.getContextIterable() - ); - } - done(null, result); - } - ); - } else { - doRealResolve( - itemCache, - resolver, - resolveContext, - request, - done - ); - } - }; - itemCache.get(processCacheResult); - if (callbacks === undefined) { - callbacks = [callback]; - activeRequests.set(identifier, callbacks); - } - } - ); - } - ); - return hook; - } - }); + tracer.trace.begin({ + name, + id, + cat: defaultCategory + }); + let r; + try { + r = fn(...args); + } catch (error) { + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + throw error; + } + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + return r; + }; + default: + break; } -} +}; -module.exports = ResolverCachePlugin; +module.exports = ProfilingPlugin; +module.exports.Profiler = Profiler; /***/ }), -/***/ 94075: +/***/ 96816: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -70030,86 +70430,226 @@ module.exports = ResolverCachePlugin; -const createHash = __webpack_require__(49835); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {typeof import("../util/Hash")} HashConstructor */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** - * @typedef {Object} HashableObject - * @property {function(Hash): void} updateHash - */ +/** @type {Record} */ +const DEFINITIONS = { + f: { + definition: "var __WEBPACK_AMD_DEFINE_RESULT__;", + content: `!(__WEBPACK_AMD_DEFINE_RESULT__ = (#).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, + requests: [ + RuntimeGlobals.require, + RuntimeGlobals.exports, + RuntimeGlobals.module + ] + }, + o: { + definition: "", + content: "!(module.exports = #)", + requests: [RuntimeGlobals.module] + }, + of: { + definition: + "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;", + content: `!(__WEBPACK_AMD_DEFINE_FACTORY__ = (#), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, + requests: [ + RuntimeGlobals.require, + RuntimeGlobals.exports, + RuntimeGlobals.module + ] + }, + af: { + definition: + "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", + content: `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = (#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, + requests: [RuntimeGlobals.exports, RuntimeGlobals.module] + }, + ao: { + definition: "", + content: "!(#, module.exports = #)", + requests: [RuntimeGlobals.module] + }, + aof: { + definition: + "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", + content: `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, + requests: [RuntimeGlobals.exports, RuntimeGlobals.module] + }, + lf: { + definition: "var XXX, XXXmodule;", + content: + "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = (#).call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))", + requests: [RuntimeGlobals.require, RuntimeGlobals.module] + }, + lo: { + definition: "var XXX;", + content: "!(XXX = #)", + requests: [] + }, + lof: { + definition: "var XXX, XXXfactory, XXXmodule;", + content: + "!(XXXfactory = (#), (typeof XXXfactory === 'function' ? ((XXXmodule = { id: YYY, exports: {}, loaded: false }), (XXX = XXXfactory.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule)), (XXXmodule.loaded = true), XXX === undefined && (XXX = XXXmodule.exports)) : XXX = XXXfactory))", + requests: [RuntimeGlobals.require, RuntimeGlobals.module] + }, + laf: { + definition: "var __WEBPACK_AMD_DEFINE_ARRAY__, XXX, XXXexports;", + content: + "!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = (#).apply(XXXexports = {}, __WEBPACK_AMD_DEFINE_ARRAY__), XXX === undefined && (XXX = XXXexports))", + requests: [] + }, + lao: { + definition: "var XXX;", + content: "!(#, XXX = #)", + requests: [] + }, + laof: { + definition: "var XXXarray, XXXfactory, XXXexports, XXX;", + content: `!(XXXarray = #, XXXfactory = (#), + (typeof XXXfactory === 'function' ? + ((XXX = XXXfactory.apply(XXXexports = {}, XXXarray)), XXX === undefined && (XXX = XXXexports)) : + (XXX = XXXfactory) + ))`, + requests: [] + } +}; -class LazyHashedEtag { - /** - * @param {HashableObject} obj object with updateHash method - * @param {string | HashConstructor} hashFunction the hash function to use - */ - constructor(obj, hashFunction = "md4") { - this._obj = obj; - this._hash = undefined; - this._hashFunction = hashFunction; +class AMDDefineDependency extends NullDependency { + constructor(range, arrayRange, functionRange, objectRange, namedModule) { + super(); + this.range = range; + this.arrayRange = arrayRange; + this.functionRange = functionRange; + this.objectRange = objectRange; + this.namedModule = namedModule; + this.localModule = null; + } + + get type() { + return "amd define"; + } + + serialize(context) { + const { write } = context; + write(this.range); + write(this.arrayRange); + write(this.functionRange); + write(this.objectRange); + write(this.namedModule); + write(this.localModule); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.range = read(); + this.arrayRange = read(); + this.functionRange = read(); + this.objectRange = read(); + this.namedModule = read(); + this.localModule = read(); + super.deserialize(context); } +} +makeSerializable( + AMDDefineDependency, + "webpack/lib/dependencies/AMDDefineDependency" +); + +AMDDefineDependency.Template = class AMDDefineDependencyTemplate extends ( + NullDependency.Template +) { /** - * @returns {string} hash of object + * @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} */ - toString() { - if (this._hash === undefined) { - const hash = createHash(this._hashFunction); - this._obj.updateHash(hash); - this._hash = /** @type {string} */ (hash.digest("base64")); + apply(dependency, source, { runtimeRequirements }) { + const dep = /** @type {AMDDefineDependency} */ (dependency); + const branch = this.branch(dep); + const { definition, content, requests } = DEFINITIONS[branch]; + for (const req of requests) { + runtimeRequirements.add(req); } - return this._hash; + this.replace(dep, source, definition, content); } -} -/** @type {Map>} */ -const mapStrings = new Map(); + localModuleVar(dependency) { + return ( + dependency.localModule && + dependency.localModule.used && + dependency.localModule.variableName() + ); + } -/** @type {WeakMap>} */ -const mapObjects = new WeakMap(); + branch(dependency) { + const localModuleVar = this.localModuleVar(dependency) ? "l" : ""; + const arrayRange = dependency.arrayRange ? "a" : ""; + const objectRange = dependency.objectRange ? "o" : ""; + const functionRange = dependency.functionRange ? "f" : ""; + return localModuleVar + arrayRange + objectRange + functionRange; + } -/** - * @param {HashableObject} obj object with updateHash method - * @param {string | HashConstructor} hashFunction the hash function to use - * @returns {LazyHashedEtag} etag - */ -const getter = (obj, hashFunction = "md4") => { - let innerMap; - if (typeof hashFunction === "string") { - innerMap = mapStrings.get(hashFunction); - if (innerMap === undefined) { - const newHash = new LazyHashedEtag(obj, hashFunction); - innerMap = new WeakMap(); - innerMap.set(obj, newHash); - mapStrings.set(hashFunction, innerMap); - return newHash; + replace(dependency, source, definition, text) { + const localModuleVar = this.localModuleVar(dependency); + if (localModuleVar) { + text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); + definition = definition.replace( + /XXX/g, + localModuleVar.replace(/\$/g, "$$$$") + ); } - } else { - innerMap = mapObjects.get(hashFunction); - if (innerMap === undefined) { - const newHash = new LazyHashedEtag(obj, hashFunction); - innerMap = new WeakMap(); - innerMap.set(obj, newHash); - mapObjects.set(hashFunction, innerMap); - return newHash; + + if (dependency.namedModule) { + text = text.replace(/YYY/g, JSON.stringify(dependency.namedModule)); + } + + const texts = text.split("#"); + + if (definition) source.insert(0, definition); + + let current = dependency.range[0]; + if (dependency.arrayRange) { + source.replace(current, dependency.arrayRange[0] - 1, texts.shift()); + current = dependency.arrayRange[1]; + } + + if (dependency.objectRange) { + source.replace(current, dependency.objectRange[0] - 1, texts.shift()); + current = dependency.objectRange[1]; + } else if (dependency.functionRange) { + source.replace(current, dependency.functionRange[0] - 1, texts.shift()); + current = dependency.functionRange[1]; } + source.replace(current, dependency.range[1] - 1, texts.shift()); + if (texts.length > 0) throw new Error("Implementation error"); } - const hash = innerMap.get(obj); - if (hash !== undefined) return hash; - const newHash = new LazyHashedEtag(obj, hashFunction); - innerMap.set(obj, newHash); - return newHash; }; -module.exports = getter; +module.exports = AMDDefineDependency; /***/ }), -/***/ 54980: -/***/ (function(module) { +/***/ 48519: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -70119,79 +70659,359 @@ module.exports = getter; -/** @typedef {import("../Cache").Etag} Etag */ +const RuntimeGlobals = __webpack_require__(16475); +const AMDDefineDependency = __webpack_require__(96816); +const AMDRequireArrayDependency = __webpack_require__(33516); +const AMDRequireContextDependency = __webpack_require__(96123); +const AMDRequireItemDependency = __webpack_require__(71806); +const ConstDependency = __webpack_require__(76911); +const ContextDependencyHelpers = __webpack_require__(99630); +const DynamicExports = __webpack_require__(32006); +const LocalModuleDependency = __webpack_require__(52805); +const { addLocalModule, getLocalModule } = __webpack_require__(75827); -class MergedEtag { - /** - * @param {Etag} a first - * @param {Etag} b second - */ - constructor(a, b) { - this.a = a; - this.b = b; - } +const isBoundFunctionExpression = expr => { + if (expr.type !== "CallExpression") return false; + if (expr.callee.type !== "MemberExpression") return false; + if (expr.callee.computed) return false; + if (expr.callee.object.type !== "FunctionExpression") return false; + if (expr.callee.property.type !== "Identifier") return false; + if (expr.callee.property.name !== "bind") return false; + return true; +}; - toString() { - return `${this.a.toString()}|${this.b.toString()}`; +const isUnboundFunctionExpression = expr => { + if (expr.type === "FunctionExpression") return true; + if (expr.type === "ArrowFunctionExpression") return true; + return false; +}; + +const isCallable = expr => { + if (isUnboundFunctionExpression(expr)) return true; + if (isBoundFunctionExpression(expr)) return true; + return false; +}; + +class AMDDefineDependencyParserPlugin { + constructor(options) { + this.options = options; } -} -const dualObjectMap = new WeakMap(); -const objectStringMap = new WeakMap(); + apply(parser) { + parser.hooks.call + .for("define") + .tap( + "AMDDefineDependencyParserPlugin", + this.processCallDefine.bind(this, parser) + ); + } -/** - * @param {Etag} a first - * @param {Etag} b second - * @returns {Etag} result - */ -const mergeEtags = (a, b) => { - if (typeof a === "string") { - if (typeof b === "string") { - return `${a}|${b}`; - } else { - const temp = b; - b = a; - a = temp; + processArray(parser, expr, param, identifiers, namedModule) { + if (param.isArray()) { + param.items.forEach((param, idx) => { + if ( + param.isString() && + ["require", "module", "exports"].includes(param.string) + ) + identifiers[idx] = param.string; + const result = this.processItem(parser, expr, param, namedModule); + if (result === undefined) { + this.processContext(parser, expr, param); + } + }); + return true; + } else if (param.isConstArray()) { + const deps = []; + param.array.forEach((request, idx) => { + let dep; + let localModule; + if (request === "require") { + identifiers[idx] = request; + dep = "__webpack_require__"; + } else if (["exports", "module"].includes(request)) { + identifiers[idx] = request; + dep = request; + } else if ((localModule = getLocalModule(parser.state, request))) { + localModule.flagUsed(); + dep = new LocalModuleDependency(localModule, undefined, false); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + } else { + dep = this.newRequireItemDependency(request); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + } + deps.push(dep); + }); + const dep = this.newRequireArrayDependency(deps, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.module.addPresentationalDependency(dep); + return true; } - } else { - if (typeof b !== "string") { - // both a and b are objects - let map = dualObjectMap.get(a); - if (map === undefined) { - dualObjectMap.set(a, (map = new WeakMap())); - } - const mergedEtag = map.get(b); - if (mergedEtag === undefined) { - const newMergedEtag = new MergedEtag(a, b); - map.set(b, newMergedEtag); - return newMergedEtag; + } + processItem(parser, expr, param, namedModule) { + if (param.isConditional()) { + param.options.forEach(param => { + const result = this.processItem(parser, expr, param); + if (result === undefined) { + this.processContext(parser, expr, param); + } + }); + return true; + } else if (param.isString()) { + let dep, localModule; + if (param.string === "require") { + dep = new ConstDependency("__webpack_require__", param.range, [ + RuntimeGlobals.require + ]); + } else if (param.string === "exports") { + dep = new ConstDependency("exports", param.range, [ + RuntimeGlobals.exports + ]); + } else if (param.string === "module") { + dep = new ConstDependency("module", param.range, [ + RuntimeGlobals.module + ]); + } else if ( + (localModule = getLocalModule(parser.state, param.string, namedModule)) + ) { + localModule.flagUsed(); + dep = new LocalModuleDependency(localModule, param.range, false); } else { - return mergedEtag; + dep = this.newRequireItemDependency(param.string, param.range); + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; } + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; } } - // a is object, b is string - let map = objectStringMap.get(a); - if (map === undefined) { - objectStringMap.set(a, (map = new Map())); + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + param.range, + param, + expr, + this.options, + { + category: "amd" + }, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; } - const mergedEtag = map.get(b); - if (mergedEtag === undefined) { - const newMergedEtag = new MergedEtag(a, b); - map.set(b, newMergedEtag); - return newMergedEtag; - } else { - return mergedEtag; + + processCallDefine(parser, expr) { + let array, fn, obj, namedModule; + switch (expr.arguments.length) { + case 1: + if (isCallable(expr.arguments[0])) { + // define(f() {…}) + fn = expr.arguments[0]; + } else if (expr.arguments[0].type === "ObjectExpression") { + // define({…}) + obj = expr.arguments[0]; + } else { + // define(expr) + // unclear if function or object + obj = fn = expr.arguments[0]; + } + break; + case 2: + if (expr.arguments[0].type === "Literal") { + namedModule = expr.arguments[0].value; + // define("…", …) + if (isCallable(expr.arguments[1])) { + // define("…", f() {…}) + fn = expr.arguments[1]; + } else if (expr.arguments[1].type === "ObjectExpression") { + // define("…", {…}) + obj = expr.arguments[1]; + } else { + // define("…", expr) + // unclear if function or object + obj = fn = expr.arguments[1]; + } + } else { + array = expr.arguments[0]; + if (isCallable(expr.arguments[1])) { + // define([…], f() {}) + fn = expr.arguments[1]; + } else if (expr.arguments[1].type === "ObjectExpression") { + // define([…], {…}) + obj = expr.arguments[1]; + } else { + // define([…], expr) + // unclear if function or object + obj = fn = expr.arguments[1]; + } + } + break; + case 3: + // define("…", […], f() {…}) + namedModule = expr.arguments[0].value; + array = expr.arguments[1]; + if (isCallable(expr.arguments[2])) { + // define("…", […], f() {}) + fn = expr.arguments[2]; + } else if (expr.arguments[2].type === "ObjectExpression") { + // define("…", […], {…}) + obj = expr.arguments[2]; + } else { + // define("…", […], expr) + // unclear if function or object + obj = fn = expr.arguments[2]; + } + break; + default: + return; + } + DynamicExports.bailout(parser.state); + let fnParams = null; + let fnParamsOffset = 0; + if (fn) { + if (isUnboundFunctionExpression(fn)) { + fnParams = fn.params; + } else if (isBoundFunctionExpression(fn)) { + fnParams = fn.callee.object.params; + fnParamsOffset = fn.arguments.length - 1; + if (fnParamsOffset < 0) { + fnParamsOffset = 0; + } + } + } + let fnRenames = new Map(); + if (array) { + const identifiers = {}; + const param = parser.evaluateExpression(array); + const result = this.processArray( + parser, + expr, + param, + identifiers, + namedModule + ); + if (!result) return; + if (fnParams) { + fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { + if (identifiers[idx]) { + fnRenames.set(param.name, parser.getVariableInfo(identifiers[idx])); + return false; + } + return true; + }); + } + } else { + const identifiers = ["require", "exports", "module"]; + if (fnParams) { + fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { + if (identifiers[idx]) { + fnRenames.set(param.name, parser.getVariableInfo(identifiers[idx])); + return false; + } + return true; + }); + } + } + let inTry; + if (fn && isUnboundFunctionExpression(fn)) { + inTry = parser.scope.inTry; + parser.inScope(fnParams, () => { + for (const [name, varInfo] of fnRenames) { + parser.setVariable(name, varInfo); + } + parser.scope.inTry = inTry; + if (fn.body.type === "BlockStatement") { + parser.detectMode(fn.body.body); + const prev = parser.prevStatement; + parser.preWalkStatement(fn.body); + parser.prevStatement = prev; + parser.walkStatement(fn.body); + } else { + parser.walkExpression(fn.body); + } + }); + } else if (fn && isBoundFunctionExpression(fn)) { + inTry = parser.scope.inTry; + parser.inScope( + fn.callee.object.params.filter( + i => !["require", "module", "exports"].includes(i.name) + ), + () => { + for (const [name, varInfo] of fnRenames) { + parser.setVariable(name, varInfo); + } + parser.scope.inTry = inTry; + if (fn.callee.object.body.type === "BlockStatement") { + parser.detectMode(fn.callee.object.body.body); + const prev = parser.prevStatement; + parser.preWalkStatement(fn.callee.object.body); + parser.prevStatement = prev; + parser.walkStatement(fn.callee.object.body); + } else { + parser.walkExpression(fn.callee.object.body); + } + } + ); + if (fn.arguments) { + parser.walkExpressions(fn.arguments); + } + } else if (fn || obj) { + parser.walkExpression(fn || obj); + } + + const dep = this.newDefineDependency( + expr.range, + array ? array.range : null, + fn ? fn.range : null, + obj ? obj.range : null, + namedModule ? namedModule : null + ); + dep.loc = expr.loc; + if (namedModule) { + dep.localModule = addLocalModule(parser.state, namedModule); + } + parser.state.module.addPresentationalDependency(dep); + return true; } -}; -module.exports = mergeEtags; + newDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ) { + return new AMDDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ); + } + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); + } + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); + } +} +module.exports = AMDDefineDependencyParserPlugin; /***/ }), -/***/ 13462: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 50067: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -70201,1003 +71021,419 @@ module.exports = mergeEtags; -const path = __webpack_require__(71017); -const webpackSchema = __webpack_require__(73342); +const RuntimeGlobals = __webpack_require__(16475); +const { + approve, + evaluateToIdentifier, + evaluateToString, + toConstantDependency +} = __webpack_require__(93998); -// TODO add originPath to PathItem for better errors -/** - * @typedef {Object} PathItem - * @property {any} schema the part of the schema - * @property {string} path the path in the config - */ - -/** @typedef {"unknown-argument" | "unexpected-non-array-in-path" | "unexpected-non-object-in-path" | "multiple-values-unexpected" | "invalid-value"} ProblemType */ - -/** - * @typedef {Object} Problem - * @property {ProblemType} type - * @property {string} path - * @property {string} argument - * @property {any=} value - * @property {number=} index - * @property {string=} expected - */ - -/** - * @typedef {Object} LocalProblem - * @property {ProblemType} type - * @property {string} path - * @property {string=} expected - */ - -/** - * @typedef {Object} ArgumentConfig - * @property {string} description - * @property {string} [negatedDescription] - * @property {string} path - * @property {boolean} multiple - * @property {"enum"|"string"|"path"|"number"|"boolean"|"RegExp"|"reset"} type - * @property {any[]=} values - */ - -/** - * @typedef {Object} Argument - * @property {string} description - * @property {"string"|"number"|"boolean"} simpleType - * @property {boolean} multiple - * @property {ArgumentConfig[]} configs - */ - -/** - * @param {any=} schema a json schema to create arguments for (by default webpack schema is used) - * @returns {Record} object of arguments - */ -const getArguments = (schema = webpackSchema) => { - /** @type {Record} */ - const flags = {}; - - const pathToArgumentName = input => { - return input - .replace(/\./g, "-") - .replace(/\[\]/g, "") - .replace( - /(\p{Uppercase_Letter}+|\p{Lowercase_Letter}|\d)(\p{Uppercase_Letter}+)/gu, - "$1-$2" - ) - .replace(/-?[^\p{Uppercase_Letter}\p{Lowercase_Letter}\d]+/gu, "-") - .toLowerCase(); - }; - - const getSchemaPart = path => { - const newPath = path.split("/"); - - let schemaPart = schema; - - for (let i = 1; i < newPath.length; i++) { - const inner = schemaPart[newPath[i]]; - - if (!inner) { - break; - } - - schemaPart = inner; - } - - return schemaPart; - }; - - /** - * - * @param {PathItem[]} path path in the schema - * @returns {string | undefined} description - */ - const getDescription = path => { - for (const { schema } of path) { - if (schema.cli) { - if (schema.cli.helper) continue; - if (schema.cli.description) return schema.cli.description; - } - if (schema.description) return schema.description; - } - }; - - /** - * - * @param {PathItem[]} path path in the schema - * @returns {string | undefined} negative description - */ - const getNegatedDescription = path => { - for (const { schema } of path) { - if (schema.cli) { - if (schema.cli.helper) continue; - if (schema.cli.negatedDescription) return schema.cli.negatedDescription; - } - } - }; +const AMDDefineDependency = __webpack_require__(96816); +const AMDDefineDependencyParserPlugin = __webpack_require__(48519); +const AMDRequireArrayDependency = __webpack_require__(33516); +const AMDRequireContextDependency = __webpack_require__(96123); +const AMDRequireDependenciesBlockParserPlugin = __webpack_require__(66866); +const AMDRequireDependency = __webpack_require__(43911); +const AMDRequireItemDependency = __webpack_require__(71806); +const { + AMDDefineRuntimeModule, + AMDOptionsRuntimeModule +} = __webpack_require__(45242); +const ConstDependency = __webpack_require__(76911); +const LocalModuleDependency = __webpack_require__(52805); +const UnsupportedDependency = __webpack_require__(51669); - /** - * - * @param {PathItem[]} path path in the schema - * @returns {string | undefined} reset description - */ - const getResetDescription = path => { - for (const { schema } of path) { - if (schema.cli) { - if (schema.cli.helper) continue; - if (schema.cli.resetDescription) return schema.cli.resetDescription; - } - } - }; +/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ +/** @typedef {import("../Compiler")} Compiler */ +class AMDPlugin { /** - * - * @param {any} schemaPart schema - * @returns {Pick} partial argument config + * @param {Record} amdOptions the AMD options */ - const schemaToArgumentConfig = schemaPart => { - if (schemaPart.enum) { - return { - type: "enum", - values: schemaPart.enum - }; - } - switch (schemaPart.type) { - case "number": - return { - type: "number" - }; - case "string": - return { - type: schemaPart.absolutePath ? "path" : "string" - }; - case "boolean": - return { - type: "boolean" - }; - } - if (schemaPart.instanceof === "RegExp") { - return { - type: "RegExp" - }; - } - return undefined; - }; + constructor(amdOptions) { + this.amdOptions = amdOptions; + } /** - * @param {PathItem[]} path path in the schema + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - const addResetFlag = path => { - const schemaPath = path[0].path; - const name = pathToArgumentName(`${schemaPath}.reset`); - const description = - getResetDescription(path) || - `Clear all items provided in '${schemaPath}' configuration. ${getDescription( - path - )}`; - flags[name] = { - configs: [ - { - type: "reset", - multiple: false, - description, - path: schemaPath - } - ], - description: undefined, - simpleType: undefined, - multiple: undefined - }; - }; - - /** - * @param {PathItem[]} path full path in schema - * @param {boolean} multiple inside of an array - * @returns {number} number of arguments added - */ - const addFlag = (path, multiple) => { - const argConfigBase = schemaToArgumentConfig(path[0].schema); - if (!argConfigBase) return 0; + apply(compiler) { + const amdOptions = this.amdOptions; + compiler.hooks.compilation.tap( + "AMDPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyTemplates.set( + AMDRequireDependency, + new AMDRequireDependency.Template() + ); - const negatedDescription = getNegatedDescription(path); - const name = pathToArgumentName(path[0].path); - /** @type {ArgumentConfig} */ - const argConfig = { - ...argConfigBase, - multiple, - description: getDescription(path), - path: path[0].path - }; + compilation.dependencyFactories.set( + AMDRequireItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + AMDRequireItemDependency, + new AMDRequireItemDependency.Template() + ); - if (negatedDescription) { - argConfig.negatedDescription = negatedDescription; - } + compilation.dependencyTemplates.set( + AMDRequireArrayDependency, + new AMDRequireArrayDependency.Template() + ); - if (!flags[name]) { - flags[name] = { - configs: [], - description: undefined, - simpleType: undefined, - multiple: undefined - }; - } + compilation.dependencyFactories.set( + AMDRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + AMDRequireContextDependency, + new AMDRequireContextDependency.Template() + ); - if ( - flags[name].configs.some( - item => JSON.stringify(item) === JSON.stringify(argConfig) - ) - ) { - return 0; - } + compilation.dependencyTemplates.set( + AMDDefineDependency, + new AMDDefineDependency.Template() + ); - if ( - flags[name].configs.some( - item => item.type === argConfig.type && item.multiple !== multiple - ) - ) { - if (multiple) { - throw new Error( - `Conflicting schema for ${path[0].path} with ${argConfig.type} type (array type must be before single item type)` + compilation.dependencyTemplates.set( + UnsupportedDependency, + new UnsupportedDependency.Template() ); - } - return 0; - } - flags[name].configs.push(argConfig); + compilation.dependencyTemplates.set( + LocalModuleDependency, + new LocalModuleDependency.Template() + ); - return 1; - }; + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.amdDefine) + .tap("AMDPlugin", (module, set) => { + set.add(RuntimeGlobals.require); + }); - // TODO support `not` and `if/then/else` - // TODO support `const`, but we don't use it on our schema - /** - * - * @param {object} schemaPart the current schema - * @param {string} schemaPath the current path in the schema - * @param {{schema: object, path: string}[]} path all previous visited schemaParts - * @param {string | null} inArray if inside of an array, the path to the array - * @returns {number} added arguments - */ - const traverse = (schemaPart, schemaPath = "", path = [], inArray = null) => { - while (schemaPart.$ref) { - schemaPart = getSchemaPart(schemaPart.$ref); - } + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.amdOptions) + .tap("AMDPlugin", (module, set) => { + set.add(RuntimeGlobals.requireScope); + }); - const repetitions = path.filter(({ schema }) => schema === schemaPart); - if ( - repetitions.length >= 2 || - repetitions.some(({ path }) => path === schemaPath) - ) { - return 0; - } + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.amdDefine) + .tap("AMDPlugin", (chunk, set) => { + compilation.addRuntimeModule(chunk, new AMDDefineRuntimeModule()); + }); - if (schemaPart.cli && schemaPart.cli.exclude) return 0; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.amdOptions) + .tap("AMDPlugin", (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new AMDOptionsRuntimeModule(amdOptions) + ); + }); - const fullPath = [{ schema: schemaPart, path: schemaPath }, ...path]; + const handler = (parser, parserOptions) => { + if (parserOptions.amd !== undefined && !parserOptions.amd) return; - let addedArguments = 0; + const tapOptionsHooks = (optionExpr, rootName, getMembers) => { + parser.hooks.expression + .for(optionExpr) + .tap( + "AMDPlugin", + toConstantDependency(parser, RuntimeGlobals.amdOptions, [ + RuntimeGlobals.amdOptions + ]) + ); + parser.hooks.evaluateIdentifier + .for(optionExpr) + .tap( + "AMDPlugin", + evaluateToIdentifier(optionExpr, rootName, getMembers, true) + ); + parser.hooks.evaluateTypeof + .for(optionExpr) + .tap("AMDPlugin", evaluateToString("object")); + parser.hooks.typeof + .for(optionExpr) + .tap( + "AMDPlugin", + toConstantDependency(parser, JSON.stringify("object")) + ); + }; - addedArguments += addFlag(fullPath, !!inArray); + new AMDRequireDependenciesBlockParserPlugin(parserOptions).apply( + parser + ); + new AMDDefineDependencyParserPlugin(parserOptions).apply(parser); - if (schemaPart.type === "object") { - if (schemaPart.properties) { - for (const property of Object.keys(schemaPart.properties)) { - addedArguments += traverse( - schemaPart.properties[property], - schemaPath ? `${schemaPath}.${property}` : property, - fullPath, - inArray + tapOptionsHooks("define.amd", "define", () => "amd"); + tapOptionsHooks("require.amd", "require", () => ["amd"]); + tapOptionsHooks( + "__webpack_amd_options__", + "__webpack_amd_options__", + () => [] ); - } - } - return addedArguments; - } + parser.hooks.expression.for("define").tap("AMDPlugin", expr => { + const dep = new ConstDependency( + RuntimeGlobals.amdDefine, + expr.range, + [RuntimeGlobals.amdDefine] + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.typeof + .for("define") + .tap( + "AMDPlugin", + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for("define") + .tap("AMDPlugin", evaluateToString("function")); + parser.hooks.canRename.for("define").tap("AMDPlugin", approve); + parser.hooks.rename.for("define").tap("AMDPlugin", expr => { + const dep = new ConstDependency( + RuntimeGlobals.amdDefine, + expr.range, + [RuntimeGlobals.amdDefine] + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return false; + }); + parser.hooks.typeof + .for("require") + .tap( + "AMDPlugin", + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for("require") + .tap("AMDPlugin", evaluateToString("function")); + }; - if (schemaPart.type === "array") { - if (inArray) { - return 0; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("AMDPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("AMDPlugin", handler); } - if (Array.isArray(schemaPart.items)) { - let i = 0; - for (const item of schemaPart.items) { - addedArguments += traverse( - item, - `${schemaPath}.${i}`, - fullPath, - schemaPath - ); - } + ); + } +} - return addedArguments; - } +module.exports = AMDPlugin; - addedArguments += traverse( - schemaPart.items, - `${schemaPath}[]`, - fullPath, - schemaPath - ); - if (addedArguments > 0) { - addResetFlag(fullPath); - addedArguments++; - } +/***/ }), - return addedArguments; - } +/***/ 33516: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const maybeOf = schemaPart.oneOf || schemaPart.anyOf || schemaPart.allOf; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (maybeOf) { - const items = maybeOf; - for (let i = 0; i < items.length; i++) { - addedArguments += traverse(items[i], schemaPath, fullPath, inArray); - } - return addedArguments; - } +const DependencyTemplate = __webpack_require__(5160); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); - return addedArguments; - }; +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - traverse(schema); +class AMDRequireArrayDependency extends NullDependency { + constructor(depsArray, range) { + super(); - // Summarize flags - for (const name of Object.keys(flags)) { - const argument = flags[name]; - argument.description = argument.configs.reduce((desc, { description }) => { - if (!desc) return description; - if (!description) return desc; - if (desc.includes(description)) return desc; - return `${desc} ${description}`; - }, /** @type {string | undefined} */ (undefined)); - argument.simpleType = argument.configs.reduce((t, argConfig) => { - /** @type {"string" | "number" | "boolean"} */ - let type = "string"; - switch (argConfig.type) { - case "number": - type = "number"; - break; - case "reset": - case "boolean": - type = "boolean"; - break; - case "enum": - if (argConfig.values.every(v => typeof v === "boolean")) - type = "boolean"; - if (argConfig.values.every(v => typeof v === "number")) - type = "number"; - break; - } - if (t === undefined) return type; - return t === type ? t : "string"; - }, /** @type {"string" | "number" | "boolean" | undefined} */ (undefined)); - argument.multiple = argument.configs.some(c => c.multiple); + this.depsArray = depsArray; + this.range = range; } - return flags; -}; - -const cliAddedItems = new WeakMap(); - -/** - * @param {any} config configuration - * @param {string} schemaPath path in the config - * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined - * @returns {{ problem?: LocalProblem, object?: any, property?: string | number, value?: any }} problem or object with property and value - */ -const getObjectAndProperty = (config, schemaPath, index = 0) => { - if (!schemaPath) return { value: config }; - const parts = schemaPath.split("."); - let property = parts.pop(); - let current = config; - let i = 0; - for (const part of parts) { - const isArray = part.endsWith("[]"); - const name = isArray ? part.slice(0, -2) : part; - let value = current[name]; - if (isArray) { - if (value === undefined) { - value = {}; - current[name] = [...Array.from({ length: index }), value]; - cliAddedItems.set(current[name], index + 1); - } else if (!Array.isArray(value)) { - return { - problem: { - type: "unexpected-non-array-in-path", - path: parts.slice(0, i).join(".") - } - }; - } else { - let addedItems = cliAddedItems.get(value) || 0; - while (addedItems <= index) { - value.push(undefined); - addedItems++; - } - cliAddedItems.set(value, addedItems); - const x = value.length - addedItems + index; - if (value[x] === undefined) { - value[x] = {}; - } else if (value[x] === null || typeof value[x] !== "object") { - return { - problem: { - type: "unexpected-non-object-in-path", - path: parts.slice(0, i).join(".") - } - }; - } - value = value[x]; - } - } else { - if (value === undefined) { - value = current[name] = {}; - } else if (value === null || typeof value !== "object") { - return { - problem: { - type: "unexpected-non-object-in-path", - path: parts.slice(0, i).join(".") - } - }; - } - } - current = value; - i++; + get type() { + return "amd require array"; } - let value = current[property]; - if (property.endsWith("[]")) { - const name = property.slice(0, -2); - const value = current[name]; - if (value === undefined) { - current[name] = [...Array.from({ length: index }), undefined]; - cliAddedItems.set(current[name], index + 1); - return { object: current[name], property: index, value: undefined }; - } else if (!Array.isArray(value)) { - current[name] = [value, ...Array.from({ length: index }), undefined]; - cliAddedItems.set(current[name], index + 1); - return { object: current[name], property: index + 1, value: undefined }; - } else { - let addedItems = cliAddedItems.get(value) || 0; - while (addedItems <= index) { - value.push(undefined); - addedItems++; - } - cliAddedItems.set(value, addedItems); - const x = value.length - addedItems + index; - if (value[x] === undefined) { - value[x] = {}; - } else if (value[x] === null || typeof value[x] !== "object") { - return { - problem: { - type: "unexpected-non-object-in-path", - path: schemaPath - } - }; - } - return { - object: value, - property: x, - value: value[x] - }; - } + + get category() { + return "amd"; } - return { object: current, property, value }; -}; -/** - * @param {any} config configuration - * @param {string} schemaPath path in the config - * @param {any} value parsed value - * @param {number | undefined} index index of value when multiple values are provided, otherwise undefined - * @returns {LocalProblem | null} problem or null for success - */ -const setValue = (config, schemaPath, value, index) => { - const { problem, object, property } = getObjectAndProperty( - config, - schemaPath, - index - ); - if (problem) return problem; - object[property] = value; - return null; -}; + serialize(context) { + const { write } = context; -/** - * @param {ArgumentConfig} argConfig processing instructions - * @param {any} config configuration - * @param {any} value the value - * @param {number | undefined} index the index if multiple values provided - * @returns {LocalProblem | null} a problem if any - */ -const processArgumentConfig = (argConfig, config, value, index) => { - if (index !== undefined && !argConfig.multiple) { - return { - type: "multiple-values-unexpected", - path: argConfig.path - }; + write(this.depsArray); + write(this.range); + + super.serialize(context); } - const parsed = parseValueForArgumentConfig(argConfig, value); - if (parsed === undefined) { - return { - type: "invalid-value", - path: argConfig.path, - expected: getExpectedValue(argConfig) - }; + + deserialize(context) { + const { read } = context; + + this.depsArray = read(); + this.range = read(); + + super.deserialize(context); } - const problem = setValue(config, argConfig.path, parsed, index); - if (problem) return problem; - return null; -}; +} -/** - * @param {ArgumentConfig} argConfig processing instructions - * @returns {string | undefined} expected message - */ -const getExpectedValue = argConfig => { - switch (argConfig.type) { - default: - return argConfig.type; - case "boolean": - return "true | false"; - case "RegExp": - return "regular expression (example: /ab?c*/)"; - case "enum": - return argConfig.values.map(v => `${v}`).join(" | "); - case "reset": - return "true (will reset the previous value to an empty array)"; +makeSerializable( + AMDRequireArrayDependency, + "webpack/lib/dependencies/AMDRequireArrayDependency" +); + +AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate extends ( + DependencyTemplate +) { + /** + * @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 dep = /** @type {AMDRequireArrayDependency} */ (dependency); + const content = this.getContent(dep, templateContext); + source.replace(dep.range[0], dep.range[1] - 1, content); } -}; -/** - * @param {ArgumentConfig} argConfig processing instructions - * @param {any} value the value - * @returns {any | undefined} parsed value - */ -const parseValueForArgumentConfig = (argConfig, value) => { - switch (argConfig.type) { - case "string": - if (typeof value === "string") { - return value; - } - break; - case "path": - if (typeof value === "string") { - return path.resolve(value); - } - break; - case "number": - if (typeof value === "number") return value; - if (typeof value === "string" && /^[+-]?\d*(\.\d*)[eE]\d+$/) { - const n = +value; - if (!isNaN(n)) return n; - } - break; - case "boolean": - if (typeof value === "boolean") return value; - if (value === "true") return true; - if (value === "false") return false; - break; - case "RegExp": - if (value instanceof RegExp) return value; - if (typeof value === "string") { - // cspell:word yugi - const match = /^\/(.*)\/([yugi]*)$/.exec(value); - if (match && !/[^\\]\//.test(match[1])) - return new RegExp(match[1], match[2]); - } - break; - case "enum": - if (argConfig.values.includes(value)) return value; - for (const item of argConfig.values) { - if (`${item}` === value) return item; - } - break; - case "reset": - if (value === true) return []; - break; + getContent(dep, templateContext) { + const requires = dep.depsArray.map(dependency => { + return this.contentForDependency(dependency, templateContext); + }); + return `[${requires.join(", ")}]`; } -}; -/** - * @param {Record} args object of arguments - * @param {any} config configuration - * @param {Record} values object with values - * @returns {Problem[] | null} problems or null for success - */ -const processArguments = (args, config, values) => { - /** @type {Problem[]} */ - const problems = []; - for (const key of Object.keys(values)) { - const arg = args[key]; - if (!arg) { - problems.push({ - type: "unknown-argument", - path: "", - argument: key - }); - continue; + contentForDependency( + dep, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + if (typeof dep === "string") { + return dep; } - const processValue = (value, i) => { - const currentProblems = []; - for (const argConfig of arg.configs) { - const problem = processArgumentConfig(argConfig, config, value, i); - if (!problem) { - return; - } - currentProblems.push({ - ...problem, - argument: key, - value: value, - index: i - }); - } - problems.push(...currentProblems); - }; - let value = values[key]; - if (Array.isArray(value)) { - for (let i = 0; i < value.length; i++) { - processValue(value[i], i); - } + + if (dep.localModule) { + return dep.localModule.variableName(); } else { - processValue(value, undefined); + return runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + runtimeRequirements + }); } } - if (problems.length === 0) return null; - return problems; }; -exports.getArguments = getArguments; -exports.processArguments = processArguments; +module.exports = AMDRequireArrayDependency; /***/ }), -/***/ 43950: +/***/ 96123: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov + Author Tobias Koppers @sokra */ -const browserslist = __webpack_require__(14907); -const path = __webpack_require__(71017); +const makeSerializable = __webpack_require__(33032); +const ContextDependency = __webpack_require__(88101); -/** @typedef {import("./target").ApiTargetProperties} ApiTargetProperties */ -/** @typedef {import("./target").EcmaTargetProperties} EcmaTargetProperties */ -/** @typedef {import("./target").PlatformTargetProperties} PlatformTargetProperties */ +class AMDRequireContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); -// [[C:]/path/to/config][:env] -const inputRx = /^(?:((?:[A-Z]:)?[/\\].*?))?(?::(.+?))?$/i; + this.range = range; + this.valueRange = valueRange; + } -/** - * @typedef {Object} BrowserslistHandlerConfig - * @property {string=} configPath - * @property {string=} env - * @property {string=} query - */ + get type() { + return "amd require context"; + } -/** - * @param {string} input input string - * @param {string} context the context directory - * @returns {BrowserslistHandlerConfig} config - */ -const parse = (input, context) => { - if (!input) { - return {}; + get category() { + return "amd"; } - if (path.isAbsolute(input)) { - const [, configPath, env] = inputRx.exec(input) || []; - return { configPath, env }; + serialize(context) { + const { write } = context; + + write(this.range); + write(this.valueRange); + + super.serialize(context); } - const config = browserslist.findConfig(context); + deserialize(context) { + const { read } = context; - if (config && Object.keys(config).includes(input)) { - return { env: input }; + this.range = read(); + this.valueRange = read(); + + super.deserialize(context); } +} - return { query: input }; -}; +makeSerializable( + AMDRequireContextDependency, + "webpack/lib/dependencies/AMDRequireContextDependency" +); -/** - * @param {string} input input string - * @param {string} context the context directory - * @returns {string[] | undefined} selected browsers - */ -const load = (input, context) => { - const { configPath, env, query } = parse(input, context); +AMDRequireContextDependency.Template = __webpack_require__(75815); - // if a query is specified, then use it, else - // if a path to a config is specified then load it, else - // find a nearest config - const config = query - ? query - : configPath - ? browserslist.loadConfig({ - config: configPath, - env - }) - : browserslist.loadConfig({ path: context, env }); +module.exports = AMDRequireContextDependency; - if (!config) return null; - return browserslist(config); -}; -/** - * @param {string[]} browsers supported browsers list - * @returns {EcmaTargetProperties & PlatformTargetProperties & ApiTargetProperties} target properties - */ -const resolve = browsers => { - /** - * Checks all against a version number - * @param {Record} versions first supported version - * @returns {boolean} true if supports - */ - const rawChecker = versions => { - return browsers.every(v => { - const [name, parsedVersion] = v.split(" "); - if (!name) return false; - const requiredVersion = versions[name]; - if (!requiredVersion) return false; - const [parsedMajor, parserMinor] = - // safari TP supports all features for normal safari - parsedVersion === "TP" - ? [Infinity, Infinity] - : parsedVersion.split("."); - if (typeof requiredVersion === "number") { - return +parsedMajor >= requiredVersion; - } - return requiredVersion[0] === +parsedMajor - ? +parserMinor >= requiredVersion[1] - : +parsedMajor > requiredVersion[0]; - }); - }; - const anyNode = browsers.some(b => /^node /.test(b)); - const anyBrowser = browsers.some(b => /^(?!node)/.test(b)); - const browserProperty = !anyBrowser ? false : anyNode ? null : true; - const nodeProperty = !anyNode ? false : anyBrowser ? null : true; - // Internet Explorer Mobile, Blackberry browser and Opera Mini are very old browsers, they do not support new features - const es6DynamicImport = rawChecker({ - chrome: 63, - and_chr: 63, - edge: 79, - firefox: 67, - and_ff: 67, - // ie: Not supported - opera: 50, - op_mob: 46, - safari: [11, 1], - ios_saf: [11, 3], - samsung: [8, 2], - android: 63, - and_qq: [10, 4], - // baidu: Not supported - // and_uc: Not supported - // kaios: Not supported - // Since Node.js 13.14.0 no warning about usage, but it was added 8.5.0 with some limitations and it was improved in 12.0.0 and 13.2.0 - node: [13, 14] - }); +/***/ }), - return { - const: rawChecker({ - chrome: 49, - and_chr: 49, - edge: 12, - // Prior to Firefox 13, const is implemented, but re-assignment is not failing. - // Prior to Firefox 46, a TypeError was thrown on redeclaration instead of a SyntaxError. - firefox: 36, - and_ff: 36, - // Not supported in for-in and for-of loops - // ie: Not supported - opera: 36, - op_mob: 36, - safari: [10, 0], - ios_saf: [10, 0], - // Before 5.0 supported correctly in strict mode, otherwise supported without block scope - samsung: [5, 0], - android: 37, - and_qq: [10, 4], - // Supported correctly in strict mode, otherwise supported without block scope - // baidu: Not supported - and_uc: [12, 12], - kaios: [2, 5], - node: [6, 0] - }), - arrowFunction: rawChecker({ - chrome: 45, - and_chr: 45, - edge: 12, - // The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of 'use strict'; is now required. - // Prior to Firefox 39, a line terminator (\\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \\n => {} will now throw a SyntaxError in this and later versions. - firefox: 39, - and_ff: 39, - // ie: Not supported, - opera: 32, - op_mob: 32, - safari: 10, - ios_saf: 10, - samsung: [5, 0], - android: 45, - and_qq: [10, 4], - baidu: [7, 12], - and_uc: [12, 12], - kaios: [2, 5], - node: [6, 0] - }), - forOf: rawChecker({ - chrome: 38, - and_chr: 38, - edge: 12, - // Prior to Firefox 51, using the for...of loop construct with the const keyword threw a SyntaxError ("missing = in const declaration"). - firefox: 51, - and_ff: 51, - // ie: Not supported, - opera: 25, - op_mob: 25, - safari: 7, - ios_saf: 7, - samsung: [3, 0], - android: 38, - // and_qq: Unknown support - // baidu: Unknown support - // and_uc: Unknown support - // kaios: Unknown support - node: [0, 12] - }), - destructuring: rawChecker({ - chrome: 49, - and_chr: 49, - edge: 14, - firefox: 41, - and_ff: 41, - // ie: Not supported, - opera: 36, - op_mob: 36, - safari: 8, - ios_saf: 8, - samsung: [5, 0], - android: 49, - // and_qq: Unknown support - // baidu: Unknown support - // and_uc: Unknown support - // kaios: Unknown support - node: [6, 0] - }), - bigIntLiteral: rawChecker({ - chrome: 67, - and_chr: 67, - edge: 79, - firefox: 68, - and_ff: 68, - // ie: Not supported, - opera: 54, - op_mob: 48, - safari: 14, - ios_saf: 14, - samsung: [9, 2], - android: 67, - // and_qq: Not supported - // baidu: Not supported - // and_uc: Not supported - // kaios: Not supported - node: [10, 4] - }), - // Support syntax `import` and `export` and no limitations and bugs on Node.js - // Not include `export * as namespace` - module: rawChecker({ - chrome: 61, - and_chr: 61, - edge: 16, - firefox: 60, - and_ff: 60, - // ie: Not supported, - opera: 48, - op_mob: 45, - safari: [10, 1], - ios_saf: [10, 3], - samsung: [8, 0], - android: 61, - and_qq: [10, 4], - // baidu: Not supported - // and_uc: Not supported - // kaios: Not supported - // Since Node.js 13.14.0 no warning about usage, but it was added 8.5.0 with some limitations and it was improved in 12.0.0 and 13.2.0 - node: [13, 14] - }), - dynamicImport: es6DynamicImport, - dynamicImportInWorker: es6DynamicImport && !anyNode, - // browserslist does not have info about globalThis - // so this is based on mdn-browser-compat-data - globalThis: rawChecker({ - chrome: 71, - and_chr: 71, - edge: 79, - firefox: 65, - and_ff: 65, - // ie: Not supported, - opera: 58, - op_mob: 50, - safari: [12, 1], - ios_saf: [12, 2], - samsung: [10, 1], - android: 71, - // and_qq: Unknown support - // baidu: Unknown support - // and_uc: Unknown support - // kaios: Unknown support - node: [12, 0] - }), - optionalChaining: rawChecker({ - chrome: 80, - and_chr: 80, - edge: 80, - firefox: 74, - and_ff: 79, - // ie: Not supported, - opera: 67, - op_mob: 64, - safari: [13, 1], - ios_saf: [13, 4], - samsung: 13, - android: 80, - // and_qq: Not supported - // baidu: Not supported - // and_uc: Not supported - // kaios: Not supported - node: 14 - }), - templateLiteral: rawChecker({ - chrome: 41, - and_chr: 41, - edge: 13, - firefox: 34, - and_ff: 34, - // ie: Not supported, - opera: 29, - op_mob: 64, - safari: [9, 1], - ios_saf: 9, - samsung: 4, - android: 41, - and_qq: [10, 4], - baidu: [7, 12], - and_uc: [12, 12], - kaios: [2, 5], - node: 4 - }), - browser: browserProperty, - electron: false, - node: nodeProperty, - nwjs: false, - web: browserProperty, - webworker: false, +/***/ 76932: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - document: browserProperty, - fetchWasm: browserProperty, - global: nodeProperty, - importScripts: false, - importScriptsInWorker: true, - nodeBuiltins: nodeProperty, - require: nodeProperty - }; -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -module.exports = { - resolve, - load -}; + + +const AsyncDependenciesBlock = __webpack_require__(47736); +const makeSerializable = __webpack_require__(33032); + +class AMDRequireDependenciesBlock extends AsyncDependenciesBlock { + constructor(loc, request) { + super(null, loc, request); + } +} + +makeSerializable( + AMDRequireDependenciesBlock, + "webpack/lib/dependencies/AMDRequireDependenciesBlock" +); + +module.exports = AMDRequireDependenciesBlock; /***/ }), -/***/ 92988: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 66866: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -71207,2902 +71443,2457 @@ module.exports = { -const fs = __webpack_require__(57147); -const path = __webpack_require__(71017); -const Template = __webpack_require__(39722); -const { cleverMerge } = __webpack_require__(60839); -const { - getTargetsProperties, - getTargetProperties, - getDefaultTarget -} = __webpack_require__(52801); - -/** @typedef {import("../../declarations/WebpackOptions").CacheOptionsNormalized} CacheOptions */ -/** @typedef {import("../../declarations/WebpackOptions").CssExperimentOptions} CssExperimentOptions */ -/** @typedef {import("../../declarations/WebpackOptions").EntryDescription} EntryDescription */ -/** @typedef {import("../../declarations/WebpackOptions").EntryNormalized} Entry */ -/** @typedef {import("../../declarations/WebpackOptions").Experiments} Experiments */ -/** @typedef {import("../../declarations/WebpackOptions").ExperimentsNormalized} ExperimentsNormalized */ -/** @typedef {import("../../declarations/WebpackOptions").ExternalsPresets} ExternalsPresets */ -/** @typedef {import("../../declarations/WebpackOptions").ExternalsType} ExternalsType */ -/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */ -/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ -/** @typedef {import("../../declarations/WebpackOptions").Library} Library */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").Loader} Loader */ -/** @typedef {import("../../declarations/WebpackOptions").Mode} Mode */ -/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ -/** @typedef {import("../../declarations/WebpackOptions").Node} WebpackNode */ -/** @typedef {import("../../declarations/WebpackOptions").Optimization} Optimization */ -/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */ -/** @typedef {import("../../declarations/WebpackOptions").Performance} Performance */ -/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ -/** @typedef {import("../../declarations/WebpackOptions").RuleSetRules} RuleSetRules */ -/** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */ -/** @typedef {import("../../declarations/WebpackOptions").Target} Target */ -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("./target").TargetProperties} TargetProperties */ +const RuntimeGlobals = __webpack_require__(16475); +const UnsupportedFeatureWarning = __webpack_require__(42495); +const AMDRequireArrayDependency = __webpack_require__(33516); +const AMDRequireContextDependency = __webpack_require__(96123); +const AMDRequireDependenciesBlock = __webpack_require__(76932); +const AMDRequireDependency = __webpack_require__(43911); +const AMDRequireItemDependency = __webpack_require__(71806); +const ConstDependency = __webpack_require__(76911); +const ContextDependencyHelpers = __webpack_require__(99630); +const LocalModuleDependency = __webpack_require__(52805); +const { getLocalModule } = __webpack_require__(75827); +const UnsupportedDependency = __webpack_require__(51669); +const getFunctionExpression = __webpack_require__(50396); -const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i; +class AMDRequireDependenciesBlockParserPlugin { + constructor(options) { + this.options = options; + } -/** - * Sets a constant default value when undefined - * @template T - * @template {keyof T} P - * @param {T} obj an object - * @param {P} prop a property of this object - * @param {T[P]} value a default value of the property - * @returns {void} - */ -const D = (obj, prop, value) => { - if (obj[prop] === undefined) { - obj[prop] = value; + processFunctionArgument(parser, expression) { + let bindThis = true; + const fnData = getFunctionExpression(expression); + if (fnData) { + parser.inScope( + fnData.fn.params.filter(i => { + return !["require", "module", "exports"].includes(i.name); + }), + () => { + if (fnData.fn.body.type === "BlockStatement") { + parser.walkStatement(fnData.fn.body); + } else { + parser.walkExpression(fnData.fn.body); + } + } + ); + parser.walkExpressions(fnData.expressions); + if (fnData.needThis === false) { + bindThis = false; + } + } else { + parser.walkExpression(expression); + } + return bindThis; } -}; -/** - * Sets a dynamic default value when undefined, by calling the factory function - * @template T - * @template {keyof T} P - * @param {T} obj an object - * @param {P} prop a property of this object - * @param {function(): T[P]} factory a default value factory for the property - * @returns {void} - */ -const F = (obj, prop, factory) => { - if (obj[prop] === undefined) { - obj[prop] = factory(); + apply(parser) { + parser.hooks.call + .for("require") + .tap( + "AMDRequireDependenciesBlockParserPlugin", + this.processCallRequire.bind(this, parser) + ); } -}; -/** - * Sets a dynamic default value when undefined, by calling the factory function. - * factory must return an array or undefined - * When the current value is already an array an contains "..." it's replaced with - * the result of the factory function - * @template T - * @template {keyof T} P - * @param {T} obj an object - * @param {P} prop a property of this object - * @param {function(): T[P]} factory a default value factory for the property - * @returns {void} - */ -const A = (obj, prop, factory) => { - const value = obj[prop]; - if (value === undefined) { - obj[prop] = factory(); - } else if (Array.isArray(value)) { - /** @type {any[]} */ - let newArray = undefined; - for (let i = 0; i < value.length; i++) { - const item = value[i]; - if (item === "...") { - if (newArray === undefined) { - newArray = value.slice(0, i); - obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray)); + processArray(parser, expr, param) { + if (param.isArray()) { + for (const p of param.items) { + const result = this.processItem(parser, expr, p); + if (result === undefined) { + this.processContext(parser, expr, p); } - const items = /** @type {any[]} */ (/** @type {unknown} */ (factory())); - if (items !== undefined) { - for (const item of items) { - newArray.push(item); - } + } + return true; + } else if (param.isConstArray()) { + const deps = []; + for (const request of param.array) { + let dep, localModule; + if (request === "require") { + dep = "__webpack_require__"; + } else if (["exports", "module"].includes(request)) { + dep = request; + } else if ((localModule = getLocalModule(parser.state, request))) { + localModule.flagUsed(); + dep = new LocalModuleDependency(localModule, undefined, false); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + } else { + dep = this.newRequireItemDependency(request); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); } - } else if (newArray !== undefined) { - newArray.push(item); + deps.push(dep); } + const dep = this.newRequireArrayDependency(deps, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.module.addPresentationalDependency(dep); + return true; } } -}; - -/** - * @param {WebpackOptions} options options to be modified - * @returns {void} - */ -const applyWebpackOptionsBaseDefaults = options => { - F(options, "context", () => process.cwd()); - applyInfrastructureLoggingDefaults(options.infrastructureLogging); -}; + processItem(parser, expr, param) { + if (param.isConditional()) { + for (const p of param.options) { + const result = this.processItem(parser, expr, p); + if (result === undefined) { + this.processContext(parser, expr, p); + } + } + return true; + } else if (param.isString()) { + let dep, localModule; + if (param.string === "require") { + dep = new ConstDependency("__webpack_require__", param.string, [ + RuntimeGlobals.require + ]); + } else if (param.string === "module") { + dep = new ConstDependency( + parser.state.module.buildInfo.moduleArgument, + param.range, + [RuntimeGlobals.module] + ); + } else if (param.string === "exports") { + dep = new ConstDependency( + parser.state.module.buildInfo.exportsArgument, + param.range, + [RuntimeGlobals.exports] + ); + } else if ((localModule = getLocalModule(parser.state, param.string))) { + localModule.flagUsed(); + dep = new LocalModuleDependency(localModule, param.range, false); + } else { + dep = this.newRequireItemDependency(param.string, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + } + } + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + param.range, + param, + expr, + this.options, + { + category: "amd" + }, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } -/** - * @param {WebpackOptions} options options to be modified - * @returns {void} - */ -const applyWebpackOptionsDefaults = options => { - F(options, "context", () => process.cwd()); - F(options, "target", () => { - return getDefaultTarget(options.context); - }); + processArrayForRequestString(param) { + if (param.isArray()) { + const result = param.items.map(item => + this.processItemForRequestString(item) + ); + if (result.every(Boolean)) return result.join(" "); + } else if (param.isConstArray()) { + return param.array.join(" "); + } + } - const { mode, name, target } = options; + processItemForRequestString(param) { + if (param.isConditional()) { + const result = param.options.map(item => + this.processItemForRequestString(item) + ); + if (result.every(Boolean)) return result.join("|"); + } else if (param.isString()) { + return param.string; + } + } - let targetProperties = - target === false - ? /** @type {false} */ (false) - : typeof target === "string" - ? getTargetProperties(target, options.context) - : getTargetsProperties(target, options.context); + processCallRequire(parser, expr) { + let param; + let depBlock; + let dep; + let result; - const development = mode === "development"; - const production = mode === "production" || !mode; + const old = parser.state.current; - if (typeof options.entry !== "function") { - for (const key of Object.keys(options.entry)) { - F( - options.entry[key], - "import", - () => /** @type {[string]} */ (["./src"]) + if (expr.arguments.length >= 1) { + param = parser.evaluateExpression(expr.arguments[0]); + depBlock = this.newRequireDependenciesBlock( + expr.loc, + this.processArrayForRequestString(param) + ); + dep = this.newRequireDependency( + expr.range, + param.range, + expr.arguments.length > 1 ? expr.arguments[1].range : null, + expr.arguments.length > 2 ? expr.arguments[2].range : null ); + dep.loc = expr.loc; + depBlock.addDependency(dep); + + parser.state.current = depBlock; } - } - F(options, "devtool", () => (development ? "eval" : false)); - D(options, "watch", false); - D(options, "profile", false); - D(options, "parallelism", 100); - D(options, "recordsInputPath", false); - D(options, "recordsOutputPath", false); + if (expr.arguments.length === 1) { + parser.inScope([], () => { + result = this.processArray(parser, expr, param); + }); + parser.state.current = old; + if (!result) return; + parser.state.current.addBlock(depBlock); + return true; + } - applyExperimentsDefaults(options.experiments, { - production, - development, - targetProperties - }); + if (expr.arguments.length === 2 || expr.arguments.length === 3) { + try { + parser.inScope([], () => { + result = this.processArray(parser, expr, param); + }); + if (!result) { + const dep = new UnsupportedDependency("unsupported", expr.range); + old.addPresentationalDependency(dep); + if (parser.state.module) { + parser.state.module.addError( + new UnsupportedFeatureWarning( + "Cannot statically analyse 'require(…, …)' in line " + + expr.loc.start.line, + expr.loc + ) + ); + } + depBlock = null; + return true; + } + dep.functionBindThis = this.processFunctionArgument( + parser, + expr.arguments[1] + ); + if (expr.arguments.length === 3) { + dep.errorCallbackBindThis = this.processFunctionArgument( + parser, + expr.arguments[2] + ); + } + } finally { + parser.state.current = old; + if (depBlock) parser.state.current.addBlock(depBlock); + } + return true; + } + } - const futureDefaults = options.experiments.futureDefaults; + newRequireDependenciesBlock(loc, request) { + return new AMDRequireDependenciesBlock(loc, request); + } + newRequireDependency( + outerRange, + arrayRange, + functionRange, + errorCallbackRange + ) { + return new AMDRequireDependency( + outerRange, + arrayRange, + functionRange, + errorCallbackRange + ); + } + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); + } + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); + } +} +module.exports = AMDRequireDependenciesBlockParserPlugin; - F(options, "cache", () => - development ? { type: /** @type {"memory"} */ ("memory") } : false - ); - applyCacheDefaults(options.cache, { - name: name || "default", - mode: mode || "production", - development, - cacheUnaffected: options.experiments.cacheUnaffected - }); - const cache = !!options.cache; - applySnapshotDefaults(options.snapshot, { - production, - futureDefaults - }); +/***/ }), - applyModuleDefaults(options.module, { - cache, - syncWebAssembly: options.experiments.syncWebAssembly, - asyncWebAssembly: options.experiments.asyncWebAssembly, - css: options.experiments.css, - futureDefaults - }); +/***/ 43911: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - applyOutputDefaults(options.output, { - context: options.context, - targetProperties, - isAffectedByBrowserslist: - target === undefined || - (typeof target === "string" && target.startsWith("browserslist")) || - (Array.isArray(target) && - target.some(target => target.startsWith("browserslist"))), - outputModule: options.experiments.outputModule, - development, - entry: options.entry, - module: options.module, - futureDefaults - }); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - applyExternalsPresetsDefaults(options.externalsPresets, { - targetProperties, - buildHttp: !!options.experiments.buildHttp - }); - applyLoaderDefaults(options.loader, { targetProperties }); - F(options, "externalsType", () => { - const validExternalTypes = (__webpack_require__(73342).definitions.ExternalsType["enum"]); - return options.output.library && - validExternalTypes.includes(options.output.library.type) - ? /** @type {ExternalsType} */ (options.output.library.type) - : options.output.module - ? "module" - : "var"; - }); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); - applyNodeDefaults(options.node, { - futureDefaults: options.experiments.futureDefaults, - targetProperties - }); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - F(options, "performance", () => - production && - targetProperties && - (targetProperties.browser || targetProperties.browser === null) - ? {} - : false - ); - applyPerformanceDefaults(options.performance, { - production - }); +class AMDRequireDependency extends NullDependency { + constructor(outerRange, arrayRange, functionRange, errorCallbackRange) { + super(); - applyOptimizationDefaults(options.optimization, { - development, - production, - css: options.experiments.css, - records: !!(options.recordsInputPath || options.recordsOutputPath) - }); + this.outerRange = outerRange; + this.arrayRange = arrayRange; + this.functionRange = functionRange; + this.errorCallbackRange = errorCallbackRange; + this.functionBindThis = false; + this.errorCallbackBindThis = false; + } - options.resolve = cleverMerge( - getResolveDefaults({ - cache, - context: options.context, - targetProperties, - mode: options.mode - }), - options.resolve - ); + get category() { + return "amd"; + } - options.resolveLoader = cleverMerge( - getResolveLoaderDefaults({ cache }), - options.resolveLoader - ); -}; + serialize(context) { + const { write } = context; -/** - * @param {ExperimentsNormalized} experiments options - * @param {Object} options options - * @param {boolean} options.production is production - * @param {boolean} options.development is development mode - * @param {TargetProperties | false} options.targetProperties target properties - * @returns {void} - */ -const applyExperimentsDefaults = ( - experiments, - { production, development, targetProperties } -) => { - D(experiments, "futureDefaults", false); - D(experiments, "backCompat", !experiments.futureDefaults); - D(experiments, "topLevelAwait", experiments.futureDefaults); - D(experiments, "syncWebAssembly", false); - D(experiments, "asyncWebAssembly", experiments.futureDefaults); - D(experiments, "outputModule", false); - D(experiments, "layers", false); - D(experiments, "lazyCompilation", undefined); - D(experiments, "buildHttp", undefined); - D(experiments, "cacheUnaffected", experiments.futureDefaults); - F(experiments, "css", () => (experiments.futureDefaults ? {} : undefined)); + write(this.outerRange); + write(this.arrayRange); + write(this.functionRange); + write(this.errorCallbackRange); + write(this.functionBindThis); + write(this.errorCallbackBindThis); - if (typeof experiments.buildHttp === "object") { - D(experiments.buildHttp, "frozen", production); - D(experiments.buildHttp, "upgrade", false); + super.serialize(context); } - if (typeof experiments.css === "object") { - D( - experiments.css, - "exportsOnly", - !targetProperties || !targetProperties.document - ); - } -}; + deserialize(context) { + const { read } = context; -/** - * @param {CacheOptions} cache options - * @param {Object} options options - * @param {string} options.name name - * @param {string} options.mode mode - * @param {boolean} options.development is development mode - * @param {boolean} options.cacheUnaffected the cacheUnaffected experiment is enabled - * @returns {void} - */ -const applyCacheDefaults = ( - cache, - { name, mode, development, cacheUnaffected } -) => { - if (cache === false) return; - switch (cache.type) { - case "filesystem": - F(cache, "name", () => name + "-" + mode); - D(cache, "version", ""); - F(cache, "cacheDirectory", () => { - const cwd = process.cwd(); - let dir = cwd; - for (;;) { - try { - if (fs.statSync(path.join(dir, "package.json")).isFile()) break; - // eslint-disable-next-line no-empty - } catch (e) {} - const parent = path.dirname(dir); - if (dir === parent) { - dir = undefined; - break; - } - dir = parent; - } - if (!dir) { - return path.resolve(cwd, ".cache/webpack"); - } else if (process.versions.pnp === "1") { - return path.resolve(dir, ".pnp/.cache/webpack"); - } else if (process.versions.pnp === "3") { - return path.resolve(dir, ".yarn/.cache/webpack"); - } else { - return path.resolve(dir, "node_modules/.cache/webpack"); - } - }); - F(cache, "cacheLocation", () => - path.resolve(cache.cacheDirectory, cache.name) - ); - D(cache, "hashAlgorithm", "md4"); - D(cache, "store", "pack"); - D(cache, "compression", false); - D(cache, "profile", false); - D(cache, "idleTimeout", 60000); - D(cache, "idleTimeoutForInitialStore", 5000); - D(cache, "idleTimeoutAfterLargeChanges", 1000); - D(cache, "maxMemoryGenerations", development ? 5 : Infinity); - D(cache, "maxAge", 1000 * 60 * 60 * 24 * 60); // 1 month - D(cache, "allowCollectingMemory", development); - D(cache, "memoryCacheUnaffected", development && cacheUnaffected); - D(cache.buildDependencies, "defaultWebpack", [ - path.resolve(__dirname, "..") + path.sep - ]); - break; - case "memory": - D(cache, "maxGenerations", Infinity); - D(cache, "cacheUnaffected", development && cacheUnaffected); - break; + this.outerRange = read(); + this.arrayRange = read(); + this.functionRange = read(); + this.errorCallbackRange = read(); + this.functionBindThis = read(); + this.errorCallbackBindThis = read(); + + super.deserialize(context); } -}; +} -/** - * @param {SnapshotOptions} snapshot options - * @param {Object} options options - * @param {boolean} options.production is production - * @param {boolean} options.futureDefaults is future defaults enabled - * @returns {void} - */ -const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => { - if (futureDefaults) { - F(snapshot, "managedPaths", () => - process.versions.pnp === "3" - ? [ - /^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/ - ] - : [/^(.+?[\\/]node_modules[\\/])/] - ); - F(snapshot, "immutablePaths", () => - process.versions.pnp === "3" - ? [/^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/] - : [] +makeSerializable( + AMDRequireDependency, + "webpack/lib/dependencies/AMDRequireDependency" +); + +AMDRequireDependency.Template = class AMDRequireDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {AMDRequireDependency} */ (dependency); + const depBlock = /** @type {AsyncDependenciesBlock} */ ( + moduleGraph.getParentBlock(dep) ); - } else { - A(snapshot, "managedPaths", () => { - if (process.versions.pnp === "3") { - const match = - /^(.+?)[\\/]cache[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec( - /*require.resolve*/(36871) - ); - if (match) { - return [path.resolve(match[1], "unplugged")]; - } - } else { - const match = /^(.+?[\\/]node_modules[\\/])/.exec( - // eslint-disable-next-line node/no-extraneous-require - /*require.resolve*/(36871) - ); - if (match) { - return [match[1]]; - } - } - return []; - }); - A(snapshot, "immutablePaths", () => { - if (process.versions.pnp === "1") { - const match = - /^(.+?[\\/]v4)[\\/]npm-watchpack-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec( - /*require.resolve*/(36871) - ); - if (match) { - return [match[1]]; - } - } else if (process.versions.pnp === "3") { - const match = - /^(.+?)[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec( - /*require.resolve*/(36871) - ); - if (match) { - return [match[1]]; - } - } - return []; + const promise = runtimeTemplate.blockPromise({ + chunkGraph, + block: depBlock, + message: "AMD require", + runtimeRequirements }); - } - F(snapshot, "resolveBuildDependencies", () => ({ - timestamp: true, - hash: true - })); - F(snapshot, "buildDependencies", () => ({ timestamp: true, hash: true })); - F(snapshot, "module", () => - production ? { timestamp: true, hash: true } : { timestamp: true } - ); - F(snapshot, "resolve", () => - production ? { timestamp: true, hash: true } : { timestamp: true } - ); -}; -/** - * @param {JavascriptParserOptions} parserOptions parser options - * @param {Object} options options - * @param {boolean} options.futureDefaults is future defaults enabled - * @returns {void} - */ -const applyJavascriptParserOptionsDefaults = ( - parserOptions, - { futureDefaults } -) => { - D(parserOptions, "unknownContextRequest", "."); - D(parserOptions, "unknownContextRegExp", false); - D(parserOptions, "unknownContextRecursive", true); - D(parserOptions, "unknownContextCritical", true); - D(parserOptions, "exprContextRequest", "."); - D(parserOptions, "exprContextRegExp", false); - D(parserOptions, "exprContextRecursive", true); - D(parserOptions, "exprContextCritical", true); - D(parserOptions, "wrappedContextRegExp", /.*/); - D(parserOptions, "wrappedContextRecursive", true); - D(parserOptions, "wrappedContextCritical", false); - D(parserOptions, "strictThisContextOnImports", false); - if (futureDefaults) D(parserOptions, "exportsPresence", "error"); -}; + // has array range but no function range + if (dep.arrayRange && !dep.functionRange) { + const startBlock = `${promise}.then(function() {`; + const endBlock = `;})['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; + runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); -/** - * @param {ModuleOptions} module options - * @param {Object} options options - * @param {boolean} options.cache is caching enabled - * @param {boolean} options.syncWebAssembly is syncWebAssembly enabled - * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled - * @param {CssExperimentOptions} options.css is css enabled - * @param {boolean} options.futureDefaults is future defaults enabled - * @returns {void} - */ -const applyModuleDefaults = ( - module, - { cache, syncWebAssembly, asyncWebAssembly, css, futureDefaults } -) => { - if (cache) { - D(module, "unsafeCache", module => { - const name = module.nameForCondition(); - return name && NODE_MODULES_REGEXP.test(name); - }); - } else { - D(module, "unsafeCache", false); - } + source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); - F(module.parser, "asset", () => ({})); - F(module.parser.asset, "dataUrlCondition", () => ({})); - if (typeof module.parser.asset.dataUrlCondition === "object") { - D(module.parser.asset.dataUrlCondition, "maxSize", 8096); - } + source.replace(dep.arrayRange[1], dep.outerRange[1] - 1, endBlock); - F(module.parser, "javascript", () => ({})); - applyJavascriptParserOptionsDefaults(module.parser.javascript, { - futureDefaults - }); + return; + } - A(module, "defaultRules", () => { - const esm = { - type: "javascript/esm", - resolve: { - byDependency: { - esm: { - fullySpecified: true - } - } - } - }; - const commonjs = { - type: "javascript/dynamic" - }; - /** @type {RuleSetRules} */ - const rules = [ - { - mimetype: "application/node", - type: "javascript/auto" - }, - { - test: /\.json$/i, - type: "json" - }, - { - mimetype: "application/json", - type: "json" - }, - { - test: /\.mjs$/i, - ...esm - }, - { - test: /\.js$/i, - descriptionData: { - type: "module" - }, - ...esm - }, - { - test: /\.cjs$/i, - ...commonjs - }, - { - test: /\.js$/i, - descriptionData: { - type: "commonjs" - }, - ...commonjs - }, - { - mimetype: { - or: ["text/javascript", "application/javascript"] - }, - ...esm - } - ]; - if (asyncWebAssembly) { - const wasm = { - type: "webassembly/async", - rules: [ - { - descriptionData: { - type: "module" - }, - resolve: { - fullySpecified: true - } - } - ] - }; - rules.push({ - test: /\.wasm$/i, - ...wasm - }); - rules.push({ - mimetype: "application/wasm", - ...wasm - }); - } else if (syncWebAssembly) { - const wasm = { - type: "webassembly/sync", - rules: [ - { - descriptionData: { - type: "module" - }, - resolve: { - fullySpecified: true - } - } - ] - }; - rules.push({ - test: /\.wasm$/i, - ...wasm - }); - rules.push({ - mimetype: "application/wasm", - ...wasm - }); - } - if (css) { - const cssRule = { - type: "css", - resolve: { - fullySpecified: true, - preferRelative: true - } - }; - const cssModulesRule = { - type: "css/module", - resolve: { - fullySpecified: true - } - }; - rules.push({ - test: /\.css$/i, - oneOf: [ - { - test: /\.module\.css$/i, - ...cssModulesRule - }, - { - ...cssRule - } - ] - }); - rules.push({ - mimetype: "text/css+module", - ...cssModulesRule - }); - rules.push({ - mimetype: "text/css", - ...cssRule - }); - } - rules.push( - { - dependency: "url", - oneOf: [ - { - scheme: /^data$/, - type: "asset/inline" - }, - { - type: "asset/resource" - } - ] - }, - { - assert: { type: "json" }, - type: "json" - } - ); - return rules; - }); -}; + // has function range but no array range + if (dep.functionRange && !dep.arrayRange) { + const startBlock = `${promise}.then((`; + const endBlock = `).bind(exports, __webpack_require__, exports, module))['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; + runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); -/** - * @param {Output} output options - * @param {Object} options options - * @param {string} options.context context - * @param {TargetProperties | false} options.targetProperties target properties - * @param {boolean} options.isAffectedByBrowserslist is affected by browserslist - * @param {boolean} options.outputModule is outputModule experiment enabled - * @param {boolean} options.development is development mode - * @param {Entry} options.entry entry option - * @param {ModuleOptions} options.module module option - * @param {boolean} options.futureDefaults is future defaults enabled - * @returns {void} - */ -const applyOutputDefaults = ( - output, - { - context, - targetProperties: tp, - isAffectedByBrowserslist, - outputModule, - development, - entry, - module, - futureDefaults - } -) => { - /** - * @param {Library=} library the library option - * @returns {string} a readable library name - */ - const getLibraryName = library => { - const libraryName = - typeof library === "object" && - library && - !Array.isArray(library) && - "type" in library - ? library.name - : /** @type {LibraryName=} */ (library); - if (Array.isArray(libraryName)) { - return libraryName.join("."); - } else if (typeof libraryName === "object") { - return getLibraryName(libraryName.root); - } else if (typeof libraryName === "string") { - return libraryName; - } - return ""; - }; + source.replace(dep.outerRange[0], dep.functionRange[0] - 1, startBlock); - F(output, "uniqueName", () => { - const libraryName = getLibraryName(output.library); - if (libraryName) return libraryName; - const pkgPath = path.resolve(context, "package.json"); - try { - const packageInfo = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); - return packageInfo.name || ""; - } catch (e) { - if (e.code !== "ENOENT") { - e.message += `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`; - throw e; - } - return ""; - } - }); + source.replace(dep.functionRange[1], dep.outerRange[1] - 1, endBlock); - F(output, "module", () => !!outputModule); - D(output, "filename", output.module ? "[name].mjs" : "[name].js"); - F(output, "iife", () => !output.module); - D(output, "importFunctionName", "import"); - D(output, "importMetaName", "import.meta"); - F(output, "chunkFilename", () => { - const filename = output.filename; - if (typeof filename !== "function") { - const hasName = filename.includes("[name]"); - const hasId = filename.includes("[id]"); - const hasChunkHash = filename.includes("[chunkhash]"); - const hasContentHash = filename.includes("[contenthash]"); - // Anything changing depending on chunk is fine - if (hasChunkHash || hasContentHash || hasName || hasId) return filename; - // Otherwise prefix "[id]." in front of the basename to make it changing - return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2"); - } - return output.module ? "[id].mjs" : "[id].js"; - }); - F(output, "cssFilename", () => { - const filename = output.filename; - if (typeof filename !== "function") { - return filename.replace(/\.[mc]?js(\?|$)/, ".css$1"); - } - return "[id].css"; - }); - F(output, "cssChunkFilename", () => { - const chunkFilename = output.chunkFilename; - if (typeof chunkFilename !== "function") { - return chunkFilename.replace(/\.[mc]?js(\?|$)/, ".css$1"); - } - return "[id].css"; - }); - D(output, "assetModuleFilename", "[hash][ext][query]"); - D(output, "webassemblyModuleFilename", "[hash].module.wasm"); - D(output, "compareBeforeEmit", true); - D(output, "charset", true); - F(output, "hotUpdateGlobal", () => - Template.toIdentifier( - "webpackHotUpdate" + Template.toIdentifier(output.uniqueName) - ) - ); - F(output, "chunkLoadingGlobal", () => - Template.toIdentifier( - "webpackChunk" + Template.toIdentifier(output.uniqueName) - ) - ); - F(output, "globalObject", () => { - if (tp) { - if (tp.global) return "global"; - if (tp.globalThis) return "globalThis"; - } - return "self"; - }); - F(output, "chunkFormat", () => { - if (tp) { - const helpMessage = isAffectedByBrowserslist - ? "Make sure that your 'browserslist' includes only platforms that support these features or select an appropriate 'target' to allow selecting a chunk format by default. Alternatively specify the 'output.chunkFormat' directly." - : "Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly."; - if (output.module) { - if (tp.dynamicImport) return "module"; - if (tp.document) return "array-push"; - throw new Error( - "For the selected environment is no default ESM chunk format available:\n" + - "ESM exports can be chosen when 'import()' is available.\n" + - "JSONP Array push can be chosen when 'document' is available.\n" + - helpMessage - ); - } else { - if (tp.document) return "array-push"; - if (tp.require) return "commonjs"; - if (tp.nodeBuiltins) return "commonjs"; - if (tp.importScripts) return "array-push"; - throw new Error( - "For the selected environment is no default script chunk format available:\n" + - "JSONP Array push can be chosen when 'document' or 'importScripts' is available.\n" + - "CommonJs exports can be chosen when 'require' or node builtins are available.\n" + - helpMessage - ); - } - } - throw new Error( - "Chunk format can't be selected by default when no target is specified" - ); - }); - D(output, "asyncChunks", true); - F(output, "chunkLoading", () => { - if (tp) { - switch (output.chunkFormat) { - case "array-push": - if (tp.document) return "jsonp"; - if (tp.importScripts) return "import-scripts"; - break; - case "commonjs": - if (tp.require) return "require"; - if (tp.nodeBuiltins) return "async-node"; - break; - case "module": - if (tp.dynamicImport) return "import"; - break; - } - if ( - tp.require === null || - tp.nodeBuiltins === null || - tp.document === null || - tp.importScripts === null - ) { - return "universal"; - } - } - return false; - }); - F(output, "workerChunkLoading", () => { - if (tp) { - switch (output.chunkFormat) { - case "array-push": - if (tp.importScriptsInWorker) return "import-scripts"; - break; - case "commonjs": - if (tp.require) return "require"; - if (tp.nodeBuiltins) return "async-node"; - break; - case "module": - if (tp.dynamicImportInWorker) return "import"; - break; - } - if ( - tp.require === null || - tp.nodeBuiltins === null || - tp.importScriptsInWorker === null - ) { - return "universal"; - } - } - return false; - }); - F(output, "wasmLoading", () => { - if (tp) { - if (tp.fetchWasm) return "fetch"; - if (tp.nodeBuiltins) - return output.module ? "async-node-module" : "async-node"; - if (tp.nodeBuiltins === null || tp.fetchWasm === null) { - return "universal"; - } + return; } - return false; - }); - F(output, "workerWasmLoading", () => output.wasmLoading); - F(output, "devtoolNamespace", () => output.uniqueName); - if (output.library) { - F(output.library, "type", () => (output.module ? "module" : "var")); - } - F(output, "path", () => path.join(process.cwd(), "dist")); - F(output, "pathinfo", () => development); - D(output, "sourceMapFilename", "[file].map[query]"); - D( - output, - "hotUpdateChunkFilename", - `[id].[fullhash].hot-update.${output.module ? "mjs" : "js"}` - ); - D(output, "hotUpdateMainFilename", "[runtime].[fullhash].hot-update.json"); - D(output, "crossOriginLoading", false); - F(output, "scriptType", () => (output.module ? "module" : false)); - D( - output, - "publicPath", - (tp && (tp.document || tp.importScripts)) || output.scriptType === "module" - ? "auto" - : "" - ); - D(output, "chunkLoadTimeout", 120000); - D(output, "hashFunction", futureDefaults ? "xxhash64" : "md4"); - D(output, "hashDigest", "hex"); - D(output, "hashDigestLength", futureDefaults ? 16 : 20); - D(output, "strictModuleExceptionHandling", false); - const optimistic = v => v || v === undefined; - F( - output.environment, - "arrowFunction", - () => tp && optimistic(tp.arrowFunction) - ); - F(output.environment, "const", () => tp && optimistic(tp.const)); - F( - output.environment, - "destructuring", - () => tp && optimistic(tp.destructuring) - ); - F(output.environment, "forOf", () => tp && optimistic(tp.forOf)); - F(output.environment, "bigIntLiteral", () => tp && tp.bigIntLiteral); - F(output.environment, "dynamicImport", () => tp && tp.dynamicImport); - F(output.environment, "module", () => tp && tp.module); + // has array range, function range, and errorCallbackRange + if (dep.arrayRange && dep.functionRange && dep.errorCallbackRange) { + const startBlock = `${promise}.then(function() { `; + const errorRangeBlock = `}${ + dep.functionBindThis ? ".bind(this)" : "" + })['catch'](`; + const endBlock = `${dep.errorCallbackBindThis ? ".bind(this)" : ""})`; - const { trustedTypes } = output; - if (trustedTypes) { - F( - trustedTypes, - "policyName", - () => - output.uniqueName.replace(/[^a-zA-Z0-9\-#=_/@.%]+/g, "_") || "webpack" - ); - } + source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); - /** - * @param {function(EntryDescription): void} fn iterator - * @returns {void} - */ - const forEachEntry = fn => { - for (const name of Object.keys(entry)) { - fn(entry[name]); - } - }; - A(output, "enabledLibraryTypes", () => { - const enabledLibraryTypes = []; - if (output.library) { - enabledLibraryTypes.push(output.library.type); - } - forEachEntry(desc => { - if (desc.library) { - enabledLibraryTypes.push(desc.library.type); - } - }); - return enabledLibraryTypes; - }); + source.insert(dep.arrayRange[0], "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); - A(output, "enabledChunkLoadingTypes", () => { - const enabledChunkLoadingTypes = new Set(); - if (output.chunkLoading) { - enabledChunkLoadingTypes.add(output.chunkLoading); - } - if (output.workerChunkLoading) { - enabledChunkLoadingTypes.add(output.workerChunkLoading); - } - forEachEntry(desc => { - if (desc.chunkLoading) { - enabledChunkLoadingTypes.add(desc.chunkLoading); - } - }); - return Array.from(enabledChunkLoadingTypes); - }); + source.replace(dep.arrayRange[1], dep.functionRange[0] - 1, "; ("); - A(output, "enabledWasmLoadingTypes", () => { - const enabledWasmLoadingTypes = new Set(); - if (output.wasmLoading) { - enabledWasmLoadingTypes.add(output.wasmLoading); - } - if (output.workerWasmLoading) { - enabledWasmLoadingTypes.add(output.workerWasmLoading); - } - forEachEntry(desc => { - if (desc.wasmLoading) { - enabledWasmLoadingTypes.add(desc.wasmLoading); - } - }); - return Array.from(enabledWasmLoadingTypes); - }); -}; + source.insert( + dep.functionRange[1], + ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" + ); -/** - * @param {ExternalsPresets} externalsPresets options - * @param {Object} options options - * @param {TargetProperties | false} options.targetProperties target properties - * @param {boolean} options.buildHttp buildHttp experiment enabled - * @returns {void} - */ -const applyExternalsPresetsDefaults = ( - externalsPresets, - { targetProperties, buildHttp } -) => { - D( - externalsPresets, - "web", - !buildHttp && targetProperties && targetProperties.web - ); - D(externalsPresets, "node", targetProperties && targetProperties.node); - D(externalsPresets, "nwjs", targetProperties && targetProperties.nwjs); - D( - externalsPresets, - "electron", - targetProperties && targetProperties.electron - ); - D( - externalsPresets, - "electronMain", - targetProperties && - targetProperties.electron && - targetProperties.electronMain - ); - D( - externalsPresets, - "electronPreload", - targetProperties && - targetProperties.electron && - targetProperties.electronPreload - ); - D( - externalsPresets, - "electronRenderer", - targetProperties && - targetProperties.electron && - targetProperties.electronRenderer - ); -}; + source.replace( + dep.functionRange[1], + dep.errorCallbackRange[0] - 1, + errorRangeBlock + ); -/** - * @param {Loader} loader options - * @param {Object} options options - * @param {TargetProperties | false} options.targetProperties target properties - * @returns {void} - */ -const applyLoaderDefaults = (loader, { targetProperties }) => { - F(loader, "target", () => { - if (targetProperties) { - if (targetProperties.electron) { - if (targetProperties.electronMain) return "electron-main"; - if (targetProperties.electronPreload) return "electron-preload"; - if (targetProperties.electronRenderer) return "electron-renderer"; - return "electron"; - } - if (targetProperties.nwjs) return "nwjs"; - if (targetProperties.node) return "node"; - if (targetProperties.web) return "web"; + source.replace( + dep.errorCallbackRange[1], + dep.outerRange[1] - 1, + endBlock + ); + + return; } - }); -}; -/** - * @param {WebpackNode} node options - * @param {Object} options options - * @param {TargetProperties | false} options.targetProperties target properties - * @param {boolean} options.futureDefaults is future defaults enabled - * @returns {void} - */ -const applyNodeDefaults = (node, { futureDefaults, targetProperties }) => { - if (node === false) return; + // has array range, function range, but no errorCallbackRange + if (dep.arrayRange && dep.functionRange) { + const startBlock = `${promise}.then(function() { `; + const endBlock = `}${ + dep.functionBindThis ? ".bind(this)" : "" + })['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; + runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); - F(node, "global", () => { - if (targetProperties && targetProperties.global) return false; - // TODO webpack 6 should always default to false - return futureDefaults ? "warn" : true; - }); - F(node, "__filename", () => { - if (targetProperties && targetProperties.node) return "eval-only"; - // TODO webpack 6 should always default to false - return futureDefaults ? "warn-mock" : "mock"; - }); - F(node, "__dirname", () => { - if (targetProperties && targetProperties.node) return "eval-only"; - // TODO webpack 6 should always default to false - return futureDefaults ? "warn-mock" : "mock"; - }); -}; + source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); -/** - * @param {Performance} performance options - * @param {Object} options options - * @param {boolean} options.production is production - * @returns {void} - */ -const applyPerformanceDefaults = (performance, { production }) => { - if (performance === false) return; - D(performance, "maxAssetSize", 250000); - D(performance, "maxEntrypointSize", 250000); - F(performance, "hints", () => (production ? "warning" : false)); -}; + source.insert(dep.arrayRange[0], "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); -/** - * @param {Optimization} optimization options - * @param {Object} options options - * @param {boolean} options.production is production - * @param {boolean} options.development is development - * @param {CssExperimentOptions} options.css is css enabled - * @param {boolean} options.records using records - * @returns {void} - */ -const applyOptimizationDefaults = ( - optimization, - { production, development, css, records } -) => { - D(optimization, "removeAvailableModules", false); - D(optimization, "removeEmptyChunks", true); - D(optimization, "mergeDuplicateChunks", true); - D(optimization, "flagIncludedChunks", production); - F(optimization, "moduleIds", () => { - if (production) return "deterministic"; - if (development) return "named"; - return "natural"; - }); - F(optimization, "chunkIds", () => { - if (production) return "deterministic"; - if (development) return "named"; - return "natural"; - }); - F(optimization, "sideEffects", () => (production ? true : "flag")); - D(optimization, "providedExports", true); - D(optimization, "usedExports", production); - D(optimization, "innerGraph", production); - D(optimization, "mangleExports", production); - D(optimization, "concatenateModules", production); - D(optimization, "runtimeChunk", false); - D(optimization, "emitOnErrors", !production); - D(optimization, "checkWasmTypes", production); - D(optimization, "mangleWasmImports", false); - D(optimization, "portableRecords", records); - D(optimization, "realContentHash", production); - D(optimization, "minimize", production); - A(optimization, "minimizer", () => [ - { - apply: compiler => { - // Lazy load the Terser plugin - const TerserPlugin = __webpack_require__(55302); - new TerserPlugin({ - terserOptions: { - compress: { - passes: 2 - } - } - }).apply(compiler); - } + source.replace(dep.arrayRange[1], dep.functionRange[0] - 1, "; ("); + + source.insert( + dep.functionRange[1], + ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" + ); + + source.replace(dep.functionRange[1], dep.outerRange[1] - 1, endBlock); } - ]); - F(optimization, "nodeEnv", () => { - if (production) return "production"; - if (development) return "development"; - return false; - }); - const { splitChunks } = optimization; - if (splitChunks) { - A(splitChunks, "defaultSizeTypes", () => - css ? ["javascript", "css", "unknown"] : ["javascript", "unknown"] - ); - D(splitChunks, "hidePathInfo", production); - D(splitChunks, "chunks", "async"); - D(splitChunks, "usedExports", optimization.usedExports === true); - D(splitChunks, "minChunks", 1); - F(splitChunks, "minSize", () => (production ? 20000 : 10000)); - F(splitChunks, "minRemainingSize", () => (development ? 0 : undefined)); - F(splitChunks, "enforceSizeThreshold", () => (production ? 50000 : 30000)); - F(splitChunks, "maxAsyncRequests", () => (production ? 30 : Infinity)); - F(splitChunks, "maxInitialRequests", () => (production ? 30 : Infinity)); - D(splitChunks, "automaticNameDelimiter", "-"); - const { cacheGroups } = splitChunks; - F(cacheGroups, "default", () => ({ - idHint: "", - reuseExistingChunk: true, - minChunks: 2, - priority: -20 - })); - F(cacheGroups, "defaultVendors", () => ({ - idHint: "vendors", - reuseExistingChunk: true, - test: NODE_MODULES_REGEXP, - priority: -10 - })); } }; -/** - * @param {Object} options options - * @param {boolean} options.cache is cache enable - * @param {string} options.context build context - * @param {TargetProperties | false} options.targetProperties target properties - * @param {Mode} options.mode mode - * @returns {ResolveOptions} resolve options - */ -const getResolveDefaults = ({ cache, context, targetProperties, mode }) => { - /** @type {string[]} */ - const conditions = ["webpack"]; +module.exports = AMDRequireDependency; - conditions.push(mode === "development" ? "development" : "production"); - if (targetProperties) { - if (targetProperties.webworker) conditions.push("worker"); - if (targetProperties.node) conditions.push("node"); - if (targetProperties.web) conditions.push("browser"); - if (targetProperties.electron) conditions.push("electron"); - if (targetProperties.nwjs) conditions.push("nwjs"); - } +/***/ }), - const jsExtensions = [".js", ".json", ".wasm"]; +/***/ 71806: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const tp = targetProperties; - const browserField = - tp && tp.web && (!tp.node || (tp.electron && tp.electronRenderer)); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {function(): ResolveOptions} */ - const cjsDeps = () => ({ - aliasFields: browserField ? ["browser"] : [], - mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."], - conditionNames: ["require", "module", "..."], - extensions: [...jsExtensions] - }); - /** @type {function(): ResolveOptions} */ - const esmDeps = () => ({ - aliasFields: browserField ? ["browser"] : [], - mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."], - conditionNames: ["import", "module", "..."], - extensions: [...jsExtensions] - }); - /** @type {ResolveOptions} */ - const resolveOptions = { - cache, - modules: ["node_modules"], - conditionNames: conditions, - mainFiles: ["index"], - extensions: [], - aliasFields: [], - exportsFields: ["exports"], - roots: [context], - mainFields: ["main"], - byDependency: { - wasm: esmDeps(), - esm: esmDeps(), - loaderImport: esmDeps(), - url: { - preferRelative: true - }, - worker: { - ...esmDeps(), - preferRelative: true - }, - commonjs: cjsDeps(), - amd: cjsDeps(), - // for backward-compat: loadModule - loader: cjsDeps(), - // for backward-compat: Custom Dependency - unknown: cjsDeps(), - // for backward-compat: getResolve without dependencyType - undefined: cjsDeps() - } - }; - return resolveOptions; -}; +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyTemplateAsRequireId = __webpack_require__(36873); -/** - * @param {Object} options options - * @param {boolean} options.cache is cache enable - * @returns {ResolveOptions} resolve options - */ -const getResolveLoaderDefaults = ({ cache }) => { - /** @type {ResolveOptions} */ - const resolveOptions = { - cache, - conditionNames: ["loader", "require", "node"], - exportsFields: ["exports"], - mainFields: ["loader", "main"], - extensions: [".js"], - mainFiles: ["index"] - }; +class AMDRequireItemDependency extends ModuleDependency { + constructor(request, range) { + super(request); - return resolveOptions; -}; + this.range = range; + } -/** - * @param {InfrastructureLogging} infrastructureLogging options - * @returns {void} - */ -const applyInfrastructureLoggingDefaults = infrastructureLogging => { - F(infrastructureLogging, "stream", () => process.stderr); - const tty = - /** @type {any} */ (infrastructureLogging.stream).isTTY && - process.env.TERM !== "dumb"; - D(infrastructureLogging, "level", "info"); - D(infrastructureLogging, "debug", false); - D(infrastructureLogging, "colors", tty); - D(infrastructureLogging, "appendOnly", !tty); -}; + get type() { + return "amd require"; + } -exports.applyWebpackOptionsBaseDefaults = applyWebpackOptionsBaseDefaults; -exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults; + get category() { + return "amd"; + } +} + +makeSerializable( + AMDRequireItemDependency, + "webpack/lib/dependencies/AMDRequireItemDependency" +); + +AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; + +module.exports = AMDRequireItemDependency; /***/ }), -/***/ 26693: +/***/ 45242: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const util = __webpack_require__(73837); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); -/** @typedef {import("../../declarations/WebpackOptions").EntryStatic} EntryStatic */ -/** @typedef {import("../../declarations/WebpackOptions").EntryStaticNormalized} EntryStaticNormalized */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunk} OptimizationRuntimeChunk */ -/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunkNormalized} OptimizationRuntimeChunkNormalized */ -/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} OutputNormalized */ -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */ +class AMDDefineRuntimeModule extends RuntimeModule { + constructor() { + super("amd define"); + } -const handledDeprecatedNoEmitOnErrors = util.deprecate( - (noEmitOnErrors, emitOnErrors) => { - if (emitOnErrors !== undefined && !noEmitOnErrors === !emitOnErrors) { - throw new Error( - "Conflicting use of 'optimization.noEmitOnErrors' and 'optimization.emitOnErrors'. Remove deprecated 'optimization.noEmitOnErrors' from config." - ); - } - return !noEmitOnErrors; - }, - "optimization.noEmitOnErrors is deprecated in favor of optimization.emitOnErrors", - "DEP_WEBPACK_CONFIGURATION_OPTIMIZATION_NO_EMIT_ON_ERRORS" -); + /** + * @returns {string} runtime code + */ + generate() { + return Template.asString([ + `${RuntimeGlobals.amdDefine} = function () {`, + Template.indent("throw new Error('define cannot be used indirect');"), + "};" + ]); + } +} -/** - * @template T - * @template R - * @param {T|undefined} value value or not - * @param {function(T): R} fn nested handler - * @returns {R} result value - */ -const nestedConfig = (value, fn) => - value === undefined ? fn(/** @type {T} */ ({})) : fn(value); +class AMDOptionsRuntimeModule extends RuntimeModule { + /** + * @param {Record} options the AMD options + */ + constructor(options) { + super("amd options"); + this.options = options; + } -/** - * @template T - * @param {T|undefined} value value or not - * @returns {T} result value - */ -const cloneObject = value => { - return /** @type {T} */ ({ ...value }); -}; + /** + * @returns {string} runtime code + */ + generate() { + return Template.asString([ + `${RuntimeGlobals.amdOptions} = ${JSON.stringify(this.options)};` + ]); + } +} -/** - * @template T - * @template R - * @param {T|undefined} value value or not - * @param {function(T): R} fn nested handler - * @returns {R|undefined} result value - */ -const optionalNestedConfig = (value, fn) => - value === undefined ? undefined : fn(value); +exports.AMDDefineRuntimeModule = AMDDefineRuntimeModule; +exports.AMDOptionsRuntimeModule = AMDOptionsRuntimeModule; -/** - * @template T - * @template R - * @param {T[]|undefined} value array or not - * @param {function(T[]): R[]} fn nested handler - * @returns {R[]|undefined} cloned value - */ -const nestedArray = (value, fn) => (Array.isArray(value) ? fn(value) : fn([])); -/** - * @template T - * @template R - * @param {T[]|undefined} value array or not - * @param {function(T[]): R[]} fn nested handler - * @returns {R[]|undefined} cloned value - */ -const optionalNestedArray = (value, fn) => - Array.isArray(value) ? fn(value) : undefined; +/***/ }), -/** - * @template T - * @template R - * @param {Record|undefined} value value or not - * @param {function(T): R} fn nested handler - * @param {Record=} customKeys custom nested handler for some keys - * @returns {Record} result value - */ -const keyedNestedConfig = (value, fn, customKeys) => { - const result = - value === undefined - ? {} - : Object.keys(value).reduce( - (obj, key) => ( - (obj[key] = ( - customKeys && key in customKeys ? customKeys[key] : fn - )(value[key])), - obj - ), - /** @type {Record} */ ({}) - ); - if (customKeys) { - for (const key of Object.keys(customKeys)) { - if (!(key in result)) { - result[key] = customKeys[key](/** @type {T} */ ({})); - } - } +/***/ 57403: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + + + +const DependencyTemplate = __webpack_require__(5160); +const InitFragment = __webpack_require__(55870); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../util/Hash")} Hash */ + +class CachedConstDependency extends NullDependency { + constructor(expression, range, identifier) { + super(); + + this.expression = expression; + this.range = range; + this.identifier = identifier; + this._hashUpdate = undefined; } - return result; -}; -/** - * @param {WebpackOptions} config input config - * @returns {WebpackOptionsNormalized} normalized options - */ -const getNormalizedWebpackOptions = config => { - return { - amd: config.amd, - bail: config.bail, - cache: optionalNestedConfig(config.cache, cache => { - if (cache === false) return false; - if (cache === true) { - return { - type: "memory", - maxGenerations: undefined - }; - } - switch (cache.type) { - case "filesystem": - return { - type: "filesystem", - allowCollectingMemory: cache.allowCollectingMemory, - maxMemoryGenerations: cache.maxMemoryGenerations, - maxAge: cache.maxAge, - profile: cache.profile, - buildDependencies: cloneObject(cache.buildDependencies), - cacheDirectory: cache.cacheDirectory, - cacheLocation: cache.cacheLocation, - hashAlgorithm: cache.hashAlgorithm, - compression: cache.compression, - idleTimeout: cache.idleTimeout, - idleTimeoutForInitialStore: cache.idleTimeoutForInitialStore, - idleTimeoutAfterLargeChanges: cache.idleTimeoutAfterLargeChanges, - name: cache.name, - store: cache.store, - version: cache.version - }; - case undefined: - case "memory": - return { - type: "memory", - maxGenerations: cache.maxGenerations - }; - default: - // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339) - throw new Error(`Not implemented cache.type ${cache.type}`); - } - }), - context: config.context, - dependencies: config.dependencies, - devServer: optionalNestedConfig(config.devServer, devServer => ({ - ...devServer - })), - devtool: config.devtool, - entry: - config.entry === undefined - ? { main: {} } - : typeof config.entry === "function" - ? ( - fn => () => - Promise.resolve().then(fn).then(getNormalizedEntryStatic) - )(config.entry) - : getNormalizedEntryStatic(config.entry), - experiments: nestedConfig(config.experiments, experiments => ({ - ...experiments, - buildHttp: optionalNestedConfig(experiments.buildHttp, options => - Array.isArray(options) ? { allowedUris: options } : options - ), - lazyCompilation: optionalNestedConfig( - experiments.lazyCompilation, - options => - options === true ? {} : options === false ? undefined : options - ), - css: optionalNestedConfig(experiments.css, options => - options === true ? {} : options === false ? undefined : options - ) - })), - externals: config.externals, - externalsPresets: cloneObject(config.externalsPresets), - externalsType: config.externalsType, - ignoreWarnings: config.ignoreWarnings - ? config.ignoreWarnings.map(ignore => { - if (typeof ignore === "function") return ignore; - const i = ignore instanceof RegExp ? { message: ignore } : ignore; - return (warning, { requestShortener }) => { - if (!i.message && !i.module && !i.file) return false; - if (i.message && !i.message.test(warning.message)) { - return false; - } - if ( - i.module && - (!warning.module || - !i.module.test( - warning.module.readableIdentifier(requestShortener) - )) - ) { - return false; - } - if (i.file && (!warning.file || !i.file.test(warning.file))) { - return false; - } - return true; - }; - }) - : undefined, - infrastructureLogging: cloneObject(config.infrastructureLogging), - loader: cloneObject(config.loader), - mode: config.mode, - module: nestedConfig(config.module, module => ({ - noParse: module.noParse, - unsafeCache: module.unsafeCache, - parser: keyedNestedConfig(module.parser, cloneObject, { - javascript: parserOptions => ({ - unknownContextRequest: module.unknownContextRequest, - unknownContextRegExp: module.unknownContextRegExp, - unknownContextRecursive: module.unknownContextRecursive, - unknownContextCritical: module.unknownContextCritical, - exprContextRequest: module.exprContextRequest, - exprContextRegExp: module.exprContextRegExp, - exprContextRecursive: module.exprContextRecursive, - exprContextCritical: module.exprContextCritical, - wrappedContextRegExp: module.wrappedContextRegExp, - wrappedContextRecursive: module.wrappedContextRecursive, - wrappedContextCritical: module.wrappedContextCritical, - // TODO webpack 6 remove - strictExportPresence: module.strictExportPresence, - strictThisContextOnImports: module.strictThisContextOnImports, - ...parserOptions - }) - }), - generator: cloneObject(module.generator), - defaultRules: optionalNestedArray(module.defaultRules, r => [...r]), - rules: nestedArray(module.rules, r => [...r]) - })), - name: config.name, - node: nestedConfig( - config.node, - node => - node && { - ...node - } - ), - optimization: nestedConfig(config.optimization, optimization => { - return { - ...optimization, - runtimeChunk: getNormalizedOptimizationRuntimeChunk( - optimization.runtimeChunk - ), - splitChunks: nestedConfig( - optimization.splitChunks, - splitChunks => - splitChunks && { - ...splitChunks, - defaultSizeTypes: splitChunks.defaultSizeTypes - ? [...splitChunks.defaultSizeTypes] - : ["..."], - cacheGroups: cloneObject(splitChunks.cacheGroups) - } - ), - emitOnErrors: - optimization.noEmitOnErrors !== undefined - ? handledDeprecatedNoEmitOnErrors( - optimization.noEmitOnErrors, - optimization.emitOnErrors - ) - : optimization.emitOnErrors - }; - }), - output: nestedConfig(config.output, output => { - const { library } = output; - const libraryAsName = /** @type {LibraryName} */ (library); - const libraryBase = - typeof library === "object" && - library && - !Array.isArray(library) && - "type" in library - ? library - : libraryAsName || output.libraryTarget - ? /** @type {LibraryOptions} */ ({ - name: libraryAsName - }) - : undefined; - /** @type {OutputNormalized} */ - const result = { - assetModuleFilename: output.assetModuleFilename, - asyncChunks: output.asyncChunks, - charset: output.charset, - chunkFilename: output.chunkFilename, - chunkFormat: output.chunkFormat, - chunkLoading: output.chunkLoading, - chunkLoadingGlobal: output.chunkLoadingGlobal, - chunkLoadTimeout: output.chunkLoadTimeout, - cssFilename: output.cssFilename, - cssChunkFilename: output.cssChunkFilename, - clean: output.clean, - compareBeforeEmit: output.compareBeforeEmit, - crossOriginLoading: output.crossOriginLoading, - devtoolFallbackModuleFilenameTemplate: - output.devtoolFallbackModuleFilenameTemplate, - devtoolModuleFilenameTemplate: output.devtoolModuleFilenameTemplate, - devtoolNamespace: output.devtoolNamespace, - environment: cloneObject(output.environment), - enabledChunkLoadingTypes: output.enabledChunkLoadingTypes - ? [...output.enabledChunkLoadingTypes] - : ["..."], - enabledLibraryTypes: output.enabledLibraryTypes - ? [...output.enabledLibraryTypes] - : ["..."], - enabledWasmLoadingTypes: output.enabledWasmLoadingTypes - ? [...output.enabledWasmLoadingTypes] - : ["..."], - filename: output.filename, - globalObject: output.globalObject, - hashDigest: output.hashDigest, - hashDigestLength: output.hashDigestLength, - hashFunction: output.hashFunction, - hashSalt: output.hashSalt, - hotUpdateChunkFilename: output.hotUpdateChunkFilename, - hotUpdateGlobal: output.hotUpdateGlobal, - hotUpdateMainFilename: output.hotUpdateMainFilename, - iife: output.iife, - importFunctionName: output.importFunctionName, - importMetaName: output.importMetaName, - scriptType: output.scriptType, - library: libraryBase && { - type: - output.libraryTarget !== undefined - ? output.libraryTarget - : libraryBase.type, - auxiliaryComment: - output.auxiliaryComment !== undefined - ? output.auxiliaryComment - : libraryBase.auxiliaryComment, - export: - output.libraryExport !== undefined - ? output.libraryExport - : libraryBase.export, - name: libraryBase.name, - umdNamedDefine: - output.umdNamedDefine !== undefined - ? output.umdNamedDefine - : libraryBase.umdNamedDefine - }, - module: output.module, - path: output.path, - pathinfo: output.pathinfo, - publicPath: output.publicPath, - sourceMapFilename: output.sourceMapFilename, - sourcePrefix: output.sourcePrefix, - strictModuleExceptionHandling: output.strictModuleExceptionHandling, - trustedTypes: optionalNestedConfig( - output.trustedTypes, - trustedTypes => { - if (trustedTypes === true) return {}; - if (typeof trustedTypes === "string") - return { policyName: trustedTypes }; - return { ...trustedTypes }; - } - ), - uniqueName: output.uniqueName, - wasmLoading: output.wasmLoading, - webassemblyModuleFilename: output.webassemblyModuleFilename, - workerChunkLoading: output.workerChunkLoading, - workerWasmLoading: output.workerWasmLoading - }; - return result; - }), - parallelism: config.parallelism, - performance: optionalNestedConfig(config.performance, performance => { - if (performance === false) return false; - return { - ...performance - }; - }), - plugins: nestedArray(config.plugins, p => [...p]), - profile: config.profile, - recordsInputPath: - config.recordsInputPath !== undefined - ? config.recordsInputPath - : config.recordsPath, - recordsOutputPath: - config.recordsOutputPath !== undefined - ? config.recordsOutputPath - : config.recordsPath, - resolve: nestedConfig(config.resolve, resolve => ({ - ...resolve, - byDependency: keyedNestedConfig(resolve.byDependency, cloneObject) - })), - resolveLoader: cloneObject(config.resolveLoader), - snapshot: nestedConfig(config.snapshot, snapshot => ({ - resolveBuildDependencies: optionalNestedConfig( - snapshot.resolveBuildDependencies, - resolveBuildDependencies => ({ - timestamp: resolveBuildDependencies.timestamp, - hash: resolveBuildDependencies.hash - }) - ), - buildDependencies: optionalNestedConfig( - snapshot.buildDependencies, - buildDependencies => ({ - timestamp: buildDependencies.timestamp, - hash: buildDependencies.hash - }) - ), - resolve: optionalNestedConfig(snapshot.resolve, resolve => ({ - timestamp: resolve.timestamp, - hash: resolve.hash - })), - module: optionalNestedConfig(snapshot.module, module => ({ - timestamp: module.timestamp, - hash: module.hash - })), - immutablePaths: optionalNestedArray(snapshot.immutablePaths, p => [...p]), - managedPaths: optionalNestedArray(snapshot.managedPaths, p => [...p]) - })), - stats: nestedConfig(config.stats, stats => { - if (stats === false) { - return { - preset: "none" - }; - } - if (stats === true) { - return { - preset: "normal" - }; - } - if (typeof stats === "string") { - return { - preset: stats - }; - } - return { - ...stats - }; - }), - target: config.target, - watch: config.watch, - watchOptions: cloneObject(config.watchOptions) - }; -}; - -/** - * @param {EntryStatic} entry static entry options - * @returns {EntryStaticNormalized} normalized static entry options - */ -const getNormalizedEntryStatic = entry => { - if (typeof entry === "string") { - return { - main: { - import: [entry] - } - }; - } - if (Array.isArray(entry)) { - return { - main: { - import: entry - } - }; - } - /** @type {EntryStaticNormalized} */ - const result = {}; - for (const key of Object.keys(entry)) { - const value = entry[key]; - if (typeof value === "string") { - result[key] = { - import: [value] - }; - } else if (Array.isArray(value)) { - result[key] = { - import: value - }; - } else { - result[key] = { - import: - value.import && - (Array.isArray(value.import) ? value.import : [value.import]), - filename: value.filename, - layer: value.layer, - runtime: value.runtime, - publicPath: value.publicPath, - chunkLoading: value.chunkLoading, - asyncChunks: value.asyncChunks, - wasmLoading: value.wasmLoading, - dependOn: - value.dependOn && - (Array.isArray(value.dependOn) ? value.dependOn : [value.dependOn]), - library: value.library - }; - } - } - return result; -}; - -/** - * @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option - * @returns {OptimizationRuntimeChunkNormalized=} normalized runtimeChunk option - */ -const getNormalizedOptimizationRuntimeChunk = runtimeChunk => { - if (runtimeChunk === undefined) return undefined; - if (runtimeChunk === false) return false; - if (runtimeChunk === "single") { - return { - name: () => "runtime" - }; - } - if (runtimeChunk === true || runtimeChunk === "multiple") { - return { - name: entrypoint => `runtime~${entrypoint.name}` - }; + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) + this._hashUpdate = "" + this.identifier + this.range + this.expression; + hash.update(this._hashUpdate); } - const { name } = runtimeChunk; - return { - name: typeof name === "function" ? name : () => name - }; -}; - -exports.getNormalizedWebpackOptions = getNormalizedWebpackOptions; - -/***/ }), + serialize(context) { + const { write } = context; -/***/ 52801: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + write(this.expression); + write(this.range); + write(this.identifier); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + super.serialize(context); + } + deserialize(context) { + const { read } = context; + this.expression = read(); + this.range = read(); + this.identifier = read(); -const memoize = __webpack_require__(78676); + super.deserialize(context); + } +} -const getBrowserslistTargetHandler = memoize(() => - __webpack_require__(43950) +makeSerializable( + CachedConstDependency, + "webpack/lib/dependencies/CachedConstDependency" ); -/** - * @param {string} context the context directory - * @returns {string} default target - */ -const getDefaultTarget = context => { - const browsers = getBrowserslistTargetHandler().load(null, context); - return browsers ? "browserslist" : "web"; -}; - -/** - * @typedef {Object} PlatformTargetProperties - * @property {boolean | null} web web platform, importing of http(s) and std: is available - * @property {boolean | null} browser browser platform, running in a normal web browser - * @property {boolean | null} webworker (Web)Worker platform, running in a web/shared/service worker - * @property {boolean | null} node node platform, require of node built-in modules is available - * @property {boolean | null} nwjs nwjs platform, require of legacy nw.gui is available - * @property {boolean | null} electron electron platform, require of some electron built-in modules is available - */ - -/** - * @typedef {Object} ElectronContextTargetProperties - * @property {boolean | null} electronMain in main context - * @property {boolean | null} electronPreload in preload context - * @property {boolean | null} electronRenderer in renderer context with node integration - */ - -/** - * @typedef {Object} ApiTargetProperties - * @property {boolean | null} require has require function available - * @property {boolean | null} nodeBuiltins has node.js built-in modules available - * @property {boolean | null} document has document available (allows script tags) - * @property {boolean | null} importScripts has importScripts available - * @property {boolean | null} importScriptsInWorker has importScripts available when creating a worker - * @property {boolean | null} fetchWasm has fetch function available for WebAssembly - * @property {boolean | null} global has global variable available - */ - -/** - * @typedef {Object} EcmaTargetProperties - * @property {boolean | null} globalThis has globalThis variable available - * @property {boolean | null} bigIntLiteral big int literal syntax is available - * @property {boolean | null} const const and let variable declarations are available - * @property {boolean | null} arrowFunction arrow functions are available - * @property {boolean | null} forOf for of iteration is available - * @property {boolean | null} destructuring destructuring is available - * @property {boolean | null} dynamicImport async import() is available - * @property {boolean | null} dynamicImportInWorker async import() is available when creating a worker - * @property {boolean | null} module ESM syntax is available (when in module) - * @property {boolean | null} optionalChaining optional chaining is available - * @property {boolean | null} templateLiteral template literal is available - */ - -///** @typedef {PlatformTargetProperties | ApiTargetProperties | EcmaTargetProperties | PlatformTargetProperties & ApiTargetProperties | PlatformTargetProperties & EcmaTargetProperties | ApiTargetProperties & EcmaTargetProperties} TargetProperties */ -/** @template T @typedef {{ [P in keyof T]?: never }} Never */ -/** @template A @template B @typedef {(A & Never) | (Never & B) | (A & B)} Mix */ -/** @typedef {Mix, Mix>} TargetProperties */ - -const versionDependent = (major, minor) => { - if (!major) return () => /** @type {undefined} */ (undefined); - major = +major; - minor = minor ? +minor : 0; - return (vMajor, vMinor = 0) => { - return major > vMajor || (major === vMajor && minor >= vMinor); - }; -}; - -/** @type {[string, string, RegExp, (...args: string[]) => TargetProperties | false][]} */ -const TARGETS = [ - [ - "browserslist / browserslist:env / browserslist:query / browserslist:path-to-config / browserslist:path-to-config:env", - "Resolve features from browserslist. Will resolve browserslist config automatically. Only browser or node queries are supported (electron is not supported). Examples: 'browserslist:modern' to use 'modern' environment from browserslist config", - /^browserslist(?::(.+))?$/, - (rest, context) => { - const browserslistTargetHandler = getBrowserslistTargetHandler(); - const browsers = browserslistTargetHandler.load( - rest ? rest.trim() : null, - context - ); - if (!browsers) { - throw new Error(`No browserslist config found to handle the 'browserslist' target. -See https://github.com/browserslist/browserslist#queries for possible ways to provide a config. -The recommended way is to add a 'browserslist' key to your package.json and list supported browsers (resp. node.js versions). -You can also more options via the 'target' option: 'browserslist' / 'browserslist:env' / 'browserslist:query' / 'browserslist:path-to-config' / 'browserslist:path-to-config:env'`); - } - return browserslistTargetHandler.resolve(browsers); - } - ], - [ - "web", - "Web browser.", - /^web$/, - () => { - return { - web: true, - browser: true, - webworker: null, - node: false, - electron: false, - nwjs: false, - - document: true, - importScriptsInWorker: true, - fetchWasm: true, - nodeBuiltins: false, - importScripts: false, - require: false, - global: false - }; - } - ], - [ - "webworker", - "Web Worker, SharedWorker or Service Worker.", - /^webworker$/, - () => { - return { - web: true, - browser: true, - webworker: true, - node: false, - electron: false, - nwjs: false, - - importScripts: true, - importScriptsInWorker: true, - fetchWasm: true, - nodeBuiltins: false, - require: false, - document: false, - global: false - }; - } - ], - [ - "[async-]node[X[.Y]]", - "Node.js in version X.Y. The 'async-' prefix will load chunks asynchronously via 'fs' and 'vm' instead of 'require()'. Examples: node14.5, async-node10.", - /^(async-)?node(\d+(?:\.(\d+))?)?$/, - (asyncFlag, major, minor) => { - const v = versionDependent(major, minor); - // see https://node.green/ - return { - node: true, - electron: false, - nwjs: false, - web: false, - webworker: false, - browser: false, - - require: !asyncFlag, - nodeBuiltins: true, - global: true, - document: false, - fetchWasm: false, - importScripts: false, - importScriptsInWorker: false, - - globalThis: v(12), - const: v(6), - templateLiteral: v(4), - optionalChaining: v(14), - arrowFunction: v(6), - forOf: v(5), - destructuring: v(6), - bigIntLiteral: v(10, 4), - dynamicImport: v(12, 17), - dynamicImportInWorker: major ? false : undefined, - module: v(12, 17) - }; - } - ], - [ - "electron[X[.Y]]-main/preload/renderer", - "Electron in version X.Y. Script is running in main, preload resp. renderer context.", - /^electron(\d+(?:\.(\d+))?)?-(main|preload|renderer)$/, - (major, minor, context) => { - const v = versionDependent(major, minor); - // see https://node.green/ + https://github.com/electron/releases - return { - node: true, - electron: true, - web: context !== "main", - webworker: false, - browser: false, - nwjs: false, - - electronMain: context === "main", - electronPreload: context === "preload", - electronRenderer: context === "renderer", - - global: true, - nodeBuiltins: true, - require: true, - document: context === "renderer", - fetchWasm: context === "renderer", - importScripts: false, - importScriptsInWorker: true, - - globalThis: v(5), - const: v(1, 1), - templateLiteral: v(1, 1), - optionalChaining: v(8), - arrowFunction: v(1, 1), - forOf: v(0, 36), - destructuring: v(1, 1), - bigIntLiteral: v(4), - dynamicImport: v(11), - dynamicImportInWorker: major ? false : undefined, - module: v(11) - }; - } - ], - [ - "nwjs[X[.Y]] / node-webkit[X[.Y]]", - "NW.js in version X.Y.", - /^(?:nwjs|node-webkit)(\d+(?:\.(\d+))?)?$/, - (major, minor) => { - const v = versionDependent(major, minor); - // see https://node.green/ + https://github.com/nwjs/nw.js/blob/nw48/CHANGELOG.md - return { - node: true, - web: true, - nwjs: true, - webworker: null, - browser: false, - electron: false, +CachedConstDependency.Template = class CachedConstDependencyTemplate extends ( + DependencyTemplate +) { + /** + * @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, + { runtimeTemplate, dependencyTemplates, initFragments } + ) { + const dep = /** @type {CachedConstDependency} */ (dependency); - global: true, - nodeBuiltins: true, - document: false, - importScriptsInWorker: false, - fetchWasm: false, - importScripts: false, - require: false, + initFragments.push( + new InitFragment( + `var ${dep.identifier} = ${dep.expression};\n`, + InitFragment.STAGE_CONSTANTS, + 0, + `const ${dep.identifier}` + ) + ); - globalThis: v(0, 43), - const: v(0, 15), - templateLiteral: v(0, 13), - optionalChaining: v(0, 44), - arrowFunction: v(0, 15), - forOf: v(0, 13), - destructuring: v(0, 15), - bigIntLiteral: v(0, 32), - dynamicImport: v(0, 43), - dynamicImportInWorker: major ? false : undefined, - module: v(0, 43) - }; - } - ], - [ - "esX", - "EcmaScript in this version. Examples: es2020, es5.", - /^es(\d+)$/, - version => { - let v = +version; - if (v < 1000) v = v + 2009; - return { - const: v >= 2015, - templateLiteral: v >= 2015, - optionalChaining: v >= 2020, - arrowFunction: v >= 2015, - forOf: v >= 2015, - destructuring: v >= 2015, - module: v >= 2015, - globalThis: v >= 2020, - bigIntLiteral: v >= 2020, - dynamicImport: v >= 2020, - dynamicImportInWorker: v >= 2020 - }; - } - ] -]; + if (typeof dep.range === "number") { + source.insert(dep.range, dep.identifier); -/** - * @param {string} target the target - * @param {string} context the context directory - * @returns {TargetProperties} target properties - */ -const getTargetProperties = (target, context) => { - for (const [, , regExp, handler] of TARGETS) { - const match = regExp.exec(target); - if (match) { - const [, ...args] = match; - const result = handler(...args, context); - if (result) return result; + return; } - } - throw new Error( - `Unknown target '${target}'. The following targets are supported:\n${TARGETS.map( - ([name, description]) => `* ${name}: ${description}` - ).join("\n")}` - ); -}; -const mergeTargetProperties = targetProperties => { - const keys = new Set(); - for (const tp of targetProperties) { - for (const key of Object.keys(tp)) { - keys.add(key); - } - } - const result = {}; - for (const key of keys) { - let hasTrue = false; - let hasFalse = false; - for (const tp of targetProperties) { - const value = tp[key]; - switch (value) { - case true: - hasTrue = true; - break; - case false: - hasFalse = true; - break; - } - } - if (hasTrue || hasFalse) - result[key] = hasFalse && hasTrue ? null : hasTrue ? true : false; + source.replace(dep.range[0], dep.range[1] - 1, dep.identifier); } - return /** @type {TargetProperties} */ (result); -}; - -/** - * @param {string[]} targets the targets - * @param {string} context the context directory - * @returns {TargetProperties} target properties - */ -const getTargetsProperties = (targets, context) => { - return mergeTargetProperties( - targets.map(t => getTargetProperties(t, context)) - ); }; -exports.getDefaultTarget = getDefaultTarget; -exports.getTargetProperties = getTargetProperties; -exports.getTargetsProperties = getTargetsProperties; +module.exports = CachedConstDependency; /***/ }), -/***/ 64813: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 59643: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr + Author Tobias Koppers @sokra */ -const Dependency = __webpack_require__(54912); -const makeSerializable = __webpack_require__(33032); - -/** @typedef {import("./ContainerEntryModule").ExposeOptions} ExposeOptions */ - -class ContainerEntryDependency extends Dependency { - /** - * @param {string} name entry name - * @param {[string, ExposeOptions][]} exposes list of exposed modules - * @param {string} shareScope name of the share scope - */ - constructor(name, exposes, shareScope) { - super(); - this.name = name; - this.exposes = exposes; - this.shareScope = shareScope; - } - - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - return `container-entry-${this.name}`; - } - - get type() { - return "container entry"; - } +const RuntimeGlobals = __webpack_require__(16475); - get category() { - return "esm"; +exports.handleDependencyBase = (depBase, module, runtimeRequirements) => { + let base = undefined; + let type; + switch (depBase) { + case "exports": + runtimeRequirements.add(RuntimeGlobals.exports); + base = module.exportsArgument; + type = "expression"; + break; + case "module.exports": + runtimeRequirements.add(RuntimeGlobals.module); + base = `${module.moduleArgument}.exports`; + type = "expression"; + break; + case "this": + runtimeRequirements.add(RuntimeGlobals.thisAsExports); + base = "this"; + type = "expression"; + break; + case "Object.defineProperty(exports)": + runtimeRequirements.add(RuntimeGlobals.exports); + base = module.exportsArgument; + type = "Object.defineProperty"; + break; + case "Object.defineProperty(module.exports)": + runtimeRequirements.add(RuntimeGlobals.module); + base = `${module.moduleArgument}.exports`; + type = "Object.defineProperty"; + break; + case "Object.defineProperty(this)": + runtimeRequirements.add(RuntimeGlobals.thisAsExports); + base = "this"; + type = "Object.defineProperty"; + break; + default: + throw new Error(`Unsupported base ${depBase}`); } -} - -makeSerializable( - ContainerEntryDependency, - "webpack/lib/container/ContainerEntryDependency" -); -module.exports = ContainerEntryDependency; + return [type, base]; +}; /***/ }), -/***/ 80580: +/***/ 62892: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr + Author Tobias Koppers @sokra */ -const { OriginalSource, RawSource } = __webpack_require__(51255); -const AsyncDependenciesBlock = __webpack_require__(47736); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const StaticExportsDependency = __webpack_require__(91418); +const Dependency = __webpack_require__(54912); +const { UsageState } = __webpack_require__(63686); +const Template = __webpack_require__(1626); +const { equals } = __webpack_require__(84953); const makeSerializable = __webpack_require__(33032); -const ContainerExposedDependency = __webpack_require__(72374); - -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */ +const propertyAccess = __webpack_require__(54190); +const { handleDependencyBase } = __webpack_require__(59643); +const ModuleDependency = __webpack_require__(80321); +const processExportInfo = __webpack_require__(55207); -/** - * @typedef {Object} ExposeOptions - * @property {string[]} import requests to exposed modules (last one is exported) - * @property {string} name custom chunk name for the exposed module - */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -const SOURCE_TYPES = new Set(["javascript"]); +const idsSymbol = Symbol("CommonJsExportRequireDependency.ids"); -class ContainerEntryModule extends Module { - /** - * @param {string} name container entry name - * @param {[string, ExposeOptions][]} exposes list of exposed modules - * @param {string} shareScope name of the share scope - */ - constructor(name, exposes, shareScope) { - super("javascript/dynamic", null); - this._name = name; - this._exposes = exposes; - this._shareScope = shareScope; - } +const EMPTY_OBJECT = {}; - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return SOURCE_TYPES; +class CommonJsExportRequireDependency extends ModuleDependency { + constructor(range, valueRange, base, names, request, ids, resultUsed) { + super(request); + this.range = range; + this.valueRange = valueRange; + this.base = base; + this.names = names; + this.ids = ids; + this.resultUsed = resultUsed; + this.asiSafe = undefined; } - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return `container entry (${this._shareScope}) ${JSON.stringify( - this._exposes - )}`; + get type() { + return "cjs export require"; } /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module */ - readableIdentifier(requestShortener) { - return `container entry`; + couldAffectReferencingModule() { + return Dependency.TRANSITIVE; } /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @param {ModuleGraph} moduleGraph the module graph + * @returns {string[]} the imported id */ - libIdent(options) { - return `${this.layer ? `(${this.layer})/` : ""}webpack/container/entry/${ - this._name - }`; + getIds(moduleGraph) { + return moduleGraph.getMeta(this)[idsSymbol] || this.ids; } /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @param {ModuleGraph} moduleGraph the module graph + * @param {string[]} ids the imported ids * @returns {void} */ - needBuild(context, callback) { - return callback(null, !this.buildMeta); + setIds(moduleGraph, ids) { + moduleGraph.getMeta(this)[idsSymbol] = ids; } /** - * @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} + * 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 */ - build(options, compilation, resolver, fs, callback) { - this.buildMeta = {}; - this.buildInfo = { - strict: true, - topLevelDeclarations: new Set(["moduleMap", "get", "init"]) + getReferencedExports(moduleGraph, runtime) { + const ids = this.getIds(moduleGraph); + const getFullResult = () => { + if (ids.length === 0) { + return Dependency.EXPORTS_OBJECT_REFERENCED; + } else { + return [ + { + name: ids, + canMangle: false + } + ]; + } }; - this.buildMeta.exportsType = "namespace"; - - this.clearDependenciesAndBlocks(); - - for (const [name, options] of this._exposes) { - const block = new AsyncDependenciesBlock( - { - name: options.name - }, - { name }, - options.import[options.import.length - 1] + if (this.resultUsed) return getFullResult(); + let exportsInfo = moduleGraph.getExportsInfo( + moduleGraph.getParentModule(this) + ); + for (const name of this.names) { + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + const used = exportInfo.getUsed(runtime); + if (used === UsageState.Unused) return Dependency.NO_EXPORTS_REFERENCED; + if (used !== UsageState.OnlyPropertiesUsed) return getFullResult(); + exportsInfo = exportInfo.exportsInfo; + if (!exportsInfo) return getFullResult(); + } + if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { + return getFullResult(); + } + /** @type {string[][]} */ + const referencedExports = []; + for (const exportInfo of exportsInfo.orderedExports) { + processExportInfo( + runtime, + referencedExports, + ids.concat(exportInfo.name), + exportInfo, + false ); - let idx = 0; - for (const request of options.import) { - const dep = new ContainerExposedDependency(name, request); - dep.loc = { - name, - index: idx++ - }; - - block.addDependency(dep); - } - this.addBlock(block); } - this.addDependency(new StaticExportsDependency(["get", "init"], false)); - - callback(); + return referencedExports.map(name => ({ + name, + canMangle: false + })); } /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names */ - codeGeneration({ moduleGraph, chunkGraph, runtimeTemplate }) { - const sources = new Map(); - const runtimeRequirements = new Set([ - RuntimeGlobals.definePropertyGetters, - RuntimeGlobals.hasOwnProperty, - RuntimeGlobals.exports - ]); - const getters = []; - - for (const block of this.blocks) { - const { dependencies } = block; - - const modules = dependencies.map(dependency => { - const dep = /** @type {ContainerExposedDependency} */ (dependency); + getExports(moduleGraph) { + const ids = this.getIds(moduleGraph); + if (this.names.length === 1) { + const name = this.names[0]; + const from = moduleGraph.getConnection(this); + if (!from) return; + return { + exports: [ + { + name, + from, + export: ids.length === 0 ? null : ids, + // we can't mangle names that are in an empty object + // because one could access the prototype property + // when export isn't set yet + canMangle: !(name in EMPTY_OBJECT) && false + } + ], + dependencies: [from.module] + }; + } else if (this.names.length > 0) { + const name = this.names[0]; + return { + exports: [ + { + name, + // we can't mangle names that are in an empty object + // because one could access the prototype property + // when export isn't set yet + canMangle: !(name in EMPTY_OBJECT) && false + } + ], + dependencies: undefined + }; + } else { + const from = moduleGraph.getConnection(this); + if (!from) return; + const reexportInfo = this.getStarReexports( + moduleGraph, + undefined, + from.module + ); + if (reexportInfo) { return { - name: dep.exposedName, - module: moduleGraph.getModule(dep), - request: dep.userRequest + exports: Array.from(reexportInfo.exports, name => { + return { + name, + from, + export: ids.concat(name), + canMangle: !(name in EMPTY_OBJECT) && false + }; + }), + // TODO handle deep reexports + dependencies: [from.module] }; - }); - - let str; - - if (modules.some(m => !m.module)) { - str = runtimeTemplate.throwMissingModuleErrorBlock({ - request: modules.map(m => m.request).join(", ") - }); } else { - str = `return ${runtimeTemplate.blockPromise({ - block, - message: "", - chunkGraph, - runtimeRequirements - })}.then(${runtimeTemplate.returningFunction( - runtimeTemplate.returningFunction( - `(${modules - .map(({ module, request }) => - runtimeTemplate.moduleRaw({ - module, - chunkGraph, - request, - weak: false, - runtimeRequirements - }) - ) - .join(", ")})` - ) - )});`; + return { + exports: true, + from: ids.length === 0 ? from : undefined, + canMangle: false, + dependencies: [from.module] + }; } + } + } - getters.push( - `${JSON.stringify(modules[0].name)}: ${runtimeTemplate.basicFunction( - "", - str - )}` - ); + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @param {Module} importedModule the imported module (optional) + * @returns {{exports?: Set, checked?: Set}} information + */ + getStarReexports( + moduleGraph, + runtime, + importedModule = moduleGraph.getModule(this) + ) { + let importedExportsInfo = moduleGraph.getExportsInfo(importedModule); + const ids = this.getIds(moduleGraph); + if (ids.length > 0) + importedExportsInfo = importedExportsInfo.getNestedExportsInfo(ids); + let exportsInfo = moduleGraph.getExportsInfo( + moduleGraph.getParentModule(this) + ); + if (this.names.length > 0) + exportsInfo = exportsInfo.getNestedExportsInfo(this.names); + + const noExtraExports = + importedExportsInfo && + importedExportsInfo.otherExportsInfo.provided === false; + const noExtraImports = + exportsInfo && + exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused; + + if (!noExtraExports && !noExtraImports) { + return; } - const source = Template.asString([ - `var moduleMap = {`, - Template.indent(getters.join(",\n")), - "};", - `var get = ${runtimeTemplate.basicFunction("module, getScope", [ - `${RuntimeGlobals.currentRemoteGetScope} = getScope;`, - // reusing the getScope variable to avoid creating a new var (and module is also used later) - "getScope = (", - Template.indent([ - `${RuntimeGlobals.hasOwnProperty}(moduleMap, module)`, - Template.indent([ - "? moduleMap[module]()", - `: Promise.resolve().then(${runtimeTemplate.basicFunction( - "", - "throw new Error('Module \"' + module + '\" does not exist in container.');" - )})` - ]) - ]), - ");", - `${RuntimeGlobals.currentRemoteGetScope} = undefined;`, - "return getScope;" - ])};`, - `var init = ${runtimeTemplate.basicFunction("shareScope, initScope", [ - `if (!${RuntimeGlobals.shareScopeMap}) return;`, - `var name = ${JSON.stringify(this._shareScope)}`, - `var oldScope = ${RuntimeGlobals.shareScopeMap}[name];`, - `if(oldScope && oldScope !== shareScope) throw new Error("Container initialization failed as it has already been initialized with a different share scope");`, - `${RuntimeGlobals.shareScopeMap}[name] = shareScope;`, - `return ${RuntimeGlobals.initializeSharing}(name, initScope);` - ])};`, - "", - "// This exports getters to disallow modifications", - `${RuntimeGlobals.definePropertyGetters}(exports, {`, - Template.indent([ - `get: ${runtimeTemplate.returningFunction("get")},`, - `init: ${runtimeTemplate.returningFunction("init")}` - ]), - "});" - ]); + const isNamespaceImport = + importedModule.getExportsType(moduleGraph, false) === "namespace"; - sources.set( - "javascript", - this.useSourceMap || this.useSimpleSourceMap - ? new OriginalSource(source, "webpack/container-entry") - : new RawSource(source) - ); + /** @type {Set} */ + const exports = new Set(); + /** @type {Set} */ + const checked = new Set(); - return { - sources, - runtimeRequirements - }; - } + if (noExtraImports) { + for (const exportInfo of exportsInfo.orderedExports) { + const name = exportInfo.name; + if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; + if (name === "__esModule" && isNamespaceImport) { + exports.add(name); + } else if (importedExportsInfo) { + const importedExportInfo = + importedExportsInfo.getReadOnlyExportInfo(name); + if (importedExportInfo.provided === false) continue; + exports.add(name); + if (importedExportInfo.provided === true) continue; + checked.add(name); + } else { + exports.add(name); + checked.add(name); + } + } + } else if (noExtraExports) { + for (const importedExportInfo of importedExportsInfo.orderedExports) { + const name = importedExportInfo.name; + if (importedExportInfo.provided === false) continue; + if (exportsInfo) { + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; + } + exports.add(name); + if (importedExportInfo.provided === true) continue; + checked.add(name); + } + if (isNamespaceImport) { + exports.add("__esModule"); + checked.delete("__esModule"); + } + } - /** - * @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; + return { exports, checked }; } serialize(context) { const { write } = context; - write(this._name); - write(this._exposes); - write(this._shareScope); + write(this.asiSafe); + write(this.range); + write(this.valueRange); + write(this.base); + write(this.names); + write(this.ids); + write(this.resultUsed); super.serialize(context); } - static deserialize(context) { + deserialize(context) { const { read } = context; - const obj = new ContainerEntryModule(read(), read(), read()); - obj.deserialize(context); - return obj; + this.asiSafe = read(); + this.range = read(); + this.valueRange = read(); + this.base = read(); + this.names = read(); + this.ids = read(); + this.resultUsed = read(); + super.deserialize(context); } } makeSerializable( - ContainerEntryModule, - "webpack/lib/container/ContainerEntryModule" + CommonJsExportRequireDependency, + "webpack/lib/dependencies/CommonJsExportRequireDependency" ); -module.exports = ContainerEntryModule; - - -/***/ }), - -/***/ 76398: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr -*/ - - - -const ModuleFactory = __webpack_require__(51010); -const ContainerEntryModule = __webpack_require__(80580); - -/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */ - -module.exports = class ContainerEntryModuleFactory extends ModuleFactory { +CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependencyTemplate extends ( + ModuleDependency.Template +) { /** - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * @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} */ - create({ dependencies: [dependency] }, callback) { - const dep = /** @type {ContainerEntryDependency} */ (dependency); - callback(null, { - module: new ContainerEntryModule(dep.name, dep.exposes, dep.shareScope) + apply( + dependency, + source, + { + module, + runtimeTemplate, + chunkGraph, + moduleGraph, + runtimeRequirements, + runtime + } + ) { + const dep = /** @type {CommonJsExportRequireDependency} */ (dependency); + const used = moduleGraph + .getExportsInfo(module) + .getUsedName(dep.names, runtime); + + const [type, base] = handleDependencyBase( + dep.base, + module, + runtimeRequirements + ); + + const importedModule = moduleGraph.getModule(dep); + let requireExpr = runtimeTemplate.moduleExports({ + module: importedModule, + chunkGraph, + request: dep.request, + weak: dep.weak, + runtimeRequirements }); + if (importedModule) { + const ids = dep.getIds(moduleGraph); + const usedImported = moduleGraph + .getExportsInfo(importedModule) + .getUsedName(ids, runtime); + if (usedImported) { + const comment = equals(usedImported, ids) + ? "" + : Template.toNormalComment(propertyAccess(ids)) + " "; + requireExpr += `${comment}${propertyAccess(usedImported)}`; + } + } + + switch (type) { + case "expression": + source.replace( + dep.range[0], + dep.range[1] - 1, + used + ? `${base}${propertyAccess(used)} = ${requireExpr}` + : `/* unused reexport */ ${requireExpr}` + ); + return; + case "Object.defineProperty": + throw new Error("TODO"); + default: + throw new Error("Unexpected type"); + } } }; +module.exports = CommonJsExportRequireDependency; + /***/ }), -/***/ 72374: +/***/ 45598: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr + Author Tobias Koppers @sokra */ -const ModuleDependency = __webpack_require__(80321); +const InitFragment = __webpack_require__(55870); const makeSerializable = __webpack_require__(33032); +const propertyAccess = __webpack_require__(54190); +const { handleDependencyBase } = __webpack_require__(59643); +const NullDependency = __webpack_require__(31830); -class ContainerExposedDependency extends ModuleDependency { - /** - * @param {string} exposedName public name - * @param {string} request request to module - */ - constructor(exposedName, request) { - super(request); - this.exposedName = exposedName; - } +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ - get type() { - return "container exposed"; +const EMPTY_OBJECT = {}; + +class CommonJsExportsDependency extends NullDependency { + constructor(range, valueRange, base, names) { + super(); + this.range = range; + this.valueRange = valueRange; + this.base = base; + this.names = names; } - get category() { - return "esm"; + get type() { + return "cjs exports"; } /** - * @returns {string | null} an identifier to merge equal requests + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names */ - getResourceIdentifier() { - return `exposed dependency ${this.exposedName}=${this.request}`; + getExports(moduleGraph) { + const name = this.names[0]; + return { + exports: [ + { + name, + // we can't mangle names that are in an empty object + // because one could access the prototype property + // when export isn't set yet + canMangle: !(name in EMPTY_OBJECT) + } + ], + dependencies: undefined + }; } serialize(context) { - context.write(this.exposedName); + const { write } = context; + write(this.range); + write(this.valueRange); + write(this.base); + write(this.names); super.serialize(context); } deserialize(context) { - this.exposedName = context.read(); + const { read } = context; + this.range = read(); + this.valueRange = read(); + this.base = read(); + this.names = read(); super.deserialize(context); } } makeSerializable( - ContainerExposedDependency, - "webpack/lib/container/ContainerExposedDependency" + CommonJsExportsDependency, + "webpack/lib/dependencies/CommonJsExportsDependency" ); -module.exports = ContainerExposedDependency; +CommonJsExportsDependency.Template = class CommonJsExportsDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, + { module, moduleGraph, initFragments, runtimeRequirements, runtime } + ) { + const dep = /** @type {CommonJsExportsDependency} */ (dependency); + const used = moduleGraph + .getExportsInfo(module) + .getUsedName(dep.names, runtime); + + const [type, base] = handleDependencyBase( + dep.base, + module, + runtimeRequirements + ); + + switch (type) { + case "expression": + if (!used) { + initFragments.push( + new InitFragment( + "var __webpack_unused_export__;\n", + InitFragment.STAGE_CONSTANTS, + 0, + "__webpack_unused_export__" + ) + ); + source.replace( + dep.range[0], + dep.range[1] - 1, + "__webpack_unused_export__" + ); + return; + } + source.replace( + dep.range[0], + dep.range[1] - 1, + `${base}${propertyAccess(used)}` + ); + return; + case "Object.defineProperty": + if (!used) { + initFragments.push( + new InitFragment( + "var __webpack_unused_export__;\n", + InitFragment.STAGE_CONSTANTS, + 0, + "__webpack_unused_export__" + ) + ); + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + "__webpack_unused_export__ = (" + ); + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + return; + } + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `Object.defineProperty(${base}${propertyAccess( + used.slice(0, -1) + )}, ${JSON.stringify(used[used.length - 1])}, (` + ); + source.replace(dep.valueRange[1], dep.range[1] - 1, "))"); + return; + } + } +}; + +module.exports = CommonJsExportsDependency; /***/ }), -/***/ 9244: +/***/ 97107: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr + Author Tobias Koppers @sokra */ -const createSchemaValidation = __webpack_require__(32540); -const ContainerEntryDependency = __webpack_require__(64813); -const ContainerEntryModuleFactory = __webpack_require__(76398); -const ContainerExposedDependency = __webpack_require__(72374); -const { parseOptions } = __webpack_require__(3083); +const RuntimeGlobals = __webpack_require__(16475); +const formatLocation = __webpack_require__(16734); +const { evaluateToString } = __webpack_require__(93998); +const propertyAccess = __webpack_require__(54190); +const CommonJsExportRequireDependency = __webpack_require__(62892); +const CommonJsExportsDependency = __webpack_require__(45598); +const CommonJsSelfReferenceDependency = __webpack_require__(52225); +const DynamicExports = __webpack_require__(32006); +const HarmonyExports = __webpack_require__(39211); +const ModuleDecoratorDependency = __webpack_require__(88488); -/** @typedef {import("../../declarations/plugins/container/ContainerPlugin").ContainerPluginOptions} ContainerPluginOptions */ -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("estree").Expression} ExpressionNode */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ -const validate = createSchemaValidation( - __webpack_require__(9504), - () => __webpack_require__(84899), - { - name: "Container Plugin", - baseDataPath: "options" +const getValueOfPropertyDescription = expr => { + if (expr.type !== "ObjectExpression") return; + for (const property of expr.properties) { + if (property.computed) continue; + const key = property.key; + if (key.type !== "Identifier" || key.name !== "value") continue; + return property.value; } -); +}; -const PLUGIN_NAME = "ContainerPlugin"; +const isTruthyLiteral = expr => { + switch (expr.type) { + case "Literal": + return !!expr.value; + case "UnaryExpression": + if (expr.operator === "!") return isFalsyLiteral(expr.argument); + } + return false; +}; -class ContainerPlugin { - /** - * @param {ContainerPluginOptions} options options - */ - constructor(options) { - validate(options); +const isFalsyLiteral = expr => { + switch (expr.type) { + case "Literal": + return !expr.value; + case "UnaryExpression": + if (expr.operator === "!") return isTruthyLiteral(expr.argument); + } + return false; +}; - this._options = { - name: options.name, - shareScope: options.shareScope || "default", - library: options.library || { - type: "var", - name: options.name - }, - runtime: options.runtime, - filename: options.filename || undefined, - exposes: parseOptions( - options.exposes, - item => ({ - import: Array.isArray(item) ? item : [item], - name: undefined - }), - item => ({ - import: Array.isArray(item.import) ? item.import : [item.import], - name: item.name || undefined - }) - ) - }; +/** + * @param {JavascriptParser} parser the parser + * @param {ExpressionNode} expr expression + * @returns {{ argument: BasicEvaluatedExpression, ids: string[] } | undefined} parsed call + */ +const parseRequireCall = (parser, expr) => { + const ids = []; + while (expr.type === "MemberExpression") { + if (expr.object.type === "Super") return; + if (!expr.property) return; + const prop = expr.property; + if (expr.computed) { + if (prop.type !== "Literal") return; + ids.push(`${prop.value}`); + } else { + if (prop.type !== "Identifier") return; + ids.push(prop.name); + } + expr = expr.object; + } + if (expr.type !== "CallExpression" || expr.arguments.length !== 1) return; + const callee = expr.callee; + if ( + callee.type !== "Identifier" || + parser.getVariableInfo(callee.name) !== "require" + ) { + return; + } + const arg = expr.arguments[0]; + if (arg.type === "SpreadElement") return; + const argValue = parser.evaluateExpression(arg); + return { argument: argValue, ids: ids.reverse() }; +}; + +class CommonJsExportsParserPlugin { + constructor(moduleGraph) { + this.moduleGraph = moduleGraph; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {JavascriptParser} parser the parser */ - apply(compiler) { - const { name, exposes, shareScope, filename, library, runtime } = - this._options; + apply(parser) { + const enableStructuredExports = () => { + DynamicExports.enable(parser.state); + }; + const checkNamespace = (topLevel, members, valueExpr) => { + if (!DynamicExports.isEnabled(parser.state)) return; + if (members.length > 0 && members[0] === "__esModule") { + if (valueExpr && isTruthyLiteral(valueExpr) && topLevel) { + DynamicExports.setFlagged(parser.state); + } else { + DynamicExports.setDynamic(parser.state); + } + } + }; + const bailout = reason => { + DynamicExports.bailout(parser.state); + if (reason) bailoutHint(reason); + }; + const bailoutHint = reason => { + this.moduleGraph + .getOptimizationBailout(parser.state.module) + .push(`CommonJS bailout: ${reason}`); + }; - compiler.options.output.enabledLibraryTypes.push(library.type); + // metadata // + parser.hooks.evaluateTypeof + .for("module") + .tap("CommonJsExportsParserPlugin", evaluateToString("object")); + parser.hooks.evaluateTypeof + .for("exports") + .tap("CommonJsPlugin", evaluateToString("object")); - compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => { - const dep = new ContainerEntryDependency(name, exposes, shareScope); - dep.loc = { name }; - compilation.addEntry( - compilation.options.context, - dep, - { - name, - filename, - runtime, - library - }, - error => { - if (error) return callback(error); - callback(); - } + // exporting // + const handleAssignExport = (expr, base, members) => { + if (HarmonyExports.isEnabled(parser.state)) return; + // Handle reexporting + const requireCall = parseRequireCall(parser, expr.right); + if ( + requireCall && + requireCall.argument.isString() && + (members.length === 0 || members[0] !== "__esModule") + ) { + enableStructuredExports(); + // It's possible to reexport __esModule, so we must convert to a dynamic module + if (members.length === 0) DynamicExports.setDynamic(parser.state); + const dep = new CommonJsExportRequireDependency( + expr.range, + null, + base, + members, + requireCall.argument.string, + requireCall.ids, + !parser.isStatementLevelExpression(expr) + ); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.module.addDependency(dep); + return true; + } + if (members.length === 0) return; + enableStructuredExports(); + const remainingMembers = members; + checkNamespace( + parser.statementPath.length === 1 && + parser.isStatementLevelExpression(expr), + remainingMembers, + expr.right ); - }); - - compiler.hooks.thisCompilation.tap( - PLUGIN_NAME, - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - ContainerEntryDependency, - new ContainerEntryModuleFactory() + const dep = new CommonJsExportsDependency( + expr.left.range, + null, + base, + remainingMembers + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + parser.walkExpression(expr.right); + return true; + }; + parser.hooks.assignMemberChain + .for("exports") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + return handleAssignExport(expr, "exports", members); + }); + parser.hooks.assignMemberChain + .for("this") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + if (!parser.scope.topLevelScope) return; + return handleAssignExport(expr, "this", members); + }); + parser.hooks.assignMemberChain + .for("module") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + if (members[0] !== "exports") return; + return handleAssignExport(expr, "module.exports", members.slice(1)); + }); + parser.hooks.call + .for("Object.defineProperty") + .tap("CommonJsExportsParserPlugin", expression => { + const expr = /** @type {import("estree").CallExpression} */ ( + expression + ); + if (!parser.isStatementLevelExpression(expr)) return; + if (expr.arguments.length !== 3) return; + if (expr.arguments[0].type === "SpreadElement") return; + if (expr.arguments[1].type === "SpreadElement") return; + if (expr.arguments[2].type === "SpreadElement") return; + const exportsArg = parser.evaluateExpression(expr.arguments[0]); + if (!exportsArg || !exportsArg.isIdentifier()) return; + if ( + exportsArg.identifier !== "exports" && + exportsArg.identifier !== "module.exports" && + (exportsArg.identifier !== "this" || !parser.scope.topLevelScope) + ) { + return; + } + const propertyArg = parser.evaluateExpression(expr.arguments[1]); + if (!propertyArg) return; + const property = propertyArg.asString(); + if (typeof property !== "string") return; + enableStructuredExports(); + const descArg = expr.arguments[2]; + checkNamespace( + parser.statementPath.length === 1, + [property], + getValueOfPropertyDescription(descArg) + ); + const dep = new CommonJsExportsDependency( + expr.range, + expr.arguments[2].range, + `Object.defineProperty(${exportsArg.identifier})`, + [property] ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); - compilation.dependencyFactories.set( - ContainerExposedDependency, - normalModuleFactory + parser.walkExpression(expr.arguments[2]); + return true; + }); + + // Self reference // + const handleAccessExport = (expr, base, members, call = undefined) => { + if (HarmonyExports.isEnabled(parser.state)) return; + if (members.length === 0) { + bailout(`${base} is used directly at ${formatLocation(expr.loc)}`); + } + if (call && members.length === 1) { + bailoutHint( + `${base}${propertyAccess( + members + )}(...) prevents optimization as ${base} is passed as call context at ${formatLocation( + expr.loc + )}` ); } - ); + const dep = new CommonJsSelfReferenceDependency( + expr.range, + base, + members, + !!call + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + if (call) { + parser.walkExpressions(call.arguments); + } + return true; + }; + parser.hooks.callMemberChain + .for("exports") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + return handleAccessExport(expr.callee, "exports", members, expr); + }); + parser.hooks.expressionMemberChain + .for("exports") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + return handleAccessExport(expr, "exports", members); + }); + parser.hooks.expression + .for("exports") + .tap("CommonJsExportsParserPlugin", expr => { + return handleAccessExport(expr, "exports", []); + }); + parser.hooks.callMemberChain + .for("module") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + if (members[0] !== "exports") return; + return handleAccessExport( + expr.callee, + "module.exports", + members.slice(1), + expr + ); + }); + parser.hooks.expressionMemberChain + .for("module") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + if (members[0] !== "exports") return; + return handleAccessExport(expr, "module.exports", members.slice(1)); + }); + parser.hooks.expression + .for("module.exports") + .tap("CommonJsExportsParserPlugin", expr => { + return handleAccessExport(expr, "module.exports", []); + }); + parser.hooks.callMemberChain + .for("this") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + if (!parser.scope.topLevelScope) return; + return handleAccessExport(expr.callee, "this", members, expr); + }); + parser.hooks.expressionMemberChain + .for("this") + .tap("CommonJsExportsParserPlugin", (expr, members) => { + if (!parser.scope.topLevelScope) return; + return handleAccessExport(expr, "this", members); + }); + parser.hooks.expression + .for("this") + .tap("CommonJsExportsParserPlugin", expr => { + if (!parser.scope.topLevelScope) return; + return handleAccessExport(expr, "this", []); + }); + + // Bailouts // + parser.hooks.expression.for("module").tap("CommonJsPlugin", expr => { + bailout(); + const isHarmony = HarmonyExports.isEnabled(parser.state); + const dep = new ModuleDecoratorDependency( + isHarmony + ? RuntimeGlobals.harmonyModuleDecorator + : RuntimeGlobals.nodeModuleDecorator, + !isHarmony + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return true; + }); } } - -module.exports = ContainerPlugin; +module.exports = CommonJsExportsParserPlugin; /***/ }), -/***/ 95757: +/***/ 59440: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy + Author Tobias Koppers @sokra */ -const ExternalsPlugin = __webpack_require__(6652); -const RuntimeGlobals = __webpack_require__(16475); -const createSchemaValidation = __webpack_require__(32540); -const FallbackDependency = __webpack_require__(57764); -const FallbackItemDependency = __webpack_require__(29593); -const FallbackModuleFactory = __webpack_require__(4112); -const RemoteModule = __webpack_require__(62916); -const RemoteRuntimeModule = __webpack_require__(88288); -const RemoteToExternalDependency = __webpack_require__(14389); -const { parseOptions } = __webpack_require__(3083); - -/** @typedef {import("../../declarations/plugins/container/ContainerReferencePlugin").ContainerReferencePluginOptions} ContainerReferencePluginOptions */ -/** @typedef {import("../../declarations/plugins/container/ContainerReferencePlugin").RemotesConfig} RemotesConfig */ -/** @typedef {import("../Compiler")} Compiler */ - -const validate = createSchemaValidation( - __webpack_require__(95122), - () => - __webpack_require__(66681), - { - name: "Container Reference Plugin", - baseDataPath: "options" - } -); +const Template = __webpack_require__(1626); +const { equals } = __webpack_require__(84953); +const makeSerializable = __webpack_require__(33032); +const propertyAccess = __webpack_require__(54190); +const ModuleDependency = __webpack_require__(80321); -const slashCode = "/".charCodeAt(0); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -class ContainerReferencePlugin { +class CommonJsFullRequireDependency extends ModuleDependency { /** - * @param {ContainerReferencePluginOptions} options options + * @param {string} request the request string + * @param {[number, number]} range location in source code + * @param {string[]} names accessed properties on module */ - constructor(options) { - validate(options); - - this._remoteType = options.remoteType; - this._remotes = parseOptions( - options.remotes, - item => ({ - external: Array.isArray(item) ? item : [item], - shareScope: options.shareScope || "default" - }), - item => ({ - external: Array.isArray(item.external) - ? item.external - : [item.external], - shareScope: item.shareScope || options.shareScope || "default" - }) - ); + constructor(request, range, names) { + super(request); + this.range = range; + this.names = names; + this.call = false; + this.asiSafe = undefined; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * 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 */ - apply(compiler) { - const { _remotes: remotes, _remoteType: remoteType } = this; - - /** @type {Record} */ - const remoteExternals = {}; - for (const [key, config] of remotes) { - let i = 0; - for (const external of config.external) { - if (external.startsWith("internal ")) continue; - remoteExternals[ - `webpack/container/reference/${key}${i ? `/fallback-${i}` : ""}` - ] = external; - i++; + getReferencedExports(moduleGraph, runtime) { + if (this.call) { + const importedModule = moduleGraph.getModule(this); + if ( + !importedModule || + importedModule.getExportsType(moduleGraph, false) !== "namespace" + ) { + return [this.names.slice(0, -1)]; } } + return [this.names]; + } - new ExternalsPlugin(remoteType, remoteExternals).apply(compiler); - - compiler.hooks.compilation.tap( - "ContainerReferencePlugin", - (compilation, { normalModuleFactory }) => { + serialize(context) { + const { write } = context; + write(this.names); + write(this.call); + write(this.asiSafe); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.names = read(); + this.call = read(); + this.asiSafe = read(); + super.deserialize(context); + } + + get type() { + return "cjs full require"; + } + + get category() { + return "commonjs"; + } +} + +CommonJsFullRequireDependency.Template = class CommonJsFullRequireDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @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, + { + module, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtimeRequirements, + runtime, + initFragments + } + ) { + const dep = /** @type {CommonJsFullRequireDependency} */ (dependency); + if (!dep.range) return; + const importedModule = moduleGraph.getModule(dep); + let requireExpr = runtimeTemplate.moduleExports({ + module: importedModule, + chunkGraph, + request: dep.request, + weak: dep.weak, + runtimeRequirements + }); + if (importedModule) { + const ids = dep.names; + const usedImported = moduleGraph + .getExportsInfo(importedModule) + .getUsedName(ids, runtime); + if (usedImported) { + const comment = equals(usedImported, ids) + ? "" + : Template.toNormalComment(propertyAccess(ids)) + " "; + const access = `${comment}${propertyAccess(usedImported)}`; + requireExpr = + dep.asiSafe === true + ? `(${requireExpr}${access})` + : `${requireExpr}${access}`; + } + } + source.replace(dep.range[0], dep.range[1] - 1, requireExpr); + } +}; + +makeSerializable( + CommonJsFullRequireDependency, + "webpack/lib/dependencies/CommonJsFullRequireDependency" +); + +module.exports = CommonJsFullRequireDependency; + + +/***/ }), + +/***/ 36013: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const CommentCompilationWarning = __webpack_require__(98427); +const RuntimeGlobals = __webpack_require__(16475); +const UnsupportedFeatureWarning = __webpack_require__(42495); +const { + evaluateToIdentifier, + evaluateToString, + expressionIsUnsupported, + toConstantDependency +} = __webpack_require__(93998); +const CommonJsFullRequireDependency = __webpack_require__(59440); +const CommonJsRequireContextDependency = __webpack_require__(23962); +const CommonJsRequireDependency = __webpack_require__(21264); +const ConstDependency = __webpack_require__(76911); +const ContextDependencyHelpers = __webpack_require__(99630); +const LocalModuleDependency = __webpack_require__(52805); +const { getLocalModule } = __webpack_require__(75827); +const RequireHeaderDependency = __webpack_require__(89183); +const RequireResolveContextDependency = __webpack_require__(55627); +const RequireResolveDependency = __webpack_require__(68582); +const RequireResolveHeaderDependency = __webpack_require__(9880); + +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ + +class CommonJsImportsParserPlugin { + /** + * @param {JavascriptParserOptions} options parser options + */ + constructor(options) { + this.options = options; + } + + apply(parser) { + const options = this.options; + + // metadata // + const tapRequireExpression = (expression, getMembers) => { + parser.hooks.typeof + .for(expression) + .tap( + "CommonJsPlugin", + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for(expression) + .tap("CommonJsPlugin", evaluateToString("function")); + parser.hooks.evaluateIdentifier + .for(expression) + .tap( + "CommonJsPlugin", + evaluateToIdentifier(expression, "require", getMembers, true) + ); + }; + tapRequireExpression("require", () => []); + tapRequireExpression("require.resolve", () => ["resolve"]); + tapRequireExpression("require.resolveWeak", () => ["resolveWeak"]); + + // Weird stuff // + parser.hooks.assign.for("require").tap("CommonJsPlugin", expr => { + // to not leak to global "require", we need to define a local require here. + const dep = new ConstDependency("var require;", 0); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + + // Unsupported // + parser.hooks.expression + .for("require.main.require") + .tap( + "CommonJsPlugin", + expressionIsUnsupported( + parser, + "require.main.require is not supported by webpack." + ) + ); + parser.hooks.call + .for("require.main.require") + .tap( + "CommonJsPlugin", + expressionIsUnsupported( + parser, + "require.main.require is not supported by webpack." + ) + ); + parser.hooks.expression + .for("module.parent.require") + .tap( + "CommonJsPlugin", + expressionIsUnsupported( + parser, + "module.parent.require is not supported by webpack." + ) + ); + parser.hooks.call + .for("module.parent.require") + .tap( + "CommonJsPlugin", + expressionIsUnsupported( + parser, + "module.parent.require is not supported by webpack." + ) + ); + + // renaming // + parser.hooks.canRename.for("require").tap("CommonJsPlugin", () => true); + parser.hooks.rename.for("require").tap("CommonJsPlugin", expr => { + // To avoid "not defined" error, replace the value with undefined + const dep = new ConstDependency("undefined", expr.range); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return false; + }); + + // inspection // + parser.hooks.expression + .for("require.cache") + .tap( + "CommonJsImportsParserPlugin", + toConstantDependency(parser, RuntimeGlobals.moduleCache, [ + RuntimeGlobals.moduleCache, + RuntimeGlobals.moduleId, + RuntimeGlobals.moduleLoaded + ]) + ); + + // require as expression // + parser.hooks.expression + .for("require") + .tap("CommonJsImportsParserPlugin", expr => { + const dep = new CommonJsRequireContextDependency( + { + request: options.unknownContextRequest, + recursive: options.unknownContextRecursive, + regExp: options.unknownContextRegExp, + mode: "sync" + }, + expr.range, + undefined, + parser.scope.inShorthand + ); + dep.critical = + options.unknownContextCritical && + "require function is used in a way in which dependencies cannot be statically extracted"; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }); + + // require // + const processRequireItem = (expr, param) => { + if (param.isString()) { + const dep = new CommonJsRequireDependency(param.string, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + }; + const processRequireContext = (expr, param) => { + const dep = ContextDependencyHelpers.create( + CommonJsRequireContextDependency, + expr.range, + param, + expr, + options, + { + category: "commonjs" + }, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }; + const createRequireHandler = callNew => expr => { + if (options.commonjsMagicComments) { + const { options: requireOptions, errors: commentErrors } = + parser.parseCommentOptions(expr.range); + + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + comment.loc + ) + ); + } + } + if (requireOptions) { + if (requireOptions.webpackIgnore !== undefined) { + if (typeof requireOptions.webpackIgnore !== "boolean") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${requireOptions.webpackIgnore}.`, + expr.loc + ) + ); + } else { + // Do not instrument `require()` if `webpackIgnore` is `true` + if (requireOptions.webpackIgnore) { + return true; + } + } + } + } + } + + if (expr.arguments.length !== 1) return; + let localModule; + const param = parser.evaluateExpression(expr.arguments[0]); + if (param.isConditional()) { + let isExpression = false; + for (const p of param.options) { + const result = processRequireItem(expr, p); + if (result === undefined) { + isExpression = true; + } + } + if (!isExpression) { + const dep = new RequireHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + } + } + if ( + param.isString() && + (localModule = getLocalModule(parser.state, param.string)) + ) { + localModule.flagUsed(); + const dep = new LocalModuleDependency(localModule, expr.range, callNew); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + } else { + const result = processRequireItem(expr, param); + if (result === undefined) { + processRequireContext(expr, param); + } else { + const dep = new RequireHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + } + return true; + } + }; + parser.hooks.call + .for("require") + .tap("CommonJsImportsParserPlugin", createRequireHandler(false)); + parser.hooks.new + .for("require") + .tap("CommonJsImportsParserPlugin", createRequireHandler(true)); + parser.hooks.call + .for("module.require") + .tap("CommonJsImportsParserPlugin", createRequireHandler(false)); + parser.hooks.new + .for("module.require") + .tap("CommonJsImportsParserPlugin", createRequireHandler(true)); + + // require with property access // + const chainHandler = (expr, calleeMembers, callExpr, members) => { + if (callExpr.arguments.length !== 1) return; + const param = parser.evaluateExpression(callExpr.arguments[0]); + if (param.isString() && !getLocalModule(parser.state, param.string)) { + const dep = new CommonJsFullRequireDependency( + param.string, + expr.range, + members + ); + dep.asiSafe = !parser.isAsiPosition(expr.range[0]); + dep.optional = !!parser.scope.inTry; + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + } + }; + const callChainHandler = (expr, calleeMembers, callExpr, members) => { + if (callExpr.arguments.length !== 1) return; + const param = parser.evaluateExpression(callExpr.arguments[0]); + if (param.isString() && !getLocalModule(parser.state, param.string)) { + const dep = new CommonJsFullRequireDependency( + param.string, + expr.callee.range, + members + ); + dep.call = true; + dep.asiSafe = !parser.isAsiPosition(expr.range[0]); + dep.optional = !!parser.scope.inTry; + dep.loc = expr.callee.loc; + parser.state.current.addDependency(dep); + parser.walkExpressions(expr.arguments); + return true; + } + }; + parser.hooks.memberChainOfCallMemberChain + .for("require") + .tap("CommonJsImportsParserPlugin", chainHandler); + parser.hooks.memberChainOfCallMemberChain + .for("module.require") + .tap("CommonJsImportsParserPlugin", chainHandler); + parser.hooks.callMemberChainOfCallMemberChain + .for("require") + .tap("CommonJsImportsParserPlugin", callChainHandler); + parser.hooks.callMemberChainOfCallMemberChain + .for("module.require") + .tap("CommonJsImportsParserPlugin", callChainHandler); + + // require.resolve // + const processResolve = (expr, weak) => { + if (expr.arguments.length !== 1) return; + const param = parser.evaluateExpression(expr.arguments[0]); + if (param.isConditional()) { + for (const option of param.options) { + const result = processResolveItem(expr, option, weak); + if (result === undefined) { + processResolveContext(expr, option, weak); + } + } + const dep = new RequireResolveHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + } else { + const result = processResolveItem(expr, param, weak); + if (result === undefined) { + processResolveContext(expr, param, weak); + } + const dep = new RequireResolveHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + } + }; + const processResolveItem = (expr, param, weak) => { + if (param.isString()) { + const dep = new RequireResolveDependency(param.string, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + dep.weak = weak; + parser.state.current.addDependency(dep); + return true; + } + }; + const processResolveContext = (expr, param, weak) => { + const dep = ContextDependencyHelpers.create( + RequireResolveContextDependency, + param.range, + param, + expr, + options, + { + category: "commonjs", + mode: weak ? "weak" : "sync" + }, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }; + + parser.hooks.call + .for("require.resolve") + .tap("RequireResolveDependencyParserPlugin", expr => { + return processResolve(expr, false); + }); + parser.hooks.call + .for("require.resolveWeak") + .tap("RequireResolveDependencyParserPlugin", expr => { + return processResolve(expr, true); + }); + } +} +module.exports = CommonJsImportsParserPlugin; + + +/***/ }), + +/***/ 32406: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const SelfModuleFactory = __webpack_require__(63560); +const Template = __webpack_require__(1626); +const CommonJsExportsDependency = __webpack_require__(45598); +const CommonJsFullRequireDependency = __webpack_require__(59440); +const CommonJsRequireContextDependency = __webpack_require__(23962); +const CommonJsRequireDependency = __webpack_require__(21264); +const CommonJsSelfReferenceDependency = __webpack_require__(52225); +const ModuleDecoratorDependency = __webpack_require__(88488); +const RequireHeaderDependency = __webpack_require__(89183); +const RequireResolveContextDependency = __webpack_require__(55627); +const RequireResolveDependency = __webpack_require__(68582); +const RequireResolveHeaderDependency = __webpack_require__(9880); +const RuntimeRequirementsDependency = __webpack_require__(24187); + +const CommonJsExportsParserPlugin = __webpack_require__(97107); +const CommonJsImportsParserPlugin = __webpack_require__(36013); + +const { + evaluateToIdentifier, + toConstantDependency +} = __webpack_require__(93998); +const CommonJsExportRequireDependency = __webpack_require__(62892); + +class CommonJsPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "CommonJsPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { compilation.dependencyFactories.set( - RemoteToExternalDependency, + CommonJsRequireDependency, normalModuleFactory ); + compilation.dependencyTemplates.set( + CommonJsRequireDependency, + new CommonJsRequireDependency.Template() + ); compilation.dependencyFactories.set( - FallbackItemDependency, + CommonJsFullRequireDependency, normalModuleFactory ); + compilation.dependencyTemplates.set( + CommonJsFullRequireDependency, + new CommonJsFullRequireDependency.Template() + ); compilation.dependencyFactories.set( - FallbackDependency, - new FallbackModuleFactory() + CommonJsRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsRequireContextDependency, + new CommonJsRequireContextDependency.Template() ); - normalModuleFactory.hooks.factorize.tap( - "ContainerReferencePlugin", - data => { - if (!data.request.includes("!")) { - for (const [key, config] of remotes) { - if ( - data.request.startsWith(`${key}`) && - (data.request.length === key.length || - data.request.charCodeAt(key.length) === slashCode) - ) { - return new RemoteModule( - data.request, - config.external.map((external, i) => - external.startsWith("internal ") - ? external.slice(9) - : `webpack/container/reference/${key}${ - i ? `/fallback-${i}` : "" - }` - ), - `.${data.request.slice(key.length)}`, - config.shareScope - ); - } - } - } - } + compilation.dependencyFactories.set( + RequireResolveDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveDependency, + new RequireResolveDependency.Template() ); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("ContainerReferencePlugin", (chunk, set) => { + compilation.dependencyFactories.set( + RequireResolveContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveContextDependency, + new RequireResolveContextDependency.Template() + ); + + compilation.dependencyTemplates.set( + RequireResolveHeaderDependency, + new RequireResolveHeaderDependency.Template() + ); + + compilation.dependencyTemplates.set( + RequireHeaderDependency, + new RequireHeaderDependency.Template() + ); + + compilation.dependencyTemplates.set( + CommonJsExportsDependency, + new CommonJsExportsDependency.Template() + ); + + compilation.dependencyFactories.set( + CommonJsExportRequireDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsExportRequireDependency, + new CommonJsExportRequireDependency.Template() + ); + + const selfFactory = new SelfModuleFactory(compilation.moduleGraph); + + compilation.dependencyFactories.set( + CommonJsSelfReferenceDependency, + selfFactory + ); + compilation.dependencyTemplates.set( + CommonJsSelfReferenceDependency, + new CommonJsSelfReferenceDependency.Template() + ); + + compilation.dependencyFactories.set( + ModuleDecoratorDependency, + selfFactory + ); + compilation.dependencyTemplates.set( + ModuleDecoratorDependency, + new ModuleDecoratorDependency.Template() + ); + + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.harmonyModuleDecorator) + .tap("CommonJsPlugin", (module, set) => { set.add(RuntimeGlobals.module); - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.hasOwnProperty); - set.add(RuntimeGlobals.initializeSharing); - set.add(RuntimeGlobals.shareScopeMap); - compilation.addRuntimeModule(chunk, new RemoteRuntimeModule()); + set.add(RuntimeGlobals.requireScope); + }); + + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.nodeModuleDecorator) + .tap("CommonJsPlugin", (module, set) => { + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.requireScope); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.harmonyModuleDecorator) + .tap("CommonJsPlugin", (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new HarmonyModuleDecoratorRuntimeModule() + ); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.nodeModuleDecorator) + .tap("CommonJsPlugin", (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new NodeModuleDecoratorRuntimeModule() + ); }); + + const handler = (parser, parserOptions) => { + if (parserOptions.commonjs !== undefined && !parserOptions.commonjs) + return; + parser.hooks.typeof + .for("module") + .tap( + "CommonJsPlugin", + toConstantDependency(parser, JSON.stringify("object")) + ); + + parser.hooks.expression + .for("require.main") + .tap( + "CommonJsPlugin", + toConstantDependency( + parser, + `${RuntimeGlobals.moduleCache}[${RuntimeGlobals.entryModuleId}]`, + [RuntimeGlobals.moduleCache, RuntimeGlobals.entryModuleId] + ) + ); + parser.hooks.expression + .for("module.loaded") + .tap("CommonJsPlugin", expr => { + parser.state.module.buildInfo.moduleConcatenationBailout = + "module.loaded"; + const dep = new RuntimeRequirementsDependency([ + RuntimeGlobals.moduleLoaded + ]); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + + parser.hooks.expression + .for("module.id") + .tap("CommonJsPlugin", expr => { + parser.state.module.buildInfo.moduleConcatenationBailout = + "module.id"; + const dep = new RuntimeRequirementsDependency([ + RuntimeGlobals.moduleId + ]); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + + parser.hooks.evaluateIdentifier.for("module.hot").tap( + "CommonJsPlugin", + evaluateToIdentifier("module.hot", "module", () => ["hot"], null) + ); + + new CommonJsImportsParserPlugin(parserOptions).apply(parser); + new CommonJsExportsParserPlugin(compilation.moduleGraph).apply( + parser + ); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CommonJsPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("CommonJsPlugin", handler); } ); } } -module.exports = ContainerReferencePlugin; +class HarmonyModuleDecoratorRuntimeModule extends RuntimeModule { + constructor() { + super("harmony module decorator"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + return Template.asString([ + `${ + RuntimeGlobals.harmonyModuleDecorator + } = ${runtimeTemplate.basicFunction("module", [ + "module = Object.create(module);", + "if (!module.children) module.children = [];", + "Object.defineProperty(module, 'exports', {", + Template.indent([ + "enumerable: true,", + `set: ${runtimeTemplate.basicFunction("", [ + "throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);" + ])}` + ]), + "});", + "return module;" + ])};` + ]); + } +} + +class NodeModuleDecoratorRuntimeModule extends RuntimeModule { + constructor() { + super("node module decorator"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + return Template.asString([ + `${RuntimeGlobals.nodeModuleDecorator} = ${runtimeTemplate.basicFunction( + "module", + [ + "module.paths = [];", + "if (!module.children) module.children = [];", + "return module;" + ] + )};` + ]); + } +} + +module.exports = CommonJsPlugin; /***/ }), -/***/ 57764: +/***/ 23962: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -74113,55 +73904,59 @@ module.exports = ContainerReferencePlugin; -const Dependency = __webpack_require__(54912); const makeSerializable = __webpack_require__(33032); +const ContextDependency = __webpack_require__(88101); +const ContextDependencyTemplateAsRequireCall = __webpack_require__(75815); -class FallbackDependency extends Dependency { - constructor(requests) { - super(); - this.requests = requests; - } +class CommonJsRequireContextDependency extends ContextDependency { + constructor(options, range, valueRange, inShorthand) { + super(options); - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - return `fallback ${this.requests.join(" ")}`; + this.range = range; + this.valueRange = valueRange; + // inShorthand must be serialized by subclasses that use it + this.inShorthand = inShorthand; } get type() { - return "fallback"; - } - - get category() { - return "esm"; + return "cjs require context"; } serialize(context) { const { write } = context; - write(this.requests); + + write(this.range); + write(this.valueRange); + write(this.inShorthand); + super.serialize(context); } - static deserialize(context) { + deserialize(context) { const { read } = context; - const obj = new FallbackDependency(read()); - obj.deserialize(context); - return obj; + + this.range = read(); + this.valueRange = read(); + this.inShorthand = read(); + + super.deserialize(context); } } makeSerializable( - FallbackDependency, - "webpack/lib/container/FallbackDependency" + CommonJsRequireContextDependency, + "webpack/lib/dependencies/CommonJsRequireContextDependency" ); -module.exports = FallbackDependency; +CommonJsRequireContextDependency.Template = + ContextDependencyTemplateAsRequireCall; + +module.exports = CommonJsRequireContextDependency; /***/ }), -/***/ 29593: +/***/ 21264: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -74172,530 +73967,459 @@ module.exports = FallbackDependency; -const ModuleDependency = __webpack_require__(80321); const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyTemplateAsId = __webpack_require__(80825); -class FallbackItemDependency extends ModuleDependency { - constructor(request) { +class CommonJsRequireDependency extends ModuleDependency { + constructor(request, range) { super(request); + this.range = range; } get type() { - return "fallback item"; + return "cjs require"; } get category() { - return "esm"; + return "commonjs"; } } +CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; + makeSerializable( - FallbackItemDependency, - "webpack/lib/container/FallbackItemDependency" + CommonJsRequireDependency, + "webpack/lib/dependencies/CommonJsRequireDependency" ); -module.exports = FallbackItemDependency; +module.exports = CommonJsRequireDependency; /***/ }), -/***/ 82886: +/***/ 52225: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy + Author Tobias Koppers @sokra */ -const { RawSource } = __webpack_require__(51255); -const Module = __webpack_require__(73208); const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); +const { equals } = __webpack_require__(84953); const makeSerializable = __webpack_require__(33032); -const FallbackItemDependency = __webpack_require__(29593); - -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ - -const TYPES = new Set(["javascript"]); -const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); +const propertyAccess = __webpack_require__(54190); +const NullDependency = __webpack_require__(31830); -class FallbackModule extends Module { - /** - * @param {string[]} requests list of requests to choose one - */ - constructor(requests) { - super("fallback-module"); - this.requests = requests; - this._identifier = `fallback ${this.requests.join(" ")}`; - } +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return this._identifier; +class CommonJsSelfReferenceDependency extends NullDependency { + constructor(range, base, names, call) { + super(); + this.range = range; + this.base = base; + this.names = names; + this.call = call; } - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return this._identifier; + get type() { + return "cjs self exports reference"; } - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - return `${this.layer ? `(${this.layer})/` : ""}webpack/container/fallback/${ - this.requests[0] - }/and ${this.requests.length - 1} more`; + get category() { + return "self"; } /** - * @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 + * @returns {string | null} an identifier to merge equal requests */ - chunkCondition(chunk, { chunkGraph }) { - return chunkGraph.getNumberOfEntryModules(chunk) > 0; + getResourceIdentifier() { + return `self`; } /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} + * 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 */ - needBuild(context, callback) { - callback(null, !this.buildInfo); + getReferencedExports(moduleGraph, runtime) { + return [this.call ? this.names.slice(0, -1) : this.names]; } - /** - * @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 = { - strict: true - }; - - this.clearDependenciesAndBlocks(); - for (const request of this.requests) - this.addDependency(new FallbackItemDependency(request)); - - callback(); + serialize(context) { + const { write } = context; + write(this.range); + write(this.base); + write(this.names); + write(this.call); + super.serialize(context); } - /** - * @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 this.requests.length * 5 + 42; + deserialize(context) { + const { read } = context; + this.range = read(); + this.base = read(); + this.names = read(); + this.call = read(); + super.deserialize(context); } +} - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; - } +makeSerializable( + CommonJsSelfReferenceDependency, + "webpack/lib/dependencies/CommonJsSelfReferenceDependency" +); +CommonJsSelfReferenceDependency.Template = class CommonJsSelfReferenceDependencyTemplate extends ( + NullDependency.Template +) { /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result + * @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} */ - codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { - const ids = this.dependencies.map(dep => - chunkGraph.getModuleId(moduleGraph.getModule(dep)) - ); - const code = Template.asString([ - `var ids = ${JSON.stringify(ids)};`, - "var error, result, i = 0;", - `var loop = ${runtimeTemplate.basicFunction("next", [ - "while(i < ids.length) {", - Template.indent([ - "try { next = __webpack_require__(ids[i++]); } catch(e) { return handleError(e); }", - "if(next) return next.then ? next.then(handleResult, handleError) : handleResult(next);" - ]), - "}", - "if(error) throw error;" - ])}`, - `var handleResult = ${runtimeTemplate.basicFunction("result", [ - "if(result) return result;", - "return loop();" - ])};`, - `var handleError = ${runtimeTemplate.basicFunction("e", [ - "error = e;", - "return loop();" - ])};`, - "module.exports = loop();" - ]); - const sources = new Map(); - sources.set("javascript", new RawSource(code)); - return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS }; - } + apply( + dependency, + source, + { module, moduleGraph, runtime, runtimeRequirements } + ) { + const dep = /** @type {CommonJsSelfReferenceDependency} */ (dependency); + let used; + if (dep.names.length === 0) { + used = dep.names; + } else { + used = moduleGraph.getExportsInfo(module).getUsedName(dep.names, runtime); + } + if (!used) { + throw new Error( + "Self-reference dependency has unused export name: This should not happen" + ); + } - serialize(context) { - const { write } = context; - write(this.requests); - super.serialize(context); - } + let base = undefined; + switch (dep.base) { + case "exports": + runtimeRequirements.add(RuntimeGlobals.exports); + base = module.exportsArgument; + break; + case "module.exports": + runtimeRequirements.add(RuntimeGlobals.module); + base = `${module.moduleArgument}.exports`; + break; + case "this": + runtimeRequirements.add(RuntimeGlobals.thisAsExports); + base = "this"; + break; + default: + throw new Error(`Unsupported base ${dep.base}`); + } - static deserialize(context) { - const { read } = context; - const obj = new FallbackModule(read()); - obj.deserialize(context); - return obj; - } -} + if (base === dep.base && equals(used, dep.names)) { + // Nothing has to be changed + // We don't use a replacement for compat reasons + // for plugins that update `module._source` which they + // shouldn't do! + return; + } -makeSerializable(FallbackModule, "webpack/lib/container/FallbackModule"); + source.replace( + dep.range[0], + dep.range[1] - 1, + `${base}${propertyAccess(used)}` + ); + } +}; -module.exports = FallbackModule; +module.exports = CommonJsSelfReferenceDependency; /***/ }), -/***/ 4112: +/***/ 76911: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr + Author Tobias Koppers @sokra */ -const ModuleFactory = __webpack_require__(51010); -const FallbackModule = __webpack_require__(82886); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("./FallbackDependency")} FallbackDependency */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/Hash")} Hash */ -module.exports = class FallbackModuleFactory extends ModuleFactory { +class ConstDependency extends NullDependency { /** - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback - * @returns {void} + * @param {string} expression the expression + * @param {number|[number, number]} range the source range + * @param {string[]=} runtimeRequirements runtime requirements */ - create({ dependencies: [dependency] }, callback) { - const dep = /** @type {FallbackDependency} */ (dependency); - callback(null, { - module: new FallbackModule(dep.requests) - }); + constructor(expression, range, runtimeRequirements) { + super(); + this.expression = expression; + this.range = range; + this.runtimeRequirements = runtimeRequirements + ? new Set(runtimeRequirements) + : null; + this._hashUpdate = undefined; } -}; - - -/***/ }), - -/***/ 30569: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy -*/ - - - -const isValidExternalsType = __webpack_require__(62142); -const SharePlugin = __webpack_require__(26335); -const createSchemaValidation = __webpack_require__(32540); -const ContainerPlugin = __webpack_require__(9244); -const ContainerReferencePlugin = __webpack_require__(95757); - -/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ExternalsType} ExternalsType */ -/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ModuleFederationPluginOptions} ModuleFederationPluginOptions */ -/** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").Shared} Shared */ -/** @typedef {import("../Compiler")} Compiler */ -const validate = createSchemaValidation( - __webpack_require__(7467), - () => __webpack_require__(82601), - { - name: "Module Federation Plugin", - baseDataPath: "options" + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + let hashUpdate = "" + this.range + "|" + this.expression; + if (this.runtimeRequirements) { + for (const item of this.runtimeRequirements) { + hashUpdate += "|"; + hashUpdate += item; + } + } + this._hashUpdate = hashUpdate; + } + hash.update(this._hashUpdate); } -); -class ModuleFederationPlugin { + /** - * @param {ModuleFederationPluginOptions} options options + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules */ - constructor(options) { - validate(options); + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } - this._options = options; + serialize(context) { + const { write } = context; + write(this.expression); + write(this.range); + write(this.runtimeRequirements); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.expression = read(); + this.range = read(); + this.runtimeRequirements = read(); + super.deserialize(context); } +} + +makeSerializable(ConstDependency, "webpack/lib/dependencies/ConstDependency"); +ConstDependency.Template = class ConstDependencyTemplate extends ( + NullDependency.Template +) { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - const { _options: options } = this; - const library = options.library || { type: "var", name: options.name }; - const remoteType = - options.remoteType || - (options.library && isValidExternalsType(options.library.type) - ? /** @type {ExternalsType} */ (options.library.type) - : "script"); - if ( - library && - !compiler.options.output.enabledLibraryTypes.includes(library.type) - ) { - compiler.options.output.enabledLibraryTypes.push(library.type); - } - compiler.hooks.afterPlugins.tap("ModuleFederationPlugin", () => { - if ( - options.exposes && - (Array.isArray(options.exposes) - ? options.exposes.length > 0 - : Object.keys(options.exposes).length > 0) - ) { - new ContainerPlugin({ - name: options.name, - library, - filename: options.filename, - runtime: options.runtime, - exposes: options.exposes - }).apply(compiler); - } - if ( - options.remotes && - (Array.isArray(options.remotes) - ? options.remotes.length > 0 - : Object.keys(options.remotes).length > 0) - ) { - new ContainerReferencePlugin({ - remoteType, - remotes: options.remotes - }).apply(compiler); - } - if (options.shared) { - new SharePlugin({ - shared: options.shared, - shareScope: options.shareScope - }).apply(compiler); + apply(dependency, source, templateContext) { + const dep = /** @type {ConstDependency} */ (dependency); + if (dep.runtimeRequirements) { + for (const req of dep.runtimeRequirements) { + templateContext.runtimeRequirements.add(req); } - }); + } + if (typeof dep.range === "number") { + source.insert(dep.range, dep.expression); + return; + } + + source.replace(dep.range[0], dep.range[1] - 1, dep.expression); } -} +}; -module.exports = ModuleFederationPlugin; +module.exports = ConstDependency; /***/ }), -/***/ 62916: +/***/ 88101: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy + Author Tobias Koppers @sokra */ -const { RawSource } = __webpack_require__(51255); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); +const Dependency = __webpack_require__(54912); +const DependencyTemplate = __webpack_require__(5160); const makeSerializable = __webpack_require__(33032); -const FallbackDependency = __webpack_require__(57764); -const RemoteToExternalDependency = __webpack_require__(14389); +const memoize = __webpack_require__(78676); -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../ContextModule").ContextOptions} ContextOptions */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ - -const TYPES = new Set(["remote", "share-init"]); -const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]); - -class RemoteModule extends Module { - /** - * @param {string} request request string - * @param {string[]} externalRequests list of external requests to containers - * @param {string} internalRequest name of exposed module in container - * @param {string} shareScope the used share scope name - */ - constructor(request, externalRequests, internalRequest, shareScope) { - super("remote-module"); - this.request = request; - this.externalRequests = externalRequests; - this.internalRequest = internalRequest; - this.shareScope = shareScope; - this._identifier = `remote (${shareScope}) ${this.externalRequests.join( - " " - )} ${this.internalRequest}`; - } - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return this._identifier; - } +const getCriticalDependencyWarning = memoize(() => + __webpack_require__(15427) +); - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return `remote ${this.request}`; - } +/** @typedef {ContextOptions & { request: string }} ContextDependencyOptions */ - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - return `${this.layer ? `(${this.layer})/` : ""}webpack/container/remote/${ - this.request - }`; - } +const regExpToString = r => (r ? r + "" : ""); +class ContextDependency extends Dependency { /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} + * @param {ContextDependencyOptions} options options for the context module */ - needBuild(context, callback) { - callback(null, !this.buildInfo); - } + constructor(options) { + super(); - /** - * @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 = { - strict: true - }; + this.options = options; + this.userRequest = this.options && this.options.request; + /** @type {false | string} */ + this.critical = false; + this.hadGlobalOrStickyRegExp = false; - this.clearDependenciesAndBlocks(); - if (this.externalRequests.length === 1) { - this.addDependency( - new RemoteToExternalDependency(this.externalRequests[0]) - ); - } else { - this.addDependency(new FallbackDependency(this.externalRequests)); + if ( + this.options && + (this.options.regExp.global || this.options.regExp.sticky) + ) { + this.options = { ...this.options, regExp: null }; + this.hadGlobalOrStickyRegExp = true; } - callback(); + this.request = undefined; + this.range = undefined; + this.valueRange = undefined; + this.inShorthand = undefined; + // TODO refactor this + this.replaces = undefined; } - /** - * @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 6; + get category() { + return "commonjs"; } /** - * @returns {Set} types available (do not mutate) + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module */ - getSourceTypes() { - return TYPES; + couldAffectReferencingModule() { + return true; } /** - * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + * @returns {string | null} an identifier to merge equal requests */ - nameForCondition() { - return this.request; + getResourceIdentifier() { + return ( + `context${this.options.request} ${this.options.recursive} ` + + `${regExpToString(this.options.regExp)} ${regExpToString( + this.options.include + )} ${regExpToString(this.options.exclude)} ` + + `${this.options.mode} ${this.options.chunkName} ` + + `${JSON.stringify(this.options.groupOptions)}` + ); } /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result + * Returns warnings + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} warnings */ - codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { - const module = moduleGraph.getModule(this.dependencies[0]); - const id = module && chunkGraph.getModuleId(module); - const sources = new Map(); - sources.set("remote", new RawSource("")); - const data = new Map(); - data.set("share-init", [ - { - shareScope: this.shareScope, - initStage: 20, - init: id === undefined ? "" : `initExternal(${JSON.stringify(id)});` - } - ]); - return { sources, data, runtimeRequirements: RUNTIME_REQUIREMENTS }; + getWarnings(moduleGraph) { + let warnings = super.getWarnings(moduleGraph); + + if (this.critical) { + if (!warnings) warnings = []; + const CriticalDependencyWarning = getCriticalDependencyWarning(); + warnings.push(new CriticalDependencyWarning(this.critical)); + } + + if (this.hadGlobalOrStickyRegExp) { + if (!warnings) warnings = []; + const CriticalDependencyWarning = getCriticalDependencyWarning(); + warnings.push( + new CriticalDependencyWarning( + "Contexts can't use RegExps with the 'g' or 'y' flags." + ) + ); + } + + return warnings; } serialize(context) { const { write } = context; + + write(this.options); + write(this.userRequest); + write(this.critical); + write(this.hadGlobalOrStickyRegExp); write(this.request); - write(this.externalRequests); - write(this.internalRequest); - write(this.shareScope); + write(this.range); + write(this.valueRange); + write(this.prepend); + write(this.replaces); + super.serialize(context); } - static deserialize(context) { + deserialize(context) { const { read } = context; - const obj = new RemoteModule(read(), read(), read(), read()); - obj.deserialize(context); - return obj; + + this.options = read(); + this.userRequest = read(); + this.critical = read(); + this.hadGlobalOrStickyRegExp = read(); + this.request = read(); + this.range = read(); + this.valueRange = read(); + this.prepend = read(); + this.replaces = read(); + + super.deserialize(context); } } -makeSerializable(RemoteModule, "webpack/lib/container/RemoteModule"); +makeSerializable( + ContextDependency, + "webpack/lib/dependencies/ContextDependency" +); -module.exports = RemoteModule; +ContextDependency.Template = DependencyTemplate; + +module.exports = ContextDependency; /***/ }), -/***/ 88288: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 99630: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -74705,171 +74429,237 @@ module.exports = RemoteModule; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); +const { parseResource } = __webpack_require__(82186); -/** @typedef {import("./RemoteModule")} RemoteModule */ +/** @typedef {import("estree").Node} EsTreeNode */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./ContextDependency")} ContextDependency */ +/** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */ -class RemoteRuntimeModule extends RuntimeModule { - constructor() { - super("remotes loading"); - } +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string + */ +const quoteMeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); +}; - /** - * @returns {string} runtime code - */ - generate() { - const { compilation, chunkGraph } = this; - const { runtimeTemplate, moduleGraph } = compilation; - const chunkToRemotesMapping = {}; - const idToExternalAndNameMapping = {}; - for (const chunk of this.chunk.getAllAsyncChunks()) { - const modules = chunkGraph.getChunkModulesIterableBySourceType( - chunk, - "remote" - ); - if (!modules) continue; - const remotes = (chunkToRemotesMapping[chunk.id] = []); - for (const m of modules) { - const module = /** @type {RemoteModule} */ (m); - const name = module.internalRequest; - const id = chunkGraph.getModuleId(module); - const shareScope = module.shareScope; - const dep = module.dependencies[0]; - const externalModule = moduleGraph.getModule(dep); - const externalModuleId = - externalModule && chunkGraph.getModuleId(externalModule); - remotes.push(id); - idToExternalAndNameMapping[id] = [shareScope, name, externalModuleId]; - } - } - return Template.asString([ - `var chunkMapping = ${JSON.stringify( - chunkToRemotesMapping, - null, - "\t" - )};`, - `var idToExternalAndNameMapping = ${JSON.stringify( - idToExternalAndNameMapping, - null, - "\t" - )};`, - `${ - RuntimeGlobals.ensureChunkHandlers - }.remotes = ${runtimeTemplate.basicFunction("chunkId, promises", [ - `if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`, - Template.indent([ - `chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction("id", [ - `var getScope = ${RuntimeGlobals.currentRemoteGetScope};`, - "if(!getScope) getScope = [];", - "var data = idToExternalAndNameMapping[id];", - "if(getScope.indexOf(data) >= 0) return;", - "getScope.push(data);", - `if(data.p) return promises.push(data.p);`, - `var onError = ${runtimeTemplate.basicFunction("error", [ - 'if(!error) error = new Error("Container missing");', - 'if(typeof error.message === "string")', - Template.indent( - `error.message += '\\nwhile loading "' + data[1] + '" from ' + data[2];` - ), - `__webpack_modules__[id] = ${runtimeTemplate.basicFunction("", [ - "throw error;" - ])}`, - "data.p = 0;" - ])};`, - `var handleFunction = ${runtimeTemplate.basicFunction( - "fn, arg1, arg2, d, next, first", - [ - "try {", - Template.indent([ - "var promise = fn(arg1, arg2);", - "if(promise && promise.then) {", - Template.indent([ - `var p = promise.then(${runtimeTemplate.returningFunction( - "next(result, d)", - "result" - )}, onError);`, - `if(first) promises.push(data.p = p); else return p;` - ]), - "} else {", - Template.indent(["return next(promise, d, first);"]), - "}" - ]), - "} catch(error) {", - Template.indent(["onError(error);"]), - "}" - ] - )}`, - `var onExternal = ${runtimeTemplate.returningFunction( - `external ? handleFunction(${RuntimeGlobals.initializeSharing}, data[0], 0, external, onInitialized, first) : onError()`, - "external, _, first" - )};`, - `var onInitialized = ${runtimeTemplate.returningFunction( - `handleFunction(external.get, data[1], getScope, 0, onFactory, first)`, - "_, external, first" - )};`, - `var onFactory = ${runtimeTemplate.basicFunction("factory", [ - "data.p = 1;", - `__webpack_modules__[id] = ${runtimeTemplate.basicFunction( - "module", - ["module.exports = factory();"] - )}` - ])};`, - "handleFunction(__webpack_require__, data[2], 0, 0, onExternal, 1);" - ])});` - ]), - "}" - ])}` - ]); +const splitContextFromPrefix = prefix => { + const idx = prefix.lastIndexOf("/"); + let context = "."; + if (idx >= 0) { + context = prefix.substr(0, idx); + prefix = `.${prefix.substr(idx)}`; } -} - -module.exports = RemoteRuntimeModule; + return { + context, + prefix + }; +}; +/** @typedef {Partial>} PartialContextDependencyOptions */ -/***/ }), +/** @typedef {{ new(options: ContextDependencyOptions, range: [number, number], valueRange: [number, number]): ContextDependency }} ContextDependencyConstructor */ -/***/ 14389: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @param {ContextDependencyConstructor} Dep the Dependency class + * @param {[number, number]} range source range + * @param {BasicEvaluatedExpression} param context param + * @param {EsTreeNode} expr expr + * @param {Pick} options options for context creation + * @param {PartialContextDependencyOptions} contextOptions options for the ContextModule + * @param {JavascriptParser} parser the parser + * @returns {ContextDependency} the created Dependency + */ +exports.create = (Dep, range, param, expr, options, contextOptions, parser) => { + if (param.isTemplateString()) { + let prefixRaw = param.quasis[0].string; + let postfixRaw = + param.quasis.length > 1 + ? param.quasis[param.quasis.length - 1].string + : ""; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const valueRange = param.range; + const { context, prefix } = splitContextFromPrefix(prefixRaw); + const { + path: postfix, + query, + fragment + } = parseResource(postfixRaw, parser); + // When there are more than two quasis, the generated RegExp can be more precise + // We join the quasis with the expression regexp + const innerQuasis = param.quasis.slice(1, param.quasis.length - 1); + const innerRegExp = + options.wrappedContextRegExp.source + + innerQuasis + .map(q => quoteMeta(q.string) + options.wrappedContextRegExp.source) + .join(""); + // Example: `./context/pre${e}inner${e}inner2${e}post?query#frag` + // context: "./context" + // prefix: "./pre" + // innerQuasis: [BEE("inner"), BEE("inner2")] + // (BEE = BasicEvaluatedExpression) + // postfix: "post" + // query: "?query" + // fragment: "#frag" + // regExp: /^\.\/pre.*inner.*inner2.*post$/ + const regExp = new RegExp( + `^${quoteMeta(prefix)}${innerRegExp}${quoteMeta(postfix)}$` + ); + const dep = new Dep( + { + request: context + query + fragment, + recursive: options.wrappedContextRecursive, + regExp, + mode: "sync", + ...contextOptions + }, + range, + valueRange + ); + dep.loc = expr.loc; + const replaces = []; -const ModuleDependency = __webpack_require__(80321); -const makeSerializable = __webpack_require__(33032); + param.parts.forEach((part, i) => { + if (i % 2 === 0) { + // Quasis or merged quasi + let range = part.range; + let value = part.string; + if (param.templateStringKind === "cooked") { + value = JSON.stringify(value); + value = value.slice(1, value.length - 1); + } + if (i === 0) { + // prefix + value = prefix; + range = [param.range[0], part.range[1]]; + value = + (param.templateStringKind === "cooked" ? "`" : "String.raw`") + + value; + } else if (i === param.parts.length - 1) { + // postfix + value = postfix; + range = [part.range[0], param.range[1]]; + value = value + "`"; + } else if ( + part.expression && + part.expression.type === "TemplateElement" && + part.expression.value.raw === value + ) { + // Shortcut when it's a single quasi and doesn't need to be replaced + return; + } + replaces.push({ + range, + value + }); + } else { + // Expression + parser.walkExpression(part.expression); + } + }); -class RemoteToExternalDependency extends ModuleDependency { - constructor(request) { - super(request); - } + dep.replaces = replaces; + dep.critical = + options.wrappedContextCritical && + "a part of the request of a dependency is an expression"; + return dep; + } else if ( + param.isWrapped() && + ((param.prefix && param.prefix.isString()) || + (param.postfix && param.postfix.isString())) + ) { + let prefixRaw = + param.prefix && param.prefix.isString() ? param.prefix.string : ""; + let postfixRaw = + param.postfix && param.postfix.isString() ? param.postfix.string : ""; + const prefixRange = + param.prefix && param.prefix.isString() ? param.prefix.range : null; + const postfixRange = + param.postfix && param.postfix.isString() ? param.postfix.range : null; + const valueRange = param.range; + const { context, prefix } = splitContextFromPrefix(prefixRaw); + const { + path: postfix, + query, + fragment + } = parseResource(postfixRaw, parser); + const regExp = new RegExp( + `^${quoteMeta(prefix)}${options.wrappedContextRegExp.source}${quoteMeta( + postfix + )}$` + ); + const dep = new Dep( + { + request: context + query + fragment, + recursive: options.wrappedContextRecursive, + regExp, + mode: "sync", + ...contextOptions + }, + range, + valueRange + ); + dep.loc = expr.loc; + const replaces = []; + if (prefixRange) { + replaces.push({ + range: prefixRange, + value: JSON.stringify(prefix) + }); + } + if (postfixRange) { + replaces.push({ + range: postfixRange, + value: JSON.stringify(postfix) + }); + } + dep.replaces = replaces; + dep.critical = + options.wrappedContextCritical && + "a part of the request of a dependency is an expression"; - get type() { - return "remote to external"; - } + if (parser && param.wrappedInnerExpressions) { + for (const part of param.wrappedInnerExpressions) { + if (part.expression) parser.walkExpression(part.expression); + } + } - get category() { - return "esm"; - } -} + return dep; + } else { + const dep = new Dep( + { + request: options.exprContextRequest, + recursive: options.exprContextRecursive, + regExp: /** @type {RegExp} */ (options.exprContextRegExp), + mode: "sync", + ...contextOptions + }, + range, + param.range + ); + dep.loc = expr.loc; + dep.critical = + options.exprContextCritical && + "the request of a dependency is an expression"; -makeSerializable( - RemoteToExternalDependency, - "webpack/lib/container/RemoteToExternalDependency" -); + parser.walkExpression(param.expression); -module.exports = RemoteToExternalDependency; + return dep; + } +}; /***/ }), -/***/ 3083: -/***/ (function(__unused_webpack_module, exports) { +/***/ 76081: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -74879,1283 +74669,908 @@ module.exports = RemoteToExternalDependency; -/** @template T @typedef {(string | Record)[] | Record} ContainerOptionsFormat */ +const ContextDependency = __webpack_require__(88101); -/** - * @template T - * @template N - * @param {ContainerOptionsFormat} options options passed by the user - * @param {function(string | string[], string) : N} normalizeSimple normalize a simple item - * @param {function(T, string) : N} normalizeOptions normalize a complex item - * @param {function(string, N): void} fn processing function - * @returns {void} - */ -const process = (options, normalizeSimple, normalizeOptions, fn) => { - const array = items => { - for (const item of items) { - if (typeof item === "string") { - fn(item, normalizeSimple(item, item)); - } else if (item && typeof item === "object") { - object(item); - } else { - throw new Error("Unexpected options format"); - } - } - }; - const object = obj => { - for (const [key, value] of Object.entries(obj)) { - if (typeof value === "string" || Array.isArray(value)) { - fn(key, normalizeSimple(value, key)); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + +class ContextDependencyTemplateAsId extends ContextDependency.Template { + /** + * @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, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ContextDependency} */ (dependency); + const moduleExports = runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + weak: dep.weak, + runtimeRequirements + }); + + if (moduleGraph.getModule(dep)) { + if (dep.valueRange) { + if (Array.isArray(dep.replaces)) { + for (let i = 0; i < dep.replaces.length; i++) { + const rep = dep.replaces[i]; + source.replace(rep.range[0], rep.range[1] - 1, rep.value); + } + } + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `${moduleExports}.resolve(` + ); } else { - fn(key, normalizeOptions(value, key)); + source.replace( + dep.range[0], + dep.range[1] - 1, + `${moduleExports}.resolve` + ); } + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); } - }; - if (!options) { - return; - } else if (Array.isArray(options)) { - array(options); - } else if (typeof options === "object") { - object(options); - } else { - throw new Error("Unexpected options format"); } -}; - -/** - * @template T - * @template R - * @param {ContainerOptionsFormat} options options passed by the user - * @param {function(string | string[], string) : R} normalizeSimple normalize a simple item - * @param {function(T, string) : R} normalizeOptions normalize a complex item - * @returns {[string, R][]} parsed options - */ -const parseOptions = (options, normalizeSimple, normalizeOptions) => { - /** @type {[string, R][]} */ - const items = []; - process(options, normalizeSimple, normalizeOptions, (key, value) => { - items.push([key, value]); - }); - return items; -}; - -/** - * @template T - * @param {string} scope scope name - * @param {ContainerOptionsFormat} options options passed by the user - * @returns {Record} options to spread or pass - */ -const scope = (scope, options) => { - /** @type {Record} */ - const obj = {}; - process( - options, - item => /** @type {string | string[] | T} */ (item), - item => /** @type {string | string[] | T} */ (item), - (key, value) => { - obj[ - key.startsWith("./") ? `${scope}${key.slice(1)}` : `${scope}/${key}` - ] = value; - } - ); - return obj; -}; - -exports.parseOptions = parseOptions; -exports.scope = scope; +} +module.exports = ContextDependencyTemplateAsId; /***/ }), -/***/ 91254: +/***/ 75815: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov + Author Tobias Koppers @sokra */ -const { ReplaceSource, RawSource, ConcatSource } = __webpack_require__(51255); -const { UsageState } = __webpack_require__(63686); -const Generator = __webpack_require__(93401); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); +const ContextDependency = __webpack_require__(88101); -/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../util/Hash")} Hash */ - -const TYPES = new Set(["javascript"]); - -class CssExportsGenerator extends Generator { - constructor() { - super(); - } - - // TODO add getConcatenationBailoutReason to allow concatenation - // but how to make it have a module id +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +class ContextDependencyTemplateAsRequireCall extends ContextDependency.Template { /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code + * @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} */ - generate(module, generateContext) { - const source = new ReplaceSource(new RawSource("")); - const initFragments = []; - const cssExports = new Map(); + apply( + dependency, + source, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ContextDependency} */ (dependency); + let moduleExports = runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + runtimeRequirements + }); - generateContext.runtimeRequirements.add(RuntimeGlobals.module); + if (dep.inShorthand) { + moduleExports = `${dep.inShorthand}: ${moduleExports}`; + } + if (moduleGraph.getModule(dep)) { + if (dep.valueRange) { + if (Array.isArray(dep.replaces)) { + for (let i = 0; i < dep.replaces.length; i++) { + const rep = dep.replaces[i]; + source.replace(rep.range[0], rep.range[1] - 1, rep.value); + } + } + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `${moduleExports}(` + ); + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } +} +module.exports = ContextDependencyTemplateAsRequireCall; - const runtimeRequirements = new Set(); - const templateContext = { - runtimeTemplate: generateContext.runtimeTemplate, - dependencyTemplates: generateContext.dependencyTemplates, - moduleGraph: generateContext.moduleGraph, - chunkGraph: generateContext.chunkGraph, - module, - runtime: generateContext.runtime, - runtimeRequirements: runtimeRequirements, - concatenationScope: generateContext.concatenationScope, - codeGenerationResults: generateContext.codeGenerationResults, - initFragments, - cssExports - }; +/***/ }), - const handleDependency = dependency => { - const constructor = /** @type {new (...args: any[]) => Dependency} */ ( - dependency.constructor - ); - const template = generateContext.dependencyTemplates.get(constructor); - if (!template) { - throw new Error( - "No template for dependency: " + dependency.constructor.name - ); - } +/***/ 58477: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - template.apply(dependency, source, templateContext); - }; - module.dependencies.forEach(handleDependency); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (generateContext.concatenationScope) { - const source = new ConcatSource(); - const usedIdentifiers = new Set(); - for (const [k, v] of cssExports) { - let identifier = Template.toIdentifier(k); - let i = 0; - while (usedIdentifiers.has(identifier)) { - identifier = Template.toIdentifier(k + i); - } - usedIdentifiers.add(identifier); - generateContext.concatenationScope.registerExport(k, identifier); - source.add( - `${ - generateContext.runtimeTemplate.supportsConst ? "const" : "var" - } ${identifier} = ${JSON.stringify(v)};\n` - ); - } - return source; - } else { - const otherUsed = - generateContext.moduleGraph - .getExportsInfo(module) - .otherExportsInfo.getUsed(generateContext.runtime) !== - UsageState.Unused; - if (otherUsed) { - generateContext.runtimeRequirements.add( - RuntimeGlobals.makeNamespaceObject - ); - } - return new RawSource( - `${otherUsed ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${ - module.moduleArgument - }.exports = {\n${Array.from( - cssExports, - ([k, v]) => `\t${JSON.stringify(k)}: ${JSON.stringify(v)}` - ).join(",\n")}\n}${otherUsed ? ")" : ""};` - ); + + +const Dependency = __webpack_require__(54912); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); + +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class ContextElementDependency extends ModuleDependency { + constructor(request, userRequest, typePrefix, category, referencedExports) { + super(request); + this.referencedExports = referencedExports; + this._typePrefix = typePrefix; + this._category = category; + + if (userRequest) { + this.userRequest = userRequest; } } - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; + get type() { + if (this._typePrefix) { + return `${this._typePrefix} context element`; + } + + return "context element"; } - /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module - */ - getSize(module, type) { - return 42; + get category() { + return this._category; } /** - * @param {Hash} hash hash that will be modified - * @param {UpdateHashContext} updateHashContext context for updating hash + * 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 */ - updateHash(hash, { module }) {} + getReferencedExports(moduleGraph, runtime) { + return this.referencedExports + ? this.referencedExports.map(e => ({ + name: e, + canMangle: false + })) + : Dependency.EXPORTS_OBJECT_REFERENCED; + } + + serialize(context) { + context.write(this.referencedExports); + super.serialize(context); + } + + deserialize(context) { + this.referencedExports = context.read(); + super.deserialize(context); + } } -module.exports = CssExportsGenerator; +makeSerializable( + ContextElementDependency, + "webpack/lib/dependencies/ContextElementDependency" +); + +module.exports = ContextElementDependency; /***/ }), -/***/ 46061: +/***/ 79062: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov + Author Tobias Koppers @sokra */ -const { ReplaceSource } = __webpack_require__(51255); -const Generator = __webpack_require__(93401); -const InitFragment = __webpack_require__(55870); const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../util/Hash")} Hash */ - -const TYPES = new Set(["css"]); +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -class CssGenerator extends Generator { - constructor() { +class CreateScriptUrlDependency extends NullDependency { + /** + * @param {[number, number]} range range + */ + constructor(range) { super(); + this.range = range; + } + + get type() { + return "create script url"; + } + + serialize(context) { + const { write } = context; + write(this.range); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.range = read(); + super.deserialize(context); } +} +CreateScriptUrlDependency.Template = class CreateScriptUrlDependencyTemplate extends ( + NullDependency.Template +) { /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code + * @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} */ - generate(module, generateContext) { - const originalSource = module.originalSource(); - const source = new ReplaceSource(originalSource); - const initFragments = []; - const cssExports = new Map(); + apply(dependency, source, { runtimeRequirements }) { + const dep = /** @type {CreateScriptUrlDependency} */ (dependency); - generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules); + runtimeRequirements.add(RuntimeGlobals.createScriptUrl); - const templateContext = { - runtimeTemplate: generateContext.runtimeTemplate, - dependencyTemplates: generateContext.dependencyTemplates, - moduleGraph: generateContext.moduleGraph, - chunkGraph: generateContext.chunkGraph, - module, - runtime: generateContext.runtime, - runtimeRequirements: generateContext.runtimeRequirements, - concatenationScope: generateContext.concatenationScope, - codeGenerationResults: generateContext.codeGenerationResults, - initFragments, - cssExports - }; + source.insert(dep.range[0], `${RuntimeGlobals.createScriptUrl}(`); + source.insert(dep.range[1], ")"); + } +}; - const handleDependency = dependency => { - const constructor = /** @type {new (...args: any[]) => Dependency} */ ( - dependency.constructor - ); - const template = generateContext.dependencyTemplates.get(constructor); - if (!template) { - throw new Error( - "No template for dependency: " + dependency.constructor.name - ); - } +makeSerializable( + CreateScriptUrlDependency, + "webpack/lib/dependencies/CreateScriptUrlDependency" +); - template.apply(dependency, source, templateContext); - }; - module.dependencies.forEach(handleDependency); - if (module.presentationalDependencies !== undefined) - module.presentationalDependencies.forEach(handleDependency); +module.exports = CreateScriptUrlDependency; - if (cssExports.size > 0) { - const data = generateContext.getData(); - data.set("css-exports", cssExports); - } - return InitFragment.addToSource(source, initFragments, generateContext); - } +/***/ }), - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; - } +/***/ 15427: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module - */ - getSize(module, type) { - const originalSource = module.originalSource(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (!originalSource) { - return 0; - } - return originalSource.size(); - } - /** - * @param {Hash} hash hash that will be modified - * @param {UpdateHashContext} updateHashContext context for updating hash - */ - updateHash(hash, { module }) {} +const WebpackError = __webpack_require__(53799); +const makeSerializable = __webpack_require__(33032); + +class CriticalDependencyWarning extends WebpackError { + constructor(message) { + super(); + + this.name = "CriticalDependencyWarning"; + this.message = "Critical dependency: " + message; + } } -module.exports = CssGenerator; +makeSerializable( + CriticalDependencyWarning, + "webpack/lib/dependencies/CriticalDependencyWarning" +); + +module.exports = CriticalDependencyWarning; /***/ }), -/***/ 80806: +/***/ 76760: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const { SyncWaterfallHook } = __webpack_require__(41242); -const Compilation = __webpack_require__(85720); -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); -const compileBooleanMatcher = __webpack_require__(29404); -const { chunkHasCss } = __webpack_require__(47283); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** - * @typedef {Object} JsonpCompilationPluginHooks - * @property {SyncWaterfallHook<[string, Chunk]>} createStylesheet - */ +class CssExportDependency extends NullDependency { + /** + * @param {string} name name + * @param {string} value value + */ + constructor(name, value) { + super(); + this.name = name; + this.value = value; + } -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); + get type() { + return "css :export"; + } -class CssLoadingRuntimeModule extends RuntimeModule { /** - * @param {Compilation} compilation the compilation - * @returns {JsonpCompilationPluginHooks} hooks + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names */ - 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 = { - createStylesheet: new SyncWaterfallHook(["source", "chunk"]) - }; - compilationHooksMap.set(compilation, hooks); - } - return hooks; + getExports(moduleGraph) { + const name = this.name; + return { + exports: [ + { + name, + canMangle: true + } + ], + dependencies: undefined + }; } - constructor(runtimeRequirements, runtimeOptions) { - super("css loading", 10); + serialize(context) { + const { write } = context; + write(this.name); + write(this.value); + super.serialize(context); + } - this._runtimeRequirements = runtimeRequirements; - this.runtimeOptions = runtimeOptions; + deserialize(context) { + const { read } = context; + this.name = read(); + this.value = read(); + super.deserialize(context); } +} +CssExportDependency.Template = class CssExportDependencyTemplate extends ( + NullDependency.Template +) { /** - * @returns {string} runtime code + * @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} */ - generate() { - const { compilation, chunk, _runtimeRequirements } = this; - const { - chunkGraph, - runtimeTemplate, - outputOptions: { - crossOriginLoading, - uniqueName, - chunkLoadTimeout: loadTimeout - } - } = compilation; - const fn = RuntimeGlobals.ensureChunkHandlers; - const conditionMap = chunkGraph.getChunkConditionMap( - chunk, - (chunk, chunkGraph) => - !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css") - ); - const hasCssMatcher = compileBooleanMatcher(conditionMap); + apply(dependency, source, { cssExports }) { + const dep = /** @type {CssExportDependency} */ (dependency); + cssExports.set(dep.name, dep.value); + } +}; - const withLoading = - _runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) && - hasCssMatcher !== false; - const withHmr = _runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const initialChunkIdsWithCss = new Set(); - const initialChunkIdsWithoutCss = new Set(); - for (const c of chunk.getAllInitialChunks()) { - (chunkHasCss(c, chunkGraph) - ? initialChunkIdsWithCss - : initialChunkIdsWithoutCss - ).add(c.id); - } +makeSerializable( + CssExportDependency, + "webpack/lib/dependencies/CssExportDependency" +); - if (!withLoading && !withHmr && initialChunkIdsWithCss.size === 0) { - return null; - } +module.exports = CssExportDependency; - const { createStylesheet } = - CssLoadingRuntimeModule.getCompilationHooks(compilation); - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_css` - : undefined; +/***/ }), - const code = Template.asString([ - "link = document.createElement('link');", - uniqueName - ? 'link.setAttribute("data-webpack", uniqueName + ":" + key);' - : "", - "link.setAttribute(loadingAttribute, 1);", - 'link.rel = "stylesheet";', - "link.href = url;", - crossOriginLoading - ? Template.asString([ - "if (link.src.indexOf(window.location.origin + '/') !== 0) {", - Template.indent( - `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` - ), - "}" - ]) - : "" - ]); +/***/ 90542: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const cc = str => str.charCodeAt(0); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - return Template.asString([ - "// object to store loaded and loading chunks", - "// undefined = chunk not loaded, null = chunk preloaded/prefetched", - "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", - `var installedChunks = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{${Array.from( - initialChunkIdsWithoutCss, - id => `${JSON.stringify(id)}:0` - ).join(",")}};`, - "", - uniqueName - ? `var uniqueName = ${JSON.stringify( - runtimeTemplate.outputOptions.uniqueName - )};` - : "// data-webpack is not used as build has no uniqueName", - `var loadCssChunkData = ${runtimeTemplate.basicFunction( - "target, link, chunkId", - [ - `var data, token = "", token2, exports = {}, exportsWithId = [], exportsWithDashes = [], ${ - withHmr ? "moduleIds = [], " : "" - }i = 0, cc = 1;`, - "try { if(!link) link = loadStylesheet(chunkId); data = link.sheet.cssRules; data = data[data.length - 1].style; } catch(e) { data = getComputedStyle(document.head); }", - `data = data.getPropertyValue(${ - uniqueName - ? runtimeTemplate.concatenation( - "--webpack-", - { expr: "uniqueName" }, - "-", - { expr: "chunkId" } - ) - : runtimeTemplate.concatenation("--webpack-", { expr: "chunkId" }) - });`, - "if(!data) return [];", - "for(; cc; i++) {", - Template.indent([ - "cc = data.charCodeAt(i);", - `if(cc == ${cc("(")}) { token2 = token; token = ""; }`, - `else if(cc == ${cc( - ")" - )}) { exports[token2.replace(/^_/, "")] = token.replace(/^_/, ""); token = ""; }`, - `else if(cc == ${cc("/")} || cc == ${cc( - "%" - )}) { token = token.replace(/^_/, ""); exports[token] = token; exportsWithId.push(token); if(cc == ${cc( - "%" - )}) exportsWithDashes.push(token); token = ""; }`, - `else if(!cc || cc == ${cc( - "," - )}) { token = token.replace(/^_/, ""); exportsWithId.forEach(${runtimeTemplate.expressionFunction( - `exports[x] = ${ - uniqueName - ? runtimeTemplate.concatenation( - { expr: "uniqueName" }, - "-", - { expr: "token" }, - "-", - { expr: "exports[x]" } - ) - : runtimeTemplate.concatenation({ expr: "token" }, "-", { - expr: "exports[x]" - }) - }`, - "x" - )}); exportsWithDashes.forEach(${runtimeTemplate.expressionFunction( - `exports[x] = "--" + exports[x]`, - "x" - )}); ${ - RuntimeGlobals.makeNamespaceObject - }(exports); target[token] = (${runtimeTemplate.basicFunction( - "exports, module", - `module.exports = exports;` - )}).bind(null, exports); ${ - withHmr ? "moduleIds.push(token); " : "" - }token = ""; exports = {}; exportsWithId.length = 0; }`, - `else if(cc == ${cc("\\")}) { token += data[++i] }`, - `else { token += data[i]; }` - ]), - "}", - `${ - withHmr ? `if(target == ${RuntimeGlobals.moduleFactories}) ` : "" - }installedChunks[chunkId] = 0;`, - withHmr ? "return moduleIds;" : "" - ] - )}`, - 'var loadingAttribute = "data-webpack-loading";', - `var loadStylesheet = ${runtimeTemplate.basicFunction( - "chunkId, url, done" + (withHmr ? ", hmr" : ""), - [ - 'var link, needAttach, key = "chunk-" + chunkId;', - withHmr ? "if(!hmr) {" : "", - 'var links = document.getElementsByTagName("link");', - "for(var i = 0; i < links.length; i++) {", - Template.indent([ - "var l = links[i];", - `if(l.rel == "stylesheet" && (${ - withHmr - ? 'l.href.startsWith(url) || l.getAttribute("href").startsWith(url)' - : 'l.href == url || l.getAttribute("href") == url' - }${ - uniqueName - ? ' || l.getAttribute("data-webpack") == uniqueName + ":" + key' - : "" - })) { link = l; break; }` - ]), - "}", - "if(!done) return link;", - withHmr ? "}" : "", - "if(!link) {", - Template.indent([ - "needAttach = true;", - createStylesheet.call(code, this.chunk) - ]), - "}", - `var onLinkComplete = ${runtimeTemplate.basicFunction( - "prev, event", - Template.asString([ - "link.onerror = link.onload = null;", - "link.removeAttribute(loadingAttribute);", - "clearTimeout(timeout);", - 'if(event && event.type != "load") link.parentNode.removeChild(link)', - "done(event);", - "if(prev) return prev(event);" - ]) - )};`, - "if(link.getAttribute(loadingAttribute)) {", - Template.indent([ - `var timeout = setTimeout(onLinkComplete.bind(null, undefined, { type: 'timeout', target: link }), ${loadTimeout});`, - "link.onerror = onLinkComplete.bind(null, link.onerror);", - "link.onload = onLinkComplete.bind(null, link.onload);" - ]), - "} else onLinkComplete(undefined, { type: 'load', target: link });", // We assume any existing stylesheet is render blocking - withHmr ? "hmr ? document.head.insertBefore(link, hmr) :" : "", - "needAttach && document.head.appendChild(link);", - "return link;" - ] - )};`, - initialChunkIdsWithCss.size > 2 - ? `${JSON.stringify( - Array.from(initialChunkIdsWithCss) - )}.forEach(loadCssChunkData.bind(null, ${ - RuntimeGlobals.moduleFactories - }, 0));` - : initialChunkIdsWithCss.size > 0 - ? `${Array.from( - initialChunkIdsWithCss, - id => - `loadCssChunkData(${ - RuntimeGlobals.moduleFactories - }, 0, ${JSON.stringify(id)});` - ).join("")}` - : "// no initial css", - "", - withLoading - ? Template.asString([ - `${fn}.css = ${runtimeTemplate.basicFunction( - "chunkId, promises", - hasCssMatcher !== false - ? [ - "// css chunk loading", - `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, - 'if(installedChunkData !== 0) { // 0 means "already installed".', - Template.indent([ - "", - '// a Promise means "currently loading".', - "if(installedChunkData) {", - Template.indent([ - "promises.push(installedChunkData[2]);" - ]), - "} else {", - Template.indent([ - hasCssMatcher === true - ? "if(true) { // all chunks have CSS" - : `if(${hasCssMatcher("chunkId")}) {`, - Template.indent([ - "// setup Promise in chunk cache", - `var promise = new Promise(${runtimeTemplate.expressionFunction( - `installedChunkData = installedChunks[chunkId] = [resolve, reject]`, - "resolve, reject" - )});`, - "promises.push(installedChunkData[2] = promise);", - "", - "// start chunk loading", - `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, - "// create error before stack unwound to get useful stacktrace later", - "var error = new Error();", - `var loadingEnded = ${runtimeTemplate.basicFunction( - "event", - [ - `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`, - Template.indent([ - "installedChunkData = installedChunks[chunkId];", - "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;", - "if(installedChunkData) {", - Template.indent([ - 'if(event.type !== "load") {', - Template.indent([ - "var errorType = event && event.type;", - "var realSrc = event && event.target && event.target.src;", - "error.message = 'Loading css chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", - "error.name = 'ChunkLoadError';", - "error.type = errorType;", - "error.request = realSrc;", - "installedChunkData[1](error);" - ]), - "} else {", - Template.indent([ - `loadCssChunkData(${RuntimeGlobals.moduleFactories}, link, chunkId);`, - "installedChunkData[0]();" - ]), - "}" - ]), - "}" - ]), - "}" - ] - )};`, - "var link = loadStylesheet(chunkId, url, loadingEnded);" - ]), - "} else installedChunks[chunkId] = 0;" - ]), - "}" - ]), - "}" - ] - : "installedChunks[chunkId] = 0;" - )};` - ]) - : "// no chunk loading", - "", - withHmr - ? Template.asString([ - "var oldTags = [];", - "var newTags = [];", - `var applyHandler = ${runtimeTemplate.basicFunction("options", [ - `return { dispose: ${runtimeTemplate.basicFunction( - "", - [] - )}, apply: ${runtimeTemplate.basicFunction("", [ - "var moduleIds = [];", - `newTags.forEach(${runtimeTemplate.expressionFunction( - "info[1].sheet.disabled = false", - "info" - )});`, - "while(oldTags.length) {", - Template.indent([ - "var oldTag = oldTags.pop();", - "if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);" - ]), - "}", - "while(newTags.length) {", - Template.indent([ - `var info = newTags.pop();`, - `var chunkModuleIds = loadCssChunkData(${RuntimeGlobals.moduleFactories}, info[1], info[0]);`, - `chunkModuleIds.forEach(${runtimeTemplate.expressionFunction( - "moduleIds.push(id)", - "id" - )});` - ]), - "}", - "return moduleIds;" - ])} };` - ])}`, - `var cssTextKey = ${runtimeTemplate.returningFunction( - `Array.from(link.sheet.cssRules, ${runtimeTemplate.returningFunction( - "r.cssText", - "r" - )}).join()`, - "link" - )}`, - `${ - RuntimeGlobals.hmrDownloadUpdateHandlers - }.css = ${runtimeTemplate.basicFunction( - "chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList", - [ - "applyHandlers.push(applyHandler);", - `chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [ - `var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, - `var url = ${RuntimeGlobals.publicPath} + filename;`, - "var oldTag = loadStylesheet(chunkId, url);", - "if(!oldTag) return;", - `promises.push(new Promise(${runtimeTemplate.basicFunction( - "resolve, reject", - [ - `var link = loadStylesheet(chunkId, url + (url.indexOf("?") < 0 ? "?" : "&") + "hmr=" + Date.now(), ${runtimeTemplate.basicFunction( - "event", - [ - 'if(event.type !== "load") {', - Template.indent([ - "var errorType = event && event.type;", - "var realSrc = event && event.target && event.target.src;", - "error.message = 'Loading css hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", - "error.name = 'ChunkLoadError';", - "error.type = errorType;", - "error.request = realSrc;", - "reject(error);" - ]), - "} else {", - Template.indent([ - "try { if(cssTextKey(oldTag) == cssTextKey(link)) { if(link.parentNode) link.parentNode.removeChild(link); return resolve(); } } catch(e) {}", - "var factories = {};", - "loadCssChunkData(factories, link, chunkId);", - `Object.keys(factories).forEach(${runtimeTemplate.expressionFunction( - "updatedModulesList.push(id)", - "id" - )})`, - "link.sheet.disabled = true;", - "oldTags.push(oldTag);", - "newTags.push([chunkId, link]);", - "resolve();" - ]), - "}" - ] - )}, oldTag);` - ] - )}));` - ])});` - ] - )}` - ]) - : "// no hmr" - ]); + + +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class CssImportDependency extends ModuleDependency { + /** + * @param {string} request request + * @param {[number, number]} range range of the argument + * @param {string | undefined} supports list of supports conditions + * @param {string | undefined} media list of media conditions + */ + constructor(request, range, supports, media) { + super(request); + this.range = range; + this.supports = supports; + this.media = media; + } + + get type() { + return "css @import"; + } + + get category() { + return "css-import"; + } + + /** + * @param {string} context context directory + * @returns {Module} a module + */ + createIgnoredModule(context) { + return null; } } -module.exports = CssLoadingRuntimeModule; +CssImportDependency.Template = class CssImportDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @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 dep = /** @type {CssImportDependency} */ (dependency); + + source.replace(dep.range[0], dep.range[1] - 1, ""); + } +}; + +makeSerializable( + CssImportDependency, + "webpack/lib/dependencies/CssImportDependency" +); + +module.exports = CssImportDependency; /***/ }), -/***/ 47283: +/***/ 92328: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const { ConcatSource } = __webpack_require__(51255); -const HotUpdateChunk = __webpack_require__(9597); -const RuntimeGlobals = __webpack_require__(16475); -const SelfModuleFactory = __webpack_require__(63560); -const CssExportDependency = __webpack_require__(76760); -const CssImportDependency = __webpack_require__(90542); -const CssLocalIdentifierDependency = __webpack_require__(92328); -const CssSelfLocalIdentifierDependency = __webpack_require__(29094); -const CssUrlDependency = __webpack_require__(70749); -const StaticExportsDependency = __webpack_require__(91418); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const createSchemaValidation = __webpack_require__(32540); -const createHash = __webpack_require__(49835); -const memoize = __webpack_require__(78676); -const CssExportsGenerator = __webpack_require__(91254); -const CssGenerator = __webpack_require__(46061); -const CssParser = __webpack_require__(98305); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").CssExperimentOptions} CssExperimentOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ -const getCssLoadingRuntimeModule = memoize(() => - __webpack_require__(80806) -); +class CssLocalIdentifierDependency extends NullDependency { + /** + * @param {string} name name + * @param {[number, number]} range range + * @param {string=} prefix prefix + */ + constructor(name, range, prefix = "") { + super(); + this.name = name; + this.range = range; + this.prefix = prefix; + } -const getSchema = name => { - const { definitions } = __webpack_require__(73342); - return { - definitions, - oneOf: [{ $ref: `#/definitions/${name}` }] - }; -}; + get type() { + return "css local identifier"; + } -const validateGeneratorOptions = createSchemaValidation( - __webpack_require__(59170), - () => getSchema("CssGeneratorOptions"), - { - name: "Css Modules Plugin", - baseDataPath: "parser" + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + const name = this.name; + return { + exports: [ + { + name, + canMangle: true + } + ], + dependencies: undefined + }; } -); -const validateParserOptions = createSchemaValidation( - __webpack_require__(38542), - () => getSchema("CssParserOptions"), - { - name: "Css Modules Plugin", - baseDataPath: "parser" + + serialize(context) { + const { write } = context; + write(this.name); + write(this.range); + write(this.prefix); + super.serialize(context); } -); -const escapeCss = (str, omitOptionalUnderscore) => { + deserialize(context) { + const { read } = context; + this.name = read(); + this.range = read(); + this.prefix = read(); + super.deserialize(context); + } +} + +const escapeCssIdentifier = (str, omitUnderscore) => { const escaped = `${str}`.replace( // cspell:word uffff /[^a-zA-Z0-9_\u0081-\uffff-]/g, s => `\\${s}` ); - return !omitOptionalUnderscore && /^(?!--)[0-9_-]/.test(escaped) + return !omitUnderscore && /^(?!--)[0-9-]/.test(escaped) ? `_${escaped}` : escaped; }; -const plugin = "CssModulesPlugin"; - -class CssModulesPlugin { - /** - * @param {CssExperimentOptions} options options - */ - constructor({ exportsOnly = false }) { - this._exportsOnly = exportsOnly; - } +CssLocalIdentifierDependency.Template = class CssLocalIdentifierDependencyTemplate extends ( + NullDependency.Template +) { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @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(compiler) { - compiler.hooks.compilation.tap( - plugin, - (compilation, { normalModuleFactory }) => { - const selfFactory = new SelfModuleFactory(compilation.moduleGraph); - compilation.dependencyFactories.set( - CssUrlDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - CssUrlDependency, - new CssUrlDependency.Template() - ); - compilation.dependencyTemplates.set( - CssLocalIdentifierDependency, - new CssLocalIdentifierDependency.Template() - ); - compilation.dependencyFactories.set( - CssSelfLocalIdentifierDependency, - selfFactory - ); - compilation.dependencyTemplates.set( - CssSelfLocalIdentifierDependency, - new CssSelfLocalIdentifierDependency.Template() - ); - compilation.dependencyTemplates.set( - CssExportDependency, - new CssExportDependency.Template() - ); - compilation.dependencyFactories.set( - CssImportDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - CssImportDependency, - new CssImportDependency.Template() - ); - compilation.dependencyTemplates.set( - StaticExportsDependency, - new StaticExportsDependency.Template() - ); - normalModuleFactory.hooks.createParser - .for("css") - .tap(plugin, parserOptions => { - validateParserOptions(parserOptions); - return new CssParser(); - }); - normalModuleFactory.hooks.createParser - .for("css/global") - .tap(plugin, parserOptions => { - validateParserOptions(parserOptions); - return new CssParser({ - allowPseudoBlocks: false, - allowModeSwitch: false - }); - }); - normalModuleFactory.hooks.createParser - .for("css/module") - .tap(plugin, parserOptions => { - validateParserOptions(parserOptions); - return new CssParser({ - defaultMode: "local" - }); - }); - normalModuleFactory.hooks.createGenerator - .for("css") - .tap(plugin, generatorOptions => { - validateGeneratorOptions(generatorOptions); - return this._exportsOnly - ? new CssExportsGenerator() - : new CssGenerator(); - }); - normalModuleFactory.hooks.createGenerator - .for("css/global") - .tap(plugin, generatorOptions => { - validateGeneratorOptions(generatorOptions); - return this._exportsOnly - ? new CssExportsGenerator() - : new CssGenerator(); - }); - normalModuleFactory.hooks.createGenerator - .for("css/module") - .tap(plugin, generatorOptions => { - validateGeneratorOptions(generatorOptions); - return this._exportsOnly - ? new CssExportsGenerator() - : new CssGenerator(); - }); - const orderedCssModulesPerChunk = new WeakMap(); - compilation.hooks.afterCodeGeneration.tap("CssModulesPlugin", () => { - const { chunkGraph } = compilation; - for (const chunk of compilation.chunks) { - if (CssModulesPlugin.chunkHasCss(chunk, chunkGraph)) { - orderedCssModulesPerChunk.set( - chunk, - this.getOrderedChunkCssModules(chunk, chunkGraph, compilation) - ); - } - } - }); - compilation.hooks.contentHash.tap("CssModulesPlugin", chunk => { - const { - chunkGraph, - outputOptions: { - hashSalt, - hashDigest, - hashDigestLength, - hashFunction - } - } = compilation; - const modules = orderedCssModulesPerChunk.get(chunk); - if (modules === undefined) return; - const hash = createHash(hashFunction); - if (hashSalt) hash.update(hashSalt); - for (const module of modules) { - hash.update(chunkGraph.getModuleHash(module, chunk.runtime)); - } - const digest = /** @type {string} */ (hash.digest(hashDigest)); - chunk.contentHash.css = digest.substr(0, hashDigestLength); - }); - compilation.hooks.renderManifest.tap(plugin, (result, options) => { - const { chunkGraph } = compilation; - const { hash, chunk, codeGenerationResults } = options; + apply( + dependency, + source, + { module, moduleGraph, chunkGraph, runtime, runtimeTemplate, cssExports } + ) { + const dep = /** @type {CssLocalIdentifierDependency} */ (dependency); + const used = moduleGraph + .getExportInfo(module, dep.name) + .getUsedName(dep.name, runtime); + const moduleId = chunkGraph.getModuleId(module); + const identifier = + dep.prefix + + (runtimeTemplate.outputOptions.uniqueName + ? runtimeTemplate.outputOptions.uniqueName + "-" + : "") + + (used ? moduleId + "-" + used : "-"); + source.replace( + dep.range[0], + dep.range[1] - 1, + escapeCssIdentifier(identifier, dep.prefix) + ); + if (used) cssExports.set(used, identifier); + } +}; - if (chunk instanceof HotUpdateChunk) return result; +makeSerializable( + CssLocalIdentifierDependency, + "webpack/lib/dependencies/CssLocalIdentifierDependency" +); - const modules = orderedCssModulesPerChunk.get(chunk); - if (modules !== undefined) { - result.push({ - render: () => - this.renderChunk({ - chunk, - chunkGraph, - codeGenerationResults, - uniqueName: compilation.outputOptions.uniqueName, - modules - }), - filenameTemplate: CssModulesPlugin.getChunkFilenameTemplate( - chunk, - compilation.outputOptions - ), - pathOptions: { - hash, - runtime: chunk.runtime, - chunk, - contentHashType: "css" - }, - identifier: `css${chunk.id}`, - hash: chunk.contentHash.css - }); - } - return result; - }); - const enabledChunks = new WeakSet(); - const handler = (chunk, set) => { - if (enabledChunks.has(chunk)) { - return; - } - enabledChunks.add(chunk); +module.exports = CssLocalIdentifierDependency; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.getChunkCssFilename); - set.add(RuntimeGlobals.hasOwnProperty); - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.makeNamespaceObject); - const CssLoadingRuntimeModule = getCssLoadingRuntimeModule(); - compilation.addRuntimeModule(chunk, new CssLoadingRuntimeModule(set)); - }; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hasCssModules) - .tap(plugin, handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap(plugin, handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap(plugin, handler); - } - ); +/***/ }), + +/***/ 29094: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +const Dependency = __webpack_require__(54912); +const makeSerializable = __webpack_require__(33032); +const CssLocalIdentifierDependency = __webpack_require__(92328); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class CssSelfLocalIdentifierDependency extends CssLocalIdentifierDependency { + /** + * @param {string} name name + * @param {[number, number]} range range + * @param {string=} prefix prefix + * @param {Set=} declaredSet set of declared names (will only be active when in declared set) + */ + constructor(name, range, prefix = "", declaredSet = undefined) { + super(name, range, prefix); + this.declaredSet = declaredSet; } - getModulesInOrder(chunk, modules, compilation) { - if (!modules) return []; + get type() { + return "css self local identifier"; + } - const modulesList = [...modules]; + get category() { + return "self"; + } - // Get ordered list of modules per chunk group - // Lists are in reverse order to allow to use Array.pop() - const modulesByChunkGroup = Array.from(chunk.groupsIterable, chunkGroup => { - const sortedModules = modulesList - .map(module => { - return { - module, - index: chunkGroup.getModulePostOrderIndex(module) - }; - }) - .filter(item => item.index !== undefined) - .sort((a, b) => b.index - a.index) - .map(item => item.module); + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return `self`; + } + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + if (this.declaredSet && !this.declaredSet.has(this.name)) return; + return super.getExports(moduleGraph); + } - return { list: sortedModules, set: new Set(sortedModules) }; - }); + /** + * 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) { + if (this.declaredSet && !this.declaredSet.has(this.name)) + return Dependency.NO_EXPORTS_REFERENCED; + return [[this.name]]; + } - if (modulesByChunkGroup.length === 1) - return modulesByChunkGroup[0].list.reverse(); + serialize(context) { + const { write } = context; + write(this.declaredSet); + super.serialize(context); + } - const compareModuleLists = ({ list: a }, { list: b }) => { - if (a.length === 0) { - return b.length === 0 ? 0 : 1; - } else { - if (b.length === 0) return -1; - return compareModulesByIdentifier(a[a.length - 1], b[b.length - 1]); - } - }; + deserialize(context) { + const { read } = context; + this.declaredSet = read(); + super.deserialize(context); + } +} - modulesByChunkGroup.sort(compareModuleLists); +CssSelfLocalIdentifierDependency.Template = class CssSelfLocalIdentifierDependencyTemplate extends ( + CssLocalIdentifierDependency.Template +) { + /** + * @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 dep = /** @type {CssSelfLocalIdentifierDependency} */ (dependency); + if (dep.declaredSet && !dep.declaredSet.has(dep.name)) return; + super.apply(dependency, source, templateContext); + } +}; - const finalModules = []; +makeSerializable( + CssSelfLocalIdentifierDependency, + "webpack/lib/dependencies/CssSelfLocalIdentifierDependency" +); - for (;;) { - const failedModules = new Set(); - const list = modulesByChunkGroup[0].list; - if (list.length === 0) { - // done, everything empty +module.exports = CssSelfLocalIdentifierDependency; + + +/***/ }), + +/***/ 70749: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +const makeSerializable = __webpack_require__(33032); +const memoize = __webpack_require__(78676); +const ModuleDependency = __webpack_require__(80321); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +const getRawDataUrlModule = memoize(() => __webpack_require__(19684)); + +class CssUrlDependency extends ModuleDependency { + /** + * @param {string} request request + * @param {[number, number]} range range of the argument + * @param {string} cssFunctionKind kind of css function, e. g. url(), image() + */ + constructor(request, range, cssFunctionKind) { + super(request); + this.range = range; + this.cssFunctionKind = cssFunctionKind; + } + + get type() { + return "css url()"; + } + + get category() { + return "url"; + } + + /** + * @param {string} context context directory + * @returns {Module} a module + */ + createIgnoredModule(context) { + const RawDataUrlModule = getRawDataUrlModule(); + return new RawDataUrlModule("data:,", `ignored-asset`, `(ignored asset)`); + } + + serialize(context) { + const { write } = context; + write(this.cssFunctionKind); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.cssFunctionKind = read(); + super.deserialize(context); + } +} + +const cssEscapeString = str => { + let countWhiteOrBracket = 0; + let countQuotation = 0; + let countApostrophe = 0; + for (let i = 0; i < str.length; i++) { + const cc = str.charCodeAt(i); + switch (cc) { + case 9: // tab + case 10: // nl + case 32: // space + case 40: // ( + case 41: // ) + countWhiteOrBracket++; break; - } - let selectedModule = list[list.length - 1]; - let hasFailed = undefined; - outer: for (;;) { - for (const { list, set } of modulesByChunkGroup) { - if (list.length === 0) continue; - const lastModule = list[list.length - 1]; - if (lastModule === selectedModule) continue; - if (!set.has(selectedModule)) continue; - failedModules.add(selectedModule); - if (failedModules.has(lastModule)) { - // There is a conflict, try other alternatives - hasFailed = lastModule; - continue; - } - selectedModule = lastModule; - hasFailed = false; - continue outer; // restart - } + case 34: + countQuotation++; + break; + case 39: + countApostrophe++; break; - } - if (hasFailed) { - // There is a not resolve-able conflict with the selectedModule - if (compilation) { - // TODO print better warning - compilation.warnings.push( - new Error( - `chunk ${ - chunk.name || chunk.id - }\nConflicting order between ${hasFailed.readableIdentifier( - compilation.requestShortener - )} and ${selectedModule.readableIdentifier( - compilation.requestShortener - )}` - ) - ); - } - selectedModule = hasFailed; - } - // Insert the selected module into the final modules list - finalModules.push(selectedModule); - // Remove the selected module from all lists - for (const { list, set } of modulesByChunkGroup) { - const lastModule = list[list.length - 1]; - if (lastModule === selectedModule) list.pop(); - else if (hasFailed && set.has(selectedModule)) { - const idx = list.indexOf(selectedModule); - if (idx >= 0) list.splice(idx, 1); - } - } - modulesByChunkGroup.sort(compareModuleLists); } - return finalModules; } - - getOrderedChunkCssModules(chunk, chunkGraph, compilation) { - return [ - ...this.getModulesInOrder( - chunk, - chunkGraph.getOrderedChunkModulesIterableBySourceType( - chunk, - "css-import", - compareModulesByIdentifier - ), - compilation - ), - ...this.getModulesInOrder( - chunk, - chunkGraph.getOrderedChunkModulesIterableBySourceType( - chunk, - "css", - compareModulesByIdentifier - ), - compilation - ) - ]; + if (countWhiteOrBracket < 2) { + return str.replace(/[\n\t ()'"\\]/g, m => `\\${m}`); + } else if (countQuotation <= countApostrophe) { + return `"${str.replace(/[\n"\\]/g, m => `\\${m}`)}"`; + } else { + return `'${str.replace(/[\n'\\]/g, m => `\\${m}`)}'`; } +}; - renderChunk({ - uniqueName, - chunk, - chunkGraph, - codeGenerationResults, - modules - }) { - const source = new ConcatSource(); - const metaData = []; - for (const module of modules) { - try { - const codeGenResult = codeGenerationResults.get(module, chunk.runtime); +CssUrlDependency.Template = class CssUrlDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @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, + { runtime, moduleGraph, runtimeTemplate, codeGenerationResults } + ) { + const dep = /** @type {CssUrlDependency} */ (dependency); - const s = - codeGenResult.sources.get("css") || - codeGenResult.sources.get("css-import"); - if (s) { - source.add(s); - source.add("\n"); - } - const exports = - codeGenResult.data && codeGenResult.data.get("css-exports"); - const moduleId = chunkGraph.getModuleId(module) + ""; - metaData.push( - `${ - exports - ? Array.from(exports, ([n, v]) => { - const shortcutValue = `${ - uniqueName ? uniqueName + "-" : "" - }${moduleId}-${n}`; - return v === shortcutValue - ? `${escapeCss(n)}/` - : v === "--" + shortcutValue - ? `${escapeCss(n)}%` - : `${escapeCss(n)}(${escapeCss(v)})`; - }).join("") - : "" - }${escapeCss(moduleId)}` - ); - } catch (e) { - e.message += `\nduring rendering of css ${module.identifier()}`; - throw e; - } - } - source.add( - `head{--webpack-${escapeCss( - (uniqueName ? uniqueName + "-" : "") + chunk.id, - true - )}:${metaData.join(",")};}` + source.replace( + dep.range[0], + dep.range[1] - 1, + `${dep.cssFunctionKind}(${cssEscapeString( + runtimeTemplate.assetUrl({ + publicPath: "", + runtime, + module: moduleGraph.getModule(dep), + codeGenerationResults + }) + )})` ); - return source; } +}; - static getChunkFilenameTemplate(chunk, outputOptions) { - if (chunk.cssFilenameTemplate) { - return chunk.cssFilenameTemplate; - } else if (chunk.canBeInitial()) { - return outputOptions.cssFilename; - } else { - return outputOptions.cssChunkFilename; - } +makeSerializable(CssUrlDependency, "webpack/lib/dependencies/CssUrlDependency"); + +module.exports = CssUrlDependency; + + +/***/ }), + +/***/ 22914: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); + +class DelegatedSourceDependency extends ModuleDependency { + constructor(request) { + super(request); } - static chunkHasCss(chunk, chunkGraph) { - return ( - !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css") || - !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css-import") - ); + get type() { + return "delegated source"; + } + + get category() { + return "esm"; } } -module.exports = CssModulesPlugin; +makeSerializable( + DelegatedSourceDependency, + "webpack/lib/dependencies/DelegatedSourceDependency" +); + +module.exports = DelegatedSourceDependency; /***/ }), -/***/ 98305: +/***/ 95666: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -76166,623 +75581,312 @@ module.exports = CssModulesPlugin; -const Parser = __webpack_require__(11715); -const ConstDependency = __webpack_require__(76911); -const CssExportDependency = __webpack_require__(76760); -const CssImportDependency = __webpack_require__(90542); -const CssLocalIdentifierDependency = __webpack_require__(92328); -const CssSelfLocalIdentifierDependency = __webpack_require__(29094); -const CssUrlDependency = __webpack_require__(70749); -const StaticExportsDependency = __webpack_require__(91418); -const walkCssTokens = __webpack_require__(44124); +const Dependency = __webpack_require__(54912); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ +class DllEntryDependency extends Dependency { + constructor(dependencies, name) { + super(); -const CC_LEFT_CURLY = "{".charCodeAt(0); -const CC_RIGHT_CURLY = "}".charCodeAt(0); -const CC_COLON = ":".charCodeAt(0); -const CC_SLASH = "/".charCodeAt(0); -const CC_SEMICOLON = ";".charCodeAt(0); + this.dependencies = dependencies; + this.name = name; + } -const cssUnescape = str => { - return str.replace(/\\([0-9a-fA-F]{1,6}[ \t\n\r\f]?|[\s\S])/g, match => { - if (match.length > 2) { - return String.fromCharCode(parseInt(match.slice(1).trim(), 16)); - } else { - return match[1]; - } - }); -}; + get type() { + return "dll entry"; + } -class LocConverter { - constructor(input) { - this._input = input; - this.line = 1; - this.column = 0; - this.pos = 0; + serialize(context) { + const { write } = context; + + write(this.dependencies); + write(this.name); + + super.serialize(context); } - get(pos) { - if (this.pos !== pos) { - if (this.pos < pos) { - const str = this._input.slice(this.pos, pos); - let i = str.lastIndexOf("\n"); - if (i === -1) { - this.column += str.length; - } else { - this.column = str.length - i - 1; - this.line++; - while (i > 0 && (i = str.lastIndexOf("\n", i - 1)) !== -1) - this.line++; - } - } else { - let i = this._input.lastIndexOf("\n", this.pos); - while (i >= pos) { - this.line--; - i = i > 0 ? this._input.lastIndexOf("\n", i - 1) : -1; - } - this.column = pos - i; - } - this.pos = pos; - } - return this; + deserialize(context) { + const { read } = context; + + this.dependencies = read(); + this.name = read(); + + super.deserialize(context); } } -const CSS_MODE_TOP_LEVEL = 0; -const CSS_MODE_IN_RULE = 1; -const CSS_MODE_IN_LOCAL_RULE = 2; -const CSS_MODE_AT_IMPORT_EXPECT_URL = 3; -// TODO implement layer and supports for @import -const CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS = 4; -const CSS_MODE_AT_IMPORT_EXPECT_MEDIA = 5; -const CSS_MODE_AT_OTHER = 6; +makeSerializable( + DllEntryDependency, + "webpack/lib/dependencies/DllEntryDependency" +); -const explainMode = mode => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: - return "parsing top level css"; - case CSS_MODE_IN_RULE: - return "parsing css rule content (global)"; - case CSS_MODE_IN_LOCAL_RULE: - return "parsing css rule content (local)"; - case CSS_MODE_AT_IMPORT_EXPECT_URL: - return "parsing @import (expecting url)"; - case CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS: - return "parsing @import (expecting optionally supports or media query)"; - case CSS_MODE_AT_IMPORT_EXPECT_MEDIA: - return "parsing @import (expecting optionally media query)"; - case CSS_MODE_AT_OTHER: - return "parsing at-rule"; - default: - return mode; +module.exports = DllEntryDependency; + + +/***/ }), + +/***/ 32006: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("../Parser").ParserState} ParserState */ + +/** @type {WeakMap} */ +const parserStateExportsState = new WeakMap(); + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +exports.bailout = parserState => { + const value = parserStateExportsState.get(parserState); + parserStateExportsState.set(parserState, false); + if (value === true) { + parserState.module.buildMeta.exportsType = undefined; + parserState.module.buildMeta.defaultObject = false; } }; -class CssParser extends Parser { - constructor({ - allowPseudoBlocks = true, - allowModeSwitch = true, - defaultMode = "global" - } = {}) { - super(); - this.allowPseudoBlocks = allowPseudoBlocks; - this.allowModeSwitch = allowModeSwitch; - this.defaultMode = defaultMode; +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +exports.enable = parserState => { + const value = parserStateExportsState.get(parserState); + if (value === false) return; + parserStateExportsState.set(parserState, true); + if (value !== true) { + parserState.module.buildMeta.exportsType = "default"; + parserState.module.buildMeta.defaultObject = "redirect"; } +}; + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +exports.setFlagged = parserState => { + const value = parserStateExportsState.get(parserState); + if (value !== true) return; + const buildMeta = parserState.module.buildMeta; + if (buildMeta.exportsType === "dynamic") return; + buildMeta.exportsType = "flagged"; +}; + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +exports.setDynamic = parserState => { + const value = parserStateExportsState.get(parserState); + if (value !== true) return; + parserState.module.buildMeta.exportsType = "dynamic"; +}; + +/** + * @param {ParserState} parserState parser state + * @returns {boolean} true, when enabled + */ +exports.isEnabled = parserState => { + const value = parserStateExportsState.get(parserState); + return value === true; +}; + + +/***/ }), + +/***/ 3979: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); + +class EntryDependency extends ModuleDependency { /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state + * @param {string} request request path for entry */ - parse(source, state) { - if (Buffer.isBuffer(source)) { - source = source.toString("utf-8"); - } else if (typeof source === "object") { - throw new Error("webpackAst is unexpected for the CssParser"); - } - if (source[0] === "\ufeff") { - source = source.slice(1); - } + constructor(request) { + super(request); + } - const module = state.module; + get type() { + return "entry"; + } - const declaredCssVariables = new Set(); + get category() { + return "esm"; + } +} - const locConverter = new LocConverter(source); - let mode = CSS_MODE_TOP_LEVEL; - let modePos = 0; - let modeNestingLevel = 0; - let modeData = undefined; - let singleClassSelector = undefined; - let lastIdentifier = undefined; - const modeStack = []; - const isTopLevelLocal = () => - modeData === "local" || - (this.defaultMode === "local" && modeData === undefined); - const eatWhiteLine = (input, pos) => { - for (;;) { - const cc = input.charCodeAt(pos); - if (cc === 32 || cc === 9) { - pos++; - continue; +makeSerializable(EntryDependency, "webpack/lib/dependencies/EntryDependency"); + +module.exports = EntryDependency; + + +/***/ }), + +/***/ 78988: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { UsageState } = __webpack_require__(63686); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {Module} module the module + * @param {string | null} exportName name of the export if any + * @param {string | null} property name of the requested property + * @param {RuntimeSpec} runtime for which runtime + * @returns {any} value of the property + */ +const getProperty = (moduleGraph, module, exportName, property, runtime) => { + if (!exportName) { + switch (property) { + case "usedExports": { + const usedExports = moduleGraph + .getExportsInfo(module) + .getUsedExports(runtime); + if ( + typeof usedExports === "boolean" || + usedExports === undefined || + usedExports === null + ) { + return usedExports; } - if (cc === 10) pos++; - break; + return Array.from(usedExports).sort(); } - return pos; - }; - const eatUntil = chars => { - const charCodes = Array.from({ length: chars.length }, (_, i) => - chars.charCodeAt(i) - ); - const arr = Array.from( - { length: charCodes.reduce((a, b) => Math.max(a, b), 0) + 1 }, - () => false + } + } + switch (property) { + case "used": + return ( + moduleGraph.getExportsInfo(module).getUsed(exportName, runtime) !== + UsageState.Unused ); - charCodes.forEach(cc => (arr[cc] = true)); - return (input, pos) => { - for (;;) { - const cc = input.charCodeAt(pos); - if (cc < arr.length && arr[cc]) { - return pos; - } - pos++; - if (pos === input.length) return pos; - } - }; - }; - const eatText = (input, pos, eater) => { - let text = ""; - for (;;) { - if (input.charCodeAt(pos) === CC_SLASH) { - const newPos = walkCssTokens.eatComments(input, pos); - if (pos !== newPos) { - pos = newPos; - if (pos === input.length) break; - } else { - text += "/"; - pos++; - if (pos === input.length) break; - } - } - const newPos = eater(input, pos); - if (pos !== newPos) { - text += input.slice(pos, newPos); - pos = newPos; - } else { - break; - } - if (pos === input.length) break; + case "useInfo": { + const state = moduleGraph + .getExportsInfo(module) + .getUsed(exportName, runtime); + switch (state) { + case UsageState.Used: + case UsageState.OnlyPropertiesUsed: + return true; + case UsageState.Unused: + return false; + case UsageState.NoInfo: + return undefined; + case UsageState.Unknown: + return null; + default: + throw new Error(`Unexpected UsageState ${state}`); } - return [pos, text.trimRight()]; - }; - const eatExportName = eatUntil(":};/"); - const eatExportValue = eatUntil("};/"); - const parseExports = (input, pos) => { - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - const cc = input.charCodeAt(pos); - if (cc !== CC_LEFT_CURLY) - throw new Error( - `Unexpected ${input[pos]} at ${pos} during parsing of ':export' (expected '{')` - ); - pos++; - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - for (;;) { - if (input.charCodeAt(pos) === CC_RIGHT_CURLY) break; - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - if (pos === input.length) return pos; - let start = pos; - let name; - [pos, name] = eatText(input, pos, eatExportName); - if (pos === input.length) return pos; - if (input.charCodeAt(pos) !== CC_COLON) { - throw new Error( - `Unexpected ${input[pos]} at ${pos} during parsing of export name in ':export' (expected ':')` - ); - } - pos++; - if (pos === input.length) return pos; - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - if (pos === input.length) return pos; - let value; - [pos, value] = eatText(input, pos, eatExportValue); - if (pos === input.length) return pos; - const cc = input.charCodeAt(pos); - if (cc === CC_SEMICOLON) { - pos++; - if (pos === input.length) return pos; - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - if (pos === input.length) return pos; - } else if (cc !== CC_RIGHT_CURLY) { - throw new Error( - `Unexpected ${input[pos]} at ${pos} during parsing of export value in ':export' (expected ';' or '}')` - ); - } - const dep = new CssExportDependency(name, value); - const { line: sl, column: sc } = locConverter.get(start); - const { line: el, column: ec } = locConverter.get(pos); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - } - pos++; - if (pos === input.length) return pos; - pos = eatWhiteLine(input, pos); - return pos; - }; - const eatPropertyName = eatUntil(":{};"); - const processLocalDeclaration = (input, pos) => { - modeData = undefined; - const start = pos; - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - const propertyNameStart = pos; - const [propertyNameEnd, propertyName] = eatText( - input, - pos, - eatPropertyName - ); - if (input.charCodeAt(propertyNameEnd) !== CC_COLON) return start; - pos = propertyNameEnd + 1; - if (propertyName.startsWith("--")) { - // CSS Variable - const { line: sl, column: sc } = locConverter.get(propertyNameStart); - const { line: el, column: ec } = locConverter.get(propertyNameEnd); - const name = propertyName.slice(2); - const dep = new CssLocalIdentifierDependency( - name, - [propertyNameStart, propertyNameEnd], - "--" - ); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - declaredCssVariables.add(name); - } else if ( - propertyName === "animation-name" || - propertyName === "animation" - ) { - modeData = "animation"; - lastIdentifier = undefined; - } - return pos; - }; - const processDeclarationValueDone = (input, pos) => { - if (modeData === "animation" && lastIdentifier) { - const { line: sl, column: sc } = locConverter.get(lastIdentifier[0]); - const { line: el, column: ec } = locConverter.get(lastIdentifier[1]); - const name = input.slice(lastIdentifier[0], lastIdentifier[1]); - const dep = new CssSelfLocalIdentifierDependency(name, lastIdentifier); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - } - }; - const eatKeyframes = eatUntil("{};/"); - const eatNameInVar = eatUntil(",)};/"); - walkCssTokens(source, { - isSelector: () => { - return mode !== CSS_MODE_IN_RULE && mode !== CSS_MODE_IN_LOCAL_RULE; - }, - url: (input, start, end, contentStart, contentEnd) => { - const value = cssUnescape(input.slice(contentStart, contentEnd)); - switch (mode) { - case CSS_MODE_AT_IMPORT_EXPECT_URL: { - modeData.url = value; - mode = CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS; - break; - } - case CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS: - case CSS_MODE_AT_IMPORT_EXPECT_MEDIA: - throw new Error( - `Unexpected ${input.slice( - start, - end - )} at ${start} during ${explainMode(mode)}` - ); - default: { - const dep = new CssUrlDependency(value, [start, end], "url"); - const { line: sl, column: sc } = locConverter.get(start); - const { line: el, column: ec } = locConverter.get(end); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - module.addCodeGenerationDependency(dep); - break; - } - } - return end; - }, - string: (input, start, end) => { - switch (mode) { - case CSS_MODE_AT_IMPORT_EXPECT_URL: { - modeData.url = cssUnescape(input.slice(start + 1, end - 1)); - mode = CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS; - break; - } - } - return end; - }, - atKeyword: (input, start, end) => { - const name = input.slice(start, end); - if (name === "@namespace") { - throw new Error("@namespace is not supported in bundled CSS"); - } - if (name === "@import") { - if (mode !== CSS_MODE_TOP_LEVEL) { - throw new Error( - `Unexpected @import at ${start} during ${explainMode(mode)}` - ); - } - mode = CSS_MODE_AT_IMPORT_EXPECT_URL; - modePos = end; - modeData = { - start: start, - url: undefined, - supports: undefined - }; - } - if (name === "@keyframes") { - let pos = end; - pos = walkCssTokens.eatWhitespaceAndComments(input, pos); - if (pos === input.length) return pos; - const [newPos, name] = eatText(input, pos, eatKeyframes); - const { line: sl, column: sc } = locConverter.get(pos); - const { line: el, column: ec } = locConverter.get(newPos); - const dep = new CssLocalIdentifierDependency(name, [pos, newPos]); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - pos = newPos; - if (pos === input.length) return pos; - if (input.charCodeAt(pos) !== CC_LEFT_CURLY) { - throw new Error( - `Unexpected ${input[pos]} at ${pos} during parsing of @keyframes (expected '{')` - ); - } - mode = CSS_MODE_IN_LOCAL_RULE; - modeNestingLevel = 1; - return pos + 1; - } - return end; - }, - semicolon: (input, start, end) => { - switch (mode) { - case CSS_MODE_AT_IMPORT_EXPECT_URL: - throw new Error(`Expected URL for @import at ${start}`); - case CSS_MODE_AT_IMPORT_EXPECT_MEDIA: - case CSS_MODE_AT_IMPORT_EXPECT_SUPPORTS: { - const { line: sl, column: sc } = locConverter.get(modeData.start); - const { line: el, column: ec } = locConverter.get(end); - end = eatWhiteLine(input, end); - const media = input.slice(modePos, start).trim(); - const dep = new CssImportDependency( - modeData.url, - [modeData.start, end], - modeData.supports, - media - ); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - break; - } - case CSS_MODE_IN_LOCAL_RULE: { - processDeclarationValueDone(input, start); - return processLocalDeclaration(input, end); - } - case CSS_MODE_IN_RULE: { - return end; - } - } - mode = CSS_MODE_TOP_LEVEL; - modeData = undefined; - singleClassSelector = undefined; - return end; - }, - leftCurlyBracket: (input, start, end) => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: - mode = isTopLevelLocal() - ? CSS_MODE_IN_LOCAL_RULE - : CSS_MODE_IN_RULE; - modeNestingLevel = 1; - if (mode === CSS_MODE_IN_LOCAL_RULE) - return processLocalDeclaration(input, end); - break; - case CSS_MODE_IN_RULE: - case CSS_MODE_IN_LOCAL_RULE: - modeNestingLevel++; - break; - } - return end; - }, - rightCurlyBracket: (input, start, end) => { - switch (mode) { - case CSS_MODE_IN_LOCAL_RULE: - processDeclarationValueDone(input, start); - /* falls through */ - case CSS_MODE_IN_RULE: - if (--modeNestingLevel === 0) { - mode = CSS_MODE_TOP_LEVEL; - modeData = undefined; - singleClassSelector = undefined; - } - break; - } - return end; - }, - id: (input, start, end) => { - singleClassSelector = false; - switch (mode) { - case CSS_MODE_TOP_LEVEL: - if (isTopLevelLocal()) { - const name = input.slice(start + 1, end); - const dep = new CssLocalIdentifierDependency(name, [ - start + 1, - end - ]); - const { line: sl, column: sc } = locConverter.get(start); - const { line: el, column: ec } = locConverter.get(end); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - } - break; - } - return end; - }, - identifier: (input, start, end) => { - singleClassSelector = false; - switch (mode) { - case CSS_MODE_IN_LOCAL_RULE: - if (modeData === "animation") { - lastIdentifier = [start, end]; - } - break; - } - return end; - }, - class: (input, start, end) => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: { - if (isTopLevelLocal()) { - const name = input.slice(start + 1, end); - const dep = new CssLocalIdentifierDependency(name, [ - start + 1, - end - ]); - const { line: sl, column: sc } = locConverter.get(start); - const { line: el, column: ec } = locConverter.get(end); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - if (singleClassSelector === undefined) singleClassSelector = name; - } else { - singleClassSelector = false; - } - break; - } - } - return end; - }, - leftParenthesis: (input, start, end) => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: { - modeStack.push(false); - break; - } - } - return end; - }, - rightParenthesis: (input, start, end) => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: { - const newModeData = modeStack.pop(); - if (newModeData !== false) { - modeData = newModeData; - const dep = new ConstDependency("", [start, end]); - module.addPresentationalDependency(dep); - } - break; - } - } - return end; - }, - pseudoClass: (input, start, end) => { - singleClassSelector = false; - switch (mode) { - case CSS_MODE_TOP_LEVEL: { - const name = input.slice(start, end); - if (this.allowModeSwitch && name === ":global") { - modeData = "global"; - const dep = new ConstDependency("", [start, end]); - module.addPresentationalDependency(dep); - } else if (this.allowModeSwitch && name === ":local") { - modeData = "local"; - const dep = new ConstDependency("", [start, end]); - module.addPresentationalDependency(dep); - } else if (this.allowPseudoBlocks && name === ":export") { - const pos = parseExports(input, end); - const dep = new ConstDependency("", [start, pos]); - module.addPresentationalDependency(dep); - return pos; - } - break; - } - } - return end; - }, - pseudoFunction: (input, start, end) => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: { - const name = input.slice(start, end - 1); - if (this.allowModeSwitch && name === ":global") { - modeStack.push(modeData); - modeData = "global"; - const dep = new ConstDependency("", [start, end]); - module.addPresentationalDependency(dep); - } else if (this.allowModeSwitch && name === ":local") { - modeStack.push(modeData); - modeData = "local"; - const dep = new ConstDependency("", [start, end]); - module.addPresentationalDependency(dep); - } else { - modeStack.push(false); - } - break; - } - } - return end; - }, - function: (input, start, end) => { - switch (mode) { - case CSS_MODE_IN_LOCAL_RULE: { - const name = input.slice(start, end - 1); - if (name === "var") { - let pos = walkCssTokens.eatWhitespaceAndComments(input, end); - if (pos === input.length) return pos; - const [newPos, name] = eatText(input, pos, eatNameInVar); - if (!name.startsWith("--")) return end; - const { line: sl, column: sc } = locConverter.get(pos); - const { line: el, column: ec } = locConverter.get(newPos); - const dep = new CssSelfLocalIdentifierDependency( - name.slice(2), - [pos, newPos], - "--", - declaredCssVariables - ); - dep.setLoc(sl, sc, el, ec); - module.addDependency(dep); - return newPos; - } - break; - } - } - return end; - }, - comma: (input, start, end) => { - switch (mode) { - case CSS_MODE_TOP_LEVEL: - modeData = undefined; - modeStack.length = 0; - break; - case CSS_MODE_IN_LOCAL_RULE: - processDeclarationValueDone(input, start); - break; - } - return end; - } - }); + } + case "provideInfo": + return moduleGraph.getExportsInfo(module).isExportProvided(exportName); + } + return undefined; +}; - module.buildInfo.strict = true; - module.buildMeta.exportsType = "namespace"; - module.addDependency(new StaticExportsDependency([], true)); - return state; +class ExportsInfoDependency extends NullDependency { + constructor(range, exportName, property) { + super(); + this.range = range; + this.exportName = exportName; + this.property = property; + } + + serialize(context) { + const { write } = context; + write(this.range); + write(this.exportName); + write(this.property); + super.serialize(context); + } + + static deserialize(context) { + const obj = new ExportsInfoDependency( + context.read(), + context.read(), + context.read() + ); + obj.deserialize(context); + return obj; } } -module.exports = CssParser; +makeSerializable( + ExportsInfoDependency, + "webpack/lib/dependencies/ExportsInfoDependency" +); + +ExportsInfoDependency.Template = class ExportsInfoDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, { module, moduleGraph, runtime }) { + const dep = /** @type {ExportsInfoDependency} */ (dependency); + + const value = getProperty( + moduleGraph, + module, + dep.exportName, + dep.property, + runtime + ); + source.replace( + dep.range[0], + dep.range[1] - 1, + value === undefined ? "undefined" : JSON.stringify(value) + ); + } +}; + +module.exports = ExportsInfoDependency; /***/ }), -/***/ 44124: -/***/ (function(module) { +/***/ 23624: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -76792,2048 +75896,2128 @@ module.exports = CssParser; -/** - * @typedef {Object} CssTokenCallbacks - * @property {function(string, number): boolean} isSelector - * @property {function(string, number, number, number, number): number=} url - * @property {function(string, number, number): number=} string - * @property {function(string, number, number): number=} leftParenthesis - * @property {function(string, number, number): number=} rightParenthesis - * @property {function(string, number, number): number=} pseudoFunction - * @property {function(string, number, number): number=} function - * @property {function(string, number, number): number=} pseudoClass - * @property {function(string, number, number): number=} atKeyword - * @property {function(string, number, number): number=} class - * @property {function(string, number, number): number=} identifier - * @property {function(string, number, number): number=} id - * @property {function(string, number, number): number=} leftCurlyBracket - * @property {function(string, number, number): number=} rightCurlyBracket - * @property {function(string, number, number): number=} semicolon - * @property {function(string, number, number): number=} comma - */ +const Template = __webpack_require__(1626); +const makeSerializable = __webpack_require__(33032); +const HarmonyImportDependency = __webpack_require__(57154); +const NullDependency = __webpack_require__(31830); -/** @typedef {function(string, number, CssTokenCallbacks): number} CharHandler */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("./HarmonyAcceptImportDependency")} HarmonyAcceptImportDependency */ -// spec: https://drafts.csswg.org/css-syntax/ +class HarmonyAcceptDependency extends NullDependency { + /** + * @param {[number, number]} range expression range + * @param {HarmonyAcceptImportDependency[]} dependencies import dependencies + * @param {boolean} hasCallback true, if the range wraps an existing callback + */ + constructor(range, dependencies, hasCallback) { + super(); + this.range = range; + this.dependencies = dependencies; + this.hasCallback = hasCallback; + } -const CC_LINE_FEED = "\n".charCodeAt(0); -const CC_CARRIAGE_RETURN = "\r".charCodeAt(0); -const CC_FORM_FEED = "\f".charCodeAt(0); + get type() { + return "accepted harmony modules"; + } -const CC_TAB = "\t".charCodeAt(0); -const CC_SPACE = " ".charCodeAt(0); + serialize(context) { + const { write } = context; + write(this.range); + write(this.dependencies); + write(this.hasCallback); + super.serialize(context); + } -const CC_SLASH = "/".charCodeAt(0); -const CC_BACK_SLASH = "\\".charCodeAt(0); -const CC_ASTERISK = "*".charCodeAt(0); + deserialize(context) { + const { read } = context; + this.range = read(); + this.dependencies = read(); + this.hasCallback = read(); + super.deserialize(context); + } +} -const CC_LEFT_PARENTHESIS = "(".charCodeAt(0); -const CC_RIGHT_PARENTHESIS = ")".charCodeAt(0); -const CC_LEFT_CURLY = "{".charCodeAt(0); -const CC_RIGHT_CURLY = "}".charCodeAt(0); +makeSerializable( + HarmonyAcceptDependency, + "webpack/lib/dependencies/HarmonyAcceptDependency" +); -const CC_QUOTATION_MARK = '"'.charCodeAt(0); -const CC_APOSTROPHE = "'".charCodeAt(0); +HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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 dep = /** @type {HarmonyAcceptDependency} */ (dependency); + const { + module, + runtime, + runtimeRequirements, + runtimeTemplate, + moduleGraph, + chunkGraph + } = templateContext; + const content = dep.dependencies + .map(dependency => { + const referencedModule = moduleGraph.getModule(dependency); + return { + dependency, + runtimeCondition: referencedModule + ? HarmonyImportDependency.Template.getImportEmittedRuntime( + module, + referencedModule + ) + : false + }; + }) + .filter(({ runtimeCondition }) => runtimeCondition !== false) + .map(({ dependency, runtimeCondition }) => { + const condition = runtimeTemplate.runtimeConditionExpression({ + chunkGraph, + runtime, + runtimeCondition, + runtimeRequirements + }); + const s = dependency.getImportStatement(true, templateContext); + const code = s[0] + s[1]; + if (condition !== "true") { + return `if (${condition}) {\n${Template.indent(code)}\n}\n`; + } + return code; + }) + .join(""); -const CC_FULL_STOP = ".".charCodeAt(0); -const CC_COLON = ":".charCodeAt(0); -const CC_SEMICOLON = ";".charCodeAt(0); -const CC_COMMA = ",".charCodeAt(0); -const CC_PERCENTAGE = "%".charCodeAt(0); -const CC_AT_SIGN = "@".charCodeAt(0); + if (dep.hasCallback) { + if (runtimeTemplate.supportsArrowFunction()) { + source.insert( + dep.range[0], + `__WEBPACK_OUTDATED_DEPENDENCIES__ => { ${content}(` + ); + source.insert(dep.range[1], ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }"); + } else { + source.insert( + dep.range[0], + `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(` + ); + source.insert( + dep.range[1], + ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }.bind(this)" + ); + } + return; + } -const CC_LOW_LINE = "_".charCodeAt(0); -const CC_LOWER_A = "a".charCodeAt(0); -const CC_LOWER_U = "u".charCodeAt(0); -const CC_LOWER_E = "e".charCodeAt(0); -const CC_LOWER_Z = "z".charCodeAt(0); -const CC_UPPER_A = "A".charCodeAt(0); -const CC_UPPER_E = "E".charCodeAt(0); -const CC_UPPER_Z = "Z".charCodeAt(0); -const CC_0 = "0".charCodeAt(0); -const CC_9 = "9".charCodeAt(0); + const arrow = runtimeTemplate.supportsArrowFunction(); + source.insert( + dep.range[1] - 0.5, + `, ${arrow ? "() =>" : "function()"} { ${content} }` + ); + } +}; -const CC_NUMBER_SIGN = "#".charCodeAt(0); -const CC_PLUS_SIGN = "+".charCodeAt(0); -const CC_HYPHEN_MINUS = "-".charCodeAt(0); +module.exports = HarmonyAcceptDependency; -const CC_LESS_THAN_SIGN = "<".charCodeAt(0); -const CC_GREATER_THAN_SIGN = ">".charCodeAt(0); -const _isNewLine = cc => { - return ( - cc === CC_LINE_FEED || cc === CC_CARRIAGE_RETURN || cc === CC_FORM_FEED - ); -}; +/***/ }), -/** @type {CharHandler} */ -const consumeSpace = (input, pos, callbacks) => { - let cc; - do { - pos++; - cc = input.charCodeAt(pos); - } while (_isWhiteSpace(cc)); - return pos; -}; +/***/ 99843: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const _isWhiteSpace = cc => { - return ( - cc === CC_LINE_FEED || - cc === CC_CARRIAGE_RETURN || - cc === CC_FORM_FEED || - cc === CC_TAB || - cc === CC_SPACE - ); -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** @type {CharHandler} */ -const consumeSingleCharToken = (input, pos, callbacks) => { - return pos + 1; -}; -/** @type {CharHandler} */ -const consumePotentialComment = (input, pos, callbacks) => { - pos++; - if (pos === input.length) return pos; - let cc = input.charCodeAt(pos); - if (cc !== CC_ASTERISK) return pos; - for (;;) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - while (cc === CC_ASTERISK) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - if (cc === CC_SLASH) return pos + 1; - } - } -}; -/** @type {function(number): CharHandler} */ -const consumeString = end => (input, pos, callbacks) => { - const start = pos; - pos = _consumeString(input, pos, end); - if (callbacks.string !== undefined) { - pos = callbacks.string(input, start, pos); +const makeSerializable = __webpack_require__(33032); +const HarmonyImportDependency = __webpack_require__(57154); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + +class HarmonyAcceptImportDependency extends HarmonyImportDependency { + constructor(request) { + super(request, NaN); + this.weak = true; } - return pos; -}; -const _consumeString = (input, pos, end) => { - pos++; - for (;;) { - if (pos === input.length) return pos; - const cc = input.charCodeAt(pos); - if (cc === end) return pos + 1; - if (_isNewLine(cc)) { - // bad string - return pos; - } - if (cc === CC_BACK_SLASH) { - // we don't need to fully parse the escaped code point - // just skip over a potential new line - pos++; - if (pos === input.length) return pos; - pos++; - } else { - pos++; - } + get type() { + return "harmony accept"; } -}; +} -const _isIdentifierStartCode = cc => { - return ( - cc === CC_LOW_LINE || - (cc >= CC_LOWER_A && cc <= CC_LOWER_Z) || - (cc >= CC_UPPER_A && cc <= CC_UPPER_Z) || - cc > 0x80 - ); -}; +makeSerializable( + HarmonyAcceptImportDependency, + "webpack/lib/dependencies/HarmonyAcceptImportDependency" +); -const _isDigit = cc => { - return cc >= CC_0 && cc <= CC_9; -}; +HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate extends ( + HarmonyImportDependency.Template +) {}; -const _startsIdentifier = (input, pos) => { - const cc = input.charCodeAt(pos); - if (cc === CC_HYPHEN_MINUS) { - if (pos === input.length) return false; - const cc = input.charCodeAt(pos + 1); - if (cc === CC_HYPHEN_MINUS) return true; - if (cc === CC_BACK_SLASH) { - const cc = input.charCodeAt(pos + 2); - return !_isNewLine(cc); - } - return _isIdentifierStartCode(cc); - } - if (cc === CC_BACK_SLASH) { - const cc = input.charCodeAt(pos + 1); - return !_isNewLine(cc); - } - return _isIdentifierStartCode(cc); -}; +module.exports = HarmonyAcceptImportDependency; -/** @type {CharHandler} */ -const consumeNumberSign = (input, pos, callbacks) => { - const start = pos; - pos++; - if (pos === input.length) return pos; - if (callbacks.isSelector(input, pos) && _startsIdentifier(input, pos)) { - pos = _consumeIdentifier(input, pos); - if (callbacks.id !== undefined) { - return callbacks.id(input, start, pos); - } + +/***/ }), + +/***/ 72906: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { UsageState } = __webpack_require__(63686); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ + +class HarmonyCompatibilityDependency extends NullDependency { + get type() { + return "harmony export header"; } - return pos; -}; +} -/** @type {CharHandler} */ -const consumeMinus = (input, pos, callbacks) => { - const start = pos; - pos++; - if (pos === input.length) return pos; - const cc = input.charCodeAt(pos); - if (cc === CC_FULL_STOP || _isDigit(cc)) { - return consumeNumericToken(input, pos, callbacks); - } else if (cc === CC_HYPHEN_MINUS) { - pos++; - if (pos === input.length) return pos; - const cc = input.charCodeAt(pos); - if (cc === CC_GREATER_THAN_SIGN) { - return pos + 1; - } else { - pos = _consumeIdentifier(input, pos); - if (callbacks.identifier !== undefined) { - return callbacks.identifier(input, start, pos); - } +makeSerializable( + HarmonyCompatibilityDependency, + "webpack/lib/dependencies/HarmonyCompatibilityDependency" +); + +HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, + { + module, + runtimeTemplate, + moduleGraph, + initFragments, + runtimeRequirements, + runtime, + concatenationScope } - } else if (cc === CC_BACK_SLASH) { - if (pos + 1 === input.length) return pos; - const cc = input.charCodeAt(pos + 1); - if (_isNewLine(cc)) return pos; - pos = _consumeIdentifier(input, pos); - if (callbacks.identifier !== undefined) { - return callbacks.identifier(input, start, pos); + ) { + if (concatenationScope) return; + const exportsInfo = moduleGraph.getExportsInfo(module); + if ( + exportsInfo.getReadOnlyExportInfo("__esModule").getUsed(runtime) !== + UsageState.Unused + ) { + const content = runtimeTemplate.defineEsModuleFlagStatement({ + exportsArgument: module.exportsArgument, + runtimeRequirements + }); + initFragments.push( + new InitFragment( + content, + InitFragment.STAGE_HARMONY_EXPORTS, + 0, + "harmony compatibility" + ) + ); } - } else if (_isIdentifierStartCode(cc)) { - pos++; - pos = _consumeIdentifier(input, pos); - if (callbacks.identifier !== undefined) { - return callbacks.identifier(input, start, pos); + if (moduleGraph.isAsync(module)) { + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(RuntimeGlobals.asyncModule); + initFragments.push( + new InitFragment( + runtimeTemplate.supportsArrowFunction() + ? `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async (__webpack_handle_async_dependencies__) => {\n` + : `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async function (__webpack_handle_async_dependencies__) {\n`, + InitFragment.STAGE_ASYNC_BOUNDARY, + 0, + undefined, + module.buildMeta.async + ? `\n__webpack_handle_async_dependencies__();\n}, 1);` + : "\n});" + ) + ); } } - return pos; }; -/** @type {CharHandler} */ -const consumeDot = (input, pos, callbacks) => { - const start = pos; - pos++; - if (pos === input.length) return pos; - const cc = input.charCodeAt(pos); - if (_isDigit(cc)) return consumeNumericToken(input, pos - 2, callbacks); - if (!callbacks.isSelector(input, pos) || !_startsIdentifier(input, pos)) - return pos; - pos = _consumeIdentifier(input, pos); - if (callbacks.class !== undefined) return callbacks.class(input, start, pos); - return pos; -}; +module.exports = HarmonyCompatibilityDependency; -/** @type {CharHandler} */ -const consumeNumericToken = (input, pos, callbacks) => { - pos = _consumeNumber(input, pos); - if (pos === input.length) return pos; - if (_startsIdentifier(input, pos)) return _consumeIdentifier(input, pos); - const cc = input.charCodeAt(pos); - if (cc === CC_PERCENTAGE) return pos + 1; - return pos; -}; -/** @type {CharHandler} */ -const consumeOtherIdentifier = (input, pos, callbacks) => { - const start = pos; - pos = _consumeIdentifier(input, pos); - if ( - pos !== input.length && - !callbacks.isSelector(input, pos) && - input.charCodeAt(pos) === CC_LEFT_PARENTHESIS - ) { - pos++; - if (callbacks.function !== undefined) { - return callbacks.function(input, start, pos); - } - } else { - if (callbacks.identifier !== undefined) { - return callbacks.identifier(input, start, pos); - } +/***/ }), + +/***/ 17223: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const DynamicExports = __webpack_require__(32006); +const HarmonyCompatibilityDependency = __webpack_require__(72906); +const HarmonyExports = __webpack_require__(39211); + +module.exports = class HarmonyDetectionParserPlugin { + constructor(options) { + const { topLevelAwait = false } = options || {}; + this.topLevelAwait = topLevelAwait; } - return pos; -}; -/** @type {CharHandler} */ -const consumePotentialUrl = (input, pos, callbacks) => { - const start = pos; - pos = _consumeIdentifier(input, pos); - if (pos === start + 3 && input.slice(start, pos + 1) === "url(") { - pos++; - let cc = input.charCodeAt(pos); - while (_isWhiteSpace(cc)) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - } - if (cc === CC_QUOTATION_MARK || cc === CC_APOSTROPHE) { - pos++; - const contentStart = pos; - pos = _consumeString(input, pos, cc); - const contentEnd = pos - 1; - cc = input.charCodeAt(pos); - while (_isWhiteSpace(cc)) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); + apply(parser) { + parser.hooks.program.tap("HarmonyDetectionParserPlugin", ast => { + const isStrictHarmony = parser.state.module.type === "javascript/esm"; + const isHarmony = + isStrictHarmony || + ast.body.some( + statement => + statement.type === "ImportDeclaration" || + statement.type === "ExportDefaultDeclaration" || + statement.type === "ExportNamedDeclaration" || + statement.type === "ExportAllDeclaration" + ); + if (isHarmony) { + const module = parser.state.module; + const compatDep = new HarmonyCompatibilityDependency(); + compatDep.loc = { + start: { + line: -1, + column: 0 + }, + end: { + line: -1, + column: 0 + }, + index: -3 + }; + module.addPresentationalDependency(compatDep); + DynamicExports.bailout(parser.state); + HarmonyExports.enable(parser.state, isStrictHarmony); + parser.scope.isStrict = true; } - if (cc !== CC_RIGHT_PARENTHESIS) return pos; - pos++; - if (callbacks.url !== undefined) - return callbacks.url(input, start, pos, contentStart, contentEnd); - return pos; - } else { - const contentStart = pos; - let contentEnd; - for (;;) { - if (cc === CC_BACK_SLASH) { - pos++; - if (pos === input.length) return pos; - pos++; - } else if (_isWhiteSpace(cc)) { - contentEnd = pos; - do { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - } while (_isWhiteSpace(cc)); - if (cc !== CC_RIGHT_PARENTHESIS) return pos; - pos++; - if (callbacks.url !== undefined) { - return callbacks.url(input, start, pos, contentStart, contentEnd); - } - return pos; - } else if (cc === CC_RIGHT_PARENTHESIS) { - contentEnd = pos; - pos++; - if (callbacks.url !== undefined) { - return callbacks.url(input, start, pos, contentStart, contentEnd); - } - return pos; - } else if (cc === CC_LEFT_PARENTHESIS) { - return pos; - } else { - pos++; - } - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); + }); + + parser.hooks.topLevelAwait.tap("HarmonyDetectionParserPlugin", () => { + const module = parser.state.module; + if (!this.topLevelAwait) { + throw new Error( + "The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)" + ); } - } - } else { - if (callbacks.identifier !== undefined) { - return callbacks.identifier(input, start, pos); - } - return pos; - } -}; + if (!HarmonyExports.isEnabled(parser.state)) { + throw new Error( + "Top-level-await is only supported in EcmaScript Modules" + ); + } + module.buildMeta.async = true; + }); -/** @type {CharHandler} */ -const consumePotentialPseudo = (input, pos, callbacks) => { - const start = pos; - pos++; - if (!callbacks.isSelector(input, pos) || !_startsIdentifier(input, pos)) - return pos; - pos = _consumeIdentifier(input, pos); - let cc = input.charCodeAt(pos); - if (cc === CC_LEFT_PARENTHESIS) { - pos++; - if (callbacks.pseudoFunction !== undefined) { - return callbacks.pseudoFunction(input, start, pos); + const skipInHarmony = () => { + if (HarmonyExports.isEnabled(parser.state)) { + return true; + } + }; + + const nullInHarmony = () => { + if (HarmonyExports.isEnabled(parser.state)) { + return null; + } + }; + + const nonHarmonyIdentifiers = ["define", "exports"]; + for (const identifier of nonHarmonyIdentifiers) { + parser.hooks.evaluateTypeof + .for(identifier) + .tap("HarmonyDetectionParserPlugin", nullInHarmony); + parser.hooks.typeof + .for(identifier) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + parser.hooks.evaluate + .for(identifier) + .tap("HarmonyDetectionParserPlugin", nullInHarmony); + parser.hooks.expression + .for(identifier) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + parser.hooks.call + .for(identifier) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); } - return pos; - } - if (callbacks.pseudoClass !== undefined) { - return callbacks.pseudoClass(input, start, pos); } - return pos; }; -/** @type {CharHandler} */ -const consumeLeftParenthesis = (input, pos, callbacks) => { - pos++; - if (callbacks.leftParenthesis !== undefined) { - return callbacks.leftParenthesis(input, pos - 1, pos); - } - return pos; -}; -/** @type {CharHandler} */ -const consumeRightParenthesis = (input, pos, callbacks) => { - pos++; - if (callbacks.rightParenthesis !== undefined) { - return callbacks.rightParenthesis(input, pos - 1, pos); - } - return pos; -}; +/***/ }), -/** @type {CharHandler} */ -const consumeLeftCurlyBracket = (input, pos, callbacks) => { - pos++; - if (callbacks.leftCurlyBracket !== undefined) { - return callbacks.leftCurlyBracket(input, pos - 1, pos); - } - return pos; -}; +/***/ 93466: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** @type {CharHandler} */ -const consumeRightCurlyBracket = (input, pos, callbacks) => { - pos++; - if (callbacks.rightCurlyBracket !== undefined) { - return callbacks.rightCurlyBracket(input, pos - 1, pos); - } - return pos; -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** @type {CharHandler} */ -const consumeSemicolon = (input, pos, callbacks) => { - pos++; - if (callbacks.semicolon !== undefined) { - return callbacks.semicolon(input, pos - 1, pos); - } - return pos; -}; -/** @type {CharHandler} */ -const consumeComma = (input, pos, callbacks) => { - pos++; - if (callbacks.comma !== undefined) { - return callbacks.comma(input, pos - 1, pos); - } - return pos; -}; -const _consumeIdentifier = (input, pos) => { - for (;;) { - const cc = input.charCodeAt(pos); - if (cc === CC_BACK_SLASH) { - pos++; - if (pos === input.length) return pos; - pos++; - } else if ( - _isIdentifierStartCode(cc) || - _isDigit(cc) || - cc === CC_HYPHEN_MINUS - ) { - pos++; - } else { - return pos; - } - } -}; +const InnerGraph = __webpack_require__(38988); +const ConstDependency = __webpack_require__(76911); +const HarmonyExportExpressionDependency = __webpack_require__(51340); +const HarmonyExportHeaderDependency = __webpack_require__(38873); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(67157); +const HarmonyExportSpecifierDependency = __webpack_require__(48567); +const { ExportPresenceModes } = __webpack_require__(57154); +const { + harmonySpecifierTag, + getAssertions +} = __webpack_require__(20862); +const HarmonyImportSideEffectDependency = __webpack_require__(73132); -const _consumeNumber = (input, pos) => { - pos++; - if (pos === input.length) return pos; - let cc = input.charCodeAt(pos); - while (_isDigit(cc)) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); +const { HarmonyStarExportsList } = HarmonyExportImportedSpecifierDependency; + +module.exports = class HarmonyExportDependencyParserPlugin { + constructor(options) { + this.exportPresenceMode = + options.reexportExportsPresence !== undefined + ? ExportPresenceModes.fromUserOption(options.reexportExportsPresence) + : options.exportsPresence !== undefined + ? ExportPresenceModes.fromUserOption(options.exportsPresence) + : options.strictExportPresence + ? ExportPresenceModes.ERROR + : ExportPresenceModes.AUTO; } - if (cc === CC_FULL_STOP && pos + 1 !== input.length) { - const next = input.charCodeAt(pos + 1); - if (_isDigit(next)) { - pos += 2; - cc = input.charCodeAt(pos); - while (_isDigit(cc)) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); + + apply(parser) { + const { exportPresenceMode } = this; + parser.hooks.export.tap( + "HarmonyExportDependencyParserPlugin", + statement => { + const dep = new HarmonyExportHeaderDependency( + statement.declaration && statement.declaration.range, + statement.range + ); + dep.loc = Object.create(statement.loc); + dep.loc.index = -1; + parser.state.module.addPresentationalDependency(dep); + return true; } - } - } - if (cc === CC_LOWER_E || cc === CC_UPPER_E) { - if (pos + 1 !== input.length) { - const next = input.charCodeAt(pos + 2); - if (_isDigit(next)) { - pos += 2; - } else if ( - (next === CC_HYPHEN_MINUS || next === CC_PLUS_SIGN) && - pos + 2 !== input.length - ) { - const next = input.charCodeAt(pos + 2); - if (_isDigit(next)) { - pos += 3; + ); + parser.hooks.exportImport.tap( + "HarmonyExportDependencyParserPlugin", + (statement, source) => { + parser.state.lastHarmonyImportOrder = + (parser.state.lastHarmonyImportOrder || 0) + 1; + const clearDep = new ConstDependency("", statement.range); + clearDep.loc = Object.create(statement.loc); + clearDep.loc.index = -1; + parser.state.module.addPresentationalDependency(clearDep); + const sideEffectDep = new HarmonyImportSideEffectDependency( + source, + parser.state.lastHarmonyImportOrder, + getAssertions(statement) + ); + sideEffectDep.loc = Object.create(statement.loc); + sideEffectDep.loc.index = -1; + parser.state.current.addDependency(sideEffectDep); + return true; + } + ); + parser.hooks.exportExpression.tap( + "HarmonyExportDependencyParserPlugin", + (statement, expr) => { + const isFunctionDeclaration = expr.type === "FunctionDeclaration"; + const comments = parser.getComments([ + statement.range[0], + expr.range[0] + ]); + const dep = new HarmonyExportExpressionDependency( + expr.range, + statement.range, + comments + .map(c => { + switch (c.type) { + case "Block": + return `/*${c.value}*/`; + case "Line": + return `//${c.value}\n`; + } + return ""; + }) + .join(""), + expr.type.endsWith("Declaration") && expr.id + ? expr.id.name + : isFunctionDeclaration + ? { + id: expr.id ? expr.id.name : undefined, + range: [ + expr.range[0], + expr.params.length > 0 + ? expr.params[0].range[0] + : expr.body.range[0] + ], + prefix: `${expr.async ? "async " : ""}function${ + expr.generator ? "*" : "" + } `, + suffix: `(${expr.params.length > 0 ? "" : ") "}` + } + : undefined + ); + dep.loc = Object.create(statement.loc); + dep.loc.index = -1; + parser.state.current.addDependency(dep); + InnerGraph.addVariableUsage( + parser, + expr.type.endsWith("Declaration") && expr.id + ? expr.id.name + : "*default*", + "default" + ); + return true; + } + ); + parser.hooks.exportSpecifier.tap( + "HarmonyExportDependencyParserPlugin", + (statement, id, name, idx) => { + const settings = parser.getTagData(id, harmonySpecifierTag); + let dep; + const harmonyNamedExports = (parser.state.harmonyNamedExports = + parser.state.harmonyNamedExports || new Set()); + harmonyNamedExports.add(name); + InnerGraph.addVariableUsage(parser, id, name); + if (settings) { + dep = new HarmonyExportImportedSpecifierDependency( + settings.source, + settings.sourceOrder, + settings.ids, + name, + harmonyNamedExports, + null, + exportPresenceMode, + null, + settings.assertions + ); } else { - return pos; + dep = new HarmonyExportSpecifierDependency(id, name); } - } else { - return pos; + dep.loc = Object.create(statement.loc); + dep.loc.index = idx; + parser.state.current.addDependency(dep); + return true; } - } - } else { - return pos; - } - cc = input.charCodeAt(pos); - while (_isDigit(cc)) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); + ); + parser.hooks.exportImportSpecifier.tap( + "HarmonyExportDependencyParserPlugin", + (statement, source, id, name, idx) => { + const harmonyNamedExports = (parser.state.harmonyNamedExports = + parser.state.harmonyNamedExports || new Set()); + let harmonyStarExports = null; + if (name) { + harmonyNamedExports.add(name); + } else { + harmonyStarExports = parser.state.harmonyStarExports = + parser.state.harmonyStarExports || new HarmonyStarExportsList(); + } + const dep = new HarmonyExportImportedSpecifierDependency( + source, + parser.state.lastHarmonyImportOrder, + id ? [id] : [], + name, + harmonyNamedExports, + harmonyStarExports && harmonyStarExports.slice(), + exportPresenceMode, + harmonyStarExports + ); + if (harmonyStarExports) { + harmonyStarExports.push(dep); + } + dep.loc = Object.create(statement.loc); + dep.loc.index = idx; + parser.state.current.addDependency(dep); + return true; + } + ); } - return pos; }; -/** @type {CharHandler} */ -const consumeLessThan = (input, pos, callbacks) => { - if (input.slice(pos + 1, pos + 4) === "!--") return pos + 4; - return pos + 1; -}; -/** @type {CharHandler} */ -const consumeAt = (input, pos, callbacks) => { - const start = pos; - pos++; - if (pos === input.length) return pos; - if (_startsIdentifier(input, pos)) { - pos = _consumeIdentifier(input, pos); - if (callbacks.atKeyword !== undefined) { - pos = callbacks.atKeyword(input, start, pos); - } +/***/ }), + +/***/ 51340: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const ConcatenationScope = __webpack_require__(98229); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const HarmonyExportInitFragment = __webpack_require__(89500); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ + +class HarmonyExportExpressionDependency extends NullDependency { + constructor(range, rangeStatement, prefix, declarationId) { + super(); + this.range = range; + this.rangeStatement = rangeStatement; + this.prefix = prefix; + this.declarationId = declarationId; } - return pos; -}; -const CHAR_MAP = Array.from({ length: 0x80 }, (_, cc) => { - // https://drafts.csswg.org/css-syntax/#consume-token - switch (cc) { - case CC_LINE_FEED: - case CC_CARRIAGE_RETURN: - case CC_FORM_FEED: - case CC_TAB: - case CC_SPACE: - return consumeSpace; - case CC_QUOTATION_MARK: - case CC_APOSTROPHE: - return consumeString(cc); - case CC_NUMBER_SIGN: - return consumeNumberSign; - case CC_SLASH: - return consumePotentialComment; - // case CC_LEFT_SQUARE: - // case CC_RIGHT_SQUARE: - // case CC_COMMA: - // case CC_COLON: - // return consumeSingleCharToken; - case CC_COMMA: - return consumeComma; - case CC_SEMICOLON: - return consumeSemicolon; - case CC_LEFT_PARENTHESIS: - return consumeLeftParenthesis; - case CC_RIGHT_PARENTHESIS: - return consumeRightParenthesis; - case CC_LEFT_CURLY: - return consumeLeftCurlyBracket; - case CC_RIGHT_CURLY: - return consumeRightCurlyBracket; - case CC_COLON: - return consumePotentialPseudo; - case CC_PLUS_SIGN: - return consumeNumericToken; - case CC_FULL_STOP: - return consumeDot; - case CC_HYPHEN_MINUS: - return consumeMinus; - case CC_LESS_THAN_SIGN: - return consumeLessThan; - case CC_AT_SIGN: - return consumeAt; - case CC_LOWER_U: - return consumePotentialUrl; - case CC_LOW_LINE: - return consumeOtherIdentifier; - default: - if (_isDigit(cc)) return consumeNumericToken; - if ( - (cc >= CC_LOWER_A && cc <= CC_LOWER_Z) || - (cc >= CC_UPPER_A && cc <= CC_UPPER_Z) - ) { - return consumeOtherIdentifier; - } - return consumeSingleCharToken; + get type() { + return "harmony export expression"; } -}); -/** - * @param {string} input input css - * @param {CssTokenCallbacks} callbacks callbacks - * @returns {void} - */ -module.exports = (input, callbacks) => { - let pos = 0; - while (pos < input.length) { - const cc = input.charCodeAt(pos); - if (cc < 0x80) { - pos = CHAR_MAP[cc](input, pos, callbacks); - } else { - pos++; - } + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + return { + exports: ["default"], + priority: 1, + terminalBinding: true, + dependencies: undefined + }; } -}; -module.exports.eatComments = (input, pos) => { - loop: for (;;) { - const cc = input.charCodeAt(pos); - if (cc === CC_SLASH) { - if (pos === input.length) return pos; - let cc = input.charCodeAt(pos + 1); - if (cc !== CC_ASTERISK) return pos; - pos++; - for (;;) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - while (cc === CC_ASTERISK) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - if (cc === CC_SLASH) { - pos++; - continue loop; - } + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + // The expression/declaration is already covered by SideEffectsFlagPlugin + return false; + } + + serialize(context) { + const { write } = context; + write(this.range); + write(this.rangeStatement); + write(this.prefix); + write(this.declarationId); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.range = read(); + this.rangeStatement = read(); + this.prefix = read(); + this.declarationId = read(); + super.deserialize(context); + } +} + +makeSerializable( + HarmonyExportExpressionDependency, + "webpack/lib/dependencies/HarmonyExportExpressionDependency" +); + +HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, + { + module, + moduleGraph, + runtimeTemplate, + runtimeRequirements, + initFragments, + runtime, + concatenationScope + } + ) { + const dep = /** @type {HarmonyExportExpressionDependency} */ (dependency); + const { declarationId } = dep; + const exportsName = module.exportsArgument; + if (declarationId) { + let name; + if (typeof declarationId === "string") { + name = declarationId; + } else { + name = ConcatenationScope.DEFAULT_EXPORT; + source.replace( + declarationId.range[0], + declarationId.range[1] - 1, + `${declarationId.prefix}${name}${declarationId.suffix}` + ); + } + + if (concatenationScope) { + concatenationScope.registerExport("default", name); + } else { + const used = moduleGraph + .getExportsInfo(module) + .getUsedName("default", runtime); + if (used) { + const map = new Map(); + map.set(used, `/* export default binding */ ${name}`); + initFragments.push(new HarmonyExportInitFragment(exportsName, map)); } } - } - return pos; - } -}; -module.exports.eatWhitespaceAndComments = (input, pos) => { - loop: for (;;) { - const cc = input.charCodeAt(pos); - if (cc === CC_SLASH) { - if (pos === input.length) return pos; - let cc = input.charCodeAt(pos + 1); - if (cc !== CC_ASTERISK) return pos; - pos++; - for (;;) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - while (cc === CC_ASTERISK) { - pos++; - if (pos === input.length) return pos; - cc = input.charCodeAt(pos); - if (cc === CC_SLASH) { - pos++; - continue loop; + source.replace( + dep.rangeStatement[0], + dep.range[0] - 1, + `/* harmony default export */ ${dep.prefix}` + ); + } else { + let content; + const name = ConcatenationScope.DEFAULT_EXPORT; + if (runtimeTemplate.supportsConst()) { + content = `/* harmony default export */ const ${name} = `; + if (concatenationScope) { + concatenationScope.registerExport("default", name); + } else { + const used = moduleGraph + .getExportsInfo(module) + .getUsedName("default", runtime); + if (used) { + runtimeRequirements.add(RuntimeGlobals.exports); + const map = new Map(); + map.set(used, name); + initFragments.push(new HarmonyExportInitFragment(exportsName, map)); + } else { + content = `/* unused harmony default export */ var ${name} = `; } } + } else if (concatenationScope) { + content = `/* harmony default export */ var ${name} = `; + concatenationScope.registerExport("default", name); + } else { + const used = moduleGraph + .getExportsInfo(module) + .getUsedName("default", runtime); + if (used) { + runtimeRequirements.add(RuntimeGlobals.exports); + // This is a little bit incorrect as TDZ is not correct, but we can't use const. + content = `/* harmony default export */ ${exportsName}[${JSON.stringify( + used + )}] = `; + } else { + content = `/* unused harmony default export */ var ${name} = `; + } } - } else if (_isWhiteSpace(cc)) { - pos++; - continue; + + if (dep.range) { + source.replace( + dep.rangeStatement[0], + dep.range[0] - 1, + content + "(" + dep.prefix + ); + source.replace(dep.range[1], dep.rangeStatement[1] - 0.5, ");"); + return; + } + + source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); } - return pos; } }; +module.exports = HarmonyExportExpressionDependency; + /***/ }), -/***/ 2757: +/***/ 38873: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const { Tracer } = __webpack_require__(5787); -const createSchemaValidation = __webpack_require__(32540); -const { dirname, mkdirpSync } = __webpack_require__(17139); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -/** @typedef {import("../../declarations/plugins/debug/ProfilingPlugin").ProfilingPluginOptions} ProfilingPluginOptions */ -/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -const validate = createSchemaValidation( - __webpack_require__(37134), - () => __webpack_require__(50686), - { - name: "Profiling Plugin", - baseDataPath: "options" +class HarmonyExportHeaderDependency extends NullDependency { + constructor(range, rangeStatement) { + super(); + this.range = range; + this.rangeStatement = rangeStatement; } -); -let inspector = undefined; - -try { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - inspector = __webpack_require__(31405); -} catch (e) { - console.log("Unable to CPU profile in < node 8.0"); -} -class Profiler { - constructor(inspector) { - this.session = undefined; - this.inspector = inspector; - this._startTime = 0; + get type() { + return "harmony export header"; } - hasSession() { - return this.session !== undefined; + serialize(context) { + const { write } = context; + write(this.range); + write(this.rangeStatement); + super.serialize(context); } - startProfiling() { - if (this.inspector === undefined) { - return Promise.resolve(); - } - - try { - this.session = new inspector.Session(); - this.session.connect(); - } catch (_) { - this.session = undefined; - return Promise.resolve(); - } + deserialize(context) { + const { read } = context; + this.range = read(); + this.rangeStatement = read(); + super.deserialize(context); + } +} - const hrtime = process.hrtime(); - this._startTime = hrtime[0] * 1000000 + Math.round(hrtime[1] / 1000); +makeSerializable( + HarmonyExportHeaderDependency, + "webpack/lib/dependencies/HarmonyExportHeaderDependency" +); - return Promise.all([ - this.sendCommand("Profiler.setSamplingInterval", { - interval: 100 - }), - this.sendCommand("Profiler.enable"), - this.sendCommand("Profiler.start") - ]); +HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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 dep = /** @type {HarmonyExportHeaderDependency} */ (dependency); + const content = ""; + const replaceUntil = dep.range + ? dep.range[0] - 1 + : dep.rangeStatement[1] - 1; + source.replace(dep.rangeStatement[0], replaceUntil, content); } +}; - sendCommand(method, params) { - if (this.hasSession()) { - return new Promise((res, rej) => { - return this.session.post(method, params, (err, params) => { - if (err !== null) { - rej(err); - } else { - res(params); - } - }); - }); - } else { - return Promise.resolve(); - } - } +module.exports = HarmonyExportHeaderDependency; - destroy() { - if (this.hasSession()) { - this.session.disconnect(); - } - return Promise.resolve(); - } +/***/ }), - stopProfiling() { - return this.sendCommand("Profiler.stop").then(({ profile }) => { - const hrtime = process.hrtime(); - const endTime = hrtime[0] * 1000000 + Math.round(hrtime[1] / 1000); - if (profile.startTime < this._startTime || profile.endTime > endTime) { - // In some cases timestamps mismatch and we need to adjust them - // Both process.hrtime and the inspector timestamps claim to be relative - // to a unknown point in time. But they do not guarantee that this is the - // same point in time. - const duration = profile.endTime - profile.startTime; - const ownDuration = endTime - this._startTime; - const untracked = Math.max(0, ownDuration - duration); - profile.startTime = this._startTime + untracked / 2; - profile.endTime = endTime - untracked / 2; - } - return { profile }; - }); - } -} +/***/ 67157: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * an object that wraps Tracer and Profiler with a counter - * @typedef {Object} Trace - * @property {Tracer} trace instance of Tracer - * @property {number} counter Counter - * @property {Profiler} profiler instance of Profiler - * @property {Function} end the end function - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * @param {IntermediateFileSystem} fs filesystem used for output - * @param {string} outputPath The location where to write the log. - * @returns {Trace} The trace object - */ -const createTrace = (fs, outputPath) => { - const trace = new Tracer(); - const profiler = new Profiler(inspector); - if (/\/|\\/.test(outputPath)) { - const dirPath = dirname(fs, outputPath); - mkdirpSync(fs, dirPath); - } - const fsStream = fs.createWriteStream(outputPath); - let counter = 0; - trace.pipe(fsStream); - // These are critical events that need to be inserted so that tools like - // chrome dev tools can load the profile. - trace.instantEvent({ - name: "TracingStartedInPage", - id: ++counter, - cat: ["disabled-by-default-devtools.timeline"], - args: { - data: { - sessionId: "-1", - page: "0xfff", - frames: [ - { - frame: "0xfff", - url: "webpack", - name: "" - } - ] - } - } - }); +const Dependency = __webpack_require__(54912); +const { UsageState } = __webpack_require__(63686); +const HarmonyLinkingError = __webpack_require__(97511); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const { countIterable } = __webpack_require__(39104); +const { first, combine } = __webpack_require__(93347); +const makeSerializable = __webpack_require__(33032); +const propertyAccess = __webpack_require__(54190); +const { getRuntimeKey, keyToRuntime } = __webpack_require__(17156); +const HarmonyExportInitFragment = __webpack_require__(89500); +const HarmonyImportDependency = __webpack_require__(57154); +const processExportInfo = __webpack_require__(55207); - trace.instantEvent({ - name: "TracingStartedInBrowser", - id: ++counter, - cat: ["disabled-by-default-devtools.timeline"], - args: { - data: { - sessionId: "-1" - } - } - }); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ExportsInfo")} ExportsInfo */ +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ +/** @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 */ - return { - trace, - counter, - profiler, - end: callback => { - trace.push("]"); - // Wait until the write stream finishes. - fsStream.on("close", () => { - callback(); - }); - // Tear down the readable trace stream. - trace.push(null); - } - }; -}; +/** @typedef {"missing"|"unused"|"empty-star"|"reexport-dynamic-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-fake-namespace-object"|"reexport-undefined"|"normal-reexport"|"dynamic-reexport"} ExportModeType */ -const pluginName = "ProfilingPlugin"; +const { ExportPresenceModes } = HarmonyImportDependency; -class ProfilingPlugin { +const idsSymbol = Symbol("HarmonyExportImportedSpecifierDependency.ids"); + +class NormalReexportItem { /** - * @param {ProfilingPluginOptions=} options options object + * @param {string} name export name + * @param {string[]} ids reexported ids from other module + * @param {ExportInfo} exportInfo export info from other module + * @param {boolean} checked true, if it should be checked at runtime if this export exists + * @param {boolean} hidden true, if it is hidden behind another active export in the same module */ - constructor(options = {}) { - validate(options); - this.outputPath = options.outputPath || "events.json"; + constructor(name, ids, exportInfo, checked, hidden) { + this.name = name; + this.ids = ids; + this.exportInfo = exportInfo; + this.checked = checked; + this.hidden = hidden; } +} - apply(compiler) { - const tracer = createTrace( - compiler.intermediateFileSystem, - this.outputPath - ); - tracer.profiler.startProfiling(); +class ExportMode { + /** + * @param {ExportModeType} type type of the mode + */ + constructor(type) { + /** @type {ExportModeType} */ + this.type = type; - // Compiler Hooks - Object.keys(compiler.hooks).forEach(hookName => { - const hook = compiler.hooks[hookName]; - if (hook) { - hook.intercept(makeInterceptorFor("Compiler", tracer)(hookName)); - } - }); + // for "normal-reexport": + /** @type {NormalReexportItem[] | null} */ + this.items = null; - Object.keys(compiler.resolverFactory.hooks).forEach(hookName => { - const hook = compiler.resolverFactory.hooks[hookName]; - if (hook) { - hook.intercept(makeInterceptorFor("Resolver", tracer)(hookName)); - } - }); + // for "reexport-named-default" | "reexport-fake-namespace-object" | "reexport-namespace-object" + /** @type {string|null} */ + this.name = null; + /** @type {ExportInfo | null} */ + this.partialNamespaceExportInfo = null; - compiler.hooks.compilation.tap( - pluginName, - (compilation, { normalModuleFactory, contextModuleFactory }) => { - interceptAllHooksFor(compilation, tracer, "Compilation"); - interceptAllHooksFor( - normalModuleFactory, - tracer, - "Normal Module Factory" - ); - interceptAllHooksFor( - contextModuleFactory, - tracer, - "Context Module Factory" - ); - interceptAllParserHooks(normalModuleFactory, tracer); - interceptAllJavascriptModulesPluginHooks(compilation, tracer); - } - ); + // for "dynamic-reexport": + /** @type {Set | null} */ + this.ignored = null; - // We need to write out the CPU profile when we are all done. - compiler.hooks.done.tapAsync( - { - name: pluginName, - stage: Infinity - }, - (stats, callback) => { - if (compiler.watchMode) return callback(); - tracer.profiler.stopProfiling().then(parsedResults => { - if (parsedResults === undefined) { - tracer.profiler.destroy(); - tracer.end(callback); - return; - } + // for "dynamic-reexport" | "empty-star": + /** @type {Set | null} */ + this.hidden = null; - const cpuStartTime = parsedResults.profile.startTime; - const cpuEndTime = parsedResults.profile.endTime; + // for "missing": + /** @type {string | null} */ + this.userRequest = null; - tracer.trace.completeEvent({ - name: "TaskQueueManager::ProcessTaskFromWorkQueue", - id: ++tracer.counter, - cat: ["toplevel"], - ts: cpuStartTime, - args: { - src_file: "../../ipc/ipc_moji_bootstrap.cc", - src_func: "Accept" - } - }); + // for "reexport-fake-namespace-object": + /** @type {number} */ + this.fakeType = 0; + } +} - tracer.trace.completeEvent({ - name: "EvaluateScript", - id: ++tracer.counter, - cat: ["devtools.timeline"], - ts: cpuStartTime, - dur: cpuEndTime - cpuStartTime, - args: { - data: { - url: "webpack", - lineNumber: 1, - columnNumber: 1, - frame: "0xFFF" - } - } - }); +const determineExportAssignments = ( + moduleGraph, + dependencies, + additionalDependency +) => { + const names = new Set(); + const dependencyIndices = []; - tracer.trace.instantEvent({ - name: "CpuProfile", - id: ++tracer.counter, - cat: ["disabled-by-default-devtools.timeline"], - ts: cpuEndTime, - args: { - data: { - cpuProfile: parsedResults.profile - } - } - }); + if (additionalDependency) { + dependencies = dependencies.concat(additionalDependency); + } - tracer.profiler.destroy(); - tracer.end(callback); - }); + for (const dep of dependencies) { + const i = dependencyIndices.length; + dependencyIndices[i] = names.size; + const otherImportedModule = moduleGraph.getModule(dep); + if (otherImportedModule) { + const exportsInfo = moduleGraph.getExportsInfo(otherImportedModule); + for (const exportInfo of exportsInfo.exports) { + if ( + exportInfo.provided === true && + exportInfo.name !== "default" && + !names.has(exportInfo.name) + ) { + names.add(exportInfo.name); + dependencyIndices[i] = names.size; + } } - ); + } } -} + dependencyIndices.push(names.size); -const interceptAllHooksFor = (instance, tracer, logLabel) => { - if (Reflect.has(instance, "hooks")) { - Object.keys(instance.hooks).forEach(hookName => { - const hook = instance.hooks[hookName]; - if (hook && !hook._fakeHook) { - hook.intercept(makeInterceptorFor(logLabel, tracer)(hookName)); - } - }); + return { names: Array.from(names), dependencyIndices }; +}; + +const findDependencyForName = ( + { names, dependencyIndices }, + name, + dependencies +) => { + const dependenciesIt = dependencies[Symbol.iterator](); + const dependencyIndicesIt = dependencyIndices[Symbol.iterator](); + let dependenciesItResult = dependenciesIt.next(); + let dependencyIndicesItResult = dependencyIndicesIt.next(); + if (dependencyIndicesItResult.done) return; + for (let i = 0; i < names.length; i++) { + while (i >= dependencyIndicesItResult.value) { + dependenciesItResult = dependenciesIt.next(); + dependencyIndicesItResult = dependencyIndicesIt.next(); + if (dependencyIndicesItResult.done) return; + } + if (names[i] === name) return dependenciesItResult.value; } + return undefined; }; -const interceptAllParserHooks = (moduleFactory, tracer) => { - const moduleTypes = [ - "javascript/auto", - "javascript/dynamic", - "javascript/esm", - "json", - "webassembly/async", - "webassembly/sync" - ]; +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {HarmonyExportImportedSpecifierDependency} dep the dependency + * @param {string} runtimeKey the runtime key + * @returns {ExportMode} the export mode + */ +const getMode = (moduleGraph, dep, runtimeKey) => { + const importedModule = moduleGraph.getModule(dep); - moduleTypes.forEach(moduleType => { - moduleFactory.hooks.parser - .for(moduleType) - .tap("ProfilingPlugin", (parser, parserOpts) => { - interceptAllHooksFor(parser, tracer, "Parser"); - }); - }); -}; + if (!importedModule) { + const mode = new ExportMode("missing"); -const interceptAllJavascriptModulesPluginHooks = (compilation, tracer) => { - interceptAllHooksFor( - { - hooks: - (__webpack_require__(89464).getCompilationHooks)( - compilation - ) - }, - tracer, - "JavascriptModulesPlugin" - ); -}; + mode.userRequest = dep.userRequest; -const makeInterceptorFor = (instance, tracer) => hookName => ({ - register: ({ name, type, context, fn }) => { - const newFn = - // Don't tap our own hooks to ensure stream can close cleanly - name === pluginName - ? fn - : makeNewProfiledTapFn(hookName, tracer, { - name, - type, - fn - }); - return { - name, - type, - context, - fn: newFn - }; + return mode; } -}); -// TODO improve typing -/** @typedef {(...args: TODO[]) => void | Promise} PluginFunction */ + const name = dep.name; + const runtime = keyToRuntime(runtimeKey); + const parentModule = moduleGraph.getParentModule(dep); + const exportsInfo = moduleGraph.getExportsInfo(parentModule); -/** - * @param {string} hookName Name of the hook to profile. - * @param {Trace} tracer The trace object. - * @param {object} options Options for the profiled fn. - * @param {string} options.name Plugin name - * @param {string} options.type Plugin type (sync | async | promise) - * @param {PluginFunction} options.fn Plugin function - * @returns {PluginFunction} Chainable hooked function. - */ -const makeNewProfiledTapFn = (hookName, tracer, { name, type, fn }) => { - const defaultCategory = ["blink.user_timing"]; + if ( + name + ? exportsInfo.getUsed(name, runtime) === UsageState.Unused + : exportsInfo.isUsed(runtime) === false + ) { + const mode = new ExportMode("unused"); - switch (type) { - case "promise": - return (...args) => { - const id = ++tracer.counter; - tracer.trace.begin({ - name, - id, - cat: defaultCategory - }); - const promise = /** @type {Promise<*>} */ (fn(...args)); - return promise.then(r => { - tracer.trace.end({ - name, - id, - cat: defaultCategory - }); - return r; - }); - }; - case "async": - return (...args) => { - const id = ++tracer.counter; - tracer.trace.begin({ - name, - id, - cat: defaultCategory - }); - const callback = args.pop(); - fn(...args, (...r) => { - tracer.trace.end({ - name, - id, - cat: defaultCategory - }); - callback(...r); - }); - }; - case "sync": - return (...args) => { - const id = ++tracer.counter; - // Do not instrument ourself due to the CPU - // profile needing to be the last event in the trace. - if (name === pluginName) { - return fn(...args); - } + mode.name = name || "*"; - tracer.trace.begin({ - name, - id, - cat: defaultCategory - }); - let r; - try { - r = fn(...args); - } catch (error) { - tracer.trace.end({ - name, - id, - cat: defaultCategory - }); - throw error; - } - tracer.trace.end({ - name, - id, - cat: defaultCategory - }); - return r; - }; - default: - break; + return mode; } -}; -module.exports = ProfilingPlugin; -module.exports.Profiler = Profiler; + const importedExportsType = importedModule.getExportsType( + moduleGraph, + parentModule.buildMeta.strictHarmonyModule + ); + const ids = dep.getIds(moduleGraph); -/***/ }), + // Special handling for reexporting the default export + // from non-namespace modules + if (name && ids.length > 0 && ids[0] === "default") { + switch (importedExportsType) { + case "dynamic": { + const mode = new ExportMode("reexport-dynamic-default"); -/***/ 96816: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + mode.name = name; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return mode; + } + case "default-only": + case "default-with-named": { + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + const mode = new ExportMode("reexport-named-default"); + mode.name = name; + mode.partialNamespaceExportInfo = exportInfo; + return mode; + } + } + } -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); + // reexporting with a fixed name + if (name) { + let mode; + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + if (ids.length > 0) { + // export { name as name } + switch (importedExportsType) { + case "default-only": + mode = new ExportMode("reexport-undefined"); + mode.name = name; + break; + default: + mode = new ExportMode("normal-reexport"); + mode.items = [ + new NormalReexportItem(name, ids, exportInfo, false, false) + ]; + break; + } + } else { + // export * as name + switch (importedExportsType) { + case "default-only": + mode = new ExportMode("reexport-fake-namespace-object"); + mode.name = name; + mode.partialNamespaceExportInfo = exportInfo; + mode.fakeType = 0; + break; + case "default-with-named": + mode = new ExportMode("reexport-fake-namespace-object"); + mode.name = name; + mode.partialNamespaceExportInfo = exportInfo; + mode.fakeType = 2; + break; + case "dynamic": + default: + mode = new ExportMode("reexport-namespace-object"); + mode.name = name; + mode.partialNamespaceExportInfo = exportInfo; + } + } -/** @type {Record} */ -const DEFINITIONS = { - f: { - definition: "var __WEBPACK_AMD_DEFINE_RESULT__;", - content: `!(__WEBPACK_AMD_DEFINE_RESULT__ = (#).call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, - requests: [ - RuntimeGlobals.require, - RuntimeGlobals.exports, - RuntimeGlobals.module - ] - }, - o: { - definition: "", - content: "!(module.exports = #)", - requests: [RuntimeGlobals.module] - }, - of: { - definition: - "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;", - content: `!(__WEBPACK_AMD_DEFINE_FACTORY__ = (#), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : - __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, - requests: [ - RuntimeGlobals.require, - RuntimeGlobals.exports, - RuntimeGlobals.module - ] - }, - af: { - definition: - "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", - content: `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = (#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, - requests: [RuntimeGlobals.exports, RuntimeGlobals.module] - }, - ao: { - definition: "", - content: "!(#, module.exports = #)", - requests: [RuntimeGlobals.module] - }, - aof: { - definition: - "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", - content: `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`, - requests: [RuntimeGlobals.exports, RuntimeGlobals.module] - }, - lf: { - definition: "var XXX, XXXmodule;", - content: - "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = (#).call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))", - requests: [RuntimeGlobals.require, RuntimeGlobals.module] - }, - lo: { - definition: "var XXX;", - content: "!(XXX = #)", - requests: [] - }, - lof: { - definition: "var XXX, XXXfactory, XXXmodule;", - content: - "!(XXXfactory = (#), (typeof XXXfactory === 'function' ? ((XXXmodule = { id: YYY, exports: {}, loaded: false }), (XXX = XXXfactory.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule)), (XXXmodule.loaded = true), XXX === undefined && (XXX = XXXmodule.exports)) : XXX = XXXfactory))", - requests: [RuntimeGlobals.require, RuntimeGlobals.module] - }, - laf: { - definition: "var __WEBPACK_AMD_DEFINE_ARRAY__, XXX, XXXexports;", - content: - "!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = (#).apply(XXXexports = {}, __WEBPACK_AMD_DEFINE_ARRAY__), XXX === undefined && (XXX = XXXexports))", - requests: [] - }, - lao: { - definition: "var XXX;", - content: "!(#, XXX = #)", - requests: [] - }, - laof: { - definition: "var XXXarray, XXXfactory, XXXexports, XXX;", - content: `!(XXXarray = #, XXXfactory = (#), - (typeof XXXfactory === 'function' ? - ((XXX = XXXfactory.apply(XXXexports = {}, XXXarray)), XXX === undefined && (XXX = XXXexports)) : - (XXX = XXXfactory) - ))`, - requests: [] + return mode; + } + + // Star reexporting + + const { ignoredExports, exports, checked, hidden } = dep.getStarReexports( + moduleGraph, + runtime, + exportsInfo, + importedModule + ); + if (!exports) { + // We have too few info about the modules + // Delegate the logic to the runtime code + + const mode = new ExportMode("dynamic-reexport"); + mode.ignored = ignoredExports; + mode.hidden = hidden; + + return mode; + } + + if (exports.size === 0) { + const mode = new ExportMode("empty-star"); + mode.hidden = hidden; + + return mode; + } + + const mode = new ExportMode("normal-reexport"); + + mode.items = Array.from( + exports, + exportName => + new NormalReexportItem( + exportName, + [exportName], + exportsInfo.getReadOnlyExportInfo(exportName), + checked.has(exportName), + false + ) + ); + if (hidden !== undefined) { + for (const exportName of hidden) { + mode.items.push( + new NormalReexportItem( + exportName, + [exportName], + exportsInfo.getReadOnlyExportInfo(exportName), + false, + true + ) + ); + } } + + return mode; }; -class AMDDefineDependency extends NullDependency { - constructor(range, arrayRange, functionRange, objectRange, namedModule) { - super(); - this.range = range; - this.arrayRange = arrayRange; - this.functionRange = functionRange; - this.objectRange = objectRange; - this.namedModule = namedModule; - this.localModule = null; +class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { + /** + * @param {string} request the request string + * @param {number} sourceOrder the order in the original source file + * @param {string[]} ids the requested export name of the imported module + * @param {string | null} name the export name of for this module + * @param {Set} activeExports other named exports in the module + * @param {ReadonlyArray | Iterable} otherStarExports other star exports in the module before this import + * @param {number} exportPresenceMode mode of checking export names + * @param {HarmonyStarExportsList} allStarExports all star exports in the module + * @param {Record=} assertions import assertions + */ + constructor( + request, + sourceOrder, + ids, + name, + activeExports, + otherStarExports, + exportPresenceMode, + allStarExports, + assertions + ) { + super(request, sourceOrder, assertions); + + this.ids = ids; + this.name = name; + this.activeExports = activeExports; + this.otherStarExports = otherStarExports; + this.exportPresenceMode = exportPresenceMode; + this.allStarExports = allStarExports; } - get type() { - return "amd define"; + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return Dependency.TRANSITIVE; } - serialize(context) { - const { write } = context; - write(this.range); - write(this.arrayRange); - write(this.functionRange); - write(this.objectRange); - write(this.namedModule); - write(this.localModule); - super.serialize(context); + // TODO webpack 6 remove + get id() { + throw new Error("id was renamed to ids and type changed to string[]"); } - deserialize(context) { - const { read } = context; - this.range = read(); - this.arrayRange = read(); - this.functionRange = read(); - this.objectRange = read(); - this.namedModule = read(); - this.localModule = read(); - super.deserialize(context); + // TODO webpack 6 remove + getId() { + throw new Error("id was renamed to ids and type changed to string[]"); } -} -makeSerializable( - AMDDefineDependency, - "webpack/lib/dependencies/AMDDefineDependency" -); + // TODO webpack 6 remove + setId() { + throw new Error("id was renamed to ids and type changed to string[]"); + } + + get type() { + return "harmony export imported specifier"; + } -AMDDefineDependency.Template = class AMDDefineDependencyTemplate extends ( - NullDependency.Template -) { /** - * @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 + * @param {ModuleGraph} moduleGraph the module graph + * @returns {string[]} the imported id + */ + getIds(moduleGraph) { + return moduleGraph.getMeta(this)[idsSymbol] || this.ids; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {string[]} ids the imported ids * @returns {void} */ - apply(dependency, source, { runtimeRequirements }) { - const dep = /** @type {AMDDefineDependency} */ (dependency); - const branch = this.branch(dep); - const { definition, content, requests } = DEFINITIONS[branch]; - for (const req of requests) { - runtimeRequirements.add(req); - } - this.replace(dep, source, definition, content); + setIds(moduleGraph, ids) { + moduleGraph.getMeta(this)[idsSymbol] = ids; } - localModuleVar(dependency) { - return ( - dependency.localModule && - dependency.localModule.used && - dependency.localModule.variableName() + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @returns {ExportMode} the export mode + */ + getMode(moduleGraph, runtime) { + return moduleGraph.dependencyCacheProvide( + this, + getRuntimeKey(runtime), + getMode ); } - branch(dependency) { - const localModuleVar = this.localModuleVar(dependency) ? "l" : ""; - const arrayRange = dependency.arrayRange ? "a" : ""; - const objectRange = dependency.objectRange ? "o" : ""; - const functionRange = dependency.functionRange ? "f" : ""; - return localModuleVar + arrayRange + objectRange + functionRange; - } + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @param {ExportsInfo} exportsInfo exports info about the current module (optional) + * @param {Module} importedModule the imported module (optional) + * @returns {{exports?: Set, checked?: Set, ignoredExports: Set, hidden?: Set}} information + */ + getStarReexports( + moduleGraph, + runtime, + exportsInfo = moduleGraph.getExportsInfo(moduleGraph.getParentModule(this)), + importedModule = moduleGraph.getModule(this) + ) { + const importedExportsInfo = moduleGraph.getExportsInfo(importedModule); - replace(dependency, source, definition, text) { - const localModuleVar = this.localModuleVar(dependency); - if (localModuleVar) { - text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); - definition = definition.replace( - /XXX/g, - localModuleVar.replace(/\$/g, "$$$$") - ); - } + const noExtraExports = + importedExportsInfo.otherExportsInfo.provided === false; + const noExtraImports = + exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused; - if (dependency.namedModule) { - text = text.replace(/YYY/g, JSON.stringify(dependency.namedModule)); + const ignoredExports = new Set(["default", ...this.activeExports]); + + let hiddenExports = undefined; + const otherStarExports = + this._discoverActiveExportsFromOtherStarExports(moduleGraph); + if (otherStarExports !== undefined) { + hiddenExports = new Set(); + for (let i = 0; i < otherStarExports.namesSlice; i++) { + hiddenExports.add(otherStarExports.names[i]); + } + for (const e of ignoredExports) hiddenExports.delete(e); } - const texts = text.split("#"); + if (!noExtraExports && !noExtraImports) { + return { + ignoredExports, + hidden: hiddenExports + }; + } - if (definition) source.insert(0, definition); + /** @type {Set} */ + const exports = new Set(); + /** @type {Set} */ + const checked = new Set(); + /** @type {Set} */ + const hidden = hiddenExports !== undefined ? new Set() : undefined; - let current = dependency.range[0]; - if (dependency.arrayRange) { - source.replace(current, dependency.arrayRange[0] - 1, texts.shift()); - current = dependency.arrayRange[1]; + if (noExtraImports) { + for (const exportInfo of exportsInfo.orderedExports) { + const name = exportInfo.name; + if (ignoredExports.has(name)) continue; + if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; + const importedExportInfo = + importedExportsInfo.getReadOnlyExportInfo(name); + if (importedExportInfo.provided === false) continue; + if (hiddenExports !== undefined && hiddenExports.has(name)) { + hidden.add(name); + continue; + } + exports.add(name); + if (importedExportInfo.provided === true) continue; + checked.add(name); + } + } else if (noExtraExports) { + for (const importedExportInfo of importedExportsInfo.orderedExports) { + const name = importedExportInfo.name; + if (ignoredExports.has(name)) continue; + if (importedExportInfo.provided === false) continue; + const exportInfo = exportsInfo.getReadOnlyExportInfo(name); + if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; + if (hiddenExports !== undefined && hiddenExports.has(name)) { + hidden.add(name); + continue; + } + exports.add(name); + if (importedExportInfo.provided === true) continue; + checked.add(name); + } } - if (dependency.objectRange) { - source.replace(current, dependency.objectRange[0] - 1, texts.shift()); - current = dependency.objectRange[1]; - } else if (dependency.functionRange) { - source.replace(current, dependency.functionRange[0] - 1, texts.shift()); - current = dependency.functionRange[1]; - } - source.replace(current, dependency.range[1] - 1, texts.shift()); - if (texts.length > 0) throw new Error("Implementation error"); + return { ignoredExports, exports, checked, hidden }; } -}; -module.exports = AMDDefineDependency; + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return (connection, runtime) => { + const mode = this.getMode(moduleGraph, runtime); + return mode.type !== "unused" && mode.type !== "empty-star"; + }; + } + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } -/***/ }), + /** + * 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) { + const mode = this.getMode(moduleGraph, runtime); -/***/ 48519: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + switch (mode.type) { + case "missing": + case "unused": + case "empty-star": + case "reexport-undefined": + return Dependency.NO_EXPORTS_REFERENCED; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + case "reexport-dynamic-default": + return Dependency.EXPORTS_OBJECT_REFERENCED; + case "reexport-named-default": { + if (!mode.partialNamespaceExportInfo) + return Dependency.EXPORTS_OBJECT_REFERENCED; + /** @type {string[][]} */ + const referencedExports = []; + processExportInfo( + runtime, + referencedExports, + [], + /** @type {ExportInfo} */ (mode.partialNamespaceExportInfo) + ); + return referencedExports; + } + case "reexport-namespace-object": + case "reexport-fake-namespace-object": { + if (!mode.partialNamespaceExportInfo) + return Dependency.EXPORTS_OBJECT_REFERENCED; + /** @type {string[][]} */ + const referencedExports = []; + processExportInfo( + runtime, + referencedExports, + [], + /** @type {ExportInfo} */ (mode.partialNamespaceExportInfo), + mode.type === "reexport-fake-namespace-object" + ); + return referencedExports; + } -const RuntimeGlobals = __webpack_require__(16475); -const AMDDefineDependency = __webpack_require__(96816); -const AMDRequireArrayDependency = __webpack_require__(33516); -const AMDRequireContextDependency = __webpack_require__(96123); -const AMDRequireItemDependency = __webpack_require__(71806); -const ConstDependency = __webpack_require__(76911); -const ContextDependencyHelpers = __webpack_require__(99630); -const DynamicExports = __webpack_require__(32006); -const LocalModuleDependency = __webpack_require__(52805); -const { addLocalModule, getLocalModule } = __webpack_require__(75827); + case "dynamic-reexport": + return Dependency.EXPORTS_OBJECT_REFERENCED; -const isBoundFunctionExpression = expr => { - if (expr.type !== "CallExpression") return false; - if (expr.callee.type !== "MemberExpression") return false; - if (expr.callee.computed) return false; - if (expr.callee.object.type !== "FunctionExpression") return false; - if (expr.callee.property.type !== "Identifier") return false; - if (expr.callee.property.name !== "bind") return false; - return true; -}; + case "normal-reexport": { + const referencedExports = []; + for (const { ids, exportInfo, hidden } of mode.items) { + if (hidden) continue; + processExportInfo(runtime, referencedExports, ids, exportInfo, false); + } + return referencedExports; + } -const isUnboundFunctionExpression = expr => { - if (expr.type === "FunctionExpression") return true; - if (expr.type === "ArrowFunctionExpression") return true; - return false; -}; + default: + throw new Error(`Unknown mode ${mode.type}`); + } + } -const isCallable = expr => { - if (isUnboundFunctionExpression(expr)) return true; - if (isBoundFunctionExpression(expr)) return true; - return false; -}; + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {{ names: string[], namesSlice: number, dependencyIndices: number[], dependencyIndex: number } | undefined} exported names and their origin dependency + */ + _discoverActiveExportsFromOtherStarExports(moduleGraph) { + if (!this.otherStarExports) return undefined; -class AMDDefineDependencyParserPlugin { - constructor(options) { - this.options = options; - } + const i = + "length" in this.otherStarExports + ? this.otherStarExports.length + : countIterable(this.otherStarExports); + if (i === 0) return undefined; - apply(parser) { - parser.hooks.call - .for("define") - .tap( - "AMDDefineDependencyParserPlugin", - this.processCallDefine.bind(this, parser) + if (this.allStarExports) { + const { names, dependencyIndices } = moduleGraph.cached( + determineExportAssignments, + this.allStarExports.dependencies ); - } - processArray(parser, expr, param, identifiers, namedModule) { - if (param.isArray()) { - param.items.forEach((param, idx) => { - if ( - param.isString() && - ["require", "module", "exports"].includes(param.string) - ) - identifiers[idx] = param.string; - const result = this.processItem(parser, expr, param, namedModule); - if (result === undefined) { - this.processContext(parser, expr, param); - } - }); - return true; - } else if (param.isConstArray()) { - const deps = []; - param.array.forEach((request, idx) => { - let dep; - let localModule; - if (request === "require") { - identifiers[idx] = request; - dep = "__webpack_require__"; - } else if (["exports", "module"].includes(request)) { - identifiers[idx] = request; - dep = request; - } else if ((localModule = getLocalModule(parser.state, request))) { - localModule.flagUsed(); - dep = new LocalModuleDependency(localModule, undefined, false); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - } else { - dep = this.newRequireItemDependency(request); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - } - deps.push(dep); - }); - const dep = this.newRequireArrayDependency(deps, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.module.addPresentationalDependency(dep); - return true; - } - } - processItem(parser, expr, param, namedModule) { - if (param.isConditional()) { - param.options.forEach(param => { - const result = this.processItem(parser, expr, param); - if (result === undefined) { - this.processContext(parser, expr, param); - } - }); - return true; - } else if (param.isString()) { - let dep, localModule; - if (param.string === "require") { - dep = new ConstDependency("__webpack_require__", param.range, [ - RuntimeGlobals.require - ]); - } else if (param.string === "exports") { - dep = new ConstDependency("exports", param.range, [ - RuntimeGlobals.exports - ]); - } else if (param.string === "module") { - dep = new ConstDependency("module", param.range, [ - RuntimeGlobals.module - ]); - } else if ( - (localModule = getLocalModule(parser.state, param.string, namedModule)) - ) { - localModule.flagUsed(); - dep = new LocalModuleDependency(localModule, param.range, false); - } else { - dep = this.newRequireItemDependency(param.string, param.range); - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; + return { + names, + namesSlice: dependencyIndices[i - 1], + dependencyIndices, + dependencyIndex: i + }; } - } - processContext(parser, expr, param) { - const dep = ContextDependencyHelpers.create( - AMDRequireContextDependency, - param.range, - param, - expr, - this.options, - { - category: "amd" - }, - parser + + const { names, dependencyIndices } = moduleGraph.cached( + determineExportAssignments, + this.otherStarExports, + this ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; + + return { + names, + namesSlice: dependencyIndices[i - 1], + dependencyIndices, + dependencyIndex: i + }; } - processCallDefine(parser, expr) { - let array, fn, obj, namedModule; - switch (expr.arguments.length) { - case 1: - if (isCallable(expr.arguments[0])) { - // define(f() {…}) - fn = expr.arguments[0]; - } else if (expr.arguments[0].type === "ObjectExpression") { - // define({…}) - obj = expr.arguments[0]; - } else { - // define(expr) - // unclear if function or object - obj = fn = expr.arguments[0]; - } - break; - case 2: - if (expr.arguments[0].type === "Literal") { - namedModule = expr.arguments[0].value; - // define("…", …) - if (isCallable(expr.arguments[1])) { - // define("…", f() {…}) - fn = expr.arguments[1]; - } else if (expr.arguments[1].type === "ObjectExpression") { - // define("…", {…}) - obj = expr.arguments[1]; - } else { - // define("…", expr) - // unclear if function or object - obj = fn = expr.arguments[1]; - } - } else { - array = expr.arguments[0]; - if (isCallable(expr.arguments[1])) { - // define([…], f() {}) - fn = expr.arguments[1]; - } else if (expr.arguments[1].type === "ObjectExpression") { - // define([…], {…}) - obj = expr.arguments[1]; - } else { - // define([…], expr) - // unclear if function or object - obj = fn = expr.arguments[1]; - } - } - break; - case 3: - // define("…", […], f() {…}) - namedModule = expr.arguments[0].value; - array = expr.arguments[1]; - if (isCallable(expr.arguments[2])) { - // define("…", […], f() {}) - fn = expr.arguments[2]; - } else if (expr.arguments[2].type === "ObjectExpression") { - // define("…", […], {…}) - obj = expr.arguments[2]; - } else { - // define("…", […], expr) - // unclear if function or object - obj = fn = expr.arguments[2]; - } - break; - default: - return; - } - DynamicExports.bailout(parser.state); - let fnParams = null; - let fnParamsOffset = 0; - if (fn) { - if (isUnboundFunctionExpression(fn)) { - fnParams = fn.params; - } else if (isBoundFunctionExpression(fn)) { - fnParams = fn.callee.object.params; - fnParamsOffset = fn.arguments.length - 1; - if (fnParamsOffset < 0) { - fnParamsOffset = 0; + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + const mode = this.getMode(moduleGraph, undefined); + + switch (mode.type) { + case "missing": + return undefined; + case "dynamic-reexport": { + const from = moduleGraph.getConnection(this); + return { + exports: true, + from, + canMangle: false, + excludeExports: mode.hidden + ? combine(mode.ignored, mode.hidden) + : mode.ignored, + hideExports: mode.hidden, + dependencies: [from.module] + }; + } + case "empty-star": + return { + exports: [], + hideExports: mode.hidden, + dependencies: [moduleGraph.getModule(this)] + }; + // falls through + case "normal-reexport": { + const from = moduleGraph.getConnection(this); + return { + exports: Array.from(mode.items, item => ({ + name: item.name, + from, + export: item.ids, + hidden: item.hidden + })), + priority: 1, + dependencies: [from.module] + }; + } + case "reexport-dynamic-default": { + { + const from = moduleGraph.getConnection(this); + return { + exports: [ + { + name: mode.name, + from, + export: ["default"] + } + ], + priority: 1, + dependencies: [from.module] + }; } } - } - let fnRenames = new Map(); - if (array) { - const identifiers = {}; - const param = parser.evaluateExpression(array); - const result = this.processArray( - parser, - expr, - param, - identifiers, - namedModule - ); - if (!result) return; - if (fnParams) { - fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { - if (identifiers[idx]) { - fnRenames.set(param.name, parser.getVariableInfo(identifiers[idx])); - return false; - } - return true; - }); + case "reexport-undefined": + return { + exports: [mode.name], + dependencies: [moduleGraph.getModule(this)] + }; + case "reexport-fake-namespace-object": { + const from = moduleGraph.getConnection(this); + return { + exports: [ + { + name: mode.name, + from, + export: null, + exports: [ + { + name: "default", + canMangle: false, + from, + export: null + } + ] + } + ], + priority: 1, + dependencies: [from.module] + }; } - } else { - const identifiers = ["require", "exports", "module"]; - if (fnParams) { - fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { - if (identifiers[idx]) { - fnRenames.set(param.name, parser.getVariableInfo(identifiers[idx])); - return false; - } - return true; - }); + case "reexport-namespace-object": { + const from = moduleGraph.getConnection(this); + return { + exports: [ + { + name: mode.name, + from, + export: null + } + ], + priority: 1, + dependencies: [from.module] + }; } - } - let inTry; - if (fn && isUnboundFunctionExpression(fn)) { - inTry = parser.scope.inTry; - parser.inScope(fnParams, () => { - for (const [name, varInfo] of fnRenames) { - parser.setVariable(name, varInfo); - } - parser.scope.inTry = inTry; - if (fn.body.type === "BlockStatement") { - parser.detectMode(fn.body.body); - const prev = parser.prevStatement; - parser.preWalkStatement(fn.body); - parser.prevStatement = prev; - parser.walkStatement(fn.body); - } else { - parser.walkExpression(fn.body); - } - }); - } else if (fn && isBoundFunctionExpression(fn)) { - inTry = parser.scope.inTry; - parser.inScope( - fn.callee.object.params.filter( - i => !["require", "module", "exports"].includes(i.name) - ), - () => { - for (const [name, varInfo] of fnRenames) { - parser.setVariable(name, varInfo); - } - parser.scope.inTry = inTry; - if (fn.callee.object.body.type === "BlockStatement") { - parser.detectMode(fn.callee.object.body.body); - const prev = parser.prevStatement; - parser.preWalkStatement(fn.callee.object.body); - parser.prevStatement = prev; - parser.walkStatement(fn.callee.object.body); - } else { - parser.walkExpression(fn.callee.object.body); - } - } - ); - if (fn.arguments) { - parser.walkExpressions(fn.arguments); + case "reexport-named-default": { + const from = moduleGraph.getConnection(this); + return { + exports: [ + { + name: mode.name, + from, + export: ["default"] + } + ], + priority: 1, + dependencies: [from.module] + }; } - } else if (fn || obj) { - parser.walkExpression(fn || obj); - } - - const dep = this.newDefineDependency( - expr.range, - array ? array.range : null, - fn ? fn.range : null, - obj ? obj.range : null, - namedModule ? namedModule : null - ); - dep.loc = expr.loc; - if (namedModule) { - dep.localModule = addLocalModule(parser.state, namedModule); + default: + throw new Error(`Unknown mode ${mode.type}`); } - parser.state.module.addPresentationalDependency(dep); - return true; } - newDefineDependency( - range, - arrayRange, - functionRange, - objectRange, - namedModule - ) { - return new AMDDefineDependency( - range, - arrayRange, - functionRange, - objectRange, - namedModule - ); + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {number} effective mode + */ + _getEffectiveExportPresenceLevel(moduleGraph) { + if (this.exportPresenceMode !== ExportPresenceModes.AUTO) + return this.exportPresenceMode; + return moduleGraph.getParentModule(this).buildMeta.strictHarmonyModule + ? ExportPresenceModes.ERROR + : ExportPresenceModes.WARN; } - newRequireArrayDependency(depsArray, range) { - return new AMDRequireArrayDependency(depsArray, range); + + /** + * Returns warnings + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} warnings + */ + getWarnings(moduleGraph) { + const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); + if (exportsPresence === ExportPresenceModes.WARN) { + return this._getErrors(moduleGraph); + } + return null; } - newRequireItemDependency(request, range) { - return new AMDRequireItemDependency(request, range); + + /** + * Returns errors + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} errors + */ + getErrors(moduleGraph) { + const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); + if (exportsPresence === ExportPresenceModes.ERROR) { + return this._getErrors(moduleGraph); + } + return null; } -} -module.exports = AMDDefineDependencyParserPlugin; + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | undefined} errors + */ + _getErrors(moduleGraph) { + const ids = this.getIds(moduleGraph); + let errors = this.getLinkingErrors( + moduleGraph, + ids, + `(reexported as '${this.name}')` + ); + if (ids.length === 0 && this.name === null) { + const potentialConflicts = + this._discoverActiveExportsFromOtherStarExports(moduleGraph); + if (potentialConflicts && potentialConflicts.namesSlice > 0) { + const ownNames = new Set( + potentialConflicts.names.slice( + potentialConflicts.namesSlice, + potentialConflicts.dependencyIndices[ + potentialConflicts.dependencyIndex + ] + ) + ); + const importedModule = moduleGraph.getModule(this); + if (importedModule) { + const exportsInfo = moduleGraph.getExportsInfo(importedModule); + const conflicts = new Map(); + for (const exportInfo of exportsInfo.orderedExports) { + if (exportInfo.provided !== true) continue; + if (exportInfo.name === "default") continue; + if (this.activeExports.has(exportInfo.name)) continue; + if (ownNames.has(exportInfo.name)) continue; + const conflictingDependency = findDependencyForName( + potentialConflicts, + exportInfo.name, + this.allStarExports + ? this.allStarExports.dependencies + : [...this.otherStarExports, this] + ); + if (!conflictingDependency) continue; + const target = exportInfo.getTerminalBinding(moduleGraph); + if (!target) continue; + const conflictingModule = moduleGraph.getModule( + conflictingDependency + ); + if (conflictingModule === importedModule) continue; + const conflictingExportInfo = moduleGraph.getExportInfo( + conflictingModule, + exportInfo.name + ); + const conflictingTarget = + conflictingExportInfo.getTerminalBinding(moduleGraph); + if (!conflictingTarget) continue; + if (target === conflictingTarget) continue; + const list = conflicts.get(conflictingDependency.request); + if (list === undefined) { + conflicts.set(conflictingDependency.request, [exportInfo.name]); + } else { + list.push(exportInfo.name); + } + } + for (const [request, exports] of conflicts) { + if (!errors) errors = []; + errors.push( + new HarmonyLinkingError( + `The requested module '${ + this.request + }' contains conflicting star exports for the ${ + exports.length > 1 ? "names" : "name" + } ${exports + .map(e => `'${e}'`) + .join(", ")} with the previous requested module '${request}'` + ) + ); + } + } + } + } + return errors; + } -/***/ }), + serialize(context) { + const { write, setCircularReference } = context; -/***/ 50067: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + setCircularReference(this); + write(this.ids); + write(this.name); + write(this.activeExports); + write(this.otherStarExports); + write(this.exportPresenceMode); + write(this.allStarExports); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + super.serialize(context); + } + deserialize(context) { + const { read, setCircularReference } = context; + setCircularReference(this); + this.ids = read(); + this.name = read(); + this.activeExports = read(); + this.otherStarExports = read(); + this.exportPresenceMode = read(); + this.allStarExports = read(); -const RuntimeGlobals = __webpack_require__(16475); -const { - approve, - evaluateToIdentifier, - evaluateToString, - toConstantDependency -} = __webpack_require__(93998); + super.deserialize(context); + } +} -const AMDDefineDependency = __webpack_require__(96816); -const AMDDefineDependencyParserPlugin = __webpack_require__(48519); -const AMDRequireArrayDependency = __webpack_require__(33516); -const AMDRequireContextDependency = __webpack_require__(96123); -const AMDRequireDependenciesBlockParserPlugin = __webpack_require__(66866); -const AMDRequireDependency = __webpack_require__(43911); -const AMDRequireItemDependency = __webpack_require__(71806); -const { - AMDDefineRuntimeModule, - AMDOptionsRuntimeModule -} = __webpack_require__(45242); -const ConstDependency = __webpack_require__(76911); -const LocalModuleDependency = __webpack_require__(52805); -const UnsupportedDependency = __webpack_require__(51669); +makeSerializable( + HarmonyExportImportedSpecifierDependency, + "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency" +); -/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ -/** @typedef {import("../Compiler")} Compiler */ +module.exports = HarmonyExportImportedSpecifierDependency; -class AMDPlugin { +HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate extends ( + HarmonyImportDependency.Template +) { /** - * @param {Record} amdOptions the AMD options + * @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} */ - constructor(amdOptions) { - this.amdOptions = amdOptions; + apply(dependency, source, templateContext) { + const { moduleGraph, runtime, concatenationScope } = templateContext; + + const dep = /** @type {HarmonyExportImportedSpecifierDependency} */ ( + dependency + ); + + const mode = dep.getMode(moduleGraph, runtime); + + if (concatenationScope) { + switch (mode.type) { + case "reexport-undefined": + concatenationScope.registerRawExport( + mode.name, + "/* reexport non-default export from non-harmony */ undefined" + ); + } + return; + } + + if (mode.type !== "unused" && mode.type !== "empty-star") { + super.apply(dependency, source, templateContext); + + this._addExportFragments( + templateContext.initFragments, + dep, + mode, + templateContext.module, + moduleGraph, + runtime, + templateContext.runtimeTemplate, + templateContext.runtimeRequirements + ); + } } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {InitFragment[]} initFragments target array for init fragments + * @param {HarmonyExportImportedSpecifierDependency} dep dependency + * @param {ExportMode} mode the export mode + * @param {Module} module the current module + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {Set} runtimeRequirements runtime requirements * @returns {void} */ - apply(compiler) { - const amdOptions = this.amdOptions; - compiler.hooks.compilation.tap( - "AMDPlugin", - (compilation, { contextModuleFactory, normalModuleFactory }) => { - compilation.dependencyTemplates.set( - AMDRequireDependency, - new AMDRequireDependency.Template() - ); + _addExportFragments( + initFragments, + dep, + mode, + module, + moduleGraph, + runtime, + runtimeTemplate, + runtimeRequirements + ) { + const importedModule = moduleGraph.getModule(dep); + const importVar = dep.getImportVar(moduleGraph); - compilation.dependencyFactories.set( - AMDRequireItemDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - AMDRequireItemDependency, - new AMDRequireItemDependency.Template() + switch (mode.type) { + case "missing": + case "empty-star": + initFragments.push( + new InitFragment( + "/* empty/unused harmony star reexport */\n", + InitFragment.STAGE_HARMONY_EXPORTS, + 1 + ) ); + break; - compilation.dependencyTemplates.set( - AMDRequireArrayDependency, - new AMDRequireArrayDependency.Template() + case "unused": + initFragments.push( + new InitFragment( + `${Template.toNormalComment( + `unused harmony reexport ${mode.name}` + )}\n`, + InitFragment.STAGE_HARMONY_EXPORTS, + 1 + ) ); + break; - compilation.dependencyFactories.set( - AMDRequireContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - AMDRequireContextDependency, - new AMDRequireContextDependency.Template() + case "reexport-dynamic-default": + initFragments.push( + this.getReexportFragment( + module, + "reexport default from dynamic", + moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + importVar, + null, + runtimeRequirements + ) ); + break; - compilation.dependencyTemplates.set( - AMDDefineDependency, - new AMDDefineDependency.Template() + case "reexport-fake-namespace-object": + initFragments.push( + ...this.getReexportFakeNamespaceObjectFragments( + module, + moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + importVar, + mode.fakeType, + runtimeRequirements + ) ); + break; - compilation.dependencyTemplates.set( - UnsupportedDependency, - new UnsupportedDependency.Template() + case "reexport-undefined": + initFragments.push( + this.getReexportFragment( + module, + "reexport non-default export from non-harmony", + moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + "undefined", + "", + runtimeRequirements + ) ); + break; - compilation.dependencyTemplates.set( - LocalModuleDependency, - new LocalModuleDependency.Template() + case "reexport-named-default": + initFragments.push( + this.getReexportFragment( + module, + "reexport default export from named module", + moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + importVar, + "", + runtimeRequirements + ) ); + break; - compilation.hooks.runtimeRequirementInModule - .for(RuntimeGlobals.amdDefine) - .tap("AMDPlugin", (module, set) => { - set.add(RuntimeGlobals.require); - }); - - compilation.hooks.runtimeRequirementInModule - .for(RuntimeGlobals.amdOptions) - .tap("AMDPlugin", (module, set) => { - set.add(RuntimeGlobals.requireScope); - }); - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.amdDefine) - .tap("AMDPlugin", (chunk, set) => { - compilation.addRuntimeModule(chunk, new AMDDefineRuntimeModule()); - }); + case "reexport-namespace-object": + initFragments.push( + this.getReexportFragment( + module, + "reexport module object", + moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), + importVar, + "", + runtimeRequirements + ) + ); + break; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.amdOptions) - .tap("AMDPlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new AMDOptionsRuntimeModule(amdOptions) + case "normal-reexport": + for (const { name, ids, checked, hidden } of mode.items) { + if (hidden) continue; + if (checked) { + initFragments.push( + new InitFragment( + "/* harmony reexport (checked) */ " + + this.getConditionalReexportStatement( + module, + name, + importVar, + ids, + runtimeRequirements + ), + moduleGraph.isAsync(importedModule) + ? InitFragment.STAGE_ASYNC_HARMONY_IMPORTS + : InitFragment.STAGE_HARMONY_IMPORTS, + dep.sourceOrder + ) ); - }); - - const handler = (parser, parserOptions) => { - if (parserOptions.amd !== undefined && !parserOptions.amd) return; + } else { + initFragments.push( + this.getReexportFragment( + module, + "reexport safe", + moduleGraph.getExportsInfo(module).getUsedName(name, runtime), + importVar, + moduleGraph + .getExportsInfo(importedModule) + .getUsedName(ids, runtime), + runtimeRequirements + ) + ); + } + } + break; - const tapOptionsHooks = (optionExpr, rootName, getMembers) => { - parser.hooks.expression - .for(optionExpr) - .tap( - "AMDPlugin", - toConstantDependency(parser, RuntimeGlobals.amdOptions, [ - RuntimeGlobals.amdOptions - ]) - ); - parser.hooks.evaluateIdentifier - .for(optionExpr) - .tap( - "AMDPlugin", - evaluateToIdentifier(optionExpr, rootName, getMembers, true) - ); - parser.hooks.evaluateTypeof - .for(optionExpr) - .tap("AMDPlugin", evaluateToString("object")); - parser.hooks.typeof - .for(optionExpr) - .tap( - "AMDPlugin", - toConstantDependency(parser, JSON.stringify("object")) - ); - }; + case "dynamic-reexport": { + const ignored = mode.hidden + ? combine(mode.ignored, mode.hidden) + : mode.ignored; + const modern = + runtimeTemplate.supportsConst() && + runtimeTemplate.supportsArrowFunction(); + let content = + "/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {};\n" + + `/* harmony reexport (unknown) */ for(${ + modern ? "const" : "var" + } __WEBPACK_IMPORT_KEY__ in ${importVar}) `; - new AMDRequireDependenciesBlockParserPlugin(parserOptions).apply( - parser - ); - new AMDDefineDependencyParserPlugin(parserOptions).apply(parser); + // Filter out exports which are defined by other exports + // and filter out default export because it cannot be reexported with * + if (ignored.size > 1) { + content += + "if(" + + JSON.stringify(Array.from(ignored)) + + ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) "; + } else if (ignored.size === 1) { + content += `if(__WEBPACK_IMPORT_KEY__ !== ${JSON.stringify( + first(ignored) + )}) `; + } - tapOptionsHooks("define.amd", "define", () => "amd"); - tapOptionsHooks("require.amd", "require", () => ["amd"]); - tapOptionsHooks( - "__webpack_amd_options__", - "__webpack_amd_options__", - () => [] - ); + content += `__WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = `; + if (modern) { + content += `() => ${importVar}[__WEBPACK_IMPORT_KEY__]`; + } else { + content += `function(key) { return ${importVar}[key]; }.bind(0, __WEBPACK_IMPORT_KEY__)`; + } - parser.hooks.expression.for("define").tap("AMDPlugin", expr => { - const dep = new ConstDependency( - RuntimeGlobals.amdDefine, - expr.range, - [RuntimeGlobals.amdDefine] - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); - parser.hooks.typeof - .for("define") - .tap( - "AMDPlugin", - toConstantDependency(parser, JSON.stringify("function")) - ); - parser.hooks.evaluateTypeof - .for("define") - .tap("AMDPlugin", evaluateToString("function")); - parser.hooks.canRename.for("define").tap("AMDPlugin", approve); - parser.hooks.rename.for("define").tap("AMDPlugin", expr => { - const dep = new ConstDependency( - RuntimeGlobals.amdDefine, - expr.range, - [RuntimeGlobals.amdDefine] - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return false; - }); - parser.hooks.typeof - .for("require") - .tap( - "AMDPlugin", - toConstantDependency(parser, JSON.stringify("function")) - ); - parser.hooks.evaluateTypeof - .for("require") - .tap("AMDPlugin", evaluateToString("function")); - }; + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("AMDPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("AMDPlugin", handler); + const exportsName = module.exportsArgument; + initFragments.push( + new InitFragment( + `${content}\n/* harmony reexport (unknown) */ ${RuntimeGlobals.definePropertyGetters}(${exportsName}, __WEBPACK_REEXPORT_OBJECT__);\n`, + moduleGraph.isAsync(importedModule) + ? InitFragment.STAGE_ASYNC_HARMONY_IMPORTS + : InitFragment.STAGE_HARMONY_IMPORTS, + dep.sourceOrder + ) + ); + break; } - ); - } -} -module.exports = AMDPlugin; + default: + throw new Error(`Unknown mode ${mode.type}`); + } + } + getReexportFragment( + module, + comment, + key, + name, + valueKey, + runtimeRequirements + ) { + const returnValue = this.getReturnValue(name, valueKey); -/***/ }), + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); -/***/ 33516: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const map = new Map(); + map.set(key, `/* ${comment} */ ${returnValue}`); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return new HarmonyExportInitFragment(module.exportsArgument, map); + } + getReexportFakeNamespaceObjectFragments( + module, + key, + name, + fakeType, + runtimeRequirements + ) { + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + const map = new Map(); + map.set( + key, + `/* reexport fake namespace object from non-harmony */ ${name}_namespace_cache || (${name}_namespace_cache = ${ + RuntimeGlobals.createFakeNamespaceObject + }(${name}${fakeType ? `, ${fakeType}` : ""}))` + ); -const DependencyTemplate = __webpack_require__(5160); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); + return [ + new InitFragment( + `var ${name}_namespace_cache;\n`, + InitFragment.STAGE_CONSTANTS, + -1, + `${name}_namespace_cache` + ), + new HarmonyExportInitFragment(module.exportsArgument, map) + ]; + } -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + getConditionalReexportStatement( + module, + key, + name, + valueKey, + runtimeRequirements + ) { + if (valueKey === false) { + return "/* unused export */\n"; + } -class AMDRequireArrayDependency extends NullDependency { - constructor(depsArray, range) { - super(); + const exportsName = module.exportsArgument; + const returnValue = this.getReturnValue(name, valueKey); - this.depsArray = depsArray; - this.range = range; - } + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + runtimeRequirements.add(RuntimeGlobals.hasOwnProperty); - get type() { - return "amd require array"; + return `if(${RuntimeGlobals.hasOwnProperty}(${name}, ${JSON.stringify( + valueKey[0] + )})) ${ + RuntimeGlobals.definePropertyGetters + }(${exportsName}, { ${JSON.stringify( + key + )}: function() { return ${returnValue}; } });\n`; } - get category() { - return "amd"; - } + getReturnValue(name, valueKey) { + if (valueKey === null) { + return `${name}_default.a`; + } - serialize(context) { - const { write } = context; + if (valueKey === "") { + return name; + } - write(this.depsArray); - write(this.range); + if (valueKey === false) { + return "/* unused export */ undefined"; + } - super.serialize(context); + return `${name}${propertyAccess(valueKey)}`; } +}; - deserialize(context) { - const { read } = context; - - this.depsArray = read(); - this.range = read(); - - super.deserialize(context); +class HarmonyStarExportsList { + constructor() { + /** @type {HarmonyExportImportedSpecifierDependency[]} */ + this.dependencies = []; } -} - -makeSerializable( - AMDRequireArrayDependency, - "webpack/lib/dependencies/AMDRequireArrayDependency" -); -AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate extends ( - DependencyTemplate -) { /** - * @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 + * @param {HarmonyExportImportedSpecifierDependency} dep dependency * @returns {void} */ - apply(dependency, source, templateContext) { - const dep = /** @type {AMDRequireArrayDependency} */ (dependency); - const content = this.getContent(dep, templateContext); - source.replace(dep.range[0], dep.range[1] - 1, content); + push(dep) { + this.dependencies.push(dep); } - getContent(dep, templateContext) { - const requires = dep.depsArray.map(dependency => { - return this.contentForDependency(dependency, templateContext); - }); - return `[${requires.join(", ")}]`; + slice() { + return this.dependencies.slice(); } - contentForDependency( - dep, - { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } - ) { - if (typeof dep === "string") { - return dep; - } + serialize({ write, setCircularReference }) { + setCircularReference(this); + write(this.dependencies); + } - if (dep.localModule) { - return dep.localModule.variableName(); - } else { - return runtimeTemplate.moduleExports({ - module: moduleGraph.getModule(dep), - chunkGraph, - request: dep.request, - runtimeRequirements - }); - } + deserialize({ read, setCircularReference }) { + setCircularReference(this); + this.dependencies = read(); } -}; +} -module.exports = AMDRequireArrayDependency; +makeSerializable( + HarmonyStarExportsList, + "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency", + "HarmonyStarExportsList" +); + +module.exports.HarmonyStarExportsList = HarmonyStarExportsList; /***/ }), -/***/ 96123: +/***/ 89500: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -78844,374 +78028,169 @@ module.exports = AMDRequireArrayDependency; -const makeSerializable = __webpack_require__(33032); -const ContextDependency = __webpack_require__(88101); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const { first } = __webpack_require__(93347); -class AMDRequireContextDependency extends ContextDependency { - constructor(options, range, valueRange) { - super(options); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ - this.range = range; - this.valueRange = valueRange; +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; +}; - get type() { - return "amd require context"; - } - - get category() { - return "amd"; - } - - serialize(context) { - const { write } = context; - - write(this.range); - write(this.valueRange); - - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - - this.range = read(); - this.valueRange = read(); - - super.deserialize(context); - } -} - -makeSerializable( - AMDRequireContextDependency, - "webpack/lib/dependencies/AMDRequireContextDependency" -); - -AMDRequireContextDependency.Template = __webpack_require__(75815); - -module.exports = AMDRequireContextDependency; - - -/***/ }), - -/***/ 76932: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const AsyncDependenciesBlock = __webpack_require__(47736); -const makeSerializable = __webpack_require__(33032); +const EMPTY_MAP = new Map(); +const EMPTY_SET = new Set(); -class AMDRequireDependenciesBlock extends AsyncDependenciesBlock { - constructor(loc, request) { - super(null, loc, request); +/** + * @typedef {GenerateContext} Context + */ +class HarmonyExportInitFragment extends InitFragment { + /** + * @param {string} exportsArgument the exports identifier + * @param {Map} exportMap mapping from used name to exposed variable name + * @param {Set} unusedExports list of unused export names + */ + constructor( + exportsArgument, + exportMap = EMPTY_MAP, + unusedExports = EMPTY_SET + ) { + super(undefined, InitFragment.STAGE_HARMONY_EXPORTS, 1, "harmony-exports"); + this.exportsArgument = exportsArgument; + this.exportMap = exportMap; + this.unusedExports = unusedExports; } -} - -makeSerializable( - AMDRequireDependenciesBlock, - "webpack/lib/dependencies/AMDRequireDependenciesBlock" -); - -module.exports = AMDRequireDependenciesBlock; - - -/***/ }), - -/***/ 66866: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {HarmonyExportInitFragment[]} fragments all fragments to merge + * @returns {HarmonyExportInitFragment} merged fragment + */ + mergeAll(fragments) { + let exportMap; + let exportMapOwned = false; + let unusedExports; + let unusedExportsOwned = false; - -const RuntimeGlobals = __webpack_require__(16475); -const UnsupportedFeatureWarning = __webpack_require__(42495); -const AMDRequireArrayDependency = __webpack_require__(33516); -const AMDRequireContextDependency = __webpack_require__(96123); -const AMDRequireDependenciesBlock = __webpack_require__(76932); -const AMDRequireDependency = __webpack_require__(43911); -const AMDRequireItemDependency = __webpack_require__(71806); -const ConstDependency = __webpack_require__(76911); -const ContextDependencyHelpers = __webpack_require__(99630); -const LocalModuleDependency = __webpack_require__(52805); -const { getLocalModule } = __webpack_require__(75827); -const UnsupportedDependency = __webpack_require__(51669); -const getFunctionExpression = __webpack_require__(50396); - -class AMDRequireDependenciesBlockParserPlugin { - constructor(options) { - this.options = options; - } - - processFunctionArgument(parser, expression) { - let bindThis = true; - const fnData = getFunctionExpression(expression); - if (fnData) { - parser.inScope( - fnData.fn.params.filter(i => { - return !["require", "module", "exports"].includes(i.name); - }), - () => { - if (fnData.fn.body.type === "BlockStatement") { - parser.walkStatement(fnData.fn.body); - } else { - parser.walkExpression(fnData.fn.body); + for (const fragment of fragments) { + if (fragment.exportMap.size !== 0) { + if (exportMap === undefined) { + exportMap = fragment.exportMap; + exportMapOwned = false; + } else { + if (!exportMapOwned) { + exportMap = new Map(exportMap); + exportMapOwned = true; + } + for (const [key, value] of fragment.exportMap) { + if (!exportMap.has(key)) exportMap.set(key, value); } - } - ); - parser.walkExpressions(fnData.expressions); - if (fnData.needThis === false) { - bindThis = false; - } - } else { - parser.walkExpression(expression); - } - return bindThis; - } - - apply(parser) { - parser.hooks.call - .for("require") - .tap( - "AMDRequireDependenciesBlockParserPlugin", - this.processCallRequire.bind(this, parser) - ); - } - - processArray(parser, expr, param) { - if (param.isArray()) { - for (const p of param.items) { - const result = this.processItem(parser, expr, p); - if (result === undefined) { - this.processContext(parser, expr, p); } } - return true; - } else if (param.isConstArray()) { - const deps = []; - for (const request of param.array) { - let dep, localModule; - if (request === "require") { - dep = "__webpack_require__"; - } else if (["exports", "module"].includes(request)) { - dep = request; - } else if ((localModule = getLocalModule(parser.state, request))) { - localModule.flagUsed(); - dep = new LocalModuleDependency(localModule, undefined, false); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); + if (fragment.unusedExports.size !== 0) { + if (unusedExports === undefined) { + unusedExports = fragment.unusedExports; + unusedExportsOwned = false; } else { - dep = this.newRequireItemDependency(request); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - } - deps.push(dep); - } - const dep = this.newRequireArrayDependency(deps, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.module.addPresentationalDependency(dep); - return true; - } - } - processItem(parser, expr, param) { - if (param.isConditional()) { - for (const p of param.options) { - const result = this.processItem(parser, expr, p); - if (result === undefined) { - this.processContext(parser, expr, p); + if (!unusedExportsOwned) { + unusedExports = new Set(unusedExports); + unusedExportsOwned = true; + } + for (const value of fragment.unusedExports) { + unusedExports.add(value); + } } } - return true; - } else if (param.isString()) { - let dep, localModule; - if (param.string === "require") { - dep = new ConstDependency("__webpack_require__", param.string, [ - RuntimeGlobals.require - ]); - } else if (param.string === "module") { - dep = new ConstDependency( - parser.state.module.buildInfo.moduleArgument, - param.range, - [RuntimeGlobals.module] - ); - } else if (param.string === "exports") { - dep = new ConstDependency( - parser.state.module.buildInfo.exportsArgument, - param.range, - [RuntimeGlobals.exports] - ); - } else if ((localModule = getLocalModule(parser.state, param.string))) { - localModule.flagUsed(); - dep = new LocalModuleDependency(localModule, param.range, false); - } else { - dep = this.newRequireItemDependency(param.string, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; } - } - processContext(parser, expr, param) { - const dep = ContextDependencyHelpers.create( - AMDRequireContextDependency, - param.range, - param, - expr, - this.options, - { - category: "amd" - }, - parser + return new HarmonyExportInitFragment( + this.exportsArgument, + exportMap, + unusedExports ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; } - processArrayForRequestString(param) { - if (param.isArray()) { - const result = param.items.map(item => - this.processItemForRequestString(item) - ); - if (result.every(Boolean)) return result.join(" "); - } else if (param.isConstArray()) { - return param.array.join(" "); + merge(other) { + let exportMap; + if (this.exportMap.size === 0) { + exportMap = other.exportMap; + } else if (other.exportMap.size === 0) { + exportMap = this.exportMap; + } else { + exportMap = new Map(other.exportMap); + for (const [key, value] of this.exportMap) { + if (!exportMap.has(key)) exportMap.set(key, value); + } } - } - - processItemForRequestString(param) { - if (param.isConditional()) { - const result = param.options.map(item => - this.processItemForRequestString(item) - ); - if (result.every(Boolean)) return result.join("|"); - } else if (param.isString()) { - return param.string; + let unusedExports; + if (this.unusedExports.size === 0) { + unusedExports = other.unusedExports; + } else if (other.unusedExports.size === 0) { + unusedExports = this.unusedExports; + } else { + unusedExports = new Set(other.unusedExports); + for (const value of this.unusedExports) { + unusedExports.add(value); + } } + return new HarmonyExportInitFragment( + this.exportsArgument, + exportMap, + unusedExports + ); } - processCallRequire(parser, expr) { - let param; - let depBlock; - let dep; - let result; - - const old = parser.state.current; + /** + * @param {Context} context context + * @returns {string|Source} the source code that will be included as initialization code + */ + getContent({ runtimeTemplate, runtimeRequirements }) { + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - if (expr.arguments.length >= 1) { - param = parser.evaluateExpression(expr.arguments[0]); - depBlock = this.newRequireDependenciesBlock( - expr.loc, - this.processArrayForRequestString(param) - ); - dep = this.newRequireDependency( - expr.range, - param.range, - expr.arguments.length > 1 ? expr.arguments[1].range : null, - expr.arguments.length > 2 ? expr.arguments[2].range : null + const unusedPart = + this.unusedExports.size > 1 + ? `/* unused harmony exports ${joinIterableWithComma( + this.unusedExports + )} */\n` + : this.unusedExports.size > 0 + ? `/* unused harmony export ${first(this.unusedExports)} */\n` + : ""; + const definitions = []; + for (const [key, value] of this.exportMap) { + definitions.push( + `\n/* harmony export */ ${JSON.stringify( + key + )}: ${runtimeTemplate.returningFunction(value)}` ); - dep.loc = expr.loc; - depBlock.addDependency(dep); - - parser.state.current = depBlock; - } - - if (expr.arguments.length === 1) { - parser.inScope([], () => { - result = this.processArray(parser, expr, param); - }); - parser.state.current = old; - if (!result) return; - parser.state.current.addBlock(depBlock); - return true; - } - - if (expr.arguments.length === 2 || expr.arguments.length === 3) { - try { - parser.inScope([], () => { - result = this.processArray(parser, expr, param); - }); - if (!result) { - const dep = new UnsupportedDependency("unsupported", expr.range); - old.addPresentationalDependency(dep); - if (parser.state.module) { - parser.state.module.addError( - new UnsupportedFeatureWarning( - "Cannot statically analyse 'require(…, …)' in line " + - expr.loc.start.line, - expr.loc - ) - ); - } - depBlock = null; - return true; - } - dep.functionBindThis = this.processFunctionArgument( - parser, - expr.arguments[1] - ); - if (expr.arguments.length === 3) { - dep.errorCallbackBindThis = this.processFunctionArgument( - parser, - expr.arguments[2] - ); - } - } finally { - parser.state.current = old; - if (depBlock) parser.state.current.addBlock(depBlock); - } - return true; } - } - - newRequireDependenciesBlock(loc, request) { - return new AMDRequireDependenciesBlock(loc, request); - } - newRequireDependency( - outerRange, - arrayRange, - functionRange, - errorCallbackRange - ) { - return new AMDRequireDependency( - outerRange, - arrayRange, - functionRange, - errorCallbackRange - ); - } - newRequireItemDependency(request, range) { - return new AMDRequireItemDependency(request, range); - } - newRequireArrayDependency(depsArray, range) { - return new AMDRequireArrayDependency(depsArray, range); + const definePart = + this.exportMap.size > 0 + ? `/* harmony export */ ${RuntimeGlobals.definePropertyGetters}(${ + this.exportsArgument + }, {${definitions.join(",")}\n/* harmony export */ });\n` + : ""; + return `${definePart}${unusedPart}`; } } -module.exports = AMDRequireDependenciesBlockParserPlugin; + +module.exports = HarmonyExportInitFragment; /***/ }), -/***/ 43911: +/***/ 48567: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -79222,64 +78201,71 @@ module.exports = AMDRequireDependenciesBlockParserPlugin; -const RuntimeGlobals = __webpack_require__(16475); const makeSerializable = __webpack_require__(33032); +const HarmonyExportInitFragment = __webpack_require__(89500); const NullDependency = __webpack_require__(31830); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ /** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -class AMDRequireDependency extends NullDependency { - constructor(outerRange, arrayRange, functionRange, errorCallbackRange) { +class HarmonyExportSpecifierDependency extends NullDependency { + constructor(id, name) { super(); + this.id = id; + this.name = name; + } - this.outerRange = outerRange; - this.arrayRange = arrayRange; - this.functionRange = functionRange; - this.errorCallbackRange = errorCallbackRange; - this.functionBindThis = false; - this.errorCallbackBindThis = false; + get type() { + return "harmony export specifier"; } - get category() { - return "amd"; + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + return { + exports: [this.name], + priority: 1, + terminalBinding: true, + dependencies: undefined + }; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; } serialize(context) { const { write } = context; - - write(this.outerRange); - write(this.arrayRange); - write(this.functionRange); - write(this.errorCallbackRange); - write(this.functionBindThis); - write(this.errorCallbackBindThis); - + write(this.id); + write(this.name); super.serialize(context); } deserialize(context) { const { read } = context; - - this.outerRange = read(); - this.arrayRange = read(); - this.functionRange = read(); - this.errorCallbackRange = read(); - this.functionBindThis = read(); - this.errorCallbackBindThis = read(); - + this.id = read(); + this.name = read(); super.deserialize(context); } } makeSerializable( - AMDRequireDependency, - "webpack/lib/dependencies/AMDRequireDependency" + HarmonyExportSpecifierDependency, + "webpack/lib/dependencies/HarmonyExportSpecifierDependency" ); -AMDRequireDependency.Template = class AMDRequireDependencyTemplate extends ( +HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate extends ( NullDependency.Template ) { /** @@ -79291,109 +78277,87 @@ AMDRequireDependency.Template = class AMDRequireDependencyTemplate extends ( apply( dependency, source, - { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + { module, moduleGraph, initFragments, runtime, concatenationScope } ) { - const dep = /** @type {AMDRequireDependency} */ (dependency); - const depBlock = /** @type {AsyncDependenciesBlock} */ ( - moduleGraph.getParentBlock(dep) - ); - const promise = runtimeTemplate.blockPromise({ - chunkGraph, - block: depBlock, - message: "AMD require", - runtimeRequirements - }); - - // has array range but no function range - if (dep.arrayRange && !dep.functionRange) { - const startBlock = `${promise}.then(function() {`; - const endBlock = `;})['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; - runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); - - source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); - - source.replace(dep.arrayRange[1], dep.outerRange[1] - 1, endBlock); - + const dep = /** @type {HarmonyExportSpecifierDependency} */ (dependency); + if (concatenationScope) { + concatenationScope.registerExport(dep.name, dep.id); return; } - - // has function range but no array range - if (dep.functionRange && !dep.arrayRange) { - const startBlock = `${promise}.then((`; - const endBlock = `).bind(exports, __webpack_require__, exports, module))['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; - runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); - - source.replace(dep.outerRange[0], dep.functionRange[0] - 1, startBlock); - - source.replace(dep.functionRange[1], dep.outerRange[1] - 1, endBlock); - + const used = moduleGraph + .getExportsInfo(module) + .getUsedName(dep.name, runtime); + if (!used) { + const set = new Set(); + set.add(dep.name || "namespace"); + initFragments.push( + new HarmonyExportInitFragment(module.exportsArgument, undefined, set) + ); return; } - // has array range, function range, and errorCallbackRange - if (dep.arrayRange && dep.functionRange && dep.errorCallbackRange) { - const startBlock = `${promise}.then(function() { `; - const errorRangeBlock = `}${ - dep.functionBindThis ? ".bind(this)" : "" - })['catch'](`; - const endBlock = `${dep.errorCallbackBindThis ? ".bind(this)" : ""})`; - - source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); - - source.insert(dep.arrayRange[0], "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); - - source.replace(dep.arrayRange[1], dep.functionRange[0] - 1, "; ("); + const map = new Map(); + map.set(used, `/* binding */ ${dep.id}`); + initFragments.push( + new HarmonyExportInitFragment(module.exportsArgument, map, undefined) + ); + } +}; - source.insert( - dep.functionRange[1], - ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" - ); +module.exports = HarmonyExportSpecifierDependency; - source.replace( - dep.functionRange[1], - dep.errorCallbackRange[0] - 1, - errorRangeBlock - ); - source.replace( - dep.errorCallbackRange[1], - dep.outerRange[1] - 1, - endBlock - ); +/***/ }), - return; - } +/***/ 39211: +/***/ (function(__unused_webpack_module, exports) { - // has array range, function range, but no errorCallbackRange - if (dep.arrayRange && dep.functionRange) { - const startBlock = `${promise}.then(function() { `; - const endBlock = `}${ - dep.functionBindThis ? ".bind(this)" : "" - })['catch'](${RuntimeGlobals.uncaughtErrorHandler})`; - runtimeRequirements.add(RuntimeGlobals.uncaughtErrorHandler); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - source.replace(dep.outerRange[0], dep.arrayRange[0] - 1, startBlock); - source.insert(dep.arrayRange[0], "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); - source.replace(dep.arrayRange[1], dep.functionRange[0] - 1, "; ("); +/** @typedef {import("../Parser").ParserState} ParserState */ - source.insert( - dep.functionRange[1], - ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" - ); +/** @type {WeakMap} */ +const parserStateExportsState = new WeakMap(); - source.replace(dep.functionRange[1], dep.outerRange[1] - 1, endBlock); +/** + * @param {ParserState} parserState parser state + * @param {boolean} isStrictHarmony strict harmony mode should be enabled + * @returns {void} + */ +exports.enable = (parserState, isStrictHarmony) => { + const value = parserStateExportsState.get(parserState); + if (value === false) return; + parserStateExportsState.set(parserState, true); + if (value !== true) { + parserState.module.buildMeta.exportsType = "namespace"; + parserState.module.buildInfo.strict = true; + parserState.module.buildInfo.exportsArgument = "__webpack_exports__"; + if (isStrictHarmony) { + parserState.module.buildMeta.strictHarmonyModule = true; + parserState.module.buildInfo.moduleArgument = "__webpack_module__"; } } }; -module.exports = AMDRequireDependency; +/** + * @param {ParserState} parserState parser state + * @returns {boolean} true, when enabled + */ +exports.isEnabled = parserState => { + const value = parserStateExportsState.get(parserState); + return value === true; +}; /***/ }), -/***/ 71806: +/***/ 57154: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -79404,170 +78368,244 @@ module.exports = AMDRequireDependency; -const makeSerializable = __webpack_require__(33032); +const ConditionalInitFragment = __webpack_require__(61333); +const Dependency = __webpack_require__(54912); +const HarmonyLinkingError = __webpack_require__(97511); +const InitFragment = __webpack_require__(55870); +const Template = __webpack_require__(1626); +const AwaitDependenciesInitFragment = __webpack_require__(41153); +const { filterRuntime, mergeRuntime } = __webpack_require__(17156); const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyTemplateAsRequireId = __webpack_require__(36873); -class AMDRequireItemDependency extends ModuleDependency { - constructor(request, range) { - super(request); +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - this.range = range; +const ExportPresenceModes = { + NONE: /** @type {0} */ (0), + WARN: /** @type {1} */ (1), + AUTO: /** @type {2} */ (2), + ERROR: /** @type {3} */ (3), + fromUserOption(str) { + switch (str) { + case "error": + return ExportPresenceModes.ERROR; + case "warn": + return ExportPresenceModes.WARN; + case "auto": + return ExportPresenceModes.AUTO; + case false: + return ExportPresenceModes.NONE; + default: + throw new Error(`Invalid export presence value ${str}`); + } } +}; - get type() { - return "amd require"; +class HarmonyImportDependency extends ModuleDependency { + /** + * + * @param {string} request request string + * @param {number} sourceOrder source order + * @param {Record=} assertions import assertions + */ + constructor(request, sourceOrder, assertions) { + super(request); + this.sourceOrder = sourceOrder; + this.assertions = assertions; } get category() { - return "amd"; - } -} - -makeSerializable( - AMDRequireItemDependency, - "webpack/lib/dependencies/AMDRequireItemDependency" -); - -AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; - -module.exports = AMDRequireItemDependency; - - -/***/ }), - -/***/ 45242: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); - -class AMDDefineRuntimeModule extends RuntimeModule { - constructor() { - super("amd define"); + return "esm"; } /** - * @returns {string} runtime code + * 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 */ - generate() { - return Template.asString([ - `${RuntimeGlobals.amdDefine} = function () {`, - Template.indent("throw new Error('define cannot be used indirect');"), - "};" - ]); + getReferencedExports(moduleGraph, runtime) { + return Dependency.NO_EXPORTS_REFERENCED; } -} -class AMDOptionsRuntimeModule extends RuntimeModule { /** - * @param {Record} options the AMD options + * @param {ModuleGraph} moduleGraph the module graph + * @returns {string} name of the variable for the import */ - constructor(options) { - super("amd options"); - this.options = options; + getImportVar(moduleGraph) { + const module = moduleGraph.getParentModule(this); + const meta = moduleGraph.getMeta(module); + let importVarMap = meta.importVarMap; + if (!importVarMap) meta.importVarMap = importVarMap = new Map(); + let importVar = importVarMap.get(moduleGraph.getModule(this)); + if (importVar) return importVar; + importVar = `${Template.toIdentifier( + `${this.userRequest}` + )}__WEBPACK_IMPORTED_MODULE_${importVarMap.size}__`; + importVarMap.set(moduleGraph.getModule(this), importVar); + return importVar; } /** - * @returns {string} runtime code + * @param {boolean} update create new variables or update existing one + * @param {DependencyTemplateContext} templateContext the template context + * @returns {[string, string]} the import statement and the compat statement */ - generate() { - return Template.asString([ - `${RuntimeGlobals.amdOptions} = ${JSON.stringify(this.options)};` - ]); + getImportStatement( + update, + { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } + ) { + return runtimeTemplate.importStatement({ + update, + module: moduleGraph.getModule(this), + chunkGraph, + importVar: this.getImportVar(moduleGraph), + request: this.request, + originModule: module, + runtimeRequirements + }); } -} - -exports.AMDDefineRuntimeModule = AMDDefineRuntimeModule; -exports.AMDOptionsRuntimeModule = AMDOptionsRuntimeModule; - - -/***/ }), - -/***/ 57403: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ + /** + * @param {ModuleGraph} moduleGraph module graph + * @param {string[]} ids imported ids + * @param {string} additionalMessage extra info included in the error message + * @returns {WebpackError[] | undefined} errors + */ + getLinkingErrors(moduleGraph, ids, additionalMessage) { + const importedModule = moduleGraph.getModule(this); + // ignore errors for missing or failed modules + if (!importedModule || importedModule.getNumberOfErrors() > 0) { + return; + } + const parentModule = moduleGraph.getParentModule(this); + const exportsType = importedModule.getExportsType( + moduleGraph, + parentModule.buildMeta.strictHarmonyModule + ); + if (exportsType === "namespace" || exportsType === "default-with-named") { + if (ids.length === 0) { + return; + } -const DependencyTemplate = __webpack_require__(5160); -const InitFragment = __webpack_require__(55870); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../util/Hash")} Hash */ - -class CachedConstDependency extends NullDependency { - constructor(expression, range, identifier) { - super(); + if ( + (exportsType !== "default-with-named" || ids[0] !== "default") && + moduleGraph.isExportProvided(importedModule, ids) === false + ) { + // We are sure that it's not provided - this.expression = expression; - this.range = range; - this.identifier = identifier; - this._hashUpdate = undefined; - } + // Try to provide detailed info in the error message + let pos = 0; + let exportsInfo = moduleGraph.getExportsInfo(importedModule); + while (pos < ids.length && exportsInfo) { + const id = ids[pos++]; + const exportInfo = exportsInfo.getReadOnlyExportInfo(id); + if (exportInfo.provided === false) { + // We are sure that it's not provided + const providedExports = exportsInfo.getProvidedExports(); + const moreInfo = !Array.isArray(providedExports) + ? " (possible exports unknown)" + : providedExports.length === 0 + ? " (module has no exports)" + : ` (possible exports: ${providedExports.join(", ")})`; + return [ + new HarmonyLinkingError( + `export ${ids + .slice(0, pos) + .map(id => `'${id}'`) + .join(".")} ${additionalMessage} was not found in '${ + this.userRequest + }'${moreInfo}` + ) + ]; + } + exportsInfo = exportInfo.getNestedExportsInfo(); + } - /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) - this._hashUpdate = "" + this.identifier + this.range + this.expression; - hash.update(this._hashUpdate); + // General error message + return [ + new HarmonyLinkingError( + `export ${ids + .map(id => `'${id}'`) + .join(".")} ${additionalMessage} was not found in '${ + this.userRequest + }'` + ) + ]; + } + } + switch (exportsType) { + case "default-only": + // It's has only a default export + if (ids.length > 0 && ids[0] !== "default") { + // In strict harmony modules we only support the default export + return [ + new HarmonyLinkingError( + `Can't import the named export ${ids + .map(id => `'${id}'`) + .join( + "." + )} ${additionalMessage} from default-exporting module (only default export is available)` + ) + ]; + } + break; + case "default-with-named": + // It has a default export and named properties redirect + // In some cases we still want to warn here + if ( + ids.length > 0 && + ids[0] !== "default" && + importedModule.buildMeta.defaultObject === "redirect-warn" + ) { + // For these modules only the default export is supported + return [ + new HarmonyLinkingError( + `Should not import the named export ${ids + .map(id => `'${id}'`) + .join( + "." + )} ${additionalMessage} from default-exporting module (only default export is available soon)` + ) + ]; + } + break; + } } serialize(context) { const { write } = context; - - write(this.expression); - write(this.range); - write(this.identifier); - + write(this.sourceOrder); + write(this.assertions); super.serialize(context); } deserialize(context) { const { read } = context; - - this.expression = read(); - this.range = read(); - this.identifier = read(); - + this.sourceOrder = read(); + this.assertions = read(); super.deserialize(context); } } -makeSerializable( - CachedConstDependency, - "webpack/lib/dependencies/CachedConstDependency" -); +module.exports = HarmonyImportDependency; -CachedConstDependency.Template = class CachedConstDependencyTemplate extends ( - DependencyTemplate +/** @type {WeakMap>} */ +const importEmittedMap = new WeakMap(); + +HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends ( + ModuleDependency.Template ) { /** * @param {Dependency} dependency the dependency for which the template should be applied @@ -79575,95 +78613,470 @@ CachedConstDependency.Template = class CachedConstDependencyTemplate extends ( * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ - apply( - dependency, - source, - { runtimeTemplate, dependencyTemplates, initFragments } - ) { - const dep = /** @type {CachedConstDependency} */ (dependency); + apply(dependency, source, templateContext) { + const dep = /** @type {HarmonyImportDependency} */ (dependency); + const { module, chunkGraph, moduleGraph, runtime } = templateContext; - initFragments.push( - new InitFragment( - `var ${dep.identifier} = ${dep.expression};\n`, - InitFragment.STAGE_CONSTANTS, - 0, - `const ${dep.identifier}` - ) - ); + const connection = moduleGraph.getConnection(dep); + if (connection && !connection.isTargetActive(runtime)) return; - if (typeof dep.range === "number") { - source.insert(dep.range, dep.identifier); + const referencedModule = connection && connection.module; + if ( + connection && + connection.weak && + referencedModule && + chunkGraph.getModuleId(referencedModule) === null + ) { + // in weak references, module might not be in any chunk + // but that's ok, we don't need that logic in this case return; } - source.replace(dep.range[0], dep.range[1] - 1, dep.identifier); - } -}; - -module.exports = CachedConstDependency; - - -/***/ }), - -/***/ 59643: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + const moduleKey = referencedModule + ? referencedModule.identifier() + : dep.request; + const key = `harmony import ${moduleKey}`; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const runtimeCondition = dep.weak + ? false + : connection + ? filterRuntime(runtime, r => connection.isTargetActive(r)) + : true; + if (module && referencedModule) { + let emittedModules = importEmittedMap.get(module); + if (emittedModules === undefined) { + emittedModules = new WeakMap(); + importEmittedMap.set(module, emittedModules); + } + let mergedRuntimeCondition = runtimeCondition; + const oldRuntimeCondition = emittedModules.get(referencedModule) || false; + if (oldRuntimeCondition !== false && mergedRuntimeCondition !== true) { + if (mergedRuntimeCondition === false || oldRuntimeCondition === true) { + mergedRuntimeCondition = oldRuntimeCondition; + } else { + mergedRuntimeCondition = mergeRuntime( + oldRuntimeCondition, + mergedRuntimeCondition + ); + } + } + emittedModules.set(referencedModule, mergedRuntimeCondition); + } + const importStatement = dep.getImportStatement(false, templateContext); + if ( + referencedModule && + templateContext.moduleGraph.isAsync(referencedModule) + ) { + templateContext.initFragments.push( + new ConditionalInitFragment( + importStatement[0], + InitFragment.STAGE_HARMONY_IMPORTS, + dep.sourceOrder, + key, + runtimeCondition + ) + ); + templateContext.initFragments.push( + new AwaitDependenciesInitFragment( + new Set([dep.getImportVar(templateContext.moduleGraph)]) + ) + ); + templateContext.initFragments.push( + new ConditionalInitFragment( + importStatement[1], + InitFragment.STAGE_ASYNC_HARMONY_IMPORTS, + dep.sourceOrder, + key + " compat", + runtimeCondition + ) + ); + } else { + templateContext.initFragments.push( + new ConditionalInitFragment( + importStatement[0] + importStatement[1], + InitFragment.STAGE_HARMONY_IMPORTS, + dep.sourceOrder, + key, + runtimeCondition + ) + ); + } + } -const RuntimeGlobals = __webpack_require__(16475); + /** + * + * @param {Module} module the module + * @param {Module} referencedModule the referenced module + * @returns {RuntimeSpec | boolean} runtimeCondition in which this import has been emitted + */ + static getImportEmittedRuntime(module, referencedModule) { + const emittedModules = importEmittedMap.get(module); + if (emittedModules === undefined) return false; + return emittedModules.get(referencedModule) || false; + } +}; -exports.handleDependencyBase = (depBase, module, runtimeRequirements) => { - let base = undefined; - let type; - switch (depBase) { - case "exports": - runtimeRequirements.add(RuntimeGlobals.exports); - base = module.exportsArgument; - type = "expression"; - break; - case "module.exports": - runtimeRequirements.add(RuntimeGlobals.module); - base = `${module.moduleArgument}.exports`; - type = "expression"; - break; - case "this": - runtimeRequirements.add(RuntimeGlobals.thisAsExports); - base = "this"; - type = "expression"; - break; - case "Object.defineProperty(exports)": - runtimeRequirements.add(RuntimeGlobals.exports); - base = module.exportsArgument; - type = "Object.defineProperty"; - break; - case "Object.defineProperty(module.exports)": - runtimeRequirements.add(RuntimeGlobals.module); - base = `${module.moduleArgument}.exports`; - type = "Object.defineProperty"; - break; - case "Object.defineProperty(this)": - runtimeRequirements.add(RuntimeGlobals.thisAsExports); - base = "this"; - type = "Object.defineProperty"; - break; - default: - throw new Error(`Unsupported base ${depBase}`); +module.exports.ExportPresenceModes = ExportPresenceModes; + + +/***/ }), + +/***/ 20862: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const HotModuleReplacementPlugin = __webpack_require__(6404); +const InnerGraph = __webpack_require__(38988); +const ConstDependency = __webpack_require__(76911); +const HarmonyAcceptDependency = __webpack_require__(23624); +const HarmonyAcceptImportDependency = __webpack_require__(99843); +const HarmonyExports = __webpack_require__(39211); +const { ExportPresenceModes } = __webpack_require__(57154); +const HarmonyImportSideEffectDependency = __webpack_require__(73132); +const HarmonyImportSpecifierDependency = __webpack_require__(14077); + +/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */ +/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */ +/** @typedef {import("estree").Identifier} Identifier */ +/** @typedef {import("estree").ImportDeclaration} ImportDeclaration */ +/** @typedef {import("estree").ImportExpression} ImportExpression */ +/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../optimize/InnerGraph").InnerGraph} InnerGraph */ +/** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */ +/** @typedef {import("./HarmonyImportDependency")} HarmonyImportDependency */ + +const harmonySpecifierTag = Symbol("harmony import"); + +/** + * @typedef {Object} HarmonySettings + * @property {string[]} ids + * @property {string} source + * @property {number} sourceOrder + * @property {string} name + * @property {boolean} await + * @property {Record | undefined} assertions + */ + +/** + * @param {ImportDeclaration | ExportNamedDeclaration | ExportAllDeclaration | ImportExpression} node node with assertions + * @returns {Record | undefined} assertions + */ +function getAssertions(node) { + // TODO remove cast when @types/estree has been updated to import assertions + const assertions = /** @type {{ assertions?: ImportAttributeNode[] }} */ ( + node + ).assertions; + if (assertions === undefined) { + return undefined; + } + const result = {}; + for (const assertion of assertions) { + const key = + assertion.key.type === "Identifier" + ? assertion.key.name + : assertion.key.value; + result[key] = assertion.value.value; } + return result; +} - return [type, base]; +module.exports = class HarmonyImportDependencyParserPlugin { + /** + * @param {JavascriptParserOptions} options options + */ + constructor(options) { + this.exportPresenceMode = + options.importExportsPresence !== undefined + ? ExportPresenceModes.fromUserOption(options.importExportsPresence) + : options.exportsPresence !== undefined + ? ExportPresenceModes.fromUserOption(options.exportsPresence) + : options.strictExportPresence + ? ExportPresenceModes.ERROR + : ExportPresenceModes.AUTO; + this.strictThisContextOnImports = options.strictThisContextOnImports; + } + + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + apply(parser) { + const { exportPresenceMode } = this; + parser.hooks.isPure + .for("Identifier") + .tap("HarmonyImportDependencyParserPlugin", expression => { + const expr = /** @type {Identifier} */ (expression); + if ( + parser.isVariableDefined(expr.name) || + parser.getTagData(expr.name, harmonySpecifierTag) + ) { + return true; + } + }); + parser.hooks.import.tap( + "HarmonyImportDependencyParserPlugin", + (statement, source) => { + parser.state.lastHarmonyImportOrder = + (parser.state.lastHarmonyImportOrder || 0) + 1; + const clearDep = new ConstDependency( + parser.isAsiPosition(statement.range[0]) ? ";" : "", + statement.range + ); + clearDep.loc = statement.loc; + parser.state.module.addPresentationalDependency(clearDep); + parser.unsetAsiPosition(statement.range[1]); + const assertions = getAssertions(statement); + const sideEffectDep = new HarmonyImportSideEffectDependency( + source, + parser.state.lastHarmonyImportOrder, + assertions + ); + sideEffectDep.loc = statement.loc; + parser.state.module.addDependency(sideEffectDep); + return true; + } + ); + parser.hooks.importSpecifier.tap( + "HarmonyImportDependencyParserPlugin", + (statement, source, id, name) => { + const ids = id === null ? [] : [id]; + parser.tagVariable(name, harmonySpecifierTag, { + name, + source, + ids, + sourceOrder: parser.state.lastHarmonyImportOrder, + assertions: getAssertions(statement) + }); + return true; + } + ); + parser.hooks.expression + .for(harmonySpecifierTag) + .tap("HarmonyImportDependencyParserPlugin", expr => { + const settings = /** @type {HarmonySettings} */ (parser.currentTagData); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + settings.sourceOrder, + settings.ids, + settings.name, + expr.range, + exportPresenceMode, + settings.assertions + ); + dep.shorthand = parser.scope.inShorthand; + dep.directImport = true; + dep.asiSafe = !parser.isAsiPosition(expr.range[0]); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); + return true; + }); + parser.hooks.expressionMemberChain + .for(harmonySpecifierTag) + .tap("HarmonyImportDependencyParserPlugin", (expr, members) => { + const settings = /** @type {HarmonySettings} */ (parser.currentTagData); + const ids = settings.ids.concat(members); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + settings.sourceOrder, + ids, + settings.name, + expr.range, + exportPresenceMode, + settings.assertions + ); + dep.asiSafe = !parser.isAsiPosition(expr.range[0]); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); + return true; + }); + parser.hooks.callMemberChain + .for(harmonySpecifierTag) + .tap("HarmonyImportDependencyParserPlugin", (expr, members) => { + const { arguments: args, callee } = expr; + const settings = /** @type {HarmonySettings} */ (parser.currentTagData); + const ids = settings.ids.concat(members); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + settings.sourceOrder, + ids, + settings.name, + callee.range, + exportPresenceMode, + settings.assertions + ); + dep.directImport = members.length === 0; + dep.call = true; + dep.asiSafe = !parser.isAsiPosition(callee.range[0]); + // only in case when we strictly follow the spec we need a special case here + dep.namespaceObjectAsContext = + members.length > 0 && this.strictThisContextOnImports; + dep.loc = callee.loc; + parser.state.module.addDependency(dep); + if (args) parser.walkExpressions(args); + InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); + return true; + }); + const { hotAcceptCallback, hotAcceptWithoutCallback } = + HotModuleReplacementPlugin.getParserHooks(parser); + hotAcceptCallback.tap( + "HarmonyImportDependencyParserPlugin", + (expr, requests) => { + if (!HarmonyExports.isEnabled(parser.state)) { + // This is not a harmony module, skip it + return; + } + const dependencies = requests.map(request => { + const dep = new HarmonyAcceptImportDependency(request); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return dep; + }); + if (dependencies.length > 0) { + const dep = new HarmonyAcceptDependency( + expr.range, + dependencies, + true + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + } + } + ); + hotAcceptWithoutCallback.tap( + "HarmonyImportDependencyParserPlugin", + (expr, requests) => { + if (!HarmonyExports.isEnabled(parser.state)) { + // This is not a harmony module, skip it + return; + } + const dependencies = requests.map(request => { + const dep = new HarmonyAcceptImportDependency(request); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return dep; + }); + if (dependencies.length > 0) { + const dep = new HarmonyAcceptDependency( + expr.range, + dependencies, + false + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + } + } + ); + } }; +module.exports.harmonySpecifierTag = harmonySpecifierTag; +module.exports.getAssertions = getAssertions; + /***/ }), -/***/ 62892: +/***/ 73132: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); +const HarmonyImportDependency = __webpack_require__(57154); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../InitFragment")} InitFragment */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class HarmonyImportSideEffectDependency extends HarmonyImportDependency { + constructor(request, sourceOrder, assertions) { + super(request, sourceOrder, assertions); + } + + get type() { + return "harmony side effect evaluation"; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return connection => { + const refModule = connection.resolvedModule; + if (!refModule) return true; + return refModule.getSideEffectsConnectionState(moduleGraph); + }; + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + const refModule = moduleGraph.getModule(this); + if (!refModule) return true; + return refModule.getSideEffectsConnectionState(moduleGraph); + } +} + +makeSerializable( + HarmonyImportSideEffectDependency, + "webpack/lib/dependencies/HarmonyImportSideEffectDependency" +); + +HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends ( + HarmonyImportDependency.Template +) { + /** + * @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 { moduleGraph, concatenationScope } = templateContext; + if (concatenationScope) { + const module = moduleGraph.getModule(dependency); + if (concatenationScope.isModuleInScope(module)) { + return; + } + } + super.apply(dependency, source, templateContext); + } +}; + +module.exports = HarmonyImportSideEffectDependency; + + +/***/ }), + +/***/ 14077: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -79675,57 +79088,82 @@ exports.handleDependencyBase = (depBase, module, runtimeRequirements) => { const Dependency = __webpack_require__(54912); -const { UsageState } = __webpack_require__(63686); -const Template = __webpack_require__(39722); -const { equals } = __webpack_require__(84953); +const { + getDependencyUsedByExportsCondition +} = __webpack_require__(38988); const makeSerializable = __webpack_require__(33032); const propertyAccess = __webpack_require__(54190); -const { handleDependencyBase } = __webpack_require__(59643); -const ModuleDependency = __webpack_require__(80321); -const processExportInfo = __webpack_require__(55207); +const HarmonyImportDependency = __webpack_require__(57154); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -const idsSymbol = Symbol("CommonJsExportRequireDependency.ids"); +const idsSymbol = Symbol("HarmonyImportSpecifierDependency.ids"); -const EMPTY_OBJECT = {}; +const { ExportPresenceModes } = HarmonyImportDependency; -class CommonJsExportRequireDependency extends ModuleDependency { - constructor(range, valueRange, base, names, request, ids, resultUsed) { - super(request); - this.range = range; - this.valueRange = valueRange; - this.base = base; - this.names = names; +class HarmonyImportSpecifierDependency extends HarmonyImportDependency { + constructor( + request, + sourceOrder, + ids, + name, + range, + exportPresenceMode, + assertions + ) { + super(request, sourceOrder, assertions); this.ids = ids; - this.resultUsed = resultUsed; + this.name = name; + this.range = range; + this.exportPresenceMode = exportPresenceMode; + this.namespaceObjectAsContext = false; + this.call = undefined; + this.directImport = undefined; + this.shorthand = undefined; this.asiSafe = undefined; + /** @type {Set | boolean} */ + this.usedByExports = undefined; } - get type() { - return "cjs export require"; + // TODO webpack 6 remove + get id() { + throw new Error("id was renamed to ids and type changed to string[]"); } - /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module - */ - couldAffectReferencingModule() { - return Dependency.TRANSITIVE; + // TODO webpack 6 remove + getId() { + throw new Error("id was renamed to ids and type changed to string[]"); + } + + // TODO webpack 6 remove + setId() { + throw new Error("id was renamed to ids and type changed to string[]"); + } + + get type() { + return "harmony import specifier"; } /** * @param {ModuleGraph} moduleGraph the module graph - * @returns {string[]} the imported id + * @returns {string[]} the imported ids */ getIds(moduleGraph) { - return moduleGraph.getMeta(this)[idsSymbol] || this.ids; + const meta = moduleGraph.getMetaIfExisting(this); + if (meta === undefined) return this.ids; + const ids = meta[idsSymbol]; + return ids !== undefined ? ids : this.ids; } /** @@ -79737,6 +79175,26 @@ class CommonJsExportRequireDependency extends ModuleDependency { moduleGraph.getMeta(this)[idsSymbol] = ids; } + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return getDependencyUsedByExportsCondition( + this, + this.usedByExports, + moduleGraph + ); + } + + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules + */ + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; + } + /** * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph @@ -79744,233 +79202,138 @@ class CommonJsExportRequireDependency extends ModuleDependency { * @returns {(string[] | ReferencedExport)[]} referenced exports */ getReferencedExports(moduleGraph, runtime) { - const ids = this.getIds(moduleGraph); - const getFullResult = () => { - if (ids.length === 0) { - return Dependency.EXPORTS_OBJECT_REFERENCED; - } else { - return [ - { - name: ids, - canMangle: false - } - ]; + let ids = this.getIds(moduleGraph); + if (ids.length === 0) return Dependency.EXPORTS_OBJECT_REFERENCED; + let namespaceObjectAsContext = this.namespaceObjectAsContext; + if (ids[0] === "default") { + const selfModule = moduleGraph.getParentModule(this); + const importedModule = moduleGraph.getModule(this); + switch ( + importedModule.getExportsType( + moduleGraph, + selfModule.buildMeta.strictHarmonyModule + ) + ) { + case "default-only": + case "default-with-named": + if (ids.length === 1) return Dependency.EXPORTS_OBJECT_REFERENCED; + ids = ids.slice(1); + namespaceObjectAsContext = true; + break; + case "dynamic": + return Dependency.EXPORTS_OBJECT_REFERENCED; } - }; - if (this.resultUsed) return getFullResult(); - let exportsInfo = moduleGraph.getExportsInfo( - moduleGraph.getParentModule(this) - ); - for (const name of this.names) { - const exportInfo = exportsInfo.getReadOnlyExportInfo(name); - const used = exportInfo.getUsed(runtime); - if (used === UsageState.Unused) return Dependency.NO_EXPORTS_REFERENCED; - if (used !== UsageState.OnlyPropertiesUsed) return getFullResult(); - exportsInfo = exportInfo.exportsInfo; - if (!exportsInfo) return getFullResult(); } - if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { - return getFullResult(); + + if ( + this.call && + !this.directImport && + (namespaceObjectAsContext || ids.length > 1) + ) { + if (ids.length === 1) return Dependency.EXPORTS_OBJECT_REFERENCED; + ids = ids.slice(0, -1); } - /** @type {string[][]} */ - const referencedExports = []; - for (const exportInfo of exportsInfo.orderedExports) { - processExportInfo( - runtime, - referencedExports, - ids.concat(exportInfo.name), - exportInfo, - false - ); + + return [ids]; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {number} effective mode + */ + _getEffectiveExportPresenceLevel(moduleGraph) { + if (this.exportPresenceMode !== ExportPresenceModes.AUTO) + return this.exportPresenceMode; + return moduleGraph.getParentModule(this).buildMeta.strictHarmonyModule + ? ExportPresenceModes.ERROR + : ExportPresenceModes.WARN; + } + + /** + * Returns warnings + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} warnings + */ + getWarnings(moduleGraph) { + const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); + if (exportsPresence === ExportPresenceModes.WARN) { + return this._getErrors(moduleGraph); } - return referencedExports.map(name => ({ - name, - canMangle: false - })); + return null; } /** - * Returns the exported names + * Returns errors * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names + * @returns {WebpackError[]} errors */ - getExports(moduleGraph) { - const ids = this.getIds(moduleGraph); - if (this.names.length === 1) { - const name = this.names[0]; - const from = moduleGraph.getConnection(this); - if (!from) return; - return { - exports: [ - { - name, - from, - export: ids.length === 0 ? null : ids, - // we can't mangle names that are in an empty object - // because one could access the prototype property - // when export isn't set yet - canMangle: !(name in EMPTY_OBJECT) && false - } - ], - dependencies: [from.module] - }; - } else if (this.names.length > 0) { - const name = this.names[0]; - return { - exports: [ - { - name, - // we can't mangle names that are in an empty object - // because one could access the prototype property - // when export isn't set yet - canMangle: !(name in EMPTY_OBJECT) && false - } - ], - dependencies: undefined - }; - } else { - const from = moduleGraph.getConnection(this); - if (!from) return; - const reexportInfo = this.getStarReexports( - moduleGraph, - undefined, - from.module - ); - if (reexportInfo) { - return { - exports: Array.from(reexportInfo.exports, name => { - return { - name, - from, - export: ids.concat(name), - canMangle: !(name in EMPTY_OBJECT) && false - }; - }), - // TODO handle deep reexports - dependencies: [from.module] - }; - } else { - return { - exports: true, - from: ids.length === 0 ? from : undefined, - canMangle: false, - dependencies: [from.module] - }; - } + getErrors(moduleGraph) { + const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); + if (exportsPresence === ExportPresenceModes.ERROR) { + return this._getErrors(moduleGraph); } + return null; } /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {RuntimeSpec} runtime the runtime - * @param {Module} importedModule the imported module (optional) - * @returns {{exports?: Set, checked?: Set}} information + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[] | undefined} errors */ - getStarReexports( - moduleGraph, - runtime, - importedModule = moduleGraph.getModule(this) - ) { - let importedExportsInfo = moduleGraph.getExportsInfo(importedModule); + _getErrors(moduleGraph) { const ids = this.getIds(moduleGraph); - if (ids.length > 0) - importedExportsInfo = importedExportsInfo.getNestedExportsInfo(ids); - let exportsInfo = moduleGraph.getExportsInfo( - moduleGraph.getParentModule(this) + return this.getLinkingErrors( + moduleGraph, + ids, + `(imported as '${this.name}')` ); - if (this.names.length > 0) - exportsInfo = exportsInfo.getNestedExportsInfo(this.names); - - const noExtraExports = - importedExportsInfo && - importedExportsInfo.otherExportsInfo.provided === false; - const noExtraImports = - exportsInfo && - exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused; - - if (!noExtraExports && !noExtraImports) { - return; - } - - const isNamespaceImport = - importedModule.getExportsType(moduleGraph, false) === "namespace"; - - /** @type {Set} */ - const exports = new Set(); - /** @type {Set} */ - const checked = new Set(); - - if (noExtraImports) { - for (const exportInfo of exportsInfo.orderedExports) { - const name = exportInfo.name; - if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; - if (name === "__esModule" && isNamespaceImport) { - exports.add(name); - } else if (importedExportsInfo) { - const importedExportInfo = - importedExportsInfo.getReadOnlyExportInfo(name); - if (importedExportInfo.provided === false) continue; - exports.add(name); - if (importedExportInfo.provided === true) continue; - checked.add(name); - } else { - exports.add(name); - checked.add(name); - } - } - } else if (noExtraExports) { - for (const importedExportInfo of importedExportsInfo.orderedExports) { - const name = importedExportInfo.name; - if (importedExportInfo.provided === false) continue; - if (exportsInfo) { - const exportInfo = exportsInfo.getReadOnlyExportInfo(name); - if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; - } - exports.add(name); - if (importedExportInfo.provided === true) continue; - checked.add(name); - } - if (isNamespaceImport) { - exports.add("__esModule"); - checked.delete("__esModule"); - } - } + } - return { exports, checked }; + /** + * 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 0; } serialize(context) { const { write } = context; - write(this.asiSafe); - write(this.range); - write(this.valueRange); - write(this.base); - write(this.names); write(this.ids); - write(this.resultUsed); + write(this.name); + write(this.range); + write(this.exportPresenceMode); + write(this.namespaceObjectAsContext); + write(this.call); + write(this.directImport); + write(this.shorthand); + write(this.asiSafe); + write(this.usedByExports); super.serialize(context); } deserialize(context) { const { read } = context; - this.asiSafe = read(); - this.range = read(); - this.valueRange = read(); - this.base = read(); - this.names = read(); this.ids = read(); - this.resultUsed = read(); + this.name = read(); + this.range = read(); + this.exportPresenceMode = read(); + this.namespaceObjectAsContext = read(); + this.call = read(); + this.directImport = read(); + this.shorthand = read(); + this.asiSafe = read(); + this.usedByExports = read(); super.deserialize(context); } } makeSerializable( - CommonJsExportRequireDependency, - "webpack/lib/dependencies/CommonJsExportRequireDependency" + HarmonyImportSpecifierDependency, + "webpack/lib/dependencies/HarmonyImportSpecifierDependency" ); -CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependencyTemplate extends ( - ModuleDependency.Template +HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate extends ( + HarmonyImportDependency.Template ) { /** * @param {Dependency} dependency the dependency for which the template should be applied @@ -79978,74 +79341,81 @@ CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependency * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ - apply( - dependency, - source, - { - module, - runtimeTemplate, - chunkGraph, - moduleGraph, - runtimeRequirements, - runtime - } - ) { - const dep = /** @type {CommonJsExportRequireDependency} */ (dependency); - const used = moduleGraph - .getExportsInfo(module) - .getUsedName(dep.names, runtime); + apply(dependency, source, templateContext) { + const dep = /** @type {HarmonyImportSpecifierDependency} */ (dependency); + const { moduleGraph, module, runtime, concatenationScope } = + templateContext; + const connection = moduleGraph.getConnection(dep); + // Skip rendering depending when dependency is conditional + if (connection && !connection.isTargetActive(runtime)) return; - const [type, base] = handleDependencyBase( - dep.base, - module, - runtimeRequirements - ); + const ids = dep.getIds(moduleGraph); - const importedModule = moduleGraph.getModule(dep); - let requireExpr = runtimeTemplate.moduleExports({ - module: importedModule, - chunkGraph, - request: dep.request, - weak: dep.weak, - runtimeRequirements - }); - if (importedModule) { - const ids = dep.getIds(moduleGraph); - const usedImported = moduleGraph - .getExportsInfo(importedModule) - .getUsedName(ids, runtime); - if (usedImported) { - const comment = equals(usedImported, ids) - ? "" - : Template.toNormalComment(propertyAccess(ids)) + " "; - requireExpr += `${comment}${propertyAccess(usedImported)}`; + let exportExpr; + if ( + connection && + concatenationScope && + concatenationScope.isModuleInScope(connection.module) + ) { + if (ids.length === 0) { + exportExpr = concatenationScope.createModuleReference( + connection.module, + { + asiSafe: dep.asiSafe + } + ); + } else if (dep.namespaceObjectAsContext && ids.length === 1) { + exportExpr = + concatenationScope.createModuleReference(connection.module, { + asiSafe: dep.asiSafe + }) + propertyAccess(ids); + } else { + exportExpr = concatenationScope.createModuleReference( + connection.module, + { + ids, + call: dep.call, + directImport: dep.directImport, + asiSafe: dep.asiSafe + } + ); } - } + } else { + super.apply(dependency, source, templateContext); - switch (type) { - case "expression": - source.replace( - dep.range[0], - dep.range[1] - 1, - used - ? `${base}${propertyAccess(used)} = ${requireExpr}` - : `/* unused reexport */ ${requireExpr}` - ); - return; - case "Object.defineProperty": - throw new Error("TODO"); - default: - throw new Error("Unexpected type"); + const { runtimeTemplate, initFragments, runtimeRequirements } = + templateContext; + + exportExpr = runtimeTemplate.exportFromImport({ + moduleGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + exportName: ids, + originModule: module, + asiSafe: dep.shorthand ? true : dep.asiSafe, + isCall: dep.call, + callContext: !dep.directImport, + defaultInterop: true, + importVar: dep.getImportVar(moduleGraph), + initFragments, + runtime, + runtimeRequirements + }); + } + if (dep.shorthand) { + source.insert(dep.range[1], `: ${exportExpr}`); + } else { + source.replace(dep.range[0], dep.range[1] - 1, exportExpr); } } }; -module.exports = CommonJsExportRequireDependency; +module.exports = HarmonyImportSpecifierDependency; /***/ }), -/***/ 45598: +/***/ 39029: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -80056,164 +79426,160 @@ module.exports = CommonJsExportRequireDependency; -const InitFragment = __webpack_require__(55870); -const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const { handleDependencyBase } = __webpack_require__(59643); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ +const HarmonyAcceptDependency = __webpack_require__(23624); +const HarmonyAcceptImportDependency = __webpack_require__(99843); +const HarmonyCompatibilityDependency = __webpack_require__(72906); +const HarmonyExportExpressionDependency = __webpack_require__(51340); +const HarmonyExportHeaderDependency = __webpack_require__(38873); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(67157); +const HarmonyExportSpecifierDependency = __webpack_require__(48567); +const HarmonyImportSideEffectDependency = __webpack_require__(73132); +const HarmonyImportSpecifierDependency = __webpack_require__(14077); -const EMPTY_OBJECT = {}; +const HarmonyDetectionParserPlugin = __webpack_require__(17223); +const HarmonyExportDependencyParserPlugin = __webpack_require__(93466); +const HarmonyImportDependencyParserPlugin = __webpack_require__(20862); +const HarmonyTopLevelThisParserPlugin = __webpack_require__(63232); -class CommonJsExportsDependency extends NullDependency { - constructor(range, valueRange, base, names) { - super(); - this.range = range; - this.valueRange = valueRange; - this.base = base; - this.names = names; - } +/** @typedef {import("../Compiler")} Compiler */ - get type() { - return "cjs exports"; +class HarmonyModulesPlugin { + constructor(options) { + this.options = options; } /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - getExports(moduleGraph) { - const name = this.names[0]; - return { - exports: [ - { - name, - // we can't mangle names that are in an empty object - // because one could access the prototype property - // when export isn't set yet - canMangle: !(name in EMPTY_OBJECT) - } - ], - dependencies: undefined - }; - } + apply(compiler) { + compiler.hooks.compilation.tap( + "HarmonyModulesPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyTemplates.set( + HarmonyCompatibilityDependency, + new HarmonyCompatibilityDependency.Template() + ); - serialize(context) { - const { write } = context; - write(this.range); - write(this.valueRange); - write(this.base); - write(this.names); - super.serialize(context); - } + compilation.dependencyFactories.set( + HarmonyImportSideEffectDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSideEffectDependency, + new HarmonyImportSideEffectDependency.Template() + ); - deserialize(context) { - const { read } = context; - this.range = read(); - this.valueRange = read(); - this.base = read(); - this.names = read(); - super.deserialize(context); + compilation.dependencyFactories.set( + HarmonyImportSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSpecifierDependency, + new HarmonyImportSpecifierDependency.Template() + ); + + compilation.dependencyTemplates.set( + HarmonyExportHeaderDependency, + new HarmonyExportHeaderDependency.Template() + ); + + compilation.dependencyTemplates.set( + HarmonyExportExpressionDependency, + new HarmonyExportExpressionDependency.Template() + ); + + compilation.dependencyTemplates.set( + HarmonyExportSpecifierDependency, + new HarmonyExportSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportImportedSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyExportImportedSpecifierDependency, + new HarmonyExportImportedSpecifierDependency.Template() + ); + + compilation.dependencyTemplates.set( + HarmonyAcceptDependency, + new HarmonyAcceptDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyAcceptImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyAcceptImportDependency, + new HarmonyAcceptImportDependency.Template() + ); + + const handler = (parser, parserOptions) => { + // TODO webpack 6: rename harmony to esm or module + if (parserOptions.harmony !== undefined && !parserOptions.harmony) + return; + + new HarmonyDetectionParserPlugin(this.options).apply(parser); + new HarmonyImportDependencyParserPlugin(parserOptions).apply(parser); + new HarmonyExportDependencyParserPlugin(parserOptions).apply(parser); + new HarmonyTopLevelThisParserPlugin().apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("HarmonyModulesPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("HarmonyModulesPlugin", handler); + } + ); } } +module.exports = HarmonyModulesPlugin; -makeSerializable( - CommonJsExportsDependency, - "webpack/lib/dependencies/CommonJsExportsDependency" -); -CommonJsExportsDependency.Template = class CommonJsExportsDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, - { module, moduleGraph, initFragments, runtimeRequirements, runtime } - ) { - const dep = /** @type {CommonJsExportsDependency} */ (dependency); - const used = moduleGraph - .getExportsInfo(module) - .getUsedName(dep.names, runtime); +/***/ }), - const [type, base] = handleDependencyBase( - dep.base, - module, - runtimeRequirements - ); +/***/ 63232: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - switch (type) { - case "expression": - if (!used) { - initFragments.push( - new InitFragment( - "var __webpack_unused_export__;\n", - InitFragment.STAGE_CONSTANTS, - 0, - "__webpack_unused_export__" - ) - ); - source.replace( - dep.range[0], - dep.range[1] - 1, - "__webpack_unused_export__" - ); - return; - } - source.replace( - dep.range[0], - dep.range[1] - 1, - `${base}${propertyAccess(used)}` - ); - return; - case "Object.defineProperty": - if (!used) { - initFragments.push( - new InitFragment( - "var __webpack_unused_export__;\n", - InitFragment.STAGE_CONSTANTS, - 0, - "__webpack_unused_export__" - ) - ); - source.replace( - dep.range[0], - dep.valueRange[0] - 1, - "__webpack_unused_export__ = (" - ); - source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); - return; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + + + +const ConstDependency = __webpack_require__(76911); +const HarmonyExports = __webpack_require__(39211); + +class HarmonyTopLevelThisParserPlugin { + apply(parser) { + parser.hooks.expression + .for("this") + .tap("HarmonyTopLevelThisParserPlugin", node => { + if (!parser.scope.topLevelScope) return; + if (HarmonyExports.isEnabled(parser.state)) { + const dep = new ConstDependency("undefined", node.range, null); + dep.loc = node.loc; + parser.state.module.addPresentationalDependency(dep); + return this; } - source.replace( - dep.range[0], - dep.valueRange[0] - 1, - `Object.defineProperty(${base}${propertyAccess( - used.slice(0, -1) - )}, ${JSON.stringify(used[used.length - 1])}, (` - ); - source.replace(dep.valueRange[1], dep.range[1] - 1, "))"); - return; - } + }); } -}; +} -module.exports = CommonJsExportsDependency; +module.exports = HarmonyTopLevelThisParserPlugin; /***/ }), -/***/ 97107: +/***/ 1902: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -80224,340 +79590,58 @@ module.exports = CommonJsExportsDependency; -const RuntimeGlobals = __webpack_require__(16475); -const formatLocation = __webpack_require__(16734); -const { evaluateToString } = __webpack_require__(93998); -const propertyAccess = __webpack_require__(54190); -const CommonJsExportRequireDependency = __webpack_require__(62892); -const CommonJsExportsDependency = __webpack_require__(45598); -const CommonJsSelfReferenceDependency = __webpack_require__(52225); -const DynamicExports = __webpack_require__(32006); -const HarmonyExports = __webpack_require__(39211); -const ModuleDecoratorDependency = __webpack_require__(88488); +const makeSerializable = __webpack_require__(33032); +const ContextDependency = __webpack_require__(88101); +const ContextDependencyTemplateAsRequireCall = __webpack_require__(75815); -/** @typedef {import("estree").Expression} ExpressionNode */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +class ImportContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); -const getValueOfPropertyDescription = expr => { - if (expr.type !== "ObjectExpression") return; - for (const property of expr.properties) { - if (property.computed) continue; - const key = property.key; - if (key.type !== "Identifier" || key.name !== "value") continue; - return property.value; + this.range = range; + this.valueRange = valueRange; } -}; -const isTruthyLiteral = expr => { - switch (expr.type) { - case "Literal": - return !!expr.value; - case "UnaryExpression": - if (expr.operator === "!") return isFalsyLiteral(expr.argument); + get type() { + return `import() context ${this.options.mode}`; } - return false; -}; -const isFalsyLiteral = expr => { - switch (expr.type) { - case "Literal": - return !expr.value; - case "UnaryExpression": - if (expr.operator === "!") return isTruthyLiteral(expr.argument); + get category() { + return "esm"; } - return false; -}; -/** - * @param {JavascriptParser} parser the parser - * @param {ExpressionNode} expr expression - * @returns {{ argument: BasicEvaluatedExpression, ids: string[] } | undefined} parsed call - */ -const parseRequireCall = (parser, expr) => { - const ids = []; - while (expr.type === "MemberExpression") { - if (expr.object.type === "Super") return; - if (!expr.property) return; - const prop = expr.property; - if (expr.computed) { - if (prop.type !== "Literal") return; - ids.push(`${prop.value}`); - } else { - if (prop.type !== "Identifier") return; - ids.push(prop.name); - } - expr = expr.object; - } - if (expr.type !== "CallExpression" || expr.arguments.length !== 1) return; - const callee = expr.callee; - if ( - callee.type !== "Identifier" || - parser.getVariableInfo(callee.name) !== "require" - ) { - return; - } - const arg = expr.arguments[0]; - if (arg.type === "SpreadElement") return; - const argValue = parser.evaluateExpression(arg); - return { argument: argValue, ids: ids.reverse() }; -}; + serialize(context) { + const { write } = context; -class CommonJsExportsParserPlugin { - constructor(moduleGraph) { - this.moduleGraph = moduleGraph; + write(this.range); + write(this.valueRange); + + super.serialize(context); } - /** - * @param {JavascriptParser} parser the parser - */ - apply(parser) { - const enableStructuredExports = () => { - DynamicExports.enable(parser.state); - }; - const checkNamespace = (topLevel, members, valueExpr) => { - if (!DynamicExports.isEnabled(parser.state)) return; - if (members.length > 0 && members[0] === "__esModule") { - if (valueExpr && isTruthyLiteral(valueExpr) && topLevel) { - DynamicExports.setFlagged(parser.state); - } else { - DynamicExports.setDynamic(parser.state); - } - } - }; - const bailout = reason => { - DynamicExports.bailout(parser.state); - if (reason) bailoutHint(reason); - }; - const bailoutHint = reason => { - this.moduleGraph - .getOptimizationBailout(parser.state.module) - .push(`CommonJS bailout: ${reason}`); - }; + deserialize(context) { + const { read } = context; - // metadata // - parser.hooks.evaluateTypeof - .for("module") - .tap("CommonJsExportsParserPlugin", evaluateToString("object")); - parser.hooks.evaluateTypeof - .for("exports") - .tap("CommonJsPlugin", evaluateToString("object")); + this.range = read(); + this.valueRange = read(); - // exporting // - const handleAssignExport = (expr, base, members) => { - if (HarmonyExports.isEnabled(parser.state)) return; - // Handle reexporting - const requireCall = parseRequireCall(parser, expr.right); - if ( - requireCall && - requireCall.argument.isString() && - (members.length === 0 || members[0] !== "__esModule") - ) { - enableStructuredExports(); - // It's possible to reexport __esModule, so we must convert to a dynamic module - if (members.length === 0) DynamicExports.setDynamic(parser.state); - const dep = new CommonJsExportRequireDependency( - expr.range, - null, - base, - members, - requireCall.argument.string, - requireCall.ids, - !parser.isStatementLevelExpression(expr) - ); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.module.addDependency(dep); - return true; - } - if (members.length === 0) return; - enableStructuredExports(); - const remainingMembers = members; - checkNamespace( - parser.statementPath.length === 1 && - parser.isStatementLevelExpression(expr), - remainingMembers, - expr.right - ); - const dep = new CommonJsExportsDependency( - expr.left.range, - null, - base, - remainingMembers - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - parser.walkExpression(expr.right); - return true; - }; - parser.hooks.assignMemberChain - .for("exports") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - return handleAssignExport(expr, "exports", members); - }); - parser.hooks.assignMemberChain - .for("this") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - if (!parser.scope.topLevelScope) return; - return handleAssignExport(expr, "this", members); - }); - parser.hooks.assignMemberChain - .for("module") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - if (members[0] !== "exports") return; - return handleAssignExport(expr, "module.exports", members.slice(1)); - }); - parser.hooks.call - .for("Object.defineProperty") - .tap("CommonJsExportsParserPlugin", expression => { - const expr = /** @type {import("estree").CallExpression} */ ( - expression - ); - if (!parser.isStatementLevelExpression(expr)) return; - if (expr.arguments.length !== 3) return; - if (expr.arguments[0].type === "SpreadElement") return; - if (expr.arguments[1].type === "SpreadElement") return; - if (expr.arguments[2].type === "SpreadElement") return; - const exportsArg = parser.evaluateExpression(expr.arguments[0]); - if (!exportsArg || !exportsArg.isIdentifier()) return; - if ( - exportsArg.identifier !== "exports" && - exportsArg.identifier !== "module.exports" && - (exportsArg.identifier !== "this" || !parser.scope.topLevelScope) - ) { - return; - } - const propertyArg = parser.evaluateExpression(expr.arguments[1]); - if (!propertyArg) return; - const property = propertyArg.asString(); - if (typeof property !== "string") return; - enableStructuredExports(); - const descArg = expr.arguments[2]; - checkNamespace( - parser.statementPath.length === 1, - [property], - getValueOfPropertyDescription(descArg) - ); - const dep = new CommonJsExportsDependency( - expr.range, - expr.arguments[2].range, - `Object.defineProperty(${exportsArg.identifier})`, - [property] - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); + super.deserialize(context); + } +} - parser.walkExpression(expr.arguments[2]); - return true; - }); +makeSerializable( + ImportContextDependency, + "webpack/lib/dependencies/ImportContextDependency" +); - // Self reference // - const handleAccessExport = (expr, base, members, call = undefined) => { - if (HarmonyExports.isEnabled(parser.state)) return; - if (members.length === 0) { - bailout(`${base} is used directly at ${formatLocation(expr.loc)}`); - } - if (call && members.length === 1) { - bailoutHint( - `${base}${propertyAccess( - members - )}(...) prevents optimization as ${base} is passed as call context at ${formatLocation( - expr.loc - )}` - ); - } - const dep = new CommonJsSelfReferenceDependency( - expr.range, - base, - members, - !!call - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - if (call) { - parser.walkExpressions(call.arguments); - } - return true; - }; - parser.hooks.callMemberChain - .for("exports") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - return handleAccessExport(expr.callee, "exports", members, expr); - }); - parser.hooks.expressionMemberChain - .for("exports") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - return handleAccessExport(expr, "exports", members); - }); - parser.hooks.expression - .for("exports") - .tap("CommonJsExportsParserPlugin", expr => { - return handleAccessExport(expr, "exports", []); - }); - parser.hooks.callMemberChain - .for("module") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - if (members[0] !== "exports") return; - return handleAccessExport( - expr.callee, - "module.exports", - members.slice(1), - expr - ); - }); - parser.hooks.expressionMemberChain - .for("module") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - if (members[0] !== "exports") return; - return handleAccessExport(expr, "module.exports", members.slice(1)); - }); - parser.hooks.expression - .for("module.exports") - .tap("CommonJsExportsParserPlugin", expr => { - return handleAccessExport(expr, "module.exports", []); - }); - parser.hooks.callMemberChain - .for("this") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - if (!parser.scope.topLevelScope) return; - return handleAccessExport(expr.callee, "this", members, expr); - }); - parser.hooks.expressionMemberChain - .for("this") - .tap("CommonJsExportsParserPlugin", (expr, members) => { - if (!parser.scope.topLevelScope) return; - return handleAccessExport(expr, "this", members); - }); - parser.hooks.expression - .for("this") - .tap("CommonJsExportsParserPlugin", expr => { - if (!parser.scope.topLevelScope) return; - return handleAccessExport(expr, "this", []); - }); +ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; - // Bailouts // - parser.hooks.expression.for("module").tap("CommonJsPlugin", expr => { - bailout(); - const isHarmony = HarmonyExports.isEnabled(parser.state); - const dep = new ModuleDecoratorDependency( - isHarmony - ? RuntimeGlobals.harmonyModuleDecorator - : RuntimeGlobals.nodeModuleDecorator, - !isHarmony - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return true; - }); - } -} -module.exports = CommonJsExportsParserPlugin; +module.exports = ImportContextDependency; /***/ }), -/***/ 59440: +/***/ 89376: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -80568,31 +79652,35 @@ module.exports = CommonJsExportsParserPlugin; -const Template = __webpack_require__(39722); -const { equals } = __webpack_require__(84953); +const Dependency = __webpack_require__(54912); const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); const ModuleDependency = __webpack_require__(80321); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -class CommonJsFullRequireDependency extends ModuleDependency { +class ImportDependency extends ModuleDependency { /** - * @param {string} request the request string - * @param {[number, number]} range location in source code - * @param {string[]} names accessed properties on module + * @param {string} request the request + * @param {[number, number]} range expression range + * @param {string[][]=} referencedExports list of referenced exports */ - constructor(request, range, names) { + constructor(request, range, referencedExports) { super(request); this.range = range; - this.names = names; - this.call = false; - this.asiSafe = undefined; + this.referencedExports = referencedExports; + } + + get type() { + return "import()"; + } + + get category() { + return "esm"; } /** @@ -80602,45 +79690,112 @@ class CommonJsFullRequireDependency extends ModuleDependency { * @returns {(string[] | ReferencedExport)[]} referenced exports */ getReferencedExports(moduleGraph, runtime) { - if (this.call) { - const importedModule = moduleGraph.getModule(this); - if ( - !importedModule || - importedModule.getExportsType(moduleGraph, false) !== "namespace" - ) { - return [this.names.slice(0, -1)]; - } - } - return [this.names]; + return this.referencedExports + ? this.referencedExports.map(e => ({ + name: e, + canMangle: false + })) + : Dependency.EXPORTS_OBJECT_REFERENCED; } serialize(context) { - const { write } = context; - write(this.names); - write(this.call); - write(this.asiSafe); + context.write(this.range); + context.write(this.referencedExports); super.serialize(context); } deserialize(context) { - const { read } = context; - this.names = read(); - this.call = read(); - this.asiSafe = read(); + this.range = context.read(); + this.referencedExports = context.read(); super.deserialize(context); } +} + +makeSerializable(ImportDependency, "webpack/lib/dependencies/ImportDependency"); + +ImportDependency.Template = class ImportDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @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, + { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ImportDependency} */ (dependency); + const block = /** @type {AsyncDependenciesBlock} */ ( + moduleGraph.getParentBlock(dep) + ); + const content = runtimeTemplate.moduleNamespacePromise({ + chunkGraph, + block: block, + module: moduleGraph.getModule(dep), + request: dep.request, + strict: module.buildMeta.strictHarmonyModule, + message: "import()", + runtimeRequirements + }); + + source.replace(dep.range[0], dep.range[1] - 1, content); + } +}; + +module.exports = ImportDependency; + + +/***/ }), + +/***/ 50718: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); +const ImportDependency = __webpack_require__(89376); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ + +class ImportEagerDependency extends ImportDependency { + /** + * @param {string} request the request + * @param {[number, number]} range expression range + * @param {string[][]=} referencedExports list of referenced exports + */ + constructor(request, range, referencedExports) { + super(request, range, referencedExports); + } get type() { - return "cjs full require"; + return "import() eager"; } get category() { - return "commonjs"; + return "esm"; } } -CommonJsFullRequireDependency.Template = class CommonJsFullRequireDependencyTemplate extends ( - ModuleDependency.Template +makeSerializable( + ImportEagerDependency, + "webpack/lib/dependencies/ImportEagerDependency" +); + +ImportEagerDependency.Template = class ImportEagerDependencyTemplate extends ( + ImportDependency.Template ) { /** * @param {Dependency} dependency the dependency for which the template should be applied @@ -80651,453 +79806,582 @@ CommonJsFullRequireDependency.Template = class CommonJsFullRequireDependencyTemp apply( dependency, source, - { - module, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtimeRequirements, - runtime, - initFragments - } + { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } ) { - const dep = /** @type {CommonJsFullRequireDependency} */ (dependency); - if (!dep.range) return; - const importedModule = moduleGraph.getModule(dep); - let requireExpr = runtimeTemplate.moduleExports({ - module: importedModule, + const dep = /** @type {ImportEagerDependency} */ (dependency); + const content = runtimeTemplate.moduleNamespacePromise({ chunkGraph, + module: moduleGraph.getModule(dep), request: dep.request, - weak: dep.weak, + strict: module.buildMeta.strictHarmonyModule, + message: "import() eager", runtimeRequirements }); - if (importedModule) { - const ids = dep.names; - const usedImported = moduleGraph - .getExportsInfo(importedModule) - .getUsedName(ids, runtime); - if (usedImported) { - const comment = equals(usedImported, ids) - ? "" - : Template.toNormalComment(propertyAccess(ids)) + " "; - const access = `${comment}${propertyAccess(usedImported)}`; - requireExpr = - dep.asiSafe === true - ? `(${requireExpr}${access})` - : `${requireExpr}${access}`; - } - } - source.replace(dep.range[0], dep.range[1] - 1, requireExpr); + + source.replace(dep.range[0], dep.range[1] - 1, content); } }; +module.exports = ImportEagerDependency; + + +/***/ }), + +/***/ 51274: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyTemplateAsId = __webpack_require__(80825); + +class ImportMetaHotAcceptDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; + } + + get type() { + return "import.meta.webpackHot.accept"; + } + + get category() { + return "esm"; + } +} + makeSerializable( - CommonJsFullRequireDependency, - "webpack/lib/dependencies/CommonJsFullRequireDependency" + ImportMetaHotAcceptDependency, + "webpack/lib/dependencies/ImportMetaHotAcceptDependency" ); -module.exports = CommonJsFullRequireDependency; +ImportMetaHotAcceptDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = ImportMetaHotAcceptDependency; /***/ }), -/***/ 36013: +/***/ 53141: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const CommentCompilationWarning = __webpack_require__(98427); -const RuntimeGlobals = __webpack_require__(16475); -const UnsupportedFeatureWarning = __webpack_require__(42495); -const { - evaluateToIdentifier, - evaluateToString, - expressionIsUnsupported, - toConstantDependency -} = __webpack_require__(93998); -const CommonJsFullRequireDependency = __webpack_require__(59440); -const CommonJsRequireContextDependency = __webpack_require__(23962); -const CommonJsRequireDependency = __webpack_require__(21264); -const ConstDependency = __webpack_require__(76911); -const ContextDependencyHelpers = __webpack_require__(99630); -const LocalModuleDependency = __webpack_require__(52805); -const { getLocalModule } = __webpack_require__(75827); -const RequireHeaderDependency = __webpack_require__(89183); -const RequireResolveContextDependency = __webpack_require__(55627); -const RequireResolveDependency = __webpack_require__(68582); -const RequireResolveHeaderDependency = __webpack_require__(9880); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyTemplateAsId = __webpack_require__(80825); -/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ +class ImportMetaHotDeclineDependency extends ModuleDependency { + constructor(request, range) { + super(request); -class CommonJsImportsParserPlugin { - /** - * @param {JavascriptParserOptions} options parser options - */ - constructor(options) { - this.options = options; + this.range = range; + this.weak = true; } - apply(parser) { - const options = this.options; + get type() { + return "import.meta.webpackHot.decline"; + } - // metadata // - const tapRequireExpression = (expression, getMembers) => { - parser.hooks.typeof - .for(expression) - .tap( - "CommonJsPlugin", - toConstantDependency(parser, JSON.stringify("function")) - ); - parser.hooks.evaluateTypeof - .for(expression) - .tap("CommonJsPlugin", evaluateToString("function")); - parser.hooks.evaluateIdentifier - .for(expression) - .tap( - "CommonJsPlugin", - evaluateToIdentifier(expression, "require", getMembers, true) - ); - }; - tapRequireExpression("require", () => []); - tapRequireExpression("require.resolve", () => ["resolve"]); - tapRequireExpression("require.resolveWeak", () => ["resolveWeak"]); + get category() { + return "esm"; + } +} - // Weird stuff // - parser.hooks.assign.for("require").tap("CommonJsPlugin", expr => { - // to not leak to global "require", we need to define a local require here. - const dep = new ConstDependency("var require;", 0); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); +makeSerializable( + ImportMetaHotDeclineDependency, + "webpack/lib/dependencies/ImportMetaHotDeclineDependency" +); - // Unsupported // - parser.hooks.expression - .for("require.main.require") - .tap( - "CommonJsPlugin", - expressionIsUnsupported( - parser, - "require.main.require is not supported by webpack." - ) - ); - parser.hooks.call - .for("require.main.require") - .tap( - "CommonJsPlugin", - expressionIsUnsupported( - parser, - "require.main.require is not supported by webpack." - ) - ); - parser.hooks.expression - .for("module.parent.require") - .tap( - "CommonJsPlugin", - expressionIsUnsupported( - parser, - "module.parent.require is not supported by webpack." - ) - ); - parser.hooks.call - .for("module.parent.require") - .tap( - "CommonJsPlugin", - expressionIsUnsupported( - parser, - "module.parent.require is not supported by webpack." - ) - ); +ImportMetaHotDeclineDependency.Template = ModuleDependencyTemplateAsId; - // renaming // - parser.hooks.canRename.for("require").tap("CommonJsPlugin", () => true); - parser.hooks.rename.for("require").tap("CommonJsPlugin", expr => { - // To avoid "not defined" error, replace the value with undefined - const dep = new ConstDependency("undefined", expr.range); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return false; - }); +module.exports = ImportMetaHotDeclineDependency; - // inspection // - parser.hooks.expression - .for("require.cache") - .tap( - "CommonJsImportsParserPlugin", - toConstantDependency(parser, RuntimeGlobals.moduleCache, [ - RuntimeGlobals.moduleCache, - RuntimeGlobals.moduleId, - RuntimeGlobals.moduleLoaded - ]) - ); - // require as expression // - parser.hooks.expression - .for("require") - .tap("CommonJsImportsParserPlugin", expr => { - const dep = new CommonJsRequireContextDependency( - { - request: options.unknownContextRequest, - recursive: options.unknownContextRecursive, - regExp: options.unknownContextRegExp, - mode: "sync" - }, - expr.range, - undefined, - parser.scope.inShorthand - ); - dep.critical = - options.unknownContextCritical && - "require function is used in a way in which dependencies cannot be statically extracted"; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - }); +/***/ }), - // require // - const processRequireItem = (expr, param) => { - if (param.isString()) { - const dep = new CommonJsRequireDependency(param.string, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - }; - const processRequireContext = (expr, param) => { - const dep = ContextDependencyHelpers.create( - CommonJsRequireContextDependency, - expr.range, - param, - expr, - options, - { - category: "commonjs" - }, - parser - ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - }; - const createRequireHandler = callNew => expr => { - if (options.commonjsMagicComments) { - const { options: requireOptions, errors: commentErrors } = - parser.parseCommentOptions(expr.range); +/***/ 17228: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (commentErrors) { - for (const e of commentErrors) { - const { comment } = e; - parser.state.module.addWarning( - new CommentCompilationWarning( - `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, - comment.loc - ) - ); - } - } - if (requireOptions) { - if (requireOptions.webpackIgnore !== undefined) { - if (typeof requireOptions.webpackIgnore !== "boolean") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackIgnore\` expected a boolean, but received: ${requireOptions.webpackIgnore}.`, - expr.loc - ) - ); - } else { - // Do not instrument `require()` if `webpackIgnore` is `true` - if (requireOptions.webpackIgnore) { - return true; - } - } - } - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - if (expr.arguments.length !== 1) return; - let localModule; - const param = parser.evaluateExpression(expr.arguments[0]); - if (param.isConditional()) { - let isExpression = false; - for (const p of param.options) { - const result = processRequireItem(expr, p); - if (result === undefined) { - isExpression = true; - } - } - if (!isExpression) { - const dep = new RequireHeaderDependency(expr.callee.range); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - } + + +const { pathToFileURL } = __webpack_require__(57310); +const ModuleDependencyWarning = __webpack_require__(29656); +const Template = __webpack_require__(1626); +const BasicEvaluatedExpression = __webpack_require__(950); +const { + evaluateToIdentifier, + toConstantDependency, + evaluateToString, + evaluateToNumber +} = __webpack_require__(93998); +const memoize = __webpack_require__(78676); +const propertyAccess = __webpack_require__(54190); +const ConstDependency = __webpack_require__(76911); + +/** @typedef {import("estree").MemberExpression} MemberExpression */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../javascript/JavascriptParser")} Parser */ + +const getCriticalDependencyWarning = memoize(() => + __webpack_require__(15427) +); + +class ImportMetaPlugin { + /** + * @param {Compiler} compiler compiler + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "ImportMetaPlugin", + (compilation, { normalModuleFactory }) => { + /** + * @param {NormalModule} module module + * @returns {string} file url + */ + const getUrl = module => { + return pathToFileURL(module.resource).toString(); + }; + /** + * @param {Parser} parser parser + * @param {Object} parserOptions parserOptions + * @returns {void} + */ + const parserHandler = (parser, parserOptions) => { + /// import.meta direct /// + parser.hooks.typeof + .for("import.meta") + .tap( + "ImportMetaPlugin", + toConstantDependency(parser, JSON.stringify("object")) + ); + parser.hooks.expression + .for("import.meta") + .tap("ImportMetaPlugin", metaProperty => { + const CriticalDependencyWarning = getCriticalDependencyWarning(); + parser.state.module.addWarning( + new ModuleDependencyWarning( + parser.state.module, + new CriticalDependencyWarning( + "Accessing import.meta directly is unsupported (only property access is supported)" + ), + metaProperty.loc + ) + ); + const dep = new ConstDependency( + `${parser.isAsiPosition(metaProperty.range[0]) ? ";" : ""}({})`, + metaProperty.range + ); + dep.loc = metaProperty.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.evaluateTypeof + .for("import.meta") + .tap("ImportMetaPlugin", evaluateToString("object")); + parser.hooks.evaluateIdentifier.for("import.meta").tap( + "ImportMetaPlugin", + evaluateToIdentifier("import.meta", "import.meta", () => [], true) + ); + + /// import.meta.url /// + parser.hooks.typeof + .for("import.meta.url") + .tap( + "ImportMetaPlugin", + toConstantDependency(parser, JSON.stringify("string")) + ); + parser.hooks.expression + .for("import.meta.url") + .tap("ImportMetaPlugin", expr => { + const dep = new ConstDependency( + JSON.stringify(getUrl(parser.state.module)), + expr.range + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.evaluateTypeof + .for("import.meta.url") + .tap("ImportMetaPlugin", evaluateToString("string")); + parser.hooks.evaluateIdentifier + .for("import.meta.url") + .tap("ImportMetaPlugin", expr => { + return new BasicEvaluatedExpression() + .setString(getUrl(parser.state.module)) + .setRange(expr.range); + }); + + /// import.meta.webpack /// + const webpackVersion = parseInt( + (__webpack_require__(32702)/* .version */ .i8), + 10 + ); + parser.hooks.typeof + .for("import.meta.webpack") + .tap( + "ImportMetaPlugin", + toConstantDependency(parser, JSON.stringify("number")) + ); + parser.hooks.expression + .for("import.meta.webpack") + .tap( + "ImportMetaPlugin", + toConstantDependency(parser, JSON.stringify(webpackVersion)) + ); + parser.hooks.evaluateTypeof + .for("import.meta.webpack") + .tap("ImportMetaPlugin", evaluateToString("number")); + parser.hooks.evaluateIdentifier + .for("import.meta.webpack") + .tap("ImportMetaPlugin", evaluateToNumber(webpackVersion)); + + /// Unknown properties /// + parser.hooks.unhandledExpressionMemberChain + .for("import.meta") + .tap("ImportMetaPlugin", (expr, members) => { + const dep = new ConstDependency( + `${Template.toNormalComment( + "unsupported import.meta." + members.join(".") + )} undefined${propertyAccess(members, 1)}`, + expr.range + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + parser.hooks.evaluate + .for("MemberExpression") + .tap("ImportMetaPlugin", expression => { + const expr = /** @type {MemberExpression} */ (expression); + if ( + expr.object.type === "MetaProperty" && + expr.object.meta.name === "import" && + expr.object.property.name === "meta" && + expr.property.type === + (expr.computed ? "Literal" : "Identifier") + ) { + return new BasicEvaluatedExpression() + .setUndefined() + .setRange(expr.range); + } + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ImportMetaPlugin", parserHandler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ImportMetaPlugin", parserHandler); } - if ( - param.isString() && - (localModule = getLocalModule(parser.state, param.string)) - ) { - localModule.flagUsed(); - const dep = new LocalModuleDependency(localModule, expr.range, callNew); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - } else { - const result = processRequireItem(expr, param); - if (result === undefined) { - processRequireContext(expr, param); - } else { - const dep = new RequireHeaderDependency(expr.callee.range); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); + ); + } +} + +module.exports = ImportMetaPlugin; + + +/***/ }), + +/***/ 88130: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const AsyncDependenciesBlock = __webpack_require__(47736); +const CommentCompilationWarning = __webpack_require__(98427); +const UnsupportedFeatureWarning = __webpack_require__(42495); +const ContextDependencyHelpers = __webpack_require__(99630); +const ImportContextDependency = __webpack_require__(1902); +const ImportDependency = __webpack_require__(89376); +const ImportEagerDependency = __webpack_require__(50718); +const ImportWeakDependency = __webpack_require__(82483); + +/** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ +/** @typedef {import("../ContextModule").ContextMode} ContextMode */ + +class ImportParserPlugin { + constructor(options) { + this.options = options; + } + + apply(parser) { + parser.hooks.importCall.tap("ImportParserPlugin", expr => { + const param = parser.evaluateExpression(expr.source); + + let chunkName = null; + /** @type {ContextMode} */ + let mode = "lazy"; + let include = null; + let exclude = null; + /** @type {string[][] | null} */ + let exports = null; + /** @type {RawChunkGroupOptions} */ + const groupOptions = {}; + + const { options: importOptions, errors: commentErrors } = + parser.parseCommentOptions(expr.range); + + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + comment.loc + ) + ); } - return true; } - }; - parser.hooks.call - .for("require") - .tap("CommonJsImportsParserPlugin", createRequireHandler(false)); - parser.hooks.new - .for("require") - .tap("CommonJsImportsParserPlugin", createRequireHandler(true)); - parser.hooks.call - .for("module.require") - .tap("CommonJsImportsParserPlugin", createRequireHandler(false)); - parser.hooks.new - .for("module.require") - .tap("CommonJsImportsParserPlugin", createRequireHandler(true)); - // require with property access // - const chainHandler = (expr, calleeMembers, callExpr, members) => { - if (callExpr.arguments.length !== 1) return; - const param = parser.evaluateExpression(callExpr.arguments[0]); - if (param.isString() && !getLocalModule(parser.state, param.string)) { - const dep = new CommonJsFullRequireDependency( - param.string, - expr.range, - members - ); - dep.asiSafe = !parser.isAsiPosition(expr.range[0]); - dep.optional = !!parser.scope.inTry; - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return true; - } - }; - const callChainHandler = (expr, calleeMembers, callExpr, members) => { - if (callExpr.arguments.length !== 1) return; - const param = parser.evaluateExpression(callExpr.arguments[0]); - if (param.isString() && !getLocalModule(parser.state, param.string)) { - const dep = new CommonJsFullRequireDependency( - param.string, - expr.callee.range, - members - ); - dep.call = true; - dep.asiSafe = !parser.isAsiPosition(expr.range[0]); - dep.optional = !!parser.scope.inTry; - dep.loc = expr.callee.loc; - parser.state.current.addDependency(dep); - parser.walkExpressions(expr.arguments); - return true; + if (importOptions) { + if (importOptions.webpackIgnore !== undefined) { + if (typeof importOptions.webpackIgnore !== "boolean") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, + expr.loc + ) + ); + } else { + // Do not instrument `import()` if `webpackIgnore` is `true` + if (importOptions.webpackIgnore) { + return false; + } + } + } + if (importOptions.webpackChunkName !== undefined) { + if (typeof importOptions.webpackChunkName !== "string") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, + expr.loc + ) + ); + } else { + chunkName = importOptions.webpackChunkName; + } + } + if (importOptions.webpackMode !== undefined) { + if (typeof importOptions.webpackMode !== "string") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackMode\` expected a string, but received: ${importOptions.webpackMode}.`, + expr.loc + ) + ); + } else { + mode = importOptions.webpackMode; + } + } + if (importOptions.webpackPrefetch !== undefined) { + if (importOptions.webpackPrefetch === true) { + groupOptions.prefetchOrder = 0; + } else if (typeof importOptions.webpackPrefetch === "number") { + groupOptions.prefetchOrder = importOptions.webpackPrefetch; + } else { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackPrefetch\` expected true or a number, but received: ${importOptions.webpackPrefetch}.`, + expr.loc + ) + ); + } + } + if (importOptions.webpackPreload !== undefined) { + if (importOptions.webpackPreload === true) { + groupOptions.preloadOrder = 0; + } else if (typeof importOptions.webpackPreload === "number") { + groupOptions.preloadOrder = importOptions.webpackPreload; + } else { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackPreload\` expected true or a number, but received: ${importOptions.webpackPreload}.`, + expr.loc + ) + ); + } + } + if (importOptions.webpackInclude !== undefined) { + if ( + !importOptions.webpackInclude || + importOptions.webpackInclude.constructor.name !== "RegExp" + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackInclude\` expected a regular expression, but received: ${importOptions.webpackInclude}.`, + expr.loc + ) + ); + } else { + include = new RegExp(importOptions.webpackInclude); + } + } + if (importOptions.webpackExclude !== undefined) { + if ( + !importOptions.webpackExclude || + importOptions.webpackExclude.constructor.name !== "RegExp" + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackExclude\` expected a regular expression, but received: ${importOptions.webpackExclude}.`, + expr.loc + ) + ); + } else { + exclude = new RegExp(importOptions.webpackExclude); + } + } + if (importOptions.webpackExports !== undefined) { + if ( + !( + typeof importOptions.webpackExports === "string" || + (Array.isArray(importOptions.webpackExports) && + importOptions.webpackExports.every( + item => typeof item === "string" + )) + ) + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackExports\` expected a string or an array of strings, but received: ${importOptions.webpackExports}.`, + expr.loc + ) + ); + } else { + if (typeof importOptions.webpackExports === "string") { + exports = [[importOptions.webpackExports]]; + } else { + exports = Array.from(importOptions.webpackExports, e => [e]); + } + } + } } - }; - parser.hooks.memberChainOfCallMemberChain - .for("require") - .tap("CommonJsImportsParserPlugin", chainHandler); - parser.hooks.memberChainOfCallMemberChain - .for("module.require") - .tap("CommonJsImportsParserPlugin", chainHandler); - parser.hooks.callMemberChainOfCallMemberChain - .for("require") - .tap("CommonJsImportsParserPlugin", callChainHandler); - parser.hooks.callMemberChainOfCallMemberChain - .for("module.require") - .tap("CommonJsImportsParserPlugin", callChainHandler); - // require.resolve // - const processResolve = (expr, weak) => { - if (expr.arguments.length !== 1) return; - const param = parser.evaluateExpression(expr.arguments[0]); - if (param.isConditional()) { - for (const option of param.options) { - const result = processResolveItem(expr, option, weak); - if (result === undefined) { - processResolveContext(expr, option, weak); - } + if (param.isString()) { + if (mode !== "lazy" && mode !== "eager" && mode !== "weak") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackMode\` expected 'lazy', 'eager' or 'weak', but received: ${mode}.`, + expr.loc + ) + ); + } + + if (mode === "eager") { + const dep = new ImportEagerDependency( + param.string, + expr.range, + exports + ); + parser.state.current.addDependency(dep); + } else if (mode === "weak") { + const dep = new ImportWeakDependency( + param.string, + expr.range, + exports + ); + parser.state.current.addDependency(dep); + } else { + const depBlock = new AsyncDependenciesBlock( + { + ...groupOptions, + name: chunkName + }, + expr.loc, + param.string + ); + const dep = new ImportDependency(param.string, expr.range, exports); + dep.loc = expr.loc; + depBlock.addDependency(dep); + parser.state.current.addBlock(depBlock); } - const dep = new RequireResolveHeaderDependency(expr.callee.range); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); return true; } else { - const result = processResolveItem(expr, param, weak); - if (result === undefined) { - processResolveContext(expr, param, weak); + if ( + mode !== "lazy" && + mode !== "lazy-once" && + mode !== "eager" && + mode !== "weak" + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`, + expr.loc + ) + ); + mode = "lazy"; } - const dep = new RequireResolveHeaderDependency(expr.callee.range); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - } - }; - const processResolveItem = (expr, param, weak) => { - if (param.isString()) { - const dep = new RequireResolveDependency(param.string, param.range); + + if (mode === "weak") { + mode = "async-weak"; + } + const dep = ContextDependencyHelpers.create( + ImportContextDependency, + expr.range, + param, + expr, + this.options, + { + chunkName, + groupOptions, + include, + exclude, + mode, + namespaceObject: parser.state.module.buildMeta.strictHarmonyModule + ? "strict" + : true, + typePrefix: "import()", + category: "esm", + referencedExports: exports + }, + parser + ); + if (!dep) return; dep.loc = expr.loc; dep.optional = !!parser.scope.inTry; - dep.weak = weak; parser.state.current.addDependency(dep); return true; } - }; - const processResolveContext = (expr, param, weak) => { - const dep = ContextDependencyHelpers.create( - RequireResolveContextDependency, - param.range, - param, - expr, - options, - { - category: "commonjs", - mode: weak ? "weak" : "sync" - }, - parser - ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - }; - - parser.hooks.call - .for("require.resolve") - .tap("RequireResolveDependencyParserPlugin", expr => { - return processResolve(expr, false); - }); - parser.hooks.call - .for("require.resolveWeak") - .tap("RequireResolveDependencyParserPlugin", expr => { - return processResolve(expr, true); - }); + }); } } -module.exports = CommonJsImportsParserPlugin; + +module.exports = ImportParserPlugin; /***/ }), -/***/ 32406: +/***/ 41293: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -81108,284 +80392,161 @@ module.exports = CommonJsImportsParserPlugin; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const SelfModuleFactory = __webpack_require__(63560); -const Template = __webpack_require__(39722); -const CommonJsExportsDependency = __webpack_require__(45598); -const CommonJsFullRequireDependency = __webpack_require__(59440); -const CommonJsRequireContextDependency = __webpack_require__(23962); -const CommonJsRequireDependency = __webpack_require__(21264); -const CommonJsSelfReferenceDependency = __webpack_require__(52225); -const ModuleDecoratorDependency = __webpack_require__(88488); -const RequireHeaderDependency = __webpack_require__(89183); -const RequireResolveContextDependency = __webpack_require__(55627); -const RequireResolveDependency = __webpack_require__(68582); -const RequireResolveHeaderDependency = __webpack_require__(9880); -const RuntimeRequirementsDependency = __webpack_require__(24187); - -const CommonJsExportsParserPlugin = __webpack_require__(97107); -const CommonJsImportsParserPlugin = __webpack_require__(36013); +const ImportContextDependency = __webpack_require__(1902); +const ImportDependency = __webpack_require__(89376); +const ImportEagerDependency = __webpack_require__(50718); +const ImportParserPlugin = __webpack_require__(88130); +const ImportWeakDependency = __webpack_require__(82483); -const { - evaluateToIdentifier, - toConstantDependency -} = __webpack_require__(93998); -const CommonJsExportRequireDependency = __webpack_require__(62892); +/** @typedef {import("../Compiler")} Compiler */ -class CommonJsPlugin { +class ImportPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ apply(compiler) { compiler.hooks.compilation.tap( - "CommonJsPlugin", + "ImportPlugin", (compilation, { contextModuleFactory, normalModuleFactory }) => { compilation.dependencyFactories.set( - CommonJsRequireDependency, + ImportDependency, normalModuleFactory ); compilation.dependencyTemplates.set( - CommonJsRequireDependency, - new CommonJsRequireDependency.Template() + ImportDependency, + new ImportDependency.Template() ); compilation.dependencyFactories.set( - CommonJsFullRequireDependency, + ImportEagerDependency, normalModuleFactory ); compilation.dependencyTemplates.set( - CommonJsFullRequireDependency, - new CommonJsFullRequireDependency.Template() - ); - - compilation.dependencyFactories.set( - CommonJsRequireContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - CommonJsRequireContextDependency, - new CommonJsRequireContextDependency.Template() + ImportEagerDependency, + new ImportEagerDependency.Template() ); compilation.dependencyFactories.set( - RequireResolveDependency, + ImportWeakDependency, normalModuleFactory ); compilation.dependencyTemplates.set( - RequireResolveDependency, - new RequireResolveDependency.Template() + ImportWeakDependency, + new ImportWeakDependency.Template() ); compilation.dependencyFactories.set( - RequireResolveContextDependency, + ImportContextDependency, contextModuleFactory ); compilation.dependencyTemplates.set( - RequireResolveContextDependency, - new RequireResolveContextDependency.Template() - ); - - compilation.dependencyTemplates.set( - RequireResolveHeaderDependency, - new RequireResolveHeaderDependency.Template() - ); - - compilation.dependencyTemplates.set( - RequireHeaderDependency, - new RequireHeaderDependency.Template() - ); - - compilation.dependencyTemplates.set( - CommonJsExportsDependency, - new CommonJsExportsDependency.Template() - ); - - compilation.dependencyFactories.set( - CommonJsExportRequireDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - CommonJsExportRequireDependency, - new CommonJsExportRequireDependency.Template() - ); - - const selfFactory = new SelfModuleFactory(compilation.moduleGraph); - - compilation.dependencyFactories.set( - CommonJsSelfReferenceDependency, - selfFactory - ); - compilation.dependencyTemplates.set( - CommonJsSelfReferenceDependency, - new CommonJsSelfReferenceDependency.Template() - ); - - compilation.dependencyFactories.set( - ModuleDecoratorDependency, - selfFactory - ); - compilation.dependencyTemplates.set( - ModuleDecoratorDependency, - new ModuleDecoratorDependency.Template() + ImportContextDependency, + new ImportContextDependency.Template() ); - compilation.hooks.runtimeRequirementInModule - .for(RuntimeGlobals.harmonyModuleDecorator) - .tap("CommonJsPlugin", (module, set) => { - set.add(RuntimeGlobals.module); - set.add(RuntimeGlobals.requireScope); - }); - - compilation.hooks.runtimeRequirementInModule - .for(RuntimeGlobals.nodeModuleDecorator) - .tap("CommonJsPlugin", (module, set) => { - set.add(RuntimeGlobals.module); - set.add(RuntimeGlobals.requireScope); - }); - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.harmonyModuleDecorator) - .tap("CommonJsPlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new HarmonyModuleDecoratorRuntimeModule() - ); - }); - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.nodeModuleDecorator) - .tap("CommonJsPlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new NodeModuleDecoratorRuntimeModule() - ); - }); - const handler = (parser, parserOptions) => { - if (parserOptions.commonjs !== undefined && !parserOptions.commonjs) + if (parserOptions.import !== undefined && !parserOptions.import) return; - parser.hooks.typeof - .for("module") - .tap( - "CommonJsPlugin", - toConstantDependency(parser, JSON.stringify("object")) - ); - - parser.hooks.expression - .for("require.main") - .tap( - "CommonJsPlugin", - toConstantDependency( - parser, - `${RuntimeGlobals.moduleCache}[${RuntimeGlobals.entryModuleId}]`, - [RuntimeGlobals.moduleCache, RuntimeGlobals.entryModuleId] - ) - ); - parser.hooks.expression - .for("module.loaded") - .tap("CommonJsPlugin", expr => { - parser.state.module.buildInfo.moduleConcatenationBailout = - "module.loaded"; - const dep = new RuntimeRequirementsDependency([ - RuntimeGlobals.moduleLoaded - ]); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); - - parser.hooks.expression - .for("module.id") - .tap("CommonJsPlugin", expr => { - parser.state.module.buildInfo.moduleConcatenationBailout = - "module.id"; - const dep = new RuntimeRequirementsDependency([ - RuntimeGlobals.moduleId - ]); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); - parser.hooks.evaluateIdentifier.for("module.hot").tap( - "CommonJsPlugin", - evaluateToIdentifier("module.hot", "module", () => ["hot"], null) - ); - - new CommonJsImportsParserPlugin(parserOptions).apply(parser); - new CommonJsExportsParserPlugin(compilation.moduleGraph).apply( - parser - ); + new ImportParserPlugin(parserOptions).apply(parser); }; normalModuleFactory.hooks.parser .for("javascript/auto") - .tap("CommonJsPlugin", handler); + .tap("ImportPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") - .tap("CommonJsPlugin", handler); + .tap("ImportPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ImportPlugin", handler); } ); } } +module.exports = ImportPlugin; -class HarmonyModuleDecoratorRuntimeModule extends RuntimeModule { - constructor() { - super("harmony module decorator"); - } +/***/ }), + +/***/ 82483: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); +const ImportDependency = __webpack_require__(89376); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ + +class ImportWeakDependency extends ImportDependency { /** - * @returns {string} runtime code + * @param {string} request the request + * @param {[number, number]} range expression range + * @param {string[][]=} referencedExports list of referenced exports */ - generate() { - const { runtimeTemplate } = this.compilation; - return Template.asString([ - `${ - RuntimeGlobals.harmonyModuleDecorator - } = ${runtimeTemplate.basicFunction("module", [ - "module = Object.create(module);", - "if (!module.children) module.children = [];", - "Object.defineProperty(module, 'exports', {", - Template.indent([ - "enumerable: true,", - `set: ${runtimeTemplate.basicFunction("", [ - "throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id);" - ])}` - ]), - "});", - "return module;" - ])};` - ]); + constructor(request, range, referencedExports) { + super(request, range, referencedExports); + this.weak = true; } -} -class NodeModuleDecoratorRuntimeModule extends RuntimeModule { - constructor() { - super("node module decorator"); + get type() { + return "import() weak"; } +} + +makeSerializable( + ImportWeakDependency, + "webpack/lib/dependencies/ImportWeakDependency" +); +ImportWeakDependency.Template = class ImportDependencyTemplate extends ( + ImportDependency.Template +) { /** - * @returns {string} runtime code + * @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} */ - generate() { - const { runtimeTemplate } = this.compilation; - return Template.asString([ - `${RuntimeGlobals.nodeModuleDecorator} = ${runtimeTemplate.basicFunction( - "module", - [ - "module.paths = [];", - "if (!module.children) module.children = [];", - "return module;" - ] - )};` - ]); + apply( + dependency, + source, + { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {ImportWeakDependency} */ (dependency); + const content = runtimeTemplate.moduleNamespacePromise({ + chunkGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + strict: module.buildMeta.strictHarmonyModule, + message: "import() weak", + weak: true, + runtimeRequirements + }); + + source.replace(dep.range[0], dep.range[1] - 1, content); } -} +}; -module.exports = CommonJsPlugin; +module.exports = ImportWeakDependency; /***/ }), -/***/ 23962: +/***/ 750: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -81397,58 +80558,106 @@ module.exports = CommonJsPlugin; const makeSerializable = __webpack_require__(33032); -const ContextDependency = __webpack_require__(88101); -const ContextDependencyTemplateAsRequireCall = __webpack_require__(75815); +const NullDependency = __webpack_require__(31830); -class CommonJsRequireContextDependency extends ContextDependency { - constructor(options, range, valueRange, inShorthand) { - super(options); +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ExportSpec} ExportSpec */ +/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/Hash")} Hash */ - this.range = range; - this.valueRange = valueRange; - // inShorthand must be serialized by subclasses that use it - this.inShorthand = inShorthand; +const getExportsFromData = data => { + if (data && typeof data === "object") { + if (Array.isArray(data)) { + return data.map((item, idx) => { + return { + name: `${idx}`, + canMangle: true, + exports: getExportsFromData(item) + }; + }); + } else { + const exports = []; + for (const key of Object.keys(data)) { + exports.push({ + name: key, + canMangle: true, + exports: getExportsFromData(data[key]) + }); + } + return exports; + } + } + return undefined; +}; + +class JsonExportsDependency extends NullDependency { + /** + * @param {(string | ExportSpec)[]} exports json exports + */ + constructor(exports) { + super(); + this.exports = exports; + this._hashUpdate = undefined; } get type() { - return "cjs require context"; + return "json exports"; } - serialize(context) { - const { write } = context; + /** + * Returns the exported names + * @param {ModuleGraph} moduleGraph module graph + * @returns {ExportsSpec | undefined} export names + */ + getExports(moduleGraph) { + return { + exports: this.exports, + dependencies: undefined + }; + } - write(this.range); - write(this.valueRange); - write(this.inShorthand); + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = this.exports + ? JSON.stringify(this.exports) + : "undefined"; + } + hash.update(this._hashUpdate); + } + serialize(context) { + const { write } = context; + write(this.exports); super.serialize(context); } deserialize(context) { const { read } = context; - - this.range = read(); - this.valueRange = read(); - this.inShorthand = read(); - + this.exports = read(); super.deserialize(context); } } makeSerializable( - CommonJsRequireContextDependency, - "webpack/lib/dependencies/CommonJsRequireContextDependency" + JsonExportsDependency, + "webpack/lib/dependencies/JsonExportsDependency" ); -CommonJsRequireContextDependency.Template = - ContextDependencyTemplateAsRequireCall; - -module.exports = CommonJsRequireContextDependency; +module.exports = JsonExportsDependency; +module.exports.getExportsFromData = getExportsFromData; /***/ }), -/***/ 21264: +/***/ 71693: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -81459,38 +80668,31 @@ module.exports = CommonJsRequireContextDependency; -const makeSerializable = __webpack_require__(33032); const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyTemplateAsId = __webpack_require__(80825); -class CommonJsRequireDependency extends ModuleDependency { - constructor(request, range) { +class LoaderDependency extends ModuleDependency { + /** + * @param {string} request request string + */ + constructor(request) { super(request); - this.range = range; } get type() { - return "cjs require"; + return "loader"; } get category() { - return "commonjs"; + return "loader"; } } -CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; - -makeSerializable( - CommonJsRequireDependency, - "webpack/lib/dependencies/CommonJsRequireDependency" -); - -module.exports = CommonJsRequireDependency; +module.exports = LoaderDependency; /***/ }), -/***/ 52225: +/***/ 223: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -81501,79 +80703,404 @@ module.exports = CommonJsRequireDependency; -const RuntimeGlobals = __webpack_require__(16475); -const { equals } = __webpack_require__(84953); -const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +const ModuleDependency = __webpack_require__(80321); -class CommonJsSelfReferenceDependency extends NullDependency { - constructor(range, base, names, call) { - super(); - this.range = range; - this.base = base; - this.names = names; - this.call = call; +class LoaderImportDependency extends ModuleDependency { + /** + * @param {string} request request string + */ + constructor(request) { + super(request); + this.weak = true; } get type() { - return "cjs self exports reference"; + return "loader import"; } get category() { - return "self"; + return "loaderImport"; } +} + +module.exports = LoaderImportDependency; + + +/***/ }), + +/***/ 24721: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const NormalModule = __webpack_require__(39); +const LazySet = __webpack_require__(38938); +const LoaderDependency = __webpack_require__(71693); +const LoaderImportDependency = __webpack_require__(223); + +/** @typedef {import("../Compilation").DepConstructor} DepConstructor */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +/** + * @callback LoadModuleCallback + * @param {(Error | null)=} err error object + * @param {string | Buffer=} source source code + * @param {object=} map source map + * @param {Module=} module loaded module if successful + */ + +/** + * @callback ImportModuleCallback + * @param {(Error | null)=} err error object + * @param {any=} exports exports of the evaluated module + */ + +/** + * @typedef {Object} ImportModuleOptions + * @property {string=} layer the target layer + * @property {string=} publicPath the target public path + */ +class LoaderPlugin { /** - * @returns {string | null} an identifier to merge equal requests + * @param {Object} options options */ - getResourceIdentifier() { - return `self`; - } + constructor(options = {}) {} /** - * 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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - getReferencedExports(moduleGraph, runtime) { - return [this.call ? this.names.slice(0, -1) : this.names]; + apply(compiler) { + compiler.hooks.compilation.tap( + "LoaderPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + LoaderDependency, + normalModuleFactory + ); + compilation.dependencyFactories.set( + LoaderImportDependency, + normalModuleFactory + ); + } + ); + + compiler.hooks.compilation.tap("LoaderPlugin", compilation => { + const moduleGraph = compilation.moduleGraph; + NormalModule.getCompilationHooks(compilation).loader.tap( + "LoaderPlugin", + loaderContext => { + /** + * @param {string} request the request string to load the module from + * @param {LoadModuleCallback} callback callback returning the loaded module or error + * @returns {void} + */ + loaderContext.loadModule = (request, callback) => { + const dep = new LoaderDependency(request); + dep.loc = { + name: request + }; + const factory = compilation.dependencyFactories.get( + /** @type {DepConstructor} */ (dep.constructor) + ); + if (factory === undefined) { + return callback( + new Error( + `No module factory available for dependency type: ${dep.constructor.name}` + ) + ); + } + compilation.buildQueue.increaseParallelism(); + compilation.handleModuleCreation( + { + factory, + dependencies: [dep], + originModule: loaderContext._module, + context: loaderContext.context, + recursive: false + }, + err => { + compilation.buildQueue.decreaseParallelism(); + if (err) { + return callback(err); + } + const referencedModule = moduleGraph.getModule(dep); + if (!referencedModule) { + return callback(new Error("Cannot load the module")); + } + if (referencedModule.getNumberOfErrors() > 0) { + return callback( + new Error("The loaded module contains errors") + ); + } + const moduleSource = referencedModule.originalSource(); + if (!moduleSource) { + return callback( + new Error( + "The module created for a LoaderDependency must have an original source" + ) + ); + } + let source, map; + if (moduleSource.sourceAndMap) { + const sourceAndMap = moduleSource.sourceAndMap(); + map = sourceAndMap.map; + source = sourceAndMap.source; + } else { + map = moduleSource.map(); + source = moduleSource.source(); + } + const fileDependencies = new LazySet(); + const contextDependencies = new LazySet(); + const missingDependencies = new LazySet(); + const buildDependencies = new LazySet(); + referencedModule.addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ); + + for (const d of fileDependencies) { + loaderContext.addDependency(d); + } + for (const d of contextDependencies) { + loaderContext.addContextDependency(d); + } + for (const d of missingDependencies) { + loaderContext.addMissingDependency(d); + } + for (const d of buildDependencies) { + loaderContext.addBuildDependency(d); + } + return callback(null, source, map, referencedModule); + } + ); + }; + + /** + * @param {string} request the request string to load the module from + * @param {ImportModuleOptions=} options options + * @param {ImportModuleCallback=} callback callback returning the exports + * @returns {void} + */ + const importModule = (request, options, callback) => { + const dep = new LoaderImportDependency(request); + dep.loc = { + name: request + }; + const factory = compilation.dependencyFactories.get( + /** @type {DepConstructor} */ (dep.constructor) + ); + if (factory === undefined) { + return callback( + new Error( + `No module factory available for dependency type: ${dep.constructor.name}` + ) + ); + } + compilation.buildQueue.increaseParallelism(); + compilation.handleModuleCreation( + { + factory, + dependencies: [dep], + originModule: loaderContext._module, + contextInfo: { + issuerLayer: options.layer + }, + context: loaderContext.context, + connectOrigin: false + }, + err => { + compilation.buildQueue.decreaseParallelism(); + if (err) { + return callback(err); + } + const referencedModule = moduleGraph.getModule(dep); + if (!referencedModule) { + return callback(new Error("Cannot load the module")); + } + compilation.executeModule( + referencedModule, + { + entryOptions: { + publicPath: options.publicPath + } + }, + (err, result) => { + if (err) return callback(err); + for (const d of result.fileDependencies) { + loaderContext.addDependency(d); + } + for (const d of result.contextDependencies) { + loaderContext.addContextDependency(d); + } + for (const d of result.missingDependencies) { + loaderContext.addMissingDependency(d); + } + for (const d of result.buildDependencies) { + loaderContext.addBuildDependency(d); + } + if (result.cacheable === false) + loaderContext.cacheable(false); + for (const [name, { source, info }] of result.assets) { + const { buildInfo } = loaderContext._module; + if (!buildInfo.assets) { + buildInfo.assets = Object.create(null); + buildInfo.assetsInfo = new Map(); + } + buildInfo.assets[name] = source; + buildInfo.assetsInfo.set(name, info); + } + callback(null, result.exports); + } + ); + } + ); + }; + + /** + * @param {string} request the request string to load the module from + * @param {ImportModuleOptions} options options + * @param {ImportModuleCallback=} callback callback returning the exports + * @returns {Promise | void} exports + */ + loaderContext.importModule = (request, options, callback) => { + if (!callback) { + return new Promise((resolve, reject) => { + importModule(request, options || {}, (err, result) => { + if (err) reject(err); + else resolve(result); + }); + }); + } + return importModule(request, options || {}, callback); + }; + } + ); + }); + } +} +module.exports = LoaderPlugin; + + +/***/ }), + +/***/ 5826: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); + +class LocalModule { + constructor(name, idx) { + this.name = name; + this.idx = idx; + this.used = false; + } + + flagUsed() { + this.used = true; + } + + variableName() { + return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__"; + } + + serialize(context) { + const { write } = context; + + write(this.name); + write(this.idx); + write(this.used); + } + + deserialize(context) { + const { read } = context; + + this.name = read(); + this.idx = read(); + this.used = read(); + } +} + +makeSerializable(LocalModule, "webpack/lib/dependencies/LocalModule"); + +module.exports = LocalModule; + + +/***/ }), + +/***/ 52805: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + +class LocalModuleDependency extends NullDependency { + constructor(localModule, range, callNew) { + super(); + + this.localModule = localModule; + this.range = range; + this.callNew = callNew; } serialize(context) { const { write } = context; + + write(this.localModule); write(this.range); - write(this.base); - write(this.names); - write(this.call); + write(this.callNew); + super.serialize(context); } deserialize(context) { const { read } = context; + + this.localModule = read(); this.range = read(); - this.base = read(); - this.names = read(); - this.call = read(); + this.callNew = read(); + super.deserialize(context); } } makeSerializable( - CommonJsSelfReferenceDependency, - "webpack/lib/dependencies/CommonJsSelfReferenceDependency" + LocalModuleDependency, + "webpack/lib/dependencies/LocalModuleDependency" ); -CommonJsSelfReferenceDependency.Template = class CommonJsSelfReferenceDependencyTemplate extends ( +LocalModuleDependency.Template = class LocalModuleDependencyTemplate extends ( NullDependency.Template ) { /** @@ -81582,64 +81109,80 @@ CommonJsSelfReferenceDependency.Template = class CommonJsSelfReferenceDependency * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ - apply( - dependency, - source, - { module, moduleGraph, runtime, runtimeRequirements } - ) { - const dep = /** @type {CommonJsSelfReferenceDependency} */ (dependency); - let used; - if (dep.names.length === 0) { - used = dep.names; - } else { - used = moduleGraph.getExportsInfo(module).getUsedName(dep.names, runtime); - } - if (!used) { - throw new Error( - "Self-reference dependency has unused export name: This should not happen" - ); - } + apply(dependency, source, templateContext) { + const dep = /** @type {LocalModuleDependency} */ (dependency); + if (!dep.range) return; + const moduleInstance = dep.callNew + ? `new (function () { return ${dep.localModule.variableName()}; })()` + : dep.localModule.variableName(); + source.replace(dep.range[0], dep.range[1] - 1, moduleInstance); + } +}; - let base = undefined; - switch (dep.base) { - case "exports": - runtimeRequirements.add(RuntimeGlobals.exports); - base = module.exportsArgument; - break; - case "module.exports": - runtimeRequirements.add(RuntimeGlobals.module); - base = `${module.moduleArgument}.exports`; - break; - case "this": - runtimeRequirements.add(RuntimeGlobals.thisAsExports); - base = "this"; - break; - default: - throw new Error(`Unsupported base ${dep.base}`); - } +module.exports = LocalModuleDependency; - if (base === dep.base && equals(used, dep.names)) { - // Nothing has to be changed - // We don't use a replacement for compat reasons - // for plugins that update `module._source` which they - // shouldn't do! - return; + +/***/ }), + +/***/ 75827: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const LocalModule = __webpack_require__(5826); + +const lookup = (parent, mod) => { + if (mod.charAt(0) !== ".") return mod; + + var path = parent.split("/"); + var segments = mod.split("/"); + path.pop(); + + for (let i = 0; i < segments.length; i++) { + const seg = segments[i]; + if (seg === "..") { + path.pop(); + } else if (seg !== ".") { + path.push(seg); } + } - source.replace( - dep.range[0], - dep.range[1] - 1, - `${base}${propertyAccess(used)}` - ); + return path.join("/"); +}; + +exports.addLocalModule = (state, name) => { + if (!state.localModules) { + state.localModules = []; } + const m = new LocalModule(name, state.localModules.length); + state.localModules.push(m); + return m; }; -module.exports = CommonJsSelfReferenceDependency; +exports.getLocalModule = (state, name, namedModule) => { + if (!state.localModules) return null; + if (namedModule) { + // resolve dependency name relative to the defining named module + name = lookup(namedModule, name); + } + for (let i = 0; i < state.localModules.length; i++) { + if (state.localModules[i].name === name) { + return state.localModules[i]; + } + } + return null; +}; /***/ }), -/***/ 76911: +/***/ 88488: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -81650,34 +81193,64 @@ module.exports = CommonJsSelfReferenceDependency; +const Dependency = __webpack_require__(54912); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); const makeSerializable = __webpack_require__(33032); const NullDependency = __webpack_require__(31830); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ /** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -class ConstDependency extends NullDependency { +class ModuleDecoratorDependency extends NullDependency { /** - * @param {string} expression the expression - * @param {number|[number, number]} range the source range - * @param {string[]=} runtimeRequirements runtime requirements + * @param {string} decorator the decorator requirement + * @param {boolean} allowExportsAccess allow to access exports from module */ - constructor(expression, range, runtimeRequirements) { + constructor(decorator, allowExportsAccess) { super(); - this.expression = expression; - this.range = range; - this.runtimeRequirements = runtimeRequirements - ? new Set(runtimeRequirements) - : null; + this.decorator = decorator; + this.allowExportsAccess = allowExportsAccess; this._hashUpdate = undefined; } + /** + * @returns {string} a display name for the type of dependency + */ + get type() { + return "module decorator"; + } + + get category() { + return "self"; + } + + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return `self`; + } + + /** + * 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 this.allowExportsAccess + ? Dependency.EXPORTS_OBJECT_REFERENCED + : Dependency.NO_EXPORTS_REFERENCED; + } + /** * Update the hash * @param {Hash} hash hash to be updated @@ -81686,46 +81259,32 @@ class ConstDependency extends NullDependency { */ updateHash(hash, context) { if (this._hashUpdate === undefined) { - let hashUpdate = "" + this.range + "|" + this.expression; - if (this.runtimeRequirements) { - for (const item of this.runtimeRequirements) { - hashUpdate += "|"; - hashUpdate += item; - } - } - this._hashUpdate = hashUpdate; + this._hashUpdate = `${this.decorator}${this.allowExportsAccess}`; } hash.update(this._hashUpdate); } - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules - */ - getModuleEvaluationSideEffectsState(moduleGraph) { - return false; - } - serialize(context) { const { write } = context; - write(this.expression); - write(this.range); - write(this.runtimeRequirements); + write(this.decorator); + write(this.allowExportsAccess); super.serialize(context); } deserialize(context) { const { read } = context; - this.expression = read(); - this.range = read(); - this.runtimeRequirements = read(); + this.decorator = read(); + this.allowExportsAccess = read(); super.deserialize(context); } } -makeSerializable(ConstDependency, "webpack/lib/dependencies/ConstDependency"); +makeSerializable( + ModuleDecoratorDependency, + "webpack/lib/dependencies/ModuleDecoratorDependency" +); -ConstDependency.Template = class ConstDependencyTemplate extends ( +ModuleDecoratorDependency.Template = class ModuleDecoratorDependencyTemplate extends ( NullDependency.Template ) { /** @@ -81734,28 +81293,33 @@ ConstDependency.Template = class ConstDependencyTemplate extends ( * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ - apply(dependency, source, templateContext) { - const dep = /** @type {ConstDependency} */ (dependency); - if (dep.runtimeRequirements) { - for (const req of dep.runtimeRequirements) { - templateContext.runtimeRequirements.add(req); - } - } - if (typeof dep.range === "number") { - source.insert(dep.range, dep.expression); - return; - } - - source.replace(dep.range[0], dep.range[1] - 1, dep.expression); + apply( + dependency, + source, + { module, chunkGraph, initFragments, runtimeRequirements } + ) { + const dep = /** @type {ModuleDecoratorDependency} */ (dependency); + runtimeRequirements.add(RuntimeGlobals.moduleLoaded); + runtimeRequirements.add(RuntimeGlobals.moduleId); + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(dep.decorator); + initFragments.push( + new InitFragment( + `/* module decorator */ ${module.moduleArgument} = ${dep.decorator}(${module.moduleArgument});\n`, + InitFragment.STAGE_PROVIDES, + 0, + `module decorator ${chunkGraph.getModuleId(module)}` + ) + ); } }; -module.exports = ConstDependency; +module.exports = ModuleDecoratorDependency; /***/ }), -/***/ 88101: +/***/ 80321: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -81768,53 +81332,36 @@ module.exports = ConstDependency; const Dependency = __webpack_require__(54912); const DependencyTemplate = __webpack_require__(5160); -const makeSerializable = __webpack_require__(33032); const memoize = __webpack_require__(78676); -/** @typedef {import("../ContextModule").ContextOptions} ContextOptions */ /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../WebpackError")} WebpackError */ - -const getCriticalDependencyWarning = memoize(() => - __webpack_require__(15427) -); - -/** @typedef {ContextOptions & { request: string }} ContextDependencyOptions */ +/** @typedef {import("../Module")} Module */ -const regExpToString = r => (r ? r + "" : ""); +const getRawModule = memoize(() => __webpack_require__(84929)); -class ContextDependency extends Dependency { +class ModuleDependency extends Dependency { /** - * @param {ContextDependencyOptions} options options for the context module + * @param {string} request request path which needs resolving */ - constructor(options) { + constructor(request) { super(); - - this.options = options; - this.userRequest = this.options && this.options.request; - /** @type {false | string} */ - this.critical = false; - this.hadGlobalOrStickyRegExp = false; - - if ( - this.options && - (this.options.regExp.global || this.options.regExp.sticky) - ) { - this.options = { ...this.options, regExp: null }; - this.hadGlobalOrStickyRegExp = true; - } - - this.request = undefined; + this.request = request; + this.userRequest = request; this.range = undefined; - this.valueRange = undefined; - this.inShorthand = undefined; - // TODO refactor this - this.replaces = undefined; + // assertions must be serialized by subclasses that use it + /** @type {Record | undefined} */ + this.assertions = undefined; } - get category() { - return "commonjs"; + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + let str = `module${this.request}`; + if (this.assertions !== undefined) { + str += JSON.stringify(this.assertions); + } + return str; } /** @@ -81825,93 +81372,44 @@ class ContextDependency extends Dependency { } /** - * @returns {string | null} an identifier to merge equal requests + * @param {string} context context directory + * @returns {Module} a module */ - getResourceIdentifier() { - return ( - `context${this.options.request} ${this.options.recursive} ` + - `${regExpToString(this.options.regExp)} ${regExpToString( - this.options.include - )} ${regExpToString(this.options.exclude)} ` + - `${this.options.mode} ${this.options.chunkName} ` + - `${JSON.stringify(this.options.groupOptions)}` + createIgnoredModule(context) { + const RawModule = getRawModule(); + return new RawModule( + "/* (ignored) */", + `ignored|${context}|${this.request}`, + `${this.request} (ignored)` ); } - /** - * Returns warnings - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} warnings - */ - getWarnings(moduleGraph) { - let warnings = super.getWarnings(moduleGraph); - - if (this.critical) { - if (!warnings) warnings = []; - const CriticalDependencyWarning = getCriticalDependencyWarning(); - warnings.push(new CriticalDependencyWarning(this.critical)); - } - - if (this.hadGlobalOrStickyRegExp) { - if (!warnings) warnings = []; - const CriticalDependencyWarning = getCriticalDependencyWarning(); - warnings.push( - new CriticalDependencyWarning( - "Contexts can't use RegExps with the 'g' or 'y' flags." - ) - ); - } - - return warnings; - } - serialize(context) { const { write } = context; - - write(this.options); - write(this.userRequest); - write(this.critical); - write(this.hadGlobalOrStickyRegExp); write(this.request); + write(this.userRequest); write(this.range); - write(this.valueRange); - write(this.prepend); - write(this.replaces); - super.serialize(context); } deserialize(context) { const { read } = context; - - this.options = read(); - this.userRequest = read(); - this.critical = read(); - this.hadGlobalOrStickyRegExp = read(); this.request = read(); + this.userRequest = read(); this.range = read(); - this.valueRange = read(); - this.prepend = read(); - this.replaces = read(); - super.deserialize(context); } } -makeSerializable( - ContextDependency, - "webpack/lib/dependencies/ContextDependency" -); - -ContextDependency.Template = DependencyTemplate; +ModuleDependency.Template = DependencyTemplate; -module.exports = ContextDependency; +module.exports = ModuleDependency; /***/ }), -/***/ 99630: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 80825: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -81921,236 +81419,38 @@ module.exports = ContextDependency; -const { parseResource } = __webpack_require__(82186); - -/** @typedef {import("estree").Node} EsTreeNode */ -/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ -/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */ -/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ -/** @typedef {import("./ContextDependency")} ContextDependency */ -/** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */ - -/** - * Escapes regular expression metacharacters - * @param {string} str String to quote - * @returns {string} Escaped string - */ -const quoteMeta = str => { - return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); -}; - -const splitContextFromPrefix = prefix => { - const idx = prefix.lastIndexOf("/"); - let context = "."; - if (idx >= 0) { - context = prefix.substr(0, idx); - prefix = `.${prefix.substr(idx)}`; - } - return { - context, - prefix - }; -}; - -/** @typedef {Partial>} PartialContextDependencyOptions */ - -/** @typedef {{ new(options: ContextDependencyOptions, range: [number, number], valueRange: [number, number]): ContextDependency }} ContextDependencyConstructor */ - -/** - * @param {ContextDependencyConstructor} Dep the Dependency class - * @param {[number, number]} range source range - * @param {BasicEvaluatedExpression} param context param - * @param {EsTreeNode} expr expr - * @param {Pick} options options for context creation - * @param {PartialContextDependencyOptions} contextOptions options for the ContextModule - * @param {JavascriptParser} parser the parser - * @returns {ContextDependency} the created Dependency - */ -exports.create = (Dep, range, param, expr, options, contextOptions, parser) => { - if (param.isTemplateString()) { - let prefixRaw = param.quasis[0].string; - let postfixRaw = - param.quasis.length > 1 - ? param.quasis[param.quasis.length - 1].string - : ""; - - const valueRange = param.range; - const { context, prefix } = splitContextFromPrefix(prefixRaw); - const { - path: postfix, - query, - fragment - } = parseResource(postfixRaw, parser); - - // When there are more than two quasis, the generated RegExp can be more precise - // We join the quasis with the expression regexp - const innerQuasis = param.quasis.slice(1, param.quasis.length - 1); - const innerRegExp = - options.wrappedContextRegExp.source + - innerQuasis - .map(q => quoteMeta(q.string) + options.wrappedContextRegExp.source) - .join(""); +const ModuleDependency = __webpack_require__(80321); - // Example: `./context/pre${e}inner${e}inner2${e}post?query#frag` - // context: "./context" - // prefix: "./pre" - // innerQuasis: [BEE("inner"), BEE("inner2")] - // (BEE = BasicEvaluatedExpression) - // postfix: "post" - // query: "?query" - // fragment: "#frag" - // regExp: /^\.\/pre.*inner.*inner2.*post$/ - const regExp = new RegExp( - `^${quoteMeta(prefix)}${innerRegExp}${quoteMeta(postfix)}$` - ); - const dep = new Dep( - { - request: context + query + fragment, - recursive: options.wrappedContextRecursive, - regExp, - mode: "sync", - ...contextOptions - }, - range, - valueRange - ); - dep.loc = expr.loc; - const replaces = []; +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - param.parts.forEach((part, i) => { - if (i % 2 === 0) { - // Quasis or merged quasi - let range = part.range; - let value = part.string; - if (param.templateStringKind === "cooked") { - value = JSON.stringify(value); - value = value.slice(1, value.length - 1); - } - if (i === 0) { - // prefix - value = prefix; - range = [param.range[0], part.range[1]]; - value = - (param.templateStringKind === "cooked" ? "`" : "String.raw`") + - value; - } else if (i === param.parts.length - 1) { - // postfix - value = postfix; - range = [part.range[0], param.range[1]]; - value = value + "`"; - } else if ( - part.expression && - part.expression.type === "TemplateElement" && - part.expression.value.raw === value - ) { - // Shortcut when it's a single quasi and doesn't need to be replaced - return; - } - replaces.push({ - range, - value - }); - } else { - // Expression - parser.walkExpression(part.expression); - } +class ModuleDependencyTemplateAsId extends ModuleDependency.Template { + /** + * @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, { runtimeTemplate, moduleGraph, chunkGraph }) { + const dep = /** @type {ModuleDependency} */ (dependency); + if (!dep.range) return; + const content = runtimeTemplate.moduleId({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + weak: dep.weak }); - - dep.replaces = replaces; - dep.critical = - options.wrappedContextCritical && - "a part of the request of a dependency is an expression"; - return dep; - } else if ( - param.isWrapped() && - ((param.prefix && param.prefix.isString()) || - (param.postfix && param.postfix.isString())) - ) { - let prefixRaw = - param.prefix && param.prefix.isString() ? param.prefix.string : ""; - let postfixRaw = - param.postfix && param.postfix.isString() ? param.postfix.string : ""; - const prefixRange = - param.prefix && param.prefix.isString() ? param.prefix.range : null; - const postfixRange = - param.postfix && param.postfix.isString() ? param.postfix.range : null; - const valueRange = param.range; - const { context, prefix } = splitContextFromPrefix(prefixRaw); - const { - path: postfix, - query, - fragment - } = parseResource(postfixRaw, parser); - const regExp = new RegExp( - `^${quoteMeta(prefix)}${options.wrappedContextRegExp.source}${quoteMeta( - postfix - )}$` - ); - const dep = new Dep( - { - request: context + query + fragment, - recursive: options.wrappedContextRecursive, - regExp, - mode: "sync", - ...contextOptions - }, - range, - valueRange - ); - dep.loc = expr.loc; - const replaces = []; - if (prefixRange) { - replaces.push({ - range: prefixRange, - value: JSON.stringify(prefix) - }); - } - if (postfixRange) { - replaces.push({ - range: postfixRange, - value: JSON.stringify(postfix) - }); - } - dep.replaces = replaces; - dep.critical = - options.wrappedContextCritical && - "a part of the request of a dependency is an expression"; - - if (parser && param.wrappedInnerExpressions) { - for (const part of param.wrappedInnerExpressions) { - if (part.expression) parser.walkExpression(part.expression); - } - } - - return dep; - } else { - const dep = new Dep( - { - request: options.exprContextRequest, - recursive: options.exprContextRecursive, - regExp: /** @type {RegExp} */ (options.exprContextRegExp), - mode: "sync", - ...contextOptions - }, - range, - param.range - ); - dep.loc = expr.loc; - dep.critical = - options.exprContextCritical && - "the request of a dependency is an expression"; - - parser.walkExpression(param.expression); - - return dep; + source.replace(dep.range[0], dep.range[1] - 1, content); } -}; +} + +module.exports = ModuleDependencyTemplateAsId; /***/ }), -/***/ 76081: +/***/ 36873: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -82161,13 +81461,13 @@ exports.create = (Dep, range, param, expr, options, contextOptions, parser) => { -const ContextDependency = __webpack_require__(88101); +const ModuleDependency = __webpack_require__(80321); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -class ContextDependencyTemplateAsId extends ContextDependency.Template { +class ModuleDependencyTemplateAsRequireId extends ModuleDependency.Template { /** * @param {Dependency} dependency the dependency for which the template should be applied * @param {ReplaceSource} source the current replace source which can be modified @@ -82179,47 +81479,24 @@ class ContextDependencyTemplateAsId extends ContextDependency.Template { source, { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } ) { - const dep = /** @type {ContextDependency} */ (dependency); - const moduleExports = runtimeTemplate.moduleExports({ + const dep = /** @type {ModuleDependency} */ (dependency); + if (!dep.range) return; + const content = runtimeTemplate.moduleExports({ module: moduleGraph.getModule(dep), chunkGraph, request: dep.request, weak: dep.weak, runtimeRequirements }); - - if (moduleGraph.getModule(dep)) { - if (dep.valueRange) { - if (Array.isArray(dep.replaces)) { - for (let i = 0; i < dep.replaces.length; i++) { - const rep = dep.replaces[i]; - source.replace(rep.range[0], rep.range[1] - 1, rep.value); - } - } - source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); - source.replace( - dep.range[0], - dep.valueRange[0] - 1, - `${moduleExports}.resolve(` - ); - } else { - source.replace( - dep.range[0], - dep.range[1] - 1, - `${moduleExports}.resolve` - ); - } - } else { - source.replace(dep.range[0], dep.range[1] - 1, moduleExports); - } + source.replace(dep.range[0], dep.range[1] - 1, content); } } -module.exports = ContextDependencyTemplateAsId; +module.exports = ModuleDependencyTemplateAsRequireId; /***/ }), -/***/ 75815: +/***/ 47511: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -82230,63 +81507,39 @@ module.exports = ContextDependencyTemplateAsId; -const ContextDependency = __webpack_require__(88101); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyTemplateAsId = __webpack_require__(80825); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +class ModuleHotAcceptDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; + } -class ContextDependencyTemplateAsRequireCall extends ContextDependency.Template { - /** - * @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, - { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {ContextDependency} */ (dependency); - let moduleExports = runtimeTemplate.moduleExports({ - module: moduleGraph.getModule(dep), - chunkGraph, - request: dep.request, - runtimeRequirements - }); + get type() { + return "module.hot.accept"; + } - if (dep.inShorthand) { - moduleExports = `${dep.inShorthand}: ${moduleExports}`; - } - if (moduleGraph.getModule(dep)) { - if (dep.valueRange) { - if (Array.isArray(dep.replaces)) { - for (let i = 0; i < dep.replaces.length; i++) { - const rep = dep.replaces[i]; - source.replace(rep.range[0], rep.range[1] - 1, rep.value); - } - } - source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); - source.replace( - dep.range[0], - dep.valueRange[0] - 1, - `${moduleExports}(` - ); - } else { - source.replace(dep.range[0], dep.range[1] - 1, moduleExports); - } - } else { - source.replace(dep.range[0], dep.range[1] - 1, moduleExports); - } + get category() { + return "commonjs"; } } -module.exports = ContextDependencyTemplateAsRequireCall; + +makeSerializable( + ModuleHotAcceptDependency, + "webpack/lib/dependencies/ModuleHotAcceptDependency" +); + +ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = ModuleHotAcceptDependency; /***/ }), -/***/ 58477: +/***/ 86301: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -82297,75 +81550,40 @@ module.exports = ContextDependencyTemplateAsRequireCall; -const Dependency = __webpack_require__(54912); const makeSerializable = __webpack_require__(33032); const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyTemplateAsId = __webpack_require__(80825); -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -class ContextElementDependency extends ModuleDependency { - constructor(request, userRequest, typePrefix, category, referencedExports) { +class ModuleHotDeclineDependency extends ModuleDependency { + constructor(request, range) { super(request); - this.referencedExports = referencedExports; - this._typePrefix = typePrefix; - this._category = category; - if (userRequest) { - this.userRequest = userRequest; - } + this.range = range; + this.weak = true; } get type() { - if (this._typePrefix) { - return `${this._typePrefix} context element`; - } - - return "context element"; + return "module.hot.decline"; } get category() { - return this._category; - } - - /** - * 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 this.referencedExports - ? this.referencedExports.map(e => ({ - name: e, - canMangle: false - })) - : Dependency.EXPORTS_OBJECT_REFERENCED; - } - - serialize(context) { - context.write(this.referencedExports); - super.serialize(context); - } - - deserialize(context) { - this.referencedExports = context.read(); - super.deserialize(context); + return "commonjs"; } } makeSerializable( - ContextElementDependency, - "webpack/lib/dependencies/ContextElementDependency" + ModuleHotDeclineDependency, + "webpack/lib/dependencies/ModuleHotDeclineDependency" ); -module.exports = ContextElementDependency; +ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId; + +module.exports = ModuleHotDeclineDependency; /***/ }), -/***/ 79062: +/***/ 31830: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -82376,42 +81594,28 @@ module.exports = ContextElementDependency; -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +const Dependency = __webpack_require__(54912); +const DependencyTemplate = __webpack_require__(5160); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -class CreateScriptUrlDependency extends NullDependency { - /** - * @param {[number, number]} range range - */ - constructor(range) { - super(); - this.range = range; - } - +class NullDependency extends Dependency { get type() { - return "create script url"; - } - - serialize(context) { - const { write } = context; - write(this.range); - super.serialize(context); + return "null"; } - deserialize(context) { - const { read } = context; - this.range = read(); - super.deserialize(context); + /** + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + */ + couldAffectReferencingModule() { + return false; } } -CreateScriptUrlDependency.Template = class CreateScriptUrlDependencyTemplate extends ( - NullDependency.Template +NullDependency.Template = class NullDependencyTemplate extends ( + DependencyTemplate ) { /** * @param {Dependency} dependency the dependency for which the template should be applied @@ -82419,27 +81623,15 @@ CreateScriptUrlDependency.Template = class CreateScriptUrlDependencyTemplate ext * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ - apply(dependency, source, { runtimeRequirements }) { - const dep = /** @type {CreateScriptUrlDependency} */ (dependency); - - runtimeRequirements.add(RuntimeGlobals.createScriptUrl); - - source.insert(dep.range[0], `${RuntimeGlobals.createScriptUrl}(`); - source.insert(dep.range[1], ")"); - } + apply(dependency, source, templateContext) {} }; -makeSerializable( - CreateScriptUrlDependency, - "webpack/lib/dependencies/CreateScriptUrlDependency" -); - -module.exports = CreateScriptUrlDependency; +module.exports = NullDependency; /***/ }), -/***/ 15427: +/***/ 31618: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -82450,288 +81642,236 @@ module.exports = CreateScriptUrlDependency; -const WebpackError = __webpack_require__(53799); -const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); -class CriticalDependencyWarning extends WebpackError { - constructor(message) { - super(); +class PrefetchDependency extends ModuleDependency { + constructor(request) { + super(request); + } - this.name = "CriticalDependencyWarning"; - this.message = "Critical dependency: " + message; + get type() { + return "prefetch"; } -} -makeSerializable( - CriticalDependencyWarning, - "webpack/lib/dependencies/CriticalDependencyWarning" -); + get category() { + return "esm"; + } +} -module.exports = CriticalDependencyWarning; +module.exports = PrefetchDependency; /***/ }), -/***/ 76760: +/***/ 95770: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Florent Cailhol @ooflorent */ +const InitFragment = __webpack_require__(55870); const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +const ModuleDependency = __webpack_require__(80321); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ /** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../util/Hash")} Hash */ -class CssExportDependency extends NullDependency { - /** - * @param {string} name name - * @param {string} value value - */ - constructor(name, value) { - super(); - this.name = name; - this.value = value; +/** + * @param {string[]|null} path the property path array + * @returns {string} the converted path + */ +const pathToString = path => + path !== null && path.length > 0 + ? path.map(part => `[${JSON.stringify(part)}]`).join("") + : ""; + +class ProvidedDependency extends ModuleDependency { + constructor(request, identifier, path, range) { + super(request); + this.identifier = identifier; + this.path = path; + this.range = range; + this._hashUpdate = undefined; } get type() { - return "css :export"; + return "provided"; + } + + get category() { + return "esm"; } /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} */ - getExports(moduleGraph) { - const name = this.name; - return { - exports: [ - { - name, - canMangle: true - } - ], - dependencies: undefined - }; + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = + this.identifier + (this.path ? this.path.join(",") : "null"); + } + hash.update(this._hashUpdate); } serialize(context) { const { write } = context; - write(this.name); - write(this.value); + write(this.identifier); + write(this.path); super.serialize(context); } deserialize(context) { const { read } = context; - this.name = read(); - this.value = read(); + this.identifier = read(); + this.path = read(); super.deserialize(context); } } -CssExportDependency.Template = class CssExportDependencyTemplate extends ( - NullDependency.Template -) { +makeSerializable( + ProvidedDependency, + "webpack/lib/dependencies/ProvidedDependency" +); + +class ProvidedDependencyTemplate extends ModuleDependency.Template { /** * @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, { cssExports }) { - const dep = /** @type {CssExportDependency} */ (dependency); - cssExports.set(dep.name, dep.value); + apply( + dependency, + source, + { + runtimeTemplate, + moduleGraph, + chunkGraph, + initFragments, + runtimeRequirements + } + ) { + const dep = /** @type {ProvidedDependency} */ (dependency); + initFragments.push( + new InitFragment( + `/* provided dependency */ var ${ + dep.identifier + } = ${runtimeTemplate.moduleExports({ + module: moduleGraph.getModule(dep), + chunkGraph, + request: dep.request, + runtimeRequirements + })}${pathToString(dep.path)};\n`, + InitFragment.STAGE_PROVIDES, + 1, + `provided ${dep.identifier}` + ) + ); + source.replace(dep.range[0], dep.range[1] - 1, dep.identifier); } -}; +} -makeSerializable( - CssExportDependency, - "webpack/lib/dependencies/CssExportDependency" -); +ProvidedDependency.Template = ProvidedDependencyTemplate; -module.exports = CssExportDependency; +module.exports = ProvidedDependency; /***/ }), -/***/ 90542: +/***/ 55799: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ +const { UsageState } = __webpack_require__(63686); const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); +const { filterRuntime } = __webpack_require__(17156); +const NullDependency = __webpack_require__(31830); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ /** @typedef {import("../ChunkGraph")} ChunkGraph */ /** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ /** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ /** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -class CssImportDependency extends ModuleDependency { +class PureExpressionDependency extends NullDependency { /** - * @param {string} request request - * @param {[number, number]} range range of the argument - * @param {string | undefined} supports list of supports conditions - * @param {string | undefined} media list of media conditions + * @param {[number, number]} range the source range */ - constructor(request, range, supports, media) { - super(request); + constructor(range) { + super(); this.range = range; - this.supports = supports; - this.media = media; - } - - get type() { - return "css @import"; - } - - get category() { - return "css-import"; - } - - /** - * @param {string} context context directory - * @returns {Module} a module - */ - createIgnoredModule(context) { - return null; + /** @type {Set | false} */ + this.usedByExports = false; + this._hashUpdate = undefined; } -} -CssImportDependency.Template = class CssImportDependencyTemplate extends ( - ModuleDependency.Template -) { /** - * @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 + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context * @returns {void} */ - apply(dependency, source, templateContext) { - const dep = /** @type {CssImportDependency} */ (dependency); - - source.replace(dep.range[0], dep.range[1] - 1, ""); - } -}; - -makeSerializable( - CssImportDependency, - "webpack/lib/dependencies/CssImportDependency" -); - -module.exports = CssImportDependency; - - -/***/ }), - -/***/ 92328: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - - - -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ - -class CssLocalIdentifierDependency extends NullDependency { - /** - * @param {string} name name - * @param {[number, number]} range range - * @param {string=} prefix prefix - */ - constructor(name, range, prefix = "") { - super(); - this.name = name; - this.range = range; - this.prefix = prefix; - } - - get type() { - return "css local identifier"; + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = this.range + ""; + } + hash.update(this._hashUpdate); } /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this dependency connects the module to referencing modules */ - getExports(moduleGraph) { - const name = this.name; - return { - exports: [ - { - name, - canMangle: true - } - ], - dependencies: undefined - }; + getModuleEvaluationSideEffectsState(moduleGraph) { + return false; } serialize(context) { const { write } = context; - write(this.name); write(this.range); - write(this.prefix); + write(this.usedByExports); super.serialize(context); } deserialize(context) { const { read } = context; - this.name = read(); this.range = read(); - this.prefix = read(); + this.usedByExports = read(); super.deserialize(context); } } -const escapeCssIdentifier = (str, omitUnderscore) => { - const escaped = `${str}`.replace( - // cspell:word uffff - /[^a-zA-Z0-9_\u0081-\uffff-]/g, - s => `\\${s}` - ); - return !omitUnderscore && /^(?!--)[0-9-]/.test(escaped) - ? `_${escaped}` - : escaped; -}; +makeSerializable( + PureExpressionDependency, + "webpack/lib/dependencies/PureExpressionDependency" +); -CssLocalIdentifierDependency.Template = class CssLocalIdentifierDependencyTemplate extends ( +PureExpressionDependency.Template = class PureExpressionDependencyTemplate extends ( NullDependency.Template ) { /** @@ -82743,288 +81883,332 @@ CssLocalIdentifierDependency.Template = class CssLocalIdentifierDependencyTempla apply( dependency, source, - { module, moduleGraph, chunkGraph, runtime, runtimeTemplate, cssExports } + { chunkGraph, moduleGraph, runtime, runtimeTemplate, runtimeRequirements } ) { - const dep = /** @type {CssLocalIdentifierDependency} */ (dependency); - const used = moduleGraph - .getExportInfo(module, dep.name) - .getUsedName(dep.name, runtime); - const moduleId = chunkGraph.getModuleId(module); - const identifier = - dep.prefix + - (runtimeTemplate.outputOptions.uniqueName - ? runtimeTemplate.outputOptions.uniqueName + "-" - : "") + - (used ? moduleId + "-" + used : "-"); - source.replace( + const dep = /** @type {PureExpressionDependency} */ (dependency); + + const usedByExports = dep.usedByExports; + if (usedByExports !== false) { + const selfModule = moduleGraph.getParentModule(dep); + const exportsInfo = moduleGraph.getExportsInfo(selfModule); + const runtimeCondition = filterRuntime(runtime, runtime => { + for (const exportName of usedByExports) { + if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) { + return true; + } + } + return false; + }); + if (runtimeCondition === true) return; + if (runtimeCondition !== false) { + const condition = runtimeTemplate.runtimeConditionExpression({ + chunkGraph, + runtime, + runtimeCondition, + runtimeRequirements + }); + source.insert( + dep.range[0], + `(/* runtime-dependent pure expression or super */ ${condition} ? (` + ); + source.insert(dep.range[1], ") : null)"); + return; + } + } + + source.insert( dep.range[0], - dep.range[1] - 1, - escapeCssIdentifier(identifier, dep.prefix) + `(/* unused pure expression or super */ null && (` ); - if (used) cssExports.set(used, identifier); + source.insert(dep.range[1], "))"); } }; -makeSerializable( - CssLocalIdentifierDependency, - "webpack/lib/dependencies/CssLocalIdentifierDependency" -); - -module.exports = CssLocalIdentifierDependency; +module.exports = PureExpressionDependency; /***/ }), -/***/ 29094: +/***/ 46917: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const Dependency = __webpack_require__(54912); const makeSerializable = __webpack_require__(33032); -const CssLocalIdentifierDependency = __webpack_require__(92328); +const ContextDependency = __webpack_require__(88101); +const ModuleDependencyTemplateAsRequireId = __webpack_require__(36873); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +class RequireContextDependency extends ContextDependency { + constructor(options, range) { + super(options); -class CssSelfLocalIdentifierDependency extends CssLocalIdentifierDependency { - /** - * @param {string} name name - * @param {[number, number]} range range - * @param {string=} prefix prefix - * @param {Set=} declaredSet set of declared names (will only be active when in declared set) - */ - constructor(name, range, prefix = "", declaredSet = undefined) { - super(name, range, prefix); - this.declaredSet = declaredSet; + this.range = range; } get type() { - return "css self local identifier"; - } - - get category() { - return "self"; - } - - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - return `self`; - } - /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names - */ - getExports(moduleGraph) { - if (this.declaredSet && !this.declaredSet.has(this.name)) return; - return super.getExports(moduleGraph); - } - - /** - * 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) { - if (this.declaredSet && !this.declaredSet.has(this.name)) - return Dependency.NO_EXPORTS_REFERENCED; - return [[this.name]]; + return "require.context"; } serialize(context) { const { write } = context; - write(this.declaredSet); + + write(this.range); + super.serialize(context); } deserialize(context) { const { read } = context; - this.declaredSet = read(); + + this.range = read(); + super.deserialize(context); } } -CssSelfLocalIdentifierDependency.Template = class CssSelfLocalIdentifierDependencyTemplate extends ( - CssLocalIdentifierDependency.Template -) { - /** - * @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 dep = /** @type {CssSelfLocalIdentifierDependency} */ (dependency); - if (dep.declaredSet && !dep.declaredSet.has(dep.name)) return; - super.apply(dependency, source, templateContext); - } -}; - makeSerializable( - CssSelfLocalIdentifierDependency, - "webpack/lib/dependencies/CssSelfLocalIdentifierDependency" + RequireContextDependency, + "webpack/lib/dependencies/RequireContextDependency" ); -module.exports = CssSelfLocalIdentifierDependency; +RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; + +module.exports = RequireContextDependency; /***/ }), -/***/ 70749: +/***/ 18851: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const makeSerializable = __webpack_require__(33032); -const memoize = __webpack_require__(78676); -const ModuleDependency = __webpack_require__(80321); +const RequireContextDependency = __webpack_require__(46917); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +module.exports = class RequireContextDependencyParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.context") + .tap("RequireContextDependencyParserPlugin", expr => { + let regExp = /^\.\/.*$/; + let recursive = true; + let mode = "sync"; + switch (expr.arguments.length) { + case 4: { + const modeExpr = parser.evaluateExpression(expr.arguments[3]); + if (!modeExpr.isString()) return; + mode = modeExpr.string; + } + // falls through + case 3: { + const regExpExpr = parser.evaluateExpression(expr.arguments[2]); + if (!regExpExpr.isRegExp()) return; + regExp = regExpExpr.regExp; + } + // falls through + case 2: { + const recursiveExpr = parser.evaluateExpression(expr.arguments[1]); + if (!recursiveExpr.isBoolean()) return; + recursive = recursiveExpr.bool; + } + // falls through + case 1: { + const requestExpr = parser.evaluateExpression(expr.arguments[0]); + if (!requestExpr.isString()) return; + const dep = new RequireContextDependency( + { + request: requestExpr.string, + recursive, + regExp, + mode, + category: "commonjs" + }, + expr.range + ); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + }); + } +}; -const getRawDataUrlModule = memoize(() => __webpack_require__(19684)); -class CssUrlDependency extends ModuleDependency { - /** - * @param {string} request request - * @param {[number, number]} range range of the argument - * @param {string} cssFunctionKind kind of css function, e. g. url(), image() - */ - constructor(request, range, cssFunctionKind) { - super(request); - this.range = range; - this.cssFunctionKind = cssFunctionKind; - } +/***/ }), - get type() { - return "css url()"; - } +/***/ 2928: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - get category() { - return "url"; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @param {string} context context directory - * @returns {Module} a module - */ - createIgnoredModule(context) { - const RawDataUrlModule = getRawDataUrlModule(); - return new RawDataUrlModule("data:,", `ignored-asset`, `(ignored asset)`); - } - serialize(context) { - const { write } = context; - write(this.cssFunctionKind); - super.serialize(context); - } - deserialize(context) { - const { read } = context; - this.cssFunctionKind = read(); - super.deserialize(context); - } -} +const { cachedSetProperty } = __webpack_require__(60839); +const ContextElementDependency = __webpack_require__(58477); +const RequireContextDependency = __webpack_require__(46917); +const RequireContextDependencyParserPlugin = __webpack_require__(18851); -const cssEscapeString = str => { - let countWhiteOrBracket = 0; - let countQuotation = 0; - let countApostrophe = 0; - for (let i = 0; i < str.length; i++) { - const cc = str.charCodeAt(i); - switch (cc) { - case 9: // tab - case 10: // nl - case 32: // space - case 40: // ( - case 41: // ) - countWhiteOrBracket++; - break; - case 34: - countQuotation++; - break; - case 39: - countApostrophe++; - break; - } - } - if (countWhiteOrBracket < 2) { - return str.replace(/[\n\t ()'"\\]/g, m => `\\${m}`); - } else if (countQuotation <= countApostrophe) { - return `"${str.replace(/[\n"\\]/g, m => `\\${m}`)}"`; - } else { - return `'${str.replace(/[\n'\\]/g, m => `\\${m}`)}'`; - } -}; +/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../Compiler")} Compiler */ -CssUrlDependency.Template = class CssUrlDependencyTemplate extends ( - ModuleDependency.Template -) { +/** @type {ResolveOptions} */ +const EMPTY_RESOLVE_OPTIONS = {}; + +class RequireContextPlugin { /** - * @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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply( - dependency, - source, - { runtime, moduleGraph, runtimeTemplate, codeGenerationResults } - ) { - const dep = /** @type {CssUrlDependency} */ (dependency); + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireContextPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireContextDependency, + new RequireContextDependency.Template() + ); - source.replace( - dep.range[0], - dep.range[1] - 1, - `${dep.cssFunctionKind}(${cssEscapeString( - runtimeTemplate.assetUrl({ - publicPath: "", - runtime, - module: moduleGraph.getModule(dep), - codeGenerationResults - }) - )})` - ); - } -}; + compilation.dependencyFactories.set( + ContextElementDependency, + normalModuleFactory + ); -makeSerializable(CssUrlDependency, "webpack/lib/dependencies/CssUrlDependency"); + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireContext !== undefined && + !parserOptions.requireContext + ) + return; -module.exports = CssUrlDependency; + new RequireContextDependencyParserPlugin().apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireContextPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireContextPlugin", handler); + + contextModuleFactory.hooks.alternativeRequests.tap( + "RequireContextPlugin", + (items, options) => { + if (items.length === 0) return items; + + const finalResolveOptions = compiler.resolverFactory.get( + "normal", + cachedSetProperty( + options.resolveOptions || EMPTY_RESOLVE_OPTIONS, + "dependencyType", + options.category + ) + ).options; + + let newItems; + if (!finalResolveOptions.fullySpecified) { + newItems = []; + for (const item of items) { + const { request, context } = item; + for (const ext of finalResolveOptions.extensions) { + if (request.endsWith(ext)) { + newItems.push({ + context, + request: request.slice(0, -ext.length) + }); + } + } + if (!finalResolveOptions.enforceExtension) { + newItems.push(item); + } + } + items = newItems; + + newItems = []; + for (const obj of items) { + const { request, context } = obj; + for (const mainFile of finalResolveOptions.mainFiles) { + if (request.endsWith(`/${mainFile}`)) { + newItems.push({ + context, + request: request.slice(0, -mainFile.length) + }); + newItems.push({ + context, + request: request.slice(0, -mainFile.length - 1) + }); + } + } + newItems.push(obj); + } + items = newItems; + } + + newItems = []; + for (const item of items) { + let hideOriginal = false; + for (const modulesItems of finalResolveOptions.modules) { + if (Array.isArray(modulesItems)) { + for (const dir of modulesItems) { + if (item.request.startsWith(`./${dir}/`)) { + newItems.push({ + context: item.context, + request: item.request.slice(dir.length + 3) + }); + hideOriginal = true; + } + } + } else { + const dir = modulesItems.replace(/\\/g, "/"); + const fullPath = + item.context.replace(/\\/g, "/") + item.request.slice(1); + if (fullPath.startsWith(dir)) { + newItems.push({ + context: item.context, + request: fullPath.slice(dir.length + 1) + }); + } + } + } + if (!hideOriginal) { + newItems.push(item); + } + } + return newItems; + } + ); + } + ); + } +} +module.exports = RequireContextPlugin; /***/ }), -/***/ 22914: +/***/ 27153: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -83035,34 +82219,26 @@ module.exports = CssUrlDependency; +const AsyncDependenciesBlock = __webpack_require__(47736); const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); - -class DelegatedSourceDependency extends ModuleDependency { - constructor(request) { - super(request); - } - - get type() { - return "delegated source"; - } - get category() { - return "esm"; +class RequireEnsureDependenciesBlock extends AsyncDependenciesBlock { + constructor(chunkName, loc) { + super(chunkName, loc, null); } } makeSerializable( - DelegatedSourceDependency, - "webpack/lib/dependencies/DelegatedSourceDependency" + RequireEnsureDependenciesBlock, + "webpack/lib/dependencies/RequireEnsureDependenciesBlock" ); -module.exports = DelegatedSourceDependency; +module.exports = RequireEnsureDependenciesBlock; /***/ }), -/***/ 95666: +/***/ 7235: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -83073,26 +82249,163 @@ module.exports = DelegatedSourceDependency; -const Dependency = __webpack_require__(54912); -const makeSerializable = __webpack_require__(33032); - -class DllEntryDependency extends Dependency { - constructor(dependencies, name) { - super(); - - this.dependencies = dependencies; - this.name = name; - } - - get type() { - return "dll entry"; - } +const RequireEnsureDependenciesBlock = __webpack_require__(27153); +const RequireEnsureDependency = __webpack_require__(27223); +const RequireEnsureItemDependency = __webpack_require__(50329); +const getFunctionExpression = __webpack_require__(50396); - serialize(context) { +module.exports = class RequireEnsureDependenciesBlockParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.ensure") + .tap("RequireEnsureDependenciesBlockParserPlugin", expr => { + let chunkName = null; + let errorExpressionArg = null; + let errorExpression = null; + switch (expr.arguments.length) { + case 4: { + const chunkNameExpr = parser.evaluateExpression(expr.arguments[3]); + if (!chunkNameExpr.isString()) return; + chunkName = chunkNameExpr.string; + } + // falls through + case 3: { + errorExpressionArg = expr.arguments[2]; + errorExpression = getFunctionExpression(errorExpressionArg); + + if (!errorExpression && !chunkName) { + const chunkNameExpr = parser.evaluateExpression( + expr.arguments[2] + ); + if (!chunkNameExpr.isString()) return; + chunkName = chunkNameExpr.string; + } + } + // falls through + case 2: { + const dependenciesExpr = parser.evaluateExpression( + expr.arguments[0] + ); + const dependenciesItems = dependenciesExpr.isArray() + ? dependenciesExpr.items + : [dependenciesExpr]; + const successExpressionArg = expr.arguments[1]; + const successExpression = + getFunctionExpression(successExpressionArg); + + if (successExpression) { + parser.walkExpressions(successExpression.expressions); + } + if (errorExpression) { + parser.walkExpressions(errorExpression.expressions); + } + + const depBlock = new RequireEnsureDependenciesBlock( + chunkName, + expr.loc + ); + const errorCallbackExists = + expr.arguments.length === 4 || + (!chunkName && expr.arguments.length === 3); + const dep = new RequireEnsureDependency( + expr.range, + expr.arguments[1].range, + errorCallbackExists && expr.arguments[2].range + ); + dep.loc = expr.loc; + depBlock.addDependency(dep); + const old = parser.state.current; + parser.state.current = depBlock; + try { + let failed = false; + parser.inScope([], () => { + for (const ee of dependenciesItems) { + if (ee.isString()) { + const ensureDependency = new RequireEnsureItemDependency( + ee.string + ); + ensureDependency.loc = ee.loc || expr.loc; + depBlock.addDependency(ensureDependency); + } else { + failed = true; + } + } + }); + if (failed) { + return; + } + if (successExpression) { + if (successExpression.fn.body.type === "BlockStatement") { + parser.walkStatement(successExpression.fn.body); + } else { + parser.walkExpression(successExpression.fn.body); + } + } + old.addBlock(depBlock); + } finally { + parser.state.current = old; + } + if (!successExpression) { + parser.walkExpression(successExpressionArg); + } + if (errorExpression) { + if (errorExpression.fn.body.type === "BlockStatement") { + parser.walkStatement(errorExpression.fn.body); + } else { + parser.walkExpression(errorExpression.fn.body); + } + } else if (errorExpressionArg) { + parser.walkExpression(errorExpressionArg); + } + return true; + } + } + }); + } +}; + + +/***/ }), + +/***/ 27223: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + +class RequireEnsureDependency extends NullDependency { + constructor(range, contentRange, errorHandlerRange) { + super(); + + this.range = range; + this.contentRange = contentRange; + this.errorHandlerRange = errorHandlerRange; + } + + get type() { + return "require.ensure"; + } + + serialize(context) { const { write } = context; - write(this.dependencies); - write(this.name); + write(this.range); + write(this.contentRange); + write(this.errorHandlerRange); super.serialize(context); } @@ -83100,25 +82413,71 @@ class DllEntryDependency extends Dependency { deserialize(context) { const { read } = context; - this.dependencies = read(); - this.name = read(); + this.range = read(); + this.contentRange = read(); + this.errorHandlerRange = read(); super.deserialize(context); } } makeSerializable( - DllEntryDependency, - "webpack/lib/dependencies/DllEntryDependency" + RequireEnsureDependency, + "webpack/lib/dependencies/RequireEnsureDependency" ); -module.exports = DllEntryDependency; +RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, + { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } + ) { + const dep = /** @type {RequireEnsureDependency} */ (dependency); + const depBlock = /** @type {AsyncDependenciesBlock} */ ( + moduleGraph.getParentBlock(dep) + ); + const promise = runtimeTemplate.blockPromise({ + chunkGraph, + block: depBlock, + message: "require.ensure", + runtimeRequirements + }); + const range = dep.range; + const contentRange = dep.contentRange; + const errorHandlerRange = dep.errorHandlerRange; + source.replace(range[0], contentRange[0] - 1, `${promise}.then((`); + if (errorHandlerRange) { + source.replace( + contentRange[1], + errorHandlerRange[0] - 1, + ").bind(null, __webpack_require__))['catch'](" + ); + source.replace(errorHandlerRange[1], range[1] - 1, ")"); + } else { + source.replace( + contentRange[1], + range[1] - 1, + `).bind(null, __webpack_require__))['catch'](${RuntimeGlobals.uncaughtErrorHandler})` + ); + } + } +}; + +module.exports = RequireEnsureDependency; /***/ }), -/***/ 32006: -/***/ (function(__unused_webpack_module, exports) { +/***/ 50329: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -83128,73 +82487,37 @@ module.exports = DllEntryDependency; -/** @typedef {import("../Parser").ParserState} ParserState */ +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); +const NullDependency = __webpack_require__(31830); -/** @type {WeakMap} */ -const parserStateExportsState = new WeakMap(); +class RequireEnsureItemDependency extends ModuleDependency { + constructor(request) { + super(request); + } -/** - * @param {ParserState} parserState parser state - * @returns {void} - */ -exports.bailout = parserState => { - const value = parserStateExportsState.get(parserState); - parserStateExportsState.set(parserState, false); - if (value === true) { - parserState.module.buildMeta.exportsType = undefined; - parserState.module.buildMeta.defaultObject = false; + get type() { + return "require.ensure item"; } -}; -/** - * @param {ParserState} parserState parser state - * @returns {void} - */ -exports.enable = parserState => { - const value = parserStateExportsState.get(parserState); - if (value === false) return; - parserStateExportsState.set(parserState, true); - if (value !== true) { - parserState.module.buildMeta.exportsType = "default"; - parserState.module.buildMeta.defaultObject = "redirect"; + get category() { + return "commonjs"; } -}; +} -/** - * @param {ParserState} parserState parser state - * @returns {void} - */ -exports.setFlagged = parserState => { - const value = parserStateExportsState.get(parserState); - if (value !== true) return; - const buildMeta = parserState.module.buildMeta; - if (buildMeta.exportsType === "dynamic") return; - buildMeta.exportsType = "flagged"; -}; +makeSerializable( + RequireEnsureItemDependency, + "webpack/lib/dependencies/RequireEnsureItemDependency" +); -/** - * @param {ParserState} parserState parser state - * @returns {void} - */ -exports.setDynamic = parserState => { - const value = parserStateExportsState.get(parserState); - if (value !== true) return; - parserState.module.buildMeta.exportsType = "dynamic"; -}; +RequireEnsureItemDependency.Template = NullDependency.Template; -/** - * @param {ParserState} parserState parser state - * @returns {boolean} true, when enabled - */ -exports.isEnabled = parserState => { - const value = parserStateExportsState.get(parserState); - return value === true; -}; +module.exports = RequireEnsureItemDependency; /***/ }), -/***/ 3979: +/***/ 8434: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -83205,34 +82528,70 @@ exports.isEnabled = parserState => { -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); +const RequireEnsureDependency = __webpack_require__(27223); +const RequireEnsureItemDependency = __webpack_require__(50329); -class EntryDependency extends ModuleDependency { - /** - * @param {string} request request path for entry - */ - constructor(request) { - super(request); - } +const RequireEnsureDependenciesBlockParserPlugin = __webpack_require__(7235); - get type() { - return "entry"; - } +const { + evaluateToString, + toConstantDependency +} = __webpack_require__(93998); - get category() { - return "esm"; - } -} +class RequireEnsurePlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireEnsurePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireEnsureItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireEnsureItemDependency, + new RequireEnsureItemDependency.Template() + ); -makeSerializable(EntryDependency, "webpack/lib/dependencies/EntryDependency"); + compilation.dependencyTemplates.set( + RequireEnsureDependency, + new RequireEnsureDependency.Template() + ); -module.exports = EntryDependency; + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireEnsure !== undefined && + !parserOptions.requireEnsure + ) + return; + + new RequireEnsureDependenciesBlockParserPlugin().apply(parser); + parser.hooks.evaluateTypeof + .for("require.ensure") + .tap("RequireEnsurePlugin", evaluateToString("function")); + parser.hooks.typeof + .for("require.ensure") + .tap( + "RequireEnsurePlugin", + toConstantDependency(parser, JSON.stringify("function")) + ); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireEnsurePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireEnsurePlugin", handler); + } + ); + } +} +module.exports = RequireEnsurePlugin; /***/ }), -/***/ 78988: +/***/ 89183: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -83243,109 +82602,40 @@ module.exports = EntryDependency; -const { UsageState } = __webpack_require__(63686); +const RuntimeGlobals = __webpack_require__(16475); const makeSerializable = __webpack_require__(33032); const NullDependency = __webpack_require__(31830); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ /** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -/** - * @param {ModuleGraph} moduleGraph the module graph - * @param {Module} module the module - * @param {string | null} exportName name of the export if any - * @param {string | null} property name of the requested property - * @param {RuntimeSpec} runtime for which runtime - * @returns {any} value of the property - */ -const getProperty = (moduleGraph, module, exportName, property, runtime) => { - if (!exportName) { - switch (property) { - case "usedExports": { - const usedExports = moduleGraph - .getExportsInfo(module) - .getUsedExports(runtime); - if ( - typeof usedExports === "boolean" || - usedExports === undefined || - usedExports === null - ) { - return usedExports; - } - return Array.from(usedExports).sort(); - } - } - } - switch (property) { - case "used": - return ( - moduleGraph.getExportsInfo(module).getUsed(exportName, runtime) !== - UsageState.Unused - ); - case "useInfo": { - const state = moduleGraph - .getExportsInfo(module) - .getUsed(exportName, runtime); - switch (state) { - case UsageState.Used: - case UsageState.OnlyPropertiesUsed: - return true; - case UsageState.Unused: - return false; - case UsageState.NoInfo: - return undefined; - case UsageState.Unknown: - return null; - default: - throw new Error(`Unexpected UsageState ${state}`); - } - } - case "provideInfo": - return moduleGraph.getExportsInfo(module).isExportProvided(exportName); - } - return undefined; -}; -class ExportsInfoDependency extends NullDependency { - constructor(range, exportName, property) { +class RequireHeaderDependency extends NullDependency { + constructor(range) { super(); + if (!Array.isArray(range)) throw new Error("range must be valid"); this.range = range; - this.exportName = exportName; - this.property = property; } serialize(context) { const { write } = context; write(this.range); - write(this.exportName); - write(this.property); super.serialize(context); } static deserialize(context) { - const obj = new ExportsInfoDependency( - context.read(), - context.read(), - context.read() - ); + const obj = new RequireHeaderDependency(context.read()); obj.deserialize(context); return obj; } } makeSerializable( - ExportsInfoDependency, - "webpack/lib/dependencies/ExportsInfoDependency" + RequireHeaderDependency, + "webpack/lib/dependencies/RequireHeaderDependency" ); -ExportsInfoDependency.Template = class ExportsInfoDependencyTemplate extends ( +RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate extends ( NullDependency.Template ) { /** @@ -83354,30 +82644,19 @@ ExportsInfoDependency.Template = class ExportsInfoDependencyTemplate extends ( * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ - apply(dependency, source, { module, moduleGraph, runtime }) { - const dep = /** @type {ExportsInfoDependency} */ (dependency); - - const value = getProperty( - moduleGraph, - module, - dep.exportName, - dep.property, - runtime - ); - source.replace( - dep.range[0], - dep.range[1] - 1, - value === undefined ? "undefined" : JSON.stringify(value) - ); + apply(dependency, source, { runtimeRequirements }) { + const dep = /** @type {RequireHeaderDependency} */ (dependency); + runtimeRequirements.add(RuntimeGlobals.require); + source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__"); } }; -module.exports = ExportsInfoDependency; +module.exports = RequireHeaderDependency; /***/ }), -/***/ 23624: +/***/ 71284: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -83388,57 +82667,51 @@ module.exports = ExportsInfoDependency; -const Template = __webpack_require__(39722); +const Dependency = __webpack_require__(54912); +const Template = __webpack_require__(1626); const makeSerializable = __webpack_require__(33032); -const HarmonyImportDependency = __webpack_require__(57154); -const NullDependency = __webpack_require__(31830); +const ModuleDependency = __webpack_require__(80321); /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("./HarmonyAcceptImportDependency")} HarmonyAcceptImportDependency */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class RequireIncludeDependency extends ModuleDependency { + constructor(request, range) { + super(request); -class HarmonyAcceptDependency extends NullDependency { - /** - * @param {[number, number]} range expression range - * @param {HarmonyAcceptImportDependency[]} dependencies import dependencies - * @param {boolean} hasCallback true, if the range wraps an existing callback - */ - constructor(range, dependencies, hasCallback) { - super(); this.range = range; - this.dependencies = dependencies; - this.hasCallback = hasCallback; } - get type() { - return "accepted harmony modules"; + /** + * 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) { + // This doesn't use any export + return Dependency.NO_EXPORTS_REFERENCED; } - serialize(context) { - const { write } = context; - write(this.range); - write(this.dependencies); - write(this.hasCallback); - super.serialize(context); + get type() { + return "require.include"; } - deserialize(context) { - const { read } = context; - this.range = read(); - this.dependencies = read(); - this.hasCallback = read(); - super.deserialize(context); + get category() { + return "commonjs"; } } makeSerializable( - HarmonyAcceptDependency, - "webpack/lib/dependencies/HarmonyAcceptDependency" + RequireIncludeDependency, + "webpack/lib/dependencies/RequireIncludeDependency" ); -HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate extends ( - NullDependency.Template +RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate extends ( + ModuleDependency.Template ) { /** * @param {Dependency} dependency the dependency for which the template should be applied @@ -83446,80 +82719,161 @@ HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate extends * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ - apply(dependency, source, templateContext) { - const dep = /** @type {HarmonyAcceptDependency} */ (dependency); - const { - module, - runtime, - runtimeRequirements, - runtimeTemplate, - moduleGraph, - chunkGraph - } = templateContext; - const content = dep.dependencies - .map(dependency => { - const referencedModule = moduleGraph.getModule(dependency); - return { - dependency, - runtimeCondition: referencedModule - ? HarmonyImportDependency.Template.getImportEmittedRuntime( - module, - referencedModule - ) - : false - }; - }) - .filter(({ runtimeCondition }) => runtimeCondition !== false) - .map(({ dependency, runtimeCondition }) => { - const condition = runtimeTemplate.runtimeConditionExpression({ - chunkGraph, - runtime, - runtimeCondition, - runtimeRequirements - }); - const s = dependency.getImportStatement(true, templateContext); - const code = s[0] + s[1]; - if (condition !== "true") { - return `if (${condition}) {\n${Template.indent(code)}\n}\n`; + apply(dependency, source, { runtimeTemplate }) { + const dep = /** @type {RequireIncludeDependency} */ (dependency); + const comment = runtimeTemplate.outputOptions.pathinfo + ? Template.toComment( + `require.include ${runtimeTemplate.requestShortener.shorten( + dep.request + )}` + ) + : ""; + + source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`); + } +}; + +module.exports = RequireIncludeDependency; + + +/***/ }), + +/***/ 35768: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const WebpackError = __webpack_require__(53799); +const { + evaluateToString, + toConstantDependency +} = __webpack_require__(93998); +const makeSerializable = __webpack_require__(33032); +const RequireIncludeDependency = __webpack_require__(71284); + +module.exports = class RequireIncludeDependencyParserPlugin { + constructor(warn) { + this.warn = warn; + } + apply(parser) { + const { warn } = this; + parser.hooks.call + .for("require.include") + .tap("RequireIncludeDependencyParserPlugin", expr => { + if (expr.arguments.length !== 1) return; + const param = parser.evaluateExpression(expr.arguments[0]); + if (!param.isString()) return; + + if (warn) { + parser.state.module.addWarning( + new RequireIncludeDeprecationWarning(expr.loc) + ); } - return code; - }) - .join(""); - if (dep.hasCallback) { - if (runtimeTemplate.supportsArrowFunction()) { - source.insert( - dep.range[0], - `__WEBPACK_OUTDATED_DEPENDENCIES__ => { ${content}(` - ); - source.insert(dep.range[1], ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }"); - } else { - source.insert( - dep.range[0], - `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(` + const dep = new RequireIncludeDependency(param.string, expr.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }); + parser.hooks.evaluateTypeof + .for("require.include") + .tap("RequireIncludePlugin", expr => { + if (warn) { + parser.state.module.addWarning( + new RequireIncludeDeprecationWarning(expr.loc) + ); + } + return evaluateToString("function")(expr); + }); + parser.hooks.typeof + .for("require.include") + .tap("RequireIncludePlugin", expr => { + if (warn) { + parser.state.module.addWarning( + new RequireIncludeDeprecationWarning(expr.loc) + ); + } + return toConstantDependency(parser, JSON.stringify("function"))(expr); + }); + } +}; + +class RequireIncludeDeprecationWarning extends WebpackError { + constructor(loc) { + super("require.include() is deprecated and will be removed soon."); + + this.name = "RequireIncludeDeprecationWarning"; + + this.loc = loc; + } +} + +makeSerializable( + RequireIncludeDeprecationWarning, + "webpack/lib/dependencies/RequireIncludeDependencyParserPlugin", + "RequireIncludeDeprecationWarning" +); + + +/***/ }), + +/***/ 37378: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RequireIncludeDependency = __webpack_require__(71284); +const RequireIncludeDependencyParserPlugin = __webpack_require__(35768); + +class RequireIncludePlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireIncludePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireIncludeDependency, + normalModuleFactory ); - source.insert( - dep.range[1], - ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }.bind(this)" + compilation.dependencyTemplates.set( + RequireIncludeDependency, + new RequireIncludeDependency.Template() ); - } - return; - } - const arrow = runtimeTemplate.supportsArrowFunction(); - source.insert( - dep.range[1] - 0.5, - `, ${arrow ? "() =>" : "function()"} { ${content} }` + const handler = (parser, parserOptions) => { + if (parserOptions.requireInclude === false) return; + const warn = parserOptions.requireInclude === undefined; + + new RequireIncludeDependencyParserPlugin(warn).apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireIncludePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireIncludePlugin", handler); + } ); } -}; - -module.exports = HarmonyAcceptDependency; +} +module.exports = RequireIncludePlugin; /***/ }), -/***/ 99843: +/***/ 55627: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -83531,38 +82885,53 @@ module.exports = HarmonyAcceptDependency; const makeSerializable = __webpack_require__(33032); -const HarmonyImportDependency = __webpack_require__(57154); +const ContextDependency = __webpack_require__(88101); +const ContextDependencyTemplateAsId = __webpack_require__(76081); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +class RequireResolveContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); -class HarmonyAcceptImportDependency extends HarmonyImportDependency { - constructor(request) { - super(request, NaN); - this.weak = true; + this.range = range; + this.valueRange = valueRange; } get type() { - return "harmony accept"; + return "amd require context"; + } + + serialize(context) { + const { write } = context; + + write(this.range); + write(this.valueRange); + + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + + this.range = read(); + this.valueRange = read(); + + super.deserialize(context); } } makeSerializable( - HarmonyAcceptImportDependency, - "webpack/lib/dependencies/HarmonyAcceptImportDependency" + RequireResolveContextDependency, + "webpack/lib/dependencies/RequireResolveContextDependency" ); -HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate extends ( - HarmonyImportDependency.Template -) {}; +RequireResolveContextDependency.Template = ContextDependencyTemplateAsId; -module.exports = HarmonyAcceptImportDependency; +module.exports = RequireResolveContextDependency; /***/ }), -/***/ 72906: +/***/ 68582: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -83573,95 +82942,55 @@ module.exports = HarmonyAcceptImportDependency; -const { UsageState } = __webpack_require__(63686); -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); +const Dependency = __webpack_require__(54912); const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +const ModuleDependency = __webpack_require__(80321); +const ModuleDependencyAsId = __webpack_require__(80825); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class RequireResolveDependency extends ModuleDependency { + constructor(request, range) { + super(request); + + this.range = range; + } -class HarmonyCompatibilityDependency extends NullDependency { get type() { - return "harmony export header"; + return "require.resolve"; } -} -makeSerializable( - HarmonyCompatibilityDependency, - "webpack/lib/dependencies/HarmonyCompatibilityDependency" -); + get category() { + return "commonjs"; + } -HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate extends ( - NullDependency.Template -) { /** - * @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} + * 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 */ - apply( - dependency, - source, - { - module, - runtimeTemplate, - moduleGraph, - initFragments, - runtimeRequirements, - runtime, - concatenationScope - } - ) { - if (concatenationScope) return; - const exportsInfo = moduleGraph.getExportsInfo(module); - if ( - exportsInfo.getReadOnlyExportInfo("__esModule").getUsed(runtime) !== - UsageState.Unused - ) { - const content = runtimeTemplate.defineEsModuleFlagStatement({ - exportsArgument: module.exportsArgument, - runtimeRequirements - }); - initFragments.push( - new InitFragment( - content, - InitFragment.STAGE_HARMONY_EXPORTS, - 0, - "harmony compatibility" - ) - ); - } - if (moduleGraph.isAsync(module)) { - runtimeRequirements.add(RuntimeGlobals.module); - runtimeRequirements.add(RuntimeGlobals.asyncModule); - initFragments.push( - new InitFragment( - runtimeTemplate.supportsArrowFunction() - ? `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async (__webpack_handle_async_dependencies__) => {\n` - : `${RuntimeGlobals.asyncModule}(${module.moduleArgument}, async function (__webpack_handle_async_dependencies__) {\n`, - InitFragment.STAGE_ASYNC_BOUNDARY, - 0, - undefined, - module.buildMeta.async - ? `\n__webpack_handle_async_dependencies__();\n}, 1);` - : "\n});" - ) - ); - } + getReferencedExports(moduleGraph, runtime) { + // This doesn't use any export + return Dependency.NO_EXPORTS_REFERENCED; } -}; +} -module.exports = HarmonyCompatibilityDependency; +makeSerializable( + RequireResolveDependency, + "webpack/lib/dependencies/RequireResolveDependency" +); + +RequireResolveDependency.Template = ModuleDependencyAsId; + +module.exports = RequireResolveDependency; /***/ }), -/***/ 17223: +/***/ 9880: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -83672,101 +83001,67 @@ module.exports = HarmonyCompatibilityDependency; -const DynamicExports = __webpack_require__(32006); -const HarmonyCompatibilityDependency = __webpack_require__(72906); -const HarmonyExports = __webpack_require__(39211); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -module.exports = class HarmonyDetectionParserPlugin { - constructor(options) { - const { topLevelAwait = false } = options || {}; - this.topLevelAwait = topLevelAwait; +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + +class RequireResolveHeaderDependency extends NullDependency { + constructor(range) { + super(); + + if (!Array.isArray(range)) throw new Error("range must be valid"); + + this.range = range; } - apply(parser) { - parser.hooks.program.tap("HarmonyDetectionParserPlugin", ast => { - const isStrictHarmony = parser.state.module.type === "javascript/esm"; - const isHarmony = - isStrictHarmony || - ast.body.some( - statement => - statement.type === "ImportDeclaration" || - statement.type === "ExportDefaultDeclaration" || - statement.type === "ExportNamedDeclaration" || - statement.type === "ExportAllDeclaration" - ); - if (isHarmony) { - const module = parser.state.module; - const compatDep = new HarmonyCompatibilityDependency(); - compatDep.loc = { - start: { - line: -1, - column: 0 - }, - end: { - line: -1, - column: 0 - }, - index: -3 - }; - module.addPresentationalDependency(compatDep); - DynamicExports.bailout(parser.state); - HarmonyExports.enable(parser.state, isStrictHarmony); - parser.scope.isStrict = true; - } - }); + serialize(context) { + const { write } = context; - parser.hooks.topLevelAwait.tap("HarmonyDetectionParserPlugin", () => { - const module = parser.state.module; - if (!this.topLevelAwait) { - throw new Error( - "The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)" - ); - } - if (!HarmonyExports.isEnabled(parser.state)) { - throw new Error( - "Top-level-await is only supported in EcmaScript Modules" - ); - } - module.buildMeta.async = true; - }); + write(this.range); - const skipInHarmony = () => { - if (HarmonyExports.isEnabled(parser.state)) { - return true; - } - }; + super.serialize(context); + } - const nullInHarmony = () => { - if (HarmonyExports.isEnabled(parser.state)) { - return null; - } - }; + static deserialize(context) { + const obj = new RequireResolveHeaderDependency(context.read()); + obj.deserialize(context); + return obj; + } +} - const nonHarmonyIdentifiers = ["define", "exports"]; - for (const identifier of nonHarmonyIdentifiers) { - parser.hooks.evaluateTypeof - .for(identifier) - .tap("HarmonyDetectionParserPlugin", nullInHarmony); - parser.hooks.typeof - .for(identifier) - .tap("HarmonyDetectionParserPlugin", skipInHarmony); - parser.hooks.evaluate - .for(identifier) - .tap("HarmonyDetectionParserPlugin", nullInHarmony); - parser.hooks.expression - .for(identifier) - .tap("HarmonyDetectionParserPlugin", skipInHarmony); - parser.hooks.call - .for(identifier) - .tap("HarmonyDetectionParserPlugin", skipInHarmony); - } +makeSerializable( + RequireResolveHeaderDependency, + "webpack/lib/dependencies/RequireResolveHeaderDependency" +); + +RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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 dep = /** @type {RequireResolveHeaderDependency} */ (dependency); + source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + } + + applyAsTemplateArgument(name, dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); } }; +module.exports = RequireResolveHeaderDependency; + /***/ }), -/***/ 93466: +/***/ 24187: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -83777,189 +83072,81 @@ module.exports = class HarmonyDetectionParserPlugin { -const InnerGraph = __webpack_require__(38988); -const ConstDependency = __webpack_require__(76911); -const HarmonyExportExpressionDependency = __webpack_require__(51340); -const HarmonyExportHeaderDependency = __webpack_require__(38873); -const HarmonyExportImportedSpecifierDependency = __webpack_require__(67157); -const HarmonyExportSpecifierDependency = __webpack_require__(48567); -const { ExportPresenceModes } = __webpack_require__(57154); -const { - harmonySpecifierTag, - getAssertions -} = __webpack_require__(20862); -const HarmonyImportSideEffectDependency = __webpack_require__(73132); +const makeSerializable = __webpack_require__(33032); +const NullDependency = __webpack_require__(31830); -const { HarmonyStarExportsList } = HarmonyExportImportedSpecifierDependency; +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/Hash")} Hash */ -module.exports = class HarmonyExportDependencyParserPlugin { - constructor(options) { - this.exportPresenceMode = - options.reexportExportsPresence !== undefined - ? ExportPresenceModes.fromUserOption(options.reexportExportsPresence) - : options.exportsPresence !== undefined - ? ExportPresenceModes.fromUserOption(options.exportsPresence) - : options.strictExportPresence - ? ExportPresenceModes.ERROR - : ExportPresenceModes.AUTO; +class RuntimeRequirementsDependency extends NullDependency { + /** + * @param {string[]} runtimeRequirements runtime requirements + */ + constructor(runtimeRequirements) { + super(); + this.runtimeRequirements = new Set(runtimeRequirements); + this._hashUpdate = undefined; } - apply(parser) { - const { exportPresenceMode } = this; - parser.hooks.export.tap( - "HarmonyExportDependencyParserPlugin", - statement => { - const dep = new HarmonyExportHeaderDependency( - statement.declaration && statement.declaration.range, - statement.range - ); - dep.loc = Object.create(statement.loc); - dep.loc.index = -1; - parser.state.module.addPresentationalDependency(dep); - return true; - } - ); - parser.hooks.exportImport.tap( - "HarmonyExportDependencyParserPlugin", - (statement, source) => { - parser.state.lastHarmonyImportOrder = - (parser.state.lastHarmonyImportOrder || 0) + 1; - const clearDep = new ConstDependency("", statement.range); - clearDep.loc = Object.create(statement.loc); - clearDep.loc.index = -1; - parser.state.module.addPresentationalDependency(clearDep); - const sideEffectDep = new HarmonyImportSideEffectDependency( - source, - parser.state.lastHarmonyImportOrder, - getAssertions(statement) - ); - sideEffectDep.loc = Object.create(statement.loc); - sideEffectDep.loc.index = -1; - parser.state.current.addDependency(sideEffectDep); - return true; - } - ); - parser.hooks.exportExpression.tap( - "HarmonyExportDependencyParserPlugin", - (statement, expr) => { - const isFunctionDeclaration = expr.type === "FunctionDeclaration"; - const comments = parser.getComments([ - statement.range[0], - expr.range[0] - ]); - const dep = new HarmonyExportExpressionDependency( - expr.range, - statement.range, - comments - .map(c => { - switch (c.type) { - case "Block": - return `/*${c.value}*/`; - case "Line": - return `//${c.value}\n`; - } - return ""; - }) - .join(""), - expr.type.endsWith("Declaration") && expr.id - ? expr.id.name - : isFunctionDeclaration - ? { - id: expr.id ? expr.id.name : undefined, - range: [ - expr.range[0], - expr.params.length > 0 - ? expr.params[0].range[0] - : expr.body.range[0] - ], - prefix: `${expr.async ? "async " : ""}function${ - expr.generator ? "*" : "" - } `, - suffix: `(${expr.params.length > 0 ? "" : ") "}` - } - : undefined - ); - dep.loc = Object.create(statement.loc); - dep.loc.index = -1; - parser.state.current.addDependency(dep); - InnerGraph.addVariableUsage( - parser, - expr.type.endsWith("Declaration") && expr.id - ? expr.id.name - : "*default*", - "default" - ); - return true; - } - ); - parser.hooks.exportSpecifier.tap( - "HarmonyExportDependencyParserPlugin", - (statement, id, name, idx) => { - const settings = parser.getTagData(id, harmonySpecifierTag); - let dep; - const harmonyNamedExports = (parser.state.harmonyNamedExports = - parser.state.harmonyNamedExports || new Set()); - harmonyNamedExports.add(name); - InnerGraph.addVariableUsage(parser, id, name); - if (settings) { - dep = new HarmonyExportImportedSpecifierDependency( - settings.source, - settings.sourceOrder, - settings.ids, - name, - harmonyNamedExports, - null, - exportPresenceMode, - null, - settings.assertions - ); - } else { - dep = new HarmonyExportSpecifierDependency(id, name); - } - dep.loc = Object.create(statement.loc); - dep.loc.index = idx; - parser.state.current.addDependency(dep); - return true; - } - ); - parser.hooks.exportImportSpecifier.tap( - "HarmonyExportDependencyParserPlugin", - (statement, source, id, name, idx) => { - const harmonyNamedExports = (parser.state.harmonyNamedExports = - parser.state.harmonyNamedExports || new Set()); - let harmonyStarExports = null; - if (name) { - harmonyNamedExports.add(name); - } else { - harmonyStarExports = parser.state.harmonyStarExports = - parser.state.harmonyStarExports || new HarmonyStarExportsList(); - } - const dep = new HarmonyExportImportedSpecifierDependency( - source, - parser.state.lastHarmonyImportOrder, - id ? [id] : [], - name, - harmonyNamedExports, - harmonyStarExports && harmonyStarExports.slice(), - exportPresenceMode, - harmonyStarExports - ); - if (harmonyStarExports) { - harmonyStarExports.push(dep); - } - dep.loc = Object.create(statement.loc); - dep.loc.index = idx; - parser.state.current.addDependency(dep); - return true; - } - ); + /** + * Update the hash + * @param {Hash} hash hash to be updated + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + if (this._hashUpdate === undefined) { + this._hashUpdate = Array.from(this.runtimeRequirements).join() + ""; + } + hash.update(this._hashUpdate); + } + + serialize(context) { + const { write } = context; + write(this.runtimeRequirements); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.runtimeRequirements = read(); + super.deserialize(context); + } +} + +makeSerializable( + RuntimeRequirementsDependency, + "webpack/lib/dependencies/RuntimeRequirementsDependency" +); + +RuntimeRequirementsDependency.Template = class RuntimeRequirementsDependencyTemplate extends ( + NullDependency.Template +) { + /** + * @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, { runtimeRequirements }) { + const dep = /** @type {RuntimeRequirementsDependency} */ (dependency); + for (const req of dep.runtimeRequirements) { + runtimeRequirements.add(req); + } } }; +module.exports = RuntimeRequirementsDependency; + /***/ }), -/***/ 51340: +/***/ 91418: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -83970,30 +83157,29 @@ module.exports = class HarmonyExportDependencyParserPlugin { -const ConcatenationScope = __webpack_require__(98229); -const RuntimeGlobals = __webpack_require__(16475); const makeSerializable = __webpack_require__(33032); -const HarmonyExportInitFragment = __webpack_require__(89500); const NullDependency = __webpack_require__(31830); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ExportSpec} ExportSpec */ /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/Hash")} Hash */ -class HarmonyExportExpressionDependency extends NullDependency { - constructor(range, rangeStatement, prefix, declarationId) { +class StaticExportsDependency extends NullDependency { + /** + * @param {string[] | true} exports export names + * @param {boolean} canMangle true, if mangling exports names is allowed + */ + constructor(exports, canMangle) { super(); - this.range = range; - this.rangeStatement = rangeStatement; - this.prefix = prefix; - this.declarationId = declarationId; + this.exports = exports; + this.canMangle = canMangle; } get type() { - return "harmony export expression"; + return "static exports"; } /** @@ -84003,48 +83189,325 @@ class HarmonyExportExpressionDependency extends NullDependency { */ getExports(moduleGraph) { return { - exports: ["default"], - priority: 1, - terminalBinding: true, + exports: this.exports, + canMangle: this.canMangle, dependencies: undefined }; } + serialize(context) { + const { write } = context; + write(this.exports); + write(this.canMangle); + super.serialize(context); + } + + deserialize(context) { + const { read } = context; + this.exports = read(); + this.canMangle = read(); + super.deserialize(context); + } +} + +makeSerializable( + StaticExportsDependency, + "webpack/lib/dependencies/StaticExportsDependency" +); + +module.exports = StaticExportsDependency; + + +/***/ }), + +/***/ 97981: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const WebpackError = __webpack_require__(53799); +const { + evaluateToString, + expressionIsUnsupported, + toConstantDependency +} = __webpack_require__(93998); +const makeSerializable = __webpack_require__(33032); +const ConstDependency = __webpack_require__(76911); +const SystemRuntimeModule = __webpack_require__(85439); + +/** @typedef {import("../Compiler")} Compiler */ + +class SystemPlugin { /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - getModuleEvaluationSideEffectsState(moduleGraph) { - // The expression/declaration is already covered by SideEffectsFlagPlugin - return false; + apply(compiler) { + compiler.hooks.compilation.tap( + "SystemPlugin", + (compilation, { normalModuleFactory }) => { + compilation.hooks.runtimeRequirementInModule + .for(RuntimeGlobals.system) + .tap("SystemPlugin", (module, set) => { + set.add(RuntimeGlobals.requireScope); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.system) + .tap("SystemPlugin", (chunk, set) => { + compilation.addRuntimeModule(chunk, new SystemRuntimeModule()); + }); + + const handler = (parser, parserOptions) => { + if (parserOptions.system === undefined || !parserOptions.system) { + return; + } + + const setNotSupported = name => { + parser.hooks.evaluateTypeof + .for(name) + .tap("SystemPlugin", evaluateToString("undefined")); + parser.hooks.expression + .for(name) + .tap( + "SystemPlugin", + expressionIsUnsupported( + parser, + name + " is not supported by webpack." + ) + ); + }; + + parser.hooks.typeof + .for("System.import") + .tap( + "SystemPlugin", + toConstantDependency(parser, JSON.stringify("function")) + ); + parser.hooks.evaluateTypeof + .for("System.import") + .tap("SystemPlugin", evaluateToString("function")); + parser.hooks.typeof + .for("System") + .tap( + "SystemPlugin", + toConstantDependency(parser, JSON.stringify("object")) + ); + parser.hooks.evaluateTypeof + .for("System") + .tap("SystemPlugin", evaluateToString("object")); + + setNotSupported("System.set"); + setNotSupported("System.get"); + setNotSupported("System.register"); + + parser.hooks.expression.for("System").tap("SystemPlugin", expr => { + const dep = new ConstDependency(RuntimeGlobals.system, expr.range, [ + RuntimeGlobals.system + ]); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }); + + parser.hooks.call.for("System.import").tap("SystemPlugin", expr => { + parser.state.module.addWarning( + new SystemImportDeprecationWarning(expr.loc) + ); + + return parser.hooks.importCall.call({ + type: "ImportExpression", + source: expr.arguments[0], + loc: expr.loc, + range: expr.range + }); + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("SystemPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("SystemPlugin", handler); + } + ); + } +} + +class SystemImportDeprecationWarning extends WebpackError { + constructor(loc) { + super( + "System.import() is deprecated and will be removed soon. Use import() instead.\n" + + "For more info visit https://webpack.js.org/guides/code-splitting/" + ); + + this.name = "SystemImportDeprecationWarning"; + + this.loc = loc; + } +} + +makeSerializable( + SystemImportDeprecationWarning, + "webpack/lib/dependencies/SystemPlugin", + "SystemImportDeprecationWarning" +); + +module.exports = SystemPlugin; +module.exports.SystemImportDeprecationWarning = SystemImportDeprecationWarning; + + +/***/ }), + +/***/ 85439: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Florent Cailhol @ooflorent +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); + +class SystemRuntimeModule extends RuntimeModule { + constructor() { + super("system"); + } + + /** + * @returns {string} runtime code + */ + generate() { + return Template.asString([ + `${RuntimeGlobals.system} = {`, + Template.indent([ + "import: function () {", + Template.indent( + "throw new Error('System.import cannot be used indirectly');" + ), + "}" + ]), + "};" + ]); + } +} + +module.exports = SystemRuntimeModule; + + +/***/ }), + +/***/ 58612: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const { + getDependencyUsedByExportsCondition +} = __webpack_require__(38988); +const makeSerializable = __webpack_require__(33032); +const memoize = __webpack_require__(78676); +const ModuleDependency = __webpack_require__(80321); + +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +const getRawDataUrlModule = memoize(() => __webpack_require__(19684)); + +class URLDependency extends ModuleDependency { + /** + * @param {string} request request + * @param {[number, number]} range range of the arguments of new URL( |> ... <| ) + * @param {[number, number]} outerRange range of the full |> new URL(...) <| + * @param {boolean=} relative use relative urls instead of absolute with base uri + */ + constructor(request, range, outerRange, relative) { + super(request); + this.range = range; + this.outerRange = outerRange; + this.relative = relative || false; + /** @type {Set | boolean} */ + this.usedByExports = undefined; + } + + get type() { + return "new URL()"; + } + + get category() { + return "url"; + } + + /** + * @param {ModuleGraph} moduleGraph module graph + * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active + */ + getCondition(moduleGraph) { + return getDependencyUsedByExportsCondition( + this, + this.usedByExports, + moduleGraph + ); + } + + /** + * @param {string} context context directory + * @returns {Module} a module + */ + createIgnoredModule(context) { + const RawDataUrlModule = getRawDataUrlModule(); + return new RawDataUrlModule("data:,", `ignored-asset`, `(ignored asset)`); } serialize(context) { const { write } = context; - write(this.range); - write(this.rangeStatement); - write(this.prefix); - write(this.declarationId); + write(this.outerRange); + write(this.relative); + write(this.usedByExports); super.serialize(context); } deserialize(context) { const { read } = context; - this.range = read(); - this.rangeStatement = read(); - this.prefix = read(); - this.declarationId = read(); + this.outerRange = read(); + this.relative = read(); + this.usedByExports = read(); super.deserialize(context); } } -makeSerializable( - HarmonyExportExpressionDependency, - "webpack/lib/dependencies/HarmonyExportExpressionDependency" -); - -HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTemplate extends ( - NullDependency.Template +URLDependency.Template = class URLDependencyTemplate extends ( + ModuleDependency.Template ) { /** * @param {Dependency} dependency the dependency for which the template should be applied @@ -84052,112 +83515,191 @@ HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTempla * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ - apply( - dependency, - source, - { - module, + apply(dependency, source, templateContext) { + const { + chunkGraph, moduleGraph, - runtimeTemplate, runtimeRequirements, - initFragments, - runtime, - concatenationScope + runtimeTemplate, + runtime + } = templateContext; + const dep = /** @type {URLDependency} */ (dependency); + const connection = moduleGraph.getConnection(dep); + // Skip rendering depending when dependency is conditional + if (connection && !connection.isTargetActive(runtime)) { + source.replace( + dep.outerRange[0], + dep.outerRange[1] - 1, + "/* unused asset import */ undefined" + ); + return; } - ) { - const dep = /** @type {HarmonyExportExpressionDependency} */ (dependency); - const { declarationId } = dep; - const exportsName = module.exportsArgument; - if (declarationId) { - let name; - if (typeof declarationId === "string") { - name = declarationId; - } else { - name = ConcatenationScope.DEFAULT_EXPORT; - source.replace( - declarationId.range[0], - declarationId.range[1] - 1, - `${declarationId.prefix}${name}${declarationId.suffix}` - ); - } - if (concatenationScope) { - concatenationScope.registerExport("default", name); - } else { - const used = moduleGraph - .getExportsInfo(module) - .getUsedName("default", runtime); - if (used) { - const map = new Map(); - map.set(used, `/* export default binding */ ${name}`); - initFragments.push(new HarmonyExportInitFragment(exportsName, map)); - } - } + runtimeRequirements.add(RuntimeGlobals.require); + if (dep.relative) { + runtimeRequirements.add(RuntimeGlobals.relativeUrl); source.replace( - dep.rangeStatement[0], - dep.range[0] - 1, - `/* harmony default export */ ${dep.prefix}` + dep.outerRange[0], + dep.outerRange[1] - 1, + `/* asset import */ new ${ + RuntimeGlobals.relativeUrl + }(${runtimeTemplate.moduleRaw({ + chunkGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + runtimeRequirements, + weak: false + })})` ); } else { - let content; - const name = ConcatenationScope.DEFAULT_EXPORT; - if (runtimeTemplate.supportsConst()) { - content = `/* harmony default export */ const ${name} = `; - if (concatenationScope) { - concatenationScope.registerExport("default", name); - } else { - const used = moduleGraph - .getExportsInfo(module) - .getUsedName("default", runtime); - if (used) { - runtimeRequirements.add(RuntimeGlobals.exports); - const map = new Map(); - map.set(used, name); - initFragments.push(new HarmonyExportInitFragment(exportsName, map)); - } else { - content = `/* unused harmony default export */ var ${name} = `; - } - } - } else if (concatenationScope) { - content = `/* harmony default export */ var ${name} = `; - concatenationScope.registerExport("default", name); - } else { - const used = moduleGraph - .getExportsInfo(module) - .getUsedName("default", runtime); - if (used) { - runtimeRequirements.add(RuntimeGlobals.exports); - // This is a little bit incorrect as TDZ is not correct, but we can't use const. - content = `/* harmony default export */ ${exportsName}[${JSON.stringify( - used - )}] = `; - } else { - content = `/* unused harmony default export */ var ${name} = `; - } - } - - if (dep.range) { - source.replace( - dep.rangeStatement[0], - dep.range[0] - 1, - content + "(" + dep.prefix - ); - source.replace(dep.range[1], dep.rangeStatement[1] - 0.5, ");"); - return; - } + runtimeRequirements.add(RuntimeGlobals.baseURI); - source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); + source.replace( + dep.range[0], + dep.range[1] - 1, + `/* asset import */ ${runtimeTemplate.moduleRaw({ + chunkGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + runtimeRequirements, + weak: false + })}, ${RuntimeGlobals.baseURI}` + ); } } }; -module.exports = HarmonyExportExpressionDependency; +makeSerializable(URLDependency, "webpack/lib/dependencies/URLDependency"); + +module.exports = URLDependency; /***/ }), -/***/ 38873: +/***/ 14412: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +const { approve } = __webpack_require__(93998); +const InnerGraph = __webpack_require__(38988); +const URLDependency = __webpack_require__(58612); + +/** @typedef {import("estree").NewExpression} NewExpressionNode */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ + +class URLPlugin { + /** + * @param {Compiler} compiler compiler + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "URLPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(URLDependency, normalModuleFactory); + compilation.dependencyTemplates.set( + URLDependency, + new URLDependency.Template() + ); + + /** + * @param {JavascriptParser} parser parser + * @param {object} parserOptions options + */ + const parserCallback = (parser, parserOptions) => { + if (parserOptions.url === false) return; + const relative = parserOptions.url === "relative"; + + /** + * @param {NewExpressionNode} expr expression + * @returns {undefined | string} request + */ + const getUrlRequest = expr => { + if (expr.arguments.length !== 2) return; + + const [arg1, arg2] = expr.arguments; + + if ( + arg2.type !== "MemberExpression" || + arg1.type === "SpreadElement" + ) + return; + + const chain = parser.extractMemberExpressionChain(arg2); + + if ( + chain.members.length !== 1 || + chain.object.type !== "MetaProperty" || + chain.object.meta.name !== "import" || + chain.object.property.name !== "meta" || + chain.members[0] !== "url" + ) + return; + + const request = parser.evaluateExpression(arg1).asString(); + + return request; + }; + + parser.hooks.canRename.for("URL").tap("URLPlugin", approve); + parser.hooks.new.for("URL").tap("URLPlugin", _expr => { + const expr = /** @type {NewExpressionNode} */ (_expr); + + const request = getUrlRequest(expr); + + if (!request) return; + + const [arg1, arg2] = expr.arguments; + const dep = new URLDependency( + request, + [arg1.range[0], arg2.range[1]], + expr.range, + relative + ); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); + return true; + }); + parser.hooks.isPure.for("NewExpression").tap("URLPlugin", _expr => { + const expr = /** @type {NewExpressionNode} */ (_expr); + const { callee } = expr; + if (callee.type !== "Identifier") return; + const calleeInfo = parser.getFreeInfoFromVariable(callee.name); + if (!calleeInfo || calleeInfo.name !== "URL") return; + + const request = getUrlRequest(expr); + + if (request) return true; + }); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("URLPlugin", parserCallback); + + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("URLPlugin", parserCallback); + } + ); + } +} + +module.exports = URLPlugin; + + +/***/ }), + +/***/ 51669: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -84175,38 +83717,39 @@ const NullDependency = __webpack_require__(31830); /** @typedef {import("../Dependency")} Dependency */ /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -class HarmonyExportHeaderDependency extends NullDependency { - constructor(range, rangeStatement) { +class UnsupportedDependency extends NullDependency { + constructor(request, range) { super(); - this.range = range; - this.rangeStatement = rangeStatement; - } - get type() { - return "harmony export header"; + this.request = request; + this.range = range; } serialize(context) { const { write } = context; + + write(this.request); write(this.range); - write(this.rangeStatement); + super.serialize(context); } deserialize(context) { const { read } = context; + + this.request = read(); this.range = read(); - this.rangeStatement = read(); + super.deserialize(context); } } makeSerializable( - HarmonyExportHeaderDependency, - "webpack/lib/dependencies/HarmonyExportHeaderDependency" + UnsupportedDependency, + "webpack/lib/dependencies/UnsupportedDependency" ); -HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate extends ( +UnsupportedDependency.Template = class UnsupportedDependencyTemplate extends ( NullDependency.Template ) { /** @@ -84215,22 +83758,25 @@ HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate e * @param {DependencyTemplateContext} templateContext the context object * @returns {void} */ - apply(dependency, source, templateContext) { - const dep = /** @type {HarmonyExportHeaderDependency} */ (dependency); - const content = ""; - const replaceUntil = dep.range - ? dep.range[0] - 1 - : dep.rangeStatement[1] - 1; - source.replace(dep.rangeStatement[0], replaceUntil, content); + apply(dependency, source, { runtimeTemplate }) { + const dep = /** @type {UnsupportedDependency} */ (dependency); + + source.replace( + dep.range[0], + dep.range[1], + runtimeTemplate.missingModule({ + request: dep.request + }) + ); } }; -module.exports = HarmonyExportHeaderDependency; +module.exports = UnsupportedDependency; /***/ }), -/***/ 67157: +/***/ 52204: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -84242,508 +83788,218 @@ module.exports = HarmonyExportHeaderDependency; const Dependency = __webpack_require__(54912); -const { UsageState } = __webpack_require__(63686); -const HarmonyLinkingError = __webpack_require__(97511); -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const { countIterable } = __webpack_require__(39104); -const { first, combine } = __webpack_require__(93347); const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const { getRuntimeKey, keyToRuntime } = __webpack_require__(17156); -const HarmonyExportInitFragment = __webpack_require__(89500); -const HarmonyImportDependency = __webpack_require__(57154); -const processExportInfo = __webpack_require__(55207); +const ModuleDependency = __webpack_require__(80321); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ExportsInfo")} ExportsInfo */ -/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ -/** @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 {"missing"|"unused"|"empty-star"|"reexport-dynamic-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-fake-namespace-object"|"reexport-undefined"|"normal-reexport"|"dynamic-reexport"} ExportModeType */ - -const { ExportPresenceModes } = HarmonyImportDependency; - -const idsSymbol = Symbol("HarmonyExportImportedSpecifierDependency.ids"); +class WebAssemblyExportImportedDependency extends ModuleDependency { + constructor(exportName, request, name, valueType) { + super(request); + /** @type {string} */ + this.exportName = exportName; + /** @type {string} */ + this.name = name; + /** @type {string} */ + this.valueType = valueType; + } -class NormalReexportItem { /** - * @param {string} name export name - * @param {string[]} ids reexported ids from other module - * @param {ExportInfo} exportInfo export info from other module - * @param {boolean} checked true, if it should be checked at runtime if this export exists - * @param {boolean} hidden true, if it is hidden behind another active export in the same module + * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module */ - constructor(name, ids, exportInfo, checked, hidden) { - this.name = name; - this.ids = ids; - this.exportInfo = exportInfo; - this.checked = checked; - this.hidden = hidden; + couldAffectReferencingModule() { + return Dependency.TRANSITIVE; } -} -class ExportMode { /** - * @param {ExportModeType} type type of the mode + * 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 */ - constructor(type) { - /** @type {ExportModeType} */ - this.type = type; - - // for "normal-reexport": - /** @type {NormalReexportItem[] | null} */ - this.items = null; + getReferencedExports(moduleGraph, runtime) { + return [[this.name]]; + } - // for "reexport-named-default" | "reexport-fake-namespace-object" | "reexport-namespace-object" - /** @type {string|null} */ - this.name = null; - /** @type {ExportInfo | null} */ - this.partialNamespaceExportInfo = null; + get type() { + return "wasm export import"; + } - // for "dynamic-reexport": - /** @type {Set | null} */ - this.ignored = null; + get category() { + return "wasm"; + } - // for "dynamic-reexport" | "empty-star": - /** @type {Set | null} */ - this.hidden = null; + serialize(context) { + const { write } = context; - // for "missing": - /** @type {string | null} */ - this.userRequest = null; + write(this.exportName); + write(this.name); + write(this.valueType); - // for "reexport-fake-namespace-object": - /** @type {number} */ - this.fakeType = 0; + super.serialize(context); } -} -const determineExportAssignments = ( - moduleGraph, - dependencies, - additionalDependency -) => { - const names = new Set(); - const dependencyIndices = []; + deserialize(context) { + const { read } = context; - if (additionalDependency) { - dependencies = dependencies.concat(additionalDependency); - } + this.exportName = read(); + this.name = read(); + this.valueType = read(); - for (const dep of dependencies) { - const i = dependencyIndices.length; - dependencyIndices[i] = names.size; - const otherImportedModule = moduleGraph.getModule(dep); - if (otherImportedModule) { - const exportsInfo = moduleGraph.getExportsInfo(otherImportedModule); - for (const exportInfo of exportsInfo.exports) { - if ( - exportInfo.provided === true && - exportInfo.name !== "default" && - !names.has(exportInfo.name) - ) { - names.add(exportInfo.name); - dependencyIndices[i] = names.size; - } - } - } + super.deserialize(context); } - dependencyIndices.push(names.size); - - return { names: Array.from(names), dependencyIndices }; -}; +} -const findDependencyForName = ( - { names, dependencyIndices }, - name, - dependencies -) => { - const dependenciesIt = dependencies[Symbol.iterator](); - const dependencyIndicesIt = dependencyIndices[Symbol.iterator](); - let dependenciesItResult = dependenciesIt.next(); - let dependencyIndicesItResult = dependencyIndicesIt.next(); - if (dependencyIndicesItResult.done) return; - for (let i = 0; i < names.length; i++) { - while (i >= dependencyIndicesItResult.value) { - dependenciesItResult = dependenciesIt.next(); - dependencyIndicesItResult = dependencyIndicesIt.next(); - if (dependencyIndicesItResult.done) return; - } - if (names[i] === name) return dependenciesItResult.value; - } - return undefined; -}; - -/** - * @param {ModuleGraph} moduleGraph the module graph - * @param {HarmonyExportImportedSpecifierDependency} dep the dependency - * @param {string} runtimeKey the runtime key - * @returns {ExportMode} the export mode - */ -const getMode = (moduleGraph, dep, runtimeKey) => { - const importedModule = moduleGraph.getModule(dep); - - if (!importedModule) { - const mode = new ExportMode("missing"); - - mode.userRequest = dep.userRequest; - - return mode; - } - - const name = dep.name; - const runtime = keyToRuntime(runtimeKey); - const parentModule = moduleGraph.getParentModule(dep); - const exportsInfo = moduleGraph.getExportsInfo(parentModule); - - if ( - name - ? exportsInfo.getUsed(name, runtime) === UsageState.Unused - : exportsInfo.isUsed(runtime) === false - ) { - const mode = new ExportMode("unused"); - - mode.name = name || "*"; - - return mode; - } - - const importedExportsType = importedModule.getExportsType( - moduleGraph, - parentModule.buildMeta.strictHarmonyModule - ); - - const ids = dep.getIds(moduleGraph); - - // Special handling for reexporting the default export - // from non-namespace modules - if (name && ids.length > 0 && ids[0] === "default") { - switch (importedExportsType) { - case "dynamic": { - const mode = new ExportMode("reexport-dynamic-default"); - - mode.name = name; +makeSerializable( + WebAssemblyExportImportedDependency, + "webpack/lib/dependencies/WebAssemblyExportImportedDependency" +); - return mode; - } - case "default-only": - case "default-with-named": { - const exportInfo = exportsInfo.getReadOnlyExportInfo(name); - const mode = new ExportMode("reexport-named-default"); +module.exports = WebAssemblyExportImportedDependency; - mode.name = name; - mode.partialNamespaceExportInfo = exportInfo; - return mode; - } - } - } +/***/ }), - // reexporting with a fixed name - if (name) { - let mode; - const exportInfo = exportsInfo.getReadOnlyExportInfo(name); +/***/ 5239: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (ids.length > 0) { - // export { name as name } - switch (importedExportsType) { - case "default-only": - mode = new ExportMode("reexport-undefined"); - mode.name = name; - break; - default: - mode = new ExportMode("normal-reexport"); - mode.items = [ - new NormalReexportItem(name, ids, exportInfo, false, false) - ]; - break; - } - } else { - // export * as name - switch (importedExportsType) { - case "default-only": - mode = new ExportMode("reexport-fake-namespace-object"); - mode.name = name; - mode.partialNamespaceExportInfo = exportInfo; - mode.fakeType = 0; - break; - case "default-with-named": - mode = new ExportMode("reexport-fake-namespace-object"); - mode.name = name; - mode.partialNamespaceExportInfo = exportInfo; - mode.fakeType = 2; - break; - case "dynamic": - default: - mode = new ExportMode("reexport-namespace-object"); - mode.name = name; - mode.partialNamespaceExportInfo = exportInfo; - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - return mode; - } - // Star reexporting - const { ignoredExports, exports, checked, hidden } = dep.getStarReexports( - moduleGraph, - runtime, - exportsInfo, - importedModule - ); - if (!exports) { - // We have too few info about the modules - // Delegate the logic to the runtime code +const makeSerializable = __webpack_require__(33032); +const UnsupportedWebAssemblyFeatureError = __webpack_require__(78455); +const ModuleDependency = __webpack_require__(80321); - const mode = new ExportMode("dynamic-reexport"); - mode.ignored = ignoredExports; - mode.hidden = hidden; +/** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - return mode; +class WebAssemblyImportDependency extends ModuleDependency { + /** + * @param {string} request the request + * @param {string} name the imported name + * @param {ModuleImportDescription} description the WASM ast node + * @param {false | string} onlyDirectImport if only direct imports are allowed + */ + constructor(request, name, description, onlyDirectImport) { + super(request); + /** @type {string} */ + this.name = name; + /** @type {ModuleImportDescription} */ + this.description = description; + /** @type {false | string} */ + this.onlyDirectImport = onlyDirectImport; } - if (exports.size === 0) { - const mode = new ExportMode("empty-star"); - mode.hidden = hidden; - - return mode; + get type() { + return "wasm import"; } - const mode = new ExportMode("normal-reexport"); - - mode.items = Array.from( - exports, - exportName => - new NormalReexportItem( - exportName, - [exportName], - exportsInfo.getReadOnlyExportInfo(exportName), - checked.has(exportName), - false - ) - ); - if (hidden !== undefined) { - for (const exportName of hidden) { - mode.items.push( - new NormalReexportItem( - exportName, - [exportName], - exportsInfo.getReadOnlyExportInfo(exportName), - false, - true - ) - ); - } + get category() { + return "wasm"; } - return mode; -}; - -class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { /** - * @param {string} request the request string - * @param {number} sourceOrder the order in the original source file - * @param {string[]} ids the requested export name of the imported module - * @param {string | null} name the export name of for this module - * @param {Set} activeExports other named exports in the module - * @param {ReadonlyArray | Iterable} otherStarExports other star exports in the module before this import - * @param {number} exportPresenceMode mode of checking export names - * @param {HarmonyStarExportsList} allStarExports all star exports in the module - * @param {Record=} assertions import assertions + * 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 */ - constructor( - request, - sourceOrder, - ids, - name, - activeExports, - otherStarExports, - exportPresenceMode, - allStarExports, - assertions - ) { - super(request, sourceOrder, assertions); - - this.ids = ids; - this.name = name; - this.activeExports = activeExports; - this.otherStarExports = otherStarExports; - this.exportPresenceMode = exportPresenceMode; - this.allStarExports = allStarExports; + getReferencedExports(moduleGraph, runtime) { + return [[this.name]]; } /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + * Returns errors + * @param {ModuleGraph} moduleGraph module graph + * @returns {WebpackError[]} errors */ - couldAffectReferencingModule() { - return Dependency.TRANSITIVE; - } + getErrors(moduleGraph) { + const module = moduleGraph.getModule(this); - // TODO webpack 6 remove - get id() { - throw new Error("id was renamed to ids and type changed to string[]"); + if ( + this.onlyDirectImport && + module && + !module.type.startsWith("webassembly") + ) { + return [ + new UnsupportedWebAssemblyFeatureError( + `Import "${this.name}" from "${this.request}" with ${this.onlyDirectImport} can only be used for direct wasm to wasm dependencies` + ) + ]; + } } - // TODO webpack 6 remove - getId() { - throw new Error("id was renamed to ids and type changed to string[]"); - } + serialize(context) { + const { write } = context; - // TODO webpack 6 remove - setId() { - throw new Error("id was renamed to ids and type changed to string[]"); - } + write(this.name); + write(this.description); + write(this.onlyDirectImport); - get type() { - return "harmony export imported specifier"; + super.serialize(context); } - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {string[]} the imported id - */ - getIds(moduleGraph) { - return moduleGraph.getMeta(this)[idsSymbol] || this.ids; - } + deserialize(context) { + const { read } = context; - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {string[]} ids the imported ids - * @returns {void} - */ - setIds(moduleGraph, ids) { - moduleGraph.getMeta(this)[idsSymbol] = ids; - } + this.name = read(); + this.description = read(); + this.onlyDirectImport = read(); - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {RuntimeSpec} runtime the runtime - * @returns {ExportMode} the export mode - */ - getMode(moduleGraph, runtime) { - return moduleGraph.dependencyCacheProvide( - this, - getRuntimeKey(runtime), - getMode - ); + super.deserialize(context); } +} - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {RuntimeSpec} runtime the runtime - * @param {ExportsInfo} exportsInfo exports info about the current module (optional) - * @param {Module} importedModule the imported module (optional) - * @returns {{exports?: Set, checked?: Set, ignoredExports: Set, hidden?: Set}} information - */ - getStarReexports( - moduleGraph, - runtime, - exportsInfo = moduleGraph.getExportsInfo(moduleGraph.getParentModule(this)), - importedModule = moduleGraph.getModule(this) - ) { - const importedExportsInfo = moduleGraph.getExportsInfo(importedModule); +makeSerializable( + WebAssemblyImportDependency, + "webpack/lib/dependencies/WebAssemblyImportDependency" +); - const noExtraExports = - importedExportsInfo.otherExportsInfo.provided === false; - const noExtraImports = - exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused; +module.exports = WebAssemblyImportDependency; - const ignoredExports = new Set(["default", ...this.activeExports]); - let hiddenExports = undefined; - const otherStarExports = - this._discoverActiveExportsFromOtherStarExports(moduleGraph); - if (otherStarExports !== undefined) { - hiddenExports = new Set(); - for (let i = 0; i < otherStarExports.namesSlice; i++) { - hiddenExports.add(otherStarExports.names[i]); - } - for (const e of ignoredExports) hiddenExports.delete(e); - } +/***/ }), - if (!noExtraExports && !noExtraImports) { - return { - ignoredExports, - hidden: hiddenExports - }; - } +/***/ 26505: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {Set} */ - const exports = new Set(); - /** @type {Set} */ - const checked = new Set(); - /** @type {Set} */ - const hidden = hiddenExports !== undefined ? new Set() : undefined; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - if (noExtraImports) { - for (const exportInfo of exportsInfo.orderedExports) { - const name = exportInfo.name; - if (ignoredExports.has(name)) continue; - if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; - const importedExportInfo = - importedExportsInfo.getReadOnlyExportInfo(name); - if (importedExportInfo.provided === false) continue; - if (hiddenExports !== undefined && hiddenExports.has(name)) { - hidden.add(name); - continue; - } - exports.add(name); - if (importedExportInfo.provided === true) continue; - checked.add(name); - } - } else if (noExtraExports) { - for (const importedExportInfo of importedExportsInfo.orderedExports) { - const name = importedExportInfo.name; - if (ignoredExports.has(name)) continue; - if (importedExportInfo.provided === false) continue; - const exportInfo = exportsInfo.getReadOnlyExportInfo(name); - if (exportInfo.getUsed(runtime) === UsageState.Unused) continue; - if (hiddenExports !== undefined && hiddenExports.has(name)) { - hidden.add(name); - continue; - } - exports.add(name); - if (importedExportInfo.provided === true) continue; - checked.add(name); - } - } - return { ignoredExports, exports, checked, hidden }; - } - /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active - */ - getCondition(moduleGraph) { - return (connection, runtime) => { - const mode = this.getMode(moduleGraph, runtime); - return mode.type !== "unused" && mode.type !== "empty-star"; - }; - } +const Dependency = __webpack_require__(54912); +const Template = __webpack_require__(1626); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules - */ - getModuleEvaluationSideEffectsState(moduleGraph) { - return false; +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +class WebpackIsIncludedDependency extends ModuleDependency { + constructor(request, range) { + super(request); + + this.weak = true; + this.range = range; } /** @@ -84753,763 +84009,714 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { * @returns {(string[] | ReferencedExport)[]} referenced exports */ getReferencedExports(moduleGraph, runtime) { - const mode = this.getMode(moduleGraph, runtime); + // This doesn't use any export + return Dependency.NO_EXPORTS_REFERENCED; + } - switch (mode.type) { - case "missing": - case "unused": - case "empty-star": - case "reexport-undefined": - return Dependency.NO_EXPORTS_REFERENCED; + get type() { + return "__webpack_is_included__"; + } +} - case "reexport-dynamic-default": - return Dependency.EXPORTS_OBJECT_REFERENCED; +makeSerializable( + WebpackIsIncludedDependency, + "webpack/lib/dependencies/WebpackIsIncludedDependency" +); - case "reexport-named-default": { - if (!mode.partialNamespaceExportInfo) - return Dependency.EXPORTS_OBJECT_REFERENCED; - /** @type {string[][]} */ - const referencedExports = []; - processExportInfo( - runtime, - referencedExports, - [], - /** @type {ExportInfo} */ (mode.partialNamespaceExportInfo) - ); - return referencedExports; - } +WebpackIsIncludedDependency.Template = class WebpackIsIncludedDependencyTemplate extends ( + ModuleDependency.Template +) { + /** + * @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, { runtimeTemplate, chunkGraph, moduleGraph }) { + const dep = /** @type {WebpackIsIncludedDependency} */ (dependency); + const connection = moduleGraph.getConnection(dep); + const included = connection + ? chunkGraph.getNumberOfModuleChunks(connection.module) > 0 + : false; + const comment = runtimeTemplate.outputOptions.pathinfo + ? Template.toComment( + `__webpack_is_included__ ${runtimeTemplate.requestShortener.shorten( + dep.request + )}` + ) + : ""; - case "reexport-namespace-object": - case "reexport-fake-namespace-object": { - if (!mode.partialNamespaceExportInfo) - return Dependency.EXPORTS_OBJECT_REFERENCED; - /** @type {string[][]} */ - const referencedExports = []; - processExportInfo( - runtime, - referencedExports, - [], - /** @type {ExportInfo} */ (mode.partialNamespaceExportInfo), - mode.type === "reexport-fake-namespace-object" - ); - return referencedExports; - } + source.replace( + dep.range[0], + dep.range[1] - 1, + `${comment}${JSON.stringify(included)}` + ); + } +}; - case "dynamic-reexport": - return Dependency.EXPORTS_OBJECT_REFERENCED; +module.exports = WebpackIsIncludedDependency; - case "normal-reexport": { - const referencedExports = []; - for (const { ids, exportInfo, hidden } of mode.items) { - if (hidden) continue; - processExportInfo(runtime, referencedExports, ids, exportInfo, false); - } - return referencedExports; - } - default: - throw new Error(`Unknown mode ${mode.type}`); - } - } +/***/ }), - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {{ names: string[], namesSlice: number, dependencyIndices: number[], dependencyIndex: number } | undefined} exported names and their origin dependency - */ - _discoverActiveExportsFromOtherStarExports(moduleGraph) { - if (!this.otherStarExports) return undefined; +/***/ 1466: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const i = - "length" in this.otherStarExports - ? this.otherStarExports.length - : countIterable(this.otherStarExports); - if (i === 0) return undefined; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - if (this.allStarExports) { - const { names, dependencyIndices } = moduleGraph.cached( - determineExportAssignments, - this.allStarExports.dependencies - ); - return { - names, - namesSlice: dependencyIndices[i - 1], - dependencyIndices, - dependencyIndex: i - }; - } - const { names, dependencyIndices } = moduleGraph.cached( - determineExportAssignments, - this.otherStarExports, - this - ); +const Dependency = __webpack_require__(54912); +const RuntimeGlobals = __webpack_require__(16475); +const makeSerializable = __webpack_require__(33032); +const ModuleDependency = __webpack_require__(80321); - return { - names, - namesSlice: dependencyIndices[i - 1], - dependencyIndices, - dependencyIndex: i - }; - } +/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ +/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Entrypoint")} Entrypoint */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +class WorkerDependency extends ModuleDependency { /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names + * @param {string} request request + * @param {[number, number]} range range */ - getExports(moduleGraph) { - const mode = this.getMode(moduleGraph, undefined); - - switch (mode.type) { - case "missing": - return undefined; - case "dynamic-reexport": { - const from = moduleGraph.getConnection(this); - return { - exports: true, - from, - canMangle: false, - excludeExports: mode.hidden - ? combine(mode.ignored, mode.hidden) - : mode.ignored, - hideExports: mode.hidden, - dependencies: [from.module] - }; - } - case "empty-star": - return { - exports: [], - hideExports: mode.hidden, - dependencies: [moduleGraph.getModule(this)] - }; - // falls through - case "normal-reexport": { - const from = moduleGraph.getConnection(this); - return { - exports: Array.from(mode.items, item => ({ - name: item.name, - from, - export: item.ids, - hidden: item.hidden - })), - priority: 1, - dependencies: [from.module] - }; - } - case "reexport-dynamic-default": { - { - const from = moduleGraph.getConnection(this); - return { - exports: [ - { - name: mode.name, - from, - export: ["default"] - } - ], - priority: 1, - dependencies: [from.module] - }; - } - } - case "reexport-undefined": - return { - exports: [mode.name], - dependencies: [moduleGraph.getModule(this)] - }; - case "reexport-fake-namespace-object": { - const from = moduleGraph.getConnection(this); - return { - exports: [ - { - name: mode.name, - from, - export: null, - exports: [ - { - name: "default", - canMangle: false, - from, - export: null - } - ] - } - ], - priority: 1, - dependencies: [from.module] - }; - } - case "reexport-namespace-object": { - const from = moduleGraph.getConnection(this); - return { - exports: [ - { - name: mode.name, - from, - export: null - } - ], - priority: 1, - dependencies: [from.module] - }; - } - case "reexport-named-default": { - const from = moduleGraph.getConnection(this); - return { - exports: [ - { - name: mode.name, - from, - export: ["default"] - } - ], - priority: 1, - dependencies: [from.module] - }; - } - default: - throw new Error(`Unknown mode ${mode.type}`); - } + constructor(request, range) { + super(request); + this.range = range; } /** + * Returns list of exports referenced by this dependency * @param {ModuleGraph} moduleGraph module graph - * @returns {number} effective mode + * @param {RuntimeSpec} runtime the runtime for which the module is analysed + * @returns {(string[] | ReferencedExport)[]} referenced exports */ - _getEffectiveExportPresenceLevel(moduleGraph) { - if (this.exportPresenceMode !== ExportPresenceModes.AUTO) - return this.exportPresenceMode; - return moduleGraph.getParentModule(this).buildMeta.strictHarmonyModule - ? ExportPresenceModes.ERROR - : ExportPresenceModes.WARN; + getReferencedExports(moduleGraph, runtime) { + return Dependency.NO_EXPORTS_REFERENCED; } - /** - * Returns warnings - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} warnings - */ - getWarnings(moduleGraph) { - const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); - if (exportsPresence === ExportPresenceModes.WARN) { - return this._getErrors(moduleGraph); - } - return null; + get type() { + return "new Worker()"; } - /** - * Returns errors - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} errors - */ - getErrors(moduleGraph) { - const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); - if (exportsPresence === ExportPresenceModes.ERROR) { - return this._getErrors(moduleGraph); - } - return null; + get category() { + return "worker"; } +} +WorkerDependency.Template = class WorkerDependencyTemplate extends ( + ModuleDependency.Template +) { /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[] | undefined} errors + * @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} */ - _getErrors(moduleGraph) { - const ids = this.getIds(moduleGraph); - let errors = this.getLinkingErrors( - moduleGraph, - ids, - `(reexported as '${this.name}')` + apply(dependency, source, templateContext) { + const { chunkGraph, moduleGraph, runtimeRequirements } = templateContext; + const dep = /** @type {WorkerDependency} */ (dependency); + const block = /** @type {AsyncDependenciesBlock} */ ( + moduleGraph.getParentBlock(dependency) + ); + const entrypoint = /** @type {Entrypoint} */ ( + chunkGraph.getBlockChunkGroup(block) + ); + const chunk = entrypoint.getEntrypointChunk(); + + runtimeRequirements.add(RuntimeGlobals.publicPath); + runtimeRequirements.add(RuntimeGlobals.baseURI); + runtimeRequirements.add(RuntimeGlobals.getChunkScriptFilename); + + source.replace( + dep.range[0], + dep.range[1] - 1, + `/* worker import */ ${RuntimeGlobals.publicPath} + ${ + RuntimeGlobals.getChunkScriptFilename + }(${JSON.stringify(chunk.id)}), ${RuntimeGlobals.baseURI}` ); - if (ids.length === 0 && this.name === null) { - const potentialConflicts = - this._discoverActiveExportsFromOtherStarExports(moduleGraph); - if (potentialConflicts && potentialConflicts.namesSlice > 0) { - const ownNames = new Set( - potentialConflicts.names.slice( - potentialConflicts.namesSlice, - potentialConflicts.dependencyIndices[ - potentialConflicts.dependencyIndex - ] - ) - ); - const importedModule = moduleGraph.getModule(this); - if (importedModule) { - const exportsInfo = moduleGraph.getExportsInfo(importedModule); - const conflicts = new Map(); - for (const exportInfo of exportsInfo.orderedExports) { - if (exportInfo.provided !== true) continue; - if (exportInfo.name === "default") continue; - if (this.activeExports.has(exportInfo.name)) continue; - if (ownNames.has(exportInfo.name)) continue; - const conflictingDependency = findDependencyForName( - potentialConflicts, - exportInfo.name, - this.allStarExports - ? this.allStarExports.dependencies - : [...this.otherStarExports, this] - ); - if (!conflictingDependency) continue; - const target = exportInfo.getTerminalBinding(moduleGraph); - if (!target) continue; - const conflictingModule = moduleGraph.getModule( - conflictingDependency - ); - if (conflictingModule === importedModule) continue; - const conflictingExportInfo = moduleGraph.getExportInfo( - conflictingModule, - exportInfo.name - ); - const conflictingTarget = - conflictingExportInfo.getTerminalBinding(moduleGraph); - if (!conflictingTarget) continue; - if (target === conflictingTarget) continue; - const list = conflicts.get(conflictingDependency.request); - if (list === undefined) { - conflicts.set(conflictingDependency.request, [exportInfo.name]); - } else { - list.push(exportInfo.name); - } - } - for (const [request, exports] of conflicts) { - if (!errors) errors = []; - errors.push( - new HarmonyLinkingError( - `The requested module '${ - this.request - }' contains conflicting star exports for the ${ - exports.length > 1 ? "names" : "name" - } ${exports - .map(e => `'${e}'`) - .join(", ")} with the previous requested module '${request}'` - ) - ); - } - } - } - } - return errors; } +}; - serialize(context) { - const { write, setCircularReference } = context; +makeSerializable(WorkerDependency, "webpack/lib/dependencies/WorkerDependency"); - setCircularReference(this); - write(this.ids); - write(this.name); - write(this.activeExports); - write(this.otherStarExports); - write(this.exportPresenceMode); - write(this.allStarExports); +module.exports = WorkerDependency; - super.serialize(context); - } - deserialize(context) { - const { read, setCircularReference } = context; +/***/ }), - setCircularReference(this); - this.ids = read(); - this.name = read(); - this.activeExports = read(); - this.otherStarExports = read(); - this.exportPresenceMode = read(); - this.allStarExports = read(); +/***/ 82509: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - super.deserialize(context); - } -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -makeSerializable( - HarmonyExportImportedSpecifierDependency, - "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency" -); -module.exports = HarmonyExportImportedSpecifierDependency; -HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate extends ( - HarmonyImportDependency.Template -) { - /** - * @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 { moduleGraph, runtime, concatenationScope } = templateContext; +const { pathToFileURL } = __webpack_require__(57310); +const AsyncDependenciesBlock = __webpack_require__(47736); +const CommentCompilationWarning = __webpack_require__(98427); +const UnsupportedFeatureWarning = __webpack_require__(42495); +const EnableChunkLoadingPlugin = __webpack_require__(61291); +const { equals } = __webpack_require__(84953); +const createHash = __webpack_require__(49835); +const { contextify } = __webpack_require__(82186); +const EnableWasmLoadingPlugin = __webpack_require__(78613); +const ConstDependency = __webpack_require__(76911); +const CreateScriptUrlDependency = __webpack_require__(79062); +const { + harmonySpecifierTag +} = __webpack_require__(20862); +const WorkerDependency = __webpack_require__(1466); - const dep = /** @type {HarmonyExportImportedSpecifierDependency} */ ( - dependency - ); +/** @typedef {import("estree").Expression} Expression */ +/** @typedef {import("estree").ObjectExpression} ObjectExpression */ +/** @typedef {import("estree").Pattern} Pattern */ +/** @typedef {import("estree").Property} Property */ +/** @typedef {import("estree").SpreadElement} SpreadElement */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./HarmonyImportDependencyParserPlugin").HarmonySettings} HarmonySettings */ - const mode = dep.getMode(moduleGraph, runtime); +const getUrl = module => { + return pathToFileURL(module.resource).toString(); +}; - if (concatenationScope) { - switch (mode.type) { - case "reexport-undefined": - concatenationScope.registerRawExport( - mode.name, - "/* reexport non-default export from non-harmony */ undefined" - ); - } - return; - } +const DEFAULT_SYNTAX = [ + "Worker", + "SharedWorker", + "navigator.serviceWorker.register()", + "Worker from worker_threads" +]; - if (mode.type !== "unused" && mode.type !== "empty-star") { - super.apply(dependency, source, templateContext); +/** @type {WeakMap} */ +const workerIndexMap = new WeakMap(); - this._addExportFragments( - templateContext.initFragments, - dep, - mode, - templateContext.module, - moduleGraph, - runtime, - templateContext.runtimeTemplate, - templateContext.runtimeRequirements - ); - } +class WorkerPlugin { + constructor(chunkLoading, wasmLoading, module) { + this._chunkLoading = chunkLoading; + this._wasmLoading = wasmLoading; + this._module = module; } - /** - * @param {InitFragment[]} initFragments target array for init fragments - * @param {HarmonyExportImportedSpecifierDependency} dep dependency - * @param {ExportMode} mode the export mode - * @param {Module} module the current module - * @param {ModuleGraph} moduleGraph the module graph - * @param {RuntimeSpec} runtime the runtime - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {Set} runtimeRequirements runtime requirements + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - _addExportFragments( - initFragments, - dep, - mode, - module, - moduleGraph, - runtime, - runtimeTemplate, - runtimeRequirements - ) { - const importedModule = moduleGraph.getModule(dep); - const importVar = dep.getImportVar(moduleGraph); - - switch (mode.type) { - case "missing": - case "empty-star": - initFragments.push( - new InitFragment( - "/* empty/unused harmony star reexport */\n", - InitFragment.STAGE_HARMONY_EXPORTS, - 1 - ) + apply(compiler) { + if (this._chunkLoading) { + new EnableChunkLoadingPlugin(this._chunkLoading).apply(compiler); + } + if (this._wasmLoading) { + new EnableWasmLoadingPlugin(this._wasmLoading).apply(compiler); + } + const cachedContextify = contextify.bindContextCache( + compiler.context, + compiler.root + ); + compiler.hooks.thisCompilation.tap( + "WorkerPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + WorkerDependency, + normalModuleFactory ); - break; - - case "unused": - initFragments.push( - new InitFragment( - `${Template.toNormalComment( - `unused harmony reexport ${mode.name}` - )}\n`, - InitFragment.STAGE_HARMONY_EXPORTS, - 1 - ) + compilation.dependencyTemplates.set( + WorkerDependency, + new WorkerDependency.Template() ); - break; - - case "reexport-dynamic-default": - initFragments.push( - this.getReexportFragment( - module, - "reexport default from dynamic", - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), - importVar, - null, - runtimeRequirements - ) + compilation.dependencyTemplates.set( + CreateScriptUrlDependency, + new CreateScriptUrlDependency.Template() ); - break; - case "reexport-fake-namespace-object": - initFragments.push( - ...this.getReexportFakeNamespaceObjectFragments( - module, - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), - importVar, - mode.fakeType, - runtimeRequirements + /** + * @param {JavascriptParser} parser the parser + * @param {Expression} expr expression + * @returns {[BasicEvaluatedExpression, [number, number]]} parsed + */ + const parseModuleUrl = (parser, expr) => { + if ( + expr.type !== "NewExpression" || + expr.callee.type === "Super" || + expr.arguments.length !== 2 ) - ); - break; + return; + const [arg1, arg2] = expr.arguments; + if (arg1.type === "SpreadElement") return; + if (arg2.type === "SpreadElement") return; + const callee = parser.evaluateExpression(expr.callee); + if (!callee.isIdentifier() || callee.identifier !== "URL") return; + const arg2Value = parser.evaluateExpression(arg2); + if ( + !arg2Value.isString() || + !arg2Value.string.startsWith("file://") || + arg2Value.string !== getUrl(parser.state.module) + ) { + return; + } + const arg1Value = parser.evaluateExpression(arg1); + return [arg1Value, [arg1.range[0], arg2.range[1]]]; + }; - case "reexport-undefined": - initFragments.push( - this.getReexportFragment( - module, - "reexport non-default export from non-harmony", - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), - "undefined", - "", - runtimeRequirements - ) - ); - break; + /** + * @param {JavascriptParser} parser the parser + * @param {ObjectExpression} expr expression + * @returns {{ expressions: Record, otherElements: (Property | SpreadElement)[], values: Record, spread: boolean, insertType: "comma" | "single", insertLocation: number }} parsed object + */ + const parseObjectExpression = (parser, expr) => { + /** @type {Record} */ + const values = {}; + /** @type {Record} */ + const expressions = {}; + /** @type {(Property | SpreadElement)[]} */ + const otherElements = []; + let spread = false; + for (const prop of expr.properties) { + if (prop.type === "SpreadElement") { + spread = true; + } else if ( + prop.type === "Property" && + !prop.method && + !prop.computed && + prop.key.type === "Identifier" + ) { + expressions[prop.key.name] = prop.value; + if (!prop.shorthand && !prop.value.type.endsWith("Pattern")) { + const value = parser.evaluateExpression( + /** @type {Expression} */ (prop.value) + ); + if (value.isCompileTimeValue()) + values[prop.key.name] = value.asCompileTimeValue(); + } + } else { + otherElements.push(prop); + } + } + const insertType = expr.properties.length > 0 ? "comma" : "single"; + const insertLocation = + expr.properties[expr.properties.length - 1].range[1]; + return { + expressions, + otherElements, + values, + spread, + insertType, + insertLocation + }; + }; - case "reexport-named-default": - initFragments.push( - this.getReexportFragment( - module, - "reexport default export from named module", - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), - importVar, - "", - runtimeRequirements - ) - ); - break; + /** + * @param {JavascriptParser} parser the parser + * @param {object} parserOptions options + */ + const parserPlugin = (parser, parserOptions) => { + if (parserOptions.worker === false) return; + const options = !Array.isArray(parserOptions.worker) + ? ["..."] + : parserOptions.worker; + const handleNewWorker = expr => { + if (expr.arguments.length === 0 || expr.arguments.length > 2) + return; + const [arg1, arg2] = expr.arguments; + if (arg1.type === "SpreadElement") return; + if (arg2 && arg2.type === "SpreadElement") return; + const parsedUrl = parseModuleUrl(parser, arg1); + if (!parsedUrl) return; + const [url, range] = parsedUrl; + if (!url.isString()) return; + const { + expressions, + otherElements, + values: options, + spread: hasSpreadInOptions, + insertType, + insertLocation + } = arg2 && arg2.type === "ObjectExpression" + ? parseObjectExpression(parser, arg2) + : { + expressions: {}, + otherElements: [], + values: {}, + spread: false, + insertType: arg2 ? "spread" : "argument", + insertLocation: arg2 ? arg2.range : arg1.range[1] + }; + const { options: importOptions, errors: commentErrors } = + parser.parseCommentOptions(expr.range); - case "reexport-namespace-object": - initFragments.push( - this.getReexportFragment( - module, - "reexport module object", - moduleGraph.getExportsInfo(module).getUsedName(mode.name, runtime), - importVar, - "", - runtimeRequirements - ) - ); - break; + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.addWarning( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + comment.loc + ) + ); + } + } - case "normal-reexport": - for (const { name, ids, checked, hidden } of mode.items) { - if (hidden) continue; - if (checked) { - initFragments.push( - new InitFragment( - "/* harmony reexport (checked) */ " + - this.getConditionalReexportStatement( - module, - name, - importVar, - ids, - runtimeRequirements - ), - moduleGraph.isAsync(importedModule) - ? InitFragment.STAGE_ASYNC_HARMONY_IMPORTS - : InitFragment.STAGE_HARMONY_IMPORTS, - dep.sourceOrder - ) - ); - } else { - initFragments.push( - this.getReexportFragment( - module, - "reexport safe", - moduleGraph.getExportsInfo(module).getUsedName(name, runtime), - importVar, - moduleGraph - .getExportsInfo(importedModule) - .getUsedName(ids, runtime), - runtimeRequirements - ) - ); - } - } - break; + /** @type {EntryOptions} */ + let entryOptions = {}; - case "dynamic-reexport": { - const ignored = mode.hidden - ? combine(mode.ignored, mode.hidden) - : mode.ignored; - const modern = - runtimeTemplate.supportsConst() && - runtimeTemplate.supportsArrowFunction(); - let content = - "/* harmony reexport (unknown) */ var __WEBPACK_REEXPORT_OBJECT__ = {};\n" + - `/* harmony reexport (unknown) */ for(${ - modern ? "const" : "var" - } __WEBPACK_IMPORT_KEY__ in ${importVar}) `; + if (importOptions) { + if (importOptions.webpackIgnore !== undefined) { + if (typeof importOptions.webpackIgnore !== "boolean") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, + expr.loc + ) + ); + } else { + if (importOptions.webpackIgnore) { + return false; + } + } + } + if (importOptions.webpackEntryOptions !== undefined) { + if ( + typeof importOptions.webpackEntryOptions !== "object" || + importOptions.webpackEntryOptions === null + ) { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackEntryOptions\` expected a object, but received: ${importOptions.webpackEntryOptions}.`, + expr.loc + ) + ); + } else { + Object.assign( + entryOptions, + importOptions.webpackEntryOptions + ); + } + } + if (importOptions.webpackChunkName !== undefined) { + if (typeof importOptions.webpackChunkName !== "string") { + parser.state.module.addWarning( + new UnsupportedFeatureWarning( + `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, + expr.loc + ) + ); + } else { + entryOptions.name = importOptions.webpackChunkName; + } + } + } - // Filter out exports which are defined by other exports - // and filter out default export because it cannot be reexported with * - if (ignored.size > 1) { - content += - "if(" + - JSON.stringify(Array.from(ignored)) + - ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) "; - } else if (ignored.size === 1) { - content += `if(__WEBPACK_IMPORT_KEY__ !== ${JSON.stringify( - first(ignored) - )}) `; - } + if ( + !Object.prototype.hasOwnProperty.call(entryOptions, "name") && + options && + typeof options.name === "string" + ) { + entryOptions.name = options.name; + } - content += `__WEBPACK_REEXPORT_OBJECT__[__WEBPACK_IMPORT_KEY__] = `; - if (modern) { - content += `() => ${importVar}[__WEBPACK_IMPORT_KEY__]`; - } else { - content += `function(key) { return ${importVar}[key]; }.bind(0, __WEBPACK_IMPORT_KEY__)`; - } + if (entryOptions.runtime === undefined) { + let i = workerIndexMap.get(parser.state) || 0; + workerIndexMap.set(parser.state, i + 1); + let name = `${cachedContextify( + parser.state.module.identifier() + )}|${i}`; + const hash = createHash(compilation.outputOptions.hashFunction); + hash.update(name); + const digest = /** @type {string} */ ( + hash.digest(compilation.outputOptions.hashDigest) + ); + entryOptions.runtime = digest.slice( + 0, + compilation.outputOptions.hashDigestLength + ); + } - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + const block = new AsyncDependenciesBlock({ + name: entryOptions.name, + entryOptions: { + chunkLoading: this._chunkLoading, + wasmLoading: this._wasmLoading, + ...entryOptions + } + }); + block.loc = expr.loc; + const dep = new WorkerDependency(url.string, range); + dep.loc = expr.loc; + block.addDependency(dep); + parser.state.module.addBlock(block); - const exportsName = module.exportsArgument; - initFragments.push( - new InitFragment( - `${content}\n/* harmony reexport (unknown) */ ${RuntimeGlobals.definePropertyGetters}(${exportsName}, __WEBPACK_REEXPORT_OBJECT__);\n`, - moduleGraph.isAsync(importedModule) - ? InitFragment.STAGE_ASYNC_HARMONY_IMPORTS - : InitFragment.STAGE_HARMONY_IMPORTS, - dep.sourceOrder - ) - ); - break; - } + if (compilation.outputOptions.trustedTypes) { + const dep = new CreateScriptUrlDependency( + expr.arguments[0].range + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + } - default: - throw new Error(`Unknown mode ${mode.type}`); - } + if (expressions.type) { + const expr = expressions.type; + if (options.type !== false) { + const dep = new ConstDependency( + this._module ? '"module"' : "undefined", + expr.range + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + expressions.type = undefined; + } + } else if (insertType === "comma") { + if (this._module || hasSpreadInOptions) { + const dep = new ConstDependency( + `, type: ${this._module ? '"module"' : "undefined"}`, + insertLocation + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + } + } else if (insertType === "spread") { + const dep1 = new ConstDependency( + "Object.assign({}, ", + insertLocation[0] + ); + const dep2 = new ConstDependency( + `, { type: ${this._module ? '"module"' : "undefined"} })`, + insertLocation[1] + ); + dep1.loc = expr.loc; + dep2.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep1); + parser.state.module.addPresentationalDependency(dep2); + } else if (insertType === "argument") { + if (this._module) { + const dep = new ConstDependency( + ', { type: "module" }', + insertLocation + ); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + } + } + + parser.walkExpression(expr.callee); + for (const key of Object.keys(expressions)) { + if (expressions[key]) parser.walkExpression(expressions[key]); + } + for (const prop of otherElements) { + parser.walkProperty(prop); + } + if (insertType === "spread") { + parser.walkExpression(arg2); + } + + return true; + }; + const processItem = item => { + if (item.endsWith("()")) { + parser.hooks.call + .for(item.slice(0, -2)) + .tap("WorkerPlugin", handleNewWorker); + } else { + const match = /^(.+?)(\(\))?\s+from\s+(.+)$/.exec(item); + if (match) { + const ids = match[1].split("."); + const call = match[2]; + const source = match[3]; + (call ? parser.hooks.call : parser.hooks.new) + .for(harmonySpecifierTag) + .tap("WorkerPlugin", expr => { + const settings = /** @type {HarmonySettings} */ ( + parser.currentTagData + ); + if ( + !settings || + settings.source !== source || + !equals(settings.ids, ids) + ) { + return; + } + return handleNewWorker(expr); + }); + } else { + parser.hooks.new.for(item).tap("WorkerPlugin", handleNewWorker); + } + } + }; + for (const item of options) { + if (item === "...") { + DEFAULT_SYNTAX.forEach(processItem); + } else processItem(item); + } + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("WorkerPlugin", parserPlugin); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("WorkerPlugin", parserPlugin); + } + ); } +} +module.exports = WorkerPlugin; - getReexportFragment( - module, - comment, - key, - name, - valueKey, - runtimeRequirements - ) { - const returnValue = this.getReturnValue(name, valueKey); - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); +/***/ }), - const map = new Map(); - map.set(key, `/* ${comment} */ ${returnValue}`); +/***/ 50396: +/***/ (function(module) { - return new HarmonyExportInitFragment(module.exportsArgument, map); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - getReexportFakeNamespaceObjectFragments( - module, - key, - name, - fakeType, - runtimeRequirements - ) { - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - const map = new Map(); - map.set( - key, - `/* reexport fake namespace object from non-harmony */ ${name}_namespace_cache || (${name}_namespace_cache = ${ - RuntimeGlobals.createFakeNamespaceObject - }(${name}${fakeType ? `, ${fakeType}` : ""}))` - ); - return [ - new InitFragment( - `var ${name}_namespace_cache;\n`, - InitFragment.STAGE_CONSTANTS, - -1, - `${name}_namespace_cache` - ), - new HarmonyExportInitFragment(module.exportsArgument, map) - ]; +module.exports = expr => { + // + if ( + expr.type === "FunctionExpression" || + expr.type === "ArrowFunctionExpression" + ) { + return { + fn: expr, + expressions: [], + needThis: false + }; } - getConditionalReexportStatement( - module, - key, - name, - valueKey, - runtimeRequirements + // .bind() + if ( + expr.type === "CallExpression" && + expr.callee.type === "MemberExpression" && + expr.callee.object.type === "FunctionExpression" && + expr.callee.property.type === "Identifier" && + expr.callee.property.name === "bind" && + expr.arguments.length === 1 ) { - if (valueKey === false) { - return "/* unused export */\n"; - } + return { + fn: expr.callee.object, + expressions: [expr.arguments[0]], + needThis: undefined + }; + } + // (function(_this) {return })(this) (Coffeescript) + if ( + expr.type === "CallExpression" && + expr.callee.type === "FunctionExpression" && + expr.callee.body.type === "BlockStatement" && + expr.arguments.length === 1 && + expr.arguments[0].type === "ThisExpression" && + expr.callee.body.body && + expr.callee.body.body.length === 1 && + expr.callee.body.body[0].type === "ReturnStatement" && + expr.callee.body.body[0].argument && + expr.callee.body.body[0].argument.type === "FunctionExpression" + ) { + return { + fn: expr.callee.body.body[0].argument, + expressions: [], + needThis: true + }; + } +}; - const exportsName = module.exportsArgument; - const returnValue = this.getReturnValue(name, valueKey); - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - runtimeRequirements.add(RuntimeGlobals.hasOwnProperty); +/***/ }), - return `if(${RuntimeGlobals.hasOwnProperty}(${name}, ${JSON.stringify( - valueKey[0] - )})) ${ - RuntimeGlobals.definePropertyGetters - }(${exportsName}, { ${JSON.stringify( - key - )}: function() { return ${returnValue}; } });\n`; - } +/***/ 55207: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - getReturnValue(name, valueKey) { - if (valueKey === null) { - return `${name}_default.a`; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (valueKey === "") { - return name; - } - if (valueKey === false) { - return "/* unused export */ undefined"; - } - return `${name}${propertyAccess(valueKey)}`; - } -}; +const { UsageState } = __webpack_require__(63686); -class HarmonyStarExportsList { - constructor() { - /** @type {HarmonyExportImportedSpecifierDependency[]} */ - this.dependencies = []; - } +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - /** - * @param {HarmonyExportImportedSpecifierDependency} dep dependency - * @returns {void} - */ - push(dep) { - this.dependencies.push(dep); +/** + * @param {RuntimeSpec} runtime the runtime + * @param {string[][]} referencedExports list of referenced exports, will be added to + * @param {string[]} prefix export prefix + * @param {ExportInfo=} exportInfo the export info + * @param {boolean} defaultPointsToSelf when true, using default will reference itself + * @param {Set} alreadyVisited already visited export info (to handle circular reexports) + */ +const processExportInfo = ( + runtime, + referencedExports, + prefix, + exportInfo, + defaultPointsToSelf = false, + alreadyVisited = new Set() +) => { + if (!exportInfo) { + referencedExports.push(prefix); + return; } - - slice() { - return this.dependencies.slice(); + const used = exportInfo.getUsed(runtime); + if (used === UsageState.Unused) return; + if (alreadyVisited.has(exportInfo)) { + referencedExports.push(prefix); + return; } - - serialize({ write, setCircularReference }) { - setCircularReference(this); - write(this.dependencies); + alreadyVisited.add(exportInfo); + if ( + used !== UsageState.OnlyPropertiesUsed || + !exportInfo.exportsInfo || + exportInfo.exportsInfo.otherExportsInfo.getUsed(runtime) !== + UsageState.Unused + ) { + alreadyVisited.delete(exportInfo); + referencedExports.push(prefix); + return; } - - deserialize({ read, setCircularReference }) { - setCircularReference(this); - this.dependencies = read(); + const exportsInfo = exportInfo.exportsInfo; + for (const exportInfo of exportsInfo.orderedExports) { + processExportInfo( + runtime, + referencedExports, + defaultPointsToSelf && exportInfo.name === "default" + ? prefix + : prefix.concat(exportInfo.name), + exportInfo, + false, + alreadyVisited + ); } -} - -makeSerializable( - HarmonyStarExportsList, - "webpack/lib/dependencies/HarmonyExportImportedSpecifierDependency", - "HarmonyStarExportsList" -); - -module.exports.HarmonyStarExportsList = HarmonyStarExportsList; + alreadyVisited.delete(exportInfo); +}; +module.exports = processExportInfo; /***/ }), -/***/ 89500: +/***/ 32277: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -85520,169 +84727,72 @@ module.exports.HarmonyStarExportsList = HarmonyStarExportsList; -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const { first } = __webpack_require__(93347); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ - -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; -}; - -const EMPTY_MAP = new Map(); -const EMPTY_SET = new Set(); +const ExternalsPlugin = __webpack_require__(6652); -/** - * @typedef {GenerateContext} Context - */ -class HarmonyExportInitFragment extends InitFragment { - /** - * @param {string} exportsArgument the exports identifier - * @param {Map} exportMap mapping from used name to exposed variable name - * @param {Set} unusedExports list of unused export names - */ - constructor( - exportsArgument, - exportMap = EMPTY_MAP, - unusedExports = EMPTY_SET - ) { - super(undefined, InitFragment.STAGE_HARMONY_EXPORTS, 1, "harmony-exports"); - this.exportsArgument = exportsArgument; - this.exportMap = exportMap; - this.unusedExports = unusedExports; - } +/** @typedef {import("../Compiler")} Compiler */ +class ElectronTargetPlugin { /** - * @param {HarmonyExportInitFragment[]} fragments all fragments to merge - * @returns {HarmonyExportInitFragment} merged fragment + * @param {"main" | "preload" | "renderer"=} context in main, preload or renderer context? */ - mergeAll(fragments) { - let exportMap; - let exportMapOwned = false; - let unusedExports; - let unusedExportsOwned = false; - - for (const fragment of fragments) { - if (fragment.exportMap.size !== 0) { - if (exportMap === undefined) { - exportMap = fragment.exportMap; - exportMapOwned = false; - } else { - if (!exportMapOwned) { - exportMap = new Map(exportMap); - exportMapOwned = true; - } - for (const [key, value] of fragment.exportMap) { - if (!exportMap.has(key)) exportMap.set(key, value); - } - } - } - if (fragment.unusedExports.size !== 0) { - if (unusedExports === undefined) { - unusedExports = fragment.unusedExports; - unusedExportsOwned = false; - } else { - if (!unusedExportsOwned) { - unusedExports = new Set(unusedExports); - unusedExportsOwned = true; - } - for (const value of fragment.unusedExports) { - unusedExports.add(value); - } - } - } - } - return new HarmonyExportInitFragment( - this.exportsArgument, - exportMap, - unusedExports - ); - } - - merge(other) { - let exportMap; - if (this.exportMap.size === 0) { - exportMap = other.exportMap; - } else if (other.exportMap.size === 0) { - exportMap = this.exportMap; - } else { - exportMap = new Map(other.exportMap); - for (const [key, value] of this.exportMap) { - if (!exportMap.has(key)) exportMap.set(key, value); - } - } - let unusedExports; - if (this.unusedExports.size === 0) { - unusedExports = other.unusedExports; - } else if (other.unusedExports.size === 0) { - unusedExports = this.unusedExports; - } else { - unusedExports = new Set(other.unusedExports); - for (const value of this.unusedExports) { - unusedExports.add(value); - } - } - return new HarmonyExportInitFragment( - this.exportsArgument, - exportMap, - unusedExports - ); + constructor(context) { + this._context = context; } - /** - * @param {Context} context context - * @returns {string|Source} the source code that will be included as initialization code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - getContent({ runtimeTemplate, runtimeRequirements }) { - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - - const unusedPart = - this.unusedExports.size > 1 - ? `/* unused harmony exports ${joinIterableWithComma( - this.unusedExports - )} */\n` - : this.unusedExports.size > 0 - ? `/* unused harmony export ${first(this.unusedExports)} */\n` - : ""; - const definitions = []; - for (const [key, value] of this.exportMap) { - definitions.push( - `\n/* harmony export */ ${JSON.stringify( - key - )}: ${runtimeTemplate.returningFunction(value)}` - ); + apply(compiler) { + new ExternalsPlugin("node-commonjs", [ + "clipboard", + "crash-reporter", + "electron", + "ipc", + "native-image", + "original-fs", + "screen", + "shell" + ]).apply(compiler); + switch (this._context) { + case "main": + new ExternalsPlugin("node-commonjs", [ + "app", + "auto-updater", + "browser-window", + "content-tracing", + "dialog", + "global-shortcut", + "ipc-main", + "menu", + "menu-item", + "power-monitor", + "power-save-blocker", + "protocol", + "session", + "tray", + "web-contents" + ]).apply(compiler); + break; + case "preload": + case "renderer": + new ExternalsPlugin("node-commonjs", [ + "desktop-capturer", + "ipc-renderer", + "remote", + "web-frame" + ]).apply(compiler); + break; } - const definePart = - this.exportMap.size > 0 - ? `/* harmony export */ ${RuntimeGlobals.definePropertyGetters}(${ - this.exportsArgument - }, {${definitions.join(",")}\n/* harmony export */ });\n` - : ""; - return `${definePart}${unusedPart}`; } } -module.exports = HarmonyExportInitFragment; +module.exports = ElectronTargetPlugin; /***/ }), -/***/ 48567: +/***/ 22273: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -85693,163 +84803,68 @@ module.exports = HarmonyExportInitFragment; -const makeSerializable = __webpack_require__(33032); -const HarmonyExportInitFragment = __webpack_require__(89500); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ - -class HarmonyExportSpecifierDependency extends NullDependency { - constructor(id, name) { - super(); - this.id = id; - this.name = name; - } - - get type() { - return "harmony export specifier"; - } +const WebpackError = __webpack_require__(53799); - /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names - */ - getExports(moduleGraph) { - return { - exports: [this.name], - priority: 1, - terminalBinding: true, - dependencies: undefined - }; - } +/** @typedef {import("../Module")} Module */ +class BuildCycleError extends WebpackError { /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules + * Creates an instance of ModuleDependencyError. + * @param {Module} module the module starting the cycle */ - getModuleEvaluationSideEffectsState(moduleGraph) { - return false; - } - - serialize(context) { - const { write } = context; - write(this.id); - write(this.name); - super.serialize(context); - } + constructor(module) { + super( + "There is a circular build dependency, which makes it impossible to create this module" + ); - deserialize(context) { - const { read } = context; - this.id = read(); - this.name = read(); - super.deserialize(context); + this.name = "BuildCycleError"; + this.module = module; } } -makeSerializable( - HarmonyExportSpecifierDependency, - "webpack/lib/dependencies/HarmonyExportSpecifierDependency" -); - -HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, - { module, moduleGraph, initFragments, runtime, concatenationScope } - ) { - const dep = /** @type {HarmonyExportSpecifierDependency} */ (dependency); - if (concatenationScope) { - concatenationScope.registerExport(dep.name, dep.id); - return; - } - const used = moduleGraph - .getExportsInfo(module) - .getUsedName(dep.name, runtime); - if (!used) { - const set = new Set(); - set.add(dep.name || "namespace"); - initFragments.push( - new HarmonyExportInitFragment(module.exportsArgument, undefined, set) - ); - return; - } - - const map = new Map(); - map.set(used, `/* binding */ ${dep.id}`); - initFragments.push( - new HarmonyExportInitFragment(module.exportsArgument, map, undefined) - ); - } -}; - -module.exports = HarmonyExportSpecifierDependency; +module.exports = BuildCycleError; /***/ }), -/***/ 39211: -/***/ (function(__unused_webpack_module, exports) { +/***/ 5294: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -/** @typedef {import("../Parser").ParserState} ParserState */ +const RuntimeModule = __webpack_require__(16963); -/** @type {WeakMap} */ -const parserStateExportsState = new WeakMap(); +class ExportWebpackRequireRuntimeModule extends RuntimeModule { + constructor() { + super("export webpack runtime", RuntimeModule.STAGE_ATTACH); + } -/** - * @param {ParserState} parserState parser state - * @param {boolean} isStrictHarmony strict harmony mode should be enabled - * @returns {void} - */ -exports.enable = (parserState, isStrictHarmony) => { - const value = parserStateExportsState.get(parserState); - if (value === false) return; - parserStateExportsState.set(parserState, true); - if (value !== true) { - parserState.module.buildMeta.exportsType = "namespace"; - parserState.module.buildInfo.strict = true; - parserState.module.buildInfo.exportsArgument = "__webpack_exports__"; - if (isStrictHarmony) { - parserState.module.buildMeta.strictHarmonyModule = true; - parserState.module.buildInfo.moduleArgument = "__webpack_module__"; - } + /** + * @returns {boolean} true, if the runtime module should get it's own scope + */ + shouldIsolate() { + return false; } -}; -/** - * @param {ParserState} parserState parser state - * @returns {boolean} true, when enabled - */ -exports.isEnabled = parserState => { - const value = parserStateExportsState.get(parserState); - return value === true; -}; + /** + * @returns {string} runtime code + */ + generate() { + return "export default __webpack_require__;"; + } +} + +module.exports = ExportWebpackRequireRuntimeModule; /***/ }), -/***/ 57154: +/***/ 68927: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -85860,363 +84875,206 @@ exports.isEnabled = parserState => { -const ConditionalInitFragment = __webpack_require__(61333); -const Dependency = __webpack_require__(54912); -const HarmonyLinkingError = __webpack_require__(97511); -const InitFragment = __webpack_require__(55870); -const Template = __webpack_require__(39722); -const AwaitDependenciesInitFragment = __webpack_require__(41153); -const { filterRuntime, mergeRuntime } = __webpack_require__(17156); -const ModuleDependency = __webpack_require__(80321); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +const { ConcatSource } = __webpack_require__(51255); +const { RuntimeGlobals } = __webpack_require__(91919); +const HotUpdateChunk = __webpack_require__(9597); +const Template = __webpack_require__(1626); +const { getAllChunks } = __webpack_require__(91145); +const { + getCompilationHooks, + getChunkFilenameTemplate +} = __webpack_require__(89464); +const { updateHashForEntryStartup } = __webpack_require__(98124); -const ExportPresenceModes = { - NONE: /** @type {0} */ (0), - WARN: /** @type {1} */ (1), - AUTO: /** @type {2} */ (2), - ERROR: /** @type {3} */ (3), - fromUserOption(str) { - switch (str) { - case "error": - return ExportPresenceModes.ERROR; - case "warn": - return ExportPresenceModes.WARN; - case "auto": - return ExportPresenceModes.AUTO; - case false: - return ExportPresenceModes.NONE; - default: - throw new Error(`Invalid export presence value ${str}`); - } - } -}; +/** @typedef {import("../Compiler")} Compiler */ -class HarmonyImportDependency extends ModuleDependency { +class ModuleChunkFormatPlugin { /** - * - * @param {string} request request string - * @param {number} sourceOrder source order - * @param {Record=} assertions import assertions + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - constructor(request, sourceOrder, assertions) { - super(request); - this.sourceOrder = sourceOrder; - this.assertions = assertions; - } - - get category() { - return "esm"; - } + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "ModuleChunkFormatPlugin", + compilation => { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + "ModuleChunkFormatPlugin", + (chunk, set) => { + if (chunk.hasRuntime()) return; + if (compilation.chunkGraph.getNumberOfEntryModules(chunk) > 0) { + set.add(RuntimeGlobals.require); + set.add(RuntimeGlobals.startupEntrypoint); + set.add(RuntimeGlobals.externalInstallChunk); + } + } + ); + const hooks = getCompilationHooks(compilation); + hooks.renderChunk.tap( + "ModuleChunkFormatPlugin", + (modules, renderContext) => { + const { chunk, chunkGraph, runtimeTemplate } = renderContext; + const hotUpdateChunk = + chunk instanceof HotUpdateChunk ? chunk : null; + const source = new ConcatSource(); + if (hotUpdateChunk) { + throw new Error( + "HMR is not implemented for module chunk format yet" + ); + } else { + source.add(`export const id = ${JSON.stringify(chunk.id)};\n`); + source.add(`export const ids = ${JSON.stringify(chunk.ids)};\n`); + source.add(`export const modules = `); + source.add(modules); + source.add(`;\n`); + const runtimeModules = + chunkGraph.getChunkRuntimeModulesInOrder(chunk); + if (runtimeModules.length > 0) { + source.add("export const runtime =\n"); + source.add( + Template.renderChunkRuntimeModules( + runtimeModules, + renderContext + ) + ); + } + const entries = Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ); + if (entries.length > 0) { + const runtimeChunk = entries[0][1].getRuntimeChunk(); + const currentOutputName = compilation + .getPath( + getChunkFilenameTemplate(chunk, compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ) + .split("/"); - /** - * 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.NO_EXPORTS_REFERENCED; - } + // remove filename, we only need the directory + currentOutputName.pop(); - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {string} name of the variable for the import - */ - getImportVar(moduleGraph) { - const module = moduleGraph.getParentModule(this); - const meta = moduleGraph.getMeta(module); - let importVarMap = meta.importVarMap; - if (!importVarMap) meta.importVarMap = importVarMap = new Map(); - let importVar = importVarMap.get(moduleGraph.getModule(this)); - if (importVar) return importVar; - importVar = `${Template.toIdentifier( - `${this.userRequest}` - )}__WEBPACK_IMPORTED_MODULE_${importVarMap.size}__`; - importVarMap.set(moduleGraph.getModule(this), importVar); - return importVar; - } + const getRelativePath = chunk => { + const baseOutputName = currentOutputName.slice(); + const chunkOutputName = compilation + .getPath( + getChunkFilenameTemplate( + chunk, + compilation.outputOptions + ), + { + chunk: chunk, + contentHashType: "javascript" + } + ) + .split("/"); - /** - * @param {boolean} update create new variables or update existing one - * @param {DependencyTemplateContext} templateContext the template context - * @returns {[string, string]} the import statement and the compat statement - */ - getImportStatement( - update, - { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } - ) { - return runtimeTemplate.importStatement({ - update, - module: moduleGraph.getModule(this), - chunkGraph, - importVar: this.getImportVar(moduleGraph), - request: this.request, - originModule: module, - runtimeRequirements - }); - } + // remove common parts + while ( + baseOutputName.length > 0 && + chunkOutputName.length > 0 && + baseOutputName[0] === chunkOutputName[0] + ) { + baseOutputName.shift(); + chunkOutputName.shift(); + } + // create final path + return ( + (baseOutputName.length > 0 + ? "../".repeat(baseOutputName.length) + : "./") + chunkOutputName.join("/") + ); + }; - /** - * @param {ModuleGraph} moduleGraph module graph - * @param {string[]} ids imported ids - * @param {string} additionalMessage extra info included in the error message - * @returns {WebpackError[] | undefined} errors - */ - getLinkingErrors(moduleGraph, ids, additionalMessage) { - const importedModule = moduleGraph.getModule(this); - // ignore errors for missing or failed modules - if (!importedModule || importedModule.getNumberOfErrors() > 0) { - return; - } + const entrySource = new ConcatSource(); + entrySource.add(source); + entrySource.add(";\n\n// load runtime\n"); + entrySource.add( + `import __webpack_require__ from ${JSON.stringify( + getRelativePath(runtimeChunk) + )};\n` + ); - const parentModule = moduleGraph.getParentModule(this); - const exportsType = importedModule.getExportsType( - moduleGraph, - parentModule.buildMeta.strictHarmonyModule - ); - if (exportsType === "namespace" || exportsType === "default-with-named") { - if (ids.length === 0) { - return; - } + const startupSource = new ConcatSource(); + startupSource.add( + `var __webpack_exec__ = ${runtimeTemplate.returningFunction( + `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)`, + "moduleId" + )}\n` + ); - if ( - (exportsType !== "default-with-named" || ids[0] !== "default") && - moduleGraph.isExportProvided(importedModule, ids) === false - ) { - // We are sure that it's not provided + const loadedChunks = new Set(); + let index = 0; + for (let i = 0; i < entries.length; i++) { + const [module, entrypoint] = entries[i]; + const final = i + 1 === entries.length; + const moduleId = chunkGraph.getModuleId(module); + const chunks = getAllChunks( + entrypoint, + runtimeChunk, + undefined + ); + for (const chunk of chunks) { + if (loadedChunks.has(chunk)) continue; + loadedChunks.add(chunk); + startupSource.add( + `import * as __webpack_chunk_${index}__ from ${JSON.stringify( + getRelativePath(chunk) + )};\n` + ); + startupSource.add( + `${RuntimeGlobals.externalInstallChunk}(__webpack_chunk_${index}__);\n` + ); + index++; + } + startupSource.add( + `${ + final ? "var __webpack_exports__ = " : "" + }__webpack_exec__(${JSON.stringify(moduleId)});\n` + ); + } - // Try to provide detailed info in the error message - let pos = 0; - let exportsInfo = moduleGraph.getExportsInfo(importedModule); - while (pos < ids.length && exportsInfo) { - const id = ids[pos++]; - const exportInfo = exportsInfo.getReadOnlyExportInfo(id); - if (exportInfo.provided === false) { - // We are sure that it's not provided - const providedExports = exportsInfo.getProvidedExports(); - const moreInfo = !Array.isArray(providedExports) - ? " (possible exports unknown)" - : providedExports.length === 0 - ? " (module has no exports)" - : ` (possible exports: ${providedExports.join(", ")})`; - return [ - new HarmonyLinkingError( - `export ${ids - .slice(0, pos) - .map(id => `'${id}'`) - .join(".")} ${additionalMessage} was not found in '${ - this.userRequest - }'${moreInfo}` - ) - ]; + entrySource.add( + hooks.renderStartup.call( + startupSource, + entries[entries.length - 1][0], + { + ...renderContext, + inlined: false + } + ) + ); + return entrySource; + } + } + return source; } - exportsInfo = exportInfo.getNestedExportsInfo(); - } - - // General error message - return [ - new HarmonyLinkingError( - `export ${ids - .map(id => `'${id}'`) - .join(".")} ${additionalMessage} was not found in '${ - this.userRequest - }'` - ) - ]; + ); + hooks.chunkHash.tap( + "ModuleChunkFormatPlugin", + (chunk, hash, { chunkGraph, runtimeTemplate }) => { + if (chunk.hasRuntime()) return; + hash.update("ModuleChunkFormatPlugin"); + hash.update("1"); + const entries = Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ); + updateHashForEntryStartup(hash, chunkGraph, entries, chunk); + } + ); } - } - switch (exportsType) { - case "default-only": - // It's has only a default export - if (ids.length > 0 && ids[0] !== "default") { - // In strict harmony modules we only support the default export - return [ - new HarmonyLinkingError( - `Can't import the named export ${ids - .map(id => `'${id}'`) - .join( - "." - )} ${additionalMessage} from default-exporting module (only default export is available)` - ) - ]; - } - break; - case "default-with-named": - // It has a default export and named properties redirect - // In some cases we still want to warn here - if ( - ids.length > 0 && - ids[0] !== "default" && - importedModule.buildMeta.defaultObject === "redirect-warn" - ) { - // For these modules only the default export is supported - return [ - new HarmonyLinkingError( - `Should not import the named export ${ids - .map(id => `'${id}'`) - .join( - "." - )} ${additionalMessage} from default-exporting module (only default export is available soon)` - ) - ]; - } - break; - } - } - - serialize(context) { - const { write } = context; - write(this.sourceOrder); - write(this.assertions); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.sourceOrder = read(); - this.assertions = read(); - super.deserialize(context); + ); } } -module.exports = HarmonyImportDependency; - -/** @type {WeakMap>} */ -const importEmittedMap = new WeakMap(); - -HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends ( - ModuleDependency.Template -) { - /** - * @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 dep = /** @type {HarmonyImportDependency} */ (dependency); - const { module, chunkGraph, moduleGraph, runtime } = templateContext; - - const connection = moduleGraph.getConnection(dep); - if (connection && !connection.isTargetActive(runtime)) return; - - const referencedModule = connection && connection.module; - - if ( - connection && - connection.weak && - referencedModule && - chunkGraph.getModuleId(referencedModule) === null - ) { - // in weak references, module might not be in any chunk - // but that's ok, we don't need that logic in this case - return; - } - - const moduleKey = referencedModule - ? referencedModule.identifier() - : dep.request; - const key = `harmony import ${moduleKey}`; - - const runtimeCondition = dep.weak - ? false - : connection - ? filterRuntime(runtime, r => connection.isTargetActive(r)) - : true; - - if (module && referencedModule) { - let emittedModules = importEmittedMap.get(module); - if (emittedModules === undefined) { - emittedModules = new WeakMap(); - importEmittedMap.set(module, emittedModules); - } - let mergedRuntimeCondition = runtimeCondition; - const oldRuntimeCondition = emittedModules.get(referencedModule) || false; - if (oldRuntimeCondition !== false && mergedRuntimeCondition !== true) { - if (mergedRuntimeCondition === false || oldRuntimeCondition === true) { - mergedRuntimeCondition = oldRuntimeCondition; - } else { - mergedRuntimeCondition = mergeRuntime( - oldRuntimeCondition, - mergedRuntimeCondition - ); - } - } - emittedModules.set(referencedModule, mergedRuntimeCondition); - } - - const importStatement = dep.getImportStatement(false, templateContext); - if ( - referencedModule && - templateContext.moduleGraph.isAsync(referencedModule) - ) { - templateContext.initFragments.push( - new ConditionalInitFragment( - importStatement[0], - InitFragment.STAGE_HARMONY_IMPORTS, - dep.sourceOrder, - key, - runtimeCondition - ) - ); - templateContext.initFragments.push( - new AwaitDependenciesInitFragment( - new Set([dep.getImportVar(templateContext.moduleGraph)]) - ) - ); - templateContext.initFragments.push( - new ConditionalInitFragment( - importStatement[1], - InitFragment.STAGE_ASYNC_HARMONY_IMPORTS, - dep.sourceOrder, - key + " compat", - runtimeCondition - ) - ); - } else { - templateContext.initFragments.push( - new ConditionalInitFragment( - importStatement[0] + importStatement[1], - InitFragment.STAGE_HARMONY_IMPORTS, - dep.sourceOrder, - key, - runtimeCondition - ) - ); - } - } - - /** - * - * @param {Module} module the module - * @param {Module} referencedModule the referenced module - * @returns {RuntimeSpec | boolean} runtimeCondition in which this import has been emitted - */ - static getImportEmittedRuntime(module, referencedModule) { - const emittedModules = importEmittedMap.get(module); - if (emittedModules === undefined) return false; - return emittedModules.get(referencedModule) || false; - } -}; - -module.exports.ExportPresenceModes = ExportPresenceModes; +module.exports = ModuleChunkFormatPlugin; /***/ }), -/***/ 20862: +/***/ 89831: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -86227,687 +85085,390 @@ module.exports.ExportPresenceModes = ExportPresenceModes; -const HotModuleReplacementPlugin = __webpack_require__(6404); -const InnerGraph = __webpack_require__(38988); -const ConstDependency = __webpack_require__(76911); -const HarmonyAcceptDependency = __webpack_require__(23624); -const HarmonyAcceptImportDependency = __webpack_require__(99843); -const HarmonyExports = __webpack_require__(39211); -const { ExportPresenceModes } = __webpack_require__(57154); -const HarmonyImportSideEffectDependency = __webpack_require__(73132); -const HarmonyImportSpecifierDependency = __webpack_require__(14077); - -/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclaration */ -/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclaration */ -/** @typedef {import("estree").Identifier} Identifier */ -/** @typedef {import("estree").ImportDeclaration} ImportDeclaration */ -/** @typedef {import("estree").ImportExpression} ImportExpression */ -/** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ -/** @typedef {import("../optimize/InnerGraph").InnerGraph} InnerGraph */ -/** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */ -/** @typedef {import("./HarmonyImportDependency")} HarmonyImportDependency */ - -const harmonySpecifierTag = Symbol("harmony import"); - -/** - * @typedef {Object} HarmonySettings - * @property {string[]} ids - * @property {string} source - * @property {number} sourceOrder - * @property {string} name - * @property {boolean} await - * @property {Record | undefined} assertions - */ - -/** - * @param {ImportDeclaration | ExportNamedDeclaration | ExportAllDeclaration | ImportExpression} node node with assertions - * @returns {Record | undefined} assertions - */ -function getAssertions(node) { - // TODO remove cast when @types/estree has been updated to import assertions - const assertions = /** @type {{ assertions?: ImportAttributeNode[] }} */ ( - node - ).assertions; - if (assertions === undefined) { - return undefined; - } - const result = {}; - for (const assertion of assertions) { - const key = - assertion.key.type === "Identifier" - ? assertion.key.name - : assertion.key.value; - result[key] = assertion.value.value; - } - return result; -} +const RuntimeGlobals = __webpack_require__(16475); +const ExportWebpackRequireRuntimeModule = __webpack_require__(5294); +const ModuleChunkLoadingRuntimeModule = __webpack_require__(64747); -module.exports = class HarmonyImportDependencyParserPlugin { - /** - * @param {JavascriptParserOptions} options options - */ - constructor(options) { - this.exportPresenceMode = - options.importExportsPresence !== undefined - ? ExportPresenceModes.fromUserOption(options.importExportsPresence) - : options.exportsPresence !== undefined - ? ExportPresenceModes.fromUserOption(options.exportsPresence) - : options.strictExportPresence - ? ExportPresenceModes.ERROR - : ExportPresenceModes.AUTO; - this.strictThisContextOnImports = options.strictThisContextOnImports; - } +/** @typedef {import("../Compiler")} Compiler */ +class ModuleChunkLoadingPlugin { /** - * @param {JavascriptParser} parser the parser + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply(parser) { - const { exportPresenceMode } = this; - parser.hooks.isPure - .for("Identifier") - .tap("HarmonyImportDependencyParserPlugin", expression => { - const expr = /** @type {Identifier} */ (expression); - if ( - parser.isVariableDefined(expr.name) || - parser.getTagData(expr.name, harmonySpecifierTag) - ) { - return true; - } - }); - parser.hooks.import.tap( - "HarmonyImportDependencyParserPlugin", - (statement, source) => { - parser.state.lastHarmonyImportOrder = - (parser.state.lastHarmonyImportOrder || 0) + 1; - const clearDep = new ConstDependency( - parser.isAsiPosition(statement.range[0]) ? ";" : "", - statement.range - ); - clearDep.loc = statement.loc; - parser.state.module.addPresentationalDependency(clearDep); - parser.unsetAsiPosition(statement.range[1]); - const assertions = getAssertions(statement); - const sideEffectDep = new HarmonyImportSideEffectDependency( - source, - parser.state.lastHarmonyImportOrder, - assertions - ); - sideEffectDep.loc = statement.loc; - parser.state.module.addDependency(sideEffectDep); - return true; - } - ); - parser.hooks.importSpecifier.tap( - "HarmonyImportDependencyParserPlugin", - (statement, source, id, name) => { - const ids = id === null ? [] : [id]; - parser.tagVariable(name, harmonySpecifierTag, { - name, - source, - ids, - sourceOrder: parser.state.lastHarmonyImportOrder, - assertions: getAssertions(statement) - }); - return true; - } - ); - parser.hooks.expression - .for(harmonySpecifierTag) - .tap("HarmonyImportDependencyParserPlugin", expr => { - const settings = /** @type {HarmonySettings} */ (parser.currentTagData); - const dep = new HarmonyImportSpecifierDependency( - settings.source, - settings.sourceOrder, - settings.ids, - settings.name, - expr.range, - exportPresenceMode, - settings.assertions - ); - dep.shorthand = parser.scope.inShorthand; - dep.directImport = true; - dep.asiSafe = !parser.isAsiPosition(expr.range[0]); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); - return true; - }); - parser.hooks.expressionMemberChain - .for(harmonySpecifierTag) - .tap("HarmonyImportDependencyParserPlugin", (expr, members) => { - const settings = /** @type {HarmonySettings} */ (parser.currentTagData); - const ids = settings.ids.concat(members); - const dep = new HarmonyImportSpecifierDependency( - settings.source, - settings.sourceOrder, - ids, - settings.name, - expr.range, - exportPresenceMode, - settings.assertions - ); - dep.asiSafe = !parser.isAsiPosition(expr.range[0]); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); - return true; - }); - parser.hooks.callMemberChain - .for(harmonySpecifierTag) - .tap("HarmonyImportDependencyParserPlugin", (expr, members) => { - const { arguments: args, callee } = expr; - const settings = /** @type {HarmonySettings} */ (parser.currentTagData); - const ids = settings.ids.concat(members); - const dep = new HarmonyImportSpecifierDependency( - settings.source, - settings.sourceOrder, - ids, - settings.name, - callee.range, - exportPresenceMode, - settings.assertions - ); - dep.directImport = members.length === 0; - dep.call = true; - dep.asiSafe = !parser.isAsiPosition(callee.range[0]); - // only in case when we strictly follow the spec we need a special case here - dep.namespaceObjectAsContext = - members.length > 0 && this.strictThisContextOnImports; - dep.loc = callee.loc; - parser.state.module.addDependency(dep); - if (args) parser.walkExpressions(args); - InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); - return true; - }); - const { hotAcceptCallback, hotAcceptWithoutCallback } = - HotModuleReplacementPlugin.getParserHooks(parser); - hotAcceptCallback.tap( - "HarmonyImportDependencyParserPlugin", - (expr, requests) => { - if (!HarmonyExports.isEnabled(parser.state)) { - // This is not a harmony module, skip it - return; - } - const dependencies = requests.map(request => { - const dep = new HarmonyAcceptImportDependency(request); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return dep; - }); - if (dependencies.length > 0) { - const dep = new HarmonyAcceptDependency( - expr.range, - dependencies, - true - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - } - } - ); - hotAcceptWithoutCallback.tap( - "HarmonyImportDependencyParserPlugin", - (expr, requests) => { - if (!HarmonyExports.isEnabled(parser.state)) { - // This is not a harmony module, skip it - return; - } - const dependencies = requests.map(request => { - const dep = new HarmonyAcceptImportDependency(request); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return dep; - }); - if (dependencies.length > 0) { - const dep = new HarmonyAcceptDependency( - expr.range, - dependencies, - false + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "ModuleChunkLoadingPlugin", + compilation => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const chunkLoading = + (options && options.chunkLoading) || globalChunkLoading; + return chunkLoading === "import"; + }; + const onceForChunkSet = new WeakSet(); + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new ModuleChunkLoadingRuntimeModule(set) ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - } + }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("ModuleChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap("ModuleChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.externalInstallChunk) + .tap("ModuleChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap("ModuleChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.externalInstallChunk) + .tap("ModuleChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + compilation.addRuntimeModule( + chunk, + new ExportWebpackRequireRuntimeModule() + ); + }); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("ModuleChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.getChunkScriptFilename); + }); } ); } -}; +} -module.exports.harmonySpecifierTag = harmonySpecifierTag; -module.exports.getAssertions = getAssertions; +module.exports = ModuleChunkLoadingPlugin; /***/ }), -/***/ 73132: +/***/ 64747: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const makeSerializable = __webpack_require__(33032); -const HarmonyImportDependency = __webpack_require__(57154); +const { SyncWaterfallHook } = __webpack_require__(6967); +const Compilation = __webpack_require__(85720); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); +const { + getChunkFilenameTemplate, + chunkHasJs +} = __webpack_require__(89464); +const { getInitialChunkIds } = __webpack_require__(98124); +const compileBooleanMatcher = __webpack_require__(29404); +const { getUndoPath } = __webpack_require__(82186); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../InitFragment")} InitFragment */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("../Chunk")} Chunk */ -class HarmonyImportSideEffectDependency extends HarmonyImportDependency { - constructor(request, sourceOrder, assertions) { - super(request, sourceOrder, assertions); - } +/** + * @typedef {Object} JsonpCompilationPluginHooks + * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload + * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch + */ - get type() { - return "harmony side effect evaluation"; - } +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); +class ModuleChunkLoadingRuntimeModule extends RuntimeModule { /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active + * @param {Compilation} compilation the compilation + * @returns {JsonpCompilationPluginHooks} hooks */ - getCondition(moduleGraph) { - return connection => { - const refModule = connection.resolvedModule; - if (!refModule) return true; - return refModule.getSideEffectsConnectionState(moduleGraph); - }; + 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 = { + linkPreload: new SyncWaterfallHook(["source", "chunk"]), + linkPrefetch: new SyncWaterfallHook(["source", "chunk"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; } - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules - */ - getModuleEvaluationSideEffectsState(moduleGraph) { - const refModule = moduleGraph.getModule(this); - if (!refModule) return true; - return refModule.getSideEffectsConnectionState(moduleGraph); + constructor(runtimeRequirements) { + super("import chunk loading", RuntimeModule.STAGE_ATTACH); + this._runtimeRequirements = runtimeRequirements; } -} - -makeSerializable( - HarmonyImportSideEffectDependency, - "webpack/lib/dependencies/HarmonyImportSideEffectDependency" -); -HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends ( - HarmonyImportDependency.Template -) { /** - * @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} + * @returns {string} runtime code */ - apply(dependency, source, templateContext) { - const { moduleGraph, concatenationScope } = templateContext; - if (concatenationScope) { - const module = moduleGraph.getModule(dependency); - if (concatenationScope.isModuleInScope(module)) { - return; - } - } - super.apply(dependency, source, templateContext); - } -}; - -module.exports = HarmonyImportSideEffectDependency; - - -/***/ }), - -/***/ 14077: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Dependency = __webpack_require__(54912); -const { - getDependencyUsedByExportsCondition -} = __webpack_require__(38988); -const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const HarmonyImportDependency = __webpack_require__(57154); + generate() { + const { compilation, chunk } = this; + const { + runtimeTemplate, + chunkGraph, + outputOptions: { importFunctionName, importMetaName } + } = compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI); + const withExternalInstallChunk = this._runtimeRequirements.has( + RuntimeGlobals.externalInstallChunk + ); + const withLoading = this._runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withOnChunkLoad = this._runtimeRequirements.has( + RuntimeGlobals.onChunksLoaded + ); + const withHmr = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); + const hasJsMatcher = compileBooleanMatcher(conditionMap); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + const outputName = this.compilation.getPath( + getChunkFilenameTemplate(chunk, this.compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath( + outputName, + this.compilation.outputOptions.path, + true + ); -const idsSymbol = Symbol("HarmonyImportSpecifierDependency.ids"); + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_module` + : undefined; -const { ExportPresenceModes } = HarmonyImportDependency; - -class HarmonyImportSpecifierDependency extends HarmonyImportDependency { - constructor( - request, - sourceOrder, - ids, - name, - range, - exportPresenceMode, - assertions - ) { - super(request, sourceOrder, assertions); - this.ids = ids; - this.name = name; - this.range = range; - this.exportPresenceMode = exportPresenceMode; - this.namespaceObjectAsContext = false; - this.call = undefined; - this.directImport = undefined; - this.shorthand = undefined; - this.asiSafe = undefined; - /** @type {Set | boolean} */ - this.usedByExports = undefined; - } - - // TODO webpack 6 remove - get id() { - throw new Error("id was renamed to ids and type changed to string[]"); - } - - // TODO webpack 6 remove - getId() { - throw new Error("id was renamed to ids and type changed to string[]"); - } - - // TODO webpack 6 remove - setId() { - throw new Error("id was renamed to ids and type changed to string[]"); - } - - get type() { - return "harmony import specifier"; - } - - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {string[]} the imported ids - */ - getIds(moduleGraph) { - const meta = moduleGraph.getMetaIfExisting(this); - if (meta === undefined) return this.ids; - const ids = meta[idsSymbol]; - return ids !== undefined ? ids : this.ids; + return Template.asString([ + withBaseURI + ? Template.asString([ + `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify( + rootOutputDir + )}, ${importMetaName}.url);` + ]) + : "// no baseURI", + "", + "// object to store loaded and loading chunks", + "// undefined = chunk not loaded, null = chunk preloaded/prefetched", + "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join( + ",\n" + ) + ), + "};", + "", + withLoading || withExternalInstallChunk + ? `var installChunk = ${runtimeTemplate.basicFunction("data", [ + runtimeTemplate.destructureObject( + ["ids", "modules", "runtime"], + "data" + ), + '// add "modules" to the modules object,', + '// then flag all "ids" as loaded and fire callback', + "var moduleId, chunkId, i = 0;", + "for(moduleId in modules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(modules, moduleId)) {`, + Template.indent( + `${RuntimeGlobals.moduleFactories}[moduleId] = modules[moduleId];` + ), + "}" + ]), + "}", + "if(runtime) runtime(__webpack_require__);", + "for(;i < ids.length; i++) {", + Template.indent([ + "chunkId = ids[i];", + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`, + Template.indent("installedChunks[chunkId][0]();"), + "}", + "installedChunks[ids[i]] = 0;" + ]), + "}", + withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" + ])}` + : "// no install chunk", + "", + withLoading + ? Template.asString([ + `${fn}.j = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasJsMatcher !== false + ? Template.indent([ + "// import() chunk loading for javascript", + `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + "", + '// a Promise means "currently loading".', + "if(installedChunkData) {", + Template.indent([ + "promises.push(installedChunkData[1]);" + ]), + "} else {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent([ + "// setup Promise in chunk cache", + `var promise = ${importFunctionName}(${JSON.stringify( + rootOutputDir + )} + ${ + RuntimeGlobals.getChunkScriptFilename + }(chunkId)).then(installChunk, ${runtimeTemplate.basicFunction( + "e", + [ + "if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;", + "throw e;" + ] + )});`, + `var promise = Promise.race([promise, new Promise(${runtimeTemplate.expressionFunction( + `installedChunkData = installedChunks[chunkId] = [resolve]`, + "resolve" + )})])`, + `promises.push(installedChunkData[1] = promise);` + ]), + "} else installedChunks[chunkId] = 0;" + ]), + "}" + ]), + "}" + ]) + : Template.indent(["installedChunks[chunkId] = 0;"]) + )};` + ]) + : "// no chunk on demand loading", + "", + withExternalInstallChunk + ? Template.asString([ + `${RuntimeGlobals.externalInstallChunk} = installChunk;` + ]) + : "// no external install chunk", + "", + withOnChunkLoad + ? `${ + RuntimeGlobals.onChunksLoaded + }.j = ${runtimeTemplate.returningFunction( + "installedChunks[chunkId] === 0", + "chunkId" + )};` + : "// no on chunks loaded" + ]); } +} - /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {string[]} ids the imported ids - * @returns {void} - */ - setIds(moduleGraph, ids) { - moduleGraph.getMeta(this)[idsSymbol] = ids; - } +module.exports = ModuleChunkLoadingRuntimeModule; - /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active - */ - getCondition(moduleGraph) { - return getDependencyUsedByExportsCondition( - this, - this.usedByExports, - moduleGraph - ); - } - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules - */ - getModuleEvaluationSideEffectsState(moduleGraph) { - return false; - } +/***/ }), - /** - * 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) { - let ids = this.getIds(moduleGraph); - if (ids.length === 0) return Dependency.EXPORTS_OBJECT_REFERENCED; - let namespaceObjectAsContext = this.namespaceObjectAsContext; - if (ids[0] === "default") { - const selfModule = moduleGraph.getParentModule(this); - const importedModule = moduleGraph.getModule(this); - switch ( - importedModule.getExportsType( - moduleGraph, - selfModule.buildMeta.strictHarmonyModule - ) - ) { - case "default-only": - case "default-with-named": - if (ids.length === 1) return Dependency.EXPORTS_OBJECT_REFERENCED; - ids = ids.slice(1); - namespaceObjectAsContext = true; - break; - case "dynamic": - return Dependency.EXPORTS_OBJECT_REFERENCED; - } - } +/***/ 16734: +/***/ (function(module) { - if ( - this.call && - !this.directImport && - (namespaceObjectAsContext || ids.length > 1) - ) { - if (ids.length === 1) return Dependency.EXPORTS_OBJECT_REFERENCED; - ids = ids.slice(0, -1); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - return [ids]; - } - /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {number} effective mode - */ - _getEffectiveExportPresenceLevel(moduleGraph) { - if (this.exportPresenceMode !== ExportPresenceModes.AUTO) - return this.exportPresenceMode; - return moduleGraph.getParentModule(this).buildMeta.strictHarmonyModule - ? ExportPresenceModes.ERROR - : ExportPresenceModes.WARN; - } - /** - * Returns warnings - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} warnings - */ - getWarnings(moduleGraph) { - const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); - if (exportsPresence === ExportPresenceModes.WARN) { - return this._getErrors(moduleGraph); - } - return null; - } +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Dependency").SourcePosition} SourcePosition */ - /** - * Returns errors - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} errors - */ - getErrors(moduleGraph) { - const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); - if (exportsPresence === ExportPresenceModes.ERROR) { - return this._getErrors(moduleGraph); +/** + * @param {SourcePosition} pos position + * @returns {string} formatted position + */ +const formatPosition = pos => { + if (pos && typeof pos === "object") { + if ("line" in pos && "column" in pos) { + return `${pos.line}:${pos.column}`; + } else if ("line" in pos) { + return `${pos.line}:?`; } - return null; - } - - /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[] | undefined} errors - */ - _getErrors(moduleGraph) { - const ids = this.getIds(moduleGraph); - return this.getLinkingErrors( - moduleGraph, - ids, - `(imported as '${this.name}')` - ); - } - - /** - * 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 0; - } - - serialize(context) { - const { write } = context; - write(this.ids); - write(this.name); - write(this.range); - write(this.exportPresenceMode); - write(this.namespaceObjectAsContext); - write(this.call); - write(this.directImport); - write(this.shorthand); - write(this.asiSafe); - write(this.usedByExports); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.ids = read(); - this.name = read(); - this.range = read(); - this.exportPresenceMode = read(); - this.namespaceObjectAsContext = read(); - this.call = read(); - this.directImport = read(); - this.shorthand = read(); - this.asiSafe = read(); - this.usedByExports = read(); - super.deserialize(context); } -} - -makeSerializable( - HarmonyImportSpecifierDependency, - "webpack/lib/dependencies/HarmonyImportSpecifierDependency" -); - -HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate extends ( - HarmonyImportDependency.Template -) { - /** - * @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 dep = /** @type {HarmonyImportSpecifierDependency} */ (dependency); - const { moduleGraph, module, runtime, concatenationScope } = - templateContext; - const connection = moduleGraph.getConnection(dep); - // Skip rendering depending when dependency is conditional - if (connection && !connection.isTargetActive(runtime)) return; - - const ids = dep.getIds(moduleGraph); + return ""; +}; - let exportExpr; - if ( - connection && - concatenationScope && - concatenationScope.isModuleInScope(connection.module) - ) { - if (ids.length === 0) { - exportExpr = concatenationScope.createModuleReference( - connection.module, - { - asiSafe: dep.asiSafe - } - ); - } else if (dep.namespaceObjectAsContext && ids.length === 1) { - exportExpr = - concatenationScope.createModuleReference(connection.module, { - asiSafe: dep.asiSafe - }) + propertyAccess(ids); +/** + * @param {DependencyLocation} loc location + * @returns {string} formatted location + */ +const formatLocation = loc => { + if (loc && typeof loc === "object") { + if ("start" in loc && loc.start && "end" in loc && loc.end) { + if ( + typeof loc.start === "object" && + typeof loc.start.line === "number" && + typeof loc.end === "object" && + typeof loc.end.line === "number" && + typeof loc.end.column === "number" && + loc.start.line === loc.end.line + ) { + return `${formatPosition(loc.start)}-${loc.end.column}`; + } else if ( + typeof loc.start === "object" && + typeof loc.start.line === "number" && + typeof loc.start.column !== "number" && + typeof loc.end === "object" && + typeof loc.end.line === "number" && + typeof loc.end.column !== "number" + ) { + return `${loc.start.line}-${loc.end.line}`; } else { - exportExpr = concatenationScope.createModuleReference( - connection.module, - { - ids, - call: dep.call, - directImport: dep.directImport, - asiSafe: dep.asiSafe - } - ); + return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; } - } else { - super.apply(dependency, source, templateContext); - - const { runtimeTemplate, initFragments, runtimeRequirements } = - templateContext; - - exportExpr = runtimeTemplate.exportFromImport({ - moduleGraph, - module: moduleGraph.getModule(dep), - request: dep.request, - exportName: ids, - originModule: module, - asiSafe: dep.shorthand ? true : dep.asiSafe, - isCall: dep.call, - callContext: !dep.directImport, - defaultInterop: true, - importVar: dep.getImportVar(moduleGraph), - initFragments, - runtime, - runtimeRequirements - }); } - if (dep.shorthand) { - source.insert(dep.range[1], `: ${exportExpr}`); - } else { - source.replace(dep.range[0], dep.range[1] - 1, exportExpr); + if ("start" in loc && loc.start) { + return formatPosition(loc.start); + } + if ("name" in loc && "index" in loc) { + return `${loc.name}[${loc.index}]`; + } + if ("name" in loc) { + return loc.name; } } + return ""; }; -module.exports = HarmonyImportSpecifierDependency; +module.exports = formatLocation; /***/ }), -/***/ 39029: +/***/ 27899: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -86918,160 +85479,46 @@ module.exports = HarmonyImportSpecifierDependency; -const HarmonyAcceptDependency = __webpack_require__(23624); -const HarmonyAcceptImportDependency = __webpack_require__(99843); -const HarmonyCompatibilityDependency = __webpack_require__(72906); -const HarmonyExportExpressionDependency = __webpack_require__(51340); -const HarmonyExportHeaderDependency = __webpack_require__(38873); -const HarmonyExportImportedSpecifierDependency = __webpack_require__(67157); -const HarmonyExportSpecifierDependency = __webpack_require__(48567); -const HarmonyImportSideEffectDependency = __webpack_require__(73132); -const HarmonyImportSpecifierDependency = __webpack_require__(14077); - -const HarmonyDetectionParserPlugin = __webpack_require__(17223); -const HarmonyExportDependencyParserPlugin = __webpack_require__(93466); -const HarmonyImportDependencyParserPlugin = __webpack_require__(20862); -const HarmonyTopLevelThisParserPlugin = __webpack_require__(63232); - -/** @typedef {import("../Compiler")} Compiler */ +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); -class HarmonyModulesPlugin { - constructor(options) { - this.options = options; +class HotModuleReplacementRuntimeModule extends RuntimeModule { + constructor() { + super("hot module replacement", RuntimeModule.STAGE_BASIC); } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @returns {string} runtime code */ - apply(compiler) { - compiler.hooks.compilation.tap( - "HarmonyModulesPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyTemplates.set( - HarmonyCompatibilityDependency, - new HarmonyCompatibilityDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyImportSideEffectDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - HarmonyImportSideEffectDependency, - new HarmonyImportSideEffectDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyImportSpecifierDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - HarmonyImportSpecifierDependency, - new HarmonyImportSpecifierDependency.Template() - ); - - compilation.dependencyTemplates.set( - HarmonyExportHeaderDependency, - new HarmonyExportHeaderDependency.Template() - ); - - compilation.dependencyTemplates.set( - HarmonyExportExpressionDependency, - new HarmonyExportExpressionDependency.Template() - ); - - compilation.dependencyTemplates.set( - HarmonyExportSpecifierDependency, - new HarmonyExportSpecifierDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyExportImportedSpecifierDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - HarmonyExportImportedSpecifierDependency, - new HarmonyExportImportedSpecifierDependency.Template() - ); - - compilation.dependencyTemplates.set( - HarmonyAcceptDependency, - new HarmonyAcceptDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyAcceptImportDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - HarmonyAcceptImportDependency, - new HarmonyAcceptImportDependency.Template() - ); - - const handler = (parser, parserOptions) => { - // TODO webpack 6: rename harmony to esm or module - if (parserOptions.harmony !== undefined && !parserOptions.harmony) - return; - - new HarmonyDetectionParserPlugin(this.options).apply(parser); - new HarmonyImportDependencyParserPlugin(parserOptions).apply(parser); - new HarmonyExportDependencyParserPlugin(parserOptions).apply(parser); - new HarmonyTopLevelThisParserPlugin().apply(parser); - }; - - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("HarmonyModulesPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("HarmonyModulesPlugin", handler); - } - ); - } -} -module.exports = HarmonyModulesPlugin; - - -/***/ }), - -/***/ 63232: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ - - - -const ConstDependency = __webpack_require__(76911); -const HarmonyExports = __webpack_require__(39211); - -class HarmonyTopLevelThisParserPlugin { - apply(parser) { - parser.hooks.expression - .for("this") - .tap("HarmonyTopLevelThisParserPlugin", node => { - if (!parser.scope.topLevelScope) return; - if (HarmonyExports.isEnabled(parser.state)) { - const dep = new ConstDependency("undefined", node.range, null); - dep.loc = node.loc; - parser.state.module.addPresentationalDependency(dep); - return this; - } - }); + generate() { + return Template.getFunctionContent( + require('./HotModuleReplacement.runtime.js') + ) + .replace(/\$getFullHash\$/g, RuntimeGlobals.getFullHash) + .replace( + /\$interceptModuleExecution\$/g, + RuntimeGlobals.interceptModuleExecution + ) + .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) + .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) + .replace(/\$hmrDownloadManifest\$/g, RuntimeGlobals.hmrDownloadManifest) + .replace( + /\$hmrInvalidateModuleHandlers\$/g, + RuntimeGlobals.hmrInvalidateModuleHandlers + ) + .replace( + /\$hmrDownloadUpdateHandlers\$/g, + RuntimeGlobals.hmrDownloadUpdateHandlers + ); } } -module.exports = HarmonyTopLevelThisParserPlugin; +module.exports = HotModuleReplacementRuntimeModule; /***/ }), -/***/ 1902: +/***/ 79040: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -87082,817 +85529,775 @@ module.exports = HarmonyTopLevelThisParserPlugin; -const makeSerializable = __webpack_require__(33032); -const ContextDependency = __webpack_require__(88101); -const ContextDependencyTemplateAsRequireCall = __webpack_require__(75815); +const { RawSource } = __webpack_require__(51255); +const AsyncDependenciesBlock = __webpack_require__(47736); +const Dependency = __webpack_require__(54912); +const Module = __webpack_require__(73208); +const ModuleFactory = __webpack_require__(51010); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const CommonJsRequireDependency = __webpack_require__(21264); +const { registerNotSerializable } = __webpack_require__(8282); -class ImportContextDependency extends ContextDependency { - constructor(options, range, valueRange) { - super(options); +/** @typedef {import("../../declarations/WebpackOptions")} WebpackOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").BuildMeta} BuildMeta */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../dependencies/HarmonyImportDependency")} HarmonyImportDependency */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ - this.range = range; - this.valueRange = valueRange; +/** + * @typedef {Object} BackendApi + * @property {function(Error=): void} dispose + * @property {function(Module): { client: string, data: string, active: boolean }} module + */ + +const HMR_DEPENDENCY_TYPES = new Set([ + "import.meta.webpackHot.accept", + "import.meta.webpackHot.decline", + "module.hot.accept", + "module.hot.decline" +]); + +/** + * @param {undefined|string|RegExp|Function} test test option + * @param {Module} module the module + * @returns {boolean} true, if the module should be selected + */ +const checkTest = (test, module) => { + if (test === undefined) return true; + if (typeof test === "function") { + return test(module); + } + if (typeof test === "string") { + const name = module.nameForCondition(); + return name && name.startsWith(test); + } + if (test instanceof RegExp) { + const name = module.nameForCondition(); + return name && test.test(name); } + return false; +}; - get type() { - return `import() context ${this.options.mode}`; +const TYPES = new Set(["javascript"]); + +class LazyCompilationDependency extends Dependency { + constructor(proxyModule) { + super(); + this.proxyModule = proxyModule; } get category() { return "esm"; } - serialize(context) { - const { write } = context; - - write(this.range); - write(this.valueRange); - - super.serialize(context); + get type() { + return "lazy import()"; } - deserialize(context) { - const { read } = context; - - this.range = read(); - this.valueRange = read(); - - super.deserialize(context); + /** + * @returns {string | null} an identifier to merge equal requests + */ + getResourceIdentifier() { + return this.proxyModule.originalModule.identifier(); } } -makeSerializable( - ImportContextDependency, - "webpack/lib/dependencies/ImportContextDependency" -); - -ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; - -module.exports = ImportContextDependency; - - -/***/ }), - -/***/ 89376: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - +registerNotSerializable(LazyCompilationDependency); -const Dependency = __webpack_require__(54912); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); +class LazyCompilationProxyModule extends Module { + constructor(context, originalModule, request, client, data, active) { + super("lazy-compilation-proxy", context, originalModule.layer); + this.originalModule = originalModule; + this.request = request; + this.client = client; + this.data = data; + this.active = active; + } -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return `lazy-compilation-proxy|${this.originalModule.identifier()}`; + } -class ImportDependency extends ModuleDependency { /** - * @param {string} request the request - * @param {[number, number]} range expression range - * @param {string[][]=} referencedExports list of referenced exports + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module */ - constructor(request, range, referencedExports) { - super(request); - this.range = range; - this.referencedExports = referencedExports; + readableIdentifier(requestShortener) { + return `lazy-compilation-proxy ${this.originalModule.readableIdentifier( + requestShortener + )}`; } - get type() { - return "import()"; + /** + * 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 {LazyCompilationProxyModule} */ (module); + this.originalModule = m.originalModule; + this.request = m.request; + this.client = m.client; + this.data = m.data; + this.active = m.active; } - get category() { - return "esm"; + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return `${this.originalModule.libIdent(options)}!lazy-compilation-proxy`; } /** - * 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 + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} */ - getReferencedExports(moduleGraph, runtime) { - return this.referencedExports - ? this.referencedExports.map(e => ({ - name: e, - canMangle: false - })) - : Dependency.EXPORTS_OBJECT_REFERENCED; + needBuild(context, callback) { + callback(null, !this.buildInfo || this.buildInfo.active !== this.active); } - serialize(context) { - context.write(this.range); - context.write(this.referencedExports); - super.serialize(context); + /** + * @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.buildInfo = { + active: this.active + }; + /** @type {BuildMeta} */ + this.buildMeta = {}; + this.clearDependenciesAndBlocks(); + const dep = new CommonJsRequireDependency(this.client); + this.addDependency(dep); + if (this.active) { + const dep = new LazyCompilationDependency(this); + const block = new AsyncDependenciesBlock({}); + block.addDependency(dep); + this.addBlock(block); + } + callback(); } - deserialize(context) { - this.range = context.read(); - this.referencedExports = context.read(); - super.deserialize(context); + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; } -} -makeSerializable(ImportDependency, "webpack/lib/dependencies/ImportDependency"); + /** + * @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 200; + } -ImportDependency.Template = class ImportDependencyTemplate extends ( - ModuleDependency.Template -) { /** - * @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} + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - apply( - dependency, - source, - { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {ImportDependency} */ (dependency); - const block = /** @type {AsyncDependenciesBlock} */ ( - moduleGraph.getParentBlock(dep) + codeGeneration({ runtimeTemplate, chunkGraph, moduleGraph }) { + const sources = new Map(); + const runtimeRequirements = new Set(); + runtimeRequirements.add(RuntimeGlobals.module); + const clientDep = /** @type {CommonJsRequireDependency} */ ( + this.dependencies[0] ); - const content = runtimeTemplate.moduleNamespacePromise({ - chunkGraph, - block: block, - module: moduleGraph.getModule(dep), - request: dep.request, - strict: module.buildMeta.strictHarmonyModule, - message: "import()", + const clientModule = moduleGraph.getModule(clientDep); + const block = this.blocks[0]; + const client = Template.asString([ + `var client = ${runtimeTemplate.moduleExports({ + module: clientModule, + chunkGraph, + request: clientDep.userRequest, + runtimeRequirements + })}`, + `var data = ${JSON.stringify(this.data)};` + ]); + const keepActive = Template.asString([ + `var dispose = client.keepAlive({ data: data, active: ${JSON.stringify( + !!block + )}, module: module, onError: onError });` + ]); + let source; + if (block) { + const dep = block.dependencies[0]; + const module = moduleGraph.getModule(dep); + source = Template.asString([ + client, + `module.exports = ${runtimeTemplate.moduleNamespacePromise({ + chunkGraph, + block, + module, + request: this.request, + strict: false, // TODO this should be inherited from the original module + message: "import()", + runtimeRequirements + })};`, + "if (module.hot) {", + Template.indent([ + "module.hot.accept();", + `module.hot.accept(${JSON.stringify( + chunkGraph.getModuleId(module) + )}, function() { module.hot.invalidate(); });`, + "module.hot.dispose(function(data) { delete data.resolveSelf; dispose(data); });", + "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);" + ]), + "}", + "function onError() { /* ignore */ }", + keepActive + ]); + } else { + source = Template.asString([ + client, + "var resolveSelf, onError;", + `module.exports = new Promise(function(resolve, reject) { resolveSelf = resolve; onError = reject; });`, + "if (module.hot) {", + Template.indent([ + "module.hot.accept();", + "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);", + "module.hot.dispose(function(data) { data.resolveSelf = resolveSelf; dispose(data); });" + ]), + "}", + keepActive + ]); + } + sources.set("javascript", new RawSource(source)); + return { + sources, runtimeRequirements - }); - - source.replace(dep.range[0], dep.range[1] - 1, content); + }; } -}; - -module.exports = ImportDependency; - - -/***/ }), - -/***/ 50718: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const ImportDependency = __webpack_require__(89376); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ - -class ImportEagerDependency extends ImportDependency { /** - * @param {string} request the request - * @param {[number, number]} range expression range - * @param {string[][]=} referencedExports list of referenced exports + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} */ - constructor(request, range, referencedExports) { - super(request, range, referencedExports); + updateHash(hash, context) { + super.updateHash(hash, context); + hash.update(this.active ? "active" : ""); + hash.update(JSON.stringify(this.data)); } +} - get type() { - return "import() eager"; - } +registerNotSerializable(LazyCompilationProxyModule); - get category() { - return "esm"; +class LazyCompilationDependencyFactory extends ModuleFactory { + constructor(factory) { + super(); + this._factory = factory; } -} -makeSerializable( - ImportEagerDependency, - "webpack/lib/dependencies/ImportEagerDependency" -); - -ImportEagerDependency.Template = class ImportEagerDependencyTemplate extends ( - ImportDependency.Template -) { /** - * @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 + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback * @returns {void} */ - apply( - dependency, - source, - { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {ImportEagerDependency} */ (dependency); - const content = runtimeTemplate.moduleNamespacePromise({ - chunkGraph, - module: moduleGraph.getModule(dep), - request: dep.request, - strict: module.buildMeta.strictHarmonyModule, - message: "import() eager", - runtimeRequirements + create(data, callback) { + const dependency = /** @type {LazyCompilationDependency} */ ( + data.dependencies[0] + ); + callback(null, { + module: dependency.proxyModule.originalModule }); - - source.replace(dep.range[0], dep.range[1] - 1, content); - } -}; - -module.exports = ImportEagerDependency; - - -/***/ }), - -/***/ 51274: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - - - -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyTemplateAsId = __webpack_require__(80825); - -class ImportMetaHotAcceptDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; - this.weak = true; } +} - get type() { - return "import.meta.webpackHot.accept"; +class LazyCompilationPlugin { + /** + * @param {Object} options options + * @param {(function(Compiler, function(Error?, BackendApi?): void): void) | function(Compiler): Promise} options.backend the backend + * @param {boolean} options.entries true, when entries are lazy compiled + * @param {boolean} options.imports true, when import() modules are lazy compiled + * @param {RegExp | string | (function(Module): boolean)} options.test additional filter for lazy compiled entrypoint modules + */ + constructor({ backend, entries, imports, test }) { + this.backend = backend; + this.entries = entries; + this.imports = imports; + this.test = test; } + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + let backend; + compiler.hooks.beforeCompile.tapAsync( + "LazyCompilationPlugin", + (params, callback) => { + if (backend !== undefined) return callback(); + const promise = this.backend(compiler, (err, result) => { + if (err) return callback(err); + backend = result; + callback(); + }); + if (promise && promise.then) { + promise.then(b => { + backend = b; + callback(); + }, callback); + } + } + ); + compiler.hooks.thisCompilation.tap( + "LazyCompilationPlugin", + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.module.tap( + "LazyCompilationPlugin", + (originalModule, createData, resolveData) => { + if ( + resolveData.dependencies.every(dep => + HMR_DEPENDENCY_TYPES.has(dep.type) + ) + ) { + // for HMR only resolving, try to determine if the HMR accept/decline refers to + // an import() or not + const hmrDep = resolveData.dependencies[0]; + const originModule = + compilation.moduleGraph.getParentModule(hmrDep); + const isReferringToDynamicImport = originModule.blocks.some( + block => + block.dependencies.some( + dep => + dep.type === "import()" && + /** @type {HarmonyImportDependency} */ (dep).request === + hmrDep.request + ) + ); + if (!isReferringToDynamicImport) return; + } else if ( + !resolveData.dependencies.every( + dep => + HMR_DEPENDENCY_TYPES.has(dep.type) || + (this.imports && + (dep.type === "import()" || + dep.type === "import() context element")) || + (this.entries && dep.type === "entry") + ) + ) + return; + if ( + /webpack[/\\]hot[/\\]|webpack-dev-server[/\\]client|webpack-hot-middleware[/\\]client/.test( + resolveData.request + ) || + !checkTest(this.test, originalModule) + ) + return; + const moduleInfo = backend.module(originalModule); + if (!moduleInfo) return; + const { client, data, active } = moduleInfo; - get category() { - return "esm"; + return new LazyCompilationProxyModule( + compiler.context, + originalModule, + resolveData.request, + client, + data, + active + ); + } + ); + compilation.dependencyFactories.set( + LazyCompilationDependency, + new LazyCompilationDependencyFactory() + ); + } + ); + compiler.hooks.shutdown.tapAsync("LazyCompilationPlugin", callback => { + backend.dispose(callback); + }); } } -makeSerializable( - ImportMetaHotAcceptDependency, - "webpack/lib/dependencies/ImportMetaHotAcceptDependency" -); - -ImportMetaHotAcceptDependency.Template = ModuleDependencyTemplateAsId; - -module.exports = ImportMetaHotAcceptDependency; +module.exports = LazyCompilationPlugin; /***/ }), -/***/ 53141: +/***/ 17781: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyTemplateAsId = __webpack_require__(80825); +/** @typedef {import("http").ServerOptions} HttpServerOptions */ +/** @typedef {import("https").ServerOptions} HttpsServerOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LazyCompilationDefaultBackendOptions} LazyCompilationDefaultBackendOptions */ +/** @typedef {import("../Compiler")} Compiler */ -class ImportMetaHotDeclineDependency extends ModuleDependency { - constructor(request, range) { - super(request); +/** + * @callback BackendHandler + * @param {Compiler} compiler compiler + * @param {function((Error | null)=, any=): void} callback callback + * @returns {void} + */ - this.range = range; - this.weak = true; - } +/** + * @param {Omit & { client: NonNullable}} options additional options for the backend + * @returns {BackendHandler} backend + */ +module.exports = options => (compiler, callback) => { + const logger = compiler.getInfrastructureLogger("LazyCompilationBackend"); + const activeModules = new Map(); + const prefix = "/lazy-compilation-using-"; - get type() { - return "import.meta.webpackHot.decline"; - } + const isHttps = + options.protocol === "https" || + (typeof options.server === "object" && + ("key" in options.server || "pfx" in options.server)); - get category() { - return "esm"; - } -} + const createServer = + typeof options.server === "function" + ? options.server + : (() => { + const http = isHttps ? __webpack_require__(95687) : __webpack_require__(13685); + return http.createServer.bind(http, options.server); + })(); + const listen = + typeof options.listen === "function" + ? options.listen + : server => { + let listen = options.listen; + if (typeof listen === "object" && !("port" in listen)) + listen = { ...listen, port: undefined }; + server.listen(listen); + }; -makeSerializable( - ImportMetaHotDeclineDependency, - "webpack/lib/dependencies/ImportMetaHotDeclineDependency" -); + const protocol = options.protocol || (isHttps ? "https" : "http"); -ImportMetaHotDeclineDependency.Template = ModuleDependencyTemplateAsId; + const requestListener = (req, res) => { + const keys = req.url.slice(prefix.length).split("@"); + req.socket.on("close", () => { + setTimeout(() => { + for (const key of keys) { + const oldValue = activeModules.get(key) || 0; + activeModules.set(key, oldValue - 1); + if (oldValue === 1) { + logger.log( + `${key} is no longer in use. Next compilation will skip this module.` + ); + } + } + }, 120000); + }); + req.socket.setNoDelay(true); + res.writeHead(200, { + "content-type": "text/event-stream", + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "*", + "Access-Control-Allow-Headers": "*" + }); + res.write("\n"); + let moduleActivated = false; + for (const key of keys) { + const oldValue = activeModules.get(key) || 0; + activeModules.set(key, oldValue + 1); + if (oldValue === 0) { + logger.log(`${key} is now in use and will be compiled.`); + moduleActivated = true; + } + } + if (moduleActivated && compiler.watching) compiler.watching.invalidate(); + }; -module.exports = ImportMetaHotDeclineDependency; + const server = /** @type {import("net").Server} */ (createServer()); + server.on("request", requestListener); + + let isClosing = false; + /** @type {Set} */ + const sockets = new Set(); + server.on("connection", socket => { + sockets.add(socket); + socket.on("close", () => { + sockets.delete(socket); + }); + if (isClosing) socket.destroy(); + }); + server.on("clientError", e => { + if (e.message !== "Server is disposing") logger.warn(e); + }); + server.on("listening", err => { + if (err) return callback(err); + const addr = server.address(); + if (typeof addr === "string") throw new Error("addr must not be a string"); + const urlBase = + addr.address === "::" || addr.address === "0.0.0.0" + ? `${protocol}://localhost:${addr.port}` + : addr.family === "IPv6" + ? `${protocol}://[${addr.address}]:${addr.port}` + : `${protocol}://${addr.address}:${addr.port}`; + logger.log( + `Server-Sent-Events server for lazy compilation open at ${urlBase}.` + ); + callback(null, { + dispose(callback) { + isClosing = true; + // Removing the listener is a workaround for a memory leak in node.js + server.off("request", requestListener); + server.close(err => { + callback(err); + }); + for (const socket of sockets) { + socket.destroy(new Error("Server is disposing")); + } + }, + module(originalModule) { + const key = `${encodeURIComponent( + originalModule.identifier().replace(/\\/g, "/").replace(/@/g, "_") + ).replace(/%(2F|3A|24|26|2B|2C|3B|3D|3A)/g, decodeURIComponent)}`; + const active = activeModules.get(key) > 0; + return { + client: `${options.client}?${encodeURIComponent(urlBase + prefix)}`, + data: key, + active + }; + } + }); + }); + listen(server); +}; /***/ }), -/***/ 17228: +/***/ 64618: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const { pathToFileURL } = __webpack_require__(57310); -const ModuleDependencyWarning = __webpack_require__(29656); -const Template = __webpack_require__(39722); -const BasicEvaluatedExpression = __webpack_require__(950); +const { find } = __webpack_require__(93347); const { - evaluateToIdentifier, - toConstantDependency, - evaluateToString, - evaluateToNumber -} = __webpack_require__(93998); -const memoize = __webpack_require__(78676); -const propertyAccess = __webpack_require__(54190); -const ConstDependency = __webpack_require__(76911); + compareModulesByPreOrderIndexOrIdentifier, + compareModulesByPostOrderIndexOrIdentifier +} = __webpack_require__(29579); -/** @typedef {import("estree").MemberExpression} MemberExpression */ /** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../javascript/JavascriptParser")} Parser */ -const getCriticalDependencyWarning = memoize(() => - __webpack_require__(15427) -); +class ChunkModuleIdRangePlugin { + constructor(options) { + this.options = options; + } -class ImportMetaPlugin { /** - * @param {Compiler} compiler compiler + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap( - "ImportMetaPlugin", - (compilation, { normalModuleFactory }) => { - /** - * @param {NormalModule} module module - * @returns {string} file url - */ - const getUrl = module => { - return pathToFileURL(module.resource).toString(); - }; - /** - * @param {Parser} parser parser - * @param {Object} parserOptions parserOptions - * @returns {void} - */ - const parserHandler = (parser, parserOptions) => { - /// import.meta direct /// - parser.hooks.typeof - .for("import.meta") - .tap( - "ImportMetaPlugin", - toConstantDependency(parser, JSON.stringify("object")) - ); - parser.hooks.expression - .for("import.meta") - .tap("ImportMetaPlugin", metaProperty => { - const CriticalDependencyWarning = getCriticalDependencyWarning(); - parser.state.module.addWarning( - new ModuleDependencyWarning( - parser.state.module, - new CriticalDependencyWarning( - "Accessing import.meta directly is unsupported (only property access is supported)" - ), - metaProperty.loc - ) - ); - const dep = new ConstDependency( - `${parser.isAsiPosition(metaProperty.range[0]) ? ";" : ""}({})`, - metaProperty.range - ); - dep.loc = metaProperty.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); - parser.hooks.evaluateTypeof - .for("import.meta") - .tap("ImportMetaPlugin", evaluateToString("object")); - parser.hooks.evaluateIdentifier.for("import.meta").tap( - "ImportMetaPlugin", - evaluateToIdentifier("import.meta", "import.meta", () => [], true) - ); - - /// import.meta.url /// - parser.hooks.typeof - .for("import.meta.url") - .tap( - "ImportMetaPlugin", - toConstantDependency(parser, JSON.stringify("string")) - ); - parser.hooks.expression - .for("import.meta.url") - .tap("ImportMetaPlugin", expr => { - const dep = new ConstDependency( - JSON.stringify(getUrl(parser.state.module)), - expr.range - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); - parser.hooks.evaluateTypeof - .for("import.meta.url") - .tap("ImportMetaPlugin", evaluateToString("string")); - parser.hooks.evaluateIdentifier - .for("import.meta.url") - .tap("ImportMetaPlugin", expr => { - return new BasicEvaluatedExpression() - .setString(getUrl(parser.state.module)) - .setRange(expr.range); - }); - - /// import.meta.webpack /// - const webpackVersion = parseInt( - (__webpack_require__(32702)/* .version */ .i8), - 10 + const options = this.options; + compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => { + const moduleGraph = compilation.moduleGraph; + compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => { + const chunkGraph = compilation.chunkGraph; + const chunk = find( + compilation.chunks, + chunk => chunk.name === options.name + ); + if (!chunk) { + throw new Error( + `ChunkModuleIdRangePlugin: Chunk with name '${options.name}"' was not found` ); - parser.hooks.typeof - .for("import.meta.webpack") - .tap( - "ImportMetaPlugin", - toConstantDependency(parser, JSON.stringify("number")) - ); - parser.hooks.expression - .for("import.meta.webpack") - .tap( - "ImportMetaPlugin", - toConstantDependency(parser, JSON.stringify(webpackVersion)) - ); - parser.hooks.evaluateTypeof - .for("import.meta.webpack") - .tap("ImportMetaPlugin", evaluateToString("number")); - parser.hooks.evaluateIdentifier - .for("import.meta.webpack") - .tap("ImportMetaPlugin", evaluateToNumber(webpackVersion)); + } - /// Unknown properties /// - parser.hooks.unhandledExpressionMemberChain - .for("import.meta") - .tap("ImportMetaPlugin", (expr, members) => { - const dep = new ConstDependency( - `${Template.toNormalComment( - "unsupported import.meta." + members.join(".") - )} undefined${propertyAccess(members, 1)}`, - expr.range + let chunkModules; + if (options.order) { + let cmpFn; + switch (options.order) { + case "index": + case "preOrderIndex": + cmpFn = compareModulesByPreOrderIndexOrIdentifier(moduleGraph); + break; + case "index2": + case "postOrderIndex": + cmpFn = compareModulesByPostOrderIndexOrIdentifier(moduleGraph); + break; + default: + throw new Error( + "ChunkModuleIdRangePlugin: unexpected value of order" ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); - parser.hooks.evaluate - .for("MemberExpression") - .tap("ImportMetaPlugin", expression => { - const expr = /** @type {MemberExpression} */ (expression); - if ( - expr.object.type === "MetaProperty" && - expr.object.meta.name === "import" && - expr.object.property.name === "meta" && - expr.property.type === - (expr.computed ? "Literal" : "Identifier") - ) { - return new BasicEvaluatedExpression() - .setUndefined() - .setRange(expr.range); - } - }); - }; + } + chunkModules = chunkGraph.getOrderedChunkModules(chunk, cmpFn); + } else { + chunkModules = Array.from(modules) + .filter(m => { + return chunkGraph.isModuleInChunk(m, chunk); + }) + .sort(compareModulesByPreOrderIndexOrIdentifier(moduleGraph)); + } - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("ImportMetaPlugin", parserHandler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("ImportMetaPlugin", parserHandler); - } - ); + let currentId = options.start || 0; + for (let i = 0; i < chunkModules.length; i++) { + const m = chunkModules[i]; + if (m.needId && chunkGraph.getModuleId(m) === null) { + chunkGraph.setModuleId(m, currentId++); + } + if (options.end && currentId > options.end) break; + } + }); + }); } } - -module.exports = ImportMetaPlugin; +module.exports = ChunkModuleIdRangePlugin; /***/ }), -/***/ 88130: +/***/ 8747: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Florent Cailhol @ooflorent */ -const AsyncDependenciesBlock = __webpack_require__(47736); -const CommentCompilationWarning = __webpack_require__(98427); -const UnsupportedFeatureWarning = __webpack_require__(42495); -const ContextDependencyHelpers = __webpack_require__(99630); -const ImportContextDependency = __webpack_require__(1902); -const ImportDependency = __webpack_require__(89376); -const ImportEagerDependency = __webpack_require__(50718); -const ImportWeakDependency = __webpack_require__(82483); +const { compareChunksNatural } = __webpack_require__(29579); +const { + getFullChunkName, + getUsedChunkIds, + assignDeterministicIds +} = __webpack_require__(63290); -/** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */ -/** @typedef {import("../ContextModule").ContextMode} ContextMode */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ -class ImportParserPlugin { +class DeterministicChunkIdsPlugin { constructor(options) { - this.options = options; + this.options = options || {}; } - apply(parser) { - parser.hooks.importCall.tap("ImportParserPlugin", expr => { - const param = parser.evaluateExpression(expr.source); - - let chunkName = null; - /** @type {ContextMode} */ - let mode = "lazy"; - let include = null; - let exclude = null; - /** @type {string[][] | null} */ - let exports = null; - /** @type {RawChunkGroupOptions} */ - const groupOptions = {}; - - const { options: importOptions, errors: commentErrors } = - parser.parseCommentOptions(expr.range); + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "DeterministicChunkIdsPlugin", + compilation => { + compilation.hooks.chunkIds.tap( + "DeterministicChunkIdsPlugin", + chunks => { + const chunkGraph = compilation.chunkGraph; + const context = this.options.context + ? this.options.context + : compiler.context; + const maxLength = this.options.maxLength || 3; - if (commentErrors) { - for (const e of commentErrors) { - const { comment } = e; - parser.state.module.addWarning( - new CommentCompilationWarning( - `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, - comment.loc - ) - ); - } - } + const compareNatural = compareChunksNatural(chunkGraph); - if (importOptions) { - if (importOptions.webpackIgnore !== undefined) { - if (typeof importOptions.webpackIgnore !== "boolean") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, - expr.loc - ) - ); - } else { - // Do not instrument `import()` if `webpackIgnore` is `true` - if (importOptions.webpackIgnore) { - return false; - } - } - } - if (importOptions.webpackChunkName !== undefined) { - if (typeof importOptions.webpackChunkName !== "string") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, - expr.loc - ) - ); - } else { - chunkName = importOptions.webpackChunkName; - } - } - if (importOptions.webpackMode !== undefined) { - if (typeof importOptions.webpackMode !== "string") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackMode\` expected a string, but received: ${importOptions.webpackMode}.`, - expr.loc - ) - ); - } else { - mode = importOptions.webpackMode; - } - } - if (importOptions.webpackPrefetch !== undefined) { - if (importOptions.webpackPrefetch === true) { - groupOptions.prefetchOrder = 0; - } else if (typeof importOptions.webpackPrefetch === "number") { - groupOptions.prefetchOrder = importOptions.webpackPrefetch; - } else { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackPrefetch\` expected true or a number, but received: ${importOptions.webpackPrefetch}.`, - expr.loc - ) - ); - } - } - if (importOptions.webpackPreload !== undefined) { - if (importOptions.webpackPreload === true) { - groupOptions.preloadOrder = 0; - } else if (typeof importOptions.webpackPreload === "number") { - groupOptions.preloadOrder = importOptions.webpackPreload; - } else { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackPreload\` expected true or a number, but received: ${importOptions.webpackPreload}.`, - expr.loc - ) - ); - } - } - if (importOptions.webpackInclude !== undefined) { - if ( - !importOptions.webpackInclude || - importOptions.webpackInclude.constructor.name !== "RegExp" - ) { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackInclude\` expected a regular expression, but received: ${importOptions.webpackInclude}.`, - expr.loc - ) - ); - } else { - include = new RegExp(importOptions.webpackInclude); - } - } - if (importOptions.webpackExclude !== undefined) { - if ( - !importOptions.webpackExclude || - importOptions.webpackExclude.constructor.name !== "RegExp" - ) { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackExclude\` expected a regular expression, but received: ${importOptions.webpackExclude}.`, - expr.loc - ) - ); - } else { - exclude = new RegExp(importOptions.webpackExclude); - } - } - if (importOptions.webpackExports !== undefined) { - if ( - !( - typeof importOptions.webpackExports === "string" || - (Array.isArray(importOptions.webpackExports) && - importOptions.webpackExports.every( - item => typeof item === "string" - )) - ) - ) { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackExports\` expected a string or an array of strings, but received: ${importOptions.webpackExports}.`, - expr.loc - ) + const usedIds = getUsedChunkIds(compilation); + assignDeterministicIds( + Array.from(chunks).filter(chunk => { + return chunk.id === null; + }), + chunk => + getFullChunkName(chunk, chunkGraph, context, compiler.root), + compareNatural, + (chunk, id) => { + const size = usedIds.size; + usedIds.add(`${id}`); + if (size === usedIds.size) return false; + chunk.id = id; + chunk.ids = [id]; + return true; + }, + [Math.pow(10, maxLength)], + 10, + usedIds.size ); - } else { - if (typeof importOptions.webpackExports === "string") { - exports = [[importOptions.webpackExports]]; - } else { - exports = Array.from(importOptions.webpackExports, e => [e]); - } } - } - } - - if (param.isString()) { - if (mode !== "lazy" && mode !== "eager" && mode !== "weak") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackMode\` expected 'lazy', 'eager' or 'weak', but received: ${mode}.`, - expr.loc - ) - ); - } - - if (mode === "eager") { - const dep = new ImportEagerDependency( - param.string, - expr.range, - exports - ); - parser.state.current.addDependency(dep); - } else if (mode === "weak") { - const dep = new ImportWeakDependency( - param.string, - expr.range, - exports - ); - parser.state.current.addDependency(dep); - } else { - const depBlock = new AsyncDependenciesBlock( - { - ...groupOptions, - name: chunkName - }, - expr.loc, - param.string - ); - const dep = new ImportDependency(param.string, expr.range, exports); - dep.loc = expr.loc; - depBlock.addDependency(dep); - parser.state.current.addBlock(depBlock); - } - return true; - } else { - if ( - mode !== "lazy" && - mode !== "lazy-once" && - mode !== "eager" && - mode !== "weak" - ) { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`, - expr.loc - ) - ); - mode = "lazy"; - } - - if (mode === "weak") { - mode = "async-weak"; - } - const dep = ContextDependencyHelpers.create( - ImportContextDependency, - expr.range, - param, - expr, - this.options, - { - chunkName, - groupOptions, - include, - exclude, - mode, - namespaceObject: parser.state.module.buildMeta.strictHarmonyModule - ? "strict" - : true, - typePrefix: "import()", - category: "esm", - referencedExports: exports - }, - parser ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; } - }); + ); } } -module.exports = ImportParserPlugin; +module.exports = DeterministicChunkIdsPlugin; /***/ }), -/***/ 41293: +/***/ 76692: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Florent Cailhol @ooflorent */ -const ImportContextDependency = __webpack_require__(1902); -const ImportDependency = __webpack_require__(89376); -const ImportEagerDependency = __webpack_require__(50718); -const ImportParserPlugin = __webpack_require__(88130); -const ImportWeakDependency = __webpack_require__(82483); +const { + compareModulesByPreOrderIndexOrIdentifier +} = __webpack_require__(29579); +const { + getUsedModuleIdsAndModules, + getFullModuleName, + assignDeterministicIds +} = __webpack_require__(63290); /** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +class DeterministicModuleIdsPlugin { + /** + * @param {Object} options options + * @param {string=} options.context context relative to which module identifiers are computed + * @param {function(Module): boolean=} options.test selector function for modules + * @param {number=} options.maxLength maximum id length in digits (used as starting point) + * @param {number=} options.salt hash salt for ids + * @param {boolean=} options.fixedLength do not increase the maxLength to find an optimal id space size + * @param {boolean=} options.failOnConflict throw an error when id conflicts occur (instead of rehashing) + */ + constructor(options = {}) { + this.options = options; + } -class ImportPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance @@ -87900,70 +86305,64 @@ class ImportPlugin { */ apply(compiler) { compiler.hooks.compilation.tap( - "ImportPlugin", - (compilation, { contextModuleFactory, normalModuleFactory }) => { - compilation.dependencyFactories.set( - ImportDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ImportDependency, - new ImportDependency.Template() - ); - - compilation.dependencyFactories.set( - ImportEagerDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ImportEagerDependency, - new ImportEagerDependency.Template() - ); - - compilation.dependencyFactories.set( - ImportWeakDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ImportWeakDependency, - new ImportWeakDependency.Template() - ); - - compilation.dependencyFactories.set( - ImportContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - ImportContextDependency, - new ImportContextDependency.Template() - ); - - const handler = (parser, parserOptions) => { - if (parserOptions.import !== undefined && !parserOptions.import) - return; - - new ImportParserPlugin(parserOptions).apply(parser); - }; + "DeterministicModuleIdsPlugin", + compilation => { + compilation.hooks.moduleIds.tap("DeterministicModuleIdsPlugin", () => { + const chunkGraph = compilation.chunkGraph; + const context = this.options.context + ? this.options.context + : compiler.context; + const maxLength = this.options.maxLength || 3; + const failOnConflict = this.options.failOnConflict || false; + const fixedLength = this.options.fixedLength || false; + const salt = this.options.salt || 0; + let conflicts = 0; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("ImportPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("ImportPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("ImportPlugin", handler); + const [usedIds, modules] = getUsedModuleIdsAndModules( + compilation, + this.options.test + ); + assignDeterministicIds( + modules, + module => getFullModuleName(module, context, compiler.root), + failOnConflict + ? () => 0 + : compareModulesByPreOrderIndexOrIdentifier( + compilation.moduleGraph + ), + (module, id) => { + const size = usedIds.size; + usedIds.add(`${id}`); + if (size === usedIds.size) { + conflicts++; + return false; + } + chunkGraph.setModuleId(module, id); + return true; + }, + [Math.pow(10, maxLength)], + fixedLength ? 0 : 10, + usedIds.size, + salt + ); + if (failOnConflict && conflicts) + throw new Error( + `Assigning deterministic module ids has lead to ${conflicts} conflict${ + conflicts > 1 ? "s" : "" + }.\nIncrease the 'maxLength' to increase the id space and make conflicts less likely (recommended when there are many conflicts or application is expected to grow), or add an 'salt' number to try another hash starting value in the same id space (recommended when there is only a single conflict).` + ); + }); } ); } } -module.exports = ImportPlugin; + +module.exports = DeterministicModuleIdsPlugin; /***/ }), -/***/ 82483: +/***/ 21825: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -87974,72 +86373,82 @@ module.exports = ImportPlugin; -const makeSerializable = __webpack_require__(33032); -const ImportDependency = __webpack_require__(89376); +const { + compareModulesByPreOrderIndexOrIdentifier +} = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); +const createHash = __webpack_require__(49835); +const { + getUsedModuleIdsAndModules, + getFullModuleName +} = __webpack_require__(63290); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../../declarations/plugins/HashedModuleIdsPlugin").HashedModuleIdsPluginOptions} HashedModuleIdsPluginOptions */ -class ImportWeakDependency extends ImportDependency { +const validate = createSchemaValidation( + __webpack_require__(52210), + () => __webpack_require__(59106), + { + name: "Hashed Module Ids Plugin", + baseDataPath: "options" + } +); + +class HashedModuleIdsPlugin { /** - * @param {string} request the request - * @param {[number, number]} range expression range - * @param {string[][]=} referencedExports list of referenced exports + * @param {HashedModuleIdsPluginOptions=} options options object */ - constructor(request, range, referencedExports) { - super(request, range, referencedExports); - this.weak = true; - } + constructor(options = {}) { + validate(options); - get type() { - return "import() weak"; + /** @type {HashedModuleIdsPluginOptions} */ + this.options = { + context: null, + hashFunction: "md4", + hashDigest: "base64", + hashDigestLength: 4, + ...options + }; } -} -makeSerializable( - ImportWeakDependency, - "webpack/lib/dependencies/ImportWeakDependency" -); + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("HashedModuleIdsPlugin", compilation => { + compilation.hooks.moduleIds.tap("HashedModuleIdsPlugin", () => { + const chunkGraph = compilation.chunkGraph; + const context = this.options.context + ? this.options.context + : compiler.context; -ImportWeakDependency.Template = class ImportDependencyTemplate extends ( - ImportDependency.Template -) { - /** - * @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, - { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {ImportWeakDependency} */ (dependency); - const content = runtimeTemplate.moduleNamespacePromise({ - chunkGraph, - module: moduleGraph.getModule(dep), - request: dep.request, - strict: module.buildMeta.strictHarmonyModule, - message: "import() weak", - weak: true, - runtimeRequirements + const [usedIds, modules] = getUsedModuleIdsAndModules(compilation); + const modulesInNaturalOrder = modules.sort( + compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph) + ); + for (const module of modulesInNaturalOrder) { + const ident = getFullModuleName(module, context, compiler.root); + const hash = createHash(options.hashFunction); + hash.update(ident || ""); + const hashId = /** @type {string} */ ( + hash.digest(options.hashDigest) + ); + let len = options.hashDigestLength; + while (usedIds.has(hashId.substr(0, len))) len++; + const moduleId = hashId.substr(0, len); + chunkGraph.setModuleId(module, moduleId); + usedIds.add(moduleId); + } + }); }); - - source.replace(dep.range[0], dep.range[1] - 1, content); } -}; +} -module.exports = ImportWeakDependency; +module.exports = HashedModuleIdsPlugin; /***/ }), -/***/ 750: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 63290: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -88049,178 +86458,481 @@ module.exports = ImportWeakDependency; -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +const createHash = __webpack_require__(49835); +const { makePathsRelative } = __webpack_require__(82186); +const numberHash = __webpack_require__(70002); +/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ExportSpec} ExportSpec */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {typeof import("../util/Hash")} Hash */ -const getExportsFromData = data => { - if (data && typeof data === "object") { - if (Array.isArray(data)) { - return data.map((item, idx) => { - return { - name: `${idx}`, - canMangle: true, - exports: getExportsFromData(item) - }; - }); - } else { - const exports = []; - for (const key of Object.keys(data)) { - exports.push({ - name: key, - canMangle: true, - exports: getExportsFromData(data[key]) - }); - } - return exports; - } - } - return undefined; +/** + * @param {string} str string to hash + * @param {number} len max length of the hash + * @param {string | Hash} hashFunction hash function to use + * @returns {string} hash + */ +const getHash = (str, len, hashFunction) => { + const hash = createHash(hashFunction); + hash.update(str); + const digest = /** @type {string} */ (hash.digest("hex")); + return digest.substr(0, len); }; -class JsonExportsDependency extends NullDependency { - /** - * @param {(string | ExportSpec)[]} exports json exports - */ - constructor(exports) { - super(); - this.exports = exports; - this._hashUpdate = undefined; - } - - get type() { - return "json exports"; +/** + * @param {string} str the string + * @returns {string} string prefixed by an underscore if it is a number + */ +const avoidNumber = str => { + // max length of a number is 21 chars, bigger numbers a written as "...e+xx" + if (str.length > 21) return str; + const firstChar = str.charCodeAt(0); + // skip everything that doesn't look like a number + // charCodes: "-": 45, "1": 49, "9": 57 + if (firstChar < 49) { + if (firstChar !== 45) return str; + } else if (firstChar > 57) { + return str; } - - /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names - */ - getExports(moduleGraph) { - return { - exports: this.exports, - dependencies: undefined - }; + if (str === +str + "") { + return `_${str}`; } + return str; +}; - /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) { - this._hashUpdate = this.exports - ? JSON.stringify(this.exports) - : "undefined"; - } - hash.update(this._hashUpdate); - } +/** + * @param {string} request the request + * @returns {string} id representation + */ +const requestToId = request => { + return request + .replace(/^(\.\.?\/)+/, "") + .replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_"); +}; +exports.requestToId = requestToId; - serialize(context) { - const { write } = context; - write(this.exports); - super.serialize(context); - } +/** + * @param {string} string the string + * @param {string} delimiter separator for string and hash + * @param {string | Hash} hashFunction hash function to use + * @returns {string} string with limited max length to 100 chars + */ +const shortenLongString = (string, delimiter, hashFunction) => { + if (string.length < 100) return string; + return ( + string.slice(0, 100 - 6 - delimiter.length) + + delimiter + + getHash(string, 6, hashFunction) + ); +}; - deserialize(context) { - const { read } = context; - this.exports = read(); - super.deserialize(context); - } -} +/** + * @param {Module} module the module + * @param {string} context context directory + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} short module name + */ +const getShortModuleName = (module, context, associatedObjectForCache) => { + const libIdent = module.libIdent({ context, associatedObjectForCache }); + if (libIdent) return avoidNumber(libIdent); + const nameForCondition = module.nameForCondition(); + if (nameForCondition) + return avoidNumber( + makePathsRelative(context, nameForCondition, associatedObjectForCache) + ); + return ""; +}; +exports.getShortModuleName = getShortModuleName; -makeSerializable( - JsonExportsDependency, - "webpack/lib/dependencies/JsonExportsDependency" -); +/** + * @param {string} shortName the short name + * @param {Module} module the module + * @param {string} context context directory + * @param {string | Hash} hashFunction hash function to use + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} long module name + */ +const getLongModuleName = ( + shortName, + module, + context, + hashFunction, + associatedObjectForCache +) => { + const fullName = getFullModuleName(module, context, associatedObjectForCache); + return `${shortName}?${getHash(fullName, 4, hashFunction)}`; +}; +exports.getLongModuleName = getLongModuleName; -module.exports = JsonExportsDependency; -module.exports.getExportsFromData = getExportsFromData; +/** + * @param {Module} module the module + * @param {string} context context directory + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} full module name + */ +const getFullModuleName = (module, context, associatedObjectForCache) => { + return makePathsRelative( + context, + module.identifier(), + associatedObjectForCache + ); +}; +exports.getFullModuleName = getFullModuleName; +/** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} context context directory + * @param {string} delimiter delimiter for names + * @param {string | Hash} hashFunction hash function to use + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} short chunk name + */ +const getShortChunkName = ( + chunk, + chunkGraph, + context, + delimiter, + hashFunction, + associatedObjectForCache +) => { + const modules = chunkGraph.getChunkRootModules(chunk); + const shortModuleNames = modules.map(m => + requestToId(getShortModuleName(m, context, associatedObjectForCache)) + ); + chunk.idNameHints.sort(); + const chunkName = Array.from(chunk.idNameHints) + .concat(shortModuleNames) + .filter(Boolean) + .join(delimiter); + return shortenLongString(chunkName, delimiter, hashFunction); +}; +exports.getShortChunkName = getShortChunkName; -/***/ }), +/** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} context context directory + * @param {string} delimiter delimiter for names + * @param {string | Hash} hashFunction hash function to use + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} short chunk name + */ +const getLongChunkName = ( + chunk, + chunkGraph, + context, + delimiter, + hashFunction, + associatedObjectForCache +) => { + const modules = chunkGraph.getChunkRootModules(chunk); + const shortModuleNames = modules.map(m => + requestToId(getShortModuleName(m, context, associatedObjectForCache)) + ); + const longModuleNames = modules.map(m => + requestToId( + getLongModuleName("", m, context, hashFunction, associatedObjectForCache) + ) + ); + chunk.idNameHints.sort(); + const chunkName = Array.from(chunk.idNameHints) + .concat(shortModuleNames, longModuleNames) + .filter(Boolean) + .join(delimiter); + return shortenLongString(chunkName, delimiter, hashFunction); +}; +exports.getLongChunkName = getLongChunkName; -/***/ 71693: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {string} context context directory + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} full chunk name + */ +const getFullChunkName = ( + chunk, + chunkGraph, + context, + associatedObjectForCache +) => { + if (chunk.name) return chunk.name; + const modules = chunkGraph.getChunkRootModules(chunk); + const fullModuleNames = modules.map(m => + makePathsRelative(context, m.identifier(), associatedObjectForCache) + ); + return fullModuleNames.join(); +}; +exports.getFullChunkName = getFullChunkName; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @template K + * @template V + * @param {Map} map a map from key to values + * @param {K} key key + * @param {V} value value + * @returns {void} + */ +const addToMapOfItems = (map, key, value) => { + let array = map.get(key); + if (array === undefined) { + array = []; + map.set(key, array); + } + array.push(value); +}; +/** + * @param {Compilation} compilation the compilation + * @param {function(Module): boolean=} filter filter modules + * @returns {[Set, Module[]]} used module ids as strings and modules without id matching the filter + */ +const getUsedModuleIdsAndModules = (compilation, filter) => { + const chunkGraph = compilation.chunkGraph; + const modules = []; -const ModuleDependency = __webpack_require__(80321); + /** @type {Set} */ + const usedIds = new Set(); + if (compilation.usedModuleIds) { + for (const id of compilation.usedModuleIds) { + usedIds.add(id + ""); + } + } -class LoaderDependency extends ModuleDependency { - /** - * @param {string} request request string - */ - constructor(request) { - super(request); + for (const module of compilation.modules) { + if (!module.needId) continue; + const moduleId = chunkGraph.getModuleId(module); + if (moduleId !== null) { + usedIds.add(moduleId + ""); + } else { + if ( + (!filter || filter(module)) && + chunkGraph.getNumberOfModuleChunks(module) !== 0 + ) { + modules.push(module); + } + } } - get type() { - return "loader"; + return [usedIds, modules]; +}; +exports.getUsedModuleIdsAndModules = getUsedModuleIdsAndModules; + +/** + * @param {Compilation} compilation the compilation + * @returns {Set} used chunk ids as strings + */ +const getUsedChunkIds = compilation => { + /** @type {Set} */ + const usedIds = new Set(); + if (compilation.usedChunkIds) { + for (const id of compilation.usedChunkIds) { + usedIds.add(id + ""); + } } - get category() { - return "loader"; + for (const chunk of compilation.chunks) { + const chunkId = chunk.id; + if (chunkId !== null) { + usedIds.add(chunkId + ""); + } } -} -module.exports = LoaderDependency; + return usedIds; +}; +exports.getUsedChunkIds = getUsedChunkIds; +/** + * @template T + * @param {Iterable} items list of items to be named + * @param {function(T): string} getShortName get a short name for an item + * @param {function(T, string): string} getLongName get a long name for an item + * @param {function(T, T): -1|0|1} comparator order of items + * @param {Set} usedIds already used ids, will not be assigned + * @param {function(T, string): void} assignName assign a name to an item + * @returns {T[]} list of items without a name + */ +const assignNames = ( + items, + getShortName, + getLongName, + comparator, + usedIds, + assignName +) => { + /** @type {Map} */ + const nameToItems = new Map(); -/***/ }), + for (const item of items) { + const name = getShortName(item); + addToMapOfItems(nameToItems, name, item); + } -/***/ 223: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {Map} */ + const nameToItems2 = new Map(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + for (const [name, items] of nameToItems) { + if (items.length > 1 || !name) { + for (const item of items) { + const longName = getLongName(item, name); + addToMapOfItems(nameToItems2, longName, item); + } + } else { + addToMapOfItems(nameToItems2, name, items[0]); + } + } + + /** @type {T[]} */ + const unnamedItems = []; + + for (const [name, items] of nameToItems2) { + if (!name) { + for (const item of items) { + unnamedItems.push(item); + } + } else if (items.length === 1 && !usedIds.has(name)) { + assignName(items[0], name); + usedIds.add(name); + } else { + items.sort(comparator); + let i = 0; + for (const item of items) { + while (nameToItems2.has(name + i) && usedIds.has(name + i)) i++; + assignName(item, name + i); + usedIds.add(name + i); + i++; + } + } + } + unnamedItems.sort(comparator); + return unnamedItems; +}; +exports.assignNames = assignNames; +/** + * @template T + * @param {T[]} items list of items to be named + * @param {function(T): string} getName get a name for an item + * @param {function(T, T): -1|0|1} comparator order of items + * @param {function(T, number): boolean} assignId assign an id to an item + * @param {number[]} ranges usable ranges for ids + * @param {number} expandFactor factor to create more ranges + * @param {number} extraSpace extra space to allocate, i. e. when some ids are already used + * @param {number} salt salting number to initialize hashing + * @returns {void} + */ +const assignDeterministicIds = ( + items, + getName, + comparator, + assignId, + ranges = [10], + expandFactor = 10, + extraSpace = 0, + salt = 0 +) => { + items.sort(comparator); -const ModuleDependency = __webpack_require__(80321); + // max 5% fill rate + const optimalRange = Math.min( + Math.ceil(items.length * 20) + extraSpace, + Number.MAX_SAFE_INTEGER + ); -class LoaderImportDependency extends ModuleDependency { - /** - * @param {string} request request string - */ - constructor(request) { - super(request); - this.weak = true; + let i = 0; + let range = ranges[i]; + while (range < optimalRange) { + i++; + if (i < ranges.length) { + range = Math.min(ranges[i], Number.MAX_SAFE_INTEGER); + } else if (expandFactor) { + range = Math.min(range * expandFactor, Number.MAX_SAFE_INTEGER); + } else { + break; + } } - get type() { - return "loader import"; + for (const item of items) { + const ident = getName(item); + let id; + let i = salt; + do { + id = numberHash(ident + i++, range); + } while (!assignId(item, id)); } +}; +exports.assignDeterministicIds = assignDeterministicIds; - get category() { - return "loaderImport"; +/** + * @param {Set} usedIds used ids + * @param {Iterable} modules the modules + * @param {Compilation} compilation the compilation + * @returns {void} + */ +const assignAscendingModuleIds = (usedIds, modules, compilation) => { + const chunkGraph = compilation.chunkGraph; + + let nextId = 0; + let assignId; + if (usedIds.size > 0) { + assignId = module => { + if (chunkGraph.getModuleId(module) === null) { + while (usedIds.has(nextId + "")) nextId++; + chunkGraph.setModuleId(module, nextId++); + } + }; + } else { + assignId = module => { + if (chunkGraph.getModuleId(module) === null) { + chunkGraph.setModuleId(module, nextId++); + } + }; } -} + for (const module of modules) { + assignId(module); + } +}; +exports.assignAscendingModuleIds = assignAscendingModuleIds; -module.exports = LoaderImportDependency; +/** + * @param {Iterable} chunks the chunks + * @param {Compilation} compilation the compilation + * @returns {void} + */ +const assignAscendingChunkIds = (chunks, compilation) => { + const usedIds = getUsedChunkIds(compilation); + + let nextId = 0; + if (usedIds.size > 0) { + for (const chunk of chunks) { + if (chunk.id === null) { + while (usedIds.has(nextId + "")) nextId++; + chunk.id = nextId; + chunk.ids = [nextId]; + nextId++; + } + } + } else { + for (const chunk of chunks) { + if (chunk.id === null) { + chunk.id = nextId; + chunk.ids = [nextId]; + nextId++; + } + } + } +}; +exports.assignAscendingChunkIds = assignAscendingChunkIds; /***/ }), -/***/ 24721: +/***/ 6454: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -88231,40 +86943,24 @@ module.exports = LoaderImportDependency; -const NormalModule = __webpack_require__(39); -const LazySet = __webpack_require__(38938); -const LoaderDependency = __webpack_require__(71693); -const LoaderImportDependency = __webpack_require__(223); +const { compareChunksNatural } = __webpack_require__(29579); +const { + getShortChunkName, + getLongChunkName, + assignNames, + getUsedChunkIds, + assignAscendingChunkIds +} = __webpack_require__(63290); -/** @typedef {import("../Compilation").DepConstructor} DepConstructor */ +/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Module")} Module */ -/** - * @callback LoadModuleCallback - * @param {(Error | null)=} err error object - * @param {string | Buffer=} source source code - * @param {object=} map source map - * @param {Module=} module loaded module if successful - */ - -/** - * @callback ImportModuleCallback - * @param {(Error | null)=} err error object - * @param {any=} exports exports of the evaluated module - */ - -/** - * @typedef {Object} ImportModuleOptions - * @property {string=} layer the target layer - * @property {string=} publicPath the target public path - */ - -class LoaderPlugin { - /** - * @param {Object} options options - */ - constructor(options = {}) {} +class NamedChunkIdsPlugin { + constructor(options) { + this.delimiter = (options && options.delimiter) || "-"; + this.context = options && options.context; + } /** * Apply the plugin @@ -88272,222 +86968,60 @@ class LoaderPlugin { * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap( - "LoaderPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - LoaderDependency, - normalModuleFactory - ); - compilation.dependencyFactories.set( - LoaderImportDependency, - normalModuleFactory - ); - } - ); - - compiler.hooks.compilation.tap("LoaderPlugin", compilation => { - const moduleGraph = compilation.moduleGraph; - NormalModule.getCompilationHooks(compilation).loader.tap( - "LoaderPlugin", - loaderContext => { - /** - * @param {string} request the request string to load the module from - * @param {LoadModuleCallback} callback callback returning the loaded module or error - * @returns {void} - */ - loaderContext.loadModule = (request, callback) => { - const dep = new LoaderDependency(request); - dep.loc = { - name: request - }; - const factory = compilation.dependencyFactories.get( - /** @type {DepConstructor} */ (dep.constructor) - ); - if (factory === undefined) { - return callback( - new Error( - `No module factory available for dependency type: ${dep.constructor.name}` - ) - ); - } - compilation.buildQueue.increaseParallelism(); - compilation.handleModuleCreation( - { - factory, - dependencies: [dep], - originModule: loaderContext._module, - context: loaderContext.context, - recursive: false - }, - err => { - compilation.buildQueue.decreaseParallelism(); - if (err) { - return callback(err); - } - const referencedModule = moduleGraph.getModule(dep); - if (!referencedModule) { - return callback(new Error("Cannot load the module")); - } - if (referencedModule.getNumberOfErrors() > 0) { - return callback( - new Error("The loaded module contains errors") - ); - } - const moduleSource = referencedModule.originalSource(); - if (!moduleSource) { - return callback( - new Error( - "The module created for a LoaderDependency must have an original source" - ) - ); - } - let source, map; - if (moduleSource.sourceAndMap) { - const sourceAndMap = moduleSource.sourceAndMap(); - map = sourceAndMap.map; - source = sourceAndMap.source; - } else { - map = moduleSource.map(); - source = moduleSource.source(); - } - const fileDependencies = new LazySet(); - const contextDependencies = new LazySet(); - const missingDependencies = new LazySet(); - const buildDependencies = new LazySet(); - referencedModule.addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ); - - for (const d of fileDependencies) { - loaderContext.addDependency(d); - } - for (const d of contextDependencies) { - loaderContext.addContextDependency(d); - } - for (const d of missingDependencies) { - loaderContext.addMissingDependency(d); - } - for (const d of buildDependencies) { - loaderContext.addBuildDependency(d); - } - return callback(null, source, map, referencedModule); - } - ); - }; - - /** - * @param {string} request the request string to load the module from - * @param {ImportModuleOptions=} options options - * @param {ImportModuleCallback=} callback callback returning the exports - * @returns {void} - */ - const importModule = (request, options, callback) => { - const dep = new LoaderImportDependency(request); - dep.loc = { - name: request - }; - const factory = compilation.dependencyFactories.get( - /** @type {DepConstructor} */ (dep.constructor) - ); - if (factory === undefined) { - return callback( - new Error( - `No module factory available for dependency type: ${dep.constructor.name}` - ) - ); - } - compilation.buildQueue.increaseParallelism(); - compilation.handleModuleCreation( - { - factory, - dependencies: [dep], - originModule: loaderContext._module, - contextInfo: { - issuerLayer: options.layer - }, - context: loaderContext.context, - connectOrigin: false - }, - err => { - compilation.buildQueue.decreaseParallelism(); - if (err) { - return callback(err); - } - const referencedModule = moduleGraph.getModule(dep); - if (!referencedModule) { - return callback(new Error("Cannot load the module")); - } - compilation.executeModule( - referencedModule, - { - entryOptions: { - publicPath: options.publicPath - } - }, - (err, result) => { - if (err) return callback(err); - for (const d of result.fileDependencies) { - loaderContext.addDependency(d); - } - for (const d of result.contextDependencies) { - loaderContext.addContextDependency(d); - } - for (const d of result.missingDependencies) { - loaderContext.addMissingDependency(d); - } - for (const d of result.buildDependencies) { - loaderContext.addBuildDependency(d); - } - if (result.cacheable === false) - loaderContext.cacheable(false); - for (const [name, { source, info }] of result.assets) { - const { buildInfo } = loaderContext._module; - if (!buildInfo.assets) { - buildInfo.assets = Object.create(null); - buildInfo.assetsInfo = new Map(); - } - buildInfo.assets[name] = source; - buildInfo.assetsInfo.set(name, info); - } - callback(null, result.exports); - } - ); - } - ); - }; + compiler.hooks.compilation.tap("NamedChunkIdsPlugin", compilation => { + const { hashFunction } = compilation.outputOptions; + compilation.hooks.chunkIds.tap("NamedChunkIdsPlugin", chunks => { + const chunkGraph = compilation.chunkGraph; + const context = this.context ? this.context : compiler.context; + const delimiter = this.delimiter; - /** - * @param {string} request the request string to load the module from - * @param {ImportModuleOptions} options options - * @param {ImportModuleCallback=} callback callback returning the exports - * @returns {Promise | void} exports - */ - loaderContext.importModule = (request, options, callback) => { - if (!callback) { - return new Promise((resolve, reject) => { - importModule(request, options || {}, (err, result) => { - if (err) reject(err); - else resolve(result); - }); - }); + const unnamedChunks = assignNames( + Array.from(chunks).filter(chunk => { + if (chunk.name) { + chunk.id = chunk.name; + chunk.ids = [chunk.name]; } - return importModule(request, options || {}, callback); - }; + return chunk.id === null; + }), + chunk => + getShortChunkName( + chunk, + chunkGraph, + context, + delimiter, + hashFunction, + compiler.root + ), + chunk => + getLongChunkName( + chunk, + chunkGraph, + context, + delimiter, + hashFunction, + compiler.root + ), + compareChunksNatural(chunkGraph), + getUsedChunkIds(compilation), + (chunk, name) => { + chunk.id = name; + chunk.ids = [name]; + } + ); + if (unnamedChunks.length > 0) { + assignAscendingChunkIds(unnamedChunks, compilation); } - ); + }); }); } } -module.exports = LoaderPlugin; + +module.exports = NamedChunkIdsPlugin; /***/ }), -/***/ 5826: +/***/ 24339: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -88498,48 +87032,62 @@ module.exports = LoaderPlugin; -const makeSerializable = __webpack_require__(33032); - -class LocalModule { - constructor(name, idx) { - this.name = name; - this.idx = idx; - this.used = false; - } - - flagUsed() { - this.used = true; - } - - variableName() { - return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__"; - } +const { compareModulesByIdentifier } = __webpack_require__(29579); +const { + getShortModuleName, + getLongModuleName, + assignNames, + getUsedModuleIdsAndModules, + assignAscendingModuleIds +} = __webpack_require__(63290); - serialize(context) { - const { write } = context; +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ - write(this.name); - write(this.idx); - write(this.used); +class NamedModuleIdsPlugin { + constructor(options) { + this.options = options || {}; } - deserialize(context) { - const { read } = context; + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { root } = compiler; + compiler.hooks.compilation.tap("NamedModuleIdsPlugin", compilation => { + const { hashFunction } = compilation.outputOptions; + compilation.hooks.moduleIds.tap("NamedModuleIdsPlugin", () => { + const chunkGraph = compilation.chunkGraph; + const context = this.options.context + ? this.options.context + : compiler.context; - this.name = read(); - this.idx = read(); - this.used = read(); + const [usedIds, modules] = getUsedModuleIdsAndModules(compilation); + const unnamedModules = assignNames( + modules, + m => getShortModuleName(m, context, root), + (m, shortName) => + getLongModuleName(shortName, m, context, hashFunction, root), + compareModulesByIdentifier, + usedIds, + (m, name) => chunkGraph.setModuleId(m, name) + ); + if (unnamedModules.length > 0) { + assignAscendingModuleIds(usedIds, unnamedModules, compilation); + } + }); + }); } } -makeSerializable(LocalModule, "webpack/lib/dependencies/LocalModule"); - -module.exports = LocalModule; +module.exports = NamedModuleIdsPlugin; /***/ }), -/***/ 52805: +/***/ 86221: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -88550,268 +87098,84 @@ module.exports = LocalModule; -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +const { compareChunksNatural } = __webpack_require__(29579); +const { assignAscendingChunkIds } = __webpack_require__(63290); -class LocalModuleDependency extends NullDependency { - constructor(localModule, range, callNew) { - super(); +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ - this.localModule = localModule; - this.range = range; - this.callNew = callNew; - } - - serialize(context) { - const { write } = context; - - write(this.localModule); - write(this.range); - write(this.callNew); - - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - - this.localModule = read(); - this.range = read(); - this.callNew = read(); - - super.deserialize(context); - } -} - -makeSerializable( - LocalModuleDependency, - "webpack/lib/dependencies/LocalModuleDependency" -); - -LocalModuleDependency.Template = class LocalModuleDependencyTemplate extends ( - NullDependency.Template -) { +class NaturalChunkIdsPlugin { /** - * @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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply(dependency, source, templateContext) { - const dep = /** @type {LocalModuleDependency} */ (dependency); - if (!dep.range) return; - const moduleInstance = dep.callNew - ? `new (function () { return ${dep.localModule.variableName()}; })()` - : dep.localModule.variableName(); - source.replace(dep.range[0], dep.range[1] - 1, moduleInstance); - } -}; - -module.exports = LocalModuleDependency; - - -/***/ }), - -/***/ 75827: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const LocalModule = __webpack_require__(5826); - -const lookup = (parent, mod) => { - if (mod.charAt(0) !== ".") return mod; - - var path = parent.split("/"); - var segments = mod.split("/"); - path.pop(); - - for (let i = 0; i < segments.length; i++) { - const seg = segments[i]; - if (seg === "..") { - path.pop(); - } else if (seg !== ".") { - path.push(seg); - } - } - - return path.join("/"); -}; - -exports.addLocalModule = (state, name) => { - if (!state.localModules) { - state.localModules = []; + apply(compiler) { + compiler.hooks.compilation.tap("NaturalChunkIdsPlugin", compilation => { + compilation.hooks.chunkIds.tap("NaturalChunkIdsPlugin", chunks => { + const chunkGraph = compilation.chunkGraph; + const compareNatural = compareChunksNatural(chunkGraph); + const chunksInNaturalOrder = Array.from(chunks).sort(compareNatural); + assignAscendingChunkIds(chunksInNaturalOrder, compilation); + }); + }); } - const m = new LocalModule(name, state.localModules.length); - state.localModules.push(m); - return m; -}; +} -exports.getLocalModule = (state, name, namedModule) => { - if (!state.localModules) return null; - if (namedModule) { - // resolve dependency name relative to the defining named module - name = lookup(namedModule, name); - } - for (let i = 0; i < state.localModules.length; i++) { - if (state.localModules[i].name === name) { - return state.localModules[i]; - } - } - return null; -}; +module.exports = NaturalChunkIdsPlugin; /***/ }), -/***/ 88488: +/***/ 83366: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Florent Cailhol @ooflorent */ -const Dependency = __webpack_require__(54912); -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -class ModuleDecoratorDependency extends NullDependency { - /** - * @param {string} decorator the decorator requirement - * @param {boolean} allowExportsAccess allow to access exports from module - */ - constructor(decorator, allowExportsAccess) { - super(); - this.decorator = decorator; - this.allowExportsAccess = allowExportsAccess; - this._hashUpdate = undefined; - } - - /** - * @returns {string} a display name for the type of dependency - */ - get type() { - return "module decorator"; - } - - get category() { - return "self"; - } - - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - return `self`; - } +const { + compareModulesByPreOrderIndexOrIdentifier +} = __webpack_require__(29579); +const { + assignAscendingModuleIds, + getUsedModuleIdsAndModules +} = __webpack_require__(63290); - /** - * 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 this.allowExportsAccess - ? Dependency.EXPORTS_OBJECT_REFERENCED - : Dependency.NO_EXPORTS_REFERENCED; - } +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +class NaturalModuleIdsPlugin { /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) { - this._hashUpdate = `${this.decorator}${this.allowExportsAccess}`; - } - hash.update(this._hashUpdate); - } - - serialize(context) { - const { write } = context; - write(this.decorator); - write(this.allowExportsAccess); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.decorator = read(); - this.allowExportsAccess = read(); - super.deserialize(context); + apply(compiler) { + compiler.hooks.compilation.tap("NaturalModuleIdsPlugin", compilation => { + compilation.hooks.moduleIds.tap("NaturalModuleIdsPlugin", modules => { + const [usedIds, modulesInNaturalOrder] = + getUsedModuleIdsAndModules(compilation); + modulesInNaturalOrder.sort( + compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph) + ); + assignAscendingModuleIds(usedIds, modulesInNaturalOrder, compilation); + }); + }); } } -makeSerializable( - ModuleDecoratorDependency, - "webpack/lib/dependencies/ModuleDecoratorDependency" -); - -ModuleDecoratorDependency.Template = class ModuleDecoratorDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, - { module, chunkGraph, initFragments, runtimeRequirements } - ) { - const dep = /** @type {ModuleDecoratorDependency} */ (dependency); - runtimeRequirements.add(RuntimeGlobals.moduleLoaded); - runtimeRequirements.add(RuntimeGlobals.moduleId); - runtimeRequirements.add(RuntimeGlobals.module); - runtimeRequirements.add(dep.decorator); - initFragments.push( - new InitFragment( - `/* module decorator */ ${module.moduleArgument} = ${dep.decorator}(${module.moduleArgument});\n`, - InitFragment.STAGE_PROVIDES, - 0, - `module decorator ${chunkGraph.getModuleId(module)}` - ) - ); - } -}; - -module.exports = ModuleDecoratorDependency; +module.exports = NaturalModuleIdsPlugin; /***/ }), -/***/ 80321: +/***/ 51020: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -88822,216 +87186,84 @@ module.exports = ModuleDecoratorDependency; -const Dependency = __webpack_require__(54912); -const DependencyTemplate = __webpack_require__(5160); -const memoize = __webpack_require__(78676); +const { compareChunksNatural } = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); +const { assignAscendingChunkIds } = __webpack_require__(63290); -/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ +/** @typedef {import("../../declarations/plugins/ids/OccurrenceChunkIdsPlugin").OccurrenceChunkIdsPluginOptions} OccurrenceChunkIdsPluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Module")} Module */ -const getRawModule = memoize(() => __webpack_require__(84929)); - -class ModuleDependency extends Dependency { - /** - * @param {string} request request path which needs resolving - */ - constructor(request) { - super(); - this.request = request; - this.userRequest = request; - this.range = undefined; - // assertions must be serialized by subclasses that use it - /** @type {Record | undefined} */ - this.assertions = undefined; - } - - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - let str = `module${this.request}`; - if (this.assertions !== undefined) { - str += JSON.stringify(this.assertions); - } - return str; - } - - /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module - */ - couldAffectReferencingModule() { - return true; +const validate = createSchemaValidation( + __webpack_require__(24344), + () => __webpack_require__(53576), + { + name: "Occurrence Order Chunk Ids Plugin", + baseDataPath: "options" } +); +class OccurrenceChunkIdsPlugin { /** - * @param {string} context context directory - * @returns {Module} a module + * @param {OccurrenceChunkIdsPluginOptions=} options options object */ - createIgnoredModule(context) { - const RawModule = getRawModule(); - return new RawModule( - "/* (ignored) */", - `ignored|${context}|${this.request}`, - `${this.request} (ignored)` - ); - } - - serialize(context) { - const { write } = context; - write(this.request); - write(this.userRequest); - write(this.range); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.request = read(); - this.userRequest = read(); - this.range = read(); - super.deserialize(context); + constructor(options = {}) { + validate(options); + this.options = options; } -} - -ModuleDependency.Template = DependencyTemplate; - -module.exports = ModuleDependency; - - -/***/ }), - -/***/ 80825: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const ModuleDependency = __webpack_require__(80321); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -class ModuleDependencyTemplateAsId extends ModuleDependency.Template { /** - * @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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply(dependency, source, { runtimeTemplate, moduleGraph, chunkGraph }) { - const dep = /** @type {ModuleDependency} */ (dependency); - if (!dep.range) return; - const content = runtimeTemplate.moduleId({ - module: moduleGraph.getModule(dep), - chunkGraph, - request: dep.request, - weak: dep.weak - }); - source.replace(dep.range[0], dep.range[1] - 1, content); - } -} - -module.exports = ModuleDependencyTemplateAsId; - - -/***/ }), - -/***/ 36873: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + apply(compiler) { + const prioritiseInitial = this.options.prioritiseInitial; + compiler.hooks.compilation.tap("OccurrenceChunkIdsPlugin", compilation => { + compilation.hooks.chunkIds.tap("OccurrenceChunkIdsPlugin", chunks => { + const chunkGraph = compilation.chunkGraph; + /** @type {Map} */ + const occursInInitialChunksMap = new Map(); -const ModuleDependency = __webpack_require__(80321); + const compareNatural = compareChunksNatural(chunkGraph); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + for (const c of chunks) { + let occurs = 0; + for (const chunkGroup of c.groupsIterable) { + for (const parent of chunkGroup.parentsIterable) { + if (parent.isInitial()) occurs++; + } + } + occursInInitialChunksMap.set(c, occurs); + } -class ModuleDependencyTemplateAsRequireId extends ModuleDependency.Template { - /** - * @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, - { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {ModuleDependency} */ (dependency); - if (!dep.range) return; - const content = runtimeTemplate.moduleExports({ - module: moduleGraph.getModule(dep), - chunkGraph, - request: dep.request, - weak: dep.weak, - runtimeRequirements + const chunksInOccurrenceOrder = Array.from(chunks).sort((a, b) => { + if (prioritiseInitial) { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + } + const aOccurs = a.getNumberOfGroups(); + const bOccurs = b.getNumberOfGroups(); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + return compareNatural(a, b); + }); + assignAscendingChunkIds(chunksInOccurrenceOrder, compilation); + }); }); - source.replace(dep.range[0], dep.range[1] - 1, content); - } -} -module.exports = ModuleDependencyTemplateAsRequireId; - - -/***/ }), - -/***/ 47511: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyTemplateAsId = __webpack_require__(80825); - -class ModuleHotAcceptDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; - this.weak = true; - } - - get type() { - return "module.hot.accept"; - } - - get category() { - return "commonjs"; } } -makeSerializable( - ModuleHotAcceptDependency, - "webpack/lib/dependencies/ModuleHotAcceptDependency" -); - -ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId; - -module.exports = ModuleHotAcceptDependency; +module.exports = OccurrenceChunkIdsPlugin; /***/ }), -/***/ 86301: +/***/ 35371: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -89042,250 +87274,311 @@ module.exports = ModuleHotAcceptDependency; -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyTemplateAsId = __webpack_require__(80825); - -class ModuleHotDeclineDependency extends ModuleDependency { - constructor(request, range) { - super(request); - - this.range = range; - this.weak = true; - } +const { + compareModulesByPreOrderIndexOrIdentifier +} = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); +const { + assignAscendingModuleIds, + getUsedModuleIdsAndModules +} = __webpack_require__(63290); - get type() { - return "module.hot.decline"; - } +/** @typedef {import("../../declarations/plugins/ids/OccurrenceModuleIdsPlugin").OccurrenceModuleIdsPluginOptions} OccurrenceModuleIdsPluginOptions */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ - get category() { - return "commonjs"; +const validate = createSchemaValidation( + __webpack_require__(14916), + () => __webpack_require__(19330), + { + name: "Occurrence Order Module Ids Plugin", + baseDataPath: "options" } -} - -makeSerializable( - ModuleHotDeclineDependency, - "webpack/lib/dependencies/ModuleHotDeclineDependency" ); -ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId; - -module.exports = ModuleHotDeclineDependency; - - -/***/ }), - -/***/ 31830: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Dependency = __webpack_require__(54912); -const DependencyTemplate = __webpack_require__(5160); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - -class NullDependency extends Dependency { - get type() { - return "null"; - } - +class OccurrenceModuleIdsPlugin { /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + * @param {OccurrenceModuleIdsPluginOptions=} options options object */ - couldAffectReferencingModule() { - return false; + constructor(options = {}) { + validate(options); + this.options = options; } -} -NullDependency.Template = class NullDependencyTemplate extends ( - DependencyTemplate -) { /** - * @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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply(dependency, source, templateContext) {} -}; + apply(compiler) { + const prioritiseInitial = this.options.prioritiseInitial; + compiler.hooks.compilation.tap("OccurrenceModuleIdsPlugin", compilation => { + const moduleGraph = compilation.moduleGraph; -module.exports = NullDependency; + compilation.hooks.moduleIds.tap("OccurrenceModuleIdsPlugin", () => { + const chunkGraph = compilation.chunkGraph; + const [usedIds, modulesInOccurrenceOrder] = + getUsedModuleIdsAndModules(compilation); -/***/ }), + const occursInInitialChunksMap = new Map(); + const occursInAllChunksMap = new Map(); -/***/ 31618: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const initialChunkChunkMap = new Map(); + const entryCountMap = new Map(); + for (const m of modulesInOccurrenceOrder) { + let initial = 0; + let entry = 0; + for (const c of chunkGraph.getModuleChunksIterable(m)) { + if (c.canBeInitial()) initial++; + if (chunkGraph.isEntryModuleInChunk(m, c)) entry++; + } + initialChunkChunkMap.set(m, initial); + entryCountMap.set(m, entry); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {Module} module module + * @returns {number} count of occurs + */ + const countOccursInEntry = module => { + let sum = 0; + for (const [ + originModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if (!originModule) continue; + if (!connections.some(c => c.isTargetActive(undefined))) continue; + sum += initialChunkChunkMap.get(originModule); + } + return sum; + }; + /** + * @param {Module} module module + * @returns {number} count of occurs + */ + const countOccurs = module => { + let sum = 0; + for (const [ + originModule, + connections + ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { + if (!originModule) continue; + const chunkModules = + chunkGraph.getNumberOfModuleChunks(originModule); + for (const c of connections) { + if (!c.isTargetActive(undefined)) continue; + if (!c.dependency) continue; + const factor = c.dependency.getNumberOfIdOccurrences(); + if (factor === 0) continue; + sum += factor * chunkModules; + } + } + return sum; + }; + if (prioritiseInitial) { + for (const m of modulesInOccurrenceOrder) { + const result = + countOccursInEntry(m) + + initialChunkChunkMap.get(m) + + entryCountMap.get(m); + occursInInitialChunksMap.set(m, result); + } + } -const ModuleDependency = __webpack_require__(80321); + for (const m of modulesInOccurrenceOrder) { + const result = + countOccurs(m) + + chunkGraph.getNumberOfModuleChunks(m) + + entryCountMap.get(m); + occursInAllChunksMap.set(m, result); + } -class PrefetchDependency extends ModuleDependency { - constructor(request) { - super(request); - } + const naturalCompare = compareModulesByPreOrderIndexOrIdentifier( + compilation.moduleGraph + ); - get type() { - return "prefetch"; - } + modulesInOccurrenceOrder.sort((a, b) => { + if (prioritiseInitial) { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + } + const aOccurs = occursInAllChunksMap.get(a); + const bOccurs = occursInAllChunksMap.get(b); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + return naturalCompare(a, b); + }); - get category() { - return "esm"; + assignAscendingModuleIds( + usedIds, + modulesInOccurrenceOrder, + compilation + ); + }); + }); } } -module.exports = PrefetchDependency; +module.exports = OccurrenceModuleIdsPlugin; /***/ }), -/***/ 95770: +/***/ 8635: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent + Author Tobias Koppers @sokra */ -const InitFragment = __webpack_require__(55870); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../util/Hash")} Hash */ - -/** - * @param {string[]|null} path the property path array - * @returns {string} the converted path - */ -const pathToString = path => - path !== null && path.length > 0 - ? path.map(part => `[${JSON.stringify(part)}]`).join("") - : ""; - -class ProvidedDependency extends ModuleDependency { - constructor(request, identifier, path, range) { - super(request); - this.identifier = identifier; - this.path = path; - this.range = range; - this._hashUpdate = undefined; - } +const { WebpackError } = __webpack_require__(91919); +const { getUsedModuleIdsAndModules } = __webpack_require__(63290); - get type() { - return "provided"; - } +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ - get category() { - return "esm"; - } +const plugin = "SyncModuleIdsPlugin"; +class SyncModuleIdsPlugin { /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context - * @returns {void} + * @param {Object} options options + * @param {string} options.path path to file + * @param {string=} options.context context for module names + * @param {function(Module): boolean} options.test selector for modules + * @param {"read" | "create" | "merge" | "update"=} options.mode operation mode (defaults to merge) */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) { - this._hashUpdate = - this.identifier + (this.path ? this.path.join(",") : "null"); - } - hash.update(this._hashUpdate); - } - - serialize(context) { - const { write } = context; - write(this.identifier); - write(this.path); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.identifier = read(); - this.path = read(); - super.deserialize(context); + constructor({ path, context, test, mode }) { + this._path = path; + this._context = context; + this._test = test || (() => true); + const readAndWrite = !mode || mode === "merge" || mode === "update"; + this._read = readAndWrite || mode === "read"; + this._write = readAndWrite || mode === "create"; + this._prune = mode === "update"; } -} - -makeSerializable( - ProvidedDependency, - "webpack/lib/dependencies/ProvidedDependency" -); -class ProvidedDependencyTemplate extends ModuleDependency.Template { /** - * @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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply( - dependency, - source, - { - runtimeTemplate, - moduleGraph, - chunkGraph, - initFragments, - runtimeRequirements + apply(compiler) { + /** @type {Map} */ + let data; + let dataChanged = false; + if (this._read) { + compiler.hooks.readRecords.tapAsync(plugin, callback => { + const fs = compiler.intermediateFileSystem; + fs.readFile(this._path, (err, buffer) => { + if (err) { + if (err.code !== "ENOENT") { + return callback(err); + } + return callback(); + } + const json = JSON.parse(buffer.toString()); + data = new Map(); + for (const key of Object.keys(json)) { + data.set(key, json[key]); + } + dataChanged = false; + return callback(); + }); + }); } - ) { - const dep = /** @type {ProvidedDependency} */ (dependency); - initFragments.push( - new InitFragment( - `/* provided dependency */ var ${ - dep.identifier - } = ${runtimeTemplate.moduleExports({ - module: moduleGraph.getModule(dep), - chunkGraph, - request: dep.request, - runtimeRequirements - })}${pathToString(dep.path)};\n`, - InitFragment.STAGE_PROVIDES, - 1, - `provided ${dep.identifier}` - ) - ); - source.replace(dep.range[0], dep.range[1] - 1, dep.identifier); + if (this._write) { + compiler.hooks.emitRecords.tapAsync(plugin, callback => { + if (!data || !dataChanged) return callback(); + const json = {}; + const sorted = Array.from(data).sort(([a], [b]) => (a < b ? -1 : 1)); + for (const [key, value] of sorted) { + json[key] = value; + } + const fs = compiler.intermediateFileSystem; + fs.writeFile(this._path, JSON.stringify(json), callback); + }); + } + compiler.hooks.thisCompilation.tap(plugin, compilation => { + const associatedObjectForCache = compiler.root; + const context = this._context || compiler.context; + if (this._read) { + compilation.hooks.reviveModules.tap(plugin, (_1, _2) => { + if (!data) return; + const { chunkGraph } = compilation; + const [usedIds, modules] = getUsedModuleIdsAndModules( + compilation, + this._test + ); + for (const module of modules) { + const name = module.libIdent({ + context, + associatedObjectForCache + }); + if (!name) continue; + const id = data.get(name); + const idAsString = `${id}`; + if (usedIds.has(idAsString)) { + const err = new WebpackError( + `SyncModuleIdsPlugin: Unable to restore id '${id}' from '${this._path}' as it's already used.` + ); + err.module = module; + compilation.errors.push(err); + } + chunkGraph.setModuleId(module, id); + usedIds.add(idAsString); + } + }); + } + if (this._write) { + compilation.hooks.recordModules.tap(plugin, modules => { + const { chunkGraph } = compilation; + let oldData = data; + if (!oldData) { + oldData = data = new Map(); + } else if (this._prune) { + data = new Map(); + } + for (const module of modules) { + if (this._test(module)) { + const name = module.libIdent({ + context, + associatedObjectForCache + }); + if (!name) continue; + const id = chunkGraph.getModuleId(module); + if (id === null) continue; + const oldId = oldData.get(name); + if (oldId !== id) { + dataChanged = true; + } else if (data === oldData) { + continue; + } + data.set(name, id); + } + } + if (data.size !== oldData.size) dataChanged = true; + }); + } + }); } } -ProvidedDependency.Template = ProvidedDependencyTemplate; - -module.exports = ProvidedDependency; +module.exports = SyncModuleIdsPlugin; /***/ }), -/***/ 55799: +/***/ 91919: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -89296,253 +87589,578 @@ module.exports = ProvidedDependency; -const { UsageState } = __webpack_require__(63686); -const makeSerializable = __webpack_require__(33032); -const { filterRuntime } = __webpack_require__(17156); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../util/Hash")} Hash */ +const util = __webpack_require__(73837); +const memoize = __webpack_require__(78676); -class PureExpressionDependency extends NullDependency { - /** - * @param {[number, number]} range the source range - */ - constructor(range) { - super(); - this.range = range; - /** @type {Set | false} */ - this.usedByExports = false; - this._hashUpdate = undefined; - } +/** @typedef {import("../declarations/WebpackOptions").Entry} Entry */ +/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} EntryNormalized */ +/** @typedef {import("../declarations/WebpackOptions").EntryObject} EntryObject */ +/** @typedef {import("../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../declarations/WebpackOptions").ModuleOptions} ModuleOptions */ +/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetCondition} RuleSetCondition */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetConditionAbsolute} RuleSetConditionAbsolute */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetRule} RuleSetRule */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetUse} RuleSetUse */ +/** @typedef {import("../declarations/WebpackOptions").RuleSetUseItem} RuleSetUseItem */ +/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} Configuration */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ +/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ +/** @typedef {import("./Compilation").Asset} Asset */ +/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("./MultiStats")} MultiStats */ +/** @typedef {import("./Parser").ParserState} ParserState */ +/** @typedef {import("./ResolverFactory").ResolvePluginInstance} ResolvePluginInstance */ +/** @typedef {import("./ResolverFactory").Resolver} Resolver */ +/** @typedef {import("./Watching")} Watching */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunk} StatsChunk */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunkGroup} StatsChunkGroup */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunkOrigin} StatsChunkOrigin */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsLogging} StatsLogging */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsLoggingEntry} StatsLoggingEntry */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleIssuer} StatsModuleIssuer */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleReason} StatsModuleReason */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleTraceDependency} StatsModuleTraceDependency */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleTraceItem} StatsModuleTraceItem */ +/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsProfile} StatsProfile */ - /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) { - this._hashUpdate = this.range + ""; +/** + * @template {Function} T + * @param {function(): T} factory factory function + * @returns {T} function + */ +const lazyFunction = factory => { + const fac = memoize(factory); + const f = /** @type {any} */ ( + (...args) => { + return fac()(...args); } - hash.update(this._hashUpdate); - } + ); + return /** @type {T} */ (f); +}; - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this dependency connects the module to referencing modules - */ - getModuleEvaluationSideEffectsState(moduleGraph) { - return false; - } - - serialize(context) { - const { write } = context; - write(this.range); - write(this.usedByExports); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.range = read(); - this.usedByExports = read(); - super.deserialize(context); - } -} - -makeSerializable( - PureExpressionDependency, - "webpack/lib/dependencies/PureExpressionDependency" -); - -PureExpressionDependency.Template = class PureExpressionDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, - { chunkGraph, moduleGraph, runtime, runtimeTemplate, runtimeRequirements } - ) { - const dep = /** @type {PureExpressionDependency} */ (dependency); - - const usedByExports = dep.usedByExports; - if (usedByExports !== false) { - const selfModule = moduleGraph.getParentModule(dep); - const exportsInfo = moduleGraph.getExportsInfo(selfModule); - const runtimeCondition = filterRuntime(runtime, runtime => { - for (const exportName of usedByExports) { - if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) { - return true; - } - } - return false; +/** + * @template A + * @template B + * @param {A} obj input a + * @param {B} exports input b + * @returns {A & B} merged + */ +const mergeExports = (obj, exports) => { + const descriptors = Object.getOwnPropertyDescriptors(exports); + for (const name of Object.keys(descriptors)) { + const descriptor = descriptors[name]; + if (descriptor.get) { + const fn = descriptor.get; + Object.defineProperty(obj, name, { + configurable: false, + enumerable: true, + get: memoize(fn) }); - if (runtimeCondition === true) return; - if (runtimeCondition !== false) { - const condition = runtimeTemplate.runtimeConditionExpression({ - chunkGraph, - runtime, - runtimeCondition, - runtimeRequirements - }); - source.insert( - dep.range[0], - `(/* runtime-dependent pure expression or super */ ${condition} ? (` - ); - source.insert(dep.range[1], ") : null)"); - return; - } + } else if (typeof descriptor.value === "object") { + Object.defineProperty(obj, name, { + configurable: false, + enumerable: true, + writable: false, + value: mergeExports({}, descriptor.value) + }); + } else { + throw new Error( + "Exposed values must be either a getter or an nested object" + ); } - - source.insert( - dep.range[0], - `(/* unused pure expression or super */ null && (` - ); - source.insert(dep.range[1], "))"); } + return /** @type {A & B} */ (Object.freeze(obj)); }; -module.exports = PureExpressionDependency; - - -/***/ }), - -/***/ 46917: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - +const fn = lazyFunction(() => __webpack_require__(36243)); +module.exports = mergeExports(fn, { + get webpack() { + return __webpack_require__(36243); + }, + get validate() { + const webpackOptionsSchemaCheck = __webpack_require__(10382); + const getRealValidate = memoize(() => { + const validateSchema = __webpack_require__(12047); + const webpackOptionsSchema = __webpack_require__(73342); + return options => validateSchema(webpackOptionsSchema, options); + }); + return options => { + if (!webpackOptionsSchemaCheck(options)) getRealValidate()(options); + }; + }, + get validateSchema() { + const validateSchema = __webpack_require__(12047); + return validateSchema; + }, + get version() { + return /** @type {string} */ ((__webpack_require__(32702)/* .version */ .i8)); + }, -const makeSerializable = __webpack_require__(33032); -const ContextDependency = __webpack_require__(88101); -const ModuleDependencyTemplateAsRequireId = __webpack_require__(36873); + get cli() { + return __webpack_require__(13462); + }, + get AutomaticPrefetchPlugin() { + return __webpack_require__(17714); + }, + get AsyncDependenciesBlock() { + return __webpack_require__(47736); + }, + get BannerPlugin() { + return __webpack_require__(21242); + }, + get Cache() { + return __webpack_require__(7592); + }, + get Chunk() { + return __webpack_require__(39385); + }, + get ChunkGraph() { + return __webpack_require__(64971); + }, + get CleanPlugin() { + return __webpack_require__(31085); + }, + get Compilation() { + return __webpack_require__(85720); + }, + get Compiler() { + return __webpack_require__(70845); + }, + get ConcatenationScope() { + return __webpack_require__(98229); + }, + get ContextExclusionPlugin() { + return __webpack_require__(21411); + }, + get ContextReplacementPlugin() { + return __webpack_require__(12206); + }, + get DefinePlugin() { + return __webpack_require__(79065); + }, + get DelegatedPlugin() { + return __webpack_require__(80632); + }, + get Dependency() { + return __webpack_require__(54912); + }, + get DllPlugin() { + return __webpack_require__(40038); + }, + get DllReferencePlugin() { + return __webpack_require__(90999); + }, + get DynamicEntryPlugin() { + return __webpack_require__(96475); + }, + get EntryOptionPlugin() { + return __webpack_require__(9909); + }, + get EntryPlugin() { + return __webpack_require__(96953); + }, + get EnvironmentPlugin() { + return __webpack_require__(22070); + }, + get EvalDevToolModulePlugin() { + return __webpack_require__(65218); + }, + get EvalSourceMapDevToolPlugin() { + return __webpack_require__(14790); + }, + get ExternalModule() { + return __webpack_require__(73071); + }, + get ExternalsPlugin() { + return __webpack_require__(6652); + }, + get Generator() { + return __webpack_require__(93401); + }, + get HotUpdateChunk() { + return __webpack_require__(9597); + }, + get HotModuleReplacementPlugin() { + return __webpack_require__(6404); + }, + get IgnorePlugin() { + return __webpack_require__(84808); + }, + get JavascriptModulesPlugin() { + return util.deprecate( + () => __webpack_require__(89464), + "webpack.JavascriptModulesPlugin has moved to webpack.javascript.JavascriptModulesPlugin", + "DEP_WEBPACK_JAVASCRIPT_MODULES_PLUGIN" + )(); + }, + get LibManifestPlugin() { + return __webpack_require__(93837); + }, + get LibraryTemplatePlugin() { + return util.deprecate( + () => __webpack_require__(14157), + "webpack.LibraryTemplatePlugin is deprecated and has been replaced by compilation.outputOptions.library or compilation.addEntry + passing a library option", + "DEP_WEBPACK_LIBRARY_TEMPLATE_PLUGIN" + )(); + }, + get LoaderOptionsPlugin() { + return __webpack_require__(22078); + }, + get LoaderTargetPlugin() { + return __webpack_require__(86738); + }, + get Module() { + return __webpack_require__(73208); + }, + get ModuleFilenameHelpers() { + return __webpack_require__(88821); + }, + get ModuleGraph() { + return __webpack_require__(99988); + }, + get ModuleGraphConnection() { + return __webpack_require__(40639); + }, + get NoEmitOnErrorsPlugin() { + return __webpack_require__(50169); + }, + get NormalModule() { + return __webpack_require__(39); + }, + get NormalModuleReplacementPlugin() { + return __webpack_require__(30633); + }, + get MultiCompiler() { + return __webpack_require__(33370); + }, + get Parser() { + return __webpack_require__(11715); + }, + get PrefetchPlugin() { + return __webpack_require__(73850); + }, + get ProgressPlugin() { + return __webpack_require__(13216); + }, + get ProvidePlugin() { + return __webpack_require__(38309); + }, + get RuntimeGlobals() { + return __webpack_require__(16475); + }, + get RuntimeModule() { + return __webpack_require__(16963); + }, + get SingleEntryPlugin() { + return util.deprecate( + () => __webpack_require__(96953), + "SingleEntryPlugin was renamed to EntryPlugin", + "DEP_WEBPACK_SINGLE_ENTRY_PLUGIN" + )(); + }, + get SourceMapDevToolPlugin() { + return __webpack_require__(63872); + }, + get Stats() { + return __webpack_require__(31743); + }, + get Template() { + return __webpack_require__(1626); + }, + get UsageState() { + return (__webpack_require__(63686).UsageState); + }, + get WatchIgnorePlugin() { + return __webpack_require__(65193); + }, + get WebpackError() { + return __webpack_require__(53799); + }, + get WebpackOptionsApply() { + return __webpack_require__(88422); + }, + get WebpackOptionsDefaulter() { + return util.deprecate( + () => __webpack_require__(14452), + "webpack.WebpackOptionsDefaulter is deprecated and has been replaced by webpack.config.getNormalizedWebpackOptions and webpack.config.applyWebpackOptionsDefaults", + "DEP_WEBPACK_OPTIONS_DEFAULTER" + )(); + }, + // TODO webpack 6 deprecate + get WebpackOptionsValidationError() { + return (__webpack_require__(38476).ValidationError); + }, + get ValidationError() { + return (__webpack_require__(38476).ValidationError); + }, -class RequireContextDependency extends ContextDependency { - constructor(options, range) { - super(options); + cache: { + get MemoryCachePlugin() { + return __webpack_require__(52539); + } + }, - this.range = range; - } + config: { + get getNormalizedWebpackOptions() { + return (__webpack_require__(26693).getNormalizedWebpackOptions); + }, + get applyWebpackOptionsDefaults() { + return (__webpack_require__(92988).applyWebpackOptionsDefaults); + } + }, - get type() { - return "require.context"; - } + dependencies: { + get ModuleDependency() { + return __webpack_require__(80321); + }, + get ConstDependency() { + return __webpack_require__(76911); + }, + get NullDependency() { + return __webpack_require__(31830); + } + }, - serialize(context) { - const { write } = context; + ids: { + get ChunkModuleIdRangePlugin() { + return __webpack_require__(64618); + }, + get NaturalModuleIdsPlugin() { + return __webpack_require__(83366); + }, + get OccurrenceModuleIdsPlugin() { + return __webpack_require__(35371); + }, + get NamedModuleIdsPlugin() { + return __webpack_require__(24339); + }, + get DeterministicChunkIdsPlugin() { + return __webpack_require__(8747); + }, + get DeterministicModuleIdsPlugin() { + return __webpack_require__(76692); + }, + get NamedChunkIdsPlugin() { + return __webpack_require__(6454); + }, + get OccurrenceChunkIdsPlugin() { + return __webpack_require__(51020); + }, + get HashedModuleIdsPlugin() { + return __webpack_require__(21825); + } + }, - write(this.range); + javascript: { + get EnableChunkLoadingPlugin() { + return __webpack_require__(61291); + }, + get JavascriptModulesPlugin() { + return __webpack_require__(89464); + }, + get JavascriptParser() { + return __webpack_require__(29050); + } + }, - super.serialize(context); - } + optimize: { + get AggressiveMergingPlugin() { + return __webpack_require__(64395); + }, + get AggressiveSplittingPlugin() { + return util.deprecate( + () => __webpack_require__(15543), + "AggressiveSplittingPlugin is deprecated in favor of SplitChunksPlugin", + "DEP_WEBPACK_AGGRESSIVE_SPLITTING_PLUGIN" + )(); + }, + get InnerGraph() { + return __webpack_require__(38988); + }, + get LimitChunkCountPlugin() { + return __webpack_require__(83608); + }, + get MinChunkSizePlugin() { + return __webpack_require__(53912); + }, + get ModuleConcatenationPlugin() { + return __webpack_require__(74844); + }, + get RealContentHashPlugin() { + return __webpack_require__(46043); + }, + get RuntimeChunkPlugin() { + return __webpack_require__(2837); + }, + get SideEffectsFlagPlugin() { + return __webpack_require__(84800); + }, + get SplitChunksPlugin() { + return __webpack_require__(21478); + } + }, - deserialize(context) { - const { read } = context; + runtime: { + get GetChunkFilenameRuntimeModule() { + return __webpack_require__(34277); + }, + get LoadScriptRuntimeModule() { + return __webpack_require__(19942); + } + }, - this.range = read(); + prefetch: { + get ChunkPrefetchPreloadPlugin() { + return __webpack_require__(33895); + } + }, - super.deserialize(context); - } -} + web: { + get FetchCompileAsyncWasmPlugin() { + return __webpack_require__(8437); + }, + get FetchCompileWasmPlugin() { + return __webpack_require__(35537); + }, + get JsonpChunkLoadingRuntimeModule() { + return __webpack_require__(84154); + }, + get JsonpTemplatePlugin() { + return __webpack_require__(4607); + } + }, -makeSerializable( - RequireContextDependency, - "webpack/lib/dependencies/RequireContextDependency" -); + webworker: { + get WebWorkerTemplatePlugin() { + return __webpack_require__(68693); + } + }, -RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; + node: { + get NodeEnvironmentPlugin() { + return __webpack_require__(7553); + }, + get NodeSourcePlugin() { + return __webpack_require__(7103); + }, + get NodeTargetPlugin() { + return __webpack_require__(17916); + }, + get NodeTemplatePlugin() { + return __webpack_require__(61052); + }, + get ReadFileCompileWasmPlugin() { + return __webpack_require__(98939); + } + }, -module.exports = RequireContextDependency; + electron: { + get ElectronTargetPlugin() { + return __webpack_require__(32277); + } + }, + wasm: { + get AsyncWebAssemblyModulesPlugin() { + return __webpack_require__(7538); + } + }, -/***/ }), + library: { + get AbstractLibraryPlugin() { + return __webpack_require__(26030); + }, + get EnableLibraryPlugin() { + return __webpack_require__(91452); + } + }, -/***/ 18851: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + container: { + get ContainerPlugin() { + return __webpack_require__(9244); + }, + get ContainerReferencePlugin() { + return __webpack_require__(95757); + }, + get ModuleFederationPlugin() { + return __webpack_require__(30569); + }, + get scope() { + return (__webpack_require__(3083).scope); + } + }, -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + sharing: { + get ConsumeSharedPlugin() { + return __webpack_require__(15046); + }, + get ProvideSharedPlugin() { + return __webpack_require__(31225); + }, + get SharePlugin() { + return __webpack_require__(26335); + }, + get scope() { + return (__webpack_require__(3083).scope); + } + }, + debug: { + get ProfilingPlugin() { + return __webpack_require__(2757); + } + }, + util: { + get createHash() { + return __webpack_require__(49835); + }, + get comparators() { + return __webpack_require__(29579); + }, + get runtime() { + return __webpack_require__(17156); + }, + get serialization() { + return __webpack_require__(8282); + }, + get cleverMerge() { + return (__webpack_require__(60839).cachedCleverMerge); + }, + get LazySet() { + return __webpack_require__(38938); + } + }, -const RequireContextDependency = __webpack_require__(46917); + get sources() { + return __webpack_require__(51255); + }, -module.exports = class RequireContextDependencyParserPlugin { - apply(parser) { - parser.hooks.call - .for("require.context") - .tap("RequireContextDependencyParserPlugin", expr => { - let regExp = /^\.\/.*$/; - let recursive = true; - let mode = "sync"; - switch (expr.arguments.length) { - case 4: { - const modeExpr = parser.evaluateExpression(expr.arguments[3]); - if (!modeExpr.isString()) return; - mode = modeExpr.string; - } - // falls through - case 3: { - const regExpExpr = parser.evaluateExpression(expr.arguments[2]); - if (!regExpExpr.isRegExp()) return; - regExp = regExpExpr.regExp; - } - // falls through - case 2: { - const recursiveExpr = parser.evaluateExpression(expr.arguments[1]); - if (!recursiveExpr.isBoolean()) return; - recursive = recursiveExpr.bool; - } - // falls through - case 1: { - const requestExpr = parser.evaluateExpression(expr.arguments[0]); - if (!requestExpr.isString()) return; - const dep = new RequireContextDependency( - { - request: requestExpr.string, - recursive, - regExp, - mode, - category: "commonjs" - }, - expr.range - ); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - } - }); + experiments: { + schemes: { + get HttpUriPlugin() { + return __webpack_require__(42110); + } + }, + ids: { + get SyncModuleIdsPlugin() { + return __webpack_require__(8635); + } + } } -}; +}); /***/ }), -/***/ 2928: +/***/ 18535: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -89553,155 +88171,159 @@ module.exports = class RequireContextDependencyParserPlugin { -const { cachedSetProperty } = __webpack_require__(60839); -const ContextElementDependency = __webpack_require__(58477); -const RequireContextDependency = __webpack_require__(46917); -const RequireContextDependencyParserPlugin = __webpack_require__(18851); +const { ConcatSource, PrefixSource, RawSource } = __webpack_require__(51255); +const { RuntimeGlobals } = __webpack_require__(91919); +const HotUpdateChunk = __webpack_require__(9597); +const Template = __webpack_require__(1626); +const { getCompilationHooks } = __webpack_require__(89464); +const { + generateEntryStartup, + updateHashForEntryStartup +} = __webpack_require__(98124); -/** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ /** @typedef {import("../Compiler")} Compiler */ -/** @type {ResolveOptions} */ -const EMPTY_RESOLVE_OPTIONS = {}; - -class RequireContextPlugin { +class ArrayPushCallbackChunkFormatPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap( - "RequireContextPlugin", - (compilation, { contextModuleFactory, normalModuleFactory }) => { - compilation.dependencyFactories.set( - RequireContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - RequireContextDependency, - new RequireContextDependency.Template() - ); - - compilation.dependencyFactories.set( - ContextElementDependency, - normalModuleFactory + compiler.hooks.thisCompilation.tap( + "ArrayPushCallbackChunkFormatPlugin", + compilation => { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + "ArrayPushCallbackChunkFormatPlugin", + (chunk, set, { chunkGraph }) => { + if (chunk.hasRuntime()) return; + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { + set.add(RuntimeGlobals.onChunksLoaded); + set.add(RuntimeGlobals.require); + } + set.add(RuntimeGlobals.chunkCallback); + } ); - - const handler = (parser, parserOptions) => { - if ( - parserOptions.requireContext !== undefined && - !parserOptions.requireContext - ) - return; - - new RequireContextDependencyParserPlugin().apply(parser); - }; - - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireContextPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireContextPlugin", handler); - - contextModuleFactory.hooks.alternativeRequests.tap( - "RequireContextPlugin", - (items, options) => { - if (items.length === 0) return items; - - const finalResolveOptions = compiler.resolverFactory.get( - "normal", - cachedSetProperty( - options.resolveOptions || EMPTY_RESOLVE_OPTIONS, - "dependencyType", - options.category - ) - ).options; - - let newItems; - if (!finalResolveOptions.fullySpecified) { - newItems = []; - for (const item of items) { - const { request, context } = item; - for (const ext of finalResolveOptions.extensions) { - if (request.endsWith(ext)) { - newItems.push({ - context, - request: request.slice(0, -ext.length) - }); - } - } - if (!finalResolveOptions.enforceExtension) { - newItems.push(item); - } + const hooks = getCompilationHooks(compilation); + hooks.renderChunk.tap( + "ArrayPushCallbackChunkFormatPlugin", + (modules, renderContext) => { + const { chunk, chunkGraph, runtimeTemplate } = renderContext; + const hotUpdateChunk = + chunk instanceof HotUpdateChunk ? chunk : null; + const globalObject = runtimeTemplate.globalObject; + const source = new ConcatSource(); + const runtimeModules = + chunkGraph.getChunkRuntimeModulesInOrder(chunk); + if (hotUpdateChunk) { + const hotUpdateGlobal = + runtimeTemplate.outputOptions.hotUpdateGlobal; + source.add( + `${globalObject}[${JSON.stringify(hotUpdateGlobal)}](` + ); + source.add(`${JSON.stringify(chunk.id)},`); + source.add(modules); + if (runtimeModules.length > 0) { + source.add(",\n"); + const runtimePart = Template.renderChunkRuntimeModules( + runtimeModules, + renderContext + ); + source.add(runtimePart); } - items = newItems; - - newItems = []; - for (const obj of items) { - const { request, context } = obj; - for (const mainFile of finalResolveOptions.mainFiles) { - if (request.endsWith(`/${mainFile}`)) { - newItems.push({ - context, - request: request.slice(0, -mainFile.length) - }); - newItems.push({ - context, - request: request.slice(0, -mainFile.length - 1) - }); - } + source.add(")"); + } else { + const chunkLoadingGlobal = + runtimeTemplate.outputOptions.chunkLoadingGlobal; + source.add( + `(${globalObject}[${JSON.stringify( + chunkLoadingGlobal + )}] = ${globalObject}[${JSON.stringify( + chunkLoadingGlobal + )}] || []).push([` + ); + source.add(`${JSON.stringify(chunk.ids)},`); + source.add(modules); + const entries = Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ); + if (runtimeModules.length > 0 || entries.length > 0) { + const runtime = new ConcatSource( + (runtimeTemplate.supportsArrowFunction() + ? "__webpack_require__ =>" + : "function(__webpack_require__)") + + " { // webpackRuntimeModules\n" + ); + if (runtimeModules.length > 0) { + runtime.add( + Template.renderRuntimeModules(runtimeModules, { + ...renderContext, + codeGenerationResults: compilation.codeGenerationResults + }) + ); } - newItems.push(obj); - } - items = newItems; - } - - newItems = []; - for (const item of items) { - let hideOriginal = false; - for (const modulesItems of finalResolveOptions.modules) { - if (Array.isArray(modulesItems)) { - for (const dir of modulesItems) { - if (item.request.startsWith(`./${dir}/`)) { - newItems.push({ - context: item.context, - request: item.request.slice(dir.length + 3) - }); - hideOriginal = true; - } - } - } else { - const dir = modulesItems.replace(/\\/g, "/"); - const fullPath = - item.context.replace(/\\/g, "/") + item.request.slice(1); - if (fullPath.startsWith(dir)) { - newItems.push({ - context: item.context, - request: fullPath.slice(dir.length + 1) - }); + if (entries.length > 0) { + const startupSource = new RawSource( + generateEntryStartup( + chunkGraph, + runtimeTemplate, + entries, + chunk, + true + ) + ); + runtime.add( + hooks.renderStartup.call( + startupSource, + entries[entries.length - 1][0], + { + ...renderContext, + inlined: false + } + ) + ); + if ( + chunkGraph + .getChunkRuntimeRequirements(chunk) + .has(RuntimeGlobals.returnExportsFromRuntime) + ) { + runtime.add("return __webpack_exports__;\n"); } } + runtime.add("}\n"); + source.add(",\n"); + source.add(new PrefixSource("/******/ ", runtime)); } - if (!hideOriginal) { - newItems.push(item); - } + source.add("])"); } - return newItems; + return source; + } + ); + hooks.chunkHash.tap( + "ArrayPushCallbackChunkFormatPlugin", + (chunk, hash, { chunkGraph, runtimeTemplate }) => { + if (chunk.hasRuntime()) return; + hash.update( + `ArrayPushCallbackChunkFormatPlugin1${runtimeTemplate.outputOptions.chunkLoadingGlobal}${runtimeTemplate.outputOptions.hotUpdateGlobal}${runtimeTemplate.globalObject}` + ); + const entries = Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ); + updateHashForEntryStartup(hash, chunkGraph, entries, chunk); } ); } ); } } -module.exports = RequireContextPlugin; + +module.exports = ArrayPushCallbackChunkFormatPlugin; /***/ }), -/***/ 27153: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 950: +/***/ (function(module) { "use strict"; /* @@ -89711,306 +88333,485 @@ module.exports = RequireContextPlugin; -const AsyncDependenciesBlock = __webpack_require__(47736); -const makeSerializable = __webpack_require__(33032); +/** @typedef {import("estree").Node} EsTreeNode */ +/** @typedef {import("./JavascriptParser").VariableInfoInterface} VariableInfoInterface */ -class RequireEnsureDependenciesBlock extends AsyncDependenciesBlock { - constructor(chunkName, loc) { - super(chunkName, loc, null); +const TypeUnknown = 0; +const TypeUndefined = 1; +const TypeNull = 2; +const TypeString = 3; +const TypeNumber = 4; +const TypeBoolean = 5; +const TypeRegExp = 6; +const TypeConditional = 7; +const TypeArray = 8; +const TypeConstArray = 9; +const TypeIdentifier = 10; +const TypeWrapped = 11; +const TypeTemplateString = 12; +const TypeBigInt = 13; + +class BasicEvaluatedExpression { + constructor() { + this.type = TypeUnknown; + /** @type {[number, number]} */ + this.range = undefined; + /** @type {boolean} */ + this.falsy = false; + /** @type {boolean} */ + this.truthy = false; + /** @type {boolean | undefined} */ + this.nullish = undefined; + /** @type {boolean} */ + this.sideEffects = true; + /** @type {boolean | undefined} */ + this.bool = undefined; + /** @type {number | undefined} */ + this.number = undefined; + /** @type {bigint | undefined} */ + this.bigint = undefined; + /** @type {RegExp | undefined} */ + this.regExp = undefined; + /** @type {string | undefined} */ + this.string = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.quasis = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.parts = undefined; + /** @type {any[] | undefined} */ + this.array = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.items = undefined; + /** @type {BasicEvaluatedExpression[] | undefined} */ + this.options = undefined; + /** @type {BasicEvaluatedExpression | undefined} */ + this.prefix = undefined; + /** @type {BasicEvaluatedExpression | undefined} */ + this.postfix = undefined; + this.wrappedInnerExpressions = undefined; + /** @type {string | undefined} */ + this.identifier = undefined; + /** @type {VariableInfoInterface} */ + this.rootInfo = undefined; + /** @type {() => string[]} */ + this.getMembers = undefined; + /** @type {EsTreeNode} */ + this.expression = undefined; } -} -makeSerializable( - RequireEnsureDependenciesBlock, - "webpack/lib/dependencies/RequireEnsureDependenciesBlock" -); + isUnknown() { + return this.type === TypeUnknown; + } -module.exports = RequireEnsureDependenciesBlock; + isNull() { + return this.type === TypeNull; + } + isUndefined() { + return this.type === TypeUndefined; + } -/***/ }), + isString() { + return this.type === TypeString; + } -/***/ 7235: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + isNumber() { + return this.type === TypeNumber; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + isBigInt() { + return this.type === TypeBigInt; + } + isBoolean() { + return this.type === TypeBoolean; + } + isRegExp() { + return this.type === TypeRegExp; + } -const RequireEnsureDependenciesBlock = __webpack_require__(27153); -const RequireEnsureDependency = __webpack_require__(27223); -const RequireEnsureItemDependency = __webpack_require__(50329); -const getFunctionExpression = __webpack_require__(50396); + isConditional() { + return this.type === TypeConditional; + } -module.exports = class RequireEnsureDependenciesBlockParserPlugin { - apply(parser) { - parser.hooks.call - .for("require.ensure") - .tap("RequireEnsureDependenciesBlockParserPlugin", expr => { - let chunkName = null; - let errorExpressionArg = null; - let errorExpression = null; - switch (expr.arguments.length) { - case 4: { - const chunkNameExpr = parser.evaluateExpression(expr.arguments[3]); - if (!chunkNameExpr.isString()) return; - chunkName = chunkNameExpr.string; - } - // falls through - case 3: { - errorExpressionArg = expr.arguments[2]; - errorExpression = getFunctionExpression(errorExpressionArg); + isArray() { + return this.type === TypeArray; + } - if (!errorExpression && !chunkName) { - const chunkNameExpr = parser.evaluateExpression( - expr.arguments[2] - ); - if (!chunkNameExpr.isString()) return; - chunkName = chunkNameExpr.string; - } - } - // falls through - case 2: { - const dependenciesExpr = parser.evaluateExpression( - expr.arguments[0] - ); - const dependenciesItems = dependenciesExpr.isArray() - ? dependenciesExpr.items - : [dependenciesExpr]; - const successExpressionArg = expr.arguments[1]; - const successExpression = - getFunctionExpression(successExpressionArg); + isConstArray() { + return this.type === TypeConstArray; + } - if (successExpression) { - parser.walkExpressions(successExpression.expressions); - } - if (errorExpression) { - parser.walkExpressions(errorExpression.expressions); - } + isIdentifier() { + return this.type === TypeIdentifier; + } - const depBlock = new RequireEnsureDependenciesBlock( - chunkName, - expr.loc - ); - const errorCallbackExists = - expr.arguments.length === 4 || - (!chunkName && expr.arguments.length === 3); - const dep = new RequireEnsureDependency( - expr.range, - expr.arguments[1].range, - errorCallbackExists && expr.arguments[2].range - ); - dep.loc = expr.loc; - depBlock.addDependency(dep); - const old = parser.state.current; - parser.state.current = depBlock; - try { - let failed = false; - parser.inScope([], () => { - for (const ee of dependenciesItems) { - if (ee.isString()) { - const ensureDependency = new RequireEnsureItemDependency( - ee.string - ); - ensureDependency.loc = ee.loc || expr.loc; - depBlock.addDependency(ensureDependency); - } else { - failed = true; - } - } - }); - if (failed) { - return; - } - if (successExpression) { - if (successExpression.fn.body.type === "BlockStatement") { - parser.walkStatement(successExpression.fn.body); - } else { - parser.walkExpression(successExpression.fn.body); - } - } - old.addBlock(depBlock); - } finally { - parser.state.current = old; - } - if (!successExpression) { - parser.walkExpression(successExpressionArg); - } - if (errorExpression) { - if (errorExpression.fn.body.type === "BlockStatement") { - parser.walkStatement(errorExpression.fn.body); - } else { - parser.walkExpression(errorExpression.fn.body); - } - } else if (errorExpressionArg) { - parser.walkExpression(errorExpressionArg); - } - return true; - } - } - }); + isWrapped() { + return this.type === TypeWrapped; } -}; + isTemplateString() { + return this.type === TypeTemplateString; + } -/***/ }), + /** + * Is expression a primitive or an object type value? + * @returns {boolean | undefined} true: primitive type, false: object type, undefined: unknown/runtime-defined + */ + isPrimitiveType() { + switch (this.type) { + case TypeUndefined: + case TypeNull: + case TypeString: + case TypeNumber: + case TypeBoolean: + case TypeBigInt: + case TypeWrapped: + case TypeTemplateString: + return true; + case TypeRegExp: + case TypeArray: + case TypeConstArray: + return false; + default: + return undefined; + } + } -/***/ 27223: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * Is expression a runtime or compile-time value? + * @returns {boolean} true: compile time value, false: runtime value + */ + isCompileTimeValue() { + switch (this.type) { + case TypeUndefined: + case TypeNull: + case TypeString: + case TypeNumber: + case TypeBoolean: + case TypeRegExp: + case TypeConstArray: + case TypeBigInt: + return true; + default: + return false; + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * Gets the compile-time value of the expression + * @returns {any} the javascript value + */ + asCompileTimeValue() { + switch (this.type) { + case TypeUndefined: + return undefined; + case TypeNull: + return null; + case TypeString: + return this.string; + case TypeNumber: + return this.number; + case TypeBoolean: + return this.bool; + case TypeRegExp: + return this.regExp; + case TypeConstArray: + return this.array; + case TypeBigInt: + return this.bigint; + default: + throw new Error( + "asCompileTimeValue must only be called for compile-time values" + ); + } + } + isTruthy() { + return this.truthy; + } + isFalsy() { + return this.falsy; + } -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); + isNullish() { + return this.nullish; + } -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ + /** + * Can this expression have side effects? + * @returns {boolean} false: never has side effects + */ + couldHaveSideEffects() { + return this.sideEffects; + } -class RequireEnsureDependency extends NullDependency { - constructor(range, contentRange, errorHandlerRange) { - super(); + asBool() { + if (this.truthy) return true; + if (this.falsy || this.nullish) return false; + if (this.isBoolean()) return this.bool; + if (this.isNull()) return false; + if (this.isUndefined()) return false; + if (this.isString()) return this.string !== ""; + if (this.isNumber()) return this.number !== 0; + if (this.isBigInt()) return this.bigint !== BigInt(0); + if (this.isRegExp()) return true; + if (this.isArray()) return true; + if (this.isConstArray()) return true; + if (this.isWrapped()) { + return (this.prefix && this.prefix.asBool()) || + (this.postfix && this.postfix.asBool()) + ? true + : undefined; + } + if (this.isTemplateString()) { + const str = this.asString(); + if (typeof str === "string") return str !== ""; + } + return undefined; + } - this.range = range; - this.contentRange = contentRange; - this.errorHandlerRange = errorHandlerRange; + asNullish() { + const nullish = this.isNullish(); + + if (nullish === true || this.isNull() || this.isUndefined()) return true; + + if (nullish === false) return false; + if (this.isTruthy()) return false; + if (this.isBoolean()) return false; + if (this.isString()) return false; + if (this.isNumber()) return false; + if (this.isBigInt()) return false; + if (this.isRegExp()) return false; + if (this.isArray()) return false; + if (this.isConstArray()) return false; + if (this.isTemplateString()) return false; + if (this.isRegExp()) return false; + + return undefined; } - get type() { - return "require.ensure"; + asString() { + if (this.isBoolean()) return `${this.bool}`; + if (this.isNull()) return "null"; + if (this.isUndefined()) return "undefined"; + if (this.isString()) return this.string; + if (this.isNumber()) return `${this.number}`; + if (this.isBigInt()) return `${this.bigint}`; + if (this.isRegExp()) return `${this.regExp}`; + if (this.isArray()) { + let array = []; + for (const item of this.items) { + const itemStr = item.asString(); + if (itemStr === undefined) return undefined; + array.push(itemStr); + } + return `${array}`; + } + if (this.isConstArray()) return `${this.array}`; + if (this.isTemplateString()) { + let str = ""; + for (const part of this.parts) { + const partStr = part.asString(); + if (partStr === undefined) return undefined; + str += partStr; + } + return str; + } + return undefined; } - serialize(context) { - const { write } = context; + setString(string) { + this.type = TypeString; + this.string = string; + this.sideEffects = false; + return this; + } - write(this.range); - write(this.contentRange); - write(this.errorHandlerRange); + setUndefined() { + this.type = TypeUndefined; + this.sideEffects = false; + return this; + } - super.serialize(context); + setNull() { + this.type = TypeNull; + this.sideEffects = false; + return this; } - deserialize(context) { - const { read } = context; + setNumber(number) { + this.type = TypeNumber; + this.number = number; + this.sideEffects = false; + return this; + } - this.range = read(); - this.contentRange = read(); - this.errorHandlerRange = read(); + setBigInt(bigint) { + this.type = TypeBigInt; + this.bigint = bigint; + this.sideEffects = false; + return this; + } - super.deserialize(context); + setBoolean(bool) { + this.type = TypeBoolean; + this.bool = bool; + this.sideEffects = false; + return this; } -} -makeSerializable( - RequireEnsureDependency, - "webpack/lib/dependencies/RequireEnsureDependency" -); + setRegExp(regExp) { + this.type = TypeRegExp; + this.regExp = regExp; + this.sideEffects = false; + return this; + } -RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, - { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements } - ) { - const dep = /** @type {RequireEnsureDependency} */ (dependency); - const depBlock = /** @type {AsyncDependenciesBlock} */ ( - moduleGraph.getParentBlock(dep) - ); - const promise = runtimeTemplate.blockPromise({ - chunkGraph, - block: depBlock, - message: "require.ensure", - runtimeRequirements - }); - const range = dep.range; - const contentRange = dep.contentRange; - const errorHandlerRange = dep.errorHandlerRange; - source.replace(range[0], contentRange[0] - 1, `${promise}.then((`); - if (errorHandlerRange) { - source.replace( - contentRange[1], - errorHandlerRange[0] - 1, - ").bind(null, __webpack_require__))['catch'](" - ); - source.replace(errorHandlerRange[1], range[1] - 1, ")"); - } else { - source.replace( - contentRange[1], - range[1] - 1, - `).bind(null, __webpack_require__))['catch'](${RuntimeGlobals.uncaughtErrorHandler})` - ); + setIdentifier(identifier, rootInfo, getMembers) { + this.type = TypeIdentifier; + this.identifier = identifier; + this.rootInfo = rootInfo; + this.getMembers = getMembers; + this.sideEffects = true; + return this; + } + + setWrapped(prefix, postfix, innerExpressions) { + this.type = TypeWrapped; + this.prefix = prefix; + this.postfix = postfix; + this.wrappedInnerExpressions = innerExpressions; + this.sideEffects = true; + return this; + } + + setOptions(options) { + this.type = TypeConditional; + this.options = options; + this.sideEffects = true; + return this; + } + + addOptions(options) { + if (!this.options) { + this.type = TypeConditional; + this.options = []; + this.sideEffects = true; + } + for (const item of options) { + this.options.push(item); } + return this; } -}; -module.exports = RequireEnsureDependency; + setItems(items) { + this.type = TypeArray; + this.items = items; + this.sideEffects = items.some(i => i.couldHaveSideEffects()); + return this; + } + setArray(array) { + this.type = TypeConstArray; + this.array = array; + this.sideEffects = false; + return this; + } -/***/ }), + setTemplateString(quasis, parts, kind) { + this.type = TypeTemplateString; + this.quasis = quasis; + this.parts = parts; + this.templateStringKind = kind; + this.sideEffects = parts.some(p => p.sideEffects); + return this; + } -/***/ 50329: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + setTruthy() { + this.falsy = false; + this.truthy = true; + this.nullish = false; + return this; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + setFalsy() { + this.falsy = true; + this.truthy = false; + return this; + } + setNullish(value) { + this.nullish = value; + if (value) return this.setFalsy(); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const NullDependency = __webpack_require__(31830); + return this; + } -class RequireEnsureItemDependency extends ModuleDependency { - constructor(request) { - super(request); + setRange(range) { + this.range = range; + return this; } - get type() { - return "require.ensure item"; + setSideEffects(sideEffects = true) { + this.sideEffects = sideEffects; + return this; } - get category() { - return "commonjs"; + setExpression(expression) { + this.expression = expression; + return this; } } -makeSerializable( - RequireEnsureItemDependency, - "webpack/lib/dependencies/RequireEnsureItemDependency" -); +/** + * @param {string} flags regexp flags + * @returns {boolean} is valid flags + */ +BasicEvaluatedExpression.isValidRegExpFlags = flags => { + const len = flags.length; -RequireEnsureItemDependency.Template = NullDependency.Template; + if (len === 0) return true; + if (len > 4) return false; -module.exports = RequireEnsureItemDependency; + // cspell:word gimy + let remaining = 0b0000; // bit per RegExp flag: gimy + + for (let i = 0; i < len; i++) + switch (flags.charCodeAt(i)) { + case 103 /* g */: + if (remaining & 0b1000) return false; + remaining |= 0b1000; + break; + case 105 /* i */: + if (remaining & 0b0100) return false; + remaining |= 0b0100; + break; + case 109 /* m */: + if (remaining & 0b0010) return false; + remaining |= 0b0010; + break; + case 121 /* y */: + if (remaining & 0b0001) return false; + remaining |= 0b0001; + break; + default: + return false; + } + + return true; +}; + +module.exports = BasicEvaluatedExpression; /***/ }), -/***/ 8434: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 91145: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -90020,70 +88821,37 @@ module.exports = RequireEnsureItemDependency; -const RequireEnsureDependency = __webpack_require__(27223); -const RequireEnsureItemDependency = __webpack_require__(50329); - -const RequireEnsureDependenciesBlockParserPlugin = __webpack_require__(7235); - -const { - evaluateToString, - toConstantDependency -} = __webpack_require__(93998); - -class RequireEnsurePlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "RequireEnsurePlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - RequireEnsureItemDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - RequireEnsureItemDependency, - new RequireEnsureItemDependency.Template() - ); - - compilation.dependencyTemplates.set( - RequireEnsureDependency, - new RequireEnsureDependency.Template() - ); - - const handler = (parser, parserOptions) => { - if ( - parserOptions.requireEnsure !== undefined && - !parserOptions.requireEnsure - ) - return; +const Entrypoint = __webpack_require__(13795); - new RequireEnsureDependenciesBlockParserPlugin().apply(parser); - parser.hooks.evaluateTypeof - .for("require.ensure") - .tap("RequireEnsurePlugin", evaluateToString("function")); - parser.hooks.typeof - .for("require.ensure") - .tap( - "RequireEnsurePlugin", - toConstantDependency(parser, JSON.stringify("function")) - ); - }; +/** @typedef {import("../Chunk")} Chunk */ - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireEnsurePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireEnsurePlugin", handler); - } - ); +/** + * @param {Entrypoint} entrypoint a chunk group + * @param {Chunk} excludedChunk1 current chunk which is excluded + * @param {Chunk} excludedChunk2 runtime chunk which is excluded + * @returns {Set} chunks + */ +const getAllChunks = (entrypoint, excludedChunk1, excludedChunk2) => { + const queue = new Set([entrypoint]); + const chunks = new Set(); + for (const entrypoint of queue) { + for (const chunk of entrypoint.chunks) { + if (chunk === excludedChunk1) continue; + if (chunk === excludedChunk2) continue; + chunks.add(chunk); + } + for (const parent of entrypoint.parentsIterable) { + if (parent instanceof Entrypoint) queue.add(parent); + } } -} -module.exports = RequireEnsurePlugin; + return chunks; +}; +exports.getAllChunks = getAllChunks; /***/ }), -/***/ 89183: +/***/ 84508: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90094,61 +88862,176 @@ module.exports = RequireEnsurePlugin; +const { ConcatSource, RawSource } = __webpack_require__(51255); const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +const Template = __webpack_require__(1626); +const { + getChunkFilenameTemplate, + getCompilationHooks +} = __webpack_require__(89464); +const { + generateEntryStartup, + updateHashForEntryStartup +} = __webpack_require__(98124); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../Compiler")} Compiler */ -class RequireHeaderDependency extends NullDependency { - constructor(range) { - super(); - if (!Array.isArray(range)) throw new Error("range must be valid"); - this.range = range; - } +class CommonJsChunkFormatPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "CommonJsChunkFormatPlugin", + compilation => { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + "CommonJsChunkLoadingPlugin", + (chunk, set, { chunkGraph }) => { + if (chunk.hasRuntime()) return; + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { + set.add(RuntimeGlobals.require); + set.add(RuntimeGlobals.startupEntrypoint); + set.add(RuntimeGlobals.externalInstallChunk); + } + } + ); + const hooks = getCompilationHooks(compilation); + hooks.renderChunk.tap( + "CommonJsChunkFormatPlugin", + (modules, renderContext) => { + const { chunk, chunkGraph, runtimeTemplate } = renderContext; + const source = new ConcatSource(); + source.add(`exports.id = ${JSON.stringify(chunk.id)};\n`); + source.add(`exports.ids = ${JSON.stringify(chunk.ids)};\n`); + source.add(`exports.modules = `); + source.add(modules); + source.add(";\n"); + const runtimeModules = + chunkGraph.getChunkRuntimeModulesInOrder(chunk); + if (runtimeModules.length > 0) { + source.add("exports.runtime =\n"); + source.add( + Template.renderChunkRuntimeModules( + runtimeModules, + renderContext + ) + ); + } + const entries = Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ); + if (entries.length > 0) { + const runtimeChunk = entries[0][1].getRuntimeChunk(); + const currentOutputName = compilation + .getPath( + getChunkFilenameTemplate(chunk, compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ) + .split("/"); + const runtimeOutputName = compilation + .getPath( + getChunkFilenameTemplate( + runtimeChunk, + compilation.outputOptions + ), + { + chunk: runtimeChunk, + contentHashType: "javascript" + } + ) + .split("/"); - serialize(context) { - const { write } = context; - write(this.range); - super.serialize(context); - } + // remove filename, we only need the directory + currentOutputName.pop(); - static deserialize(context) { - const obj = new RequireHeaderDependency(context.read()); - obj.deserialize(context); - return obj; - } -} + // remove common parts + while ( + currentOutputName.length > 0 && + runtimeOutputName.length > 0 && + currentOutputName[0] === runtimeOutputName[0] + ) { + currentOutputName.shift(); + runtimeOutputName.shift(); + } -makeSerializable( - RequireHeaderDependency, - "webpack/lib/dependencies/RequireHeaderDependency" -); + // create final path + const runtimePath = + (currentOutputName.length > 0 + ? "../".repeat(currentOutputName.length) + : "./") + runtimeOutputName.join("/"); -RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, { runtimeRequirements }) { - const dep = /** @type {RequireHeaderDependency} */ (dependency); - runtimeRequirements.add(RuntimeGlobals.require); - source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__"); + const entrySource = new ConcatSource(); + entrySource.add( + `(${ + runtimeTemplate.supportsArrowFunction() + ? "() => " + : "function() " + }{\n` + ); + entrySource.add("var exports = {};\n"); + entrySource.add(source); + entrySource.add(";\n\n// load runtime\n"); + entrySource.add( + `var __webpack_require__ = require(${JSON.stringify( + runtimePath + )});\n` + ); + entrySource.add( + `${RuntimeGlobals.externalInstallChunk}(exports);\n` + ); + const startupSource = new RawSource( + generateEntryStartup( + chunkGraph, + runtimeTemplate, + entries, + chunk, + false + ) + ); + entrySource.add( + hooks.renderStartup.call( + startupSource, + entries[entries.length - 1][0], + { + ...renderContext, + inlined: false + } + ) + ); + entrySource.add("\n})()"); + return entrySource; + } + return source; + } + ); + hooks.chunkHash.tap( + "CommonJsChunkFormatPlugin", + (chunk, hash, { chunkGraph }) => { + if (chunk.hasRuntime()) return; + hash.update("CommonJsChunkFormatPlugin"); + hash.update("1"); + const entries = Array.from( + chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) + ); + updateHashForEntryStartup(hash, chunkGraph, entries, chunk); + } + ); + } + ); } -}; +} -module.exports = RequireHeaderDependency; +module.exports = CommonJsChunkFormatPlugin; /***/ }), -/***/ 71284: +/***/ 61291: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90159,78 +89042,122 @@ module.exports = RequireHeaderDependency; -const Dependency = __webpack_require__(54912); -const Template = __webpack_require__(39722); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("../../declarations/WebpackOptions").ChunkLoadingType} ChunkLoadingType */ +/** @typedef {import("../Compiler")} Compiler */ -class RequireIncludeDependency extends ModuleDependency { - constructor(request, range) { - super(request); +/** @type {WeakMap>} */ +const enabledTypes = new WeakMap(); - this.range = range; +const getEnabledTypes = compiler => { + let set = enabledTypes.get(compiler); + if (set === undefined) { + set = new Set(); + enabledTypes.set(compiler, set); } + return set; +}; +class EnableChunkLoadingPlugin { /** - * 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 + * @param {ChunkLoadingType} type library type that should be available */ - getReferencedExports(moduleGraph, runtime) { - // This doesn't use any export - return Dependency.NO_EXPORTS_REFERENCED; + constructor(type) { + this.type = type; } - get type() { - return "require.include"; + /** + * @param {Compiler} compiler the compiler instance + * @param {ChunkLoadingType} type type of library + * @returns {void} + */ + static setEnabled(compiler, type) { + getEnabledTypes(compiler).add(type); } - get category() { - return "commonjs"; + /** + * @param {Compiler} compiler the compiler instance + * @param {ChunkLoadingType} type type of library + * @returns {void} + */ + static checkEnabled(compiler, type) { + if (!getEnabledTypes(compiler).has(type)) { + throw new Error( + `Chunk loading type "${type}" is not enabled. ` + + "EnableChunkLoadingPlugin need to be used to enable this type of chunk loading. " + + 'This usually happens through the "output.enabledChunkLoadingTypes" option. ' + + 'If you are using a function as entry which sets "chunkLoading", you need to add all potential chunk loading types to "output.enabledChunkLoadingTypes". ' + + "These types are enabled: " + + Array.from(getEnabledTypes(compiler)).join(", ") + ); + } } -} -makeSerializable( - RequireIncludeDependency, - "webpack/lib/dependencies/RequireIncludeDependency" -); - -RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate extends ( - ModuleDependency.Template -) { /** - * @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 + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - apply(dependency, source, { runtimeTemplate }) { - const dep = /** @type {RequireIncludeDependency} */ (dependency); - const comment = runtimeTemplate.outputOptions.pathinfo - ? Template.toComment( - `require.include ${runtimeTemplate.requestShortener.shorten( - dep.request - )}` - ) - : ""; + apply(compiler) { + const { type } = this; - source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`); + // Only enable once + const enabled = getEnabledTypes(compiler); + if (enabled.has(type)) return; + enabled.add(type); + + if (typeof type === "string") { + switch (type) { + case "jsonp": { + const JsonpChunkLoadingPlugin = __webpack_require__(83121); + new JsonpChunkLoadingPlugin().apply(compiler); + break; + } + case "import-scripts": { + const ImportScriptsChunkLoadingPlugin = __webpack_require__(54182); + new ImportScriptsChunkLoadingPlugin().apply(compiler); + break; + } + case "require": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const CommonJsChunkLoadingPlugin = __webpack_require__(1313); + new CommonJsChunkLoadingPlugin({ + asyncChunkLoading: false + }).apply(compiler); + break; + } + case "async-node": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const CommonJsChunkLoadingPlugin = __webpack_require__(1313); + new CommonJsChunkLoadingPlugin({ + asyncChunkLoading: true + }).apply(compiler); + break; + } + case "import": { + const ModuleChunkLoadingPlugin = __webpack_require__(89831); + new ModuleChunkLoadingPlugin().apply(compiler); + break; + } + case "universal": + // TODO implement universal chunk loading + throw new Error("Universal Chunk Loading is not implemented yet"); + default: + throw new Error(`Unsupported chunk loading type ${type}. +Plugins which provide custom chunk loading types must call EnableChunkLoadingPlugin.setEnabled(compiler, type) to disable this error.`); + } + } else { + // TODO support plugin instances here + // apply them to the compiler + } } -}; +} -module.exports = RequireIncludeDependency; +module.exports = EnableChunkLoadingPlugin; /***/ }), -/***/ 35768: +/***/ 77106: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90241,404 +89168,229 @@ module.exports = RequireIncludeDependency; -const WebpackError = __webpack_require__(53799); -const { - evaluateToString, - toConstantDependency -} = __webpack_require__(93998); -const makeSerializable = __webpack_require__(33032); -const RequireIncludeDependency = __webpack_require__(71284); +const util = __webpack_require__(73837); +const { RawSource, ReplaceSource } = __webpack_require__(51255); +const Generator = __webpack_require__(93401); +const InitFragment = __webpack_require__(55870); +const HarmonyCompatibilityDependency = __webpack_require__(72906); -module.exports = class RequireIncludeDependencyParserPlugin { - constructor(warn) { - this.warn = warn; - } - apply(parser) { - const { warn } = this; - parser.hooks.call - .for("require.include") - .tap("RequireIncludeDependencyParserPlugin", expr => { - if (expr.arguments.length !== 1) return; - const param = parser.evaluateExpression(expr.arguments[0]); - if (!param.isString()) return; +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ - if (warn) { - parser.state.module.addWarning( - new RequireIncludeDeprecationWarning(expr.loc) - ); - } +// TODO: clean up this file +// replace with newer constructs - const dep = new RequireIncludeDependency(param.string, expr.range); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return true; - }); - parser.hooks.evaluateTypeof - .for("require.include") - .tap("RequireIncludePlugin", expr => { - if (warn) { - parser.state.module.addWarning( - new RequireIncludeDeprecationWarning(expr.loc) - ); - } - return evaluateToString("function")(expr); - }); - parser.hooks.typeof - .for("require.include") - .tap("RequireIncludePlugin", expr => { - if (warn) { - parser.state.module.addWarning( - new RequireIncludeDeprecationWarning(expr.loc) - ); - } - return toConstantDependency(parser, JSON.stringify("function"))(expr); - }); - } -}; - -class RequireIncludeDeprecationWarning extends WebpackError { - constructor(loc) { - super("require.include() is deprecated and will be removed soon."); - - this.name = "RequireIncludeDeprecationWarning"; - - this.loc = loc; - } -} - -makeSerializable( - RequireIncludeDeprecationWarning, - "webpack/lib/dependencies/RequireIncludeDependencyParserPlugin", - "RequireIncludeDeprecationWarning" -); - - -/***/ }), - -/***/ 37378: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const RequireIncludeDependency = __webpack_require__(71284); -const RequireIncludeDependencyParserPlugin = __webpack_require__(35768); - -class RequireIncludePlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "RequireIncludePlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - RequireIncludeDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - RequireIncludeDependency, - new RequireIncludeDependency.Template() - ); - - const handler = (parser, parserOptions) => { - if (parserOptions.requireInclude === false) return; - const warn = parserOptions.requireInclude === undefined; - - new RequireIncludeDependencyParserPlugin(warn).apply(parser); - }; - - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireIncludePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireIncludePlugin", handler); - } - ); - } -} -module.exports = RequireIncludePlugin; - - -/***/ }), - -/***/ 55627: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const ContextDependency = __webpack_require__(88101); -const ContextDependencyTemplateAsId = __webpack_require__(76081); - -class RequireResolveContextDependency extends ContextDependency { - constructor(options, range, valueRange) { - super(options); - - this.range = range; - this.valueRange = valueRange; - } - - get type() { - return "amd require context"; - } - - serialize(context) { - const { write } = context; - - write(this.range); - write(this.valueRange); - - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - - this.range = read(); - this.valueRange = read(); - - super.deserialize(context); - } -} - -makeSerializable( - RequireResolveContextDependency, - "webpack/lib/dependencies/RequireResolveContextDependency" +const deprecatedGetInitFragments = util.deprecate( + (template, dependency, templateContext) => + template.getInitFragments(dependency, templateContext), + "DependencyTemplate.getInitFragment is deprecated (use apply(dep, source, { initFragments }) instead)", + "DEP_WEBPACK_JAVASCRIPT_GENERATOR_GET_INIT_FRAGMENTS" ); -RequireResolveContextDependency.Template = ContextDependencyTemplateAsId; - -module.exports = RequireResolveContextDependency; - - -/***/ }), - -/***/ 68582: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Dependency = __webpack_require__(54912); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); -const ModuleDependencyAsId = __webpack_require__(80825); - -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -class RequireResolveDependency extends ModuleDependency { - constructor(request, range) { - super(request); - - this.range = range; - } - - get type() { - return "require.resolve"; - } +const TYPES = new Set(["javascript"]); - get category() { - return "commonjs"; +class JavascriptGenerator extends Generator { + /** + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) + */ + getTypes(module) { + return TYPES; } /** - * 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 + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - getReferencedExports(moduleGraph, runtime) { - // This doesn't use any export - return Dependency.NO_EXPORTS_REFERENCED; + getSize(module, type) { + const originalSource = module.originalSource(); + if (!originalSource) { + return 39; + } + return originalSource.size(); } -} - -makeSerializable( - RequireResolveDependency, - "webpack/lib/dependencies/RequireResolveDependency" -); - -RequireResolveDependency.Template = ModuleDependencyAsId; - -module.exports = RequireResolveDependency; - - -/***/ }), - -/***/ 9880: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - -class RequireResolveHeaderDependency extends NullDependency { - constructor(range) { - super(); - if (!Array.isArray(range)) throw new Error("range must be valid"); + /** + * @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) { + // Only harmony modules are valid for optimization + if ( + !module.buildMeta || + module.buildMeta.exportsType !== "namespace" || + module.presentationalDependencies === undefined || + !module.presentationalDependencies.some( + d => d instanceof HarmonyCompatibilityDependency + ) + ) { + return "Module is not an ECMAScript module"; + } - this.range = range; + // Some expressions are not compatible with module concatenation + // because they may produce unexpected results. The plugin bails out + // if some were detected upfront. + if (module.buildInfo && module.buildInfo.moduleConcatenationBailout) { + return `Module uses ${module.buildInfo.moduleConcatenationBailout}`; + } } - serialize(context) { - const { write } = context; + /** + * @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 originalSource = module.originalSource(); + if (!originalSource) { + return new RawSource("throw new Error('No source available');"); + } - write(this.range); + const source = new ReplaceSource(originalSource); + const initFragments = []; - super.serialize(context); - } + this.sourceModule(module, initFragments, source, generateContext); - static deserialize(context) { - const obj = new RequireResolveHeaderDependency(context.read()); - obj.deserialize(context); - return obj; + return InitFragment.addToSource(source, initFragments, generateContext); } -} - -makeSerializable( - RequireResolveHeaderDependency, - "webpack/lib/dependencies/RequireResolveHeaderDependency" -); -RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTemplate extends ( - NullDependency.Template -) { /** - * @param {Dependency} dependency the dependency for which the template should be applied + * @param {Module} module the module to generate + * @param {InitFragment[]} initFragments mutable list of init fragments * @param {ReplaceSource} source the current replace source which can be modified - * @param {DependencyTemplateContext} templateContext the context object + * @param {GenerateContext} generateContext the generateContext * @returns {void} */ - apply(dependency, source, templateContext) { - const dep = /** @type {RequireResolveHeaderDependency} */ (dependency); - source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); - } - - applyAsTemplateArgument(name, dep, source) { - source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); - } -}; - -module.exports = RequireResolveHeaderDependency; - - -/***/ }), - -/***/ 24187: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); + sourceModule(module, initFragments, source, generateContext) { + for (const dependency of module.dependencies) { + this.sourceDependency( + module, + dependency, + initFragments, + source, + generateContext + ); + } -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/Hash")} Hash */ + if (module.presentationalDependencies !== undefined) { + for (const dependency of module.presentationalDependencies) { + this.sourceDependency( + module, + dependency, + initFragments, + source, + generateContext + ); + } + } -class RuntimeRequirementsDependency extends NullDependency { - /** - * @param {string[]} runtimeRequirements runtime requirements - */ - constructor(runtimeRequirements) { - super(); - this.runtimeRequirements = new Set(runtimeRequirements); - this._hashUpdate = undefined; + for (const childBlock of module.blocks) { + this.sourceBlock( + module, + childBlock, + initFragments, + source, + generateContext + ); + } } /** - * Update the hash - * @param {Hash} hash hash to be updated - * @param {UpdateHashContext} context context + * @param {Module} module the module to generate + * @param {DependenciesBlock} block the dependencies block which will be processed + * @param {InitFragment[]} initFragments mutable list of init fragments + * @param {ReplaceSource} source the current replace source which can be modified + * @param {GenerateContext} generateContext the generateContext * @returns {void} */ - updateHash(hash, context) { - if (this._hashUpdate === undefined) { - this._hashUpdate = Array.from(this.runtimeRequirements).join() + ""; + sourceBlock(module, block, initFragments, source, generateContext) { + for (const dependency of block.dependencies) { + this.sourceDependency( + module, + dependency, + initFragments, + source, + generateContext + ); } - hash.update(this._hashUpdate); - } - - serialize(context) { - const { write } = context; - write(this.runtimeRequirements); - super.serialize(context); - } - deserialize(context) { - const { read } = context; - this.runtimeRequirements = read(); - super.deserialize(context); + for (const childBlock of block.blocks) { + this.sourceBlock( + module, + childBlock, + initFragments, + source, + generateContext + ); + } } -} - -makeSerializable( - RuntimeRequirementsDependency, - "webpack/lib/dependencies/RuntimeRequirementsDependency" -); -RuntimeRequirementsDependency.Template = class RuntimeRequirementsDependencyTemplate extends ( - NullDependency.Template -) { /** - * @param {Dependency} dependency the dependency for which the template should be applied + * @param {Module} module the current module + * @param {Dependency} dependency the dependency to generate + * @param {InitFragment[]} initFragments mutable list of init fragments * @param {ReplaceSource} source the current replace source which can be modified - * @param {DependencyTemplateContext} templateContext the context object + * @param {GenerateContext} generateContext the render context * @returns {void} */ - apply(dependency, source, { runtimeRequirements }) { - const dep = /** @type {RuntimeRequirementsDependency} */ (dependency); - for (const req of dep.runtimeRequirements) { - runtimeRequirements.add(req); + sourceDependency(module, dependency, initFragments, source, generateContext) { + const constructor = /** @type {new (...args: any[]) => Dependency} */ ( + dependency.constructor + ); + const template = generateContext.dependencyTemplates.get(constructor); + if (!template) { + throw new Error( + "No template for dependency: " + dependency.constructor.name + ); + } + + const templateContext = { + runtimeTemplate: generateContext.runtimeTemplate, + dependencyTemplates: generateContext.dependencyTemplates, + moduleGraph: generateContext.moduleGraph, + chunkGraph: generateContext.chunkGraph, + module, + runtime: generateContext.runtime, + runtimeRequirements: generateContext.runtimeRequirements, + concatenationScope: generateContext.concatenationScope, + codeGenerationResults: generateContext.codeGenerationResults, + initFragments + }; + + template.apply(dependency, source, templateContext); + + // TODO remove in webpack 6 + if ("getInitFragments" in template) { + const fragments = deprecatedGetInitFragments( + template, + dependency, + templateContext + ); + + if (fragments) { + for (const fragment of fragments) { + initFragments.push(fragment); + } + } } } -}; +} -module.exports = RuntimeRequirementsDependency; +module.exports = JavascriptGenerator; /***/ }), -/***/ 91418: +/***/ 89464: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90649,94 +89401,188 @@ module.exports = RuntimeRequirementsDependency; -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); +const { SyncWaterfallHook, SyncHook, SyncBailHook } = __webpack_require__(6967); +const vm = __webpack_require__(26144); +const { + ConcatSource, + OriginalSource, + PrefixSource, + RawSource, + CachedSource +} = __webpack_require__(51255); +const Compilation = __webpack_require__(85720); +const { tryRunOrWebpackError } = __webpack_require__(11351); +const HotUpdateChunk = __webpack_require__(9597); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const { last, someInIterable } = __webpack_require__(39104); +const StringXor = __webpack_require__(40293); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const createHash = __webpack_require__(49835); +const { intersectRuntime } = __webpack_require__(17156); +const JavascriptGenerator = __webpack_require__(77106); +const JavascriptParser = __webpack_require__(29050); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ExportSpec} ExportSpec */ -/** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Module")} Module */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ /** @typedef {import("../util/Hash")} Hash */ -class StaticExportsDependency extends NullDependency { - /** - * @param {string[] | true} exports export names - * @param {boolean} canMangle true, if mangling exports names is allowed - */ - constructor(exports, canMangle) { - super(); - this.exports = exports; - this.canMangle = canMangle; - } - - get type() { - return "static exports"; - } - - /** - * Returns the exported names - * @param {ModuleGraph} moduleGraph module graph - * @returns {ExportsSpec | undefined} export names - */ - getExports(moduleGraph) { - return { - exports: this.exports, - canMangle: this.canMangle, - dependencies: undefined - }; - } - - serialize(context) { - const { write } = context; - write(this.exports); - write(this.canMangle); - super.serialize(context); - } +/** + * @param {Chunk} chunk a chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {boolean} true, when a JS file is needed for this chunk + */ +const chunkHasJs = (chunk, chunkGraph) => { + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) return true; - deserialize(context) { - const { read } = context; - this.exports = read(); - this.canMangle = read(); - super.deserialize(context); - } -} + return chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript") + ? true + : false; +}; -makeSerializable( - StaticExportsDependency, - "webpack/lib/dependencies/StaticExportsDependency" -); +const printGeneratedCodeForStack = (module, code) => { + const lines = code.split("\n"); + const n = `${lines.length}`.length; + return `\n\nGenerated code for ${module.identifier()}\n${lines + .map((line, i, lines) => { + const iStr = `${i + 1}`; + return `${" ".repeat(n - iStr.length)}${iStr} | ${line}`; + }) + .join("\n")}`; +}; -module.exports = StaticExportsDependency; +/** + * @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 + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {boolean} strictMode rendering in strict context + */ +/** + * @typedef {Object} MainRenderContext + * @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 + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {string} hash hash to be used for render call + * @property {boolean} strictMode rendering in strict context + */ -/***/ }), +/** + * @typedef {Object} ChunkRenderContext + * @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 + * @property {CodeGenerationResults} codeGenerationResults results of code generation + * @property {InitFragment[]} chunkInitFragments init fragments for the chunk + * @property {boolean} strictMode rendering in strict context + */ -/***/ 97981: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @typedef {Object} RenderBootstrapContext + * @property {Chunk} chunk the chunk + * @property {RuntimeTemplate} runtimeTemplate the runtime template + * @property {ModuleGraph} moduleGraph the module graph + * @property {ChunkGraph} chunkGraph the chunk graph + * @property {string} hash hash to be used for render call + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** @typedef {RenderContext & { inlined: boolean }} StartupRenderContext */ +/** + * @typedef {Object} CompilationHooks + * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModuleContent + * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModuleContainer + * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModulePackage + * @property {SyncWaterfallHook<[Source, RenderContext]>} renderChunk + * @property {SyncWaterfallHook<[Source, RenderContext]>} renderMain + * @property {SyncWaterfallHook<[Source, RenderContext]>} renderContent + * @property {SyncWaterfallHook<[Source, RenderContext]>} render + * @property {SyncWaterfallHook<[Source, Module, StartupRenderContext]>} renderStartup + * @property {SyncWaterfallHook<[string, RenderBootstrapContext]>} renderRequire + * @property {SyncBailHook<[Module, RenderBootstrapContext], string>} inlineInRuntimeBailout + * @property {SyncBailHook<[Module, RenderContext], string>} embedInRuntimeBailout + * @property {SyncBailHook<[RenderContext], string>} strictRuntimeBailout + * @property {SyncHook<[Chunk, Hash, ChunkHashContext]>} chunkHash + * @property {SyncBailHook<[Chunk, RenderContext], boolean>} useSourceMap + */ +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); -const RuntimeGlobals = __webpack_require__(16475); -const WebpackError = __webpack_require__(53799); -const { - evaluateToString, - expressionIsUnsupported, - toConstantDependency -} = __webpack_require__(93998); -const makeSerializable = __webpack_require__(33032); -const ConstDependency = __webpack_require__(76911); -const SystemRuntimeModule = __webpack_require__(85439); +class JavascriptModulesPlugin { + /** + * @param {Compilation} compilation the compilation + * @returns {CompilationHooks} 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 = { + renderModuleContent: new SyncWaterfallHook([ + "source", + "module", + "renderContext" + ]), + renderModuleContainer: new SyncWaterfallHook([ + "source", + "module", + "renderContext" + ]), + renderModulePackage: new SyncWaterfallHook([ + "source", + "module", + "renderContext" + ]), + render: new SyncWaterfallHook(["source", "renderContext"]), + renderContent: new SyncWaterfallHook(["source", "renderContext"]), + renderStartup: new SyncWaterfallHook([ + "source", + "module", + "startupRenderContext" + ]), + renderChunk: new SyncWaterfallHook(["source", "renderContext"]), + renderMain: new SyncWaterfallHook(["source", "renderContext"]), + renderRequire: new SyncWaterfallHook(["code", "renderContext"]), + inlineInRuntimeBailout: new SyncBailHook(["module", "renderContext"]), + embedInRuntimeBailout: new SyncBailHook(["module", "renderContext"]), + strictRuntimeBailout: new SyncBailHook(["renderContext"]), + chunkHash: new SyncHook(["chunk", "hash", "context"]), + useSourceMap: new SyncBailHook(["chunk", "renderContext"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } -/** @typedef {import("../Compiler")} Compiler */ + constructor(options = {}) { + this.options = options; + /** @type {WeakMap} */ + this._moduleFactoryCache = new WeakMap(); + } -class SystemPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance @@ -90744,3777 +89590,4945 @@ class SystemPlugin { */ apply(compiler) { compiler.hooks.compilation.tap( - "SystemPlugin", + "JavascriptModulesPlugin", (compilation, { normalModuleFactory }) => { - compilation.hooks.runtimeRequirementInModule - .for(RuntimeGlobals.system) - .tap("SystemPlugin", (module, set) => { - set.add(RuntimeGlobals.requireScope); + const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); + normalModuleFactory.hooks.createParser + .for("javascript/auto") + .tap("JavascriptModulesPlugin", options => { + return new JavascriptParser("auto"); }); - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.system) - .tap("SystemPlugin", (chunk, set) => { - compilation.addRuntimeModule(chunk, new SystemRuntimeModule()); + normalModuleFactory.hooks.createParser + .for("javascript/dynamic") + .tap("JavascriptModulesPlugin", options => { + return new JavascriptParser("script"); + }); + normalModuleFactory.hooks.createParser + .for("javascript/esm") + .tap("JavascriptModulesPlugin", options => { + return new JavascriptParser("module"); + }); + normalModuleFactory.hooks.createGenerator + .for("javascript/auto") + .tap("JavascriptModulesPlugin", () => { + return new JavascriptGenerator(); + }); + normalModuleFactory.hooks.createGenerator + .for("javascript/dynamic") + .tap("JavascriptModulesPlugin", () => { + return new JavascriptGenerator(); + }); + normalModuleFactory.hooks.createGenerator + .for("javascript/esm") + .tap("JavascriptModulesPlugin", () => { + return new JavascriptGenerator(); }); + compilation.hooks.renderManifest.tap( + "JavascriptModulesPlugin", + (result, options) => { + const { + hash, + chunk, + chunkGraph, + moduleGraph, + runtimeTemplate, + dependencyTemplates, + outputOptions, + codeGenerationResults + } = options; - const handler = (parser, parserOptions) => { - if (parserOptions.system === undefined || !parserOptions.system) { - return; - } + const hotUpdateChunk = + chunk instanceof HotUpdateChunk ? chunk : null; - const setNotSupported = name => { - parser.hooks.evaluateTypeof - .for(name) - .tap("SystemPlugin", evaluateToString("undefined")); - parser.hooks.expression - .for(name) - .tap( - "SystemPlugin", - expressionIsUnsupported( - parser, - name + " is not supported by webpack." - ) + let render; + const filenameTemplate = + JavascriptModulesPlugin.getChunkFilenameTemplate( + chunk, + outputOptions ); - }; - - parser.hooks.typeof - .for("System.import") - .tap( - "SystemPlugin", - toConstantDependency(parser, JSON.stringify("function")) - ); - parser.hooks.evaluateTypeof - .for("System.import") - .tap("SystemPlugin", evaluateToString("function")); - parser.hooks.typeof - .for("System") - .tap( - "SystemPlugin", - toConstantDependency(parser, JSON.stringify("object")) - ); - parser.hooks.evaluateTypeof - .for("System") - .tap("SystemPlugin", evaluateToString("object")); + if (hotUpdateChunk) { + render = () => + this.renderChunk( + { + chunk, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + codeGenerationResults, + strictMode: runtimeTemplate.isModule() + }, + hooks + ); + } else if (chunk.hasRuntime()) { + render = () => + this.renderMain( + { + hash, + chunk, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + codeGenerationResults, + strictMode: runtimeTemplate.isModule() + }, + hooks, + compilation + ); + } else { + if (!chunkHasJs(chunk, chunkGraph)) { + return result; + } - setNotSupported("System.set"); - setNotSupported("System.get"); - setNotSupported("System.register"); + render = () => + this.renderChunk( + { + chunk, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + codeGenerationResults, + strictMode: runtimeTemplate.isModule() + }, + hooks + ); + } - parser.hooks.expression.for("System").tap("SystemPlugin", expr => { - const dep = new ConstDependency(RuntimeGlobals.system, expr.range, [ - RuntimeGlobals.system - ]); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }); + result.push({ + render, + filenameTemplate, + pathOptions: { + hash, + runtime: chunk.runtime, + chunk, + contentHashType: "javascript" + }, + info: { + javascriptModule: compilation.runtimeTemplate.isModule() + }, + identifier: hotUpdateChunk + ? `hotupdatechunk${chunk.id}` + : `chunk${chunk.id}`, + hash: chunk.contentHash.javascript + }); - parser.hooks.call.for("System.import").tap("SystemPlugin", expr => { - parser.state.module.addWarning( - new SystemImportDeprecationWarning(expr.loc) + return result; + } + ); + compilation.hooks.chunkHash.tap( + "JavascriptModulesPlugin", + (chunk, hash, context) => { + hooks.chunkHash.call(chunk, hash, context); + if (chunk.hasRuntime()) { + this.updateHashWithBootstrap( + hash, + { + hash: "0000", + chunk, + chunkGraph: context.chunkGraph, + moduleGraph: context.moduleGraph, + runtimeTemplate: context.runtimeTemplate + }, + hooks + ); + } + } + ); + compilation.hooks.contentHash.tap("JavascriptModulesPlugin", chunk => { + const { + chunkGraph, + moduleGraph, + runtimeTemplate, + outputOptions: { + hashSalt, + hashDigest, + hashDigestLength, + hashFunction + } + } = compilation; + const hash = createHash(hashFunction); + if (hashSalt) hash.update(hashSalt); + if (chunk.hasRuntime()) { + this.updateHashWithBootstrap( + hash, + { + hash: "0000", + chunk, + chunkGraph: compilation.chunkGraph, + moduleGraph: compilation.moduleGraph, + runtimeTemplate: compilation.runtimeTemplate + }, + hooks ); - - return parser.hooks.importCall.call({ - type: "ImportExpression", - source: expr.arguments[0], - loc: expr.loc, - range: expr.range - }); + } else { + hash.update(`${chunk.id} `); + hash.update(chunk.ids ? chunk.ids.join(",") : ""); + } + hooks.chunkHash.call(chunk, hash, { + chunkGraph, + moduleGraph, + runtimeTemplate }); - }; + const modules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "javascript" + ); + if (modules) { + const xor = new StringXor(); + for (const m of modules) { + xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); + } + xor.updateHash(hash); + } + const runtimeModules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "runtime" + ); + if (runtimeModules) { + const xor = new StringXor(); + for (const m of runtimeModules) { + xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); + } + xor.updateHash(hash); + } + const digest = /** @type {string} */ (hash.digest(hashDigest)); + chunk.contentHash.javascript = digest.substr(0, hashDigestLength); + }); + compilation.hooks.additionalTreeRuntimeRequirements.tap( + "JavascriptModulesPlugin", + (chunk, set, { chunkGraph }) => { + if ( + !set.has(RuntimeGlobals.startupNoDefault) && + chunkGraph.hasChunkEntryDependentChunks(chunk) + ) { + set.add(RuntimeGlobals.onChunksLoaded); + set.add(RuntimeGlobals.require); + } + } + ); + compilation.hooks.executeModule.tap( + "JavascriptModulesPlugin", + (options, context) => { + const source = + options.codeGenerationResult.sources.get("javascript"); + if (source === undefined) return; + const { module, moduleObject } = options; + const code = source.source(); - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("SystemPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("SystemPlugin", handler); - } - ); - } -} + const fn = vm.runInThisContext( + `(function(${module.moduleArgument}, ${module.exportsArgument}, __webpack_require__) {\n${code}\n/**/})`, + { + filename: module.identifier(), + lineOffset: -1 + } + ); + try { + fn.call( + moduleObject.exports, + moduleObject, + moduleObject.exports, + context.__webpack_require__ + ); + } catch (e) { + e.stack += printGeneratedCodeForStack(options.module, code); + throw e; + } + } + ); + compilation.hooks.executeModule.tap( + "JavascriptModulesPlugin", + (options, context) => { + const source = options.codeGenerationResult.sources.get("runtime"); + if (source === undefined) return; + let code = source.source(); + if (typeof code !== "string") code = code.toString(); -class SystemImportDeprecationWarning extends WebpackError { - constructor(loc) { - super( - "System.import() is deprecated and will be removed soon. Use import() instead.\n" + - "For more info visit https://webpack.js.org/guides/code-splitting/" - ); - - this.name = "SystemImportDeprecationWarning"; - - this.loc = loc; - } -} - -makeSerializable( - SystemImportDeprecationWarning, - "webpack/lib/dependencies/SystemPlugin", - "SystemImportDeprecationWarning" -); - -module.exports = SystemPlugin; -module.exports.SystemImportDeprecationWarning = SystemImportDeprecationWarning; - - -/***/ }), - -/***/ 85439: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); - -class SystemRuntimeModule extends RuntimeModule { - constructor() { - super("system"); - } - - /** - * @returns {string} runtime code - */ - generate() { - return Template.asString([ - `${RuntimeGlobals.system} = {`, - Template.indent([ - "import: function () {", - Template.indent( - "throw new Error('System.import cannot be used indirectly');" - ), - "}" - ]), - "};" - ]); - } -} - -module.exports = SystemRuntimeModule; - - -/***/ }), - -/***/ 58612: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const { - getDependencyUsedByExportsCondition -} = __webpack_require__(38988); -const makeSerializable = __webpack_require__(33032); -const memoize = __webpack_require__(78676); -const ModuleDependency = __webpack_require__(80321); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -const getRawDataUrlModule = memoize(() => __webpack_require__(19684)); - -class URLDependency extends ModuleDependency { - /** - * @param {string} request request - * @param {[number, number]} range range of the arguments of new URL( |> ... <| ) - * @param {[number, number]} outerRange range of the full |> new URL(...) <| - * @param {boolean=} relative use relative urls instead of absolute with base uri - */ - constructor(request, range, outerRange, relative) { - super(request); - this.range = range; - this.outerRange = outerRange; - this.relative = relative || false; - /** @type {Set | boolean} */ - this.usedByExports = undefined; - } - - get type() { - return "new URL()"; - } - - get category() { - return "url"; - } - - /** - * @param {ModuleGraph} moduleGraph module graph - * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active - */ - getCondition(moduleGraph) { - return getDependencyUsedByExportsCondition( - this, - this.usedByExports, - moduleGraph + const fn = vm.runInThisContext( + `(function(__webpack_require__) {\n${code}\n/**/})`, + { + filename: options.module.identifier(), + lineOffset: -1 + } + ); + try { + fn.call(null, context.__webpack_require__); + } catch (e) { + e.stack += printGeneratedCodeForStack(options.module, code); + throw e; + } + } + ); + } ); } - /** - * @param {string} context context directory - * @returns {Module} a module - */ - createIgnoredModule(context) { - const RawDataUrlModule = getRawDataUrlModule(); - return new RawDataUrlModule("data:,", `ignored-asset`, `(ignored asset)`); - } - - serialize(context) { - const { write } = context; - write(this.outerRange); - write(this.relative); - write(this.usedByExports); - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - this.outerRange = read(); - this.relative = read(); - this.usedByExports = read(); - super.deserialize(context); + static getChunkFilenameTemplate(chunk, outputOptions) { + if (chunk.filenameTemplate) { + return chunk.filenameTemplate; + } else if (chunk instanceof HotUpdateChunk) { + return outputOptions.hotUpdateChunkFilename; + } else if (chunk.canBeInitial()) { + return outputOptions.filename; + } else { + return outputOptions.chunkFilename; + } } -} -URLDependency.Template = class URLDependencyTemplate extends ( - ModuleDependency.Template -) { /** - * @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} + * @param {Module} module the rendered module + * @param {ChunkRenderContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @param {boolean} factory true: renders as factory method, false: pure module content + * @returns {Source} the newly generated source from rendering */ - apply(dependency, source, templateContext) { + renderModule(module, renderContext, hooks, factory) { const { + chunk, chunkGraph, - moduleGraph, - runtimeRequirements, runtimeTemplate, - runtime - } = templateContext; - const dep = /** @type {URLDependency} */ (dependency); - const connection = moduleGraph.getConnection(dep); - // Skip rendering depending when dependency is conditional - if (connection && !connection.isTargetActive(runtime)) { - source.replace( - dep.outerRange[0], - dep.outerRange[1] - 1, - "/* unused asset import */ undefined" + codeGenerationResults, + strictMode + } = renderContext; + try { + const codeGenResult = codeGenerationResults.get(module, chunk.runtime); + const moduleSource = codeGenResult.sources.get("javascript"); + if (!moduleSource) return null; + if (codeGenResult.data !== undefined) { + const chunkInitFragments = codeGenResult.data.get("chunkInitFragments"); + if (chunkInitFragments) { + for (const i of chunkInitFragments) + renderContext.chunkInitFragments.push(i); + } + } + const moduleSourcePostContent = tryRunOrWebpackError( + () => + hooks.renderModuleContent.call(moduleSource, module, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderModuleContent" ); - return; + let moduleSourcePostContainer; + if (factory) { + const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( + module, + chunk.runtime + ); + const needModule = runtimeRequirements.has(RuntimeGlobals.module); + const needExports = runtimeRequirements.has(RuntimeGlobals.exports); + const needRequire = + runtimeRequirements.has(RuntimeGlobals.require) || + runtimeRequirements.has(RuntimeGlobals.requireScope); + const needThisAsExports = runtimeRequirements.has( + RuntimeGlobals.thisAsExports + ); + const needStrict = module.buildInfo.strict && !strictMode; + const cacheEntry = this._moduleFactoryCache.get( + moduleSourcePostContent + ); + let source; + if ( + cacheEntry && + cacheEntry.needModule === needModule && + cacheEntry.needExports === needExports && + cacheEntry.needRequire === needRequire && + cacheEntry.needThisAsExports === needThisAsExports && + cacheEntry.needStrict === needStrict + ) { + source = cacheEntry.source; + } else { + const factorySource = new ConcatSource(); + const args = []; + if (needExports || needRequire || needModule) + args.push( + needModule + ? module.moduleArgument + : "__unused_webpack_" + module.moduleArgument + ); + if (needExports || needRequire) + args.push( + needExports + ? module.exportsArgument + : "__unused_webpack_" + module.exportsArgument + ); + if (needRequire) args.push("__webpack_require__"); + if (!needThisAsExports && runtimeTemplate.supportsArrowFunction()) { + factorySource.add("/***/ ((" + args.join(", ") + ") => {\n\n"); + } else { + factorySource.add("/***/ (function(" + args.join(", ") + ") {\n\n"); + } + if (needStrict) { + factorySource.add('"use strict";\n'); + } + factorySource.add(moduleSourcePostContent); + factorySource.add("\n\n/***/ })"); + source = new CachedSource(factorySource); + this._moduleFactoryCache.set(moduleSourcePostContent, { + source, + needModule, + needExports, + needRequire, + needThisAsExports, + needStrict + }); + } + moduleSourcePostContainer = tryRunOrWebpackError( + () => hooks.renderModuleContainer.call(source, module, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderModuleContainer" + ); + } else { + moduleSourcePostContainer = moduleSourcePostContent; + } + return tryRunOrWebpackError( + () => + hooks.renderModulePackage.call( + moduleSourcePostContainer, + module, + renderContext + ), + "JavascriptModulesPlugin.getCompilationHooks().renderModulePackage" + ); + } catch (e) { + e.module = module; + throw e; } + } - runtimeRequirements.add(RuntimeGlobals.require); - - if (dep.relative) { - runtimeRequirements.add(RuntimeGlobals.relativeUrl); - source.replace( - dep.outerRange[0], - dep.outerRange[1] - 1, - `/* asset import */ new ${ - RuntimeGlobals.relativeUrl - }(${runtimeTemplate.moduleRaw({ - chunkGraph, - module: moduleGraph.getModule(dep), - request: dep.request, - runtimeRequirements, - weak: false - })})` + /** + * @param {RenderContext} renderContext the render context + * @param {CompilationHooks} hooks hooks + * @returns {Source} the rendered source + */ + renderChunk(renderContext, hooks) { + const { chunk, chunkGraph } = renderContext; + const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "javascript", + compareModulesByIdentifier + ); + const allModules = modules ? Array.from(modules) : []; + let strictHeader; + let allStrict = renderContext.strictMode; + if (!allStrict && allModules.every(m => m.buildInfo.strict)) { + const strictBailout = hooks.strictRuntimeBailout.call(renderContext); + strictHeader = strictBailout + ? `// runtime can't be in strict mode because ${strictBailout}.\n` + : '"use strict";\n'; + if (!strictBailout) allStrict = true; + } + /** @type {ChunkRenderContext} */ + const chunkRenderContext = { + ...renderContext, + chunkInitFragments: [], + strictMode: allStrict + }; + const moduleSources = + Template.renderChunkModules(chunkRenderContext, allModules, module => + this.renderModule(module, chunkRenderContext, hooks, true) + ) || new RawSource("{}"); + let source = tryRunOrWebpackError( + () => hooks.renderChunk.call(moduleSources, chunkRenderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderChunk" + ); + source = tryRunOrWebpackError( + () => hooks.renderContent.call(source, chunkRenderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderContent" + ); + if (!source) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something" ); - } else { - runtimeRequirements.add(RuntimeGlobals.baseURI); - - source.replace( - dep.range[0], - dep.range[1] - 1, - `/* asset import */ ${runtimeTemplate.moduleRaw({ - chunkGraph, - module: moduleGraph.getModule(dep), - request: dep.request, - runtimeRequirements, - weak: false - })}, ${RuntimeGlobals.baseURI}` + } + source = InitFragment.addToSource( + source, + chunkRenderContext.chunkInitFragments, + chunkRenderContext + ); + source = tryRunOrWebpackError( + () => hooks.render.call(source, chunkRenderContext), + "JavascriptModulesPlugin.getCompilationHooks().render" + ); + if (!source) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something" ); } + chunk.rendered = true; + return strictHeader + ? new ConcatSource(strictHeader, source, ";") + : renderContext.runtimeTemplate.isModule() + ? source + : new ConcatSource(source, ";"); } -}; - -makeSerializable(URLDependency, "webpack/lib/dependencies/URLDependency"); - -module.exports = URLDependency; - - -/***/ }), - -/***/ 14412: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - - -const { approve } = __webpack_require__(93998); -const InnerGraph = __webpack_require__(38988); -const URLDependency = __webpack_require__(58612); - -/** @typedef {import("estree").NewExpression} NewExpressionNode */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ - -class URLPlugin { /** - * @param {Compiler} compiler compiler + * @param {MainRenderContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @param {Compilation} compilation the compilation + * @returns {Source} the newly generated source from rendering */ - apply(compiler) { - compiler.hooks.compilation.tap( - "URLPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set(URLDependency, normalModuleFactory); - compilation.dependencyTemplates.set( - URLDependency, - new URLDependency.Template() - ); - - /** - * @param {JavascriptParser} parser parser - * @param {object} parserOptions options - */ - const parserCallback = (parser, parserOptions) => { - if (parserOptions.url === false) return; - const relative = parserOptions.url === "relative"; - - /** - * @param {NewExpressionNode} expr expression - * @returns {undefined | string} request - */ - const getUrlRequest = expr => { - if (expr.arguments.length !== 2) return; + renderMain(renderContext, hooks, compilation) { + const { chunk, chunkGraph, runtimeTemplate } = renderContext; - const [arg1, arg2] = expr.arguments; + const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); + const iife = runtimeTemplate.isIIFE(); - if ( - arg2.type !== "MemberExpression" || - arg1.type === "SpreadElement" - ) - return; + const bootstrap = this.renderBootstrap(renderContext, hooks); + const useSourceMap = hooks.useSourceMap.call(chunk, renderContext); - const chain = parser.extractMemberExpressionChain(arg2); + const allModules = Array.from( + chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "javascript", + compareModulesByIdentifier + ) || [] + ); - if ( - chain.members.length !== 1 || - chain.object.type !== "MetaProperty" || - chain.object.meta.name !== "import" || - chain.object.property.name !== "meta" || - chain.members[0] !== "url" - ) - return; + const hasEntryModules = chunkGraph.getNumberOfEntryModules(chunk) > 0; + let inlinedModules; + if (bootstrap.allowInlineStartup && hasEntryModules) { + inlinedModules = new Set(chunkGraph.getChunkEntryModulesIterable(chunk)); + } - const request = parser.evaluateExpression(arg1).asString(); + let source = new ConcatSource(); + let prefix; + if (iife) { + if (runtimeTemplate.supportsArrowFunction()) { + source.add("/******/ (() => { // webpackBootstrap\n"); + } else { + source.add("/******/ (function() { // webpackBootstrap\n"); + } + prefix = "/******/ \t"; + } else { + prefix = "/******/ "; + } + let allStrict = renderContext.strictMode; + if (!allStrict && allModules.every(m => m.buildInfo.strict)) { + const strictBailout = hooks.strictRuntimeBailout.call(renderContext); + if (strictBailout) { + source.add( + prefix + + `// runtime can't be in strict mode because ${strictBailout}.\n` + ); + } else { + allStrict = true; + source.add(prefix + '"use strict";\n'); + } + } - return request; - }; + /** @type {ChunkRenderContext} */ + const chunkRenderContext = { + ...renderContext, + chunkInitFragments: [], + strictMode: allStrict + }; - parser.hooks.canRename.for("URL").tap("URLPlugin", approve); - parser.hooks.new.for("URL").tap("URLPlugin", _expr => { - const expr = /** @type {NewExpressionNode} */ (_expr); + const chunkModules = Template.renderChunkModules( + chunkRenderContext, + inlinedModules + ? allModules.filter(m => !inlinedModules.has(m)) + : allModules, + module => this.renderModule(module, chunkRenderContext, hooks, true), + prefix + ); + if ( + chunkModules || + runtimeRequirements.has(RuntimeGlobals.moduleFactories) || + runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) || + runtimeRequirements.has(RuntimeGlobals.require) + ) { + source.add(prefix + "var __webpack_modules__ = ("); + source.add(chunkModules || "{}"); + source.add(");\n"); + source.add( + "/************************************************************************/\n" + ); + } - const request = getUrlRequest(expr); + if (bootstrap.header.length > 0) { + const header = Template.asString(bootstrap.header) + "\n"; + source.add( + new PrefixSource( + prefix, + useSourceMap + ? new OriginalSource(header, "webpack/bootstrap") + : new RawSource(header) + ) + ); + source.add( + "/************************************************************************/\n" + ); + } - if (!request) return; + const runtimeModules = + renderContext.chunkGraph.getChunkRuntimeModulesInOrder(chunk); - const [arg1, arg2] = expr.arguments; - const dep = new URLDependency( - request, - [arg1.range[0], arg2.range[1]], - expr.range, - relative + if (runtimeModules.length > 0) { + source.add( + new PrefixSource( + prefix, + Template.renderRuntimeModules(runtimeModules, chunkRenderContext) + ) + ); + source.add( + "/************************************************************************/\n" + ); + // runtimeRuntimeModules calls codeGeneration + for (const module of runtimeModules) { + compilation.codeGeneratedModules.add(module); + } + } + if (inlinedModules) { + if (bootstrap.beforeStartup.length > 0) { + const beforeStartup = Template.asString(bootstrap.beforeStartup) + "\n"; + source.add( + new PrefixSource( + prefix, + useSourceMap + ? new OriginalSource(beforeStartup, "webpack/before-startup") + : new RawSource(beforeStartup) + ) + ); + } + const lastInlinedModule = last(inlinedModules); + const startupSource = new ConcatSource(); + startupSource.add(`var __webpack_exports__ = {};\n`); + for (const m of inlinedModules) { + const renderedModule = this.renderModule( + m, + chunkRenderContext, + hooks, + false + ); + if (renderedModule) { + const innerStrict = !allStrict && m.buildInfo.strict; + const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( + m, + chunk.runtime + ); + const exports = runtimeRequirements.has(RuntimeGlobals.exports); + const webpackExports = + exports && m.exportsArgument === "__webpack_exports__"; + let iife = innerStrict + ? "it need to be in strict mode." + : inlinedModules.size > 1 + ? // TODO check globals and top-level declarations of other entries and chunk modules + // to make a better decision + "it need to be isolated against other entry modules." + : chunkModules + ? "it need to be isolated against other modules in the chunk." + : exports && !webpackExports + ? `it uses a non-standard name for the exports (${m.exportsArgument}).` + : hooks.embedInRuntimeBailout.call(m, renderContext); + let footer; + if (iife !== undefined) { + startupSource.add( + `// This entry need to be wrapped in an IIFE because ${iife}\n` ); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); - return true; - }); - parser.hooks.isPure.for("NewExpression").tap("URLPlugin", _expr => { - const expr = /** @type {NewExpressionNode} */ (_expr); - const { callee } = expr; - if (callee.type !== "Identifier") return; - const calleeInfo = parser.getFreeInfoFromVariable(callee.name); - if (!calleeInfo || calleeInfo.name !== "URL") return; - - const request = getUrlRequest(expr); - - if (request) return true; - }); - }; - - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("URLPlugin", parserCallback); - - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("URLPlugin", parserCallback); + const arrow = runtimeTemplate.supportsArrowFunction(); + if (arrow) { + startupSource.add("(() => {\n"); + footer = "\n})();\n\n"; + } else { + startupSource.add("!function() {\n"); + footer = "\n}();\n"; + } + if (innerStrict) startupSource.add('"use strict";\n'); + } else { + footer = "\n"; + } + if (exports) { + if (m !== lastInlinedModule) + startupSource.add(`var ${m.exportsArgument} = {};\n`); + else if (m.exportsArgument !== "__webpack_exports__") + startupSource.add( + `var ${m.exportsArgument} = __webpack_exports__;\n` + ); + } + startupSource.add(renderedModule); + startupSource.add(footer); + } } - ); - } -} - -module.exports = URLPlugin; - - -/***/ }), - -/***/ 51669: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const NullDependency = __webpack_require__(31830); - -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ - -class UnsupportedDependency extends NullDependency { - constructor(request, range) { - super(); - - this.request = request; - this.range = range; - } - - serialize(context) { - const { write } = context; - - write(this.request); - write(this.range); - - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - - this.request = read(); - this.range = read(); - - super.deserialize(context); - } -} - -makeSerializable( - UnsupportedDependency, - "webpack/lib/dependencies/UnsupportedDependency" -); - -UnsupportedDependency.Template = class UnsupportedDependencyTemplate extends ( - NullDependency.Template -) { - /** - * @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, { runtimeTemplate }) { - const dep = /** @type {UnsupportedDependency} */ (dependency); + if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) { + startupSource.add( + `__webpack_exports__ = ${RuntimeGlobals.onChunksLoaded}(__webpack_exports__);\n` + ); + } + source.add( + hooks.renderStartup.call(startupSource, lastInlinedModule, { + ...renderContext, + inlined: true + }) + ); + if (bootstrap.afterStartup.length > 0) { + const afterStartup = Template.asString(bootstrap.afterStartup) + "\n"; + source.add( + new PrefixSource( + prefix, + useSourceMap + ? new OriginalSource(afterStartup, "webpack/after-startup") + : new RawSource(afterStartup) + ) + ); + } + } else { + const lastEntryModule = last( + chunkGraph.getChunkEntryModulesIterable(chunk) + ); + const toSource = useSourceMap + ? (content, name) => + new OriginalSource(Template.asString(content), name) + : content => new RawSource(Template.asString(content)); + source.add( + new PrefixSource( + prefix, + new ConcatSource( + toSource(bootstrap.beforeStartup, "webpack/before-startup"), + "\n", + hooks.renderStartup.call( + toSource(bootstrap.startup.concat(""), "webpack/startup"), + lastEntryModule, + { + ...renderContext, + inlined: false + } + ), + toSource(bootstrap.afterStartup, "webpack/after-startup"), + "\n" + ) + ) + ); + } + if ( + hasEntryModules && + runtimeRequirements.has(RuntimeGlobals.returnExportsFromRuntime) + ) { + source.add(`${prefix}return __webpack_exports__;\n`); + } + if (iife) { + source.add("/******/ })()\n"); + } - source.replace( - dep.range[0], - dep.range[1], - runtimeTemplate.missingModule({ - request: dep.request - }) + /** @type {Source} */ + let finalSource = tryRunOrWebpackError( + () => hooks.renderMain.call(source, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderMain" ); - } -}; - -module.exports = UnsupportedDependency; - - -/***/ }), - -/***/ 52204: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const Dependency = __webpack_require__(54912); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); - -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -class WebAssemblyExportImportedDependency extends ModuleDependency { - constructor(exportName, request, name, valueType) { - super(request); - /** @type {string} */ - this.exportName = exportName; - /** @type {string} */ - this.name = name; - /** @type {string} */ - this.valueType = valueType; + if (!finalSource) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderMain plugins should return something" + ); + } + finalSource = tryRunOrWebpackError( + () => hooks.renderContent.call(finalSource, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderContent" + ); + if (!finalSource) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something" + ); + } + finalSource = InitFragment.addToSource( + finalSource, + chunkRenderContext.chunkInitFragments, + chunkRenderContext + ); + finalSource = tryRunOrWebpackError( + () => hooks.render.call(finalSource, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().render" + ); + if (!finalSource) { + throw new Error( + "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something" + ); + } + chunk.rendered = true; + return iife ? new ConcatSource(finalSource, ";") : finalSource; } /** - * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module + * @param {Hash} hash the hash to be updated + * @param {RenderBootstrapContext} renderContext options object + * @param {CompilationHooks} hooks hooks */ - couldAffectReferencingModule() { - return Dependency.TRANSITIVE; + updateHashWithBootstrap(hash, renderContext, hooks) { + const bootstrap = this.renderBootstrap(renderContext, hooks); + for (const key of Object.keys(bootstrap)) { + hash.update(key); + if (Array.isArray(bootstrap[key])) { + for (const line of bootstrap[key]) { + hash.update(line); + } + } else { + hash.update(JSON.stringify(bootstrap[key])); + } + } } /** - * 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 + * @param {RenderBootstrapContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @returns {{ header: string[], beforeStartup: string[], startup: string[], afterStartup: string[], allowInlineStartup: boolean }} the generated source of the bootstrap code */ - getReferencedExports(moduleGraph, runtime) { - return [[this.name]]; - } - - get type() { - return "wasm export import"; - } - - get category() { - return "wasm"; - } + renderBootstrap(renderContext, hooks) { + const { chunkGraph, moduleGraph, chunk, runtimeTemplate } = renderContext; - serialize(context) { - const { write } = context; + const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); - write(this.exportName); - write(this.name); - write(this.valueType); + const requireFunction = runtimeRequirements.has(RuntimeGlobals.require); + const moduleCache = runtimeRequirements.has(RuntimeGlobals.moduleCache); + const moduleFactories = runtimeRequirements.has( + RuntimeGlobals.moduleFactories + ); + const moduleUsed = runtimeRequirements.has(RuntimeGlobals.module); + const requireScopeUsed = runtimeRequirements.has( + RuntimeGlobals.requireScope + ); + const interceptModuleExecution = runtimeRequirements.has( + RuntimeGlobals.interceptModuleExecution + ); - super.serialize(context); - } + const useRequire = + requireFunction || interceptModuleExecution || moduleUsed; - deserialize(context) { - const { read } = context; + const result = { + header: [], + beforeStartup: [], + startup: [], + afterStartup: [], + allowInlineStartup: true + }; - this.exportName = read(); - this.name = read(); - this.valueType = read(); + let { header: buf, startup, beforeStartup, afterStartup } = result; - super.deserialize(context); - } -} + if (result.allowInlineStartup && moduleFactories) { + startup.push( + "// module factories are used so entry inlining is disabled" + ); + result.allowInlineStartup = false; + } + if (result.allowInlineStartup && moduleCache) { + startup.push("// module cache are used so entry inlining is disabled"); + result.allowInlineStartup = false; + } + if (result.allowInlineStartup && interceptModuleExecution) { + startup.push( + "// module execution is intercepted so entry inlining is disabled" + ); + result.allowInlineStartup = false; + } -makeSerializable( - WebAssemblyExportImportedDependency, - "webpack/lib/dependencies/WebAssemblyExportImportedDependency" -); + if (useRequire || moduleCache) { + buf.push("// The module cache"); + buf.push("var __webpack_module_cache__ = {};"); + buf.push(""); + } -module.exports = WebAssemblyExportImportedDependency; + if (useRequire) { + buf.push("// The require function"); + buf.push(`function __webpack_require__(moduleId) {`); + buf.push(Template.indent(this.renderRequire(renderContext, hooks))); + buf.push("}"); + buf.push(""); + } else if (runtimeRequirements.has(RuntimeGlobals.requireScope)) { + buf.push("// The require scope"); + buf.push("var __webpack_require__ = {};"); + buf.push(""); + } + if ( + moduleFactories || + runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) + ) { + buf.push("// expose the modules object (__webpack_modules__)"); + buf.push(`${RuntimeGlobals.moduleFactories} = __webpack_modules__;`); + buf.push(""); + } -/***/ }), + if (moduleCache) { + buf.push("// expose the module cache"); + buf.push(`${RuntimeGlobals.moduleCache} = __webpack_module_cache__;`); + buf.push(""); + } -/***/ 5239: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (interceptModuleExecution) { + buf.push("// expose the module execution interceptor"); + buf.push(`${RuntimeGlobals.interceptModuleExecution} = [];`); + buf.push(""); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const makeSerializable = __webpack_require__(33032); -const UnsupportedWebAssemblyFeatureError = __webpack_require__(78455); -const ModuleDependency = __webpack_require__(80321); - -/** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -class WebAssemblyImportDependency extends ModuleDependency { - /** - * @param {string} request the request - * @param {string} name the imported name - * @param {ModuleImportDescription} description the WASM ast node - * @param {false | string} onlyDirectImport if only direct imports are allowed - */ - constructor(request, name, description, onlyDirectImport) { - super(request); - /** @type {string} */ - this.name = name; - /** @type {ModuleImportDescription} */ - this.description = description; - /** @type {false | string} */ - this.onlyDirectImport = onlyDirectImport; - } - - get type() { - return "wasm import"; - } - - get category() { - return "wasm"; - } - - /** - * 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 [[this.name]]; - } - - /** - * Returns errors - * @param {ModuleGraph} moduleGraph module graph - * @returns {WebpackError[]} errors - */ - getErrors(moduleGraph) { - const module = moduleGraph.getModule(this); - - if ( - this.onlyDirectImport && - module && - !module.type.startsWith("webassembly") + if (!runtimeRequirements.has(RuntimeGlobals.startupNoDefault)) { + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { + /** @type {string[]} */ + const buf2 = []; + const runtimeRequirements = + chunkGraph.getTreeRuntimeRequirements(chunk); + buf2.push("// Load entry module and return exports"); + let i = chunkGraph.getNumberOfEntryModules(chunk); + for (const [ + entryModule, + entrypoint + ] of chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)) { + const chunks = entrypoint.chunks.filter(c => c !== chunk); + if (result.allowInlineStartup && chunks.length > 0) { + buf2.push( + "// This entry module depends on other loaded chunks and execution need to be delayed" + ); + result.allowInlineStartup = false; + } + if ( + result.allowInlineStartup && + someInIterable( + moduleGraph.getIncomingConnectionsByOriginModule(entryModule), + ([originModule, connections]) => + originModule && + connections.some(c => c.isTargetActive(chunk.runtime)) && + someInIterable( + chunkGraph.getModuleRuntimes(originModule), + runtime => + intersectRuntime(runtime, chunk.runtime) !== undefined + ) + ) + ) { + buf2.push( + "// This entry module is referenced by other modules so it can't be inlined" + ); + result.allowInlineStartup = false; + } + if ( + result.allowInlineStartup && + (!entryModule.buildInfo || + !entryModule.buildInfo.topLevelDeclarations) + ) { + buf2.push( + "// This entry module doesn't tell about it's top-level declarations so it can't be inlined" + ); + result.allowInlineStartup = false; + } + if (result.allowInlineStartup) { + const bailout = hooks.inlineInRuntimeBailout.call( + entryModule, + renderContext + ); + if (bailout !== undefined) { + buf2.push( + `// This entry module can't be inlined because ${bailout}` + ); + result.allowInlineStartup = false; + } + } + i--; + const moduleId = chunkGraph.getModuleId(entryModule); + const entryRuntimeRequirements = + chunkGraph.getModuleRuntimeRequirements(entryModule, chunk.runtime); + let moduleIdExpr = JSON.stringify(moduleId); + if (runtimeRequirements.has(RuntimeGlobals.entryModuleId)) { + moduleIdExpr = `${RuntimeGlobals.entryModuleId} = ${moduleIdExpr}`; + } + if ( + result.allowInlineStartup && + entryRuntimeRequirements.has(RuntimeGlobals.module) + ) { + result.allowInlineStartup = false; + buf2.push( + "// This entry module used 'module' so it can't be inlined" + ); + } + if (chunks.length > 0) { + buf2.push( + `${i === 0 ? "var __webpack_exports__ = " : ""}${ + RuntimeGlobals.onChunksLoaded + }(undefined, ${JSON.stringify( + chunks.map(c => c.id) + )}, ${runtimeTemplate.returningFunction( + `__webpack_require__(${moduleIdExpr})` + )})` + ); + } else if (useRequire) { + buf2.push( + `${ + i === 0 ? "var __webpack_exports__ = " : "" + }__webpack_require__(${moduleIdExpr});` + ); + } else { + if (i === 0) buf2.push("var __webpack_exports__ = {};"); + if (requireScopeUsed) { + buf2.push( + `__webpack_modules__[${moduleIdExpr}](0, ${ + i === 0 ? "__webpack_exports__" : "{}" + }, __webpack_require__);` + ); + } else if (entryRuntimeRequirements.has(RuntimeGlobals.exports)) { + buf2.push( + `__webpack_modules__[${moduleIdExpr}](0, ${ + i === 0 ? "__webpack_exports__" : "{}" + });` + ); + } else { + buf2.push(`__webpack_modules__[${moduleIdExpr}]();`); + } + } + } + if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) { + buf2.push( + `__webpack_exports__ = ${RuntimeGlobals.onChunksLoaded}(__webpack_exports__);` + ); + } + if ( + runtimeRequirements.has(RuntimeGlobals.startup) || + (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) && + runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)) + ) { + result.allowInlineStartup = false; + buf.push("// the startup function"); + buf.push( + `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction("", [ + ...buf2, + "return __webpack_exports__;" + ])};` + ); + buf.push(""); + startup.push("// run startup"); + startup.push( + `var __webpack_exports__ = ${RuntimeGlobals.startup}();` + ); + } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore)) { + buf.push("// the startup function"); + buf.push( + `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` + ); + beforeStartup.push("// run runtime startup"); + beforeStartup.push(`${RuntimeGlobals.startup}();`); + startup.push("// startup"); + startup.push(Template.asString(buf2)); + } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)) { + buf.push("// the startup function"); + buf.push( + `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` + ); + startup.push("// startup"); + startup.push(Template.asString(buf2)); + afterStartup.push("// run runtime startup"); + afterStartup.push(`${RuntimeGlobals.startup}();`); + } else { + startup.push("// startup"); + startup.push(Template.asString(buf2)); + } + } else if ( + runtimeRequirements.has(RuntimeGlobals.startup) || + runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) || + runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter) + ) { + buf.push( + "// the startup function", + "// It's empty as no entry modules are in this chunk", + `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};`, + "" + ); + } + } else if ( + runtimeRequirements.has(RuntimeGlobals.startup) || + runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) || + runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter) ) { - return [ - new UnsupportedWebAssemblyFeatureError( - `Import "${this.name}" from "${this.request}" with ${this.onlyDirectImport} can only be used for direct wasm to wasm dependencies` - ) - ]; + result.allowInlineStartup = false; + buf.push( + "// the startup function", + "// It's empty as some runtime module handles the default behavior", + `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` + ); + startup.push("// run startup"); + startup.push(`var __webpack_exports__ = ${RuntimeGlobals.startup}();`); } + return result; } - serialize(context) { - const { write } = context; - - write(this.name); - write(this.description); - write(this.onlyDirectImport); - - super.serialize(context); - } - - deserialize(context) { - const { read } = context; - - this.name = read(); - this.description = read(); - this.onlyDirectImport = read(); - - super.deserialize(context); + /** + * @param {RenderBootstrapContext} renderContext options object + * @param {CompilationHooks} hooks hooks + * @returns {string} the generated source of the require function + */ + renderRequire(renderContext, hooks) { + const { + chunk, + chunkGraph, + runtimeTemplate: { outputOptions } + } = renderContext; + const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); + const moduleExecution = runtimeRequirements.has( + RuntimeGlobals.interceptModuleExecution + ) + ? Template.asString([ + "var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: __webpack_require__ };", + `${RuntimeGlobals.interceptModuleExecution}.forEach(function(handler) { handler(execOptions); });`, + "module = execOptions.module;", + "execOptions.factory.call(module.exports, module, module.exports, execOptions.require);" + ]) + : runtimeRequirements.has(RuntimeGlobals.thisAsExports) + ? Template.asString([ + "__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);" + ]) + : Template.asString([ + "__webpack_modules__[moduleId](module, module.exports, __webpack_require__);" + ]); + const needModuleId = runtimeRequirements.has(RuntimeGlobals.moduleId); + const needModuleLoaded = runtimeRequirements.has( + RuntimeGlobals.moduleLoaded + ); + const content = Template.asString([ + "// Check if module is in cache", + "var cachedModule = __webpack_module_cache__[moduleId];", + "if (cachedModule !== undefined) {", + outputOptions.strictModuleErrorHandling + ? Template.indent([ + "if (cachedModule.error !== undefined) throw cachedModule.error;", + "return cachedModule.exports;" + ]) + : Template.indent("return cachedModule.exports;"), + "}", + "// Create a new module (and put it into the cache)", + "var module = __webpack_module_cache__[moduleId] = {", + Template.indent([ + needModuleId ? "id: moduleId," : "// no module.id needed", + needModuleLoaded ? "loaded: false," : "// no module.loaded needed", + "exports: {}" + ]), + "};", + "", + outputOptions.strictModuleExceptionHandling + ? Template.asString([ + "// Execute the module function", + "var threw = true;", + "try {", + Template.indent([moduleExecution, "threw = false;"]), + "} finally {", + Template.indent([ + "if(threw) delete __webpack_module_cache__[moduleId];" + ]), + "}" + ]) + : outputOptions.strictModuleErrorHandling + ? Template.asString([ + "// Execute the module function", + "try {", + Template.indent(moduleExecution), + "} catch(e) {", + Template.indent(["module.error = e;", "throw e;"]), + "}" + ]) + : Template.asString([ + "// Execute the module function", + moduleExecution + ]), + needModuleLoaded + ? Template.asString([ + "", + "// Flag the module as loaded", + "module.loaded = true;", + "" + ]) + : "", + "// Return the exports of the module", + "return module.exports;" + ]); + return tryRunOrWebpackError( + () => hooks.renderRequire.call(content, renderContext), + "JavascriptModulesPlugin.getCompilationHooks().renderRequire" + ); } } -makeSerializable( - WebAssemblyImportDependency, - "webpack/lib/dependencies/WebAssemblyImportDependency" -); - -module.exports = WebAssemblyImportDependency; +module.exports = JavascriptModulesPlugin; +module.exports.chunkHasJs = chunkHasJs; /***/ }), -/***/ 26505: +/***/ 29050: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Tobias Koppers @sokra */ -const Dependency = __webpack_require__(54912); -const Template = __webpack_require__(39722); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); +const { Parser: AcornParser } = __webpack_require__(31988); +const { importAssertions } = __webpack_require__(50283); +const { SyncBailHook, HookMap } = __webpack_require__(6967); +const vm = __webpack_require__(26144); +const Parser = __webpack_require__(11715); +const StackedMap = __webpack_require__(58845); +const binarySearchBounds = __webpack_require__(92229); +const memoize = __webpack_require__(78676); +const BasicEvaluatedExpression = __webpack_require__(950); -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("acorn").Options} AcornOptions */ +/** @typedef {import("estree").ArrayExpression} ArrayExpressionNode */ +/** @typedef {import("estree").BinaryExpression} BinaryExpressionNode */ +/** @typedef {import("estree").BlockStatement} BlockStatementNode */ +/** @typedef {import("estree").SequenceExpression} SequenceExpressionNode */ +/** @typedef {import("estree").CallExpression} CallExpressionNode */ +/** @typedef {import("estree").ClassDeclaration} ClassDeclarationNode */ +/** @typedef {import("estree").ClassExpression} ClassExpressionNode */ +/** @typedef {import("estree").Comment} CommentNode */ +/** @typedef {import("estree").ConditionalExpression} ConditionalExpressionNode */ +/** @typedef {import("estree").Declaration} DeclarationNode */ +/** @typedef {import("estree").PrivateIdentifier} PrivateIdentifierNode */ +/** @typedef {import("estree").PropertyDefinition} PropertyDefinitionNode */ +/** @typedef {import("estree").Expression} ExpressionNode */ +/** @typedef {import("estree").Identifier} IdentifierNode */ +/** @typedef {import("estree").IfStatement} IfStatementNode */ +/** @typedef {import("estree").LabeledStatement} LabeledStatementNode */ +/** @typedef {import("estree").Literal} LiteralNode */ +/** @typedef {import("estree").LogicalExpression} LogicalExpressionNode */ +/** @typedef {import("estree").ChainExpression} ChainExpressionNode */ +/** @typedef {import("estree").MemberExpression} MemberExpressionNode */ +/** @typedef {import("estree").MetaProperty} MetaPropertyNode */ +/** @typedef {import("estree").MethodDefinition} MethodDefinitionNode */ +/** @typedef {import("estree").ModuleDeclaration} ModuleDeclarationNode */ +/** @typedef {import("estree").NewExpression} NewExpressionNode */ +/** @typedef {import("estree").Node} AnyNode */ +/** @typedef {import("estree").Program} ProgramNode */ +/** @typedef {import("estree").Statement} StatementNode */ +/** @typedef {import("estree").ImportDeclaration} ImportDeclarationNode */ +/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclarationNode */ +/** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclarationNode */ +/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclarationNode */ +/** @typedef {import("estree").Super} SuperNode */ +/** @typedef {import("estree").TaggedTemplateExpression} TaggedTemplateExpressionNode */ +/** @typedef {import("estree").TemplateLiteral} TemplateLiteralNode */ +/** @typedef {import("estree").ThisExpression} ThisExpressionNode */ +/** @typedef {import("estree").UnaryExpression} UnaryExpressionNode */ +/** @typedef {import("estree").VariableDeclarator} VariableDeclaratorNode */ +/** @template T @typedef {import("tapable").AsArray} AsArray */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ +/** @typedef {{declaredScope: ScopeInfo, freeName: string | true, tagInfo: TagInfo | undefined}} VariableInfoInterface */ +/** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[] }} GetInfoResult */ -class WebpackIsIncludedDependency extends ModuleDependency { - constructor(request, range) { - super(request); +const EMPTY_ARRAY = []; +const ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = 0b01; +const ALLOWED_MEMBER_TYPES_EXPRESSION = 0b10; +const ALLOWED_MEMBER_TYPES_ALL = 0b11; - this.weak = true; - this.range = range; - } +// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API +const parser = AcornParser.extend(importAssertions); + +class VariableInfo { /** - * 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 + * @param {ScopeInfo} declaredScope scope in which the variable is declared + * @param {string | true} freeName which free name the variable aliases, or true when none + * @param {TagInfo | undefined} tagInfo info about tags */ - getReferencedExports(moduleGraph, runtime) { - // This doesn't use any export - return Dependency.NO_EXPORTS_REFERENCED; - } - - get type() { - return "__webpack_is_included__"; + constructor(declaredScope, freeName, tagInfo) { + this.declaredScope = declaredScope; + this.freeName = freeName; + this.tagInfo = tagInfo; } } -makeSerializable( - WebpackIsIncludedDependency, - "webpack/lib/dependencies/WebpackIsIncludedDependency" -); +/** @typedef {string | ScopeInfo | VariableInfo} ExportedVariableInfo */ +/** @typedef {LiteralNode | string | null | undefined} ImportSource */ +/** @typedef {Omit & { sourceType: "module" | "script" | "auto", ecmaVersion?: AcornOptions["ecmaVersion"] }} ParseOptions */ -WebpackIsIncludedDependency.Template = class WebpackIsIncludedDependencyTemplate extends ( - ModuleDependency.Template -) { - /** - * @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, { runtimeTemplate, chunkGraph, moduleGraph }) { - const dep = /** @type {WebpackIsIncludedDependency} */ (dependency); - const connection = moduleGraph.getConnection(dep); - const included = connection - ? chunkGraph.getNumberOfModuleChunks(connection.module) > 0 - : false; - const comment = runtimeTemplate.outputOptions.pathinfo - ? Template.toComment( - `__webpack_is_included__ ${runtimeTemplate.requestShortener.shorten( - dep.request - )}` - ) - : ""; +/** + * @typedef {Object} TagInfo + * @property {any} tag + * @property {any} data + * @property {TagInfo | undefined} next + */ - source.replace( - dep.range[0], - dep.range[1] - 1, - `${comment}${JSON.stringify(included)}` - ); +/** + * @typedef {Object} ScopeInfo + * @property {StackedMap} definitions + * @property {boolean | "arrow"} topLevelScope + * @property {boolean} inShorthand + * @property {boolean} isStrict + * @property {boolean} isAsmJs + * @property {boolean} inTry + */ + +const joinRanges = (startRange, endRange) => { + if (!endRange) return startRange; + if (!startRange) return endRange; + return [startRange[0], endRange[1]]; +}; + +const objectAndMembersToName = (object, membersReversed) => { + let name = object; + for (let i = membersReversed.length - 1; i >= 0; i--) { + name = name + "." + membersReversed[i]; } + return name; }; -module.exports = WebpackIsIncludedDependency; +const getRootName = expression => { + switch (expression.type) { + case "Identifier": + return expression.name; + case "ThisExpression": + return "this"; + case "MetaProperty": + return `${expression.meta.name}.${expression.property.name}`; + default: + return undefined; + } +}; +/** @type {AcornOptions} */ +const defaultParserOptions = { + ranges: true, + locations: true, + ecmaVersion: "latest", + sourceType: "module", + // https://github.com/tc39/proposal-hashbang + allowHashBang: true, + onComment: null +}; -/***/ }), +// regexp to match at least one "magic comment" +const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/); -/***/ 1466: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const EMPTY_COMMENT_OPTIONS = { + options: null, + errors: null +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ +class JavascriptParser extends Parser { + /** + * @param {"module" | "script" | "auto"} sourceType default source type + */ + constructor(sourceType = "auto") { + super(); + this.hooks = Object.freeze({ + /** @type {HookMap>} */ + evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + evaluate: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + evaluateDefinedIdentifier: new HookMap( + () => new SyncBailHook(["expression"]) + ), + /** @type {HookMap>} */ + evaluateCallExpressionMember: new HookMap( + () => new SyncBailHook(["expression", "param"]) + ), + /** @type {HookMap>} */ + isPure: new HookMap( + () => new SyncBailHook(["expression", "commentsStartPosition"]) + ), + /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ + preStatement: new SyncBailHook(["statement"]), + /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ + blockPreStatement: new SyncBailHook(["declaration"]), + /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ + statement: new SyncBailHook(["statement"]), + /** @type {SyncBailHook<[IfStatementNode], boolean | void>} */ + statementIf: new SyncBailHook(["statement"]), + /** @type {SyncBailHook<[ExpressionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ + classExtendsExpression: new SyncBailHook([ + "expression", + "classDefinition" + ]), + /** @type {SyncBailHook<[MethodDefinitionNode | PropertyDefinitionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ + classBodyElement: new SyncBailHook(["element", "classDefinition"]), + /** @type {SyncBailHook<[ExpressionNode, MethodDefinitionNode | PropertyDefinitionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ + classBodyValue: new SyncBailHook([ + "expression", + "element", + "classDefinition" + ]), + /** @type {HookMap>} */ + label: new HookMap(() => new SyncBailHook(["statement"])), + /** @type {SyncBailHook<[ImportDeclarationNode, ImportSource], boolean | void>} */ + import: new SyncBailHook(["statement", "source"]), + /** @type {SyncBailHook<[ImportDeclarationNode, ImportSource, string, string], boolean | void>} */ + importSpecifier: new SyncBailHook([ + "statement", + "source", + "exportName", + "identifierName" + ]), + /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode], boolean | void>} */ + export: new SyncBailHook(["statement"]), + /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, ImportSource], boolean | void>} */ + exportImport: new SyncBailHook(["statement", "source"]), + /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, DeclarationNode], boolean | void>} */ + exportDeclaration: new SyncBailHook(["statement", "declaration"]), + /** @type {SyncBailHook<[ExportDefaultDeclarationNode, DeclarationNode], boolean | void>} */ + exportExpression: new SyncBailHook(["statement", "declaration"]), + /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, string, string, number | undefined], boolean | void>} */ + exportSpecifier: new SyncBailHook([ + "statement", + "identifierName", + "exportName", + "index" + ]), + /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, ImportSource, string, string, number | undefined], boolean | void>} */ + exportImportSpecifier: new SyncBailHook([ + "statement", + "source", + "identifierName", + "exportName", + "index" + ]), + /** @type {SyncBailHook<[VariableDeclaratorNode, StatementNode], boolean | void>} */ + preDeclarator: new SyncBailHook(["declarator", "statement"]), + /** @type {SyncBailHook<[VariableDeclaratorNode, StatementNode], boolean | void>} */ + declarator: new SyncBailHook(["declarator", "statement"]), + /** @type {HookMap>} */ + varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])), + /** @type {HookMap>} */ + pattern: new HookMap(() => new SyncBailHook(["pattern"])), + /** @type {HookMap>} */ + canRename: new HookMap(() => new SyncBailHook(["initExpression"])), + /** @type {HookMap>} */ + rename: new HookMap(() => new SyncBailHook(["initExpression"])), + /** @type {HookMap>} */ + assign: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + assignMemberChain: new HookMap( + () => new SyncBailHook(["expression", "members"]) + ), + /** @type {HookMap>} */ + typeof: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ + importCall: new SyncBailHook(["expression"]), + /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ + topLevelAwait: new SyncBailHook(["expression"]), + /** @type {HookMap>} */ + call: new HookMap(() => new SyncBailHook(["expression"])), + /** Something like "a.b()" */ + /** @type {HookMap>} */ + callMemberChain: new HookMap( + () => new SyncBailHook(["expression", "members"]) + ), + /** Something like "a.b().c.d" */ + /** @type {HookMap>} */ + memberChainOfCallMemberChain: new HookMap( + () => + new SyncBailHook([ + "expression", + "calleeMembers", + "callExpression", + "members" + ]) + ), + /** Something like "a.b().c.d()"" */ + /** @type {HookMap>} */ + callMemberChainOfCallMemberChain: new HookMap( + () => + new SyncBailHook([ + "expression", + "calleeMembers", + "innerCallExpression", + "members" + ]) + ), + /** @type {SyncBailHook<[ChainExpressionNode], boolean | void>} */ + optionalChaining: new SyncBailHook(["optionalChaining"]), + /** @type {HookMap>} */ + new: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + expression: new HookMap(() => new SyncBailHook(["expression"])), + /** @type {HookMap>} */ + expressionMemberChain: new HookMap( + () => new SyncBailHook(["expression", "members"]) + ), + /** @type {HookMap>} */ + unhandledExpressionMemberChain: new HookMap( + () => new SyncBailHook(["expression", "members"]) + ), + /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ + expressionConditionalOperator: new SyncBailHook(["expression"]), + /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ + expressionLogicalOperator: new SyncBailHook(["expression"]), + /** @type {SyncBailHook<[ProgramNode, CommentNode[]], boolean | void>} */ + program: new SyncBailHook(["ast", "comments"]), + /** @type {SyncBailHook<[ProgramNode, CommentNode[]], boolean | void>} */ + finish: new SyncBailHook(["ast", "comments"]) + }); + this.sourceType = sourceType; + /** @type {ScopeInfo} */ + this.scope = undefined; + /** @type {ParserState} */ + this.state = undefined; + this.comments = undefined; + this.semicolons = undefined; + /** @type {(StatementNode|ExpressionNode)[]} */ + this.statementPath = undefined; + this.prevStatement = undefined; + this.currentTagData = undefined; + this._initializeEvaluating(); + } + _initializeEvaluating() { + this.hooks.evaluate.for("Literal").tap("JavascriptParser", _expr => { + const expr = /** @type {LiteralNode} */ (_expr); -const Dependency = __webpack_require__(54912); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const ModuleDependency = __webpack_require__(80321); + switch (typeof expr.value) { + case "number": + return new BasicEvaluatedExpression() + .setNumber(expr.value) + .setRange(expr.range); + case "bigint": + return new BasicEvaluatedExpression() + .setBigInt(expr.value) + .setRange(expr.range); + case "string": + return new BasicEvaluatedExpression() + .setString(expr.value) + .setRange(expr.range); + case "boolean": + return new BasicEvaluatedExpression() + .setBoolean(expr.value) + .setRange(expr.range); + } + if (expr.value === null) { + return new BasicEvaluatedExpression().setNull().setRange(expr.range); + } + if (expr.value instanceof RegExp) { + return new BasicEvaluatedExpression() + .setRegExp(expr.value) + .setRange(expr.range); + } + }); + this.hooks.evaluate.for("NewExpression").tap("JavascriptParser", _expr => { + const expr = /** @type {NewExpressionNode} */ (_expr); + const callee = expr.callee; + if ( + callee.type !== "Identifier" || + callee.name !== "RegExp" || + expr.arguments.length > 2 || + this.getVariableInfo("RegExp") !== "RegExp" + ) + return; -/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ -/** @typedef {import("../AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../Entrypoint")} Entrypoint */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + let regExp, flags; + const arg1 = expr.arguments[0]; -class WorkerDependency extends ModuleDependency { - /** - * @param {string} request request - * @param {[number, number]} range range - */ - constructor(request, range) { - super(request); - this.range = range; - } + if (arg1) { + if (arg1.type === "SpreadElement") return; - /** - * 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.NO_EXPORTS_REFERENCED; - } + const evaluatedRegExp = this.evaluateExpression(arg1); - get type() { - return "new Worker()"; - } + if (!evaluatedRegExp) return; - get category() { - return "worker"; - } -} + regExp = evaluatedRegExp.asString(); -WorkerDependency.Template = class WorkerDependencyTemplate extends ( - ModuleDependency.Template -) { - /** - * @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 { chunkGraph, moduleGraph, runtimeRequirements } = templateContext; - const dep = /** @type {WorkerDependency} */ (dependency); - const block = /** @type {AsyncDependenciesBlock} */ ( - moduleGraph.getParentBlock(dependency) - ); - const entrypoint = /** @type {Entrypoint} */ ( - chunkGraph.getBlockChunkGroup(block) - ); - const chunk = entrypoint.getEntrypointChunk(); + if (!regExp) return; + } else { + return new BasicEvaluatedExpression() + .setRegExp(new RegExp("")) + .setRange(expr.range); + } - runtimeRequirements.add(RuntimeGlobals.publicPath); - runtimeRequirements.add(RuntimeGlobals.baseURI); - runtimeRequirements.add(RuntimeGlobals.getChunkScriptFilename); + const arg2 = expr.arguments[1]; - source.replace( - dep.range[0], - dep.range[1] - 1, - `/* worker import */ ${RuntimeGlobals.publicPath} + ${ - RuntimeGlobals.getChunkScriptFilename - }(${JSON.stringify(chunk.id)}), ${RuntimeGlobals.baseURI}` - ); - } -}; + if (arg2) { + if (arg2.type === "SpreadElement") return; -makeSerializable(WorkerDependency, "webpack/lib/dependencies/WorkerDependency"); + const evaluatedFlags = this.evaluateExpression(arg2); -module.exports = WorkerDependency; + if (!evaluatedFlags) return; + if (!evaluatedFlags.isUndefined()) { + flags = evaluatedFlags.asString(); -/***/ }), + if ( + flags === undefined || + !BasicEvaluatedExpression.isValidRegExpFlags(flags) + ) + return; + } + } -/***/ 82509: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + return new BasicEvaluatedExpression() + .setRegExp(flags ? new RegExp(regExp, flags) : new RegExp(regExp)) + .setRange(expr.range); + }); + this.hooks.evaluate + .for("LogicalExpression") + .tap("JavascriptParser", _expr => { + const expr = /** @type {LogicalExpressionNode} */ (_expr); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const left = this.evaluateExpression(expr.left); + if (!left) return; + let returnRight = false; + /** @type {boolean|undefined} */ + let allowedRight; + if (expr.operator === "&&") { + const leftAsBool = left.asBool(); + if (leftAsBool === false) return left.setRange(expr.range); + returnRight = leftAsBool === true; + allowedRight = false; + } else if (expr.operator === "||") { + const leftAsBool = left.asBool(); + if (leftAsBool === true) return left.setRange(expr.range); + returnRight = leftAsBool === false; + allowedRight = true; + } else if (expr.operator === "??") { + const leftAsNullish = left.asNullish(); + if (leftAsNullish === false) return left.setRange(expr.range); + if (leftAsNullish !== true) return; + returnRight = true; + } else return; + const right = this.evaluateExpression(expr.right); + if (!right) return; + if (returnRight) { + if (left.couldHaveSideEffects()) right.setSideEffects(); + return right.setRange(expr.range); + } + const asBool = right.asBool(); + if (allowedRight === true && asBool === true) { + return new BasicEvaluatedExpression() + .setRange(expr.range) + .setTruthy(); + } else if (allowedRight === false && asBool === false) { + return new BasicEvaluatedExpression().setRange(expr.range).setFalsy(); + } + }); -const { pathToFileURL } = __webpack_require__(57310); -const AsyncDependenciesBlock = __webpack_require__(47736); -const CommentCompilationWarning = __webpack_require__(98427); -const UnsupportedFeatureWarning = __webpack_require__(42495); -const EnableChunkLoadingPlugin = __webpack_require__(61291); -const { equals } = __webpack_require__(84953); -const createHash = __webpack_require__(49835); -const { contextify } = __webpack_require__(82186); -const EnableWasmLoadingPlugin = __webpack_require__(78613); -const ConstDependency = __webpack_require__(76911); -const CreateScriptUrlDependency = __webpack_require__(79062); -const { - harmonySpecifierTag -} = __webpack_require__(20862); -const WorkerDependency = __webpack_require__(1466); + const valueAsExpression = (value, expr, sideEffects) => { + switch (typeof value) { + case "boolean": + return new BasicEvaluatedExpression() + .setBoolean(value) + .setSideEffects(sideEffects) + .setRange(expr.range); + case "number": + return new BasicEvaluatedExpression() + .setNumber(value) + .setSideEffects(sideEffects) + .setRange(expr.range); + case "bigint": + return new BasicEvaluatedExpression() + .setBigInt(value) + .setSideEffects(sideEffects) + .setRange(expr.range); + case "string": + return new BasicEvaluatedExpression() + .setString(value) + .setSideEffects(sideEffects) + .setRange(expr.range); + } + }; -/** @typedef {import("estree").Expression} Expression */ -/** @typedef {import("estree").ObjectExpression} ObjectExpression */ -/** @typedef {import("estree").Pattern} Pattern */ -/** @typedef {import("estree").Property} Property */ -/** @typedef {import("estree").SpreadElement} SpreadElement */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */ -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ -/** @typedef {import("./HarmonyImportDependencyParserPlugin").HarmonySettings} HarmonySettings */ + this.hooks.evaluate + .for("BinaryExpression") + .tap("JavascriptParser", _expr => { + const expr = /** @type {BinaryExpressionNode} */ (_expr); -const getUrl = module => { - return pathToFileURL(module.resource).toString(); -}; + const handleConstOperation = fn => { + const left = this.evaluateExpression(expr.left); + if (!left || !left.isCompileTimeValue()) return; -const DEFAULT_SYNTAX = [ - "Worker", - "SharedWorker", - "navigator.serviceWorker.register()", - "Worker from worker_threads" -]; + const right = this.evaluateExpression(expr.right); + if (!right || !right.isCompileTimeValue()) return; -/** @type {WeakMap} */ -const workerIndexMap = new WeakMap(); + const result = fn( + left.asCompileTimeValue(), + right.asCompileTimeValue() + ); + return valueAsExpression( + result, + expr, + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + }; -class WorkerPlugin { - constructor(chunkLoading, wasmLoading, module) { - this._chunkLoading = chunkLoading; - this._wasmLoading = wasmLoading; - this._module = module; - } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - if (this._chunkLoading) { - new EnableChunkLoadingPlugin(this._chunkLoading).apply(compiler); - } - if (this._wasmLoading) { - new EnableWasmLoadingPlugin(this._wasmLoading).apply(compiler); - } - const cachedContextify = contextify.bindContextCache( - compiler.context, - compiler.root - ); - compiler.hooks.thisCompilation.tap( - "WorkerPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - WorkerDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - WorkerDependency, - new WorkerDependency.Template() - ); - compilation.dependencyTemplates.set( - CreateScriptUrlDependency, - new CreateScriptUrlDependency.Template() - ); + const isAlwaysDifferent = (a, b) => + (a === true && b === false) || (a === false && b === true); - /** - * @param {JavascriptParser} parser the parser - * @param {Expression} expr expression - * @returns {[BasicEvaluatedExpression, [number, number]]} parsed - */ - const parseModuleUrl = (parser, expr) => { - if ( - expr.type !== "NewExpression" || - expr.callee.type === "Super" || - expr.arguments.length !== 2 - ) - return; - const [arg1, arg2] = expr.arguments; - if (arg1.type === "SpreadElement") return; - if (arg2.type === "SpreadElement") return; - const callee = parser.evaluateExpression(expr.callee); - if (!callee.isIdentifier() || callee.identifier !== "URL") return; - const arg2Value = parser.evaluateExpression(arg2); + const handleTemplateStringCompare = (left, right, res, eql) => { + const getPrefix = parts => { + let value = ""; + for (const p of parts) { + const v = p.asString(); + if (v !== undefined) value += v; + else break; + } + return value; + }; + const getSuffix = parts => { + let value = ""; + for (let i = parts.length - 1; i >= 0; i--) { + const v = parts[i].asString(); + if (v !== undefined) value = v + value; + else break; + } + return value; + }; + const leftPrefix = getPrefix(left.parts); + const rightPrefix = getPrefix(right.parts); + const leftSuffix = getSuffix(left.parts); + const rightSuffix = getSuffix(right.parts); + const lenPrefix = Math.min(leftPrefix.length, rightPrefix.length); + const lenSuffix = Math.min(leftSuffix.length, rightSuffix.length); if ( - !arg2Value.isString() || - !arg2Value.string.startsWith("file://") || - arg2Value.string !== getUrl(parser.state.module) + leftPrefix.slice(0, lenPrefix) !== + rightPrefix.slice(0, lenPrefix) || + leftSuffix.slice(-lenSuffix) !== rightSuffix.slice(-lenSuffix) ) { - return; + return res + .setBoolean(!eql) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); } - const arg1Value = parser.evaluateExpression(arg1); - return [arg1Value, [arg1.range[0], arg2.range[1]]]; }; - /** - * @param {JavascriptParser} parser the parser - * @param {ObjectExpression} expr expression - * @returns {{ expressions: Record, otherElements: (Property | SpreadElement)[], values: Record, spread: boolean, insertType: "comma" | "single", insertLocation: number }} parsed object - */ - const parseObjectExpression = (parser, expr) => { - /** @type {Record} */ - const values = {}; - /** @type {Record} */ - const expressions = {}; - /** @type {(Property | SpreadElement)[]} */ - const otherElements = []; - let spread = false; - for (const prop of expr.properties) { - if (prop.type === "SpreadElement") { - spread = true; - } else if ( - prop.type === "Property" && - !prop.method && - !prop.computed && - prop.key.type === "Identifier" - ) { - expressions[prop.key.name] = prop.value; - if (!prop.shorthand && !prop.value.type.endsWith("Pattern")) { - const value = parser.evaluateExpression( - /** @type {Expression} */ (prop.value) - ); - if (value.isCompileTimeValue()) - values[prop.key.name] = value.asCompileTimeValue(); - } - } else { - otherElements.push(prop); - } + const handleStrictEqualityComparison = eql => { + const left = this.evaluateExpression(expr.left); + if (!left) return; + const right = this.evaluateExpression(expr.right); + if (!right) return; + const res = new BasicEvaluatedExpression(); + res.setRange(expr.range); + + const leftConst = left.isCompileTimeValue(); + const rightConst = right.isCompileTimeValue(); + + if (leftConst && rightConst) { + return res + .setBoolean( + eql === + (left.asCompileTimeValue() === right.asCompileTimeValue()) + ) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + + if (left.isArray() && right.isArray()) { + return res + .setBoolean(!eql) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + if (left.isTemplateString() && right.isTemplateString()) { + return handleTemplateStringCompare(left, right, res, eql); + } + + const leftPrimitive = left.isPrimitiveType(); + const rightPrimitive = right.isPrimitiveType(); + + if ( + // Primitive !== Object or + // compile-time object types are never equal to something at runtime + (leftPrimitive === false && + (leftConst || rightPrimitive === true)) || + (rightPrimitive === false && + (rightConst || leftPrimitive === true)) || + // Different nullish or boolish status also means not equal + isAlwaysDifferent(left.asBool(), right.asBool()) || + isAlwaysDifferent(left.asNullish(), right.asNullish()) + ) { + return res + .setBoolean(!eql) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); } - const insertType = expr.properties.length > 0 ? "comma" : "single"; - const insertLocation = - expr.properties[expr.properties.length - 1].range[1]; - return { - expressions, - otherElements, - values, - spread, - insertType, - insertLocation - }; }; - /** - * @param {JavascriptParser} parser the parser - * @param {object} parserOptions options - */ - const parserPlugin = (parser, parserOptions) => { - if (parserOptions.worker === false) return; - const options = !Array.isArray(parserOptions.worker) - ? ["..."] - : parserOptions.worker; - const handleNewWorker = expr => { - if (expr.arguments.length === 0 || expr.arguments.length > 2) - return; - const [arg1, arg2] = expr.arguments; - if (arg1.type === "SpreadElement") return; - if (arg2 && arg2.type === "SpreadElement") return; - const parsedUrl = parseModuleUrl(parser, arg1); - if (!parsedUrl) return; - const [url, range] = parsedUrl; - if (!url.isString()) return; - const { - expressions, - otherElements, - values: options, - spread: hasSpreadInOptions, - insertType, - insertLocation - } = arg2 && arg2.type === "ObjectExpression" - ? parseObjectExpression(parser, arg2) - : { - expressions: {}, - otherElements: [], - values: {}, - spread: false, - insertType: arg2 ? "spread" : "argument", - insertLocation: arg2 ? arg2.range : arg1.range[1] - }; - const { options: importOptions, errors: commentErrors } = - parser.parseCommentOptions(expr.range); + const handleAbstractEqualityComparison = eql => { + const left = this.evaluateExpression(expr.left); + if (!left) return; + const right = this.evaluateExpression(expr.right); + if (!right) return; + const res = new BasicEvaluatedExpression(); + res.setRange(expr.range); - if (commentErrors) { - for (const e of commentErrors) { - const { comment } = e; - parser.state.module.addWarning( - new CommentCompilationWarning( - `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, - comment.loc - ) - ); - } - } + const leftConst = left.isCompileTimeValue(); + const rightConst = right.isCompileTimeValue(); - /** @type {EntryOptions} */ - let entryOptions = {}; + if (leftConst && rightConst) { + return res + .setBoolean( + eql === + // eslint-disable-next-line eqeqeq + (left.asCompileTimeValue() == right.asCompileTimeValue()) + ) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } - if (importOptions) { - if (importOptions.webpackIgnore !== undefined) { - if (typeof importOptions.webpackIgnore !== "boolean") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, - expr.loc - ) - ); - } else { - if (importOptions.webpackIgnore) { - return false; - } - } - } - if (importOptions.webpackEntryOptions !== undefined) { - if ( - typeof importOptions.webpackEntryOptions !== "object" || - importOptions.webpackEntryOptions === null - ) { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackEntryOptions\` expected a object, but received: ${importOptions.webpackEntryOptions}.`, - expr.loc - ) - ); - } else { - Object.assign( - entryOptions, - importOptions.webpackEntryOptions - ); - } - } - if (importOptions.webpackChunkName !== undefined) { - if (typeof importOptions.webpackChunkName !== "string") { - parser.state.module.addWarning( - new UnsupportedFeatureWarning( - `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, - expr.loc - ) - ); - } else { - entryOptions.name = importOptions.webpackChunkName; - } - } - } + if (left.isArray() && right.isArray()) { + return res + .setBoolean(!eql) + .setSideEffects( + left.couldHaveSideEffects() || right.couldHaveSideEffects() + ); + } + if (left.isTemplateString() && right.isTemplateString()) { + return handleTemplateStringCompare(left, right, res, eql); + } + }; - if ( - !Object.prototype.hasOwnProperty.call(entryOptions, "name") && - options && - typeof options.name === "string" + if (expr.operator === "+") { + const left = this.evaluateExpression(expr.left); + if (!left) return; + const right = this.evaluateExpression(expr.right); + if (!right) return; + const res = new BasicEvaluatedExpression(); + if (left.isString()) { + if (right.isString()) { + res.setString(left.string + right.string); + } else if (right.isNumber()) { + res.setString(left.string + right.number); + } else if ( + right.isWrapped() && + right.prefix && + right.prefix.isString() ) { - entryOptions.name = options.name; + // "left" + ("prefix" + inner + "postfix") + // => ("leftPrefix" + inner + "postfix") + res.setWrapped( + new BasicEvaluatedExpression() + .setString(left.string + right.prefix.string) + .setRange(joinRanges(left.range, right.prefix.range)), + right.postfix, + right.wrappedInnerExpressions + ); + } else if (right.isWrapped()) { + // "left" + ([null] + inner + "postfix") + // => ("left" + inner + "postfix") + res.setWrapped( + left, + right.postfix, + right.wrappedInnerExpressions + ); + } else { + // "left" + expr + // => ("left" + expr + "") + res.setWrapped(left, null, [right]); } - - if (entryOptions.runtime === undefined) { - let i = workerIndexMap.get(parser.state) || 0; - workerIndexMap.set(parser.state, i + 1); - let name = `${cachedContextify( - parser.state.module.identifier() - )}|${i}`; - const hash = createHash(compilation.outputOptions.hashFunction); - hash.update(name); - const digest = /** @type {string} */ ( - hash.digest(compilation.outputOptions.hashDigest) + } else if (left.isNumber()) { + if (right.isString()) { + res.setString(left.number + right.string); + } else if (right.isNumber()) { + res.setNumber(left.number + right.number); + } else { + return; + } + } else if (left.isBigInt()) { + if (right.isBigInt()) { + res.setBigInt(left.bigint + right.bigint); + } + } else if (left.isWrapped()) { + if (left.postfix && left.postfix.isString() && right.isString()) { + // ("prefix" + inner + "postfix") + "right" + // => ("prefix" + inner + "postfixRight") + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(left.postfix.string + right.string) + .setRange(joinRanges(left.postfix.range, right.range)), + left.wrappedInnerExpressions ); - entryOptions.runtime = digest.slice( - 0, - compilation.outputOptions.hashDigestLength + } else if ( + left.postfix && + left.postfix.isString() && + right.isNumber() + ) { + // ("prefix" + inner + "postfix") + 123 + // => ("prefix" + inner + "postfix123") + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(left.postfix.string + right.number) + .setRange(joinRanges(left.postfix.range, right.range)), + left.wrappedInnerExpressions + ); + } else if (right.isString()) { + // ("prefix" + inner + [null]) + "right" + // => ("prefix" + inner + "right") + res.setWrapped(left.prefix, right, left.wrappedInnerExpressions); + } else if (right.isNumber()) { + // ("prefix" + inner + [null]) + 123 + // => ("prefix" + inner + "123") + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(right.number + "") + .setRange(right.range), + left.wrappedInnerExpressions + ); + } else if (right.isWrapped()) { + // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2") + // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2") + res.setWrapped( + left.prefix, + right.postfix, + left.wrappedInnerExpressions && + right.wrappedInnerExpressions && + left.wrappedInnerExpressions + .concat(left.postfix ? [left.postfix] : []) + .concat(right.prefix ? [right.prefix] : []) + .concat(right.wrappedInnerExpressions) + ); + } else { + // ("prefix" + inner + postfix) + expr + // => ("prefix" + inner + postfix + expr + [null]) + res.setWrapped( + left.prefix, + null, + left.wrappedInnerExpressions && + left.wrappedInnerExpressions.concat( + left.postfix ? [left.postfix, right] : [right] + ) ); } - - const block = new AsyncDependenciesBlock({ - name: entryOptions.name, - entryOptions: { - chunkLoading: this._chunkLoading, - wasmLoading: this._wasmLoading, - ...entryOptions - } - }); - block.loc = expr.loc; - const dep = new WorkerDependency(url.string, range); - dep.loc = expr.loc; - block.addDependency(dep); - parser.state.module.addBlock(block); - - if (compilation.outputOptions.trustedTypes) { - const dep = new CreateScriptUrlDependency( - expr.arguments[0].range + } else { + if (right.isString()) { + // left + "right" + // => ([null] + left + "right") + res.setWrapped(null, right, [left]); + } else if (right.isWrapped()) { + // left + (prefix + inner + "postfix") + // => ([null] + left + prefix + inner + "postfix") + res.setWrapped( + null, + right.postfix, + right.wrappedInnerExpressions && + (right.prefix ? [left, right.prefix] : [left]).concat( + right.wrappedInnerExpressions + ) ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); + } else { + return; } + } + if (left.couldHaveSideEffects() || right.couldHaveSideEffects()) + res.setSideEffects(); + res.setRange(expr.range); + return res; + } else if (expr.operator === "-") { + return handleConstOperation((l, r) => l - r); + } else if (expr.operator === "*") { + return handleConstOperation((l, r) => l * r); + } else if (expr.operator === "/") { + return handleConstOperation((l, r) => l / r); + } else if (expr.operator === "**") { + return handleConstOperation((l, r) => l ** r); + } else if (expr.operator === "===") { + return handleStrictEqualityComparison(true); + } else if (expr.operator === "==") { + return handleAbstractEqualityComparison(true); + } else if (expr.operator === "!==") { + return handleStrictEqualityComparison(false); + } else if (expr.operator === "!=") { + return handleAbstractEqualityComparison(false); + } else if (expr.operator === "&") { + return handleConstOperation((l, r) => l & r); + } else if (expr.operator === "|") { + return handleConstOperation((l, r) => l | r); + } else if (expr.operator === "^") { + return handleConstOperation((l, r) => l ^ r); + } else if (expr.operator === ">>>") { + return handleConstOperation((l, r) => l >>> r); + } else if (expr.operator === ">>") { + return handleConstOperation((l, r) => l >> r); + } else if (expr.operator === "<<") { + return handleConstOperation((l, r) => l << r); + } else if (expr.operator === "<") { + return handleConstOperation((l, r) => l < r); + } else if (expr.operator === ">") { + return handleConstOperation((l, r) => l > r); + } else if (expr.operator === "<=") { + return handleConstOperation((l, r) => l <= r); + } else if (expr.operator === ">=") { + return handleConstOperation((l, r) => l >= r); + } + }); + this.hooks.evaluate + .for("UnaryExpression") + .tap("JavascriptParser", _expr => { + const expr = /** @type {UnaryExpressionNode} */ (_expr); - if (expressions.type) { - const expr = expressions.type; - if (options.type !== false) { - const dep = new ConstDependency( - this._module ? '"module"' : "undefined", - expr.range - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - expressions.type = undefined; - } - } else if (insertType === "comma") { - if (this._module || hasSpreadInOptions) { - const dep = new ConstDependency( - `, type: ${this._module ? '"module"' : "undefined"}`, - insertLocation - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - } - } else if (insertType === "spread") { - const dep1 = new ConstDependency( - "Object.assign({}, ", - insertLocation[0] + const handleConstOperation = fn => { + const argument = this.evaluateExpression(expr.argument); + if (!argument || !argument.isCompileTimeValue()) return; + const result = fn(argument.asCompileTimeValue()); + return valueAsExpression( + result, + expr, + argument.couldHaveSideEffects() + ); + }; + + if (expr.operator === "typeof") { + switch (expr.argument.type) { + case "Identifier": { + const res = this.callHooksForName( + this.hooks.evaluateTypeof, + expr.argument.name, + expr ); - const dep2 = new ConstDependency( - `, { type: ${this._module ? '"module"' : "undefined"} })`, - insertLocation[1] + if (res !== undefined) return res; + break; + } + case "MetaProperty": { + const res = this.callHooksForName( + this.hooks.evaluateTypeof, + getRootName(expr.argument), + expr ); - dep1.loc = expr.loc; - dep2.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep1); - parser.state.module.addPresentationalDependency(dep2); - } else if (insertType === "argument") { - if (this._module) { - const dep = new ConstDependency( - ', { type: "module" }', - insertLocation - ); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - } + if (res !== undefined) return res; + break; } - - parser.walkExpression(expr.callee); - for (const key of Object.keys(expressions)) { - if (expressions[key]) parser.walkExpression(expressions[key]); + case "MemberExpression": { + const res = this.callHooksForExpression( + this.hooks.evaluateTypeof, + expr.argument, + expr + ); + if (res !== undefined) return res; + break; } - for (const prop of otherElements) { - parser.walkProperty(prop); + case "ChainExpression": { + const res = this.callHooksForExpression( + this.hooks.evaluateTypeof, + expr.argument.expression, + expr + ); + if (res !== undefined) return res; + break; } - if (insertType === "spread") { - parser.walkExpression(arg2); + case "FunctionExpression": { + return new BasicEvaluatedExpression() + .setString("function") + .setRange(expr.range); } + } + const arg = this.evaluateExpression(expr.argument); + if (arg.isUnknown()) return; + if (arg.isString()) { + return new BasicEvaluatedExpression() + .setString("string") + .setRange(expr.range); + } + if (arg.isWrapped()) { + return new BasicEvaluatedExpression() + .setString("string") + .setSideEffects() + .setRange(expr.range); + } + if (arg.isUndefined()) { + return new BasicEvaluatedExpression() + .setString("undefined") + .setRange(expr.range); + } + if (arg.isNumber()) { + return new BasicEvaluatedExpression() + .setString("number") + .setRange(expr.range); + } + if (arg.isBigInt()) { + return new BasicEvaluatedExpression() + .setString("bigint") + .setRange(expr.range); + } + if (arg.isBoolean()) { + return new BasicEvaluatedExpression() + .setString("boolean") + .setRange(expr.range); + } + if (arg.isConstArray() || arg.isRegExp() || arg.isNull()) { + return new BasicEvaluatedExpression() + .setString("object") + .setRange(expr.range); + } + if (arg.isArray()) { + return new BasicEvaluatedExpression() + .setString("object") + .setSideEffects(arg.couldHaveSideEffects()) + .setRange(expr.range); + } + } else if (expr.operator === "!") { + const argument = this.evaluateExpression(expr.argument); + if (!argument) return; + const bool = argument.asBool(); + if (typeof bool !== "boolean") return; + return new BasicEvaluatedExpression() + .setBoolean(!bool) + .setSideEffects(argument.couldHaveSideEffects()) + .setRange(expr.range); + } else if (expr.operator === "~") { + return handleConstOperation(v => ~v); + } else if (expr.operator === "+") { + return handleConstOperation(v => +v); + } else if (expr.operator === "-") { + return handleConstOperation(v => -v); + } + }); + this.hooks.evaluateTypeof.for("undefined").tap("JavascriptParser", expr => { + return new BasicEvaluatedExpression() + .setString("undefined") + .setRange(expr.range); + }); + this.hooks.evaluate.for("Identifier").tap("JavascriptParser", expr => { + if (/** @type {IdentifierNode} */ (expr).name === "undefined") { + return new BasicEvaluatedExpression() + .setUndefined() + .setRange(expr.range); + } + }); + /** + * @param {string} exprType expression type name + * @param {function(ExpressionNode): GetInfoResult | undefined} getInfo get info + * @returns {void} + */ + const tapEvaluateWithVariableInfo = (exprType, getInfo) => { + /** @type {ExpressionNode | undefined} */ + let cachedExpression = undefined; + /** @type {GetInfoResult | undefined} */ + let cachedInfo = undefined; + this.hooks.evaluate.for(exprType).tap("JavascriptParser", expr => { + const expression = /** @type {MemberExpressionNode} */ (expr); - return true; - }; - const processItem = item => { - if (item.endsWith("()")) { - parser.hooks.call - .for(item.slice(0, -2)) - .tap("WorkerPlugin", handleNewWorker); - } else { - const match = /^(.+?)(\(\))?\s+from\s+(.+)$/.exec(item); - if (match) { - const ids = match[1].split("."); - const call = match[2]; - const source = match[3]; - (call ? parser.hooks.call : parser.hooks.new) - .for(harmonySpecifierTag) - .tap("WorkerPlugin", expr => { - const settings = /** @type {HarmonySettings} */ ( - parser.currentTagData - ); - if ( - !settings || - settings.source !== source || - !equals(settings.ids, ids) - ) { - return; - } - return handleNewWorker(expr); - }); - } else { - parser.hooks.new.for(item).tap("WorkerPlugin", handleNewWorker); + const info = getInfo(expr); + if (info !== undefined) { + return this.callHooksForInfoWithFallback( + this.hooks.evaluateIdentifier, + info.name, + name => { + cachedExpression = expression; + cachedInfo = info; + }, + name => { + const hook = this.hooks.evaluateDefinedIdentifier.get(name); + if (hook !== undefined) { + return hook.call(expression); } - } - }; - for (const item of options) { - if (item === "...") { - DEFAULT_SYNTAX.forEach(processItem); - } else processItem(item); + }, + expression + ); + } + }); + this.hooks.evaluate + .for(exprType) + .tap({ name: "JavascriptParser", stage: 100 }, expr => { + const info = cachedExpression === expr ? cachedInfo : getInfo(expr); + if (info !== undefined) { + return new BasicEvaluatedExpression() + .setIdentifier(info.name, info.rootInfo, info.getMembers) + .setRange(expr.range); } - }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("WorkerPlugin", parserPlugin); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("WorkerPlugin", parserPlugin); + }); + this.hooks.finish.tap("JavascriptParser", () => { + // Cleanup for GC + cachedExpression = cachedInfo = undefined; + }); + }; + tapEvaluateWithVariableInfo("Identifier", expr => { + const info = this.getVariableInfo( + /** @type {IdentifierNode} */ (expr).name + ); + if ( + typeof info === "string" || + (info instanceof VariableInfo && typeof info.freeName === "string") + ) { + return { name: info, rootInfo: info, getMembers: () => [] }; + } + }); + tapEvaluateWithVariableInfo("ThisExpression", expr => { + const info = this.getVariableInfo("this"); + if ( + typeof info === "string" || + (info instanceof VariableInfo && typeof info.freeName === "string") + ) { + return { name: info, rootInfo: info, getMembers: () => [] }; } + }); + this.hooks.evaluate.for("MetaProperty").tap("JavascriptParser", expr => { + const metaProperty = /** @type {MetaPropertyNode} */ (expr); + + return this.callHooksForName( + this.hooks.evaluateIdentifier, + getRootName(expr), + metaProperty + ); + }); + tapEvaluateWithVariableInfo("MemberExpression", expr => + this.getMemberExpressionInfo( + /** @type {MemberExpressionNode} */ (expr), + ALLOWED_MEMBER_TYPES_EXPRESSION + ) ); - } -} -module.exports = WorkerPlugin; + this.hooks.evaluate.for("CallExpression").tap("JavascriptParser", _expr => { + const expr = /** @type {CallExpressionNode} */ (_expr); + if ( + expr.callee.type !== "MemberExpression" || + expr.callee.property.type !== + (expr.callee.computed ? "Literal" : "Identifier") + ) { + return; + } -/***/ }), + // type Super also possible here + const param = this.evaluateExpression( + /** @type {ExpressionNode} */ (expr.callee.object) + ); + if (!param) return; + const property = + expr.callee.property.type === "Literal" + ? `${expr.callee.property.value}` + : expr.callee.property.name; + const hook = this.hooks.evaluateCallExpressionMember.get(property); + if (hook !== undefined) { + return hook.call(expr, param); + } + }); + this.hooks.evaluateCallExpressionMember + .for("indexOf") + .tap("JavascriptParser", (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length === 0) return; + const [arg1, arg2] = expr.arguments; + if (arg1.type === "SpreadElement") return; + const arg1Eval = this.evaluateExpression(arg1); + if (!arg1Eval.isString()) return; + const arg1Value = arg1Eval.string; -/***/ 50396: -/***/ (function(module) { + let result; + if (arg2) { + if (arg2.type === "SpreadElement") return; + const arg2Eval = this.evaluateExpression(arg2); + if (!arg2Eval.isNumber()) return; + result = param.string.indexOf(arg1Value, arg2Eval.number); + } else { + result = param.string.indexOf(arg1Value); + } + return new BasicEvaluatedExpression() + .setNumber(result) + .setSideEffects(param.couldHaveSideEffects()) + .setRange(expr.range); + }); + this.hooks.evaluateCallExpressionMember + .for("replace") + .tap("JavascriptParser", (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length !== 2) return; + if (expr.arguments[0].type === "SpreadElement") return; + if (expr.arguments[1].type === "SpreadElement") return; + let arg1 = this.evaluateExpression(expr.arguments[0]); + let arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isString() && !arg1.isRegExp()) return; + const arg1Value = arg1.regExp || arg1.string; + if (!arg2.isString()) return; + const arg2Value = arg2.string; + return new BasicEvaluatedExpression() + .setString(param.string.replace(arg1Value, arg2Value)) + .setSideEffects(param.couldHaveSideEffects()) + .setRange(expr.range); + }); + ["substr", "substring", "slice"].forEach(fn => { + this.hooks.evaluateCallExpressionMember + .for(fn) + .tap("JavascriptParser", (expr, param) => { + if (!param.isString()) return; + let arg1; + let result, + str = param.string; + switch (expr.arguments.length) { + case 1: + if (expr.arguments[0].type === "SpreadElement") return; + arg1 = this.evaluateExpression(expr.arguments[0]); + if (!arg1.isNumber()) return; + result = str[fn](arg1.number); + break; + case 2: { + if (expr.arguments[0].type === "SpreadElement") return; + if (expr.arguments[1].type === "SpreadElement") return; + arg1 = this.evaluateExpression(expr.arguments[0]); + const arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isNumber()) return; + if (!arg2.isNumber()) return; + result = str[fn](arg1.number, arg2.number); + break; + } + default: + return; + } + return new BasicEvaluatedExpression() + .setString(result) + .setSideEffects(param.couldHaveSideEffects()) + .setRange(expr.range); + }); + }); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {"cooked" | "raw"} kind kind of values to get + * @param {TemplateLiteralNode} templateLiteralExpr TemplateLiteral expr + * @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template + */ + const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => { + /** @type {BasicEvaluatedExpression[]} */ + const quasis = []; + /** @type {BasicEvaluatedExpression[]} */ + const parts = []; + for (let i = 0; i < templateLiteralExpr.quasis.length; i++) { + const quasiExpr = templateLiteralExpr.quasis[i]; + const quasi = quasiExpr.value[kind]; + if (i > 0) { + const prevExpr = parts[parts.length - 1]; + const expr = this.evaluateExpression( + templateLiteralExpr.expressions[i - 1] + ); + const exprAsString = expr.asString(); + if ( + typeof exprAsString === "string" && + !expr.couldHaveSideEffects() + ) { + // We can merge quasi + expr + quasi when expr + // is a const string -module.exports = expr => { - // - if ( - expr.type === "FunctionExpression" || - expr.type === "ArrowFunctionExpression" - ) { - return { - fn: expr, - expressions: [], - needThis: false - }; - } + prevExpr.setString(prevExpr.string + exprAsString + quasi); + prevExpr.setRange([prevExpr.range[0], quasiExpr.range[1]]); + // We unset the expression as it doesn't match to a single expression + prevExpr.setExpression(undefined); + continue; + } + parts.push(expr); + } - // .bind() - if ( - expr.type === "CallExpression" && - expr.callee.type === "MemberExpression" && - expr.callee.object.type === "FunctionExpression" && - expr.callee.property.type === "Identifier" && - expr.callee.property.name === "bind" && - expr.arguments.length === 1 - ) { - return { - fn: expr.callee.object, - expressions: [expr.arguments[0]], - needThis: undefined - }; - } - // (function(_this) {return })(this) (Coffeescript) - if ( - expr.type === "CallExpression" && - expr.callee.type === "FunctionExpression" && - expr.callee.body.type === "BlockStatement" && - expr.arguments.length === 1 && - expr.arguments[0].type === "ThisExpression" && - expr.callee.body.body && - expr.callee.body.body.length === 1 && - expr.callee.body.body[0].type === "ReturnStatement" && - expr.callee.body.body[0].argument && - expr.callee.body.body[0].argument.type === "FunctionExpression" - ) { - return { - fn: expr.callee.body.body[0].argument, - expressions: [], - needThis: true + const part = new BasicEvaluatedExpression() + .setString(quasi) + .setRange(quasiExpr.range) + .setExpression(quasiExpr); + quasis.push(part); + parts.push(part); + } + return { + quasis, + parts + }; }; - } -}; - -/***/ }), + this.hooks.evaluate + .for("TemplateLiteral") + .tap("JavascriptParser", _node => { + const node = /** @type {TemplateLiteralNode} */ (_node); -/***/ 55207: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const { quasis, parts } = getSimplifiedTemplateResult("cooked", node); + if (parts.length === 1) { + return parts[0].setRange(node.range); + } + return new BasicEvaluatedExpression() + .setTemplateString(quasis, parts, "cooked") + .setRange(node.range); + }); + this.hooks.evaluate + .for("TaggedTemplateExpression") + .tap("JavascriptParser", _node => { + const node = /** @type {TaggedTemplateExpressionNode} */ (_node); + const tag = this.evaluateExpression(node.tag); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { UsageState } = __webpack_require__(63686); + if (tag.isIdentifier() && tag.identifier === "String.raw") { + const { quasis, parts } = getSimplifiedTemplateResult( + "raw", + node.quasi + ); + return new BasicEvaluatedExpression() + .setTemplateString(quasis, parts, "raw") + .setRange(node.range); + } + }); -/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + this.hooks.evaluateCallExpressionMember + .for("concat") + .tap("JavascriptParser", (expr, param) => { + if (!param.isString() && !param.isWrapped()) return; -/** - * @param {RuntimeSpec} runtime the runtime - * @param {string[][]} referencedExports list of referenced exports, will be added to - * @param {string[]} prefix export prefix - * @param {ExportInfo=} exportInfo the export info - * @param {boolean} defaultPointsToSelf when true, using default will reference itself - * @param {Set} alreadyVisited already visited export info (to handle circular reexports) - */ -const processExportInfo = ( - runtime, - referencedExports, - prefix, - exportInfo, - defaultPointsToSelf = false, - alreadyVisited = new Set() -) => { - if (!exportInfo) { - referencedExports.push(prefix); - return; - } - const used = exportInfo.getUsed(runtime); - if (used === UsageState.Unused) return; - if (alreadyVisited.has(exportInfo)) { - referencedExports.push(prefix); - return; - } - alreadyVisited.add(exportInfo); - if ( - used !== UsageState.OnlyPropertiesUsed || - !exportInfo.exportsInfo || - exportInfo.exportsInfo.otherExportsInfo.getUsed(runtime) !== - UsageState.Unused - ) { - alreadyVisited.delete(exportInfo); - referencedExports.push(prefix); - return; - } - const exportsInfo = exportInfo.exportsInfo; - for (const exportInfo of exportsInfo.orderedExports) { - processExportInfo( - runtime, - referencedExports, - defaultPointsToSelf && exportInfo.name === "default" - ? prefix - : prefix.concat(exportInfo.name), - exportInfo, - false, - alreadyVisited - ); - } - alreadyVisited.delete(exportInfo); -}; -module.exports = processExportInfo; + let stringSuffix = null; + let hasUnknownParams = false; + const innerExpressions = []; + for (let i = expr.arguments.length - 1; i >= 0; i--) { + const arg = expr.arguments[i]; + if (arg.type === "SpreadElement") return; + const argExpr = this.evaluateExpression(arg); + if ( + hasUnknownParams || + (!argExpr.isString() && !argExpr.isNumber()) + ) { + hasUnknownParams = true; + innerExpressions.push(argExpr); + continue; + } + const value = argExpr.isString() + ? argExpr.string + : "" + argExpr.number; -/***/ }), + const newString = value + (stringSuffix ? stringSuffix.string : ""); + const newRange = [ + argExpr.range[0], + (stringSuffix || argExpr).range[1] + ]; + stringSuffix = new BasicEvaluatedExpression() + .setString(newString) + .setSideEffects( + (stringSuffix && stringSuffix.couldHaveSideEffects()) || + argExpr.couldHaveSideEffects() + ) + .setRange(newRange); + } -/***/ 32277: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (hasUnknownParams) { + const prefix = param.isString() ? param : param.prefix; + const inner = + param.isWrapped() && param.wrappedInnerExpressions + ? param.wrappedInnerExpressions.concat(innerExpressions.reverse()) + : innerExpressions.reverse(); + return new BasicEvaluatedExpression() + .setWrapped(prefix, stringSuffix, inner) + .setRange(expr.range); + } else if (param.isWrapped()) { + const postfix = stringSuffix || param.postfix; + const inner = param.wrappedInnerExpressions + ? param.wrappedInnerExpressions.concat(innerExpressions.reverse()) + : innerExpressions.reverse(); + return new BasicEvaluatedExpression() + .setWrapped(param.prefix, postfix, inner) + .setRange(expr.range); + } else { + const newString = + param.string + (stringSuffix ? stringSuffix.string : ""); + return new BasicEvaluatedExpression() + .setString(newString) + .setSideEffects( + (stringSuffix && stringSuffix.couldHaveSideEffects()) || + param.couldHaveSideEffects() + ) + .setRange(expr.range); + } + }); + this.hooks.evaluateCallExpressionMember + .for("split") + .tap("JavascriptParser", (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length !== 1) return; + if (expr.arguments[0].type === "SpreadElement") return; + let result; + const arg = this.evaluateExpression(expr.arguments[0]); + if (arg.isString()) { + result = param.string.split(arg.string); + } else if (arg.isRegExp()) { + result = param.string.split(arg.regExp); + } else { + return; + } + return new BasicEvaluatedExpression() + .setArray(result) + .setSideEffects(param.couldHaveSideEffects()) + .setRange(expr.range); + }); + this.hooks.evaluate + .for("ConditionalExpression") + .tap("JavascriptParser", _expr => { + const expr = /** @type {ConditionalExpressionNode} */ (_expr); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const condition = this.evaluateExpression(expr.test); + const conditionValue = condition.asBool(); + let res; + if (conditionValue === undefined) { + const consequent = this.evaluateExpression(expr.consequent); + const alternate = this.evaluateExpression(expr.alternate); + if (!consequent || !alternate) return; + res = new BasicEvaluatedExpression(); + if (consequent.isConditional()) { + res.setOptions(consequent.options); + } else { + res.setOptions([consequent]); + } + if (alternate.isConditional()) { + res.addOptions(alternate.options); + } else { + res.addOptions([alternate]); + } + } else { + res = this.evaluateExpression( + conditionValue ? expr.consequent : expr.alternate + ); + if (condition.couldHaveSideEffects()) res.setSideEffects(); + } + res.setRange(expr.range); + return res; + }); + this.hooks.evaluate + .for("ArrayExpression") + .tap("JavascriptParser", _expr => { + const expr = /** @type {ArrayExpressionNode} */ (_expr); + const items = expr.elements.map(element => { + return ( + element !== null && + element.type !== "SpreadElement" && + this.evaluateExpression(element) + ); + }); + if (!items.every(Boolean)) return; + return new BasicEvaluatedExpression() + .setItems(items) + .setRange(expr.range); + }); + this.hooks.evaluate + .for("ChainExpression") + .tap("JavascriptParser", _expr => { + const expr = /** @type {ChainExpressionNode} */ (_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; + } + } -const ExternalsPlugin = __webpack_require__(6652); + while (optionalExpressionsStack.length > 0) { + const expression = optionalExpressionsStack.pop(); + const evaluated = this.evaluateExpression(expression); -/** @typedef {import("../Compiler")} Compiler */ + if (evaluated && evaluated.asNullish()) { + return evaluated.setRange(_expr.range); + } + } + return this.evaluateExpression(expr.expression); + }); + } -class ElectronTargetPlugin { - /** - * @param {"main" | "preload" | "renderer"=} context in main, preload or renderer context? - */ - constructor(context) { - this._context = context; + getRenameIdentifier(expr) { + const result = this.evaluateExpression(expr); + if (result && result.isIdentifier()) { + return result.identifier; + } } + /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {ClassExpressionNode | ClassDeclarationNode} classy a class node * @returns {void} */ - apply(compiler) { - new ExternalsPlugin("node-commonjs", [ - "clipboard", - "crash-reporter", - "electron", - "ipc", - "native-image", - "original-fs", - "screen", - "shell" - ]).apply(compiler); - switch (this._context) { - case "main": - new ExternalsPlugin("node-commonjs", [ - "app", - "auto-updater", - "browser-window", - "content-tracing", - "dialog", - "global-shortcut", - "ipc-main", - "menu", - "menu-item", - "power-monitor", - "power-save-blocker", - "protocol", - "session", - "tray", - "web-contents" - ]).apply(compiler); - break; - case "preload": - case "renderer": - new ExternalsPlugin("node-commonjs", [ - "desktop-capturer", - "ipc-renderer", - "remote", - "web-frame" - ]).apply(compiler); - break; + walkClass(classy) { + if (classy.superClass) { + if (!this.hooks.classExtendsExpression.call(classy.superClass, classy)) { + this.walkExpression(classy.superClass); + } + } + if (classy.body && classy.body.type === "ClassBody") { + for (const classElement of /** @type {TODO} */ (classy.body.body)) { + if (!this.hooks.classBodyElement.call(classElement, classy)) { + if (classElement.computed && classElement.key) { + this.walkExpression(classElement.key); + } + if (classElement.value) { + if ( + !this.hooks.classBodyValue.call( + classElement.value, + classElement, + classy + ) + ) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + this.walkExpression(classElement.value); + this.scope.topLevelScope = wasTopLevel; + } + } + } + } } } -} - -module.exports = ElectronTargetPlugin; - - -/***/ }), -/***/ 22273: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Pre walking iterates the scope for variable declarations + preWalkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.preWalkStatement(statement); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // Block pre walking iterates the scope for block variable declarations + blockPreWalkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.blockPreWalkStatement(statement); + } + } + // Walking iterates the statements and expressions and processes them + walkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.walkStatement(statement); + } + } + preWalkStatement(statement) { + this.statementPath.push(statement); + if (this.hooks.preStatement.call(statement)) { + this.prevStatement = this.statementPath.pop(); + return; + } + switch (statement.type) { + case "BlockStatement": + this.preWalkBlockStatement(statement); + break; + case "DoWhileStatement": + this.preWalkDoWhileStatement(statement); + break; + case "ForInStatement": + this.preWalkForInStatement(statement); + break; + case "ForOfStatement": + this.preWalkForOfStatement(statement); + break; + case "ForStatement": + this.preWalkForStatement(statement); + break; + case "FunctionDeclaration": + this.preWalkFunctionDeclaration(statement); + break; + case "IfStatement": + this.preWalkIfStatement(statement); + break; + case "LabeledStatement": + this.preWalkLabeledStatement(statement); + break; + case "SwitchStatement": + this.preWalkSwitchStatement(statement); + break; + case "TryStatement": + this.preWalkTryStatement(statement); + break; + case "VariableDeclaration": + this.preWalkVariableDeclaration(statement); + break; + case "WhileStatement": + this.preWalkWhileStatement(statement); + break; + case "WithStatement": + this.preWalkWithStatement(statement); + break; + } + this.prevStatement = this.statementPath.pop(); + } -const WebpackError = __webpack_require__(53799); + blockPreWalkStatement(statement) { + this.statementPath.push(statement); + if (this.hooks.blockPreStatement.call(statement)) { + this.prevStatement = this.statementPath.pop(); + return; + } + switch (statement.type) { + case "ImportDeclaration": + this.blockPreWalkImportDeclaration(statement); + break; + case "ExportAllDeclaration": + this.blockPreWalkExportAllDeclaration(statement); + break; + case "ExportDefaultDeclaration": + this.blockPreWalkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.blockPreWalkExportNamedDeclaration(statement); + break; + case "VariableDeclaration": + this.blockPreWalkVariableDeclaration(statement); + break; + case "ClassDeclaration": + this.blockPreWalkClassDeclaration(statement); + break; + } + this.prevStatement = this.statementPath.pop(); + } -/** @typedef {import("../Module")} Module */ + walkStatement(statement) { + this.statementPath.push(statement); + if (this.hooks.statement.call(statement) !== undefined) { + this.prevStatement = this.statementPath.pop(); + return; + } + switch (statement.type) { + case "BlockStatement": + this.walkBlockStatement(statement); + break; + case "ClassDeclaration": + this.walkClassDeclaration(statement); + break; + case "DoWhileStatement": + this.walkDoWhileStatement(statement); + break; + case "ExportDefaultDeclaration": + this.walkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.walkExportNamedDeclaration(statement); + break; + case "ExpressionStatement": + this.walkExpressionStatement(statement); + break; + case "ForInStatement": + this.walkForInStatement(statement); + break; + case "ForOfStatement": + this.walkForOfStatement(statement); + break; + case "ForStatement": + this.walkForStatement(statement); + break; + case "FunctionDeclaration": + this.walkFunctionDeclaration(statement); + break; + case "IfStatement": + this.walkIfStatement(statement); + break; + case "LabeledStatement": + this.walkLabeledStatement(statement); + break; + case "ReturnStatement": + this.walkReturnStatement(statement); + break; + case "SwitchStatement": + this.walkSwitchStatement(statement); + break; + case "ThrowStatement": + this.walkThrowStatement(statement); + break; + case "TryStatement": + this.walkTryStatement(statement); + break; + case "VariableDeclaration": + this.walkVariableDeclaration(statement); + break; + case "WhileStatement": + this.walkWhileStatement(statement); + break; + case "WithStatement": + this.walkWithStatement(statement); + break; + } + this.prevStatement = this.statementPath.pop(); + } -class BuildCycleError extends WebpackError { /** - * Creates an instance of ModuleDependencyError. - * @param {Module} module the module starting the cycle + * Walks a statements that is nested within a parent statement + * and can potentially be a non-block statement. + * This enforces the nested statement to never be in ASI position. + * @param {StatementNode} statement the nested statement + * @returns {void} */ - constructor(module) { - super( - "There is a circular build dependency, which makes it impossible to create this module" - ); + walkNestedStatement(statement) { + this.prevStatement = undefined; + this.walkStatement(statement); + } - this.name = "BuildCycleError"; - this.module = module; + // Real Statements + preWalkBlockStatement(statement) { + this.preWalkStatements(statement.body); } -} -module.exports = BuildCycleError; + walkBlockStatement(statement) { + this.inBlockScope(() => { + const body = statement.body; + const prev = this.prevStatement; + this.blockPreWalkStatements(body); + this.prevStatement = prev; + this.walkStatements(body); + }); + } + walkExpressionStatement(statement) { + this.walkExpression(statement.expression); + } -/***/ }), + preWalkIfStatement(statement) { + this.preWalkStatement(statement.consequent); + if (statement.alternate) { + this.preWalkStatement(statement.alternate); + } + } -/***/ 5294: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + walkIfStatement(statement) { + const result = this.hooks.statementIf.call(statement); + if (result === undefined) { + this.walkExpression(statement.test); + this.walkNestedStatement(statement.consequent); + if (statement.alternate) { + this.walkNestedStatement(statement.alternate); + } + } else { + if (result) { + this.walkNestedStatement(statement.consequent); + } else if (statement.alternate) { + this.walkNestedStatement(statement.alternate); + } + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + preWalkLabeledStatement(statement) { + this.preWalkStatement(statement.body); + } + walkLabeledStatement(statement) { + const hook = this.hooks.label.get(statement.label.name); + if (hook !== undefined) { + const result = hook.call(statement); + if (result === true) return; + } + this.walkNestedStatement(statement.body); + } + preWalkWithStatement(statement) { + this.preWalkStatement(statement.body); + } -const RuntimeModule = __webpack_require__(16963); + walkWithStatement(statement) { + this.walkExpression(statement.object); + this.walkNestedStatement(statement.body); + } -class ExportWebpackRequireRuntimeModule extends RuntimeModule { - constructor() { - super("export webpack runtime", RuntimeModule.STAGE_ATTACH); + preWalkSwitchStatement(statement) { + this.preWalkSwitchCases(statement.cases); } - /** - * @returns {boolean} true, if the runtime module should get it's own scope - */ - shouldIsolate() { - return false; + walkSwitchStatement(statement) { + this.walkExpression(statement.discriminant); + this.walkSwitchCases(statement.cases); } - /** - * @returns {string} runtime code - */ - generate() { - return "export default __webpack_require__;"; + walkTerminatingStatement(statement) { + if (statement.argument) this.walkExpression(statement.argument); } -} -module.exports = ExportWebpackRequireRuntimeModule; + walkReturnStatement(statement) { + this.walkTerminatingStatement(statement); + } + walkThrowStatement(statement) { + this.walkTerminatingStatement(statement); + } -/***/ }), + preWalkTryStatement(statement) { + this.preWalkStatement(statement.block); + if (statement.handler) this.preWalkCatchClause(statement.handler); + if (statement.finializer) this.preWalkStatement(statement.finializer); + } -/***/ 68927: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + walkTryStatement(statement) { + if (this.scope.inTry) { + this.walkStatement(statement.block); + } else { + this.scope.inTry = true; + this.walkStatement(statement.block); + this.scope.inTry = false; + } + if (statement.handler) this.walkCatchClause(statement.handler); + if (statement.finalizer) this.walkStatement(statement.finalizer); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + preWalkWhileStatement(statement) { + this.preWalkStatement(statement.body); + } + walkWhileStatement(statement) { + this.walkExpression(statement.test); + this.walkNestedStatement(statement.body); + } + preWalkDoWhileStatement(statement) { + this.preWalkStatement(statement.body); + } -const { ConcatSource } = __webpack_require__(51255); -const { RuntimeGlobals } = __webpack_require__(91919); -const HotUpdateChunk = __webpack_require__(9597); -const Template = __webpack_require__(39722); -const { getAllChunks } = __webpack_require__(91145); -const { - getCompilationHooks, - getChunkFilenameTemplate -} = __webpack_require__(89464); -const { updateHashForEntryStartup } = __webpack_require__(98124); + walkDoWhileStatement(statement) { + this.walkNestedStatement(statement.body); + this.walkExpression(statement.test); + } -/** @typedef {import("../Compiler")} Compiler */ + preWalkForStatement(statement) { + if (statement.init) { + if (statement.init.type === "VariableDeclaration") { + this.preWalkStatement(statement.init); + } + } + this.preWalkStatement(statement.body); + } -class ModuleChunkFormatPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "ModuleChunkFormatPlugin", - compilation => { - compilation.hooks.additionalChunkRuntimeRequirements.tap( - "ModuleChunkFormatPlugin", - (chunk, set) => { - if (chunk.hasRuntime()) return; - if (compilation.chunkGraph.getNumberOfEntryModules(chunk) > 0) { - set.add(RuntimeGlobals.require); - set.add(RuntimeGlobals.startupEntrypoint); - set.add(RuntimeGlobals.externalInstallChunk); - } - } - ); - const hooks = getCompilationHooks(compilation); - hooks.renderChunk.tap( - "ModuleChunkFormatPlugin", - (modules, renderContext) => { - const { chunk, chunkGraph, runtimeTemplate } = renderContext; - const hotUpdateChunk = - chunk instanceof HotUpdateChunk ? chunk : null; - const source = new ConcatSource(); - if (hotUpdateChunk) { - throw new Error( - "HMR is not implemented for module chunk format yet" - ); - } else { - source.add(`export const id = ${JSON.stringify(chunk.id)};\n`); - source.add(`export const ids = ${JSON.stringify(chunk.ids)};\n`); - source.add(`export const modules = `); - source.add(modules); - source.add(`;\n`); - const runtimeModules = - chunkGraph.getChunkRuntimeModulesInOrder(chunk); - if (runtimeModules.length > 0) { - source.add("export const runtime =\n"); - source.add( - Template.renderChunkRuntimeModules( - runtimeModules, - renderContext - ) - ); - } - const entries = Array.from( - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) - ); - if (entries.length > 0) { - const runtimeChunk = entries[0][1].getRuntimeChunk(); - const currentOutputName = compilation - .getPath( - getChunkFilenameTemplate(chunk, compilation.outputOptions), - { - chunk, - contentHashType: "javascript" - } - ) - .split("/"); + walkForStatement(statement) { + this.inBlockScope(() => { + if (statement.init) { + if (statement.init.type === "VariableDeclaration") { + this.blockPreWalkVariableDeclaration(statement.init); + this.prevStatement = undefined; + this.walkStatement(statement.init); + } else { + this.walkExpression(statement.init); + } + } + if (statement.test) { + this.walkExpression(statement.test); + } + if (statement.update) { + this.walkExpression(statement.update); + } + const body = statement.body; + if (body.type === "BlockStatement") { + // no need to add additional scope + const prev = this.prevStatement; + this.blockPreWalkStatements(body.body); + this.prevStatement = prev; + this.walkStatements(body.body); + } else { + this.walkNestedStatement(body); + } + }); + } - // remove filename, we only need the directory - currentOutputName.pop(); + preWalkForInStatement(statement) { + if (statement.left.type === "VariableDeclaration") { + this.preWalkVariableDeclaration(statement.left); + } + this.preWalkStatement(statement.body); + } - const getRelativePath = chunk => { - const baseOutputName = currentOutputName.slice(); - const chunkOutputName = compilation - .getPath( - getChunkFilenameTemplate( - chunk, - compilation.outputOptions - ), - { - chunk: chunk, - contentHashType: "javascript" - } - ) - .split("/"); + walkForInStatement(statement) { + this.inBlockScope(() => { + if (statement.left.type === "VariableDeclaration") { + this.blockPreWalkVariableDeclaration(statement.left); + this.walkVariableDeclaration(statement.left); + } else { + this.walkPattern(statement.left); + } + this.walkExpression(statement.right); + const body = statement.body; + if (body.type === "BlockStatement") { + // no need to add additional scope + const prev = this.prevStatement; + this.blockPreWalkStatements(body.body); + this.prevStatement = prev; + this.walkStatements(body.body); + } else { + this.walkNestedStatement(body); + } + }); + } - // remove common parts - while ( - baseOutputName.length > 0 && - chunkOutputName.length > 0 && - baseOutputName[0] === chunkOutputName[0] - ) { - baseOutputName.shift(); - chunkOutputName.shift(); - } - // create final path - return ( - (baseOutputName.length > 0 - ? "../".repeat(baseOutputName.length) - : "./") + chunkOutputName.join("/") - ); - }; + preWalkForOfStatement(statement) { + if (statement.await && this.scope.topLevelScope === true) { + this.hooks.topLevelAwait.call(statement); + } + if (statement.left.type === "VariableDeclaration") { + this.preWalkVariableDeclaration(statement.left); + } + this.preWalkStatement(statement.body); + } - const entrySource = new ConcatSource(); - entrySource.add(source); - entrySource.add(";\n\n// load runtime\n"); - entrySource.add( - `import __webpack_require__ from ${JSON.stringify( - getRelativePath(runtimeChunk) - )};\n` - ); + walkForOfStatement(statement) { + this.inBlockScope(() => { + if (statement.left.type === "VariableDeclaration") { + this.blockPreWalkVariableDeclaration(statement.left); + this.walkVariableDeclaration(statement.left); + } else { + this.walkPattern(statement.left); + } + this.walkExpression(statement.right); + const body = statement.body; + if (body.type === "BlockStatement") { + // no need to add additional scope + const prev = this.prevStatement; + this.blockPreWalkStatements(body.body); + this.prevStatement = prev; + this.walkStatements(body.body); + } else { + this.walkNestedStatement(body); + } + }); + } - const startupSource = new ConcatSource(); - startupSource.add( - `var __webpack_exec__ = ${runtimeTemplate.returningFunction( - `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)`, - "moduleId" - )}\n` - ); + // Declarations + preWalkFunctionDeclaration(statement) { + if (statement.id) { + this.defineVariable(statement.id.name); + } + } - const loadedChunks = new Set(); - let index = 0; - for (let i = 0; i < entries.length; i++) { - const [module, entrypoint] = entries[i]; - const final = i + 1 === entries.length; - const moduleId = chunkGraph.getModuleId(module); - const chunks = getAllChunks( - entrypoint, - runtimeChunk, - undefined - ); - for (const chunk of chunks) { - if (loadedChunks.has(chunk)) continue; - loadedChunks.add(chunk); - startupSource.add( - `import * as __webpack_chunk_${index}__ from ${JSON.stringify( - getRelativePath(chunk) - )};\n` - ); - startupSource.add( - `${RuntimeGlobals.externalInstallChunk}(__webpack_chunk_${index}__);\n` - ); - index++; - } - startupSource.add( - `${ - final ? "var __webpack_exports__ = " : "" - }__webpack_exec__(${JSON.stringify(moduleId)});\n` - ); - } + walkFunctionDeclaration(statement) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + this.inFunctionScope(true, statement.params, () => { + for (const param of statement.params) { + this.walkPattern(param); + } + if (statement.body.type === "BlockStatement") { + this.detectMode(statement.body.body); + const prev = this.prevStatement; + this.preWalkStatement(statement.body); + this.prevStatement = prev; + this.walkStatement(statement.body); + } else { + this.walkExpression(statement.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } - entrySource.add( - hooks.renderStartup.call( - startupSource, - entries[entries.length - 1][0], - { - ...renderContext, - inlined: false - } - ) - ); - return entrySource; - } - } - return source; + blockPreWalkImportDeclaration(statement) { + const source = statement.source.value; + this.hooks.import.call(statement, source); + for (const specifier of statement.specifiers) { + const name = specifier.local.name; + switch (specifier.type) { + case "ImportDefaultSpecifier": + if ( + !this.hooks.importSpecifier.call(statement, source, "default", name) + ) { + this.defineVariable(name); } - ); - hooks.chunkHash.tap( - "ModuleChunkFormatPlugin", - (chunk, hash, { chunkGraph, runtimeTemplate }) => { - if (chunk.hasRuntime()) return; - hash.update("ModuleChunkFormatPlugin"); - hash.update("1"); - const entries = Array.from( - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) - ); - updateHashForEntryStartup(hash, chunkGraph, entries, chunk); + break; + case "ImportSpecifier": + if ( + !this.hooks.importSpecifier.call( + statement, + source, + specifier.imported.name, + name + ) + ) { + this.defineVariable(name); } - ); + break; + case "ImportNamespaceSpecifier": + if (!this.hooks.importSpecifier.call(statement, source, null, name)) { + this.defineVariable(name); + } + break; + default: + this.defineVariable(name); } - ); + } } -} - -module.exports = ModuleChunkFormatPlugin; - - -/***/ }), -/***/ 89831: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + enterDeclaration(declaration, onIdent) { + switch (declaration.type) { + case "VariableDeclaration": + for (const declarator of declaration.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + this.enterPattern(declarator.id, onIdent); + break; + } + } + } + break; + case "FunctionDeclaration": + this.enterPattern(declaration.id, onIdent); + break; + case "ClassDeclaration": + this.enterPattern(declaration.id, onIdent); + break; + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const ExportWebpackRequireRuntimeModule = __webpack_require__(5294); -const ModuleChunkLoadingRuntimeModule = __webpack_require__(64747); - -/** @typedef {import("../Compiler")} Compiler */ - -class ModuleChunkLoadingPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "ModuleChunkLoadingPlugin", - compilation => { - const globalChunkLoading = compilation.outputOptions.chunkLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const chunkLoading = - (options && options.chunkLoading) || globalChunkLoading; - return chunkLoading === "import"; - }; - const onceForChunkSet = new WeakSet(); - const handler = (chunk, set) => { - if (onceForChunkSet.has(chunk)) return; - onceForChunkSet.add(chunk); - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.hasOwnProperty); - compilation.addRuntimeModule( - chunk, - new ModuleChunkLoadingRuntimeModule(set) - ); - }; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("ModuleChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.baseURI) - .tap("ModuleChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.externalInstallChunk) - .tap("ModuleChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.onChunksLoaded) - .tap("ModuleChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.externalInstallChunk) - .tap("ModuleChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - compilation.addRuntimeModule( - chunk, - new ExportWebpackRequireRuntimeModule() - ); - }); - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("ModuleChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.getChunkScriptFilename); - }); + blockPreWalkExportNamedDeclaration(statement) { + let source; + if (statement.source) { + source = statement.source.value; + this.hooks.exportImport.call(statement, source); + } else { + this.hooks.export.call(statement); + } + if (statement.declaration) { + if ( + !this.hooks.exportDeclaration.call(statement, statement.declaration) + ) { + const prev = this.prevStatement; + this.preWalkStatement(statement.declaration); + this.prevStatement = prev; + this.blockPreWalkStatement(statement.declaration); + let index = 0; + this.enterDeclaration(statement.declaration, def => { + this.hooks.exportSpecifier.call(statement, def, def, index++); + }); } - ); - } -} - -module.exports = ModuleChunkLoadingPlugin; - - -/***/ }), - -/***/ 64747: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const { SyncWaterfallHook } = __webpack_require__(41242); -const Compilation = __webpack_require__(85720); -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); -const { - getChunkFilenameTemplate, - chunkHasJs -} = __webpack_require__(89464); -const { getInitialChunkIds } = __webpack_require__(98124); -const compileBooleanMatcher = __webpack_require__(29404); -const { getUndoPath } = __webpack_require__(82186); - -/** @typedef {import("../Chunk")} Chunk */ - -/** - * @typedef {Object} JsonpCompilationPluginHooks - * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload - * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch - */ - -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); - -class ModuleChunkLoadingRuntimeModule extends RuntimeModule { - /** - * @param {Compilation} compilation the compilation - * @returns {JsonpCompilationPluginHooks} 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 = { - linkPreload: new SyncWaterfallHook(["source", "chunk"]), - linkPrefetch: new SyncWaterfallHook(["source", "chunk"]) - }; - compilationHooksMap.set(compilation, hooks); + if (statement.specifiers) { + for ( + let specifierIndex = 0; + specifierIndex < statement.specifiers.length; + specifierIndex++ + ) { + const specifier = statement.specifiers[specifierIndex]; + switch (specifier.type) { + case "ExportSpecifier": { + const name = specifier.exported.name; + if (source) { + this.hooks.exportImportSpecifier.call( + statement, + source, + specifier.local.name, + name, + specifierIndex + ); + } else { + this.hooks.exportSpecifier.call( + statement, + specifier.local.name, + name, + specifierIndex + ); + } + break; + } + } + } } - return hooks; - } - - constructor(runtimeRequirements) { - super("import chunk loading", RuntimeModule.STAGE_ATTACH); - this._runtimeRequirements = runtimeRequirements; } - /** - * @returns {string} runtime code - */ - generate() { - const { compilation, chunk } = this; - const { - runtimeTemplate, - chunkGraph, - outputOptions: { importFunctionName, importMetaName } - } = compilation; - const fn = RuntimeGlobals.ensureChunkHandlers; - const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI); - const withExternalInstallChunk = this._runtimeRequirements.has( - RuntimeGlobals.externalInstallChunk - ); - const withLoading = this._runtimeRequirements.has( - RuntimeGlobals.ensureChunkHandlers - ); - const withOnChunkLoad = this._runtimeRequirements.has( - RuntimeGlobals.onChunksLoaded - ); - const withHmr = this._runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); - const hasJsMatcher = compileBooleanMatcher(conditionMap); - const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); - - const outputName = this.compilation.getPath( - getChunkFilenameTemplate(chunk, this.compilation.outputOptions), - { - chunk, - contentHashType: "javascript" - } - ); - const rootOutputDir = getUndoPath( - outputName, - this.compilation.outputOptions.path, - true - ); - - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_module` - : undefined; - - return Template.asString([ - withBaseURI - ? Template.asString([ - `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify( - rootOutputDir - )}, ${importMetaName}.url);` - ]) - : "// no baseURI", - "", - "// object to store loaded and loading chunks", - "// undefined = chunk not loaded, null = chunk preloaded/prefetched", - "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", - `var installedChunks = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{`, - Template.indent( - Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join( - ",\n" - ) - ), - "};", - "", - withLoading || withExternalInstallChunk - ? `var installChunk = ${runtimeTemplate.basicFunction("data", [ - runtimeTemplate.destructureObject( - ["ids", "modules", "runtime"], - "data" - ), - '// add "modules" to the modules object,', - '// then flag all "ids" as loaded and fire callback', - "var moduleId, chunkId, i = 0;", - "for(moduleId in modules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(modules, moduleId)) {`, - Template.indent( - `${RuntimeGlobals.moduleFactories}[moduleId] = modules[moduleId];` - ), - "}" - ]), - "}", - "if(runtime) runtime(__webpack_require__);", - "for(;i < ids.length; i++) {", - Template.indent([ - "chunkId = ids[i];", - `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`, - Template.indent("installedChunks[chunkId][0]();"), - "}", - "installedChunks[ids[i]] = 0;" - ]), - "}", - withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" - ])}` - : "// no install chunk", - "", - withLoading - ? Template.asString([ - `${fn}.j = ${runtimeTemplate.basicFunction( - "chunkId, promises", - hasJsMatcher !== false - ? Template.indent([ - "// import() chunk loading for javascript", - `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, - 'if(installedChunkData !== 0) { // 0 means "already installed".', - Template.indent([ - "", - '// a Promise means "currently loading".', - "if(installedChunkData) {", - Template.indent([ - "promises.push(installedChunkData[1]);" - ]), - "} else {", - Template.indent([ - hasJsMatcher === true - ? "if(true) { // all chunks have JS" - : `if(${hasJsMatcher("chunkId")}) {`, - Template.indent([ - "// setup Promise in chunk cache", - `var promise = ${importFunctionName}(${JSON.stringify( - rootOutputDir - )} + ${ - RuntimeGlobals.getChunkScriptFilename - }(chunkId)).then(installChunk, ${runtimeTemplate.basicFunction( - "e", - [ - "if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;", - "throw e;" - ] - )});`, - `var promise = Promise.race([promise, new Promise(${runtimeTemplate.expressionFunction( - `installedChunkData = installedChunks[chunkId] = [resolve]`, - "resolve" - )})])`, - `promises.push(installedChunkData[1] = promise);` - ]), - "} else installedChunks[chunkId] = 0;" - ]), - "}" - ]), - "}" - ]) - : Template.indent(["installedChunks[chunkId] = 0;"]) - )};` - ]) - : "// no chunk on demand loading", - "", - withExternalInstallChunk - ? Template.asString([ - `${RuntimeGlobals.externalInstallChunk} = installChunk;` - ]) - : "// no external install chunk", - "", - withOnChunkLoad - ? `${ - RuntimeGlobals.onChunksLoaded - }.j = ${runtimeTemplate.returningFunction( - "installedChunks[chunkId] === 0", - "chunkId" - )};` - : "// no on chunks loaded" - ]); + walkExportNamedDeclaration(statement) { + if (statement.declaration) { + this.walkStatement(statement.declaration); + } } -} - -module.exports = ModuleChunkLoadingRuntimeModule; - - -/***/ }), - -/***/ 16734: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Dependency").SourcePosition} SourcePosition */ - -/** - * @param {SourcePosition} pos position - * @returns {string} formatted position - */ -const formatPosition = pos => { - if (pos && typeof pos === "object") { - if ("line" in pos && "column" in pos) { - return `${pos.line}:${pos.column}`; - } else if ("line" in pos) { - return `${pos.line}:?`; + blockPreWalkExportDefaultDeclaration(statement) { + const prev = this.prevStatement; + this.preWalkStatement(statement.declaration); + this.prevStatement = prev; + this.blockPreWalkStatement(statement.declaration); + if ( + statement.declaration.id && + statement.declaration.type !== "FunctionExpression" && + statement.declaration.type !== "ClassExpression" + ) { + this.hooks.exportSpecifier.call( + statement, + statement.declaration.id.name, + "default", + undefined + ); } } - return ""; -}; -/** - * @param {DependencyLocation} loc location - * @returns {string} formatted location - */ -const formatLocation = loc => { - if (loc && typeof loc === "object") { - if ("start" in loc && loc.start && "end" in loc && loc.end) { + walkExportDefaultDeclaration(statement) { + this.hooks.export.call(statement); + if ( + statement.declaration.id && + statement.declaration.type !== "FunctionExpression" && + statement.declaration.type !== "ClassExpression" + ) { if ( - typeof loc.start === "object" && - typeof loc.start.line === "number" && - typeof loc.end === "object" && - typeof loc.end.line === "number" && - typeof loc.end.column === "number" && - loc.start.line === loc.end.line + !this.hooks.exportDeclaration.call(statement, statement.declaration) ) { - return `${formatPosition(loc.start)}-${loc.end.column}`; - } else if ( - typeof loc.start === "object" && - typeof loc.start.line === "number" && - typeof loc.start.column !== "number" && - typeof loc.end === "object" && - typeof loc.end.line === "number" && - typeof loc.end.column !== "number" + this.walkStatement(statement.declaration); + } + } else { + // Acorn parses `export default function() {}` as `FunctionDeclaration` and + // `export default class {}` as `ClassDeclaration`, both with `id = null`. + // These nodes must be treated as expressions. + if ( + statement.declaration.type === "FunctionDeclaration" || + statement.declaration.type === "ClassDeclaration" ) { - return `${loc.start.line}-${loc.end.line}`; + this.walkStatement(statement.declaration); } else { - return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; + this.walkExpression(statement.declaration); + } + if (!this.hooks.exportExpression.call(statement, statement.declaration)) { + this.hooks.exportSpecifier.call( + statement, + statement.declaration, + "default", + undefined + ); } - } - if ("start" in loc && loc.start) { - return formatPosition(loc.start); - } - if ("name" in loc && "index" in loc) { - return `${loc.name}[${loc.index}]`; - } - if ("name" in loc) { - return loc.name; } } - return ""; -}; - -module.exports = formatLocation; - - -/***/ }), - -/***/ 27899: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); -class HotModuleReplacementRuntimeModule extends RuntimeModule { - constructor() { - super("hot module replacement", RuntimeModule.STAGE_BASIC); - } - /** - * @returns {string} runtime code - */ - generate() { - return Template.getFunctionContent( - require('./HotModuleReplacement.runtime.js') - ) - .replace(/\$getFullHash\$/g, RuntimeGlobals.getFullHash) - .replace( - /\$interceptModuleExecution\$/g, - RuntimeGlobals.interceptModuleExecution - ) - .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) - .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) - .replace(/\$hmrDownloadManifest\$/g, RuntimeGlobals.hmrDownloadManifest) - .replace( - /\$hmrInvalidateModuleHandlers\$/g, - RuntimeGlobals.hmrInvalidateModuleHandlers - ) - .replace( - /\$hmrDownloadUpdateHandlers\$/g, - RuntimeGlobals.hmrDownloadUpdateHandlers - ); + blockPreWalkExportAllDeclaration(statement) { + const source = statement.source.value; + const name = statement.exported ? statement.exported.name : null; + this.hooks.exportImport.call(statement, source); + this.hooks.exportImportSpecifier.call(statement, source, null, name, 0); } -} -module.exports = HotModuleReplacementRuntimeModule; + preWalkVariableDeclaration(statement) { + if (statement.kind !== "var") return; + this._preWalkVariableDeclaration(statement, this.hooks.varDeclarationVar); + } + blockPreWalkVariableDeclaration(statement) { + if (statement.kind === "var") return; + const hookMap = + statement.kind === "const" + ? this.hooks.varDeclarationConst + : this.hooks.varDeclarationLet; + this._preWalkVariableDeclaration(statement, hookMap); + } -/***/ }), + _preWalkVariableDeclaration(statement, hookMap) { + for (const declarator of statement.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + if (!this.hooks.preDeclarator.call(declarator, statement)) { + this.enterPattern(declarator.id, (name, decl) => { + let hook = hookMap.get(name); + if (hook === undefined || !hook.call(decl)) { + hook = this.hooks.varDeclaration.get(name); + if (hook === undefined || !hook.call(decl)) { + this.defineVariable(name); + } + } + }); + } + break; + } + } + } + } -/***/ 79040: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + walkVariableDeclaration(statement) { + for (const declarator of statement.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + const renameIdentifier = + declarator.init && this.getRenameIdentifier(declarator.init); + if (renameIdentifier && declarator.id.type === "Identifier") { + const hook = this.hooks.canRename.get(renameIdentifier); + if (hook !== undefined && hook.call(declarator.init)) { + // renaming with "var a = b;" + const hook = this.hooks.rename.get(renameIdentifier); + if (hook === undefined || !hook.call(declarator.init)) { + this.setVariable(declarator.id.name, renameIdentifier); + } + break; + } + } + if (!this.hooks.declarator.call(declarator, statement)) { + this.walkPattern(declarator.id); + if (declarator.init) this.walkExpression(declarator.init); + } + break; + } + } + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + blockPreWalkClassDeclaration(statement) { + if (statement.id) { + this.defineVariable(statement.id.name); + } + } + walkClassDeclaration(statement) { + this.walkClass(statement); + } + preWalkSwitchCases(switchCases) { + for (let index = 0, len = switchCases.length; index < len; index++) { + const switchCase = switchCases[index]; + this.preWalkStatements(switchCase.consequent); + } + } -const { RawSource } = __webpack_require__(51255); -const AsyncDependenciesBlock = __webpack_require__(47736); -const Dependency = __webpack_require__(54912); -const Module = __webpack_require__(73208); -const ModuleFactory = __webpack_require__(51010); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const CommonJsRequireDependency = __webpack_require__(21264); -const { registerNotSerializable } = __webpack_require__(8282); + walkSwitchCases(switchCases) { + this.inBlockScope(() => { + const len = switchCases.length; -/** @typedef {import("../../declarations/WebpackOptions")} WebpackOptions */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../Module").BuildMeta} BuildMeta */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../dependencies/HarmonyImportDependency")} HarmonyImportDependency */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ + // we need to pre walk all statements first since we can have invalid code + // import A from "module"; + // switch(1) { + // case 1: + // console.log(A); // should fail at runtime + // case 2: + // const A = 1; + // } + for (let index = 0; index < len; index++) { + const switchCase = switchCases[index]; -/** - * @typedef {Object} BackendApi - * @property {function(Error=): void} dispose - * @property {function(Module): { client: string, data: string, active: boolean }} module - */ + if (switchCase.consequent.length > 0) { + const prev = this.prevStatement; + this.blockPreWalkStatements(switchCase.consequent); + this.prevStatement = prev; + } + } -const HMR_DEPENDENCY_TYPES = new Set([ - "import.meta.webpackHot.accept", - "import.meta.webpackHot.decline", - "module.hot.accept", - "module.hot.decline" -]); + for (let index = 0; index < len; index++) { + const switchCase = switchCases[index]; -/** - * @param {undefined|string|RegExp|Function} test test option - * @param {Module} module the module - * @returns {boolean} true, if the module should be selected - */ -const checkTest = (test, module) => { - if (test === undefined) return true; - if (typeof test === "function") { - return test(module); + if (switchCase.test) { + this.walkExpression(switchCase.test); + } + if (switchCase.consequent.length > 0) { + this.walkStatements(switchCase.consequent); + } + } + }); } - if (typeof test === "string") { - const name = module.nameForCondition(); - return name && name.startsWith(test); + + preWalkCatchClause(catchClause) { + this.preWalkStatement(catchClause.body); } - if (test instanceof RegExp) { - const name = module.nameForCondition(); - return name && test.test(name); + + walkCatchClause(catchClause) { + this.inBlockScope(() => { + // Error binding is optional in catch clause since ECMAScript 2019 + if (catchClause.param !== null) { + this.enterPattern(catchClause.param, ident => { + this.defineVariable(ident); + }); + this.walkPattern(catchClause.param); + } + const prev = this.prevStatement; + this.blockPreWalkStatement(catchClause.body); + this.prevStatement = prev; + this.walkStatement(catchClause.body); + }); } - return false; -}; -const TYPES = new Set(["javascript"]); + walkPattern(pattern) { + switch (pattern.type) { + case "ArrayPattern": + this.walkArrayPattern(pattern); + break; + case "AssignmentPattern": + this.walkAssignmentPattern(pattern); + break; + case "MemberExpression": + this.walkMemberExpression(pattern); + break; + case "ObjectPattern": + this.walkObjectPattern(pattern); + break; + case "RestElement": + this.walkRestElement(pattern); + break; + } + } -class LazyCompilationDependency extends Dependency { - constructor(proxyModule) { - super(); - this.proxyModule = proxyModule; + walkAssignmentPattern(pattern) { + this.walkExpression(pattern.right); + this.walkPattern(pattern.left); } - get category() { - return "esm"; + walkObjectPattern(pattern) { + for (let i = 0, len = pattern.properties.length; i < len; i++) { + const prop = pattern.properties[i]; + if (prop) { + if (prop.computed) this.walkExpression(prop.key); + if (prop.value) this.walkPattern(prop.value); + } + } } - get type() { - return "lazy import()"; + walkArrayPattern(pattern) { + for (let i = 0, len = pattern.elements.length; i < len; i++) { + const element = pattern.elements[i]; + if (element) this.walkPattern(element); + } } - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - return this.proxyModule.originalModule.identifier(); + walkRestElement(pattern) { + this.walkPattern(pattern.argument); } -} -registerNotSerializable(LazyCompilationDependency); + walkExpressions(expressions) { + for (const expression of expressions) { + if (expression) { + this.walkExpression(expression); + } + } + } -class LazyCompilationProxyModule extends Module { - constructor(context, originalModule, request, client, data, active) { - super("lazy-compilation-proxy", context, originalModule.layer); - this.originalModule = originalModule; - this.request = request; - this.client = client; - this.data = data; - this.active = active; + walkExpression(expression) { + switch (expression.type) { + case "ArrayExpression": + this.walkArrayExpression(expression); + break; + case "ArrowFunctionExpression": + this.walkArrowFunctionExpression(expression); + break; + case "AssignmentExpression": + this.walkAssignmentExpression(expression); + break; + case "AwaitExpression": + this.walkAwaitExpression(expression); + break; + case "BinaryExpression": + this.walkBinaryExpression(expression); + break; + case "CallExpression": + this.walkCallExpression(expression); + break; + case "ChainExpression": + this.walkChainExpression(expression); + break; + case "ClassExpression": + this.walkClassExpression(expression); + break; + case "ConditionalExpression": + this.walkConditionalExpression(expression); + break; + case "FunctionExpression": + this.walkFunctionExpression(expression); + break; + case "Identifier": + this.walkIdentifier(expression); + break; + case "ImportExpression": + this.walkImportExpression(expression); + break; + case "LogicalExpression": + this.walkLogicalExpression(expression); + break; + case "MetaProperty": + this.walkMetaProperty(expression); + break; + case "MemberExpression": + this.walkMemberExpression(expression); + break; + case "NewExpression": + this.walkNewExpression(expression); + break; + case "ObjectExpression": + this.walkObjectExpression(expression); + break; + case "SequenceExpression": + this.walkSequenceExpression(expression); + break; + case "SpreadElement": + this.walkSpreadElement(expression); + break; + case "TaggedTemplateExpression": + this.walkTaggedTemplateExpression(expression); + break; + case "TemplateLiteral": + this.walkTemplateLiteral(expression); + break; + case "ThisExpression": + this.walkThisExpression(expression); + break; + case "UnaryExpression": + this.walkUnaryExpression(expression); + break; + case "UpdateExpression": + this.walkUpdateExpression(expression); + break; + case "YieldExpression": + this.walkYieldExpression(expression); + break; + } } - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return `lazy-compilation-proxy|${this.originalModule.identifier()}`; + walkAwaitExpression(expression) { + if (this.scope.topLevelScope === true) + this.hooks.topLevelAwait.call(expression); + this.walkExpression(expression.argument); } - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - return `lazy-compilation-proxy ${this.originalModule.readableIdentifier( - requestShortener - )}`; + walkArrayExpression(expression) { + if (expression.elements) { + this.walkExpressions(expression.elements); + } } - /** - * 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 {LazyCompilationProxyModule} */ (module); - this.originalModule = m.originalModule; - this.request = m.request; - this.client = m.client; - this.data = m.data; - this.active = m.active; + walkSpreadElement(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } } - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - return `${this.originalModule.libIdent(options)}!lazy-compilation-proxy`; + walkObjectExpression(expression) { + for ( + let propIndex = 0, len = expression.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = expression.properties[propIndex]; + this.walkProperty(prop); + } } - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - callback(null, !this.buildInfo || this.buildInfo.active !== this.active); + walkProperty(prop) { + if (prop.type === "SpreadElement") { + this.walkExpression(prop.argument); + return; + } + if (prop.computed) { + this.walkExpression(prop.key); + } + if (prop.shorthand && prop.value && prop.value.type === "Identifier") { + this.scope.inShorthand = prop.value.name; + this.walkIdentifier(prop.value); + this.scope.inShorthand = false; + } else { + this.walkExpression(prop.value); + } } - /** - * @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.buildInfo = { - active: this.active - }; - /** @type {BuildMeta} */ - this.buildMeta = {}; - this.clearDependenciesAndBlocks(); - const dep = new CommonJsRequireDependency(this.client); - this.addDependency(dep); - if (this.active) { - const dep = new LazyCompilationDependency(this); - const block = new AsyncDependenciesBlock({}); - block.addDependency(dep); - this.addBlock(block); + walkFunctionExpression(expression) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + const scopeParams = expression.params; + + // Add function name in scope for recursive calls + if (expression.id) { + scopeParams.push(expression.id.name); } - callback(); + + this.inFunctionScope(true, scopeParams, () => { + for (const param of expression.params) { + this.walkPattern(param); + } + if (expression.body.type === "BlockStatement") { + this.detectMode(expression.body.body); + const prev = this.prevStatement; + this.preWalkStatement(expression.body); + this.prevStatement = prev; + this.walkStatement(expression.body); + } else { + this.walkExpression(expression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; } - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; + walkArrowFunctionExpression(expression) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = wasTopLevel ? "arrow" : false; + this.inFunctionScope(false, expression.params, () => { + for (const param of expression.params) { + this.walkPattern(param); + } + if (expression.body.type === "BlockStatement") { + this.detectMode(expression.body.body); + const prev = this.prevStatement; + this.preWalkStatement(expression.body); + this.prevStatement = prev; + this.walkStatement(expression.body); + } else { + this.walkExpression(expression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; } /** - * @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) + * @param {SequenceExpressionNode} expression the sequence */ - size(type) { - return 200; + walkSequenceExpression(expression) { + if (!expression.expressions) return; + // We treat sequence expressions like statements when they are one statement level + // This has some benefits for optimizations that only work on statement level + const currentStatement = this.statementPath[this.statementPath.length - 1]; + if ( + currentStatement === expression || + (currentStatement.type === "ExpressionStatement" && + currentStatement.expression === expression) + ) { + const old = this.statementPath.pop(); + for (const expr of expression.expressions) { + this.statementPath.push(expr); + this.walkExpression(expr); + this.statementPath.pop(); + } + this.statementPath.push(old); + } else { + this.walkExpressions(expression.expressions); + } } - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration({ runtimeTemplate, chunkGraph, moduleGraph }) { - const sources = new Map(); - const runtimeRequirements = new Set(); - runtimeRequirements.add(RuntimeGlobals.module); - const clientDep = /** @type {CommonJsRequireDependency} */ ( - this.dependencies[0] - ); - const clientModule = moduleGraph.getModule(clientDep); - const block = this.blocks[0]; - const client = Template.asString([ - `var client = ${runtimeTemplate.moduleExports({ - module: clientModule, - chunkGraph, - request: clientDep.userRequest, - runtimeRequirements - })}`, - `var data = ${JSON.stringify(this.data)};` - ]); - const keepActive = Template.asString([ - `var dispose = client.keepAlive({ data: data, active: ${JSON.stringify( - !!block - )}, module: module, onError: onError });` - ]); - let source; - if (block) { - const dep = block.dependencies[0]; - const module = moduleGraph.getModule(dep); - source = Template.asString([ - client, - `module.exports = ${runtimeTemplate.moduleNamespacePromise({ - chunkGraph, - block, - module, - request: this.request, - strict: false, // TODO this should be inherited from the original module - message: "import()", - runtimeRequirements - })};`, - "if (module.hot) {", - Template.indent([ - "module.hot.accept();", - `module.hot.accept(${JSON.stringify( - chunkGraph.getModuleId(module) - )}, function() { module.hot.invalidate(); });`, - "module.hot.dispose(function(data) { delete data.resolveSelf; dispose(data); });", - "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);" - ]), - "}", - "function onError() { /* ignore */ }", - keepActive - ]); - } else { - source = Template.asString([ - client, - "var resolveSelf, onError;", - `module.exports = new Promise(function(resolve, reject) { resolveSelf = resolve; onError = reject; });`, - "if (module.hot) {", - Template.indent([ - "module.hot.accept();", - "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);", - "module.hot.dispose(function(data) { data.resolveSelf = resolveSelf; dispose(data); });" - ]), - "}", - keepActive - ]); - } - sources.set("javascript", new RawSource(source)); - return { - sources, - runtimeRequirements - }; + walkUpdateExpression(expression) { + this.walkExpression(expression.argument); } - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - super.updateHash(hash, context); - hash.update(this.active ? "active" : ""); - hash.update(JSON.stringify(this.data)); + walkUnaryExpression(expression) { + if (expression.operator === "typeof") { + const result = this.callHooksForExpression( + this.hooks.typeof, + expression.argument, + expression + ); + if (result === true) return; + if (expression.argument.type === "ChainExpression") { + const result = this.callHooksForExpression( + this.hooks.typeof, + expression.argument.expression, + expression + ); + if (result === true) return; + } + } + this.walkExpression(expression.argument); } -} - -registerNotSerializable(LazyCompilationProxyModule); -class LazyCompilationDependencyFactory extends ModuleFactory { - constructor(factory) { - super(); - this._factory = factory; + walkLeftRightExpression(expression) { + this.walkExpression(expression.left); + this.walkExpression(expression.right); } - /** - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback - * @returns {void} - */ - create(data, callback) { - const dependency = /** @type {LazyCompilationDependency} */ ( - data.dependencies[0] - ); - callback(null, { - module: dependency.proxyModule.originalModule - }); + walkBinaryExpression(expression) { + this.walkLeftRightExpression(expression); } -} -class LazyCompilationPlugin { - /** - * @param {Object} options options - * @param {(function(Compiler, function(Error?, BackendApi?): void): void) | function(Compiler): Promise} options.backend the backend - * @param {boolean} options.entries true, when entries are lazy compiled - * @param {boolean} options.imports true, when import() modules are lazy compiled - * @param {RegExp | string | (function(Module): boolean)} options.test additional filter for lazy compiled entrypoint modules - */ - constructor({ backend, entries, imports, test }) { - this.backend = backend; - this.entries = entries; - this.imports = imports; - this.test = test; - } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - let backend; - compiler.hooks.beforeCompile.tapAsync( - "LazyCompilationPlugin", - (params, callback) => { - if (backend !== undefined) return callback(); - const promise = this.backend(compiler, (err, result) => { - if (err) return callback(err); - backend = result; - callback(); - }); - if (promise && promise.then) { - promise.then(b => { - backend = b; - callback(); - }, callback); - } + walkLogicalExpression(expression) { + const result = this.hooks.expressionLogicalOperator.call(expression); + if (result === undefined) { + this.walkLeftRightExpression(expression); + } else { + if (result) { + this.walkExpression(expression.right); } - ); - compiler.hooks.thisCompilation.tap( - "LazyCompilationPlugin", - (compilation, { normalModuleFactory }) => { - normalModuleFactory.hooks.module.tap( - "LazyCompilationPlugin", - (originalModule, createData, resolveData) => { - if ( - resolveData.dependencies.every(dep => - HMR_DEPENDENCY_TYPES.has(dep.type) - ) - ) { - // for HMR only resolving, try to determine if the HMR accept/decline refers to - // an import() or not - const hmrDep = resolveData.dependencies[0]; - const originModule = - compilation.moduleGraph.getParentModule(hmrDep); - const isReferringToDynamicImport = originModule.blocks.some( - block => - block.dependencies.some( - dep => - dep.type === "import()" && - /** @type {HarmonyImportDependency} */ (dep).request === - hmrDep.request - ) - ); - if (!isReferringToDynamicImport) return; - } else if ( - !resolveData.dependencies.every( - dep => - HMR_DEPENDENCY_TYPES.has(dep.type) || - (this.imports && - (dep.type === "import()" || - dep.type === "import() context element")) || - (this.entries && dep.type === "entry") - ) - ) - return; - if ( - /webpack[/\\]hot[/\\]|webpack-dev-server[/\\]client|webpack-hot-middleware[/\\]client/.test( - resolveData.request - ) || - !checkTest(this.test, originalModule) - ) - return; - const moduleInfo = backend.module(originalModule); - if (!moduleInfo) return; - const { client, data, active } = moduleInfo; + } + } - return new LazyCompilationProxyModule( - compiler.context, - originalModule, - resolveData.request, - client, - data, - active + walkAssignmentExpression(expression) { + if (expression.left.type === "Identifier") { + const renameIdentifier = this.getRenameIdentifier(expression.right); + if (renameIdentifier) { + if ( + this.callHooksForInfo( + this.hooks.canRename, + renameIdentifier, + expression.right + ) + ) { + // renaming "a = b;" + if ( + !this.callHooksForInfo( + this.hooks.rename, + renameIdentifier, + expression.right + ) + ) { + this.setVariable( + expression.left.name, + this.getVariableInfo(renameIdentifier) ); } - ); - compilation.dependencyFactories.set( - LazyCompilationDependency, - new LazyCompilationDependencyFactory() - ); + return; + } } - ); - compiler.hooks.shutdown.tapAsync("LazyCompilationPlugin", callback => { - backend.dispose(callback); - }); + this.walkExpression(expression.right); + this.enterPattern(expression.left, (name, decl) => { + if (!this.callHooksForName(this.hooks.assign, name, expression)) { + this.walkExpression(expression.left); + } + }); + return; + } + if (expression.left.type.endsWith("Pattern")) { + this.walkExpression(expression.right); + this.enterPattern(expression.left, (name, decl) => { + if (!this.callHooksForName(this.hooks.assign, name, expression)) { + this.defineVariable(name); + } + }); + this.walkPattern(expression.left); + } else if (expression.left.type === "MemberExpression") { + const exprName = this.getMemberExpressionInfo( + expression.left, + ALLOWED_MEMBER_TYPES_EXPRESSION + ); + if (exprName) { + if ( + this.callHooksForInfo( + this.hooks.assignMemberChain, + exprName.rootInfo, + expression, + exprName.getMembers() + ) + ) { + return; + } + } + this.walkExpression(expression.right); + this.walkExpression(expression.left); + } else { + this.walkExpression(expression.right); + this.walkExpression(expression.left); + } } -} - -module.exports = LazyCompilationPlugin; - - -/***/ }), - -/***/ 17781: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + walkConditionalExpression(expression) { + const result = this.hooks.expressionConditionalOperator.call(expression); + if (result === undefined) { + this.walkExpression(expression.test); + this.walkExpression(expression.consequent); + if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } else { + if (result) { + this.walkExpression(expression.consequent); + } else if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } + } + walkNewExpression(expression) { + const result = this.callHooksForExpression( + this.hooks.new, + expression.callee, + expression + ); + if (result === true) return; + this.walkExpression(expression.callee); + if (expression.arguments) { + this.walkExpressions(expression.arguments); + } + } -/** @typedef {import("http").ServerOptions} HttpServerOptions */ -/** @typedef {import("https").ServerOptions} HttpsServerOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LazyCompilationDefaultBackendOptions} LazyCompilationDefaultBackendOptions */ -/** @typedef {import("../Compiler")} Compiler */ + walkYieldExpression(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } + } -/** - * @callback BackendHandler - * @param {Compiler} compiler compiler - * @param {function((Error | null)=, any=): void} callback callback - * @returns {void} - */ + walkTemplateLiteral(expression) { + if (expression.expressions) { + this.walkExpressions(expression.expressions); + } + } -/** - * @param {Omit & { client: NonNullable}} options additional options for the backend - * @returns {BackendHandler} backend - */ -module.exports = options => (compiler, callback) => { - const logger = compiler.getInfrastructureLogger("LazyCompilationBackend"); - const activeModules = new Map(); - const prefix = "/lazy-compilation-using-"; + walkTaggedTemplateExpression(expression) { + if (expression.tag) { + this.walkExpression(expression.tag); + } + if (expression.quasi && expression.quasi.expressions) { + this.walkExpressions(expression.quasi.expressions); + } + } - const isHttps = - options.protocol === "https" || - (typeof options.server === "object" && - ("key" in options.server || "pfx" in options.server)); + walkClassExpression(expression) { + this.walkClass(expression); + } - const createServer = - typeof options.server === "function" - ? options.server - : (() => { - const http = isHttps ? __webpack_require__(95687) : __webpack_require__(13685); - return http.createServer.bind(http, options.server); - })(); - const listen = - typeof options.listen === "function" - ? options.listen - : server => { - let listen = options.listen; - if (typeof listen === "object" && !("port" in listen)) - listen = { ...listen, port: undefined }; - server.listen(listen); - }; + /** + * @param {ChainExpressionNode} expression expression + */ + walkChainExpression(expression) { + const result = this.hooks.optionalChaining.call(expression); - const protocol = options.protocol || (isHttps ? "https" : "http"); + if (result === undefined) { + if (expression.expression.type === "CallExpression") { + this.walkCallExpression(expression.expression); + } else { + this.walkMemberExpression(expression.expression); + } + } + } - const requestListener = (req, res) => { - const keys = req.url.slice(prefix.length).split("@"); - req.socket.on("close", () => { - setTimeout(() => { - for (const key of keys) { - const oldValue = activeModules.get(key) || 0; - activeModules.set(key, oldValue - 1); - if (oldValue === 1) { - logger.log( - `${key} is no longer in use. Next compilation will skip this module.` - ); + _walkIIFE(functionExpression, options, currentThis) { + const getVarInfo = argOrThis => { + const renameIdentifier = this.getRenameIdentifier(argOrThis); + if (renameIdentifier) { + if ( + this.callHooksForInfo( + this.hooks.canRename, + renameIdentifier, + argOrThis + ) + ) { + if ( + !this.callHooksForInfo( + this.hooks.rename, + renameIdentifier, + argOrThis + ) + ) { + return this.getVariableInfo(renameIdentifier); } } - }, 120000); - }); - req.socket.setNoDelay(true); - res.writeHead(200, { - "content-type": "text/event-stream", - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Methods": "*", - "Access-Control-Allow-Headers": "*" - }); - res.write("\n"); - let moduleActivated = false; - for (const key of keys) { - const oldValue = activeModules.get(key) || 0; - activeModules.set(key, oldValue + 1); - if (oldValue === 0) { - logger.log(`${key} is now in use and will be compiled.`); - moduleActivated = true; } - } - if (moduleActivated && compiler.watching) compiler.watching.invalidate(); - }; + this.walkExpression(argOrThis); + }; + const { params, type } = functionExpression; + const arrow = type === "ArrowFunctionExpression"; + const renameThis = currentThis ? getVarInfo(currentThis) : null; + const varInfoForArgs = options.map(getVarInfo); + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = wasTopLevel && arrow ? "arrow" : false; + const scopeParams = params.filter( + (identifier, idx) => !varInfoForArgs[idx] + ); - const server = /** @type {import("net").Server} */ (createServer()); - server.on("request", requestListener); + // Add function name in scope for recursive calls + if (functionExpression.id) { + scopeParams.push(functionExpression.id.name); + } - let isClosing = false; - /** @type {Set} */ - const sockets = new Set(); - server.on("connection", socket => { - sockets.add(socket); - socket.on("close", () => { - sockets.delete(socket); - }); - if (isClosing) socket.destroy(); - }); - server.on("clientError", e => { - if (e.message !== "Server is disposing") logger.warn(e); - }); - server.on("listening", err => { - if (err) return callback(err); - const addr = server.address(); - if (typeof addr === "string") throw new Error("addr must not be a string"); - const urlBase = - addr.address === "::" || addr.address === "0.0.0.0" - ? `${protocol}://localhost:${addr.port}` - : addr.family === "IPv6" - ? `${protocol}://[${addr.address}]:${addr.port}` - : `${protocol}://${addr.address}:${addr.port}`; - logger.log( - `Server-Sent-Events server for lazy compilation open at ${urlBase}.` - ); - callback(null, { - dispose(callback) { - isClosing = true; - // Removing the listener is a workaround for a memory leak in node.js - server.off("request", requestListener); - server.close(err => { - callback(err); - }); - for (const socket of sockets) { - socket.destroy(new Error("Server is disposing")); - } - }, - module(originalModule) { - const key = `${encodeURIComponent( - originalModule.identifier().replace(/\\/g, "/").replace(/@/g, "_") - ).replace(/%(2F|3A|24|26|2B|2C|3B|3D|3A)/g, decodeURIComponent)}`; - const active = activeModules.get(key) > 0; - return { - client: `${options.client}?${encodeURIComponent(urlBase + prefix)}`, - data: key, - active - }; + this.inFunctionScope(true, scopeParams, () => { + if (renameThis && !arrow) { + this.setVariable("this", renameThis); + } + for (let i = 0; i < varInfoForArgs.length; i++) { + const varInfo = varInfoForArgs[i]; + if (!varInfo) continue; + if (!params[i] || params[i].type !== "Identifier") continue; + this.setVariable(params[i].name, varInfo); + } + if (functionExpression.body.type === "BlockStatement") { + this.detectMode(functionExpression.body.body); + const prev = this.prevStatement; + this.preWalkStatement(functionExpression.body); + this.prevStatement = prev; + this.walkStatement(functionExpression.body); + } else { + this.walkExpression(functionExpression.body); } }); - }); - listen(server); -}; - - -/***/ }), - -/***/ 64618: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { find } = __webpack_require__(93347); -const { - compareModulesByPreOrderIndexOrIdentifier, - compareModulesByPostOrderIndexOrIdentifier -} = __webpack_require__(29579); + this.scope.topLevelScope = wasTopLevel; + } -/** @typedef {import("../Compiler")} Compiler */ + walkImportExpression(expression) { + let result = this.hooks.importCall.call(expression); + if (result === true) return; -class ChunkModuleIdRangePlugin { - constructor(options) { - this.options = options; + this.walkExpression(expression.source); } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => { - const moduleGraph = compilation.moduleGraph; - compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => { - const chunkGraph = compilation.chunkGraph; - const chunk = find( - compilation.chunks, - chunk => chunk.name === options.name + walkCallExpression(expression) { + const isSimpleFunction = fn => { + return fn.params.every(p => p.type === "Identifier"); + }; + if ( + expression.callee.type === "MemberExpression" && + expression.callee.object.type.endsWith("FunctionExpression") && + !expression.callee.computed && + (expression.callee.property.name === "call" || + expression.callee.property.name === "bind") && + expression.arguments.length > 0 && + isSimpleFunction(expression.callee.object) + ) { + // (function(…) { }.call/bind(?, …)) + this._walkIIFE( + expression.callee.object, + expression.arguments.slice(1), + expression.arguments[0] + ); + } else if ( + expression.callee.type.endsWith("FunctionExpression") && + isSimpleFunction(expression.callee) + ) { + // (function(…) { }(…)) + this._walkIIFE(expression.callee, expression.arguments, null); + } else { + if (expression.callee.type === "MemberExpression") { + const exprInfo = this.getMemberExpressionInfo( + expression.callee, + ALLOWED_MEMBER_TYPES_CALL_EXPRESSION ); - if (!chunk) { - throw new Error( - `ChunkModuleIdRangePlugin: Chunk with name '${options.name}"' was not found` + if (exprInfo && exprInfo.type === "call") { + const result = this.callHooksForInfo( + this.hooks.callMemberChainOfCallMemberChain, + exprInfo.rootInfo, + expression, + exprInfo.getCalleeMembers(), + exprInfo.call, + exprInfo.getMembers() ); + if (result === true) return; } + } + const callee = this.evaluateExpression(expression.callee); + if (callee.isIdentifier()) { + const result1 = this.callHooksForInfo( + this.hooks.callMemberChain, + callee.rootInfo, + expression, + callee.getMembers() + ); + if (result1 === true) return; + const result2 = this.callHooksForInfo( + this.hooks.call, + callee.identifier, + expression + ); + if (result2 === true) return; + } - let chunkModules; - if (options.order) { - let cmpFn; - switch (options.order) { - case "index": - case "preOrderIndex": - cmpFn = compareModulesByPreOrderIndexOrIdentifier(moduleGraph); - break; - case "index2": - case "postOrderIndex": - cmpFn = compareModulesByPostOrderIndexOrIdentifier(moduleGraph); - break; - default: - throw new Error( - "ChunkModuleIdRangePlugin: unexpected value of order" - ); - } - chunkModules = chunkGraph.getOrderedChunkModules(chunk, cmpFn); + if (expression.callee) { + if (expression.callee.type === "MemberExpression") { + // because of call context we need to walk the call context as expression + this.walkExpression(expression.callee.object); + if (expression.callee.computed === true) + this.walkExpression(expression.callee.property); } else { - chunkModules = Array.from(modules) - .filter(m => { - return chunkGraph.isModuleInChunk(m, chunk); - }) - .sort(compareModulesByPreOrderIndexOrIdentifier(moduleGraph)); + this.walkExpression(expression.callee); } + } + if (expression.arguments) this.walkExpressions(expression.arguments); + } + } - let currentId = options.start || 0; - for (let i = 0; i < chunkModules.length; i++) { - const m = chunkModules[i]; - if (m.needId && chunkGraph.getModuleId(m) === null) { - chunkGraph.setModuleId(m, currentId++); - } - if (options.end && currentId > options.end) break; + walkMemberExpression(expression) { + const exprInfo = this.getMemberExpressionInfo( + expression, + ALLOWED_MEMBER_TYPES_ALL + ); + if (exprInfo) { + switch (exprInfo.type) { + case "expression": { + const result1 = this.callHooksForInfo( + this.hooks.expression, + exprInfo.name, + expression + ); + if (result1 === true) return; + const members = exprInfo.getMembers(); + const result2 = this.callHooksForInfo( + this.hooks.expressionMemberChain, + exprInfo.rootInfo, + expression, + members + ); + if (result2 === true) return; + this.walkMemberExpressionWithExpressionName( + expression, + exprInfo.name, + exprInfo.rootInfo, + members.slice(), + () => + this.callHooksForInfo( + this.hooks.unhandledExpressionMemberChain, + exprInfo.rootInfo, + expression, + members + ) + ); + return; } - }); - }); + case "call": { + const result = this.callHooksForInfo( + this.hooks.memberChainOfCallMemberChain, + exprInfo.rootInfo, + expression, + exprInfo.getCalleeMembers(), + exprInfo.call, + exprInfo.getMembers() + ); + if (result === true) return; + // Fast skip over the member chain as we already called memberChainOfCallMemberChain + // and call computed property are literals anyway + this.walkExpression(exprInfo.call); + return; + } + } + } + this.walkExpression(expression.object); + if (expression.computed === true) this.walkExpression(expression.property); } -} -module.exports = ChunkModuleIdRangePlugin; - - -/***/ }), - -/***/ 8747: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ - + walkMemberExpressionWithExpressionName( + expression, + name, + rootInfo, + members, + onUnhandled + ) { + if (expression.object.type === "MemberExpression") { + // optimize the case where expression.object is a MemberExpression too. + // we can keep info here when calling walkMemberExpression directly + const property = + expression.property.name || `${expression.property.value}`; + name = name.slice(0, -property.length - 1); + members.pop(); + const result = this.callHooksForInfo( + this.hooks.expression, + name, + expression.object + ); + if (result === true) return; + this.walkMemberExpressionWithExpressionName( + expression.object, + name, + rootInfo, + members, + onUnhandled + ); + } else if (!onUnhandled || !onUnhandled()) { + this.walkExpression(expression.object); + } + if (expression.computed === true) this.walkExpression(expression.property); + } -const { compareChunksNatural } = __webpack_require__(29579); -const { - getFullChunkName, - getUsedChunkIds, - assignDeterministicIds -} = __webpack_require__(63290); - -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ + walkThisExpression(expression) { + this.callHooksForName(this.hooks.expression, "this", expression); + } -class DeterministicChunkIdsPlugin { - constructor(options) { - this.options = options || {}; + walkIdentifier(expression) { + this.callHooksForName(this.hooks.expression, expression.name, expression); } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {MetaPropertyNode} metaProperty meta property */ - apply(compiler) { - compiler.hooks.compilation.tap( - "DeterministicChunkIdsPlugin", - compilation => { - compilation.hooks.chunkIds.tap( - "DeterministicChunkIdsPlugin", - chunks => { - const chunkGraph = compilation.chunkGraph; - const context = this.options.context - ? this.options.context - : compiler.context; - const maxLength = this.options.maxLength || 3; - - const compareNatural = compareChunksNatural(chunkGraph); + walkMetaProperty(metaProperty) { + this.hooks.expression.for(getRootName(metaProperty)).call(metaProperty); + } - const usedIds = getUsedChunkIds(compilation); - assignDeterministicIds( - Array.from(chunks).filter(chunk => { - return chunk.id === null; - }), - chunk => - getFullChunkName(chunk, chunkGraph, context, compiler.root), - compareNatural, - (chunk, id) => { - const size = usedIds.size; - usedIds.add(`${id}`); - if (size === usedIds.size) return false; - chunk.id = id; - chunk.ids = [id]; - return true; - }, - [Math.pow(10, maxLength)], - 10, - usedIds.size - ); - } - ); - } + callHooksForExpression(hookMap, expr, ...args) { + return this.callHooksForExpressionWithFallback( + hookMap, + expr, + undefined, + undefined, + ...args ); } -} - -module.exports = DeterministicChunkIdsPlugin; - - -/***/ }), -/***/ 76692: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent -*/ - - - -const { - compareModulesByPreOrderIndexOrIdentifier -} = __webpack_require__(29579); -const { - getUsedModuleIdsAndModules, - getFullModuleName, - assignDeterministicIds -} = __webpack_require__(63290); - -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ - -class DeterministicModuleIdsPlugin { /** - * @param {Object} options options - * @param {string=} options.context context relative to which module identifiers are computed - * @param {function(Module): boolean=} options.test selector function for modules - * @param {number=} options.maxLength maximum id length in digits (used as starting point) - * @param {number=} options.salt hash salt for ids - * @param {boolean=} options.fixedLength do not increase the maxLength to find an optimal id space size - * @param {boolean=} options.failOnConflict throw an error when id conflicts occur (instead of rehashing) + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {MemberExpressionNode} expr expression info + * @param {function(string, string | ScopeInfo | VariableInfo, function(): string[]): any} fallback callback when variable in not handled by hooks + * @param {function(string): any} defined callback when variable is defined + * @param {AsArray} args args for the hook + * @returns {R} result of hook */ - constructor(options = {}) { - this.options = options; + callHooksForExpressionWithFallback( + hookMap, + expr, + fallback, + defined, + ...args + ) { + const exprName = this.getMemberExpressionInfo( + expr, + ALLOWED_MEMBER_TYPES_EXPRESSION + ); + if (exprName !== undefined) { + const members = exprName.getMembers(); + return this.callHooksForInfoWithFallback( + hookMap, + members.length === 0 ? exprName.rootInfo : exprName.name, + fallback && + (name => fallback(name, exprName.rootInfo, exprName.getMembers)), + defined && (() => defined(exprName.name)), + ...args + ); + } } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {string} name key in map + * @param {AsArray} args args for the hook + * @returns {R} result of hook */ - apply(compiler) { - compiler.hooks.compilation.tap( - "DeterministicModuleIdsPlugin", - compilation => { - compilation.hooks.moduleIds.tap("DeterministicModuleIdsPlugin", () => { - const chunkGraph = compilation.chunkGraph; - const context = this.options.context - ? this.options.context - : compiler.context; - const maxLength = this.options.maxLength || 3; - const failOnConflict = this.options.failOnConflict || false; - const fixedLength = this.options.fixedLength || false; - const salt = this.options.salt || 0; - let conflicts = 0; - - const [usedIds, modules] = getUsedModuleIdsAndModules( - compilation, - this.options.test - ); - assignDeterministicIds( - modules, - module => getFullModuleName(module, context, compiler.root), - failOnConflict - ? () => 0 - : compareModulesByPreOrderIndexOrIdentifier( - compilation.moduleGraph - ), - (module, id) => { - const size = usedIds.size; - usedIds.add(`${id}`); - if (size === usedIds.size) { - conflicts++; - return false; - } - chunkGraph.setModuleId(module, id); - return true; - }, - [Math.pow(10, maxLength)], - fixedLength ? 0 : 10, - usedIds.size, - salt - ); - if (failOnConflict && conflicts) - throw new Error( - `Assigning deterministic module ids has lead to ${conflicts} conflict${ - conflicts > 1 ? "s" : "" - }.\nIncrease the 'maxLength' to increase the id space and make conflicts less likely (recommended when there are many conflicts or application is expected to grow), or add an 'salt' number to try another hash starting value in the same id space (recommended when there is only a single conflict).` - ); - }); - } + callHooksForName(hookMap, name, ...args) { + return this.callHooksForNameWithFallback( + hookMap, + name, + undefined, + undefined, + ...args ); } -} - -module.exports = DeterministicModuleIdsPlugin; - - -/***/ }), - -/***/ 21825: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks that should be called + * @param {ExportedVariableInfo} info variable info + * @param {AsArray} args args for the hook + * @returns {R} result of hook + */ + callHooksForInfo(hookMap, info, ...args) { + return this.callHooksForInfoWithFallback( + hookMap, + info, + undefined, + undefined, + ...args + ); + } - - -const { - compareModulesByPreOrderIndexOrIdentifier -} = __webpack_require__(29579); -const createSchemaValidation = __webpack_require__(32540); -const createHash = __webpack_require__(49835); -const { - getUsedModuleIdsAndModules, - getFullModuleName -} = __webpack_require__(63290); - -/** @typedef {import("../../declarations/plugins/HashedModuleIdsPlugin").HashedModuleIdsPluginOptions} HashedModuleIdsPluginOptions */ - -const validate = createSchemaValidation( - __webpack_require__(52210), - () => __webpack_require__(59106), - { - name: "Hashed Module Ids Plugin", - baseDataPath: "options" + /** + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {ExportedVariableInfo} info variable info + * @param {function(string): any} fallback callback when variable in not handled by hooks + * @param {function(): any} defined callback when variable is defined + * @param {AsArray} args args for the hook + * @returns {R} result of hook + */ + callHooksForInfoWithFallback(hookMap, info, fallback, defined, ...args) { + let name; + if (typeof info === "string") { + name = info; + } else { + if (!(info instanceof VariableInfo)) { + if (defined !== undefined) { + return defined(); + } + return; + } + let tagInfo = info.tagInfo; + while (tagInfo !== undefined) { + const hook = hookMap.get(tagInfo.tag); + if (hook !== undefined) { + this.currentTagData = tagInfo.data; + const result = hook.call(...args); + this.currentTagData = undefined; + if (result !== undefined) return result; + } + tagInfo = tagInfo.next; + } + if (info.freeName === true) { + if (defined !== undefined) { + return defined(); + } + return; + } + name = info.freeName; + } + const hook = hookMap.get(name); + if (hook !== undefined) { + const result = hook.call(...args); + if (result !== undefined) return result; + } + if (fallback !== undefined) { + return fallback(name); + } } -); -class HashedModuleIdsPlugin { /** - * @param {HashedModuleIdsPluginOptions=} options options object + * @template T + * @template R + * @param {HookMap>} hookMap hooks the should be called + * @param {string} name key in map + * @param {function(string): any} fallback callback when variable in not handled by hooks + * @param {function(): any} defined callback when variable is defined + * @param {AsArray} args args for the hook + * @returns {R} result of hook */ - constructor(options = {}) { - validate(options); + callHooksForNameWithFallback(hookMap, name, fallback, defined, ...args) { + return this.callHooksForInfoWithFallback( + hookMap, + this.getVariableInfo(name), + fallback, + defined, + ...args + ); + } - /** @type {HashedModuleIdsPluginOptions} */ - this.options = { - context: null, - hashFunction: "md4", - hashDigest: "base64", - hashDigestLength: 4, - ...options + /** + * @deprecated + * @param {any} params scope params + * @param {function(): void} fn inner function + * @returns {void} + */ + inScope(params, fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: false, + inShorthand: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + definitions: oldScope.definitions.createChild() }; - } - apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap("HashedModuleIdsPlugin", compilation => { - compilation.hooks.moduleIds.tap("HashedModuleIdsPlugin", () => { - const chunkGraph = compilation.chunkGraph; - const context = this.options.context - ? this.options.context - : compiler.context; + this.undefineVariable("this"); - const [usedIds, modules] = getUsedModuleIdsAndModules(compilation); - const modulesInNaturalOrder = modules.sort( - compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph) - ); - for (const module of modulesInNaturalOrder) { - const ident = getFullModuleName(module, context, compiler.root); - const hash = createHash(options.hashFunction); - hash.update(ident || ""); - const hashId = /** @type {string} */ ( - hash.digest(options.hashDigest) - ); - let len = options.hashDigestLength; - while (usedIds.has(hashId.substr(0, len))) len++; - const moduleId = hashId.substr(0, len); - chunkGraph.setModuleId(module, moduleId); - usedIds.add(moduleId); - } - }); + this.enterPatterns(params, (ident, pattern) => { + this.defineVariable(ident); }); - } -} - -module.exports = HashedModuleIdsPlugin; - - -/***/ }), - -/***/ 63290: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const createHash = __webpack_require__(49835); -const { makePathsRelative } = __webpack_require__(82186); -const numberHash = __webpack_require__(70002); - -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module")} Module */ -/** @typedef {typeof import("../util/Hash")} Hash */ - -/** - * @param {string} str string to hash - * @param {number} len max length of the hash - * @param {string | Hash} hashFunction hash function to use - * @returns {string} hash - */ -const getHash = (str, len, hashFunction) => { - const hash = createHash(hashFunction); - hash.update(str); - const digest = /** @type {string} */ (hash.digest("hex")); - return digest.substr(0, len); -}; + fn(); -/** - * @param {string} str the string - * @returns {string} string prefixed by an underscore if it is a number - */ -const avoidNumber = str => { - // max length of a number is 21 chars, bigger numbers a written as "...e+xx" - if (str.length > 21) return str; - const firstChar = str.charCodeAt(0); - // skip everything that doesn't look like a number - // charCodes: "-": 45, "1": 49, "9": 57 - if (firstChar < 49) { - if (firstChar !== 45) return str; - } else if (firstChar > 57) { - return str; - } - if (str === +str + "") { - return `_${str}`; + this.scope = oldScope; } - return str; -}; - -/** - * @param {string} request the request - * @returns {string} id representation - */ -const requestToId = request => { - return request - .replace(/^(\.\.?\/)+/, "") - .replace(/(^[.-]|[^a-zA-Z0-9_-])+/g, "_"); -}; -exports.requestToId = requestToId; -/** - * @param {string} string the string - * @param {string} delimiter separator for string and hash - * @param {string | Hash} hashFunction hash function to use - * @returns {string} string with limited max length to 100 chars - */ -const shortenLongString = (string, delimiter, hashFunction) => { - if (string.length < 100) return string; - return ( - string.slice(0, 100 - 6 - delimiter.length) + - delimiter + - getHash(string, 6, hashFunction) - ); -}; + inFunctionScope(hasThis, params, fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: false, + inShorthand: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + definitions: oldScope.definitions.createChild() + }; -/** - * @param {Module} module the module - * @param {string} context context directory - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} short module name - */ -const getShortModuleName = (module, context, associatedObjectForCache) => { - const libIdent = module.libIdent({ context, associatedObjectForCache }); - if (libIdent) return avoidNumber(libIdent); - const nameForCondition = module.nameForCondition(); - if (nameForCondition) - return avoidNumber( - makePathsRelative(context, nameForCondition, associatedObjectForCache) - ); - return ""; -}; -exports.getShortModuleName = getShortModuleName; + if (hasThis) { + this.undefineVariable("this"); + } -/** - * @param {string} shortName the short name - * @param {Module} module the module - * @param {string} context context directory - * @param {string | Hash} hashFunction hash function to use - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} long module name - */ -const getLongModuleName = ( - shortName, - module, - context, - hashFunction, - associatedObjectForCache -) => { - const fullName = getFullModuleName(module, context, associatedObjectForCache); - return `${shortName}?${getHash(fullName, 4, hashFunction)}`; -}; -exports.getLongModuleName = getLongModuleName; + this.enterPatterns(params, (ident, pattern) => { + this.defineVariable(ident); + }); -/** - * @param {Module} module the module - * @param {string} context context directory - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} full module name - */ -const getFullModuleName = (module, context, associatedObjectForCache) => { - return makePathsRelative( - context, - module.identifier(), - associatedObjectForCache - ); -}; -exports.getFullModuleName = getFullModuleName; + fn(); -/** - * @param {Chunk} chunk the chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {string} context context directory - * @param {string} delimiter delimiter for names - * @param {string | Hash} hashFunction hash function to use - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} short chunk name - */ -const getShortChunkName = ( - chunk, - chunkGraph, - context, - delimiter, - hashFunction, - associatedObjectForCache -) => { - const modules = chunkGraph.getChunkRootModules(chunk); - const shortModuleNames = modules.map(m => - requestToId(getShortModuleName(m, context, associatedObjectForCache)) - ); - chunk.idNameHints.sort(); - const chunkName = Array.from(chunk.idNameHints) - .concat(shortModuleNames) - .filter(Boolean) - .join(delimiter); - return shortenLongString(chunkName, delimiter, hashFunction); -}; -exports.getShortChunkName = getShortChunkName; + this.scope = oldScope; + } -/** - * @param {Chunk} chunk the chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {string} context context directory - * @param {string} delimiter delimiter for names - * @param {string | Hash} hashFunction hash function to use - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} short chunk name - */ -const getLongChunkName = ( - chunk, - chunkGraph, - context, - delimiter, - hashFunction, - associatedObjectForCache -) => { - const modules = chunkGraph.getChunkRootModules(chunk); - const shortModuleNames = modules.map(m => - requestToId(getShortModuleName(m, context, associatedObjectForCache)) - ); - const longModuleNames = modules.map(m => - requestToId( - getLongModuleName("", m, context, hashFunction, associatedObjectForCache) - ) - ); - chunk.idNameHints.sort(); - const chunkName = Array.from(chunk.idNameHints) - .concat(shortModuleNames, longModuleNames) - .filter(Boolean) - .join(delimiter); - return shortenLongString(chunkName, delimiter, hashFunction); -}; -exports.getLongChunkName = getLongChunkName; + inBlockScope(fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: oldScope.inTry, + inShorthand: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + definitions: oldScope.definitions.createChild() + }; -/** - * @param {Chunk} chunk the chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {string} context context directory - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} full chunk name - */ -const getFullChunkName = ( - chunk, - chunkGraph, - context, - associatedObjectForCache -) => { - if (chunk.name) return chunk.name; - const modules = chunkGraph.getChunkRootModules(chunk); - const fullModuleNames = modules.map(m => - makePathsRelative(context, m.identifier(), associatedObjectForCache) - ); - return fullModuleNames.join(); -}; -exports.getFullChunkName = getFullChunkName; + fn(); -/** - * @template K - * @template V - * @param {Map} map a map from key to values - * @param {K} key key - * @param {V} value value - * @returns {void} - */ -const addToMapOfItems = (map, key, value) => { - let array = map.get(key); - if (array === undefined) { - array = []; - map.set(key, array); + this.scope = oldScope; } - array.push(value); -}; - -/** - * @param {Compilation} compilation the compilation - * @param {function(Module): boolean=} filter filter modules - * @returns {[Set, Module[]]} used module ids as strings and modules without id matching the filter - */ -const getUsedModuleIdsAndModules = (compilation, filter) => { - const chunkGraph = compilation.chunkGraph; - const modules = []; - - /** @type {Set} */ - const usedIds = new Set(); - if (compilation.usedModuleIds) { - for (const id of compilation.usedModuleIds) { - usedIds.add(id + ""); + detectMode(statements) { + const isLiteral = + statements.length >= 1 && + statements[0].type === "ExpressionStatement" && + statements[0].expression.type === "Literal"; + if (isLiteral && statements[0].expression.value === "use strict") { + this.scope.isStrict = true; + } + if (isLiteral && statements[0].expression.value === "use asm") { + this.scope.isAsmJs = true; } } - for (const module of compilation.modules) { - if (!module.needId) continue; - const moduleId = chunkGraph.getModuleId(module); - if (moduleId !== null) { - usedIds.add(moduleId + ""); - } else { - if ( - (!filter || filter(module)) && - chunkGraph.getNumberOfModuleChunks(module) !== 0 - ) { - modules.push(module); + enterPatterns(patterns, onIdent) { + for (const pattern of patterns) { + if (typeof pattern !== "string") { + this.enterPattern(pattern, onIdent); + } else if (pattern) { + onIdent(pattern); } } } - return [usedIds, modules]; -}; -exports.getUsedModuleIdsAndModules = getUsedModuleIdsAndModules; - -/** - * @param {Compilation} compilation the compilation - * @returns {Set} used chunk ids as strings - */ -const getUsedChunkIds = compilation => { - /** @type {Set} */ - const usedIds = new Set(); - if (compilation.usedChunkIds) { - for (const id of compilation.usedChunkIds) { - usedIds.add(id + ""); + enterPattern(pattern, onIdent) { + if (!pattern) return; + switch (pattern.type) { + case "ArrayPattern": + this.enterArrayPattern(pattern, onIdent); + break; + case "AssignmentPattern": + this.enterAssignmentPattern(pattern, onIdent); + break; + case "Identifier": + this.enterIdentifier(pattern, onIdent); + break; + case "ObjectPattern": + this.enterObjectPattern(pattern, onIdent); + break; + case "RestElement": + this.enterRestElement(pattern, onIdent); + break; + case "Property": + if (pattern.shorthand && pattern.value.type === "Identifier") { + this.scope.inShorthand = pattern.value.name; + this.enterIdentifier(pattern.value, onIdent); + this.scope.inShorthand = false; + } else { + this.enterPattern(pattern.value, onIdent); + } + break; } } - for (const chunk of compilation.chunks) { - const chunkId = chunk.id; - if (chunkId !== null) { - usedIds.add(chunkId + ""); + enterIdentifier(pattern, onIdent) { + if (!this.callHooksForName(this.hooks.pattern, pattern.name, pattern)) { + onIdent(pattern.name, pattern); } } - return usedIds; -}; -exports.getUsedChunkIds = getUsedChunkIds; + enterObjectPattern(pattern, onIdent) { + for ( + let propIndex = 0, len = pattern.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = pattern.properties[propIndex]; + this.enterPattern(prop, onIdent); + } + } -/** - * @template T - * @param {Iterable} items list of items to be named - * @param {function(T): string} getShortName get a short name for an item - * @param {function(T, string): string} getLongName get a long name for an item - * @param {function(T, T): -1|0|1} comparator order of items - * @param {Set} usedIds already used ids, will not be assigned - * @param {function(T, string): void} assignName assign a name to an item - * @returns {T[]} list of items without a name - */ -const assignNames = ( - items, - getShortName, - getLongName, - comparator, - usedIds, - assignName -) => { - /** @type {Map} */ - const nameToItems = new Map(); + enterArrayPattern(pattern, onIdent) { + for ( + let elementIndex = 0, len = pattern.elements.length; + elementIndex < len; + elementIndex++ + ) { + const element = pattern.elements[elementIndex]; + this.enterPattern(element, onIdent); + } + } - for (const item of items) { - const name = getShortName(item); - addToMapOfItems(nameToItems, name, item); + enterRestElement(pattern, onIdent) { + this.enterPattern(pattern.argument, onIdent); } - /** @type {Map} */ - const nameToItems2 = new Map(); + enterAssignmentPattern(pattern, onIdent) { + this.enterPattern(pattern.left, onIdent); + } - for (const [name, items] of nameToItems) { - if (items.length > 1 || !name) { - for (const item of items) { - const longName = getLongName(item, name); - addToMapOfItems(nameToItems2, longName, item); + /** + * @param {ExpressionNode} expression expression node + * @returns {BasicEvaluatedExpression | undefined} evaluation result + */ + evaluateExpression(expression) { + try { + const hook = this.hooks.evaluate.get(expression.type); + if (hook !== undefined) { + const result = hook.call(expression); + if (result !== undefined) { + if (result) { + result.setExpression(expression); + } + return result; + } } - } else { - addToMapOfItems(nameToItems2, name, items[0]); + } catch (e) { + console.warn(e); + // ignore error } + return new BasicEvaluatedExpression() + .setRange(expression.range) + .setExpression(expression); } - /** @type {T[]} */ - const unnamedItems = []; + parseString(expression) { + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + return ( + this.parseString(expression.left) + + this.parseString(expression.right) + ); + } + break; + case "Literal": + return expression.value + ""; + } + throw new Error( + expression.type + " is not supported as parameter for require" + ); + } - for (const [name, items] of nameToItems2) { - if (!name) { - for (const item of items) { - unnamedItems.push(item); - } - } else if (items.length === 1 && !usedIds.has(name)) { - assignName(items[0], name); - usedIds.add(name); - } else { - items.sort(comparator); - let i = 0; - for (const item of items) { - while (nameToItems2.has(name + i) && usedIds.has(name + i)) i++; - assignName(item, name + i); - usedIds.add(name + i); - i++; + parseCalculatedString(expression) { + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + const left = this.parseCalculatedString(expression.left); + const right = this.parseCalculatedString(expression.right); + if (left.code) { + return { + range: left.range, + value: left.value, + code: true, + conditional: false + }; + } else if (right.code) { + return { + range: [ + left.range[0], + right.range ? right.range[1] : left.range[1] + ], + value: left.value + right.value, + code: true, + conditional: false + }; + } else { + return { + range: [left.range[0], right.range[1]], + value: left.value + right.value, + code: false, + conditional: false + }; + } + } + break; + case "ConditionalExpression": { + const consequent = this.parseCalculatedString(expression.consequent); + const alternate = this.parseCalculatedString(expression.alternate); + const items = []; + if (consequent.conditional) { + items.push(...consequent.conditional); + } else if (!consequent.code) { + items.push(consequent); + } else { + break; + } + if (alternate.conditional) { + items.push(...alternate.conditional); + } else if (!alternate.code) { + items.push(alternate); + } else { + break; + } + return { + range: undefined, + value: "", + code: true, + conditional: items + }; } + case "Literal": + return { + range: expression.range, + value: expression.value + "", + code: false, + conditional: false + }; } + return { + range: undefined, + value: "", + code: true, + conditional: false + }; } - unnamedItems.sort(comparator); - return unnamedItems; -}; -exports.assignNames = assignNames; - -/** - * @template T - * @param {T[]} items list of items to be named - * @param {function(T): string} getName get a name for an item - * @param {function(T, T): -1|0|1} comparator order of items - * @param {function(T, number): boolean} assignId assign an id to an item - * @param {number[]} ranges usable ranges for ids - * @param {number} expandFactor factor to create more ranges - * @param {number} extraSpace extra space to allocate, i. e. when some ids are already used - * @param {number} salt salting number to initialize hashing - * @returns {void} - */ -const assignDeterministicIds = ( - items, - getName, - comparator, - assignId, - ranges = [10], - expandFactor = 10, - extraSpace = 0, - salt = 0 -) => { - items.sort(comparator); - - // max 5% fill rate - const optimalRange = Math.min( - Math.ceil(items.length * 20) + extraSpace, - Number.MAX_SAFE_INTEGER - ); - - let i = 0; - let range = ranges[i]; - while (range < optimalRange) { - i++; - if (i < ranges.length) { - range = Math.min(ranges[i], Number.MAX_SAFE_INTEGER); - } else if (expandFactor) { - range = Math.min(range * expandFactor, Number.MAX_SAFE_INTEGER); + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + let ast; + let comments; + const semicolons = new Set(); + if (source === null) { + throw new Error("source must not be null"); + } + if (Buffer.isBuffer(source)) { + source = source.toString("utf-8"); + } + if (typeof source === "object") { + ast = /** @type {ProgramNode} */ (source); + comments = source.comments; } else { - break; + comments = []; + ast = JavascriptParser._parse(source, { + sourceType: this.sourceType, + onComment: comments, + onInsertedSemicolon: pos => semicolons.add(pos) + }); } - } - - for (const item of items) { - const ident = getName(item); - let id; - let i = salt; - do { - id = numberHash(ident + i++, range); - } while (!assignId(item, id)); - } -}; -exports.assignDeterministicIds = assignDeterministicIds; - -/** - * @param {Set} usedIds used ids - * @param {Iterable} modules the modules - * @param {Compilation} compilation the compilation - * @returns {void} - */ -const assignAscendingModuleIds = (usedIds, modules, compilation) => { - const chunkGraph = compilation.chunkGraph; - let nextId = 0; - let assignId; - if (usedIds.size > 0) { - assignId = module => { - if (chunkGraph.getModuleId(module) === null) { - while (usedIds.has(nextId + "")) nextId++; - chunkGraph.setModuleId(module, nextId++); - } - }; - } else { - assignId = module => { - if (chunkGraph.getModuleId(module) === null) { - chunkGraph.setModuleId(module, nextId++); - } + const oldScope = this.scope; + const oldState = this.state; + const oldComments = this.comments; + const oldSemicolons = this.semicolons; + const oldStatementPath = this.statementPath; + const oldPrevStatement = this.prevStatement; + this.scope = { + topLevelScope: true, + inTry: false, + inShorthand: false, + isStrict: false, + isAsmJs: false, + definitions: new StackedMap() }; + /** @type {ParserState} */ + this.state = state; + this.comments = comments; + this.semicolons = semicolons; + this.statementPath = []; + this.prevStatement = undefined; + if (this.hooks.program.call(ast, comments) === undefined) { + this.detectMode(ast.body); + this.preWalkStatements(ast.body); + this.prevStatement = undefined; + this.blockPreWalkStatements(ast.body); + this.prevStatement = undefined; + this.walkStatements(ast.body); + } + this.hooks.finish.call(ast, comments); + this.scope = oldScope; + /** @type {ParserState} */ + this.state = oldState; + this.comments = oldComments; + this.semicolons = oldSemicolons; + this.statementPath = oldStatementPath; + this.prevStatement = oldPrevStatement; + return state; } - for (const module of modules) { - assignId(module); - } -}; -exports.assignAscendingModuleIds = assignAscendingModuleIds; - -/** - * @param {Iterable} chunks the chunks - * @param {Compilation} compilation the compilation - * @returns {void} - */ -const assignAscendingChunkIds = (chunks, compilation) => { - const usedIds = getUsedChunkIds(compilation); - let nextId = 0; - if (usedIds.size > 0) { - for (const chunk of chunks) { - if (chunk.id === null) { - while (usedIds.has(nextId + "")) nextId++; - chunk.id = nextId; - chunk.ids = [nextId]; - nextId++; - } - } - } else { - for (const chunk of chunks) { - if (chunk.id === null) { - chunk.id = nextId; - chunk.ids = [nextId]; - nextId++; - } + evaluate(source) { + const ast = JavascriptParser._parse("(" + source + ")", { + sourceType: this.sourceType, + locations: false + }); + if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") { + throw new Error("evaluate: Source is not a expression"); } + return this.evaluateExpression(ast.body[0].expression); } -}; -exports.assignAscendingChunkIds = assignAscendingChunkIds; + /** + * @param {ExpressionNode | DeclarationNode | PrivateIdentifierNode | null | undefined} expr an expression + * @param {number} commentsStartPos source position from which annotation comments are checked + * @returns {boolean} true, when the expression is pure + */ + isPure(expr, commentsStartPos) { + if (!expr) return true; + const result = this.hooks.isPure + .for(expr.type) + .call(expr, commentsStartPos); + if (typeof result === "boolean") return result; + switch (expr.type) { + case "ClassDeclaration": + case "ClassExpression": { + if (expr.body.type !== "ClassBody") return false; + if (expr.superClass && !this.isPure(expr.superClass, expr.range[0])) { + return false; + } + const items = + /** @type {(MethodDefinitionNode | PropertyDefinitionNode)[]} */ ( + expr.body.body + ); + return items.every( + item => + (!item.computed || + !item.key || + this.isPure(item.key, item.range[0])) && + (!item.static || + !item.value || + this.isPure( + item.value, + item.key ? item.key.range[1] : item.range[0] + )) + ); + } -/***/ }), + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + case "Literal": + case "PrivateIdentifier": + return true; -/***/ 6454: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + case "VariableDeclaration": + return expr.declarations.every(decl => + this.isPure(decl.init, decl.range[0]) + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + case "ConditionalExpression": + return ( + this.isPure(expr.test, commentsStartPos) && + this.isPure(expr.consequent, expr.test.range[1]) && + this.isPure(expr.alternate, expr.consequent.range[1]) + ); + case "SequenceExpression": + return expr.expressions.every(expr => { + const pureFlag = this.isPure(expr, commentsStartPos); + commentsStartPos = expr.range[1]; + return pureFlag; + }); + case "CallExpression": { + const pureFlag = + expr.range[0] - commentsStartPos > 12 && + this.getComments([commentsStartPos, expr.range[0]]).some( + comment => + comment.type === "Block" && + /^\s*(#|@)__PURE__\s*$/.test(comment.value) + ); + if (!pureFlag) return false; + commentsStartPos = expr.callee.range[1]; + return expr.arguments.every(arg => { + if (arg.type === "SpreadElement") return false; + const pureFlag = this.isPure(arg, commentsStartPos); + commentsStartPos = arg.range[1]; + return pureFlag; + }); + } + } + const evaluated = this.evaluateExpression(expr); + return !evaluated.couldHaveSideEffects(); + } -const { compareChunksNatural } = __webpack_require__(29579); -const { - getShortChunkName, - getLongChunkName, - assignNames, - getUsedChunkIds, - assignAscendingChunkIds -} = __webpack_require__(63290); + getComments(range) { + const [rangeStart, rangeEnd] = range; + const compare = (comment, needle) => comment.range[0] - needle; + let idx = binarySearchBounds.ge(this.comments, rangeStart, compare); + let commentsInRange = []; + while (this.comments[idx] && this.comments[idx].range[1] <= rangeEnd) { + commentsInRange.push(this.comments[idx]); + idx++; + } -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ + return commentsInRange; + } -class NamedChunkIdsPlugin { - constructor(options) { - this.delimiter = (options && options.delimiter) || "-"; - this.context = options && options.context; + /** + * @param {number} pos source code position + * @returns {boolean} true when a semicolon has been inserted before this position, false if not + */ + isAsiPosition(pos) { + const currentStatement = this.statementPath[this.statementPath.length - 1]; + if (currentStatement === undefined) throw new Error("Not in statement"); + return ( + // Either asking directly for the end position of the current statement + (currentStatement.range[1] === pos && this.semicolons.has(pos)) || + // Or asking for the start position of the current statement, + // here we have to check multiple things + (currentStatement.range[0] === pos && + // is there a previous statement which might be relevant? + this.prevStatement !== undefined && + // is the end position of the previous statement an ASI position? + this.semicolons.has(this.prevStatement.range[1])) + ); } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {number} pos source code position * @returns {void} */ - apply(compiler) { - compiler.hooks.compilation.tap("NamedChunkIdsPlugin", compilation => { - const { hashFunction } = compilation.outputOptions; - compilation.hooks.chunkIds.tap("NamedChunkIdsPlugin", chunks => { - const chunkGraph = compilation.chunkGraph; - const context = this.context ? this.context : compiler.context; - const delimiter = this.delimiter; + unsetAsiPosition(pos) { + this.semicolons.delete(pos); + } - const unnamedChunks = assignNames( - Array.from(chunks).filter(chunk => { - if (chunk.name) { - chunk.id = chunk.name; - chunk.ids = [chunk.name]; - } - return chunk.id === null; - }), - chunk => - getShortChunkName( - chunk, - chunkGraph, - context, - delimiter, - hashFunction, - compiler.root - ), - chunk => - getLongChunkName( - chunk, - chunkGraph, - context, - delimiter, - hashFunction, - compiler.root - ), - compareChunksNatural(chunkGraph), - getUsedChunkIds(compilation), - (chunk, name) => { - chunk.id = name; - chunk.ids = [name]; - } + isStatementLevelExpression(expr) { + const currentStatement = this.statementPath[this.statementPath.length - 1]; + return ( + expr === currentStatement || + (currentStatement.type === "ExpressionStatement" && + currentStatement.expression === expr) + ); + } + + getTagData(name, tag) { + const info = this.scope.definitions.get(name); + if (info instanceof VariableInfo) { + let tagInfo = info.tagInfo; + while (tagInfo !== undefined) { + if (tagInfo.tag === tag) return tagInfo.data; + tagInfo = tagInfo.next; + } + } + } + + tagVariable(name, tag, data) { + const oldInfo = this.scope.definitions.get(name); + /** @type {VariableInfo} */ + let newInfo; + if (oldInfo === undefined) { + newInfo = new VariableInfo(this.scope, name, { + tag, + data, + next: undefined + }); + } else if (oldInfo instanceof VariableInfo) { + newInfo = new VariableInfo(oldInfo.declaredScope, oldInfo.freeName, { + tag, + data, + next: oldInfo.tagInfo + }); + } else { + newInfo = new VariableInfo(oldInfo, true, { + tag, + data, + next: undefined + }); + } + this.scope.definitions.set(name, newInfo); + } + + defineVariable(name) { + const oldInfo = this.scope.definitions.get(name); + // Don't redefine variable in same scope to keep existing tags + if (oldInfo instanceof VariableInfo && oldInfo.declaredScope === this.scope) + return; + this.scope.definitions.set(name, this.scope); + } + + undefineVariable(name) { + this.scope.definitions.delete(name); + } + + isVariableDefined(name) { + const info = this.scope.definitions.get(name); + if (info === undefined) return false; + if (info instanceof VariableInfo) { + return info.freeName === true; + } + return true; + } + + /** + * @param {string} name variable name + * @returns {ExportedVariableInfo} info for this variable + */ + getVariableInfo(name) { + const value = this.scope.definitions.get(name); + if (value === undefined) { + return name; + } else { + return value; + } + } + + /** + * @param {string} name variable name + * @param {ExportedVariableInfo} variableInfo new info for this variable + * @returns {void} + */ + setVariable(name, variableInfo) { + if (typeof variableInfo === "string") { + if (variableInfo === name) { + this.scope.definitions.delete(name); + } else { + this.scope.definitions.set( + name, + new VariableInfo(this.scope, variableInfo, undefined) ); - if (unnamedChunks.length > 0) { - assignAscendingChunkIds(unnamedChunks, compilation); + } + } else { + this.scope.definitions.set(name, variableInfo); + } + } + + parseCommentOptions(range) { + const comments = this.getComments(range); + if (comments.length === 0) { + return EMPTY_COMMENT_OPTIONS; + } + let options = {}; + let errors = []; + for (const comment of comments) { + const { value } = comment; + if (value && webpackCommentRegExp.test(value)) { + // try compile only if webpack options comment is present + try { + const val = vm.runInNewContext(`(function(){return {${value}};})()`); + Object.assign(options, val); + } catch (e) { + e.comment = comment; + errors.push(e); } - }); - }); + } + } + return { options, errors }; + } + + /** + * @param {MemberExpressionNode} expression a member expression + * @returns {{ members: string[], object: ExpressionNode | SuperNode }} member names (reverse order) and remaining object + */ + extractMemberExpressionChain(expression) { + /** @type {AnyNode} */ + let expr = expression; + const members = []; + while (expr.type === "MemberExpression") { + if (expr.computed) { + if (expr.property.type !== "Literal") break; + members.push(`${expr.property.value}`); + } else { + if (expr.property.type !== "Identifier") break; + members.push(expr.property.name); + } + expr = expr.object; + } + return { + members, + object: expr + }; + } + + /** + * @param {string} varName variable name + * @returns {{name: string, info: VariableInfo | string}} name of the free variable and variable info for that + */ + getFreeInfoFromVariable(varName) { + const info = this.getVariableInfo(varName); + let name; + if (info instanceof VariableInfo) { + name = info.freeName; + if (typeof name !== "string") return undefined; + } else if (typeof info !== "string") { + return undefined; + } else { + name = info; + } + return { info, name }; + } + + /** @typedef {{ type: "call", call: CallExpressionNode, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => string[], name: string, getMembers: () => string[]}} CallExpressionInfo */ + /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[]}} ExpressionExpressionInfo */ + + /** + * @param {MemberExpressionNode} expression a member expression + * @param {number} allowedTypes which types should be returned, presented in bit mask + * @returns {CallExpressionInfo | ExpressionExpressionInfo | undefined} expression info + */ + getMemberExpressionInfo(expression, allowedTypes) { + const { object, members } = this.extractMemberExpressionChain(expression); + switch (object.type) { + case "CallExpression": { + if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0) + return undefined; + let callee = object.callee; + let rootMembers = EMPTY_ARRAY; + if (callee.type === "MemberExpression") { + ({ object: callee, members: rootMembers } = + this.extractMemberExpressionChain(callee)); + } + const rootName = getRootName(callee); + if (!rootName) return undefined; + const result = this.getFreeInfoFromVariable(rootName); + if (!result) return undefined; + const { info: rootInfo, name: resolvedRoot } = result; + const calleeName = objectAndMembersToName(resolvedRoot, rootMembers); + return { + type: "call", + call: object, + calleeName, + rootInfo, + getCalleeMembers: memoize(() => rootMembers.reverse()), + name: objectAndMembersToName(`${calleeName}()`, members), + getMembers: memoize(() => members.reverse()) + }; + } + case "Identifier": + case "MetaProperty": + case "ThisExpression": { + if ((allowedTypes & ALLOWED_MEMBER_TYPES_EXPRESSION) === 0) + return undefined; + const rootName = getRootName(object); + if (!rootName) return undefined; + + const result = this.getFreeInfoFromVariable(rootName); + if (!result) return undefined; + const { info: rootInfo, name: resolvedRoot } = result; + return { + type: "expression", + name: objectAndMembersToName(resolvedRoot, members), + rootInfo, + getMembers: memoize(() => members.reverse()) + }; + } + } + } + + /** + * @param {MemberExpressionNode} expression an expression + * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => string[]}} name info + */ + getNameForExpression(expression) { + return this.getMemberExpressionInfo( + expression, + ALLOWED_MEMBER_TYPES_EXPRESSION + ); + } + + /** + * @param {string} code source code + * @param {ParseOptions} options parsing options + * @returns {ProgramNode} parsed ast + */ + static _parse(code, options) { + const type = options ? options.sourceType : "module"; + /** @type {AcornOptions} */ + const parserOptions = { + ...defaultParserOptions, + allowReturnOutsideFunction: type === "script", + ...options, + sourceType: type === "auto" ? "module" : type + }; + + /** @type {AnyNode} */ + let ast; + let error; + let threw = false; + try { + ast = /** @type {AnyNode} */ (parser.parse(code, parserOptions)); + } catch (e) { + error = e; + threw = true; + } + + if (threw && type === "auto") { + parserOptions.sourceType = "script"; + if (!("allowReturnOutsideFunction" in options)) { + parserOptions.allowReturnOutsideFunction = true; + } + if (Array.isArray(parserOptions.onComment)) { + parserOptions.onComment.length = 0; + } + try { + ast = /** @type {AnyNode} */ (parser.parse(code, parserOptions)); + threw = false; + } catch (e) { + // we use the error from first parse try + // so nothing to do here + } + } + + if (threw) { + throw error; + } + + return /** @type {ProgramNode} */ (ast); } } -module.exports = NamedChunkIdsPlugin; +module.exports = JavascriptParser; +module.exports.ALLOWED_MEMBER_TYPES_ALL = ALLOWED_MEMBER_TYPES_ALL; +module.exports.ALLOWED_MEMBER_TYPES_EXPRESSION = + ALLOWED_MEMBER_TYPES_EXPRESSION; +module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = + ALLOWED_MEMBER_TYPES_CALL_EXPRESSION; /***/ }), -/***/ 24339: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 93998: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -94524,63 +94538,112 @@ module.exports = NamedChunkIdsPlugin; -const { compareModulesByIdentifier } = __webpack_require__(29579); -const { - getShortModuleName, - getLongModuleName, - assignNames, - getUsedModuleIdsAndModules, - assignAscendingModuleIds -} = __webpack_require__(63290); +const UnsupportedFeatureWarning = __webpack_require__(42495); +const ConstDependency = __webpack_require__(76911); +const BasicEvaluatedExpression = __webpack_require__(950); -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("estree").Expression} ExpressionNode */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("./JavascriptParser")} JavascriptParser */ -class NamedModuleIdsPlugin { - constructor(options) { - this.options = options || {}; - } +/** + * @param {JavascriptParser} parser the parser + * @param {string} value the const value + * @param {string[]=} runtimeRequirements runtime requirements + * @returns {function(ExpressionNode): true} plugin function + */ +exports.toConstantDependency = (parser, value, runtimeRequirements) => { + return function constDependency(expr) { + const dep = new ConstDependency(value, expr.range, runtimeRequirements); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + return true; + }; +}; - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const { root } = compiler; - compiler.hooks.compilation.tap("NamedModuleIdsPlugin", compilation => { - const { hashFunction } = compilation.outputOptions; - compilation.hooks.moduleIds.tap("NamedModuleIdsPlugin", () => { - const chunkGraph = compilation.chunkGraph; - const context = this.options.context - ? this.options.context - : compiler.context; +/** + * @param {string} value the string value + * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + */ +exports.evaluateToString = value => { + return function stringExpression(expr) { + return new BasicEvaluatedExpression().setString(value).setRange(expr.range); + }; +}; - const [usedIds, modules] = getUsedModuleIdsAndModules(compilation); - const unnamedModules = assignNames( - modules, - m => getShortModuleName(m, context, root), - (m, shortName) => - getLongModuleName(shortName, m, context, hashFunction, root), - compareModulesByIdentifier, - usedIds, - (m, name) => chunkGraph.setModuleId(m, name) - ); - if (unnamedModules.length > 0) { - assignAscendingModuleIds(usedIds, unnamedModules, compilation); - } - }); - }); - } -} +/** + * @param {number} value the number value + * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + */ +exports.evaluateToNumber = value => { + return function stringExpression(expr) { + return new BasicEvaluatedExpression().setNumber(value).setRange(expr.range); + }; +}; -module.exports = NamedModuleIdsPlugin; +/** + * @param {boolean} value the boolean value + * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + */ +exports.evaluateToBoolean = value => { + return function booleanExpression(expr) { + return new BasicEvaluatedExpression() + .setBoolean(value) + .setRange(expr.range); + }; +}; + +/** + * @param {string} identifier identifier + * @param {string} rootInfo rootInfo + * @param {function(): string[]} getMembers getMembers + * @param {boolean|null=} truthy is truthy, null if nullish + * @returns {function(ExpressionNode): BasicEvaluatedExpression} callback + */ +exports.evaluateToIdentifier = (identifier, rootInfo, getMembers, truthy) => { + return function identifierExpression(expr) { + let evaluatedExpression = new BasicEvaluatedExpression() + .setIdentifier(identifier, rootInfo, getMembers) + .setSideEffects(false) + .setRange(expr.range); + switch (truthy) { + case true: + evaluatedExpression.setTruthy(); + break; + case null: + evaluatedExpression.setNullish(true); + break; + case false: + evaluatedExpression.setFalsy(); + break; + } + + return evaluatedExpression; + }; +}; + +exports.expressionIsUnsupported = (parser, message) => { + return function unsupportedExpression(expr) { + const dep = new ConstDependency("(void 0)", expr.range, null); + dep.loc = expr.loc; + parser.state.module.addPresentationalDependency(dep); + if (!parser.state.module) return; + parser.state.module.addWarning( + new UnsupportedFeatureWarning(message, expr.loc) + ); + return true; + }; +}; + +exports.skipTraversal = () => true; + +exports.approve = () => true; /***/ }), -/***/ 86221: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 98124: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -94590,84 +94653,184 @@ module.exports = NamedModuleIdsPlugin; -const { compareChunksNatural } = __webpack_require__(29579); -const { assignAscendingChunkIds } = __webpack_require__(63290); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const { isSubset } = __webpack_require__(93347); +const { getAllChunks } = __webpack_require__(91145); +/** @typedef {import("../util/Hash")} Hash */ /** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {(string|number)[]} EntryItem */ -class NaturalChunkIdsPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap("NaturalChunkIdsPlugin", compilation => { - compilation.hooks.chunkIds.tap("NaturalChunkIdsPlugin", chunks => { - const chunkGraph = compilation.chunkGraph; - const compareNatural = compareChunksNatural(chunkGraph); - const chunksInNaturalOrder = Array.from(chunks).sort(compareNatural); - assignAscendingChunkIds(chunksInNaturalOrder, compilation); - }); - }); +const EXPORT_PREFIX = "var __webpack_exports__ = "; + +/** + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate + * @param {import("../ChunkGraph").EntryModuleWithChunkGroup[]} entries entries + * @param {Chunk} chunk chunk + * @param {boolean} passive true: passive startup with on chunks loaded + * @returns {string} runtime code + */ +exports.generateEntryStartup = ( + chunkGraph, + runtimeTemplate, + entries, + chunk, + passive +) => { + /** @type {string[]} */ + const runtime = [ + `var __webpack_exec__ = ${runtimeTemplate.returningFunction( + `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)`, + "moduleId" + )}` + ]; + + const runModule = id => { + return `__webpack_exec__(${JSON.stringify(id)})`; + }; + const outputCombination = (chunks, moduleIds, final) => { + if (chunks.size === 0) { + runtime.push( + `${final ? EXPORT_PREFIX : ""}(${moduleIds.map(runModule).join(", ")});` + ); + } else { + const fn = runtimeTemplate.returningFunction( + moduleIds.map(runModule).join(", ") + ); + runtime.push( + `${final && !passive ? EXPORT_PREFIX : ""}${ + passive + ? RuntimeGlobals.onChunksLoaded + : RuntimeGlobals.startupEntrypoint + }(0, ${JSON.stringify(Array.from(chunks, c => c.id))}, ${fn});` + ); + if (final && passive) { + runtime.push(`${EXPORT_PREFIX}${RuntimeGlobals.onChunksLoaded}();`); + } + } + }; + + let currentChunks = undefined; + let currentModuleIds = undefined; + + for (const [module, entrypoint] of entries) { + const runtimeChunk = entrypoint.getRuntimeChunk(); + const moduleId = chunkGraph.getModuleId(module); + const chunks = getAllChunks(entrypoint, chunk, runtimeChunk); + if ( + currentChunks && + currentChunks.size === chunks.size && + isSubset(currentChunks, chunks) + ) { + currentModuleIds.push(moduleId); + } else { + if (currentChunks) { + outputCombination(currentChunks, currentModuleIds); + } + currentChunks = chunks; + currentModuleIds = [moduleId]; + } } -} -module.exports = NaturalChunkIdsPlugin; + // output current modules with export prefix + if (currentChunks) { + outputCombination(currentChunks, currentModuleIds, true); + } + runtime.push(""); + return Template.asString(runtime); +}; + +/** + * @param {Hash} hash the hash to update + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {import("../ChunkGraph").EntryModuleWithChunkGroup[]} entries entries + * @param {Chunk} chunk chunk + * @returns {void} + */ +exports.updateHashForEntryStartup = (hash, chunkGraph, entries, chunk) => { + for (const [module, entrypoint] of entries) { + const runtimeChunk = entrypoint.getRuntimeChunk(); + const moduleId = chunkGraph.getModuleId(module); + hash.update(`${moduleId}`); + for (const c of getAllChunks(entrypoint, chunk, runtimeChunk)) + hash.update(`${c.id}`); + } +}; + +/** + * @param {Chunk} chunk the chunk + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {function(Chunk, ChunkGraph): boolean} filterFn filter function + * @returns {Set} initially fulfilled chunk ids + */ +exports.getInitialChunkIds = (chunk, chunkGraph, filterFn) => { + const initialChunkIds = new Set(chunk.ids); + for (const c of chunk.getAllInitialChunks()) { + if (c === chunk || filterFn(c, chunkGraph)) continue; + for (const id of c.ids) initialChunkIds.add(id); + } + return initialChunkIds; +}; /***/ }), -/***/ 83366: +/***/ 90490: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent + Author Tobias Koppers @sokra */ -const { - compareModulesByPreOrderIndexOrIdentifier -} = __webpack_require__(29579); -const { - assignAscendingModuleIds, - getUsedModuleIdsAndModules -} = __webpack_require__(63290); +const { register } = __webpack_require__(8282); -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +class JsonData { + constructor(data) { + this._buffer = undefined; + this._data = undefined; + if (Buffer.isBuffer(data)) { + this._buffer = data; + } else { + this._data = data; + } + } -class NaturalModuleIdsPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap("NaturalModuleIdsPlugin", compilation => { - compilation.hooks.moduleIds.tap("NaturalModuleIdsPlugin", modules => { - const [usedIds, modulesInNaturalOrder] = - getUsedModuleIdsAndModules(compilation); - modulesInNaturalOrder.sort( - compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph) - ); - assignAscendingModuleIds(usedIds, modulesInNaturalOrder, compilation); - }); - }); + get() { + if (this._data === undefined && this._buffer !== undefined) { + this._data = JSON.parse(this._buffer.toString()); + } + return this._data; } } -module.exports = NaturalModuleIdsPlugin; +register(JsonData, "webpack/lib/json/JsonData", null, { + serialize(obj, { write }) { + if (obj._buffer === undefined && obj._data !== undefined) { + obj._buffer = Buffer.from(JSON.stringify(obj._data)); + } + write(obj._buffer); + }, + deserialize({ read }) { + return new JsonData(read()); + } +}); + +module.exports = JsonData; /***/ }), -/***/ 51020: +/***/ 70393: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -94678,84 +94841,195 @@ module.exports = NaturalModuleIdsPlugin; -const { compareChunksNatural } = __webpack_require__(29579); -const createSchemaValidation = __webpack_require__(32540); -const { assignAscendingChunkIds } = __webpack_require__(63290); +const { RawSource } = __webpack_require__(51255); +const ConcatenationScope = __webpack_require__(98229); +const { UsageState } = __webpack_require__(63686); +const Generator = __webpack_require__(93401); +const RuntimeGlobals = __webpack_require__(16475); -/** @typedef {import("../../declarations/plugins/ids/OccurrenceChunkIdsPlugin").OccurrenceChunkIdsPluginOptions} OccurrenceChunkIdsPluginOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../ExportsInfo")} ExportsInfo */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -const validate = createSchemaValidation( - __webpack_require__(24344), - () => __webpack_require__(53576), - { - name: "Occurrence Order Chunk Ids Plugin", - baseDataPath: "options" +const stringifySafe = data => { + const stringified = JSON.stringify(data); + if (!stringified) { + return undefined; // Invalid JSON } -); -class OccurrenceChunkIdsPlugin { + return stringified.replace(/\u2028|\u2029/g, str => + str === "\u2029" ? "\\u2029" : "\\u2028" + ); // invalid in JavaScript but valid JSON +}; + +/** + * @param {Object} data data (always an object or array) + * @param {ExportsInfo} exportsInfo exports info + * @param {RuntimeSpec} runtime the runtime + * @returns {Object} reduced data + */ +const createObjectForExportsInfo = (data, exportsInfo, runtime) => { + if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) + return data; + const isArray = Array.isArray(data); + const reducedData = isArray ? [] : {}; + for (const key of Object.keys(data)) { + const exportInfo = exportsInfo.getReadOnlyExportInfo(key); + const used = exportInfo.getUsed(runtime); + if (used === UsageState.Unused) continue; + + let value; + if (used === UsageState.OnlyPropertiesUsed && exportInfo.exportsInfo) { + value = createObjectForExportsInfo( + data[key], + exportInfo.exportsInfo, + runtime + ); + } else { + value = data[key]; + } + const name = exportInfo.getUsedName(key, runtime); + reducedData[name] = value; + } + if (isArray) { + let arrayLengthWhenUsed = + exportsInfo.getReadOnlyExportInfo("length").getUsed(runtime) !== + UsageState.Unused + ? data.length + : undefined; + + let sizeObjectMinusArray = 0; + for (let i = 0; i < reducedData.length; i++) { + if (reducedData[i] === undefined) { + sizeObjectMinusArray -= 2; + } else { + sizeObjectMinusArray += `${i}`.length + 3; + } + } + if (arrayLengthWhenUsed !== undefined) { + sizeObjectMinusArray += + `${arrayLengthWhenUsed}`.length + + 8 - + (arrayLengthWhenUsed - reducedData.length) * 2; + } + if (sizeObjectMinusArray < 0) + return Object.assign( + arrayLengthWhenUsed === undefined + ? {} + : { length: arrayLengthWhenUsed }, + reducedData + ); + const generatedLength = + arrayLengthWhenUsed !== undefined + ? Math.max(arrayLengthWhenUsed, reducedData.length) + : reducedData.length; + for (let i = 0; i < generatedLength; i++) { + if (reducedData[i] === undefined) { + reducedData[i] = 0; + } + } + } + return reducedData; +}; + +const TYPES = new Set(["javascript"]); + +class JsonGenerator extends Generator { /** - * @param {OccurrenceChunkIdsPluginOptions=} options options object + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - constructor(options = {}) { - validate(options); - this.options = options; + getTypes(module) { + return TYPES; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - apply(compiler) { - const prioritiseInitial = this.options.prioritiseInitial; - compiler.hooks.compilation.tap("OccurrenceChunkIdsPlugin", compilation => { - compilation.hooks.chunkIds.tap("OccurrenceChunkIdsPlugin", chunks => { - const chunkGraph = compilation.chunkGraph; - - /** @type {Map} */ - const occursInInitialChunksMap = new Map(); - - const compareNatural = compareChunksNatural(chunkGraph); + getSize(module, type) { + let data = + module.buildInfo && + module.buildInfo.jsonData && + module.buildInfo.jsonData.get(); + if (!data) return 0; + return stringifySafe(data).length + 10; + } - for (const c of chunks) { - let occurs = 0; - for (const chunkGroup of c.groupsIterable) { - for (const parent of chunkGroup.parentsIterable) { - if (parent.isInitial()) occurs++; - } - } - occursInInitialChunksMap.set(c, occurs); - } + /** + * @param {NormalModule} module module for which the bailout reason should be determined + * @param {ConcatenationBailoutReasonContext} context context + * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated + */ + getConcatenationBailoutReason(module, context) { + return undefined; + } - const chunksInOccurrenceOrder = Array.from(chunks).sort((a, b) => { - if (prioritiseInitial) { - const aEntryOccurs = occursInInitialChunksMap.get(a); - const bEntryOccurs = occursInInitialChunksMap.get(b); - if (aEntryOccurs > bEntryOccurs) return -1; - if (aEntryOccurs < bEntryOccurs) return 1; - } - const aOccurs = a.getNumberOfGroups(); - const bOccurs = b.getNumberOfGroups(); - if (aOccurs > bOccurs) return -1; - if (aOccurs < bOccurs) return 1; - return compareNatural(a, b); - }); - assignAscendingChunkIds(chunksInOccurrenceOrder, compilation); - }); - }); + /** + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code + */ + generate( + module, + { + moduleGraph, + runtimeTemplate, + runtimeRequirements, + runtime, + concatenationScope + } + ) { + const data = + module.buildInfo && + module.buildInfo.jsonData && + module.buildInfo.jsonData.get(); + if (data === undefined) { + return new RawSource( + runtimeTemplate.missingModuleStatement({ + request: module.rawRequest + }) + ); + } + const exportsInfo = moduleGraph.getExportsInfo(module); + let finalJson = + typeof data === "object" && + data && + exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused + ? createObjectForExportsInfo(data, exportsInfo, runtime) + : data; + // Use JSON because JSON.parse() is much faster than JavaScript evaluation + const jsonStr = stringifySafe(finalJson); + const jsonExpr = + jsonStr.length > 20 && typeof finalJson === "object" + ? `JSON.parse('${jsonStr.replace(/[\\']/g, "\\$&")}')` + : jsonStr; + let content; + if (concatenationScope) { + content = `${runtimeTemplate.supportsConst() ? "const" : "var"} ${ + ConcatenationScope.NAMESPACE_OBJECT_EXPORT + } = ${jsonExpr};`; + concatenationScope.registerNamespaceExport( + ConcatenationScope.NAMESPACE_OBJECT_EXPORT + ); + } else { + runtimeRequirements.add(RuntimeGlobals.module); + content = `${module.moduleArgument}.exports = ${jsonExpr};`; + } + return new RawSource(content); } } -module.exports = OccurrenceChunkIdsPlugin; +module.exports = JsonGenerator; /***/ }), -/***/ 35371: +/***/ 86770: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -94766,163 +95040,119 @@ module.exports = OccurrenceChunkIdsPlugin; -const { - compareModulesByPreOrderIndexOrIdentifier -} = __webpack_require__(29579); const createSchemaValidation = __webpack_require__(32540); -const { - assignAscendingModuleIds, - getUsedModuleIdsAndModules -} = __webpack_require__(63290); +const JsonGenerator = __webpack_require__(70393); +const JsonParser = __webpack_require__(41090); -/** @typedef {import("../../declarations/plugins/ids/OccurrenceModuleIdsPlugin").OccurrenceModuleIdsPluginOptions} OccurrenceModuleIdsPluginOptions */ /** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ const validate = createSchemaValidation( - __webpack_require__(14916), - () => __webpack_require__(19330), + __webpack_require__(54094), + () => __webpack_require__(50166), { - name: "Occurrence Order Module Ids Plugin", - baseDataPath: "options" + name: "Json Modules Plugin", + baseDataPath: "parser" } ); -class OccurrenceModuleIdsPlugin { - /** - * @param {OccurrenceModuleIdsPluginOptions=} options options object - */ - constructor(options = {}) { - validate(options); - this.options = options; - } - +class JsonModulesPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - const prioritiseInitial = this.options.prioritiseInitial; - compiler.hooks.compilation.tap("OccurrenceModuleIdsPlugin", compilation => { - const moduleGraph = compilation.moduleGraph; + compiler.hooks.compilation.tap( + "JsonModulesPlugin", + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.createParser + .for("json") + .tap("JsonModulesPlugin", parserOptions => { + validate(parserOptions); - compilation.hooks.moduleIds.tap("OccurrenceModuleIdsPlugin", () => { - const chunkGraph = compilation.chunkGraph; + return new JsonParser(parserOptions); + }); + normalModuleFactory.hooks.createGenerator + .for("json") + .tap("JsonModulesPlugin", () => { + return new JsonGenerator(); + }); + } + ); + } +} - const [usedIds, modulesInOccurrenceOrder] = - getUsedModuleIdsAndModules(compilation); +module.exports = JsonModulesPlugin; - const occursInInitialChunksMap = new Map(); - const occursInAllChunksMap = new Map(); - const initialChunkChunkMap = new Map(); - const entryCountMap = new Map(); - for (const m of modulesInOccurrenceOrder) { - let initial = 0; - let entry = 0; - for (const c of chunkGraph.getModuleChunksIterable(m)) { - if (c.canBeInitial()) initial++; - if (chunkGraph.isEntryModuleInChunk(m, c)) entry++; - } - initialChunkChunkMap.set(m, initial); - entryCountMap.set(m, entry); - } +/***/ }), - /** - * @param {Module} module module - * @returns {number} count of occurs - */ - const countOccursInEntry = module => { - let sum = 0; - for (const [ - originModule, - connections - ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { - if (!originModule) continue; - if (!connections.some(c => c.isTargetActive(undefined))) continue; - sum += initialChunkChunkMap.get(originModule); - } - return sum; - }; +/***/ 41090: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @param {Module} module module - * @returns {number} count of occurs - */ - const countOccurs = module => { - let sum = 0; - for (const [ - originModule, - connections - ] of moduleGraph.getIncomingConnectionsByOriginModule(module)) { - if (!originModule) continue; - const chunkModules = - chunkGraph.getNumberOfModuleChunks(originModule); - for (const c of connections) { - if (!c.isTargetActive(undefined)) continue; - if (!c.dependency) continue; - const factor = c.dependency.getNumberOfIdOccurrences(); - if (factor === 0) continue; - sum += factor * chunkModules; - } - } - return sum; - }; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (prioritiseInitial) { - for (const m of modulesInOccurrenceOrder) { - const result = - countOccursInEntry(m) + - initialChunkChunkMap.get(m) + - entryCountMap.get(m); - occursInInitialChunksMap.set(m, result); - } - } - for (const m of modulesInOccurrenceOrder) { - const result = - countOccurs(m) + - chunkGraph.getNumberOfModuleChunks(m) + - entryCountMap.get(m); - occursInAllChunksMap.set(m, result); - } - const naturalCompare = compareModulesByPreOrderIndexOrIdentifier( - compilation.moduleGraph - ); +const parseJson = __webpack_require__(15235); +const Parser = __webpack_require__(11715); +const JsonExportsDependency = __webpack_require__(750); +const JsonData = __webpack_require__(90490); - modulesInOccurrenceOrder.sort((a, b) => { - if (prioritiseInitial) { - const aEntryOccurs = occursInInitialChunksMap.get(a); - const bEntryOccurs = occursInInitialChunksMap.get(b); - if (aEntryOccurs > bEntryOccurs) return -1; - if (aEntryOccurs < bEntryOccurs) return 1; - } - const aOccurs = occursInAllChunksMap.get(a); - const bOccurs = occursInAllChunksMap.get(b); - if (aOccurs > bOccurs) return -1; - if (aOccurs < bOccurs) return 1; - return naturalCompare(a, b); - }); +/** @typedef {import("../../declarations/plugins/JsonModulesPluginParser").JsonModulesPluginParserOptions} JsonModulesPluginParserOptions */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ - assignAscendingModuleIds( - usedIds, - modulesInOccurrenceOrder, - compilation - ); - }); - }); +class JsonParser extends Parser { + /** + * @param {JsonModulesPluginParserOptions} options parser options + */ + constructor(options) { + super(); + this.options = options || {}; + } + + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (Buffer.isBuffer(source)) { + source = source.toString("utf-8"); + } + + /** @type {JsonModulesPluginParserOptions["parse"]} */ + const parseFn = + typeof this.options.parse === "function" ? this.options.parse : parseJson; + + const data = + typeof source === "object" + ? source + : parseFn(source[0] === "\ufeff" ? source.slice(1) : source); + + state.module.buildInfo.jsonData = new JsonData(data); + state.module.buildInfo.strict = true; + state.module.buildMeta.exportsType = "default"; + state.module.buildMeta.defaultObject = + typeof data === "object" ? "redirect-warn" : false; + state.module.addDependency( + new JsonExportsDependency(JsonExportsDependency.getExportsFromData(data)) + ); + return state; } } -module.exports = OccurrenceModuleIdsPlugin; +module.exports = JsonParser; /***/ }), -/***/ 8635: +/***/ 26030: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -94933,30 +95163,46 @@ module.exports = OccurrenceModuleIdsPlugin; -const { WebpackError } = __webpack_require__(91919); -const { getUsedModuleIdsAndModules } = __webpack_require__(63290); +const RuntimeGlobals = __webpack_require__(16475); +const JavascriptModulesPlugin = __webpack_require__(89464); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ /** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ +/** @typedef {import("../util/Hash")} Hash */ -const plugin = "SyncModuleIdsPlugin"; +const COMMON_LIBRARY_NAME_MESSAGE = + "Common configuration options that specific library names are 'output.library[.name]', 'entry.xyz.library[.name]', 'ModuleFederationPlugin.name' and 'ModuleFederationPlugin.library[.name]'."; -class SyncModuleIdsPlugin { +/** + * @template T + * @typedef {Object} LibraryContext + * @property {Compilation} compilation + * @property {ChunkGraph} chunkGraph + * @property {T} options + */ + +/** + * @template T + */ +class AbstractLibraryPlugin { /** * @param {Object} options options - * @param {string} options.path path to file - * @param {string=} options.context context for module names - * @param {function(Module): boolean} options.test selector for modules - * @param {"read" | "create" | "merge" | "update"=} options.mode operation mode (defaults to merge) + * @param {string} options.pluginName name of the plugin + * @param {LibraryType} options.type used library type */ - constructor({ path, context, test, mode }) { - this._path = path; - this._context = context; - this._test = test || (() => true); - const readAndWrite = !mode || mode === "merge" || mode === "update"; - this._read = readAndWrite || mode === "read"; - this._write = readAndWrite || mode === "create"; - this._prune = mode === "update"; + constructor({ pluginName, type }) { + this._pluginName = pluginName; + this._type = type; + this._parseCache = new WeakMap(); } /** @@ -94965,112 +95211,253 @@ class SyncModuleIdsPlugin { * @returns {void} */ apply(compiler) { - /** @type {Map} */ - let data; - let dataChanged = false; - if (this._read) { - compiler.hooks.readRecords.tapAsync(plugin, callback => { - const fs = compiler.intermediateFileSystem; - fs.readFile(this._path, (err, buffer) => { - if (err) { - if (err.code !== "ENOENT") { - return callback(err); + const { _pluginName } = this; + compiler.hooks.thisCompilation.tap(_pluginName, compilation => { + compilation.hooks.finishModules.tap( + { name: _pluginName, stage: 10 }, + () => { + for (const [ + name, + { + dependencies: deps, + options: { library } + } + ] of compilation.entries) { + const options = this._parseOptionsCached( + library !== undefined + ? library + : compilation.outputOptions.library + ); + if (options !== false) { + const dep = deps[deps.length - 1]; + if (dep) { + const module = compilation.moduleGraph.getModule(dep); + if (module) { + this.finishEntryModule(module, name, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + } + } } - return callback(); - } - const json = JSON.parse(buffer.toString()); - data = new Map(); - for (const key of Object.keys(json)) { - data.set(key, json[key]); } - dataChanged = false; - return callback(); - }); - }); - } - if (this._write) { - compiler.hooks.emitRecords.tapAsync(plugin, callback => { - if (!data || !dataChanged) return callback(); - const json = {}; - const sorted = Array.from(data).sort(([a], [b]) => (a < b ? -1 : 1)); - for (const [key, value] of sorted) { - json[key] = value; } - const fs = compiler.intermediateFileSystem; - fs.writeFile(this._path, JSON.stringify(json), callback); - }); - } - compiler.hooks.thisCompilation.tap(plugin, compilation => { - const associatedObjectForCache = compiler.root; - const context = this._context || compiler.context; - if (this._read) { - compilation.hooks.reviveModules.tap(plugin, (_1, _2) => { - if (!data) return; - const { chunkGraph } = compilation; - const [usedIds, modules] = getUsedModuleIdsAndModules( - compilation, - this._test - ); - for (const module of modules) { - const name = module.libIdent({ - context, - associatedObjectForCache - }); - if (!name) continue; - const id = data.get(name); - const idAsString = `${id}`; - if (usedIds.has(idAsString)) { - const err = new WebpackError( - `SyncModuleIdsPlugin: Unable to restore id '${id}' from '${this._path}' as it's already used.` - ); - err.module = module; - compilation.errors.push(err); + ); + + const getOptionsForChunk = chunk => { + if (compilation.chunkGraph.getNumberOfEntryModules(chunk) === 0) + return false; + const options = chunk.getEntryOptions(); + const library = options && options.library; + return this._parseOptionsCached( + library !== undefined ? library : compilation.outputOptions.library + ); + }; + + if ( + this.render !== AbstractLibraryPlugin.prototype.render || + this.runtimeRequirements !== + AbstractLibraryPlugin.prototype.runtimeRequirements + ) { + compilation.hooks.additionalChunkRuntimeRequirements.tap( + _pluginName, + (chunk, set, { chunkGraph }) => { + const options = getOptionsForChunk(chunk); + if (options !== false) { + this.runtimeRequirements(chunk, set, { + options, + compilation, + chunkGraph + }); } - chunkGraph.setModuleId(module, id); - usedIds.add(idAsString); } + ); + } + + const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); + + if (this.render !== AbstractLibraryPlugin.prototype.render) { + hooks.render.tap(_pluginName, (source, renderContext) => { + const options = getOptionsForChunk(renderContext.chunk); + if (options === false) return source; + return this.render(source, renderContext, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); }); } - if (this._write) { - compilation.hooks.recordModules.tap(plugin, modules => { - const { chunkGraph } = compilation; - let oldData = data; - if (!oldData) { - oldData = data = new Map(); - } else if (this._prune) { - data = new Map(); - } - for (const module of modules) { - if (this._test(module)) { - const name = module.libIdent({ - context, - associatedObjectForCache - }); - if (!name) continue; - const id = chunkGraph.getModuleId(module); - if (id === null) continue; - const oldId = oldData.get(name); - if (oldId !== id) { - dataChanged = true; - } else if (data === oldData) { - continue; - } - data.set(name, id); - } + + if ( + this.embedInRuntimeBailout !== + AbstractLibraryPlugin.prototype.embedInRuntimeBailout + ) { + hooks.embedInRuntimeBailout.tap( + _pluginName, + (module, renderContext) => { + const options = getOptionsForChunk(renderContext.chunk); + if (options === false) return; + return this.embedInRuntimeBailout(module, renderContext, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); } - if (data.size !== oldData.size) dataChanged = true; + ); + } + + if ( + this.strictRuntimeBailout !== + AbstractLibraryPlugin.prototype.strictRuntimeBailout + ) { + hooks.strictRuntimeBailout.tap(_pluginName, renderContext => { + const options = getOptionsForChunk(renderContext.chunk); + if (options === false) return; + return this.strictRuntimeBailout(renderContext, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); }); } + + if ( + this.renderStartup !== AbstractLibraryPlugin.prototype.renderStartup + ) { + hooks.renderStartup.tap( + _pluginName, + (source, module, renderContext) => { + const options = getOptionsForChunk(renderContext.chunk); + if (options === false) return source; + return this.renderStartup(source, module, renderContext, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + } + ); + } + + hooks.chunkHash.tap(_pluginName, (chunk, hash, context) => { + const options = getOptionsForChunk(chunk); + if (options === false) return; + this.chunkHash(chunk, hash, context, { + options, + compilation, + chunkGraph: compilation.chunkGraph + }); + }); }); } + + /** + * @param {LibraryOptions=} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + _parseOptionsCached(library) { + if (!library) return false; + if (library.type !== this._type) return false; + const cacheEntry = this._parseCache.get(library); + if (cacheEntry !== undefined) return cacheEntry; + const result = this.parseOptions(library); + this._parseCache.set(library, result); + return result; + } + + /* istanbul ignore next */ + /** + * @abstract + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); + } + + /** + * @param {Module} module the exporting entry module + * @param {string} entryName the name of the entrypoint + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + finishEntryModule(module, entryName, libraryContext) {} + + /** + * @param {Module} module the exporting entry module + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {string | undefined} bailout reason + */ + embedInRuntimeBailout(module, renderContext, libraryContext) { + return undefined; + } + + /** + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {string | undefined} bailout reason + */ + strictRuntimeBailout(renderContext, libraryContext) { + return undefined; + } + + /** + * @param {Chunk} chunk the chunk + * @param {Set} set runtime requirements + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + runtimeRequirements(chunk, set, libraryContext) { + if (this.render !== AbstractLibraryPlugin.prototype.render) + set.add(RuntimeGlobals.returnExportsFromRuntime); + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render(source, renderContext, libraryContext) { + return source; + } + + /** + * @param {Source} source source + * @param {Module} module module + * @param {StartupRenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + renderStartup(source, module, renderContext, libraryContext) { + return source; + } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, libraryContext) { + const options = this._parseOptionsCached( + libraryContext.compilation.outputOptions.library + ); + hash.update(this._pluginName); + hash.update(JSON.stringify(options)); + } } -module.exports = SyncModuleIdsPlugin; +AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE = COMMON_LIBRARY_NAME_MESSAGE; +module.exports = AbstractLibraryPlugin; /***/ }), -/***/ 91919: +/***/ 67416: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95081,578 +95468,543 @@ module.exports = SyncModuleIdsPlugin; -const util = __webpack_require__(73837); -const memoize = __webpack_require__(78676); +const { ConcatSource } = __webpack_require__(51255); +const ExternalModule = __webpack_require__(73071); +const Template = __webpack_require__(1626); +const AbstractLibraryPlugin = __webpack_require__(26030); -/** @typedef {import("../declarations/WebpackOptions").Entry} Entry */ -/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} EntryNormalized */ -/** @typedef {import("../declarations/WebpackOptions").EntryObject} EntryObject */ -/** @typedef {import("../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../declarations/WebpackOptions").ModuleOptions} ModuleOptions */ -/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */ -/** @typedef {import("../declarations/WebpackOptions").RuleSetCondition} RuleSetCondition */ -/** @typedef {import("../declarations/WebpackOptions").RuleSetConditionAbsolute} RuleSetConditionAbsolute */ -/** @typedef {import("../declarations/WebpackOptions").RuleSetRule} RuleSetRule */ -/** @typedef {import("../declarations/WebpackOptions").RuleSetUse} RuleSetUse */ -/** @typedef {import("../declarations/WebpackOptions").RuleSetUseItem} RuleSetUseItem */ -/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} Configuration */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptionsNormalized */ -/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */ -/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */ -/** @typedef {import("./Compilation").Asset} Asset */ -/** @typedef {import("./Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("./MultiStats")} MultiStats */ -/** @typedef {import("./Parser").ParserState} ParserState */ -/** @typedef {import("./ResolverFactory").ResolvePluginInstance} ResolvePluginInstance */ -/** @typedef {import("./ResolverFactory").Resolver} Resolver */ -/** @typedef {import("./Watching")} Watching */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunk} StatsChunk */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunkGroup} StatsChunkGroup */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsChunkOrigin} StatsChunkOrigin */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsLogging} StatsLogging */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsLoggingEntry} StatsLoggingEntry */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleIssuer} StatsModuleIssuer */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleReason} StatsModuleReason */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleTraceDependency} StatsModuleTraceDependency */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModuleTraceItem} StatsModuleTraceItem */ -/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsProfile} StatsProfile */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ /** - * @template {Function} T - * @param {function(): T} factory factory function - * @returns {T} function + * @typedef {Object} AmdLibraryPluginOptions + * @property {LibraryType} type + * @property {boolean=} requireAsWrapper */ -const lazyFunction = factory => { - const fac = memoize(factory); - const f = /** @type {any} */ ( - (...args) => { - return fac()(...args); - } - ); - return /** @type {T} */ (f); -}; /** - * @template A - * @template B - * @param {A} obj input a - * @param {B} exports input b - * @returns {A & B} merged + * @typedef {Object} AmdLibraryPluginParsed + * @property {string} name */ -const mergeExports = (obj, exports) => { - const descriptors = Object.getOwnPropertyDescriptors(exports); - for (const name of Object.keys(descriptors)) { - const descriptor = descriptors[name]; - if (descriptor.get) { - const fn = descriptor.get; - Object.defineProperty(obj, name, { - configurable: false, - enumerable: true, - get: memoize(fn) - }); - } else if (typeof descriptor.value === "object") { - Object.defineProperty(obj, name, { - configurable: false, - enumerable: true, - writable: false, - value: mergeExports({}, descriptor.value) - }); + +/** + * @typedef {AmdLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class AmdLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {AmdLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "AmdLibraryPlugin", + type: options.type + }); + this.requireAsWrapper = options.requireAsWrapper; + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (this.requireAsWrapper) { + if (name) { + throw new Error( + `AMD library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } } else { - throw new Error( - "Exposed values must be either a getter or an nested object" - ); + if (name && typeof name !== "string") { + throw new Error( + `AMD library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } } + return { + name: /** @type {string=} */ (name) + }; } - return /** @type {A & B} */ (Object.freeze(obj)); -}; -const fn = lazyFunction(() => __webpack_require__(36243)); -module.exports = mergeExports(fn, { - get webpack() { - return __webpack_require__(36243); - }, - get validate() { - const webpackOptionsSchemaCheck = __webpack_require__(10382); - const getRealValidate = memoize(() => { - const validateSchema = __webpack_require__(12047); - const webpackOptionsSchema = __webpack_require__(73342); - return options => validateSchema(webpackOptionsSchema, options); - }); - return options => { - if (!webpackOptionsSchemaCheck(options)) getRealValidate()(options); - }; - }, - get validateSchema() { - const validateSchema = __webpack_require__(12047); - return validateSchema; - }, - get version() { - return /** @type {string} */ ((__webpack_require__(32702)/* .version */ .i8)); - }, + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render( + source, + { chunkGraph, chunk, runtimeTemplate }, + { options, compilation } + ) { + const modern = runtimeTemplate.supportsArrowFunction(); + const modules = chunkGraph + .getChunkModules(chunk) + .filter(m => m instanceof ExternalModule); + const externals = /** @type {ExternalModule[]} */ (modules); + const externalsDepsArray = JSON.stringify( + externals.map(m => + typeof m.request === "object" && !Array.isArray(m.request) + ? m.request.amd + : m.request + ) + ); + const externalsArguments = externals + .map( + m => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${chunkGraph.getModuleId(m)}` + )}__` + ) + .join(", "); - get cli() { - return __webpack_require__(13462); - }, - get AutomaticPrefetchPlugin() { - return __webpack_require__(17714); - }, - get AsyncDependenciesBlock() { - return __webpack_require__(47736); - }, - get BannerPlugin() { - return __webpack_require__(21242); - }, - get Cache() { - return __webpack_require__(7592); - }, - get Chunk() { - return __webpack_require__(39385); - }, - get ChunkGraph() { - return __webpack_require__(64971); - }, - get CleanPlugin() { - return __webpack_require__(31085); - }, - get Compilation() { - return __webpack_require__(85720); - }, - get Compiler() { - return __webpack_require__(70845); - }, - get ConcatenationScope() { - return __webpack_require__(98229); - }, - get ContextExclusionPlugin() { - return __webpack_require__(21411); - }, - get ContextReplacementPlugin() { - return __webpack_require__(12206); - }, - get DefinePlugin() { - return __webpack_require__(79065); - }, - get DelegatedPlugin() { - return __webpack_require__(80632); - }, - get Dependency() { - return __webpack_require__(54912); - }, - get DllPlugin() { - return __webpack_require__(40038); - }, - get DllReferencePlugin() { - return __webpack_require__(90999); - }, - get DynamicEntryPlugin() { - return __webpack_require__(96475); - }, - get EntryOptionPlugin() { - return __webpack_require__(9909); - }, - get EntryPlugin() { - return __webpack_require__(96953); - }, - get EnvironmentPlugin() { - return __webpack_require__(22070); - }, - get EvalDevToolModulePlugin() { - return __webpack_require__(65218); - }, - get EvalSourceMapDevToolPlugin() { - return __webpack_require__(14790); - }, - get ExternalModule() { - return __webpack_require__(73071); - }, - get ExternalsPlugin() { - return __webpack_require__(6652); - }, - get Generator() { - return __webpack_require__(93401); - }, - get HotUpdateChunk() { - return __webpack_require__(9597); - }, - get HotModuleReplacementPlugin() { - return __webpack_require__(6404); - }, - get IgnorePlugin() { - return __webpack_require__(84808); - }, - get JavascriptModulesPlugin() { - return util.deprecate( - () => __webpack_require__(89464), - "webpack.JavascriptModulesPlugin has moved to webpack.javascript.JavascriptModulesPlugin", - "DEP_WEBPACK_JAVASCRIPT_MODULES_PLUGIN" - )(); - }, - get LibManifestPlugin() { - return __webpack_require__(93837); - }, - get LibraryTemplatePlugin() { - return util.deprecate( - () => __webpack_require__(14157), - "webpack.LibraryTemplatePlugin is deprecated and has been replaced by compilation.outputOptions.library or compilation.addEntry + passing a library option", - "DEP_WEBPACK_LIBRARY_TEMPLATE_PLUGIN" - )(); - }, - get LoaderOptionsPlugin() { - return __webpack_require__(22078); - }, - get LoaderTargetPlugin() { - return __webpack_require__(86738); - }, - get Module() { - return __webpack_require__(73208); - }, - get ModuleFilenameHelpers() { - return __webpack_require__(88821); - }, - get ModuleGraph() { - return __webpack_require__(99988); - }, - get ModuleGraphConnection() { - return __webpack_require__(40639); - }, - get NoEmitOnErrorsPlugin() { - return __webpack_require__(50169); - }, - get NormalModule() { - return __webpack_require__(39); - }, - get NormalModuleReplacementPlugin() { - return __webpack_require__(30633); - }, - get MultiCompiler() { - return __webpack_require__(33370); - }, - get Parser() { - return __webpack_require__(11715); - }, - get PrefetchPlugin() { - return __webpack_require__(73850); - }, - get ProgressPlugin() { - return __webpack_require__(13216); - }, - get ProvidePlugin() { - return __webpack_require__(38309); - }, - get RuntimeGlobals() { - return __webpack_require__(16475); - }, - get RuntimeModule() { - return __webpack_require__(16963); - }, - get SingleEntryPlugin() { - return util.deprecate( - () => __webpack_require__(96953), - "SingleEntryPlugin was renamed to EntryPlugin", - "DEP_WEBPACK_SINGLE_ENTRY_PLUGIN" - )(); - }, - get SourceMapDevToolPlugin() { - return __webpack_require__(63872); - }, - get Stats() { - return __webpack_require__(31743); - }, - get Template() { - return __webpack_require__(39722); - }, - get UsageState() { - return (__webpack_require__(63686).UsageState); - }, - get WatchIgnorePlugin() { - return __webpack_require__(65193); - }, - get WebpackError() { - return __webpack_require__(53799); - }, - get WebpackOptionsApply() { - return __webpack_require__(88422); - }, - get WebpackOptionsDefaulter() { - return util.deprecate( - () => __webpack_require__(14452), - "webpack.WebpackOptionsDefaulter is deprecated and has been replaced by webpack.config.getNormalizedWebpackOptions and webpack.config.applyWebpackOptionsDefaults", - "DEP_WEBPACK_OPTIONS_DEFAULTER" - )(); - }, - // TODO webpack 6 deprecate - get WebpackOptionsValidationError() { - return (__webpack_require__(38476).ValidationError); - }, - get ValidationError() { - return (__webpack_require__(38476).ValidationError); - }, + const iife = runtimeTemplate.isIIFE(); + const fnStart = + (modern + ? `(${externalsArguments}) => {` + : `function(${externalsArguments}) {`) + + (iife || !chunk.hasRuntime() ? " return " : "\n"); + const fnEnd = iife ? ";\n}" : "\n}"; - cache: { - get MemoryCachePlugin() { - return __webpack_require__(52539); - } - }, + if (this.requireAsWrapper) { + return new ConcatSource( + `require(${externalsDepsArray}, ${fnStart}`, + source, + `${fnEnd});` + ); + } else if (options.name) { + const name = compilation.getPath(options.name, { + chunk + }); - config: { - get getNormalizedWebpackOptions() { - return (__webpack_require__(26693).getNormalizedWebpackOptions); - }, - get applyWebpackOptionsDefaults() { - return (__webpack_require__(92988).applyWebpackOptionsDefaults); + return new ConcatSource( + `define(${JSON.stringify(name)}, ${externalsDepsArray}, ${fnStart}`, + source, + `${fnEnd});` + ); + } else if (externalsArguments) { + return new ConcatSource( + `define(${externalsDepsArray}, ${fnStart}`, + source, + `${fnEnd});` + ); + } else { + return new ConcatSource(`define(${fnStart}`, source, `${fnEnd});`); } - }, + } - dependencies: { - get ModuleDependency() { - return __webpack_require__(80321); - }, - get ConstDependency() { - return __webpack_require__(76911); - }, - get NullDependency() { - return __webpack_require__(31830); + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { + hash.update("AmdLibraryPlugin"); + if (this.requireAsWrapper) { + hash.update("requireAsWrapper"); + } else if (options.name) { + hash.update("named"); + const name = compilation.getPath(options.name, { + chunk + }); + hash.update(name); } - }, + } +} - ids: { - get ChunkModuleIdRangePlugin() { - return __webpack_require__(64618); - }, - get NaturalModuleIdsPlugin() { - return __webpack_require__(83366); - }, - get OccurrenceModuleIdsPlugin() { - return __webpack_require__(35371); - }, - get NamedModuleIdsPlugin() { - return __webpack_require__(24339); - }, - get DeterministicChunkIdsPlugin() { - return __webpack_require__(8747); - }, - get DeterministicModuleIdsPlugin() { - return __webpack_require__(76692); - }, - get NamedChunkIdsPlugin() { - return __webpack_require__(6454); - }, - get OccurrenceChunkIdsPlugin() { - return __webpack_require__(51020); - }, - get HashedModuleIdsPlugin() { - return __webpack_require__(21825); - } - }, +module.exports = AmdLibraryPlugin; - javascript: { - get EnableChunkLoadingPlugin() { - return __webpack_require__(61291); - }, - get JavascriptModulesPlugin() { - return __webpack_require__(89464); - }, - get JavascriptParser() { - return __webpack_require__(29050); - } - }, - optimize: { - get AggressiveMergingPlugin() { - return __webpack_require__(64395); - }, - get AggressiveSplittingPlugin() { - return util.deprecate( - () => __webpack_require__(15543), - "AggressiveSplittingPlugin is deprecated in favor of SplitChunksPlugin", - "DEP_WEBPACK_AGGRESSIVE_SPLITTING_PLUGIN" - )(); - }, - get InnerGraph() { - return __webpack_require__(38988); - }, - get LimitChunkCountPlugin() { - return __webpack_require__(83608); - }, - get MinChunkSizePlugin() { - return __webpack_require__(53912); - }, - get ModuleConcatenationPlugin() { - return __webpack_require__(74844); - }, - get RealContentHashPlugin() { - return __webpack_require__(46043); - }, - get RuntimeChunkPlugin() { - return __webpack_require__(2837); - }, - get SideEffectsFlagPlugin() { - return __webpack_require__(84800); - }, - get SplitChunksPlugin() { - return __webpack_require__(21478); - } - }, +/***/ }), - runtime: { - get GetChunkFilenameRuntimeModule() { - return __webpack_require__(34277); - }, - get LoadScriptRuntimeModule() { - return __webpack_require__(19942); - } - }, +/***/ 40080: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - prefetch: { - get ChunkPrefetchPreloadPlugin() { - return __webpack_require__(33895); - } - }, +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - web: { - get FetchCompileAsyncWasmPlugin() { - return __webpack_require__(8437); - }, - get FetchCompileWasmPlugin() { - return __webpack_require__(35537); - }, - get JsonpChunkLoadingRuntimeModule() { - return __webpack_require__(84154); - }, - get JsonpTemplatePlugin() { - return __webpack_require__(4607); - } - }, - webworker: { - get WebWorkerTemplatePlugin() { - return __webpack_require__(68693); - } - }, - node: { - get NodeEnvironmentPlugin() { - return __webpack_require__(7553); - }, - get NodeSourcePlugin() { - return __webpack_require__(7103); - }, - get NodeTargetPlugin() { - return __webpack_require__(17916); - }, - get NodeTemplatePlugin() { - return __webpack_require__(61052); - }, - get ReadFileCompileWasmPlugin() { - return __webpack_require__(98939); - } - }, +const { ConcatSource } = __webpack_require__(51255); +const { UsageState } = __webpack_require__(63686); +const Template = __webpack_require__(1626); +const propertyAccess = __webpack_require__(54190); +const { getEntryRuntime } = __webpack_require__(17156); +const AbstractLibraryPlugin = __webpack_require__(26030); - electron: { - get ElectronTargetPlugin() { - return __webpack_require__(32277); - } - }, +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ - wasm: { - get AsyncWebAssemblyModulesPlugin() { - return __webpack_require__(7538); - } - }, +const KEYWORD_REGEX = + /^(await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|super|switch|static|this|throw|try|true|typeof|var|void|while|with|yield)$/; +const IDENTIFIER_REGEX = + /^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/iu; - library: { - get AbstractLibraryPlugin() { - return __webpack_require__(26030); - }, - get EnableLibraryPlugin() { - return __webpack_require__(91452); - } - }, +/** + * Validates the library name by checking for keywords and valid characters + * @param {string} name name to be validated + * @returns {boolean} true, when valid + */ +const isNameValid = name => { + return !KEYWORD_REGEX.test(name) && IDENTIFIER_REGEX.test(name); +}; - container: { - get ContainerPlugin() { - return __webpack_require__(9244); - }, - get ContainerReferencePlugin() { - return __webpack_require__(95757); - }, - get ModuleFederationPlugin() { - return __webpack_require__(30569); - }, - get scope() { - return (__webpack_require__(3083).scope); - } - }, +/** + * @param {string[]} accessor variable plus properties + * @param {number} existingLength items of accessor that are existing already + * @param {boolean=} initLast if the last property should also be initialized to an object + * @returns {string} code to access the accessor while initializing + */ +const accessWithInit = (accessor, existingLength, initLast = false) => { + // This generates for [a, b, c, d]: + // (((a = typeof a === "undefined" ? {} : a).b = a.b || {}).c = a.b.c || {}).d + const base = accessor[0]; + if (accessor.length === 1 && !initLast) return base; + let current = + existingLength > 0 + ? base + : `(${base} = typeof ${base} === "undefined" ? {} : ${base})`; - sharing: { - get ConsumeSharedPlugin() { - return __webpack_require__(15046); - }, - get ProvideSharedPlugin() { - return __webpack_require__(31225); - }, - get SharePlugin() { - return __webpack_require__(26335); - }, - get scope() { - return (__webpack_require__(3083).scope); + // i is the current position in accessor that has been printed + let i = 1; + + // all properties printed so far (excluding base) + let propsSoFar; + + // if there is existingLength, print all properties until this position as property access + if (existingLength > i) { + propsSoFar = accessor.slice(1, existingLength); + i = existingLength; + current += propertyAccess(propsSoFar); + } else { + propsSoFar = []; + } + + // all remaining properties (except the last one when initLast is not set) + // should be printed as initializer + const initUntil = initLast ? accessor.length : accessor.length - 1; + for (; i < initUntil; i++) { + const prop = accessor[i]; + propsSoFar.push(prop); + current = `(${current}${propertyAccess([prop])} = ${base}${propertyAccess( + propsSoFar + )} || {})`; + } + + // print the last property as property access if not yet printed + if (i < accessor.length) + current = `${current}${propertyAccess([accessor[accessor.length - 1]])}`; + + return current; +}; + +/** + * @typedef {Object} AssignLibraryPluginOptions + * @property {LibraryType} type + * @property {string[] | "global"} prefix name prefix + * @property {string | false} declare declare name as variable + * @property {"error"|"static"|"copy"|"assign"} unnamed behavior for unnamed library name + * @property {"copy"|"assign"=} named behavior for named library name + */ + +/** + * @typedef {Object} AssignLibraryPluginParsed + * @property {string | string[]} name + * @property {string | string[] | undefined} export + */ + +/** + * @typedef {AssignLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class AssignLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {AssignLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "AssignLibraryPlugin", + type: options.type + }); + this.prefix = options.prefix; + this.declare = options.declare; + this.unnamed = options.unnamed; + this.named = options.named || "assign"; + } + + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (this.unnamed === "error") { + if (typeof name !== "string" && !Array.isArray(name)) { + throw new Error( + `Library name must be a string or string array. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + } else { + if (name && typeof name !== "string" && !Array.isArray(name)) { + throw new Error( + `Library name must be a string, string array or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } } - }, + return { + name: /** @type {string|string[]=} */ (name), + export: library.export + }; + } - debug: { - get ProfilingPlugin() { - return __webpack_require__(2757); + /** + * @param {Module} module the exporting entry module + * @param {string} entryName the name of the entrypoint + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + finishEntryModule( + module, + entryName, + { options, compilation, compilation: { moduleGraph } } + ) { + const runtime = getEntryRuntime(compilation, entryName); + if (options.export) { + const exportsInfo = moduleGraph.getExportInfo( + module, + Array.isArray(options.export) ? options.export[0] : options.export + ); + exportsInfo.setUsed(UsageState.Used, runtime); + exportsInfo.canMangleUse = false; + } else { + const exportsInfo = moduleGraph.getExportsInfo(module); + exportsInfo.setUsedInUnknownWay(runtime); } - }, + moduleGraph.addExtraReason(module, "used as library export"); + } - util: { - get createHash() { - return __webpack_require__(49835); - }, - get comparators() { - return __webpack_require__(29579); - }, - get runtime() { - return __webpack_require__(17156); - }, - get serialization() { - return __webpack_require__(8282); - }, - get cleverMerge() { - return (__webpack_require__(60839).cachedCleverMerge); - }, - get LazySet() { - return __webpack_require__(38938); + _getPrefix(compilation) { + return this.prefix === "global" + ? [compilation.runtimeTemplate.globalObject] + : this.prefix; + } + + _getResolvedFullName(options, chunk, compilation) { + const prefix = this._getPrefix(compilation); + const fullName = options.name ? prefix.concat(options.name) : prefix; + return fullName.map(n => + compilation.getPath(n, { + chunk + }) + ); + } + + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render(source, { chunk }, { options, compilation }) { + const fullNameResolved = this._getResolvedFullName( + options, + chunk, + compilation + ); + if (this.declare) { + const base = fullNameResolved[0]; + if (!isNameValid(base)) { + throw new Error( + `Library name base (${base}) must be a valid identifier when using a var declaring library type. Either use a valid identifier (e. g. ${Template.toIdentifier( + base + )}) or use a different library type (e. g. 'type: "global"', which assign a property on the global scope instead of declaring a variable). ${ + AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE + }` + ); + } + source = new ConcatSource(`${this.declare} ${base};\n`, source); } - }, + return source; + } - get sources() { - return __webpack_require__(51255); - }, + /** + * @param {Module} module the exporting entry module + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {string | undefined} bailout reason + */ + embedInRuntimeBailout(module, { chunk }, { options, compilation }) { + const topLevelDeclarations = + module.buildInfo && module.buildInfo.topLevelDeclarations; + if (!topLevelDeclarations) + return "it doesn't tell about top level declarations."; + const fullNameResolved = this._getResolvedFullName( + options, + chunk, + compilation + ); + const base = fullNameResolved[0]; + if (topLevelDeclarations.has(base)) + return `it declares '${base}' on top-level, which conflicts with the current library output.`; + } - experiments: { - schemes: { - get HttpUriPlugin() { - return __webpack_require__(42110); + /** + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {string | undefined} bailout reason + */ + strictRuntimeBailout({ chunk }, { options, compilation }) { + if ( + this.declare || + this.prefix === "global" || + this.prefix.length > 0 || + !options.name + ) { + return; + } + return "a global variable is assign and maybe created"; + } + + /** + * @param {Source} source source + * @param {Module} module module + * @param {StartupRenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + renderStartup( + source, + module, + { moduleGraph, chunk }, + { options, compilation } + ) { + const fullNameResolved = this._getResolvedFullName( + options, + chunk, + compilation + ); + const staticExports = this.unnamed === "static"; + const exportAccess = options.export + ? propertyAccess( + Array.isArray(options.export) ? options.export : [options.export] + ) + : ""; + const result = new ConcatSource(source); + if (staticExports) { + const exportsInfo = moduleGraph.getExportsInfo(module); + const exportTarget = accessWithInit( + fullNameResolved, + this._getPrefix(compilation).length, + true + ); + for (const exportInfo of exportsInfo.orderedExports) { + if (!exportInfo.provided) continue; + const nameAccess = propertyAccess([exportInfo.name]); + result.add( + `${exportTarget}${nameAccess} = __webpack_exports__${exportAccess}${nameAccess};\n` + ); } - }, - ids: { - get SyncModuleIdsPlugin() { - return __webpack_require__(8635); + result.add( + `Object.defineProperty(${exportTarget}, "__esModule", { value: true });\n` + ); + } else if (options.name ? this.named === "copy" : this.unnamed === "copy") { + result.add( + `var __webpack_export_target__ = ${accessWithInit( + fullNameResolved, + this._getPrefix(compilation).length, + true + )};\n` + ); + let exports = "__webpack_exports__"; + if (exportAccess) { + result.add( + `var __webpack_exports_export__ = __webpack_exports__${exportAccess};\n` + ); + exports = "__webpack_exports_export__"; } + result.add( + `for(var i in ${exports}) __webpack_export_target__[i] = ${exports}[i];\n` + ); + result.add( + `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n` + ); + } else { + result.add( + `${accessWithInit( + fullNameResolved, + this._getPrefix(compilation).length, + false + )} = __webpack_exports__${exportAccess};\n` + ); } + return result; } -}); + + /** + * @param {Chunk} chunk the chunk + * @param {Set} set runtime requirements + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + runtimeRequirements(chunk, set, libraryContext) { + // we don't need to return exports from runtime + } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { + hash.update("AssignLibraryPlugin"); + const fullNameResolved = this._getResolvedFullName( + options, + chunk, + compilation + ); + if (options.name ? this.named === "copy" : this.unnamed === "copy") { + hash.update("copy"); + } + if (this.declare) { + hash.update(this.declare); + } + hash.update(fullNameResolved.join(".")); + if (options.export) { + hash.update(`${options.export}`); + } + } +} + +module.exports = AssignLibraryPlugin; /***/ }), -/***/ 18535: +/***/ 91452: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95663,159 +96015,253 @@ module.exports = mergeExports(fn, { -const { ConcatSource, PrefixSource, RawSource } = __webpack_require__(51255); -const { RuntimeGlobals } = __webpack_require__(91919); -const HotUpdateChunk = __webpack_require__(9597); -const Template = __webpack_require__(39722); -const { getCompilationHooks } = __webpack_require__(89464); -const { - generateEntryStartup, - updateHashForEntryStartup -} = __webpack_require__(98124); - +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ /** @typedef {import("../Compiler")} Compiler */ -class ArrayPushCallbackChunkFormatPlugin { +/** @type {WeakMap>} */ +const enabledTypes = new WeakMap(); + +const getEnabledTypes = compiler => { + let set = enabledTypes.get(compiler); + if (set === undefined) { + set = new Set(); + enabledTypes.set(compiler, set); + } + return set; +}; + +class EnableLibraryPlugin { + /** + * @param {LibraryType} type library type that should be available + */ + constructor(type) { + this.type = type; + } + + /** + * @param {Compiler} compiler the compiler instance + * @param {LibraryType} type type of library + * @returns {void} + */ + static setEnabled(compiler, type) { + getEnabledTypes(compiler).add(type); + } + + /** + * @param {Compiler} compiler the compiler instance + * @param {LibraryType} type type of library + * @returns {void} + */ + static checkEnabled(compiler, type) { + if (!getEnabledTypes(compiler).has(type)) { + throw new Error( + `Library type "${type}" is not enabled. ` + + "EnableLibraryPlugin need to be used to enable this type of library. " + + 'This usually happens through the "output.enabledLibraryTypes" option. ' + + 'If you are using a function as entry which sets "library", you need to add all potential library types to "output.enabledLibraryTypes". ' + + "These types are enabled: " + + Array.from(getEnabledTypes(compiler)).join(", ") + ); + } + } + /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - compiler.hooks.thisCompilation.tap( - "ArrayPushCallbackChunkFormatPlugin", - compilation => { - compilation.hooks.additionalChunkRuntimeRequirements.tap( - "ArrayPushCallbackChunkFormatPlugin", - (chunk, set, { chunkGraph }) => { - if (chunk.hasRuntime()) return; - if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { - set.add(RuntimeGlobals.onChunksLoaded); - set.add(RuntimeGlobals.require); - } - set.add(RuntimeGlobals.chunkCallback); - } - ); - const hooks = getCompilationHooks(compilation); - hooks.renderChunk.tap( - "ArrayPushCallbackChunkFormatPlugin", - (modules, renderContext) => { - const { chunk, chunkGraph, runtimeTemplate } = renderContext; - const hotUpdateChunk = - chunk instanceof HotUpdateChunk ? chunk : null; - const globalObject = runtimeTemplate.globalObject; - const source = new ConcatSource(); - const runtimeModules = - chunkGraph.getChunkRuntimeModulesInOrder(chunk); - if (hotUpdateChunk) { - const hotUpdateGlobal = - runtimeTemplate.outputOptions.hotUpdateGlobal; - source.add( - `${globalObject}[${JSON.stringify(hotUpdateGlobal)}](` - ); - source.add(`${JSON.stringify(chunk.id)},`); - source.add(modules); - if (runtimeModules.length > 0) { - source.add(",\n"); - const runtimePart = Template.renderChunkRuntimeModules( - runtimeModules, - renderContext - ); - source.add(runtimePart); - } - source.add(")"); - } else { - const chunkLoadingGlobal = - runtimeTemplate.outputOptions.chunkLoadingGlobal; - source.add( - `(${globalObject}[${JSON.stringify( - chunkLoadingGlobal - )}] = ${globalObject}[${JSON.stringify( - chunkLoadingGlobal - )}] || []).push([` - ); - source.add(`${JSON.stringify(chunk.ids)},`); - source.add(modules); - const entries = Array.from( - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) - ); - if (runtimeModules.length > 0 || entries.length > 0) { - const runtime = new ConcatSource( - (runtimeTemplate.supportsArrowFunction() - ? "__webpack_require__ =>" - : "function(__webpack_require__)") + - " { // webpackRuntimeModules\n" - ); - if (runtimeModules.length > 0) { - runtime.add( - Template.renderRuntimeModules(runtimeModules, { - ...renderContext, - codeGenerationResults: compilation.codeGenerationResults - }) - ); - } - if (entries.length > 0) { - const startupSource = new RawSource( - generateEntryStartup( - chunkGraph, - runtimeTemplate, - entries, - chunk, - true - ) - ); - runtime.add( - hooks.renderStartup.call( - startupSource, - entries[entries.length - 1][0], - { - ...renderContext, - inlined: false - } - ) - ); - if ( - chunkGraph - .getChunkRuntimeRequirements(chunk) - .has(RuntimeGlobals.returnExportsFromRuntime) - ) { - runtime.add("return __webpack_exports__;\n"); - } - } - runtime.add("}\n"); - source.add(",\n"); - source.add(new PrefixSource("/******/ ", runtime)); - } - source.add("])"); - } - return source; - } - ); - hooks.chunkHash.tap( - "ArrayPushCallbackChunkFormatPlugin", - (chunk, hash, { chunkGraph, runtimeTemplate }) => { - if (chunk.hasRuntime()) return; - hash.update( - `ArrayPushCallbackChunkFormatPlugin1${runtimeTemplate.outputOptions.chunkLoadingGlobal}${runtimeTemplate.outputOptions.hotUpdateGlobal}${runtimeTemplate.globalObject}` - ); - const entries = Array.from( - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) - ); - updateHashForEntryStartup(hash, chunkGraph, entries, chunk); - } - ); + const { type } = this; + + // Only enable once + const enabled = getEnabledTypes(compiler); + if (enabled.has(type)) return; + enabled.add(type); + + if (typeof type === "string") { + const enableExportProperty = () => { + const ExportPropertyTemplatePlugin = __webpack_require__(5487); + new ExportPropertyTemplatePlugin({ + type, + nsObjectUsed: type !== "module" + }).apply(compiler); + }; + switch (type) { + case "var": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: [], + declare: "var", + unnamed: "error" + }).apply(compiler); + break; + } + case "assign-properties": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: [], + declare: false, + unnamed: "error", + named: "copy" + }).apply(compiler); + break; + } + case "assign": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: [], + declare: false, + unnamed: "error" + }).apply(compiler); + break; + } + case "this": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: ["this"], + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "window": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: ["window"], + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "self": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: ["self"], + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "global": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: "global", + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "commonjs": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: ["exports"], + declare: false, + unnamed: "copy" + }).apply(compiler); + break; + } + case "commonjs-static": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: ["exports"], + declare: false, + unnamed: "static" + }).apply(compiler); + break; + } + case "commonjs2": + case "commonjs-module": { + //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 + const AssignLibraryPlugin = __webpack_require__(40080); + new AssignLibraryPlugin({ + type, + prefix: ["module", "exports"], + declare: false, + unnamed: "assign" + }).apply(compiler); + break; + } + case "amd": + case "amd-require": { + enableExportProperty(); + const AmdLibraryPlugin = __webpack_require__(67416); + new AmdLibraryPlugin({ + type, + requireAsWrapper: type === "amd-require" + }).apply(compiler); + break; + } + case "umd": + case "umd2": { + enableExportProperty(); + const UmdLibraryPlugin = __webpack_require__(54442); + new UmdLibraryPlugin({ + type, + optionalAmdExternalAsGlobal: type === "umd2" + }).apply(compiler); + break; + } + case "system": { + enableExportProperty(); + const SystemLibraryPlugin = __webpack_require__(11707); + new SystemLibraryPlugin({ + type + }).apply(compiler); + break; + } + case "jsonp": { + enableExportProperty(); + const JsonpLibraryPlugin = __webpack_require__(84415); + new JsonpLibraryPlugin({ + type + }).apply(compiler); + break; + } + case "module": { + enableExportProperty(); + const ModuleLibraryPlugin = __webpack_require__(59780); + new ModuleLibraryPlugin({ + type + }).apply(compiler); + break; + } + default: + throw new Error(`Unsupported library type ${type}. +Plugins which provide custom library types must call EnableLibraryPlugin.setEnabled(compiler, type) to disable this error.`); } - ); + } else { + // TODO support plugin instances here + // apply them to the compiler + } } } -module.exports = ArrayPushCallbackChunkFormatPlugin; +module.exports = EnableLibraryPlugin; /***/ }), -/***/ 950: -/***/ (function(module) { +/***/ 5487: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -95825,705 +96271,566 @@ module.exports = ArrayPushCallbackChunkFormatPlugin; -/** @typedef {import("estree").Node} EsTreeNode */ -/** @typedef {import("./JavascriptParser").VariableInfoInterface} VariableInfoInterface */ +const { ConcatSource } = __webpack_require__(51255); +const { UsageState } = __webpack_require__(63686); +const propertyAccess = __webpack_require__(54190); +const { getEntryRuntime } = __webpack_require__(17156); +const AbstractLibraryPlugin = __webpack_require__(26030); -const TypeUnknown = 0; -const TypeUndefined = 1; -const TypeNull = 2; -const TypeString = 3; -const TypeNumber = 4; -const TypeBoolean = 5; -const TypeRegExp = 6; -const TypeConditional = 7; -const TypeArray = 8; -const TypeConstArray = 9; -const TypeIdentifier = 10; -const TypeWrapped = 11; -const TypeTemplateString = 12; -const TypeBigInt = 13; +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ -class BasicEvaluatedExpression { - constructor() { - this.type = TypeUnknown; - /** @type {[number, number]} */ - this.range = undefined; - /** @type {boolean} */ - this.falsy = false; - /** @type {boolean} */ - this.truthy = false; - /** @type {boolean | undefined} */ - this.nullish = undefined; - /** @type {boolean} */ - this.sideEffects = true; - /** @type {boolean | undefined} */ - this.bool = undefined; - /** @type {number | undefined} */ - this.number = undefined; - /** @type {bigint | undefined} */ - this.bigint = undefined; - /** @type {RegExp | undefined} */ - this.regExp = undefined; - /** @type {string | undefined} */ - this.string = undefined; - /** @type {BasicEvaluatedExpression[] | undefined} */ - this.quasis = undefined; - /** @type {BasicEvaluatedExpression[] | undefined} */ - this.parts = undefined; - /** @type {any[] | undefined} */ - this.array = undefined; - /** @type {BasicEvaluatedExpression[] | undefined} */ - this.items = undefined; - /** @type {BasicEvaluatedExpression[] | undefined} */ - this.options = undefined; - /** @type {BasicEvaluatedExpression | undefined} */ - this.prefix = undefined; - /** @type {BasicEvaluatedExpression | undefined} */ - this.postfix = undefined; - this.wrappedInnerExpressions = undefined; - /** @type {string | undefined} */ - this.identifier = undefined; - /** @type {VariableInfoInterface} */ - this.rootInfo = undefined; - /** @type {() => string[]} */ - this.getMembers = undefined; - /** @type {EsTreeNode} */ - this.expression = undefined; - } +/** + * @typedef {Object} ExportPropertyLibraryPluginParsed + * @property {string | string[]} export + */ - isUnknown() { - return this.type === TypeUnknown; +/** + * @typedef {Object} ExportPropertyLibraryPluginOptions + * @property {LibraryType} type + * @property {boolean} nsObjectUsed the namespace object is used + */ +/** + * @typedef {ExportPropertyLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {ExportPropertyLibraryPluginOptions} options options + */ + constructor({ type, nsObjectUsed }) { + super({ + pluginName: "ExportPropertyLibraryPlugin", + type + }); + this.nsObjectUsed = nsObjectUsed; } - isNull() { - return this.type === TypeNull; + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + return { + export: library.export + }; } - isUndefined() { - return this.type === TypeUndefined; + /** + * @param {Module} module the exporting entry module + * @param {string} entryName the name of the entrypoint + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + finishEntryModule( + module, + entryName, + { options, compilation, compilation: { moduleGraph } } + ) { + const runtime = getEntryRuntime(compilation, entryName); + if (options.export) { + const exportsInfo = moduleGraph.getExportInfo( + module, + Array.isArray(options.export) ? options.export[0] : options.export + ); + exportsInfo.setUsed(UsageState.Used, runtime); + exportsInfo.canMangleUse = false; + } else { + const exportsInfo = moduleGraph.getExportsInfo(module); + if (this.nsObjectUsed) { + exportsInfo.setUsedInUnknownWay(runtime); + } else { + exportsInfo.setAllKnownExportsUsed(runtime); + } + } + moduleGraph.addExtraReason(module, "used as library export"); } - isString() { - return this.type === TypeString; - } + /** + * @param {Chunk} chunk the chunk + * @param {Set} set runtime requirements + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + runtimeRequirements(chunk, set, libraryContext) {} - isNumber() { - return this.type === TypeNumber; + /** + * @param {Source} source source + * @param {Module} module module + * @param {StartupRenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + renderStartup(source, module, renderContext, { options }) { + if (!options.export) return source; + const postfix = `__webpack_exports__ = __webpack_exports__${propertyAccess( + Array.isArray(options.export) ? options.export : [options.export] + )};\n`; + return new ConcatSource(source, postfix); } +} - isBigInt() { - return this.type === TypeBigInt; - } +module.exports = ExportPropertyLibraryPlugin; - isBoolean() { - return this.type === TypeBoolean; - } - isRegExp() { - return this.type === TypeRegExp; - } +/***/ }), - isConditional() { - return this.type === TypeConditional; - } +/***/ 84415: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - isArray() { - return this.type === TypeArray; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - isConstArray() { - return this.type === TypeConstArray; - } - isIdentifier() { - return this.type === TypeIdentifier; - } - isWrapped() { - return this.type === TypeWrapped; - } +const { ConcatSource } = __webpack_require__(51255); +const AbstractLibraryPlugin = __webpack_require__(26030); - isTemplateString() { - return this.type === TypeTemplateString; - } +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + +/** + * @typedef {Object} JsonpLibraryPluginOptions + * @property {LibraryType} type + */ + +/** + * @typedef {Object} JsonpLibraryPluginParsed + * @property {string} name + */ +/** + * @typedef {JsonpLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class JsonpLibraryPlugin extends AbstractLibraryPlugin { /** - * Is expression a primitive or an object type value? - * @returns {boolean | undefined} true: primitive type, false: object type, undefined: unknown/runtime-defined + * @param {JsonpLibraryPluginOptions} options the plugin options */ - isPrimitiveType() { - switch (this.type) { - case TypeUndefined: - case TypeNull: - case TypeString: - case TypeNumber: - case TypeBoolean: - case TypeBigInt: - case TypeWrapped: - case TypeTemplateString: - return true; - case TypeRegExp: - case TypeArray: - case TypeConstArray: - return false; - default: - return undefined; - } + constructor(options) { + super({ + pluginName: "JsonpLibraryPlugin", + type: options.type + }); } /** - * Is expression a runtime or compile-time value? - * @returns {boolean} true: compile time value, false: runtime value + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding */ - isCompileTimeValue() { - switch (this.type) { - case TypeUndefined: - case TypeNull: - case TypeString: - case TypeNumber: - case TypeBoolean: - case TypeRegExp: - case TypeConstArray: - case TypeBigInt: - return true; - default: - return false; + parseOptions(library) { + const { name } = library; + if (typeof name !== "string") { + throw new Error( + `Jsonp library name must be a simple string. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); } + return { + name: /** @type {string} */ (name) + }; } /** - * Gets the compile-time value of the expression - * @returns {any} the javascript value + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export */ - asCompileTimeValue() { - switch (this.type) { - case TypeUndefined: - return undefined; - case TypeNull: - return null; - case TypeString: - return this.string; - case TypeNumber: - return this.number; - case TypeBoolean: - return this.bool; - case TypeRegExp: - return this.regExp; - case TypeConstArray: - return this.array; - case TypeBigInt: - return this.bigint; - default: - throw new Error( - "asCompileTimeValue must only be called for compile-time values" - ); - } - } - - isTruthy() { - return this.truthy; - } - - isFalsy() { - return this.falsy; - } - - isNullish() { - return this.nullish; + render(source, { chunk }, { options, compilation }) { + const name = compilation.getPath(options.name, { + chunk + }); + return new ConcatSource(`${name}(`, source, ")"); } /** - * Can this expression have side effects? - * @returns {boolean} false: never has side effects + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} */ - couldHaveSideEffects() { - return this.sideEffects; - } - - asBool() { - if (this.truthy) return true; - if (this.falsy || this.nullish) return false; - if (this.isBoolean()) return this.bool; - if (this.isNull()) return false; - if (this.isUndefined()) return false; - if (this.isString()) return this.string !== ""; - if (this.isNumber()) return this.number !== 0; - if (this.isBigInt()) return this.bigint !== BigInt(0); - if (this.isRegExp()) return true; - if (this.isArray()) return true; - if (this.isConstArray()) return true; - if (this.isWrapped()) { - return (this.prefix && this.prefix.asBool()) || - (this.postfix && this.postfix.asBool()) - ? true - : undefined; - } - if (this.isTemplateString()) { - const str = this.asString(); - if (typeof str === "string") return str !== ""; - } - return undefined; + chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { + hash.update("JsonpLibraryPlugin"); + hash.update(compilation.getPath(options.name, { chunk })); } +} - asNullish() { - const nullish = this.isNullish(); - - if (nullish === true || this.isNull() || this.isUndefined()) return true; - - if (nullish === false) return false; - if (this.isTruthy()) return false; - if (this.isBoolean()) return false; - if (this.isString()) return false; - if (this.isNumber()) return false; - if (this.isBigInt()) return false; - if (this.isRegExp()) return false; - if (this.isArray()) return false; - if (this.isConstArray()) return false; - if (this.isTemplateString()) return false; - if (this.isRegExp()) return false; +module.exports = JsonpLibraryPlugin; - return undefined; - } - asString() { - if (this.isBoolean()) return `${this.bool}`; - if (this.isNull()) return "null"; - if (this.isUndefined()) return "undefined"; - if (this.isString()) return this.string; - if (this.isNumber()) return `${this.number}`; - if (this.isBigInt()) return `${this.bigint}`; - if (this.isRegExp()) return `${this.regExp}`; - if (this.isArray()) { - let array = []; - for (const item of this.items) { - const itemStr = item.asString(); - if (itemStr === undefined) return undefined; - array.push(itemStr); - } - return `${array}`; - } - if (this.isConstArray()) return `${this.array}`; - if (this.isTemplateString()) { - let str = ""; - for (const part of this.parts) { - const partStr = part.asString(); - if (partStr === undefined) return undefined; - str += partStr; - } - return str; - } - return undefined; - } +/***/ }), - setString(string) { - this.type = TypeString; - this.string = string; - this.sideEffects = false; - return this; - } +/***/ 59780: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - setUndefined() { - this.type = TypeUndefined; - this.sideEffects = false; - return this; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - setNull() { - this.type = TypeNull; - this.sideEffects = false; - return this; - } - setNumber(number) { - this.type = TypeNumber; - this.number = number; - this.sideEffects = false; - return this; - } - setBigInt(bigint) { - this.type = TypeBigInt; - this.bigint = bigint; - this.sideEffects = false; - return this; - } +const { ConcatSource } = __webpack_require__(51255); +const Template = __webpack_require__(1626); +const propertyAccess = __webpack_require__(54190); +const AbstractLibraryPlugin = __webpack_require__(26030); - setBoolean(bool) { - this.type = TypeBoolean; - this.bool = bool; - this.sideEffects = false; - return this; - } +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ - setRegExp(regExp) { - this.type = TypeRegExp; - this.regExp = regExp; - this.sideEffects = false; - return this; - } +/** + * @typedef {Object} ModuleLibraryPluginOptions + * @property {LibraryType} type + */ - setIdentifier(identifier, rootInfo, getMembers) { - this.type = TypeIdentifier; - this.identifier = identifier; - this.rootInfo = rootInfo; - this.getMembers = getMembers; - this.sideEffects = true; - return this; - } +/** + * @typedef {Object} ModuleLibraryPluginParsed + * @property {string} name + */ - setWrapped(prefix, postfix, innerExpressions) { - this.type = TypeWrapped; - this.prefix = prefix; - this.postfix = postfix; - this.wrappedInnerExpressions = innerExpressions; - this.sideEffects = true; - return this; +/** + * @typedef {ModuleLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class ModuleLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {ModuleLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "ModuleLibraryPlugin", + type: options.type + }); } - setOptions(options) { - this.type = TypeConditional; - this.options = options; - this.sideEffects = true; - return this; + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (name) { + throw new Error( + `Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + return { + name: /** @type {string} */ (name) + }; } - addOptions(options) { - if (!this.options) { - this.type = TypeConditional; - this.options = []; - this.sideEffects = true; + /** + * @param {Source} source source + * @param {Module} module module + * @param {StartupRenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + renderStartup( + source, + module, + { moduleGraph, chunk }, + { options, compilation } + ) { + const result = new ConcatSource(source); + const exportsInfo = moduleGraph.getExportsInfo(module); + const exports = []; + const isAsync = moduleGraph.isAsync(module); + if (isAsync) { + result.add(`__webpack_exports__ = await __webpack_exports__;\n`); } - for (const item of options) { - this.options.push(item); + for (const exportInfo of exportsInfo.orderedExports) { + if (!exportInfo.provided) continue; + const varName = `__webpack_exports__${Template.toIdentifier( + exportInfo.name + )}`; + result.add( + `var ${varName} = __webpack_exports__${propertyAccess([ + exportInfo.getUsedName(exportInfo.name, chunk.runtime) + ])};\n` + ); + exports.push(`${varName} as ${exportInfo.name}`); } - return this; - } - - setItems(items) { - this.type = TypeArray; - this.items = items; - this.sideEffects = items.some(i => i.couldHaveSideEffects()); - return this; - } - - setArray(array) { - this.type = TypeConstArray; - this.array = array; - this.sideEffects = false; - return this; - } - - setTemplateString(quasis, parts, kind) { - this.type = TypeTemplateString; - this.quasis = quasis; - this.parts = parts; - this.templateStringKind = kind; - this.sideEffects = parts.some(p => p.sideEffects); - return this; - } - - setTruthy() { - this.falsy = false; - this.truthy = true; - this.nullish = false; - return this; - } - - setFalsy() { - this.falsy = true; - this.truthy = false; - return this; - } - - setNullish(value) { - this.nullish = value; - - if (value) return this.setFalsy(); - - return this; - } - - setRange(range) { - this.range = range; - return this; - } - - setSideEffects(sideEffects = true) { - this.sideEffects = sideEffects; - return this; - } - - setExpression(expression) { - this.expression = expression; - return this; + if (exports.length > 0) { + result.add(`export { ${exports.join(", ")} };\n`); + } + return result; } } -/** - * @param {string} flags regexp flags - * @returns {boolean} is valid flags - */ -BasicEvaluatedExpression.isValidRegExpFlags = flags => { - const len = flags.length; - - if (len === 0) return true; - if (len > 4) return false; - - // cspell:word gimy - let remaining = 0b0000; // bit per RegExp flag: gimy - - for (let i = 0; i < len; i++) - switch (flags.charCodeAt(i)) { - case 103 /* g */: - if (remaining & 0b1000) return false; - remaining |= 0b1000; - break; - case 105 /* i */: - if (remaining & 0b0100) return false; - remaining |= 0b0100; - break; - case 109 /* m */: - if (remaining & 0b0010) return false; - remaining |= 0b0010; - break; - case 121 /* y */: - if (remaining & 0b0001) return false; - remaining |= 0b0001; - break; - default: - return false; - } - - return true; -}; - -module.exports = BasicEvaluatedExpression; +module.exports = ModuleLibraryPlugin; /***/ }), -/***/ 91145: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 11707: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Joel Denning @joeldenning */ -const Entrypoint = __webpack_require__(13795); +const { ConcatSource } = __webpack_require__(51255); +const { UsageState } = __webpack_require__(63686); +const ExternalModule = __webpack_require__(73071); +const Template = __webpack_require__(1626); +const propertyAccess = __webpack_require__(54190); +const AbstractLibraryPlugin = __webpack_require__(26030); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ /** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ /** - * @param {Entrypoint} entrypoint a chunk group - * @param {Chunk} excludedChunk1 current chunk which is excluded - * @param {Chunk} excludedChunk2 runtime chunk which is excluded - * @returns {Set} chunks + * @typedef {Object} SystemLibraryPluginOptions + * @property {LibraryType} type */ -const getAllChunks = (entrypoint, excludedChunk1, excludedChunk2) => { - const queue = new Set([entrypoint]); - const chunks = new Set(); - for (const entrypoint of queue) { - for (const chunk of entrypoint.chunks) { - if (chunk === excludedChunk1) continue; - if (chunk === excludedChunk2) continue; - chunks.add(chunk); - } - for (const parent of entrypoint.parentsIterable) { - if (parent instanceof Entrypoint) queue.add(parent); - } + +/** + * @typedef {Object} SystemLibraryPluginParsed + * @property {string} name + */ + +/** + * @typedef {SystemLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class SystemLibraryPlugin extends AbstractLibraryPlugin { + /** + * @param {SystemLibraryPluginOptions} options the plugin options + */ + constructor(options) { + super({ + pluginName: "SystemLibraryPlugin", + type: options.type + }); } - return chunks; -}; -exports.getAllChunks = getAllChunks; + /** + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding + */ + parseOptions(library) { + const { name } = library; + if (name && typeof name !== "string") { + throw new Error( + `System.js library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` + ); + } + return { + name: /** @type {string=} */ (name) + }; + } -/***/ }), + /** + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export + */ + render(source, { chunkGraph, moduleGraph, chunk }, { options, compilation }) { + const modules = chunkGraph + .getChunkModules(chunk) + .filter(m => m instanceof ExternalModule && m.externalType === "system"); + const externals = /** @type {ExternalModule[]} */ (modules); -/***/ 84508: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // The name this bundle should be registered as with System + const name = options.name + ? `${JSON.stringify(compilation.getPath(options.name, { chunk }))}, ` + : ""; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // The array of dependencies that are external to webpack and will be provided by System + const systemDependencies = JSON.stringify( + externals.map(m => + typeof m.request === "object" && !Array.isArray(m.request) + ? m.request.amd + : m.request + ) + ); + // The name of the variable provided by System for exporting + const dynamicExport = "__WEBPACK_DYNAMIC_EXPORT__"; + // An array of the internal variable names for the webpack externals + const externalWebpackNames = externals.map( + m => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${chunkGraph.getModuleId(m)}` + )}__` + ); -const { ConcatSource, RawSource } = __webpack_require__(51255); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const { - getChunkFilenameTemplate, - getCompilationHooks -} = __webpack_require__(89464); -const { - generateEntryStartup, - updateHashForEntryStartup -} = __webpack_require__(98124); + // Declaring variables for the internal variable names for the webpack externals + const externalVarDeclarations = externalWebpackNames + .map(name => `var ${name} = {};`) + .join("\n"); -/** @typedef {import("../Compiler")} Compiler */ + // Define __esModule flag on all internal variables and helpers + const externalVarInitialization = []; -class CommonJsChunkFormatPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "CommonJsChunkFormatPlugin", - compilation => { - compilation.hooks.additionalChunkRuntimeRequirements.tap( - "CommonJsChunkLoadingPlugin", - (chunk, set, { chunkGraph }) => { - if (chunk.hasRuntime()) return; - if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { - set.add(RuntimeGlobals.require); - set.add(RuntimeGlobals.startupEntrypoint); - set.add(RuntimeGlobals.externalInstallChunk); - } - } - ); - const hooks = getCompilationHooks(compilation); - hooks.renderChunk.tap( - "CommonJsChunkFormatPlugin", - (modules, renderContext) => { - const { chunk, chunkGraph, runtimeTemplate } = renderContext; - const source = new ConcatSource(); - source.add(`exports.id = ${JSON.stringify(chunk.id)};\n`); - source.add(`exports.ids = ${JSON.stringify(chunk.ids)};\n`); - source.add(`exports.modules = `); - source.add(modules); - source.add(";\n"); - const runtimeModules = - chunkGraph.getChunkRuntimeModulesInOrder(chunk); - if (runtimeModules.length > 0) { - source.add("exports.runtime =\n"); - source.add( - Template.renderChunkRuntimeModules( - runtimeModules, - renderContext - ) - ); - } - const entries = Array.from( - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) - ); - if (entries.length > 0) { - const runtimeChunk = entries[0][1].getRuntimeChunk(); - const currentOutputName = compilation - .getPath( - getChunkFilenameTemplate(chunk, compilation.outputOptions), - { - chunk, - contentHashType: "javascript" + // The system.register format requires an array of setter functions for externals. + const setters = + externalWebpackNames.length === 0 + ? "" + : Template.asString([ + "setters: [", + Template.indent( + externals + .map((module, i) => { + const external = externalWebpackNames[i]; + const exportsInfo = moduleGraph.getExportsInfo(module); + const otherUnused = + exportsInfo.otherExportsInfo.getUsed(chunk.runtime) === + UsageState.Unused; + const instructions = []; + const handledNames = []; + for (const exportInfo of exportsInfo.orderedExports) { + const used = exportInfo.getUsedName( + undefined, + chunk.runtime + ); + if (used) { + if (otherUnused || used !== exportInfo.name) { + instructions.push( + `${external}${propertyAccess([ + used + ])} = module${propertyAccess([exportInfo.name])};` + ); + handledNames.push(exportInfo.name); + } + } else { + handledNames.push(exportInfo.name); + } } - ) - .split("/"); - const runtimeOutputName = compilation - .getPath( - getChunkFilenameTemplate( - runtimeChunk, - compilation.outputOptions - ), - { - chunk: runtimeChunk, - contentHashType: "javascript" + if (!otherUnused) { + if ( + !Array.isArray(module.request) || + module.request.length === 1 + ) { + externalVarInitialization.push( + `Object.defineProperty(${external}, "__esModule", { value: true });` + ); + } + if (handledNames.length > 0) { + const name = `${external}handledNames`; + externalVarInitialization.push( + `var ${name} = ${JSON.stringify(handledNames)};` + ); + instructions.push( + Template.asString([ + "Object.keys(module).forEach(function(key) {", + Template.indent([ + `if(${name}.indexOf(key) >= 0)`, + Template.indent(`${external}[key] = module[key];`) + ]), + "});" + ]) + ); + } else { + instructions.push( + Template.asString([ + "Object.keys(module).forEach(function(key) {", + Template.indent([`${external}[key] = module[key];`]), + "});" + ]) + ); + } } - ) - .split("/"); - - // remove filename, we only need the directory - currentOutputName.pop(); - - // remove common parts - while ( - currentOutputName.length > 0 && - runtimeOutputName.length > 0 && - currentOutputName[0] === runtimeOutputName[0] - ) { - currentOutputName.shift(); - runtimeOutputName.shift(); - } - - // create final path - const runtimePath = - (currentOutputName.length > 0 - ? "../".repeat(currentOutputName.length) - : "./") + runtimeOutputName.join("/"); + if (instructions.length === 0) return "function() {}"; + return Template.asString([ + "function(module) {", + Template.indent(instructions), + "}" + ]); + }) + .join(",\n") + ), + "]," + ]); - const entrySource = new ConcatSource(); - entrySource.add( - `(${ - runtimeTemplate.supportsArrowFunction() - ? "() => " - : "function() " - }{\n` - ); - entrySource.add("var exports = {};\n"); - entrySource.add(source); - entrySource.add(";\n\n// load runtime\n"); - entrySource.add( - `var __webpack_require__ = require(${JSON.stringify( - runtimePath - )});\n` - ); - entrySource.add( - `${RuntimeGlobals.externalInstallChunk}(exports);\n` - ); - const startupSource = new RawSource( - generateEntryStartup( - chunkGraph, - runtimeTemplate, - entries, - chunk, - false - ) - ); - entrySource.add( - hooks.renderStartup.call( - startupSource, - entries[entries.length - 1][0], - { - ...renderContext, - inlined: false - } - ) - ); - entrySource.add("\n})()"); - return entrySource; - } - return source; - } - ); - hooks.chunkHash.tap( - "CommonJsChunkFormatPlugin", - (chunk, hash, { chunkGraph }) => { - if (chunk.hasRuntime()) return; - hash.update("CommonJsChunkFormatPlugin"); - hash.update("1"); - const entries = Array.from( - chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk) - ); - updateHashForEntryStartup(hash, chunkGraph, entries, chunk); - } - ); - } + return new ConcatSource( + Template.asString([ + `System.register(${name}${systemDependencies}, function(${dynamicExport}, __system_context__) {`, + Template.indent([ + externalVarDeclarations, + Template.asString(externalVarInitialization), + "return {", + Template.indent([ + setters, + "execute: function() {", + Template.indent(`${dynamicExport}(`) + ]) + ]), + "" + ]), + source, + Template.asString([ + "", + Template.indent([ + Template.indent([Template.indent([");"]), "}"]), + "};" + ]), + "})" + ]) ); } + + /** + * @param {Chunk} chunk the chunk + * @param {Hash} hash hash + * @param {ChunkHashContext} chunkHashContext chunk hash context + * @param {LibraryContext} libraryContext context + * @returns {void} + */ + chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { + hash.update("SystemLibraryPlugin"); + if (options.name) { + hash.update(compilation.getPath(options.name, { chunk })); + } + } } -module.exports = CommonJsChunkFormatPlugin; +module.exports = SystemLibraryPlugin; /***/ }), -/***/ 61291: +/***/ 54442: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -96534,123 +96841,329 @@ module.exports = CommonJsChunkFormatPlugin; -/** @typedef {import("../../declarations/WebpackOptions").ChunkLoadingType} ChunkLoadingType */ +const { ConcatSource, OriginalSource } = __webpack_require__(51255); +const ExternalModule = __webpack_require__(73071); +const Template = __webpack_require__(1626); +const AbstractLibraryPlugin = __webpack_require__(26030); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryCustomUmdCommentObject} LibraryCustomUmdCommentObject */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ /** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ -/** @type {WeakMap>} */ -const enabledTypes = new WeakMap(); +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +}; -const getEnabledTypes = compiler => { - let set = enabledTypes.get(compiler); - if (set === undefined) { - set = new Set(); - enabledTypes.set(compiler, set); - } - return set; +/** + * @param {string|undefined} base the path prefix + * @param {string|string[]} accessor the accessor + * @param {string=} joinWith the element separator + * @returns {string} the path + */ +const accessorAccess = (base, accessor, joinWith = ", ") => { + const accessors = Array.isArray(accessor) ? accessor : [accessor]; + return accessors + .map((_, idx) => { + const a = base + ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) + : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); + if (idx === accessors.length - 1) return a; + if (idx === 0 && base === undefined) + return `${a} = typeof ${a} === "object" ? ${a} : {}`; + return `${a} = ${a} || {}`; + }) + .join(joinWith); }; -class EnableChunkLoadingPlugin { +/** @typedef {string | string[] | LibraryCustomUmdObject} UmdLibraryPluginName */ + +/** + * @typedef {Object} UmdLibraryPluginOptions + * @property {LibraryType} type + * @property {boolean=} optionalAmdExternalAsGlobal + */ + +/** + * @typedef {Object} UmdLibraryPluginParsed + * @property {string | string[]} name + * @property {LibraryCustomUmdObject} names + * @property {string | LibraryCustomUmdCommentObject} auxiliaryComment + * @property {boolean} namedDefine + */ + +/** + * @typedef {UmdLibraryPluginParsed} T + * @extends {AbstractLibraryPlugin} + */ +class UmdLibraryPlugin extends AbstractLibraryPlugin { /** - * @param {ChunkLoadingType} type library type that should be available + * @param {UmdLibraryPluginOptions} options the plugin option */ - constructor(type) { - this.type = type; + constructor(options) { + super({ + pluginName: "UmdLibraryPlugin", + type: options.type + }); + + this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal; } /** - * @param {Compiler} compiler the compiler instance - * @param {ChunkLoadingType} type type of library - * @returns {void} + * @param {LibraryOptions} library normalized library option + * @returns {T | false} preprocess as needed by overriding */ - static setEnabled(compiler, type) { - getEnabledTypes(compiler).add(type); + parseOptions(library) { + /** @type {LibraryName} */ + let name; + /** @type {LibraryCustomUmdObject} */ + let names; + if (typeof library.name === "object" && !Array.isArray(library.name)) { + name = library.name.root || library.name.amd || library.name.commonjs; + names = library.name; + } else { + name = library.name; + const singleName = Array.isArray(name) ? name[0] : name; + names = { + commonjs: singleName, + root: library.name, + amd: singleName + }; + } + return { + name, + names, + auxiliaryComment: library.auxiliaryComment, + namedDefine: library.umdNamedDefine + }; } /** - * @param {Compiler} compiler the compiler instance - * @param {ChunkLoadingType} type type of library - * @returns {void} + * @param {Source} source source + * @param {RenderContext} renderContext render context + * @param {LibraryContext} libraryContext context + * @returns {Source} source with library export */ - static checkEnabled(compiler, type) { - if (!getEnabledTypes(compiler).has(type)) { - throw new Error( - `Chunk loading type "${type}" is not enabled. ` + - "EnableChunkLoadingPlugin need to be used to enable this type of chunk loading. " + - 'This usually happens through the "output.enabledChunkLoadingTypes" option. ' + - 'If you are using a function as entry which sets "chunkLoading", you need to add all potential chunk loading types to "output.enabledChunkLoadingTypes". ' + - "These types are enabled: " + - Array.from(getEnabledTypes(compiler)).join(", ") + render( + source, + { chunkGraph, runtimeTemplate, chunk, moduleGraph }, + { options, compilation } + ) { + const modules = chunkGraph + .getChunkModules(chunk) + .filter( + m => + m instanceof ExternalModule && + (m.externalType === "umd" || m.externalType === "umd2") ); + let externals = /** @type {ExternalModule[]} */ (modules); + /** @type {ExternalModule[]} */ + const optionalExternals = []; + /** @type {ExternalModule[]} */ + let requiredExternals = []; + if (this.optionalAmdExternalAsGlobal) { + for (const m of externals) { + if (m.isOptional(moduleGraph)) { + optionalExternals.push(m); + } else { + requiredExternals.push(m); + } + } + externals = requiredExternals.concat(optionalExternals); + } else { + requiredExternals = externals; } - } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const { type } = this; + const replaceKeys = str => { + return compilation.getPath(str, { + chunk + }); + }; - // Only enable once - const enabled = getEnabledTypes(compiler); - if (enabled.has(type)) return; - enabled.add(type); + const externalsDepsArray = modules => { + return `[${replaceKeys( + modules + .map(m => + JSON.stringify( + typeof m.request === "object" ? m.request.amd : m.request + ) + ) + .join(", ") + )}]`; + }; - if (typeof type === "string") { - switch (type) { - case "jsonp": { - const JsonpChunkLoadingPlugin = __webpack_require__(83121); - new JsonpChunkLoadingPlugin().apply(compiler); - break; - } - case "import-scripts": { - const ImportScriptsChunkLoadingPlugin = __webpack_require__(54182); - new ImportScriptsChunkLoadingPlugin().apply(compiler); - break; - } - case "require": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const CommonJsChunkLoadingPlugin = __webpack_require__(1313); - new CommonJsChunkLoadingPlugin({ - asyncChunkLoading: false - }).apply(compiler); - break; - } - case "async-node": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const CommonJsChunkLoadingPlugin = __webpack_require__(1313); - new CommonJsChunkLoadingPlugin({ - asyncChunkLoading: true - }).apply(compiler); - break; - } - case "import": { - const ModuleChunkLoadingPlugin = __webpack_require__(89831); - new ModuleChunkLoadingPlugin().apply(compiler); - break; - } - case "universal": - // TODO implement universal chunk loading - throw new Error("Universal Chunk Loading is not implemented yet"); - default: - throw new Error(`Unsupported chunk loading type ${type}. -Plugins which provide custom chunk loading types must call EnableChunkLoadingPlugin.setEnabled(compiler, type) to disable this error.`); - } + const externalsRootArray = modules => { + return replaceKeys( + modules + .map(m => { + let request = m.request; + if (typeof request === "object") request = request.root; + return `root${accessorToObjectAccess([].concat(request))}`; + }) + .join(", ") + ); + }; + + const externalsRequireArray = type => { + return replaceKeys( + externals + .map(m => { + let expr; + let request = m.request; + if (typeof request === "object") { + request = request[type]; + } + if (request === undefined) { + throw new Error( + "Missing external configuration for type:" + type + ); + } + if (Array.isArray(request)) { + expr = `require(${JSON.stringify( + request[0] + )})${accessorToObjectAccess(request.slice(1))}`; + } else { + expr = `require(${JSON.stringify(request)})`; + } + if (m.isOptional(moduleGraph)) { + expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; + } + return expr; + }) + .join(", ") + ); + }; + + const externalsArguments = modules => { + return modules + .map( + m => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${chunkGraph.getModuleId(m)}` + )}__` + ) + .join(", "); + }; + + const libraryName = library => { + return JSON.stringify(replaceKeys([].concat(library).pop())); + }; + + let amdFactory; + if (optionalExternals.length > 0) { + const wrapperArguments = externalsArguments(requiredExternals); + const factoryArguments = + requiredExternals.length > 0 + ? externalsArguments(requiredExternals) + + ", " + + externalsRootArray(optionalExternals) + : externalsRootArray(optionalExternals); + amdFactory = + `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` + + ` return factory(${factoryArguments});\n` + + " }"; } else { - // TODO support plugin instances here - // apply them to the compiler + amdFactory = "factory"; } + + const { auxiliaryComment, namedDefine, names } = options; + + const getAuxiliaryComment = type => { + if (auxiliaryComment) { + if (typeof auxiliaryComment === "string") + return "\t//" + auxiliaryComment + "\n"; + if (auxiliaryComment[type]) + return "\t//" + auxiliaryComment[type] + "\n"; + } + return ""; + }; + + return new ConcatSource( + new OriginalSource( + "(function webpackUniversalModuleDefinition(root, factory) {\n" + + getAuxiliaryComment("commonjs2") + + " if(typeof exports === 'object' && typeof module === 'object')\n" + + " module.exports = factory(" + + externalsRequireArray("commonjs2") + + ");\n" + + getAuxiliaryComment("amd") + + " else if(typeof define === 'function' && define.amd)\n" + + (requiredExternals.length > 0 + ? names.amd && namedDefine === true + ? " define(" + + libraryName(names.amd) + + ", " + + externalsDepsArray(requiredExternals) + + ", " + + amdFactory + + ");\n" + : " define(" + + externalsDepsArray(requiredExternals) + + ", " + + amdFactory + + ");\n" + : names.amd && namedDefine === true + ? " define(" + + libraryName(names.amd) + + ", [], " + + amdFactory + + ");\n" + : " define([], " + amdFactory + ");\n") + + (names.root || names.commonjs + ? getAuxiliaryComment("commonjs") + + " else if(typeof exports === 'object')\n" + + " exports[" + + libraryName(names.commonjs || names.root) + + "] = factory(" + + externalsRequireArray("commonjs") + + ");\n" + + getAuxiliaryComment("root") + + " else\n" + + " " + + replaceKeys( + accessorAccess("root", names.root || names.commonjs) + ) + + " = factory(" + + externalsRootArray(externals) + + ");\n" + : " else {\n" + + (externals.length > 0 + ? " var a = typeof exports === 'object' ? factory(" + + externalsRequireArray("commonjs") + + ") : factory(" + + externalsRootArray(externals) + + ");\n" + : " var a = factory();\n") + + " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" + + " }\n") + + `})(${ + runtimeTemplate.outputOptions.globalObject + }, function(${externalsArguments(externals)}) {\nreturn `, + "webpack/universalModuleDefinition" + ), + source, + ";\n})" + ); } } -module.exports = EnableChunkLoadingPlugin; +module.exports = UmdLibraryPlugin; /***/ }), -/***/ 77106: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 32597: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -96660,229 +97173,167 @@ module.exports = EnableChunkLoadingPlugin; -const util = __webpack_require__(73837); -const { RawSource, ReplaceSource } = __webpack_require__(51255); -const Generator = __webpack_require__(93401); -const InitFragment = __webpack_require__(55870); -const HarmonyCompatibilityDependency = __webpack_require__(72906); +const LogType = Object.freeze({ + error: /** @type {"error"} */ ("error"), // message, c style arguments + warn: /** @type {"warn"} */ ("warn"), // message, c style arguments + info: /** @type {"info"} */ ("info"), // message, c style arguments + log: /** @type {"log"} */ ("log"), // message, c style arguments + debug: /** @type {"debug"} */ ("debug"), // message, c style arguments -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + trace: /** @type {"trace"} */ ("trace"), // no arguments -// TODO: clean up this file -// replace with newer constructs + group: /** @type {"group"} */ ("group"), // [label] + groupCollapsed: /** @type {"groupCollapsed"} */ ("groupCollapsed"), // [label] + groupEnd: /** @type {"groupEnd"} */ ("groupEnd"), // [label] -const deprecatedGetInitFragments = util.deprecate( - (template, dependency, templateContext) => - template.getInitFragments(dependency, templateContext), - "DependencyTemplate.getInitFragment is deprecated (use apply(dep, source, { initFragments }) instead)", - "DEP_WEBPACK_JAVASCRIPT_GENERATOR_GET_INIT_FRAGMENTS" -); + profile: /** @type {"profile"} */ ("profile"), // [profileName] + profileEnd: /** @type {"profileEnd"} */ ("profileEnd"), // [profileName] -const TYPES = new Set(["javascript"]); + time: /** @type {"time"} */ ("time"), // name, time as [seconds, nanoseconds] -class JavascriptGenerator extends Generator { + clear: /** @type {"clear"} */ ("clear"), // no arguments + status: /** @type {"status"} */ ("status") // message, arguments +}); + +exports.LogType = LogType; + +/** @typedef {typeof LogType[keyof typeof LogType]} LogTypeEnum */ + +const LOG_SYMBOL = Symbol("webpack logger raw log method"); +const TIMERS_SYMBOL = Symbol("webpack logger times"); +const TIMERS_AGGREGATES_SYMBOL = Symbol("webpack logger aggregated times"); + +class WebpackLogger { /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) + * @param {function(LogTypeEnum, any[]=): void} log log function + * @param {function(string | function(): string): WebpackLogger} getChildLogger function to create child logger */ - getTypes(module) { - return TYPES; + constructor(log, getChildLogger) { + this[LOG_SYMBOL] = log; + this.getChildLogger = getChildLogger; } - /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module - */ - getSize(module, type) { - const originalSource = module.originalSource(); - if (!originalSource) { - return 39; - } - return originalSource.size(); + error(...args) { + this[LOG_SYMBOL](LogType.error, args); } - /** - * @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) { - // Only harmony modules are valid for optimization - if ( - !module.buildMeta || - module.buildMeta.exportsType !== "namespace" || - module.presentationalDependencies === undefined || - !module.presentationalDependencies.some( - d => d instanceof HarmonyCompatibilityDependency - ) - ) { - return "Module is not an ECMAScript module"; - } + warn(...args) { + this[LOG_SYMBOL](LogType.warn, args); + } - // Some expressions are not compatible with module concatenation - // because they may produce unexpected results. The plugin bails out - // if some were detected upfront. - if (module.buildInfo && module.buildInfo.moduleConcatenationBailout) { - return `Module uses ${module.buildInfo.moduleConcatenationBailout}`; - } + info(...args) { + this[LOG_SYMBOL](LogType.info, args); } - /** - * @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 originalSource = module.originalSource(); - if (!originalSource) { - return new RawSource("throw new Error('No source available');"); + log(...args) { + this[LOG_SYMBOL](LogType.log, args); + } + + debug(...args) { + this[LOG_SYMBOL](LogType.debug, args); + } + + assert(assertion, ...args) { + if (!assertion) { + this[LOG_SYMBOL](LogType.error, args); } + } - const source = new ReplaceSource(originalSource); - const initFragments = []; + trace() { + this[LOG_SYMBOL](LogType.trace, ["Trace"]); + } - this.sourceModule(module, initFragments, source, generateContext); + clear() { + this[LOG_SYMBOL](LogType.clear); + } - return InitFragment.addToSource(source, initFragments, generateContext); + status(...args) { + this[LOG_SYMBOL](LogType.status, args); } - /** - * @param {Module} module the module to generate - * @param {InitFragment[]} initFragments mutable list of init fragments - * @param {ReplaceSource} source the current replace source which can be modified - * @param {GenerateContext} generateContext the generateContext - * @returns {void} - */ - sourceModule(module, initFragments, source, generateContext) { - for (const dependency of module.dependencies) { - this.sourceDependency( - module, - dependency, - initFragments, - source, - generateContext - ); - } + group(...args) { + this[LOG_SYMBOL](LogType.group, args); + } - if (module.presentationalDependencies !== undefined) { - for (const dependency of module.presentationalDependencies) { - this.sourceDependency( - module, - dependency, - initFragments, - source, - generateContext - ); - } - } + groupCollapsed(...args) { + this[LOG_SYMBOL](LogType.groupCollapsed, args); + } - for (const childBlock of module.blocks) { - this.sourceBlock( - module, - childBlock, - initFragments, - source, - generateContext - ); - } + groupEnd(...args) { + this[LOG_SYMBOL](LogType.groupEnd, args); } - /** - * @param {Module} module the module to generate - * @param {DependenciesBlock} block the dependencies block which will be processed - * @param {InitFragment[]} initFragments mutable list of init fragments - * @param {ReplaceSource} source the current replace source which can be modified - * @param {GenerateContext} generateContext the generateContext - * @returns {void} - */ - sourceBlock(module, block, initFragments, source, generateContext) { - for (const dependency of block.dependencies) { - this.sourceDependency( - module, - dependency, - initFragments, - source, - generateContext - ); + profile(label) { + this[LOG_SYMBOL](LogType.profile, [label]); + } + + profileEnd(label) { + this[LOG_SYMBOL](LogType.profileEnd, [label]); + } + + time(label) { + this[TIMERS_SYMBOL] = this[TIMERS_SYMBOL] || new Map(); + this[TIMERS_SYMBOL].set(label, process.hrtime()); + } + + timeLog(label) { + const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); + if (!prev) { + throw new Error(`No such label '${label}' for WebpackLogger.timeLog()`); } + const time = process.hrtime(prev); + this[LOG_SYMBOL](LogType.time, [label, ...time]); + } - for (const childBlock of block.blocks) { - this.sourceBlock( - module, - childBlock, - initFragments, - source, - generateContext - ); + timeEnd(label) { + const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); + if (!prev) { + throw new Error(`No such label '${label}' for WebpackLogger.timeEnd()`); } + const time = process.hrtime(prev); + this[TIMERS_SYMBOL].delete(label); + this[LOG_SYMBOL](LogType.time, [label, ...time]); } - /** - * @param {Module} module the current module - * @param {Dependency} dependency the dependency to generate - * @param {InitFragment[]} initFragments mutable list of init fragments - * @param {ReplaceSource} source the current replace source which can be modified - * @param {GenerateContext} generateContext the render context - * @returns {void} - */ - sourceDependency(module, dependency, initFragments, source, generateContext) { - const constructor = /** @type {new (...args: any[]) => Dependency} */ ( - dependency.constructor - ); - const template = generateContext.dependencyTemplates.get(constructor); - if (!template) { + timeAggregate(label) { + const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); + if (!prev) { throw new Error( - "No template for dependency: " + dependency.constructor.name + `No such label '${label}' for WebpackLogger.timeAggregate()` ); } - - const templateContext = { - runtimeTemplate: generateContext.runtimeTemplate, - dependencyTemplates: generateContext.dependencyTemplates, - moduleGraph: generateContext.moduleGraph, - chunkGraph: generateContext.chunkGraph, - module, - runtime: generateContext.runtime, - runtimeRequirements: generateContext.runtimeRequirements, - concatenationScope: generateContext.concatenationScope, - codeGenerationResults: generateContext.codeGenerationResults, - initFragments - }; - - template.apply(dependency, source, templateContext); - - // TODO remove in webpack 6 - if ("getInitFragments" in template) { - const fragments = deprecatedGetInitFragments( - template, - dependency, - templateContext - ); - - if (fragments) { - for (const fragment of fragments) { - initFragments.push(fragment); - } + const time = process.hrtime(prev); + this[TIMERS_SYMBOL].delete(label); + this[TIMERS_AGGREGATES_SYMBOL] = + this[TIMERS_AGGREGATES_SYMBOL] || new Map(); + const current = this[TIMERS_AGGREGATES_SYMBOL].get(label); + if (current !== undefined) { + if (time[1] + current[1] > 1e9) { + time[0] += current[0] + 1; + time[1] = time[1] - 1e9 + current[1]; + } else { + time[0] += current[0]; + time[1] += current[1]; } } + this[TIMERS_AGGREGATES_SYMBOL].set(label, time); + } + + timeAggregateEnd(label) { + if (this[TIMERS_AGGREGATES_SYMBOL] === undefined) return; + const time = this[TIMERS_AGGREGATES_SYMBOL].get(label); + if (time === undefined) return; + this[TIMERS_AGGREGATES_SYMBOL].delete(label); + this[LOG_SYMBOL](LogType.time, [label, ...time]); } } -module.exports = JavascriptGenerator; +exports.Logger = WebpackLogger; /***/ }), -/***/ 89464: +/***/ 54963: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -96893,186 +97344,341 @@ module.exports = JavascriptGenerator; -const { SyncWaterfallHook, SyncHook, SyncBailHook } = __webpack_require__(41242); -const vm = __webpack_require__(26144); -const { - ConcatSource, - OriginalSource, - PrefixSource, - RawSource, - CachedSource -} = __webpack_require__(51255); -const Compilation = __webpack_require__(85720); -const { tryRunOrWebpackError } = __webpack_require__(11351); -const HotUpdateChunk = __webpack_require__(9597); -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const { last, someInIterable } = __webpack_require__(39104); -const StringXor = __webpack_require__(40293); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const createHash = __webpack_require__(49835); -const { intersectRuntime } = __webpack_require__(17156); -const JavascriptGenerator = __webpack_require__(77106); -const JavascriptParser = __webpack_require__(29050); +const { LogType } = __webpack_require__(32597); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */ +/** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */ +/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ + +/** @typedef {function(string): boolean} FilterFunction */ /** - * @param {Chunk} chunk a chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {boolean} true, when a JS file is needed for this chunk + * @typedef {Object} LoggerConsole + * @property {function(): void} clear + * @property {function(): void} trace + * @property {(...args: any[]) => void} info + * @property {(...args: any[]) => void} log + * @property {(...args: any[]) => void} warn + * @property {(...args: any[]) => void} error + * @property {(...args: any[]) => void=} debug + * @property {(...args: any[]) => void=} group + * @property {(...args: any[]) => void=} groupCollapsed + * @property {(...args: any[]) => void=} groupEnd + * @property {(...args: any[]) => void=} status + * @property {(...args: any[]) => void=} profile + * @property {(...args: any[]) => void=} profileEnd + * @property {(...args: any[]) => void=} logTime */ -const chunkHasJs = (chunk, chunkGraph) => { - if (chunkGraph.getNumberOfEntryModules(chunk) > 0) return true; - - return chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript") - ? true - : false; -}; - -const printGeneratedCodeForStack = (module, code) => { - const lines = code.split("\n"); - const n = `${lines.length}`.length; - return `\n\nGenerated code for ${module.identifier()}\n${lines - .map((line, i, lines) => { - const iStr = `${i + 1}`; - return `${" ".repeat(n - iStr.length)}${iStr} | ${line}`; - }) - .join("\n")}`; -}; /** - * @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 - * @property {CodeGenerationResults} codeGenerationResults results of code generation - * @property {boolean} strictMode rendering in strict context + * @typedef {Object} LoggerOptions + * @property {false|true|"none"|"error"|"warn"|"info"|"log"|"verbose"} level loglevel + * @property {FilterTypes|boolean} debug filter for debug logging + * @property {LoggerConsole} console the console to log to */ /** - * @typedef {Object} MainRenderContext - * @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 - * @property {CodeGenerationResults} codeGenerationResults results of code generation - * @property {string} hash hash to be used for render call - * @property {boolean} strictMode rendering in strict context + * @param {FilterItemTypes} item an input item + * @returns {FilterFunction} filter function */ +const filterToFunction = item => { + if (typeof item === "string") { + const regExp = new RegExp( + `[\\\\/]${item.replace( + // eslint-disable-next-line no-useless-escape + /[-[\]{}()*+?.\\^$|]/g, + "\\$&" + )}([\\\\/]|$|!|\\?)` + ); + return ident => regExp.test(ident); + } + if (item && typeof item === "object" && typeof item.test === "function") { + return ident => item.test(ident); + } + if (typeof item === "function") { + return item; + } + if (typeof item === "boolean") { + return () => item; + } +}; /** - * @typedef {Object} ChunkRenderContext - * @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 - * @property {CodeGenerationResults} codeGenerationResults results of code generation - * @property {InitFragment[]} chunkInitFragments init fragments for the chunk - * @property {boolean} strictMode rendering in strict context + * @enum {number} */ +const LogLevel = { + none: 6, + false: 6, + error: 5, + warn: 4, + info: 3, + log: 2, + true: 2, + verbose: 1 +}; /** - * @typedef {Object} RenderBootstrapContext - * @property {Chunk} chunk the chunk - * @property {RuntimeTemplate} runtimeTemplate the runtime template - * @property {ModuleGraph} moduleGraph the module graph - * @property {ChunkGraph} chunkGraph the chunk graph - * @property {string} hash hash to be used for render call + * @param {LoggerOptions} options options object + * @returns {function(string, LogTypeEnum, any[]): void} logging function */ +module.exports = ({ level = "info", debug = false, console }) => { + const debugFilters = + typeof debug === "boolean" + ? [() => debug] + : /** @type {FilterItemTypes[]} */ ([]) + .concat(debug) + .map(filterToFunction); + /** @type {number} */ + const loglevel = LogLevel[`${level}`] || 0; -/** @typedef {RenderContext & { inlined: boolean }} StartupRenderContext */ + /** + * @param {string} name name of the logger + * @param {LogTypeEnum} type type of the log entry + * @param {any[]} args arguments of the log entry + * @returns {void} + */ + const logger = (name, type, args) => { + const labeledArgs = () => { + if (Array.isArray(args)) { + if (args.length > 0 && typeof args[0] === "string") { + return [`[${name}] ${args[0]}`, ...args.slice(1)]; + } else { + return [`[${name}]`, ...args]; + } + } else { + return []; + } + }; + const debug = debugFilters.some(f => f(name)); + switch (type) { + case LogType.debug: + if (!debug) return; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.debug === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.debug(...labeledArgs()); + } else { + console.log(...labeledArgs()); + } + break; + case LogType.log: + if (!debug && loglevel > LogLevel.log) return; + console.log(...labeledArgs()); + break; + case LogType.info: + if (!debug && loglevel > LogLevel.info) return; + console.info(...labeledArgs()); + break; + case LogType.warn: + if (!debug && loglevel > LogLevel.warn) return; + console.warn(...labeledArgs()); + break; + case LogType.error: + if (!debug && loglevel > LogLevel.error) return; + console.error(...labeledArgs()); + break; + case LogType.trace: + if (!debug) return; + console.trace(); + break; + case LogType.groupCollapsed: + if (!debug && loglevel > LogLevel.log) return; + if (!debug && loglevel > LogLevel.verbose) { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.groupCollapsed === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.groupCollapsed(...labeledArgs()); + } else { + console.log(...labeledArgs()); + } + break; + } + // falls through + case LogType.group: + if (!debug && loglevel > LogLevel.log) return; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.group === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.group(...labeledArgs()); + } else { + console.log(...labeledArgs()); + } + break; + case LogType.groupEnd: + if (!debug && loglevel > LogLevel.log) return; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.groupEnd === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.groupEnd(); + } + break; + case LogType.time: { + if (!debug && loglevel > LogLevel.log) return; + const ms = args[1] * 1000 + args[2] / 1000000; + const msg = `[${name}] ${args[0]}: ${ms} ms`; + if (typeof console.logTime === "function") { + console.logTime(msg); + } else { + console.log(msg); + } + break; + } + case LogType.profile: + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.profile === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.profile(...labeledArgs()); + } + break; + case LogType.profileEnd: + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.profileEnd === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.profileEnd(...labeledArgs()); + } + break; + case LogType.clear: + if (!debug && loglevel > LogLevel.log) return; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.clear === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.clear(); + } + break; + case LogType.status: + if (!debug && loglevel > LogLevel.info) return; + if (typeof console.status === "function") { + if (args.length === 0) { + console.status(); + } else { + console.status(...labeledArgs()); + } + } else { + if (args.length !== 0) { + console.info(...labeledArgs()); + } + } + break; + default: + throw new Error(`Unexpected LogType ${type}`); + } + }; + return logger; +}; + + +/***/ }), + +/***/ 62090: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const arraySum = array => { + let sum = 0; + for (const item of array) sum += item; + return sum; +}; /** - * @typedef {Object} CompilationHooks - * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModuleContent - * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModuleContainer - * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModulePackage - * @property {SyncWaterfallHook<[Source, RenderContext]>} renderChunk - * @property {SyncWaterfallHook<[Source, RenderContext]>} renderMain - * @property {SyncWaterfallHook<[Source, RenderContext]>} renderContent - * @property {SyncWaterfallHook<[Source, RenderContext]>} render - * @property {SyncWaterfallHook<[Source, Module, StartupRenderContext]>} renderStartup - * @property {SyncWaterfallHook<[string, RenderBootstrapContext]>} renderRequire - * @property {SyncBailHook<[Module, RenderBootstrapContext], string>} inlineInRuntimeBailout - * @property {SyncBailHook<[Module, RenderContext], string>} embedInRuntimeBailout - * @property {SyncBailHook<[RenderContext], string>} strictRuntimeBailout - * @property {SyncHook<[Chunk, Hash, ChunkHashContext]>} chunkHash - * @property {SyncBailHook<[Chunk, RenderContext], boolean>} useSourceMap + * @param {any[]} args items to be truncated + * @param {number} maxLength maximum length of args including spaces between + * @returns {string[]} truncated args */ +const truncateArgs = (args, maxLength) => { + const lengths = args.map(a => `${a}`.length); + const availableLength = maxLength - lengths.length + 1; -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); - -class JavascriptModulesPlugin { - /** - * @param {Compilation} compilation the compilation - * @returns {CompilationHooks} the attached hooks - */ - static getCompilationHooks(compilation) { - if (!(compilation instanceof Compilation)) { - throw new TypeError( - "The 'compilation' argument must be an instance of Compilation" - ); + if (availableLength > 0 && args.length === 1) { + if (availableLength >= args[0].length) { + return args; + } else if (availableLength > 3) { + return ["..." + args[0].slice(-availableLength + 3)]; + } else { + return [args[0].slice(-availableLength)]; } - let hooks = compilationHooksMap.get(compilation); - if (hooks === undefined) { - hooks = { - renderModuleContent: new SyncWaterfallHook([ - "source", - "module", - "renderContext" - ]), - renderModuleContainer: new SyncWaterfallHook([ - "source", - "module", - "renderContext" - ]), - renderModulePackage: new SyncWaterfallHook([ - "source", - "module", - "renderContext" - ]), - render: new SyncWaterfallHook(["source", "renderContext"]), - renderContent: new SyncWaterfallHook(["source", "renderContext"]), - renderStartup: new SyncWaterfallHook([ - "source", - "module", - "startupRenderContext" - ]), - renderChunk: new SyncWaterfallHook(["source", "renderContext"]), - renderMain: new SyncWaterfallHook(["source", "renderContext"]), - renderRequire: new SyncWaterfallHook(["code", "renderContext"]), - inlineInRuntimeBailout: new SyncBailHook(["module", "renderContext"]), - embedInRuntimeBailout: new SyncBailHook(["module", "renderContext"]), - strictRuntimeBailout: new SyncBailHook(["renderContext"]), - chunkHash: new SyncHook(["chunk", "hash", "context"]), - useSourceMap: new SyncBailHook(["chunk", "renderContext"]) - }; - compilationHooksMap.set(compilation, hooks); + } + + // Check if there is space for at least 4 chars per arg + if (availableLength < arraySum(lengths.map(i => Math.min(i, 6)))) { + // remove args + if (args.length > 1) + return truncateArgs(args.slice(0, args.length - 1), maxLength); + return []; + } + + let currentLength = arraySum(lengths); + + // Check if all fits into maxLength + if (currentLength <= availableLength) return args; + + // Try to remove chars from the longest items until it fits + while (currentLength > availableLength) { + const maxLength = Math.max(...lengths); + const shorterItems = lengths.filter(l => l !== maxLength); + const nextToMaxLength = + shorterItems.length > 0 ? Math.max(...shorterItems) : 0; + const maxReduce = maxLength - nextToMaxLength; + let maxItems = lengths.length - shorterItems.length; + let overrun = currentLength - availableLength; + for (let i = 0; i < lengths.length; i++) { + if (lengths[i] === maxLength) { + const reduce = Math.min(Math.floor(overrun / maxItems), maxReduce); + lengths[i] -= reduce; + currentLength -= reduce; + overrun -= reduce; + maxItems--; + } } - return hooks; } - constructor(options = {}) { - this.options = options; - /** @type {WeakMap} */ - this._moduleFactoryCache = new WeakMap(); + // Return args reduced to length in lengths + return args.map((a, i) => { + const str = `${a}`; + const length = lengths[i]; + if (str.length === length) { + return str; + } else if (length > 5) { + return "..." + str.slice(-length + 3); + } else if (length > 0) { + return str.slice(-length); + } else { + return ""; + } + }); +}; + +module.exports = truncateArgs; + + +/***/ }), + +/***/ 1313: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const StartupChunkDependenciesPlugin = __webpack_require__(22339); + +/** @typedef {import("../Compiler")} Compiler */ + +class CommonJsChunkLoadingPlugin { + constructor(options) { + options = options || {}; + this._asyncChunkLoading = options.asyncChunkLoading; } /** @@ -97081,1161 +97687,802 @@ class JavascriptModulesPlugin { * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap( - "JavascriptModulesPlugin", - (compilation, { normalModuleFactory }) => { - const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); - normalModuleFactory.hooks.createParser - .for("javascript/auto") - .tap("JavascriptModulesPlugin", options => { - return new JavascriptParser("auto"); - }); - normalModuleFactory.hooks.createParser - .for("javascript/dynamic") - .tap("JavascriptModulesPlugin", options => { - return new JavascriptParser("script"); + const ChunkLoadingRuntimeModule = this._asyncChunkLoading + ? __webpack_require__(73369) + : __webpack_require__(94172); + const chunkLoadingValue = this._asyncChunkLoading + ? "async-node" + : "require"; + new StartupChunkDependenciesPlugin({ + chunkLoading: chunkLoadingValue, + asyncChunkLoading: this._asyncChunkLoading + }).apply(compiler); + compiler.hooks.thisCompilation.tap( + "CommonJsChunkLoadingPlugin", + compilation => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === chunkLoadingValue; + }; + const onceForChunkSet = new WeakSet(); + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new ChunkLoadingRuntimeModule(set) + ); + }; + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("CommonJsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap("CommonJsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap("CommonJsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap("CommonJsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.externalInstallChunk) + .tap("CommonJsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap("CommonJsChunkLoadingPlugin", handler); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.getChunkScriptFilename); }); - normalModuleFactory.hooks.createParser - .for("javascript/esm") - .tap("JavascriptModulesPlugin", options => { - return new JavascriptParser("module"); - }); - normalModuleFactory.hooks.createGenerator - .for("javascript/auto") - .tap("JavascriptModulesPlugin", () => { - return new JavascriptGenerator(); - }); - normalModuleFactory.hooks.createGenerator - .for("javascript/dynamic") - .tap("JavascriptModulesPlugin", () => { - return new JavascriptGenerator(); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.getChunkUpdateScriptFilename); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.hmrModuleData); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); }); - normalModuleFactory.hooks.createGenerator - .for("javascript/esm") - .tap("JavascriptModulesPlugin", () => { - return new JavascriptGenerator(); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.getUpdateManifestFilename); }); - compilation.hooks.renderManifest.tap( - "JavascriptModulesPlugin", - (result, options) => { - const { - hash, - chunk, - chunkGraph, - moduleGraph, - runtimeTemplate, - dependencyTemplates, - outputOptions, - codeGenerationResults - } = options; + } + ); + } +} - const hotUpdateChunk = - chunk instanceof HotUpdateChunk ? chunk : null; +module.exports = CommonJsChunkLoadingPlugin; - let render; - const filenameTemplate = - JavascriptModulesPlugin.getChunkFilenameTemplate( - chunk, - outputOptions - ); - if (hotUpdateChunk) { - render = () => - this.renderChunk( - { - chunk, - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - codeGenerationResults, - strictMode: runtimeTemplate.isModule() - }, - hooks - ); - } else if (chunk.hasRuntime()) { - render = () => - this.renderMain( - { - hash, - chunk, - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - codeGenerationResults, - strictMode: runtimeTemplate.isModule() - }, - hooks, - compilation - ); - } else { - if (!chunkHasJs(chunk, chunkGraph)) { - return result; - } - render = () => - this.renderChunk( - { - chunk, - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - codeGenerationResults, - strictMode: runtimeTemplate.isModule() - }, - hooks - ); - } +/***/ }), - result.push({ - render, - filenameTemplate, - pathOptions: { - hash, - runtime: chunk.runtime, - chunk, - contentHashType: "javascript" - }, - info: { - javascriptModule: compilation.runtimeTemplate.isModule() - }, - identifier: hotUpdateChunk - ? `hotupdatechunk${chunk.id}` - : `chunk${chunk.id}`, - hash: chunk.contentHash.javascript - }); +/***/ 7553: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return result; - } - ); - compilation.hooks.chunkHash.tap( - "JavascriptModulesPlugin", - (chunk, hash, context) => { - hooks.chunkHash.call(chunk, hash, context); - if (chunk.hasRuntime()) { - this.updateHashWithBootstrap( - hash, - { - hash: "0000", - chunk, - chunkGraph: context.chunkGraph, - moduleGraph: context.moduleGraph, - runtimeTemplate: context.runtimeTemplate - }, - hooks - ); - } - } - ); - compilation.hooks.contentHash.tap("JavascriptModulesPlugin", chunk => { - const { - chunkGraph, - moduleGraph, - runtimeTemplate, - outputOptions: { - hashSalt, - hashDigest, - hashDigestLength, - hashFunction - } - } = compilation; - const hash = createHash(hashFunction); - if (hashSalt) hash.update(hashSalt); - if (chunk.hasRuntime()) { - this.updateHashWithBootstrap( - hash, - { - hash: "0000", - chunk, - chunkGraph: compilation.chunkGraph, - moduleGraph: compilation.moduleGraph, - runtimeTemplate: compilation.runtimeTemplate - }, - hooks - ); - } else { - hash.update(`${chunk.id} `); - hash.update(chunk.ids ? chunk.ids.join(",") : ""); - } - hooks.chunkHash.call(chunk, hash, { - chunkGraph, - moduleGraph, - runtimeTemplate - }); - const modules = chunkGraph.getChunkModulesIterableBySourceType( - chunk, - "javascript" - ); - if (modules) { - const xor = new StringXor(); - for (const m of modules) { - xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); - } - xor.updateHash(hash); - } - const runtimeModules = chunkGraph.getChunkModulesIterableBySourceType( - chunk, - "runtime" - ); - if (runtimeModules) { - const xor = new StringXor(); - for (const m of runtimeModules) { - xor.add(chunkGraph.getModuleHash(m, chunk.runtime)); - } - xor.updateHash(hash); - } - const digest = /** @type {string} */ (hash.digest(hashDigest)); - chunk.contentHash.javascript = digest.substr(0, hashDigestLength); - }); - compilation.hooks.additionalTreeRuntimeRequirements.tap( - "JavascriptModulesPlugin", - (chunk, set, { chunkGraph }) => { - if ( - !set.has(RuntimeGlobals.startupNoDefault) && - chunkGraph.hasChunkEntryDependentChunks(chunk) - ) { - set.add(RuntimeGlobals.onChunksLoaded); - set.add(RuntimeGlobals.require); - } - } - ); - compilation.hooks.executeModule.tap( - "JavascriptModulesPlugin", - (options, context) => { - const source = - options.codeGenerationResult.sources.get("javascript"); - if (source === undefined) return; - const { module, moduleObject } = options; - const code = source.source(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const fn = vm.runInThisContext( - `(function(${module.moduleArgument}, ${module.exportsArgument}, __webpack_require__) {\n${code}\n/**/})`, - { - filename: module.identifier(), - lineOffset: -1 - } - ); - try { - fn.call( - moduleObject.exports, - moduleObject, - moduleObject.exports, - context.__webpack_require__ - ); - } catch (e) { - e.stack += printGeneratedCodeForStack(options.module, code); - throw e; - } - } - ); - compilation.hooks.executeModule.tap( - "JavascriptModulesPlugin", - (options, context) => { - const source = options.codeGenerationResult.sources.get("runtime"); - if (source === undefined) return; - let code = source.source(); - if (typeof code !== "string") code = code.toString(); - const fn = vm.runInThisContext( - `(function(__webpack_require__) {\n${code}\n/**/})`, - { - filename: options.module.identifier(), - lineOffset: -1 - } - ); - try { - fn.call(null, context.__webpack_require__); - } catch (e) { - e.stack += printGeneratedCodeForStack(options.module, code); - throw e; - } - } - ); - } - ); - } - static getChunkFilenameTemplate(chunk, outputOptions) { - if (chunk.filenameTemplate) { - return chunk.filenameTemplate; - } else if (chunk instanceof HotUpdateChunk) { - return outputOptions.hotUpdateChunkFilename; - } else if (chunk.canBeInitial()) { - return outputOptions.filename; - } else { - return outputOptions.chunkFilename; - } - } +const CachedInputFileSystem = __webpack_require__(52788); +const fs = __webpack_require__(90552); +const createConsoleLogger = __webpack_require__(54963); +const NodeWatchFileSystem = __webpack_require__(98810); +const nodeConsole = __webpack_require__(91786); + +/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */ +/** @typedef {import("../Compiler")} Compiler */ +class NodeEnvironmentPlugin { /** - * @param {Module} module the rendered module - * @param {ChunkRenderContext} renderContext options object - * @param {CompilationHooks} hooks hooks - * @param {boolean} factory true: renders as factory method, false: pure module content - * @returns {Source} the newly generated source from rendering + * @param {Object} options options + * @param {InfrastructureLogging} options.infrastructureLogging infrastructure logging options */ - renderModule(module, renderContext, hooks, factory) { - const { - chunk, - chunkGraph, - runtimeTemplate, - codeGenerationResults, - strictMode - } = renderContext; - try { - const codeGenResult = codeGenerationResults.get(module, chunk.runtime); - const moduleSource = codeGenResult.sources.get("javascript"); - if (!moduleSource) return null; - if (codeGenResult.data !== undefined) { - const chunkInitFragments = codeGenResult.data.get("chunkInitFragments"); - if (chunkInitFragments) { - for (const i of chunkInitFragments) - renderContext.chunkInitFragments.push(i); - } - } - const moduleSourcePostContent = tryRunOrWebpackError( - () => - hooks.renderModuleContent.call(moduleSource, module, renderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderModuleContent" - ); - let moduleSourcePostContainer; - if (factory) { - const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( - module, - chunk.runtime - ); - const needModule = runtimeRequirements.has(RuntimeGlobals.module); - const needExports = runtimeRequirements.has(RuntimeGlobals.exports); - const needRequire = - runtimeRequirements.has(RuntimeGlobals.require) || - runtimeRequirements.has(RuntimeGlobals.requireScope); - const needThisAsExports = runtimeRequirements.has( - RuntimeGlobals.thisAsExports - ); - const needStrict = module.buildInfo.strict && !strictMode; - const cacheEntry = this._moduleFactoryCache.get( - moduleSourcePostContent - ); - let source; - if ( - cacheEntry && - cacheEntry.needModule === needModule && - cacheEntry.needExports === needExports && - cacheEntry.needRequire === needRequire && - cacheEntry.needThisAsExports === needThisAsExports && - cacheEntry.needStrict === needStrict - ) { - source = cacheEntry.source; - } else { - const factorySource = new ConcatSource(); - const args = []; - if (needExports || needRequire || needModule) - args.push( - needModule - ? module.moduleArgument - : "__unused_webpack_" + module.moduleArgument - ); - if (needExports || needRequire) - args.push( - needExports - ? module.exportsArgument - : "__unused_webpack_" + module.exportsArgument - ); - if (needRequire) args.push("__webpack_require__"); - if (!needThisAsExports && runtimeTemplate.supportsArrowFunction()) { - factorySource.add("/***/ ((" + args.join(", ") + ") => {\n\n"); - } else { - factorySource.add("/***/ (function(" + args.join(", ") + ") {\n\n"); - } - if (needStrict) { - factorySource.add('"use strict";\n'); - } - factorySource.add(moduleSourcePostContent); - factorySource.add("\n\n/***/ })"); - source = new CachedSource(factorySource); - this._moduleFactoryCache.set(moduleSourcePostContent, { - source, - needModule, - needExports, - needRequire, - needThisAsExports, - needStrict - }); - } - moduleSourcePostContainer = tryRunOrWebpackError( - () => hooks.renderModuleContainer.call(source, module, renderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderModuleContainer" - ); - } else { - moduleSourcePostContainer = moduleSourcePostContent; - } - return tryRunOrWebpackError( - () => - hooks.renderModulePackage.call( - moduleSourcePostContainer, - module, - renderContext - ), - "JavascriptModulesPlugin.getCompilationHooks().renderModulePackage" - ); - } catch (e) { - e.module = module; - throw e; - } + constructor(options) { + this.options = options; } /** - * @param {RenderContext} renderContext the render context - * @param {CompilationHooks} hooks hooks - * @returns {Source} the rendered source + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - renderChunk(renderContext, hooks) { - const { chunk, chunkGraph } = renderContext; - const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( - chunk, - "javascript", - compareModulesByIdentifier - ); - const allModules = modules ? Array.from(modules) : []; - let strictHeader; - let allStrict = renderContext.strictMode; - if (!allStrict && allModules.every(m => m.buildInfo.strict)) { - const strictBailout = hooks.strictRuntimeBailout.call(renderContext); - strictHeader = strictBailout - ? `// runtime can't be in strict mode because ${strictBailout}.\n` - : '"use strict";\n'; - if (!strictBailout) allStrict = true; - } - /** @type {ChunkRenderContext} */ - const chunkRenderContext = { - ...renderContext, - chunkInitFragments: [], - strictMode: allStrict - }; - const moduleSources = - Template.renderChunkModules(chunkRenderContext, allModules, module => - this.renderModule(module, chunkRenderContext, hooks, true) - ) || new RawSource("{}"); - let source = tryRunOrWebpackError( - () => hooks.renderChunk.call(moduleSources, chunkRenderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderChunk" - ); - source = tryRunOrWebpackError( - () => hooks.renderContent.call(source, chunkRenderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderContent" - ); - if (!source) { - throw new Error( - "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something" - ); - } - source = InitFragment.addToSource( - source, - chunkRenderContext.chunkInitFragments, - chunkRenderContext - ); - source = tryRunOrWebpackError( - () => hooks.render.call(source, chunkRenderContext), - "JavascriptModulesPlugin.getCompilationHooks().render" + apply(compiler) { + const { infrastructureLogging } = this.options; + compiler.infrastructureLogger = createConsoleLogger({ + level: infrastructureLogging.level || "info", + debug: infrastructureLogging.debug || false, + console: + infrastructureLogging.console || + nodeConsole({ + colors: infrastructureLogging.colors, + appendOnly: infrastructureLogging.appendOnly, + stream: infrastructureLogging.stream + }) + }); + compiler.inputFileSystem = new CachedInputFileSystem(fs, 60000); + const inputFileSystem = compiler.inputFileSystem; + compiler.outputFileSystem = fs; + compiler.intermediateFileSystem = fs; + compiler.watchFileSystem = new NodeWatchFileSystem( + compiler.inputFileSystem ); - if (!source) { - throw new Error( - "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something" - ); - } - chunk.rendered = true; - return strictHeader - ? new ConcatSource(strictHeader, source, ";") - : renderContext.runtimeTemplate.isModule() - ? source - : new ConcatSource(source, ";"); + compiler.hooks.beforeRun.tap("NodeEnvironmentPlugin", compiler => { + if (compiler.inputFileSystem === inputFileSystem) { + compiler.fsStartTime = Date.now(); + inputFileSystem.purge(); + } + }); } +} + +module.exports = NodeEnvironmentPlugin; + + +/***/ }), + +/***/ 7103: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +/** @typedef {import("../Compiler")} Compiler */ + +class NodeSourcePlugin { /** - * @param {MainRenderContext} renderContext options object - * @param {CompilationHooks} hooks hooks - * @param {Compilation} compilation the compilation - * @returns {Source} the newly generated source from rendering + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - renderMain(renderContext, hooks, compilation) { - const { chunk, chunkGraph, runtimeTemplate } = renderContext; + apply(compiler) {} +} - const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); - const iife = runtimeTemplate.isIIFE(); +module.exports = NodeSourcePlugin; - const bootstrap = this.renderBootstrap(renderContext, hooks); - const useSourceMap = hooks.useSourceMap.call(chunk, renderContext); - const allModules = Array.from( - chunkGraph.getOrderedChunkModulesIterableBySourceType( - chunk, - "javascript", - compareModulesByIdentifier - ) || [] - ); +/***/ }), - const hasEntryModules = chunkGraph.getNumberOfEntryModules(chunk) > 0; - let inlinedModules; - if (bootstrap.allowInlineStartup && hasEntryModules) { - inlinedModules = new Set(chunkGraph.getChunkEntryModulesIterable(chunk)); - } +/***/ 17916: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - let source = new ConcatSource(); - let prefix; - if (iife) { - if (runtimeTemplate.supportsArrowFunction()) { - source.add("/******/ (() => { // webpackBootstrap\n"); - } else { - source.add("/******/ (function() { // webpackBootstrap\n"); - } - prefix = "/******/ \t"; - } else { - prefix = "/******/ "; - } - let allStrict = renderContext.strictMode; - if (!allStrict && allModules.every(m => m.buildInfo.strict)) { - const strictBailout = hooks.strictRuntimeBailout.call(renderContext); - if (strictBailout) { - source.add( - prefix + - `// runtime can't be in strict mode because ${strictBailout}.\n` - ); - } else { - allStrict = true; - source.add(prefix + '"use strict";\n'); - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {ChunkRenderContext} */ - const chunkRenderContext = { - ...renderContext, - chunkInitFragments: [], - strictMode: allStrict - }; - const chunkModules = Template.renderChunkModules( - chunkRenderContext, - inlinedModules - ? allModules.filter(m => !inlinedModules.has(m)) - : allModules, - module => this.renderModule(module, chunkRenderContext, hooks, true), - prefix - ); - if ( - chunkModules || - runtimeRequirements.has(RuntimeGlobals.moduleFactories) || - runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) || - runtimeRequirements.has(RuntimeGlobals.require) - ) { - source.add(prefix + "var __webpack_modules__ = ("); - source.add(chunkModules || "{}"); - source.add(");\n"); - source.add( - "/************************************************************************/\n" - ); - } - if (bootstrap.header.length > 0) { - const header = Template.asString(bootstrap.header) + "\n"; - source.add( - new PrefixSource( - prefix, - useSourceMap - ? new OriginalSource(header, "webpack/bootstrap") - : new RawSource(header) - ) - ); - source.add( - "/************************************************************************/\n" - ); - } +const ExternalsPlugin = __webpack_require__(6652); - const runtimeModules = - renderContext.chunkGraph.getChunkRuntimeModulesInOrder(chunk); +/** @typedef {import("../Compiler")} Compiler */ - if (runtimeModules.length > 0) { - source.add( - new PrefixSource( - prefix, - Template.renderRuntimeModules(runtimeModules, chunkRenderContext) - ) - ); - source.add( - "/************************************************************************/\n" - ); - // runtimeRuntimeModules calls codeGeneration - for (const module of runtimeModules) { - compilation.codeGeneratedModules.add(module); - } - } - if (inlinedModules) { - if (bootstrap.beforeStartup.length > 0) { - const beforeStartup = Template.asString(bootstrap.beforeStartup) + "\n"; - source.add( - new PrefixSource( - prefix, - useSourceMap - ? new OriginalSource(beforeStartup, "webpack/before-startup") - : new RawSource(beforeStartup) - ) - ); - } - const lastInlinedModule = last(inlinedModules); - const startupSource = new ConcatSource(); - startupSource.add(`var __webpack_exports__ = {};\n`); - for (const m of inlinedModules) { - const renderedModule = this.renderModule( - m, - chunkRenderContext, - hooks, - false - ); - if (renderedModule) { - const innerStrict = !allStrict && m.buildInfo.strict; - const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements( - m, - chunk.runtime - ); - const exports = runtimeRequirements.has(RuntimeGlobals.exports); - const webpackExports = - exports && m.exportsArgument === "__webpack_exports__"; - let iife = innerStrict - ? "it need to be in strict mode." - : inlinedModules.size > 1 - ? // TODO check globals and top-level declarations of other entries and chunk modules - // to make a better decision - "it need to be isolated against other entry modules." - : chunkModules - ? "it need to be isolated against other modules in the chunk." - : exports && !webpackExports - ? `it uses a non-standard name for the exports (${m.exportsArgument}).` - : hooks.embedInRuntimeBailout.call(m, renderContext); - let footer; - if (iife !== undefined) { - startupSource.add( - `// This entry need to be wrapped in an IIFE because ${iife}\n` - ); - const arrow = runtimeTemplate.supportsArrowFunction(); - if (arrow) { - startupSource.add("(() => {\n"); - footer = "\n})();\n\n"; - } else { - startupSource.add("!function() {\n"); - footer = "\n}();\n"; - } - if (innerStrict) startupSource.add('"use strict";\n'); - } else { - footer = "\n"; - } - if (exports) { - if (m !== lastInlinedModule) - startupSource.add(`var ${m.exportsArgument} = {};\n`); - else if (m.exportsArgument !== "__webpack_exports__") - startupSource.add( - `var ${m.exportsArgument} = __webpack_exports__;\n` - ); - } - startupSource.add(renderedModule); - startupSource.add(footer); - } - } - if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) { - startupSource.add( - `__webpack_exports__ = ${RuntimeGlobals.onChunksLoaded}(__webpack_exports__);\n` - ); - } - source.add( - hooks.renderStartup.call(startupSource, lastInlinedModule, { - ...renderContext, - inlined: true - }) - ); - if (bootstrap.afterStartup.length > 0) { - const afterStartup = Template.asString(bootstrap.afterStartup) + "\n"; - source.add( - new PrefixSource( - prefix, - useSourceMap - ? new OriginalSource(afterStartup, "webpack/after-startup") - : new RawSource(afterStartup) - ) - ); - } - } else { - const lastEntryModule = last( - chunkGraph.getChunkEntryModulesIterable(chunk) - ); - const toSource = useSourceMap - ? (content, name) => - new OriginalSource(Template.asString(content), name) - : content => new RawSource(Template.asString(content)); - source.add( - new PrefixSource( - prefix, - new ConcatSource( - toSource(bootstrap.beforeStartup, "webpack/before-startup"), - "\n", - hooks.renderStartup.call( - toSource(bootstrap.startup.concat(""), "webpack/startup"), - lastEntryModule, - { - ...renderContext, - inlined: false - } - ), - toSource(bootstrap.afterStartup, "webpack/after-startup"), - "\n" - ) - ) - ); - } - if ( - hasEntryModules && - runtimeRequirements.has(RuntimeGlobals.returnExportsFromRuntime) - ) { - source.add(`${prefix}return __webpack_exports__;\n`); - } - if (iife) { - source.add("/******/ })()\n"); - } +const builtins = [ + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "diagnostics_channel", + "dns", + "dns/promises", + "domain", + "events", + "fs", + "fs/promises", + "http", + "http2", + "https", + "inspector", + "module", + "net", + "os", + "path", + "path/posix", + "path/win32", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "stream/promises", + "stream/web", + "string_decoder", + "sys", + "timers", + "timers/promises", + "tls", + "trace_events", + "tty", + "url", + "util", + "v8", + "vm", + "wasi", + "worker_threads", + "zlib", + /^node:/, - /** @type {Source} */ - let finalSource = tryRunOrWebpackError( - () => hooks.renderMain.call(source, renderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderMain" - ); - if (!finalSource) { - throw new Error( - "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderMain plugins should return something" - ); - } - finalSource = tryRunOrWebpackError( - () => hooks.renderContent.call(finalSource, renderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderContent" - ); - if (!finalSource) { - throw new Error( - "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something" - ); - } - finalSource = InitFragment.addToSource( - finalSource, - chunkRenderContext.chunkInitFragments, - chunkRenderContext - ); - finalSource = tryRunOrWebpackError( - () => hooks.render.call(finalSource, renderContext), - "JavascriptModulesPlugin.getCompilationHooks().render" - ); - if (!finalSource) { - throw new Error( - "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().render plugins should return something" - ); - } - chunk.rendered = true; - return iife ? new ConcatSource(finalSource, ";") : finalSource; - } + // cspell:word pnpapi + // Yarn PnP adds pnpapi as "builtin" + "pnpapi" +]; +class NodeTargetPlugin { /** - * @param {Hash} hash the hash to be updated - * @param {RenderBootstrapContext} renderContext options object - * @param {CompilationHooks} hooks hooks + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - updateHashWithBootstrap(hash, renderContext, hooks) { - const bootstrap = this.renderBootstrap(renderContext, hooks); - for (const key of Object.keys(bootstrap)) { - hash.update(key); - if (Array.isArray(bootstrap[key])) { - for (const line of bootstrap[key]) { - hash.update(line); - } - } else { - hash.update(JSON.stringify(bootstrap[key])); - } - } + apply(compiler) { + new ExternalsPlugin("node-commonjs", builtins).apply(compiler); + } +} + +module.exports = NodeTargetPlugin; + + +/***/ }), + +/***/ 61052: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const CommonJsChunkFormatPlugin = __webpack_require__(84508); +const EnableChunkLoadingPlugin = __webpack_require__(61291); + +/** @typedef {import("../Compiler")} Compiler */ + +class NodeTemplatePlugin { + constructor(options) { + this._options = options || {}; } /** - * @param {RenderBootstrapContext} renderContext options object - * @param {CompilationHooks} hooks hooks - * @returns {{ header: string[], beforeStartup: string[], startup: string[], afterStartup: string[], allowInlineStartup: boolean }} the generated source of the bootstrap code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - renderBootstrap(renderContext, hooks) { - const { chunkGraph, moduleGraph, chunk, runtimeTemplate } = renderContext; + apply(compiler) { + const chunkLoading = this._options.asyncChunkLoading + ? "async-node" + : "require"; + compiler.options.output.chunkLoading = chunkLoading; + new CommonJsChunkFormatPlugin().apply(compiler); + new EnableChunkLoadingPlugin(chunkLoading).apply(compiler); + } +} - const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); +module.exports = NodeTemplatePlugin; - const requireFunction = runtimeRequirements.has(RuntimeGlobals.require); - const moduleCache = runtimeRequirements.has(RuntimeGlobals.moduleCache); - const moduleFactories = runtimeRequirements.has( - RuntimeGlobals.moduleFactories - ); - const moduleUsed = runtimeRequirements.has(RuntimeGlobals.module); - const requireScopeUsed = runtimeRequirements.has( - RuntimeGlobals.requireScope - ); - const interceptModuleExecution = runtimeRequirements.has( - RuntimeGlobals.interceptModuleExecution - ); - const useRequire = - requireFunction || interceptModuleExecution || moduleUsed; +/***/ }), - const result = { - header: [], - beforeStartup: [], - startup: [], - afterStartup: [], - allowInlineStartup: true - }; +/***/ 98810: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - let { header: buf, startup, beforeStartup, afterStartup } = result; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (result.allowInlineStartup && moduleFactories) { - startup.push( - "// module factories are used so entry inlining is disabled" - ); - result.allowInlineStartup = false; - } - if (result.allowInlineStartup && moduleCache) { - startup.push("// module cache are used so entry inlining is disabled"); - result.allowInlineStartup = false; - } - if (result.allowInlineStartup && interceptModuleExecution) { - startup.push( - "// module execution is intercepted so entry inlining is disabled" - ); - result.allowInlineStartup = false; - } - if (useRequire || moduleCache) { - buf.push("// The module cache"); - buf.push("var __webpack_module_cache__ = {};"); - buf.push(""); - } - if (useRequire) { - buf.push("// The require function"); - buf.push(`function __webpack_require__(moduleId) {`); - buf.push(Template.indent(this.renderRequire(renderContext, hooks))); - buf.push("}"); - buf.push(""); - } else if (runtimeRequirements.has(RuntimeGlobals.requireScope)) { - buf.push("// The require scope"); - buf.push("var __webpack_require__ = {};"); - buf.push(""); - } +const util = __webpack_require__(73837); +const Watchpack = __webpack_require__(36871); - if ( - moduleFactories || - runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) - ) { - buf.push("// expose the modules object (__webpack_modules__)"); - buf.push(`${RuntimeGlobals.moduleFactories} = __webpack_modules__;`); - buf.push(""); - } +/** @typedef {import("../../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("../FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ +/** @typedef {import("../util/fs").WatchFileSystem} WatchFileSystem */ +/** @typedef {import("../util/fs").WatchMethod} WatchMethod */ +/** @typedef {import("../util/fs").Watcher} Watcher */ - if (moduleCache) { - buf.push("// expose the module cache"); - buf.push(`${RuntimeGlobals.moduleCache} = __webpack_module_cache__;`); - buf.push(""); - } +class NodeWatchFileSystem { + constructor(inputFileSystem) { + this.inputFileSystem = inputFileSystem; + this.watcherOptions = { + aggregateTimeout: 0 + }; + this.watcher = new Watchpack(this.watcherOptions); + } - if (interceptModuleExecution) { - buf.push("// expose the module execution interceptor"); - buf.push(`${RuntimeGlobals.interceptModuleExecution} = [];`); - buf.push(""); - } + /** + * @param {Iterable} files watched files + * @param {Iterable} directories watched directories + * @param {Iterable} missing watched exitance entries + * @param {number} startTime timestamp of start time + * @param {WatchOptions} options options object + * @param {function(Error=, Map, Map, Set, Set): void} callback aggregated callback + * @param {function(string, number): void} callbackUndelayed callback when the first change was detected + * @returns {Watcher} a watcher + */ + watch( + files, + directories, + missing, + startTime, + options, + callback, + callbackUndelayed + ) { + if (!files || typeof files[Symbol.iterator] !== "function") { + throw new Error("Invalid arguments: 'files'"); + } + if (!directories || typeof directories[Symbol.iterator] !== "function") { + throw new Error("Invalid arguments: 'directories'"); + } + if (!missing || typeof missing[Symbol.iterator] !== "function") { + throw new Error("Invalid arguments: 'missing'"); + } + if (typeof callback !== "function") { + throw new Error("Invalid arguments: 'callback'"); + } + if (typeof startTime !== "number" && startTime) { + throw new Error("Invalid arguments: 'startTime'"); + } + if (typeof options !== "object") { + throw new Error("Invalid arguments: 'options'"); + } + if (typeof callbackUndelayed !== "function" && callbackUndelayed) { + throw new Error("Invalid arguments: 'callbackUndelayed'"); + } + const oldWatcher = this.watcher; + this.watcher = new Watchpack(options); - if (!runtimeRequirements.has(RuntimeGlobals.startupNoDefault)) { - if (chunkGraph.getNumberOfEntryModules(chunk) > 0) { - /** @type {string[]} */ - const buf2 = []; - const runtimeRequirements = - chunkGraph.getTreeRuntimeRequirements(chunk); - buf2.push("// Load entry module and return exports"); - let i = chunkGraph.getNumberOfEntryModules(chunk); - for (const [ - entryModule, - entrypoint - ] of chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)) { - const chunks = entrypoint.chunks.filter(c => c !== chunk); - if (result.allowInlineStartup && chunks.length > 0) { - buf2.push( - "// This entry module depends on other loaded chunks and execution need to be delayed" - ); - result.allowInlineStartup = false; - } - if ( - result.allowInlineStartup && - someInIterable( - moduleGraph.getIncomingConnectionsByOriginModule(entryModule), - ([originModule, connections]) => - originModule && - connections.some(c => c.isTargetActive(chunk.runtime)) && - someInIterable( - chunkGraph.getModuleRuntimes(originModule), - runtime => - intersectRuntime(runtime, chunk.runtime) !== undefined - ) - ) - ) { - buf2.push( - "// This entry module is referenced by other modules so it can't be inlined" - ); - result.allowInlineStartup = false; - } - if ( - result.allowInlineStartup && - (!entryModule.buildInfo || - !entryModule.buildInfo.topLevelDeclarations) - ) { - buf2.push( - "// This entry module doesn't tell about it's top-level declarations so it can't be inlined" - ); - result.allowInlineStartup = false; - } - if (result.allowInlineStartup) { - const bailout = hooks.inlineInRuntimeBailout.call( - entryModule, - renderContext - ); - if (bailout !== undefined) { - buf2.push( - `// This entry module can't be inlined because ${bailout}` - ); - result.allowInlineStartup = false; + if (callbackUndelayed) { + this.watcher.once("change", callbackUndelayed); + } + + const fetchTimeInfo = () => { + const fileTimeInfoEntries = new Map(); + const contextTimeInfoEntries = new Map(); + if (this.watcher) { + this.watcher.collectTimeInfoEntries( + fileTimeInfoEntries, + contextTimeInfoEntries + ); + } + return { fileTimeInfoEntries, contextTimeInfoEntries }; + }; + this.watcher.once("aggregated", (changes, removals) => { + // pause emitting events (avoids clearing aggregated changes and removals on timeout) + this.watcher.pause(); + + if (this.inputFileSystem && this.inputFileSystem.purge) { + const fs = this.inputFileSystem; + for (const item of changes) { + fs.purge(item); + } + for (const item of removals) { + fs.purge(item); + } + } + const { fileTimeInfoEntries, contextTimeInfoEntries } = fetchTimeInfo(); + callback( + null, + fileTimeInfoEntries, + contextTimeInfoEntries, + changes, + removals + ); + }); + + this.watcher.watch({ files, directories, missing, startTime }); + + if (oldWatcher) { + oldWatcher.close(); + } + return { + close: () => { + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + }, + pause: () => { + if (this.watcher) { + this.watcher.pause(); + } + }, + getAggregatedRemovals: util.deprecate( + () => { + const items = this.watcher && this.watcher.aggregatedRemovals; + if (items && this.inputFileSystem && this.inputFileSystem.purge) { + const fs = this.inputFileSystem; + for (const item of items) { + fs.purge(item); } } - i--; - const moduleId = chunkGraph.getModuleId(entryModule); - const entryRuntimeRequirements = - chunkGraph.getModuleRuntimeRequirements(entryModule, chunk.runtime); - let moduleIdExpr = JSON.stringify(moduleId); - if (runtimeRequirements.has(RuntimeGlobals.entryModuleId)) { - moduleIdExpr = `${RuntimeGlobals.entryModuleId} = ${moduleIdExpr}`; + return items; + }, + "Watcher.getAggregatedRemovals is deprecated in favor of Watcher.getInfo since that's more performant.", + "DEP_WEBPACK_WATCHER_GET_AGGREGATED_REMOVALS" + ), + getAggregatedChanges: util.deprecate( + () => { + const items = this.watcher && this.watcher.aggregatedChanges; + if (items && this.inputFileSystem && this.inputFileSystem.purge) { + const fs = this.inputFileSystem; + for (const item of items) { + fs.purge(item); + } } - if ( - result.allowInlineStartup && - entryRuntimeRequirements.has(RuntimeGlobals.module) - ) { - result.allowInlineStartup = false; - buf2.push( - "// This entry module used 'module' so it can't be inlined" - ); + return items; + }, + "Watcher.getAggregatedChanges is deprecated in favor of Watcher.getInfo since that's more performant.", + "DEP_WEBPACK_WATCHER_GET_AGGREGATED_CHANGES" + ), + getFileTimeInfoEntries: util.deprecate( + () => { + return fetchTimeInfo().fileTimeInfoEntries; + }, + "Watcher.getFileTimeInfoEntries is deprecated in favor of Watcher.getInfo since that's more performant.", + "DEP_WEBPACK_WATCHER_FILE_TIME_INFO_ENTRIES" + ), + getContextTimeInfoEntries: util.deprecate( + () => { + return fetchTimeInfo().contextTimeInfoEntries; + }, + "Watcher.getContextTimeInfoEntries is deprecated in favor of Watcher.getInfo since that's more performant.", + "DEP_WEBPACK_WATCHER_CONTEXT_TIME_INFO_ENTRIES" + ), + getInfo: () => { + const removals = this.watcher && this.watcher.aggregatedRemovals; + const changes = this.watcher && this.watcher.aggregatedChanges; + if (this.inputFileSystem && this.inputFileSystem.purge) { + const fs = this.inputFileSystem; + if (removals) { + for (const item of removals) { + fs.purge(item); + } } - if (chunks.length > 0) { - buf2.push( - `${i === 0 ? "var __webpack_exports__ = " : ""}${ - RuntimeGlobals.onChunksLoaded - }(undefined, ${JSON.stringify( - chunks.map(c => c.id) - )}, ${runtimeTemplate.returningFunction( - `__webpack_require__(${moduleIdExpr})` - )})` - ); - } else if (useRequire) { - buf2.push( - `${ - i === 0 ? "var __webpack_exports__ = " : "" - }__webpack_require__(${moduleIdExpr});` - ); - } else { - if (i === 0) buf2.push("var __webpack_exports__ = {};"); - if (requireScopeUsed) { - buf2.push( - `__webpack_modules__[${moduleIdExpr}](0, ${ - i === 0 ? "__webpack_exports__" : "{}" - }, __webpack_require__);` - ); - } else if (entryRuntimeRequirements.has(RuntimeGlobals.exports)) { - buf2.push( - `__webpack_modules__[${moduleIdExpr}](0, ${ - i === 0 ? "__webpack_exports__" : "{}" - });` - ); - } else { - buf2.push(`__webpack_modules__[${moduleIdExpr}]();`); + if (changes) { + for (const item of changes) { + fs.purge(item); } } } - if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) { - buf2.push( - `__webpack_exports__ = ${RuntimeGlobals.onChunksLoaded}(__webpack_exports__);` - ); - } - if ( - runtimeRequirements.has(RuntimeGlobals.startup) || - (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) && - runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)) - ) { - result.allowInlineStartup = false; - buf.push("// the startup function"); - buf.push( - `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction("", [ - ...buf2, - "return __webpack_exports__;" - ])};` - ); - buf.push(""); - startup.push("// run startup"); - startup.push( - `var __webpack_exports__ = ${RuntimeGlobals.startup}();` - ); - } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore)) { - buf.push("// the startup function"); - buf.push( - `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` - ); - beforeStartup.push("// run runtime startup"); - beforeStartup.push(`${RuntimeGlobals.startup}();`); - startup.push("// startup"); - startup.push(Template.asString(buf2)); - } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter)) { - buf.push("// the startup function"); - buf.push( - `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` - ); - startup.push("// startup"); - startup.push(Template.asString(buf2)); - afterStartup.push("// run runtime startup"); - afterStartup.push(`${RuntimeGlobals.startup}();`); - } else { - startup.push("// startup"); - startup.push(Template.asString(buf2)); - } - } else if ( - runtimeRequirements.has(RuntimeGlobals.startup) || - runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) || - runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter) - ) { - buf.push( - "// the startup function", - "// It's empty as no entry modules are in this chunk", - `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};`, - "" - ); + const { fileTimeInfoEntries, contextTimeInfoEntries } = fetchTimeInfo(); + return { + changes, + removals, + fileTimeInfoEntries, + contextTimeInfoEntries + }; } - } else if ( - runtimeRequirements.has(RuntimeGlobals.startup) || - runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore) || - runtimeRequirements.has(RuntimeGlobals.startupOnlyAfter) - ) { - result.allowInlineStartup = false; - buf.push( - "// the startup function", - "// It's empty as some runtime module handles the default behavior", - `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};` - ); - startup.push("// run startup"); - startup.push(`var __webpack_exports__ = ${RuntimeGlobals.startup}();`); - } - return result; + }; + } +} + +module.exports = NodeWatchFileSystem; + + +/***/ }), + +/***/ 73369: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); +const { + chunkHasJs, + getChunkFilenameTemplate +} = __webpack_require__(89464); +const { getInitialChunkIds } = __webpack_require__(98124); +const compileBooleanMatcher = __webpack_require__(29404); +const { getUndoPath } = __webpack_require__(82186); + +class ReadFileChunkLoadingRuntimeModule extends RuntimeModule { + constructor(runtimeRequirements) { + super("readFile chunk loading", RuntimeModule.STAGE_ATTACH); + this.runtimeRequirements = runtimeRequirements; } /** - * @param {RenderBootstrapContext} renderContext options object - * @param {CompilationHooks} hooks hooks - * @returns {string} the generated source of the require function + * @returns {string} runtime code */ - renderRequire(renderContext, hooks) { - const { - chunk, - chunkGraph, - runtimeTemplate: { outputOptions } - } = renderContext; - const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); - const moduleExecution = runtimeRequirements.has( - RuntimeGlobals.interceptModuleExecution - ) - ? Template.asString([ - "var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: __webpack_require__ };", - `${RuntimeGlobals.interceptModuleExecution}.forEach(function(handler) { handler(execOptions); });`, - "module = execOptions.module;", - "execOptions.factory.call(module.exports, module, module.exports, execOptions.require);" - ]) - : runtimeRequirements.has(RuntimeGlobals.thisAsExports) - ? Template.asString([ - "__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);" - ]) - : Template.asString([ - "__webpack_modules__[moduleId](module, module.exports, __webpack_require__);" - ]); - const needModuleId = runtimeRequirements.has(RuntimeGlobals.moduleId); - const needModuleLoaded = runtimeRequirements.has( - RuntimeGlobals.moduleLoaded + generate() { + const { chunkGraph, chunk } = this; + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); + const withExternalInstallChunk = this.runtimeRequirements.has( + RuntimeGlobals.externalInstallChunk ); - const content = Template.asString([ - "// Check if module is in cache", - "var cachedModule = __webpack_module_cache__[moduleId];", - "if (cachedModule !== undefined) {", - outputOptions.strictModuleErrorHandling - ? Template.indent([ - "if (cachedModule.error !== undefined) throw cachedModule.error;", - "return cachedModule.exports;" + const withOnChunkLoad = this.runtimeRequirements.has( + RuntimeGlobals.onChunksLoaded + ); + const withLoading = this.runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withHmr = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); + const hasJsMatcher = compileBooleanMatcher(conditionMap); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + + const outputName = this.compilation.getPath( + getChunkFilenameTemplate(chunk, this.compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath( + outputName, + this.compilation.outputOptions.path, + false + ); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_readFileVm` + : undefined; + + return Template.asString([ + withBaseURI + ? Template.asString([ + `${RuntimeGlobals.baseURI} = require("url").pathToFileURL(${ + rootOutputDir + ? `__dirname + ${JSON.stringify("/" + rootOutputDir)}` + : "__filename" + });` ]) - : Template.indent("return cachedModule.exports;"), - "}", - "// Create a new module (and put it into the cache)", - "var module = __webpack_module_cache__[moduleId] = {", - Template.indent([ - needModuleId ? "id: moduleId," : "// no module.id needed", - needModuleLoaded ? "loaded: false," : "// no module.loaded needed", - "exports: {}" - ]), + : "// no baseURI", + "", + "// object to store loaded chunks", + '// "0" means "already loaded", Promise means loading', + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join( + ",\n" + ) + ), "};", "", - outputOptions.strictModuleExceptionHandling - ? Template.asString([ - "// Execute the module function", - "var threw = true;", - "try {", - Template.indent([moduleExecution, "threw = false;"]), - "} finally {", + withOnChunkLoad + ? `${ + RuntimeGlobals.onChunksLoaded + }.readFileVm = ${runtimeTemplate.returningFunction( + "installedChunks[chunkId] === 0", + "chunkId" + )};` + : "// no on chunks loaded", + "", + withLoading || withExternalInstallChunk + ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [ + "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", + "for(var moduleId in moreModules) {", Template.indent([ - "if(threw) delete __webpack_module_cache__[moduleId];" + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent([ + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ]), + "}" ]), - "}" + "}", + `if(runtime) runtime(__webpack_require__);`, + "for(var i = 0; i < chunkIds.length; i++) {", + Template.indent([ + "if(installedChunks[chunkIds[i]]) {", + Template.indent(["installedChunks[chunkIds[i]][0]();"]), + "}", + "installedChunks[chunkIds[i]] = 0;" + ]), + "}", + withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" + ])};` + : "// no chunk install function needed", + "", + withLoading + ? Template.asString([ + "// ReadFile + VM.run chunk loading for javascript", + `${fn}.readFileVm = function(chunkId, promises) {`, + hasJsMatcher !== false + ? Template.indent([ + "", + "var installedChunkData = installedChunks[chunkId];", + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + '// array of [resolve, reject, promise] means "currently loading"', + "if(installedChunkData) {", + Template.indent(["promises.push(installedChunkData[2]);"]), + "} else {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent([ + "// load the chunk and return promise to it", + "var promise = new Promise(function(resolve, reject) {", + Template.indent([ + "installedChunkData = installedChunks[chunkId] = [resolve, reject];", + `var filename = require('path').join(__dirname, ${JSON.stringify( + rootOutputDir + )} + ${ + RuntimeGlobals.getChunkScriptFilename + }(chunkId));`, + "require('fs').readFile(filename, 'utf-8', function(err, content) {", + Template.indent([ + "if(err) return reject(err);", + "var chunk = {};", + "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + + "(chunk, require, require('path').dirname(filename), filename);", + "installChunk(chunk);" + ]), + "});" + ]), + "});", + "promises.push(installedChunkData[2] = promise);" + ]), + "} else installedChunks[chunkId] = 0;" + ]), + "}" + ]), + "}" + ]) + : Template.indent(["installedChunks[chunkId] = 0;"]), + "};" ]) - : outputOptions.strictModuleErrorHandling + : "// no chunk loading", + "", + withExternalInstallChunk ? Template.asString([ - "// Execute the module function", - "try {", - Template.indent(moduleExecution), - "} catch(e) {", - Template.indent(["module.error = e;", "throw e;"]), - "}" + "module.exports = __webpack_require__;", + `${RuntimeGlobals.externalInstallChunk} = installChunk;` ]) - : Template.asString([ - "// Execute the module function", - moduleExecution - ]), - needModuleLoaded + : "// no external install chunk", + "", + withHmr ? Template.asString([ + "function loadUpdateChunk(chunkId, updatedModulesList) {", + Template.indent([ + "return new Promise(function(resolve, reject) {", + Template.indent([ + `var filename = require('path').join(__dirname, ${JSON.stringify( + rootOutputDir + )} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`, + "require('fs').readFile(filename, 'utf-8', function(err, content) {", + Template.indent([ + "if(err) return reject(err);", + "var update = {};", + "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + + "(update, require, require('path').dirname(filename), filename);", + "var updatedModules = update.modules;", + "var runtime = update.runtime;", + "for(var moduleId in updatedModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, + Template.indent([ + `currentUpdate[moduleId] = updatedModules[moduleId];`, + "if(updatedModulesList) updatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "if(runtime) currentUpdateRuntime.push(runtime);", + "resolve();" + ]), + "});" + ]), + "});" + ]), + "}", "", - "// Flag the module as loaded", - "module.loaded = true;", - "" + Template.getFunctionContent( + require('./JavascriptHotModuleReplacement.runtime.js') + ) + .replace(/\$key\$/g, "readFileVm") + .replace(/\$installedChunks\$/g, "installedChunks") + .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") + .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) + .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) + .replace( + /\$ensureChunkHandlers\$/g, + RuntimeGlobals.ensureChunkHandlers + ) + .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) + .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) + .replace( + /\$hmrDownloadUpdateHandlers\$/g, + RuntimeGlobals.hmrDownloadUpdateHandlers + ) + .replace( + /\$hmrInvalidateModuleHandlers\$/g, + RuntimeGlobals.hmrInvalidateModuleHandlers + ) ]) - : "", - "// Return the exports of the module", - "return module.exports;" + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${RuntimeGlobals.hmrDownloadManifest} = function() {`, + Template.indent([ + "return new Promise(function(resolve, reject) {", + Template.indent([ + `var filename = require('path').join(__dirname, ${JSON.stringify( + rootOutputDir + )} + ${RuntimeGlobals.getUpdateManifestFilename}());`, + "require('fs').readFile(filename, 'utf-8', function(err, content) {", + Template.indent([ + "if(err) {", + Template.indent([ + 'if(err.code === "ENOENT") return resolve();', + "return reject(err);" + ]), + "}", + "try { resolve(JSON.parse(content)); }", + "catch(e) { reject(e); }" + ]), + "});" + ]), + "});" + ]), + "}" + ]) + : "// no HMR manifest" ]); - return tryRunOrWebpackError( - () => hooks.renderRequire.call(content, renderContext), - "JavascriptModulesPlugin.getCompilationHooks().renderRequire" - ); } } -module.exports = JavascriptModulesPlugin; -module.exports.chunkHasJs = chunkHasJs; +module.exports = ReadFileChunkLoadingRuntimeModule; /***/ }), -/***/ 29050: +/***/ 73163: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -98246,3781 +98493,4126 @@ module.exports.chunkHasJs = chunkHasJs; -const { Parser: AcornParser } = __webpack_require__(31988); -const { importAssertions } = __webpack_require__(72617); -const { SyncBailHook, HookMap } = __webpack_require__(41242); -const vm = __webpack_require__(26144); -const Parser = __webpack_require__(11715); -const StackedMap = __webpack_require__(58845); -const binarySearchBounds = __webpack_require__(92229); -const memoize = __webpack_require__(78676); -const BasicEvaluatedExpression = __webpack_require__(950); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const AsyncWasmLoadingRuntimeModule = __webpack_require__(5434); -/** @typedef {import("acorn").Options} AcornOptions */ -/** @typedef {import("estree").ArrayExpression} ArrayExpressionNode */ -/** @typedef {import("estree").BinaryExpression} BinaryExpressionNode */ -/** @typedef {import("estree").BlockStatement} BlockStatementNode */ -/** @typedef {import("estree").SequenceExpression} SequenceExpressionNode */ -/** @typedef {import("estree").CallExpression} CallExpressionNode */ -/** @typedef {import("estree").ClassDeclaration} ClassDeclarationNode */ -/** @typedef {import("estree").ClassExpression} ClassExpressionNode */ -/** @typedef {import("estree").Comment} CommentNode */ -/** @typedef {import("estree").ConditionalExpression} ConditionalExpressionNode */ -/** @typedef {import("estree").Declaration} DeclarationNode */ -/** @typedef {import("estree").PrivateIdentifier} PrivateIdentifierNode */ -/** @typedef {import("estree").PropertyDefinition} PropertyDefinitionNode */ -/** @typedef {import("estree").Expression} ExpressionNode */ -/** @typedef {import("estree").Identifier} IdentifierNode */ -/** @typedef {import("estree").IfStatement} IfStatementNode */ -/** @typedef {import("estree").LabeledStatement} LabeledStatementNode */ -/** @typedef {import("estree").Literal} LiteralNode */ -/** @typedef {import("estree").LogicalExpression} LogicalExpressionNode */ -/** @typedef {import("estree").ChainExpression} ChainExpressionNode */ -/** @typedef {import("estree").MemberExpression} MemberExpressionNode */ -/** @typedef {import("estree").MetaProperty} MetaPropertyNode */ -/** @typedef {import("estree").MethodDefinition} MethodDefinitionNode */ -/** @typedef {import("estree").ModuleDeclaration} ModuleDeclarationNode */ -/** @typedef {import("estree").NewExpression} NewExpressionNode */ -/** @typedef {import("estree").Node} AnyNode */ -/** @typedef {import("estree").Program} ProgramNode */ -/** @typedef {import("estree").Statement} StatementNode */ -/** @typedef {import("estree").ImportDeclaration} ImportDeclarationNode */ -/** @typedef {import("estree").ExportNamedDeclaration} ExportNamedDeclarationNode */ -/** @typedef {import("estree").ExportDefaultDeclaration} ExportDefaultDeclarationNode */ -/** @typedef {import("estree").ExportAllDeclaration} ExportAllDeclarationNode */ -/** @typedef {import("estree").Super} SuperNode */ -/** @typedef {import("estree").TaggedTemplateExpression} TaggedTemplateExpressionNode */ -/** @typedef {import("estree").TemplateLiteral} TemplateLiteralNode */ -/** @typedef {import("estree").ThisExpression} ThisExpressionNode */ -/** @typedef {import("estree").UnaryExpression} UnaryExpressionNode */ -/** @typedef {import("estree").VariableDeclarator} VariableDeclaratorNode */ -/** @template T @typedef {import("tapable").AsArray} AsArray */ -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ -/** @typedef {{declaredScope: ScopeInfo, freeName: string | true, tagInfo: TagInfo | undefined}} VariableInfoInterface */ -/** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[] }} GetInfoResult */ +/** @typedef {import("../Compiler")} Compiler */ -const EMPTY_ARRAY = []; -const ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = 0b01; -const ALLOWED_MEMBER_TYPES_EXPRESSION = 0b10; -const ALLOWED_MEMBER_TYPES_ALL = 0b11; +class ReadFileCompileAsyncWasmPlugin { + constructor({ type = "async-node", import: useImport = false } = {}) { + this._type = type; + this._import = useImport; + } + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "ReadFileCompileAsyncWasmPlugin", + compilation => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === this._type; + }; + const generateLoadBinaryCode = this._import + ? path => + Template.asString([ + "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {", + Template.indent([ + `readFile(new URL(${path}, import.meta.url), (err, buffer) => {`, + Template.indent([ + "if (err) return reject(err);", + "", + "// Fake fetch response", + "resolve({", + Template.indent(["arrayBuffer() { return buffer; }"]), + "});" + ]), + "});" + ]), + "}))" + ]) + : path => + Template.asString([ + "new Promise(function (resolve, reject) {", + Template.indent([ + "try {", + Template.indent([ + "var { readFile } = require('fs');", + "var { join } = require('path');", + "", + `readFile(join(__dirname, ${path}), function(err, buffer){`, + Template.indent([ + "if (err) return reject(err);", + "", + "// Fake fetch response", + "resolve({", + Template.indent(["arrayBuffer() { return buffer; }"]), + "});" + ]), + "});" + ]), + "} catch (err) { reject(err); }" + ]), + "})" + ]); -// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.instantiateWasm) + .tap("ReadFileCompileAsyncWasmPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + const chunkGraph = compilation.chunkGraph; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + m => m.type === "webassembly/async" + ) + ) { + return; + } + set.add(RuntimeGlobals.publicPath); + compilation.addRuntimeModule( + chunk, + new AsyncWasmLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: false + }) + ); + }); + } + ); + } +} -const parser = AcornParser.extend(importAssertions); +module.exports = ReadFileCompileAsyncWasmPlugin; + + +/***/ }), + +/***/ 98939: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const WasmChunkLoadingRuntimeModule = __webpack_require__(87394); + +/** @typedef {import("../Compiler")} Compiler */ + +// TODO webpack 6 remove + +class ReadFileCompileWasmPlugin { + constructor(options) { + this.options = options || {}; + } -class VariableInfo { /** - * @param {ScopeInfo} declaredScope scope in which the variable is declared - * @param {string | true} freeName which free name the variable aliases, or true when none - * @param {TagInfo | undefined} tagInfo info about tags + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - constructor(declaredScope, freeName, tagInfo) { - this.declaredScope = declaredScope; - this.freeName = freeName; - this.tagInfo = tagInfo; + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "ReadFileCompileWasmPlugin", + compilation => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === "async-node"; + }; + const generateLoadBinaryCode = path => + Template.asString([ + "new Promise(function (resolve, reject) {", + Template.indent([ + "var { readFile } = require('fs');", + "var { join } = require('path');", + "", + "try {", + Template.indent([ + `readFile(join(__dirname, ${path}), function(err, buffer){`, + Template.indent([ + "if (err) return reject(err);", + "", + "// Fake fetch response", + "resolve({", + Template.indent(["arrayBuffer() { return buffer; }"]), + "});" + ]), + "});" + ]), + "} catch (err) { reject(err); }" + ]), + "})" + ]); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("ReadFileCompileWasmPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + const chunkGraph = compilation.chunkGraph; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + m => m.type === "webassembly/sync" + ) + ) { + return; + } + set.add(RuntimeGlobals.moduleCache); + compilation.addRuntimeModule( + chunk, + new WasmChunkLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: false, + mangleImports: this.options.mangleImports, + runtimeRequirements: set + }) + ); + }); + } + ); } } -/** @typedef {string | ScopeInfo | VariableInfo} ExportedVariableInfo */ -/** @typedef {LiteralNode | string | null | undefined} ImportSource */ -/** @typedef {Omit & { sourceType: "module" | "script" | "auto", ecmaVersion?: AcornOptions["ecmaVersion"] }} ParseOptions */ +module.exports = ReadFileCompileWasmPlugin; -/** - * @typedef {Object} TagInfo - * @property {any} tag - * @property {any} data - * @property {TagInfo | undefined} next - */ -/** - * @typedef {Object} ScopeInfo - * @property {StackedMap} definitions - * @property {boolean | "arrow"} topLevelScope - * @property {boolean} inShorthand - * @property {boolean} isStrict - * @property {boolean} isAsmJs - * @property {boolean} inTry - */ +/***/ }), -const joinRanges = (startRange, endRange) => { - if (!endRange) return startRange; - if (!startRange) return endRange; - return [startRange[0], endRange[1]]; -}; +/***/ 94172: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const objectAndMembersToName = (object, membersReversed) => { - let name = object; - for (let i = membersReversed.length - 1; i >= 0; i--) { - name = name + "." + membersReversed[i]; - } - return name; -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ -const getRootName = expression => { - switch (expression.type) { - case "Identifier": - return expression.name; - case "ThisExpression": - return "this"; - case "MetaProperty": - return `${expression.meta.name}.${expression.property.name}`; - default: - return undefined; - } -}; -/** @type {AcornOptions} */ -const defaultParserOptions = { - ranges: true, - locations: true, - ecmaVersion: "latest", - sourceType: "module", - // https://github.com/tc39/proposal-hashbang - allowHashBang: true, - onComment: null -}; -// regexp to match at least one "magic comment" -const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); +const { + chunkHasJs, + getChunkFilenameTemplate +} = __webpack_require__(89464); +const { getInitialChunkIds } = __webpack_require__(98124); +const compileBooleanMatcher = __webpack_require__(29404); +const { getUndoPath } = __webpack_require__(82186); -const EMPTY_COMMENT_OPTIONS = { - options: null, - errors: null -}; +class RequireChunkLoadingRuntimeModule extends RuntimeModule { + constructor(runtimeRequirements) { + super("require chunk loading", RuntimeModule.STAGE_ATTACH); + this.runtimeRequirements = runtimeRequirements; + } -class JavascriptParser extends Parser { /** - * @param {"module" | "script" | "auto"} sourceType default source type + * @returns {string} runtime code */ - constructor(sourceType = "auto") { - super(); - this.hooks = Object.freeze({ - /** @type {HookMap>} */ - evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ - evaluate: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ - evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ - evaluateDefinedIdentifier: new HookMap( - () => new SyncBailHook(["expression"]) - ), - /** @type {HookMap>} */ - evaluateCallExpressionMember: new HookMap( - () => new SyncBailHook(["expression", "param"]) - ), - /** @type {HookMap>} */ - isPure: new HookMap( - () => new SyncBailHook(["expression", "commentsStartPosition"]) - ), - /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ - preStatement: new SyncBailHook(["statement"]), + generate() { + const { chunkGraph, chunk } = this; + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); + const withExternalInstallChunk = this.runtimeRequirements.has( + RuntimeGlobals.externalInstallChunk + ); + const withOnChunkLoad = this.runtimeRequirements.has( + RuntimeGlobals.onChunksLoaded + ); + const withLoading = this.runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withHmr = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); + const hasJsMatcher = compileBooleanMatcher(conditionMap); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); - /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ - blockPreStatement: new SyncBailHook(["declaration"]), - /** @type {SyncBailHook<[StatementNode | ModuleDeclarationNode], boolean | void>} */ - statement: new SyncBailHook(["statement"]), - /** @type {SyncBailHook<[IfStatementNode], boolean | void>} */ - statementIf: new SyncBailHook(["statement"]), - /** @type {SyncBailHook<[ExpressionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ - classExtendsExpression: new SyncBailHook([ - "expression", - "classDefinition" - ]), - /** @type {SyncBailHook<[MethodDefinitionNode | PropertyDefinitionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ - classBodyElement: new SyncBailHook(["element", "classDefinition"]), - /** @type {SyncBailHook<[ExpressionNode, MethodDefinitionNode | PropertyDefinitionNode, ClassExpressionNode | ClassDeclarationNode], boolean | void>} */ - classBodyValue: new SyncBailHook([ - "expression", - "element", - "classDefinition" - ]), - /** @type {HookMap>} */ - label: new HookMap(() => new SyncBailHook(["statement"])), - /** @type {SyncBailHook<[ImportDeclarationNode, ImportSource], boolean | void>} */ - import: new SyncBailHook(["statement", "source"]), - /** @type {SyncBailHook<[ImportDeclarationNode, ImportSource, string, string], boolean | void>} */ - importSpecifier: new SyncBailHook([ - "statement", - "source", - "exportName", - "identifierName" - ]), - /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode], boolean | void>} */ - export: new SyncBailHook(["statement"]), - /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, ImportSource], boolean | void>} */ - exportImport: new SyncBailHook(["statement", "source"]), - /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, DeclarationNode], boolean | void>} */ - exportDeclaration: new SyncBailHook(["statement", "declaration"]), - /** @type {SyncBailHook<[ExportDefaultDeclarationNode, DeclarationNode], boolean | void>} */ - exportExpression: new SyncBailHook(["statement", "declaration"]), - /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, string, string, number | undefined], boolean | void>} */ - exportSpecifier: new SyncBailHook([ - "statement", - "identifierName", - "exportName", - "index" - ]), - /** @type {SyncBailHook<[ExportNamedDeclarationNode | ExportAllDeclarationNode, ImportSource, string, string, number | undefined], boolean | void>} */ - exportImportSpecifier: new SyncBailHook([ - "statement", - "source", - "identifierName", - "exportName", - "index" - ]), - /** @type {SyncBailHook<[VariableDeclaratorNode, StatementNode], boolean | void>} */ - preDeclarator: new SyncBailHook(["declarator", "statement"]), - /** @type {SyncBailHook<[VariableDeclaratorNode, StatementNode], boolean | void>} */ - declarator: new SyncBailHook(["declarator", "statement"]), - /** @type {HookMap>} */ - varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])), - /** @type {HookMap>} */ - varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])), - /** @type {HookMap>} */ - varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])), - /** @type {HookMap>} */ - varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])), - /** @type {HookMap>} */ - pattern: new HookMap(() => new SyncBailHook(["pattern"])), - /** @type {HookMap>} */ - canRename: new HookMap(() => new SyncBailHook(["initExpression"])), - /** @type {HookMap>} */ - rename: new HookMap(() => new SyncBailHook(["initExpression"])), - /** @type {HookMap>} */ - assign: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ - assignMemberChain: new HookMap( - () => new SyncBailHook(["expression", "members"]) - ), - /** @type {HookMap>} */ - typeof: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ - importCall: new SyncBailHook(["expression"]), - /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ - topLevelAwait: new SyncBailHook(["expression"]), - /** @type {HookMap>} */ - call: new HookMap(() => new SyncBailHook(["expression"])), - /** Something like "a.b()" */ - /** @type {HookMap>} */ - callMemberChain: new HookMap( - () => new SyncBailHook(["expression", "members"]) - ), - /** Something like "a.b().c.d" */ - /** @type {HookMap>} */ - memberChainOfCallMemberChain: new HookMap( - () => - new SyncBailHook([ - "expression", - "calleeMembers", - "callExpression", - "members" - ]) - ), - /** Something like "a.b().c.d()"" */ - /** @type {HookMap>} */ - callMemberChainOfCallMemberChain: new HookMap( - () => - new SyncBailHook([ - "expression", - "calleeMembers", - "innerCallExpression", - "members" - ]) - ), - /** @type {SyncBailHook<[ChainExpressionNode], boolean | void>} */ - optionalChaining: new SyncBailHook(["optionalChaining"]), - /** @type {HookMap>} */ - new: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ - expression: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ - expressionMemberChain: new HookMap( - () => new SyncBailHook(["expression", "members"]) - ), - /** @type {HookMap>} */ - unhandledExpressionMemberChain: new HookMap( - () => new SyncBailHook(["expression", "members"]) + const outputName = this.compilation.getPath( + getChunkFilenameTemplate(chunk, this.compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath( + outputName, + this.compilation.outputOptions.path, + true + ); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_require` + : undefined; + + return Template.asString([ + withBaseURI + ? Template.asString([ + `${RuntimeGlobals.baseURI} = require("url").pathToFileURL(${ + rootOutputDir !== "./" + ? `__dirname + ${JSON.stringify("/" + rootOutputDir)}` + : "__filename" + });` + ]) + : "// no baseURI", + "", + "// object to store loaded chunks", + '// "1" means "loaded", otherwise not loaded yet', + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 1`).join( + ",\n" + ) ), - /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ - expressionConditionalOperator: new SyncBailHook(["expression"]), - /** @type {SyncBailHook<[ExpressionNode], boolean | void>} */ - expressionLogicalOperator: new SyncBailHook(["expression"]), - /** @type {SyncBailHook<[ProgramNode, CommentNode[]], boolean | void>} */ - program: new SyncBailHook(["ast", "comments"]), - /** @type {SyncBailHook<[ProgramNode, CommentNode[]], boolean | void>} */ - finish: new SyncBailHook(["ast", "comments"]) - }); - this.sourceType = sourceType; - /** @type {ScopeInfo} */ - this.scope = undefined; - /** @type {ParserState} */ - this.state = undefined; - this.comments = undefined; - this.semicolons = undefined; - /** @type {(StatementNode|ExpressionNode)[]} */ - this.statementPath = undefined; - this.prevStatement = undefined; - this.currentTagData = undefined; - this._initializeEvaluating(); + "};", + "", + withOnChunkLoad + ? `${ + RuntimeGlobals.onChunksLoaded + }.require = ${runtimeTemplate.returningFunction( + "installedChunks[chunkId]", + "chunkId" + )};` + : "// no on chunks loaded", + "", + withLoading || withExternalInstallChunk + ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [ + "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent([ + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ]), + "}" + ]), + "}", + `if(runtime) runtime(__webpack_require__);`, + "for(var i = 0; i < chunkIds.length; i++)", + Template.indent("installedChunks[chunkIds[i]] = 1;"), + withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" + ])};` + : "// no chunk install function needed", + "", + withLoading + ? Template.asString([ + "// require() chunk loading for javascript", + `${fn}.require = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasJsMatcher !== false + ? [ + '// "1" is the signal for "already loaded"', + "if(!installedChunks[chunkId]) {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent([ + `installChunk(require(${JSON.stringify( + rootOutputDir + )} + ${ + RuntimeGlobals.getChunkScriptFilename + }(chunkId)));` + ]), + "} else installedChunks[chunkId] = 1;", + "" + ]), + "}" + ] + : "installedChunks[chunkId] = 1;" + )};` + ]) + : "// no chunk loading", + "", + withExternalInstallChunk + ? Template.asString([ + "module.exports = __webpack_require__;", + `${RuntimeGlobals.externalInstallChunk} = installChunk;` + ]) + : "// no external install chunk", + "", + withHmr + ? Template.asString([ + "function loadUpdateChunk(chunkId, updatedModulesList) {", + Template.indent([ + `var update = require(${JSON.stringify(rootOutputDir)} + ${ + RuntimeGlobals.getChunkUpdateScriptFilename + }(chunkId));`, + "var updatedModules = update.modules;", + "var runtime = update.runtime;", + "for(var moduleId in updatedModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, + Template.indent([ + `currentUpdate[moduleId] = updatedModules[moduleId];`, + "if(updatedModulesList) updatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "if(runtime) currentUpdateRuntime.push(runtime);" + ]), + "}", + "", + Template.getFunctionContent( + require('./JavascriptHotModuleReplacement.runtime.js') + ) + .replace(/\$key\$/g, "require") + .replace(/\$installedChunks\$/g, "installedChunks") + .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") + .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) + .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) + .replace( + /\$ensureChunkHandlers\$/g, + RuntimeGlobals.ensureChunkHandlers + ) + .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) + .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) + .replace( + /\$hmrDownloadUpdateHandlers\$/g, + RuntimeGlobals.hmrDownloadUpdateHandlers + ) + .replace( + /\$hmrInvalidateModuleHandlers\$/g, + RuntimeGlobals.hmrInvalidateModuleHandlers + ) + ]) + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${RuntimeGlobals.hmrDownloadManifest} = function() {`, + Template.indent([ + "return Promise.resolve().then(function() {", + Template.indent([ + `return require(${JSON.stringify(rootOutputDir)} + ${ + RuntimeGlobals.getUpdateManifestFilename + }());` + ]), + "})['catch'](function(err) { if(err.code !== 'MODULE_NOT_FOUND') throw err; });" + ]), + "}" + ]) + : "// no HMR manifest" + ]); } +} - _initializeEvaluating() { - this.hooks.evaluate.for("Literal").tap("JavascriptParser", _expr => { - const expr = /** @type {LiteralNode} */ (_expr); +module.exports = RequireChunkLoadingRuntimeModule; - switch (typeof expr.value) { - case "number": - return new BasicEvaluatedExpression() - .setNumber(expr.value) - .setRange(expr.range); - case "bigint": - return new BasicEvaluatedExpression() - .setBigInt(expr.value) - .setRange(expr.range); - case "string": - return new BasicEvaluatedExpression() - .setString(expr.value) - .setRange(expr.range); - case "boolean": - return new BasicEvaluatedExpression() - .setBoolean(expr.value) - .setRange(expr.range); - } - if (expr.value === null) { - return new BasicEvaluatedExpression().setNull().setRange(expr.range); - } - if (expr.value instanceof RegExp) { - return new BasicEvaluatedExpression() - .setRegExp(expr.value) - .setRange(expr.range); - } - }); - this.hooks.evaluate.for("NewExpression").tap("JavascriptParser", _expr => { - const expr = /** @type {NewExpressionNode} */ (_expr); - const callee = expr.callee; - if ( - callee.type !== "Identifier" || - callee.name !== "RegExp" || - expr.arguments.length > 2 || - this.getVariableInfo("RegExp") !== "RegExp" - ) - return; - let regExp, flags; - const arg1 = expr.arguments[0]; +/***/ }), - if (arg1) { - if (arg1.type === "SpreadElement") return; +/***/ 91786: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const evaluatedRegExp = this.evaluateExpression(arg1); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (!evaluatedRegExp) return; - regExp = evaluatedRegExp.asString(); - if (!regExp) return; - } else { - return new BasicEvaluatedExpression() - .setRegExp(new RegExp("")) - .setRange(expr.range); - } +const util = __webpack_require__(73837); +const truncateArgs = __webpack_require__(62090); - const arg2 = expr.arguments[1]; +module.exports = ({ colors, appendOnly, stream }) => { + let currentStatusMessage = undefined; + let hasStatusMessage = false; + let currentIndent = ""; + let currentCollapsed = 0; - if (arg2) { - if (arg2.type === "SpreadElement") return; + const indent = (str, prefix, colorPrefix, colorSuffix) => { + if (str === "") return str; + prefix = currentIndent + prefix; + if (colors) { + return ( + prefix + + colorPrefix + + str.replace(/\n/g, colorSuffix + "\n" + prefix + colorPrefix) + + colorSuffix + ); + } else { + return prefix + str.replace(/\n/g, "\n" + prefix); + } + }; - const evaluatedFlags = this.evaluateExpression(arg2); + const clearStatusMessage = () => { + if (hasStatusMessage) { + stream.write("\x1b[2K\r"); + hasStatusMessage = false; + } + }; - if (!evaluatedFlags) return; + const writeStatusMessage = () => { + if (!currentStatusMessage) return; + const l = stream.columns; + const args = l + ? truncateArgs(currentStatusMessage, l - 1) + : currentStatusMessage; + const str = args.join(" "); + const coloredStr = `\u001b[1m${str}\u001b[39m\u001b[22m`; + stream.write(`\x1b[2K\r${coloredStr}`); + hasStatusMessage = true; + }; - if (!evaluatedFlags.isUndefined()) { - flags = evaluatedFlags.asString(); + const writeColored = (prefix, colorPrefix, colorSuffix) => { + return (...args) => { + if (currentCollapsed > 0) return; + clearStatusMessage(); + const str = indent( + util.format(...args), + prefix, + colorPrefix, + colorSuffix + ); + stream.write(str + "\n"); + writeStatusMessage(); + }; + }; - if ( - flags === undefined || - !BasicEvaluatedExpression.isValidRegExpFlags(flags) - ) - return; - } + const writeGroupMessage = writeColored( + "<-> ", + "\u001b[1m\u001b[36m", + "\u001b[39m\u001b[22m" + ); + + const writeGroupCollapsedMessage = writeColored( + "<+> ", + "\u001b[1m\u001b[36m", + "\u001b[39m\u001b[22m" + ); + + return { + log: writeColored(" ", "\u001b[1m", "\u001b[22m"), + debug: writeColored(" ", "", ""), + trace: writeColored(" ", "", ""), + info: writeColored(" ", "\u001b[1m\u001b[32m", "\u001b[39m\u001b[22m"), + warn: writeColored(" ", "\u001b[1m\u001b[33m", "\u001b[39m\u001b[22m"), + error: writeColored(" ", "\u001b[1m\u001b[31m", "\u001b[39m\u001b[22m"), + logTime: writeColored( + " ", + "\u001b[1m\u001b[35m", + "\u001b[39m\u001b[22m" + ), + group: (...args) => { + writeGroupMessage(...args); + if (currentCollapsed > 0) { + currentCollapsed++; + } else { + currentIndent += " "; } + }, + groupCollapsed: (...args) => { + writeGroupCollapsedMessage(...args); + currentCollapsed++; + }, + groupEnd: () => { + if (currentCollapsed > 0) currentCollapsed--; + else if (currentIndent.length >= 2) + currentIndent = currentIndent.slice(0, currentIndent.length - 2); + }, + // eslint-disable-next-line node/no-unsupported-features/node-builtins + profile: console.profile && (name => console.profile(name)), + // eslint-disable-next-line node/no-unsupported-features/node-builtins + profileEnd: console.profileEnd && (name => console.profileEnd(name)), + clear: + !appendOnly && + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.clear && + (() => { + clearStatusMessage(); + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.clear(); + writeStatusMessage(); + }), + status: appendOnly + ? writeColored(" ", "", "") + : (name, ...args) => { + args = args.filter(Boolean); + if (name === undefined && args.length === 0) { + clearStatusMessage(); + currentStatusMessage = undefined; + } else if ( + typeof name === "string" && + name.startsWith("[webpack.Progress] ") + ) { + currentStatusMessage = [name.slice(19), ...args]; + writeStatusMessage(); + } else if (name === "[webpack.Progress]") { + currentStatusMessage = [...args]; + writeStatusMessage(); + } else { + currentStatusMessage = [name, ...args]; + writeStatusMessage(); + } + } + }; +}; - return new BasicEvaluatedExpression() - .setRegExp(flags ? new RegExp(regExp, flags) : new RegExp(regExp)) - .setRange(expr.range); - }); - this.hooks.evaluate - .for("LogicalExpression") - .tap("JavascriptParser", _expr => { - const expr = /** @type {LogicalExpressionNode} */ (_expr); - const left = this.evaluateExpression(expr.left); - if (!left) return; - let returnRight = false; - /** @type {boolean|undefined} */ - let allowedRight; - if (expr.operator === "&&") { - const leftAsBool = left.asBool(); - if (leftAsBool === false) return left.setRange(expr.range); - returnRight = leftAsBool === true; - allowedRight = false; - } else if (expr.operator === "||") { - const leftAsBool = left.asBool(); - if (leftAsBool === true) return left.setRange(expr.range); - returnRight = leftAsBool === false; - allowedRight = true; - } else if (expr.operator === "??") { - const leftAsNullish = left.asNullish(); - if (leftAsNullish === false) return left.setRange(expr.range); - if (leftAsNullish !== true) return; - returnRight = true; - } else return; - const right = this.evaluateExpression(expr.right); - if (!right) return; - if (returnRight) { - if (left.couldHaveSideEffects()) right.setSideEffects(); - return right.setRange(expr.range); - } +/***/ }), - const asBool = right.asBool(); +/***/ 64395: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (allowedRight === true && asBool === true) { - return new BasicEvaluatedExpression() - .setRange(expr.range) - .setTruthy(); - } else if (allowedRight === false && asBool === false) { - return new BasicEvaluatedExpression().setRange(expr.range).setFalsy(); - } - }); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const valueAsExpression = (value, expr, sideEffects) => { - switch (typeof value) { - case "boolean": - return new BasicEvaluatedExpression() - .setBoolean(value) - .setSideEffects(sideEffects) - .setRange(expr.range); - case "number": - return new BasicEvaluatedExpression() - .setNumber(value) - .setSideEffects(sideEffects) - .setRange(expr.range); - case "bigint": - return new BasicEvaluatedExpression() - .setBigInt(value) - .setSideEffects(sideEffects) - .setRange(expr.range); - case "string": - return new BasicEvaluatedExpression() - .setString(value) - .setSideEffects(sideEffects) - .setRange(expr.range); - } - }; - this.hooks.evaluate - .for("BinaryExpression") - .tap("JavascriptParser", _expr => { - const expr = /** @type {BinaryExpressionNode} */ (_expr); - const handleConstOperation = fn => { - const left = this.evaluateExpression(expr.left); - if (!left || !left.isCompileTimeValue()) return; +const { STAGE_ADVANCED } = __webpack_require__(80057); - const right = this.evaluateExpression(expr.right); - if (!right || !right.isCompileTimeValue()) return; +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ - const result = fn( - left.asCompileTimeValue(), - right.asCompileTimeValue() - ); - return valueAsExpression( - result, - expr, - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - }; +class AggressiveMergingPlugin { + constructor(options) { + if ( + (options !== undefined && typeof options !== "object") || + Array.isArray(options) + ) { + throw new Error( + "Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see https://webpack.js.org/plugins/" + ); + } + this.options = options || {}; + } - const isAlwaysDifferent = (a, b) => - (a === true && b === false) || (a === false && b === true); + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const options = this.options; + const minSizeReduce = options.minSizeReduce || 1.5; - const handleTemplateStringCompare = (left, right, res, eql) => { - const getPrefix = parts => { - let value = ""; - for (const p of parts) { - const v = p.asString(); - if (v !== undefined) value += v; - else break; - } - return value; - }; - const getSuffix = parts => { - let value = ""; - for (let i = parts.length - 1; i >= 0; i--) { - const v = parts[i].asString(); - if (v !== undefined) value = v + value; - else break; + compiler.hooks.thisCompilation.tap( + "AggressiveMergingPlugin", + compilation => { + compilation.hooks.optimizeChunks.tap( + { + name: "AggressiveMergingPlugin", + stage: STAGE_ADVANCED + }, + chunks => { + const chunkGraph = compilation.chunkGraph; + /** @type {{a: Chunk, b: Chunk, improvement: number}[]} */ + let combinations = []; + for (const a of chunks) { + if (a.canBeInitial()) continue; + for (const b of chunks) { + if (b.canBeInitial()) continue; + if (b === a) break; + if (!chunkGraph.canChunksBeIntegrated(a, b)) { + continue; + } + const aSize = chunkGraph.getChunkSize(b, { + chunkOverhead: 0 + }); + const bSize = chunkGraph.getChunkSize(a, { + chunkOverhead: 0 + }); + const abSize = chunkGraph.getIntegratedChunksSize(b, a, { + chunkOverhead: 0 + }); + const improvement = (aSize + bSize) / abSize; + combinations.push({ + a, + b, + improvement + }); + } } - return value; - }; - const leftPrefix = getPrefix(left.parts); - const rightPrefix = getPrefix(right.parts); - const leftSuffix = getSuffix(left.parts); - const rightSuffix = getSuffix(right.parts); - const lenPrefix = Math.min(leftPrefix.length, rightPrefix.length); - const lenSuffix = Math.min(leftSuffix.length, rightSuffix.length); - if ( - leftPrefix.slice(0, lenPrefix) !== - rightPrefix.slice(0, lenPrefix) || - leftSuffix.slice(-lenSuffix) !== rightSuffix.slice(-lenSuffix) - ) { - return res - .setBoolean(!eql) - .setSideEffects( - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - } - }; - const handleStrictEqualityComparison = eql => { - const left = this.evaluateExpression(expr.left); - if (!left) return; - const right = this.evaluateExpression(expr.right); - if (!right) return; - const res = new BasicEvaluatedExpression(); - res.setRange(expr.range); + combinations.sort((a, b) => { + return b.improvement - a.improvement; + }); - const leftConst = left.isCompileTimeValue(); - const rightConst = right.isCompileTimeValue(); + const pair = combinations[0]; - if (leftConst && rightConst) { - return res - .setBoolean( - eql === - (left.asCompileTimeValue() === right.asCompileTimeValue()) - ) - .setSideEffects( - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - } + if (!pair) return; + if (pair.improvement < minSizeReduce) return; - if (left.isArray() && right.isArray()) { - return res - .setBoolean(!eql) - .setSideEffects( - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - } - if (left.isTemplateString() && right.isTemplateString()) { - return handleTemplateStringCompare(left, right, res, eql); + chunkGraph.integrateChunks(pair.b, pair.a); + compilation.chunks.delete(pair.a); + return true; } + ); + } + ); + } +} - const leftPrimitive = left.isPrimitiveType(); - const rightPrimitive = right.isPrimitiveType(); +module.exports = AggressiveMergingPlugin; - if ( - // Primitive !== Object or - // compile-time object types are never equal to something at runtime - (leftPrimitive === false && - (leftConst || rightPrimitive === true)) || - (rightPrimitive === false && - (rightConst || leftPrimitive === true)) || - // Different nullish or boolish status also means not equal - isAlwaysDifferent(left.asBool(), right.asBool()) || - isAlwaysDifferent(left.asNullish(), right.asNullish()) - ) { - return res - .setBoolean(!eql) - .setSideEffects( - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - } - }; - const handleAbstractEqualityComparison = eql => { - const left = this.evaluateExpression(expr.left); - if (!left) return; - const right = this.evaluateExpression(expr.right); - if (!right) return; - const res = new BasicEvaluatedExpression(); - res.setRange(expr.range); +/***/ }), - const leftConst = left.isCompileTimeValue(); - const rightConst = right.isCompileTimeValue(); +/***/ 15543: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (leftConst && rightConst) { - return res - .setBoolean( - eql === - // eslint-disable-next-line eqeqeq - (left.asCompileTimeValue() == right.asCompileTimeValue()) - ) - .setSideEffects( - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (left.isArray() && right.isArray()) { - return res - .setBoolean(!eql) - .setSideEffects( - left.couldHaveSideEffects() || right.couldHaveSideEffects() - ); - } - if (left.isTemplateString() && right.isTemplateString()) { - return handleTemplateStringCompare(left, right, res, eql); - } - }; - if (expr.operator === "+") { - const left = this.evaluateExpression(expr.left); - if (!left) return; - const right = this.evaluateExpression(expr.right); - if (!right) return; - const res = new BasicEvaluatedExpression(); - if (left.isString()) { - if (right.isString()) { - res.setString(left.string + right.string); - } else if (right.isNumber()) { - res.setString(left.string + right.number); - } else if ( - right.isWrapped() && - right.prefix && - right.prefix.isString() - ) { - // "left" + ("prefix" + inner + "postfix") - // => ("leftPrefix" + inner + "postfix") - res.setWrapped( - new BasicEvaluatedExpression() - .setString(left.string + right.prefix.string) - .setRange(joinRanges(left.range, right.prefix.range)), - right.postfix, - right.wrappedInnerExpressions - ); - } else if (right.isWrapped()) { - // "left" + ([null] + inner + "postfix") - // => ("left" + inner + "postfix") - res.setWrapped( - left, - right.postfix, - right.wrappedInnerExpressions + +const { STAGE_ADVANCED } = __webpack_require__(80057); +const { intersect } = __webpack_require__(93347); +const { + compareModulesByIdentifier, + compareChunks +} = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); +const identifierUtils = __webpack_require__(82186); + +/** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +const validate = createSchemaValidation( + __webpack_require__(32697), + () => + __webpack_require__(47995), + { + name: "Aggressive Splitting Plugin", + baseDataPath: "options" + } +); + +const moveModuleBetween = (chunkGraph, oldChunk, newChunk) => { + return module => { + chunkGraph.disconnectChunkAndModule(oldChunk, module); + chunkGraph.connectChunkAndModule(newChunk, module); + }; +}; + +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk} chunk the chunk + * @returns {function(Module): boolean} filter for entry module + */ +const isNotAEntryModule = (chunkGraph, chunk) => { + return module => { + return !chunkGraph.isEntryModuleInChunk(module, chunk); + }; +}; + +/** @type {WeakSet} */ +const recordedChunks = new WeakSet(); + +class AggressiveSplittingPlugin { + /** + * @param {AggressiveSplittingPluginOptions=} options options object + */ + constructor(options = {}) { + validate(options); + + this.options = options; + if (typeof this.options.minSize !== "number") { + this.options.minSize = 30 * 1024; + } + if (typeof this.options.maxSize !== "number") { + this.options.maxSize = 50 * 1024; + } + if (typeof this.options.chunkOverhead !== "number") { + this.options.chunkOverhead = 0; + } + if (typeof this.options.entryChunkMultiplicator !== "number") { + this.options.entryChunkMultiplicator = 1; + } + } + + /** + * @param {Chunk} chunk the chunk to test + * @returns {boolean} true if the chunk was recorded + */ + static wasChunkRecorded(chunk) { + return recordedChunks.has(chunk); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "AggressiveSplittingPlugin", + compilation => { + let needAdditionalSeal = false; + let newSplits; + let fromAggressiveSplittingSet; + let chunkSplitDataMap; + compilation.hooks.optimize.tap("AggressiveSplittingPlugin", () => { + newSplits = []; + fromAggressiveSplittingSet = new Set(); + chunkSplitDataMap = new Map(); + }); + compilation.hooks.optimizeChunks.tap( + { + name: "AggressiveSplittingPlugin", + stage: STAGE_ADVANCED + }, + chunks => { + const chunkGraph = compilation.chunkGraph; + // Precompute stuff + const nameToModuleMap = new Map(); + const moduleToNameMap = new Map(); + const makePathsRelative = + identifierUtils.makePathsRelative.bindContextCache( + compiler.context, + compiler.root ); - } else { - // "left" + expr - // => ("left" + expr + "") - res.setWrapped(left, null, [right]); - } - } else if (left.isNumber()) { - if (right.isString()) { - res.setString(left.number + right.string); - } else if (right.isNumber()) { - res.setNumber(left.number + right.number); - } else { - return; + for (const m of compilation.modules) { + const name = makePathsRelative(m.identifier()); + nameToModuleMap.set(name, m); + moduleToNameMap.set(m, name); } - } else if (left.isBigInt()) { - if (right.isBigInt()) { - res.setBigInt(left.bigint + right.bigint); + + // Check used chunk ids + const usedIds = new Set(); + for (const chunk of chunks) { + usedIds.add(chunk.id); } - } else if (left.isWrapped()) { - if (left.postfix && left.postfix.isString() && right.isString()) { - // ("prefix" + inner + "postfix") + "right" - // => ("prefix" + inner + "postfixRight") - res.setWrapped( - left.prefix, - new BasicEvaluatedExpression() - .setString(left.postfix.string + right.string) - .setRange(joinRanges(left.postfix.range, right.range)), - left.wrappedInnerExpressions - ); - } else if ( - left.postfix && - left.postfix.isString() && - right.isNumber() - ) { - // ("prefix" + inner + "postfix") + 123 - // => ("prefix" + inner + "postfix123") - res.setWrapped( - left.prefix, - new BasicEvaluatedExpression() - .setString(left.postfix.string + right.number) - .setRange(joinRanges(left.postfix.range, right.range)), - left.wrappedInnerExpressions - ); - } else if (right.isString()) { - // ("prefix" + inner + [null]) + "right" - // => ("prefix" + inner + "right") - res.setWrapped(left.prefix, right, left.wrappedInnerExpressions); - } else if (right.isNumber()) { - // ("prefix" + inner + [null]) + 123 - // => ("prefix" + inner + "123") - res.setWrapped( - left.prefix, - new BasicEvaluatedExpression() - .setString(right.number + "") - .setRange(right.range), - left.wrappedInnerExpressions - ); - } else if (right.isWrapped()) { - // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2") - // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2") - res.setWrapped( - left.prefix, - right.postfix, - left.wrappedInnerExpressions && - right.wrappedInnerExpressions && - left.wrappedInnerExpressions - .concat(left.postfix ? [left.postfix] : []) - .concat(right.prefix ? [right.prefix] : []) - .concat(right.wrappedInnerExpressions) - ); - } else { - // ("prefix" + inner + postfix) + expr - // => ("prefix" + inner + postfix + expr + [null]) - res.setWrapped( - left.prefix, - null, - left.wrappedInnerExpressions && - left.wrappedInnerExpressions.concat( - left.postfix ? [left.postfix, right] : [right] - ) - ); - } - } else { - if (right.isString()) { - // left + "right" - // => ([null] + left + "right") - res.setWrapped(null, right, [left]); - } else if (right.isWrapped()) { - // left + (prefix + inner + "postfix") - // => ([null] + left + prefix + inner + "postfix") - res.setWrapped( - null, - right.postfix, - right.wrappedInnerExpressions && - (right.prefix ? [left, right.prefix] : [left]).concat( - right.wrappedInnerExpressions - ) + + const recordedSplits = + (compilation.records && compilation.records.aggressiveSplits) || + []; + const usedSplits = newSplits + ? recordedSplits.concat(newSplits) + : recordedSplits; + + const minSize = this.options.minSize; + const maxSize = this.options.maxSize; + + const applySplit = splitData => { + // Cannot split if id is already taken + if (splitData.id !== undefined && usedIds.has(splitData.id)) { + return false; + } + + // Get module objects from names + const selectedModules = splitData.modules.map(name => + nameToModuleMap.get(name) ); - } else { - return; - } - } - if (left.couldHaveSideEffects() || right.couldHaveSideEffects()) - res.setSideEffects(); - res.setRange(expr.range); - return res; - } else if (expr.operator === "-") { - return handleConstOperation((l, r) => l - r); - } else if (expr.operator === "*") { - return handleConstOperation((l, r) => l * r); - } else if (expr.operator === "/") { - return handleConstOperation((l, r) => l / r); - } else if (expr.operator === "**") { - return handleConstOperation((l, r) => l ** r); - } else if (expr.operator === "===") { - return handleStrictEqualityComparison(true); - } else if (expr.operator === "==") { - return handleAbstractEqualityComparison(true); - } else if (expr.operator === "!==") { - return handleStrictEqualityComparison(false); - } else if (expr.operator === "!=") { - return handleAbstractEqualityComparison(false); - } else if (expr.operator === "&") { - return handleConstOperation((l, r) => l & r); - } else if (expr.operator === "|") { - return handleConstOperation((l, r) => l | r); - } else if (expr.operator === "^") { - return handleConstOperation((l, r) => l ^ r); - } else if (expr.operator === ">>>") { - return handleConstOperation((l, r) => l >>> r); - } else if (expr.operator === ">>") { - return handleConstOperation((l, r) => l >> r); - } else if (expr.operator === "<<") { - return handleConstOperation((l, r) => l << r); - } else if (expr.operator === "<") { - return handleConstOperation((l, r) => l < r); - } else if (expr.operator === ">") { - return handleConstOperation((l, r) => l > r); - } else if (expr.operator === "<=") { - return handleConstOperation((l, r) => l <= r); - } else if (expr.operator === ">=") { - return handleConstOperation((l, r) => l >= r); - } - }); - this.hooks.evaluate - .for("UnaryExpression") - .tap("JavascriptParser", _expr => { - const expr = /** @type {UnaryExpressionNode} */ (_expr); - const handleConstOperation = fn => { - const argument = this.evaluateExpression(expr.argument); - if (!argument || !argument.isCompileTimeValue()) return; - const result = fn(argument.asCompileTimeValue()); - return valueAsExpression( - result, - expr, - argument.couldHaveSideEffects() - ); - }; + // Does the modules exist at all? + if (!selectedModules.every(Boolean)) return false; - if (expr.operator === "typeof") { - switch (expr.argument.type) { - case "Identifier": { - const res = this.callHooksForName( - this.hooks.evaluateTypeof, - expr.argument.name, - expr + // Check if size matches (faster than waiting for hash) + let size = 0; + for (const m of selectedModules) size += m.size(); + if (size !== splitData.size) return false; + + // get chunks with all modules + const selectedChunks = intersect( + selectedModules.map( + m => new Set(chunkGraph.getModuleChunksIterable(m)) + ) ); - if (res !== undefined) return res; - break; + + // No relevant chunks found + if (selectedChunks.size === 0) return false; + + // The found chunk is already the split or similar + if ( + selectedChunks.size === 1 && + chunkGraph.getNumberOfChunkModules( + Array.from(selectedChunks)[0] + ) === selectedModules.length + ) { + const chunk = Array.from(selectedChunks)[0]; + if (fromAggressiveSplittingSet.has(chunk)) return false; + fromAggressiveSplittingSet.add(chunk); + chunkSplitDataMap.set(chunk, splitData); + return true; + } + + // split the chunk into two parts + const newChunk = compilation.addChunk(); + newChunk.chunkReason = "aggressive splitted"; + for (const chunk of selectedChunks) { + selectedModules.forEach( + moveModuleBetween(chunkGraph, chunk, newChunk) + ); + chunk.split(newChunk); + chunk.name = null; + } + fromAggressiveSplittingSet.add(newChunk); + chunkSplitDataMap.set(newChunk, splitData); + + if (splitData.id !== null && splitData.id !== undefined) { + newChunk.id = splitData.id; + newChunk.ids = [splitData.id]; + } + return true; + }; + + // try to restore to recorded splitting + let changed = false; + for (let j = 0; j < usedSplits.length; j++) { + const splitData = usedSplits[j]; + if (applySplit(splitData)) changed = true; } - case "MetaProperty": { - const res = this.callHooksForName( - this.hooks.evaluateTypeof, - getRootName(expr.argument), - expr - ); - if (res !== undefined) return res; - break; + + // for any chunk which isn't splitted yet, split it and create a new entry + // start with the biggest chunk + const cmpFn = compareChunks(chunkGraph); + const sortedChunks = Array.from(chunks).sort((a, b) => { + const diff1 = + chunkGraph.getChunkModulesSize(b) - + chunkGraph.getChunkModulesSize(a); + if (diff1) return diff1; + const diff2 = + chunkGraph.getNumberOfChunkModules(a) - + chunkGraph.getNumberOfChunkModules(b); + if (diff2) return diff2; + return cmpFn(a, b); + }); + for (const chunk of sortedChunks) { + if (fromAggressiveSplittingSet.has(chunk)) continue; + const size = chunkGraph.getChunkModulesSize(chunk); + if ( + size > maxSize && + chunkGraph.getNumberOfChunkModules(chunk) > 1 + ) { + const modules = chunkGraph + .getOrderedChunkModules(chunk, compareModulesByIdentifier) + .filter(isNotAEntryModule(chunkGraph, chunk)); + const selectedModules = []; + let selectedModulesSize = 0; + for (let k = 0; k < modules.length; k++) { + const module = modules[k]; + const newSize = selectedModulesSize + module.size(); + if (newSize > maxSize && selectedModulesSize >= minSize) { + break; + } + selectedModulesSize = newSize; + selectedModules.push(module); + } + if (selectedModules.length === 0) continue; + const splitData = { + modules: selectedModules + .map(m => moduleToNameMap.get(m)) + .sort(), + size: selectedModulesSize + }; + + if (applySplit(splitData)) { + newSplits = (newSplits || []).concat(splitData); + changed = true; + } + } } - case "MemberExpression": { - const res = this.callHooksForExpression( - this.hooks.evaluateTypeof, - expr.argument, - expr - ); - if (res !== undefined) return res; - break; + if (changed) return true; + } + ); + compilation.hooks.recordHash.tap( + "AggressiveSplittingPlugin", + records => { + // 4. save made splittings to records + const allSplits = new Set(); + const invalidSplits = new Set(); + + // Check if some splittings are invalid + // We remove invalid splittings and try again + for (const chunk of compilation.chunks) { + const splitData = chunkSplitDataMap.get(chunk); + if (splitData !== undefined) { + if (splitData.hash && chunk.hash !== splitData.hash) { + // Split was successful, but hash doesn't equal + // We can throw away the split since it's useless now + invalidSplits.add(splitData); + } + } } - case "ChainExpression": { - const res = this.callHooksForExpression( - this.hooks.evaluateTypeof, - expr.argument.expression, - expr + + if (invalidSplits.size > 0) { + records.aggressiveSplits = records.aggressiveSplits.filter( + splitData => !invalidSplits.has(splitData) ); - if (res !== undefined) return res; - break; - } - case "FunctionExpression": { - return new BasicEvaluatedExpression() - .setString("function") - .setRange(expr.range); - } - } - const arg = this.evaluateExpression(expr.argument); - if (arg.isUnknown()) return; - if (arg.isString()) { - return new BasicEvaluatedExpression() - .setString("string") - .setRange(expr.range); - } - if (arg.isWrapped()) { - return new BasicEvaluatedExpression() - .setString("string") - .setSideEffects() - .setRange(expr.range); - } - if (arg.isUndefined()) { - return new BasicEvaluatedExpression() - .setString("undefined") - .setRange(expr.range); - } - if (arg.isNumber()) { - return new BasicEvaluatedExpression() - .setString("number") - .setRange(expr.range); - } - if (arg.isBigInt()) { - return new BasicEvaluatedExpression() - .setString("bigint") - .setRange(expr.range); - } - if (arg.isBoolean()) { - return new BasicEvaluatedExpression() - .setString("boolean") - .setRange(expr.range); - } - if (arg.isConstArray() || arg.isRegExp() || arg.isNull()) { - return new BasicEvaluatedExpression() - .setString("object") - .setRange(expr.range); - } - if (arg.isArray()) { - return new BasicEvaluatedExpression() - .setString("object") - .setSideEffects(arg.couldHaveSideEffects()) - .setRange(expr.range); - } - } else if (expr.operator === "!") { - const argument = this.evaluateExpression(expr.argument); - if (!argument) return; - const bool = argument.asBool(); - if (typeof bool !== "boolean") return; - return new BasicEvaluatedExpression() - .setBoolean(!bool) - .setSideEffects(argument.couldHaveSideEffects()) - .setRange(expr.range); - } else if (expr.operator === "~") { - return handleConstOperation(v => ~v); - } else if (expr.operator === "+") { - return handleConstOperation(v => +v); - } else if (expr.operator === "-") { - return handleConstOperation(v => -v); - } - }); - this.hooks.evaluateTypeof.for("undefined").tap("JavascriptParser", expr => { - return new BasicEvaluatedExpression() - .setString("undefined") - .setRange(expr.range); - }); - this.hooks.evaluate.for("Identifier").tap("JavascriptParser", expr => { - if (/** @type {IdentifierNode} */ (expr).name === "undefined") { - return new BasicEvaluatedExpression() - .setUndefined() - .setRange(expr.range); - } - }); - /** - * @param {string} exprType expression type name - * @param {function(ExpressionNode): GetInfoResult | undefined} getInfo get info - * @returns {void} - */ - const tapEvaluateWithVariableInfo = (exprType, getInfo) => { - /** @type {ExpressionNode | undefined} */ - let cachedExpression = undefined; - /** @type {GetInfoResult | undefined} */ - let cachedInfo = undefined; - this.hooks.evaluate.for(exprType).tap("JavascriptParser", expr => { - const expression = /** @type {MemberExpressionNode} */ (expr); + needAdditionalSeal = true; + } else { + // set hash and id values on all (new) splittings + for (const chunk of compilation.chunks) { + const splitData = chunkSplitDataMap.get(chunk); + if (splitData !== undefined) { + splitData.hash = chunk.hash; + splitData.id = chunk.id; + allSplits.add(splitData); + // set flag for stats + recordedChunks.add(chunk); + } + } - const info = getInfo(expr); - if (info !== undefined) { - return this.callHooksForInfoWithFallback( - this.hooks.evaluateIdentifier, - info.name, - name => { - cachedExpression = expression; - cachedInfo = info; - }, - name => { - const hook = this.hooks.evaluateDefinedIdentifier.get(name); - if (hook !== undefined) { - return hook.call(expression); + // Also add all unused historical splits (after the used ones) + // They can still be used in some future compilation + const recordedSplits = + compilation.records && compilation.records.aggressiveSplits; + if (recordedSplits) { + for (const splitData of recordedSplits) { + if (!invalidSplits.has(splitData)) allSplits.add(splitData); + } } - }, - expression - ); - } - }); - this.hooks.evaluate - .for(exprType) - .tap({ name: "JavascriptParser", stage: 100 }, expr => { - const info = cachedExpression === expr ? cachedInfo : getInfo(expr); - if (info !== undefined) { - return new BasicEvaluatedExpression() - .setIdentifier(info.name, info.rootInfo, info.getMembers) - .setRange(expr.range); + + // record all splits + records.aggressiveSplits = Array.from(allSplits); + + needAdditionalSeal = false; + } } - }); - this.hooks.finish.tap("JavascriptParser", () => { - // Cleanup for GC - cachedExpression = cachedInfo = undefined; - }); - }; - tapEvaluateWithVariableInfo("Identifier", expr => { - const info = this.getVariableInfo( - /** @type {IdentifierNode} */ (expr).name - ); - if ( - typeof info === "string" || - (info instanceof VariableInfo && typeof info.freeName === "string") - ) { - return { name: info, rootInfo: info, getMembers: () => [] }; - } - }); - tapEvaluateWithVariableInfo("ThisExpression", expr => { - const info = this.getVariableInfo("this"); - if ( - typeof info === "string" || - (info instanceof VariableInfo && typeof info.freeName === "string") - ) { - return { name: info, rootInfo: info, getMembers: () => [] }; + ); + compilation.hooks.needAdditionalSeal.tap( + "AggressiveSplittingPlugin", + () => { + if (needAdditionalSeal) { + needAdditionalSeal = false; + return true; + } + } + ); } - }); - this.hooks.evaluate.for("MetaProperty").tap("JavascriptParser", expr => { - const metaProperty = /** @type {MetaPropertyNode} */ (expr); - - return this.callHooksForName( - this.hooks.evaluateIdentifier, - getRootName(expr), - metaProperty - ); - }); - tapEvaluateWithVariableInfo("MemberExpression", expr => - this.getMemberExpressionInfo( - /** @type {MemberExpressionNode} */ (expr), - ALLOWED_MEMBER_TYPES_EXPRESSION - ) ); + } +} +module.exports = AggressiveSplittingPlugin; - this.hooks.evaluate.for("CallExpression").tap("JavascriptParser", _expr => { - const expr = /** @type {CallExpressionNode} */ (_expr); - if ( - expr.callee.type !== "MemberExpression" || - expr.callee.property.type !== - (expr.callee.computed ? "Literal" : "Identifier") - ) { - return; - } - // type Super also possible here - const param = this.evaluateExpression( - /** @type {ExpressionNode} */ (expr.callee.object) - ); - if (!param) return; - const property = - expr.callee.property.type === "Literal" - ? `${expr.callee.property.value}` - : expr.callee.property.name; - const hook = this.hooks.evaluateCallExpressionMember.get(property); - if (hook !== undefined) { - return hook.call(expr, param); - } - }); - this.hooks.evaluateCallExpressionMember - .for("indexOf") - .tap("JavascriptParser", (expr, param) => { - if (!param.isString()) return; - if (expr.arguments.length === 0) return; - const [arg1, arg2] = expr.arguments; - if (arg1.type === "SpreadElement") return; - const arg1Eval = this.evaluateExpression(arg1); - if (!arg1Eval.isString()) return; - const arg1Value = arg1Eval.string; +/***/ }), - let result; - if (arg2) { - if (arg2.type === "SpreadElement") return; - const arg2Eval = this.evaluateExpression(arg2); - if (!arg2Eval.isNumber()) return; - result = param.string.indexOf(arg1Value, arg2Eval.number); - } else { - result = param.string.indexOf(arg1Value); - } - return new BasicEvaluatedExpression() - .setNumber(result) - .setSideEffects(param.couldHaveSideEffects()) - .setRange(expr.range); - }); - this.hooks.evaluateCallExpressionMember - .for("replace") - .tap("JavascriptParser", (expr, param) => { - if (!param.isString()) return; - if (expr.arguments.length !== 2) return; - if (expr.arguments[0].type === "SpreadElement") return; - if (expr.arguments[1].type === "SpreadElement") return; - let arg1 = this.evaluateExpression(expr.arguments[0]); - let arg2 = this.evaluateExpression(expr.arguments[1]); - if (!arg1.isString() && !arg1.isRegExp()) return; - const arg1Value = arg1.regExp || arg1.string; - if (!arg2.isString()) return; - const arg2Value = arg2.string; - return new BasicEvaluatedExpression() - .setString(param.string.replace(arg1Value, arg2Value)) - .setSideEffects(param.couldHaveSideEffects()) - .setRange(expr.range); - }); - ["substr", "substring", "slice"].forEach(fn => { - this.hooks.evaluateCallExpressionMember - .for(fn) - .tap("JavascriptParser", (expr, param) => { - if (!param.isString()) return; - let arg1; - let result, - str = param.string; - switch (expr.arguments.length) { - case 1: - if (expr.arguments[0].type === "SpreadElement") return; - arg1 = this.evaluateExpression(expr.arguments[0]); - if (!arg1.isNumber()) return; - result = str[fn](arg1.number); - break; - case 2: { - if (expr.arguments[0].type === "SpreadElement") return; - if (expr.arguments[1].type === "SpreadElement") return; - arg1 = this.evaluateExpression(expr.arguments[0]); - const arg2 = this.evaluateExpression(expr.arguments[1]); - if (!arg1.isNumber()) return; - if (!arg2.isNumber()) return; - result = str[fn](arg1.number, arg2.number); - break; - } - default: - return; - } - return new BasicEvaluatedExpression() - .setString(result) - .setSideEffects(param.couldHaveSideEffects()) - .setRange(expr.range); - }); - }); +/***/ 97198: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @param {"cooked" | "raw"} kind kind of values to get - * @param {TemplateLiteralNode} templateLiteralExpr TemplateLiteral expr - * @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template - */ - const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => { - /** @type {BasicEvaluatedExpression[]} */ - const quasis = []; - /** @type {BasicEvaluatedExpression[]} */ - const parts = []; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - for (let i = 0; i < templateLiteralExpr.quasis.length; i++) { - const quasiExpr = templateLiteralExpr.quasis[i]; - const quasi = quasiExpr.value[kind]; - if (i > 0) { - const prevExpr = parts[parts.length - 1]; - const expr = this.evaluateExpression( - templateLiteralExpr.expressions[i - 1] - ); - const exprAsString = expr.asString(); - if ( - typeof exprAsString === "string" && - !expr.couldHaveSideEffects() - ) { - // We can merge quasi + expr + quasi when expr - // is a const string - prevExpr.setString(prevExpr.string + exprAsString + quasi); - prevExpr.setRange([prevExpr.range[0], quasiExpr.range[1]]); - // We unset the expression as it doesn't match to a single expression - prevExpr.setExpression(undefined); - continue; - } - parts.push(expr); - } +const eslintScope = __webpack_require__(36007); +const Referencer = __webpack_require__(44585); +const { + CachedSource, + ConcatSource, + ReplaceSource +} = __webpack_require__(51255); +const ConcatenationScope = __webpack_require__(98229); +const { UsageState } = __webpack_require__(63686); +const Module = __webpack_require__(73208); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const HarmonyImportDependency = __webpack_require__(57154); +const JavascriptParser = __webpack_require__(29050); +const { equals } = __webpack_require__(84953); +const LazySet = __webpack_require__(38938); +const { concatComparators, keepOriginalOrder } = __webpack_require__(29579); +const createHash = __webpack_require__(49835); +const { makePathsRelative } = __webpack_require__(82186); +const makeSerializable = __webpack_require__(33032); +const propertyAccess = __webpack_require__(54190); +const { + filterRuntime, + intersectRuntime, + mergeRuntimeCondition, + mergeRuntimeConditionNonFalse, + runtimeConditionToString, + subtractRuntimeCondition +} = __webpack_require__(17156); - const part = new BasicEvaluatedExpression() - .setString(quasi) - .setRange(quasiExpr.range) - .setExpression(quasiExpr); - quasis.push(part); - parts.push(part); - } - return { - quasis, - parts - }; - }; +/** @typedef {import("eslint-scope").Scope} Scope */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ +/** @template T @typedef {import("../InitFragment")} InitFragment */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {typeof import("../util/Hash")} HashConstructor */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - this.hooks.evaluate - .for("TemplateLiteral") - .tap("JavascriptParser", _node => { - const node = /** @type {TemplateLiteralNode} */ (_node); +// fix eslint-scope to support class properties correctly +// cspell:word Referencer +const ReferencerClass = Referencer; +if (!ReferencerClass.prototype.PropertyDefinition) { + ReferencerClass.prototype.PropertyDefinition = + ReferencerClass.prototype.Property; +} - const { quasis, parts } = getSimplifiedTemplateResult("cooked", node); - if (parts.length === 1) { - return parts[0].setRange(node.range); - } - return new BasicEvaluatedExpression() - .setTemplateString(quasis, parts, "cooked") - .setRange(node.range); - }); - this.hooks.evaluate - .for("TaggedTemplateExpression") - .tap("JavascriptParser", _node => { - const node = /** @type {TaggedTemplateExpressionNode} */ (_node); - const tag = this.evaluateExpression(node.tag); +/** + * @typedef {Object} ReexportInfo + * @property {Module} module + * @property {string[]} export + */ - if (tag.isIdentifier() && tag.identifier === "String.raw") { - const { quasis, parts } = getSimplifiedTemplateResult( - "raw", - node.quasi - ); - return new BasicEvaluatedExpression() - .setTemplateString(quasis, parts, "raw") - .setRange(node.range); - } - }); +/** @typedef {RawBinding | SymbolBinding} Binding */ - this.hooks.evaluateCallExpressionMember - .for("concat") - .tap("JavascriptParser", (expr, param) => { - if (!param.isString() && !param.isWrapped()) return; +/** + * @typedef {Object} RawBinding + * @property {ModuleInfo} info + * @property {string} rawName + * @property {string=} comment + * @property {string[]} ids + * @property {string[]} exportName + */ - let stringSuffix = null; - let hasUnknownParams = false; - const innerExpressions = []; - for (let i = expr.arguments.length - 1; i >= 0; i--) { - const arg = expr.arguments[i]; - if (arg.type === "SpreadElement") return; - const argExpr = this.evaluateExpression(arg); - if ( - hasUnknownParams || - (!argExpr.isString() && !argExpr.isNumber()) - ) { - hasUnknownParams = true; - innerExpressions.push(argExpr); - continue; - } +/** + * @typedef {Object} SymbolBinding + * @property {ConcatenatedModuleInfo} info + * @property {string} name + * @property {string=} comment + * @property {string[]} ids + * @property {string[]} exportName + */ - const value = argExpr.isString() - ? argExpr.string - : "" + argExpr.number; +/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo } ModuleInfo */ +/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo | ReferenceToModuleInfo } ModuleInfoOrReference */ - const newString = value + (stringSuffix ? stringSuffix.string : ""); - const newRange = [ - argExpr.range[0], - (stringSuffix || argExpr).range[1] - ]; - stringSuffix = new BasicEvaluatedExpression() - .setString(newString) - .setSideEffects( - (stringSuffix && stringSuffix.couldHaveSideEffects()) || - argExpr.couldHaveSideEffects() - ) - .setRange(newRange); - } +/** + * @typedef {Object} ConcatenatedModuleInfo + * @property {"concatenated"} type + * @property {Module} module + * @property {number} index + * @property {Object} ast + * @property {Source} internalSource + * @property {ReplaceSource} source + * @property {InitFragment[]=} chunkInitFragments + * @property {Iterable} runtimeRequirements + * @property {Scope} globalScope + * @property {Scope} moduleScope + * @property {Map} internalNames + * @property {Map} exportMap + * @property {Map} rawExportMap + * @property {string=} namespaceExportSymbol + * @property {string} namespaceObjectName + * @property {boolean} interopNamespaceObjectUsed + * @property {string} interopNamespaceObjectName + * @property {boolean} interopNamespaceObject2Used + * @property {string} interopNamespaceObject2Name + * @property {boolean} interopDefaultAccessUsed + * @property {string} interopDefaultAccessName + */ - if (hasUnknownParams) { - const prefix = param.isString() ? param : param.prefix; - const inner = - param.isWrapped() && param.wrappedInnerExpressions - ? param.wrappedInnerExpressions.concat(innerExpressions.reverse()) - : innerExpressions.reverse(); - return new BasicEvaluatedExpression() - .setWrapped(prefix, stringSuffix, inner) - .setRange(expr.range); - } else if (param.isWrapped()) { - const postfix = stringSuffix || param.postfix; - const inner = param.wrappedInnerExpressions - ? param.wrappedInnerExpressions.concat(innerExpressions.reverse()) - : innerExpressions.reverse(); - return new BasicEvaluatedExpression() - .setWrapped(param.prefix, postfix, inner) - .setRange(expr.range); - } else { - const newString = - param.string + (stringSuffix ? stringSuffix.string : ""); - return new BasicEvaluatedExpression() - .setString(newString) - .setSideEffects( - (stringSuffix && stringSuffix.couldHaveSideEffects()) || - param.couldHaveSideEffects() - ) - .setRange(expr.range); - } - }); - this.hooks.evaluateCallExpressionMember - .for("split") - .tap("JavascriptParser", (expr, param) => { - if (!param.isString()) return; - if (expr.arguments.length !== 1) return; - if (expr.arguments[0].type === "SpreadElement") return; - let result; - const arg = this.evaluateExpression(expr.arguments[0]); - if (arg.isString()) { - result = param.string.split(arg.string); - } else if (arg.isRegExp()) { - result = param.string.split(arg.regExp); - } else { - return; - } - return new BasicEvaluatedExpression() - .setArray(result) - .setSideEffects(param.couldHaveSideEffects()) - .setRange(expr.range); - }); - this.hooks.evaluate - .for("ConditionalExpression") - .tap("JavascriptParser", _expr => { - const expr = /** @type {ConditionalExpressionNode} */ (_expr); +/** + * @typedef {Object} ExternalModuleInfo + * @property {"external"} type + * @property {Module} module + * @property {RuntimeSpec | boolean} runtimeCondition + * @property {number} index + * @property {string} name + * @property {boolean} interopNamespaceObjectUsed + * @property {string} interopNamespaceObjectName + * @property {boolean} interopNamespaceObject2Used + * @property {string} interopNamespaceObject2Name + * @property {boolean} interopDefaultAccessUsed + * @property {string} interopDefaultAccessName + */ - const condition = this.evaluateExpression(expr.test); - const conditionValue = condition.asBool(); - let res; - if (conditionValue === undefined) { - const consequent = this.evaluateExpression(expr.consequent); - const alternate = this.evaluateExpression(expr.alternate); - if (!consequent || !alternate) return; - res = new BasicEvaluatedExpression(); - if (consequent.isConditional()) { - res.setOptions(consequent.options); - } else { - res.setOptions([consequent]); - } - if (alternate.isConditional()) { - res.addOptions(alternate.options); - } else { - res.addOptions([alternate]); - } - } else { - res = this.evaluateExpression( - conditionValue ? expr.consequent : expr.alternate - ); - if (condition.couldHaveSideEffects()) res.setSideEffects(); - } - res.setRange(expr.range); - return res; - }); - this.hooks.evaluate - .for("ArrayExpression") - .tap("JavascriptParser", _expr => { - const expr = /** @type {ArrayExpressionNode} */ (_expr); +/** + * @typedef {Object} ReferenceToModuleInfo + * @property {"reference"} type + * @property {RuntimeSpec | boolean} runtimeCondition + * @property {ConcatenatedModuleInfo | ExternalModuleInfo} target + */ - const items = expr.elements.map(element => { - return ( - element !== null && - element.type !== "SpreadElement" && - this.evaluateExpression(element) - ); - }); - if (!items.every(Boolean)) return; - return new BasicEvaluatedExpression() - .setItems(items) - .setRange(expr.range); - }); - this.hooks.evaluate - .for("ChainExpression") - .tap("JavascriptParser", _expr => { - const expr = /** @type {ChainExpressionNode} */ (_expr); - /** @type {ExpressionNode[]} */ - const optionalExpressionsStack = []; - /** @type {ExpressionNode|SuperNode} */ - let next = expr.expression; +const RESERVED_NAMES = new Set( + [ + // internal names (should always be renamed) + ConcatenationScope.DEFAULT_EXPORT, + ConcatenationScope.NAMESPACE_OBJECT_EXPORT, - 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; - } - } + // keywords + "abstract,arguments,async,await,boolean,break,byte,case,catch,char,class,const,continue", + "debugger,default,delete,do,double,else,enum,eval,export,extends,false,final,finally,float", + "for,function,goto,if,implements,import,in,instanceof,int,interface,let,long,native,new,null", + "package,private,protected,public,return,short,static,super,switch,synchronized,this,throw", + "throws,transient,true,try,typeof,var,void,volatile,while,with,yield", - while (optionalExpressionsStack.length > 0) { - const expression = optionalExpressionsStack.pop(); - const evaluated = this.evaluateExpression(expression); + // commonjs/amd + "module,__dirname,__filename,exports,require,define", - if (evaluated && evaluated.asNullish()) { - return evaluated.setRange(_expr.range); - } - } - return this.evaluateExpression(expr.expression); - }); - } + // js globals + "Array,Date,eval,function,hasOwnProperty,Infinity,isFinite,isNaN,isPrototypeOf,length,Math", + "NaN,name,Number,Object,prototype,String,toString,undefined,valueOf", - getRenameIdentifier(expr) { - const result = this.evaluateExpression(expr); - if (result && result.isIdentifier()) { - return result.identifier; - } - } + // browser globals + "alert,all,anchor,anchors,area,assign,blur,button,checkbox,clearInterval,clearTimeout", + "clientInformation,close,closed,confirm,constructor,crypto,decodeURI,decodeURIComponent", + "defaultStatus,document,element,elements,embed,embeds,encodeURI,encodeURIComponent,escape", + "event,fileUpload,focus,form,forms,frame,innerHeight,innerWidth,layer,layers,link,location", + "mimeTypes,navigate,navigator,frames,frameRate,hidden,history,image,images,offscreenBuffering", + "open,opener,option,outerHeight,outerWidth,packages,pageXOffset,pageYOffset,parent,parseFloat", + "parseInt,password,pkcs11,plugin,prompt,propertyIsEnum,radio,reset,screenX,screenY,scroll", + "secure,select,self,setInterval,setTimeout,status,submit,taint,text,textarea,top,unescape", + "untaint,window", - /** - * @param {ClassExpressionNode | ClassDeclarationNode} classy a class node - * @returns {void} - */ - walkClass(classy) { - if (classy.superClass) { - if (!this.hooks.classExtendsExpression.call(classy.superClass, classy)) { - this.walkExpression(classy.superClass); - } + // window events + "onblur,onclick,onerror,onfocus,onkeydown,onkeypress,onkeyup,onmouseover,onload,onmouseup,onmousedown,onsubmit" + ] + .join(",") + .split(",") +); + +const bySourceOrder = (a, b) => { + const aOrder = a.sourceOrder; + const bOrder = b.sourceOrder; + if (isNaN(aOrder)) { + if (!isNaN(bOrder)) { + return 1; } - if (classy.body && classy.body.type === "ClassBody") { - for (const classElement of /** @type {TODO} */ (classy.body.body)) { - if (!this.hooks.classBodyElement.call(classElement, classy)) { - if (classElement.computed && classElement.key) { - this.walkExpression(classElement.key); - } - if (classElement.value) { - if ( - !this.hooks.classBodyValue.call( - classElement.value, - classElement, - classy - ) - ) { - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = false; - this.walkExpression(classElement.value); - this.scope.topLevelScope = wasTopLevel; - } - } - } - } + } else { + if (isNaN(bOrder)) { + return -1; } - } - - // Pre walking iterates the scope for variable declarations - preWalkStatements(statements) { - for (let index = 0, len = statements.length; index < len; index++) { - const statement = statements[index]; - this.preWalkStatement(statement); + if (aOrder !== bOrder) { + return aOrder < bOrder ? -1 : 1; } } + return 0; +}; - // Block pre walking iterates the scope for block variable declarations - blockPreWalkStatements(statements) { - for (let index = 0, len = statements.length; index < len; index++) { - const statement = statements[index]; - this.blockPreWalkStatement(statement); +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; +}; - // Walking iterates the statements and expressions and processes them - walkStatements(statements) { - for (let index = 0, len = statements.length; index < len; index++) { - const statement = statements[index]; - this.walkStatement(statement); - } - } +/** + * @typedef {Object} ConcatenationEntry + * @property {"concatenated" | "external"} type + * @property {Module} module + * @property {RuntimeSpec | boolean} runtimeCondition + */ - preWalkStatement(statement) { - this.statementPath.push(statement); - if (this.hooks.preStatement.call(statement)) { - this.prevStatement = this.statementPath.pop(); - return; - } - switch (statement.type) { - case "BlockStatement": - this.preWalkBlockStatement(statement); - break; - case "DoWhileStatement": - this.preWalkDoWhileStatement(statement); - break; - case "ForInStatement": - this.preWalkForInStatement(statement); - break; - case "ForOfStatement": - this.preWalkForOfStatement(statement); - break; - case "ForStatement": - this.preWalkForStatement(statement); - break; - case "FunctionDeclaration": - this.preWalkFunctionDeclaration(statement); - break; - case "IfStatement": - this.preWalkIfStatement(statement); - break; - case "LabeledStatement": - this.preWalkLabeledStatement(statement); - break; - case "SwitchStatement": - this.preWalkSwitchStatement(statement); - break; - case "TryStatement": - this.preWalkTryStatement(statement); - break; - case "VariableDeclaration": - this.preWalkVariableDeclaration(statement); - break; - case "WhileStatement": - this.preWalkWhileStatement(statement); - break; - case "WithStatement": - this.preWalkWithStatement(statement); +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ModuleInfo} info module info + * @param {string[]} exportName exportName + * @param {Map} moduleToInfoMap moduleToInfoMap + * @param {RuntimeSpec} runtime for which runtime + * @param {RequestShortener} requestShortener the request shortener + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {Set} neededNamespaceObjects modules for which a namespace object should be generated + * @param {boolean} asCall asCall + * @param {boolean} strictHarmonyModule strictHarmonyModule + * @param {boolean | undefined} asiSafe asiSafe + * @param {Set} alreadyVisited alreadyVisited + * @returns {Binding} the final variable + */ +const getFinalBinding = ( + moduleGraph, + info, + exportName, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + asCall, + strictHarmonyModule, + asiSafe, + alreadyVisited = new Set() +) => { + const exportsType = info.module.getExportsType( + moduleGraph, + strictHarmonyModule + ); + if (exportName.length === 0) { + switch (exportsType) { + case "default-only": + info.interopNamespaceObject2Used = true; + return { + info, + rawName: info.interopNamespaceObject2Name, + ids: exportName, + exportName + }; + case "default-with-named": + info.interopNamespaceObjectUsed = true; + return { + info, + rawName: info.interopNamespaceObjectName, + ids: exportName, + exportName + }; + case "namespace": + case "dynamic": break; + default: + throw new Error(`Unexpected exportsType ${exportsType}`); } - this.prevStatement = this.statementPath.pop(); - } - - blockPreWalkStatement(statement) { - this.statementPath.push(statement); - if (this.hooks.blockPreStatement.call(statement)) { - this.prevStatement = this.statementPath.pop(); - return; - } - switch (statement.type) { - case "ImportDeclaration": - this.blockPreWalkImportDeclaration(statement); - break; - case "ExportAllDeclaration": - this.blockPreWalkExportAllDeclaration(statement); - break; - case "ExportDefaultDeclaration": - this.blockPreWalkExportDefaultDeclaration(statement); + } else { + switch (exportsType) { + case "namespace": break; - case "ExportNamedDeclaration": - this.blockPreWalkExportNamedDeclaration(statement); + case "default-with-named": + switch (exportName[0]) { + case "default": + exportName = exportName.slice(1); + break; + case "__esModule": + return { + info, + rawName: "/* __esModule */true", + ids: exportName.slice(1), + exportName + }; + } break; - case "VariableDeclaration": - this.blockPreWalkVariableDeclaration(statement); + case "default-only": { + const exportId = exportName[0]; + if (exportId === "__esModule") { + return { + info, + rawName: "/* __esModule */true", + ids: exportName.slice(1), + exportName + }; + } + exportName = exportName.slice(1); + if (exportId !== "default") { + return { + info, + rawName: + "/* non-default import from default-exporting module */undefined", + ids: exportName, + exportName + }; + } break; - case "ClassDeclaration": - this.blockPreWalkClassDeclaration(statement); + } + case "dynamic": + switch (exportName[0]) { + case "default": { + exportName = exportName.slice(1); + info.interopDefaultAccessUsed = true; + const defaultExport = asCall + ? `${info.interopDefaultAccessName}()` + : asiSafe + ? `(${info.interopDefaultAccessName}())` + : asiSafe === false + ? `;(${info.interopDefaultAccessName}())` + : `${info.interopDefaultAccessName}.a`; + return { + info, + rawName: defaultExport, + ids: exportName, + exportName + }; + } + case "__esModule": + return { + info, + rawName: "/* __esModule */true", + ids: exportName.slice(1), + exportName + }; + } break; + default: + throw new Error(`Unexpected exportsType ${exportsType}`); } - this.prevStatement = this.statementPath.pop(); } - - walkStatement(statement) { - this.statementPath.push(statement); - if (this.hooks.statement.call(statement) !== undefined) { - this.prevStatement = this.statementPath.pop(); - return; - } - switch (statement.type) { - case "BlockStatement": - this.walkBlockStatement(statement); - break; - case "ClassDeclaration": - this.walkClassDeclaration(statement); - break; - case "DoWhileStatement": - this.walkDoWhileStatement(statement); - break; - case "ExportDefaultDeclaration": - this.walkExportDefaultDeclaration(statement); - break; - case "ExportNamedDeclaration": - this.walkExportNamedDeclaration(statement); - break; - case "ExpressionStatement": - this.walkExpressionStatement(statement); - break; - case "ForInStatement": - this.walkForInStatement(statement); - break; - case "ForOfStatement": - this.walkForOfStatement(statement); - break; - case "ForStatement": - this.walkForStatement(statement); - break; - case "FunctionDeclaration": - this.walkFunctionDeclaration(statement); - break; - case "IfStatement": - this.walkIfStatement(statement); - break; - case "LabeledStatement": - this.walkLabeledStatement(statement); - break; - case "ReturnStatement": - this.walkReturnStatement(statement); - break; - case "SwitchStatement": - this.walkSwitchStatement(statement); - break; - case "ThrowStatement": - this.walkThrowStatement(statement); - break; - case "TryStatement": - this.walkTryStatement(statement); - break; - case "VariableDeclaration": - this.walkVariableDeclaration(statement); - break; - case "WhileStatement": - this.walkWhileStatement(statement); - break; - case "WithStatement": - this.walkWithStatement(statement); - break; + if (exportName.length === 0) { + switch (info.type) { + case "concatenated": + neededNamespaceObjects.add(info); + return { + info, + rawName: info.namespaceObjectName, + ids: exportName, + exportName + }; + case "external": + return { info, rawName: info.name, ids: exportName, exportName }; } - this.prevStatement = this.statementPath.pop(); - } - - /** - * Walks a statements that is nested within a parent statement - * and can potentially be a non-block statement. - * This enforces the nested statement to never be in ASI position. - * @param {StatementNode} statement the nested statement - * @returns {void} - */ - walkNestedStatement(statement) { - this.prevStatement = undefined; - this.walkStatement(statement); } - - // Real Statements - preWalkBlockStatement(statement) { - this.preWalkStatements(statement.body); + const exportsInfo = moduleGraph.getExportsInfo(info.module); + const exportInfo = exportsInfo.getExportInfo(exportName[0]); + if (alreadyVisited.has(exportInfo)) { + return { + info, + rawName: "/* circular reexport */ Object(function x() { x() }())", + ids: [], + exportName + }; } + alreadyVisited.add(exportInfo); + switch (info.type) { + case "concatenated": { + const exportId = exportName[0]; + if (exportInfo.provided === false) { + // It's not provided, but it could be on the prototype + neededNamespaceObjects.add(info); + return { + info, + rawName: info.namespaceObjectName, + ids: exportName, + exportName + }; + } + const directExport = info.exportMap && info.exportMap.get(exportId); + if (directExport) { + const usedName = /** @type {string[]} */ ( + exportsInfo.getUsedName(exportName, runtime) + ); + if (!usedName) { + return { + info, + rawName: "/* unused export */ undefined", + ids: exportName.slice(1), + exportName + }; + } + return { + info, + name: directExport, + ids: usedName.slice(1), + exportName + }; + } + const rawExport = info.rawExportMap && info.rawExportMap.get(exportId); + if (rawExport) { + return { + info, + rawName: rawExport, + ids: exportName.slice(1), + exportName + }; + } + const reexport = exportInfo.findTarget(moduleGraph, module => + moduleToInfoMap.has(module) + ); + if (reexport === false) { + throw new Error( + `Target module of reexport from '${info.module.readableIdentifier( + requestShortener + )}' is not part of the concatenation (export '${exportId}')\nModules in the concatenation:\n${Array.from( + moduleToInfoMap, + ([m, info]) => + ` * ${info.type} ${m.readableIdentifier(requestShortener)}` + ).join("\n")}` + ); + } + if (reexport) { + const refInfo = moduleToInfoMap.get(reexport.module); + return getFinalBinding( + moduleGraph, + refInfo, + reexport.export + ? [...reexport.export, ...exportName.slice(1)] + : exportName.slice(1), + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + asCall, + info.module.buildMeta.strictHarmonyModule, + asiSafe, + alreadyVisited + ); + } + if (info.namespaceExportSymbol) { + const usedName = /** @type {string[]} */ ( + exportsInfo.getUsedName(exportName, runtime) + ); + return { + info, + rawName: info.namespaceObjectName, + ids: usedName, + exportName + }; + } + throw new Error( + `Cannot get final name for export '${exportName.join( + "." + )}' of ${info.module.readableIdentifier(requestShortener)}` + ); + } - walkBlockStatement(statement) { - this.inBlockScope(() => { - const body = statement.body; - const prev = this.prevStatement; - this.blockPreWalkStatements(body); - this.prevStatement = prev; - this.walkStatements(body); - }); + case "external": { + const used = /** @type {string[]} */ ( + exportsInfo.getUsedName(exportName, runtime) + ); + if (!used) { + return { + info, + rawName: "/* unused export */ undefined", + ids: exportName.slice(1), + exportName + }; + } + const comment = equals(used, exportName) + ? "" + : Template.toNormalComment(`${exportName.join(".")}`); + return { info, rawName: info.name + comment, ids: used, exportName }; + } } +}; - walkExpressionStatement(statement) { - this.walkExpression(statement.expression); +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {ModuleInfo} info module info + * @param {string[]} exportName exportName + * @param {Map} moduleToInfoMap moduleToInfoMap + * @param {RuntimeSpec} runtime for which runtime + * @param {RequestShortener} requestShortener the request shortener + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {Set} neededNamespaceObjects modules for which a namespace object should be generated + * @param {boolean} asCall asCall + * @param {boolean} callContext callContext + * @param {boolean} strictHarmonyModule strictHarmonyModule + * @param {boolean | undefined} asiSafe asiSafe + * @returns {string} the final name + */ +const getFinalName = ( + moduleGraph, + info, + exportName, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + asCall, + callContext, + strictHarmonyModule, + asiSafe +) => { + const binding = getFinalBinding( + moduleGraph, + info, + exportName, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + asCall, + strictHarmonyModule, + asiSafe + ); + { + const { ids, comment } = binding; + let reference; + let isPropertyAccess; + if ("rawName" in binding) { + reference = `${binding.rawName}${comment || ""}${propertyAccess(ids)}`; + isPropertyAccess = ids.length > 0; + } else { + const { info, name: exportId } = binding; + const name = info.internalNames.get(exportId); + if (!name) { + throw new Error( + `The export "${exportId}" in "${info.module.readableIdentifier( + requestShortener + )}" has no internal name (existing names: ${ + Array.from( + info.internalNames, + ([name, symbol]) => `${name}: ${symbol}` + ).join(", ") || "none" + })` + ); + } + reference = `${name}${comment || ""}${propertyAccess(ids)}`; + isPropertyAccess = ids.length > 1; + } + if (isPropertyAccess && asCall && callContext === false) { + return asiSafe + ? `(0,${reference})` + : asiSafe === false + ? `;(0,${reference})` + : `/*#__PURE__*/Object(${reference})`; + } + return reference; } +}; - preWalkIfStatement(statement) { - this.preWalkStatement(statement.consequent); - if (statement.alternate) { - this.preWalkStatement(statement.alternate); +const addScopeSymbols = (s, nameSet, scopeSet1, scopeSet2) => { + let scope = s; + while (scope) { + if (scopeSet1.has(scope)) break; + if (scopeSet2.has(scope)) break; + scopeSet1.add(scope); + for (const variable of scope.variables) { + nameSet.add(variable.name); } + scope = scope.upper; } +}; - walkIfStatement(statement) { - const result = this.hooks.statementIf.call(statement); - if (result === undefined) { - this.walkExpression(statement.test); - this.walkNestedStatement(statement.consequent); - if (statement.alternate) { - this.walkNestedStatement(statement.alternate); - } - } else { - if (result) { - this.walkNestedStatement(statement.consequent); - } else if (statement.alternate) { - this.walkNestedStatement(statement.alternate); +const getAllReferences = variable => { + let set = variable.references; + // Look for inner scope variables too (like in class Foo { t() { Foo } }) + const identifiers = new Set(variable.identifiers); + for (const scope of variable.scope.childScopes) { + for (const innerVar of scope.variables) { + if (innerVar.identifiers.some(id => identifiers.has(id))) { + set = set.concat(innerVar.references); + break; } } } + return set; +}; - preWalkLabeledStatement(statement) { - this.preWalkStatement(statement.body); +const getPathInAst = (ast, node) => { + if (ast === node) { + return []; } - walkLabeledStatement(statement) { - const hook = this.hooks.label.get(statement.label.name); - if (hook !== undefined) { - const result = hook.call(statement); - if (result === true) return; + const nr = node.range; + + const enterNode = n => { + if (!n) return undefined; + const r = n.range; + if (r) { + if (r[0] <= nr[0] && r[1] >= nr[1]) { + const path = getPathInAst(n, node); + if (path) { + path.push(n); + return path; + } + } } - this.walkNestedStatement(statement.body); - } + return undefined; + }; - preWalkWithStatement(statement) { - this.preWalkStatement(statement.body); + if (Array.isArray(ast)) { + for (let i = 0; i < ast.length; i++) { + const enterResult = enterNode(ast[i]); + if (enterResult !== undefined) return enterResult; + } + } else if (ast && typeof ast === "object") { + const keys = Object.keys(ast); + for (let i = 0; i < keys.length; i++) { + const value = ast[keys[i]]; + if (Array.isArray(value)) { + const pathResult = getPathInAst(value, node); + if (pathResult !== undefined) return pathResult; + } else if (value && typeof value === "object") { + const enterResult = enterNode(value); + if (enterResult !== undefined) return enterResult; + } + } } +}; - walkWithStatement(statement) { - this.walkExpression(statement.object); - this.walkNestedStatement(statement.body); - } +const TYPES = new Set(["javascript"]); - preWalkSwitchStatement(statement) { - this.preWalkSwitchCases(statement.cases); +class ConcatenatedModule extends Module { + /** + * @param {Module} rootModule the root module of the concatenation + * @param {Set} modules all modules in the concatenation (including the root module) + * @param {RuntimeSpec} runtime the runtime + * @param {Object=} associatedObjectForCache object for caching + * @param {string | HashConstructor=} hashFunction hash function to use + * @returns {ConcatenatedModule} the module + */ + static create( + rootModule, + modules, + runtime, + associatedObjectForCache, + hashFunction = "md4" + ) { + const identifier = ConcatenatedModule._createIdentifier( + rootModule, + modules, + associatedObjectForCache, + hashFunction + ); + return new ConcatenatedModule({ + identifier, + rootModule, + modules, + runtime + }); } - walkSwitchStatement(statement) { - this.walkExpression(statement.discriminant); - this.walkSwitchCases(statement.cases); - } + /** + * @param {Object} options options + * @param {string} options.identifier the identifier of the module + * @param {Module=} options.rootModule the root module of the concatenation + * @param {RuntimeSpec} options.runtime the selected runtime + * @param {Set=} options.modules all concatenated modules + */ + constructor({ identifier, rootModule, modules, runtime }) { + super("javascript/esm", null, rootModule && rootModule.layer); - walkTerminatingStatement(statement) { - if (statement.argument) this.walkExpression(statement.argument); + // Info from Factory + /** @type {string} */ + this._identifier = identifier; + /** @type {Module} */ + this.rootModule = rootModule; + /** @type {Set} */ + this._modules = modules; + this._runtime = runtime; + this.factoryMeta = rootModule && rootModule.factoryMeta; } - walkReturnStatement(statement) { - this.walkTerminatingStatement(statement); + /** + * 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) { + throw new Error("Must not be called"); } - walkThrowStatement(statement) { - this.walkTerminatingStatement(statement); + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; } - preWalkTryStatement(statement) { - this.preWalkStatement(statement.block); - if (statement.handler) this.preWalkCatchClause(statement.handler); - if (statement.finializer) this.preWalkStatement(statement.finializer); + get modules() { + return Array.from(this._modules); } - walkTryStatement(statement) { - if (this.scope.inTry) { - this.walkStatement(statement.block); - } else { - this.scope.inTry = true; - this.walkStatement(statement.block); - this.scope.inTry = false; - } - if (statement.handler) this.walkCatchClause(statement.handler); - if (statement.finalizer) this.walkStatement(statement.finalizer); + /** + * @returns {string} a unique identifier of the module + */ + identifier() { + return this._identifier; } - preWalkWhileStatement(statement) { - this.preWalkStatement(statement.body); + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return ( + this.rootModule.readableIdentifier(requestShortener) + + ` + ${this._modules.size - 1} modules` + ); } - walkWhileStatement(statement) { - this.walkExpression(statement.test); - this.walkNestedStatement(statement.body); + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + return this.rootModule.libIdent(options); } - preWalkDoWhileStatement(statement) { - this.preWalkStatement(statement.body); + /** + * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + */ + nameForCondition() { + return this.rootModule.nameForCondition(); } - walkDoWhileStatement(statement) { - this.walkNestedStatement(statement.body); - this.walkExpression(statement.test); + /** + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only + */ + getSideEffectsConnectionState(moduleGraph) { + return this.rootModule.getSideEffectsConnectionState(moduleGraph); } - preWalkForStatement(statement) { - if (statement.init) { - if (statement.init.type === "VariableDeclaration") { - this.preWalkStatement(statement.init); - } - } - this.preWalkStatement(statement.body); - } + /** + * @param {WebpackOptions} options webpack options + * @param {Compilation} compilation the compilation + * @param {ResolverWithOptions} resolver the resolver + * @param {InputFileSystem} fs the file system + * @param {function(WebpackError=): void} callback callback function + * @returns {void} + */ + build(options, compilation, resolver, fs, callback) { + const { rootModule } = this; + this.buildInfo = { + strict: true, + cacheable: true, + moduleArgument: rootModule.buildInfo.moduleArgument, + exportsArgument: rootModule.buildInfo.exportsArgument, + fileDependencies: new LazySet(), + contextDependencies: new LazySet(), + missingDependencies: new LazySet(), + topLevelDeclarations: new Set(), + assets: undefined + }; + this.buildMeta = rootModule.buildMeta; + this.clearDependenciesAndBlocks(); + this.clearWarningsAndErrors(); - walkForStatement(statement) { - this.inBlockScope(() => { - if (statement.init) { - if (statement.init.type === "VariableDeclaration") { - this.blockPreWalkVariableDeclaration(statement.init); - this.prevStatement = undefined; - this.walkStatement(statement.init); - } else { - this.walkExpression(statement.init); - } - } - if (statement.test) { - this.walkExpression(statement.test); + for (const m of this._modules) { + // populate cacheable + if (!m.buildInfo.cacheable) { + this.buildInfo.cacheable = false; } - if (statement.update) { - this.walkExpression(statement.update); + + // populate dependencies + for (const d of m.dependencies.filter( + dep => + !(dep instanceof HarmonyImportDependency) || + !this._modules.has(compilation.moduleGraph.getModule(dep)) + )) { + this.dependencies.push(d); } - const body = statement.body; - if (body.type === "BlockStatement") { - // no need to add additional scope - const prev = this.prevStatement; - this.blockPreWalkStatements(body.body); - this.prevStatement = prev; - this.walkStatements(body.body); - } else { - this.walkNestedStatement(body); + // populate blocks + for (const d of m.blocks) { + this.blocks.push(d); } - }); - } - preWalkForInStatement(statement) { - if (statement.left.type === "VariableDeclaration") { - this.preWalkVariableDeclaration(statement.left); - } - this.preWalkStatement(statement.body); - } + // populate warnings + const warnings = m.getWarnings(); + if (warnings !== undefined) { + for (const warning of warnings) { + this.addWarning(warning); + } + } - walkForInStatement(statement) { - this.inBlockScope(() => { - if (statement.left.type === "VariableDeclaration") { - this.blockPreWalkVariableDeclaration(statement.left); - this.walkVariableDeclaration(statement.left); - } else { - this.walkPattern(statement.left); + // populate errors + const errors = m.getErrors(); + if (errors !== undefined) { + for (const error of errors) { + this.addError(error); + } } - this.walkExpression(statement.right); - const body = statement.body; - if (body.type === "BlockStatement") { - // no need to add additional scope - const prev = this.prevStatement; - this.blockPreWalkStatements(body.body); - this.prevStatement = prev; - this.walkStatements(body.body); + + // populate topLevelDeclarations + if (m.buildInfo.topLevelDeclarations) { + const topLevelDeclarations = this.buildInfo.topLevelDeclarations; + if (topLevelDeclarations !== undefined) { + for (const decl of m.buildInfo.topLevelDeclarations) { + // reserved names will always be renamed + if (RESERVED_NAMES.has(decl)) continue; + // TODO actually this is incorrect since with renaming there could be more + // We should do the renaming during build + topLevelDeclarations.add(decl); + } + } } else { - this.walkNestedStatement(body); + this.buildInfo.topLevelDeclarations = undefined; } - }); - } - - preWalkForOfStatement(statement) { - if (statement.await && this.scope.topLevelScope === true) { - this.hooks.topLevelAwait.call(statement); - } - if (statement.left.type === "VariableDeclaration") { - this.preWalkVariableDeclaration(statement.left); - } - this.preWalkStatement(statement.body); - } - walkForOfStatement(statement) { - this.inBlockScope(() => { - if (statement.left.type === "VariableDeclaration") { - this.blockPreWalkVariableDeclaration(statement.left); - this.walkVariableDeclaration(statement.left); - } else { - this.walkPattern(statement.left); + // populate assets + if (m.buildInfo.assets) { + if (this.buildInfo.assets === undefined) { + this.buildInfo.assets = Object.create(null); + } + Object.assign(this.buildInfo.assets, m.buildInfo.assets); } - this.walkExpression(statement.right); - const body = statement.body; - if (body.type === "BlockStatement") { - // no need to add additional scope - const prev = this.prevStatement; - this.blockPreWalkStatements(body.body); - this.prevStatement = prev; - this.walkStatements(body.body); - } else { - this.walkNestedStatement(body); + if (m.buildInfo.assetsInfo) { + if (this.buildInfo.assetsInfo === undefined) { + this.buildInfo.assetsInfo = new Map(); + } + for (const [key, value] of m.buildInfo.assetsInfo) { + this.buildInfo.assetsInfo.set(key, value); + } } - }); + } + callback(); } - // Declarations - preWalkFunctionDeclaration(statement) { - if (statement.id) { - this.defineVariable(statement.id.name); + /** + * @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) { + // Guess size from embedded modules + let size = 0; + for (const module of this._modules) { + size += module.size(type); } + return size; } - walkFunctionDeclaration(statement) { - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = false; - this.inFunctionScope(true, statement.params, () => { - for (const param of statement.params) { - this.walkPattern(param); - } - if (statement.body.type === "BlockStatement") { - this.detectMode(statement.body.body); - const prev = this.prevStatement; - this.preWalkStatement(statement.body); - this.prevStatement = prev; - this.walkStatement(statement.body); - } else { - this.walkExpression(statement.body); - } - }); - this.scope.topLevelScope = wasTopLevel; - } + /** + * @private + * @param {Module} rootModule the root of the concatenation + * @param {Set} modulesSet a set of modules which should be concatenated + * @param {RuntimeSpec} runtime for this runtime + * @param {ModuleGraph} moduleGraph the module graph + * @returns {ConcatenationEntry[]} concatenation list + */ + _createConcatenationList(rootModule, modulesSet, runtime, moduleGraph) { + /** @type {ConcatenationEntry[]} */ + const list = []; + /** @type {Map} */ + const existingEntries = new Map(); - blockPreWalkImportDeclaration(statement) { - const source = statement.source.value; - this.hooks.import.call(statement, source); - for (const specifier of statement.specifiers) { - const name = specifier.local.name; - switch (specifier.type) { - case "ImportDefaultSpecifier": - if ( - !this.hooks.importSpecifier.call(statement, source, "default", name) - ) { - this.defineVariable(name); - } - break; - case "ImportSpecifier": - if ( - !this.hooks.importSpecifier.call( - statement, - source, - specifier.imported.name, - name - ) - ) { - this.defineVariable(name); - } - break; - case "ImportNamespaceSpecifier": - if (!this.hooks.importSpecifier.call(statement, source, null, name)) { - this.defineVariable(name); - } - break; - default: - this.defineVariable(name); + /** + * @param {Module} module a module + * @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} imported modules in order + */ + const getConcatenatedImports = module => { + let connections = Array.from(moduleGraph.getOutgoingConnections(module)); + if (module === rootModule) { + for (const c of moduleGraph.getOutgoingConnections(this)) + connections.push(c); } - } - } - - enterDeclaration(declaration, onIdent) { - switch (declaration.type) { - case "VariableDeclaration": - for (const declarator of declaration.declarations) { - switch (declarator.type) { - case "VariableDeclarator": { - this.enterPattern(declarator.id, onIdent); - break; - } - } + const references = connections + .filter(connection => { + if (!(connection.dependency instanceof HarmonyImportDependency)) + return false; + return ( + connection && + connection.resolvedOriginModule === module && + connection.module && + connection.isTargetActive(runtime) + ); + }) + .map(connection => ({ + connection, + sourceOrder: /** @type {HarmonyImportDependency} */ ( + connection.dependency + ).sourceOrder + })); + references.sort( + concatComparators(bySourceOrder, keepOriginalOrder(references)) + ); + /** @type {Map} */ + const referencesMap = new Map(); + for (const { connection } of references) { + const runtimeCondition = filterRuntime(runtime, r => + connection.isTargetActive(r) + ); + if (runtimeCondition === false) continue; + const module = connection.module; + const entry = referencesMap.get(module); + if (entry === undefined) { + referencesMap.set(module, { connection, runtimeCondition }); + continue; } - break; - case "FunctionDeclaration": - this.enterPattern(declaration.id, onIdent); - break; - case "ClassDeclaration": - this.enterPattern(declaration.id, onIdent); - break; - } - } + entry.runtimeCondition = mergeRuntimeConditionNonFalse( + entry.runtimeCondition, + runtimeCondition, + runtime + ); + } + return referencesMap.values(); + }; - blockPreWalkExportNamedDeclaration(statement) { - let source; - if (statement.source) { - source = statement.source.value; - this.hooks.exportImport.call(statement, source); - } else { - this.hooks.export.call(statement); - } - if (statement.declaration) { - if ( - !this.hooks.exportDeclaration.call(statement, statement.declaration) - ) { - const prev = this.prevStatement; - this.preWalkStatement(statement.declaration); - this.prevStatement = prev; - this.blockPreWalkStatement(statement.declaration); - let index = 0; - this.enterDeclaration(statement.declaration, def => { - this.hooks.exportSpecifier.call(statement, def, def, index++); - }); + /** + * @param {ModuleGraphConnection} connection graph connection + * @param {RuntimeSpec | true} runtimeCondition runtime condition + * @returns {void} + */ + const enterModule = (connection, runtimeCondition) => { + const module = connection.module; + if (!module) return; + const existingEntry = existingEntries.get(module); + if (existingEntry === true) { + return; } - } - if (statement.specifiers) { - for ( - let specifierIndex = 0; - specifierIndex < statement.specifiers.length; - specifierIndex++ - ) { - const specifier = statement.specifiers[specifierIndex]; - switch (specifier.type) { - case "ExportSpecifier": { - const name = specifier.exported.name; - if (source) { - this.hooks.exportImportSpecifier.call( - statement, - source, - specifier.local.name, - name, - specifierIndex - ); - } else { - this.hooks.exportSpecifier.call( - statement, - specifier.local.name, - name, - specifierIndex - ); - } - break; + if (modulesSet.has(module)) { + existingEntries.set(module, true); + if (runtimeCondition !== true) { + throw new Error( + `Cannot runtime-conditional concatenate a module (${module.identifier()} in ${this.rootModule.identifier()}, ${runtimeConditionToString( + runtimeCondition + )}). This should not happen.` + ); + } + const imports = getConcatenatedImports(module); + for (const { connection, runtimeCondition } of imports) + enterModule(connection, runtimeCondition); + list.push({ + type: "concatenated", + module: connection.module, + runtimeCondition + }); + } else { + if (existingEntry !== undefined) { + const reducedRuntimeCondition = subtractRuntimeCondition( + runtimeCondition, + existingEntry, + runtime + ); + if (reducedRuntimeCondition === false) return; + runtimeCondition = reducedRuntimeCondition; + existingEntries.set( + connection.module, + mergeRuntimeConditionNonFalse( + existingEntry, + runtimeCondition, + runtime + ) + ); + } else { + existingEntries.set(connection.module, runtimeCondition); + } + if (list.length > 0) { + const lastItem = list[list.length - 1]; + if ( + lastItem.type === "external" && + lastItem.module === connection.module + ) { + lastItem.runtimeCondition = mergeRuntimeCondition( + lastItem.runtimeCondition, + runtimeCondition, + runtime + ); + return; } } + list.push({ + type: "external", + get module() { + // We need to use a getter here, because the module in the dependency + // could be replaced by some other process (i. e. also replaced with a + // concatenated module) + return connection.module; + }, + runtimeCondition + }); } - } + }; + + existingEntries.set(rootModule, true); + const imports = getConcatenatedImports(rootModule); + for (const { connection, runtimeCondition } of imports) + enterModule(connection, runtimeCondition); + list.push({ + type: "concatenated", + module: rootModule, + runtimeCondition: true + }); + + return list; } - walkExportNamedDeclaration(statement) { - if (statement.declaration) { - this.walkStatement(statement.declaration); + /** + * @param {Module} rootModule the root module of the concatenation + * @param {Set} modules all modules in the concatenation (including the root module) + * @param {Object=} associatedObjectForCache object for caching + * @param {string | HashConstructor=} hashFunction hash function to use + * @returns {string} the identifier + */ + static _createIdentifier( + rootModule, + modules, + associatedObjectForCache, + hashFunction = "md4" + ) { + const cachedMakePathsRelative = makePathsRelative.bindContextCache( + rootModule.context, + associatedObjectForCache + ); + let identifiers = []; + for (const module of modules) { + identifiers.push(cachedMakePathsRelative(module.identifier())); } + identifiers.sort(); + const hash = createHash(hashFunction); + hash.update(identifiers.join(" ")); + return rootModule.identifier() + "|" + hash.digest("hex"); } - blockPreWalkExportDefaultDeclaration(statement) { - const prev = this.prevStatement; - this.preWalkStatement(statement.declaration); - this.prevStatement = prev; - this.blockPreWalkStatement(statement.declaration); - if ( - statement.declaration.id && - statement.declaration.type !== "FunctionExpression" && - statement.declaration.type !== "ClassExpression" - ) { - this.hooks.exportSpecifier.call( - statement, - statement.declaration.id.name, - "default", - undefined + /** + * @param {LazySet} fileDependencies set where file dependencies are added to + * @param {LazySet} contextDependencies set where context dependencies are added to + * @param {LazySet} missingDependencies set where missing dependencies are added to + * @param {LazySet} buildDependencies set where build dependencies are added to + */ + addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies + ) { + for (const module of this._modules) { + module.addCacheDependencies( + fileDependencies, + contextDependencies, + missingDependencies, + buildDependencies ); } } - walkExportDefaultDeclaration(statement) { - this.hooks.export.call(statement); - if ( - statement.declaration.id && - statement.declaration.type !== "FunctionExpression" && - statement.declaration.type !== "ClassExpression" - ) { - if ( - !this.hooks.exportDeclaration.call(statement, statement.declaration) - ) { - this.walkStatement(statement.declaration); - } - } else { - // Acorn parses `export default function() {}` as `FunctionDeclaration` and - // `export default class {}` as `ClassDeclaration`, both with `id = null`. - // These nodes must be treated as expressions. - if ( - statement.declaration.type === "FunctionDeclaration" || - statement.declaration.type === "ClassDeclaration" - ) { - this.walkStatement(statement.declaration); - } else { - this.walkExpression(statement.declaration); - } - if (!this.hooks.exportExpression.call(statement, statement.declaration)) { - this.hooks.exportSpecifier.call( - statement, - statement.declaration, - "default", - undefined - ); - } + /** + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result + */ + codeGeneration({ + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime: generationRuntime, + codeGenerationResults + }) { + /** @type {Set} */ + const runtimeRequirements = new Set(); + const runtime = intersectRuntime(generationRuntime, this._runtime); + + const requestShortener = runtimeTemplate.requestShortener; + // Meta info for each module + const [modulesWithInfo, moduleToInfoMap] = this._getModulesWithInfo( + moduleGraph, + runtime + ); + + // Set with modules that need a generated namespace object + /** @type {Set} */ + const neededNamespaceObjects = new Set(); + + // Generate source code and analyse scopes + // Prepare a ReplaceSource for the final source + for (const info of moduleToInfoMap.values()) { + this._analyseModule( + moduleToInfoMap, + info, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + codeGenerationResults + ); } - } - blockPreWalkExportAllDeclaration(statement) { - const source = statement.source.value; - const name = statement.exported ? statement.exported.name : null; - this.hooks.exportImport.call(statement, source); - this.hooks.exportImportSpecifier.call(statement, source, null, name, 0); - } + // List of all used names to avoid conflicts + const allUsedNames = new Set(RESERVED_NAMES); - preWalkVariableDeclaration(statement) { - if (statement.kind !== "var") return; - this._preWalkVariableDeclaration(statement, this.hooks.varDeclarationVar); - } + // List of additional names in scope for module references + /** @type {Map, alreadyCheckedScopes: Set }>} */ + const usedNamesInScopeInfo = new Map(); + /** + * @param {string} module module identifier + * @param {string} id export id + * @returns {{ usedNames: Set, alreadyCheckedScopes: Set }} info + */ + const getUsedNamesInScopeInfo = (module, id) => { + const key = `${module}-${id}`; + let info = usedNamesInScopeInfo.get(key); + if (info === undefined) { + info = { + usedNames: new Set(), + alreadyCheckedScopes: new Set() + }; + usedNamesInScopeInfo.set(key, info); + } + return info; + }; - blockPreWalkVariableDeclaration(statement) { - if (statement.kind === "var") return; - const hookMap = - statement.kind === "const" - ? this.hooks.varDeclarationConst - : this.hooks.varDeclarationLet; - this._preWalkVariableDeclaration(statement, hookMap); - } + // Set of already checked scopes + const ignoredScopes = new Set(); - _preWalkVariableDeclaration(statement, hookMap) { - for (const declarator of statement.declarations) { - switch (declarator.type) { - case "VariableDeclarator": { - if (!this.hooks.preDeclarator.call(declarator, statement)) { - this.enterPattern(declarator.id, (name, decl) => { - let hook = hookMap.get(name); - if (hook === undefined || !hook.call(decl)) { - hook = this.hooks.varDeclaration.get(name); - if (hook === undefined || !hook.call(decl)) { - this.defineVariable(name); + // get all global names + for (const info of modulesWithInfo) { + if (info.type === "concatenated") { + // ignore symbols from moduleScope + if (info.moduleScope) { + ignoredScopes.add(info.moduleScope); + } + + // The super class expression in class scopes behaves weird + // We get ranges of all super class expressions to make + // renaming to work correctly + const superClassCache = new WeakMap(); + const getSuperClassExpressions = scope => { + const cacheEntry = superClassCache.get(scope); + if (cacheEntry !== undefined) return cacheEntry; + const superClassExpressions = []; + for (const childScope of scope.childScopes) { + if (childScope.type !== "class") continue; + const block = childScope.block; + if ( + (block.type === "ClassDeclaration" || + block.type === "ClassExpression") && + block.superClass + ) { + superClassExpressions.push({ + range: block.superClass.range, + variables: childScope.variables + }); + } + } + superClassCache.set(scope, superClassExpressions); + return superClassExpressions; + }; + + // add global symbols + if (info.globalScope) { + for (const reference of info.globalScope.through) { + const name = reference.identifier.name; + if (ConcatenationScope.isModuleReference(name)) { + const match = ConcatenationScope.matchModuleReference(name); + if (!match) continue; + const referencedInfo = modulesWithInfo[match.index]; + if (referencedInfo.type === "reference") + throw new Error("Module reference can't point to a reference"); + const binding = getFinalBinding( + moduleGraph, + referencedInfo, + match.ids, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + false, + info.module.buildMeta.strictHarmonyModule, + true + ); + if (!binding.ids) continue; + const { usedNames, alreadyCheckedScopes } = + getUsedNamesInScopeInfo( + binding.info.module.identifier(), + "name" in binding ? binding.name : "" + ); + for (const expr of getSuperClassExpressions(reference.from)) { + if ( + expr.range[0] <= reference.identifier.range[0] && + expr.range[1] >= reference.identifier.range[1] + ) { + for (const variable of expr.variables) { + usedNames.add(variable.name); + } } } - }); + addScopeSymbols( + reference.from, + usedNames, + alreadyCheckedScopes, + ignoredScopes + ); + } else { + allUsedNames.add(name); + } } - break; } } } - } - walkVariableDeclaration(statement) { - for (const declarator of statement.declarations) { - switch (declarator.type) { - case "VariableDeclarator": { - const renameIdentifier = - declarator.init && this.getRenameIdentifier(declarator.init); - if (renameIdentifier && declarator.id.type === "Identifier") { - const hook = this.hooks.canRename.get(renameIdentifier); - if (hook !== undefined && hook.call(declarator.init)) { - // renaming with "var a = b;" - const hook = this.hooks.rename.get(renameIdentifier); - if (hook === undefined || !hook.call(declarator.init)) { - this.setVariable(declarator.id.name, renameIdentifier); + // generate names for symbols + for (const info of moduleToInfoMap.values()) { + const { usedNames: namespaceObjectUsedNames } = getUsedNamesInScopeInfo( + info.module.identifier(), + "" + ); + switch (info.type) { + case "concatenated": { + for (const variable of info.moduleScope.variables) { + const name = variable.name; + const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo( + info.module.identifier(), + name + ); + if (allUsedNames.has(name) || usedNames.has(name)) { + const references = getAllReferences(variable); + for (const ref of references) { + addScopeSymbols( + ref.from, + usedNames, + alreadyCheckedScopes, + ignoredScopes + ); } - break; + const newName = this.findNewName( + name, + allUsedNames, + usedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(newName); + info.internalNames.set(name, newName); + const source = info.source; + const allIdentifiers = new Set( + references.map(r => r.identifier).concat(variable.identifiers) + ); + for (const identifier of allIdentifiers) { + const r = identifier.range; + const path = getPathInAst(info.ast, identifier); + if (path && path.length > 1) { + const maybeProperty = + path[1].type === "AssignmentPattern" && + path[1].left === path[0] + ? path[2] + : path[1]; + if ( + maybeProperty.type === "Property" && + maybeProperty.shorthand + ) { + source.insert(r[1], `: ${newName}`); + continue; + } + } + source.replace(r[0], r[1] - 1, newName); + } + } else { + allUsedNames.add(name); + info.internalNames.set(name, name); } } - if (!this.hooks.declarator.call(declarator, statement)) { - this.walkPattern(declarator.id); - if (declarator.init) this.walkExpression(declarator.init); + let namespaceObjectName; + if (info.namespaceExportSymbol) { + namespaceObjectName = info.internalNames.get( + info.namespaceExportSymbol + ); + } else { + namespaceObjectName = this.findNewName( + "namespaceObject", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(namespaceObjectName); } + info.namespaceObjectName = namespaceObjectName; break; } + case "external": { + const externalName = this.findNewName( + "", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalName); + info.name = externalName; + break; + } + } + if (info.module.buildMeta.exportsType !== "namespace") { + const externalNameInterop = this.findNewName( + "namespaceObject", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopNamespaceObjectName = externalNameInterop; + } + if ( + info.module.buildMeta.exportsType === "default" && + info.module.buildMeta.defaultObject !== "redirect" + ) { + const externalNameInterop = this.findNewName( + "namespaceObject2", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopNamespaceObject2Name = externalNameInterop; + } + if ( + info.module.buildMeta.exportsType === "dynamic" || + !info.module.buildMeta.exportsType + ) { + const externalNameInterop = this.findNewName( + "default", + allUsedNames, + namespaceObjectUsedNames, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopDefaultAccessName = externalNameInterop; } } - } - blockPreWalkClassDeclaration(statement) { - if (statement.id) { - this.defineVariable(statement.id.name); + // Find and replace references to modules + for (const info of moduleToInfoMap.values()) { + if (info.type === "concatenated") { + for (const reference of info.globalScope.through) { + const name = reference.identifier.name; + const match = ConcatenationScope.matchModuleReference(name); + if (match) { + const referencedInfo = modulesWithInfo[match.index]; + if (referencedInfo.type === "reference") + throw new Error("Module reference can't point to a reference"); + const finalName = getFinalName( + moduleGraph, + referencedInfo, + match.ids, + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + match.call, + !match.directImport, + info.module.buildMeta.strictHarmonyModule, + match.asiSafe + ); + const r = reference.identifier.range; + const source = info.source; + // range is extended by 2 chars to cover the appended "._" + source.replace(r[0], r[1] + 1, finalName); + } + } + } } - } - walkClassDeclaration(statement) { - this.walkClass(statement); - } + // Map with all root exposed used exports + /** @type {Map} */ + const exportsMap = new Map(); - preWalkSwitchCases(switchCases) { - for (let index = 0, len = switchCases.length; index < len; index++) { - const switchCase = switchCases[index]; - this.preWalkStatements(switchCase.consequent); + // Set with all root exposed unused exports + /** @type {Set} */ + const unusedExports = new Set(); + + const rootInfo = /** @type {ConcatenatedModuleInfo} */ ( + moduleToInfoMap.get(this.rootModule) + ); + const strictHarmonyModule = rootInfo.module.buildMeta.strictHarmonyModule; + const exportsInfo = moduleGraph.getExportsInfo(rootInfo.module); + for (const exportInfo of exportsInfo.orderedExports) { + const name = exportInfo.name; + if (exportInfo.provided === false) continue; + const used = exportInfo.getUsedName(undefined, runtime); + if (!used) { + unusedExports.add(name); + continue; + } + exportsMap.set(used, requestShortener => { + try { + const finalName = getFinalName( + moduleGraph, + rootInfo, + [name], + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + false, + false, + strictHarmonyModule, + true + ); + return `/* ${ + exportInfo.isReexport() ? "reexport" : "binding" + } */ ${finalName}`; + } catch (e) { + e.message += `\nwhile generating the root export '${name}' (used name: '${used}')`; + throw e; + } + }); } - } - walkSwitchCases(switchCases) { - this.inBlockScope(() => { - const len = switchCases.length; + const result = new ConcatSource(); - // we need to pre walk all statements first since we can have invalid code - // import A from "module"; - // switch(1) { - // case 1: - // console.log(A); // should fail at runtime - // case 2: - // const A = 1; - // } - for (let index = 0; index < len; index++) { - const switchCase = switchCases[index]; + // add harmony compatibility flag (must be first because of possible circular dependencies) + if ( + moduleGraph.getExportsInfo(this).otherExportsInfo.getUsed(runtime) !== + UsageState.Unused + ) { + result.add(`// ESM COMPAT FLAG\n`); + result.add( + runtimeTemplate.defineEsModuleFlagStatement({ + exportsArgument: this.exportsArgument, + runtimeRequirements + }) + ); + } - if (switchCase.consequent.length > 0) { - const prev = this.prevStatement; - this.blockPreWalkStatements(switchCase.consequent); - this.prevStatement = prev; - } + // define exports + if (exportsMap.size > 0) { + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + const definitions = []; + for (const [key, value] of exportsMap) { + definitions.push( + `\n ${JSON.stringify(key)}: ${runtimeTemplate.returningFunction( + value(requestShortener) + )}` + ); } + result.add(`\n// EXPORTS\n`); + result.add( + `${RuntimeGlobals.definePropertyGetters}(${ + this.exportsArgument + }, {${definitions.join(",")}\n});\n` + ); + } - for (let index = 0; index < len; index++) { - const switchCase = switchCases[index]; + // list unused exports + if (unusedExports.size > 0) { + result.add( + `\n// UNUSED EXPORTS: ${joinIterableWithComma(unusedExports)}\n` + ); + } - if (switchCase.test) { - this.walkExpression(switchCase.test); - } - if (switchCase.consequent.length > 0) { - this.walkStatements(switchCase.consequent); + // generate namespace objects + const namespaceObjectSources = new Map(); + for (const info of neededNamespaceObjects) { + if (info.namespaceExportSymbol) continue; + const nsObj = []; + const exportsInfo = moduleGraph.getExportsInfo(info.module); + for (const exportInfo of exportsInfo.orderedExports) { + if (exportInfo.provided === false) continue; + const usedName = exportInfo.getUsedName(undefined, runtime); + if (usedName) { + const finalName = getFinalName( + moduleGraph, + info, + [exportInfo.name], + moduleToInfoMap, + runtime, + requestShortener, + runtimeTemplate, + neededNamespaceObjects, + false, + undefined, + info.module.buildMeta.strictHarmonyModule, + true + ); + nsObj.push( + `\n ${JSON.stringify( + usedName + )}: ${runtimeTemplate.returningFunction(finalName)}` + ); } } - }); - } - - preWalkCatchClause(catchClause) { - this.preWalkStatement(catchClause.body); - } + const name = info.namespaceObjectName; + const defineGetters = + nsObj.length > 0 + ? `${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join( + "," + )}\n});\n` + : ""; + if (nsObj.length > 0) + runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); + namespaceObjectSources.set( + info, + ` +// NAMESPACE OBJECT: ${info.module.readableIdentifier(requestShortener)} +var ${name} = {}; +${RuntimeGlobals.makeNamespaceObject}(${name}); +${defineGetters}` + ); + runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); + } - walkCatchClause(catchClause) { - this.inBlockScope(() => { - // Error binding is optional in catch clause since ECMAScript 2019 - if (catchClause.param !== null) { - this.enterPattern(catchClause.param, ident => { - this.defineVariable(ident); - }); - this.walkPattern(catchClause.param); + // define required namespace objects (must be before evaluation modules) + for (const info of modulesWithInfo) { + if (info.type === "concatenated") { + const source = namespaceObjectSources.get(info); + if (!source) continue; + result.add(source); } - const prev = this.prevStatement; - this.blockPreWalkStatement(catchClause.body); - this.prevStatement = prev; - this.walkStatement(catchClause.body); - }); - } - - walkPattern(pattern) { - switch (pattern.type) { - case "ArrayPattern": - this.walkArrayPattern(pattern); - break; - case "AssignmentPattern": - this.walkAssignmentPattern(pattern); - break; - case "MemberExpression": - this.walkMemberExpression(pattern); - break; - case "ObjectPattern": - this.walkObjectPattern(pattern); - break; - case "RestElement": - this.walkRestElement(pattern); - break; } - } - walkAssignmentPattern(pattern) { - this.walkExpression(pattern.right); - this.walkPattern(pattern.left); - } + const chunkInitFragments = []; - walkObjectPattern(pattern) { - for (let i = 0, len = pattern.properties.length; i < len; i++) { - const prop = pattern.properties[i]; - if (prop) { - if (prop.computed) this.walkExpression(prop.key); - if (prop.value) this.walkPattern(prop.value); + // evaluate modules in order + for (const rawInfo of modulesWithInfo) { + let name; + let isConditional = false; + const info = rawInfo.type === "reference" ? rawInfo.target : rawInfo; + switch (info.type) { + case "concatenated": { + result.add( + `\n;// CONCATENATED MODULE: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + result.add(info.source); + if (info.chunkInitFragments) { + for (const f of info.chunkInitFragments) chunkInitFragments.push(f); + } + if (info.runtimeRequirements) { + for (const r of info.runtimeRequirements) { + runtimeRequirements.add(r); + } + } + name = info.namespaceObjectName; + break; + } + case "external": { + result.add( + `\n// EXTERNAL MODULE: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + runtimeRequirements.add(RuntimeGlobals.require); + const { runtimeCondition } = + /** @type {ExternalModuleInfo | ReferenceToModuleInfo} */ (rawInfo); + const condition = runtimeTemplate.runtimeConditionExpression({ + chunkGraph, + runtimeCondition, + runtime, + runtimeRequirements + }); + if (condition !== "true") { + isConditional = true; + result.add(`if (${condition}) {\n`); + } + result.add( + `var ${info.name} = __webpack_require__(${JSON.stringify( + chunkGraph.getModuleId(info.module) + )});` + ); + name = info.name; + break; + } + default: + // @ts-expect-error never is expected here + throw new Error(`Unsupported concatenation entry type ${info.type}`); + } + if (info.interopNamespaceObjectUsed) { + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + result.add( + `\nvar ${info.interopNamespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name}, 2);` + ); + } + if (info.interopNamespaceObject2Used) { + runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); + result.add( + `\nvar ${info.interopNamespaceObject2Name} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name});` + ); + } + if (info.interopDefaultAccessUsed) { + runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport); + result.add( + `\nvar ${info.interopDefaultAccessName} = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${name});` + ); + } + if (isConditional) { + result.add("\n}"); } } - } - walkArrayPattern(pattern) { - for (let i = 0, len = pattern.elements.length; i < len; i++) { - const element = pattern.elements[i]; - if (element) this.walkPattern(element); - } - } + const data = new Map(); + if (chunkInitFragments.length > 0) + data.set("chunkInitFragments", chunkInitFragments); - walkRestElement(pattern) { - this.walkPattern(pattern.argument); - } + /** @type {CodeGenerationResult} */ + const resultEntry = { + sources: new Map([["javascript", new CachedSource(result)]]), + data, + runtimeRequirements + }; - walkExpressions(expressions) { - for (const expression of expressions) { - if (expression) { - this.walkExpression(expression); - } - } + return resultEntry; } - walkExpression(expression) { - switch (expression.type) { - case "ArrayExpression": - this.walkArrayExpression(expression); - break; - case "ArrowFunctionExpression": - this.walkArrowFunctionExpression(expression); - break; - case "AssignmentExpression": - this.walkAssignmentExpression(expression); - break; - case "AwaitExpression": - this.walkAwaitExpression(expression); - break; - case "BinaryExpression": - this.walkBinaryExpression(expression); - break; - case "CallExpression": - this.walkCallExpression(expression); - break; - case "ChainExpression": - this.walkChainExpression(expression); - break; - case "ClassExpression": - this.walkClassExpression(expression); - break; - case "ConditionalExpression": - this.walkConditionalExpression(expression); - break; - case "FunctionExpression": - this.walkFunctionExpression(expression); - break; - case "Identifier": - this.walkIdentifier(expression); - break; - case "ImportExpression": - this.walkImportExpression(expression); - break; - case "LogicalExpression": - this.walkLogicalExpression(expression); - break; - case "MetaProperty": - this.walkMetaProperty(expression); - break; - case "MemberExpression": - this.walkMemberExpression(expression); - break; - case "NewExpression": - this.walkNewExpression(expression); - break; - case "ObjectExpression": - this.walkObjectExpression(expression); - break; - case "SequenceExpression": - this.walkSequenceExpression(expression); - break; - case "SpreadElement": - this.walkSpreadElement(expression); - break; - case "TaggedTemplateExpression": - this.walkTaggedTemplateExpression(expression); - break; - case "TemplateLiteral": - this.walkTemplateLiteral(expression); - break; - case "ThisExpression": - this.walkThisExpression(expression); - break; - case "UnaryExpression": - this.walkUnaryExpression(expression); - break; - case "UpdateExpression": - this.walkUpdateExpression(expression); - break; - case "YieldExpression": - this.walkYieldExpression(expression); - break; + /** + * @param {Map} modulesMap modulesMap + * @param {ModuleInfo} info info + * @param {DependencyTemplates} dependencyTemplates dependencyTemplates + * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {ChunkGraph} chunkGraph chunkGraph + * @param {RuntimeSpec} runtime runtime + * @param {CodeGenerationResults} codeGenerationResults codeGenerationResults + */ + _analyseModule( + modulesMap, + info, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + codeGenerationResults + ) { + if (info.type === "concatenated") { + const m = info.module; + try { + // Create a concatenation scope to track and capture information + const concatenationScope = new ConcatenationScope(modulesMap, info); + + // TODO cache codeGeneration results + const codeGenResult = m.codeGeneration({ + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + runtime, + concatenationScope, + codeGenerationResults + }); + const source = codeGenResult.sources.get("javascript"); + const data = codeGenResult.data; + const chunkInitFragments = data && data.get("chunkInitFragments"); + const code = source.source().toString(); + let ast; + try { + ast = JavascriptParser._parse(code, { + sourceType: "module" + }); + } catch (err) { + if ( + err.loc && + typeof err.loc === "object" && + typeof err.loc.line === "number" + ) { + const lineNumber = err.loc.line; + const lines = code.split("\n"); + err.message += + "\n| " + + lines + .slice(Math.max(0, lineNumber - 3), lineNumber + 2) + .join("\n| "); + } + throw err; + } + const scopeManager = eslintScope.analyze(ast, { + ecmaVersion: 6, + sourceType: "module", + optimistic: true, + ignoreEval: true, + impliedStrict: true + }); + const globalScope = scopeManager.acquire(ast); + const moduleScope = globalScope.childScopes[0]; + const resultSource = new ReplaceSource(source); + info.runtimeRequirements = codeGenResult.runtimeRequirements; + info.ast = ast; + info.internalSource = source; + info.source = resultSource; + info.chunkInitFragments = chunkInitFragments; + info.globalScope = globalScope; + info.moduleScope = moduleScope; + } catch (err) { + err.message += `\nwhile analyzing module ${m.identifier()} for concatenation`; + throw err; + } } } - walkAwaitExpression(expression) { - if (this.scope.topLevelScope === true) - this.hooks.topLevelAwait.call(expression); - this.walkExpression(expression.argument); + /** + * @param {ModuleGraph} moduleGraph the module graph + * @param {RuntimeSpec} runtime the runtime + * @returns {[ModuleInfoOrReference[], Map]} module info items + */ + _getModulesWithInfo(moduleGraph, runtime) { + const orderedConcatenationList = this._createConcatenationList( + this.rootModule, + this._modules, + runtime, + moduleGraph + ); + /** @type {Map} */ + const map = new Map(); + const list = orderedConcatenationList.map((info, index) => { + let item = map.get(info.module); + if (item === undefined) { + switch (info.type) { + case "concatenated": + item = { + type: "concatenated", + module: info.module, + index, + ast: undefined, + internalSource: undefined, + runtimeRequirements: undefined, + source: undefined, + globalScope: undefined, + moduleScope: undefined, + internalNames: new Map(), + exportMap: undefined, + rawExportMap: undefined, + namespaceExportSymbol: undefined, + namespaceObjectName: undefined, + interopNamespaceObjectUsed: false, + interopNamespaceObjectName: undefined, + interopNamespaceObject2Used: false, + interopNamespaceObject2Name: undefined, + interopDefaultAccessUsed: false, + interopDefaultAccessName: undefined + }; + break; + case "external": + item = { + type: "external", + module: info.module, + runtimeCondition: info.runtimeCondition, + index, + name: undefined, + interopNamespaceObjectUsed: false, + interopNamespaceObjectName: undefined, + interopNamespaceObject2Used: false, + interopNamespaceObject2Name: undefined, + interopDefaultAccessUsed: false, + interopDefaultAccessName: undefined + }; + break; + default: + throw new Error( + `Unsupported concatenation entry type ${info.type}` + ); + } + map.set(item.module, item); + return item; + } else { + /** @type {ReferenceToModuleInfo} */ + const ref = { + type: "reference", + runtimeCondition: info.runtimeCondition, + target: item + }; + return ref; + } + }); + return [list, map]; } - walkArrayExpression(expression) { - if (expression.elements) { - this.walkExpressions(expression.elements); + findNewName(oldName, usedNamed1, usedNamed2, extraInfo) { + let name = oldName; + + if (name === ConcatenationScope.DEFAULT_EXPORT) { + name = ""; + } + if (name === ConcatenationScope.NAMESPACE_OBJECT_EXPORT) { + name = "namespaceObject"; } - } - walkSpreadElement(expression) { - if (expression.argument) { - this.walkExpression(expression.argument); + // Remove uncool stuff + extraInfo = extraInfo.replace( + /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, + "" + ); + + const splittedInfo = extraInfo.split("/"); + while (splittedInfo.length) { + name = splittedInfo.pop() + (name ? "_" + name : ""); + const nameIdent = Template.toIdentifier(name); + if ( + !usedNamed1.has(nameIdent) && + (!usedNamed2 || !usedNamed2.has(nameIdent)) + ) + return nameIdent; } - } - walkObjectExpression(expression) { - for ( - let propIndex = 0, len = expression.properties.length; - propIndex < len; - propIndex++ + let i = 0; + let nameWithNumber = Template.toIdentifier(`${name}_${i}`); + while ( + usedNamed1.has(nameWithNumber) || + (usedNamed2 && usedNamed2.has(nameWithNumber)) ) { - const prop = expression.properties[propIndex]; - this.walkProperty(prop); + i++; + nameWithNumber = Template.toIdentifier(`${name}_${i}`); } + return nameWithNumber; } - walkProperty(prop) { - if (prop.type === "SpreadElement") { - this.walkExpression(prop.argument); - return; - } - if (prop.computed) { - this.walkExpression(prop.key); - } - if (prop.shorthand && prop.value && prop.value.type === "Identifier") { - this.scope.inShorthand = prop.value.name; - this.walkIdentifier(prop.value); - this.scope.inShorthand = false; - } else { - this.walkExpression(prop.value); + /** + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} + */ + updateHash(hash, context) { + const { chunkGraph, runtime } = context; + for (const info of this._createConcatenationList( + this.rootModule, + this._modules, + intersectRuntime(runtime, this._runtime), + chunkGraph.moduleGraph + )) { + switch (info.type) { + case "concatenated": + info.module.updateHash(hash, context); + break; + case "external": + hash.update(`${chunkGraph.getModuleId(info.module)}`); + // TODO runtimeCondition + break; + } } + super.updateHash(hash, context); } - walkFunctionExpression(expression) { - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = false; - const scopeParams = expression.params; - - // Add function name in scope for recursive calls - if (expression.id) { - scopeParams.push(expression.id.name); - } - - this.inFunctionScope(true, scopeParams, () => { - for (const param of expression.params) { - this.walkPattern(param); - } - if (expression.body.type === "BlockStatement") { - this.detectMode(expression.body.body); - const prev = this.prevStatement; - this.preWalkStatement(expression.body); - this.prevStatement = prev; - this.walkStatement(expression.body); - } else { - this.walkExpression(expression.body); - } + static deserialize(context) { + const obj = new ConcatenatedModule({ + identifier: undefined, + rootModule: undefined, + modules: undefined, + runtime: undefined }); - this.scope.topLevelScope = wasTopLevel; + obj.deserialize(context); + return obj; } +} - walkArrowFunctionExpression(expression) { - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = wasTopLevel ? "arrow" : false; - this.inFunctionScope(false, expression.params, () => { - for (const param of expression.params) { - this.walkPattern(param); - } - if (expression.body.type === "BlockStatement") { - this.detectMode(expression.body.body); - const prev = this.prevStatement; - this.preWalkStatement(expression.body); - this.prevStatement = prev; - this.walkStatement(expression.body); - } else { - this.walkExpression(expression.body); +makeSerializable(ConcatenatedModule, "webpack/lib/optimize/ConcatenatedModule"); + +module.exports = ConcatenatedModule; + + +/***/ }), + +/***/ 96260: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { STAGE_BASIC } = __webpack_require__(80057); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compiler")} Compiler */ + +class EnsureChunkConditionsPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "EnsureChunkConditionsPlugin", + compilation => { + const handler = chunks => { + const chunkGraph = compilation.chunkGraph; + // These sets are hoisted here to save memory + // They are cleared at the end of every loop + /** @type {Set} */ + const sourceChunks = new Set(); + /** @type {Set} */ + const chunkGroups = new Set(); + for (const module of compilation.modules) { + if (!module.hasChunkCondition()) continue; + for (const chunk of chunkGraph.getModuleChunksIterable(module)) { + if (!module.chunkCondition(chunk, compilation)) { + sourceChunks.add(chunk); + for (const group of chunk.groupsIterable) { + chunkGroups.add(group); + } + } + } + if (sourceChunks.size === 0) continue; + /** @type {Set} */ + const targetChunks = new Set(); + chunkGroupLoop: for (const chunkGroup of chunkGroups) { + // Can module be placed in a chunk of this group? + for (const chunk of chunkGroup.chunks) { + if (module.chunkCondition(chunk, compilation)) { + targetChunks.add(chunk); + continue chunkGroupLoop; + } + } + // We reached the entrypoint: fail + if (chunkGroup.isInitial()) { + throw new Error( + "Cannot fullfil chunk condition of " + module.identifier() + ); + } + // Try placing in all parents + for (const group of chunkGroup.parentsIterable) { + chunkGroups.add(group); + } + } + for (const sourceChunk of sourceChunks) { + chunkGraph.disconnectChunkAndModule(sourceChunk, module); + } + for (const targetChunk of targetChunks) { + chunkGraph.connectChunkAndModule(targetChunk, module); + } + sourceChunks.clear(); + chunkGroups.clear(); + } + }; + compilation.hooks.optimizeChunks.tap( + { + name: "EnsureChunkConditionsPlugin", + stage: STAGE_BASIC + }, + handler + ); } - }); - this.scope.topLevelScope = wasTopLevel; + ); } +} +module.exports = EnsureChunkConditionsPlugin; + + +/***/ }), + +/***/ 50089: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ + +class FlagIncludedChunksPlugin { /** - * @param {SequenceExpressionNode} expression the sequence + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - walkSequenceExpression(expression) { - if (!expression.expressions) return; - // We treat sequence expressions like statements when they are one statement level - // This has some benefits for optimizations that only work on statement level - const currentStatement = this.statementPath[this.statementPath.length - 1]; - if ( - currentStatement === expression || - (currentStatement.type === "ExpressionStatement" && - currentStatement.expression === expression) - ) { - const old = this.statementPath.pop(); - for (const expr of expression.expressions) { - this.statementPath.push(expr); - this.walkExpression(expr); - this.statementPath.pop(); - } - this.statementPath.push(old); - } else { - this.walkExpressions(expression.expressions); - } + apply(compiler) { + compiler.hooks.compilation.tap("FlagIncludedChunksPlugin", compilation => { + compilation.hooks.optimizeChunkIds.tap( + "FlagIncludedChunksPlugin", + chunks => { + const chunkGraph = compilation.chunkGraph; + + // prepare two bit integers for each module + // 2^31 is the max number represented as SMI in v8 + // we want the bits distributed this way: + // the bit 2^31 is pretty rar and only one module should get it + // so it has a probability of 1 / modulesCount + // the first bit (2^0) is the easiest and every module could get it + // if it doesn't get a better bit + // from bit 2^n to 2^(n+1) there is a probability of p + // so 1 / modulesCount == p^31 + // <=> p = sqrt31(1 / modulesCount) + // so we use a modulo of 1 / sqrt31(1 / modulesCount) + /** @type {WeakMap} */ + const moduleBits = new WeakMap(); + const modulesCount = compilation.modules.size; + + // precalculate the modulo values for each bit + const modulo = 1 / Math.pow(1 / modulesCount, 1 / 31); + const modulos = Array.from( + { length: 31 }, + (x, i) => Math.pow(modulo, i) | 0 + ); + + // iterate all modules to generate bit values + let i = 0; + for (const module of compilation.modules) { + let bit = 30; + while (i % modulos[bit] !== 0) { + bit--; + } + moduleBits.set(module, 1 << bit); + i++; + } + + // iterate all chunks to generate bitmaps + /** @type {WeakMap} */ + const chunkModulesHash = new WeakMap(); + for (const chunk of chunks) { + let hash = 0; + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + hash |= moduleBits.get(module); + } + chunkModulesHash.set(chunk, hash); + } + + for (const chunkA of chunks) { + const chunkAHash = chunkModulesHash.get(chunkA); + const chunkAModulesCount = + chunkGraph.getNumberOfChunkModules(chunkA); + if (chunkAModulesCount === 0) continue; + let bestModule = undefined; + for (const module of chunkGraph.getChunkModulesIterable(chunkA)) { + if ( + bestModule === undefined || + chunkGraph.getNumberOfModuleChunks(bestModule) > + chunkGraph.getNumberOfModuleChunks(module) + ) + bestModule = module; + } + loopB: for (const chunkB of chunkGraph.getModuleChunksIterable( + bestModule + )) { + // as we iterate the same iterables twice + // skip if we find ourselves + if (chunkA === chunkB) continue; + + const chunkBModulesCount = + chunkGraph.getNumberOfChunkModules(chunkB); + + // ids for empty chunks are not included + if (chunkBModulesCount === 0) continue; + + // instead of swapping A and B just bail + // as we loop twice the current A will be B and B then A + if (chunkAModulesCount > chunkBModulesCount) continue; + + // is chunkA in chunkB? + + // we do a cheap check for the hash value + const chunkBHash = chunkModulesHash.get(chunkB); + if ((chunkBHash & chunkAHash) !== chunkAHash) continue; + + // compare all modules + for (const m of chunkGraph.getChunkModulesIterable(chunkA)) { + if (!chunkGraph.isModuleInChunk(m, chunkB)) continue loopB; + } + chunkB.ids.push(chunkA.id); + } + } + } + ); + }); } +} +module.exports = FlagIncludedChunksPlugin; - walkUpdateExpression(expression) { - this.walkExpression(expression.argument); + +/***/ }), + +/***/ 38988: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sergey Melyukov @smelukov +*/ + + + +const { UsageState } = __webpack_require__(63686); + +/** @typedef {import("estree").Node} AnyNode */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +/** @typedef {Map | true>} InnerGraph */ +/** @typedef {function(boolean | Set | undefined): void} UsageCallback */ + +/** + * @typedef {Object} StateObject + * @property {InnerGraph} innerGraph + * @property {TopLevelSymbol=} currentTopLevelSymbol + * @property {Map>} usageCallbackMap + */ + +/** @typedef {false|StateObject} State */ + +/** @type {WeakMap} */ +const parserStateMap = new WeakMap(); +const topLevelSymbolTag = Symbol("top level symbol"); + +/** + * @param {ParserState} parserState parser state + * @returns {State} state + */ +function getState(parserState) { + return parserStateMap.get(parserState); +} + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +exports.bailout = parserState => { + parserStateMap.set(parserState, false); +}; + +/** + * @param {ParserState} parserState parser state + * @returns {void} + */ +exports.enable = parserState => { + const state = parserStateMap.get(parserState); + if (state === false) { + return; } + parserStateMap.set(parserState, { + innerGraph: new Map(), + currentTopLevelSymbol: undefined, + usageCallbackMap: new Map() + }); +}; - walkUnaryExpression(expression) { - if (expression.operator === "typeof") { - const result = this.callHooksForExpression( - this.hooks.typeof, - expression.argument, - expression - ); - if (result === true) return; - if (expression.argument.type === "ChainExpression") { - const result = this.callHooksForExpression( - this.hooks.typeof, - expression.argument.expression, - expression - ); - if (result === true) return; - } +/** + * @param {ParserState} parserState parser state + * @returns {boolean} true, when enabled + */ +exports.isEnabled = parserState => { + const state = parserStateMap.get(parserState); + return !!state; +}; + +/** + * @param {ParserState} state parser state + * @param {TopLevelSymbol | null} symbol the symbol, or null for all symbols + * @param {string | TopLevelSymbol | true} usage usage data + * @returns {void} + */ +exports.addUsage = (state, symbol, usage) => { + const innerGraphState = getState(state); + + if (innerGraphState) { + const { innerGraph } = innerGraphState; + const info = innerGraph.get(symbol); + if (usage === true) { + innerGraph.set(symbol, true); + } else if (info === undefined) { + innerGraph.set(symbol, new Set([usage])); + } else if (info !== true) { + info.add(usage); } - this.walkExpression(expression.argument); } +}; - walkLeftRightExpression(expression) { - this.walkExpression(expression.left); - this.walkExpression(expression.right); +/** + * @param {JavascriptParser} parser the parser + * @param {string} name name of variable + * @param {string | TopLevelSymbol | true} usage usage data + * @returns {void} + */ +exports.addVariableUsage = (parser, name, usage) => { + const symbol = + /** @type {TopLevelSymbol} */ ( + parser.getTagData(name, topLevelSymbolTag) + ) || exports.tagTopLevelSymbol(parser, name); + if (symbol) { + exports.addUsage(parser.state, symbol, usage); } +}; - walkBinaryExpression(expression) { - this.walkLeftRightExpression(expression); - } +/** + * @param {ParserState} state parser state + * @returns {void} + */ +exports.inferDependencyUsage = state => { + const innerGraphState = getState(state); - walkLogicalExpression(expression) { - const result = this.hooks.expressionLogicalOperator.call(expression); - if (result === undefined) { - this.walkLeftRightExpression(expression); - } else { - if (result) { - this.walkExpression(expression.right); - } - } + if (!innerGraphState) { + return; } - walkAssignmentExpression(expression) { - if (expression.left.type === "Identifier") { - const renameIdentifier = this.getRenameIdentifier(expression.right); - if (renameIdentifier) { - if ( - this.callHooksForInfo( - this.hooks.canRename, - renameIdentifier, - expression.right - ) - ) { - // renaming "a = b;" - if ( - !this.callHooksForInfo( - this.hooks.rename, - renameIdentifier, - expression.right - ) - ) { - this.setVariable( - expression.left.name, - this.getVariableInfo(renameIdentifier) - ); - } - return; - } + const { innerGraph, usageCallbackMap } = innerGraphState; + const processed = new Map(); + // flatten graph to terminal nodes (string, undefined or true) + const nonTerminal = new Set(innerGraph.keys()); + while (nonTerminal.size > 0) { + for (const key of nonTerminal) { + /** @type {Set | true} */ + let newSet = new Set(); + let isTerminal = true; + const value = innerGraph.get(key); + let alreadyProcessed = processed.get(key); + if (alreadyProcessed === undefined) { + alreadyProcessed = new Set(); + processed.set(key, alreadyProcessed); } - this.walkExpression(expression.right); - this.enterPattern(expression.left, (name, decl) => { - if (!this.callHooksForName(this.hooks.assign, name, expression)) { - this.walkExpression(expression.left); + if (value !== true && value !== undefined) { + for (const item of value) { + alreadyProcessed.add(item); } - }); - return; - } - if (expression.left.type.endsWith("Pattern")) { - this.walkExpression(expression.right); - this.enterPattern(expression.left, (name, decl) => { - if (!this.callHooksForName(this.hooks.assign, name, expression)) { - this.defineVariable(name); + for (const item of value) { + if (typeof item === "string") { + newSet.add(item); + } else { + const itemValue = innerGraph.get(item); + if (itemValue === true) { + newSet = true; + break; + } + if (itemValue !== undefined) { + for (const i of itemValue) { + if (i === key) continue; + if (alreadyProcessed.has(i)) continue; + newSet.add(i); + if (typeof i !== "string") { + isTerminal = false; + } + } + } + } } - }); - this.walkPattern(expression.left); - } else if (expression.left.type === "MemberExpression") { - const exprName = this.getMemberExpressionInfo( - expression.left, - ALLOWED_MEMBER_TYPES_EXPRESSION - ); - if (exprName) { - if ( - this.callHooksForInfo( - this.hooks.assignMemberChain, - exprName.rootInfo, - expression, - exprName.getMembers() - ) - ) { - return; + if (newSet === true) { + innerGraph.set(key, true); + } else if (newSet.size === 0) { + innerGraph.set(key, undefined); + } else { + innerGraph.set(key, newSet); } } - this.walkExpression(expression.right); - this.walkExpression(expression.left); - } else { - this.walkExpression(expression.right); - this.walkExpression(expression.left); - } - } + if (isTerminal) { + nonTerminal.delete(key); - walkConditionalExpression(expression) { - const result = this.hooks.expressionConditionalOperator.call(expression); - if (result === undefined) { - this.walkExpression(expression.test); - this.walkExpression(expression.consequent); - if (expression.alternate) { - this.walkExpression(expression.alternate); - } - } else { - if (result) { - this.walkExpression(expression.consequent); - } else if (expression.alternate) { - this.walkExpression(expression.alternate); + // For the global key, merge with all other keys + if (key === null) { + const globalValue = innerGraph.get(null); + if (globalValue) { + for (const [key, value] of innerGraph) { + if (key !== null && value !== true) { + if (globalValue === true) { + innerGraph.set(key, true); + } else { + const newSet = new Set(value); + for (const item of globalValue) { + newSet.add(item); + } + innerGraph.set(key, newSet); + } + } + } + } + } } } } - walkNewExpression(expression) { - const result = this.callHooksForExpression( - this.hooks.new, - expression.callee, - expression + /** @type {Map>} */ + for (const [symbol, callbacks] of usageCallbackMap) { + const usage = /** @type {true | Set | undefined} */ ( + innerGraph.get(symbol) ); - if (result === true) return; - this.walkExpression(expression.callee); - if (expression.arguments) { - this.walkExpressions(expression.arguments); + for (const callback of callbacks) { + callback(usage === undefined ? false : usage); } } +}; - walkYieldExpression(expression) { - if (expression.argument) { - this.walkExpression(expression.argument); - } - } +/** + * @param {ParserState} state parser state + * @param {UsageCallback} onUsageCallback on usage callback + */ +exports.onUsage = (state, onUsageCallback) => { + const innerGraphState = getState(state); - walkTemplateLiteral(expression) { - if (expression.expressions) { - this.walkExpressions(expression.expressions); - } - } + if (innerGraphState) { + const { usageCallbackMap, currentTopLevelSymbol } = innerGraphState; + if (currentTopLevelSymbol) { + let callbacks = usageCallbackMap.get(currentTopLevelSymbol); - walkTaggedTemplateExpression(expression) { - if (expression.tag) { - this.walkExpression(expression.tag); - } - if (expression.quasi && expression.quasi.expressions) { - this.walkExpressions(expression.quasi.expressions); + if (callbacks === undefined) { + callbacks = new Set(); + usageCallbackMap.set(currentTopLevelSymbol, callbacks); + } + + callbacks.add(onUsageCallback); + } else { + onUsageCallback(true); } + } else { + onUsageCallback(undefined); } +}; - walkClassExpression(expression) { - this.walkClass(expression); +/** + * @param {ParserState} state parser state + * @param {TopLevelSymbol} symbol the symbol + */ +exports.setTopLevelSymbol = (state, symbol) => { + const innerGraphState = getState(state); + + if (innerGraphState) { + innerGraphState.currentTopLevelSymbol = symbol; } +}; - /** - * @param {ChainExpressionNode} expression expression - */ - walkChainExpression(expression) { - const result = this.hooks.optionalChaining.call(expression); +/** + * @param {ParserState} state parser state + * @returns {TopLevelSymbol|void} usage data + */ +exports.getTopLevelSymbol = state => { + const innerGraphState = getState(state); - if (result === undefined) { - if (expression.expression.type === "CallExpression") { - this.walkCallExpression(expression.expression); - } else { - this.walkMemberExpression(expression.expression); - } - } + if (innerGraphState) { + return innerGraphState.currentTopLevelSymbol; } +}; - _walkIIFE(functionExpression, options, currentThis) { - const getVarInfo = argOrThis => { - const renameIdentifier = this.getRenameIdentifier(argOrThis); - if (renameIdentifier) { - if ( - this.callHooksForInfo( - this.hooks.canRename, - renameIdentifier, - argOrThis - ) - ) { - if ( - !this.callHooksForInfo( - this.hooks.rename, - renameIdentifier, - argOrThis - ) - ) { - return this.getVariableInfo(renameIdentifier); - } - } - } - this.walkExpression(argOrThis); - }; - const { params, type } = functionExpression; - const arrow = type === "ArrowFunctionExpression"; - const renameThis = currentThis ? getVarInfo(currentThis) : null; - const varInfoForArgs = options.map(getVarInfo); - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = wasTopLevel && arrow ? "arrow" : false; - const scopeParams = params.filter( - (identifier, idx) => !varInfoForArgs[idx] - ); +/** + * @param {JavascriptParser} parser parser + * @param {string} name name of variable + * @returns {TopLevelSymbol} symbol + */ +exports.tagTopLevelSymbol = (parser, name) => { + const innerGraphState = getState(parser.state); + if (!innerGraphState) return; - // Add function name in scope for recursive calls - if (functionExpression.id) { - scopeParams.push(functionExpression.id.name); - } + parser.defineVariable(name); - this.inFunctionScope(true, scopeParams, () => { - if (renameThis && !arrow) { - this.setVariable("this", renameThis); - } - for (let i = 0; i < varInfoForArgs.length; i++) { - const varInfo = varInfoForArgs[i]; - if (!varInfo) continue; - if (!params[i] || params[i].type !== "Identifier") continue; - this.setVariable(params[i].name, varInfo); - } - if (functionExpression.body.type === "BlockStatement") { - this.detectMode(functionExpression.body.body); - const prev = this.prevStatement; - this.preWalkStatement(functionExpression.body); - this.prevStatement = prev; - this.walkStatement(functionExpression.body); - } else { - this.walkExpression(functionExpression.body); - } - }); - this.scope.topLevelScope = wasTopLevel; + const existingTag = /** @type {TopLevelSymbol} */ ( + parser.getTagData(name, topLevelSymbolTag) + ); + if (existingTag) { + return existingTag; } - walkImportExpression(expression) { - let result = this.hooks.importCall.call(expression); - if (result === true) return; + const fn = new TopLevelSymbol(name); + parser.tagVariable(name, topLevelSymbolTag, fn); + return fn; +}; - this.walkExpression(expression.source); - } - - walkCallExpression(expression) { - const isSimpleFunction = fn => { - return fn.params.every(p => p.type === "Identifier"); - }; - if ( - expression.callee.type === "MemberExpression" && - expression.callee.object.type.endsWith("FunctionExpression") && - !expression.callee.computed && - (expression.callee.property.name === "call" || - expression.callee.property.name === "bind") && - expression.arguments.length > 0 && - isSimpleFunction(expression.callee.object) - ) { - // (function(…) { }.call/bind(?, …)) - this._walkIIFE( - expression.callee.object, - expression.arguments.slice(1), - expression.arguments[0] - ); - } else if ( - expression.callee.type.endsWith("FunctionExpression") && - isSimpleFunction(expression.callee) - ) { - // (function(…) { }(…)) - this._walkIIFE(expression.callee, expression.arguments, null); - } else { - if (expression.callee.type === "MemberExpression") { - const exprInfo = this.getMemberExpressionInfo( - expression.callee, - ALLOWED_MEMBER_TYPES_CALL_EXPRESSION - ); - if (exprInfo && exprInfo.type === "call") { - const result = this.callHooksForInfo( - this.hooks.callMemberChainOfCallMemberChain, - exprInfo.rootInfo, - expression, - exprInfo.getCalleeMembers(), - exprInfo.call, - exprInfo.getMembers() - ); - if (result === true) return; - } - } - const callee = this.evaluateExpression(expression.callee); - if (callee.isIdentifier()) { - const result1 = this.callHooksForInfo( - this.hooks.callMemberChain, - callee.rootInfo, - expression, - callee.getMembers() - ); - if (result1 === true) return; - const result2 = this.callHooksForInfo( - this.hooks.call, - callee.identifier, - expression - ); - if (result2 === true) return; - } - - if (expression.callee) { - if (expression.callee.type === "MemberExpression") { - // because of call context we need to walk the call context as expression - this.walkExpression(expression.callee.object); - if (expression.callee.computed === true) - this.walkExpression(expression.callee.property); - } else { - this.walkExpression(expression.callee); - } - } - if (expression.arguments) this.walkExpressions(expression.arguments); +/** + * @param {Dependency} dependency the dependency + * @param {Set | boolean} usedByExports usedByExports info + * @param {ModuleGraph} moduleGraph moduleGraph + * @param {RuntimeSpec} runtime runtime + * @returns {boolean} false, when unused. Otherwise true + */ +exports.isDependencyUsedByExports = ( + dependency, + usedByExports, + moduleGraph, + runtime +) => { + if (usedByExports === false) return false; + if (usedByExports !== true && usedByExports !== undefined) { + const selfModule = moduleGraph.getParentModule(dependency); + const exportsInfo = moduleGraph.getExportsInfo(selfModule); + let used = false; + for (const exportName of usedByExports) { + if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) + used = true; } + if (!used) return false; } + return true; +}; - walkMemberExpression(expression) { - const exprInfo = this.getMemberExpressionInfo( - expression, - ALLOWED_MEMBER_TYPES_ALL - ); - if (exprInfo) { - switch (exprInfo.type) { - case "expression": { - const result1 = this.callHooksForInfo( - this.hooks.expression, - exprInfo.name, - expression - ); - if (result1 === true) return; - const members = exprInfo.getMembers(); - const result2 = this.callHooksForInfo( - this.hooks.expressionMemberChain, - exprInfo.rootInfo, - expression, - members - ); - if (result2 === true) return; - this.walkMemberExpressionWithExpressionName( - expression, - exprInfo.name, - exprInfo.rootInfo, - members.slice(), - () => - this.callHooksForInfo( - this.hooks.unhandledExpressionMemberChain, - exprInfo.rootInfo, - expression, - members - ) - ); - return; - } - case "call": { - const result = this.callHooksForInfo( - this.hooks.memberChainOfCallMemberChain, - exprInfo.rootInfo, - expression, - exprInfo.getCalleeMembers(), - exprInfo.call, - exprInfo.getMembers() - ); - if (result === true) return; - // Fast skip over the member chain as we already called memberChainOfCallMemberChain - // and call computed property are literals anyway - this.walkExpression(exprInfo.call); - return; - } +/** + * @param {Dependency} dependency the dependency + * @param {Set | boolean} usedByExports usedByExports info + * @param {ModuleGraph} moduleGraph moduleGraph + * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active + */ +exports.getDependencyUsedByExportsCondition = ( + dependency, + usedByExports, + moduleGraph +) => { + if (usedByExports === false) return false; + if (usedByExports !== true && usedByExports !== undefined) { + const selfModule = moduleGraph.getParentModule(dependency); + const exportsInfo = moduleGraph.getExportsInfo(selfModule); + return (connections, runtime) => { + for (const exportName of usedByExports) { + if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) + return true; } - } - this.walkExpression(expression.object); - if (expression.computed === true) this.walkExpression(expression.property); + return false; + }; } + return null; +}; - walkMemberExpressionWithExpressionName( - expression, - name, - rootInfo, - members, - onUnhandled - ) { - if (expression.object.type === "MemberExpression") { - // optimize the case where expression.object is a MemberExpression too. - // we can keep info here when calling walkMemberExpression directly - const property = - expression.property.name || `${expression.property.value}`; - name = name.slice(0, -property.length - 1); - members.pop(); - const result = this.callHooksForInfo( - this.hooks.expression, - name, - expression.object - ); - if (result === true) return; - this.walkMemberExpressionWithExpressionName( - expression.object, - name, - rootInfo, - members, - onUnhandled - ); - } else if (!onUnhandled || !onUnhandled()) { - this.walkExpression(expression.object); - } - if (expression.computed === true) this.walkExpression(expression.property); +class TopLevelSymbol { + /** + * @param {string} name name of the variable + */ + constructor(name) { + this.name = name; } +} - walkThisExpression(expression) { - this.callHooksForName(this.hooks.expression, "this", expression); - } +exports.TopLevelSymbol = TopLevelSymbol; +exports.topLevelSymbolTag = topLevelSymbolTag; - walkIdentifier(expression) { - this.callHooksForName(this.hooks.expression, expression.name, expression); - } - /** - * @param {MetaPropertyNode} metaProperty meta property - */ - walkMetaProperty(metaProperty) { - this.hooks.expression.for(getRootName(metaProperty)).call(metaProperty); - } +/***/ }), - callHooksForExpression(hookMap, expr, ...args) { - return this.callHooksForExpressionWithFallback( - hookMap, - expr, - undefined, - undefined, - ...args - ); - } +/***/ 28758: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @template T - * @template R - * @param {HookMap>} hookMap hooks the should be called - * @param {MemberExpressionNode} expr expression info - * @param {function(string, string | ScopeInfo | VariableInfo, function(): string[]): any} fallback callback when variable in not handled by hooks - * @param {function(string): any} defined callback when variable is defined - * @param {AsArray} args args for the hook - * @returns {R} result of hook - */ - callHooksForExpressionWithFallback( - hookMap, - expr, - fallback, - defined, - ...args - ) { - const exprName = this.getMemberExpressionInfo( - expr, - ALLOWED_MEMBER_TYPES_EXPRESSION - ); - if (exprName !== undefined) { - const members = exprName.getMembers(); - return this.callHooksForInfoWithFallback( - hookMap, - members.length === 0 ? exprName.rootInfo : exprName.name, - fallback && - (name => fallback(name, exprName.rootInfo, exprName.getMembers)), - defined && (() => defined(exprName.name)), - ...args - ); - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @template T - * @template R - * @param {HookMap>} hookMap hooks the should be called - * @param {string} name key in map - * @param {AsArray} args args for the hook - * @returns {R} result of hook - */ - callHooksForName(hookMap, name, ...args) { - return this.callHooksForNameWithFallback( - hookMap, - name, - undefined, - undefined, - ...args - ); - } - /** - * @template T - * @template R - * @param {HookMap>} hookMap hooks that should be called - * @param {ExportedVariableInfo} info variable info - * @param {AsArray} args args for the hook - * @returns {R} result of hook - */ - callHooksForInfo(hookMap, info, ...args) { - return this.callHooksForInfoWithFallback( - hookMap, - info, - undefined, - undefined, - ...args - ); - } - /** - * @template T - * @template R - * @param {HookMap>} hookMap hooks the should be called - * @param {ExportedVariableInfo} info variable info - * @param {function(string): any} fallback callback when variable in not handled by hooks - * @param {function(): any} defined callback when variable is defined - * @param {AsArray} args args for the hook - * @returns {R} result of hook - */ - callHooksForInfoWithFallback(hookMap, info, fallback, defined, ...args) { - let name; - if (typeof info === "string") { - name = info; - } else { - if (!(info instanceof VariableInfo)) { - if (defined !== undefined) { - return defined(); - } - return; - } - let tagInfo = info.tagInfo; - while (tagInfo !== undefined) { - const hook = hookMap.get(tagInfo.tag); - if (hook !== undefined) { - this.currentTagData = tagInfo.data; - const result = hook.call(...args); - this.currentTagData = undefined; - if (result !== undefined) return result; - } - tagInfo = tagInfo.next; - } - if (info.freeName === true) { - if (defined !== undefined) { - return defined(); - } - return; - } - name = info.freeName; - } - const hook = hookMap.get(name); - if (hook !== undefined) { - const result = hook.call(...args); - if (result !== undefined) return result; - } - if (fallback !== undefined) { - return fallback(name); - } - } +const PureExpressionDependency = __webpack_require__(55799); +const InnerGraph = __webpack_require__(38988); - /** - * @template T - * @template R - * @param {HookMap>} hookMap hooks the should be called - * @param {string} name key in map - * @param {function(string): any} fallback callback when variable in not handled by hooks - * @param {function(): any} defined callback when variable is defined - * @param {AsArray} args args for the hook - * @returns {R} result of hook - */ - callHooksForNameWithFallback(hookMap, name, fallback, defined, ...args) { - return this.callHooksForInfoWithFallback( - hookMap, - this.getVariableInfo(name), - fallback, - defined, - ...args - ); - } +/** @typedef {import("estree").ClassDeclaration} ClassDeclarationNode */ +/** @typedef {import("estree").ClassExpression} ClassExpressionNode */ +/** @typedef {import("estree").Node} Node */ +/** @typedef {import("estree").VariableDeclarator} VariableDeclaratorNode */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../dependencies/HarmonyImportSpecifierDependency")} HarmonyImportSpecifierDependency */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +/** @typedef {import("./InnerGraph").InnerGraph} InnerGraph */ +/** @typedef {import("./InnerGraph").TopLevelSymbol} TopLevelSymbol */ + +const { topLevelSymbolTag } = InnerGraph; +class InnerGraphPlugin { /** - * @deprecated - * @param {any} params scope params - * @param {function(): void} fn inner function + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - inScope(params, fn) { - const oldScope = this.scope; - this.scope = { - topLevelScope: oldScope.topLevelScope, - inTry: false, - inShorthand: false, - isStrict: oldScope.isStrict, - isAsmJs: oldScope.isAsmJs, - definitions: oldScope.definitions.createChild() - }; + apply(compiler) { + compiler.hooks.compilation.tap( + "InnerGraphPlugin", + (compilation, { normalModuleFactory }) => { + const logger = compilation.getLogger("webpack.InnerGraphPlugin"); - this.undefineVariable("this"); + compilation.dependencyTemplates.set( + PureExpressionDependency, + new PureExpressionDependency.Template() + ); - this.enterPatterns(params, (ident, pattern) => { - this.defineVariable(ident); - }); + /** + * @param {JavascriptParser} parser the parser + * @param {Object} parserOptions options + * @returns {void} + */ + const handler = (parser, parserOptions) => { + const onUsageSuper = sup => { + InnerGraph.onUsage(parser.state, usedByExports => { + switch (usedByExports) { + case undefined: + case true: + return; + default: { + const dep = new PureExpressionDependency(sup.range); + dep.loc = sup.loc; + dep.usedByExports = usedByExports; + parser.state.module.addDependency(dep); + break; + } + } + }); + }; - fn(); + parser.hooks.program.tap("InnerGraphPlugin", () => { + InnerGraph.enable(parser.state); + }); - this.scope = oldScope; - } + parser.hooks.finish.tap("InnerGraphPlugin", () => { + if (!InnerGraph.isEnabled(parser.state)) return; - inFunctionScope(hasThis, params, fn) { - const oldScope = this.scope; - this.scope = { - topLevelScope: oldScope.topLevelScope, - inTry: false, - inShorthand: false, - isStrict: oldScope.isStrict, - isAsmJs: oldScope.isAsmJs, - definitions: oldScope.definitions.createChild() - }; + logger.time("infer dependency usage"); + InnerGraph.inferDependencyUsage(parser.state); + logger.timeAggregate("infer dependency usage"); + }); - if (hasThis) { - this.undefineVariable("this"); - } + // During prewalking the following datastructures are filled with + // nodes that have a TopLevelSymbol assigned and + // variables are tagged with the assigned TopLevelSymbol - this.enterPatterns(params, (ident, pattern) => { - this.defineVariable(ident); - }); + // We differ 3 types of nodes: + // 1. full statements (export default, function declaration) + // 2. classes (class declaration, class expression) + // 3. variable declarators (const x = ...) - fn(); + /** @type {WeakMap} */ + const statementWithTopLevelSymbol = new WeakMap(); + /** @type {WeakMap} */ + const statementPurePart = new WeakMap(); - this.scope = oldScope; - } + /** @type {WeakMap} */ + const classWithTopLevelSymbol = new WeakMap(); - inBlockScope(fn) { - const oldScope = this.scope; - this.scope = { - topLevelScope: oldScope.topLevelScope, - inTry: oldScope.inTry, - inShorthand: false, - isStrict: oldScope.isStrict, - isAsmJs: oldScope.isAsmJs, - definitions: oldScope.definitions.createChild() - }; + /** @type {WeakMap} */ + const declWithTopLevelSymbol = new WeakMap(); + /** @type {WeakSet} */ + const pureDeclarators = new WeakSet(); - fn(); + // The following hooks are used during prewalking: - this.scope = oldScope; - } + parser.hooks.preStatement.tap("InnerGraphPlugin", statement => { + if (!InnerGraph.isEnabled(parser.state)) return; - detectMode(statements) { - const isLiteral = - statements.length >= 1 && - statements[0].type === "ExpressionStatement" && - statements[0].expression.type === "Literal"; - if (isLiteral && statements[0].expression.value === "use strict") { - this.scope.isStrict = true; - } - if (isLiteral && statements[0].expression.value === "use asm") { - this.scope.isAsmJs = true; - } - } + if (parser.scope.topLevelScope === true) { + if (statement.type === "FunctionDeclaration") { + const name = statement.id ? statement.id.name : "*default*"; + const fn = InnerGraph.tagTopLevelSymbol(parser, name); + statementWithTopLevelSymbol.set(statement, fn); + return true; + } + } + }); - enterPatterns(patterns, onIdent) { - for (const pattern of patterns) { - if (typeof pattern !== "string") { - this.enterPattern(pattern, onIdent); - } else if (pattern) { - onIdent(pattern); - } - } - } + parser.hooks.blockPreStatement.tap("InnerGraphPlugin", statement => { + if (!InnerGraph.isEnabled(parser.state)) return; - enterPattern(pattern, onIdent) { - if (!pattern) return; - switch (pattern.type) { - case "ArrayPattern": - this.enterArrayPattern(pattern, onIdent); - break; - case "AssignmentPattern": - this.enterAssignmentPattern(pattern, onIdent); - break; - case "Identifier": - this.enterIdentifier(pattern, onIdent); - break; - case "ObjectPattern": - this.enterObjectPattern(pattern, onIdent); - break; - case "RestElement": - this.enterRestElement(pattern, onIdent); - break; - case "Property": - if (pattern.shorthand && pattern.value.type === "Identifier") { - this.scope.inShorthand = pattern.value.name; - this.enterIdentifier(pattern.value, onIdent); - this.scope.inShorthand = false; - } else { - this.enterPattern(pattern.value, onIdent); - } - break; - } - } + if (parser.scope.topLevelScope === true) { + if (statement.type === "ClassDeclaration") { + const name = statement.id ? statement.id.name : "*default*"; + const fn = InnerGraph.tagTopLevelSymbol(parser, name); + classWithTopLevelSymbol.set(statement, fn); + return true; + } + if (statement.type === "ExportDefaultDeclaration") { + const name = "*default*"; + const fn = InnerGraph.tagTopLevelSymbol(parser, name); + const decl = statement.declaration; + if ( + decl.type === "ClassExpression" || + decl.type === "ClassDeclaration" + ) { + classWithTopLevelSymbol.set(decl, fn); + } else if (parser.isPure(decl, statement.range[0])) { + statementWithTopLevelSymbol.set(statement, fn); + if ( + !decl.type.endsWith("FunctionExpression") && + !decl.type.endsWith("Declaration") && + decl.type !== "Literal" + ) { + statementPurePart.set(statement, decl); + } + } + } + } + }); - enterIdentifier(pattern, onIdent) { - if (!this.callHooksForName(this.hooks.pattern, pattern.name, pattern)) { - onIdent(pattern.name, pattern); - } - } + parser.hooks.preDeclarator.tap( + "InnerGraphPlugin", + (decl, statement) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if ( + parser.scope.topLevelScope === true && + decl.init && + decl.id.type === "Identifier" + ) { + const name = decl.id.name; + if (decl.init.type === "ClassExpression") { + const fn = InnerGraph.tagTopLevelSymbol(parser, name); + classWithTopLevelSymbol.set(decl.init, fn); + } else if (parser.isPure(decl.init, decl.id.range[1])) { + const fn = InnerGraph.tagTopLevelSymbol(parser, name); + declWithTopLevelSymbol.set(decl, fn); + if ( + !decl.init.type.endsWith("FunctionExpression") && + decl.init.type !== "Literal" + ) { + pureDeclarators.add(decl); + } + return true; + } + } + } + ); - enterObjectPattern(pattern, onIdent) { - for ( - let propIndex = 0, len = pattern.properties.length; - propIndex < len; - propIndex++ - ) { - const prop = pattern.properties[propIndex]; - this.enterPattern(prop, onIdent); - } - } + // During real walking we set the TopLevelSymbol state to the assigned + // TopLevelSymbol by using the fill datastructures. - enterArrayPattern(pattern, onIdent) { - for ( - let elementIndex = 0, len = pattern.elements.length; - elementIndex < len; - elementIndex++ - ) { - const element = pattern.elements[elementIndex]; - this.enterPattern(element, onIdent); - } - } + // In addition to tracking TopLevelSymbols, we sometimes need to + // add a PureExpressionDependency. This is needed to skip execution + // of pure expressions, even when they are not dropped due to + // minimizing. Otherwise symbols used there might not exist anymore + // as they are removed as unused by this optimization - enterRestElement(pattern, onIdent) { - this.enterPattern(pattern.argument, onIdent); - } + // When we find a reference to a TopLevelSymbol, we register a + // TopLevelSymbol dependency from TopLevelSymbol in state to the + // referenced TopLevelSymbol. This way we get a graph of all + // TopLevelSymbols. - enterAssignmentPattern(pattern, onIdent) { - this.enterPattern(pattern.left, onIdent); - } + // The following hooks are called during walking: - /** - * @param {ExpressionNode} expression expression node - * @returns {BasicEvaluatedExpression | undefined} evaluation result - */ - evaluateExpression(expression) { - try { - const hook = this.hooks.evaluate.get(expression.type); - if (hook !== undefined) { - const result = hook.call(expression); - if (result !== undefined) { - if (result) { - result.setExpression(expression); - } - return result; - } - } - } catch (e) { - console.warn(e); - // ignore error - } - return new BasicEvaluatedExpression() - .setRange(expression.range) - .setExpression(expression); - } + parser.hooks.statement.tap("InnerGraphPlugin", statement => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (parser.scope.topLevelScope === true) { + InnerGraph.setTopLevelSymbol(parser.state, undefined); - parseString(expression) { - switch (expression.type) { - case "BinaryExpression": - if (expression.operator === "+") { - return ( - this.parseString(expression.left) + - this.parseString(expression.right) + const fn = statementWithTopLevelSymbol.get(statement); + if (fn) { + InnerGraph.setTopLevelSymbol(parser.state, fn); + const purePart = statementPurePart.get(statement); + if (purePart) { + InnerGraph.onUsage(parser.state, usedByExports => { + switch (usedByExports) { + case undefined: + case true: + return; + default: { + const dep = new PureExpressionDependency( + purePart.range + ); + dep.loc = statement.loc; + dep.usedByExports = usedByExports; + parser.state.module.addDependency(dep); + break; + } + } + }); + } + } + } + }); + + parser.hooks.classExtendsExpression.tap( + "InnerGraphPlugin", + (expr, statement) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (parser.scope.topLevelScope === true) { + const fn = classWithTopLevelSymbol.get(statement); + if ( + fn && + parser.isPure( + expr, + statement.id ? statement.id.range[1] : statement.range[0] + ) + ) { + InnerGraph.setTopLevelSymbol(parser.state, fn); + onUsageSuper(expr); + } + } + } ); - } - break; - case "Literal": - return expression.value + ""; - } - throw new Error( - expression.type + " is not supported as parameter for require" - ); - } - parseCalculatedString(expression) { - switch (expression.type) { - case "BinaryExpression": - if (expression.operator === "+") { - const left = this.parseCalculatedString(expression.left); - const right = this.parseCalculatedString(expression.right); - if (left.code) { - return { - range: left.range, - value: left.value, - code: true, - conditional: false - }; - } else if (right.code) { - return { - range: [ - left.range[0], - right.range ? right.range[1] : left.range[1] - ], - value: left.value + right.value, - code: true, - conditional: false - }; - } else { - return { - range: [left.range[0], right.range[1]], - value: left.value + right.value, - code: false, - conditional: false - }; - } - } - break; - case "ConditionalExpression": { - const consequent = this.parseCalculatedString(expression.consequent); - const alternate = this.parseCalculatedString(expression.alternate); - const items = []; - if (consequent.conditional) { - items.push(...consequent.conditional); - } else if (!consequent.code) { - items.push(consequent); - } else { - break; - } - if (alternate.conditional) { - items.push(...alternate.conditional); - } else if (!alternate.code) { - items.push(alternate); - } else { - break; - } - return { - range: undefined, - value: "", - code: true, - conditional: items + parser.hooks.classBodyElement.tap( + "InnerGraphPlugin", + (element, classDefinition) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (parser.scope.topLevelScope === true) { + const fn = classWithTopLevelSymbol.get(classDefinition); + if (fn) { + InnerGraph.setTopLevelSymbol(parser.state, undefined); + } + } + } + ); + + parser.hooks.classBodyValue.tap( + "InnerGraphPlugin", + (expression, element, classDefinition) => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (parser.scope.topLevelScope === true) { + const fn = classWithTopLevelSymbol.get(classDefinition); + if (fn) { + if ( + !element.static || + parser.isPure( + expression, + element.key ? element.key.range[1] : element.range[0] + ) + ) { + InnerGraph.setTopLevelSymbol(parser.state, fn); + if (element.type !== "MethodDefinition" && element.static) { + InnerGraph.onUsage(parser.state, usedByExports => { + switch (usedByExports) { + case undefined: + case true: + return; + default: { + const dep = new PureExpressionDependency( + expression.range + ); + dep.loc = expression.loc; + dep.usedByExports = usedByExports; + parser.state.module.addDependency(dep); + break; + } + } + }); + } + } else { + InnerGraph.setTopLevelSymbol(parser.state, undefined); + } + } + } + } + ); + + parser.hooks.declarator.tap("InnerGraphPlugin", (decl, statement) => { + if (!InnerGraph.isEnabled(parser.state)) return; + const fn = declWithTopLevelSymbol.get(decl); + + if (fn) { + InnerGraph.setTopLevelSymbol(parser.state, fn); + if (pureDeclarators.has(decl)) { + if (decl.init.type === "ClassExpression") { + if (decl.init.superClass) { + onUsageSuper(decl.init.superClass); + } + } else { + InnerGraph.onUsage(parser.state, usedByExports => { + switch (usedByExports) { + case undefined: + case true: + return; + default: { + const dep = new PureExpressionDependency( + decl.init.range + ); + dep.loc = decl.loc; + dep.usedByExports = usedByExports; + parser.state.module.addDependency(dep); + break; + } + } + }); + } + } + parser.walkExpression(decl.init); + InnerGraph.setTopLevelSymbol(parser.state, undefined); + return true; + } + }); + + parser.hooks.expression + .for(topLevelSymbolTag) + .tap("InnerGraphPlugin", () => { + const topLevelSymbol = /** @type {TopLevelSymbol} */ ( + parser.currentTagData + ); + const currentTopLevelSymbol = InnerGraph.getTopLevelSymbol( + parser.state + ); + InnerGraph.addUsage( + parser.state, + topLevelSymbol, + currentTopLevelSymbol || true + ); + }); + parser.hooks.assign + .for(topLevelSymbolTag) + .tap("InnerGraphPlugin", expr => { + if (!InnerGraph.isEnabled(parser.state)) return; + if (expr.operator === "=") return true; + }); }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("InnerGraphPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("InnerGraphPlugin", handler); + + compilation.hooks.finishModules.tap("InnerGraphPlugin", () => { + logger.timeAggregateEnd("infer dependency usage"); + }); } - case "Literal": - return { - range: expression.range, - value: expression.value + "", - code: false, - conditional: false - }; - } - return { - range: undefined, - value: "", - code: true, - conditional: false - }; + ); } +} - /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state - */ - parse(source, state) { - let ast; - let comments; - const semicolons = new Set(); - if (source === null) { - throw new Error("source must not be null"); - } - if (Buffer.isBuffer(source)) { - source = source.toString("utf-8"); - } - if (typeof source === "object") { - ast = /** @type {ProgramNode} */ (source); - comments = source.comments; - } else { - comments = []; - ast = JavascriptParser._parse(source, { - sourceType: this.sourceType, - onComment: comments, - onInsertedSemicolon: pos => semicolons.add(pos) - }); - } +module.exports = InnerGraphPlugin; - const oldScope = this.scope; - const oldState = this.state; - const oldComments = this.comments; - const oldSemicolons = this.semicolons; - const oldStatementPath = this.statementPath; - const oldPrevStatement = this.prevStatement; - this.scope = { - topLevelScope: true, - inTry: false, - inShorthand: false, - isStrict: false, - isAsmJs: false, - definitions: new StackedMap() - }; - /** @type {ParserState} */ - this.state = state; - this.comments = comments; - this.semicolons = semicolons; - this.statementPath = []; - this.prevStatement = undefined; - if (this.hooks.program.call(ast, comments) === undefined) { - this.detectMode(ast.body); - this.preWalkStatements(ast.body); - this.prevStatement = undefined; - this.blockPreWalkStatements(ast.body); - this.prevStatement = undefined; - this.walkStatements(ast.body); - } - this.hooks.finish.call(ast, comments); - this.scope = oldScope; - /** @type {ParserState} */ - this.state = oldState; - this.comments = oldComments; - this.semicolons = oldSemicolons; - this.statementPath = oldStatementPath; - this.prevStatement = oldPrevStatement; - return state; - } - evaluate(source) { - const ast = JavascriptParser._parse("(" + source + ")", { - sourceType: this.sourceType, - locations: false - }); - if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") { - throw new Error("evaluate: Source is not a expression"); - } - return this.evaluateExpression(ast.body[0].expression); - } +/***/ }), - /** - * @param {ExpressionNode | DeclarationNode | PrivateIdentifierNode | null | undefined} expr an expression - * @param {number} commentsStartPos source position from which annotation comments are checked - * @returns {boolean} true, when the expression is pure - */ - isPure(expr, commentsStartPos) { - if (!expr) return true; - const result = this.hooks.isPure - .for(expr.type) - .call(expr, commentsStartPos); - if (typeof result === "boolean") return result; - switch (expr.type) { - case "ClassDeclaration": - case "ClassExpression": { - if (expr.body.type !== "ClassBody") return false; - if (expr.superClass && !this.isPure(expr.superClass, expr.range[0])) { - return false; - } - const items = - /** @type {(MethodDefinitionNode | PropertyDefinitionNode)[]} */ ( - expr.body.body - ); - return items.every( - item => - (!item.computed || - !item.key || - this.isPure(item.key, item.range[0])) && - (!item.static || - !item.value || - this.isPure( - item.value, - item.key ? item.key.range[1] : item.range[0] - )) - ); - } +/***/ 83608: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - case "FunctionDeclaration": - case "FunctionExpression": - case "ArrowFunctionExpression": - case "Literal": - case "PrivateIdentifier": - return true; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - case "VariableDeclaration": - return expr.declarations.every(decl => - this.isPure(decl.init, decl.range[0]) - ); - case "ConditionalExpression": - return ( - this.isPure(expr.test, commentsStartPos) && - this.isPure(expr.consequent, expr.test.range[1]) && - this.isPure(expr.alternate, expr.consequent.range[1]) - ); - case "SequenceExpression": - return expr.expressions.every(expr => { - const pureFlag = this.isPure(expr, commentsStartPos); - commentsStartPos = expr.range[1]; - return pureFlag; - }); +const { STAGE_ADVANCED } = __webpack_require__(80057); +const LazyBucketSortedSet = __webpack_require__(48424); +const { compareChunks } = __webpack_require__(29579); +const createSchemaValidation = __webpack_require__(32540); - case "CallExpression": { - const pureFlag = - expr.range[0] - commentsStartPos > 12 && - this.getComments([commentsStartPos, expr.range[0]]).some( - comment => - comment.type === "Block" && - /^\s*(#|@)__PURE__\s*$/.test(comment.value) - ); - if (!pureFlag) return false; - commentsStartPos = expr.callee.range[1]; - return expr.arguments.every(arg => { - if (arg.type === "SpreadElement") return false; - const pureFlag = this.isPure(arg, commentsStartPos); - commentsStartPos = arg.range[1]; - return pureFlag; - }); - } - } - const evaluated = this.evaluateExpression(expr); - return !evaluated.couldHaveSideEffects(); +/** @typedef {import("../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions} LimitChunkCountPluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ + +const validate = createSchemaValidation( + __webpack_require__(36557), + () => __webpack_require__(30837), + { + name: "Limit Chunk Count Plugin", + baseDataPath: "options" } +); - getComments(range) { - const [rangeStart, rangeEnd] = range; - const compare = (comment, needle) => comment.range[0] - needle; - let idx = binarySearchBounds.ge(this.comments, rangeStart, compare); - let commentsInRange = []; - while (this.comments[idx] && this.comments[idx].range[1] <= rangeEnd) { - commentsInRange.push(this.comments[idx]); - idx++; - } +/** + * @typedef {Object} ChunkCombination + * @property {boolean} deleted this is set to true when combination was removed + * @property {number} sizeDiff + * @property {number} integratedSize + * @property {Chunk} a + * @property {Chunk} b + * @property {number} aIdx + * @property {number} bIdx + * @property {number} aSize + * @property {number} bSize + */ - return commentsInRange; +const addToSetMap = (map, key, value) => { + const set = map.get(key); + if (set === undefined) { + map.set(key, new Set([value])); + } else { + set.add(value); } +}; +class LimitChunkCountPlugin { /** - * @param {number} pos source code position - * @returns {boolean} true when a semicolon has been inserted before this position, false if not + * @param {LimitChunkCountPluginOptions=} options options object */ - isAsiPosition(pos) { - const currentStatement = this.statementPath[this.statementPath.length - 1]; - if (currentStatement === undefined) throw new Error("Not in statement"); - return ( - // Either asking directly for the end position of the current statement - (currentStatement.range[1] === pos && this.semicolons.has(pos)) || - // Or asking for the start position of the current statement, - // here we have to check multiple things - (currentStatement.range[0] === pos && - // is there a previous statement which might be relevant? - this.prevStatement !== undefined && - // is the end position of the previous statement an ASI position? - this.semicolons.has(this.prevStatement.range[1])) - ); + constructor(options) { + validate(options); + this.options = options; } /** - * @param {number} pos source code position + * @param {Compiler} compiler the webpack compiler * @returns {void} */ - unsetAsiPosition(pos) { - this.semicolons.delete(pos); - } - - isStatementLevelExpression(expr) { - const currentStatement = this.statementPath[this.statementPath.length - 1]; - return ( - expr === currentStatement || - (currentStatement.type === "ExpressionStatement" && - currentStatement.expression === expr) - ); - } - - getTagData(name, tag) { - const info = this.scope.definitions.get(name); - if (info instanceof VariableInfo) { - let tagInfo = info.tagInfo; - while (tagInfo !== undefined) { - if (tagInfo.tag === tag) return tagInfo.data; - tagInfo = tagInfo.next; - } - } - } - - tagVariable(name, tag, data) { - const oldInfo = this.scope.definitions.get(name); - /** @type {VariableInfo} */ - let newInfo; - if (oldInfo === undefined) { - newInfo = new VariableInfo(this.scope, name, { - tag, - data, - next: undefined - }); - } else if (oldInfo instanceof VariableInfo) { - newInfo = new VariableInfo(oldInfo.declaredScope, oldInfo.freeName, { - tag, - data, - next: oldInfo.tagInfo - }); - } else { - newInfo = new VariableInfo(oldInfo, true, { - tag, - data, - next: undefined - }); - } - this.scope.definitions.set(name, newInfo); - } + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("LimitChunkCountPlugin", compilation => { + compilation.hooks.optimizeChunks.tap( + { + name: "LimitChunkCountPlugin", + stage: STAGE_ADVANCED + }, + chunks => { + const chunkGraph = compilation.chunkGraph; + const maxChunks = options.maxChunks; + if (!maxChunks) return; + if (maxChunks < 1) return; + if (compilation.chunks.size <= maxChunks) return; - defineVariable(name) { - const oldInfo = this.scope.definitions.get(name); - // Don't redefine variable in same scope to keep existing tags - if (oldInfo instanceof VariableInfo && oldInfo.declaredScope === this.scope) - return; - this.scope.definitions.set(name, this.scope); - } + let remainingChunksToMerge = compilation.chunks.size - maxChunks; - undefineVariable(name) { - this.scope.definitions.delete(name); - } + // order chunks in a deterministic way + const compareChunksWithGraph = compareChunks(chunkGraph); + const orderedChunks = Array.from(chunks).sort(compareChunksWithGraph); - isVariableDefined(name) { - const info = this.scope.definitions.get(name); - if (info === undefined) return false; - if (info instanceof VariableInfo) { - return info.freeName === true; - } - return true; - } + // create a lazy sorted data structure to keep all combinations + // this is large. Size = chunks * (chunks - 1) / 2 + // It uses a multi layer bucket sort plus normal sort in the last layer + // It's also lazy so only accessed buckets are sorted + const combinations = new LazyBucketSortedSet( + // Layer 1: ordered by largest size benefit + c => c.sizeDiff, + (a, b) => b - a, + // Layer 2: ordered by smallest combined size + c => c.integratedSize, + (a, b) => a - b, + // Layer 3: ordered by position difference in orderedChunk (-> to be deterministic) + c => c.bIdx - c.aIdx, + (a, b) => a - b, + // Layer 4: ordered by position in orderedChunk (-> to be deterministic) + (a, b) => a.bIdx - b.bIdx + ); - /** - * @param {string} name variable name - * @returns {ExportedVariableInfo} info for this variable - */ - getVariableInfo(name) { - const value = this.scope.definitions.get(name); - if (value === undefined) { - return name; - } else { - return value; - } - } + // we keep a mapping from chunk to all combinations + // but this mapping is not kept up-to-date with deletions + // so `deleted` flag need to be considered when iterating this + /** @type {Map>} */ + const combinationsByChunk = new Map(); - /** - * @param {string} name variable name - * @param {ExportedVariableInfo} variableInfo new info for this variable - * @returns {void} - */ - setVariable(name, variableInfo) { - if (typeof variableInfo === "string") { - if (variableInfo === name) { - this.scope.definitions.delete(name); - } else { - this.scope.definitions.set( - name, - new VariableInfo(this.scope, variableInfo, undefined) - ); - } - } else { - this.scope.definitions.set(name, variableInfo); - } - } + orderedChunks.forEach((b, bIdx) => { + // create combination pairs with size and integrated size + for (let aIdx = 0; aIdx < bIdx; aIdx++) { + const a = orderedChunks[aIdx]; + // filter pairs that can not be integrated! + if (!chunkGraph.canChunksBeIntegrated(a, b)) continue; - parseCommentOptions(range) { - const comments = this.getComments(range); - if (comments.length === 0) { - return EMPTY_COMMENT_OPTIONS; - } - let options = {}; - let errors = []; - for (const comment of comments) { - const { value } = comment; - if (value && webpackCommentRegExp.test(value)) { - // try compile only if webpack options comment is present - try { - const val = vm.runInNewContext(`(function(){return {${value}};})()`); - Object.assign(options, val); - } catch (e) { - e.comment = comment; - errors.push(e); - } - } - } - return { options, errors }; - } + const integratedSize = chunkGraph.getIntegratedChunksSize( + a, + b, + options + ); - /** - * @param {MemberExpressionNode} expression a member expression - * @returns {{ members: string[], object: ExpressionNode | SuperNode }} member names (reverse order) and remaining object - */ - extractMemberExpressionChain(expression) { - /** @type {AnyNode} */ - let expr = expression; - const members = []; - while (expr.type === "MemberExpression") { - if (expr.computed) { - if (expr.property.type !== "Literal") break; - members.push(`${expr.property.value}`); - } else { - if (expr.property.type !== "Identifier") break; - members.push(expr.property.name); - } - expr = expr.object; - } - return { - members, - object: expr - }; - } + const aSize = chunkGraph.getChunkSize(a, options); + const bSize = chunkGraph.getChunkSize(b, options); + const c = { + deleted: false, + sizeDiff: aSize + bSize - integratedSize, + integratedSize, + a, + b, + aIdx, + bIdx, + aSize, + bSize + }; + combinations.add(c); + addToSetMap(combinationsByChunk, a, c); + addToSetMap(combinationsByChunk, b, c); + } + return combinations; + }); - /** - * @param {string} varName variable name - * @returns {{name: string, info: VariableInfo | string}} name of the free variable and variable info for that - */ - getFreeInfoFromVariable(varName) { - const info = this.getVariableInfo(varName); - let name; - if (info instanceof VariableInfo) { - name = info.freeName; - if (typeof name !== "string") return undefined; - } else if (typeof info !== "string") { - return undefined; - } else { - name = info; - } - return { info, name }; - } + // list of modified chunks during this run + // combinations affected by this change are skipped to allow + // further optimizations + /** @type {Set} */ + const modifiedChunks = new Set(); - /** @typedef {{ type: "call", call: CallExpressionNode, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => string[], name: string, getMembers: () => string[]}} CallExpressionInfo */ - /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[]}} ExpressionExpressionInfo */ + let changed = false; + // eslint-disable-next-line no-constant-condition + loop: while (true) { + const combination = combinations.popFirst(); + if (combination === undefined) break; - /** - * @param {MemberExpressionNode} expression a member expression - * @param {number} allowedTypes which types should be returned, presented in bit mask - * @returns {CallExpressionInfo | ExpressionExpressionInfo | undefined} expression info - */ - getMemberExpressionInfo(expression, allowedTypes) { - const { object, members } = this.extractMemberExpressionChain(expression); - switch (object.type) { - case "CallExpression": { - if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0) - return undefined; - let callee = object.callee; - let rootMembers = EMPTY_ARRAY; - if (callee.type === "MemberExpression") { - ({ object: callee, members: rootMembers } = - this.extractMemberExpressionChain(callee)); - } - const rootName = getRootName(callee); - if (!rootName) return undefined; - const result = this.getFreeInfoFromVariable(rootName); - if (!result) return undefined; - const { info: rootInfo, name: resolvedRoot } = result; - const calleeName = objectAndMembersToName(resolvedRoot, rootMembers); - return { - type: "call", - call: object, - calleeName, - rootInfo, - getCalleeMembers: memoize(() => rootMembers.reverse()), - name: objectAndMembersToName(`${calleeName}()`, members), - getMembers: memoize(() => members.reverse()) - }; - } - case "Identifier": - case "MetaProperty": - case "ThisExpression": { - if ((allowedTypes & ALLOWED_MEMBER_TYPES_EXPRESSION) === 0) - return undefined; - const rootName = getRootName(object); - if (!rootName) return undefined; + combination.deleted = true; + const { a, b, integratedSize } = combination; - const result = this.getFreeInfoFromVariable(rootName); - if (!result) return undefined; - const { info: rootInfo, name: resolvedRoot } = result; - return { - type: "expression", - name: objectAndMembersToName(resolvedRoot, members), - rootInfo, - getMembers: memoize(() => members.reverse()) - }; - } - } - } + // skip over pair when + // one of the already merged chunks is a parent of one of the chunks + if (modifiedChunks.size > 0) { + const queue = new Set(a.groupsIterable); + for (const group of b.groupsIterable) { + queue.add(group); + } + for (const group of queue) { + for (const mChunk of modifiedChunks) { + if (mChunk !== a && mChunk !== b && mChunk.isInGroup(group)) { + // This is a potential pair which needs recalculation + // We can't do that now, but it merge before following pairs + // so we leave space for it, and consider chunks as modified + // just for the worse case + remainingChunksToMerge--; + if (remainingChunksToMerge <= 0) break loop; + modifiedChunks.add(a); + modifiedChunks.add(b); + continue loop; + } + } + for (const parent of group.parentsIterable) { + queue.add(parent); + } + } + } - /** - * @param {MemberExpressionNode} expression an expression - * @returns {{ name: string, rootInfo: ExportedVariableInfo, getMembers: () => string[]}} name info - */ - getNameForExpression(expression) { - return this.getMemberExpressionInfo( - expression, - ALLOWED_MEMBER_TYPES_EXPRESSION - ); - } + // merge the chunks + if (chunkGraph.canChunksBeIntegrated(a, b)) { + chunkGraph.integrateChunks(a, b); + compilation.chunks.delete(b); - /** - * @param {string} code source code - * @param {ParseOptions} options parsing options - * @returns {ProgramNode} parsed ast - */ - static _parse(code, options) { - const type = options ? options.sourceType : "module"; - /** @type {AcornOptions} */ - const parserOptions = { - ...defaultParserOptions, - allowReturnOutsideFunction: type === "script", - ...options, - sourceType: type === "auto" ? "module" : type - }; + // flag chunk a as modified as further optimization are possible for all children here + modifiedChunks.add(a); - /** @type {AnyNode} */ - let ast; - let error; - let threw = false; - try { - ast = /** @type {AnyNode} */ (parser.parse(code, parserOptions)); - } catch (e) { - error = e; - threw = true; - } + changed = true; + remainingChunksToMerge--; + if (remainingChunksToMerge <= 0) break; - if (threw && type === "auto") { - parserOptions.sourceType = "script"; - if (!("allowReturnOutsideFunction" in options)) { - parserOptions.allowReturnOutsideFunction = true; - } - if (Array.isArray(parserOptions.onComment)) { - parserOptions.onComment.length = 0; - } - try { - ast = /** @type {AnyNode} */ (parser.parse(code, parserOptions)); - threw = false; - } catch (e) { - // we use the error from first parse try - // so nothing to do here - } - } + // Update all affected combinations + // delete all combination with the removed chunk + // we will use combinations with the kept chunk instead + for (const combination of combinationsByChunk.get(a)) { + if (combination.deleted) continue; + combination.deleted = true; + combinations.delete(combination); + } - if (threw) { - throw error; - } + // Update combinations with the kept chunk with new sizes + for (const combination of combinationsByChunk.get(b)) { + if (combination.deleted) continue; + if (combination.a === b) { + if (!chunkGraph.canChunksBeIntegrated(a, combination.b)) { + combination.deleted = true; + combinations.delete(combination); + continue; + } + // Update size + const newIntegratedSize = chunkGraph.getIntegratedChunksSize( + a, + combination.b, + options + ); + const finishUpdate = combinations.startUpdate(combination); + combination.a = a; + combination.integratedSize = newIntegratedSize; + combination.aSize = integratedSize; + combination.sizeDiff = + combination.bSize + integratedSize - newIntegratedSize; + finishUpdate(); + } else if (combination.b === b) { + if (!chunkGraph.canChunksBeIntegrated(combination.a, a)) { + combination.deleted = true; + combinations.delete(combination); + continue; + } + // Update size + const newIntegratedSize = chunkGraph.getIntegratedChunksSize( + combination.a, + a, + options + ); - return /** @type {ProgramNode} */ (ast); + const finishUpdate = combinations.startUpdate(combination); + combination.b = a; + combination.integratedSize = newIntegratedSize; + combination.bSize = integratedSize; + combination.sizeDiff = + integratedSize + combination.aSize - newIntegratedSize; + finishUpdate(); + } + } + combinationsByChunk.set(a, combinationsByChunk.get(b)); + combinationsByChunk.delete(b); + } + } + if (changed) return true; + } + ); + }); } } - -module.exports = JavascriptParser; -module.exports.ALLOWED_MEMBER_TYPES_ALL = ALLOWED_MEMBER_TYPES_ALL; -module.exports.ALLOWED_MEMBER_TYPES_EXPRESSION = - ALLOWED_MEMBER_TYPES_EXPRESSION; -module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = - ALLOWED_MEMBER_TYPES_CALL_EXPRESSION; +module.exports = LimitChunkCountPlugin; /***/ }), -/***/ 93998: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 27868: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -102030,250 +102622,181 @@ module.exports.ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = -const UnsupportedFeatureWarning = __webpack_require__(42495); -const ConstDependency = __webpack_require__(76911); -const BasicEvaluatedExpression = __webpack_require__(950); - -/** @typedef {import("estree").Expression} ExpressionNode */ -/** @typedef {import("estree").Node} Node */ -/** @typedef {import("./JavascriptParser")} JavascriptParser */ - -/** - * @param {JavascriptParser} parser the parser - * @param {string} value the const value - * @param {string[]=} runtimeRequirements runtime requirements - * @returns {function(ExpressionNode): true} plugin function - */ -exports.toConstantDependency = (parser, value, runtimeRequirements) => { - return function constDependency(expr) { - const dep = new ConstDependency(value, expr.range, runtimeRequirements); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - return true; - }; -}; +const { UsageState } = __webpack_require__(63686); +const { + numberToIdentifier, + NUMBER_OF_IDENTIFIER_START_CHARS, + NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS +} = __webpack_require__(1626); +const { assignDeterministicIds } = __webpack_require__(63290); +const { compareSelect, compareStringsNumeric } = __webpack_require__(29579); -/** - * @param {string} value the string value - * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function - */ -exports.evaluateToString = value => { - return function stringExpression(expr) { - return new BasicEvaluatedExpression().setString(value).setRange(expr.range); - }; -}; +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../ExportsInfo")} ExportsInfo */ +/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ /** - * @param {number} value the number value - * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + * @param {ExportsInfo} exportsInfo exports info + * @returns {boolean} mangle is possible */ -exports.evaluateToNumber = value => { - return function stringExpression(expr) { - return new BasicEvaluatedExpression().setNumber(value).setRange(expr.range); - }; +const canMangle = exportsInfo => { + if (exportsInfo.otherExportsInfo.getUsed(undefined) !== UsageState.Unused) + return false; + let hasSomethingToMangle = false; + for (const exportInfo of exportsInfo.exports) { + if (exportInfo.canMangle === true) { + hasSomethingToMangle = true; + } + } + return hasSomethingToMangle; }; +// Sort by name +const comparator = compareSelect(e => e.name, compareStringsNumeric); /** - * @param {boolean} value the boolean value - * @returns {function(ExpressionNode): BasicEvaluatedExpression} plugin function + * @param {boolean} deterministic use deterministic names + * @param {ExportsInfo} exportsInfo exports info + * @param {boolean} isNamespace is namespace object + * @returns {void} */ -exports.evaluateToBoolean = value => { - return function booleanExpression(expr) { - return new BasicEvaluatedExpression() - .setBoolean(value) - .setRange(expr.range); - }; -}; +const mangleExportsInfo = (deterministic, exportsInfo, isNamespace) => { + if (!canMangle(exportsInfo)) return; + const usedNames = new Set(); + /** @type {ExportInfo[]} */ + const mangleableExports = []; -/** - * @param {string} identifier identifier - * @param {string} rootInfo rootInfo - * @param {function(): string[]} getMembers getMembers - * @param {boolean|null=} truthy is truthy, null if nullish - * @returns {function(ExpressionNode): BasicEvaluatedExpression} callback - */ -exports.evaluateToIdentifier = (identifier, rootInfo, getMembers, truthy) => { - return function identifierExpression(expr) { - let evaluatedExpression = new BasicEvaluatedExpression() - .setIdentifier(identifier, rootInfo, getMembers) - .setSideEffects(false) - .setRange(expr.range); - switch (truthy) { - case true: - evaluatedExpression.setTruthy(); - break; - case null: - evaluatedExpression.setNullish(true); - break; - case false: - evaluatedExpression.setFalsy(); + // Avoid to renamed exports that are not provided when + // 1. it's not a namespace export: non-provided exports can be found in prototype chain + // 2. there are other provided exports and deterministic mode is chosen: + // non-provided exports would break the determinism + let avoidMangleNonProvided = !isNamespace; + if (!avoidMangleNonProvided && deterministic) { + for (const exportInfo of exportsInfo.ownedExports) { + if (exportInfo.provided !== false) { + avoidMangleNonProvided = true; break; + } } - - return evaluatedExpression; - }; -}; - -exports.expressionIsUnsupported = (parser, message) => { - return function unsupportedExpression(expr) { - const dep = new ConstDependency("(void 0)", expr.range, null); - dep.loc = expr.loc; - parser.state.module.addPresentationalDependency(dep); - if (!parser.state.module) return; - parser.state.module.addWarning( - new UnsupportedFeatureWarning(message, expr.loc) - ); - return true; - }; -}; - -exports.skipTraversal = () => true; - -exports.approve = () => true; - - -/***/ }), - -/***/ 98124: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const { isSubset } = __webpack_require__(93347); -const { getAllChunks } = __webpack_require__(91145); - -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {(string|number)[]} EntryItem */ - -const EXPORT_PREFIX = "var __webpack_exports__ = "; - -/** - * @param {ChunkGraph} chunkGraph chunkGraph - * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate - * @param {import("../ChunkGraph").EntryModuleWithChunkGroup[]} entries entries - * @param {Chunk} chunk chunk - * @param {boolean} passive true: passive startup with on chunks loaded - * @returns {string} runtime code - */ -exports.generateEntryStartup = ( - chunkGraph, - runtimeTemplate, - entries, - chunk, - passive -) => { - /** @type {string[]} */ - const runtime = [ - `var __webpack_exec__ = ${runtimeTemplate.returningFunction( - `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)`, - "moduleId" - )}` - ]; - - const runModule = id => { - return `__webpack_exec__(${JSON.stringify(id)})`; - }; - const outputCombination = (chunks, moduleIds, final) => { - if (chunks.size === 0) { - runtime.push( - `${final ? EXPORT_PREFIX : ""}(${moduleIds.map(runModule).join(", ")});` - ); - } else { - const fn = runtimeTemplate.returningFunction( - moduleIds.map(runModule).join(", ") - ); - runtime.push( - `${final && !passive ? EXPORT_PREFIX : ""}${ - passive - ? RuntimeGlobals.onChunksLoaded - : RuntimeGlobals.startupEntrypoint - }(0, ${JSON.stringify(Array.from(chunks, c => c.id))}, ${fn});` - ); - if (final && passive) { - runtime.push(`${EXPORT_PREFIX}${RuntimeGlobals.onChunksLoaded}();`); + } + for (const exportInfo of exportsInfo.ownedExports) { + const name = exportInfo.name; + if (!exportInfo.hasUsedName()) { + if ( + // Can the export be mangled? + exportInfo.canMangle !== true || + // Never rename 1 char exports + (name.length === 1 && /^[a-zA-Z0-9_$]/.test(name)) || + // Don't rename 2 char exports in deterministic mode + (deterministic && + name.length === 2 && + /^[a-zA-Z_$][a-zA-Z0-9_$]|^[1-9][0-9]/.test(name)) || + // Don't rename exports that are not provided + (avoidMangleNonProvided && exportInfo.provided !== true) + ) { + exportInfo.setUsedName(name); + usedNames.add(name); + } else { + mangleableExports.push(exportInfo); } } - }; - - let currentChunks = undefined; - let currentModuleIds = undefined; - - for (const [module, entrypoint] of entries) { - const runtimeChunk = entrypoint.getRuntimeChunk(); - const moduleId = chunkGraph.getModuleId(module); - const chunks = getAllChunks(entrypoint, chunk, runtimeChunk); - if ( - currentChunks && - currentChunks.size === chunks.size && - isSubset(currentChunks, chunks) - ) { - currentModuleIds.push(moduleId); - } else { - if (currentChunks) { - outputCombination(currentChunks, currentModuleIds); + if (exportInfo.exportsInfoOwned) { + const used = exportInfo.getUsed(undefined); + if ( + used === UsageState.OnlyPropertiesUsed || + used === UsageState.Unused + ) { + mangleExportsInfo(deterministic, exportInfo.exportsInfo, false); } - currentChunks = chunks; - currentModuleIds = [moduleId]; } } - - // output current modules with export prefix - if (currentChunks) { - outputCombination(currentChunks, currentModuleIds, true); + if (deterministic) { + assignDeterministicIds( + mangleableExports, + e => e.name, + comparator, + (e, id) => { + const name = numberToIdentifier(id); + const size = usedNames.size; + usedNames.add(name); + if (size === usedNames.size) return false; + e.setUsedName(name); + return true; + }, + [ + NUMBER_OF_IDENTIFIER_START_CHARS, + NUMBER_OF_IDENTIFIER_START_CHARS * + NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS + ], + NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS, + usedNames.size + ); + } else { + const usedExports = []; + const unusedExports = []; + for (const exportInfo of mangleableExports) { + if (exportInfo.getUsed(undefined) === UsageState.Unused) { + unusedExports.push(exportInfo); + } else { + usedExports.push(exportInfo); + } + } + usedExports.sort(comparator); + unusedExports.sort(comparator); + let i = 0; + for (const list of [usedExports, unusedExports]) { + for (const exportInfo of list) { + let name; + do { + name = numberToIdentifier(i++); + } while (usedNames.has(name)); + exportInfo.setUsedName(name); + } + } } - runtime.push(""); - return Template.asString(runtime); }; -/** - * @param {Hash} hash the hash to update - * @param {ChunkGraph} chunkGraph chunkGraph - * @param {import("../ChunkGraph").EntryModuleWithChunkGroup[]} entries entries - * @param {Chunk} chunk chunk - * @returns {void} - */ -exports.updateHashForEntryStartup = (hash, chunkGraph, entries, chunk) => { - for (const [module, entrypoint] of entries) { - const runtimeChunk = entrypoint.getRuntimeChunk(); - const moduleId = chunkGraph.getModuleId(module); - hash.update(`${moduleId}`); - for (const c of getAllChunks(entrypoint, chunk, runtimeChunk)) - hash.update(`${c.id}`); +class MangleExportsPlugin { + /** + * @param {boolean} deterministic use deterministic names + */ + constructor(deterministic) { + this._deterministic = deterministic; } -}; - -/** - * @param {Chunk} chunk the chunk - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {function(Chunk, ChunkGraph): boolean} filterFn filter function - * @returns {Set} initially fulfilled chunk ids - */ -exports.getInitialChunkIds = (chunk, chunkGraph, filterFn) => { - const initialChunkIds = new Set(chunk.ids); - for (const c of chunk.getAllInitialChunks()) { - if (c === chunk || filterFn(c, chunkGraph)) continue; - for (const id of c.ids) initialChunkIds.add(id); + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const { _deterministic: deterministic } = this; + compiler.hooks.compilation.tap("MangleExportsPlugin", compilation => { + const moduleGraph = compilation.moduleGraph; + compilation.hooks.optimizeCodeGeneration.tap( + "MangleExportsPlugin", + modules => { + if (compilation.moduleMemCaches) { + throw new Error( + "optimization.mangleExports can't be used with cacheUnaffected as export mangling is a global effect" + ); + } + for (const module of modules) { + const isNamespace = + module.buildMeta && module.buildMeta.exportsType === "namespace"; + const exportsInfo = moduleGraph.getExportsInfo(module); + mangleExportsInfo(deterministic, exportsInfo, isNamespace); + } + } + ); + }); } - return initialChunkIds; -}; +} + +module.exports = MangleExportsPlugin; /***/ }), -/***/ 90490: +/***/ 85067: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102284,244 +102807,119 @@ exports.getInitialChunkIds = (chunk, chunkGraph, filterFn) => { -const { register } = __webpack_require__(8282); +const { STAGE_BASIC } = __webpack_require__(80057); +const { runtimeEqual } = __webpack_require__(17156); -class JsonData { - constructor(data) { - this._buffer = undefined; - this._data = undefined; - if (Buffer.isBuffer(data)) { - this._buffer = data; - } else { - this._data = data; - } - } +/** @typedef {import("../Compiler")} Compiler */ - get() { - if (this._data === undefined && this._buffer !== undefined) { - this._data = JSON.parse(this._buffer.toString()); - } - return this._data; - } -} +class MergeDuplicateChunksPlugin { + /** + * @param {Compiler} compiler the compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "MergeDuplicateChunksPlugin", + compilation => { + compilation.hooks.optimizeChunks.tap( + { + name: "MergeDuplicateChunksPlugin", + stage: STAGE_BASIC + }, + chunks => { + const { chunkGraph, moduleGraph } = compilation; -register(JsonData, "webpack/lib/json/JsonData", null, { - serialize(obj, { write }) { - if (obj._buffer === undefined && obj._data !== undefined) { - obj._buffer = Buffer.from(JSON.stringify(obj._data)); - } - write(obj._buffer); - }, - deserialize({ read }) { - return new JsonData(read()); - } -}); + // remember already tested chunks for performance + const notDuplicates = new Set(); -module.exports = JsonData; - - -/***/ }), - -/***/ 70393: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { RawSource } = __webpack_require__(51255); -const ConcatenationScope = __webpack_require__(98229); -const { UsageState } = __webpack_require__(63686); -const Generator = __webpack_require__(93401); -const RuntimeGlobals = __webpack_require__(16475); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../ExportsInfo")} ExportsInfo */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -const stringifySafe = data => { - const stringified = JSON.stringify(data); - if (!stringified) { - return undefined; // Invalid JSON - } - - return stringified.replace(/\u2028|\u2029/g, str => - str === "\u2029" ? "\\u2029" : "\\u2028" - ); // invalid in JavaScript but valid JSON -}; - -/** - * @param {Object} data data (always an object or array) - * @param {ExportsInfo} exportsInfo exports info - * @param {RuntimeSpec} runtime the runtime - * @returns {Object} reduced data - */ -const createObjectForExportsInfo = (data, exportsInfo, runtime) => { - if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) - return data; - const isArray = Array.isArray(data); - const reducedData = isArray ? [] : {}; - for (const key of Object.keys(data)) { - const exportInfo = exportsInfo.getReadOnlyExportInfo(key); - const used = exportInfo.getUsed(runtime); - if (used === UsageState.Unused) continue; + // for each chunk + for (const chunk of chunks) { + // track a Set of all chunk that could be duplicates + let possibleDuplicates; + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (possibleDuplicates === undefined) { + // when possibleDuplicates is not yet set, + // create a new Set from chunks of the current module + // including only chunks with the same number of modules + for (const dup of chunkGraph.getModuleChunksIterable( + module + )) { + if ( + dup !== chunk && + chunkGraph.getNumberOfChunkModules(chunk) === + chunkGraph.getNumberOfChunkModules(dup) && + !notDuplicates.has(dup) + ) { + // delay allocating the new Set until here, reduce memory pressure + if (possibleDuplicates === undefined) { + possibleDuplicates = new Set(); + } + possibleDuplicates.add(dup); + } + } + // when no chunk is possible we can break here + if (possibleDuplicates === undefined) break; + } else { + // validate existing possible duplicates + for (const dup of possibleDuplicates) { + // remove possible duplicate when module is not contained + if (!chunkGraph.isModuleInChunk(module, dup)) { + possibleDuplicates.delete(dup); + } + } + // when all chunks has been removed we can break here + if (possibleDuplicates.size === 0) break; + } + } - let value; - if (used === UsageState.OnlyPropertiesUsed && exportInfo.exportsInfo) { - value = createObjectForExportsInfo( - data[key], - exportInfo.exportsInfo, - runtime - ); - } else { - value = data[key]; - } - const name = exportInfo.getUsedName(key, runtime); - reducedData[name] = value; - } - if (isArray) { - let arrayLengthWhenUsed = - exportsInfo.getReadOnlyExportInfo("length").getUsed(runtime) !== - UsageState.Unused - ? data.length - : undefined; + // when we found duplicates + if ( + possibleDuplicates !== undefined && + possibleDuplicates.size > 0 + ) { + outer: for (const otherChunk of possibleDuplicates) { + if (otherChunk.hasRuntime() !== chunk.hasRuntime()) continue; + if (chunkGraph.getNumberOfEntryModules(chunk) > 0) continue; + if (chunkGraph.getNumberOfEntryModules(otherChunk) > 0) + continue; + if (!runtimeEqual(chunk.runtime, otherChunk.runtime)) { + for (const module of chunkGraph.getChunkModulesIterable( + chunk + )) { + const exportsInfo = moduleGraph.getExportsInfo(module); + if ( + !exportsInfo.isEquallyUsed( + chunk.runtime, + otherChunk.runtime + ) + ) { + continue outer; + } + } + } + // merge them + if (chunkGraph.canChunksBeIntegrated(chunk, otherChunk)) { + chunkGraph.integrateChunks(chunk, otherChunk); + compilation.chunks.delete(otherChunk); + } + } + } - let sizeObjectMinusArray = 0; - for (let i = 0; i < reducedData.length; i++) { - if (reducedData[i] === undefined) { - sizeObjectMinusArray -= 2; - } else { - sizeObjectMinusArray += `${i}`.length + 3; - } - } - if (arrayLengthWhenUsed !== undefined) { - sizeObjectMinusArray += - `${arrayLengthWhenUsed}`.length + - 8 - - (arrayLengthWhenUsed - reducedData.length) * 2; - } - if (sizeObjectMinusArray < 0) - return Object.assign( - arrayLengthWhenUsed === undefined - ? {} - : { length: arrayLengthWhenUsed }, - reducedData - ); - const generatedLength = - arrayLengthWhenUsed !== undefined - ? Math.max(arrayLengthWhenUsed, reducedData.length) - : reducedData.length; - for (let i = 0; i < generatedLength; i++) { - if (reducedData[i] === undefined) { - reducedData[i] = 0; + // don't check already processed chunks twice + notDuplicates.add(chunk); + } + } + ); } - } - } - return reducedData; -}; - -const TYPES = new Set(["javascript"]); - -class JsonGenerator extends Generator { - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; - } - - /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module - */ - getSize(module, type) { - let data = - module.buildInfo && - module.buildInfo.jsonData && - module.buildInfo.jsonData.get(); - if (!data) return 0; - return stringifySafe(data).length + 10; - } - - /** - * @param {NormalModule} module module for which the bailout reason should be determined - * @param {ConcatenationBailoutReasonContext} context context - * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated - */ - getConcatenationBailoutReason(module, context) { - return undefined; - } - - /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code - */ - generate( - module, - { - moduleGraph, - runtimeTemplate, - runtimeRequirements, - runtime, - concatenationScope - } - ) { - const data = - module.buildInfo && - module.buildInfo.jsonData && - module.buildInfo.jsonData.get(); - if (data === undefined) { - return new RawSource( - runtimeTemplate.missingModuleStatement({ - request: module.rawRequest - }) - ); - } - const exportsInfo = moduleGraph.getExportsInfo(module); - let finalJson = - typeof data === "object" && - data && - exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused - ? createObjectForExportsInfo(data, exportsInfo, runtime) - : data; - // Use JSON because JSON.parse() is much faster than JavaScript evaluation - const jsonStr = stringifySafe(finalJson); - const jsonExpr = - jsonStr.length > 20 && typeof finalJson === "object" - ? `JSON.parse('${jsonStr.replace(/[\\']/g, "\\$&")}')` - : jsonStr; - let content; - if (concatenationScope) { - content = `${runtimeTemplate.supportsConst() ? "const" : "var"} ${ - ConcatenationScope.NAMESPACE_OBJECT_EXPORT - } = ${jsonExpr};`; - concatenationScope.registerNamespaceExport( - ConcatenationScope.NAMESPACE_OBJECT_EXPORT - ); - } else { - runtimeRequirements.add(RuntimeGlobals.module); - content = `${module.moduleArgument}.exports = ${jsonExpr};`; - } - return new RawSource(content); + ); } } - -module.exports = JsonGenerator; +module.exports = MergeDuplicateChunksPlugin; /***/ }), -/***/ 86770: +/***/ 53912: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102532,54 +102930,117 @@ module.exports = JsonGenerator; +const { STAGE_ADVANCED } = __webpack_require__(80057); const createSchemaValidation = __webpack_require__(32540); -const JsonGenerator = __webpack_require__(70393); -const JsonParser = __webpack_require__(41090); +/** @typedef {import("../../declarations/plugins/optimize/MinChunkSizePlugin").MinChunkSizePluginOptions} MinChunkSizePluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Compiler")} Compiler */ const validate = createSchemaValidation( - __webpack_require__(54094), - () => __webpack_require__(50166), + __webpack_require__(60135), + () => __webpack_require__(53850), { - name: "Json Modules Plugin", - baseDataPath: "parser" + name: "Min Chunk Size Plugin", + baseDataPath: "options" } ); -class JsonModulesPlugin { +class MinChunkSizePlugin { + /** + * @param {MinChunkSizePluginOptions} options options object + */ + constructor(options) { + validate(options); + this.options = options; + } + /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - compiler.hooks.compilation.tap( - "JsonModulesPlugin", - (compilation, { normalModuleFactory }) => { - normalModuleFactory.hooks.createParser - .for("json") - .tap("JsonModulesPlugin", parserOptions => { - validate(parserOptions); + const options = this.options; + const minChunkSize = options.minChunkSize; + compiler.hooks.compilation.tap("MinChunkSizePlugin", compilation => { + compilation.hooks.optimizeChunks.tap( + { + name: "MinChunkSizePlugin", + stage: STAGE_ADVANCED + }, + chunks => { + const chunkGraph = compilation.chunkGraph; + const equalOptions = { + chunkOverhead: 1, + entryChunkMultiplicator: 1 + }; - return new JsonParser(parserOptions); - }); - normalModuleFactory.hooks.createGenerator - .for("json") - .tap("JsonModulesPlugin", () => { - return new JsonGenerator(); - }); - } - ); + const chunkSizesMap = new Map(); + /** @type {[Chunk, Chunk][]} */ + const combinations = []; + /** @type {Chunk[]} */ + const smallChunks = []; + const visitedChunks = []; + for (const a of chunks) { + // check if one of the chunks sizes is smaller than the minChunkSize + // and filter pairs that can NOT be integrated! + if (chunkGraph.getChunkSize(a, equalOptions) < minChunkSize) { + smallChunks.push(a); + for (const b of visitedChunks) { + if (chunkGraph.canChunksBeIntegrated(b, a)) + combinations.push([b, a]); + } + } else { + for (const b of smallChunks) { + if (chunkGraph.canChunksBeIntegrated(b, a)) + combinations.push([b, a]); + } + } + chunkSizesMap.set(a, chunkGraph.getChunkSize(a, options)); + visitedChunks.push(a); + } + + const sortedSizeFilteredExtendedPairCombinations = combinations + .map(pair => { + // extend combination pairs with size and integrated size + const a = chunkSizesMap.get(pair[0]); + const b = chunkSizesMap.get(pair[1]); + const ab = chunkGraph.getIntegratedChunksSize( + pair[0], + pair[1], + options + ); + /** @type {[number, number, Chunk, Chunk]} */ + const extendedPair = [a + b - ab, ab, pair[0], pair[1]]; + return extendedPair; + }) + .sort((a, b) => { + // sadly javascript does an in place sort here + // sort by size + const diff = b[0] - a[0]; + if (diff !== 0) return diff; + return a[1] - b[1]; + }); + + if (sortedSizeFilteredExtendedPairCombinations.length === 0) return; + + const pair = sortedSizeFilteredExtendedPairCombinations[0]; + + chunkGraph.integrateChunks(pair[2], pair[3]); + compilation.chunks.delete(pair[3]); + return true; + } + ); + }); } } - -module.exports = JsonModulesPlugin; +module.exports = MinChunkSizePlugin; /***/ }), -/***/ 41090: +/***/ 85305: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102590,61 +103051,34 @@ module.exports = JsonModulesPlugin; -const parseJson = __webpack_require__(15235); -const Parser = __webpack_require__(11715); -const JsonExportsDependency = __webpack_require__(750); -const JsonData = __webpack_require__(90490); - -/** @typedef {import("../../declarations/plugins/JsonModulesPluginParser").JsonModulesPluginParserOptions} JsonModulesPluginParserOptions */ -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ - -class JsonParser extends Parser { - /** - * @param {JsonModulesPluginParserOptions} options parser options - */ - constructor(options) { - super(); - this.options = options || {}; - } +const SizeFormatHelpers = __webpack_require__(71070); +const WebpackError = __webpack_require__(53799); - /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state - */ - parse(source, state) { - if (Buffer.isBuffer(source)) { - source = source.toString("utf-8"); +class MinMaxSizeWarning extends WebpackError { + constructor(keys, minSize, maxSize) { + let keysMessage = "Fallback cache group"; + if (keys) { + keysMessage = + keys.length > 1 + ? `Cache groups ${keys.sort().join(", ")}` + : `Cache group ${keys[0]}`; } - - /** @type {JsonModulesPluginParserOptions["parse"]} */ - const parseFn = - typeof this.options.parse === "function" ? this.options.parse : parseJson; - - const data = - typeof source === "object" - ? source - : parseFn(source[0] === "\ufeff" ? source.slice(1) : source); - - state.module.buildInfo.jsonData = new JsonData(data); - state.module.buildInfo.strict = true; - state.module.buildMeta.exportsType = "default"; - state.module.buildMeta.defaultObject = - typeof data === "object" ? "redirect-warn" : false; - state.module.addDependency( - new JsonExportsDependency(JsonExportsDependency.getExportsFromData(data)) + super( + `SplitChunksPlugin\n` + + `${keysMessage}\n` + + `Configured minSize (${SizeFormatHelpers.formatSize(minSize)}) is ` + + `bigger than maxSize (${SizeFormatHelpers.formatSize(maxSize)}).\n` + + "This seem to be a invalid optimization.splitChunks configuration." ); - return state; } } -module.exports = JsonParser; +module.exports = MinMaxSizeWarning; /***/ }), -/***/ 26030: +/***/ 74844: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102655,46 +103089,49 @@ module.exports = JsonParser; -const RuntimeGlobals = __webpack_require__(16475); -const JavascriptModulesPlugin = __webpack_require__(89464); +const asyncLib = __webpack_require__(78175); +const ChunkGraph = __webpack_require__(64971); +const ModuleGraph = __webpack_require__(99988); +const { STAGE_DEFAULT } = __webpack_require__(80057); +const HarmonyImportDependency = __webpack_require__(57154); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const { + intersectRuntime, + mergeRuntimeOwned, + filterRuntime, + runtimeToString, + mergeRuntime +} = __webpack_require__(17156); +const ConcatenatedModule = __webpack_require__(97198); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ /** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ /** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Module")} Module */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ -/** @typedef {import("../util/Hash")} Hash */ - -const COMMON_LIBRARY_NAME_MESSAGE = - "Common configuration options that specific library names are 'output.library[.name]', 'entry.xyz.library[.name]', 'ModuleFederationPlugin.name' and 'ModuleFederationPlugin.library[.name]'."; +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ /** - * @template T - * @typedef {Object} LibraryContext - * @property {Compilation} compilation - * @property {ChunkGraph} chunkGraph - * @property {T} options + * @typedef {Object} Statistics + * @property {number} cached + * @property {number} alreadyInConfig + * @property {number} invalidModule + * @property {number} incorrectChunks + * @property {number} incorrectDependency + * @property {number} incorrectModuleDependency + * @property {number} incorrectChunksOfImporter + * @property {number} incorrectRuntimeCondition + * @property {number} importerFailed + * @property {number} added */ -/** - * @template T - */ -class AbstractLibraryPlugin { - /** - * @param {Object} options options - * @param {string} options.pluginName name of the plugin - * @param {LibraryType} options.type used library type - */ - constructor({ pluginName, type }) { - this._pluginName = pluginName; - this._type = type; - this._parseCache = new WeakMap(); +const formatBailoutReason = msg => { + return "ModuleConcatenation bailout: " + msg; +}; + +class ModuleConcatenationPlugin { + constructor(options) { + if (typeof options !== "object") options = {}; + this.options = options; } /** @@ -102703,800 +103140,819 @@ class AbstractLibraryPlugin { * @returns {void} */ apply(compiler) { - const { _pluginName } = this; - compiler.hooks.thisCompilation.tap(_pluginName, compilation => { - compilation.hooks.finishModules.tap( - { name: _pluginName, stage: 10 }, - () => { - for (const [ - name, - { - dependencies: deps, - options: { library } - } - ] of compilation.entries) { - const options = this._parseOptionsCached( - library !== undefined - ? library - : compilation.outputOptions.library - ); - if (options !== false) { - const dep = deps[deps.length - 1]; - if (dep) { - const module = compilation.moduleGraph.getModule(dep); - if (module) { - this.finishEntryModule(module, name, { - options, - compilation, - chunkGraph: compilation.chunkGraph - }); - } - } - } - } - } - ); + const { _backCompat: backCompat } = compiler; + compiler.hooks.compilation.tap("ModuleConcatenationPlugin", compilation => { + const moduleGraph = compilation.moduleGraph; + const bailoutReasonMap = new Map(); - const getOptionsForChunk = chunk => { - if (compilation.chunkGraph.getNumberOfEntryModules(chunk) === 0) - return false; - const options = chunk.getEntryOptions(); - const library = options && options.library; - return this._parseOptionsCached( - library !== undefined ? library : compilation.outputOptions.library - ); + const setBailoutReason = (module, reason) => { + setInnerBailoutReason(module, reason); + moduleGraph + .getOptimizationBailout(module) + .push( + typeof reason === "function" + ? rs => formatBailoutReason(reason(rs)) + : formatBailoutReason(reason) + ); }; - if ( - this.render !== AbstractLibraryPlugin.prototype.render || - this.runtimeRequirements !== - AbstractLibraryPlugin.prototype.runtimeRequirements - ) { - compilation.hooks.additionalChunkRuntimeRequirements.tap( - _pluginName, - (chunk, set, { chunkGraph }) => { - const options = getOptionsForChunk(chunk); - if (options !== false) { - this.runtimeRequirements(chunk, set, { - options, - compilation, - chunkGraph - }); - } - } - ); - } - - const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation); - - if (this.render !== AbstractLibraryPlugin.prototype.render) { - hooks.render.tap(_pluginName, (source, renderContext) => { - const options = getOptionsForChunk(renderContext.chunk); - if (options === false) return source; - return this.render(source, renderContext, { - options, - compilation, - chunkGraph: compilation.chunkGraph - }); - }); - } - - if ( - this.embedInRuntimeBailout !== - AbstractLibraryPlugin.prototype.embedInRuntimeBailout - ) { - hooks.embedInRuntimeBailout.tap( - _pluginName, - (module, renderContext) => { - const options = getOptionsForChunk(renderContext.chunk); - if (options === false) return; - return this.embedInRuntimeBailout(module, renderContext, { - options, - compilation, - chunkGraph: compilation.chunkGraph - }); - } - ); - } + const setInnerBailoutReason = (module, reason) => { + bailoutReasonMap.set(module, reason); + }; - if ( - this.strictRuntimeBailout !== - AbstractLibraryPlugin.prototype.strictRuntimeBailout - ) { - hooks.strictRuntimeBailout.tap(_pluginName, renderContext => { - const options = getOptionsForChunk(renderContext.chunk); - if (options === false) return; - return this.strictRuntimeBailout(renderContext, { - options, - compilation, - chunkGraph: compilation.chunkGraph - }); - }); - } + const getInnerBailoutReason = (module, requestShortener) => { + const reason = bailoutReasonMap.get(module); + if (typeof reason === "function") return reason(requestShortener); + return reason; + }; - if ( - this.renderStartup !== AbstractLibraryPlugin.prototype.renderStartup - ) { - hooks.renderStartup.tap( - _pluginName, - (source, module, renderContext) => { - const options = getOptionsForChunk(renderContext.chunk); - if (options === false) return source; - return this.renderStartup(source, module, renderContext, { - options, - compilation, - chunkGraph: compilation.chunkGraph - }); - } - ); - } + const formatBailoutWarning = (module, problem) => requestShortener => { + if (typeof problem === "function") { + return formatBailoutReason( + `Cannot concat with ${module.readableIdentifier( + requestShortener + )}: ${problem(requestShortener)}` + ); + } + const reason = getInnerBailoutReason(module, requestShortener); + const reasonWithPrefix = reason ? `: ${reason}` : ""; + if (module === problem) { + return formatBailoutReason( + `Cannot concat with ${module.readableIdentifier( + requestShortener + )}${reasonWithPrefix}` + ); + } else { + return formatBailoutReason( + `Cannot concat with ${module.readableIdentifier( + requestShortener + )} because of ${problem.readableIdentifier( + requestShortener + )}${reasonWithPrefix}` + ); + } + }; - hooks.chunkHash.tap(_pluginName, (chunk, hash, context) => { - const options = getOptionsForChunk(chunk); - if (options === false) return; - this.chunkHash(chunk, hash, context, { - options, - compilation, - chunkGraph: compilation.chunkGraph - }); - }); - }); - } + compilation.hooks.optimizeChunkModules.tapAsync( + { + name: "ModuleConcatenationPlugin", + stage: STAGE_DEFAULT + }, + (allChunks, modules, callback) => { + const logger = compilation.getLogger( + "webpack.ModuleConcatenationPlugin" + ); + const { chunkGraph, moduleGraph } = compilation; + const relevantModules = []; + const possibleInners = new Set(); + const context = { + chunkGraph, + moduleGraph + }; + logger.time("select relevant modules"); + for (const module of modules) { + let canBeRoot = true; + let canBeInner = true; - /** - * @param {LibraryOptions=} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - _parseOptionsCached(library) { - if (!library) return false; - if (library.type !== this._type) return false; - const cacheEntry = this._parseCache.get(library); - if (cacheEntry !== undefined) return cacheEntry; - const result = this.parseOptions(library); - this._parseCache.set(library, result); - return result; - } + const bailoutReason = module.getConcatenationBailoutReason(context); + if (bailoutReason) { + setBailoutReason(module, bailoutReason); + continue; + } - /* istanbul ignore next */ - /** - * @abstract - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - parseOptions(library) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); - } + // Must not be an async module + if (moduleGraph.isAsync(module)) { + setBailoutReason(module, `Module is async`); + continue; + } - /** - * @param {Module} module the exporting entry module - * @param {string} entryName the name of the entrypoint - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - finishEntryModule(module, entryName, libraryContext) {} + // Must be in strict mode + if (!module.buildInfo.strict) { + setBailoutReason(module, `Module is not in strict mode`); + continue; + } - /** - * @param {Module} module the exporting entry module - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {string | undefined} bailout reason - */ - embedInRuntimeBailout(module, renderContext, libraryContext) { - return undefined; - } + // Module must be in any chunk (we don't want to do useless work) + if (chunkGraph.getNumberOfModuleChunks(module) === 0) { + setBailoutReason(module, "Module is not in any chunk"); + continue; + } - /** - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {string | undefined} bailout reason - */ - strictRuntimeBailout(renderContext, libraryContext) { - return undefined; - } + // Exports must be known (and not dynamic) + const exportsInfo = moduleGraph.getExportsInfo(module); + const relevantExports = exportsInfo.getRelevantExports(undefined); + const unknownReexports = relevantExports.filter(exportInfo => { + return ( + exportInfo.isReexport() && !exportInfo.getTarget(moduleGraph) + ); + }); + if (unknownReexports.length > 0) { + setBailoutReason( + module, + `Reexports in this module do not have a static target (${Array.from( + unknownReexports, + exportInfo => + `${ + exportInfo.name || "other exports" + }: ${exportInfo.getUsedInfo()}` + ).join(", ")})` + ); + continue; + } - /** - * @param {Chunk} chunk the chunk - * @param {Set} set runtime requirements - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - runtimeRequirements(chunk, set, libraryContext) { - if (this.render !== AbstractLibraryPlugin.prototype.render) - set.add(RuntimeGlobals.returnExportsFromRuntime); - } + // Root modules must have a static list of exports + const unknownProvidedExports = relevantExports.filter( + exportInfo => { + return exportInfo.provided !== true; + } + ); + if (unknownProvidedExports.length > 0) { + setBailoutReason( + module, + `List of module exports is dynamic (${Array.from( + unknownProvidedExports, + exportInfo => + `${ + exportInfo.name || "other exports" + }: ${exportInfo.getProvidedInfo()} and ${exportInfo.getUsedInfo()}` + ).join(", ")})` + ); + canBeRoot = false; + } - /** - * @param {Source} source source - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - render(source, renderContext, libraryContext) { - return source; - } + // Module must not be an entry point + if (chunkGraph.isEntryModule(module)) { + setInnerBailoutReason(module, "Module is an entry point"); + canBeInner = false; + } - /** - * @param {Source} source source - * @param {Module} module module - * @param {StartupRenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - renderStartup(source, module, renderContext, libraryContext) { - return source; - } + if (canBeRoot) relevantModules.push(module); + if (canBeInner) possibleInners.add(module); + } + logger.timeEnd("select relevant modules"); + logger.debug( + `${relevantModules.length} potential root modules, ${possibleInners.size} potential inner modules` + ); + // sort by depth + // modules with lower depth are more likely suited as roots + // this improves performance, because modules already selected as inner are skipped + logger.time("sort relevant modules"); + relevantModules.sort((a, b) => { + return moduleGraph.getDepth(a) - moduleGraph.getDepth(b); + }); + logger.timeEnd("sort relevant modules"); - /** - * @param {Chunk} chunk the chunk - * @param {Hash} hash hash - * @param {ChunkHashContext} chunkHashContext chunk hash context - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - chunkHash(chunk, hash, chunkHashContext, libraryContext) { - const options = this._parseOptionsCached( - libraryContext.compilation.outputOptions.library - ); - hash.update(this._pluginName); - hash.update(JSON.stringify(options)); - } -} + /** @type {Statistics} */ + const stats = { + cached: 0, + alreadyInConfig: 0, + invalidModule: 0, + incorrectChunks: 0, + incorrectDependency: 0, + incorrectModuleDependency: 0, + incorrectChunksOfImporter: 0, + incorrectRuntimeCondition: 0, + importerFailed: 0, + added: 0 + }; + let statsCandidates = 0; + let statsSizeSum = 0; + let statsEmptyConfigurations = 0; -AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE = COMMON_LIBRARY_NAME_MESSAGE; -module.exports = AbstractLibraryPlugin; + logger.time("find modules to concatenate"); + const concatConfigurations = []; + const usedAsInner = new Set(); + for (const currentRoot of relevantModules) { + // when used by another configuration as inner: + // the other configuration is better and we can skip this one + // TODO reconsider that when it's only used in a different runtime + if (usedAsInner.has(currentRoot)) continue; + let chunkRuntime = undefined; + for (const r of chunkGraph.getModuleRuntimes(currentRoot)) { + chunkRuntime = mergeRuntimeOwned(chunkRuntime, r); + } + const exportsInfo = moduleGraph.getExportsInfo(currentRoot); + const filteredRuntime = filterRuntime(chunkRuntime, r => + exportsInfo.isModuleUsed(r) + ); + const activeRuntime = + filteredRuntime === true + ? chunkRuntime + : filteredRuntime === false + ? undefined + : filteredRuntime; -/***/ }), + // create a configuration with the root + const currentConfiguration = new ConcatConfiguration( + currentRoot, + activeRuntime + ); -/***/ 67416: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // cache failures to add modules + const failureCache = new Map(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // potential optional import candidates + /** @type {Set} */ + const candidates = new Set(); + // try to add all imports + for (const imp of this._getImports( + compilation, + currentRoot, + activeRuntime + )) { + candidates.add(imp); + } + for (const imp of candidates) { + const impCandidates = new Set(); + const problem = this._tryToAdd( + compilation, + currentConfiguration, + imp, + chunkRuntime, + activeRuntime, + possibleInners, + impCandidates, + failureCache, + chunkGraph, + true, + stats + ); + if (problem) { + failureCache.set(imp, problem); + currentConfiguration.addWarning(imp, problem); + } else { + for (const c of impCandidates) { + candidates.add(c); + } + } + } + statsCandidates += candidates.size; + if (!currentConfiguration.isEmpty()) { + const modules = currentConfiguration.getModules(); + statsSizeSum += modules.size; + concatConfigurations.push(currentConfiguration); + for (const module of modules) { + if (module !== currentConfiguration.rootModule) { + usedAsInner.add(module); + } + } + } else { + statsEmptyConfigurations++; + const optimizationBailouts = + moduleGraph.getOptimizationBailout(currentRoot); + for (const warning of currentConfiguration.getWarningsSorted()) { + optimizationBailouts.push( + formatBailoutWarning(warning[0], warning[1]) + ); + } + } + } + logger.timeEnd("find modules to concatenate"); + logger.debug( + `${ + concatConfigurations.length + } successful concat configurations (avg size: ${ + statsSizeSum / concatConfigurations.length + }), ${statsEmptyConfigurations} bailed out completely` + ); + logger.debug( + `${statsCandidates} candidates were considered for adding (${stats.cached} cached failure, ${stats.alreadyInConfig} already in config, ${stats.invalidModule} invalid module, ${stats.incorrectChunks} incorrect chunks, ${stats.incorrectDependency} incorrect dependency, ${stats.incorrectChunksOfImporter} incorrect chunks of importer, ${stats.incorrectModuleDependency} incorrect module dependency, ${stats.incorrectRuntimeCondition} incorrect runtime condition, ${stats.importerFailed} importer failed, ${stats.added} added)` + ); + // HACK: Sort configurations by length and start with the longest one + // to get the biggest groups possible. Used modules are marked with usedModules + // TODO: Allow to reuse existing configuration while trying to add dependencies. + // This would improve performance. O(n^2) -> O(n) + logger.time(`sort concat configurations`); + concatConfigurations.sort((a, b) => { + return b.modules.size - a.modules.size; + }); + logger.timeEnd(`sort concat configurations`); + const usedModules = new Set(); -const { ConcatSource } = __webpack_require__(51255); -const ExternalModule = __webpack_require__(73071); -const Template = __webpack_require__(39722); -const AbstractLibraryPlugin = __webpack_require__(26030); + logger.time("create concatenated modules"); + asyncLib.each( + concatConfigurations, + (concatConfiguration, callback) => { + const rootModule = concatConfiguration.rootModule; -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + // Avoid overlapping configurations + // TODO: remove this when todo above is fixed + if (usedModules.has(rootModule)) return callback(); + const modules = concatConfiguration.getModules(); + for (const m of modules) { + usedModules.add(m); + } -/** - * @typedef {Object} AmdLibraryPluginOptions - * @property {LibraryType} type - * @property {boolean=} requireAsWrapper - */ + // Create a new ConcatenatedModule + let newModule = ConcatenatedModule.create( + rootModule, + modules, + concatConfiguration.runtime, + compiler.root, + compilation.outputOptions.hashFunction + ); -/** - * @typedef {Object} AmdLibraryPluginParsed - * @property {string} name - */ + const build = () => { + newModule.build( + compiler.options, + compilation, + null, + null, + err => { + if (err) { + if (!err.module) { + err.module = newModule; + } + return callback(err); + } + integrate(); + } + ); + }; -/** - * @typedef {AmdLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} - */ -class AmdLibraryPlugin extends AbstractLibraryPlugin { - /** - * @param {AmdLibraryPluginOptions} options the plugin options - */ - constructor(options) { - super({ - pluginName: "AmdLibraryPlugin", - type: options.type + const integrate = () => { + if (backCompat) { + ChunkGraph.setChunkGraphForModule(newModule, chunkGraph); + ModuleGraph.setModuleGraphForModule(newModule, moduleGraph); + } + + for (const warning of concatConfiguration.getWarningsSorted()) { + moduleGraph + .getOptimizationBailout(newModule) + .push(formatBailoutWarning(warning[0], warning[1])); + } + moduleGraph.cloneModuleAttributes(rootModule, newModule); + for (const m of modules) { + // add to builtModules when one of the included modules was built + if (compilation.builtModules.has(m)) { + compilation.builtModules.add(newModule); + } + if (m !== rootModule) { + // attach external references to the concatenated module too + moduleGraph.copyOutgoingModuleConnections( + m, + newModule, + c => { + return ( + c.originModule === m && + !( + c.dependency instanceof HarmonyImportDependency && + modules.has(c.module) + ) + ); + } + ); + // remove module from chunk + for (const chunk of chunkGraph.getModuleChunksIterable( + rootModule + )) { + chunkGraph.disconnectChunkAndModule(chunk, m); + } + } + } + compilation.modules.delete(rootModule); + ChunkGraph.clearChunkGraphForModule(rootModule); + ModuleGraph.clearModuleGraphForModule(rootModule); + + // remove module from chunk + chunkGraph.replaceModule(rootModule, newModule); + // replace module references with the concatenated module + moduleGraph.moveModuleConnections(rootModule, newModule, c => { + const otherModule = + c.module === rootModule ? c.originModule : c.module; + const innerConnection = + c.dependency instanceof HarmonyImportDependency && + modules.has(otherModule); + return !innerConnection; + }); + // add concatenated module to the compilation + compilation.modules.add(newModule); + + callback(); + }; + + build(); + }, + err => { + logger.timeEnd("create concatenated modules"); + process.nextTick(callback.bind(null, err)); + } + ); + } + ); }); - this.requireAsWrapper = options.requireAsWrapper; } /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding + * @param {Compilation} compilation the compilation + * @param {Module} module the module to be added + * @param {RuntimeSpec} runtime the runtime scope + * @returns {Set} the imported modules */ - parseOptions(library) { - const { name } = library; - if (this.requireAsWrapper) { - if (name) { - throw new Error( - `AMD library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); + _getImports(compilation, module, runtime) { + const moduleGraph = compilation.moduleGraph; + const set = new Set(); + for (const dep of module.dependencies) { + // Get reference info only for harmony Dependencies + if (!(dep instanceof HarmonyImportDependency)) continue; + + const connection = moduleGraph.getConnection(dep); + // Reference is valid and has a module + if ( + !connection || + !connection.module || + !connection.isTargetActive(runtime) + ) { + continue; } - } else { - if (name && typeof name !== "string") { - throw new Error( - `AMD library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); + + const importedNames = compilation.getDependencyReferencedExports( + dep, + undefined + ); + + if ( + importedNames.every(i => + Array.isArray(i) ? i.length > 0 : i.name.length > 0 + ) || + Array.isArray(moduleGraph.getProvidedExports(module)) + ) { + set.add(connection.module); } } - return { - name: /** @type {string=} */ (name) - }; + return set; } /** - * @param {Source} source source - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export + * @param {Compilation} compilation webpack compilation + * @param {ConcatConfiguration} config concat configuration (will be modified when added) + * @param {Module} module the module to be added + * @param {RuntimeSpec} runtime the runtime scope of the generated code + * @param {RuntimeSpec} activeRuntime the runtime scope of the root module + * @param {Set} possibleModules modules that are candidates + * @param {Set} candidates list of potential candidates (will be added to) + * @param {Map} failureCache cache for problematic modules to be more performant + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {boolean} avoidMutateOnFailure avoid mutating the config when adding fails + * @param {Statistics} statistics gathering metrics + * @returns {Module | function(RequestShortener): string} the problematic module */ - render( - source, - { chunkGraph, chunk, runtimeTemplate }, - { options, compilation } + _tryToAdd( + compilation, + config, + module, + runtime, + activeRuntime, + possibleModules, + candidates, + failureCache, + chunkGraph, + avoidMutateOnFailure, + statistics ) { - const modern = runtimeTemplate.supportsArrowFunction(); - const modules = chunkGraph - .getChunkModules(chunk) - .filter(m => m instanceof ExternalModule); - const externals = /** @type {ExternalModule[]} */ (modules); - const externalsDepsArray = JSON.stringify( - externals.map(m => - typeof m.request === "object" && !Array.isArray(m.request) - ? m.request.amd - : m.request - ) - ); - const externalsArguments = externals - .map( - m => - `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( - `${chunkGraph.getModuleId(m)}` - )}__` - ) - .join(", "); - - const iife = runtimeTemplate.isIIFE(); - const fnStart = - (modern - ? `(${externalsArguments}) => {` - : `function(${externalsArguments}) {`) + - (iife || !chunk.hasRuntime() ? " return " : "\n"); - const fnEnd = iife ? ";\n}" : "\n}"; + const cacheEntry = failureCache.get(module); + if (cacheEntry) { + statistics.cached++; + return cacheEntry; + } - if (this.requireAsWrapper) { - return new ConcatSource( - `require(${externalsDepsArray}, ${fnStart}`, - source, - `${fnEnd});` - ); - } else if (options.name) { - const name = compilation.getPath(options.name, { - chunk - }); + // Already added? + if (config.has(module)) { + statistics.alreadyInConfig++; + return null; + } - return new ConcatSource( - `define(${JSON.stringify(name)}, ${externalsDepsArray}, ${fnStart}`, - source, - `${fnEnd});` - ); - } else if (externalsArguments) { - return new ConcatSource( - `define(${externalsDepsArray}, ${fnStart}`, - source, - `${fnEnd});` - ); - } else { - return new ConcatSource(`define(${fnStart}`, source, `${fnEnd});`); + // Not possible to add? + if (!possibleModules.has(module)) { + statistics.invalidModule++; + failureCache.set(module, module); // cache failures for performance + return module; } - } - /** - * @param {Chunk} chunk the chunk - * @param {Hash} hash hash - * @param {ChunkHashContext} chunkHashContext chunk hash context - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { - hash.update("AmdLibraryPlugin"); - if (this.requireAsWrapper) { - hash.update("requireAsWrapper"); - } else if (options.name) { - hash.update("named"); - const name = compilation.getPath(options.name, { - chunk - }); - hash.update(name); + // Module must be in the correct chunks + const missingChunks = Array.from( + chunkGraph.getModuleChunksIterable(config.rootModule) + ).filter(chunk => !chunkGraph.isModuleInChunk(module, chunk)); + if (missingChunks.length > 0) { + const problem = requestShortener => { + const missingChunksList = Array.from( + new Set(missingChunks.map(chunk => chunk.name || "unnamed chunk(s)")) + ).sort(); + const chunks = Array.from( + new Set( + Array.from(chunkGraph.getModuleChunksIterable(module)).map( + chunk => chunk.name || "unnamed chunk(s)" + ) + ) + ).sort(); + return `Module ${module.readableIdentifier( + requestShortener + )} is not in the same chunk(s) (expected in chunk(s) ${missingChunksList.join( + ", " + )}, module is in chunk(s) ${chunks.join(", ")})`; + }; + statistics.incorrectChunks++; + failureCache.set(module, problem); // cache failures for performance + return problem; } - } -} -module.exports = AmdLibraryPlugin; + const moduleGraph = compilation.moduleGraph; + const incomingConnections = + moduleGraph.getIncomingConnectionsByOriginModule(module); -/***/ }), + const incomingConnectionsFromNonModules = + incomingConnections.get(null) || incomingConnections.get(undefined); + if (incomingConnectionsFromNonModules) { + const activeNonModulesConnections = + incomingConnectionsFromNonModules.filter(connection => { + // We are not interested in inactive connections + // or connections without dependency + return connection.isActive(runtime) || connection.dependency; + }); + if (activeNonModulesConnections.length > 0) { + const problem = requestShortener => { + const importingExplanations = new Set( + activeNonModulesConnections.map(c => c.explanation).filter(Boolean) + ); + const explanations = Array.from(importingExplanations).sort(); + return `Module ${module.readableIdentifier( + requestShortener + )} is referenced ${ + explanations.length > 0 + ? `by: ${explanations.join(", ")}` + : "in an unsupported way" + }`; + }; + statistics.incorrectDependency++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + } -/***/ 40080: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {Map} */ + const incomingConnectionsFromModules = new Map(); + for (const [originModule, connections] of incomingConnections) { + if (originModule) { + // Ignore connection from orphan modules + if (chunkGraph.getNumberOfModuleChunks(originModule) === 0) continue; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // We don't care for connections from other runtimes + let originRuntime = undefined; + for (const r of chunkGraph.getModuleRuntimes(originModule)) { + originRuntime = mergeRuntimeOwned(originRuntime, r); + } + if (!intersectRuntime(runtime, originRuntime)) continue; + // We are not interested in inactive connections + const activeConnections = connections.filter(connection => + connection.isActive(runtime) + ); + if (activeConnections.length > 0) + incomingConnectionsFromModules.set(originModule, activeConnections); + } + } -const { ConcatSource } = __webpack_require__(51255); -const { UsageState } = __webpack_require__(63686); -const Template = __webpack_require__(39722); -const propertyAccess = __webpack_require__(54190); -const { getEntryRuntime } = __webpack_require__(17156); -const AbstractLibraryPlugin = __webpack_require__(26030); + const incomingModules = Array.from(incomingConnectionsFromModules.keys()); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ + // Module must be in the same chunks like the referencing module + const otherChunkModules = incomingModules.filter(originModule => { + for (const chunk of chunkGraph.getModuleChunksIterable( + config.rootModule + )) { + if (!chunkGraph.isModuleInChunk(originModule, chunk)) { + return true; + } + } + return false; + }); + if (otherChunkModules.length > 0) { + const problem = requestShortener => { + const names = otherChunkModules + .map(m => m.readableIdentifier(requestShortener)) + .sort(); + return `Module ${module.readableIdentifier( + requestShortener + )} is referenced from different chunks by these modules: ${names.join( + ", " + )}`; + }; + statistics.incorrectChunksOfImporter++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } -const KEYWORD_REGEX = - /^(await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|super|switch|static|this|throw|try|true|typeof|var|void|while|with|yield)$/; -const IDENTIFIER_REGEX = - /^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/iu; + /** @type {Map} */ + const nonHarmonyConnections = new Map(); + for (const [originModule, connections] of incomingConnectionsFromModules) { + const selected = connections.filter( + connection => + !connection.dependency || + !(connection.dependency instanceof HarmonyImportDependency) + ); + if (selected.length > 0) + nonHarmonyConnections.set(originModule, connections); + } + if (nonHarmonyConnections.size > 0) { + const problem = requestShortener => { + const names = Array.from(nonHarmonyConnections) + .map(([originModule, connections]) => { + return `${originModule.readableIdentifier( + requestShortener + )} (referenced with ${Array.from( + new Set( + connections + .map(c => c.dependency && c.dependency.type) + .filter(Boolean) + ) + ) + .sort() + .join(", ")})`; + }) + .sort(); + return `Module ${module.readableIdentifier( + requestShortener + )} is referenced from these modules with unsupported syntax: ${names.join( + ", " + )}`; + }; + statistics.incorrectModuleDependency++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } -/** - * Validates the library name by checking for keywords and valid characters - * @param {string} name name to be validated - * @returns {boolean} true, when valid - */ -const isNameValid = name => { - return !KEYWORD_REGEX.test(name) && IDENTIFIER_REGEX.test(name); -}; + if (runtime !== undefined && typeof runtime !== "string") { + // Module must be consistently referenced in the same runtimes + /** @type {{ originModule: Module, runtimeCondition: RuntimeSpec }[]} */ + const otherRuntimeConnections = []; + outer: for (const [ + originModule, + connections + ] of incomingConnectionsFromModules) { + /** @type {false | RuntimeSpec} */ + let currentRuntimeCondition = false; + for (const connection of connections) { + const runtimeCondition = filterRuntime(runtime, runtime => { + return connection.isTargetActive(runtime); + }); + if (runtimeCondition === false) continue; + if (runtimeCondition === true) continue outer; + if (currentRuntimeCondition !== false) { + currentRuntimeCondition = mergeRuntime( + currentRuntimeCondition, + runtimeCondition + ); + } else { + currentRuntimeCondition = runtimeCondition; + } + } + if (currentRuntimeCondition !== false) { + otherRuntimeConnections.push({ + originModule, + runtimeCondition: currentRuntimeCondition + }); + } + } + if (otherRuntimeConnections.length > 0) { + const problem = requestShortener => { + return `Module ${module.readableIdentifier( + requestShortener + )} is runtime-dependent referenced by these modules: ${Array.from( + otherRuntimeConnections, + ({ originModule, runtimeCondition }) => + `${originModule.readableIdentifier( + requestShortener + )} (expected runtime ${runtimeToString( + runtime + )}, module is only referenced in ${runtimeToString( + /** @type {RuntimeSpec} */ (runtimeCondition) + )})` + ).join(", ")}`; + }; + statistics.incorrectRuntimeCondition++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + } -/** - * @param {string[]} accessor variable plus properties - * @param {number} existingLength items of accessor that are existing already - * @param {boolean=} initLast if the last property should also be initialized to an object - * @returns {string} code to access the accessor while initializing - */ -const accessWithInit = (accessor, existingLength, initLast = false) => { - // This generates for [a, b, c, d]: - // (((a = typeof a === "undefined" ? {} : a).b = a.b || {}).c = a.b.c || {}).d - const base = accessor[0]; - if (accessor.length === 1 && !initLast) return base; - let current = - existingLength > 0 - ? base - : `(${base} = typeof ${base} === "undefined" ? {} : ${base})`; + let backup; + if (avoidMutateOnFailure) { + backup = config.snapshot(); + } - // i is the current position in accessor that has been printed - let i = 1; + // Add the module + config.add(module); - // all properties printed so far (excluding base) - let propsSoFar; + incomingModules.sort(compareModulesByIdentifier); - // if there is existingLength, print all properties until this position as property access - if (existingLength > i) { - propsSoFar = accessor.slice(1, existingLength); - i = existingLength; - current += propertyAccess(propsSoFar); - } else { - propsSoFar = []; - } + // Every module which depends on the added module must be in the configuration too. + for (const originModule of incomingModules) { + const problem = this._tryToAdd( + compilation, + config, + originModule, + runtime, + activeRuntime, + possibleModules, + candidates, + failureCache, + chunkGraph, + false, + statistics + ); + if (problem) { + if (backup !== undefined) config.rollback(backup); + statistics.importerFailed++; + failureCache.set(module, problem); // cache failures for performance + return problem; + } + } - // all remaining properties (except the last one when initLast is not set) - // should be printed as initializer - const initUntil = initLast ? accessor.length : accessor.length - 1; - for (; i < initUntil; i++) { - const prop = accessor[i]; - propsSoFar.push(prop); - current = `(${current}${propertyAccess([prop])} = ${base}${propertyAccess( - propsSoFar - )} || {})`; + // Add imports to possible candidates list + for (const imp of this._getImports(compilation, module, runtime)) { + candidates.add(imp); + } + statistics.added++; + return null; } +} - // print the last property as property access if not yet printed - if (i < accessor.length) - current = `${current}${propertyAccess([accessor[accessor.length - 1]])}`; - - return current; -}; - -/** - * @typedef {Object} AssignLibraryPluginOptions - * @property {LibraryType} type - * @property {string[] | "global"} prefix name prefix - * @property {string | false} declare declare name as variable - * @property {"error"|"static"|"copy"|"assign"} unnamed behavior for unnamed library name - * @property {"copy"|"assign"=} named behavior for named library name - */ - -/** - * @typedef {Object} AssignLibraryPluginParsed - * @property {string | string[]} name - * @property {string | string[] | undefined} export - */ - -/** - * @typedef {AssignLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} - */ -class AssignLibraryPlugin extends AbstractLibraryPlugin { +class ConcatConfiguration { /** - * @param {AssignLibraryPluginOptions} options the plugin options + * @param {Module} rootModule the root module + * @param {RuntimeSpec} runtime the runtime */ - constructor(options) { - super({ - pluginName: "AssignLibraryPlugin", - type: options.type - }); - this.prefix = options.prefix; - this.declare = options.declare; - this.unnamed = options.unnamed; - this.named = options.named || "assign"; + constructor(rootModule, runtime) { + this.rootModule = rootModule; + this.runtime = runtime; + /** @type {Set} */ + this.modules = new Set(); + this.modules.add(rootModule); + /** @type {Map} */ + this.warnings = new Map(); } - /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - parseOptions(library) { - const { name } = library; - if (this.unnamed === "error") { - if (typeof name !== "string" && !Array.isArray(name)) { - throw new Error( - `Library name must be a string or string array. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); - } - } else { - if (name && typeof name !== "string" && !Array.isArray(name)) { - throw new Error( - `Library name must be a string, string array or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); - } - } - return { - name: /** @type {string|string[]=} */ (name), - export: library.export - }; + add(module) { + this.modules.add(module); } - /** - * @param {Module} module the exporting entry module - * @param {string} entryName the name of the entrypoint - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - finishEntryModule( - module, - entryName, - { options, compilation, compilation: { moduleGraph } } - ) { - const runtime = getEntryRuntime(compilation, entryName); - if (options.export) { - const exportsInfo = moduleGraph.getExportInfo( - module, - Array.isArray(options.export) ? options.export[0] : options.export - ); - exportsInfo.setUsed(UsageState.Used, runtime); - exportsInfo.canMangleUse = false; - } else { - const exportsInfo = moduleGraph.getExportsInfo(module); - exportsInfo.setUsedInUnknownWay(runtime); - } - moduleGraph.addExtraReason(module, "used as library export"); + has(module) { + return this.modules.has(module); } - _getPrefix(compilation) { - return this.prefix === "global" - ? [compilation.runtimeTemplate.globalObject] - : this.prefix; + isEmpty() { + return this.modules.size === 1; } - _getResolvedFullName(options, chunk, compilation) { - const prefix = this._getPrefix(compilation); - const fullName = options.name ? prefix.concat(options.name) : prefix; - return fullName.map(n => - compilation.getPath(n, { - chunk - }) - ); + addWarning(module, problem) { + this.warnings.set(module, problem); } - /** - * @param {Source} source source - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - render(source, { chunk }, { options, compilation }) { - const fullNameResolved = this._getResolvedFullName( - options, - chunk, - compilation + getWarningsSorted() { + return new Map( + Array.from(this.warnings).sort((a, b) => { + const ai = a[0].identifier(); + const bi = b[0].identifier(); + if (ai < bi) return -1; + if (ai > bi) return 1; + return 0; + }) ); - if (this.declare) { - const base = fullNameResolved[0]; - if (!isNameValid(base)) { - throw new Error( - `Library name base (${base}) must be a valid identifier when using a var declaring library type. Either use a valid identifier (e. g. ${Template.toIdentifier( - base - )}) or use a different library type (e. g. 'type: "global"', which assign a property on the global scope instead of declaring a variable). ${ - AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE - }` - ); - } - source = new ConcatSource(`${this.declare} ${base};\n`, source); - } - return source; } /** - * @param {Module} module the exporting entry module - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {string | undefined} bailout reason + * @returns {Set} modules as set */ - embedInRuntimeBailout(module, { chunk }, { options, compilation }) { - const topLevelDeclarations = - module.buildInfo && module.buildInfo.topLevelDeclarations; - if (!topLevelDeclarations) - return "it doesn't tell about top level declarations."; - const fullNameResolved = this._getResolvedFullName( - options, - chunk, - compilation - ); - const base = fullNameResolved[0]; - if (topLevelDeclarations.has(base)) - return `it declares '${base}' on top-level, which conflicts with the current library output.`; + getModules() { + return this.modules; } - /** - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {string | undefined} bailout reason - */ - strictRuntimeBailout({ chunk }, { options, compilation }) { - if ( - this.declare || - this.prefix === "global" || - this.prefix.length > 0 || - !options.name - ) { - return; - } - return "a global variable is assign and maybe created"; + snapshot() { + return this.modules.size; } - /** - * @param {Source} source source - * @param {Module} module module - * @param {StartupRenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - renderStartup( - source, - module, - { moduleGraph, chunk }, - { options, compilation } - ) { - const fullNameResolved = this._getResolvedFullName( - options, - chunk, - compilation - ); - const staticExports = this.unnamed === "static"; - const exportAccess = options.export - ? propertyAccess( - Array.isArray(options.export) ? options.export : [options.export] - ) - : ""; - const result = new ConcatSource(source); - if (staticExports) { - const exportsInfo = moduleGraph.getExportsInfo(module); - const exportTarget = accessWithInit( - fullNameResolved, - this._getPrefix(compilation).length, - true - ); - for (const exportInfo of exportsInfo.orderedExports) { - if (!exportInfo.provided) continue; - const nameAccess = propertyAccess([exportInfo.name]); - result.add( - `${exportTarget}${nameAccess} = __webpack_exports__${exportAccess}${nameAccess};\n` - ); - } - result.add( - `Object.defineProperty(${exportTarget}, "__esModule", { value: true });\n` - ); - } else if (options.name ? this.named === "copy" : this.unnamed === "copy") { - result.add( - `var __webpack_export_target__ = ${accessWithInit( - fullNameResolved, - this._getPrefix(compilation).length, - true - )};\n` - ); - let exports = "__webpack_exports__"; - if (exportAccess) { - result.add( - `var __webpack_exports_export__ = __webpack_exports__${exportAccess};\n` - ); - exports = "__webpack_exports_export__"; + rollback(snapshot) { + const modules = this.modules; + for (const m of modules) { + if (snapshot === 0) { + modules.delete(m); + } else { + snapshot--; } - result.add( - `for(var i in ${exports}) __webpack_export_target__[i] = ${exports}[i];\n` - ); - result.add( - `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n` - ); - } else { - result.add( - `${accessWithInit( - fullNameResolved, - this._getPrefix(compilation).length, - false - )} = __webpack_exports__${exportAccess};\n` - ); - } - return result; - } - - /** - * @param {Chunk} chunk the chunk - * @param {Set} set runtime requirements - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - runtimeRequirements(chunk, set, libraryContext) { - // we don't need to return exports from runtime - } - - /** - * @param {Chunk} chunk the chunk - * @param {Hash} hash hash - * @param {ChunkHashContext} chunkHashContext chunk hash context - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { - hash.update("AssignLibraryPlugin"); - const fullNameResolved = this._getResolvedFullName( - options, - chunk, - compilation - ); - if (options.name ? this.named === "copy" : this.unnamed === "copy") { - hash.update("copy"); - } - if (this.declare) { - hash.update(this.declare); - } - hash.update(fullNameResolved.join(".")); - if (options.export) { - hash.update(`${options.export}`); } } } -module.exports = AssignLibraryPlugin; +module.exports = ModuleConcatenationPlugin; /***/ }), -/***/ 91452: +/***/ 46043: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103507,55 +103963,119 @@ module.exports = AssignLibraryPlugin; -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +const { SyncBailHook } = __webpack_require__(6967); +const { RawSource, CachedSource, CompatSource } = __webpack_require__(51255); +const Compilation = __webpack_require__(85720); +const WebpackError = __webpack_require__(53799); +const { compareSelect, compareStrings } = __webpack_require__(29579); +const createHash = __webpack_require__(49835); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ /** @typedef {import("../Compiler")} Compiler */ -/** @type {WeakMap>} */ -const enabledTypes = new WeakMap(); +const EMPTY_SET = new Set(); -const getEnabledTypes = compiler => { - let set = enabledTypes.get(compiler); - if (set === undefined) { - set = new Set(); - enabledTypes.set(compiler, set); +const addToList = (itemOrItems, list) => { + if (Array.isArray(itemOrItems)) { + for (const item of itemOrItems) { + list.add(item); + } + } else if (itemOrItems) { + list.add(itemOrItems); } - return set; }; -class EnableLibraryPlugin { - /** - * @param {LibraryType} type library type that should be available - */ - constructor(type) { - this.type = type; +/** + * @template T + * @param {T[]} input list + * @param {function(T): Buffer} fn map function + * @returns {Buffer[]} buffers without duplicates + */ +const mapAndDeduplicateBuffers = (input, fn) => { + // Buffer.equals compares size first so this should be efficient enough + // If it becomes a performance problem we can use a map and group by size + // instead of looping over all assets. + const result = []; + outer: for (const value of input) { + const buf = fn(value); + for (const other of result) { + if (buf.equals(other)) continue outer; + } + result.push(buf); } + return result; +}; - /** - * @param {Compiler} compiler the compiler instance - * @param {LibraryType} type type of library - * @returns {void} - */ - static setEnabled(compiler, type) { - getEnabledTypes(compiler).add(type); +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string + */ +const quoteMeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); +}; + +const cachedSourceMap = new WeakMap(); + +const toCachedSource = source => { + if (source instanceof CachedSource) { + return source; } + const entry = cachedSourceMap.get(source); + if (entry !== undefined) return entry; + const newSource = new CachedSource(CompatSource.from(source)); + cachedSourceMap.set(source, newSource); + return newSource; +}; + +/** + * @typedef {Object} AssetInfoForRealContentHash + * @property {string} name + * @property {AssetInfo} info + * @property {Source} source + * @property {RawSource | undefined} newSource + * @property {RawSource | undefined} newSourceWithoutOwn + * @property {string} content + * @property {Set} ownHashes + * @property {Promise} contentComputePromise + * @property {Promise} contentComputeWithoutOwnPromise + * @property {Set} referencedHashes + * @property {Set} hashes + */ +/** + * @typedef {Object} CompilationHooks + * @property {SyncBailHook<[Buffer[], string], string>} updateHash + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class RealContentHashPlugin { /** - * @param {Compiler} compiler the compiler instance - * @param {LibraryType} type type of library - * @returns {void} + * @param {Compilation} compilation the compilation + * @returns {CompilationHooks} the attached hooks */ - static checkEnabled(compiler, type) { - if (!getEnabledTypes(compiler).has(type)) { - throw new Error( - `Library type "${type}" is not enabled. ` + - "EnableLibraryPlugin need to be used to enable this type of library. " + - 'This usually happens through the "output.enabledLibraryTypes" option. ' + - 'If you are using a function as entry which sets "library", you need to add all potential library types to "output.enabledLibraryTypes". ' + - "These types are enabled: " + - Array.from(getEnabledTypes(compiler)).join(", ") + 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 = { + updateHash: new SyncBailHook(["content", "oldHash"]) + }; + compilationHooksMap.set(compilation, hooks); + } + return hooks; + } + + constructor({ hashFunction, hashDigest }) { + this._hashFunction = hashFunction; + this._hashDigest = hashDigest; } /** @@ -103564,195 +104084,291 @@ class EnableLibraryPlugin { * @returns {void} */ apply(compiler) { - const { type } = this; + compiler.hooks.compilation.tap("RealContentHashPlugin", compilation => { + const cacheAnalyse = compilation.getCache( + "RealContentHashPlugin|analyse" + ); + const cacheGenerate = compilation.getCache( + "RealContentHashPlugin|generate" + ); + const hooks = RealContentHashPlugin.getCompilationHooks(compilation); + compilation.hooks.processAssets.tapPromise( + { + name: "RealContentHashPlugin", + stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH + }, + async () => { + const assets = compilation.getAssets(); + /** @type {AssetInfoForRealContentHash[]} */ + const assetsWithInfo = []; + const hashToAssets = new Map(); + for (const { source, info, name } of assets) { + const cachedSource = toCachedSource(source); + const content = cachedSource.source(); + /** @type {Set} */ + const hashes = new Set(); + addToList(info.contenthash, hashes); + const data = { + name, + info, + source: cachedSource, + /** @type {RawSource | undefined} */ + newSource: undefined, + /** @type {RawSource | undefined} */ + newSourceWithoutOwn: undefined, + content, + /** @type {Set} */ + ownHashes: undefined, + contentComputePromise: undefined, + contentComputeWithoutOwnPromise: undefined, + /** @type {Set} */ + referencedHashes: undefined, + hashes + }; + assetsWithInfo.push(data); + for (const hash of hashes) { + const list = hashToAssets.get(hash); + if (list === undefined) { + hashToAssets.set(hash, [data]); + } else { + list.push(data); + } + } + } + if (hashToAssets.size === 0) return; + const hashRegExp = new RegExp( + Array.from(hashToAssets.keys(), quoteMeta).join("|"), + "g" + ); + await Promise.all( + assetsWithInfo.map(async asset => { + const { name, source, content, hashes } = asset; + if (Buffer.isBuffer(content)) { + asset.referencedHashes = EMPTY_SET; + asset.ownHashes = EMPTY_SET; + return; + } + const etag = cacheAnalyse.mergeEtags( + cacheAnalyse.getLazyHashedEtag(source), + Array.from(hashes).join("|") + ); + [asset.referencedHashes, asset.ownHashes] = + await cacheAnalyse.providePromise(name, etag, () => { + const referencedHashes = new Set(); + let ownHashes = new Set(); + const inContent = content.match(hashRegExp); + if (inContent) { + for (const hash of inContent) { + if (hashes.has(hash)) { + ownHashes.add(hash); + continue; + } + referencedHashes.add(hash); + } + } + return [referencedHashes, ownHashes]; + }); + }) + ); + const getDependencies = hash => { + const assets = hashToAssets.get(hash); + if (!assets) { + const referencingAssets = assetsWithInfo.filter(asset => + asset.referencedHashes.has(hash) + ); + const err = new WebpackError(`RealContentHashPlugin +Some kind of unexpected caching problem occurred. +An asset was cached with a reference to another asset (${hash}) that's not in the compilation anymore. +Either the asset was incorrectly cached, or the referenced asset should also be restored from cache. +Referenced by: +${referencingAssets + .map(a => { + const match = new RegExp(`.{0,20}${quoteMeta(hash)}.{0,20}`).exec( + a.content + ); + return ` - ${a.name}: ...${match ? match[0] : "???"}...`; + }) + .join("\n")}`); + compilation.errors.push(err); + return undefined; + } + const hashes = new Set(); + for (const { referencedHashes, ownHashes } of assets) { + if (!ownHashes.has(hash)) { + for (const hash of ownHashes) { + hashes.add(hash); + } + } + for (const hash of referencedHashes) { + hashes.add(hash); + } + } + return hashes; + }; + const hashInfo = hash => { + const assets = hashToAssets.get(hash); + return `${hash} (${Array.from(assets, a => a.name)})`; + }; + const hashesInOrder = new Set(); + for (const hash of hashToAssets.keys()) { + const add = (hash, stack) => { + const deps = getDependencies(hash); + if (!deps) return; + stack.add(hash); + for (const dep of deps) { + if (hashesInOrder.has(dep)) continue; + if (stack.has(dep)) { + throw new Error( + `Circular hash dependency ${Array.from( + stack, + hashInfo + ).join(" -> ")} -> ${hashInfo(dep)}` + ); + } + add(dep, stack); + } + hashesInOrder.add(hash); + stack.delete(hash); + }; + if (hashesInOrder.has(hash)) continue; + add(hash, new Set()); + } + const hashToNewHash = new Map(); + const getEtag = asset => + cacheGenerate.mergeEtags( + cacheGenerate.getLazyHashedEtag(asset.source), + Array.from(asset.referencedHashes, hash => + hashToNewHash.get(hash) + ).join("|") + ); + const computeNewContent = asset => { + if (asset.contentComputePromise) return asset.contentComputePromise; + return (asset.contentComputePromise = (async () => { + if ( + asset.ownHashes.size > 0 || + Array.from(asset.referencedHashes).some( + hash => hashToNewHash.get(hash) !== hash + ) + ) { + const identifier = asset.name; + const etag = getEtag(asset); + asset.newSource = await cacheGenerate.providePromise( + identifier, + etag, + () => { + const newContent = asset.content.replace(hashRegExp, hash => + hashToNewHash.get(hash) + ); + return new RawSource(newContent); + } + ); + } + })()); + }; + const computeNewContentWithoutOwn = asset => { + if (asset.contentComputeWithoutOwnPromise) + return asset.contentComputeWithoutOwnPromise; + return (asset.contentComputeWithoutOwnPromise = (async () => { + if ( + asset.ownHashes.size > 0 || + Array.from(asset.referencedHashes).some( + hash => hashToNewHash.get(hash) !== hash + ) + ) { + const identifier = asset.name + "|without-own"; + const etag = getEtag(asset); + asset.newSourceWithoutOwn = await cacheGenerate.providePromise( + identifier, + etag, + () => { + const newContent = asset.content.replace( + hashRegExp, + hash => { + if (asset.ownHashes.has(hash)) { + return ""; + } + return hashToNewHash.get(hash); + } + ); + return new RawSource(newContent); + } + ); + } + })()); + }; + const comparator = compareSelect(a => a.name, compareStrings); + for (const oldHash of hashesInOrder) { + const assets = hashToAssets.get(oldHash); + assets.sort(comparator); + const hash = createHash(this._hashFunction); + await Promise.all( + assets.map(asset => + asset.ownHashes.has(oldHash) + ? computeNewContentWithoutOwn(asset) + : computeNewContent(asset) + ) + ); + const assetsContent = mapAndDeduplicateBuffers(assets, asset => { + if (asset.ownHashes.has(oldHash)) { + return asset.newSourceWithoutOwn + ? asset.newSourceWithoutOwn.buffer() + : asset.source.buffer(); + } else { + return asset.newSource + ? asset.newSource.buffer() + : asset.source.buffer(); + } + }); + let newHash = hooks.updateHash.call(assetsContent, oldHash); + if (!newHash) { + for (const content of assetsContent) { + hash.update(content); + } + const digest = hash.digest(this._hashDigest); + newHash = /** @type {string} */ (digest.slice(0, oldHash.length)); + } + hashToNewHash.set(oldHash, newHash); + } + await Promise.all( + assetsWithInfo.map(async asset => { + await computeNewContent(asset); + const newName = asset.name.replace(hashRegExp, hash => + hashToNewHash.get(hash) + ); - // Only enable once - const enabled = getEnabledTypes(compiler); - if (enabled.has(type)) return; - enabled.add(type); + const infoUpdate = {}; + const hash = asset.info.contenthash; + infoUpdate.contenthash = Array.isArray(hash) + ? hash.map(hash => hashToNewHash.get(hash)) + : hashToNewHash.get(hash); - if (typeof type === "string") { - const enableExportProperty = () => { - const ExportPropertyTemplatePlugin = __webpack_require__(5487); - new ExportPropertyTemplatePlugin({ - type, - nsObjectUsed: type !== "module" - }).apply(compiler); - }; - switch (type) { - case "var": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: [], - declare: "var", - unnamed: "error" - }).apply(compiler); - break; - } - case "assign-properties": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: [], - declare: false, - unnamed: "error", - named: "copy" - }).apply(compiler); - break; - } - case "assign": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: [], - declare: false, - unnamed: "error" - }).apply(compiler); - break; - } - case "this": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: ["this"], - declare: false, - unnamed: "copy" - }).apply(compiler); - break; - } - case "window": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: ["window"], - declare: false, - unnamed: "copy" - }).apply(compiler); - break; - } - case "self": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: ["self"], - declare: false, - unnamed: "copy" - }).apply(compiler); - break; - } - case "global": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: "global", - declare: false, - unnamed: "copy" - }).apply(compiler); - break; - } - case "commonjs": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: ["exports"], - declare: false, - unnamed: "copy" - }).apply(compiler); - break; - } - case "commonjs-static": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: ["exports"], - declare: false, - unnamed: "static" - }).apply(compiler); - break; - } - case "commonjs2": - case "commonjs-module": { - //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 - const AssignLibraryPlugin = __webpack_require__(40080); - new AssignLibraryPlugin({ - type, - prefix: ["module", "exports"], - declare: false, - unnamed: "assign" - }).apply(compiler); - break; - } - case "amd": - case "amd-require": { - enableExportProperty(); - const AmdLibraryPlugin = __webpack_require__(67416); - new AmdLibraryPlugin({ - type, - requireAsWrapper: type === "amd-require" - }).apply(compiler); - break; - } - case "umd": - case "umd2": { - enableExportProperty(); - const UmdLibraryPlugin = __webpack_require__(54442); - new UmdLibraryPlugin({ - type, - optionalAmdExternalAsGlobal: type === "umd2" - }).apply(compiler); - break; - } - case "system": { - enableExportProperty(); - const SystemLibraryPlugin = __webpack_require__(11707); - new SystemLibraryPlugin({ - type - }).apply(compiler); - break; - } - case "jsonp": { - enableExportProperty(); - const JsonpLibraryPlugin = __webpack_require__(84415); - new JsonpLibraryPlugin({ - type - }).apply(compiler); - break; - } - case "module": { - enableExportProperty(); - const ModuleLibraryPlugin = __webpack_require__(59780); - new ModuleLibraryPlugin({ - type - }).apply(compiler); - break; + if (asset.newSource !== undefined) { + compilation.updateAsset( + asset.name, + asset.newSource, + infoUpdate + ); + } else { + compilation.updateAsset(asset.name, asset.source, infoUpdate); + } + + if (asset.name !== newName) { + compilation.renameAsset(asset.name, newName); + } + }) + ); } - default: - throw new Error(`Unsupported library type ${type}. -Plugins which provide custom library types must call EnableLibraryPlugin.setEnabled(compiler, type) to disable this error.`); - } - } else { - // TODO support plugin instances here - // apply them to the compiler - } + ); + }); } } -module.exports = EnableLibraryPlugin; +module.exports = RealContentHashPlugin; /***/ }), -/***/ 5487: +/***/ 84760: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103763,117 +104379,61 @@ module.exports = EnableLibraryPlugin; -const { ConcatSource } = __webpack_require__(51255); -const { UsageState } = __webpack_require__(63686); -const propertyAccess = __webpack_require__(54190); -const { getEntryRuntime } = __webpack_require__(17156); -const AbstractLibraryPlugin = __webpack_require__(26030); +const { STAGE_BASIC, STAGE_ADVANCED } = __webpack_require__(80057); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ /** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ - -/** - * @typedef {Object} ExportPropertyLibraryPluginParsed - * @property {string | string[]} export - */ - -/** - * @typedef {Object} ExportPropertyLibraryPluginOptions - * @property {LibraryType} type - * @property {boolean} nsObjectUsed the namespace object is used - */ -/** - * @typedef {ExportPropertyLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} - */ -class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin { - /** - * @param {ExportPropertyLibraryPluginOptions} options options - */ - constructor({ type, nsObjectUsed }) { - super({ - pluginName: "ExportPropertyLibraryPlugin", - type - }); - this.nsObjectUsed = nsObjectUsed; - } - - /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - parseOptions(library) { - return { - export: library.export - }; - } - - /** - * @param {Module} module the exporting entry module - * @param {string} entryName the name of the entrypoint - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - finishEntryModule( - module, - entryName, - { options, compilation, compilation: { moduleGraph } } - ) { - const runtime = getEntryRuntime(compilation, entryName); - if (options.export) { - const exportsInfo = moduleGraph.getExportInfo( - module, - Array.isArray(options.export) ? options.export[0] : options.export - ); - exportsInfo.setUsed(UsageState.Used, runtime); - exportsInfo.canMangleUse = false; - } else { - const exportsInfo = moduleGraph.getExportsInfo(module); - if (this.nsObjectUsed) { - exportsInfo.setUsedInUnknownWay(runtime); - } else { - exportsInfo.setAllKnownExportsUsed(runtime); - } - } - moduleGraph.addExtraReason(module, "used as library export"); - } +class RemoveEmptyChunksPlugin { /** - * @param {Chunk} chunk the chunk - * @param {Set} set runtime requirements - * @param {LibraryContext} libraryContext context + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - runtimeRequirements(chunk, set, libraryContext) {} + apply(compiler) { + compiler.hooks.compilation.tap("RemoveEmptyChunksPlugin", compilation => { + /** + * @param {Iterable} chunks the chunks array + * @returns {void} + */ + const handler = chunks => { + const chunkGraph = compilation.chunkGraph; + for (const chunk of chunks) { + if ( + chunkGraph.getNumberOfChunkModules(chunk) === 0 && + !chunk.hasRuntime() && + chunkGraph.getNumberOfEntryModules(chunk) === 0 + ) { + compilation.chunkGraph.disconnectChunk(chunk); + compilation.chunks.delete(chunk); + } + } + }; - /** - * @param {Source} source source - * @param {Module} module module - * @param {StartupRenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - renderStartup(source, module, renderContext, { options }) { - if (!options.export) return source; - const postfix = `__webpack_exports__ = __webpack_exports__${propertyAccess( - Array.isArray(options.export) ? options.export : [options.export] - )};\n`; - return new ConcatSource(source, postfix); + // TODO do it once + compilation.hooks.optimizeChunks.tap( + { + name: "RemoveEmptyChunksPlugin", + stage: STAGE_BASIC + }, + handler + ); + compilation.hooks.optimizeChunks.tap( + { + name: "RemoveEmptyChunksPlugin", + stage: STAGE_ADVANCED + }, + handler + ); + }); } } - -module.exports = ExportPropertyLibraryPlugin; +module.exports = RemoveEmptyChunksPlugin; /***/ }), -/***/ 84415: +/***/ 7081: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103884,93 +104444,126 @@ module.exports = ExportPropertyLibraryPlugin; -const { ConcatSource } = __webpack_require__(51255); -const AbstractLibraryPlugin = __webpack_require__(26030); +const { STAGE_BASIC } = __webpack_require__(80057); +const Queue = __webpack_require__(65930); +const { intersect } = __webpack_require__(93347); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ /** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ - -/** - * @typedef {Object} JsonpLibraryPluginOptions - * @property {LibraryType} type - */ - -/** - * @typedef {Object} JsonpLibraryPluginParsed - * @property {string} name - */ -/** - * @typedef {JsonpLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} - */ -class JsonpLibraryPlugin extends AbstractLibraryPlugin { +class RemoveParentModulesPlugin { /** - * @param {JsonpLibraryPluginOptions} options the plugin options + * @param {Compiler} compiler the compiler + * @returns {void} */ - constructor(options) { - super({ - pluginName: "JsonpLibraryPlugin", - type: options.type - }); - } + apply(compiler) { + compiler.hooks.compilation.tap("RemoveParentModulesPlugin", compilation => { + const handler = (chunks, chunkGroups) => { + const chunkGraph = compilation.chunkGraph; + const queue = new Queue(); + const availableModulesMap = new WeakMap(); - /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - parseOptions(library) { - const { name } = library; - if (typeof name !== "string") { - throw new Error( - `Jsonp library name must be a simple string. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); - } - return { - name: /** @type {string} */ (name) - }; - } + for (const chunkGroup of compilation.entrypoints.values()) { + // initialize available modules for chunks without parents + availableModulesMap.set(chunkGroup, new Set()); + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } + } + for (const chunkGroup of compilation.asyncEntrypoints) { + // initialize available modules for chunks without parents + availableModulesMap.set(chunkGroup, new Set()); + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } + } - /** - * @param {Source} source source - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - render(source, { chunk }, { options, compilation }) { - const name = compilation.getPath(options.name, { - chunk - }); - return new ConcatSource(`${name}(`, source, ")"); - } + while (queue.length > 0) { + const chunkGroup = queue.dequeue(); + let availableModules = availableModulesMap.get(chunkGroup); + let changed = false; + for (const parent of chunkGroup.parentsIterable) { + const availableModulesInParent = availableModulesMap.get(parent); + if (availableModulesInParent !== undefined) { + // If we know the available modules in parent: process these + if (availableModules === undefined) { + // if we have not own info yet: create new entry + availableModules = new Set(availableModulesInParent); + for (const chunk of parent.chunks) { + for (const m of chunkGraph.getChunkModulesIterable(chunk)) { + availableModules.add(m); + } + } + availableModulesMap.set(chunkGroup, availableModules); + changed = true; + } else { + for (const m of availableModules) { + if ( + !chunkGraph.isModuleInChunkGroup(m, parent) && + !availableModulesInParent.has(m) + ) { + availableModules.delete(m); + changed = true; + } + } + } + } + } + if (changed) { + // if something changed: enqueue our children + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } + } + } - /** - * @param {Chunk} chunk the chunk - * @param {Hash} hash hash - * @param {ChunkHashContext} chunkHashContext chunk hash context - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { - hash.update("JsonpLibraryPlugin"); - hash.update(compilation.getPath(options.name, { chunk })); + // now we have available modules for every chunk + for (const chunk of chunks) { + const availableModulesSets = Array.from( + chunk.groupsIterable, + chunkGroup => availableModulesMap.get(chunkGroup) + ); + if (availableModulesSets.some(s => s === undefined)) continue; // No info about this chunk group + const availableModules = + availableModulesSets.length === 1 + ? availableModulesSets[0] + : intersect(availableModulesSets); + const numberOfModules = chunkGraph.getNumberOfChunkModules(chunk); + const toRemove = new Set(); + if (numberOfModules < availableModules.size) { + for (const m of chunkGraph.getChunkModulesIterable(chunk)) { + if (availableModules.has(m)) { + toRemove.add(m); + } + } + } else { + for (const m of availableModules) { + if (chunkGraph.isModuleInChunk(m, chunk)) { + toRemove.add(m); + } + } + } + for (const module of toRemove) { + chunkGraph.disconnectChunkAndModule(chunk, module); + } + } + }; + compilation.hooks.optimizeChunks.tap( + { + name: "RemoveParentModulesPlugin", + stage: STAGE_BASIC + }, + handler + ); + }); } } - -module.exports = JsonpLibraryPlugin; +module.exports = RemoveParentModulesPlugin; /***/ }), -/***/ 59780: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 2837: +/***/ (function(module) { "use strict"; /* @@ -103980,349 +104573,393 @@ module.exports = JsonpLibraryPlugin; -const { ConcatSource } = __webpack_require__(51255); -const Template = __webpack_require__(39722); -const propertyAccess = __webpack_require__(54190); -const AbstractLibraryPlugin = __webpack_require__(26030); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ /** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ - -/** - * @typedef {Object} ModuleLibraryPluginOptions - * @property {LibraryType} type - */ - -/** - * @typedef {Object} ModuleLibraryPluginParsed - * @property {string} name - */ -/** - * @typedef {ModuleLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} - */ -class ModuleLibraryPlugin extends AbstractLibraryPlugin { - /** - * @param {ModuleLibraryPluginOptions} options the plugin options - */ +class RuntimeChunkPlugin { constructor(options) { - super({ - pluginName: "ModuleLibraryPlugin", - type: options.type - }); - } - - /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - parseOptions(library) { - const { name } = library; - if (name) { - throw new Error( - `Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); - } - return { - name: /** @type {string} */ (name) + this.options = { + name: entrypoint => `runtime~${entrypoint.name}`, + ...options }; } /** - * @param {Source} source source - * @param {Module} module module - * @param {StartupRenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - renderStartup( - source, - module, - { moduleGraph, chunk }, - { options, compilation } - ) { - const result = new ConcatSource(source); - const exportsInfo = moduleGraph.getExportsInfo(module); - const exports = []; - const isAsync = moduleGraph.isAsync(module); - if (isAsync) { - result.add(`__webpack_exports__ = await __webpack_exports__;\n`); - } - for (const exportInfo of exportsInfo.orderedExports) { - if (!exportInfo.provided) continue; - const varName = `__webpack_exports__${Template.toIdentifier( - exportInfo.name - )}`; - result.add( - `var ${varName} = __webpack_exports__${propertyAccess([ - exportInfo.getUsedName(exportInfo.name, chunk.runtime) - ])};\n` + apply(compiler) { + compiler.hooks.thisCompilation.tap("RuntimeChunkPlugin", compilation => { + compilation.hooks.addEntry.tap( + "RuntimeChunkPlugin", + (_, { name: entryName }) => { + if (entryName === undefined) return; + const data = compilation.entries.get(entryName); + if (data.options.runtime === undefined && !data.options.dependOn) { + // Determine runtime chunk name + let name = this.options.name; + if (typeof name === "function") { + name = name({ name: entryName }); + } + data.options.runtime = name; + } + } ); - exports.push(`${varName} as ${exportInfo.name}`); - } - if (exports.length > 0) { - result.add(`export { ${exports.join(", ")} };\n`); - } - return result; + }); } } -module.exports = ModuleLibraryPlugin; +module.exports = RuntimeChunkPlugin; /***/ }), -/***/ 11707: +/***/ 84800: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Joel Denning @joeldenning + Author Tobias Koppers @sokra */ -const { ConcatSource } = __webpack_require__(51255); -const { UsageState } = __webpack_require__(63686); -const ExternalModule = __webpack_require__(73071); -const Template = __webpack_require__(39722); -const propertyAccess = __webpack_require__(54190); -const AbstractLibraryPlugin = __webpack_require__(26030); +const glob2regexp = __webpack_require__(86140); +const { STAGE_DEFAULT } = __webpack_require__(80057); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(67157); +const HarmonyImportSpecifierDependency = __webpack_require__(14077); +const formatLocation = __webpack_require__(16734); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */ /** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ /** - * @typedef {Object} SystemLibraryPluginOptions - * @property {LibraryType} type + * @typedef {Object} ExportInModule + * @property {Module} module the module + * @property {string} exportName the name of the export + * @property {boolean} checked if the export is conditional */ /** - * @typedef {Object} SystemLibraryPluginParsed - * @property {string} name + * @typedef {Object} ReexportInfo + * @property {Map} static + * @property {Map>} dynamic */ +/** @type {WeakMap>} */ +const globToRegexpCache = new WeakMap(); + /** - * @typedef {SystemLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} + * @param {string} glob the pattern + * @param {Map} cache the glob to RegExp cache + * @returns {RegExp} a regular expression */ -class SystemLibraryPlugin extends AbstractLibraryPlugin { - /** - * @param {SystemLibraryPluginOptions} options the plugin options - */ - constructor(options) { - super({ - pluginName: "SystemLibraryPlugin", - type: options.type - }); +const globToRegexp = (glob, cache) => { + const cacheEntry = cache.get(glob); + if (cacheEntry !== undefined) return cacheEntry; + if (!glob.includes("/")) { + glob = `**/${glob}`; } + const baseRegexp = glob2regexp(glob, { globstar: true, extended: true }); + const regexpSource = baseRegexp.source; + const regexp = new RegExp("^(\\./)?" + regexpSource.slice(1)); + cache.set(glob, regexp); + return regexp; +}; +class SideEffectsFlagPlugin { /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding + * @param {boolean} analyseSource analyse source code for side effects */ - parseOptions(library) { - const { name } = library; - if (name && typeof name !== "string") { - throw new Error( - `System.js library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` - ); - } - return { - name: /** @type {string=} */ (name) - }; + constructor(analyseSource = true) { + this._analyseSource = analyseSource; } - /** - * @param {Source} source source - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - render(source, { chunkGraph, moduleGraph, chunk }, { options, compilation }) { - const modules = chunkGraph - .getChunkModules(chunk) - .filter(m => m instanceof ExternalModule && m.externalType === "system"); - const externals = /** @type {ExternalModule[]} */ (modules); - - // The name this bundle should be registered as with System - const name = options.name - ? `${JSON.stringify(compilation.getPath(options.name, { chunk }))}, ` - : ""; - - // The array of dependencies that are external to webpack and will be provided by System - const systemDependencies = JSON.stringify( - externals.map(m => - typeof m.request === "object" && !Array.isArray(m.request) - ? m.request.amd - : m.request - ) - ); - - // The name of the variable provided by System for exporting - const dynamicExport = "__WEBPACK_DYNAMIC_EXPORT__"; - - // An array of the internal variable names for the webpack externals - const externalWebpackNames = externals.map( - m => - `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( - `${chunkGraph.getModuleId(m)}` - )}__` - ); - - // Declaring variables for the internal variable names for the webpack externals - const externalVarDeclarations = externalWebpackNames - .map(name => `var ${name} = {};`) - .join("\n"); - - // Define __esModule flag on all internal variables and helpers - const externalVarInitialization = []; + apply(compiler) { + let cache = globToRegexpCache.get(compiler.root); + if (cache === undefined) { + cache = new Map(); + globToRegexpCache.set(compiler.root, cache); + } + compiler.hooks.compilation.tap( + "SideEffectsFlagPlugin", + (compilation, { normalModuleFactory }) => { + const moduleGraph = compilation.moduleGraph; + normalModuleFactory.hooks.module.tap( + "SideEffectsFlagPlugin", + (module, data) => { + const resolveData = data.resourceResolveData; + if ( + resolveData && + resolveData.descriptionFileData && + resolveData.relativePath + ) { + const sideEffects = resolveData.descriptionFileData.sideEffects; + if (sideEffects !== undefined) { + if (module.factoryMeta === undefined) { + module.factoryMeta = {}; + } + const hasSideEffects = + SideEffectsFlagPlugin.moduleHasSideEffects( + resolveData.relativePath, + sideEffects, + cache + ); + module.factoryMeta.sideEffectFree = !hasSideEffects; + } + } - // The system.register format requires an array of setter functions for externals. - const setters = - externalWebpackNames.length === 0 - ? "" - : Template.asString([ - "setters: [", - Template.indent( - externals - .map((module, i) => { - const external = externalWebpackNames[i]; - const exportsInfo = moduleGraph.getExportsInfo(module); - const otherUnused = - exportsInfo.otherExportsInfo.getUsed(chunk.runtime) === - UsageState.Unused; - const instructions = []; - const handledNames = []; - for (const exportInfo of exportsInfo.orderedExports) { - const used = exportInfo.getUsedName( - undefined, - chunk.runtime - ); - if (used) { - if (otherUnused || used !== exportInfo.name) { - instructions.push( - `${external}${propertyAccess([ - used - ])} = module${propertyAccess([exportInfo.name])};` - ); - handledNames.push(exportInfo.name); - } - } else { - handledNames.push(exportInfo.name); + return module; + } + ); + normalModuleFactory.hooks.module.tap( + "SideEffectsFlagPlugin", + (module, data) => { + if (typeof data.settings.sideEffects === "boolean") { + if (module.factoryMeta === undefined) { + module.factoryMeta = {}; + } + module.factoryMeta.sideEffectFree = !data.settings.sideEffects; + } + return module; + } + ); + if (this._analyseSource) { + /** + * @param {JavascriptParser} parser the parser + * @returns {void} + */ + const parserHandler = parser => { + let sideEffectsStatement; + parser.hooks.program.tap("SideEffectsFlagPlugin", () => { + sideEffectsStatement = undefined; + }); + parser.hooks.statement.tap( + { name: "SideEffectsFlagPlugin", stage: -100 }, + statement => { + if (sideEffectsStatement) return; + if (parser.scope.topLevelScope !== true) return; + switch (statement.type) { + case "ExpressionStatement": + if ( + !parser.isPure(statement.expression, statement.range[0]) + ) { + sideEffectsStatement = statement; } - } - if (!otherUnused) { + break; + case "IfStatement": + case "WhileStatement": + case "DoWhileStatement": + if (!parser.isPure(statement.test, statement.range[0])) { + sideEffectsStatement = statement; + } + // statement hook will be called for child statements too + break; + case "ForStatement": if ( - !Array.isArray(module.request) || - module.request.length === 1 + !parser.isPure(statement.init, statement.range[0]) || + !parser.isPure( + statement.test, + statement.init + ? statement.init.range[1] + : statement.range[0] + ) || + !parser.isPure( + statement.update, + statement.test + ? statement.test.range[1] + : statement.init + ? statement.init.range[1] + : statement.range[0] + ) ) { - externalVarInitialization.push( - `Object.defineProperty(${external}, "__esModule", { value: true });` + sideEffectsStatement = statement; + } + // statement hook will be called for child statements too + break; + case "SwitchStatement": + if ( + !parser.isPure(statement.discriminant, statement.range[0]) + ) { + sideEffectsStatement = statement; + } + // statement hook will be called for child statements too + break; + case "VariableDeclaration": + case "ClassDeclaration": + case "FunctionDeclaration": + if (!parser.isPure(statement, statement.range[0])) { + sideEffectsStatement = statement; + } + break; + case "ExportNamedDeclaration": + case "ExportDefaultDeclaration": + if ( + !parser.isPure(statement.declaration, statement.range[0]) + ) { + sideEffectsStatement = statement; + } + break; + case "LabeledStatement": + case "BlockStatement": + // statement hook will be called for child statements too + break; + case "EmptyStatement": + break; + case "ExportAllDeclaration": + case "ImportDeclaration": + // imports will be handled by the dependencies + break; + default: + sideEffectsStatement = statement; + break; + } + } + ); + parser.hooks.finish.tap("SideEffectsFlagPlugin", () => { + if (sideEffectsStatement === undefined) { + parser.state.module.buildMeta.sideEffectFree = true; + } else { + const { loc, type } = sideEffectsStatement; + moduleGraph + .getOptimizationBailout(parser.state.module) + .push( + () => + `Statement (${type}) with side effects in source code at ${formatLocation( + loc + )}` + ); + } + }); + }; + for (const key of [ + "javascript/auto", + "javascript/esm", + "javascript/dynamic" + ]) { + normalModuleFactory.hooks.parser + .for(key) + .tap("SideEffectsFlagPlugin", parserHandler); + } + } + compilation.hooks.optimizeDependencies.tap( + { + name: "SideEffectsFlagPlugin", + stage: STAGE_DEFAULT + }, + modules => { + const logger = compilation.getLogger( + "webpack.SideEffectsFlagPlugin" + ); + + logger.time("update dependencies"); + for (const module of modules) { + if (module.getSideEffectsConnectionState(moduleGraph) === false) { + const exportsInfo = moduleGraph.getExportsInfo(module); + for (const connection of moduleGraph.getIncomingConnections( + module + )) { + const dep = connection.dependency; + let isReexport; + if ( + (isReexport = + dep instanceof + HarmonyExportImportedSpecifierDependency) || + (dep instanceof HarmonyImportSpecifierDependency && + !dep.namespaceObjectAsContext) + ) { + // TODO improve for export * + if (isReexport && dep.name) { + const exportInfo = moduleGraph.getExportInfo( + connection.originModule, + dep.name + ); + exportInfo.moveTarget( + moduleGraph, + ({ module }) => + module.getSideEffectsConnectionState(moduleGraph) === + false, + ({ module: newModule, export: exportName }) => { + moduleGraph.updateModule(dep, newModule); + moduleGraph.addExplanation( + dep, + "(skipped side-effect-free modules)" + ); + const ids = dep.getIds(moduleGraph); + dep.setIds( + moduleGraph, + exportName + ? [...exportName, ...ids.slice(1)] + : ids.slice(1) + ); + return moduleGraph.getConnection(dep); + } ); + continue; } - if (handledNames.length > 0) { - const name = `${external}handledNames`; - externalVarInitialization.push( - `var ${name} = ${JSON.stringify(handledNames)};` + // TODO improve for nested imports + const ids = dep.getIds(moduleGraph); + if (ids.length > 0) { + const exportInfo = exportsInfo.getExportInfo(ids[0]); + const target = exportInfo.getTarget( + moduleGraph, + ({ module }) => + module.getSideEffectsConnectionState(moduleGraph) === + false ); - instructions.push( - Template.asString([ - "Object.keys(module).forEach(function(key) {", - Template.indent([ - `if(${name}.indexOf(key) >= 0)`, - Template.indent(`${external}[key] = module[key];`) - ]), - "});" - ]) + if (!target) continue; + + moduleGraph.updateModule(dep, target.module); + moduleGraph.addExplanation( + dep, + "(skipped side-effect-free modules)" ); - } else { - instructions.push( - Template.asString([ - "Object.keys(module).forEach(function(key) {", - Template.indent([`${external}[key] = module[key];`]), - "});" - ]) + dep.setIds( + moduleGraph, + target.export + ? [...target.export, ...ids.slice(1)] + : ids.slice(1) ); } } - if (instructions.length === 0) return "function() {}"; - return Template.asString([ - "function(module) {", - Template.indent(instructions), - "}" - ]); - }) - .join(",\n") - ), - "]," - ]); - - return new ConcatSource( - Template.asString([ - `System.register(${name}${systemDependencies}, function(${dynamicExport}, __system_context__) {`, - Template.indent([ - externalVarDeclarations, - Template.asString(externalVarInitialization), - "return {", - Template.indent([ - setters, - "execute: function() {", - Template.indent(`${dynamicExport}(`) - ]) - ]), - "" - ]), - source, - Template.asString([ - "", - Template.indent([ - Template.indent([Template.indent([");"]), "}"]), - "};" - ]), - "})" - ]) + } + } + } + logger.timeEnd("update dependencies"); + } + ); + } ); } - /** - * @param {Chunk} chunk the chunk - * @param {Hash} hash hash - * @param {ChunkHashContext} chunkHashContext chunk hash context - * @param {LibraryContext} libraryContext context - * @returns {void} - */ - chunkHash(chunk, hash, chunkHashContext, { options, compilation }) { - hash.update("SystemLibraryPlugin"); - if (options.name) { - hash.update(compilation.getPath(options.name, { chunk })); + static moduleHasSideEffects(moduleName, flagValue, cache) { + switch (typeof flagValue) { + case "undefined": + return true; + case "boolean": + return flagValue; + case "string": + return globToRegexp(flagValue, cache).test(moduleName); + case "object": + return flagValue.some(glob => + SideEffectsFlagPlugin.moduleHasSideEffects(moduleName, glob, cache) + ); } } } - -module.exports = SystemLibraryPlugin; +module.exports = SideEffectsFlagPlugin; /***/ }), -/***/ 54442: +/***/ 21478: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -104333,964 +104970,778 @@ module.exports = SystemLibraryPlugin; -const { ConcatSource, OriginalSource } = __webpack_require__(51255); -const ExternalModule = __webpack_require__(73071); -const Template = __webpack_require__(39722); -const AbstractLibraryPlugin = __webpack_require__(26030); +const Chunk = __webpack_require__(39385); +const { STAGE_ADVANCED } = __webpack_require__(80057); +const WebpackError = __webpack_require__(53799); +const { requestToId } = __webpack_require__(63290); +const { isSubset } = __webpack_require__(93347); +const SortableSet = __webpack_require__(13098); +const { + compareModulesByIdentifier, + compareIterables +} = __webpack_require__(29579); +const createHash = __webpack_require__(49835); +const deterministicGrouping = __webpack_require__(59836); +const { makePathsRelative } = __webpack_require__(82186); +const memoize = __webpack_require__(78676); +const MinMaxSizeWarning = __webpack_require__(85305); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryCustomUmdCommentObject} LibraryCustomUmdCommentObject */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksCacheGroup} OptimizationSplitChunksCacheGroup */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksGetCacheGroups} OptimizationSplitChunksGetCacheGroups */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksOptions} OptimizationSplitChunksOptions */ +/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksSizes} OptimizationSplitChunksSizes */ +/** @typedef {import("../../declarations/WebpackOptions").Output} OutputOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("../Compilation").PathData} PathData */ /** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext} LibraryContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../util/deterministicGrouping").GroupedItems} DeterministicGroupingGroupedItemsForModule */ +/** @typedef {import("../util/deterministicGrouping").Options} DeterministicGroupingOptionsForModule */ + +/** @typedef {Record} SplitChunksSizes */ /** - * @param {string[]} accessor the accessor to convert to path - * @returns {string} the path + * @callback ChunkFilterFunction + * @param {Chunk} chunk + * @returns {boolean} */ -const accessorToObjectAccess = accessor => { - return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); -}; /** - * @param {string|undefined} base the path prefix - * @param {string|string[]} accessor the accessor - * @param {string=} joinWith the element separator - * @returns {string} the path + * @callback CombineSizeFunction + * @param {number} a + * @param {number} b + * @returns {number} */ -const accessorAccess = (base, accessor, joinWith = ", ") => { - const accessors = Array.isArray(accessor) ? accessor : [accessor]; - return accessors - .map((_, idx) => { - const a = base - ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) - : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); - if (idx === accessors.length - 1) return a; - if (idx === 0 && base === undefined) - return `${a} = typeof ${a} === "object" ? ${a} : {}`; - return `${a} = ${a} || {}`; - }) - .join(joinWith); -}; - -/** @typedef {string | string[] | LibraryCustomUmdObject} UmdLibraryPluginName */ /** - * @typedef {Object} UmdLibraryPluginOptions - * @property {LibraryType} type - * @property {boolean=} optionalAmdExternalAsGlobal + * @typedef {Object} CacheGroupSource + * @property {string=} key + * @property {number=} priority + * @property {GetName=} getName + * @property {ChunkFilterFunction=} chunksFilter + * @property {boolean=} enforce + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} minSizeReduction + * @property {SplitChunksSizes} minRemainingSize + * @property {SplitChunksSizes} enforceSizeThreshold + * @property {SplitChunksSizes} maxAsyncSize + * @property {SplitChunksSizes} maxInitialSize + * @property {number=} minChunks + * @property {number=} maxAsyncRequests + * @property {number=} maxInitialRequests + * @property {(string | function(PathData, AssetInfo=): string)=} filename + * @property {string=} idHint + * @property {string} automaticNameDelimiter + * @property {boolean=} reuseExistingChunk + * @property {boolean=} usedExports */ /** - * @typedef {Object} UmdLibraryPluginParsed - * @property {string | string[]} name - * @property {LibraryCustomUmdObject} names - * @property {string | LibraryCustomUmdCommentObject} auxiliaryComment - * @property {boolean} namedDefine + * @typedef {Object} CacheGroup + * @property {string} key + * @property {number=} priority + * @property {GetName=} getName + * @property {ChunkFilterFunction=} chunksFilter + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} minSizeReduction + * @property {SplitChunksSizes} minRemainingSize + * @property {SplitChunksSizes} enforceSizeThreshold + * @property {SplitChunksSizes} maxAsyncSize + * @property {SplitChunksSizes} maxInitialSize + * @property {number=} minChunks + * @property {number=} maxAsyncRequests + * @property {number=} maxInitialRequests + * @property {(string | function(PathData, AssetInfo=): string)=} filename + * @property {string=} idHint + * @property {string} automaticNameDelimiter + * @property {boolean} reuseExistingChunk + * @property {boolean} usedExports + * @property {boolean} _validateSize + * @property {boolean} _validateRemainingSize + * @property {SplitChunksSizes} _minSizeForMaxSize + * @property {boolean} _conditionalEnforce */ /** - * @typedef {UmdLibraryPluginParsed} T - * @extends {AbstractLibraryPlugin} + * @typedef {Object} FallbackCacheGroup + * @property {ChunkFilterFunction} chunksFilter + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} maxAsyncSize + * @property {SplitChunksSizes} maxInitialSize + * @property {string} automaticNameDelimiter */ -class UmdLibraryPlugin extends AbstractLibraryPlugin { - /** - * @param {UmdLibraryPluginOptions} options the plugin option - */ - constructor(options) { - super({ - pluginName: "UmdLibraryPlugin", - type: options.type - }); - - this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal; - } - - /** - * @param {LibraryOptions} library normalized library option - * @returns {T | false} preprocess as needed by overriding - */ - parseOptions(library) { - /** @type {LibraryName} */ - let name; - /** @type {LibraryCustomUmdObject} */ - let names; - if (typeof library.name === "object" && !Array.isArray(library.name)) { - name = library.name.root || library.name.amd || library.name.commonjs; - names = library.name; - } else { - name = library.name; - const singleName = Array.isArray(name) ? name[0] : name; - names = { - commonjs: singleName, - root: library.name, - amd: singleName - }; - } - return { - name, - names, - auxiliaryComment: library.auxiliaryComment, - namedDefine: library.umdNamedDefine - }; - } - - /** - * @param {Source} source source - * @param {RenderContext} renderContext render context - * @param {LibraryContext} libraryContext context - * @returns {Source} source with library export - */ - render( - source, - { chunkGraph, runtimeTemplate, chunk, moduleGraph }, - { options, compilation } - ) { - const modules = chunkGraph - .getChunkModules(chunk) - .filter( - m => - m instanceof ExternalModule && - (m.externalType === "umd" || m.externalType === "umd2") - ); - let externals = /** @type {ExternalModule[]} */ (modules); - /** @type {ExternalModule[]} */ - const optionalExternals = []; - /** @type {ExternalModule[]} */ - let requiredExternals = []; - if (this.optionalAmdExternalAsGlobal) { - for (const m of externals) { - if (m.isOptional(moduleGraph)) { - optionalExternals.push(m); - } else { - requiredExternals.push(m); - } - } - externals = requiredExternals.concat(optionalExternals); - } else { - requiredExternals = externals; - } - const replaceKeys = str => { - return compilation.getPath(str, { - chunk - }); - }; +/** + * @typedef {Object} CacheGroupsContext + * @property {ModuleGraph} moduleGraph + * @property {ChunkGraph} chunkGraph + */ - const externalsDepsArray = modules => { - return `[${replaceKeys( - modules - .map(m => - JSON.stringify( - typeof m.request === "object" ? m.request.amd : m.request - ) - ) - .join(", ") - )}]`; - }; +/** + * @callback GetCacheGroups + * @param {Module} module + * @param {CacheGroupsContext} context + * @returns {CacheGroupSource[]} + */ - const externalsRootArray = modules => { - return replaceKeys( - modules - .map(m => { - let request = m.request; - if (typeof request === "object") request = request.root; - return `root${accessorToObjectAccess([].concat(request))}`; - }) - .join(", ") - ); - }; +/** + * @callback GetName + * @param {Module=} module + * @param {Chunk[]=} chunks + * @param {string=} key + * @returns {string=} + */ - const externalsRequireArray = type => { - return replaceKeys( - externals - .map(m => { - let expr; - let request = m.request; - if (typeof request === "object") { - request = request[type]; - } - if (request === undefined) { - throw new Error( - "Missing external configuration for type:" + type - ); - } - if (Array.isArray(request)) { - expr = `require(${JSON.stringify( - request[0] - )})${accessorToObjectAccess(request.slice(1))}`; - } else { - expr = `require(${JSON.stringify(request)})`; - } - if (m.isOptional(moduleGraph)) { - expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; - } - return expr; - }) - .join(", ") - ); - }; +/** + * @typedef {Object} SplitChunksOptions + * @property {ChunkFilterFunction} chunksFilter + * @property {string[]} defaultSizeTypes + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} minSizeReduction + * @property {SplitChunksSizes} minRemainingSize + * @property {SplitChunksSizes} enforceSizeThreshold + * @property {SplitChunksSizes} maxInitialSize + * @property {SplitChunksSizes} maxAsyncSize + * @property {number} minChunks + * @property {number} maxAsyncRequests + * @property {number} maxInitialRequests + * @property {boolean} hidePathInfo + * @property {string | function(PathData, AssetInfo=): string} filename + * @property {string} automaticNameDelimiter + * @property {GetCacheGroups} getCacheGroups + * @property {GetName} getName + * @property {boolean} usedExports + * @property {FallbackCacheGroup} fallbackCacheGroup + */ - const externalsArguments = modules => { - return modules - .map( - m => - `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( - `${chunkGraph.getModuleId(m)}` - )}__` - ) - .join(", "); - }; +/** + * @typedef {Object} ChunksInfoItem + * @property {SortableSet} modules + * @property {CacheGroup} cacheGroup + * @property {number} cacheGroupIndex + * @property {string} name + * @property {Record} sizes + * @property {Set} chunks + * @property {Set} reuseableChunks + * @property {Set} chunksKeys + */ - const libraryName = library => { - return JSON.stringify(replaceKeys([].concat(library).pop())); - }; +const defaultGetName = /** @type {GetName} */ (() => {}); - let amdFactory; - if (optionalExternals.length > 0) { - const wrapperArguments = externalsArguments(requiredExternals); - const factoryArguments = - requiredExternals.length > 0 - ? externalsArguments(requiredExternals) + - ", " + - externalsRootArray(optionalExternals) - : externalsRootArray(optionalExternals); - amdFactory = - `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` + - ` return factory(${factoryArguments});\n` + - " }"; - } else { - amdFactory = "factory"; - } +const deterministicGroupingForModules = + /** @type {function(DeterministicGroupingOptionsForModule): DeterministicGroupingGroupedItemsForModule[]} */ ( + deterministicGrouping + ); - const { auxiliaryComment, namedDefine, names } = options; +/** @type {WeakMap} */ +const getKeyCache = new WeakMap(); - const getAuxiliaryComment = type => { - if (auxiliaryComment) { - if (typeof auxiliaryComment === "string") - return "\t//" + auxiliaryComment + "\n"; - if (auxiliaryComment[type]) - return "\t//" + auxiliaryComment[type] + "\n"; - } - return ""; - }; +/** + * @param {string} name a filename to hash + * @param {OutputOptions} outputOptions hash function used + * @returns {string} hashed filename + */ +const hashFilename = (name, outputOptions) => { + const digest = /** @type {string} */ ( + createHash(outputOptions.hashFunction) + .update(name) + .digest(outputOptions.hashDigest) + ); + return digest.slice(0, 8); +}; - return new ConcatSource( - new OriginalSource( - "(function webpackUniversalModuleDefinition(root, factory) {\n" + - getAuxiliaryComment("commonjs2") + - " if(typeof exports === 'object' && typeof module === 'object')\n" + - " module.exports = factory(" + - externalsRequireArray("commonjs2") + - ");\n" + - getAuxiliaryComment("amd") + - " else if(typeof define === 'function' && define.amd)\n" + - (requiredExternals.length > 0 - ? names.amd && namedDefine === true - ? " define(" + - libraryName(names.amd) + - ", " + - externalsDepsArray(requiredExternals) + - ", " + - amdFactory + - ");\n" - : " define(" + - externalsDepsArray(requiredExternals) + - ", " + - amdFactory + - ");\n" - : names.amd && namedDefine === true - ? " define(" + - libraryName(names.amd) + - ", [], " + - amdFactory + - ");\n" - : " define([], " + amdFactory + ");\n") + - (names.root || names.commonjs - ? getAuxiliaryComment("commonjs") + - " else if(typeof exports === 'object')\n" + - " exports[" + - libraryName(names.commonjs || names.root) + - "] = factory(" + - externalsRequireArray("commonjs") + - ");\n" + - getAuxiliaryComment("root") + - " else\n" + - " " + - replaceKeys( - accessorAccess("root", names.root || names.commonjs) - ) + - " = factory(" + - externalsRootArray(externals) + - ");\n" - : " else {\n" + - (externals.length > 0 - ? " var a = typeof exports === 'object' ? factory(" + - externalsRequireArray("commonjs") + - ") : factory(" + - externalsRootArray(externals) + - ");\n" - : " var a = factory();\n") + - " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" + - " }\n") + - `})(${ - runtimeTemplate.outputOptions.globalObject - }, function(${externalsArguments(externals)}) {\nreturn `, - "webpack/universalModuleDefinition" - ), - source, - ";\n})" - ); +/** + * @param {Chunk} chunk the chunk + * @returns {number} the number of requests + */ +const getRequests = chunk => { + let requests = 0; + for (const chunkGroup of chunk.groupsIterable) { + requests = Math.max(requests, chunkGroup.chunks.length); } -} - -module.exports = UmdLibraryPlugin; - - -/***/ }), - -/***/ 32597: -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const LogType = Object.freeze({ - error: /** @type {"error"} */ ("error"), // message, c style arguments - warn: /** @type {"warn"} */ ("warn"), // message, c style arguments - info: /** @type {"info"} */ ("info"), // message, c style arguments - log: /** @type {"log"} */ ("log"), // message, c style arguments - debug: /** @type {"debug"} */ ("debug"), // message, c style arguments - - trace: /** @type {"trace"} */ ("trace"), // no arguments - - group: /** @type {"group"} */ ("group"), // [label] - groupCollapsed: /** @type {"groupCollapsed"} */ ("groupCollapsed"), // [label] - groupEnd: /** @type {"groupEnd"} */ ("groupEnd"), // [label] - - profile: /** @type {"profile"} */ ("profile"), // [profileName] - profileEnd: /** @type {"profileEnd"} */ ("profileEnd"), // [profileName] + return requests; +}; - time: /** @type {"time"} */ ("time"), // name, time as [seconds, nanoseconds] +const mapObject = (obj, fn) => { + const newObj = Object.create(null); + for (const key of Object.keys(obj)) { + newObj[key] = fn(obj[key], key); + } + return newObj; +}; - clear: /** @type {"clear"} */ ("clear"), // no arguments - status: /** @type {"status"} */ ("status") // message, arguments -}); +/** + * @template T + * @param {Set} a set + * @param {Set} b other set + * @returns {boolean} true if at least one item of a is in b + */ +const isOverlap = (a, b) => { + for (const item of a) { + if (b.has(item)) return true; + } + return false; +}; -exports.LogType = LogType; +const compareModuleIterables = compareIterables(compareModulesByIdentifier); -/** @typedef {typeof LogType[keyof typeof LogType]} LogTypeEnum */ +/** + * @param {ChunksInfoItem} a item + * @param {ChunksInfoItem} b item + * @returns {number} compare result + */ +const compareEntries = (a, b) => { + // 1. by priority + const diffPriority = a.cacheGroup.priority - b.cacheGroup.priority; + if (diffPriority) return diffPriority; + // 2. by number of chunks + const diffCount = a.chunks.size - b.chunks.size; + if (diffCount) return diffCount; + // 3. by size reduction + const aSizeReduce = totalSize(a.sizes) * (a.chunks.size - 1); + const bSizeReduce = totalSize(b.sizes) * (b.chunks.size - 1); + const diffSizeReduce = aSizeReduce - bSizeReduce; + if (diffSizeReduce) return diffSizeReduce; + // 4. by cache group index + const indexDiff = b.cacheGroupIndex - a.cacheGroupIndex; + if (indexDiff) return indexDiff; + // 5. by number of modules (to be able to compare by identifier) + const modulesA = a.modules; + const modulesB = b.modules; + const diff = modulesA.size - modulesB.size; + if (diff) return diff; + // 6. by module identifiers + modulesA.sort(); + modulesB.sort(); + return compareModuleIterables(modulesA, modulesB); +}; -const LOG_SYMBOL = Symbol("webpack logger raw log method"); -const TIMERS_SYMBOL = Symbol("webpack logger times"); -const TIMERS_AGGREGATES_SYMBOL = Symbol("webpack logger aggregated times"); +const INITIAL_CHUNK_FILTER = chunk => chunk.canBeInitial(); +const ASYNC_CHUNK_FILTER = chunk => !chunk.canBeInitial(); +const ALL_CHUNK_FILTER = chunk => true; -class WebpackLogger { - /** - * @param {function(LogTypeEnum, any[]=): void} log log function - * @param {function(string | function(): string): WebpackLogger} getChildLogger function to create child logger - */ - constructor(log, getChildLogger) { - this[LOG_SYMBOL] = log; - this.getChildLogger = getChildLogger; +/** + * @param {OptimizationSplitChunksSizes} value the sizes + * @param {string[]} defaultSizeTypes the default size types + * @returns {SplitChunksSizes} normalized representation + */ +const normalizeSizes = (value, defaultSizeTypes) => { + if (typeof value === "number") { + /** @type {Record} */ + const o = {}; + for (const sizeType of defaultSizeTypes) o[sizeType] = value; + return o; + } else if (typeof value === "object" && value !== null) { + return { ...value }; + } else { + return {}; } +}; - error(...args) { - this[LOG_SYMBOL](LogType.error, args); +/** + * @param {...SplitChunksSizes} sizes the sizes + * @returns {SplitChunksSizes} the merged sizes + */ +const mergeSizes = (...sizes) => { + /** @type {SplitChunksSizes} */ + let merged = {}; + for (let i = sizes.length - 1; i >= 0; i--) { + merged = Object.assign(merged, sizes[i]); } + return merged; +}; - warn(...args) { - this[LOG_SYMBOL](LogType.warn, args); +/** + * @param {SplitChunksSizes} sizes the sizes + * @returns {boolean} true, if there are sizes > 0 + */ +const hasNonZeroSizes = sizes => { + for (const key of Object.keys(sizes)) { + if (sizes[key] > 0) return true; } + return false; +}; - info(...args) { - this[LOG_SYMBOL](LogType.info, args); +/** + * @param {SplitChunksSizes} a first sizes + * @param {SplitChunksSizes} b second sizes + * @param {CombineSizeFunction} combine a function to combine sizes + * @returns {SplitChunksSizes} the combine sizes + */ +const combineSizes = (a, b, combine) => { + const aKeys = new Set(Object.keys(a)); + const bKeys = new Set(Object.keys(b)); + /** @type {SplitChunksSizes} */ + const result = {}; + for (const key of aKeys) { + if (bKeys.has(key)) { + result[key] = combine(a[key], b[key]); + } else { + result[key] = a[key]; + } } - - log(...args) { - this[LOG_SYMBOL](LogType.log, args); + for (const key of bKeys) { + if (!aKeys.has(key)) { + result[key] = b[key]; + } } + return result; +}; - debug(...args) { - this[LOG_SYMBOL](LogType.debug, args); +/** + * @param {SplitChunksSizes} sizes the sizes + * @param {SplitChunksSizes} minSize the min sizes + * @returns {boolean} true if there are sizes and all existing sizes are at least `minSize` + */ +const checkMinSize = (sizes, minSize) => { + for (const key of Object.keys(minSize)) { + const size = sizes[key]; + if (size === undefined || size === 0) continue; + if (size < minSize[key]) return false; } + return true; +}; - assert(assertion, ...args) { - if (!assertion) { - this[LOG_SYMBOL](LogType.error, args); - } +/** + * @param {SplitChunksSizes} sizes the sizes + * @param {SplitChunksSizes} minSizeReduction the min sizes + * @param {number} chunkCount number of chunks + * @returns {boolean} true if there are sizes and all existing sizes are at least `minSizeReduction` + */ +const checkMinSizeReduction = (sizes, minSizeReduction, chunkCount) => { + for (const key of Object.keys(minSizeReduction)) { + const size = sizes[key]; + if (size === undefined || size === 0) continue; + if (size * chunkCount < minSizeReduction[key]) return false; } + return true; +}; - trace() { - this[LOG_SYMBOL](LogType.trace, ["Trace"]); - } - - clear() { - this[LOG_SYMBOL](LogType.clear); - } - - status(...args) { - this[LOG_SYMBOL](LogType.status, args); - } - - group(...args) { - this[LOG_SYMBOL](LogType.group, args); - } - - groupCollapsed(...args) { - this[LOG_SYMBOL](LogType.groupCollapsed, args); - } - - groupEnd(...args) { - this[LOG_SYMBOL](LogType.groupEnd, args); - } - - profile(label) { - this[LOG_SYMBOL](LogType.profile, [label]); - } - - profileEnd(label) { - this[LOG_SYMBOL](LogType.profileEnd, [label]); - } - - time(label) { - this[TIMERS_SYMBOL] = this[TIMERS_SYMBOL] || new Map(); - this[TIMERS_SYMBOL].set(label, process.hrtime()); - } - - timeLog(label) { - const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); - if (!prev) { - throw new Error(`No such label '${label}' for WebpackLogger.timeLog()`); - } - const time = process.hrtime(prev); - this[LOG_SYMBOL](LogType.time, [label, ...time]); - } - - timeEnd(label) { - const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); - if (!prev) { - throw new Error(`No such label '${label}' for WebpackLogger.timeEnd()`); - } - const time = process.hrtime(prev); - this[TIMERS_SYMBOL].delete(label); - this[LOG_SYMBOL](LogType.time, [label, ...time]); - } - - timeAggregate(label) { - const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); - if (!prev) { - throw new Error( - `No such label '${label}' for WebpackLogger.timeAggregate()` - ); - } - const time = process.hrtime(prev); - this[TIMERS_SYMBOL].delete(label); - this[TIMERS_AGGREGATES_SYMBOL] = - this[TIMERS_AGGREGATES_SYMBOL] || new Map(); - const current = this[TIMERS_AGGREGATES_SYMBOL].get(label); - if (current !== undefined) { - if (time[1] + current[1] > 1e9) { - time[0] += current[0] + 1; - time[1] = time[1] - 1e9 + current[1]; - } else { - time[0] += current[0]; - time[1] += current[1]; - } +/** + * @param {SplitChunksSizes} sizes the sizes + * @param {SplitChunksSizes} minSize the min sizes + * @returns {undefined | string[]} list of size types that are below min size + */ +const getViolatingMinSizes = (sizes, minSize) => { + let list; + for (const key of Object.keys(minSize)) { + const size = sizes[key]; + if (size === undefined || size === 0) continue; + if (size < minSize[key]) { + if (list === undefined) list = [key]; + else list.push(key); } - this[TIMERS_AGGREGATES_SYMBOL].set(label, time); - } - - timeAggregateEnd(label) { - if (this[TIMERS_AGGREGATES_SYMBOL] === undefined) return; - const time = this[TIMERS_AGGREGATES_SYMBOL].get(label); - if (time === undefined) return; - this[TIMERS_AGGREGATES_SYMBOL].delete(label); - this[LOG_SYMBOL](LogType.time, [label, ...time]); } -} - -exports.Logger = WebpackLogger; - - -/***/ }), - -/***/ 54963: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { LogType } = __webpack_require__(32597); - -/** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */ -/** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */ -/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ - -/** @typedef {function(string): boolean} FilterFunction */ + return list; +}; /** - * @typedef {Object} LoggerConsole - * @property {function(): void} clear - * @property {function(): void} trace - * @property {(...args: any[]) => void} info - * @property {(...args: any[]) => void} log - * @property {(...args: any[]) => void} warn - * @property {(...args: any[]) => void} error - * @property {(...args: any[]) => void=} debug - * @property {(...args: any[]) => void=} group - * @property {(...args: any[]) => void=} groupCollapsed - * @property {(...args: any[]) => void=} groupEnd - * @property {(...args: any[]) => void=} status - * @property {(...args: any[]) => void=} profile - * @property {(...args: any[]) => void=} profileEnd - * @property {(...args: any[]) => void=} logTime + * @param {SplitChunksSizes} sizes the sizes + * @returns {number} the total size */ +const totalSize = sizes => { + let size = 0; + for (const key of Object.keys(sizes)) { + size += sizes[key]; + } + return size; +}; /** - * @typedef {Object} LoggerOptions - * @property {false|true|"none"|"error"|"warn"|"info"|"log"|"verbose"} level loglevel - * @property {FilterTypes|boolean} debug filter for debug logging - * @property {LoggerConsole} console the console to log to + * @param {false|string|Function} name the chunk name + * @returns {GetName} a function to get the name of the chunk */ +const normalizeName = name => { + if (typeof name === "string") { + return () => name; + } + if (typeof name === "function") { + return /** @type {GetName} */ (name); + } +}; /** - * @param {FilterItemTypes} item an input item - * @returns {FilterFunction} filter function + * @param {OptimizationSplitChunksCacheGroup["chunks"]} chunks the chunk filter option + * @returns {ChunkFilterFunction} the chunk filter function */ -const filterToFunction = item => { - if (typeof item === "string") { - const regExp = new RegExp( - `[\\\\/]${item.replace( - // eslint-disable-next-line no-useless-escape - /[-[\]{}()*+?.\\^$|]/g, - "\\$&" - )}([\\\\/]|$|!|\\?)` - ); - return ident => regExp.test(ident); +const normalizeChunksFilter = chunks => { + if (chunks === "initial") { + return INITIAL_CHUNK_FILTER; } - if (item && typeof item === "object" && typeof item.test === "function") { - return ident => item.test(ident); + if (chunks === "async") { + return ASYNC_CHUNK_FILTER; } - if (typeof item === "function") { - return item; + if (chunks === "all") { + return ALL_CHUNK_FILTER; } - if (typeof item === "boolean") { - return () => item; + if (typeof chunks === "function") { + return chunks; } }; /** - * @enum {number} - */ -const LogLevel = { - none: 6, - false: 6, - error: 5, - warn: 4, - info: 3, - log: 2, - true: 2, - verbose: 1 -}; - -/** - * @param {LoggerOptions} options options object - * @returns {function(string, LogTypeEnum, any[]): void} logging function + * @param {GetCacheGroups | Record} cacheGroups the cache group options + * @param {string[]} defaultSizeTypes the default size types + * @returns {GetCacheGroups} a function to get the cache groups */ -module.exports = ({ level = "info", debug = false, console }) => { - const debugFilters = - typeof debug === "boolean" - ? [() => debug] - : /** @type {FilterItemTypes[]} */ ([]) - .concat(debug) - .map(filterToFunction); - /** @type {number} */ - const loglevel = LogLevel[`${level}`] || 0; - - /** - * @param {string} name name of the logger - * @param {LogTypeEnum} type type of the log entry - * @param {any[]} args arguments of the log entry - * @returns {void} - */ - const logger = (name, type, args) => { - const labeledArgs = () => { - if (Array.isArray(args)) { - if (args.length > 0 && typeof args[0] === "string") { - return [`[${name}] ${args[0]}`, ...args.slice(1)]; - } else { - return [`[${name}]`, ...args]; - } - } else { - return []; +const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => { + if (typeof cacheGroups === "function") { + return cacheGroups; + } + if (typeof cacheGroups === "object" && cacheGroups !== null) { + /** @type {(function(Module, CacheGroupsContext, CacheGroupSource[]): void)[]} */ + const handlers = []; + for (const key of Object.keys(cacheGroups)) { + const option = cacheGroups[key]; + if (option === false) { + continue; } - }; - const debug = debugFilters.some(f => f(name)); - switch (type) { - case LogType.debug: - if (!debug) return; - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.debug === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.debug(...labeledArgs()); - } else { - console.log(...labeledArgs()); - } - break; - case LogType.log: - if (!debug && loglevel > LogLevel.log) return; - console.log(...labeledArgs()); - break; - case LogType.info: - if (!debug && loglevel > LogLevel.info) return; - console.info(...labeledArgs()); - break; - case LogType.warn: - if (!debug && loglevel > LogLevel.warn) return; - console.warn(...labeledArgs()); - break; - case LogType.error: - if (!debug && loglevel > LogLevel.error) return; - console.error(...labeledArgs()); - break; - case LogType.trace: - if (!debug) return; - console.trace(); - break; - case LogType.groupCollapsed: - if (!debug && loglevel > LogLevel.log) return; - if (!debug && loglevel > LogLevel.verbose) { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.groupCollapsed === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.groupCollapsed(...labeledArgs()); - } else { - console.log(...labeledArgs()); + if (typeof option === "string" || option instanceof RegExp) { + const source = createCacheGroupSource({}, key, defaultSizeTypes); + handlers.push((module, context, results) => { + if (checkTest(option, module, context)) { + results.push(source); } - break; - } - // falls through - case LogType.group: - if (!debug && loglevel > LogLevel.log) return; - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.group === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.group(...labeledArgs()); - } else { - console.log(...labeledArgs()); - } - break; - case LogType.groupEnd: - if (!debug && loglevel > LogLevel.log) return; - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.groupEnd === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.groupEnd(); - } - break; - case LogType.time: { - if (!debug && loglevel > LogLevel.log) return; - const ms = args[1] * 1000 + args[2] / 1000000; - const msg = `[${name}] ${args[0]}: ${ms} ms`; - if (typeof console.logTime === "function") { - console.logTime(msg); - } else { - console.log(msg); - } - break; - } - case LogType.profile: - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.profile === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.profile(...labeledArgs()); - } - break; - case LogType.profileEnd: - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.profileEnd === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.profileEnd(...labeledArgs()); - } - break; - case LogType.clear: - if (!debug && loglevel > LogLevel.log) return; - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.clear === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.clear(); - } - break; - case LogType.status: - if (!debug && loglevel > LogLevel.info) return; - if (typeof console.status === "function") { - if (args.length === 0) { - console.status(); - } else { - console.status(...labeledArgs()); + }); + } else if (typeof option === "function") { + const cache = new WeakMap(); + handlers.push((module, context, results) => { + const result = option(module); + if (result) { + const groups = Array.isArray(result) ? result : [result]; + for (const group of groups) { + const cachedSource = cache.get(group); + if (cachedSource !== undefined) { + results.push(cachedSource); + } else { + const source = createCacheGroupSource( + group, + key, + defaultSizeTypes + ); + cache.set(group, source); + results.push(source); + } + } } - } else { - if (args.length !== 0) { - console.info(...labeledArgs()); + }); + } else { + const source = createCacheGroupSource(option, key, defaultSizeTypes); + handlers.push((module, context, results) => { + if ( + checkTest(option.test, module, context) && + checkModuleType(option.type, module) && + checkModuleLayer(option.layer, module) + ) { + results.push(source); } - } - break; - default: - throw new Error(`Unexpected LogType ${type}`); + }); + } } - }; - return logger; + /** + * @param {Module} module the current module + * @param {CacheGroupsContext} context the current context + * @returns {CacheGroupSource[]} the matching cache groups + */ + const fn = (module, context) => { + /** @type {CacheGroupSource[]} */ + let results = []; + for (const fn of handlers) { + fn(module, context, results); + } + return results; + }; + return fn; + } + return () => null; }; - -/***/ }), - -/***/ 62090: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const arraySum = array => { - let sum = 0; - for (const item of array) sum += item; - return sum; +/** + * @param {undefined|boolean|string|RegExp|Function} test test option + * @param {Module} module the module + * @param {CacheGroupsContext} context context object + * @returns {boolean} true, if the module should be selected + */ +const checkTest = (test, module, context) => { + if (test === undefined) return true; + if (typeof test === "function") { + return test(module, context); + } + if (typeof test === "boolean") return test; + if (typeof test === "string") { + const name = module.nameForCondition(); + return name && name.startsWith(test); + } + if (test instanceof RegExp) { + const name = module.nameForCondition(); + return name && test.test(name); + } + return false; }; /** - * @param {any[]} args items to be truncated - * @param {number} maxLength maximum length of args including spaces between - * @returns {string[]} truncated args + * @param {undefined|string|RegExp|Function} test type option + * @param {Module} module the module + * @returns {boolean} true, if the module should be selected */ -const truncateArgs = (args, maxLength) => { - const lengths = args.map(a => `${a}`.length); - const availableLength = maxLength - lengths.length + 1; - - if (availableLength > 0 && args.length === 1) { - if (availableLength >= args[0].length) { - return args; - } else if (availableLength > 3) { - return ["..." + args[0].slice(-availableLength + 3)]; - } else { - return [args[0].slice(-availableLength)]; - } +const checkModuleType = (test, module) => { + if (test === undefined) return true; + if (typeof test === "function") { + return test(module.type); } - - // Check if there is space for at least 4 chars per arg - if (availableLength < arraySum(lengths.map(i => Math.min(i, 6)))) { - // remove args - if (args.length > 1) - return truncateArgs(args.slice(0, args.length - 1), maxLength); - return []; + if (typeof test === "string") { + const type = module.type; + return test === type; } - - let currentLength = arraySum(lengths); - - // Check if all fits into maxLength - if (currentLength <= availableLength) return args; - - // Try to remove chars from the longest items until it fits - while (currentLength > availableLength) { - const maxLength = Math.max(...lengths); - const shorterItems = lengths.filter(l => l !== maxLength); - const nextToMaxLength = - shorterItems.length > 0 ? Math.max(...shorterItems) : 0; - const maxReduce = maxLength - nextToMaxLength; - let maxItems = lengths.length - shorterItems.length; - let overrun = currentLength - availableLength; - for (let i = 0; i < lengths.length; i++) { - if (lengths[i] === maxLength) { - const reduce = Math.min(Math.floor(overrun / maxItems), maxReduce); - lengths[i] -= reduce; - currentLength -= reduce; - overrun -= reduce; - maxItems--; - } - } + if (test instanceof RegExp) { + const type = module.type; + return test.test(type); } - - // Return args reduced to length in lengths - return args.map((a, i) => { - const str = `${a}`; - const length = lengths[i]; - if (str.length === length) { - return str; - } else if (length > 5) { - return "..." + str.slice(-length + 3); - } else if (length > 0) { - return str.slice(-length); - } else { - return ""; - } - }); + return false; }; -module.exports = truncateArgs; - - -/***/ }), - -/***/ 1313: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const StartupChunkDependenciesPlugin = __webpack_require__(22339); - -/** @typedef {import("../Compiler")} Compiler */ - -class CommonJsChunkLoadingPlugin { - constructor(options) { - options = options || {}; - this._asyncChunkLoading = options.asyncChunkLoading; +/** + * @param {undefined|string|RegExp|Function} test type option + * @param {Module} module the module + * @returns {boolean} true, if the module should be selected + */ +const checkModuleLayer = (test, module) => { + if (test === undefined) return true; + if (typeof test === "function") { + return test(module.layer); + } + if (typeof test === "string") { + const layer = module.layer; + return test === "" ? !layer : layer && layer.startsWith(test); + } + if (test instanceof RegExp) { + const layer = module.layer; + return test.test(layer); } + return false; +}; + +/** + * @param {OptimizationSplitChunksCacheGroup} options the group options + * @param {string} key key of cache group + * @param {string[]} defaultSizeTypes the default size types + * @returns {CacheGroupSource} the normalized cached group + */ +const createCacheGroupSource = (options, key, defaultSizeTypes) => { + const minSize = normalizeSizes(options.minSize, defaultSizeTypes); + const minSizeReduction = normalizeSizes( + options.minSizeReduction, + defaultSizeTypes + ); + const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes); + return { + key, + priority: options.priority, + getName: normalizeName(options.name), + chunksFilter: normalizeChunksFilter(options.chunks), + enforce: options.enforce, + minSize, + minSizeReduction, + minRemainingSize: mergeSizes( + normalizeSizes(options.minRemainingSize, defaultSizeTypes), + minSize + ), + enforceSizeThreshold: normalizeSizes( + options.enforceSizeThreshold, + defaultSizeTypes + ), + maxAsyncSize: mergeSizes( + normalizeSizes(options.maxAsyncSize, defaultSizeTypes), + maxSize + ), + maxInitialSize: mergeSizes( + normalizeSizes(options.maxInitialSize, defaultSizeTypes), + maxSize + ), + minChunks: options.minChunks, + maxAsyncRequests: options.maxAsyncRequests, + maxInitialRequests: options.maxInitialRequests, + filename: options.filename, + idHint: options.idHint, + automaticNameDelimiter: options.automaticNameDelimiter, + reuseExistingChunk: options.reuseExistingChunk, + usedExports: options.usedExports + }; +}; +module.exports = class SplitChunksPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {OptimizationSplitChunksOptions=} options plugin options */ - apply(compiler) { - const ChunkLoadingRuntimeModule = this._asyncChunkLoading - ? __webpack_require__(73369) - : __webpack_require__(94172); - const chunkLoadingValue = this._asyncChunkLoading - ? "async-node" - : "require"; - new StartupChunkDependenciesPlugin({ - chunkLoading: chunkLoadingValue, - asyncChunkLoading: this._asyncChunkLoading - }).apply(compiler); - compiler.hooks.thisCompilation.tap( - "CommonJsChunkLoadingPlugin", - compilation => { - const globalChunkLoading = compilation.outputOptions.chunkLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const chunkLoading = - options && options.chunkLoading !== undefined - ? options.chunkLoading - : globalChunkLoading; - return chunkLoading === chunkLoadingValue; - }; - const onceForChunkSet = new WeakSet(); - const handler = (chunk, set) => { - if (onceForChunkSet.has(chunk)) return; - onceForChunkSet.add(chunk); - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.hasOwnProperty); - compilation.addRuntimeModule( - chunk, - new ChunkLoadingRuntimeModule(set) - ); - }; - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("CommonJsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap("CommonJsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadManifest) - .tap("CommonJsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.baseURI) - .tap("CommonJsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.externalInstallChunk) - .tap("CommonJsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.onChunksLoaded) - .tap("CommonJsChunkLoadingPlugin", handler); - - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.getChunkScriptFilename); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.getChunkUpdateScriptFilename); - set.add(RuntimeGlobals.moduleCache); - set.add(RuntimeGlobals.hmrModuleData); - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadManifest) - .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.getUpdateManifestFilename); - }); - } + constructor(options = {}) { + const defaultSizeTypes = options.defaultSizeTypes || [ + "javascript", + "unknown" + ]; + const fallbackCacheGroup = options.fallbackCacheGroup || {}; + const minSize = normalizeSizes(options.minSize, defaultSizeTypes); + const minSizeReduction = normalizeSizes( + options.minSizeReduction, + defaultSizeTypes ); - } -} - -module.exports = CommonJsChunkLoadingPlugin; - - -/***/ }), - -/***/ 7553: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - + const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes); -const CachedInputFileSystem = __webpack_require__(89429); -const fs = __webpack_require__(90552); -const createConsoleLogger = __webpack_require__(54963); -const NodeWatchFileSystem = __webpack_require__(98810); -const nodeConsole = __webpack_require__(91786); + /** @type {SplitChunksOptions} */ + this.options = { + chunksFilter: normalizeChunksFilter(options.chunks || "all"), + defaultSizeTypes, + minSize, + minSizeReduction, + minRemainingSize: mergeSizes( + normalizeSizes(options.minRemainingSize, defaultSizeTypes), + minSize + ), + enforceSizeThreshold: normalizeSizes( + options.enforceSizeThreshold, + defaultSizeTypes + ), + maxAsyncSize: mergeSizes( + normalizeSizes(options.maxAsyncSize, defaultSizeTypes), + maxSize + ), + maxInitialSize: mergeSizes( + normalizeSizes(options.maxInitialSize, defaultSizeTypes), + maxSize + ), + minChunks: options.minChunks || 1, + maxAsyncRequests: options.maxAsyncRequests || 1, + maxInitialRequests: options.maxInitialRequests || 1, + hidePathInfo: options.hidePathInfo || false, + filename: options.filename || undefined, + getCacheGroups: normalizeCacheGroups( + options.cacheGroups, + defaultSizeTypes + ), + getName: options.name ? normalizeName(options.name) : defaultGetName, + automaticNameDelimiter: options.automaticNameDelimiter, + usedExports: options.usedExports, + fallbackCacheGroup: { + chunksFilter: normalizeChunksFilter( + fallbackCacheGroup.chunks || options.chunks || "all" + ), + minSize: mergeSizes( + normalizeSizes(fallbackCacheGroup.minSize, defaultSizeTypes), + minSize + ), + maxAsyncSize: mergeSizes( + normalizeSizes(fallbackCacheGroup.maxAsyncSize, defaultSizeTypes), + normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes), + normalizeSizes(options.maxAsyncSize, defaultSizeTypes), + normalizeSizes(options.maxSize, defaultSizeTypes) + ), + maxInitialSize: mergeSizes( + normalizeSizes(fallbackCacheGroup.maxInitialSize, defaultSizeTypes), + normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes), + normalizeSizes(options.maxInitialSize, defaultSizeTypes), + normalizeSizes(options.maxSize, defaultSizeTypes) + ), + automaticNameDelimiter: + fallbackCacheGroup.automaticNameDelimiter || + options.automaticNameDelimiter || + "~" + } + }; -/** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */ -/** @typedef {import("../Compiler")} Compiler */ + /** @type {WeakMap} */ + this._cacheGroupCache = new WeakMap(); + } -class NodeEnvironmentPlugin { /** - * @param {Object} options options - * @param {InfrastructureLogging} options.infrastructureLogging infrastructure logging options + * @param {CacheGroupSource} cacheGroupSource source + * @returns {CacheGroup} the cache group (cached) */ - constructor(options) { - this.options = options; + _getCacheGroup(cacheGroupSource) { + const cacheEntry = this._cacheGroupCache.get(cacheGroupSource); + if (cacheEntry !== undefined) return cacheEntry; + const minSize = mergeSizes( + cacheGroupSource.minSize, + cacheGroupSource.enforce ? undefined : this.options.minSize + ); + const minSizeReduction = mergeSizes( + cacheGroupSource.minSizeReduction, + cacheGroupSource.enforce ? undefined : this.options.minSizeReduction + ); + const minRemainingSize = mergeSizes( + cacheGroupSource.minRemainingSize, + cacheGroupSource.enforce ? undefined : this.options.minRemainingSize + ); + const enforceSizeThreshold = mergeSizes( + cacheGroupSource.enforceSizeThreshold, + cacheGroupSource.enforce ? undefined : this.options.enforceSizeThreshold + ); + const cacheGroup = { + key: cacheGroupSource.key, + priority: cacheGroupSource.priority || 0, + chunksFilter: cacheGroupSource.chunksFilter || this.options.chunksFilter, + minSize, + minSizeReduction, + minRemainingSize, + enforceSizeThreshold, + maxAsyncSize: mergeSizes( + cacheGroupSource.maxAsyncSize, + cacheGroupSource.enforce ? undefined : this.options.maxAsyncSize + ), + maxInitialSize: mergeSizes( + cacheGroupSource.maxInitialSize, + cacheGroupSource.enforce ? undefined : this.options.maxInitialSize + ), + minChunks: + cacheGroupSource.minChunks !== undefined + ? cacheGroupSource.minChunks + : cacheGroupSource.enforce + ? 1 + : this.options.minChunks, + maxAsyncRequests: + cacheGroupSource.maxAsyncRequests !== undefined + ? cacheGroupSource.maxAsyncRequests + : cacheGroupSource.enforce + ? Infinity + : this.options.maxAsyncRequests, + maxInitialRequests: + cacheGroupSource.maxInitialRequests !== undefined + ? cacheGroupSource.maxInitialRequests + : cacheGroupSource.enforce + ? Infinity + : this.options.maxInitialRequests, + getName: + cacheGroupSource.getName !== undefined + ? cacheGroupSource.getName + : this.options.getName, + usedExports: + cacheGroupSource.usedExports !== undefined + ? cacheGroupSource.usedExports + : this.options.usedExports, + filename: + cacheGroupSource.filename !== undefined + ? cacheGroupSource.filename + : this.options.filename, + automaticNameDelimiter: + cacheGroupSource.automaticNameDelimiter !== undefined + ? cacheGroupSource.automaticNameDelimiter + : this.options.automaticNameDelimiter, + idHint: + cacheGroupSource.idHint !== undefined + ? cacheGroupSource.idHint + : cacheGroupSource.key, + reuseExistingChunk: cacheGroupSource.reuseExistingChunk || false, + _validateSize: hasNonZeroSizes(minSize), + _validateRemainingSize: hasNonZeroSizes(minRemainingSize), + _minSizeForMaxSize: mergeSizes( + cacheGroupSource.minSize, + this.options.minSize + ), + _conditionalEnforce: hasNonZeroSizes(enforceSizeThreshold) + }; + this._cacheGroupCache.set(cacheGroupSource, cacheGroup); + return cacheGroup; } /** @@ -105299,398 +105750,1231 @@ class NodeEnvironmentPlugin { * @returns {void} */ apply(compiler) { - const { infrastructureLogging } = this.options; - compiler.infrastructureLogger = createConsoleLogger({ - level: infrastructureLogging.level || "info", - debug: infrastructureLogging.debug || false, - console: - infrastructureLogging.console || - nodeConsole({ - colors: infrastructureLogging.colors, - appendOnly: infrastructureLogging.appendOnly, - stream: infrastructureLogging.stream - }) - }); - compiler.inputFileSystem = new CachedInputFileSystem(fs, 60000); - const inputFileSystem = compiler.inputFileSystem; - compiler.outputFileSystem = fs; - compiler.intermediateFileSystem = fs; - compiler.watchFileSystem = new NodeWatchFileSystem( - compiler.inputFileSystem + const cachedMakePathsRelative = makePathsRelative.bindContextCache( + compiler.context, + compiler.root ); - compiler.hooks.beforeRun.tap("NodeEnvironmentPlugin", compiler => { - if (compiler.inputFileSystem === inputFileSystem) { - compiler.fsStartTime = Date.now(); - inputFileSystem.purge(); - } - }); - } -} - -module.exports = NodeEnvironmentPlugin; - - -/***/ }), + compiler.hooks.thisCompilation.tap("SplitChunksPlugin", compilation => { + const logger = compilation.getLogger("webpack.SplitChunksPlugin"); + let alreadyOptimized = false; + compilation.hooks.unseal.tap("SplitChunksPlugin", () => { + alreadyOptimized = false; + }); + compilation.hooks.optimizeChunks.tap( + { + name: "SplitChunksPlugin", + stage: STAGE_ADVANCED + }, + chunks => { + if (alreadyOptimized) return; + alreadyOptimized = true; + logger.time("prepare"); + const chunkGraph = compilation.chunkGraph; + const moduleGraph = compilation.moduleGraph; + // Give each selected chunk an index (to create strings from chunks) + /** @type {Map} */ + const chunkIndexMap = new Map(); + const ZERO = BigInt("0"); + const ONE = BigInt("1"); + const START = ONE << BigInt("31"); + let index = START; + for (const chunk of chunks) { + chunkIndexMap.set( + chunk, + index | BigInt((Math.random() * 0x7fffffff) | 0) + ); + index = index << ONE; + } + /** + * @param {Iterable} chunks list of chunks + * @returns {bigint | Chunk} key of the chunks + */ + const getKey = chunks => { + const iterator = chunks[Symbol.iterator](); + let result = iterator.next(); + if (result.done) return ZERO; + const first = result.value; + result = iterator.next(); + if (result.done) return first; + let key = + chunkIndexMap.get(first) | chunkIndexMap.get(result.value); + while (!(result = iterator.next()).done) { + const raw = chunkIndexMap.get(result.value); + key = key ^ raw; + } + return key; + }; + const keyToString = key => { + if (typeof key === "bigint") return key.toString(16); + return chunkIndexMap.get(key).toString(16); + }; -/***/ 7103: -/***/ (function(module) { + const getChunkSetsInGraph = memoize(() => { + /** @type {Map>} */ + const chunkSetsInGraph = new Map(); + /** @type {Set} */ + const singleChunkSets = new Set(); + for (const module of compilation.modules) { + const chunks = chunkGraph.getModuleChunksIterable(module); + const chunksKey = getKey(chunks); + if (typeof chunksKey === "bigint") { + if (!chunkSetsInGraph.has(chunksKey)) { + chunkSetsInGraph.set(chunksKey, new Set(chunks)); + } + } else { + singleChunkSets.add(chunksKey); + } + } + return { chunkSetsInGraph, singleChunkSets }; + }); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {Module} module the module + * @returns {Iterable} groups of chunks with equal exports + */ + const groupChunksByExports = module => { + const exportsInfo = moduleGraph.getExportsInfo(module); + const groupedByUsedExports = new Map(); + for (const chunk of chunkGraph.getModuleChunksIterable(module)) { + const key = exportsInfo.getUsageKey(chunk.runtime); + const list = groupedByUsedExports.get(key); + if (list !== undefined) { + list.push(chunk); + } else { + groupedByUsedExports.set(key, [chunk]); + } + } + return groupedByUsedExports.values(); + }; + /** @type {Map>} */ + const groupedByExportsMap = new Map(); + const getExportsChunkSetsInGraph = memoize(() => { + /** @type {Map>} */ + const chunkSetsInGraph = new Map(); + /** @type {Set} */ + const singleChunkSets = new Set(); + for (const module of compilation.modules) { + const groupedChunks = Array.from(groupChunksByExports(module)); + groupedByExportsMap.set(module, groupedChunks); + for (const chunks of groupedChunks) { + if (chunks.length === 1) { + singleChunkSets.add(chunks[0]); + } else { + const chunksKey = /** @type {bigint} */ (getKey(chunks)); + if (!chunkSetsInGraph.has(chunksKey)) { + chunkSetsInGraph.set(chunksKey, new Set(chunks)); + } + } + } + } + return { chunkSetsInGraph, singleChunkSets }; + }); -/** @typedef {import("../Compiler")} Compiler */ + // group these set of chunks by count + // to allow to check less sets via isSubset + // (only smaller sets can be subset) + const groupChunkSetsByCount = chunkSets => { + /** @type {Map>>} */ + const chunkSetsByCount = new Map(); + for (const chunksSet of chunkSets) { + const count = chunksSet.size; + let array = chunkSetsByCount.get(count); + if (array === undefined) { + array = []; + chunkSetsByCount.set(count, array); + } + array.push(chunksSet); + } + return chunkSetsByCount; + }; + const getChunkSetsByCount = memoize(() => + groupChunkSetsByCount( + getChunkSetsInGraph().chunkSetsInGraph.values() + ) + ); + const getExportsChunkSetsByCount = memoize(() => + groupChunkSetsByCount( + getExportsChunkSetsInGraph().chunkSetsInGraph.values() + ) + ); -class NodeSourcePlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) {} -} + // Create a list of possible combinations + const createGetCombinations = ( + chunkSets, + singleChunkSets, + chunkSetsByCount + ) => { + /** @type {Map | Chunk)[]>} */ + const combinationsCache = new Map(); -module.exports = NodeSourcePlugin; + return key => { + const cacheEntry = combinationsCache.get(key); + if (cacheEntry !== undefined) return cacheEntry; + if (key instanceof Chunk) { + const result = [key]; + combinationsCache.set(key, result); + return result; + } + const chunksSet = chunkSets.get(key); + /** @type {(Set | Chunk)[]} */ + const array = [chunksSet]; + for (const [count, setArray] of chunkSetsByCount) { + // "equal" is not needed because they would have been merge in the first step + if (count < chunksSet.size) { + for (const set of setArray) { + if (isSubset(chunksSet, set)) { + array.push(set); + } + } + } + } + for (const chunk of singleChunkSets) { + if (chunksSet.has(chunk)) { + array.push(chunk); + } + } + combinationsCache.set(key, array); + return array; + }; + }; + + const getCombinationsFactory = memoize(() => { + const { chunkSetsInGraph, singleChunkSets } = getChunkSetsInGraph(); + return createGetCombinations( + chunkSetsInGraph, + singleChunkSets, + getChunkSetsByCount() + ); + }); + const getCombinations = key => getCombinationsFactory()(key); + + const getExportsCombinationsFactory = memoize(() => { + const { chunkSetsInGraph, singleChunkSets } = + getExportsChunkSetsInGraph(); + return createGetCombinations( + chunkSetsInGraph, + singleChunkSets, + getExportsChunkSetsByCount() + ); + }); + const getExportsCombinations = key => + getExportsCombinationsFactory()(key); + + /** + * @typedef {Object} SelectedChunksResult + * @property {Chunk[]} chunks the list of chunks + * @property {bigint | Chunk} key a key of the list + */ + + /** @type {WeakMap | Chunk, WeakMap>} */ + const selectedChunksCacheByChunksSet = new WeakMap(); + + /** + * get list and key by applying the filter function to the list + * It is cached for performance reasons + * @param {Set | Chunk} chunks list of chunks + * @param {ChunkFilterFunction} chunkFilter filter function for chunks + * @returns {SelectedChunksResult} list and key + */ + const getSelectedChunks = (chunks, chunkFilter) => { + let entry = selectedChunksCacheByChunksSet.get(chunks); + if (entry === undefined) { + entry = new WeakMap(); + selectedChunksCacheByChunksSet.set(chunks, entry); + } + /** @type {SelectedChunksResult} */ + let entry2 = entry.get(chunkFilter); + if (entry2 === undefined) { + /** @type {Chunk[]} */ + const selectedChunks = []; + if (chunks instanceof Chunk) { + if (chunkFilter(chunks)) selectedChunks.push(chunks); + } else { + for (const chunk of chunks) { + if (chunkFilter(chunk)) selectedChunks.push(chunk); + } + } + entry2 = { + chunks: selectedChunks, + key: getKey(selectedChunks) + }; + entry.set(chunkFilter, entry2); + } + return entry2; + }; + + /** @type {Map} */ + const alreadyValidatedParents = new Map(); + /** @type {Set} */ + const alreadyReportedErrors = new Set(); + + // Map a list of chunks to a list of modules + // For the key the chunk "index" is used, the value is a SortableSet of modules + /** @type {Map} */ + const chunksInfoMap = new Map(); + + /** + * @param {CacheGroup} cacheGroup the current cache group + * @param {number} cacheGroupIndex the index of the cache group of ordering + * @param {Chunk[]} selectedChunks chunks selected for this module + * @param {bigint | Chunk} selectedChunksKey a key of selectedChunks + * @param {Module} module the current module + * @returns {void} + */ + const addModuleToChunksInfoMap = ( + cacheGroup, + cacheGroupIndex, + selectedChunks, + selectedChunksKey, + module + ) => { + // Break if minimum number of chunks is not reached + if (selectedChunks.length < cacheGroup.minChunks) return; + // Determine name for split chunk + const name = cacheGroup.getName( + module, + selectedChunks, + cacheGroup.key + ); + // Check if the name is ok + const existingChunk = compilation.namedChunks.get(name); + if (existingChunk) { + const parentValidationKey = `${name}|${ + typeof selectedChunksKey === "bigint" + ? selectedChunksKey + : selectedChunksKey.debugId + }`; + const valid = alreadyValidatedParents.get(parentValidationKey); + if (valid === false) return; + if (valid === undefined) { + // Module can only be moved into the existing chunk if the existing chunk + // is a parent of all selected chunks + let isInAllParents = true; + /** @type {Set} */ + const queue = new Set(); + for (const chunk of selectedChunks) { + for (const group of chunk.groupsIterable) { + queue.add(group); + } + } + for (const group of queue) { + if (existingChunk.isInGroup(group)) continue; + let hasParent = false; + for (const parent of group.parentsIterable) { + hasParent = true; + queue.add(parent); + } + if (!hasParent) { + isInAllParents = false; + } + } + const valid = isInAllParents; + alreadyValidatedParents.set(parentValidationKey, valid); + if (!valid) { + if (!alreadyReportedErrors.has(name)) { + alreadyReportedErrors.add(name); + compilation.errors.push( + new WebpackError( + "SplitChunksPlugin\n" + + `Cache group "${cacheGroup.key}" conflicts with existing chunk.\n` + + `Both have the same name "${name}" and existing chunk is not a parent of the selected modules.\n` + + "Use a different name for the cache group or make sure that the existing chunk is a parent (e. g. via dependOn).\n" + + 'HINT: You can omit "name" to automatically create a name.\n' + + "BREAKING CHANGE: webpack < 5 used to allow to use an entrypoint as splitChunk. " + + "This is no longer allowed when the entrypoint is not a parent of the selected modules.\n" + + "Remove this entrypoint and add modules to cache group's 'test' instead. " + + "If you need modules to be evaluated on startup, add them to the existing entrypoints (make them arrays). " + + "See migration guide of more info." + ) + ); + } + return; + } + } + } + // Create key for maps + // When it has a name we use the name as key + // Otherwise we create the key from chunks and cache group key + // This automatically merges equal names + const key = + cacheGroup.key + + (name + ? ` name:${name}` + : ` chunks:${keyToString(selectedChunksKey)}`); + // Add module to maps + let info = chunksInfoMap.get(key); + if (info === undefined) { + chunksInfoMap.set( + key, + (info = { + modules: new SortableSet( + undefined, + compareModulesByIdentifier + ), + cacheGroup, + cacheGroupIndex, + name, + sizes: {}, + chunks: new Set(), + reuseableChunks: new Set(), + chunksKeys: new Set() + }) + ); + } + const oldSize = info.modules.size; + info.modules.add(module); + if (info.modules.size !== oldSize) { + for (const type of module.getSourceTypes()) { + info.sizes[type] = (info.sizes[type] || 0) + module.size(type); + } + } + const oldChunksKeysSize = info.chunksKeys.size; + info.chunksKeys.add(selectedChunksKey); + if (oldChunksKeysSize !== info.chunksKeys.size) { + for (const chunk of selectedChunks) { + info.chunks.add(chunk); + } + } + }; + + const context = { + moduleGraph, + chunkGraph + }; + + logger.timeEnd("prepare"); + + logger.time("modules"); + + // Walk through all modules + for (const module of compilation.modules) { + // Get cache group + let cacheGroups = this.options.getCacheGroups(module, context); + if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { + continue; + } + + // Prepare some values (usedExports = false) + const getCombs = memoize(() => { + const chunks = chunkGraph.getModuleChunksIterable(module); + const chunksKey = getKey(chunks); + return getCombinations(chunksKey); + }); + + // Prepare some values (usedExports = true) + const getCombsByUsedExports = memoize(() => { + // fill the groupedByExportsMap + getExportsChunkSetsInGraph(); + /** @type {Set | Chunk>} */ + const set = new Set(); + const groupedByUsedExports = groupedByExportsMap.get(module); + for (const chunks of groupedByUsedExports) { + const chunksKey = getKey(chunks); + for (const comb of getExportsCombinations(chunksKey)) + set.add(comb); + } + return set; + }); + + let cacheGroupIndex = 0; + for (const cacheGroupSource of cacheGroups) { + const cacheGroup = this._getCacheGroup(cacheGroupSource); + + const combs = cacheGroup.usedExports + ? getCombsByUsedExports() + : getCombs(); + // For all combination of chunk selection + for (const chunkCombination of combs) { + // Break if minimum number of chunks is not reached + const count = + chunkCombination instanceof Chunk ? 1 : chunkCombination.size; + if (count < cacheGroup.minChunks) continue; + // Select chunks by configuration + const { chunks: selectedChunks, key: selectedChunksKey } = + getSelectedChunks(chunkCombination, cacheGroup.chunksFilter); + + addModuleToChunksInfoMap( + cacheGroup, + cacheGroupIndex, + selectedChunks, + selectedChunksKey, + module + ); + } + cacheGroupIndex++; + } + } + + logger.timeEnd("modules"); + + logger.time("queue"); + + /** + * @param {ChunksInfoItem} info entry + * @param {string[]} sourceTypes source types to be removed + */ + const removeModulesWithSourceType = (info, sourceTypes) => { + for (const module of info.modules) { + const types = module.getSourceTypes(); + if (sourceTypes.some(type => types.has(type))) { + info.modules.delete(module); + for (const type of types) { + info.sizes[type] -= module.size(type); + } + } + } + }; + + /** + * @param {ChunksInfoItem} info entry + * @returns {boolean} true, if entry become empty + */ + const removeMinSizeViolatingModules = info => { + if (!info.cacheGroup._validateSize) return false; + const violatingSizes = getViolatingMinSizes( + info.sizes, + info.cacheGroup.minSize + ); + if (violatingSizes === undefined) return false; + removeModulesWithSourceType(info, violatingSizes); + return info.modules.size === 0; + }; + + // Filter items were size < minSize + for (const [key, info] of chunksInfoMap) { + if (removeMinSizeViolatingModules(info)) { + chunksInfoMap.delete(key); + } else if ( + !checkMinSizeReduction( + info.sizes, + info.cacheGroup.minSizeReduction, + info.chunks.size + ) + ) { + chunksInfoMap.delete(key); + } + } + + /** + * @typedef {Object} MaxSizeQueueItem + * @property {SplitChunksSizes} minSize + * @property {SplitChunksSizes} maxAsyncSize + * @property {SplitChunksSizes} maxInitialSize + * @property {string} automaticNameDelimiter + * @property {string[]} keys + */ + + /** @type {Map} */ + const maxSizeQueueMap = new Map(); + + while (chunksInfoMap.size > 0) { + // Find best matching entry + let bestEntryKey; + let bestEntry; + for (const pair of chunksInfoMap) { + const key = pair[0]; + const info = pair[1]; + if ( + bestEntry === undefined || + compareEntries(bestEntry, info) < 0 + ) { + bestEntry = info; + bestEntryKey = key; + } + } + + const item = bestEntry; + chunksInfoMap.delete(bestEntryKey); + + let chunkName = item.name; + // Variable for the new chunk (lazy created) + /** @type {Chunk} */ + let newChunk; + // When no chunk name, check if we can reuse a chunk instead of creating a new one + let isExistingChunk = false; + let isReusedWithAllModules = false; + if (chunkName) { + const chunkByName = compilation.namedChunks.get(chunkName); + if (chunkByName !== undefined) { + newChunk = chunkByName; + const oldSize = item.chunks.size; + item.chunks.delete(newChunk); + isExistingChunk = item.chunks.size !== oldSize; + } + } else if (item.cacheGroup.reuseExistingChunk) { + outer: for (const chunk of item.chunks) { + if ( + chunkGraph.getNumberOfChunkModules(chunk) !== + item.modules.size + ) { + continue; + } + if ( + item.chunks.size > 1 && + chunkGraph.getNumberOfEntryModules(chunk) > 0 + ) { + continue; + } + for (const module of item.modules) { + if (!chunkGraph.isModuleInChunk(module, chunk)) { + continue outer; + } + } + if (!newChunk || !newChunk.name) { + newChunk = chunk; + } else if ( + chunk.name && + chunk.name.length < newChunk.name.length + ) { + newChunk = chunk; + } else if ( + chunk.name && + chunk.name.length === newChunk.name.length && + chunk.name < newChunk.name + ) { + newChunk = chunk; + } + } + if (newChunk) { + item.chunks.delete(newChunk); + chunkName = undefined; + isExistingChunk = true; + isReusedWithAllModules = true; + } + } + + const enforced = + item.cacheGroup._conditionalEnforce && + checkMinSize(item.sizes, item.cacheGroup.enforceSizeThreshold); + + const usedChunks = new Set(item.chunks); + + // Check if maxRequests condition can be fulfilled + if ( + !enforced && + (Number.isFinite(item.cacheGroup.maxInitialRequests) || + Number.isFinite(item.cacheGroup.maxAsyncRequests)) + ) { + for (const chunk of usedChunks) { + // respect max requests + const maxRequests = chunk.isOnlyInitial() + ? item.cacheGroup.maxInitialRequests + : chunk.canBeInitial() + ? Math.min( + item.cacheGroup.maxInitialRequests, + item.cacheGroup.maxAsyncRequests + ) + : item.cacheGroup.maxAsyncRequests; + if ( + isFinite(maxRequests) && + getRequests(chunk) >= maxRequests + ) { + usedChunks.delete(chunk); + } + } + } + + outer: for (const chunk of usedChunks) { + for (const module of item.modules) { + if (chunkGraph.isModuleInChunk(module, chunk)) continue outer; + } + usedChunks.delete(chunk); + } + + // Were some (invalid) chunks removed from usedChunks? + // => readd all modules to the queue, as things could have been changed + if (usedChunks.size < item.chunks.size) { + if (isExistingChunk) usedChunks.add(newChunk); + if (usedChunks.size >= item.cacheGroup.minChunks) { + const chunksArr = Array.from(usedChunks); + for (const module of item.modules) { + addModuleToChunksInfoMap( + item.cacheGroup, + item.cacheGroupIndex, + chunksArr, + getKey(usedChunks), + module + ); + } + } + continue; + } + + // Validate minRemainingSize constraint when a single chunk is left over + if ( + !enforced && + item.cacheGroup._validateRemainingSize && + usedChunks.size === 1 + ) { + const [chunk] = usedChunks; + let chunkSizes = Object.create(null); + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (!item.modules.has(module)) { + for (const type of module.getSourceTypes()) { + chunkSizes[type] = + (chunkSizes[type] || 0) + module.size(type); + } + } + } + const violatingSizes = getViolatingMinSizes( + chunkSizes, + item.cacheGroup.minRemainingSize + ); + if (violatingSizes !== undefined) { + const oldModulesSize = item.modules.size; + removeModulesWithSourceType(item, violatingSizes); + if ( + item.modules.size > 0 && + item.modules.size !== oldModulesSize + ) { + // queue this item again to be processed again + // without violating modules + chunksInfoMap.set(bestEntryKey, item); + } + continue; + } + } + + // Create the new chunk if not reusing one + if (newChunk === undefined) { + newChunk = compilation.addChunk(chunkName); + } + // Walk through all chunks + for (const chunk of usedChunks) { + // Add graph connections for splitted chunk + chunk.split(newChunk); + } + + // Add a note to the chunk + newChunk.chunkReason = + (newChunk.chunkReason ? newChunk.chunkReason + ", " : "") + + (isReusedWithAllModules + ? "reused as split chunk" + : "split chunk"); + if (item.cacheGroup.key) { + newChunk.chunkReason += ` (cache group: ${item.cacheGroup.key})`; + } + if (chunkName) { + newChunk.chunkReason += ` (name: ${chunkName})`; + } + if (item.cacheGroup.filename) { + newChunk.filenameTemplate = item.cacheGroup.filename; + } + if (item.cacheGroup.idHint) { + newChunk.idNameHints.add(item.cacheGroup.idHint); + } + if (!isReusedWithAllModules) { + // Add all modules to the new chunk + for (const module of item.modules) { + if (!module.chunkCondition(newChunk, compilation)) continue; + // Add module to new chunk + chunkGraph.connectChunkAndModule(newChunk, module); + // Remove module from used chunks + for (const chunk of usedChunks) { + chunkGraph.disconnectChunkAndModule(chunk, module); + } + } + } else { + // Remove all modules from used chunks + for (const module of item.modules) { + for (const chunk of usedChunks) { + chunkGraph.disconnectChunkAndModule(chunk, module); + } + } + } + + if ( + Object.keys(item.cacheGroup.maxAsyncSize).length > 0 || + Object.keys(item.cacheGroup.maxInitialSize).length > 0 + ) { + const oldMaxSizeSettings = maxSizeQueueMap.get(newChunk); + maxSizeQueueMap.set(newChunk, { + minSize: oldMaxSizeSettings + ? combineSizes( + oldMaxSizeSettings.minSize, + item.cacheGroup._minSizeForMaxSize, + Math.max + ) + : item.cacheGroup.minSize, + maxAsyncSize: oldMaxSizeSettings + ? combineSizes( + oldMaxSizeSettings.maxAsyncSize, + item.cacheGroup.maxAsyncSize, + Math.min + ) + : item.cacheGroup.maxAsyncSize, + maxInitialSize: oldMaxSizeSettings + ? combineSizes( + oldMaxSizeSettings.maxInitialSize, + item.cacheGroup.maxInitialSize, + Math.min + ) + : item.cacheGroup.maxInitialSize, + automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter, + keys: oldMaxSizeSettings + ? oldMaxSizeSettings.keys.concat(item.cacheGroup.key) + : [item.cacheGroup.key] + }); + } + + // remove all modules from other entries and update size + for (const [key, info] of chunksInfoMap) { + if (isOverlap(info.chunks, usedChunks)) { + // update modules and total size + // may remove it from the map when < minSize + let updated = false; + for (const module of item.modules) { + if (info.modules.has(module)) { + // remove module + info.modules.delete(module); + // update size + for (const key of module.getSourceTypes()) { + info.sizes[key] -= module.size(key); + } + updated = true; + } + } + if (updated) { + if (info.modules.size === 0) { + chunksInfoMap.delete(key); + continue; + } + if ( + removeMinSizeViolatingModules(info) || + !checkMinSizeReduction( + info.sizes, + info.cacheGroup.minSizeReduction, + info.chunks.size + ) + ) { + chunksInfoMap.delete(key); + continue; + } + } + } + } + } + + logger.timeEnd("queue"); + + logger.time("maxSize"); + + /** @type {Set} */ + const incorrectMinMaxSizeSet = new Set(); + + const { outputOptions } = compilation; + + // Make sure that maxSize is fulfilled + const { fallbackCacheGroup } = this.options; + for (const chunk of Array.from(compilation.chunks)) { + const chunkConfig = maxSizeQueueMap.get(chunk); + const { + minSize, + maxAsyncSize, + maxInitialSize, + automaticNameDelimiter + } = chunkConfig || fallbackCacheGroup; + if (!chunkConfig && !fallbackCacheGroup.chunksFilter(chunk)) + continue; + /** @type {SplitChunksSizes} */ + let maxSize; + if (chunk.isOnlyInitial()) { + maxSize = maxInitialSize; + } else if (chunk.canBeInitial()) { + maxSize = combineSizes(maxAsyncSize, maxInitialSize, Math.min); + } else { + maxSize = maxAsyncSize; + } + if (Object.keys(maxSize).length === 0) { + continue; + } + for (const key of Object.keys(maxSize)) { + const maxSizeValue = maxSize[key]; + const minSizeValue = minSize[key]; + if ( + typeof minSizeValue === "number" && + minSizeValue > maxSizeValue + ) { + const keys = chunkConfig && chunkConfig.keys; + const warningKey = `${ + keys && keys.join() + } ${minSizeValue} ${maxSizeValue}`; + if (!incorrectMinMaxSizeSet.has(warningKey)) { + incorrectMinMaxSizeSet.add(warningKey); + compilation.warnings.push( + new MinMaxSizeWarning(keys, minSizeValue, maxSizeValue) + ); + } + } + } + const results = deterministicGroupingForModules({ + minSize, + maxSize: mapObject(maxSize, (value, key) => { + const minSizeValue = minSize[key]; + return typeof minSizeValue === "number" + ? Math.max(value, minSizeValue) + : value; + }), + items: chunkGraph.getChunkModulesIterable(chunk), + getKey(module) { + const cache = getKeyCache.get(module); + if (cache !== undefined) return cache; + const ident = cachedMakePathsRelative(module.identifier()); + const nameForCondition = + module.nameForCondition && module.nameForCondition(); + const name = nameForCondition + ? cachedMakePathsRelative(nameForCondition) + : ident.replace(/^.*!|\?[^?!]*$/g, ""); + const fullKey = + name + + automaticNameDelimiter + + hashFilename(ident, outputOptions); + const key = requestToId(fullKey); + getKeyCache.set(module, key); + return key; + }, + getSize(module) { + const size = Object.create(null); + for (const key of module.getSourceTypes()) { + size[key] = module.size(key); + } + return size; + } + }); + if (results.length <= 1) { + continue; + } + for (let i = 0; i < results.length; i++) { + const group = results[i]; + const key = this.options.hidePathInfo + ? hashFilename(group.key, outputOptions) + : group.key; + let name = chunk.name + ? chunk.name + automaticNameDelimiter + key + : null; + if (name && name.length > 100) { + name = + name.slice(0, 100) + + automaticNameDelimiter + + hashFilename(name, outputOptions); + } + if (i !== results.length - 1) { + const newPart = compilation.addChunk(name); + chunk.split(newPart); + newPart.chunkReason = chunk.chunkReason; + // Add all modules to the new chunk + for (const module of group.items) { + if (!module.chunkCondition(newPart, compilation)) { + continue; + } + // Add module to new chunk + chunkGraph.connectChunkAndModule(newPart, module); + // Remove module from used chunks + chunkGraph.disconnectChunkAndModule(chunk, module); + } + } else { + // change the chunk to be a part + chunk.name = name; + } + } + } + logger.timeEnd("maxSize"); + } + ); + }); + } +}; /***/ }), -/***/ 17916: +/***/ 52149: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sean Larkin @thelarkinn */ -const ExternalsPlugin = __webpack_require__(6652); - -/** @typedef {import("../Compiler")} Compiler */ - -const builtins = [ - "assert", - "async_hooks", - "buffer", - "child_process", - "cluster", - "console", - "constants", - "crypto", - "dgram", - "diagnostics_channel", - "dns", - "dns/promises", - "domain", - "events", - "fs", - "fs/promises", - "http", - "http2", - "https", - "inspector", - "module", - "net", - "os", - "path", - "path/posix", - "path/win32", - "perf_hooks", - "process", - "punycode", - "querystring", - "readline", - "repl", - "stream", - "stream/promises", - "stream/web", - "string_decoder", - "sys", - "timers", - "timers/promises", - "tls", - "trace_events", - "tty", - "url", - "util", - "v8", - "vm", - "wasi", - "worker_threads", - "zlib", - /^node:/, +const { formatSize } = __webpack_require__(71070); +const WebpackError = __webpack_require__(53799); - // cspell:word pnpapi - // Yarn PnP adds pnpapi as "builtin" - "pnpapi" -]; +/** @typedef {import("./SizeLimitsPlugin").AssetDetails} AssetDetails */ -class NodeTargetPlugin { +module.exports = class AssetsOverSizeLimitWarning extends WebpackError { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {AssetDetails[]} assetsOverSizeLimit the assets + * @param {number} assetLimit the size limit */ - apply(compiler) { - new ExternalsPlugin("node-commonjs", builtins).apply(compiler); - } -} + constructor(assetsOverSizeLimit, assetLimit) { + const assetLists = assetsOverSizeLimit + .map(asset => `\n ${asset.name} (${formatSize(asset.size)})`) + .join(""); -module.exports = NodeTargetPlugin; + super(`asset size limit: The following asset(s) exceed the recommended size limit (${formatSize( + assetLimit + )}). +This can impact web performance. +Assets: ${assetLists}`); + + this.name = "AssetsOverSizeLimitWarning"; + this.assets = assetsOverSizeLimit; + } +}; /***/ }), -/***/ 61052: +/***/ 84229: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sean Larkin @thelarkinn */ -const CommonJsChunkFormatPlugin = __webpack_require__(84508); -const EnableChunkLoadingPlugin = __webpack_require__(61291); - -/** @typedef {import("../Compiler")} Compiler */ +const { formatSize } = __webpack_require__(71070); +const WebpackError = __webpack_require__(53799); -class NodeTemplatePlugin { - constructor(options) { - this._options = options || {}; - } +/** @typedef {import("./SizeLimitsPlugin").EntrypointDetails} EntrypointDetails */ +module.exports = class EntrypointsOverSizeLimitWarning extends WebpackError { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {EntrypointDetails[]} entrypoints the entrypoints + * @param {number} entrypointLimit the size limit */ - apply(compiler) { - const chunkLoading = this._options.asyncChunkLoading - ? "async-node" - : "require"; - compiler.options.output.chunkLoading = chunkLoading; - new CommonJsChunkFormatPlugin().apply(compiler); - new EnableChunkLoadingPlugin(chunkLoading).apply(compiler); - } -} + constructor(entrypoints, entrypointLimit) { + const entrypointList = entrypoints + .map( + entrypoint => + `\n ${entrypoint.name} (${formatSize( + entrypoint.size + )})\n${entrypoint.files.map(asset => ` ${asset}`).join("\n")}` + ) + .join(""); + super(`entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (${formatSize( + entrypointLimit + )}). This can impact web performance. +Entrypoints:${entrypointList}\n`); -module.exports = NodeTemplatePlugin; + this.name = "EntrypointsOverSizeLimitWarning"; + this.entrypoints = entrypoints; + } +}; /***/ }), -/***/ 98810: +/***/ 17791: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sean Larkin @thelarkinn */ -const util = __webpack_require__(73837); -const Watchpack = __webpack_require__(36871); +const WebpackError = __webpack_require__(53799); -/** @typedef {import("../../declarations/WebpackOptions").WatchOptions} WatchOptions */ -/** @typedef {import("../FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ -/** @typedef {import("../util/fs").WatchFileSystem} WatchFileSystem */ -/** @typedef {import("../util/fs").WatchMethod} WatchMethod */ -/** @typedef {import("../util/fs").Watcher} Watcher */ +module.exports = class NoAsyncChunksWarning extends WebpackError { + constructor() { + super( + "webpack performance recommendations: \n" + + "You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\n" + + "For more info visit https://webpack.js.org/guides/code-splitting/" + ); -class NodeWatchFileSystem { - constructor(inputFileSystem) { - this.inputFileSystem = inputFileSystem; - this.watcherOptions = { - aggregateTimeout: 0 - }; - this.watcher = new Watchpack(this.watcherOptions); + this.name = "NoAsyncChunksWarning"; } +}; - /** - * @param {Iterable} files watched files - * @param {Iterable} directories watched directories - * @param {Iterable} missing watched exitance entries - * @param {number} startTime timestamp of start time - * @param {WatchOptions} options options object - * @param {function(Error=, Map, Map, Set, Set): void} callback aggregated callback - * @param {function(string, number): void} callbackUndelayed callback when the first change was detected - * @returns {Watcher} a watcher - */ - watch( - files, - directories, - missing, - startTime, - options, - callback, - callbackUndelayed - ) { - if (!files || typeof files[Symbol.iterator] !== "function") { - throw new Error("Invalid arguments: 'files'"); - } - if (!directories || typeof directories[Symbol.iterator] !== "function") { - throw new Error("Invalid arguments: 'directories'"); - } - if (!missing || typeof missing[Symbol.iterator] !== "function") { - throw new Error("Invalid arguments: 'missing'"); - } - if (typeof callback !== "function") { - throw new Error("Invalid arguments: 'callback'"); - } - if (typeof startTime !== "number" && startTime) { - throw new Error("Invalid arguments: 'startTime'"); - } - if (typeof options !== "object") { - throw new Error("Invalid arguments: 'options'"); - } - if (typeof callbackUndelayed !== "function" && callbackUndelayed) { - throw new Error("Invalid arguments: 'callbackUndelayed'"); - } - const oldWatcher = this.watcher; - this.watcher = new Watchpack(options); - if (callbackUndelayed) { - this.watcher.once("change", callbackUndelayed); - } +/***/ }), - const fetchTimeInfo = () => { - const fileTimeInfoEntries = new Map(); - const contextTimeInfoEntries = new Map(); - if (this.watcher) { - this.watcher.collectTimeInfoEntries( - fileTimeInfoEntries, - contextTimeInfoEntries - ); - } - return { fileTimeInfoEntries, contextTimeInfoEntries }; - }; - this.watcher.once("aggregated", (changes, removals) => { - // pause emitting events (avoids clearing aggregated changes and removals on timeout) - this.watcher.pause(); +/***/ 32557: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (this.inputFileSystem && this.inputFileSystem.purge) { - const fs = this.inputFileSystem; - for (const item of changes) { - fs.purge(item); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ + + + +const { find } = __webpack_require__(93347); +const AssetsOverSizeLimitWarning = __webpack_require__(52149); +const EntrypointsOverSizeLimitWarning = __webpack_require__(84229); +const NoAsyncChunksWarning = __webpack_require__(17791); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../../declarations/WebpackOptions").PerformanceOptions} PerformanceOptions */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Entrypoint")} Entrypoint */ +/** @typedef {import("../WebpackError")} WebpackError */ + +/** + * @typedef {Object} AssetDetails + * @property {string} name + * @property {number} size + */ + +/** + * @typedef {Object} EntrypointDetails + * @property {string} name + * @property {number} size + * @property {string[]} files + */ + +const isOverSizeLimitSet = new WeakSet(); + +const excludeSourceMap = (name, source, info) => !info.development; + +module.exports = class SizeLimitsPlugin { + /** + * @param {PerformanceOptions} options the plugin options + */ + constructor(options) { + this.hints = options.hints; + this.maxAssetSize = options.maxAssetSize; + this.maxEntrypointSize = options.maxEntrypointSize; + this.assetFilter = options.assetFilter; + } + + /** + * @param {ChunkGroup | Source} thing the resource to test + * @returns {boolean} true if over the limit + */ + static isOverSizeLimit(thing) { + return isOverSizeLimitSet.has(thing); + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const entrypointSizeLimit = this.maxEntrypointSize; + const assetSizeLimit = this.maxAssetSize; + const hints = this.hints; + const assetFilter = this.assetFilter || excludeSourceMap; + + compiler.hooks.afterEmit.tap("SizeLimitsPlugin", compilation => { + /** @type {WebpackError[]} */ + const warnings = []; + + /** + * @param {Entrypoint} entrypoint an entrypoint + * @returns {number} the size of the entrypoint + */ + const getEntrypointSize = entrypoint => { + let size = 0; + for (const file of entrypoint.getFiles()) { + const asset = compilation.getAsset(file); + if ( + asset && + assetFilter(asset.name, asset.source, asset.info) && + asset.source + ) { + size += asset.info.size || asset.source.size(); + } } - for (const item of removals) { - fs.purge(item); + return size; + }; + + /** @type {AssetDetails[]} */ + const assetsOverSizeLimit = []; + for (const { name, source, info } of compilation.getAssets()) { + if (!assetFilter(name, source, info) || !source) { + continue; + } + + const size = info.size || source.size(); + if (size > assetSizeLimit) { + assetsOverSizeLimit.push({ + name, + size + }); + isOverSizeLimitSet.add(source); } } - const { fileTimeInfoEntries, contextTimeInfoEntries } = fetchTimeInfo(); - callback( - null, - fileTimeInfoEntries, - contextTimeInfoEntries, - changes, - removals - ); - }); - this.watcher.watch({ files, directories, missing, startTime }); + const fileFilter = name => { + const asset = compilation.getAsset(name); + return asset && assetFilter(asset.name, asset.source, asset.info); + }; - if (oldWatcher) { - oldWatcher.close(); - } - return { - close: () => { - if (this.watcher) { - this.watcher.close(); - this.watcher = null; + /** @type {EntrypointDetails[]} */ + const entrypointsOverLimit = []; + for (const [name, entry] of compilation.entrypoints) { + const size = getEntrypointSize(entry); + + if (size > entrypointSizeLimit) { + entrypointsOverLimit.push({ + name: name, + size: size, + files: entry.getFiles().filter(fileFilter) + }); + isOverSizeLimitSet.add(entry); } - }, - pause: () => { - if (this.watcher) { - this.watcher.pause(); + } + + if (hints) { + // 1. Individual Chunk: Size < 250kb + // 2. Collective Initial Chunks [entrypoint] (Each Set?): Size < 250kb + // 3. No Async Chunks + // if !1, then 2, if !2 return + if (assetsOverSizeLimit.length > 0) { + warnings.push( + new AssetsOverSizeLimitWarning(assetsOverSizeLimit, assetSizeLimit) + ); } - }, - getAggregatedRemovals: util.deprecate( - () => { - const items = this.watcher && this.watcher.aggregatedRemovals; - if (items && this.inputFileSystem && this.inputFileSystem.purge) { - const fs = this.inputFileSystem; - for (const item of items) { - fs.purge(item); - } - } - return items; - }, - "Watcher.getAggregatedRemovals is deprecated in favor of Watcher.getInfo since that's more performant.", - "DEP_WEBPACK_WATCHER_GET_AGGREGATED_REMOVALS" - ), - getAggregatedChanges: util.deprecate( - () => { - const items = this.watcher && this.watcher.aggregatedChanges; - if (items && this.inputFileSystem && this.inputFileSystem.purge) { - const fs = this.inputFileSystem; - for (const item of items) { - fs.purge(item); - } - } - return items; - }, - "Watcher.getAggregatedChanges is deprecated in favor of Watcher.getInfo since that's more performant.", - "DEP_WEBPACK_WATCHER_GET_AGGREGATED_CHANGES" - ), - getFileTimeInfoEntries: util.deprecate( - () => { - return fetchTimeInfo().fileTimeInfoEntries; - }, - "Watcher.getFileTimeInfoEntries is deprecated in favor of Watcher.getInfo since that's more performant.", - "DEP_WEBPACK_WATCHER_FILE_TIME_INFO_ENTRIES" - ), - getContextTimeInfoEntries: util.deprecate( - () => { - return fetchTimeInfo().contextTimeInfoEntries; - }, - "Watcher.getContextTimeInfoEntries is deprecated in favor of Watcher.getInfo since that's more performant.", - "DEP_WEBPACK_WATCHER_CONTEXT_TIME_INFO_ENTRIES" - ), - getInfo: () => { - const removals = this.watcher && this.watcher.aggregatedRemovals; - const changes = this.watcher && this.watcher.aggregatedChanges; - if (this.inputFileSystem && this.inputFileSystem.purge) { - const fs = this.inputFileSystem; - if (removals) { - for (const item of removals) { - fs.purge(item); - } + if (entrypointsOverLimit.length > 0) { + warnings.push( + new EntrypointsOverSizeLimitWarning( + entrypointsOverLimit, + entrypointSizeLimit + ) + ); + } + + if (warnings.length > 0) { + const someAsyncChunk = find( + compilation.chunks, + chunk => !chunk.canBeInitial() + ); + + if (!someAsyncChunk) { + warnings.push(new NoAsyncChunksWarning()); } - if (changes) { - for (const item of changes) { - fs.purge(item); - } + + if (hints === "error") { + compilation.errors.push(...warnings); + } else { + compilation.warnings.push(...warnings); } } - const { fileTimeInfoEntries, contextTimeInfoEntries } = fetchTimeInfo(); - return { - changes, - removals, - fileTimeInfoEntries, - contextTimeInfoEntries - }; } - }; + }); } -} - -module.exports = NodeWatchFileSystem; +}; /***/ }), -/***/ 73369: +/***/ 95175: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -105700,281 +106984,49 @@ module.exports = NodeWatchFileSystem; -const RuntimeGlobals = __webpack_require__(16475); const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); -const { - chunkHasJs, - getChunkFilenameTemplate -} = __webpack_require__(89464); -const { getInitialChunkIds } = __webpack_require__(98124); -const compileBooleanMatcher = __webpack_require__(29404); -const { getUndoPath } = __webpack_require__(82186); +const Template = __webpack_require__(1626); -class ReadFileChunkLoadingRuntimeModule extends RuntimeModule { - constructor(runtimeRequirements) { - super("readFile chunk loading", RuntimeModule.STAGE_ATTACH); - this.runtimeRequirements = runtimeRequirements; +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +class ChunkPrefetchFunctionRuntimeModule extends RuntimeModule { + /** + * @param {string} childType TODO + * @param {string} runtimeFunction TODO + * @param {string} runtimeHandlers TODO + */ + constructor(childType, runtimeFunction, runtimeHandlers) { + super(`chunk ${childType} function`); + this.childType = childType; + this.runtimeFunction = runtimeFunction; + this.runtimeHandlers = runtimeHandlers; } /** * @returns {string} runtime code */ generate() { - const { chunkGraph, chunk } = this; + const { runtimeFunction, runtimeHandlers } = this; const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.ensureChunkHandlers; - const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); - const withExternalInstallChunk = this.runtimeRequirements.has( - RuntimeGlobals.externalInstallChunk - ); - const withOnChunkLoad = this.runtimeRequirements.has( - RuntimeGlobals.onChunksLoaded - ); - const withLoading = this.runtimeRequirements.has( - RuntimeGlobals.ensureChunkHandlers - ); - const withHmr = this.runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const withHmrManifest = this.runtimeRequirements.has( - RuntimeGlobals.hmrDownloadManifest - ); - const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); - const hasJsMatcher = compileBooleanMatcher(conditionMap); - const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); - - const outputName = this.compilation.getPath( - getChunkFilenameTemplate(chunk, this.compilation.outputOptions), - { - chunk, - contentHashType: "javascript" - } - ); - const rootOutputDir = getUndoPath( - outputName, - this.compilation.outputOptions.path, - false - ); - - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_readFileVm` - : undefined; - return Template.asString([ - withBaseURI - ? Template.asString([ - `${RuntimeGlobals.baseURI} = require("url").pathToFileURL(${ - rootOutputDir - ? `__dirname + ${JSON.stringify("/" + rootOutputDir)}` - : "__filename" - });` - ]) - : "// no baseURI", - "", - "// object to store loaded chunks", - '// "0" means "already loaded", Promise means loading', - `var installedChunks = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{`, - Template.indent( - Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join( - ",\n" - ) - ), - "};", - "", - withOnChunkLoad - ? `${ - RuntimeGlobals.onChunksLoaded - }.readFileVm = ${runtimeTemplate.returningFunction( - "installedChunks[chunkId] === 0", - "chunkId" - )};` - : "// no on chunks loaded", - "", - withLoading || withExternalInstallChunk - ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [ - "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", - "for(var moduleId in moreModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, - Template.indent([ - `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` - ]), - "}" - ]), - "}", - `if(runtime) runtime(__webpack_require__);`, - "for(var i = 0; i < chunkIds.length; i++) {", - Template.indent([ - "if(installedChunks[chunkIds[i]]) {", - Template.indent(["installedChunks[chunkIds[i]][0]();"]), - "}", - "installedChunks[chunkIds[i]] = 0;" - ]), - "}", - withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" - ])};` - : "// no chunk install function needed", - "", - withLoading - ? Template.asString([ - "// ReadFile + VM.run chunk loading for javascript", - `${fn}.readFileVm = function(chunkId, promises) {`, - hasJsMatcher !== false - ? Template.indent([ - "", - "var installedChunkData = installedChunks[chunkId];", - 'if(installedChunkData !== 0) { // 0 means "already installed".', - Template.indent([ - '// array of [resolve, reject, promise] means "currently loading"', - "if(installedChunkData) {", - Template.indent(["promises.push(installedChunkData[2]);"]), - "} else {", - Template.indent([ - hasJsMatcher === true - ? "if(true) { // all chunks have JS" - : `if(${hasJsMatcher("chunkId")}) {`, - Template.indent([ - "// load the chunk and return promise to it", - "var promise = new Promise(function(resolve, reject) {", - Template.indent([ - "installedChunkData = installedChunks[chunkId] = [resolve, reject];", - `var filename = require('path').join(__dirname, ${JSON.stringify( - rootOutputDir - )} + ${ - RuntimeGlobals.getChunkScriptFilename - }(chunkId));`, - "require('fs').readFile(filename, 'utf-8', function(err, content) {", - Template.indent([ - "if(err) return reject(err);", - "var chunk = {};", - "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + - "(chunk, require, require('path').dirname(filename), filename);", - "installChunk(chunk);" - ]), - "});" - ]), - "});", - "promises.push(installedChunkData[2] = promise);" - ]), - "} else installedChunks[chunkId] = 0;" - ]), - "}" - ]), - "}" - ]) - : Template.indent(["installedChunks[chunkId] = 0;"]), - "};" - ]) - : "// no chunk loading", - "", - withExternalInstallChunk - ? Template.asString([ - "module.exports = __webpack_require__;", - `${RuntimeGlobals.externalInstallChunk} = installChunk;` - ]) - : "// no external install chunk", - "", - withHmr - ? Template.asString([ - "function loadUpdateChunk(chunkId, updatedModulesList) {", - Template.indent([ - "return new Promise(function(resolve, reject) {", - Template.indent([ - `var filename = require('path').join(__dirname, ${JSON.stringify( - rootOutputDir - )} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`, - "require('fs').readFile(filename, 'utf-8', function(err, content) {", - Template.indent([ - "if(err) return reject(err);", - "var update = {};", - "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + - "(update, require, require('path').dirname(filename), filename);", - "var updatedModules = update.modules;", - "var runtime = update.runtime;", - "for(var moduleId in updatedModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, - Template.indent([ - `currentUpdate[moduleId] = updatedModules[moduleId];`, - "if(updatedModulesList) updatedModulesList.push(moduleId);" - ]), - "}" - ]), - "}", - "if(runtime) currentUpdateRuntime.push(runtime);", - "resolve();" - ]), - "});" - ]), - "});" - ]), - "}", - "", - Template.getFunctionContent( - require('./JavascriptHotModuleReplacement.runtime.js') - ) - .replace(/\$key\$/g, "readFileVm") - .replace(/\$installedChunks\$/g, "installedChunks") - .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") - .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) - .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) - .replace( - /\$ensureChunkHandlers\$/g, - RuntimeGlobals.ensureChunkHandlers - ) - .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) - .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) - .replace( - /\$hmrDownloadUpdateHandlers\$/g, - RuntimeGlobals.hmrDownloadUpdateHandlers - ) - .replace( - /\$hmrInvalidateModuleHandlers\$/g, - RuntimeGlobals.hmrInvalidateModuleHandlers - ) - ]) - : "// no HMR", - "", - withHmrManifest - ? Template.asString([ - `${RuntimeGlobals.hmrDownloadManifest} = function() {`, - Template.indent([ - "return new Promise(function(resolve, reject) {", - Template.indent([ - `var filename = require('path').join(__dirname, ${JSON.stringify( - rootOutputDir - )} + ${RuntimeGlobals.getUpdateManifestFilename}());`, - "require('fs').readFile(filename, 'utf-8', function(err, content) {", - Template.indent([ - "if(err) {", - Template.indent([ - 'if(err.code === "ENOENT") return resolve();', - "return reject(err);" - ]), - "}", - "try { resolve(JSON.parse(content)); }", - "catch(e) { reject(e); }" - ]), - "});" - ]), - "});" - ]), - "}" - ]) - : "// no HMR manifest" + `${runtimeHandlers} = {};`, + `${runtimeFunction} = ${runtimeTemplate.basicFunction("chunkId", [ + // map is shorter than forEach + `Object.keys(${runtimeHandlers}).map(${runtimeTemplate.basicFunction( + "key", + `${runtimeHandlers}[key](chunkId);` + )});` + ])}` ]); } } -module.exports = ReadFileChunkLoadingRuntimeModule; +module.exports = ChunkPrefetchFunctionRuntimeModule; /***/ }), -/***/ 73163: +/***/ 33895: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -105986,211 +107038,215 @@ module.exports = ReadFileChunkLoadingRuntimeModule; const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const AsyncWasmLoadingRuntimeModule = __webpack_require__(5434); +const ChunkPrefetchFunctionRuntimeModule = __webpack_require__(95175); +const ChunkPrefetchStartupRuntimeModule = __webpack_require__(15294); +const ChunkPrefetchTriggerRuntimeModule = __webpack_require__(98441); +const ChunkPreloadTriggerRuntimeModule = __webpack_require__(56236); /** @typedef {import("../Compiler")} Compiler */ -class ReadFileCompileAsyncWasmPlugin { - constructor({ type = "async-node", import: useImport = false } = {}) { - this._type = type; - this._import = useImport; - } +class ChunkPrefetchPreloadPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {Compiler} compiler the compiler * @returns {void} */ apply(compiler) { - compiler.hooks.thisCompilation.tap( - "ReadFileCompileAsyncWasmPlugin", + compiler.hooks.compilation.tap( + "ChunkPrefetchPreloadPlugin", compilation => { - const globalWasmLoading = compilation.outputOptions.wasmLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const wasmLoading = - options && options.wasmLoading !== undefined - ? options.wasmLoading - : globalWasmLoading; - return wasmLoading === this._type; - }; - const generateLoadBinaryCode = this._import - ? path => - Template.asString([ - "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {", - Template.indent([ - `readFile(new URL(${path}, import.meta.url), (err, buffer) => {`, - Template.indent([ - "if (err) return reject(err);", - "", - "// Fake fetch response", - "resolve({", - Template.indent(["arrayBuffer() { return buffer; }"]), - "});" - ]), - "});" - ]), - "}))" - ]) - : path => - Template.asString([ - "new Promise(function (resolve, reject) {", - Template.indent([ - "try {", - Template.indent([ - "var { readFile } = require('fs');", - "var { join } = require('path');", - "", - `readFile(join(__dirname, ${path}), function(err, buffer){`, - Template.indent([ - "if (err) return reject(err);", - "", - "// Fake fetch response", - "resolve({", - Template.indent(["arrayBuffer() { return buffer; }"]), - "});" - ]), - "});" - ]), - "} catch (err) { reject(err); }" - ]), - "})" - ]); + compilation.hooks.additionalChunkRuntimeRequirements.tap( + "ChunkPrefetchPreloadPlugin", + (chunk, set, { chunkGraph }) => { + if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return; + const startupChildChunks = chunk.getChildrenOfTypeInOrder( + chunkGraph, + "prefetchOrder" + ); + if (startupChildChunks) { + set.add(RuntimeGlobals.prefetchChunk); + set.add(RuntimeGlobals.onChunksLoaded); + compilation.addRuntimeModule( + chunk, + new ChunkPrefetchStartupRuntimeModule(startupChildChunks) + ); + } + } + ); + compilation.hooks.additionalTreeRuntimeRequirements.tap( + "ChunkPrefetchPreloadPlugin", + (chunk, set, { chunkGraph }) => { + const chunkMap = chunk.getChildIdsByOrdersMap(chunkGraph, false); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.instantiateWasm) - .tap("ReadFileCompileAsyncWasmPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - const chunkGraph = compilation.chunkGraph; - if ( - !chunkGraph.hasModuleInGraph( + if (chunkMap.prefetch) { + set.add(RuntimeGlobals.prefetchChunk); + compilation.addRuntimeModule( chunk, - m => m.type === "webassembly/async" - ) - ) { - return; + new ChunkPrefetchTriggerRuntimeModule(chunkMap.prefetch) + ); } - set.add(RuntimeGlobals.publicPath); + if (chunkMap.preload) { + set.add(RuntimeGlobals.preloadChunk); + compilation.addRuntimeModule( + chunk, + new ChunkPreloadTriggerRuntimeModule(chunkMap.preload) + ); + } + } + ); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.prefetchChunk) + .tap("ChunkPrefetchPreloadPlugin", (chunk, set) => { compilation.addRuntimeModule( chunk, - new AsyncWasmLoadingRuntimeModule({ - generateLoadBinaryCode, - supportsStreaming: false - }) + new ChunkPrefetchFunctionRuntimeModule( + "prefetch", + RuntimeGlobals.prefetchChunk, + RuntimeGlobals.prefetchChunkHandlers + ) + ); + set.add(RuntimeGlobals.prefetchChunkHandlers); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.preloadChunk) + .tap("ChunkPrefetchPreloadPlugin", (chunk, set) => { + compilation.addRuntimeModule( + chunk, + new ChunkPrefetchFunctionRuntimeModule( + "preload", + RuntimeGlobals.preloadChunk, + RuntimeGlobals.preloadChunkHandlers + ) ); + set.add(RuntimeGlobals.preloadChunkHandlers); }); } ); } } -module.exports = ReadFileCompileAsyncWasmPlugin; +module.exports = ChunkPrefetchPreloadPlugin; /***/ }), -/***/ 98939: +/***/ 15294: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const WasmChunkLoadingRuntimeModule = __webpack_require__(87394); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -// TODO webpack 6 remove +class ChunkPrefetchStartupRuntimeModule extends RuntimeModule { + /** + * @param {{ onChunks: Chunk[], chunks: Set }[]} startupChunks chunk ids to trigger when chunks are loaded + */ + constructor(startupChunks) { + super("startup prefetch", RuntimeModule.STAGE_TRIGGER); + this.startupChunks = startupChunks; + } -class ReadFileCompileWasmPlugin { - constructor(options) { - this.options = options || {}; + /** + * @returns {string} runtime code + */ + generate() { + const { startupChunks, chunk } = this; + const { runtimeTemplate } = this.compilation; + return Template.asString( + startupChunks.map( + ({ onChunks, chunks }) => + `${RuntimeGlobals.onChunksLoaded}(0, ${JSON.stringify( + // This need to include itself to delay execution after this chunk has been fully loaded + onChunks.filter(c => c === chunk).map(c => c.id) + )}, ${runtimeTemplate.basicFunction( + "", + chunks.size < 3 + ? Array.from( + chunks, + c => + `${RuntimeGlobals.prefetchChunk}(${JSON.stringify(c.id)});` + ) + : `${JSON.stringify(Array.from(chunks, c => c.id))}.map(${ + RuntimeGlobals.prefetchChunk + });` + )}, 5);` + ) + ); } +} + +module.exports = ChunkPrefetchStartupRuntimeModule; + + +/***/ }), + +/***/ 98441: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); + +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +class ChunkPrefetchTriggerRuntimeModule extends RuntimeModule { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {Record} chunkMap map from chunk to */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "ReadFileCompileWasmPlugin", - compilation => { - const globalWasmLoading = compilation.outputOptions.wasmLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const wasmLoading = - options && options.wasmLoading !== undefined - ? options.wasmLoading - : globalWasmLoading; - return wasmLoading === "async-node"; - }; - const generateLoadBinaryCode = path => - Template.asString([ - "new Promise(function (resolve, reject) {", - Template.indent([ - "var { readFile } = require('fs');", - "var { join } = require('path');", - "", - "try {", - Template.indent([ - `readFile(join(__dirname, ${path}), function(err, buffer){`, - Template.indent([ - "if (err) return reject(err);", - "", - "// Fake fetch response", - "resolve({", - Template.indent(["arrayBuffer() { return buffer; }"]), - "});" - ]), - "});" - ]), - "} catch (err) { reject(err); }" - ]), - "})" - ]); + constructor(chunkMap) { + super(`chunk prefetch trigger`, RuntimeModule.STAGE_TRIGGER); + this.chunkMap = chunkMap; + } - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("ReadFileCompileWasmPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - const chunkGraph = compilation.chunkGraph; - if ( - !chunkGraph.hasModuleInGraph( - chunk, - m => m.type === "webassembly/sync" - ) - ) { - return; - } - set.add(RuntimeGlobals.moduleCache); - compilation.addRuntimeModule( - chunk, - new WasmChunkLoadingRuntimeModule({ - generateLoadBinaryCode, - supportsStreaming: false, - mangleImports: this.options.mangleImports, - runtimeRequirements: set - }) - ); - }); - } - ); + /** + * @returns {string} runtime code + */ + generate() { + const { chunkMap } = this; + const { runtimeTemplate } = this.compilation; + const body = [ + "var chunks = chunkToChildrenMap[chunkId];", + `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.prefetchChunk});` + ]; + return Template.asString([ + Template.asString([ + `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, + `${ + RuntimeGlobals.ensureChunkHandlers + }.prefetch = ${runtimeTemplate.expressionFunction( + `Promise.all(promises).then(${runtimeTemplate.basicFunction( + "", + body + )})`, + "chunkId, promises" + )};` + ]) + ]); } } -module.exports = ReadFileCompileWasmPlugin; +module.exports = ChunkPrefetchTriggerRuntimeModule; /***/ }), -/***/ 94172: +/***/ 56236: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -106202,227 +107258,94 @@ module.exports = ReadFileCompileWasmPlugin; const RuntimeGlobals = __webpack_require__(16475); const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); -const { - chunkHasJs, - getChunkFilenameTemplate -} = __webpack_require__(89464); -const { getInitialChunkIds } = __webpack_require__(98124); -const compileBooleanMatcher = __webpack_require__(29404); -const { getUndoPath } = __webpack_require__(82186); +const Template = __webpack_require__(1626); -class RequireChunkLoadingRuntimeModule extends RuntimeModule { - constructor(runtimeRequirements) { - super("require chunk loading", RuntimeModule.STAGE_ATTACH); - this.runtimeRequirements = runtimeRequirements; +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +class ChunkPreloadTriggerRuntimeModule extends RuntimeModule { + /** + * @param {Record} chunkMap map from chunk to chunks + */ + constructor(chunkMap) { + super(`chunk preload trigger`, RuntimeModule.STAGE_TRIGGER); + this.chunkMap = chunkMap; } /** * @returns {string} runtime code */ generate() { - const { chunkGraph, chunk } = this; + const { chunkMap } = this; const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.ensureChunkHandlers; - const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); - const withExternalInstallChunk = this.runtimeRequirements.has( - RuntimeGlobals.externalInstallChunk - ); - const withOnChunkLoad = this.runtimeRequirements.has( - RuntimeGlobals.onChunksLoaded - ); - const withLoading = this.runtimeRequirements.has( - RuntimeGlobals.ensureChunkHandlers - ); - const withHmr = this.runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const withHmrManifest = this.runtimeRequirements.has( - RuntimeGlobals.hmrDownloadManifest - ); - const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); - const hasJsMatcher = compileBooleanMatcher(conditionMap); - const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + const body = [ + "var chunks = chunkToChildrenMap[chunkId];", + `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.preloadChunk});` + ]; + return Template.asString([ + Template.asString([ + `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, + `${ + RuntimeGlobals.ensureChunkHandlers + }.preload = ${runtimeTemplate.basicFunction("chunkId", body)};` + ]) + ]); + } +} - const outputName = this.compilation.getPath( - getChunkFilenameTemplate(chunk, this.compilation.outputOptions), - { - chunk, - contentHashType: "javascript" +module.exports = ChunkPreloadTriggerRuntimeModule; + + +/***/ }), + +/***/ 30318: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ + +class BasicEffectRulePlugin { + constructor(ruleProperty, effectType) { + this.ruleProperty = ruleProperty; + this.effectType = effectType || ruleProperty; + } + + /** + * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @returns {void} + */ + apply(ruleSetCompiler) { + ruleSetCompiler.hooks.rule.tap( + "BasicEffectRulePlugin", + (path, rule, unhandledProperties, result, references) => { + if (unhandledProperties.has(this.ruleProperty)) { + unhandledProperties.delete(this.ruleProperty); + + const value = rule[this.ruleProperty]; + + result.effects.push({ + type: this.effectType, + value + }); + } } ); - const rootOutputDir = getUndoPath( - outputName, - this.compilation.outputOptions.path, - true - ); + } +} - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_require` - : undefined; - - return Template.asString([ - withBaseURI - ? Template.asString([ - `${RuntimeGlobals.baseURI} = require("url").pathToFileURL(${ - rootOutputDir !== "./" - ? `__dirname + ${JSON.stringify("/" + rootOutputDir)}` - : "__filename" - });` - ]) - : "// no baseURI", - "", - "// object to store loaded chunks", - '// "1" means "loaded", otherwise not loaded yet', - `var installedChunks = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{`, - Template.indent( - Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 1`).join( - ",\n" - ) - ), - "};", - "", - withOnChunkLoad - ? `${ - RuntimeGlobals.onChunksLoaded - }.require = ${runtimeTemplate.returningFunction( - "installedChunks[chunkId]", - "chunkId" - )};` - : "// no on chunks loaded", - "", - withLoading || withExternalInstallChunk - ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [ - "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", - "for(var moduleId in moreModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, - Template.indent([ - `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` - ]), - "}" - ]), - "}", - `if(runtime) runtime(__webpack_require__);`, - "for(var i = 0; i < chunkIds.length; i++)", - Template.indent("installedChunks[chunkIds[i]] = 1;"), - withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" - ])};` - : "// no chunk install function needed", - "", - withLoading - ? Template.asString([ - "// require() chunk loading for javascript", - `${fn}.require = ${runtimeTemplate.basicFunction( - "chunkId, promises", - hasJsMatcher !== false - ? [ - '// "1" is the signal for "already loaded"', - "if(!installedChunks[chunkId]) {", - Template.indent([ - hasJsMatcher === true - ? "if(true) { // all chunks have JS" - : `if(${hasJsMatcher("chunkId")}) {`, - Template.indent([ - `installChunk(require(${JSON.stringify( - rootOutputDir - )} + ${ - RuntimeGlobals.getChunkScriptFilename - }(chunkId)));` - ]), - "} else installedChunks[chunkId] = 1;", - "" - ]), - "}" - ] - : "installedChunks[chunkId] = 1;" - )};` - ]) - : "// no chunk loading", - "", - withExternalInstallChunk - ? Template.asString([ - "module.exports = __webpack_require__;", - `${RuntimeGlobals.externalInstallChunk} = installChunk;` - ]) - : "// no external install chunk", - "", - withHmr - ? Template.asString([ - "function loadUpdateChunk(chunkId, updatedModulesList) {", - Template.indent([ - `var update = require(${JSON.stringify(rootOutputDir)} + ${ - RuntimeGlobals.getChunkUpdateScriptFilename - }(chunkId));`, - "var updatedModules = update.modules;", - "var runtime = update.runtime;", - "for(var moduleId in updatedModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, - Template.indent([ - `currentUpdate[moduleId] = updatedModules[moduleId];`, - "if(updatedModulesList) updatedModulesList.push(moduleId);" - ]), - "}" - ]), - "}", - "if(runtime) currentUpdateRuntime.push(runtime);" - ]), - "}", - "", - Template.getFunctionContent( - require('./JavascriptHotModuleReplacement.runtime.js') - ) - .replace(/\$key\$/g, "require") - .replace(/\$installedChunks\$/g, "installedChunks") - .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") - .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) - .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) - .replace( - /\$ensureChunkHandlers\$/g, - RuntimeGlobals.ensureChunkHandlers - ) - .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) - .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) - .replace( - /\$hmrDownloadUpdateHandlers\$/g, - RuntimeGlobals.hmrDownloadUpdateHandlers - ) - .replace( - /\$hmrInvalidateModuleHandlers\$/g, - RuntimeGlobals.hmrInvalidateModuleHandlers - ) - ]) - : "// no HMR", - "", - withHmrManifest - ? Template.asString([ - `${RuntimeGlobals.hmrDownloadManifest} = function() {`, - Template.indent([ - "return Promise.resolve().then(function() {", - Template.indent([ - `return require(${JSON.stringify(rootOutputDir)} + ${ - RuntimeGlobals.getUpdateManifestFilename - }());` - ]), - "})['catch'](function(err) { if(err.code !== 'MODULE_NOT_FOUND') throw err; });" - ]), - "}" - ]) - : "// no HMR manifest" - ]); - } -} - -module.exports = RequireChunkLoadingRuntimeModule; +module.exports = BasicEffectRulePlugin; /***/ }), -/***/ 91786: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 94215: +/***/ (function(module) { "use strict"; /* @@ -106432,148 +107355,52 @@ module.exports = RequireChunkLoadingRuntimeModule; -const util = __webpack_require__(73837); -const truncateArgs = __webpack_require__(62090); - -module.exports = ({ colors, appendOnly, stream }) => { - let currentStatusMessage = undefined; - let hasStatusMessage = false; - let currentIndent = ""; - let currentCollapsed = 0; - - const indent = (str, prefix, colorPrefix, colorSuffix) => { - if (str === "") return str; - prefix = currentIndent + prefix; - if (colors) { - return ( - prefix + - colorPrefix + - str.replace(/\n/g, colorSuffix + "\n" + prefix + colorPrefix) + - colorSuffix - ); - } else { - return prefix + str.replace(/\n/g, "\n" + prefix); - } - }; - - const clearStatusMessage = () => { - if (hasStatusMessage) { - stream.write("\x1b[2K\r"); - hasStatusMessage = false; - } - }; - - const writeStatusMessage = () => { - if (!currentStatusMessage) return; - const l = stream.columns; - const args = l - ? truncateArgs(currentStatusMessage, l - 1) - : currentStatusMessage; - const str = args.join(" "); - const coloredStr = `\u001b[1m${str}\u001b[39m\u001b[22m`; - stream.write(`\x1b[2K\r${coloredStr}`); - hasStatusMessage = true; - }; - - const writeColored = (prefix, colorPrefix, colorSuffix) => { - return (...args) => { - if (currentCollapsed > 0) return; - clearStatusMessage(); - const str = indent( - util.format(...args), - prefix, - colorPrefix, - colorSuffix - ); - stream.write(str + "\n"); - writeStatusMessage(); - }; - }; - - const writeGroupMessage = writeColored( - "<-> ", - "\u001b[1m\u001b[36m", - "\u001b[39m\u001b[22m" - ); +/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ +/** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */ - const writeGroupCollapsedMessage = writeColored( - "<+> ", - "\u001b[1m\u001b[36m", - "\u001b[39m\u001b[22m" - ); +class BasicMatcherRulePlugin { + constructor(ruleProperty, dataProperty, invert) { + this.ruleProperty = ruleProperty; + this.dataProperty = dataProperty || ruleProperty; + this.invert = invert || false; + } - return { - log: writeColored(" ", "\u001b[1m", "\u001b[22m"), - debug: writeColored(" ", "", ""), - trace: writeColored(" ", "", ""), - info: writeColored(" ", "\u001b[1m\u001b[32m", "\u001b[39m\u001b[22m"), - warn: writeColored(" ", "\u001b[1m\u001b[33m", "\u001b[39m\u001b[22m"), - error: writeColored(" ", "\u001b[1m\u001b[31m", "\u001b[39m\u001b[22m"), - logTime: writeColored( - " ", - "\u001b[1m\u001b[35m", - "\u001b[39m\u001b[22m" - ), - group: (...args) => { - writeGroupMessage(...args); - if (currentCollapsed > 0) { - currentCollapsed++; - } else { - currentIndent += " "; + /** + * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @returns {void} + */ + apply(ruleSetCompiler) { + ruleSetCompiler.hooks.rule.tap( + "BasicMatcherRulePlugin", + (path, rule, unhandledProperties, result) => { + if (unhandledProperties.has(this.ruleProperty)) { + unhandledProperties.delete(this.ruleProperty); + const value = rule[this.ruleProperty]; + const condition = ruleSetCompiler.compileCondition( + `${path}.${this.ruleProperty}`, + value + ); + const fn = condition.fn; + result.conditions.push({ + property: this.dataProperty, + matchWhenEmpty: this.invert + ? !condition.matchWhenEmpty + : condition.matchWhenEmpty, + fn: this.invert ? v => !fn(v) : fn + }); + } } - }, - groupCollapsed: (...args) => { - writeGroupCollapsedMessage(...args); - currentCollapsed++; - }, - groupEnd: () => { - if (currentCollapsed > 0) currentCollapsed--; - else if (currentIndent.length >= 2) - currentIndent = currentIndent.slice(0, currentIndent.length - 2); - }, - // eslint-disable-next-line node/no-unsupported-features/node-builtins - profile: console.profile && (name => console.profile(name)), - // eslint-disable-next-line node/no-unsupported-features/node-builtins - profileEnd: console.profileEnd && (name => console.profileEnd(name)), - clear: - !appendOnly && - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.clear && - (() => { - clearStatusMessage(); - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.clear(); - writeStatusMessage(); - }), - status: appendOnly - ? writeColored(" ", "", "") - : (name, ...args) => { - args = args.filter(Boolean); - if (name === undefined && args.length === 0) { - clearStatusMessage(); - currentStatusMessage = undefined; - } else if ( - typeof name === "string" && - name.startsWith("[webpack.Progress] ") - ) { - currentStatusMessage = [name.slice(19), ...args]; - writeStatusMessage(); - } else if (name === "[webpack.Progress]") { - currentStatusMessage = [...args]; - writeStatusMessage(); - } else { - currentStatusMessage = [name, ...args]; - writeStatusMessage(); - } - } - }; -}; + ); + } +} + +module.exports = BasicMatcherRulePlugin; /***/ }), -/***/ 64395: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 72021: +/***/ (function(module) { "use strict"; /* @@ -106583,96 +107410,51 @@ module.exports = ({ colors, appendOnly, stream }) => { -const { STAGE_ADVANCED } = __webpack_require__(80057); - -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ +/** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */ -class AggressiveMergingPlugin { - constructor(options) { - if ( - (options !== undefined && typeof options !== "object") || - Array.isArray(options) - ) { - throw new Error( - "Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see https://webpack.js.org/plugins/" - ); - } - this.options = options || {}; +class ObjectMatcherRulePlugin { + constructor(ruleProperty, dataProperty) { + this.ruleProperty = ruleProperty; + this.dataProperty = dataProperty || ruleProperty; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler * @returns {void} */ - apply(compiler) { - const options = this.options; - const minSizeReduce = options.minSizeReduce || 1.5; - - compiler.hooks.thisCompilation.tap( - "AggressiveMergingPlugin", - compilation => { - compilation.hooks.optimizeChunks.tap( - { - name: "AggressiveMergingPlugin", - stage: STAGE_ADVANCED - }, - chunks => { - const chunkGraph = compilation.chunkGraph; - /** @type {{a: Chunk, b: Chunk, improvement: number}[]} */ - let combinations = []; - for (const a of chunks) { - if (a.canBeInitial()) continue; - for (const b of chunks) { - if (b.canBeInitial()) continue; - if (b === a) break; - if (!chunkGraph.canChunksBeIntegrated(a, b)) { - continue; - } - const aSize = chunkGraph.getChunkSize(b, { - chunkOverhead: 0 - }); - const bSize = chunkGraph.getChunkSize(a, { - chunkOverhead: 0 - }); - const abSize = chunkGraph.getIntegratedChunksSize(b, a, { - chunkOverhead: 0 - }); - const improvement = (aSize + bSize) / abSize; - combinations.push({ - a, - b, - improvement - }); - } - } - - combinations.sort((a, b) => { - return b.improvement - a.improvement; + apply(ruleSetCompiler) { + const { ruleProperty, dataProperty } = this; + ruleSetCompiler.hooks.rule.tap( + "ObjectMatcherRulePlugin", + (path, rule, unhandledProperties, result) => { + if (unhandledProperties.has(ruleProperty)) { + unhandledProperties.delete(ruleProperty); + const value = rule[ruleProperty]; + for (const property of Object.keys(value)) { + const nestedDataProperties = property.split("."); + const condition = ruleSetCompiler.compileCondition( + `${path}.${ruleProperty}.${property}`, + value[property] + ); + result.conditions.push({ + property: [dataProperty, ...nestedDataProperties], + matchWhenEmpty: condition.matchWhenEmpty, + fn: condition.fn }); - - const pair = combinations[0]; - - if (!pair) return; - if (pair.improvement < minSizeReduce) return; - - chunkGraph.integrateChunks(pair.b, pair.a); - compilation.chunks.delete(pair.a); - return true; } - ); + } } ); } } -module.exports = AggressiveMergingPlugin; +module.exports = ObjectMatcherRulePlugin; /***/ }), -/***/ 15543: +/***/ 83349: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -106683,333 +107465,383 @@ module.exports = AggressiveMergingPlugin; -const { STAGE_ADVANCED } = __webpack_require__(80057); -const { intersect } = __webpack_require__(93347); -const { - compareModulesByIdentifier, - compareChunks -} = __webpack_require__(29579); -const createSchemaValidation = __webpack_require__(32540); -const identifierUtils = __webpack_require__(82186); +const { SyncHook } = __webpack_require__(6967); -/** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +/** + * @typedef {Object} RuleCondition + * @property {string | string[]} property + * @property {boolean} matchWhenEmpty + * @property {function(string): boolean} fn + */ -const validate = createSchemaValidation( - __webpack_require__(32697), - () => - __webpack_require__(47995), - { - name: "Aggressive Splitting Plugin", - baseDataPath: "options" - } -); +/** + * @typedef {Object} Condition + * @property {boolean} matchWhenEmpty + * @property {function(string): boolean} fn + */ -const moveModuleBetween = (chunkGraph, oldChunk, newChunk) => { - return module => { - chunkGraph.disconnectChunkAndModule(oldChunk, module); - chunkGraph.connectChunkAndModule(newChunk, module); - }; -}; +/** + * @typedef {Object} CompiledRule + * @property {RuleCondition[]} conditions + * @property {(Effect|function(object): Effect[])[]} effects + * @property {CompiledRule[]=} rules + * @property {CompiledRule[]=} oneOf + */ /** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {Chunk} chunk the chunk - * @returns {function(Module): boolean} filter for entry module + * @typedef {Object} Effect + * @property {string} type + * @property {any} value */ -const isNotAEntryModule = (chunkGraph, chunk) => { - return module => { - return !chunkGraph.isEntryModuleInChunk(module, chunk); - }; -}; -/** @type {WeakSet} */ -const recordedChunks = new WeakSet(); +/** + * @typedef {Object} RuleSet + * @property {Map} references map of references in the rule set (may grow over time) + * @property {function(object): Effect[]} exec execute the rule set + */ + +class RuleSetCompiler { + constructor(plugins) { + this.hooks = Object.freeze({ + /** @type {SyncHook<[string, object, Set, CompiledRule, Map]>} */ + rule: new SyncHook([ + "path", + "rule", + "unhandledProperties", + "compiledRule", + "references" + ]) + }); + if (plugins) { + for (const plugin of plugins) { + plugin.apply(this); + } + } + } -class AggressiveSplittingPlugin { /** - * @param {AggressiveSplittingPluginOptions=} options options object + * @param {object[]} ruleSet raw user provided rules + * @returns {RuleSet} compiled RuleSet */ - constructor(options = {}) { - validate(options); + compile(ruleSet) { + const refs = new Map(); + const rules = this.compileRules("ruleSet", ruleSet, refs); - this.options = options; - if (typeof this.options.minSize !== "number") { - this.options.minSize = 30 * 1024; - } - if (typeof this.options.maxSize !== "number") { - this.options.maxSize = 50 * 1024; - } - if (typeof this.options.chunkOverhead !== "number") { - this.options.chunkOverhead = 0; - } - if (typeof this.options.entryChunkMultiplicator !== "number") { - this.options.entryChunkMultiplicator = 1; - } + /** + * @param {object} data data passed in + * @param {CompiledRule} rule the compiled rule + * @param {Effect[]} effects an array where effects are pushed to + * @returns {boolean} true, if the rule has matched + */ + const execRule = (data, rule, effects) => { + for (const condition of rule.conditions) { + const p = condition.property; + if (Array.isArray(p)) { + let current = data; + for (const subProperty of p) { + if ( + current && + typeof current === "object" && + Object.prototype.hasOwnProperty.call(current, subProperty) + ) { + current = current[subProperty]; + } else { + current = undefined; + break; + } + } + if (current !== undefined) { + if (!condition.fn(current)) return false; + continue; + } + } else if (p in data) { + const value = data[p]; + if (value !== undefined) { + if (!condition.fn(value)) return false; + continue; + } + } + if (!condition.matchWhenEmpty) { + return false; + } + } + for (const effect of rule.effects) { + if (typeof effect === "function") { + const returnedEffects = effect(data); + for (const effect of returnedEffects) { + effects.push(effect); + } + } else { + effects.push(effect); + } + } + if (rule.rules) { + for (const childRule of rule.rules) { + execRule(data, childRule, effects); + } + } + if (rule.oneOf) { + for (const childRule of rule.oneOf) { + if (execRule(data, childRule, effects)) { + break; + } + } + } + return true; + }; + + return { + references: refs, + exec: data => { + /** @type {Effect[]} */ + const effects = []; + for (const rule of rules) { + execRule(data, rule, effects); + } + return effects; + } + }; } /** - * @param {Chunk} chunk the chunk to test - * @returns {boolean} true if the chunk was recorded + * @param {string} path current path + * @param {object[]} rules the raw rules provided by user + * @param {Map} refs references + * @returns {CompiledRule[]} rules */ - static wasChunkRecorded(chunk) { - return recordedChunks.has(chunk); + compileRules(path, rules, refs) { + return rules.map((rule, i) => + this.compileRule(`${path}[${i}]`, rule, refs) + ); } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {string} path current path + * @param {object} rule the raw rule provided by user + * @param {Map} refs references + * @returns {CompiledRule} normalized and compiled rule for processing */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "AggressiveSplittingPlugin", - compilation => { - let needAdditionalSeal = false; - let newSplits; - let fromAggressiveSplittingSet; - let chunkSplitDataMap; - compilation.hooks.optimize.tap("AggressiveSplittingPlugin", () => { - newSplits = []; - fromAggressiveSplittingSet = new Set(); - chunkSplitDataMap = new Map(); - }); - compilation.hooks.optimizeChunks.tap( - { - name: "AggressiveSplittingPlugin", - stage: STAGE_ADVANCED - }, - chunks => { - const chunkGraph = compilation.chunkGraph; - // Precompute stuff - const nameToModuleMap = new Map(); - const moduleToNameMap = new Map(); - const makePathsRelative = - identifierUtils.makePathsRelative.bindContextCache( - compiler.context, - compiler.root - ); - for (const m of compilation.modules) { - const name = makePathsRelative(m.identifier()); - nameToModuleMap.set(name, m); - moduleToNameMap.set(m, name); - } - - // Check used chunk ids - const usedIds = new Set(); - for (const chunk of chunks) { - usedIds.add(chunk.id); - } - - const recordedSplits = - (compilation.records && compilation.records.aggressiveSplits) || - []; - const usedSplits = newSplits - ? recordedSplits.concat(newSplits) - : recordedSplits; - - const minSize = this.options.minSize; - const maxSize = this.options.maxSize; - - const applySplit = splitData => { - // Cannot split if id is already taken - if (splitData.id !== undefined && usedIds.has(splitData.id)) { - return false; - } - - // Get module objects from names - const selectedModules = splitData.modules.map(name => - nameToModuleMap.get(name) - ); - - // Does the modules exist at all? - if (!selectedModules.every(Boolean)) return false; - - // Check if size matches (faster than waiting for hash) - let size = 0; - for (const m of selectedModules) size += m.size(); - if (size !== splitData.size) return false; - - // get chunks with all modules - const selectedChunks = intersect( - selectedModules.map( - m => new Set(chunkGraph.getModuleChunksIterable(m)) - ) - ); + compileRule(path, rule, refs) { + const unhandledProperties = new Set( + Object.keys(rule).filter(key => rule[key] !== undefined) + ); - // No relevant chunks found - if (selectedChunks.size === 0) return false; + /** @type {CompiledRule} */ + const compiledRule = { + conditions: [], + effects: [], + rules: undefined, + oneOf: undefined + }; - // The found chunk is already the split or similar - if ( - selectedChunks.size === 1 && - chunkGraph.getNumberOfChunkModules( - Array.from(selectedChunks)[0] - ) === selectedModules.length - ) { - const chunk = Array.from(selectedChunks)[0]; - if (fromAggressiveSplittingSet.has(chunk)) return false; - fromAggressiveSplittingSet.add(chunk); - chunkSplitDataMap.set(chunk, splitData); - return true; - } + this.hooks.rule.call(path, rule, unhandledProperties, compiledRule, refs); - // split the chunk into two parts - const newChunk = compilation.addChunk(); - newChunk.chunkReason = "aggressive splitted"; - for (const chunk of selectedChunks) { - selectedModules.forEach( - moveModuleBetween(chunkGraph, chunk, newChunk) - ); - chunk.split(newChunk); - chunk.name = null; - } - fromAggressiveSplittingSet.add(newChunk); - chunkSplitDataMap.set(newChunk, splitData); + if (unhandledProperties.has("rules")) { + unhandledProperties.delete("rules"); + const rules = rule.rules; + if (!Array.isArray(rules)) + throw this.error(path, rules, "Rule.rules must be an array of rules"); + compiledRule.rules = this.compileRules(`${path}.rules`, rules, refs); + } - if (splitData.id !== null && splitData.id !== undefined) { - newChunk.id = splitData.id; - newChunk.ids = [splitData.id]; - } - return true; - }; + if (unhandledProperties.has("oneOf")) { + unhandledProperties.delete("oneOf"); + const oneOf = rule.oneOf; + if (!Array.isArray(oneOf)) + throw this.error(path, oneOf, "Rule.oneOf must be an array of rules"); + compiledRule.oneOf = this.compileRules(`${path}.oneOf`, oneOf, refs); + } - // try to restore to recorded splitting - let changed = false; - for (let j = 0; j < usedSplits.length; j++) { - const splitData = usedSplits[j]; - if (applySplit(splitData)) changed = true; - } + if (unhandledProperties.size > 0) { + throw this.error( + path, + rule, + `Properties ${Array.from(unhandledProperties).join(", ")} are unknown` + ); + } - // for any chunk which isn't splitted yet, split it and create a new entry - // start with the biggest chunk - const cmpFn = compareChunks(chunkGraph); - const sortedChunks = Array.from(chunks).sort((a, b) => { - const diff1 = - chunkGraph.getChunkModulesSize(b) - - chunkGraph.getChunkModulesSize(a); - if (diff1) return diff1; - const diff2 = - chunkGraph.getNumberOfChunkModules(a) - - chunkGraph.getNumberOfChunkModules(b); - if (diff2) return diff2; - return cmpFn(a, b); - }); - for (const chunk of sortedChunks) { - if (fromAggressiveSplittingSet.has(chunk)) continue; - const size = chunkGraph.getChunkModulesSize(chunk); - if ( - size > maxSize && - chunkGraph.getNumberOfChunkModules(chunk) > 1 - ) { - const modules = chunkGraph - .getOrderedChunkModules(chunk, compareModulesByIdentifier) - .filter(isNotAEntryModule(chunkGraph, chunk)); - const selectedModules = []; - let selectedModulesSize = 0; - for (let k = 0; k < modules.length; k++) { - const module = modules[k]; - const newSize = selectedModulesSize + module.size(); - if (newSize > maxSize && selectedModulesSize >= minSize) { - break; - } - selectedModulesSize = newSize; - selectedModules.push(module); - } - if (selectedModules.length === 0) continue; - const splitData = { - modules: selectedModules - .map(m => moduleToNameMap.get(m)) - .sort(), - size: selectedModulesSize - }; + return compiledRule; + } - if (applySplit(splitData)) { - newSplits = (newSplits || []).concat(splitData); - changed = true; - } - } - } - if (changed) return true; - } + /** + * @param {string} path current path + * @param {any} condition user provided condition value + * @returns {Condition} compiled condition + */ + compileCondition(path, condition) { + if (condition === "") { + return { + matchWhenEmpty: true, + fn: str => str === "" + }; + } + if (!condition) { + throw this.error( + path, + condition, + "Expected condition but got falsy value" + ); + } + if (typeof condition === "string") { + return { + matchWhenEmpty: condition.length === 0, + fn: str => typeof str === "string" && str.startsWith(condition) + }; + } + if (typeof condition === "function") { + try { + return { + matchWhenEmpty: condition(""), + fn: condition + }; + } catch (err) { + throw this.error( + path, + condition, + "Evaluation of condition function threw error" ); - compilation.hooks.recordHash.tap( - "AggressiveSplittingPlugin", - records => { - // 4. save made splittings to records - const allSplits = new Set(); - const invalidSplits = new Set(); + } + } + if (condition instanceof RegExp) { + return { + matchWhenEmpty: condition.test(""), + fn: v => typeof v === "string" && condition.test(v) + }; + } + if (Array.isArray(condition)) { + const items = condition.map((c, i) => + this.compileCondition(`${path}[${i}]`, c) + ); + return this.combineConditionsOr(items); + } - // Check if some splittings are invalid - // We remove invalid splittings and try again - for (const chunk of compilation.chunks) { - const splitData = chunkSplitDataMap.get(chunk); - if (splitData !== undefined) { - if (splitData.hash && chunk.hash !== splitData.hash) { - // Split was successful, but hash doesn't equal - // We can throw away the split since it's useless now - invalidSplits.add(splitData); - } - } - } + if (typeof condition !== "object") { + throw this.error( + path, + condition, + `Unexpected ${typeof condition} when condition was expected` + ); + } - if (invalidSplits.size > 0) { - records.aggressiveSplits = records.aggressiveSplits.filter( - splitData => !invalidSplits.has(splitData) + const conditions = []; + for (const key of Object.keys(condition)) { + const value = condition[key]; + switch (key) { + case "or": + if (value) { + if (!Array.isArray(value)) { + throw this.error( + `${path}.or`, + condition.and, + "Expected array of conditions" ); - needAdditionalSeal = true; - } else { - // set hash and id values on all (new) splittings - for (const chunk of compilation.chunks) { - const splitData = chunkSplitDataMap.get(chunk); - if (splitData !== undefined) { - splitData.hash = chunk.hash; - splitData.id = chunk.id; - allSplits.add(splitData); - // set flag for stats - recordedChunks.add(chunk); - } - } - - // Also add all unused historical splits (after the used ones) - // They can still be used in some future compilation - const recordedSplits = - compilation.records && compilation.records.aggressiveSplits; - if (recordedSplits) { - for (const splitData of recordedSplits) { - if (!invalidSplits.has(splitData)) allSplits.add(splitData); - } - } - - // record all splits - records.aggressiveSplits = Array.from(allSplits); - - needAdditionalSeal = false; } + conditions.push(this.compileCondition(`${path}.or`, value)); } - ); - compilation.hooks.needAdditionalSeal.tap( - "AggressiveSplittingPlugin", - () => { - if (needAdditionalSeal) { - needAdditionalSeal = false; - return true; + break; + case "and": + if (value) { + if (!Array.isArray(value)) { + throw this.error( + `${path}.and`, + condition.and, + "Expected array of conditions" + ); + } + let i = 0; + for (const item of value) { + conditions.push(this.compileCondition(`${path}.and[${i}]`, item)); + i++; } } - ); + break; + case "not": + if (value) { + const matcher = this.compileCondition(`${path}.not`, value); + const fn = matcher.fn; + conditions.push({ + matchWhenEmpty: !matcher.matchWhenEmpty, + fn: v => !fn(v) + }); + } + break; + default: + throw this.error( + `${path}.${key}`, + condition[key], + `Unexpected property ${key} in condition` + ); } - ); + } + if (conditions.length === 0) { + throw this.error( + path, + condition, + "Expected condition, but got empty thing" + ); + } + return this.combineConditionsAnd(conditions); } -} -module.exports = AggressiveSplittingPlugin; + /** + * @param {Condition[]} conditions some conditions + * @returns {Condition} merged condition + */ + combineConditionsOr(conditions) { + if (conditions.length === 0) { + return { + matchWhenEmpty: false, + fn: () => false + }; + } else if (conditions.length === 1) { + return conditions[0]; + } else { + return { + matchWhenEmpty: conditions.some(c => c.matchWhenEmpty), + fn: v => conditions.some(c => c.fn(v)) + }; + } + } -/***/ }), + /** + * @param {Condition[]} conditions some conditions + * @returns {Condition} merged condition + */ + combineConditionsAnd(conditions) { + if (conditions.length === 0) { + return { + matchWhenEmpty: false, + fn: () => false + }; + } else if (conditions.length === 1) { + return conditions[0]; + } else { + return { + matchWhenEmpty: conditions.every(c => c.matchWhenEmpty), + fn: v => conditions.every(c => c.fn(v)) + }; + } + } -/***/ 97198: + /** + * @param {string} path current path + * @param {any} value value at the error location + * @param {string} message message explaining the problem + * @returns {Error} an error object + */ + error(path, value, message) { + return new Error( + `Compiling RuleSet failed: ${message} (at ${path}: ${value})` + ); + } +} + +module.exports = RuleSetCompiler; + + +/***/ }), + +/***/ 84977: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -107020,3398 +107852,2115 @@ module.exports = AggressiveSplittingPlugin; -const eslintScope = __webpack_require__(36007); -const Referencer = __webpack_require__(44585); -const { - CachedSource, - ConcatSource, - ReplaceSource -} = __webpack_require__(51255); -const ConcatenationScope = __webpack_require__(98229); -const { UsageState } = __webpack_require__(63686); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const HarmonyImportDependency = __webpack_require__(57154); -const JavascriptParser = __webpack_require__(29050); -const { equals } = __webpack_require__(84953); -const LazySet = __webpack_require__(38938); -const { concatComparators, keepOriginalOrder } = __webpack_require__(29579); -const createHash = __webpack_require__(49835); -const { makePathsRelative } = __webpack_require__(82186); -const makeSerializable = __webpack_require__(33032); -const propertyAccess = __webpack_require__(54190); -const { - filterRuntime, - intersectRuntime, - mergeRuntimeCondition, - mergeRuntimeConditionNonFalse, - runtimeConditionToString, - subtractRuntimeCondition -} = __webpack_require__(17156); - -/** @typedef {import("eslint-scope").Scope} Scope */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ -/** @template T @typedef {import("../InitFragment")} InitFragment */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {typeof import("../util/Hash")} HashConstructor */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -// fix eslint-scope to support class properties correctly -// cspell:word Referencer -const ReferencerClass = Referencer; -if (!ReferencerClass.prototype.PropertyDefinition) { - ReferencerClass.prototype.PropertyDefinition = - ReferencerClass.prototype.Property; -} - -/** - * @typedef {Object} ReexportInfo - * @property {Module} module - * @property {string[]} export - */ +const util = __webpack_require__(73837); -/** @typedef {RawBinding | SymbolBinding} Binding */ +/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ +/** @typedef {import("./RuleSetCompiler").Effect} Effect */ -/** - * @typedef {Object} RawBinding - * @property {ModuleInfo} info - * @property {string} rawName - * @property {string=} comment - * @property {string[]} ids - * @property {string[]} exportName - */ +class UseEffectRulePlugin { + /** + * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @returns {void} + */ + apply(ruleSetCompiler) { + ruleSetCompiler.hooks.rule.tap( + "UseEffectRulePlugin", + (path, rule, unhandledProperties, result, references) => { + const conflictWith = (property, correctProperty) => { + if (unhandledProperties.has(property)) { + throw ruleSetCompiler.error( + `${path}.${property}`, + rule[property], + `A Rule must not have a '${property}' property when it has a '${correctProperty}' property` + ); + } + }; -/** - * @typedef {Object} SymbolBinding - * @property {ConcatenatedModuleInfo} info - * @property {string} name - * @property {string=} comment - * @property {string[]} ids - * @property {string[]} exportName - */ + if (unhandledProperties.has("use")) { + unhandledProperties.delete("use"); + unhandledProperties.delete("enforce"); -/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo } ModuleInfo */ -/** @typedef {ConcatenatedModuleInfo | ExternalModuleInfo | ReferenceToModuleInfo } ModuleInfoOrReference */ + conflictWith("loader", "use"); + conflictWith("options", "use"); -/** - * @typedef {Object} ConcatenatedModuleInfo - * @property {"concatenated"} type - * @property {Module} module - * @property {number} index - * @property {Object} ast - * @property {Source} internalSource - * @property {ReplaceSource} source - * @property {InitFragment[]=} chunkInitFragments - * @property {Iterable} runtimeRequirements - * @property {Scope} globalScope - * @property {Scope} moduleScope - * @property {Map} internalNames - * @property {Map} exportMap - * @property {Map} rawExportMap - * @property {string=} namespaceExportSymbol - * @property {string} namespaceObjectName - * @property {boolean} interopNamespaceObjectUsed - * @property {string} interopNamespaceObjectName - * @property {boolean} interopNamespaceObject2Used - * @property {string} interopNamespaceObject2Name - * @property {boolean} interopDefaultAccessUsed - * @property {string} interopDefaultAccessName - */ + const use = rule.use; + const enforce = rule.enforce; -/** - * @typedef {Object} ExternalModuleInfo - * @property {"external"} type - * @property {Module} module - * @property {RuntimeSpec | boolean} runtimeCondition - * @property {number} index - * @property {string} name - * @property {boolean} interopNamespaceObjectUsed - * @property {string} interopNamespaceObjectName - * @property {boolean} interopNamespaceObject2Used - * @property {string} interopNamespaceObject2Name - * @property {boolean} interopDefaultAccessUsed - * @property {string} interopDefaultAccessName - */ + const type = enforce ? `use-${enforce}` : "use"; -/** - * @typedef {Object} ReferenceToModuleInfo - * @property {"reference"} type - * @property {RuntimeSpec | boolean} runtimeCondition - * @property {ConcatenatedModuleInfo | ExternalModuleInfo} target - */ + /** + * + * @param {string} path options path + * @param {string} defaultIdent default ident when none is provided + * @param {object} item user provided use value + * @returns {Effect|function(any): Effect[]} effect + */ + const useToEffect = (path, defaultIdent, item) => { + if (typeof item === "function") { + return data => useToEffectsWithoutIdent(path, item(data)); + } else { + return useToEffectRaw(path, defaultIdent, item); + } + }; -const RESERVED_NAMES = new Set( - [ - // internal names (should always be renamed) - ConcatenationScope.DEFAULT_EXPORT, - ConcatenationScope.NAMESPACE_OBJECT_EXPORT, + /** + * + * @param {string} path options path + * @param {string} defaultIdent default ident when none is provided + * @param {object} item user provided use value + * @returns {Effect} effect + */ + const useToEffectRaw = (path, defaultIdent, item) => { + if (typeof item === "string") { + return { + type, + value: { + loader: item, + options: undefined, + ident: undefined + } + }; + } else { + const loader = item.loader; + const options = item.options; + let ident = item.ident; + if (options && typeof options === "object") { + if (!ident) ident = defaultIdent; + references.set(ident, options); + } + if (typeof options === "string") { + util.deprecate( + () => {}, + `Using a string as loader options is deprecated (${path}.options)`, + "DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING" + )(); + } + return { + type: enforce ? `use-${enforce}` : "use", + value: { + loader, + options, + ident + } + }; + } + }; - // keywords - "abstract,arguments,async,await,boolean,break,byte,case,catch,char,class,const,continue", - "debugger,default,delete,do,double,else,enum,eval,export,extends,false,final,finally,float", - "for,function,goto,if,implements,import,in,instanceof,int,interface,let,long,native,new,null", - "package,private,protected,public,return,short,static,super,switch,synchronized,this,throw", - "throws,transient,true,try,typeof,var,void,volatile,while,with,yield", + /** + * @param {string} path options path + * @param {any} items user provided use value + * @returns {Effect[]} effects + */ + const useToEffectsWithoutIdent = (path, items) => { + if (Array.isArray(items)) { + return items.map((item, idx) => + useToEffectRaw(`${path}[${idx}]`, "[[missing ident]]", item) + ); + } + return [useToEffectRaw(path, "[[missing ident]]", items)]; + }; - // commonjs/amd - "module,__dirname,__filename,exports,require,define", + /** + * @param {string} path current path + * @param {any} items user provided use value + * @returns {(Effect|function(any): Effect[])[]} effects + */ + const useToEffects = (path, items) => { + if (Array.isArray(items)) { + return items.map((item, idx) => { + const subPath = `${path}[${idx}]`; + return useToEffect(subPath, subPath, item); + }); + } + return [useToEffect(path, path, items)]; + }; - // js globals - "Array,Date,eval,function,hasOwnProperty,Infinity,isFinite,isNaN,isPrototypeOf,length,Math", - "NaN,name,Number,Object,prototype,String,toString,undefined,valueOf", + if (typeof use === "function") { + result.effects.push(data => + useToEffectsWithoutIdent(`${path}.use`, use(data)) + ); + } else { + for (const effect of useToEffects(`${path}.use`, use)) { + result.effects.push(effect); + } + } + } - // browser globals - "alert,all,anchor,anchors,area,assign,blur,button,checkbox,clearInterval,clearTimeout", - "clientInformation,close,closed,confirm,constructor,crypto,decodeURI,decodeURIComponent", - "defaultStatus,document,element,elements,embed,embeds,encodeURI,encodeURIComponent,escape", - "event,fileUpload,focus,form,forms,frame,innerHeight,innerWidth,layer,layers,link,location", - "mimeTypes,navigate,navigator,frames,frameRate,hidden,history,image,images,offscreenBuffering", - "open,opener,option,outerHeight,outerWidth,packages,pageXOffset,pageYOffset,parent,parseFloat", - "parseInt,password,pkcs11,plugin,prompt,propertyIsEnum,radio,reset,screenX,screenY,scroll", - "secure,select,self,setInterval,setTimeout,status,submit,taint,text,textarea,top,unescape", - "untaint,window", + if (unhandledProperties.has("loader")) { + unhandledProperties.delete("loader"); + unhandledProperties.delete("options"); + unhandledProperties.delete("enforce"); - // window events - "onblur,onclick,onerror,onfocus,onkeydown,onkeypress,onkeyup,onmouseover,onload,onmouseup,onmousedown,onsubmit" - ] - .join(",") - .split(",") -); + const loader = rule.loader; + const options = rule.options; + const enforce = rule.enforce; -const bySourceOrder = (a, b) => { - const aOrder = a.sourceOrder; - const bOrder = b.sourceOrder; - if (isNaN(aOrder)) { - if (!isNaN(bOrder)) { - return 1; - } - } else { - if (isNaN(bOrder)) { - return -1; - } - if (aOrder !== bOrder) { - return aOrder < bOrder ? -1 : 1; - } - } - return 0; -}; + if (loader.includes("!")) { + throw ruleSetCompiler.error( + `${path}.loader`, + loader, + "Exclamation mark separated loader lists has been removed in favor of the 'use' property with arrays" + ); + } -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; -}; + if (loader.includes("?")) { + throw ruleSetCompiler.error( + `${path}.loader`, + loader, + "Query arguments on 'loader' has been removed in favor of the 'options' property" + ); + } -/** - * @typedef {Object} ConcatenationEntry - * @property {"concatenated" | "external"} type - * @property {Module} module - * @property {RuntimeSpec | boolean} runtimeCondition - */ + if (typeof options === "string") { + util.deprecate( + () => {}, + `Using a string as loader options is deprecated (${path}.options)`, + "DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING" + )(); + } -/** - * @param {ModuleGraph} moduleGraph the module graph - * @param {ModuleInfo} info module info - * @param {string[]} exportName exportName - * @param {Map} moduleToInfoMap moduleToInfoMap - * @param {RuntimeSpec} runtime for which runtime - * @param {RequestShortener} requestShortener the request shortener - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {Set} neededNamespaceObjects modules for which a namespace object should be generated - * @param {boolean} asCall asCall - * @param {boolean} strictHarmonyModule strictHarmonyModule - * @param {boolean | undefined} asiSafe asiSafe - * @param {Set} alreadyVisited alreadyVisited - * @returns {Binding} the final variable - */ -const getFinalBinding = ( - moduleGraph, - info, - exportName, - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - asCall, - strictHarmonyModule, - asiSafe, - alreadyVisited = new Set() -) => { - const exportsType = info.module.getExportsType( - moduleGraph, - strictHarmonyModule - ); - if (exportName.length === 0) { - switch (exportsType) { - case "default-only": - info.interopNamespaceObject2Used = true; - return { - info, - rawName: info.interopNamespaceObject2Name, - ids: exportName, - exportName - }; - case "default-with-named": - info.interopNamespaceObjectUsed = true; - return { - info, - rawName: info.interopNamespaceObjectName, - ids: exportName, - exportName - }; - case "namespace": - case "dynamic": - break; - default: - throw new Error(`Unexpected exportsType ${exportsType}`); - } - } else { - switch (exportsType) { - case "namespace": - break; - case "default-with-named": - switch (exportName[0]) { - case "default": - exportName = exportName.slice(1); - break; - case "__esModule": - return { - info, - rawName: "/* __esModule */true", - ids: exportName.slice(1), - exportName - }; - } - break; - case "default-only": { - const exportId = exportName[0]; - if (exportId === "__esModule") { - return { - info, - rawName: "/* __esModule */true", - ids: exportName.slice(1), - exportName - }; - } - exportName = exportName.slice(1); - if (exportId !== "default") { - return { - info, - rawName: - "/* non-default import from default-exporting module */undefined", - ids: exportName, - exportName - }; + const ident = + options && typeof options === "object" ? path : undefined; + references.set(ident, options); + result.effects.push({ + type: enforce ? `use-${enforce}` : "use", + value: { + loader, + options, + ident + } + }); } - break; } - case "dynamic": - switch (exportName[0]) { - case "default": { - exportName = exportName.slice(1); - info.interopDefaultAccessUsed = true; - const defaultExport = asCall - ? `${info.interopDefaultAccessName}()` - : asiSafe - ? `(${info.interopDefaultAccessName}())` - : asiSafe === false - ? `;(${info.interopDefaultAccessName}())` - : `${info.interopDefaultAccessName}.a`; - return { - info, - rawName: defaultExport, - ids: exportName, - exportName - }; - } - case "__esModule": - return { - info, - rawName: "/* __esModule */true", - ids: exportName.slice(1), - exportName - }; - } - break; - default: - throw new Error(`Unexpected exportsType ${exportsType}`); - } - } - if (exportName.length === 0) { - switch (info.type) { - case "concatenated": - neededNamespaceObjects.add(info); - return { - info, - rawName: info.namespaceObjectName, - ids: exportName, - exportName - }; - case "external": - return { info, rawName: info.name, ids: exportName, exportName }; - } - } - const exportsInfo = moduleGraph.getExportsInfo(info.module); - const exportInfo = exportsInfo.getExportInfo(exportName[0]); - if (alreadyVisited.has(exportInfo)) { - return { - info, - rawName: "/* circular reexport */ Object(function x() { x() }())", - ids: [], - exportName - }; + ); } - alreadyVisited.add(exportInfo); - switch (info.type) { - case "concatenated": { - const exportId = exportName[0]; - if (exportInfo.provided === false) { - // It's not provided, but it could be on the prototype - neededNamespaceObjects.add(info); - return { - info, - rawName: info.namespaceObjectName, - ids: exportName, - exportName - }; - } - const directExport = info.exportMap && info.exportMap.get(exportId); - if (directExport) { - const usedName = /** @type {string[]} */ ( - exportsInfo.getUsedName(exportName, runtime) - ); - if (!usedName) { - return { - info, - rawName: "/* unused export */ undefined", - ids: exportName.slice(1), - exportName - }; - } - return { - info, - name: directExport, - ids: usedName.slice(1), - exportName - }; - } - const rawExport = info.rawExportMap && info.rawExportMap.get(exportId); - if (rawExport) { - return { - info, - rawName: rawExport, - ids: exportName.slice(1), - exportName - }; - } - const reexport = exportInfo.findTarget(moduleGraph, module => - moduleToInfoMap.has(module) - ); - if (reexport === false) { - throw new Error( - `Target module of reexport from '${info.module.readableIdentifier( - requestShortener - )}' is not part of the concatenation (export '${exportId}')\nModules in the concatenation:\n${Array.from( - moduleToInfoMap, - ([m, info]) => - ` * ${info.type} ${m.readableIdentifier(requestShortener)}` - ).join("\n")}` - ); - } - if (reexport) { - const refInfo = moduleToInfoMap.get(reexport.module); - return getFinalBinding( - moduleGraph, - refInfo, - reexport.export - ? [...reexport.export, ...exportName.slice(1)] - : exportName.slice(1), - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - asCall, - info.module.buildMeta.strictHarmonyModule, - asiSafe, - alreadyVisited - ); - } - if (info.namespaceExportSymbol) { - const usedName = /** @type {string[]} */ ( - exportsInfo.getUsedName(exportName, runtime) - ); - return { - info, - rawName: info.namespaceObjectName, - ids: usedName, - exportName - }; - } - throw new Error( - `Cannot get final name for export '${exportName.join( - "." - )}' of ${info.module.readableIdentifier(requestShortener)}` - ); - } - case "external": { - const used = /** @type {string[]} */ ( - exportsInfo.getUsedName(exportName, runtime) - ); - if (!used) { - return { - info, - rawName: "/* unused export */ undefined", - ids: exportName.slice(1), - exportName - }; - } - const comment = equals(used, exportName) - ? "" - : Template.toNormalComment(`${exportName.join(".")}`); - return { info, rawName: info.name + comment, ids: used, exportName }; - } - } -}; + useItemToEffects(path, item) {} +} -/** - * @param {ModuleGraph} moduleGraph the module graph - * @param {ModuleInfo} info module info - * @param {string[]} exportName exportName - * @param {Map} moduleToInfoMap moduleToInfoMap - * @param {RuntimeSpec} runtime for which runtime - * @param {RequestShortener} requestShortener the request shortener - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {Set} neededNamespaceObjects modules for which a namespace object should be generated - * @param {boolean} asCall asCall - * @param {boolean} callContext callContext - * @param {boolean} strictHarmonyModule strictHarmonyModule - * @param {boolean | undefined} asiSafe asiSafe - * @returns {string} the final name - */ -const getFinalName = ( - moduleGraph, - info, - exportName, - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - asCall, - callContext, - strictHarmonyModule, - asiSafe -) => { - const binding = getFinalBinding( - moduleGraph, - info, - exportName, - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - asCall, - strictHarmonyModule, - asiSafe - ); - { - const { ids, comment } = binding; - let reference; - let isPropertyAccess; - if ("rawName" in binding) { - reference = `${binding.rawName}${comment || ""}${propertyAccess(ids)}`; - isPropertyAccess = ids.length > 0; - } else { - const { info, name: exportId } = binding; - const name = info.internalNames.get(exportId); - if (!name) { - throw new Error( - `The export "${exportId}" in "${info.module.readableIdentifier( - requestShortener - )}" has no internal name (existing names: ${ - Array.from( - info.internalNames, - ([name, symbol]) => `${name}: ${symbol}` - ).join(", ") || "none" - })` - ); - } - reference = `${name}${comment || ""}${propertyAccess(ids)}`; - isPropertyAccess = ids.length > 1; - } - if (isPropertyAccess && asCall && callContext === false) { - return asiSafe - ? `(0,${reference})` - : asiSafe === false - ? `;(0,${reference})` - : `/*#__PURE__*/Object(${reference})`; - } - return reference; - } -}; +module.exports = UseEffectRulePlugin; -const addScopeSymbols = (s, nameSet, scopeSet1, scopeSet2) => { - let scope = s; - while (scope) { - if (scopeSet1.has(scope)) break; - if (scopeSet2.has(scope)) break; - scopeSet1.add(scope); - for (const variable of scope.variables) { - nameSet.add(variable.name); - } - scope = scope.upper; - } -}; -const getAllReferences = variable => { - let set = variable.references; - // Look for inner scope variables too (like in class Foo { t() { Foo } }) - const identifiers = new Set(variable.identifiers); - for (const scope of variable.scope.childScopes) { - for (const innerVar of scope.variables) { - if (innerVar.identifiers.some(id => identifiers.has(id))) { - set = set.concat(innerVar.references); - break; - } - } - } - return set; -}; +/***/ }), -const getPathInAst = (ast, node) => { - if (ast === node) { - return []; - } +/***/ 63672: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const nr = node.range; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - const enterNode = n => { - if (!n) return undefined; - const r = n.range; - if (r) { - if (r[0] <= nr[0] && r[1] >= nr[1]) { - const path = getPathInAst(n, node); - if (path) { - path.push(n); - return path; - } - } - } - return undefined; - }; - if (Array.isArray(ast)) { - for (let i = 0; i < ast.length; i++) { - const enterResult = enterNode(ast[i]); - if (enterResult !== undefined) return enterResult; - } - } else if (ast && typeof ast === "object") { - const keys = Object.keys(ast); - for (let i = 0; i < keys.length; i++) { - const value = ast[keys[i]]; - if (Array.isArray(value)) { - const pathResult = getPathInAst(value, node); - if (pathResult !== undefined) return pathResult; - } else if (value && typeof value === "object") { - const enterResult = enterNode(value); - if (enterResult !== undefined) return enterResult; - } - } - } -}; -const TYPES = new Set(["javascript"]); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const HelperRuntimeModule = __webpack_require__(82444); -class ConcatenatedModule extends Module { - /** - * @param {Module} rootModule the root module of the concatenation - * @param {Set} modules all modules in the concatenation (including the root module) - * @param {RuntimeSpec} runtime the runtime - * @param {Object=} associatedObjectForCache object for caching - * @param {string | HashConstructor=} hashFunction hash function to use - * @returns {ConcatenatedModule} the module - */ - static create( - rootModule, - modules, - runtime, - associatedObjectForCache, - hashFunction = "md4" - ) { - const identifier = ConcatenatedModule._createIdentifier( - rootModule, - modules, - associatedObjectForCache, - hashFunction - ); - return new ConcatenatedModule({ - identifier, - rootModule, - modules, - runtime - }); +class AsyncModuleRuntimeModule extends HelperRuntimeModule { + constructor() { + super("async module"); } /** - * @param {Object} options options - * @param {string} options.identifier the identifier of the module - * @param {Module=} options.rootModule the root module of the concatenation - * @param {RuntimeSpec} options.runtime the selected runtime - * @param {Set=} options.modules all concatenated modules + * @returns {string} runtime code */ - constructor({ identifier, rootModule, modules, runtime }) { - super("javascript/esm", null, rootModule && rootModule.layer); - - // Info from Factory - /** @type {string} */ - this._identifier = identifier; - /** @type {Module} */ - this.rootModule = rootModule; - /** @type {Set} */ - this._modules = modules; - this._runtime = runtime; - this.factoryMeta = rootModule && rootModule.factoryMeta; + generate() { + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.asyncModule; + return Template.asString([ + 'var webpackThen = typeof Symbol === "function" ? Symbol("webpack then") : "__webpack_then__";', + 'var webpackExports = typeof Symbol === "function" ? Symbol("webpack exports") : "__webpack_exports__";', + `var completeQueue = ${runtimeTemplate.basicFunction("queue", [ + "if(queue) {", + Template.indent([ + `queue.forEach(${runtimeTemplate.expressionFunction( + "fn.r--", + "fn" + )});`, + `queue.forEach(${runtimeTemplate.expressionFunction( + "fn.r-- ? fn.r++ : fn()", + "fn" + )});` + ]), + "}" + ])}`, + `var completeFunction = ${runtimeTemplate.expressionFunction( + "!--fn.r && fn()", + "fn" + )};`, + `var queueFunction = ${runtimeTemplate.expressionFunction( + "queue ? queue.push(fn) : completeFunction(fn)", + "queue, fn" + )};`, + `var wrapDeps = ${runtimeTemplate.returningFunction( + `deps.map(${runtimeTemplate.basicFunction("dep", [ + 'if(dep !== null && typeof dep === "object") {', + Template.indent([ + "if(dep[webpackThen]) return dep;", + "if(dep.then) {", + Template.indent([ + "var queue = [];", + `dep.then(${runtimeTemplate.basicFunction("r", [ + "obj[webpackExports] = r;", + "completeQueue(queue);", + "queue = 0;" + ])});`, + `var obj = {}; + obj[webpackThen] = ${runtimeTemplate.expressionFunction( + "queueFunction(queue, fn), dep['catch'](reject)", + "fn, reject" + )};`, + "return obj;" + ]), + "}" + ]), + "}", + `var ret = {}; + ret[webpackThen] = ${runtimeTemplate.expressionFunction( + "completeFunction(fn)", + "fn" + )}; + ret[webpackExports] = dep; + return ret;` + ])})`, + "deps" + )};`, + `${fn} = ${runtimeTemplate.basicFunction("module, body, hasAwait", [ + "var queue = hasAwait && [];", + "var exports = module.exports;", + "var currentDeps;", + "var outerResolve;", + "var reject;", + "var isEvaluating = true;", + "var nested = false;", + `var whenAll = ${runtimeTemplate.basicFunction( + "deps, onResolve, onReject", + [ + "if (nested) return;", + "nested = true;", + "onResolve.r += deps.length;", + `deps.map(${runtimeTemplate.expressionFunction( + "dep[webpackThen](onResolve, onReject)", + "dep, i" + )});`, + "nested = false;" + ] + )};`, + `var promise = new Promise(${runtimeTemplate.basicFunction( + "resolve, rej", + [ + "reject = rej;", + `outerResolve = ${runtimeTemplate.expressionFunction( + "resolve(exports), completeQueue(queue), queue = 0" + )};` + ] + )});`, + "promise[webpackExports] = exports;", + `promise[webpackThen] = ${runtimeTemplate.basicFunction( + "fn, rejectFn", + [ + "if (isEvaluating) { return completeFunction(fn); }", + "if (currentDeps) whenAll(currentDeps, fn, rejectFn);", + "queueFunction(queue, fn);", + "promise['catch'](rejectFn);" + ] + )};`, + "module.exports = promise;", + `body(${runtimeTemplate.basicFunction("deps", [ + "if(!deps) return outerResolve();", + "currentDeps = wrapDeps(deps);", + "var fn, result;", + `var promise = new Promise(${runtimeTemplate.basicFunction( + "resolve, reject", + [ + `fn = ${runtimeTemplate.expressionFunction( + `resolve(result = currentDeps.map(${runtimeTemplate.returningFunction( + "d[webpackExports]", + "d" + )}))` + )};`, + "fn.r = 0;", + "whenAll(currentDeps, fn, reject);" + ] + )});`, + "return fn.r ? promise : result;" + ])}).then(outerResolve, reject);`, + "isEvaluating = false;" + ])};` + ]); } +} - /** - * 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) { - throw new Error("Must not be called"); - } +module.exports = AsyncModuleRuntimeModule; - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; - } - get modules() { - return Array.from(this._modules); - } +/***/ }), - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - return this._identifier; +/***/ 66532: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); +const JavascriptModulesPlugin = __webpack_require__(89464); +const { getUndoPath } = __webpack_require__(82186); + +class AutoPublicPathRuntimeModule extends RuntimeModule { + constructor() { + super("publicPath", RuntimeModule.STAGE_BASIC); } /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module + * @returns {string} runtime code */ - readableIdentifier(requestShortener) { - return ( - this.rootModule.readableIdentifier(requestShortener) + - ` + ${this._modules.size - 1} modules` + generate() { + const { compilation } = this; + const { scriptType, importMetaName, path } = compilation.outputOptions; + const chunkName = compilation.getPath( + JavascriptModulesPlugin.getChunkFilenameTemplate( + this.chunk, + compilation.outputOptions + ), + { + chunk: this.chunk, + contentHashType: "javascript" + } ); + const undoPath = getUndoPath(chunkName, path, false); + + return Template.asString([ + "var scriptUrl;", + scriptType === "module" + ? `if (typeof ${importMetaName}.url === "string") scriptUrl = ${importMetaName}.url` + : Template.asString([ + `if (${RuntimeGlobals.global}.importScripts) scriptUrl = ${RuntimeGlobals.global}.location + "";`, + `var document = ${RuntimeGlobals.global}.document;`, + "if (!scriptUrl && document) {", + Template.indent([ + `if (document.currentScript)`, + Template.indent(`scriptUrl = document.currentScript.src`), + "if (!scriptUrl) {", + Template.indent([ + 'var scripts = document.getElementsByTagName("script");', + "if(scripts.length) scriptUrl = scripts[scripts.length - 1].src" + ]), + "}" + ]), + "}" + ]), + "// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration", + '// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.', + 'if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");', + 'scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\\?.*$/, "").replace(/\\/[^\\/]+$/, "/");', + !undoPath + ? `${RuntimeGlobals.publicPath} = scriptUrl;` + : `${RuntimeGlobals.publicPath} = scriptUrl + ${JSON.stringify( + undoPath + )};` + ]); } +} + +module.exports = AutoPublicPathRuntimeModule; + + +/***/ }), + +/***/ 84519: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +class ChunkNameRuntimeModule extends RuntimeModule { /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion + * @param {string} chunkName the chunk's name */ - libIdent(options) { - return this.rootModule.libIdent(options); + constructor(chunkName) { + super("chunkName"); + this.chunkName = chunkName; } /** - * @returns {string | null} absolute path which should be used for condition matching (usually the resource path) + * @returns {string} runtime code */ - nameForCondition() { - return this.rootModule.nameForCondition(); + generate() { + return `${RuntimeGlobals.chunkName} = ${JSON.stringify(this.chunkName)};`; } +} - /** - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only - */ - getSideEffectsConnectionState(moduleGraph) { - return this.rootModule.getSideEffectsConnectionState(moduleGraph); +module.exports = ChunkNameRuntimeModule; + + +/***/ }), + +/***/ 44793: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const HelperRuntimeModule = __webpack_require__(82444); + +class CompatGetDefaultExportRuntimeModule extends HelperRuntimeModule { + constructor() { + super("compat get default export"); } /** - * @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} + * @returns {string} runtime code */ - build(options, compilation, resolver, fs, callback) { - const { rootModule } = this; - this.buildInfo = { - strict: true, - cacheable: true, - moduleArgument: rootModule.buildInfo.moduleArgument, - exportsArgument: rootModule.buildInfo.exportsArgument, - fileDependencies: new LazySet(), - contextDependencies: new LazySet(), - missingDependencies: new LazySet(), - topLevelDeclarations: new Set(), - assets: undefined - }; - this.buildMeta = rootModule.buildMeta; - this.clearDependenciesAndBlocks(); - this.clearWarningsAndErrors(); + generate() { + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.compatGetDefaultExport; + return Template.asString([ + "// getDefaultExport function for compatibility with non-harmony modules", + `${fn} = ${runtimeTemplate.basicFunction("module", [ + "var getter = module && module.__esModule ?", + Template.indent([ + `${runtimeTemplate.returningFunction("module['default']")} :`, + `${runtimeTemplate.returningFunction("module")};` + ]), + `${RuntimeGlobals.definePropertyGetters}(getter, { a: getter });`, + "return getter;" + ])};` + ]); + } +} - for (const m of this._modules) { - // populate cacheable - if (!m.buildInfo.cacheable) { - this.buildInfo.cacheable = false; - } +module.exports = CompatGetDefaultExportRuntimeModule; - // populate dependencies - for (const d of m.dependencies.filter( - dep => - !(dep instanceof HarmonyImportDependency) || - !this._modules.has(compilation.moduleGraph.getModule(dep)) - )) { - this.dependencies.push(d); - } - // populate blocks - for (const d of m.blocks) { - this.blocks.push(d); - } - // populate warnings - const warnings = m.getWarnings(); - if (warnings !== undefined) { - for (const warning of warnings) { - this.addWarning(warning); - } - } +/***/ }), - // populate errors - const errors = m.getErrors(); - if (errors !== undefined) { - for (const error of errors) { - this.addError(error); - } - } +/***/ 88234: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // populate topLevelDeclarations - if (m.buildInfo.topLevelDeclarations) { - const topLevelDeclarations = this.buildInfo.topLevelDeclarations; - if (topLevelDeclarations !== undefined) { - for (const decl of m.buildInfo.topLevelDeclarations) { - // reserved names will always be renamed - if (RESERVED_NAMES.has(decl)) continue; - // TODO actually this is incorrect since with renaming there could be more - // We should do the renaming during build - topLevelDeclarations.add(decl); - } - } - } else { - this.buildInfo.topLevelDeclarations = undefined; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - // populate assets - if (m.buildInfo.assets) { - if (this.buildInfo.assets === undefined) { - this.buildInfo.assets = Object.create(null); - } - Object.assign(this.buildInfo.assets, m.buildInfo.assets); - } - if (m.buildInfo.assetsInfo) { - if (this.buildInfo.assetsInfo === undefined) { - this.buildInfo.assetsInfo = new Map(); - } - for (const [key, value] of m.buildInfo.assetsInfo) { - this.buildInfo.assetsInfo.set(key, value); - } + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); + +/** @typedef {import("../MainTemplate")} MainTemplate */ + +class CompatRuntimeModule extends RuntimeModule { + constructor() { + super("compat", RuntimeModule.STAGE_ATTACH); + this.fullHash = true; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { chunkGraph, chunk, compilation } = this; + const { + runtimeTemplate, + mainTemplate, + moduleTemplates, + dependencyTemplates + } = compilation; + const bootstrap = mainTemplate.hooks.bootstrap.call( + "", + chunk, + compilation.hash || "XXXX", + moduleTemplates.javascript, + dependencyTemplates + ); + const localVars = mainTemplate.hooks.localVars.call( + "", + chunk, + compilation.hash || "XXXX" + ); + const requireExtensions = mainTemplate.hooks.requireExtensions.call( + "", + chunk, + compilation.hash || "XXXX" + ); + const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); + let requireEnsure = ""; + if (runtimeRequirements.has(RuntimeGlobals.ensureChunk)) { + const requireEnsureHandler = mainTemplate.hooks.requireEnsure.call( + "", + chunk, + compilation.hash || "XXXX", + "chunkId" + ); + if (requireEnsureHandler) { + requireEnsure = `${ + RuntimeGlobals.ensureChunkHandlers + }.compat = ${runtimeTemplate.basicFunction( + "chunkId, promises", + requireEnsureHandler + )};`; } } - callback(); + return [bootstrap, localVars, requireEnsure, requireExtensions] + .filter(Boolean) + .join("\n"); } /** - * @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) + * @returns {boolean} true, if the runtime module should get it's own scope */ - size(type) { - // Guess size from embedded modules - let size = 0; - for (const module of this._modules) { - size += module.size(type); - } - return size; + shouldIsolate() { + // We avoid isolating this to have better backward-compat + return false; + } +} + +module.exports = CompatRuntimeModule; + + +/***/ }), + +/***/ 94669: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const HelperRuntimeModule = __webpack_require__(82444); + +class CreateFakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { + constructor() { + super("create fake namespace object"); } /** - * @private - * @param {Module} rootModule the root of the concatenation - * @param {Set} modulesSet a set of modules which should be concatenated - * @param {RuntimeSpec} runtime for this runtime - * @param {ModuleGraph} moduleGraph the module graph - * @returns {ConcatenationEntry[]} concatenation list + * @returns {string} runtime code */ - _createConcatenationList(rootModule, modulesSet, runtime, moduleGraph) { - /** @type {ConcatenationEntry[]} */ - const list = []; - /** @type {Map} */ - const existingEntries = new Map(); + generate() { + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.createFakeNamespaceObject; + return Template.asString([ + `var getProto = Object.getPrototypeOf ? ${runtimeTemplate.returningFunction( + "Object.getPrototypeOf(obj)", + "obj" + )} : ${runtimeTemplate.returningFunction("obj.__proto__", "obj")};`, + "var leafPrototypes;", + "// create a fake namespace object", + "// mode & 1: value is a module id, require it", + "// mode & 2: merge all properties of value into the ns", + "// mode & 4: return value when already ns object", + "// mode & 16: return value when it's Promise-like", + "// mode & 8|1: behave like require", + // Note: must be a function (not arrow), because this is used in body! + `${fn} = function(value, mode) {`, + Template.indent([ + `if(mode & 1) value = this(value);`, + `if(mode & 8) return value;`, + "if(typeof value === 'object' && value) {", + Template.indent([ + "if((mode & 4) && value.__esModule) return value;", + "if((mode & 16) && typeof value.then === 'function') return value;" + ]), + "}", + "var ns = Object.create(null);", + `${RuntimeGlobals.makeNamespaceObject}(ns);`, + "var def = {};", + "leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];", + "for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {", + Template.indent([ + `Object.getOwnPropertyNames(current).forEach(${runtimeTemplate.expressionFunction( + `def[key] = ${runtimeTemplate.returningFunction("value[key]", "")}`, + "key" + )});` + ]), + "}", + `def['default'] = ${runtimeTemplate.returningFunction("value", "")};`, + `${RuntimeGlobals.definePropertyGetters}(ns, def);`, + "return ns;" + ]), + "};" + ]); + } +} - /** - * @param {Module} module a module - * @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} imported modules in order - */ - const getConcatenatedImports = module => { - let connections = Array.from(moduleGraph.getOutgoingConnections(module)); - if (module === rootModule) { - for (const c of moduleGraph.getOutgoingConnections(this)) - connections.push(c); - } - const references = connections - .filter(connection => { - if (!(connection.dependency instanceof HarmonyImportDependency)) - return false; - return ( - connection && - connection.resolvedOriginModule === module && - connection.module && - connection.isTargetActive(runtime) - ); - }) - .map(connection => ({ - connection, - sourceOrder: /** @type {HarmonyImportDependency} */ ( - connection.dependency - ).sourceOrder - })); - references.sort( - concatComparators(bySourceOrder, keepOriginalOrder(references)) - ); - /** @type {Map} */ - const referencesMap = new Map(); - for (const { connection } of references) { - const runtimeCondition = filterRuntime(runtime, r => - connection.isTargetActive(r) - ); - if (runtimeCondition === false) continue; - const module = connection.module; - const entry = referencesMap.get(module); - if (entry === undefined) { - referencesMap.set(module, { connection, runtimeCondition }); - continue; - } - entry.runtimeCondition = mergeRuntimeConditionNonFalse( - entry.runtimeCondition, - runtimeCondition, - runtime - ); - } - return referencesMap.values(); - }; +module.exports = CreateFakeNamespaceObjectRuntimeModule; - /** - * @param {ModuleGraphConnection} connection graph connection - * @param {RuntimeSpec | true} runtimeCondition runtime condition - * @returns {void} - */ - const enterModule = (connection, runtimeCondition) => { - const module = connection.module; - if (!module) return; - const existingEntry = existingEntries.get(module); - if (existingEntry === true) { - return; - } - if (modulesSet.has(module)) { - existingEntries.set(module, true); - if (runtimeCondition !== true) { - throw new Error( - `Cannot runtime-conditional concatenate a module (${module.identifier()} in ${this.rootModule.identifier()}, ${runtimeConditionToString( - runtimeCondition - )}). This should not happen.` - ); - } - const imports = getConcatenatedImports(module); - for (const { connection, runtimeCondition } of imports) - enterModule(connection, runtimeCondition); - list.push({ - type: "concatenated", - module: connection.module, - runtimeCondition - }); - } else { - if (existingEntry !== undefined) { - const reducedRuntimeCondition = subtractRuntimeCondition( - runtimeCondition, - existingEntry, - runtime - ); - if (reducedRuntimeCondition === false) return; - runtimeCondition = reducedRuntimeCondition; - existingEntries.set( - connection.module, - mergeRuntimeConditionNonFalse( - existingEntry, - runtimeCondition, - runtime - ) - ); - } else { - existingEntries.set(connection.module, runtimeCondition); - } - if (list.length > 0) { - const lastItem = list[list.length - 1]; - if ( - lastItem.type === "external" && - lastItem.module === connection.module - ) { - lastItem.runtimeCondition = mergeRuntimeCondition( - lastItem.runtimeCondition, - runtimeCondition, - runtime - ); - return; - } - } - list.push({ - type: "external", - get module() { - // We need to use a getter here, because the module in the dependency - // could be replaced by some other process (i. e. also replaced with a - // concatenated module) - return connection.module; - }, - runtimeCondition - }); - } - }; - existingEntries.set(rootModule, true); - const imports = getConcatenatedImports(rootModule); - for (const { connection, runtimeCondition } of imports) - enterModule(connection, runtimeCondition); - list.push({ - type: "concatenated", - module: rootModule, - runtimeCondition: true - }); +/***/ }), - return list; +/***/ 2759: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const HelperRuntimeModule = __webpack_require__(82444); + +class CreateScriptRuntimeModule extends HelperRuntimeModule { + constructor() { + super("trusted types script"); } /** - * @param {Module} rootModule the root module of the concatenation - * @param {Set} modules all modules in the concatenation (including the root module) - * @param {Object=} associatedObjectForCache object for caching - * @param {string | HashConstructor=} hashFunction hash function to use - * @returns {string} the identifier + * @returns {string} runtime code */ - static _createIdentifier( - rootModule, - modules, - associatedObjectForCache, - hashFunction = "md4" - ) { - const cachedMakePathsRelative = makePathsRelative.bindContextCache( - rootModule.context, - associatedObjectForCache + generate() { + const { compilation } = this; + const { runtimeTemplate, outputOptions } = compilation; + const { trustedTypes } = outputOptions; + const fn = RuntimeGlobals.createScript; + + return Template.asString( + `${fn} = ${runtimeTemplate.returningFunction( + trustedTypes + ? `${RuntimeGlobals.getTrustedTypesPolicy}().createScript(script)` + : "script", + "script" + )};` ); - let identifiers = []; - for (const module of modules) { - identifiers.push(cachedMakePathsRelative(module.identifier())); - } - identifiers.sort(); - const hash = createHash(hashFunction); - hash.update(identifiers.join(" ")); - return rootModule.identifier() + "|" + hash.digest("hex"); + } +} + +module.exports = CreateScriptRuntimeModule; + + +/***/ }), + +/***/ 21213: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const HelperRuntimeModule = __webpack_require__(82444); + +class CreateScriptUrlRuntimeModule extends HelperRuntimeModule { + constructor() { + super("trusted types script url"); } /** - * @param {LazySet} fileDependencies set where file dependencies are added to - * @param {LazySet} contextDependencies set where context dependencies are added to - * @param {LazySet} missingDependencies set where missing dependencies are added to - * @param {LazySet} buildDependencies set where build dependencies are added to + * @returns {string} runtime code */ - addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ) { - for (const module of this._modules) { - module.addCacheDependencies( - fileDependencies, - contextDependencies, - missingDependencies, - buildDependencies - ); - } + generate() { + const { compilation } = this; + const { runtimeTemplate, outputOptions } = compilation; + const { trustedTypes } = outputOptions; + const fn = RuntimeGlobals.createScriptUrl; + + return Template.asString( + `${fn} = ${runtimeTemplate.returningFunction( + trustedTypes + ? `${RuntimeGlobals.getTrustedTypesPolicy}().createScriptURL(url)` + : "url", + "url" + )};` + ); + } +} + +module.exports = CreateScriptUrlRuntimeModule; + + +/***/ }), + +/***/ 75481: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const HelperRuntimeModule = __webpack_require__(82444); + +class DefinePropertyGettersRuntimeModule extends HelperRuntimeModule { + constructor() { + super("define property getters"); } /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result + * @returns {string} runtime code */ - codeGeneration({ - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime: generationRuntime, - codeGenerationResults - }) { - /** @type {Set} */ - const runtimeRequirements = new Set(); - const runtime = intersectRuntime(generationRuntime, this._runtime); + generate() { + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.definePropertyGetters; + return Template.asString([ + "// define getter functions for harmony exports", + `${fn} = ${runtimeTemplate.basicFunction("exports, definition", [ + `for(var key in definition) {`, + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(definition, key) && !${RuntimeGlobals.hasOwnProperty}(exports, key)) {`, + Template.indent([ + "Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });" + ]), + "}" + ]), + "}" + ])};` + ]); + } +} - const requestShortener = runtimeTemplate.requestShortener; - // Meta info for each module - const [modulesWithInfo, moduleToInfoMap] = this._getModulesWithInfo( - moduleGraph, - runtime - ); +module.exports = DefinePropertyGettersRuntimeModule; - // Set with modules that need a generated namespace object - /** @type {Set} */ - const neededNamespaceObjects = new Set(); - // Generate source code and analyse scopes - // Prepare a ReplaceSource for the final source - for (const info of moduleToInfoMap.values()) { - this._analyseModule( - moduleToInfoMap, - info, - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime, - codeGenerationResults - ); +/***/ }), + +/***/ 71519: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); + +class EnsureChunkRuntimeModule extends RuntimeModule { + constructor(runtimeRequirements) { + super("ensure chunk"); + this.runtimeRequirements = runtimeRequirements; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + // Check if there are non initial chunks which need to be imported using require-ensure + if (this.runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers)) { + const handlers = RuntimeGlobals.ensureChunkHandlers; + return Template.asString([ + `${handlers} = {};`, + "// This file contains only the entry chunk.", + "// The chunk loading function for additional chunks", + `${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.basicFunction( + "chunkId", + [ + `return Promise.all(Object.keys(${handlers}).reduce(${runtimeTemplate.basicFunction( + "promises, key", + [`${handlers}[key](chunkId, promises);`, "return promises;"] + )}, []));` + ] + )};` + ]); + } else { + // There ensureChunk is used somewhere in the tree, so we need an empty requireEnsure + // function. This can happen with multiple entrypoints. + return Template.asString([ + "// The chunk loading function for additional chunks", + "// Since all referenced chunks are already included", + "// in this file, this function is empty here.", + `${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.returningFunction( + "Promise.resolve()" + )};` + ]); } + } +} - // List of all used names to avoid conflicts - const allUsedNames = new Set(RESERVED_NAMES); +module.exports = EnsureChunkRuntimeModule; + + +/***/ }), + +/***/ 34277: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); +const { first } = __webpack_require__(93347); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("../Compilation").PathData} PathData */ + +/** @typedef {function(PathData, AssetInfo=): string} FilenameFunction */ + +class GetChunkFilenameRuntimeModule extends RuntimeModule { + /** + * @param {string} contentType the contentType to use the content hash for + * @param {string} name kind of filename + * @param {string} global function name to be assigned + * @param {function(Chunk): string | FilenameFunction} getFilenameForChunk functor to get the filename or function + * @param {boolean} allChunks when false, only async chunks are included + */ + constructor(contentType, name, global, getFilenameForChunk, allChunks) { + super(`get ${name} chunk filename`); + this.contentType = contentType; + this.global = global; + this.getFilenameForChunk = getFilenameForChunk; + this.allChunks = allChunks; + this.dependentHash = true; + } + + /** + * @returns {string} runtime code + */ + generate() { + const { + global, + chunk, + chunkGraph, + contentType, + getFilenameForChunk, + allChunks, + compilation + } = this; + const { runtimeTemplate } = compilation; + + /** @type {Map>} */ + const chunkFilenames = new Map(); + let maxChunks = 0; + /** @type {string} */ + let dynamicFilename; - // List of additional names in scope for module references - /** @type {Map, alreadyCheckedScopes: Set }>} */ - const usedNamesInScopeInfo = new Map(); /** - * @param {string} module module identifier - * @param {string} id export id - * @returns {{ usedNames: Set, alreadyCheckedScopes: Set }} info + * @param {Chunk} c the chunk + * @returns {void} */ - const getUsedNamesInScopeInfo = (module, id) => { - const key = `${module}-${id}`; - let info = usedNamesInScopeInfo.get(key); - if (info === undefined) { - info = { - usedNames: new Set(), - alreadyCheckedScopes: new Set() - }; - usedNamesInScopeInfo.set(key, info); + const addChunk = c => { + const chunkFilename = getFilenameForChunk(c); + if (chunkFilename) { + let set = chunkFilenames.get(chunkFilename); + if (set === undefined) { + chunkFilenames.set(chunkFilename, (set = new Set())); + } + set.add(c); + if (typeof chunkFilename === "string") { + if (set.size < maxChunks) return; + if (set.size === maxChunks) { + if (chunkFilename.length < dynamicFilename.length) return; + if (chunkFilename.length === dynamicFilename.length) { + if (chunkFilename < dynamicFilename) return; + } + } + maxChunks = set.size; + dynamicFilename = chunkFilename; + } } - return info; }; - // Set of already checked scopes - const ignoredScopes = new Set(); - - // get all global names - for (const info of modulesWithInfo) { - if (info.type === "concatenated") { - // ignore symbols from moduleScope - if (info.moduleScope) { - ignoredScopes.add(info.moduleScope); + /** @type {string[]} */ + const includedChunksMessages = []; + if (allChunks) { + includedChunksMessages.push("all chunks"); + for (const c of chunk.getAllReferencedChunks()) { + addChunk(c); + } + } else { + includedChunksMessages.push("async chunks"); + for (const c of chunk.getAllAsyncChunks()) { + addChunk(c); + } + const includeEntries = chunkGraph + .getTreeRuntimeRequirements(chunk) + .has(RuntimeGlobals.ensureChunkIncludeEntries); + if (includeEntries) { + includedChunksMessages.push("sibling chunks for the entrypoint"); + for (const c of chunkGraph.getChunkEntryDependentChunksIterable( + chunk + )) { + addChunk(c); } + } + } + for (const entrypoint of chunk.getAllReferencedAsyncEntrypoints()) { + addChunk(entrypoint.chunks[entrypoint.chunks.length - 1]); + } - // The super class expression in class scopes behaves weird - // We get ranges of all super class expressions to make - // renaming to work correctly - const superClassCache = new WeakMap(); - const getSuperClassExpressions = scope => { - const cacheEntry = superClassCache.get(scope); - if (cacheEntry !== undefined) return cacheEntry; - const superClassExpressions = []; - for (const childScope of scope.childScopes) { - if (childScope.type !== "class") continue; - const block = childScope.block; - if ( - (block.type === "ClassDeclaration" || - block.type === "ClassExpression") && - block.superClass - ) { - superClassExpressions.push({ - range: block.superClass.range, - variables: childScope.variables - }); - } - } - superClassCache.set(scope, superClassExpressions); - return superClassExpressions; - }; + /** @type {Map>} */ + const staticUrls = new Map(); + /** @type {Set} */ + const dynamicUrlChunks = new Set(); - // add global symbols - if (info.globalScope) { - for (const reference of info.globalScope.through) { - const name = reference.identifier.name; - if (ConcatenationScope.isModuleReference(name)) { - const match = ConcatenationScope.matchModuleReference(name); - if (!match) continue; - const referencedInfo = modulesWithInfo[match.index]; - if (referencedInfo.type === "reference") - throw new Error("Module reference can't point to a reference"); - const binding = getFinalBinding( - moduleGraph, - referencedInfo, - match.ids, - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - false, - info.module.buildMeta.strictHarmonyModule, - true - ); - if (!binding.ids) continue; - const { usedNames, alreadyCheckedScopes } = - getUsedNamesInScopeInfo( - binding.info.module.identifier(), - "name" in binding ? binding.name : "" - ); - for (const expr of getSuperClassExpressions(reference.from)) { - if ( - expr.range[0] <= reference.identifier.range[0] && - expr.range[1] >= reference.identifier.range[1] - ) { - for (const variable of expr.variables) { - usedNames.add(variable.name); - } - } - } - addScopeSymbols( - reference.from, - usedNames, - alreadyCheckedScopes, - ignoredScopes - ); - } else { - allUsedNames.add(name); - } - } + /** + * @param {Chunk} c the chunk + * @param {string | FilenameFunction} chunkFilename the filename template for the chunk + * @returns {void} + */ + const addStaticUrl = (c, chunkFilename) => { + /** + * @param {string | number} value a value + * @returns {string} string to put in quotes + */ + const unquotedStringify = value => { + const str = `${value}`; + if (str.length >= 5 && str === `${c.id}`) { + // This is shorter and generates the same result + return '" + chunkId + "'; } + const s = JSON.stringify(str); + return s.slice(1, s.length - 1); + }; + const unquotedStringifyWithLength = value => length => + unquotedStringify(`${value}`.slice(0, length)); + const chunkFilenameValue = + typeof chunkFilename === "function" + ? JSON.stringify( + chunkFilename({ + chunk: c, + contentHashType: contentType + }) + ) + : JSON.stringify(chunkFilename); + const staticChunkFilename = compilation.getPath(chunkFilenameValue, { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: length => + `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, + chunk: { + id: unquotedStringify(c.id), + hash: unquotedStringify(c.renderedHash), + hashWithLength: unquotedStringifyWithLength(c.renderedHash), + name: unquotedStringify(c.name || c.id), + contentHash: { + [contentType]: unquotedStringify(c.contentHash[contentType]) + }, + contentHashWithLength: { + [contentType]: unquotedStringifyWithLength( + c.contentHash[contentType] + ) + } + }, + contentHashType: contentType + }); + let set = staticUrls.get(staticChunkFilename); + if (set === undefined) { + staticUrls.set(staticChunkFilename, (set = new Set())); } - } + set.add(c.id); + }; - // generate names for symbols - for (const info of moduleToInfoMap.values()) { - const { usedNames: namespaceObjectUsedNames } = getUsedNamesInScopeInfo( - info.module.identifier(), - "" - ); - switch (info.type) { - case "concatenated": { - for (const variable of info.moduleScope.variables) { - const name = variable.name; - const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo( - info.module.identifier(), - name - ); - if (allUsedNames.has(name) || usedNames.has(name)) { - const references = getAllReferences(variable); - for (const ref of references) { - addScopeSymbols( - ref.from, - usedNames, - alreadyCheckedScopes, - ignoredScopes - ); - } - const newName = this.findNewName( - name, - allUsedNames, - usedNames, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(newName); - info.internalNames.set(name, newName); - const source = info.source; - const allIdentifiers = new Set( - references.map(r => r.identifier).concat(variable.identifiers) - ); - for (const identifier of allIdentifiers) { - const r = identifier.range; - const path = getPathInAst(info.ast, identifier); - if (path && path.length > 1) { - const maybeProperty = - path[1].type === "AssignmentPattern" && - path[1].left === path[0] - ? path[2] - : path[1]; - if ( - maybeProperty.type === "Property" && - maybeProperty.shorthand - ) { - source.insert(r[1], `: ${newName}`); - continue; - } - } - source.replace(r[0], r[1] - 1, newName); - } - } else { - allUsedNames.add(name); - info.internalNames.set(name, name); - } - } - let namespaceObjectName; - if (info.namespaceExportSymbol) { - namespaceObjectName = info.internalNames.get( - info.namespaceExportSymbol - ); - } else { - namespaceObjectName = this.findNewName( - "namespaceObject", - allUsedNames, - namespaceObjectUsedNames, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(namespaceObjectName); - } - info.namespaceObjectName = namespaceObjectName; - break; - } - case "external": { - const externalName = this.findNewName( - "", - allUsedNames, - namespaceObjectUsedNames, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(externalName); - info.name = externalName; - break; - } - } - if (info.module.buildMeta.exportsType !== "namespace") { - const externalNameInterop = this.findNewName( - "namespaceObject", - allUsedNames, - namespaceObjectUsedNames, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(externalNameInterop); - info.interopNamespaceObjectName = externalNameInterop; - } - if ( - info.module.buildMeta.exportsType === "default" && - info.module.buildMeta.defaultObject !== "redirect" - ) { - const externalNameInterop = this.findNewName( - "namespaceObject2", - allUsedNames, - namespaceObjectUsedNames, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(externalNameInterop); - info.interopNamespaceObject2Name = externalNameInterop; - } - if ( - info.module.buildMeta.exportsType === "dynamic" || - !info.module.buildMeta.exportsType - ) { - const externalNameInterop = this.findNewName( - "default", - allUsedNames, - namespaceObjectUsedNames, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(externalNameInterop); - info.interopDefaultAccessName = externalNameInterop; + for (const [filename, chunks] of chunkFilenames) { + if (filename !== dynamicFilename) { + for (const c of chunks) addStaticUrl(c, filename); + } else { + for (const c of chunks) dynamicUrlChunks.add(c); } } - // Find and replace references to modules - for (const info of moduleToInfoMap.values()) { - if (info.type === "concatenated") { - for (const reference of info.globalScope.through) { - const name = reference.identifier.name; - const match = ConcatenationScope.matchModuleReference(name); - if (match) { - const referencedInfo = modulesWithInfo[match.index]; - if (referencedInfo.type === "reference") - throw new Error("Module reference can't point to a reference"); - const finalName = getFinalName( - moduleGraph, - referencedInfo, - match.ids, - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - match.call, - !match.directImport, - info.module.buildMeta.strictHarmonyModule, - match.asiSafe - ); - const r = reference.identifier.range; - const source = info.source; - // range is extended by 2 chars to cover the appended "._" - source.replace(r[0], r[1] + 1, finalName); - } + /** + * @param {function(Chunk): string | number} fn function from chunk to value + * @returns {string} code with static mapping of results of fn + */ + const createMap = fn => { + const obj = {}; + let useId = false; + let lastKey; + let entries = 0; + for (const c of dynamicUrlChunks) { + const value = fn(c); + if (value === c.id) { + useId = true; + } else { + obj[c.id] = value; + lastKey = c.id; + entries++; } } - } + if (entries === 0) return "chunkId"; + if (entries === 1) { + return useId + ? `(chunkId === ${JSON.stringify(lastKey)} ? ${JSON.stringify( + obj[lastKey] + )} : chunkId)` + : JSON.stringify(obj[lastKey]); + } + return useId + ? `(${JSON.stringify(obj)}[chunkId] || chunkId)` + : `${JSON.stringify(obj)}[chunkId]`; + }; - // Map with all root exposed used exports - /** @type {Map} */ - const exportsMap = new Map(); + /** + * @param {function(Chunk): string | number} fn function from chunk to value + * @returns {string} code with static mapping of results of fn for including in quoted string + */ + const mapExpr = fn => { + return `" + ${createMap(fn)} + "`; + }; - // Set with all root exposed unused exports - /** @type {Set} */ - const unusedExports = new Set(); + /** + * @param {function(Chunk): string | number} fn function from chunk to value + * @returns {function(number): string} function which generates code with static mapping of results of fn for including in quoted string for specific length + */ + const mapExprWithLength = fn => length => { + return `" + ${createMap(c => `${fn(c)}`.slice(0, length))} + "`; + }; - const rootInfo = /** @type {ConcatenatedModuleInfo} */ ( - moduleToInfoMap.get(this.rootModule) - ); - const strictHarmonyModule = rootInfo.module.buildMeta.strictHarmonyModule; - const exportsInfo = moduleGraph.getExportsInfo(rootInfo.module); - for (const exportInfo of exportsInfo.orderedExports) { - const name = exportInfo.name; - if (exportInfo.provided === false) continue; - const used = exportInfo.getUsedName(undefined, runtime); - if (!used) { - unusedExports.add(name); - continue; - } - exportsMap.set(used, requestShortener => { - try { - const finalName = getFinalName( - moduleGraph, - rootInfo, - [name], - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - false, - false, - strictHarmonyModule, - true - ); - return `/* ${ - exportInfo.isReexport() ? "reexport" : "binding" - } */ ${finalName}`; - } catch (e) { - e.message += `\nwhile generating the root export '${name}' (used name: '${used}')`; - throw e; - } + const url = + dynamicFilename && + compilation.getPath(JSON.stringify(dynamicFilename), { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: length => + `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, + chunk: { + id: `" + chunkId + "`, + hash: mapExpr(c => c.renderedHash), + hashWithLength: mapExprWithLength(c => c.renderedHash), + name: mapExpr(c => c.name || c.id), + contentHash: { + [contentType]: mapExpr(c => c.contentHash[contentType]) + }, + contentHashWithLength: { + [contentType]: mapExprWithLength(c => c.contentHash[contentType]) + } + }, + contentHashType: contentType }); - } - const result = new ConcatSource(); + return Template.asString([ + `// This function allow to reference ${includedChunksMessages.join( + " and " + )}`, + `${global} = ${runtimeTemplate.basicFunction( + "chunkId", - // add harmony compatibility flag (must be first because of possible circular dependencies) - if ( - moduleGraph.getExportsInfo(this).otherExportsInfo.getUsed(runtime) !== - UsageState.Unused - ) { - result.add(`// ESM COMPAT FLAG\n`); - result.add( - runtimeTemplate.defineEsModuleFlagStatement({ - exportsArgument: this.exportsArgument, - runtimeRequirements - }) - ); - } + staticUrls.size > 0 + ? [ + "// return url for filenames not based on template", + // it minimizes to `x===1?"...":x===2?"...":"..."` + Template.asString( + Array.from(staticUrls, ([url, ids]) => { + const condition = + ids.size === 1 + ? `chunkId === ${JSON.stringify(first(ids))}` + : `{${Array.from( + ids, + id => `${JSON.stringify(id)}:1` + ).join(",")}}[chunkId]`; + return `if (${condition}) return ${url};`; + }) + ), + "// return url for filenames based on template", + `return ${url};` + ] + : ["// return url for filenames based on template", `return ${url};`] + )};` + ]); + } +} - // define exports - if (exportsMap.size > 0) { - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - const definitions = []; - for (const [key, value] of exportsMap) { - definitions.push( - `\n ${JSON.stringify(key)}: ${runtimeTemplate.returningFunction( - value(requestShortener) - )}` - ); - } - result.add(`\n// EXPORTS\n`); - result.add( - `${RuntimeGlobals.definePropertyGetters}(${ - this.exportsArgument - }, {${definitions.join(",")}\n});\n` - ); - } +module.exports = GetChunkFilenameRuntimeModule; - // list unused exports - if (unusedExports.size > 0) { - result.add( - `\n// UNUSED EXPORTS: ${joinIterableWithComma(unusedExports)}\n` - ); - } - // generate namespace objects - const namespaceObjectSources = new Map(); - for (const info of neededNamespaceObjects) { - if (info.namespaceExportSymbol) continue; - const nsObj = []; - const exportsInfo = moduleGraph.getExportsInfo(info.module); - for (const exportInfo of exportsInfo.orderedExports) { - if (exportInfo.provided === false) continue; - const usedName = exportInfo.getUsedName(undefined, runtime); - if (usedName) { - const finalName = getFinalName( - moduleGraph, - info, - [exportInfo.name], - moduleToInfoMap, - runtime, - requestShortener, - runtimeTemplate, - neededNamespaceObjects, - false, - undefined, - info.module.buildMeta.strictHarmonyModule, - true - ); - nsObj.push( - `\n ${JSON.stringify( - usedName - )}: ${runtimeTemplate.returningFunction(finalName)}` - ); - } - } - const name = info.namespaceObjectName; - const defineGetters = - nsObj.length > 0 - ? `${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join( - "," - )}\n});\n` - : ""; - if (nsObj.length > 0) - runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); - namespaceObjectSources.set( - info, - ` -// NAMESPACE OBJECT: ${info.module.readableIdentifier(requestShortener)} -var ${name} = {}; -${RuntimeGlobals.makeNamespaceObject}(${name}); -${defineGetters}` - ); - runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); - } +/***/ }), - // define required namespace objects (must be before evaluation modules) - for (const info of modulesWithInfo) { - if (info.type === "concatenated") { - const source = namespaceObjectSources.get(info); - if (!source) continue; - result.add(source); - } - } +/***/ 88732: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const chunkInitFragments = []; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - // evaluate modules in order - for (const rawInfo of modulesWithInfo) { - let name; - let isConditional = false; - const info = rawInfo.type === "reference" ? rawInfo.target : rawInfo; - switch (info.type) { - case "concatenated": { - result.add( - `\n;// CONCATENATED MODULE: ${info.module.readableIdentifier( - requestShortener - )}\n` - ); - result.add(info.source); - if (info.chunkInitFragments) { - for (const f of info.chunkInitFragments) chunkInitFragments.push(f); - } - if (info.runtimeRequirements) { - for (const r of info.runtimeRequirements) { - runtimeRequirements.add(r); - } - } - name = info.namespaceObjectName; - break; - } - case "external": { - result.add( - `\n// EXTERNAL MODULE: ${info.module.readableIdentifier( - requestShortener - )}\n` - ); - runtimeRequirements.add(RuntimeGlobals.require); - const { runtimeCondition } = - /** @type {ExternalModuleInfo | ReferenceToModuleInfo} */ (rawInfo); - const condition = runtimeTemplate.runtimeConditionExpression({ - chunkGraph, - runtimeCondition, - runtime, - runtimeRequirements - }); - if (condition !== "true") { - isConditional = true; - result.add(`if (${condition}) {\n`); - } - result.add( - `var ${info.name} = __webpack_require__(${JSON.stringify( - chunkGraph.getModuleId(info.module) - )});` - ); - name = info.name; - break; - } - default: - // @ts-expect-error never is expected here - throw new Error(`Unsupported concatenation entry type ${info.type}`); - } - if (info.interopNamespaceObjectUsed) { - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - result.add( - `\nvar ${info.interopNamespaceObjectName} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name}, 2);` - ); - } - if (info.interopNamespaceObject2Used) { - runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject); - result.add( - `\nvar ${info.interopNamespaceObject2Name} = /*#__PURE__*/${RuntimeGlobals.createFakeNamespaceObject}(${name});` - ); - } - if (info.interopDefaultAccessUsed) { - runtimeRequirements.add(RuntimeGlobals.compatGetDefaultExport); - result.add( - `\nvar ${info.interopDefaultAccessName} = /*#__PURE__*/${RuntimeGlobals.compatGetDefaultExport}(${name});` - ); - } - if (isConditional) { - result.add("\n}"); - } - } - const data = new Map(); - if (chunkInitFragments.length > 0) - data.set("chunkInitFragments", chunkInitFragments); - /** @type {CodeGenerationResult} */ - const resultEntry = { - sources: new Map([["javascript", new CachedSource(result)]]), - data, - runtimeRequirements - }; +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); - return resultEntry; +/** @typedef {import("../Compilation")} Compilation */ + +class GetFullHashRuntimeModule extends RuntimeModule { + constructor() { + super("getFullHash"); + this.fullHash = true; } /** - * @param {Map} modulesMap modulesMap - * @param {ModuleInfo} info info - * @param {DependencyTemplates} dependencyTemplates dependencyTemplates - * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate - * @param {ModuleGraph} moduleGraph moduleGraph - * @param {ChunkGraph} chunkGraph chunkGraph - * @param {RuntimeSpec} runtime runtime - * @param {CodeGenerationResults} codeGenerationResults codeGenerationResults + * @returns {string} runtime code */ - _analyseModule( - modulesMap, - info, - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime, - codeGenerationResults - ) { - if (info.type === "concatenated") { - const m = info.module; - try { - // Create a concatenation scope to track and capture information - const concatenationScope = new ConcatenationScope(modulesMap, info); + generate() { + const { runtimeTemplate } = this.compilation; + return `${RuntimeGlobals.getFullHash} = ${runtimeTemplate.returningFunction( + JSON.stringify(this.compilation.hash || "XXXX") + )}`; + } +} - // TODO cache codeGeneration results - const codeGenResult = m.codeGeneration({ - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - runtime, - concatenationScope, - codeGenerationResults - }); - const source = codeGenResult.sources.get("javascript"); - const data = codeGenResult.data; - const chunkInitFragments = data && data.get("chunkInitFragments"); - const code = source.source().toString(); - let ast; - try { - ast = JavascriptParser._parse(code, { - sourceType: "module" - }); - } catch (err) { - if ( - err.loc && - typeof err.loc === "object" && - typeof err.loc.line === "number" - ) { - const lineNumber = err.loc.line; - const lines = code.split("\n"); - err.message += - "\n| " + - lines - .slice(Math.max(0, lineNumber - 3), lineNumber + 2) - .join("\n| "); - } - throw err; - } - const scopeManager = eslintScope.analyze(ast, { - ecmaVersion: 6, - sourceType: "module", - optimistic: true, - ignoreEval: true, - impliedStrict: true - }); - const globalScope = scopeManager.acquire(ast); - const moduleScope = globalScope.childScopes[0]; - const resultSource = new ReplaceSource(source); - info.runtimeRequirements = codeGenResult.runtimeRequirements; - info.ast = ast; - info.internalSource = source; - info.source = resultSource; - info.chunkInitFragments = chunkInitFragments; - info.globalScope = globalScope; - info.moduleScope = moduleScope; - } catch (err) { - err.message += `\nwhile analyzing module ${m.identifier()} for concatenation`; - throw err; - } - } +module.exports = GetFullHashRuntimeModule; + + +/***/ }), + +/***/ 10029: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); + +/** @typedef {import("../Compilation")} Compilation */ + +class GetMainFilenameRuntimeModule extends RuntimeModule { + /** + * @param {string} name readable name + * @param {string} global global object binding + * @param {string} filename main file name + */ + constructor(name, global, filename) { + super(`get ${name} filename`); + this.global = global; + this.filename = filename; } /** - * @param {ModuleGraph} moduleGraph the module graph - * @param {RuntimeSpec} runtime the runtime - * @returns {[ModuleInfoOrReference[], Map]} module info items + * @returns {string} runtime code */ - _getModulesWithInfo(moduleGraph, runtime) { - const orderedConcatenationList = this._createConcatenationList( - this.rootModule, - this._modules, - runtime, - moduleGraph - ); - /** @type {Map} */ - const map = new Map(); - const list = orderedConcatenationList.map((info, index) => { - let item = map.get(info.module); - if (item === undefined) { - switch (info.type) { - case "concatenated": - item = { - type: "concatenated", - module: info.module, - index, - ast: undefined, - internalSource: undefined, - runtimeRequirements: undefined, - source: undefined, - globalScope: undefined, - moduleScope: undefined, - internalNames: new Map(), - exportMap: undefined, - rawExportMap: undefined, - namespaceExportSymbol: undefined, - namespaceObjectName: undefined, - interopNamespaceObjectUsed: false, - interopNamespaceObjectName: undefined, - interopNamespaceObject2Used: false, - interopNamespaceObject2Name: undefined, - interopDefaultAccessUsed: false, - interopDefaultAccessName: undefined - }; - break; - case "external": - item = { - type: "external", - module: info.module, - runtimeCondition: info.runtimeCondition, - index, - name: undefined, - interopNamespaceObjectUsed: false, - interopNamespaceObjectName: undefined, - interopNamespaceObject2Used: false, - interopNamespaceObject2Name: undefined, - interopDefaultAccessUsed: false, - interopDefaultAccessName: undefined - }; - break; - default: - throw new Error( - `Unsupported concatenation entry type ${info.type}` - ); - } - map.set(item.module, item); - return item; - } else { - /** @type {ReferenceToModuleInfo} */ - const ref = { - type: "reference", - runtimeCondition: info.runtimeCondition, - target: item - }; - return ref; - } + generate() { + const { global, filename, compilation, chunk } = this; + const { runtimeTemplate } = compilation; + const url = compilation.getPath(JSON.stringify(filename), { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: length => + `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, + chunk, + runtime: chunk.runtime }); - return [list, map]; + return Template.asString([ + `${global} = ${runtimeTemplate.returningFunction(url)};` + ]); } +} - findNewName(oldName, usedNamed1, usedNamed2, extraInfo) { - let name = oldName; +module.exports = GetMainFilenameRuntimeModule; - if (name === ConcatenationScope.DEFAULT_EXPORT) { - name = ""; - } - if (name === ConcatenationScope.NAMESPACE_OBJECT_EXPORT) { - name = "namespaceObject"; - } - // Remove uncool stuff - extraInfo = extraInfo.replace( - /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, - "" - ); +/***/ }), - const splittedInfo = extraInfo.split("/"); - while (splittedInfo.length) { - name = splittedInfo.pop() + (name ? "_" + name : ""); - const nameIdent = Template.toIdentifier(name); - if ( - !usedNamed1.has(nameIdent) && - (!usedNamed2 || !usedNamed2.has(nameIdent)) - ) - return nameIdent; - } +/***/ 38713: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - let i = 0; - let nameWithNumber = Template.toIdentifier(`${name}_${i}`); - while ( - usedNamed1.has(nameWithNumber) || - (usedNamed2 && usedNamed2.has(nameWithNumber)) - ) { - i++; - nameWithNumber = Template.toIdentifier(`${name}_${i}`); - } - return nameWithNumber; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const HelperRuntimeModule = __webpack_require__(82444); +class GetTrustedTypesPolicyRuntimeModule extends HelperRuntimeModule { /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} + * @param {Set} runtimeRequirements runtime requirements */ - updateHash(hash, context) { - const { chunkGraph, runtime } = context; - for (const info of this._createConcatenationList( - this.rootModule, - this._modules, - intersectRuntime(runtime, this._runtime), - chunkGraph.moduleGraph - )) { - switch (info.type) { - case "concatenated": - info.module.updateHash(hash, context); - break; - case "external": - hash.update(`${chunkGraph.getModuleId(info.module)}`); - // TODO runtimeCondition - break; - } - } - super.updateHash(hash, context); + constructor(runtimeRequirements) { + super("trusted types policy"); + this.runtimeRequirements = runtimeRequirements; } - static deserialize(context) { - const obj = new ConcatenatedModule({ - identifier: undefined, - rootModule: undefined, - modules: undefined, - runtime: undefined - }); - obj.deserialize(context); - return obj; + /** + * @returns {string} runtime code + */ + generate() { + const { compilation } = this; + const { runtimeTemplate, outputOptions } = compilation; + const { trustedTypes } = outputOptions; + const fn = RuntimeGlobals.getTrustedTypesPolicy; + + return Template.asString([ + "var policy;", + `${fn} = ${runtimeTemplate.basicFunction("", [ + "// Create Trusted Type policy if Trusted Types are available and the policy doesn't exist yet.", + "if (policy === undefined) {", + Template.indent([ + "policy = {", + Template.indent( + [ + ...(this.runtimeRequirements.has(RuntimeGlobals.createScript) + ? [ + `createScript: ${runtimeTemplate.returningFunction( + "script", + "script" + )}` + ] + : []), + ...(this.runtimeRequirements.has(RuntimeGlobals.createScriptUrl) + ? [ + `createScriptURL: ${runtimeTemplate.returningFunction( + "url", + "url" + )}` + ] + : []) + ].join(",\n") + ), + "};", + ...(trustedTypes + ? [ + 'if (typeof trustedTypes !== "undefined" && trustedTypes.createPolicy) {', + Template.indent([ + `policy = trustedTypes.createPolicy(${JSON.stringify( + trustedTypes.policyName + )}, policy);` + ]), + "}" + ] + : []) + ]), + "}", + "return policy;" + ])};` + ]); } } -makeSerializable(ConcatenatedModule, "webpack/lib/optimize/ConcatenatedModule"); - -module.exports = ConcatenatedModule; +module.exports = GetTrustedTypesPolicyRuntimeModule; /***/ }), -/***/ 96260: +/***/ 23255: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const { STAGE_BASIC } = __webpack_require__(80057); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compiler")} Compiler */ +class GlobalRuntimeModule extends RuntimeModule { + constructor() { + super("global"); + } -class EnsureChunkConditionsPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @returns {string} runtime code */ - apply(compiler) { - compiler.hooks.compilation.tap( - "EnsureChunkConditionsPlugin", - compilation => { - const handler = chunks => { - const chunkGraph = compilation.chunkGraph; - // These sets are hoisted here to save memory - // They are cleared at the end of every loop - /** @type {Set} */ - const sourceChunks = new Set(); - /** @type {Set} */ - const chunkGroups = new Set(); - for (const module of compilation.modules) { - if (!module.hasChunkCondition()) continue; - for (const chunk of chunkGraph.getModuleChunksIterable(module)) { - if (!module.chunkCondition(chunk, compilation)) { - sourceChunks.add(chunk); - for (const group of chunk.groupsIterable) { - chunkGroups.add(group); - } - } - } - if (sourceChunks.size === 0) continue; - /** @type {Set} */ - const targetChunks = new Set(); - chunkGroupLoop: for (const chunkGroup of chunkGroups) { - // Can module be placed in a chunk of this group? - for (const chunk of chunkGroup.chunks) { - if (module.chunkCondition(chunk, compilation)) { - targetChunks.add(chunk); - continue chunkGroupLoop; - } - } - // We reached the entrypoint: fail - if (chunkGroup.isInitial()) { - throw new Error( - "Cannot fullfil chunk condition of " + module.identifier() - ); - } - // Try placing in all parents - for (const group of chunkGroup.parentsIterable) { - chunkGroups.add(group); - } - } - for (const sourceChunk of sourceChunks) { - chunkGraph.disconnectChunkAndModule(sourceChunk, module); - } - for (const targetChunk of targetChunks) { - chunkGraph.connectChunkAndModule(targetChunk, module); - } - sourceChunks.clear(); - chunkGroups.clear(); - } - }; - compilation.hooks.optimizeChunks.tap( - { - name: "EnsureChunkConditionsPlugin", - stage: STAGE_BASIC - }, - handler - ); - } - ); + generate() { + return Template.asString([ + `${RuntimeGlobals.global} = (function() {`, + Template.indent([ + "if (typeof globalThis === 'object') return globalThis;", + "try {", + Template.indent( + // This works in non-strict mode + // or + // This works if eval is allowed (see CSP) + "return this || new Function('return this')();" + ), + "} catch (e) {", + Template.indent( + // This works if the window reference is available + "if (typeof window === 'object') return window;" + ), + "}" + // It can still be `undefined`, but nothing to do about it... + // We return `undefined`, instead of nothing here, so it's + // easier to handle this case: + // if (!global) { … } + ]), + "})();" + ]); } } -module.exports = EnsureChunkConditionsPlugin; + +module.exports = GlobalRuntimeModule; /***/ }), -/***/ 50089: -/***/ (function(module) { +/***/ 8011: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sergey Melyukov @smelukov */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); + +class HasOwnPropertyRuntimeModule extends RuntimeModule { + constructor() { + super("hasOwnProperty shorthand"); + } -class FlagIncludedChunksPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @returns {string} runtime code */ - apply(compiler) { - compiler.hooks.compilation.tap("FlagIncludedChunksPlugin", compilation => { - compilation.hooks.optimizeChunkIds.tap( - "FlagIncludedChunksPlugin", - chunks => { - const chunkGraph = compilation.chunkGraph; + generate() { + const { runtimeTemplate } = this.compilation; - // prepare two bit integers for each module - // 2^31 is the max number represented as SMI in v8 - // we want the bits distributed this way: - // the bit 2^31 is pretty rar and only one module should get it - // so it has a probability of 1 / modulesCount - // the first bit (2^0) is the easiest and every module could get it - // if it doesn't get a better bit - // from bit 2^n to 2^(n+1) there is a probability of p - // so 1 / modulesCount == p^31 - // <=> p = sqrt31(1 / modulesCount) - // so we use a modulo of 1 / sqrt31(1 / modulesCount) - /** @type {WeakMap} */ - const moduleBits = new WeakMap(); - const modulesCount = compilation.modules.size; + return Template.asString([ + `${RuntimeGlobals.hasOwnProperty} = ${runtimeTemplate.returningFunction( + "Object.prototype.hasOwnProperty.call(obj, prop)", + "obj, prop" + )}` + ]); + } +} - // precalculate the modulo values for each bit - const modulo = 1 / Math.pow(1 / modulesCount, 1 / 31); - const modulos = Array.from( - { length: 31 }, - (x, i) => Math.pow(modulo, i) | 0 - ); +module.exports = HasOwnPropertyRuntimeModule; - // iterate all modules to generate bit values - let i = 0; - for (const module of compilation.modules) { - let bit = 30; - while (i % modulos[bit] !== 0) { - bit--; - } - moduleBits.set(module, 1 << bit); - i++; - } - // iterate all chunks to generate bitmaps - /** @type {WeakMap} */ - const chunkModulesHash = new WeakMap(); - for (const chunk of chunks) { - let hash = 0; - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - hash |= moduleBits.get(module); - } - chunkModulesHash.set(chunk, hash); - } - - for (const chunkA of chunks) { - const chunkAHash = chunkModulesHash.get(chunkA); - const chunkAModulesCount = - chunkGraph.getNumberOfChunkModules(chunkA); - if (chunkAModulesCount === 0) continue; - let bestModule = undefined; - for (const module of chunkGraph.getChunkModulesIterable(chunkA)) { - if ( - bestModule === undefined || - chunkGraph.getNumberOfModuleChunks(bestModule) > - chunkGraph.getNumberOfModuleChunks(module) - ) - bestModule = module; - } - loopB: for (const chunkB of chunkGraph.getModuleChunksIterable( - bestModule - )) { - // as we iterate the same iterables twice - // skip if we find ourselves - if (chunkA === chunkB) continue; +/***/ }), - const chunkBModulesCount = - chunkGraph.getNumberOfChunkModules(chunkB); +/***/ 82444: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // ids for empty chunks are not included - if (chunkBModulesCount === 0) continue; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - // instead of swapping A and B just bail - // as we loop twice the current A will be B and B then A - if (chunkAModulesCount > chunkBModulesCount) continue; - // is chunkA in chunkB? - // we do a cheap check for the hash value - const chunkBHash = chunkModulesHash.get(chunkB); - if ((chunkBHash & chunkAHash) !== chunkAHash) continue; +const RuntimeModule = __webpack_require__(16963); - // compare all modules - for (const m of chunkGraph.getChunkModulesIterable(chunkA)) { - if (!chunkGraph.isModuleInChunk(m, chunkB)) continue loopB; - } - chunkB.ids.push(chunkA.id); - } - } - } - ); - }); +class HelperRuntimeModule extends RuntimeModule { + /** + * @param {string} name a readable name + */ + constructor(name) { + super(name); } } -module.exports = FlagIncludedChunksPlugin; + +module.exports = HelperRuntimeModule; /***/ }), -/***/ 38988: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 19942: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov */ -const { UsageState } = __webpack_require__(63686); - -/** @typedef {import("estree").Node} AnyNode */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleGraphConnection").ConnectionState} ConnectionState */ -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ - -/** @typedef {Map | true>} InnerGraph */ -/** @typedef {function(boolean | Set | undefined): void} UsageCallback */ - -/** - * @typedef {Object} StateObject - * @property {InnerGraph} innerGraph - * @property {TopLevelSymbol=} currentTopLevelSymbol - * @property {Map>} usageCallbackMap - */ - -/** @typedef {false|StateObject} State */ - -/** @type {WeakMap} */ -const parserStateMap = new WeakMap(); -const topLevelSymbolTag = Symbol("top level symbol"); - -/** - * @param {ParserState} parserState parser state - * @returns {State} state - */ -function getState(parserState) { - return parserStateMap.get(parserState); -} - -/** - * @param {ParserState} parserState parser state - * @returns {void} - */ -exports.bailout = parserState => { - parserStateMap.set(parserState, false); -}; +const { SyncWaterfallHook } = __webpack_require__(6967); +const Compilation = __webpack_require__(85720); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const HelperRuntimeModule = __webpack_require__(82444); -/** - * @param {ParserState} parserState parser state - * @returns {void} - */ -exports.enable = parserState => { - const state = parserStateMap.get(parserState); - if (state === false) { - return; - } - parserStateMap.set(parserState, { - innerGraph: new Map(), - currentTopLevelSymbol: undefined, - usageCallbackMap: new Map() - }); -}; +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ /** - * @param {ParserState} parserState parser state - * @returns {boolean} true, when enabled + * @typedef {Object} LoadScriptCompilationHooks + * @property {SyncWaterfallHook<[string, Chunk]>} createScript */ -exports.isEnabled = parserState => { - const state = parserStateMap.get(parserState); - return !!state; -}; -/** - * @param {ParserState} state parser state - * @param {TopLevelSymbol | null} symbol the symbol, or null for all symbols - * @param {string | TopLevelSymbol | true} usage usage data - * @returns {void} - */ -exports.addUsage = (state, symbol, usage) => { - const innerGraphState = getState(state); +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); - if (innerGraphState) { - const { innerGraph } = innerGraphState; - const info = innerGraph.get(symbol); - if (usage === true) { - innerGraph.set(symbol, true); - } else if (info === undefined) { - innerGraph.set(symbol, new Set([usage])); - } else if (info !== true) { - info.add(usage); +class LoadScriptRuntimeModule extends HelperRuntimeModule { + /** + * @param {Compilation} compilation the compilation + * @returns {LoadScriptCompilationHooks} hooks + */ + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); } - } -}; - -/** - * @param {JavascriptParser} parser the parser - * @param {string} name name of variable - * @param {string | TopLevelSymbol | true} usage usage data - * @returns {void} - */ -exports.addVariableUsage = (parser, name, usage) => { - const symbol = - /** @type {TopLevelSymbol} */ ( - parser.getTagData(name, topLevelSymbolTag) - ) || exports.tagTopLevelSymbol(parser, name); - if (symbol) { - exports.addUsage(parser.state, symbol, usage); - } -}; - -/** - * @param {ParserState} state parser state - * @returns {void} - */ -exports.inferDependencyUsage = state => { - const innerGraphState = getState(state); - - if (!innerGraphState) { - return; - } - - const { innerGraph, usageCallbackMap } = innerGraphState; - const processed = new Map(); - // flatten graph to terminal nodes (string, undefined or true) - const nonTerminal = new Set(innerGraph.keys()); - while (nonTerminal.size > 0) { - for (const key of nonTerminal) { - /** @type {Set | true} */ - let newSet = new Set(); - let isTerminal = true; - const value = innerGraph.get(key); - let alreadyProcessed = processed.get(key); - if (alreadyProcessed === undefined) { - alreadyProcessed = new Set(); - processed.set(key, alreadyProcessed); - } - if (value !== true && value !== undefined) { - for (const item of value) { - alreadyProcessed.add(item); - } - for (const item of value) { - if (typeof item === "string") { - newSet.add(item); - } else { - const itemValue = innerGraph.get(item); - if (itemValue === true) { - newSet = true; - break; - } - if (itemValue !== undefined) { - for (const i of itemValue) { - if (i === key) continue; - if (alreadyProcessed.has(i)) continue; - newSet.add(i); - if (typeof i !== "string") { - isTerminal = false; - } - } - } - } - } - if (newSet === true) { - innerGraph.set(key, true); - } else if (newSet.size === 0) { - innerGraph.set(key, undefined); - } else { - innerGraph.set(key, newSet); - } - } - if (isTerminal) { - nonTerminal.delete(key); - - // For the global key, merge with all other keys - if (key === null) { - const globalValue = innerGraph.get(null); - if (globalValue) { - for (const [key, value] of innerGraph) { - if (key !== null && value !== true) { - if (globalValue === true) { - innerGraph.set(key, true); - } else { - const newSet = new Set(value); - for (const item of globalValue) { - newSet.add(item); - } - innerGraph.set(key, newSet); - } - } - } - } - } - } + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + createScript: new SyncWaterfallHook(["source", "chunk"]) + }; + compilationHooksMap.set(compilation, hooks); } + return hooks; } - /** @type {Map>} */ - for (const [symbol, callbacks] of usageCallbackMap) { - const usage = /** @type {true | Set | undefined} */ ( - innerGraph.get(symbol) - ); - for (const callback of callbacks) { - callback(usage === undefined ? false : usage); - } + /** + * @param {boolean=} withCreateScriptUrl use create script url for trusted types + */ + constructor(withCreateScriptUrl) { + super("load script"); + this._withCreateScriptUrl = withCreateScriptUrl; } -}; -/** - * @param {ParserState} state parser state - * @param {UsageCallback} onUsageCallback on usage callback - */ -exports.onUsage = (state, onUsageCallback) => { - const innerGraphState = getState(state); + /** + * @returns {string} runtime code + */ + generate() { + const { compilation } = this; + const { runtimeTemplate, outputOptions } = compilation; + const { + scriptType, + chunkLoadTimeout: loadTimeout, + crossOriginLoading, + uniqueName, + charset + } = outputOptions; + const fn = RuntimeGlobals.loadScript; - if (innerGraphState) { - const { usageCallbackMap, currentTopLevelSymbol } = innerGraphState; - if (currentTopLevelSymbol) { - let callbacks = usageCallbackMap.get(currentTopLevelSymbol); + const { createScript } = + LoadScriptRuntimeModule.getCompilationHooks(compilation); - if (callbacks === undefined) { - callbacks = new Set(); - usageCallbackMap.set(currentTopLevelSymbol, callbacks); - } + const code = Template.asString([ + "script = document.createElement('script');", + scriptType ? `script.type = ${JSON.stringify(scriptType)};` : "", + charset ? "script.charset = 'utf-8';" : "", + `script.timeout = ${loadTimeout / 1000};`, + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `script.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + uniqueName + ? 'script.setAttribute("data-webpack", dataWebpackPrefix + key);' + : "", + `script.src = ${ + this._withCreateScriptUrl + ? `${RuntimeGlobals.createScriptUrl}(url)` + : "url" + };`, + crossOriginLoading + ? Template.asString([ + "if (script.src.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` + ), + "}" + ]) + : "" + ]); - callbacks.add(onUsageCallback); - } else { - onUsageCallback(true); - } - } else { - onUsageCallback(undefined); + return Template.asString([ + "var inProgress = {};", + uniqueName + ? `var dataWebpackPrefix = ${JSON.stringify(uniqueName + ":")};` + : "// data-webpack is not used as build has no uniqueName", + "// loadScript function to load a script via script tag", + `${fn} = ${runtimeTemplate.basicFunction("url, done, key, chunkId", [ + "if(inProgress[url]) { inProgress[url].push(done); return; }", + "var script, needAttach;", + "if(key !== undefined) {", + Template.indent([ + 'var scripts = document.getElementsByTagName("script");', + "for(var i = 0; i < scripts.length; i++) {", + Template.indent([ + "var s = scripts[i];", + `if(s.getAttribute("src") == url${ + uniqueName + ? ' || s.getAttribute("data-webpack") == dataWebpackPrefix + key' + : "" + }) { script = s; break; }` + ]), + "}" + ]), + "}", + "if(!script) {", + Template.indent([ + "needAttach = true;", + createScript.call(code, this.chunk) + ]), + "}", + "inProgress[url] = [done];", + "var onScriptComplete = " + + runtimeTemplate.basicFunction( + "prev, event", + Template.asString([ + "// avoid mem leaks in IE.", + "script.onerror = script.onload = null;", + "clearTimeout(timeout);", + "var doneFns = inProgress[url];", + "delete inProgress[url];", + "script.parentNode && script.parentNode.removeChild(script);", + `doneFns && doneFns.forEach(${runtimeTemplate.returningFunction( + "fn(event)", + "fn" + )});`, + "if(prev) return prev(event);" + ]) + ), + ";", + `var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), ${loadTimeout});`, + "script.onerror = onScriptComplete.bind(null, script.onerror);", + "script.onload = onScriptComplete.bind(null, script.onload);", + "needAttach && document.head.appendChild(script);" + ])};` + ]); } -}; - -/** - * @param {ParserState} state parser state - * @param {TopLevelSymbol} symbol the symbol - */ -exports.setTopLevelSymbol = (state, symbol) => { - const innerGraphState = getState(state); +} - if (innerGraphState) { - innerGraphState.currentTopLevelSymbol = symbol; - } -}; +module.exports = LoadScriptRuntimeModule; -/** - * @param {ParserState} state parser state - * @returns {TopLevelSymbol|void} usage data - */ -exports.getTopLevelSymbol = state => { - const innerGraphState = getState(state); - if (innerGraphState) { - return innerGraphState.currentTopLevelSymbol; - } -}; +/***/ }), -/** - * @param {JavascriptParser} parser parser - * @param {string} name name of variable - * @returns {TopLevelSymbol} symbol - */ -exports.tagTopLevelSymbol = (parser, name) => { - const innerGraphState = getState(parser.state); - if (!innerGraphState) return; +/***/ 65714: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - parser.defineVariable(name); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - const existingTag = /** @type {TopLevelSymbol} */ ( - parser.getTagData(name, topLevelSymbolTag) - ); - if (existingTag) { - return existingTag; - } - const fn = new TopLevelSymbol(name); - parser.tagVariable(name, topLevelSymbolTag, fn); - return fn; -}; -/** - * @param {Dependency} dependency the dependency - * @param {Set | boolean} usedByExports usedByExports info - * @param {ModuleGraph} moduleGraph moduleGraph - * @param {RuntimeSpec} runtime runtime - * @returns {boolean} false, when unused. Otherwise true - */ -exports.isDependencyUsedByExports = ( - dependency, - usedByExports, - moduleGraph, - runtime -) => { - if (usedByExports === false) return false; - if (usedByExports !== true && usedByExports !== undefined) { - const selfModule = moduleGraph.getParentModule(dependency); - const exportsInfo = moduleGraph.getExportsInfo(selfModule); - let used = false; - for (const exportName of usedByExports) { - if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) - used = true; - } - if (!used) return false; - } - return true; -}; +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const HelperRuntimeModule = __webpack_require__(82444); -/** - * @param {Dependency} dependency the dependency - * @param {Set | boolean} usedByExports usedByExports info - * @param {ModuleGraph} moduleGraph moduleGraph - * @returns {null | false | function(ModuleGraphConnection, RuntimeSpec): ConnectionState} function to determine if the connection is active - */ -exports.getDependencyUsedByExportsCondition = ( - dependency, - usedByExports, - moduleGraph -) => { - if (usedByExports === false) return false; - if (usedByExports !== true && usedByExports !== undefined) { - const selfModule = moduleGraph.getParentModule(dependency); - const exportsInfo = moduleGraph.getExportsInfo(selfModule); - return (connections, runtime) => { - for (const exportName of usedByExports) { - if (exportsInfo.getUsed(exportName, runtime) !== UsageState.Unused) - return true; - } - return false; - }; +class MakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { + constructor() { + super("make namespace object"); } - return null; -}; -class TopLevelSymbol { /** - * @param {string} name name of the variable + * @returns {string} runtime code */ - constructor(name) { - this.name = name; + generate() { + const { runtimeTemplate } = this.compilation; + const fn = RuntimeGlobals.makeNamespaceObject; + return Template.asString([ + "// define __esModule on exports", + `${fn} = ${runtimeTemplate.basicFunction("exports", [ + "if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {", + Template.indent([ + "Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });" + ]), + "}", + "Object.defineProperty(exports, '__esModule', { value: true });" + ])};` + ]); } } -exports.TopLevelSymbol = TopLevelSymbol; -exports.topLevelSymbolTag = topLevelSymbolTag; +module.exports = MakeNamespaceObjectRuntimeModule; /***/ }), -/***/ 28758: +/***/ 44518: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const PureExpressionDependency = __webpack_require__(55799); -const InnerGraph = __webpack_require__(38988); - -/** @typedef {import("estree").ClassDeclaration} ClassDeclarationNode */ -/** @typedef {import("estree").ClassExpression} ClassExpressionNode */ -/** @typedef {import("estree").Node} Node */ -/** @typedef {import("estree").VariableDeclarator} VariableDeclaratorNode */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../dependencies/HarmonyImportSpecifierDependency")} HarmonyImportSpecifierDependency */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ -/** @typedef {import("./InnerGraph").InnerGraph} InnerGraph */ -/** @typedef {import("./InnerGraph").TopLevelSymbol} TopLevelSymbol */ +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); -const { topLevelSymbolTag } = InnerGraph; +class OnChunksLoadedRuntimeModule extends RuntimeModule { + constructor() { + super("chunk loaded"); + } -class InnerGraphPlugin { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @returns {string} runtime code */ - apply(compiler) { - compiler.hooks.compilation.tap( - "InnerGraphPlugin", - (compilation, { normalModuleFactory }) => { - const logger = compilation.getLogger("webpack.InnerGraphPlugin"); + generate() { + const { compilation } = this; + const { runtimeTemplate } = compilation; + return Template.asString([ + "var deferred = [];", + `${RuntimeGlobals.onChunksLoaded} = ${runtimeTemplate.basicFunction( + "result, chunkIds, fn, priority", + [ + "if(chunkIds) {", + Template.indent([ + "priority = priority || 0;", + "for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];", + "deferred[i] = [chunkIds, fn, priority];", + "return;" + ]), + "}", + "var notFulfilled = Infinity;", + "for (var i = 0; i < deferred.length; i++) {", + Template.indent([ + runtimeTemplate.destructureArray( + ["chunkIds", "fn", "priority"], + "deferred[i]" + ), + "var fulfilled = true;", + "for (var j = 0; j < chunkIds.length; j++) {", + Template.indent([ + `if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(${ + RuntimeGlobals.onChunksLoaded + }).every(${runtimeTemplate.returningFunction( + `${RuntimeGlobals.onChunksLoaded}[key](chunkIds[j])`, + "key" + )})) {`, + Template.indent(["chunkIds.splice(j--, 1);"]), + "} else {", + Template.indent([ + "fulfilled = false;", + "if(priority < notFulfilled) notFulfilled = priority;" + ]), + "}" + ]), + "}", + "if(fulfilled) {", + Template.indent([ + "deferred.splice(i--, 1)", + "var r = fn();", + "if (r !== undefined) result = r;" + ]), + "}" + ]), + "}", + "return result;" + ] + )};` + ]); + } +} - compilation.dependencyTemplates.set( - PureExpressionDependency, - new PureExpressionDependency.Template() - ); +module.exports = OnChunksLoadedRuntimeModule; - /** - * @param {JavascriptParser} parser the parser - * @param {Object} parserOptions options - * @returns {void} - */ - const handler = (parser, parserOptions) => { - const onUsageSuper = sup => { - InnerGraph.onUsage(parser.state, usedByExports => { - switch (usedByExports) { - case undefined: - case true: - return; - default: { - const dep = new PureExpressionDependency(sup.range); - dep.loc = sup.loc; - dep.usedByExports = usedByExports; - parser.state.module.addDependency(dep); - break; - } - } - }); - }; - parser.hooks.program.tap("InnerGraphPlugin", () => { - InnerGraph.enable(parser.state); - }); +/***/ }), - parser.hooks.finish.tap("InnerGraphPlugin", () => { - if (!InnerGraph.isEnabled(parser.state)) return; +/***/ 56030: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - logger.time("infer dependency usage"); - InnerGraph.inferDependencyUsage(parser.state); - logger.timeAggregate("infer dependency usage"); - }); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - // During prewalking the following datastructures are filled with - // nodes that have a TopLevelSymbol assigned and - // variables are tagged with the assigned TopLevelSymbol - // We differ 3 types of nodes: - // 1. full statements (export default, function declaration) - // 2. classes (class declaration, class expression) - // 3. variable declarators (const x = ...) - /** @type {WeakMap} */ - const statementWithTopLevelSymbol = new WeakMap(); - /** @type {WeakMap} */ - const statementPurePart = new WeakMap(); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); - /** @type {WeakMap} */ - const classWithTopLevelSymbol = new WeakMap(); +class PublicPathRuntimeModule extends RuntimeModule { + constructor(publicPath) { + super("publicPath", RuntimeModule.STAGE_BASIC); + this.publicPath = publicPath; + } - /** @type {WeakMap} */ - const declWithTopLevelSymbol = new WeakMap(); - /** @type {WeakSet} */ - const pureDeclarators = new WeakSet(); + /** + * @returns {string} runtime code + */ + generate() { + const { compilation, publicPath } = this; - // The following hooks are used during prewalking: + return `${RuntimeGlobals.publicPath} = ${JSON.stringify( + compilation.getPath(publicPath || "", { + hash: compilation.hash || "XXXX" + }) + )};`; + } +} - parser.hooks.preStatement.tap("InnerGraphPlugin", statement => { - if (!InnerGraph.isEnabled(parser.state)) return; +module.exports = PublicPathRuntimeModule; - if (parser.scope.topLevelScope === true) { - if (statement.type === "FunctionDeclaration") { - const name = statement.id ? statement.id.name : "*default*"; - const fn = InnerGraph.tagTopLevelSymbol(parser, name); - statementWithTopLevelSymbol.set(statement, fn); - return true; - } - } - }); - parser.hooks.blockPreStatement.tap("InnerGraphPlugin", statement => { - if (!InnerGraph.isEnabled(parser.state)) return; +/***/ }), - if (parser.scope.topLevelScope === true) { - if (statement.type === "ClassDeclaration") { - const name = statement.id ? statement.id.name : "*default*"; - const fn = InnerGraph.tagTopLevelSymbol(parser, name); - classWithTopLevelSymbol.set(statement, fn); - return true; - } - if (statement.type === "ExportDefaultDeclaration") { - const name = "*default*"; - const fn = InnerGraph.tagTopLevelSymbol(parser, name); - const decl = statement.declaration; - if ( - decl.type === "ClassExpression" || - decl.type === "ClassDeclaration" - ) { - classWithTopLevelSymbol.set(decl, fn); - } else if (parser.isPure(decl, statement.range[0])) { - statementWithTopLevelSymbol.set(statement, fn); - if ( - !decl.type.endsWith("FunctionExpression") && - !decl.type.endsWith("Declaration") && - decl.type !== "Literal" - ) { - statementPurePart.set(statement, decl); - } - } - } - } - }); +/***/ 4537: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - parser.hooks.preDeclarator.tap( - "InnerGraphPlugin", - (decl, statement) => { - if (!InnerGraph.isEnabled(parser.state)) return; - if ( - parser.scope.topLevelScope === true && - decl.init && - decl.id.type === "Identifier" - ) { - const name = decl.id.name; - if (decl.init.type === "ClassExpression") { - const fn = InnerGraph.tagTopLevelSymbol(parser, name); - classWithTopLevelSymbol.set(decl.init, fn); - } else if (parser.isPure(decl.init, decl.id.range[1])) { - const fn = InnerGraph.tagTopLevelSymbol(parser, name); - declWithTopLevelSymbol.set(decl, fn); - if ( - !decl.init.type.endsWith("FunctionExpression") && - decl.init.type !== "Literal" - ) { - pureDeclarators.add(decl); - } - return true; - } - } - } - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - // During real walking we set the TopLevelSymbol state to the assigned - // TopLevelSymbol by using the fill datastructures. - // In addition to tracking TopLevelSymbols, we sometimes need to - // add a PureExpressionDependency. This is needed to skip execution - // of pure expressions, even when they are not dropped due to - // minimizing. Otherwise symbols used there might not exist anymore - // as they are removed as unused by this optimization - // When we find a reference to a TopLevelSymbol, we register a - // TopLevelSymbol dependency from TopLevelSymbol in state to the - // referenced TopLevelSymbol. This way we get a graph of all - // TopLevelSymbols. +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const HelperRuntimeModule = __webpack_require__(82444); - // The following hooks are called during walking: +class RelativeUrlRuntimeModule extends HelperRuntimeModule { + constructor() { + super("relative url"); + } - parser.hooks.statement.tap("InnerGraphPlugin", statement => { - if (!InnerGraph.isEnabled(parser.state)) return; - if (parser.scope.topLevelScope === true) { - InnerGraph.setTopLevelSymbol(parser.state, undefined); + /** + * @returns {string} runtime code + */ + generate() { + const { runtimeTemplate } = this.compilation; + return Template.asString([ + `${RuntimeGlobals.relativeUrl} = function RelativeURL(url) {`, + Template.indent([ + 'var realUrl = new URL(url, "x:/");', + "var values = {};", + "for (var key in realUrl) values[key] = realUrl[key];", + "values.href = url;", + 'values.pathname = url.replace(/[?#].*/, "");', + 'values.origin = values.protocol = "";', + `values.toString = values.toJSON = ${runtimeTemplate.returningFunction( + "url" + )};`, + "for (var key in values) Object.defineProperty(this, key, { enumerable: true, configurable: true, value: values[key] });" + ]), + "};", + `${RuntimeGlobals.relativeUrl}.prototype = URL.prototype;` + ]); + } +} - const fn = statementWithTopLevelSymbol.get(statement); - if (fn) { - InnerGraph.setTopLevelSymbol(parser.state, fn); - const purePart = statementPurePart.get(statement); - if (purePart) { - InnerGraph.onUsage(parser.state, usedByExports => { - switch (usedByExports) { - case undefined: - case true: - return; - default: { - const dep = new PureExpressionDependency( - purePart.range - ); - dep.loc = statement.loc; - dep.usedByExports = usedByExports; - parser.state.module.addDependency(dep); - break; - } - } - }); - } - } - } - }); +module.exports = RelativeUrlRuntimeModule; - parser.hooks.classExtendsExpression.tap( - "InnerGraphPlugin", - (expr, statement) => { - if (!InnerGraph.isEnabled(parser.state)) return; - if (parser.scope.topLevelScope === true) { - const fn = classWithTopLevelSymbol.get(statement); - if ( - fn && - parser.isPure( - expr, - statement.id ? statement.id.range[1] : statement.range[0] - ) - ) { - InnerGraph.setTopLevelSymbol(parser.state, fn); - onUsageSuper(expr); - } - } - } - ); - parser.hooks.classBodyElement.tap( - "InnerGraphPlugin", - (element, classDefinition) => { - if (!InnerGraph.isEnabled(parser.state)) return; - if (parser.scope.topLevelScope === true) { - const fn = classWithTopLevelSymbol.get(classDefinition); - if (fn) { - InnerGraph.setTopLevelSymbol(parser.state, undefined); - } - } - } - ); +/***/ }), - parser.hooks.classBodyValue.tap( - "InnerGraphPlugin", - (expression, element, classDefinition) => { - if (!InnerGraph.isEnabled(parser.state)) return; - if (parser.scope.topLevelScope === true) { - const fn = classWithTopLevelSymbol.get(classDefinition); - if (fn) { - if ( - !element.static || - parser.isPure( - expression, - element.key ? element.key.range[1] : element.range[0] - ) - ) { - InnerGraph.setTopLevelSymbol(parser.state, fn); - if (element.type !== "MethodDefinition" && element.static) { - InnerGraph.onUsage(parser.state, usedByExports => { - switch (usedByExports) { - case undefined: - case true: - return; - default: { - const dep = new PureExpressionDependency( - expression.range - ); - dep.loc = expression.loc; - dep.usedByExports = usedByExports; - parser.state.module.addDependency(dep); - break; - } - } - }); - } - } else { - InnerGraph.setTopLevelSymbol(parser.state, undefined); - } - } - } - } - ); +/***/ 97115: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - parser.hooks.declarator.tap("InnerGraphPlugin", (decl, statement) => { - if (!InnerGraph.isEnabled(parser.state)) return; - const fn = declWithTopLevelSymbol.get(decl); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - if (fn) { - InnerGraph.setTopLevelSymbol(parser.state, fn); - if (pureDeclarators.has(decl)) { - if (decl.init.type === "ClassExpression") { - if (decl.init.superClass) { - onUsageSuper(decl.init.superClass); - } - } else { - InnerGraph.onUsage(parser.state, usedByExports => { - switch (usedByExports) { - case undefined: - case true: - return; - default: { - const dep = new PureExpressionDependency( - decl.init.range - ); - dep.loc = decl.loc; - dep.usedByExports = usedByExports; - parser.state.module.addDependency(dep); - break; - } - } - }); - } - } - parser.walkExpression(decl.init); - InnerGraph.setTopLevelSymbol(parser.state, undefined); - return true; - } - }); - parser.hooks.expression - .for(topLevelSymbolTag) - .tap("InnerGraphPlugin", () => { - const topLevelSymbol = /** @type {TopLevelSymbol} */ ( - parser.currentTagData - ); - const currentTopLevelSymbol = InnerGraph.getTopLevelSymbol( - parser.state - ); - InnerGraph.addUsage( - parser.state, - topLevelSymbol, - currentTopLevelSymbol || true - ); - }); - parser.hooks.assign - .for(topLevelSymbolTag) - .tap("InnerGraphPlugin", expr => { - if (!InnerGraph.isEnabled(parser.state)) return; - if (expr.operator === "=") return true; - }); - }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("InnerGraphPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("InnerGraphPlugin", handler); - compilation.hooks.finishModules.tap("InnerGraphPlugin", () => { - logger.timeAggregateEnd("infer dependency usage"); - }); - } - ); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); + +class RuntimeIdRuntimeModule extends RuntimeModule { + constructor() { + super("runtimeId"); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { chunkGraph, chunk } = this; + const runtime = chunk.runtime; + if (typeof runtime !== "string") + throw new Error("RuntimeIdRuntimeModule must be in a single runtime"); + const id = chunkGraph.getRuntimeId(runtime); + return `${RuntimeGlobals.runtimeId} = ${JSON.stringify(id)};`; } } -module.exports = InnerGraphPlugin; +module.exports = RuntimeIdRuntimeModule; /***/ }), -/***/ 83608: +/***/ 22339: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const { STAGE_ADVANCED } = __webpack_require__(80057); -const LazyBucketSortedSet = __webpack_require__(48424); -const { compareChunks } = __webpack_require__(29579); -const createSchemaValidation = __webpack_require__(32540); +const RuntimeGlobals = __webpack_require__(16475); +const StartupChunkDependenciesRuntimeModule = __webpack_require__(38157); +const StartupEntrypointRuntimeModule = __webpack_require__(97672); -/** @typedef {import("../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions} LimitChunkCountPluginOptions */ -/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Compiler")} Compiler */ -const validate = createSchemaValidation( - __webpack_require__(36557), - () => __webpack_require__(30837), - { - name: "Limit Chunk Count Plugin", - baseDataPath: "options" - } -); - -/** - * @typedef {Object} ChunkCombination - * @property {boolean} deleted this is set to true when combination was removed - * @property {number} sizeDiff - * @property {number} integratedSize - * @property {Chunk} a - * @property {Chunk} b - * @property {number} aIdx - * @property {number} bIdx - * @property {number} aSize - * @property {number} bSize - */ - -const addToSetMap = (map, key, value) => { - const set = map.get(key); - if (set === undefined) { - map.set(key, new Set([value])); - } else { - set.add(value); - } -}; - -class LimitChunkCountPlugin { - /** - * @param {LimitChunkCountPluginOptions=} options options object - */ +class StartupChunkDependenciesPlugin { constructor(options) { - validate(options); - this.options = options; + this.chunkLoading = options.chunkLoading; + this.asyncChunkLoading = + typeof options.asyncChunkLoading === "boolean" + ? options.asyncChunkLoading + : true; } /** - * @param {Compiler} compiler the webpack compiler + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap("LimitChunkCountPlugin", compilation => { - compilation.hooks.optimizeChunks.tap( - { - name: "LimitChunkCountPlugin", - stage: STAGE_ADVANCED - }, - chunks => { - const chunkGraph = compilation.chunkGraph; - const maxChunks = options.maxChunks; - if (!maxChunks) return; - if (maxChunks < 1) return; - if (compilation.chunks.size <= maxChunks) return; - - let remainingChunksToMerge = compilation.chunks.size - maxChunks; - - // order chunks in a deterministic way - const compareChunksWithGraph = compareChunks(chunkGraph); - const orderedChunks = Array.from(chunks).sort(compareChunksWithGraph); - - // create a lazy sorted data structure to keep all combinations - // this is large. Size = chunks * (chunks - 1) / 2 - // It uses a multi layer bucket sort plus normal sort in the last layer - // It's also lazy so only accessed buckets are sorted - const combinations = new LazyBucketSortedSet( - // Layer 1: ordered by largest size benefit - c => c.sizeDiff, - (a, b) => b - a, - // Layer 2: ordered by smallest combined size - c => c.integratedSize, - (a, b) => a - b, - // Layer 3: ordered by position difference in orderedChunk (-> to be deterministic) - c => c.bIdx - c.aIdx, - (a, b) => a - b, - // Layer 4: ordered by position in orderedChunk (-> to be deterministic) - (a, b) => a.bIdx - b.bIdx - ); - - // we keep a mapping from chunk to all combinations - // but this mapping is not kept up-to-date with deletions - // so `deleted` flag need to be considered when iterating this - /** @type {Map>} */ - const combinationsByChunk = new Map(); - - orderedChunks.forEach((b, bIdx) => { - // create combination pairs with size and integrated size - for (let aIdx = 0; aIdx < bIdx; aIdx++) { - const a = orderedChunks[aIdx]; - // filter pairs that can not be integrated! - if (!chunkGraph.canChunksBeIntegrated(a, b)) continue; - - const integratedSize = chunkGraph.getIntegratedChunksSize( - a, - b, - options + compiler.hooks.thisCompilation.tap( + "StartupChunkDependenciesPlugin", + compilation => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === this.chunkLoading; + }; + compilation.hooks.additionalTreeRuntimeRequirements.tap( + "StartupChunkDependenciesPlugin", + (chunk, set, { chunkGraph }) => { + if (!isEnabledForChunk(chunk)) return; + if (chunkGraph.hasChunkEntryDependentChunks(chunk)) { + set.add(RuntimeGlobals.startup); + set.add(RuntimeGlobals.ensureChunk); + set.add(RuntimeGlobals.ensureChunkIncludeEntries); + compilation.addRuntimeModule( + chunk, + new StartupChunkDependenciesRuntimeModule( + this.asyncChunkLoading + ) ); - - const aSize = chunkGraph.getChunkSize(a, options); - const bSize = chunkGraph.getChunkSize(b, options); - const c = { - deleted: false, - sizeDiff: aSize + bSize - integratedSize, - integratedSize, - a, - b, - aIdx, - bIdx, - aSize, - bSize - }; - combinations.add(c); - addToSetMap(combinationsByChunk, a, c); - addToSetMap(combinationsByChunk, b, c); } - return combinations; + } + ); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.startupEntrypoint) + .tap("StartupChunkDependenciesPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.require); + set.add(RuntimeGlobals.ensureChunk); + set.add(RuntimeGlobals.ensureChunkIncludeEntries); + compilation.addRuntimeModule( + chunk, + new StartupEntrypointRuntimeModule(this.asyncChunkLoading) + ); }); + } + ); + } +} - // list of modified chunks during this run - // combinations affected by this change are skipped to allow - // further optimizations - /** @type {Set} */ - const modifiedChunks = new Set(); +module.exports = StartupChunkDependenciesPlugin; - let changed = false; - // eslint-disable-next-line no-constant-condition - loop: while (true) { - const combination = combinations.popFirst(); - if (combination === undefined) break; - combination.deleted = true; - const { a, b, integratedSize } = combination; +/***/ }), - // skip over pair when - // one of the already merged chunks is a parent of one of the chunks - if (modifiedChunks.size > 0) { - const queue = new Set(a.groupsIterable); - for (const group of b.groupsIterable) { - queue.add(group); - } - for (const group of queue) { - for (const mChunk of modifiedChunks) { - if (mChunk !== a && mChunk !== b && mChunk.isInGroup(group)) { - // This is a potential pair which needs recalculation - // We can't do that now, but it merge before following pairs - // so we leave space for it, and consider chunks as modified - // just for the worse case - remainingChunksToMerge--; - if (remainingChunksToMerge <= 0) break loop; - modifiedChunks.add(a); - modifiedChunks.add(b); - continue loop; - } - } - for (const parent of group.parentsIterable) { - queue.add(parent); - } - } - } +/***/ 38157: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // merge the chunks - if (chunkGraph.canChunksBeIntegrated(a, b)) { - chunkGraph.integrateChunks(a, b); - compilation.chunks.delete(b); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // flag chunk a as modified as further optimization are possible for all children here - modifiedChunks.add(a); - changed = true; - remainingChunksToMerge--; - if (remainingChunksToMerge <= 0) break; - // Update all affected combinations - // delete all combination with the removed chunk - // we will use combinations with the kept chunk instead - for (const combination of combinationsByChunk.get(a)) { - if (combination.deleted) continue; - combination.deleted = true; - combinations.delete(combination); - } +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); - // Update combinations with the kept chunk with new sizes - for (const combination of combinationsByChunk.get(b)) { - if (combination.deleted) continue; - if (combination.a === b) { - if (!chunkGraph.canChunksBeIntegrated(a, combination.b)) { - combination.deleted = true; - combinations.delete(combination); - continue; - } - // Update size - const newIntegratedSize = chunkGraph.getIntegratedChunksSize( - a, - combination.b, - options - ); - const finishUpdate = combinations.startUpdate(combination); - combination.a = a; - combination.integratedSize = newIntegratedSize; - combination.aSize = integratedSize; - combination.sizeDiff = - combination.bSize + integratedSize - newIntegratedSize; - finishUpdate(); - } else if (combination.b === b) { - if (!chunkGraph.canChunksBeIntegrated(combination.a, a)) { - combination.deleted = true; - combinations.delete(combination); - continue; - } - // Update size - const newIntegratedSize = chunkGraph.getIntegratedChunksSize( - combination.a, - a, - options - ); +class StartupChunkDependenciesRuntimeModule extends RuntimeModule { + constructor(asyncChunkLoading) { + super("startup chunk dependencies", RuntimeModule.STAGE_TRIGGER); + this.asyncChunkLoading = asyncChunkLoading; + } - const finishUpdate = combinations.startUpdate(combination); - combination.b = a; - combination.integratedSize = newIntegratedSize; - combination.bSize = integratedSize; - combination.sizeDiff = - integratedSize + combination.aSize - newIntegratedSize; - finishUpdate(); - } - } - combinationsByChunk.set(a, combinationsByChunk.get(b)); - combinationsByChunk.delete(b); - } - } - if (changed) return true; - } - ); + /** + * @returns {string} runtime code + */ + generate() { + const { chunkGraph, chunk, compilation } = this; + const { runtimeTemplate } = compilation; + const chunkIds = Array.from( + chunkGraph.getChunkEntryDependentChunksIterable(chunk) + ).map(chunk => { + return chunk.id; }); + return Template.asString([ + `var next = ${RuntimeGlobals.startup};`, + `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction( + "", + !this.asyncChunkLoading + ? chunkIds + .map( + id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)});` + ) + .concat("return next();") + : chunkIds.length === 1 + ? `return ${RuntimeGlobals.ensureChunk}(${JSON.stringify( + chunkIds[0] + )}).then(next);` + : chunkIds.length > 2 + ? [ + // using map is shorter for 3 or more chunks + `return Promise.all(${JSON.stringify(chunkIds)}.map(${ + RuntimeGlobals.ensureChunk + }, __webpack_require__)).then(next);` + ] + : [ + // calling ensureChunk directly is shorter for 0 - 2 chunks + "return Promise.all([", + Template.indent( + chunkIds + .map( + id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)})` + ) + .join(",\n") + ), + "]).then(next);" + ] + )};` + ]); } } -module.exports = LimitChunkCountPlugin; + +module.exports = StartupChunkDependenciesRuntimeModule; /***/ }), -/***/ 27868: +/***/ 97672: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const { UsageState } = __webpack_require__(63686); -const { - numberToIdentifier, - NUMBER_OF_IDENTIFIER_START_CHARS, - NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS -} = __webpack_require__(39722); -const { assignDeterministicIds } = __webpack_require__(63290); -const { compareSelect, compareStringsNumeric } = __webpack_require__(29579); - -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../ExportsInfo")} ExportsInfo */ -/** @typedef {import("../ExportsInfo").ExportInfo} ExportInfo */ - -/** - * @param {ExportsInfo} exportsInfo exports info - * @returns {boolean} mangle is possible - */ -const canMangle = exportsInfo => { - if (exportsInfo.otherExportsInfo.getUsed(undefined) !== UsageState.Unused) - return false; - let hasSomethingToMangle = false; - for (const exportInfo of exportsInfo.exports) { - if (exportInfo.canMangle === true) { - hasSomethingToMangle = true; - } - } - return hasSomethingToMangle; -}; +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); -// Sort by name -const comparator = compareSelect(e => e.name, compareStringsNumeric); -/** - * @param {boolean} deterministic use deterministic names - * @param {ExportsInfo} exportsInfo exports info - * @param {boolean} isNamespace is namespace object - * @returns {void} - */ -const mangleExportsInfo = (deterministic, exportsInfo, isNamespace) => { - if (!canMangle(exportsInfo)) return; - const usedNames = new Set(); - /** @type {ExportInfo[]} */ - const mangleableExports = []; +/** @typedef {import("../MainTemplate")} MainTemplate */ - // Avoid to renamed exports that are not provided when - // 1. it's not a namespace export: non-provided exports can be found in prototype chain - // 2. there are other provided exports and deterministic mode is chosen: - // non-provided exports would break the determinism - let avoidMangleNonProvided = !isNamespace; - if (!avoidMangleNonProvided && deterministic) { - for (const exportInfo of exportsInfo.ownedExports) { - if (exportInfo.provided !== false) { - avoidMangleNonProvided = true; - break; - } - } - } - for (const exportInfo of exportsInfo.ownedExports) { - const name = exportInfo.name; - if (!exportInfo.hasUsedName()) { - if ( - // Can the export be mangled? - exportInfo.canMangle !== true || - // Never rename 1 char exports - (name.length === 1 && /^[a-zA-Z0-9_$]/.test(name)) || - // Don't rename 2 char exports in deterministic mode - (deterministic && - name.length === 2 && - /^[a-zA-Z_$][a-zA-Z0-9_$]|^[1-9][0-9]/.test(name)) || - // Don't rename exports that are not provided - (avoidMangleNonProvided && exportInfo.provided !== true) - ) { - exportInfo.setUsedName(name); - usedNames.add(name); - } else { - mangleableExports.push(exportInfo); - } - } - if (exportInfo.exportsInfoOwned) { - const used = exportInfo.getUsed(undefined); - if ( - used === UsageState.OnlyPropertiesUsed || - used === UsageState.Unused - ) { - mangleExportsInfo(deterministic, exportInfo.exportsInfo, false); - } - } - } - if (deterministic) { - assignDeterministicIds( - mangleableExports, - e => e.name, - comparator, - (e, id) => { - const name = numberToIdentifier(id); - const size = usedNames.size; - usedNames.add(name); - if (size === usedNames.size) return false; - e.setUsedName(name); - return true; - }, - [ - NUMBER_OF_IDENTIFIER_START_CHARS, - NUMBER_OF_IDENTIFIER_START_CHARS * - NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS - ], - NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS, - usedNames.size - ); - } else { - const usedExports = []; - const unusedExports = []; - for (const exportInfo of mangleableExports) { - if (exportInfo.getUsed(undefined) === UsageState.Unused) { - unusedExports.push(exportInfo); - } else { - usedExports.push(exportInfo); - } - } - usedExports.sort(comparator); - unusedExports.sort(comparator); - let i = 0; - for (const list of [usedExports, unusedExports]) { - for (const exportInfo of list) { - let name; - do { - name = numberToIdentifier(i++); - } while (usedNames.has(name)); - exportInfo.setUsedName(name); - } - } +class StartupEntrypointRuntimeModule extends RuntimeModule { + constructor(asyncChunkLoading) { + super("startup entrypoint"); + this.asyncChunkLoading = asyncChunkLoading; } -}; -class MangleExportsPlugin { - /** - * @param {boolean} deterministic use deterministic names - */ - constructor(deterministic) { - this._deterministic = deterministic; - } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @returns {string} runtime code */ - apply(compiler) { - const { _deterministic: deterministic } = this; - compiler.hooks.compilation.tap("MangleExportsPlugin", compilation => { - const moduleGraph = compilation.moduleGraph; - compilation.hooks.optimizeCodeGeneration.tap( - "MangleExportsPlugin", - modules => { - if (compilation.moduleMemCaches) { - throw new Error( - "optimization.mangleExports can't be used with cacheUnaffected as export mangling is a global effect" - ); - } - for (const module of modules) { - const isNamespace = - module.buildMeta && module.buildMeta.exportsType === "namespace"; - const exportsInfo = moduleGraph.getExportsInfo(module); - mangleExportsInfo(deterministic, exportsInfo, isNamespace); - } - } - ); - }); + generate() { + const { compilation } = this; + const { runtimeTemplate } = compilation; + return `${ + RuntimeGlobals.startupEntrypoint + } = ${runtimeTemplate.basicFunction("result, chunkIds, fn", [ + "// arguments: chunkIds, moduleId are deprecated", + "var moduleId = chunkIds;", + `if(!fn) chunkIds = result, fn = ${runtimeTemplate.returningFunction( + `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)` + )};`, + ...(this.asyncChunkLoading + ? [ + `return Promise.all(chunkIds.map(${ + RuntimeGlobals.ensureChunk + }, __webpack_require__)).then(${runtimeTemplate.basicFunction("", [ + "var r = fn();", + "return r === undefined ? result : r;" + ])})` + ] + : [ + `chunkIds.map(${RuntimeGlobals.ensureChunk}, __webpack_require__)`, + "var r = fn();", + "return r === undefined ? result : r;" + ]) + ])}`; } } -module.exports = MangleExportsPlugin; +module.exports = StartupEntrypointRuntimeModule; /***/ }), -/***/ 85067: +/***/ 80655: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const { STAGE_BASIC } = __webpack_require__(80057); -const { runtimeEqual } = __webpack_require__(17156); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Compilation")} Compilation */ + +class SystemContextRuntimeModule extends RuntimeModule { + constructor() { + super("__system_context__"); + } -class MergeDuplicateChunksPlugin { /** - * @param {Compiler} compiler the compiler - * @returns {void} + * @returns {string} runtime code */ - apply(compiler) { - compiler.hooks.compilation.tap( - "MergeDuplicateChunksPlugin", - compilation => { - compilation.hooks.optimizeChunks.tap( - { - name: "MergeDuplicateChunksPlugin", - stage: STAGE_BASIC - }, - chunks => { - const { chunkGraph, moduleGraph } = compilation; - - // remember already tested chunks for performance - const notDuplicates = new Set(); - - // for each chunk - for (const chunk of chunks) { - // track a Set of all chunk that could be duplicates - let possibleDuplicates; - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - if (possibleDuplicates === undefined) { - // when possibleDuplicates is not yet set, - // create a new Set from chunks of the current module - // including only chunks with the same number of modules - for (const dup of chunkGraph.getModuleChunksIterable( - module - )) { - if ( - dup !== chunk && - chunkGraph.getNumberOfChunkModules(chunk) === - chunkGraph.getNumberOfChunkModules(dup) && - !notDuplicates.has(dup) - ) { - // delay allocating the new Set until here, reduce memory pressure - if (possibleDuplicates === undefined) { - possibleDuplicates = new Set(); - } - possibleDuplicates.add(dup); - } - } - // when no chunk is possible we can break here - if (possibleDuplicates === undefined) break; - } else { - // validate existing possible duplicates - for (const dup of possibleDuplicates) { - // remove possible duplicate when module is not contained - if (!chunkGraph.isModuleInChunk(module, dup)) { - possibleDuplicates.delete(dup); - } - } - // when all chunks has been removed we can break here - if (possibleDuplicates.size === 0) break; - } - } - - // when we found duplicates - if ( - possibleDuplicates !== undefined && - possibleDuplicates.size > 0 - ) { - outer: for (const otherChunk of possibleDuplicates) { - if (otherChunk.hasRuntime() !== chunk.hasRuntime()) continue; - if (chunkGraph.getNumberOfEntryModules(chunk) > 0) continue; - if (chunkGraph.getNumberOfEntryModules(otherChunk) > 0) - continue; - if (!runtimeEqual(chunk.runtime, otherChunk.runtime)) { - for (const module of chunkGraph.getChunkModulesIterable( - chunk - )) { - const exportsInfo = moduleGraph.getExportsInfo(module); - if ( - !exportsInfo.isEquallyUsed( - chunk.runtime, - otherChunk.runtime - ) - ) { - continue outer; - } - } - } - // merge them - if (chunkGraph.canChunksBeIntegrated(chunk, otherChunk)) { - chunkGraph.integrateChunks(chunk, otherChunk); - compilation.chunks.delete(otherChunk); - } - } - } - - // don't check already processed chunks twice - notDuplicates.add(chunk); - } - } - ); - } - ); + generate() { + return `${RuntimeGlobals.systemContext} = __system_context__;`; } } -module.exports = MergeDuplicateChunksPlugin; + +module.exports = SystemContextRuntimeModule; /***/ }), -/***/ 53912: +/***/ 64820: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -110422,117 +109971,60 @@ module.exports = MergeDuplicateChunksPlugin; -const { STAGE_ADVANCED } = __webpack_require__(80057); -const createSchemaValidation = __webpack_require__(32540); +const NormalModule = __webpack_require__(39); -/** @typedef {import("../../declarations/plugins/optimize/MinChunkSizePlugin").MinChunkSizePluginOptions} MinChunkSizePluginOptions */ -/** @typedef {import("../Chunk")} Chunk */ /** @typedef {import("../Compiler")} Compiler */ -const validate = createSchemaValidation( - __webpack_require__(60135), - () => __webpack_require__(53850), - { - name: "Min Chunk Size Plugin", - baseDataPath: "options" - } -); +// data URL scheme: "data:text/javascript;charset=utf-8;base64,some-string" +// http://www.ietf.org/rfc/rfc2397.txt +const URIRegEx = /^data:([^;,]+)?((?:;[^;,]+)*?)(?:;(base64))?,(.*)$/i; -class MinChunkSizePlugin { - /** - * @param {MinChunkSizePluginOptions} options options object - */ - constructor(options) { - validate(options); - this.options = options; - } +const decodeDataURI = uri => { + const match = URIRegEx.exec(uri); + if (!match) return null; + const isBase64 = match[3]; + const body = match[4]; + return isBase64 + ? Buffer.from(body, "base64") + : Buffer.from(decodeURIComponent(body), "ascii"); +}; + +class DataUriPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - const options = this.options; - const minChunkSize = options.minChunkSize; - compiler.hooks.compilation.tap("MinChunkSizePlugin", compilation => { - compilation.hooks.optimizeChunks.tap( - { - name: "MinChunkSizePlugin", - stage: STAGE_ADVANCED - }, - chunks => { - const chunkGraph = compilation.chunkGraph; - const equalOptions = { - chunkOverhead: 1, - entryChunkMultiplicator: 1 - }; - - const chunkSizesMap = new Map(); - /** @type {[Chunk, Chunk][]} */ - const combinations = []; - /** @type {Chunk[]} */ - const smallChunks = []; - const visitedChunks = []; - for (const a of chunks) { - // check if one of the chunks sizes is smaller than the minChunkSize - // and filter pairs that can NOT be integrated! - if (chunkGraph.getChunkSize(a, equalOptions) < minChunkSize) { - smallChunks.push(a); - for (const b of visitedChunks) { - if (chunkGraph.canChunksBeIntegrated(b, a)) - combinations.push([b, a]); - } - } else { - for (const b of smallChunks) { - if (chunkGraph.canChunksBeIntegrated(b, a)) - combinations.push([b, a]); - } + compiler.hooks.compilation.tap( + "DataUriPlugin", + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.resolveForScheme + .for("data") + .tap("DataUriPlugin", resourceData => { + const match = URIRegEx.exec(resourceData.resource); + if (match) { + resourceData.data.mimetype = match[1] || ""; + resourceData.data.parameters = match[2] || ""; + resourceData.data.encoding = match[3] || false; + resourceData.data.encodedContent = match[4] || ""; } - chunkSizesMap.set(a, chunkGraph.getChunkSize(a, options)); - visitedChunks.push(a); - } - - const sortedSizeFilteredExtendedPairCombinations = combinations - .map(pair => { - // extend combination pairs with size and integrated size - const a = chunkSizesMap.get(pair[0]); - const b = chunkSizesMap.get(pair[1]); - const ab = chunkGraph.getIntegratedChunksSize( - pair[0], - pair[1], - options - ); - /** @type {[number, number, Chunk, Chunk]} */ - const extendedPair = [a + b - ab, ab, pair[0], pair[1]]; - return extendedPair; - }) - .sort((a, b) => { - // sadly javascript does an in place sort here - // sort by size - const diff = b[0] - a[0]; - if (diff !== 0) return diff; - return a[1] - b[1]; - }); - - if (sortedSizeFilteredExtendedPairCombinations.length === 0) return; - - const pair = sortedSizeFilteredExtendedPairCombinations[0]; - - chunkGraph.integrateChunks(pair[2], pair[3]); - compilation.chunks.delete(pair[3]); - return true; - } - ); - }); + }); + NormalModule.getCompilationHooks(compilation) + .readResourceForScheme.for("data") + .tap("DataUriPlugin", resource => decodeDataURI(resource)); + } + ); } } -module.exports = MinChunkSizePlugin; + +module.exports = DataUriPlugin; /***/ }), -/***/ 85305: +/***/ 57637: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -110543,34 +110035,53 @@ module.exports = MinChunkSizePlugin; -const SizeFormatHelpers = __webpack_require__(71070); -const WebpackError = __webpack_require__(53799); +const { URL, fileURLToPath } = __webpack_require__(57310); +const { NormalModule } = __webpack_require__(91919); -class MinMaxSizeWarning extends WebpackError { - constructor(keys, minSize, maxSize) { - let keysMessage = "Fallback cache group"; - if (keys) { - keysMessage = - keys.length > 1 - ? `Cache groups ${keys.sort().join(", ")}` - : `Cache group ${keys[0]}`; - } - super( - `SplitChunksPlugin\n` + - `${keysMessage}\n` + - `Configured minSize (${SizeFormatHelpers.formatSize(minSize)}) is ` + - `bigger than maxSize (${SizeFormatHelpers.formatSize(maxSize)}).\n` + - "This seem to be a invalid optimization.splitChunks configuration." +/** @typedef {import("../Compiler")} Compiler */ + +class FileUriPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "FileUriPlugin", + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.resolveForScheme + .for("file") + .tap("FileUriPlugin", resourceData => { + const url = new URL(resourceData.resource); + const path = fileURLToPath(url); + const query = url.search; + const fragment = url.hash; + resourceData.path = path; + resourceData.query = query; + resourceData.fragment = fragment; + resourceData.resource = path + query + fragment; + return true; + }); + const hooks = NormalModule.getCompilationHooks(compilation); + hooks.readResource + .for(undefined) + .tapAsync("FileUriPlugin", (loaderContext, callback) => { + const { resourcePath } = loaderContext; + loaderContext.addDependency(resourcePath); + loaderContext.fs.readFile(resourcePath, callback); + }); + } ); } } -module.exports = MinMaxSizeWarning; +module.exports = FileUriPlugin; /***/ }), -/***/ 74844: +/***/ 42110: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -110581,4047 +110092,3927 @@ module.exports = MinMaxSizeWarning; -const asyncLib = __webpack_require__(78175); -const ChunkGraph = __webpack_require__(64971); -const ModuleGraph = __webpack_require__(99988); -const { STAGE_DEFAULT } = __webpack_require__(80057); -const HarmonyImportDependency = __webpack_require__(57154); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const { - intersectRuntime, - mergeRuntimeOwned, - filterRuntime, - runtimeToString, - mergeRuntime -} = __webpack_require__(17156); -const ConcatenatedModule = __webpack_require__(97198); +const { extname, basename } = __webpack_require__(71017); +const { URL } = __webpack_require__(57310); +const { createGunzip, createBrotliDecompress, createInflate } = __webpack_require__(59796); +const NormalModule = __webpack_require__(39); +const createSchemaValidation = __webpack_require__(32540); +const createHash = __webpack_require__(49835); +const { mkdirp, dirname, join } = __webpack_require__(17139); +const memoize = __webpack_require__(78676); -/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../../declarations/plugins/schemes/HttpUriPlugin").HttpUriPluginOptions} HttpUriPluginOptions */ /** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +const getHttp = memoize(() => __webpack_require__(13685)); +const getHttps = memoize(() => __webpack_require__(95687)); + +/** @type {(() => void)[] | undefined} */ +let inProgressWrite = undefined; + +const validate = createSchemaValidation( + __webpack_require__(67263), + () => __webpack_require__(27256), + { + name: "Http Uri Plugin", + baseDataPath: "options" + } +); + +const toSafePath = str => + str + .replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, "") + .replace(/[^a-zA-Z0-9._-]+/g, "_"); + +const computeIntegrity = content => { + const hash = createHash("sha512"); + hash.update(content); + const integrity = "sha512-" + hash.digest("base64"); + return integrity; +}; + +const verifyIntegrity = (content, integrity) => { + if (integrity === "ignore") return true; + return computeIntegrity(content) === integrity; +}; /** - * @typedef {Object} Statistics - * @property {number} cached - * @property {number} alreadyInConfig - * @property {number} invalidModule - * @property {number} incorrectChunks - * @property {number} incorrectDependency - * @property {number} incorrectModuleDependency - * @property {number} incorrectChunksOfImporter - * @property {number} incorrectRuntimeCondition - * @property {number} importerFailed - * @property {number} added + * @param {string} str input + * @returns {Record} parsed */ - -const formatBailoutReason = msg => { - return "ModuleConcatenation bailout: " + msg; +const parseKeyValuePairs = str => { + /** @type {Record} */ + const result = {}; + for (const item of str.split(",")) { + const i = item.indexOf("="); + if (i >= 0) { + const key = item.slice(0, i).trim(); + const value = item.slice(i + 1).trim(); + result[key] = value; + } else { + const key = item.trim(); + if (!key) continue; + result[key] = key; + } + } + return result; }; -class ModuleConcatenationPlugin { - constructor(options) { - if (typeof options !== "object") options = {}; - this.options = options; +const parseCacheControl = (cacheControl, requestTime) => { + // When false resource is not stored in cache + let storeCache = true; + // When false resource is not stored in lockfile cache + let storeLock = true; + // Resource is only revalidated, after that timestamp and when upgrade is chosen + let validUntil = 0; + if (cacheControl) { + const parsed = parseKeyValuePairs(cacheControl); + if (parsed["no-cache"]) storeCache = storeLock = false; + if (parsed["max-age"] && !isNaN(+parsed["max-age"])) { + validUntil = requestTime + +parsed["max-age"] * 1000; + } + if (parsed["must-revalidate"]) validUntil = 0; } + return { + storeLock, + storeCache, + validUntil + }; +}; - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const { _backCompat: backCompat } = compiler; - compiler.hooks.compilation.tap("ModuleConcatenationPlugin", compilation => { - const moduleGraph = compilation.moduleGraph; - const bailoutReasonMap = new Map(); +/** + * @typedef {Object} LockfileEntry + * @property {string} resolved + * @property {string} integrity + * @property {string} contentType + */ - const setBailoutReason = (module, reason) => { - setInnerBailoutReason(module, reason); - moduleGraph - .getOptimizationBailout(module) - .push( - typeof reason === "function" - ? rs => formatBailoutReason(reason(rs)) - : formatBailoutReason(reason) - ); - }; +const areLockfileEntriesEqual = (a, b) => { + return ( + a.resolved === b.resolved && + a.integrity === b.integrity && + a.contentType === b.contentType + ); +}; - const setInnerBailoutReason = (module, reason) => { - bailoutReasonMap.set(module, reason); - }; +const entryToString = entry => { + return `resolved: ${entry.resolved}, integrity: ${entry.integrity}, contentType: ${entry.contentType}`; +}; - const getInnerBailoutReason = (module, requestShortener) => { - const reason = bailoutReasonMap.get(module); - if (typeof reason === "function") return reason(requestShortener); - return reason; - }; +class Lockfile { + constructor() { + this.version = 1; + /** @type {Map} */ + this.entries = new Map(); + } - const formatBailoutWarning = (module, problem) => requestShortener => { - if (typeof problem === "function") { - return formatBailoutReason( - `Cannot concat with ${module.readableIdentifier( - requestShortener - )}: ${problem(requestShortener)}` - ); - } - const reason = getInnerBailoutReason(module, requestShortener); - const reasonWithPrefix = reason ? `: ${reason}` : ""; - if (module === problem) { - return formatBailoutReason( - `Cannot concat with ${module.readableIdentifier( - requestShortener - )}${reasonWithPrefix}` - ); - } else { - return formatBailoutReason( - `Cannot concat with ${module.readableIdentifier( - requestShortener - )} because of ${problem.readableIdentifier( - requestShortener - )}${reasonWithPrefix}` - ); - } - }; - - compilation.hooks.optimizeChunkModules.tapAsync( - { - name: "ModuleConcatenationPlugin", - stage: STAGE_DEFAULT - }, - (allChunks, modules, callback) => { - const logger = compilation.getLogger( - "webpack.ModuleConcatenationPlugin" - ); - const { chunkGraph, moduleGraph } = compilation; - const relevantModules = []; - const possibleInners = new Set(); - const context = { - chunkGraph, - moduleGraph - }; - logger.time("select relevant modules"); - for (const module of modules) { - let canBeRoot = true; - let canBeInner = true; - - const bailoutReason = module.getConcatenationBailoutReason(context); - if (bailoutReason) { - setBailoutReason(module, bailoutReason); - continue; - } - - // Must not be an async module - if (moduleGraph.isAsync(module)) { - setBailoutReason(module, `Module is async`); - continue; - } - - // Must be in strict mode - if (!module.buildInfo.strict) { - setBailoutReason(module, `Module is not in strict mode`); - continue; - } + static parse(content) { + // TODO handle merge conflicts + const data = JSON.parse(content); + if (data.version !== 1) + throw new Error(`Unsupported lockfile version ${data.version}`); + const lockfile = new Lockfile(); + for (const key of Object.keys(data)) { + if (key === "version") continue; + const entry = data[key]; + lockfile.entries.set( + key, + typeof entry === "string" + ? entry + : { + resolved: key, + ...entry + } + ); + } + return lockfile; + } - // Module must be in any chunk (we don't want to do useless work) - if (chunkGraph.getNumberOfModuleChunks(module) === 0) { - setBailoutReason(module, "Module is not in any chunk"); - continue; - } + toString() { + let str = "{\n"; + const entries = Array.from(this.entries).sort(([a], [b]) => + a < b ? -1 : 1 + ); + for (const [key, entry] of entries) { + if (typeof entry === "string") { + str += ` ${JSON.stringify(key)}: ${JSON.stringify(entry)},\n`; + } else { + str += ` ${JSON.stringify(key)}: { `; + if (entry.resolved !== key) + str += `"resolved": ${JSON.stringify(entry.resolved)}, `; + str += `"integrity": ${JSON.stringify( + entry.integrity + )}, "contentType": ${JSON.stringify(entry.contentType)} },\n`; + } + } + str += ` "version": ${this.version}\n}\n`; + return str; + } +} - // Exports must be known (and not dynamic) - const exportsInfo = moduleGraph.getExportsInfo(module); - const relevantExports = exportsInfo.getRelevantExports(undefined); - const unknownReexports = relevantExports.filter(exportInfo => { - return ( - exportInfo.isReexport() && !exportInfo.getTarget(moduleGraph) - ); - }); - if (unknownReexports.length > 0) { - setBailoutReason( - module, - `Reexports in this module do not have a static target (${Array.from( - unknownReexports, - exportInfo => - `${ - exportInfo.name || "other exports" - }: ${exportInfo.getUsedInfo()}` - ).join(", ")})` - ); - continue; - } +/** + * @template R + * @param {function(function(Error=, R=): void): void} fn function + * @returns {function(function((Error | null)=, R=): void): void} cached function + */ +const cachedWithoutKey = fn => { + let inFlight = false; + /** @type {Error | undefined} */ + let cachedError = undefined; + /** @type {R | undefined} */ + let cachedResult = undefined; + /** @type {(function(Error=, R=): void)[] | undefined} */ + let cachedCallbacks = undefined; + return callback => { + if (inFlight) { + if (cachedResult !== undefined) return callback(null, cachedResult); + if (cachedError !== undefined) return callback(cachedError); + if (cachedCallbacks === undefined) cachedCallbacks = [callback]; + else cachedCallbacks.push(callback); + return; + } + inFlight = true; + fn((err, result) => { + if (err) cachedError = err; + else cachedResult = result; + const callbacks = cachedCallbacks; + cachedCallbacks = undefined; + callback(err, result); + if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); + }); + }; +}; - // Root modules must have a static list of exports - const unknownProvidedExports = relevantExports.filter( - exportInfo => { - return exportInfo.provided !== true; - } - ); - if (unknownProvidedExports.length > 0) { - setBailoutReason( - module, - `List of module exports is dynamic (${Array.from( - unknownProvidedExports, - exportInfo => - `${ - exportInfo.name || "other exports" - }: ${exportInfo.getProvidedInfo()} and ${exportInfo.getUsedInfo()}` - ).join(", ")})` - ); - canBeRoot = false; - } +/** + * @template T + * @template R + * @param {function(T, function(Error=, R=): void): void} fn function + * @param {function(T, function(Error=, R=): void): void=} forceFn function for the second try + * @returns {(function(T, function((Error | null)=, R=): void): void) & { force: function(T, function((Error | null)=, R=): void): void }} cached function + */ +const cachedWithKey = (fn, forceFn = fn) => { + /** @typedef {{ result?: R, error?: Error, callbacks?: (function((Error | null)=, R=): void)[], force?: true }} CacheEntry */ + /** @type {Map} */ + const cache = new Map(); + const resultFn = (arg, callback) => { + const cacheEntry = cache.get(arg); + if (cacheEntry !== undefined) { + if (cacheEntry.result !== undefined) + return callback(null, cacheEntry.result); + if (cacheEntry.error !== undefined) return callback(cacheEntry.error); + if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback]; + else cacheEntry.callbacks.push(callback); + return; + } + /** @type {CacheEntry} */ + const newCacheEntry = { + result: undefined, + error: undefined, + callbacks: undefined + }; + cache.set(arg, newCacheEntry); + fn(arg, (err, result) => { + if (err) newCacheEntry.error = err; + else newCacheEntry.result = result; + const callbacks = newCacheEntry.callbacks; + newCacheEntry.callbacks = undefined; + callback(err, result); + if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); + }); + }; + resultFn.force = (arg, callback) => { + const cacheEntry = cache.get(arg); + if (cacheEntry !== undefined && cacheEntry.force) { + if (cacheEntry.result !== undefined) + return callback(null, cacheEntry.result); + if (cacheEntry.error !== undefined) return callback(cacheEntry.error); + if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback]; + else cacheEntry.callbacks.push(callback); + return; + } + /** @type {CacheEntry} */ + const newCacheEntry = { + result: undefined, + error: undefined, + callbacks: undefined, + force: true + }; + cache.set(arg, newCacheEntry); + forceFn(arg, (err, result) => { + if (err) newCacheEntry.error = err; + else newCacheEntry.result = result; + const callbacks = newCacheEntry.callbacks; + newCacheEntry.callbacks = undefined; + callback(err, result); + if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); + }); + }; + return resultFn; +}; - // Module must not be an entry point - if (chunkGraph.isEntryModule(module)) { - setInnerBailoutReason(module, "Module is an entry point"); - canBeInner = false; - } +class HttpUriPlugin { + /** + * @param {HttpUriPluginOptions} options options + */ + constructor(options) { + validate(options); + this._lockfileLocation = options.lockfileLocation; + this._cacheLocation = options.cacheLocation; + this._upgrade = options.upgrade; + this._frozen = options.frozen; + this._allowedUris = options.allowedUris; + } - if (canBeRoot) relevantModules.push(module); - if (canBeInner) possibleInners.add(module); - } - logger.timeEnd("select relevant modules"); - logger.debug( - `${relevantModules.length} potential root modules, ${possibleInners.size} potential inner modules` + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + const schemes = [ + { + scheme: "http", + fetch: (url, options, callback) => getHttp().get(url, options, callback) + }, + { + scheme: "https", + fetch: (url, options, callback) => + getHttps().get(url, options, callback) + } + ]; + let lockfileCache; + compiler.hooks.compilation.tap( + "HttpUriPlugin", + (compilation, { normalModuleFactory }) => { + const intermediateFs = compiler.intermediateFileSystem; + const fs = compilation.inputFileSystem; + const cache = compilation.getCache("webpack.HttpUriPlugin"); + const logger = compilation.getLogger("webpack.HttpUriPlugin"); + const lockfileLocation = + this._lockfileLocation || + join( + intermediateFs, + compiler.context, + compiler.name + ? `${toSafePath(compiler.name)}.webpack.lock` + : "webpack.lock" ); - // sort by depth - // modules with lower depth are more likely suited as roots - // this improves performance, because modules already selected as inner are skipped - logger.time("sort relevant modules"); - relevantModules.sort((a, b) => { - return moduleGraph.getDepth(a) - moduleGraph.getDepth(b); - }); - logger.timeEnd("sort relevant modules"); - - /** @type {Statistics} */ - const stats = { - cached: 0, - alreadyInConfig: 0, - invalidModule: 0, - incorrectChunks: 0, - incorrectDependency: 0, - incorrectModuleDependency: 0, - incorrectChunksOfImporter: 0, - incorrectRuntimeCondition: 0, - importerFailed: 0, - added: 0 - }; - let statsCandidates = 0; - let statsSizeSum = 0; - let statsEmptyConfigurations = 0; - - logger.time("find modules to concatenate"); - const concatConfigurations = []; - const usedAsInner = new Set(); - for (const currentRoot of relevantModules) { - // when used by another configuration as inner: - // the other configuration is better and we can skip this one - // TODO reconsider that when it's only used in a different runtime - if (usedAsInner.has(currentRoot)) continue; - - let chunkRuntime = undefined; - for (const r of chunkGraph.getModuleRuntimes(currentRoot)) { - chunkRuntime = mergeRuntimeOwned(chunkRuntime, r); - } - const exportsInfo = moduleGraph.getExportsInfo(currentRoot); - const filteredRuntime = filterRuntime(chunkRuntime, r => - exportsInfo.isModuleUsed(r) - ); - const activeRuntime = - filteredRuntime === true - ? chunkRuntime - : filteredRuntime === false - ? undefined - : filteredRuntime; - - // create a configuration with the root - const currentConfiguration = new ConcatConfiguration( - currentRoot, - activeRuntime - ); + const cacheLocation = + this._cacheLocation !== undefined + ? this._cacheLocation + : lockfileLocation + ".data"; + const upgrade = this._upgrade || false; + const frozen = this._frozen || false; + const hashFunction = "sha512"; + const hashDigest = "hex"; + const hashDigestLength = 20; + const allowedUris = this._allowedUris; - // cache failures to add modules - const failureCache = new Map(); + let warnedAboutEol = false; - // potential optional import candidates - /** @type {Set} */ - const candidates = new Set(); + const cacheKeyCache = new Map(); + /** + * @param {string} url the url + * @returns {string} the key + */ + const getCacheKey = url => { + const cachedResult = cacheKeyCache.get(url); + if (cachedResult !== undefined) return cachedResult; + const result = _getCacheKey(url); + cacheKeyCache.set(url, result); + return result; + }; - // try to add all imports - for (const imp of this._getImports( - compilation, - currentRoot, - activeRuntime - )) { - candidates.add(imp); - } + /** + * @param {string} url the url + * @returns {string} the key + */ + const _getCacheKey = url => { + const parsedUrl = new URL(url); + const folder = toSafePath(parsedUrl.origin); + const name = toSafePath(parsedUrl.pathname); + const query = toSafePath(parsedUrl.search); + let ext = extname(name); + if (ext.length > 20) ext = ""; + const basename = ext ? name.slice(0, -ext.length) : name; + const hash = createHash(hashFunction); + hash.update(url); + const digest = hash.digest(hashDigest).slice(0, hashDigestLength); + return `${folder.slice(-50)}/${`${basename}${ + query ? `_${query}` : "" + }`.slice(0, 150)}_${digest}${ext}`; + }; - for (const imp of candidates) { - const impCandidates = new Set(); - const problem = this._tryToAdd( - compilation, - currentConfiguration, - imp, - chunkRuntime, - activeRuntime, - possibleInners, - impCandidates, - failureCache, - chunkGraph, - true, - stats - ); - if (problem) { - failureCache.set(imp, problem); - currentConfiguration.addWarning(imp, problem); - } else { - for (const c of impCandidates) { - candidates.add(c); + const getLockfile = cachedWithoutKey( + /** + * @param {function((Error | null)=, Lockfile=): void} callback callback + * @returns {void} + */ + callback => { + const readLockfile = () => { + intermediateFs.readFile(lockfileLocation, (err, buffer) => { + if (err && err.code !== "ENOENT") { + compilation.missingDependencies.add(lockfileLocation); + return callback(err); } - } - } - statsCandidates += candidates.size; - if (!currentConfiguration.isEmpty()) { - const modules = currentConfiguration.getModules(); - statsSizeSum += modules.size; - concatConfigurations.push(currentConfiguration); - for (const module of modules) { - if (module !== currentConfiguration.rootModule) { - usedAsInner.add(module); + compilation.fileDependencies.add(lockfileLocation); + compilation.fileSystemInfo.createSnapshot( + compiler.fsStartTime, + buffer ? [lockfileLocation] : [], + [], + buffer ? [] : [lockfileLocation], + { timestamp: true }, + (err, snapshot) => { + if (err) return callback(err); + const lockfile = buffer + ? Lockfile.parse(buffer.toString("utf-8")) + : new Lockfile(); + lockfileCache = { + lockfile, + snapshot + }; + callback(null, lockfile); + } + ); + }); + }; + if (lockfileCache) { + compilation.fileSystemInfo.checkSnapshotValid( + lockfileCache.snapshot, + (err, valid) => { + if (err) return callback(err); + if (!valid) return readLockfile(); + callback(null, lockfileCache.lockfile); } - } + ); } else { - statsEmptyConfigurations++; - const optimizationBailouts = - moduleGraph.getOptimizationBailout(currentRoot); - for (const warning of currentConfiguration.getWarningsSorted()) { - optimizationBailouts.push( - formatBailoutWarning(warning[0], warning[1]) - ); - } + readLockfile(); } } - logger.timeEnd("find modules to concatenate"); - logger.debug( - `${ - concatConfigurations.length - } successful concat configurations (avg size: ${ - statsSizeSum / concatConfigurations.length - }), ${statsEmptyConfigurations} bailed out completely` - ); - logger.debug( - `${statsCandidates} candidates were considered for adding (${stats.cached} cached failure, ${stats.alreadyInConfig} already in config, ${stats.invalidModule} invalid module, ${stats.incorrectChunks} incorrect chunks, ${stats.incorrectDependency} incorrect dependency, ${stats.incorrectChunksOfImporter} incorrect chunks of importer, ${stats.incorrectModuleDependency} incorrect module dependency, ${stats.incorrectRuntimeCondition} incorrect runtime condition, ${stats.importerFailed} importer failed, ${stats.added} added)` - ); - // HACK: Sort configurations by length and start with the longest one - // to get the biggest groups possible. Used modules are marked with usedModules - // TODO: Allow to reuse existing configuration while trying to add dependencies. - // This would improve performance. O(n^2) -> O(n) - logger.time(`sort concat configurations`); - concatConfigurations.sort((a, b) => { - return b.modules.size - a.modules.size; - }); - logger.timeEnd(`sort concat configurations`); - const usedModules = new Set(); - - logger.time("create concatenated modules"); - asyncLib.each( - concatConfigurations, - (concatConfiguration, callback) => { - const rootModule = concatConfiguration.rootModule; - - // Avoid overlapping configurations - // TODO: remove this when todo above is fixed - if (usedModules.has(rootModule)) return callback(); - const modules = concatConfiguration.getModules(); - for (const m of modules) { - usedModules.add(m); - } + ); - // Create a new ConcatenatedModule - let newModule = ConcatenatedModule.create( - rootModule, - modules, - concatConfiguration.runtime, - compiler.root, - compilation.outputOptions.hashFunction + /** @type {Map | undefined} */ + let lockfileUpdates = undefined; + const storeLockEntry = (lockfile, url, entry) => { + const oldEntry = lockfile.entries.get(url); + if (lockfileUpdates === undefined) lockfileUpdates = new Map(); + lockfileUpdates.set(url, entry); + lockfile.entries.set(url, entry); + if (!oldEntry) { + logger.log(`${url} added to lockfile`); + } else if (typeof oldEntry === "string") { + if (typeof entry === "string") { + logger.log(`${url} updated in lockfile: ${oldEntry} -> ${entry}`); + } else { + logger.log( + `${url} updated in lockfile: ${oldEntry} -> ${entry.resolved}` ); + } + } else if (typeof entry === "string") { + logger.log( + `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry}` + ); + } else if (oldEntry.resolved !== entry.resolved) { + logger.log( + `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry.resolved}` + ); + } else if (oldEntry.integrity !== entry.integrity) { + logger.log(`${url} updated in lockfile: content changed`); + } else if (oldEntry.contentType !== entry.contentType) { + logger.log( + `${url} updated in lockfile: ${oldEntry.contentType} -> ${entry.contentType}` + ); + } else { + logger.log(`${url} updated in lockfile`); + } + }; - const build = () => { - newModule.build( - compiler.options, - compilation, - null, - null, - err => { - if (err) { - if (!err.module) { - err.module = newModule; - } - return callback(err); - } - integrate(); + const storeResult = (lockfile, url, result, callback) => { + if (result.storeLock) { + storeLockEntry(lockfile, url, result.entry); + if (!cacheLocation || !result.content) + return callback(null, result); + const key = getCacheKey(result.entry.resolved); + const filePath = join(intermediateFs, cacheLocation, key); + mkdirp(intermediateFs, dirname(intermediateFs, filePath), err => { + if (err) return callback(err); + intermediateFs.writeFile(filePath, result.content, err => { + if (err) return callback(err); + callback(null, result); + }); + }); + } else { + storeLockEntry(lockfile, url, "no-cache"); + callback(null, result); + } + }; + + for (const { scheme, fetch } of schemes) { + /** + * + * @param {string} url URL + * @param {string} integrity integrity + * @param {function((Error | null)=, { entry: LockfileEntry, content: Buffer, storeLock: boolean }=): void} callback callback + */ + const resolveContent = (url, integrity, callback) => { + const handleResult = (err, result) => { + if (err) return callback(err); + if ("location" in result) { + return resolveContent( + result.location, + integrity, + (err, innerResult) => { + if (err) return callback(err); + callback(null, { + entry: innerResult.entry, + content: innerResult.content, + storeLock: innerResult.storeLock && result.storeLock + }); } ); - }; - - const integrate = () => { - if (backCompat) { - ChunkGraph.setChunkGraphForModule(newModule, chunkGraph); - ModuleGraph.setModuleGraphForModule(newModule, moduleGraph); + } else { + if ( + !result.fresh && + integrity && + result.entry.integrity !== integrity && + !verifyIntegrity(result.content, integrity) + ) { + return fetchContent.force(url, handleResult); } + return callback(null, { + entry: result.entry, + content: result.content, + storeLock: result.storeLock + }); + } + }; + fetchContent(url, handleResult); + }; - for (const warning of concatConfiguration.getWarningsSorted()) { - moduleGraph - .getOptimizationBailout(newModule) - .push(formatBailoutWarning(warning[0], warning[1])); + /** @typedef {{ storeCache: boolean, storeLock: boolean, validUntil: number, etag: string | undefined, fresh: boolean }} FetchResultMeta */ + /** @typedef {FetchResultMeta & { location: string }} RedirectFetchResult */ + /** @typedef {FetchResultMeta & { entry: LockfileEntry, content: Buffer }} ContentFetchResult */ + /** @typedef {RedirectFetchResult | ContentFetchResult} FetchResult */ + + /** + * @param {string} url URL + * @param {FetchResult} cachedResult result from cache + * @param {function((Error | null)=, FetchResult=): void} callback callback + * @returns {void} + */ + const fetchContentRaw = (url, cachedResult, callback) => { + const requestTime = Date.now(); + fetch( + new URL(url), + { + headers: { + "accept-encoding": "gzip, deflate, br", + "user-agent": "webpack", + "if-none-match": cachedResult + ? cachedResult.etag || null + : null } - moduleGraph.cloneModuleAttributes(rootModule, newModule); - for (const m of modules) { - // add to builtModules when one of the included modules was built - if (compilation.builtModules.has(m)) { - compilation.builtModules.add(newModule); + }, + res => { + const etag = res.headers["etag"]; + const location = res.headers["location"]; + const cacheControl = res.headers["cache-control"]; + const { storeLock, storeCache, validUntil } = parseCacheControl( + cacheControl, + requestTime + ); + /** + * @param {Partial> & (Pick | Pick)} partialResult result + * @returns {void} + */ + const finishWith = partialResult => { + if ("location" in partialResult) { + logger.debug( + `GET ${url} [${res.statusCode}] -> ${partialResult.location}` + ); + } else { + logger.debug( + `GET ${url} [${res.statusCode}] ${Math.ceil( + partialResult.content.length / 1024 + )} kB${!storeLock ? " no-cache" : ""}` + ); } - if (m !== rootModule) { - // attach external references to the concatenated module too - moduleGraph.copyOutgoingModuleConnections( - m, - newModule, - c => { - return ( - c.originModule === m && - !( - c.dependency instanceof HarmonyImportDependency && - modules.has(c.module) - ) + const result = { + ...partialResult, + fresh: true, + storeLock, + storeCache, + validUntil, + etag + }; + if (!storeCache) { + logger.log( + `${url} can't be stored in cache, due to Cache-Control header: ${cacheControl}` + ); + return callback(null, result); + } + cache.store( + url, + null, + { + ...result, + fresh: false + }, + err => { + if (err) { + logger.warn( + `${url} can't be stored in cache: ${err.message}` ); + logger.debug(err.stack); } - ); - // remove module from chunk - for (const chunk of chunkGraph.getModuleChunksIterable( - rootModule - )) { - chunkGraph.disconnectChunkAndModule(chunk, m); + callback(null, result); } + ); + }; + if (res.statusCode === 304) { + if ( + cachedResult.validUntil < validUntil || + cachedResult.storeLock !== storeLock || + cachedResult.storeCache !== storeCache || + cachedResult.etag !== etag + ) { + return finishWith(cachedResult); + } else { + logger.debug(`GET ${url} [${res.statusCode}] (unchanged)`); + return callback(null, { + ...cachedResult, + fresh: true + }); } } - compilation.modules.delete(rootModule); - ChunkGraph.clearChunkGraphForModule(rootModule); - ModuleGraph.clearModuleGraphForModule(rootModule); - - // remove module from chunk - chunkGraph.replaceModule(rootModule, newModule); - // replace module references with the concatenated module - moduleGraph.moveModuleConnections(rootModule, newModule, c => { - const otherModule = - c.module === rootModule ? c.originModule : c.module; - const innerConnection = - c.dependency instanceof HarmonyImportDependency && - modules.has(otherModule); - return !innerConnection; - }); - // add concatenated module to the compilation - compilation.modules.add(newModule); - - callback(); - }; - - build(); - }, - err => { - logger.timeEnd("create concatenated modules"); - process.nextTick(callback.bind(null, err)); - } - ); - } - ); - }); - } - - /** - * @param {Compilation} compilation the compilation - * @param {Module} module the module to be added - * @param {RuntimeSpec} runtime the runtime scope - * @returns {Set} the imported modules - */ - _getImports(compilation, module, runtime) { - const moduleGraph = compilation.moduleGraph; - const set = new Set(); - for (const dep of module.dependencies) { - // Get reference info only for harmony Dependencies - if (!(dep instanceof HarmonyImportDependency)) continue; - - const connection = moduleGraph.getConnection(dep); - // Reference is valid and has a module - if ( - !connection || - !connection.module || - !connection.isTargetActive(runtime) - ) { - continue; - } - - const importedNames = compilation.getDependencyReferencedExports( - dep, - undefined - ); + if ( + location && + res.statusCode >= 301 && + res.statusCode <= 308 + ) { + return finishWith({ + location: new URL(location, url).href + }); + } + const contentType = res.headers["content-type"] || ""; + const bufferArr = []; - if ( - importedNames.every(i => - Array.isArray(i) ? i.length > 0 : i.name.length > 0 - ) || - Array.isArray(moduleGraph.getProvidedExports(module)) - ) { - set.add(connection.module); - } - } - return set; - } + const contentEncoding = res.headers["content-encoding"]; + let stream = res; + if (contentEncoding === "gzip") { + stream = stream.pipe(createGunzip()); + } else if (contentEncoding === "br") { + stream = stream.pipe(createBrotliDecompress()); + } else if (contentEncoding === "deflate") { + stream = stream.pipe(createInflate()); + } - /** - * @param {Compilation} compilation webpack compilation - * @param {ConcatConfiguration} config concat configuration (will be modified when added) - * @param {Module} module the module to be added - * @param {RuntimeSpec} runtime the runtime scope of the generated code - * @param {RuntimeSpec} activeRuntime the runtime scope of the root module - * @param {Set} possibleModules modules that are candidates - * @param {Set} candidates list of potential candidates (will be added to) - * @param {Map} failureCache cache for problematic modules to be more performant - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {boolean} avoidMutateOnFailure avoid mutating the config when adding fails - * @param {Statistics} statistics gathering metrics - * @returns {Module | function(RequestShortener): string} the problematic module - */ - _tryToAdd( - compilation, - config, - module, - runtime, - activeRuntime, - possibleModules, - candidates, - failureCache, - chunkGraph, - avoidMutateOnFailure, - statistics - ) { - const cacheEntry = failureCache.get(module); - if (cacheEntry) { - statistics.cached++; - return cacheEntry; - } + stream.on("data", chunk => { + bufferArr.push(chunk); + }); - // Already added? - if (config.has(module)) { - statistics.alreadyInConfig++; - return null; - } + stream.on("end", () => { + if (!res.complete) { + logger.log(`GET ${url} [${res.statusCode}] (terminated)`); + return callback(new Error(`${url} request was terminated`)); + } - // Not possible to add? - if (!possibleModules.has(module)) { - statistics.invalidModule++; - failureCache.set(module, module); // cache failures for performance - return module; - } + const content = Buffer.concat(bufferArr); - // Module must be in the correct chunks - const missingChunks = Array.from( - chunkGraph.getModuleChunksIterable(config.rootModule) - ).filter(chunk => !chunkGraph.isModuleInChunk(module, chunk)); - if (missingChunks.length > 0) { - const problem = requestShortener => { - const missingChunksList = Array.from( - new Set(missingChunks.map(chunk => chunk.name || "unnamed chunk(s)")) - ).sort(); - const chunks = Array.from( - new Set( - Array.from(chunkGraph.getModuleChunksIterable(module)).map( - chunk => chunk.name || "unnamed chunk(s)" - ) - ) - ).sort(); - return `Module ${module.readableIdentifier( - requestShortener - )} is not in the same chunk(s) (expected in chunk(s) ${missingChunksList.join( - ", " - )}, module is in chunk(s) ${chunks.join(", ")})`; - }; - statistics.incorrectChunks++; - failureCache.set(module, problem); // cache failures for performance - return problem; - } + if (res.statusCode !== 200) { + logger.log(`GET ${url} [${res.statusCode}]`); + return callback( + new Error( + `${url} request status code = ${ + res.statusCode + }\n${content.toString("utf-8")}` + ) + ); + } - const moduleGraph = compilation.moduleGraph; + const integrity = computeIntegrity(content); + const entry = { resolved: url, integrity, contentType }; - const incomingConnections = - moduleGraph.getIncomingConnectionsByOriginModule(module); + finishWith({ + entry, + content + }); + }); + } + ).on("error", err => { + logger.log(`GET ${url} (error)`); + err.message += `\nwhile fetching ${url}`; + callback(err); + }); + }; - const incomingConnectionsFromNonModules = - incomingConnections.get(null) || incomingConnections.get(undefined); - if (incomingConnectionsFromNonModules) { - const activeNonModulesConnections = - incomingConnectionsFromNonModules.filter(connection => { - // We are not interested in inactive connections - // or connections without dependency - return connection.isActive(runtime) || connection.dependency; - }); - if (activeNonModulesConnections.length > 0) { - const problem = requestShortener => { - const importingExplanations = new Set( - activeNonModulesConnections.map(c => c.explanation).filter(Boolean) + const fetchContent = cachedWithKey( + /** + * @param {string} url URL + * @param {function((Error | null)=, { validUntil: number, etag?: string, entry: LockfileEntry, content: Buffer, fresh: boolean } | { validUntil: number, etag?: string, location: string, fresh: boolean }=): void} callback callback + * @returns {void} + */ (url, callback) => { + cache.get(url, null, (err, cachedResult) => { + if (err) return callback(err); + if (cachedResult) { + const isValid = cachedResult.validUntil >= Date.now(); + if (isValid) return callback(null, cachedResult); + } + fetchContentRaw(url, cachedResult, callback); + }); + }, + (url, callback) => fetchContentRaw(url, undefined, callback) ); - const explanations = Array.from(importingExplanations).sort(); - return `Module ${module.readableIdentifier( - requestShortener - )} is referenced ${ - explanations.length > 0 - ? `by: ${explanations.join(", ")}` - : "in an unsupported way" - }`; - }; - statistics.incorrectDependency++; - failureCache.set(module, problem); // cache failures for performance - return problem; - } - } - - /** @type {Map} */ - const incomingConnectionsFromModules = new Map(); - for (const [originModule, connections] of incomingConnections) { - if (originModule) { - // Ignore connection from orphan modules - if (chunkGraph.getNumberOfModuleChunks(originModule) === 0) continue; - - // We don't care for connections from other runtimes - let originRuntime = undefined; - for (const r of chunkGraph.getModuleRuntimes(originModule)) { - originRuntime = mergeRuntimeOwned(originRuntime, r); - } - - if (!intersectRuntime(runtime, originRuntime)) continue; - - // We are not interested in inactive connections - const activeConnections = connections.filter(connection => - connection.isActive(runtime) - ); - if (activeConnections.length > 0) - incomingConnectionsFromModules.set(originModule, activeConnections); - } - } - const incomingModules = Array.from(incomingConnectionsFromModules.keys()); + const isAllowed = uri => { + for (const allowed of allowedUris) { + if (typeof allowed === "string") { + if (uri.startsWith(allowed)) return true; + } else if (typeof allowed === "function") { + if (allowed(uri)) return true; + } else { + if (allowed.test(uri)) return true; + } + } + return false; + }; - // Module must be in the same chunks like the referencing module - const otherChunkModules = incomingModules.filter(originModule => { - for (const chunk of chunkGraph.getModuleChunksIterable( - config.rootModule - )) { - if (!chunkGraph.isModuleInChunk(originModule, chunk)) { - return true; - } - } - return false; - }); - if (otherChunkModules.length > 0) { - const problem = requestShortener => { - const names = otherChunkModules - .map(m => m.readableIdentifier(requestShortener)) - .sort(); - return `Module ${module.readableIdentifier( - requestShortener - )} is referenced from different chunks by these modules: ${names.join( - ", " - )}`; - }; - statistics.incorrectChunksOfImporter++; - failureCache.set(module, problem); // cache failures for performance - return problem; - } - - /** @type {Map} */ - const nonHarmonyConnections = new Map(); - for (const [originModule, connections] of incomingConnectionsFromModules) { - const selected = connections.filter( - connection => - !connection.dependency || - !(connection.dependency instanceof HarmonyImportDependency) - ); - if (selected.length > 0) - nonHarmonyConnections.set(originModule, connections); - } - if (nonHarmonyConnections.size > 0) { - const problem = requestShortener => { - const names = Array.from(nonHarmonyConnections) - .map(([originModule, connections]) => { - return `${originModule.readableIdentifier( - requestShortener - )} (referenced with ${Array.from( - new Set( - connections - .map(c => c.dependency && c.dependency.type) - .filter(Boolean) - ) - ) - .sort() - .join(", ")})`; - }) - .sort(); - return `Module ${module.readableIdentifier( - requestShortener - )} is referenced from these modules with unsupported syntax: ${names.join( - ", " - )}`; - }; - statistics.incorrectModuleDependency++; - failureCache.set(module, problem); // cache failures for performance - return problem; - } + const getInfo = cachedWithKey( + /** + * @param {string} url the url + * @param {function((Error | null)=, { entry: LockfileEntry, content: Buffer }=): void} callback callback + * @returns {void} + */ + (url, callback) => { + if (!isAllowed(url)) { + return callback( + new Error( + `${url} doesn't match the allowedUris policy. These URIs are allowed:\n${allowedUris + .map(uri => ` - ${uri}`) + .join("\n")}` + ) + ); + } + getLockfile((err, lockfile) => { + if (err) return callback(err); + const entryOrString = lockfile.entries.get(url); + if (!entryOrString) { + if (frozen) { + return callback( + new Error( + `${url} has no lockfile entry and lockfile is frozen` + ) + ); + } + resolveContent(url, null, (err, result) => { + if (err) return callback(err); + storeResult(lockfile, url, result, callback); + }); + return; + } + if (typeof entryOrString === "string") { + const entryTag = entryOrString; + resolveContent(url, null, (err, result) => { + if (err) return callback(err); + if (!result.storeLock || entryTag === "ignore") + return callback(null, result); + if (frozen) { + return callback( + new Error( + `${url} used to have ${entryTag} lockfile entry and has content now, but lockfile is frozen` + ) + ); + } + if (!upgrade) { + return callback( + new Error( + `${url} used to have ${entryTag} lockfile entry and has content now. +This should be reflected in the lockfile, so this lockfile entry must be upgraded, but upgrading is not enabled. +Remove this line from the lockfile to force upgrading.` + ) + ); + } + storeResult(lockfile, url, result, callback); + }); + return; + } + let entry = entryOrString; + const doFetch = lockedContent => { + resolveContent(url, entry.integrity, (err, result) => { + if (err) { + if (lockedContent) { + logger.warn( + `Upgrade request to ${url} failed: ${err.message}` + ); + logger.debug(err.stack); + return callback(null, { + entry, + content: lockedContent + }); + } + return callback(err); + } + if (!result.storeLock) { + // When the lockfile entry should be no-cache + // we need to update the lockfile + if (frozen) { + return callback( + new Error( + `${url} has a lockfile entry and is no-cache now, but lockfile is frozen\nLockfile: ${entryToString( + entry + )}` + ) + ); + } + storeResult(lockfile, url, result, callback); + return; + } + if (!areLockfileEntriesEqual(result.entry, entry)) { + // When the lockfile entry is outdated + // we need to update the lockfile + if (frozen) { + return callback( + new Error( + `${url} has an outdated lockfile entry, but lockfile is frozen\nLockfile: ${entryToString( + entry + )}\nExpected: ${entryToString(result.entry)}` + ) + ); + } + storeResult(lockfile, url, result, callback); + return; + } + if (!lockedContent && cacheLocation) { + // When the lockfile cache content is missing + // we need to update the lockfile + if (frozen) { + return callback( + new Error( + `${url} is missing content in the lockfile cache, but lockfile is frozen\nLockfile: ${entryToString( + entry + )}` + ) + ); + } + storeResult(lockfile, url, result, callback); + return; + } + return callback(null, result); + }); + }; + if (cacheLocation) { + // When there is a lockfile cache + // we read the content from there + const key = getCacheKey(entry.resolved); + const filePath = join(intermediateFs, cacheLocation, key); + fs.readFile(filePath, (err, result) => { + const content = /** @type {Buffer} */ (result); + if (err) { + if (err.code === "ENOENT") return doFetch(); + return callback(err); + } + const continueWithCachedContent = result => { + if (!upgrade) { + // When not in upgrade mode, we accept the result from the lockfile cache + return callback(null, { entry, content }); + } + return doFetch(content); + }; + if (!verifyIntegrity(content, entry.integrity)) { + let contentWithChangedEol; + let isEolChanged = false; + try { + contentWithChangedEol = Buffer.from( + content.toString("utf-8").replace(/\r\n/g, "\n") + ); + isEolChanged = verifyIntegrity( + contentWithChangedEol, + entry.integrity + ); + } catch (e) { + // ignore + } + if (isEolChanged) { + if (!warnedAboutEol) { + const explainer = `Incorrect end of line sequence was detected in the lockfile cache. +The lockfile cache is protected by integrity checks, so any external modification will lead to a corrupted lockfile cache. +When using git make sure to configure .gitattributes correctly for the lockfile cache: + **/*webpack.lock.data/** -text +This will avoid that the end of line sequence is changed by git on Windows.`; + if (frozen) { + logger.error(explainer); + } else { + logger.warn(explainer); + logger.info( + "Lockfile cache will be automatically fixed now, but when lockfile is frozen this would result in an error." + ); + } + warnedAboutEol = true; + } + if (!frozen) { + // "fix" the end of line sequence of the lockfile content + logger.log( + `${filePath} fixed end of line sequence (\\r\\n instead of \\n).` + ); + intermediateFs.writeFile( + filePath, + contentWithChangedEol, + err => { + if (err) return callback(err); + continueWithCachedContent(contentWithChangedEol); + } + ); + return; + } + } + if (frozen) { + return callback( + new Error( + `${ + entry.resolved + } integrity mismatch, expected content with integrity ${ + entry.integrity + } but got ${computeIntegrity(content)}. +Lockfile corrupted (${ + isEolChanged + ? "end of line sequence was unexpectedly changed" + : "incorrectly merged? changed by other tools?" + }). +Run build with un-frozen lockfile to automatically fix lockfile.` + ) + ); + } else { + // "fix" the lockfile entry to the correct integrity + // the content has priority over the integrity value + entry = { + ...entry, + integrity: computeIntegrity(content) + }; + storeLockEntry(lockfile, url, entry); + } + } + continueWithCachedContent(result); + }); + } else { + doFetch(); + } + }); + } + ); - if (runtime !== undefined && typeof runtime !== "string") { - // Module must be consistently referenced in the same runtimes - /** @type {{ originModule: Module, runtimeCondition: RuntimeSpec }[]} */ - const otherRuntimeConnections = []; - outer: for (const [ - originModule, - connections - ] of incomingConnectionsFromModules) { - /** @type {false | RuntimeSpec} */ - let currentRuntimeCondition = false; - for (const connection of connections) { - const runtimeCondition = filterRuntime(runtime, runtime => { - return connection.isTargetActive(runtime); - }); - if (runtimeCondition === false) continue; - if (runtimeCondition === true) continue outer; - if (currentRuntimeCondition !== false) { - currentRuntimeCondition = mergeRuntime( - currentRuntimeCondition, - runtimeCondition + const respondWithUrlModule = (url, resourceData, callback) => { + getInfo(url.href, (err, result) => { + if (err) return callback(err); + resourceData.resource = url.href; + resourceData.path = url.origin + url.pathname; + resourceData.query = url.search; + resourceData.fragment = url.hash; + resourceData.context = new URL( + ".", + result.entry.resolved + ).href.slice(0, -1); + resourceData.data.mimetype = result.entry.contentType; + callback(null, true); + }); + }; + normalModuleFactory.hooks.resolveForScheme + .for(scheme) + .tapAsync( + "HttpUriPlugin", + (resourceData, resolveData, callback) => { + respondWithUrlModule( + new URL(resourceData.resource), + resourceData, + callback + ); + } ); - } else { - currentRuntimeCondition = runtimeCondition; - } - } - if (currentRuntimeCondition !== false) { - otherRuntimeConnections.push({ - originModule, - runtimeCondition: currentRuntimeCondition - }); + normalModuleFactory.hooks.resolveInScheme + .for(scheme) + .tapAsync("HttpUriPlugin", (resourceData, data, callback) => { + // Only handle relative urls (./xxx, ../xxx, /xxx, //xxx) + if ( + data.dependencyType !== "url" && + !/^\.{0,2}\//.test(resourceData.resource) + ) { + return callback(); + } + respondWithUrlModule( + new URL(resourceData.resource, data.context + "/"), + resourceData, + callback + ); + }); + const hooks = NormalModule.getCompilationHooks(compilation); + hooks.readResourceForScheme + .for(scheme) + .tapAsync("HttpUriPlugin", (resource, module, callback) => { + return getInfo(resource, (err, result) => { + if (err) return callback(err); + module.buildInfo.resourceIntegrity = result.entry.integrity; + callback(null, result.content); + }); + }); + hooks.needBuild.tapAsync( + "HttpUriPlugin", + (module, context, callback) => { + if ( + module.resource && + module.resource.startsWith(`${scheme}://`) + ) { + getInfo(module.resource, (err, result) => { + if (err) return callback(err); + if ( + result.entry.integrity !== + module.buildInfo.resourceIntegrity + ) { + return callback(null, true); + } + callback(); + }); + } else { + return callback(); + } + } + ); } - } - if (otherRuntimeConnections.length > 0) { - const problem = requestShortener => { - return `Module ${module.readableIdentifier( - requestShortener - )} is runtime-dependent referenced by these modules: ${Array.from( - otherRuntimeConnections, - ({ originModule, runtimeCondition }) => - `${originModule.readableIdentifier( - requestShortener - )} (expected runtime ${runtimeToString( - runtime - )}, module is only referenced in ${runtimeToString( - /** @type {RuntimeSpec} */ (runtimeCondition) - )})` - ).join(", ")}`; - }; - statistics.incorrectRuntimeCondition++; - failureCache.set(module, problem); // cache failures for performance - return problem; - } - } - - let backup; - if (avoidMutateOnFailure) { - backup = config.snapshot(); - } - - // Add the module - config.add(module); - - incomingModules.sort(compareModulesByIdentifier); + compilation.hooks.finishModules.tapAsync( + "HttpUriPlugin", + (modules, callback) => { + if (!lockfileUpdates) return callback(); + const ext = extname(lockfileLocation); + const tempFile = join( + intermediateFs, + dirname(intermediateFs, lockfileLocation), + `.${basename(lockfileLocation, ext)}.${ + (Math.random() * 10000) | 0 + }${ext}` + ); - // Every module which depends on the added module must be in the configuration too. - for (const originModule of incomingModules) { - const problem = this._tryToAdd( - compilation, - config, - originModule, - runtime, - activeRuntime, - possibleModules, - candidates, - failureCache, - chunkGraph, - false, - statistics - ); - if (problem) { - if (backup !== undefined) config.rollback(backup); - statistics.importerFailed++; - failureCache.set(module, problem); // cache failures for performance - return problem; + const writeDone = () => { + const nextOperation = inProgressWrite.shift(); + if (nextOperation) { + nextOperation(); + } else { + inProgressWrite = undefined; + } + }; + const runWrite = () => { + intermediateFs.readFile(lockfileLocation, (err, buffer) => { + if (err && err.code !== "ENOENT") { + writeDone(); + return callback(err); + } + const lockfile = buffer + ? Lockfile.parse(buffer.toString("utf-8")) + : new Lockfile(); + for (const [key, value] of lockfileUpdates) { + lockfile.entries.set(key, value); + } + intermediateFs.writeFile(tempFile, lockfile.toString(), err => { + if (err) { + writeDone(); + return intermediateFs.unlink(tempFile, () => callback(err)); + } + intermediateFs.rename(tempFile, lockfileLocation, err => { + if (err) { + writeDone(); + return intermediateFs.unlink(tempFile, () => + callback(err) + ); + } + writeDone(); + callback(); + }); + }); + }); + }; + if (inProgressWrite) { + inProgressWrite.push(runWrite); + } else { + inProgressWrite = []; + runWrite(); + } + } + ); } - } - - // Add imports to possible candidates list - for (const imp of this._getImports(compilation, module, runtime)) { - candidates.add(imp); - } - statistics.added++; - return null; + ); } } -class ConcatConfiguration { - /** - * @param {Module} rootModule the root module - * @param {RuntimeSpec} runtime the runtime - */ - constructor(rootModule, runtime) { - this.rootModule = rootModule; - this.runtime = runtime; - /** @type {Set} */ - this.modules = new Set(); - this.modules.add(rootModule); - /** @type {Map} */ - this.warnings = new Map(); - } +module.exports = HttpUriPlugin; - add(module) { - this.modules.add(module); - } - has(module) { - return this.modules.has(module); - } +/***/ }), - isEmpty() { - return this.modules.size === 1; - } +/***/ 41721: +/***/ (function(module) { - addWarning(module, problem) { - this.warnings.set(module, problem); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - getWarningsSorted() { - return new Map( - Array.from(this.warnings).sort((a, b) => { - const ai = a[0].identifier(); - const bi = b[0].identifier(); - if (ai < bi) return -1; - if (ai > bi) return 1; - return 0; - }) - ); - } - /** - * @returns {Set} modules as set - */ - getModules() { - return this.modules; - } - snapshot() { - return this.modules.size; +class ArraySerializer { + serialize(array, { write }) { + write(array.length); + for (const item of array) write(item); } - - rollback(snapshot) { - const modules = this.modules; - for (const m of modules) { - if (snapshot === 0) { - modules.delete(m); - } else { - snapshot--; - } + deserialize({ read }) { + const length = read(); + const array = []; + for (let i = 0; i < length; i++) { + array.push(read()); } + return array; } } -module.exports = ModuleConcatenationPlugin; +module.exports = ArraySerializer; /***/ }), -/***/ 46043: +/***/ 97059: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const { SyncBailHook } = __webpack_require__(41242); -const { RawSource, CachedSource, CompatSource } = __webpack_require__(51255); -const Compilation = __webpack_require__(85720); -const WebpackError = __webpack_require__(53799); -const { compareSelect, compareStrings } = __webpack_require__(29579); -const createHash = __webpack_require__(49835); +const memoize = __webpack_require__(78676); +const SerializerMiddleware = __webpack_require__(83137); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("./types").BufferSerializableType} BufferSerializableType */ +/** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */ -const EMPTY_SET = new Set(); +/* +Format: -const addToList = (itemOrItems, list) => { - if (Array.isArray(itemOrItems)) { - for (const item of itemOrItems) { - list.add(item); - } - } else if (itemOrItems) { - list.add(itemOrItems); - } -}; +File -> Section* -/** - * @template T - * @param {T[]} input list - * @param {function(T): Buffer} fn map function - * @returns {Buffer[]} buffers without duplicates - */ -const mapAndDeduplicateBuffers = (input, fn) => { - // Buffer.equals compares size first so this should be efficient enough - // If it becomes a performance problem we can use a map and group by size - // instead of looping over all assets. - const result = []; - outer: for (const value of input) { - const buf = fn(value); - for (const other of result) { - if (buf.equals(other)) continue outer; - } - result.push(buf); - } - return result; -}; +Section -> NullsSection | + BooleansSection | + F64NumbersSection | + I32NumbersSection | + I8NumbersSection | + ShortStringSection | + StringSection | + BufferSection | + NopSection -/** - * Escapes regular expression metacharacters - * @param {string} str String to quote - * @returns {string} Escaped string - */ -const quoteMeta = str => { - return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); -}; -const cachedSourceMap = new WeakMap(); -const toCachedSource = source => { - if (source instanceof CachedSource) { - return source; +NullsSection -> + NullHeaderByte | Null2HeaderByte | Null3HeaderByte | + Nulls8HeaderByte 0xnn (n:count - 4) | + Nulls32HeaderByte n:ui32 (n:count - 260) | +BooleansSection -> TrueHeaderByte | FalseHeaderByte | BooleansSectionHeaderByte BooleansCountAndBitsByte +F64NumbersSection -> F64NumbersSectionHeaderByte f64* +I32NumbersSection -> I32NumbersSectionHeaderByte i32* +I8NumbersSection -> I8NumbersSectionHeaderByte i8* +ShortStringSection -> ShortStringSectionHeaderByte ascii-byte* +StringSection -> StringSectionHeaderByte i32:length utf8-byte* +BufferSection -> BufferSectionHeaderByte i32:length byte* +NopSection --> NopSectionHeaderByte + +ShortStringSectionHeaderByte -> 0b1nnn_nnnn (n:length) + +F64NumbersSectionHeaderByte -> 0b001n_nnnn (n:count - 1) +I32NumbersSectionHeaderByte -> 0b010n_nnnn (n:count - 1) +I8NumbersSectionHeaderByte -> 0b011n_nnnn (n:count - 1) + +NullsSectionHeaderByte -> 0b0001_nnnn (n:count - 1) +BooleansCountAndBitsByte -> + 0b0000_1xxx (count = 3) | + 0b0001_xxxx (count = 4) | + 0b001x_xxxx (count = 5) | + 0b01xx_xxxx (count = 6) | + 0b1nnn_nnnn (n:count - 7, 7 <= count <= 133) + 0xff n:ui32 (n:count, 134 <= count < 2^32) + +StringSectionHeaderByte -> 0b0000_1110 +BufferSectionHeaderByte -> 0b0000_1111 +NopSectionHeaderByte -> 0b0000_1011 +FalseHeaderByte -> 0b0000_1100 +TrueHeaderByte -> 0b0000_1101 + +RawNumber -> n (n <= 10) + +*/ + +const LAZY_HEADER = 0x0b; +const TRUE_HEADER = 0x0c; +const FALSE_HEADER = 0x0d; +const BOOLEANS_HEADER = 0x0e; +const NULL_HEADER = 0x10; +const NULL2_HEADER = 0x11; +const NULL3_HEADER = 0x12; +const NULLS8_HEADER = 0x13; +const NULLS32_HEADER = 0x14; +const NULL_AND_I8_HEADER = 0x15; +const NULL_AND_I32_HEADER = 0x16; +const NULL_AND_TRUE_HEADER = 0x17; +const NULL_AND_FALSE_HEADER = 0x18; +const STRING_HEADER = 0x1e; +const BUFFER_HEADER = 0x1f; +const I8_HEADER = 0x60; +const I32_HEADER = 0x40; +const F64_HEADER = 0x20; +const SHORT_STRING_HEADER = 0x80; + +/** Uplift high-order bits */ +const NUMBERS_HEADER_MASK = 0xe0; +const NUMBERS_COUNT_MASK = 0x1f; // 0b0001_1111 +const SHORT_STRING_LENGTH_MASK = 0x7f; // 0b0111_1111 + +const HEADER_SIZE = 1; +const I8_SIZE = 1; +const I32_SIZE = 4; +const F64_SIZE = 8; + +const MEASURE_START_OPERATION = Symbol("MEASURE_START_OPERATION"); +const MEASURE_END_OPERATION = Symbol("MEASURE_END_OPERATION"); + +/** @typedef {typeof MEASURE_START_OPERATION} MEASURE_START_OPERATION_TYPE */ +/** @typedef {typeof MEASURE_END_OPERATION} MEASURE_END_OPERATION_TYPE */ + +const identifyNumber = n => { + if (n === (n | 0)) { + if (n <= 127 && n >= -128) return 0; + if (n <= 2147483647 && n >= -2147483648) return 1; } - const entry = cachedSourceMap.get(source); - if (entry !== undefined) return entry; - const newSource = new CachedSource(CompatSource.from(source)); - cachedSourceMap.set(source, newSource); - return newSource; + return 2; }; /** - * @typedef {Object} AssetInfoForRealContentHash - * @property {string} name - * @property {AssetInfo} info - * @property {Source} source - * @property {RawSource | undefined} newSource - * @property {RawSource | undefined} newSourceWithoutOwn - * @property {string} content - * @property {Set} ownHashes - * @property {Promise} contentComputePromise - * @property {Promise} contentComputeWithoutOwnPromise - * @property {Set} referencedHashes - * @property {Set} hashes - */ - -/** - * @typedef {Object} CompilationHooks - * @property {SyncBailHook<[Buffer[], string], string>} updateHash + * @typedef {PrimitiveSerializableType[]} DeserializedType + * @typedef {BufferSerializableType[]} SerializedType + * @extends {SerializerMiddleware} */ - -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); - -class RealContentHashPlugin { +class BinaryMiddleware extends SerializerMiddleware { /** - * @param {Compilation} compilation the compilation - * @returns {CompilationHooks} the attached hooks + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType|Promise} serialized data */ - 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 = { - updateHash: new SyncBailHook(["content", "oldHash"]) - }; - compilationHooksMap.set(compilation, hooks); - } - return hooks; + serialize(data, context) { + return this._serialize(data, context); } - constructor({ hashFunction, hashDigest }) { - this._hashFunction = hashFunction; - this._hashDigest = hashDigest; + _serializeLazy(fn, context) { + return SerializerMiddleware.serializeLazy(fn, data => + this._serialize(data, context) + ); } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {DeserializedType} data data + * @param {Object} context context object + * @param {{ leftOverBuffer: Buffer | null, allocationSize: number, increaseCounter: number }} allocationScope allocation scope + * @returns {SerializedType} serialized data */ - apply(compiler) { - compiler.hooks.compilation.tap("RealContentHashPlugin", compilation => { - const cacheAnalyse = compilation.getCache( - "RealContentHashPlugin|analyse" - ); - const cacheGenerate = compilation.getCache( - "RealContentHashPlugin|generate" - ); - const hooks = RealContentHashPlugin.getCompilationHooks(compilation); - compilation.hooks.processAssets.tapPromise( - { - name: "RealContentHashPlugin", - stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH - }, - async () => { - const assets = compilation.getAssets(); - /** @type {AssetInfoForRealContentHash[]} */ - const assetsWithInfo = []; - const hashToAssets = new Map(); - for (const { source, info, name } of assets) { - const cachedSource = toCachedSource(source); - const content = cachedSource.source(); - /** @type {Set} */ - const hashes = new Set(); - addToList(info.contenthash, hashes); - const data = { - name, - info, - source: cachedSource, - /** @type {RawSource | undefined} */ - newSource: undefined, - /** @type {RawSource | undefined} */ - newSourceWithoutOwn: undefined, - content, - /** @type {Set} */ - ownHashes: undefined, - contentComputePromise: undefined, - contentComputeWithoutOwnPromise: undefined, - /** @type {Set} */ - referencedHashes: undefined, - hashes - }; - assetsWithInfo.push(data); - for (const hash of hashes) { - const list = hashToAssets.get(hash); - if (list === undefined) { - hashToAssets.set(hash, [data]); + _serialize( + data, + context, + allocationScope = { + allocationSize: 1024, + increaseCounter: 0, + leftOverBuffer: null + } + ) { + /** @type {Buffer} */ + let leftOverBuffer = null; + /** @type {BufferSerializableType[]} */ + let buffers = []; + /** @type {Buffer} */ + let currentBuffer = allocationScope ? allocationScope.leftOverBuffer : null; + allocationScope.leftOverBuffer = null; + let currentPosition = 0; + if (currentBuffer === null) { + currentBuffer = Buffer.allocUnsafe(allocationScope.allocationSize); + } + const allocate = bytesNeeded => { + if (currentBuffer !== null) { + if (currentBuffer.length - currentPosition >= bytesNeeded) return; + flush(); + } + if (leftOverBuffer && leftOverBuffer.length >= bytesNeeded) { + currentBuffer = leftOverBuffer; + leftOverBuffer = null; + } else { + currentBuffer = Buffer.allocUnsafe( + Math.max(bytesNeeded, allocationScope.allocationSize) + ); + if ( + !(allocationScope.increaseCounter = + (allocationScope.increaseCounter + 1) % 4) && + allocationScope.allocationSize < 16777216 + ) { + allocationScope.allocationSize = allocationScope.allocationSize << 1; + } + } + }; + const flush = () => { + if (currentBuffer !== null) { + if (currentPosition > 0) { + buffers.push( + Buffer.from( + currentBuffer.buffer, + currentBuffer.byteOffset, + currentPosition + ) + ); + } + if ( + !leftOverBuffer || + leftOverBuffer.length < currentBuffer.length - currentPosition + ) { + leftOverBuffer = Buffer.from( + currentBuffer.buffer, + currentBuffer.byteOffset + currentPosition, + currentBuffer.byteLength - currentPosition + ); + } + + currentBuffer = null; + currentPosition = 0; + } + }; + const writeU8 = byte => { + currentBuffer.writeUInt8(byte, currentPosition++); + }; + const writeU32 = ui32 => { + currentBuffer.writeUInt32LE(ui32, currentPosition); + currentPosition += 4; + }; + const measureStack = []; + const measureStart = () => { + measureStack.push(buffers.length, currentPosition); + }; + const measureEnd = () => { + const oldPos = measureStack.pop(); + const buffersIndex = measureStack.pop(); + let size = currentPosition - oldPos; + for (let i = buffersIndex; i < buffers.length; i++) { + size += buffers[i].length; + } + return size; + }; + for (let i = 0; i < data.length; i++) { + const thing = data[i]; + switch (typeof thing) { + case "function": { + if (!SerializerMiddleware.isLazy(thing)) + throw new Error("Unexpected function " + thing); + /** @type {SerializedType | (() => SerializedType)} */ + let serializedData = + SerializerMiddleware.getLazySerializedValue(thing); + if (serializedData === undefined) { + if (SerializerMiddleware.isLazy(thing, this)) { + flush(); + allocationScope.leftOverBuffer = leftOverBuffer; + const result = + /** @type {(Exclude>)[]} */ ( + thing() + ); + const data = this._serialize(result, context, allocationScope); + leftOverBuffer = allocationScope.leftOverBuffer; + allocationScope.leftOverBuffer = null; + SerializerMiddleware.setLazySerializedValue(thing, data); + serializedData = data; + } else { + serializedData = this._serializeLazy(thing, context); + flush(); + buffers.push(serializedData); + break; + } + } else { + if (typeof serializedData === "function") { + flush(); + buffers.push(serializedData); + break; + } + } + const lengths = []; + for (const item of serializedData) { + let last; + if (typeof item === "function") { + lengths.push(0); + } else if (item.length === 0) { + // ignore + } else if ( + lengths.length > 0 && + (last = lengths[lengths.length - 1]) !== 0 + ) { + const remaining = 0xffffffff - last; + if (remaining >= item.length) { + lengths[lengths.length - 1] += item.length; } else { - list.push(data); + lengths.push(item.length - remaining); + lengths[lengths.length - 2] = 0xffffffff; } + } else { + lengths.push(item.length); } } - if (hashToAssets.size === 0) return; - const hashRegExp = new RegExp( - Array.from(hashToAssets.keys(), quoteMeta).join("|"), - "g" - ); - await Promise.all( - assetsWithInfo.map(async asset => { - const { name, source, content, hashes } = asset; - if (Buffer.isBuffer(content)) { - asset.referencedHashes = EMPTY_SET; - asset.ownHashes = EMPTY_SET; - return; - } - const etag = cacheAnalyse.mergeEtags( - cacheAnalyse.getLazyHashedEtag(source), - Array.from(hashes).join("|") - ); - [asset.referencedHashes, asset.ownHashes] = - await cacheAnalyse.providePromise(name, etag, () => { - const referencedHashes = new Set(); - let ownHashes = new Set(); - const inContent = content.match(hashRegExp); - if (inContent) { - for (const hash of inContent) { - if (hashes.has(hash)) { - ownHashes.add(hash); - continue; - } - referencedHashes.add(hash); - } - } - return [referencedHashes, ownHashes]; - }); - }) - ); - const getDependencies = hash => { - const assets = hashToAssets.get(hash); - if (!assets) { - const referencingAssets = assetsWithInfo.filter(asset => - asset.referencedHashes.has(hash) - ); - const err = new WebpackError(`RealContentHashPlugin -Some kind of unexpected caching problem occurred. -An asset was cached with a reference to another asset (${hash}) that's not in the compilation anymore. -Either the asset was incorrectly cached, or the referenced asset should also be restored from cache. -Referenced by: -${referencingAssets - .map(a => { - const match = new RegExp(`.{0,20}${quoteMeta(hash)}.{0,20}`).exec( - a.content - ); - return ` - ${a.name}: ...${match ? match[0] : "???"}...`; - }) - .join("\n")}`); - compilation.errors.push(err); - return undefined; + allocate(5 + lengths.length * 4); + writeU8(LAZY_HEADER); + writeU32(lengths.length); + for (const l of lengths) { + writeU32(l); + } + flush(); + for (const item of serializedData) { + buffers.push(item); + } + break; + } + case "string": { + const len = Buffer.byteLength(thing); + if (len >= 128 || len !== thing.length) { + allocate(len + HEADER_SIZE + I32_SIZE); + writeU8(STRING_HEADER); + writeU32(len); + currentBuffer.write(thing, currentPosition); + currentPosition += len; + } else if (len >= 70) { + allocate(len + HEADER_SIZE); + writeU8(SHORT_STRING_HEADER | len); + + currentBuffer.write(thing, currentPosition, "latin1"); + currentPosition += len; + } else { + allocate(len + HEADER_SIZE); + writeU8(SHORT_STRING_HEADER | len); + + for (let i = 0; i < len; i++) { + currentBuffer[currentPosition++] = thing.charCodeAt(i); } - const hashes = new Set(); - for (const { referencedHashes, ownHashes } of assets) { - if (!ownHashes.has(hash)) { - for (const hash of ownHashes) { - hashes.add(hash); - } + } + break; + } + case "number": { + const type = identifyNumber(thing); + if (type === 0 && thing >= 0 && thing <= 10) { + // shortcut for very small numbers + allocate(I8_SIZE); + writeU8(thing); + break; + } + /** + * amount of numbers to write + * @type {number} + */ + let n = 1; + for (; n < 32 && i + n < data.length; n++) { + const item = data[i + n]; + if (typeof item !== "number") break; + if (identifyNumber(item) !== type) break; + } + switch (type) { + case 0: + allocate(HEADER_SIZE + I8_SIZE * n); + writeU8(I8_HEADER | (n - 1)); + while (n > 0) { + currentBuffer.writeInt8( + /** @type {number} */ (data[i]), + currentPosition + ); + currentPosition += I8_SIZE; + n--; + i++; } - for (const hash of referencedHashes) { - hashes.add(hash); + break; + case 1: + allocate(HEADER_SIZE + I32_SIZE * n); + writeU8(I32_HEADER | (n - 1)); + while (n > 0) { + currentBuffer.writeInt32LE( + /** @type {number} */ (data[i]), + currentPosition + ); + currentPosition += I32_SIZE; + n--; + i++; } - } - return hashes; - }; - const hashInfo = hash => { - const assets = hashToAssets.get(hash); - return `${hash} (${Array.from(assets, a => a.name)})`; - }; - const hashesInOrder = new Set(); - for (const hash of hashToAssets.keys()) { - const add = (hash, stack) => { - const deps = getDependencies(hash); - if (!deps) return; - stack.add(hash); - for (const dep of deps) { - if (hashesInOrder.has(dep)) continue; - if (stack.has(dep)) { - throw new Error( - `Circular hash dependency ${Array.from( - stack, - hashInfo - ).join(" -> ")} -> ${hashInfo(dep)}` - ); - } - add(dep, stack); + break; + case 2: + allocate(HEADER_SIZE + F64_SIZE * n); + writeU8(F64_HEADER | (n - 1)); + while (n > 0) { + currentBuffer.writeDoubleLE( + /** @type {number} */ (data[i]), + currentPosition + ); + currentPosition += F64_SIZE; + n--; + i++; } - hashesInOrder.add(hash); - stack.delete(hash); - }; - if (hashesInOrder.has(hash)) continue; - add(hash, new Set()); + break; } - const hashToNewHash = new Map(); - const getEtag = asset => - cacheGenerate.mergeEtags( - cacheGenerate.getLazyHashedEtag(asset.source), - Array.from(asset.referencedHashes, hash => - hashToNewHash.get(hash) - ).join("|") + + i--; + break; + } + case "boolean": { + let lastByte = thing === true ? 1 : 0; + const bytes = []; + let count = 1; + let n; + for (n = 1; n < 0xffffffff && i + n < data.length; n++) { + const item = data[i + n]; + if (typeof item !== "boolean") break; + const pos = count & 0x7; + if (pos === 0) { + bytes.push(lastByte); + lastByte = item === true ? 1 : 0; + } else if (item === true) { + lastByte |= 1 << pos; + } + count++; + } + i += count - 1; + if (count === 1) { + allocate(HEADER_SIZE); + writeU8(lastByte === 1 ? TRUE_HEADER : FALSE_HEADER); + } else if (count === 2) { + allocate(HEADER_SIZE * 2); + writeU8(lastByte & 1 ? TRUE_HEADER : FALSE_HEADER); + writeU8(lastByte & 2 ? TRUE_HEADER : FALSE_HEADER); + } else if (count <= 6) { + allocate(HEADER_SIZE + I8_SIZE); + writeU8(BOOLEANS_HEADER); + writeU8((1 << count) | lastByte); + } else if (count <= 133) { + allocate(HEADER_SIZE + I8_SIZE + I8_SIZE * bytes.length + I8_SIZE); + writeU8(BOOLEANS_HEADER); + writeU8(0x80 | (count - 7)); + for (const byte of bytes) writeU8(byte); + writeU8(lastByte); + } else { + allocate( + HEADER_SIZE + + I8_SIZE + + I32_SIZE + + I8_SIZE * bytes.length + + I8_SIZE ); - const computeNewContent = asset => { - if (asset.contentComputePromise) return asset.contentComputePromise; - return (asset.contentComputePromise = (async () => { - if ( - asset.ownHashes.size > 0 || - Array.from(asset.referencedHashes).some( - hash => hashToNewHash.get(hash) !== hash - ) - ) { - const identifier = asset.name; - const etag = getEtag(asset); - asset.newSource = await cacheGenerate.providePromise( - identifier, - etag, - () => { - const newContent = asset.content.replace(hashRegExp, hash => - hashToNewHash.get(hash) - ); - return new RawSource(newContent); + writeU8(BOOLEANS_HEADER); + writeU8(0xff); + writeU32(count); + for (const byte of bytes) writeU8(byte); + writeU8(lastByte); + } + break; + } + case "object": { + if (thing === null) { + let n; + for (n = 1; n < 0x100000104 && i + n < data.length; n++) { + const item = data[i + n]; + if (item !== null) break; + } + i += n - 1; + if (n === 1) { + if (i + 1 < data.length) { + const next = data[i + 1]; + if (next === true) { + allocate(HEADER_SIZE); + writeU8(NULL_AND_TRUE_HEADER); + i++; + } else if (next === false) { + allocate(HEADER_SIZE); + writeU8(NULL_AND_FALSE_HEADER); + i++; + } else if (typeof next === "number") { + const type = identifyNumber(next); + if (type === 0) { + allocate(HEADER_SIZE + I8_SIZE); + writeU8(NULL_AND_I8_HEADER); + currentBuffer.writeInt8(next, currentPosition); + currentPosition += I8_SIZE; + i++; + } else if (type === 1) { + allocate(HEADER_SIZE + I32_SIZE); + writeU8(NULL_AND_I32_HEADER); + currentBuffer.writeInt32LE(next, currentPosition); + currentPosition += I32_SIZE; + i++; + } else { + allocate(HEADER_SIZE); + writeU8(NULL_HEADER); } - ); + } else { + allocate(HEADER_SIZE); + writeU8(NULL_HEADER); + } + } else { + allocate(HEADER_SIZE); + writeU8(NULL_HEADER); } - })()); + } else if (n === 2) { + allocate(HEADER_SIZE); + writeU8(NULL2_HEADER); + } else if (n === 3) { + allocate(HEADER_SIZE); + writeU8(NULL3_HEADER); + } else if (n < 260) { + allocate(HEADER_SIZE + I8_SIZE); + writeU8(NULLS8_HEADER); + writeU8(n - 4); + } else { + allocate(HEADER_SIZE + I32_SIZE); + writeU8(NULLS32_HEADER); + writeU32(n - 260); + } + } else if (Buffer.isBuffer(thing)) { + if (thing.length < 8192) { + allocate(HEADER_SIZE + I32_SIZE + thing.length); + writeU8(BUFFER_HEADER); + writeU32(thing.length); + thing.copy(currentBuffer, currentPosition); + currentPosition += thing.length; + } else { + allocate(HEADER_SIZE + I32_SIZE); + writeU8(BUFFER_HEADER); + writeU32(thing.length); + flush(); + buffers.push(thing); + } + } + break; + } + case "symbol": { + if (thing === MEASURE_START_OPERATION) { + measureStart(); + } else if (thing === MEASURE_END_OPERATION) { + const size = measureEnd(); + allocate(HEADER_SIZE + I32_SIZE); + writeU8(I32_HEADER); + currentBuffer.writeInt32LE(size, currentPosition); + currentPosition += I32_SIZE; + } + break; + } + } + } + flush(); + + allocationScope.leftOverBuffer = leftOverBuffer; + + // avoid leaking memory + currentBuffer = null; + leftOverBuffer = null; + allocationScope = undefined; + const _buffers = buffers; + buffers = undefined; + return _buffers; + } + + /** + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data + */ + deserialize(data, context) { + return this._deserialize(data, context); + } + + _createLazyDeserialized(content, context) { + return SerializerMiddleware.createLazy( + memoize(() => this._deserialize(content, context)), + this, + undefined, + content + ); + } + + _deserializeLazy(fn, context) { + return SerializerMiddleware.deserializeLazy(fn, data => + this._deserialize(data, context) + ); + } + + /** + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType} deserialized data + */ + _deserialize(data, context) { + let currentDataItem = 0; + let currentBuffer = data[0]; + let currentIsBuffer = Buffer.isBuffer(currentBuffer); + let currentPosition = 0; + + const retainedBuffer = context.retainedBuffer || (x => x); + + const checkOverflow = () => { + if (currentPosition >= currentBuffer.length) { + currentPosition = 0; + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); + } + }; + const isInCurrentBuffer = n => { + return currentIsBuffer && n + currentPosition <= currentBuffer.length; + }; + const ensureBuffer = () => { + if (!currentIsBuffer) { + throw new Error( + currentBuffer === null + ? "Unexpected end of stream" + : "Unexpected lazy element in stream" + ); + } + }; + /** + * Reads n bytes + * @param {number} n amount of bytes to read + * @returns {Buffer} buffer with bytes + */ + const read = n => { + ensureBuffer(); + const rem = currentBuffer.length - currentPosition; + if (rem < n) { + const buffers = [read(rem)]; + n -= rem; + ensureBuffer(); + while (currentBuffer.length < n) { + const b = /** @type {Buffer} */ (currentBuffer); + buffers.push(b); + n -= b.length; + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); + ensureBuffer(); + } + buffers.push(read(n)); + return Buffer.concat(buffers); + } + const b = /** @type {Buffer} */ (currentBuffer); + const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n); + currentPosition += n; + checkOverflow(); + return res; + }; + /** + * Reads up to n bytes + * @param {number} n amount of bytes to read + * @returns {Buffer} buffer with bytes + */ + const readUpTo = n => { + ensureBuffer(); + const rem = currentBuffer.length - currentPosition; + if (rem < n) { + n = rem; + } + const b = /** @type {Buffer} */ (currentBuffer); + const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n); + currentPosition += n; + checkOverflow(); + return res; + }; + const readU8 = () => { + ensureBuffer(); + /** + * There is no need to check remaining buffer size here + * since {@link checkOverflow} guarantees at least one byte remaining + */ + const byte = /** @type {Buffer} */ (currentBuffer).readUInt8( + currentPosition + ); + currentPosition += I8_SIZE; + checkOverflow(); + return byte; + }; + const readU32 = () => { + return read(I32_SIZE).readUInt32LE(0); + }; + const readBits = (data, n) => { + let mask = 1; + while (n !== 0) { + result.push((data & mask) !== 0); + mask = mask << 1; + n--; + } + }; + const dispatchTable = Array.from({ length: 256 }).map((_, header) => { + switch (header) { + case LAZY_HEADER: + return () => { + const count = readU32(); + const lengths = Array.from({ length: count }).map(() => readU32()); + const content = []; + for (let l of lengths) { + if (l === 0) { + if (typeof currentBuffer !== "function") { + throw new Error("Unexpected non-lazy element in stream"); + } + content.push(currentBuffer); + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); + } else { + do { + const buf = readUpTo(l); + l -= buf.length; + content.push(retainedBuffer(buf)); + } while (l > 0); + } + } + result.push(this._createLazyDeserialized(content, context)); }; - const computeNewContentWithoutOwn = asset => { - if (asset.contentComputeWithoutOwnPromise) - return asset.contentComputeWithoutOwnPromise; - return (asset.contentComputeWithoutOwnPromise = (async () => { - if ( - asset.ownHashes.size > 0 || - Array.from(asset.referencedHashes).some( - hash => hashToNewHash.get(hash) !== hash + case BUFFER_HEADER: + return () => { + const len = readU32(); + result.push(retainedBuffer(read(len))); + }; + case TRUE_HEADER: + return () => result.push(true); + case FALSE_HEADER: + return () => result.push(false); + case NULL3_HEADER: + return () => result.push(null, null, null); + case NULL2_HEADER: + return () => result.push(null, null); + case NULL_HEADER: + return () => result.push(null); + case NULL_AND_TRUE_HEADER: + return () => result.push(null, true); + case NULL_AND_FALSE_HEADER: + return () => result.push(null, false); + case NULL_AND_I8_HEADER: + return () => { + if (currentIsBuffer) { + result.push( + null, + /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition) + ); + currentPosition += I8_SIZE; + checkOverflow(); + } else { + result.push(null, read(I8_SIZE).readInt8(0)); + } + }; + case NULL_AND_I32_HEADER: + return () => { + result.push(null); + if (isInCurrentBuffer(I32_SIZE)) { + result.push( + /** @type {Buffer} */ (currentBuffer).readInt32LE( + currentPosition ) - ) { - const identifier = asset.name + "|without-own"; - const etag = getEtag(asset); - asset.newSourceWithoutOwn = await cacheGenerate.providePromise( - identifier, - etag, - () => { - const newContent = asset.content.replace( - hashRegExp, - hash => { - if (asset.ownHashes.has(hash)) { - return ""; - } - return hashToNewHash.get(hash); - } - ); - return new RawSource(newContent); - } - ); - } - })()); + ); + currentPosition += I32_SIZE; + checkOverflow(); + } else { + result.push(read(I32_SIZE).readInt32LE(0)); + } }; - const comparator = compareSelect(a => a.name, compareStrings); - for (const oldHash of hashesInOrder) { - const assets = hashToAssets.get(oldHash); - assets.sort(comparator); - const hash = createHash(this._hashFunction); - await Promise.all( - assets.map(asset => - asset.ownHashes.has(oldHash) - ? computeNewContentWithoutOwn(asset) - : computeNewContent(asset) - ) - ); - const assetsContent = mapAndDeduplicateBuffers(assets, asset => { - if (asset.ownHashes.has(oldHash)) { - return asset.newSourceWithoutOwn - ? asset.newSourceWithoutOwn.buffer() - : asset.source.buffer(); - } else { - return asset.newSource - ? asset.newSource.buffer() - : asset.source.buffer(); + case NULLS8_HEADER: + return () => { + const len = readU8() + 4; + for (let i = 0; i < len; i++) { + result.push(null); + } + }; + case NULLS32_HEADER: + return () => { + const len = readU32() + 260; + for (let i = 0; i < len; i++) { + result.push(null); + } + }; + case BOOLEANS_HEADER: + return () => { + const innerHeader = readU8(); + if ((innerHeader & 0xf0) === 0) { + readBits(innerHeader, 3); + } else if ((innerHeader & 0xe0) === 0) { + readBits(innerHeader, 4); + } else if ((innerHeader & 0xc0) === 0) { + readBits(innerHeader, 5); + } else if ((innerHeader & 0x80) === 0) { + readBits(innerHeader, 6); + } else if (innerHeader !== 0xff) { + let count = (innerHeader & 0x7f) + 7; + while (count > 8) { + readBits(readU8(), 8); + count -= 8; } - }); - let newHash = hooks.updateHash.call(assetsContent, oldHash); - if (!newHash) { - for (const content of assetsContent) { - hash.update(content); + readBits(readU8(), count); + } else { + let count = readU32(); + while (count > 8) { + readBits(readU8(), 8); + count -= 8; } - const digest = hash.digest(this._hashDigest); - newHash = /** @type {string} */ (digest.slice(0, oldHash.length)); + readBits(readU8(), count); } - hashToNewHash.set(oldHash, newHash); - } - await Promise.all( - assetsWithInfo.map(async asset => { - await computeNewContent(asset); - const newName = asset.name.replace(hashRegExp, hash => - hashToNewHash.get(hash) + }; + case STRING_HEADER: + return () => { + const len = readU32(); + if (isInCurrentBuffer(len) && currentPosition + len < 0x7fffffff) { + result.push( + currentBuffer.toString( + undefined, + currentPosition, + currentPosition + len + ) ); - - const infoUpdate = {}; - const hash = asset.info.contenthash; - infoUpdate.contenthash = Array.isArray(hash) - ? hash.map(hash => hashToNewHash.get(hash)) - : hashToNewHash.get(hash); - - if (asset.newSource !== undefined) { - compilation.updateAsset( - asset.name, - asset.newSource, - infoUpdate + currentPosition += len; + checkOverflow(); + } else { + result.push(read(len).toString()); + } + }; + case SHORT_STRING_HEADER: + return () => result.push(""); + case SHORT_STRING_HEADER | 1: + return () => { + if (currentIsBuffer && currentPosition < 0x7ffffffe) { + result.push( + currentBuffer.toString( + "latin1", + currentPosition, + currentPosition + 1 + ) + ); + currentPosition++; + checkOverflow(); + } else { + result.push(read(1).toString("latin1")); + } + }; + case I8_HEADER: + return () => { + if (currentIsBuffer) { + result.push( + /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition) + ); + currentPosition++; + checkOverflow(); + } else { + result.push(read(1).readInt8(0)); + } + }; + default: + if (header <= 10) { + return () => result.push(header); + } else if ((header & SHORT_STRING_HEADER) === SHORT_STRING_HEADER) { + const len = header & SHORT_STRING_LENGTH_MASK; + return () => { + if ( + isInCurrentBuffer(len) && + currentPosition + len < 0x7fffffff + ) { + result.push( + currentBuffer.toString( + "latin1", + currentPosition, + currentPosition + len + ) ); + currentPosition += len; + checkOverflow(); } else { - compilation.updateAsset(asset.name, asset.source, infoUpdate); + result.push(read(len).toString("latin1")); } - - if (asset.name !== newName) { - compilation.renameAsset(asset.name, newName); + }; + } else if ((header & NUMBERS_HEADER_MASK) === F64_HEADER) { + const len = (header & NUMBERS_COUNT_MASK) + 1; + return () => { + const need = F64_SIZE * len; + if (isInCurrentBuffer(need)) { + for (let i = 0; i < len; i++) { + result.push( + /** @type {Buffer} */ (currentBuffer).readDoubleLE( + currentPosition + ) + ); + currentPosition += F64_SIZE; + } + checkOverflow(); + } else { + const buf = read(need); + for (let i = 0; i < len; i++) { + result.push(buf.readDoubleLE(i * F64_SIZE)); + } } - }) - ); - } - ); + }; + } else if ((header & NUMBERS_HEADER_MASK) === I32_HEADER) { + const len = (header & NUMBERS_COUNT_MASK) + 1; + return () => { + const need = I32_SIZE * len; + if (isInCurrentBuffer(need)) { + for (let i = 0; i < len; i++) { + result.push( + /** @type {Buffer} */ (currentBuffer).readInt32LE( + currentPosition + ) + ); + currentPosition += I32_SIZE; + } + checkOverflow(); + } else { + const buf = read(need); + for (let i = 0; i < len; i++) { + result.push(buf.readInt32LE(i * I32_SIZE)); + } + } + }; + } else if ((header & NUMBERS_HEADER_MASK) === I8_HEADER) { + const len = (header & NUMBERS_COUNT_MASK) + 1; + return () => { + const need = I8_SIZE * len; + if (isInCurrentBuffer(need)) { + for (let i = 0; i < len; i++) { + result.push( + /** @type {Buffer} */ (currentBuffer).readInt8( + currentPosition + ) + ); + currentPosition += I8_SIZE; + } + checkOverflow(); + } else { + const buf = read(need); + for (let i = 0; i < len; i++) { + result.push(buf.readInt8(i * I8_SIZE)); + } + } + }; + } else { + return () => { + throw new Error( + `Unexpected header byte 0x${header.toString(16)}` + ); + }; + } + } }); + + /** @type {DeserializedType} */ + let result = []; + while (currentBuffer !== null) { + if (typeof currentBuffer === "function") { + result.push(this._deserializeLazy(currentBuffer, context)); + currentDataItem++; + currentBuffer = + currentDataItem < data.length ? data[currentDataItem] : null; + currentIsBuffer = Buffer.isBuffer(currentBuffer); + } else { + const header = readU8(); + dispatchTable[header](); + } + } + + // avoid leaking memory in context + let _result = result; + result = undefined; + return _result; } } -module.exports = RealContentHashPlugin; +module.exports = BinaryMiddleware; + +module.exports.MEASURE_START_OPERATION = MEASURE_START_OPERATION; +module.exports.MEASURE_END_OPERATION = MEASURE_END_OPERATION; /***/ }), -/***/ 84760: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 93475: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const { STAGE_BASIC, STAGE_ADVANCED } = __webpack_require__(80057); - -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ - -class RemoveEmptyChunksPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap("RemoveEmptyChunksPlugin", compilation => { - /** - * @param {Iterable} chunks the chunks array - * @returns {void} - */ - const handler = chunks => { - const chunkGraph = compilation.chunkGraph; - for (const chunk of chunks) { - if ( - chunkGraph.getNumberOfChunkModules(chunk) === 0 && - !chunk.hasRuntime() && - chunkGraph.getNumberOfEntryModules(chunk) === 0 - ) { - compilation.chunkGraph.disconnectChunk(chunk); - compilation.chunks.delete(chunk); - } - } - }; - - // TODO do it once - compilation.hooks.optimizeChunks.tap( - { - name: "RemoveEmptyChunksPlugin", - stage: STAGE_BASIC - }, - handler - ); - compilation.hooks.optimizeChunks.tap( - { - name: "RemoveEmptyChunksPlugin", - stage: STAGE_ADVANCED - }, - handler - ); - }); +class DateObjectSerializer { + serialize(obj, { write }) { + write(obj.getTime()); + } + deserialize({ read }) { + return new Date(read()); } } -module.exports = RemoveEmptyChunksPlugin; + +module.exports = DateObjectSerializer; /***/ }), -/***/ 7081: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 79479: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const { STAGE_BASIC } = __webpack_require__(80057); -const Queue = __webpack_require__(65930); -const { intersect } = __webpack_require__(93347); - -/** @typedef {import("../Compiler")} Compiler */ +class ErrorObjectSerializer { + constructor(Type) { + this.Type = Type; + } -class RemoveParentModulesPlugin { - /** - * @param {Compiler} compiler the compiler - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap("RemoveParentModulesPlugin", compilation => { - const handler = (chunks, chunkGroups) => { - const chunkGraph = compilation.chunkGraph; - const queue = new Queue(); - const availableModulesMap = new WeakMap(); + serialize(obj, { write }) { + write(obj.message); + write(obj.stack); + } - for (const chunkGroup of compilation.entrypoints.values()) { - // initialize available modules for chunks without parents - availableModulesMap.set(chunkGroup, new Set()); - for (const child of chunkGroup.childrenIterable) { - queue.enqueue(child); - } - } - for (const chunkGroup of compilation.asyncEntrypoints) { - // initialize available modules for chunks without parents - availableModulesMap.set(chunkGroup, new Set()); - for (const child of chunkGroup.childrenIterable) { - queue.enqueue(child); - } - } + deserialize({ read }) { + const err = new this.Type(); - while (queue.length > 0) { - const chunkGroup = queue.dequeue(); - let availableModules = availableModulesMap.get(chunkGroup); - let changed = false; - for (const parent of chunkGroup.parentsIterable) { - const availableModulesInParent = availableModulesMap.get(parent); - if (availableModulesInParent !== undefined) { - // If we know the available modules in parent: process these - if (availableModules === undefined) { - // if we have not own info yet: create new entry - availableModules = new Set(availableModulesInParent); - for (const chunk of parent.chunks) { - for (const m of chunkGraph.getChunkModulesIterable(chunk)) { - availableModules.add(m); - } - } - availableModulesMap.set(chunkGroup, availableModules); - changed = true; - } else { - for (const m of availableModules) { - if ( - !chunkGraph.isModuleInChunkGroup(m, parent) && - !availableModulesInParent.has(m) - ) { - availableModules.delete(m); - changed = true; - } - } - } - } - } - if (changed) { - // if something changed: enqueue our children - for (const child of chunkGroup.childrenIterable) { - queue.enqueue(child); - } - } - } + err.message = read(); + err.stack = read(); - // now we have available modules for every chunk - for (const chunk of chunks) { - const availableModulesSets = Array.from( - chunk.groupsIterable, - chunkGroup => availableModulesMap.get(chunkGroup) - ); - if (availableModulesSets.some(s => s === undefined)) continue; // No info about this chunk group - const availableModules = - availableModulesSets.length === 1 - ? availableModulesSets[0] - : intersect(availableModulesSets); - const numberOfModules = chunkGraph.getNumberOfChunkModules(chunk); - const toRemove = new Set(); - if (numberOfModules < availableModules.size) { - for (const m of chunkGraph.getChunkModulesIterable(chunk)) { - if (availableModules.has(m)) { - toRemove.add(m); - } - } - } else { - for (const m of availableModules) { - if (chunkGraph.isModuleInChunk(m, chunk)) { - toRemove.add(m); - } - } - } - for (const module of toRemove) { - chunkGraph.disconnectChunkAndModule(chunk, module); - } - } - }; - compilation.hooks.optimizeChunks.tap( - { - name: "RemoveParentModulesPlugin", - stage: STAGE_BASIC - }, - handler - ); - }); + return err; } } -module.exports = RemoveParentModulesPlugin; + +module.exports = ErrorObjectSerializer; /***/ }), -/***/ 2837: -/***/ (function(module) { +/***/ 65321: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -/** @typedef {import("../Compiler")} Compiler */ +const { constants } = __webpack_require__(14300); +const { pipeline } = __webpack_require__(12781); +const { + createBrotliCompress, + createBrotliDecompress, + createGzip, + createGunzip, + constants: zConstants +} = __webpack_require__(59796); +const createHash = __webpack_require__(49835); +const { dirname, join, mkdirp } = __webpack_require__(17139); +const memoize = __webpack_require__(78676); +const SerializerMiddleware = __webpack_require__(83137); -class RuntimeChunkPlugin { - constructor(options) { - this.options = { - name: entrypoint => `runtime~${entrypoint.name}`, - ...options - }; - } +/** @typedef {typeof import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ +/** @typedef {import("./types").BufferSerializableType} BufferSerializableType */ - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap("RuntimeChunkPlugin", compilation => { - compilation.hooks.addEntry.tap( - "RuntimeChunkPlugin", - (_, { name: entryName }) => { - if (entryName === undefined) return; - const data = compilation.entries.get(entryName); - if (data.options.runtime === undefined && !data.options.dependOn) { - // Determine runtime chunk name - let name = this.options.name; - if (typeof name === "function") { - name = name({ name: entryName }); - } - data.options.runtime = name; - } - } - ); - }); - } -} +/* +Format: -module.exports = RuntimeChunkPlugin; +File -> Header Section* +Version -> u32 +AmountOfSections -> u32 +SectionSize -> i32 (if less than zero represents lazy value) -/***/ }), +Header -> Version AmountOfSections SectionSize* -/***/ 84800: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +Buffer -> n bytes +Section -> Buffer -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ +// "wpc" + 1 in little-endian +const VERSION = 0x01637077; +/** + * @param {Buffer[]} buffers buffers + * @param {string | Hash} hashFunction hash function to use + * @returns {string} hash + */ +const hashForName = (buffers, hashFunction) => { + const hash = createHash(hashFunction); + for (const buf of buffers) hash.update(buf); + return /** @type {string} */ (hash.digest("hex")); +}; -const glob2regexp = __webpack_require__(86140); -const { STAGE_DEFAULT } = __webpack_require__(80057); -const HarmonyExportImportedSpecifierDependency = __webpack_require__(67157); -const HarmonyImportSpecifierDependency = __webpack_require__(14077); -const formatLocation = __webpack_require__(16734); +const COMPRESSION_CHUNK_SIZE = 100 * 1024 * 1024; +const DECOMPRESSION_CHUNK_SIZE = 100 * 1024 * 1024; -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */ +const writeUInt64LE = Buffer.prototype.writeBigUInt64LE + ? (buf, value, offset) => { + buf.writeBigUInt64LE(BigInt(value), offset); + } + : (buf, value, offset) => { + const low = value % 0x100000000; + const high = (value - low) / 0x100000000; + buf.writeUInt32LE(low, offset); + buf.writeUInt32LE(high, offset + 4); + }; + +const readUInt64LE = Buffer.prototype.readBigUInt64LE + ? (buf, offset) => { + return Number(buf.readBigUInt64LE(offset)); + } + : (buf, offset) => { + const low = buf.readUInt32LE(offset); + const high = buf.readUInt32LE(offset + 4); + return high * 0x100000000 + low; + }; /** - * @typedef {Object} ExportInModule - * @property {Module} module the module - * @property {string} exportName the name of the export - * @property {boolean} checked if the export is conditional + * @typedef {Object} SerializeResult + * @property {string | false} name + * @property {number} size + * @property {Promise=} backgroundJob */ /** - * @typedef {Object} ReexportInfo - * @property {Map} static - * @property {Map>} dynamic + * @param {FileMiddleware} middleware this + * @param {BufferSerializableType[] | Promise} data data to be serialized + * @param {string | boolean} name file base name + * @param {function(string | false, Buffer[]): Promise} writeFile writes a file + * @param {string | Hash} hashFunction hash function to use + * @returns {Promise} resulting file pointer and promise */ +const serialize = async ( + middleware, + data, + name, + writeFile, + hashFunction = "md4" +) => { + /** @type {(Buffer[] | Buffer | SerializeResult | Promise)[]} */ + const processedData = []; + /** @type {WeakMap>} */ + const resultToLazy = new WeakMap(); + /** @type {Buffer[]} */ + let lastBuffers = undefined; + for (const item of await data) { + if (typeof item === "function") { + if (!SerializerMiddleware.isLazy(item)) + throw new Error("Unexpected function"); + if (!SerializerMiddleware.isLazy(item, middleware)) { + throw new Error( + "Unexpected lazy value with non-this target (can't pass through lazy values)" + ); + } + lastBuffers = undefined; + const serializedInfo = SerializerMiddleware.getLazySerializedValue(item); + if (serializedInfo) { + if (typeof serializedInfo === "function") { + throw new Error( + "Unexpected lazy value with non-this target (can't pass through lazy values)" + ); + } else { + processedData.push(serializedInfo); + } + } else { + const content = item(); + if (content) { + const options = SerializerMiddleware.getLazyOptions(item); + processedData.push( + serialize( + middleware, + content, + (options && options.name) || true, + writeFile, + hashFunction + ).then(result => { + /** @type {any} */ (item).options.size = result.size; + resultToLazy.set(result, item); + return result; + }) + ); + } else { + throw new Error( + "Unexpected falsy value returned by lazy value function" + ); + } + } + } else if (item) { + if (lastBuffers) { + lastBuffers.push(item); + } else { + lastBuffers = [item]; + processedData.push(lastBuffers); + } + } else { + throw new Error("Unexpected falsy value in items array"); + } + } + /** @type {Promise[]} */ + const backgroundJobs = []; + const resolvedData = ( + await Promise.all( + /** @type {Promise[]} */ ( + processedData + ) + ) + ).map(item => { + if (Array.isArray(item) || Buffer.isBuffer(item)) return item; -/** @type {WeakMap>} */ -const globToRegexpCache = new WeakMap(); + backgroundJobs.push(item.backgroundJob); + // create pointer buffer from size and name + const name = /** @type {string} */ (item.name); + const nameBuffer = Buffer.from(name); + const buf = Buffer.allocUnsafe(8 + nameBuffer.length); + writeUInt64LE(buf, item.size, 0); + nameBuffer.copy(buf, 8, 0); + const lazy = resultToLazy.get(item); + SerializerMiddleware.setLazySerializedValue(lazy, buf); + return buf; + }); + const lengths = []; + for (const item of resolvedData) { + if (Array.isArray(item)) { + let l = 0; + for (const b of item) l += b.length; + while (l > 0x7fffffff) { + lengths.push(0x7fffffff); + l -= 0x7fffffff; + } + lengths.push(l); + } else if (item) { + lengths.push(-item.length); + } else { + throw new Error("Unexpected falsy value in resolved data " + item); + } + } + const header = Buffer.allocUnsafe(8 + lengths.length * 4); + header.writeUInt32LE(VERSION, 0); + header.writeUInt32LE(lengths.length, 4); + for (let i = 0; i < lengths.length; i++) { + header.writeInt32LE(lengths[i], 8 + i * 4); + } + const buf = [header]; + for (const item of resolvedData) { + if (Array.isArray(item)) { + for (const b of item) buf.push(b); + } else if (item) { + buf.push(item); + } + } + if (name === true) { + name = hashForName(buf, hashFunction); + } + backgroundJobs.push(writeFile(name, buf)); + let size = 0; + for (const b of buf) size += b.length; + return { + size, + name, + backgroundJob: + backgroundJobs.length === 1 + ? backgroundJobs[0] + : Promise.all(backgroundJobs) + }; +}; /** - * @param {string} glob the pattern - * @param {Map} cache the glob to RegExp cache - * @returns {RegExp} a regular expression + * @param {FileMiddleware} middleware this + * @param {string | false} name filename + * @param {function(string | false): Promise} readFile read content of a file + * @returns {Promise} deserialized data */ -const globToRegexp = (glob, cache) => { - const cacheEntry = cache.get(glob); - if (cacheEntry !== undefined) return cacheEntry; - if (!glob.includes("/")) { - glob = `**/${glob}`; +const deserialize = async (middleware, name, readFile) => { + const contents = await readFile(name); + if (contents.length === 0) throw new Error("Empty file " + name); + let contentsIndex = 0; + let contentItem = contents[0]; + let contentItemLength = contentItem.length; + let contentPosition = 0; + if (contentItemLength === 0) throw new Error("Empty file " + name); + const nextContent = () => { + contentsIndex++; + contentItem = contents[contentsIndex]; + contentItemLength = contentItem.length; + contentPosition = 0; + }; + const ensureData = n => { + if (contentPosition === contentItemLength) { + nextContent(); + } + while (contentItemLength - contentPosition < n) { + const remaining = contentItem.slice(contentPosition); + let lengthFromNext = n - remaining.length; + const buffers = [remaining]; + for (let i = contentsIndex + 1; i < contents.length; i++) { + const l = contents[i].length; + if (l > lengthFromNext) { + buffers.push(contents[i].slice(0, lengthFromNext)); + contents[i] = contents[i].slice(lengthFromNext); + lengthFromNext = 0; + break; + } else { + buffers.push(contents[i]); + contentsIndex = i; + lengthFromNext -= l; + } + } + if (lengthFromNext > 0) throw new Error("Unexpected end of data"); + contentItem = Buffer.concat(buffers, n); + contentItemLength = n; + contentPosition = 0; + } + }; + const readUInt32LE = () => { + ensureData(4); + const value = contentItem.readUInt32LE(contentPosition); + contentPosition += 4; + return value; + }; + const readInt32LE = () => { + ensureData(4); + const value = contentItem.readInt32LE(contentPosition); + contentPosition += 4; + return value; + }; + const readSlice = l => { + ensureData(l); + if (contentPosition === 0 && contentItemLength === l) { + const result = contentItem; + if (contentsIndex + 1 < contents.length) { + nextContent(); + } else { + contentPosition = l; + } + return result; + } + const result = contentItem.slice(contentPosition, contentPosition + l); + contentPosition += l; + // we clone the buffer here to allow the original content to be garbage collected + return l * 2 < contentItem.buffer.byteLength ? Buffer.from(result) : result; + }; + const version = readUInt32LE(); + if (version !== VERSION) { + throw new Error("Invalid file version"); } - const baseRegexp = glob2regexp(glob, { globstar: true, extended: true }); - const regexpSource = baseRegexp.source; - const regexp = new RegExp("^(\\./)?" + regexpSource.slice(1)); - cache.set(glob, regexp); - return regexp; + const sectionCount = readUInt32LE(); + const lengths = []; + let lastLengthPositive = false; + for (let i = 0; i < sectionCount; i++) { + const value = readInt32LE(); + const valuePositive = value >= 0; + if (lastLengthPositive && valuePositive) { + lengths[lengths.length - 1] += value; + } else { + lengths.push(value); + lastLengthPositive = valuePositive; + } + } + const result = []; + for (let length of lengths) { + if (length < 0) { + const slice = readSlice(-length); + const size = Number(readUInt64LE(slice, 0)); + const nameBuffer = slice.slice(8); + const name = nameBuffer.toString(); + result.push( + SerializerMiddleware.createLazy( + memoize(() => deserialize(middleware, name, readFile)), + middleware, + { + name, + size + }, + slice + ) + ); + } else { + if (contentPosition === contentItemLength) { + nextContent(); + } else if (contentPosition !== 0) { + if (length <= contentItemLength - contentPosition) { + result.push( + Buffer.from( + contentItem.buffer, + contentItem.byteOffset + contentPosition, + length + ) + ); + contentPosition += length; + length = 0; + } else { + const l = contentItemLength - contentPosition; + result.push( + Buffer.from( + contentItem.buffer, + contentItem.byteOffset + contentPosition, + l + ) + ); + length -= l; + contentPosition = contentItemLength; + } + } else { + if (length >= contentItemLength) { + result.push(contentItem); + length -= contentItemLength; + contentPosition = contentItemLength; + } else { + result.push( + Buffer.from(contentItem.buffer, contentItem.byteOffset, length) + ); + contentPosition += length; + length = 0; + } + } + while (length > 0) { + nextContent(); + if (length >= contentItemLength) { + result.push(contentItem); + length -= contentItemLength; + contentPosition = contentItemLength; + } else { + result.push( + Buffer.from(contentItem.buffer, contentItem.byteOffset, length) + ); + contentPosition += length; + length = 0; + } + } + } + } + return result; }; -class SideEffectsFlagPlugin { +/** + * @typedef {BufferSerializableType[]} DeserializedType + * @typedef {true} SerializedType + * @extends {SerializerMiddleware} + */ +class FileMiddleware extends SerializerMiddleware { /** - * @param {boolean} analyseSource analyse source code for side effects + * @param {IntermediateFileSystem} fs filesystem + * @param {string | Hash} hashFunction hash function to use */ - constructor(analyseSource = true) { - this._analyseSource = analyseSource; + constructor(fs, hashFunction = "md4") { + super(); + this.fs = fs; + this._hashFunction = hashFunction; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType|Promise} serialized data */ - apply(compiler) { - let cache = globToRegexpCache.get(compiler.root); - if (cache === undefined) { - cache = new Map(); - globToRegexpCache.set(compiler.root, cache); - } - compiler.hooks.compilation.tap( - "SideEffectsFlagPlugin", - (compilation, { normalModuleFactory }) => { - const moduleGraph = compilation.moduleGraph; - normalModuleFactory.hooks.module.tap( - "SideEffectsFlagPlugin", - (module, data) => { - const resolveData = data.resourceResolveData; - if ( - resolveData && - resolveData.descriptionFileData && - resolveData.relativePath - ) { - const sideEffects = resolveData.descriptionFileData.sideEffects; - if (sideEffects !== undefined) { - if (module.factoryMeta === undefined) { - module.factoryMeta = {}; + serialize(data, context) { + const { filename, extension = "" } = context; + return new Promise((resolve, reject) => { + mkdirp(this.fs, dirname(this.fs, filename), err => { + if (err) return reject(err); + + // It's important that we don't touch existing files during serialization + // because serialize may read existing files (when deserializing) + const allWrittenFiles = new Set(); + const writeFile = async (name, content) => { + const file = name + ? join(this.fs, filename, `../${name}${extension}`) + : filename; + await new Promise((resolve, reject) => { + let stream = this.fs.createWriteStream(file + "_"); + let compression; + if (file.endsWith(".gz")) { + compression = createGzip({ + chunkSize: COMPRESSION_CHUNK_SIZE, + level: zConstants.Z_BEST_SPEED + }); + } else if (file.endsWith(".br")) { + compression = createBrotliCompress({ + chunkSize: COMPRESSION_CHUNK_SIZE, + params: { + [zConstants.BROTLI_PARAM_MODE]: zConstants.BROTLI_MODE_TEXT, + [zConstants.BROTLI_PARAM_QUALITY]: 2, + [zConstants.BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING]: true, + [zConstants.BROTLI_PARAM_SIZE_HINT]: content.reduce( + (size, b) => size + b.length, + 0 + ) } - const hasSideEffects = - SideEffectsFlagPlugin.moduleHasSideEffects( - resolveData.relativePath, - sideEffects, - cache - ); - module.factoryMeta.sideEffectFree = !hasSideEffects; - } + }); + } + if (compression) { + pipeline(compression, stream, reject); + stream = compression; + stream.on("finish", () => resolve()); + } else { + stream.on("error", err => reject(err)); + stream.on("finish", () => resolve()); } + for (const b of content) stream.write(b); + stream.end(); + }); + if (name) allWrittenFiles.add(file); + }; - return module; - } - ); - normalModuleFactory.hooks.module.tap( - "SideEffectsFlagPlugin", - (module, data) => { - if (typeof data.settings.sideEffects === "boolean") { - if (module.factoryMeta === undefined) { - module.factoryMeta = {}; - } - module.factoryMeta.sideEffectFree = !data.settings.sideEffects; + resolve( + serialize(this, data, false, writeFile, this._hashFunction).then( + async ({ backgroundJob }) => { + await backgroundJob; + + // Rename the index file to disallow access during inconsistent file state + await new Promise(resolve => + this.fs.rename(filename, filename + ".old", err => { + resolve(); + }) + ); + + // update all written files + await Promise.all( + Array.from( + allWrittenFiles, + file => + new Promise((resolve, reject) => { + this.fs.rename(file + "_", file, err => { + if (err) return reject(err); + resolve(); + }); + }) + ) + ); + + // As final step automatically update the index file to have a consistent pack again + await new Promise(resolve => { + this.fs.rename(filename + "_", filename, err => { + if (err) return reject(err); + resolve(); + }); + }); + return /** @type {true} */ (true); } - return module; - } + ) ); - if (this._analyseSource) { - /** - * @param {JavascriptParser} parser the parser - * @returns {void} - */ - const parserHandler = parser => { - let sideEffectsStatement; - parser.hooks.program.tap("SideEffectsFlagPlugin", () => { - sideEffectsStatement = undefined; + }); + }); + } + + /** + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data + */ + deserialize(data, context) { + const { filename, extension = "" } = context; + const readFile = name => + new Promise((resolve, reject) => { + const file = name + ? join(this.fs, filename, `../${name}${extension}`) + : filename; + this.fs.stat(file, (err, stats) => { + if (err) { + reject(err); + return; + } + let remaining = /** @type {number} */ (stats.size); + let currentBuffer; + let currentBufferUsed; + const buf = []; + let decompression; + if (file.endsWith(".gz")) { + decompression = createGunzip({ + chunkSize: DECOMPRESSION_CHUNK_SIZE }); - parser.hooks.statement.tap( - { name: "SideEffectsFlagPlugin", stage: -100 }, - statement => { - if (sideEffectsStatement) return; - if (parser.scope.topLevelScope !== true) return; - switch (statement.type) { - case "ExpressionStatement": - if ( - !parser.isPure(statement.expression, statement.range[0]) - ) { - sideEffectsStatement = statement; - } - break; - case "IfStatement": - case "WhileStatement": - case "DoWhileStatement": - if (!parser.isPure(statement.test, statement.range[0])) { - sideEffectsStatement = statement; - } - // statement hook will be called for child statements too - break; - case "ForStatement": - if ( - !parser.isPure(statement.init, statement.range[0]) || - !parser.isPure( - statement.test, - statement.init - ? statement.init.range[1] - : statement.range[0] - ) || - !parser.isPure( - statement.update, - statement.test - ? statement.test.range[1] - : statement.init - ? statement.init.range[1] - : statement.range[0] - ) - ) { - sideEffectsStatement = statement; - } - // statement hook will be called for child statements too - break; - case "SwitchStatement": - if ( - !parser.isPure(statement.discriminant, statement.range[0]) - ) { - sideEffectsStatement = statement; - } - // statement hook will be called for child statements too - break; - case "VariableDeclaration": - case "ClassDeclaration": - case "FunctionDeclaration": - if (!parser.isPure(statement, statement.range[0])) { - sideEffectsStatement = statement; - } - break; - case "ExportNamedDeclaration": - case "ExportDefaultDeclaration": - if ( - !parser.isPure(statement.declaration, statement.range[0]) - ) { - sideEffectsStatement = statement; - } - break; - case "LabeledStatement": - case "BlockStatement": - // statement hook will be called for child statements too - break; - case "EmptyStatement": - break; - case "ExportAllDeclaration": - case "ImportDeclaration": - // imports will be handled by the dependencies - break; - default: - sideEffectsStatement = statement; - break; - } - } - ); - parser.hooks.finish.tap("SideEffectsFlagPlugin", () => { - if (sideEffectsStatement === undefined) { - parser.state.module.buildMeta.sideEffectFree = true; - } else { - const { loc, type } = sideEffectsStatement; - moduleGraph - .getOptimizationBailout(parser.state.module) - .push( - () => - `Statement (${type}) with side effects in source code at ${formatLocation( - loc - )}` - ); - } + } else if (file.endsWith(".br")) { + decompression = createBrotliDecompress({ + chunkSize: DECOMPRESSION_CHUNK_SIZE }); - }; - for (const key of [ - "javascript/auto", - "javascript/esm", - "javascript/dynamic" - ]) { - normalModuleFactory.hooks.parser - .for(key) - .tap("SideEffectsFlagPlugin", parserHandler); } - } - compilation.hooks.optimizeDependencies.tap( - { - name: "SideEffectsFlagPlugin", - stage: STAGE_DEFAULT - }, - modules => { - const logger = compilation.getLogger( - "webpack.SideEffectsFlagPlugin" + if (decompression) { + let newResolve, newReject; + resolve( + Promise.all([ + new Promise((rs, rj) => { + newResolve = rs; + newReject = rj; + }), + new Promise((resolve, reject) => { + decompression.on("data", chunk => buf.push(chunk)); + decompression.on("end", () => resolve()); + decompression.on("error", err => reject(err)); + }) + ]).then(() => buf) ); - - logger.time("update dependencies"); - for (const module of modules) { - if (module.getSideEffectsConnectionState(moduleGraph) === false) { - const exportsInfo = moduleGraph.getExportsInfo(module); - for (const connection of moduleGraph.getIncomingConnections( - module - )) { - const dep = connection.dependency; - let isReexport; - if ( - (isReexport = - dep instanceof - HarmonyExportImportedSpecifierDependency) || - (dep instanceof HarmonyImportSpecifierDependency && - !dep.namespaceObjectAsContext) - ) { - // TODO improve for export * - if (isReexport && dep.name) { - const exportInfo = moduleGraph.getExportInfo( - connection.originModule, - dep.name - ); - exportInfo.moveTarget( - moduleGraph, - ({ module }) => - module.getSideEffectsConnectionState(moduleGraph) === - false, - ({ module: newModule, export: exportName }) => { - moduleGraph.updateModule(dep, newModule); - moduleGraph.addExplanation( - dep, - "(skipped side-effect-free modules)" - ); - const ids = dep.getIds(moduleGraph); - dep.setIds( - moduleGraph, - exportName - ? [...exportName, ...ids.slice(1)] - : ids.slice(1) - ); - return moduleGraph.getConnection(dep); - } - ); - continue; + resolve = newResolve; + reject = newReject; + } + this.fs.open(file, "r", (err, fd) => { + if (err) { + reject(err); + return; + } + const read = () => { + if (currentBuffer === undefined) { + currentBuffer = Buffer.allocUnsafeSlow( + Math.min( + constants.MAX_LENGTH, + remaining, + decompression ? DECOMPRESSION_CHUNK_SIZE : Infinity + ) + ); + currentBufferUsed = 0; + } + let readBuffer = currentBuffer; + let readOffset = currentBufferUsed; + let readLength = currentBuffer.length - currentBufferUsed; + // values passed to fs.read must be valid int32 values + if (readOffset > 0x7fffffff) { + readBuffer = currentBuffer.slice(readOffset); + readOffset = 0; + } + if (readLength > 0x7fffffff) { + readLength = 0x7fffffff; + } + this.fs.read( + fd, + readBuffer, + readOffset, + readLength, + null, + (err, bytesRead) => { + if (err) { + this.fs.close(fd, () => { + reject(err); + }); + return; + } + currentBufferUsed += bytesRead; + remaining -= bytesRead; + if (currentBufferUsed === currentBuffer.length) { + if (decompression) { + decompression.write(currentBuffer); + } else { + buf.push(currentBuffer); } - // TODO improve for nested imports - const ids = dep.getIds(moduleGraph); - if (ids.length > 0) { - const exportInfo = exportsInfo.getExportInfo(ids[0]); - const target = exportInfo.getTarget( - moduleGraph, - ({ module }) => - module.getSideEffectsConnectionState(moduleGraph) === - false - ); - if (!target) continue; - - moduleGraph.updateModule(dep, target.module); - moduleGraph.addExplanation( - dep, - "(skipped side-effect-free modules)" - ); - dep.setIds( - moduleGraph, - target.export - ? [...target.export, ...ids.slice(1)] - : ids.slice(1) - ); + currentBuffer = undefined; + if (remaining === 0) { + if (decompression) { + decompression.end(); + } + this.fs.close(fd, err => { + if (err) { + reject(err); + return; + } + resolve(buf); + }); + return; } } + read(); } - } - } - logger.timeEnd("update dependencies"); - } - ); - } - ); + ); + }; + read(); + }); + }); + }); + return deserialize(this, false, readFile); } +} - static moduleHasSideEffects(moduleName, flagValue, cache) { - switch (typeof flagValue) { - case "undefined": - return true; - case "boolean": - return flagValue; - case "string": - return globToRegexp(flagValue, cache).test(moduleName); - case "object": - return flagValue.some(glob => - SideEffectsFlagPlugin.moduleHasSideEffects(moduleName, glob, cache) - ); +module.exports = FileMiddleware; + + +/***/ }), + +/***/ 86791: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +class MapObjectSerializer { + serialize(obj, { write }) { + write(obj.size); + for (const key of obj.keys()) { + write(key); + } + for (const value of obj.values()) { + write(value); + } + } + deserialize({ read }) { + let size = read(); + const map = new Map(); + const keys = []; + for (let i = 0; i < size; i++) { + keys.push(read()); } + for (let i = 0; i < size; i++) { + map.set(keys[i], read()); + } + return map; } } -module.exports = SideEffectsFlagPlugin; + +module.exports = MapObjectSerializer; /***/ }), -/***/ 21478: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 21048: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const Chunk = __webpack_require__(39385); -const { STAGE_ADVANCED } = __webpack_require__(80057); -const WebpackError = __webpack_require__(53799); -const { requestToId } = __webpack_require__(63290); -const { isSubset } = __webpack_require__(93347); -const SortableSet = __webpack_require__(13098); -const { - compareModulesByIdentifier, - compareIterables -} = __webpack_require__(29579); -const createHash = __webpack_require__(49835); -const deterministicGrouping = __webpack_require__(59836); -const { makePathsRelative } = __webpack_require__(82186); -const memoize = __webpack_require__(78676); -const MinMaxSizeWarning = __webpack_require__(85305); +class NullPrototypeObjectSerializer { + serialize(obj, { write }) { + const keys = Object.keys(obj); + for (const key of keys) { + write(key); + } + write(null); + for (const key of keys) { + write(obj[key]); + } + } + deserialize({ read }) { + const obj = Object.create(null); + const keys = []; + let key = read(); + while (key !== null) { + keys.push(key); + key = read(); + } + for (const key of keys) { + obj[key] = read(); + } + return obj; + } +} -/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksCacheGroup} OptimizationSplitChunksCacheGroup */ -/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksGetCacheGroups} OptimizationSplitChunksGetCacheGroups */ -/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksOptions} OptimizationSplitChunksOptions */ -/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksSizes} OptimizationSplitChunksSizes */ -/** @typedef {import("../../declarations/WebpackOptions").Output} OutputOptions */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("../Compilation").PathData} PathData */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../util/deterministicGrouping").GroupedItems} DeterministicGroupingGroupedItemsForModule */ -/** @typedef {import("../util/deterministicGrouping").Options} DeterministicGroupingOptionsForModule */ +module.exports = NullPrototypeObjectSerializer; -/** @typedef {Record} SplitChunksSizes */ -/** - * @callback ChunkFilterFunction - * @param {Chunk} chunk - * @returns {boolean} - */ +/***/ }), -/** - * @callback CombineSizeFunction - * @param {number} a - * @param {number} b - * @returns {number} - */ +/***/ 34795: +/***/ (function(module, exports, __webpack_require__) { -/** - * @typedef {Object} CacheGroupSource - * @property {string=} key - * @property {number=} priority - * @property {GetName=} getName - * @property {ChunkFilterFunction=} chunksFilter - * @property {boolean=} enforce - * @property {SplitChunksSizes} minSize - * @property {SplitChunksSizes} minSizeReduction - * @property {SplitChunksSizes} minRemainingSize - * @property {SplitChunksSizes} enforceSizeThreshold - * @property {SplitChunksSizes} maxAsyncSize - * @property {SplitChunksSizes} maxInitialSize - * @property {number=} minChunks - * @property {number=} maxAsyncRequests - * @property {number=} maxInitialRequests - * @property {(string | function(PathData, AssetInfo=): string)=} filename - * @property {string=} idHint - * @property {string} automaticNameDelimiter - * @property {boolean=} reuseExistingChunk - * @property {boolean=} usedExports - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ -/** - * @typedef {Object} CacheGroup - * @property {string} key - * @property {number=} priority - * @property {GetName=} getName - * @property {ChunkFilterFunction=} chunksFilter - * @property {SplitChunksSizes} minSize - * @property {SplitChunksSizes} minSizeReduction - * @property {SplitChunksSizes} minRemainingSize - * @property {SplitChunksSizes} enforceSizeThreshold - * @property {SplitChunksSizes} maxAsyncSize - * @property {SplitChunksSizes} maxInitialSize - * @property {number=} minChunks - * @property {number=} maxAsyncRequests - * @property {number=} maxInitialRequests - * @property {(string | function(PathData, AssetInfo=): string)=} filename - * @property {string=} idHint - * @property {string} automaticNameDelimiter - * @property {boolean} reuseExistingChunk - * @property {boolean} usedExports - * @property {boolean} _validateSize - * @property {boolean} _validateRemainingSize - * @property {SplitChunksSizes} _minSizeForMaxSize - * @property {boolean} _conditionalEnforce - */ -/** - * @typedef {Object} FallbackCacheGroup - * @property {ChunkFilterFunction} chunksFilter - * @property {SplitChunksSizes} minSize - * @property {SplitChunksSizes} maxAsyncSize - * @property {SplitChunksSizes} maxInitialSize - * @property {string} automaticNameDelimiter - */ -/** - * @typedef {Object} CacheGroupsContext - * @property {ModuleGraph} moduleGraph - * @property {ChunkGraph} chunkGraph - */ +const createHash = __webpack_require__(49835); +const ArraySerializer = __webpack_require__(41721); +const DateObjectSerializer = __webpack_require__(93475); +const ErrorObjectSerializer = __webpack_require__(79479); +const MapObjectSerializer = __webpack_require__(86791); +const NullPrototypeObjectSerializer = __webpack_require__(21048); +const PlainObjectSerializer = __webpack_require__(33040); +const RegExpObjectSerializer = __webpack_require__(57328); +const SerializerMiddleware = __webpack_require__(83137); +const SetObjectSerializer = __webpack_require__(79240); -/** - * @callback GetCacheGroups - * @param {Module} module - * @param {CacheGroupsContext} context - * @returns {CacheGroupSource[]} - */ +/** @typedef {typeof import("../util/Hash")} Hash */ +/** @typedef {import("./types").ComplexSerializableType} ComplexSerializableType */ +/** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */ -/** - * @callback GetName - * @param {Module=} module - * @param {Chunk[]=} chunks - * @param {string=} key - * @returns {string=} - */ +/** @typedef {new (...params: any[]) => any} Constructor */ -/** - * @typedef {Object} SplitChunksOptions - * @property {ChunkFilterFunction} chunksFilter - * @property {string[]} defaultSizeTypes - * @property {SplitChunksSizes} minSize - * @property {SplitChunksSizes} minSizeReduction - * @property {SplitChunksSizes} minRemainingSize - * @property {SplitChunksSizes} enforceSizeThreshold - * @property {SplitChunksSizes} maxInitialSize - * @property {SplitChunksSizes} maxAsyncSize - * @property {number} minChunks - * @property {number} maxAsyncRequests - * @property {number} maxInitialRequests - * @property {boolean} hidePathInfo - * @property {string | function(PathData, AssetInfo=): string} filename - * @property {string} automaticNameDelimiter - * @property {GetCacheGroups} getCacheGroups - * @property {GetName} getName - * @property {boolean} usedExports - * @property {FallbackCacheGroup} fallbackCacheGroup - */ +/* -/** - * @typedef {Object} ChunksInfoItem - * @property {SortableSet} modules - * @property {CacheGroup} cacheGroup - * @property {number} cacheGroupIndex - * @property {string} name - * @property {Record} sizes - * @property {Set} chunks - * @property {Set} reuseableChunks - * @property {Set} chunksKeys - */ +Format: -const defaultGetName = /** @type {GetName} */ (() => {}); +File -> Section* +Section -> ObjectSection | ReferenceSection | EscapeSection | OtherSection -const deterministicGroupingForModules = - /** @type {function(DeterministicGroupingOptionsForModule): DeterministicGroupingGroupedItemsForModule[]} */ ( - deterministicGrouping - ); +ObjectSection -> ESCAPE ( + number:relativeOffset (number > 0) | + string:request (string|null):export +) Section:value* ESCAPE ESCAPE_END_OBJECT +ReferenceSection -> ESCAPE number:relativeOffset (number < 0) +EscapeSection -> ESCAPE ESCAPE_ESCAPE_VALUE (escaped value ESCAPE) +EscapeSection -> ESCAPE ESCAPE_UNDEFINED (escaped value ESCAPE) +OtherSection -> any (except ESCAPE) -/** @type {WeakMap} */ -const getKeyCache = new WeakMap(); +Why using null as escape value? +Multiple null values can merged by the BinaryMiddleware, which makes it very efficient +Technically any value can be used. + +*/ /** - * @param {string} name a filename to hash - * @param {OutputOptions} outputOptions hash function used - * @returns {string} hashed filename + * @typedef {Object} ObjectSerializerContext + * @property {function(any): void} write */ -const hashFilename = (name, outputOptions) => { - const digest = /** @type {string} */ ( - createHash(outputOptions.hashFunction) - .update(name) - .digest(outputOptions.hashDigest) - ); - return digest.slice(0, 8); -}; /** - * @param {Chunk} chunk the chunk - * @returns {number} the number of requests + * @typedef {Object} ObjectDeserializerContext + * @property {function(): any} read */ -const getRequests = chunk => { - let requests = 0; - for (const chunkGroup of chunk.groupsIterable) { - requests = Math.max(requests, chunkGroup.chunks.length); + +/** + * @typedef {Object} ObjectSerializer + * @property {function(any, ObjectSerializerContext): void} serialize + * @property {function(ObjectDeserializerContext): any} deserialize + */ + +const setSetSize = (set, size) => { + let i = 0; + for (const item of set) { + if (i++ >= size) { + set.delete(item); + } } - return requests; }; -const mapObject = (obj, fn) => { - const newObj = Object.create(null); - for (const key of Object.keys(obj)) { - newObj[key] = fn(obj[key], key); +const setMapSize = (map, size) => { + let i = 0; + for (const item of map.keys()) { + if (i++ >= size) { + map.delete(item); + } } - return newObj; }; /** - * @template T - * @param {Set} a set - * @param {Set} b other set - * @returns {boolean} true if at least one item of a is in b + * @param {Buffer} buffer buffer + * @param {string | Hash} hashFunction hash function to use + * @returns {string} hash */ -const isOverlap = (a, b) => { - for (const item of a) { - if (b.has(item)) return true; - } - return false; +const toHash = (buffer, hashFunction) => { + const hash = createHash(hashFunction); + hash.update(buffer); + return /** @type {string} */ (hash.digest("latin1")); }; -const compareModuleIterables = compareIterables(compareModulesByIdentifier); +const ESCAPE = null; +const ESCAPE_ESCAPE_VALUE = null; +const ESCAPE_END_OBJECT = true; +const ESCAPE_UNDEFINED = false; -/** - * @param {ChunksInfoItem} a item - * @param {ChunksInfoItem} b item - * @returns {number} compare result - */ -const compareEntries = (a, b) => { - // 1. by priority - const diffPriority = a.cacheGroup.priority - b.cacheGroup.priority; - if (diffPriority) return diffPriority; - // 2. by number of chunks - const diffCount = a.chunks.size - b.chunks.size; - if (diffCount) return diffCount; - // 3. by size reduction - const aSizeReduce = totalSize(a.sizes) * (a.chunks.size - 1); - const bSizeReduce = totalSize(b.sizes) * (b.chunks.size - 1); - const diffSizeReduce = aSizeReduce - bSizeReduce; - if (diffSizeReduce) return diffSizeReduce; - // 4. by cache group index - const indexDiff = b.cacheGroupIndex - a.cacheGroupIndex; - if (indexDiff) return indexDiff; - // 5. by number of modules (to be able to compare by identifier) - const modulesA = a.modules; - const modulesB = b.modules; - const diff = modulesA.size - modulesB.size; - if (diff) return diff; - // 6. by module identifiers - modulesA.sort(); - modulesB.sort(); - return compareModuleIterables(modulesA, modulesB); -}; +const CURRENT_VERSION = 2; -const INITIAL_CHUNK_FILTER = chunk => chunk.canBeInitial(); -const ASYNC_CHUNK_FILTER = chunk => !chunk.canBeInitial(); -const ALL_CHUNK_FILTER = chunk => true; +const serializers = new Map(); +const serializerInversed = new Map(); -/** - * @param {OptimizationSplitChunksSizes} value the sizes - * @param {string[]} defaultSizeTypes the default size types - * @returns {SplitChunksSizes} normalized representation - */ -const normalizeSizes = (value, defaultSizeTypes) => { - if (typeof value === "number") { - /** @type {Record} */ - const o = {}; - for (const sizeType of defaultSizeTypes) o[sizeType] = value; - return o; - } else if (typeof value === "object" && value !== null) { - return { ...value }; - } else { - return {}; +const loadedRequests = new Set(); + +const NOT_SERIALIZABLE = {}; + +const jsTypes = new Map(); +jsTypes.set(Object, new PlainObjectSerializer()); +jsTypes.set(Array, new ArraySerializer()); +jsTypes.set(null, new NullPrototypeObjectSerializer()); +jsTypes.set(Map, new MapObjectSerializer()); +jsTypes.set(Set, new SetObjectSerializer()); +jsTypes.set(Date, new DateObjectSerializer()); +jsTypes.set(RegExp, new RegExpObjectSerializer()); +jsTypes.set(Error, new ErrorObjectSerializer(Error)); +jsTypes.set(EvalError, new ErrorObjectSerializer(EvalError)); +jsTypes.set(RangeError, new ErrorObjectSerializer(RangeError)); +jsTypes.set(ReferenceError, new ErrorObjectSerializer(ReferenceError)); +jsTypes.set(SyntaxError, new ErrorObjectSerializer(SyntaxError)); +jsTypes.set(TypeError, new ErrorObjectSerializer(TypeError)); + +// If in a sandboxed environment (e. g. jest), this escapes the sandbox and registers +// real Object and Array types to. These types may occur in the wild too, e. g. when +// using Structured Clone in postMessage. +if (exports.constructor !== Object) { + const Obj = /** @type {typeof Object} */ (exports.constructor); + const Fn = /** @type {typeof Function} */ (Obj.constructor); + for (const [type, config] of Array.from(jsTypes)) { + if (type) { + const Type = new Fn(`return ${type.name};`)(); + jsTypes.set(Type, config); + } } -}; +} -/** - * @param {...SplitChunksSizes} sizes the sizes - * @returns {SplitChunksSizes} the merged sizes - */ -const mergeSizes = (...sizes) => { - /** @type {SplitChunksSizes} */ - let merged = {}; - for (let i = sizes.length - 1; i >= 0; i--) { - merged = Object.assign(merged, sizes[i]); +{ + let i = 1; + for (const [type, serializer] of jsTypes) { + serializers.set(type, { + request: "", + name: i++, + serializer + }); } - return merged; -}; +} + +for (const { request, name, serializer } of serializers.values()) { + serializerInversed.set(`${request}/${name}`, serializer); +} + +/** @type {Map boolean>} */ +const loaders = new Map(); /** - * @param {SplitChunksSizes} sizes the sizes - * @returns {boolean} true, if there are sizes > 0 + * @typedef {ComplexSerializableType[]} DeserializedType + * @typedef {PrimitiveSerializableType[]} SerializedType + * @extends {SerializerMiddleware} */ -const hasNonZeroSizes = sizes => { - for (const key of Object.keys(sizes)) { - if (sizes[key] > 0) return true; +class ObjectMiddleware extends SerializerMiddleware { + /** + * @param {function(any): void} extendContext context extensions + * @param {string | Hash} hashFunction hash function to use + */ + constructor(extendContext, hashFunction = "md4") { + super(); + this.extendContext = extendContext; + this._hashFunction = hashFunction; + } + /** + * @param {RegExp} regExp RegExp for which the request is tested + * @param {function(string): boolean} loader loader to load the request, returns true when successful + * @returns {void} + */ + static registerLoader(regExp, loader) { + loaders.set(regExp, loader); } - return false; -}; -/** - * @param {SplitChunksSizes} a first sizes - * @param {SplitChunksSizes} b second sizes - * @param {CombineSizeFunction} combine a function to combine sizes - * @returns {SplitChunksSizes} the combine sizes - */ -const combineSizes = (a, b, combine) => { - const aKeys = new Set(Object.keys(a)); - const bKeys = new Set(Object.keys(b)); - /** @type {SplitChunksSizes} */ - const result = {}; - for (const key of aKeys) { - if (bKeys.has(key)) { - result[key] = combine(a[key], b[key]); - } else { - result[key] = a[key]; + /** + * @param {Constructor} Constructor the constructor + * @param {string} request the request which will be required when deserializing + * @param {string} name the name to make multiple serializer unique when sharing a request + * @param {ObjectSerializer} serializer the serializer + * @returns {void} + */ + static register(Constructor, request, name, serializer) { + const key = request + "/" + name; + + if (serializers.has(Constructor)) { + throw new Error( + `ObjectMiddleware.register: serializer for ${Constructor.name} is already registered` + ); } - } - for (const key of bKeys) { - if (!aKeys.has(key)) { - result[key] = b[key]; + + if (serializerInversed.has(key)) { + throw new Error( + `ObjectMiddleware.register: serializer for ${key} is already registered` + ); } - } - return result; -}; -/** - * @param {SplitChunksSizes} sizes the sizes - * @param {SplitChunksSizes} minSize the min sizes - * @returns {boolean} true if there are sizes and all existing sizes are at least `minSize` - */ -const checkMinSize = (sizes, minSize) => { - for (const key of Object.keys(minSize)) { - const size = sizes[key]; - if (size === undefined || size === 0) continue; - if (size < minSize[key]) return false; - } - return true; -}; + serializers.set(Constructor, { + request, + name, + serializer + }); -/** - * @param {SplitChunksSizes} sizes the sizes - * @param {SplitChunksSizes} minSizeReduction the min sizes - * @param {number} chunkCount number of chunks - * @returns {boolean} true if there are sizes and all existing sizes are at least `minSizeReduction` - */ -const checkMinSizeReduction = (sizes, minSizeReduction, chunkCount) => { - for (const key of Object.keys(minSizeReduction)) { - const size = sizes[key]; - if (size === undefined || size === 0) continue; - if (size * chunkCount < minSizeReduction[key]) return false; + serializerInversed.set(key, serializer); } - return true; -}; -/** - * @param {SplitChunksSizes} sizes the sizes - * @param {SplitChunksSizes} minSize the min sizes - * @returns {undefined | string[]} list of size types that are below min size - */ -const getViolatingMinSizes = (sizes, minSize) => { - let list; - for (const key of Object.keys(minSize)) { - const size = sizes[key]; - if (size === undefined || size === 0) continue; - if (size < minSize[key]) { - if (list === undefined) list = [key]; - else list.push(key); + /** + * @param {Constructor} Constructor the constructor + * @returns {void} + */ + static registerNotSerializable(Constructor) { + if (serializers.has(Constructor)) { + throw new Error( + `ObjectMiddleware.registerNotSerializable: serializer for ${Constructor.name} is already registered` + ); } - } - return list; -}; -/** - * @param {SplitChunksSizes} sizes the sizes - * @returns {number} the total size - */ -const totalSize = sizes => { - let size = 0; - for (const key of Object.keys(sizes)) { - size += sizes[key]; + serializers.set(Constructor, NOT_SERIALIZABLE); } - return size; -}; -/** - * @param {false|string|Function} name the chunk name - * @returns {GetName} a function to get the name of the chunk - */ -const normalizeName = name => { - if (typeof name === "string") { - return () => name; - } - if (typeof name === "function") { - return /** @type {GetName} */ (name); - } -}; + static getSerializerFor(object) { + const proto = Object.getPrototypeOf(object); + let c; + if (proto === null) { + // Object created with Object.create(null) + c = null; + } else { + c = proto.constructor; + if (!c) { + throw new Error( + "Serialization of objects with prototype without valid constructor property not possible" + ); + } + } + const config = serializers.get(c); -/** - * @param {OptimizationSplitChunksCacheGroup["chunks"]} chunks the chunk filter option - * @returns {ChunkFilterFunction} the chunk filter function - */ -const normalizeChunksFilter = chunks => { - if (chunks === "initial") { - return INITIAL_CHUNK_FILTER; - } - if (chunks === "async") { - return ASYNC_CHUNK_FILTER; - } - if (chunks === "all") { - return ALL_CHUNK_FILTER; + if (!config) throw new Error(`No serializer registered for ${c.name}`); + if (config === NOT_SERIALIZABLE) throw NOT_SERIALIZABLE; + + return config; } - if (typeof chunks === "function") { - return chunks; + + static getDeserializerFor(request, name) { + const key = request + "/" + name; + const serializer = serializerInversed.get(key); + + if (serializer === undefined) { + throw new Error(`No deserializer registered for ${key}`); + } + + return serializer; } -}; -/** - * @param {GetCacheGroups | Record} cacheGroups the cache group options - * @param {string[]} defaultSizeTypes the default size types - * @returns {GetCacheGroups} a function to get the cache groups - */ -const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => { - if (typeof cacheGroups === "function") { - return cacheGroups; + static _getDeserializerForWithoutError(request, name) { + const key = request + "/" + name; + const serializer = serializerInversed.get(key); + return serializer; } - if (typeof cacheGroups === "object" && cacheGroups !== null) { - /** @type {(function(Module, CacheGroupsContext, CacheGroupSource[]): void)[]} */ - const handlers = []; - for (const key of Object.keys(cacheGroups)) { - const option = cacheGroups[key]; - if (option === false) { - continue; + + /** + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType|Promise} serialized data + */ + serialize(data, context) { + /** @type {any[]} */ + let result = [CURRENT_VERSION]; + let currentPos = 0; + let referenceable = new Map(); + const addReferenceable = item => { + referenceable.set(item, currentPos++); + }; + let bufferDedupeMap = new Map(); + const dedupeBuffer = buf => { + const len = buf.length; + const entry = bufferDedupeMap.get(len); + if (entry === undefined) { + bufferDedupeMap.set(len, buf); + return buf; } - if (typeof option === "string" || option instanceof RegExp) { - const source = createCacheGroupSource({}, key, defaultSizeTypes); - handlers.push((module, context, results) => { - if (checkTest(option, module, context)) { - results.push(source); + if (Buffer.isBuffer(entry)) { + if (len < 32) { + if (buf.equals(entry)) { + return entry; } - }); - } else if (typeof option === "function") { - const cache = new WeakMap(); - handlers.push((module, context, results) => { - const result = option(module); - if (result) { - const groups = Array.isArray(result) ? result : [result]; - for (const group of groups) { - const cachedSource = cache.get(group); - if (cachedSource !== undefined) { - results.push(cachedSource); - } else { - const source = createCacheGroupSource( - group, - key, - defaultSizeTypes - ); - cache.set(group, source); - results.push(source); - } + bufferDedupeMap.set(len, [entry, buf]); + return buf; + } else { + const hash = toHash(entry, this._hashFunction); + const newMap = new Map(); + newMap.set(hash, entry); + bufferDedupeMap.set(len, newMap); + const hashBuf = toHash(buf, this._hashFunction); + if (hash === hashBuf) { + return entry; + } + return buf; + } + } else if (Array.isArray(entry)) { + if (entry.length < 16) { + for (const item of entry) { + if (buf.equals(item)) { + return item; } } - }); - } else { - const source = createCacheGroupSource(option, key, defaultSizeTypes); - handlers.push((module, context, results) => { - if ( - checkTest(option.test, module, context) && - checkModuleType(option.type, module) && - checkModuleLayer(option.layer, module) - ) { - results.push(source); + entry.push(buf); + return buf; + } else { + const newMap = new Map(); + const hash = toHash(buf, this._hashFunction); + let found; + for (const item of entry) { + const itemHash = toHash(item, this._hashFunction); + newMap.set(itemHash, item); + if (found === undefined && itemHash === hash) found = item; } - }); - } - } - /** - * @param {Module} module the current module - * @param {CacheGroupsContext} context the current context - * @returns {CacheGroupSource[]} the matching cache groups - */ - const fn = (module, context) => { - /** @type {CacheGroupSource[]} */ - let results = []; - for (const fn of handlers) { - fn(module, context, results); + bufferDedupeMap.set(len, newMap); + if (found === undefined) { + newMap.set(hash, buf); + return buf; + } else { + return found; + } + } + } else { + const hash = toHash(buf, this._hashFunction); + const item = entry.get(hash); + if (item !== undefined) { + return item; + } + entry.set(hash, buf); + return buf; } - return results; }; - return fn; - } - return () => null; -}; + let currentPosTypeLookup = 0; + let objectTypeLookup = new Map(); + const cycleStack = new Set(); + const stackToString = item => { + const arr = Array.from(cycleStack); + arr.push(item); + return arr + .map(item => { + if (typeof item === "string") { + if (item.length > 100) { + return `String ${JSON.stringify(item.slice(0, 100)).slice( + 0, + -1 + )}..."`; + } + return `String ${JSON.stringify(item)}`; + } + try { + const { request, name } = ObjectMiddleware.getSerializerFor(item); + if (request) { + return `${request}${name ? `.${name}` : ""}`; + } + } catch (e) { + // ignore -> fallback + } + if (typeof item === "object" && item !== null) { + if (item.constructor) { + if (item.constructor === Object) + return `Object { ${Object.keys(item).join(", ")} }`; + if (item.constructor === Map) return `Map { ${item.size} items }`; + if (item.constructor === Array) + return `Array { ${item.length} items }`; + if (item.constructor === Set) return `Set { ${item.size} items }`; + if (item.constructor === RegExp) return item.toString(); + return `${item.constructor.name}`; + } + return `Object [null prototype] { ${Object.keys(item).join( + ", " + )} }`; + } + try { + return `${item}`; + } catch (e) { + return `(${e.message})`; + } + }) + .join(" -> "); + }; + let hasDebugInfoAttached; + let ctx = { + write(value, key) { + try { + process(value); + } catch (e) { + if (e !== NOT_SERIALIZABLE) { + if (hasDebugInfoAttached === undefined) + hasDebugInfoAttached = new WeakSet(); + if (!hasDebugInfoAttached.has(e)) { + e.message += `\nwhile serializing ${stackToString(value)}`; + hasDebugInfoAttached.add(e); + } + } + throw e; + } + }, + setCircularReference(ref) { + addReferenceable(ref); + }, + snapshot() { + return { + length: result.length, + cycleStackSize: cycleStack.size, + referenceableSize: referenceable.size, + currentPos, + objectTypeLookupSize: objectTypeLookup.size, + currentPosTypeLookup + }; + }, + rollback(snapshot) { + result.length = snapshot.length; + setSetSize(cycleStack, snapshot.cycleStackSize); + setMapSize(referenceable, snapshot.referenceableSize); + currentPos = snapshot.currentPos; + setMapSize(objectTypeLookup, snapshot.objectTypeLookupSize); + currentPosTypeLookup = snapshot.currentPosTypeLookup; + }, + ...context + }; + this.extendContext(ctx); + const process = item => { + if (Buffer.isBuffer(item)) { + // check if we can emit a reference + const ref = referenceable.get(item); + if (ref !== undefined) { + result.push(ESCAPE, ref - currentPos); + return; + } + const alreadyUsedBuffer = dedupeBuffer(item); + if (alreadyUsedBuffer !== item) { + const ref = referenceable.get(alreadyUsedBuffer); + if (ref !== undefined) { + referenceable.set(item, ref); + result.push(ESCAPE, ref - currentPos); + return; + } + item = alreadyUsedBuffer; + } + addReferenceable(item); -/** - * @param {undefined|boolean|string|RegExp|Function} test test option - * @param {Module} module the module - * @param {CacheGroupsContext} context context object - * @returns {boolean} true, if the module should be selected - */ -const checkTest = (test, module, context) => { - if (test === undefined) return true; - if (typeof test === "function") { - return test(module, context); - } - if (typeof test === "boolean") return test; - if (typeof test === "string") { - const name = module.nameForCondition(); - return name && name.startsWith(test); - } - if (test instanceof RegExp) { - const name = module.nameForCondition(); - return name && test.test(name); - } - return false; -}; + result.push(item); + } else if (item === ESCAPE) { + result.push(ESCAPE, ESCAPE_ESCAPE_VALUE); + } else if ( + typeof item === "object" + // We don't have to check for null as ESCAPE is null and this has been checked before + ) { + // check if we can emit a reference + const ref = referenceable.get(item); + if (ref !== undefined) { + result.push(ESCAPE, ref - currentPos); + return; + } -/** - * @param {undefined|string|RegExp|Function} test type option - * @param {Module} module the module - * @returns {boolean} true, if the module should be selected - */ -const checkModuleType = (test, module) => { - if (test === undefined) return true; - if (typeof test === "function") { - return test(module.type); - } - if (typeof test === "string") { - const type = module.type; - return test === type; - } - if (test instanceof RegExp) { - const type = module.type; - return test.test(type); - } - return false; -}; + if (cycleStack.has(item)) { + throw new Error( + `This is a circular references. To serialize circular references use 'setCircularReference' somewhere in the circle during serialize and deserialize.` + ); + } -/** - * @param {undefined|string|RegExp|Function} test type option - * @param {Module} module the module - * @returns {boolean} true, if the module should be selected - */ -const checkModuleLayer = (test, module) => { - if (test === undefined) return true; - if (typeof test === "function") { - return test(module.layer); - } - if (typeof test === "string") { - const layer = module.layer; - return test === "" ? !layer : layer && layer.startsWith(test); - } - if (test instanceof RegExp) { - const layer = module.layer; - return test.test(layer); - } - return false; -}; + const { request, name, serializer } = + ObjectMiddleware.getSerializerFor(item); + const key = `${request}/${name}`; + const lastIndex = objectTypeLookup.get(key); -/** - * @param {OptimizationSplitChunksCacheGroup} options the group options - * @param {string} key key of cache group - * @param {string[]} defaultSizeTypes the default size types - * @returns {CacheGroupSource} the normalized cached group - */ -const createCacheGroupSource = (options, key, defaultSizeTypes) => { - const minSize = normalizeSizes(options.minSize, defaultSizeTypes); - const minSizeReduction = normalizeSizes( - options.minSizeReduction, - defaultSizeTypes - ); - const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes); - return { - key, - priority: options.priority, - getName: normalizeName(options.name), - chunksFilter: normalizeChunksFilter(options.chunks), - enforce: options.enforce, - minSize, - minSizeReduction, - minRemainingSize: mergeSizes( - normalizeSizes(options.minRemainingSize, defaultSizeTypes), - minSize - ), - enforceSizeThreshold: normalizeSizes( - options.enforceSizeThreshold, - defaultSizeTypes - ), - maxAsyncSize: mergeSizes( - normalizeSizes(options.maxAsyncSize, defaultSizeTypes), - maxSize - ), - maxInitialSize: mergeSizes( - normalizeSizes(options.maxInitialSize, defaultSizeTypes), - maxSize - ), - minChunks: options.minChunks, - maxAsyncRequests: options.maxAsyncRequests, - maxInitialRequests: options.maxInitialRequests, - filename: options.filename, - idHint: options.idHint, - automaticNameDelimiter: options.automaticNameDelimiter, - reuseExistingChunk: options.reuseExistingChunk, - usedExports: options.usedExports - }; -}; + if (lastIndex === undefined) { + objectTypeLookup.set(key, currentPosTypeLookup++); -module.exports = class SplitChunksPlugin { - /** - * @param {OptimizationSplitChunksOptions=} options plugin options - */ - constructor(options = {}) { - const defaultSizeTypes = options.defaultSizeTypes || [ - "javascript", - "unknown" - ]; - const fallbackCacheGroup = options.fallbackCacheGroup || {}; - const minSize = normalizeSizes(options.minSize, defaultSizeTypes); - const minSizeReduction = normalizeSizes( - options.minSizeReduction, - defaultSizeTypes - ); - const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes); + result.push(ESCAPE, request, name); + } else { + result.push(ESCAPE, currentPosTypeLookup - lastIndex); + } - /** @type {SplitChunksOptions} */ - this.options = { - chunksFilter: normalizeChunksFilter(options.chunks || "all"), - defaultSizeTypes, - minSize, - minSizeReduction, - minRemainingSize: mergeSizes( - normalizeSizes(options.minRemainingSize, defaultSizeTypes), - minSize - ), - enforceSizeThreshold: normalizeSizes( - options.enforceSizeThreshold, - defaultSizeTypes - ), - maxAsyncSize: mergeSizes( - normalizeSizes(options.maxAsyncSize, defaultSizeTypes), - maxSize - ), - maxInitialSize: mergeSizes( - normalizeSizes(options.maxInitialSize, defaultSizeTypes), - maxSize - ), - minChunks: options.minChunks || 1, - maxAsyncRequests: options.maxAsyncRequests || 1, - maxInitialRequests: options.maxInitialRequests || 1, - hidePathInfo: options.hidePathInfo || false, - filename: options.filename || undefined, - getCacheGroups: normalizeCacheGroups( - options.cacheGroups, - defaultSizeTypes - ), - getName: options.name ? normalizeName(options.name) : defaultGetName, - automaticNameDelimiter: options.automaticNameDelimiter, - usedExports: options.usedExports, - fallbackCacheGroup: { - chunksFilter: normalizeChunksFilter( - fallbackCacheGroup.chunks || options.chunks || "all" - ), - minSize: mergeSizes( - normalizeSizes(fallbackCacheGroup.minSize, defaultSizeTypes), - minSize - ), - maxAsyncSize: mergeSizes( - normalizeSizes(fallbackCacheGroup.maxAsyncSize, defaultSizeTypes), - normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes), - normalizeSizes(options.maxAsyncSize, defaultSizeTypes), - normalizeSizes(options.maxSize, defaultSizeTypes) - ), - maxInitialSize: mergeSizes( - normalizeSizes(fallbackCacheGroup.maxInitialSize, defaultSizeTypes), - normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes), - normalizeSizes(options.maxInitialSize, defaultSizeTypes), - normalizeSizes(options.maxSize, defaultSizeTypes) - ), - automaticNameDelimiter: - fallbackCacheGroup.automaticNameDelimiter || - options.automaticNameDelimiter || - "~" + cycleStack.add(item); + + try { + serializer.serialize(item, ctx); + } finally { + cycleStack.delete(item); + } + + result.push(ESCAPE, ESCAPE_END_OBJECT); + + addReferenceable(item); + } else if (typeof item === "string") { + if (item.length > 1) { + // short strings are shorter when not emitting a reference (this saves 1 byte per empty string) + // check if we can emit a reference + const ref = referenceable.get(item); + if (ref !== undefined) { + result.push(ESCAPE, ref - currentPos); + return; + } + addReferenceable(item); + } + + if (item.length > 102400 && context.logger) { + context.logger.warn( + `Serializing big strings (${Math.round( + item.length / 1024 + )}kiB) impacts deserialization performance (consider using Buffer instead and decode when needed)` + ); + } + + result.push(item); + } else if (typeof item === "function") { + if (!SerializerMiddleware.isLazy(item)) + throw new Error("Unexpected function " + item); + /** @type {SerializedType} */ + const serializedData = + SerializerMiddleware.getLazySerializedValue(item); + if (serializedData !== undefined) { + if (typeof serializedData === "function") { + result.push(serializedData); + } else { + throw new Error("Not implemented"); + } + } else if (SerializerMiddleware.isLazy(item, this)) { + throw new Error("Not implemented"); + } else { + const data = SerializerMiddleware.serializeLazy(item, data => + this.serialize([data], context) + ); + SerializerMiddleware.setLazySerializedValue(item, data); + result.push(data); + } + } else if (item === undefined) { + result.push(ESCAPE, ESCAPE_UNDEFINED); + } else { + result.push(item); } }; - /** @type {WeakMap} */ - this._cacheGroupCache = new WeakMap(); - } - - /** - * @param {CacheGroupSource} cacheGroupSource source - * @returns {CacheGroup} the cache group (cached) - */ - _getCacheGroup(cacheGroupSource) { - const cacheEntry = this._cacheGroupCache.get(cacheGroupSource); - if (cacheEntry !== undefined) return cacheEntry; - const minSize = mergeSizes( - cacheGroupSource.minSize, - cacheGroupSource.enforce ? undefined : this.options.minSize - ); - const minSizeReduction = mergeSizes( - cacheGroupSource.minSizeReduction, - cacheGroupSource.enforce ? undefined : this.options.minSizeReduction - ); - const minRemainingSize = mergeSizes( - cacheGroupSource.minRemainingSize, - cacheGroupSource.enforce ? undefined : this.options.minRemainingSize - ); - const enforceSizeThreshold = mergeSizes( - cacheGroupSource.enforceSizeThreshold, - cacheGroupSource.enforce ? undefined : this.options.enforceSizeThreshold - ); - const cacheGroup = { - key: cacheGroupSource.key, - priority: cacheGroupSource.priority || 0, - chunksFilter: cacheGroupSource.chunksFilter || this.options.chunksFilter, - minSize, - minSizeReduction, - minRemainingSize, - enforceSizeThreshold, - maxAsyncSize: mergeSizes( - cacheGroupSource.maxAsyncSize, - cacheGroupSource.enforce ? undefined : this.options.maxAsyncSize - ), - maxInitialSize: mergeSizes( - cacheGroupSource.maxInitialSize, - cacheGroupSource.enforce ? undefined : this.options.maxInitialSize - ), - minChunks: - cacheGroupSource.minChunks !== undefined - ? cacheGroupSource.minChunks - : cacheGroupSource.enforce - ? 1 - : this.options.minChunks, - maxAsyncRequests: - cacheGroupSource.maxAsyncRequests !== undefined - ? cacheGroupSource.maxAsyncRequests - : cacheGroupSource.enforce - ? Infinity - : this.options.maxAsyncRequests, - maxInitialRequests: - cacheGroupSource.maxInitialRequests !== undefined - ? cacheGroupSource.maxInitialRequests - : cacheGroupSource.enforce - ? Infinity - : this.options.maxInitialRequests, - getName: - cacheGroupSource.getName !== undefined - ? cacheGroupSource.getName - : this.options.getName, - usedExports: - cacheGroupSource.usedExports !== undefined - ? cacheGroupSource.usedExports - : this.options.usedExports, - filename: - cacheGroupSource.filename !== undefined - ? cacheGroupSource.filename - : this.options.filename, - automaticNameDelimiter: - cacheGroupSource.automaticNameDelimiter !== undefined - ? cacheGroupSource.automaticNameDelimiter - : this.options.automaticNameDelimiter, - idHint: - cacheGroupSource.idHint !== undefined - ? cacheGroupSource.idHint - : cacheGroupSource.key, - reuseExistingChunk: cacheGroupSource.reuseExistingChunk || false, - _validateSize: hasNonZeroSizes(minSize), - _validateRemainingSize: hasNonZeroSizes(minRemainingSize), - _minSizeForMaxSize: mergeSizes( - cacheGroupSource.minSize, - this.options.minSize - ), - _conditionalEnforce: hasNonZeroSizes(enforceSizeThreshold) - }; - this._cacheGroupCache.set(cacheGroupSource, cacheGroup); - return cacheGroup; + try { + for (const item of data) { + process(item); + } + return result; + } catch (e) { + if (e === NOT_SERIALIZABLE) return null; + + throw e; + } finally { + // Get rid of these references to avoid leaking memory + // This happens because the optimized code v8 generates + // is optimized for our "ctx.write" method so it will reference + // it from e. g. Dependency.prototype.serialize -(IC)-> ctx.write + data = + result = + referenceable = + bufferDedupeMap = + objectTypeLookup = + ctx = + undefined; + } } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data */ - apply(compiler) { - const cachedMakePathsRelative = makePathsRelative.bindContextCache( - compiler.context, - compiler.root - ); - compiler.hooks.thisCompilation.tap("SplitChunksPlugin", compilation => { - const logger = compilation.getLogger("webpack.SplitChunksPlugin"); - let alreadyOptimized = false; - compilation.hooks.unseal.tap("SplitChunksPlugin", () => { - alreadyOptimized = false; - }); - compilation.hooks.optimizeChunks.tap( - { - name: "SplitChunksPlugin", - stage: STAGE_ADVANCED - }, - chunks => { - if (alreadyOptimized) return; - alreadyOptimized = true; - logger.time("prepare"); - const chunkGraph = compilation.chunkGraph; - const moduleGraph = compilation.moduleGraph; - // Give each selected chunk an index (to create strings from chunks) - /** @type {Map} */ - const chunkIndexMap = new Map(); - const ZERO = BigInt("0"); - const ONE = BigInt("1"); - const START = ONE << BigInt("31"); - let index = START; - for (const chunk of chunks) { - chunkIndexMap.set( - chunk, - index | BigInt((Math.random() * 0x7fffffff) | 0) - ); - index = index << ONE; - } - /** - * @param {Iterable} chunks list of chunks - * @returns {bigint | Chunk} key of the chunks - */ - const getKey = chunks => { - const iterator = chunks[Symbol.iterator](); - let result = iterator.next(); - if (result.done) return ZERO; - const first = result.value; - result = iterator.next(); - if (result.done) return first; - let key = - chunkIndexMap.get(first) | chunkIndexMap.get(result.value); - while (!(result = iterator.next()).done) { - const raw = chunkIndexMap.get(result.value); - key = key ^ raw; - } - return key; - }; - const keyToString = key => { - if (typeof key === "bigint") return key.toString(16); - return chunkIndexMap.get(key).toString(16); - }; + deserialize(data, context) { + let currentDataPos = 0; + const read = () => { + if (currentDataPos >= data.length) + throw new Error("Unexpected end of stream"); - const getChunkSetsInGraph = memoize(() => { - /** @type {Map>} */ - const chunkSetsInGraph = new Map(); - /** @type {Set} */ - const singleChunkSets = new Set(); - for (const module of compilation.modules) { - const chunks = chunkGraph.getModuleChunksIterable(module); - const chunksKey = getKey(chunks); - if (typeof chunksKey === "bigint") { - if (!chunkSetsInGraph.has(chunksKey)) { - chunkSetsInGraph.set(chunksKey, new Set(chunks)); - } - } else { - singleChunkSets.add(chunksKey); - } - } - return { chunkSetsInGraph, singleChunkSets }; - }); + return data[currentDataPos++]; + }; - /** - * @param {Module} module the module - * @returns {Iterable} groups of chunks with equal exports - */ - const groupChunksByExports = module => { - const exportsInfo = moduleGraph.getExportsInfo(module); - const groupedByUsedExports = new Map(); - for (const chunk of chunkGraph.getModuleChunksIterable(module)) { - const key = exportsInfo.getUsageKey(chunk.runtime); - const list = groupedByUsedExports.get(key); - if (list !== undefined) { - list.push(chunk); - } else { - groupedByUsedExports.set(key, [chunk]); - } - } - return groupedByUsedExports.values(); - }; + if (read() !== CURRENT_VERSION) + throw new Error("Version mismatch, serializer changed"); - /** @type {Map>} */ - const groupedByExportsMap = new Map(); + let currentPos = 0; + let referenceable = []; + const addReferenceable = item => { + referenceable.push(item); + currentPos++; + }; + let currentPosTypeLookup = 0; + let objectTypeLookup = []; + let result = []; + let ctx = { + read() { + return decodeValue(); + }, + setCircularReference(ref) { + addReferenceable(ref); + }, + ...context + }; + this.extendContext(ctx); + const decodeValue = () => { + const item = read(); - const getExportsChunkSetsInGraph = memoize(() => { - /** @type {Map>} */ - const chunkSetsInGraph = new Map(); - /** @type {Set} */ - const singleChunkSets = new Set(); - for (const module of compilation.modules) { - const groupedChunks = Array.from(groupChunksByExports(module)); - groupedByExportsMap.set(module, groupedChunks); - for (const chunks of groupedChunks) { - if (chunks.length === 1) { - singleChunkSets.add(chunks[0]); - } else { - const chunksKey = /** @type {bigint} */ (getKey(chunks)); - if (!chunkSetsInGraph.has(chunksKey)) { - chunkSetsInGraph.set(chunksKey, new Set(chunks)); - } - } - } - } - return { chunkSetsInGraph, singleChunkSets }; - }); + if (item === ESCAPE) { + const nextItem = read(); - // group these set of chunks by count - // to allow to check less sets via isSubset - // (only smaller sets can be subset) - const groupChunkSetsByCount = chunkSets => { - /** @type {Map>>} */ - const chunkSetsByCount = new Map(); - for (const chunksSet of chunkSets) { - const count = chunksSet.size; - let array = chunkSetsByCount.get(count); - if (array === undefined) { - array = []; - chunkSetsByCount.set(count, array); - } - array.push(chunksSet); - } - return chunkSetsByCount; - }; - const getChunkSetsByCount = memoize(() => - groupChunkSetsByCount( - getChunkSetsInGraph().chunkSetsInGraph.values() - ) - ); - const getExportsChunkSetsByCount = memoize(() => - groupChunkSetsByCount( - getExportsChunkSetsInGraph().chunkSetsInGraph.values() - ) + if (nextItem === ESCAPE_ESCAPE_VALUE) { + return ESCAPE; + } else if (nextItem === ESCAPE_UNDEFINED) { + return undefined; + } else if (nextItem === ESCAPE_END_OBJECT) { + throw new Error( + `Unexpected end of object at position ${currentDataPos - 1}` ); + } else { + const request = nextItem; + let serializer; - // Create a list of possible combinations - const createGetCombinations = ( - chunkSets, - singleChunkSets, - chunkSetsByCount - ) => { - /** @type {Map | Chunk)[]>} */ - const combinationsCache = new Map(); + if (typeof request === "number") { + if (request < 0) { + // relative reference + return referenceable[currentPos + request]; + } + serializer = objectTypeLookup[currentPosTypeLookup - request]; + } else { + if (typeof request !== "string") { + throw new Error( + `Unexpected type (${typeof request}) of request ` + + `at position ${currentDataPos - 1}` + ); + } + const name = read(); - return key => { - const cacheEntry = combinationsCache.get(key); - if (cacheEntry !== undefined) return cacheEntry; - if (key instanceof Chunk) { - const result = [key]; - combinationsCache.set(key, result); - return result; - } - const chunksSet = chunkSets.get(key); - /** @type {(Set | Chunk)[]} */ - const array = [chunksSet]; - for (const [count, setArray] of chunkSetsByCount) { - // "equal" is not needed because they would have been merge in the first step - if (count < chunksSet.size) { - for (const set of setArray) { - if (isSubset(chunksSet, set)) { - array.push(set); + serializer = ObjectMiddleware._getDeserializerForWithoutError( + request, + name + ); + + if (serializer === undefined) { + if (request && !loadedRequests.has(request)) { + let loaded = false; + for (const [regExp, loader] of loaders) { + if (regExp.test(request)) { + if (loader(request)) { + loaded = true; + break; } } } - } - for (const chunk of singleChunkSets) { - if (chunksSet.has(chunk)) { - array.push(chunk); + if (!loaded) { + require(request); } + + loadedRequests.add(request); } - combinationsCache.set(key, array); - return array; - }; - }; - const getCombinationsFactory = memoize(() => { - const { chunkSetsInGraph, singleChunkSets } = getChunkSetsInGraph(); - return createGetCombinations( - chunkSetsInGraph, - singleChunkSets, - getChunkSetsByCount() - ); - }); - const getCombinations = key => getCombinationsFactory()(key); + serializer = ObjectMiddleware.getDeserializerFor(request, name); + } - const getExportsCombinationsFactory = memoize(() => { - const { chunkSetsInGraph, singleChunkSets } = - getExportsChunkSetsInGraph(); - return createGetCombinations( - chunkSetsInGraph, - singleChunkSets, - getExportsChunkSetsByCount() - ); - }); - const getExportsCombinations = key => - getExportsCombinationsFactory()(key); + objectTypeLookup.push(serializer); + currentPosTypeLookup++; + } + try { + const item = serializer.deserialize(ctx); + const end1 = read(); - /** - * @typedef {Object} SelectedChunksResult - * @property {Chunk[]} chunks the list of chunks - * @property {bigint | Chunk} key a key of the list - */ + if (end1 !== ESCAPE) { + throw new Error("Expected end of object"); + } - /** @type {WeakMap | Chunk, WeakMap>} */ - const selectedChunksCacheByChunksSet = new WeakMap(); + const end2 = read(); - /** - * get list and key by applying the filter function to the list - * It is cached for performance reasons - * @param {Set | Chunk} chunks list of chunks - * @param {ChunkFilterFunction} chunkFilter filter function for chunks - * @returns {SelectedChunksResult} list and key - */ - const getSelectedChunks = (chunks, chunkFilter) => { - let entry = selectedChunksCacheByChunksSet.get(chunks); - if (entry === undefined) { - entry = new WeakMap(); - selectedChunksCacheByChunksSet.set(chunks, entry); + if (end2 !== ESCAPE_END_OBJECT) { + throw new Error("Expected end of object"); } - /** @type {SelectedChunksResult} */ - let entry2 = entry.get(chunkFilter); - if (entry2 === undefined) { - /** @type {Chunk[]} */ - const selectedChunks = []; - if (chunks instanceof Chunk) { - if (chunkFilter(chunks)) selectedChunks.push(chunks); - } else { - for (const chunk of chunks) { - if (chunkFilter(chunk)) selectedChunks.push(chunk); - } + + addReferenceable(item); + + return item; + } catch (err) { + // As this is only for error handling, we omit creating a Map for + // faster access to this information, as this would affect performance + // in the good case + let serializerEntry; + for (const entry of serializers) { + if (entry[1].serializer === serializer) { + serializerEntry = entry; + break; } - entry2 = { - chunks: selectedChunks, - key: getKey(selectedChunks) - }; - entry.set(chunkFilter, entry2); } - return entry2; - }; + const name = !serializerEntry + ? "unknown" + : !serializerEntry[1].request + ? serializerEntry[0].name + : serializerEntry[1].name + ? `${serializerEntry[1].request} ${serializerEntry[1].name}` + : serializerEntry[1].request; + err.message += `\n(during deserialization of ${name})`; + throw err; + } + } + } else if (typeof item === "string") { + if (item.length > 1) { + addReferenceable(item); + } - /** @type {Map} */ - const alreadyValidatedParents = new Map(); - /** @type {Set} */ - const alreadyReportedErrors = new Set(); + return item; + } else if (Buffer.isBuffer(item)) { + addReferenceable(item); - // Map a list of chunks to a list of modules - // For the key the chunk "index" is used, the value is a SortableSet of modules - /** @type {Map} */ - const chunksInfoMap = new Map(); + return item; + } else if (typeof item === "function") { + return SerializerMiddleware.deserializeLazy( + item, + data => this.deserialize(data, context)[0] + ); + } else { + return item; + } + }; - /** - * @param {CacheGroup} cacheGroup the current cache group - * @param {number} cacheGroupIndex the index of the cache group of ordering - * @param {Chunk[]} selectedChunks chunks selected for this module - * @param {bigint | Chunk} selectedChunksKey a key of selectedChunks - * @param {Module} module the current module - * @returns {void} - */ - const addModuleToChunksInfoMap = ( - cacheGroup, - cacheGroupIndex, - selectedChunks, - selectedChunksKey, - module - ) => { - // Break if minimum number of chunks is not reached - if (selectedChunks.length < cacheGroup.minChunks) return; - // Determine name for split chunk - const name = cacheGroup.getName( - module, - selectedChunks, - cacheGroup.key - ); - // Check if the name is ok - const existingChunk = compilation.namedChunks.get(name); - if (existingChunk) { - const parentValidationKey = `${name}|${ - typeof selectedChunksKey === "bigint" - ? selectedChunksKey - : selectedChunksKey.debugId - }`; - const valid = alreadyValidatedParents.get(parentValidationKey); - if (valid === false) return; - if (valid === undefined) { - // Module can only be moved into the existing chunk if the existing chunk - // is a parent of all selected chunks - let isInAllParents = true; - /** @type {Set} */ - const queue = new Set(); - for (const chunk of selectedChunks) { - for (const group of chunk.groupsIterable) { - queue.add(group); - } - } - for (const group of queue) { - if (existingChunk.isInGroup(group)) continue; - let hasParent = false; - for (const parent of group.parentsIterable) { - hasParent = true; - queue.add(parent); - } - if (!hasParent) { - isInAllParents = false; - } - } - const valid = isInAllParents; - alreadyValidatedParents.set(parentValidationKey, valid); - if (!valid) { - if (!alreadyReportedErrors.has(name)) { - alreadyReportedErrors.add(name); - compilation.errors.push( - new WebpackError( - "SplitChunksPlugin\n" + - `Cache group "${cacheGroup.key}" conflicts with existing chunk.\n` + - `Both have the same name "${name}" and existing chunk is not a parent of the selected modules.\n` + - "Use a different name for the cache group or make sure that the existing chunk is a parent (e. g. via dependOn).\n" + - 'HINT: You can omit "name" to automatically create a name.\n' + - "BREAKING CHANGE: webpack < 5 used to allow to use an entrypoint as splitChunk. " + - "This is no longer allowed when the entrypoint is not a parent of the selected modules.\n" + - "Remove this entrypoint and add modules to cache group's 'test' instead. " + - "If you need modules to be evaluated on startup, add them to the existing entrypoints (make them arrays). " + - "See migration guide of more info." - ) - ); - } - return; - } - } - } - // Create key for maps - // When it has a name we use the name as key - // Otherwise we create the key from chunks and cache group key - // This automatically merges equal names - const key = - cacheGroup.key + - (name - ? ` name:${name}` - : ` chunks:${keyToString(selectedChunksKey)}`); - // Add module to maps - let info = chunksInfoMap.get(key); - if (info === undefined) { - chunksInfoMap.set( - key, - (info = { - modules: new SortableSet( - undefined, - compareModulesByIdentifier - ), - cacheGroup, - cacheGroupIndex, - name, - sizes: {}, - chunks: new Set(), - reuseableChunks: new Set(), - chunksKeys: new Set() - }) - ); - } - const oldSize = info.modules.size; - info.modules.add(module); - if (info.modules.size !== oldSize) { - for (const type of module.getSourceTypes()) { - info.sizes[type] = (info.sizes[type] || 0) + module.size(type); - } - } - const oldChunksKeysSize = info.chunksKeys.size; - info.chunksKeys.add(selectedChunksKey); - if (oldChunksKeysSize !== info.chunksKeys.size) { - for (const chunk of selectedChunks) { - info.chunks.add(chunk); - } - } - }; + try { + while (currentDataPos < data.length) { + result.push(decodeValue()); + } + return result; + } finally { + // Get rid of these references to avoid leaking memory + // This happens because the optimized code v8 generates + // is optimized for our "ctx.read" method so it will reference + // it from e. g. Dependency.prototype.deserialize -(IC)-> ctx.read + result = referenceable = data = objectTypeLookup = ctx = undefined; + } + } +} - const context = { - moduleGraph, - chunkGraph - }; +module.exports = ObjectMiddleware; +module.exports.NOT_SERIALIZABLE = NOT_SERIALIZABLE; - logger.timeEnd("prepare"); - logger.time("modules"); +/***/ }), - // Walk through all modules - for (const module of compilation.modules) { - // Get cache group - let cacheGroups = this.options.getCacheGroups(module, context); - if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { - continue; - } +/***/ 33040: +/***/ (function(module) { - // Prepare some values (usedExports = false) - const getCombs = memoize(() => { - const chunks = chunkGraph.getModuleChunksIterable(module); - const chunksKey = getKey(chunks); - return getCombinations(chunksKey); - }); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - // Prepare some values (usedExports = true) - const getCombsByUsedExports = memoize(() => { - // fill the groupedByExportsMap - getExportsChunkSetsInGraph(); - /** @type {Set | Chunk>} */ - const set = new Set(); - const groupedByUsedExports = groupedByExportsMap.get(module); - for (const chunks of groupedByUsedExports) { - const chunksKey = getKey(chunks); - for (const comb of getExportsCombinations(chunksKey)) - set.add(comb); - } - return set; - }); - let cacheGroupIndex = 0; - for (const cacheGroupSource of cacheGroups) { - const cacheGroup = this._getCacheGroup(cacheGroupSource); - const combs = cacheGroup.usedExports - ? getCombsByUsedExports() - : getCombs(); - // For all combination of chunk selection - for (const chunkCombination of combs) { - // Break if minimum number of chunks is not reached - const count = - chunkCombination instanceof Chunk ? 1 : chunkCombination.size; - if (count < cacheGroup.minChunks) continue; - // Select chunks by configuration - const { chunks: selectedChunks, key: selectedChunksKey } = - getSelectedChunks(chunkCombination, cacheGroup.chunksFilter); +const cache = new WeakMap(); - addModuleToChunksInfoMap( - cacheGroup, - cacheGroupIndex, - selectedChunks, - selectedChunksKey, - module - ); - } - cacheGroupIndex++; - } - } +class ObjectStructure { + constructor() { + this.keys = undefined; + this.children = undefined; + } - logger.timeEnd("modules"); + getKeys(keys) { + if (this.keys === undefined) this.keys = keys; + return this.keys; + } - logger.time("queue"); + key(key) { + if (this.children === undefined) this.children = new Map(); + const child = this.children.get(key); + if (child !== undefined) return child; + const newChild = new ObjectStructure(); + this.children.set(key, newChild); + return newChild; + } +} - /** - * @param {ChunksInfoItem} info entry - * @param {string[]} sourceTypes source types to be removed - */ - const removeModulesWithSourceType = (info, sourceTypes) => { - for (const module of info.modules) { - const types = module.getSourceTypes(); - if (sourceTypes.some(type => types.has(type))) { - info.modules.delete(module); - for (const type of types) { - info.sizes[type] -= module.size(type); - } - } - } - }; +const getCachedKeys = (keys, cacheAssoc) => { + let root = cache.get(cacheAssoc); + if (root === undefined) { + root = new ObjectStructure(); + cache.set(cacheAssoc, root); + } + let current = root; + for (const key of keys) { + current = current.key(key); + } + return current.getKeys(keys); +}; - /** - * @param {ChunksInfoItem} info entry - * @returns {boolean} true, if entry become empty - */ - const removeMinSizeViolatingModules = info => { - if (!info.cacheGroup._validateSize) return false; - const violatingSizes = getViolatingMinSizes( - info.sizes, - info.cacheGroup.minSize - ); - if (violatingSizes === undefined) return false; - removeModulesWithSourceType(info, violatingSizes); - return info.modules.size === 0; - }; +class PlainObjectSerializer { + serialize(obj, { write }) { + const keys = Object.keys(obj); + if (keys.length > 128) { + // Objects with so many keys are unlikely to share structure + // with other objects + write(keys); + for (const key of keys) { + write(obj[key]); + } + } else if (keys.length > 1) { + write(getCachedKeys(keys, write)); + for (const key of keys) { + write(obj[key]); + } + } else if (keys.length === 1) { + const key = keys[0]; + write(key); + write(obj[key]); + } else { + write(null); + } + } + deserialize({ read }) { + const keys = read(); + const obj = {}; + if (Array.isArray(keys)) { + for (const key of keys) { + obj[key] = read(); + } + } else if (keys !== null) { + obj[keys] = read(); + } + return obj; + } +} - // Filter items were size < minSize - for (const [key, info] of chunksInfoMap) { - if (removeMinSizeViolatingModules(info)) { - chunksInfoMap.delete(key); - } else if ( - !checkMinSizeReduction( - info.sizes, - info.cacheGroup.minSizeReduction, - info.chunks.size - ) - ) { - chunksInfoMap.delete(key); - } - } +module.exports = PlainObjectSerializer; - /** - * @typedef {Object} MaxSizeQueueItem - * @property {SplitChunksSizes} minSize - * @property {SplitChunksSizes} maxAsyncSize - * @property {SplitChunksSizes} maxInitialSize - * @property {string} automaticNameDelimiter - * @property {string[]} keys - */ - /** @type {Map} */ - const maxSizeQueueMap = new Map(); +/***/ }), - while (chunksInfoMap.size > 0) { - // Find best matching entry - let bestEntryKey; - let bestEntry; - for (const pair of chunksInfoMap) { - const key = pair[0]; - const info = pair[1]; - if ( - bestEntry === undefined || - compareEntries(bestEntry, info) < 0 - ) { - bestEntry = info; - bestEntryKey = key; - } - } +/***/ 57328: +/***/ (function(module) { - const item = bestEntry; - chunksInfoMap.delete(bestEntryKey); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - let chunkName = item.name; - // Variable for the new chunk (lazy created) - /** @type {Chunk} */ - let newChunk; - // When no chunk name, check if we can reuse a chunk instead of creating a new one - let isExistingChunk = false; - let isReusedWithAllModules = false; - if (chunkName) { - const chunkByName = compilation.namedChunks.get(chunkName); - if (chunkByName !== undefined) { - newChunk = chunkByName; - const oldSize = item.chunks.size; - item.chunks.delete(newChunk); - isExistingChunk = item.chunks.size !== oldSize; - } - } else if (item.cacheGroup.reuseExistingChunk) { - outer: for (const chunk of item.chunks) { - if ( - chunkGraph.getNumberOfChunkModules(chunk) !== - item.modules.size - ) { - continue; - } - if ( - item.chunks.size > 1 && - chunkGraph.getNumberOfEntryModules(chunk) > 0 - ) { - continue; - } - for (const module of item.modules) { - if (!chunkGraph.isModuleInChunk(module, chunk)) { - continue outer; - } - } - if (!newChunk || !newChunk.name) { - newChunk = chunk; - } else if ( - chunk.name && - chunk.name.length < newChunk.name.length - ) { - newChunk = chunk; - } else if ( - chunk.name && - chunk.name.length === newChunk.name.length && - chunk.name < newChunk.name - ) { - newChunk = chunk; - } - } - if (newChunk) { - item.chunks.delete(newChunk); - chunkName = undefined; - isExistingChunk = true; - isReusedWithAllModules = true; - } - } - const enforced = - item.cacheGroup._conditionalEnforce && - checkMinSize(item.sizes, item.cacheGroup.enforceSizeThreshold); - const usedChunks = new Set(item.chunks); +class RegExpObjectSerializer { + serialize(obj, { write }) { + write(obj.source); + write(obj.flags); + } + deserialize({ read }) { + return new RegExp(read(), read()); + } +} - // Check if maxRequests condition can be fulfilled - if ( - !enforced && - (Number.isFinite(item.cacheGroup.maxInitialRequests) || - Number.isFinite(item.cacheGroup.maxAsyncRequests)) - ) { - for (const chunk of usedChunks) { - // respect max requests - const maxRequests = chunk.isOnlyInitial() - ? item.cacheGroup.maxInitialRequests - : chunk.canBeInitial() - ? Math.min( - item.cacheGroup.maxInitialRequests, - item.cacheGroup.maxAsyncRequests - ) - : item.cacheGroup.maxAsyncRequests; - if ( - isFinite(maxRequests) && - getRequests(chunk) >= maxRequests - ) { - usedChunks.delete(chunk); - } - } - } +module.exports = RegExpObjectSerializer; - outer: for (const chunk of usedChunks) { - for (const module of item.modules) { - if (chunkGraph.isModuleInChunk(module, chunk)) continue outer; - } - usedChunks.delete(chunk); - } - // Were some (invalid) chunks removed from usedChunks? - // => readd all modules to the queue, as things could have been changed - if (usedChunks.size < item.chunks.size) { - if (isExistingChunk) usedChunks.add(newChunk); - if (usedChunks.size >= item.cacheGroup.minChunks) { - const chunksArr = Array.from(usedChunks); - for (const module of item.modules) { - addModuleToChunksInfoMap( - item.cacheGroup, - item.cacheGroupIndex, - chunksArr, - getKey(usedChunks), - module - ); - } - } - continue; - } +/***/ }), - // Validate minRemainingSize constraint when a single chunk is left over - if ( - !enforced && - item.cacheGroup._validateRemainingSize && - usedChunks.size === 1 - ) { - const [chunk] = usedChunks; - let chunkSizes = Object.create(null); - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - if (!item.modules.has(module)) { - for (const type of module.getSourceTypes()) { - chunkSizes[type] = - (chunkSizes[type] || 0) + module.size(type); - } - } - } - const violatingSizes = getViolatingMinSizes( - chunkSizes, - item.cacheGroup.minRemainingSize - ); - if (violatingSizes !== undefined) { - const oldModulesSize = item.modules.size; - removeModulesWithSourceType(item, violatingSizes); - if ( - item.modules.size > 0 && - item.modules.size !== oldModulesSize - ) { - // queue this item again to be processed again - // without violating modules - chunksInfoMap.set(bestEntryKey, item); - } - continue; - } - } +/***/ 53080: +/***/ (function(module) { - // Create the new chunk if not reusing one - if (newChunk === undefined) { - newChunk = compilation.addChunk(chunkName); - } - // Walk through all chunks - for (const chunk of usedChunks) { - // Add graph connections for splitted chunk - chunk.split(newChunk); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - // Add a note to the chunk - newChunk.chunkReason = - (newChunk.chunkReason ? newChunk.chunkReason + ", " : "") + - (isReusedWithAllModules - ? "reused as split chunk" - : "split chunk"); - if (item.cacheGroup.key) { - newChunk.chunkReason += ` (cache group: ${item.cacheGroup.key})`; - } - if (chunkName) { - newChunk.chunkReason += ` (name: ${chunkName})`; - } - if (item.cacheGroup.filename) { - newChunk.filenameTemplate = item.cacheGroup.filename; - } - if (item.cacheGroup.idHint) { - newChunk.idNameHints.add(item.cacheGroup.idHint); - } - if (!isReusedWithAllModules) { - // Add all modules to the new chunk - for (const module of item.modules) { - if (!module.chunkCondition(newChunk, compilation)) continue; - // Add module to new chunk - chunkGraph.connectChunkAndModule(newChunk, module); - // Remove module from used chunks - for (const chunk of usedChunks) { - chunkGraph.disconnectChunkAndModule(chunk, module); - } - } - } else { - // Remove all modules from used chunks - for (const module of item.modules) { - for (const chunk of usedChunks) { - chunkGraph.disconnectChunkAndModule(chunk, module); - } - } - } - - if ( - Object.keys(item.cacheGroup.maxAsyncSize).length > 0 || - Object.keys(item.cacheGroup.maxInitialSize).length > 0 - ) { - const oldMaxSizeSettings = maxSizeQueueMap.get(newChunk); - maxSizeQueueMap.set(newChunk, { - minSize: oldMaxSizeSettings - ? combineSizes( - oldMaxSizeSettings.minSize, - item.cacheGroup._minSizeForMaxSize, - Math.max - ) - : item.cacheGroup.minSize, - maxAsyncSize: oldMaxSizeSettings - ? combineSizes( - oldMaxSizeSettings.maxAsyncSize, - item.cacheGroup.maxAsyncSize, - Math.min - ) - : item.cacheGroup.maxAsyncSize, - maxInitialSize: oldMaxSizeSettings - ? combineSizes( - oldMaxSizeSettings.maxInitialSize, - item.cacheGroup.maxInitialSize, - Math.min - ) - : item.cacheGroup.maxInitialSize, - automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter, - keys: oldMaxSizeSettings - ? oldMaxSizeSettings.keys.concat(item.cacheGroup.key) - : [item.cacheGroup.key] - }); - } - - // remove all modules from other entries and update size - for (const [key, info] of chunksInfoMap) { - if (isOverlap(info.chunks, usedChunks)) { - // update modules and total size - // may remove it from the map when < minSize - let updated = false; - for (const module of item.modules) { - if (info.modules.has(module)) { - // remove module - info.modules.delete(module); - // update size - for (const key of module.getSourceTypes()) { - info.sizes[key] -= module.size(key); - } - updated = true; - } - } - if (updated) { - if (info.modules.size === 0) { - chunksInfoMap.delete(key); - continue; - } - if ( - removeMinSizeViolatingModules(info) || - !checkMinSizeReduction( - info.sizes, - info.cacheGroup.minSizeReduction, - info.chunks.size - ) - ) { - chunksInfoMap.delete(key); - continue; - } - } - } - } - } - logger.timeEnd("queue"); - - logger.time("maxSize"); - - /** @type {Set} */ - const incorrectMinMaxSizeSet = new Set(); - const { outputOptions } = compilation; +class Serializer { + constructor(middlewares, context) { + this.serializeMiddlewares = middlewares.slice(); + this.deserializeMiddlewares = middlewares.slice().reverse(); + this.context = context; + } - // Make sure that maxSize is fulfilled - const { fallbackCacheGroup } = this.options; - for (const chunk of Array.from(compilation.chunks)) { - const chunkConfig = maxSizeQueueMap.get(chunk); - const { - minSize, - maxAsyncSize, - maxInitialSize, - automaticNameDelimiter - } = chunkConfig || fallbackCacheGroup; - if (!chunkConfig && !fallbackCacheGroup.chunksFilter(chunk)) - continue; - /** @type {SplitChunksSizes} */ - let maxSize; - if (chunk.isOnlyInitial()) { - maxSize = maxInitialSize; - } else if (chunk.canBeInitial()) { - maxSize = combineSizes(maxAsyncSize, maxInitialSize, Math.min); - } else { - maxSize = maxAsyncSize; - } - if (Object.keys(maxSize).length === 0) { - continue; - } - for (const key of Object.keys(maxSize)) { - const maxSizeValue = maxSize[key]; - const minSizeValue = minSize[key]; - if ( - typeof minSizeValue === "number" && - minSizeValue > maxSizeValue - ) { - const keys = chunkConfig && chunkConfig.keys; - const warningKey = `${ - keys && keys.join() - } ${minSizeValue} ${maxSizeValue}`; - if (!incorrectMinMaxSizeSet.has(warningKey)) { - incorrectMinMaxSizeSet.add(warningKey); - compilation.warnings.push( - new MinMaxSizeWarning(keys, minSizeValue, maxSizeValue) - ); - } - } - } - const results = deterministicGroupingForModules({ - minSize, - maxSize: mapObject(maxSize, (value, key) => { - const minSizeValue = minSize[key]; - return typeof minSizeValue === "number" - ? Math.max(value, minSizeValue) - : value; - }), - items: chunkGraph.getChunkModulesIterable(chunk), - getKey(module) { - const cache = getKeyCache.get(module); - if (cache !== undefined) return cache; - const ident = cachedMakePathsRelative(module.identifier()); - const nameForCondition = - module.nameForCondition && module.nameForCondition(); - const name = nameForCondition - ? cachedMakePathsRelative(nameForCondition) - : ident.replace(/^.*!|\?[^?!]*$/g, ""); - const fullKey = - name + - automaticNameDelimiter + - hashFilename(ident, outputOptions); - const key = requestToId(fullKey); - getKeyCache.set(module, key); - return key; - }, - getSize(module) { - const size = Object.create(null); - for (const key of module.getSourceTypes()) { - size[key] = module.size(key); - } - return size; - } - }); - if (results.length <= 1) { - continue; - } - for (let i = 0; i < results.length; i++) { - const group = results[i]; - const key = this.options.hidePathInfo - ? hashFilename(group.key, outputOptions) - : group.key; - let name = chunk.name - ? chunk.name + automaticNameDelimiter + key - : null; - if (name && name.length > 100) { - name = - name.slice(0, 100) + - automaticNameDelimiter + - hashFilename(name, outputOptions); - } - if (i !== results.length - 1) { - const newPart = compilation.addChunk(name); - chunk.split(newPart); - newPart.chunkReason = chunk.chunkReason; - // Add all modules to the new chunk - for (const module of group.items) { - if (!module.chunkCondition(newPart, compilation)) { - continue; - } - // Add module to new chunk - chunkGraph.connectChunkAndModule(newPart, module); - // Remove module from used chunks - chunkGraph.disconnectChunkAndModule(chunk, module); - } - } else { - // change the chunk to be a part - chunk.name = name; - } - } - } - logger.timeEnd("maxSize"); + serialize(obj, context) { + const ctx = { ...context, ...this.context }; + let current = obj; + for (const middleware of this.serializeMiddlewares) { + if (current && typeof current.then === "function") { + current = current.then(data => data && middleware.serialize(data, ctx)); + } else if (current) { + try { + current = middleware.serialize(current, ctx); + } catch (err) { + current = Promise.reject(err); } - ); - }); + } else break; + } + return current; } -}; + + deserialize(value, context) { + const ctx = { ...context, ...this.context }; + /** @type {any} */ + let current = value; + for (const middleware of this.deserializeMiddlewares) { + if (current && typeof current.then === "function") { + current = current.then(data => middleware.deserialize(data, ctx)); + } else { + current = middleware.deserialize(current, ctx); + } + } + return current; + } +} + +module.exports = Serializer; /***/ }), -/***/ 52149: +/***/ 83137: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn */ -const { formatSize } = __webpack_require__(71070); -const WebpackError = __webpack_require__(53799); +const memoize = __webpack_require__(78676); -/** @typedef {import("./SizeLimitsPlugin").AssetDetails} AssetDetails */ +const LAZY_TARGET = Symbol("lazy serialization target"); +const LAZY_SERIALIZED_VALUE = Symbol("lazy serialization data"); -module.exports = class AssetsOverSizeLimitWarning extends WebpackError { +/** + * @template DeserializedType + * @template SerializedType + */ +class SerializerMiddleware { + /* istanbul ignore next */ /** - * @param {AssetDetails[]} assetsOverSizeLimit the assets - * @param {number} assetLimit the size limit + * @abstract + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType|Promise} serialized data */ - constructor(assetsOverSizeLimit, assetLimit) { - const assetLists = assetsOverSizeLimit - .map(asset => `\n ${asset.name} (${formatSize(asset.size)})`) - .join(""); - - super(`asset size limit: The following asset(s) exceed the recommended size limit (${formatSize( - assetLimit - )}). -This can impact web performance. -Assets: ${assetLists}`); - - this.name = "AssetsOverSizeLimitWarning"; - this.assets = assetsOverSizeLimit; + serialize(data, context) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } -}; - - -/***/ }), - -/***/ 84229: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ - - - -const { formatSize } = __webpack_require__(71070); -const WebpackError = __webpack_require__(53799); - -/** @typedef {import("./SizeLimitsPlugin").EntrypointDetails} EntrypointDetails */ -module.exports = class EntrypointsOverSizeLimitWarning extends WebpackError { + /* istanbul ignore next */ /** - * @param {EntrypointDetails[]} entrypoints the entrypoints - * @param {number} entrypointLimit the size limit + * @abstract + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data */ - constructor(entrypoints, entrypointLimit) { - const entrypointList = entrypoints - .map( - entrypoint => - `\n ${entrypoint.name} (${formatSize( - entrypoint.size - )})\n${entrypoint.files.map(asset => ` ${asset}`).join("\n")}` - ) - .join(""); - super(`entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (${formatSize( - entrypointLimit - )}). This can impact web performance. -Entrypoints:${entrypointList}\n`); - - this.name = "EntrypointsOverSizeLimitWarning"; - this.entrypoints = entrypoints; + deserialize(data, context) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } -}; - - -/***/ }), - -/***/ 17791: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ - - - -const WebpackError = __webpack_require__(53799); -module.exports = class NoAsyncChunksWarning extends WebpackError { - constructor() { - super( - "webpack performance recommendations: \n" + - "You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\n" + - "For more info visit https://webpack.js.org/guides/code-splitting/" - ); - - this.name = "NoAsyncChunksWarning"; + /** + * @param {any | function(): Promise | any} value contained value or function to value + * @param {SerializerMiddleware} target target middleware + * @param {object=} options lazy options + * @param {any=} serializedValue serialized value + * @returns {function(): Promise | any} lazy function + */ + static createLazy(value, target, options = {}, serializedValue) { + if (SerializerMiddleware.isLazy(value, target)) return value; + const fn = typeof value === "function" ? value : () => value; + fn[LAZY_TARGET] = target; + /** @type {any} */ (fn).options = options; + fn[LAZY_SERIALIZED_VALUE] = serializedValue; + return fn; } -}; - - -/***/ }), - -/***/ 32557: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ - - - -const { find } = __webpack_require__(93347); -const AssetsOverSizeLimitWarning = __webpack_require__(52149); -const EntrypointsOverSizeLimitWarning = __webpack_require__(84229); -const NoAsyncChunksWarning = __webpack_require__(17791); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../../declarations/WebpackOptions").PerformanceOptions} PerformanceOptions */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Entrypoint")} Entrypoint */ -/** @typedef {import("../WebpackError")} WebpackError */ - -/** - * @typedef {Object} AssetDetails - * @property {string} name - * @property {number} size - */ - -/** - * @typedef {Object} EntrypointDetails - * @property {string} name - * @property {number} size - * @property {string[]} files - */ - -const isOverSizeLimitSet = new WeakSet(); -const excludeSourceMap = (name, source, info) => !info.development; + /** + * @param {function(): Promise | any} fn lazy function + * @param {SerializerMiddleware=} target target middleware + * @returns {boolean} true, when fn is a lazy function (optionally of that target) + */ + static isLazy(fn, target) { + if (typeof fn !== "function") return false; + const t = fn[LAZY_TARGET]; + return target ? t === target : !!t; + } -module.exports = class SizeLimitsPlugin { /** - * @param {PerformanceOptions} options the plugin options + * @param {function(): Promise | any} fn lazy function + * @returns {object} options */ - constructor(options) { - this.hints = options.hints; - this.maxAssetSize = options.maxAssetSize; - this.maxEntrypointSize = options.maxEntrypointSize; - this.assetFilter = options.assetFilter; + static getLazyOptions(fn) { + if (typeof fn !== "function") return undefined; + return /** @type {any} */ (fn).options; } /** - * @param {ChunkGroup | Source} thing the resource to test - * @returns {boolean} true if over the limit + * @param {function(): Promise | any} fn lazy function + * @returns {any} serialized value */ - static isOverSizeLimit(thing) { - return isOverSizeLimitSet.has(thing); + static getLazySerializedValue(fn) { + if (typeof fn !== "function") return undefined; + return fn[LAZY_SERIALIZED_VALUE]; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {function(): Promise | any} fn lazy function + * @param {any} value serialized value * @returns {void} */ - apply(compiler) { - const entrypointSizeLimit = this.maxEntrypointSize; - const assetSizeLimit = this.maxAssetSize; - const hints = this.hints; - const assetFilter = this.assetFilter || excludeSourceMap; - - compiler.hooks.afterEmit.tap("SizeLimitsPlugin", compilation => { - /** @type {WebpackError[]} */ - const warnings = []; - - /** - * @param {Entrypoint} entrypoint an entrypoint - * @returns {number} the size of the entrypoint - */ - const getEntrypointSize = entrypoint => { - let size = 0; - for (const file of entrypoint.getFiles()) { - const asset = compilation.getAsset(file); - if ( - asset && - assetFilter(asset.name, asset.source, asset.info) && - asset.source - ) { - size += asset.info.size || asset.source.size(); - } - } - return size; - }; - - /** @type {AssetDetails[]} */ - const assetsOverSizeLimit = []; - for (const { name, source, info } of compilation.getAssets()) { - if (!assetFilter(name, source, info) || !source) { - continue; - } - - const size = info.size || source.size(); - if (size > assetSizeLimit) { - assetsOverSizeLimit.push({ - name, - size - }); - isOverSizeLimitSet.add(source); - } - } - - const fileFilter = name => { - const asset = compilation.getAsset(name); - return asset && assetFilter(asset.name, asset.source, asset.info); - }; - - /** @type {EntrypointDetails[]} */ - const entrypointsOverLimit = []; - for (const [name, entry] of compilation.entrypoints) { - const size = getEntrypointSize(entry); - - if (size > entrypointSizeLimit) { - entrypointsOverLimit.push({ - name: name, - size: size, - files: entry.getFiles().filter(fileFilter) - }); - isOverSizeLimitSet.add(entry); - } - } - - if (hints) { - // 1. Individual Chunk: Size < 250kb - // 2. Collective Initial Chunks [entrypoint] (Each Set?): Size < 250kb - // 3. No Async Chunks - // if !1, then 2, if !2 return - if (assetsOverSizeLimit.length > 0) { - warnings.push( - new AssetsOverSizeLimitWarning(assetsOverSizeLimit, assetSizeLimit) - ); - } - if (entrypointsOverLimit.length > 0) { - warnings.push( - new EntrypointsOverSizeLimitWarning( - entrypointsOverLimit, - entrypointSizeLimit - ) - ); - } - - if (warnings.length > 0) { - const someAsyncChunk = find( - compilation.chunks, - chunk => !chunk.canBeInitial() - ); - - if (!someAsyncChunk) { - warnings.push(new NoAsyncChunksWarning()); - } + static setLazySerializedValue(fn, value) { + fn[LAZY_SERIALIZED_VALUE] = value; + } - if (hints === "error") { - compilation.errors.push(...warnings); - } else { - compilation.warnings.push(...warnings); - } - } + /** + * @param {function(): Promise | any} lazy lazy function + * @param {function(any): Promise | any} serialize serialize function + * @returns {function(): Promise | any} new lazy + */ + static serializeLazy(lazy, serialize) { + const fn = memoize(() => { + const r = lazy(); + if (r && typeof r.then === "function") { + return r.then(data => data && serialize(data)); } + return serialize(r); }); + fn[LAZY_TARGET] = lazy[LAZY_TARGET]; + /** @type {any} */ (fn).options = /** @type {any} */ (lazy).options; + lazy[LAZY_SERIALIZED_VALUE] = fn; + return fn; } -}; - - -/***/ }), - -/***/ 95175: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); - -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ - -class ChunkPrefetchFunctionRuntimeModule extends RuntimeModule { /** - * @param {string} childType TODO - * @param {string} runtimeFunction TODO - * @param {string} runtimeHandlers TODO + * @param {function(): Promise | any} lazy lazy function + * @param {function(any): Promise | any} deserialize deserialize function + * @returns {function(): Promise | any} new lazy */ - constructor(childType, runtimeFunction, runtimeHandlers) { - super(`chunk ${childType} function`); - this.childType = childType; - this.runtimeFunction = runtimeFunction; - this.runtimeHandlers = runtimeHandlers; + static deserializeLazy(lazy, deserialize) { + const fn = memoize(() => { + const r = lazy(); + if (r && typeof r.then === "function") { + return r.then(data => deserialize(data)); + } + return deserialize(r); + }); + fn[LAZY_TARGET] = lazy[LAZY_TARGET]; + /** @type {any} */ (fn).options = /** @type {any} */ (lazy).options; + fn[LAZY_SERIALIZED_VALUE] = lazy; + return fn; } /** - * @returns {string} runtime code + * @param {function(): Promise | any} lazy lazy function + * @returns {function(): Promise | any} new lazy */ - generate() { - const { runtimeFunction, runtimeHandlers } = this; - const { runtimeTemplate } = this.compilation; - return Template.asString([ - `${runtimeHandlers} = {};`, - `${runtimeFunction} = ${runtimeTemplate.basicFunction("chunkId", [ - // map is shorter than forEach - `Object.keys(${runtimeHandlers}).map(${runtimeTemplate.basicFunction( - "key", - `${runtimeHandlers}[key](chunkId);` - )});` - ])}` - ]); + static unMemoizeLazy(lazy) { + if (!SerializerMiddleware.isLazy(lazy)) return lazy; + const fn = () => { + throw new Error( + "A lazy value that has been unmemorized can't be called again" + ); + }; + fn[LAZY_SERIALIZED_VALUE] = SerializerMiddleware.unMemoizeLazy( + lazy[LAZY_SERIALIZED_VALUE] + ); + fn[LAZY_TARGET] = lazy[LAZY_TARGET]; + fn.options = /** @type {any} */ (lazy).options; + return fn; } } -module.exports = ChunkPrefetchFunctionRuntimeModule; +module.exports = SerializerMiddleware; /***/ }), -/***/ 33895: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 79240: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const ChunkPrefetchFunctionRuntimeModule = __webpack_require__(95175); -const ChunkPrefetchStartupRuntimeModule = __webpack_require__(15294); -const ChunkPrefetchTriggerRuntimeModule = __webpack_require__(98441); -const ChunkPreloadTriggerRuntimeModule = __webpack_require__(56236); - -/** @typedef {import("../Compiler")} Compiler */ - -class ChunkPrefetchPreloadPlugin { - /** - * @param {Compiler} compiler the compiler - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "ChunkPrefetchPreloadPlugin", - compilation => { - compilation.hooks.additionalChunkRuntimeRequirements.tap( - "ChunkPrefetchPreloadPlugin", - (chunk, set, { chunkGraph }) => { - if (chunkGraph.getNumberOfEntryModules(chunk) === 0) return; - const startupChildChunks = chunk.getChildrenOfTypeInOrder( - chunkGraph, - "prefetchOrder" - ); - if (startupChildChunks) { - set.add(RuntimeGlobals.prefetchChunk); - set.add(RuntimeGlobals.onChunksLoaded); - compilation.addRuntimeModule( - chunk, - new ChunkPrefetchStartupRuntimeModule(startupChildChunks) - ); - } - } - ); - compilation.hooks.additionalTreeRuntimeRequirements.tap( - "ChunkPrefetchPreloadPlugin", - (chunk, set, { chunkGraph }) => { - const chunkMap = chunk.getChildIdsByOrdersMap(chunkGraph, false); - - if (chunkMap.prefetch) { - set.add(RuntimeGlobals.prefetchChunk); - compilation.addRuntimeModule( - chunk, - new ChunkPrefetchTriggerRuntimeModule(chunkMap.prefetch) - ); - } - if (chunkMap.preload) { - set.add(RuntimeGlobals.preloadChunk); - compilation.addRuntimeModule( - chunk, - new ChunkPreloadTriggerRuntimeModule(chunkMap.preload) - ); - } - } - ); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.prefetchChunk) - .tap("ChunkPrefetchPreloadPlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new ChunkPrefetchFunctionRuntimeModule( - "prefetch", - RuntimeGlobals.prefetchChunk, - RuntimeGlobals.prefetchChunkHandlers - ) - ); - set.add(RuntimeGlobals.prefetchChunkHandlers); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.preloadChunk) - .tap("ChunkPrefetchPreloadPlugin", (chunk, set) => { - compilation.addRuntimeModule( - chunk, - new ChunkPrefetchFunctionRuntimeModule( - "preload", - RuntimeGlobals.preloadChunk, - RuntimeGlobals.preloadChunkHandlers - ) - ); - set.add(RuntimeGlobals.preloadChunkHandlers); - }); - } - ); +class SetObjectSerializer { + serialize(obj, { write }) { + write(obj.size); + for (const value of obj) { + write(value); + } + } + deserialize({ read }) { + let size = read(); + const set = new Set(); + for (let i = 0; i < size; i++) { + set.add(read()); + } + return set; } } -module.exports = ChunkPrefetchPreloadPlugin; +module.exports = SetObjectSerializer; /***/ }), -/***/ 15294: +/***/ 65112: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -114631,709 +114022,336 @@ module.exports = ChunkPrefetchPreloadPlugin; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); - -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +const SerializerMiddleware = __webpack_require__(83137); -class ChunkPrefetchStartupRuntimeModule extends RuntimeModule { +/** + * @typedef {any} DeserializedType + * @typedef {any[]} SerializedType + * @extends {SerializerMiddleware} + */ +class SingleItemMiddleware extends SerializerMiddleware { /** - * @param {{ onChunks: Chunk[], chunks: Set }[]} startupChunks chunk ids to trigger when chunks are loaded + * @param {DeserializedType} data data + * @param {Object} context context object + * @returns {SerializedType|Promise} serialized data */ - constructor(startupChunks) { - super("startup prefetch", RuntimeModule.STAGE_TRIGGER); - this.startupChunks = startupChunks; + serialize(data, context) { + return [data]; } /** - * @returns {string} runtime code + * @param {SerializedType} data data + * @param {Object} context context object + * @returns {DeserializedType|Promise} deserialized data */ - generate() { - const { startupChunks, chunk } = this; - const { runtimeTemplate } = this.compilation; - return Template.asString( - startupChunks.map( - ({ onChunks, chunks }) => - `${RuntimeGlobals.onChunksLoaded}(0, ${JSON.stringify( - // This need to include itself to delay execution after this chunk has been fully loaded - onChunks.filter(c => c === chunk).map(c => c.id) - )}, ${runtimeTemplate.basicFunction( - "", - chunks.size < 3 - ? Array.from( - chunks, - c => - `${RuntimeGlobals.prefetchChunk}(${JSON.stringify(c.id)});` - ) - : `${JSON.stringify(Array.from(chunks, c => c.id))}.map(${ - RuntimeGlobals.prefetchChunk - });` - )}, 5);` - ) - ); + deserialize(data, context) { + return data[0]; } } -module.exports = ChunkPrefetchStartupRuntimeModule; +module.exports = SingleItemMiddleware; /***/ }), -/***/ 98441: +/***/ 58831: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); +const ModuleDependency = __webpack_require__(80321); +const makeSerializable = __webpack_require__(33032); -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +class ConsumeSharedFallbackDependency extends ModuleDependency { + constructor(request) { + super(request); + } -class ChunkPrefetchTriggerRuntimeModule extends RuntimeModule { - /** - * @param {Record} chunkMap map from chunk to - */ - constructor(chunkMap) { - super(`chunk prefetch trigger`, RuntimeModule.STAGE_TRIGGER); - this.chunkMap = chunkMap; + get type() { + return "consume shared fallback"; } - /** - * @returns {string} runtime code - */ - generate() { - const { chunkMap } = this; - const { runtimeTemplate } = this.compilation; - const body = [ - "var chunks = chunkToChildrenMap[chunkId];", - `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.prefetchChunk});` - ]; - return Template.asString([ - Template.asString([ - `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, - `${ - RuntimeGlobals.ensureChunkHandlers - }.prefetch = ${runtimeTemplate.expressionFunction( - `Promise.all(promises).then(${runtimeTemplate.basicFunction( - "", - body - )})`, - "chunkId, promises" - )};` - ]) - ]); + get category() { + return "esm"; } } -module.exports = ChunkPrefetchTriggerRuntimeModule; +makeSerializable( + ConsumeSharedFallbackDependency, + "webpack/lib/sharing/ConsumeSharedFallbackDependency" +); + +module.exports = ConsumeSharedFallbackDependency; /***/ }), -/***/ 56236: +/***/ 62286: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ +const { RawSource } = __webpack_require__(51255); +const AsyncDependenciesBlock = __webpack_require__(47736); +const Module = __webpack_require__(73208); const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); +const makeSerializable = __webpack_require__(33032); +const { rangeToString, stringifyHoley } = __webpack_require__(19702); +const ConsumeSharedFallbackDependency = __webpack_require__(58831); -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +/** @typedef {import("../util/semver").SemVerRange} SemVerRange */ -class ChunkPreloadTriggerRuntimeModule extends RuntimeModule { +/** + * @typedef {Object} ConsumeOptions + * @property {string=} import fallback request + * @property {string=} importResolved resolved fallback request + * @property {string} shareKey global share key + * @property {string} shareScope share scope + * @property {SemVerRange | false | undefined} requiredVersion version requirement + * @property {string} packageName package name to determine required version automatically + * @property {boolean} strictVersion don't use shared version even if version isn't valid + * @property {boolean} singleton use single global version + * @property {boolean} eager include the fallback module in a sync way + */ + +const TYPES = new Set(["consume-shared"]); + +class ConsumeSharedModule extends Module { /** - * @param {Record} chunkMap map from chunk to chunks + * @param {string} context context + * @param {ConsumeOptions} options consume options */ - constructor(chunkMap) { - super(`chunk preload trigger`, RuntimeModule.STAGE_TRIGGER); - this.chunkMap = chunkMap; + constructor(context, options) { + super("consume-shared-module", context); + this.options = options; } /** - * @returns {string} runtime code + * @returns {string} a unique identifier of the module */ - generate() { - const { chunkMap } = this; - const { runtimeTemplate } = this.compilation; - const body = [ - "var chunks = chunkToChildrenMap[chunkId];", - `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.preloadChunk});` - ]; - return Template.asString([ - Template.asString([ - `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, - `${ - RuntimeGlobals.ensureChunkHandlers - }.preload = ${runtimeTemplate.basicFunction("chunkId", body)};` - ]) - ]); + identifier() { + const { + shareKey, + shareScope, + importResolved, + requiredVersion, + strictVersion, + singleton, + eager + } = this.options; + return `consume-shared-module|${shareScope}|${shareKey}|${ + requiredVersion && rangeToString(requiredVersion) + }|${strictVersion}|${importResolved}|${singleton}|${eager}`; } -} - -module.exports = ChunkPreloadTriggerRuntimeModule; - -/***/ }), - -/***/ 30318: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + const { + shareKey, + shareScope, + importResolved, + requiredVersion, + strictVersion, + singleton, + eager + } = this.options; + return `consume shared module (${shareScope}) ${shareKey}@${ + requiredVersion ? rangeToString(requiredVersion) : "*" + }${strictVersion ? " (strict)" : ""}${singleton ? " (singleton)" : ""}${ + importResolved + ? ` (fallback: ${requestShortener.shorten(importResolved)})` + : "" + }${eager ? " (eager)" : ""}`; + } -class BasicEffectRulePlugin { - constructor(ruleProperty, effectType) { - this.ruleProperty = ruleProperty; - this.effectType = effectType || ruleProperty; + /** + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion + */ + libIdent(options) { + const { shareKey, shareScope, import: request } = this.options; + return `${ + this.layer ? `(${this.layer})/` : "" + }webpack/sharing/consume/${shareScope}/${shareKey}${ + request ? `/${request}` : "" + }`; } /** - * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild * @returns {void} */ - apply(ruleSetCompiler) { - ruleSetCompiler.hooks.rule.tap( - "BasicEffectRulePlugin", - (path, rule, unhandledProperties, result, references) => { - if (unhandledProperties.has(this.ruleProperty)) { - unhandledProperties.delete(this.ruleProperty); - - const value = rule[this.ruleProperty]; - - result.effects.push({ - type: this.effectType, - value - }); - } - } - ); - } -} - -module.exports = BasicEffectRulePlugin; - - -/***/ }), - -/***/ 94215: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ -/** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */ - -class BasicMatcherRulePlugin { - constructor(ruleProperty, dataProperty, invert) { - this.ruleProperty = ruleProperty; - this.dataProperty = dataProperty || ruleProperty; - this.invert = invert || false; - } - - /** - * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler - * @returns {void} - */ - apply(ruleSetCompiler) { - ruleSetCompiler.hooks.rule.tap( - "BasicMatcherRulePlugin", - (path, rule, unhandledProperties, result) => { - if (unhandledProperties.has(this.ruleProperty)) { - unhandledProperties.delete(this.ruleProperty); - const value = rule[this.ruleProperty]; - const condition = ruleSetCompiler.compileCondition( - `${path}.${this.ruleProperty}`, - value - ); - const fn = condition.fn; - result.conditions.push({ - property: this.dataProperty, - matchWhenEmpty: this.invert - ? !condition.matchWhenEmpty - : condition.matchWhenEmpty, - fn: this.invert ? v => !fn(v) : fn - }); - } - } - ); - } -} - -module.exports = BasicMatcherRulePlugin; - - -/***/ }), - -/***/ 72021: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ -/** @typedef {import("./RuleSetCompiler").RuleCondition} RuleCondition */ - -class ObjectMatcherRulePlugin { - constructor(ruleProperty, dataProperty) { - this.ruleProperty = ruleProperty; - this.dataProperty = dataProperty || ruleProperty; + needBuild(context, callback) { + callback(null, !this.buildInfo); } /** - * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler + * @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} */ - apply(ruleSetCompiler) { - const { ruleProperty, dataProperty } = this; - ruleSetCompiler.hooks.rule.tap( - "ObjectMatcherRulePlugin", - (path, rule, unhandledProperties, result) => { - if (unhandledProperties.has(ruleProperty)) { - unhandledProperties.delete(ruleProperty); - const value = rule[ruleProperty]; - for (const property of Object.keys(value)) { - const nestedDataProperties = property.split("."); - const condition = ruleSetCompiler.compileCondition( - `${path}.${ruleProperty}.${property}`, - value[property] - ); - result.conditions.push({ - property: [dataProperty, ...nestedDataProperties], - matchWhenEmpty: condition.matchWhenEmpty, - fn: condition.fn - }); - } - } - } - ); - } -} - -module.exports = ObjectMatcherRulePlugin; - - -/***/ }), - -/***/ 83349: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { SyncHook } = __webpack_require__(41242); - -/** - * @typedef {Object} RuleCondition - * @property {string | string[]} property - * @property {boolean} matchWhenEmpty - * @property {function(string): boolean} fn - */ - -/** - * @typedef {Object} Condition - * @property {boolean} matchWhenEmpty - * @property {function(string): boolean} fn - */ - -/** - * @typedef {Object} CompiledRule - * @property {RuleCondition[]} conditions - * @property {(Effect|function(object): Effect[])[]} effects - * @property {CompiledRule[]=} rules - * @property {CompiledRule[]=} oneOf - */ - -/** - * @typedef {Object} Effect - * @property {string} type - * @property {any} value - */ - -/** - * @typedef {Object} RuleSet - * @property {Map} references map of references in the rule set (may grow over time) - * @property {function(object): Effect[]} exec execute the rule set - */ - -class RuleSetCompiler { - constructor(plugins) { - this.hooks = Object.freeze({ - /** @type {SyncHook<[string, object, Set, CompiledRule, Map]>} */ - rule: new SyncHook([ - "path", - "rule", - "unhandledProperties", - "compiledRule", - "references" - ]) - }); - if (plugins) { - for (const plugin of plugins) { - plugin.apply(this); + build(options, compilation, resolver, fs, callback) { + this.buildMeta = {}; + this.buildInfo = {}; + if (this.options.import) { + const dep = new ConsumeSharedFallbackDependency(this.options.import); + if (this.options.eager) { + this.addDependency(dep); + } else { + const block = new AsyncDependenciesBlock({}); + block.addDependency(dep); + this.addBlock(block); } } + callback(); } /** - * @param {object[]} ruleSet raw user provided rules - * @returns {RuleSet} compiled RuleSet + * @returns {Set} types available (do not mutate) */ - compile(ruleSet) { - const refs = new Map(); - const rules = this.compileRules("ruleSet", ruleSet, refs); - - /** - * @param {object} data data passed in - * @param {CompiledRule} rule the compiled rule - * @param {Effect[]} effects an array where effects are pushed to - * @returns {boolean} true, if the rule has matched - */ - const execRule = (data, rule, effects) => { - for (const condition of rule.conditions) { - const p = condition.property; - if (Array.isArray(p)) { - let current = data; - for (const subProperty of p) { - if ( - current && - typeof current === "object" && - Object.prototype.hasOwnProperty.call(current, subProperty) - ) { - current = current[subProperty]; - } else { - current = undefined; - break; - } - } - if (current !== undefined) { - if (!condition.fn(current)) return false; - continue; - } - } else if (p in data) { - const value = data[p]; - if (value !== undefined) { - if (!condition.fn(value)) return false; - continue; - } - } - if (!condition.matchWhenEmpty) { - return false; - } - } - for (const effect of rule.effects) { - if (typeof effect === "function") { - const returnedEffects = effect(data); - for (const effect of returnedEffects) { - effects.push(effect); - } - } else { - effects.push(effect); - } - } - if (rule.rules) { - for (const childRule of rule.rules) { - execRule(data, childRule, effects); - } - } - if (rule.oneOf) { - for (const childRule of rule.oneOf) { - if (execRule(data, childRule, effects)) { - break; - } - } - } - return true; - }; - - return { - references: refs, - exec: data => { - /** @type {Effect[]} */ - const effects = []; - for (const rule of rules) { - execRule(data, rule, effects); - } - return effects; - } - }; + getSourceTypes() { + return TYPES; } /** - * @param {string} path current path - * @param {object[]} rules the raw rules provided by user - * @param {Map} refs references - * @returns {CompiledRule[]} rules + * @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) */ - compileRules(path, rules, refs) { - return rules.map((rule, i) => - this.compileRule(`${path}[${i}]`, rule, refs) - ); + size(type) { + return 42; } /** - * @param {string} path current path - * @param {object} rule the raw rule provided by user - * @param {Map} refs references - * @returns {CompiledRule} normalized and compiled rule for processing + * @param {Hash} hash the hash used to track dependencies + * @param {UpdateHashContext} context context + * @returns {void} */ - compileRule(path, rule, refs) { - const unhandledProperties = new Set( - Object.keys(rule).filter(key => rule[key] !== undefined) - ); - - /** @type {CompiledRule} */ - const compiledRule = { - conditions: [], - effects: [], - rules: undefined, - oneOf: undefined - }; - - this.hooks.rule.call(path, rule, unhandledProperties, compiledRule, refs); - - if (unhandledProperties.has("rules")) { - unhandledProperties.delete("rules"); - const rules = rule.rules; - if (!Array.isArray(rules)) - throw this.error(path, rules, "Rule.rules must be an array of rules"); - compiledRule.rules = this.compileRules(`${path}.rules`, rules, refs); - } - - if (unhandledProperties.has("oneOf")) { - unhandledProperties.delete("oneOf"); - const oneOf = rule.oneOf; - if (!Array.isArray(oneOf)) - throw this.error(path, oneOf, "Rule.oneOf must be an array of rules"); - compiledRule.oneOf = this.compileRules(`${path}.oneOf`, oneOf, refs); - } - - if (unhandledProperties.size > 0) { - throw this.error( - path, - rule, - `Properties ${Array.from(unhandledProperties).join(", ")} are unknown` - ); - } - - return compiledRule; + updateHash(hash, context) { + hash.update(JSON.stringify(this.options)); + super.updateHash(hash, context); } /** - * @param {string} path current path - * @param {any} condition user provided condition value - * @returns {Condition} compiled condition + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - compileCondition(path, condition) { - if (condition === "") { - return { - matchWhenEmpty: true, - fn: str => str === "" - }; - } - if (!condition) { - throw this.error( - path, - condition, - "Expected condition but got falsy value" - ); - } - if (typeof condition === "string") { - return { - matchWhenEmpty: condition.length === 0, - fn: str => typeof str === "string" && str.startsWith(condition) - }; - } - if (typeof condition === "function") { - try { - return { - matchWhenEmpty: condition(""), - fn: condition - }; - } catch (err) { - throw this.error( - path, - condition, - "Evaluation of condition function threw error" - ); + codeGeneration({ chunkGraph, moduleGraph, runtimeTemplate }) { + const runtimeRequirements = new Set([RuntimeGlobals.shareScopeMap]); + const { + shareScope, + shareKey, + strictVersion, + requiredVersion, + import: request, + singleton, + eager + } = this.options; + let fallbackCode; + if (request) { + if (eager) { + const dep = this.dependencies[0]; + fallbackCode = runtimeTemplate.syncModuleFactory({ + dependency: dep, + chunkGraph, + runtimeRequirements, + request: this.options.import + }); + } else { + const block = this.blocks[0]; + fallbackCode = runtimeTemplate.asyncModuleFactory({ + block, + chunkGraph, + runtimeRequirements, + request: this.options.import + }); } } - if (condition instanceof RegExp) { - return { - matchWhenEmpty: condition.test(""), - fn: v => typeof v === "string" && condition.test(v) - }; - } - if (Array.isArray(condition)) { - const items = condition.map((c, i) => - this.compileCondition(`${path}[${i}]`, c) - ); - return this.combineConditionsOr(items); - } - - if (typeof condition !== "object") { - throw this.error( - path, - condition, - `Unexpected ${typeof condition} when condition was expected` - ); - } - - const conditions = []; - for (const key of Object.keys(condition)) { - const value = condition[key]; - switch (key) { - case "or": - if (value) { - if (!Array.isArray(value)) { - throw this.error( - `${path}.or`, - condition.and, - "Expected array of conditions" - ); - } - conditions.push(this.compileCondition(`${path}.or`, value)); - } - break; - case "and": - if (value) { - if (!Array.isArray(value)) { - throw this.error( - `${path}.and`, - condition.and, - "Expected array of conditions" - ); - } - let i = 0; - for (const item of value) { - conditions.push(this.compileCondition(`${path}.and[${i}]`, item)); - i++; - } - } - break; - case "not": - if (value) { - const matcher = this.compileCondition(`${path}.not`, value); - const fn = matcher.fn; - conditions.push({ - matchWhenEmpty: !matcher.matchWhenEmpty, - fn: v => !fn(v) - }); - } - break; - default: - throw this.error( - `${path}.${key}`, - condition[key], - `Unexpected property ${key} in condition` - ); + let fn = "load"; + const args = [JSON.stringify(shareScope), JSON.stringify(shareKey)]; + if (requiredVersion) { + if (strictVersion) { + fn += "Strict"; } - } - if (conditions.length === 0) { - throw this.error( - path, - condition, - "Expected condition, but got empty thing" - ); - } - return this.combineConditionsAnd(conditions); - } - - /** - * @param {Condition[]} conditions some conditions - * @returns {Condition} merged condition - */ - combineConditionsOr(conditions) { - if (conditions.length === 0) { - return { - matchWhenEmpty: false, - fn: () => false - }; - } else if (conditions.length === 1) { - return conditions[0]; + if (singleton) { + fn += "Singleton"; + } + args.push(stringifyHoley(requiredVersion)); + fn += "VersionCheck"; } else { - return { - matchWhenEmpty: conditions.some(c => c.matchWhenEmpty), - fn: v => conditions.some(c => c.fn(v)) - }; + if (singleton) { + fn += "Singleton"; + } + } + if (fallbackCode) { + fn += "Fallback"; + args.push(fallbackCode); } + const code = runtimeTemplate.returningFunction(`${fn}(${args.join(", ")})`); + const sources = new Map(); + sources.set("consume-shared", new RawSource(code)); + return { + runtimeRequirements, + sources + }; } - /** - * @param {Condition[]} conditions some conditions - * @returns {Condition} merged condition - */ - combineConditionsAnd(conditions) { - if (conditions.length === 0) { - return { - matchWhenEmpty: false, - fn: () => false - }; - } else if (conditions.length === 1) { - return conditions[0]; - } else { - return { - matchWhenEmpty: conditions.every(c => c.matchWhenEmpty), - fn: v => conditions.every(c => c.fn(v)) - }; - } + serialize(context) { + const { write } = context; + write(this.options); + super.serialize(context); } - /** - * @param {string} path current path - * @param {any} value value at the error location - * @param {string} message message explaining the problem - * @returns {Error} an error object - */ - error(path, value, message) { - return new Error( - `Compiling RuleSet failed: ${message} (at ${path}: ${value})` - ); + deserialize(context) { + const { read } = context; + this.options = read(); + super.deserialize(context); } } -module.exports = RuleSetCompiler; +makeSerializable( + ConsumeSharedModule, + "webpack/lib/sharing/ConsumeSharedModule" +); + +module.exports = ConsumeSharedModule; /***/ }), -/***/ 84977: +/***/ 15046: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -115344,1949 +114362,4136 @@ module.exports = RuleSetCompiler; -const util = __webpack_require__(73837); +const ModuleNotFoundError = __webpack_require__(32882); +const RuntimeGlobals = __webpack_require__(16475); +const WebpackError = __webpack_require__(53799); +const { parseOptions } = __webpack_require__(3083); +const LazySet = __webpack_require__(38938); +const createSchemaValidation = __webpack_require__(32540); +const { parseRange } = __webpack_require__(19702); +const ConsumeSharedFallbackDependency = __webpack_require__(58831); +const ConsumeSharedModule = __webpack_require__(62286); +const ConsumeSharedRuntimeModule = __webpack_require__(10394); +const ProvideForSharedDependency = __webpack_require__(40017); +const { resolveMatchedConfigs } = __webpack_require__(3591); +const { + isRequiredVersion, + getDescriptionFile, + getRequiredVersionFromDescriptionFile +} = __webpack_require__(84379); -/** @typedef {import("./RuleSetCompiler")} RuleSetCompiler */ -/** @typedef {import("./RuleSetCompiler").Effect} Effect */ +/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumeSharedPluginOptions} ConsumeSharedPluginOptions */ +/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumesConfig} ConsumesConfig */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */ +/** @typedef {import("./ConsumeSharedModule").ConsumeOptions} ConsumeOptions */ -class UseEffectRulePlugin { +const validate = createSchemaValidation( + __webpack_require__(6464), + () => __webpack_require__(16116), + { + name: "Consume Shared Plugin", + baseDataPath: "options" + } +); + +/** @type {ResolveOptionsWithDependencyType} */ +const RESOLVE_OPTIONS = { dependencyType: "esm" }; +const PLUGIN_NAME = "ConsumeSharedPlugin"; + +class ConsumeSharedPlugin { /** - * @param {RuleSetCompiler} ruleSetCompiler the rule set compiler - * @returns {void} + * @param {ConsumeSharedPluginOptions} options options */ - apply(ruleSetCompiler) { - ruleSetCompiler.hooks.rule.tap( - "UseEffectRulePlugin", - (path, rule, unhandledProperties, result, references) => { - const conflictWith = (property, correctProperty) => { - if (unhandledProperties.has(property)) { - throw ruleSetCompiler.error( - `${path}.${property}`, - rule[property], - `A Rule must not have a '${property}' property when it has a '${correctProperty}' property` - ); - } - }; + constructor(options) { + if (typeof options !== "string") { + validate(options); + } - if (unhandledProperties.has("use")) { - unhandledProperties.delete("use"); - unhandledProperties.delete("enforce"); + /** @type {[string, ConsumeOptions][]} */ + this._consumes = parseOptions( + options.consumes, + (item, key) => { + if (Array.isArray(item)) throw new Error("Unexpected array in options"); + /** @type {ConsumeOptions} */ + let result = + item === key || !isRequiredVersion(item) + ? // item is a request/key + { + import: key, + shareScope: options.shareScope || "default", + shareKey: key, + requiredVersion: undefined, + packageName: undefined, + strictVersion: false, + singleton: false, + eager: false + } + : // key is a request/key + // item is a version + { + import: key, + shareScope: options.shareScope || "default", + shareKey: key, + requiredVersion: parseRange(item), + strictVersion: true, + packageName: undefined, + singleton: false, + eager: false + }; + return result; + }, + (item, key) => ({ + import: item.import === false ? undefined : item.import || key, + shareScope: item.shareScope || options.shareScope || "default", + shareKey: item.shareKey || key, + requiredVersion: + typeof item.requiredVersion === "string" + ? parseRange(item.requiredVersion) + : item.requiredVersion, + strictVersion: + typeof item.strictVersion === "boolean" + ? item.strictVersion + : item.import !== false && !item.singleton, + packageName: item.packageName, + singleton: !!item.singleton, + eager: !!item.eager + }) + ); + } - conflictWith("loader", "use"); - conflictWith("options", "use"); + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + PLUGIN_NAME, + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + ConsumeSharedFallbackDependency, + normalModuleFactory + ); - const use = rule.use; - const enforce = rule.enforce; + let unresolvedConsumes, resolvedConsumes, prefixedConsumes; + const promise = resolveMatchedConfigs(compilation, this._consumes).then( + ({ resolved, unresolved, prefixed }) => { + resolvedConsumes = resolved; + unresolvedConsumes = unresolved; + prefixedConsumes = prefixed; + } + ); - const type = enforce ? `use-${enforce}` : "use"; + const resolver = compilation.resolverFactory.get( + "normal", + RESOLVE_OPTIONS + ); - /** - * - * @param {string} path options path - * @param {string} defaultIdent default ident when none is provided - * @param {object} item user provided use value - * @returns {Effect|function(any): Effect[]} effect - */ - const useToEffect = (path, defaultIdent, item) => { - if (typeof item === "function") { - return data => useToEffectsWithoutIdent(path, item(data)); - } else { - return useToEffectRaw(path, defaultIdent, item); - } + /** + * @param {string} context issuer directory + * @param {string} request request + * @param {ConsumeOptions} config options + * @returns {Promise} create module + */ + const createConsumeSharedModule = (context, request, config) => { + const requiredVersionWarning = details => { + const error = new WebpackError( + `No required version specified and unable to automatically determine one. ${details}` + ); + error.file = `shared module ${request}`; + compilation.warnings.push(error); }; - - /** - * - * @param {string} path options path - * @param {string} defaultIdent default ident when none is provided - * @param {object} item user provided use value - * @returns {Effect} effect - */ - const useToEffectRaw = (path, defaultIdent, item) => { - if (typeof item === "string") { - return { - type, - value: { - loader: item, - options: undefined, - ident: undefined - } + const directFallback = + config.import && + /^(\.\.?(\/|$)|\/|[A-Za-z]:|\\\\)/.test(config.import); + return Promise.all([ + new Promise(resolve => { + if (!config.import) return resolve(); + const resolveContext = { + /** @type {LazySet} */ + fileDependencies: new LazySet(), + /** @type {LazySet} */ + contextDependencies: new LazySet(), + /** @type {LazySet} */ + missingDependencies: new LazySet() }; - } else { - const loader = item.loader; - const options = item.options; - let ident = item.ident; - if (options && typeof options === "object") { - if (!ident) ident = defaultIdent; - references.set(ident, options); - } - if (typeof options === "string") { - util.deprecate( - () => {}, - `Using a string as loader options is deprecated (${path}.options)`, - "DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING" - )(); - } - return { - type: enforce ? `use-${enforce}` : "use", - value: { - loader, - options, - ident + resolver.resolve( + {}, + directFallback ? compiler.context : context, + config.import, + resolveContext, + (err, result) => { + compilation.contextDependencies.addAll( + resolveContext.contextDependencies + ); + compilation.fileDependencies.addAll( + resolveContext.fileDependencies + ); + compilation.missingDependencies.addAll( + resolveContext.missingDependencies + ); + if (err) { + compilation.errors.push( + new ModuleNotFoundError(null, err, { + name: `resolving fallback for shared module ${request}` + }) + ); + return resolve(); + } + resolve(result); } - }; - } - }; + ); + }), + new Promise(resolve => { + if (config.requiredVersion !== undefined) + return resolve(config.requiredVersion); + let packageName = config.packageName; + if (packageName === undefined) { + if (/^(\/|[A-Za-z]:|\\\\)/.test(request)) { + // For relative or absolute requests we don't automatically use a packageName. + // If wished one can specify one with the packageName option. + return resolve(); + } + const match = /^((?:@[^\\/]+[\\/])?[^\\/]+)/.exec(request); + if (!match) { + requiredVersionWarning( + "Unable to extract the package name from request." + ); + return resolve(); + } + packageName = match[0]; + } - /** - * @param {string} path options path - * @param {any} items user provided use value - * @returns {Effect[]} effects - */ - const useToEffectsWithoutIdent = (path, items) => { - if (Array.isArray(items)) { - return items.map((item, idx) => - useToEffectRaw(`${path}[${idx}]`, "[[missing ident]]", item) + getDescriptionFile( + compilation.inputFileSystem, + context, + ["package.json"], + (err, result) => { + if (err) { + requiredVersionWarning( + `Unable to read description file: ${err}` + ); + return resolve(); + } + const { data, path: descriptionPath } = result; + if (!data) { + requiredVersionWarning( + `Unable to find description file in ${context}.` + ); + return resolve(); + } + const requiredVersion = getRequiredVersionFromDescriptionFile( + data, + packageName + ); + if (typeof requiredVersion !== "string") { + requiredVersionWarning( + `Unable to find required version for "${packageName}" in description file (${descriptionPath}). It need to be in dependencies, devDependencies or peerDependencies.` + ); + return resolve(); + } + resolve(parseRange(requiredVersion)); + } ); - } - return [useToEffectRaw(path, "[[missing ident]]", items)]; - }; + }) + ]).then(([importResolved, requiredVersion]) => { + return new ConsumeSharedModule( + directFallback ? compiler.context : context, + { + ...config, + importResolved, + import: importResolved ? config.import : undefined, + requiredVersion + } + ); + }); + }; - /** - * @param {string} path current path - * @param {any} items user provided use value - * @returns {(Effect|function(any): Effect[])[]} effects - */ - const useToEffects = (path, items) => { - if (Array.isArray(items)) { - return items.map((item, idx) => { - const subPath = `${path}[${idx}]`; - return useToEffect(subPath, subPath, item); - }); + normalModuleFactory.hooks.factorize.tapPromise( + PLUGIN_NAME, + ({ context, request, dependencies }) => + // wait for resolving to be complete + promise.then(() => { + if ( + dependencies[0] instanceof ConsumeSharedFallbackDependency || + dependencies[0] instanceof ProvideForSharedDependency + ) { + return; + } + const match = unresolvedConsumes.get(request); + if (match !== undefined) { + return createConsumeSharedModule(context, request, match); + } + for (const [prefix, options] of prefixedConsumes) { + if (request.startsWith(prefix)) { + const remainder = request.slice(prefix.length); + return createConsumeSharedModule(context, request, { + ...options, + import: options.import + ? options.import + remainder + : undefined, + shareKey: options.shareKey + remainder + }); + } + } + }) + ); + normalModuleFactory.hooks.createModule.tapPromise( + PLUGIN_NAME, + ({ resource }, { context, dependencies }) => { + if ( + dependencies[0] instanceof ConsumeSharedFallbackDependency || + dependencies[0] instanceof ProvideForSharedDependency + ) { + return Promise.resolve(); } - return [useToEffect(path, path, items)]; - }; - - if (typeof use === "function") { - result.effects.push(data => - useToEffectsWithoutIdent(`${path}.use`, use(data)) - ); - } else { - for (const effect of useToEffects(`${path}.use`, use)) { - result.effects.push(effect); + const options = resolvedConsumes.get(resource); + if (options !== undefined) { + return createConsumeSharedModule(context, resource, options); } + return Promise.resolve(); } - } - - if (unhandledProperties.has("loader")) { - unhandledProperties.delete("loader"); - unhandledProperties.delete("options"); - unhandledProperties.delete("enforce"); - - const loader = rule.loader; - const options = rule.options; - const enforce = rule.enforce; - - if (loader.includes("!")) { - throw ruleSetCompiler.error( - `${path}.loader`, - loader, - "Exclamation mark separated loader lists has been removed in favor of the 'use' property with arrays" - ); - } - - if (loader.includes("?")) { - throw ruleSetCompiler.error( - `${path}.loader`, - loader, - "Query arguments on 'loader' has been removed in favor of the 'options' property" + ); + compilation.hooks.additionalTreeRuntimeRequirements.tap( + PLUGIN_NAME, + (chunk, set) => { + set.add(RuntimeGlobals.module); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.shareScopeMap); + set.add(RuntimeGlobals.initializeSharing); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new ConsumeSharedRuntimeModule(set) ); } - - if (typeof options === "string") { - util.deprecate( - () => {}, - `Using a string as loader options is deprecated (${path}.options)`, - "DEP_WEBPACK_RULE_LOADER_OPTIONS_STRING" - )(); - } - - const ident = - options && typeof options === "object" ? path : undefined; - references.set(ident, options); - result.effects.push({ - type: enforce ? `use-${enforce}` : "use", - value: { - loader, - options, - ident - } - }); - } + ); } ); } - - useItemToEffects(path, item) {} } -module.exports = UseEffectRulePlugin; +module.exports = ConsumeSharedPlugin; /***/ }), -/***/ 63672: +/***/ 10394: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const HelperRuntimeModule = __webpack_require__(82444); - -class AsyncModuleRuntimeModule extends HelperRuntimeModule { - constructor() { - super("async module"); - } +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); +const { + parseVersionRuntimeCode, + versionLtRuntimeCode, + rangeToStringRuntimeCode, + satisfyRuntimeCode +} = __webpack_require__(19702); - /** +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("./ConsumeSharedModule")} ConsumeSharedModule */ + +class ConsumeSharedRuntimeModule extends RuntimeModule { + constructor(runtimeRequirements) { + super("consumes", RuntimeModule.STAGE_ATTACH); + this._runtimeRequirements = runtimeRequirements; + } + + /** * @returns {string} runtime code */ generate() { - const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.asyncModule; + const { compilation, chunkGraph } = this; + const { runtimeTemplate, codeGenerationResults } = compilation; + const chunkToModuleMapping = {}; + /** @type {Map} */ + const moduleIdToSourceMapping = new Map(); + const initialConsumes = []; + /** + * + * @param {Iterable} modules modules + * @param {Chunk} chunk the chunk + * @param {(string | number)[]} list list of ids + */ + const addModules = (modules, chunk, list) => { + for (const m of modules) { + const module = /** @type {ConsumeSharedModule} */ (m); + const id = chunkGraph.getModuleId(module); + list.push(id); + moduleIdToSourceMapping.set( + id, + codeGenerationResults.getSource( + module, + chunk.runtime, + "consume-shared" + ) + ); + } + }; + for (const chunk of this.chunk.getAllAsyncChunks()) { + const modules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "consume-shared" + ); + if (!modules) continue; + addModules(modules, chunk, (chunkToModuleMapping[chunk.id] = [])); + } + for (const chunk of this.chunk.getAllInitialChunks()) { + const modules = chunkGraph.getChunkModulesIterableBySourceType( + chunk, + "consume-shared" + ); + if (!modules) continue; + addModules(modules, chunk, initialConsumes); + } + if (moduleIdToSourceMapping.size === 0) return null; return Template.asString([ - 'var webpackThen = typeof Symbol === "function" ? Symbol("webpack then") : "__webpack_then__";', - 'var webpackExports = typeof Symbol === "function" ? Symbol("webpack exports") : "__webpack_exports__";', - `var completeQueue = ${runtimeTemplate.basicFunction("queue", [ - "if(queue) {", - Template.indent([ - `queue.forEach(${runtimeTemplate.expressionFunction( - "fn.r--", - "fn" - )});`, - `queue.forEach(${runtimeTemplate.expressionFunction( - "fn.r-- ? fn.r++ : fn()", - "fn" - )});` - ]), - "}" - ])}`, - `var completeFunction = ${runtimeTemplate.expressionFunction( - "!--fn.r && fn()", - "fn" + parseVersionRuntimeCode(runtimeTemplate), + versionLtRuntimeCode(runtimeTemplate), + rangeToStringRuntimeCode(runtimeTemplate), + satisfyRuntimeCode(runtimeTemplate), + `var ensureExistence = ${runtimeTemplate.basicFunction("scopeName, key", [ + `var scope = ${RuntimeGlobals.shareScopeMap}[scopeName];`, + `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) throw new Error("Shared module " + key + " doesn't exist in shared scope " + scopeName);`, + "return scope;" + ])};`, + `var findVersion = ${runtimeTemplate.basicFunction("scope, key", [ + "var versions = scope[key];", + `var key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( + "a, b", + ["return !a || versionLt(a, b) ? b : a;"] + )}, 0);`, + "return key && versions[key]" + ])};`, + `var findSingletonVersionKey = ${runtimeTemplate.basicFunction( + "scope, key", + [ + "var versions = scope[key];", + `return Object.keys(versions).reduce(${runtimeTemplate.basicFunction( + "a, b", + ["return !a || (!versions[a].loaded && versionLt(a, b)) ? b : a;"] + )}, 0);` + ] )};`, - `var queueFunction = ${runtimeTemplate.expressionFunction( - "queue ? queue.push(fn) : completeFunction(fn)", - "queue, fn" + `var getInvalidSingletonVersionMessage = ${runtimeTemplate.basicFunction( + "scope, key, version, requiredVersion", + [ + `return "Unsatisfied version " + version + " from " + (version && scope[key][version].from) + " of shared singleton module " + key + " (required " + rangeToString(requiredVersion) + ")"` + ] )};`, - `var wrapDeps = ${runtimeTemplate.returningFunction( - `deps.map(${runtimeTemplate.basicFunction("dep", [ - 'if(dep !== null && typeof dep === "object") {', - Template.indent([ - "if(dep[webpackThen]) return dep;", - "if(dep.then) {", - Template.indent([ - "var queue = [];", - `dep.then(${runtimeTemplate.basicFunction("r", [ - "obj[webpackExports] = r;", - "completeQueue(queue);", - "queue = 0;" - ])});`, - `var obj = {}; - obj[webpackThen] = ${runtimeTemplate.expressionFunction( - "queueFunction(queue, fn), dep['catch'](reject)", - "fn, reject" - )};`, - "return obj;" - ]), - "}" - ]), - "}", - `var ret = {}; - ret[webpackThen] = ${runtimeTemplate.expressionFunction( - "completeFunction(fn)", - "fn" - )}; - ret[webpackExports] = dep; - return ret;` - ])})`, - "deps" + `var getSingleton = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion", + [ + "var version = findSingletonVersionKey(scope, key);", + "return get(scope[key][version]);" + ] )};`, - `${fn} = ${runtimeTemplate.basicFunction("module, body, hasAwait", [ - "var queue = hasAwait && [];", - "var exports = module.exports;", - "var currentDeps;", - "var outerResolve;", - "var reject;", - "var isEvaluating = true;", - "var nested = false;", - `var whenAll = ${runtimeTemplate.basicFunction( - "deps, onResolve, onReject", - [ - "if (nested) return;", - "nested = true;", - "onResolve.r += deps.length;", - `deps.map(${runtimeTemplate.expressionFunction( - "dep[webpackThen](onResolve, onReject)", - "dep, i" - )});`, - "nested = false;" - ] - )};`, - `var promise = new Promise(${runtimeTemplate.basicFunction( - "resolve, rej", - [ - "reject = rej;", - `outerResolve = ${runtimeTemplate.expressionFunction( - "resolve(exports), completeQueue(queue), queue = 0" - )};` - ] - )});`, - "promise[webpackExports] = exports;", - `promise[webpackThen] = ${runtimeTemplate.basicFunction( - "fn, rejectFn", - [ - "if (isEvaluating) { return completeFunction(fn); }", - "if (currentDeps) whenAll(currentDeps, fn, rejectFn);", - "queueFunction(queue, fn);", - "promise['catch'](rejectFn);" - ] - )};`, - "module.exports = promise;", - `body(${runtimeTemplate.basicFunction("deps", [ - "if(!deps) return outerResolve();", - "currentDeps = wrapDeps(deps);", - "var fn, result;", - `var promise = new Promise(${runtimeTemplate.basicFunction( - "resolve, reject", + `var getSingletonVersion = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion", + [ + "var version = findSingletonVersionKey(scope, key);", + "if (!satisfy(requiredVersion, version)) " + + 'typeof console !== "undefined" && console.warn && console.warn(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));', + "return get(scope[key][version]);" + ] + )};`, + `var getStrictSingletonVersion = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion", + [ + "var version = findSingletonVersionKey(scope, key);", + "if (!satisfy(requiredVersion, version)) " + + "throw new Error(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));", + "return get(scope[key][version]);" + ] + )};`, + `var findValidVersion = ${runtimeTemplate.basicFunction( + "scope, key, requiredVersion", + [ + "var versions = scope[key];", + `var key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( + "a, b", [ - `fn = ${runtimeTemplate.expressionFunction( - `resolve(result = currentDeps.map(${runtimeTemplate.returningFunction( - "d[webpackExports]", - "d" - )}))` - )};`, - "fn.r = 0;", - "whenAll(currentDeps, fn, reject);" + "if (!satisfy(requiredVersion, b)) return a;", + "return !a || versionLt(a, b) ? b : a;" ] - )});`, - "return fn.r ? promise : result;" - ])}).then(outerResolve, reject);`, - "isEvaluating = false;" - ])};` - ]); - } -} - -module.exports = AsyncModuleRuntimeModule; - - -/***/ }), - -/***/ 66532: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); -const JavascriptModulesPlugin = __webpack_require__(89464); -const { getUndoPath } = __webpack_require__(82186); - -class AutoPublicPathRuntimeModule extends RuntimeModule { - constructor() { - super("publicPath", RuntimeModule.STAGE_BASIC); - } - - /** - * @returns {string} runtime code - */ - generate() { - const { compilation } = this; - const { scriptType, importMetaName, path } = compilation.outputOptions; - const chunkName = compilation.getPath( - JavascriptModulesPlugin.getChunkFilenameTemplate( - this.chunk, - compilation.outputOptions + )}, 0);`, + "return key && versions[key]" + ] + )};`, + `var getInvalidVersionMessage = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion", + [ + "var versions = scope[key];", + 'return "No satisfying version (" + rangeToString(requiredVersion) + ") of shared module " + key + " found in shared scope " + scopeName + ".\\n" +', + `\t"Available versions: " + Object.keys(versions).map(${runtimeTemplate.basicFunction( + "key", + ['return key + " from " + versions[key].from;'] + )}).join(", ");` + ] + )};`, + `var getValidVersion = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion", + [ + "var entry = findValidVersion(scope, key, requiredVersion);", + "if(entry) return get(entry);", + "throw new Error(getInvalidVersionMessage(scope, scopeName, key, requiredVersion));" + ] + )};`, + `var warnInvalidVersion = ${runtimeTemplate.basicFunction( + "scope, scopeName, key, requiredVersion", + [ + 'typeof console !== "undefined" && console.warn && console.warn(getInvalidVersionMessage(scope, scopeName, key, requiredVersion));' + ] + )};`, + `var get = ${runtimeTemplate.basicFunction("entry", [ + "entry.loaded = 1;", + "return entry.get()" + ])};`, + `var init = ${runtimeTemplate.returningFunction( + Template.asString([ + "function(scopeName, a, b, c) {", + Template.indent([ + `var promise = ${RuntimeGlobals.initializeSharing}(scopeName);`, + `if (promise && promise.then) return promise.then(fn.bind(fn, scopeName, ${RuntimeGlobals.shareScopeMap}[scopeName], a, b, c));`, + `return fn(scopeName, ${RuntimeGlobals.shareScopeMap}[scopeName], a, b, c);` + ]), + "}" + ]), + "fn" + )};`, + "", + `var load = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key", + [ + "ensureExistence(scopeName, key);", + "return get(findVersion(scope, key));" + ] + )});`, + `var loadFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, fallback", + [ + `return scope && ${RuntimeGlobals.hasOwnProperty}(scope, key) ? get(findVersion(scope, key)) : fallback();` + ] + )});`, + `var loadVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version", + [ + "ensureExistence(scopeName, key);", + "return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key));" + ] + )});`, + `var loadSingleton = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key", + [ + "ensureExistence(scopeName, key);", + "return getSingleton(scope, scopeName, key);" + ] + )});`, + `var loadSingletonVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version", + [ + "ensureExistence(scopeName, key);", + "return getSingletonVersion(scope, scopeName, key, version);" + ] + )});`, + `var loadStrictVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version", + [ + "ensureExistence(scopeName, key);", + "return getValidVersion(scope, scopeName, key, version);" + ] + )});`, + `var loadStrictSingletonVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version", + [ + "ensureExistence(scopeName, key);", + "return getStrictSingletonVersion(scope, scopeName, key, version);" + ] + )});`, + `var loadVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version, fallback", + [ + `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, + "return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key));" + ] + )});`, + `var loadSingletonFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, fallback", + [ + `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, + "return getSingleton(scope, scopeName, key);" + ] + )});`, + `var loadSingletonVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version, fallback", + [ + `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, + "return getSingletonVersion(scope, scopeName, key, version);" + ] + )});`, + `var loadStrictVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version, fallback", + [ + `var entry = scope && ${RuntimeGlobals.hasOwnProperty}(scope, key) && findValidVersion(scope, key, version);`, + `return entry ? get(entry) : fallback();` + ] + )});`, + `var loadStrictSingletonVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( + "scopeName, scope, key, version, fallback", + [ + `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, + "return getStrictSingletonVersion(scope, scopeName, key, version);" + ] + )});`, + "var installedModules = {};", + "var moduleToHandlerMapping = {", + Template.indent( + Array.from( + moduleIdToSourceMapping, + ([key, source]) => `${JSON.stringify(key)}: ${source.source()}` + ).join(",\n") ), - { - chunk: this.chunk, - contentHashType: "javascript" - } - ); - const undoPath = getUndoPath(chunkName, path, false); + "};", - return Template.asString([ - "var scriptUrl;", - scriptType === "module" - ? `if (typeof ${importMetaName}.url === "string") scriptUrl = ${importMetaName}.url` - : Template.asString([ - `if (${RuntimeGlobals.global}.importScripts) scriptUrl = ${RuntimeGlobals.global}.location + "";`, - `var document = ${RuntimeGlobals.global}.document;`, - "if (!scriptUrl && document) {", - Template.indent([ - `if (document.currentScript)`, - Template.indent(`scriptUrl = document.currentScript.src`), - "if (!scriptUrl) {", + initialConsumes.length > 0 + ? Template.asString([ + `var initialConsumes = ${JSON.stringify(initialConsumes)};`, + `initialConsumes.forEach(${runtimeTemplate.basicFunction("id", [ + `${ + RuntimeGlobals.moduleFactories + }[id] = ${runtimeTemplate.basicFunction("module", [ + "// Handle case when module is used sync", + "installedModules[id] = 0;", + `delete ${RuntimeGlobals.moduleCache}[id];`, + "var factory = moduleToHandlerMapping[id]();", + 'if(typeof factory !== "function") throw new Error("Shared module is not available for eager consumption: " + id);', + `module.exports = factory();` + ])}` + ])});` + ]) + : "// no consumes in initial chunks", + this._runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) + ? Template.asString([ + `var chunkMapping = ${JSON.stringify( + chunkToModuleMapping, + null, + "\t" + )};`, + `${ + RuntimeGlobals.ensureChunkHandlers + }.consumes = ${runtimeTemplate.basicFunction("chunkId, promises", [ + `if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`, Template.indent([ - 'var scripts = document.getElementsByTagName("script");', - "if(scripts.length) scriptUrl = scripts[scripts.length - 1].src" + `chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction( + "id", + [ + `if(${RuntimeGlobals.hasOwnProperty}(installedModules, id)) return promises.push(installedModules[id]);`, + `var onFactory = ${runtimeTemplate.basicFunction( + "factory", + [ + "installedModules[id] = 0;", + `${ + RuntimeGlobals.moduleFactories + }[id] = ${runtimeTemplate.basicFunction("module", [ + `delete ${RuntimeGlobals.moduleCache}[id];`, + "module.exports = factory();" + ])}` + ] + )};`, + `var onError = ${runtimeTemplate.basicFunction("error", [ + "delete installedModules[id];", + `${ + RuntimeGlobals.moduleFactories + }[id] = ${runtimeTemplate.basicFunction("module", [ + `delete ${RuntimeGlobals.moduleCache}[id];`, + "throw error;" + ])}` + ])};`, + "try {", + Template.indent([ + "var promise = moduleToHandlerMapping[id]();", + "if(promise.then) {", + Template.indent( + "promises.push(installedModules[id] = promise.then(onFactory)['catch'](onError));" + ), + "} else onFactory(promise);" + ]), + "} catch(e) { onError(e); }" + ] + )});` ]), "}" - ]), - "}" - ]), - "// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration", - '// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.', - 'if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");', - 'scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\\?.*$/, "").replace(/\\/[^\\/]+$/, "/");', - !undoPath - ? `${RuntimeGlobals.publicPath} = scriptUrl;` - : `${RuntimeGlobals.publicPath} = scriptUrl + ${JSON.stringify( - undoPath - )};` + ])}` + ]) + : "// no chunk loading of consumes" ]); } } -module.exports = AutoPublicPathRuntimeModule; +module.exports = ConsumeSharedRuntimeModule; /***/ }), -/***/ 84519: +/***/ 40017: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); +const ModuleDependency = __webpack_require__(80321); +const makeSerializable = __webpack_require__(33032); -class ChunkNameRuntimeModule extends RuntimeModule { +class ProvideForSharedDependency extends ModuleDependency { /** - * @param {string} chunkName the chunk's name + * + * @param {string} request request string */ - constructor(chunkName) { - super("chunkName"); - this.chunkName = chunkName; + constructor(request) { + super(request); } - /** - * @returns {string} runtime code - */ - generate() { - return `${RuntimeGlobals.chunkName} = ${JSON.stringify(this.chunkName)};`; + get type() { + return "provide module for shared"; + } + + get category() { + return "esm"; } } -module.exports = ChunkNameRuntimeModule; +makeSerializable( + ProvideForSharedDependency, + "webpack/lib/sharing/ProvideForSharedDependency" +); + +module.exports = ProvideForSharedDependency; /***/ }), -/***/ 44793: +/***/ 1798: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const HelperRuntimeModule = __webpack_require__(82444); +const Dependency = __webpack_require__(54912); +const makeSerializable = __webpack_require__(33032); -class CompatGetDefaultExportRuntimeModule extends HelperRuntimeModule { - constructor() { - super("compat get default export"); +class ProvideSharedDependency extends Dependency { + constructor(shareScope, name, version, request, eager) { + super(); + this.shareScope = shareScope; + this.name = name; + this.version = version; + this.request = request; + this.eager = eager; + } + + get type() { + return "provide shared module"; } /** - * @returns {string} runtime code + * @returns {string | null} an identifier to merge equal requests */ - generate() { - const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.compatGetDefaultExport; - return Template.asString([ - "// getDefaultExport function for compatibility with non-harmony modules", - `${fn} = ${runtimeTemplate.basicFunction("module", [ - "var getter = module && module.__esModule ?", - Template.indent([ - `${runtimeTemplate.returningFunction("module['default']")} :`, - `${runtimeTemplate.returningFunction("module")};` - ]), - `${RuntimeGlobals.definePropertyGetters}(getter, { a: getter });`, - "return getter;" - ])};` - ]); + getResourceIdentifier() { + return `provide module (${this.shareScope}) ${this.request} as ${ + this.name + } @ ${this.version}${this.eager ? " (eager)" : ""}`; + } + + serialize(context) { + context.write(this.shareScope); + context.write(this.name); + context.write(this.request); + context.write(this.version); + context.write(this.eager); + super.serialize(context); + } + + static deserialize(context) { + const { read } = context; + const obj = new ProvideSharedDependency( + read(), + read(), + read(), + read(), + read() + ); + this.shareScope = context.read(); + obj.deserialize(context); + return obj; } } -module.exports = CompatGetDefaultExportRuntimeModule; +makeSerializable( + ProvideSharedDependency, + "webpack/lib/sharing/ProvideSharedDependency" +); + +module.exports = ProvideSharedDependency; /***/ }), -/***/ 88234: +/***/ 50821: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ +const AsyncDependenciesBlock = __webpack_require__(47736); +const Module = __webpack_require__(73208); const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); +const makeSerializable = __webpack_require__(33032); +const ProvideForSharedDependency = __webpack_require__(40017); -/** @typedef {import("../MainTemplate")} MainTemplate */ +/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ +/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ +/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ +/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/Hash")} Hash */ +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ -class CompatRuntimeModule extends RuntimeModule { - constructor() { - super("compat", RuntimeModule.STAGE_ATTACH); - this.fullHash = true; - } +const TYPES = new Set(["share-init"]); +class ProvideSharedModule extends Module { /** - * @returns {string} runtime code + * @param {string} shareScope shared scope name + * @param {string} name shared key + * @param {string | false} version version + * @param {string} request request to the provided module + * @param {boolean} eager include the module in sync way */ - generate() { - const { chunkGraph, chunk, compilation } = this; - const { - runtimeTemplate, - mainTemplate, - moduleTemplates, - dependencyTemplates - } = compilation; - const bootstrap = mainTemplate.hooks.bootstrap.call( - "", - chunk, - compilation.hash || "XXXX", - moduleTemplates.javascript, - dependencyTemplates - ); - const localVars = mainTemplate.hooks.localVars.call( - "", - chunk, - compilation.hash || "XXXX" - ); - const requireExtensions = mainTemplate.hooks.requireExtensions.call( - "", - chunk, - compilation.hash || "XXXX" - ); - const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk); - let requireEnsure = ""; - if (runtimeRequirements.has(RuntimeGlobals.ensureChunk)) { - const requireEnsureHandler = mainTemplate.hooks.requireEnsure.call( - "", - chunk, - compilation.hash || "XXXX", - "chunkId" - ); - if (requireEnsureHandler) { - requireEnsure = `${ - RuntimeGlobals.ensureChunkHandlers - }.compat = ${runtimeTemplate.basicFunction( - "chunkId, promises", - requireEnsureHandler - )};`; - } - } - return [bootstrap, localVars, requireEnsure, requireExtensions] - .filter(Boolean) - .join("\n"); + constructor(shareScope, name, version, request, eager) { + super("provide-module"); + this._shareScope = shareScope; + this._name = name; + this._version = version; + this._request = request; + this._eager = eager; } /** - * @returns {boolean} true, if the runtime module should get it's own scope + * @returns {string} a unique identifier of the module */ - shouldIsolate() { - // We avoid isolating this to have better backward-compat - return false; + identifier() { + return `provide module (${this._shareScope}) ${this._name}@${this._version} = ${this._request}`; } -} - -module.exports = CompatRuntimeModule; - - -/***/ }), - -/***/ 94669: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const HelperRuntimeModule = __webpack_require__(82444); -class CreateFakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { - constructor() { - super("create fake namespace object"); + /** + * @param {RequestShortener} requestShortener the request shortener + * @returns {string} a user readable identifier of the module + */ + readableIdentifier(requestShortener) { + return `provide shared module (${this._shareScope}) ${this._name}@${ + this._version + } = ${requestShortener.shorten(this._request)}`; } /** - * @returns {string} runtime code + * @param {LibIdentOptions} options options + * @returns {string | null} an identifier for library inclusion */ - generate() { - const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.createFakeNamespaceObject; - return Template.asString([ - `var getProto = Object.getPrototypeOf ? ${runtimeTemplate.returningFunction( - "Object.getPrototypeOf(obj)", - "obj" - )} : ${runtimeTemplate.returningFunction("obj.__proto__", "obj")};`, - "var leafPrototypes;", - "// create a fake namespace object", - "// mode & 1: value is a module id, require it", - "// mode & 2: merge all properties of value into the ns", - "// mode & 4: return value when already ns object", - "// mode & 16: return value when it's Promise-like", - "// mode & 8|1: behave like require", - // Note: must be a function (not arrow), because this is used in body! - `${fn} = function(value, mode) {`, - Template.indent([ - `if(mode & 1) value = this(value);`, - `if(mode & 8) return value;`, - "if(typeof value === 'object' && value) {", - Template.indent([ - "if((mode & 4) && value.__esModule) return value;", - "if((mode & 16) && typeof value.then === 'function') return value;" - ]), - "}", - "var ns = Object.create(null);", - `${RuntimeGlobals.makeNamespaceObject}(ns);`, - "var def = {};", - "leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];", - "for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {", - Template.indent([ - `Object.getOwnPropertyNames(current).forEach(${runtimeTemplate.expressionFunction( - `def[key] = ${runtimeTemplate.returningFunction("value[key]", "")}`, - "key" - )});` - ]), - "}", - `def['default'] = ${runtimeTemplate.returningFunction("value", "")};`, - `${RuntimeGlobals.definePropertyGetters}(ns, def);`, - "return ns;" - ]), - "};" - ]); + libIdent(options) { + return `${this.layer ? `(${this.layer})/` : ""}webpack/sharing/provide/${ + this._shareScope + }/${this._name}`; } -} - -module.exports = CreateFakeNamespaceObjectRuntimeModule; - - -/***/ }), - -/***/ 2759: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + /** + * @param {NeedBuildContext} context context info + * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild + * @returns {void} + */ + needBuild(context, callback) { + callback(null, !this.buildInfo); + } + /** + * @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 = { + strict: true + }; -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const HelperRuntimeModule = __webpack_require__(82444); + this.clearDependenciesAndBlocks(); + const dep = new ProvideForSharedDependency(this._request); + if (this._eager) { + this.addDependency(dep); + } else { + const block = new AsyncDependenciesBlock({}); + block.addDependency(dep); + this.addBlock(block); + } -class CreateScriptRuntimeModule extends HelperRuntimeModule { - constructor() { - super("trusted types script"); + callback(); } /** - * @returns {string} runtime code + * @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) */ - generate() { - const { compilation } = this; - const { runtimeTemplate, outputOptions } = compilation; - const { trustedTypes } = outputOptions; - const fn = RuntimeGlobals.createScript; - - return Template.asString( - `${fn} = ${runtimeTemplate.returningFunction( - trustedTypes - ? `${RuntimeGlobals.getTrustedTypesPolicy}().createScript(script)` - : "script", - "script" - )};` - ); + size(type) { + return 42; } -} - -module.exports = CreateScriptRuntimeModule; - - -/***/ }), - -/***/ 21213: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const HelperRuntimeModule = __webpack_require__(82444); -class CreateScriptUrlRuntimeModule extends HelperRuntimeModule { - constructor() { - super("trusted types script url"); + /** + * @returns {Set} types available (do not mutate) + */ + getSourceTypes() { + return TYPES; } /** - * @returns {string} runtime code + * @param {CodeGenerationContext} context context for code generation + * @returns {CodeGenerationResult} result */ - generate() { - const { compilation } = this; - const { runtimeTemplate, outputOptions } = compilation; - const { trustedTypes } = outputOptions; - const fn = RuntimeGlobals.createScriptUrl; + codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { + const runtimeRequirements = new Set([RuntimeGlobals.initializeSharing]); + const code = `register(${JSON.stringify(this._name)}, ${JSON.stringify( + this._version || "0" + )}, ${ + this._eager + ? runtimeTemplate.syncModuleFactory({ + dependency: this.dependencies[0], + chunkGraph, + request: this._request, + runtimeRequirements + }) + : runtimeTemplate.asyncModuleFactory({ + block: this.blocks[0], + chunkGraph, + request: this._request, + runtimeRequirements + }) + }${this._eager ? ", 1" : ""});`; + const sources = new Map(); + const data = new Map(); + data.set("share-init", [ + { + shareScope: this._shareScope, + initStage: 10, + init: code + } + ]); + return { sources, data, runtimeRequirements }; + } - return Template.asString( - `${fn} = ${runtimeTemplate.returningFunction( - trustedTypes - ? `${RuntimeGlobals.getTrustedTypesPolicy}().createScriptURL(url)` - : "url", - "url" - )};` - ); + serialize(context) { + const { write } = context; + write(this._shareScope); + write(this._name); + write(this._version); + write(this._request); + write(this._eager); + super.serialize(context); + } + + static deserialize(context) { + const { read } = context; + const obj = new ProvideSharedModule(read(), read(), read(), read(), read()); + obj.deserialize(context); + return obj; } } -module.exports = CreateScriptUrlRuntimeModule; +makeSerializable( + ProvideSharedModule, + "webpack/lib/sharing/ProvideSharedModule" +); + +module.exports = ProvideSharedModule; /***/ }), -/***/ 75481: +/***/ 39344: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const HelperRuntimeModule = __webpack_require__(82444); +const ModuleFactory = __webpack_require__(51010); +const ProvideSharedModule = __webpack_require__(50821); -class DefinePropertyGettersRuntimeModule extends HelperRuntimeModule { - constructor() { - super("define property getters"); - } +/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ +/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ +/** @typedef {import("./ProvideSharedDependency")} ProvideSharedDependency */ +class ProvideSharedModuleFactory extends ModuleFactory { /** - * @returns {string} runtime code + * @param {ModuleFactoryCreateData} data data object + * @param {function(Error=, ModuleFactoryResult=): void} callback callback + * @returns {void} */ - generate() { - const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.definePropertyGetters; - return Template.asString([ - "// define getter functions for harmony exports", - `${fn} = ${runtimeTemplate.basicFunction("exports, definition", [ - `for(var key in definition) {`, - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(definition, key) && !${RuntimeGlobals.hasOwnProperty}(exports, key)) {`, - Template.indent([ - "Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });" - ]), - "}" - ]), - "}" - ])};` - ]); + create(data, callback) { + const dep = /** @type {ProvideSharedDependency} */ (data.dependencies[0]); + callback(null, { + module: new ProvideSharedModule( + dep.shareScope, + dep.name, + dep.version, + dep.request, + dep.eager + ) + }); } } -module.exports = DefinePropertyGettersRuntimeModule; +module.exports = ProvideSharedModuleFactory; /***/ }), -/***/ 71519: +/***/ 31225: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); +const WebpackError = __webpack_require__(53799); +const { parseOptions } = __webpack_require__(3083); +const createSchemaValidation = __webpack_require__(32540); +const ProvideForSharedDependency = __webpack_require__(40017); +const ProvideSharedDependency = __webpack_require__(1798); +const ProvideSharedModuleFactory = __webpack_require__(39344); -class EnsureChunkRuntimeModule extends RuntimeModule { - constructor(runtimeRequirements) { - super("ensure chunk"); - this.runtimeRequirements = runtimeRequirements; - } +/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvideSharedPluginOptions} ProvideSharedPluginOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ - /** - * @returns {string} runtime code - */ - generate() { - const { runtimeTemplate } = this.compilation; - // Check if there are non initial chunks which need to be imported using require-ensure - if (this.runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers)) { - const handlers = RuntimeGlobals.ensureChunkHandlers; - return Template.asString([ - `${handlers} = {};`, - "// This file contains only the entry chunk.", - "// The chunk loading function for additional chunks", - `${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.basicFunction( - "chunkId", - [ - `return Promise.all(Object.keys(${handlers}).reduce(${runtimeTemplate.basicFunction( - "promises, key", - [`${handlers}[key](chunkId, promises);`, "return promises;"] - )}, []));` - ] - )};` - ]); - } else { - // There ensureChunk is used somewhere in the tree, so we need an empty requireEnsure - // function. This can happen with multiple entrypoints. - return Template.asString([ - "// The chunk loading function for additional chunks", - "// Since all referenced chunks are already included", - "// in this file, this function is empty here.", - `${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.returningFunction( - "Promise.resolve()" - )};` - ]); - } +const validate = createSchemaValidation( + __webpack_require__(91924), + () => __webpack_require__(438), + { + name: "Provide Shared Plugin", + baseDataPath: "options" } -} - -module.exports = EnsureChunkRuntimeModule; - - -/***/ }), - -/***/ 34277: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); -const { first } = __webpack_require__(93347); +); -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("../Compilation").PathData} PathData */ +/** + * @typedef {Object} ProvideOptions + * @property {string} shareKey + * @property {string} shareScope + * @property {string | undefined | false} version + * @property {boolean} eager + */ -/** @typedef {function(PathData, AssetInfo=): string} FilenameFunction */ +/** @typedef {Map} ResolvedProvideMap */ -class GetChunkFilenameRuntimeModule extends RuntimeModule { +class ProvideSharedPlugin { /** - * @param {string} contentType the contentType to use the content hash for - * @param {string} name kind of filename - * @param {string} global function name to be assigned - * @param {function(Chunk): string | FilenameFunction} getFilenameForChunk functor to get the filename or function - * @param {boolean} allChunks when false, only async chunks are included + * @param {ProvideSharedPluginOptions} options options */ - constructor(contentType, name, global, getFilenameForChunk, allChunks) { - super(`get ${name} chunk filename`); - this.contentType = contentType; - this.global = global; - this.getFilenameForChunk = getFilenameForChunk; - this.allChunks = allChunks; - this.dependentHash = true; + constructor(options) { + validate(options); + + /** @type {[string, ProvideOptions][]} */ + this._provides = parseOptions( + options.provides, + item => { + if (Array.isArray(item)) + throw new Error("Unexpected array of provides"); + /** @type {ProvideOptions} */ + const result = { + shareKey: item, + version: undefined, + shareScope: options.shareScope || "default", + eager: false + }; + return result; + }, + item => ({ + shareKey: item.shareKey, + version: item.version, + shareScope: item.shareScope || options.shareScope || "default", + eager: !!item.eager + }) + ); + this._provides.sort(([a], [b]) => { + if (a < b) return -1; + if (b < a) return 1; + return 0; + }); } /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - const { - global, - chunk, - chunkGraph, - contentType, - getFilenameForChunk, - allChunks, - compilation - } = this; - const { runtimeTemplate } = compilation; - - /** @type {Map>} */ - const chunkFilenames = new Map(); - let maxChunks = 0; - /** @type {string} */ - let dynamicFilename; + apply(compiler) { + /** @type {WeakMap} */ + const compilationData = new WeakMap(); - /** - * @param {Chunk} c the chunk - * @returns {void} - */ - const addChunk = c => { - const chunkFilename = getFilenameForChunk(c); - if (chunkFilename) { - let set = chunkFilenames.get(chunkFilename); - if (set === undefined) { - chunkFilenames.set(chunkFilename, (set = new Set())); + compiler.hooks.compilation.tap( + "ProvideSharedPlugin", + (compilation, { normalModuleFactory }) => { + /** @type {ResolvedProvideMap} */ + const resolvedProvideMap = new Map(); + /** @type {Map} */ + const matchProvides = new Map(); + /** @type {Map} */ + const prefixMatchProvides = new Map(); + for (const [request, config] of this._provides) { + if (/^(\/|[A-Za-z]:\\|\\\\|\.\.?(\/|$))/.test(request)) { + // relative request + resolvedProvideMap.set(request, { + config, + version: config.version + }); + } else if (/^(\/|[A-Za-z]:\\|\\\\)/.test(request)) { + // absolute path + resolvedProvideMap.set(request, { + config, + version: config.version + }); + } else if (request.endsWith("/")) { + // module request prefix + prefixMatchProvides.set(request, config); + } else { + // module request + matchProvides.set(request, config); + } } - set.add(c); - if (typeof chunkFilename === "string") { - if (set.size < maxChunks) return; - if (set.size === maxChunks) { - if (chunkFilename.length < dynamicFilename.length) return; - if (chunkFilename.length === dynamicFilename.length) { - if (chunkFilename < dynamicFilename) return; + compilationData.set(compilation, resolvedProvideMap); + const provideSharedModule = ( + key, + config, + resource, + resourceResolveData + ) => { + let version = config.version; + if (version === undefined) { + let details = ""; + if (!resourceResolveData) { + details = `No resolve data provided from resolver.`; + } else { + const descriptionFileData = + resourceResolveData.descriptionFileData; + if (!descriptionFileData) { + details = + "No description file (usually package.json) found. Add description file with name and version, or manually specify version in shared config."; + } else if (!descriptionFileData.version) { + details = + "No version in description file (usually package.json). Add version to description file, or manually specify version in shared config."; + } else { + version = descriptionFileData.version; + } + } + if (!version) { + const error = new WebpackError( + `No version specified and unable to automatically determine one. ${details}` + ); + error.file = `shared module ${key} -> ${resource}`; + compilation.warnings.push(error); } } - maxChunks = set.size; - dynamicFilename = chunkFilename; - } - } - }; - - /** @type {string[]} */ - const includedChunksMessages = []; - if (allChunks) { - includedChunksMessages.push("all chunks"); - for (const c of chunk.getAllReferencedChunks()) { - addChunk(c); - } - } else { - includedChunksMessages.push("async chunks"); - for (const c of chunk.getAllAsyncChunks()) { - addChunk(c); - } - const includeEntries = chunkGraph - .getTreeRuntimeRequirements(chunk) - .has(RuntimeGlobals.ensureChunkIncludeEntries); - if (includeEntries) { - includedChunksMessages.push("sibling chunks for the entrypoint"); - for (const c of chunkGraph.getChunkEntryDependentChunksIterable( - chunk - )) { - addChunk(c); - } - } - } - for (const entrypoint of chunk.getAllReferencedAsyncEntrypoints()) { - addChunk(entrypoint.chunks[entrypoint.chunks.length - 1]); - } - - /** @type {Map>} */ - const staticUrls = new Map(); - /** @type {Set} */ - const dynamicUrlChunks = new Set(); - - /** - * @param {Chunk} c the chunk - * @param {string | FilenameFunction} chunkFilename the filename template for the chunk - * @returns {void} - */ - const addStaticUrl = (c, chunkFilename) => { - /** - * @param {string | number} value a value - * @returns {string} string to put in quotes - */ - const unquotedStringify = value => { - const str = `${value}`; - if (str.length >= 5 && str === `${c.id}`) { - // This is shorter and generates the same result - return '" + chunkId + "'; - } - const s = JSON.stringify(str); - return s.slice(1, s.length - 1); - }; - const unquotedStringifyWithLength = value => length => - unquotedStringify(`${value}`.slice(0, length)); - const chunkFilenameValue = - typeof chunkFilename === "function" - ? JSON.stringify( - chunkFilename({ - chunk: c, - contentHashType: contentType - }) - ) - : JSON.stringify(chunkFilename); - const staticChunkFilename = compilation.getPath(chunkFilenameValue, { - hash: `" + ${RuntimeGlobals.getFullHash}() + "`, - hashWithLength: length => - `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, - chunk: { - id: unquotedStringify(c.id), - hash: unquotedStringify(c.renderedHash), - hashWithLength: unquotedStringifyWithLength(c.renderedHash), - name: unquotedStringify(c.name || c.id), - contentHash: { - [contentType]: unquotedStringify(c.contentHash[contentType]) - }, - contentHashWithLength: { - [contentType]: unquotedStringifyWithLength( - c.contentHash[contentType] - ) + resolvedProvideMap.set(resource, { + config, + version + }); + }; + normalModuleFactory.hooks.module.tap( + "ProvideSharedPlugin", + (module, { resource, resourceResolveData }, resolveData) => { + if (resolvedProvideMap.has(resource)) { + return module; + } + const { request } = resolveData; + { + const config = matchProvides.get(request); + if (config !== undefined) { + provideSharedModule( + request, + config, + resource, + resourceResolveData + ); + resolveData.cacheable = false; + } + } + for (const [prefix, config] of prefixMatchProvides) { + if (request.startsWith(prefix)) { + const remainder = request.slice(prefix.length); + provideSharedModule( + resource, + { + ...config, + shareKey: config.shareKey + remainder + }, + resource, + resourceResolveData + ); + resolveData.cacheable = false; + } + } + return module; } - }, - contentHashType: contentType - }); - let set = staticUrls.get(staticChunkFilename); - if (set === undefined) { - staticUrls.set(staticChunkFilename, (set = new Set())); + ); } - set.add(c.id); - }; + ); + compiler.hooks.finishMake.tapPromise("ProvideSharedPlugin", compilation => { + const resolvedProvideMap = compilationData.get(compilation); + if (!resolvedProvideMap) return Promise.resolve(); + return Promise.all( + Array.from( + resolvedProvideMap, + ([resource, { config, version }]) => + new Promise((resolve, reject) => { + compilation.addInclude( + compiler.context, + new ProvideSharedDependency( + config.shareScope, + config.shareKey, + version || false, + resource, + config.eager + ), + { + name: undefined + }, + err => { + if (err) return reject(err); + resolve(); + } + ); + }) + ) + ).then(() => {}); + }); - for (const [filename, chunks] of chunkFilenames) { - if (filename !== dynamicFilename) { - for (const c of chunks) addStaticUrl(c, filename); - } else { - for (const c of chunks) dynamicUrlChunks.add(c); - } - } + compiler.hooks.compilation.tap( + "ProvideSharedPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + ProvideForSharedDependency, + normalModuleFactory + ); - /** - * @param {function(Chunk): string | number} fn function from chunk to value - * @returns {string} code with static mapping of results of fn - */ - const createMap = fn => { - const obj = {}; - let useId = false; - let lastKey; - let entries = 0; - for (const c of dynamicUrlChunks) { - const value = fn(c); - if (value === c.id) { - useId = true; - } else { - obj[c.id] = value; - lastKey = c.id; - entries++; - } - } - if (entries === 0) return "chunkId"; - if (entries === 1) { - return useId - ? `(chunkId === ${JSON.stringify(lastKey)} ? ${JSON.stringify( - obj[lastKey] - )} : chunkId)` - : JSON.stringify(obj[lastKey]); + compilation.dependencyFactories.set( + ProvideSharedDependency, + new ProvideSharedModuleFactory() + ); } - return useId - ? `(${JSON.stringify(obj)}[chunkId] || chunkId)` - : `${JSON.stringify(obj)}[chunkId]`; - }; - - /** - * @param {function(Chunk): string | number} fn function from chunk to value - * @returns {string} code with static mapping of results of fn for including in quoted string - */ - const mapExpr = fn => { - return `" + ${createMap(fn)} + "`; - }; - - /** - * @param {function(Chunk): string | number} fn function from chunk to value - * @returns {function(number): string} function which generates code with static mapping of results of fn for including in quoted string for specific length - */ - const mapExprWithLength = fn => length => { - return `" + ${createMap(c => `${fn(c)}`.slice(0, length))} + "`; - }; - - const url = - dynamicFilename && - compilation.getPath(JSON.stringify(dynamicFilename), { - hash: `" + ${RuntimeGlobals.getFullHash}() + "`, - hashWithLength: length => - `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, - chunk: { - id: `" + chunkId + "`, - hash: mapExpr(c => c.renderedHash), - hashWithLength: mapExprWithLength(c => c.renderedHash), - name: mapExpr(c => c.name || c.id), - contentHash: { - [contentType]: mapExpr(c => c.contentHash[contentType]) - }, - contentHashWithLength: { - [contentType]: mapExprWithLength(c => c.contentHash[contentType]) - } - }, - contentHashType: contentType - }); - - return Template.asString([ - `// This function allow to reference ${includedChunksMessages.join( - " and " - )}`, - `${global} = ${runtimeTemplate.basicFunction( - "chunkId", - - staticUrls.size > 0 - ? [ - "// return url for filenames not based on template", - // it minimizes to `x===1?"...":x===2?"...":"..."` - Template.asString( - Array.from(staticUrls, ([url, ids]) => { - const condition = - ids.size === 1 - ? `chunkId === ${JSON.stringify(first(ids))}` - : `{${Array.from( - ids, - id => `${JSON.stringify(id)}:1` - ).join(",")}}[chunkId]`; - return `if (${condition}) return ${url};`; - }) - ), - "// return url for filenames based on template", - `return ${url};` - ] - : ["// return url for filenames based on template", `return ${url};`] - )};` - ]); + ); } } -module.exports = GetChunkFilenameRuntimeModule; +module.exports = ProvideSharedPlugin; /***/ }), -/***/ 88732: +/***/ 26335: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); +const { parseOptions } = __webpack_require__(3083); +const ConsumeSharedPlugin = __webpack_require__(15046); +const ProvideSharedPlugin = __webpack_require__(31225); +const { isRequiredVersion } = __webpack_require__(84379); -/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumeSharedPluginOptions} ConsumeSharedPluginOptions */ +/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumesConfig} ConsumesConfig */ +/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvideSharedPluginOptions} ProvideSharedPluginOptions */ +/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvidesConfig} ProvidesConfig */ +/** @typedef {import("../../declarations/plugins/sharing/SharePlugin").SharePluginOptions} SharePluginOptions */ +/** @typedef {import("../../declarations/plugins/sharing/SharePlugin").SharedConfig} SharedConfig */ +/** @typedef {import("../Compiler")} Compiler */ -class GetFullHashRuntimeModule extends RuntimeModule { - constructor() { - super("getFullHash"); - this.fullHash = true; +class SharePlugin { + /** + * @param {SharePluginOptions} options options + */ + constructor(options) { + /** @type {[string, SharedConfig][]} */ + const sharedOptions = parseOptions( + options.shared, + (item, key) => { + if (typeof item !== "string") + throw new Error("Unexpected array in shared"); + /** @type {SharedConfig} */ + const config = + item === key || !isRequiredVersion(item) + ? { + import: item + } + : { + import: key, + requiredVersion: item + }; + return config; + }, + item => item + ); + /** @type {Record[]} */ + const consumes = sharedOptions.map(([key, options]) => ({ + [key]: { + import: options.import, + shareKey: options.shareKey || key, + shareScope: options.shareScope, + requiredVersion: options.requiredVersion, + strictVersion: options.strictVersion, + singleton: options.singleton, + packageName: options.packageName, + eager: options.eager + } + })); + /** @type {Record[]} */ + const provides = sharedOptions + .filter(([, options]) => options.import !== false) + .map(([key, options]) => ({ + [options.import || key]: { + shareKey: options.shareKey || key, + shareScope: options.shareScope, + version: options.version, + eager: options.eager + } + })); + this._shareScope = options.shareScope; + this._consumes = consumes; + this._provides = provides; } /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - const { runtimeTemplate } = this.compilation; - return `${RuntimeGlobals.getFullHash} = ${runtimeTemplate.returningFunction( - JSON.stringify(this.compilation.hash || "XXXX") - )}`; + apply(compiler) { + new ConsumeSharedPlugin({ + shareScope: this._shareScope, + consumes: this._consumes + }).apply(compiler); + new ProvideSharedPlugin({ + shareScope: this._shareScope, + provides: this._provides + }).apply(compiler); } } -module.exports = GetFullHashRuntimeModule; +module.exports = SharePlugin; /***/ }), -/***/ 10029: +/***/ 96066: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ const RuntimeGlobals = __webpack_require__(16475); const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); - -/** @typedef {import("../Compilation")} Compilation */ +const Template = __webpack_require__(1626); +const { + compareModulesByIdentifier, + compareStrings +} = __webpack_require__(29579); -class GetMainFilenameRuntimeModule extends RuntimeModule { - /** - * @param {string} name readable name - * @param {string} global global object binding - * @param {string} filename main file name - */ - constructor(name, global, filename) { - super(`get ${name} filename`); - this.global = global; - this.filename = filename; +class ShareRuntimeModule extends RuntimeModule { + constructor() { + super("sharing"); } /** * @returns {string} runtime code */ generate() { - const { global, filename, compilation, chunk } = this; - const { runtimeTemplate } = compilation; - const url = compilation.getPath(JSON.stringify(filename), { - hash: `" + ${RuntimeGlobals.getFullHash}() + "`, - hashWithLength: length => - `" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`, - chunk, - runtime: chunk.runtime - }); + const { compilation, chunkGraph } = this; + const { + runtimeTemplate, + codeGenerationResults, + outputOptions: { uniqueName } + } = compilation; + /** @type {Map>>} */ + const initCodePerScope = new Map(); + for (const chunk of this.chunk.getAllReferencedChunks()) { + const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( + chunk, + "share-init", + compareModulesByIdentifier + ); + if (!modules) continue; + for (const m of modules) { + const data = codeGenerationResults.getData( + m, + chunk.runtime, + "share-init" + ); + if (!data) continue; + for (const item of data) { + const { shareScope, initStage, init } = item; + let stages = initCodePerScope.get(shareScope); + if (stages === undefined) { + initCodePerScope.set(shareScope, (stages = new Map())); + } + let list = stages.get(initStage || 0); + if (list === undefined) { + stages.set(initStage || 0, (list = new Set())); + } + list.add(init); + } + } + } return Template.asString([ - `${global} = ${runtimeTemplate.returningFunction(url)};` + `${RuntimeGlobals.shareScopeMap} = {};`, + "var initPromises = {};", + "var initTokens = {};", + `${RuntimeGlobals.initializeSharing} = ${runtimeTemplate.basicFunction( + "name, initScope", + [ + "if(!initScope) initScope = [];", + "// handling circular init calls", + "var initToken = initTokens[name];", + "if(!initToken) initToken = initTokens[name] = {};", + "if(initScope.indexOf(initToken) >= 0) return;", + "initScope.push(initToken);", + "// only runs once", + "if(initPromises[name]) return initPromises[name];", + "// creates a new share scope if needed", + `if(!${RuntimeGlobals.hasOwnProperty}(${RuntimeGlobals.shareScopeMap}, name)) ${RuntimeGlobals.shareScopeMap}[name] = {};`, + "// runs all init snippets from all modules reachable", + `var scope = ${RuntimeGlobals.shareScopeMap}[name];`, + `var warn = ${runtimeTemplate.returningFunction( + 'typeof console !== "undefined" && console.warn && console.warn(msg)', + "msg" + )};`, + `var uniqueName = ${JSON.stringify(uniqueName || undefined)};`, + `var register = ${runtimeTemplate.basicFunction( + "name, version, factory, eager", + [ + "var versions = scope[name] = scope[name] || {};", + "var activeVersion = versions[version];", + "if(!activeVersion || (!activeVersion.loaded && (!eager != !activeVersion.eager ? eager : uniqueName > activeVersion.from))) versions[version] = { get: factory, from: uniqueName, eager: !!eager };" + ] + )};`, + `var initExternal = ${runtimeTemplate.basicFunction("id", [ + `var handleError = ${runtimeTemplate.expressionFunction( + 'warn("Initialization of sharing external failed: " + err)', + "err" + )};`, + "try {", + Template.indent([ + "var module = __webpack_require__(id);", + "if(!module) return;", + `var initFn = ${runtimeTemplate.returningFunction( + `module && module.init && module.init(${RuntimeGlobals.shareScopeMap}[name], initScope)`, + "module" + )}`, + "if(module.then) return promises.push(module.then(initFn, handleError));", + "var initResult = initFn(module);", + "if(initResult && initResult.then) return promises.push(initResult['catch'](handleError));" + ]), + "} catch(err) { handleError(err); }" + ])}`, + "var promises = [];", + "switch(name) {", + ...Array.from(initCodePerScope) + .sort(([a], [b]) => compareStrings(a, b)) + .map(([name, stages]) => + Template.indent([ + `case ${JSON.stringify(name)}: {`, + Template.indent( + Array.from(stages) + .sort(([a], [b]) => a - b) + .map(([, initCode]) => + Template.asString(Array.from(initCode)) + ) + ), + "}", + "break;" + ]) + ), + "}", + "if(!promises.length) return initPromises[name] = 1;", + `return initPromises[name] = Promise.all(promises).then(${runtimeTemplate.returningFunction( + "initPromises[name] = 1" + )});` + ] + )};` ]); } } -module.exports = GetMainFilenameRuntimeModule; +module.exports = ShareRuntimeModule; /***/ }), -/***/ 38713: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 3591: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const HelperRuntimeModule = __webpack_require__(82444); +const ModuleNotFoundError = __webpack_require__(32882); +const LazySet = __webpack_require__(38938); -class GetTrustedTypesPolicyRuntimeModule extends HelperRuntimeModule { - /** - * @param {Set} runtimeRequirements runtime requirements - */ - constructor(runtimeRequirements) { - super("trusted types policy"); - this.runtimeRequirements = runtimeRequirements; - } +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */ - /** - * @returns {string} runtime code - */ - generate() { - const { compilation } = this; - const { runtimeTemplate, outputOptions } = compilation; - const { trustedTypes } = outputOptions; - const fn = RuntimeGlobals.getTrustedTypesPolicy; +/** + * @template T + * @typedef {Object} MatchedConfigs + * @property {Map} resolved + * @property {Map} unresolved + * @property {Map} prefixed + */ - return Template.asString([ - "var policy;", - `${fn} = ${runtimeTemplate.basicFunction("", [ - "// Create Trusted Type policy if Trusted Types are available and the policy doesn't exist yet.", - "if (policy === undefined) {", - Template.indent([ - "policy = {", - Template.indent( - [ - ...(this.runtimeRequirements.has(RuntimeGlobals.createScript) - ? [ - `createScript: ${runtimeTemplate.returningFunction( - "script", - "script" - )}` - ] - : []), - ...(this.runtimeRequirements.has(RuntimeGlobals.createScriptUrl) - ? [ - `createScriptURL: ${runtimeTemplate.returningFunction( - "url", - "url" - )}` - ] - : []) - ].join(",\n") - ), - "};", - ...(trustedTypes - ? [ - 'if (typeof trustedTypes !== "undefined" && trustedTypes.createPolicy) {', - Template.indent([ - `policy = trustedTypes.createPolicy(${JSON.stringify( - trustedTypes.policyName - )}, policy);` - ]), - "}" - ] - : []) - ]), - "}", - "return policy;" - ])};` - ]); - } -} +/** @type {ResolveOptionsWithDependencyType} */ +const RESOLVE_OPTIONS = { dependencyType: "esm" }; -module.exports = GetTrustedTypesPolicyRuntimeModule; +/** + * @template T + * @param {Compilation} compilation the compilation + * @param {[string, T][]} configs to be processed configs + * @returns {Promise>} resolved matchers + */ +exports.resolveMatchedConfigs = (compilation, configs) => { + /** @type {Map} */ + const resolved = new Map(); + /** @type {Map} */ + const unresolved = new Map(); + /** @type {Map} */ + const prefixed = new Map(); + const resolveContext = { + /** @type {LazySet} */ + fileDependencies: new LazySet(), + /** @type {LazySet} */ + contextDependencies: new LazySet(), + /** @type {LazySet} */ + missingDependencies: new LazySet() + }; + const resolver = compilation.resolverFactory.get("normal", RESOLVE_OPTIONS); + const context = compilation.compiler.context; + + return Promise.all( + configs.map(([request, config]) => { + if (/^\.\.?(\/|$)/.test(request)) { + // relative request + return new Promise(resolve => { + resolver.resolve( + {}, + context, + request, + resolveContext, + (err, result) => { + if (err || result === false) { + err = err || new Error(`Can't resolve ${request}`); + compilation.errors.push( + new ModuleNotFoundError(null, err, { + name: `shared module ${request}` + }) + ); + return resolve(); + } + resolved.set(result, config); + resolve(); + } + ); + }); + } else if (/^(\/|[A-Za-z]:\\|\\\\)/.test(request)) { + // absolute path + resolved.set(request, config); + } else if (request.endsWith("/")) { + // module request prefix + prefixed.set(request, config); + } else { + // module request + unresolved.set(request, config); + } + }) + ).then(() => { + compilation.contextDependencies.addAll(resolveContext.contextDependencies); + compilation.fileDependencies.addAll(resolveContext.fileDependencies); + compilation.missingDependencies.addAll(resolveContext.missingDependencies); + return { resolved, unresolved, prefixed }; + }); +}; /***/ }), -/***/ 23255: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 84379: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); +const { join, dirname, readJson } = __webpack_require__(17139); -class GlobalRuntimeModule extends RuntimeModule { - constructor() { - super("global"); - } +/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ - /** - * @returns {string} runtime code - */ - generate() { - return Template.asString([ - `${RuntimeGlobals.global} = (function() {`, - Template.indent([ - "if (typeof globalThis === 'object') return globalThis;", - "try {", - Template.indent( - // This works in non-strict mode - // or - // This works if eval is allowed (see CSP) - "return this || new Function('return this')();" - ), - "} catch (e) {", - Template.indent( - // This works if the window reference is available - "if (typeof window === 'object') return window;" - ), - "}" - // It can still be `undefined`, but nothing to do about it... - // We return `undefined`, instead of nothing here, so it's - // easier to handle this case: - // if (!global) { … } - ]), - "})();" - ]); - } -} +/** + * @param {string} str maybe required version + * @returns {boolean} true, if it looks like a version + */ +exports.isRequiredVersion = str => { + return /^([\d^=v<>~]|[*xX]$)/.test(str); +}; -module.exports = GlobalRuntimeModule; +/** + * + * @param {InputFileSystem} fs file system + * @param {string} directory directory to start looking into + * @param {string[]} descriptionFiles possible description filenames + * @param {function((Error | null)=, {data: object, path: string}=): void} callback callback + */ +const getDescriptionFile = (fs, directory, descriptionFiles, callback) => { + let i = 0; + const tryLoadCurrent = () => { + if (i >= descriptionFiles.length) { + const parentDirectory = dirname(fs, directory); + if (!parentDirectory || parentDirectory === directory) return callback(); + return getDescriptionFile( + fs, + parentDirectory, + descriptionFiles, + callback + ); + } + const filePath = join(fs, directory, descriptionFiles[i]); + readJson(fs, filePath, (err, data) => { + if (err) { + if ("code" in err && err.code === "ENOENT") { + i++; + return tryLoadCurrent(); + } + return callback(err); + } + if (!data || typeof data !== "object" || Array.isArray(data)) { + return callback( + new Error(`Description file ${filePath} is not an object`) + ); + } + callback(null, { data, path: filePath }); + }); + }; + tryLoadCurrent(); +}; +exports.getDescriptionFile = getDescriptionFile; + +exports.getRequiredVersionFromDescriptionFile = (data, packageName) => { + if ( + data.optionalDependencies && + typeof data.optionalDependencies === "object" && + packageName in data.optionalDependencies + ) { + return data.optionalDependencies[packageName]; + } + if ( + data.dependencies && + typeof data.dependencies === "object" && + packageName in data.dependencies + ) { + return data.dependencies[packageName]; + } + if ( + data.peerDependencies && + typeof data.peerDependencies === "object" && + packageName in data.peerDependencies + ) { + return data.peerDependencies[packageName]; + } + if ( + data.devDependencies && + typeof data.devDependencies === "object" && + packageName in data.devDependencies + ) { + return data.devDependencies[packageName]; + } +}; /***/ }), -/***/ 8011: +/***/ 71760: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sergey Melyukov @smelukov + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); - -class HasOwnPropertyRuntimeModule extends RuntimeModule { - constructor() { - super("hasOwnProperty shorthand"); - } - - /** - * @returns {string} runtime code - */ - generate() { - const { runtimeTemplate } = this.compilation; - - return Template.asString([ - `${RuntimeGlobals.hasOwnProperty} = ${runtimeTemplate.returningFunction( - "Object.prototype.hasOwnProperty.call(obj, prop)", - "obj, prop" - )}` - ]); - } -} - -module.exports = HasOwnPropertyRuntimeModule; - - -/***/ }), - -/***/ 82444: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeModule = __webpack_require__(16963); - -class HelperRuntimeModule extends RuntimeModule { - /** - * @param {string} name a readable name - */ - constructor(name) { - super(name); - } -} - -module.exports = HelperRuntimeModule; - - -/***/ }), - -/***/ 19942: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const { SyncWaterfallHook } = __webpack_require__(41242); -const Compilation = __webpack_require__(85720); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const HelperRuntimeModule = __webpack_require__(82444); +const util = __webpack_require__(73837); +const ModuleDependency = __webpack_require__(80321); +const formatLocation = __webpack_require__(16734); +const { LogType } = __webpack_require__(32597); +const AggressiveSplittingPlugin = __webpack_require__(15543); +const SizeLimitsPlugin = __webpack_require__(32557); +const { countIterable } = __webpack_require__(39104); +const { + compareLocations, + compareChunksById, + compareNumbers, + compareIds, + concatComparators, + compareSelect, + compareModulesByIdentifier +} = __webpack_require__(29579); +const { makePathsRelative, parseResource } = __webpack_require__(82186); +/** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../ChunkGroup").OriginRecord} OriginRecord */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").Asset} Asset */ +/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ +/** @typedef {import("../Compilation").NormalizedStatsOptions} NormalizedStatsOptions */ /** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ +/** @typedef {import("../ModuleProfile")} ModuleProfile */ +/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @template T @typedef {import("../util/comparators").Comparator} Comparator */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("../util/smartGrouping").GroupConfig} GroupConfig */ +/** @typedef {import("./StatsFactory")} StatsFactory */ +/** @typedef {import("./StatsFactory").StatsFactoryContext} StatsFactoryContext */ +/** @typedef {KnownStatsCompilation & Record} StatsCompilation */ /** - * @typedef {Object} LoadScriptCompilationHooks - * @property {SyncWaterfallHook<[string, Chunk]>} createScript + * @typedef {Object} KnownStatsCompilation + * @property {any=} env + * @property {string=} name + * @property {string=} hash + * @property {string=} version + * @property {number=} time + * @property {number=} builtAt + * @property {boolean=} needAdditionalPass + * @property {string=} publicPath + * @property {string=} outputPath + * @property {Record=} assetsByChunkName + * @property {StatsAsset[]=} assets + * @property {number=} filteredAssets + * @property {StatsChunk[]=} chunks + * @property {StatsModule[]=} modules + * @property {number=} filteredModules + * @property {Record=} entrypoints + * @property {Record=} namedChunkGroups + * @property {StatsError[]=} errors + * @property {number=} errorsCount + * @property {StatsError[]=} warnings + * @property {number=} warningsCount + * @property {StatsCompilation[]=} children + * @property {Record=} logging */ -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); +/** @typedef {KnownStatsLogging & Record} StatsLogging */ +/** + * @typedef {Object} KnownStatsLogging + * @property {StatsLoggingEntry[]} entries + * @property {number} filteredEntries + * @property {boolean} debug + */ -class LoadScriptRuntimeModule extends HelperRuntimeModule { - /** - * @param {Compilation} compilation the compilation - * @returns {LoadScriptCompilationHooks} 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 = { - createScript: new SyncWaterfallHook(["source", "chunk"]) - }; - compilationHooksMap.set(compilation, hooks); - } - return hooks; - } +/** @typedef {KnownStatsLoggingEntry & Record} StatsLoggingEntry */ +/** + * @typedef {Object} KnownStatsLoggingEntry + * @property {string} type + * @property {string} message + * @property {string[]=} trace + * @property {StatsLoggingEntry[]=} children + * @property {any[]=} args + * @property {number=} time + */ - /** - * @param {boolean=} withCreateScriptUrl use create script url for trusted types - */ - constructor(withCreateScriptUrl) { - super("load script"); - this._withCreateScriptUrl = withCreateScriptUrl; - } +/** @typedef {KnownStatsAsset & Record} StatsAsset */ +/** + * @typedef {Object} KnownStatsAsset + * @property {string} type + * @property {string} name + * @property {AssetInfo} info + * @property {number} size + * @property {boolean} emitted + * @property {boolean} comparedForEmit + * @property {boolean} cached + * @property {StatsAsset[]=} related + * @property {(string|number)[]=} chunkNames + * @property {(string|number)[]=} chunkIdHints + * @property {(string|number)[]=} chunks + * @property {(string|number)[]=} auxiliaryChunkNames + * @property {(string|number)[]=} auxiliaryChunks + * @property {(string|number)[]=} auxiliaryChunkIdHints + * @property {number=} filteredRelated + * @property {boolean=} isOverSizeLimit + */ - /** - * @returns {string} runtime code - */ - generate() { - const { compilation } = this; - const { runtimeTemplate, outputOptions } = compilation; - const { - scriptType, - chunkLoadTimeout: loadTimeout, - crossOriginLoading, - uniqueName, - charset - } = outputOptions; - const fn = RuntimeGlobals.loadScript; +/** @typedef {KnownStatsChunkGroup & Record} StatsChunkGroup */ +/** + * @typedef {Object} KnownStatsChunkGroup + * @property {string=} name + * @property {(string|number)[]=} chunks + * @property {({ name: string, size?: number })[]=} assets + * @property {number=} filteredAssets + * @property {number=} assetsSize + * @property {({ name: string, size?: number })[]=} auxiliaryAssets + * @property {number=} filteredAuxiliaryAssets + * @property {number=} auxiliaryAssetsSize + * @property {{ [x: string]: StatsChunkGroup[] }=} children + * @property {{ [x: string]: string[] }=} childAssets + * @property {boolean=} isOverSizeLimit + */ - const { createScript } = - LoadScriptRuntimeModule.getCompilationHooks(compilation); +/** @typedef {KnownStatsModule & Record} StatsModule */ +/** + * @typedef {Object} KnownStatsModule + * @property {string=} type + * @property {string=} moduleType + * @property {string=} layer + * @property {string=} identifier + * @property {string=} name + * @property {string=} nameForCondition + * @property {number=} index + * @property {number=} preOrderIndex + * @property {number=} index2 + * @property {number=} postOrderIndex + * @property {number=} size + * @property {{[x: string]: number}=} sizes + * @property {boolean=} cacheable + * @property {boolean=} built + * @property {boolean=} codeGenerated + * @property {boolean=} buildTimeExecuted + * @property {boolean=} cached + * @property {boolean=} optional + * @property {boolean=} orphan + * @property {string|number=} id + * @property {string|number=} issuerId + * @property {(string|number)[]=} chunks + * @property {(string|number)[]=} assets + * @property {boolean=} dependent + * @property {string=} issuer + * @property {string=} issuerName + * @property {StatsModuleIssuer[]=} issuerPath + * @property {boolean=} failed + * @property {number=} errors + * @property {number=} warnings + * @property {StatsProfile=} profile + * @property {StatsModuleReason[]=} reasons + * @property {(boolean | string[])=} usedExports + * @property {string[]=} providedExports + * @property {string[]=} optimizationBailout + * @property {number=} depth + * @property {StatsModule[]=} modules + * @property {number=} filteredModules + * @property {ReturnType=} source + */ - const code = Template.asString([ - "script = document.createElement('script');", - scriptType ? `script.type = ${JSON.stringify(scriptType)};` : "", - charset ? "script.charset = 'utf-8';" : "", - `script.timeout = ${loadTimeout / 1000};`, - `if (${RuntimeGlobals.scriptNonce}) {`, - Template.indent( - `script.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` - ), - "}", - uniqueName - ? 'script.setAttribute("data-webpack", dataWebpackPrefix + key);' - : "", - `script.src = ${ - this._withCreateScriptUrl - ? `${RuntimeGlobals.createScriptUrl}(url)` - : "url" - };`, - crossOriginLoading - ? Template.asString([ - "if (script.src.indexOf(window.location.origin + '/') !== 0) {", - Template.indent( - `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` - ), - "}" - ]) - : "" - ]); +/** @typedef {KnownStatsProfile & Record} StatsProfile */ +/** + * @typedef {Object} KnownStatsProfile + * @property {number} total + * @property {number} resolving + * @property {number} restoring + * @property {number} building + * @property {number} integration + * @property {number} storing + * @property {number} additionalResolving + * @property {number} additionalIntegration + * @property {number} factory + * @property {number} dependencies + */ - return Template.asString([ - "var inProgress = {};", - uniqueName - ? `var dataWebpackPrefix = ${JSON.stringify(uniqueName + ":")};` - : "// data-webpack is not used as build has no uniqueName", - "// loadScript function to load a script via script tag", - `${fn} = ${runtimeTemplate.basicFunction("url, done, key, chunkId", [ - "if(inProgress[url]) { inProgress[url].push(done); return; }", - "var script, needAttach;", - "if(key !== undefined) {", - Template.indent([ - 'var scripts = document.getElementsByTagName("script");', - "for(var i = 0; i < scripts.length; i++) {", - Template.indent([ - "var s = scripts[i];", - `if(s.getAttribute("src") == url${ - uniqueName - ? ' || s.getAttribute("data-webpack") == dataWebpackPrefix + key' - : "" - }) { script = s; break; }` - ]), - "}" - ]), - "}", - "if(!script) {", - Template.indent([ - "needAttach = true;", - createScript.call(code, this.chunk) - ]), - "}", - "inProgress[url] = [done];", - "var onScriptComplete = " + - runtimeTemplate.basicFunction( - "prev, event", - Template.asString([ - "// avoid mem leaks in IE.", - "script.onerror = script.onload = null;", - "clearTimeout(timeout);", - "var doneFns = inProgress[url];", - "delete inProgress[url];", - "script.parentNode && script.parentNode.removeChild(script);", - `doneFns && doneFns.forEach(${runtimeTemplate.returningFunction( - "fn(event)", - "fn" - )});`, - "if(prev) return prev(event);" - ]) - ), - ";", - `var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), ${loadTimeout});`, - "script.onerror = onScriptComplete.bind(null, script.onerror);", - "script.onload = onScriptComplete.bind(null, script.onload);", - "needAttach && document.head.appendChild(script);" - ])};` - ]); - } -} +/** @typedef {KnownStatsModuleIssuer & Record} StatsModuleIssuer */ +/** + * @typedef {Object} KnownStatsModuleIssuer + * @property {string=} identifier + * @property {string=} name + * @property {(string|number)=} id + * @property {StatsProfile=} profile + */ -module.exports = LoadScriptRuntimeModule; +/** @typedef {KnownStatsModuleReason & Record} StatsModuleReason */ +/** + * @typedef {Object} KnownStatsModuleReason + * @property {string=} moduleIdentifier + * @property {string=} module + * @property {string=} moduleName + * @property {string=} resolvedModuleIdentifier + * @property {string=} resolvedModule + * @property {string=} type + * @property {boolean} active + * @property {string=} explanation + * @property {string=} userRequest + * @property {string=} loc + * @property {(string|number)=} moduleId + * @property {(string|number)=} resolvedModuleId + */ +/** @typedef {KnownStatsChunk & Record} StatsChunk */ +/** + * @typedef {Object} KnownStatsChunk + * @property {boolean} rendered + * @property {boolean} initial + * @property {boolean} entry + * @property {boolean} recorded + * @property {string=} reason + * @property {number} size + * @property {Record=} sizes + * @property {string[]=} names + * @property {string[]=} idHints + * @property {string[]=} runtime + * @property {string[]=} files + * @property {string[]=} auxiliaryFiles + * @property {string} hash + * @property {Record=} childrenByOrder + * @property {(string|number)=} id + * @property {(string|number)[]=} siblings + * @property {(string|number)[]=} parents + * @property {(string|number)[]=} children + * @property {StatsModule[]=} modules + * @property {number=} filteredModules + * @property {StatsChunkOrigin[]=} origins + */ -/***/ }), +/** @typedef {KnownStatsChunkOrigin & Record} StatsChunkOrigin */ +/** + * @typedef {Object} KnownStatsChunkOrigin + * @property {string=} module + * @property {string=} moduleIdentifier + * @property {string=} moduleName + * @property {string=} loc + * @property {string=} request + * @property {(string|number)=} moduleId + */ -/***/ 65714: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** @typedef {KnownStatsModuleTraceItem & Record} StatsModuleTraceItem */ +/** + * @typedef {Object} KnownStatsModuleTraceItem + * @property {string=} originIdentifier + * @property {string=} originName + * @property {string=} moduleIdentifier + * @property {string=} moduleName + * @property {StatsModuleTraceDependency[]=} dependencies + * @property {(string|number)=} originId + * @property {(string|number)=} moduleId + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ +/** @typedef {KnownStatsModuleTraceDependency & Record} StatsModuleTraceDependency */ +/** + * @typedef {Object} KnownStatsModuleTraceDependency + * @property {string=} loc + */ +/** @typedef {KnownStatsError & Record} StatsError */ +/** + * @typedef {Object} KnownStatsError + * @property {string} message + * @property {string=} chunkName + * @property {boolean=} chunkEntry + * @property {boolean=} chunkInitial + * @property {string=} file + * @property {string=} moduleIdentifier + * @property {string=} moduleName + * @property {string=} loc + * @property {string|number=} chunkId + * @property {string|number=} moduleId + * @property {StatsModuleTraceItem[]=} moduleTrace + * @property {any=} details + * @property {string=} stack + */ +/** @typedef {Asset & { type: string, related: PreprocessedAsset[] }} PreprocessedAsset */ -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const HelperRuntimeModule = __webpack_require__(82444); +/** + * @template T + * @template O + * @typedef {Record void>} ExtractorsByOption + */ -class MakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { - constructor() { - super("make namespace object"); - } +/** + * @typedef {Object} SimpleExtractors + * @property {ExtractorsByOption} compilation + * @property {ExtractorsByOption} asset + * @property {ExtractorsByOption} asset$visible + * @property {ExtractorsByOption<{ name: string, chunkGroup: ChunkGroup }, StatsChunkGroup>} chunkGroup + * @property {ExtractorsByOption} module + * @property {ExtractorsByOption} module$visible + * @property {ExtractorsByOption} moduleIssuer + * @property {ExtractorsByOption} profile + * @property {ExtractorsByOption} moduleReason + * @property {ExtractorsByOption} chunk + * @property {ExtractorsByOption} chunkOrigin + * @property {ExtractorsByOption} error + * @property {ExtractorsByOption} warning + * @property {ExtractorsByOption<{ origin: Module, module: Module }, StatsModuleTraceItem>} moduleTraceItem + * @property {ExtractorsByOption} moduleTraceDependency + */ - /** - * @returns {string} runtime code - */ - generate() { - const { runtimeTemplate } = this.compilation; - const fn = RuntimeGlobals.makeNamespaceObject; - return Template.asString([ - "// define __esModule on exports", - `${fn} = ${runtimeTemplate.basicFunction("exports", [ - "if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {", - Template.indent([ - "Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });" - ]), - "}", - "Object.defineProperty(exports, '__esModule', { value: true });" - ])};` - ]); +/** + * @template T + * @template I + * @param {Iterable} items items to select from + * @param {function(T): Iterable} selector selector function to select values from item + * @returns {I[]} array of values + */ +const uniqueArray = (items, selector) => { + /** @type {Set} */ + const set = new Set(); + for (const item of items) { + for (const i of selector(item)) { + set.add(i); + } } -} - -module.exports = MakeNamespaceObjectRuntimeModule; - - -/***/ }), - -/***/ 44518: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - + return Array.from(set); +}; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); +/** + * @template T + * @template I + * @param {Iterable} items items to select from + * @param {function(T): Iterable} selector selector function to select values from item + * @param {Comparator} comparator comparator function + * @returns {I[]} array of values + */ +const uniqueOrderedArray = (items, selector, comparator) => { + return uniqueArray(items, selector).sort(comparator); +}; -class OnChunksLoadedRuntimeModule extends RuntimeModule { - constructor() { - super("chunk loaded"); - } +/** @template T @template R @typedef {{ [P in keyof T]: R }} MappedValues */ - /** - * @returns {string} runtime code - */ - generate() { - const { compilation } = this; - const { runtimeTemplate } = compilation; - return Template.asString([ - "var deferred = [];", - `${RuntimeGlobals.onChunksLoaded} = ${runtimeTemplate.basicFunction( - "result, chunkIds, fn, priority", - [ - "if(chunkIds) {", - Template.indent([ - "priority = priority || 0;", - "for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];", - "deferred[i] = [chunkIds, fn, priority];", - "return;" - ]), - "}", - "var notFulfilled = Infinity;", - "for (var i = 0; i < deferred.length; i++) {", - Template.indent([ - runtimeTemplate.destructureArray( - ["chunkIds", "fn", "priority"], - "deferred[i]" - ), - "var fulfilled = true;", - "for (var j = 0; j < chunkIds.length; j++) {", - Template.indent([ - `if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(${ - RuntimeGlobals.onChunksLoaded - }).every(${runtimeTemplate.returningFunction( - `${RuntimeGlobals.onChunksLoaded}[key](chunkIds[j])`, - "key" - )})) {`, - Template.indent(["chunkIds.splice(j--, 1);"]), - "} else {", - Template.indent([ - "fulfilled = false;", - "if(priority < notFulfilled) notFulfilled = priority;" - ]), - "}" - ]), - "}", - "if(fulfilled) {", - Template.indent([ - "deferred.splice(i--, 1)", - "var r = fn();", - "if (r !== undefined) result = r;" - ]), - "}" - ]), - "}", - "return result;" - ] - )};` - ]); +/** + * @template T + * @template R + * @param {T} obj object to be mapped + * @param {function(T[keyof T], keyof T): R} fn mapping function + * @returns {MappedValues} mapped object + */ +const mapObject = (obj, fn) => { + const newObj = Object.create(null); + for (const key of Object.keys(obj)) { + newObj[key] = fn(obj[key], /** @type {keyof T} */ (key)); } -} - -module.exports = OnChunksLoadedRuntimeModule; - - -/***/ }), - -/***/ 56030: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); + return newObj; +}; -class PublicPathRuntimeModule extends RuntimeModule { - constructor(publicPath) { - super("publicPath", RuntimeModule.STAGE_BASIC); - this.publicPath = publicPath; +/** + * @param {Compilation} compilation the compilation + * @param {function(Compilation, string): any[]} getItems get items + * @returns {number} total number + */ +const countWithChildren = (compilation, getItems) => { + let count = getItems(compilation, "").length; + for (const child of compilation.children) { + count += countWithChildren(child, (c, type) => + getItems(c, `.children[].compilation${type}`) + ); } + return count; +}; - /** - * @returns {string} runtime code - */ - generate() { - const { compilation, publicPath } = this; - - return `${RuntimeGlobals.publicPath} = ${JSON.stringify( - compilation.getPath(publicPath || "", { - hash: compilation.hash || "XXXX" - }) - )};`; +/** @type {ExtractorsByOption} */ +const EXTRACT_ERROR = { + _: (object, error, context, { requestShortener }) => { + // TODO webpack 6 disallow strings in the errors/warnings list + if (typeof error === "string") { + object.message = error; + } else { + if (error.chunk) { + object.chunkName = error.chunk.name; + object.chunkEntry = error.chunk.hasRuntime(); + object.chunkInitial = error.chunk.canBeInitial(); + } + if (error.file) { + object.file = error.file; + } + if (error.module) { + object.moduleIdentifier = error.module.identifier(); + object.moduleName = error.module.readableIdentifier(requestShortener); + } + if (error.loc) { + object.loc = formatLocation(error.loc); + } + object.message = error.message; + } + }, + ids: (object, error, { compilation: { chunkGraph } }) => { + if (typeof error !== "string") { + if (error.chunk) { + object.chunkId = error.chunk.id; + } + if (error.module) { + object.moduleId = chunkGraph.getModuleId(error.module); + } + } + }, + moduleTrace: (object, error, context, options, factory) => { + if (typeof error !== "string" && error.module) { + const { + type, + compilation: { moduleGraph } + } = context; + /** @type {Set} */ + const visitedModules = new Set(); + const moduleTrace = []; + let current = error.module; + while (current) { + if (visitedModules.has(current)) break; // circular (technically impossible, but how knows) + visitedModules.add(current); + const origin = moduleGraph.getIssuer(current); + if (!origin) break; + moduleTrace.push({ origin, module: current }); + current = origin; + } + object.moduleTrace = factory.create( + `${type}.moduleTrace`, + moduleTrace, + context + ); + } + }, + errorDetails: ( + object, + error, + { type, compilation, cachedGetErrors, cachedGetWarnings }, + { errorDetails } + ) => { + if ( + typeof error !== "string" && + (errorDetails === true || + (type.endsWith(".error") && cachedGetErrors(compilation).length < 3)) + ) { + object.details = error.details; + } + }, + errorStack: (object, error) => { + if (typeof error !== "string") { + object.stack = error.stack; + } } -} - -module.exports = PublicPathRuntimeModule; - +}; -/***/ }), +/** @type {SimpleExtractors} */ +const SIMPLE_EXTRACTORS = { + compilation: { + _: (object, compilation, context, options) => { + if (!context.makePathsRelative) { + context.makePathsRelative = makePathsRelative.bindContextCache( + compilation.compiler.context, + compilation.compiler.root + ); + } + if (!context.cachedGetErrors) { + const map = new WeakMap(); + context.cachedGetErrors = compilation => { + return ( + map.get(compilation) || + (errors => (map.set(compilation, errors), errors))( + compilation.getErrors() + ) + ); + }; + } + if (!context.cachedGetWarnings) { + const map = new WeakMap(); + context.cachedGetWarnings = compilation => { + return ( + map.get(compilation) || + (warnings => (map.set(compilation, warnings), warnings))( + compilation.getWarnings() + ) + ); + }; + } + if (compilation.name) { + object.name = compilation.name; + } + if (compilation.needAdditionalPass) { + object.needAdditionalPass = true; + } -/***/ 4537: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const { logging, loggingDebug, loggingTrace } = options; + if (logging || (loggingDebug && loggingDebug.length > 0)) { + const util = __webpack_require__(73837); + object.logging = {}; + let acceptedTypes; + let collapsedGroups = false; + switch (logging) { + default: + acceptedTypes = new Set(); + break; + case "error": + acceptedTypes = new Set([LogType.error]); + break; + case "warn": + acceptedTypes = new Set([LogType.error, LogType.warn]); + break; + case "info": + acceptedTypes = new Set([ + LogType.error, + LogType.warn, + LogType.info + ]); + break; + case "log": + acceptedTypes = new Set([ + LogType.error, + LogType.warn, + LogType.info, + LogType.log, + LogType.group, + LogType.groupEnd, + LogType.groupCollapsed, + LogType.clear + ]); + break; + case "verbose": + acceptedTypes = new Set([ + LogType.error, + LogType.warn, + LogType.info, + LogType.log, + LogType.group, + LogType.groupEnd, + LogType.groupCollapsed, + LogType.profile, + LogType.profileEnd, + LogType.time, + LogType.status, + LogType.clear + ]); + collapsedGroups = true; + break; + } + const cachedMakePathsRelative = makePathsRelative.bindContextCache( + options.context, + compilation.compiler.root + ); + let depthInCollapsedGroup = 0; + for (const [origin, logEntries] of compilation.logging) { + const debugMode = loggingDebug.some(fn => fn(origin)); + if (logging === false && !debugMode) continue; + /** @type {KnownStatsLoggingEntry[]} */ + const groupStack = []; + /** @type {KnownStatsLoggingEntry[]} */ + const rootList = []; + let currentList = rootList; + let processedLogEntries = 0; + for (const entry of logEntries) { + let type = entry.type; + if (!debugMode && !acceptedTypes.has(type)) continue; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + // Expand groups in verbose and debug modes + if ( + type === LogType.groupCollapsed && + (debugMode || collapsedGroups) + ) + type = LogType.group; + if (depthInCollapsedGroup === 0) { + processedLogEntries++; + } + if (type === LogType.groupEnd) { + groupStack.pop(); + if (groupStack.length > 0) { + currentList = groupStack[groupStack.length - 1].children; + } else { + currentList = rootList; + } + if (depthInCollapsedGroup > 0) depthInCollapsedGroup--; + continue; + } + let message = undefined; + if (entry.type === LogType.time) { + message = `${entry.args[0]}: ${ + entry.args[1] * 1000 + entry.args[2] / 1000000 + } ms`; + } else if (entry.args && entry.args.length > 0) { + message = util.format(entry.args[0], ...entry.args.slice(1)); + } + /** @type {KnownStatsLoggingEntry} */ + const newEntry = { + ...entry, + type, + message, + trace: loggingTrace ? entry.trace : undefined, + children: + type === LogType.group || type === LogType.groupCollapsed + ? [] + : undefined + }; + currentList.push(newEntry); + if (newEntry.children) { + groupStack.push(newEntry); + currentList = newEntry.children; + if (depthInCollapsedGroup > 0) { + depthInCollapsedGroup++; + } else if (type === LogType.groupCollapsed) { + depthInCollapsedGroup = 1; + } + } + } + let name = cachedMakePathsRelative(origin).replace(/\|/g, " "); + if (name in object.logging) { + let i = 1; + while (`${name}#${i}` in object.logging) { + i++; + } + name = `${name}#${i}`; + } + object.logging[name] = { + entries: rootList, + filteredEntries: logEntries.length - processedLogEntries, + debug: debugMode + }; + } + } + }, + hash: (object, compilation) => { + object.hash = compilation.hash; + }, + version: object => { + object.version = (__webpack_require__(32702)/* .version */ .i8); + }, + env: (object, compilation, context, { _env }) => { + object.env = _env; + }, + timings: (object, compilation) => { + object.time = compilation.endTime - compilation.startTime; + }, + builtAt: (object, compilation) => { + object.builtAt = compilation.endTime; + }, + publicPath: (object, compilation) => { + object.publicPath = compilation.getPath( + compilation.outputOptions.publicPath + ); + }, + outputPath: (object, compilation) => { + object.outputPath = compilation.outputOptions.path; + }, + assets: (object, compilation, context, options, factory) => { + const { type } = context; + /** @type {Map} */ + const compilationFileToChunks = new Map(); + /** @type {Map} */ + const compilationAuxiliaryFileToChunks = new Map(); + for (const chunk of compilation.chunks) { + for (const file of chunk.files) { + let array = compilationFileToChunks.get(file); + if (array === undefined) { + array = []; + compilationFileToChunks.set(file, array); + } + array.push(chunk); + } + for (const file of chunk.auxiliaryFiles) { + let array = compilationAuxiliaryFileToChunks.get(file); + if (array === undefined) { + array = []; + compilationAuxiliaryFileToChunks.set(file, array); + } + array.push(chunk); + } + } + /** @type {Map} */ + const assetMap = new Map(); + /** @type {Set} */ + const assets = new Set(); + for (const asset of compilation.getAssets()) { + /** @type {PreprocessedAsset} */ + const item = { + ...asset, + type: "asset", + related: undefined + }; + assets.add(item); + assetMap.set(asset.name, item); + } + for (const item of assetMap.values()) { + const related = item.info.related; + if (!related) continue; + for (const type of Object.keys(related)) { + const relatedEntry = related[type]; + const deps = Array.isArray(relatedEntry) + ? relatedEntry + : [relatedEntry]; + for (const dep of deps) { + const depItem = assetMap.get(dep); + if (!depItem) continue; + assets.delete(depItem); + depItem.type = type; + item.related = item.related || []; + item.related.push(depItem); + } + } + } -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const HelperRuntimeModule = __webpack_require__(82444); + object.assetsByChunkName = {}; + for (const [file, chunks] of compilationFileToChunks) { + for (const chunk of chunks) { + const name = chunk.name; + if (!name) continue; + if ( + !Object.prototype.hasOwnProperty.call( + object.assetsByChunkName, + name + ) + ) { + object.assetsByChunkName[name] = []; + } + object.assetsByChunkName[name].push(file); + } + } -class RelativeUrlRuntimeModule extends HelperRuntimeModule { - constructor() { - super("relative url"); + const groupedAssets = factory.create( + `${type}.assets`, + Array.from(assets), + { + ...context, + compilationFileToChunks, + compilationAuxiliaryFileToChunks + } + ); + const limited = spaceLimited(groupedAssets, options.assetsSpace); + object.assets = limited.children; + object.filteredAssets = limited.filteredChildren; + }, + chunks: (object, compilation, context, options, factory) => { + const { type } = context; + object.chunks = factory.create( + `${type}.chunks`, + Array.from(compilation.chunks), + context + ); + }, + modules: (object, compilation, context, options, factory) => { + const { type } = context; + const array = Array.from(compilation.modules); + const groupedModules = factory.create(`${type}.modules`, array, context); + const limited = spaceLimited(groupedModules, options.modulesSpace); + object.modules = limited.children; + object.filteredModules = limited.filteredChildren; + }, + entrypoints: ( + object, + compilation, + context, + { entrypoints, chunkGroups, chunkGroupAuxiliary, chunkGroupChildren }, + factory + ) => { + const { type } = context; + const array = Array.from(compilation.entrypoints, ([key, value]) => ({ + name: key, + chunkGroup: value + })); + if (entrypoints === "auto" && !chunkGroups) { + if (array.length > 5) return; + if ( + !chunkGroupChildren && + array.every(({ chunkGroup }) => { + if (chunkGroup.chunks.length !== 1) return false; + const chunk = chunkGroup.chunks[0]; + return ( + chunk.files.size === 1 && + (!chunkGroupAuxiliary || chunk.auxiliaryFiles.size === 0) + ); + }) + ) { + return; + } + } + object.entrypoints = factory.create( + `${type}.entrypoints`, + array, + context + ); + }, + chunkGroups: (object, compilation, context, options, factory) => { + const { type } = context; + const array = Array.from( + compilation.namedChunkGroups, + ([key, value]) => ({ + name: key, + chunkGroup: value + }) + ); + object.namedChunkGroups = factory.create( + `${type}.namedChunkGroups`, + array, + context + ); + }, + errors: (object, compilation, context, options, factory) => { + const { type, cachedGetErrors } = context; + object.errors = factory.create( + `${type}.errors`, + cachedGetErrors(compilation), + context + ); + }, + errorsCount: (object, compilation, { cachedGetErrors }) => { + object.errorsCount = countWithChildren(compilation, c => + cachedGetErrors(c) + ); + }, + warnings: (object, compilation, context, options, factory) => { + const { type, cachedGetWarnings } = context; + object.warnings = factory.create( + `${type}.warnings`, + cachedGetWarnings(compilation), + context + ); + }, + warningsCount: ( + object, + compilation, + context, + { warningsFilter }, + factory + ) => { + const { type, cachedGetWarnings } = context; + object.warningsCount = countWithChildren(compilation, (c, childType) => { + if (!warningsFilter && warningsFilter.length === 0) + return cachedGetWarnings(c); + return factory + .create(`${type}${childType}.warnings`, cachedGetWarnings(c), context) + .filter(warning => { + const warningString = Object.keys(warning) + .map(key => `${warning[key]}`) + .join("\n"); + return !warningsFilter.some(filter => + filter(warning, warningString) + ); + }); + }); + }, + errorDetails: ( + object, + compilation, + { cachedGetErrors, cachedGetWarnings }, + { errorDetails, errors, warnings } + ) => { + if (errorDetails === "auto") { + if (warnings) { + const warnings = cachedGetWarnings(compilation); + object.filteredWarningDetailsCount = warnings + .map(e => typeof e !== "string" && e.details) + .filter(Boolean).length; + } + if (errors) { + const errors = cachedGetErrors(compilation); + if (errors.length >= 3) { + object.filteredErrorDetailsCount = errors + .map(e => typeof e !== "string" && e.details) + .filter(Boolean).length; + } + } + } + }, + children: (object, compilation, context, options, factory) => { + const { type } = context; + object.children = factory.create( + `${type}.children`, + compilation.children, + context + ); + } + }, + asset: { + _: (object, asset, context, options, factory) => { + const { compilation } = context; + object.type = asset.type; + object.name = asset.name; + object.size = asset.source.size(); + object.emitted = compilation.emittedAssets.has(asset.name); + object.comparedForEmit = compilation.comparedForEmitAssets.has( + asset.name + ); + const cached = !object.emitted && !object.comparedForEmit; + object.cached = cached; + object.info = asset.info; + if (!cached || options.cachedAssets) { + Object.assign( + object, + factory.create(`${context.type}$visible`, asset, context) + ); + } + } + }, + asset$visible: { + _: ( + object, + asset, + { compilation, compilationFileToChunks, compilationAuxiliaryFileToChunks } + ) => { + const chunks = compilationFileToChunks.get(asset.name) || []; + const auxiliaryChunks = + compilationAuxiliaryFileToChunks.get(asset.name) || []; + object.chunkNames = uniqueOrderedArray( + chunks, + c => (c.name ? [c.name] : []), + compareIds + ); + object.chunkIdHints = uniqueOrderedArray( + chunks, + c => Array.from(c.idNameHints), + compareIds + ); + object.auxiliaryChunkNames = uniqueOrderedArray( + auxiliaryChunks, + c => (c.name ? [c.name] : []), + compareIds + ); + object.auxiliaryChunkIdHints = uniqueOrderedArray( + auxiliaryChunks, + c => Array.from(c.idNameHints), + compareIds + ); + object.filteredRelated = asset.related ? asset.related.length : undefined; + }, + relatedAssets: (object, asset, context, options, factory) => { + const { type } = context; + object.related = factory.create( + `${type.slice(0, -8)}.related`, + asset.related, + context + ); + object.filteredRelated = asset.related + ? asset.related.length - object.related.length + : undefined; + }, + ids: ( + object, + asset, + { compilationFileToChunks, compilationAuxiliaryFileToChunks } + ) => { + const chunks = compilationFileToChunks.get(asset.name) || []; + const auxiliaryChunks = + compilationAuxiliaryFileToChunks.get(asset.name) || []; + object.chunks = uniqueOrderedArray(chunks, c => c.ids, compareIds); + object.auxiliaryChunks = uniqueOrderedArray( + auxiliaryChunks, + c => c.ids, + compareIds + ); + }, + performance: (object, asset) => { + object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(asset.source); + } + }, + chunkGroup: { + _: ( + object, + { name, chunkGroup }, + { compilation, compilation: { moduleGraph, chunkGraph } }, + { ids, chunkGroupAuxiliary, chunkGroupChildren, chunkGroupMaxAssets } + ) => { + const children = + chunkGroupChildren && + chunkGroup.getChildrenByOrders(moduleGraph, chunkGraph); + /** + * @param {string} name Name + * @returns {{ name: string, size: number }} Asset object + */ + const toAsset = name => { + const asset = compilation.getAsset(name); + return { + name, + size: asset ? asset.info.size : -1 + }; + }; + /** @type {(total: number, asset: { size: number }) => number} */ + const sizeReducer = (total, { size }) => total + size; + const assets = uniqueArray(chunkGroup.chunks, c => c.files).map(toAsset); + const auxiliaryAssets = uniqueOrderedArray( + chunkGroup.chunks, + c => c.auxiliaryFiles, + compareIds + ).map(toAsset); + const assetsSize = assets.reduce(sizeReducer, 0); + const auxiliaryAssetsSize = auxiliaryAssets.reduce(sizeReducer, 0); + /** @type {KnownStatsChunkGroup} */ + const statsChunkGroup = { + name, + chunks: ids ? chunkGroup.chunks.map(c => c.id) : undefined, + assets: assets.length <= chunkGroupMaxAssets ? assets : undefined, + filteredAssets: + assets.length <= chunkGroupMaxAssets ? 0 : assets.length, + assetsSize, + auxiliaryAssets: + chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets + ? auxiliaryAssets + : undefined, + filteredAuxiliaryAssets: + chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets + ? 0 + : auxiliaryAssets.length, + auxiliaryAssetsSize, + children: children + ? mapObject(children, groups => + groups.map(group => { + const assets = uniqueArray(group.chunks, c => c.files).map( + toAsset + ); + const auxiliaryAssets = uniqueOrderedArray( + group.chunks, + c => c.auxiliaryFiles, + compareIds + ).map(toAsset); + + /** @type {KnownStatsChunkGroup} */ + const childStatsChunkGroup = { + name: group.name, + chunks: ids ? group.chunks.map(c => c.id) : undefined, + assets: + assets.length <= chunkGroupMaxAssets ? assets : undefined, + filteredAssets: + assets.length <= chunkGroupMaxAssets ? 0 : assets.length, + auxiliaryAssets: + chunkGroupAuxiliary && + auxiliaryAssets.length <= chunkGroupMaxAssets + ? auxiliaryAssets + : undefined, + filteredAuxiliaryAssets: + chunkGroupAuxiliary && + auxiliaryAssets.length <= chunkGroupMaxAssets + ? 0 + : auxiliaryAssets.length + }; + + return childStatsChunkGroup; + }) + ) + : undefined, + childAssets: children + ? mapObject(children, groups => { + /** @type {Set} */ + const set = new Set(); + for (const group of groups) { + for (const chunk of group.chunks) { + for (const asset of chunk.files) { + set.add(asset); + } + } + } + return Array.from(set); + }) + : undefined + }; + Object.assign(object, statsChunkGroup); + }, + performance: (object, { chunkGroup }) => { + object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(chunkGroup); + } + }, + module: { + _: (object, module, context, options, factory) => { + const { compilation, type } = context; + const built = compilation.builtModules.has(module); + const codeGenerated = compilation.codeGeneratedModules.has(module); + const buildTimeExecuted = + compilation.buildTimeExecutedModules.has(module); + /** @type {{[x: string]: number}} */ + const sizes = {}; + for (const sourceType of module.getSourceTypes()) { + sizes[sourceType] = module.size(sourceType); + } + /** @type {KnownStatsModule} */ + const statsModule = { + type: "module", + moduleType: module.type, + layer: module.layer, + size: module.size(), + sizes, + built, + codeGenerated, + buildTimeExecuted, + cached: !built && !codeGenerated + }; + Object.assign(object, statsModule); + + if (built || codeGenerated || options.cachedModules) { + Object.assign( + object, + factory.create(`${type}$visible`, module, context) + ); + } + } + }, + module$visible: { + _: (object, module, context, { requestShortener }, factory) => { + const { compilation, type, rootModules } = context; + const { moduleGraph } = compilation; + /** @type {Module[]} */ + const path = []; + const issuer = moduleGraph.getIssuer(module); + let current = issuer; + while (current) { + path.push(current); + current = moduleGraph.getIssuer(current); + } + path.reverse(); + const profile = moduleGraph.getProfile(module); + const errors = module.getErrors(); + const errorsCount = errors !== undefined ? countIterable(errors) : 0; + const warnings = module.getWarnings(); + const warningsCount = + warnings !== undefined ? countIterable(warnings) : 0; + /** @type {{[x: string]: number}} */ + const sizes = {}; + for (const sourceType of module.getSourceTypes()) { + sizes[sourceType] = module.size(sourceType); + } + /** @type {KnownStatsModule} */ + const statsModule = { + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener), + nameForCondition: module.nameForCondition(), + index: moduleGraph.getPreOrderIndex(module), + preOrderIndex: moduleGraph.getPreOrderIndex(module), + index2: moduleGraph.getPostOrderIndex(module), + postOrderIndex: moduleGraph.getPostOrderIndex(module), + cacheable: module.buildInfo.cacheable, + optional: module.isOptional(moduleGraph), + orphan: + !type.endsWith("module.modules[].module$visible") && + compilation.chunkGraph.getNumberOfModuleChunks(module) === 0, + dependent: rootModules ? !rootModules.has(module) : undefined, + issuer: issuer && issuer.identifier(), + issuerName: issuer && issuer.readableIdentifier(requestShortener), + issuerPath: + issuer && + factory.create(`${type.slice(0, -8)}.issuerPath`, path, context), + failed: errorsCount > 0, + errors: errorsCount, + warnings: warningsCount + }; + Object.assign(object, statsModule); + if (profile) { + object.profile = factory.create( + `${type.slice(0, -8)}.profile`, + profile, + context + ); + } + }, + ids: (object, module, { compilation: { chunkGraph, moduleGraph } }) => { + object.id = chunkGraph.getModuleId(module); + const issuer = moduleGraph.getIssuer(module); + object.issuerId = issuer && chunkGraph.getModuleId(issuer); + object.chunks = Array.from( + chunkGraph.getOrderedModuleChunksIterable(module, compareChunksById), + chunk => chunk.id + ); + }, + moduleAssets: (object, module) => { + object.assets = module.buildInfo.assets + ? Object.keys(module.buildInfo.assets) + : []; + }, + reasons: (object, module, context, options, factory) => { + const { + type, + compilation: { moduleGraph } + } = context; + const groupsReasons = factory.create( + `${type.slice(0, -8)}.reasons`, + Array.from(moduleGraph.getIncomingConnections(module)), + context + ); + const limited = spaceLimited(groupsReasons, options.reasonsSpace); + object.reasons = limited.children; + object.filteredReasons = limited.filteredChildren; + }, + usedExports: ( + object, + module, + { runtime, compilation: { moduleGraph } } + ) => { + const usedExports = moduleGraph.getUsedExports(module, runtime); + if (usedExports === null) { + object.usedExports = null; + } else if (typeof usedExports === "boolean") { + object.usedExports = usedExports; + } else { + object.usedExports = Array.from(usedExports); + } + }, + providedExports: (object, module, { compilation: { moduleGraph } }) => { + const providedExports = moduleGraph.getProvidedExports(module); + object.providedExports = Array.isArray(providedExports) + ? providedExports + : null; + }, + optimizationBailout: ( + object, + module, + { compilation: { moduleGraph } }, + { requestShortener } + ) => { + object.optimizationBailout = moduleGraph + .getOptimizationBailout(module) + .map(item => { + if (typeof item === "function") return item(requestShortener); + return item; + }); + }, + depth: (object, module, { compilation: { moduleGraph } }) => { + object.depth = moduleGraph.getDepth(module); + }, + nestedModules: (object, module, context, options, factory) => { + const { type } = context; + const innerModules = /** @type {Module & { modules?: Module[] }} */ ( + module + ).modules; + if (Array.isArray(innerModules)) { + const groupedModules = factory.create( + `${type.slice(0, -8)}.modules`, + innerModules, + context + ); + const limited = spaceLimited( + groupedModules, + options.nestedModulesSpace + ); + object.modules = limited.children; + object.filteredModules = limited.filteredChildren; + } + }, + source: (object, module) => { + const originalSource = module.originalSource(); + if (originalSource) { + object.source = originalSource.source(); + } + } + }, + profile: { + _: (object, profile) => { + /** @type {KnownStatsProfile} */ + const statsProfile = { + total: + profile.factory + + profile.restoring + + profile.integration + + profile.building + + profile.storing, + resolving: profile.factory, + restoring: profile.restoring, + building: profile.building, + integration: profile.integration, + storing: profile.storing, + additionalResolving: profile.additionalFactories, + additionalIntegration: profile.additionalIntegration, + // TODO remove this in webpack 6 + factory: profile.factory, + // TODO remove this in webpack 6 + dependencies: profile.additionalFactories + }; + Object.assign(object, statsProfile); + } + }, + moduleIssuer: { + _: (object, module, context, { requestShortener }, factory) => { + const { compilation, type } = context; + const { moduleGraph } = compilation; + const profile = moduleGraph.getProfile(module); + /** @type {KnownStatsModuleIssuer} */ + const statsModuleIssuer = { + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener) + }; + Object.assign(object, statsModuleIssuer); + if (profile) { + object.profile = factory.create(`${type}.profile`, profile, context); + } + }, + ids: (object, module, { compilation: { chunkGraph } }) => { + object.id = chunkGraph.getModuleId(module); + } + }, + moduleReason: { + _: (object, reason, { runtime }, { requestShortener }) => { + const dep = reason.dependency; + const moduleDep = + dep && dep instanceof ModuleDependency ? dep : undefined; + /** @type {KnownStatsModuleReason} */ + const statsModuleReason = { + moduleIdentifier: reason.originModule + ? reason.originModule.identifier() + : null, + module: reason.originModule + ? reason.originModule.readableIdentifier(requestShortener) + : null, + moduleName: reason.originModule + ? reason.originModule.readableIdentifier(requestShortener) + : null, + resolvedModuleIdentifier: reason.resolvedOriginModule + ? reason.resolvedOriginModule.identifier() + : null, + resolvedModule: reason.resolvedOriginModule + ? reason.resolvedOriginModule.readableIdentifier(requestShortener) + : null, + type: reason.dependency ? reason.dependency.type : null, + active: reason.isActive(runtime), + explanation: reason.explanation, + userRequest: (moduleDep && moduleDep.userRequest) || null + }; + Object.assign(object, statsModuleReason); + if (reason.dependency) { + const locInfo = formatLocation(reason.dependency.loc); + if (locInfo) { + object.loc = locInfo; + } + } + }, + ids: (object, reason, { compilation: { chunkGraph } }) => { + object.moduleId = reason.originModule + ? chunkGraph.getModuleId(reason.originModule) + : null; + object.resolvedModuleId = reason.resolvedOriginModule + ? chunkGraph.getModuleId(reason.resolvedOriginModule) + : null; + } + }, + chunk: { + _: (object, chunk, { makePathsRelative, compilation: { chunkGraph } }) => { + const childIdByOrder = chunk.getChildIdsByOrders(chunkGraph); + + /** @type {KnownStatsChunk} */ + const statsChunk = { + rendered: chunk.rendered, + initial: chunk.canBeInitial(), + entry: chunk.hasRuntime(), + recorded: AggressiveSplittingPlugin.wasChunkRecorded(chunk), + reason: chunk.chunkReason, + size: chunkGraph.getChunkModulesSize(chunk), + sizes: chunkGraph.getChunkModulesSizes(chunk), + names: chunk.name ? [chunk.name] : [], + idHints: Array.from(chunk.idNameHints), + runtime: + chunk.runtime === undefined + ? undefined + : typeof chunk.runtime === "string" + ? [makePathsRelative(chunk.runtime)] + : Array.from(chunk.runtime.sort(), makePathsRelative), + files: Array.from(chunk.files), + auxiliaryFiles: Array.from(chunk.auxiliaryFiles).sort(compareIds), + hash: chunk.renderedHash, + childrenByOrder: childIdByOrder + }; + Object.assign(object, statsChunk); + }, + ids: (object, chunk) => { + object.id = chunk.id; + }, + chunkRelations: (object, chunk, { compilation: { chunkGraph } }) => { + /** @type {Set} */ + const parents = new Set(); + /** @type {Set} */ + const children = new Set(); + /** @type {Set} */ + const siblings = new Set(); + + for (const chunkGroup of chunk.groupsIterable) { + for (const parentGroup of chunkGroup.parentsIterable) { + for (const chunk of parentGroup.chunks) { + parents.add(chunk.id); + } + } + for (const childGroup of chunkGroup.childrenIterable) { + for (const chunk of childGroup.chunks) { + children.add(chunk.id); + } + } + for (const sibling of chunkGroup.chunks) { + if (sibling !== chunk) siblings.add(sibling.id); + } + } + object.siblings = Array.from(siblings).sort(compareIds); + object.parents = Array.from(parents).sort(compareIds); + object.children = Array.from(children).sort(compareIds); + }, + chunkModules: (object, chunk, context, options, factory) => { + const { + type, + compilation: { chunkGraph } + } = context; + const array = chunkGraph.getChunkModules(chunk); + const groupedModules = factory.create(`${type}.modules`, array, { + ...context, + runtime: chunk.runtime, + rootModules: new Set(chunkGraph.getChunkRootModules(chunk)) + }); + const limited = spaceLimited(groupedModules, options.chunkModulesSpace); + object.modules = limited.children; + object.filteredModules = limited.filteredChildren; + }, + chunkOrigins: (object, chunk, context, options, factory) => { + const { + type, + compilation: { chunkGraph } + } = context; + /** @type {Set} */ + const originsKeySet = new Set(); + const origins = []; + for (const g of chunk.groupsIterable) { + origins.push(...g.origins); + } + const array = origins.filter(origin => { + const key = [ + origin.module ? chunkGraph.getModuleId(origin.module) : undefined, + formatLocation(origin.loc), + origin.request + ].join(); + if (originsKeySet.has(key)) return false; + originsKeySet.add(key); + return true; + }); + object.origins = factory.create(`${type}.origins`, array, context); + } + }, + chunkOrigin: { + _: (object, origin, context, { requestShortener }) => { + /** @type {KnownStatsChunkOrigin} */ + const statsChunkOrigin = { + module: origin.module ? origin.module.identifier() : "", + moduleIdentifier: origin.module ? origin.module.identifier() : "", + moduleName: origin.module + ? origin.module.readableIdentifier(requestShortener) + : "", + loc: formatLocation(origin.loc), + request: origin.request + }; + Object.assign(object, statsChunkOrigin); + }, + ids: (object, origin, { compilation: { chunkGraph } }) => { + object.moduleId = origin.module + ? chunkGraph.getModuleId(origin.module) + : undefined; + } + }, + error: EXTRACT_ERROR, + warning: EXTRACT_ERROR, + moduleTraceItem: { + _: (object, { origin, module }, context, { requestShortener }, factory) => { + const { + type, + compilation: { moduleGraph } + } = context; + object.originIdentifier = origin.identifier(); + object.originName = origin.readableIdentifier(requestShortener); + object.moduleIdentifier = module.identifier(); + object.moduleName = module.readableIdentifier(requestShortener); + const dependencies = Array.from( + moduleGraph.getIncomingConnections(module) + ) + .filter(c => c.resolvedOriginModule === origin && c.dependency) + .map(c => c.dependency); + object.dependencies = factory.create( + `${type}.dependencies`, + Array.from(new Set(dependencies)), + context + ); + }, + ids: (object, { origin, module }, { compilation: { chunkGraph } }) => { + object.originId = chunkGraph.getModuleId(origin); + object.moduleId = chunkGraph.getModuleId(module); + } + }, + moduleTraceDependency: { + _: (object, dependency) => { + object.loc = formatLocation(dependency.loc); + } } +}; - /** - * @returns {string} runtime code - */ - generate() { - const { runtimeTemplate } = this.compilation; - return Template.asString([ - `${RuntimeGlobals.relativeUrl} = function RelativeURL(url) {`, - Template.indent([ - 'var realUrl = new URL(url, "x:/");', - "var values = {};", - "for (var key in realUrl) values[key] = realUrl[key];", - "values.href = url;", - 'values.pathname = url.replace(/[?#].*/, "");', - 'values.origin = values.protocol = "";', - `values.toString = values.toJSON = ${runtimeTemplate.returningFunction( - "url" - )};`, - "for (var key in values) Object.defineProperty(this, key, { enumerable: true, configurable: true, value: values[key] });" - ]), - "};", - `${RuntimeGlobals.relativeUrl}.prototype = URL.prototype;` - ]); +/** @type {Record boolean | undefined>>} */ +const FILTER = { + "module.reasons": { + "!orphanModules": (reason, { compilation: { chunkGraph } }) => { + if ( + reason.originModule && + chunkGraph.getNumberOfModuleChunks(reason.originModule) === 0 + ) { + return false; + } + } } -} +}; -module.exports = RelativeUrlRuntimeModule; +/** @type {Record boolean | undefined>>} */ +const FILTER_RESULTS = { + "compilation.warnings": { + warningsFilter: util.deprecate( + (warning, context, { warningsFilter }) => { + const warningString = Object.keys(warning) + .map(key => `${warning[key]}`) + .join("\n"); + return !warningsFilter.some(filter => filter(warning, warningString)); + }, + "config.stats.warningsFilter is deprecated in favor of config.ignoreWarnings", + "DEP_WEBPACK_STATS_WARNINGS_FILTER" + ) + } +}; +/** @type {Record void>} */ +const MODULES_SORTER = { + _: (comparators, { compilation: { moduleGraph } }) => { + comparators.push( + compareSelect( + /** + * @param {Module} m module + * @returns {number} depth + */ + m => moduleGraph.getDepth(m), + compareNumbers + ), + compareSelect( + /** + * @param {Module} m module + * @returns {number} index + */ + m => moduleGraph.getPreOrderIndex(m), + compareNumbers + ), + compareSelect( + /** + * @param {Module} m module + * @returns {string} identifier + */ + m => m.identifier(), + compareIds + ) + ); + } +}; + +/** @type {Record void>>} */ +const SORTERS = { + "compilation.chunks": { + _: comparators => { + comparators.push(compareSelect(c => c.id, compareIds)); + } + }, + "compilation.modules": MODULES_SORTER, + "chunk.rootModules": MODULES_SORTER, + "chunk.modules": MODULES_SORTER, + "module.modules": MODULES_SORTER, + "module.reasons": { + _: (comparators, { compilation: { chunkGraph } }) => { + comparators.push( + compareSelect(x => x.originModule, compareModulesByIdentifier) + ); + comparators.push( + compareSelect(x => x.resolvedOriginModule, compareModulesByIdentifier) + ); + comparators.push( + compareSelect( + x => x.dependency, + concatComparators( + compareSelect( + /** + * @param {Dependency} x dependency + * @returns {DependencyLocation} location + */ + x => x.loc, + compareLocations + ), + compareSelect(x => x.type, compareIds) + ) + ) + ); + } + }, + "chunk.origins": { + _: (comparators, { compilation: { chunkGraph } }) => { + comparators.push( + compareSelect( + origin => + origin.module ? chunkGraph.getModuleId(origin.module) : undefined, + compareIds + ), + compareSelect(origin => formatLocation(origin.loc), compareIds), + compareSelect(origin => origin.request, compareIds) + ); + } + } +}; + +const getItemSize = item => { + // Each item takes 1 line + // + the size of the children + // + 1 extra line when it has children and filteredChildren + return !item.children + ? 1 + : item.filteredChildren + ? 2 + getTotalSize(item.children) + : 1 + getTotalSize(item.children); +}; + +const getTotalSize = children => { + let size = 0; + for (const child of children) { + size += getItemSize(child); + } + return size; +}; + +const getTotalItems = children => { + let count = 0; + for (const child of children) { + if (!child.children && !child.filteredChildren) { + count++; + } else { + if (child.children) count += getTotalItems(child.children); + if (child.filteredChildren) count += child.filteredChildren; + } + } + return count; +}; + +const collapse = children => { + // After collapse each child must take exactly one line + const newChildren = []; + for (const child of children) { + if (child.children) { + let filteredChildren = child.filteredChildren || 0; + filteredChildren += getTotalItems(child.children); + newChildren.push({ + ...child, + children: undefined, + filteredChildren + }); + } else { + newChildren.push(child); + } + } + return newChildren; +}; + +const spaceLimited = ( + itemsAndGroups, + max, + filteredChildrenLineReserved = false +) => { + if (max < 1) { + return { + children: undefined, + filteredChildren: getTotalItems(itemsAndGroups) + }; + } + /** @type {any[] | undefined} */ + let children = undefined; + /** @type {number | undefined} */ + let filteredChildren = undefined; + // This are the groups, which take 1+ lines each + const groups = []; + // The sizes of the groups are stored in groupSizes + const groupSizes = []; + // This are the items, which take 1 line each + const items = []; + // The total of group sizes + let groupsSize = 0; + + for (const itemOrGroup of itemsAndGroups) { + // is item + if (!itemOrGroup.children && !itemOrGroup.filteredChildren) { + items.push(itemOrGroup); + } else { + groups.push(itemOrGroup); + const size = getItemSize(itemOrGroup); + groupSizes.push(size); + groupsSize += size; + } + } + + if (groupsSize + items.length <= max) { + // The total size in the current state fits into the max + // keep all + children = groups.length > 0 ? groups.concat(items) : items; + } else if (groups.length === 0) { + // slice items to max + // inner space marks that lines for filteredChildren already reserved + const limit = max - (filteredChildrenLineReserved ? 0 : 1); + filteredChildren = items.length - limit; + items.length = limit; + children = items; + } else { + // limit is the size when all groups are collapsed + const limit = + groups.length + + (filteredChildrenLineReserved || items.length === 0 ? 0 : 1); + if (limit < max) { + // calculate how much we are over the size limit + // this allows to approach the limit faster + let oversize; + // If each group would take 1 line the total would be below the maximum + // collapse some groups, keep items + while ( + (oversize = + groupsSize + + items.length + + (filteredChildren && !filteredChildrenLineReserved ? 1 : 0) - + max) > 0 + ) { + // Find the maximum group and process only this one + const maxGroupSize = Math.max(...groupSizes); + if (maxGroupSize < items.length) { + filteredChildren = items.length; + items.length = 0; + continue; + } + for (let i = 0; i < groups.length; i++) { + if (groupSizes[i] === maxGroupSize) { + const group = groups[i]; + // run this algorithm recursively and limit the size of the children to + // current size - oversize / number of groups + // So it should always end up being smaller + const headerSize = group.filteredChildren ? 2 : 1; + const limited = spaceLimited( + group.children, + maxGroupSize - + // we should use ceil to always feet in max + Math.ceil(oversize / groups.length) - + // we substitute size of group head + headerSize, + headerSize === 2 + ); + groups[i] = { + ...group, + children: limited.children, + filteredChildren: limited.filteredChildren + ? (group.filteredChildren || 0) + limited.filteredChildren + : group.filteredChildren + }; + const newSize = getItemSize(groups[i]); + groupsSize -= maxGroupSize - newSize; + groupSizes[i] = newSize; + break; + } + } + } + children = groups.concat(items); + } else if (limit === max) { + // If we have only enough space to show one line per group and one line for the filtered items + // collapse all groups and items + children = collapse(groups); + filteredChildren = items.length; + } else { + // If we have no space + // collapse complete group + filteredChildren = getTotalItems(itemsAndGroups); + } + } + + return { + children, + filteredChildren + }; +}; + +const assetGroup = (children, assets) => { + let size = 0; + for (const asset of children) { + size += asset.size; + } + return { + size + }; +}; + +const moduleGroup = (children, modules) => { + let size = 0; + const sizes = {}; + for (const module of children) { + size += module.size; + for (const key of Object.keys(module.sizes)) { + sizes[key] = (sizes[key] || 0) + module.sizes[key]; + } + } + return { + size, + sizes + }; +}; -/***/ }), +const reasonGroup = (children, reasons) => { + let active = false; + for (const reason of children) { + active = active || reason.active; + } + return { + active + }; +}; -/***/ 97115: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const GROUP_EXTENSION_REGEXP = /(\.[^.]+?)(?:\?|(?: \+ \d+ modules?)?$)/; +const GROUP_PATH_REGEXP = /(.+)[/\\][^/\\]+?(?:\?|(?: \+ \d+ modules?)?$)/; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ +/** @type {Record void>} */ +const ASSETS_GROUPERS = { + _: (groupConfigs, context, options) => { + const groupByFlag = (name, exclude) => { + groupConfigs.push({ + getKeys: asset => { + return asset[name] ? ["1"] : undefined; + }, + getOptions: () => { + return { + groupChildren: !exclude, + force: exclude + }; + }, + createGroup: (key, children, assets) => { + return exclude + ? { + type: "assets by status", + [name]: !!key, + filteredChildren: assets.length, + ...assetGroup(children, assets) + } + : { + type: "assets by status", + [name]: !!key, + children, + ...assetGroup(children, assets) + }; + } + }); + }; + const { + groupAssetsByEmitStatus, + groupAssetsByPath, + groupAssetsByExtension + } = options; + if (groupAssetsByEmitStatus) { + groupByFlag("emitted"); + groupByFlag("comparedForEmit"); + groupByFlag("isOverSizeLimit"); + } + if (groupAssetsByEmitStatus || !options.cachedAssets) { + groupByFlag("cached", !options.cachedAssets); + } + if (groupAssetsByPath || groupAssetsByExtension) { + groupConfigs.push({ + getKeys: asset => { + const extensionMatch = + groupAssetsByExtension && GROUP_EXTENSION_REGEXP.exec(asset.name); + const extension = extensionMatch ? extensionMatch[1] : ""; + const pathMatch = + groupAssetsByPath && GROUP_PATH_REGEXP.exec(asset.name); + const path = pathMatch ? pathMatch[1].split(/[/\\]/) : []; + const keys = []; + if (groupAssetsByPath) { + keys.push("."); + if (extension) + keys.push( + path.length + ? `${path.join("/")}/*${extension}` + : `*${extension}` + ); + while (path.length > 0) { + keys.push(path.join("/") + "/"); + path.pop(); + } + } else { + if (extension) keys.push(`*${extension}`); + } + return keys; + }, + createGroup: (key, children, assets) => { + return { + type: groupAssetsByPath ? "assets by path" : "assets by extension", + name: key, + children, + ...assetGroup(children, assets) + }; + } + }); + } + }, + groupAssetsByInfo: (groupConfigs, context, options) => { + const groupByAssetInfoFlag = name => { + groupConfigs.push({ + getKeys: asset => { + return asset.info && asset.info[name] ? ["1"] : undefined; + }, + createGroup: (key, children, assets) => { + return { + type: "assets by info", + info: { + [name]: !!key + }, + children, + ...assetGroup(children, assets) + }; + } + }); + }; + groupByAssetInfoFlag("immutable"); + groupByAssetInfoFlag("development"); + groupByAssetInfoFlag("hotModuleReplacement"); + }, + groupAssetsByChunk: (groupConfigs, context, options) => { + const groupByNames = name => { + groupConfigs.push({ + getKeys: asset => { + return asset[name]; + }, + createGroup: (key, children, assets) => { + return { + type: "assets by chunk", + [name]: [key], + children, + ...assetGroup(children, assets) + }; + } + }); + }; + groupByNames("chunkNames"); + groupByNames("auxiliaryChunkNames"); + groupByNames("chunkIdHints"); + groupByNames("auxiliaryChunkIdHints"); + }, + excludeAssets: (groupConfigs, context, { excludeAssets }) => { + groupConfigs.push({ + getKeys: asset => { + const ident = asset.name; + const excluded = excludeAssets.some(fn => fn(ident, asset)); + if (excluded) return ["excluded"]; + }, + getOptions: () => ({ + groupChildren: false, + force: true + }), + createGroup: (key, children, assets) => ({ + type: "hidden assets", + filteredChildren: assets.length, + ...assetGroup(children, assets) + }) + }); + } +}; +/** @type {function("module" | "chunk" | "root-of-chunk" | "nested"): Record void>} */ +const MODULES_GROUPERS = type => ({ + _: (groupConfigs, context, options) => { + const groupByFlag = (name, type, exclude) => { + groupConfigs.push({ + getKeys: module => { + return module[name] ? ["1"] : undefined; + }, + getOptions: () => { + return { + groupChildren: !exclude, + force: exclude + }; + }, + createGroup: (key, children, modules) => { + return { + type, + [name]: !!key, + ...(exclude ? { filteredChildren: modules.length } : { children }), + ...moduleGroup(children, modules) + }; + } + }); + }; + const { + groupModulesByCacheStatus, + groupModulesByLayer, + groupModulesByAttributes, + groupModulesByType, + groupModulesByPath, + groupModulesByExtension + } = options; + if (groupModulesByAttributes) { + groupByFlag("errors", "modules with errors"); + groupByFlag("warnings", "modules with warnings"); + groupByFlag("assets", "modules with assets"); + groupByFlag("optional", "optional modules"); + } + if (groupModulesByCacheStatus) { + groupByFlag("cacheable", "cacheable modules"); + groupByFlag("built", "built modules"); + groupByFlag("codeGenerated", "code generated modules"); + } + if (groupModulesByCacheStatus || !options.cachedModules) { + groupByFlag("cached", "cached modules", !options.cachedModules); + } + if (groupModulesByAttributes || !options.orphanModules) { + groupByFlag("orphan", "orphan modules", !options.orphanModules); + } + if (groupModulesByAttributes || !options.dependentModules) { + groupByFlag("dependent", "dependent modules", !options.dependentModules); + } + if (groupModulesByType || !options.runtimeModules) { + groupConfigs.push({ + getKeys: module => { + if (!module.moduleType) return; + if (groupModulesByType) { + return [module.moduleType.split("/", 1)[0]]; + } else if (module.moduleType === "runtime") { + return ["runtime"]; + } + }, + getOptions: key => { + const exclude = key === "runtime" && !options.runtimeModules; + return { + groupChildren: !exclude, + force: exclude + }; + }, + createGroup: (key, children, modules) => { + const exclude = key === "runtime" && !options.runtimeModules; + return { + type: `${key} modules`, + moduleType: key, + ...(exclude ? { filteredChildren: modules.length } : { children }), + ...moduleGroup(children, modules) + }; + } + }); + } + if (groupModulesByLayer) { + groupConfigs.push({ + getKeys: module => { + return [module.layer]; + }, + createGroup: (key, children, modules) => { + return { + type: "modules by layer", + layer: key, + children, + ...moduleGroup(children, modules) + }; + } + }); + } + if (groupModulesByPath || groupModulesByExtension) { + groupConfigs.push({ + getKeys: module => { + if (!module.name) return; + const resource = parseResource(module.name.split("!").pop()).path; + const dataUrl = /^data:[^,;]+/.exec(resource); + if (dataUrl) return [dataUrl[0]]; + const extensionMatch = + groupModulesByExtension && GROUP_EXTENSION_REGEXP.exec(resource); + const extension = extensionMatch ? extensionMatch[1] : ""; + const pathMatch = + groupModulesByPath && GROUP_PATH_REGEXP.exec(resource); + const path = pathMatch ? pathMatch[1].split(/[/\\]/) : []; + const keys = []; + if (groupModulesByPath) { + if (extension) + keys.push( + path.length + ? `${path.join("/")}/*${extension}` + : `*${extension}` + ); + while (path.length > 0) { + keys.push(path.join("/") + "/"); + path.pop(); + } + } else { + if (extension) keys.push(`*${extension}`); + } + return keys; + }, + createGroup: (key, children, modules) => { + const isDataUrl = key.startsWith("data:"); + return { + type: isDataUrl + ? "modules by mime type" + : groupModulesByPath + ? "modules by path" + : "modules by extension", + name: isDataUrl ? key.slice(/* 'data:'.length */ 5) : key, + children, + ...moduleGroup(children, modules) + }; + } + }); + } + }, + excludeModules: (groupConfigs, context, { excludeModules }) => { + groupConfigs.push({ + getKeys: module => { + const name = module.name; + if (name) { + const excluded = excludeModules.some(fn => fn(name, module, type)); + if (excluded) return ["1"]; + } + }, + getOptions: () => ({ + groupChildren: false, + force: true + }), + createGroup: (key, children, modules) => ({ + type: "hidden modules", + filteredChildren: children.length, + ...moduleGroup(children, modules) + }) + }); + } +}); +/** @type {Record void>>} */ +const RESULT_GROUPERS = { + "compilation.assets": ASSETS_GROUPERS, + "asset.related": ASSETS_GROUPERS, + "compilation.modules": MODULES_GROUPERS("module"), + "chunk.modules": MODULES_GROUPERS("chunk"), + "chunk.rootModules": MODULES_GROUPERS("root-of-chunk"), + "module.modules": MODULES_GROUPERS("nested"), + "module.reasons": { + groupReasonsByOrigin: groupConfigs => { + groupConfigs.push({ + getKeys: reason => { + return [reason.module]; + }, + createGroup: (key, children, reasons) => { + return { + type: "from origin", + module: key, + children, + ...reasonGroup(children, reasons) + }; + } + }); + } + } +}; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); +// remove a prefixed "!" that can be specified to reverse sort order +const normalizeFieldKey = field => { + if (field[0] === "!") { + return field.substr(1); + } + return field; +}; -class RuntimeIdRuntimeModule extends RuntimeModule { - constructor() { - super("runtimeId"); +// if a field is prefixed by a "!" reverse sort order +const sortOrderRegular = field => { + if (field[0] === "!") { + return false; } + return true; +}; - /** - * @returns {string} runtime code - */ - generate() { - const { chunkGraph, chunk } = this; - const runtime = chunk.runtime; - if (typeof runtime !== "string") - throw new Error("RuntimeIdRuntimeModule must be in a single runtime"); - const id = chunkGraph.getRuntimeId(runtime); - return `${RuntimeGlobals.runtimeId} = ${JSON.stringify(id)};`; +/** + * @param {string} field field name + * @returns {function(Object, Object): number} comparators + */ +const sortByField = field => { + if (!field) { + /** + * @param {any} a first + * @param {any} b second + * @returns {-1|0|1} zero + */ + const noSort = (a, b) => 0; + return noSort; } -} -module.exports = RuntimeIdRuntimeModule; + const fieldKey = normalizeFieldKey(field); + let sortFn = compareSelect(m => m[fieldKey], compareIds); -/***/ }), + // if a field is prefixed with a "!" the sort is reversed! + const sortIsRegular = sortOrderRegular(field); -/***/ 22339: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (!sortIsRegular) { + const oldSortFn = sortFn; + sortFn = (a, b) => oldSortFn(b, a); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + return sortFn; +}; +const ASSET_SORTERS = { + /** @type {(comparators: Function[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void} */ + assetsSort: (comparators, context, { assetsSort }) => { + comparators.push(sortByField(assetsSort)); + }, + _: comparators => { + comparators.push(compareSelect(a => a.name, compareIds)); + } +}; +/** @type {Record void>>} */ +const RESULT_SORTERS = { + "compilation.chunks": { + chunksSort: (comparators, context, { chunksSort }) => { + comparators.push(sortByField(chunksSort)); + } + }, + "compilation.modules": { + modulesSort: (comparators, context, { modulesSort }) => { + comparators.push(sortByField(modulesSort)); + } + }, + "chunk.modules": { + chunkModulesSort: (comparators, context, { chunkModulesSort }) => { + comparators.push(sortByField(chunkModulesSort)); + } + }, + "module.modules": { + nestedModulesSort: (comparators, context, { nestedModulesSort }) => { + comparators.push(sortByField(nestedModulesSort)); + } + }, + "compilation.assets": ASSET_SORTERS, + "asset.related": ASSET_SORTERS +}; -const RuntimeGlobals = __webpack_require__(16475); -const StartupChunkDependenciesRuntimeModule = __webpack_require__(38157); -const StartupEntrypointRuntimeModule = __webpack_require__(97672); +/** + * @param {Record>} config the config see above + * @param {NormalizedStatsOptions} options stats options + * @param {function(string, Function): void} fn handler function called for every active line in config + * @returns {void} + */ +const iterateConfig = (config, options, fn) => { + for (const hookFor of Object.keys(config)) { + const subConfig = config[hookFor]; + for (const option of Object.keys(subConfig)) { + if (option !== "_") { + if (option.startsWith("!")) { + if (options[option.slice(1)]) continue; + } else { + const value = options[option]; + if ( + value === false || + value === undefined || + (Array.isArray(value) && value.length === 0) + ) + continue; + } + } + fn(hookFor, subConfig[option]); + } + } +}; -/** @typedef {import("../Compiler")} Compiler */ +/** @type {Record} */ +const ITEM_NAMES = { + "compilation.children[]": "compilation", + "compilation.modules[]": "module", + "compilation.entrypoints[]": "chunkGroup", + "compilation.namedChunkGroups[]": "chunkGroup", + "compilation.errors[]": "error", + "compilation.warnings[]": "warning", + "chunk.modules[]": "module", + "chunk.rootModules[]": "module", + "chunk.origins[]": "chunkOrigin", + "compilation.chunks[]": "chunk", + "compilation.assets[]": "asset", + "asset.related[]": "asset", + "module.issuerPath[]": "moduleIssuer", + "module.reasons[]": "moduleReason", + "module.modules[]": "module", + "module.children[]": "module", + "moduleTrace[]": "moduleTraceItem", + "moduleTraceItem.dependencies[]": "moduleTraceDependency" +}; -class StartupChunkDependenciesPlugin { - constructor(options) { - this.chunkLoading = options.chunkLoading; - this.asyncChunkLoading = - typeof options.asyncChunkLoading === "boolean" - ? options.asyncChunkLoading - : true; +/** + * @param {Object[]} items items to be merged + * @returns {Object} an object + */ +const mergeToObject = items => { + const obj = Object.create(null); + for (const item of items) { + obj[item.name] = item; } + return obj; +}; + +/** @type {Record any>} */ +const MERGER = { + "compilation.entrypoints": mergeToObject, + "compilation.namedChunkGroups": mergeToObject +}; +class DefaultStatsFactoryPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - compiler.hooks.thisCompilation.tap( - "StartupChunkDependenciesPlugin", - compilation => { - const globalChunkLoading = compilation.outputOptions.chunkLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const chunkLoading = - options && options.chunkLoading !== undefined - ? options.chunkLoading - : globalChunkLoading; - return chunkLoading === this.chunkLoading; - }; - compilation.hooks.additionalTreeRuntimeRequirements.tap( - "StartupChunkDependenciesPlugin", - (chunk, set, { chunkGraph }) => { - if (!isEnabledForChunk(chunk)) return; - if (chunkGraph.hasChunkEntryDependentChunks(chunk)) { - set.add(RuntimeGlobals.startup); - set.add(RuntimeGlobals.ensureChunk); - set.add(RuntimeGlobals.ensureChunkIncludeEntries); - compilation.addRuntimeModule( - chunk, - new StartupChunkDependenciesRuntimeModule( - this.asyncChunkLoading - ) + compiler.hooks.compilation.tap("DefaultStatsFactoryPlugin", compilation => { + compilation.hooks.statsFactory.tap( + "DefaultStatsFactoryPlugin", + (stats, options, context) => { + iterateConfig(SIMPLE_EXTRACTORS, options, (hookFor, fn) => { + stats.hooks.extract + .for(hookFor) + .tap("DefaultStatsFactoryPlugin", (obj, data, ctx) => + fn(obj, data, ctx, options, stats) + ); + }); + iterateConfig(FILTER, options, (hookFor, fn) => { + stats.hooks.filter + .for(hookFor) + .tap("DefaultStatsFactoryPlugin", (item, ctx, idx, i) => + fn(item, ctx, options, idx, i) + ); + }); + iterateConfig(FILTER_RESULTS, options, (hookFor, fn) => { + stats.hooks.filterResults + .for(hookFor) + .tap("DefaultStatsFactoryPlugin", (item, ctx, idx, i) => + fn(item, ctx, options, idx, i) + ); + }); + iterateConfig(SORTERS, options, (hookFor, fn) => { + stats.hooks.sort + .for(hookFor) + .tap("DefaultStatsFactoryPlugin", (comparators, ctx) => + fn(comparators, ctx, options) ); + }); + iterateConfig(RESULT_SORTERS, options, (hookFor, fn) => { + stats.hooks.sortResults + .for(hookFor) + .tap("DefaultStatsFactoryPlugin", (comparators, ctx) => + fn(comparators, ctx, options) + ); + }); + iterateConfig(RESULT_GROUPERS, options, (hookFor, fn) => { + stats.hooks.groupResults + .for(hookFor) + .tap("DefaultStatsFactoryPlugin", (groupConfigs, ctx) => + fn(groupConfigs, ctx, options) + ); + }); + for (const key of Object.keys(ITEM_NAMES)) { + const itemName = ITEM_NAMES[key]; + stats.hooks.getItemName + .for(key) + .tap("DefaultStatsFactoryPlugin", () => itemName); + } + for (const key of Object.keys(MERGER)) { + const merger = MERGER[key]; + stats.hooks.merge.for(key).tap("DefaultStatsFactoryPlugin", merger); + } + if (options.children) { + if (Array.isArray(options.children)) { + stats.hooks.getItemFactory + .for("compilation.children[].compilation") + .tap("DefaultStatsFactoryPlugin", (comp, { _index: idx }) => { + if (idx < options.children.length) { + return compilation.createStatsFactory( + compilation.createStatsOptions( + options.children[idx], + context + ) + ); + } + }); + } else if (options.children !== true) { + const childFactory = compilation.createStatsFactory( + compilation.createStatsOptions(options.children, context) + ); + stats.hooks.getItemFactory + .for("compilation.children[].compilation") + .tap("DefaultStatsFactoryPlugin", () => { + return childFactory; + }); } } - ); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.startupEntrypoint) - .tap("StartupChunkDependenciesPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.require); - set.add(RuntimeGlobals.ensureChunk); - set.add(RuntimeGlobals.ensureChunkIncludeEntries); - compilation.addRuntimeModule( - chunk, - new StartupEntrypointRuntimeModule(this.asyncChunkLoading) - ); - }); - } - ); + } + ); + }); } } - -module.exports = StartupChunkDependenciesPlugin; +module.exports = DefaultStatsFactoryPlugin; /***/ }), -/***/ 38157: +/***/ 55442: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -117297,162 +118502,330 @@ module.exports = StartupChunkDependenciesPlugin; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); +const RequestShortener = __webpack_require__(73406); -class StartupChunkDependenciesRuntimeModule extends RuntimeModule { - constructor(asyncChunkLoading) { - super("startup chunk dependencies", RuntimeModule.STAGE_TRIGGER); - this.asyncChunkLoading = asyncChunkLoading; - } +/** @typedef {import("../../declarations/WebpackOptions").StatsOptions} StatsOptions */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compilation").CreateStatsOptionsContext} CreateStatsOptionsContext */ +/** @typedef {import("../Compiler")} Compiler */ - /** - * @returns {string} runtime code - */ - generate() { - const { chunkGraph, chunk, compilation } = this; - const { runtimeTemplate } = compilation; - const chunkIds = Array.from( - chunkGraph.getChunkEntryDependentChunksIterable(chunk) - ).map(chunk => { - return chunk.id; - }); - return Template.asString([ - `var next = ${RuntimeGlobals.startup};`, - `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction( - "", - !this.asyncChunkLoading - ? chunkIds - .map( - id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)});` - ) - .concat("return next();") - : chunkIds.length === 1 - ? `return ${RuntimeGlobals.ensureChunk}(${JSON.stringify( - chunkIds[0] - )}).then(next);` - : chunkIds.length > 2 - ? [ - // using map is shorter for 3 or more chunks - `return Promise.all(${JSON.stringify(chunkIds)}.map(${ - RuntimeGlobals.ensureChunk - }, __webpack_require__)).then(next);` - ] - : [ - // calling ensureChunk directly is shorter for 0 - 2 chunks - "return Promise.all([", - Template.indent( - chunkIds - .map( - id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)})` - ) - .join(",\n") - ), - "]).then(next);" - ] - )};` - ]); +const applyDefaults = (options, defaults) => { + for (const key of Object.keys(defaults)) { + if (typeof options[key] === "undefined") { + options[key] = defaults[key]; + } } -} - -module.exports = StartupChunkDependenciesRuntimeModule; - - -/***/ }), - -/***/ 97672: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - +}; +const NAMED_PRESETS = { + verbose: { + hash: true, + builtAt: true, + relatedAssets: true, + entrypoints: true, + chunkGroups: true, + ids: true, + modules: false, + chunks: true, + chunkRelations: true, + chunkModules: true, + dependentModules: true, + chunkOrigins: true, + depth: true, + env: true, + reasons: true, + usedExports: true, + providedExports: true, + optimizationBailout: true, + errorDetails: true, + errorStack: true, + publicPath: true, + logging: "verbose", + orphanModules: true, + runtimeModules: true, + exclude: false, + modulesSpace: Infinity, + chunkModulesSpace: Infinity, + assetsSpace: Infinity, + reasonsSpace: Infinity, + children: true + }, + detailed: { + hash: true, + builtAt: true, + relatedAssets: true, + entrypoints: true, + chunkGroups: true, + ids: true, + chunks: true, + chunkRelations: true, + chunkModules: false, + chunkOrigins: true, + depth: true, + usedExports: true, + providedExports: true, + optimizationBailout: true, + errorDetails: true, + publicPath: true, + logging: true, + runtimeModules: true, + exclude: false, + modulesSpace: 1000, + assetsSpace: 1000, + reasonsSpace: 1000 + }, + minimal: { + all: false, + version: true, + timings: true, + modules: true, + modulesSpace: 0, + assets: true, + assetsSpace: 0, + errors: true, + errorsCount: true, + warnings: true, + warningsCount: true, + logging: "warn" + }, + "errors-only": { + all: false, + errors: true, + errorsCount: true, + moduleTrace: true, + logging: "error" + }, + "errors-warnings": { + all: false, + errors: true, + errorsCount: true, + warnings: true, + warningsCount: true, + logging: "warn" + }, + summary: { + all: false, + version: true, + errorsCount: true, + warningsCount: true + }, + none: { + all: false + } +}; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); +const NORMAL_ON = ({ all }) => all !== false; +const NORMAL_OFF = ({ all }) => all === true; +const ON_FOR_TO_STRING = ({ all }, { forToString }) => + forToString ? all !== false : all === true; +const OFF_FOR_TO_STRING = ({ all }, { forToString }) => + forToString ? all === true : all !== false; +const AUTO_FOR_TO_STRING = ({ all }, { forToString }) => { + if (all === false) return false; + if (all === true) return true; + if (forToString) return "auto"; + return true; +}; -/** @typedef {import("../MainTemplate")} MainTemplate */ +/** @type {Record any>} */ +const DEFAULTS = { + context: (options, context, compilation) => compilation.compiler.context, + requestShortener: (options, context, compilation) => + compilation.compiler.context === options.context + ? compilation.requestShortener + : new RequestShortener(options.context, compilation.compiler.root), + performance: NORMAL_ON, + hash: OFF_FOR_TO_STRING, + env: NORMAL_OFF, + version: NORMAL_ON, + timings: NORMAL_ON, + builtAt: OFF_FOR_TO_STRING, + assets: NORMAL_ON, + entrypoints: AUTO_FOR_TO_STRING, + chunkGroups: OFF_FOR_TO_STRING, + chunkGroupAuxiliary: OFF_FOR_TO_STRING, + chunkGroupChildren: OFF_FOR_TO_STRING, + chunkGroupMaxAssets: (o, { forToString }) => (forToString ? 5 : Infinity), + chunks: OFF_FOR_TO_STRING, + chunkRelations: OFF_FOR_TO_STRING, + chunkModules: ({ all, modules }) => { + if (all === false) return false; + if (all === true) return true; + if (modules) return false; + return true; + }, + dependentModules: OFF_FOR_TO_STRING, + chunkOrigins: OFF_FOR_TO_STRING, + ids: OFF_FOR_TO_STRING, + modules: ({ all, chunks, chunkModules }, { forToString }) => { + if (all === false) return false; + if (all === true) return true; + if (forToString && chunks && chunkModules) return false; + return true; + }, + nestedModules: OFF_FOR_TO_STRING, + groupModulesByType: ON_FOR_TO_STRING, + groupModulesByCacheStatus: ON_FOR_TO_STRING, + groupModulesByLayer: ON_FOR_TO_STRING, + groupModulesByAttributes: ON_FOR_TO_STRING, + groupModulesByPath: ON_FOR_TO_STRING, + groupModulesByExtension: ON_FOR_TO_STRING, + modulesSpace: (o, { forToString }) => (forToString ? 15 : Infinity), + chunkModulesSpace: (o, { forToString }) => (forToString ? 10 : Infinity), + nestedModulesSpace: (o, { forToString }) => (forToString ? 10 : Infinity), + relatedAssets: OFF_FOR_TO_STRING, + groupAssetsByEmitStatus: ON_FOR_TO_STRING, + groupAssetsByInfo: ON_FOR_TO_STRING, + groupAssetsByPath: ON_FOR_TO_STRING, + groupAssetsByExtension: ON_FOR_TO_STRING, + groupAssetsByChunk: ON_FOR_TO_STRING, + assetsSpace: (o, { forToString }) => (forToString ? 15 : Infinity), + orphanModules: OFF_FOR_TO_STRING, + runtimeModules: ({ all, runtime }, { forToString }) => + runtime !== undefined + ? runtime + : forToString + ? all === true + : all !== false, + cachedModules: ({ all, cached }, { forToString }) => + cached !== undefined ? cached : forToString ? all === true : all !== false, + moduleAssets: OFF_FOR_TO_STRING, + depth: OFF_FOR_TO_STRING, + cachedAssets: OFF_FOR_TO_STRING, + reasons: OFF_FOR_TO_STRING, + reasonsSpace: (o, { forToString }) => (forToString ? 15 : Infinity), + groupReasonsByOrigin: ON_FOR_TO_STRING, + usedExports: OFF_FOR_TO_STRING, + providedExports: OFF_FOR_TO_STRING, + optimizationBailout: OFF_FOR_TO_STRING, + children: OFF_FOR_TO_STRING, + source: NORMAL_OFF, + moduleTrace: NORMAL_ON, + errors: NORMAL_ON, + errorsCount: NORMAL_ON, + errorDetails: AUTO_FOR_TO_STRING, + errorStack: OFF_FOR_TO_STRING, + warnings: NORMAL_ON, + warningsCount: NORMAL_ON, + publicPath: OFF_FOR_TO_STRING, + logging: ({ all }, { forToString }) => + forToString && all !== false ? "info" : false, + loggingDebug: () => [], + loggingTrace: OFF_FOR_TO_STRING, + excludeModules: () => [], + excludeAssets: () => [], + modulesSort: () => "depth", + chunkModulesSort: () => "name", + nestedModulesSort: () => false, + chunksSort: () => false, + assetsSort: () => "!size", + outputPath: OFF_FOR_TO_STRING, + colors: () => false +}; -class StartupEntrypointRuntimeModule extends RuntimeModule { - constructor(asyncChunkLoading) { - super("startup entrypoint"); - this.asyncChunkLoading = asyncChunkLoading; +const normalizeFilter = item => { + if (typeof item === "string") { + const regExp = new RegExp( + `[\\\\/]${item.replace( + // eslint-disable-next-line no-useless-escape + /[-[\]{}()*+?.\\^$|]/g, + "\\$&" + )}([\\\\/]|$|!|\\?)` + ); + return ident => regExp.test(ident); } - - /** - * @returns {string} runtime code - */ - generate() { - const { compilation } = this; - const { runtimeTemplate } = compilation; - return `${ - RuntimeGlobals.startupEntrypoint - } = ${runtimeTemplate.basicFunction("result, chunkIds, fn", [ - "// arguments: chunkIds, moduleId are deprecated", - "var moduleId = chunkIds;", - `if(!fn) chunkIds = result, fn = ${runtimeTemplate.returningFunction( - `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)` - )};`, - ...(this.asyncChunkLoading - ? [ - `return Promise.all(chunkIds.map(${ - RuntimeGlobals.ensureChunk - }, __webpack_require__)).then(${runtimeTemplate.basicFunction("", [ - "var r = fn();", - "return r === undefined ? result : r;" - ])})` - ] - : [ - `chunkIds.map(${RuntimeGlobals.ensureChunk}, __webpack_require__)`, - "var r = fn();", - "return r === undefined ? result : r;" - ]) - ])}`; + if (item && typeof item === "object" && typeof item.test === "function") { + return ident => item.test(ident); } -} - -module.exports = StartupEntrypointRuntimeModule; - - -/***/ }), - -/***/ 80655: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - - -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); - -/** @typedef {import("../Compilation")} Compilation */ + if (typeof item === "function") { + return item; + } + if (typeof item === "boolean") { + return () => item; + } +}; -class SystemContextRuntimeModule extends RuntimeModule { - constructor() { - super("__system_context__"); +const NORMALIZER = { + excludeModules: value => { + if (!Array.isArray(value)) { + value = value ? [value] : []; + } + return value.map(normalizeFilter); + }, + excludeAssets: value => { + if (!Array.isArray(value)) { + value = value ? [value] : []; + } + return value.map(normalizeFilter); + }, + warningsFilter: value => { + if (!Array.isArray(value)) { + value = value ? [value] : []; + } + return value.map(filter => { + if (typeof filter === "string") { + return (warning, warningString) => warningString.includes(filter); + } + if (filter instanceof RegExp) { + return (warning, warningString) => filter.test(warningString); + } + if (typeof filter === "function") { + return filter; + } + throw new Error( + `Can only filter warnings with Strings or RegExps. (Given: ${filter})` + ); + }); + }, + logging: value => { + if (value === true) value = "log"; + return value; + }, + loggingDebug: value => { + if (!Array.isArray(value)) { + value = value ? [value] : []; + } + return value.map(normalizeFilter); } +}; +class DefaultStatsPresetPlugin { /** - * @returns {string} runtime code + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - generate() { - return `${RuntimeGlobals.systemContext} = __system_context__;`; + apply(compiler) { + compiler.hooks.compilation.tap("DefaultStatsPresetPlugin", compilation => { + for (const key of Object.keys(NAMED_PRESETS)) { + const defaults = NAMED_PRESETS[key]; + compilation.hooks.statsPreset + .for(key) + .tap("DefaultStatsPresetPlugin", (options, context) => { + applyDefaults(options, defaults); + }); + } + compilation.hooks.statsNormalize.tap( + "DefaultStatsPresetPlugin", + (options, context) => { + for (const key of Object.keys(DEFAULTS)) { + if (options[key] === undefined) + options[key] = DEFAULTS[key](options, context, compilation); + } + for (const key of Object.keys(NORMALIZER)) { + options[key] = NORMALIZER[key](options[key]); + } + } + ); + }); } } - -module.exports = SystemContextRuntimeModule; +module.exports = DefaultStatsPresetPlugin; /***/ }), -/***/ 64820: +/***/ 58692: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -117463,4091 +118836,4413 @@ module.exports = SystemContextRuntimeModule; -const NormalModule = __webpack_require__(39); - /** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("./StatsPrinter")} StatsPrinter */ +/** @typedef {import("./StatsPrinter").StatsPrinterContext} StatsPrinterContext */ -// data URL scheme: "data:text/javascript;charset=utf-8;base64,some-string" -// http://www.ietf.org/rfc/rfc2397.txt -const URIRegEx = /^data:([^;,]+)?((?:;[^;,]+)*?)(?:;(base64))?,(.*)$/i; +const DATA_URI_CONTENT_LENGTH = 16; -const decodeDataURI = uri => { - const match = URIRegEx.exec(uri); - if (!match) return null; +const plural = (n, singular, plural) => (n === 1 ? singular : plural); - const isBase64 = match[3]; - const body = match[4]; - return isBase64 - ? Buffer.from(body, "base64") - : Buffer.from(decodeURIComponent(body), "ascii"); +/** + * @param {Record} sizes sizes by source type + * @param {Object} options options + * @param {(number) => string=} options.formatSize size formatter + * @returns {string} text + */ +const printSizes = (sizes, { formatSize = n => `${n}` }) => { + const keys = Object.keys(sizes); + if (keys.length > 1) { + return keys.map(key => `${formatSize(sizes[key])} (${key})`).join(" "); + } else if (keys.length === 1) { + return formatSize(sizes[keys[0]]); + } }; -class DataUriPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "DataUriPlugin", - (compilation, { normalModuleFactory }) => { - normalModuleFactory.hooks.resolveForScheme - .for("data") - .tap("DataUriPlugin", resourceData => { - const match = URIRegEx.exec(resourceData.resource); - if (match) { - resourceData.data.mimetype = match[1] || ""; - resourceData.data.parameters = match[2] || ""; - resourceData.data.encoding = match[3] || false; - resourceData.data.encodedContent = match[4] || ""; - } - }); - NormalModule.getCompilationHooks(compilation) - .readResourceForScheme.for("data") - .tap("DataUriPlugin", resource => decodeDataURI(resource)); - } - ); - } -} +const getResourceName = resource => { + const dataUrl = /^data:[^,]+,/.exec(resource); + if (!dataUrl) return resource; -module.exports = DataUriPlugin; + const len = dataUrl[0].length + DATA_URI_CONTENT_LENGTH; + if (resource.length < len) return resource; + return `${resource.slice( + 0, + Math.min(resource.length - /* '..'.length */ 2, len) + )}..`; +}; +const getModuleName = name => { + const [, prefix, resource] = /^(.*!)?([^!]*)$/.exec(name); + return [prefix, getResourceName(resource)]; +}; -/***/ }), +const mapLines = (str, fn) => str.split("\n").map(fn).join("\n"); -/***/ 57637: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @param {number} n a number + * @returns {string} number as two digit string, leading 0 + */ +const twoDigit = n => (n >= 10 ? `${n}` : `0${n}`); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const isValidId = id => { + return typeof id === "number" || id; +}; + +const moreCount = (list, count) => { + return list && list.length > 0 ? `+ ${count}` : `${count}`; +}; + +/** @type {Record string | void>} */ +const SIMPLE_PRINTERS = { + "compilation.summary!": ( + _, + { + type, + bold, + green, + red, + yellow, + formatDateTime, + formatTime, + compilation: { + name, + hash, + version, + time, + builtAt, + errorsCount, + warningsCount + } + } + ) => { + const root = type === "compilation.summary!"; + const warningsMessage = + warningsCount > 0 + ? yellow( + `${warningsCount} ${plural(warningsCount, "warning", "warnings")}` + ) + : ""; + const errorsMessage = + errorsCount > 0 + ? red(`${errorsCount} ${plural(errorsCount, "error", "errors")}`) + : ""; + const timeMessage = root && time ? ` in ${formatTime(time)}` : ""; + const hashMessage = hash ? ` (${hash})` : ""; + const builtAtMessage = + root && builtAt ? `${formatDateTime(builtAt)}: ` : ""; + const versionMessage = root && version ? `webpack ${version}` : ""; + const nameMessage = + root && name + ? bold(name) + : name + ? `Child ${bold(name)}` + : root + ? "" + : "Child"; + const subjectMessage = + nameMessage && versionMessage + ? `${nameMessage} (${versionMessage})` + : versionMessage || nameMessage || "webpack"; + let statusMessage; + if (errorsMessage && warningsMessage) { + statusMessage = `compiled with ${errorsMessage} and ${warningsMessage}`; + } else if (errorsMessage) { + statusMessage = `compiled with ${errorsMessage}`; + } else if (warningsMessage) { + statusMessage = `compiled with ${warningsMessage}`; + } else if (errorsCount === 0 && warningsCount === 0) { + statusMessage = `compiled ${green("successfully")}`; + } else { + statusMessage = `compiled`; + } + if ( + builtAtMessage || + versionMessage || + errorsMessage || + warningsMessage || + (errorsCount === 0 && warningsCount === 0) || + timeMessage || + hashMessage + ) + return `${builtAtMessage}${subjectMessage} ${statusMessage}${timeMessage}${hashMessage}`; + }, + "compilation.filteredWarningDetailsCount": count => + count + ? `${count} ${plural( + count, + "warning has", + "warnings have" + )} detailed information that is not shown.\nUse 'stats.errorDetails: true' resp. '--stats-error-details' to show it.` + : undefined, + "compilation.filteredErrorDetailsCount": (count, { yellow }) => + count + ? yellow( + `${count} ${plural( + count, + "error has", + "errors have" + )} detailed information that is not shown.\nUse 'stats.errorDetails: true' resp. '--stats-error-details' to show it.` + ) + : undefined, + "compilation.env": (env, { bold }) => + env + ? `Environment (--env): ${bold(JSON.stringify(env, null, 2))}` + : undefined, + "compilation.publicPath": (publicPath, { bold }) => + `PublicPath: ${bold(publicPath || "(none)")}`, + "compilation.entrypoints": (entrypoints, context, printer) => + Array.isArray(entrypoints) + ? undefined + : printer.print(context.type, Object.values(entrypoints), { + ...context, + chunkGroupKind: "Entrypoint" + }), + "compilation.namedChunkGroups": (namedChunkGroups, context, printer) => { + if (!Array.isArray(namedChunkGroups)) { + const { + compilation: { entrypoints } + } = context; + let chunkGroups = Object.values(namedChunkGroups); + if (entrypoints) { + chunkGroups = chunkGroups.filter( + group => + !Object.prototype.hasOwnProperty.call(entrypoints, group.name) + ); + } + return printer.print(context.type, chunkGroups, { + ...context, + chunkGroupKind: "Chunk Group" + }); + } + }, + "compilation.assetsByChunkName": () => "", + "compilation.filteredModules": ( + filteredModules, + { compilation: { modules } } + ) => + filteredModules > 0 + ? `${moreCount(modules, filteredModules)} ${plural( + filteredModules, + "module", + "modules" + )}` + : undefined, + "compilation.filteredAssets": (filteredAssets, { compilation: { assets } }) => + filteredAssets > 0 + ? `${moreCount(assets, filteredAssets)} ${plural( + filteredAssets, + "asset", + "assets" + )}` + : undefined, + "compilation.logging": (logging, context, printer) => + Array.isArray(logging) + ? undefined + : printer.print( + context.type, + Object.entries(logging).map(([name, value]) => ({ ...value, name })), + context + ), + "compilation.warningsInChildren!": (_, { yellow, compilation }) => { + if ( + !compilation.children && + compilation.warningsCount > 0 && + compilation.warnings + ) { + const childWarnings = + compilation.warningsCount - compilation.warnings.length; + if (childWarnings > 0) { + return yellow( + `${childWarnings} ${plural( + childWarnings, + "WARNING", + "WARNINGS" + )} in child compilations${ + compilation.children + ? "" + : " (Use 'stats.children: true' resp. '--stats-children' for more details)" + }` + ); + } + } + }, + "compilation.errorsInChildren!": (_, { red, compilation }) => { + if ( + !compilation.children && + compilation.errorsCount > 0 && + compilation.errors + ) { + const childErrors = compilation.errorsCount - compilation.errors.length; + if (childErrors > 0) { + return red( + `${childErrors} ${plural( + childErrors, + "ERROR", + "ERRORS" + )} in child compilations${ + compilation.children + ? "" + : " (Use 'stats.children: true' resp. '--stats-children' for more details)" + }` + ); + } + } + }, + "asset.type": type => type, + "asset.name": (name, { formatFilename, asset: { isOverSizeLimit } }) => + formatFilename(name, isOverSizeLimit), + "asset.size": ( + size, + { asset: { isOverSizeLimit }, yellow, green, formatSize } + ) => (isOverSizeLimit ? yellow(formatSize(size)) : formatSize(size)), + "asset.emitted": (emitted, { green, formatFlag }) => + emitted ? green(formatFlag("emitted")) : undefined, + "asset.comparedForEmit": (comparedForEmit, { yellow, formatFlag }) => + comparedForEmit ? yellow(formatFlag("compared for emit")) : undefined, + "asset.cached": (cached, { green, formatFlag }) => + cached ? green(formatFlag("cached")) : undefined, + "asset.isOverSizeLimit": (isOverSizeLimit, { yellow, formatFlag }) => + isOverSizeLimit ? yellow(formatFlag("big")) : undefined, -const { URL, fileURLToPath } = __webpack_require__(57310); -const { NormalModule } = __webpack_require__(91919); + "asset.info.immutable": (immutable, { green, formatFlag }) => + immutable ? green(formatFlag("immutable")) : undefined, + "asset.info.javascriptModule": (javascriptModule, { formatFlag }) => + javascriptModule ? formatFlag("javascript module") : undefined, + "asset.info.sourceFilename": (sourceFilename, { formatFlag }) => + sourceFilename + ? formatFlag( + sourceFilename === true + ? "from source file" + : `from: ${sourceFilename}` + ) + : undefined, + "asset.info.development": (development, { green, formatFlag }) => + development ? green(formatFlag("dev")) : undefined, + "asset.info.hotModuleReplacement": ( + hotModuleReplacement, + { green, formatFlag } + ) => (hotModuleReplacement ? green(formatFlag("hmr")) : undefined), + "asset.separator!": () => "\n", + "asset.filteredRelated": (filteredRelated, { asset: { related } }) => + filteredRelated > 0 + ? `${moreCount(related, filteredRelated)} related ${plural( + filteredRelated, + "asset", + "assets" + )}` + : undefined, + "asset.filteredChildren": (filteredChildren, { asset: { children } }) => + filteredChildren > 0 + ? `${moreCount(children, filteredChildren)} ${plural( + filteredChildren, + "asset", + "assets" + )}` + : undefined, -/** @typedef {import("../Compiler")} Compiler */ + assetChunk: (id, { formatChunkId }) => formatChunkId(id), -class FileUriPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "FileUriPlugin", - (compilation, { normalModuleFactory }) => { - normalModuleFactory.hooks.resolveForScheme - .for("file") - .tap("FileUriPlugin", resourceData => { - const url = new URL(resourceData.resource); - const path = fileURLToPath(url); - const query = url.search; - const fragment = url.hash; - resourceData.path = path; - resourceData.query = query; - resourceData.fragment = fragment; - resourceData.resource = path + query + fragment; - return true; - }); - const hooks = NormalModule.getCompilationHooks(compilation); - hooks.readResource - .for(undefined) - .tapAsync("FileUriPlugin", (loaderContext, callback) => { - const { resourcePath } = loaderContext; - loaderContext.addDependency(resourcePath); - loaderContext.fs.readFile(resourcePath, callback); - }); + assetChunkName: name => name, + assetChunkIdHint: name => name, + + "module.type": type => (type !== "module" ? type : undefined), + "module.id": (id, { formatModuleId }) => + isValidId(id) ? formatModuleId(id) : undefined, + "module.name": (name, { bold }) => { + const [prefix, resource] = getModuleName(name); + return `${prefix || ""}${bold(resource || "")}`; + }, + "module.identifier": identifier => undefined, + "module.layer": (layer, { formatLayer }) => + layer ? formatLayer(layer) : undefined, + "module.sizes": printSizes, + "module.chunks[]": (id, { formatChunkId }) => formatChunkId(id), + "module.depth": (depth, { formatFlag }) => + depth !== null ? formatFlag(`depth ${depth}`) : undefined, + "module.cacheable": (cacheable, { formatFlag, red }) => + cacheable === false ? red(formatFlag("not cacheable")) : undefined, + "module.orphan": (orphan, { formatFlag, yellow }) => + orphan ? yellow(formatFlag("orphan")) : undefined, + "module.runtime": (runtime, { formatFlag, yellow }) => + runtime ? yellow(formatFlag("runtime")) : undefined, + "module.optional": (optional, { formatFlag, yellow }) => + optional ? yellow(formatFlag("optional")) : undefined, + "module.dependent": (dependent, { formatFlag, cyan }) => + dependent ? cyan(formatFlag("dependent")) : undefined, + "module.built": (built, { formatFlag, yellow }) => + built ? yellow(formatFlag("built")) : undefined, + "module.codeGenerated": (codeGenerated, { formatFlag, yellow }) => + codeGenerated ? yellow(formatFlag("code generated")) : undefined, + "module.buildTimeExecuted": (buildTimeExecuted, { formatFlag, green }) => + buildTimeExecuted ? green(formatFlag("build time executed")) : undefined, + "module.cached": (cached, { formatFlag, green }) => + cached ? green(formatFlag("cached")) : undefined, + "module.assets": (assets, { formatFlag, magenta }) => + assets && assets.length + ? magenta( + formatFlag( + `${assets.length} ${plural(assets.length, "asset", "assets")}` + ) + ) + : undefined, + "module.warnings": (warnings, { formatFlag, yellow }) => + warnings === true + ? yellow(formatFlag("warnings")) + : warnings + ? yellow( + formatFlag(`${warnings} ${plural(warnings, "warning", "warnings")}`) + ) + : undefined, + "module.errors": (errors, { formatFlag, red }) => + errors === true + ? red(formatFlag("errors")) + : errors + ? red(formatFlag(`${errors} ${plural(errors, "error", "errors")}`)) + : undefined, + "module.providedExports": (providedExports, { formatFlag, cyan }) => { + if (Array.isArray(providedExports)) { + if (providedExports.length === 0) return cyan(formatFlag("no exports")); + return cyan(formatFlag(`exports: ${providedExports.join(", ")}`)); + } + }, + "module.usedExports": (usedExports, { formatFlag, cyan, module }) => { + if (usedExports !== true) { + if (usedExports === null) return cyan(formatFlag("used exports unknown")); + if (usedExports === false) return cyan(formatFlag("module unused")); + if (Array.isArray(usedExports)) { + if (usedExports.length === 0) + return cyan(formatFlag("no exports used")); + const providedExportsCount = Array.isArray(module.providedExports) + ? module.providedExports.length + : null; + if ( + providedExportsCount !== null && + providedExportsCount === usedExports.length + ) { + return cyan(formatFlag("all exports used")); + } else { + return cyan( + formatFlag(`only some exports used: ${usedExports.join(", ")}`) + ); + } } - ); - } -} + } + }, + "module.optimizationBailout[]": (optimizationBailout, { yellow }) => + yellow(optimizationBailout), + "module.issuerPath": (issuerPath, { module }) => + module.profile ? undefined : "", + "module.profile": profile => undefined, + "module.filteredModules": (filteredModules, { module: { modules } }) => + filteredModules > 0 + ? `${moreCount(modules, filteredModules)} nested ${plural( + filteredModules, + "module", + "modules" + )}` + : undefined, + "module.filteredReasons": (filteredReasons, { module: { reasons } }) => + filteredReasons > 0 + ? `${moreCount(reasons, filteredReasons)} ${plural( + filteredReasons, + "reason", + "reasons" + )}` + : undefined, + "module.filteredChildren": (filteredChildren, { module: { children } }) => + filteredChildren > 0 + ? `${moreCount(children, filteredChildren)} ${plural( + filteredChildren, + "module", + "modules" + )}` + : undefined, + "module.separator!": () => "\n", -module.exports = FileUriPlugin; + "moduleIssuer.id": (id, { formatModuleId }) => formatModuleId(id), + "moduleIssuer.profile.total": (value, { formatTime }) => formatTime(value), + "moduleReason.type": type => type, + "moduleReason.userRequest": (userRequest, { cyan }) => + cyan(getResourceName(userRequest)), + "moduleReason.moduleId": (moduleId, { formatModuleId }) => + isValidId(moduleId) ? formatModuleId(moduleId) : undefined, + "moduleReason.module": (module, { magenta }) => magenta(module), + "moduleReason.loc": loc => loc, + "moduleReason.explanation": (explanation, { cyan }) => cyan(explanation), + "moduleReason.active": (active, { formatFlag }) => + active ? undefined : formatFlag("inactive"), + "moduleReason.resolvedModule": (module, { magenta }) => magenta(module), + "moduleReason.filteredChildren": ( + filteredChildren, + { moduleReason: { children } } + ) => + filteredChildren > 0 + ? `${moreCount(children, filteredChildren)} ${plural( + filteredChildren, + "reason", + "reasons" + )}` + : undefined, -/***/ }), + "module.profile.total": (value, { formatTime }) => formatTime(value), + "module.profile.resolving": (value, { formatTime }) => + `resolving: ${formatTime(value)}`, + "module.profile.restoring": (value, { formatTime }) => + `restoring: ${formatTime(value)}`, + "module.profile.integration": (value, { formatTime }) => + `integration: ${formatTime(value)}`, + "module.profile.building": (value, { formatTime }) => + `building: ${formatTime(value)}`, + "module.profile.storing": (value, { formatTime }) => + `storing: ${formatTime(value)}`, + "module.profile.additionalResolving": (value, { formatTime }) => + value ? `additional resolving: ${formatTime(value)}` : undefined, + "module.profile.additionalIntegration": (value, { formatTime }) => + value ? `additional integration: ${formatTime(value)}` : undefined, -/***/ 42110: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + "chunkGroup.kind!": (_, { chunkGroupKind }) => chunkGroupKind, + "chunkGroup.separator!": () => "\n", + "chunkGroup.name": (name, { bold }) => bold(name), + "chunkGroup.isOverSizeLimit": (isOverSizeLimit, { formatFlag, yellow }) => + isOverSizeLimit ? yellow(formatFlag("big")) : undefined, + "chunkGroup.assetsSize": (size, { formatSize }) => + size ? formatSize(size) : undefined, + "chunkGroup.auxiliaryAssetsSize": (size, { formatSize }) => + size ? `(${formatSize(size)})` : undefined, + "chunkGroup.filteredAssets": (n, { chunkGroup: { assets } }) => + n > 0 + ? `${moreCount(assets, n)} ${plural(n, "asset", "assets")}` + : undefined, + "chunkGroup.filteredAuxiliaryAssets": ( + n, + { chunkGroup: { auxiliaryAssets } } + ) => + n > 0 + ? `${moreCount(auxiliaryAssets, n)} auxiliary ${plural( + n, + "asset", + "assets" + )}` + : undefined, + "chunkGroup.is!": () => "=", + "chunkGroupAsset.name": (asset, { green }) => green(asset), + "chunkGroupAsset.size": (size, { formatSize, chunkGroup }) => + chunkGroup.assets.length > 1 || + (chunkGroup.auxiliaryAssets && chunkGroup.auxiliaryAssets.length > 0) + ? formatSize(size) + : undefined, + "chunkGroup.children": (children, context, printer) => + Array.isArray(children) + ? undefined + : printer.print( + context.type, + Object.keys(children).map(key => ({ + type: key, + children: children[key] + })), + context + ), + "chunkGroupChildGroup.type": type => `${type}:`, + "chunkGroupChild.assets[]": (file, { formatFilename }) => + formatFilename(file), + "chunkGroupChild.chunks[]": (id, { formatChunkId }) => formatChunkId(id), + "chunkGroupChild.name": name => (name ? `(name: ${name})` : undefined), -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + "chunk.id": (id, { formatChunkId }) => formatChunkId(id), + "chunk.files[]": (file, { formatFilename }) => formatFilename(file), + "chunk.names[]": name => name, + "chunk.idHints[]": name => name, + "chunk.runtime[]": name => name, + "chunk.sizes": (sizes, context) => printSizes(sizes, context), + "chunk.parents[]": (parents, context) => + context.formatChunkId(parents, "parent"), + "chunk.siblings[]": (siblings, context) => + context.formatChunkId(siblings, "sibling"), + "chunk.children[]": (children, context) => + context.formatChunkId(children, "child"), + "chunk.childrenByOrder": (childrenByOrder, context, printer) => + Array.isArray(childrenByOrder) + ? undefined + : printer.print( + context.type, + Object.keys(childrenByOrder).map(key => ({ + type: key, + children: childrenByOrder[key] + })), + context + ), + "chunk.childrenByOrder[].type": type => `${type}:`, + "chunk.childrenByOrder[].children[]": (id, { formatChunkId }) => + isValidId(id) ? formatChunkId(id) : undefined, + "chunk.entry": (entry, { formatFlag, yellow }) => + entry ? yellow(formatFlag("entry")) : undefined, + "chunk.initial": (initial, { formatFlag, yellow }) => + initial ? yellow(formatFlag("initial")) : undefined, + "chunk.rendered": (rendered, { formatFlag, green }) => + rendered ? green(formatFlag("rendered")) : undefined, + "chunk.recorded": (recorded, { formatFlag, green }) => + recorded ? green(formatFlag("recorded")) : undefined, + "chunk.reason": (reason, { yellow }) => (reason ? yellow(reason) : undefined), + "chunk.filteredModules": (filteredModules, { chunk: { modules } }) => + filteredModules > 0 + ? `${moreCount(modules, filteredModules)} chunk ${plural( + filteredModules, + "module", + "modules" + )}` + : undefined, + "chunk.separator!": () => "\n", + "chunkOrigin.request": request => request, + "chunkOrigin.moduleId": (moduleId, { formatModuleId }) => + isValidId(moduleId) ? formatModuleId(moduleId) : undefined, + "chunkOrigin.moduleName": (moduleName, { bold }) => bold(moduleName), + "chunkOrigin.loc": loc => loc, + "error.compilerPath": (compilerPath, { bold }) => + compilerPath ? bold(`(${compilerPath})`) : undefined, + "error.chunkId": (chunkId, { formatChunkId }) => + isValidId(chunkId) ? formatChunkId(chunkId) : undefined, + "error.chunkEntry": (chunkEntry, { formatFlag }) => + chunkEntry ? formatFlag("entry") : undefined, + "error.chunkInitial": (chunkInitial, { formatFlag }) => + chunkInitial ? formatFlag("initial") : undefined, + "error.file": (file, { bold }) => bold(file), + "error.moduleName": (moduleName, { bold }) => { + return moduleName.includes("!") + ? `${bold(moduleName.replace(/^(\s|\S)*!/, ""))} (${moduleName})` + : `${bold(moduleName)}`; + }, + "error.loc": (loc, { green }) => green(loc), + "error.message": (message, { bold, formatError }) => + message.includes("\u001b[") ? message : bold(formatError(message)), + "error.details": (details, { formatError }) => formatError(details), + "error.stack": stack => stack, + "error.moduleTrace": moduleTrace => undefined, + "error.separator!": () => "\n", -const { extname, basename } = __webpack_require__(71017); -const { URL } = __webpack_require__(57310); -const { createGunzip, createBrotliDecompress, createInflate } = __webpack_require__(59796); -const NormalModule = __webpack_require__(39); -const createSchemaValidation = __webpack_require__(32540); -const createHash = __webpack_require__(49835); -const { mkdirp, dirname, join } = __webpack_require__(17139); -const memoize = __webpack_require__(78676); + "loggingEntry(error).loggingEntry.message": (message, { red }) => + mapLines(message, x => ` ${red(x)}`), + "loggingEntry(warn).loggingEntry.message": (message, { yellow }) => + mapLines(message, x => ` ${yellow(x)}`), + "loggingEntry(info).loggingEntry.message": (message, { green }) => + mapLines(message, x => ` ${green(x)}`), + "loggingEntry(log).loggingEntry.message": (message, { bold }) => + mapLines(message, x => ` ${bold(x)}`), + "loggingEntry(debug).loggingEntry.message": message => + mapLines(message, x => ` ${x}`), + "loggingEntry(trace).loggingEntry.message": message => + mapLines(message, x => ` ${x}`), + "loggingEntry(status).loggingEntry.message": (message, { magenta }) => + mapLines(message, x => ` ${magenta(x)}`), + "loggingEntry(profile).loggingEntry.message": (message, { magenta }) => + mapLines(message, x => `

${magenta(x)}`), + "loggingEntry(profileEnd).loggingEntry.message": (message, { magenta }) => + mapLines(message, x => `

${magenta(x)}`), + "loggingEntry(time).loggingEntry.message": (message, { magenta }) => + mapLines(message, x => ` ${magenta(x)}`), + "loggingEntry(group).loggingEntry.message": (message, { cyan }) => + mapLines(message, x => `<-> ${cyan(x)}`), + "loggingEntry(groupCollapsed).loggingEntry.message": (message, { cyan }) => + mapLines(message, x => `<+> ${cyan(x)}`), + "loggingEntry(clear).loggingEntry": () => " -------", + "loggingEntry(groupCollapsed).loggingEntry.children": () => "", + "loggingEntry.trace[]": trace => + trace ? mapLines(trace, x => `| ${x}`) : undefined, -/** @typedef {import("../../declarations/plugins/schemes/HttpUriPlugin").HttpUriPluginOptions} HttpUriPluginOptions */ -/** @typedef {import("../Compiler")} Compiler */ + "moduleTraceItem.originName": originName => originName, -const getHttp = memoize(() => __webpack_require__(13685)); -const getHttps = memoize(() => __webpack_require__(95687)); + loggingGroup: loggingGroup => + loggingGroup.entries.length === 0 ? "" : undefined, + "loggingGroup.debug": (flag, { red }) => (flag ? red("DEBUG") : undefined), + "loggingGroup.name": (name, { bold }) => bold(`LOG from ${name}`), + "loggingGroup.separator!": () => "\n", + "loggingGroup.filteredEntries": filteredEntries => + filteredEntries > 0 ? `+ ${filteredEntries} hidden lines` : undefined, -/** @type {(() => void)[] | undefined} */ -let inProgressWrite = undefined; + "moduleTraceDependency.loc": loc => loc +}; -const validate = createSchemaValidation( - __webpack_require__(67263), - () => __webpack_require__(27256), - { - name: "Http Uri Plugin", - baseDataPath: "options" - } -); +/** @type {Record} */ +const ITEM_NAMES = { + "compilation.assets[]": "asset", + "compilation.modules[]": "module", + "compilation.chunks[]": "chunk", + "compilation.entrypoints[]": "chunkGroup", + "compilation.namedChunkGroups[]": "chunkGroup", + "compilation.errors[]": "error", + "compilation.warnings[]": "error", + "compilation.logging[]": "loggingGroup", + "compilation.children[]": "compilation", + "asset.related[]": "asset", + "asset.children[]": "asset", + "asset.chunks[]": "assetChunk", + "asset.auxiliaryChunks[]": "assetChunk", + "asset.chunkNames[]": "assetChunkName", + "asset.chunkIdHints[]": "assetChunkIdHint", + "asset.auxiliaryChunkNames[]": "assetChunkName", + "asset.auxiliaryChunkIdHints[]": "assetChunkIdHint", + "chunkGroup.assets[]": "chunkGroupAsset", + "chunkGroup.auxiliaryAssets[]": "chunkGroupAsset", + "chunkGroupChild.assets[]": "chunkGroupAsset", + "chunkGroupChild.auxiliaryAssets[]": "chunkGroupAsset", + "chunkGroup.children[]": "chunkGroupChildGroup", + "chunkGroupChildGroup.children[]": "chunkGroupChild", + "module.modules[]": "module", + "module.children[]": "module", + "module.reasons[]": "moduleReason", + "moduleReason.children[]": "moduleReason", + "module.issuerPath[]": "moduleIssuer", + "chunk.origins[]": "chunkOrigin", + "chunk.modules[]": "module", + "loggingGroup.entries[]": logEntry => + `loggingEntry(${logEntry.type}).loggingEntry`, + "loggingEntry.children[]": logEntry => + `loggingEntry(${logEntry.type}).loggingEntry`, + "error.moduleTrace[]": "moduleTraceItem", + "moduleTraceItem.dependencies[]": "moduleTraceDependency" +}; -const toSafePath = str => - str - .replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, "") - .replace(/[^a-zA-Z0-9._-]+/g, "_"); +const ERROR_PREFERRED_ORDER = [ + "compilerPath", + "chunkId", + "chunkEntry", + "chunkInitial", + "file", + "separator!", + "moduleName", + "loc", + "separator!", + "message", + "separator!", + "details", + "separator!", + "stack", + "separator!", + "missing", + "separator!", + "moduleTrace" +]; -const computeIntegrity = content => { - const hash = createHash("sha512"); - hash.update(content); - const integrity = "sha512-" + hash.digest("base64"); - return integrity; +/** @type {Record} */ +const PREFERRED_ORDERS = { + compilation: [ + "name", + "hash", + "version", + "time", + "builtAt", + "env", + "publicPath", + "assets", + "filteredAssets", + "entrypoints", + "namedChunkGroups", + "chunks", + "modules", + "filteredModules", + "children", + "logging", + "warnings", + "warningsInChildren!", + "filteredWarningDetailsCount", + "errors", + "errorsInChildren!", + "filteredErrorDetailsCount", + "summary!", + "needAdditionalPass" + ], + asset: [ + "type", + "name", + "size", + "chunks", + "auxiliaryChunks", + "emitted", + "comparedForEmit", + "cached", + "info", + "isOverSizeLimit", + "chunkNames", + "auxiliaryChunkNames", + "chunkIdHints", + "auxiliaryChunkIdHints", + "related", + "filteredRelated", + "children", + "filteredChildren" + ], + "asset.info": [ + "immutable", + "sourceFilename", + "javascriptModule", + "development", + "hotModuleReplacement" + ], + chunkGroup: [ + "kind!", + "name", + "isOverSizeLimit", + "assetsSize", + "auxiliaryAssetsSize", + "is!", + "assets", + "filteredAssets", + "auxiliaryAssets", + "filteredAuxiliaryAssets", + "separator!", + "children" + ], + chunkGroupAsset: ["name", "size"], + chunkGroupChildGroup: ["type", "children"], + chunkGroupChild: ["assets", "chunks", "name"], + module: [ + "type", + "name", + "identifier", + "id", + "layer", + "sizes", + "chunks", + "depth", + "cacheable", + "orphan", + "runtime", + "optional", + "dependent", + "built", + "codeGenerated", + "cached", + "assets", + "failed", + "warnings", + "errors", + "children", + "filteredChildren", + "providedExports", + "usedExports", + "optimizationBailout", + "reasons", + "filteredReasons", + "issuerPath", + "profile", + "modules", + "filteredModules" + ], + moduleReason: [ + "active", + "type", + "userRequest", + "moduleId", + "module", + "resolvedModule", + "loc", + "explanation", + "children", + "filteredChildren" + ], + "module.profile": [ + "total", + "separator!", + "resolving", + "restoring", + "integration", + "building", + "storing", + "additionalResolving", + "additionalIntegration" + ], + chunk: [ + "id", + "runtime", + "files", + "names", + "idHints", + "sizes", + "parents", + "siblings", + "children", + "childrenByOrder", + "entry", + "initial", + "rendered", + "recorded", + "reason", + "separator!", + "origins", + "separator!", + "modules", + "separator!", + "filteredModules" + ], + chunkOrigin: ["request", "moduleId", "moduleName", "loc"], + error: ERROR_PREFERRED_ORDER, + warning: ERROR_PREFERRED_ORDER, + "chunk.childrenByOrder[]": ["type", "children"], + loggingGroup: [ + "debug", + "name", + "separator!", + "entries", + "separator!", + "filteredEntries" + ], + loggingEntry: ["message", "trace", "children"] }; -const verifyIntegrity = (content, integrity) => { - if (integrity === "ignore") return true; - return computeIntegrity(content) === integrity; +const itemsJoinOneLine = items => items.filter(Boolean).join(" "); +const itemsJoinOneLineBrackets = items => + items.length > 0 ? `(${items.filter(Boolean).join(" ")})` : undefined; +const itemsJoinMoreSpacing = items => items.filter(Boolean).join("\n\n"); +const itemsJoinComma = items => items.filter(Boolean).join(", "); +const itemsJoinCommaBrackets = items => + items.length > 0 ? `(${items.filter(Boolean).join(", ")})` : undefined; +const itemsJoinCommaBracketsWithName = name => items => + items.length > 0 + ? `(${name}: ${items.filter(Boolean).join(", ")})` + : undefined; + +/** @type {Record string>} */ +const SIMPLE_ITEMS_JOINER = { + "chunk.parents": itemsJoinOneLine, + "chunk.siblings": itemsJoinOneLine, + "chunk.children": itemsJoinOneLine, + "chunk.names": itemsJoinCommaBrackets, + "chunk.idHints": itemsJoinCommaBracketsWithName("id hint"), + "chunk.runtime": itemsJoinCommaBracketsWithName("runtime"), + "chunk.files": itemsJoinComma, + "chunk.childrenByOrder": itemsJoinOneLine, + "chunk.childrenByOrder[].children": itemsJoinOneLine, + "chunkGroup.assets": itemsJoinOneLine, + "chunkGroup.auxiliaryAssets": itemsJoinOneLineBrackets, + "chunkGroupChildGroup.children": itemsJoinComma, + "chunkGroupChild.assets": itemsJoinOneLine, + "chunkGroupChild.auxiliaryAssets": itemsJoinOneLineBrackets, + "asset.chunks": itemsJoinComma, + "asset.auxiliaryChunks": itemsJoinCommaBrackets, + "asset.chunkNames": itemsJoinCommaBracketsWithName("name"), + "asset.auxiliaryChunkNames": itemsJoinCommaBracketsWithName("auxiliary name"), + "asset.chunkIdHints": itemsJoinCommaBracketsWithName("id hint"), + "asset.auxiliaryChunkIdHints": + itemsJoinCommaBracketsWithName("auxiliary id hint"), + "module.chunks": itemsJoinOneLine, + "module.issuerPath": items => + items + .filter(Boolean) + .map(item => `${item} ->`) + .join(" "), + "compilation.errors": itemsJoinMoreSpacing, + "compilation.warnings": itemsJoinMoreSpacing, + "compilation.logging": itemsJoinMoreSpacing, + "compilation.children": items => indent(itemsJoinMoreSpacing(items), " "), + "moduleTraceItem.dependencies": itemsJoinOneLine, + "loggingEntry.children": items => + indent(items.filter(Boolean).join("\n"), " ", false) }; -/** - * @param {string} str input - * @returns {Record} parsed - */ -const parseKeyValuePairs = str => { - /** @type {Record} */ - const result = {}; - for (const item of str.split(",")) { - const i = item.indexOf("="); - if (i >= 0) { - const key = item.slice(0, i).trim(); - const value = item.slice(i + 1).trim(); - result[key] = value; - } else { - const key = item.trim(); - if (!key) continue; - result[key] = key; - } - } - return result; -}; +const joinOneLine = items => + items + .map(item => item.content) + .filter(Boolean) + .join(" "); -const parseCacheControl = (cacheControl, requestTime) => { - // When false resource is not stored in cache - let storeCache = true; - // When false resource is not stored in lockfile cache - let storeLock = true; - // Resource is only revalidated, after that timestamp and when upgrade is chosen - let validUntil = 0; - if (cacheControl) { - const parsed = parseKeyValuePairs(cacheControl); - if (parsed["no-cache"]) storeCache = storeLock = false; - if (parsed["max-age"] && !isNaN(+parsed["max-age"])) { - validUntil = requestTime + +parsed["max-age"] * 1000; +const joinInBrackets = items => { + const res = []; + let mode = 0; + for (const item of items) { + if (item.element === "separator!") { + switch (mode) { + case 0: + case 1: + mode += 2; + break; + case 4: + res.push(")"); + mode = 3; + break; + } } - if (parsed["must-revalidate"]) validUntil = 0; + if (!item.content) continue; + switch (mode) { + case 0: + mode = 1; + break; + case 1: + res.push(" "); + break; + case 2: + res.push("("); + mode = 4; + break; + case 3: + res.push(" ("); + mode = 4; + break; + case 4: + res.push(", "); + break; + } + res.push(item.content); } - return { - storeLock, - storeCache, - validUntil - }; + if (mode === 4) res.push(")"); + return res.join(""); }; -/** - * @typedef {Object} LockfileEntry - * @property {string} resolved - * @property {string} integrity - * @property {string} contentType - */ - -const areLockfileEntriesEqual = (a, b) => { - return ( - a.resolved === b.resolved && - a.integrity === b.integrity && - a.contentType === b.contentType - ); +const indent = (str, prefix, noPrefixInFirstLine) => { + const rem = str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); + if (noPrefixInFirstLine) return rem; + const ind = str[0] === "\n" ? "" : prefix; + return ind + rem; }; -const entryToString = entry => { - return `resolved: ${entry.resolved}, integrity: ${entry.integrity}, contentType: ${entry.contentType}`; +const joinExplicitNewLine = (items, indenter) => { + let firstInLine = true; + let first = true; + return items + .map(item => { + if (!item || !item.content) return; + let content = indent(item.content, first ? "" : indenter, !firstInLine); + if (firstInLine) { + content = content.replace(/^\n+/, ""); + } + if (!content) return; + first = false; + const noJoiner = firstInLine || content.startsWith("\n"); + firstInLine = content.endsWith("\n"); + return noJoiner ? content : " " + content; + }) + .filter(Boolean) + .join("") + .trim(); }; -class Lockfile { - constructor() { - this.version = 1; - /** @type {Map} */ - this.entries = new Map(); - } +const joinError = + error => + (items, { red, yellow }) => + `${error ? red("ERROR") : yellow("WARNING")} in ${joinExplicitNewLine( + items, + "" + )}`; - static parse(content) { - // TODO handle merge conflicts - const data = JSON.parse(content); - if (data.version !== 1) - throw new Error(`Unsupported lockfile version ${data.version}`); - const lockfile = new Lockfile(); - for (const key of Object.keys(data)) { - if (key === "version") continue; - const entry = data[key]; - lockfile.entries.set( - key, - typeof entry === "string" - ? entry - : { - resolved: key, - ...entry - } - ); +/** @type {Record string>} */ +const SIMPLE_ELEMENT_JOINERS = { + compilation: items => { + const result = []; + let lastNeedMore = false; + for (const item of items) { + if (!item.content) continue; + const needMoreSpace = + item.element === "warnings" || + item.element === "filteredWarningDetailsCount" || + item.element === "errors" || + item.element === "filteredErrorDetailsCount" || + item.element === "logging"; + if (result.length !== 0) { + result.push(needMoreSpace || lastNeedMore ? "\n\n" : "\n"); + } + result.push(item.content); + lastNeedMore = needMoreSpace; } - return lockfile; - } - - toString() { - let str = "{\n"; - const entries = Array.from(this.entries).sort(([a], [b]) => - a < b ? -1 : 1 + if (lastNeedMore) result.push("\n"); + return result.join(""); + }, + asset: items => + joinExplicitNewLine( + items.map(item => { + if ( + (item.element === "related" || item.element === "children") && + item.content + ) { + return { + ...item, + content: `\n${item.content}\n` + }; + } + return item; + }), + " " + ), + "asset.info": joinOneLine, + module: (items, { module }) => { + let hasName = false; + return joinExplicitNewLine( + items.map(item => { + switch (item.element) { + case "id": + if (module.id === module.name) { + if (hasName) return false; + if (item.content) hasName = true; + } + break; + case "name": + if (hasName) return false; + if (item.content) hasName = true; + break; + case "providedExports": + case "usedExports": + case "optimizationBailout": + case "reasons": + case "issuerPath": + case "profile": + case "children": + case "modules": + if (item.content) { + return { + ...item, + content: `\n${item.content}\n` + }; + } + break; + } + return item; + }), + " " ); - for (const [key, entry] of entries) { - if (typeof entry === "string") { - str += ` ${JSON.stringify(key)}: ${JSON.stringify(entry)},\n`; - } else { - str += ` ${JSON.stringify(key)}: { `; - if (entry.resolved !== key) - str += `"resolved": ${JSON.stringify(entry.resolved)}, `; - str += `"integrity": ${JSON.stringify( - entry.integrity - )}, "contentType": ${JSON.stringify(entry.contentType)} },\n`; + }, + chunk: items => { + let hasEntry = false; + return ( + "chunk " + + joinExplicitNewLine( + items.filter(item => { + switch (item.element) { + case "entry": + if (item.content) hasEntry = true; + break; + case "initial": + if (hasEntry) return false; + break; + } + return true; + }), + " " + ) + ); + }, + "chunk.childrenByOrder[]": items => `(${joinOneLine(items)})`, + chunkGroup: items => joinExplicitNewLine(items, " "), + chunkGroupAsset: joinOneLine, + chunkGroupChildGroup: joinOneLine, + chunkGroupChild: joinOneLine, + // moduleReason: (items, { moduleReason }) => { + // let hasName = false; + // return joinOneLine( + // items.filter(item => { + // switch (item.element) { + // case "moduleId": + // if (moduleReason.moduleId === moduleReason.module && item.content) + // hasName = true; + // break; + // case "module": + // if (hasName) return false; + // break; + // case "resolvedModule": + // return ( + // moduleReason.module !== moduleReason.resolvedModule && + // item.content + // ); + // } + // return true; + // }) + // ); + // }, + moduleReason: (items, { moduleReason }) => { + let hasName = false; + return joinExplicitNewLine( + items.map(item => { + switch (item.element) { + case "moduleId": + if (moduleReason.moduleId === moduleReason.module && item.content) + hasName = true; + break; + case "module": + if (hasName) return false; + break; + case "resolvedModule": + if (moduleReason.module === moduleReason.resolvedModule) + return false; + break; + case "children": + if (item.content) { + return { + ...item, + content: `\n${item.content}\n` + }; + } + break; + } + return item; + }), + " " + ); + }, + "module.profile": joinInBrackets, + moduleIssuer: joinOneLine, + chunkOrigin: items => "> " + joinOneLine(items), + "errors[].error": joinError(true), + "warnings[].error": joinError(false), + loggingGroup: items => joinExplicitNewLine(items, "").trimRight(), + moduleTraceItem: items => " @ " + joinOneLine(items), + moduleTraceDependency: joinOneLine +}; + +const AVAILABLE_COLORS = { + bold: "\u001b[1m", + yellow: "\u001b[1m\u001b[33m", + red: "\u001b[1m\u001b[31m", + green: "\u001b[1m\u001b[32m", + cyan: "\u001b[1m\u001b[36m", + magenta: "\u001b[1m\u001b[35m" +}; + +const AVAILABLE_FORMATS = { + formatChunkId: (id, { yellow }, direction) => { + switch (direction) { + case "parent": + return `<{${yellow(id)}}>`; + case "sibling": + return `={${yellow(id)}}=`; + case "child": + return `>{${yellow(id)}}<`; + default: + return `{${yellow(id)}}`; + } + }, + formatModuleId: id => `[${id}]`, + formatFilename: (filename, { green, yellow }, oversize) => + (oversize ? yellow : green)(filename), + formatFlag: flag => `[${flag}]`, + formatLayer: layer => `(in ${layer})`, + formatSize: (__webpack_require__(71070).formatSize), + formatDateTime: (dateTime, { bold }) => { + const d = new Date(dateTime); + const x = twoDigit; + const date = `${d.getFullYear()}-${x(d.getMonth() + 1)}-${x(d.getDate())}`; + const time = `${x(d.getHours())}:${x(d.getMinutes())}:${x(d.getSeconds())}`; + return `${date} ${bold(time)}`; + }, + formatTime: ( + time, + { timeReference, bold, green, yellow, red }, + boldQuantity + ) => { + const unit = " ms"; + if (timeReference && time !== timeReference) { + const times = [ + timeReference / 2, + timeReference / 4, + timeReference / 8, + timeReference / 16 + ]; + if (time < times[3]) return `${time}${unit}`; + else if (time < times[2]) return bold(`${time}${unit}`); + else if (time < times[1]) return green(`${time}${unit}`); + else if (time < times[0]) return yellow(`${time}${unit}`); + else return red(`${time}${unit}`); + } else { + return `${boldQuantity ? bold(time) : time}${unit}`; + } + }, + formatError: (message, { green, yellow, red }) => { + if (message.includes("\u001b[")) return message; + const highlights = [ + { regExp: /(Did you mean .+)/g, format: green }, + { + regExp: /(Set 'mode' option to 'development' or 'production')/g, + format: green + }, + { regExp: /(\(module has no exports\))/g, format: red }, + { regExp: /\(possible exports: (.+)\)/g, format: green }, + { regExp: /(?:^|\n)(.* doesn't exist)/g, format: red }, + { regExp: /('\w+' option has not been set)/g, format: red }, + { + regExp: /(Emitted value instead of an instance of Error)/g, + format: yellow + }, + { regExp: /(Used? .+ instead)/gi, format: yellow }, + { regExp: /\b(deprecated|must|required)\b/g, format: yellow }, + { + regExp: /\b(BREAKING CHANGE)\b/gi, + format: red + }, + { + regExp: + /\b(error|failed|unexpected|invalid|not found|not supported|not available|not possible|not implemented|doesn't support|conflict|conflicting|not existing|duplicate)\b/gi, + format: red } + ]; + for (const { regExp, format } of highlights) { + message = message.replace(regExp, (match, content) => { + return match.replace(content, format(content)); + }); } - str += ` "version": ${this.version}\n}\n`; - return str; + return message; } -} +}; -/** - * @template R - * @param {function(function(Error=, R=): void): void} fn function - * @returns {function(function((Error | null)=, R=): void): void} cached function - */ -const cachedWithoutKey = fn => { - let inFlight = false; - /** @type {Error | undefined} */ - let cachedError = undefined; - /** @type {R | undefined} */ - let cachedResult = undefined; - /** @type {(function(Error=, R=): void)[] | undefined} */ - let cachedCallbacks = undefined; - return callback => { - if (inFlight) { - if (cachedResult !== undefined) return callback(null, cachedResult); - if (cachedError !== undefined) return callback(cachedError); - if (cachedCallbacks === undefined) cachedCallbacks = [callback]; - else cachedCallbacks.push(callback); - return; - } - inFlight = true; - fn((err, result) => { - if (err) cachedError = err; - else cachedResult = result; - const callbacks = cachedCallbacks; - cachedCallbacks = undefined; - callback(err, result); - if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); - }); - }; +const RESULT_MODIFIER = { + "module.modules": result => { + return indent(result, "| "); + } }; -/** - * @template T - * @template R - * @param {function(T, function(Error=, R=): void): void} fn function - * @param {function(T, function(Error=, R=): void): void=} forceFn function for the second try - * @returns {(function(T, function((Error | null)=, R=): void): void) & { force: function(T, function((Error | null)=, R=): void): void }} cached function - */ -const cachedWithKey = (fn, forceFn = fn) => { - /** @typedef {{ result?: R, error?: Error, callbacks?: (function((Error | null)=, R=): void)[], force?: true }} CacheEntry */ - /** @type {Map} */ - const cache = new Map(); - const resultFn = (arg, callback) => { - const cacheEntry = cache.get(arg); - if (cacheEntry !== undefined) { - if (cacheEntry.result !== undefined) - return callback(null, cacheEntry.result); - if (cacheEntry.error !== undefined) return callback(cacheEntry.error); - if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback]; - else cacheEntry.callbacks.push(callback); - return; +const createOrder = (array, preferredOrder) => { + const originalArray = array.slice(); + const set = new Set(array); + const usedSet = new Set(); + array.length = 0; + for (const element of preferredOrder) { + if (element.endsWith("!") || set.has(element)) { + array.push(element); + usedSet.add(element); } - /** @type {CacheEntry} */ - const newCacheEntry = { - result: undefined, - error: undefined, - callbacks: undefined - }; - cache.set(arg, newCacheEntry); - fn(arg, (err, result) => { - if (err) newCacheEntry.error = err; - else newCacheEntry.result = result; - const callbacks = newCacheEntry.callbacks; - newCacheEntry.callbacks = undefined; - callback(err, result); - if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); - }); - }; - resultFn.force = (arg, callback) => { - const cacheEntry = cache.get(arg); - if (cacheEntry !== undefined && cacheEntry.force) { - if (cacheEntry.result !== undefined) - return callback(null, cacheEntry.result); - if (cacheEntry.error !== undefined) return callback(cacheEntry.error); - if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback]; - else cacheEntry.callbacks.push(callback); - return; + } + for (const element of originalArray) { + if (!usedSet.has(element)) { + array.push(element); } - /** @type {CacheEntry} */ - const newCacheEntry = { - result: undefined, - error: undefined, - callbacks: undefined, - force: true - }; - cache.set(arg, newCacheEntry); - forceFn(arg, (err, result) => { - if (err) newCacheEntry.error = err; - else newCacheEntry.result = result; - const callbacks = newCacheEntry.callbacks; - newCacheEntry.callbacks = undefined; - callback(err, result); - if (callbacks !== undefined) for (const cb of callbacks) cb(err, result); - }); - }; - return resultFn; -}; - -class HttpUriPlugin { - /** - * @param {HttpUriPluginOptions} options options - */ - constructor(options) { - validate(options); - this._lockfileLocation = options.lockfileLocation; - this._cacheLocation = options.cacheLocation; - this._upgrade = options.upgrade; - this._frozen = options.frozen; - this._allowedUris = options.allowedUris; } + return array; +}; +class DefaultStatsPrinterPlugin { /** * Apply the plugin * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - const schemes = [ - { - scheme: "http", - fetch: (url, options, callback) => getHttp().get(url, options, callback) - }, - { - scheme: "https", - fetch: (url, options, callback) => - getHttps().get(url, options, callback) - } - ]; - let lockfileCache; - compiler.hooks.compilation.tap( - "HttpUriPlugin", - (compilation, { normalModuleFactory }) => { - const intermediateFs = compiler.intermediateFileSystem; - const fs = compilation.inputFileSystem; - const cache = compilation.getCache("webpack.HttpUriPlugin"); - const logger = compilation.getLogger("webpack.HttpUriPlugin"); - const lockfileLocation = - this._lockfileLocation || - join( - intermediateFs, - compiler.context, - compiler.name - ? `${toSafePath(compiler.name)}.webpack.lock` - : "webpack.lock" - ); - const cacheLocation = - this._cacheLocation !== undefined - ? this._cacheLocation - : lockfileLocation + ".data"; - const upgrade = this._upgrade || false; - const frozen = this._frozen || false; - const hashFunction = "sha512"; - const hashDigest = "hex"; - const hashDigestLength = 20; - const allowedUris = this._allowedUris; - - let warnedAboutEol = false; - - const cacheKeyCache = new Map(); - /** - * @param {string} url the url - * @returns {string} the key - */ - const getCacheKey = url => { - const cachedResult = cacheKeyCache.get(url); - if (cachedResult !== undefined) return cachedResult; - const result = _getCacheKey(url); - cacheKeyCache.set(url, result); - return result; - }; - - /** - * @param {string} url the url - * @returns {string} the key - */ - const _getCacheKey = url => { - const parsedUrl = new URL(url); - const folder = toSafePath(parsedUrl.origin); - const name = toSafePath(parsedUrl.pathname); - const query = toSafePath(parsedUrl.search); - let ext = extname(name); - if (ext.length > 20) ext = ""; - const basename = ext ? name.slice(0, -ext.length) : name; - const hash = createHash(hashFunction); - hash.update(url); - const digest = hash.digest(hashDigest).slice(0, hashDigestLength); - return `${folder.slice(-50)}/${`${basename}${ - query ? `_${query}` : "" - }`.slice(0, 150)}_${digest}${ext}`; - }; - - const getLockfile = cachedWithoutKey( - /** - * @param {function((Error | null)=, Lockfile=): void} callback callback - * @returns {void} - */ - callback => { - const readLockfile = () => { - intermediateFs.readFile(lockfileLocation, (err, buffer) => { - if (err && err.code !== "ENOENT") { - compilation.missingDependencies.add(lockfileLocation); - return callback(err); - } - compilation.fileDependencies.add(lockfileLocation); - compilation.fileSystemInfo.createSnapshot( - compiler.fsStartTime, - buffer ? [lockfileLocation] : [], - [], - buffer ? [] : [lockfileLocation], - { timestamp: true }, - (err, snapshot) => { - if (err) return callback(err); - const lockfile = buffer - ? Lockfile.parse(buffer.toString("utf-8")) - : new Lockfile(); - lockfileCache = { - lockfile, - snapshot - }; - callback(null, lockfile); - } - ); - }); - }; - if (lockfileCache) { - compilation.fileSystemInfo.checkSnapshotValid( - lockfileCache.snapshot, - (err, valid) => { - if (err) return callback(err); - if (!valid) return readLockfile(); - callback(null, lockfileCache.lockfile); - } - ); - } else { - readLockfile(); - } - } - ); - - /** @type {Map | undefined} */ - let lockfileUpdates = undefined; - const storeLockEntry = (lockfile, url, entry) => { - const oldEntry = lockfile.entries.get(url); - if (lockfileUpdates === undefined) lockfileUpdates = new Map(); - lockfileUpdates.set(url, entry); - lockfile.entries.set(url, entry); - if (!oldEntry) { - logger.log(`${url} added to lockfile`); - } else if (typeof oldEntry === "string") { - if (typeof entry === "string") { - logger.log(`${url} updated in lockfile: ${oldEntry} -> ${entry}`); - } else { - logger.log( - `${url} updated in lockfile: ${oldEntry} -> ${entry.resolved}` - ); - } - } else if (typeof entry === "string") { - logger.log( - `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry}` - ); - } else if (oldEntry.resolved !== entry.resolved) { - logger.log( - `${url} updated in lockfile: ${oldEntry.resolved} -> ${entry.resolved}` - ); - } else if (oldEntry.integrity !== entry.integrity) { - logger.log(`${url} updated in lockfile: content changed`); - } else if (oldEntry.contentType !== entry.contentType) { - logger.log( - `${url} updated in lockfile: ${oldEntry.contentType} -> ${entry.contentType}` - ); - } else { - logger.log(`${url} updated in lockfile`); - } - }; - - const storeResult = (lockfile, url, result, callback) => { - if (result.storeLock) { - storeLockEntry(lockfile, url, result.entry); - if (!cacheLocation || !result.content) - return callback(null, result); - const key = getCacheKey(result.entry.resolved); - const filePath = join(intermediateFs, cacheLocation, key); - mkdirp(intermediateFs, dirname(intermediateFs, filePath), err => { - if (err) return callback(err); - intermediateFs.writeFile(filePath, result.content, err => { - if (err) return callback(err); - callback(null, result); - }); - }); - } else { - storeLockEntry(lockfile, url, "no-cache"); - callback(null, result); - } - }; - - for (const { scheme, fetch } of schemes) { - /** - * - * @param {string} url URL - * @param {string} integrity integrity - * @param {function((Error | null)=, { entry: LockfileEntry, content: Buffer, storeLock: boolean }=): void} callback callback - */ - const resolveContent = (url, integrity, callback) => { - const handleResult = (err, result) => { - if (err) return callback(err); - if ("location" in result) { - return resolveContent( - result.location, - integrity, - (err, innerResult) => { - if (err) return callback(err); - callback(null, { - entry: innerResult.entry, - content: innerResult.content, - storeLock: innerResult.storeLock && result.storeLock - }); - } - ); - } else { - if ( - !result.fresh && - integrity && - result.entry.integrity !== integrity && - !verifyIntegrity(result.content, integrity) - ) { - return fetchContent.force(url, handleResult); - } - return callback(null, { - entry: result.entry, - content: result.content, - storeLock: result.storeLock - }); - } - }; - fetchContent(url, handleResult); - }; - - /** @typedef {{ storeCache: boolean, storeLock: boolean, validUntil: number, etag: string | undefined, fresh: boolean }} FetchResultMeta */ - /** @typedef {FetchResultMeta & { location: string }} RedirectFetchResult */ - /** @typedef {FetchResultMeta & { entry: LockfileEntry, content: Buffer }} ContentFetchResult */ - /** @typedef {RedirectFetchResult | ContentFetchResult} FetchResult */ - - /** - * @param {string} url URL - * @param {FetchResult} cachedResult result from cache - * @param {function((Error | null)=, FetchResult=): void} callback callback - * @returns {void} - */ - const fetchContentRaw = (url, cachedResult, callback) => { - const requestTime = Date.now(); - fetch( - new URL(url), - { - headers: { - "accept-encoding": "gzip, deflate, br", - "user-agent": "webpack", - "if-none-match": cachedResult - ? cachedResult.etag || null - : null - } - }, - res => { - const etag = res.headers["etag"]; - const location = res.headers["location"]; - const cacheControl = res.headers["cache-control"]; - const { storeLock, storeCache, validUntil } = parseCacheControl( - cacheControl, - requestTime - ); - /** - * @param {Partial> & (Pick | Pick)} partialResult result - * @returns {void} - */ - const finishWith = partialResult => { - if ("location" in partialResult) { - logger.debug( - `GET ${url} [${res.statusCode}] -> ${partialResult.location}` - ); - } else { - logger.debug( - `GET ${url} [${res.statusCode}] ${Math.ceil( - partialResult.content.length / 1024 - )} kB${!storeLock ? " no-cache" : ""}` - ); - } - const result = { - ...partialResult, - fresh: true, - storeLock, - storeCache, - validUntil, - etag - }; - if (!storeCache) { - logger.log( - `${url} can't be stored in cache, due to Cache-Control header: ${cacheControl}` - ); - return callback(null, result); - } - cache.store( - url, - null, - { - ...result, - fresh: false - }, - err => { - if (err) { - logger.warn( - `${url} can't be stored in cache: ${err.message}` - ); - logger.debug(err.stack); - } - callback(null, result); - } - ); - }; - if (res.statusCode === 304) { - if ( - cachedResult.validUntil < validUntil || - cachedResult.storeLock !== storeLock || - cachedResult.storeCache !== storeCache || - cachedResult.etag !== etag - ) { - return finishWith(cachedResult); - } else { - logger.debug(`GET ${url} [${res.statusCode}] (unchanged)`); - return callback(null, { - ...cachedResult, - fresh: true - }); - } - } - if ( - location && - res.statusCode >= 301 && - res.statusCode <= 308 - ) { - return finishWith({ - location: new URL(location, url).href - }); - } - const contentType = res.headers["content-type"] || ""; - const bufferArr = []; - - const contentEncoding = res.headers["content-encoding"]; - let stream = res; - if (contentEncoding === "gzip") { - stream = stream.pipe(createGunzip()); - } else if (contentEncoding === "br") { - stream = stream.pipe(createBrotliDecompress()); - } else if (contentEncoding === "deflate") { - stream = stream.pipe(createInflate()); - } - - stream.on("data", chunk => { - bufferArr.push(chunk); - }); - - stream.on("end", () => { - if (!res.complete) { - logger.log(`GET ${url} [${res.statusCode}] (terminated)`); - return callback(new Error(`${url} request was terminated`)); - } - - const content = Buffer.concat(bufferArr); - - if (res.statusCode !== 200) { - logger.log(`GET ${url} [${res.statusCode}]`); - return callback( - new Error( - `${url} request status code = ${ - res.statusCode - }\n${content.toString("utf-8")}` - ) - ); - } - - const integrity = computeIntegrity(content); - const entry = { resolved: url, integrity, contentType }; - - finishWith({ - entry, - content - }); - }); - } - ).on("error", err => { - logger.log(`GET ${url} (error)`); - err.message += `\nwhile fetching ${url}`; - callback(err); - }); - }; - - const fetchContent = cachedWithKey( - /** - * @param {string} url URL - * @param {function((Error | null)=, { validUntil: number, etag?: string, entry: LockfileEntry, content: Buffer, fresh: boolean } | { validUntil: number, etag?: string, location: string, fresh: boolean }=): void} callback callback - * @returns {void} - */ (url, callback) => { - cache.get(url, null, (err, cachedResult) => { - if (err) return callback(err); - if (cachedResult) { - const isValid = cachedResult.validUntil >= Date.now(); - if (isValid) return callback(null, cachedResult); - } - fetchContentRaw(url, cachedResult, callback); - }); - }, - (url, callback) => fetchContentRaw(url, undefined, callback) - ); - - const isAllowed = uri => { - for (const allowed of allowedUris) { - if (typeof allowed === "string") { - if (uri.startsWith(allowed)) return true; - } else if (typeof allowed === "function") { - if (allowed(uri)) return true; - } else { - if (allowed.test(uri)) return true; - } - } - return false; - }; - - const getInfo = cachedWithKey( - /** - * @param {string} url the url - * @param {function((Error | null)=, { entry: LockfileEntry, content: Buffer }=): void} callback callback - * @returns {void} - */ - (url, callback) => { - if (!isAllowed(url)) { - return callback( - new Error( - `${url} doesn't match the allowedUris policy. These URIs are allowed:\n${allowedUris - .map(uri => ` - ${uri}`) - .join("\n")}` - ) - ); - } - getLockfile((err, lockfile) => { - if (err) return callback(err); - const entryOrString = lockfile.entries.get(url); - if (!entryOrString) { - if (frozen) { - return callback( - new Error( - `${url} has no lockfile entry and lockfile is frozen` - ) - ); + compiler.hooks.compilation.tap("DefaultStatsPrinterPlugin", compilation => { + compilation.hooks.statsPrinter.tap( + "DefaultStatsPrinterPlugin", + (stats, options, context) => { + // Put colors into context + stats.hooks.print + .for("compilation") + .tap("DefaultStatsPrinterPlugin", (compilation, context) => { + for (const color of Object.keys(AVAILABLE_COLORS)) { + let start; + if (options.colors) { + if ( + typeof options.colors === "object" && + typeof options.colors[color] === "string" + ) { + start = options.colors[color]; + } else { + start = AVAILABLE_COLORS[color]; } - resolveContent(url, null, (err, result) => { - if (err) return callback(err); - storeResult(lockfile, url, result, callback); - }); - return; - } - if (typeof entryOrString === "string") { - const entryTag = entryOrString; - resolveContent(url, null, (err, result) => { - if (err) return callback(err); - if (!result.storeLock || entryTag === "ignore") - return callback(null, result); - if (frozen) { - return callback( - new Error( - `${url} used to have ${entryTag} lockfile entry and has content now, but lockfile is frozen` - ) - ); - } - if (!upgrade) { - return callback( - new Error( - `${url} used to have ${entryTag} lockfile entry and has content now. -This should be reflected in the lockfile, so this lockfile entry must be upgraded, but upgrading is not enabled. -Remove this line from the lockfile to force upgrading.` - ) - ); - } - storeResult(lockfile, url, result, callback); - }); - return; } - let entry = entryOrString; - const doFetch = lockedContent => { - resolveContent(url, entry.integrity, (err, result) => { - if (err) { - if (lockedContent) { - logger.warn( - `Upgrade request to ${url} failed: ${err.message}` - ); - logger.debug(err.stack); - return callback(null, { - entry, - content: lockedContent - }); - } - return callback(err); - } - if (!result.storeLock) { - // When the lockfile entry should be no-cache - // we need to update the lockfile - if (frozen) { - return callback( - new Error( - `${url} has a lockfile entry and is no-cache now, but lockfile is frozen\nLockfile: ${entryToString( - entry - )}` - ) - ); - } - storeResult(lockfile, url, result, callback); - return; - } - if (!areLockfileEntriesEqual(result.entry, entry)) { - // When the lockfile entry is outdated - // we need to update the lockfile - if (frozen) { - return callback( - new Error( - `${url} has an outdated lockfile entry, but lockfile is frozen\nLockfile: ${entryToString( - entry - )}\nExpected: ${entryToString(result.entry)}` - ) - ); - } - storeResult(lockfile, url, result, callback); - return; - } - if (!lockedContent && cacheLocation) { - // When the lockfile cache content is missing - // we need to update the lockfile - if (frozen) { - return callback( - new Error( - `${url} is missing content in the lockfile cache, but lockfile is frozen\nLockfile: ${entryToString( - entry - )}` - ) - ); - } - storeResult(lockfile, url, result, callback); - return; - } - return callback(null, result); - }); - }; - if (cacheLocation) { - // When there is a lockfile cache - // we read the content from there - const key = getCacheKey(entry.resolved); - const filePath = join(intermediateFs, cacheLocation, key); - fs.readFile(filePath, (err, result) => { - const content = /** @type {Buffer} */ (result); - if (err) { - if (err.code === "ENOENT") return doFetch(); - return callback(err); - } - const continueWithCachedContent = result => { - if (!upgrade) { - // When not in upgrade mode, we accept the result from the lockfile cache - return callback(null, { entry, content }); - } - return doFetch(content); - }; - if (!verifyIntegrity(content, entry.integrity)) { - let contentWithChangedEol; - let isEolChanged = false; - try { - contentWithChangedEol = Buffer.from( - content.toString("utf-8").replace(/\r\n/g, "\n") - ); - isEolChanged = verifyIntegrity( - contentWithChangedEol, - entry.integrity - ); - } catch (e) { - // ignore - } - if (isEolChanged) { - if (!warnedAboutEol) { - const explainer = `Incorrect end of line sequence was detected in the lockfile cache. -The lockfile cache is protected by integrity checks, so any external modification will lead to a corrupted lockfile cache. -When using git make sure to configure .gitattributes correctly for the lockfile cache: - **/*webpack.lock.data/** -text -This will avoid that the end of line sequence is changed by git on Windows.`; - if (frozen) { - logger.error(explainer); - } else { - logger.warn(explainer); - logger.info( - "Lockfile cache will be automatically fixed now, but when lockfile is frozen this would result in an error." - ); - } - warnedAboutEol = true; - } - if (!frozen) { - // "fix" the end of line sequence of the lockfile content - logger.log( - `${filePath} fixed end of line sequence (\\r\\n instead of \\n).` - ); - intermediateFs.writeFile( - filePath, - contentWithChangedEol, - err => { - if (err) return callback(err); - continueWithCachedContent(contentWithChangedEol); - } - ); - return; - } - } - if (frozen) { - return callback( - new Error( - `${ - entry.resolved - } integrity mismatch, expected content with integrity ${ - entry.integrity - } but got ${computeIntegrity(content)}. -Lockfile corrupted (${ - isEolChanged - ? "end of line sequence was unexpectedly changed" - : "incorrectly merged? changed by other tools?" - }). -Run build with un-frozen lockfile to automatically fix lockfile.` - ) - ); - } else { - // "fix" the lockfile entry to the correct integrity - // the content has priority over the integrity value - entry = { - ...entry, - integrity: computeIntegrity(content) - }; - storeLockEntry(lockfile, url, entry); - } - } - continueWithCachedContent(result); - }); + if (start) { + context[color] = str => + `${start}${ + typeof str === "string" + ? str.replace( + /((\u001b\[39m|\u001b\[22m|\u001b\[0m)+)/g, + `$1${start}` + ) + : str + }\u001b[39m\u001b[22m`; } else { - doFetch(); + context[color] = str => str; } - }); - } - ); - - const respondWithUrlModule = (url, resourceData, callback) => { - getInfo(url.href, (err, result) => { - if (err) return callback(err); - resourceData.resource = url.href; - resourceData.path = url.origin + url.pathname; - resourceData.query = url.search; - resourceData.fragment = url.hash; - resourceData.context = new URL( - ".", - result.entry.resolved - ).href.slice(0, -1); - resourceData.data.mimetype = result.entry.contentType; - callback(null, true); - }); - }; - normalModuleFactory.hooks.resolveForScheme - .for(scheme) - .tapAsync( - "HttpUriPlugin", - (resourceData, resolveData, callback) => { - respondWithUrlModule( - new URL(resourceData.resource), - resourceData, - callback - ); } - ); - normalModuleFactory.hooks.resolveInScheme - .for(scheme) - .tapAsync("HttpUriPlugin", (resourceData, data, callback) => { - // Only handle relative urls (./xxx, ../xxx, /xxx, //xxx) - if ( - data.dependencyType !== "url" && - !/^\.{0,2}\//.test(resourceData.resource) - ) { - return callback(); + for (const format of Object.keys(AVAILABLE_FORMATS)) { + context[format] = (content, ...args) => + AVAILABLE_FORMATS[format](content, context, ...args); } - respondWithUrlModule( - new URL(resourceData.resource, data.context + "/"), - resourceData, - callback - ); - }); - const hooks = NormalModule.getCompilationHooks(compilation); - hooks.readResourceForScheme - .for(scheme) - .tapAsync("HttpUriPlugin", (resource, module, callback) => { - return getInfo(resource, (err, result) => { - if (err) return callback(err); - module.buildInfo.resourceIntegrity = result.entry.integrity; - callback(null, result.content); - }); + context.timeReference = compilation.time; }); - hooks.needBuild.tapAsync( - "HttpUriPlugin", - (module, context, callback) => { - if ( - module.resource && - module.resource.startsWith(`${scheme}://`) - ) { - getInfo(module.resource, (err, result) => { - if (err) return callback(err); - if ( - result.entry.integrity !== - module.buildInfo.resourceIntegrity - ) { - return callback(null, true); - } - callback(); - }); - } else { - return callback(); - } - } - ); - } - compilation.hooks.finishModules.tapAsync( - "HttpUriPlugin", - (modules, callback) => { - if (!lockfileUpdates) return callback(); - const ext = extname(lockfileLocation); - const tempFile = join( - intermediateFs, - dirname(intermediateFs, lockfileLocation), - `.${basename(lockfileLocation, ext)}.${ - (Math.random() * 10000) | 0 - }${ext}` - ); - const writeDone = () => { - const nextOperation = inProgressWrite.shift(); - if (nextOperation) { - nextOperation(); - } else { - inProgressWrite = undefined; - } - }; - const runWrite = () => { - intermediateFs.readFile(lockfileLocation, (err, buffer) => { - if (err && err.code !== "ENOENT") { - writeDone(); - return callback(err); - } - const lockfile = buffer - ? Lockfile.parse(buffer.toString("utf-8")) - : new Lockfile(); - for (const [key, value] of lockfileUpdates) { - lockfile.entries.set(key, value); - } - intermediateFs.writeFile(tempFile, lockfile.toString(), err => { - if (err) { - writeDone(); - return intermediateFs.unlink(tempFile, () => callback(err)); - } - intermediateFs.rename(tempFile, lockfileLocation, err => { - if (err) { - writeDone(); - return intermediateFs.unlink(tempFile, () => - callback(err) - ); - } - writeDone(); - callback(); - }); - }); + for (const key of Object.keys(SIMPLE_PRINTERS)) { + stats.hooks.print + .for(key) + .tap("DefaultStatsPrinterPlugin", (obj, ctx) => + SIMPLE_PRINTERS[key](obj, ctx, stats) + ); + } + + for (const key of Object.keys(PREFERRED_ORDERS)) { + const preferredOrder = PREFERRED_ORDERS[key]; + stats.hooks.sortElements + .for(key) + .tap("DefaultStatsPrinterPlugin", (elements, context) => { + createOrder(elements, preferredOrder); }); - }; - if (inProgressWrite) { - inProgressWrite.push(runWrite); - } else { - inProgressWrite = []; - runWrite(); - } } - ); - } - ); + + for (const key of Object.keys(ITEM_NAMES)) { + const itemName = ITEM_NAMES[key]; + stats.hooks.getItemName + .for(key) + .tap( + "DefaultStatsPrinterPlugin", + typeof itemName === "string" ? () => itemName : itemName + ); + } + + for (const key of Object.keys(SIMPLE_ITEMS_JOINER)) { + const joiner = SIMPLE_ITEMS_JOINER[key]; + stats.hooks.printItems + .for(key) + .tap("DefaultStatsPrinterPlugin", joiner); + } + + for (const key of Object.keys(SIMPLE_ELEMENT_JOINERS)) { + const joiner = SIMPLE_ELEMENT_JOINERS[key]; + stats.hooks.printElements + .for(key) + .tap("DefaultStatsPrinterPlugin", joiner); + } + + for (const key of Object.keys(RESULT_MODIFIER)) { + const modifier = RESULT_MODIFIER[key]; + stats.hooks.result + .for(key) + .tap("DefaultStatsPrinterPlugin", modifier); + } + } + ); + }); } } - -module.exports = HttpUriPlugin; +module.exports = DefaultStatsPrinterPlugin; /***/ }), -/***/ 41721: -/***/ (function(module) { +/***/ 92629: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -class ArraySerializer { - serialize(array, { write }) { - write(array.length); - for (const item of array) write(item); +const { HookMap, SyncBailHook, SyncWaterfallHook } = __webpack_require__(6967); +const { concatComparators, keepOriginalOrder } = __webpack_require__(29579); +const smartGrouping = __webpack_require__(15652); + +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../WebpackError")} WebpackError */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +/** @typedef {import("../util/smartGrouping").GroupConfig} GroupConfig */ + +/** + * @typedef {Object} KnownStatsFactoryContext + * @property {string} type + * @property {function(string): string=} makePathsRelative + * @property {Compilation=} compilation + * @property {Set=} rootModules + * @property {Map=} compilationFileToChunks + * @property {Map=} compilationAuxiliaryFileToChunks + * @property {RuntimeSpec=} runtime + * @property {function(Compilation): WebpackError[]=} cachedGetErrors + * @property {function(Compilation): WebpackError[]=} cachedGetWarnings + */ + +/** @typedef {KnownStatsFactoryContext & Record} StatsFactoryContext */ + +class StatsFactory { + constructor() { + this.hooks = Object.freeze({ + /** @type {HookMap>} */ + extract: new HookMap( + () => new SyncBailHook(["object", "data", "context"]) + ), + /** @type {HookMap>} */ + filter: new HookMap( + () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) + ), + /** @type {HookMap>} */ + sort: new HookMap(() => new SyncBailHook(["comparators", "context"])), + /** @type {HookMap>} */ + filterSorted: new HookMap( + () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) + ), + /** @type {HookMap>} */ + groupResults: new HookMap( + () => new SyncBailHook(["groupConfigs", "context"]) + ), + /** @type {HookMap>} */ + sortResults: new HookMap( + () => new SyncBailHook(["comparators", "context"]) + ), + /** @type {HookMap>} */ + filterResults: new HookMap( + () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) + ), + /** @type {HookMap>} */ + merge: new HookMap(() => new SyncBailHook(["items", "context"])), + /** @type {HookMap>} */ + result: new HookMap(() => new SyncWaterfallHook(["result", "context"])), + /** @type {HookMap>} */ + getItemName: new HookMap(() => new SyncBailHook(["item", "context"])), + /** @type {HookMap>} */ + getItemFactory: new HookMap(() => new SyncBailHook(["item", "context"])) + }); + const hooks = this.hooks; + this._caches = + /** @type {Record[]>>} */ ({}); + for (const key of Object.keys(hooks)) { + this._caches[key] = new Map(); + } + this._inCreate = false; } - deserialize({ read }) { - const length = read(); - const array = []; - for (let i = 0; i < length; i++) { - array.push(read()); + + _getAllLevelHooks(hookMap, cache, type) { + const cacheEntry = cache.get(type); + if (cacheEntry !== undefined) { + return cacheEntry; } - return array; + const hooks = []; + const typeParts = type.split("."); + for (let i = 0; i < typeParts.length; i++) { + const hook = hookMap.get(typeParts.slice(i).join(".")); + if (hook) { + hooks.push(hook); + } + } + cache.set(type, hooks); + return hooks; } -} -module.exports = ArraySerializer; + _forEachLevel(hookMap, cache, type, fn) { + for (const hook of this._getAllLevelHooks(hookMap, cache, type)) { + const result = fn(hook); + if (result !== undefined) return result; + } + } + + _forEachLevelWaterfall(hookMap, cache, type, data, fn) { + for (const hook of this._getAllLevelHooks(hookMap, cache, type)) { + data = fn(hook, data); + } + return data; + } + + _forEachLevelFilter(hookMap, cache, type, items, fn, forceClone) { + const hooks = this._getAllLevelHooks(hookMap, cache, type); + if (hooks.length === 0) return forceClone ? items.slice() : items; + let i = 0; + return items.filter((item, idx) => { + for (const hook of hooks) { + const r = fn(hook, item, idx, i); + if (r !== undefined) { + if (r) i++; + return r; + } + } + i++; + return true; + }); + } + + /** + * @param {string} type type + * @param {any} data factory data + * @param {Omit} baseContext context used as base + * @returns {any} created object + */ + create(type, data, baseContext) { + if (this._inCreate) { + return this._create(type, data, baseContext); + } else { + try { + this._inCreate = true; + return this._create(type, data, baseContext); + } finally { + for (const key of Object.keys(this._caches)) this._caches[key].clear(); + this._inCreate = false; + } + } + } + + _create(type, data, baseContext) { + const context = { + ...baseContext, + type, + [type]: data + }; + if (Array.isArray(data)) { + // run filter on unsorted items + const items = this._forEachLevelFilter( + this.hooks.filter, + this._caches.filter, + type, + data, + (h, r, idx, i) => h.call(r, context, idx, i), + true + ); + + // sort items + const comparators = []; + this._forEachLevel(this.hooks.sort, this._caches.sort, type, h => + h.call(comparators, context) + ); + if (comparators.length > 0) { + items.sort( + // @ts-expect-error number of arguments is correct + concatComparators(...comparators, keepOriginalOrder(items)) + ); + } + + // run filter on sorted items + const items2 = this._forEachLevelFilter( + this.hooks.filterSorted, + this._caches.filterSorted, + type, + items, + (h, r, idx, i) => h.call(r, context, idx, i), + false + ); + + // for each item + let resultItems = items2.map((item, i) => { + const itemContext = { + ...context, + _index: i + }; + + // run getItemName + const itemName = this._forEachLevel( + this.hooks.getItemName, + this._caches.getItemName, + `${type}[]`, + h => h.call(item, itemContext) + ); + if (itemName) itemContext[itemName] = item; + const innerType = itemName ? `${type}[].${itemName}` : `${type}[]`; + + // run getItemFactory + const itemFactory = + this._forEachLevel( + this.hooks.getItemFactory, + this._caches.getItemFactory, + innerType, + h => h.call(item, itemContext) + ) || this; + + // run item factory + return itemFactory.create(innerType, item, itemContext); + }); + + // sort result items + const comparators2 = []; + this._forEachLevel( + this.hooks.sortResults, + this._caches.sortResults, + type, + h => h.call(comparators2, context) + ); + if (comparators2.length > 0) { + resultItems.sort( + // @ts-expect-error number of arguments is correct + concatComparators(...comparators2, keepOriginalOrder(resultItems)) + ); + } + + // group result items + const groupConfigs = []; + this._forEachLevel( + this.hooks.groupResults, + this._caches.groupResults, + type, + h => h.call(groupConfigs, context) + ); + if (groupConfigs.length > 0) { + resultItems = smartGrouping(resultItems, groupConfigs); + } + + // run filter on sorted result items + const finalResultItems = this._forEachLevelFilter( + this.hooks.filterResults, + this._caches.filterResults, + type, + resultItems, + (h, r, idx, i) => h.call(r, context, idx, i), + false + ); + + // run merge on mapped items + let result = this._forEachLevel( + this.hooks.merge, + this._caches.merge, + type, + h => h.call(finalResultItems, context) + ); + if (result === undefined) result = finalResultItems; + + // run result on merged items + return this._forEachLevelWaterfall( + this.hooks.result, + this._caches.result, + type, + result, + (h, r) => h.call(r, context) + ); + } else { + const object = {}; + + // run extract on value + this._forEachLevel(this.hooks.extract, this._caches.extract, type, h => + h.call(object, data, context) + ); + + // run result on extracted object + return this._forEachLevelWaterfall( + this.hooks.result, + this._caches.result, + type, + object, + (h, r) => h.call(r, context) + ); + } + } +} +module.exports = StatsFactory; /***/ }), -/***/ 97059: +/***/ 30198: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const memoize = __webpack_require__(78676); -const SerializerMiddleware = __webpack_require__(83137); +const { HookMap, SyncWaterfallHook, SyncBailHook } = __webpack_require__(6967); -/** @typedef {import("./types").BufferSerializableType} BufferSerializableType */ -/** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */ +/** @template T @typedef {import("tapable").AsArray} AsArray */ +/** @typedef {import("tapable").Hook} Hook */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunk} StatsChunk */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunkGroup} StatsChunkGroup */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModule} StatsModule */ +/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleReason} StatsModuleReason */ -/* -Format: +/** + * @typedef {Object} PrintedElement + * @property {string} element + * @property {string} content + */ -File -> Section* +/** + * @typedef {Object} KnownStatsPrinterContext + * @property {string=} type + * @property {StatsCompilation=} compilation + * @property {StatsChunkGroup=} chunkGroup + * @property {StatsAsset=} asset + * @property {StatsModule=} module + * @property {StatsChunk=} chunk + * @property {StatsModuleReason=} moduleReason + * @property {(str: string) => string=} bold + * @property {(str: string) => string=} yellow + * @property {(str: string) => string=} red + * @property {(str: string) => string=} green + * @property {(str: string) => string=} magenta + * @property {(str: string) => string=} cyan + * @property {(file: string, oversize?: boolean) => string=} formatFilename + * @property {(id: string) => string=} formatModuleId + * @property {(id: string, direction?: "parent"|"child"|"sibling") => string=} formatChunkId + * @property {(size: number) => string=} formatSize + * @property {(dateTime: number) => string=} formatDateTime + * @property {(flag: string) => string=} formatFlag + * @property {(time: number, boldQuantity?: boolean) => string=} formatTime + * @property {string=} chunkGroupKind + */ -Section -> NullsSection | - BooleansSection | - F64NumbersSection | - I32NumbersSection | - I8NumbersSection | - ShortStringSection | - StringSection | - BufferSection | - NopSection +/** @typedef {KnownStatsPrinterContext & Record} StatsPrinterContext */ + +class StatsPrinter { + constructor() { + this.hooks = Object.freeze({ + /** @type {HookMap>} */ + sortElements: new HookMap( + () => new SyncBailHook(["elements", "context"]) + ), + /** @type {HookMap>} */ + printElements: new HookMap( + () => new SyncBailHook(["printedElements", "context"]) + ), + /** @type {HookMap>} */ + sortItems: new HookMap(() => new SyncBailHook(["items", "context"])), + /** @type {HookMap>} */ + getItemName: new HookMap(() => new SyncBailHook(["item", "context"])), + /** @type {HookMap>} */ + printItems: new HookMap( + () => new SyncBailHook(["printedItems", "context"]) + ), + /** @type {HookMap>} */ + print: new HookMap(() => new SyncBailHook(["object", "context"])), + /** @type {HookMap>} */ + result: new HookMap(() => new SyncWaterfallHook(["result", "context"])) + }); + /** @type {Map, Map>} */ + this._levelHookCache = new Map(); + this._inPrint = false; + } + /** + * get all level hooks + * @private + * @template {Hook} T + * @param {HookMap} hookMap HookMap + * @param {string} type type + * @returns {T[]} hooks + */ + _getAllLevelHooks(hookMap, type) { + let cache = /** @type {Map} */ ( + this._levelHookCache.get(hookMap) + ); + if (cache === undefined) { + cache = new Map(); + this._levelHookCache.set(hookMap, cache); + } + const cacheEntry = cache.get(type); + if (cacheEntry !== undefined) { + return cacheEntry; + } + /** @type {T[]} */ + const hooks = []; + const typeParts = type.split("."); + for (let i = 0; i < typeParts.length; i++) { + const hook = hookMap.get(typeParts.slice(i).join(".")); + if (hook) { + hooks.push(hook); + } + } + cache.set(type, hooks); + return hooks; + } + /** + * Run `fn` for each level + * @private + * @template T + * @template R + * @param {HookMap>} hookMap HookMap + * @param {string} type type + * @param {(hook: SyncBailHook) => R} fn function + * @returns {R} result of `fn` + */ + _forEachLevel(hookMap, type, fn) { + for (const hook of this._getAllLevelHooks(hookMap, type)) { + const result = fn(hook); + if (result !== undefined) return result; + } + } -NullsSection -> - NullHeaderByte | Null2HeaderByte | Null3HeaderByte | - Nulls8HeaderByte 0xnn (n:count - 4) | - Nulls32HeaderByte n:ui32 (n:count - 260) | -BooleansSection -> TrueHeaderByte | FalseHeaderByte | BooleansSectionHeaderByte BooleansCountAndBitsByte -F64NumbersSection -> F64NumbersSectionHeaderByte f64* -I32NumbersSection -> I32NumbersSectionHeaderByte i32* -I8NumbersSection -> I8NumbersSectionHeaderByte i8* -ShortStringSection -> ShortStringSectionHeaderByte ascii-byte* -StringSection -> StringSectionHeaderByte i32:length utf8-byte* -BufferSection -> BufferSectionHeaderByte i32:length byte* -NopSection --> NopSectionHeaderByte + /** + * Run `fn` for each level + * @private + * @template T + * @param {HookMap>} hookMap HookMap + * @param {string} type type + * @param {AsArray[0]} data data + * @param {(hook: SyncWaterfallHook, data: AsArray[0]) => AsArray[0]} fn function + * @returns {AsArray[0]} result of `fn` + */ + _forEachLevelWaterfall(hookMap, type, data, fn) { + for (const hook of this._getAllLevelHooks(hookMap, type)) { + data = fn(hook, data); + } + return data; + } -ShortStringSectionHeaderByte -> 0b1nnn_nnnn (n:length) + /** + * @param {string} type The type + * @param {Object} object Object to print + * @param {Object=} baseContext The base context + * @returns {string} printed result + */ + print(type, object, baseContext) { + if (this._inPrint) { + return this._print(type, object, baseContext); + } else { + try { + this._inPrint = true; + return this._print(type, object, baseContext); + } finally { + this._levelHookCache.clear(); + this._inPrint = false; + } + } + } -F64NumbersSectionHeaderByte -> 0b001n_nnnn (n:count - 1) -I32NumbersSectionHeaderByte -> 0b010n_nnnn (n:count - 1) -I8NumbersSectionHeaderByte -> 0b011n_nnnn (n:count - 1) + /** + * @private + * @param {string} type type + * @param {Object} object object + * @param {Object=} baseContext context + * @returns {string} printed result + */ + _print(type, object, baseContext) { + const context = { + ...baseContext, + type, + [type]: object + }; -NullsSectionHeaderByte -> 0b0001_nnnn (n:count - 1) -BooleansCountAndBitsByte -> - 0b0000_1xxx (count = 3) | - 0b0001_xxxx (count = 4) | - 0b001x_xxxx (count = 5) | - 0b01xx_xxxx (count = 6) | - 0b1nnn_nnnn (n:count - 7, 7 <= count <= 133) - 0xff n:ui32 (n:count, 134 <= count < 2^32) + let printResult = this._forEachLevel(this.hooks.print, type, hook => + hook.call(object, context) + ); + if (printResult === undefined) { + if (Array.isArray(object)) { + const sortedItems = object.slice(); + this._forEachLevel(this.hooks.sortItems, type, h => + h.call(sortedItems, context) + ); + const printedItems = sortedItems.map((item, i) => { + const itemContext = { + ...context, + _index: i + }; + const itemName = this._forEachLevel( + this.hooks.getItemName, + `${type}[]`, + h => h.call(item, itemContext) + ); + if (itemName) itemContext[itemName] = item; + return this.print( + itemName ? `${type}[].${itemName}` : `${type}[]`, + item, + itemContext + ); + }); + printResult = this._forEachLevel(this.hooks.printItems, type, h => + h.call(printedItems, context) + ); + if (printResult === undefined) { + const result = printedItems.filter(Boolean); + if (result.length > 0) printResult = result.join("\n"); + } + } else if (object !== null && typeof object === "object") { + const elements = Object.keys(object).filter( + key => object[key] !== undefined + ); + this._forEachLevel(this.hooks.sortElements, type, h => + h.call(elements, context) + ); + const printedElements = elements.map(element => { + const content = this.print(`${type}.${element}`, object[element], { + ...context, + _parent: object, + _element: element, + [element]: object[element] + }); + return { element, content }; + }); + printResult = this._forEachLevel(this.hooks.printElements, type, h => + h.call(printedElements, context) + ); + if (printResult === undefined) { + const result = printedElements.map(e => e.content).filter(Boolean); + if (result.length > 0) printResult = result.join("\n"); + } + } + } -StringSectionHeaderByte -> 0b0000_1110 -BufferSectionHeaderByte -> 0b0000_1111 -NopSectionHeaderByte -> 0b0000_1011 -FalseHeaderByte -> 0b0000_1100 -TrueHeaderByte -> 0b0000_1101 + return this._forEachLevelWaterfall( + this.hooks.result, + type, + printResult, + (h, r) => h.call(r, context) + ); + } +} +module.exports = StatsPrinter; -RawNumber -> n (n <= 10) +/***/ }), + +/***/ 84953: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const LAZY_HEADER = 0x0b; -const TRUE_HEADER = 0x0c; -const FALSE_HEADER = 0x0d; -const BOOLEANS_HEADER = 0x0e; -const NULL_HEADER = 0x10; -const NULL2_HEADER = 0x11; -const NULL3_HEADER = 0x12; -const NULLS8_HEADER = 0x13; -const NULLS32_HEADER = 0x14; -const NULL_AND_I8_HEADER = 0x15; -const NULL_AND_I32_HEADER = 0x16; -const NULL_AND_TRUE_HEADER = 0x17; -const NULL_AND_FALSE_HEADER = 0x18; -const STRING_HEADER = 0x1e; -const BUFFER_HEADER = 0x1f; -const I8_HEADER = 0x60; -const I32_HEADER = 0x40; -const F64_HEADER = 0x20; -const SHORT_STRING_HEADER = 0x80; -/** Uplift high-order bits */ -const NUMBERS_HEADER_MASK = 0xe0; -const NUMBERS_COUNT_MASK = 0x1f; // 0b0001_1111 -const SHORT_STRING_LENGTH_MASK = 0x7f; // 0b0111_1111 -const HEADER_SIZE = 1; -const I8_SIZE = 1; -const I32_SIZE = 4; -const F64_SIZE = 8; +exports.equals = (a, b) => { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; +}; + +/** + * + * @param {Array} arr Array of values to be partitioned + * @param {(value: any) => boolean} fn Partition function which partitions based on truthiness of result. + * @returns {[Array, Array]} returns the values of `arr` partitioned into two new arrays based on fn predicate. + */ +exports.groupBy = (arr = [], fn) => { + return arr.reduce( + (groups, value) => { + groups[fn(value) ? 0 : 1].push(value); + return groups; + }, + [[], []] + ); +}; + + +/***/ }), -const MEASURE_START_OPERATION = Symbol("MEASURE_START_OPERATION"); -const MEASURE_END_OPERATION = Symbol("MEASURE_END_OPERATION"); +/***/ 41792: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** @typedef {typeof MEASURE_START_OPERATION} MEASURE_START_OPERATION_TYPE */ -/** @typedef {typeof MEASURE_END_OPERATION} MEASURE_END_OPERATION_TYPE */ -const identifyNumber = n => { - if (n === (n | 0)) { - if (n <= 127 && n >= -128) return 0; - if (n <= 2147483647 && n >= -2147483648) return 1; - } - return 2; -}; /** - * @typedef {PrimitiveSerializableType[]} DeserializedType - * @typedef {BufferSerializableType[]} SerializedType - * @extends {SerializerMiddleware} + * @template T */ -class BinaryMiddleware extends SerializerMiddleware { +class ArrayQueue { /** - * @param {DeserializedType} data data - * @param {Object} context context object - * @returns {SerializedType|Promise} serialized data + * @param {Iterable=} items The initial elements. */ - serialize(data, context) { - return this._serialize(data, context); + constructor(items) { + /** @private @type {T[]} */ + this._list = items ? Array.from(items) : []; + /** @private @type {T[]} */ + this._listReversed = []; } - _serializeLazy(fn, context) { - return SerializerMiddleware.serializeLazy(fn, data => - this._serialize(data, context) - ); + /** + * Returns the number of elements in this queue. + * @returns {number} The number of elements in this queue. + */ + get length() { + return this._list.length + this._listReversed.length; } /** - * @param {DeserializedType} data data - * @param {Object} context context object - * @param {{ leftOverBuffer: Buffer | null, allocationSize: number, increaseCounter: number }} allocationScope allocation scope - * @returns {SerializedType} serialized data + * Empties the queue. */ - _serialize( - data, - context, - allocationScope = { - allocationSize: 1024, - increaseCounter: 0, - leftOverBuffer: null + clear() { + this._list.length = 0; + this._listReversed.length = 0; + } + + /** + * Appends the specified element to this queue. + * @param {T} item The element to add. + * @returns {void} + */ + enqueue(item) { + this._list.push(item); + } + + /** + * Retrieves and removes the head of this queue. + * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + */ + dequeue() { + if (this._listReversed.length === 0) { + if (this._list.length === 0) return undefined; + if (this._list.length === 1) return this._list.pop(); + if (this._list.length < 16) return this._list.shift(); + const temp = this._listReversed; + this._listReversed = this._list; + this._listReversed.reverse(); + this._list = temp; } - ) { - /** @type {Buffer} */ - let leftOverBuffer = null; - /** @type {BufferSerializableType[]} */ - let buffers = []; - /** @type {Buffer} */ - let currentBuffer = allocationScope ? allocationScope.leftOverBuffer : null; - allocationScope.leftOverBuffer = null; - let currentPosition = 0; - if (currentBuffer === null) { - currentBuffer = Buffer.allocUnsafe(allocationScope.allocationSize); + return this._listReversed.pop(); + } + + /** + * Finds and removes an item + * @param {T} item the item + * @returns {void} + */ + delete(item) { + const i = this._list.indexOf(item); + if (i >= 0) { + this._list.splice(i, 1); + } else { + const i = this._listReversed.indexOf(item); + if (i >= 0) this._listReversed.splice(i, 1); } - const allocate = bytesNeeded => { - if (currentBuffer !== null) { - if (currentBuffer.length - currentPosition >= bytesNeeded) return; - flush(); - } - if (leftOverBuffer && leftOverBuffer.length >= bytesNeeded) { - currentBuffer = leftOverBuffer; - leftOverBuffer = null; - } else { - currentBuffer = Buffer.allocUnsafe( - Math.max(bytesNeeded, allocationScope.allocationSize) - ); - if ( - !(allocationScope.increaseCounter = - (allocationScope.increaseCounter + 1) % 4) && - allocationScope.allocationSize < 16777216 - ) { - allocationScope.allocationSize = allocationScope.allocationSize << 1; - } - } - }; - const flush = () => { - if (currentBuffer !== null) { - if (currentPosition > 0) { - buffers.push( - Buffer.from( - currentBuffer.buffer, - currentBuffer.byteOffset, - currentPosition - ) - ); + } + + [Symbol.iterator]() { + let i = -1; + let reversed = false; + return { + next: () => { + if (!reversed) { + i++; + if (i < this._list.length) { + return { + done: false, + value: this._list[i] + }; + } + reversed = true; + i = this._listReversed.length; } - if ( - !leftOverBuffer || - leftOverBuffer.length < currentBuffer.length - currentPosition - ) { - leftOverBuffer = Buffer.from( - currentBuffer.buffer, - currentBuffer.byteOffset + currentPosition, - currentBuffer.byteLength - currentPosition - ); + i--; + if (i < 0) { + return { + done: true, + value: undefined + }; } - - currentBuffer = null; - currentPosition = 0; - } - }; - const writeU8 = byte => { - currentBuffer.writeUInt8(byte, currentPosition++); - }; - const writeU32 = ui32 => { - currentBuffer.writeUInt32LE(ui32, currentPosition); - currentPosition += 4; - }; - const measureStack = []; - const measureStart = () => { - measureStack.push(buffers.length, currentPosition); - }; - const measureEnd = () => { - const oldPos = measureStack.pop(); - const buffersIndex = measureStack.pop(); - let size = currentPosition - oldPos; - for (let i = buffersIndex; i < buffers.length; i++) { - size += buffers[i].length; + return { + done: false, + value: this._listReversed[i] + }; } - return size; }; - for (let i = 0; i < data.length; i++) { - const thing = data[i]; - switch (typeof thing) { - case "function": { - if (!SerializerMiddleware.isLazy(thing)) - throw new Error("Unexpected function " + thing); - /** @type {SerializedType | (() => SerializedType)} */ - let serializedData = - SerializerMiddleware.getLazySerializedValue(thing); - if (serializedData === undefined) { - if (SerializerMiddleware.isLazy(thing, this)) { - flush(); - allocationScope.leftOverBuffer = leftOverBuffer; - const result = - /** @type {(Exclude>)[]} */ ( - thing() - ); - const data = this._serialize(result, context, allocationScope); - leftOverBuffer = allocationScope.leftOverBuffer; - allocationScope.leftOverBuffer = null; - SerializerMiddleware.setLazySerializedValue(thing, data); - serializedData = data; - } else { - serializedData = this._serializeLazy(thing, context); - flush(); - buffers.push(serializedData); - break; - } - } else { - if (typeof serializedData === "function") { - flush(); - buffers.push(serializedData); - break; - } - } - const lengths = []; - for (const item of serializedData) { - let last; - if (typeof item === "function") { - lengths.push(0); - } else if (item.length === 0) { - // ignore - } else if ( - lengths.length > 0 && - (last = lengths[lengths.length - 1]) !== 0 - ) { - const remaining = 0xffffffff - last; - if (remaining >= item.length) { - lengths[lengths.length - 1] += item.length; - } else { - lengths.push(item.length - remaining); - lengths[lengths.length - 2] = 0xffffffff; - } - } else { - lengths.push(item.length); - } - } - allocate(5 + lengths.length * 4); - writeU8(LAZY_HEADER); - writeU32(lengths.length); - for (const l of lengths) { - writeU32(l); - } - flush(); - for (const item of serializedData) { - buffers.push(item); - } - break; - } - case "string": { - const len = Buffer.byteLength(thing); - if (len >= 128 || len !== thing.length) { - allocate(len + HEADER_SIZE + I32_SIZE); - writeU8(STRING_HEADER); - writeU32(len); - currentBuffer.write(thing, currentPosition); - currentPosition += len; - } else if (len >= 70) { - allocate(len + HEADER_SIZE); - writeU8(SHORT_STRING_HEADER | len); + } +} - currentBuffer.write(thing, currentPosition, "latin1"); - currentPosition += len; - } else { - allocate(len + HEADER_SIZE); - writeU8(SHORT_STRING_HEADER | len); +module.exports = ArrayQueue; - for (let i = 0; i < len; i++) { - currentBuffer[currentPosition++] = thing.charCodeAt(i); - } - } - break; - } - case "number": { - const type = identifyNumber(thing); - if (type === 0 && thing >= 0 && thing <= 10) { - // shortcut for very small numbers - allocate(I8_SIZE); - writeU8(thing); - break; - } - /** - * amount of numbers to write - * @type {number} - */ - let n = 1; - for (; n < 32 && i + n < data.length; n++) { - const item = data[i + n]; - if (typeof item !== "number") break; - if (identifyNumber(item) !== type) break; - } - switch (type) { - case 0: - allocate(HEADER_SIZE + I8_SIZE * n); - writeU8(I8_HEADER | (n - 1)); - while (n > 0) { - currentBuffer.writeInt8( - /** @type {number} */ (data[i]), - currentPosition - ); - currentPosition += I8_SIZE; - n--; - i++; - } - break; - case 1: - allocate(HEADER_SIZE + I32_SIZE * n); - writeU8(I32_HEADER | (n - 1)); - while (n > 0) { - currentBuffer.writeInt32LE( - /** @type {number} */ (data[i]), - currentPosition - ); - currentPosition += I32_SIZE; - n--; - i++; - } - break; - case 2: - allocate(HEADER_SIZE + F64_SIZE * n); - writeU8(F64_HEADER | (n - 1)); - while (n > 0) { - currentBuffer.writeDoubleLE( - /** @type {number} */ (data[i]), - currentPosition - ); - currentPosition += F64_SIZE; - n--; - i++; - } - break; - } - i--; - break; - } - case "boolean": { - let lastByte = thing === true ? 1 : 0; - const bytes = []; - let count = 1; - let n; - for (n = 1; n < 0xffffffff && i + n < data.length; n++) { - const item = data[i + n]; - if (typeof item !== "boolean") break; - const pos = count & 0x7; - if (pos === 0) { - bytes.push(lastByte); - lastByte = item === true ? 1 : 0; - } else if (item === true) { - lastByte |= 1 << pos; - } - count++; - } - i += count - 1; - if (count === 1) { - allocate(HEADER_SIZE); - writeU8(lastByte === 1 ? TRUE_HEADER : FALSE_HEADER); - } else if (count === 2) { - allocate(HEADER_SIZE * 2); - writeU8(lastByte & 1 ? TRUE_HEADER : FALSE_HEADER); - writeU8(lastByte & 2 ? TRUE_HEADER : FALSE_HEADER); - } else if (count <= 6) { - allocate(HEADER_SIZE + I8_SIZE); - writeU8(BOOLEANS_HEADER); - writeU8((1 << count) | lastByte); - } else if (count <= 133) { - allocate(HEADER_SIZE + I8_SIZE + I8_SIZE * bytes.length + I8_SIZE); - writeU8(BOOLEANS_HEADER); - writeU8(0x80 | (count - 7)); - for (const byte of bytes) writeU8(byte); - writeU8(lastByte); - } else { - allocate( - HEADER_SIZE + - I8_SIZE + - I32_SIZE + - I8_SIZE * bytes.length + - I8_SIZE - ); - writeU8(BOOLEANS_HEADER); - writeU8(0xff); - writeU32(count); - for (const byte of bytes) writeU8(byte); - writeU8(lastByte); - } - break; - } - case "object": { - if (thing === null) { - let n; - for (n = 1; n < 0x100000104 && i + n < data.length; n++) { - const item = data[i + n]; - if (item !== null) break; - } - i += n - 1; - if (n === 1) { - if (i + 1 < data.length) { - const next = data[i + 1]; - if (next === true) { - allocate(HEADER_SIZE); - writeU8(NULL_AND_TRUE_HEADER); - i++; - } else if (next === false) { - allocate(HEADER_SIZE); - writeU8(NULL_AND_FALSE_HEADER); - i++; - } else if (typeof next === "number") { - const type = identifyNumber(next); - if (type === 0) { - allocate(HEADER_SIZE + I8_SIZE); - writeU8(NULL_AND_I8_HEADER); - currentBuffer.writeInt8(next, currentPosition); - currentPosition += I8_SIZE; - i++; - } else if (type === 1) { - allocate(HEADER_SIZE + I32_SIZE); - writeU8(NULL_AND_I32_HEADER); - currentBuffer.writeInt32LE(next, currentPosition); - currentPosition += I32_SIZE; - i++; - } else { - allocate(HEADER_SIZE); - writeU8(NULL_HEADER); - } - } else { - allocate(HEADER_SIZE); - writeU8(NULL_HEADER); - } - } else { - allocate(HEADER_SIZE); - writeU8(NULL_HEADER); - } - } else if (n === 2) { - allocate(HEADER_SIZE); - writeU8(NULL2_HEADER); - } else if (n === 3) { - allocate(HEADER_SIZE); - writeU8(NULL3_HEADER); - } else if (n < 260) { - allocate(HEADER_SIZE + I8_SIZE); - writeU8(NULLS8_HEADER); - writeU8(n - 4); - } else { - allocate(HEADER_SIZE + I32_SIZE); - writeU8(NULLS32_HEADER); - writeU32(n - 260); - } - } else if (Buffer.isBuffer(thing)) { - if (thing.length < 8192) { - allocate(HEADER_SIZE + I32_SIZE + thing.length); - writeU8(BUFFER_HEADER); - writeU32(thing.length); - thing.copy(currentBuffer, currentPosition); - currentPosition += thing.length; - } else { - allocate(HEADER_SIZE + I32_SIZE); - writeU8(BUFFER_HEADER); - writeU32(thing.length); - flush(); - buffers.push(thing); - } - } - break; - } - case "symbol": { - if (thing === MEASURE_START_OPERATION) { - measureStart(); - } else if (thing === MEASURE_END_OPERATION) { - const size = measureEnd(); - allocate(HEADER_SIZE + I32_SIZE); - writeU8(I32_HEADER); - currentBuffer.writeInt32LE(size, currentPosition); - currentPosition += I32_SIZE; - } - break; - } - } - } - flush(); +/***/ }), - allocationScope.leftOverBuffer = leftOverBuffer; +/***/ 12260: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // avoid leaking memory - currentBuffer = null; - leftOverBuffer = null; - allocationScope = undefined; - const _buffers = buffers; - buffers = undefined; - return _buffers; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const { SyncHook, AsyncSeriesHook } = __webpack_require__(6967); +const { makeWebpackError } = __webpack_require__(11351); +const WebpackError = __webpack_require__(53799); +const ArrayQueue = __webpack_require__(41792); +const QUEUED_STATE = 0; +const PROCESSING_STATE = 1; +const DONE_STATE = 2; + +let inHandleResult = 0; + +/** + * @template T + * @callback Callback + * @param {(WebpackError | null)=} err + * @param {T=} result + */ + +/** + * @template T + * @template K + * @template R + */ +class AsyncQueueEntry { /** - * @param {SerializedType} data data - * @param {Object} context context object - * @returns {DeserializedType|Promise} deserialized data + * @param {T} item the item + * @param {Callback} callback the callback */ - deserialize(data, context) { - return this._deserialize(data, context); + constructor(item, callback) { + this.item = item; + /** @type {typeof QUEUED_STATE | typeof PROCESSING_STATE | typeof DONE_STATE} */ + this.state = QUEUED_STATE; + this.callback = callback; + /** @type {Callback[] | undefined} */ + this.callbacks = undefined; + this.result = undefined; + /** @type {WebpackError | undefined} */ + this.error = undefined; } +} - _createLazyDeserialized(content, context) { - return SerializerMiddleware.createLazy( - memoize(() => this._deserialize(content, context)), - this, - undefined, - content - ); - } +/** + * @template T + * @template K + * @template R + */ +class AsyncQueue { + /** + * @param {Object} options options object + * @param {string=} options.name name of the queue + * @param {number=} options.parallelism how many items should be processed at once + * @param {AsyncQueue=} options.parent parent queue, which will have priority over this queue and with shared parallelism + * @param {function(T): K=} options.getKey extract key from item + * @param {function(T, Callback): void} options.processor async function to process items + */ + constructor({ name, parallelism, parent, processor, getKey }) { + this._name = name; + this._parallelism = parallelism || 1; + this._processor = processor; + this._getKey = + getKey || /** @type {(T) => K} */ (item => /** @type {any} */ (item)); + /** @type {Map>} */ + this._entries = new Map(); + /** @type {ArrayQueue>} */ + this._queued = new ArrayQueue(); + /** @type {AsyncQueue[]} */ + this._children = undefined; + this._activeTasks = 0; + this._willEnsureProcessing = false; + this._needProcessing = false; + this._stopped = false; + this._root = parent ? parent._root : this; + if (parent) { + if (this._root._children === undefined) { + this._root._children = [this]; + } else { + this._root._children.push(this); + } + } - _deserializeLazy(fn, context) { - return SerializerMiddleware.deserializeLazy(fn, data => - this._deserialize(data, context) - ); + this.hooks = { + /** @type {AsyncSeriesHook<[T]>} */ + beforeAdd: new AsyncSeriesHook(["item"]), + /** @type {SyncHook<[T]>} */ + added: new SyncHook(["item"]), + /** @type {AsyncSeriesHook<[T]>} */ + beforeStart: new AsyncSeriesHook(["item"]), + /** @type {SyncHook<[T]>} */ + started: new SyncHook(["item"]), + /** @type {SyncHook<[T, Error, R]>} */ + result: new SyncHook(["item", "error", "result"]) + }; + + this._ensureProcessing = this._ensureProcessing.bind(this); } /** - * @param {SerializedType} data data - * @param {Object} context context object - * @returns {DeserializedType} deserialized data + * @param {T} item an item + * @param {Callback} callback callback function + * @returns {void} */ - _deserialize(data, context) { - let currentDataItem = 0; - let currentBuffer = data[0]; - let currentIsBuffer = Buffer.isBuffer(currentBuffer); - let currentPosition = 0; - - const retainedBuffer = context.retainedBuffer || (x => x); - - const checkOverflow = () => { - if (currentPosition >= currentBuffer.length) { - currentPosition = 0; - currentDataItem++; - currentBuffer = - currentDataItem < data.length ? data[currentDataItem] : null; - currentIsBuffer = Buffer.isBuffer(currentBuffer); - } - }; - const isInCurrentBuffer = n => { - return currentIsBuffer && n + currentPosition <= currentBuffer.length; - }; - const ensureBuffer = () => { - if (!currentIsBuffer) { - throw new Error( - currentBuffer === null - ? "Unexpected end of stream" - : "Unexpected lazy element in stream" + add(item, callback) { + if (this._stopped) return callback(new WebpackError("Queue was stopped")); + this.hooks.beforeAdd.callAsync(item, err => { + if (err) { + callback( + makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeAdd`) ); + return; } - }; - /** - * Reads n bytes - * @param {number} n amount of bytes to read - * @returns {Buffer} buffer with bytes - */ - const read = n => { - ensureBuffer(); - const rem = currentBuffer.length - currentPosition; - if (rem < n) { - const buffers = [read(rem)]; - n -= rem; - ensureBuffer(); - while (currentBuffer.length < n) { - const b = /** @type {Buffer} */ (currentBuffer); - buffers.push(b); - n -= b.length; - currentDataItem++; - currentBuffer = - currentDataItem < data.length ? data[currentDataItem] : null; - currentIsBuffer = Buffer.isBuffer(currentBuffer); - ensureBuffer(); - } - buffers.push(read(n)); - return Buffer.concat(buffers); - } - const b = /** @type {Buffer} */ (currentBuffer); - const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n); - currentPosition += n; - checkOverflow(); - return res; - }; - /** - * Reads up to n bytes - * @param {number} n amount of bytes to read - * @returns {Buffer} buffer with bytes - */ - const readUpTo = n => { - ensureBuffer(); - const rem = currentBuffer.length - currentPosition; - if (rem < n) { - n = rem; - } - const b = /** @type {Buffer} */ (currentBuffer); - const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n); - currentPosition += n; - checkOverflow(); - return res; - }; - const readU8 = () => { - ensureBuffer(); - /** - * There is no need to check remaining buffer size here - * since {@link checkOverflow} guarantees at least one byte remaining - */ - const byte = /** @type {Buffer} */ (currentBuffer).readUInt8( - currentPosition - ); - currentPosition += I8_SIZE; - checkOverflow(); - return byte; - }; - const readU32 = () => { - return read(I32_SIZE).readUInt32LE(0); - }; - const readBits = (data, n) => { - let mask = 1; - while (n !== 0) { - result.push((data & mask) !== 0); - mask = mask << 1; - n--; - } - }; - const dispatchTable = Array.from({ length: 256 }).map((_, header) => { - switch (header) { - case LAZY_HEADER: - return () => { - const count = readU32(); - const lengths = Array.from({ length: count }).map(() => readU32()); - const content = []; - for (let l of lengths) { - if (l === 0) { - if (typeof currentBuffer !== "function") { - throw new Error("Unexpected non-lazy element in stream"); - } - content.push(currentBuffer); - currentDataItem++; - currentBuffer = - currentDataItem < data.length ? data[currentDataItem] : null; - currentIsBuffer = Buffer.isBuffer(currentBuffer); - } else { - do { - const buf = readUpTo(l); - l -= buf.length; - content.push(retainedBuffer(buf)); - } while (l > 0); - } - } - result.push(this._createLazyDeserialized(content, context)); - }; - case BUFFER_HEADER: - return () => { - const len = readU32(); - result.push(retainedBuffer(read(len))); - }; - case TRUE_HEADER: - return () => result.push(true); - case FALSE_HEADER: - return () => result.push(false); - case NULL3_HEADER: - return () => result.push(null, null, null); - case NULL2_HEADER: - return () => result.push(null, null); - case NULL_HEADER: - return () => result.push(null); - case NULL_AND_TRUE_HEADER: - return () => result.push(null, true); - case NULL_AND_FALSE_HEADER: - return () => result.push(null, false); - case NULL_AND_I8_HEADER: - return () => { - if (currentIsBuffer) { - result.push( - null, - /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition) - ); - currentPosition += I8_SIZE; - checkOverflow(); - } else { - result.push(null, read(I8_SIZE).readInt8(0)); - } - }; - case NULL_AND_I32_HEADER: - return () => { - result.push(null); - if (isInCurrentBuffer(I32_SIZE)) { - result.push( - /** @type {Buffer} */ (currentBuffer).readInt32LE( - currentPosition - ) - ); - currentPosition += I32_SIZE; - checkOverflow(); - } else { - result.push(read(I32_SIZE).readInt32LE(0)); - } - }; - case NULLS8_HEADER: - return () => { - const len = readU8() + 4; - for (let i = 0; i < len; i++) { - result.push(null); - } - }; - case NULLS32_HEADER: - return () => { - const len = readU32() + 260; - for (let i = 0; i < len; i++) { - result.push(null); - } - }; - case BOOLEANS_HEADER: - return () => { - const innerHeader = readU8(); - if ((innerHeader & 0xf0) === 0) { - readBits(innerHeader, 3); - } else if ((innerHeader & 0xe0) === 0) { - readBits(innerHeader, 4); - } else if ((innerHeader & 0xc0) === 0) { - readBits(innerHeader, 5); - } else if ((innerHeader & 0x80) === 0) { - readBits(innerHeader, 6); - } else if (innerHeader !== 0xff) { - let count = (innerHeader & 0x7f) + 7; - while (count > 8) { - readBits(readU8(), 8); - count -= 8; - } - readBits(readU8(), count); - } else { - let count = readU32(); - while (count > 8) { - readBits(readU8(), 8); - count -= 8; - } - readBits(readU8(), count); - } - }; - case STRING_HEADER: - return () => { - const len = readU32(); - if (isInCurrentBuffer(len) && currentPosition + len < 0x7fffffff) { - result.push( - currentBuffer.toString( - undefined, - currentPosition, - currentPosition + len - ) - ); - currentPosition += len; - checkOverflow(); - } else { - result.push(read(len).toString()); - } - }; - case SHORT_STRING_HEADER: - return () => result.push(""); - case SHORT_STRING_HEADER | 1: - return () => { - if (currentIsBuffer && currentPosition < 0x7ffffffe) { - result.push( - currentBuffer.toString( - "latin1", - currentPosition, - currentPosition + 1 - ) - ); - currentPosition++; - checkOverflow(); - } else { - result.push(read(1).toString("latin1")); - } - }; - case I8_HEADER: - return () => { - if (currentIsBuffer) { - result.push( - /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition) - ); - currentPosition++; - checkOverflow(); - } else { - result.push(read(1).readInt8(0)); - } - }; - default: - if (header <= 10) { - return () => result.push(header); - } else if ((header & SHORT_STRING_HEADER) === SHORT_STRING_HEADER) { - const len = header & SHORT_STRING_LENGTH_MASK; - return () => { - if ( - isInCurrentBuffer(len) && - currentPosition + len < 0x7fffffff - ) { - result.push( - currentBuffer.toString( - "latin1", - currentPosition, - currentPosition + len - ) - ); - currentPosition += len; - checkOverflow(); - } else { - result.push(read(len).toString("latin1")); - } - }; - } else if ((header & NUMBERS_HEADER_MASK) === F64_HEADER) { - const len = (header & NUMBERS_COUNT_MASK) + 1; - return () => { - const need = F64_SIZE * len; - if (isInCurrentBuffer(need)) { - for (let i = 0; i < len; i++) { - result.push( - /** @type {Buffer} */ (currentBuffer).readDoubleLE( - currentPosition - ) - ); - currentPosition += F64_SIZE; - } - checkOverflow(); - } else { - const buf = read(need); - for (let i = 0; i < len; i++) { - result.push(buf.readDoubleLE(i * F64_SIZE)); - } - } - }; - } else if ((header & NUMBERS_HEADER_MASK) === I32_HEADER) { - const len = (header & NUMBERS_COUNT_MASK) + 1; - return () => { - const need = I32_SIZE * len; - if (isInCurrentBuffer(need)) { - for (let i = 0; i < len; i++) { - result.push( - /** @type {Buffer} */ (currentBuffer).readInt32LE( - currentPosition - ) - ); - currentPosition += I32_SIZE; - } - checkOverflow(); - } else { - const buf = read(need); - for (let i = 0; i < len; i++) { - result.push(buf.readInt32LE(i * I32_SIZE)); - } - } - }; - } else if ((header & NUMBERS_HEADER_MASK) === I8_HEADER) { - const len = (header & NUMBERS_COUNT_MASK) + 1; - return () => { - const need = I8_SIZE * len; - if (isInCurrentBuffer(need)) { - for (let i = 0; i < len; i++) { - result.push( - /** @type {Buffer} */ (currentBuffer).readInt8( - currentPosition - ) - ); - currentPosition += I8_SIZE; - } - checkOverflow(); - } else { - const buf = read(need); - for (let i = 0; i < len; i++) { - result.push(buf.readInt8(i * I8_SIZE)); - } - } - }; + const key = this._getKey(item); + const entry = this._entries.get(key); + if (entry !== undefined) { + if (entry.state === DONE_STATE) { + if (inHandleResult++ > 3) { + process.nextTick(() => callback(entry.error, entry.result)); } else { - return () => { - throw new Error( - `Unexpected header byte 0x${header.toString(16)}` - ); - }; + callback(entry.error, entry.result); } + inHandleResult--; + } else if (entry.callbacks === undefined) { + entry.callbacks = [callback]; + } else { + entry.callbacks.push(callback); + } + return; } - }); - - /** @type {DeserializedType} */ - let result = []; - while (currentBuffer !== null) { - if (typeof currentBuffer === "function") { - result.push(this._deserializeLazy(currentBuffer, context)); - currentDataItem++; - currentBuffer = - currentDataItem < data.length ? data[currentDataItem] : null; - currentIsBuffer = Buffer.isBuffer(currentBuffer); + const newEntry = new AsyncQueueEntry(item, callback); + if (this._stopped) { + this.hooks.added.call(item); + this._root._activeTasks++; + process.nextTick(() => + this._handleResult(newEntry, new WebpackError("Queue was stopped")) + ); } else { - const header = readU8(); - dispatchTable[header](); + this._entries.set(key, newEntry); + this._queued.enqueue(newEntry); + const root = this._root; + root._needProcessing = true; + if (root._willEnsureProcessing === false) { + root._willEnsureProcessing = true; + setImmediate(root._ensureProcessing); + } + this.hooks.added.call(item); } + }); + } + + /** + * @param {T} item an item + * @returns {void} + */ + invalidate(item) { + const key = this._getKey(item); + const entry = this._entries.get(key); + this._entries.delete(key); + if (entry.state === QUEUED_STATE) { + this._queued.delete(entry); } + } - // avoid leaking memory in context - let _result = result; - result = undefined; - return _result; + /** + * Waits for an already started item + * @param {T} item an item + * @param {Callback} callback callback function + * @returns {void} + */ + waitFor(item, callback) { + const key = this._getKey(item); + const entry = this._entries.get(key); + if (entry === undefined) { + return callback( + new WebpackError( + "waitFor can only be called for an already started item" + ) + ); + } + if (entry.state === DONE_STATE) { + process.nextTick(() => callback(entry.error, entry.result)); + } else if (entry.callbacks === undefined) { + entry.callbacks = [callback]; + } else { + entry.callbacks.push(callback); + } } -} -module.exports = BinaryMiddleware; + /** + * @returns {void} + */ + stop() { + this._stopped = true; + const queue = this._queued; + this._queued = new ArrayQueue(); + const root = this._root; + for (const entry of queue) { + this._entries.delete(this._getKey(entry.item)); + root._activeTasks++; + this._handleResult(entry, new WebpackError("Queue was stopped")); + } + } -module.exports.MEASURE_START_OPERATION = MEASURE_START_OPERATION; -module.exports.MEASURE_END_OPERATION = MEASURE_END_OPERATION; + /** + * @returns {void} + */ + increaseParallelism() { + const root = this._root; + root._parallelism++; + /* istanbul ignore next */ + if (root._willEnsureProcessing === false && root._needProcessing) { + root._willEnsureProcessing = true; + setImmediate(root._ensureProcessing); + } + } + /** + * @returns {void} + */ + decreaseParallelism() { + const root = this._root; + root._parallelism--; + } -/***/ }), + /** + * @param {T} item an item + * @returns {boolean} true, if the item is currently being processed + */ + isProcessing(item) { + const key = this._getKey(item); + const entry = this._entries.get(key); + return entry !== undefined && entry.state === PROCESSING_STATE; + } -/***/ 93475: -/***/ (function(module) { + /** + * @param {T} item an item + * @returns {boolean} true, if the item is currently queued + */ + isQueued(item) { + const key = this._getKey(item); + const entry = this._entries.get(key); + return entry !== undefined && entry.state === QUEUED_STATE; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + /** + * @param {T} item an item + * @returns {boolean} true, if the item is currently queued + */ + isDone(item) { + const key = this._getKey(item); + const entry = this._entries.get(key); + return entry !== undefined && entry.state === DONE_STATE; + } + + /** + * @returns {void} + */ + _ensureProcessing() { + while (this._activeTasks < this._parallelism) { + const entry = this._queued.dequeue(); + if (entry === undefined) break; + this._activeTasks++; + entry.state = PROCESSING_STATE; + this._startProcessing(entry); + } + this._willEnsureProcessing = false; + if (this._queued.length > 0) return; + if (this._children !== undefined) { + for (const child of this._children) { + while (this._activeTasks < this._parallelism) { + const entry = child._queued.dequeue(); + if (entry === undefined) break; + this._activeTasks++; + entry.state = PROCESSING_STATE; + child._startProcessing(entry); + } + if (child._queued.length > 0) return; + } + } + if (!this._willEnsureProcessing) this._needProcessing = false; + } + + /** + * @param {AsyncQueueEntry} entry the entry + * @returns {void} + */ + _startProcessing(entry) { + this.hooks.beforeStart.callAsync(entry.item, err => { + if (err) { + this._handleResult( + entry, + makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeStart`) + ); + return; + } + let inCallback = false; + try { + this._processor(entry.item, (e, r) => { + inCallback = true; + this._handleResult(entry, e, r); + }); + } catch (err) { + if (inCallback) throw err; + this._handleResult(entry, err, null); + } + this.hooks.started.call(entry.item); + }); + } + + /** + * @param {AsyncQueueEntry} entry the entry + * @param {WebpackError=} err error, if any + * @param {R=} result result, if any + * @returns {void} + */ + _handleResult(entry, err, result) { + this.hooks.result.callAsync(entry.item, err, result, hookError => { + const error = hookError + ? makeWebpackError(hookError, `AsyncQueue(${this._name}).hooks.result`) + : err; + const callback = entry.callback; + const callbacks = entry.callbacks; + entry.state = DONE_STATE; + entry.callback = undefined; + entry.callbacks = undefined; + entry.result = result; + entry.error = error; + const root = this._root; + root._activeTasks--; + if (root._willEnsureProcessing === false && root._needProcessing) { + root._willEnsureProcessing = true; + setImmediate(root._ensureProcessing); + } -class DateObjectSerializer { - serialize(obj, { write }) { - write(obj.getTime()); + if (inHandleResult++ > 3) { + process.nextTick(() => { + callback(error, result); + if (callbacks !== undefined) { + for (const callback of callbacks) { + callback(error, result); + } + } + }); + } else { + callback(error, result); + if (callbacks !== undefined) { + for (const callback of callbacks) { + callback(error, result); + } + } + } + inHandleResult--; + }); } - deserialize({ read }) { - return new Date(read()); + + clear() { + this._entries.clear(); + this._queued.clear(); + this._activeTasks = 0; + this._willEnsureProcessing = false; + this._needProcessing = false; + this._stopped = false; } } -module.exports = DateObjectSerializer; +module.exports = AsyncQueue; /***/ }), -/***/ 79479: -/***/ (function(module) { +/***/ 36692: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -class ErrorObjectSerializer { - constructor(Type) { - this.Type = Type; - } - - serialize(obj, { write }) { - write(obj.message); - write(obj.stack); +class Hash { + /* istanbul ignore next */ + /** + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @abstract + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash + */ + update(data, inputEncoding) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } - deserialize({ read }) { - const err = new this.Type(); - - err.message = read(); - err.stack = read(); - - return err; + /* istanbul ignore next */ + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @abstract + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + const AbstractMethodError = __webpack_require__(77198); + throw new AbstractMethodError(); } } -module.exports = ErrorObjectSerializer; +module.exports = Hash; /***/ }), -/***/ 65321: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 39104: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const { constants } = __webpack_require__(14300); -const { pipeline } = __webpack_require__(12781); -const { - createBrotliCompress, - createBrotliDecompress, - createGzip, - createGunzip, - constants: zConstants -} = __webpack_require__(59796); -const createHash = __webpack_require__(49835); -const { dirname, join, mkdirp } = __webpack_require__(17139); -const memoize = __webpack_require__(78676); -const SerializerMiddleware = __webpack_require__(83137); +/** + * @template T + * @param {Iterable} set a set + * @returns {T | undefined} last item + */ +const last = set => { + let last; + for (const item of set) last = item; + return last; +}; -/** @typedef {typeof import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").IntermediateFileSystem} IntermediateFileSystem */ -/** @typedef {import("./types").BufferSerializableType} BufferSerializableType */ +/** + * @template T + * @param {Iterable} iterable iterable + * @param {function(T): boolean} filter predicate + * @returns {boolean} true, if some items match the filter predicate + */ +const someInIterable = (iterable, filter) => { + for (const item of iterable) { + if (filter(item)) return true; + } + return false; +}; -/* -Format: +/** + * @template T + * @param {Iterable} iterable an iterable + * @returns {number} count of items + */ +const countIterable = iterable => { + let i = 0; + // eslint-disable-next-line no-unused-vars + for (const _ of iterable) i++; + return i; +}; -File -> Header Section* +exports.last = last; +exports.someInIterable = someInIterable; +exports.countIterable = countIterable; -Version -> u32 -AmountOfSections -> u32 -SectionSize -> i32 (if less than zero represents lazy value) -Header -> Version AmountOfSections SectionSize* +/***/ }), -Buffer -> n bytes -Section -> Buffer +/***/ 48424: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -// "wpc" + 1 in little-endian -const VERSION = 0x01637077; + + +const { first } = __webpack_require__(93347); +const SortableSet = __webpack_require__(13098); /** - * @param {Buffer[]} buffers buffers - * @param {string | Hash} hashFunction hash function to use - * @returns {string} hash + * Multi layer bucket sorted set: + * Supports adding non-existing items (DO NOT ADD ITEM TWICE), + * Supports removing exiting items (DO NOT REMOVE ITEM NOT IN SET), + * Supports popping the first items according to defined order, + * Supports iterating all items without order, + * Supports updating an item in an efficient way, + * Supports size property, which is the number of items, + * Items are lazy partially sorted when needed + * @template T + * @template K */ -const hashForName = (buffers, hashFunction) => { - const hash = createHash(hashFunction); - for (const buf of buffers) hash.update(buf); - return /** @type {string} */ (hash.digest("hex")); -}; +class LazyBucketSortedSet { + /** + * @param {function(T): K} getKey function to get key from item + * @param {function(K, K): number} comparator comparator to sort keys + * @param {...((function(T): any) | (function(any, any): number))} args more pairs of getKey and comparator plus optional final comparator for the last layer + */ + constructor(getKey, comparator, ...args) { + this._getKey = getKey; + this._innerArgs = args; + this._leaf = args.length <= 1; + this._keys = new SortableSet(undefined, comparator); + /** @type {Map | SortableSet>} */ + this._map = new Map(); + this._unsortedItems = new Set(); + this.size = 0; + } -const COMPRESSION_CHUNK_SIZE = 100 * 1024 * 1024; -const DECOMPRESSION_CHUNK_SIZE = 100 * 1024 * 1024; + /** + * @param {T} item an item + * @returns {void} + */ + add(item) { + this.size++; + this._unsortedItems.add(item); + } -const writeUInt64LE = Buffer.prototype.writeBigUInt64LE - ? (buf, value, offset) => { - buf.writeBigUInt64LE(BigInt(value), offset); - } - : (buf, value, offset) => { - const low = value % 0x100000000; - const high = (value - low) / 0x100000000; - buf.writeUInt32LE(low, offset); - buf.writeUInt32LE(high, offset + 4); - }; + /** + * @param {K} key key of item + * @param {T} item the item + * @returns {void} + */ + _addInternal(key, item) { + let entry = this._map.get(key); + if (entry === undefined) { + entry = this._leaf + ? new SortableSet(undefined, this._innerArgs[0]) + : new /** @type {any} */ (LazyBucketSortedSet)(...this._innerArgs); + this._keys.add(key); + this._map.set(key, entry); + } + entry.add(item); + } -const readUInt64LE = Buffer.prototype.readBigUInt64LE - ? (buf, offset) => { - return Number(buf.readBigUInt64LE(offset)); - } - : (buf, offset) => { - const low = buf.readUInt32LE(offset); - const high = buf.readUInt32LE(offset + 4); - return high * 0x100000000 + low; - }; + /** + * @param {T} item an item + * @returns {void} + */ + delete(item) { + this.size--; + if (this._unsortedItems.has(item)) { + this._unsortedItems.delete(item); + return; + } + const key = this._getKey(item); + const entry = this._map.get(key); + entry.delete(item); + if (entry.size === 0) { + this._deleteKey(key); + } + } -/** - * @typedef {Object} SerializeResult - * @property {string | false} name - * @property {number} size - * @property {Promise=} backgroundJob - */ + /** + * @param {K} key key to be removed + * @returns {void} + */ + _deleteKey(key) { + this._keys.delete(key); + this._map.delete(key); + } -/** - * @param {FileMiddleware} middleware this - * @param {BufferSerializableType[] | Promise} data data to be serialized - * @param {string | boolean} name file base name - * @param {function(string | false, Buffer[]): Promise} writeFile writes a file - * @param {string | Hash} hashFunction hash function to use - * @returns {Promise} resulting file pointer and promise - */ -const serialize = async ( - middleware, - data, - name, - writeFile, - hashFunction = "md4" -) => { - /** @type {(Buffer[] | Buffer | SerializeResult | Promise)[]} */ - const processedData = []; - /** @type {WeakMap>} */ - const resultToLazy = new WeakMap(); - /** @type {Buffer[]} */ - let lastBuffers = undefined; - for (const item of await data) { - if (typeof item === "function") { - if (!SerializerMiddleware.isLazy(item)) - throw new Error("Unexpected function"); - if (!SerializerMiddleware.isLazy(item, middleware)) { - throw new Error( - "Unexpected lazy value with non-this target (can't pass through lazy values)" - ); + /** + * @returns {T | undefined} an item + */ + popFirst() { + if (this.size === 0) return undefined; + this.size--; + if (this._unsortedItems.size > 0) { + for (const item of this._unsortedItems) { + const key = this._getKey(item); + this._addInternal(key, item); } - lastBuffers = undefined; - const serializedInfo = SerializerMiddleware.getLazySerializedValue(item); - if (serializedInfo) { - if (typeof serializedInfo === "function") { - throw new Error( - "Unexpected lazy value with non-this target (can't pass through lazy values)" - ); - } else { - processedData.push(serializedInfo); + this._unsortedItems.clear(); + } + this._keys.sort(); + const key = first(this._keys); + const entry = this._map.get(key); + if (this._leaf) { + const leafEntry = /** @type {SortableSet} */ (entry); + leafEntry.sort(); + const item = first(leafEntry); + leafEntry.delete(item); + if (leafEntry.size === 0) { + this._deleteKey(key); + } + return item; + } else { + const nodeEntry = /** @type {LazyBucketSortedSet} */ (entry); + const item = nodeEntry.popFirst(); + if (nodeEntry.size === 0) { + this._deleteKey(key); + } + return item; + } + } + + /** + * @param {T} item to be updated item + * @returns {function(true=): void} finish update + */ + startUpdate(item) { + if (this._unsortedItems.has(item)) { + return remove => { + if (remove) { + this._unsortedItems.delete(item); + this.size--; + return; } - } else { - const content = item(); - if (content) { - const options = SerializerMiddleware.getLazyOptions(item); - processedData.push( - serialize( - middleware, - content, - (options && options.name) || true, - writeFile, - hashFunction - ).then(result => { - /** @type {any} */ (item).options.size = result.size; - resultToLazy.set(result, item); - return result; - }) - ); + }; + } + const key = this._getKey(item); + if (this._leaf) { + const oldEntry = /** @type {SortableSet} */ (this._map.get(key)); + return remove => { + if (remove) { + this.size--; + oldEntry.delete(item); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + return; + } + const newKey = this._getKey(item); + if (key === newKey) { + // This flags the sortable set as unordered + oldEntry.add(item); } else { - throw new Error( - "Unexpected falsy value returned by lazy value function" - ); + oldEntry.delete(item); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + this._addInternal(newKey, item); } - } - } else if (item) { - if (lastBuffers) { - lastBuffers.push(item); - } else { - lastBuffers = [item]; - processedData.push(lastBuffers); - } + }; } else { - throw new Error("Unexpected falsy value in items array"); + const oldEntry = /** @type {LazyBucketSortedSet} */ ( + this._map.get(key) + ); + const finishUpdate = oldEntry.startUpdate(item); + return remove => { + if (remove) { + this.size--; + finishUpdate(true); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + return; + } + const newKey = this._getKey(item); + if (key === newKey) { + finishUpdate(); + } else { + finishUpdate(true); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + this._addInternal(newKey, item); + } + }; } } - /** @type {Promise[]} */ - const backgroundJobs = []; - const resolvedData = ( - await Promise.all( - /** @type {Promise[]} */ ( - processedData - ) - ) - ).map(item => { - if (Array.isArray(item) || Buffer.isBuffer(item)) return item; - backgroundJobs.push(item.backgroundJob); - // create pointer buffer from size and name - const name = /** @type {string} */ (item.name); - const nameBuffer = Buffer.from(name); - const buf = Buffer.allocUnsafe(8 + nameBuffer.length); - writeUInt64LE(buf, item.size, 0); - nameBuffer.copy(buf, 8, 0); - const lazy = resultToLazy.get(item); - SerializerMiddleware.setLazySerializedValue(lazy, buf); - return buf; - }); - const lengths = []; - for (const item of resolvedData) { - if (Array.isArray(item)) { - let l = 0; - for (const b of item) l += b.length; - while (l > 0x7fffffff) { - lengths.push(0x7fffffff); - l -= 0x7fffffff; + /** + * @param {Iterator[]} iterators list of iterators to append to + * @returns {void} + */ + _appendIterators(iterators) { + if (this._unsortedItems.size > 0) + iterators.push(this._unsortedItems[Symbol.iterator]()); + for (const key of this._keys) { + const entry = this._map.get(key); + if (this._leaf) { + const leafEntry = /** @type {SortableSet} */ (entry); + const iterator = leafEntry[Symbol.iterator](); + iterators.push(iterator); + } else { + const nodeEntry = /** @type {LazyBucketSortedSet} */ (entry); + nodeEntry._appendIterators(iterators); } - lengths.push(l); - } else if (item) { - lengths.push(-item.length); - } else { - throw new Error("Unexpected falsy value in resolved data " + item); } } - const header = Buffer.allocUnsafe(8 + lengths.length * 4); - header.writeUInt32LE(VERSION, 0); - header.writeUInt32LE(lengths.length, 4); - for (let i = 0; i < lengths.length; i++) { - header.writeInt32LE(lengths[i], 8 + i * 4); + + /** + * @returns {Iterator} the iterator + */ + [Symbol.iterator]() { + const iterators = []; + this._appendIterators(iterators); + iterators.reverse(); + let currentIterator = iterators.pop(); + return { + next: () => { + const res = currentIterator.next(); + if (res.done) { + if (iterators.length === 0) return res; + currentIterator = iterators.pop(); + return currentIterator.next(); + } + return res; + } + }; } - const buf = [header]; - for (const item of resolvedData) { - if (Array.isArray(item)) { - for (const b of item) buf.push(b); - } else if (item) { - buf.push(item); +} + +module.exports = LazyBucketSortedSet; + + +/***/ }), + +/***/ 38938: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const makeSerializable = __webpack_require__(33032); + +/** + * @template T + * @param {Set} targetSet set where items should be added + * @param {Set>} toMerge iterables to be merged + * @returns {void} + */ +const merge = (targetSet, toMerge) => { + for (const set of toMerge) { + for (const item of set) { + targetSet.add(item); } } - if (name === true) { - name = hashForName(buf, hashFunction); - } - backgroundJobs.push(writeFile(name, buf)); - let size = 0; - for (const b of buf) size += b.length; - return { - size, - name, - backgroundJob: - backgroundJobs.length === 1 - ? backgroundJobs[0] - : Promise.all(backgroundJobs) - }; }; /** - * @param {FileMiddleware} middleware this - * @param {string | false} name filename - * @param {function(string | false): Promise} readFile read content of a file - * @returns {Promise} deserialized data + * @template T + * @param {Set>} targetSet set where iterables should be added + * @param {Array>} toDeepMerge lazy sets to be flattened + * @returns {void} */ -const deserialize = async (middleware, name, readFile) => { - const contents = await readFile(name); - if (contents.length === 0) throw new Error("Empty file " + name); - let contentsIndex = 0; - let contentItem = contents[0]; - let contentItemLength = contentItem.length; - let contentPosition = 0; - if (contentItemLength === 0) throw new Error("Empty file " + name); - const nextContent = () => { - contentsIndex++; - contentItem = contents[contentsIndex]; - contentItemLength = contentItem.length; - contentPosition = 0; - }; - const ensureData = n => { - if (contentPosition === contentItemLength) { - nextContent(); - } - while (contentItemLength - contentPosition < n) { - const remaining = contentItem.slice(contentPosition); - let lengthFromNext = n - remaining.length; - const buffers = [remaining]; - for (let i = contentsIndex + 1; i < contents.length; i++) { - const l = contents[i].length; - if (l > lengthFromNext) { - buffers.push(contents[i].slice(0, lengthFromNext)); - contents[i] = contents[i].slice(lengthFromNext); - lengthFromNext = 0; - break; - } else { - buffers.push(contents[i]); - contentsIndex = i; - lengthFromNext -= l; - } - } - if (lengthFromNext > 0) throw new Error("Unexpected end of data"); - contentItem = Buffer.concat(buffers, n); - contentItemLength = n; - contentPosition = 0; - } - }; - const readUInt32LE = () => { - ensureData(4); - const value = contentItem.readUInt32LE(contentPosition); - contentPosition += 4; - return value; - }; - const readInt32LE = () => { - ensureData(4); - const value = contentItem.readInt32LE(contentPosition); - contentPosition += 4; - return value; - }; - const readSlice = l => { - ensureData(l); - if (contentPosition === 0 && contentItemLength === l) { - const result = contentItem; - if (contentsIndex + 1 < contents.length) { - nextContent(); - } else { - contentPosition = l; +const flatten = (targetSet, toDeepMerge) => { + for (const set of toDeepMerge) { + if (set._set.size > 0) targetSet.add(set._set); + if (set._needMerge) { + for (const mergedSet of set._toMerge) { + targetSet.add(mergedSet); } - return result; + flatten(targetSet, set._toDeepMerge); } - const result = contentItem.slice(contentPosition, contentPosition + l); - contentPosition += l; - // we clone the buffer here to allow the original content to be garbage collected - return l * 2 < contentItem.buffer.byteLength ? Buffer.from(result) : result; - }; - const version = readUInt32LE(); - if (version !== VERSION) { - throw new Error("Invalid file version"); } - const sectionCount = readUInt32LE(); - const lengths = []; - let lastLengthPositive = false; - for (let i = 0; i < sectionCount; i++) { - const value = readInt32LE(); - const valuePositive = value >= 0; - if (lastLengthPositive && valuePositive) { - lengths[lengths.length - 1] += value; - } else { - lengths.push(value); - lastLengthPositive = valuePositive; - } +}; + +/** + * Like Set but with an addAll method to eventually add items from another iterable. + * Access methods make sure that all delayed operations are executed. + * Iteration methods deopts to normal Set performance until clear is called again (because of the chance of modifications during iteration). + * @template T + */ +class LazySet { + /** + * @param {Iterable=} iterable init iterable + */ + constructor(iterable) { + /** @type {Set} */ + this._set = new Set(iterable); + /** @type {Set>} */ + this._toMerge = new Set(); + /** @type {Array>} */ + this._toDeepMerge = []; + this._needMerge = false; + this._deopt = false; } - const result = []; - for (let length of lengths) { - if (length < 0) { - const slice = readSlice(-length); - const size = Number(readUInt64LE(slice, 0)); - const nameBuffer = slice.slice(8); - const name = nameBuffer.toString(); - result.push( - SerializerMiddleware.createLazy( - memoize(() => deserialize(middleware, name, readFile)), - middleware, - { - name, - size - }, - slice - ) - ); + + _flatten() { + flatten(this._toMerge, this._toDeepMerge); + this._toDeepMerge.length = 0; + } + + _merge() { + this._flatten(); + merge(this._set, this._toMerge); + this._toMerge.clear(); + this._needMerge = false; + } + + _isEmpty() { + return ( + this._set.size === 0 && + this._toMerge.size === 0 && + this._toDeepMerge.length === 0 + ); + } + + get size() { + if (this._needMerge) this._merge(); + return this._set.size; + } + + /** + * @param {T} item an item + * @returns {this} itself + */ + add(item) { + this._set.add(item); + return this; + } + + /** + * @param {Iterable | LazySet} iterable a immutable iterable or another immutable LazySet which will eventually be merged into the Set + * @returns {this} itself + */ + addAll(iterable) { + if (this._deopt) { + const _set = this._set; + for (const item of iterable) { + _set.add(item); + } } else { - if (contentPosition === contentItemLength) { - nextContent(); - } else if (contentPosition !== 0) { - if (length <= contentItemLength - contentPosition) { - result.push( - Buffer.from( - contentItem.buffer, - contentItem.byteOffset + contentPosition, - length - ) - ); - contentPosition += length; - length = 0; - } else { - const l = contentItemLength - contentPosition; - result.push( - Buffer.from( - contentItem.buffer, - contentItem.byteOffset + contentPosition, - l - ) - ); - length -= l; - contentPosition = contentItemLength; + if (iterable instanceof LazySet) { + if (iterable._isEmpty()) return this; + this._toDeepMerge.push(iterable); + this._needMerge = true; + if (this._toDeepMerge.length > 100000) { + this._flatten(); } } else { - if (length >= contentItemLength) { - result.push(contentItem); - length -= contentItemLength; - contentPosition = contentItemLength; - } else { - result.push( - Buffer.from(contentItem.buffer, contentItem.byteOffset, length) - ); - contentPosition += length; - length = 0; - } - } - while (length > 0) { - nextContent(); - if (length >= contentItemLength) { - result.push(contentItem); - length -= contentItemLength; - contentPosition = contentItemLength; - } else { - result.push( - Buffer.from(contentItem.buffer, contentItem.byteOffset, length) - ); - contentPosition += length; - length = 0; - } + this._toMerge.add(iterable); + this._needMerge = true; } + if (this._toMerge.size > 100000) this._merge(); } + return this; + } + + clear() { + this._set.clear(); + this._toMerge.clear(); + this._toDeepMerge.length = 0; + this._needMerge = false; + this._deopt = false; + } + + /** + * @param {T} value an item + * @returns {boolean} true, if the value was in the Set before + */ + delete(value) { + if (this._needMerge) this._merge(); + return this._set.delete(value); + } + + entries() { + this._deopt = true; + if (this._needMerge) this._merge(); + return this._set.entries(); } - return result; -}; -/** - * @typedef {BufferSerializableType[]} DeserializedType - * @typedef {true} SerializedType - * @extends {SerializerMiddleware} - */ -class FileMiddleware extends SerializerMiddleware { /** - * @param {IntermediateFileSystem} fs filesystem - * @param {string | Hash} hashFunction hash function to use + * @param {function(T, T, Set): void} callbackFn function called for each entry + * @param {any} thisArg this argument for the callbackFn + * @returns {void} */ - constructor(fs, hashFunction = "md4") { - super(); - this.fs = fs; - this._hashFunction = hashFunction; + forEach(callbackFn, thisArg) { + this._deopt = true; + if (this._needMerge) this._merge(); + this._set.forEach(callbackFn, thisArg); } + /** - * @param {DeserializedType} data data - * @param {Object} context context object - * @returns {SerializedType|Promise} serialized data + * @param {T} item an item + * @returns {boolean} true, when the item is in the Set */ - serialize(data, context) { - const { filename, extension = "" } = context; - return new Promise((resolve, reject) => { - mkdirp(this.fs, dirname(this.fs, filename), err => { - if (err) return reject(err); + has(item) { + if (this._needMerge) this._merge(); + return this._set.has(item); + } - // It's important that we don't touch existing files during serialization - // because serialize may read existing files (when deserializing) - const allWrittenFiles = new Set(); - const writeFile = async (name, content) => { - const file = name - ? join(this.fs, filename, `../${name}${extension}`) - : filename; - await new Promise((resolve, reject) => { - let stream = this.fs.createWriteStream(file + "_"); - let compression; - if (file.endsWith(".gz")) { - compression = createGzip({ - chunkSize: COMPRESSION_CHUNK_SIZE, - level: zConstants.Z_BEST_SPEED - }); - } else if (file.endsWith(".br")) { - compression = createBrotliCompress({ - chunkSize: COMPRESSION_CHUNK_SIZE, - params: { - [zConstants.BROTLI_PARAM_MODE]: zConstants.BROTLI_MODE_TEXT, - [zConstants.BROTLI_PARAM_QUALITY]: 2, - [zConstants.BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING]: true, - [zConstants.BROTLI_PARAM_SIZE_HINT]: content.reduce( - (size, b) => size + b.length, - 0 - ) - } - }); - } - if (compression) { - pipeline(compression, stream, reject); - stream = compression; - stream.on("finish", () => resolve()); - } else { - stream.on("error", err => reject(err)); - stream.on("finish", () => resolve()); - } - for (const b of content) stream.write(b); - stream.end(); - }); - if (name) allWrittenFiles.add(file); - }; + keys() { + this._deopt = true; + if (this._needMerge) this._merge(); + return this._set.keys(); + } - resolve( - serialize(this, data, false, writeFile, this._hashFunction).then( - async ({ backgroundJob }) => { - await backgroundJob; + values() { + this._deopt = true; + if (this._needMerge) this._merge(); + return this._set.values(); + } - // Rename the index file to disallow access during inconsistent file state - await new Promise(resolve => - this.fs.rename(filename, filename + ".old", err => { - resolve(); - }) - ); + [Symbol.iterator]() { + this._deopt = true; + if (this._needMerge) this._merge(); + return this._set[Symbol.iterator](); + } - // update all written files - await Promise.all( - Array.from( - allWrittenFiles, - file => - new Promise((resolve, reject) => { - this.fs.rename(file + "_", file, err => { - if (err) return reject(err); - resolve(); - }); - }) - ) - ); + /* istanbul ignore next */ + get [Symbol.toStringTag]() { + return "LazySet"; + } - // As final step automatically update the index file to have a consistent pack again - await new Promise(resolve => { - this.fs.rename(filename + "_", filename, err => { - if (err) return reject(err); - resolve(); - }); - }); - return /** @type {true} */ (true); - } - ) - ); - }); - }); + serialize({ write }) { + if (this._needMerge) this._merge(); + write(this._set.size); + for (const item of this._set) write(item); } - /** - * @param {SerializedType} data data - * @param {Object} context context object - * @returns {DeserializedType|Promise} deserialized data - */ - deserialize(data, context) { - const { filename, extension = "" } = context; - const readFile = name => - new Promise((resolve, reject) => { - const file = name - ? join(this.fs, filename, `../${name}${extension}`) - : filename; - this.fs.stat(file, (err, stats) => { - if (err) { - reject(err); - return; - } - let remaining = /** @type {number} */ (stats.size); - let currentBuffer; - let currentBufferUsed; - const buf = []; - let decompression; - if (file.endsWith(".gz")) { - decompression = createGunzip({ - chunkSize: DECOMPRESSION_CHUNK_SIZE - }); - } else if (file.endsWith(".br")) { - decompression = createBrotliDecompress({ - chunkSize: DECOMPRESSION_CHUNK_SIZE - }); - } - if (decompression) { - let newResolve, newReject; - resolve( - Promise.all([ - new Promise((rs, rj) => { - newResolve = rs; - newReject = rj; - }), - new Promise((resolve, reject) => { - decompression.on("data", chunk => buf.push(chunk)); - decompression.on("end", () => resolve()); - decompression.on("error", err => reject(err)); - }) - ]).then(() => buf) - ); - resolve = newResolve; - reject = newReject; - } - this.fs.open(file, "r", (err, fd) => { - if (err) { - reject(err); - return; - } - const read = () => { - if (currentBuffer === undefined) { - currentBuffer = Buffer.allocUnsafeSlow( - Math.min( - constants.MAX_LENGTH, - remaining, - decompression ? DECOMPRESSION_CHUNK_SIZE : Infinity - ) - ); - currentBufferUsed = 0; - } - let readBuffer = currentBuffer; - let readOffset = currentBufferUsed; - let readLength = currentBuffer.length - currentBufferUsed; - // values passed to fs.read must be valid int32 values - if (readOffset > 0x7fffffff) { - readBuffer = currentBuffer.slice(readOffset); - readOffset = 0; - } - if (readLength > 0x7fffffff) { - readLength = 0x7fffffff; - } - this.fs.read( - fd, - readBuffer, - readOffset, - readLength, - null, - (err, bytesRead) => { - if (err) { - this.fs.close(fd, () => { - reject(err); - }); - return; - } - currentBufferUsed += bytesRead; - remaining -= bytesRead; - if (currentBufferUsed === currentBuffer.length) { - if (decompression) { - decompression.write(currentBuffer); - } else { - buf.push(currentBuffer); - } - currentBuffer = undefined; - if (remaining === 0) { - if (decompression) { - decompression.end(); - } - this.fs.close(fd, err => { - if (err) { - reject(err); - return; - } - resolve(buf); - }); - return; - } - } - read(); - } - ); - }; - read(); - }); - }); - }); - return deserialize(this, false, readFile); + static deserialize({ read }) { + const count = read(); + const items = []; + for (let i = 0; i < count; i++) { + items.push(read()); + } + return new LazySet(items); } } -module.exports = FileMiddleware; +makeSerializable(LazySet, "webpack/lib/util/LazySet"); + +module.exports = LazySet; /***/ }), -/***/ 86791: -/***/ (function(module) { +/***/ 82482: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -class MapObjectSerializer { - serialize(obj, { write }) { - write(obj.size); - for (const key of obj.keys()) { - write(key); - } - for (const value of obj.values()) { - write(value); - } - } - deserialize({ read }) { - let size = read(); - const map = new Map(); - const keys = []; - for (let i = 0; i < size; i++) { - keys.push(read()); - } - for (let i = 0; i < size; i++) { - map.set(keys[i], read()); - } - return map; - } -} - -module.exports = MapObjectSerializer; +/** + * @template K + * @template V + * @param {Map} map a map + * @param {K} key the key + * @param {function(): V} computer compute value + * @returns {V} value + */ +exports.provide = (map, key, computer) => { + const value = map.get(key); + if (value !== undefined) return value; + const newValue = computer(); + map.set(key, newValue); + return newValue; +}; /***/ }), -/***/ 21048: -/***/ (function(module) { +/***/ 50780: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -class NullPrototypeObjectSerializer { - serialize(obj, { write }) { - const keys = Object.keys(obj); - for (const key of keys) { - write(key); - } - write(null); - for (const key of keys) { - write(obj[key]); - } +const binarySearchBounds = __webpack_require__(92229); + +class ParallelismFactorCalculator { + constructor() { + this._rangePoints = []; + this._rangeCallbacks = []; } - deserialize({ read }) { - const obj = Object.create(null); - const keys = []; - let key = read(); - while (key !== null) { - keys.push(key); - key = read(); + + range(start, end, callback) { + if (start === end) return callback(1); + this._rangePoints.push(start); + this._rangePoints.push(end); + this._rangeCallbacks.push(callback); + } + + calculate() { + const segments = Array.from(new Set(this._rangePoints)).sort((a, b) => + a < b ? -1 : 1 + ); + const parallelism = segments.map(() => 0); + const rangeStartIndices = []; + for (let i = 0; i < this._rangePoints.length; i += 2) { + const start = this._rangePoints[i]; + const end = this._rangePoints[i + 1]; + let idx = binarySearchBounds.eq(segments, start); + rangeStartIndices.push(idx); + do { + parallelism[idx]++; + idx++; + } while (segments[idx] < end); } - for (const key of keys) { - obj[key] = read(); + for (let i = 0; i < this._rangeCallbacks.length; i++) { + const start = this._rangePoints[i * 2]; + const end = this._rangePoints[i * 2 + 1]; + let idx = rangeStartIndices[i]; + let sum = 0; + let totalDuration = 0; + let current = start; + do { + const p = parallelism[idx]; + idx++; + const duration = segments[idx] - current; + totalDuration += duration; + current = segments[idx]; + sum += p * duration; + } while (current < end); + this._rangeCallbacks[i](sum / totalDuration); } - return obj; } } -module.exports = NullPrototypeObjectSerializer; +module.exports = ParallelismFactorCalculator; /***/ }), -/***/ 34795: -/***/ (function(module, exports, __webpack_require__) { +/***/ 65930: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const createHash = __webpack_require__(49835); -const ArraySerializer = __webpack_require__(41721); -const DateObjectSerializer = __webpack_require__(93475); -const ErrorObjectSerializer = __webpack_require__(79479); -const MapObjectSerializer = __webpack_require__(86791); -const NullPrototypeObjectSerializer = __webpack_require__(21048); -const PlainObjectSerializer = __webpack_require__(33040); -const RegExpObjectSerializer = __webpack_require__(57328); -const SerializerMiddleware = __webpack_require__(83137); -const SetObjectSerializer = __webpack_require__(79240); +/** + * @template T + */ +class Queue { + /** + * @param {Iterable=} items The initial elements. + */ + constructor(items) { + /** @private @type {Set} */ + this._set = new Set(items); + /** @private @type {Iterator} */ + this._iterator = this._set[Symbol.iterator](); + } -/** @typedef {typeof import("../util/Hash")} Hash */ -/** @typedef {import("./types").ComplexSerializableType} ComplexSerializableType */ -/** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */ + /** + * Returns the number of elements in this queue. + * @returns {number} The number of elements in this queue. + */ + get length() { + return this._set.size; + } -/** @typedef {new (...params: any[]) => any} Constructor */ + /** + * Appends the specified element to this queue. + * @param {T} item The element to add. + * @returns {void} + */ + enqueue(item) { + this._set.add(item); + } -/* + /** + * Retrieves and removes the head of this queue. + * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + */ + dequeue() { + const result = this._iterator.next(); + if (result.done) return undefined; + this._set.delete(result.value); + return result.value; + } +} -Format: +module.exports = Queue; -File -> Section* -Section -> ObjectSection | ReferenceSection | EscapeSection | OtherSection -ObjectSection -> ESCAPE ( - number:relativeOffset (number > 0) | - string:request (string|null):export -) Section:value* ESCAPE ESCAPE_END_OBJECT -ReferenceSection -> ESCAPE number:relativeOffset (number < 0) -EscapeSection -> ESCAPE ESCAPE_ESCAPE_VALUE (escaped value ESCAPE) -EscapeSection -> ESCAPE ESCAPE_UNDEFINED (escaped value ESCAPE) -OtherSection -> any (except ESCAPE) +/***/ }), -Why using null as escape value? -Multiple null values can merged by the BinaryMiddleware, which makes it very efficient -Technically any value can be used. +/***/ 93347: +/***/ (function(__unused_webpack_module, exports) { +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ + + /** - * @typedef {Object} ObjectSerializerContext - * @property {function(any): void} write + * intersect creates Set containing the intersection of elements between all sets + * @template T + * @param {Set[]} sets an array of sets being checked for shared elements + * @returns {Set} returns a new Set containing the intersecting items */ +const intersect = sets => { + if (sets.length === 0) return new Set(); + if (sets.length === 1) return new Set(sets[0]); + let minSize = Infinity; + let minIndex = -1; + for (let i = 0; i < sets.length; i++) { + const size = sets[i].size; + if (size < minSize) { + minIndex = i; + minSize = size; + } + } + const current = new Set(sets[minIndex]); + for (let i = 0; i < sets.length; i++) { + if (i === minIndex) continue; + const set = sets[i]; + for (const item of current) { + if (!set.has(item)) { + current.delete(item); + } + } + } + return current; +}; /** - * @typedef {Object} ObjectDeserializerContext - * @property {function(): any} read + * Checks if a set is the subset of another set + * @template T + * @param {Set} bigSet a Set which contains the original elements to compare against + * @param {Set} smallSet the set whose elements might be contained inside of bigSet + * @returns {boolean} returns true if smallSet contains all elements inside of the bigSet */ +const isSubset = (bigSet, smallSet) => { + if (bigSet.size < smallSet.size) return false; + for (const item of smallSet) { + if (!bigSet.has(item)) return false; + } + return true; +}; /** - * @typedef {Object} ObjectSerializer - * @property {function(any, ObjectSerializerContext): void} serialize - * @property {function(ObjectDeserializerContext): any} deserialize + * @template T + * @param {Set} set a set + * @param {function(T): boolean} fn selector function + * @returns {T | undefined} found item */ - -const setSetSize = (set, size) => { - let i = 0; +const find = (set, fn) => { for (const item of set) { - if (i++ >= size) { - set.delete(item); - } + if (fn(item)) return item; } }; -const setMapSize = (map, size) => { - let i = 0; - for (const item of map.keys()) { - if (i++ >= size) { - map.delete(item); - } - } +/** + * @template T + * @param {Set} set a set + * @returns {T | undefined} first item + */ +const first = set => { + const entry = set.values().next(); + return entry.done ? undefined : entry.value; }; /** - * @param {Buffer} buffer buffer - * @param {string | Hash} hashFunction hash function to use - * @returns {string} hash + * @template T + * @param {Set} a first + * @param {Set} b second + * @returns {Set} combined set, may be identical to a or b */ -const toHash = (buffer, hashFunction) => { - const hash = createHash(hashFunction); - hash.update(buffer); - return /** @type {string} */ (hash.digest("latin1")); +const combine = (a, b) => { + if (b.size === 0) return a; + if (a.size === 0) return b; + const set = new Set(a); + for (const item of b) set.add(item); + return set; }; -const ESCAPE = null; -const ESCAPE_ESCAPE_VALUE = null; -const ESCAPE_END_OBJECT = true; -const ESCAPE_UNDEFINED = false; - -const CURRENT_VERSION = 2; - -const serializers = new Map(); -const serializerInversed = new Map(); +exports.intersect = intersect; +exports.isSubset = isSubset; +exports.find = find; +exports.first = first; +exports.combine = combine; -const loadedRequests = new Set(); -const NOT_SERIALIZABLE = {}; +/***/ }), -const jsTypes = new Map(); -jsTypes.set(Object, new PlainObjectSerializer()); -jsTypes.set(Array, new ArraySerializer()); -jsTypes.set(null, new NullPrototypeObjectSerializer()); -jsTypes.set(Map, new MapObjectSerializer()); -jsTypes.set(Set, new SetObjectSerializer()); -jsTypes.set(Date, new DateObjectSerializer()); -jsTypes.set(RegExp, new RegExpObjectSerializer()); -jsTypes.set(Error, new ErrorObjectSerializer(Error)); -jsTypes.set(EvalError, new ErrorObjectSerializer(EvalError)); -jsTypes.set(RangeError, new ErrorObjectSerializer(RangeError)); -jsTypes.set(ReferenceError, new ErrorObjectSerializer(ReferenceError)); -jsTypes.set(SyntaxError, new ErrorObjectSerializer(SyntaxError)); -jsTypes.set(TypeError, new ErrorObjectSerializer(TypeError)); +/***/ 13098: +/***/ (function(module) { -// If in a sandboxed environment (e. g. jest), this escapes the sandbox and registers -// real Object and Array types to. These types may occur in the wild too, e. g. when -// using Structured Clone in postMessage. -if (exports.constructor !== Object) { - const Obj = /** @type {typeof Object} */ (exports.constructor); - const Fn = /** @type {typeof Function} */ (Obj.constructor); - for (const [type, config] of Array.from(jsTypes)) { - if (type) { - const Type = new Fn(`return ${type.name};`)(); - jsTypes.set(Type, config); - } - } -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -{ - let i = 1; - for (const [type, serializer] of jsTypes) { - serializers.set(type, { - request: "", - name: i++, - serializer - }); - } -} -for (const { request, name, serializer } of serializers.values()) { - serializerInversed.set(`${request}/${name}`, serializer); -} -/** @type {Map boolean>} */ -const loaders = new Map(); +const NONE = Symbol("not sorted"); /** - * @typedef {ComplexSerializableType[]} DeserializedType - * @typedef {PrimitiveSerializableType[]} SerializedType - * @extends {SerializerMiddleware} + * A subset of Set that offers sorting functionality + * @template T item type in set + * @extends {Set} */ -class ObjectMiddleware extends SerializerMiddleware { +class SortableSet extends Set { /** - * @param {function(any): void} extendContext context extensions - * @param {string | Hash} hashFunction hash function to use + * Create a new sortable set + * @param {Iterable=} initialIterable The initial iterable value + * @typedef {function(T, T): number} SortFunction + * @param {SortFunction=} defaultSort Default sorting function */ - constructor(extendContext, hashFunction = "md4") { - super(); - this.extendContext = extendContext; - this._hashFunction = hashFunction; + constructor(initialIterable, defaultSort) { + super(initialIterable); + /** @private @type {undefined | function(T, T): number}} */ + this._sortFn = defaultSort; + /** @private @type {typeof NONE | undefined | function(T, T): number}} */ + this._lastActiveSortFn = NONE; + /** @private @type {Map | undefined} */ + this._cache = undefined; + /** @private @type {Map | undefined} */ + this._cacheOrderIndependent = undefined; } + /** - * @param {RegExp} regExp RegExp for which the request is tested - * @param {function(string): boolean} loader loader to load the request, returns true when successful - * @returns {void} + * @param {T} value value to add to set + * @returns {this} returns itself */ - static registerLoader(regExp, loader) { - loaders.set(regExp, loader); + add(value) { + this._lastActiveSortFn = NONE; + this._invalidateCache(); + this._invalidateOrderedCache(); + super.add(value); + return this; } /** - * @param {Constructor} Constructor the constructor - * @param {string} request the request which will be required when deserializing - * @param {string} name the name to make multiple serializer unique when sharing a request - * @param {ObjectSerializer} serializer the serializer - * @returns {void} + * @param {T} value value to delete + * @returns {boolean} true if value existed in set, false otherwise */ - static register(Constructor, request, name, serializer) { - const key = request + "/" + name; - - if (serializers.has(Constructor)) { - throw new Error( - `ObjectMiddleware.register: serializer for ${Constructor.name} is already registered` - ); - } - - if (serializerInversed.has(key)) { - throw new Error( - `ObjectMiddleware.register: serializer for ${key} is already registered` - ); - } - - serializers.set(Constructor, { - request, - name, - serializer - }); - - serializerInversed.set(key, serializer); + delete(value) { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.delete(value); } /** - * @param {Constructor} Constructor the constructor * @returns {void} */ - static registerNotSerializable(Constructor) { - if (serializers.has(Constructor)) { - throw new Error( - `ObjectMiddleware.registerNotSerializable: serializer for ${Constructor.name} is already registered` - ); - } - - serializers.set(Constructor, NOT_SERIALIZABLE); - } - - static getSerializerFor(object) { - const proto = Object.getPrototypeOf(object); - let c; - if (proto === null) { - // Object created with Object.create(null) - c = null; - } else { - c = proto.constructor; - if (!c) { - throw new Error( - "Serialization of objects with prototype without valid constructor property not possible" - ); - } - } - const config = serializers.get(c); - - if (!config) throw new Error(`No serializer registered for ${c.name}`); - if (config === NOT_SERIALIZABLE) throw NOT_SERIALIZABLE; - - return config; - } - - static getDeserializerFor(request, name) { - const key = request + "/" + name; - const serializer = serializerInversed.get(key); - - if (serializer === undefined) { - throw new Error(`No deserializer registered for ${key}`); - } - - return serializer; - } - - static _getDeserializerForWithoutError(request, name) { - const key = request + "/" + name; - const serializer = serializerInversed.get(key); - return serializer; + clear() { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.clear(); } /** - * @param {DeserializedType} data data - * @param {Object} context context object - * @returns {SerializedType|Promise} serialized data + * Sort with a comparer function + * @param {SortFunction} sortFn Sorting comparer function + * @returns {void} */ - serialize(data, context) { - /** @type {any[]} */ - let result = [CURRENT_VERSION]; - let currentPos = 0; - let referenceable = new Map(); - const addReferenceable = item => { - referenceable.set(item, currentPos++); - }; - let bufferDedupeMap = new Map(); - const dedupeBuffer = buf => { - const len = buf.length; - const entry = bufferDedupeMap.get(len); - if (entry === undefined) { - bufferDedupeMap.set(len, buf); - return buf; - } - if (Buffer.isBuffer(entry)) { - if (len < 32) { - if (buf.equals(entry)) { - return entry; - } - bufferDedupeMap.set(len, [entry, buf]); - return buf; - } else { - const hash = toHash(entry, this._hashFunction); - const newMap = new Map(); - newMap.set(hash, entry); - bufferDedupeMap.set(len, newMap); - const hashBuf = toHash(buf, this._hashFunction); - if (hash === hashBuf) { - return entry; - } - return buf; - } - } else if (Array.isArray(entry)) { - if (entry.length < 16) { - for (const item of entry) { - if (buf.equals(item)) { - return item; - } - } - entry.push(buf); - return buf; - } else { - const newMap = new Map(); - const hash = toHash(buf, this._hashFunction); - let found; - for (const item of entry) { - const itemHash = toHash(item, this._hashFunction); - newMap.set(itemHash, item); - if (found === undefined && itemHash === hash) found = item; - } - bufferDedupeMap.set(len, newMap); - if (found === undefined) { - newMap.set(hash, buf); - return buf; - } else { - return found; - } - } - } else { - const hash = toHash(buf, this._hashFunction); - const item = entry.get(hash); - if (item !== undefined) { - return item; - } - entry.set(hash, buf); - return buf; - } - }; - let currentPosTypeLookup = 0; - let objectTypeLookup = new Map(); - const cycleStack = new Set(); - const stackToString = item => { - const arr = Array.from(cycleStack); - arr.push(item); - return arr - .map(item => { - if (typeof item === "string") { - if (item.length > 100) { - return `String ${JSON.stringify(item.slice(0, 100)).slice( - 0, - -1 - )}..."`; - } - return `String ${JSON.stringify(item)}`; - } - try { - const { request, name } = ObjectMiddleware.getSerializerFor(item); - if (request) { - return `${request}${name ? `.${name}` : ""}`; - } - } catch (e) { - // ignore -> fallback - } - if (typeof item === "object" && item !== null) { - if (item.constructor) { - if (item.constructor === Object) - return `Object { ${Object.keys(item).join(", ")} }`; - if (item.constructor === Map) return `Map { ${item.size} items }`; - if (item.constructor === Array) - return `Array { ${item.length} items }`; - if (item.constructor === Set) return `Set { ${item.size} items }`; - if (item.constructor === RegExp) return item.toString(); - return `${item.constructor.name}`; - } - return `Object [null prototype] { ${Object.keys(item).join( - ", " - )} }`; - } - try { - return `${item}`; - } catch (e) { - return `(${e.message})`; - } - }) - .join(" -> "); - }; - let hasDebugInfoAttached; - let ctx = { - write(value, key) { - try { - process(value); - } catch (e) { - if (e !== NOT_SERIALIZABLE) { - if (hasDebugInfoAttached === undefined) - hasDebugInfoAttached = new WeakSet(); - if (!hasDebugInfoAttached.has(e)) { - e.message += `\nwhile serializing ${stackToString(value)}`; - hasDebugInfoAttached.add(e); - } - } - throw e; - } - }, - setCircularReference(ref) { - addReferenceable(ref); - }, - snapshot() { - return { - length: result.length, - cycleStackSize: cycleStack.size, - referenceableSize: referenceable.size, - currentPos, - objectTypeLookupSize: objectTypeLookup.size, - currentPosTypeLookup - }; - }, - rollback(snapshot) { - result.length = snapshot.length; - setSetSize(cycleStack, snapshot.cycleStackSize); - setMapSize(referenceable, snapshot.referenceableSize); - currentPos = snapshot.currentPos; - setMapSize(objectTypeLookup, snapshot.objectTypeLookupSize); - currentPosTypeLookup = snapshot.currentPosTypeLookup; - }, - ...context - }; - this.extendContext(ctx); - const process = item => { - if (Buffer.isBuffer(item)) { - // check if we can emit a reference - const ref = referenceable.get(item); - if (ref !== undefined) { - result.push(ESCAPE, ref - currentPos); - return; - } - const alreadyUsedBuffer = dedupeBuffer(item); - if (alreadyUsedBuffer !== item) { - const ref = referenceable.get(alreadyUsedBuffer); - if (ref !== undefined) { - referenceable.set(item, ref); - result.push(ESCAPE, ref - currentPos); - return; - } - item = alreadyUsedBuffer; - } - addReferenceable(item); - - result.push(item); - } else if (item === ESCAPE) { - result.push(ESCAPE, ESCAPE_ESCAPE_VALUE); - } else if ( - typeof item === "object" - // We don't have to check for null as ESCAPE is null and this has been checked before - ) { - // check if we can emit a reference - const ref = referenceable.get(item); - if (ref !== undefined) { - result.push(ESCAPE, ref - currentPos); - return; - } - - if (cycleStack.has(item)) { - throw new Error( - `This is a circular references. To serialize circular references use 'setCircularReference' somewhere in the circle during serialize and deserialize.` - ); - } - - const { request, name, serializer } = - ObjectMiddleware.getSerializerFor(item); - const key = `${request}/${name}`; - const lastIndex = objectTypeLookup.get(key); - - if (lastIndex === undefined) { - objectTypeLookup.set(key, currentPosTypeLookup++); - - result.push(ESCAPE, request, name); - } else { - result.push(ESCAPE, currentPosTypeLookup - lastIndex); - } - - cycleStack.add(item); - - try { - serializer.serialize(item, ctx); - } finally { - cycleStack.delete(item); - } - - result.push(ESCAPE, ESCAPE_END_OBJECT); - - addReferenceable(item); - } else if (typeof item === "string") { - if (item.length > 1) { - // short strings are shorter when not emitting a reference (this saves 1 byte per empty string) - // check if we can emit a reference - const ref = referenceable.get(item); - if (ref !== undefined) { - result.push(ESCAPE, ref - currentPos); - return; - } - addReferenceable(item); - } + sortWith(sortFn) { + if (this.size <= 1 || sortFn === this._lastActiveSortFn) { + // already sorted - nothing to do + return; + } - if (item.length > 102400 && context.logger) { - context.logger.warn( - `Serializing big strings (${Math.round( - item.length / 1024 - )}kiB) impacts deserialization performance (consider using Buffer instead and decode when needed)` - ); - } + const sortedArray = Array.from(this).sort(sortFn); + super.clear(); + for (let i = 0; i < sortedArray.length; i += 1) { + super.add(sortedArray[i]); + } + this._lastActiveSortFn = sortFn; + this._invalidateCache(); + } - result.push(item); - } else if (typeof item === "function") { - if (!SerializerMiddleware.isLazy(item)) - throw new Error("Unexpected function " + item); - /** @type {SerializedType} */ - const serializedData = - SerializerMiddleware.getLazySerializedValue(item); - if (serializedData !== undefined) { - if (typeof serializedData === "function") { - result.push(serializedData); - } else { - throw new Error("Not implemented"); - } - } else if (SerializerMiddleware.isLazy(item, this)) { - throw new Error("Not implemented"); - } else { - const data = SerializerMiddleware.serializeLazy(item, data => - this.serialize([data], context) - ); - SerializerMiddleware.setLazySerializedValue(item, data); - result.push(data); - } - } else if (item === undefined) { - result.push(ESCAPE, ESCAPE_UNDEFINED); - } else { - result.push(item); + sort() { + this.sortWith(this._sortFn); + return this; + } + + /** + * Get data from cache + * @template R + * @param {function(SortableSet): R} fn function to calculate value + * @returns {R} returns result of fn(this), cached until set changes + */ + getFromCache(fn) { + if (this._cache === undefined) { + this._cache = new Map(); + } else { + const result = this._cache.get(fn); + const data = /** @type {R} */ (result); + if (data !== undefined) { + return data; } - }; + } + const newData = fn(this); + this._cache.set(fn, newData); + return newData; + } - try { - for (const item of data) { - process(item); + /** + * Get data from cache (ignoring sorting) + * @template R + * @param {function(SortableSet): R} fn function to calculate value + * @returns {R} returns result of fn(this), cached until set changes + */ + getFromUnorderedCache(fn) { + if (this._cacheOrderIndependent === undefined) { + this._cacheOrderIndependent = new Map(); + } else { + const result = this._cacheOrderIndependent.get(fn); + const data = /** @type {R} */ (result); + if (data !== undefined) { + return data; } - return result; - } catch (e) { - if (e === NOT_SERIALIZABLE) return null; + } + const newData = fn(this); + this._cacheOrderIndependent.set(fn, newData); + return newData; + } - throw e; - } finally { - // Get rid of these references to avoid leaking memory - // This happens because the optimized code v8 generates - // is optimized for our "ctx.write" method so it will reference - // it from e. g. Dependency.prototype.serialize -(IC)-> ctx.write - data = - result = - referenceable = - bufferDedupeMap = - objectTypeLookup = - ctx = - undefined; + /** + * @private + * @returns {void} + */ + _invalidateCache() { + if (this._cache !== undefined) { + this._cache.clear(); } } /** - * @param {SerializedType} data data - * @param {Object} context context object - * @returns {DeserializedType|Promise} deserialized data + * @private + * @returns {void} */ - deserialize(data, context) { - let currentDataPos = 0; - const read = () => { - if (currentDataPos >= data.length) - throw new Error("Unexpected end of stream"); + _invalidateOrderedCache() { + if (this._cacheOrderIndependent !== undefined) { + this._cacheOrderIndependent.clear(); + } + } - return data[currentDataPos++]; - }; + /** + * @returns {T[]} the raw array + */ + toJSON() { + return Array.from(this); + } +} - if (read() !== CURRENT_VERSION) - throw new Error("Version mismatch, serializer changed"); +module.exports = SortableSet; - let currentPos = 0; - let referenceable = []; - const addReferenceable = item => { - referenceable.push(item); - currentPos++; - }; - let currentPosTypeLookup = 0; - let objectTypeLookup = []; - let result = []; - let ctx = { - read() { - return decodeValue(); - }, - setCircularReference(ref) { - addReferenceable(ref); - }, - ...context - }; - this.extendContext(ctx); - const decodeValue = () => { - const item = read(); - if (item === ESCAPE) { - const nextItem = read(); +/***/ }), - if (nextItem === ESCAPE_ESCAPE_VALUE) { - return ESCAPE; - } else if (nextItem === ESCAPE_UNDEFINED) { - return undefined; - } else if (nextItem === ESCAPE_END_OBJECT) { - throw new Error( - `Unexpected end of object at position ${currentDataPos - 1}` - ); - } else { - const request = nextItem; - let serializer; +/***/ 64985: +/***/ (function(module) { - if (typeof request === "number") { - if (request < 0) { - // relative reference - return referenceable[currentPos + request]; - } - serializer = objectTypeLookup[currentPosTypeLookup - request]; - } else { - if (typeof request !== "string") { - throw new Error( - `Unexpected type (${typeof request}) of request ` + - `at position ${currentDataPos - 1}` - ); - } - const name = read(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - serializer = ObjectMiddleware._getDeserializerForWithoutError( - request, - name - ); - if (serializer === undefined) { - if (request && !loadedRequests.has(request)) { - let loaded = false; - for (const [regExp, loader] of loaders) { - if (regExp.test(request)) { - if (loader(request)) { - loaded = true; - break; - } - } - } - if (!loaded) { - require(request); - } - loadedRequests.add(request); - } +/** + * @template K + * @template V + */ +class StackedCacheMap { + constructor() { + /** @type {Map} */ + this.map = new Map(); + /** @type {ReadonlyMap[]} */ + this.stack = []; + } - serializer = ObjectMiddleware.getDeserializerFor(request, name); - } + /** + * @param {ReadonlyMap} map map to add + * @param {boolean} immutable if 'map' is immutable and StackedCacheMap can keep referencing it + */ + addAll(map, immutable) { + if (immutable) { + this.stack.push(map); - objectTypeLookup.push(serializer); - currentPosTypeLookup++; - } - try { - const item = serializer.deserialize(ctx); - const end1 = read(); + // largest map should go first + for (let i = this.stack.length - 1; i > 0; i--) { + const beforeLast = this.stack[i - 1]; + if (beforeLast.size >= map.size) break; + this.stack[i] = beforeLast; + this.stack[i - 1] = map; + } + } else { + for (const [key, value] of map) { + this.map.set(key, value); + } + } + } - if (end1 !== ESCAPE) { - throw new Error("Expected end of object"); - } + /** + * @param {K} item the key of the element to add + * @param {V} value the value of the element to add + * @returns {void} + */ + set(item, value) { + this.map.set(item, value); + } - const end2 = read(); + /** + * @param {K} item the item to delete + * @returns {void} + */ + delete(item) { + throw new Error("Items can't be deleted from a StackedCacheMap"); + } - if (end2 !== ESCAPE_END_OBJECT) { - throw new Error("Expected end of object"); - } + /** + * @param {K} item the item to test + * @returns {boolean} true if the item exists in this set + */ + has(item) { + throw new Error( + "Checking StackedCacheMap.has before reading is inefficient, use StackedCacheMap.get and check for undefined" + ); + } - addReferenceable(item); + /** + * @param {K} item the key of the element to return + * @returns {V} the value of the element + */ + get(item) { + for (const map of this.stack) { + const value = map.get(item); + if (value !== undefined) return value; + } + return this.map.get(item); + } - return item; - } catch (err) { - // As this is only for error handling, we omit creating a Map for - // faster access to this information, as this would affect performance - // in the good case - let serializerEntry; - for (const entry of serializers) { - if (entry[1].serializer === serializer) { - serializerEntry = entry; - break; - } - } - const name = !serializerEntry - ? "unknown" - : !serializerEntry[1].request - ? serializerEntry[0].name - : serializerEntry[1].name - ? `${serializerEntry[1].request} ${serializerEntry[1].name}` - : serializerEntry[1].request; - err.message += `\n(during deserialization of ${name})`; - throw err; - } - } - } else if (typeof item === "string") { - if (item.length > 1) { - addReferenceable(item); - } + clear() { + this.stack.length = 0; + this.map.clear(); + } - return item; - } else if (Buffer.isBuffer(item)) { - addReferenceable(item); + get size() { + let size = this.map.size; + for (const map of this.stack) { + size += map.size; + } + return size; + } - return item; - } else if (typeof item === "function") { - return SerializerMiddleware.deserializeLazy( - item, - data => this.deserialize(data, context)[0] - ); - } else { - return item; + [Symbol.iterator]() { + const iterators = this.stack.map(map => map[Symbol.iterator]()); + let current = this.map[Symbol.iterator](); + return { + next() { + let result = current.next(); + while (result.done && iterators.length > 0) { + current = iterators.pop(); + result = current.next(); + } + return result; } }; - - try { - while (currentDataPos < data.length) { - result.push(decodeValue()); - } - return result; - } finally { - // Get rid of these references to avoid leaking memory - // This happens because the optimized code v8 generates - // is optimized for our "ctx.read" method so it will reference - // it from e. g. Dependency.prototype.deserialize -(IC)-> ctx.read - result = referenceable = data = objectTypeLookup = ctx = undefined; - } } } -module.exports = ObjectMiddleware; -module.exports.NOT_SERIALIZABLE = NOT_SERIALIZABLE; +module.exports = StackedCacheMap; /***/ }), -/***/ 33040: +/***/ 58845: /***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const cache = new WeakMap(); +const TOMBSTONE = Symbol("tombstone"); +const UNDEFINED_MARKER = Symbol("undefined"); -class ObjectStructure { - constructor() { - this.keys = undefined; - this.children = undefined; - } +/** + * @template T + * @typedef {T | undefined} Cell + */ - getKeys(keys) { - if (this.keys === undefined) this.keys = keys; - return this.keys; +/** + * @template T + * @typedef {T | typeof TOMBSTONE | typeof UNDEFINED_MARKER} InternalCell + */ + +/** + * @template K + * @template V + * @param {[K, InternalCell]} pair the internal cell + * @returns {[K, Cell]} its “safe” representation + */ +const extractPair = pair => { + const key = pair[0]; + const val = pair[1]; + if (val === UNDEFINED_MARKER || val === TOMBSTONE) { + return [key, undefined]; + } else { + return /** @type {[K, Cell]} */ (pair); } +}; - key(key) { - if (this.children === undefined) this.children = new Map(); - const child = this.children.get(key); - if (child !== undefined) return child; - const newChild = new ObjectStructure(); - this.children.set(key, newChild); - return newChild; +/** + * @template K + * @template V + */ +class StackedMap { + /** + * @param {Map>[]=} parentStack an optional parent + */ + constructor(parentStack) { + /** @type {Map>} */ + this.map = new Map(); + /** @type {Map>[]} */ + this.stack = parentStack === undefined ? [] : parentStack.slice(); + this.stack.push(this.map); } -} -const getCachedKeys = (keys, cacheAssoc) => { - let root = cache.get(cacheAssoc); - if (root === undefined) { - root = new ObjectStructure(); - cache.set(cacheAssoc, root); + /** + * @param {K} item the key of the element to add + * @param {V} value the value of the element to add + * @returns {void} + */ + set(item, value) { + this.map.set(item, value === undefined ? UNDEFINED_MARKER : value); } - let current = root; - for (const key of keys) { - current = current.key(key); + + /** + * @param {K} item the item to delete + * @returns {void} + */ + delete(item) { + if (this.stack.length > 1) { + this.map.set(item, TOMBSTONE); + } else { + this.map.delete(item); + } } - return current.getKeys(keys); -}; -class PlainObjectSerializer { - serialize(obj, { write }) { - const keys = Object.keys(obj); - if (keys.length > 128) { - // Objects with so many keys are unlikely to share structure - // with other objects - write(keys); - for (const key of keys) { - write(obj[key]); + /** + * @param {K} item the item to test + * @returns {boolean} true if the item exists in this set + */ + has(item) { + const topValue = this.map.get(item); + if (topValue !== undefined) { + return topValue !== TOMBSTONE; + } + if (this.stack.length > 1) { + for (let i = this.stack.length - 2; i >= 0; i--) { + const value = this.stack[i].get(item); + if (value !== undefined) { + this.map.set(item, value); + return value !== TOMBSTONE; + } } - } else if (keys.length > 1) { - write(getCachedKeys(keys, write)); - for (const key of keys) { - write(obj[key]); + this.map.set(item, TOMBSTONE); + } + return false; + } + + /** + * @param {K} item the key of the element to return + * @returns {Cell} the value of the element + */ + get(item) { + const topValue = this.map.get(item); + if (topValue !== undefined) { + return topValue === TOMBSTONE || topValue === UNDEFINED_MARKER + ? undefined + : topValue; + } + if (this.stack.length > 1) { + for (let i = this.stack.length - 2; i >= 0; i--) { + const value = this.stack[i].get(item); + if (value !== undefined) { + this.map.set(item, value); + return value === TOMBSTONE || value === UNDEFINED_MARKER + ? undefined + : value; + } } - } else if (keys.length === 1) { - const key = keys[0]; - write(key); - write(obj[key]); - } else { - write(null); + this.map.set(item, TOMBSTONE); } + return undefined; } - deserialize({ read }) { - const keys = read(); - const obj = {}; - if (Array.isArray(keys)) { - for (const key of keys) { - obj[key] = read(); + + _compress() { + if (this.stack.length === 1) return; + this.map = new Map(); + for (const data of this.stack) { + for (const pair of data) { + if (pair[1] === TOMBSTONE) { + this.map.delete(pair[0]); + } else { + this.map.set(pair[0], pair[1]); + } } - } else if (keys !== null) { - obj[keys] = read(); } - return obj; + this.stack = [this.map]; + } + + asArray() { + this._compress(); + return Array.from(this.map.keys()); + } + + asSet() { + this._compress(); + return new Set(this.map.keys()); + } + + asPairArray() { + this._compress(); + return Array.from(this.map.entries(), extractPair); + } + + asMap() { + return new Map(this.asPairArray()); + } + + get size() { + this._compress(); + return this.map.size; + } + + createChild() { + return new StackedMap(this.stack); } } -module.exports = PlainObjectSerializer; +module.exports = StackedMap; /***/ }), -/***/ 57328: +/***/ 40293: /***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -class RegExpObjectSerializer { - serialize(obj, { write }) { - write(obj.source); - write(obj.flags); +class StringXor { + constructor() { + this._value = undefined; } - deserialize({ read }) { - return new RegExp(read(), read()); + + /** + * @param {string} str string + * @returns {void} + */ + add(str) { + const len = str.length; + const value = this._value; + if (value === undefined) { + const newValue = (this._value = Buffer.allocUnsafe(len)); + for (let i = 0; i < len; i++) { + newValue[i] = str.charCodeAt(i); + } + return; + } + const valueLen = value.length; + if (valueLen < len) { + const newValue = (this._value = Buffer.allocUnsafe(len)); + let i; + for (i = 0; i < valueLen; i++) { + newValue[i] = value[i] ^ str.charCodeAt(i); + } + for (; i < len; i++) { + newValue[i] = str.charCodeAt(i); + } + } else { + for (let i = 0; i < len; i++) { + value[i] = value[i] ^ str.charCodeAt(i); + } + } + } + + toString() { + const value = this._value; + return value === undefined ? "" : value.toString("latin1"); + } + + updateHash(hash) { + const value = this._value; + if (value !== undefined) hash.update(value); } } -module.exports = RegExpObjectSerializer; +module.exports = StringXor; /***/ }), -/***/ 53080: -/***/ (function(module) { +/***/ 38415: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -class Serializer { - constructor(middlewares, context) { - this.serializeMiddlewares = middlewares.slice(); - this.deserializeMiddlewares = middlewares.slice().reverse(); - this.context = context; +const TupleSet = __webpack_require__(76455); + +/** + * @template {any[]} T + */ +class TupleQueue { + /** + * @param {Iterable=} items The initial elements. + */ + constructor(items) { + /** @private @type {TupleSet} */ + this._set = new TupleSet(items); + /** @private @type {Iterator} */ + this._iterator = this._set[Symbol.iterator](); } - serialize(obj, context) { - const ctx = { ...context, ...this.context }; - let current = obj; - for (const middleware of this.serializeMiddlewares) { - if (current && typeof current.then === "function") { - current = current.then(data => data && middleware.serialize(data, ctx)); - } else if (current) { - try { - current = middleware.serialize(current, ctx); - } catch (err) { - current = Promise.reject(err); - } - } else break; - } - return current; + /** + * Returns the number of elements in this queue. + * @returns {number} The number of elements in this queue. + */ + get length() { + return this._set.size; } - deserialize(value, context) { - const ctx = { ...context, ...this.context }; - /** @type {any} */ - let current = value; - for (const middleware of this.deserializeMiddlewares) { - if (current && typeof current.then === "function") { - current = current.then(data => middleware.deserialize(data, ctx)); - } else { - current = middleware.deserialize(current, ctx); + /** + * Appends the specified element to this queue. + * @param {T} item The element to add. + * @returns {void} + */ + enqueue(...item) { + this._set.add(...item); + } + + /** + * Retrieves and removes the head of this queue. + * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + */ + dequeue() { + const result = this._iterator.next(); + if (result.done) { + if (this._set.size > 0) { + this._iterator = this._set[Symbol.iterator](); + const value = this._iterator.next().value; + this._set.delete(...value); + return value; } + return undefined; } - return current; + this._set.delete(...result.value); + return result.value; } } -module.exports = Serializer; +module.exports = TupleQueue; /***/ }), -/***/ 83137: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 76455: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const memoize = __webpack_require__(78676); - -const LAZY_TARGET = Symbol("lazy serialization target"); -const LAZY_SERIALIZED_VALUE = Symbol("lazy serialization data"); - /** - * @template DeserializedType - * @template SerializedType + * @template {any[]} T */ -class SerializerMiddleware { - /* istanbul ignore next */ +class TupleSet { + constructor(init) { + this._map = new Map(); + this.size = 0; + if (init) { + for (const tuple of init) { + this.add(...tuple); + } + } + } + /** - * @abstract - * @param {DeserializedType} data data - * @param {Object} context context object - * @returns {SerializedType|Promise} serialized data + * @param {T} args tuple + * @returns {void} */ - serialize(data, context) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + add(...args) { + let map = this._map; + for (let i = 0; i < args.length - 2; i++) { + const arg = args[i]; + const innerMap = map.get(arg); + if (innerMap === undefined) { + map.set(arg, (map = new Map())); + } else { + map = innerMap; + } + } + + const beforeLast = args[args.length - 2]; + let set = map.get(beforeLast); + if (set === undefined) { + map.set(beforeLast, (set = new Set())); + } + + const last = args[args.length - 1]; + this.size -= set.size; + set.add(last); + this.size += set.size; } - /* istanbul ignore next */ /** - * @abstract - * @param {SerializedType} data data - * @param {Object} context context object - * @returns {DeserializedType|Promise} deserialized data + * @param {T} args tuple + * @returns {boolean} true, if the tuple is in the Set */ - deserialize(data, context) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + has(...args) { + let map = this._map; + for (let i = 0; i < args.length - 2; i++) { + const arg = args[i]; + map = map.get(arg); + if (map === undefined) { + return false; + } + } + + const beforeLast = args[args.length - 2]; + let set = map.get(beforeLast); + if (set === undefined) { + return false; + } + + const last = args[args.length - 1]; + return set.has(last); } /** - * @param {any | function(): Promise | any} value contained value or function to value - * @param {SerializerMiddleware} target target middleware - * @param {object=} options lazy options - * @param {any=} serializedValue serialized value - * @returns {function(): Promise | any} lazy function + * @param {T} args tuple + * @returns {void} */ - static createLazy(value, target, options = {}, serializedValue) { - if (SerializerMiddleware.isLazy(value, target)) return value; - const fn = typeof value === "function" ? value : () => value; - fn[LAZY_TARGET] = target; - /** @type {any} */ (fn).options = options; - fn[LAZY_SERIALIZED_VALUE] = serializedValue; - return fn; + delete(...args) { + let map = this._map; + for (let i = 0; i < args.length - 2; i++) { + const arg = args[i]; + map = map.get(arg); + if (map === undefined) { + return; + } + } + + const beforeLast = args[args.length - 2]; + let set = map.get(beforeLast); + if (set === undefined) { + return; + } + + const last = args[args.length - 1]; + this.size -= set.size; + set.delete(last); + this.size += set.size; } /** - * @param {function(): Promise | any} fn lazy function - * @param {SerializerMiddleware=} target target middleware - * @returns {boolean} true, when fn is a lazy function (optionally of that target) + * @returns {Iterator} iterator */ - static isLazy(fn, target) { - if (typeof fn !== "function") return false; - const t = fn[LAZY_TARGET]; - return target ? t === target : !!t; + [Symbol.iterator]() { + const iteratorStack = []; + const tuple = []; + let currentSetIterator = undefined; + + const next = it => { + const result = it.next(); + if (result.done) { + if (iteratorStack.length === 0) return false; + tuple.pop(); + return next(iteratorStack.pop()); + } + const [key, value] = result.value; + iteratorStack.push(it); + tuple.push(key); + if (value instanceof Set) { + currentSetIterator = value[Symbol.iterator](); + return true; + } else { + return next(value[Symbol.iterator]()); + } + }; + + next(this._map[Symbol.iterator]()); + + return { + next() { + while (currentSetIterator) { + const result = currentSetIterator.next(); + if (result.done) { + tuple.pop(); + if (!next(iteratorStack.pop())) { + currentSetIterator = undefined; + } + } else { + return { + done: false, + value: /** @type {T} */ (tuple.concat(result.value)) + }; + } + } + return { done: true, value: undefined }; + } + }; + } +} + +module.exports = TupleSet; + + +/***/ }), + +/***/ 54500: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +/** @typedef {import("./fs").InputFileSystem} InputFileSystem */ +/** @typedef {(error: Error|null, result?: Buffer) => void} ErrorFirstCallback */ + +const backSlashCharCode = "\\".charCodeAt(0); +const slashCharCode = "/".charCodeAt(0); +const aLowerCaseCharCode = "a".charCodeAt(0); +const zLowerCaseCharCode = "z".charCodeAt(0); +const aUpperCaseCharCode = "A".charCodeAt(0); +const zUpperCaseCharCode = "Z".charCodeAt(0); +const _0CharCode = "0".charCodeAt(0); +const _9CharCode = "9".charCodeAt(0); +const plusCharCode = "+".charCodeAt(0); +const hyphenCharCode = "-".charCodeAt(0); +const colonCharCode = ":".charCodeAt(0); +const hashCharCode = "#".charCodeAt(0); +const queryCharCode = "?".charCodeAt(0); +/** + * Get scheme if specifier is an absolute URL specifier + * e.g. Absolute specifiers like 'file:///user/webpack/index.js' + * https://tools.ietf.org/html/rfc3986#section-3.1 + * @param {string} specifier specifier + * @returns {string|undefined} scheme if absolute URL specifier provided + */ +function getScheme(specifier) { + const start = specifier.charCodeAt(0); + + // First char maybe only a letter + if ( + (start < aLowerCaseCharCode || start > zLowerCaseCharCode) && + (start < aUpperCaseCharCode || start > zUpperCaseCharCode) + ) { + return undefined; + } + + let i = 1; + let ch = specifier.charCodeAt(i); + + while ( + (ch >= aLowerCaseCharCode && ch <= zLowerCaseCharCode) || + (ch >= aUpperCaseCharCode && ch <= zUpperCaseCharCode) || + (ch >= _0CharCode && ch <= _9CharCode) || + ch === plusCharCode || + ch === hyphenCharCode + ) { + if (++i === specifier.length) return undefined; + ch = specifier.charCodeAt(i); + } + + // Scheme must end with colon + if (ch !== colonCharCode) return undefined; + + // Check for Windows absolute path + // https://url.spec.whatwg.org/#url-miscellaneous + if (i === 1) { + const nextChar = i + 1 < specifier.length ? specifier.charCodeAt(i + 1) : 0; + if ( + nextChar === 0 || + nextChar === backSlashCharCode || + nextChar === slashCharCode || + nextChar === hashCharCode || + nextChar === queryCharCode + ) { + return undefined; + } + } + + return specifier.slice(0, i).toLowerCase(); +} + +/** + * @param {string} specifier specifier + * @returns {string|null} protocol if absolute URL specifier provided + */ +function getProtocol(specifier) { + const scheme = getScheme(specifier); + return scheme === undefined ? undefined : scheme + ":"; +} + +exports.getScheme = getScheme; +exports.getProtocol = getProtocol; + + +/***/ }), + +/***/ 28745: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const isWeakKey = thing => typeof thing === "object" && thing !== null; + +/** + * @template {any[]} T + * @template V + */ +class WeakTupleMap { + constructor() { + /** @private */ + this.f = 0; + /** @private @type {any} */ + this.v = undefined; + /** @private @type {Map> | undefined} */ + this.m = undefined; + /** @private @type {WeakMap> | undefined} */ + this.w = undefined; } /** - * @param {function(): Promise | any} fn lazy function - * @returns {object} options + * @param {[...T, V]} args tuple + * @returns {void} */ - static getLazyOptions(fn) { - if (typeof fn !== "function") return undefined; - return /** @type {any} */ (fn).options; + set(...args) { + /** @type {WeakTupleMap} */ + let node = this; + for (let i = 0; i < args.length - 1; i++) { + node = node._get(args[i]); + } + node._setValue(args[args.length - 1]); } /** - * @param {function(): Promise | any} fn lazy function - * @returns {any} serialized value + * @param {T} args tuple + * @returns {boolean} true, if the tuple is in the Set */ - static getLazySerializedValue(fn) { - if (typeof fn !== "function") return undefined; - return fn[LAZY_SERIALIZED_VALUE]; + has(...args) { + /** @type {WeakTupleMap} */ + let node = this; + for (let i = 0; i < args.length; i++) { + node = node._peek(args[i]); + if (node === undefined) return false; + } + return node._hasValue(); } /** - * @param {function(): Promise | any} fn lazy function - * @param {any} value serialized value - * @returns {void} + * @param {T} args tuple + * @returns {V} the value */ - static setLazySerializedValue(fn, value) { - fn[LAZY_SERIALIZED_VALUE] = value; + get(...args) { + /** @type {WeakTupleMap} */ + let node = this; + for (let i = 0; i < args.length; i++) { + node = node._peek(args[i]); + if (node === undefined) return undefined; + } + return node._getValue(); } /** - * @param {function(): Promise | any} lazy lazy function - * @param {function(any): Promise | any} serialize serialize function - * @returns {function(): Promise | any} new lazy + * @param {[...T, function(): V]} args tuple + * @returns {V} the value */ - static serializeLazy(lazy, serialize) { - const fn = memoize(() => { - const r = lazy(); - if (r && typeof r.then === "function") { - return r.then(data => data && serialize(data)); - } - return serialize(r); - }); - fn[LAZY_TARGET] = lazy[LAZY_TARGET]; - /** @type {any} */ (fn).options = /** @type {any} */ (lazy).options; - lazy[LAZY_SERIALIZED_VALUE] = fn; - return fn; + provide(...args) { + /** @type {WeakTupleMap} */ + let node = this; + for (let i = 0; i < args.length - 1; i++) { + node = node._get(args[i]); + } + if (node._hasValue()) return node._getValue(); + const fn = args[args.length - 1]; + const newValue = fn(...args.slice(0, -1)); + node._setValue(newValue); + return newValue; } /** - * @param {function(): Promise | any} lazy lazy function - * @param {function(any): Promise | any} deserialize deserialize function - * @returns {function(): Promise | any} new lazy + * @param {T} args tuple + * @returns {void} */ - static deserializeLazy(lazy, deserialize) { - const fn = memoize(() => { - const r = lazy(); - if (r && typeof r.then === "function") { - return r.then(data => deserialize(data)); - } - return deserialize(r); - }); - fn[LAZY_TARGET] = lazy[LAZY_TARGET]; - /** @type {any} */ (fn).options = /** @type {any} */ (lazy).options; - fn[LAZY_SERIALIZED_VALUE] = lazy; - return fn; + delete(...args) { + /** @type {WeakTupleMap} */ + let node = this; + for (let i = 0; i < args.length; i++) { + node = node._peek(args[i]); + if (node === undefined) return; + } + node._deleteValue(); } /** - * @param {function(): Promise | any} lazy lazy function - * @returns {function(): Promise | any} new lazy + * @returns {void} */ - static unMemoizeLazy(lazy) { - if (!SerializerMiddleware.isLazy(lazy)) return lazy; - const fn = () => { - throw new Error( - "A lazy value that has been unmemorized can't be called again" - ); - }; - fn[LAZY_SERIALIZED_VALUE] = SerializerMiddleware.unMemoizeLazy( - lazy[LAZY_SERIALIZED_VALUE] - ); - fn[LAZY_TARGET] = lazy[LAZY_TARGET]; - fn.options = /** @type {any} */ (lazy).options; - return fn; + clear() { + this.f = 0; + this.v = undefined; + this.w = undefined; + this.m = undefined; } -} - -module.exports = SerializerMiddleware; + _getValue() { + return this.v; + } -/***/ }), - -/***/ 79240: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + _hasValue() { + return (this.f & 1) === 1; + } + _setValue(v) { + this.f |= 1; + this.v = v; + } + _deleteValue() { + this.f &= 6; + this.v = undefined; + } -class SetObjectSerializer { - serialize(obj, { write }) { - write(obj.size); - for (const value of obj) { - write(value); + _peek(thing) { + if (isWeakKey(thing)) { + if ((this.f & 4) !== 4) return undefined; + return this.w.get(thing); + } else { + if ((this.f & 2) !== 2) return undefined; + return this.m.get(thing); } } - deserialize({ read }) { - let size = read(); - const set = new Set(); - for (let i = 0; i < size; i++) { - set.add(read()); + + _get(thing) { + if (isWeakKey(thing)) { + if ((this.f & 4) !== 4) { + const newMap = new WeakMap(); + this.f |= 4; + const newNode = new WeakTupleMap(); + (this.w = newMap).set(thing, newNode); + return newNode; + } + const entry = this.w.get(thing); + if (entry !== undefined) { + return entry; + } + const newNode = new WeakTupleMap(); + this.w.set(thing, newNode); + return newNode; + } else { + if ((this.f & 2) !== 2) { + const newMap = new Map(); + this.f |= 2; + const newNode = new WeakTupleMap(); + (this.m = newMap).set(thing, newNode); + return newNode; + } + const entry = this.m.get(thing); + if (entry !== undefined) { + return entry; + } + const newNode = new WeakTupleMap(); + this.m.set(thing, newNode); + return newNode; } - return set; } } -module.exports = SetObjectSerializer; +module.exports = WeakTupleMap; /***/ }), -/***/ 65112: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 92229: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Mikola Lysenko @mikolalysenko */ -const SerializerMiddleware = __webpack_require__(83137); +/* cspell:disable-next-line */ +// Refactor: Peter Somogyvari @petermetz -/** - * @typedef {any} DeserializedType - * @typedef {any[]} SerializedType - * @extends {SerializerMiddleware} - */ -class SingleItemMiddleware extends SerializerMiddleware { - /** - * @param {DeserializedType} data data - * @param {Object} context context object - * @returns {SerializedType|Promise} serialized data - */ - serialize(data, context) { - return [data]; - } +const compileSearch = (funcName, predicate, reversed, extraArgs, earlyOut) => { + const code = [ + "function ", + funcName, + "(a,l,h,", + extraArgs.join(","), + "){", + earlyOut ? "" : "var i=", + reversed ? "l-1" : "h+1", + ";while(l<=h){var m=(l+h)>>>1,x=a[m]" + ]; - /** - * @param {SerializedType} data data - * @param {Object} context context object - * @returns {DeserializedType|Promise} deserialized data - */ - deserialize(data, context) { - return data[0]; + if (earlyOut) { + if (predicate.indexOf("c") < 0) { + code.push(";if(x===y){return m}else if(x<=y){"); + } else { + code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"); + } + } else { + code.push(";if(", predicate, "){i=m;"); } -} + if (reversed) { + code.push("l=m+1}else{h=m-1}"); + } else { + code.push("h=m-1}else{l=m+1}"); + } + code.push("}"); + if (earlyOut) { + code.push("return -1};"); + } else { + code.push("return i};"); + } + return code.join(""); +}; -module.exports = SingleItemMiddleware; +const compileBoundsSearch = (predicate, reversed, suffix, earlyOut) => { + const arg1 = compileSearch( + "A", + "x" + predicate + "y", + reversed, + ["y"], + earlyOut + ); + + const arg2 = compileSearch( + "P", + "c(x,y)" + predicate + "0", + reversed, + ["y", "c"], + earlyOut + ); + + const fnHeader = "function dispatchBinarySearch"; + + const fnBody = + "(a,y,c,l,h){\ +if(typeof(c)==='function'){\ +return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ +}else{\ +return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ +}}\ +return dispatchBinarySearch"; + + const fnArgList = [arg1, arg2, fnHeader, suffix, fnBody, suffix]; + const fnSource = fnArgList.join(""); + const result = new Function(fnSource); + return result(); +}; + +module.exports = { + ge: compileBoundsSearch(">=", false, "GE"), + gt: compileBoundsSearch(">", false, "GT"), + lt: compileBoundsSearch("<", true, "LT"), + le: compileBoundsSearch("<=", true, "LE"), + eq: compileBoundsSearch("-", true, "EQ", true) +}; /***/ }), -/***/ 58831: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 60839: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -121557,294 +123252,573 @@ module.exports = SingleItemMiddleware; -const ModuleDependency = __webpack_require__(80321); -const makeSerializable = __webpack_require__(33032); +/** @type {WeakMap>} */ +const mergeCache = new WeakMap(); +/** @type {WeakMap>>} */ +const setPropertyCache = new WeakMap(); +const DELETE = Symbol("DELETE"); +const DYNAMIC_INFO = Symbol("cleverMerge dynamic info"); -class ConsumeSharedFallbackDependency extends ModuleDependency { - constructor(request) { - super(request); - } +/** + * Merges two given objects and caches the result to avoid computation if same objects passed as arguments again. + * @template T + * @template O + * @example + * // performs cleverMerge(first, second), stores the result in WeakMap and returns result + * cachedCleverMerge({a: 1}, {a: 2}) + * {a: 2} + * // when same arguments passed, gets the result from WeakMap and returns it. + * cachedCleverMerge({a: 1}, {a: 2}) + * {a: 2} + * @param {T} first first object + * @param {O} second second object + * @returns {T & O | T | O} merged object of first and second object + */ +const cachedCleverMerge = (first, second) => { + if (second === undefined) return first; + if (first === undefined) return second; + if (typeof second !== "object" || second === null) return second; + if (typeof first !== "object" || first === null) return first; - get type() { - return "consume shared fallback"; + let innerCache = mergeCache.get(first); + if (innerCache === undefined) { + innerCache = new WeakMap(); + mergeCache.set(first, innerCache); } + const prevMerge = innerCache.get(second); + if (prevMerge !== undefined) return prevMerge; + const newMerge = _cleverMerge(first, second, true); + innerCache.set(second, newMerge); + return newMerge; +}; - get category() { - return "esm"; - } -} +/** + * @template T + * @param {Partial} obj object + * @param {string} property property + * @param {string|number|boolean} value assignment value + * @returns {T} new object + */ +const cachedSetProperty = (obj, property, value) => { + let mapByProperty = setPropertyCache.get(obj); -makeSerializable( - ConsumeSharedFallbackDependency, - "webpack/lib/sharing/ConsumeSharedFallbackDependency" -); + if (mapByProperty === undefined) { + mapByProperty = new Map(); + setPropertyCache.set(obj, mapByProperty); + } -module.exports = ConsumeSharedFallbackDependency; + let mapByValue = mapByProperty.get(property); + if (mapByValue === undefined) { + mapByValue = new Map(); + mapByProperty.set(property, mapByValue); + } -/***/ }), + let result = mapByValue.get(value); -/***/ 62286: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (result) return result; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + result = { + ...obj, + [property]: value + }; + mapByValue.set(value, result); + return result; +}; +/** + * @typedef {Object} ObjectParsedPropertyEntry + * @property {any | undefined} base base value + * @property {string | undefined} byProperty the name of the selector property + * @property {Map} byValues value depending on selector property, merged with base + */ -const { RawSource } = __webpack_require__(51255); -const AsyncDependenciesBlock = __webpack_require__(47736); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const { rangeToString, stringifyHoley } = __webpack_require__(19702); -const ConsumeSharedFallbackDependency = __webpack_require__(58831); +/** + * @typedef {Object} ParsedObject + * @property {Map} static static properties (key is property name) + * @property {{ byProperty: string, fn: Function } | undefined} dynamic dynamic part + */ -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ -/** @typedef {import("../util/semver").SemVerRange} SemVerRange */ +/** @type {WeakMap} */ +const parseCache = new WeakMap(); /** - * @typedef {Object} ConsumeOptions - * @property {string=} import fallback request - * @property {string=} importResolved resolved fallback request - * @property {string} shareKey global share key - * @property {string} shareScope share scope - * @property {SemVerRange | false | undefined} requiredVersion version requirement - * @property {string} packageName package name to determine required version automatically - * @property {boolean} strictVersion don't use shared version even if version isn't valid - * @property {boolean} singleton use single global version - * @property {boolean} eager include the fallback module in a sync way + * @param {object} obj the object + * @returns {ParsedObject} parsed object */ +const cachedParseObject = obj => { + const entry = parseCache.get(obj); + if (entry !== undefined) return entry; + const result = parseObject(obj); + parseCache.set(obj, result); + return result; +}; -const TYPES = new Set(["consume-shared"]); - -class ConsumeSharedModule extends Module { - /** - * @param {string} context context - * @param {ConsumeOptions} options consume options - */ - constructor(context, options) { - super("consume-shared-module", context); - this.options = options; +/** + * @param {object} obj the object + * @returns {ParsedObject} parsed object + */ +const parseObject = obj => { + const info = new Map(); + let dynamicInfo; + const getInfo = p => { + const entry = info.get(p); + if (entry !== undefined) return entry; + const newEntry = { + base: undefined, + byProperty: undefined, + byValues: undefined + }; + info.set(p, newEntry); + return newEntry; + }; + for (const key of Object.keys(obj)) { + if (key.startsWith("by")) { + const byProperty = key; + const byObj = obj[byProperty]; + if (typeof byObj === "object") { + for (const byValue of Object.keys(byObj)) { + const obj = byObj[byValue]; + for (const key of Object.keys(obj)) { + const entry = getInfo(key); + if (entry.byProperty === undefined) { + entry.byProperty = byProperty; + entry.byValues = new Map(); + } else if (entry.byProperty !== byProperty) { + throw new Error( + `${byProperty} and ${entry.byProperty} for a single property is not supported` + ); + } + entry.byValues.set(byValue, obj[key]); + if (byValue === "default") { + for (const otherByValue of Object.keys(byObj)) { + if (!entry.byValues.has(otherByValue)) + entry.byValues.set(otherByValue, undefined); + } + } + } + } + } else if (typeof byObj === "function") { + if (dynamicInfo === undefined) { + dynamicInfo = { + byProperty: key, + fn: byObj + }; + } else { + throw new Error( + `${key} and ${dynamicInfo.byProperty} when both are functions is not supported` + ); + } + } else { + const entry = getInfo(key); + entry.base = obj[key]; + } + } else { + const entry = getInfo(key); + entry.base = obj[key]; + } } + return { + static: info, + dynamic: dynamicInfo + }; +}; - /** - * @returns {string} a unique identifier of the module - */ - identifier() { - const { - shareKey, - shareScope, - importResolved, - requiredVersion, - strictVersion, - singleton, - eager - } = this.options; - return `consume-shared-module|${shareScope}|${shareKey}|${ - requiredVersion && rangeToString(requiredVersion) - }|${strictVersion}|${importResolved}|${singleton}|${eager}`; +/** + * @param {Map} info static properties (key is property name) + * @param {{ byProperty: string, fn: Function } | undefined} dynamicInfo dynamic part + * @returns {object} the object + */ +const serializeObject = (info, dynamicInfo) => { + const obj = {}; + // Setup byProperty structure + for (const entry of info.values()) { + if (entry.byProperty !== undefined) { + const byObj = (obj[entry.byProperty] = obj[entry.byProperty] || {}); + for (const byValue of entry.byValues.keys()) { + byObj[byValue] = byObj[byValue] || {}; + } + } } - - /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module - */ - readableIdentifier(requestShortener) { - const { - shareKey, - shareScope, - importResolved, - requiredVersion, - strictVersion, - singleton, - eager - } = this.options; - return `consume shared module (${shareScope}) ${shareKey}@${ - requiredVersion ? rangeToString(requiredVersion) : "*" - }${strictVersion ? " (strict)" : ""}${singleton ? " (singleton)" : ""}${ - importResolved - ? ` (fallback: ${requestShortener.shorten(importResolved)})` - : "" - }${eager ? " (eager)" : ""}`; + for (const [key, entry] of info) { + if (entry.base !== undefined) { + obj[key] = entry.base; + } + // Fill byProperty structure + if (entry.byProperty !== undefined) { + const byObj = (obj[entry.byProperty] = obj[entry.byProperty] || {}); + for (const byValue of Object.keys(byObj)) { + const value = getFromByValues(entry.byValues, byValue); + if (value !== undefined) byObj[byValue][key] = value; + } + } } - - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - const { shareKey, shareScope, import: request } = this.options; - return `${ - this.layer ? `(${this.layer})/` : "" - }webpack/sharing/consume/${shareScope}/${shareKey}${ - request ? `/${request}` : "" - }`; + if (dynamicInfo !== undefined) { + obj[dynamicInfo.byProperty] = dynamicInfo.fn; } + return obj; +}; - /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} - */ - needBuild(context, callback) { - callback(null, !this.buildInfo); - } +const VALUE_TYPE_UNDEFINED = 0; +const VALUE_TYPE_ATOM = 1; +const VALUE_TYPE_ARRAY_EXTEND = 2; +const VALUE_TYPE_OBJECT = 3; +const VALUE_TYPE_DELETE = 4; - /** - * @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 = {}; - if (this.options.import) { - const dep = new ConsumeSharedFallbackDependency(this.options.import); - if (this.options.eager) { - this.addDependency(dep); - } else { - const block = new AsyncDependenciesBlock({}); - block.addDependency(dep); - this.addBlock(block); - } - } - callback(); +/** + * @param {any} value a single value + * @returns {VALUE_TYPE_UNDEFINED | VALUE_TYPE_ATOM | VALUE_TYPE_ARRAY_EXTEND | VALUE_TYPE_OBJECT | VALUE_TYPE_DELETE} value type + */ +const getValueType = value => { + if (value === undefined) { + return VALUE_TYPE_UNDEFINED; + } else if (value === DELETE) { + return VALUE_TYPE_DELETE; + } else if (Array.isArray(value)) { + if (value.lastIndexOf("...") !== -1) return VALUE_TYPE_ARRAY_EXTEND; + return VALUE_TYPE_ATOM; + } else if ( + typeof value === "object" && + value !== null && + (!value.constructor || value.constructor === Object) + ) { + return VALUE_TYPE_OBJECT; } + return VALUE_TYPE_ATOM; +}; - /** - * @returns {Set} types available (do not mutate) - */ - getSourceTypes() { - return TYPES; - } +/** + * Merges two objects. Objects are deeply clever merged. + * Arrays might reference the old value with "...". + * Non-object values take preference over object values. + * @template T + * @template O + * @param {T} first first object + * @param {O} second second object + * @returns {T & O | T | O} merged object of first and second object + */ +const cleverMerge = (first, second) => { + if (second === undefined) return first; + if (first === undefined) return second; + if (typeof second !== "object" || second === null) return second; + if (typeof first !== "object" || first === null) return first; - /** - * @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; + return _cleverMerge(first, second, false); +}; + +/** + * Merges two objects. Objects are deeply clever merged. + * @param {object} first first object + * @param {object} second second object + * @param {boolean} internalCaching should parsing of objects and nested merges be cached + * @returns {object} merged object of first and second object + */ +const _cleverMerge = (first, second, internalCaching = false) => { + const firstObject = internalCaching + ? cachedParseObject(first) + : parseObject(first); + const { static: firstInfo, dynamic: firstDynamicInfo } = firstObject; + + // If the first argument has a dynamic part we modify the dynamic part to merge the second argument + if (firstDynamicInfo !== undefined) { + let { byProperty, fn } = firstDynamicInfo; + const fnInfo = fn[DYNAMIC_INFO]; + if (fnInfo) { + second = internalCaching + ? cachedCleverMerge(fnInfo[1], second) + : cleverMerge(fnInfo[1], second); + fn = fnInfo[0]; + } + const newFn = (...args) => { + const fnResult = fn(...args); + return internalCaching + ? cachedCleverMerge(fnResult, second) + : cleverMerge(fnResult, second); + }; + newFn[DYNAMIC_INFO] = [fn, second]; + return serializeObject(firstObject.static, { byProperty, fn: newFn }); } - /** - * @param {Hash} hash the hash used to track dependencies - * @param {UpdateHashContext} context context - * @returns {void} - */ - updateHash(hash, context) { - hash.update(JSON.stringify(this.options)); - super.updateHash(hash, context); + // If the first part is static only, we merge the static parts and keep the dynamic part of the second argument + const secondObject = internalCaching + ? cachedParseObject(second) + : parseObject(second); + const { static: secondInfo, dynamic: secondDynamicInfo } = secondObject; + /** @type {Map} */ + const resultInfo = new Map(); + for (const [key, firstEntry] of firstInfo) { + const secondEntry = secondInfo.get(key); + const entry = + secondEntry !== undefined + ? mergeEntries(firstEntry, secondEntry, internalCaching) + : firstEntry; + resultInfo.set(key, entry); + } + for (const [key, secondEntry] of secondInfo) { + if (!firstInfo.has(key)) { + resultInfo.set(key, secondEntry); + } } + return serializeObject(resultInfo, secondDynamicInfo); +}; - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration({ chunkGraph, moduleGraph, runtimeTemplate }) { - const runtimeRequirements = new Set([RuntimeGlobals.shareScopeMap]); - const { - shareScope, - shareKey, - strictVersion, - requiredVersion, - import: request, - singleton, - eager - } = this.options; - let fallbackCode; - if (request) { - if (eager) { - const dep = this.dependencies[0]; - fallbackCode = runtimeTemplate.syncModuleFactory({ - dependency: dep, - chunkGraph, - runtimeRequirements, - request: this.options.import - }); +/** + * @param {ObjectParsedPropertyEntry} firstEntry a + * @param {ObjectParsedPropertyEntry} secondEntry b + * @param {boolean} internalCaching should parsing of objects and nested merges be cached + * @returns {ObjectParsedPropertyEntry} new entry + */ +const mergeEntries = (firstEntry, secondEntry, internalCaching) => { + switch (getValueType(secondEntry.base)) { + case VALUE_TYPE_ATOM: + case VALUE_TYPE_DELETE: + // No need to consider firstEntry at all + // second value override everything + // = second.base + second.byProperty + return secondEntry; + case VALUE_TYPE_UNDEFINED: + if (!firstEntry.byProperty) { + // = first.base + second.byProperty + return { + base: firstEntry.base, + byProperty: secondEntry.byProperty, + byValues: secondEntry.byValues + }; + } else if (firstEntry.byProperty !== secondEntry.byProperty) { + throw new Error( + `${firstEntry.byProperty} and ${secondEntry.byProperty} for a single property is not supported` + ); } else { - const block = this.blocks[0]; - fallbackCode = runtimeTemplate.asyncModuleFactory({ - block, - chunkGraph, - runtimeRequirements, - request: this.options.import - }); + // = first.base + (first.byProperty + second.byProperty) + // need to merge first and second byValues + const newByValues = new Map(firstEntry.byValues); + for (const [key, value] of secondEntry.byValues) { + const firstValue = getFromByValues(firstEntry.byValues, key); + newByValues.set( + key, + mergeSingleValue(firstValue, value, internalCaching) + ); + } + return { + base: firstEntry.base, + byProperty: firstEntry.byProperty, + byValues: newByValues + }; } - } - let fn = "load"; - const args = [JSON.stringify(shareScope), JSON.stringify(shareKey)]; - if (requiredVersion) { - if (strictVersion) { - fn += "Strict"; + default: { + if (!firstEntry.byProperty) { + // The simple case + // = (first.base + second.base) + second.byProperty + return { + base: mergeSingleValue( + firstEntry.base, + secondEntry.base, + internalCaching + ), + byProperty: secondEntry.byProperty, + byValues: secondEntry.byValues + }; } - if (singleton) { - fn += "Singleton"; + let newBase; + const intermediateByValues = new Map(firstEntry.byValues); + for (const [key, value] of intermediateByValues) { + intermediateByValues.set( + key, + mergeSingleValue(value, secondEntry.base, internalCaching) + ); } - args.push(stringifyHoley(requiredVersion)); - fn += "VersionCheck"; - } else { - if (singleton) { - fn += "Singleton"; + if ( + Array.from(firstEntry.byValues.values()).every(value => { + const type = getValueType(value); + return type === VALUE_TYPE_ATOM || type === VALUE_TYPE_DELETE; + }) + ) { + // = (first.base + second.base) + ((first.byProperty + second.base) + second.byProperty) + newBase = mergeSingleValue( + firstEntry.base, + secondEntry.base, + internalCaching + ); + } else { + // = first.base + ((first.byProperty (+default) + second.base) + second.byProperty) + newBase = firstEntry.base; + if (!intermediateByValues.has("default")) + intermediateByValues.set("default", secondEntry.base); } + if (!secondEntry.byProperty) { + // = first.base + (first.byProperty + second.base) + return { + base: newBase, + byProperty: firstEntry.byProperty, + byValues: intermediateByValues + }; + } else if (firstEntry.byProperty !== secondEntry.byProperty) { + throw new Error( + `${firstEntry.byProperty} and ${secondEntry.byProperty} for a single property is not supported` + ); + } + const newByValues = new Map(intermediateByValues); + for (const [key, value] of secondEntry.byValues) { + const firstValue = getFromByValues(intermediateByValues, key); + newByValues.set( + key, + mergeSingleValue(firstValue, value, internalCaching) + ); + } + return { + base: newBase, + byProperty: firstEntry.byProperty, + byValues: newByValues + }; } - if (fallbackCode) { - fn += "Fallback"; - args.push(fallbackCode); - } - const code = runtimeTemplate.returningFunction(`${fn}(${args.join(", ")})`); - const sources = new Map(); - sources.set("consume-shared", new RawSource(code)); - return { - runtimeRequirements, - sources - }; } +}; - serialize(context) { - const { write } = context; - write(this.options); - super.serialize(context); +/** + * @param {Map} byValues all values + * @param {string} key value of the selector + * @returns {any | undefined} value + */ +const getFromByValues = (byValues, key) => { + if (key !== "default" && byValues.has(key)) { + return byValues.get(key); } + return byValues.get("default"); +}; - deserialize(context) { - const { read } = context; - this.options = read(); - super.deserialize(context); +/** + * @param {any} a value + * @param {any} b value + * @param {boolean} internalCaching should parsing of objects and nested merges be cached + * @returns {any} value + */ +const mergeSingleValue = (a, b, internalCaching) => { + const bType = getValueType(b); + const aType = getValueType(a); + switch (bType) { + case VALUE_TYPE_DELETE: + case VALUE_TYPE_ATOM: + return b; + case VALUE_TYPE_OBJECT: { + return aType !== VALUE_TYPE_OBJECT + ? b + : internalCaching + ? cachedCleverMerge(a, b) + : cleverMerge(a, b); + } + case VALUE_TYPE_UNDEFINED: + return a; + case VALUE_TYPE_ARRAY_EXTEND: + switch ( + aType !== VALUE_TYPE_ATOM + ? aType + : Array.isArray(a) + ? VALUE_TYPE_ARRAY_EXTEND + : VALUE_TYPE_OBJECT + ) { + case VALUE_TYPE_UNDEFINED: + return b; + case VALUE_TYPE_DELETE: + return b.filter(item => item !== "..."); + case VALUE_TYPE_ARRAY_EXTEND: { + const newArray = []; + for (const item of b) { + if (item === "...") { + for (const item of a) { + newArray.push(item); + } + } else { + newArray.push(item); + } + } + return newArray; + } + case VALUE_TYPE_OBJECT: + return b.map(item => (item === "..." ? a : item)); + default: + throw new Error("Not implemented"); + } + default: + throw new Error("Not implemented"); } -} +}; -makeSerializable( - ConsumeSharedModule, - "webpack/lib/sharing/ConsumeSharedModule" -); +/** + * @template T + * @param {T} obj the object + * @returns {T} the object without operations like "..." or DELETE + */ +const removeOperations = obj => { + const newObj = /** @type {T} */ ({}); + for (const key of Object.keys(obj)) { + const value = obj[key]; + const type = getValueType(value); + switch (type) { + case VALUE_TYPE_UNDEFINED: + case VALUE_TYPE_DELETE: + break; + case VALUE_TYPE_OBJECT: + newObj[key] = removeOperations(value); + break; + case VALUE_TYPE_ARRAY_EXTEND: + newObj[key] = value.filter(i => i !== "..."); + break; + default: + newObj[key] = value; + break; + } + } + return newObj; +}; -module.exports = ConsumeSharedModule; +/** + * @template T + * @template {string} P + * @param {T} obj the object + * @param {P} byProperty the by description + * @param {...any} values values + * @returns {Omit} object with merged byProperty + */ +const resolveByProperty = (obj, byProperty, ...values) => { + if (typeof obj !== "object" || obj === null || !(byProperty in obj)) { + return obj; + } + const { [byProperty]: _byValue, ..._remaining } = /** @type {object} */ (obj); + const remaining = /** @type {T} */ (_remaining); + const byValue = /** @type {Record | function(...any[]): T} */ ( + _byValue + ); + if (typeof byValue === "object") { + const key = values[0]; + if (key in byValue) { + return cachedCleverMerge(remaining, byValue[key]); + } else if ("default" in byValue) { + return cachedCleverMerge(remaining, byValue.default); + } else { + return /** @type {T} */ (remaining); + } + } else if (typeof byValue === "function") { + const result = byValue.apply(null, values); + return cachedCleverMerge( + remaining, + resolveByProperty(result, byProperty, ...values) + ); + } +}; + +exports.cachedSetProperty = cachedSetProperty; +exports.cachedCleverMerge = cachedCleverMerge; +exports.cleverMerge = cleverMerge; +exports.resolveByProperty = resolveByProperty; +exports.removeOperations = removeOperations; +exports.DELETE = DELETE; /***/ }), -/***/ 15046: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 29579: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -121854,692 +123828,464 @@ module.exports = ConsumeSharedModule; -const ModuleNotFoundError = __webpack_require__(32882); -const RuntimeGlobals = __webpack_require__(16475); -const WebpackError = __webpack_require__(53799); -const { parseOptions } = __webpack_require__(3083); -const LazySet = __webpack_require__(38938); -const createSchemaValidation = __webpack_require__(32540); -const { parseRange } = __webpack_require__(19702); -const ConsumeSharedFallbackDependency = __webpack_require__(58831); -const ConsumeSharedModule = __webpack_require__(62286); -const ConsumeSharedRuntimeModule = __webpack_require__(10394); -const ProvideForSharedDependency = __webpack_require__(40017); -const { resolveMatchedConfigs } = __webpack_require__(3591); -const { - isRequiredVersion, - getDescriptionFile, - getRequiredVersionFromDescriptionFile -} = __webpack_require__(84379); +const { compareRuntime } = __webpack_require__(17156); -/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumeSharedPluginOptions} ConsumeSharedPluginOptions */ -/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumesConfig} ConsumesConfig */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */ -/** @typedef {import("./ConsumeSharedModule").ConsumeOptions} ConsumeOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../ChunkGroup")} ChunkGroup */ +/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ -const validate = createSchemaValidation( - __webpack_require__(6464), - () => __webpack_require__(16116), - { - name: "Consume Shared Plugin", - baseDataPath: "options" - } -); +/** @template T @typedef {function(T, T): -1|0|1} Comparator */ +/** @template TArg @template T @typedef {function(TArg, T, T): -1|0|1} RawParameterizedComparator */ +/** @template TArg @template T @typedef {function(TArg): Comparator} ParameterizedComparator */ -/** @type {ResolveOptionsWithDependencyType} */ -const RESOLVE_OPTIONS = { dependencyType: "esm" }; -const PLUGIN_NAME = "ConsumeSharedPlugin"; +/** + * @template T + * @param {RawParameterizedComparator} fn comparator with argument + * @returns {ParameterizedComparator} comparator + */ +const createCachedParameterizedComparator = fn => { + /** @type {WeakMap>} */ + const map = new WeakMap(); + return arg => { + const cachedResult = map.get(arg); + if (cachedResult !== undefined) return cachedResult; + /** + * @param {T} a first item + * @param {T} b second item + * @returns {-1|0|1} compare result + */ + const result = fn.bind(null, arg); + map.set(arg, result); + return result; + }; +}; -class ConsumeSharedPlugin { - /** - * @param {ConsumeSharedPluginOptions} options options - */ - constructor(options) { - if (typeof options !== "string") { - validate(options); - } +/** + * @param {Chunk} a chunk + * @param {Chunk} b chunk + * @returns {-1|0|1} compare result + */ +exports.compareChunksById = (a, b) => { + return compareIds(a.id, b.id); +}; - /** @type {[string, ConsumeOptions][]} */ - this._consumes = parseOptions( - options.consumes, - (item, key) => { - if (Array.isArray(item)) throw new Error("Unexpected array in options"); - /** @type {ConsumeOptions} */ - let result = - item === key || !isRequiredVersion(item) - ? // item is a request/key - { - import: key, - shareScope: options.shareScope || "default", - shareKey: key, - requiredVersion: undefined, - packageName: undefined, - strictVersion: false, - singleton: false, - eager: false - } - : // key is a request/key - // item is a version - { - import: key, - shareScope: options.shareScope || "default", - shareKey: key, - requiredVersion: parseRange(item), - strictVersion: true, - packageName: undefined, - singleton: false, - eager: false - }; - return result; - }, - (item, key) => ({ - import: item.import === false ? undefined : item.import || key, - shareScope: item.shareScope || options.shareScope || "default", - shareKey: item.shareKey || key, - requiredVersion: - typeof item.requiredVersion === "string" - ? parseRange(item.requiredVersion) - : item.requiredVersion, - strictVersion: - typeof item.strictVersion === "boolean" - ? item.strictVersion - : item.import !== false && !item.singleton, - packageName: item.packageName, - singleton: !!item.singleton, - eager: !!item.eager - }) - ); +/** + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result + */ +exports.compareModulesByIdentifier = (a, b) => { + return compareIds(a.identifier(), b.identifier()); +}; + +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result + */ +const compareModulesById = (chunkGraph, a, b) => { + return compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b)); +}; +/** @type {ParameterizedComparator} */ +exports.compareModulesById = + createCachedParameterizedComparator(compareModulesById); + +/** + * @param {number} a number + * @param {number} b number + * @returns {-1|0|1} compare result + */ +const compareNumbers = (a, b) => { + if (typeof a !== typeof b) { + return typeof a < typeof b ? -1 : 1; } + if (a < b) return -1; + if (a > b) return 1; + return 0; +}; +exports.compareNumbers = compareNumbers; - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - PLUGIN_NAME, - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - ConsumeSharedFallbackDependency, - normalModuleFactory - ); +/** + * @param {string} a string + * @param {string} b string + * @returns {-1|0|1} compare result + */ +const compareStringsNumeric = (a, b) => { + const partsA = a.split(/(\d+)/); + const partsB = b.split(/(\d+)/); + const len = Math.min(partsA.length, partsB.length); + for (let i = 0; i < len; i++) { + const pA = partsA[i]; + const pB = partsB[i]; + if (i % 2 === 0) { + if (pA.length > pB.length) { + if (pA.slice(0, pB.length) > pB) return 1; + return -1; + } else if (pB.length > pA.length) { + if (pB.slice(0, pA.length) > pA) return -1; + return 1; + } else { + if (pA < pB) return -1; + if (pA > pB) return 1; + } + } else { + const nA = +pA; + const nB = +pB; + if (nA < nB) return -1; + if (nA > nB) return 1; + } + } + if (partsB.length < partsA.length) return 1; + if (partsB.length > partsA.length) return -1; + return 0; +}; +exports.compareStringsNumeric = compareStringsNumeric; - let unresolvedConsumes, resolvedConsumes, prefixedConsumes; - const promise = resolveMatchedConfigs(compilation, this._consumes).then( - ({ resolved, unresolved, prefixed }) => { - resolvedConsumes = resolved; - unresolvedConsumes = unresolved; - prefixedConsumes = prefixed; - } - ); +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result + */ +const compareModulesByPostOrderIndexOrIdentifier = (moduleGraph, a, b) => { + const cmp = compareNumbers( + moduleGraph.getPostOrderIndex(a), + moduleGraph.getPostOrderIndex(b) + ); + if (cmp !== 0) return cmp; + return compareIds(a.identifier(), b.identifier()); +}; +/** @type {ParameterizedComparator} */ +exports.compareModulesByPostOrderIndexOrIdentifier = + createCachedParameterizedComparator( + compareModulesByPostOrderIndexOrIdentifier + ); - const resolver = compilation.resolverFactory.get( - "normal", - RESOLVE_OPTIONS - ); +/** + * @param {ModuleGraph} moduleGraph the module graph + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result + */ +const compareModulesByPreOrderIndexOrIdentifier = (moduleGraph, a, b) => { + const cmp = compareNumbers( + moduleGraph.getPreOrderIndex(a), + moduleGraph.getPreOrderIndex(b) + ); + if (cmp !== 0) return cmp; + return compareIds(a.identifier(), b.identifier()); +}; +/** @type {ParameterizedComparator} */ +exports.compareModulesByPreOrderIndexOrIdentifier = + createCachedParameterizedComparator( + compareModulesByPreOrderIndexOrIdentifier + ); - /** - * @param {string} context issuer directory - * @param {string} request request - * @param {ConsumeOptions} config options - * @returns {Promise} create module - */ - const createConsumeSharedModule = (context, request, config) => { - const requiredVersionWarning = details => { - const error = new WebpackError( - `No required version specified and unable to automatically determine one. ${details}` - ); - error.file = `shared module ${request}`; - compilation.warnings.push(error); - }; - const directFallback = - config.import && - /^(\.\.?(\/|$)|\/|[A-Za-z]:|\\\\)/.test(config.import); - return Promise.all([ - new Promise(resolve => { - if (!config.import) return resolve(); - const resolveContext = { - /** @type {LazySet} */ - fileDependencies: new LazySet(), - /** @type {LazySet} */ - contextDependencies: new LazySet(), - /** @type {LazySet} */ - missingDependencies: new LazySet() - }; - resolver.resolve( - {}, - directFallback ? compiler.context : context, - config.import, - resolveContext, - (err, result) => { - compilation.contextDependencies.addAll( - resolveContext.contextDependencies - ); - compilation.fileDependencies.addAll( - resolveContext.fileDependencies - ); - compilation.missingDependencies.addAll( - resolveContext.missingDependencies - ); - if (err) { - compilation.errors.push( - new ModuleNotFoundError(null, err, { - name: `resolving fallback for shared module ${request}` - }) - ); - return resolve(); - } - resolve(result); - } - ); - }), - new Promise(resolve => { - if (config.requiredVersion !== undefined) - return resolve(config.requiredVersion); - let packageName = config.packageName; - if (packageName === undefined) { - if (/^(\/|[A-Za-z]:|\\\\)/.test(request)) { - // For relative or absolute requests we don't automatically use a packageName. - // If wished one can specify one with the packageName option. - return resolve(); - } - const match = /^((?:@[^\\/]+[\\/])?[^\\/]+)/.exec(request); - if (!match) { - requiredVersionWarning( - "Unable to extract the package name from request." - ); - return resolve(); - } - packageName = match[0]; - } +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} compare result + */ +const compareModulesByIdOrIdentifier = (chunkGraph, a, b) => { + const cmp = compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b)); + if (cmp !== 0) return cmp; + return compareIds(a.identifier(), b.identifier()); +}; +/** @type {ParameterizedComparator} */ +exports.compareModulesByIdOrIdentifier = createCachedParameterizedComparator( + compareModulesByIdOrIdentifier +); - getDescriptionFile( - compilation.inputFileSystem, - context, - ["package.json"], - (err, result) => { - if (err) { - requiredVersionWarning( - `Unable to read description file: ${err}` - ); - return resolve(); - } - const { data, path: descriptionPath } = result; - if (!data) { - requiredVersionWarning( - `Unable to find description file in ${context}.` - ); - return resolve(); - } - const requiredVersion = getRequiredVersionFromDescriptionFile( - data, - packageName - ); - if (typeof requiredVersion !== "string") { - requiredVersionWarning( - `Unable to find required version for "${packageName}" in description file (${descriptionPath}). It need to be in dependencies, devDependencies or peerDependencies.` - ); - return resolve(); - } - resolve(parseRange(requiredVersion)); - } - ); - }) - ]).then(([importResolved, requiredVersion]) => { - return new ConsumeSharedModule( - directFallback ? compiler.context : context, - { - ...config, - importResolved, - import: importResolved ? config.import : undefined, - requiredVersion - } - ); - }); - }; +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Chunk} a chunk + * @param {Chunk} b chunk + * @returns {-1|0|1} compare result + */ +const compareChunks = (chunkGraph, a, b) => { + return chunkGraph.compareChunks(a, b); +}; +/** @type {ParameterizedComparator} */ +exports.compareChunks = createCachedParameterizedComparator(compareChunks); - normalModuleFactory.hooks.factorize.tapPromise( - PLUGIN_NAME, - ({ context, request, dependencies }) => - // wait for resolving to be complete - promise.then(() => { - if ( - dependencies[0] instanceof ConsumeSharedFallbackDependency || - dependencies[0] instanceof ProvideForSharedDependency - ) { - return; - } - const match = unresolvedConsumes.get(request); - if (match !== undefined) { - return createConsumeSharedModule(context, request, match); - } - for (const [prefix, options] of prefixedConsumes) { - if (request.startsWith(prefix)) { - const remainder = request.slice(prefix.length); - return createConsumeSharedModule(context, request, { - ...options, - import: options.import - ? options.import + remainder - : undefined, - shareKey: options.shareKey + remainder - }); - } - } - }) - ); - normalModuleFactory.hooks.createModule.tapPromise( - PLUGIN_NAME, - ({ resource }, { context, dependencies }) => { - if ( - dependencies[0] instanceof ConsumeSharedFallbackDependency || - dependencies[0] instanceof ProvideForSharedDependency - ) { - return Promise.resolve(); - } - const options = resolvedConsumes.get(resource); - if (options !== undefined) { - return createConsumeSharedModule(context, resource, options); - } - return Promise.resolve(); - } - ); - compilation.hooks.additionalTreeRuntimeRequirements.tap( - PLUGIN_NAME, - (chunk, set) => { - set.add(RuntimeGlobals.module); - set.add(RuntimeGlobals.moduleCache); - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.shareScopeMap); - set.add(RuntimeGlobals.initializeSharing); - set.add(RuntimeGlobals.hasOwnProperty); - compilation.addRuntimeModule( - chunk, - new ConsumeSharedRuntimeModule(set) - ); - } - ); - } - ); +/** + * @param {string|number} a first id + * @param {string|number} b second id + * @returns {-1|0|1} compare result + */ +const compareIds = (a, b) => { + if (typeof a !== typeof b) { + return typeof a < typeof b ? -1 : 1; } -} + if (a < b) return -1; + if (a > b) return 1; + return 0; +}; -module.exports = ConsumeSharedPlugin; +exports.compareIds = compareIds; +/** + * @param {string} a first string + * @param {string} b second string + * @returns {-1|0|1} compare result + */ +const compareStrings = (a, b) => { + if (a < b) return -1; + if (a > b) return 1; + return 0; +}; -/***/ }), +exports.compareStrings = compareStrings; -/***/ 10394: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @param {ChunkGroup} a first chunk group + * @param {ChunkGroup} b second chunk group + * @returns {-1|0|1} compare result + */ +const compareChunkGroupsByIndex = (a, b) => { + return a.index < b.index ? -1 : 1; +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +exports.compareChunkGroupsByIndex = compareChunkGroupsByIndex; +/** + * @template K1 {Object} + * @template K2 + * @template T + */ +class TwoKeyWeakMap { + constructor() { + /** @private @type {WeakMap>} */ + this._map = new WeakMap(); + } + /** + * @param {K1} key1 first key + * @param {K2} key2 second key + * @returns {T | undefined} value + */ + get(key1, key2) { + const childMap = this._map.get(key1); + if (childMap === undefined) { + return undefined; + } + return childMap.get(key2); + } -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); -const { - parseVersionRuntimeCode, - versionLtRuntimeCode, - rangeToStringRuntimeCode, - satisfyRuntimeCode -} = __webpack_require__(19702); + /** + * @param {K1} key1 first key + * @param {K2} key2 second key + * @param {T | undefined} value new value + * @returns {void} + */ + set(key1, key2, value) { + let childMap = this._map.get(key1); + if (childMap === undefined) { + childMap = new WeakMap(); + this._map.set(key1, childMap); + } + childMap.set(key2, value); + } +} -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("./ConsumeSharedModule")} ConsumeSharedModule */ +/** @type {TwoKeyWeakMap, Comparator, Comparator>}} */ +const concatComparatorsCache = new TwoKeyWeakMap(); -class ConsumeSharedRuntimeModule extends RuntimeModule { - constructor(runtimeRequirements) { - super("consumes", RuntimeModule.STAGE_ATTACH); - this._runtimeRequirements = runtimeRequirements; +/** + * @template T + * @param {Comparator} c1 comparator + * @param {Comparator} c2 comparator + * @param {Comparator[]} cRest comparators + * @returns {Comparator} comparator + */ +const concatComparators = (c1, c2, ...cRest) => { + if (cRest.length > 0) { + const [c3, ...cRest2] = cRest; + return concatComparators(c1, concatComparators(c2, c3, ...cRest2)); } + const cacheEntry = /** @type {Comparator} */ ( + concatComparatorsCache.get(c1, c2) + ); + if (cacheEntry !== undefined) return cacheEntry; + /** + * @param {T} a first value + * @param {T} b second value + * @returns {-1|0|1} compare result + */ + const result = (a, b) => { + const res = c1(a, b); + if (res !== 0) return res; + return c2(a, b); + }; + concatComparatorsCache.set(c1, c2, result); + return result; +}; +exports.concatComparators = concatComparators; + +/** @template A, B @typedef {(input: A) => B} Selector */ + +/** @type {TwoKeyWeakMap, Comparator, Comparator>}} */ +const compareSelectCache = new TwoKeyWeakMap(); +/** + * @template T + * @template R + * @param {Selector} getter getter for value + * @param {Comparator} comparator comparator + * @returns {Comparator} comparator + */ +const compareSelect = (getter, comparator) => { + const cacheEntry = compareSelectCache.get(getter, comparator); + if (cacheEntry !== undefined) return cacheEntry; /** - * @returns {string} runtime code + * @param {T} a first value + * @param {T} b second value + * @returns {-1|0|1} compare result */ - generate() { - const { compilation, chunkGraph } = this; - const { runtimeTemplate, codeGenerationResults } = compilation; - const chunkToModuleMapping = {}; - /** @type {Map} */ - const moduleIdToSourceMapping = new Map(); - const initialConsumes = []; - /** - * - * @param {Iterable} modules modules - * @param {Chunk} chunk the chunk - * @param {(string | number)[]} list list of ids - */ - const addModules = (modules, chunk, list) => { - for (const m of modules) { - const module = /** @type {ConsumeSharedModule} */ (m); - const id = chunkGraph.getModuleId(module); - list.push(id); - moduleIdToSourceMapping.set( - id, - codeGenerationResults.getSource( - module, - chunk.runtime, - "consume-shared" - ) - ); + const result = (a, b) => { + const aValue = getter(a); + const bValue = getter(b); + if (aValue !== undefined && aValue !== null) { + if (bValue !== undefined && bValue !== null) { + return comparator(aValue, bValue); } - }; - for (const chunk of this.chunk.getAllAsyncChunks()) { - const modules = chunkGraph.getChunkModulesIterableBySourceType( - chunk, - "consume-shared" - ); - if (!modules) continue; - addModules(modules, chunk, (chunkToModuleMapping[chunk.id] = [])); + return -1; + } else { + if (bValue !== undefined && bValue !== null) { + return 1; + } + return 0; } - for (const chunk of this.chunk.getAllInitialChunks()) { - const modules = chunkGraph.getChunkModulesIterableBySourceType( - chunk, - "consume-shared" - ); - if (!modules) continue; - addModules(modules, chunk, initialConsumes); + }; + compareSelectCache.set(getter, comparator, result); + return result; +}; +exports.compareSelect = compareSelect; + +/** @type {WeakMap, Comparator>>} */ +const compareIteratorsCache = new WeakMap(); + +/** + * @template T + * @param {Comparator} elementComparator comparator for elements + * @returns {Comparator>} comparator for iterables of elements + */ +const compareIterables = elementComparator => { + const cacheEntry = compareIteratorsCache.get(elementComparator); + if (cacheEntry !== undefined) return cacheEntry; + /** + * @param {Iterable} a first value + * @param {Iterable} b second value + * @returns {-1|0|1} compare result + */ + const result = (a, b) => { + const aI = a[Symbol.iterator](); + const bI = b[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = aI.next(); + const bItem = bI.next(); + if (aItem.done) { + return bItem.done ? 0 : -1; + } else if (bItem.done) { + return 1; + } + const res = elementComparator(aItem.value, bItem.value); + if (res !== 0) return res; } - if (moduleIdToSourceMapping.size === 0) return null; - return Template.asString([ - parseVersionRuntimeCode(runtimeTemplate), - versionLtRuntimeCode(runtimeTemplate), - rangeToStringRuntimeCode(runtimeTemplate), - satisfyRuntimeCode(runtimeTemplate), - `var ensureExistence = ${runtimeTemplate.basicFunction("scopeName, key", [ - `var scope = ${RuntimeGlobals.shareScopeMap}[scopeName];`, - `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) throw new Error("Shared module " + key + " doesn't exist in shared scope " + scopeName);`, - "return scope;" - ])};`, - `var findVersion = ${runtimeTemplate.basicFunction("scope, key", [ - "var versions = scope[key];", - `var key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( - "a, b", - ["return !a || versionLt(a, b) ? b : a;"] - )}, 0);`, - "return key && versions[key]" - ])};`, - `var findSingletonVersionKey = ${runtimeTemplate.basicFunction( - "scope, key", - [ - "var versions = scope[key];", - `return Object.keys(versions).reduce(${runtimeTemplate.basicFunction( - "a, b", - ["return !a || (!versions[a].loaded && versionLt(a, b)) ? b : a;"] - )}, 0);` - ] - )};`, - `var getInvalidSingletonVersionMessage = ${runtimeTemplate.basicFunction( - "scope, key, version, requiredVersion", - [ - `return "Unsatisfied version " + version + " from " + (version && scope[key][version].from) + " of shared singleton module " + key + " (required " + rangeToString(requiredVersion) + ")"` - ] - )};`, - `var getSingleton = ${runtimeTemplate.basicFunction( - "scope, scopeName, key, requiredVersion", - [ - "var version = findSingletonVersionKey(scope, key);", - "return get(scope[key][version]);" - ] - )};`, - `var getSingletonVersion = ${runtimeTemplate.basicFunction( - "scope, scopeName, key, requiredVersion", - [ - "var version = findSingletonVersionKey(scope, key);", - "if (!satisfy(requiredVersion, version)) " + - 'typeof console !== "undefined" && console.warn && console.warn(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));', - "return get(scope[key][version]);" - ] - )};`, - `var getStrictSingletonVersion = ${runtimeTemplate.basicFunction( - "scope, scopeName, key, requiredVersion", - [ - "var version = findSingletonVersionKey(scope, key);", - "if (!satisfy(requiredVersion, version)) " + - "throw new Error(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));", - "return get(scope[key][version]);" - ] - )};`, - `var findValidVersion = ${runtimeTemplate.basicFunction( - "scope, key, requiredVersion", - [ - "var versions = scope[key];", - `var key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( - "a, b", - [ - "if (!satisfy(requiredVersion, b)) return a;", - "return !a || versionLt(a, b) ? b : a;" - ] - )}, 0);`, - "return key && versions[key]" - ] - )};`, - `var getInvalidVersionMessage = ${runtimeTemplate.basicFunction( - "scope, scopeName, key, requiredVersion", - [ - "var versions = scope[key];", - 'return "No satisfying version (" + rangeToString(requiredVersion) + ") of shared module " + key + " found in shared scope " + scopeName + ".\\n" +', - `\t"Available versions: " + Object.keys(versions).map(${runtimeTemplate.basicFunction( - "key", - ['return key + " from " + versions[key].from;'] - )}).join(", ");` - ] - )};`, - `var getValidVersion = ${runtimeTemplate.basicFunction( - "scope, scopeName, key, requiredVersion", - [ - "var entry = findValidVersion(scope, key, requiredVersion);", - "if(entry) return get(entry);", - "throw new Error(getInvalidVersionMessage(scope, scopeName, key, requiredVersion));" - ] - )};`, - `var warnInvalidVersion = ${runtimeTemplate.basicFunction( - "scope, scopeName, key, requiredVersion", - [ - 'typeof console !== "undefined" && console.warn && console.warn(getInvalidVersionMessage(scope, scopeName, key, requiredVersion));' - ] - )};`, - `var get = ${runtimeTemplate.basicFunction("entry", [ - "entry.loaded = 1;", - "return entry.get()" - ])};`, - `var init = ${runtimeTemplate.returningFunction( - Template.asString([ - "function(scopeName, a, b, c) {", - Template.indent([ - `var promise = ${RuntimeGlobals.initializeSharing}(scopeName);`, - `if (promise && promise.then) return promise.then(fn.bind(fn, scopeName, ${RuntimeGlobals.shareScopeMap}[scopeName], a, b, c));`, - `return fn(scopeName, ${RuntimeGlobals.shareScopeMap}[scopeName], a, b, c);` - ]), - "}" - ]), - "fn" - )};`, - "", - `var load = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key", - [ - "ensureExistence(scopeName, key);", - "return get(findVersion(scope, key));" - ] - )});`, - `var loadFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, fallback", - [ - `return scope && ${RuntimeGlobals.hasOwnProperty}(scope, key) ? get(findVersion(scope, key)) : fallback();` - ] - )});`, - `var loadVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version", - [ - "ensureExistence(scopeName, key);", - "return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key));" - ] - )});`, - `var loadSingleton = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key", - [ - "ensureExistence(scopeName, key);", - "return getSingleton(scope, scopeName, key);" - ] - )});`, - `var loadSingletonVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version", - [ - "ensureExistence(scopeName, key);", - "return getSingletonVersion(scope, scopeName, key, version);" - ] - )});`, - `var loadStrictVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version", - [ - "ensureExistence(scopeName, key);", - "return getValidVersion(scope, scopeName, key, version);" - ] - )});`, - `var loadStrictSingletonVersionCheck = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version", - [ - "ensureExistence(scopeName, key);", - "return getStrictSingletonVersion(scope, scopeName, key, version);" - ] - )});`, - `var loadVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version, fallback", - [ - `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, - "return get(findValidVersion(scope, key, version) || warnInvalidVersion(scope, scopeName, key, version) || findVersion(scope, key));" - ] - )});`, - `var loadSingletonFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, fallback", - [ - `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, - "return getSingleton(scope, scopeName, key);" - ] - )});`, - `var loadSingletonVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version, fallback", - [ - `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, - "return getSingletonVersion(scope, scopeName, key, version);" - ] - )});`, - `var loadStrictVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version, fallback", - [ - `var entry = scope && ${RuntimeGlobals.hasOwnProperty}(scope, key) && findValidVersion(scope, key, version);`, - `return entry ? get(entry) : fallback();` - ] - )});`, - `var loadStrictSingletonVersionCheckFallback = /*#__PURE__*/ init(${runtimeTemplate.basicFunction( - "scopeName, scope, key, version, fallback", - [ - `if(!scope || !${RuntimeGlobals.hasOwnProperty}(scope, key)) return fallback();`, - "return getStrictSingletonVersion(scope, scopeName, key, version);" - ] - )});`, - "var installedModules = {};", - "var moduleToHandlerMapping = {", - Template.indent( - Array.from( - moduleIdToSourceMapping, - ([key, source]) => `${JSON.stringify(key)}: ${source.source()}` - ).join(",\n") - ), - "};", + }; + compareIteratorsCache.set(elementComparator, result); + return result; +}; +exports.compareIterables = compareIterables; - initialConsumes.length > 0 - ? Template.asString([ - `var initialConsumes = ${JSON.stringify(initialConsumes)};`, - `initialConsumes.forEach(${runtimeTemplate.basicFunction("id", [ - `${ - RuntimeGlobals.moduleFactories - }[id] = ${runtimeTemplate.basicFunction("module", [ - "// Handle case when module is used sync", - "installedModules[id] = 0;", - `delete ${RuntimeGlobals.moduleCache}[id];`, - "var factory = moduleToHandlerMapping[id]();", - 'if(typeof factory !== "function") throw new Error("Shared module is not available for eager consumption: " + id);', - `module.exports = factory();` - ])}` - ])});` - ]) - : "// no consumes in initial chunks", - this._runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) - ? Template.asString([ - `var chunkMapping = ${JSON.stringify( - chunkToModuleMapping, - null, - "\t" - )};`, - `${ - RuntimeGlobals.ensureChunkHandlers - }.consumes = ${runtimeTemplate.basicFunction("chunkId, promises", [ - `if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`, - Template.indent([ - `chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction( - "id", - [ - `if(${RuntimeGlobals.hasOwnProperty}(installedModules, id)) return promises.push(installedModules[id]);`, - `var onFactory = ${runtimeTemplate.basicFunction( - "factory", - [ - "installedModules[id] = 0;", - `${ - RuntimeGlobals.moduleFactories - }[id] = ${runtimeTemplate.basicFunction("module", [ - `delete ${RuntimeGlobals.moduleCache}[id];`, - "module.exports = factory();" - ])}` - ] - )};`, - `var onError = ${runtimeTemplate.basicFunction("error", [ - "delete installedModules[id];", - `${ - RuntimeGlobals.moduleFactories - }[id] = ${runtimeTemplate.basicFunction("module", [ - `delete ${RuntimeGlobals.moduleCache}[id];`, - "throw error;" - ])}` - ])};`, - "try {", - Template.indent([ - "var promise = moduleToHandlerMapping[id]();", - "if(promise.then) {", - Template.indent( - "promises.push(installedModules[id] = promise.then(onFactory)['catch'](onError));" - ), - "} else onFactory(promise);" - ]), - "} catch(e) { onError(e); }" - ] - )});` - ]), - "}" - ])}` - ]) - : "// no chunk loading of consumes" - ]); +// TODO this is no longer needed when minimum node.js version is >= 12 +// since these versions ship with a stable sort function +/** + * @template T + * @param {Iterable} iterable original ordered list + * @returns {Comparator} comparator + */ +exports.keepOriginalOrder = iterable => { + /** @type {Map} */ + const map = new Map(); + let i = 0; + for (const item of iterable) { + map.set(item, i++); } -} + return (a, b) => compareNumbers(map.get(a), map.get(b)); +}; + +/** + * @param {ChunkGraph} chunkGraph the chunk graph + * @returns {Comparator} comparator + */ +exports.compareChunksNatural = chunkGraph => { + const cmpFn = exports.compareModulesById(chunkGraph); + const cmpIterableFn = compareIterables(cmpFn); + return concatComparators( + compareSelect(chunk => chunk.name, compareIds), + compareSelect(chunk => chunk.runtime, compareRuntime), + compareSelect( + /** + * @param {Chunk} chunk a chunk + * @returns {Iterable} modules + */ + chunk => chunkGraph.getOrderedChunkModulesIterable(chunk, cmpFn), + cmpIterableFn + ) + ); +}; -module.exports = ConsumeSharedRuntimeModule; +/** + * Compare two locations + * @param {DependencyLocation} a A location node + * @param {DependencyLocation} b A location node + * @returns {-1|0|1} sorting comparator value + */ +exports.compareLocations = (a, b) => { + let isObjectA = typeof a === "object" && a !== null; + let isObjectB = typeof b === "object" && b !== null; + if (!isObjectA || !isObjectB) { + if (isObjectA) return 1; + if (isObjectB) return -1; + return 0; + } + if ("start" in a) { + if ("start" in b) { + const ap = a.start; + const bp = b.start; + if (ap.line < bp.line) return -1; + if (ap.line > bp.line) return 1; + if (ap.column < bp.column) return -1; + if (ap.column > bp.column) return 1; + } else return -1; + } else if ("start" in b) return 1; + if ("name" in a) { + if ("name" in b) { + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + } else return -1; + } else if ("name" in b) return 1; + if ("index" in a) { + if ("index" in b) { + if (a.index < b.index) return -1; + if (a.index > b.index) return 1; + } else return -1; + } else if ("index" in b) return 1; + return 0; +}; /***/ }), -/***/ 40017: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 29404: +/***/ (function(module) { "use strict"; /* @@ -122549,38 +124295,210 @@ module.exports = ConsumeSharedRuntimeModule; -const ModuleDependency = __webpack_require__(80321); -const makeSerializable = __webpack_require__(33032); +const quoteMeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); +}; -class ProvideForSharedDependency extends ModuleDependency { - /** - * - * @param {string} request request string - */ - constructor(request) { - super(request); +const toSimpleString = str => { + if (`${+str}` === str) { + return str; } + return JSON.stringify(str); +}; - get type() { - return "provide module for shared"; +/** + * @param {Record} map value map + * @returns {true|false|function(string): string} true/false, when unconditionally true/false, or a template function to determine the value at runtime + */ +const compileBooleanMatcher = map => { + const positiveItems = Object.keys(map).filter(i => map[i]); + const negativeItems = Object.keys(map).filter(i => !map[i]); + if (positiveItems.length === 0) return false; + if (negativeItems.length === 0) return true; + return compileBooleanMatcherFromLists(positiveItems, negativeItems); +}; + +/** + * @param {string[]} positiveItems positive items + * @param {string[]} negativeItems negative items + * @returns {function(string): string} a template function to determine the value at runtime + */ +const compileBooleanMatcherFromLists = (positiveItems, negativeItems) => { + if (positiveItems.length === 0) return () => "false"; + if (negativeItems.length === 0) return () => "true"; + if (positiveItems.length === 1) + return value => `${toSimpleString(positiveItems[0])} == ${value}`; + if (negativeItems.length === 1) + return value => `${toSimpleString(negativeItems[0])} != ${value}`; + const positiveRegexp = itemsToRegexp(positiveItems); + const negativeRegexp = itemsToRegexp(negativeItems); + if (positiveRegexp.length <= negativeRegexp.length) { + return value => `/^${positiveRegexp}$/.test(${value})`; + } else { + return value => `!/^${negativeRegexp}$/.test(${value})`; } +}; - get category() { - return "esm"; +const popCommonItems = (itemsSet, getKey, condition) => { + const map = new Map(); + for (const item of itemsSet) { + const key = getKey(item); + if (key) { + let list = map.get(key); + if (list === undefined) { + list = []; + map.set(key, list); + } + list.push(item); + } } -} + const result = []; + for (const list of map.values()) { + if (condition(list)) { + for (const item of list) { + itemsSet.delete(item); + } + result.push(list); + } + } + return result; +}; -makeSerializable( - ProvideForSharedDependency, - "webpack/lib/sharing/ProvideForSharedDependency" -); +const getCommonPrefix = items => { + let prefix = items[0]; + for (let i = 1; i < items.length; i++) { + const item = items[i]; + for (let p = 0; p < prefix.length; p++) { + if (item[p] !== prefix[p]) { + prefix = prefix.slice(0, p); + break; + } + } + } + return prefix; +}; -module.exports = ProvideForSharedDependency; +const getCommonSuffix = items => { + let suffix = items[0]; + for (let i = 1; i < items.length; i++) { + const item = items[i]; + for (let p = item.length - 1, s = suffix.length - 1; s >= 0; p--, s--) { + if (item[p] !== suffix[s]) { + suffix = suffix.slice(s + 1); + break; + } + } + } + return suffix; +}; + +const itemsToRegexp = itemsArr => { + if (itemsArr.length === 1) { + return quoteMeta(itemsArr[0]); + } + const finishedItems = []; + + // merge single char items: (a|b|c|d|ef) => ([abcd]|ef) + let countOfSingleCharItems = 0; + for (const item of itemsArr) { + if (item.length === 1) { + countOfSingleCharItems++; + } + } + // special case for only single char items + if (countOfSingleCharItems === itemsArr.length) { + return `[${quoteMeta(itemsArr.sort().join(""))}]`; + } + const items = new Set(itemsArr.sort()); + if (countOfSingleCharItems > 2) { + let singleCharItems = ""; + for (const item of items) { + if (item.length === 1) { + singleCharItems += item; + items.delete(item); + } + } + finishedItems.push(`[${quoteMeta(singleCharItems)}]`); + } + + // special case for 2 items with common prefix/suffix + if (finishedItems.length === 0 && items.size === 2) { + const prefix = getCommonPrefix(itemsArr); + const suffix = getCommonSuffix( + itemsArr.map(item => item.slice(prefix.length)) + ); + if (prefix.length > 0 || suffix.length > 0) { + return `${quoteMeta(prefix)}${itemsToRegexp( + itemsArr.map(i => i.slice(prefix.length, -suffix.length || undefined)) + )}${quoteMeta(suffix)}`; + } + } + + // special case for 2 items with common suffix + if (finishedItems.length === 0 && items.size === 2) { + const it = items[Symbol.iterator](); + const a = it.next().value; + const b = it.next().value; + if (a.length > 0 && b.length > 0 && a.slice(-1) === b.slice(-1)) { + return `${itemsToRegexp([a.slice(0, -1), b.slice(0, -1)])}${quoteMeta( + a.slice(-1) + )}`; + } + } + + // find common prefix: (a1|a2|a3|a4|b5) => (a(1|2|3|4)|b5) + const prefixed = popCommonItems( + items, + item => (item.length >= 1 ? item[0] : false), + list => { + if (list.length >= 3) return true; + if (list.length <= 1) return false; + return list[0][1] === list[1][1]; + } + ); + for (const prefixedItems of prefixed) { + const prefix = getCommonPrefix(prefixedItems); + finishedItems.push( + `${quoteMeta(prefix)}${itemsToRegexp( + prefixedItems.map(i => i.slice(prefix.length)) + )}` + ); + } + + // find common suffix: (a1|b1|c1|d1|e2) => ((a|b|c|d)1|e2) + const suffixed = popCommonItems( + items, + item => (item.length >= 1 ? item.slice(-1) : false), + list => { + if (list.length >= 3) return true; + if (list.length <= 1) return false; + return list[0].slice(-2) === list[1].slice(-2); + } + ); + for (const suffixedItems of suffixed) { + const suffix = getCommonSuffix(suffixedItems); + finishedItems.push( + `${itemsToRegexp( + suffixedItems.map(i => i.slice(0, -suffix.length)) + )}${quoteMeta(suffix)}` + ); + } + + // TODO further optimize regexp, i. e. + // use ranges: (1|2|3|4|a) => [1-4a] + const conditional = finishedItems.concat(Array.from(items, quoteMeta)); + if (conditional.length === 1) return conditional[0]; + return `(${conditional.join("|")})`; +}; + +compileBooleanMatcher.fromLists = compileBooleanMatcherFromLists; +compileBooleanMatcher.itemsToRegexp = itemsToRegexp; +module.exports = compileBooleanMatcher; /***/ }), -/***/ 1798: +/***/ 32540: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -122591,648 +124509,1026 @@ module.exports = ProvideForSharedDependency; -const Dependency = __webpack_require__(54912); -const makeSerializable = __webpack_require__(33032); - -class ProvideSharedDependency extends Dependency { - constructor(shareScope, name, version, request, eager) { - super(); - this.shareScope = shareScope; - this.name = name; - this.version = version; - this.request = request; - this.eager = eager; - } - - get type() { - return "provide shared module"; - } - - /** - * @returns {string | null} an identifier to merge equal requests - */ - getResourceIdentifier() { - return `provide module (${this.shareScope}) ${this.request} as ${ - this.name - } @ ${this.version}${this.eager ? " (eager)" : ""}`; - } - - serialize(context) { - context.write(this.shareScope); - context.write(this.name); - context.write(this.request); - context.write(this.version); - context.write(this.eager); - super.serialize(context); - } +const memoize = __webpack_require__(78676); - static deserialize(context) { - const { read } = context; - const obj = new ProvideSharedDependency( - read(), - read(), - read(), - read(), - read() - ); - this.shareScope = context.read(); - obj.deserialize(context); - return obj; - } -} +const getValidate = memoize(() => (__webpack_require__(38476).validate)); -makeSerializable( - ProvideSharedDependency, - "webpack/lib/sharing/ProvideSharedDependency" -); +const createSchemaValidation = (check, getSchema, options) => { + getSchema = memoize(getSchema); + return value => { + if (check && !check(value)) { + getValidate()(getSchema(), value, options); + if (check) { + (__webpack_require__(73837).deprecate)( + () => {}, + "webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.", + "DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID" + )(); + } + } + }; +}; -module.exports = ProvideSharedDependency; +module.exports = createSchemaValidation; /***/ }), -/***/ 50821: +/***/ 49835: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy + Author Tobias Koppers @sokra */ -const AsyncDependenciesBlock = __webpack_require__(47736); -const Module = __webpack_require__(73208); -const RuntimeGlobals = __webpack_require__(16475); -const makeSerializable = __webpack_require__(33032); -const ProvideForSharedDependency = __webpack_require__(40017); +const Hash = __webpack_require__(36692); -/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */ -/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */ -/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */ -/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/Hash")} Hash */ -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ +const BULK_SIZE = 2000; -const TYPES = new Set(["share-init"]); +// We are using an object instead of a Map as this will stay static during the runtime +// so access to it can be optimized by v8 +const digestCaches = {}; -class ProvideSharedModule extends Module { +class BulkUpdateDecorator extends Hash { /** - * @param {string} shareScope shared scope name - * @param {string} name shared key - * @param {string | false} version version - * @param {string} request request to the provided module - * @param {boolean} eager include the module in sync way + * @param {Hash | function(): Hash} hashOrFactory function to create a hash + * @param {string=} hashKey key for caching */ - constructor(shareScope, name, version, request, eager) { - super("provide-module"); - this._shareScope = shareScope; - this._name = name; - this._version = version; - this._request = request; - this._eager = eager; + constructor(hashOrFactory, hashKey) { + super(); + this.hashKey = hashKey; + if (typeof hashOrFactory === "function") { + this.hashFactory = hashOrFactory; + this.hash = undefined; + } else { + this.hashFactory = undefined; + this.hash = hashOrFactory; + } + this.buffer = ""; } /** - * @returns {string} a unique identifier of the module + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash */ - identifier() { - return `provide module (${this._shareScope}) ${this._name}@${this._version} = ${this._request}`; + update(data, inputEncoding) { + if ( + inputEncoding !== undefined || + typeof data !== "string" || + data.length > BULK_SIZE + ) { + if (this.hash === undefined) this.hash = this.hashFactory(); + if (this.buffer.length > 0) { + this.hash.update(this.buffer); + this.buffer = ""; + } + this.hash.update(data, inputEncoding); + } else { + this.buffer += data; + if (this.buffer.length > BULK_SIZE) { + if (this.hash === undefined) this.hash = this.hashFactory(); + this.hash.update(this.buffer); + this.buffer = ""; + } + } + return this; } /** - * @param {RequestShortener} requestShortener the request shortener - * @returns {string} a user readable identifier of the module + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest */ - readableIdentifier(requestShortener) { - return `provide shared module (${this._shareScope}) ${this._name}@${ - this._version - } = ${requestShortener.shorten(this._request)}`; + digest(encoding) { + let digestCache; + const buffer = this.buffer; + if (this.hash === undefined) { + // short data for hash, we can use caching + const cacheKey = `${this.hashKey}-${encoding}`; + digestCache = digestCaches[cacheKey]; + if (digestCache === undefined) { + digestCache = digestCaches[cacheKey] = new Map(); + } + const cacheEntry = digestCache.get(buffer); + if (cacheEntry !== undefined) return cacheEntry; + this.hash = this.hashFactory(); + } + if (buffer.length > 0) { + this.hash.update(buffer); + } + const digestResult = this.hash.digest(encoding); + const result = + typeof digestResult === "string" ? digestResult : digestResult.toString(); + if (digestCache !== undefined) { + digestCache.set(buffer, result); + } + return result; } +} - /** - * @param {LibIdentOptions} options options - * @returns {string | null} an identifier for library inclusion - */ - libIdent(options) { - return `${this.layer ? `(${this.layer})/` : ""}webpack/sharing/provide/${ - this._shareScope - }/${this._name}`; +/* istanbul ignore next */ +class DebugHash extends Hash { + constructor() { + super(); + this.string = ""; } /** - * @param {NeedBuildContext} context context info - * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild - * @returns {void} + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash */ - needBuild(context, callback) { - callback(null, !this.buildInfo); + update(data, inputEncoding) { + if (typeof data !== "string") data = data.toString("utf-8"); + if (data.startsWith("debug-digest-")) { + data = Buffer.from(data.slice("debug-digest-".length), "hex").toString(); + } + this.string += `[${data}](${new Error().stack.split("\n", 3)[2]})\n`; + return this; } /** - * @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} + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest */ - build(options, compilation, resolver, fs, callback) { - this.buildMeta = {}; - this.buildInfo = { - strict: true - }; + digest(encoding) { + return "debug-digest-" + Buffer.from(this.string).toString("hex"); + } +} - this.clearDependenciesAndBlocks(); - const dep = new ProvideForSharedDependency(this._request); - if (this._eager) { - this.addDependency(dep); - } else { - const block = new AsyncDependenciesBlock({}); - block.addDependency(dep); - this.addBlock(block); - } +let crypto = undefined; +let createXXHash64 = undefined; +let createMd4 = undefined; +let BatchedHash = undefined; - callback(); +/** + * Creates a hash by name or function + * @param {string | typeof Hash} algorithm the algorithm name or a constructor creating a hash + * @returns {Hash} the hash + */ +module.exports = algorithm => { + if (typeof algorithm === "function") { + return new BulkUpdateDecorator(() => new algorithm()); } - - /** - * @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; + switch (algorithm) { + // TODO add non-cryptographic algorithm here + case "debug": + return new DebugHash(); + case "xxhash64": + if (createXXHash64 === undefined) { + createXXHash64 = __webpack_require__(35028); + if (BatchedHash === undefined) { + BatchedHash = __webpack_require__(59461); + } + } + return new BatchedHash(createXXHash64()); + case "md4": + if (createMd4 === undefined) { + createMd4 = __webpack_require__(86884); + if (BatchedHash === undefined) { + BatchedHash = __webpack_require__(59461); + } + } + return new BatchedHash(createMd4()); + case "native-md4": + if (crypto === undefined) crypto = __webpack_require__(6113); + return new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4"); + default: + if (crypto === undefined) crypto = __webpack_require__(6113); + return new BulkUpdateDecorator( + () => crypto.createHash(algorithm), + algorithm + ); } +}; + + +/***/ }), + +/***/ 64518: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const util = __webpack_require__(73837); +/** @type {Map} */ +const deprecationCache = new Map(); + +/** + * @typedef {Object} FakeHookMarker + * @property {true} _fakeHook it's a fake hook + */ + +/** @template T @typedef {T & FakeHookMarker} FakeHook */ + +/** + * @param {string} message deprecation message + * @param {string} code deprecation code + * @returns {Function} function to trigger deprecation + */ +const createDeprecation = (message, code) => { + const cached = deprecationCache.get(message); + if (cached !== undefined) return cached; + const fn = util.deprecate( + () => {}, + message, + "DEP_WEBPACK_DEPRECATION_" + code + ); + deprecationCache.set(message, fn); + return fn; +}; + +const COPY_METHODS = [ + "concat", + "entry", + "filter", + "find", + "findIndex", + "includes", + "indexOf", + "join", + "lastIndexOf", + "map", + "reduce", + "reduceRight", + "slice", + "some" +]; + +const DISABLED_METHODS = [ + "copyWithin", + "entries", + "fill", + "keys", + "pop", + "reverse", + "shift", + "splice", + "sort", + "unshift" +]; + +/** + * @param {any} set new set + * @param {string} name property name + * @returns {void} + */ +exports.arrayToSetDeprecation = (set, name) => { + for (const method of COPY_METHODS) { + if (set[method]) continue; + const d = createDeprecation( + `${name} was changed from Array to Set (using Array method '${method}' is deprecated)`, + "ARRAY_TO_SET" + ); + /** + * @deprecated + * @this {Set} + * @returns {number} count + */ + set[method] = function () { + d(); + const array = Array.from(this); + return Array.prototype[method].apply(array, arguments); + }; + } + const dPush = createDeprecation( + `${name} was changed from Array to Set (using Array method 'push' is deprecated)`, + "ARRAY_TO_SET_PUSH" + ); + const dLength = createDeprecation( + `${name} was changed from Array to Set (using Array property 'length' is deprecated)`, + "ARRAY_TO_SET_LENGTH" + ); + const dIndexer = createDeprecation( + `${name} was changed from Array to Set (indexing Array is deprecated)`, + "ARRAY_TO_SET_INDEXER" + ); /** - * @returns {Set} types available (do not mutate) + * @deprecated + * @this {Set} + * @returns {number} count */ - getSourceTypes() { - return TYPES; + set.push = function () { + dPush(); + for (const item of Array.from(arguments)) { + this.add(item); + } + return this.size; + }; + for (const method of DISABLED_METHODS) { + if (set[method]) continue; + set[method] = () => { + throw new Error( + `${name} was changed from Array to Set (using Array method '${method}' is not possible)` + ); + }; } + const createIndexGetter = index => { + /** + * @this {Set} a Set + * @returns {any} the value at this location + */ + const fn = function () { + dIndexer(); + let i = 0; + for (const item of this) { + if (i++ === index) return item; + } + return undefined; + }; + return fn; + }; + const defineIndexGetter = index => { + Object.defineProperty(set, index, { + get: createIndexGetter(index), + set(value) { + throw new Error( + `${name} was changed from Array to Set (indexing Array with write is not possible)` + ); + } + }); + }; + defineIndexGetter(0); + let indexerDefined = 1; + Object.defineProperty(set, "length", { + get() { + dLength(); + const length = this.size; + for (indexerDefined; indexerDefined < length + 1; indexerDefined++) { + defineIndexGetter(indexerDefined); + } + return length; + }, + set(value) { + throw new Error( + `${name} was changed from Array to Set (writing to Array property 'length' is not possible)` + ); + } + }); + set[Symbol.isConcatSpreadable] = true; +}; - /** - * @param {CodeGenerationContext} context context for code generation - * @returns {CodeGenerationResult} result - */ - codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) { - const runtimeRequirements = new Set([RuntimeGlobals.initializeSharing]); - const code = `register(${JSON.stringify(this._name)}, ${JSON.stringify( - this._version || "0" - )}, ${ - this._eager - ? runtimeTemplate.syncModuleFactory({ - dependency: this.dependencies[0], - chunkGraph, - request: this._request, - runtimeRequirements - }) - : runtimeTemplate.asyncModuleFactory({ - block: this.blocks[0], - chunkGraph, - request: this._request, - runtimeRequirements - }) - }${this._eager ? ", 1" : ""});`; - const sources = new Map(); - const data = new Map(); - data.set("share-init", [ - { - shareScope: this._shareScope, - initStage: 10, - init: code +exports.createArrayToSetDeprecationSet = name => { + let initialized = false; + class SetDeprecatedArray extends Set { + constructor(items) { + super(items); + if (!initialized) { + initialized = true; + exports.arrayToSetDeprecation(SetDeprecatedArray.prototype, name); } - ]); - return { sources, data, runtimeRequirements }; + } } + return SetDeprecatedArray; +}; - serialize(context) { - const { write } = context; - write(this._shareScope); - write(this._name); - write(this._version); - write(this._request); - write(this._eager); - super.serialize(context); - } +exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => { + const message = `${name} will be frozen in future, all modifications are deprecated.${ + note && `\n${note}` + }`; + return new Proxy(obj, { + set: util.deprecate( + (target, property, value, receiver) => + Reflect.set(target, property, value, receiver), + message, + code + ), + defineProperty: util.deprecate( + (target, property, descriptor) => + Reflect.defineProperty(target, property, descriptor), + message, + code + ), + deleteProperty: util.deprecate( + (target, property) => Reflect.deleteProperty(target, property), + message, + code + ), + setPrototypeOf: util.deprecate( + (target, proto) => Reflect.setPrototypeOf(target, proto), + message, + code + ) + }); +}; - static deserialize(context) { - const { read } = context; - const obj = new ProvideSharedModule(read(), read(), read(), read(), read()); - obj.deserialize(context); - return obj; +/** + * @template T + * @param {T} obj object + * @param {string} message deprecation message + * @param {string} code deprecation code + * @returns {T} object with property access deprecated + */ +const deprecateAllProperties = (obj, message, code) => { + const newObj = {}; + const descriptors = Object.getOwnPropertyDescriptors(obj); + for (const name of Object.keys(descriptors)) { + const descriptor = descriptors[name]; + if (typeof descriptor.value === "function") { + Object.defineProperty(newObj, name, { + ...descriptor, + value: util.deprecate(descriptor.value, message, code) + }); + } else if (descriptor.get || descriptor.set) { + Object.defineProperty(newObj, name, { + ...descriptor, + get: descriptor.get && util.deprecate(descriptor.get, message, code), + set: descriptor.set && util.deprecate(descriptor.set, message, code) + }); + } else { + let value = descriptor.value; + Object.defineProperty(newObj, name, { + configurable: descriptor.configurable, + enumerable: descriptor.enumerable, + get: util.deprecate(() => value, message, code), + set: descriptor.writable + ? util.deprecate(v => (value = v), message, code) + : undefined + }); + } } -} - -makeSerializable( - ProvideSharedModule, - "webpack/lib/sharing/ProvideSharedModule" -); + return /** @type {T} */ (newObj); +}; +exports.deprecateAllProperties = deprecateAllProperties; -module.exports = ProvideSharedModule; +/** + * @template T + * @param {T} fakeHook fake hook implementation + * @param {string=} message deprecation message (not deprecated when unset) + * @param {string=} code deprecation code (not deprecated when unset) + * @returns {FakeHook} fake hook which redirects + */ +exports.createFakeHook = (fakeHook, message, code) => { + if (message && code) { + fakeHook = deprecateAllProperties(fakeHook, message, code); + } + return Object.freeze( + Object.assign(fakeHook, { _fakeHook: /** @type {true} */ (true) }) + ); +}; /***/ }), -/***/ 39344: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 59836: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy + Author Tobias Koppers @sokra */ -const ModuleFactory = __webpack_require__(51010); -const ProvideSharedModule = __webpack_require__(50821); +// Simulations show these probabilities for a single change +// 93.1% that one group is invalidated +// 4.8% that two groups are invalidated +// 1.1% that 3 groups are invalidated +// 0.1% that 4 or more groups are invalidated +// +// And these for removing/adding 10 lexically adjacent files +// 64.5% that one group is invalidated +// 24.8% that two groups are invalidated +// 7.8% that 3 groups are invalidated +// 2.7% that 4 or more groups are invalidated +// +// And these for removing/adding 3 random files +// 0% that one group is invalidated +// 3.7% that two groups are invalidated +// 80.8% that 3 groups are invalidated +// 12.3% that 4 groups are invalidated +// 3.2% that 5 or more groups are invalidated + +/** + * + * @param {string} a key + * @param {string} b key + * @returns {number} the similarity as number + */ +const similarity = (a, b) => { + const l = Math.min(a.length, b.length); + let dist = 0; + for (let i = 0; i < l; i++) { + const ca = a.charCodeAt(i); + const cb = b.charCodeAt(i); + dist += Math.max(0, 10 - Math.abs(ca - cb)); + } + return dist; +}; + +/** + * @param {string} a key + * @param {string} b key + * @param {Set} usedNames set of already used names + * @returns {string} the common part and a single char for the difference + */ +const getName = (a, b, usedNames) => { + const l = Math.min(a.length, b.length); + let i = 0; + while (i < l) { + if (a.charCodeAt(i) !== b.charCodeAt(i)) { + i++; + break; + } + i++; + } + while (i < l) { + const name = a.slice(0, i); + const lowerName = name.toLowerCase(); + if (!usedNames.has(lowerName)) { + usedNames.add(lowerName); + return name; + } + i++; + } + // names always contain a hash, so this is always unique + // we don't need to check usedNames nor add it + return a; +}; + +/** + * @param {Record} total total size + * @param {Record} size single size + * @returns {void} + */ +const addSizeTo = (total, size) => { + for (const key of Object.keys(size)) { + total[key] = (total[key] || 0) + size[key]; + } +}; + +/** + * @param {Record} total total size + * @param {Record} size single size + * @returns {void} + */ +const subtractSizeFrom = (total, size) => { + for (const key of Object.keys(size)) { + total[key] -= size[key]; + } +}; + +/** + * @param {Iterable} nodes some nodes + * @returns {Record} total size + */ +const sumSize = nodes => { + const sum = Object.create(null); + for (const node of nodes) { + addSizeTo(sum, node.size); + } + return sum; +}; + +const isTooBig = (size, maxSize) => { + for (const key of Object.keys(size)) { + const s = size[key]; + if (s === 0) continue; + const maxSizeValue = maxSize[key]; + if (typeof maxSizeValue === "number") { + if (s > maxSizeValue) return true; + } + } + return false; +}; + +const isTooSmall = (size, minSize) => { + for (const key of Object.keys(size)) { + const s = size[key]; + if (s === 0) continue; + const minSizeValue = minSize[key]; + if (typeof minSizeValue === "number") { + if (s < minSizeValue) return true; + } + } + return false; +}; + +const getTooSmallTypes = (size, minSize) => { + const types = new Set(); + for (const key of Object.keys(size)) { + const s = size[key]; + if (s === 0) continue; + const minSizeValue = minSize[key]; + if (typeof minSizeValue === "number") { + if (s < minSizeValue) types.add(key); + } + } + return types; +}; + +const getNumberOfMatchingSizeTypes = (size, types) => { + let i = 0; + for (const key of Object.keys(size)) { + if (size[key] !== 0 && types.has(key)) i++; + } + return i; +}; + +const selectiveSizeSum = (size, types) => { + let sum = 0; + for (const key of Object.keys(size)) { + if (size[key] !== 0 && types.has(key)) sum += size[key]; + } + return sum; +}; + +/** + * @template T + */ +class Node { + /** + * @param {T} item item + * @param {string} key key + * @param {Record} size size + */ + constructor(item, key, size) { + this.item = item; + this.key = key; + this.size = size; + } +} -/** @typedef {import("../ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */ -/** @typedef {import("../ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */ -/** @typedef {import("./ProvideSharedDependency")} ProvideSharedDependency */ +/** + * @template T + */ +class Group { + /** + * @param {Node[]} nodes nodes + * @param {number[]} similarities similarities between the nodes (length = nodes.length - 1) + * @param {Record=} size size of the group + */ + constructor(nodes, similarities, size) { + this.nodes = nodes; + this.similarities = similarities; + this.size = size || sumSize(nodes); + /** @type {string} */ + this.key = undefined; + } -class ProvideSharedModuleFactory extends ModuleFactory { /** - * @param {ModuleFactoryCreateData} data data object - * @param {function(Error=, ModuleFactoryResult=): void} callback callback - * @returns {void} + * @param {function(Node): boolean} filter filter function + * @returns {Node[]} removed nodes */ - create(data, callback) { - const dep = /** @type {ProvideSharedDependency} */ (data.dependencies[0]); - callback(null, { - module: new ProvideSharedModule( - dep.shareScope, - dep.name, - dep.version, - dep.request, - dep.eager - ) - }); + popNodes(filter) { + const newNodes = []; + const newSimilarities = []; + const resultNodes = []; + let lastNode; + for (let i = 0; i < this.nodes.length; i++) { + const node = this.nodes[i]; + if (filter(node)) { + resultNodes.push(node); + } else { + if (newNodes.length > 0) { + newSimilarities.push( + lastNode === this.nodes[i - 1] + ? this.similarities[i - 1] + : similarity(lastNode.key, node.key) + ); + } + newNodes.push(node); + lastNode = node; + } + } + if (resultNodes.length === this.nodes.length) return undefined; + this.nodes = newNodes; + this.similarities = newSimilarities; + this.size = sumSize(newNodes); + return resultNodes; } } -module.exports = ProvideSharedModuleFactory; +/** + * @param {Iterable} nodes nodes + * @returns {number[]} similarities + */ +const getSimilarities = nodes => { + // calculate similarities between lexically adjacent nodes + /** @type {number[]} */ + const similarities = []; + let last = undefined; + for (const node of nodes) { + if (last !== undefined) { + similarities.push(similarity(last.key, node.key)); + } + last = node; + } + return similarities; +}; +/** + * @template T + * @typedef {Object} GroupedItems + * @property {string} key + * @property {T[]} items + * @property {Record} size + */ -/***/ }), +/** + * @template T + * @typedef {Object} Options + * @property {Record} maxSize maximum size of a group + * @property {Record} minSize minimum size of a group (preferred over maximum size) + * @property {Iterable} items a list of items + * @property {function(T): Record} getSize function to get size of an item + * @property {function(T): string} getKey function to get the key of an item + */ -/***/ 31225: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @template T + * @param {Options} options options object + * @returns {GroupedItems[]} grouped items + */ +module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { + /** @type {Group[]} */ + const result = []; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy -*/ + const nodes = Array.from( + items, + item => new Node(item, getKey(item), getSize(item)) + ); + /** @type {Node[]} */ + const initialNodes = []; + // lexically ordering of keys + nodes.sort((a, b) => { + if (a.key < b.key) return -1; + if (a.key > b.key) return 1; + return 0; + }); -const WebpackError = __webpack_require__(53799); -const { parseOptions } = __webpack_require__(3083); -const createSchemaValidation = __webpack_require__(32540); -const ProvideForSharedDependency = __webpack_require__(40017); -const ProvideSharedDependency = __webpack_require__(1798); -const ProvideSharedModuleFactory = __webpack_require__(39344); + // return nodes bigger than maxSize directly as group + // But make sure that minSize is not violated + for (const node of nodes) { + if (isTooBig(node.size, maxSize) && !isTooSmall(node.size, minSize)) { + result.push(new Group([node], [])); + } else { + initialNodes.push(node); + } + } -/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvideSharedPluginOptions} ProvideSharedPluginOptions */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compiler")} Compiler */ + if (initialNodes.length > 0) { + const initialGroup = new Group(initialNodes, getSimilarities(initialNodes)); -const validate = createSchemaValidation( - __webpack_require__(91924), - () => __webpack_require__(438), - { - name: "Provide Shared Plugin", - baseDataPath: "options" - } -); + const removeProblematicNodes = (group, consideredSize = group.size) => { + const problemTypes = getTooSmallTypes(consideredSize, minSize); + if (problemTypes.size > 0) { + // We hit an edge case where the working set is already smaller than minSize + // We merge problematic nodes with the smallest result node to keep minSize intact + const problemNodes = group.popNodes( + n => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0 + ); + if (problemNodes === undefined) return false; + // Only merge it with result nodes that have the problematic size type + const possibleResultGroups = result.filter( + n => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0 + ); + if (possibleResultGroups.length > 0) { + const bestGroup = possibleResultGroups.reduce((min, group) => { + const minMatches = getNumberOfMatchingSizeTypes(min, problemTypes); + const groupMatches = getNumberOfMatchingSizeTypes( + group, + problemTypes + ); + if (minMatches !== groupMatches) + return minMatches < groupMatches ? group : min; + if ( + selectiveSizeSum(min.size, problemTypes) > + selectiveSizeSum(group.size, problemTypes) + ) + return group; + return min; + }); + for (const node of problemNodes) bestGroup.nodes.push(node); + bestGroup.nodes.sort((a, b) => { + if (a.key < b.key) return -1; + if (a.key > b.key) return 1; + return 0; + }); + } else { + // There are no other nodes with the same size types + // We create a new group and have to accept that it's smaller than minSize + result.push(new Group(problemNodes, null)); + } + return true; + } else { + return false; + } + }; -/** - * @typedef {Object} ProvideOptions - * @property {string} shareKey - * @property {string} shareScope - * @property {string | undefined | false} version - * @property {boolean} eager - */ + if (initialGroup.nodes.length > 0) { + const queue = [initialGroup]; -/** @typedef {Map} ResolvedProvideMap */ + while (queue.length) { + const group = queue.pop(); + // only groups bigger than maxSize need to be splitted + if (!isTooBig(group.size, maxSize)) { + result.push(group); + continue; + } + // If the group is already too small + // we try to work only with the unproblematic nodes + if (removeProblematicNodes(group)) { + // This changed something, so we try this group again + queue.push(group); + continue; + } -class ProvideSharedPlugin { - /** - * @param {ProvideSharedPluginOptions} options options - */ - constructor(options) { - validate(options); + // find unsplittable area from left and right + // going minSize from left and right + // at least one node need to be included otherwise we get stuck + let left = 1; + let leftSize = Object.create(null); + addSizeTo(leftSize, group.nodes[0].size); + while (left < group.nodes.length && isTooSmall(leftSize, minSize)) { + addSizeTo(leftSize, group.nodes[left].size); + left++; + } + let right = group.nodes.length - 2; + let rightSize = Object.create(null); + addSizeTo(rightSize, group.nodes[group.nodes.length - 1].size); + while (right >= 0 && isTooSmall(rightSize, minSize)) { + addSizeTo(rightSize, group.nodes[right].size); + right--; + } - /** @type {[string, ProvideOptions][]} */ - this._provides = parseOptions( - options.provides, - item => { - if (Array.isArray(item)) - throw new Error("Unexpected array of provides"); - /** @type {ProvideOptions} */ - const result = { - shareKey: item, - version: undefined, - shareScope: options.shareScope || "default", - eager: false - }; - return result; - }, - item => ({ - shareKey: item.shareKey, - version: item.version, - shareScope: item.shareScope || options.shareScope || "default", - eager: !!item.eager - }) - ); - this._provides.sort(([a], [b]) => { - if (a < b) return -1; - if (b < a) return 1; - return 0; - }); - } + // left v v right + // [ O O O ] O O O [ O O O ] + // ^^^^^^^^^ leftSize + // rightSize ^^^^^^^^^ + // leftSize > minSize + // rightSize > minSize - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - /** @type {WeakMap} */ - const compilationData = new WeakMap(); + // Perfect split: [ O O O ] [ O O O ] + // right === left - 1 - compiler.hooks.compilation.tap( - "ProvideSharedPlugin", - (compilation, { normalModuleFactory }) => { - /** @type {ResolvedProvideMap} */ - const resolvedProvideMap = new Map(); - /** @type {Map} */ - const matchProvides = new Map(); - /** @type {Map} */ - const prefixMatchProvides = new Map(); - for (const [request, config] of this._provides) { - if (/^(\/|[A-Za-z]:\\|\\\\|\.\.?(\/|$))/.test(request)) { - // relative request - resolvedProvideMap.set(request, { - config, - version: config.version - }); - } else if (/^(\/|[A-Za-z]:\\|\\\\)/.test(request)) { - // absolute path - resolvedProvideMap.set(request, { - config, - version: config.version - }); - } else if (request.endsWith("/")) { - // module request prefix - prefixMatchProvides.set(request, config); + if (left - 1 > right) { + // We try to remove some problematic nodes to "fix" that + let prevSize; + if (right < group.nodes.length - left) { + subtractSizeFrom(rightSize, group.nodes[right + 1].size); + prevSize = rightSize; } else { - // module request - matchProvides.set(request, config); + subtractSizeFrom(leftSize, group.nodes[left - 1].size); + prevSize = leftSize; } + if (removeProblematicNodes(group, prevSize)) { + // This changed something, so we try this group again + queue.push(group); + continue; + } + // can't split group while holding minSize + // because minSize is preferred of maxSize we return + // the problematic nodes as result here even while it's too big + // To avoid this make sure maxSize > minSize * 3 + result.push(group); + continue; } - compilationData.set(compilation, resolvedProvideMap); - const provideSharedModule = ( - key, - config, - resource, - resourceResolveData - ) => { - let version = config.version; - if (version === undefined) { - let details = ""; - if (!resourceResolveData) { - details = `No resolve data provided from resolver.`; - } else { - const descriptionFileData = - resourceResolveData.descriptionFileData; - if (!descriptionFileData) { - details = - "No description file (usually package.json) found. Add description file with name and version, or manually specify version in shared config."; - } else if (!descriptionFileData.version) { - details = - "No version in description file (usually package.json). Add version to description file, or manually specify version in shared config."; - } else { - version = descriptionFileData.version; - } - } - if (!version) { - const error = new WebpackError( - `No version specified and unable to automatically determine one. ${details}` - ); - error.file = `shared module ${key} -> ${resource}`; - compilation.warnings.push(error); + if (left <= right) { + // when there is a area between left and right + // we look for best split point + // we split at the minimum similarity + // here key space is separated the most + // But we also need to make sure to not create too small groups + let best = -1; + let bestSimilarity = Infinity; + let pos = left; + let rightSize = sumSize(group.nodes.slice(pos)); + + // pos v v right + // [ O O O ] O O O [ O O O ] + // ^^^^^^^^^ leftSize + // rightSize ^^^^^^^^^^^^^^^ + + while (pos <= right + 1) { + const similarity = group.similarities[pos - 1]; + if ( + similarity < bestSimilarity && + !isTooSmall(leftSize, minSize) && + !isTooSmall(rightSize, minSize) + ) { + best = pos; + bestSimilarity = similarity; } + addSizeTo(leftSize, group.nodes[pos].size); + subtractSizeFrom(rightSize, group.nodes[pos].size); + pos++; } - resolvedProvideMap.set(resource, { - config, - version - }); - }; - normalModuleFactory.hooks.module.tap( - "ProvideSharedPlugin", - (module, { resource, resourceResolveData }, resolveData) => { - if (resolvedProvideMap.has(resource)) { - return module; - } - const { request } = resolveData; - { - const config = matchProvides.get(request); - if (config !== undefined) { - provideSharedModule( - request, - config, - resource, - resourceResolveData - ); - resolveData.cacheable = false; - } - } - for (const [prefix, config] of prefixMatchProvides) { - if (request.startsWith(prefix)) { - const remainder = request.slice(prefix.length); - provideSharedModule( - resource, - { - ...config, - shareKey: config.shareKey + remainder - }, - resource, - resourceResolveData - ); - resolveData.cacheable = false; - } - } - return module; + if (best < 0) { + // This can't happen + // but if that assumption is wrong + // fallback to a big group + result.push(group); + continue; } - ); - } - ); - compiler.hooks.finishMake.tapPromise("ProvideSharedPlugin", compilation => { - const resolvedProvideMap = compilationData.get(compilation); - if (!resolvedProvideMap) return Promise.resolve(); - return Promise.all( - Array.from( - resolvedProvideMap, - ([resource, { config, version }]) => - new Promise((resolve, reject) => { - compilation.addInclude( - compiler.context, - new ProvideSharedDependency( - config.shareScope, - config.shareKey, - version || false, - resource, - config.eager - ), - { - name: undefined - }, - err => { - if (err) return reject(err); - resolve(); - } - ); - }) - ) - ).then(() => {}); - }); + left = best; + right = best - 1; + } - compiler.hooks.compilation.tap( - "ProvideSharedPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - ProvideForSharedDependency, - normalModuleFactory - ); + // create two new groups for left and right area + // and queue them up + const rightNodes = [group.nodes[right + 1]]; + /** @type {number[]} */ + const rightSimilarities = []; + for (let i = right + 2; i < group.nodes.length; i++) { + rightSimilarities.push(group.similarities[i - 1]); + rightNodes.push(group.nodes[i]); + } + queue.push(new Group(rightNodes, rightSimilarities)); - compilation.dependencyFactories.set( - ProvideSharedDependency, - new ProvideSharedModuleFactory() - ); + const leftNodes = [group.nodes[0]]; + /** @type {number[]} */ + const leftSimilarities = []; + for (let i = 1; i < left; i++) { + leftSimilarities.push(group.similarities[i - 1]); + leftNodes.push(group.nodes[i]); + } + queue.push(new Group(leftNodes, leftSimilarities)); } - ); + } } -} -module.exports = ProvideSharedPlugin; + // lexically ordering + result.sort((a, b) => { + if (a.nodes[0].key < b.nodes[0].key) return -1; + if (a.nodes[0].key > b.nodes[0].key) return 1; + return 0; + }); + + // give every group a name + const usedNames = new Set(); + for (let i = 0; i < result.length; i++) { + const group = result[i]; + if (group.nodes.length === 1) { + group.key = group.nodes[0].key; + } else { + const first = group.nodes[0]; + const last = group.nodes[group.nodes.length - 1]; + const name = getName(first.key, last.key, usedNames); + group.key = name; + } + } + + // return the results + return result.map(group => { + /** @type {GroupedItems} */ + return { + key: group.key, + items: group.nodes.map(node => node.item), + size: group.size + }; + }); +}; /***/ }), -/***/ 26335: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 11850: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy + Author Sam Chen @chenxsan */ -const { parseOptions } = __webpack_require__(3083); -const ConsumeSharedPlugin = __webpack_require__(15046); -const ProvideSharedPlugin = __webpack_require__(31225); -const { isRequiredVersion } = __webpack_require__(84379); - -/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumeSharedPluginOptions} ConsumeSharedPluginOptions */ -/** @typedef {import("../../declarations/plugins/sharing/ConsumeSharedPlugin").ConsumesConfig} ConsumesConfig */ -/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvideSharedPluginOptions} ProvideSharedPluginOptions */ -/** @typedef {import("../../declarations/plugins/sharing/ProvideSharedPlugin").ProvidesConfig} ProvidesConfig */ -/** @typedef {import("../../declarations/plugins/sharing/SharePlugin").SharePluginOptions} SharePluginOptions */ -/** @typedef {import("../../declarations/plugins/sharing/SharePlugin").SharedConfig} SharedConfig */ -/** @typedef {import("../Compiler")} Compiler */ - -class SharePlugin { - /** - * @param {SharePluginOptions} options options - */ - constructor(options) { - /** @type {[string, SharedConfig][]} */ - const sharedOptions = parseOptions( - options.shared, - (item, key) => { - if (typeof item !== "string") - throw new Error("Unexpected array in shared"); - /** @type {SharedConfig} */ - const config = - item === key || !isRequiredVersion(item) - ? { - import: item - } - : { - import: key, - requiredVersion: item - }; - return config; - }, - item => item - ); - /** @type {Record[]} */ - const consumes = sharedOptions.map(([key, options]) => ({ - [key]: { - import: options.import, - shareKey: options.shareKey || key, - shareScope: options.shareScope, - requiredVersion: options.requiredVersion, - strictVersion: options.strictVersion, - singleton: options.singleton, - packageName: options.packageName, - eager: options.eager - } - })); - /** @type {Record[]} */ - const provides = sharedOptions - .filter(([, options]) => options.import !== false) - .map(([key, options]) => ({ - [options.import || key]: { - shareKey: options.shareKey || key, - shareScope: options.shareScope, - version: options.version, - eager: options.eager - } - })); - this._shareScope = options.shareScope; - this._consumes = consumes; - this._provides = provides; - } - - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - new ConsumeSharedPlugin({ - shareScope: this._shareScope, - consumes: this._consumes - }).apply(compiler); - new ProvideSharedPlugin({ - shareScope: this._shareScope, - provides: this._provides - }).apply(compiler); +/** + * @param {string} urlAndGlobal the script request + * @returns {string[]} script url and its global variable + */ +module.exports = function extractUrlAndGlobal(urlAndGlobal) { + const index = urlAndGlobal.indexOf("@"); + if (index <= 0 || index === urlAndGlobal.length - 1) { + throw new Error(`Invalid request "${urlAndGlobal}"`); } -} - -module.exports = SharePlugin; + return [urlAndGlobal.substring(index + 1), urlAndGlobal.substring(0, index)]; +}; /***/ }), -/***/ 96066: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 6261: +/***/ (function(module) { "use strict"; /* @@ -123242,343 +125538,234 @@ module.exports = SharePlugin; -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); -const { - compareModulesByIdentifier, - compareStrings -} = __webpack_require__(29579); - -class ShareRuntimeModule extends RuntimeModule { - constructor() { - super("sharing"); - } +const NO_MARKER = 0; +const IN_PROGRESS_MARKER = 1; +const DONE_MARKER = 2; +const DONE_MAYBE_ROOT_CYCLE_MARKER = 3; +const DONE_AND_ROOT_MARKER = 4; +/** + * @template T + */ +class Node { /** - * @returns {string} runtime code + * @param {T} item the value of the node */ - generate() { - const { compilation, chunkGraph } = this; - const { - runtimeTemplate, - codeGenerationResults, - outputOptions: { uniqueName } - } = compilation; - /** @type {Map>>} */ - const initCodePerScope = new Map(); - for (const chunk of this.chunk.getAllReferencedChunks()) { - const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType( - chunk, - "share-init", - compareModulesByIdentifier - ); - if (!modules) continue; - for (const m of modules) { - const data = codeGenerationResults.getData( - m, - chunk.runtime, - "share-init" - ); - if (!data) continue; - for (const item of data) { - const { shareScope, initStage, init } = item; - let stages = initCodePerScope.get(shareScope); - if (stages === undefined) { - initCodePerScope.set(shareScope, (stages = new Map())); - } - let list = stages.get(initStage || 0); - if (list === undefined) { - stages.set(initStage || 0, (list = new Set())); - } - list.add(init); - } - } - } - return Template.asString([ - `${RuntimeGlobals.shareScopeMap} = {};`, - "var initPromises = {};", - "var initTokens = {};", - `${RuntimeGlobals.initializeSharing} = ${runtimeTemplate.basicFunction( - "name, initScope", - [ - "if(!initScope) initScope = [];", - "// handling circular init calls", - "var initToken = initTokens[name];", - "if(!initToken) initToken = initTokens[name] = {};", - "if(initScope.indexOf(initToken) >= 0) return;", - "initScope.push(initToken);", - "// only runs once", - "if(initPromises[name]) return initPromises[name];", - "// creates a new share scope if needed", - `if(!${RuntimeGlobals.hasOwnProperty}(${RuntimeGlobals.shareScopeMap}, name)) ${RuntimeGlobals.shareScopeMap}[name] = {};`, - "// runs all init snippets from all modules reachable", - `var scope = ${RuntimeGlobals.shareScopeMap}[name];`, - `var warn = ${runtimeTemplate.returningFunction( - 'typeof console !== "undefined" && console.warn && console.warn(msg)', - "msg" - )};`, - `var uniqueName = ${JSON.stringify(uniqueName || undefined)};`, - `var register = ${runtimeTemplate.basicFunction( - "name, version, factory, eager", - [ - "var versions = scope[name] = scope[name] || {};", - "var activeVersion = versions[version];", - "if(!activeVersion || (!activeVersion.loaded && (!eager != !activeVersion.eager ? eager : uniqueName > activeVersion.from))) versions[version] = { get: factory, from: uniqueName, eager: !!eager };" - ] - )};`, - `var initExternal = ${runtimeTemplate.basicFunction("id", [ - `var handleError = ${runtimeTemplate.expressionFunction( - 'warn("Initialization of sharing external failed: " + err)', - "err" - )};`, - "try {", - Template.indent([ - "var module = __webpack_require__(id);", - "if(!module) return;", - `var initFn = ${runtimeTemplate.returningFunction( - `module && module.init && module.init(${RuntimeGlobals.shareScopeMap}[name], initScope)`, - "module" - )}`, - "if(module.then) return promises.push(module.then(initFn, handleError));", - "var initResult = initFn(module);", - "if(initResult && initResult.then) return promises.push(initResult['catch'](handleError));" - ]), - "} catch(err) { handleError(err); }" - ])}`, - "var promises = [];", - "switch(name) {", - ...Array.from(initCodePerScope) - .sort(([a], [b]) => compareStrings(a, b)) - .map(([name, stages]) => - Template.indent([ - `case ${JSON.stringify(name)}: {`, - Template.indent( - Array.from(stages) - .sort(([a], [b]) => a - b) - .map(([, initCode]) => - Template.asString(Array.from(initCode)) - ) - ), - "}", - "break;" - ]) - ), - "}", - "if(!promises.length) return initPromises[name] = 1;", - `return initPromises[name] = Promise.all(promises).then(${runtimeTemplate.returningFunction( - "initPromises[name] = 1" - )});` - ] - )};` - ]); + constructor(item) { + this.item = item; + /** @type {Set>} */ + this.dependencies = new Set(); + this.marker = NO_MARKER; + /** @type {Cycle | undefined} */ + this.cycle = undefined; + this.incoming = 0; } } -module.exports = ShareRuntimeModule; - +/** + * @template T + */ +class Cycle { + constructor() { + /** @type {Set>} */ + this.nodes = new Set(); + } +} -/***/ }), +/** + * @template T + * @typedef {Object} StackEntry + * @property {Node} node + * @property {Node[]} openEdges + */ -/***/ 3591: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/** + * @template T + * @param {Iterable} items list of items + * @param {function(T): Iterable} getDependencies function to get dependencies of an item (items that are not in list are ignored) + * @returns {Iterable} graph roots of the items + */ +module.exports = (items, getDependencies) => { + /** @type {Map>} */ + const itemToNode = new Map(); + for (const item of items) { + const node = new Node(item); + itemToNode.set(item, node); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // early exit when there is only a single item + if (itemToNode.size <= 1) return items; + // grab all the dependencies + for (const node of itemToNode.values()) { + for (const dep of getDependencies(node.item)) { + const depNode = itemToNode.get(dep); + if (depNode !== undefined) { + node.dependencies.add(depNode); + } + } + } + // Set of current root modules + // items will be removed if a new reference to it has been found + /** @type {Set>} */ + const roots = new Set(); -const ModuleNotFoundError = __webpack_require__(32882); -const LazySet = __webpack_require__(38938); + // Set of current cycles without references to it + // cycles will be removed if a new reference to it has been found + // that is not part of the cycle + /** @type {Set>} */ + const rootCycles = new Set(); -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */ + // For all non-marked nodes + for (const selectedNode of itemToNode.values()) { + if (selectedNode.marker === NO_MARKER) { + // deep-walk all referenced modules + // in a non-recursive way -/** - * @template T - * @typedef {Object} MatchedConfigs - * @property {Map} resolved - * @property {Map} unresolved - * @property {Map} prefixed - */ + // start by entering the selected node + selectedNode.marker = IN_PROGRESS_MARKER; -/** @type {ResolveOptionsWithDependencyType} */ -const RESOLVE_OPTIONS = { dependencyType: "esm" }; + // keep a stack to avoid recursive walk + /** @type {StackEntry[]} */ + const stack = [ + { + node: selectedNode, + openEdges: Array.from(selectedNode.dependencies) + } + ]; -/** - * @template T - * @param {Compilation} compilation the compilation - * @param {[string, T][]} configs to be processed configs - * @returns {Promise>} resolved matchers - */ -exports.resolveMatchedConfigs = (compilation, configs) => { - /** @type {Map} */ - const resolved = new Map(); - /** @type {Map} */ - const unresolved = new Map(); - /** @type {Map} */ - const prefixed = new Map(); - const resolveContext = { - /** @type {LazySet} */ - fileDependencies: new LazySet(), - /** @type {LazySet} */ - contextDependencies: new LazySet(), - /** @type {LazySet} */ - missingDependencies: new LazySet() - }; - const resolver = compilation.resolverFactory.get("normal", RESOLVE_OPTIONS); - const context = compilation.compiler.context; + // process the top item until stack is empty + while (stack.length > 0) { + const topOfStack = stack[stack.length - 1]; - return Promise.all( - configs.map(([request, config]) => { - if (/^\.\.?(\/|$)/.test(request)) { - // relative request - return new Promise(resolve => { - resolver.resolve( - {}, - context, - request, - resolveContext, - (err, result) => { - if (err || result === false) { - err = err || new Error(`Can't resolve ${request}`); - compilation.errors.push( - new ModuleNotFoundError(null, err, { - name: `shared module ${request}` - }) - ); - return resolve(); + // Are there still edges unprocessed in the current node? + if (topOfStack.openEdges.length > 0) { + // Process one dependency + const dependency = topOfStack.openEdges.pop(); + switch (dependency.marker) { + case NO_MARKER: + // dependency has not be visited yet + // mark it as in-progress and recurse + stack.push({ + node: dependency, + openEdges: Array.from(dependency.dependencies) + }); + dependency.marker = IN_PROGRESS_MARKER; + break; + case IN_PROGRESS_MARKER: { + // It's a in-progress cycle + let cycle = dependency.cycle; + if (!cycle) { + cycle = new Cycle(); + cycle.nodes.add(dependency); + dependency.cycle = cycle; } - resolved.set(result, config); - resolve(); + // set cycle property for each node in the cycle + // if nodes are already part of a cycle + // we merge the cycles to a shared cycle + for ( + let i = stack.length - 1; + stack[i].node !== dependency; + i-- + ) { + const node = stack[i].node; + if (node.cycle) { + if (node.cycle !== cycle) { + // merge cycles + for (const cycleNode of node.cycle.nodes) { + cycleNode.cycle = cycle; + cycle.nodes.add(cycleNode); + } + } + } else { + node.cycle = cycle; + cycle.nodes.add(node); + } + } + // don't recurse into dependencies + // these are already on the stack + break; } - ); - }); - } else if (/^(\/|[A-Za-z]:\\|\\\\)/.test(request)) { - // absolute path - resolved.set(request, config); - } else if (request.endsWith("/")) { - // module request prefix - prefixed.set(request, config); + case DONE_AND_ROOT_MARKER: + // This node has be visited yet and is currently a root node + // But as this is a new reference to the node + // it's not really a root + // so we have to convert it to a normal node + dependency.marker = DONE_MARKER; + roots.delete(dependency); + break; + case DONE_MAYBE_ROOT_CYCLE_MARKER: + // This node has be visited yet and + // is maybe currently part of a completed root cycle + // we found a new reference to the cycle + // so it's not really a root cycle + // remove the cycle from the root cycles + // and convert it to a normal node + rootCycles.delete(dependency.cycle); + dependency.marker = DONE_MARKER; + break; + // DONE_MARKER: nothing to do, don't recurse into dependencies + } + } else { + // All dependencies of the current node has been visited + // we leave the node + stack.pop(); + topOfStack.node.marker = DONE_MARKER; + } + } + const cycle = selectedNode.cycle; + if (cycle) { + for (const node of cycle.nodes) { + node.marker = DONE_MAYBE_ROOT_CYCLE_MARKER; + } + rootCycles.add(cycle); } else { - // module request - unresolved.set(request, config); + selectedNode.marker = DONE_AND_ROOT_MARKER; + roots.add(selectedNode); } - }) - ).then(() => { - compilation.contextDependencies.addAll(resolveContext.contextDependencies); - compilation.fileDependencies.addAll(resolveContext.fileDependencies); - compilation.missingDependencies.addAll(resolveContext.missingDependencies); - return { resolved, unresolved, prefixed }; - }); -}; - - -/***/ }), - -/***/ 84379: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -const { join, dirname, readJson } = __webpack_require__(17139); - -/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */ - -/** - * @param {string} str maybe required version - * @returns {boolean} true, if it looks like a version - */ -exports.isRequiredVersion = str => { - return /^([\d^=v<>~]|[*xX]$)/.test(str); -}; - -/** - * - * @param {InputFileSystem} fs file system - * @param {string} directory directory to start looking into - * @param {string[]} descriptionFiles possible description filenames - * @param {function((Error | null)=, {data: object, path: string}=): void} callback callback - */ -const getDescriptionFile = (fs, directory, descriptionFiles, callback) => { - let i = 0; - const tryLoadCurrent = () => { - if (i >= descriptionFiles.length) { - const parentDirectory = dirname(fs, directory); - if (!parentDirectory || parentDirectory === directory) return callback(); - return getDescriptionFile( - fs, - parentDirectory, - descriptionFiles, - callback - ); } - const filePath = join(fs, directory, descriptionFiles[i]); - readJson(fs, filePath, (err, data) => { - if (err) { - if ("code" in err && err.code === "ENOENT") { - i++; - return tryLoadCurrent(); + } + + // Extract roots from root cycles + // We take the nodes with most incoming edges + // inside of the cycle + for (const cycle of rootCycles) { + let max = 0; + /** @type {Set>} */ + const cycleRoots = new Set(); + const nodes = cycle.nodes; + for (const node of nodes) { + for (const dep of node.dependencies) { + if (nodes.has(dep)) { + dep.incoming++; + if (dep.incoming < max) continue; + if (dep.incoming > max) { + cycleRoots.clear(); + max = dep.incoming; + } + cycleRoots.add(dep); } - return callback(err); } - if (!data || typeof data !== "object" || Array.isArray(data)) { - return callback( - new Error(`Description file ${filePath} is not an object`) - ); - } - callback(null, { data, path: filePath }); - }); - }; - tryLoadCurrent(); -}; -exports.getDescriptionFile = getDescriptionFile; - -exports.getRequiredVersionFromDescriptionFile = (data, packageName) => { - if ( - data.optionalDependencies && - typeof data.optionalDependencies === "object" && - packageName in data.optionalDependencies - ) { - return data.optionalDependencies[packageName]; - } - if ( - data.dependencies && - typeof data.dependencies === "object" && - packageName in data.dependencies - ) { - return data.dependencies[packageName]; - } - if ( - data.peerDependencies && - typeof data.peerDependencies === "object" && - packageName in data.peerDependencies - ) { - return data.peerDependencies[packageName]; + } + for (const cycleRoot of cycleRoots) { + roots.add(cycleRoot); + } } - if ( - data.devDependencies && - typeof data.devDependencies === "object" && - packageName in data.devDependencies - ) { - return data.devDependencies[packageName]; + + // When roots were found, return them + if (roots.size > 0) { + return Array.from(roots, r => r.item); + } else { + throw new Error("Implementation of findGraphRoots is broken"); } }; /***/ }), -/***/ 71760: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 17139: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -123588,2403 +125775,1357 @@ exports.getRequiredVersionFromDescriptionFile = (data, packageName) => { -const util = __webpack_require__(73837); -const ModuleDependency = __webpack_require__(80321); -const formatLocation = __webpack_require__(16734); -const { LogType } = __webpack_require__(32597); -const AggressiveSplittingPlugin = __webpack_require__(15543); -const SizeLimitsPlugin = __webpack_require__(32557); -const { countIterable } = __webpack_require__(39104); -const { - compareLocations, - compareChunksById, - compareNumbers, - compareIds, - concatComparators, - compareSelect, - compareModulesByIdentifier -} = __webpack_require__(29579); -const { makePathsRelative, parseResource } = __webpack_require__(82186); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../ChunkGroup").OriginRecord} OriginRecord */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compilation").Asset} Asset */ -/** @typedef {import("../Compilation").AssetInfo} AssetInfo */ -/** @typedef {import("../Compilation").NormalizedStatsOptions} NormalizedStatsOptions */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */ -/** @typedef {import("../ModuleProfile")} ModuleProfile */ -/** @typedef {import("../RequestShortener")} RequestShortener */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @template T @typedef {import("../util/comparators").Comparator} Comparator */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -/** @typedef {import("../util/smartGrouping").GroupConfig} GroupConfig */ -/** @typedef {import("./StatsFactory")} StatsFactory */ -/** @typedef {import("./StatsFactory").StatsFactoryContext} StatsFactoryContext */ - -/** @typedef {KnownStatsCompilation & Record} StatsCompilation */ -/** - * @typedef {Object} KnownStatsCompilation - * @property {any=} env - * @property {string=} name - * @property {string=} hash - * @property {string=} version - * @property {number=} time - * @property {number=} builtAt - * @property {boolean=} needAdditionalPass - * @property {string=} publicPath - * @property {string=} outputPath - * @property {Record=} assetsByChunkName - * @property {StatsAsset[]=} assets - * @property {number=} filteredAssets - * @property {StatsChunk[]=} chunks - * @property {StatsModule[]=} modules - * @property {number=} filteredModules - * @property {Record=} entrypoints - * @property {Record=} namedChunkGroups - * @property {StatsError[]=} errors - * @property {number=} errorsCount - * @property {StatsError[]=} warnings - * @property {number=} warningsCount - * @property {StatsCompilation[]=} children - * @property {Record=} logging - */ - -/** @typedef {KnownStatsLogging & Record} StatsLogging */ -/** - * @typedef {Object} KnownStatsLogging - * @property {StatsLoggingEntry[]} entries - * @property {number} filteredEntries - * @property {boolean} debug - */ - -/** @typedef {KnownStatsLoggingEntry & Record} StatsLoggingEntry */ -/** - * @typedef {Object} KnownStatsLoggingEntry - * @property {string} type - * @property {string} message - * @property {string[]=} trace - * @property {StatsLoggingEntry[]=} children - * @property {any[]=} args - * @property {number=} time - */ - -/** @typedef {KnownStatsAsset & Record} StatsAsset */ -/** - * @typedef {Object} KnownStatsAsset - * @property {string} type - * @property {string} name - * @property {AssetInfo} info - * @property {number} size - * @property {boolean} emitted - * @property {boolean} comparedForEmit - * @property {boolean} cached - * @property {StatsAsset[]=} related - * @property {(string|number)[]=} chunkNames - * @property {(string|number)[]=} chunkIdHints - * @property {(string|number)[]=} chunks - * @property {(string|number)[]=} auxiliaryChunkNames - * @property {(string|number)[]=} auxiliaryChunks - * @property {(string|number)[]=} auxiliaryChunkIdHints - * @property {number=} filteredRelated - * @property {boolean=} isOverSizeLimit - */ - -/** @typedef {KnownStatsChunkGroup & Record} StatsChunkGroup */ -/** - * @typedef {Object} KnownStatsChunkGroup - * @property {string=} name - * @property {(string|number)[]=} chunks - * @property {({ name: string, size?: number })[]=} assets - * @property {number=} filteredAssets - * @property {number=} assetsSize - * @property {({ name: string, size?: number })[]=} auxiliaryAssets - * @property {number=} filteredAuxiliaryAssets - * @property {number=} auxiliaryAssetsSize - * @property {{ [x: string]: StatsChunkGroup[] }=} children - * @property {{ [x: string]: string[] }=} childAssets - * @property {boolean=} isOverSizeLimit - */ - -/** @typedef {KnownStatsModule & Record} StatsModule */ -/** - * @typedef {Object} KnownStatsModule - * @property {string=} type - * @property {string=} moduleType - * @property {string=} layer - * @property {string=} identifier - * @property {string=} name - * @property {string=} nameForCondition - * @property {number=} index - * @property {number=} preOrderIndex - * @property {number=} index2 - * @property {number=} postOrderIndex - * @property {number=} size - * @property {{[x: string]: number}=} sizes - * @property {boolean=} cacheable - * @property {boolean=} built - * @property {boolean=} codeGenerated - * @property {boolean=} buildTimeExecuted - * @property {boolean=} cached - * @property {boolean=} optional - * @property {boolean=} orphan - * @property {string|number=} id - * @property {string|number=} issuerId - * @property {(string|number)[]=} chunks - * @property {(string|number)[]=} assets - * @property {boolean=} dependent - * @property {string=} issuer - * @property {string=} issuerName - * @property {StatsModuleIssuer[]=} issuerPath - * @property {boolean=} failed - * @property {number=} errors - * @property {number=} warnings - * @property {StatsProfile=} profile - * @property {StatsModuleReason[]=} reasons - * @property {(boolean | string[])=} usedExports - * @property {string[]=} providedExports - * @property {string[]=} optimizationBailout - * @property {number=} depth - * @property {StatsModule[]=} modules - * @property {number=} filteredModules - * @property {ReturnType=} source - */ - -/** @typedef {KnownStatsProfile & Record} StatsProfile */ -/** - * @typedef {Object} KnownStatsProfile - * @property {number} total - * @property {number} resolving - * @property {number} restoring - * @property {number} building - * @property {number} integration - * @property {number} storing - * @property {number} additionalResolving - * @property {number} additionalIntegration - * @property {number} factory - * @property {number} dependencies - */ +const path = __webpack_require__(71017); -/** @typedef {KnownStatsModuleIssuer & Record} StatsModuleIssuer */ -/** - * @typedef {Object} KnownStatsModuleIssuer - * @property {string=} identifier - * @property {string=} name - * @property {(string|number)=} id - * @property {StatsProfile=} profile - */ +/** @typedef {import("../../declarations/WebpackOptions").WatchOptions} WatchOptions */ +/** @typedef {import("../FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ -/** @typedef {KnownStatsModuleReason & Record} StatsModuleReason */ /** - * @typedef {Object} KnownStatsModuleReason - * @property {string=} moduleIdentifier - * @property {string=} module - * @property {string=} moduleName - * @property {string=} resolvedModuleIdentifier - * @property {string=} resolvedModule - * @property {string=} type - * @property {boolean} active - * @property {string=} explanation - * @property {string=} userRequest - * @property {string=} loc - * @property {(string|number)=} moduleId - * @property {(string|number)=} resolvedModuleId + * @typedef {Object} IStats + * @property {() => boolean} isFile + * @property {() => boolean} isDirectory + * @property {() => boolean} isBlockDevice + * @property {() => boolean} isCharacterDevice + * @property {() => boolean} isSymbolicLink + * @property {() => boolean} isFIFO + * @property {() => boolean} isSocket + * @property {number | bigint} dev + * @property {number | bigint} ino + * @property {number | bigint} mode + * @property {number | bigint} nlink + * @property {number | bigint} uid + * @property {number | bigint} gid + * @property {number | bigint} rdev + * @property {number | bigint} size + * @property {number | bigint} blksize + * @property {number | bigint} blocks + * @property {number | bigint} atimeMs + * @property {number | bigint} mtimeMs + * @property {number | bigint} ctimeMs + * @property {number | bigint} birthtimeMs + * @property {Date} atime + * @property {Date} mtime + * @property {Date} ctime + * @property {Date} birthtime */ -/** @typedef {KnownStatsChunk & Record} StatsChunk */ /** - * @typedef {Object} KnownStatsChunk - * @property {boolean} rendered - * @property {boolean} initial - * @property {boolean} entry - * @property {boolean} recorded - * @property {string=} reason - * @property {number} size - * @property {Record=} sizes - * @property {string[]=} names - * @property {string[]=} idHints - * @property {string[]=} runtime - * @property {string[]=} files - * @property {string[]=} auxiliaryFiles - * @property {string} hash - * @property {Record=} childrenByOrder - * @property {(string|number)=} id - * @property {(string|number)[]=} siblings - * @property {(string|number)[]=} parents - * @property {(string|number)[]=} children - * @property {StatsModule[]=} modules - * @property {number=} filteredModules - * @property {StatsChunkOrigin[]=} origins + * @typedef {Object} IDirent + * @property {() => boolean} isFile + * @property {() => boolean} isDirectory + * @property {() => boolean} isBlockDevice + * @property {() => boolean} isCharacterDevice + * @property {() => boolean} isSymbolicLink + * @property {() => boolean} isFIFO + * @property {() => boolean} isSocket + * @property {string | Buffer} name */ -/** @typedef {KnownStatsChunkOrigin & Record} StatsChunkOrigin */ -/** - * @typedef {Object} KnownStatsChunkOrigin - * @property {string=} module - * @property {string=} moduleIdentifier - * @property {string=} moduleName - * @property {string=} loc - * @property {string=} request - * @property {(string|number)=} moduleId - */ +/** @typedef {function((NodeJS.ErrnoException | null)=): void} Callback */ +/** @typedef {function((NodeJS.ErrnoException | null)=, Buffer=): void} BufferCallback */ +/** @typedef {function((NodeJS.ErrnoException | null)=, Buffer|string=): void} BufferOrStringCallback */ +/** @typedef {function((NodeJS.ErrnoException | null)=, (string | Buffer)[] | IDirent[]=): void} DirentArrayCallback */ +/** @typedef {function((NodeJS.ErrnoException | null)=, string=): void} StringCallback */ +/** @typedef {function((NodeJS.ErrnoException | null)=, number=): void} NumberCallback */ +/** @typedef {function((NodeJS.ErrnoException | null)=, IStats=): void} StatsCallback */ +/** @typedef {function((NodeJS.ErrnoException | Error | null)=, any=): void} ReadJsonCallback */ +/** @typedef {function((NodeJS.ErrnoException | Error | null)=, IStats|string=): void} LstatReadlinkAbsoluteCallback */ -/** @typedef {KnownStatsModuleTraceItem & Record} StatsModuleTraceItem */ /** - * @typedef {Object} KnownStatsModuleTraceItem - * @property {string=} originIdentifier - * @property {string=} originName - * @property {string=} moduleIdentifier - * @property {string=} moduleName - * @property {StatsModuleTraceDependency[]=} dependencies - * @property {(string|number)=} originId - * @property {(string|number)=} moduleId + * @typedef {Object} WatcherInfo + * @property {Set} changes get current aggregated changes that have not yet send to callback + * @property {Set} removals get current aggregated removals that have not yet send to callback + * @property {Map} fileTimeInfoEntries get info about files + * @property {Map} contextTimeInfoEntries get info about directories */ -/** @typedef {KnownStatsModuleTraceDependency & Record} StatsModuleTraceDependency */ +// TODO webpack 6 deprecate missing getInfo /** - * @typedef {Object} KnownStatsModuleTraceDependency - * @property {string=} loc + * @typedef {Object} Watcher + * @property {function(): void} close closes the watcher and all underlying file watchers + * @property {function(): void} pause closes the watcher, but keeps underlying file watchers alive until the next watch call + * @property {function(): Set=} getAggregatedChanges get current aggregated changes that have not yet send to callback + * @property {function(): Set=} getAggregatedRemovals get current aggregated removals that have not yet send to callback + * @property {function(): Map} getFileTimeInfoEntries get info about files + * @property {function(): Map} getContextTimeInfoEntries get info about directories + * @property {function(): WatcherInfo=} getInfo get info about timestamps and changes */ -/** @typedef {KnownStatsError & Record} StatsError */ /** - * @typedef {Object} KnownStatsError - * @property {string} message - * @property {string=} chunkName - * @property {boolean=} chunkEntry - * @property {boolean=} chunkInitial - * @property {string=} file - * @property {string=} moduleIdentifier - * @property {string=} moduleName - * @property {string=} loc - * @property {string|number=} chunkId - * @property {string|number=} moduleId - * @property {StatsModuleTraceItem[]=} moduleTrace - * @property {any=} details - * @property {string=} stack + * @callback WatchMethod + * @param {Iterable} files watched files + * @param {Iterable} directories watched directories + * @param {Iterable} missing watched exitance entries + * @param {number} startTime timestamp of start time + * @param {WatchOptions} options options object + * @param {function(Error=, Map, Map, Set, Set): void} callback aggregated callback + * @param {function(string, number): void} callbackUndelayed callback when the first change was detected + * @returns {Watcher} a watcher */ -/** @typedef {Asset & { type: string, related: PreprocessedAsset[] }} PreprocessedAsset */ +// TODO webpack 6 make optional methods required /** - * @template T - * @template O - * @typedef {Record void>} ExtractorsByOption + * @typedef {Object} OutputFileSystem + * @property {function(string, Buffer|string, Callback): void} writeFile + * @property {function(string, Callback): void} mkdir + * @property {function(string, DirentArrayCallback): void=} readdir + * @property {function(string, Callback): void=} rmdir + * @property {function(string, Callback): void=} unlink + * @property {function(string, StatsCallback): void} stat + * @property {function(string, StatsCallback): void=} lstat + * @property {function(string, BufferOrStringCallback): void} readFile + * @property {(function(string, string): string)=} join + * @property {(function(string, string): string)=} relative + * @property {(function(string): string)=} dirname */ /** - * @typedef {Object} SimpleExtractors - * @property {ExtractorsByOption} compilation - * @property {ExtractorsByOption} asset - * @property {ExtractorsByOption} asset$visible - * @property {ExtractorsByOption<{ name: string, chunkGroup: ChunkGroup }, StatsChunkGroup>} chunkGroup - * @property {ExtractorsByOption} module - * @property {ExtractorsByOption} module$visible - * @property {ExtractorsByOption} moduleIssuer - * @property {ExtractorsByOption} profile - * @property {ExtractorsByOption} moduleReason - * @property {ExtractorsByOption} chunk - * @property {ExtractorsByOption} chunkOrigin - * @property {ExtractorsByOption} error - * @property {ExtractorsByOption} warning - * @property {ExtractorsByOption<{ origin: Module, module: Module }, StatsModuleTraceItem>} moduleTraceItem - * @property {ExtractorsByOption} moduleTraceDependency + * @typedef {Object} InputFileSystem + * @property {function(string, BufferOrStringCallback): void} readFile + * @property {(function(string, ReadJsonCallback): void)=} readJson + * @property {function(string, BufferOrStringCallback): void} readlink + * @property {function(string, DirentArrayCallback): void} readdir + * @property {function(string, StatsCallback): void} stat + * @property {function(string, StatsCallback): void=} lstat + * @property {(function(string, BufferOrStringCallback): void)=} realpath + * @property {(function(string=): void)=} purge + * @property {(function(string, string): string)=} join + * @property {(function(string, string): string)=} relative + * @property {(function(string): string)=} dirname */ /** - * @template T - * @template I - * @param {Iterable} items items to select from - * @param {function(T): Iterable} selector selector function to select values from item - * @returns {I[]} array of values + * @typedef {Object} WatchFileSystem + * @property {WatchMethod} watch */ -const uniqueArray = (items, selector) => { - /** @type {Set} */ - const set = new Set(); - for (const item of items) { - for (const i of selector(item)) { - set.add(i); - } - } - return Array.from(set); -}; /** - * @template T - * @template I - * @param {Iterable} items items to select from - * @param {function(T): Iterable} selector selector function to select values from item - * @param {Comparator} comparator comparator function - * @returns {I[]} array of values + * @typedef {Object} IntermediateFileSystemExtras + * @property {function(string): void} mkdirSync + * @property {function(string): NodeJS.WritableStream} createWriteStream + * @property {function(string, string, NumberCallback): void} open + * @property {function(number, Buffer, number, number, number, NumberCallback): void} read + * @property {function(number, Callback): void} close + * @property {function(string, string, Callback): void} rename */ -const uniqueOrderedArray = (items, selector, comparator) => { - return uniqueArray(items, selector).sort(comparator); -}; -/** @template T @template R @typedef {{ [P in keyof T]: R }} MappedValues */ +/** @typedef {InputFileSystem & OutputFileSystem & IntermediateFileSystemExtras} IntermediateFileSystem */ /** - * @template T - * @template R - * @param {T} obj object to be mapped - * @param {function(T[keyof T], keyof T): R} fn mapping function - * @returns {MappedValues} mapped object + * + * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system + * @param {string} rootPath the root path + * @param {string} targetPath the target path + * @returns {string} location of targetPath relative to rootPath */ -const mapObject = (obj, fn) => { - const newObj = Object.create(null); - for (const key of Object.keys(obj)) { - newObj[key] = fn(obj[key], /** @type {keyof T} */ (key)); +const relative = (fs, rootPath, targetPath) => { + if (fs && fs.relative) { + return fs.relative(rootPath, targetPath); + } else if (path.posix.isAbsolute(rootPath)) { + return path.posix.relative(rootPath, targetPath); + } else if (path.win32.isAbsolute(rootPath)) { + return path.win32.relative(rootPath, targetPath); + } else { + throw new Error( + `${rootPath} is neither a posix nor a windows path, and there is no 'relative' method defined in the file system` + ); } - return newObj; }; +exports.relative = relative; /** - * @param {Compilation} compilation the compilation - * @param {function(Compilation, string): any[]} getItems get items - * @returns {number} total number + * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system + * @param {string} rootPath a path + * @param {string} filename a filename + * @returns {string} the joined path */ -const countWithChildren = (compilation, getItems) => { - let count = getItems(compilation, "").length; - for (const child of compilation.children) { - count += countWithChildren(child, (c, type) => - getItems(c, `.children[].compilation${type}`) +const join = (fs, rootPath, filename) => { + if (fs && fs.join) { + return fs.join(rootPath, filename); + } else if (path.posix.isAbsolute(rootPath)) { + return path.posix.join(rootPath, filename); + } else if (path.win32.isAbsolute(rootPath)) { + return path.win32.join(rootPath, filename); + } else { + throw new Error( + `${rootPath} is neither a posix nor a windows path, and there is no 'join' method defined in the file system` ); } - return count; -}; - -/** @type {ExtractorsByOption} */ -const EXTRACT_ERROR = { - _: (object, error, context, { requestShortener }) => { - // TODO webpack 6 disallow strings in the errors/warnings list - if (typeof error === "string") { - object.message = error; - } else { - if (error.chunk) { - object.chunkName = error.chunk.name; - object.chunkEntry = error.chunk.hasRuntime(); - object.chunkInitial = error.chunk.canBeInitial(); - } - if (error.file) { - object.file = error.file; - } - if (error.module) { - object.moduleIdentifier = error.module.identifier(); - object.moduleName = error.module.readableIdentifier(requestShortener); - } - if (error.loc) { - object.loc = formatLocation(error.loc); - } - object.message = error.message; - } - }, - ids: (object, error, { compilation: { chunkGraph } }) => { - if (typeof error !== "string") { - if (error.chunk) { - object.chunkId = error.chunk.id; - } - if (error.module) { - object.moduleId = chunkGraph.getModuleId(error.module); - } - } - }, - moduleTrace: (object, error, context, options, factory) => { - if (typeof error !== "string" && error.module) { - const { - type, - compilation: { moduleGraph } - } = context; - /** @type {Set} */ - const visitedModules = new Set(); - const moduleTrace = []; - let current = error.module; - while (current) { - if (visitedModules.has(current)) break; // circular (technically impossible, but how knows) - visitedModules.add(current); - const origin = moduleGraph.getIssuer(current); - if (!origin) break; - moduleTrace.push({ origin, module: current }); - current = origin; - } - object.moduleTrace = factory.create( - `${type}.moduleTrace`, - moduleTrace, - context - ); - } - }, - errorDetails: ( - object, - error, - { type, compilation, cachedGetErrors, cachedGetWarnings }, - { errorDetails } - ) => { - if ( - typeof error !== "string" && - (errorDetails === true || - (type.endsWith(".error") && cachedGetErrors(compilation).length < 3)) - ) { - object.details = error.details; - } - }, - errorStack: (object, error) => { - if (typeof error !== "string") { - object.stack = error.stack; - } - } }; +exports.join = join; -/** @type {SimpleExtractors} */ -const SIMPLE_EXTRACTORS = { - compilation: { - _: (object, compilation, context, options) => { - if (!context.makePathsRelative) { - context.makePathsRelative = makePathsRelative.bindContextCache( - compilation.compiler.context, - compilation.compiler.root - ); - } - if (!context.cachedGetErrors) { - const map = new WeakMap(); - context.cachedGetErrors = compilation => { - return ( - map.get(compilation) || - (errors => (map.set(compilation, errors), errors))( - compilation.getErrors() - ) - ); - }; - } - if (!context.cachedGetWarnings) { - const map = new WeakMap(); - context.cachedGetWarnings = compilation => { - return ( - map.get(compilation) || - (warnings => (map.set(compilation, warnings), warnings))( - compilation.getWarnings() - ) - ); - }; - } - if (compilation.name) { - object.name = compilation.name; - } - if (compilation.needAdditionalPass) { - object.needAdditionalPass = true; - } - - const { logging, loggingDebug, loggingTrace } = options; - if (logging || (loggingDebug && loggingDebug.length > 0)) { - const util = __webpack_require__(73837); - object.logging = {}; - let acceptedTypes; - let collapsedGroups = false; - switch (logging) { - default: - acceptedTypes = new Set(); - break; - case "error": - acceptedTypes = new Set([LogType.error]); - break; - case "warn": - acceptedTypes = new Set([LogType.error, LogType.warn]); - break; - case "info": - acceptedTypes = new Set([ - LogType.error, - LogType.warn, - LogType.info - ]); - break; - case "log": - acceptedTypes = new Set([ - LogType.error, - LogType.warn, - LogType.info, - LogType.log, - LogType.group, - LogType.groupEnd, - LogType.groupCollapsed, - LogType.clear - ]); - break; - case "verbose": - acceptedTypes = new Set([ - LogType.error, - LogType.warn, - LogType.info, - LogType.log, - LogType.group, - LogType.groupEnd, - LogType.groupCollapsed, - LogType.profile, - LogType.profileEnd, - LogType.time, - LogType.status, - LogType.clear - ]); - collapsedGroups = true; - break; - } - const cachedMakePathsRelative = makePathsRelative.bindContextCache( - options.context, - compilation.compiler.root - ); - let depthInCollapsedGroup = 0; - for (const [origin, logEntries] of compilation.logging) { - const debugMode = loggingDebug.some(fn => fn(origin)); - if (logging === false && !debugMode) continue; - /** @type {KnownStatsLoggingEntry[]} */ - const groupStack = []; - /** @type {KnownStatsLoggingEntry[]} */ - const rootList = []; - let currentList = rootList; - let processedLogEntries = 0; - for (const entry of logEntries) { - let type = entry.type; - if (!debugMode && !acceptedTypes.has(type)) continue; - - // Expand groups in verbose and debug modes - if ( - type === LogType.groupCollapsed && - (debugMode || collapsedGroups) - ) - type = LogType.group; - - if (depthInCollapsedGroup === 0) { - processedLogEntries++; - } - - if (type === LogType.groupEnd) { - groupStack.pop(); - if (groupStack.length > 0) { - currentList = groupStack[groupStack.length - 1].children; - } else { - currentList = rootList; - } - if (depthInCollapsedGroup > 0) depthInCollapsedGroup--; - continue; - } - let message = undefined; - if (entry.type === LogType.time) { - message = `${entry.args[0]}: ${ - entry.args[1] * 1000 + entry.args[2] / 1000000 - } ms`; - } else if (entry.args && entry.args.length > 0) { - message = util.format(entry.args[0], ...entry.args.slice(1)); - } - /** @type {KnownStatsLoggingEntry} */ - const newEntry = { - ...entry, - type, - message, - trace: loggingTrace ? entry.trace : undefined, - children: - type === LogType.group || type === LogType.groupCollapsed - ? [] - : undefined - }; - currentList.push(newEntry); - if (newEntry.children) { - groupStack.push(newEntry); - currentList = newEntry.children; - if (depthInCollapsedGroup > 0) { - depthInCollapsedGroup++; - } else if (type === LogType.groupCollapsed) { - depthInCollapsedGroup = 1; - } - } - } - let name = cachedMakePathsRelative(origin).replace(/\|/g, " "); - if (name in object.logging) { - let i = 1; - while (`${name}#${i}` in object.logging) { - i++; - } - name = `${name}#${i}`; - } - object.logging[name] = { - entries: rootList, - filteredEntries: logEntries.length - processedLogEntries, - debug: debugMode - }; - } - } - }, - hash: (object, compilation) => { - object.hash = compilation.hash; - }, - version: object => { - object.version = (__webpack_require__(32702)/* .version */ .i8); - }, - env: (object, compilation, context, { _env }) => { - object.env = _env; - }, - timings: (object, compilation) => { - object.time = compilation.endTime - compilation.startTime; - }, - builtAt: (object, compilation) => { - object.builtAt = compilation.endTime; - }, - publicPath: (object, compilation) => { - object.publicPath = compilation.getPath( - compilation.outputOptions.publicPath - ); - }, - outputPath: (object, compilation) => { - object.outputPath = compilation.outputOptions.path; - }, - assets: (object, compilation, context, options, factory) => { - const { type } = context; - /** @type {Map} */ - const compilationFileToChunks = new Map(); - /** @type {Map} */ - const compilationAuxiliaryFileToChunks = new Map(); - for (const chunk of compilation.chunks) { - for (const file of chunk.files) { - let array = compilationFileToChunks.get(file); - if (array === undefined) { - array = []; - compilationFileToChunks.set(file, array); - } - array.push(chunk); - } - for (const file of chunk.auxiliaryFiles) { - let array = compilationAuxiliaryFileToChunks.get(file); - if (array === undefined) { - array = []; - compilationAuxiliaryFileToChunks.set(file, array); - } - array.push(chunk); - } - } - /** @type {Map} */ - const assetMap = new Map(); - /** @type {Set} */ - const assets = new Set(); - for (const asset of compilation.getAssets()) { - /** @type {PreprocessedAsset} */ - const item = { - ...asset, - type: "asset", - related: undefined - }; - assets.add(item); - assetMap.set(asset.name, item); - } - for (const item of assetMap.values()) { - const related = item.info.related; - if (!related) continue; - for (const type of Object.keys(related)) { - const relatedEntry = related[type]; - const deps = Array.isArray(relatedEntry) - ? relatedEntry - : [relatedEntry]; - for (const dep of deps) { - const depItem = assetMap.get(dep); - if (!depItem) continue; - assets.delete(depItem); - depItem.type = type; - item.related = item.related || []; - item.related.push(depItem); - } - } - } - - object.assetsByChunkName = {}; - for (const [file, chunks] of compilationFileToChunks) { - for (const chunk of chunks) { - const name = chunk.name; - if (!name) continue; - if ( - !Object.prototype.hasOwnProperty.call( - object.assetsByChunkName, - name - ) - ) { - object.assetsByChunkName[name] = []; - } - object.assetsByChunkName[name].push(file); - } - } - - const groupedAssets = factory.create( - `${type}.assets`, - Array.from(assets), - { - ...context, - compilationFileToChunks, - compilationAuxiliaryFileToChunks - } - ); - const limited = spaceLimited(groupedAssets, options.assetsSpace); - object.assets = limited.children; - object.filteredAssets = limited.filteredChildren; - }, - chunks: (object, compilation, context, options, factory) => { - const { type } = context; - object.chunks = factory.create( - `${type}.chunks`, - Array.from(compilation.chunks), - context - ); - }, - modules: (object, compilation, context, options, factory) => { - const { type } = context; - const array = Array.from(compilation.modules); - const groupedModules = factory.create(`${type}.modules`, array, context); - const limited = spaceLimited(groupedModules, options.modulesSpace); - object.modules = limited.children; - object.filteredModules = limited.filteredChildren; - }, - entrypoints: ( - object, - compilation, - context, - { entrypoints, chunkGroups, chunkGroupAuxiliary, chunkGroupChildren }, - factory - ) => { - const { type } = context; - const array = Array.from(compilation.entrypoints, ([key, value]) => ({ - name: key, - chunkGroup: value - })); - if (entrypoints === "auto" && !chunkGroups) { - if (array.length > 5) return; - if ( - !chunkGroupChildren && - array.every(({ chunkGroup }) => { - if (chunkGroup.chunks.length !== 1) return false; - const chunk = chunkGroup.chunks[0]; - return ( - chunk.files.size === 1 && - (!chunkGroupAuxiliary || chunk.auxiliaryFiles.size === 0) - ); - }) - ) { +/** + * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system + * @param {string} absPath an absolute path + * @returns {string} the parent directory of the absolute path + */ +const dirname = (fs, absPath) => { + if (fs && fs.dirname) { + return fs.dirname(absPath); + } else if (path.posix.isAbsolute(absPath)) { + return path.posix.dirname(absPath); + } else if (path.win32.isAbsolute(absPath)) { + return path.win32.dirname(absPath); + } else { + throw new Error( + `${absPath} is neither a posix nor a windows path, and there is no 'dirname' method defined in the file system` + ); + } +}; +exports.dirname = dirname; + +/** + * @param {OutputFileSystem} fs a file system + * @param {string} p an absolute path + * @param {function(Error=): void} callback callback function for the error + * @returns {void} + */ +const mkdirp = (fs, p, callback) => { + fs.mkdir(p, err => { + if (err) { + if (err.code === "ENOENT") { + const dir = dirname(fs, p); + if (dir === p) { + callback(err); return; } - } - object.entrypoints = factory.create( - `${type}.entrypoints`, - array, - context - ); - }, - chunkGroups: (object, compilation, context, options, factory) => { - const { type } = context; - const array = Array.from( - compilation.namedChunkGroups, - ([key, value]) => ({ - name: key, - chunkGroup: value - }) - ); - object.namedChunkGroups = factory.create( - `${type}.namedChunkGroups`, - array, - context - ); - }, - errors: (object, compilation, context, options, factory) => { - const { type, cachedGetErrors } = context; - object.errors = factory.create( - `${type}.errors`, - cachedGetErrors(compilation), - context - ); - }, - errorsCount: (object, compilation, { cachedGetErrors }) => { - object.errorsCount = countWithChildren(compilation, c => - cachedGetErrors(c) - ); - }, - warnings: (object, compilation, context, options, factory) => { - const { type, cachedGetWarnings } = context; - object.warnings = factory.create( - `${type}.warnings`, - cachedGetWarnings(compilation), - context - ); - }, - warningsCount: ( - object, - compilation, - context, - { warningsFilter }, - factory - ) => { - const { type, cachedGetWarnings } = context; - object.warningsCount = countWithChildren(compilation, (c, childType) => { - if (!warningsFilter && warningsFilter.length === 0) - return cachedGetWarnings(c); - return factory - .create(`${type}${childType}.warnings`, cachedGetWarnings(c), context) - .filter(warning => { - const warningString = Object.keys(warning) - .map(key => `${warning[key]}`) - .join("\n"); - return !warningsFilter.some(filter => - filter(warning, warningString) - ); - }); - }); - }, - errorDetails: ( - object, - compilation, - { cachedGetErrors, cachedGetWarnings }, - { errorDetails, errors, warnings } - ) => { - if (errorDetails === "auto") { - if (warnings) { - const warnings = cachedGetWarnings(compilation); - object.filteredWarningDetailsCount = warnings - .map(e => typeof e !== "string" && e.details) - .filter(Boolean).length; - } - if (errors) { - const errors = cachedGetErrors(compilation); - if (errors.length >= 3) { - object.filteredErrorDetailsCount = errors - .map(e => typeof e !== "string" && e.details) - .filter(Boolean).length; + mkdirp(fs, dir, err => { + if (err) { + callback(err); + return; } - } + fs.mkdir(p, err => { + if (err) { + if (err.code === "EEXIST") { + callback(); + return; + } + callback(err); + return; + } + callback(); + }); + }); + return; + } else if (err.code === "EEXIST") { + callback(); + return; } - }, - children: (object, compilation, context, options, factory) => { - const { type } = context; - object.children = factory.create( - `${type}.children`, - compilation.children, - context - ); + callback(err); + return; } - }, - asset: { - _: (object, asset, context, options, factory) => { - const { compilation } = context; - object.type = asset.type; - object.name = asset.name; - object.size = asset.source.size(); - object.emitted = compilation.emittedAssets.has(asset.name); - object.comparedForEmit = compilation.comparedForEmitAssets.has( - asset.name - ); - const cached = !object.emitted && !object.comparedForEmit; - object.cached = cached; - object.info = asset.info; - if (!cached || options.cachedAssets) { - Object.assign( - object, - factory.create(`${context.type}$visible`, asset, context) - ); + callback(); + }); +}; +exports.mkdirp = mkdirp; + +/** + * @param {IntermediateFileSystem} fs a file system + * @param {string} p an absolute path + * @returns {void} + */ +const mkdirpSync = (fs, p) => { + try { + fs.mkdirSync(p); + } catch (err) { + if (err) { + if (err.code === "ENOENT") { + const dir = dirname(fs, p); + if (dir === p) { + throw err; + } + mkdirpSync(fs, dir); + fs.mkdirSync(p); + return; + } else if (err.code === "EEXIST") { + return; } + throw err; } - }, - asset$visible: { - _: ( - object, - asset, - { compilation, compilationFileToChunks, compilationAuxiliaryFileToChunks } - ) => { - const chunks = compilationFileToChunks.get(asset.name) || []; - const auxiliaryChunks = - compilationAuxiliaryFileToChunks.get(asset.name) || []; - object.chunkNames = uniqueOrderedArray( - chunks, - c => (c.name ? [c.name] : []), - compareIds - ); - object.chunkIdHints = uniqueOrderedArray( - chunks, - c => Array.from(c.idNameHints), - compareIds - ); - object.auxiliaryChunkNames = uniqueOrderedArray( - auxiliaryChunks, - c => (c.name ? [c.name] : []), - compareIds - ); - object.auxiliaryChunkIdHints = uniqueOrderedArray( - auxiliaryChunks, - c => Array.from(c.idNameHints), - compareIds - ); - object.filteredRelated = asset.related ? asset.related.length : undefined; - }, - relatedAssets: (object, asset, context, options, factory) => { - const { type } = context; - object.related = factory.create( - `${type.slice(0, -8)}.related`, - asset.related, - context - ); - object.filteredRelated = asset.related - ? asset.related.length - object.related.length - : undefined; - }, - ids: ( - object, - asset, - { compilationFileToChunks, compilationAuxiliaryFileToChunks } - ) => { - const chunks = compilationFileToChunks.get(asset.name) || []; - const auxiliaryChunks = - compilationAuxiliaryFileToChunks.get(asset.name) || []; - object.chunks = uniqueOrderedArray(chunks, c => c.ids, compareIds); - object.auxiliaryChunks = uniqueOrderedArray( - auxiliaryChunks, - c => c.ids, - compareIds - ); - }, - performance: (object, asset) => { - object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(asset.source); - } - }, - chunkGroup: { - _: ( - object, - { name, chunkGroup }, - { compilation, compilation: { moduleGraph, chunkGraph } }, - { ids, chunkGroupAuxiliary, chunkGroupChildren, chunkGroupMaxAssets } - ) => { - const children = - chunkGroupChildren && - chunkGroup.getChildrenByOrders(moduleGraph, chunkGraph); - /** - * @param {string} name Name - * @returns {{ name: string, size: number }} Asset object - */ - const toAsset = name => { - const asset = compilation.getAsset(name); - return { - name, - size: asset ? asset.info.size : -1 - }; - }; - /** @type {(total: number, asset: { size: number }) => number} */ - const sizeReducer = (total, { size }) => total + size; - const assets = uniqueArray(chunkGroup.chunks, c => c.files).map(toAsset); - const auxiliaryAssets = uniqueOrderedArray( - chunkGroup.chunks, - c => c.auxiliaryFiles, - compareIds - ).map(toAsset); - const assetsSize = assets.reduce(sizeReducer, 0); - const auxiliaryAssetsSize = auxiliaryAssets.reduce(sizeReducer, 0); - /** @type {KnownStatsChunkGroup} */ - const statsChunkGroup = { - name, - chunks: ids ? chunkGroup.chunks.map(c => c.id) : undefined, - assets: assets.length <= chunkGroupMaxAssets ? assets : undefined, - filteredAssets: - assets.length <= chunkGroupMaxAssets ? 0 : assets.length, - assetsSize, - auxiliaryAssets: - chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets - ? auxiliaryAssets - : undefined, - filteredAuxiliaryAssets: - chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets - ? 0 - : auxiliaryAssets.length, - auxiliaryAssetsSize, - children: children - ? mapObject(children, groups => - groups.map(group => { - const assets = uniqueArray(group.chunks, c => c.files).map( - toAsset - ); - const auxiliaryAssets = uniqueOrderedArray( - group.chunks, - c => c.auxiliaryFiles, - compareIds - ).map(toAsset); - - /** @type {KnownStatsChunkGroup} */ - const childStatsChunkGroup = { - name: group.name, - chunks: ids ? group.chunks.map(c => c.id) : undefined, - assets: - assets.length <= chunkGroupMaxAssets ? assets : undefined, - filteredAssets: - assets.length <= chunkGroupMaxAssets ? 0 : assets.length, - auxiliaryAssets: - chunkGroupAuxiliary && - auxiliaryAssets.length <= chunkGroupMaxAssets - ? auxiliaryAssets - : undefined, - filteredAuxiliaryAssets: - chunkGroupAuxiliary && - auxiliaryAssets.length <= chunkGroupMaxAssets - ? 0 - : auxiliaryAssets.length - }; + } +}; +exports.mkdirpSync = mkdirpSync; - return childStatsChunkGroup; - }) - ) - : undefined, - childAssets: children - ? mapObject(children, groups => { - /** @type {Set} */ - const set = new Set(); - for (const group of groups) { - for (const chunk of group.chunks) { - for (const asset of chunk.files) { - set.add(asset); - } - } - } - return Array.from(set); - }) - : undefined - }; - Object.assign(object, statsChunkGroup); - }, - performance: (object, { chunkGroup }) => { - object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(chunkGroup); +/** + * @param {InputFileSystem} fs a file system + * @param {string} p an absolute path + * @param {ReadJsonCallback} callback callback + * @returns {void} + */ +const readJson = (fs, p, callback) => { + if ("readJson" in fs) return fs.readJson(p, callback); + fs.readFile(p, (err, buf) => { + if (err) return callback(err); + let data; + try { + data = JSON.parse(buf.toString("utf-8")); + } catch (e) { + return callback(e); } - }, - module: { - _: (object, module, context, options, factory) => { - const { compilation, type } = context; - const built = compilation.builtModules.has(module); - const codeGenerated = compilation.codeGeneratedModules.has(module); - const buildTimeExecuted = - compilation.buildTimeExecutedModules.has(module); - /** @type {{[x: string]: number}} */ - const sizes = {}; - for (const sourceType of module.getSourceTypes()) { - sizes[sourceType] = module.size(sourceType); - } - /** @type {KnownStatsModule} */ - const statsModule = { - type: "module", - moduleType: module.type, - layer: module.layer, - size: module.size(), - sizes, - built, - codeGenerated, - buildTimeExecuted, - cached: !built && !codeGenerated - }; - Object.assign(object, statsModule); + return callback(null, data); + }); +}; +exports.readJson = readJson; - if (built || codeGenerated || options.cachedModules) { - Object.assign( - object, - factory.create(`${type}$visible`, module, context) - ); +/** + * @param {InputFileSystem} fs a file system + * @param {string} p an absolute path + * @param {ReadJsonCallback} callback callback + * @returns {void} + */ +const lstatReadlinkAbsolute = (fs, p, callback) => { + let i = 3; + const doReadLink = () => { + fs.readlink(p, (err, target) => { + if (err && --i > 0) { + // It might was just changed from symlink to file + // we retry 2 times to catch this case before throwing the error + return doStat(); } + if (err || !target) return doStat(); + const value = target.toString(); + callback(null, join(fs, dirname(fs, p), value)); + }); + }; + const doStat = () => { + if ("lstat" in fs) { + return fs.lstat(p, (err, stats) => { + if (err) return callback(err); + if (stats.isSymbolicLink()) { + return doReadLink(); + } + callback(null, stats); + }); + } else { + return fs.stat(p, callback); } - }, - module$visible: { - _: (object, module, context, { requestShortener }, factory) => { - const { compilation, type, rootModules } = context; - const { moduleGraph } = compilation; - /** @type {Module[]} */ - const path = []; - const issuer = moduleGraph.getIssuer(module); - let current = issuer; - while (current) { - path.push(current); - current = moduleGraph.getIssuer(current); - } - path.reverse(); - const profile = moduleGraph.getProfile(module); - const errors = module.getErrors(); - const errorsCount = errors !== undefined ? countIterable(errors) : 0; - const warnings = module.getWarnings(); - const warningsCount = - warnings !== undefined ? countIterable(warnings) : 0; - /** @type {{[x: string]: number}} */ - const sizes = {}; - for (const sourceType of module.getSourceTypes()) { - sizes[sourceType] = module.size(sourceType); - } - /** @type {KnownStatsModule} */ - const statsModule = { - identifier: module.identifier(), - name: module.readableIdentifier(requestShortener), - nameForCondition: module.nameForCondition(), - index: moduleGraph.getPreOrderIndex(module), - preOrderIndex: moduleGraph.getPreOrderIndex(module), - index2: moduleGraph.getPostOrderIndex(module), - postOrderIndex: moduleGraph.getPostOrderIndex(module), - cacheable: module.buildInfo.cacheable, - optional: module.isOptional(moduleGraph), - orphan: - !type.endsWith("module.modules[].module$visible") && - compilation.chunkGraph.getNumberOfModuleChunks(module) === 0, - dependent: rootModules ? !rootModules.has(module) : undefined, - issuer: issuer && issuer.identifier(), - issuerName: issuer && issuer.readableIdentifier(requestShortener), - issuerPath: - issuer && - factory.create(`${type.slice(0, -8)}.issuerPath`, path, context), - failed: errorsCount > 0, - errors: errorsCount, - warnings: warningsCount - }; - Object.assign(object, statsModule); - if (profile) { - object.profile = factory.create( - `${type.slice(0, -8)}.profile`, - profile, - context - ); + }; + if ("lstat" in fs) return doStat(); + doReadLink(); +}; +exports.lstatReadlinkAbsolute = lstatReadlinkAbsolute; + + +/***/ }), + +/***/ 59461: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const Hash = __webpack_require__(36692); +const MAX_SHORT_STRING = (__webpack_require__(1842).MAX_SHORT_STRING); + +class BatchedHash extends Hash { + constructor(hash) { + super(); + this.string = undefined; + this.encoding = undefined; + this.hash = hash; + } + + /** + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash + */ + update(data, inputEncoding) { + if (this.string !== undefined) { + if ( + typeof data === "string" && + inputEncoding === this.encoding && + this.string.length + data.length < MAX_SHORT_STRING + ) { + this.string += data; + return this; } - }, - ids: (object, module, { compilation: { chunkGraph, moduleGraph } }) => { - object.id = chunkGraph.getModuleId(module); - const issuer = moduleGraph.getIssuer(module); - object.issuerId = issuer && chunkGraph.getModuleId(issuer); - object.chunks = Array.from( - chunkGraph.getOrderedModuleChunksIterable(module, compareChunksById), - chunk => chunk.id - ); - }, - moduleAssets: (object, module) => { - object.assets = module.buildInfo.assets - ? Object.keys(module.buildInfo.assets) - : []; - }, - reasons: (object, module, context, options, factory) => { - const { - type, - compilation: { moduleGraph } - } = context; - const groupsReasons = factory.create( - `${type.slice(0, -8)}.reasons`, - Array.from(moduleGraph.getIncomingConnections(module)), - context - ); - const limited = spaceLimited(groupsReasons, options.reasonsSpace); - object.reasons = limited.children; - object.filteredReasons = limited.filteredChildren; - }, - usedExports: ( - object, - module, - { runtime, compilation: { moduleGraph } } - ) => { - const usedExports = moduleGraph.getUsedExports(module, runtime); - if (usedExports === null) { - object.usedExports = null; - } else if (typeof usedExports === "boolean") { - object.usedExports = usedExports; + this.hash.update(this.string, this.encoding); + this.string = undefined; + } + if (typeof data === "string") { + if ( + data.length < MAX_SHORT_STRING && + // base64 encoding is not valid since it may contain padding chars + (!inputEncoding || !inputEncoding.startsWith("ba")) + ) { + this.string = data; + this.encoding = inputEncoding; } else { - object.usedExports = Array.from(usedExports); - } - }, - providedExports: (object, module, { compilation: { moduleGraph } }) => { - const providedExports = moduleGraph.getProvidedExports(module); - object.providedExports = Array.isArray(providedExports) - ? providedExports - : null; - }, - optimizationBailout: ( - object, - module, - { compilation: { moduleGraph } }, - { requestShortener } - ) => { - object.optimizationBailout = moduleGraph - .getOptimizationBailout(module) - .map(item => { - if (typeof item === "function") return item(requestShortener); - return item; - }); - }, - depth: (object, module, { compilation: { moduleGraph } }) => { - object.depth = moduleGraph.getDepth(module); - }, - nestedModules: (object, module, context, options, factory) => { - const { type } = context; - const innerModules = /** @type {Module & { modules?: Module[] }} */ ( - module - ).modules; - if (Array.isArray(innerModules)) { - const groupedModules = factory.create( - `${type.slice(0, -8)}.modules`, - innerModules, - context - ); - const limited = spaceLimited( - groupedModules, - options.nestedModulesSpace - ); - object.modules = limited.children; - object.filteredModules = limited.filteredChildren; - } - }, - source: (object, module) => { - const originalSource = module.originalSource(); - if (originalSource) { - object.source = originalSource.source(); + this.hash.update(data, inputEncoding); } + } else { + this.hash.update(data); } - }, - profile: { - _: (object, profile) => { - /** @type {KnownStatsProfile} */ - const statsProfile = { - total: - profile.factory + - profile.restoring + - profile.integration + - profile.building + - profile.storing, - resolving: profile.factory, - restoring: profile.restoring, - building: profile.building, - integration: profile.integration, - storing: profile.storing, - additionalResolving: profile.additionalFactories, - additionalIntegration: profile.additionalIntegration, - // TODO remove this in webpack 6 - factory: profile.factory, - // TODO remove this in webpack 6 - dependencies: profile.additionalFactories - }; - Object.assign(object, statsProfile); - } - }, - moduleIssuer: { - _: (object, module, context, { requestShortener }, factory) => { - const { compilation, type } = context; - const { moduleGraph } = compilation; - const profile = moduleGraph.getProfile(module); - /** @type {KnownStatsModuleIssuer} */ - const statsModuleIssuer = { - identifier: module.identifier(), - name: module.readableIdentifier(requestShortener) - }; - Object.assign(object, statsModuleIssuer); - if (profile) { - object.profile = factory.create(`${type}.profile`, profile, context); - } - }, - ids: (object, module, { compilation: { chunkGraph } }) => { - object.id = chunkGraph.getModuleId(module); + return this; + } + + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + if (this.string !== undefined) { + this.hash.update(this.string, this.encoding); } - }, - moduleReason: { - _: (object, reason, { runtime }, { requestShortener }) => { - const dep = reason.dependency; - const moduleDep = - dep && dep instanceof ModuleDependency ? dep : undefined; - /** @type {KnownStatsModuleReason} */ - const statsModuleReason = { - moduleIdentifier: reason.originModule - ? reason.originModule.identifier() - : null, - module: reason.originModule - ? reason.originModule.readableIdentifier(requestShortener) - : null, - moduleName: reason.originModule - ? reason.originModule.readableIdentifier(requestShortener) - : null, - resolvedModuleIdentifier: reason.resolvedOriginModule - ? reason.resolvedOriginModule.identifier() - : null, - resolvedModule: reason.resolvedOriginModule - ? reason.resolvedOriginModule.readableIdentifier(requestShortener) - : null, - type: reason.dependency ? reason.dependency.type : null, - active: reason.isActive(runtime), - explanation: reason.explanation, - userRequest: (moduleDep && moduleDep.userRequest) || null - }; - Object.assign(object, statsModuleReason); - if (reason.dependency) { - const locInfo = formatLocation(reason.dependency.loc); - if (locInfo) { - object.loc = locInfo; - } + return this.hash.digest(encoding); + } +} + +module.exports = BatchedHash; + + +/***/ }), + +/***/ 86884: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const create = __webpack_require__(1842); + +//#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1 +const md4 = new WebAssembly.Module( + Buffer.from( + // 2156 bytes + "AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqLEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvSCgEZfyMBIQUjAiECIwMhAyMEIQQDQCAAIAFLBEAgASgCJCISIAEoAiAiEyABKAIcIgkgASgCGCIIIAEoAhQiByABKAIQIg4gASgCDCIGIAEoAggiDyABKAIEIhAgASgCACIRIAMgBHMgAnEgBHMgBWpqQQN3IgogAiADc3EgA3MgBGpqQQd3IgsgAiAKc3EgAnMgA2pqQQt3IgwgCiALc3EgCnMgAmpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IgogDCANc3EgDHMgC2pqQQd3IgsgCiANc3EgDXMgDGpqQQt3IgwgCiALc3EgCnMgDWpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IhQgDCANc3EgDHMgC2pqQQd3IRUgASgCLCILIAEoAigiCiAMIA0gDSAUcyAVcXNqakELdyIWIBQgFXNxIBRzIA1qakETdyEXIAEoAjQiGCABKAIwIhkgFSAWcyAXcSAVcyAUampBA3ciFCAWIBdzcSAWcyAVampBB3chFSABKAI8Ig0gASgCOCIMIBQgF3MgFXEgF3MgFmpqQQt3IhYgFCAVc3EgFHMgF2pqQRN3IRcgEyAOIBEgFCAVIBZyIBdxIBUgFnFyampBmfOJ1AVqQQN3IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEFdyIVIBQgF3JxIBQgF3FyIBZqakGZ84nUBWpBCXchFiAPIBggEiAWIAcgFSAQIBQgGSAUIBVyIBZxIBQgFXFyIBdqakGZ84nUBWpBDXciFCAVIBZycSAVIBZxcmpqQZnzidQFakEDdyIVIBQgFnJxIBQgFnFyampBmfOJ1AVqQQV3IhcgFCAVcnEgFCAVcXJqakGZ84nUBWpBCXciFiAVIBdycSAVIBdxciAUampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEDdyEVIBEgBiAVIAwgFCAKIBYgCCAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFyAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIWIBUgF3JxIBUgF3FyampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXJqakGZ84nUBWpBA3ciFSALIBYgCSAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFiAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIXIA0gFSAWciAXcSAVIBZxciAUampBmfOJ1AVqQQ13IhRzIBZzampBodfn9gZqQQN3IREgByAIIA4gFCARIBcgESAUc3MgFmogE2pBodfn9gZqQQl3IhNzcyAXampBodfn9gZqQQt3Ig4gDyARIBMgDiARIA4gE3NzIBRqIBlqQaHX5/YGakEPdyIRc3NqakGh1+f2BmpBA3ciDyAOIA8gEXNzIBNqIApqQaHX5/YGakEJdyIKcyARc2pqQaHX5/YGakELdyIIIBAgDyAKIAggDCAPIAggCnNzIBFqakGh1+f2BmpBD3ciDHNzampBodfn9gZqQQN3Ig4gEiAIIAwgDnNzIApqakGh1+f2BmpBCXciCHMgDHNqakGh1+f2BmpBC3chByAFIAYgCCAHIBggDiAHIAhzcyAMampBodfn9gZqQQ93IgpzcyAOampBodfn9gZqQQN3IgZqIQUgDSAGIAkgByAGIAsgByAGIApzcyAIampBodfn9gZqQQl3IgdzIApzampBodfn9gZqQQt3IgYgB3NzIApqakGh1+f2BmpBD3cgAmohAiADIAZqIQMgBCAHaiEEIAFBQGshAQwBCwsgBSQBIAIkAiADJAMgBCQECw0AIAAQASAAIwBqJAAL/wQCA38BfiAAIwBqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=", + "base64" + ) +); +//#endregion + +module.exports = create.bind(null, md4, [], 64, 32); + + +/***/ }), + +/***/ 1842: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +// 65536 is the size of a wasm memory page +// 64 is the maximum chunk size for every possible wasm hash implementation +// 4 is the maximum number of bytes per char for string encoding (max is utf-8) +// ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64 +const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3; + +class WasmHash { + /** + * @param {WebAssembly.Instance} instance wasm instance + * @param {WebAssembly.Instance[]} instancesPool pool of instances + * @param {number} chunkSize size of data chunks passed to wasm + * @param {number} digestSize size of digest returned by wasm + */ + constructor(instance, instancesPool, chunkSize, digestSize) { + const exports = /** @type {any} */ (instance.exports); + exports.init(); + this.exports = exports; + this.mem = Buffer.from(exports.memory.buffer, 0, 65536); + this.buffered = 0; + this.instancesPool = instancesPool; + this.chunkSize = chunkSize; + this.digestSize = digestSize; + } + + reset() { + this.buffered = 0; + this.exports.init(); + } + + /** + * @param {Buffer | string} data data + * @param {BufferEncoding=} encoding encoding + * @returns {this} itself + */ + update(data, encoding) { + if (typeof data === "string") { + while (data.length > MAX_SHORT_STRING) { + this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding); + data = data.slice(MAX_SHORT_STRING); } - }, - ids: (object, reason, { compilation: { chunkGraph } }) => { - object.moduleId = reason.originModule - ? chunkGraph.getModuleId(reason.originModule) - : null; - object.resolvedModuleId = reason.resolvedOriginModule - ? chunkGraph.getModuleId(reason.resolvedOriginModule) - : null; + this._updateWithShortString(data, encoding); + return this; } - }, - chunk: { - _: (object, chunk, { makePathsRelative, compilation: { chunkGraph } }) => { - const childIdByOrder = chunk.getChildIdsByOrders(chunkGraph); - - /** @type {KnownStatsChunk} */ - const statsChunk = { - rendered: chunk.rendered, - initial: chunk.canBeInitial(), - entry: chunk.hasRuntime(), - recorded: AggressiveSplittingPlugin.wasChunkRecorded(chunk), - reason: chunk.chunkReason, - size: chunkGraph.getChunkModulesSize(chunk), - sizes: chunkGraph.getChunkModulesSizes(chunk), - names: chunk.name ? [chunk.name] : [], - idHints: Array.from(chunk.idNameHints), - runtime: - chunk.runtime === undefined - ? undefined - : typeof chunk.runtime === "string" - ? [makePathsRelative(chunk.runtime)] - : Array.from(chunk.runtime.sort(), makePathsRelative), - files: Array.from(chunk.files), - auxiliaryFiles: Array.from(chunk.auxiliaryFiles).sort(compareIds), - hash: chunk.renderedHash, - childrenByOrder: childIdByOrder - }; - Object.assign(object, statsChunk); - }, - ids: (object, chunk) => { - object.id = chunk.id; - }, - chunkRelations: (object, chunk, { compilation: { chunkGraph } }) => { - /** @type {Set} */ - const parents = new Set(); - /** @type {Set} */ - const children = new Set(); - /** @type {Set} */ - const siblings = new Set(); + this._updateWithBuffer(data); + return this; + } - for (const chunkGroup of chunk.groupsIterable) { - for (const parentGroup of chunkGroup.parentsIterable) { - for (const chunk of parentGroup.chunks) { - parents.add(chunk.id); - } - } - for (const childGroup of chunkGroup.childrenIterable) { - for (const chunk of childGroup.chunks) { - children.add(chunk.id); + /** + * @param {string} data data + * @param {BufferEncoding=} encoding encoding + * @returns {void} + */ + _updateWithShortString(data, encoding) { + const { exports, buffered, mem, chunkSize } = this; + let endPos; + if (data.length < 70) { + if (!encoding || encoding === "utf-8" || encoding === "utf8") { + endPos = buffered; + for (let i = 0; i < data.length; i++) { + const cc = data.charCodeAt(i); + if (cc < 0x80) mem[endPos++] = cc; + else if (cc < 0x800) { + mem[endPos] = (cc >> 6) | 0xc0; + mem[endPos + 1] = (cc & 0x3f) | 0x80; + endPos += 2; + } else { + // bail-out for weird chars + endPos += mem.write(data.slice(i), endPos, encoding); + break; } } - for (const sibling of chunkGroup.chunks) { - if (sibling !== chunk) siblings.add(sibling.id); + } else if (encoding === "latin1") { + endPos = buffered; + for (let i = 0; i < data.length; i++) { + const cc = data.charCodeAt(i); + mem[endPos++] = cc; } + } else { + endPos = buffered + mem.write(data, buffered, encoding); } - object.siblings = Array.from(siblings).sort(compareIds); - object.parents = Array.from(parents).sort(compareIds); - object.children = Array.from(children).sort(compareIds); - }, - chunkModules: (object, chunk, context, options, factory) => { - const { - type, - compilation: { chunkGraph } - } = context; - const array = chunkGraph.getChunkModules(chunk); - const groupedModules = factory.create(`${type}.modules`, array, { - ...context, - runtime: chunk.runtime, - rootModules: new Set(chunkGraph.getChunkRootModules(chunk)) - }); - const limited = spaceLimited(groupedModules, options.chunkModulesSpace); - object.modules = limited.children; - object.filteredModules = limited.filteredChildren; - }, - chunkOrigins: (object, chunk, context, options, factory) => { - const { - type, - compilation: { chunkGraph } - } = context; - /** @type {Set} */ - const originsKeySet = new Set(); - const origins = []; - for (const g of chunk.groupsIterable) { - origins.push(...g.origins); - } - const array = origins.filter(origin => { - const key = [ - origin.module ? chunkGraph.getModuleId(origin.module) : undefined, - formatLocation(origin.loc), - origin.request - ].join(); - if (originsKeySet.has(key)) return false; - originsKeySet.add(key); - return true; - }); - object.origins = factory.create(`${type}.origins`, array, context); - } - }, - chunkOrigin: { - _: (object, origin, context, { requestShortener }) => { - /** @type {KnownStatsChunkOrigin} */ - const statsChunkOrigin = { - module: origin.module ? origin.module.identifier() : "", - moduleIdentifier: origin.module ? origin.module.identifier() : "", - moduleName: origin.module - ? origin.module.readableIdentifier(requestShortener) - : "", - loc: formatLocation(origin.loc), - request: origin.request - }; - Object.assign(object, statsChunkOrigin); - }, - ids: (object, origin, { compilation: { chunkGraph } }) => { - object.moduleId = origin.module - ? chunkGraph.getModuleId(origin.module) - : undefined; - } - }, - error: EXTRACT_ERROR, - warning: EXTRACT_ERROR, - moduleTraceItem: { - _: (object, { origin, module }, context, { requestShortener }, factory) => { - const { - type, - compilation: { moduleGraph } - } = context; - object.originIdentifier = origin.identifier(); - object.originName = origin.readableIdentifier(requestShortener); - object.moduleIdentifier = module.identifier(); - object.moduleName = module.readableIdentifier(requestShortener); - const dependencies = Array.from( - moduleGraph.getIncomingConnections(module) - ) - .filter(c => c.resolvedOriginModule === origin && c.dependency) - .map(c => c.dependency); - object.dependencies = factory.create( - `${type}.dependencies`, - Array.from(new Set(dependencies)), - context - ); - }, - ids: (object, { origin, module }, { compilation: { chunkGraph } }) => { - object.originId = chunkGraph.getModuleId(origin); - object.moduleId = chunkGraph.getModuleId(module); + } else { + endPos = buffered + mem.write(data, buffered, encoding); } - }, - moduleTraceDependency: { - _: (object, dependency) => { - object.loc = formatLocation(dependency.loc); + if (endPos < chunkSize) { + this.buffered = endPos; + } else { + const l = endPos & ~(this.chunkSize - 1); + exports.update(l); + const newBuffered = endPos - l; + this.buffered = newBuffered; + if (newBuffered > 0) mem.copyWithin(0, l, endPos); } } -}; - -/** @type {Record boolean | undefined>>} */ -const FILTER = { - "module.reasons": { - "!orphanModules": (reason, { compilation: { chunkGraph } }) => { - if ( - reason.originModule && - chunkGraph.getNumberOfModuleChunks(reason.originModule) === 0 - ) { - return false; + + /** + * @param {Buffer} data data + * @returns {void} + */ + _updateWithBuffer(data) { + const { exports, buffered, mem } = this; + const length = data.length; + if (buffered + length < this.chunkSize) { + data.copy(mem, buffered, 0, length); + this.buffered += length; + } else { + const l = (buffered + length) & ~(this.chunkSize - 1); + if (l > 65536) { + let i = 65536 - buffered; + data.copy(mem, buffered, 0, i); + exports.update(65536); + const stop = l - buffered - 65536; + while (i < stop) { + data.copy(mem, 0, i, i + 65536); + exports.update(65536); + i += 65536; + } + data.copy(mem, 0, i, l - buffered); + exports.update(l - buffered - i); + } else { + data.copy(mem, buffered, 0, l - buffered); + exports.update(l); } + const newBuffered = length + buffered - l; + this.buffered = newBuffered; + if (newBuffered > 0) data.copy(mem, 0, length - newBuffered, length); } } -}; -/** @type {Record boolean | undefined>>} */ -const FILTER_RESULTS = { - "compilation.warnings": { - warningsFilter: util.deprecate( - (warning, context, { warningsFilter }) => { - const warningString = Object.keys(warning) - .map(key => `${warning[key]}`) - .join("\n"); - return !warningsFilter.some(filter => filter(warning, warningString)); - }, - "config.stats.warningsFilter is deprecated in favor of config.ignoreWarnings", - "DEP_WEBPACK_STATS_WARNINGS_FILTER" - ) + digest(type) { + const { exports, buffered, mem, digestSize } = this; + exports.final(buffered); + this.instancesPool.push(this); + const hex = mem.toString("latin1", 0, digestSize); + if (type === "hex") return hex; + if (type === "binary" || !type) return Buffer.from(hex, "hex"); + return Buffer.from(hex, "hex").toString(type); } -}; +} -/** @type {Record void>} */ -const MODULES_SORTER = { - _: (comparators, { compilation: { moduleGraph } }) => { - comparators.push( - compareSelect( - /** - * @param {Module} m module - * @returns {number} depth - */ - m => moduleGraph.getDepth(m), - compareNumbers - ), - compareSelect( - /** - * @param {Module} m module - * @returns {number} index - */ - m => moduleGraph.getPreOrderIndex(m), - compareNumbers - ), - compareSelect( - /** - * @param {Module} m module - * @returns {string} identifier - */ - m => m.identifier(), - compareIds - ) +const create = (wasmModule, instancesPool, chunkSize, digestSize) => { + if (instancesPool.length > 0) { + const old = instancesPool.pop(); + old.reset(); + return old; + } else { + return new WasmHash( + new WebAssembly.Instance(wasmModule), + instancesPool, + chunkSize, + digestSize ); } }; -/** @type {Record void>>} */ -const SORTERS = { - "compilation.chunks": { - _: comparators => { - comparators.push(compareSelect(c => c.id, compareIds)); - } - }, - "compilation.modules": MODULES_SORTER, - "chunk.rootModules": MODULES_SORTER, - "chunk.modules": MODULES_SORTER, - "module.modules": MODULES_SORTER, - "module.reasons": { - _: (comparators, { compilation: { chunkGraph } }) => { - comparators.push( - compareSelect(x => x.originModule, compareModulesByIdentifier) - ); - comparators.push( - compareSelect(x => x.resolvedOriginModule, compareModulesByIdentifier) - ); - comparators.push( - compareSelect( - x => x.dependency, - concatComparators( - compareSelect( - /** - * @param {Dependency} x dependency - * @returns {DependencyLocation} location - */ - x => x.loc, - compareLocations - ), - compareSelect(x => x.type, compareIds) - ) - ) - ); +module.exports = create; +module.exports.MAX_SHORT_STRING = MAX_SHORT_STRING; + + +/***/ }), + +/***/ 35028: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const create = __webpack_require__(1842); + +//#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1 +const xxhash64 = new WebAssembly.Module( + Buffer.from( + // 1170 bytes + "AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrIIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqAYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEAgAiABNQIAQoeVr6+Ytt6bnn9+hUIXiULP1tO+0ser2UJ+Qvnz3fGZ9pmrFnwhAiABQQRqIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAkIdiCAChUL5893xmfaZqxZ+IgJCIIggAoUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL", + "base64" + ) +); +//#endregion + +module.exports = create.bind(null, xxhash64, [], 32, 16); + + +/***/ }), + +/***/ 82186: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const path = __webpack_require__(71017); + +const WINDOWS_ABS_PATH_REGEXP = /^[a-zA-Z]:[\\/]/; +const SEGMENTS_SPLIT_REGEXP = /([|!])/; +const WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g; + +/** + * @typedef {Object} MakeRelativePathsCache + * @property {Map>=} relativePaths + */ + +const relativePathToRequest = relativePath => { + if (relativePath === "") return "./."; + if (relativePath === "..") return "../."; + if (relativePath.startsWith("../")) return relativePath; + return `./${relativePath}`; +}; + +/** + * @param {string} context context for relative path + * @param {string} maybeAbsolutePath path to make relative + * @returns {string} relative path in request style + */ +const absoluteToRequest = (context, maybeAbsolutePath) => { + if (maybeAbsolutePath[0] === "/") { + if ( + maybeAbsolutePath.length > 1 && + maybeAbsolutePath[maybeAbsolutePath.length - 1] === "/" + ) { + // this 'path' is actually a regexp generated by dynamic requires. + // Don't treat it as an absolute path. + return maybeAbsolutePath; } - }, - "chunk.origins": { - _: (comparators, { compilation: { chunkGraph } }) => { - comparators.push( - compareSelect( - origin => - origin.module ? chunkGraph.getModuleId(origin.module) : undefined, - compareIds - ), - compareSelect(origin => formatLocation(origin.loc), compareIds), - compareSelect(origin => origin.request, compareIds) + + const querySplitPos = maybeAbsolutePath.indexOf("?"); + let resource = + querySplitPos === -1 + ? maybeAbsolutePath + : maybeAbsolutePath.slice(0, querySplitPos); + resource = relativePathToRequest(path.posix.relative(context, resource)); + return querySplitPos === -1 + ? resource + : resource + maybeAbsolutePath.slice(querySplitPos); + } + + if (WINDOWS_ABS_PATH_REGEXP.test(maybeAbsolutePath)) { + const querySplitPos = maybeAbsolutePath.indexOf("?"); + let resource = + querySplitPos === -1 + ? maybeAbsolutePath + : maybeAbsolutePath.slice(0, querySplitPos); + resource = path.win32.relative(context, resource); + if (!WINDOWS_ABS_PATH_REGEXP.test(resource)) { + resource = relativePathToRequest( + resource.replace(WINDOWS_PATH_SEPARATOR_REGEXP, "/") ); } + return querySplitPos === -1 + ? resource + : resource + maybeAbsolutePath.slice(querySplitPos); } -}; -const getItemSize = item => { - // Each item takes 1 line - // + the size of the children - // + 1 extra line when it has children and filteredChildren - return !item.children - ? 1 - : item.filteredChildren - ? 2 + getTotalSize(item.children) - : 1 + getTotalSize(item.children); + // not an absolute path + return maybeAbsolutePath; }; -const getTotalSize = children => { - let size = 0; - for (const child of children) { - size += getItemSize(child); - } - return size; +/** + * @param {string} context context for relative path + * @param {string} relativePath path + * @returns {string} absolute path + */ +const requestToAbsolute = (context, relativePath) => { + if (relativePath.startsWith("./") || relativePath.startsWith("../")) + return path.join(context, relativePath); + return relativePath; }; -const getTotalItems = children => { - let count = 0; - for (const child of children) { - if (!child.children && !child.filteredChildren) { - count++; - } else { - if (child.children) count += getTotalItems(child.children); - if (child.filteredChildren) count += child.filteredChildren; +const makeCacheable = fn => { + /** @type {WeakMap>>} */ + const cache = new WeakMap(); + + /** + * @param {string} context context used to create relative path + * @param {string} identifier identifier used to create relative path + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {string} the returned relative path + */ + const cachedFn = (context, identifier, associatedObjectForCache) => { + if (!associatedObjectForCache) return fn(context, identifier); + + let innerCache = cache.get(associatedObjectForCache); + if (innerCache === undefined) { + innerCache = new Map(); + cache.set(associatedObjectForCache, innerCache); } - } - return count; -}; -const collapse = children => { - // After collapse each child must take exactly one line - const newChildren = []; - for (const child of children) { - if (child.children) { - let filteredChildren = child.filteredChildren || 0; - filteredChildren += getTotalItems(child.children); - newChildren.push({ - ...child, - children: undefined, - filteredChildren - }); + let cachedResult; + let innerSubCache = innerCache.get(context); + if (innerSubCache === undefined) { + innerCache.set(context, (innerSubCache = new Map())); } else { - newChildren.push(child); + cachedResult = innerSubCache.get(identifier); } - } - return newChildren; -}; -const spaceLimited = ( - itemsAndGroups, - max, - filteredChildrenLineReserved = false -) => { - if (max < 1) { - return { - children: undefined, - filteredChildren: getTotalItems(itemsAndGroups) - }; - } - /** @type {any[] | undefined} */ - let children = undefined; - /** @type {number | undefined} */ - let filteredChildren = undefined; - // This are the groups, which take 1+ lines each - const groups = []; - // The sizes of the groups are stored in groupSizes - const groupSizes = []; - // This are the items, which take 1 line each - const items = []; - // The total of group sizes - let groupsSize = 0; + if (cachedResult !== undefined) { + return cachedResult; + } else { + const result = fn(context, identifier); + innerSubCache.set(identifier, result); + return result; + } + }; - for (const itemOrGroup of itemsAndGroups) { - // is item - if (!itemOrGroup.children && !itemOrGroup.filteredChildren) { - items.push(itemOrGroup); + /** + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {function(string, string): string} cached function + */ + cachedFn.bindCache = associatedObjectForCache => { + let innerCache; + if (associatedObjectForCache) { + innerCache = cache.get(associatedObjectForCache); + if (innerCache === undefined) { + innerCache = new Map(); + cache.set(associatedObjectForCache, innerCache); + } } else { - groups.push(itemOrGroup); - const size = getItemSize(itemOrGroup); - groupSizes.push(size); - groupsSize += size; + innerCache = new Map(); } - } - if (groupsSize + items.length <= max) { - // The total size in the current state fits into the max - // keep all - children = groups.length > 0 ? groups.concat(items) : items; - } else if (groups.length === 0) { - // slice items to max - // inner space marks that lines for filteredChildren already reserved - const limit = max - (filteredChildrenLineReserved ? 0 : 1); - filteredChildren = items.length - limit; - items.length = limit; - children = items; - } else { - // limit is the size when all groups are collapsed - const limit = - groups.length + - (filteredChildrenLineReserved || items.length === 0 ? 0 : 1); - if (limit < max) { - // calculate how much we are over the size limit - // this allows to approach the limit faster - let oversize; - // If each group would take 1 line the total would be below the maximum - // collapse some groups, keep items - while ( - (oversize = - groupsSize + - items.length + - (filteredChildren && !filteredChildrenLineReserved ? 1 : 0) - - max) > 0 - ) { - // Find the maximum group and process only this one - const maxGroupSize = Math.max(...groupSizes); - if (maxGroupSize < items.length) { - filteredChildren = items.length; - items.length = 0; - continue; - } - for (let i = 0; i < groups.length; i++) { - if (groupSizes[i] === maxGroupSize) { - const group = groups[i]; - // run this algorithm recursively and limit the size of the children to - // current size - oversize / number of groups - // So it should always end up being smaller - const headerSize = group.filteredChildren ? 2 : 1; - const limited = spaceLimited( - group.children, - maxGroupSize - - // we should use ceil to always feet in max - Math.ceil(oversize / groups.length) - - // we substitute size of group head - headerSize, - headerSize === 2 - ); - groups[i] = { - ...group, - children: limited.children, - filteredChildren: limited.filteredChildren - ? (group.filteredChildren || 0) + limited.filteredChildren - : group.filteredChildren - }; - const newSize = getItemSize(groups[i]); - groupsSize -= maxGroupSize - newSize; - groupSizes[i] = newSize; - break; - } - } + /** + * @param {string} context context used to create relative path + * @param {string} identifier identifier used to create relative path + * @returns {string} the returned relative path + */ + const boundFn = (context, identifier) => { + let cachedResult; + let innerSubCache = innerCache.get(context); + if (innerSubCache === undefined) { + innerCache.set(context, (innerSubCache = new Map())); + } else { + cachedResult = innerSubCache.get(identifier); + } + + if (cachedResult !== undefined) { + return cachedResult; + } else { + const result = fn(context, identifier); + innerSubCache.set(identifier, result); + return result; + } + }; + + return boundFn; + }; + + /** + * @param {string} context context used to create relative path + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {function(string): string} cached function + */ + cachedFn.bindContextCache = (context, associatedObjectForCache) => { + let innerSubCache; + if (associatedObjectForCache) { + let innerCache = cache.get(associatedObjectForCache); + if (innerCache === undefined) { + innerCache = new Map(); + cache.set(associatedObjectForCache, innerCache); + } + + innerSubCache = innerCache.get(context); + if (innerSubCache === undefined) { + innerCache.set(context, (innerSubCache = new Map())); } - children = groups.concat(items); - } else if (limit === max) { - // If we have only enough space to show one line per group and one line for the filtered items - // collapse all groups and items - children = collapse(groups); - filteredChildren = items.length; } else { - // If we have no space - // collapse complete group - filteredChildren = getTotalItems(itemsAndGroups); + innerSubCache = new Map(); } - } - return { - children, - filteredChildren + /** + * @param {string} identifier identifier used to create relative path + * @returns {string} the returned relative path + */ + const boundFn = identifier => { + const cachedResult = innerSubCache.get(identifier); + if (cachedResult !== undefined) { + return cachedResult; + } else { + const result = fn(context, identifier); + innerSubCache.set(identifier, result); + return result; + } + }; + + return boundFn; }; + + return cachedFn; }; -const assetGroup = (children, assets) => { - let size = 0; - for (const asset of children) { - size += asset.size; - } - return { - size - }; +/** + * + * @param {string} context context for relative path + * @param {string} identifier identifier for path + * @returns {string} a converted relative path + */ +const _makePathsRelative = (context, identifier) => { + return identifier + .split(SEGMENTS_SPLIT_REGEXP) + .map(str => absoluteToRequest(context, str)) + .join(""); }; -const moduleGroup = (children, modules) => { - let size = 0; - const sizes = {}; - for (const module of children) { - size += module.size; - for (const key of Object.keys(module.sizes)) { - sizes[key] = (sizes[key] || 0) + module.sizes[key]; - } - } - return { - size, - sizes - }; +exports.makePathsRelative = makeCacheable(_makePathsRelative); + +/** + * + * @param {string} context context for relative path + * @param {string} identifier identifier for path + * @returns {string} a converted relative path + */ +const _makePathsAbsolute = (context, identifier) => { + return identifier + .split(SEGMENTS_SPLIT_REGEXP) + .map(str => requestToAbsolute(context, str)) + .join(""); }; -const reasonGroup = (children, reasons) => { - let active = false; - for (const reason of children) { - active = active || reason.active; - } +exports.makePathsAbsolute = makeCacheable(_makePathsAbsolute); + +/** + * @param {string} context absolute context path + * @param {string} request any request string may containing absolute paths, query string, etc. + * @returns {string} a new request string avoiding absolute paths when possible + */ +const _contextify = (context, request) => { + return request + .split("!") + .map(r => absoluteToRequest(context, r)) + .join("!"); +}; + +const contextify = makeCacheable(_contextify); +exports.contextify = contextify; + +/** + * @param {string} context absolute context path + * @param {string} request any request string + * @returns {string} a new request string using absolute paths when possible + */ +const _absolutify = (context, request) => { + return request + .split("!") + .map(r => requestToAbsolute(context, r)) + .join("!"); +}; + +const absolutify = makeCacheable(_absolutify); +exports.absolutify = absolutify; + +const PATH_QUERY_FRAGMENT_REGEXP = + /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; + +/** @typedef {{ resource: string, path: string, query: string, fragment: string }} ParsedResource */ + +/** + * @param {string} str the path with query and fragment + * @returns {ParsedResource} parsed parts + */ +const _parseResource = str => { + const match = PATH_QUERY_FRAGMENT_REGEXP.exec(str); return { - active + resource: str, + path: match[1].replace(/\0(.)/g, "$1"), + query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "", + fragment: match[3] || "" }; }; +exports.parseResource = (realFn => { + /** @type {WeakMap>} */ + const cache = new WeakMap(); -const GROUP_EXTENSION_REGEXP = /(\.[^.]+?)(?:\?|(?: \+ \d+ modules?)?$)/; -const GROUP_PATH_REGEXP = /(.+)[/\\][^/\\]+?(?:\?|(?: \+ \d+ modules?)?$)/; + const getCache = associatedObjectForCache => { + const entry = cache.get(associatedObjectForCache); + if (entry !== undefined) return entry; + /** @type {Map} */ + const map = new Map(); + cache.set(associatedObjectForCache, map); + return map; + }; -/** @type {Record void>} */ -const ASSETS_GROUPERS = { - _: (groupConfigs, context, options) => { - const groupByFlag = (name, exclude) => { - groupConfigs.push({ - getKeys: asset => { - return asset[name] ? ["1"] : undefined; - }, - getOptions: () => { - return { - groupChildren: !exclude, - force: exclude - }; - }, - createGroup: (key, children, assets) => { - return exclude - ? { - type: "assets by status", - [name]: !!key, - filteredChildren: assets.length, - ...assetGroup(children, assets) - } - : { - type: "assets by status", - [name]: !!key, - children, - ...assetGroup(children, assets) - }; - } - }); + /** + * @param {string} str the path with query and fragment + * @param {Object=} associatedObjectForCache an object to which the cache will be attached + * @returns {ParsedResource} parsed parts + */ + const fn = (str, associatedObjectForCache) => { + if (!associatedObjectForCache) return realFn(str); + const cache = getCache(associatedObjectForCache); + const entry = cache.get(str); + if (entry !== undefined) return entry; + const result = realFn(str); + cache.set(str, result); + return result; + }; + + fn.bindCache = associatedObjectForCache => { + const cache = getCache(associatedObjectForCache); + return str => { + const entry = cache.get(str); + if (entry !== undefined) return entry; + const result = realFn(str); + cache.set(str, result); + return result; }; - const { - groupAssetsByEmitStatus, - groupAssetsByPath, - groupAssetsByExtension - } = options; - if (groupAssetsByEmitStatus) { - groupByFlag("emitted"); - groupByFlag("comparedForEmit"); - groupByFlag("isOverSizeLimit"); - } - if (groupAssetsByEmitStatus || !options.cachedAssets) { - groupByFlag("cached", !options.cachedAssets); - } - if (groupAssetsByPath || groupAssetsByExtension) { - groupConfigs.push({ - getKeys: asset => { - const extensionMatch = - groupAssetsByExtension && GROUP_EXTENSION_REGEXP.exec(asset.name); - const extension = extensionMatch ? extensionMatch[1] : ""; - const pathMatch = - groupAssetsByPath && GROUP_PATH_REGEXP.exec(asset.name); - const path = pathMatch ? pathMatch[1].split(/[/\\]/) : []; - const keys = []; - if (groupAssetsByPath) { - keys.push("."); - if (extension) - keys.push( - path.length - ? `${path.join("/")}/*${extension}` - : `*${extension}` - ); - while (path.length > 0) { - keys.push(path.join("/") + "/"); - path.pop(); - } - } else { - if (extension) keys.push(`*${extension}`); - } - return keys; - }, - createGroup: (key, children, assets) => { - return { - type: groupAssetsByPath ? "assets by path" : "assets by extension", - name: key, - children, - ...assetGroup(children, assets) - }; - } - }); + }; + + return fn; +})(_parseResource); + +/** + * @param {string} filename the filename which should be undone + * @param {string} outputPath the output path that is restored (only relevant when filename contains "..") + * @param {boolean} enforceRelative true returns ./ for empty paths + * @returns {string} repeated ../ to leave the directory of the provided filename to be back on output dir + */ +exports.getUndoPath = (filename, outputPath, enforceRelative) => { + let depth = -1; + let append = ""; + outputPath = outputPath.replace(/[\\/]$/, ""); + for (const part of filename.split(/[/\\]+/)) { + if (part === "..") { + if (depth > -1) { + depth--; + } else { + const i = outputPath.lastIndexOf("/"); + const j = outputPath.lastIndexOf("\\"); + const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j); + if (pos < 0) return outputPath + "/"; + append = outputPath.slice(pos + 1) + "/" + append; + outputPath = outputPath.slice(0, pos); + } + } else if (part !== ".") { + depth++; } - }, - groupAssetsByInfo: (groupConfigs, context, options) => { - const groupByAssetInfoFlag = name => { - groupConfigs.push({ - getKeys: asset => { - return asset.info && asset.info[name] ? ["1"] : undefined; - }, - createGroup: (key, children, assets) => { - return { - type: "assets by info", - info: { - [name]: !!key - }, - children, - ...assetGroup(children, assets) - }; - } - }); - }; - groupByAssetInfoFlag("immutable"); - groupByAssetInfoFlag("development"); - groupByAssetInfoFlag("hotModuleReplacement"); - }, - groupAssetsByChunk: (groupConfigs, context, options) => { - const groupByNames = name => { - groupConfigs.push({ - getKeys: asset => { - return asset[name]; - }, - createGroup: (key, children, assets) => { - return { - type: "assets by chunk", - [name]: [key], - children, - ...assetGroup(children, assets) - }; - } - }); - }; - groupByNames("chunkNames"); - groupByNames("auxiliaryChunkNames"); - groupByNames("chunkIdHints"); - groupByNames("auxiliaryChunkIdHints"); - }, - excludeAssets: (groupConfigs, context, { excludeAssets }) => { - groupConfigs.push({ - getKeys: asset => { - const ident = asset.name; - const excluded = excludeAssets.some(fn => fn(ident, asset)); - if (excluded) return ["excluded"]; - }, - getOptions: () => ({ - groupChildren: false, - force: true - }), - createGroup: (key, children, assets) => ({ - type: "hidden assets", - filteredChildren: assets.length, - ...assetGroup(children, assets) - }) - }); + } + return depth > 0 + ? `${"../".repeat(depth)}${append}` + : enforceRelative + ? `./${append}` + : append; +}; + + +/***/ }), + +/***/ 53023: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +// We need to include a list of requires here +// to allow webpack to be bundled with only static requires +// We could use a dynamic require(`../${request}`) but this +// would include too many modules and not every tool is able +// to process this +module.exports = { + AsyncDependenciesBlock: () => __webpack_require__(47736), + CommentCompilationWarning: () => __webpack_require__(98427), + ContextModule: () => __webpack_require__(76729), + "cache/PackFileCacheStrategy": () => + __webpack_require__(86180), + "cache/ResolverCachePlugin": () => __webpack_require__(97347), + "container/ContainerEntryDependency": () => + __webpack_require__(64813), + "container/ContainerEntryModule": () => + __webpack_require__(80580), + "container/ContainerExposedDependency": () => + __webpack_require__(72374), + "container/FallbackDependency": () => + __webpack_require__(57764), + "container/FallbackItemDependency": () => + __webpack_require__(29593), + "container/FallbackModule": () => __webpack_require__(82886), + "container/RemoteModule": () => __webpack_require__(62916), + "container/RemoteToExternalDependency": () => + __webpack_require__(14389), + "dependencies/AMDDefineDependency": () => + __webpack_require__(96816), + "dependencies/AMDRequireArrayDependency": () => + __webpack_require__(33516), + "dependencies/AMDRequireContextDependency": () => + __webpack_require__(96123), + "dependencies/AMDRequireDependenciesBlock": () => + __webpack_require__(76932), + "dependencies/AMDRequireDependency": () => + __webpack_require__(43911), + "dependencies/AMDRequireItemDependency": () => + __webpack_require__(71806), + "dependencies/CachedConstDependency": () => + __webpack_require__(57403), + "dependencies/CreateScriptUrlDependency": () => + __webpack_require__(79062), + "dependencies/CommonJsRequireContextDependency": () => + __webpack_require__(23962), + "dependencies/CommonJsExportRequireDependency": () => + __webpack_require__(62892), + "dependencies/CommonJsExportsDependency": () => + __webpack_require__(45598), + "dependencies/CommonJsFullRequireDependency": () => + __webpack_require__(59440), + "dependencies/CommonJsRequireDependency": () => + __webpack_require__(21264), + "dependencies/CommonJsSelfReferenceDependency": () => + __webpack_require__(52225), + "dependencies/ConstDependency": () => + __webpack_require__(76911), + "dependencies/ContextDependency": () => + __webpack_require__(88101), + "dependencies/ContextElementDependency": () => + __webpack_require__(58477), + "dependencies/CriticalDependencyWarning": () => + __webpack_require__(15427), + "dependencies/CssImportDependency": () => + __webpack_require__(90542), + "dependencies/CssLocalIdentifierDependency": () => + __webpack_require__(92328), + "dependencies/CssSelfLocalIdentifierDependency": () => + __webpack_require__(29094), + "dependencies/CssExportDependency": () => + __webpack_require__(76760), + "dependencies/CssUrlDependency": () => + __webpack_require__(70749), + "dependencies/DelegatedSourceDependency": () => + __webpack_require__(22914), + "dependencies/DllEntryDependency": () => + __webpack_require__(95666), + "dependencies/EntryDependency": () => + __webpack_require__(3979), + "dependencies/ExportsInfoDependency": () => + __webpack_require__(78988), + "dependencies/HarmonyAcceptDependency": () => + __webpack_require__(23624), + "dependencies/HarmonyAcceptImportDependency": () => + __webpack_require__(99843), + "dependencies/HarmonyCompatibilityDependency": () => + __webpack_require__(72906), + "dependencies/HarmonyExportExpressionDependency": () => + __webpack_require__(51340), + "dependencies/HarmonyExportHeaderDependency": () => + __webpack_require__(38873), + "dependencies/HarmonyExportImportedSpecifierDependency": () => + __webpack_require__(67157), + "dependencies/HarmonyExportSpecifierDependency": () => + __webpack_require__(48567), + "dependencies/HarmonyImportSideEffectDependency": () => + __webpack_require__(73132), + "dependencies/HarmonyImportSpecifierDependency": () => + __webpack_require__(14077), + "dependencies/ImportContextDependency": () => + __webpack_require__(1902), + "dependencies/ImportDependency": () => + __webpack_require__(89376), + "dependencies/ImportEagerDependency": () => + __webpack_require__(50718), + "dependencies/ImportWeakDependency": () => + __webpack_require__(82483), + "dependencies/JsonExportsDependency": () => + __webpack_require__(750), + "dependencies/LocalModule": () => __webpack_require__(5826), + "dependencies/LocalModuleDependency": () => + __webpack_require__(52805), + "dependencies/ModuleDecoratorDependency": () => + __webpack_require__(88488), + "dependencies/ModuleHotAcceptDependency": () => + __webpack_require__(47511), + "dependencies/ModuleHotDeclineDependency": () => + __webpack_require__(86301), + "dependencies/ImportMetaHotAcceptDependency": () => + __webpack_require__(51274), + "dependencies/ImportMetaHotDeclineDependency": () => + __webpack_require__(53141), + "dependencies/ProvidedDependency": () => + __webpack_require__(95770), + "dependencies/PureExpressionDependency": () => + __webpack_require__(55799), + "dependencies/RequireContextDependency": () => + __webpack_require__(46917), + "dependencies/RequireEnsureDependenciesBlock": () => + __webpack_require__(27153), + "dependencies/RequireEnsureDependency": () => + __webpack_require__(27223), + "dependencies/RequireEnsureItemDependency": () => + __webpack_require__(50329), + "dependencies/RequireHeaderDependency": () => + __webpack_require__(89183), + "dependencies/RequireIncludeDependency": () => + __webpack_require__(71284), + "dependencies/RequireIncludeDependencyParserPlugin": () => + __webpack_require__(35768), + "dependencies/RequireResolveContextDependency": () => + __webpack_require__(55627), + "dependencies/RequireResolveDependency": () => + __webpack_require__(68582), + "dependencies/RequireResolveHeaderDependency": () => + __webpack_require__(9880), + "dependencies/RuntimeRequirementsDependency": () => + __webpack_require__(24187), + "dependencies/StaticExportsDependency": () => + __webpack_require__(91418), + "dependencies/SystemPlugin": () => __webpack_require__(97981), + "dependencies/UnsupportedDependency": () => + __webpack_require__(51669), + "dependencies/URLDependency": () => __webpack_require__(58612), + "dependencies/WebAssemblyExportImportedDependency": () => + __webpack_require__(52204), + "dependencies/WebAssemblyImportDependency": () => + __webpack_require__(5239), + "dependencies/WebpackIsIncludedDependency": () => + __webpack_require__(26505), + "dependencies/WorkerDependency": () => + __webpack_require__(1466), + "json/JsonData": () => __webpack_require__(90490), + "optimize/ConcatenatedModule": () => + __webpack_require__(97198), + DelegatedModule: () => __webpack_require__(28623), + DependenciesBlock: () => __webpack_require__(71040), + DllModule: () => __webpack_require__(28280), + ExternalModule: () => __webpack_require__(73071), + FileSystemInfo: () => __webpack_require__(79453), + InitFragment: () => __webpack_require__(55870), + InvalidDependenciesModuleWarning: () => + __webpack_require__(68257), + Module: () => __webpack_require__(73208), + ModuleBuildError: () => __webpack_require__(21305), + ModuleDependencyWarning: () => __webpack_require__(29656), + ModuleError: () => __webpack_require__(23744), + ModuleGraph: () => __webpack_require__(99988), + ModuleParseError: () => __webpack_require__(58443), + ModuleWarning: () => __webpack_require__(11234), + NormalModule: () => __webpack_require__(39), + RawDataUrlModule: () => __webpack_require__(19684), + RawModule: () => __webpack_require__(84929), + "sharing/ConsumeSharedModule": () => + __webpack_require__(62286), + "sharing/ConsumeSharedFallbackDependency": () => + __webpack_require__(58831), + "sharing/ProvideSharedModule": () => + __webpack_require__(50821), + "sharing/ProvideSharedDependency": () => + __webpack_require__(1798), + "sharing/ProvideForSharedDependency": () => + __webpack_require__(40017), + UnsupportedFeatureWarning: () => __webpack_require__(42495), + "util/LazySet": () => __webpack_require__(38938), + UnhandledSchemeError: () => __webpack_require__(68099), + NodeStuffInWebError: () => __webpack_require__(6325), + WebpackError: () => __webpack_require__(53799), + + "util/registerExternalSerializer": () => { + // already registered } }; -/** @type {function("module" | "chunk" | "root-of-chunk" | "nested"): Record void>} */ -const MODULES_GROUPERS = type => ({ - _: (groupConfigs, context, options) => { - const groupByFlag = (name, type, exclude) => { - groupConfigs.push({ - getKeys: module => { - return module[name] ? ["1"] : undefined; - }, - getOptions: () => { - return { - groupChildren: !exclude, - force: exclude - }; - }, - createGroup: (key, children, modules) => { - return { - type, - [name]: !!key, - ...(exclude ? { filteredChildren: modules.length } : { children }), - ...moduleGroup(children, modules) - }; - } - }); - }; - const { - groupModulesByCacheStatus, - groupModulesByLayer, - groupModulesByAttributes, - groupModulesByType, - groupModulesByPath, - groupModulesByExtension - } = options; - if (groupModulesByAttributes) { - groupByFlag("errors", "modules with errors"); - groupByFlag("warnings", "modules with warnings"); - groupByFlag("assets", "modules with assets"); - groupByFlag("optional", "optional modules"); - } - if (groupModulesByCacheStatus) { - groupByFlag("cacheable", "cacheable modules"); - groupByFlag("built", "built modules"); - groupByFlag("codeGenerated", "code generated modules"); - } - if (groupModulesByCacheStatus || !options.cachedModules) { - groupByFlag("cached", "cached modules", !options.cachedModules); - } - if (groupModulesByAttributes || !options.orphanModules) { - groupByFlag("orphan", "orphan modules", !options.orphanModules); - } - if (groupModulesByAttributes || !options.dependentModules) { - groupByFlag("dependent", "dependent modules", !options.dependentModules); - } - if (groupModulesByType || !options.runtimeModules) { - groupConfigs.push({ - getKeys: module => { - if (!module.moduleType) return; - if (groupModulesByType) { - return [module.moduleType.split("/", 1)[0]]; - } else if (module.moduleType === "runtime") { - return ["runtime"]; - } - }, - getOptions: key => { - const exclude = key === "runtime" && !options.runtimeModules; - return { - groupChildren: !exclude, - force: exclude - }; - }, - createGroup: (key, children, modules) => { - const exclude = key === "runtime" && !options.runtimeModules; - return { - type: `${key} modules`, - moduleType: key, - ...(exclude ? { filteredChildren: modules.length } : { children }), - ...moduleGroup(children, modules) - }; - } - }); - } - if (groupModulesByLayer) { - groupConfigs.push({ - getKeys: module => { - return [module.layer]; - }, - createGroup: (key, children, modules) => { - return { - type: "modules by layer", - layer: key, - children, - ...moduleGroup(children, modules) - }; - } - }); - } - if (groupModulesByPath || groupModulesByExtension) { - groupConfigs.push({ - getKeys: module => { - if (!module.name) return; - const resource = parseResource(module.name.split("!").pop()).path; - const dataUrl = /^data:[^,;]+/.exec(resource); - if (dataUrl) return [dataUrl[0]]; - const extensionMatch = - groupModulesByExtension && GROUP_EXTENSION_REGEXP.exec(resource); - const extension = extensionMatch ? extensionMatch[1] : ""; - const pathMatch = - groupModulesByPath && GROUP_PATH_REGEXP.exec(resource); - const path = pathMatch ? pathMatch[1].split(/[/\\]/) : []; - const keys = []; - if (groupModulesByPath) { - if (extension) - keys.push( - path.length - ? `${path.join("/")}/*${extension}` - : `*${extension}` - ); - while (path.length > 0) { - keys.push(path.join("/") + "/"); - path.pop(); - } - } else { - if (extension) keys.push(`*${extension}`); - } - return keys; - }, - createGroup: (key, children, modules) => { - const isDataUrl = key.startsWith("data:"); - return { - type: isDataUrl - ? "modules by mime type" - : groupModulesByPath - ? "modules by path" - : "modules by extension", - name: isDataUrl ? key.slice(/* 'data:'.length */ 5) : key, - children, - ...moduleGroup(children, modules) - }; - } - }); - } - }, - excludeModules: (groupConfigs, context, { excludeModules }) => { - groupConfigs.push({ - getKeys: module => { - const name = module.name; - if (name) { - const excluded = excludeModules.some(fn => fn(name, module, type)); - if (excluded) return ["1"]; - } - }, - getOptions: () => ({ - groupChildren: false, - force: true - }), - createGroup: (key, children, modules) => ({ - type: "hidden modules", - filteredChildren: children.length, - ...moduleGroup(children, modules) - }) - }); - } -}); -/** @type {Record void>>} */ -const RESULT_GROUPERS = { - "compilation.assets": ASSETS_GROUPERS, - "asset.related": ASSETS_GROUPERS, - "compilation.modules": MODULES_GROUPERS("module"), - "chunk.modules": MODULES_GROUPERS("chunk"), - "chunk.rootModules": MODULES_GROUPERS("root-of-chunk"), - "module.modules": MODULES_GROUPERS("nested"), - "module.reasons": { - groupReasonsByOrigin: groupConfigs => { - groupConfigs.push({ - getKeys: reason => { - return [reason.module]; - }, - createGroup: (key, children, reasons) => { - return { - type: "from origin", - module: key, - children, - ...reasonGroup(children, reasons) - }; - } - }); - } - } -}; +/***/ }), -// remove a prefixed "!" that can be specified to reverse sort order -const normalizeFieldKey = field => { - if (field[0] === "!") { - return field.substr(1); +/***/ 33032: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const { register } = __webpack_require__(8282); + +class ClassSerializer { + constructor(Constructor) { + this.Constructor = Constructor; } - return field; -}; -// if a field is prefixed by a "!" reverse sort order -const sortOrderRegular = field => { - if (field[0] === "!") { - return false; + serialize(obj, context) { + obj.serialize(context); } - return true; -}; -/** - * @param {string} field field name - * @returns {function(Object, Object): number} comparators - */ -const sortByField = field => { - if (!field) { - /** - * @param {any} a first - * @param {any} b second - * @returns {-1|0|1} zero - */ - const noSort = (a, b) => 0; - return noSort; + deserialize(context) { + if (typeof this.Constructor.deserialize === "function") { + return this.Constructor.deserialize(context); + } + const obj = new this.Constructor(); + obj.deserialize(context); + return obj; } +} - const fieldKey = normalizeFieldKey(field); +module.exports = (Constructor, request, name = null) => { + register(Constructor, request, name, new ClassSerializer(Constructor)); +}; - let sortFn = compareSelect(m => m[fieldKey], compareIds); - // if a field is prefixed with a "!" the sort is reversed! - const sortIsRegular = sortOrderRegular(field); +/***/ }), - if (!sortIsRegular) { - const oldSortFn = sortFn; - sortFn = (a, b) => oldSortFn(b, a); - } +/***/ 78676: +/***/ (function(module) { - return sortFn; -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ -const ASSET_SORTERS = { - /** @type {(comparators: Function[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void} */ - assetsSort: (comparators, context, { assetsSort }) => { - comparators.push(sortByField(assetsSort)); - }, - _: comparators => { - comparators.push(compareSelect(a => a.name, compareIds)); - } -}; -/** @type {Record void>>} */ -const RESULT_SORTERS = { - "compilation.chunks": { - chunksSort: (comparators, context, { chunksSort }) => { - comparators.push(sortByField(chunksSort)); - } - }, - "compilation.modules": { - modulesSort: (comparators, context, { modulesSort }) => { - comparators.push(sortByField(modulesSort)); - } - }, - "chunk.modules": { - chunkModulesSort: (comparators, context, { chunkModulesSort }) => { - comparators.push(sortByField(chunkModulesSort)); - } - }, - "module.modules": { - nestedModulesSort: (comparators, context, { nestedModulesSort }) => { - comparators.push(sortByField(nestedModulesSort)); - } - }, - "compilation.assets": ASSET_SORTERS, - "asset.related": ASSET_SORTERS -}; + +/** @template T @typedef {function(): T} FunctionReturning */ /** - * @param {Record>} config the config see above - * @param {NormalizedStatsOptions} options stats options - * @param {function(string, Function): void} fn handler function called for every active line in config - * @returns {void} + * @template T + * @param {FunctionReturning} fn memorized function + * @returns {FunctionReturning} new function */ -const iterateConfig = (config, options, fn) => { - for (const hookFor of Object.keys(config)) { - const subConfig = config[hookFor]; - for (const option of Object.keys(subConfig)) { - if (option !== "_") { - if (option.startsWith("!")) { - if (options[option.slice(1)]) continue; - } else { - const value = options[option]; - if ( - value === false || - value === undefined || - (Array.isArray(value) && value.length === 0) - ) - continue; - } - } - fn(hookFor, subConfig[option]); +const memoize = fn => { + let cache = false; + /** @type {T} */ + let result = undefined; + return () => { + if (cache) { + return result; + } else { + result = fn(); + cache = true; + // Allow to clean up memory for fn + // and all dependent resources + fn = undefined; + return result; } - } + }; }; -/** @type {Record} */ -const ITEM_NAMES = { - "compilation.children[]": "compilation", - "compilation.modules[]": "module", - "compilation.entrypoints[]": "chunkGroup", - "compilation.namedChunkGroups[]": "chunkGroup", - "compilation.errors[]": "error", - "compilation.warnings[]": "warning", - "chunk.modules[]": "module", - "chunk.rootModules[]": "module", - "chunk.origins[]": "chunkOrigin", - "compilation.chunks[]": "chunk", - "compilation.assets[]": "asset", - "asset.related[]": "asset", - "module.issuerPath[]": "moduleIssuer", - "module.reasons[]": "moduleReason", - "module.modules[]": "module", - "module.children[]": "module", - "moduleTrace[]": "moduleTraceItem", - "moduleTraceItem.dependencies[]": "moduleTraceDependency" -}; +module.exports = memoize; -/** - * @param {Object[]} items items to be merged - * @returns {Object} an object - */ -const mergeToObject = items => { - const obj = Object.create(null); - for (const item of items) { - obj[item.name] = item; - } - return obj; -}; -/** @type {Record any>} */ -const MERGER = { - "compilation.entrypoints": mergeToObject, - "compilation.namedChunkGroups": mergeToObject -}; +/***/ }), -class DefaultStatsFactoryPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap("DefaultStatsFactoryPlugin", compilation => { - compilation.hooks.statsFactory.tap( - "DefaultStatsFactoryPlugin", - (stats, options, context) => { - iterateConfig(SIMPLE_EXTRACTORS, options, (hookFor, fn) => { - stats.hooks.extract - .for(hookFor) - .tap("DefaultStatsFactoryPlugin", (obj, data, ctx) => - fn(obj, data, ctx, options, stats) - ); - }); - iterateConfig(FILTER, options, (hookFor, fn) => { - stats.hooks.filter - .for(hookFor) - .tap("DefaultStatsFactoryPlugin", (item, ctx, idx, i) => - fn(item, ctx, options, idx, i) - ); - }); - iterateConfig(FILTER_RESULTS, options, (hookFor, fn) => { - stats.hooks.filterResults - .for(hookFor) - .tap("DefaultStatsFactoryPlugin", (item, ctx, idx, i) => - fn(item, ctx, options, idx, i) - ); - }); - iterateConfig(SORTERS, options, (hookFor, fn) => { - stats.hooks.sort - .for(hookFor) - .tap("DefaultStatsFactoryPlugin", (comparators, ctx) => - fn(comparators, ctx, options) - ); - }); - iterateConfig(RESULT_SORTERS, options, (hookFor, fn) => { - stats.hooks.sortResults - .for(hookFor) - .tap("DefaultStatsFactoryPlugin", (comparators, ctx) => - fn(comparators, ctx, options) - ); - }); - iterateConfig(RESULT_GROUPERS, options, (hookFor, fn) => { - stats.hooks.groupResults - .for(hookFor) - .tap("DefaultStatsFactoryPlugin", (groupConfigs, ctx) => - fn(groupConfigs, ctx, options) - ); - }); - for (const key of Object.keys(ITEM_NAMES)) { - const itemName = ITEM_NAMES[key]; - stats.hooks.getItemName - .for(key) - .tap("DefaultStatsFactoryPlugin", () => itemName); - } - for (const key of Object.keys(MERGER)) { - const merger = MERGER[key]; - stats.hooks.merge.for(key).tap("DefaultStatsFactoryPlugin", merger); - } - if (options.children) { - if (Array.isArray(options.children)) { - stats.hooks.getItemFactory - .for("compilation.children[].compilation") - .tap("DefaultStatsFactoryPlugin", (comp, { _index: idx }) => { - if (idx < options.children.length) { - return compilation.createStatsFactory( - compilation.createStatsOptions( - options.children[idx], - context - ) - ); - } - }); - } else if (options.children !== true) { - const childFactory = compilation.createStatsFactory( - compilation.createStatsOptions(options.children, context) - ); - stats.hooks.getItemFactory - .for("compilation.children[].compilation") - .tap("DefaultStatsFactoryPlugin", () => { - return childFactory; - }); - } - } - } - ); - }); +/***/ 70002: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const SAFE_LIMIT = 0x80000000; +const SAFE_PART = SAFE_LIMIT - 1; +const COUNT = 4; +const arr = [0, 0, 0, 0, 0]; +const primes = [3, 7, 17, 19]; + +module.exports = (str, range) => { + arr.fill(0); + for (let i = 0; i < str.length; i++) { + const c = str.charCodeAt(i); + for (let j = 0; j < COUNT; j++) { + const p = (j + COUNT - 1) % COUNT; + arr[j] = (arr[j] + c * primes[j] + arr[p]) & SAFE_PART; + } + for (let j = 0; j < COUNT; j++) { + const q = arr[j] % COUNT; + arr[j] = arr[j] ^ (arr[q] >> 1); + } } -} -module.exports = DefaultStatsFactoryPlugin; + if (range <= SAFE_PART) { + let sum = 0; + for (let j = 0; j < COUNT; j++) { + sum = (sum + arr[j]) % range; + } + return sum; + } else { + let sum1 = 0; + let sum2 = 0; + const rangeExt = Math.floor(range / SAFE_LIMIT); + for (let j = 0; j < COUNT; j += 2) { + sum1 = (sum1 + arr[j]) & SAFE_PART; + } + for (let j = 1; j < COUNT; j += 2) { + sum2 = (sum2 + arr[j]) % rangeExt; + } + return (sum2 * SAFE_LIMIT + sum1) % range; + } +}; /***/ }), -/***/ 55442: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 42791: +/***/ (function(module) { "use strict"; /* @@ -125994,331 +127135,153 @@ module.exports = DefaultStatsFactoryPlugin; -const RequestShortener = __webpack_require__(73406); +/** + * @template T + * @template {Error} E + * @param {Iterable} items initial items + * @param {number} concurrency number of items running in parallel + * @param {function(T, function(T): void, function(E=): void): void} processor worker which pushes more items + * @param {function(E=): void} callback all items processed + * @returns {void} + */ +const processAsyncTree = (items, concurrency, processor, callback) => { + const queue = Array.from(items); + if (queue.length === 0) return callback(); + let processing = 0; + let finished = false; + let processScheduled = true; -/** @typedef {import("../../declarations/WebpackOptions").StatsOptions} StatsOptions */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compilation").CreateStatsOptionsContext} CreateStatsOptionsContext */ -/** @typedef {import("../Compiler")} Compiler */ + const push = item => { + queue.push(item); + if (!processScheduled && processing < concurrency) { + processScheduled = true; + process.nextTick(processQueue); + } + }; -const applyDefaults = (options, defaults) => { - for (const key of Object.keys(defaults)) { - if (typeof options[key] === "undefined") { - options[key] = defaults[key]; + const processorCallback = err => { + processing--; + if (err && !finished) { + finished = true; + callback(err); + return; } - } -}; + if (!processScheduled) { + processScheduled = true; + process.nextTick(processQueue); + } + }; -const NAMED_PRESETS = { - verbose: { - hash: true, - builtAt: true, - relatedAssets: true, - entrypoints: true, - chunkGroups: true, - ids: true, - modules: false, - chunks: true, - chunkRelations: true, - chunkModules: true, - dependentModules: true, - chunkOrigins: true, - depth: true, - env: true, - reasons: true, - usedExports: true, - providedExports: true, - optimizationBailout: true, - errorDetails: true, - errorStack: true, - publicPath: true, - logging: "verbose", - orphanModules: true, - runtimeModules: true, - exclude: false, - modulesSpace: Infinity, - chunkModulesSpace: Infinity, - assetsSpace: Infinity, - reasonsSpace: Infinity, - children: true - }, - detailed: { - hash: true, - builtAt: true, - relatedAssets: true, - entrypoints: true, - chunkGroups: true, - ids: true, - chunks: true, - chunkRelations: true, - chunkModules: false, - chunkOrigins: true, - depth: true, - usedExports: true, - providedExports: true, - optimizationBailout: true, - errorDetails: true, - publicPath: true, - logging: true, - runtimeModules: true, - exclude: false, - modulesSpace: 1000, - assetsSpace: 1000, - reasonsSpace: 1000 - }, - minimal: { - all: false, - version: true, - timings: true, - modules: true, - modulesSpace: 0, - assets: true, - assetsSpace: 0, - errors: true, - errorsCount: true, - warnings: true, - warningsCount: true, - logging: "warn" - }, - "errors-only": { - all: false, - errors: true, - errorsCount: true, - moduleTrace: true, - logging: "error" - }, - "errors-warnings": { - all: false, - errors: true, - errorsCount: true, - warnings: true, - warningsCount: true, - logging: "warn" - }, - summary: { - all: false, - version: true, - errorsCount: true, - warningsCount: true - }, - none: { - all: false - } -}; + const processQueue = () => { + if (finished) return; + while (processing < concurrency && queue.length > 0) { + processing++; + const item = queue.pop(); + processor(item, push, processorCallback); + } + processScheduled = false; + if (queue.length === 0 && processing === 0 && !finished) { + finished = true; + callback(); + } + }; -const NORMAL_ON = ({ all }) => all !== false; -const NORMAL_OFF = ({ all }) => all === true; -const ON_FOR_TO_STRING = ({ all }, { forToString }) => - forToString ? all !== false : all === true; -const OFF_FOR_TO_STRING = ({ all }, { forToString }) => - forToString ? all === true : all !== false; -const AUTO_FOR_TO_STRING = ({ all }, { forToString }) => { - if (all === false) return false; - if (all === true) return true; - if (forToString) return "auto"; - return true; + processQueue(); }; -/** @type {Record any>} */ -const DEFAULTS = { - context: (options, context, compilation) => compilation.compiler.context, - requestShortener: (options, context, compilation) => - compilation.compiler.context === options.context - ? compilation.requestShortener - : new RequestShortener(options.context, compilation.compiler.root), - performance: NORMAL_ON, - hash: OFF_FOR_TO_STRING, - env: NORMAL_OFF, - version: NORMAL_ON, - timings: NORMAL_ON, - builtAt: OFF_FOR_TO_STRING, - assets: NORMAL_ON, - entrypoints: AUTO_FOR_TO_STRING, - chunkGroups: OFF_FOR_TO_STRING, - chunkGroupAuxiliary: OFF_FOR_TO_STRING, - chunkGroupChildren: OFF_FOR_TO_STRING, - chunkGroupMaxAssets: (o, { forToString }) => (forToString ? 5 : Infinity), - chunks: OFF_FOR_TO_STRING, - chunkRelations: OFF_FOR_TO_STRING, - chunkModules: ({ all, modules }) => { - if (all === false) return false; - if (all === true) return true; - if (modules) return false; - return true; - }, - dependentModules: OFF_FOR_TO_STRING, - chunkOrigins: OFF_FOR_TO_STRING, - ids: OFF_FOR_TO_STRING, - modules: ({ all, chunks, chunkModules }, { forToString }) => { - if (all === false) return false; - if (all === true) return true; - if (forToString && chunks && chunkModules) return false; - return true; - }, - nestedModules: OFF_FOR_TO_STRING, - groupModulesByType: ON_FOR_TO_STRING, - groupModulesByCacheStatus: ON_FOR_TO_STRING, - groupModulesByLayer: ON_FOR_TO_STRING, - groupModulesByAttributes: ON_FOR_TO_STRING, - groupModulesByPath: ON_FOR_TO_STRING, - groupModulesByExtension: ON_FOR_TO_STRING, - modulesSpace: (o, { forToString }) => (forToString ? 15 : Infinity), - chunkModulesSpace: (o, { forToString }) => (forToString ? 10 : Infinity), - nestedModulesSpace: (o, { forToString }) => (forToString ? 10 : Infinity), - relatedAssets: OFF_FOR_TO_STRING, - groupAssetsByEmitStatus: ON_FOR_TO_STRING, - groupAssetsByInfo: ON_FOR_TO_STRING, - groupAssetsByPath: ON_FOR_TO_STRING, - groupAssetsByExtension: ON_FOR_TO_STRING, - groupAssetsByChunk: ON_FOR_TO_STRING, - assetsSpace: (o, { forToString }) => (forToString ? 15 : Infinity), - orphanModules: OFF_FOR_TO_STRING, - runtimeModules: ({ all, runtime }, { forToString }) => - runtime !== undefined - ? runtime - : forToString - ? all === true - : all !== false, - cachedModules: ({ all, cached }, { forToString }) => - cached !== undefined ? cached : forToString ? all === true : all !== false, - moduleAssets: OFF_FOR_TO_STRING, - depth: OFF_FOR_TO_STRING, - cachedAssets: OFF_FOR_TO_STRING, - reasons: OFF_FOR_TO_STRING, - reasonsSpace: (o, { forToString }) => (forToString ? 15 : Infinity), - groupReasonsByOrigin: ON_FOR_TO_STRING, - usedExports: OFF_FOR_TO_STRING, - providedExports: OFF_FOR_TO_STRING, - optimizationBailout: OFF_FOR_TO_STRING, - children: OFF_FOR_TO_STRING, - source: NORMAL_OFF, - moduleTrace: NORMAL_ON, - errors: NORMAL_ON, - errorsCount: NORMAL_ON, - errorDetails: AUTO_FOR_TO_STRING, - errorStack: OFF_FOR_TO_STRING, - warnings: NORMAL_ON, - warningsCount: NORMAL_ON, - publicPath: OFF_FOR_TO_STRING, - logging: ({ all }, { forToString }) => - forToString && all !== false ? "info" : false, - loggingDebug: () => [], - loggingTrace: OFF_FOR_TO_STRING, - excludeModules: () => [], - excludeAssets: () => [], - modulesSort: () => "depth", - chunkModulesSort: () => "name", - nestedModulesSort: () => false, - chunksSort: () => false, - assetsSort: () => "!size", - outputPath: OFF_FOR_TO_STRING, - colors: () => false -}; +module.exports = processAsyncTree; -const normalizeFilter = item => { - if (typeof item === "string") { - const regExp = new RegExp( - `[\\\\/]${item.replace( - // eslint-disable-next-line no-useless-escape - /[-[\]{}()*+?.\\^$|]/g, - "\\$&" - )}([\\\\/]|$|!|\\?)` - ); - return ident => regExp.test(ident); - } - if (item && typeof item === "object" && typeof item.test === "function") { - return ident => item.test(ident); - } - if (typeof item === "function") { - return item; - } - if (typeof item === "boolean") { - return () => item; - } -}; -const NORMALIZER = { - excludeModules: value => { - if (!Array.isArray(value)) { - value = value ? [value] : []; - } - return value.map(normalizeFilter); - }, - excludeAssets: value => { - if (!Array.isArray(value)) { - value = value ? [value] : []; - } - return value.map(normalizeFilter); - }, - warningsFilter: value => { - if (!Array.isArray(value)) { - value = value ? [value] : []; - } - return value.map(filter => { - if (typeof filter === "string") { - return (warning, warningString) => warningString.includes(filter); - } - if (filter instanceof RegExp) { - return (warning, warningString) => filter.test(warningString); - } - if (typeof filter === "function") { - return filter; - } - throw new Error( - `Can only filter warnings with Strings or RegExps. (Given: ${filter})` - ); - }); - }, - logging: value => { - if (value === true) value = "log"; - return value; - }, - loggingDebug: value => { - if (!Array.isArray(value)) { - value = value ? [value] : []; +/***/ }), + +/***/ 54190: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const SAFE_IDENTIFIER = /^[_a-zA-Z$][_a-zA-Z$0-9]*$/; +const RESERVED_IDENTIFIER = new Set([ + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "export", + "extends", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "return", + "super", + "switch", + "this", + "throw", + "try", + "typeof", + "var", + "void", + "while", + "with", + "enum", + // strict mode + "implements", + "interface", + "let", + "package", + "private", + "protected", + "public", + "static", + "yield", + "yield", + // module code + "await", + // skip future reserved keywords defined under ES1 till ES3 + // additional + "null", + "true", + "false" +]); + +const propertyAccess = (properties, start = 0) => { + let str = ""; + for (let i = start; i < properties.length; i++) { + const p = properties[i]; + if (`${+p}` === p) { + str += `[${p}]`; + } else if (SAFE_IDENTIFIER.test(p) && !RESERVED_IDENTIFIER.has(p)) { + str += `.${p}`; + } else { + str += `[${JSON.stringify(p)}]`; } - return value.map(normalizeFilter); } + return str; }; -class DefaultStatsPresetPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap("DefaultStatsPresetPlugin", compilation => { - for (const key of Object.keys(NAMED_PRESETS)) { - const defaults = NAMED_PRESETS[key]; - compilation.hooks.statsPreset - .for(key) - .tap("DefaultStatsPresetPlugin", (options, context) => { - applyDefaults(options, defaults); - }); - } - compilation.hooks.statsNormalize.tap( - "DefaultStatsPresetPlugin", - (options, context) => { - for (const key of Object.keys(DEFAULTS)) { - if (options[key] === undefined) - options[key] = DEFAULTS[key](options, context, compilation); - } - for (const key of Object.keys(NORMALIZER)) { - options[key] = NORMALIZER[key](options[key]); - } - } - ); - }); - } -} -module.exports = DefaultStatsPresetPlugin; +module.exports = propertyAccess; /***/ }), -/***/ 58692: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 26611: +/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -126328,1385 +127291,973 @@ module.exports = DefaultStatsPresetPlugin; -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("./StatsPrinter")} StatsPrinter */ -/** @typedef {import("./StatsPrinter").StatsPrinterContext} StatsPrinterContext */ +const { register } = __webpack_require__(8282); -const DATA_URI_CONTENT_LENGTH = 16; +const Position = /** @type {TODO} */ (__webpack_require__(31988).Position); +const SourceLocation = (__webpack_require__(31988).SourceLocation); +const ValidationError = (__webpack_require__(54983)/* ["default"] */ .Z); +const { + CachedSource, + ConcatSource, + OriginalSource, + PrefixSource, + RawSource, + ReplaceSource, + SourceMapSource +} = __webpack_require__(51255); -const plural = (n, singular, plural) => (n === 1 ? singular : plural); +/** @typedef {import("acorn").Position} Position */ +/** @typedef {import("../Dependency").RealDependencyLocation} RealDependencyLocation */ +/** @typedef {import("../Dependency").SourcePosition} SourcePosition */ +/** @typedef {import("./serialization").ObjectDeserializerContext} ObjectDeserializerContext */ +/** @typedef {import("./serialization").ObjectSerializerContext} ObjectSerializerContext */ -/** - * @param {Record} sizes sizes by source type - * @param {Object} options options - * @param {(number) => string=} options.formatSize size formatter - * @returns {string} text - */ -const printSizes = (sizes, { formatSize = n => `${n}` }) => { - const keys = Object.keys(sizes); - if (keys.length > 1) { - return keys.map(key => `${formatSize(sizes[key])} (${key})`).join(" "); - } else if (keys.length === 1) { - return formatSize(sizes[keys[0]]); - } -}; +/** @typedef {ObjectSerializerContext & { writeLazy?: (any) => void }} WebpackObjectSerializerContext */ + +const CURRENT_MODULE = "webpack/lib/util/registerExternalSerializer"; + +register( + CachedSource, + CURRENT_MODULE, + "webpack-sources/CachedSource", + new (class CachedSourceSerializer { + /** + * @param {CachedSource} source the cached source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write, writeLazy }) { + if (writeLazy) { + writeLazy(source.originalLazy()); + } else { + write(source.original()); + } + write(source.getCachedData()); + } -const getResourceName = resource => { - const dataUrl = /^data:[^,]+,/.exec(resource); - if (!dataUrl) return resource; + /** + * @param {ObjectDeserializerContext} context context + * @returns {CachedSource} cached source + */ + deserialize({ read }) { + const source = read(); + const cachedData = read(); + return new CachedSource(source, cachedData); + } + })() +); - const len = dataUrl[0].length + DATA_URI_CONTENT_LENGTH; - if (resource.length < len) return resource; - return `${resource.slice( - 0, - Math.min(resource.length - /* '..'.length */ 2, len) - )}..`; -}; +register( + RawSource, + CURRENT_MODULE, + "webpack-sources/RawSource", + new (class RawSourceSerializer { + /** + * @param {RawSource} source the raw source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.buffer()); + write(!source.isBuffer()); + } -const getModuleName = name => { - const [, prefix, resource] = /^(.*!)?([^!]*)$/.exec(name); - return [prefix, getResourceName(resource)]; -}; + /** + * @param {ObjectDeserializerContext} context context + * @returns {RawSource} raw source + */ + deserialize({ read }) { + const source = read(); + const convertToString = read(); + return new RawSource(source, convertToString); + } + })() +); -const mapLines = (str, fn) => str.split("\n").map(fn).join("\n"); +register( + ConcatSource, + CURRENT_MODULE, + "webpack-sources/ConcatSource", + new (class ConcatSourceSerializer { + /** + * @param {ConcatSource} source the concat source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.getChildren()); + } -/** - * @param {number} n a number - * @returns {string} number as two digit string, leading 0 - */ -const twoDigit = n => (n >= 10 ? `${n}` : `0${n}`); + /** + * @param {ObjectDeserializerContext} context context + * @returns {ConcatSource} concat source + */ + deserialize({ read }) { + const source = new ConcatSource(); + source.addAllSkipOptimizing(read()); + return source; + } + })() +); -const isValidId = id => { - return typeof id === "number" || id; -}; +register( + PrefixSource, + CURRENT_MODULE, + "webpack-sources/PrefixSource", + new (class PrefixSourceSerializer { + /** + * @param {PrefixSource} source the prefix source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.getPrefix()); + write(source.original()); + } -const moreCount = (list, count) => { - return list && list.length > 0 ? `+ ${count}` : `${count}`; -}; + /** + * @param {ObjectDeserializerContext} context context + * @returns {PrefixSource} prefix source + */ + deserialize({ read }) { + return new PrefixSource(read(), read()); + } + })() +); -/** @type {Record string | void>} */ -const SIMPLE_PRINTERS = { - "compilation.summary!": ( - _, - { - type, - bold, - green, - red, - yellow, - formatDateTime, - formatTime, - compilation: { - name, - hash, - version, - time, - builtAt, - errorsCount, - warningsCount +register( + ReplaceSource, + CURRENT_MODULE, + "webpack-sources/ReplaceSource", + new (class ReplaceSourceSerializer { + /** + * @param {ReplaceSource} source the replace source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.original()); + write(source.getName()); + const replacements = source.getReplacements(); + write(replacements.length); + for (const repl of replacements) { + write(repl.start); + write(repl.end); } - } - ) => { - const root = type === "compilation.summary!"; - const warningsMessage = - warningsCount > 0 - ? yellow( - `${warningsCount} ${plural(warningsCount, "warning", "warnings")}` - ) - : ""; - const errorsMessage = - errorsCount > 0 - ? red(`${errorsCount} ${plural(errorsCount, "error", "errors")}`) - : ""; - const timeMessage = root && time ? ` in ${formatTime(time)}` : ""; - const hashMessage = hash ? ` (${hash})` : ""; - const builtAtMessage = - root && builtAt ? `${formatDateTime(builtAt)}: ` : ""; - const versionMessage = root && version ? `webpack ${version}` : ""; - const nameMessage = - root && name - ? bold(name) - : name - ? `Child ${bold(name)}` - : root - ? "" - : "Child"; - const subjectMessage = - nameMessage && versionMessage - ? `${nameMessage} (${versionMessage})` - : versionMessage || nameMessage || "webpack"; - let statusMessage; - if (errorsMessage && warningsMessage) { - statusMessage = `compiled with ${errorsMessage} and ${warningsMessage}`; - } else if (errorsMessage) { - statusMessage = `compiled with ${errorsMessage}`; - } else if (warningsMessage) { - statusMessage = `compiled with ${warningsMessage}`; - } else if (errorsCount === 0 && warningsCount === 0) { - statusMessage = `compiled ${green("successfully")}`; - } else { - statusMessage = `compiled`; - } - if ( - builtAtMessage || - versionMessage || - errorsMessage || - warningsMessage || - (errorsCount === 0 && warningsCount === 0) || - timeMessage || - hashMessage - ) - return `${builtAtMessage}${subjectMessage} ${statusMessage}${timeMessage}${hashMessage}`; - }, - "compilation.filteredWarningDetailsCount": count => - count - ? `${count} ${plural( - count, - "warning has", - "warnings have" - )} detailed information that is not shown.\nUse 'stats.errorDetails: true' resp. '--stats-error-details' to show it.` - : undefined, - "compilation.filteredErrorDetailsCount": (count, { yellow }) => - count - ? yellow( - `${count} ${plural( - count, - "error has", - "errors have" - )} detailed information that is not shown.\nUse 'stats.errorDetails: true' resp. '--stats-error-details' to show it.` - ) - : undefined, - "compilation.env": (env, { bold }) => - env - ? `Environment (--env): ${bold(JSON.stringify(env, null, 2))}` - : undefined, - "compilation.publicPath": (publicPath, { bold }) => - `PublicPath: ${bold(publicPath || "(none)")}`, - "compilation.entrypoints": (entrypoints, context, printer) => - Array.isArray(entrypoints) - ? undefined - : printer.print(context.type, Object.values(entrypoints), { - ...context, - chunkGroupKind: "Entrypoint" - }), - "compilation.namedChunkGroups": (namedChunkGroups, context, printer) => { - if (!Array.isArray(namedChunkGroups)) { - const { - compilation: { entrypoints } - } = context; - let chunkGroups = Object.values(namedChunkGroups); - if (entrypoints) { - chunkGroups = chunkGroups.filter( - group => - !Object.prototype.hasOwnProperty.call(entrypoints, group.name) - ); + for (const repl of replacements) { + write(repl.content); + write(repl.name); } - return printer.print(context.type, chunkGroups, { - ...context, - chunkGroupKind: "Chunk Group" - }); } - }, - "compilation.assetsByChunkName": () => "", - "compilation.filteredModules": ( - filteredModules, - { compilation: { modules } } - ) => - filteredModules > 0 - ? `${moreCount(modules, filteredModules)} ${plural( - filteredModules, - "module", - "modules" - )}` - : undefined, - "compilation.filteredAssets": (filteredAssets, { compilation: { assets } }) => - filteredAssets > 0 - ? `${moreCount(assets, filteredAssets)} ${plural( - filteredAssets, - "asset", - "assets" - )}` - : undefined, - "compilation.logging": (logging, context, printer) => - Array.isArray(logging) - ? undefined - : printer.print( - context.type, - Object.entries(logging).map(([name, value]) => ({ ...value, name })), - context - ), - "compilation.warningsInChildren!": (_, { yellow, compilation }) => { - if ( - !compilation.children && - compilation.warningsCount > 0 && - compilation.warnings - ) { - const childWarnings = - compilation.warningsCount - compilation.warnings.length; - if (childWarnings > 0) { - return yellow( - `${childWarnings} ${plural( - childWarnings, - "WARNING", - "WARNINGS" - )} in child compilations${ - compilation.children - ? "" - : " (Use 'stats.children: true' resp. '--stats-children' for more details)" - }` - ); + /** + * @param {ObjectDeserializerContext} context context + * @returns {ReplaceSource} replace source + */ + deserialize({ read }) { + const source = new ReplaceSource(read(), read()); + const len = read(); + const startEndBuffer = []; + for (let i = 0; i < len; i++) { + startEndBuffer.push(read(), read()); } - } - }, - "compilation.errorsInChildren!": (_, { red, compilation }) => { - if ( - !compilation.children && - compilation.errorsCount > 0 && - compilation.errors - ) { - const childErrors = compilation.errorsCount - compilation.errors.length; - if (childErrors > 0) { - return red( - `${childErrors} ${plural( - childErrors, - "ERROR", - "ERRORS" - )} in child compilations${ - compilation.children - ? "" - : " (Use 'stats.children: true' resp. '--stats-children' for more details)" - }` + let j = 0; + for (let i = 0; i < len; i++) { + source.replace( + startEndBuffer[j++], + startEndBuffer[j++], + read(), + read() ); } + return source; } - }, - - "asset.type": type => type, - "asset.name": (name, { formatFilename, asset: { isOverSizeLimit } }) => - formatFilename(name, isOverSizeLimit), - "asset.size": ( - size, - { asset: { isOverSizeLimit }, yellow, green, formatSize } - ) => (isOverSizeLimit ? yellow(formatSize(size)) : formatSize(size)), - "asset.emitted": (emitted, { green, formatFlag }) => - emitted ? green(formatFlag("emitted")) : undefined, - "asset.comparedForEmit": (comparedForEmit, { yellow, formatFlag }) => - comparedForEmit ? yellow(formatFlag("compared for emit")) : undefined, - "asset.cached": (cached, { green, formatFlag }) => - cached ? green(formatFlag("cached")) : undefined, - "asset.isOverSizeLimit": (isOverSizeLimit, { yellow, formatFlag }) => - isOverSizeLimit ? yellow(formatFlag("big")) : undefined, - - "asset.info.immutable": (immutable, { green, formatFlag }) => - immutable ? green(formatFlag("immutable")) : undefined, - "asset.info.javascriptModule": (javascriptModule, { formatFlag }) => - javascriptModule ? formatFlag("javascript module") : undefined, - "asset.info.sourceFilename": (sourceFilename, { formatFlag }) => - sourceFilename - ? formatFlag( - sourceFilename === true - ? "from source file" - : `from: ${sourceFilename}` - ) - : undefined, - "asset.info.development": (development, { green, formatFlag }) => - development ? green(formatFlag("dev")) : undefined, - "asset.info.hotModuleReplacement": ( - hotModuleReplacement, - { green, formatFlag } - ) => (hotModuleReplacement ? green(formatFlag("hmr")) : undefined), - "asset.separator!": () => "\n", - "asset.filteredRelated": (filteredRelated, { asset: { related } }) => - filteredRelated > 0 - ? `${moreCount(related, filteredRelated)} related ${plural( - filteredRelated, - "asset", - "assets" - )}` - : undefined, - "asset.filteredChildren": (filteredChildren, { asset: { children } }) => - filteredChildren > 0 - ? `${moreCount(children, filteredChildren)} ${plural( - filteredChildren, - "asset", - "assets" - )}` - : undefined, + })() +); - assetChunk: (id, { formatChunkId }) => formatChunkId(id), +register( + OriginalSource, + CURRENT_MODULE, + "webpack-sources/OriginalSource", + new (class OriginalSourceSerializer { + /** + * @param {OriginalSource} source the original source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.buffer()); + write(source.getName()); + } - assetChunkName: name => name, - assetChunkIdHint: name => name, + /** + * @param {ObjectDeserializerContext} context context + * @returns {OriginalSource} original source + */ + deserialize({ read }) { + const buffer = read(); + const name = read(); + return new OriginalSource(buffer, name); + } + })() +); - "module.type": type => (type !== "module" ? type : undefined), - "module.id": (id, { formatModuleId }) => - isValidId(id) ? formatModuleId(id) : undefined, - "module.name": (name, { bold }) => { - const [prefix, resource] = getModuleName(name); - return `${prefix || ""}${bold(resource || "")}`; - }, - "module.identifier": identifier => undefined, - "module.layer": (layer, { formatLayer }) => - layer ? formatLayer(layer) : undefined, - "module.sizes": printSizes, - "module.chunks[]": (id, { formatChunkId }) => formatChunkId(id), - "module.depth": (depth, { formatFlag }) => - depth !== null ? formatFlag(`depth ${depth}`) : undefined, - "module.cacheable": (cacheable, { formatFlag, red }) => - cacheable === false ? red(formatFlag("not cacheable")) : undefined, - "module.orphan": (orphan, { formatFlag, yellow }) => - orphan ? yellow(formatFlag("orphan")) : undefined, - "module.runtime": (runtime, { formatFlag, yellow }) => - runtime ? yellow(formatFlag("runtime")) : undefined, - "module.optional": (optional, { formatFlag, yellow }) => - optional ? yellow(formatFlag("optional")) : undefined, - "module.dependent": (dependent, { formatFlag, cyan }) => - dependent ? cyan(formatFlag("dependent")) : undefined, - "module.built": (built, { formatFlag, yellow }) => - built ? yellow(formatFlag("built")) : undefined, - "module.codeGenerated": (codeGenerated, { formatFlag, yellow }) => - codeGenerated ? yellow(formatFlag("code generated")) : undefined, - "module.buildTimeExecuted": (buildTimeExecuted, { formatFlag, green }) => - buildTimeExecuted ? green(formatFlag("build time executed")) : undefined, - "module.cached": (cached, { formatFlag, green }) => - cached ? green(formatFlag("cached")) : undefined, - "module.assets": (assets, { formatFlag, magenta }) => - assets && assets.length - ? magenta( - formatFlag( - `${assets.length} ${plural(assets.length, "asset", "assets")}` - ) - ) - : undefined, - "module.warnings": (warnings, { formatFlag, yellow }) => - warnings === true - ? yellow(formatFlag("warnings")) - : warnings - ? yellow( - formatFlag(`${warnings} ${plural(warnings, "warning", "warnings")}`) - ) - : undefined, - "module.errors": (errors, { formatFlag, red }) => - errors === true - ? red(formatFlag("errors")) - : errors - ? red(formatFlag(`${errors} ${plural(errors, "error", "errors")}`)) - : undefined, - "module.providedExports": (providedExports, { formatFlag, cyan }) => { - if (Array.isArray(providedExports)) { - if (providedExports.length === 0) return cyan(formatFlag("no exports")); - return cyan(formatFlag(`exports: ${providedExports.join(", ")}`)); +register( + SourceLocation, + CURRENT_MODULE, + "acorn/SourceLocation", + new (class SourceLocationSerializer { + /** + * @param {SourceLocation} loc the location to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(loc, { write }) { + write(loc.start.line); + write(loc.start.column); + write(loc.end.line); + write(loc.end.column); } - }, - "module.usedExports": (usedExports, { formatFlag, cyan, module }) => { - if (usedExports !== true) { - if (usedExports === null) return cyan(formatFlag("used exports unknown")); - if (usedExports === false) return cyan(formatFlag("module unused")); - if (Array.isArray(usedExports)) { - if (usedExports.length === 0) - return cyan(formatFlag("no exports used")); - const providedExportsCount = Array.isArray(module.providedExports) - ? module.providedExports.length - : null; - if ( - providedExportsCount !== null && - providedExportsCount === usedExports.length - ) { - return cyan(formatFlag("all exports used")); - } else { - return cyan( - formatFlag(`only some exports used: ${usedExports.join(", ")}`) - ); + + /** + * @param {ObjectDeserializerContext} context context + * @returns {RealDependencyLocation} location + */ + deserialize({ read }) { + return { + start: { + line: read(), + column: read() + }, + end: { + line: read(), + column: read() } - } + }; } - }, - "module.optimizationBailout[]": (optimizationBailout, { yellow }) => - yellow(optimizationBailout), - "module.issuerPath": (issuerPath, { module }) => - module.profile ? undefined : "", - "module.profile": profile => undefined, - "module.filteredModules": (filteredModules, { module: { modules } }) => - filteredModules > 0 - ? `${moreCount(modules, filteredModules)} nested ${plural( - filteredModules, - "module", - "modules" - )}` - : undefined, - "module.filteredReasons": (filteredReasons, { module: { reasons } }) => - filteredReasons > 0 - ? `${moreCount(reasons, filteredReasons)} ${plural( - filteredReasons, - "reason", - "reasons" - )}` - : undefined, - "module.filteredChildren": (filteredChildren, { module: { children } }) => - filteredChildren > 0 - ? `${moreCount(children, filteredChildren)} ${plural( - filteredChildren, - "module", - "modules" - )}` - : undefined, - "module.separator!": () => "\n", - - "moduleIssuer.id": (id, { formatModuleId }) => formatModuleId(id), - "moduleIssuer.profile.total": (value, { formatTime }) => formatTime(value), - - "moduleReason.type": type => type, - "moduleReason.userRequest": (userRequest, { cyan }) => - cyan(getResourceName(userRequest)), - "moduleReason.moduleId": (moduleId, { formatModuleId }) => - isValidId(moduleId) ? formatModuleId(moduleId) : undefined, - "moduleReason.module": (module, { magenta }) => magenta(module), - "moduleReason.loc": loc => loc, - "moduleReason.explanation": (explanation, { cyan }) => cyan(explanation), - "moduleReason.active": (active, { formatFlag }) => - active ? undefined : formatFlag("inactive"), - "moduleReason.resolvedModule": (module, { magenta }) => magenta(module), - "moduleReason.filteredChildren": ( - filteredChildren, - { moduleReason: { children } } - ) => - filteredChildren > 0 - ? `${moreCount(children, filteredChildren)} ${plural( - filteredChildren, - "reason", - "reasons" - )}` - : undefined, - - "module.profile.total": (value, { formatTime }) => formatTime(value), - "module.profile.resolving": (value, { formatTime }) => - `resolving: ${formatTime(value)}`, - "module.profile.restoring": (value, { formatTime }) => - `restoring: ${formatTime(value)}`, - "module.profile.integration": (value, { formatTime }) => - `integration: ${formatTime(value)}`, - "module.profile.building": (value, { formatTime }) => - `building: ${formatTime(value)}`, - "module.profile.storing": (value, { formatTime }) => - `storing: ${formatTime(value)}`, - "module.profile.additionalResolving": (value, { formatTime }) => - value ? `additional resolving: ${formatTime(value)}` : undefined, - "module.profile.additionalIntegration": (value, { formatTime }) => - value ? `additional integration: ${formatTime(value)}` : undefined, - - "chunkGroup.kind!": (_, { chunkGroupKind }) => chunkGroupKind, - "chunkGroup.separator!": () => "\n", - "chunkGroup.name": (name, { bold }) => bold(name), - "chunkGroup.isOverSizeLimit": (isOverSizeLimit, { formatFlag, yellow }) => - isOverSizeLimit ? yellow(formatFlag("big")) : undefined, - "chunkGroup.assetsSize": (size, { formatSize }) => - size ? formatSize(size) : undefined, - "chunkGroup.auxiliaryAssetsSize": (size, { formatSize }) => - size ? `(${formatSize(size)})` : undefined, - "chunkGroup.filteredAssets": (n, { chunkGroup: { assets } }) => - n > 0 - ? `${moreCount(assets, n)} ${plural(n, "asset", "assets")}` - : undefined, - "chunkGroup.filteredAuxiliaryAssets": ( - n, - { chunkGroup: { auxiliaryAssets } } - ) => - n > 0 - ? `${moreCount(auxiliaryAssets, n)} auxiliary ${plural( - n, - "asset", - "assets" - )}` - : undefined, - "chunkGroup.is!": () => "=", - "chunkGroupAsset.name": (asset, { green }) => green(asset), - "chunkGroupAsset.size": (size, { formatSize, chunkGroup }) => - chunkGroup.assets.length > 1 || - (chunkGroup.auxiliaryAssets && chunkGroup.auxiliaryAssets.length > 0) - ? formatSize(size) - : undefined, - "chunkGroup.children": (children, context, printer) => - Array.isArray(children) - ? undefined - : printer.print( - context.type, - Object.keys(children).map(key => ({ - type: key, - children: children[key] - })), - context - ), - "chunkGroupChildGroup.type": type => `${type}:`, - "chunkGroupChild.assets[]": (file, { formatFilename }) => - formatFilename(file), - "chunkGroupChild.chunks[]": (id, { formatChunkId }) => formatChunkId(id), - "chunkGroupChild.name": name => (name ? `(name: ${name})` : undefined), - - "chunk.id": (id, { formatChunkId }) => formatChunkId(id), - "chunk.files[]": (file, { formatFilename }) => formatFilename(file), - "chunk.names[]": name => name, - "chunk.idHints[]": name => name, - "chunk.runtime[]": name => name, - "chunk.sizes": (sizes, context) => printSizes(sizes, context), - "chunk.parents[]": (parents, context) => - context.formatChunkId(parents, "parent"), - "chunk.siblings[]": (siblings, context) => - context.formatChunkId(siblings, "sibling"), - "chunk.children[]": (children, context) => - context.formatChunkId(children, "child"), - "chunk.childrenByOrder": (childrenByOrder, context, printer) => - Array.isArray(childrenByOrder) - ? undefined - : printer.print( - context.type, - Object.keys(childrenByOrder).map(key => ({ - type: key, - children: childrenByOrder[key] - })), - context - ), - "chunk.childrenByOrder[].type": type => `${type}:`, - "chunk.childrenByOrder[].children[]": (id, { formatChunkId }) => - isValidId(id) ? formatChunkId(id) : undefined, - "chunk.entry": (entry, { formatFlag, yellow }) => - entry ? yellow(formatFlag("entry")) : undefined, - "chunk.initial": (initial, { formatFlag, yellow }) => - initial ? yellow(formatFlag("initial")) : undefined, - "chunk.rendered": (rendered, { formatFlag, green }) => - rendered ? green(formatFlag("rendered")) : undefined, - "chunk.recorded": (recorded, { formatFlag, green }) => - recorded ? green(formatFlag("recorded")) : undefined, - "chunk.reason": (reason, { yellow }) => (reason ? yellow(reason) : undefined), - "chunk.filteredModules": (filteredModules, { chunk: { modules } }) => - filteredModules > 0 - ? `${moreCount(modules, filteredModules)} chunk ${plural( - filteredModules, - "module", - "modules" - )}` - : undefined, - "chunk.separator!": () => "\n", - - "chunkOrigin.request": request => request, - "chunkOrigin.moduleId": (moduleId, { formatModuleId }) => - isValidId(moduleId) ? formatModuleId(moduleId) : undefined, - "chunkOrigin.moduleName": (moduleName, { bold }) => bold(moduleName), - "chunkOrigin.loc": loc => loc, - - "error.compilerPath": (compilerPath, { bold }) => - compilerPath ? bold(`(${compilerPath})`) : undefined, - "error.chunkId": (chunkId, { formatChunkId }) => - isValidId(chunkId) ? formatChunkId(chunkId) : undefined, - "error.chunkEntry": (chunkEntry, { formatFlag }) => - chunkEntry ? formatFlag("entry") : undefined, - "error.chunkInitial": (chunkInitial, { formatFlag }) => - chunkInitial ? formatFlag("initial") : undefined, - "error.file": (file, { bold }) => bold(file), - "error.moduleName": (moduleName, { bold }) => { - return moduleName.includes("!") - ? `${bold(moduleName.replace(/^(\s|\S)*!/, ""))} (${moduleName})` - : `${bold(moduleName)}`; - }, - "error.loc": (loc, { green }) => green(loc), - "error.message": (message, { bold, formatError }) => - message.includes("\u001b[") ? message : bold(formatError(message)), - "error.details": (details, { formatError }) => formatError(details), - "error.stack": stack => stack, - "error.moduleTrace": moduleTrace => undefined, - "error.separator!": () => "\n", - - "loggingEntry(error).loggingEntry.message": (message, { red }) => - mapLines(message, x => ` ${red(x)}`), - "loggingEntry(warn).loggingEntry.message": (message, { yellow }) => - mapLines(message, x => ` ${yellow(x)}`), - "loggingEntry(info).loggingEntry.message": (message, { green }) => - mapLines(message, x => ` ${green(x)}`), - "loggingEntry(log).loggingEntry.message": (message, { bold }) => - mapLines(message, x => ` ${bold(x)}`), - "loggingEntry(debug).loggingEntry.message": message => - mapLines(message, x => ` ${x}`), - "loggingEntry(trace).loggingEntry.message": message => - mapLines(message, x => ` ${x}`), - "loggingEntry(status).loggingEntry.message": (message, { magenta }) => - mapLines(message, x => ` ${magenta(x)}`), - "loggingEntry(profile).loggingEntry.message": (message, { magenta }) => - mapLines(message, x => `

${magenta(x)}`), - "loggingEntry(profileEnd).loggingEntry.message": (message, { magenta }) => - mapLines(message, x => `

${magenta(x)}`), - "loggingEntry(time).loggingEntry.message": (message, { magenta }) => - mapLines(message, x => ` ${magenta(x)}`), - "loggingEntry(group).loggingEntry.message": (message, { cyan }) => - mapLines(message, x => `<-> ${cyan(x)}`), - "loggingEntry(groupCollapsed).loggingEntry.message": (message, { cyan }) => - mapLines(message, x => `<+> ${cyan(x)}`), - "loggingEntry(clear).loggingEntry": () => " -------", - "loggingEntry(groupCollapsed).loggingEntry.children": () => "", - "loggingEntry.trace[]": trace => - trace ? mapLines(trace, x => `| ${x}`) : undefined, - - "moduleTraceItem.originName": originName => originName, - - loggingGroup: loggingGroup => - loggingGroup.entries.length === 0 ? "" : undefined, - "loggingGroup.debug": (flag, { red }) => (flag ? red("DEBUG") : undefined), - "loggingGroup.name": (name, { bold }) => bold(`LOG from ${name}`), - "loggingGroup.separator!": () => "\n", - "loggingGroup.filteredEntries": filteredEntries => - filteredEntries > 0 ? `+ ${filteredEntries} hidden lines` : undefined, - - "moduleTraceDependency.loc": loc => loc -}; + })() +); -/** @type {Record} */ -const ITEM_NAMES = { - "compilation.assets[]": "asset", - "compilation.modules[]": "module", - "compilation.chunks[]": "chunk", - "compilation.entrypoints[]": "chunkGroup", - "compilation.namedChunkGroups[]": "chunkGroup", - "compilation.errors[]": "error", - "compilation.warnings[]": "error", - "compilation.logging[]": "loggingGroup", - "compilation.children[]": "compilation", - "asset.related[]": "asset", - "asset.children[]": "asset", - "asset.chunks[]": "assetChunk", - "asset.auxiliaryChunks[]": "assetChunk", - "asset.chunkNames[]": "assetChunkName", - "asset.chunkIdHints[]": "assetChunkIdHint", - "asset.auxiliaryChunkNames[]": "assetChunkName", - "asset.auxiliaryChunkIdHints[]": "assetChunkIdHint", - "chunkGroup.assets[]": "chunkGroupAsset", - "chunkGroup.auxiliaryAssets[]": "chunkGroupAsset", - "chunkGroupChild.assets[]": "chunkGroupAsset", - "chunkGroupChild.auxiliaryAssets[]": "chunkGroupAsset", - "chunkGroup.children[]": "chunkGroupChildGroup", - "chunkGroupChildGroup.children[]": "chunkGroupChild", - "module.modules[]": "module", - "module.children[]": "module", - "module.reasons[]": "moduleReason", - "moduleReason.children[]": "moduleReason", - "module.issuerPath[]": "moduleIssuer", - "chunk.origins[]": "chunkOrigin", - "chunk.modules[]": "module", - "loggingGroup.entries[]": logEntry => - `loggingEntry(${logEntry.type}).loggingEntry`, - "loggingEntry.children[]": logEntry => - `loggingEntry(${logEntry.type}).loggingEntry`, - "error.moduleTrace[]": "moduleTraceItem", - "moduleTraceItem.dependencies[]": "moduleTraceDependency" -}; +register( + Position, + CURRENT_MODULE, + "acorn/Position", + new (class PositionSerializer { + /** + * @param {Position} pos the position to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(pos, { write }) { + write(pos.line); + write(pos.column); + } -const ERROR_PREFERRED_ORDER = [ - "compilerPath", - "chunkId", - "chunkEntry", - "chunkInitial", - "file", - "separator!", - "moduleName", - "loc", - "separator!", - "message", - "separator!", - "details", - "separator!", - "stack", - "separator!", - "missing", - "separator!", - "moduleTrace" -]; + /** + * @param {ObjectDeserializerContext} context context + * @returns {SourcePosition} position + */ + deserialize({ read }) { + return { + line: read(), + column: read() + }; + } + })() +); -/** @type {Record} */ -const PREFERRED_ORDERS = { - compilation: [ - "name", - "hash", - "version", - "time", - "builtAt", - "env", - "publicPath", - "assets", - "filteredAssets", - "entrypoints", - "namedChunkGroups", - "chunks", - "modules", - "filteredModules", - "children", - "logging", - "warnings", - "warningsInChildren!", - "filteredWarningDetailsCount", - "errors", - "errorsInChildren!", - "filteredErrorDetailsCount", - "summary!", - "needAdditionalPass" - ], - asset: [ - "type", - "name", - "size", - "chunks", - "auxiliaryChunks", - "emitted", - "comparedForEmit", - "cached", - "info", - "isOverSizeLimit", - "chunkNames", - "auxiliaryChunkNames", - "chunkIdHints", - "auxiliaryChunkIdHints", - "related", - "filteredRelated", - "children", - "filteredChildren" - ], - "asset.info": [ - "immutable", - "sourceFilename", - "javascriptModule", - "development", - "hotModuleReplacement" - ], - chunkGroup: [ - "kind!", - "name", - "isOverSizeLimit", - "assetsSize", - "auxiliaryAssetsSize", - "is!", - "assets", - "filteredAssets", - "auxiliaryAssets", - "filteredAuxiliaryAssets", - "separator!", - "children" - ], - chunkGroupAsset: ["name", "size"], - chunkGroupChildGroup: ["type", "children"], - chunkGroupChild: ["assets", "chunks", "name"], - module: [ - "type", - "name", - "identifier", - "id", - "layer", - "sizes", - "chunks", - "depth", - "cacheable", - "orphan", - "runtime", - "optional", - "dependent", - "built", - "codeGenerated", - "cached", - "assets", - "failed", - "warnings", - "errors", - "children", - "filteredChildren", - "providedExports", - "usedExports", - "optimizationBailout", - "reasons", - "filteredReasons", - "issuerPath", - "profile", - "modules", - "filteredModules" - ], - moduleReason: [ - "active", - "type", - "userRequest", - "moduleId", - "module", - "resolvedModule", - "loc", - "explanation", - "children", - "filteredChildren" - ], - "module.profile": [ - "total", - "separator!", - "resolving", - "restoring", - "integration", - "building", - "storing", - "additionalResolving", - "additionalIntegration" - ], - chunk: [ - "id", - "runtime", - "files", - "names", - "idHints", - "sizes", - "parents", - "siblings", - "children", - "childrenByOrder", - "entry", - "initial", - "rendered", - "recorded", - "reason", - "separator!", - "origins", - "separator!", - "modules", - "separator!", - "filteredModules" - ], - chunkOrigin: ["request", "moduleId", "moduleName", "loc"], - error: ERROR_PREFERRED_ORDER, - warning: ERROR_PREFERRED_ORDER, - "chunk.childrenByOrder[]": ["type", "children"], - loggingGroup: [ - "debug", - "name", - "separator!", - "entries", - "separator!", - "filteredEntries" - ], - loggingEntry: ["message", "trace", "children"] -}; +register( + SourceMapSource, + CURRENT_MODULE, + "webpack-sources/SourceMapSource", + new (class SourceMapSourceSerializer { + /** + * @param {SourceMapSource} source the source map source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(source, { write }) { + write(source.getArgsAsBuffers()); + } -const itemsJoinOneLine = items => items.filter(Boolean).join(" "); -const itemsJoinOneLineBrackets = items => - items.length > 0 ? `(${items.filter(Boolean).join(" ")})` : undefined; -const itemsJoinMoreSpacing = items => items.filter(Boolean).join("\n\n"); -const itemsJoinComma = items => items.filter(Boolean).join(", "); -const itemsJoinCommaBrackets = items => - items.length > 0 ? `(${items.filter(Boolean).join(", ")})` : undefined; -const itemsJoinCommaBracketsWithName = name => items => - items.length > 0 - ? `(${name}: ${items.filter(Boolean).join(", ")})` - : undefined; + /** + * @param {ObjectDeserializerContext} context context + * @returns {SourceMapSource} source source map source + */ + deserialize({ read }) { + // @ts-expect-error + return new SourceMapSource(...read()); + } + })() +); -/** @type {Record string>} */ -const SIMPLE_ITEMS_JOINER = { - "chunk.parents": itemsJoinOneLine, - "chunk.siblings": itemsJoinOneLine, - "chunk.children": itemsJoinOneLine, - "chunk.names": itemsJoinCommaBrackets, - "chunk.idHints": itemsJoinCommaBracketsWithName("id hint"), - "chunk.runtime": itemsJoinCommaBracketsWithName("runtime"), - "chunk.files": itemsJoinComma, - "chunk.childrenByOrder": itemsJoinOneLine, - "chunk.childrenByOrder[].children": itemsJoinOneLine, - "chunkGroup.assets": itemsJoinOneLine, - "chunkGroup.auxiliaryAssets": itemsJoinOneLineBrackets, - "chunkGroupChildGroup.children": itemsJoinComma, - "chunkGroupChild.assets": itemsJoinOneLine, - "chunkGroupChild.auxiliaryAssets": itemsJoinOneLineBrackets, - "asset.chunks": itemsJoinComma, - "asset.auxiliaryChunks": itemsJoinCommaBrackets, - "asset.chunkNames": itemsJoinCommaBracketsWithName("name"), - "asset.auxiliaryChunkNames": itemsJoinCommaBracketsWithName("auxiliary name"), - "asset.chunkIdHints": itemsJoinCommaBracketsWithName("id hint"), - "asset.auxiliaryChunkIdHints": - itemsJoinCommaBracketsWithName("auxiliary id hint"), - "module.chunks": itemsJoinOneLine, - "module.issuerPath": items => - items - .filter(Boolean) - .map(item => `${item} ->`) - .join(" "), - "compilation.errors": itemsJoinMoreSpacing, - "compilation.warnings": itemsJoinMoreSpacing, - "compilation.logging": itemsJoinMoreSpacing, - "compilation.children": items => indent(itemsJoinMoreSpacing(items), " "), - "moduleTraceItem.dependencies": itemsJoinOneLine, - "loggingEntry.children": items => - indent(items.filter(Boolean).join("\n"), " ", false) -}; +register( + ValidationError, + CURRENT_MODULE, + "schema-utils/ValidationError", + new (class ValidationErrorSerializer { + // TODO error should be ValidationError, but this fails the type checks + /** + * @param {TODO} error the source map source to be serialized + * @param {WebpackObjectSerializerContext} context context + * @returns {void} + */ + serialize(error, { write }) { + write(error.errors); + write(error.schema); + write({ + name: error.headerName, + baseDataPath: error.baseDataPath, + postFormatter: error.postFormatter + }); + } -const joinOneLine = items => - items - .map(item => item.content) - .filter(Boolean) - .join(" "); + /** + * @param {ObjectDeserializerContext} context context + * @returns {TODO} error + */ + deserialize({ read }) { + return new ValidationError(read(), read(), read()); + } + })() +); -const joinInBrackets = items => { - const res = []; - let mode = 0; - for (const item of items) { - if (item.element === "separator!") { - switch (mode) { - case 0: - case 1: - mode += 2; - break; - case 4: - res.push(")"); - mode = 3; - break; + +/***/ }), + +/***/ 17156: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const SortableSet = __webpack_require__(13098); + +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */ + +/** @typedef {string | SortableSet | undefined} RuntimeSpec */ +/** @typedef {RuntimeSpec | boolean} RuntimeCondition */ + +/** + * @param {Compilation} compilation the compilation + * @param {string} name name of the entry + * @param {EntryOptions=} options optionally already received entry options + * @returns {RuntimeSpec} runtime + */ +exports.getEntryRuntime = (compilation, name, options) => { + let dependOn; + let runtime; + if (options) { + ({ dependOn, runtime } = options); + } else { + const entry = compilation.entries.get(name); + if (!entry) return name; + ({ dependOn, runtime } = entry.options); + } + if (dependOn) { + /** @type {RuntimeSpec} */ + let result = undefined; + const queue = new Set(dependOn); + for (const name of queue) { + const dep = compilation.entries.get(name); + if (!dep) continue; + const { dependOn, runtime } = dep.options; + if (dependOn) { + for (const name of dependOn) { + queue.add(name); + } + } else { + result = mergeRuntimeOwned(result, runtime || name); } } - if (!item.content) continue; - switch (mode) { - case 0: - mode = 1; - break; - case 1: - res.push(" "); - break; - case 2: - res.push("("); - mode = 4; - break; - case 3: - res.push(" ("); - mode = 4; - break; - case 4: - res.push(", "); - break; + return result || name; + } else { + return runtime || name; + } +}; + +/** + * @param {RuntimeSpec} runtime runtime + * @param {function(string): void} fn functor + * @param {boolean} deterministicOrder enforce a deterministic order + * @returns {void} + */ +exports.forEachRuntime = (runtime, fn, deterministicOrder = false) => { + if (runtime === undefined) { + fn(undefined); + } else if (typeof runtime === "string") { + fn(runtime); + } else { + if (deterministicOrder) runtime.sort(); + for (const r of runtime) { + fn(r); } - res.push(item.content); } - if (mode === 4) res.push(")"); - return res.join(""); }; -const indent = (str, prefix, noPrefixInFirstLine) => { - const rem = str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); - if (noPrefixInFirstLine) return rem; - const ind = str[0] === "\n" ? "" : prefix; - return ind + rem; +const getRuntimesKey = set => { + set.sort(); + return Array.from(set).join("\n"); }; -const joinExplicitNewLine = (items, indenter) => { - let firstInLine = true; - let first = true; - return items - .map(item => { - if (!item || !item.content) return; - let content = indent(item.content, first ? "" : indenter, !firstInLine); - if (firstInLine) { - content = content.replace(/^\n+/, ""); - } - if (!content) return; - first = false; - const noJoiner = firstInLine || content.startsWith("\n"); - firstInLine = content.endsWith("\n"); - return noJoiner ? content : " " + content; - }) - .filter(Boolean) - .join("") - .trim(); +/** + * @param {RuntimeSpec} runtime runtime(s) + * @returns {string} key of runtimes + */ +const getRuntimeKey = runtime => { + if (runtime === undefined) return "*"; + if (typeof runtime === "string") return runtime; + return runtime.getFromUnorderedCache(getRuntimesKey); }; +exports.getRuntimeKey = getRuntimeKey; -const joinError = - error => - (items, { red, yellow }) => - `${error ? red("ERROR") : yellow("WARNING")} in ${joinExplicitNewLine( - items, - "" - )}`; +/** + * @param {string} key key of runtimes + * @returns {RuntimeSpec} runtime(s) + */ +const keyToRuntime = key => { + if (key === "*") return undefined; + const items = key.split("\n"); + if (items.length === 1) return items[0]; + return new SortableSet(items); +}; +exports.keyToRuntime = keyToRuntime; -/** @type {Record string>} */ -const SIMPLE_ELEMENT_JOINERS = { - compilation: items => { - const result = []; - let lastNeedMore = false; - for (const item of items) { - if (!item.content) continue; - const needMoreSpace = - item.element === "warnings" || - item.element === "filteredWarningDetailsCount" || - item.element === "errors" || - item.element === "filteredErrorDetailsCount" || - item.element === "logging"; - if (result.length !== 0) { - result.push(needMoreSpace || lastNeedMore ? "\n\n" : "\n"); - } - result.push(item.content); - lastNeedMore = needMoreSpace; +const getRuntimesString = set => { + set.sort(); + return Array.from(set).join("+"); +}; + +/** + * @param {RuntimeSpec} runtime runtime(s) + * @returns {string} readable version + */ +const runtimeToString = runtime => { + if (runtime === undefined) return "*"; + if (typeof runtime === "string") return runtime; + return runtime.getFromUnorderedCache(getRuntimesString); +}; +exports.runtimeToString = runtimeToString; + +/** + * @param {RuntimeCondition} runtimeCondition runtime condition + * @returns {string} readable version + */ +exports.runtimeConditionToString = runtimeCondition => { + if (runtimeCondition === true) return "true"; + if (runtimeCondition === false) return "false"; + return runtimeToString(runtimeCondition); +}; + +/** + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {boolean} true, when they are equal + */ +const runtimeEqual = (a, b) => { + if (a === b) { + return true; + } else if ( + a === undefined || + b === undefined || + typeof a === "string" || + typeof b === "string" + ) { + return false; + } else if (a.size !== b.size) { + return false; + } else { + a.sort(); + b.sort(); + const aIt = a[Symbol.iterator](); + const bIt = b[Symbol.iterator](); + for (;;) { + const aV = aIt.next(); + if (aV.done) return true; + const bV = bIt.next(); + if (aV.value !== bV.value) return false; } - if (lastNeedMore) result.push("\n"); - return result.join(""); - }, - asset: items => - joinExplicitNewLine( - items.map(item => { - if ( - (item.element === "related" || item.element === "children") && - item.content - ) { - return { - ...item, - content: `\n${item.content}\n` - }; - } - return item; - }), - " " - ), - "asset.info": joinOneLine, - module: (items, { module }) => { - let hasName = false; - return joinExplicitNewLine( - items.map(item => { - switch (item.element) { - case "id": - if (module.id === module.name) { - if (hasName) return false; - if (item.content) hasName = true; - } - break; - case "name": - if (hasName) return false; - if (item.content) hasName = true; - break; - case "providedExports": - case "usedExports": - case "optimizationBailout": - case "reasons": - case "issuerPath": - case "profile": - case "children": - case "modules": - if (item.content) { - return { - ...item, - content: `\n${item.content}\n` - }; - } - break; - } - return item; - }), - " " - ); - }, - chunk: items => { - let hasEntry = false; - return ( - "chunk " + - joinExplicitNewLine( - items.filter(item => { - switch (item.element) { - case "entry": - if (item.content) hasEntry = true; - break; - case "initial": - if (hasEntry) return false; - break; - } - return true; - }), - " " - ) - ); - }, - "chunk.childrenByOrder[]": items => `(${joinOneLine(items)})`, - chunkGroup: items => joinExplicitNewLine(items, " "), - chunkGroupAsset: joinOneLine, - chunkGroupChildGroup: joinOneLine, - chunkGroupChild: joinOneLine, - // moduleReason: (items, { moduleReason }) => { - // let hasName = false; - // return joinOneLine( - // items.filter(item => { - // switch (item.element) { - // case "moduleId": - // if (moduleReason.moduleId === moduleReason.module && item.content) - // hasName = true; - // break; - // case "module": - // if (hasName) return false; - // break; - // case "resolvedModule": - // return ( - // moduleReason.module !== moduleReason.resolvedModule && - // item.content - // ); - // } - // return true; - // }) - // ); - // }, - moduleReason: (items, { moduleReason }) => { - let hasName = false; - return joinExplicitNewLine( - items.map(item => { - switch (item.element) { - case "moduleId": - if (moduleReason.moduleId === moduleReason.module && item.content) - hasName = true; - break; - case "module": - if (hasName) return false; - break; - case "resolvedModule": - if (moduleReason.module === moduleReason.resolvedModule) - return false; - break; - case "children": - if (item.content) { - return { - ...item, - content: `\n${item.content}\n` - }; - } - break; - } - return item; - }), - " " - ); - }, - "module.profile": joinInBrackets, - moduleIssuer: joinOneLine, - chunkOrigin: items => "> " + joinOneLine(items), - "errors[].error": joinError(true), - "warnings[].error": joinError(false), - loggingGroup: items => joinExplicitNewLine(items, "").trimRight(), - moduleTraceItem: items => " @ " + joinOneLine(items), - moduleTraceDependency: joinOneLine + } }; +exports.runtimeEqual = runtimeEqual; -const AVAILABLE_COLORS = { - bold: "\u001b[1m", - yellow: "\u001b[1m\u001b[33m", - red: "\u001b[1m\u001b[31m", - green: "\u001b[1m\u001b[32m", - cyan: "\u001b[1m\u001b[36m", - magenta: "\u001b[1m\u001b[35m" +/** + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {-1|0|1} compare + */ +exports.compareRuntime = (a, b) => { + if (a === b) { + return 0; + } else if (a === undefined) { + return -1; + } else if (b === undefined) { + return 1; + } else { + const aKey = getRuntimeKey(a); + const bKey = getRuntimeKey(b); + if (aKey < bKey) return -1; + if (aKey > bKey) return 1; + return 0; + } }; -const AVAILABLE_FORMATS = { - formatChunkId: (id, { yellow }, direction) => { - switch (direction) { - case "parent": - return `<{${yellow(id)}}>`; - case "sibling": - return `={${yellow(id)}}=`; - case "child": - return `>{${yellow(id)}}<`; - default: - return `{${yellow(id)}}`; +/** + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {RuntimeSpec} merged + */ +const mergeRuntime = (a, b) => { + if (a === undefined) { + return b; + } else if (b === undefined) { + return a; + } else if (a === b) { + return a; + } else if (typeof a === "string") { + if (typeof b === "string") { + const set = new SortableSet(); + set.add(a); + set.add(b); + return set; + } else if (b.has(a)) { + return b; + } else { + const set = new SortableSet(b); + set.add(a); + return set; } - }, - formatModuleId: id => `[${id}]`, - formatFilename: (filename, { green, yellow }, oversize) => - (oversize ? yellow : green)(filename), - formatFlag: flag => `[${flag}]`, - formatLayer: layer => `(in ${layer})`, - formatSize: (__webpack_require__(71070).formatSize), - formatDateTime: (dateTime, { bold }) => { - const d = new Date(dateTime); - const x = twoDigit; - const date = `${d.getFullYear()}-${x(d.getMonth() + 1)}-${x(d.getDate())}`; - const time = `${x(d.getHours())}:${x(d.getMinutes())}:${x(d.getSeconds())}`; - return `${date} ${bold(time)}`; - }, - formatTime: ( - time, - { timeReference, bold, green, yellow, red }, - boldQuantity - ) => { - const unit = " ms"; - if (timeReference && time !== timeReference) { - const times = [ - timeReference / 2, - timeReference / 4, - timeReference / 8, - timeReference / 16 - ]; - if (time < times[3]) return `${time}${unit}`; - else if (time < times[2]) return bold(`${time}${unit}`); - else if (time < times[1]) return green(`${time}${unit}`); - else if (time < times[0]) return yellow(`${time}${unit}`); - else return red(`${time}${unit}`); + } else { + if (typeof b === "string") { + if (a.has(b)) return a; + const set = new SortableSet(a); + set.add(b); + return set; } else { - return `${boldQuantity ? bold(time) : time}${unit}`; + const set = new SortableSet(a); + for (const item of b) set.add(item); + if (set.size === a.size) return a; + return set; } - }, - formatError: (message, { green, yellow, red }) => { - if (message.includes("\u001b[")) return message; - const highlights = [ - { regExp: /(Did you mean .+)/g, format: green }, - { - regExp: /(Set 'mode' option to 'development' or 'production')/g, - format: green - }, - { regExp: /(\(module has no exports\))/g, format: red }, - { regExp: /\(possible exports: (.+)\)/g, format: green }, - { regExp: /(?:^|\n)(.* doesn't exist)/g, format: red }, - { regExp: /('\w+' option has not been set)/g, format: red }, - { - regExp: /(Emitted value instead of an instance of Error)/g, - format: yellow - }, - { regExp: /(Used? .+ instead)/gi, format: yellow }, - { regExp: /\b(deprecated|must|required)\b/g, format: yellow }, - { - regExp: /\b(BREAKING CHANGE)\b/gi, - format: red - }, - { - regExp: - /\b(error|failed|unexpected|invalid|not found|not supported|not available|not possible|not implemented|doesn't support|conflict|conflicting|not existing|duplicate)\b/gi, - format: red - } - ]; - for (const { regExp, format } of highlights) { - message = message.replace(regExp, (match, content) => { - return match.replace(content, format(content)); - }); + } +}; +exports.mergeRuntime = mergeRuntime; + +/** + * @param {RuntimeCondition} a first + * @param {RuntimeCondition} b second + * @param {RuntimeSpec} runtime full runtime + * @returns {RuntimeCondition} result + */ +exports.mergeRuntimeCondition = (a, b, runtime) => { + if (a === false) return b; + if (b === false) return a; + if (a === true || b === true) return true; + const merged = mergeRuntime(a, b); + if (merged === undefined) return undefined; + if (typeof merged === "string") { + if (typeof runtime === "string" && merged === runtime) return true; + return merged; + } + if (typeof runtime === "string" || runtime === undefined) return merged; + if (merged.size === runtime.size) return true; + return merged; +}; + +/** + * @param {RuntimeSpec | true} a first + * @param {RuntimeSpec | true} b second + * @param {RuntimeSpec} runtime full runtime + * @returns {RuntimeSpec | true} result + */ +exports.mergeRuntimeConditionNonFalse = (a, b, runtime) => { + if (a === true || b === true) return true; + const merged = mergeRuntime(a, b); + if (merged === undefined) return undefined; + if (typeof merged === "string") { + if (typeof runtime === "string" && merged === runtime) return true; + return merged; + } + if (typeof runtime === "string" || runtime === undefined) return merged; + if (merged.size === runtime.size) return true; + return merged; +}; + +/** + * @param {RuntimeSpec} a first (may be modified) + * @param {RuntimeSpec} b second + * @returns {RuntimeSpec} merged + */ +const mergeRuntimeOwned = (a, b) => { + if (b === undefined) { + return a; + } else if (a === b) { + return a; + } else if (a === undefined) { + if (typeof b === "string") { + return b; + } else { + return new SortableSet(b); + } + } else if (typeof a === "string") { + if (typeof b === "string") { + const set = new SortableSet(); + set.add(a); + set.add(b); + return set; + } else { + const set = new SortableSet(b); + set.add(a); + return set; + } + } else { + if (typeof b === "string") { + a.add(b); + return a; + } else { + for (const item of b) a.add(item); + return a; } - return message; } }; +exports.mergeRuntimeOwned = mergeRuntimeOwned; -const RESULT_MODIFIER = { - "module.modules": result => { - return indent(result, "| "); +/** + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {RuntimeSpec} merged + */ +exports.intersectRuntime = (a, b) => { + if (a === undefined) { + return b; + } else if (b === undefined) { + return a; + } else if (a === b) { + return a; + } else if (typeof a === "string") { + if (typeof b === "string") { + return undefined; + } else if (b.has(a)) { + return a; + } else { + return undefined; + } + } else { + if (typeof b === "string") { + if (a.has(b)) return b; + return undefined; + } else { + const set = new SortableSet(); + for (const item of b) { + if (a.has(item)) set.add(item); + } + if (set.size === 0) return undefined; + if (set.size === 1) for (const item of set) return item; + return set; + } } }; -const createOrder = (array, preferredOrder) => { - const originalArray = array.slice(); - const set = new Set(array); - const usedSet = new Set(); - array.length = 0; - for (const element of preferredOrder) { - if (element.endsWith("!") || set.has(element)) { - array.push(element); - usedSet.add(element); +/** + * @param {RuntimeSpec} a first + * @param {RuntimeSpec} b second + * @returns {RuntimeSpec} result + */ +const subtractRuntime = (a, b) => { + if (a === undefined) { + return undefined; + } else if (b === undefined) { + return a; + } else if (a === b) { + return undefined; + } else if (typeof a === "string") { + if (typeof b === "string") { + return a; + } else if (b.has(a)) { + return undefined; + } else { + return a; + } + } else { + if (typeof b === "string") { + if (!a.has(b)) return a; + if (a.size === 2) { + for (const item of a) { + if (item !== b) return item; + } + } + const set = new SortableSet(a); + set.delete(b); + } else { + const set = new SortableSet(); + for (const item of a) { + if (!b.has(item)) set.add(item); + } + if (set.size === 0) return undefined; + if (set.size === 1) for (const item of set) return item; + return set; } } - for (const element of originalArray) { - if (!usedSet.has(element)) { - array.push(element); +}; +exports.subtractRuntime = subtractRuntime; + +/** + * @param {RuntimeCondition} a first + * @param {RuntimeCondition} b second + * @param {RuntimeSpec} runtime runtime + * @returns {RuntimeCondition} result + */ +exports.subtractRuntimeCondition = (a, b, runtime) => { + if (b === true) return false; + if (b === false) return a; + if (a === false) return false; + const result = subtractRuntime(a === true ? runtime : a, b); + return result === undefined ? false : result; +}; + +/** + * @param {RuntimeSpec} runtime runtime + * @param {function(RuntimeSpec): boolean} filter filter function + * @returns {boolean | RuntimeSpec} true/false if filter is constant for all runtimes, otherwise runtimes that are active + */ +exports.filterRuntime = (runtime, filter) => { + if (runtime === undefined) return filter(undefined); + if (typeof runtime === "string") return filter(runtime); + let some = false; + let every = true; + let result = undefined; + for (const r of runtime) { + const v = filter(r); + if (v) { + some = true; + result = mergeRuntimeOwned(result, r); + } else { + every = false; } } - return array; + if (!some) return false; + if (every) return true; + return result; }; -class DefaultStatsPrinterPlugin { +/** + * @template T + */ +class RuntimeSpecMap { /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} + * @param {RuntimeSpecMap=} clone copy form this */ - apply(compiler) { - compiler.hooks.compilation.tap("DefaultStatsPrinterPlugin", compilation => { - compilation.hooks.statsPrinter.tap( - "DefaultStatsPrinterPlugin", - (stats, options, context) => { - // Put colors into context - stats.hooks.print - .for("compilation") - .tap("DefaultStatsPrinterPlugin", (compilation, context) => { - for (const color of Object.keys(AVAILABLE_COLORS)) { - let start; - if (options.colors) { - if ( - typeof options.colors === "object" && - typeof options.colors[color] === "string" - ) { - start = options.colors[color]; - } else { - start = AVAILABLE_COLORS[color]; - } - } - if (start) { - context[color] = str => - `${start}${ - typeof str === "string" - ? str.replace( - /((\u001b\[39m|\u001b\[22m|\u001b\[0m)+)/g, - `$1${start}` - ) - : str - }\u001b[39m\u001b[22m`; - } else { - context[color] = str => str; - } - } - for (const format of Object.keys(AVAILABLE_FORMATS)) { - context[format] = (content, ...args) => - AVAILABLE_FORMATS[format](content, context, ...args); - } - context.timeReference = compilation.time; - }); + constructor(clone) { + this._mode = clone ? clone._mode : 0; // 0 = empty, 1 = single entry, 2 = map + /** @type {RuntimeSpec} */ + this._singleRuntime = clone ? clone._singleRuntime : undefined; + /** @type {T} */ + this._singleValue = clone ? clone._singleValue : undefined; + /** @type {Map | undefined} */ + this._map = clone && clone._map ? new Map(clone._map) : undefined; + } + + /** + * @param {RuntimeSpec} runtime the runtimes + * @returns {T} value + */ + get(runtime) { + switch (this._mode) { + case 0: + return undefined; + case 1: + return runtimeEqual(this._singleRuntime, runtime) + ? this._singleValue + : undefined; + default: + return this._map.get(getRuntimeKey(runtime)); + } + } + + /** + * @param {RuntimeSpec} runtime the runtimes + * @returns {boolean} true, when the runtime is stored + */ + has(runtime) { + switch (this._mode) { + case 0: + return false; + case 1: + return runtimeEqual(this._singleRuntime, runtime); + default: + return this._map.has(getRuntimeKey(runtime)); + } + } + + set(runtime, value) { + switch (this._mode) { + case 0: + this._mode = 1; + this._singleRuntime = runtime; + this._singleValue = value; + break; + case 1: + if (runtimeEqual(this._singleRuntime, runtime)) { + this._singleValue = value; + break; + } + this._mode = 2; + this._map = new Map(); + this._map.set(getRuntimeKey(this._singleRuntime), this._singleValue); + this._singleRuntime = undefined; + this._singleValue = undefined; + /* falls through */ + default: + this._map.set(getRuntimeKey(runtime), value); + } + } + + provide(runtime, computer) { + switch (this._mode) { + case 0: + this._mode = 1; + this._singleRuntime = runtime; + return (this._singleValue = computer()); + case 1: { + if (runtimeEqual(this._singleRuntime, runtime)) { + return this._singleValue; + } + this._mode = 2; + this._map = new Map(); + this._map.set(getRuntimeKey(this._singleRuntime), this._singleValue); + this._singleRuntime = undefined; + this._singleValue = undefined; + const newValue = computer(); + this._map.set(getRuntimeKey(runtime), newValue); + return newValue; + } + default: { + const key = getRuntimeKey(runtime); + const value = this._map.get(key); + if (value !== undefined) return value; + const newValue = computer(); + this._map.set(key, newValue); + return newValue; + } + } + } + + delete(runtime) { + switch (this._mode) { + case 0: + return; + case 1: + if (runtimeEqual(this._singleRuntime, runtime)) { + this._mode = 0; + this._singleRuntime = undefined; + this._singleValue = undefined; + } + return; + default: + this._map.delete(getRuntimeKey(runtime)); + } + } + + update(runtime, fn) { + switch (this._mode) { + case 0: + throw new Error("runtime passed to update must exist"); + case 1: { + if (runtimeEqual(this._singleRuntime, runtime)) { + this._singleValue = fn(this._singleValue); + break; + } + const newValue = fn(undefined); + if (newValue !== undefined) { + this._mode = 2; + this._map = new Map(); + this._map.set(getRuntimeKey(this._singleRuntime), this._singleValue); + this._singleRuntime = undefined; + this._singleValue = undefined; + this._map.set(getRuntimeKey(runtime), newValue); + } + break; + } + default: { + const key = getRuntimeKey(runtime); + const oldValue = this._map.get(key); + const newValue = fn(oldValue); + if (newValue !== oldValue) this._map.set(key, newValue); + } + } + } + + keys() { + switch (this._mode) { + case 0: + return []; + case 1: + return [this._singleRuntime]; + default: + return Array.from(this._map.keys(), keyToRuntime); + } + } + + values() { + switch (this._mode) { + case 0: + return [][Symbol.iterator](); + case 1: + return [this._singleValue][Symbol.iterator](); + default: + return this._map.values(); + } + } - for (const key of Object.keys(SIMPLE_PRINTERS)) { - stats.hooks.print - .for(key) - .tap("DefaultStatsPrinterPlugin", (obj, ctx) => - SIMPLE_PRINTERS[key](obj, ctx, stats) - ); - } + get size() { + if (this._mode <= 1) return this._mode; + return this._map.size; + } +} - for (const key of Object.keys(PREFERRED_ORDERS)) { - const preferredOrder = PREFERRED_ORDERS[key]; - stats.hooks.sortElements - .for(key) - .tap("DefaultStatsPrinterPlugin", (elements, context) => { - createOrder(elements, preferredOrder); - }); - } +exports.RuntimeSpecMap = RuntimeSpecMap; - for (const key of Object.keys(ITEM_NAMES)) { - const itemName = ITEM_NAMES[key]; - stats.hooks.getItemName - .for(key) - .tap( - "DefaultStatsPrinterPlugin", - typeof itemName === "string" ? () => itemName : itemName - ); - } +class RuntimeSpecSet { + constructor(iterable) { + /** @type {Map} */ + this._map = new Map(); + if (iterable) { + for (const item of iterable) { + this.add(item); + } + } + } - for (const key of Object.keys(SIMPLE_ITEMS_JOINER)) { - const joiner = SIMPLE_ITEMS_JOINER[key]; - stats.hooks.printItems - .for(key) - .tap("DefaultStatsPrinterPlugin", joiner); - } + add(runtime) { + this._map.set(getRuntimeKey(runtime), runtime); + } - for (const key of Object.keys(SIMPLE_ELEMENT_JOINERS)) { - const joiner = SIMPLE_ELEMENT_JOINERS[key]; - stats.hooks.printElements - .for(key) - .tap("DefaultStatsPrinterPlugin", joiner); - } + has(runtime) { + return this._map.has(getRuntimeKey(runtime)); + } - for (const key of Object.keys(RESULT_MODIFIER)) { - const modifier = RESULT_MODIFIER[key]; - stats.hooks.result - .for(key) - .tap("DefaultStatsPrinterPlugin", modifier); - } - } - ); - }); + [Symbol.iterator]() { + return this._map.values(); + } + + get size() { + return this._map.size; } } -module.exports = DefaultStatsPrinterPlugin; + +exports.RuntimeSpecSet = RuntimeSpecSet; /***/ }), -/***/ 92629: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 19702: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -127716,553 +128267,831 @@ module.exports = DefaultStatsPrinterPlugin; -const { HookMap, SyncBailHook, SyncWaterfallHook } = __webpack_require__(41242); -const { concatComparators, keepOriginalOrder } = __webpack_require__(29579); -const smartGrouping = __webpack_require__(15652); - -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../WebpackError")} WebpackError */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {(string|number|undefined|[])[]} SemVerRange */ -/** @typedef {import("../util/smartGrouping").GroupConfig} GroupConfig */ +/** + * @param {string} str version string + * @returns {(string|number|undefined|[])[]} parsed version + */ +const parseVersion = str => { + var splitAndConvert = function (str) { + return str.split(".").map(function (item) { + // eslint-disable-next-line eqeqeq + return +item == item ? +item : item; + }); + }; + var match = /^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str); + /** @type {(string|number|undefined|[])[]} */ + var ver = match[1] ? splitAndConvert(match[1]) : []; + if (match[2]) { + ver.length++; + ver.push.apply(ver, splitAndConvert(match[2])); + } + if (match[3]) { + ver.push([]); + ver.push.apply(ver, splitAndConvert(match[3])); + } + return ver; +}; +exports.parseVersion = parseVersion; +/* eslint-disable eqeqeq */ /** - * @typedef {Object} KnownStatsFactoryContext - * @property {string} type - * @property {function(string): string=} makePathsRelative - * @property {Compilation=} compilation - * @property {Set=} rootModules - * @property {Map=} compilationFileToChunks - * @property {Map=} compilationAuxiliaryFileToChunks - * @property {RuntimeSpec=} runtime - * @property {function(Compilation): WebpackError[]=} cachedGetErrors - * @property {function(Compilation): WebpackError[]=} cachedGetWarnings + * @param {string} a version + * @param {string} b version + * @returns {boolean} true, iff a < b */ +const versionLt = (a, b) => { + // @ts-expect-error + a = parseVersion(a); + // @ts-expect-error + b = parseVersion(b); + var i = 0; + for (;;) { + // a b EOA object undefined number string + // EOA a == b a < b b < a a < b a < b + // object b < a (0) b < a a < b a < b + // undefined a < b a < b (0) a < b a < b + // number b < a b < a b < a (1) a < b + // string b < a b < a b < a b < a (1) + // EOA end of array + // (0) continue on + // (1) compare them via "<" -/** @typedef {KnownStatsFactoryContext & Record} StatsFactoryContext */ + // Handles first row in table + if (i >= a.length) return i < b.length && (typeof b[i])[0] != "u"; -class StatsFactory { - constructor() { - this.hooks = Object.freeze({ - /** @type {HookMap>} */ - extract: new HookMap( - () => new SyncBailHook(["object", "data", "context"]) - ), - /** @type {HookMap>} */ - filter: new HookMap( - () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) - ), - /** @type {HookMap>} */ - sort: new HookMap(() => new SyncBailHook(["comparators", "context"])), - /** @type {HookMap>} */ - filterSorted: new HookMap( - () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) - ), - /** @type {HookMap>} */ - groupResults: new HookMap( - () => new SyncBailHook(["groupConfigs", "context"]) - ), - /** @type {HookMap>} */ - sortResults: new HookMap( - () => new SyncBailHook(["comparators", "context"]) - ), - /** @type {HookMap>} */ - filterResults: new HookMap( - () => new SyncBailHook(["item", "context", "index", "unfilteredIndex"]) - ), - /** @type {HookMap>} */ - merge: new HookMap(() => new SyncBailHook(["items", "context"])), - /** @type {HookMap>} */ - result: new HookMap(() => new SyncWaterfallHook(["result", "context"])), - /** @type {HookMap>} */ - getItemName: new HookMap(() => new SyncBailHook(["item", "context"])), - /** @type {HookMap>} */ - getItemFactory: new HookMap(() => new SyncBailHook(["item", "context"])) - }); - const hooks = this.hooks; - this._caches = - /** @type {Record[]>>} */ ({}); - for (const key of Object.keys(hooks)) { - this._caches[key] = new Map(); - } - this._inCreate = false; - } + var aValue = a[i]; + var aType = (typeof aValue)[0]; - _getAllLevelHooks(hookMap, cache, type) { - const cacheEntry = cache.get(type); - if (cacheEntry !== undefined) { - return cacheEntry; - } - const hooks = []; - const typeParts = type.split("."); - for (let i = 0; i < typeParts.length; i++) { - const hook = hookMap.get(typeParts.slice(i).join(".")); - if (hook) { - hooks.push(hook); + // Handles first column in table + if (i >= b.length) return aType == "u"; + + var bValue = b[i]; + var bType = (typeof bValue)[0]; + + if (aType == bType) { + if (aType != "o" && aType != "u" && aValue != bValue) { + return aValue < bValue; } + i++; + } else { + // Handles remaining cases + if (aType == "o" && bType == "n") return true; + return bType == "s" || aType == "u"; } - cache.set(type, hooks); - return hooks; } +}; +/* eslint-enable eqeqeq */ +exports.versionLt = versionLt; - _forEachLevel(hookMap, cache, type, fn) { - for (const hook of this._getAllLevelHooks(hookMap, cache, type)) { - const result = fn(hook); - if (result !== undefined) return result; +/** + * @param {string} str range string + * @returns {SemVerRange} parsed range + */ +exports.parseRange = str => { + const splitAndConvert = str => { + return str.split(".").map(item => (`${+item}` === item ? +item : item)); + }; + // see https://docs.npmjs.com/misc/semver#range-grammar for grammar + const parsePartial = str => { + const match = /^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str); + /** @type {(string|number|undefined|[])[]} */ + const ver = match[1] ? [0, ...splitAndConvert(match[1])] : [0]; + if (match[2]) { + ver.length++; + ver.push.apply(ver, splitAndConvert(match[2])); } - } - _forEachLevelWaterfall(hookMap, cache, type, data, fn) { - for (const hook of this._getAllLevelHooks(hookMap, cache, type)) { - data = fn(hook, data); + // remove trailing any matchers + let last = ver[ver.length - 1]; + while ( + ver.length && + (last === undefined || /^[*xX]$/.test(/** @type {string} */ (last))) + ) { + ver.pop(); + last = ver[ver.length - 1]; } - return data; - } - _forEachLevelFilter(hookMap, cache, type, items, fn, forceClone) { - const hooks = this._getAllLevelHooks(hookMap, cache, type); - if (hooks.length === 0) return forceClone ? items.slice() : items; - let i = 0; - return items.filter((item, idx) => { - for (const hook of hooks) { - const r = fn(hook, item, idx, i); - if (r !== undefined) { - if (r) i++; - return r; + return ver; + }; + const toFixed = range => { + if (range.length === 1) { + // Special case for "*" is "x.x.x" instead of "=" + return [0]; + } else if (range.length === 2) { + // Special case for "1" is "1.x.x" instead of "=1" + return [1, ...range.slice(1)]; + } else if (range.length === 3) { + // Special case for "1.2" is "1.2.x" instead of "=1.2" + return [2, ...range.slice(1)]; + } else { + return [range.length, ...range.slice(1)]; + } + }; + const negate = range => { + return [-range[0] - 1, ...range.slice(1)]; + }; + const parseSimple = str => { + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + const match = /^(\^|~|<=|<|>=|>|=|v|!)/.exec(str); + const start = match ? match[0] : ""; + const remainder = parsePartial(str.slice(start.length)); + switch (start) { + case "^": + if (remainder.length > 1 && remainder[1] === 0) { + if (remainder.length > 2 && remainder[2] === 0) { + return [3, ...remainder.slice(1)]; + } + return [2, ...remainder.slice(1)]; } + return [1, ...remainder.slice(1)]; + case "~": + return [2, ...remainder.slice(1)]; + case ">=": + return remainder; + case "=": + case "v": + case "": + return toFixed(remainder); + case "<": + return negate(remainder); + case ">": { + // and( >=, not( = ) ) => >=, =, not, and + const fixed = toFixed(remainder); + // eslint-disable-next-line no-sparse-arrays + return [, fixed, 0, remainder, 2]; } - i++; - return true; - }); - } - - /** - * @param {string} type type - * @param {any} data factory data - * @param {Omit} baseContext context used as base - * @returns {any} created object - */ - create(type, data, baseContext) { - if (this._inCreate) { - return this._create(type, data, baseContext); - } else { - try { - this._inCreate = true; - return this._create(type, data, baseContext); - } finally { - for (const key of Object.keys(this._caches)) this._caches[key].clear(); - this._inCreate = false; + case "<=": + // or( <, = ) => <, =, or + // eslint-disable-next-line no-sparse-arrays + return [, toFixed(remainder), negate(remainder), 1]; + case "!": { + // not = + const fixed = toFixed(remainder); + // eslint-disable-next-line no-sparse-arrays + return [, fixed, 0]; } + default: + throw new Error("Unexpected start value"); } - } + }; + const combine = (items, fn) => { + if (items.length === 1) return items[0]; + const arr = []; + for (const item of items.slice().reverse()) { + if (0 in item) { + arr.push(item); + } else { + arr.push(...item.slice(1)); + } + } + // eslint-disable-next-line no-sparse-arrays + return [, ...arr, ...items.slice(1).map(() => fn)]; + }; + const parseRange = str => { + // range ::= hyphen | simple ( ' ' simple ) * | '' + // hyphen ::= partial ' - ' partial + const items = str.split(" - "); + if (items.length === 1) { + const items = str.trim().split(/\s+/g).map(parseSimple); + return combine(items, 2); + } + const a = parsePartial(items[0]); + const b = parsePartial(items[1]); + // >=a <=b => and( >=a, or( >=a, { + // range-set ::= range ( logical-or range ) * + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + const items = str.split(/\s*\|\|\s*/).map(parseRange); + return combine(items, 1); + }; + return parseLogicalOr(str); +}; - _create(type, data, baseContext) { - const context = { - ...baseContext, - type, - [type]: data - }; - if (Array.isArray(data)) { - // run filter on unsorted items - const items = this._forEachLevelFilter( - this.hooks.filter, - this._caches.filter, - type, - data, - (h, r, idx, i) => h.call(r, context, idx, i), - true +/* eslint-disable eqeqeq */ +const rangeToString = range => { + var fixCount = range[0]; + var str = ""; + if (range.length === 1) { + return "*"; + } else if (fixCount + 0.5) { + str += + fixCount == 0 + ? ">=" + : fixCount == -1 + ? "<" + : fixCount == 1 + ? "^" + : fixCount == 2 + ? "~" + : fixCount > 0 + ? "=" + : "!="; + var needDot = 1; + // eslint-disable-next-line no-redeclare + for (var i = 1; i < range.length; i++) { + var item = range[i]; + var t = (typeof item)[0]; + needDot--; + str += + t == "u" + ? // undefined: prerelease marker, add an "-" + "-" + : // number or string: add the item, set flag to add an "." between two of them + (needDot > 0 ? "." : "") + ((needDot = 2), item); + } + return str; + } else { + var stack = []; + // eslint-disable-next-line no-redeclare + for (var i = 1; i < range.length; i++) { + // eslint-disable-next-line no-redeclare + var item = range[i]; + stack.push( + item === 0 + ? "not(" + pop() + ")" + : item === 1 + ? "(" + pop() + " || " + pop() + ")" + : item === 2 + ? stack.pop() + " " + stack.pop() + : rangeToString(item) ); + } + return pop(); + } + function pop() { + return stack.pop().replace(/^\((.+)\)$/, "$1"); + } +}; +/* eslint-enable eqeqeq */ +exports.rangeToString = rangeToString; - // sort items - const comparators = []; - this._forEachLevel(this.hooks.sort, this._caches.sort, type, h => - h.call(comparators, context) - ); - if (comparators.length > 0) { - items.sort( - // @ts-expect-error number of arguments is correct - concatComparators(...comparators, keepOriginalOrder(items)) - ); - } +/* eslint-disable eqeqeq */ +/** + * @param {SemVerRange} range version range + * @param {string} version the version + * @returns {boolean} if version satisfy the range + */ +const satisfy = (range, version) => { + if (0 in range) { + // @ts-expect-error + version = parseVersion(version); + var fixCount = range[0]; + // when negated is set it swill set for < instead of >= + var negated = fixCount < 0; + if (negated) fixCount = -fixCount - 1; + for (var i = 0, j = 1, isEqual = true; ; j++, i++) { + // cspell:word nequal nequ - // run filter on sorted items - const items2 = this._forEachLevelFilter( - this.hooks.filterSorted, - this._caches.filterSorted, - type, - items, - (h, r, idx, i) => h.call(r, context, idx, i), - false - ); + // when isEqual = true: + // range version: EOA/object undefined number string + // EOA equal block big-ver big-ver + // undefined bigger next big-ver big-ver + // number smaller block cmp big-cmp + // fixed number smaller block cmp-fix differ + // string smaller block differ cmp + // fixed string smaller block small-cmp cmp-fix - // for each item - let resultItems = items2.map((item, i) => { - const itemContext = { - ...context, - _index: i - }; + // when isEqual = false: + // range version: EOA/object undefined number string + // EOA nequal block next-ver next-ver + // undefined nequal block next-ver next-ver + // number nequal block next next + // fixed number nequal block next next (this never happens) + // string nequal block next next + // fixed string nequal block next next (this never happens) - // run getItemName - const itemName = this._forEachLevel( - this.hooks.getItemName, - this._caches.getItemName, - `${type}[]`, - h => h.call(item, itemContext) - ); - if (itemName) itemContext[itemName] = item; - const innerType = itemName ? `${type}[].${itemName}` : `${type}[]`; + // EOA end of array + // equal (version is equal range): + // when !negated: return true, + // when negated: return false + // bigger (version is bigger as range): + // when fixed: return false, + // when !negated: return true, + // when negated: return false, + // smaller (version is smaller as range): + // when !negated: return false, + // when negated: return true + // nequal (version is not equal range (> resp <)): return true + // block (version is in different prerelease area): return false + // differ (version is different from fixed range (string vs. number)): return false + // next: continues to the next items + // next-ver: when fixed: return false, continues to the next item only for the version, sets isEqual=false + // big-ver: when fixed || negated: return false, continues to the next item only for the version, sets isEqual=false + // next-nequ: continues to the next items, sets isEqual=false + // cmp (negated === false): version < range => return false, version > range => next-nequ, else => next + // cmp (negated === true): version > range => return false, version < range => next-nequ, else => next + // cmp-fix: version == range => next, else => return false + // big-cmp: when negated => return false, else => next-nequ + // small-cmp: when negated => next-nequ, else => return false - // run getItemFactory - const itemFactory = - this._forEachLevel( - this.hooks.getItemFactory, - this._caches.getItemFactory, - innerType, - h => h.call(item, itemContext) - ) || this; + var rangeType = j < range.length ? (typeof range[j])[0] : ""; - // run item factory - return itemFactory.create(innerType, item, itemContext); - }); + var versionValue; + var versionType; - // sort result items - const comparators2 = []; - this._forEachLevel( - this.hooks.sortResults, - this._caches.sortResults, - type, - h => h.call(comparators2, context) - ); - if (comparators2.length > 0) { - resultItems.sort( - // @ts-expect-error number of arguments is correct - concatComparators(...comparators2, keepOriginalOrder(resultItems)) - ); + // Handles first column in both tables (end of version or object) + if ( + i >= version.length || + ((versionValue = version[i]), + (versionType = (typeof versionValue)[0]) == "o") + ) { + // Handles nequal + if (!isEqual) return true; + // Handles bigger + if (rangeType == "u") return j > fixCount && !negated; + // Handles equal and smaller: (range === EOA) XOR negated + return (rangeType == "") != negated; // equal + smaller } - // group result items - const groupConfigs = []; - this._forEachLevel( - this.hooks.groupResults, - this._caches.groupResults, - type, - h => h.call(groupConfigs, context) - ); - if (groupConfigs.length > 0) { - resultItems = smartGrouping(resultItems, groupConfigs); + // Handles second column in both tables (version = undefined) + if (versionType == "u") { + if (!isEqual || rangeType != "u") { + return false; + } } - // run filter on sorted result items - const finalResultItems = this._forEachLevelFilter( - this.hooks.filterResults, - this._caches.filterResults, - type, - resultItems, - (h, r, idx, i) => h.call(r, context, idx, i), - false - ); - - // run merge on mapped items - let result = this._forEachLevel( - this.hooks.merge, - this._caches.merge, - type, - h => h.call(finalResultItems, context) - ); - if (result === undefined) result = finalResultItems; + // switch between first and second table + else if (isEqual) { + // Handle diagonal + if (rangeType == versionType) { + if (j <= fixCount) { + // Handles "cmp-fix" cases + if (versionValue != range[j]) { + return false; + } + } else { + // Handles "cmp" cases + if (negated ? versionValue > range[j] : versionValue < range[j]) { + return false; + } + if (versionValue != range[j]) isEqual = false; + } + } - // run result on merged items - return this._forEachLevelWaterfall( - this.hooks.result, - this._caches.result, - type, - result, - (h, r) => h.call(r, context) - ); - } else { - const object = {}; + // Handle big-ver + else if (rangeType != "s" && rangeType != "n") { + if (negated || j <= fixCount) return false; + isEqual = false; + j--; + } - // run extract on value - this._forEachLevel(this.hooks.extract, this._caches.extract, type, h => - h.call(object, data, context) - ); + // Handle differ, big-cmp and small-cmp + else if (j <= fixCount || versionType < rangeType != negated) { + return false; + } else { + isEqual = false; + } + } else { + // Handles all "next-ver" cases in the second table + if (rangeType != "s" && rangeType != "n") { + isEqual = false; + j--; + } - // run result on extracted object - return this._forEachLevelWaterfall( - this.hooks.result, - this._caches.result, - type, - object, - (h, r) => h.call(r, context) - ); + // next is applied by default + } } } -} -module.exports = StatsFactory; + /** @type {(boolean | number)[]} */ + var stack = []; + var p = stack.pop.bind(stack); + // eslint-disable-next-line no-redeclare + for (var i = 1; i < range.length; i++) { + var item = /** @type {SemVerRange | 0 | 1 | 2} */ (range[i]); + stack.push( + item == 1 + ? p() | p() + : item == 2 + ? p() & p() + : item + ? satisfy(item, version) + : !p() + ); + } + return !!p(); +}; +/* eslint-enable eqeqeq */ +exports.satisfy = satisfy; + +exports.stringifyHoley = json => { + switch (typeof json) { + case "undefined": + return ""; + case "object": + if (Array.isArray(json)) { + let str = "["; + for (let i = 0; i < json.length; i++) { + if (i !== 0) str += ","; + str += this.stringifyHoley(json[i]); + } + str += "]"; + return str; + } else { + return JSON.stringify(json); + } + default: + return JSON.stringify(json); + } +}; + +//#region runtime code: parseVersion +exports.parseVersionRuntimeCode = runtimeTemplate => + `var parseVersion = ${runtimeTemplate.basicFunction("str", [ + "// see webpack/lib/util/semver.js for original code", + `var p=${ + runtimeTemplate.supportsArrowFunction() ? "p=>" : "function(p)" + }{return p.split(".").map((${ + runtimeTemplate.supportsArrowFunction() ? "p=>" : "function(p)" + }{return+p==p?+p:p}))},n=/^([^-+]+)?(?:-([^+]+))?(?:\\+(.+))?$/.exec(str),r=n[1]?p(n[1]):[];return n[2]&&(r.length++,r.push.apply(r,p(n[2]))),n[3]&&(r.push([]),r.push.apply(r,p(n[3]))),r;` + ])}`; +//#endregion + +//#region runtime code: versionLt +exports.versionLtRuntimeCode = runtimeTemplate => + `var versionLt = ${runtimeTemplate.basicFunction("a, b", [ + "// see webpack/lib/util/semver.js for original code", + 'a=parseVersion(a),b=parseVersion(b);for(var r=0;;){if(r>=a.length)return r=b.length)return"u"==n;var t=b[r],f=(typeof t)[0];if(n!=f)return"o"==n&&"n"==f||("s"==f||"u"==n);if("o"!=n&&"u"!=n&&e!=t)return e + `var rangeToString = ${runtimeTemplate.basicFunction("range", [ + "// see webpack/lib/util/semver.js for original code", + 'var r=range[0],n="";if(1===range.length)return"*";if(r+.5){n+=0==r?">=":-1==r?"<":1==r?"^":2==r?"~":r>0?"=":"!=";for(var e=1,a=1;a0?".":"")+(e=2,t)}return n}var g=[];for(a=1;a + `var satisfy = ${runtimeTemplate.basicFunction("range, version", [ + "// see webpack/lib/util/semver.js for original code", + 'if(0 in range){version=parseVersion(version);var e=range[0],r=e<0;r&&(e=-e-1);for(var n=0,i=1,a=!0;;i++,n++){var f,s,g=i=version.length||"o"==(s=(typeof(f=version[n]))[0]))return!a||("u"==g?i>e&&!r:""==g!=r);if("u"==s){if(!a||"u"!=g)return!1}else if(a)if(g==s)if(i<=e){if(f!=range[i])return!1}else{if(r?f>range[i]:f + __webpack_require__(97059) +); +const getObjectMiddleware = memoize(() => + __webpack_require__(34795) +); +const getSingleItemMiddleware = memoize(() => + __webpack_require__(65112) +); +const getSerializer = memoize(() => __webpack_require__(53080)); +const getSerializerMiddleware = memoize(() => + __webpack_require__(83137) +); + +const getBinaryMiddlewareInstance = memoize( + () => new (getBinaryMiddleware())() +); + +const registerSerializers = memoize(() => { + __webpack_require__(26611); + + // Load internal paths with a relative require + // This allows bundling all internal serializers + const internalSerializables = __webpack_require__(53023); + getObjectMiddleware().registerLoader(/^webpack\/lib\//, req => { + const loader = internalSerializables[req.slice("webpack/lib/".length)]; + if (loader) { + loader(); + } else { + console.warn(`${req} not found in internalSerializables`); + } + return true; + }); +}); + +/** @type {Serializer} */ +let buffersSerializer; + +// Expose serialization API +module.exports = { + get register() { + return getObjectMiddleware().register; + }, + get registerLoader() { + return getObjectMiddleware().registerLoader; + }, + get registerNotSerializable() { + return getObjectMiddleware().registerNotSerializable; + }, + get NOT_SERIALIZABLE() { + return getObjectMiddleware().NOT_SERIALIZABLE; + }, + /** @type {MEASURE_START_OPERATION} */ + get MEASURE_START_OPERATION() { + return getBinaryMiddleware().MEASURE_START_OPERATION; + }, + /** @type {MEASURE_END_OPERATION} */ + get MEASURE_END_OPERATION() { + return getBinaryMiddleware().MEASURE_END_OPERATION; + }, + get buffersSerializer() { + if (buffersSerializer !== undefined) return buffersSerializer; + registerSerializers(); + const Serializer = getSerializer(); + const binaryMiddleware = getBinaryMiddlewareInstance(); + const SerializerMiddleware = getSerializerMiddleware(); + const SingleItemMiddleware = getSingleItemMiddleware(); + return (buffersSerializer = new Serializer([ + new SingleItemMiddleware(), + new (getObjectMiddleware())(context => { + if (context.write) { + context.writeLazy = value => { + context.write( + SerializerMiddleware.createLazy(value, binaryMiddleware) + ); + }; + } + }, "md4"), + binaryMiddleware + ])); + }, + createFileSerializer: (fs, hashFunction) => { + registerSerializers(); + const Serializer = getSerializer(); + const FileMiddleware = __webpack_require__(65321); + const fileMiddleware = new FileMiddleware(fs, hashFunction); + const binaryMiddleware = getBinaryMiddlewareInstance(); + const SerializerMiddleware = getSerializerMiddleware(); + const SingleItemMiddleware = getSingleItemMiddleware(); + return new Serializer([ + new SingleItemMiddleware(), + new (getObjectMiddleware())(context => { + if (context.write) { + context.writeLazy = value => { + context.write( + SerializerMiddleware.createLazy(value, binaryMiddleware) + ); + }; + context.writeSeparate = (value, options) => { + const lazy = SerializerMiddleware.createLazy( + value, + fileMiddleware, + options + ); + context.write(lazy); + return lazy; + }; + } + }, hashFunction), + binaryMiddleware, + fileMiddleware + ]); + } +}; + + +/***/ }), + +/***/ 15652: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + -/** @template T @typedef {import("tapable").AsArray} AsArray */ -/** @typedef {import("tapable").Hook} Hook */ -/** @typedef {import("./DefaultStatsFactoryPlugin").StatsAsset} StatsAsset */ -/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunk} StatsChunk */ -/** @typedef {import("./DefaultStatsFactoryPlugin").StatsChunkGroup} StatsChunkGroup */ -/** @typedef {import("./DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */ -/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModule} StatsModule */ -/** @typedef {import("./DefaultStatsFactoryPlugin").StatsModuleReason} StatsModuleReason */ /** - * @typedef {Object} PrintedElement - * @property {string} element - * @property {string} content + * @typedef {Object} GroupOptions + * @property {boolean=} groupChildren + * @property {boolean=} force + * @property {number=} targetGroupCount */ /** - * @typedef {Object} KnownStatsPrinterContext - * @property {string=} type - * @property {StatsCompilation=} compilation - * @property {StatsChunkGroup=} chunkGroup - * @property {StatsAsset=} asset - * @property {StatsModule=} module - * @property {StatsChunk=} chunk - * @property {StatsModuleReason=} moduleReason - * @property {(str: string) => string=} bold - * @property {(str: string) => string=} yellow - * @property {(str: string) => string=} red - * @property {(str: string) => string=} green - * @property {(str: string) => string=} magenta - * @property {(str: string) => string=} cyan - * @property {(file: string, oversize?: boolean) => string=} formatFilename - * @property {(id: string) => string=} formatModuleId - * @property {(id: string, direction?: "parent"|"child"|"sibling") => string=} formatChunkId - * @property {(size: number) => string=} formatSize - * @property {(dateTime: number) => string=} formatDateTime - * @property {(flag: string) => string=} formatFlag - * @property {(time: number, boldQuantity?: boolean) => string=} formatTime - * @property {string=} chunkGroupKind + * @template T + * @template R + * @typedef {Object} GroupConfig + * @property {function(T): string[]} getKeys + * @property {function(string, (R | T)[], T[]): R} createGroup + * @property {function(string, T[]): GroupOptions=} getOptions */ -/** @typedef {KnownStatsPrinterContext & Record} StatsPrinterContext */ +/** + * @template T + * @template R + * @typedef {Object} ItemWithGroups + * @property {T} item + * @property {Set>} groups + */ -class StatsPrinter { - constructor() { - this.hooks = Object.freeze({ - /** @type {HookMap>} */ - sortElements: new HookMap( - () => new SyncBailHook(["elements", "context"]) - ), - /** @type {HookMap>} */ - printElements: new HookMap( - () => new SyncBailHook(["printedElements", "context"]) - ), - /** @type {HookMap>} */ - sortItems: new HookMap(() => new SyncBailHook(["items", "context"])), - /** @type {HookMap>} */ - getItemName: new HookMap(() => new SyncBailHook(["item", "context"])), - /** @type {HookMap>} */ - printItems: new HookMap( - () => new SyncBailHook(["printedItems", "context"]) - ), - /** @type {HookMap>} */ - print: new HookMap(() => new SyncBailHook(["object", "context"])), - /** @type {HookMap>} */ - result: new HookMap(() => new SyncWaterfallHook(["result", "context"])) - }); - /** @type {Map, Map>} */ - this._levelHookCache = new Map(); - this._inPrint = false; - } +/** + * @template T + * @template R + * @typedef {{ config: GroupConfig, name: string, alreadyGrouped: boolean, items: Set> | undefined }} Group + */ - /** - * get all level hooks - * @private - * @template {Hook} T - * @param {HookMap} hookMap HookMap - * @param {string} type type - * @returns {T[]} hooks - */ - _getAllLevelHooks(hookMap, type) { - let cache = /** @type {Map} */ ( - this._levelHookCache.get(hookMap) - ); - if (cache === undefined) { - cache = new Map(); - this._levelHookCache.set(hookMap, cache); - } - const cacheEntry = cache.get(type); - if (cacheEntry !== undefined) { - return cacheEntry; - } - /** @type {T[]} */ - const hooks = []; - const typeParts = type.split("."); - for (let i = 0; i < typeParts.length; i++) { - const hook = hookMap.get(typeParts.slice(i).join(".")); - if (hook) { - hooks.push(hook); +/** + * @template T + * @template R + * @param {T[]} items the list of items + * @param {GroupConfig[]} groupConfigs configuration + * @returns {(R | T)[]} grouped items + */ +const smartGrouping = (items, groupConfigs) => { + /** @type {Set>} */ + const itemsWithGroups = new Set(); + /** @type {Map>} */ + const allGroups = new Map(); + for (const item of items) { + /** @type {Set>} */ + const groups = new Set(); + for (let i = 0; i < groupConfigs.length; i++) { + const groupConfig = groupConfigs[i]; + const keys = groupConfig.getKeys(item); + if (keys) { + for (const name of keys) { + const key = `${i}:${name}`; + let group = allGroups.get(key); + if (group === undefined) { + allGroups.set( + key, + (group = { + config: groupConfig, + name, + alreadyGrouped: false, + items: undefined + }) + ); + } + groups.add(group); + } } } - cache.set(type, hooks); - return hooks; + itemsWithGroups.add({ + item, + groups + }); } - /** - * Run `fn` for each level - * @private - * @template T - * @template R - * @param {HookMap>} hookMap HookMap - * @param {string} type type - * @param {(hook: SyncBailHook) => R} fn function - * @returns {R} result of `fn` + * @param {Set>} itemsWithGroups input items with groups + * @returns {(T | R)[]} groups items */ - _forEachLevel(hookMap, type, fn) { - for (const hook of this._getAllLevelHooks(hookMap, type)) { - const result = fn(hook); - if (result !== undefined) return result; + const runGrouping = itemsWithGroups => { + const totalSize = itemsWithGroups.size; + for (const entry of itemsWithGroups) { + for (const group of entry.groups) { + if (group.alreadyGrouped) continue; + const items = group.items; + if (items === undefined) { + group.items = new Set([entry]); + } else { + items.add(entry); + } + } } - } - - /** - * Run `fn` for each level - * @private - * @template T - * @param {HookMap>} hookMap HookMap - * @param {string} type type - * @param {AsArray[0]} data data - * @param {(hook: SyncWaterfallHook, data: AsArray[0]) => AsArray[0]} fn function - * @returns {AsArray[0]} result of `fn` - */ - _forEachLevelWaterfall(hookMap, type, data, fn) { - for (const hook of this._getAllLevelHooks(hookMap, type)) { - data = fn(hook, data); + /** @type {Map, { items: Set>, options: GroupOptions | false | undefined, used: boolean }>} */ + const groupMap = new Map(); + for (const group of allGroups.values()) { + if (group.items) { + const items = group.items; + group.items = undefined; + groupMap.set(group, { + items, + options: undefined, + used: false + }); + } } - return data; - } + /** @type {(T | R)[]} */ + const results = []; + for (;;) { + /** @type {Group} */ + let bestGroup = undefined; + let bestGroupSize = -1; + let bestGroupItems = undefined; + let bestGroupOptions = undefined; + for (const [group, state] of groupMap) { + const { items, used } = state; + let options = state.options; + if (options === undefined) { + const groupConfig = group.config; + state.options = options = + (groupConfig.getOptions && + groupConfig.getOptions( + group.name, + Array.from(items, ({ item }) => item) + )) || + false; + } - /** - * @param {string} type The type - * @param {Object} object Object to print - * @param {Object=} baseContext The base context - * @returns {string} printed result - */ - print(type, object, baseContext) { - if (this._inPrint) { - return this._print(type, object, baseContext); - } else { - try { - this._inPrint = true; - return this._print(type, object, baseContext); - } finally { - this._levelHookCache.clear(); - this._inPrint = false; + const force = options && options.force; + if (!force) { + if (bestGroupOptions && bestGroupOptions.force) continue; + if (used) continue; + if (items.size <= 1 || totalSize - items.size <= 1) { + continue; + } + } + const targetGroupCount = (options && options.targetGroupCount) || 4; + let sizeValue = force + ? items.size + : Math.min( + items.size, + (totalSize * 2) / targetGroupCount + + itemsWithGroups.size - + items.size + ); + if ( + sizeValue > bestGroupSize || + (force && (!bestGroupOptions || !bestGroupOptions.force)) + ) { + bestGroup = group; + bestGroupSize = sizeValue; + bestGroupItems = items; + bestGroupOptions = options; + } } - } - } + if (bestGroup === undefined) { + break; + } + const items = new Set(bestGroupItems); + const options = bestGroupOptions; - /** - * @private - * @param {string} type type - * @param {Object} object object - * @param {Object=} baseContext context - * @returns {string} printed result - */ - _print(type, object, baseContext) { - const context = { - ...baseContext, - type, - [type]: object - }; + const groupChildren = !options || options.groupChildren !== false; - let printResult = this._forEachLevel(this.hooks.print, type, hook => - hook.call(object, context) - ); - if (printResult === undefined) { - if (Array.isArray(object)) { - const sortedItems = object.slice(); - this._forEachLevel(this.hooks.sortItems, type, h => - h.call(sortedItems, context) - ); - const printedItems = sortedItems.map((item, i) => { - const itemContext = { - ...context, - _index: i - }; - const itemName = this._forEachLevel( - this.hooks.getItemName, - `${type}[]`, - h => h.call(item, itemContext) - ); - if (itemName) itemContext[itemName] = item; - return this.print( - itemName ? `${type}[].${itemName}` : `${type}[]`, - item, - itemContext - ); - }); - printResult = this._forEachLevel(this.hooks.printItems, type, h => - h.call(printedItems, context) - ); - if (printResult === undefined) { - const result = printedItems.filter(Boolean); - if (result.length > 0) printResult = result.join("\n"); - } - } else if (object !== null && typeof object === "object") { - const elements = Object.keys(object).filter( - key => object[key] !== undefined - ); - this._forEachLevel(this.hooks.sortElements, type, h => - h.call(elements, context) - ); - const printedElements = elements.map(element => { - const content = this.print(`${type}.${element}`, object[element], { - ...context, - _parent: object, - _element: element, - [element]: object[element] - }); - return { element, content }; - }); - printResult = this._forEachLevel(this.hooks.printElements, type, h => - h.call(printedElements, context) - ); - if (printResult === undefined) { - const result = printedElements.map(e => e.content).filter(Boolean); - if (result.length > 0) printResult = result.join("\n"); + for (const item of items) { + itemsWithGroups.delete(item); + // Remove all groups that items have from the map to not select them again + for (const group of item.groups) { + const state = groupMap.get(group); + if (state !== undefined) { + state.items.delete(item); + if (state.items.size === 0) { + groupMap.delete(group); + } else { + state.options = undefined; + if (groupChildren) { + state.used = true; + } + } + } } } + groupMap.delete(bestGroup); + + const key = bestGroup.name; + const groupConfig = bestGroup.config; + + const allItems = Array.from(items, ({ item }) => item); + + bestGroup.alreadyGrouped = true; + const children = groupChildren ? runGrouping(items) : allItems; + bestGroup.alreadyGrouped = false; + + results.push(groupConfig.createGroup(key, children, allItems)); } + for (const { item } of itemsWithGroups) { + results.push(item); + } + return results; + }; + return runGrouping(itemsWithGroups); +}; - return this._forEachLevelWaterfall( - this.hooks.result, - type, - printResult, - (h, r) => h.call(r, context) - ); - } -} -module.exports = StatsPrinter; +module.exports = smartGrouping; /***/ }), -/***/ 84953: +/***/ 41245: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -128273,35 +129102,66 @@ module.exports = StatsPrinter; -exports.equals = (a, b) => { - if (a.length !== b.length) return false; - for (let i = 0; i < a.length; i++) { - if (a[i] !== b[i]) return false; - } - return true; +/** @typedef {import("webpack-sources").Source} Source */ + +/** @type {WeakMap>} */ +const equalityCache = new WeakMap(); + +/** + * @param {Source} a a source + * @param {Source} b another source + * @returns {boolean} true, when both sources are equal + */ +const _isSourceEqual = (a, b) => { + // prefer .buffer(), it's called anyway during emit + /** @type {Buffer|string} */ + let aSource = typeof a.buffer === "function" ? a.buffer() : a.source(); + /** @type {Buffer|string} */ + let bSource = typeof b.buffer === "function" ? b.buffer() : b.source(); + if (aSource === bSource) return true; + if (typeof aSource === "string" && typeof bSource === "string") return false; + if (!Buffer.isBuffer(aSource)) aSource = Buffer.from(aSource, "utf-8"); + if (!Buffer.isBuffer(bSource)) bSource = Buffer.from(bSource, "utf-8"); + return aSource.equals(bSource); }; /** - * - * @param {Array} arr Array of values to be partitioned - * @param {(value: any) => boolean} fn Partition function which partitions based on truthiness of result. - * @returns {[Array, Array]} returns the values of `arr` partitioned into two new arrays based on fn predicate. + * @param {Source} a a source + * @param {Source} b another source + * @returns {boolean} true, when both sources are equal */ -exports.groupBy = (arr = [], fn) => { - return arr.reduce( - (groups, value) => { - groups[fn(value) ? 0 : 1].push(value); - return groups; - }, - [[], []] - ); +const isSourceEqual = (a, b) => { + if (a === b) return true; + const cache1 = equalityCache.get(a); + if (cache1 !== undefined) { + const result = cache1.get(b); + if (result !== undefined) return result; + } + const result = _isSourceEqual(a, b); + if (cache1 !== undefined) { + cache1.set(b, result); + } else { + const map = new WeakMap(); + map.set(b, result); + equalityCache.set(a, map); + } + const cache2 = equalityCache.get(b); + if (cache2 !== undefined) { + cache2.set(a, result); + } else { + const map = new WeakMap(); + map.set(a, result); + equalityCache.set(b, map); + } + return result; }; +exports.isSourceEqual = isSourceEqual; /***/ }), -/***/ 41792: -/***/ (function(module) { +/***/ 12047: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -128311,115 +129171,179 @@ exports.groupBy = (arr = [], fn) => { +const { validate } = __webpack_require__(38476); + +/* cSpell:disable */ +const DID_YOU_MEAN = { + rules: "module.rules", + loaders: "module.rules or module.rules.*.use", + query: "module.rules.*.options (BREAKING CHANGE since webpack 5)", + noParse: "module.noParse", + filename: "output.filename or module.rules.*.generator.filename", + file: "output.filename", + chunkFilename: "output.chunkFilename", + chunkfilename: "output.chunkFilename", + ecmaVersion: + "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", + ecmaversion: + "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", + ecma: "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", + path: "output.path", + pathinfo: "output.pathinfo", + pathInfo: "output.pathinfo", + jsonpFunction: "output.chunkLoadingGlobal (BREAKING CHANGE since webpack 5)", + chunkCallbackName: + "output.chunkLoadingGlobal (BREAKING CHANGE since webpack 5)", + jsonpScriptType: "output.scriptType (BREAKING CHANGE since webpack 5)", + hotUpdateFunction: "output.hotUpdateGlobal (BREAKING CHANGE since webpack 5)", + splitChunks: "optimization.splitChunks", + immutablePaths: "snapshot.immutablePaths", + managedPaths: "snapshot.managedPaths", + maxModules: "stats.modulesSpace (BREAKING CHANGE since webpack 5)", + hashedModuleIds: + 'optimization.moduleIds: "hashed" (BREAKING CHANGE since webpack 5)', + namedChunks: + 'optimization.chunkIds: "named" (BREAKING CHANGE since webpack 5)', + namedModules: + 'optimization.moduleIds: "named" (BREAKING CHANGE since webpack 5)', + occurrenceOrder: + 'optimization.chunkIds: "size" and optimization.moduleIds: "size" (BREAKING CHANGE since webpack 5)', + automaticNamePrefix: + "optimization.splitChunks.[cacheGroups.*].idHint (BREAKING CHANGE since webpack 5)", + noEmitOnErrors: + "optimization.emitOnErrors (BREAKING CHANGE since webpack 5: logic is inverted to avoid negative flags)", + Buffer: + "to use the ProvidePlugin to process the Buffer variable to modules as polyfill\n" + + "BREAKING CHANGE: webpack 5 no longer provided Node.js polyfills by default.\n" + + "Note: if you are using 'node.Buffer: false', you can just remove that as this is the default behavior now.\n" + + "To provide a polyfill to modules use:\n" + + 'new ProvidePlugin({ Buffer: ["buffer", "Buffer"] }) and npm install buffer.', + process: + "to use the ProvidePlugin to process the process variable to modules as polyfill\n" + + "BREAKING CHANGE: webpack 5 no longer provided Node.js polyfills by default.\n" + + "Note: if you are using 'node.process: false', you can just remove that as this is the default behavior now.\n" + + "To provide a polyfill to modules use:\n" + + 'new ProvidePlugin({ process: "process" }) and npm install buffer.' +}; + +const REMOVED = { + concord: + "BREAKING CHANGE: resolve.concord has been removed and is no longer available.", + devtoolLineToLine: + "BREAKING CHANGE: output.devtoolLineToLine has been removed and is no longer available." +}; +/* cSpell:enable */ + /** - * @template T + * @param {Parameters[0]} schema a json schema + * @param {Parameters[1]} options the options that should be validated + * @param {Parameters[2]=} validationConfiguration configuration for generating errors + * @returns {void} */ -class ArrayQueue { - /** - * @param {Iterable=} items The initial elements. - */ - constructor(items) { - /** @private @type {T[]} */ - this._list = items ? Array.from(items) : []; - /** @private @type {T[]} */ - this._listReversed = []; - } - - /** - * Returns the number of elements in this queue. - * @returns {number} The number of elements in this queue. - */ - get length() { - return this._list.length + this._listReversed.length; - } +const validateSchema = (schema, options, validationConfiguration) => { + validate( + schema, + options, + validationConfiguration || { + name: "Webpack", + postFormatter: (formattedError, error) => { + const children = error.children; + if ( + children && + children.some( + child => + child.keyword === "absolutePath" && + child.dataPath === ".output.filename" + ) + ) { + return `${formattedError}\nPlease use output.path to specify absolute path and output.filename for the file name.`; + } - /** - * Empties the queue. - */ - clear() { - this._list.length = 0; - this._listReversed.length = 0; - } + if ( + children && + children.some( + child => + child.keyword === "pattern" && child.dataPath === ".devtool" + ) + ) { + return ( + `${formattedError}\n` + + "BREAKING CHANGE since webpack 5: The devtool option is more strict.\n" + + "Please strictly follow the order of the keywords in the pattern." + ); + } - /** - * Appends the specified element to this queue. - * @param {T} item The element to add. - * @returns {void} - */ - enqueue(item) { - this._list.push(item); - } + if (error.keyword === "additionalProperties") { + const params = + /** @type {import("ajv").AdditionalPropertiesParams} */ ( + error.params + ); + if ( + Object.prototype.hasOwnProperty.call( + DID_YOU_MEAN, + params.additionalProperty + ) + ) { + return `${formattedError}\nDid you mean ${ + DID_YOU_MEAN[params.additionalProperty] + }?`; + } - /** - * Retrieves and removes the head of this queue. - * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. - */ - dequeue() { - if (this._listReversed.length === 0) { - if (this._list.length === 0) return undefined; - if (this._list.length === 1) return this._list.pop(); - if (this._list.length < 16) return this._list.shift(); - const temp = this._listReversed; - this._listReversed = this._list; - this._listReversed.reverse(); - this._list = temp; - } - return this._listReversed.pop(); - } + if ( + Object.prototype.hasOwnProperty.call( + REMOVED, + params.additionalProperty + ) + ) { + return `${formattedError}\n${REMOVED[params.additionalProperty]}?`; + } - /** - * Finds and removes an item - * @param {T} item the item - * @returns {void} - */ - delete(item) { - const i = this._list.indexOf(item); - if (i >= 0) { - this._list.splice(i, 1); - } else { - const i = this._listReversed.indexOf(item); - if (i >= 0) this._listReversed.splice(i, 1); - } - } + if (!error.dataPath) { + if (params.additionalProperty === "debug") { + return ( + `${formattedError}\n` + + "The 'debug' property was removed in webpack 2.0.0.\n" + + "Loaders should be updated to allow passing this option via loader options in module.rules.\n" + + "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" + + "plugins: [\n" + + " new webpack.LoaderOptionsPlugin({\n" + + " debug: true\n" + + " })\n" + + "]" + ); + } - [Symbol.iterator]() { - let i = -1; - let reversed = false; - return { - next: () => { - if (!reversed) { - i++; - if (i < this._list.length) { - return { - done: false, - value: this._list[i] - }; + if (params.additionalProperty) { + return ( + `${formattedError}\n` + + "For typos: please correct them.\n" + + "For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.\n" + + " Loaders should be updated to allow passing options via loader options in module.rules.\n" + + " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" + + " plugins: [\n" + + " new webpack.LoaderOptionsPlugin({\n" + + " // test: /\\.xxx$/, // may apply this only for some modules\n" + + " options: {\n" + + ` ${params.additionalProperty}: …\n` + + " }\n" + + " })\n" + + " ]" + ); + } } - reversed = true; - i = this._listReversed.length; } - i--; - if (i < 0) { - return { - done: true, - value: undefined - }; - } - return { - done: false, - value: this._listReversed[i] - }; - } - }; - } -} -module.exports = ArrayQueue; + return formattedError; + } + } + ); +}; +module.exports = validateSchema; /***/ }), -/***/ 12260: +/***/ 5434: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -128430,377 +129354,143 @@ module.exports = ArrayQueue; -const { SyncHook, AsyncSeriesHook } = __webpack_require__(41242); -const { makeWebpackError } = __webpack_require__(11351); -const WebpackError = __webpack_require__(53799); -const ArrayQueue = __webpack_require__(41792); - -const QUEUED_STATE = 0; -const PROCESSING_STATE = 1; -const DONE_STATE = 2; - -let inHandleResult = 0; +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); -/** - * @template T - * @callback Callback - * @param {(WebpackError | null)=} err - * @param {T=} result - */ +class AsyncWasmLoadingRuntimeModule extends RuntimeModule { + constructor({ generateLoadBinaryCode, supportsStreaming }) { + super("wasm loading", RuntimeModule.STAGE_NORMAL); + this.generateLoadBinaryCode = generateLoadBinaryCode; + this.supportsStreaming = supportsStreaming; + } -/** - * @template T - * @template K - * @template R - */ -class AsyncQueueEntry { /** - * @param {T} item the item - * @param {Callback} callback the callback + * @returns {string} runtime code */ - constructor(item, callback) { - this.item = item; - /** @type {typeof QUEUED_STATE | typeof PROCESSING_STATE | typeof DONE_STATE} */ - this.state = QUEUED_STATE; - this.callback = callback; - /** @type {Callback[] | undefined} */ - this.callbacks = undefined; - this.result = undefined; - /** @type {WebpackError | undefined} */ - this.error = undefined; + generate() { + const { compilation, chunk } = this; + const { outputOptions, runtimeTemplate } = compilation; + const fn = RuntimeGlobals.instantiateWasm; + const wasmModuleSrcPath = compilation.getPath( + JSON.stringify(outputOptions.webassemblyModuleFilename), + { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: length => + `" + ${RuntimeGlobals.getFullHash}}().slice(0, ${length}) + "`, + module: { + id: '" + wasmModuleId + "', + hash: `" + wasmModuleHash + "`, + hashWithLength(length) { + return `" + wasmModuleHash.slice(0, ${length}) + "`; + } + }, + runtime: chunk.runtime + } + ); + return `${fn} = ${runtimeTemplate.basicFunction( + "exports, wasmModuleId, wasmModuleHash, importsObj", + [ + `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, + this.supportsStreaming + ? Template.asString([ + "if (typeof WebAssembly.instantiateStreaming === 'function') {", + Template.indent([ + "return WebAssembly.instantiateStreaming(req, importsObj)", + Template.indent([ + `.then(${runtimeTemplate.returningFunction( + "Object.assign(exports, res.instance.exports)", + "res" + )});` + ]) + ]), + "}" + ]) + : "// no support for streaming compilation", + "return req", + Template.indent([ + `.then(${runtimeTemplate.returningFunction("x.arrayBuffer()", "x")})`, + `.then(${runtimeTemplate.returningFunction( + "WebAssembly.instantiate(bytes, importsObj)", + "bytes" + )})`, + `.then(${runtimeTemplate.returningFunction( + "Object.assign(exports, res.instance.exports)", + "res" + )});` + ]) + ] + )};`; } } -/** - * @template T - * @template K - * @template R - */ -class AsyncQueue { - /** - * @param {Object} options options object - * @param {string=} options.name name of the queue - * @param {number=} options.parallelism how many items should be processed at once - * @param {AsyncQueue=} options.parent parent queue, which will have priority over this queue and with shared parallelism - * @param {function(T): K=} options.getKey extract key from item - * @param {function(T, Callback): void} options.processor async function to process items - */ - constructor({ name, parallelism, parent, processor, getKey }) { - this._name = name; - this._parallelism = parallelism || 1; - this._processor = processor; - this._getKey = - getKey || /** @type {(T) => K} */ (item => /** @type {any} */ (item)); - /** @type {Map>} */ - this._entries = new Map(); - /** @type {ArrayQueue>} */ - this._queued = new ArrayQueue(); - /** @type {AsyncQueue[]} */ - this._children = undefined; - this._activeTasks = 0; - this._willEnsureProcessing = false; - this._needProcessing = false; - this._stopped = false; - this._root = parent ? parent._root : this; - if (parent) { - if (this._root._children === undefined) { - this._root._children = [this]; - } else { - this._root._children.push(this); - } - } +module.exports = AsyncWasmLoadingRuntimeModule; - this.hooks = { - /** @type {AsyncSeriesHook<[T]>} */ - beforeAdd: new AsyncSeriesHook(["item"]), - /** @type {SyncHook<[T]>} */ - added: new SyncHook(["item"]), - /** @type {AsyncSeriesHook<[T]>} */ - beforeStart: new AsyncSeriesHook(["item"]), - /** @type {SyncHook<[T]>} */ - started: new SyncHook(["item"]), - /** @type {SyncHook<[T, Error, R]>} */ - result: new SyncHook(["item", "error", "result"]) - }; - this._ensureProcessing = this._ensureProcessing.bind(this); - } +/***/ }), - /** - * @param {T} item an item - * @param {Callback} callback callback function - * @returns {void} - */ - add(item, callback) { - if (this._stopped) return callback(new WebpackError("Queue was stopped")); - this.hooks.beforeAdd.callAsync(item, err => { - if (err) { - callback( - makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeAdd`) - ); - return; - } - const key = this._getKey(item); - const entry = this._entries.get(key); - if (entry !== undefined) { - if (entry.state === DONE_STATE) { - if (inHandleResult++ > 3) { - process.nextTick(() => callback(entry.error, entry.result)); - } else { - callback(entry.error, entry.result); - } - inHandleResult--; - } else if (entry.callbacks === undefined) { - entry.callbacks = [callback]; - } else { - entry.callbacks.push(callback); - } - return; - } - const newEntry = new AsyncQueueEntry(item, callback); - if (this._stopped) { - this.hooks.added.call(item); - this._root._activeTasks++; - process.nextTick(() => - this._handleResult(newEntry, new WebpackError("Queue was stopped")) - ); - } else { - this._entries.set(key, newEntry); - this._queued.enqueue(newEntry); - const root = this._root; - root._needProcessing = true; - if (root._willEnsureProcessing === false) { - root._willEnsureProcessing = true; - setImmediate(root._ensureProcessing); - } - this.hooks.added.call(item); - } - }); - } +/***/ 58461: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @param {T} item an item - * @returns {void} - */ - invalidate(item) { - const key = this._getKey(item); - const entry = this._entries.get(key); - this._entries.delete(key); - if (entry.state === QUEUED_STATE) { - this._queued.delete(entry); - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * Waits for an already started item - * @param {T} item an item - * @param {Callback} callback callback function - * @returns {void} - */ - waitFor(item, callback) { - const key = this._getKey(item); - const entry = this._entries.get(key); - if (entry === undefined) { - return callback( - new WebpackError( - "waitFor can only be called for an already started item" - ) - ); - } - if (entry.state === DONE_STATE) { - process.nextTick(() => callback(entry.error, entry.result)); - } else if (entry.callbacks === undefined) { - entry.callbacks = [callback]; - } else { - entry.callbacks.push(callback); - } - } - /** - * @returns {void} - */ - stop() { - this._stopped = true; - const queue = this._queued; - this._queued = new ArrayQueue(); - const root = this._root; - for (const entry of queue) { - this._entries.delete(this._getKey(entry.item)); - root._activeTasks++; - this._handleResult(entry, new WebpackError("Queue was stopped")); - } - } - /** - * @returns {void} - */ - increaseParallelism() { - const root = this._root; - root._parallelism++; - /* istanbul ignore next */ - if (root._willEnsureProcessing === false && root._needProcessing) { - root._willEnsureProcessing = true; - setImmediate(root._ensureProcessing); - } - } +const Generator = __webpack_require__(93401); - /** - * @returns {void} - */ - decreaseParallelism() { - const root = this._root; - root._parallelism--; - } +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../NormalModule")} NormalModule */ - /** - * @param {T} item an item - * @returns {boolean} true, if the item is currently being processed - */ - isProcessing(item) { - const key = this._getKey(item); - const entry = this._entries.get(key); - return entry !== undefined && entry.state === PROCESSING_STATE; - } +const TYPES = new Set(["webassembly"]); - /** - * @param {T} item an item - * @returns {boolean} true, if the item is currently queued - */ - isQueued(item) { - const key = this._getKey(item); - const entry = this._entries.get(key); - return entry !== undefined && entry.state === QUEUED_STATE; +class AsyncWebAssemblyGenerator extends Generator { + constructor(options) { + super(); + this.options = options; } /** - * @param {T} item an item - * @returns {boolean} true, if the item is currently queued + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - isDone(item) { - const key = this._getKey(item); - const entry = this._entries.get(key); - return entry !== undefined && entry.state === DONE_STATE; + getTypes(module) { + return TYPES; } /** - * @returns {void} + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - _ensureProcessing() { - while (this._activeTasks < this._parallelism) { - const entry = this._queued.dequeue(); - if (entry === undefined) break; - this._activeTasks++; - entry.state = PROCESSING_STATE; - this._startProcessing(entry); - } - this._willEnsureProcessing = false; - if (this._queued.length > 0) return; - if (this._children !== undefined) { - for (const child of this._children) { - while (this._activeTasks < this._parallelism) { - const entry = child._queued.dequeue(); - if (entry === undefined) break; - this._activeTasks++; - entry.state = PROCESSING_STATE; - child._startProcessing(entry); - } - if (child._queued.length > 0) return; - } + getSize(module, type) { + const originalSource = module.originalSource(); + if (!originalSource) { + return 0; } - if (!this._willEnsureProcessing) this._needProcessing = false; - } - - /** - * @param {AsyncQueueEntry} entry the entry - * @returns {void} - */ - _startProcessing(entry) { - this.hooks.beforeStart.callAsync(entry.item, err => { - if (err) { - this._handleResult( - entry, - makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeStart`) - ); - return; - } - let inCallback = false; - try { - this._processor(entry.item, (e, r) => { - inCallback = true; - this._handleResult(entry, e, r); - }); - } catch (err) { - if (inCallback) throw err; - this._handleResult(entry, err, null); - } - this.hooks.started.call(entry.item); - }); + return originalSource.size(); } /** - * @param {AsyncQueueEntry} entry the entry - * @param {WebpackError=} err error, if any - * @param {R=} result result, if any - * @returns {void} - */ - _handleResult(entry, err, result) { - this.hooks.result.callAsync(entry.item, err, result, hookError => { - const error = hookError - ? makeWebpackError(hookError, `AsyncQueue(${this._name}).hooks.result`) - : err; - - const callback = entry.callback; - const callbacks = entry.callbacks; - entry.state = DONE_STATE; - entry.callback = undefined; - entry.callbacks = undefined; - entry.result = result; - entry.error = error; - - const root = this._root; - root._activeTasks--; - if (root._willEnsureProcessing === false && root._needProcessing) { - root._willEnsureProcessing = true; - setImmediate(root._ensureProcessing); - } - - if (inHandleResult++ > 3) { - process.nextTick(() => { - callback(error, result); - if (callbacks !== undefined) { - for (const callback of callbacks) { - callback(error, result); - } - } - }); - } else { - callback(error, result); - if (callbacks !== undefined) { - for (const callback of callbacks) { - callback(error, result); - } - } - } - inHandleResult--; - }); - } - - clear() { - this._entries.clear(); - this._queued.clear(); - this._activeTasks = 0; - this._willEnsureProcessing = false; - this._needProcessing = false; - this._stopped = false; + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code + */ + generate(module, generateContext) { + return module.originalSource(); } } -module.exports = AsyncQueue; +module.exports = AsyncWebAssemblyGenerator; /***/ }), -/***/ 36692: +/***/ 95614: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -128811,93 +129501,192 @@ module.exports = AsyncQueue; -class Hash { - /* istanbul ignore next */ +const { RawSource } = __webpack_require__(51255); +const Generator = __webpack_require__(93401); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const WebAssemblyImportDependency = __webpack_require__(5239); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ + +const TYPES = new Set(["webassembly"]); + +class AsyncWebAssemblyJavascriptGenerator extends Generator { + constructor(filenameTemplate) { + super(); + this.filenameTemplate = filenameTemplate; + } + /** - * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} - * @abstract - * @param {string|Buffer} data data - * @param {string=} inputEncoding data encoding - * @returns {this} updated hash + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - update(data, inputEncoding) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + getTypes(module) { + return TYPES; } - /* istanbul ignore next */ /** - * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} - * @abstract - * @param {string=} encoding encoding of the return value - * @returns {string|Buffer} digest + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - digest(encoding) { - const AbstractMethodError = __webpack_require__(77198); - throw new AbstractMethodError(); + getSize(module, type) { + return 40 + module.dependencies.length * 10; } -} -module.exports = Hash; + /** + * @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 { + runtimeTemplate, + chunkGraph, + moduleGraph, + runtimeRequirements, + runtime + } = generateContext; + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(RuntimeGlobals.moduleId); + runtimeRequirements.add(RuntimeGlobals.exports); + runtimeRequirements.add(RuntimeGlobals.instantiateWasm); + /** @type {InitFragment[]} */ + const initFragments = []; + /** @type {Map} */ + const depModules = new Map(); + /** @type {Map} */ + const wasmDepsByRequest = new Map(); + for (const dep of module.dependencies) { + if (dep instanceof WebAssemblyImportDependency) { + const module = moduleGraph.getModule(dep); + if (!depModules.has(module)) { + depModules.set(module, { + request: dep.request, + importVar: `WEBPACK_IMPORTED_MODULE_${depModules.size}` + }); + } + let list = wasmDepsByRequest.get(dep.request); + if (list === undefined) { + list = []; + wasmDepsByRequest.set(dep.request, list); + } + list.push(dep); + } + } + const promises = []; -/***/ }), + const importStatements = Array.from( + depModules, + ([importedModule, { request, importVar }]) => { + if (moduleGraph.isAsync(importedModule)) { + promises.push(importVar); + } + return runtimeTemplate.importStatement({ + update: false, + module: importedModule, + chunkGraph, + request, + originModule: module, + importVar, + runtimeRequirements + }); + } + ); + const importsCode = importStatements.map(([x]) => x).join(""); + const importsCompatCode = importStatements.map(([_, x]) => x).join(""); -/***/ 39104: -/***/ (function(__unused_webpack_module, exports) { + const importObjRequestItems = Array.from( + wasmDepsByRequest, + ([request, deps]) => { + const exportItems = deps.map(dep => { + const importedModule = moduleGraph.getModule(dep); + const importVar = depModules.get(importedModule).importVar; + return `${JSON.stringify( + dep.name + )}: ${runtimeTemplate.exportFromImport({ + moduleGraph, + module: importedModule, + request, + exportName: dep.name, + originModule: module, + asiSafe: true, + isCall: false, + callContext: false, + defaultInterop: true, + importVar, + initFragments, + runtime, + runtimeRequirements + })}`; + }); + return Template.asString([ + `${JSON.stringify(request)}: {`, + Template.indent(exportItems.join(",\n")), + "}" + ]); + } + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const importsObj = + importObjRequestItems.length > 0 + ? Template.asString([ + "{", + Template.indent(importObjRequestItems.join(",\n")), + "}" + ]) + : undefined; + const instantiateCall = + `${RuntimeGlobals.instantiateWasm}(${module.exportsArgument}, ${ + module.moduleArgument + }.id, ${JSON.stringify( + chunkGraph.getRenderedModuleHash(module, runtime) + )}` + (importsObj ? `, ${importsObj})` : `)`); + if (promises.length > 0) + runtimeRequirements.add(RuntimeGlobals.asyncModule); -/** - * @template T - * @param {Iterable} set a set - * @returns {T | undefined} last item - */ -const last = set => { - let last; - for (const item of set) last = item; - return last; -}; + const source = new RawSource( + promises.length > 0 + ? Template.asString([ + `var __webpack_instantiate__ = ${runtimeTemplate.basicFunction( + `[${promises.join(", ")}]`, + `${importsCompatCode}return ${instantiateCall};` + )}`, + `${RuntimeGlobals.asyncModule}(${ + module.moduleArgument + }, ${runtimeTemplate.basicFunction( + "__webpack_handle_async_dependencies__", + [ + importsCode, + `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${promises.join( + ", " + )}]);`, + "return __webpack_async_dependencies__.then ? __webpack_async_dependencies__.then(__webpack_instantiate__) : __webpack_instantiate__(__webpack_async_dependencies__);" + ] + )}, 1);` + ]) + : `${importsCode}${importsCompatCode}module.exports = ${instantiateCall};` + ); -/** - * @template T - * @param {Iterable} iterable iterable - * @param {function(T): boolean} filter predicate - * @returns {boolean} true, if some items match the filter predicate - */ -const someInIterable = (iterable, filter) => { - for (const item of iterable) { - if (filter(item)) return true; + return InitFragment.addToSource(source, initFragments, generateContext); } - return false; -}; - -/** - * @template T - * @param {Iterable} iterable an iterable - * @returns {number} count of items - */ -const countIterable = iterable => { - let i = 0; - // eslint-disable-next-line no-unused-vars - for (const _ of iterable) i++; - return i; -}; +} -exports.last = last; -exports.someInIterable = someInIterable; -exports.countIterable = countIterable; +module.exports = AsyncWebAssemblyJavascriptGenerator; /***/ }), -/***/ 48424: +/***/ 7538: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -128908,240 +129697,202 @@ exports.countIterable = countIterable; -const { first } = __webpack_require__(93347); -const SortableSet = __webpack_require__(13098); +const { SyncWaterfallHook } = __webpack_require__(6967); +const Compilation = __webpack_require__(85720); +const Generator = __webpack_require__(93401); +const { tryRunOrWebpackError } = __webpack_require__(11351); +const WebAssemblyImportDependency = __webpack_require__(5239); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const memoize = __webpack_require__(78676); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../Template").RenderManifestEntry} RenderManifestEntry */ +/** @typedef {import("../Template").RenderManifestOptions} RenderManifestOptions */ + +const getAsyncWebAssemblyGenerator = memoize(() => + __webpack_require__(58461) +); +const getAsyncWebAssemblyJavascriptGenerator = memoize(() => + __webpack_require__(95614) +); +const getAsyncWebAssemblyParser = memoize(() => + __webpack_require__(96305) +); /** - * Multi layer bucket sorted set: - * Supports adding non-existing items (DO NOT ADD ITEM TWICE), - * Supports removing exiting items (DO NOT REMOVE ITEM NOT IN SET), - * Supports popping the first items according to defined order, - * Supports iterating all items without order, - * Supports updating an item in an efficient way, - * Supports size property, which is the number of items, - * Items are lazy partially sorted when needed - * @template T - * @template K + * @typedef {Object} WebAssemblyRenderContext + * @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 + * @property {CodeGenerationResults} codeGenerationResults results of code generation */ -class LazyBucketSortedSet { - /** - * @param {function(T): K} getKey function to get key from item - * @param {function(K, K): number} comparator comparator to sort keys - * @param {...((function(T): any) | (function(any, any): number))} args more pairs of getKey and comparator plus optional final comparator for the last layer - */ - constructor(getKey, comparator, ...args) { - this._getKey = getKey; - this._innerArgs = args; - this._leaf = args.length <= 1; - this._keys = new SortableSet(undefined, comparator); - /** @type {Map | SortableSet>} */ - this._map = new Map(); - this._unsortedItems = new Set(); - this.size = 0; - } - /** - * @param {T} item an item - * @returns {void} - */ - add(item) { - this.size++; - this._unsortedItems.add(item); - } +/** + * @typedef {Object} CompilationHooks + * @property {SyncWaterfallHook<[Source, Module, WebAssemblyRenderContext]>} renderModuleContent + */ - /** - * @param {K} key key of item - * @param {T} item the item - * @returns {void} - */ - _addInternal(key, item) { - let entry = this._map.get(key); - if (entry === undefined) { - entry = this._leaf - ? new SortableSet(undefined, this._innerArgs[0]) - : new /** @type {any} */ (LazyBucketSortedSet)(...this._innerArgs); - this._keys.add(key); - this._map.set(key, entry); - } - entry.add(item); - } +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); +class AsyncWebAssemblyModulesPlugin { /** - * @param {T} item an item - * @returns {void} + * @param {Compilation} compilation the compilation + * @returns {CompilationHooks} the attached hooks */ - delete(item) { - this.size--; - if (this._unsortedItems.has(item)) { - this._unsortedItems.delete(item); - return; + static getCompilationHooks(compilation) { + if (!(compilation instanceof Compilation)) { + throw new TypeError( + "The 'compilation' argument must be an instance of Compilation" + ); } - const key = this._getKey(item); - const entry = this._map.get(key); - entry.delete(item); - if (entry.size === 0) { - this._deleteKey(key); + let hooks = compilationHooksMap.get(compilation); + if (hooks === undefined) { + hooks = { + renderModuleContent: new SyncWaterfallHook([ + "source", + "module", + "renderContext" + ]) + }; + compilationHooksMap.set(compilation, hooks); } + return hooks; } - /** - * @param {K} key key to be removed - * @returns {void} - */ - _deleteKey(key) { - this._keys.delete(key); - this._map.delete(key); + constructor(options) { + this.options = options; } /** - * @returns {T | undefined} an item + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - popFirst() { - if (this.size === 0) return undefined; - this.size--; - if (this._unsortedItems.size > 0) { - for (const item of this._unsortedItems) { - const key = this._getKey(item); - this._addInternal(key, item); - } - this._unsortedItems.clear(); - } - this._keys.sort(); - const key = first(this._keys); - const entry = this._map.get(key); - if (this._leaf) { - const leafEntry = /** @type {SortableSet} */ (entry); - leafEntry.sort(); - const item = first(leafEntry); - leafEntry.delete(item); - if (leafEntry.size === 0) { - this._deleteKey(key); - } - return item; - } else { - const nodeEntry = /** @type {LazyBucketSortedSet} */ (entry); - const item = nodeEntry.popFirst(); - if (nodeEntry.size === 0) { - this._deleteKey(key); - } - return item; - } - } + apply(compiler) { + compiler.hooks.compilation.tap( + "AsyncWebAssemblyModulesPlugin", + (compilation, { normalModuleFactory }) => { + const hooks = + AsyncWebAssemblyModulesPlugin.getCompilationHooks(compilation); + compilation.dependencyFactories.set( + WebAssemblyImportDependency, + normalModuleFactory + ); - /** - * @param {T} item to be updated item - * @returns {function(true=): void} finish update - */ - startUpdate(item) { - if (this._unsortedItems.has(item)) { - return remove => { - if (remove) { - this._unsortedItems.delete(item); - this.size--; - return; - } - }; - } - const key = this._getKey(item); - if (this._leaf) { - const oldEntry = /** @type {SortableSet} */ (this._map.get(key)); - return remove => { - if (remove) { - this.size--; - oldEntry.delete(item); - if (oldEntry.size === 0) { - this._deleteKey(key); - } - return; - } - const newKey = this._getKey(item); - if (key === newKey) { - // This flags the sortable set as unordered - oldEntry.add(item); - } else { - oldEntry.delete(item); - if (oldEntry.size === 0) { - this._deleteKey(key); - } - this._addInternal(newKey, item); - } - }; - } else { - const oldEntry = /** @type {LazyBucketSortedSet} */ ( - this._map.get(key) - ); - const finishUpdate = oldEntry.startUpdate(item); - return remove => { - if (remove) { - this.size--; - finishUpdate(true); - if (oldEntry.size === 0) { - this._deleteKey(key); - } - return; - } - const newKey = this._getKey(item); - if (key === newKey) { - finishUpdate(); - } else { - finishUpdate(true); - if (oldEntry.size === 0) { - this._deleteKey(key); - } - this._addInternal(newKey, item); - } - }; - } - } + normalModuleFactory.hooks.createParser + .for("webassembly/async") + .tap("AsyncWebAssemblyModulesPlugin", () => { + const AsyncWebAssemblyParser = getAsyncWebAssemblyParser(); - /** - * @param {Iterator[]} iterators list of iterators to append to - * @returns {void} - */ - _appendIterators(iterators) { - if (this._unsortedItems.size > 0) - iterators.push(this._unsortedItems[Symbol.iterator]()); - for (const key of this._keys) { - const entry = this._map.get(key); - if (this._leaf) { - const leafEntry = /** @type {SortableSet} */ (entry); - const iterator = leafEntry[Symbol.iterator](); - iterators.push(iterator); - } else { - const nodeEntry = /** @type {LazyBucketSortedSet} */ (entry); - nodeEntry._appendIterators(iterators); + return new AsyncWebAssemblyParser(); + }); + normalModuleFactory.hooks.createGenerator + .for("webassembly/async") + .tap("AsyncWebAssemblyModulesPlugin", () => { + const AsyncWebAssemblyJavascriptGenerator = + getAsyncWebAssemblyJavascriptGenerator(); + const AsyncWebAssemblyGenerator = getAsyncWebAssemblyGenerator(); + + return Generator.byType({ + javascript: new AsyncWebAssemblyJavascriptGenerator( + compilation.outputOptions.webassemblyModuleFilename + ), + webassembly: new AsyncWebAssemblyGenerator(this.options) + }); + }); + + compilation.hooks.renderManifest.tap( + "WebAssemblyModulesPlugin", + (result, options) => { + const { moduleGraph, chunkGraph, runtimeTemplate } = compilation; + const { + chunk, + outputOptions, + dependencyTemplates, + codeGenerationResults + } = options; + + for (const module of chunkGraph.getOrderedChunkModulesIterable( + chunk, + compareModulesByIdentifier + )) { + if (module.type === "webassembly/async") { + const filenameTemplate = + outputOptions.webassemblyModuleFilename; + + result.push({ + render: () => + this.renderModule( + module, + { + chunk, + dependencyTemplates, + runtimeTemplate, + moduleGraph, + chunkGraph, + codeGenerationResults + }, + hooks + ), + filenameTemplate, + pathOptions: { + module, + runtime: chunk.runtime, + chunkGraph + }, + auxiliary: true, + identifier: `webassemblyAsyncModule${chunkGraph.getModuleId( + module + )}`, + hash: chunkGraph.getModuleHash(module, chunk.runtime) + }); + } + } + + return result; + } + ); } - } + ); } - /** - * @returns {Iterator} the iterator - */ - [Symbol.iterator]() { - const iterators = []; - this._appendIterators(iterators); - iterators.reverse(); - let currentIterator = iterators.pop(); - return { - next: () => { - const res = currentIterator.next(); - if (res.done) { - if (iterators.length === 0) return res; - currentIterator = iterators.pop(); - return currentIterator.next(); - } - return res; - } - }; + renderModule(module, renderContext, hooks) { + const { codeGenerationResults, chunk } = renderContext; + try { + const moduleSource = codeGenerationResults.getSource( + module, + chunk.runtime, + "webassembly" + ); + return tryRunOrWebpackError( + () => + hooks.renderModuleContent.call(moduleSource, module, renderContext), + "AsyncWebAssemblyModulesPlugin.getCompilationHooks().renderModuleContent" + ); + } catch (e) { + e.module = module; + throw e; + } } } -module.exports = LazyBucketSortedSet; +module.exports = AsyncWebAssemblyModulesPlugin; /***/ }), -/***/ 38938: +/***/ 96305: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -129152,310 +129903,484 @@ module.exports = LazyBucketSortedSet; -const makeSerializable = __webpack_require__(33032); +const t = __webpack_require__(51826); +const { decode } = __webpack_require__(73726); +const Parser = __webpack_require__(11715); +const StaticExportsDependency = __webpack_require__(91418); +const WebAssemblyImportDependency = __webpack_require__(5239); -/** - * @template T - * @param {Set} targetSet set where items should be added - * @param {Set>} toMerge iterables to be merged - * @returns {void} - */ -const merge = (targetSet, toMerge) => { - for (const set of toMerge) { - for (const item of set) { - targetSet.add(item); - } - } +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ + +const decoderOpts = { + ignoreCodeSection: true, + ignoreDataSection: true, + + // this will avoid having to lookup with identifiers in the ModuleContext + ignoreCustomNameSection: true }; -/** - * @template T - * @param {Set>} targetSet set where iterables should be added - * @param {Array>} toDeepMerge lazy sets to be flattened - * @returns {void} - */ -const flatten = (targetSet, toDeepMerge) => { - for (const set of toDeepMerge) { - if (set._set.size > 0) targetSet.add(set._set); - if (set._needMerge) { - for (const mergedSet of set._toMerge) { - targetSet.add(mergedSet); - } - flatten(targetSet, set._toDeepMerge); - } +class WebAssemblyParser extends Parser { + constructor(options) { + super(); + this.hooks = Object.freeze({}); + this.options = options; } -}; -/** - * Like Set but with an addAll method to eventually add items from another iterable. - * Access methods make sure that all delayed operations are executed. - * Iteration methods deopts to normal Set performance until clear is called again (because of the chance of modifications during iteration). - * @template T - */ -class LazySet { /** - * @param {Iterable=} iterable init iterable + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state */ - constructor(iterable) { - /** @type {Set} */ - this._set = new Set(iterable); - /** @type {Set>} */ - this._toMerge = new Set(); - /** @type {Array>} */ - this._toDeepMerge = []; - this._needMerge = false; - this._deopt = false; - } - - _flatten() { - flatten(this._toMerge, this._toDeepMerge); - this._toDeepMerge.length = 0; - } + parse(source, state) { + if (!Buffer.isBuffer(source)) { + throw new Error("WebAssemblyParser input must be a Buffer"); + } - _merge() { - this._flatten(); - merge(this._set, this._toMerge); - this._toMerge.clear(); - this._needMerge = false; - } + // flag it as async module + state.module.buildInfo.strict = true; + state.module.buildMeta.exportsType = "namespace"; + state.module.buildMeta.async = true; - _isEmpty() { - return ( - this._set.size === 0 && - this._toMerge.size === 0 && - this._toDeepMerge.length === 0 - ); - } + // parse it + const program = decode(source, decoderOpts); + const module = program.body[0]; - get size() { - if (this._needMerge) this._merge(); - return this._set.size; - } + const exports = []; + t.traverse(module, { + ModuleExport({ node }) { + exports.push(node.name); + }, - /** - * @param {T} item an item - * @returns {this} itself - */ - add(item) { - this._set.add(item); - return this; - } + ModuleImport({ node }) { + const dep = new WebAssemblyImportDependency( + node.module, + node.name, + node.descr, + false + ); - /** - * @param {Iterable | LazySet} iterable a immutable iterable or another immutable LazySet which will eventually be merged into the Set - * @returns {this} itself - */ - addAll(iterable) { - if (this._deopt) { - const _set = this._set; - for (const item of iterable) { - _set.add(item); - } - } else { - if (iterable instanceof LazySet) { - if (iterable._isEmpty()) return this; - this._toDeepMerge.push(iterable); - this._needMerge = true; - if (this._toDeepMerge.length > 100000) { - this._flatten(); - } - } else { - this._toMerge.add(iterable); - this._needMerge = true; + state.module.addDependency(dep); } - if (this._toMerge.size > 100000) this._merge(); - } - return this; - } + }); - clear() { - this._set.clear(); - this._toMerge.clear(); - this._toDeepMerge.length = 0; - this._needMerge = false; - this._deopt = false; - } + state.module.addDependency(new StaticExportsDependency(exports, false)); - /** - * @param {T} value an item - * @returns {boolean} true, if the value was in the Set before - */ - delete(value) { - if (this._needMerge) this._merge(); - return this._set.delete(value); + return state; } +} - entries() { - this._deopt = true; - if (this._needMerge) this._merge(); - return this._set.entries(); - } +module.exports = WebAssemblyParser; - /** - * @param {function(T, T, Set): void} callbackFn function called for each entry - * @param {any} thisArg this argument for the callbackFn - * @returns {void} - */ - forEach(callbackFn, thisArg) { - this._deopt = true; - if (this._needMerge) this._merge(); - this._set.forEach(callbackFn, thisArg); - } - /** - * @param {T} item an item - * @returns {boolean} true, when the item is in the Set - */ - has(item) { - if (this._needMerge) this._merge(); - return this._set.has(item); - } +/***/ }), - keys() { - this._deopt = true; - if (this._needMerge) this._merge(); - return this._set.keys(); - } +/***/ 78455: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - values() { - this._deopt = true; - if (this._needMerge) this._merge(); - return this._set.values(); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - [Symbol.iterator]() { - this._deopt = true; - if (this._needMerge) this._merge(); - return this._set[Symbol.iterator](); - } - /* istanbul ignore next */ - get [Symbol.toStringTag]() { - return "LazySet"; - } - serialize({ write }) { - if (this._needMerge) this._merge(); - write(this._set.size); - for (const item of this._set) write(item); - } +const WebpackError = __webpack_require__(53799); - static deserialize({ read }) { - const count = read(); - const items = []; - for (let i = 0; i < count; i++) { - items.push(read()); - } - return new LazySet(items); +module.exports = class UnsupportedWebAssemblyFeatureError extends WebpackError { + /** @param {string} message Error message */ + constructor(message) { + super(message); + this.name = "UnsupportedWebAssemblyFeatureError"; + this.hideStack = true; } -} - -makeSerializable(LazySet, "webpack/lib/util/LazySet"); - -module.exports = LazySet; +}; /***/ }), -/***/ 82482: -/***/ (function(__unused_webpack_module, exports) { +/***/ 87394: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -/** - * @template K - * @template V - * @param {Map} map a map - * @param {K} key the key - * @param {function(): V} computer compute value - * @returns {V} value - */ -exports.provide = (map, key, computer) => { - const value = map.get(key); - if (value !== undefined) return value; - const newValue = computer(); - map.set(key, newValue); - return newValue; +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const WebAssemblyUtils = __webpack_require__(18650); + +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ + +// TODO webpack 6 remove the whole folder + +// Get all wasm modules +const getAllWasmModules = (moduleGraph, chunkGraph, chunk) => { + const wasmModules = chunk.getAllAsyncChunks(); + const array = []; + for (const chunk of wasmModules) { + for (const m of chunkGraph.getOrderedChunkModulesIterable( + chunk, + compareModulesByIdentifier + )) { + if (m.type.startsWith("webassembly")) { + array.push(m); + } + } + } + + return array; }; +/** + * generates the import object function for a module + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {Module} module the module + * @param {boolean} mangle mangle imports + * @param {string[]} declarations array where declarations are pushed to + * @param {RuntimeSpec} runtime the runtime + * @returns {string} source code + */ +const generateImportObject = ( + chunkGraph, + module, + mangle, + declarations, + runtime +) => { + const moduleGraph = chunkGraph.moduleGraph; + const waitForInstances = new Map(); + const properties = []; + const usedWasmDependencies = WebAssemblyUtils.getUsedDependencies( + moduleGraph, + module, + mangle + ); + for (const usedDep of usedWasmDependencies) { + const dep = usedDep.dependency; + const importedModule = moduleGraph.getModule(dep); + const exportName = dep.name; + const usedName = + importedModule && + moduleGraph + .getExportsInfo(importedModule) + .getUsedName(exportName, runtime); + const description = dep.description; + const direct = dep.onlyDirectImport; -/***/ }), + const module = usedDep.module; + const name = usedDep.name; -/***/ 50780: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (direct) { + const instanceVar = `m${waitForInstances.size}`; + waitForInstances.set(instanceVar, chunkGraph.getModuleId(importedModule)); + properties.push({ + module, + name, + value: `${instanceVar}[${JSON.stringify(usedName)}]` + }); + } else { + const params = description.signature.params.map( + (param, k) => "p" + k + param.valtype + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const mod = `${RuntimeGlobals.moduleCache}[${JSON.stringify( + chunkGraph.getModuleId(importedModule) + )}]`; + const modExports = `${mod}.exports`; + const cache = `wasmImportedFuncCache${declarations.length}`; + declarations.push(`var ${cache};`); + properties.push({ + module, + name, + value: Template.asString([ + (importedModule.type.startsWith("webassembly") + ? `${mod} ? ${modExports}[${JSON.stringify(usedName)}] : ` + : "") + `function(${params}) {`, + Template.indent([ + `if(${cache} === undefined) ${cache} = ${modExports};`, + `return ${cache}[${JSON.stringify(usedName)}](${params});` + ]), + "}" + ]) + }); + } + } -const binarySearchBounds = __webpack_require__(92229); + let importObject; + if (mangle) { + importObject = [ + "return {", + Template.indent([ + properties.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") + ]), + "};" + ]; + } else { + const propertiesByModule = new Map(); + for (const p of properties) { + let list = propertiesByModule.get(p.module); + if (list === undefined) { + propertiesByModule.set(p.module, (list = [])); + } + list.push(p); + } + importObject = [ + "return {", + Template.indent([ + Array.from(propertiesByModule, ([module, list]) => { + return Template.asString([ + `${JSON.stringify(module)}: {`, + Template.indent([ + list.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") + ]), + "}" + ]); + }).join(",\n") + ]), + "};" + ]; + } -class ParallelismFactorCalculator { - constructor() { - this._rangePoints = []; - this._rangeCallbacks = []; + const moduleIdStringified = JSON.stringify(chunkGraph.getModuleId(module)); + if (waitForInstances.size === 1) { + const moduleId = Array.from(waitForInstances.values())[0]; + const promise = `installedWasmModules[${JSON.stringify(moduleId)}]`; + const variable = Array.from(waitForInstances.keys())[0]; + return Template.asString([ + `${moduleIdStringified}: function() {`, + Template.indent([ + `return promiseResolve().then(function() { return ${promise}; }).then(function(${variable}) {`, + Template.indent(importObject), + "});" + ]), + "}," + ]); + } else if (waitForInstances.size > 0) { + const promises = Array.from( + waitForInstances.values(), + id => `installedWasmModules[${JSON.stringify(id)}]` + ).join(", "); + const variables = Array.from( + waitForInstances.keys(), + (name, i) => `${name} = array[${i}]` + ).join(", "); + return Template.asString([ + `${moduleIdStringified}: function() {`, + Template.indent([ + `return promiseResolve().then(function() { return Promise.all([${promises}]); }).then(function(array) {`, + Template.indent([`var ${variables};`, ...importObject]), + "});" + ]), + "}," + ]); + } else { + return Template.asString([ + `${moduleIdStringified}: function() {`, + Template.indent(importObject), + "}," + ]); } +}; - range(start, end, callback) { - if (start === end) return callback(1); - this._rangePoints.push(start); - this._rangePoints.push(end); - this._rangeCallbacks.push(callback); +class WasmChunkLoadingRuntimeModule extends RuntimeModule { + constructor({ + generateLoadBinaryCode, + supportsStreaming, + mangleImports, + runtimeRequirements + }) { + super("wasm chunk loading", RuntimeModule.STAGE_ATTACH); + this.generateLoadBinaryCode = generateLoadBinaryCode; + this.supportsStreaming = supportsStreaming; + this.mangleImports = mangleImports; + this._runtimeRequirements = runtimeRequirements; } - calculate() { - const segments = Array.from(new Set(this._rangePoints)).sort((a, b) => - a < b ? -1 : 1 + /** + * @returns {string} runtime code + */ + generate() { + const { chunkGraph, compilation, chunk, mangleImports } = this; + const { moduleGraph, outputOptions } = compilation; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withHmr = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers ); - const parallelism = segments.map(() => 0); - const rangeStartIndices = []; - for (let i = 0; i < this._rangePoints.length; i += 2) { - const start = this._rangePoints[i]; - const end = this._rangePoints[i + 1]; - let idx = binarySearchBounds.eq(segments, start); - rangeStartIndices.push(idx); - do { - parallelism[idx]++; - idx++; - } while (segments[idx] < end); - } - for (let i = 0; i < this._rangeCallbacks.length; i++) { - const start = this._rangePoints[i * 2]; - const end = this._rangePoints[i * 2 + 1]; - let idx = rangeStartIndices[i]; - let sum = 0; - let totalDuration = 0; - let current = start; - do { - const p = parallelism[idx]; - idx++; - const duration = segments[idx] - current; - totalDuration += duration; - current = segments[idx]; - sum += p * duration; - } while (current < end); - this._rangeCallbacks[i](sum / totalDuration); - } + const wasmModules = getAllWasmModules(moduleGraph, chunkGraph, chunk); + const declarations = []; + const importObjects = wasmModules.map(module => { + return generateImportObject( + chunkGraph, + module, + this.mangleImports, + declarations, + chunk.runtime + ); + }); + const chunkModuleIdMap = chunkGraph.getChunkModuleIdMap(chunk, m => + m.type.startsWith("webassembly") + ); + const createImportObject = content => + mangleImports + ? `{ ${JSON.stringify(WebAssemblyUtils.MANGLED_MODULE)}: ${content} }` + : content; + const wasmModuleSrcPath = compilation.getPath( + JSON.stringify(outputOptions.webassemblyModuleFilename), + { + hash: `" + ${RuntimeGlobals.getFullHash}() + "`, + hashWithLength: length => + `" + ${RuntimeGlobals.getFullHash}}().slice(0, ${length}) + "`, + module: { + id: '" + wasmModuleId + "', + hash: `" + ${JSON.stringify( + chunkGraph.getChunkModuleRenderedHashMap(chunk, m => + m.type.startsWith("webassembly") + ) + )}[chunkId][wasmModuleId] + "`, + hashWithLength(length) { + return `" + ${JSON.stringify( + chunkGraph.getChunkModuleRenderedHashMap( + chunk, + m => m.type.startsWith("webassembly"), + length + ) + )}[chunkId][wasmModuleId] + "`; + } + }, + runtime: chunk.runtime + } + ); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_wasm` + : undefined; + + return Template.asString([ + "// object to store loaded and loading wasm modules", + `var installedWasmModules = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{};`, + "", + // This function is used to delay reading the installed wasm module promises + // by a microtask. Sorting them doesn't help because there are edge cases where + // sorting is not possible (modules splitted into different chunks). + // So we not even trying and solve this by a microtask delay. + "function promiseResolve() { return Promise.resolve(); }", + "", + Template.asString(declarations), + "var wasmImportObjects = {", + Template.indent(importObjects), + "};", + "", + `var wasmModuleMap = ${JSON.stringify( + chunkModuleIdMap, + undefined, + "\t" + )};`, + "", + "// object with all WebAssembly.instance exports", + `${RuntimeGlobals.wasmInstances} = {};`, + "", + "// Fetch + compile chunk loading for webassembly", + `${fn}.wasm = function(chunkId, promises) {`, + Template.indent([ + "", + `var wasmModules = wasmModuleMap[chunkId] || [];`, + "", + "wasmModules.forEach(function(wasmModuleId, idx) {", + Template.indent([ + "var installedWasmModuleData = installedWasmModules[wasmModuleId];", + "", + '// a Promise means "currently loading" or "already loaded".', + "if(installedWasmModuleData)", + Template.indent(["promises.push(installedWasmModuleData);"]), + "else {", + Template.indent([ + `var importObject = wasmImportObjects[wasmModuleId]();`, + `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, + "var promise;", + this.supportsStreaming + ? Template.asString([ + "if(importObject && typeof importObject.then === 'function' && typeof WebAssembly.compileStreaming === 'function') {", + Template.indent([ + "promise = Promise.all([WebAssembly.compileStreaming(req), importObject]).then(function(items) {", + Template.indent([ + `return WebAssembly.instantiate(items[0], ${createImportObject( + "items[1]" + )});` + ]), + "});" + ]), + "} else if(typeof WebAssembly.instantiateStreaming === 'function') {", + Template.indent([ + `promise = WebAssembly.instantiateStreaming(req, ${createImportObject( + "importObject" + )});` + ]) + ]) + : Template.asString([ + "if(importObject && typeof importObject.then === 'function') {", + Template.indent([ + "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", + "promise = Promise.all([", + Template.indent([ + "bytesPromise.then(function(bytes) { return WebAssembly.compile(bytes); }),", + "importObject" + ]), + "]).then(function(items) {", + Template.indent([ + `return WebAssembly.instantiate(items[0], ${createImportObject( + "items[1]" + )});` + ]), + "});" + ]) + ]), + "} else {", + Template.indent([ + "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", + "promise = bytesPromise.then(function(bytes) {", + Template.indent([ + `return WebAssembly.instantiate(bytes, ${createImportObject( + "importObject" + )});` + ]), + "});" + ]), + "}", + "promises.push(installedWasmModules[wasmModuleId] = promise.then(function(res) {", + Template.indent([ + `return ${RuntimeGlobals.wasmInstances}[wasmModuleId] = (res.instance || res).exports;` + ]), + "}));" + ]), + "}" + ]), + "});" + ]), + "};" + ]); } } -module.exports = ParallelismFactorCalculator; +module.exports = WasmChunkLoadingRuntimeModule; /***/ }), -/***/ 65930: -/***/ (function(module) { +/***/ 19810: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -129465,56 +130390,87 @@ module.exports = ParallelismFactorCalculator; -/** - * @template T - */ -class Queue { - /** - * @param {Iterable=} items The initial elements. - */ - constructor(items) { - /** @private @type {Set} */ - this._set = new Set(items); - /** @private @type {Iterator} */ - this._iterator = this._set[Symbol.iterator](); - } +const formatLocation = __webpack_require__(16734); +const UnsupportedWebAssemblyFeatureError = __webpack_require__(78455); - /** - * Returns the number of elements in this queue. - * @returns {number} The number of elements in this queue. - */ - get length() { - return this._set.size; - } +/** @typedef {import("../Compiler")} Compiler */ +class WasmFinalizeExportsPlugin { /** - * Appends the specified element to this queue. - * @param {T} item The element to add. + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - enqueue(item) { - this._set.add(item); - } + apply(compiler) { + compiler.hooks.compilation.tap("WasmFinalizeExportsPlugin", compilation => { + compilation.hooks.finishModules.tap( + "WasmFinalizeExportsPlugin", + modules => { + for (const module of modules) { + // 1. if a WebAssembly module + if (module.type.startsWith("webassembly") === true) { + const jsIncompatibleExports = + module.buildMeta.jsIncompatibleExports; - /** - * Retrieves and removes the head of this queue. - * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. - */ - dequeue() { - const result = this._iterator.next(); - if (result.done) return undefined; - this._set.delete(result.value); - return result.value; + if (jsIncompatibleExports === undefined) { + continue; + } + + for (const connection of compilation.moduleGraph.getIncomingConnections( + module + )) { + // 2. is active and referenced by a non-WebAssembly module + if ( + connection.isTargetActive(undefined) && + connection.originModule.type.startsWith("webassembly") === + false + ) { + const referencedExports = + compilation.getDependencyReferencedExports( + connection.dependency, + undefined + ); + + for (const info of referencedExports) { + const names = Array.isArray(info) ? info : info.name; + if (names.length === 0) continue; + const name = names[0]; + if (typeof name === "object") continue; + // 3. and uses a func with an incompatible JS signature + if ( + Object.prototype.hasOwnProperty.call( + jsIncompatibleExports, + name + ) + ) { + // 4. error + const error = new UnsupportedWebAssemblyFeatureError( + `Export "${name}" with ${jsIncompatibleExports[name]} can only be used for direct wasm to wasm dependencies\n` + + `It's used from ${connection.originModule.readableIdentifier( + compilation.requestShortener + )} at ${formatLocation(connection.dependency.loc)}.` + ); + error.module = module; + compilation.errors.push(error); + } + } + } + } + } + } + } + ); + }); } } -module.exports = Queue; +module.exports = WasmFinalizeExportsPlugin; /***/ }), -/***/ 93347: -/***/ (function(__unused_webpack_module, exports) { +/***/ 47012: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -129524,691 +130480,620 @@ module.exports = Queue; -/** - * intersect creates Set containing the intersection of elements between all sets - * @template T - * @param {Set[]} sets an array of sets being checked for shared elements - * @returns {Set} returns a new Set containing the intersecting items - */ -const intersect = sets => { - if (sets.length === 0) return new Set(); - if (sets.length === 1) return new Set(sets[0]); - let minSize = Infinity; - let minIndex = -1; - for (let i = 0; i < sets.length; i++) { - const size = sets[i].size; - if (size < minSize) { - minIndex = i; - minSize = size; - } - } - const current = new Set(sets[minIndex]); - for (let i = 0; i < sets.length; i++) { - if (i === minIndex) continue; - const set = sets[i]; - for (const item of current) { - if (!set.has(item)) { - current.delete(item); - } - } - } - return current; -}; +const { RawSource } = __webpack_require__(51255); +const Generator = __webpack_require__(93401); +const WebAssemblyUtils = __webpack_require__(18650); + +const t = __webpack_require__(51826); +const { moduleContextFromModuleAST } = __webpack_require__(51826); +const { editWithAST, addWithAST } = __webpack_require__(87362); +const { decode } = __webpack_require__(73726); + +const WebAssemblyExportImportedDependency = __webpack_require__(52204); + +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./WebAssemblyUtils").UsedWasmDependency} UsedWasmDependency */ /** - * Checks if a set is the subset of another set - * @template T - * @param {Set} bigSet a Set which contains the original elements to compare against - * @param {Set} smallSet the set whose elements might be contained inside of bigSet - * @returns {boolean} returns true if smallSet contains all elements inside of the bigSet + * @typedef {(ArrayBuffer) => ArrayBuffer} ArrayBufferTransform */ -const isSubset = (bigSet, smallSet) => { - if (bigSet.size < smallSet.size) return false; - for (const item of smallSet) { - if (!bigSet.has(item)) return false; - } - return true; -}; /** * @template T - * @param {Set} set a set - * @param {function(T): boolean} fn selector function - * @returns {T | undefined} found item + * @param {Function[]} fns transforms + * @returns {Function} composed transform */ -const find = (set, fn) => { - for (const item of set) { - if (fn(item)) return item; - } +const compose = (...fns) => { + return fns.reduce( + (prevFn, nextFn) => { + return value => nextFn(prevFn(value)); + }, + value => value + ); }; /** - * @template T - * @param {Set} set a set - * @returns {T | undefined} first item + * Removes the start instruction + * + * @param {Object} state unused state + * @returns {ArrayBufferTransform} transform */ -const first = set => { - const entry = set.values().next(); - return entry.done ? undefined : entry.value; +const removeStartFunc = state => bin => { + return editWithAST(state.ast, bin, { + Start(path) { + path.remove(); + } + }); }; /** - * @template T - * @param {Set} a first - * @param {Set} b second - * @returns {Set} combined set, may be identical to a or b + * Get imported globals + * + * @param {Object} ast Module's AST + * @returns {Array} - nodes */ -const combine = (a, b) => { - if (b.size === 0) return a; - if (a.size === 0) return b; - const set = new Set(a); - for (const item of b) set.add(item); - return set; -}; +const getImportedGlobals = ast => { + const importedGlobals = []; -exports.intersect = intersect; -exports.isSubset = isSubset; -exports.find = find; -exports.first = first; -exports.combine = combine; + t.traverse(ast, { + ModuleImport({ node }) { + if (t.isGlobalType(node.descr)) { + importedGlobals.push(node); + } + } + }); + return importedGlobals; +}; -/***/ }), +/** + * Get the count for imported func + * + * @param {Object} ast Module's AST + * @returns {Number} - count + */ +const getCountImportedFunc = ast => { + let count = 0; -/***/ 13098: -/***/ (function(module) { + t.traverse(ast, { + ModuleImport({ node }) { + if (t.isFuncImportDescr(node.descr)) { + count++; + } + } + }); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return count; +}; +/** + * Get next type index + * + * @param {Object} ast Module's AST + * @returns {t.Index} - index + */ +const getNextTypeIndex = ast => { + const typeSectionMetadata = t.getSectionMetadata(ast, "type"); + if (typeSectionMetadata === undefined) { + return t.indexLiteral(0); + } -const NONE = Symbol("not sorted"); + return t.indexLiteral(typeSectionMetadata.vectorOfSize.value); +}; /** - * A subset of Set that offers sorting functionality - * @template T item type in set - * @extends {Set} + * Get next func index + * + * The Func section metadata provide informations for implemented funcs + * in order to have the correct index we shift the index by number of external + * functions. + * + * @param {Object} ast Module's AST + * @param {Number} countImportedFunc number of imported funcs + * @returns {t.Index} - index */ -class SortableSet extends Set { - /** - * Create a new sortable set - * @param {Iterable=} initialIterable The initial iterable value - * @typedef {function(T, T): number} SortFunction - * @param {SortFunction=} defaultSort Default sorting function - */ - constructor(initialIterable, defaultSort) { - super(initialIterable); - /** @private @type {undefined | function(T, T): number}} */ - this._sortFn = defaultSort; - /** @private @type {typeof NONE | undefined | function(T, T): number}} */ - this._lastActiveSortFn = NONE; - /** @private @type {Map | undefined} */ - this._cache = undefined; - /** @private @type {Map | undefined} */ - this._cacheOrderIndependent = undefined; - } - - /** - * @param {T} value value to add to set - * @returns {this} returns itself - */ - add(value) { - this._lastActiveSortFn = NONE; - this._invalidateCache(); - this._invalidateOrderedCache(); - super.add(value); - return this; - } +const getNextFuncIndex = (ast, countImportedFunc) => { + const funcSectionMetadata = t.getSectionMetadata(ast, "func"); - /** - * @param {T} value value to delete - * @returns {boolean} true if value existed in set, false otherwise - */ - delete(value) { - this._invalidateCache(); - this._invalidateOrderedCache(); - return super.delete(value); + if (funcSectionMetadata === undefined) { + return t.indexLiteral(0 + countImportedFunc); } - /** - * @returns {void} - */ - clear() { - this._invalidateCache(); - this._invalidateOrderedCache(); - return super.clear(); - } + const vectorOfSize = funcSectionMetadata.vectorOfSize.value; - /** - * Sort with a comparer function - * @param {SortFunction} sortFn Sorting comparer function - * @returns {void} - */ - sortWith(sortFn) { - if (this.size <= 1 || sortFn === this._lastActiveSortFn) { - // already sorted - nothing to do - return; - } + return t.indexLiteral(vectorOfSize + countImportedFunc); +}; - const sortedArray = Array.from(this).sort(sortFn); - super.clear(); - for (let i = 0; i < sortedArray.length; i += 1) { - super.add(sortedArray[i]); - } - this._lastActiveSortFn = sortFn; - this._invalidateCache(); +/** + * Creates an init instruction for a global type + * @param {t.GlobalType} globalType the global type + * @returns {t.Instruction} init expression + */ +const createDefaultInitForGlobal = globalType => { + if (globalType.valtype[0] === "i") { + // create NumberLiteral global initializer + return t.objectInstruction("const", globalType.valtype, [ + t.numberLiteralFromRaw(66) + ]); + } else if (globalType.valtype[0] === "f") { + // create FloatLiteral global initializer + return t.objectInstruction("const", globalType.valtype, [ + t.floatLiteral(66, false, false, "66") + ]); + } else { + throw new Error("unknown type: " + globalType.valtype); } +}; - sort() { - this.sortWith(this._sortFn); - return this; - } +/** + * Rewrite the import globals: + * - removes the ModuleImport instruction + * - injects at the same offset a mutable global of the same type + * + * Since the imported globals are before the other global declarations, our + * indices will be preserved. + * + * Note that globals will become mutable. + * + * @param {Object} state unused state + * @returns {ArrayBufferTransform} transform + */ +const rewriteImportedGlobals = state => bin => { + const additionalInitCode = state.additionalInitCode; + const newGlobals = []; - /** - * Get data from cache - * @template R - * @param {function(SortableSet): R} fn function to calculate value - * @returns {R} returns result of fn(this), cached until set changes - */ - getFromCache(fn) { - if (this._cache === undefined) { - this._cache = new Map(); - } else { - const result = this._cache.get(fn); - const data = /** @type {R} */ (result); - if (data !== undefined) { - return data; - } - } - const newData = fn(this); - this._cache.set(fn, newData); - return newData; - } + bin = editWithAST(state.ast, bin, { + ModuleImport(path) { + if (t.isGlobalType(path.node.descr)) { + const globalType = path.node.descr; - /** - * Get data from cache (ignoring sorting) - * @template R - * @param {function(SortableSet): R} fn function to calculate value - * @returns {R} returns result of fn(this), cached until set changes - */ - getFromUnorderedCache(fn) { - if (this._cacheOrderIndependent === undefined) { - this._cacheOrderIndependent = new Map(); - } else { - const result = this._cacheOrderIndependent.get(fn); - const data = /** @type {R} */ (result); - if (data !== undefined) { - return data; - } - } - const newData = fn(this); - this._cacheOrderIndependent.set(fn, newData); - return newData; - } + globalType.mutability = "var"; - /** - * @private - * @returns {void} - */ - _invalidateCache() { - if (this._cache !== undefined) { - this._cache.clear(); - } - } + const init = [ + createDefaultInitForGlobal(globalType), + t.instruction("end") + ]; - /** - * @private - * @returns {void} - */ - _invalidateOrderedCache() { - if (this._cacheOrderIndependent !== undefined) { - this._cacheOrderIndependent.clear(); - } - } + newGlobals.push(t.global(globalType, init)); - /** - * @returns {T[]} the raw array - */ - toJSON() { - return Array.from(this); - } -} + path.remove(); + } + }, -module.exports = SortableSet; + // in order to preserve non-imported global's order we need to re-inject + // those as well + Global(path) { + const { node } = path; + const [init] = node.init; + if (init.id === "get_global") { + node.globalType.mutability = "var"; -/***/ }), + const initialGlobalIdx = init.args[0]; -/***/ 64985: -/***/ (function(module) { + node.init = [ + createDefaultInitForGlobal(node.globalType), + t.instruction("end") + ]; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + additionalInitCode.push( + /** + * get_global in global initializer only works for imported globals. + * They have the same indices as the init params, so use the + * same index. + */ + t.instruction("get_local", [initialGlobalIdx]), + t.instruction("set_global", [t.indexLiteral(newGlobals.length)]) + ); + } + + newGlobals.push(node); + path.remove(); + } + }); + // Add global declaration instructions + return addWithAST(state.ast, bin, newGlobals); +}; /** - * @template K - * @template V + * Rewrite the export names + * @param {Object} state state + * @param {Object} state.ast Module's ast + * @param {Module} state.module Module + * @param {ModuleGraph} state.moduleGraph module graph + * @param {Set} state.externalExports Module + * @param {RuntimeSpec} state.runtime runtime + * @returns {ArrayBufferTransform} transform */ -class StackedCacheMap { - constructor() { - /** @type {Map} */ - this.map = new Map(); - /** @type {ReadonlyMap[]} */ - this.stack = []; - } +const rewriteExportNames = + ({ ast, moduleGraph, module, externalExports, runtime }) => + bin => { + return editWithAST(ast, bin, { + ModuleExport(path) { + const isExternal = externalExports.has(path.node.name); + if (isExternal) { + path.remove(); + return; + } + const usedName = moduleGraph + .getExportsInfo(module) + .getUsedName(path.node.name, runtime); + if (!usedName) { + path.remove(); + return; + } + path.node.name = usedName; + } + }); + }; - /** - * @param {ReadonlyMap} map map to add - * @param {boolean} immutable if 'map' is immutable and StackedCacheMap can keep referencing it - */ - addAll(map, immutable) { - if (immutable) { - this.stack.push(map); +/** + * Mangle import names and modules + * @param {Object} state state + * @param {Object} state.ast Module's ast + * @param {Map} state.usedDependencyMap mappings to mangle names + * @returns {ArrayBufferTransform} transform + */ +const rewriteImports = + ({ ast, usedDependencyMap }) => + bin => { + return editWithAST(ast, bin, { + ModuleImport(path) { + const result = usedDependencyMap.get( + path.node.module + ":" + path.node.name + ); - // largest map should go first - for (let i = this.stack.length - 1; i > 0; i--) { - const beforeLast = this.stack[i - 1]; - if (beforeLast.size >= map.size) break; - this.stack[i] = beforeLast; - this.stack[i - 1] = map; - } - } else { - for (const [key, value] of map) { - this.map.set(key, value); + if (result !== undefined) { + path.node.module = result.module; + path.node.name = result.name; + } } - } - } - - /** - * @param {K} item the key of the element to add - * @param {V} value the value of the element to add - * @returns {void} - */ - set(item, value) { - this.map.set(item, value); - } + }); + }; - /** - * @param {K} item the item to delete - * @returns {void} - */ - delete(item) { - throw new Error("Items can't be deleted from a StackedCacheMap"); - } +/** + * Add an init function. + * + * The init function fills the globals given input arguments. + * + * @param {Object} state transformation state + * @param {Object} state.ast Module's ast + * @param {t.Identifier} state.initFuncId identifier of the init function + * @param {t.Index} state.startAtFuncOffset index of the start function + * @param {t.ModuleImport[]} state.importedGlobals list of imported globals + * @param {t.Instruction[]} state.additionalInitCode list of addition instructions for the init function + * @param {t.Index} state.nextFuncIndex index of the next function + * @param {t.Index} state.nextTypeIndex index of the next type + * @returns {ArrayBufferTransform} transform + */ +const addInitFunction = + ({ + ast, + initFuncId, + startAtFuncOffset, + importedGlobals, + additionalInitCode, + nextFuncIndex, + nextTypeIndex + }) => + bin => { + const funcParams = importedGlobals.map(importedGlobal => { + // used for debugging + const id = t.identifier( + `${importedGlobal.module}.${importedGlobal.name}` + ); - /** - * @param {K} item the item to test - * @returns {boolean} true if the item exists in this set - */ - has(item) { - throw new Error( - "Checking StackedCacheMap.has before reading is inefficient, use StackedCacheMap.get and check for undefined" - ); - } + return t.funcParam(importedGlobal.descr.valtype, id); + }); - /** - * @param {K} item the key of the element to return - * @returns {V} the value of the element - */ - get(item) { - for (const map of this.stack) { - const value = map.get(item); - if (value !== undefined) return value; - } - return this.map.get(item); - } + const funcBody = []; + importedGlobals.forEach((importedGlobal, index) => { + const args = [t.indexLiteral(index)]; + const body = [ + t.instruction("get_local", args), + t.instruction("set_global", args) + ]; - clear() { - this.stack.length = 0; - this.map.clear(); - } + funcBody.push(...body); + }); - get size() { - let size = this.map.size; - for (const map of this.stack) { - size += map.size; + if (typeof startAtFuncOffset === "number") { + funcBody.push( + t.callInstruction(t.numberLiteralFromRaw(startAtFuncOffset)) + ); } - return size; - } - [Symbol.iterator]() { - const iterators = this.stack.map(map => map[Symbol.iterator]()); - let current = this.map[Symbol.iterator](); - return { - next() { - let result = current.next(); - while (result.done && iterators.length > 0) { - current = iterators.pop(); - result = current.next(); - } - return result; - } - }; - } -} - -module.exports = StackedCacheMap; - - -/***/ }), - -/***/ 58845: -/***/ (function(module) { + for (const instr of additionalInitCode) { + funcBody.push(instr); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + funcBody.push(t.instruction("end")); + const funcResults = []; + // Code section + const funcSignature = t.signature(funcParams, funcResults); + const func = t.func(initFuncId, funcSignature, funcBody); -const TOMBSTONE = Symbol("tombstone"); -const UNDEFINED_MARKER = Symbol("undefined"); + // Type section + const functype = t.typeInstruction(undefined, funcSignature); -/** - * @template T - * @typedef {T | undefined} Cell - */ + // Func section + const funcindex = t.indexInFuncSection(nextTypeIndex); -/** - * @template T - * @typedef {T | typeof TOMBSTONE | typeof UNDEFINED_MARKER} InternalCell - */ + // Export section + const moduleExport = t.moduleExport( + initFuncId.value, + t.moduleExportDescr("Func", nextFuncIndex) + ); -/** - * @template K - * @template V - * @param {[K, InternalCell]} pair the internal cell - * @returns {[K, Cell]} its “safe” representation - */ -const extractPair = pair => { - const key = pair[0]; - const val = pair[1]; - if (val === UNDEFINED_MARKER || val === TOMBSTONE) { - return [key, undefined]; - } else { - return /** @type {[K, Cell]} */ (pair); - } -}; + return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]); + }; /** - * @template K - * @template V + * Extract mangle mappings from module + * @param {ModuleGraph} moduleGraph module graph + * @param {Module} module current module + * @param {boolean} mangle mangle imports + * @returns {Map} mappings to mangled names */ -class StackedMap { - /** - * @param {Map>[]=} parentStack an optional parent - */ - constructor(parentStack) { - /** @type {Map>} */ - this.map = new Map(); - /** @type {Map>[]} */ - this.stack = parentStack === undefined ? [] : parentStack.slice(); - this.stack.push(this.map); +const getUsedDependencyMap = (moduleGraph, module, mangle) => { + /** @type {Map} */ + const map = new Map(); + for (const usedDep of WebAssemblyUtils.getUsedDependencies( + moduleGraph, + module, + mangle + )) { + const dep = usedDep.dependency; + const request = dep.request; + const exportName = dep.name; + map.set(request + ":" + exportName, usedDep); } + return map; +}; - /** - * @param {K} item the key of the element to add - * @param {V} value the value of the element to add - * @returns {void} - */ - set(item, value) { - this.map.set(item, value === undefined ? UNDEFINED_MARKER : value); +const TYPES = new Set(["webassembly"]); + +class WebAssemblyGenerator extends Generator { + constructor(options) { + super(); + this.options = options; } /** - * @param {K} item the item to delete - * @returns {void} + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - delete(item) { - if (this.stack.length > 1) { - this.map.set(item, TOMBSTONE); - } else { - this.map.delete(item); - } + getTypes(module) { + return TYPES; } /** - * @param {K} item the item to test - * @returns {boolean} true if the item exists in this set + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - has(item) { - const topValue = this.map.get(item); - if (topValue !== undefined) { - return topValue !== TOMBSTONE; - } - if (this.stack.length > 1) { - for (let i = this.stack.length - 2; i >= 0; i--) { - const value = this.stack[i].get(item); - if (value !== undefined) { - this.map.set(item, value); - return value !== TOMBSTONE; - } - } - this.map.set(item, TOMBSTONE); + getSize(module, type) { + const originalSource = module.originalSource(); + if (!originalSource) { + return 0; } - return false; + return originalSource.size(); } /** - * @param {K} item the key of the element to return - * @returns {Cell} the value of the element + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code */ - get(item) { - const topValue = this.map.get(item); - if (topValue !== undefined) { - return topValue === TOMBSTONE || topValue === UNDEFINED_MARKER - ? undefined - : topValue; - } - if (this.stack.length > 1) { - for (let i = this.stack.length - 2; i >= 0; i--) { - const value = this.stack[i].get(item); - if (value !== undefined) { - this.map.set(item, value); - return value === TOMBSTONE || value === UNDEFINED_MARKER - ? undefined - : value; - } - } - this.map.set(item, TOMBSTONE); - } - return undefined; - } - - _compress() { - if (this.stack.length === 1) return; - this.map = new Map(); - for (const data of this.stack) { - for (const pair of data) { - if (pair[1] === TOMBSTONE) { - this.map.delete(pair[0]); - } else { - this.map.set(pair[0], pair[1]); - } - } - } - this.stack = [this.map]; - } - - asArray() { - this._compress(); - return Array.from(this.map.keys()); - } - - asSet() { - this._compress(); - return new Set(this.map.keys()); - } - - asPairArray() { - this._compress(); - return Array.from(this.map.entries(), extractPair); - } + generate(module, { moduleGraph, runtime }) { + const bin = module.originalSource().source(); - asMap() { - return new Map(this.asPairArray()); - } + const initFuncId = t.identifier(""); - get size() { - this._compress(); - return this.map.size; - } + // parse it + const ast = decode(bin, { + ignoreDataSection: true, + ignoreCodeSection: true, + ignoreCustomNameSection: true + }); - createChild() { - return new StackedMap(this.stack); - } -} + const moduleContext = moduleContextFromModuleAST(ast.body[0]); -module.exports = StackedMap; + const importedGlobals = getImportedGlobals(ast); + const countImportedFunc = getCountImportedFunc(ast); + const startAtFuncOffset = moduleContext.getStart(); + const nextFuncIndex = getNextFuncIndex(ast, countImportedFunc); + const nextTypeIndex = getNextTypeIndex(ast); + const usedDependencyMap = getUsedDependencyMap( + moduleGraph, + module, + this.options.mangleImports + ); + const externalExports = new Set( + module.dependencies + .filter(d => d instanceof WebAssemblyExportImportedDependency) + .map(d => { + const wasmDep = /** @type {WebAssemblyExportImportedDependency} */ ( + d + ); + return wasmDep.exportName; + }) + ); -/***/ }), + /** @type {t.Instruction[]} */ + const additionalInitCode = []; -/***/ 40293: -/***/ (function(module) { + const transform = compose( + rewriteExportNames({ + ast, + moduleGraph, + module, + externalExports, + runtime + }), -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + removeStartFunc({ ast }), + rewriteImportedGlobals({ ast, additionalInitCode }), + rewriteImports({ + ast, + usedDependencyMap + }), -class StringXor { - constructor() { - this._value = undefined; - } + addInitFunction({ + ast, + initFuncId, + importedGlobals, + additionalInitCode, + startAtFuncOffset, + nextFuncIndex, + nextTypeIndex + }) + ); - /** - * @param {string} str string - * @returns {void} - */ - add(str) { - const len = str.length; - const value = this._value; - if (value === undefined) { - const newValue = (this._value = Buffer.allocUnsafe(len)); - for (let i = 0; i < len; i++) { - newValue[i] = str.charCodeAt(i); - } - return; - } - const valueLen = value.length; - if (valueLen < len) { - const newValue = (this._value = Buffer.allocUnsafe(len)); - let i; - for (i = 0; i < valueLen; i++) { - newValue[i] = value[i] ^ str.charCodeAt(i); - } - for (; i < len; i++) { - newValue[i] = str.charCodeAt(i); - } - } else { - for (let i = 0; i < len; i++) { - value[i] = value[i] ^ str.charCodeAt(i); - } - } - } + const newBin = transform(bin); - toString() { - const value = this._value; - return value === undefined ? "" : value.toString("latin1"); - } + const newBuf = Buffer.from(newBin); - updateHash(hash) { - const value = this._value; - if (value !== undefined) hash.update(value); + return new RawSource(newBuf); } } -module.exports = StringXor; +module.exports = WebAssemblyGenerator; /***/ }), -/***/ 38415: +/***/ 47342: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -const TupleSet = __webpack_require__(76455); +const WebpackError = __webpack_require__(53799); + +/** @typedef {import("../ChunkGraph")} ChunkGraph */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleGraph")} ModuleGraph */ +/** @typedef {import("../RequestShortener")} RequestShortener */ /** - * @template {any[]} T + * @param {Module} module module to get chains from + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {RequestShortener} requestShortener to make readable identifiers + * @returns {string[]} all chains to the module */ -class TupleQueue { - /** - * @param {Iterable=} items The initial elements. - */ - constructor(items) { - /** @private @type {TupleSet} */ - this._set = new TupleSet(items); - /** @private @type {Iterator} */ - this._iterator = this._set[Symbol.iterator](); - } +const getInitialModuleChains = ( + module, + moduleGraph, + chunkGraph, + requestShortener +) => { + const queue = [ + { head: module, message: module.readableIdentifier(requestShortener) } + ]; + /** @type {Set} */ + const results = new Set(); + /** @type {Set} */ + const incompleteResults = new Set(); + /** @type {Set} */ + const visitedModules = new Set(); - /** - * Returns the number of elements in this queue. - * @returns {number} The number of elements in this queue. - */ - get length() { - return this._set.size; + for (const chain of queue) { + const { head, message } = chain; + let final = true; + /** @type {Set} */ + const alreadyReferencedModules = new Set(); + for (const connection of moduleGraph.getIncomingConnections(head)) { + const newHead = connection.originModule; + if (newHead) { + if (!chunkGraph.getModuleChunks(newHead).some(c => c.canBeInitial())) + continue; + final = false; + if (alreadyReferencedModules.has(newHead)) continue; + alreadyReferencedModules.add(newHead); + const moduleName = newHead.readableIdentifier(requestShortener); + const detail = connection.explanation + ? ` (${connection.explanation})` + : ""; + const newMessage = `${moduleName}${detail} --> ${message}`; + if (visitedModules.has(newHead)) { + incompleteResults.add(`... --> ${newMessage}`); + continue; + } + visitedModules.add(newHead); + queue.push({ + head: newHead, + message: newMessage + }); + } else { + final = false; + const newMessage = connection.explanation + ? `(${connection.explanation}) --> ${message}` + : message; + results.add(newMessage); + } + } + if (final) { + results.add(message); + } } - - /** - * Appends the specified element to this queue. - * @param {T} item The element to add. - * @returns {void} - */ - enqueue(...item) { - this._set.add(...item); + for (const result of incompleteResults) { + results.add(result); } + return Array.from(results); +}; +module.exports = class WebAssemblyInInitialChunkError extends WebpackError { /** - * Retrieves and removes the head of this queue. - * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + * @param {Module} module WASM module + * @param {ModuleGraph} moduleGraph the module graph + * @param {ChunkGraph} chunkGraph the chunk graph + * @param {RequestShortener} requestShortener request shortener */ - dequeue() { - const result = this._iterator.next(); - if (result.done) { - if (this._set.size > 0) { - this._iterator = this._set[Symbol.iterator](); - const value = this._iterator.next().value; - this._set.delete(...value); - return value; - } - return undefined; - } - this._set.delete(...result.value); - return result.value; - } -} + constructor(module, moduleGraph, chunkGraph, requestShortener) { + const moduleChains = getInitialModuleChains( + module, + moduleGraph, + chunkGraph, + requestShortener + ); + const message = `WebAssembly module is included in initial chunk. +This is not allowed, because WebAssembly download and compilation must happen asynchronous. +Add an async split point (i. e. import()) somewhere between your entrypoint and the WebAssembly module: +${moduleChains.map(s => `* ${s}`).join("\n")}`; -module.exports = TupleQueue; + super(message); + this.name = "WebAssemblyInInitialChunkError"; + this.hideStack = true; + this.module = module; + } +}; /***/ }), -/***/ 76455: -/***/ (function(module) { +/***/ 46545: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -130218,250 +131103,221 @@ module.exports = TupleQueue; -/** - * @template {any[]} T - */ -class TupleSet { - constructor(init) { - this._map = new Map(); - this.size = 0; - if (init) { - for (const tuple of init) { - this.add(...tuple); - } - } - } - - /** - * @param {T} args tuple - * @returns {void} - */ - add(...args) { - let map = this._map; - for (let i = 0; i < args.length - 2; i++) { - const arg = args[i]; - const innerMap = map.get(arg); - if (innerMap === undefined) { - map.set(arg, (map = new Map())); - } else { - map = innerMap; - } - } +const { RawSource } = __webpack_require__(51255); +const { UsageState } = __webpack_require__(63686); +const Generator = __webpack_require__(93401); +const InitFragment = __webpack_require__(55870); +const RuntimeGlobals = __webpack_require__(16475); +const Template = __webpack_require__(1626); +const ModuleDependency = __webpack_require__(80321); +const WebAssemblyExportImportedDependency = __webpack_require__(52204); +const WebAssemblyImportDependency = __webpack_require__(5239); - const beforeLast = args[args.length - 2]; - let set = map.get(beforeLast); - if (set === undefined) { - map.set(beforeLast, (set = new Set())); - } +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ +/** @typedef {import("../Generator").GenerateContext} GenerateContext */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ - const last = args[args.length - 1]; - this.size -= set.size; - set.add(last); - this.size += set.size; - } +const TYPES = new Set(["webassembly"]); +class WebAssemblyJavascriptGenerator extends Generator { /** - * @param {T} args tuple - * @returns {boolean} true, if the tuple is in the Set + * @param {NormalModule} module fresh module + * @returns {Set} available types (do not mutate) */ - has(...args) { - let map = this._map; - for (let i = 0; i < args.length - 2; i++) { - const arg = args[i]; - map = map.get(arg); - if (map === undefined) { - return false; - } - } - - const beforeLast = args[args.length - 2]; - let set = map.get(beforeLast); - if (set === undefined) { - return false; - } - - const last = args[args.length - 1]; - return set.has(last); + getTypes(module) { + return TYPES; } /** - * @param {T} args tuple - * @returns {void} + * @param {NormalModule} module the module + * @param {string=} type source type + * @returns {number} estimate size of the module */ - delete(...args) { - let map = this._map; - for (let i = 0; i < args.length - 2; i++) { - const arg = args[i]; - map = map.get(arg); - if (map === undefined) { - return; - } - } - - const beforeLast = args[args.length - 2]; - let set = map.get(beforeLast); - if (set === undefined) { - return; - } - - const last = args[args.length - 1]; - this.size -= set.size; - set.delete(last); - this.size += set.size; + getSize(module, type) { + return 95 + module.dependencies.length * 5; } /** - * @returns {Iterator} iterator + * @param {NormalModule} module module for which the code should be generated + * @param {GenerateContext} generateContext context for generate + * @returns {Source} generated code */ - [Symbol.iterator]() { - const iteratorStack = []; - const tuple = []; - let currentSetIterator = undefined; + generate(module, generateContext) { + const { + runtimeTemplate, + moduleGraph, + chunkGraph, + runtimeRequirements, + runtime + } = generateContext; + /** @type {InitFragment[]} */ + const initFragments = []; - const next = it => { - const result = it.next(); - if (result.done) { - if (iteratorStack.length === 0) return false; - tuple.pop(); - return next(iteratorStack.pop()); - } - const [key, value] = result.value; - iteratorStack.push(it); - tuple.push(key); - if (value instanceof Set) { - currentSetIterator = value[Symbol.iterator](); - return true; - } else { - return next(value[Symbol.iterator]()); - } - }; + const exportsInfo = moduleGraph.getExportsInfo(module); - next(this._map[Symbol.iterator]()); + let needExportsCopy = false; + const importedModules = new Map(); + const initParams = []; + let index = 0; + for (const dep of module.dependencies) { + const moduleDep = + dep && dep instanceof ModuleDependency ? dep : undefined; + if (moduleGraph.getModule(dep)) { + let importData = importedModules.get(moduleGraph.getModule(dep)); + if (importData === undefined) { + importedModules.set( + moduleGraph.getModule(dep), + (importData = { + importVar: `m${index}`, + index, + request: (moduleDep && moduleDep.userRequest) || undefined, + names: new Set(), + reexports: [] + }) + ); + index++; + } + if (dep instanceof WebAssemblyImportDependency) { + importData.names.add(dep.name); + if (dep.description.type === "GlobalType") { + const exportName = dep.name; + const importedModule = moduleGraph.getModule(dep); - return { - next() { - while (currentSetIterator) { - const result = currentSetIterator.next(); - if (result.done) { - tuple.pop(); - if (!next(iteratorStack.pop())) { - currentSetIterator = undefined; + if (importedModule) { + const usedName = moduleGraph + .getExportsInfo(importedModule) + .getUsedName(exportName, runtime); + if (usedName) { + initParams.push( + runtimeTemplate.exportFromImport({ + moduleGraph, + module: importedModule, + request: dep.request, + importVar: importData.importVar, + originModule: module, + exportName: dep.name, + asiSafe: true, + isCall: false, + callContext: null, + defaultInterop: true, + initFragments, + runtime, + runtimeRequirements + }) + ); + } } - } else { - return { - done: false, - value: /** @type {T} */ (tuple.concat(result.value)) - }; } } - return { done: true, value: undefined }; + if (dep instanceof WebAssemblyExportImportedDependency) { + importData.names.add(dep.name); + const usedName = moduleGraph + .getExportsInfo(module) + .getUsedName(dep.exportName, runtime); + if (usedName) { + runtimeRequirements.add(RuntimeGlobals.exports); + const exportProp = `${module.exportsArgument}[${JSON.stringify( + usedName + )}]`; + const defineStatement = Template.asString([ + `${exportProp} = ${runtimeTemplate.exportFromImport({ + moduleGraph, + module: moduleGraph.getModule(dep), + request: dep.request, + importVar: importData.importVar, + originModule: module, + exportName: dep.name, + asiSafe: true, + isCall: false, + callContext: null, + defaultInterop: true, + initFragments, + runtime, + runtimeRequirements + })};`, + `if(WebAssembly.Global) ${exportProp} = ` + + `new WebAssembly.Global({ value: ${JSON.stringify( + dep.valueType + )} }, ${exportProp});` + ]); + importData.reexports.push(defineStatement); + needExportsCopy = true; + } + } } - }; - } -} - -module.exports = TupleSet; - - -/***/ }), - -/***/ 54500: -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop -*/ - - - -/** @typedef {import("./fs").InputFileSystem} InputFileSystem */ -/** @typedef {(error: Error|null, result?: Buffer) => void} ErrorFirstCallback */ - -const backSlashCharCode = "\\".charCodeAt(0); -const slashCharCode = "/".charCodeAt(0); -const aLowerCaseCharCode = "a".charCodeAt(0); -const zLowerCaseCharCode = "z".charCodeAt(0); -const aUpperCaseCharCode = "A".charCodeAt(0); -const zUpperCaseCharCode = "Z".charCodeAt(0); -const _0CharCode = "0".charCodeAt(0); -const _9CharCode = "9".charCodeAt(0); -const plusCharCode = "+".charCodeAt(0); -const hyphenCharCode = "-".charCodeAt(0); -const colonCharCode = ":".charCodeAt(0); -const hashCharCode = "#".charCodeAt(0); -const queryCharCode = "?".charCodeAt(0); -/** - * Get scheme if specifier is an absolute URL specifier - * e.g. Absolute specifiers like 'file:///user/webpack/index.js' - * https://tools.ietf.org/html/rfc3986#section-3.1 - * @param {string} specifier specifier - * @returns {string|undefined} scheme if absolute URL specifier provided - */ -function getScheme(specifier) { - const start = specifier.charCodeAt(0); + } + const importsCode = Template.asString( + Array.from( + importedModules, + ([module, { importVar, request, reexports }]) => { + const importStatement = runtimeTemplate.importStatement({ + module, + chunkGraph, + request, + importVar, + originModule: module, + runtimeRequirements + }); + return importStatement[0] + importStatement[1] + reexports.join("\n"); + } + ) + ); - // First char maybe only a letter - if ( - (start < aLowerCaseCharCode || start > zLowerCaseCharCode) && - (start < aUpperCaseCharCode || start > zUpperCaseCharCode) - ) { - return undefined; - } + const copyAllExports = + exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused && + !needExportsCopy; - let i = 1; - let ch = specifier.charCodeAt(i); + // need these globals + runtimeRequirements.add(RuntimeGlobals.module); + runtimeRequirements.add(RuntimeGlobals.moduleId); + runtimeRequirements.add(RuntimeGlobals.wasmInstances); + if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { + runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); + runtimeRequirements.add(RuntimeGlobals.exports); + } + if (!copyAllExports) { + runtimeRequirements.add(RuntimeGlobals.exports); + } - while ( - (ch >= aLowerCaseCharCode && ch <= zLowerCaseCharCode) || - (ch >= aUpperCaseCharCode && ch <= zUpperCaseCharCode) || - (ch >= _0CharCode && ch <= _9CharCode) || - ch === plusCharCode || - ch === hyphenCharCode - ) { - if (++i === specifier.length) return undefined; - ch = specifier.charCodeAt(i); - } + // create source + const source = new RawSource( + [ + '"use strict";', + "// Instantiate WebAssembly module", + `var wasmExports = ${RuntimeGlobals.wasmInstances}[${module.moduleArgument}.id];`, - // Scheme must end with colon - if (ch !== colonCharCode) return undefined; + exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused + ? `${RuntimeGlobals.makeNamespaceObject}(${module.exportsArgument});` + : "", - // Check for Windows absolute path - // https://url.spec.whatwg.org/#url-miscellaneous - if (i === 1) { - const nextChar = i + 1 < specifier.length ? specifier.charCodeAt(i + 1) : 0; - if ( - nextChar === 0 || - nextChar === backSlashCharCode || - nextChar === slashCharCode || - nextChar === hashCharCode || - nextChar === queryCharCode - ) { - return undefined; - } + // this must be before import for circular dependencies + "// export exports from WebAssembly module", + copyAllExports + ? `${module.moduleArgument}.exports = wasmExports;` + : "for(var name in wasmExports) " + + `if(name) ` + + `${module.exportsArgument}[name] = wasmExports[name];`, + "// exec imports from WebAssembly module (for esm order)", + importsCode, + "", + "// exec wasm module", + `wasmExports[""](${initParams.join(", ")})` + ].join("\n") + ); + return InitFragment.addToSource(source, initFragments, generateContext); } - - return specifier.slice(0, i).toLowerCase(); -} - -/** - * @param {string} specifier specifier - * @returns {string|null} protocol if absolute URL specifier provided - */ -function getProtocol(specifier) { - const scheme = getScheme(specifier); - return scheme === undefined ? undefined : scheme + ":"; } -exports.getScheme = getScheme; -exports.getProtocol = getProtocol; +module.exports = WebAssemblyJavascriptGenerator; /***/ }), -/***/ 28745: -/***/ (function(module) { +/***/ 53639: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -130471,270 +131327,147 @@ exports.getProtocol = getProtocol; -const isWeakKey = thing => typeof thing === "object" && thing !== null; - -/** - * @template {any[]} T - * @template V - */ -class WeakTupleMap { - constructor() { - /** @private */ - this.f = 0; - /** @private @type {any} */ - this.v = undefined; - /** @private @type {Map> | undefined} */ - this.m = undefined; - /** @private @type {WeakMap> | undefined} */ - this.w = undefined; - } - - /** - * @param {[...T, V]} args tuple - * @returns {void} - */ - set(...args) { - /** @type {WeakTupleMap} */ - let node = this; - for (let i = 0; i < args.length - 1; i++) { - node = node._get(args[i]); - } - node._setValue(args[args.length - 1]); - } - - /** - * @param {T} args tuple - * @returns {boolean} true, if the tuple is in the Set - */ - has(...args) { - /** @type {WeakTupleMap} */ - let node = this; - for (let i = 0; i < args.length; i++) { - node = node._peek(args[i]); - if (node === undefined) return false; - } - return node._hasValue(); - } +const Generator = __webpack_require__(93401); +const WebAssemblyExportImportedDependency = __webpack_require__(52204); +const WebAssemblyImportDependency = __webpack_require__(5239); +const { compareModulesByIdentifier } = __webpack_require__(29579); +const memoize = __webpack_require__(78676); +const WebAssemblyInInitialChunkError = __webpack_require__(47342); - /** - * @param {T} args tuple - * @returns {V} the value - */ - get(...args) { - /** @type {WeakTupleMap} */ - let node = this; - for (let i = 0; i < args.length; i++) { - node = node._peek(args[i]); - if (node === undefined) return undefined; - } - return node._getValue(); - } +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ - /** - * @param {[...T, function(): V]} args tuple - * @returns {V} the value - */ - provide(...args) { - /** @type {WeakTupleMap} */ - let node = this; - for (let i = 0; i < args.length - 1; i++) { - node = node._get(args[i]); - } - if (node._hasValue()) return node._getValue(); - const fn = args[args.length - 1]; - const newValue = fn(...args.slice(0, -1)); - node._setValue(newValue); - return newValue; - } +const getWebAssemblyGenerator = memoize(() => + __webpack_require__(47012) +); +const getWebAssemblyJavascriptGenerator = memoize(() => + __webpack_require__(46545) +); +const getWebAssemblyParser = memoize(() => __webpack_require__(57059)); - /** - * @param {T} args tuple - * @returns {void} - */ - delete(...args) { - /** @type {WeakTupleMap} */ - let node = this; - for (let i = 0; i < args.length; i++) { - node = node._peek(args[i]); - if (node === undefined) return; - } - node._deleteValue(); +class WebAssemblyModulesPlugin { + constructor(options) { + this.options = options; } /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance * @returns {void} */ - clear() { - this.f = 0; - this.v = undefined; - this.w = undefined; - this.m = undefined; - } - - _getValue() { - return this.v; - } - - _hasValue() { - return (this.f & 1) === 1; - } - - _setValue(v) { - this.f |= 1; - this.v = v; - } - - _deleteValue() { - this.f &= 6; - this.v = undefined; - } - - _peek(thing) { - if (isWeakKey(thing)) { - if ((this.f & 4) !== 4) return undefined; - return this.w.get(thing); - } else { - if ((this.f & 2) !== 2) return undefined; - return this.m.get(thing); - } - } - - _get(thing) { - if (isWeakKey(thing)) { - if ((this.f & 4) !== 4) { - const newMap = new WeakMap(); - this.f |= 4; - const newNode = new WeakTupleMap(); - (this.w = newMap).set(thing, newNode); - return newNode; - } - const entry = this.w.get(thing); - if (entry !== undefined) { - return entry; - } - const newNode = new WeakTupleMap(); - this.w.set(thing, newNode); - return newNode; - } else { - if ((this.f & 2) !== 2) { - const newMap = new Map(); - this.f |= 2; - const newNode = new WeakTupleMap(); - (this.m = newMap).set(thing, newNode); - return newNode; - } - const entry = this.m.get(thing); - if (entry !== undefined) { - return entry; - } - const newNode = new WeakTupleMap(); - this.m.set(thing, newNode); - return newNode; - } - } -} - -module.exports = WeakTupleMap; - - -/***/ }), - -/***/ 92229: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Mikola Lysenko @mikolalysenko -*/ + apply(compiler) { + compiler.hooks.compilation.tap( + "WebAssemblyModulesPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + WebAssemblyImportDependency, + normalModuleFactory + ); + compilation.dependencyFactories.set( + WebAssemblyExportImportedDependency, + normalModuleFactory + ); + normalModuleFactory.hooks.createParser + .for("webassembly/sync") + .tap("WebAssemblyModulesPlugin", () => { + const WebAssemblyParser = getWebAssemblyParser(); -/* cspell:disable-next-line */ -// Refactor: Peter Somogyvari @petermetz + return new WebAssemblyParser(); + }); -const compileSearch = (funcName, predicate, reversed, extraArgs, earlyOut) => { - const code = [ - "function ", - funcName, - "(a,l,h,", - extraArgs.join(","), - "){", - earlyOut ? "" : "var i=", - reversed ? "l-1" : "h+1", - ";while(l<=h){var m=(l+h)>>>1,x=a[m]" - ]; + normalModuleFactory.hooks.createGenerator + .for("webassembly/sync") + .tap("WebAssemblyModulesPlugin", () => { + const WebAssemblyJavascriptGenerator = + getWebAssemblyJavascriptGenerator(); + const WebAssemblyGenerator = getWebAssemblyGenerator(); - if (earlyOut) { - if (predicate.indexOf("c") < 0) { - code.push(";if(x===y){return m}else if(x<=y){"); - } else { - code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"); - } - } else { - code.push(";if(", predicate, "){i=m;"); - } - if (reversed) { - code.push("l=m+1}else{h=m-1}"); - } else { - code.push("h=m-1}else{l=m+1}"); - } - code.push("}"); - if (earlyOut) { - code.push("return -1};"); - } else { - code.push("return i};"); - } - return code.join(""); -}; + return Generator.byType({ + javascript: new WebAssemblyJavascriptGenerator(), + webassembly: new WebAssemblyGenerator(this.options) + }); + }); -const compileBoundsSearch = (predicate, reversed, suffix, earlyOut) => { - const arg1 = compileSearch( - "A", - "x" + predicate + "y", - reversed, - ["y"], - earlyOut - ); + compilation.hooks.renderManifest.tap( + "WebAssemblyModulesPlugin", + (result, options) => { + const { chunkGraph } = compilation; + const { chunk, outputOptions, codeGenerationResults } = options; - const arg2 = compileSearch( - "P", - "c(x,y)" + predicate + "0", - reversed, - ["y", "c"], - earlyOut - ); + for (const module of chunkGraph.getOrderedChunkModulesIterable( + chunk, + compareModulesByIdentifier + )) { + if (module.type === "webassembly/sync") { + const filenameTemplate = + outputOptions.webassemblyModuleFilename; - const fnHeader = "function dispatchBinarySearch"; + result.push({ + render: () => + codeGenerationResults.getSource( + module, + chunk.runtime, + "webassembly" + ), + filenameTemplate, + pathOptions: { + module, + runtime: chunk.runtime, + chunkGraph + }, + auxiliary: true, + identifier: `webassemblyModule${chunkGraph.getModuleId( + module + )}`, + hash: chunkGraph.getModuleHash(module, chunk.runtime) + }); + } + } - const fnBody = - "(a,y,c,l,h){\ -if(typeof(c)==='function'){\ -return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ -}else{\ -return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ -}}\ -return dispatchBinarySearch"; + return result; + } + ); - const fnArgList = [arg1, arg2, fnHeader, suffix, fnBody, suffix]; - const fnSource = fnArgList.join(""); - const result = new Function(fnSource); - return result(); -}; + compilation.hooks.afterChunks.tap("WebAssemblyModulesPlugin", () => { + const chunkGraph = compilation.chunkGraph; + const initialWasmModules = new Set(); + for (const chunk of compilation.chunks) { + if (chunk.canBeInitial()) { + for (const module of chunkGraph.getChunkModulesIterable(chunk)) { + if (module.type === "webassembly/sync") { + initialWasmModules.add(module); + } + } + } + } + for (const module of initialWasmModules) { + compilation.errors.push( + new WebAssemblyInInitialChunkError( + module, + compilation.moduleGraph, + compilation.chunkGraph, + compilation.requestShortener + ) + ); + } + }); + } + ); + } +} -module.exports = { - ge: compileBoundsSearch(">=", false, "GE"), - gt: compileBoundsSearch(">", false, "GT"), - lt: compileBoundsSearch("<", true, "LT"), - le: compileBoundsSearch("<=", true, "LE"), - eq: compileBoundsSearch("-", true, "EQ", true) -}; +module.exports = WebAssemblyModulesPlugin; /***/ }), -/***/ 60839: -/***/ (function(__unused_webpack_module, exports) { +/***/ 57059: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -130744,572 +131477,196 @@ module.exports = { -/** @type {WeakMap>} */ -const mergeCache = new WeakMap(); -/** @type {WeakMap>>} */ -const setPropertyCache = new WeakMap(); -const DELETE = Symbol("DELETE"); -const DYNAMIC_INFO = Symbol("cleverMerge dynamic info"); +const t = __webpack_require__(51826); +const { moduleContextFromModuleAST } = __webpack_require__(51826); +const { decode } = __webpack_require__(73726); +const Parser = __webpack_require__(11715); +const StaticExportsDependency = __webpack_require__(91418); +const WebAssemblyExportImportedDependency = __webpack_require__(52204); +const WebAssemblyImportDependency = __webpack_require__(5239); + +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Parser").ParserState} ParserState */ +/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ + +const JS_COMPAT_TYPES = new Set(["i32", "f32", "f64"]); /** - * Merges two given objects and caches the result to avoid computation if same objects passed as arguments again. - * @template T - * @template O - * @example - * // performs cleverMerge(first, second), stores the result in WeakMap and returns result - * cachedCleverMerge({a: 1}, {a: 2}) - * {a: 2} - * // when same arguments passed, gets the result from WeakMap and returns it. - * cachedCleverMerge({a: 1}, {a: 2}) - * {a: 2} - * @param {T} first first object - * @param {O} second second object - * @returns {T & O | T | O} merged object of first and second object + * @param {t.Signature} signature the func signature + * @returns {null | string} the type incompatible with js types */ -const cachedCleverMerge = (first, second) => { - if (second === undefined) return first; - if (first === undefined) return second; - if (typeof second !== "object" || second === null) return second; - if (typeof first !== "object" || first === null) return first; - - let innerCache = mergeCache.get(first); - if (innerCache === undefined) { - innerCache = new WeakMap(); - mergeCache.set(first, innerCache); +const getJsIncompatibleType = signature => { + for (const param of signature.params) { + if (!JS_COMPAT_TYPES.has(param.valtype)) { + return `${param.valtype} as parameter`; + } } - const prevMerge = innerCache.get(second); - if (prevMerge !== undefined) return prevMerge; - const newMerge = _cleverMerge(first, second, true); - innerCache.set(second, newMerge); - return newMerge; + for (const type of signature.results) { + if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; + } + return null; }; /** - * @template T - * @param {Partial} obj object - * @param {string} property property - * @param {string|number|boolean} value assignment value - * @returns {T} new object + * TODO why are there two different Signature types? + * @param {t.FuncSignature} signature the func signature + * @returns {null | string} the type incompatible with js types */ -const cachedSetProperty = (obj, property, value) => { - let mapByProperty = setPropertyCache.get(obj); - - if (mapByProperty === undefined) { - mapByProperty = new Map(); - setPropertyCache.set(obj, mapByProperty); +const getJsIncompatibleTypeOfFuncSignature = signature => { + for (const param of signature.args) { + if (!JS_COMPAT_TYPES.has(param)) { + return `${param} as parameter`; + } + } + for (const type of signature.result) { + if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; } + return null; +}; - let mapByValue = mapByProperty.get(property); +const decoderOpts = { + ignoreCodeSection: true, + ignoreDataSection: true, - if (mapByValue === undefined) { - mapByValue = new Map(); - mapByProperty.set(property, mapByValue); + // this will avoid having to lookup with identifiers in the ModuleContext + ignoreCustomNameSection: true +}; + +class WebAssemblyParser extends Parser { + constructor(options) { + super(); + this.hooks = Object.freeze({}); + this.options = options; } - let result = mapByValue.get(value); + /** + * @param {string | Buffer | PreparsedAst} source the source to parse + * @param {ParserState} state the parser state + * @returns {ParserState} the parser state + */ + parse(source, state) { + if (!Buffer.isBuffer(source)) { + throw new Error("WebAssemblyParser input must be a Buffer"); + } - if (result) return result; + // flag it as ESM + state.module.buildInfo.strict = true; + state.module.buildMeta.exportsType = "namespace"; - result = { - ...obj, - [property]: value - }; - mapByValue.set(value, result); + // parse it + const program = decode(source, decoderOpts); + const module = program.body[0]; - return result; -}; + const moduleContext = moduleContextFromModuleAST(module); -/** - * @typedef {Object} ObjectParsedPropertyEntry - * @property {any | undefined} base base value - * @property {string | undefined} byProperty the name of the selector property - * @property {Map} byValues value depending on selector property, merged with base - */ + // extract imports and exports + const exports = []; + let jsIncompatibleExports = (state.module.buildMeta.jsIncompatibleExports = + undefined); -/** - * @typedef {Object} ParsedObject - * @property {Map} static static properties (key is property name) - * @property {{ byProperty: string, fn: Function } | undefined} dynamic dynamic part - */ + const importedGlobals = []; + t.traverse(module, { + ModuleExport({ node }) { + const descriptor = node.descr; -/** @type {WeakMap} */ -const parseCache = new WeakMap(); + if (descriptor.exportType === "Func") { + const funcIdx = descriptor.id.value; -/** - * @param {object} obj the object - * @returns {ParsedObject} parsed object - */ -const cachedParseObject = obj => { - const entry = parseCache.get(obj); - if (entry !== undefined) return entry; - const result = parseObject(obj); - parseCache.set(obj, result); - return result; -}; + /** @type {t.FuncSignature} */ + const funcSignature = moduleContext.getFunction(funcIdx); -/** - * @param {object} obj the object - * @returns {ParsedObject} parsed object - */ -const parseObject = obj => { - const info = new Map(); - let dynamicInfo; - const getInfo = p => { - const entry = info.get(p); - if (entry !== undefined) return entry; - const newEntry = { - base: undefined, - byProperty: undefined, - byValues: undefined - }; - info.set(p, newEntry); - return newEntry; - }; - for (const key of Object.keys(obj)) { - if (key.startsWith("by")) { - const byProperty = key; - const byObj = obj[byProperty]; - if (typeof byObj === "object") { - for (const byValue of Object.keys(byObj)) { - const obj = byObj[byValue]; - for (const key of Object.keys(obj)) { - const entry = getInfo(key); - if (entry.byProperty === undefined) { - entry.byProperty = byProperty; - entry.byValues = new Map(); - } else if (entry.byProperty !== byProperty) { - throw new Error( - `${byProperty} and ${entry.byProperty} for a single property is not supported` - ); - } - entry.byValues.set(byValue, obj[key]); - if (byValue === "default") { - for (const otherByValue of Object.keys(byObj)) { - if (!entry.byValues.has(otherByValue)) - entry.byValues.set(otherByValue, undefined); - } + const incompatibleType = + getJsIncompatibleTypeOfFuncSignature(funcSignature); + + if (incompatibleType) { + if (jsIncompatibleExports === undefined) { + jsIncompatibleExports = + state.module.buildMeta.jsIncompatibleExports = {}; } + jsIncompatibleExports[node.name] = incompatibleType; } } - } else if (typeof byObj === "function") { - if (dynamicInfo === undefined) { - dynamicInfo = { - byProperty: key, - fn: byObj - }; - } else { - throw new Error( - `${key} and ${dynamicInfo.byProperty} when both are functions is not supported` - ); - } - } else { - const entry = getInfo(key); - entry.base = obj[key]; - } - } else { - const entry = getInfo(key); - entry.base = obj[key]; - } - } - return { - static: info, - dynamic: dynamicInfo - }; -}; -/** - * @param {Map} info static properties (key is property name) - * @param {{ byProperty: string, fn: Function } | undefined} dynamicInfo dynamic part - * @returns {object} the object - */ -const serializeObject = (info, dynamicInfo) => { - const obj = {}; - // Setup byProperty structure - for (const entry of info.values()) { - if (entry.byProperty !== undefined) { - const byObj = (obj[entry.byProperty] = obj[entry.byProperty] || {}); - for (const byValue of entry.byValues.keys()) { - byObj[byValue] = byObj[byValue] || {}; - } - } - } - for (const [key, entry] of info) { - if (entry.base !== undefined) { - obj[key] = entry.base; - } - // Fill byProperty structure - if (entry.byProperty !== undefined) { - const byObj = (obj[entry.byProperty] = obj[entry.byProperty] || {}); - for (const byValue of Object.keys(byObj)) { - const value = getFromByValues(entry.byValues, byValue); - if (value !== undefined) byObj[byValue][key] = value; - } - } - } - if (dynamicInfo !== undefined) { - obj[dynamicInfo.byProperty] = dynamicInfo.fn; - } - return obj; -}; + exports.push(node.name); -const VALUE_TYPE_UNDEFINED = 0; -const VALUE_TYPE_ATOM = 1; -const VALUE_TYPE_ARRAY_EXTEND = 2; -const VALUE_TYPE_OBJECT = 3; -const VALUE_TYPE_DELETE = 4; + if (node.descr && node.descr.exportType === "Global") { + const refNode = importedGlobals[node.descr.id.value]; + if (refNode) { + const dep = new WebAssemblyExportImportedDependency( + node.name, + refNode.module, + refNode.name, + refNode.descr.valtype + ); -/** - * @param {any} value a single value - * @returns {VALUE_TYPE_UNDEFINED | VALUE_TYPE_ATOM | VALUE_TYPE_ARRAY_EXTEND | VALUE_TYPE_OBJECT | VALUE_TYPE_DELETE} value type - */ -const getValueType = value => { - if (value === undefined) { - return VALUE_TYPE_UNDEFINED; - } else if (value === DELETE) { - return VALUE_TYPE_DELETE; - } else if (Array.isArray(value)) { - if (value.lastIndexOf("...") !== -1) return VALUE_TYPE_ARRAY_EXTEND; - return VALUE_TYPE_ATOM; - } else if ( - typeof value === "object" && - value !== null && - (!value.constructor || value.constructor === Object) - ) { - return VALUE_TYPE_OBJECT; - } - return VALUE_TYPE_ATOM; -}; + state.module.addDependency(dep); + } + } + }, -/** - * Merges two objects. Objects are deeply clever merged. - * Arrays might reference the old value with "...". - * Non-object values take preference over object values. - * @template T - * @template O - * @param {T} first first object - * @param {O} second second object - * @returns {T & O | T | O} merged object of first and second object - */ -const cleverMerge = (first, second) => { - if (second === undefined) return first; - if (first === undefined) return second; - if (typeof second !== "object" || second === null) return second; - if (typeof first !== "object" || first === null) return first; + Global({ node }) { + const init = node.init[0]; - return _cleverMerge(first, second, false); -}; + let importNode = null; -/** - * Merges two objects. Objects are deeply clever merged. - * @param {object} first first object - * @param {object} second second object - * @param {boolean} internalCaching should parsing of objects and nested merges be cached - * @returns {object} merged object of first and second object - */ -const _cleverMerge = (first, second, internalCaching = false) => { - const firstObject = internalCaching - ? cachedParseObject(first) - : parseObject(first); - const { static: firstInfo, dynamic: firstDynamicInfo } = firstObject; + if (init.id === "get_global") { + const globalIdx = init.args[0].value; - // If the first argument has a dynamic part we modify the dynamic part to merge the second argument - if (firstDynamicInfo !== undefined) { - let { byProperty, fn } = firstDynamicInfo; - const fnInfo = fn[DYNAMIC_INFO]; - if (fnInfo) { - second = internalCaching - ? cachedCleverMerge(fnInfo[1], second) - : cleverMerge(fnInfo[1], second); - fn = fnInfo[0]; - } - const newFn = (...args) => { - const fnResult = fn(...args); - return internalCaching - ? cachedCleverMerge(fnResult, second) - : cleverMerge(fnResult, second); - }; - newFn[DYNAMIC_INFO] = [fn, second]; - return serializeObject(firstObject.static, { byProperty, fn: newFn }); - } + if (globalIdx < importedGlobals.length) { + importNode = importedGlobals[globalIdx]; + } + } - // If the first part is static only, we merge the static parts and keep the dynamic part of the second argument - const secondObject = internalCaching - ? cachedParseObject(second) - : parseObject(second); - const { static: secondInfo, dynamic: secondDynamicInfo } = secondObject; - /** @type {Map} */ - const resultInfo = new Map(); - for (const [key, firstEntry] of firstInfo) { - const secondEntry = secondInfo.get(key); - const entry = - secondEntry !== undefined - ? mergeEntries(firstEntry, secondEntry, internalCaching) - : firstEntry; - resultInfo.set(key, entry); - } - for (const [key, secondEntry] of secondInfo) { - if (!firstInfo.has(key)) { - resultInfo.set(key, secondEntry); - } - } - return serializeObject(resultInfo, secondDynamicInfo); -}; + importedGlobals.push(importNode); + }, -/** - * @param {ObjectParsedPropertyEntry} firstEntry a - * @param {ObjectParsedPropertyEntry} secondEntry b - * @param {boolean} internalCaching should parsing of objects and nested merges be cached - * @returns {ObjectParsedPropertyEntry} new entry - */ -const mergeEntries = (firstEntry, secondEntry, internalCaching) => { - switch (getValueType(secondEntry.base)) { - case VALUE_TYPE_ATOM: - case VALUE_TYPE_DELETE: - // No need to consider firstEntry at all - // second value override everything - // = second.base + second.byProperty - return secondEntry; - case VALUE_TYPE_UNDEFINED: - if (!firstEntry.byProperty) { - // = first.base + second.byProperty - return { - base: firstEntry.base, - byProperty: secondEntry.byProperty, - byValues: secondEntry.byValues - }; - } else if (firstEntry.byProperty !== secondEntry.byProperty) { - throw new Error( - `${firstEntry.byProperty} and ${secondEntry.byProperty} for a single property is not supported` - ); - } else { - // = first.base + (first.byProperty + second.byProperty) - // need to merge first and second byValues - const newByValues = new Map(firstEntry.byValues); - for (const [key, value] of secondEntry.byValues) { - const firstValue = getFromByValues(firstEntry.byValues, key); - newByValues.set( - key, - mergeSingleValue(firstValue, value, internalCaching) - ); + ModuleImport({ node }) { + /** @type {false | string} */ + let onlyDirectImport = false; + + if (t.isMemory(node.descr) === true) { + onlyDirectImport = "Memory"; + } else if (t.isTable(node.descr) === true) { + onlyDirectImport = "Table"; + } else if (t.isFuncImportDescr(node.descr) === true) { + const incompatibleType = getJsIncompatibleType(node.descr.signature); + if (incompatibleType) { + onlyDirectImport = `Non-JS-compatible Func Signature (${incompatibleType})`; + } + } else if (t.isGlobalType(node.descr) === true) { + const type = node.descr.valtype; + if (!JS_COMPAT_TYPES.has(type)) { + onlyDirectImport = `Non-JS-compatible Global Type (${type})`; + } } - return { - base: firstEntry.base, - byProperty: firstEntry.byProperty, - byValues: newByValues - }; - } - default: { - if (!firstEntry.byProperty) { - // The simple case - // = (first.base + second.base) + second.byProperty - return { - base: mergeSingleValue( - firstEntry.base, - secondEntry.base, - internalCaching - ), - byProperty: secondEntry.byProperty, - byValues: secondEntry.byValues - }; - } - let newBase; - const intermediateByValues = new Map(firstEntry.byValues); - for (const [key, value] of intermediateByValues) { - intermediateByValues.set( - key, - mergeSingleValue(value, secondEntry.base, internalCaching) - ); - } - if ( - Array.from(firstEntry.byValues.values()).every(value => { - const type = getValueType(value); - return type === VALUE_TYPE_ATOM || type === VALUE_TYPE_DELETE; - }) - ) { - // = (first.base + second.base) + ((first.byProperty + second.base) + second.byProperty) - newBase = mergeSingleValue( - firstEntry.base, - secondEntry.base, - internalCaching - ); - } else { - // = first.base + ((first.byProperty (+default) + second.base) + second.byProperty) - newBase = firstEntry.base; - if (!intermediateByValues.has("default")) - intermediateByValues.set("default", secondEntry.base); - } - if (!secondEntry.byProperty) { - // = first.base + (first.byProperty + second.base) - return { - base: newBase, - byProperty: firstEntry.byProperty, - byValues: intermediateByValues - }; - } else if (firstEntry.byProperty !== secondEntry.byProperty) { - throw new Error( - `${firstEntry.byProperty} and ${secondEntry.byProperty} for a single property is not supported` - ); - } - const newByValues = new Map(intermediateByValues); - for (const [key, value] of secondEntry.byValues) { - const firstValue = getFromByValues(intermediateByValues, key); - newByValues.set( - key, - mergeSingleValue(firstValue, value, internalCaching) + + const dep = new WebAssemblyImportDependency( + node.module, + node.name, + node.descr, + onlyDirectImport ); - } - return { - base: newBase, - byProperty: firstEntry.byProperty, - byValues: newByValues - }; - } - } -}; -/** - * @param {Map} byValues all values - * @param {string} key value of the selector - * @returns {any | undefined} value - */ -const getFromByValues = (byValues, key) => { - if (key !== "default" && byValues.has(key)) { - return byValues.get(key); - } - return byValues.get("default"); -}; + state.module.addDependency(dep); -/** - * @param {any} a value - * @param {any} b value - * @param {boolean} internalCaching should parsing of objects and nested merges be cached - * @returns {any} value - */ -const mergeSingleValue = (a, b, internalCaching) => { - const bType = getValueType(b); - const aType = getValueType(a); - switch (bType) { - case VALUE_TYPE_DELETE: - case VALUE_TYPE_ATOM: - return b; - case VALUE_TYPE_OBJECT: { - return aType !== VALUE_TYPE_OBJECT - ? b - : internalCaching - ? cachedCleverMerge(a, b) - : cleverMerge(a, b); - } - case VALUE_TYPE_UNDEFINED: - return a; - case VALUE_TYPE_ARRAY_EXTEND: - switch ( - aType !== VALUE_TYPE_ATOM - ? aType - : Array.isArray(a) - ? VALUE_TYPE_ARRAY_EXTEND - : VALUE_TYPE_OBJECT - ) { - case VALUE_TYPE_UNDEFINED: - return b; - case VALUE_TYPE_DELETE: - return b.filter(item => item !== "..."); - case VALUE_TYPE_ARRAY_EXTEND: { - const newArray = []; - for (const item of b) { - if (item === "...") { - for (const item of a) { - newArray.push(item); - } - } else { - newArray.push(item); - } - } - return newArray; + if (t.isGlobalType(node.descr)) { + importedGlobals.push(node); } - case VALUE_TYPE_OBJECT: - return b.map(item => (item === "..." ? a : item)); - default: - throw new Error("Not implemented"); } - default: - throw new Error("Not implemented"); - } -}; + }); -/** - * @template T - * @param {T} obj the object - * @returns {T} the object without operations like "..." or DELETE - */ -const removeOperations = obj => { - const newObj = /** @type {T} */ ({}); - for (const key of Object.keys(obj)) { - const value = obj[key]; - const type = getValueType(value); - switch (type) { - case VALUE_TYPE_UNDEFINED: - case VALUE_TYPE_DELETE: - break; - case VALUE_TYPE_OBJECT: - newObj[key] = removeOperations(value); - break; - case VALUE_TYPE_ARRAY_EXTEND: - newObj[key] = value.filter(i => i !== "..."); - break; - default: - newObj[key] = value; - break; - } - } - return newObj; -}; + state.module.addDependency(new StaticExportsDependency(exports, false)); -/** - * @template T - * @template {string} P - * @param {T} obj the object - * @param {P} byProperty the by description - * @param {...any} values values - * @returns {Omit} object with merged byProperty - */ -const resolveByProperty = (obj, byProperty, ...values) => { - if (typeof obj !== "object" || obj === null || !(byProperty in obj)) { - return obj; - } - const { [byProperty]: _byValue, ..._remaining } = /** @type {object} */ (obj); - const remaining = /** @type {T} */ (_remaining); - const byValue = /** @type {Record | function(...any[]): T} */ ( - _byValue - ); - if (typeof byValue === "object") { - const key = values[0]; - if (key in byValue) { - return cachedCleverMerge(remaining, byValue[key]); - } else if ("default" in byValue) { - return cachedCleverMerge(remaining, byValue.default); - } else { - return /** @type {T} */ (remaining); - } - } else if (typeof byValue === "function") { - const result = byValue.apply(null, values); - return cachedCleverMerge( - remaining, - resolveByProperty(result, byProperty, ...values) - ); + return state; } -}; +} -exports.cachedSetProperty = cachedSetProperty; -exports.cachedCleverMerge = cachedCleverMerge; -exports.cleverMerge = cleverMerge; -exports.resolveByProperty = resolveByProperty; -exports.removeOperations = removeOperations; -exports.DELETE = DELETE; +module.exports = WebAssemblyParser; /***/ }), -/***/ 29579: +/***/ 18650: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; @@ -131320,464 +131677,266 @@ exports.DELETE = DELETE; -const { compareRuntime } = __webpack_require__(17156); +const Template = __webpack_require__(1626); +const WebAssemblyImportDependency = __webpack_require__(5239); -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../ChunkGroup")} ChunkGroup */ -/** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */ /** @typedef {import("../Module")} Module */ /** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @template T @typedef {function(T, T): -1|0|1} Comparator */ -/** @template TArg @template T @typedef {function(TArg, T, T): -1|0|1} RawParameterizedComparator */ -/** @template TArg @template T @typedef {function(TArg): Comparator} ParameterizedComparator */ - -/** - * @template T - * @param {RawParameterizedComparator} fn comparator with argument - * @returns {ParameterizedComparator} comparator - */ -const createCachedParameterizedComparator = fn => { - /** @type {WeakMap>} */ - const map = new WeakMap(); - return arg => { - const cachedResult = map.get(arg); - if (cachedResult !== undefined) return cachedResult; - /** - * @param {T} a first item - * @param {T} b second item - * @returns {-1|0|1} compare result - */ - const result = fn.bind(null, arg); - map.set(arg, result); - return result; - }; -}; - -/** - * @param {Chunk} a chunk - * @param {Chunk} b chunk - * @returns {-1|0|1} compare result - */ -exports.compareChunksById = (a, b) => { - return compareIds(a.id, b.id); -}; - -/** - * @param {Module} a module - * @param {Module} b module - * @returns {-1|0|1} compare result +/** @typedef {Object} UsedWasmDependency + * @property {WebAssemblyImportDependency} dependency the dependency + * @property {string} name the export name + * @property {string} module the module name */ -exports.compareModulesByIdentifier = (a, b) => { - return compareIds(a.identifier(), b.identifier()); -}; -/** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {Module} a module - * @param {Module} b module - * @returns {-1|0|1} compare result - */ -const compareModulesById = (chunkGraph, a, b) => { - return compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b)); -}; -/** @type {ParameterizedComparator} */ -exports.compareModulesById = - createCachedParameterizedComparator(compareModulesById); +const MANGLED_MODULE = "a"; /** - * @param {number} a number - * @param {number} b number - * @returns {-1|0|1} compare result + * @param {ModuleGraph} moduleGraph the module graph + * @param {Module} module the module + * @param {boolean} mangle mangle module and export names + * @returns {UsedWasmDependency[]} used dependencies and (mangled) name */ -const compareNumbers = (a, b) => { - if (typeof a !== typeof b) { - return typeof a < typeof b ? -1 : 1; - } - if (a < b) return -1; - if (a > b) return 1; - return 0; -}; -exports.compareNumbers = compareNumbers; +const getUsedDependencies = (moduleGraph, module, mangle) => { + /** @type {UsedWasmDependency[]} */ + const array = []; + let importIndex = 0; + for (const dep of module.dependencies) { + if (dep instanceof WebAssemblyImportDependency) { + if ( + dep.description.type === "GlobalType" || + moduleGraph.getModule(dep) === null + ) { + continue; + } -/** - * @param {string} a string - * @param {string} b string - * @returns {-1|0|1} compare result - */ -const compareStringsNumeric = (a, b) => { - const partsA = a.split(/(\d+)/); - const partsB = b.split(/(\d+)/); - const len = Math.min(partsA.length, partsB.length); - for (let i = 0; i < len; i++) { - const pA = partsA[i]; - const pB = partsB[i]; - if (i % 2 === 0) { - if (pA.length > pB.length) { - if (pA.slice(0, pB.length) > pB) return 1; - return -1; - } else if (pB.length > pA.length) { - if (pB.slice(0, pA.length) > pA) return -1; - return 1; + const exportName = dep.name; + // TODO add the following 3 lines when removing of ModuleExport is possible + // const importedModule = moduleGraph.getModule(dep); + // const usedName = importedModule && moduleGraph.getExportsInfo(importedModule).getUsedName(exportName, runtime); + // if (usedName !== false) { + if (mangle) { + array.push({ + dependency: dep, + name: Template.numberToIdentifier(importIndex++), + module: MANGLED_MODULE + }); } else { - if (pA < pB) return -1; - if (pA > pB) return 1; + array.push({ + dependency: dep, + name: exportName, + module: dep.request + }); } - } else { - const nA = +pA; - const nB = +pB; - if (nA < nB) return -1; - if (nA > nB) return 1; } } - if (partsB.length < partsA.length) return 1; - if (partsB.length > partsA.length) return -1; - return 0; + return array; }; -exports.compareStringsNumeric = compareStringsNumeric; -/** - * @param {ModuleGraph} moduleGraph the module graph - * @param {Module} a module - * @param {Module} b module - * @returns {-1|0|1} compare result - */ -const compareModulesByPostOrderIndexOrIdentifier = (moduleGraph, a, b) => { - const cmp = compareNumbers( - moduleGraph.getPostOrderIndex(a), - moduleGraph.getPostOrderIndex(b) - ); - if (cmp !== 0) return cmp; - return compareIds(a.identifier(), b.identifier()); -}; -/** @type {ParameterizedComparator} */ -exports.compareModulesByPostOrderIndexOrIdentifier = - createCachedParameterizedComparator( - compareModulesByPostOrderIndexOrIdentifier - ); +exports.getUsedDependencies = getUsedDependencies; +exports.MANGLED_MODULE = MANGLED_MODULE; -/** - * @param {ModuleGraph} moduleGraph the module graph - * @param {Module} a module - * @param {Module} b module - * @returns {-1|0|1} compare result - */ -const compareModulesByPreOrderIndexOrIdentifier = (moduleGraph, a, b) => { - const cmp = compareNumbers( - moduleGraph.getPreOrderIndex(a), - moduleGraph.getPreOrderIndex(b) - ); - if (cmp !== 0) return cmp; - return compareIds(a.identifier(), b.identifier()); -}; -/** @type {ParameterizedComparator} */ -exports.compareModulesByPreOrderIndexOrIdentifier = - createCachedParameterizedComparator( - compareModulesByPreOrderIndexOrIdentifier - ); -/** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {Module} a module - * @param {Module} b module - * @returns {-1|0|1} compare result - */ -const compareModulesByIdOrIdentifier = (chunkGraph, a, b) => { - const cmp = compareIds(chunkGraph.getModuleId(a), chunkGraph.getModuleId(b)); - if (cmp !== 0) return cmp; - return compareIds(a.identifier(), b.identifier()); -}; -/** @type {ParameterizedComparator} */ -exports.compareModulesByIdOrIdentifier = createCachedParameterizedComparator( - compareModulesByIdOrIdentifier -); +/***/ }), -/** - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {Chunk} a chunk - * @param {Chunk} b chunk - * @returns {-1|0|1} compare result - */ -const compareChunks = (chunkGraph, a, b) => { - return chunkGraph.compareChunks(a, b); -}; -/** @type {ParameterizedComparator} */ -exports.compareChunks = createCachedParameterizedComparator(compareChunks); +/***/ 78613: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * @param {string|number} a first id - * @param {string|number} b second id - * @returns {-1|0|1} compare result - */ -const compareIds = (a, b) => { - if (typeof a !== typeof b) { - return typeof a < typeof b ? -1 : 1; - } - if (a < b) return -1; - if (a > b) return 1; - return 0; -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -exports.compareIds = compareIds; -/** - * @param {string} a first string - * @param {string} b second string - * @returns {-1|0|1} compare result - */ -const compareStrings = (a, b) => { - if (a < b) return -1; - if (a > b) return 1; - return 0; -}; -exports.compareStrings = compareStrings; +/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ +/** @typedef {import("../../declarations/WebpackOptions").WasmLoadingType} WasmLoadingType */ +/** @typedef {import("../Compiler")} Compiler */ -/** - * @param {ChunkGroup} a first chunk group - * @param {ChunkGroup} b second chunk group - * @returns {-1|0|1} compare result - */ -const compareChunkGroupsByIndex = (a, b) => { - return a.index < b.index ? -1 : 1; +/** @type {WeakMap>} */ +const enabledTypes = new WeakMap(); + +const getEnabledTypes = compiler => { + let set = enabledTypes.get(compiler); + if (set === undefined) { + set = new Set(); + enabledTypes.set(compiler, set); + } + return set; }; -exports.compareChunkGroupsByIndex = compareChunkGroupsByIndex; - -/** - * @template K1 {Object} - * @template K2 - * @template T - */ -class TwoKeyWeakMap { - constructor() { - /** @private @type {WeakMap>} */ - this._map = new WeakMap(); +class EnableWasmLoadingPlugin { + /** + * @param {WasmLoadingType} type library type that should be available + */ + constructor(type) { + this.type = type; } /** - * @param {K1} key1 first key - * @param {K2} key2 second key - * @returns {T | undefined} value + * @param {Compiler} compiler the compiler instance + * @param {WasmLoadingType} type type of library + * @returns {void} */ - get(key1, key2) { - const childMap = this._map.get(key1); - if (childMap === undefined) { - return undefined; - } - return childMap.get(key2); + static setEnabled(compiler, type) { + getEnabledTypes(compiler).add(type); } /** - * @param {K1} key1 first key - * @param {K2} key2 second key - * @param {T | undefined} value new value + * @param {Compiler} compiler the compiler instance + * @param {WasmLoadingType} type type of library * @returns {void} */ - set(key1, key2, value) { - let childMap = this._map.get(key1); - if (childMap === undefined) { - childMap = new WeakMap(); - this._map.set(key1, childMap); + static checkEnabled(compiler, type) { + if (!getEnabledTypes(compiler).has(type)) { + throw new Error( + `Library type "${type}" is not enabled. ` + + "EnableWasmLoadingPlugin need to be used to enable this type of wasm loading. " + + 'This usually happens through the "output.enabledWasmLoadingTypes" option. ' + + 'If you are using a function as entry which sets "wasmLoading", you need to add all potential library types to "output.enabledWasmLoadingTypes". ' + + "These types are enabled: " + + Array.from(getEnabledTypes(compiler)).join(", ") + ); } - childMap.set(key2, value); } -} - -/** @type {TwoKeyWeakMap, Comparator, Comparator>}} */ -const concatComparatorsCache = new TwoKeyWeakMap(); -/** - * @template T - * @param {Comparator} c1 comparator - * @param {Comparator} c2 comparator - * @param {Comparator[]} cRest comparators - * @returns {Comparator} comparator - */ -const concatComparators = (c1, c2, ...cRest) => { - if (cRest.length > 0) { - const [c3, ...cRest2] = cRest; - return concatComparators(c1, concatComparators(c2, c3, ...cRest2)); - } - const cacheEntry = /** @type {Comparator} */ ( - concatComparatorsCache.get(c1, c2) - ); - if (cacheEntry !== undefined) return cacheEntry; /** - * @param {T} a first value - * @param {T} b second value - * @returns {-1|0|1} compare result + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - const result = (a, b) => { - const res = c1(a, b); - if (res !== 0) return res; - return c2(a, b); - }; - concatComparatorsCache.set(c1, c2, result); - return result; -}; -exports.concatComparators = concatComparators; - -/** @template A, B @typedef {(input: A) => B} Selector */ + apply(compiler) { + const { type } = this; -/** @type {TwoKeyWeakMap, Comparator, Comparator>}} */ -const compareSelectCache = new TwoKeyWeakMap(); + // Only enable once + const enabled = getEnabledTypes(compiler); + if (enabled.has(type)) return; + enabled.add(type); -/** - * @template T - * @template R - * @param {Selector} getter getter for value - * @param {Comparator} comparator comparator - * @returns {Comparator} comparator - */ -const compareSelect = (getter, comparator) => { - const cacheEntry = compareSelectCache.get(getter, comparator); - if (cacheEntry !== undefined) return cacheEntry; - /** - * @param {T} a first value - * @param {T} b second value - * @returns {-1|0|1} compare result - */ - const result = (a, b) => { - const aValue = getter(a); - const bValue = getter(b); - if (aValue !== undefined && aValue !== null) { - if (bValue !== undefined && bValue !== null) { - return comparator(aValue, bValue); + if (typeof type === "string") { + switch (type) { + case "fetch": { + // TODO webpack 6 remove FetchCompileWasmPlugin + const FetchCompileWasmPlugin = __webpack_require__(35537); + const FetchCompileAsyncWasmPlugin = __webpack_require__(8437); + new FetchCompileWasmPlugin({ + mangleImports: compiler.options.optimization.mangleWasmImports + }).apply(compiler); + new FetchCompileAsyncWasmPlugin().apply(compiler); + break; + } + case "async-node": { + // TODO webpack 6 remove ReadFileCompileWasmPlugin + const ReadFileCompileWasmPlugin = __webpack_require__(98939); + // @ts-expect-error typescript bug for duplicate require + const ReadFileCompileAsyncWasmPlugin = __webpack_require__(73163); + new ReadFileCompileWasmPlugin({ + mangleImports: compiler.options.optimization.mangleWasmImports + }).apply(compiler); + new ReadFileCompileAsyncWasmPlugin({ type }).apply(compiler); + break; + } + case "async-node-module": { + // @ts-expect-error typescript bug for duplicate require + const ReadFileCompileAsyncWasmPlugin = __webpack_require__(73163); + new ReadFileCompileAsyncWasmPlugin({ type, import: true }).apply( + compiler + ); + break; + } + case "universal": + throw new Error( + "Universal WebAssembly Loading is not implemented yet" + ); + default: + throw new Error(`Unsupported wasm loading type ${type}. +Plugins which provide custom wasm loading types must call EnableWasmLoadingPlugin.setEnabled(compiler, type) to disable this error.`); } - return -1; } else { - if (bValue !== undefined && bValue !== null) { - return 1; - } - return 0; + // TODO support plugin instances here + // apply them to the compiler } - }; - compareSelectCache.set(getter, comparator, result); - return result; -}; -exports.compareSelect = compareSelect; + } +} -/** @type {WeakMap, Comparator>>} */ -const compareIteratorsCache = new WeakMap(); +module.exports = EnableWasmLoadingPlugin; -/** - * @template T - * @param {Comparator} elementComparator comparator for elements - * @returns {Comparator>} comparator for iterables of elements - */ -const compareIterables = elementComparator => { - const cacheEntry = compareIteratorsCache.get(elementComparator); - if (cacheEntry !== undefined) return cacheEntry; + +/***/ }), + +/***/ 8437: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const AsyncWasmLoadingRuntimeModule = __webpack_require__(5434); + +/** @typedef {import("../Compiler")} Compiler */ + +class FetchCompileAsyncWasmPlugin { /** - * @param {Iterable} a first value - * @param {Iterable} b second value - * @returns {-1|0|1} compare result + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - const result = (a, b) => { - const aI = a[Symbol.iterator](); - const bI = b[Symbol.iterator](); - // eslint-disable-next-line no-constant-condition - while (true) { - const aItem = aI.next(); - const bItem = bI.next(); - if (aItem.done) { - return bItem.done ? 0 : -1; - } else if (bItem.done) { - return 1; - } - const res = elementComparator(aItem.value, bItem.value); - if (res !== 0) return res; - } - }; - compareIteratorsCache.set(elementComparator, result); - return result; -}; -exports.compareIterables = compareIterables; + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "FetchCompileAsyncWasmPlugin", + compilation => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === "fetch"; + }; + const generateLoadBinaryCode = path => + `fetch(${RuntimeGlobals.publicPath} + ${path})`; -// TODO this is no longer needed when minimum node.js version is >= 12 -// since these versions ship with a stable sort function -/** - * @template T - * @param {Iterable} iterable original ordered list - * @returns {Comparator} comparator - */ -exports.keepOriginalOrder = iterable => { - /** @type {Map} */ - const map = new Map(); - let i = 0; - for (const item of iterable) { - map.set(item, i++); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.instantiateWasm) + .tap("FetchCompileAsyncWasmPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + const chunkGraph = compilation.chunkGraph; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + m => m.type === "webassembly/async" + ) + ) { + return; + } + set.add(RuntimeGlobals.publicPath); + compilation.addRuntimeModule( + chunk, + new AsyncWasmLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: true + }) + ); + }); + } + ); } - return (a, b) => compareNumbers(map.get(a), map.get(b)); -}; - -/** - * @param {ChunkGraph} chunkGraph the chunk graph - * @returns {Comparator} comparator - */ -exports.compareChunksNatural = chunkGraph => { - const cmpFn = exports.compareModulesById(chunkGraph); - const cmpIterableFn = compareIterables(cmpFn); - return concatComparators( - compareSelect(chunk => chunk.name, compareIds), - compareSelect(chunk => chunk.runtime, compareRuntime), - compareSelect( - /** - * @param {Chunk} chunk a chunk - * @returns {Iterable} modules - */ - chunk => chunkGraph.getOrderedChunkModulesIterable(chunk, cmpFn), - cmpIterableFn - ) - ); -}; +} -/** - * Compare two locations - * @param {DependencyLocation} a A location node - * @param {DependencyLocation} b A location node - * @returns {-1|0|1} sorting comparator value - */ -exports.compareLocations = (a, b) => { - let isObjectA = typeof a === "object" && a !== null; - let isObjectB = typeof b === "object" && b !== null; - if (!isObjectA || !isObjectB) { - if (isObjectA) return 1; - if (isObjectB) return -1; - return 0; - } - if ("start" in a) { - if ("start" in b) { - const ap = a.start; - const bp = b.start; - if (ap.line < bp.line) return -1; - if (ap.line > bp.line) return 1; - if (ap.column < bp.column) return -1; - if (ap.column > bp.column) return 1; - } else return -1; - } else if ("start" in b) return 1; - if ("name" in a) { - if ("name" in b) { - if (a.name < b.name) return -1; - if (a.name > b.name) return 1; - } else return -1; - } else if ("name" in b) return 1; - if ("index" in a) { - if ("index" in b) { - if (a.index < b.index) return -1; - if (a.index > b.index) return 1; - } else return -1; - } else if ("index" in b) return 1; - return 0; -}; +module.exports = FetchCompileAsyncWasmPlugin; /***/ }), -/***/ 29404: -/***/ (function(module) { +/***/ 35537: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -131787,210 +131946,622 @@ exports.compareLocations = (a, b) => { -const quoteMeta = str => { - return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); -}; +const RuntimeGlobals = __webpack_require__(16475); +const WasmChunkLoadingRuntimeModule = __webpack_require__(87394); -const toSimpleString = str => { - if (`${+str}` === str) { - return str; - } - return JSON.stringify(str); -}; +/** @typedef {import("../Compiler")} Compiler */ -/** - * @param {Record} map value map - * @returns {true|false|function(string): string} true/false, when unconditionally true/false, or a template function to determine the value at runtime - */ -const compileBooleanMatcher = map => { - const positiveItems = Object.keys(map).filter(i => map[i]); - const negativeItems = Object.keys(map).filter(i => !map[i]); - if (positiveItems.length === 0) return false; - if (negativeItems.length === 0) return true; - return compileBooleanMatcherFromLists(positiveItems, negativeItems); -}; +// TODO webpack 6 remove -/** - * @param {string[]} positiveItems positive items - * @param {string[]} negativeItems negative items - * @returns {function(string): string} a template function to determine the value at runtime - */ -const compileBooleanMatcherFromLists = (positiveItems, negativeItems) => { - if (positiveItems.length === 0) return () => "false"; - if (negativeItems.length === 0) return () => "true"; - if (positiveItems.length === 1) - return value => `${toSimpleString(positiveItems[0])} == ${value}`; - if (negativeItems.length === 1) - return value => `${toSimpleString(negativeItems[0])} != ${value}`; - const positiveRegexp = itemsToRegexp(positiveItems); - const negativeRegexp = itemsToRegexp(negativeItems); - if (positiveRegexp.length <= negativeRegexp.length) { - return value => `/^${positiveRegexp}$/.test(${value})`; - } else { - return value => `!/^${negativeRegexp}$/.test(${value})`; +class FetchCompileWasmPlugin { + constructor(options) { + this.options = options || {}; } -}; -const popCommonItems = (itemsSet, getKey, condition) => { - const map = new Map(); - for (const item of itemsSet) { - const key = getKey(item); - if (key) { - let list = map.get(key); - if (list === undefined) { - list = []; - map.set(key, list); - } - list.push(item); - } - } - const result = []; - for (const list of map.values()) { - if (condition(list)) { - for (const item of list) { - itemsSet.delete(item); - } - result.push(list); - } - } - return result; -}; + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "FetchCompileWasmPlugin", + compilation => { + const globalWasmLoading = compilation.outputOptions.wasmLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const wasmLoading = + options && options.wasmLoading !== undefined + ? options.wasmLoading + : globalWasmLoading; + return wasmLoading === "fetch"; + }; + const generateLoadBinaryCode = path => + `fetch(${RuntimeGlobals.publicPath} + ${path})`; -const getCommonPrefix = items => { - let prefix = items[0]; - for (let i = 1; i < items.length; i++) { - const item = items[i]; - for (let p = 0; p < prefix.length; p++) { - if (item[p] !== prefix[p]) { - prefix = prefix.slice(0, p); - break; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("FetchCompileWasmPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + const chunkGraph = compilation.chunkGraph; + if ( + !chunkGraph.hasModuleInGraph( + chunk, + m => m.type === "webassembly/sync" + ) + ) { + return; + } + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.publicPath); + compilation.addRuntimeModule( + chunk, + new WasmChunkLoadingRuntimeModule({ + generateLoadBinaryCode, + supportsStreaming: true, + mangleImports: this.options.mangleImports, + runtimeRequirements: set + }) + ); + }); } - } + ); } - return prefix; -}; +} -const getCommonSuffix = items => { - let suffix = items[0]; - for (let i = 1; i < items.length; i++) { - const item = items[i]; - for (let p = item.length - 1, s = suffix.length - 1; s >= 0; p--, s--) { - if (item[p] !== suffix[s]) { - suffix = suffix.slice(s + 1); - break; - } - } - } - return suffix; -}; +module.exports = FetchCompileWasmPlugin; -const itemsToRegexp = itemsArr => { - if (itemsArr.length === 1) { - return quoteMeta(itemsArr[0]); - } - const finishedItems = []; - // merge single char items: (a|b|c|d|ef) => ([abcd]|ef) - let countOfSingleCharItems = 0; - for (const item of itemsArr) { - if (item.length === 1) { - countOfSingleCharItems++; - } - } - // special case for only single char items - if (countOfSingleCharItems === itemsArr.length) { - return `[${quoteMeta(itemsArr.sort().join(""))}]`; - } - const items = new Set(itemsArr.sort()); - if (countOfSingleCharItems > 2) { - let singleCharItems = ""; - for (const item of items) { - if (item.length === 1) { - singleCharItems += item; - items.delete(item); - } - } - finishedItems.push(`[${quoteMeta(singleCharItems)}]`); - } +/***/ }), - // special case for 2 items with common prefix/suffix - if (finishedItems.length === 0 && items.size === 2) { - const prefix = getCommonPrefix(itemsArr); - const suffix = getCommonSuffix( - itemsArr.map(item => item.slice(prefix.length)) +/***/ 83121: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const RuntimeGlobals = __webpack_require__(16475); +const JsonpChunkLoadingRuntimeModule = __webpack_require__(84154); + +/** @typedef {import("../Compiler")} Compiler */ + +class JsonpChunkLoadingPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "JsonpChunkLoadingPlugin", + compilation => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === "jsonp"; + }; + const onceForChunkSet = new WeakSet(); + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + compilation.addRuntimeModule( + chunk, + new JsonpChunkLoadingRuntimeModule(set) + ); + }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("JsonpChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap("JsonpChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap("JsonpChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap("JsonpChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.onChunksLoaded) + .tap("JsonpChunkLoadingPlugin", handler); + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("JsonpChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.loadScript); + set.add(RuntimeGlobals.getChunkScriptFilename); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap("JsonpChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.loadScript); + set.add(RuntimeGlobals.getChunkUpdateScriptFilename); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.hmrModuleData); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap("JsonpChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getUpdateManifestFilename); + }); + } ); - if (prefix.length > 0 || suffix.length > 0) { - return `${quoteMeta(prefix)}${itemsToRegexp( - itemsArr.map(i => i.slice(prefix.length, -suffix.length || undefined)) - )}${quoteMeta(suffix)}`; - } } +} - // special case for 2 items with common suffix - if (finishedItems.length === 0 && items.size === 2) { - const it = items[Symbol.iterator](); - const a = it.next().value; - const b = it.next().value; - if (a.length > 0 && b.length > 0 && a.slice(-1) === b.slice(-1)) { - return `${itemsToRegexp([a.slice(0, -1), b.slice(0, -1)])}${quoteMeta( - a.slice(-1) - )}`; +module.exports = JsonpChunkLoadingPlugin; + + +/***/ }), + +/***/ 84154: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + + + +const { SyncWaterfallHook } = __webpack_require__(6967); +const Compilation = __webpack_require__(85720); +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); +const chunkHasJs = (__webpack_require__(89464).chunkHasJs); +const { getInitialChunkIds } = __webpack_require__(98124); +const compileBooleanMatcher = __webpack_require__(29404); + +/** @typedef {import("../Chunk")} Chunk */ + +/** + * @typedef {Object} JsonpCompilationPluginHooks + * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload + * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch + */ + +/** @type {WeakMap} */ +const compilationHooksMap = new WeakMap(); + +class JsonpChunkLoadingRuntimeModule extends RuntimeModule { + /** + * @param {Compilation} compilation the compilation + * @returns {JsonpCompilationPluginHooks} 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 = { + linkPreload: new SyncWaterfallHook(["source", "chunk"]), + linkPrefetch: new SyncWaterfallHook(["source", "chunk"]) + }; + compilationHooksMap.set(compilation, hooks); } + return hooks; } - // find common prefix: (a1|a2|a3|a4|b5) => (a(1|2|3|4)|b5) - const prefixed = popCommonItems( - items, - item => (item.length >= 1 ? item[0] : false), - list => { - if (list.length >= 3) return true; - if (list.length <= 1) return false; - return list[0][1] === list[1][1]; - } - ); - for (const prefixedItems of prefixed) { - const prefix = getCommonPrefix(prefixedItems); - finishedItems.push( - `${quoteMeta(prefix)}${itemsToRegexp( - prefixedItems.map(i => i.slice(prefix.length)) - )}` - ); + constructor(runtimeRequirements) { + super("jsonp chunk loading", RuntimeModule.STAGE_ATTACH); + this._runtimeRequirements = runtimeRequirements; } - // find common suffix: (a1|b1|c1|d1|e2) => ((a|b|c|d)1|e2) - const suffixed = popCommonItems( - items, - item => (item.length >= 1 ? item.slice(-1) : false), - list => { - if (list.length >= 3) return true; - if (list.length <= 1) return false; - return list[0].slice(-2) === list[1].slice(-2); - } - ); - for (const suffixedItems of suffixed) { - const suffix = getCommonSuffix(suffixedItems); - finishedItems.push( - `${itemsToRegexp( - suffixedItems.map(i => i.slice(0, -suffix.length)) - )}${quoteMeta(suffix)}` + /** + * @returns {string} runtime code + */ + generate() { + const { chunkGraph, compilation, chunk } = this; + const { + runtimeTemplate, + outputOptions: { + chunkLoadingGlobal, + hotUpdateGlobal, + crossOriginLoading, + scriptType + } + } = compilation; + const globalObject = runtimeTemplate.globalObject; + const { linkPreload, linkPrefetch } = + JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation); + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI); + const withLoading = this._runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withCallback = this._runtimeRequirements.has( + RuntimeGlobals.chunkCallback + ); + const withOnChunkLoad = this._runtimeRequirements.has( + RuntimeGlobals.onChunksLoaded + ); + const withHmr = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this._runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const withPrefetch = this._runtimeRequirements.has( + RuntimeGlobals.prefetchChunkHandlers ); + const withPreload = this._runtimeRequirements.has( + RuntimeGlobals.preloadChunkHandlers + ); + const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( + chunkLoadingGlobal + )}]`; + const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); + const hasJsMatcher = compileBooleanMatcher(conditionMap); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_jsonp` + : undefined; + + return Template.asString([ + withBaseURI + ? Template.asString([ + `${RuntimeGlobals.baseURI} = document.baseURI || self.location.href;` + ]) + : "// no baseURI", + "", + "// object to store loaded and loading chunks", + "// undefined = chunk not loaded, null = chunk preloaded/prefetched", + "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join( + ",\n" + ) + ), + "};", + "", + withLoading + ? Template.asString([ + `${fn}.j = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasJsMatcher !== false + ? Template.indent([ + "// JSONP chunk loading for javascript", + `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + "", + '// a Promise means "currently loading".', + "if(installedChunkData) {", + Template.indent([ + "promises.push(installedChunkData[2]);" + ]), + "} else {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent([ + "// setup Promise in chunk cache", + `var promise = new Promise(${runtimeTemplate.expressionFunction( + `installedChunkData = installedChunks[chunkId] = [resolve, reject]`, + "resolve, reject" + )});`, + "promises.push(installedChunkData[2] = promise);", + "", + "// start chunk loading", + `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, + "// create error before stack unwound to get useful stacktrace later", + "var error = new Error();", + `var loadingEnded = ${runtimeTemplate.basicFunction( + "event", + [ + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`, + Template.indent([ + "installedChunkData = installedChunks[chunkId];", + "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;", + "if(installedChunkData) {", + Template.indent([ + "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", + "var realSrc = event && event.target && event.target.src;", + "error.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realSrc;", + "installedChunkData[1](error);" + ]), + "}" + ]), + "}" + ] + )};`, + `${RuntimeGlobals.loadScript}(url, loadingEnded, "chunk-" + chunkId, chunkId);` + ]), + "} else installedChunks[chunkId] = 0;" + ]), + "}" + ]), + "}" + ]) + : Template.indent(["installedChunks[chunkId] = 0;"]) + )};` + ]) + : "// no chunk on demand loading", + "", + withPrefetch && hasJsMatcher !== false + ? `${ + RuntimeGlobals.prefetchChunkHandlers + }.j = ${runtimeTemplate.basicFunction("chunkId", [ + `if((!${ + RuntimeGlobals.hasOwnProperty + }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ + hasJsMatcher === true ? "true" : hasJsMatcher("chunkId") + }) {`, + Template.indent([ + "installedChunks[chunkId] = null;", + linkPrefetch.call( + Template.asString([ + "var link = document.createElement('link');", + crossOriginLoading + ? `link.crossOrigin = ${JSON.stringify( + crossOriginLoading + )};` + : "", + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + 'link.rel = "prefetch";', + 'link.as = "script";', + `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);` + ]), + chunk + ), + "document.head.appendChild(link);" + ]), + "}" + ])};` + : "// no prefetching", + "", + withPreload && hasJsMatcher !== false + ? `${ + RuntimeGlobals.preloadChunkHandlers + }.j = ${runtimeTemplate.basicFunction("chunkId", [ + `if((!${ + RuntimeGlobals.hasOwnProperty + }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ + hasJsMatcher === true ? "true" : hasJsMatcher("chunkId") + }) {`, + Template.indent([ + "installedChunks[chunkId] = null;", + linkPreload.call( + Template.asString([ + "var link = document.createElement('link');", + scriptType + ? `link.type = ${JSON.stringify(scriptType)};` + : "", + "link.charset = 'utf-8';", + `if (${RuntimeGlobals.scriptNonce}) {`, + Template.indent( + `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` + ), + "}", + 'link.rel = "preload";', + 'link.as = "script";', + `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, + crossOriginLoading + ? Template.asString([ + "if (link.href.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `link.crossOrigin = ${JSON.stringify( + crossOriginLoading + )};` + ), + "}" + ]) + : "" + ]), + chunk + ), + "document.head.appendChild(link);" + ]), + "}" + ])};` + : "// no preloaded", + "", + withHmr + ? Template.asString([ + "var currentUpdatedModulesList;", + "var waitingUpdateResolves = {};", + "function loadUpdateChunk(chunkId) {", + Template.indent([ + `return new Promise(${runtimeTemplate.basicFunction( + "resolve, reject", + [ + "waitingUpdateResolves[chunkId] = resolve;", + "// start update chunk loading", + `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`, + "// create error before stack unwound to get useful stacktrace later", + "var error = new Error();", + `var loadingEnded = ${runtimeTemplate.basicFunction("event", [ + "if(waitingUpdateResolves[chunkId]) {", + Template.indent([ + "waitingUpdateResolves[chunkId] = undefined", + "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", + "var realSrc = event && event.target && event.target.src;", + "error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realSrc;", + "reject(error);" + ]), + "}" + ])};`, + `${RuntimeGlobals.loadScript}(url, loadingEnded);` + ] + )});` + ]), + "}", + "", + `${globalObject}[${JSON.stringify( + hotUpdateGlobal + )}] = ${runtimeTemplate.basicFunction( + "chunkId, moreModules, runtime", + [ + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent([ + "currentUpdate[moduleId] = moreModules[moduleId];", + "if(currentUpdatedModulesList) currentUpdatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "if(runtime) currentUpdateRuntime.push(runtime);", + "if(waitingUpdateResolves[chunkId]) {", + Template.indent([ + "waitingUpdateResolves[chunkId]();", + "waitingUpdateResolves[chunkId] = undefined;" + ]), + "}" + ] + )};`, + "", + Template.getFunctionContent( + require('./JavascriptHotModuleReplacement.runtime.js') + ) + .replace(/\$key\$/g, "jsonp") + .replace(/\$installedChunks\$/g, "installedChunks") + .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") + .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) + .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) + .replace( + /\$ensureChunkHandlers\$/g, + RuntimeGlobals.ensureChunkHandlers + ) + .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) + .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) + .replace( + /\$hmrDownloadUpdateHandlers\$/g, + RuntimeGlobals.hmrDownloadUpdateHandlers + ) + .replace( + /\$hmrInvalidateModuleHandlers\$/g, + RuntimeGlobals.hmrInvalidateModuleHandlers + ) + ]) + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${ + RuntimeGlobals.hmrDownloadManifest + } = ${runtimeTemplate.basicFunction("", [ + 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");', + `return fetch(${RuntimeGlobals.publicPath} + ${ + RuntimeGlobals.getUpdateManifestFilename + }()).then(${runtimeTemplate.basicFunction("response", [ + "if(response.status === 404) return; // no update available", + 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);', + "return response.json();" + ])});` + ])};` + ]) + : "// no HMR manifest", + "", + withOnChunkLoad + ? `${ + RuntimeGlobals.onChunksLoaded + }.j = ${runtimeTemplate.returningFunction( + "installedChunks[chunkId] === 0", + "chunkId" + )};` + : "// no on chunks loaded", + "", + withCallback || withLoading + ? Template.asString([ + "// install a JSONP callback for chunk loading", + `var webpackJsonpCallback = ${runtimeTemplate.basicFunction( + "parentChunkLoadingFunction, data", + [ + runtimeTemplate.destructureArray( + ["chunkIds", "moreModules", "runtime"], + "data" + ), + '// add "moreModules" to the modules object,', + '// then flag all "chunkIds" as loaded and fire callback', + "var moduleId, chunkId, i = 0;", + `if(chunkIds.some(${runtimeTemplate.returningFunction( + "installedChunks[id] !== 0", + "id" + )})) {`, + Template.indent([ + "for(moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent( + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ), + "}" + ]), + "}", + "if(runtime) var result = runtime(__webpack_require__);" + ]), + "}", + "if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);", + "for(;i < chunkIds.length; i++) {", + Template.indent([ + "chunkId = chunkIds[i];", + `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`, + Template.indent("installedChunks[chunkId][0]();"), + "}", + "installedChunks[chunkId] = 0;" + ]), + "}", + withOnChunkLoad + ? `return ${RuntimeGlobals.onChunksLoaded}(result);` + : "" + ] + )}`, + "", + `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, + "chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));", + "chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));" + ]) + : "// no jsonp function" + ]); } +} - // TODO further optimize regexp, i. e. - // use ranges: (1|2|3|4|a) => [1-4a] - const conditional = finishedItems.concat(Array.from(items, quoteMeta)); - if (conditional.length === 1) return conditional[0]; - return `(${conditional.join("|")})`; -}; - -compileBooleanMatcher.fromLists = compileBooleanMatcherFromLists; -compileBooleanMatcher.itemsToRegexp = itemsToRegexp; -module.exports = compileBooleanMatcher; +module.exports = JsonpChunkLoadingRuntimeModule; /***/ }), -/***/ 32540: +/***/ 4607: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -132001,32 +132572,42 @@ module.exports = compileBooleanMatcher; -const memoize = __webpack_require__(78676); +const ArrayPushCallbackChunkFormatPlugin = __webpack_require__(18535); +const EnableChunkLoadingPlugin = __webpack_require__(61291); +const JsonpChunkLoadingRuntimeModule = __webpack_require__(84154); -const getValidate = memoize(() => (__webpack_require__(38476).validate)); +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../Compiler")} Compiler */ -const createSchemaValidation = (check, getSchema, options) => { - getSchema = memoize(getSchema); - return value => { - if (check && !check(value)) { - getValidate()(getSchema(), value, options); - if (check) { - (__webpack_require__(73837).deprecate)( - () => {}, - "webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.", - "DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID" - )(); - } - } - }; -}; +class JsonpTemplatePlugin { + /** + * @deprecated use JsonpChunkLoadingRuntimeModule.getCompilationHooks instead + * @param {Compilation} compilation the compilation + * @returns {JsonpChunkLoadingRuntimeModule.JsonpCompilationPluginHooks} hooks + */ + static getCompilationHooks(compilation) { + return JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation); + } -module.exports = createSchemaValidation; + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.options.output.chunkLoading = "jsonp"; + new ArrayPushCallbackChunkFormatPlugin().apply(compiler); + new EnableChunkLoadingPlugin("jsonp").apply(compiler); + } +} + +module.exports = JsonpTemplatePlugin; /***/ }), -/***/ 49835: +/***/ 36243: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -132037,176 +132618,176 @@ module.exports = createSchemaValidation; -const Hash = __webpack_require__(36692); +const util = __webpack_require__(73837); +const webpackOptionsSchemaCheck = __webpack_require__(10382); +const webpackOptionsSchema = __webpack_require__(73342); +const Compiler = __webpack_require__(70845); +const MultiCompiler = __webpack_require__(33370); +const WebpackOptionsApply = __webpack_require__(88422); +const { + applyWebpackOptionsDefaults, + applyWebpackOptionsBaseDefaults +} = __webpack_require__(92988); +const { getNormalizedWebpackOptions } = __webpack_require__(26693); +const NodeEnvironmentPlugin = __webpack_require__(7553); +const memoize = __webpack_require__(78676); -const BULK_SIZE = 2000; +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("./Compiler").WatchOptions} WatchOptions */ +/** @typedef {import("./MultiCompiler").MultiCompilerOptions} MultiCompilerOptions */ +/** @typedef {import("./MultiStats")} MultiStats */ +/** @typedef {import("./Stats")} Stats */ -// We are using an object instead of a Map as this will stay static during the runtime -// so access to it can be optimized by v8 -const digestCaches = {}; +const getValidateSchema = memoize(() => __webpack_require__(12047)); -class BulkUpdateDecorator extends Hash { - /** - * @param {Hash | function(): Hash} hashOrFactory function to create a hash - * @param {string=} hashKey key for caching - */ - constructor(hashOrFactory, hashKey) { - super(); - this.hashKey = hashKey; - if (typeof hashOrFactory === "function") { - this.hashFactory = hashOrFactory; - this.hash = undefined; - } else { - this.hashFactory = undefined; - this.hash = hashOrFactory; - } - this.buffer = ""; - } +/** + * @template T + * @callback Callback + * @param {Error=} err + * @param {T=} stats + * @returns {void} + */ - /** - * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} - * @param {string|Buffer} data data - * @param {string=} inputEncoding data encoding - * @returns {this} updated hash - */ - update(data, inputEncoding) { - if ( - inputEncoding !== undefined || - typeof data !== "string" || - data.length > BULK_SIZE - ) { - if (this.hash === undefined) this.hash = this.hashFactory(); - if (this.buffer.length > 0) { - this.hash.update(this.buffer); - this.buffer = ""; - } - this.hash.update(data, inputEncoding); - } else { - this.buffer += data; - if (this.buffer.length > BULK_SIZE) { - if (this.hash === undefined) this.hash = this.hashFactory(); - this.hash.update(this.buffer); - this.buffer = ""; - } +/** + * @param {ReadonlyArray} childOptions options array + * @param {MultiCompilerOptions} options options + * @returns {MultiCompiler} a multi-compiler + */ +const createMultiCompiler = (childOptions, options) => { + const compilers = childOptions.map(options => createCompiler(options)); + const compiler = new MultiCompiler(compilers, options); + for (const childCompiler of compilers) { + if (childCompiler.options.dependencies) { + compiler.setDependencies( + childCompiler, + childCompiler.options.dependencies + ); } - return this; } + return compiler; +}; - /** - * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} - * @param {string=} encoding encoding of the return value - * @returns {string|Buffer} digest - */ - digest(encoding) { - let digestCache; - const buffer = this.buffer; - if (this.hash === undefined) { - // short data for hash, we can use caching - const cacheKey = `${this.hashKey}-${encoding}`; - digestCache = digestCaches[cacheKey]; - if (digestCache === undefined) { - digestCache = digestCaches[cacheKey] = new Map(); +/** + * @param {WebpackOptions} rawOptions options object + * @returns {Compiler} a compiler + */ +const createCompiler = rawOptions => { + const options = getNormalizedWebpackOptions(rawOptions); + applyWebpackOptionsBaseDefaults(options); + const compiler = new Compiler(options.context, options); + new NodeEnvironmentPlugin({ + infrastructureLogging: options.infrastructureLogging + }).apply(compiler); + if (Array.isArray(options.plugins)) { + for (const plugin of options.plugins) { + if (typeof plugin === "function") { + plugin.call(compiler, compiler); + } else { + plugin.apply(compiler); } - const cacheEntry = digestCache.get(buffer); - if (cacheEntry !== undefined) return cacheEntry; - this.hash = this.hashFactory(); - } - if (buffer.length > 0) { - this.hash.update(buffer); - } - const digestResult = this.hash.digest(encoding); - const result = - typeof digestResult === "string" ? digestResult : digestResult.toString(); - if (digestCache !== undefined) { - digestCache.set(buffer, result); } - return result; } -} + applyWebpackOptionsDefaults(options); + compiler.hooks.environment.call(); + compiler.hooks.afterEnvironment.call(); + new WebpackOptionsApply().process(options, compiler); + compiler.hooks.initialize.call(); + return compiler; +}; -/* istanbul ignore next */ -class DebugHash extends Hash { - constructor() { - super(); - this.string = ""; - } +/** + * @callback WebpackFunctionSingle + * @param {WebpackOptions} options options object + * @param {Callback=} callback callback + * @returns {Compiler} the compiler object + */ - /** - * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} - * @param {string|Buffer} data data - * @param {string=} inputEncoding data encoding - * @returns {this} updated hash - */ - update(data, inputEncoding) { - if (typeof data !== "string") data = data.toString("utf-8"); - if (data.startsWith("debug-digest-")) { - data = Buffer.from(data.slice("debug-digest-".length), "hex").toString(); - } - this.string += `[${data}](${new Error().stack.split("\n", 3)[2]})\n`; - return this; - } +/** + * @callback WebpackFunctionMulti + * @param {ReadonlyArray & MultiCompilerOptions} options options objects + * @param {Callback=} callback callback + * @returns {MultiCompiler} the multi compiler object + */ + +const asArray = options => + Array.isArray(options) ? Array.from(options) : [options]; +const webpack = /** @type {WebpackFunctionSingle & WebpackFunctionMulti} */ ( /** - * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} - * @param {string=} encoding encoding of the return value - * @returns {string|Buffer} digest + * @param {WebpackOptions | (ReadonlyArray & MultiCompilerOptions)} options options + * @param {Callback & Callback=} callback callback + * @returns {Compiler | MultiCompiler} */ - digest(encoding) { - return "debug-digest-" + Buffer.from(this.string).toString("hex"); - } -} - -let crypto = undefined; -let createXXHash64 = undefined; -let createMd4 = undefined; -let BatchedHash = undefined; - -/** - * Creates a hash by name or function - * @param {string | typeof Hash} algorithm the algorithm name or a constructor creating a hash - * @returns {Hash} the hash - */ -module.exports = algorithm => { - if (typeof algorithm === "function") { - return new BulkUpdateDecorator(() => new algorithm()); - } - switch (algorithm) { - // TODO add non-cryptographic algorithm here - case "debug": - return new DebugHash(); - case "xxhash64": - if (createXXHash64 === undefined) { - createXXHash64 = __webpack_require__(35028); - if (BatchedHash === undefined) { - BatchedHash = __webpack_require__(59461); - } + (options, callback) => { + const create = () => { + if (!asArray(options).every(webpackOptionsSchemaCheck)) { + getValidateSchema()(webpackOptionsSchema, options); + util.deprecate( + () => {}, + "webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.", + "DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID" + )(); } - return new BatchedHash(createXXHash64()); - case "md4": - if (createMd4 === undefined) { - createMd4 = __webpack_require__(86884); - if (BatchedHash === undefined) { - BatchedHash = __webpack_require__(59461); + /** @type {MultiCompiler|Compiler} */ + let compiler; + let watch = false; + /** @type {WatchOptions|WatchOptions[]} */ + let watchOptions; + if (Array.isArray(options)) { + /** @type {MultiCompiler} */ + compiler = createMultiCompiler( + options, + /** @type {MultiCompilerOptions} */ (options) + ); + watch = options.some(options => options.watch); + watchOptions = options.map(options => options.watchOptions || {}); + } else { + const webpackOptions = /** @type {WebpackOptions} */ (options); + /** @type {Compiler} */ + compiler = createCompiler(webpackOptions); + watch = webpackOptions.watch; + watchOptions = webpackOptions.watchOptions || {}; + } + return { compiler, watch, watchOptions }; + }; + if (callback) { + try { + const { compiler, watch, watchOptions } = create(); + if (watch) { + compiler.watch(watchOptions, callback); + } else { + compiler.run((err, stats) => { + compiler.close(err2 => { + callback(err || err2, stats); + }); + }); } + return compiler; + } catch (err) { + process.nextTick(() => callback(err)); + return null; } - return new BatchedHash(createMd4()); - case "native-md4": - if (crypto === undefined) crypto = __webpack_require__(6113); - return new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4"); - default: - if (crypto === undefined) crypto = __webpack_require__(6113); - return new BulkUpdateDecorator( - () => crypto.createHash(algorithm), - algorithm - ); + } else { + const { compiler, watch } = create(); + if (watch) { + util.deprecate( + () => {}, + "A 'callback' argument needs to be provided to the 'webpack(options, callback)' function when the 'watch' option is set. There is no way to handle the 'watch' option without a callback.", + "DEP_WEBPACK_WATCH_WITHOUT_CALLBACK" + )(); + } + return compiler; + } } -}; +); + +module.exports = webpack; /***/ }), -/***/ 64518: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 54182: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -132216,1392 +132797,766 @@ module.exports = algorithm => { -const util = __webpack_require__(73837); - -/** @type {Map} */ -const deprecationCache = new Map(); - -/** - * @typedef {Object} FakeHookMarker - * @property {true} _fakeHook it's a fake hook - */ - -/** @template T @typedef {T & FakeHookMarker} FakeHook */ - -/** - * @param {string} message deprecation message - * @param {string} code deprecation code - * @returns {Function} function to trigger deprecation - */ -const createDeprecation = (message, code) => { - const cached = deprecationCache.get(message); - if (cached !== undefined) return cached; - const fn = util.deprecate( - () => {}, - message, - "DEP_WEBPACK_DEPRECATION_" + code - ); - deprecationCache.set(message, fn); - return fn; -}; - -const COPY_METHODS = [ - "concat", - "entry", - "filter", - "find", - "findIndex", - "includes", - "indexOf", - "join", - "lastIndexOf", - "map", - "reduce", - "reduceRight", - "slice", - "some" -]; +const RuntimeGlobals = __webpack_require__(16475); +const StartupChunkDependenciesPlugin = __webpack_require__(22339); +const ImportScriptsChunkLoadingRuntimeModule = __webpack_require__(96952); -const DISABLED_METHODS = [ - "copyWithin", - "entries", - "fill", - "keys", - "pop", - "reverse", - "shift", - "splice", - "sort", - "unshift" -]; +/** @typedef {import("../Compiler")} Compiler */ -/** - * @param {any} set new set - * @param {string} name property name - * @returns {void} - */ -exports.arrayToSetDeprecation = (set, name) => { - for (const method of COPY_METHODS) { - if (set[method]) continue; - const d = createDeprecation( - `${name} was changed from Array to Set (using Array method '${method}' is deprecated)`, - "ARRAY_TO_SET" - ); - /** - * @deprecated - * @this {Set} - * @returns {number} count - */ - set[method] = function () { - d(); - const array = Array.from(this); - return Array.prototype[method].apply(array, arguments); - }; - } - const dPush = createDeprecation( - `${name} was changed from Array to Set (using Array method 'push' is deprecated)`, - "ARRAY_TO_SET_PUSH" - ); - const dLength = createDeprecation( - `${name} was changed from Array to Set (using Array property 'length' is deprecated)`, - "ARRAY_TO_SET_LENGTH" - ); - const dIndexer = createDeprecation( - `${name} was changed from Array to Set (indexing Array is deprecated)`, - "ARRAY_TO_SET_INDEXER" - ); +class ImportScriptsChunkLoadingPlugin { /** - * @deprecated - * @this {Set} - * @returns {number} count + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - set.push = function () { - dPush(); - for (const item of Array.from(arguments)) { - this.add(item); - } - return this.size; - }; - for (const method of DISABLED_METHODS) { - if (set[method]) continue; - set[method] = () => { - throw new Error( - `${name} was changed from Array to Set (using Array method '${method}' is not possible)` - ); - }; - } - const createIndexGetter = index => { - /** - * @this {Set} a Set - * @returns {any} the value at this location - */ - const fn = function () { - dIndexer(); - let i = 0; - for (const item of this) { - if (i++ === index) return item; - } - return undefined; - }; - return fn; - }; - const defineIndexGetter = index => { - Object.defineProperty(set, index, { - get: createIndexGetter(index), - set(value) { - throw new Error( - `${name} was changed from Array to Set (indexing Array with write is not possible)` - ); - } - }); - }; - defineIndexGetter(0); - let indexerDefined = 1; - Object.defineProperty(set, "length", { - get() { - dLength(); - const length = this.size; - for (indexerDefined; indexerDefined < length + 1; indexerDefined++) { - defineIndexGetter(indexerDefined); - } - return length; - }, - set(value) { - throw new Error( - `${name} was changed from Array to Set (writing to Array property 'length' is not possible)` - ); - } - }); - set[Symbol.isConcatSpreadable] = true; -}; + apply(compiler) { + new StartupChunkDependenciesPlugin({ + chunkLoading: "import-scripts", + asyncChunkLoading: true + }).apply(compiler); + compiler.hooks.thisCompilation.tap( + "ImportScriptsChunkLoadingPlugin", + compilation => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + const isEnabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === "import-scripts"; + }; + const onceForChunkSet = new WeakSet(); + const handler = (chunk, set) => { + if (onceForChunkSet.has(chunk)) return; + onceForChunkSet.add(chunk); + if (!isEnabledForChunk(chunk)) return; + const withCreateScriptUrl = !!compilation.outputOptions.trustedTypes; + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + set.add(RuntimeGlobals.hasOwnProperty); + if (withCreateScriptUrl) { + set.add(RuntimeGlobals.createScriptUrl); + } + compilation.addRuntimeModule( + chunk, + new ImportScriptsChunkLoadingRuntimeModule(set, withCreateScriptUrl) + ); + }; + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("ImportScriptsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap("ImportScriptsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap("ImportScriptsChunkLoadingPlugin", handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap("ImportScriptsChunkLoadingPlugin", handler); -exports.createArrayToSetDeprecationSet = name => { - let initialized = false; - class SetDeprecatedArray extends Set { - constructor(items) { - super(items); - if (!initialized) { - initialized = true; - exports.arrayToSetDeprecation(SetDeprecatedArray.prototype, name); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap("ImportScriptsChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getChunkScriptFilename); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap("ImportScriptsChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getChunkUpdateScriptFilename); + set.add(RuntimeGlobals.moduleCache); + set.add(RuntimeGlobals.hmrModuleData); + set.add(RuntimeGlobals.moduleFactoriesAddOnly); + }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadManifest) + .tap("ImportScriptsChunkLoadingPlugin", (chunk, set) => { + if (!isEnabledForChunk(chunk)) return; + set.add(RuntimeGlobals.publicPath); + set.add(RuntimeGlobals.getUpdateManifestFilename); + }); } - } - } - return SetDeprecatedArray; -}; - -exports.soonFrozenObjectDeprecation = (obj, name, code, note = "") => { - const message = `${name} will be frozen in future, all modifications are deprecated.${ - note && `\n${note}` - }`; - return new Proxy(obj, { - set: util.deprecate( - (target, property, value, receiver) => - Reflect.set(target, property, value, receiver), - message, - code - ), - defineProperty: util.deprecate( - (target, property, descriptor) => - Reflect.defineProperty(target, property, descriptor), - message, - code - ), - deleteProperty: util.deprecate( - (target, property) => Reflect.deleteProperty(target, property), - message, - code - ), - setPrototypeOf: util.deprecate( - (target, proto) => Reflect.setPrototypeOf(target, proto), - message, - code - ) - }); -}; - -/** - * @template T - * @param {T} obj object - * @param {string} message deprecation message - * @param {string} code deprecation code - * @returns {T} object with property access deprecated - */ -const deprecateAllProperties = (obj, message, code) => { - const newObj = {}; - const descriptors = Object.getOwnPropertyDescriptors(obj); - for (const name of Object.keys(descriptors)) { - const descriptor = descriptors[name]; - if (typeof descriptor.value === "function") { - Object.defineProperty(newObj, name, { - ...descriptor, - value: util.deprecate(descriptor.value, message, code) - }); - } else if (descriptor.get || descriptor.set) { - Object.defineProperty(newObj, name, { - ...descriptor, - get: descriptor.get && util.deprecate(descriptor.get, message, code), - set: descriptor.set && util.deprecate(descriptor.set, message, code) - }); - } else { - let value = descriptor.value; - Object.defineProperty(newObj, name, { - configurable: descriptor.configurable, - enumerable: descriptor.enumerable, - get: util.deprecate(() => value, message, code), - set: descriptor.writable - ? util.deprecate(v => (value = v), message, code) - : undefined - }); - } - } - return /** @type {T} */ (newObj); -}; -exports.deprecateAllProperties = deprecateAllProperties; - -/** - * @template T - * @param {T} fakeHook fake hook implementation - * @param {string=} message deprecation message (not deprecated when unset) - * @param {string=} code deprecation code (not deprecated when unset) - * @returns {FakeHook} fake hook which redirects - */ -exports.createFakeHook = (fakeHook, message, code) => { - if (message && code) { - fakeHook = deprecateAllProperties(fakeHook, message, code); + ); } - return Object.freeze( - Object.assign(fakeHook, { _fakeHook: /** @type {true} */ (true) }) - ); -}; +} +module.exports = ImportScriptsChunkLoadingPlugin; /***/ }), -/***/ 59836: -/***/ (function(module) { +/***/ 96952: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra */ -// Simulations show these probabilities for a single change -// 93.1% that one group is invalidated -// 4.8% that two groups are invalidated -// 1.1% that 3 groups are invalidated -// 0.1% that 4 or more groups are invalidated -// -// And these for removing/adding 10 lexically adjacent files -// 64.5% that one group is invalidated -// 24.8% that two groups are invalidated -// 7.8% that 3 groups are invalidated -// 2.7% that 4 or more groups are invalidated -// -// And these for removing/adding 3 random files -// 0% that one group is invalidated -// 3.7% that two groups are invalidated -// 80.8% that 3 groups are invalidated -// 12.3% that 4 groups are invalidated -// 3.2% that 5 or more groups are invalidated +const RuntimeGlobals = __webpack_require__(16475); +const RuntimeModule = __webpack_require__(16963); +const Template = __webpack_require__(1626); +const { + getChunkFilenameTemplate, + chunkHasJs +} = __webpack_require__(89464); +const { getInitialChunkIds } = __webpack_require__(98124); +const compileBooleanMatcher = __webpack_require__(29404); +const { getUndoPath } = __webpack_require__(82186); -/** - * - * @param {string} a key - * @param {string} b key - * @returns {number} the similarity as number - */ -const similarity = (a, b) => { - const l = Math.min(a.length, b.length); - let dist = 0; - for (let i = 0; i < l; i++) { - const ca = a.charCodeAt(i); - const cb = b.charCodeAt(i); - dist += Math.max(0, 10 - Math.abs(ca - cb)); +class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { + constructor(runtimeRequirements, withCreateScriptUrl) { + super("importScripts chunk loading", RuntimeModule.STAGE_ATTACH); + this.runtimeRequirements = runtimeRequirements; + this._withCreateScriptUrl = withCreateScriptUrl; } - return dist; -}; -/** - * @param {string} a key - * @param {string} b key - * @param {Set} usedNames set of already used names - * @returns {string} the common part and a single char for the difference - */ -const getName = (a, b, usedNames) => { - const l = Math.min(a.length, b.length); - let i = 0; - while (i < l) { - if (a.charCodeAt(i) !== b.charCodeAt(i)) { - i++; - break; - } - i++; - } - while (i < l) { - const name = a.slice(0, i); - const lowerName = name.toLowerCase(); - if (!usedNames.has(lowerName)) { - usedNames.add(lowerName); - return name; - } - i++; + /** + * @returns {string} runtime code + */ + generate() { + const { + chunk, + chunkGraph, + compilation: { + runtimeTemplate, + outputOptions: { chunkLoadingGlobal, hotUpdateGlobal } + }, + _withCreateScriptUrl: withCreateScriptUrl + } = this; + const globalObject = runtimeTemplate.globalObject; + const fn = RuntimeGlobals.ensureChunkHandlers; + const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); + const withLoading = this.runtimeRequirements.has( + RuntimeGlobals.ensureChunkHandlers + ); + const withHmr = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); + const withHmrManifest = this.runtimeRequirements.has( + RuntimeGlobals.hmrDownloadManifest + ); + const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( + chunkLoadingGlobal + )}]`; + const hasJsMatcher = compileBooleanMatcher( + chunkGraph.getChunkConditionMap(chunk, chunkHasJs) + ); + const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + + const outputName = this.compilation.getPath( + getChunkFilenameTemplate(chunk, this.compilation.outputOptions), + { + chunk, + contentHashType: "javascript" + } + ); + const rootOutputDir = getUndoPath( + outputName, + this.compilation.outputOptions.path, + false + ); + + const stateExpression = withHmr + ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_importScripts` + : undefined; + + return Template.asString([ + withBaseURI + ? Template.asString([ + `${RuntimeGlobals.baseURI} = self.location + ${JSON.stringify( + rootOutputDir ? "/../" + rootOutputDir : "" + )};` + ]) + : "// no baseURI", + "", + "// object to store loaded chunks", + '// "1" means "already loaded"', + `var installedChunks = ${ + stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" + }{`, + Template.indent( + Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 1`).join( + ",\n" + ) + ), + "};", + "", + withLoading + ? Template.asString([ + "// importScripts chunk loading", + `var installChunk = ${runtimeTemplate.basicFunction("data", [ + runtimeTemplate.destructureArray( + ["chunkIds", "moreModules", "runtime"], + "data" + ), + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent( + `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` + ), + "}" + ]), + "}", + "if(runtime) runtime(__webpack_require__);", + "while(chunkIds.length)", + Template.indent("installedChunks[chunkIds.pop()] = 1;"), + "parentChunkLoadingFunction(data);" + ])};` + ]) + : "// no chunk install function needed", + withLoading + ? Template.asString([ + `${fn}.i = ${runtimeTemplate.basicFunction( + "chunkId, promises", + hasJsMatcher !== false + ? [ + '// "1" is the signal for "already loaded"', + "if(!installedChunks[chunkId]) {", + Template.indent([ + hasJsMatcher === true + ? "if(true) { // all chunks have JS" + : `if(${hasJsMatcher("chunkId")}) {`, + Template.indent( + `importScripts(${ + withCreateScriptUrl + ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId))` + : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId)` + });` + ), + "}" + ]), + "}" + ] + : "installedChunks[chunkId] = 1;" + )};`, + "", + `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, + "var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);", + "chunkLoadingGlobal.push = installChunk;" + ]) + : "// no chunk loading", + "", + withHmr + ? Template.asString([ + "function loadUpdateChunk(chunkId, updatedModulesList) {", + Template.indent([ + "var success = false;", + `${globalObject}[${JSON.stringify( + hotUpdateGlobal + )}] = ${runtimeTemplate.basicFunction("_, moreModules, runtime", [ + "for(var moduleId in moreModules) {", + Template.indent([ + `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, + Template.indent([ + "currentUpdate[moduleId] = moreModules[moduleId];", + "if(updatedModulesList) updatedModulesList.push(moduleId);" + ]), + "}" + ]), + "}", + "if(runtime) currentUpdateRuntime.push(runtime);", + "success = true;" + ])};`, + "// start update chunk loading", + `importScripts(${ + withCreateScriptUrl + ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId))` + : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)` + });`, + 'if(!success) throw new Error("Loading update chunk failed for unknown reason");' + ]), + "}", + "", + Template.getFunctionContent( + require('./JavascriptHotModuleReplacement.runtime.js') + ) + .replace(/\$key\$/g, "importScrips") + .replace(/\$installedChunks\$/g, "installedChunks") + .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") + .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) + .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) + .replace( + /\$ensureChunkHandlers\$/g, + RuntimeGlobals.ensureChunkHandlers + ) + .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) + .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) + .replace( + /\$hmrDownloadUpdateHandlers\$/g, + RuntimeGlobals.hmrDownloadUpdateHandlers + ) + .replace( + /\$hmrInvalidateModuleHandlers\$/g, + RuntimeGlobals.hmrInvalidateModuleHandlers + ) + ]) + : "// no HMR", + "", + withHmrManifest + ? Template.asString([ + `${ + RuntimeGlobals.hmrDownloadManifest + } = ${runtimeTemplate.basicFunction("", [ + 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");', + `return fetch(${RuntimeGlobals.publicPath} + ${ + RuntimeGlobals.getUpdateManifestFilename + }()).then(${runtimeTemplate.basicFunction("response", [ + "if(response.status === 404) return; // no update available", + 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);', + "return response.json();" + ])});` + ])};` + ]) + : "// no HMR manifest" + ]); } - // names always contain a hash, so this is always unique - // we don't need to check usedNames nor add it - return a; -}; +} -/** - * @param {Record} total total size - * @param {Record} size single size - * @returns {void} - */ -const addSizeTo = (total, size) => { - for (const key of Object.keys(size)) { - total[key] = (total[key] || 0) + size[key]; - } -}; +module.exports = ImportScriptsChunkLoadingRuntimeModule; -/** - * @param {Record} total total size - * @param {Record} size single size - * @returns {void} - */ -const subtractSizeFrom = (total, size) => { - for (const key of Object.keys(size)) { - total[key] -= size[key]; - } -}; -/** - * @param {Iterable} nodes some nodes - * @returns {Record} total size - */ -const sumSize = nodes => { - const sum = Object.create(null); - for (const node of nodes) { - addSizeTo(sum, node.size); - } - return sum; -}; +/***/ }), -const isTooBig = (size, maxSize) => { - for (const key of Object.keys(size)) { - const s = size[key]; - if (s === 0) continue; - const maxSizeValue = maxSize[key]; - if (typeof maxSizeValue === "number") { - if (s > maxSizeValue) return true; - } - } - return false; -}; +/***/ 68693: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const isTooSmall = (size, minSize) => { - for (const key of Object.keys(size)) { - const s = size[key]; - if (s === 0) continue; - const minSizeValue = minSize[key]; - if (typeof minSizeValue === "number") { - if (s < minSizeValue) return true; - } - } - return false; -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -const getTooSmallTypes = (size, minSize) => { - const types = new Set(); - for (const key of Object.keys(size)) { - const s = size[key]; - if (s === 0) continue; - const minSizeValue = minSize[key]; - if (typeof minSizeValue === "number") { - if (s < minSizeValue) types.add(key); - } - } - return types; -}; -const getNumberOfMatchingSizeTypes = (size, types) => { - let i = 0; - for (const key of Object.keys(size)) { - if (size[key] !== 0 && types.has(key)) i++; - } - return i; -}; -const selectiveSizeSum = (size, types) => { - let sum = 0; - for (const key of Object.keys(size)) { - if (size[key] !== 0 && types.has(key)) sum += size[key]; - } - return sum; -}; +const ArrayPushCallbackChunkFormatPlugin = __webpack_require__(18535); +const EnableChunkLoadingPlugin = __webpack_require__(61291); -/** - * @template T - */ -class Node { +/** @typedef {import("../Compiler")} Compiler */ + +class WebWorkerTemplatePlugin { /** - * @param {T} item item - * @param {string} key key - * @param {Record} size size + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} */ - constructor(item, key, size) { - this.item = item; - this.key = key; - this.size = size; + apply(compiler) { + compiler.options.output.chunkLoading = "import-scripts"; + new ArrayPushCallbackChunkFormatPlugin().apply(compiler); + new EnableChunkLoadingPlugin("import-scripts").apply(compiler); } } +module.exports = WebWorkerTemplatePlugin; -/** - * @template T - */ -class Group { - /** - * @param {Node[]} nodes nodes - * @param {number[]} similarities similarities between the nodes (length = nodes.length - 1) - * @param {Record=} size size of the group - */ - constructor(nodes, similarities, size) { - this.nodes = nodes; - this.similarities = similarities; - this.size = size || sumSize(nodes); - /** @type {string} */ - this.key = undefined; - } - /** - * @param {function(Node): boolean} filter filter function - * @returns {Node[]} removed nodes - */ - popNodes(filter) { - const newNodes = []; - const newSimilarities = []; - const resultNodes = []; - let lastNode; - for (let i = 0; i < this.nodes.length; i++) { - const node = this.nodes[i]; - if (filter(node)) { - resultNodes.push(node); - } else { - if (newNodes.length > 0) { - newSimilarities.push( - lastNode === this.nodes[i - 1] - ? this.similarities[i - 1] - : similarity(lastNode.key, node.key) - ); - } - newNodes.push(node); - lastNode = node; - } - } - if (resultNodes.length === this.nodes.length) return undefined; - this.nodes = newNodes; - this.similarities = newSimilarities; - this.size = sumSize(newNodes); - return resultNodes; - } -} +/***/ }), -/** - * @param {Iterable} nodes nodes - * @returns {number[]} similarities - */ -const getSimilarities = nodes => { - // calculate similarities between lexically adjacent nodes - /** @type {number[]} */ - const similarities = []; - let last = undefined; - for (const node of nodes) { - if (last !== undefined) { - similarities.push(similarity(last.key, node.key)); - } - last = node; - } - return similarities; -}; +/***/ 50283: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -/** - * @template T - * @typedef {Object} GroupedItems - * @property {string} key - * @property {T[]} items - * @property {Record} size - */ +"use strict"; -/** - * @template T - * @typedef {Object} Options - * @property {Record} maxSize maximum size of a group - * @property {Record} minSize minimum size of a group (preferred over maximum size) - * @property {Iterable} items a list of items - * @property {function(T): Record} getSize function to get size of an item - * @property {function(T): string} getKey function to get the key of an item - */ -/** - * @template T - * @param {Options} options options object - * @returns {GroupedItems[]} grouped items - */ -module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { - /** @type {Group[]} */ - const result = []; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.importAssertions = importAssertions; - const nodes = Array.from( - items, - item => new Node(item, getKey(item), getSize(item)) - ); +var _acorn = _interopRequireWildcard(__webpack_require__(31988)); - /** @type {Node[]} */ - const initialNodes = []; +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } - // lexically ordering of keys - nodes.sort((a, b) => { - if (a.key < b.key) return -1; - if (a.key > b.key) return 1; - return 0; - }); +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } - // return nodes bigger than maxSize directly as group - // But make sure that minSize is not violated - for (const node of nodes) { - if (isTooBig(node.size, maxSize) && !isTooSmall(node.size, minSize)) { - result.push(new Group([node], [])); - } else { - initialNodes.push(node); - } - } +const leftCurlyBrace = "{".charCodeAt(0); +const space = " ".charCodeAt(0); +const keyword = "assert"; +const FUNC_STATEMENT = 1, + FUNC_HANGING_STATEMENT = 2, + FUNC_NULLABLE_ID = 4; - if (initialNodes.length > 0) { - const initialGroup = new Group(initialNodes, getSimilarities(initialNodes)); +function importAssertions(Parser) { + // Use supplied version acorn version if present, to avoid + // reference mismatches due to different acorn versions. This + // allows this plugin to be used with Rollup which supplies + // its own internal version of acorn and thereby sidesteps + // the package manager. + const acorn = Parser.acorn || _acorn; + const { + tokTypes: tt, + TokenType + } = acorn; + return class extends Parser { + constructor(...args) { + super(...args); + this.assertToken = new TokenType(keyword); + } - const removeProblematicNodes = (group, consideredSize = group.size) => { - const problemTypes = getTooSmallTypes(consideredSize, minSize); - if (problemTypes.size > 0) { - // We hit an edge case where the working set is already smaller than minSize - // We merge problematic nodes with the smallest result node to keep minSize intact - const problemNodes = group.popNodes( - n => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0 - ); - if (problemNodes === undefined) return false; - // Only merge it with result nodes that have the problematic size type - const possibleResultGroups = result.filter( - n => getNumberOfMatchingSizeTypes(n.size, problemTypes) > 0 - ); - if (possibleResultGroups.length > 0) { - const bestGroup = possibleResultGroups.reduce((min, group) => { - const minMatches = getNumberOfMatchingSizeTypes(min, problemTypes); - const groupMatches = getNumberOfMatchingSizeTypes( - group, - problemTypes - ); - if (minMatches !== groupMatches) - return minMatches < groupMatches ? group : min; - if ( - selectiveSizeSum(min.size, problemTypes) > - selectiveSizeSum(group.size, problemTypes) - ) - return group; - return min; - }); - for (const node of problemNodes) bestGroup.nodes.push(node); - bestGroup.nodes.sort((a, b) => { - if (a.key < b.key) return -1; - if (a.key > b.key) return 1; - return 0; - }); - } else { - // There are no other nodes with the same size types - // We create a new group and have to accept that it's smaller than minSize - result.push(new Group(problemNodes, null)); - } - return true; - } else { - return false; - } - }; + _codeAt(i) { + return this.input.charCodeAt(i); + } - if (initialGroup.nodes.length > 0) { - const queue = [initialGroup]; + _eat(t) { + if (this.type !== t) { + this.unexpected(); + } - while (queue.length) { - const group = queue.pop(); - // only groups bigger than maxSize need to be splitted - if (!isTooBig(group.size, maxSize)) { - result.push(group); - continue; - } - // If the group is already too small - // we try to work only with the unproblematic nodes - if (removeProblematicNodes(group)) { - // This changed something, so we try this group again - queue.push(group); - continue; - } + this.next(); + } - // find unsplittable area from left and right - // going minSize from left and right - // at least one node need to be included otherwise we get stuck - let left = 1; - let leftSize = Object.create(null); - addSizeTo(leftSize, group.nodes[0].size); - while (left < group.nodes.length && isTooSmall(leftSize, minSize)) { - addSizeTo(leftSize, group.nodes[left].size); - left++; - } - let right = group.nodes.length - 2; - let rightSize = Object.create(null); - addSizeTo(rightSize, group.nodes[group.nodes.length - 1].size); - while (right >= 0 && isTooSmall(rightSize, minSize)) { - addSizeTo(rightSize, group.nodes[right].size); - right--; - } + readToken(code) { + let i = 0; - // left v v right - // [ O O O ] O O O [ O O O ] - // ^^^^^^^^^ leftSize - // rightSize ^^^^^^^^^ - // leftSize > minSize - // rightSize > minSize + for (; i < keyword.length; i++) { + if (this._codeAt(this.pos + i) !== keyword.charCodeAt(i)) { + return super.readToken(code); + } + } // ensure that the keyword is at the correct location + // ie `assert{...` or `assert {...` - // Perfect split: [ O O O ] [ O O O ] - // right === left - 1 - if (left - 1 > right) { - // We try to remove some problematic nodes to "fix" that - let prevSize; - if (right < group.nodes.length - left) { - subtractSizeFrom(rightSize, group.nodes[right + 1].size); - prevSize = rightSize; - } else { - subtractSizeFrom(leftSize, group.nodes[left - 1].size); - prevSize = leftSize; - } - if (removeProblematicNodes(group, prevSize)) { - // This changed something, so we try this group again - queue.push(group); - continue; - } - // can't split group while holding minSize - // because minSize is preferred of maxSize we return - // the problematic nodes as result here even while it's too big - // To avoid this make sure maxSize > minSize * 3 - result.push(group); - continue; - } - if (left <= right) { - // when there is a area between left and right - // we look for best split point - // we split at the minimum similarity - // here key space is separated the most - // But we also need to make sure to not create too small groups - let best = -1; - let bestSimilarity = Infinity; - let pos = left; - let rightSize = sumSize(group.nodes.slice(pos)); + for (;; i++) { + if (this._codeAt(this.pos + i) === leftCurlyBrace) { + // Found '{' + break; + } else if (this._codeAt(this.pos + i) === space) { + // white space is allowed between `assert` and `{`, so continue. + continue; + } else { + return super.readToken(code); + } + } // If we're inside a dynamic import expression we'll parse + // the `assert` keyword as a standard object property name + // ie `import(""./foo.json", { assert: { type: "json" } })` - // pos v v right - // [ O O O ] O O O [ O O O ] - // ^^^^^^^^^ leftSize - // rightSize ^^^^^^^^^^^^^^^ - while (pos <= right + 1) { - const similarity = group.similarities[pos - 1]; - if ( - similarity < bestSimilarity && - !isTooSmall(leftSize, minSize) && - !isTooSmall(rightSize, minSize) - ) { - best = pos; - bestSimilarity = similarity; - } - addSizeTo(leftSize, group.nodes[pos].size); - subtractSizeFrom(rightSize, group.nodes[pos].size); - pos++; - } - if (best < 0) { - // This can't happen - // but if that assumption is wrong - // fallback to a big group - result.push(group); - continue; - } - left = best; - right = best - 1; - } + if (this.type.label === "{") { + return super.readToken(code); + } - // create two new groups for left and right area - // and queue them up - const rightNodes = [group.nodes[right + 1]]; - /** @type {number[]} */ - const rightSimilarities = []; - for (let i = right + 2; i < group.nodes.length; i++) { - rightSimilarities.push(group.similarities[i - 1]); - rightNodes.push(group.nodes[i]); - } - queue.push(new Group(rightNodes, rightSimilarities)); + this.pos += keyword.length; + return this.finishToken(this.assertToken); + } - const leftNodes = [group.nodes[0]]; - /** @type {number[]} */ - const leftSimilarities = []; - for (let i = 1; i < left; i++) { - leftSimilarities.push(group.similarities[i - 1]); - leftNodes.push(group.nodes[i]); - } - queue.push(new Group(leftNodes, leftSimilarities)); - } - } - } + parseDynamicImport(node) { + this.next(); // skip `(` + // Parse node.source. - // lexically ordering - result.sort((a, b) => { - if (a.nodes[0].key < b.nodes[0].key) return -1; - if (a.nodes[0].key > b.nodes[0].key) return 1; - return 0; - }); + node.source = this.parseMaybeAssign(); - // give every group a name - const usedNames = new Set(); - for (let i = 0; i < result.length; i++) { - const group = result[i]; - if (group.nodes.length === 1) { - group.key = group.nodes[0].key; - } else { - const first = group.nodes[0]; - const last = group.nodes[group.nodes.length - 1]; - const name = getName(first.key, last.key, usedNames); - group.key = name; - } - } + if (this.eat(tt.comma)) { + const obj = this.parseObj(false); + node.arguments = [obj]; + } - // return the results - return result.map(group => { - /** @type {GroupedItems} */ - return { - key: group.key, - items: group.nodes.map(node => node.item), - size: group.size - }; - }); -}; + this._eat(tt.parenR); + return this.finishNode(node, "ImportExpression"); + } // ported from acorn/src/statement.js pp.parseExport -/***/ }), -/***/ 11850: -/***/ (function(module) { + parseExport(node, exports) { + this.next(); // export * from '...' -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sam Chen @chenxsan -*/ + if (this.eat(tt.star)) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseIdent(true); + this.checkExport(exports, node.exported.name, this.lastTokStart); + } else { + node.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== tt.string) { + this.unexpected(); + } -/** - * @param {string} urlAndGlobal the script request - * @returns {string[]} script url and its global variable - */ -module.exports = function extractUrlAndGlobal(urlAndGlobal) { - const index = urlAndGlobal.indexOf("@"); - if (index <= 0 || index === urlAndGlobal.length - 1) { - throw new Error(`Invalid request "${urlAndGlobal}"`); - } - return [urlAndGlobal.substring(index + 1), urlAndGlobal.substring(0, index)]; -}; + node.source = this.parseExprAtom(); + if (this.type === this.assertToken) { + this.next(); + const assertions = this.parseImportAssertions(); -/***/ }), + if (assertions) { + node.assertions = assertions; + } + } -/***/ 6261: -/***/ (function(module) { + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration"); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (this.eat(tt._default)) { + // export default ... + this.checkExport(exports, "default", this.lastTokStart); + var isAsync; + if (this.type === tt._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { + this.next(); + } -const NO_MARKER = 0; -const IN_PROGRESS_MARKER = 1; -const DONE_MARKER = 2; -const DONE_MAYBE_ROOT_CYCLE_MARKER = 3; -const DONE_AND_ROOT_MARKER = 4; + node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); + } else if (this.type === tt._class) { + var cNode = this.startNode(); + node.declaration = this.parseClass(cNode, "nullableID"); + } else { + node.declaration = this.parseMaybeAssign(); + this.semicolon(); + } -/** - * @template T - */ -class Node { - /** - * @param {T} item the value of the node - */ - constructor(item) { - this.item = item; - /** @type {Set>} */ - this.dependencies = new Set(); - this.marker = NO_MARKER; - /** @type {Cycle | undefined} */ - this.cycle = undefined; - this.incoming = 0; - } -} + return this.finishNode(node, "ExportDefaultDeclaration"); + } // export var|const|let|function|class ... -/** - * @template T - */ -class Cycle { - constructor() { - /** @type {Set>} */ - this.nodes = new Set(); - } -} -/** - * @template T - * @typedef {Object} StackEntry - * @property {Node} node - * @property {Node[]} openEdges - */ + if (this.shouldParseExportStatement()) { + node.declaration = this.parseStatement(null); -/** - * @template T - * @param {Iterable} items list of items - * @param {function(T): Iterable} getDependencies function to get dependencies of an item (items that are not in list are ignored) - * @returns {Iterable} graph roots of the items - */ -module.exports = (items, getDependencies) => { - /** @type {Map>} */ - const itemToNode = new Map(); - for (const item of items) { - const node = new Node(item); - itemToNode.set(item, node); - } + if (node.declaration.type === "VariableDeclaration") { + this.checkVariableExport(exports, node.declaration.declarations); + } else { + this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); + } - // early exit when there is only a single item - if (itemToNode.size <= 1) return items; + node.specifiers = []; + node.source = null; + } else { + // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); - // grab all the dependencies - for (const node of itemToNode.values()) { - for (const dep of getDependencies(node.item)) { - const depNode = itemToNode.get(dep); - if (depNode !== undefined) { - node.dependencies.add(depNode); - } - } - } + if (this.eatContextual("from")) { + if (this.type !== tt.string) { + this.unexpected(); + } - // Set of current root modules - // items will be removed if a new reference to it has been found - /** @type {Set>} */ - const roots = new Set(); + node.source = this.parseExprAtom(); - // Set of current cycles without references to it - // cycles will be removed if a new reference to it has been found - // that is not part of the cycle - /** @type {Set>} */ - const rootCycles = new Set(); + if (this.type === this.assertToken) { + this.next(); + const assertions = this.parseImportAssertions(); - // For all non-marked nodes - for (const selectedNode of itemToNode.values()) { - if (selectedNode.marker === NO_MARKER) { - // deep-walk all referenced modules - // in a non-recursive way + if (assertions) { + node.assertions = assertions; + } + } + } else { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) { + // check for keywords used as local names + var spec = list[i]; + this.checkUnreserved(spec.local); // check if export is defined - // start by entering the selected node - selectedNode.marker = IN_PROGRESS_MARKER; + this.checkLocalExport(spec.local); + } - // keep a stack to avoid recursive walk - /** @type {StackEntry[]} */ - const stack = [ - { - node: selectedNode, - openEdges: Array.from(selectedNode.dependencies) - } - ]; + node.source = null; + } - // process the top item until stack is empty - while (stack.length > 0) { - const topOfStack = stack[stack.length - 1]; + this.semicolon(); + } - // Are there still edges unprocessed in the current node? - if (topOfStack.openEdges.length > 0) { - // Process one dependency - const dependency = topOfStack.openEdges.pop(); - switch (dependency.marker) { - case NO_MARKER: - // dependency has not be visited yet - // mark it as in-progress and recurse - stack.push({ - node: dependency, - openEdges: Array.from(dependency.dependencies) - }); - dependency.marker = IN_PROGRESS_MARKER; - break; - case IN_PROGRESS_MARKER: { - // It's a in-progress cycle - let cycle = dependency.cycle; - if (!cycle) { - cycle = new Cycle(); - cycle.nodes.add(dependency); - dependency.cycle = cycle; - } - // set cycle property for each node in the cycle - // if nodes are already part of a cycle - // we merge the cycles to a shared cycle - for ( - let i = stack.length - 1; - stack[i].node !== dependency; - i-- - ) { - const node = stack[i].node; - if (node.cycle) { - if (node.cycle !== cycle) { - // merge cycles - for (const cycleNode of node.cycle.nodes) { - cycleNode.cycle = cycle; - cycle.nodes.add(cycleNode); - } - } - } else { - node.cycle = cycle; - cycle.nodes.add(node); - } - } - // don't recurse into dependencies - // these are already on the stack - break; - } - case DONE_AND_ROOT_MARKER: - // This node has be visited yet and is currently a root node - // But as this is a new reference to the node - // it's not really a root - // so we have to convert it to a normal node - dependency.marker = DONE_MARKER; - roots.delete(dependency); - break; - case DONE_MAYBE_ROOT_CYCLE_MARKER: - // This node has be visited yet and - // is maybe currently part of a completed root cycle - // we found a new reference to the cycle - // so it's not really a root cycle - // remove the cycle from the root cycles - // and convert it to a normal node - rootCycles.delete(dependency.cycle); - dependency.marker = DONE_MARKER; - break; - // DONE_MARKER: nothing to do, don't recurse into dependencies - } - } else { - // All dependencies of the current node has been visited - // we leave the node - stack.pop(); - topOfStack.node.marker = DONE_MARKER; - } - } - const cycle = selectedNode.cycle; - if (cycle) { - for (const node of cycle.nodes) { - node.marker = DONE_MAYBE_ROOT_CYCLE_MARKER; - } - rootCycles.add(cycle); - } else { - selectedNode.marker = DONE_AND_ROOT_MARKER; - roots.add(selectedNode); - } - } - } + return this.finishNode(node, "ExportNamedDeclaration"); + } - // Extract roots from root cycles - // We take the nodes with most incoming edges - // inside of the cycle - for (const cycle of rootCycles) { - let max = 0; - /** @type {Set>} */ - const cycleRoots = new Set(); - const nodes = cycle.nodes; - for (const node of nodes) { - for (const dep of node.dependencies) { - if (nodes.has(dep)) { - dep.incoming++; - if (dep.incoming < max) continue; - if (dep.incoming > max) { - cycleRoots.clear(); - max = dep.incoming; - } - cycleRoots.add(dep); - } - } - } - for (const cycleRoot of cycleRoots) { - roots.add(cycleRoot); - } - } + parseImport(node) { + this.next(); // import '...' - // When roots were found, return them - if (roots.size > 0) { - return Array.from(roots, r => r.item); - } else { - throw new Error("Implementation of findGraphRoots is broken"); - } -}; + if (this.type === tt.string) { + node.specifiers = []; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected(); + } + if (this.type === this.assertToken) { + this.next(); + const assertions = this.parseImportAssertions(); -/***/ }), + if (assertions) { + node.assertions = assertions; + } + } -/***/ 17139: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + parseImportAssertions() { + this._eat(tt.braceL); + const attrs = this.parseAssertEntries(); + this._eat(tt.braceR); -const path = __webpack_require__(71017); + return attrs; + } -/** @typedef {import("../../declarations/WebpackOptions").WatchOptions} WatchOptions */ -/** @typedef {import("../FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */ + parseAssertEntries() { + const attrs = []; + const attrNames = new Set(); -/** - * @typedef {Object} IStats - * @property {() => boolean} isFile - * @property {() => boolean} isDirectory - * @property {() => boolean} isBlockDevice - * @property {() => boolean} isCharacterDevice - * @property {() => boolean} isSymbolicLink - * @property {() => boolean} isFIFO - * @property {() => boolean} isSocket - * @property {number | bigint} dev - * @property {number | bigint} ino - * @property {number | bigint} mode - * @property {number | bigint} nlink - * @property {number | bigint} uid - * @property {number | bigint} gid - * @property {number | bigint} rdev - * @property {number | bigint} size - * @property {number | bigint} blksize - * @property {number | bigint} blocks - * @property {number | bigint} atimeMs - * @property {number | bigint} mtimeMs - * @property {number | bigint} ctimeMs - * @property {number | bigint} birthtimeMs - * @property {Date} atime - * @property {Date} mtime - * @property {Date} ctime - * @property {Date} birthtime - */ + do { + if (this.type === tt.braceR) { + break; + } -/** - * @typedef {Object} IDirent - * @property {() => boolean} isFile - * @property {() => boolean} isDirectory - * @property {() => boolean} isBlockDevice - * @property {() => boolean} isCharacterDevice - * @property {() => boolean} isSymbolicLink - * @property {() => boolean} isFIFO - * @property {() => boolean} isSocket - * @property {string | Buffer} name - */ + const node = this.startNode(); // parse AssertionKey : IdentifierName, StringLiteral -/** @typedef {function((NodeJS.ErrnoException | null)=): void} Callback */ -/** @typedef {function((NodeJS.ErrnoException | null)=, Buffer=): void} BufferCallback */ -/** @typedef {function((NodeJS.ErrnoException | null)=, Buffer|string=): void} BufferOrStringCallback */ -/** @typedef {function((NodeJS.ErrnoException | null)=, (string | Buffer)[] | IDirent[]=): void} DirentArrayCallback */ -/** @typedef {function((NodeJS.ErrnoException | null)=, string=): void} StringCallback */ -/** @typedef {function((NodeJS.ErrnoException | null)=, number=): void} NumberCallback */ -/** @typedef {function((NodeJS.ErrnoException | null)=, IStats=): void} StatsCallback */ -/** @typedef {function((NodeJS.ErrnoException | Error | null)=, any=): void} ReadJsonCallback */ -/** @typedef {function((NodeJS.ErrnoException | Error | null)=, IStats|string=): void} LstatReadlinkAbsoluteCallback */ + let assertionKeyNode; -/** - * @typedef {Object} WatcherInfo - * @property {Set} changes get current aggregated changes that have not yet send to callback - * @property {Set} removals get current aggregated removals that have not yet send to callback - * @property {Map} fileTimeInfoEntries get info about files - * @property {Map} contextTimeInfoEntries get info about directories - */ + if (this.type === tt.string) { + assertionKeyNode = this.parseLiteral(this.value); + } else { + assertionKeyNode = this.parseIdent(true); + } -// TODO webpack 6 deprecate missing getInfo -/** - * @typedef {Object} Watcher - * @property {function(): void} close closes the watcher and all underlying file watchers - * @property {function(): void} pause closes the watcher, but keeps underlying file watchers alive until the next watch call - * @property {function(): Set=} getAggregatedChanges get current aggregated changes that have not yet send to callback - * @property {function(): Set=} getAggregatedRemovals get current aggregated removals that have not yet send to callback - * @property {function(): Map} getFileTimeInfoEntries get info about files - * @property {function(): Map} getContextTimeInfoEntries get info about directories - * @property {function(): WatcherInfo=} getInfo get info about timestamps and changes - */ + this.next(); + node.key = assertionKeyNode; // for now we are only allowing `type` as the only allowed module attribute -/** - * @callback WatchMethod - * @param {Iterable} files watched files - * @param {Iterable} directories watched directories - * @param {Iterable} missing watched exitance entries - * @param {number} startTime timestamp of start time - * @param {WatchOptions} options options object - * @param {function(Error=, Map, Map, Set, Set): void} callback aggregated callback - * @param {function(string, number): void} callbackUndelayed callback when the first change was detected - * @returns {Watcher} a watcher - */ + if (node.key.name !== "type") { + this.raise(this.pos, "The only accepted import assertion is `type`"); + } // check if we already have an entry for an attribute + // if a duplicate entry is found, throw an error + // for now this logic will come into play only when someone declares `type` twice -// TODO webpack 6 make optional methods required -/** - * @typedef {Object} OutputFileSystem - * @property {function(string, Buffer|string, Callback): void} writeFile - * @property {function(string, Callback): void} mkdir - * @property {function(string, DirentArrayCallback): void=} readdir - * @property {function(string, Callback): void=} rmdir - * @property {function(string, Callback): void=} unlink - * @property {function(string, StatsCallback): void} stat - * @property {function(string, StatsCallback): void=} lstat - * @property {function(string, BufferOrStringCallback): void} readFile - * @property {(function(string, string): string)=} join - * @property {(function(string, string): string)=} relative - * @property {(function(string): string)=} dirname - */ + if (attrNames.has(node.key.name)) { + this.raise(this.pos, "Duplicated key in assertions"); + } -/** - * @typedef {Object} InputFileSystem - * @property {function(string, BufferOrStringCallback): void} readFile - * @property {(function(string, ReadJsonCallback): void)=} readJson - * @property {function(string, BufferOrStringCallback): void} readlink - * @property {function(string, DirentArrayCallback): void} readdir - * @property {function(string, StatsCallback): void} stat - * @property {function(string, StatsCallback): void=} lstat - * @property {(function(string, BufferOrStringCallback): void)=} realpath - * @property {(function(string=): void)=} purge - * @property {(function(string, string): string)=} join - * @property {(function(string, string): string)=} relative - * @property {(function(string): string)=} dirname - */ + attrNames.add(node.key.name); -/** - * @typedef {Object} WatchFileSystem - * @property {WatchMethod} watch - */ + if (this.type !== tt.string) { + this.raise(this.pos, "Only string is supported as an assertion value"); + } + + node.value = this.parseLiteral(this.value); + attrs.push(this.finishNode(node, "ImportAttribute")); + } while (this.eat(tt.comma)); + + return attrs; + } + + }; +} + +/***/ }), + +/***/ 14819: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * @typedef {Object} IntermediateFileSystemExtras - * @property {function(string): void} mkdirSync - * @property {function(string): NodeJS.WritableStream} createWriteStream - * @property {function(string, string, NumberCallback): void} open - * @property {function(number, Buffer, number, number, number, NumberCallback): void} read - * @property {function(number, Callback): void} close - * @property {function(string, string, Callback): void} rename - */ -/** @typedef {InputFileSystem & OutputFileSystem & IntermediateFileSystemExtras} IntermediateFileSystem */ -/** - * - * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system - * @param {string} rootPath the root path - * @param {string} targetPath the target path - * @returns {string} location of targetPath relative to rootPath - */ -const relative = (fs, rootPath, targetPath) => { - if (fs && fs.relative) { - return fs.relative(rootPath, targetPath); - } else if (path.posix.isAbsolute(rootPath)) { - return path.posix.relative(rootPath, targetPath); - } else if (path.win32.isAbsolute(rootPath)) { - return path.win32.relative(rootPath, targetPath); - } else { - throw new Error( - `${rootPath} is neither a posix nor a windows path, and there is no 'relative' method defined in the file system` - ); - } -}; -exports.relative = relative; +const DescriptionFileUtils = __webpack_require__(25424); +const getInnerRequest = __webpack_require__(47956); -/** - * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system - * @param {string} rootPath a path - * @param {string} filename a filename - * @returns {string} the joined path - */ -const join = (fs, rootPath, filename) => { - if (fs && fs.join) { - return fs.join(rootPath, filename); - } else if (path.posix.isAbsolute(rootPath)) { - return path.posix.join(rootPath, filename); - } else if (path.win32.isAbsolute(rootPath)) { - return path.win32.join(rootPath, filename); - } else { - throw new Error( - `${rootPath} is neither a posix nor a windows path, and there is no 'join' method defined in the file system` - ); - } -}; -exports.join = join; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** - * @param {InputFileSystem|OutputFileSystem|undefined} fs a file system - * @param {string} absPath an absolute path - * @returns {string} the parent directory of the absolute path - */ -const dirname = (fs, absPath) => { - if (fs && fs.dirname) { - return fs.dirname(absPath); - } else if (path.posix.isAbsolute(absPath)) { - return path.posix.dirname(absPath); - } else if (path.win32.isAbsolute(absPath)) { - return path.win32.dirname(absPath); - } else { - throw new Error( - `${absPath} is neither a posix nor a windows path, and there is no 'dirname' method defined in the file system` - ); +module.exports = class AliasFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | Array} field field + * @param {string | ResolveStepHook} target target + */ + constructor(source, field, target) { + this.source = source; + this.field = field; + this.target = target; } -}; -exports.dirname = dirname; -/** - * @param {OutputFileSystem} fs a file system - * @param {string} p an absolute path - * @param {function(Error=): void} callback callback function for the error - * @returns {void} - */ -const mkdirp = (fs, p, callback) => { - fs.mkdir(p, err => { - if (err) { - if (err.code === "ENOENT") { - const dir = dirname(fs, p); - if (dir === p) { - callback(err); - return; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("AliasFieldPlugin", (request, resolveContext, callback) => { + if (!request.descriptionFileData) return callback(); + const innerRequest = getInnerRequest(resolver, request); + if (!innerRequest) return callback(); + const fieldData = DescriptionFileUtils.getField( + request.descriptionFileData, + this.field + ); + if (fieldData === null || typeof fieldData !== "object") { + if (resolveContext.log) + resolveContext.log( + "Field '" + + this.field + + "' doesn't contain a valid alias configuration" + ); + return callback(); } - mkdirp(fs, dir, err => { - if (err) { - callback(err); - return; - } - fs.mkdir(p, err => { - if (err) { - if (err.code === "EEXIST") { - callback(); - return; - } - callback(err); - return; - } - callback(); - }); - }); - return; - } else if (err.code === "EEXIST") { - callback(); - return; - } - callback(err); - return; - } - callback(); - }); -}; -exports.mkdirp = mkdirp; - -/** - * @param {IntermediateFileSystem} fs a file system - * @param {string} p an absolute path - * @returns {void} - */ -const mkdirpSync = (fs, p) => { - try { - fs.mkdirSync(p); - } catch (err) { - if (err) { - if (err.code === "ENOENT") { - const dir = dirname(fs, p); - if (dir === p) { - throw err; + const data1 = fieldData[innerRequest]; + const data2 = fieldData[innerRequest.replace(/^\.\//, "")]; + const data = typeof data1 !== "undefined" ? data1 : data2; + if (data === innerRequest) return callback(); + if (data === undefined) return callback(); + if (data === false) { + /** @type {ResolveRequest} */ + const ignoreObj = { + ...request, + path: false + }; + return callback(null, ignoreObj); } - mkdirpSync(fs, dir); - fs.mkdirSync(p); - return; - } else if (err.code === "EEXIST") { - return; - } - throw err; - } - } -}; -exports.mkdirpSync = mkdirpSync; - -/** - * @param {InputFileSystem} fs a file system - * @param {string} p an absolute path - * @param {ReadJsonCallback} callback callback - * @returns {void} - */ -const readJson = (fs, p, callback) => { - if ("readJson" in fs) return fs.readJson(p, callback); - fs.readFile(p, (err, buf) => { - if (err) return callback(err); - let data; - try { - data = JSON.parse(buf.toString("utf-8")); - } catch (e) { - return callback(e); - } - return callback(null, data); - }); -}; -exports.readJson = readJson; + const obj = { + ...request, + path: request.descriptionFileRoot, + request: data, + fullySpecified: false + }; + resolver.doResolve( + target, + obj, + "aliased from description file " + + request.descriptionFilePath + + " with mapping '" + + innerRequest + + "' to '" + + data + + "'", + resolveContext, + (err, result) => { + if (err) return callback(err); -/** - * @param {InputFileSystem} fs a file system - * @param {string} p an absolute path - * @param {ReadJsonCallback} callback callback - * @returns {void} - */ -const lstatReadlinkAbsolute = (fs, p, callback) => { - let i = 3; - const doReadLink = () => { - fs.readlink(p, (err, target) => { - if (err && --i > 0) { - // It might was just changed from symlink to file - // we retry 2 times to catch this case before throwing the error - return doStat(); - } - if (err || !target) return doStat(); - const value = target.toString(); - callback(null, join(fs, dirname(fs, p), value)); - }); - }; - const doStat = () => { - if ("lstat" in fs) { - return fs.lstat(p, (err, stats) => { - if (err) return callback(err); - if (stats.isSymbolicLink()) { - return doReadLink(); - } - callback(null, stats); + // Don't allow other aliasing or raw request + if (result === undefined) return callback(null, null); + callback(null, result); + } + ); }); - } else { - return fs.stat(p, callback); - } - }; - if ("lstat" in fs) return doStat(); - doReadLink(); + } }; -exports.lstatReadlinkAbsolute = lstatReadlinkAbsolute; /***/ }), -/***/ 59461: +/***/ 63676: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -133612,73 +133567,114 @@ exports.lstatReadlinkAbsolute = lstatReadlinkAbsolute; -const Hash = __webpack_require__(36692); -const MAX_SHORT_STRING = (__webpack_require__(1842).MAX_SHORT_STRING); +const forEachBail = __webpack_require__(78565); -class BatchedHash extends Hash { - constructor(hash) { - super(); - this.string = undefined; - this.encoding = undefined; - this.hash = hash; - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {{alias: string|Array|false, name: string, onlyModule?: boolean}} AliasOption */ +module.exports = class AliasPlugin { /** - * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} - * @param {string|Buffer} data data - * @param {string=} inputEncoding data encoding - * @returns {this} updated hash + * @param {string | ResolveStepHook} source source + * @param {AliasOption | Array} options options + * @param {string | ResolveStepHook} target target */ - update(data, inputEncoding) { - if (this.string !== undefined) { - if ( - typeof data === "string" && - inputEncoding === this.encoding && - this.string.length + data.length < MAX_SHORT_STRING - ) { - this.string += data; - return this; - } - this.hash.update(this.string, this.encoding); - this.string = undefined; - } - if (typeof data === "string") { - if ( - data.length < MAX_SHORT_STRING && - // base64 encoding is not valid since it may contain padding chars - (!inputEncoding || !inputEncoding.startsWith("ba")) - ) { - this.string = data; - this.encoding = inputEncoding; - } else { - this.hash.update(data, inputEncoding); - } - } else { - this.hash.update(data); - } - return this; + constructor(source, options, target) { + this.source = source; + this.options = Array.isArray(options) ? options : [options]; + this.target = target; } /** - * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} - * @param {string=} encoding encoding of the return value - * @returns {string|Buffer} digest + * @param {Resolver} resolver the resolver + * @returns {void} */ - digest(encoding) { - if (this.string !== undefined) { - this.hash.update(this.string, this.encoding); - } - return this.hash.digest(encoding); - } -} + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("AliasPlugin", (request, resolveContext, callback) => { + const innerRequest = request.request || request.path; + if (!innerRequest) return callback(); + forEachBail( + this.options, + (item, callback) => { + let shouldStop = false; + if ( + innerRequest === item.name || + (!item.onlyModule && innerRequest.startsWith(item.name + "/")) + ) { + const remainingRequest = innerRequest.substr(item.name.length); + const resolveWithAlias = (alias, callback) => { + if (alias === false) { + const ignoreObj = { + ...request, + path: false + }; + return callback(null, ignoreObj); + } + if ( + innerRequest !== alias && + !innerRequest.startsWith(alias + "/") + ) { + shouldStop = true; + const newRequestStr = alias + remainingRequest; + const obj = { + ...request, + request: newRequestStr, + fullySpecified: false + }; + return resolver.doResolve( + target, + obj, + "aliased with mapping '" + + item.name + + "': '" + + alias + + "' to '" + + newRequestStr + + "'", + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + return callback(); + } + ); + } + return callback(); + }; + const stoppingCallback = (err, result) => { + if (err) return callback(err); -module.exports = BatchedHash; + if (result) return callback(null, result); + // Don't allow other aliasing or raw request + if (shouldStop) return callback(null, null); + return callback(); + }; + if (Array.isArray(item.alias)) { + return forEachBail( + item.alias, + resolveWithAlias, + stoppingCallback + ); + } else { + return resolveWithAlias(item.alias, stoppingCallback); + } + } + return callback(); + }, + callback + ); + }); + } +}; /***/ }), -/***/ 86884: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 92088: +/***/ (function(module) { "use strict"; /* @@ -133688,25 +133684,52 @@ module.exports = BatchedHash; -const create = __webpack_require__(1842); +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -//#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1 -const md4 = new WebAssembly.Module( - Buffer.from( - // 2156 bytes - "AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqLEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvSCgEZfyMBIQUjAiECIwMhAyMEIQQDQCAAIAFLBEAgASgCJCISIAEoAiAiEyABKAIcIgkgASgCGCIIIAEoAhQiByABKAIQIg4gASgCDCIGIAEoAggiDyABKAIEIhAgASgCACIRIAMgBHMgAnEgBHMgBWpqQQN3IgogAiADc3EgA3MgBGpqQQd3IgsgAiAKc3EgAnMgA2pqQQt3IgwgCiALc3EgCnMgAmpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IgogDCANc3EgDHMgC2pqQQd3IgsgCiANc3EgDXMgDGpqQQt3IgwgCiALc3EgCnMgDWpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IhQgDCANc3EgDHMgC2pqQQd3IRUgASgCLCILIAEoAigiCiAMIA0gDSAUcyAVcXNqakELdyIWIBQgFXNxIBRzIA1qakETdyEXIAEoAjQiGCABKAIwIhkgFSAWcyAXcSAVcyAUampBA3ciFCAWIBdzcSAWcyAVampBB3chFSABKAI8Ig0gASgCOCIMIBQgF3MgFXEgF3MgFmpqQQt3IhYgFCAVc3EgFHMgF2pqQRN3IRcgEyAOIBEgFCAVIBZyIBdxIBUgFnFyampBmfOJ1AVqQQN3IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEFdyIVIBQgF3JxIBQgF3FyIBZqakGZ84nUBWpBCXchFiAPIBggEiAWIAcgFSAQIBQgGSAUIBVyIBZxIBQgFXFyIBdqakGZ84nUBWpBDXciFCAVIBZycSAVIBZxcmpqQZnzidQFakEDdyIVIBQgFnJxIBQgFnFyampBmfOJ1AVqQQV3IhcgFCAVcnEgFCAVcXJqakGZ84nUBWpBCXciFiAVIBdycSAVIBdxciAUampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEDdyEVIBEgBiAVIAwgFCAKIBYgCCAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFyAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIWIBUgF3JxIBUgF3FyampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXJqakGZ84nUBWpBA3ciFSALIBYgCSAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFiAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIXIA0gFSAWciAXcSAVIBZxciAUampBmfOJ1AVqQQ13IhRzIBZzampBodfn9gZqQQN3IREgByAIIA4gFCARIBcgESAUc3MgFmogE2pBodfn9gZqQQl3IhNzcyAXampBodfn9gZqQQt3Ig4gDyARIBMgDiARIA4gE3NzIBRqIBlqQaHX5/YGakEPdyIRc3NqakGh1+f2BmpBA3ciDyAOIA8gEXNzIBNqIApqQaHX5/YGakEJdyIKcyARc2pqQaHX5/YGakELdyIIIBAgDyAKIAggDCAPIAggCnNzIBFqakGh1+f2BmpBD3ciDHNzampBodfn9gZqQQN3Ig4gEiAIIAwgDnNzIApqakGh1+f2BmpBCXciCHMgDHNqakGh1+f2BmpBC3chByAFIAYgCCAHIBggDiAHIAhzcyAMampBodfn9gZqQQ93IgpzcyAOampBodfn9gZqQQN3IgZqIQUgDSAGIAkgByAGIAsgByAGIApzcyAIampBodfn9gZqQQl3IgdzIApzampBodfn9gZqQQt3IgYgB3NzIApqakGh1+f2BmpBD3cgAmohAiADIAZqIQMgBCAHaiEEIAFBQGshAQwBCwsgBSQBIAIkAiADJAMgBCQECw0AIAAQASAAIwBqJAAL/wQCA38BfiAAIwBqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=", - "base64" - ) -); -//#endregion +module.exports = class AppendPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} appending appending + * @param {string | ResolveStepHook} target target + */ + constructor(source, appending, target) { + this.source = source; + this.appending = appending; + this.target = target; + } -module.exports = create.bind(null, md4, [], 64, 32); + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("AppendPlugin", (request, resolveContext, callback) => { + const obj = { + ...request, + path: request.path + this.appending, + relativePath: + request.relativePath && request.relativePath + this.appending + }; + resolver.doResolve( + target, + obj, + this.appending, + resolveContext, + callback + ); + }); + } +}; /***/ }), -/***/ 1842: -/***/ (function(module) { +/***/ 52788: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -133716,167 +133739,481 @@ module.exports = create.bind(null, md4, [], 64, 32); -// 65536 is the size of a wasm memory page -// 64 is the maximum chunk size for every possible wasm hash implementation -// 4 is the maximum number of bytes per char for string encoding (max is utf-8) -// ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64 -const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3; +const nextTick = (__webpack_require__(77282).nextTick); -class WasmHash { - /** - * @param {WebAssembly.Instance} instance wasm instance - * @param {WebAssembly.Instance[]} instancesPool pool of instances - * @param {number} chunkSize size of data chunks passed to wasm - * @param {number} digestSize size of digest returned by wasm - */ - constructor(instance, instancesPool, chunkSize, digestSize) { - const exports = /** @type {any} */ (instance.exports); - exports.init(); - this.exports = exports; - this.mem = Buffer.from(exports.memory.buffer, 0, 65536); - this.buffered = 0; - this.instancesPool = instancesPool; - this.chunkSize = chunkSize; - this.digestSize = digestSize; +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ + +const dirname = path => { + let idx = path.length - 1; + while (idx >= 0) { + const c = path.charCodeAt(idx); + // slash or backslash + if (c === 47 || c === 92) break; + idx--; } + if (idx < 0) return ""; + return path.slice(0, idx); +}; - reset() { - this.buffered = 0; - this.exports.init(); +const runCallbacks = (callbacks, err, result) => { + if (callbacks.length === 1) { + callbacks[0](err, result); + callbacks.length = 0; + return; + } + let error; + for (const callback of callbacks) { + try { + callback(err, result); + } catch (e) { + if (!error) error = e; + } } + callbacks.length = 0; + if (error) throw error; +}; +class OperationMergerBackend { /** - * @param {Buffer | string} data data - * @param {BufferEncoding=} encoding encoding - * @returns {this} itself + * @param {any} provider async method + * @param {any} syncProvider sync method + * @param {any} providerContext call context for the provider methods */ - update(data, encoding) { - if (typeof data === "string") { - while (data.length > MAX_SHORT_STRING) { - this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding); - data = data.slice(MAX_SHORT_STRING); - } - this._updateWithShortString(data, encoding); - return this; - } - this._updateWithBuffer(data); - return this; + constructor(provider, syncProvider, providerContext) { + this._provider = provider; + this._syncProvider = syncProvider; + this._providerContext = providerContext; + this._activeAsyncOperations = new Map(); + + this.provide = this._provider + ? (path, options, callback) => { + if (typeof options === "function") { + callback = options; + options = undefined; + } + if (options) { + return this._provider.call( + this._providerContext, + path, + options, + callback + ); + } + if (typeof path !== "string") { + callback(new TypeError("path must be a string")); + return; + } + let callbacks = this._activeAsyncOperations.get(path); + if (callbacks) { + callbacks.push(callback); + return; + } + this._activeAsyncOperations.set(path, (callbacks = [callback])); + provider(path, (err, result) => { + this._activeAsyncOperations.delete(path); + runCallbacks(callbacks, err, result); + }); + } + : null; + this.provideSync = this._syncProvider + ? (path, options) => { + return this._syncProvider.call(this._providerContext, path, options); + } + : null; } + purge() {} + purgeParent() {} +} + +/* + +IDLE: + insert data: goto SYNC + +SYNC: + before provide: run ticks + event loop tick: goto ASYNC_ACTIVE + +ASYNC: + timeout: run tick, goto ASYNC_PASSIVE + +ASYNC_PASSIVE: + before provide: run ticks + +IDLE --[insert data]--> SYNC --[event loop tick]--> ASYNC_ACTIVE --[interval tick]-> ASYNC_PASSIVE + ^ | + +---------[insert data]-------+ +*/ + +const STORAGE_MODE_IDLE = 0; +const STORAGE_MODE_SYNC = 1; +const STORAGE_MODE_ASYNC = 2; + +class CacheBackend { /** - * @param {string} data data - * @param {BufferEncoding=} encoding encoding - * @returns {void} + * @param {number} duration max cache duration of items + * @param {any} provider async method + * @param {any} syncProvider sync method + * @param {any} providerContext call context for the provider methods */ - _updateWithShortString(data, encoding) { - const { exports, buffered, mem, chunkSize } = this; - let endPos; - if (data.length < 70) { - if (!encoding || encoding === "utf-8" || encoding === "utf8") { - endPos = buffered; - for (let i = 0; i < data.length; i++) { - const cc = data.charCodeAt(i); - if (cc < 0x80) mem[endPos++] = cc; - else if (cc < 0x800) { - mem[endPos] = (cc >> 6) | 0xc0; - mem[endPos + 1] = (cc & 0x3f) | 0x80; - endPos += 2; - } else { - // bail-out for weird chars - endPos += mem.write(data.slice(i), endPos, encoding); - break; - } + constructor(duration, provider, syncProvider, providerContext) { + this._duration = duration; + this._provider = provider; + this._syncProvider = syncProvider; + this._providerContext = providerContext; + /** @type {Map} */ + this._activeAsyncOperations = new Map(); + /** @type {Map }>} */ + this._data = new Map(); + /** @type {Set[]} */ + this._levels = []; + for (let i = 0; i < 10; i++) this._levels.push(new Set()); + for (let i = 5000; i < duration; i += 500) this._levels.push(new Set()); + this._currentLevel = 0; + this._tickInterval = Math.floor(duration / this._levels.length); + /** @type {STORAGE_MODE_IDLE | STORAGE_MODE_SYNC | STORAGE_MODE_ASYNC} */ + this._mode = STORAGE_MODE_IDLE; + + /** @type {NodeJS.Timeout | undefined} */ + this._timeout = undefined; + /** @type {number | undefined} */ + this._nextDecay = undefined; + + this.provide = provider ? this.provide.bind(this) : null; + this.provideSync = syncProvider ? this.provideSync.bind(this) : null; + } + + provide(path, options, callback) { + if (typeof options === "function") { + callback = options; + options = undefined; + } + if (typeof path !== "string") { + callback(new TypeError("path must be a string")); + return; + } + if (options) { + return this._provider.call( + this._providerContext, + path, + options, + callback + ); + } + + // When in sync mode we can move to async mode + if (this._mode === STORAGE_MODE_SYNC) { + this._enterAsyncMode(); + } + + // Check in cache + let cacheEntry = this._data.get(path); + if (cacheEntry !== undefined) { + if (cacheEntry.err) return nextTick(callback, cacheEntry.err); + return nextTick(callback, null, cacheEntry.result); + } + + // Check if there is already the same operation running + let callbacks = this._activeAsyncOperations.get(path); + if (callbacks !== undefined) { + callbacks.push(callback); + return; + } + this._activeAsyncOperations.set(path, (callbacks = [callback])); + + // Run the operation + this._provider.call(this._providerContext, path, (err, result) => { + this._activeAsyncOperations.delete(path); + this._storeResult(path, err, result); + + // Enter async mode if not yet done + this._enterAsyncMode(); + + runCallbacks(callbacks, err, result); + }); + } + + provideSync(path, options) { + if (typeof path !== "string") { + throw new TypeError("path must be a string"); + } + if (options) { + return this._syncProvider.call(this._providerContext, path, options); + } + + // In sync mode we may have to decay some cache items + if (this._mode === STORAGE_MODE_SYNC) { + this._runDecays(); + } + + // Check in cache + let cacheEntry = this._data.get(path); + if (cacheEntry !== undefined) { + if (cacheEntry.err) throw cacheEntry.err; + return cacheEntry.result; + } + + // Get all active async operations + // This sync operation will also complete them + const callbacks = this._activeAsyncOperations.get(path); + this._activeAsyncOperations.delete(path); + + // Run the operation + // When in idle mode, we will enter sync mode + let result; + try { + result = this._syncProvider.call(this._providerContext, path); + } catch (err) { + this._storeResult(path, err, undefined); + this._enterSyncModeWhenIdle(); + if (callbacks) runCallbacks(callbacks, err, undefined); + throw err; + } + this._storeResult(path, undefined, result); + this._enterSyncModeWhenIdle(); + if (callbacks) runCallbacks(callbacks, undefined, result); + return result; + } + + purge(what) { + if (!what) { + if (this._mode !== STORAGE_MODE_IDLE) { + this._data.clear(); + for (const level of this._levels) { + level.clear(); } - } else if (encoding === "latin1") { - endPos = buffered; - for (let i = 0; i < data.length; i++) { - const cc = data.charCodeAt(i); - mem[endPos++] = cc; + this._enterIdleMode(); + } + } else if (typeof what === "string") { + for (let [key, data] of this._data) { + if (key.startsWith(what)) { + this._data.delete(key); + data.level.delete(key); } - } else { - endPos = buffered + mem.write(data, buffered, encoding); + } + if (this._data.size === 0) { + this._enterIdleMode(); } } else { - endPos = buffered + mem.write(data, buffered, encoding); + for (let [key, data] of this._data) { + for (const item of what) { + if (key.startsWith(item)) { + this._data.delete(key); + data.level.delete(key); + break; + } + } + } + if (this._data.size === 0) { + this._enterIdleMode(); + } } - if (endPos < chunkSize) { - this.buffered = endPos; + } + + purgeParent(what) { + if (!what) { + this.purge(); + } else if (typeof what === "string") { + this.purge(dirname(what)); } else { - const l = endPos & ~(this.chunkSize - 1); - exports.update(l); - const newBuffered = endPos - l; - this.buffered = newBuffered; - if (newBuffered > 0) mem.copyWithin(0, l, endPos); + const set = new Set(); + for (const item of what) { + set.add(dirname(item)); + } + this.purge(set); } } - /** - * @param {Buffer} data data - * @returns {void} - */ - _updateWithBuffer(data) { - const { exports, buffered, mem } = this; - const length = data.length; - if (buffered + length < this.chunkSize) { - data.copy(mem, buffered, 0, length); - this.buffered += length; + _storeResult(path, err, result) { + if (this._data.has(path)) return; + const level = this._levels[this._currentLevel]; + this._data.set(path, { err, result, level }); + level.add(path); + } + + _decayLevel() { + const nextLevel = (this._currentLevel + 1) % this._levels.length; + const decay = this._levels[nextLevel]; + this._currentLevel = nextLevel; + for (let item of decay) { + this._data.delete(item); + } + decay.clear(); + if (this._data.size === 0) { + this._enterIdleMode(); } else { - const l = (buffered + length) & ~(this.chunkSize - 1); - if (l > 65536) { - let i = 65536 - buffered; - data.copy(mem, buffered, 0, i); - exports.update(65536); - const stop = l - buffered - 65536; - while (i < stop) { - data.copy(mem, 0, i, i + 65536); - exports.update(65536); - i += 65536; - } - data.copy(mem, 0, i, l - buffered); - exports.update(l - buffered - i); - } else { - data.copy(mem, buffered, 0, l - buffered); - exports.update(l); - } - const newBuffered = length + buffered - l; - this.buffered = newBuffered; - if (newBuffered > 0) data.copy(mem, 0, length - newBuffered, length); + // @ts-ignore _nextDecay is always a number in sync mode + this._nextDecay += this._tickInterval; } } - digest(type) { - const { exports, buffered, mem, digestSize } = this; - exports.final(buffered); - this.instancesPool.push(this); - const hex = mem.toString("latin1", 0, digestSize); - if (type === "hex") return hex; - if (type === "binary" || !type) return Buffer.from(hex, "hex"); - return Buffer.from(hex, "hex").toString(type); + _runDecays() { + while ( + /** @type {number} */ (this._nextDecay) <= Date.now() && + this._mode !== STORAGE_MODE_IDLE + ) { + this._decayLevel(); + } + } + + _enterAsyncMode() { + let timeout = 0; + switch (this._mode) { + case STORAGE_MODE_ASYNC: + return; + case STORAGE_MODE_IDLE: + this._nextDecay = Date.now() + this._tickInterval; + timeout = this._tickInterval; + break; + case STORAGE_MODE_SYNC: + this._runDecays(); + // @ts-ignore _runDecays may change the mode + if (this._mode === STORAGE_MODE_IDLE) return; + timeout = Math.max( + 0, + /** @type {number} */ (this._nextDecay) - Date.now() + ); + break; + } + this._mode = STORAGE_MODE_ASYNC; + const ref = setTimeout(() => { + this._mode = STORAGE_MODE_SYNC; + this._runDecays(); + }, timeout); + if (ref.unref) ref.unref(); + this._timeout = ref; + } + + _enterSyncModeWhenIdle() { + if (this._mode === STORAGE_MODE_IDLE) { + this._mode = STORAGE_MODE_SYNC; + this._nextDecay = Date.now() + this._tickInterval; + } + } + + _enterIdleMode() { + this._mode = STORAGE_MODE_IDLE; + this._nextDecay = undefined; + if (this._timeout) clearTimeout(this._timeout); } } -const create = (wasmModule, instancesPool, chunkSize, digestSize) => { - if (instancesPool.length > 0) { - const old = instancesPool.pop(); - old.reset(); - return old; - } else { - return new WasmHash( - new WebAssembly.Instance(wasmModule), - instancesPool, - chunkSize, - digestSize +const createBackend = (duration, provider, syncProvider, providerContext) => { + if (duration > 0) { + return new CacheBackend(duration, provider, syncProvider, providerContext); + } + return new OperationMergerBackend(provider, syncProvider, providerContext); +}; + +module.exports = class CachedInputFileSystem { + constructor(fileSystem, duration) { + this.fileSystem = fileSystem; + + this._lstatBackend = createBackend( + duration, + this.fileSystem.lstat, + this.fileSystem.lstatSync, + this.fileSystem + ); + const lstat = this._lstatBackend.provide; + this.lstat = /** @type {FileSystem["lstat"]} */ (lstat); + const lstatSync = this._lstatBackend.provideSync; + this.lstatSync = /** @type {SyncFileSystem["lstatSync"]} */ (lstatSync); + + this._statBackend = createBackend( + duration, + this.fileSystem.stat, + this.fileSystem.statSync, + this.fileSystem + ); + const stat = this._statBackend.provide; + this.stat = /** @type {FileSystem["stat"]} */ (stat); + const statSync = this._statBackend.provideSync; + this.statSync = /** @type {SyncFileSystem["statSync"]} */ (statSync); + + this._readdirBackend = createBackend( + duration, + this.fileSystem.readdir, + this.fileSystem.readdirSync, + this.fileSystem + ); + const readdir = this._readdirBackend.provide; + this.readdir = /** @type {FileSystem["readdir"]} */ (readdir); + const readdirSync = this._readdirBackend.provideSync; + this.readdirSync = /** @type {SyncFileSystem["readdirSync"]} */ (readdirSync); + + this._readFileBackend = createBackend( + duration, + this.fileSystem.readFile, + this.fileSystem.readFileSync, + this.fileSystem + ); + const readFile = this._readFileBackend.provide; + this.readFile = /** @type {FileSystem["readFile"]} */ (readFile); + const readFileSync = this._readFileBackend.provideSync; + this.readFileSync = /** @type {SyncFileSystem["readFileSync"]} */ (readFileSync); + + this._readJsonBackend = createBackend( + duration, + this.fileSystem.readJson || + (this.readFile && + ((path, callback) => { + // @ts-ignore + this.readFile(path, (err, buffer) => { + if (err) return callback(err); + if (!buffer || buffer.length === 0) + return callback(new Error("No file content")); + let data; + try { + data = JSON.parse(buffer.toString("utf-8")); + } catch (e) { + return callback(e); + } + callback(null, data); + }); + })), + this.fileSystem.readJsonSync || + (this.readFileSync && + (path => { + const buffer = this.readFileSync(path); + const data = JSON.parse(buffer.toString("utf-8")); + return data; + })), + this.fileSystem + ); + const readJson = this._readJsonBackend.provide; + this.readJson = /** @type {FileSystem["readJson"]} */ (readJson); + const readJsonSync = this._readJsonBackend.provideSync; + this.readJsonSync = /** @type {SyncFileSystem["readJsonSync"]} */ (readJsonSync); + + this._readlinkBackend = createBackend( + duration, + this.fileSystem.readlink, + this.fileSystem.readlinkSync, + this.fileSystem ); + const readlink = this._readlinkBackend.provide; + this.readlink = /** @type {FileSystem["readlink"]} */ (readlink); + const readlinkSync = this._readlinkBackend.provideSync; + this.readlinkSync = /** @type {SyncFileSystem["readlinkSync"]} */ (readlinkSync); } -}; -module.exports = create; -module.exports.MAX_SHORT_STRING = MAX_SHORT_STRING; + purge(what) { + this._statBackend.purge(what); + this._lstatBackend.purge(what); + this._readdirBackend.purgeParent(what); + this._readFileBackend.purge(what); + this._readlinkBackend.purge(what); + this._readJsonBackend.purge(what); + } +}; /***/ }), -/***/ 35028: +/***/ 22254: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -133887,683 +134224,871 @@ module.exports.MAX_SHORT_STRING = MAX_SHORT_STRING; -const create = __webpack_require__(1842); +const basename = (__webpack_require__(82918).basename); -//#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1 -const xxhash64 = new WebAssembly.Module( - Buffer.from( - // 1170 bytes - "AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrIIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqAYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEAgAiABNQIAQoeVr6+Ytt6bnn9+hUIXiULP1tO+0ser2UJ+Qvnz3fGZ9pmrFnwhAiABQQRqIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAkIdiCAChUL5893xmfaZqxZ+IgJCIIggAoUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL", - "base64" - ) -); -//#endregion +/** @typedef {import("./Resolver")} Resolver */ -module.exports = create.bind(null, xxhash64, [], 32, 16); +module.exports = class CloneBasenamePlugin { + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("CloneBasenamePlugin", (request, resolveContext, callback) => { + const filename = basename(request.path); + const filePath = resolver.join(request.path, filename); + const obj = { + ...request, + path: filePath, + relativePath: + request.relativePath && + resolver.join(request.relativePath, filename) + }; + resolver.doResolve( + target, + obj, + "using path: " + filePath, + resolveContext, + callback + ); + }); + } +}; /***/ }), -/***/ 82186: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 6953: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const path = __webpack_require__(71017); +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -const WINDOWS_ABS_PATH_REGEXP = /^[a-zA-Z]:[\\/]/; -const SEGMENTS_SPLIT_REGEXP = /([|!])/; -const WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g; +module.exports = class ConditionalPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Partial} test compare object + * @param {string | null} message log message + * @param {boolean} allowAlternatives when false, do not continue with the current step when "test" matches + * @param {string | ResolveStepHook} target target + */ + constructor(source, test, message, allowAlternatives, target) { + this.source = source; + this.test = test; + this.message = message; + this.allowAlternatives = allowAlternatives; + this.target = target; + } -/** - * @typedef {Object} MakeRelativePathsCache - * @property {Map>=} relativePaths - */ + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const { test, message, allowAlternatives } = this; + const keys = Object.keys(test); + resolver + .getHook(this.source) + .tapAsync("ConditionalPlugin", (request, resolveContext, callback) => { + for (const prop of keys) { + if (request[prop] !== test[prop]) return callback(); + } + resolver.doResolve( + target, + request, + message, + resolveContext, + allowAlternatives + ? callback + : (err, result) => { + if (err) return callback(err); -const relativePathToRequest = relativePath => { - if (relativePath === "") return "./."; - if (relativePath === "..") return "../."; - if (relativePath.startsWith("../")) return relativePath; - return `./${relativePath}`; + // Don't allow other alternatives + if (result === undefined) return callback(null, null); + callback(null, result); + } + ); + }); + } }; -/** - * @param {string} context context for relative path - * @param {string} maybeAbsolutePath path to make relative - * @returns {string} relative path in request style - */ -const absoluteToRequest = (context, maybeAbsolutePath) => { - if (maybeAbsolutePath[0] === "/") { - if ( - maybeAbsolutePath.length > 1 && - maybeAbsolutePath[maybeAbsolutePath.length - 1] === "/" - ) { - // this 'path' is actually a regexp generated by dynamic requires. - // Don't treat it as an absolute path. - return maybeAbsolutePath; - } - - const querySplitPos = maybeAbsolutePath.indexOf("?"); - let resource = - querySplitPos === -1 - ? maybeAbsolutePath - : maybeAbsolutePath.slice(0, querySplitPos); - resource = relativePathToRequest(path.posix.relative(context, resource)); - return querySplitPos === -1 - ? resource - : resource + maybeAbsolutePath.slice(querySplitPos); - } - if (WINDOWS_ABS_PATH_REGEXP.test(maybeAbsolutePath)) { - const querySplitPos = maybeAbsolutePath.indexOf("?"); - let resource = - querySplitPos === -1 - ? maybeAbsolutePath - : maybeAbsolutePath.slice(0, querySplitPos); - resource = path.win32.relative(context, resource); - if (!WINDOWS_ABS_PATH_REGEXP.test(resource)) { - resource = relativePathToRequest( - resource.replace(WINDOWS_PATH_SEPARATOR_REGEXP, "/") - ); - } - return querySplitPos === -1 - ? resource - : resource + maybeAbsolutePath.slice(querySplitPos); - } +/***/ }), - // not an absolute path - return maybeAbsolutePath; -}; +/***/ 44112: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * @param {string} context context for relative path - * @param {string} relativePath path - * @returns {string} absolute path - */ -const requestToAbsolute = (context, relativePath) => { - if (relativePath.startsWith("./") || relativePath.startsWith("../")) - return path.join(context, relativePath); - return relativePath; -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -const makeCacheable = fn => { - /** @type {WeakMap>>} */ - const cache = new WeakMap(); - /** - * @param {string} context context used to create relative path - * @param {string} identifier identifier used to create relative path - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {string} the returned relative path - */ - const cachedFn = (context, identifier, associatedObjectForCache) => { - if (!associatedObjectForCache) return fn(context, identifier); - let innerCache = cache.get(associatedObjectForCache); - if (innerCache === undefined) { - innerCache = new Map(); - cache.set(associatedObjectForCache, innerCache); - } +const DescriptionFileUtils = __webpack_require__(25424); - let cachedResult; - let innerSubCache = innerCache.get(context); - if (innerSubCache === undefined) { - innerCache.set(context, (innerSubCache = new Map())); - } else { - cachedResult = innerSubCache.get(identifier); - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - if (cachedResult !== undefined) { - return cachedResult; - } else { - const result = fn(context, identifier); - innerSubCache.set(identifier, result); - return result; - } - }; +module.exports = class DescriptionFilePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string[]} filenames filenames + * @param {boolean} pathIsFile pathIsFile + * @param {string | ResolveStepHook} target target + */ + constructor(source, filenames, pathIsFile, target) { + this.source = source; + this.filenames = filenames; + this.pathIsFile = pathIsFile; + this.target = target; + } /** - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {function(string, string): string} cached function + * @param {Resolver} resolver the resolver + * @returns {void} */ - cachedFn.bindCache = associatedObjectForCache => { - let innerCache; - if (associatedObjectForCache) { - innerCache = cache.get(associatedObjectForCache); - if (innerCache === undefined) { - innerCache = new Map(); - cache.set(associatedObjectForCache, innerCache); - } - } else { - innerCache = new Map(); - } + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "DescriptionFilePlugin", + (request, resolveContext, callback) => { + const path = request.path; + if (!path) return callback(); + const directory = this.pathIsFile + ? DescriptionFileUtils.cdUp(path) + : path; + if (!directory) return callback(); + DescriptionFileUtils.loadDescriptionFile( + resolver, + directory, + this.filenames, + request.descriptionFilePath + ? { + path: request.descriptionFilePath, + content: request.descriptionFileData, + directory: /** @type {string} */ (request.descriptionFileRoot) + } + : undefined, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (!result) { + if (resolveContext.log) + resolveContext.log( + `No description file found in ${directory} or above` + ); + return callback(); + } + const relativePath = + "." + path.substr(result.directory.length).replace(/\\/g, "/"); + const obj = { + ...request, + descriptionFilePath: result.path, + descriptionFileData: result.content, + descriptionFileRoot: result.directory, + relativePath: relativePath + }; + resolver.doResolve( + target, + obj, + "using description file: " + + result.path + + " (relative path: " + + relativePath + + ")", + resolveContext, + (err, result) => { + if (err) return callback(err); - /** - * @param {string} context context used to create relative path - * @param {string} identifier identifier used to create relative path - * @returns {string} the returned relative path - */ - const boundFn = (context, identifier) => { - let cachedResult; - let innerSubCache = innerCache.get(context); - if (innerSubCache === undefined) { - innerCache.set(context, (innerSubCache = new Map())); - } else { - cachedResult = innerSubCache.get(identifier); - } + // Don't allow other processing + if (result === undefined) return callback(null, null); + callback(null, result); + } + ); + } + ); + } + ); + } +}; - if (cachedResult !== undefined) { - return cachedResult; - } else { - const result = fn(context, identifier); - innerSubCache.set(identifier, result); - return result; - } - }; - return boundFn; - }; +/***/ }), - /** - * @param {string} context context used to create relative path - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {function(string): string} cached function - */ - cachedFn.bindContextCache = (context, associatedObjectForCache) => { - let innerSubCache; - if (associatedObjectForCache) { - let innerCache = cache.get(associatedObjectForCache); - if (innerCache === undefined) { - innerCache = new Map(); - cache.set(associatedObjectForCache, innerCache); - } +/***/ 25424: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - innerSubCache = innerCache.get(context); - if (innerSubCache === undefined) { - innerCache.set(context, (innerSubCache = new Map())); - } - } else { - innerSubCache = new Map(); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @param {string} identifier identifier used to create relative path - * @returns {string} the returned relative path - */ - const boundFn = identifier => { - const cachedResult = innerSubCache.get(identifier); - if (cachedResult !== undefined) { - return cachedResult; - } else { - const result = fn(context, identifier); - innerSubCache.set(identifier, result); - return result; - } - }; - return boundFn; - }; - return cachedFn; -}; +const forEachBail = __webpack_require__(78565); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ /** - * - * @param {string} context context for relative path - * @param {string} identifier identifier for path - * @returns {string} a converted relative path + * @typedef {Object} DescriptionFileInfo + * @property {any=} content + * @property {string} path + * @property {string} directory */ -const _makePathsRelative = (context, identifier) => { - return identifier - .split(SEGMENTS_SPLIT_REGEXP) - .map(str => absoluteToRequest(context, str)) - .join(""); -}; -exports.makePathsRelative = makeCacheable(_makePathsRelative); +/** + * @callback ErrorFirstCallback + * @param {Error|null=} error + * @param {DescriptionFileInfo=} result + */ /** - * - * @param {string} context context for relative path - * @param {string} identifier identifier for path - * @returns {string} a converted relative path + * @param {Resolver} resolver resolver + * @param {string} directory directory + * @param {string[]} filenames filenames + * @param {DescriptionFileInfo|undefined} oldInfo oldInfo + * @param {ResolveContext} resolveContext resolveContext + * @param {ErrorFirstCallback} callback callback */ -const _makePathsAbsolute = (context, identifier) => { - return identifier - .split(SEGMENTS_SPLIT_REGEXP) - .map(str => requestToAbsolute(context, str)) - .join(""); -}; +function loadDescriptionFile( + resolver, + directory, + filenames, + oldInfo, + resolveContext, + callback +) { + (function findDescriptionFile() { + if (oldInfo && oldInfo.directory === directory) { + // We already have info for this directory and can reuse it + return callback(null, oldInfo); + } + forEachBail( + filenames, + (filename, callback) => { + const descriptionFilePath = resolver.join(directory, filename); + if (resolver.fileSystem.readJson) { + resolver.fileSystem.readJson(descriptionFilePath, (err, content) => { + if (err) { + if (typeof err.code !== "undefined") { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(descriptionFilePath); + } + return callback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + return onJson(err); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + onJson(null, content); + }); + } else { + resolver.fileSystem.readFile(descriptionFilePath, (err, content) => { + if (err) { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(descriptionFilePath); + } + return callback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + let json; -exports.makePathsAbsolute = makeCacheable(_makePathsAbsolute); + if (content) { + try { + json = JSON.parse(content.toString()); + } catch (e) { + return onJson(e); + } + } else { + return onJson(new Error("No content in file")); + } + + onJson(null, json); + }); + } + + function onJson(err, content) { + if (err) { + if (resolveContext.log) + resolveContext.log( + descriptionFilePath + " (directory description file): " + err + ); + else + err.message = + descriptionFilePath + " (directory description file): " + err; + return callback(err); + } + callback(null, { + content, + directory, + path: descriptionFilePath + }); + } + }, + (err, result) => { + if (err) return callback(err); + if (result) { + return callback(null, result); + } else { + const dir = cdUp(directory); + if (!dir) { + return callback(); + } else { + directory = dir; + return findDescriptionFile(); + } + } + } + ); + })(); +} /** - * @param {string} context absolute context path - * @param {string} request any request string may containing absolute paths, query string, etc. - * @returns {string} a new request string avoiding absolute paths when possible + * @param {any} content content + * @param {string|string[]} field field + * @returns {object|string|number|boolean|undefined} field data */ -const _contextify = (context, request) => { - return request - .split("!") - .map(r => absoluteToRequest(context, r)) - .join("!"); -}; - -const contextify = makeCacheable(_contextify); -exports.contextify = contextify; +function getField(content, field) { + if (!content) return undefined; + if (Array.isArray(field)) { + let current = content; + for (let j = 0; j < field.length; j++) { + if (current === null || typeof current !== "object") { + current = null; + break; + } + current = current[field[j]]; + } + return current; + } else { + return content[field]; + } +} /** - * @param {string} context absolute context path - * @param {string} request any request string - * @returns {string} a new request string using absolute paths when possible + * @param {string} directory directory + * @returns {string|null} parent directory or null */ -const _absolutify = (context, request) => { - return request - .split("!") - .map(r => requestToAbsolute(context, r)) - .join("!"); -}; +function cdUp(directory) { + if (directory === "/") return null; + const i = directory.lastIndexOf("/"), + j = directory.lastIndexOf("\\"); + const p = i < 0 ? j : j < 0 ? i : i < j ? j : i; + if (p < 0) return null; + return directory.substr(0, p || 1); +} -const absolutify = makeCacheable(_absolutify); -exports.absolutify = absolutify; +exports.loadDescriptionFile = loadDescriptionFile; +exports.getField = getField; +exports.cdUp = cdUp; -const PATH_QUERY_FRAGMENT_REGEXP = - /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; -/** @typedef {{ resource: string, path: string, query: string, fragment: string }} ParsedResource */ +/***/ }), -/** - * @param {string} str the path with query and fragment - * @returns {ParsedResource} parsed parts - */ -const _parseResource = str => { - const match = PATH_QUERY_FRAGMENT_REGEXP.exec(str); - return { - resource: str, - path: match[1].replace(/\0(.)/g, "$1"), - query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "", - fragment: match[3] || "" - }; -}; -exports.parseResource = (realFn => { - /** @type {WeakMap>} */ - const cache = new WeakMap(); +/***/ 60895: +/***/ (function(module) { - const getCache = associatedObjectForCache => { - const entry = cache.get(associatedObjectForCache); - if (entry !== undefined) return entry; - /** @type {Map} */ - const map = new Map(); - cache.set(associatedObjectForCache, map); - return map; - }; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @param {string} str the path with query and fragment - * @param {Object=} associatedObjectForCache an object to which the cache will be attached - * @returns {ParsedResource} parsed parts - */ - const fn = (str, associatedObjectForCache) => { - if (!associatedObjectForCache) return realFn(str); - const cache = getCache(associatedObjectForCache); - const entry = cache.get(str); - if (entry !== undefined) return entry; - const result = realFn(str); - cache.set(str, result); - return result; - }; - fn.bindCache = associatedObjectForCache => { - const cache = getCache(associatedObjectForCache); - return str => { - const entry = cache.get(str); - if (entry !== undefined) return entry; - const result = realFn(str); - cache.set(str, result); - return result; - }; - }; - return fn; -})(_parseResource); +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** - * @param {string} filename the filename which should be undone - * @param {string} outputPath the output path that is restored (only relevant when filename contains "..") - * @param {boolean} enforceRelative true returns ./ for empty paths - * @returns {string} repeated ../ to leave the directory of the provided filename to be back on output dir - */ -exports.getUndoPath = (filename, outputPath, enforceRelative) => { - let depth = -1; - let append = ""; - outputPath = outputPath.replace(/[\\/]$/, ""); - for (const part of filename.split(/[/\\]+/)) { - if (part === "..") { - if (depth > -1) { - depth--; - } else { - const i = outputPath.lastIndexOf("/"); - const j = outputPath.lastIndexOf("\\"); - const pos = i < 0 ? j : j < 0 ? i : Math.max(i, j); - if (pos < 0) return outputPath + "/"; - append = outputPath.slice(pos + 1) + "/" + append; - outputPath = outputPath.slice(0, pos); - } - } else if (part !== ".") { - depth++; - } +module.exports = class DirectoryExistsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "DirectoryExistsPlugin", + (request, resolveContext, callback) => { + const fs = resolver.fileSystem; + const directory = request.path; + if (!directory) return callback(); + fs.stat(directory, (err, stat) => { + if (err || !stat) { + if (resolveContext.missingDependencies) + resolveContext.missingDependencies.add(directory); + if (resolveContext.log) + resolveContext.log(directory + " doesn't exist"); + return callback(); + } + if (!stat.isDirectory()) { + if (resolveContext.missingDependencies) + resolveContext.missingDependencies.add(directory); + if (resolveContext.log) + resolveContext.log(directory + " is not a directory"); + return callback(); + } + if (resolveContext.fileDependencies) + resolveContext.fileDependencies.add(directory); + resolver.doResolve( + target, + request, + `existing directory ${directory}`, + resolveContext, + callback + ); + }); + } + ); } - return depth > 0 - ? `${"../".repeat(depth)}${append}` - : enforceRelative - ? `./${append}` - : append; }; /***/ }), -/***/ 53023: +/***/ 83849: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -// We need to include a list of requires here -// to allow webpack to be bundled with only static requires -// We could use a dynamic require(`../${request}`) but this -// would include too many modules and not every tool is able -// to process this -module.exports = { - AsyncDependenciesBlock: () => __webpack_require__(47736), - CommentCompilationWarning: () => __webpack_require__(98427), - ContextModule: () => __webpack_require__(76729), - "cache/PackFileCacheStrategy": () => - __webpack_require__(86180), - "cache/ResolverCachePlugin": () => __webpack_require__(97347), - "container/ContainerEntryDependency": () => - __webpack_require__(64813), - "container/ContainerEntryModule": () => - __webpack_require__(80580), - "container/ContainerExposedDependency": () => - __webpack_require__(72374), - "container/FallbackDependency": () => - __webpack_require__(57764), - "container/FallbackItemDependency": () => - __webpack_require__(29593), - "container/FallbackModule": () => __webpack_require__(82886), - "container/RemoteModule": () => __webpack_require__(62916), - "container/RemoteToExternalDependency": () => - __webpack_require__(14389), - "dependencies/AMDDefineDependency": () => - __webpack_require__(96816), - "dependencies/AMDRequireArrayDependency": () => - __webpack_require__(33516), - "dependencies/AMDRequireContextDependency": () => - __webpack_require__(96123), - "dependencies/AMDRequireDependenciesBlock": () => - __webpack_require__(76932), - "dependencies/AMDRequireDependency": () => - __webpack_require__(43911), - "dependencies/AMDRequireItemDependency": () => - __webpack_require__(71806), - "dependencies/CachedConstDependency": () => - __webpack_require__(57403), - "dependencies/CreateScriptUrlDependency": () => - __webpack_require__(79062), - "dependencies/CommonJsRequireContextDependency": () => - __webpack_require__(23962), - "dependencies/CommonJsExportRequireDependency": () => - __webpack_require__(62892), - "dependencies/CommonJsExportsDependency": () => - __webpack_require__(45598), - "dependencies/CommonJsFullRequireDependency": () => - __webpack_require__(59440), - "dependencies/CommonJsRequireDependency": () => - __webpack_require__(21264), - "dependencies/CommonJsSelfReferenceDependency": () => - __webpack_require__(52225), - "dependencies/ConstDependency": () => - __webpack_require__(76911), - "dependencies/ContextDependency": () => - __webpack_require__(88101), - "dependencies/ContextElementDependency": () => - __webpack_require__(58477), - "dependencies/CriticalDependencyWarning": () => - __webpack_require__(15427), - "dependencies/CssImportDependency": () => - __webpack_require__(90542), - "dependencies/CssLocalIdentifierDependency": () => - __webpack_require__(92328), - "dependencies/CssSelfLocalIdentifierDependency": () => - __webpack_require__(29094), - "dependencies/CssExportDependency": () => - __webpack_require__(76760), - "dependencies/CssUrlDependency": () => - __webpack_require__(70749), - "dependencies/DelegatedSourceDependency": () => - __webpack_require__(22914), - "dependencies/DllEntryDependency": () => - __webpack_require__(95666), - "dependencies/EntryDependency": () => - __webpack_require__(3979), - "dependencies/ExportsInfoDependency": () => - __webpack_require__(78988), - "dependencies/HarmonyAcceptDependency": () => - __webpack_require__(23624), - "dependencies/HarmonyAcceptImportDependency": () => - __webpack_require__(99843), - "dependencies/HarmonyCompatibilityDependency": () => - __webpack_require__(72906), - "dependencies/HarmonyExportExpressionDependency": () => - __webpack_require__(51340), - "dependencies/HarmonyExportHeaderDependency": () => - __webpack_require__(38873), - "dependencies/HarmonyExportImportedSpecifierDependency": () => - __webpack_require__(67157), - "dependencies/HarmonyExportSpecifierDependency": () => - __webpack_require__(48567), - "dependencies/HarmonyImportSideEffectDependency": () => - __webpack_require__(73132), - "dependencies/HarmonyImportSpecifierDependency": () => - __webpack_require__(14077), - "dependencies/ImportContextDependency": () => - __webpack_require__(1902), - "dependencies/ImportDependency": () => - __webpack_require__(89376), - "dependencies/ImportEagerDependency": () => - __webpack_require__(50718), - "dependencies/ImportWeakDependency": () => - __webpack_require__(82483), - "dependencies/JsonExportsDependency": () => - __webpack_require__(750), - "dependencies/LocalModule": () => __webpack_require__(5826), - "dependencies/LocalModuleDependency": () => - __webpack_require__(52805), - "dependencies/ModuleDecoratorDependency": () => - __webpack_require__(88488), - "dependencies/ModuleHotAcceptDependency": () => - __webpack_require__(47511), - "dependencies/ModuleHotDeclineDependency": () => - __webpack_require__(86301), - "dependencies/ImportMetaHotAcceptDependency": () => - __webpack_require__(51274), - "dependencies/ImportMetaHotDeclineDependency": () => - __webpack_require__(53141), - "dependencies/ProvidedDependency": () => - __webpack_require__(95770), - "dependencies/PureExpressionDependency": () => - __webpack_require__(55799), - "dependencies/RequireContextDependency": () => - __webpack_require__(46917), - "dependencies/RequireEnsureDependenciesBlock": () => - __webpack_require__(27153), - "dependencies/RequireEnsureDependency": () => - __webpack_require__(27223), - "dependencies/RequireEnsureItemDependency": () => - __webpack_require__(50329), - "dependencies/RequireHeaderDependency": () => - __webpack_require__(89183), - "dependencies/RequireIncludeDependency": () => - __webpack_require__(71284), - "dependencies/RequireIncludeDependencyParserPlugin": () => - __webpack_require__(35768), - "dependencies/RequireResolveContextDependency": () => - __webpack_require__(55627), - "dependencies/RequireResolveDependency": () => - __webpack_require__(68582), - "dependencies/RequireResolveHeaderDependency": () => - __webpack_require__(9880), - "dependencies/RuntimeRequirementsDependency": () => - __webpack_require__(24187), - "dependencies/StaticExportsDependency": () => - __webpack_require__(91418), - "dependencies/SystemPlugin": () => __webpack_require__(97981), - "dependencies/UnsupportedDependency": () => - __webpack_require__(51669), - "dependencies/URLDependency": () => __webpack_require__(58612), - "dependencies/WebAssemblyExportImportedDependency": () => - __webpack_require__(52204), - "dependencies/WebAssemblyImportDependency": () => - __webpack_require__(5239), - "dependencies/WebpackIsIncludedDependency": () => - __webpack_require__(26505), - "dependencies/WorkerDependency": () => - __webpack_require__(1466), - "json/JsonData": () => __webpack_require__(90490), - "optimize/ConcatenatedModule": () => - __webpack_require__(97198), - DelegatedModule: () => __webpack_require__(28623), - DependenciesBlock: () => __webpack_require__(71040), - DllModule: () => __webpack_require__(28280), - ExternalModule: () => __webpack_require__(73071), - FileSystemInfo: () => __webpack_require__(79453), - InitFragment: () => __webpack_require__(55870), - InvalidDependenciesModuleWarning: () => - __webpack_require__(68257), - Module: () => __webpack_require__(73208), - ModuleBuildError: () => __webpack_require__(21305), - ModuleDependencyWarning: () => __webpack_require__(29656), - ModuleError: () => __webpack_require__(23744), - ModuleGraph: () => __webpack_require__(99988), - ModuleParseError: () => __webpack_require__(58443), - ModuleWarning: () => __webpack_require__(11234), - NormalModule: () => __webpack_require__(39), - RawDataUrlModule: () => __webpack_require__(19684), - RawModule: () => __webpack_require__(84929), - "sharing/ConsumeSharedModule": () => - __webpack_require__(62286), - "sharing/ConsumeSharedFallbackDependency": () => - __webpack_require__(58831), - "sharing/ProvideSharedModule": () => - __webpack_require__(50821), - "sharing/ProvideSharedDependency": () => - __webpack_require__(1798), - "sharing/ProvideForSharedDependency": () => - __webpack_require__(40017), - UnsupportedFeatureWarning: () => __webpack_require__(42495), - "util/LazySet": () => __webpack_require__(38938), - UnhandledSchemeError: () => __webpack_require__(68099), - NodeStuffInWebError: () => __webpack_require__(6325), - WebpackError: () => __webpack_require__(53799), +const path = __webpack_require__(71017); +const DescriptionFileUtils = __webpack_require__(25424); +const forEachBail = __webpack_require__(78565); +const { processExportsField } = __webpack_require__(55863); +const { parseIdentifier } = __webpack_require__(71053); +const { checkExportsFieldTarget } = __webpack_require__(67079); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./util/entrypoints").ExportsField} ExportsField */ +/** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ + +module.exports = class ExportsFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} conditionNames condition names + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} target target + */ + constructor(source, conditionNames, fieldNamePath, target) { + this.source = source; + this.target = target; + this.conditionNames = conditionNames; + this.fieldName = fieldNamePath; + /** @type {WeakMap} */ + this.fieldProcessorCache = new WeakMap(); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ExportsFieldPlugin", (request, resolveContext, callback) => { + // When there is no description file, abort + if (!request.descriptionFilePath) return callback(); + if ( + // When the description file is inherited from parent, abort + // (There is no description file inside of this package) + request.relativePath !== "." || + request.request === undefined + ) + return callback(); + + const remainingRequest = + request.query || request.fragment + ? (request.request === "." ? "./" : request.request) + + request.query + + request.fragment + : request.request; + /** @type {ExportsField|null} */ + const exportsField = DescriptionFileUtils.getField( + request.descriptionFileData, + this.fieldName + ); + if (!exportsField) return callback(); + + if (request.directory) { + return callback( + new Error( + `Resolving to directories is not possible with the exports field (request was ${remainingRequest}/)` + ) + ); + } + + let paths; + + try { + // We attach the cache to the description file instead of the exportsField value + // because we use a WeakMap and the exportsField could be a string too. + // Description file is always an object when exports field can be accessed. + let fieldProcessor = this.fieldProcessorCache.get( + request.descriptionFileData + ); + if (fieldProcessor === undefined) { + fieldProcessor = processExportsField(exportsField); + this.fieldProcessorCache.set( + request.descriptionFileData, + fieldProcessor + ); + } + paths = fieldProcessor(remainingRequest, this.conditionNames); + } catch (err) { + if (resolveContext.log) { + resolveContext.log( + `Exports field in ${request.descriptionFilePath} can't be processed: ${err}` + ); + } + return callback(err); + } + + if (paths.length === 0) { + return callback( + new Error( + `Package path ${remainingRequest} is not exported from package ${request.descriptionFileRoot} (see exports field in ${request.descriptionFilePath})` + ) + ); + } + + forEachBail( + paths, + (p, callback) => { + const parsedIdentifier = parseIdentifier(p); + + if (!parsedIdentifier) return callback(); + + const [relativePath, query, fragment] = parsedIdentifier; + + const error = checkExportsFieldTarget(relativePath); - "util/registerExternalSerializer": () => { - // already registered + if (error) { + return callback(error); + } + + const obj = { + ...request, + request: undefined, + path: path.join( + /** @type {string} */ (request.descriptionFileRoot), + relativePath + ), + relativePath, + query, + fragment + }; + + resolver.doResolve( + target, + obj, + "using exports field: " + p, + resolveContext, + callback + ); + }, + (err, result) => callback(err, result || null) + ); + }); } }; /***/ }), -/***/ 33032: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 50295: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const { register } = __webpack_require__(8282); - -class ClassSerializer { - constructor(Constructor) { - this.Constructor = Constructor; - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - serialize(obj, context) { - obj.serialize(context); +module.exports = class FileExistsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; } - deserialize(context) { - if (typeof this.Constructor.deserialize === "function") { - return this.Constructor.deserialize(context); - } - const obj = new this.Constructor(); - obj.deserialize(context); - return obj; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const fs = resolver.fileSystem; + resolver + .getHook(this.source) + .tapAsync("FileExistsPlugin", (request, resolveContext, callback) => { + const file = request.path; + if (!file) return callback(); + fs.stat(file, (err, stat) => { + if (err || !stat) { + if (resolveContext.missingDependencies) + resolveContext.missingDependencies.add(file); + if (resolveContext.log) resolveContext.log(file + " doesn't exist"); + return callback(); + } + if (!stat.isFile()) { + if (resolveContext.missingDependencies) + resolveContext.missingDependencies.add(file); + if (resolveContext.log) resolveContext.log(file + " is not a file"); + return callback(); + } + if (resolveContext.fileDependencies) + resolveContext.fileDependencies.add(file); + resolver.doResolve( + target, + request, + "existing file: " + file, + resolveContext, + callback + ); + }); + }); } -} - -module.exports = (Constructor, request, name = null) => { - register(Constructor, request, name, new ClassSerializer(Constructor)); }; /***/ }), -/***/ 78676: -/***/ (function(module) { +/***/ 7317: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop */ -/** @template T @typedef {function(): T} FunctionReturning */ +const path = __webpack_require__(71017); +const DescriptionFileUtils = __webpack_require__(25424); +const forEachBail = __webpack_require__(78565); +const { processImportsField } = __webpack_require__(55863); +const { parseIdentifier } = __webpack_require__(71053); -/** - * @template T - * @param {FunctionReturning} fn memorized function - * @returns {FunctionReturning} new function - */ -const memoize = fn => { - let cache = false; - /** @type {T} */ - let result = undefined; - return () => { - if (cache) { - return result; - } else { - result = fn(); - cache = true; - // Allow to clean up memory for fn - // and all dependent resources - fn = undefined; - return result; - } - }; -}; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ +/** @typedef {import("./util/entrypoints").ImportsField} ImportsField */ -module.exports = memoize; +const dotCode = ".".charCodeAt(0); + +module.exports = class ImportsFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} conditionNames condition names + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} targetFile target file + * @param {string | ResolveStepHook} targetPackage target package + */ + constructor( + source, + conditionNames, + fieldNamePath, + targetFile, + targetPackage + ) { + this.source = source; + this.targetFile = targetFile; + this.targetPackage = targetPackage; + this.conditionNames = conditionNames; + this.fieldName = fieldNamePath; + /** @type {WeakMap} */ + this.fieldProcessorCache = new WeakMap(); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const targetFile = resolver.ensureHook(this.targetFile); + const targetPackage = resolver.ensureHook(this.targetPackage); + + resolver + .getHook(this.source) + .tapAsync("ImportsFieldPlugin", (request, resolveContext, callback) => { + // When there is no description file, abort + if (!request.descriptionFilePath || request.request === undefined) { + return callback(); + } + + const remainingRequest = + request.request + request.query + request.fragment; + /** @type {ImportsField|null} */ + const importsField = DescriptionFileUtils.getField( + request.descriptionFileData, + this.fieldName + ); + if (!importsField) return callback(); + + if (request.directory) { + return callback( + new Error( + `Resolving to directories is not possible with the imports field (request was ${remainingRequest}/)` + ) + ); + } + + let paths; + + try { + // We attach the cache to the description file instead of the importsField value + // because we use a WeakMap and the importsField could be a string too. + // Description file is always an object when exports field can be accessed. + let fieldProcessor = this.fieldProcessorCache.get( + request.descriptionFileData + ); + if (fieldProcessor === undefined) { + fieldProcessor = processImportsField(importsField); + this.fieldProcessorCache.set( + request.descriptionFileData, + fieldProcessor + ); + } + paths = fieldProcessor(remainingRequest, this.conditionNames); + } catch (err) { + if (resolveContext.log) { + resolveContext.log( + `Imports field in ${request.descriptionFilePath} can't be processed: ${err}` + ); + } + return callback(err); + } + + if (paths.length === 0) { + return callback( + new Error( + `Package import ${remainingRequest} is not imported from package ${request.descriptionFileRoot} (see imports field in ${request.descriptionFilePath})` + ) + ); + } + + forEachBail( + paths, + (p, callback) => { + const parsedIdentifier = parseIdentifier(p); + + if (!parsedIdentifier) return callback(); + + const [path_, query, fragment] = parsedIdentifier; + + switch (path_.charCodeAt(0)) { + // should be relative + case dotCode: { + const obj = { + ...request, + request: undefined, + path: path.join( + /** @type {string} */ (request.descriptionFileRoot), + path_ + ), + relativePath: path_, + query, + fragment + }; + + resolver.doResolve( + targetFile, + obj, + "using imports field: " + p, + resolveContext, + callback + ); + break; + } + + // package resolving + default: { + const obj = { + ...request, + request: path_, + relativePath: path_, + fullySpecified: true, + query, + fragment + }; + + resolver.doResolve( + targetPackage, + obj, + "using imports field: " + p, + resolveContext, + callback + ); + } + } + }, + (err, result) => callback(err, result || null) + ); + }); + } +}; /***/ }), -/***/ 70002: +/***/ 35949: /***/ (function(module) { "use strict"; @@ -134574,49 +135099,68 @@ module.exports = memoize; -const SAFE_LIMIT = 0x80000000; -const SAFE_PART = SAFE_LIMIT - 1; -const COUNT = 4; -const arr = [0, 0, 0, 0, 0]; -const primes = [3, 7, 17, 19]; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -module.exports = (str, range) => { - arr.fill(0); - for (let i = 0; i < str.length; i++) { - const c = str.charCodeAt(i); - for (let j = 0; j < COUNT; j++) { - const p = (j + COUNT - 1) % COUNT; - arr[j] = (arr[j] + c * primes[j] + arr[p]) & SAFE_PART; - } - for (let j = 0; j < COUNT; j++) { - const q = arr[j] % COUNT; - arr[j] = arr[j] ^ (arr[q] >> 1); - } +const namespaceStartCharCode = "@".charCodeAt(0); + +module.exports = class JoinRequestPartPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; } - if (range <= SAFE_PART) { - let sum = 0; - for (let j = 0; j < COUNT; j++) { - sum = (sum + arr[j]) % range; - } - return sum; - } else { - let sum1 = 0; - let sum2 = 0; - const rangeExt = Math.floor(range / SAFE_LIMIT); - for (let j = 0; j < COUNT; j += 2) { - sum1 = (sum1 + arr[j]) & SAFE_PART; - } - for (let j = 1; j < COUNT; j += 2) { - sum2 = (sum2 + arr[j]) % rangeExt; - } - return (sum2 * SAFE_LIMIT + sum1) % range; + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "JoinRequestPartPlugin", + (request, resolveContext, callback) => { + const req = request.request || ""; + let i = req.indexOf("/", 3); + + if (i >= 0 && req.charCodeAt(2) === namespaceStartCharCode) { + i = req.indexOf("/", i + 1); + } + + let moduleName, remainingRequest, fullySpecified; + if (i < 0) { + moduleName = req; + remainingRequest = "."; + fullySpecified = false; + } else { + moduleName = req.slice(0, i); + remainingRequest = "." + req.slice(i); + fullySpecified = request.fullySpecified; + } + const obj = { + ...request, + path: resolver.join(request.path, moduleName), + relativePath: + request.relativePath && + resolver.join(request.relativePath, moduleName), + request: remainingRequest, + fullySpecified + }; + resolver.doResolve(target, obj, null, resolveContext, callback); + } + ); } }; /***/ }), -/***/ 42791: +/***/ 5190: /***/ (function(module) { "use strict"; @@ -134627,66 +135171,45 @@ module.exports = (str, range) => { -/** - * @template T - * @template {Error} E - * @param {Iterable} items initial items - * @param {number} concurrency number of items running in parallel - * @param {function(T, function(T): void, function(E=): void): void} processor worker which pushes more items - * @param {function(E=): void} callback all items processed - * @returns {void} - */ -const processAsyncTree = (items, concurrency, processor, callback) => { - const queue = Array.from(items); - if (queue.length === 0) return callback(); - let processing = 0; - let finished = false; - let processScheduled = true; - - const push = item => { - queue.push(item); - if (!processScheduled && processing < concurrency) { - processScheduled = true; - process.nextTick(processQueue); - } - }; - - const processorCallback = err => { - processing--; - if (err && !finished) { - finished = true; - callback(err); - return; - } - if (!processScheduled) { - processScheduled = true; - process.nextTick(processQueue); - } - }; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - const processQueue = () => { - if (finished) return; - while (processing < concurrency && queue.length > 0) { - processing++; - const item = queue.pop(); - processor(item, push, processorCallback); - } - processScheduled = false; - if (queue.length === 0 && processing === 0 && !finished) { - finished = true; - callback(); - } - }; +module.exports = class JoinRequestPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } - processQueue(); + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("JoinRequestPlugin", (request, resolveContext, callback) => { + const obj = { + ...request, + path: resolver.join(request.path, request.request), + relativePath: + request.relativePath && + resolver.join(request.relativePath, request.request), + request: undefined + }; + resolver.doResolve(target, obj, null, resolveContext, callback); + }); + } }; -module.exports = processAsyncTree; - /***/ }), -/***/ 54190: +/***/ 5049: /***/ (function(module) { "use strict"; @@ -134697,83 +135220,55 @@ module.exports = processAsyncTree; -const SAFE_IDENTIFIER = /^[_a-zA-Z$][_a-zA-Z$0-9]*$/; -const RESERVED_IDENTIFIER = new Set([ - "break", - "case", - "catch", - "class", - "const", - "continue", - "debugger", - "default", - "delete", - "do", - "else", - "export", - "extends", - "finally", - "for", - "function", - "if", - "import", - "in", - "instanceof", - "new", - "return", - "super", - "switch", - "this", - "throw", - "try", - "typeof", - "var", - "void", - "while", - "with", - "enum", - // strict mode - "implements", - "interface", - "let", - "package", - "private", - "protected", - "public", - "static", - "yield", - "yield", - // module code - "await", - // skip future reserved keywords defined under ES1 till ES3 - // additional - "null", - "true", - "false" -]); +/** @typedef {import("./Resolver")} Resolver */ -const propertyAccess = (properties, start = 0) => { - let str = ""; - for (let i = start; i < properties.length; i++) { - const p = properties[i]; - if (`${+p}` === p) { - str += `[${p}]`; - } else if (SAFE_IDENTIFIER.test(p) && !RESERVED_IDENTIFIER.has(p)) { - str += `.${p}`; - } else { - str += `[${JSON.stringify(p)}]`; - } +module.exports = class LogInfoPlugin { + constructor(source) { + this.source = source; } - return str; -}; -module.exports = propertyAccess; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const source = this.source; + resolver + .getHook(this.source) + .tapAsync("LogInfoPlugin", (request, resolveContext, callback) => { + if (!resolveContext.log) return callback(); + const log = resolveContext.log; + const prefix = "[" + source + "] "; + if (request.path) + log(prefix + "Resolving in directory: " + request.path); + if (request.request) + log(prefix + "Resolving request: " + request.request); + if (request.module) log(prefix + "Request is an module request."); + if (request.directory) log(prefix + "Request is a directory request."); + if (request.query) + log(prefix + "Resolving request query: " + request.query); + if (request.fragment) + log(prefix + "Resolving request fragment: " + request.fragment); + if (request.descriptionFilePath) + log( + prefix + "Has description data from " + request.descriptionFilePath + ); + if (request.relativePath) + log( + prefix + + "Relative path from description file is: " + + request.relativePath + ); + callback(); + }); + } +}; /***/ }), -/***/ 26611: -/***/ (function(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { +/***/ 47450: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -134783,342 +135278,229 @@ module.exports = propertyAccess; -const { register } = __webpack_require__(8282); +const path = __webpack_require__(71017); +const DescriptionFileUtils = __webpack_require__(25424); -const Position = /** @type {TODO} */ (__webpack_require__(31988).Position); -const SourceLocation = (__webpack_require__(31988).SourceLocation); -const ValidationError = (__webpack_require__(54983)/* ["default"] */ .Z); -const { - CachedSource, - ConcatSource, - OriginalSource, - PrefixSource, - RawSource, - ReplaceSource, - SourceMapSource -} = __webpack_require__(51255); +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {{name: string|Array, forceRelative: boolean}} MainFieldOptions */ -/** @typedef {import("acorn").Position} Position */ -/** @typedef {import("../Dependency").RealDependencyLocation} RealDependencyLocation */ -/** @typedef {import("../Dependency").SourcePosition} SourcePosition */ -/** @typedef {import("./serialization").ObjectDeserializerContext} ObjectDeserializerContext */ -/** @typedef {import("./serialization").ObjectSerializerContext} ObjectSerializerContext */ +const alreadyTriedMainField = Symbol("alreadyTriedMainField"); -/** @typedef {ObjectSerializerContext & { writeLazy?: (any) => void }} WebpackObjectSerializerContext */ +module.exports = class MainFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {MainFieldOptions} options options + * @param {string | ResolveStepHook} target target + */ + constructor(source, options, target) { + this.source = source; + this.options = options; + this.target = target; + } -const CURRENT_MODULE = "webpack/lib/util/registerExternalSerializer"; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("MainFieldPlugin", (request, resolveContext, callback) => { + if ( + request.path !== request.descriptionFileRoot || + request[alreadyTriedMainField] === request.descriptionFilePath || + !request.descriptionFilePath + ) + return callback(); + const filename = path.basename(request.descriptionFilePath); + let mainModule = DescriptionFileUtils.getField( + request.descriptionFileData, + this.options.name + ); -register( - CachedSource, - CURRENT_MODULE, - "webpack-sources/CachedSource", - new (class CachedSourceSerializer { - /** - * @param {CachedSource} source the cached source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write, writeLazy }) { - if (writeLazy) { - writeLazy(source.originalLazy()); - } else { - write(source.original()); - } - write(source.getCachedData()); - } + if ( + !mainModule || + typeof mainModule !== "string" || + mainModule === "." || + mainModule === "./" + ) { + return callback(); + } + if (this.options.forceRelative && !/^\.\.?\//.test(mainModule)) + mainModule = "./" + mainModule; + const obj = { + ...request, + request: mainModule, + module: false, + directory: mainModule.endsWith("/"), + [alreadyTriedMainField]: request.descriptionFilePath + }; + return resolver.doResolve( + target, + obj, + "use " + + mainModule + + " from " + + this.options.name + + " in " + + filename, + resolveContext, + callback + ); + }); + } +}; - /** - * @param {ObjectDeserializerContext} context context - * @returns {CachedSource} cached source - */ - deserialize({ read }) { - const source = read(); - const cachedData = read(); - return new CachedSource(source, cachedData); - } - })() -); -register( - RawSource, - CURRENT_MODULE, - "webpack-sources/RawSource", - new (class RawSourceSerializer { - /** - * @param {RawSource} source the raw source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write }) { - write(source.buffer()); - write(!source.isBuffer()); - } +/***/ }), - /** - * @param {ObjectDeserializerContext} context context - * @returns {RawSource} raw source - */ - deserialize({ read }) { - const source = read(); - const convertToString = read(); - return new RawSource(source, convertToString); - } - })() -); +/***/ 48506: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -register( - ConcatSource, - CURRENT_MODULE, - "webpack-sources/ConcatSource", - new (class ConcatSourceSerializer { - /** - * @param {ConcatSource} source the concat source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write }) { - write(source.getChildren()); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @param {ObjectDeserializerContext} context context - * @returns {ConcatSource} concat source - */ - deserialize({ read }) { - const source = new ConcatSource(); - source.addAllSkipOptimizing(read()); - return source; - } - })() -); -register( - PrefixSource, - CURRENT_MODULE, - "webpack-sources/PrefixSource", - new (class PrefixSourceSerializer { - /** - * @param {PrefixSource} source the prefix source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write }) { - write(source.getPrefix()); - write(source.original()); - } - /** - * @param {ObjectDeserializerContext} context context - * @returns {PrefixSource} prefix source - */ - deserialize({ read }) { - return new PrefixSource(read(), read()); - } - })() -); +const forEachBail = __webpack_require__(78565); +const getPaths = __webpack_require__(82918); -register( - ReplaceSource, - CURRENT_MODULE, - "webpack-sources/ReplaceSource", - new (class ReplaceSourceSerializer { - /** - * @param {ReplaceSource} source the replace source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write }) { - write(source.original()); - write(source.getName()); - const replacements = source.getReplacements(); - write(replacements.length); - for (const repl of replacements) { - write(repl.start); - write(repl.end); - } - for (const repl of replacements) { - write(repl.content); - write(repl.name); - } - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ - /** - * @param {ObjectDeserializerContext} context context - * @returns {ReplaceSource} replace source - */ - deserialize({ read }) { - const source = new ReplaceSource(read(), read()); - const len = read(); - const startEndBuffer = []; - for (let i = 0; i < len; i++) { - startEndBuffer.push(read(), read()); - } - let j = 0; - for (let i = 0; i < len; i++) { - source.replace( - startEndBuffer[j++], - startEndBuffer[j++], - read(), - read() - ); - } - return source; - } - })() -); +module.exports = class ModulesInHierachicDirectoriesPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | Array} directories directories + * @param {string | ResolveStepHook} target target + */ + constructor(source, directories, target) { + this.source = source; + this.directories = /** @type {Array} */ ([]).concat(directories); + this.target = target; + } -register( - OriginalSource, - CURRENT_MODULE, - "webpack-sources/OriginalSource", - new (class OriginalSourceSerializer { - /** - * @param {OriginalSource} source the original source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write }) { - write(source.buffer()); - write(source.getName()); - } + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "ModulesInHierachicDirectoriesPlugin", + (request, resolveContext, callback) => { + const fs = resolver.fileSystem; + const addrs = getPaths(request.path) + .paths.map(p => { + return this.directories.map(d => resolver.join(p, d)); + }) + .reduce((array, p) => { + array.push.apply(array, p); + return array; + }, []); + forEachBail( + addrs, + (addr, callback) => { + fs.stat(addr, (err, stat) => { + if (!err && stat && stat.isDirectory()) { + const obj = { + ...request, + path: addr, + request: "./" + request.request, + module: false + }; + const message = "looking for modules in " + addr; + return resolver.doResolve( + target, + obj, + message, + resolveContext, + callback + ); + } + if (resolveContext.log) + resolveContext.log( + addr + " doesn't exist or is not a directory" + ); + if (resolveContext.missingDependencies) + resolveContext.missingDependencies.add(addr); + return callback(); + }); + }, + callback + ); + } + ); + } +}; - /** - * @param {ObjectDeserializerContext} context context - * @returns {OriginalSource} original source - */ - deserialize({ read }) { - const buffer = read(); - const name = read(); - return new OriginalSource(buffer, name); - } - })() -); -register( - SourceLocation, - CURRENT_MODULE, - "acorn/SourceLocation", - new (class SourceLocationSerializer { - /** - * @param {SourceLocation} loc the location to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(loc, { write }) { - write(loc.start.line); - write(loc.start.column); - write(loc.end.line); - write(loc.end.column); - } +/***/ }), - /** - * @param {ObjectDeserializerContext} context context - * @returns {RealDependencyLocation} location - */ - deserialize({ read }) { - return { - start: { - line: read(), - column: read() - }, - end: { - line: read(), - column: read() - } - }; - } - })() -); +/***/ 88138: +/***/ (function(module) { -register( - Position, - CURRENT_MODULE, - "acorn/Position", - new (class PositionSerializer { - /** - * @param {Position} pos the position to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(pos, { write }) { - write(pos.line); - write(pos.column); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @param {ObjectDeserializerContext} context context - * @returns {SourcePosition} position - */ - deserialize({ read }) { - return { - line: read(), - column: read() - }; - } - })() -); -register( - SourceMapSource, - CURRENT_MODULE, - "webpack-sources/SourceMapSource", - new (class SourceMapSourceSerializer { - /** - * @param {SourceMapSource} source the source map source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(source, { write }) { - write(source.getArgsAsBuffers()); - } - /** - * @param {ObjectDeserializerContext} context context - * @returns {SourceMapSource} source source map source - */ - deserialize({ read }) { - // @ts-expect-error - return new SourceMapSource(...read()); - } - })() -); +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -register( - ValidationError, - CURRENT_MODULE, - "schema-utils/ValidationError", - new (class ValidationErrorSerializer { - // TODO error should be ValidationError, but this fails the type checks - /** - * @param {TODO} error the source map source to be serialized - * @param {WebpackObjectSerializerContext} context context - * @returns {void} - */ - serialize(error, { write }) { - write(error.errors); - write(error.schema); - write({ - name: error.headerName, - baseDataPath: error.baseDataPath, - postFormatter: error.postFormatter - }); - } +module.exports = class ModulesInRootPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} path path + * @param {string | ResolveStepHook} target target + */ + constructor(source, path, target) { + this.source = source; + this.path = path; + this.target = target; + } - /** - * @param {ObjectDeserializerContext} context context - * @returns {TODO} error - */ - deserialize({ read }) { - return new ValidationError(read(), read(), read()); - } - })() -); + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ModulesInRootPlugin", (request, resolveContext, callback) => { + const obj = { + ...request, + path: this.path, + request: "./" + request.request, + module: false + }; + resolver.doResolve( + target, + obj, + "looking for modules in " + this.path, + resolveContext, + callback + ); + }); + } +}; /***/ }), -/***/ 17156: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 40777: +/***/ (function(module) { "use strict"; /* @@ -135128,1249 +135510,714 @@ register( -const SortableSet = __webpack_require__(13098); - -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */ - -/** @typedef {string | SortableSet | undefined} RuntimeSpec */ -/** @typedef {RuntimeSpec | boolean} RuntimeCondition */ +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** - * @param {Compilation} compilation the compilation - * @param {string} name name of the entry - * @param {EntryOptions=} options optionally already received entry options - * @returns {RuntimeSpec} runtime - */ -exports.getEntryRuntime = (compilation, name, options) => { - let dependOn; - let runtime; - if (options) { - ({ dependOn, runtime } = options); - } else { - const entry = compilation.entries.get(name); - if (!entry) return name; - ({ dependOn, runtime } = entry.options); - } - if (dependOn) { - /** @type {RuntimeSpec} */ - let result = undefined; - const queue = new Set(dependOn); - for (const name of queue) { - const dep = compilation.entries.get(name); - if (!dep) continue; - const { dependOn, runtime } = dep.options; - if (dependOn) { - for (const name of dependOn) { - queue.add(name); - } - } else { - result = mergeRuntimeOwned(result, runtime || name); - } - } - return result || name; - } else { - return runtime || name; +module.exports = class NextPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; } -}; -/** - * @param {RuntimeSpec} runtime runtime - * @param {function(string): void} fn functor - * @param {boolean} deterministicOrder enforce a deterministic order - * @returns {void} - */ -exports.forEachRuntime = (runtime, fn, deterministicOrder = false) => { - if (runtime === undefined) { - fn(undefined); - } else if (typeof runtime === "string") { - fn(runtime); - } else { - if (deterministicOrder) runtime.sort(); - for (const r of runtime) { - fn(r); - } + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("NextPlugin", (request, resolveContext, callback) => { + resolver.doResolve(target, request, null, resolveContext, callback); + }); } }; -const getRuntimesKey = set => { - set.sort(); - return Array.from(set).join("\n"); -}; - -/** - * @param {RuntimeSpec} runtime runtime(s) - * @returns {string} key of runtimes - */ -const getRuntimeKey = runtime => { - if (runtime === undefined) return "*"; - if (typeof runtime === "string") return runtime; - return runtime.getFromUnorderedCache(getRuntimesKey); -}; -exports.getRuntimeKey = getRuntimeKey; -/** - * @param {string} key key of runtimes - * @returns {RuntimeSpec} runtime(s) - */ -const keyToRuntime = key => { - if (key === "*") return undefined; - const items = key.split("\n"); - if (items.length === 1) return items[0]; - return new SortableSet(items); -}; -exports.keyToRuntime = keyToRuntime; +/***/ }), -const getRuntimesString = set => { - set.sort(); - return Array.from(set).join("+"); -}; +/***/ 97849: +/***/ (function(module) { -/** - * @param {RuntimeSpec} runtime runtime(s) - * @returns {string} readable version - */ -const runtimeToString = runtime => { - if (runtime === undefined) return "*"; - if (typeof runtime === "string") return runtime; - return runtime.getFromUnorderedCache(getRuntimesString); -}; -exports.runtimeToString = runtimeToString; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * @param {RuntimeCondition} runtimeCondition runtime condition - * @returns {string} readable version - */ -exports.runtimeConditionToString = runtimeCondition => { - if (runtimeCondition === true) return "true"; - if (runtimeCondition === false) return "false"; - return runtimeToString(runtimeCondition); -}; -/** - * @param {RuntimeSpec} a first - * @param {RuntimeSpec} b second - * @returns {boolean} true, when they are equal - */ -const runtimeEqual = (a, b) => { - if (a === b) { - return true; - } else if ( - a === undefined || - b === undefined || - typeof a === "string" || - typeof b === "string" - ) { - return false; - } else if (a.size !== b.size) { - return false; - } else { - a.sort(); - b.sort(); - const aIt = a[Symbol.iterator](); - const bIt = b[Symbol.iterator](); - for (;;) { - const aV = aIt.next(); - if (aV.done) return true; - const bV = bIt.next(); - if (aV.value !== bV.value) return false; - } - } -}; -exports.runtimeEqual = runtimeEqual; -/** - * @param {RuntimeSpec} a first - * @param {RuntimeSpec} b second - * @returns {-1|0|1} compare - */ -exports.compareRuntime = (a, b) => { - if (a === b) { - return 0; - } else if (a === undefined) { - return -1; - } else if (b === undefined) { - return 1; - } else { - const aKey = getRuntimeKey(a); - const bKey = getRuntimeKey(b); - if (aKey < bKey) return -1; - if (aKey > bKey) return 1; - return 0; - } -}; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** - * @param {RuntimeSpec} a first - * @param {RuntimeSpec} b second - * @returns {RuntimeSpec} merged - */ -const mergeRuntime = (a, b) => { - if (a === undefined) { - return b; - } else if (b === undefined) { - return a; - } else if (a === b) { - return a; - } else if (typeof a === "string") { - if (typeof b === "string") { - const set = new SortableSet(); - set.add(a); - set.add(b); - return set; - } else if (b.has(a)) { - return b; - } else { - const set = new SortableSet(b); - set.add(a); - return set; - } - } else { - if (typeof b === "string") { - if (a.has(b)) return a; - const set = new SortableSet(a); - set.add(b); - return set; - } else { - const set = new SortableSet(a); - for (const item of b) set.add(item); - if (set.size === a.size) return a; - return set; - } +module.exports = class ParsePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Partial} requestOptions request options + * @param {string | ResolveStepHook} target target + */ + constructor(source, requestOptions, target) { + this.source = source; + this.requestOptions = requestOptions; + this.target = target; } -}; -exports.mergeRuntime = mergeRuntime; -/** - * @param {RuntimeCondition} a first - * @param {RuntimeCondition} b second - * @param {RuntimeSpec} runtime full runtime - * @returns {RuntimeCondition} result - */ -exports.mergeRuntimeCondition = (a, b, runtime) => { - if (a === false) return b; - if (b === false) return a; - if (a === true || b === true) return true; - const merged = mergeRuntime(a, b); - if (merged === undefined) return undefined; - if (typeof merged === "string") { - if (typeof runtime === "string" && merged === runtime) return true; - return merged; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ParsePlugin", (request, resolveContext, callback) => { + const parsed = resolver.parse(/** @type {string} */ (request.request)); + const obj = { ...request, ...parsed, ...this.requestOptions }; + if (request.query && !parsed.query) { + obj.query = request.query; + } + if (request.fragment && !parsed.fragment) { + obj.fragment = request.fragment; + } + if (parsed && resolveContext.log) { + if (parsed.module) resolveContext.log("Parsed request is a module"); + if (parsed.directory) + resolveContext.log("Parsed request is a directory"); + } + // There is an edge-case where a request with # can be a path or a fragment -> try both + if (obj.request && !obj.query && obj.fragment) { + const directory = obj.fragment.endsWith("/"); + const alternative = { + ...obj, + directory, + request: + obj.request + + (obj.directory ? "/" : "") + + (directory ? obj.fragment.slice(0, -1) : obj.fragment), + fragment: "" + }; + resolver.doResolve( + target, + alternative, + null, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + resolver.doResolve(target, obj, null, resolveContext, callback); + } + ); + return; + } + resolver.doResolve(target, obj, null, resolveContext, callback); + }); } - if (typeof runtime === "string" || runtime === undefined) return merged; - if (merged.size === runtime.size) return true; - return merged; }; -/** - * @param {RuntimeSpec | true} a first - * @param {RuntimeSpec | true} b second - * @param {RuntimeSpec} runtime full runtime - * @returns {RuntimeSpec | true} result - */ -exports.mergeRuntimeConditionNonFalse = (a, b, runtime) => { - if (a === true || b === true) return true; - const merged = mergeRuntime(a, b); - if (merged === undefined) return undefined; - if (typeof merged === "string") { - if (typeof runtime === "string" && merged === runtime) return true; - return merged; - } - if (typeof runtime === "string" || runtime === undefined) return merged; - if (merged.size === runtime.size) return true; - return merged; -}; -/** - * @param {RuntimeSpec} a first (may be modified) - * @param {RuntimeSpec} b second - * @returns {RuntimeSpec} merged - */ -const mergeRuntimeOwned = (a, b) => { - if (b === undefined) { - return a; - } else if (a === b) { - return a; - } else if (a === undefined) { - if (typeof b === "string") { - return b; - } else { - return new SortableSet(b); - } - } else if (typeof a === "string") { - if (typeof b === "string") { - const set = new SortableSet(); - set.add(a); - set.add(b); - return set; - } else { - const set = new SortableSet(b); - set.add(a); - return set; - } - } else { - if (typeof b === "string") { - a.add(b); - return a; - } else { - for (const item of b) a.add(item); - return a; - } - } -}; -exports.mergeRuntimeOwned = mergeRuntimeOwned; +/***/ }), -/** - * @param {RuntimeSpec} a first - * @param {RuntimeSpec} b second - * @returns {RuntimeSpec} merged - */ -exports.intersectRuntime = (a, b) => { - if (a === undefined) { - return b; - } else if (b === undefined) { - return a; - } else if (a === b) { - return a; - } else if (typeof a === "string") { - if (typeof b === "string") { - return undefined; - } else if (b.has(a)) { - return a; - } else { - return undefined; - } - } else { - if (typeof b === "string") { - if (a.has(b)) return b; - return undefined; - } else { - const set = new SortableSet(); - for (const item of b) { - if (a.has(item)) set.add(item); - } - if (set.size === 0) return undefined; - if (set.size === 1) for (const item of set) return item; - return set; - } - } -}; +/***/ 44222: +/***/ (function(module) { -/** - * @param {RuntimeSpec} a first - * @param {RuntimeSpec} b second - * @returns {RuntimeSpec} result - */ -const subtractRuntime = (a, b) => { - if (a === undefined) { - return undefined; - } else if (b === undefined) { - return a; - } else if (a === b) { - return undefined; - } else if (typeof a === "string") { - if (typeof b === "string") { - return a; - } else if (b.has(a)) { - return undefined; - } else { - return a; - } - } else { - if (typeof b === "string") { - if (!a.has(b)) return a; - if (a.size === 2) { - for (const item of a) { - if (item !== b) return item; - } - } - const set = new SortableSet(a); - set.delete(b); - } else { - const set = new SortableSet(); - for (const item of a) { - if (!b.has(item)) set.add(item); - } - if (set.size === 0) return undefined; - if (set.size === 1) for (const item of set) return item; - return set; - } - } -}; -exports.subtractRuntime = subtractRuntime; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Maël Nison @arcanis +*/ -/** - * @param {RuntimeCondition} a first - * @param {RuntimeCondition} b second - * @param {RuntimeSpec} runtime runtime - * @returns {RuntimeCondition} result - */ -exports.subtractRuntimeCondition = (a, b, runtime) => { - if (b === true) return false; - if (b === false) return a; - if (a === false) return false; - const result = subtractRuntime(a === true ? runtime : a, b); - return result === undefined ? false : result; -}; -/** - * @param {RuntimeSpec} runtime runtime - * @param {function(RuntimeSpec): boolean} filter filter function - * @returns {boolean | RuntimeSpec} true/false if filter is constant for all runtimes, otherwise runtimes that are active - */ -exports.filterRuntime = (runtime, filter) => { - if (runtime === undefined) return filter(undefined); - if (typeof runtime === "string") return filter(runtime); - let some = false; - let every = true; - let result = undefined; - for (const r of runtime) { - const v = filter(r); - if (v) { - some = true; - result = mergeRuntimeOwned(result, r); - } else { - every = false; - } - } - if (!some) return false; - if (every) return true; - return result; -}; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ /** - * @template T + * @typedef {Object} PnpApiImpl + * @property {function(string, string, object): string} resolveToUnqualified */ -class RuntimeSpecMap { - /** - * @param {RuntimeSpecMap=} clone copy form this - */ - constructor(clone) { - this._mode = clone ? clone._mode : 0; // 0 = empty, 1 = single entry, 2 = map - /** @type {RuntimeSpec} */ - this._singleRuntime = clone ? clone._singleRuntime : undefined; - /** @type {T} */ - this._singleValue = clone ? clone._singleValue : undefined; - /** @type {Map | undefined} */ - this._map = clone && clone._map ? new Map(clone._map) : undefined; - } +module.exports = class PnpPlugin { /** - * @param {RuntimeSpec} runtime the runtimes - * @returns {T} value + * @param {string | ResolveStepHook} source source + * @param {PnpApiImpl} pnpApi pnpApi + * @param {string | ResolveStepHook} target target */ - get(runtime) { - switch (this._mode) { - case 0: - return undefined; - case 1: - return runtimeEqual(this._singleRuntime, runtime) - ? this._singleValue - : undefined; - default: - return this._map.get(getRuntimeKey(runtime)); - } + constructor(source, pnpApi, target) { + this.source = source; + this.pnpApi = pnpApi; + this.target = target; } /** - * @param {RuntimeSpec} runtime the runtimes - * @returns {boolean} true, when the runtime is stored + * @param {Resolver} resolver the resolver + * @returns {void} */ - has(runtime) { - switch (this._mode) { - case 0: - return false; - case 1: - return runtimeEqual(this._singleRuntime, runtime); - default: - return this._map.has(getRuntimeKey(runtime)); - } - } + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("PnpPlugin", (request, resolveContext, callback) => { + const req = request.request; + if (!req) return callback(); - set(runtime, value) { - switch (this._mode) { - case 0: - this._mode = 1; - this._singleRuntime = runtime; - this._singleValue = value; - break; - case 1: - if (runtimeEqual(this._singleRuntime, runtime)) { - this._singleValue = value; - break; - } - this._mode = 2; - this._map = new Map(); - this._map.set(getRuntimeKey(this._singleRuntime), this._singleValue); - this._singleRuntime = undefined; - this._singleValue = undefined; - /* falls through */ - default: - this._map.set(getRuntimeKey(runtime), value); - } - } + // The trailing slash indicates to PnP that this value is a folder rather than a file + const issuer = `${request.path}/`; - provide(runtime, computer) { - switch (this._mode) { - case 0: - this._mode = 1; - this._singleRuntime = runtime; - return (this._singleValue = computer()); - case 1: { - if (runtimeEqual(this._singleRuntime, runtime)) { - return this._singleValue; - } - this._mode = 2; - this._map = new Map(); - this._map.set(getRuntimeKey(this._singleRuntime), this._singleValue); - this._singleRuntime = undefined; - this._singleValue = undefined; - const newValue = computer(); - this._map.set(getRuntimeKey(runtime), newValue); - return newValue; - } - default: { - const key = getRuntimeKey(runtime); - const value = this._map.get(key); - if (value !== undefined) return value; - const newValue = computer(); - this._map.set(key, newValue); - return newValue; - } - } - } + const packageMatch = /^(@[^/]+\/)?[^/]+/.exec(req); + if (!packageMatch) return callback(); - delete(runtime) { - switch (this._mode) { - case 0: - return; - case 1: - if (runtimeEqual(this._singleRuntime, runtime)) { - this._mode = 0; - this._singleRuntime = undefined; - this._singleValue = undefined; - } - return; - default: - this._map.delete(getRuntimeKey(runtime)); - } - } + const packageName = packageMatch[0]; + const innerRequest = `.${req.slice(packageName.length)}`; - update(runtime, fn) { - switch (this._mode) { - case 0: - throw new Error("runtime passed to update must exist"); - case 1: { - if (runtimeEqual(this._singleRuntime, runtime)) { - this._singleValue = fn(this._singleValue); - break; - } - const newValue = fn(undefined); - if (newValue !== undefined) { - this._mode = 2; - this._map = new Map(); - this._map.set(getRuntimeKey(this._singleRuntime), this._singleValue); - this._singleRuntime = undefined; - this._singleValue = undefined; - this._map.set(getRuntimeKey(runtime), newValue); + let resolution; + let apiResolution; + try { + resolution = this.pnpApi.resolveToUnqualified(packageName, issuer, { + considerBuiltins: false + }); + if (resolveContext.fileDependencies) { + apiResolution = this.pnpApi.resolveToUnqualified("pnpapi", issuer, { + considerBuiltins: false + }); + } + } catch (error) { + if ( + error.code === "MODULE_NOT_FOUND" && + error.pnpCode === "UNDECLARED_DEPENDENCY" + ) { + // This is not a PnP managed dependency. + // Try to continue resolving with our alternatives + if (resolveContext.log) { + resolveContext.log(`request is not managed by the pnpapi`); + for (const line of error.message.split("\n").filter(Boolean)) + resolveContext.log(` ${line}`); + } + return callback(); + } + return callback(error); } - break; - } - default: { - const key = getRuntimeKey(runtime); - const oldValue = this._map.get(key); - const newValue = fn(oldValue); - if (newValue !== oldValue) this._map.set(key, newValue); - } - } - } - keys() { - switch (this._mode) { - case 0: - return []; - case 1: - return [this._singleRuntime]; - default: - return Array.from(this._map.keys(), keyToRuntime); - } - } + if (resolution === packageName) return callback(); - values() { - switch (this._mode) { - case 0: - return [][Symbol.iterator](); - case 1: - return [this._singleValue][Symbol.iterator](); - default: - return this._map.values(); - } - } + if (apiResolution && resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(apiResolution); + } - get size() { - if (this._mode <= 1) return this._mode; - return this._map.size; + const obj = { + ...request, + path: resolution, + request: innerRequest, + ignoreSymlinks: true, + fullySpecified: request.fullySpecified && innerRequest !== "." + }; + resolver.doResolve( + target, + obj, + `resolved by pnp to ${resolution}`, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + // Skip alternatives + return callback(null, null); + } + ); + }); } -} +}; -exports.RuntimeSpecMap = RuntimeSpecMap; -class RuntimeSpecSet { - constructor(iterable) { - /** @type {Map} */ - this._map = new Map(); - if (iterable) { - for (const item of iterable) { - this.add(item); - } - } - } +/***/ }), - add(runtime) { - this._map.set(getRuntimeKey(runtime), runtime); - } +/***/ 55516: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - has(runtime) { - return this._map.has(getRuntimeKey(runtime)); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - [Symbol.iterator]() { - return this._map.values(); - } - get size() { - return this._map.size; - } -} -exports.RuntimeSpecSet = RuntimeSpecSet; +const { AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } = __webpack_require__(6967); +const createInnerContext = __webpack_require__(81218); +const { parseIdentifier } = __webpack_require__(71053); +const { + normalize, + cachedJoin: join, + getType, + PathType +} = __webpack_require__(67079); +/** @typedef {import("./ResolverFactory").ResolveOptions} ResolveOptions */ -/***/ }), +/** + * @typedef {Object} FileSystemStats + * @property {function(): boolean} isDirectory + * @property {function(): boolean} isFile + */ -/***/ 19702: -/***/ (function(__unused_webpack_module, exports) { +/** + * @typedef {Object} FileSystemDirent + * @property {Buffer | string} name + * @property {function(): boolean} isDirectory + * @property {function(): boolean} isFile + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @typedef {Object} PossibleFileSystemError + * @property {string=} code + * @property {number=} errno + * @property {string=} path + * @property {string=} syscall + */ +/** + * @template T + * @callback FileSystemCallback + * @param {PossibleFileSystemError & Error | null | undefined} err + * @param {T=} result + */ +/** + * @typedef {Object} FileSystem + * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} readFile + * @property {(function(string, FileSystemCallback<(Buffer | string)[] | FileSystemDirent[]>): void) & function(string, object, FileSystemCallback<(Buffer | string)[] | FileSystemDirent[]>): void} readdir + * @property {((function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void)=} readJson + * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} readlink + * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void=} lstat + * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} stat + */ -/** @typedef {(string|number|undefined|[])[]} SemVerRange */ +/** + * @typedef {Object} SyncFileSystem + * @property {function(string, object=): Buffer | string} readFileSync + * @property {function(string, object=): (Buffer | string)[] | FileSystemDirent[]} readdirSync + * @property {(function(string, object=): object)=} readJsonSync + * @property {function(string, object=): Buffer | string} readlinkSync + * @property {function(string, object=): FileSystemStats=} lstatSync + * @property {function(string, object=): FileSystemStats} statSync + */ /** - * @param {string} str version string - * @returns {(string|number|undefined|[])[]} parsed version + * @typedef {Object} ParsedIdentifier + * @property {string} request + * @property {string} query + * @property {string} fragment + * @property {boolean} directory + * @property {boolean} module + * @property {boolean} file + * @property {boolean} internal */ -const parseVersion = str => { - var splitAndConvert = function (str) { - return str.split(".").map(function (item) { - // eslint-disable-next-line eqeqeq - return +item == item ? +item : item; - }); - }; - var match = /^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str); - /** @type {(string|number|undefined|[])[]} */ - var ver = match[1] ? splitAndConvert(match[1]) : []; - if (match[2]) { - ver.length++; - ver.push.apply(ver, splitAndConvert(match[2])); - } - if (match[3]) { - ver.push([]); - ver.push.apply(ver, splitAndConvert(match[3])); - } - return ver; -}; -exports.parseVersion = parseVersion; -/* eslint-disable eqeqeq */ /** - * @param {string} a version - * @param {string} b version - * @returns {boolean} true, iff a < b + * @typedef {Object} BaseResolveRequest + * @property {string | false} path + * @property {string=} descriptionFilePath + * @property {string=} descriptionFileRoot + * @property {object=} descriptionFileData + * @property {string=} relativePath + * @property {boolean=} ignoreSymlinks + * @property {boolean=} fullySpecified */ -const versionLt = (a, b) => { - // @ts-expect-error - a = parseVersion(a); - // @ts-expect-error - b = parseVersion(b); - var i = 0; - for (;;) { - // a b EOA object undefined number string - // EOA a == b a < b b < a a < b a < b - // object b < a (0) b < a a < b a < b - // undefined a < b a < b (0) a < b a < b - // number b < a b < a b < a (1) a < b - // string b < a b < a b < a b < a (1) - // EOA end of array - // (0) continue on - // (1) compare them via "<" - // Handles first row in table - if (i >= a.length) return i < b.length && (typeof b[i])[0] != "u"; +/** @typedef {BaseResolveRequest & Partial} ResolveRequest */ - var aValue = a[i]; - var aType = (typeof aValue)[0]; +/** + * String with special formatting + * @typedef {string} StackEntry + */ - // Handles first column in table - if (i >= b.length) return aType == "u"; +/** @template T @typedef {{ add: (T) => void }} WriteOnlySet */ - var bValue = b[i]; - var bType = (typeof bValue)[0]; +/** + * Resolve context + * @typedef {Object} ResolveContext + * @property {WriteOnlySet=} contextDependencies + * @property {WriteOnlySet=} fileDependencies files that was found on file system + * @property {WriteOnlySet=} missingDependencies dependencies that was not found on file system + * @property {Set=} stack set of hooks' calls. For instance, `resolve → parsedResolve → describedResolve`, + * @property {(function(string): void)=} log log function + */ - if (aType == bType) { - if (aType != "o" && aType != "u" && aValue != bValue) { - return aValue < bValue; - } - i++; - } else { - // Handles remaining cases - if (aType == "o" && bType == "n") return true; - return bType == "s" || aType == "u"; - } - } -}; -/* eslint-enable eqeqeq */ -exports.versionLt = versionLt; +/** @typedef {AsyncSeriesBailHook<[ResolveRequest, ResolveContext], ResolveRequest | null>} ResolveStepHook */ /** - * @param {string} str range string - * @returns {SemVerRange} parsed range + * @param {string} str input string + * @returns {string} in camel case */ -exports.parseRange = str => { - const splitAndConvert = str => { - return str.split(".").map(item => (`${+item}` === item ? +item : item)); - }; - // see https://docs.npmjs.com/misc/semver#range-grammar for grammar - const parsePartial = str => { - const match = /^([^-+]+)?(?:-([^+]+))?(?:\+(.+))?$/.exec(str); - /** @type {(string|number|undefined|[])[]} */ - const ver = match[1] ? [0, ...splitAndConvert(match[1])] : [0]; - if (match[2]) { - ver.length++; - ver.push.apply(ver, splitAndConvert(match[2])); +function toCamelCase(str) { + return str.replace(/-([a-z])/g, str => str.substr(1).toUpperCase()); +} + +class Resolver { + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @returns {StackEntry} stack entry + */ + static createStackEntry(hook, request) { + return ( + hook.name + + ": (" + + request.path + + ") " + + (request.request || "") + + (request.query || "") + + (request.fragment || "") + + (request.directory ? " directory" : "") + + (request.module ? " module" : "") + ); + } + + /** + * @param {FileSystem} fileSystem a filesystem + * @param {ResolveOptions} options options + */ + constructor(fileSystem, options) { + this.fileSystem = fileSystem; + this.options = options; + this.hooks = { + /** @type {SyncHook<[ResolveStepHook, ResolveRequest], void>} */ + resolveStep: new SyncHook(["hook", "request"], "resolveStep"), + /** @type {SyncHook<[ResolveRequest, Error]>} */ + noResolve: new SyncHook(["request", "error"], "noResolve"), + /** @type {ResolveStepHook} */ + resolve: new AsyncSeriesBailHook( + ["request", "resolveContext"], + "resolve" + ), + /** @type {AsyncSeriesHook<[ResolveRequest, ResolveContext]>} */ + result: new AsyncSeriesHook(["result", "resolveContext"], "result") + }; + } + + /** + * @param {string | ResolveStepHook} name hook name or hook itself + * @returns {ResolveStepHook} the hook + */ + ensureHook(name) { + if (typeof name !== "string") { + return name; + } + name = toCamelCase(name); + if (/^before/.test(name)) { + return /** @type {ResolveStepHook} */ (this.ensureHook( + name[6].toLowerCase() + name.substr(7) + ).withOptions({ + stage: -10 + })); + } + if (/^after/.test(name)) { + return /** @type {ResolveStepHook} */ (this.ensureHook( + name[5].toLowerCase() + name.substr(6) + ).withOptions({ + stage: 10 + })); } - - // remove trailing any matchers - let last = ver[ver.length - 1]; - while ( - ver.length && - (last === undefined || /^[*xX]$/.test(/** @type {string} */ (last))) - ) { - ver.pop(); - last = ver[ver.length - 1]; + const hook = this.hooks[name]; + if (!hook) { + return (this.hooks[name] = new AsyncSeriesBailHook( + ["request", "resolveContext"], + name + )); } + return hook; + } - return ver; - }; - const toFixed = range => { - if (range.length === 1) { - // Special case for "*" is "x.x.x" instead of "=" - return [0]; - } else if (range.length === 2) { - // Special case for "1" is "1.x.x" instead of "=1" - return [1, ...range.slice(1)]; - } else if (range.length === 3) { - // Special case for "1.2" is "1.2.x" instead of "=1.2" - return [2, ...range.slice(1)]; - } else { - return [range.length, ...range.slice(1)]; + /** + * @param {string | ResolveStepHook} name hook name or hook itself + * @returns {ResolveStepHook} the hook + */ + getHook(name) { + if (typeof name !== "string") { + return name; } - }; - const negate = range => { - return [-range[0] - 1, ...range.slice(1)]; - }; - const parseSimple = str => { - // simple ::= primitive | partial | tilde | caret - // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial - // tilde ::= '~' partial - // caret ::= '^' partial - const match = /^(\^|~|<=|<|>=|>|=|v|!)/.exec(str); - const start = match ? match[0] : ""; - const remainder = parsePartial(str.slice(start.length)); - switch (start) { - case "^": - if (remainder.length > 1 && remainder[1] === 0) { - if (remainder.length > 2 && remainder[2] === 0) { - return [3, ...remainder.slice(1)]; - } - return [2, ...remainder.slice(1)]; - } - return [1, ...remainder.slice(1)]; - case "~": - return [2, ...remainder.slice(1)]; - case ">=": - return remainder; - case "=": - case "v": - case "": - return toFixed(remainder); - case "<": - return negate(remainder); - case ">": { - // and( >=, not( = ) ) => >=, =, not, and - const fixed = toFixed(remainder); - // eslint-disable-next-line no-sparse-arrays - return [, fixed, 0, remainder, 2]; - } - case "<=": - // or( <, = ) => <, =, or - // eslint-disable-next-line no-sparse-arrays - return [, toFixed(remainder), negate(remainder), 1]; - case "!": { - // not = - const fixed = toFixed(remainder); - // eslint-disable-next-line no-sparse-arrays - return [, fixed, 0]; - } - default: - throw new Error("Unexpected start value"); + name = toCamelCase(name); + if (/^before/.test(name)) { + return /** @type {ResolveStepHook} */ (this.getHook( + name[6].toLowerCase() + name.substr(7) + ).withOptions({ + stage: -10 + })); } - }; - const combine = (items, fn) => { - if (items.length === 1) return items[0]; - const arr = []; - for (const item of items.slice().reverse()) { - if (0 in item) { - arr.push(item); - } else { - arr.push(...item.slice(1)); - } + if (/^after/.test(name)) { + return /** @type {ResolveStepHook} */ (this.getHook( + name[5].toLowerCase() + name.substr(6) + ).withOptions({ + stage: 10 + })); } - // eslint-disable-next-line no-sparse-arrays - return [, ...arr, ...items.slice(1).map(() => fn)]; - }; - const parseRange = str => { - // range ::= hyphen | simple ( ' ' simple ) * | '' - // hyphen ::= partial ' - ' partial - const items = str.split(" - "); - if (items.length === 1) { - const items = str.trim().split(/\s+/g).map(parseSimple); - return combine(items, 2); + const hook = this.hooks[name]; + if (!hook) { + throw new Error(`Hook ${name} doesn't exist`); } - const a = parsePartial(items[0]); - const b = parsePartial(items[1]); - // >=a <=b => and( >=a, or( >=a, { - // range-set ::= range ( logical-or range ) * - // logical-or ::= ( ' ' ) * '||' ( ' ' ) * - const items = str.split(/\s*\|\|\s*/).map(parseRange); - return combine(items, 1); - }; - return parseLogicalOr(str); -}; + return hook; + } -/* eslint-disable eqeqeq */ -const rangeToString = range => { - var fixCount = range[0]; - var str = ""; - if (range.length === 1) { - return "*"; - } else if (fixCount + 0.5) { - str += - fixCount == 0 - ? ">=" - : fixCount == -1 - ? "<" - : fixCount == 1 - ? "^" - : fixCount == 2 - ? "~" - : fixCount > 0 - ? "=" - : "!="; - var needDot = 1; - // eslint-disable-next-line no-redeclare - for (var i = 1; i < range.length; i++) { - var item = range[i]; - var t = (typeof item)[0]; - needDot--; - str += - t == "u" - ? // undefined: prerelease marker, add an "-" - "-" - : // number or string: add the item, set flag to add an "." between two of them - (needDot > 0 ? "." : "") + ((needDot = 2), item); - } - return str; - } else { - var stack = []; - // eslint-disable-next-line no-redeclare - for (var i = 1; i < range.length; i++) { - // eslint-disable-next-line no-redeclare - var item = range[i]; - stack.push( - item === 0 - ? "not(" + pop() + ")" - : item === 1 - ? "(" + pop() + " || " + pop() + ")" - : item === 2 - ? stack.pop() + " " + stack.pop() - : rangeToString(item) + /** + * @param {object} context context information object + * @param {string} path context path + * @param {string} request request string + * @returns {string | false} result + */ + resolveSync(context, path, request) { + /** @type {Error | null | undefined} */ + let err = undefined; + /** @type {string | false | undefined} */ + let result = undefined; + let sync = false; + this.resolve(context, path, request, {}, (e, r) => { + err = e; + result = r; + sync = true; + }); + if (!sync) { + throw new Error( + "Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!" ); } - return pop(); - } - function pop() { - return stack.pop().replace(/^\((.+)\)$/, "$1"); + if (err) throw err; + if (result === undefined) throw new Error("No result"); + return result; } -}; -/* eslint-enable eqeqeq */ -exports.rangeToString = rangeToString; -/* eslint-disable eqeqeq */ -/** - * @param {SemVerRange} range version range - * @param {string} version the version - * @returns {boolean} if version satisfy the range - */ -const satisfy = (range, version) => { - if (0 in range) { - // @ts-expect-error - version = parseVersion(version); - var fixCount = range[0]; - // when negated is set it swill set for < instead of >= - var negated = fixCount < 0; - if (negated) fixCount = -fixCount - 1; - for (var i = 0, j = 1, isEqual = true; ; j++, i++) { - // cspell:word nequal nequ + /** + * @param {object} context context information object + * @param {string} path context path + * @param {string} request request string + * @param {ResolveContext} resolveContext resolve context + * @param {function(Error | null, (string|false)=, ResolveRequest=): void} callback callback function + * @returns {void} + */ + resolve(context, path, request, resolveContext, callback) { + if (!context || typeof context !== "object") + return callback(new Error("context argument is not an object")); + if (typeof path !== "string") + return callback(new Error("path argument is not a string")); + if (typeof request !== "string") + return callback(new Error("path argument is not a string")); + if (!resolveContext) + return callback(new Error("resolveContext argument is not set")); - // when isEqual = true: - // range version: EOA/object undefined number string - // EOA equal block big-ver big-ver - // undefined bigger next big-ver big-ver - // number smaller block cmp big-cmp - // fixed number smaller block cmp-fix differ - // string smaller block differ cmp - // fixed string smaller block small-cmp cmp-fix + const obj = { + context: context, + path: path, + request: request + }; - // when isEqual = false: - // range version: EOA/object undefined number string - // EOA nequal block next-ver next-ver - // undefined nequal block next-ver next-ver - // number nequal block next next - // fixed number nequal block next next (this never happens) - // string nequal block next next - // fixed string nequal block next next (this never happens) + const message = `resolve '${request}' in '${path}'`; - // EOA end of array - // equal (version is equal range): - // when !negated: return true, - // when negated: return false - // bigger (version is bigger as range): - // when fixed: return false, - // when !negated: return true, - // when negated: return false, - // smaller (version is smaller as range): - // when !negated: return false, - // when negated: return true - // nequal (version is not equal range (> resp <)): return true - // block (version is in different prerelease area): return false - // differ (version is different from fixed range (string vs. number)): return false - // next: continues to the next items - // next-ver: when fixed: return false, continues to the next item only for the version, sets isEqual=false - // big-ver: when fixed || negated: return false, continues to the next item only for the version, sets isEqual=false - // next-nequ: continues to the next items, sets isEqual=false - // cmp (negated === false): version < range => return false, version > range => next-nequ, else => next - // cmp (negated === true): version > range => return false, version < range => next-nequ, else => next - // cmp-fix: version == range => next, else => return false - // big-cmp: when negated => return false, else => next-nequ - // small-cmp: when negated => next-nequ, else => return false + const finishResolved = result => { + return callback( + null, + result.path === false + ? false + : `${result.path.replace(/#/g, "\0#")}${ + result.query ? result.query.replace(/#/g, "\0#") : "" + }${result.fragment || ""}`, + result + ); + }; - var rangeType = j < range.length ? (typeof range[j])[0] : ""; + const finishWithoutResolve = log => { + /** + * @type {Error & {details?: string}} + */ + const error = new Error("Can't " + message); + error.details = log.join("\n"); + this.hooks.noResolve.call(obj, error); + return callback(error); + }; - var versionValue; - var versionType; + if (resolveContext.log) { + // We need log anyway to capture it in case of an error + const parentLog = resolveContext.log; + const log = []; + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: msg => { + parentLog(msg); + log.push(msg); + }, + fileDependencies: resolveContext.fileDependencies, + contextDependencies: resolveContext.contextDependencies, + missingDependencies: resolveContext.missingDependencies, + stack: resolveContext.stack + }, + (err, result) => { + if (err) return callback(err); - // Handles first column in both tables (end of version or object) - if ( - i >= version.length || - ((versionValue = version[i]), - (versionType = (typeof versionValue)[0]) == "o") - ) { - // Handles nequal - if (!isEqual) return true; - // Handles bigger - if (rangeType == "u") return j > fixCount && !negated; - // Handles equal and smaller: (range === EOA) XOR negated - return (rangeType == "") != negated; // equal + smaller - } + if (result) return finishResolved(result); - // Handles second column in both tables (version = undefined) - if (versionType == "u") { - if (!isEqual || rangeType != "u") { - return false; + return finishWithoutResolve(log); } - } + ); + } else { + // Try to resolve assuming there is no error + // We don't log stuff in this case + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: undefined, + fileDependencies: resolveContext.fileDependencies, + contextDependencies: resolveContext.contextDependencies, + missingDependencies: resolveContext.missingDependencies, + stack: resolveContext.stack + }, + (err, result) => { + if (err) return callback(err); - // switch between first and second table - else if (isEqual) { - // Handle diagonal - if (rangeType == versionType) { - if (j <= fixCount) { - // Handles "cmp-fix" cases - if (versionValue != range[j]) { - return false; - } - } else { - // Handles "cmp" cases - if (negated ? versionValue > range[j] : versionValue < range[j]) { - return false; - } - if (versionValue != range[j]) isEqual = false; - } - } + if (result) return finishResolved(result); - // Handle big-ver - else if (rangeType != "s" && rangeType != "n") { - if (negated || j <= fixCount) return false; - isEqual = false; - j--; - } + // log is missing for the error details + // so we redo the resolving for the log info + // this is more expensive to the success case + // is assumed by default - // Handle differ, big-cmp and small-cmp - else if (j <= fixCount || versionType < rangeType != negated) { - return false; - } else { - isEqual = false; - } - } else { - // Handles all "next-ver" cases in the second table - if (rangeType != "s" && rangeType != "n") { - isEqual = false; - j--; - } + const log = []; - // next is applied by default - } - } - } - /** @type {(boolean | number)[]} */ - var stack = []; - var p = stack.pop.bind(stack); - // eslint-disable-next-line no-redeclare - for (var i = 1; i < range.length; i++) { - var item = /** @type {SemVerRange | 0 | 1 | 2} */ (range[i]); - stack.push( - item == 1 - ? p() | p() - : item == 2 - ? p() & p() - : item - ? satisfy(item, version) - : !p() - ); - } - return !!p(); -}; -/* eslint-enable eqeqeq */ -exports.satisfy = satisfy; + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: msg => log.push(msg), + stack: resolveContext.stack + }, + (err, result) => { + if (err) return callback(err); -exports.stringifyHoley = json => { - switch (typeof json) { - case "undefined": - return ""; - case "object": - if (Array.isArray(json)) { - let str = "["; - for (let i = 0; i < json.length; i++) { - if (i !== 0) str += ","; - str += this.stringifyHoley(json[i]); + return finishWithoutResolve(log); + } + ); } - str += "]"; - return str; - } else { - return JSON.stringify(json); - } - default: - return JSON.stringify(json); + ); + } } -}; - -//#region runtime code: parseVersion -exports.parseVersionRuntimeCode = runtimeTemplate => - `var parseVersion = ${runtimeTemplate.basicFunction("str", [ - "// see webpack/lib/util/semver.js for original code", - `var p=${ - runtimeTemplate.supportsArrowFunction() ? "p=>" : "function(p)" - }{return p.split(".").map((${ - runtimeTemplate.supportsArrowFunction() ? "p=>" : "function(p)" - }{return+p==p?+p:p}))},n=/^([^-+]+)?(?:-([^+]+))?(?:\\+(.+))?$/.exec(str),r=n[1]?p(n[1]):[];return n[2]&&(r.length++,r.push.apply(r,p(n[2]))),n[3]&&(r.push([]),r.push.apply(r,p(n[3]))),r;` - ])}`; -//#endregion - -//#region runtime code: versionLt -exports.versionLtRuntimeCode = runtimeTemplate => - `var versionLt = ${runtimeTemplate.basicFunction("a, b", [ - "// see webpack/lib/util/semver.js for original code", - 'a=parseVersion(a),b=parseVersion(b);for(var r=0;;){if(r>=a.length)return r=b.length)return"u"==n;var t=b[r],f=(typeof t)[0];if(n!=f)return"o"==n&&"n"==f||("s"==f||"u"==n);if("o"!=n&&"u"!=n&&e!=t)return e - `var rangeToString = ${runtimeTemplate.basicFunction("range", [ - "// see webpack/lib/util/semver.js for original code", - 'var r=range[0],n="";if(1===range.length)return"*";if(r+.5){n+=0==r?">=":-1==r?"<":1==r?"^":2==r?"~":r>0?"=":"!=";for(var e=1,a=1;a0?".":"")+(e=2,t)}return n}var g=[];for(a=1;a - `var satisfy = ${runtimeTemplate.basicFunction("range, version", [ - "// see webpack/lib/util/semver.js for original code", - 'if(0 in range){version=parseVersion(version);var e=range[0],r=e<0;r&&(e=-e-1);for(var n=0,i=1,a=!0;;i++,n++){var f,s,g=i=version.length||"o"==(s=(typeof(f=version[n]))[0]))return!a||("u"==g?i>e&&!r:""==g!=r);if("u"==s){if(!a||"u"!=g)return!1}else if(a)if(g==s)if(i<=e){if(f!=range[i])return!1}else{if(r?f>range[i]:f { + if (err) return callback(err); + if (result) return callback(null, result); + callback(); + }); + } else { + callback(); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ + /** + * @param {string} identifier identifier + * @returns {ParsedIdentifier} parsed identifier + */ + parse(identifier) { + const part = { + request: "", + query: "", + fragment: "", + module: false, + directory: false, + file: false, + internal: false + }; + const parsedIdentifier = parseIdentifier(identifier); + if (!parsedIdentifier) return part; -const memoize = __webpack_require__(78676); + [part.request, part.query, part.fragment] = parsedIdentifier; -/** @typedef {import("../serialization/BinaryMiddleware").MEASURE_END_OPERATION_TYPE} MEASURE_END_OPERATION */ -/** @typedef {import("../serialization/BinaryMiddleware").MEASURE_START_OPERATION_TYPE} MEASURE_START_OPERATION */ -/** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */ -/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ -/** @typedef {import("../serialization/Serializer")} Serializer */ + if (part.request.length > 0) { + part.internal = this.isPrivate(identifier); + part.module = this.isModule(part.request); + part.directory = this.isDirectory(part.request); + if (part.directory) { + part.request = part.request.substr(0, part.request.length - 1); + } + } -const getBinaryMiddleware = memoize(() => - __webpack_require__(97059) -); -const getObjectMiddleware = memoize(() => - __webpack_require__(34795) -); -const getSingleItemMiddleware = memoize(() => - __webpack_require__(65112) -); -const getSerializer = memoize(() => __webpack_require__(53080)); -const getSerializerMiddleware = memoize(() => - __webpack_require__(83137) -); + return part; + } -const getBinaryMiddlewareInstance = memoize( - () => new (getBinaryMiddleware())() -); + isModule(path) { + return getType(path) === PathType.Normal; + } -const registerSerializers = memoize(() => { - __webpack_require__(26611); + isPrivate(path) { + return getType(path) === PathType.Internal; + } - // Load internal paths with a relative require - // This allows bundling all internal serializers - const internalSerializables = __webpack_require__(53023); - getObjectMiddleware().registerLoader(/^webpack\/lib\//, req => { - const loader = internalSerializables[req.slice("webpack/lib/".length)]; - if (loader) { - loader(); - } else { - console.warn(`${req} not found in internalSerializables`); - } - return true; - }); -}); + /** + * @param {string} path a path + * @returns {boolean} true, if the path is a directory path + */ + isDirectory(path) { + return path.endsWith("/"); + } -/** @type {Serializer} */ -let buffersSerializer; + join(path, request) { + return join(path, request); + } -// Expose serialization API -module.exports = { - get register() { - return getObjectMiddleware().register; - }, - get registerLoader() { - return getObjectMiddleware().registerLoader; - }, - get registerNotSerializable() { - return getObjectMiddleware().registerNotSerializable; - }, - get NOT_SERIALIZABLE() { - return getObjectMiddleware().NOT_SERIALIZABLE; - }, - /** @type {MEASURE_START_OPERATION} */ - get MEASURE_START_OPERATION() { - return getBinaryMiddleware().MEASURE_START_OPERATION; - }, - /** @type {MEASURE_END_OPERATION} */ - get MEASURE_END_OPERATION() { - return getBinaryMiddleware().MEASURE_END_OPERATION; - }, - get buffersSerializer() { - if (buffersSerializer !== undefined) return buffersSerializer; - registerSerializers(); - const Serializer = getSerializer(); - const binaryMiddleware = getBinaryMiddlewareInstance(); - const SerializerMiddleware = getSerializerMiddleware(); - const SingleItemMiddleware = getSingleItemMiddleware(); - return (buffersSerializer = new Serializer([ - new SingleItemMiddleware(), - new (getObjectMiddleware())(context => { - if (context.write) { - context.writeLazy = value => { - context.write( - SerializerMiddleware.createLazy(value, binaryMiddleware) - ); - }; - } - }, "md4"), - binaryMiddleware - ])); - }, - createFileSerializer: (fs, hashFunction) => { - registerSerializers(); - const Serializer = getSerializer(); - const FileMiddleware = __webpack_require__(65321); - const fileMiddleware = new FileMiddleware(fs, hashFunction); - const binaryMiddleware = getBinaryMiddlewareInstance(); - const SerializerMiddleware = getSerializerMiddleware(); - const SingleItemMiddleware = getSingleItemMiddleware(); - return new Serializer([ - new SingleItemMiddleware(), - new (getObjectMiddleware())(context => { - if (context.write) { - context.writeLazy = value => { - context.write( - SerializerMiddleware.createLazy(value, binaryMiddleware) - ); - }; - context.writeSeparate = (value, options) => { - const lazy = SerializerMiddleware.createLazy( - value, - fileMiddleware, - options - ); - context.write(lazy); - return lazy; - }; - } - }, hashFunction), - binaryMiddleware, - fileMiddleware - ]); + normalize(path) { + return normalize(path); } -}; +} + +module.exports = Resolver; /***/ }), -/***/ 15652: -/***/ (function(module) { +/***/ 47716: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -136380,549 +136227,730 @@ module.exports = { +const versions = (__webpack_require__(77282).versions); +const Resolver = __webpack_require__(55516); +const { getType, PathType } = __webpack_require__(67079); + +const SyncAsyncFileSystemDecorator = __webpack_require__(87474); + +const AliasFieldPlugin = __webpack_require__(14819); +const AliasPlugin = __webpack_require__(63676); +const AppendPlugin = __webpack_require__(92088); +const ConditionalPlugin = __webpack_require__(6953); +const DescriptionFilePlugin = __webpack_require__(44112); +const DirectoryExistsPlugin = __webpack_require__(60895); +const ExportsFieldPlugin = __webpack_require__(83849); +const FileExistsPlugin = __webpack_require__(50295); +const ImportsFieldPlugin = __webpack_require__(7317); +const JoinRequestPartPlugin = __webpack_require__(35949); +const JoinRequestPlugin = __webpack_require__(5190); +const MainFieldPlugin = __webpack_require__(47450); +const ModulesInHierachicDirectoriesPlugin = __webpack_require__(48506); +const ModulesInRootPlugin = __webpack_require__(88138); +const NextPlugin = __webpack_require__(40777); +const ParsePlugin = __webpack_require__(97849); +const PnpPlugin = __webpack_require__(44222); +const RestrictionsPlugin = __webpack_require__(36400); +const ResultPlugin = __webpack_require__(13965); +const RootsPlugin = __webpack_require__(66737); +const SelfReferencePlugin = __webpack_require__(52232); +const SymlinkPlugin = __webpack_require__(58885); +const TryNextPlugin = __webpack_require__(99324); +const UnsafeCachePlugin = __webpack_require__(41606); +const UseFilePlugin = __webpack_require__(96972); + +/** @typedef {import("./AliasPlugin").AliasOption} AliasOptionEntry */ +/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ + +/** @typedef {string|string[]|false} AliasOptionNewRequest */ +/** @typedef {{[k: string]: AliasOptionNewRequest}} AliasOptions */ +/** @typedef {{apply: function(Resolver): void} | function(this: Resolver, Resolver): void} Plugin */ + /** - * @typedef {Object} GroupOptions - * @property {boolean=} groupChildren - * @property {boolean=} force - * @property {number=} targetGroupCount + * @typedef {Object} UserResolveOptions + * @property {(AliasOptions | AliasOptionEntry[])=} alias A list of module alias configurations or an object which maps key to value + * @property {(AliasOptions | AliasOptionEntry[])=} fallback A list of module alias configurations or an object which maps key to value, applied only after modules option + * @property {(string | string[])[]=} aliasFields A list of alias fields in description files + * @property {(function(ResolveRequest): boolean)=} cachePredicate A function which decides whether a request should be cached or not. An object is passed with at least `path` and `request` properties. + * @property {boolean=} cacheWithContext Whether or not the unsafeCache should include request context as part of the cache key. + * @property {string[]=} descriptionFiles A list of description files to read from + * @property {string[]=} conditionNames A list of exports field condition names. + * @property {boolean=} enforceExtension Enforce that a extension from extensions must be used + * @property {(string | string[])[]=} exportsFields A list of exports fields in description files + * @property {(string | string[])[]=} importsFields A list of imports fields in description files + * @property {string[]=} extensions A list of extensions which should be tried for files + * @property {FileSystem} fileSystem The file system which should be used + * @property {(object | boolean)=} unsafeCache Use this cache object to unsafely cache the successful requests + * @property {boolean=} symlinks Resolve symlinks to their symlinked location + * @property {Resolver=} resolver A prepared Resolver to which the plugins are attached + * @property {string[] | string=} modules A list of directories to resolve modules from, can be absolute path or folder name + * @property {(string | string[] | {name: string | string[], forceRelative: boolean})[]=} mainFields A list of main fields in description files + * @property {string[]=} mainFiles A list of main files in directories + * @property {Plugin[]=} plugins A list of additional resolve plugins which should be applied + * @property {PnpApi | null=} pnpApi A PnP API that should be used - null is "never", undefined is "auto" + * @property {string[]=} roots A list of root paths + * @property {boolean=} fullySpecified The request is already fully specified and no extensions or directories are resolved for it + * @property {boolean=} resolveToContext Resolve to a context instead of a file + * @property {(string|RegExp)[]=} restrictions A list of resolve restrictions + * @property {boolean=} useSyncFileSystemCalls Use only the sync constiants of the file system calls + * @property {boolean=} preferRelative Prefer to resolve module requests as relative requests before falling back to modules + * @property {boolean=} preferAbsolute Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots */ /** - * @template T - * @template R - * @typedef {Object} GroupConfig - * @property {function(T): string[]} getKeys - * @property {function(string, (R | T)[], T[]): R} createGroup - * @property {function(string, T[]): GroupOptions=} getOptions + * @typedef {Object} ResolveOptions + * @property {AliasOptionEntry[]} alias + * @property {AliasOptionEntry[]} fallback + * @property {Set} aliasFields + * @property {(function(ResolveRequest): boolean)} cachePredicate + * @property {boolean} cacheWithContext + * @property {Set} conditionNames A list of exports field condition names. + * @property {string[]} descriptionFiles + * @property {boolean} enforceExtension + * @property {Set} exportsFields + * @property {Set} importsFields + * @property {Set} extensions + * @property {FileSystem} fileSystem + * @property {object | false} unsafeCache + * @property {boolean} symlinks + * @property {Resolver=} resolver + * @property {Array} modules + * @property {{name: string[], forceRelative: boolean}[]} mainFields + * @property {Set} mainFiles + * @property {Plugin[]} plugins + * @property {PnpApi | null} pnpApi + * @property {Set} roots + * @property {boolean} fullySpecified + * @property {boolean} resolveToContext + * @property {Set} restrictions + * @property {boolean} preferRelative + * @property {boolean} preferAbsolute */ /** - * @template T - * @template R - * @typedef {Object} ItemWithGroups - * @property {T} item - * @property {Set>} groups + * @param {PnpApi | null=} option option + * @returns {PnpApi | null} processed option */ +function processPnpApiOption(option) { + if ( + option === undefined && + /** @type {NodeJS.ProcessVersions & {pnp: string}} */ versions.pnp + ) { + // @ts-ignore + return __webpack_require__(35125); // eslint-disable-line node/no-missing-require + } + + return option || null; +} /** - * @template T - * @template R - * @typedef {{ config: GroupConfig, name: string, alreadyGrouped: boolean, items: Set> | undefined }} Group + * @param {AliasOptions | AliasOptionEntry[] | undefined} alias alias + * @returns {AliasOptionEntry[]} normalized aliases */ +function normalizeAlias(alias) { + return typeof alias === "object" && !Array.isArray(alias) && alias !== null + ? Object.keys(alias).map(key => { + /** @type {AliasOptionEntry} */ + const obj = { name: key, onlyModule: false, alias: alias[key] }; + + if (/\$$/.test(key)) { + obj.onlyModule = true; + obj.name = key.substr(0, key.length - 1); + } + + return obj; + }) + : /** @type {Array} */ (alias) || []; +} /** - * @template T - * @template R - * @param {T[]} items the list of items - * @param {GroupConfig[]} groupConfigs configuration - * @returns {(R | T)[]} grouped items + * @param {UserResolveOptions} options input options + * @returns {ResolveOptions} output options */ -const smartGrouping = (items, groupConfigs) => { - /** @type {Set>} */ - const itemsWithGroups = new Set(); - /** @type {Map>} */ - const allGroups = new Map(); - for (const item of items) { - /** @type {Set>} */ - const groups = new Set(); - for (let i = 0; i < groupConfigs.length; i++) { - const groupConfig = groupConfigs[i]; - const keys = groupConfig.getKeys(item); - if (keys) { - for (const name of keys) { - const key = `${i}:${name}`; - let group = allGroups.get(key); - if (group === undefined) { - allGroups.set( - key, - (group = { - config: groupConfig, - name, - alreadyGrouped: false, - items: undefined - }) - ); - } - groups.add(group); - } - } +function createOptions(options) { + const mainFieldsSet = new Set(options.mainFields || ["main"]); + const mainFields = []; + + for (const item of mainFieldsSet) { + if (typeof item === "string") { + mainFields.push({ + name: [item], + forceRelative: true + }); + } else if (Array.isArray(item)) { + mainFields.push({ + name: item, + forceRelative: true + }); + } else { + mainFields.push({ + name: Array.isArray(item.name) ? item.name : [item.name], + forceRelative: item.forceRelative + }); } - itemsWithGroups.add({ - item, - groups - }); } - /** - * @param {Set>} itemsWithGroups input items with groups - * @returns {(T | R)[]} groups items - */ - const runGrouping = itemsWithGroups => { - const totalSize = itemsWithGroups.size; - for (const entry of itemsWithGroups) { - for (const group of entry.groups) { - if (group.alreadyGrouped) continue; - const items = group.items; - if (items === undefined) { - group.items = new Set([entry]); - } else { - items.add(entry); - } - } - } - /** @type {Map, { items: Set>, options: GroupOptions | false | undefined, used: boolean }>} */ - const groupMap = new Map(); - for (const group of allGroups.values()) { - if (group.items) { - const items = group.items; - group.items = undefined; - groupMap.set(group, { - items, - options: undefined, - used: false - }); - } - } - /** @type {(T | R)[]} */ - const results = []; - for (;;) { - /** @type {Group} */ - let bestGroup = undefined; - let bestGroupSize = -1; - let bestGroupItems = undefined; - let bestGroupOptions = undefined; - for (const [group, state] of groupMap) { - const { items, used } = state; - let options = state.options; - if (options === undefined) { - const groupConfig = group.config; - state.options = options = - (groupConfig.getOptions && - groupConfig.getOptions( - group.name, - Array.from(items, ({ item }) => item) - )) || - false; - } - const force = options && options.force; - if (!force) { - if (bestGroupOptions && bestGroupOptions.force) continue; - if (used) continue; - if (items.size <= 1 || totalSize - items.size <= 1) { - continue; - } - } - const targetGroupCount = (options && options.targetGroupCount) || 4; - let sizeValue = force - ? items.size - : Math.min( - items.size, - (totalSize * 2) / targetGroupCount + - itemsWithGroups.size - - items.size - ); - if ( - sizeValue > bestGroupSize || - (force && (!bestGroupOptions || !bestGroupOptions.force)) - ) { - bestGroup = group; - bestGroupSize = sizeValue; - bestGroupItems = items; - bestGroupOptions = options; - } - } - if (bestGroup === undefined) { - break; + return { + alias: normalizeAlias(options.alias), + fallback: normalizeAlias(options.fallback), + aliasFields: new Set(options.aliasFields), + cachePredicate: + options.cachePredicate || + function () { + return true; + }, + cacheWithContext: + typeof options.cacheWithContext !== "undefined" + ? options.cacheWithContext + : true, + exportsFields: new Set(options.exportsFields || ["exports"]), + importsFields: new Set(options.importsFields || ["imports"]), + conditionNames: new Set(options.conditionNames), + descriptionFiles: Array.from( + new Set(options.descriptionFiles || ["package.json"]) + ), + enforceExtension: + options.enforceExtension === undefined + ? options.extensions && options.extensions.includes("") + ? true + : false + : options.enforceExtension, + extensions: new Set(options.extensions || [".js", ".json", ".node"]), + fileSystem: options.useSyncFileSystemCalls + ? new SyncAsyncFileSystemDecorator( + /** @type {SyncFileSystem} */ ( + /** @type {unknown} */ (options.fileSystem) + ) + ) + : options.fileSystem, + unsafeCache: + options.unsafeCache && typeof options.unsafeCache !== "object" + ? {} + : options.unsafeCache || false, + symlinks: typeof options.symlinks !== "undefined" ? options.symlinks : true, + resolver: options.resolver, + modules: mergeFilteredToArray( + Array.isArray(options.modules) + ? options.modules + : options.modules + ? [options.modules] + : ["node_modules"], + item => { + const type = getType(item); + return type === PathType.Normal || type === PathType.Relative; } - const items = new Set(bestGroupItems); - const options = bestGroupOptions; + ), + mainFields, + mainFiles: new Set(options.mainFiles || ["index"]), + plugins: options.plugins || [], + pnpApi: processPnpApiOption(options.pnpApi), + roots: new Set(options.roots || undefined), + fullySpecified: options.fullySpecified || false, + resolveToContext: options.resolveToContext || false, + preferRelative: options.preferRelative || false, + preferAbsolute: options.preferAbsolute || false, + restrictions: new Set(options.restrictions) + }; +} - const groupChildren = !options || options.groupChildren !== false; +/** + * @param {UserResolveOptions} options resolve options + * @returns {Resolver} created resolver + */ +exports.createResolver = function (options) { + const normalizedOptions = createOptions(options); - for (const item of items) { - itemsWithGroups.delete(item); - // Remove all groups that items have from the map to not select them again - for (const group of item.groups) { - const state = groupMap.get(group); - if (state !== undefined) { - state.items.delete(item); - if (state.items.size === 0) { - groupMap.delete(group); - } else { - state.options = undefined; - if (groupChildren) { - state.used = true; - } - } - } - } - } - groupMap.delete(bestGroup); + const { + alias, + fallback, + aliasFields, + cachePredicate, + cacheWithContext, + conditionNames, + descriptionFiles, + enforceExtension, + exportsFields, + importsFields, + extensions, + fileSystem, + fullySpecified, + mainFields, + mainFiles, + modules, + plugins: userPlugins, + pnpApi, + resolveToContext, + preferRelative, + preferAbsolute, + symlinks, + unsafeCache, + resolver: customResolver, + restrictions, + roots + } = normalizedOptions; - const key = bestGroup.name; - const groupConfig = bestGroup.config; + const plugins = userPlugins.slice(); - const allItems = Array.from(items, ({ item }) => item); + const resolver = customResolver + ? customResolver + : new Resolver(fileSystem, normalizedOptions); - bestGroup.alreadyGrouped = true; - const children = groupChildren ? runGrouping(items) : allItems; - bestGroup.alreadyGrouped = false; + //// pipeline //// - results.push(groupConfig.createGroup(key, children, allItems)); - } - for (const { item } of itemsWithGroups) { - results.push(item); + resolver.ensureHook("resolve"); + resolver.ensureHook("internalResolve"); + resolver.ensureHook("newInteralResolve"); + resolver.ensureHook("parsedResolve"); + resolver.ensureHook("describedResolve"); + resolver.ensureHook("internal"); + resolver.ensureHook("rawModule"); + resolver.ensureHook("module"); + resolver.ensureHook("resolveAsModule"); + resolver.ensureHook("undescribedResolveInPackage"); + resolver.ensureHook("resolveInPackage"); + resolver.ensureHook("resolveInExistingDirectory"); + resolver.ensureHook("relative"); + resolver.ensureHook("describedRelative"); + resolver.ensureHook("directory"); + resolver.ensureHook("undescribedExistingDirectory"); + resolver.ensureHook("existingDirectory"); + resolver.ensureHook("undescribedRawFile"); + resolver.ensureHook("rawFile"); + resolver.ensureHook("file"); + resolver.ensureHook("finalFile"); + resolver.ensureHook("existingFile"); + resolver.ensureHook("resolved"); + + // resolve + for (const { source, resolveOptions } of [ + { source: "resolve", resolveOptions: { fullySpecified } }, + { source: "internal-resolve", resolveOptions: { fullySpecified: false } } + ]) { + if (unsafeCache) { + plugins.push( + new UnsafeCachePlugin( + source, + cachePredicate, + unsafeCache, + cacheWithContext, + `new-${source}` + ) + ); + plugins.push( + new ParsePlugin(`new-${source}`, resolveOptions, "parsed-resolve") + ); + } else { + plugins.push(new ParsePlugin(source, resolveOptions, "parsed-resolve")); } - return results; - }; - return runGrouping(itemsWithGroups); -}; + } -module.exports = smartGrouping; + // parsed-resolve + plugins.push( + new DescriptionFilePlugin( + "parsed-resolve", + descriptionFiles, + false, + "described-resolve" + ) + ); + plugins.push(new NextPlugin("after-parsed-resolve", "described-resolve")); + // described-resolve + plugins.push(new NextPlugin("described-resolve", "normal-resolve")); + if (fallback.length > 0) { + plugins.push( + new AliasPlugin("described-resolve", fallback, "internal-resolve") + ); + } -/***/ }), + // normal-resolve + if (alias.length > 0) + plugins.push(new AliasPlugin("normal-resolve", alias, "internal-resolve")); + aliasFields.forEach(item => { + plugins.push( + new AliasFieldPlugin("normal-resolve", item, "internal-resolve") + ); + }); + if (preferRelative) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } + plugins.push( + new ConditionalPlugin( + "after-normal-resolve", + { module: true }, + "resolve as module", + false, + "raw-module" + ) + ); + plugins.push( + new ConditionalPlugin( + "after-normal-resolve", + { internal: true }, + "resolve as internal import", + false, + "internal" + ) + ); + if (preferAbsolute) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } + if (roots.size > 0) { + plugins.push(new RootsPlugin("after-normal-resolve", roots, "relative")); + } + if (!preferRelative && !preferAbsolute) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } -/***/ 41245: -/***/ (function(__unused_webpack_module, exports) { + // internal + importsFields.forEach(importsField => { + plugins.push( + new ImportsFieldPlugin( + "internal", + conditionNames, + importsField, + "relative", + "internal-resolve" + ) + ); + }); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // raw-module + exportsFields.forEach(exportsField => { + plugins.push( + new SelfReferencePlugin("raw-module", exportsField, "resolve-as-module") + ); + }); + modules.forEach(item => { + if (Array.isArray(item)) { + if (item.includes("node_modules") && pnpApi) { + plugins.push( + new ModulesInHierachicDirectoriesPlugin( + "raw-module", + item.filter(i => i !== "node_modules"), + "module" + ) + ); + plugins.push( + new PnpPlugin("raw-module", pnpApi, "undescribed-resolve-in-package") + ); + } else { + plugins.push( + new ModulesInHierachicDirectoriesPlugin("raw-module", item, "module") + ); + } + } else { + plugins.push(new ModulesInRootPlugin("raw-module", item, "module")); + } + }); + + // module + plugins.push(new JoinRequestPartPlugin("module", "resolve-as-module")); + // resolve-as-module + if (!resolveToContext) { + plugins.push( + new ConditionalPlugin( + "resolve-as-module", + { directory: false, request: "." }, + "single file module", + true, + "undescribed-raw-file" + ) + ); + } + plugins.push( + new DirectoryExistsPlugin( + "resolve-as-module", + "undescribed-resolve-in-package" + ) + ); + // undescribed-resolve-in-package + plugins.push( + new DescriptionFilePlugin( + "undescribed-resolve-in-package", + descriptionFiles, + false, + "resolve-in-package" + ) + ); + plugins.push( + new NextPlugin("after-undescribed-resolve-in-package", "resolve-in-package") + ); -/** @typedef {import("webpack-sources").Source} Source */ + // resolve-in-package + exportsFields.forEach(exportsField => { + plugins.push( + new ExportsFieldPlugin( + "resolve-in-package", + conditionNames, + exportsField, + "relative" + ) + ); + }); + plugins.push( + new NextPlugin("resolve-in-package", "resolve-in-existing-directory") + ); -/** @type {WeakMap>} */ -const equalityCache = new WeakMap(); + // resolve-in-existing-directory + plugins.push( + new JoinRequestPlugin("resolve-in-existing-directory", "relative") + ); -/** - * @param {Source} a a source - * @param {Source} b another source - * @returns {boolean} true, when both sources are equal - */ -const _isSourceEqual = (a, b) => { - // prefer .buffer(), it's called anyway during emit - /** @type {Buffer|string} */ - let aSource = typeof a.buffer === "function" ? a.buffer() : a.source(); - /** @type {Buffer|string} */ - let bSource = typeof b.buffer === "function" ? b.buffer() : b.source(); - if (aSource === bSource) return true; - if (typeof aSource === "string" && typeof bSource === "string") return false; - if (!Buffer.isBuffer(aSource)) aSource = Buffer.from(aSource, "utf-8"); - if (!Buffer.isBuffer(bSource)) bSource = Buffer.from(bSource, "utf-8"); - return aSource.equals(bSource); -}; + // relative + plugins.push( + new DescriptionFilePlugin( + "relative", + descriptionFiles, + true, + "described-relative" + ) + ); + plugins.push(new NextPlugin("after-relative", "described-relative")); -/** - * @param {Source} a a source - * @param {Source} b another source - * @returns {boolean} true, when both sources are equal - */ -const isSourceEqual = (a, b) => { - if (a === b) return true; - const cache1 = equalityCache.get(a); - if (cache1 !== undefined) { - const result = cache1.get(b); - if (result !== undefined) return result; - } - const result = _isSourceEqual(a, b); - if (cache1 !== undefined) { - cache1.set(b, result); + // described-relative + if (resolveToContext) { + plugins.push(new NextPlugin("described-relative", "directory")); } else { - const map = new WeakMap(); - map.set(b, result); - equalityCache.set(a, map); + plugins.push( + new ConditionalPlugin( + "described-relative", + { directory: false }, + null, + true, + "raw-file" + ) + ); + plugins.push( + new ConditionalPlugin( + "described-relative", + { fullySpecified: false }, + "as directory", + true, + "directory" + ) + ); } - const cache2 = equalityCache.get(b); - if (cache2 !== undefined) { - cache2.set(a, result); + + // directory + plugins.push( + new DirectoryExistsPlugin("directory", "undescribed-existing-directory") + ); + + if (resolveToContext) { + // undescribed-existing-directory + plugins.push(new NextPlugin("undescribed-existing-directory", "resolved")); } else { - const map = new WeakMap(); - map.set(a, result); - equalityCache.set(b, map); - } - return result; -}; -exports.isSourceEqual = isSourceEqual; + // undescribed-existing-directory + plugins.push( + new DescriptionFilePlugin( + "undescribed-existing-directory", + descriptionFiles, + false, + "existing-directory" + ) + ); + mainFiles.forEach(item => { + plugins.push( + new UseFilePlugin( + "undescribed-existing-directory", + item, + "undescribed-raw-file" + ) + ); + }); + // described-existing-directory + mainFields.forEach(item => { + plugins.push( + new MainFieldPlugin( + "existing-directory", + item, + "resolve-in-existing-directory" + ) + ); + }); + mainFiles.forEach(item => { + plugins.push( + new UseFilePlugin("existing-directory", item, "undescribed-raw-file") + ); + }); -/***/ }), + // undescribed-raw-file + plugins.push( + new DescriptionFilePlugin( + "undescribed-raw-file", + descriptionFiles, + true, + "raw-file" + ) + ); + plugins.push(new NextPlugin("after-undescribed-raw-file", "raw-file")); -/***/ 12047: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // raw-file + plugins.push( + new ConditionalPlugin( + "raw-file", + { fullySpecified: true }, + null, + false, + "file" + ) + ); + if (!enforceExtension) { + plugins.push(new TryNextPlugin("raw-file", "no extension", "file")); + } + extensions.forEach(item => { + plugins.push(new AppendPlugin("raw-file", item, "file")); + }); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // file + if (alias.length > 0) + plugins.push(new AliasPlugin("file", alias, "internal-resolve")); + aliasFields.forEach(item => { + plugins.push(new AliasFieldPlugin("file", item, "internal-resolve")); + }); + plugins.push(new NextPlugin("file", "final-file")); + // final-file + plugins.push(new FileExistsPlugin("final-file", "existing-file")); + // existing-file + if (symlinks) + plugins.push(new SymlinkPlugin("existing-file", "existing-file")); + plugins.push(new NextPlugin("existing-file", "resolved")); + } -const { validate } = __webpack_require__(38476); + // resolved + if (restrictions.size > 0) { + plugins.push(new RestrictionsPlugin(resolver.hooks.resolved, restrictions)); + } + plugins.push(new ResultPlugin(resolver.hooks.resolved)); -/* cSpell:disable */ -const DID_YOU_MEAN = { - rules: "module.rules", - loaders: "module.rules or module.rules.*.use", - query: "module.rules.*.options (BREAKING CHANGE since webpack 5)", - noParse: "module.noParse", - filename: "output.filename or module.rules.*.generator.filename", - file: "output.filename", - chunkFilename: "output.chunkFilename", - chunkfilename: "output.chunkFilename", - ecmaVersion: - "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", - ecmaversion: - "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", - ecma: "output.environment (output.ecmaVersion was a temporary configuration option during webpack 5 beta)", - path: "output.path", - pathinfo: "output.pathinfo", - pathInfo: "output.pathinfo", - jsonpFunction: "output.chunkLoadingGlobal (BREAKING CHANGE since webpack 5)", - chunkCallbackName: - "output.chunkLoadingGlobal (BREAKING CHANGE since webpack 5)", - jsonpScriptType: "output.scriptType (BREAKING CHANGE since webpack 5)", - hotUpdateFunction: "output.hotUpdateGlobal (BREAKING CHANGE since webpack 5)", - splitChunks: "optimization.splitChunks", - immutablePaths: "snapshot.immutablePaths", - managedPaths: "snapshot.managedPaths", - maxModules: "stats.modulesSpace (BREAKING CHANGE since webpack 5)", - hashedModuleIds: - 'optimization.moduleIds: "hashed" (BREAKING CHANGE since webpack 5)', - namedChunks: - 'optimization.chunkIds: "named" (BREAKING CHANGE since webpack 5)', - namedModules: - 'optimization.moduleIds: "named" (BREAKING CHANGE since webpack 5)', - occurrenceOrder: - 'optimization.chunkIds: "size" and optimization.moduleIds: "size" (BREAKING CHANGE since webpack 5)', - automaticNamePrefix: - "optimization.splitChunks.[cacheGroups.*].idHint (BREAKING CHANGE since webpack 5)", - noEmitOnErrors: - "optimization.emitOnErrors (BREAKING CHANGE since webpack 5: logic is inverted to avoid negative flags)", - Buffer: - "to use the ProvidePlugin to process the Buffer variable to modules as polyfill\n" + - "BREAKING CHANGE: webpack 5 no longer provided Node.js polyfills by default.\n" + - "Note: if you are using 'node.Buffer: false', you can just remove that as this is the default behavior now.\n" + - "To provide a polyfill to modules use:\n" + - 'new ProvidePlugin({ Buffer: ["buffer", "Buffer"] }) and npm install buffer.', - process: - "to use the ProvidePlugin to process the process variable to modules as polyfill\n" + - "BREAKING CHANGE: webpack 5 no longer provided Node.js polyfills by default.\n" + - "Note: if you are using 'node.process: false', you can just remove that as this is the default behavior now.\n" + - "To provide a polyfill to modules use:\n" + - 'new ProvidePlugin({ process: "process" }) and npm install buffer.' -}; + //// RESOLVER //// -const REMOVED = { - concord: - "BREAKING CHANGE: resolve.concord has been removed and is no longer available.", - devtoolLineToLine: - "BREAKING CHANGE: output.devtoolLineToLine has been removed and is no longer available." + for (const plugin of plugins) { + if (typeof plugin === "function") { + plugin.call(resolver, resolver); + } else { + plugin.apply(resolver); + } + } + + return resolver; }; -/* cSpell:enable */ /** - * @param {Parameters[0]} schema a json schema - * @param {Parameters[1]} options the options that should be validated - * @param {Parameters[2]=} validationConfiguration configuration for generating errors - * @returns {void} + * Merging filtered elements + * @param {string[]} array source array + * @param {function(string): boolean} filter predicate + * @returns {Array} merge result */ -const validateSchema = (schema, options, validationConfiguration) => { - validate( - schema, - options, - validationConfiguration || { - name: "Webpack", - postFormatter: (formattedError, error) => { - const children = error.children; - if ( - children && - children.some( - child => - child.keyword === "absolutePath" && - child.dataPath === ".output.filename" - ) - ) { - return `${formattedError}\nPlease use output.path to specify absolute path and output.filename for the file name.`; - } - - if ( - children && - children.some( - child => - child.keyword === "pattern" && child.dataPath === ".devtool" - ) - ) { - return ( - `${formattedError}\n` + - "BREAKING CHANGE since webpack 5: The devtool option is more strict.\n" + - "Please strictly follow the order of the keywords in the pattern." - ); - } - - if (error.keyword === "additionalProperties") { - const params = - /** @type {import("ajv").AdditionalPropertiesParams} */ ( - error.params - ); - if ( - Object.prototype.hasOwnProperty.call( - DID_YOU_MEAN, - params.additionalProperty - ) - ) { - return `${formattedError}\nDid you mean ${ - DID_YOU_MEAN[params.additionalProperty] - }?`; - } - - if ( - Object.prototype.hasOwnProperty.call( - REMOVED, - params.additionalProperty - ) - ) { - return `${formattedError}\n${REMOVED[params.additionalProperty]}?`; - } - - if (!error.dataPath) { - if (params.additionalProperty === "debug") { - return ( - `${formattedError}\n` + - "The 'debug' property was removed in webpack 2.0.0.\n" + - "Loaders should be updated to allow passing this option via loader options in module.rules.\n" + - "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" + - "plugins: [\n" + - " new webpack.LoaderOptionsPlugin({\n" + - " debug: true\n" + - " })\n" + - "]" - ); - } - - if (params.additionalProperty) { - return ( - `${formattedError}\n` + - "For typos: please correct them.\n" + - "For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.\n" + - " Loaders should be updated to allow passing options via loader options in module.rules.\n" + - " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" + - " plugins: [\n" + - " new webpack.LoaderOptionsPlugin({\n" + - " // test: /\\.xxx$/, // may apply this only for some modules\n" + - " options: {\n" + - ` ${params.additionalProperty}: …\n` + - " }\n" + - " })\n" + - " ]" - ); - } - } - } +function mergeFilteredToArray(array, filter) { + /** @type {Array} */ + const result = []; + const set = new Set(array); - return formattedError; + for (const item of set) { + if (filter(item)) { + const lastElement = + result.length > 0 ? result[result.length - 1] : undefined; + if (Array.isArray(lastElement)) { + lastElement.push(item); + } else { + result.push([item]); } + } else { + result.push(item); } - ); -}; -module.exports = validateSchema; + } + + return result; +} /***/ }), -/***/ 5434: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 36400: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -class AsyncWasmLoadingRuntimeModule extends RuntimeModule { - constructor({ generateLoadBinaryCode, supportsStreaming }) { - super("wasm loading", RuntimeModule.STAGE_NORMAL); - this.generateLoadBinaryCode = generateLoadBinaryCode; - this.supportsStreaming = supportsStreaming; +const slashCode = "/".charCodeAt(0); +const backslashCode = "\\".charCodeAt(0); + +const isInside = (path, parent) => { + if (!path.startsWith(parent)) return false; + if (path.length === parent.length) return true; + const charCode = path.charCodeAt(parent.length); + return charCode === slashCode || charCode === backslashCode; +}; + +module.exports = class RestrictionsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} restrictions restrictions + */ + constructor(source, restrictions) { + this.source = source; + this.restrictions = restrictions; } /** - * @returns {string} runtime code + * @param {Resolver} resolver the resolver + * @returns {void} */ - generate() { - const { compilation, chunk } = this; - const { outputOptions, runtimeTemplate } = compilation; - const fn = RuntimeGlobals.instantiateWasm; - const wasmModuleSrcPath = compilation.getPath( - JSON.stringify(outputOptions.webassemblyModuleFilename), - { - hash: `" + ${RuntimeGlobals.getFullHash}() + "`, - hashWithLength: length => - `" + ${RuntimeGlobals.getFullHash}}().slice(0, ${length}) + "`, - module: { - id: '" + wasmModuleId + "', - hash: `" + wasmModuleHash + "`, - hashWithLength(length) { - return `" + wasmModuleHash.slice(0, ${length}) + "`; + apply(resolver) { + resolver + .getHook(this.source) + .tapAsync("RestrictionsPlugin", (request, resolveContext, callback) => { + if (typeof request.path === "string") { + const path = request.path; + for (const rule of this.restrictions) { + if (typeof rule === "string") { + if (!isInside(path, rule)) { + if (resolveContext.log) { + resolveContext.log( + `${path} is not inside of the restriction ${rule}` + ); + } + return callback(null, null); + } + } else if (!rule.test(path)) { + if (resolveContext.log) { + resolveContext.log( + `${path} doesn't match the restriction ${rule}` + ); + } + return callback(null, null); + } } - }, - runtime: chunk.runtime - } - ); - return `${fn} = ${runtimeTemplate.basicFunction( - "exports, wasmModuleId, wasmModuleHash, importsObj", - [ - `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, - this.supportsStreaming - ? Template.asString([ - "if (typeof WebAssembly.instantiateStreaming === 'function') {", - Template.indent([ - "return WebAssembly.instantiateStreaming(req, importsObj)", - Template.indent([ - `.then(${runtimeTemplate.returningFunction( - "Object.assign(exports, res.instance.exports)", - "res" - )});` - ]) - ]), - "}" - ]) - : "// no support for streaming compilation", - "return req", - Template.indent([ - `.then(${runtimeTemplate.returningFunction("x.arrayBuffer()", "x")})`, - `.then(${runtimeTemplate.returningFunction( - "WebAssembly.instantiate(bytes, importsObj)", - "bytes" - )})`, - `.then(${runtimeTemplate.returningFunction( - "Object.assign(exports, res.instance.exports)", - "res" - )});` - ]) - ] - )};`; - } -} + } -module.exports = AsyncWasmLoadingRuntimeModule; + callback(); + }); + } +}; /***/ }), -/***/ 58461: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 13965: +/***/ (function(module) { "use strict"; /* @@ -136932,253 +136960,111 @@ module.exports = AsyncWasmLoadingRuntimeModule; -const Generator = __webpack_require__(93401); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../NormalModule")} NormalModule */ - -const TYPES = new Set(["webassembly"]); - -class AsyncWebAssemblyGenerator extends Generator { - constructor(options) { - super(); - this.options = options; - } - - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +module.exports = class ResultPlugin { /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module + * @param {ResolveStepHook} source source */ - getSize(module, type) { - const originalSource = module.originalSource(); - if (!originalSource) { - return 0; - } - return originalSource.size(); + constructor(source) { + this.source = source; } /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code + * @param {Resolver} resolver the resolver + * @returns {void} */ - generate(module, generateContext) { - return module.originalSource(); + apply(resolver) { + this.source.tapAsync( + "ResultPlugin", + (request, resolverContext, callback) => { + const obj = { ...request }; + if (resolverContext.log) + resolverContext.log("reporting result " + obj.path); + resolver.hooks.result.callAsync(obj, resolverContext, err => { + if (err) return callback(err); + callback(null, obj); + }); + } + ); } -} - -module.exports = AsyncWebAssemblyGenerator; +}; /***/ }), -/***/ 95614: +/***/ 66737: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const { RawSource } = __webpack_require__(51255); -const Generator = __webpack_require__(93401); -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const WebAssemblyImportDependency = __webpack_require__(5239); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ - -const TYPES = new Set(["webassembly"]); - -class AsyncWebAssemblyJavascriptGenerator extends Generator { - constructor(filenameTemplate) { - super(); - this.filenameTemplate = filenameTemplate; - } +const forEachBail = __webpack_require__(78565); - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; - } +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +class RootsPlugin { /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module + * @param {string | ResolveStepHook} source source hook + * @param {Set} roots roots + * @param {string | ResolveStepHook} target target hook */ - getSize(module, type) { - return 40 + module.dependencies.length * 10; + constructor(source, roots, target) { + this.roots = Array.from(roots); + this.source = source; + this.target = target; } /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code + * @param {Resolver} resolver the resolver + * @returns {void} */ - generate(module, generateContext) { - const { - runtimeTemplate, - chunkGraph, - moduleGraph, - runtimeRequirements, - runtime - } = generateContext; - runtimeRequirements.add(RuntimeGlobals.module); - runtimeRequirements.add(RuntimeGlobals.moduleId); - runtimeRequirements.add(RuntimeGlobals.exports); - runtimeRequirements.add(RuntimeGlobals.instantiateWasm); - /** @type {InitFragment[]} */ - const initFragments = []; - /** @type {Map} */ - const depModules = new Map(); - /** @type {Map} */ - const wasmDepsByRequest = new Map(); - for (const dep of module.dependencies) { - if (dep instanceof WebAssemblyImportDependency) { - const module = moduleGraph.getModule(dep); - if (!depModules.has(module)) { - depModules.set(module, { - request: dep.request, - importVar: `WEBPACK_IMPORTED_MODULE_${depModules.size}` - }); - } - let list = wasmDepsByRequest.get(dep.request); - if (list === undefined) { - list = []; - wasmDepsByRequest.set(dep.request, list); - } - list.push(dep); - } - } - - const promises = []; - - const importStatements = Array.from( - depModules, - ([importedModule, { request, importVar }]) => { - if (moduleGraph.isAsync(importedModule)) { - promises.push(importVar); - } - return runtimeTemplate.importStatement({ - update: false, - module: importedModule, - chunkGraph, - request, - originModule: module, - importVar, - runtimeRequirements - }); - } - ); - const importsCode = importStatements.map(([x]) => x).join(""); - const importsCompatCode = importStatements.map(([_, x]) => x).join(""); - - const importObjRequestItems = Array.from( - wasmDepsByRequest, - ([request, deps]) => { - const exportItems = deps.map(dep => { - const importedModule = moduleGraph.getModule(dep); - const importVar = depModules.get(importedModule).importVar; - return `${JSON.stringify( - dep.name - )}: ${runtimeTemplate.exportFromImport({ - moduleGraph, - module: importedModule, - request, - exportName: dep.name, - originModule: module, - asiSafe: true, - isCall: false, - callContext: false, - defaultInterop: true, - importVar, - initFragments, - runtime, - runtimeRequirements - })}`; - }); - return Template.asString([ - `${JSON.stringify(request)}: {`, - Template.indent(exportItems.join(",\n")), - "}" - ]); - } - ); - - const importsObj = - importObjRequestItems.length > 0 - ? Template.asString([ - "{", - Template.indent(importObjRequestItems.join(",\n")), - "}" - ]) - : undefined; - - const instantiateCall = - `${RuntimeGlobals.instantiateWasm}(${module.exportsArgument}, ${ - module.moduleArgument - }.id, ${JSON.stringify( - chunkGraph.getRenderedModuleHash(module, runtime) - )}` + (importsObj ? `, ${importsObj})` : `)`); - - if (promises.length > 0) - runtimeRequirements.add(RuntimeGlobals.asyncModule); - - const source = new RawSource( - promises.length > 0 - ? Template.asString([ - `var __webpack_instantiate__ = ${runtimeTemplate.basicFunction( - `[${promises.join(", ")}]`, - `${importsCompatCode}return ${instantiateCall};` - )}`, - `${RuntimeGlobals.asyncModule}(${ - module.moduleArgument - }, ${runtimeTemplate.basicFunction( - "__webpack_handle_async_dependencies__", - [ - importsCode, - `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${promises.join( - ", " - )}]);`, - "return __webpack_async_dependencies__.then ? __webpack_async_dependencies__.then(__webpack_instantiate__) : __webpack_instantiate__(__webpack_async_dependencies__);" - ] - )}, 1);` - ]) - : `${importsCode}${importsCompatCode}module.exports = ${instantiateCall};` - ); + apply(resolver) { + const target = resolver.ensureHook(this.target); - return InitFragment.addToSource(source, initFragments, generateContext); + resolver + .getHook(this.source) + .tapAsync("RootsPlugin", (request, resolveContext, callback) => { + const req = request.request; + if (!req) return callback(); + if (!req.startsWith("/")) return callback(); + + forEachBail( + this.roots, + (root, callback) => { + const path = resolver.join(root, req.slice(1)); + const obj = { + ...request, + path, + relativePath: request.relativePath && path + }; + resolver.doResolve( + target, + obj, + `root path ${root}`, + resolveContext, + callback + ); + }, + callback + ); + }); } } -module.exports = AsyncWebAssemblyJavascriptGenerator; +module.exports = RootsPlugin; /***/ }), -/***/ 7538: +/***/ 52232: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -137189,202 +137075,84 @@ module.exports = AsyncWebAssemblyJavascriptGenerator; -const { SyncWaterfallHook } = __webpack_require__(41242); -const Compilation = __webpack_require__(85720); -const Generator = __webpack_require__(93401); -const { tryRunOrWebpackError } = __webpack_require__(11351); -const WebAssemblyImportDependency = __webpack_require__(5239); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const memoize = __webpack_require__(78676); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../Template").RenderManifestEntry} RenderManifestEntry */ -/** @typedef {import("../Template").RenderManifestOptions} RenderManifestOptions */ - -const getAsyncWebAssemblyGenerator = memoize(() => - __webpack_require__(58461) -); -const getAsyncWebAssemblyJavascriptGenerator = memoize(() => - __webpack_require__(95614) -); -const getAsyncWebAssemblyParser = memoize(() => - __webpack_require__(96305) -); - -/** - * @typedef {Object} WebAssemblyRenderContext - * @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 - * @property {CodeGenerationResults} codeGenerationResults results of code generation - */ +const DescriptionFileUtils = __webpack_require__(25424); -/** - * @typedef {Object} CompilationHooks - * @property {SyncWaterfallHook<[Source, Module, WebAssemblyRenderContext]>} renderModuleContent - */ +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); +const slashCode = "/".charCodeAt(0); -class AsyncWebAssemblyModulesPlugin { +module.exports = class SelfReferencePlugin { /** - * @param {Compilation} compilation the compilation - * @returns {CompilationHooks} the attached hooks + * @param {string | ResolveStepHook} source source + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} target target */ - 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 = { - renderModuleContent: new SyncWaterfallHook([ - "source", - "module", - "renderContext" - ]) - }; - compilationHooksMap.set(compilation, hooks); - } - return hooks; - } - - constructor(options) { - this.options = options; + constructor(source, fieldNamePath, target) { + this.source = source; + this.target = target; + this.fieldName = fieldNamePath; } /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance + * @param {Resolver} resolver the resolver * @returns {void} */ - apply(compiler) { - compiler.hooks.compilation.tap( - "AsyncWebAssemblyModulesPlugin", - (compilation, { normalModuleFactory }) => { - const hooks = - AsyncWebAssemblyModulesPlugin.getCompilationHooks(compilation); - compilation.dependencyFactories.set( - WebAssemblyImportDependency, - normalModuleFactory - ); - - normalModuleFactory.hooks.createParser - .for("webassembly/async") - .tap("AsyncWebAssemblyModulesPlugin", () => { - const AsyncWebAssemblyParser = getAsyncWebAssemblyParser(); - - return new AsyncWebAssemblyParser(); - }); - normalModuleFactory.hooks.createGenerator - .for("webassembly/async") - .tap("AsyncWebAssemblyModulesPlugin", () => { - const AsyncWebAssemblyJavascriptGenerator = - getAsyncWebAssemblyJavascriptGenerator(); - const AsyncWebAssemblyGenerator = getAsyncWebAssemblyGenerator(); + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("SelfReferencePlugin", (request, resolveContext, callback) => { + if (!request.descriptionFilePath) return callback(); - return Generator.byType({ - javascript: new AsyncWebAssemblyJavascriptGenerator( - compilation.outputOptions.webassemblyModuleFilename - ), - webassembly: new AsyncWebAssemblyGenerator(this.options) - }); - }); + const req = request.request; + if (!req) return callback(); - compilation.hooks.renderManifest.tap( - "WebAssemblyModulesPlugin", - (result, options) => { - const { moduleGraph, chunkGraph, runtimeTemplate } = compilation; - const { - chunk, - outputOptions, - dependencyTemplates, - codeGenerationResults - } = options; + // Feature is only enabled when an exports field is present + const exportsField = DescriptionFileUtils.getField( + request.descriptionFileData, + this.fieldName + ); + if (!exportsField) return callback(); - for (const module of chunkGraph.getOrderedChunkModulesIterable( - chunk, - compareModulesByIdentifier - )) { - if (module.type === "webassembly/async") { - const filenameTemplate = - outputOptions.webassemblyModuleFilename; + const name = DescriptionFileUtils.getField( + request.descriptionFileData, + "name" + ); + if (typeof name !== "string") return callback(); - result.push({ - render: () => - this.renderModule( - module, - { - chunk, - dependencyTemplates, - runtimeTemplate, - moduleGraph, - chunkGraph, - codeGenerationResults - }, - hooks - ), - filenameTemplate, - pathOptions: { - module, - runtime: chunk.runtime, - chunkGraph - }, - auxiliary: true, - identifier: `webassemblyAsyncModule${chunkGraph.getModuleId( - module - )}`, - hash: chunkGraph.getModuleHash(module, chunk.runtime) - }); - } - } + if ( + req.startsWith(name) && + (req.length === name.length || + req.charCodeAt(name.length) === slashCode) + ) { + const remainingRequest = `.${req.slice(name.length)}`; - return result; - } - ); - } - ); - } + const obj = { + ...request, + request: remainingRequest, + path: /** @type {string} */ (request.descriptionFileRoot), + relativePath: "." + }; - renderModule(module, renderContext, hooks) { - const { codeGenerationResults, chunk } = renderContext; - try { - const moduleSource = codeGenerationResults.getSource( - module, - chunk.runtime, - "webassembly" - ); - return tryRunOrWebpackError( - () => - hooks.renderModuleContent.call(moduleSource, module, renderContext), - "AsyncWebAssemblyModulesPlugin.getCompilationHooks().renderModuleContent" - ); - } catch (e) { - e.module = module; - throw e; - } + resolver.doResolve( + target, + obj, + "self reference", + resolveContext, + callback + ); + } else { + return callback(); + } + }); } -} - -module.exports = AsyncWebAssemblyModulesPlugin; +}; /***/ }), -/***/ 96305: +/***/ 58885: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -137395,484 +137163,454 @@ module.exports = AsyncWebAssemblyModulesPlugin; -const t = __webpack_require__(51826); -const { decode } = __webpack_require__(73726); -const Parser = __webpack_require__(11715); -const StaticExportsDependency = __webpack_require__(91418); -const WebAssemblyImportDependency = __webpack_require__(5239); - -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ - -const decoderOpts = { - ignoreCodeSection: true, - ignoreDataSection: true, +const forEachBail = __webpack_require__(78565); +const getPaths = __webpack_require__(82918); +const { getType, PathType } = __webpack_require__(67079); - // this will avoid having to lookup with identifiers in the ModuleContext - ignoreCustomNameSection: true -}; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -class WebAssemblyParser extends Parser { - constructor(options) { - super(); - this.hooks = Object.freeze({}); - this.options = options; +module.exports = class SymlinkPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; } /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state + * @param {Resolver} resolver the resolver + * @returns {void} */ - parse(source, state) { - if (!Buffer.isBuffer(source)) { - throw new Error("WebAssemblyParser input must be a Buffer"); - } + apply(resolver) { + const target = resolver.ensureHook(this.target); + const fs = resolver.fileSystem; + resolver + .getHook(this.source) + .tapAsync("SymlinkPlugin", (request, resolveContext, callback) => { + if (request.ignoreSymlinks) return callback(); + const pathsResult = getPaths(request.path); + const pathSeqments = pathsResult.seqments; + const paths = pathsResult.paths; - // flag it as async module - state.module.buildInfo.strict = true; - state.module.buildMeta.exportsType = "namespace"; - state.module.buildMeta.async = true; + let containsSymlink = false; + let idx = -1; + forEachBail( + paths, + (path, callback) => { + idx++; + if (resolveContext.fileDependencies) + resolveContext.fileDependencies.add(path); + fs.readlink(path, (err, result) => { + if (!err && result) { + pathSeqments[idx] = result; + containsSymlink = true; + // Shortcut when absolute symlink found + const resultType = getType(result.toString()); + if ( + resultType === PathType.AbsoluteWin || + resultType === PathType.AbsolutePosix + ) { + return callback(null, idx); + } + } + callback(); + }); + }, + (err, idx) => { + if (!containsSymlink) return callback(); + const resultSeqments = + typeof idx === "number" + ? pathSeqments.slice(0, idx + 1) + : pathSeqments.slice(); + const result = resultSeqments.reduceRight((a, b) => { + return resolver.join(a, b); + }); + const obj = { + ...request, + path: result + }; + resolver.doResolve( + target, + obj, + "resolved symlink to " + result, + resolveContext, + callback + ); + } + ); + }); + } +}; - // parse it - const program = decode(source, decoderOpts); - const module = program.body[0]; - const exports = []; - t.traverse(module, { - ModuleExport({ node }) { - exports.push(node.name); - }, +/***/ }), - ModuleImport({ node }) { - const dep = new WebAssemblyImportDependency( - node.module, - node.name, - node.descr, - false - ); +/***/ 87474: +/***/ (function(module) { - state.module.addDependency(dep); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ + +/** + * @param {SyncFileSystem} fs file system implementation + * @constructor + */ +function SyncAsyncFileSystemDecorator(fs) { + this.fs = fs; + + this.lstat = undefined; + this.lstatSync = undefined; + const lstatSync = fs.lstatSync; + if (lstatSync) { + this.lstat = (arg, options, callback) => { + let result; + try { + result = lstatSync.call(fs, arg); + } catch (e) { + return (callback || options)(e); } - }); + (callback || options)(null, result); + }; + this.lstatSync = (arg, options) => lstatSync.call(fs, arg, options); + } - state.module.addDependency(new StaticExportsDependency(exports, false)); + this.stat = (arg, options, callback) => { + let result; + try { + result = callback ? fs.statSync(arg, options) : fs.statSync(arg); + } catch (e) { + return (callback || options)(e); + } + (callback || options)(null, result); + }; + this.statSync = (arg, options) => fs.statSync(arg, options); - return state; + this.readdir = (arg, options, callback) => { + let result; + try { + result = fs.readdirSync(arg); + } catch (e) { + return (callback || options)(e); + } + (callback || options)(null, result); + }; + this.readdirSync = (arg, options) => fs.readdirSync(arg, options); + + this.readFile = (arg, options, callback) => { + let result; + try { + result = fs.readFileSync(arg); + } catch (e) { + return (callback || options)(e); + } + (callback || options)(null, result); + }; + this.readFileSync = (arg, options) => fs.readFileSync(arg, options); + + this.readlink = (arg, options, callback) => { + let result; + try { + result = fs.readlinkSync(arg); + } catch (e) { + return (callback || options)(e); + } + (callback || options)(null, result); + }; + this.readlinkSync = (arg, options) => fs.readlinkSync(arg, options); + + this.readJson = undefined; + this.readJsonSync = undefined; + const readJsonSync = fs.readJsonSync; + if (readJsonSync) { + this.readJson = (arg, options, callback) => { + let result; + try { + result = readJsonSync.call(fs, arg); + } catch (e) { + return (callback || options)(e); + } + (callback || options)(null, result); + }; + + this.readJsonSync = (arg, options) => readJsonSync.call(fs, arg, options); } } - -module.exports = WebAssemblyParser; +module.exports = SyncAsyncFileSystemDecorator; /***/ }), -/***/ 78455: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 99324: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const WebpackError = __webpack_require__(53799); +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -module.exports = class UnsupportedWebAssemblyFeatureError extends WebpackError { - /** @param {string} message Error message */ - constructor(message) { - super(message); - this.name = "UnsupportedWebAssemblyFeatureError"; - this.hideStack = true; +module.exports = class TryNextPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} message message + * @param {string | ResolveStepHook} target target + */ + constructor(source, message, target) { + this.source = source; + this.message = message; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("TryNextPlugin", (request, resolveContext, callback) => { + resolver.doResolve( + target, + request, + this.message, + resolveContext, + callback + ); + }); } }; /***/ }), -/***/ 87394: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 41606: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const WebAssemblyUtils = __webpack_require__(18650); - -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {{[k: string]: any}} Cache */ -// TODO webpack 6 remove the whole folder +function getCacheId(request, withContext) { + return JSON.stringify({ + context: withContext ? request.context : "", + path: request.path, + query: request.query, + fragment: request.fragment, + request: request.request + }); +} -// Get all wasm modules -const getAllWasmModules = (moduleGraph, chunkGraph, chunk) => { - const wasmModules = chunk.getAllAsyncChunks(); - const array = []; - for (const chunk of wasmModules) { - for (const m of chunkGraph.getOrderedChunkModulesIterable( - chunk, - compareModulesByIdentifier - )) { - if (m.type.startsWith("webassembly")) { - array.push(m); - } - } +module.exports = class UnsafeCachePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {function(ResolveRequest): boolean} filterPredicate filterPredicate + * @param {Cache} cache cache + * @param {boolean} withContext withContext + * @param {string | ResolveStepHook} target target + */ + constructor(source, filterPredicate, cache, withContext, target) { + this.source = source; + this.filterPredicate = filterPredicate; + this.withContext = withContext; + this.cache = cache; + this.target = target; } - return array; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("UnsafeCachePlugin", (request, resolveContext, callback) => { + if (!this.filterPredicate(request)) return callback(); + const cacheId = getCacheId(request, this.withContext); + const cacheEntry = this.cache[cacheId]; + if (cacheEntry) { + return callback(null, cacheEntry); + } + resolver.doResolve( + target, + request, + null, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, (this.cache[cacheId] = result)); + callback(); + } + ); + }); + } }; -/** - * generates the import object function for a module - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {Module} module the module - * @param {boolean} mangle mangle imports - * @param {string[]} declarations array where declarations are pushed to - * @param {RuntimeSpec} runtime the runtime - * @returns {string} source code - */ -const generateImportObject = ( - chunkGraph, - module, - mangle, - declarations, - runtime -) => { - const moduleGraph = chunkGraph.moduleGraph; - const waitForInstances = new Map(); - const properties = []; - const usedWasmDependencies = WebAssemblyUtils.getUsedDependencies( - moduleGraph, - module, - mangle - ); - for (const usedDep of usedWasmDependencies) { - const dep = usedDep.dependency; - const importedModule = moduleGraph.getModule(dep); - const exportName = dep.name; - const usedName = - importedModule && - moduleGraph - .getExportsInfo(importedModule) - .getUsedName(exportName, runtime); - const description = dep.description; - const direct = dep.onlyDirectImport; - const module = usedDep.module; - const name = usedDep.name; +/***/ }), - if (direct) { - const instanceVar = `m${waitForInstances.size}`; - waitForInstances.set(instanceVar, chunkGraph.getModuleId(importedModule)); - properties.push({ - module, - name, - value: `${instanceVar}[${JSON.stringify(usedName)}]` - }); - } else { - const params = description.signature.params.map( - (param, k) => "p" + k + param.valtype - ); +/***/ 96972: +/***/ (function(module) { - const mod = `${RuntimeGlobals.moduleCache}[${JSON.stringify( - chunkGraph.getModuleId(importedModule) - )}]`; - const modExports = `${mod}.exports`; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const cache = `wasmImportedFuncCache${declarations.length}`; - declarations.push(`var ${cache};`); - properties.push({ - module, - name, - value: Template.asString([ - (importedModule.type.startsWith("webassembly") - ? `${mod} ? ${modExports}[${JSON.stringify(usedName)}] : ` - : "") + `function(${params}) {`, - Template.indent([ - `if(${cache} === undefined) ${cache} = ${modExports};`, - `return ${cache}[${JSON.stringify(usedName)}](${params});` - ]), - "}" - ]) - }); - } - } - let importObject; - if (mangle) { - importObject = [ - "return {", - Template.indent([ - properties.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") - ]), - "};" - ]; - } else { - const propertiesByModule = new Map(); - for (const p of properties) { - let list = propertiesByModule.get(p.module); - if (list === undefined) { - propertiesByModule.set(p.module, (list = [])); - } - list.push(p); - } - importObject = [ - "return {", - Template.indent([ - Array.from(propertiesByModule, ([module, list]) => { - return Template.asString([ - `${JSON.stringify(module)}: {`, - Template.indent([ - list.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") - ]), - "}" - ]); - }).join(",\n") - ]), - "};" - ]; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class UseFilePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} filename filename + * @param {string | ResolveStepHook} target target + */ + constructor(source, filename, target) { + this.source = source; + this.filename = filename; + this.target = target; } - const moduleIdStringified = JSON.stringify(chunkGraph.getModuleId(module)); - if (waitForInstances.size === 1) { - const moduleId = Array.from(waitForInstances.values())[0]; - const promise = `installedWasmModules[${JSON.stringify(moduleId)}]`; - const variable = Array.from(waitForInstances.keys())[0]; - return Template.asString([ - `${moduleIdStringified}: function() {`, - Template.indent([ - `return promiseResolve().then(function() { return ${promise}; }).then(function(${variable}) {`, - Template.indent(importObject), - "});" - ]), - "}," - ]); - } else if (waitForInstances.size > 0) { - const promises = Array.from( - waitForInstances.values(), - id => `installedWasmModules[${JSON.stringify(id)}]` - ).join(", "); - const variables = Array.from( - waitForInstances.keys(), - (name, i) => `${name} = array[${i}]` - ).join(", "); - return Template.asString([ - `${moduleIdStringified}: function() {`, - Template.indent([ - `return promiseResolve().then(function() { return Promise.all([${promises}]); }).then(function(array) {`, - Template.indent([`var ${variables};`, ...importObject]), - "});" - ]), - "}," - ]); - } else { - return Template.asString([ - `${moduleIdStringified}: function() {`, - Template.indent(importObject), - "}," - ]); + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("UseFilePlugin", (request, resolveContext, callback) => { + const filePath = resolver.join(request.path, this.filename); + const obj = { + ...request, + path: filePath, + relativePath: + request.relativePath && + resolver.join(request.relativePath, this.filename) + }; + resolver.doResolve( + target, + obj, + "using path: " + filePath, + resolveContext, + callback + ); + }); } }; -class WasmChunkLoadingRuntimeModule extends RuntimeModule { - constructor({ - generateLoadBinaryCode, - supportsStreaming, - mangleImports, - runtimeRequirements - }) { - super("wasm chunk loading", RuntimeModule.STAGE_ATTACH); - this.generateLoadBinaryCode = generateLoadBinaryCode; - this.supportsStreaming = supportsStreaming; - this.mangleImports = mangleImports; - this._runtimeRequirements = runtimeRequirements; - } - /** - * @returns {string} runtime code - */ - generate() { - const { chunkGraph, compilation, chunk, mangleImports } = this; - const { moduleGraph, outputOptions } = compilation; - const fn = RuntimeGlobals.ensureChunkHandlers; - const withHmr = this._runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const wasmModules = getAllWasmModules(moduleGraph, chunkGraph, chunk); - const declarations = []; - const importObjects = wasmModules.map(module => { - return generateImportObject( - chunkGraph, - module, - this.mangleImports, - declarations, - chunk.runtime - ); - }); - const chunkModuleIdMap = chunkGraph.getChunkModuleIdMap(chunk, m => - m.type.startsWith("webassembly") - ); - const createImportObject = content => - mangleImports - ? `{ ${JSON.stringify(WebAssemblyUtils.MANGLED_MODULE)}: ${content} }` - : content; - const wasmModuleSrcPath = compilation.getPath( - JSON.stringify(outputOptions.webassemblyModuleFilename), - { - hash: `" + ${RuntimeGlobals.getFullHash}() + "`, - hashWithLength: length => - `" + ${RuntimeGlobals.getFullHash}}().slice(0, ${length}) + "`, - module: { - id: '" + wasmModuleId + "', - hash: `" + ${JSON.stringify( - chunkGraph.getChunkModuleRenderedHashMap(chunk, m => - m.type.startsWith("webassembly") - ) - )}[chunkId][wasmModuleId] + "`, - hashWithLength(length) { - return `" + ${JSON.stringify( - chunkGraph.getChunkModuleRenderedHashMap( - chunk, - m => m.type.startsWith("webassembly"), - length - ) - )}[chunkId][wasmModuleId] + "`; - } - }, - runtime: chunk.runtime - } - ); +/***/ }), - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_wasm` - : undefined; +/***/ 81218: +/***/ (function(module) { - return Template.asString([ - "// object to store loaded and loading wasm modules", - `var installedWasmModules = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{};`, - "", - // This function is used to delay reading the installed wasm module promises - // by a microtask. Sorting them doesn't help because there are edge cases where - // sorting is not possible (modules splitted into different chunks). - // So we not even trying and solve this by a microtask delay. - "function promiseResolve() { return Promise.resolve(); }", - "", - Template.asString(declarations), - "var wasmImportObjects = {", - Template.indent(importObjects), - "};", - "", - `var wasmModuleMap = ${JSON.stringify( - chunkModuleIdMap, - undefined, - "\t" - )};`, - "", - "// object with all WebAssembly.instance exports", - `${RuntimeGlobals.wasmInstances} = {};`, - "", - "// Fetch + compile chunk loading for webassembly", - `${fn}.wasm = function(chunkId, promises) {`, - Template.indent([ - "", - `var wasmModules = wasmModuleMap[chunkId] || [];`, - "", - "wasmModules.forEach(function(wasmModuleId, idx) {", - Template.indent([ - "var installedWasmModuleData = installedWasmModules[wasmModuleId];", - "", - '// a Promise means "currently loading" or "already loaded".', - "if(installedWasmModuleData)", - Template.indent(["promises.push(installedWasmModuleData);"]), - "else {", - Template.indent([ - `var importObject = wasmImportObjects[wasmModuleId]();`, - `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, - "var promise;", - this.supportsStreaming - ? Template.asString([ - "if(importObject && typeof importObject.then === 'function' && typeof WebAssembly.compileStreaming === 'function') {", - Template.indent([ - "promise = Promise.all([WebAssembly.compileStreaming(req), importObject]).then(function(items) {", - Template.indent([ - `return WebAssembly.instantiate(items[0], ${createImportObject( - "items[1]" - )});` - ]), - "});" - ]), - "} else if(typeof WebAssembly.instantiateStreaming === 'function') {", - Template.indent([ - `promise = WebAssembly.instantiateStreaming(req, ${createImportObject( - "importObject" - )});` - ]) - ]) - : Template.asString([ - "if(importObject && typeof importObject.then === 'function') {", - Template.indent([ - "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", - "promise = Promise.all([", - Template.indent([ - "bytesPromise.then(function(bytes) { return WebAssembly.compile(bytes); }),", - "importObject" - ]), - "]).then(function(items) {", - Template.indent([ - `return WebAssembly.instantiate(items[0], ${createImportObject( - "items[1]" - )});` - ]), - "});" - ]) - ]), - "} else {", - Template.indent([ - "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", - "promise = bytesPromise.then(function(bytes) {", - Template.indent([ - `return WebAssembly.instantiate(bytes, ${createImportObject( - "importObject" - )});` - ]), - "});" - ]), - "}", - "promises.push(installedWasmModules[wasmModuleId] = promise.then(function(res) {", - Template.indent([ - `return ${RuntimeGlobals.wasmInstances}[wasmModuleId] = (res.instance || res).exports;` - ]), - "}));" - ]), - "}" - ]), - "});" - ]), - "};" - ]); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +module.exports = function createInnerContext( + options, + message, + messageOptional +) { + let messageReported = false; + let innerLog = undefined; + if (options.log) { + if (message) { + innerLog = msg => { + if (!messageReported) { + options.log(message); + messageReported = true; + } + options.log(" " + msg); + }; + } else { + innerLog = options.log; + } } -} + const childContext = { + log: innerLog, + fileDependencies: options.fileDependencies, + contextDependencies: options.contextDependencies, + missingDependencies: options.missingDependencies, + stack: options.stack + }; + return childContext; +}; -module.exports = WasmChunkLoadingRuntimeModule; + +/***/ }), + +/***/ 78565: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +module.exports = function forEachBail(array, iterator, callback) { + if (array.length === 0) return callback(); + + let i = 0; + const next = () => { + let loop = undefined; + iterator(array[i++], (err, result) => { + if (err || result !== undefined || i >= array.length) { + return callback(err, result); + } + if (loop === false) while (next()); + loop = true; + }); + if (!loop) loop = false; + return loop; + }; + while (next()); +}; /***/ }), -/***/ 19810: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 47956: +/***/ (function(module) { "use strict"; /* @@ -137882,86 +137620,75 @@ module.exports = WasmChunkLoadingRuntimeModule; -const formatLocation = __webpack_require__(16734); -const UnsupportedWebAssemblyFeatureError = __webpack_require__(78455); +module.exports = function getInnerRequest(resolver, request) { + if ( + typeof request.__innerRequest === "string" && + request.__innerRequest_request === request.request && + request.__innerRequest_relativePath === request.relativePath + ) + return request.__innerRequest; + let innerRequest; + if (request.request) { + innerRequest = request.request; + if (/^\.\.?(?:\/|$)/.test(innerRequest) && request.relativePath) { + innerRequest = resolver.join(request.relativePath, innerRequest); + } + } else { + innerRequest = request.relativePath; + } + request.__innerRequest_request = request.request; + request.__innerRequest_relativePath = request.relativePath; + return (request.__innerRequest = innerRequest); +}; -/** @typedef {import("../Compiler")} Compiler */ -class WasmFinalizeExportsPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap("WasmFinalizeExportsPlugin", compilation => { - compilation.hooks.finishModules.tap( - "WasmFinalizeExportsPlugin", - modules => { - for (const module of modules) { - // 1. if a WebAssembly module - if (module.type.startsWith("webassembly") === true) { - const jsIncompatibleExports = - module.buildMeta.jsIncompatibleExports; +/***/ }), - if (jsIncompatibleExports === undefined) { - continue; - } +/***/ 82918: +/***/ (function(module) { - for (const connection of compilation.moduleGraph.getIncomingConnections( - module - )) { - // 2. is active and referenced by a non-WebAssembly module - if ( - connection.isTargetActive(undefined) && - connection.originModule.type.startsWith("webassembly") === - false - ) { - const referencedExports = - compilation.getDependencyReferencedExports( - connection.dependency, - undefined - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - for (const info of referencedExports) { - const names = Array.isArray(info) ? info : info.name; - if (names.length === 0) continue; - const name = names[0]; - if (typeof name === "object") continue; - // 3. and uses a func with an incompatible JS signature - if ( - Object.prototype.hasOwnProperty.call( - jsIncompatibleExports, - name - ) - ) { - // 4. error - const error = new UnsupportedWebAssemblyFeatureError( - `Export "${name}" with ${jsIncompatibleExports[name]} can only be used for direct wasm to wasm dependencies\n` + - `It's used from ${connection.originModule.readableIdentifier( - compilation.requestShortener - )} at ${formatLocation(connection.dependency.loc)}.` - ); - error.module = module; - compilation.errors.push(error); - } - } - } - } - } - } - } - ); - }); + + +module.exports = function getPaths(path) { + const parts = path.split(/(.*?[\\/]+)/); + const paths = [path]; + const seqments = [parts[parts.length - 1]]; + let part = parts[parts.length - 1]; + path = path.substr(0, path.length - part.length - 1); + for (let i = parts.length - 2; i > 2; i -= 2) { + paths.push(path); + part = parts[i]; + path = path.substr(0, path.length - part.length) || "/"; + seqments.push(part.substr(0, part.length - 1)); } -} + part = parts[1]; + seqments.push(part); + paths.push(part); + return { + paths: paths, + seqments: seqments + }; +}; -module.exports = WasmFinalizeExportsPlugin; +module.exports.basename = function basename(path) { + const i = path.lastIndexOf("/"), + j = path.lastIndexOf("\\"); + const p = i < 0 ? j : j < 0 ? i : i < j ? j : i; + if (p < 0) return null; + const s = path.substr(p + 1); + return s; +}; /***/ }), -/***/ 47012: +/***/ 9256: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -137972,1194 +137699,1883 @@ module.exports = WasmFinalizeExportsPlugin; -const { RawSource } = __webpack_require__(51255); -const Generator = __webpack_require__(93401); -const WebAssemblyUtils = __webpack_require__(18650); +const fs = __webpack_require__(90552); +const CachedInputFileSystem = __webpack_require__(52788); +const ResolverFactory = __webpack_require__(47716); -const t = __webpack_require__(51826); -const { moduleContextFromModuleAST } = __webpack_require__(51826); -const { editWithAST, addWithAST } = __webpack_require__(87362); -const { decode } = __webpack_require__(73726); +/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./ResolverFactory").Plugin} Plugin */ +/** @typedef {import("./ResolverFactory").UserResolveOptions} ResolveOptions */ -const WebAssemblyExportImportedDependency = __webpack_require__(52204); +const nodeFileSystem = new CachedInputFileSystem(fs, 4000); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ -/** @typedef {import("./WebAssemblyUtils").UsedWasmDependency} UsedWasmDependency */ +const nodeContext = { + environments: ["node+es3+es5+process+native"] +}; + +const asyncResolver = ResolverFactory.createResolver({ + conditionNames: ["node"], + extensions: [".js", ".json", ".node"], + fileSystem: nodeFileSystem +}); +function resolve(context, path, request, resolveContext, callback) { + if (typeof context === "string") { + callback = resolveContext; + resolveContext = request; + request = path; + path = context; + context = nodeContext; + } + if (typeof callback !== "function") { + callback = resolveContext; + } + asyncResolver.resolve(context, path, request, resolveContext, callback); +} + +const syncResolver = ResolverFactory.createResolver({ + conditionNames: ["node"], + extensions: [".js", ".json", ".node"], + useSyncFileSystemCalls: true, + fileSystem: nodeFileSystem +}); +function resolveSync(context, path, request) { + if (typeof context === "string") { + request = path; + path = context; + context = nodeContext; + } + return syncResolver.resolveSync(context, path, request); +} + +function create(options) { + options = { + fileSystem: nodeFileSystem, + ...options + }; + const resolver = ResolverFactory.createResolver(options); + return function (context, path, request, resolveContext, callback) { + if (typeof context === "string") { + callback = resolveContext; + resolveContext = request; + request = path; + path = context; + context = nodeContext; + } + if (typeof callback !== "function") { + callback = resolveContext; + } + resolver.resolve(context, path, request, resolveContext, callback); + }; +} + +function createSync(options) { + options = { + useSyncFileSystemCalls: true, + fileSystem: nodeFileSystem, + ...options + }; + const resolver = ResolverFactory.createResolver(options); + return function (context, path, request) { + if (typeof context === "string") { + request = path; + path = context; + context = nodeContext; + } + return resolver.resolveSync(context, path, request); + }; +} /** - * @typedef {(ArrayBuffer) => ArrayBuffer} ArrayBufferTransform + * @template A + * @template B + * @param {A} obj input a + * @param {B} exports input b + * @returns {A & B} merged + */ +const mergeExports = (obj, exports) => { + const descriptors = Object.getOwnPropertyDescriptors(exports); + Object.defineProperties(obj, descriptors); + return /** @type {A & B} */ (Object.freeze(obj)); +}; + +module.exports = mergeExports(resolve, { + get sync() { + return resolveSync; + }, + create: mergeExports(create, { + get sync() { + return createSync; + } + }), + ResolverFactory, + CachedInputFileSystem, + get CloneBasenamePlugin() { + return __webpack_require__(22254); + }, + get LogInfoPlugin() { + return __webpack_require__(5049); + }, + get forEachBail() { + return __webpack_require__(78565); + } +}); + + +/***/ }), + +/***/ 55863: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + + + +/** @typedef {string|(string|ConditionalMapping)[]} DirectMapping */ +/** @typedef {{[k: string]: MappingValue}} ConditionalMapping */ +/** @typedef {ConditionalMapping|DirectMapping|null} MappingValue */ +/** @typedef {Record|ConditionalMapping|DirectMapping} ExportsField */ +/** @typedef {Record} ImportsField */ + +/** + * @typedef {Object} PathTreeNode + * @property {Map|null} children + * @property {MappingValue} folder + * @property {Map|null} wildcards + * @property {Map} files */ /** - * @template T - * @param {Function[]} fns transforms - * @returns {Function} composed transform + * Processing exports/imports field + * @callback FieldProcessor + * @param {string} request request + * @param {Set} conditionNames condition names + * @returns {string[]} resolved paths */ -const compose = (...fns) => { - return fns.reduce( - (prevFn, nextFn) => { - return value => nextFn(prevFn(value)); - }, - value => value + +/* +Example exports field: +{ + ".": "./main.js", + "./feature": { + "browser": "./feature-browser.js", + "default": "./feature.js" + } +} +Terminology: + +Enhanced-resolve name keys ("." and "./feature") as exports field keys. + +If value is string or string[], mapping is called as a direct mapping +and value called as a direct export. + +If value is key-value object, mapping is called as a conditional mapping +and value called as a conditional export. + +Key in conditional mapping is called condition name. + +Conditional mapping nested in another conditional mapping is called nested mapping. + +---------- + +Example imports field: +{ + "#a": "./main.js", + "#moment": { + "browser": "./moment/index.js", + "default": "moment" + }, + "#moment/": { + "browser": "./moment/", + "default": "moment/" + } +} +Terminology: + +Enhanced-resolve name keys ("#a" and "#moment/", "#moment") as imports field keys. + +If value is string or string[], mapping is called as a direct mapping +and value called as a direct export. + +If value is key-value object, mapping is called as a conditional mapping +and value called as a conditional export. + +Key in conditional mapping is called condition name. + +Conditional mapping nested in another conditional mapping is called nested mapping. + +*/ + +const slashCode = "/".charCodeAt(0); +const dotCode = ".".charCodeAt(0); +const hashCode = "#".charCodeAt(0); + +/** + * @param {ExportsField} exportsField the exports field + * @returns {FieldProcessor} process callback + */ +module.exports.processExportsField = function processExportsField( + exportsField +) { + return createFieldProcessor( + buildExportsFieldPathTree(exportsField), + assertExportsFieldRequest, + assertExportTarget ); }; /** - * Removes the start instruction - * - * @param {Object} state unused state - * @returns {ArrayBufferTransform} transform + * @param {ImportsField} importsField the exports field + * @returns {FieldProcessor} process callback */ -const removeStartFunc = state => bin => { - return editWithAST(state.ast, bin, { - Start(path) { - path.remove(); - } - }); +module.exports.processImportsField = function processImportsField( + importsField +) { + return createFieldProcessor( + buildImportsFieldPathTree(importsField), + assertImportsFieldRequest, + assertImportTarget + ); }; /** - * Get imported globals - * - * @param {Object} ast Module's AST - * @returns {Array} - nodes + * @param {PathTreeNode} treeRoot root + * @param {(s: string) => string} assertRequest assertRequest + * @param {(s: string, f: boolean) => void} assertTarget assertTarget + * @returns {FieldProcessor} field processor */ -const getImportedGlobals = ast => { - const importedGlobals = []; +function createFieldProcessor(treeRoot, assertRequest, assertTarget) { + return function fieldProcessor(request, conditionNames) { + request = assertRequest(request); - t.traverse(ast, { - ModuleImport({ node }) { - if (t.isGlobalType(node.descr)) { - importedGlobals.push(node); - } - } - }); + const match = findMatch(request, treeRoot); - return importedGlobals; -}; + if (match === null) return []; -/** - * Get the count for imported func - * - * @param {Object} ast Module's AST - * @returns {Number} - count - */ -const getCountImportedFunc = ast => { - let count = 0; + const [mapping, remainRequestIndex] = match; - t.traverse(ast, { - ModuleImport({ node }) { - if (t.isFuncImportDescr(node.descr)) { - count++; - } + /** @type {DirectMapping|null} */ + let direct = null; + + if (isConditionalMapping(mapping)) { + direct = conditionalMapping( + /** @type {ConditionalMapping} */ (mapping), + conditionNames + ); + + // matching not found + if (direct === null) return []; + } else { + direct = /** @type {DirectMapping} */ (mapping); } - }); - return count; -}; + const remainingRequest = + remainRequestIndex === request.length + 1 + ? undefined + : remainRequestIndex < 0 + ? request.slice(-remainRequestIndex - 1) + : request.slice(remainRequestIndex); + + return directMapping( + remainingRequest, + remainRequestIndex < 0, + direct, + conditionNames, + assertTarget + ); + }; +} /** - * Get next type index - * - * @param {Object} ast Module's AST - * @returns {t.Index} - index + * @param {string} request request + * @returns {string} updated request */ -const getNextTypeIndex = ast => { - const typeSectionMetadata = t.getSectionMetadata(ast, "type"); - - if (typeSectionMetadata === undefined) { - return t.indexLiteral(0); +function assertExportsFieldRequest(request) { + if (request.charCodeAt(0) !== dotCode) { + throw new Error('Request should be relative path and start with "."'); + } + if (request.length === 1) return ""; + if (request.charCodeAt(1) !== slashCode) { + throw new Error('Request should be relative path and start with "./"'); + } + if (request.charCodeAt(request.length - 1) === slashCode) { + throw new Error("Only requesting file allowed"); } - return t.indexLiteral(typeSectionMetadata.vectorOfSize.value); -}; + return request.slice(2); +} /** - * Get next func index - * - * The Func section metadata provide informations for implemented funcs - * in order to have the correct index we shift the index by number of external - * functions. - * - * @param {Object} ast Module's AST - * @param {Number} countImportedFunc number of imported funcs - * @returns {t.Index} - index + * @param {string} request request + * @returns {string} updated request */ -const getNextFuncIndex = (ast, countImportedFunc) => { - const funcSectionMetadata = t.getSectionMetadata(ast, "func"); +function assertImportsFieldRequest(request) { + if (request.charCodeAt(0) !== hashCode) { + throw new Error('Request should start with "#"'); + } + if (request.length === 1) { + throw new Error("Request should have at least 2 characters"); + } + if (request.charCodeAt(1) === slashCode) { + throw new Error('Request should not start with "#/"'); + } + if (request.charCodeAt(request.length - 1) === slashCode) { + throw new Error("Only requesting file allowed"); + } - if (funcSectionMetadata === undefined) { - return t.indexLiteral(0 + countImportedFunc); + return request.slice(1); +} + +/** + * @param {string} exp export target + * @param {boolean} expectFolder is folder expected + */ +function assertExportTarget(exp, expectFolder) { + if ( + exp.charCodeAt(0) === slashCode || + (exp.charCodeAt(0) === dotCode && exp.charCodeAt(1) !== slashCode) + ) { + throw new Error( + `Export should be relative path and start with "./", got ${JSON.stringify( + exp + )}.` + ); } - const vectorOfSize = funcSectionMetadata.vectorOfSize.value; + const isFolder = exp.charCodeAt(exp.length - 1) === slashCode; - return t.indexLiteral(vectorOfSize + countImportedFunc); -}; + if (isFolder !== expectFolder) { + throw new Error( + expectFolder + ? `Expecting folder to folder mapping. ${JSON.stringify( + exp + )} should end with "/"` + : `Expecting file to file mapping. ${JSON.stringify( + exp + )} should not end with "/"` + ); + } +} /** - * Creates an init instruction for a global type - * @param {t.GlobalType} globalType the global type - * @returns {t.Instruction} init expression + * @param {string} imp import target + * @param {boolean} expectFolder is folder expected */ -const createDefaultInitForGlobal = globalType => { - if (globalType.valtype[0] === "i") { - // create NumberLiteral global initializer - return t.objectInstruction("const", globalType.valtype, [ - t.numberLiteralFromRaw(66) - ]); - } else if (globalType.valtype[0] === "f") { - // create FloatLiteral global initializer - return t.objectInstruction("const", globalType.valtype, [ - t.floatLiteral(66, false, false, "66") - ]); - } else { - throw new Error("unknown type: " + globalType.valtype); +function assertImportTarget(imp, expectFolder) { + const isFolder = imp.charCodeAt(imp.length - 1) === slashCode; + + if (isFolder !== expectFolder) { + throw new Error( + expectFolder + ? `Expecting folder to folder mapping. ${JSON.stringify( + imp + )} should end with "/"` + : `Expecting file to file mapping. ${JSON.stringify( + imp + )} should not end with "/"` + ); } -}; +} /** - * Rewrite the import globals: - * - removes the ModuleImport instruction - * - injects at the same offset a mutable global of the same type - * - * Since the imported globals are before the other global declarations, our - * indices will be preserved. - * - * Note that globals will become mutable. - * - * @param {Object} state unused state - * @returns {ArrayBufferTransform} transform + * Trying to match request to field + * @param {string} request request + * @param {PathTreeNode} treeRoot path tree root + * @returns {[MappingValue, number]|null} match or null, number is negative and one less when it's a folder mapping, number is request.length + 1 for direct mappings */ -const rewriteImportedGlobals = state => bin => { - const additionalInitCode = state.additionalInitCode; - const newGlobals = []; +function findMatch(request, treeRoot) { + if (request.length === 0) { + const value = treeRoot.files.get(""); - bin = editWithAST(state.ast, bin, { - ModuleImport(path) { - if (t.isGlobalType(path.node.descr)) { - const globalType = path.node.descr; + return value ? [value, 1] : null; + } - globalType.mutability = "var"; + if ( + treeRoot.children === null && + treeRoot.folder === null && + treeRoot.wildcards === null + ) { + const value = treeRoot.files.get(request); - const init = [ - createDefaultInitForGlobal(globalType), - t.instruction("end") - ]; + return value ? [value, request.length + 1] : null; + } - newGlobals.push(t.global(globalType, init)); + let node = treeRoot; + let lastNonSlashIndex = 0; + let slashIndex = request.indexOf("/", 0); - path.remove(); + /** @type {[MappingValue, number]|null} */ + let lastFolderMatch = null; + + const applyFolderMapping = () => { + const folderMapping = node.folder; + if (folderMapping) { + if (lastFolderMatch) { + lastFolderMatch[0] = folderMapping; + lastFolderMatch[1] = -lastNonSlashIndex - 1; + } else { + lastFolderMatch = [folderMapping, -lastNonSlashIndex - 1]; } - }, + } + }; - // in order to preserve non-imported global's order we need to re-inject - // those as well - Global(path) { - const { node } = path; - const [init] = node.init; + const applyWildcardMappings = (wildcardMappings, remainingRequest) => { + if (wildcardMappings) { + for (const [key, target] of wildcardMappings) { + if (remainingRequest.startsWith(key)) { + if (!lastFolderMatch) { + lastFolderMatch = [target, lastNonSlashIndex + key.length]; + } else if (lastFolderMatch[1] < lastNonSlashIndex + key.length) { + lastFolderMatch[0] = target; + lastFolderMatch[1] = lastNonSlashIndex + key.length; + } + } + } + } + }; - if (init.id === "get_global") { - node.globalType.mutability = "var"; + while (slashIndex !== -1) { + applyFolderMapping(); - const initialGlobalIdx = init.args[0]; + const wildcardMappings = node.wildcards; - node.init = [ - createDefaultInitForGlobal(node.globalType), - t.instruction("end") - ]; + if (!wildcardMappings && node.children === null) return lastFolderMatch; - additionalInitCode.push( - /** - * get_global in global initializer only works for imported globals. - * They have the same indices as the init params, so use the - * same index. - */ - t.instruction("get_local", [initialGlobalIdx]), - t.instruction("set_global", [t.indexLiteral(newGlobals.length)]) - ); - } + const folder = request.slice(lastNonSlashIndex, slashIndex); - newGlobals.push(node); + applyWildcardMappings(wildcardMappings, folder); - path.remove(); + if (node.children === null) return lastFolderMatch; + + const newNode = node.children.get(folder); + + if (!newNode) { + return lastFolderMatch; } - }); - // Add global declaration instructions - return addWithAST(state.ast, bin, newGlobals); -}; + node = newNode; + lastNonSlashIndex = slashIndex + 1; + slashIndex = request.indexOf("/", lastNonSlashIndex); + } + + const remainingRequest = + lastNonSlashIndex > 0 ? request.slice(lastNonSlashIndex) : request; + + const value = node.files.get(remainingRequest); + + if (value) { + return [value, request.length + 1]; + } + + applyFolderMapping(); + + applyWildcardMappings(node.wildcards, remainingRequest); + + return lastFolderMatch; +} /** - * Rewrite the export names - * @param {Object} state state - * @param {Object} state.ast Module's ast - * @param {Module} state.module Module - * @param {ModuleGraph} state.moduleGraph module graph - * @param {Set} state.externalExports Module - * @param {RuntimeSpec} state.runtime runtime - * @returns {ArrayBufferTransform} transform + * @param {ConditionalMapping|DirectMapping|null} mapping mapping + * @returns {boolean} is conditional mapping */ -const rewriteExportNames = - ({ ast, moduleGraph, module, externalExports, runtime }) => - bin => { - return editWithAST(ast, bin, { - ModuleExport(path) { - const isExternal = externalExports.has(path.node.name); - if (isExternal) { - path.remove(); - return; +function isConditionalMapping(mapping) { + return ( + mapping !== null && typeof mapping === "object" && !Array.isArray(mapping) + ); +} + +/** + * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings + * @param {boolean} subpathMapping true, for subpath mappings + * @param {DirectMapping|null} mappingTarget direct export + * @param {Set} conditionNames condition names + * @param {(d: string, f: boolean) => void} assert asserting direct value + * @returns {string[]} mapping result + */ +function directMapping( + remainingRequest, + subpathMapping, + mappingTarget, + conditionNames, + assert +) { + if (mappingTarget === null) return []; + + if (typeof mappingTarget === "string") { + return [ + targetMapping(remainingRequest, subpathMapping, mappingTarget, assert) + ]; + } + + const targets = []; + + for (const exp of mappingTarget) { + if (typeof exp === "string") { + targets.push( + targetMapping(remainingRequest, subpathMapping, exp, assert) + ); + continue; + } + + const mapping = conditionalMapping(exp, conditionNames); + if (!mapping) continue; + const innerExports = directMapping( + remainingRequest, + subpathMapping, + mapping, + conditionNames, + assert + ); + for (const innerExport of innerExports) { + targets.push(innerExport); + } + } + + return targets; +} + +/** + * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings + * @param {boolean} subpathMapping true, for subpath mappings + * @param {string} mappingTarget direct export + * @param {(d: string, f: boolean) => void} assert asserting direct value + * @returns {string} mapping result + */ +function targetMapping( + remainingRequest, + subpathMapping, + mappingTarget, + assert +) { + if (remainingRequest === undefined) { + assert(mappingTarget, false); + return mappingTarget; + } + if (subpathMapping) { + assert(mappingTarget, true); + return mappingTarget + remainingRequest; + } + assert(mappingTarget, false); + return mappingTarget.replace(/\*/g, remainingRequest.replace(/\$/g, "$$")); +} + +/** + * @param {ConditionalMapping} conditionalMapping_ conditional mapping + * @param {Set} conditionNames condition names + * @returns {DirectMapping|null} direct mapping if found + */ +function conditionalMapping(conditionalMapping_, conditionNames) { + /** @type {[ConditionalMapping, string[], number][]} */ + let lookup = [[conditionalMapping_, Object.keys(conditionalMapping_), 0]]; + + loop: while (lookup.length > 0) { + const [mapping, conditions, j] = lookup[lookup.length - 1]; + const last = conditions.length - 1; + + for (let i = j; i < conditions.length; i++) { + const condition = conditions[i]; + + // assert default. Could be last only + if (i !== last) { + if (condition === "default") { + throw new Error("Default condition should be last one"); } - const usedName = moduleGraph - .getExportsInfo(module) - .getUsedName(path.node.name, runtime); - if (!usedName) { - path.remove(); - return; + } else if (condition === "default") { + const innerMapping = mapping[condition]; + // is nested + if (isConditionalMapping(innerMapping)) { + const conditionalMapping = /** @type {ConditionalMapping} */ (innerMapping); + lookup[lookup.length - 1][2] = i + 1; + lookup.push([conditionalMapping, Object.keys(conditionalMapping), 0]); + continue loop; } - path.node.name = usedName; + + return /** @type {DirectMapping} */ (innerMapping); } - }); + + if (conditionNames.has(condition)) { + const innerMapping = mapping[condition]; + // is nested + if (isConditionalMapping(innerMapping)) { + const conditionalMapping = /** @type {ConditionalMapping} */ (innerMapping); + lookup[lookup.length - 1][2] = i + 1; + lookup.push([conditionalMapping, Object.keys(conditionalMapping), 0]); + continue loop; + } + + return /** @type {DirectMapping} */ (innerMapping); + } + } + + lookup.pop(); + } + + return null; +} + +/** + * Internal helper to create path tree node + * to ensure that each node gets the same hidden class + * @returns {PathTreeNode} node + */ +function createNode() { + return { + children: null, + folder: null, + wildcards: null, + files: new Map() }; +} /** - * Mangle import names and modules - * @param {Object} state state - * @param {Object} state.ast Module's ast - * @param {Map} state.usedDependencyMap mappings to mangle names - * @returns {ArrayBufferTransform} transform + * Internal helper for building path tree + * @param {PathTreeNode} root root + * @param {string} path path + * @param {MappingValue} target target */ -const rewriteImports = - ({ ast, usedDependencyMap }) => - bin => { - return editWithAST(ast, bin, { - ModuleImport(path) { - const result = usedDependencyMap.get( - path.node.module + ":" + path.node.name - ); +function walkPath(root, path, target) { + if (path.length === 0) { + root.folder = target; + return; + } - if (result !== undefined) { - path.node.module = result.module; - path.node.name = result.name; - } + let node = root; + // Typical path tree can looks like + // root + // - files: ["a.js", "b.js"] + // - children: + // node1: + // - files: ["a.js", "b.js"] + let lastNonSlashIndex = 0; + let slashIndex = path.indexOf("/", 0); + + while (slashIndex !== -1) { + const folder = path.slice(lastNonSlashIndex, slashIndex); + let newNode; + + if (node.children === null) { + newNode = createNode(); + node.children = new Map(); + node.children.set(folder, newNode); + } else { + newNode = node.children.get(folder); + + if (!newNode) { + newNode = createNode(); + node.children.set(folder, newNode); } - }); - }; + } + + node = newNode; + lastNonSlashIndex = slashIndex + 1; + slashIndex = path.indexOf("/", lastNonSlashIndex); + } + + if (lastNonSlashIndex >= path.length) { + node.folder = target; + } else { + const file = lastNonSlashIndex > 0 ? path.slice(lastNonSlashIndex) : path; + if (file.endsWith("*")) { + if (node.wildcards === null) node.wildcards = new Map(); + node.wildcards.set(file.slice(0, -1), target); + } else { + node.files.set(file, target); + } + } +} /** - * Add an init function. - * - * The init function fills the globals given input arguments. - * - * @param {Object} state transformation state - * @param {Object} state.ast Module's ast - * @param {t.Identifier} state.initFuncId identifier of the init function - * @param {t.Index} state.startAtFuncOffset index of the start function - * @param {t.ModuleImport[]} state.importedGlobals list of imported globals - * @param {t.Instruction[]} state.additionalInitCode list of addition instructions for the init function - * @param {t.Index} state.nextFuncIndex index of the next function - * @param {t.Index} state.nextTypeIndex index of the next type - * @returns {ArrayBufferTransform} transform + * @param {ExportsField} field exports field + * @returns {PathTreeNode} tree root */ -const addInitFunction = - ({ - ast, - initFuncId, - startAtFuncOffset, - importedGlobals, - additionalInitCode, - nextFuncIndex, - nextTypeIndex - }) => - bin => { - const funcParams = importedGlobals.map(importedGlobal => { - // used for debugging - const id = t.identifier( - `${importedGlobal.module}.${importedGlobal.name}` - ); +function buildExportsFieldPathTree(field) { + const root = createNode(); - return t.funcParam(importedGlobal.descr.valtype, id); - }); + // handle syntax sugar, if exports field is direct mapping for "." + if (typeof field === "string") { + root.files.set("", field); - const funcBody = []; - importedGlobals.forEach((importedGlobal, index) => { - const args = [t.indexLiteral(index)]; - const body = [ - t.instruction("get_local", args), - t.instruction("set_global", args) - ]; + return root; + } else if (Array.isArray(field)) { + root.files.set("", field.slice()); + + return root; + } + + const keys = Object.keys(field); + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + + if (key.charCodeAt(0) !== dotCode) { + // handle syntax sugar, if exports field is conditional mapping for "." + if (i === 0) { + while (i < keys.length) { + const charCode = keys[i].charCodeAt(0); + if (charCode === dotCode || charCode === slashCode) { + throw new Error( + `Exports field key should be relative path and start with "." (key: ${JSON.stringify( + key + )})` + ); + } + i++; + } - funcBody.push(...body); - }); + root.files.set("", field); + return root; + } - if (typeof startAtFuncOffset === "number") { - funcBody.push( - t.callInstruction(t.numberLiteralFromRaw(startAtFuncOffset)) + throw new Error( + `Exports field key should be relative path and start with "." (key: ${JSON.stringify( + key + )})` ); } - for (const instr of additionalInitCode) { - funcBody.push(instr); + if (key.length === 1) { + root.files.set("", field[key]); + continue; } - funcBody.push(t.instruction("end")); - - const funcResults = []; - - // Code section - const funcSignature = t.signature(funcParams, funcResults); - const func = t.func(initFuncId, funcSignature, funcBody); - - // Type section - const functype = t.typeInstruction(undefined, funcSignature); - - // Func section - const funcindex = t.indexInFuncSection(nextTypeIndex); + if (key.charCodeAt(1) !== slashCode) { + throw new Error( + `Exports field key should be relative path and start with "./" (key: ${JSON.stringify( + key + )})` + ); + } - // Export section - const moduleExport = t.moduleExport( - initFuncId.value, - t.moduleExportDescr("Func", nextFuncIndex) - ); + walkPath(root, key.slice(2), field[key]); + } - return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]); - }; + return root; +} /** - * Extract mangle mappings from module - * @param {ModuleGraph} moduleGraph module graph - * @param {Module} module current module - * @param {boolean} mangle mangle imports - * @returns {Map} mappings to mangled names + * @param {ImportsField} field imports field + * @returns {PathTreeNode} root */ -const getUsedDependencyMap = (moduleGraph, module, mangle) => { - /** @type {Map} */ - const map = new Map(); - for (const usedDep of WebAssemblyUtils.getUsedDependencies( - moduleGraph, - module, - mangle - )) { - const dep = usedDep.dependency; - const request = dep.request; - const exportName = dep.name; - map.set(request + ":" + exportName, usedDep); - } - return map; -}; - -const TYPES = new Set(["webassembly"]); +function buildImportsFieldPathTree(field) { + const root = createNode(); -class WebAssemblyGenerator extends Generator { - constructor(options) { - super(); - this.options = options; - } + const keys = Object.keys(field); - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; - } + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; - /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module - */ - getSize(module, type) { - const originalSource = module.originalSource(); - if (!originalSource) { - return 0; + if (key.charCodeAt(0) !== hashCode) { + throw new Error( + `Imports field key should start with "#" (key: ${JSON.stringify(key)})` + ); } - return originalSource.size(); - } - - /** - * @param {NormalModule} module module for which the code should be generated - * @param {GenerateContext} generateContext context for generate - * @returns {Source} generated code - */ - generate(module, { moduleGraph, runtime }) { - const bin = module.originalSource().source(); - const initFuncId = t.identifier(""); + if (key.length === 1) { + throw new Error( + `Imports field key should have at least 2 characters (key: ${JSON.stringify( + key + )})` + ); + } - // parse it - const ast = decode(bin, { - ignoreDataSection: true, - ignoreCodeSection: true, - ignoreCustomNameSection: true - }); + if (key.charCodeAt(1) === slashCode) { + throw new Error( + `Imports field key should not start with "#/" (key: ${JSON.stringify( + key + )})` + ); + } - const moduleContext = moduleContextFromModuleAST(ast.body[0]); + walkPath(root, key.slice(1), field[key]); + } - const importedGlobals = getImportedGlobals(ast); - const countImportedFunc = getCountImportedFunc(ast); - const startAtFuncOffset = moduleContext.getStart(); - const nextFuncIndex = getNextFuncIndex(ast, countImportedFunc); - const nextTypeIndex = getNextTypeIndex(ast); + return root; +} - const usedDependencyMap = getUsedDependencyMap( - moduleGraph, - module, - this.options.mangleImports - ); - const externalExports = new Set( - module.dependencies - .filter(d => d instanceof WebAssemblyExportImportedDependency) - .map(d => { - const wasmDep = /** @type {WebAssemblyExportImportedDependency} */ ( - d - ); - return wasmDep.exportName; - }) - ); - /** @type {t.Instruction[]} */ - const additionalInitCode = []; +/***/ }), - const transform = compose( - rewriteExportNames({ - ast, - moduleGraph, - module, - externalExports, - runtime - }), +/***/ 71053: +/***/ (function(module) { - removeStartFunc({ ast }), +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ - rewriteImportedGlobals({ ast, additionalInitCode }), - rewriteImports({ - ast, - usedDependencyMap - }), - addInitFunction({ - ast, - initFuncId, - importedGlobals, - additionalInitCode, - startAtFuncOffset, - nextFuncIndex, - nextTypeIndex - }) - ); +const PATH_QUERY_FRAGMENT_REGEXP = /^(#?(?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; - const newBin = transform(bin); +/** + * @param {string} identifier identifier + * @returns {[string, string, string]|null} parsed identifier + */ +function parseIdentifier(identifier) { + const match = PATH_QUERY_FRAGMENT_REGEXP.exec(identifier); - const newBuf = Buffer.from(newBin); + if (!match) return null; - return new RawSource(newBuf); - } + return [ + match[1].replace(/\0(.)/g, "$1"), + match[2] ? match[2].replace(/\0(.)/g, "$1") : "", + match[3] || "" + ]; } -module.exports = WebAssemblyGenerator; +module.exports.parseIdentifier = parseIdentifier; /***/ }), -/***/ 47342: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 67079: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -const WebpackError = __webpack_require__(53799); +const path = __webpack_require__(71017); -/** @typedef {import("../ChunkGraph")} ChunkGraph */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ -/** @typedef {import("../RequestShortener")} RequestShortener */ +const CHAR_HASH = "#".charCodeAt(0); +const CHAR_SLASH = "/".charCodeAt(0); +const CHAR_BACKSLASH = "\\".charCodeAt(0); +const CHAR_A = "A".charCodeAt(0); +const CHAR_Z = "Z".charCodeAt(0); +const CHAR_LOWER_A = "a".charCodeAt(0); +const CHAR_LOWER_Z = "z".charCodeAt(0); +const CHAR_DOT = ".".charCodeAt(0); +const CHAR_COLON = ":".charCodeAt(0); + +const posixNormalize = path.posix.normalize; +const winNormalize = path.win32.normalize; /** - * @param {Module} module module to get chains from - * @param {ModuleGraph} moduleGraph the module graph - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {RequestShortener} requestShortener to make readable identifiers - * @returns {string[]} all chains to the module + * @enum {number} */ -const getInitialModuleChains = ( - module, - moduleGraph, - chunkGraph, - requestShortener -) => { - const queue = [ - { head: module, message: module.readableIdentifier(requestShortener) } - ]; - /** @type {Set} */ - const results = new Set(); - /** @type {Set} */ - const incompleteResults = new Set(); - /** @type {Set} */ - const visitedModules = new Set(); +const PathType = Object.freeze({ + Empty: 0, + Normal: 1, + Relative: 2, + AbsoluteWin: 3, + AbsolutePosix: 4, + Internal: 5 +}); +exports.PathType = PathType; - for (const chain of queue) { - const { head, message } = chain; - let final = true; - /** @type {Set} */ - const alreadyReferencedModules = new Set(); - for (const connection of moduleGraph.getIncomingConnections(head)) { - const newHead = connection.originModule; - if (newHead) { - if (!chunkGraph.getModuleChunks(newHead).some(c => c.canBeInitial())) - continue; - final = false; - if (alreadyReferencedModules.has(newHead)) continue; - alreadyReferencedModules.add(newHead); - const moduleName = newHead.readableIdentifier(requestShortener); - const detail = connection.explanation - ? ` (${connection.explanation})` - : ""; - const newMessage = `${moduleName}${detail} --> ${message}`; - if (visitedModules.has(newHead)) { - incompleteResults.add(`... --> ${newMessage}`); - continue; +/** + * @param {string} p a path + * @returns {PathType} type of path + */ +const getType = p => { + switch (p.length) { + case 0: + return PathType.Empty; + case 1: { + const c0 = p.charCodeAt(0); + switch (c0) { + case CHAR_DOT: + return PathType.Relative; + case CHAR_SLASH: + return PathType.AbsolutePosix; + case CHAR_HASH: + return PathType.Internal; + } + return PathType.Normal; + } + case 2: { + const c0 = p.charCodeAt(0); + switch (c0) { + case CHAR_DOT: { + const c1 = p.charCodeAt(1); + switch (c1) { + case CHAR_DOT: + case CHAR_SLASH: + return PathType.Relative; + } + return PathType.Normal; + } + case CHAR_SLASH: + return PathType.AbsolutePosix; + case CHAR_HASH: + return PathType.Internal; + } + const c1 = p.charCodeAt(1); + if (c1 === CHAR_COLON) { + if ( + (c0 >= CHAR_A && c0 <= CHAR_Z) || + (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z) + ) { + return PathType.AbsoluteWin; } - visitedModules.add(newHead); - queue.push({ - head: newHead, - message: newMessage - }); - } else { - final = false; - const newMessage = connection.explanation - ? `(${connection.explanation}) --> ${message}` - : message; - results.add(newMessage); } + return PathType.Normal; } - if (final) { - results.add(message); + } + const c0 = p.charCodeAt(0); + switch (c0) { + case CHAR_DOT: { + const c1 = p.charCodeAt(1); + switch (c1) { + case CHAR_SLASH: + return PathType.Relative; + case CHAR_DOT: { + const c2 = p.charCodeAt(2); + if (c2 === CHAR_SLASH) return PathType.Relative; + return PathType.Normal; + } + } + return PathType.Normal; } + case CHAR_SLASH: + return PathType.AbsolutePosix; + case CHAR_HASH: + return PathType.Internal; } - for (const result of incompleteResults) { - results.add(result); + const c1 = p.charCodeAt(1); + if (c1 === CHAR_COLON) { + const c2 = p.charCodeAt(2); + if ( + (c2 === CHAR_BACKSLASH || c2 === CHAR_SLASH) && + ((c0 >= CHAR_A && c0 <= CHAR_Z) || + (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z)) + ) { + return PathType.AbsoluteWin; + } } - return Array.from(results); + return PathType.Normal; }; +exports.getType = getType; -module.exports = class WebAssemblyInInitialChunkError extends WebpackError { - /** - * @param {Module} module WASM module - * @param {ModuleGraph} moduleGraph the module graph - * @param {ChunkGraph} chunkGraph the chunk graph - * @param {RequestShortener} requestShortener request shortener - */ - constructor(module, moduleGraph, chunkGraph, requestShortener) { - const moduleChains = getInitialModuleChains( - module, - moduleGraph, - chunkGraph, - requestShortener - ); - const message = `WebAssembly module is included in initial chunk. -This is not allowed, because WebAssembly download and compilation must happen asynchronous. -Add an async split point (i. e. import()) somewhere between your entrypoint and the WebAssembly module: -${moduleChains.map(s => `* ${s}`).join("\n")}`; +/** + * @param {string} p a path + * @returns {string} the normalized path + */ +const normalize = p => { + switch (getType(p)) { + case PathType.Empty: + return p; + case PathType.AbsoluteWin: + return winNormalize(p); + case PathType.Relative: { + const r = posixNormalize(p); + return getType(r) === PathType.Relative ? r : `./${r}`; + } + } + return posixNormalize(p); +}; +exports.normalize = normalize; - super(message); - this.name = "WebAssemblyInInitialChunkError"; - this.hideStack = true; - this.module = module; +/** + * @param {string} rootPath the root path + * @param {string | undefined} request the request path + * @returns {string} the joined path + */ +const join = (rootPath, request) => { + if (!request) return normalize(rootPath); + const requestType = getType(request); + switch (requestType) { + case PathType.AbsolutePosix: + return posixNormalize(request); + case PathType.AbsoluteWin: + return winNormalize(request); + } + switch (getType(rootPath)) { + case PathType.Normal: + case PathType.Relative: + case PathType.AbsolutePosix: + return posixNormalize(`${rootPath}/${request}`); + case PathType.AbsoluteWin: + return winNormalize(`${rootPath}\\${request}`); + } + switch (requestType) { + case PathType.Empty: + return rootPath; + case PathType.Relative: { + const r = posixNormalize(rootPath); + return getType(r) === PathType.Relative ? r : `./${r}`; + } + } + return posixNormalize(rootPath); +}; +exports.join = join; + +const joinCache = new Map(); + +/** + * @param {string} rootPath the root path + * @param {string | undefined} request the request path + * @returns {string} the joined path + */ +const cachedJoin = (rootPath, request) => { + let cacheEntry; + let cache = joinCache.get(rootPath); + if (cache === undefined) { + joinCache.set(rootPath, (cache = new Map())); + } else { + cacheEntry = cache.get(request); + if (cacheEntry !== undefined) return cacheEntry; + } + cacheEntry = join(rootPath, request); + cache.set(request, cacheEntry); + return cacheEntry; +}; +exports.cachedJoin = cachedJoin; + +const checkExportsFieldTarget = relativePath => { + let lastNonSlashIndex = 2; + let slashIndex = relativePath.indexOf("/", 2); + let cd = 0; + + while (slashIndex !== -1) { + const folder = relativePath.slice(lastNonSlashIndex, slashIndex); + + switch (folder) { + case "..": { + cd--; + if (cd < 0) + return new Error( + `Trying to access out of package scope. Requesting ${relativePath}` + ); + break; + } + default: + cd++; + break; + } + + lastNonSlashIndex = slashIndex + 1; + slashIndex = relativePath.indexOf("/", lastNonSlashIndex); } }; +exports.checkExportsFieldTarget = checkExportsFieldTarget; /***/ }), -/***/ 46545: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 39102: +/***/ (function(module) { "use strict"; + + +class LoadingLoaderError extends Error { + constructor(message) { + super(message); + this.name = "LoaderRunnerError"; + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = LoadingLoaderError; + + +/***/ }), + +/***/ 8255: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ +var fs = __webpack_require__(57147); +var readFile = fs.readFile.bind(fs); +var loadLoader = __webpack_require__(44690); +function utf8BufferToString(buf) { + var str = buf.toString("utf-8"); + if(str.charCodeAt(0) === 0xFEFF) { + return str.substr(1); + } else { + return str; + } +} +const PATH_QUERY_FRAGMENT_REGEXP = /^((?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; -const { RawSource } = __webpack_require__(51255); -const { UsageState } = __webpack_require__(63686); -const Generator = __webpack_require__(93401); -const InitFragment = __webpack_require__(55870); -const RuntimeGlobals = __webpack_require__(16475); -const Template = __webpack_require__(39722); -const ModuleDependency = __webpack_require__(80321); -const WebAssemblyExportImportedDependency = __webpack_require__(52204); -const WebAssemblyImportDependency = __webpack_require__(5239); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../DependencyTemplates")} DependencyTemplates */ -/** @typedef {import("../Generator").GenerateContext} GenerateContext */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** + * @param {string} str the path with query and fragment + * @returns {{ path: string, query: string, fragment: string }} parsed parts + */ +function parsePathQueryFragment(str) { + var match = PATH_QUERY_FRAGMENT_REGEXP.exec(str); + return { + path: match[1].replace(/\0(.)/g, "$1"), + query: match[2] ? match[2].replace(/\0(.)/g, "$1") : "", + fragment: match[3] || "" + }; +} -const TYPES = new Set(["webassembly"]); +function dirname(path) { + if(path === "/") return "/"; + var i = path.lastIndexOf("/"); + var j = path.lastIndexOf("\\"); + var i2 = path.indexOf("/"); + var j2 = path.indexOf("\\"); + var idx = i > j ? i : j; + var idx2 = i > j ? i2 : j2; + if(idx < 0) return path; + if(idx === idx2) return path.substr(0, idx + 1); + return path.substr(0, idx); +} -class WebAssemblyJavascriptGenerator extends Generator { - /** - * @param {NormalModule} module fresh module - * @returns {Set} available types (do not mutate) - */ - getTypes(module) { - return TYPES; +function createLoaderObject(loader) { + var obj = { + path: null, + query: null, + fragment: null, + options: null, + ident: null, + normal: null, + pitch: null, + raw: null, + data: null, + pitchExecuted: false, + normalExecuted: false + }; + Object.defineProperty(obj, "request", { + enumerable: true, + get: function() { + return obj.path.replace(/#/g, "\0#") + obj.query.replace(/#/g, "\0#") + obj.fragment; + }, + set: function(value) { + if(typeof value === "string") { + var splittedRequest = parsePathQueryFragment(value); + obj.path = splittedRequest.path; + obj.query = splittedRequest.query; + obj.fragment = splittedRequest.fragment; + obj.options = undefined; + obj.ident = undefined; + } else { + if(!value.loader) + throw new Error("request should be a string or object with loader and options (" + JSON.stringify(value) + ")"); + obj.path = value.loader; + obj.fragment = value.fragment || ""; + obj.type = value.type; + obj.options = value.options; + obj.ident = value.ident; + if(obj.options === null) + obj.query = ""; + else if(obj.options === undefined) + obj.query = ""; + else if(typeof obj.options === "string") + obj.query = "?" + obj.options; + else if(obj.ident) + obj.query = "??" + obj.ident; + else if(typeof obj.options === "object" && obj.options.ident) + obj.query = "??" + obj.options.ident; + else + obj.query = "?" + JSON.stringify(obj.options); + } + } + }); + obj.request = loader; + if(Object.preventExtensions) { + Object.preventExtensions(obj); } + return obj; +} - /** - * @param {NormalModule} module the module - * @param {string=} type source type - * @returns {number} estimate size of the module - */ - getSize(module, type) { - return 95 + module.dependencies.length * 5; +function runSyncOrAsync(fn, context, args, callback) { + var isSync = true; + var isDone = false; + var isError = false; // internal error + var reportedError = false; + context.async = function async() { + if(isDone) { + if(reportedError) return; // ignore + throw new Error("async(): The callback was already called."); + } + isSync = false; + return innerCallback; + }; + var innerCallback = context.callback = function() { + if(isDone) { + if(reportedError) return; // ignore + throw new Error("callback(): The callback was already called."); + } + isDone = true; + isSync = false; + try { + callback.apply(null, arguments); + } catch(e) { + isError = true; + throw e; + } + }; + try { + var result = (function LOADER_EXECUTION() { + return fn.apply(context, args); + }()); + if(isSync) { + isDone = true; + if(result === undefined) + return callback(); + if(result && typeof result === "object" && typeof result.then === "function") { + return result.then(function(r) { + callback(null, r); + }, callback); + } + return callback(null, result); + } + } catch(e) { + if(isError) throw e; + if(isDone) { + // loader is already "done", so we cannot use the callback function + // for better debugging we print the error on the console + if(typeof e === "object" && e.stack) console.error(e.stack); + else console.error(e); + return; + } + isDone = true; + reportedError = true; + callback(e); } - /** - * @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 { - runtimeTemplate, - moduleGraph, - chunkGraph, - runtimeRequirements, - runtime - } = generateContext; - /** @type {InitFragment[]} */ - const initFragments = []; +} - const exportsInfo = moduleGraph.getExportsInfo(module); +function convertArgs(args, raw) { + if(!raw && Buffer.isBuffer(args[0])) + args[0] = utf8BufferToString(args[0]); + else if(raw && typeof args[0] === "string") + args[0] = Buffer.from(args[0], "utf-8"); +} - let needExportsCopy = false; - const importedModules = new Map(); - const initParams = []; - let index = 0; - for (const dep of module.dependencies) { - const moduleDep = - dep && dep instanceof ModuleDependency ? dep : undefined; - if (moduleGraph.getModule(dep)) { - let importData = importedModules.get(moduleGraph.getModule(dep)); - if (importData === undefined) { - importedModules.set( - moduleGraph.getModule(dep), - (importData = { - importVar: `m${index}`, - index, - request: (moduleDep && moduleDep.userRequest) || undefined, - names: new Set(), - reexports: [] - }) - ); - index++; - } - if (dep instanceof WebAssemblyImportDependency) { - importData.names.add(dep.name); - if (dep.description.type === "GlobalType") { - const exportName = dep.name; - const importedModule = moduleGraph.getModule(dep); +function iteratePitchingLoaders(options, loaderContext, callback) { + // abort after last loader + if(loaderContext.loaderIndex >= loaderContext.loaders.length) + return processResource(options, loaderContext, callback); - if (importedModule) { - const usedName = moduleGraph - .getExportsInfo(importedModule) - .getUsedName(exportName, runtime); - if (usedName) { - initParams.push( - runtimeTemplate.exportFromImport({ - moduleGraph, - module: importedModule, - request: dep.request, - importVar: importData.importVar, - originModule: module, - exportName: dep.name, - asiSafe: true, - isCall: false, - callContext: null, - defaultInterop: true, - initFragments, - runtime, - runtimeRequirements - }) - ); - } - } - } - } - if (dep instanceof WebAssemblyExportImportedDependency) { - importData.names.add(dep.name); - const usedName = moduleGraph - .getExportsInfo(module) - .getUsedName(dep.exportName, runtime); - if (usedName) { - runtimeRequirements.add(RuntimeGlobals.exports); - const exportProp = `${module.exportsArgument}[${JSON.stringify( - usedName - )}]`; - const defineStatement = Template.asString([ - `${exportProp} = ${runtimeTemplate.exportFromImport({ - moduleGraph, - module: moduleGraph.getModule(dep), - request: dep.request, - importVar: importData.importVar, - originModule: module, - exportName: dep.name, - asiSafe: true, - isCall: false, - callContext: null, - defaultInterop: true, - initFragments, - runtime, - runtimeRequirements - })};`, - `if(WebAssembly.Global) ${exportProp} = ` + - `new WebAssembly.Global({ value: ${JSON.stringify( - dep.valueType - )} }, ${exportProp});` - ]); - importData.reexports.push(defineStatement); - needExportsCopy = true; - } - } - } + var currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex]; + + // iterate + if(currentLoaderObject.pitchExecuted) { + loaderContext.loaderIndex++; + return iteratePitchingLoaders(options, loaderContext, callback); + } + + // load loader module + loadLoader(currentLoaderObject, function(err) { + if(err) { + loaderContext.cacheable(false); + return callback(err); } - const importsCode = Template.asString( - Array.from( - importedModules, - ([module, { importVar, request, reexports }]) => { - const importStatement = runtimeTemplate.importStatement({ - module, - chunkGraph, - request, - importVar, - originModule: module, - runtimeRequirements - }); - return importStatement[0] + importStatement[1] + reexports.join("\n"); + var fn = currentLoaderObject.pitch; + currentLoaderObject.pitchExecuted = true; + if(!fn) return iteratePitchingLoaders(options, loaderContext, callback); + + runSyncOrAsync( + fn, + loaderContext, [loaderContext.remainingRequest, loaderContext.previousRequest, currentLoaderObject.data = {}], + function(err) { + if(err) return callback(err); + var args = Array.prototype.slice.call(arguments, 1); + // Determine whether to continue the pitching process based on + // argument values (as opposed to argument presence) in order + // to support synchronous and asynchronous usages. + var hasArg = args.some(function(value) { + return value !== undefined; + }); + if(hasArg) { + loaderContext.loaderIndex--; + iterateNormalLoaders(options, loaderContext, args, callback); + } else { + iteratePitchingLoaders(options, loaderContext, callback); } - ) + } ); + }); +} - const copyAllExports = - exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused && - !needExportsCopy; +function processResource(options, loaderContext, callback) { + // set loader index to last loader + loaderContext.loaderIndex = loaderContext.loaders.length - 1; - // need these globals - runtimeRequirements.add(RuntimeGlobals.module); - runtimeRequirements.add(RuntimeGlobals.moduleId); - runtimeRequirements.add(RuntimeGlobals.wasmInstances); - if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) { - runtimeRequirements.add(RuntimeGlobals.makeNamespaceObject); - runtimeRequirements.add(RuntimeGlobals.exports); + var resourcePath = loaderContext.resourcePath; + if(resourcePath) { + options.processResource(loaderContext, resourcePath, function(err, buffer) { + if(err) return callback(err); + options.resourceBuffer = buffer; + iterateNormalLoaders(options, loaderContext, [buffer], callback); + }); + } else { + iterateNormalLoaders(options, loaderContext, [null], callback); + } +} + +function iterateNormalLoaders(options, loaderContext, args, callback) { + if(loaderContext.loaderIndex < 0) + return callback(null, args); + + var currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex]; + + // iterate + if(currentLoaderObject.normalExecuted) { + loaderContext.loaderIndex--; + return iterateNormalLoaders(options, loaderContext, args, callback); + } + + var fn = currentLoaderObject.normal; + currentLoaderObject.normalExecuted = true; + if(!fn) { + return iterateNormalLoaders(options, loaderContext, args, callback); + } + + convertArgs(args, currentLoaderObject.raw); + + runSyncOrAsync(fn, loaderContext, args, function(err) { + if(err) return callback(err); + + var args = Array.prototype.slice.call(arguments, 1); + iterateNormalLoaders(options, loaderContext, args, callback); + }); +} + +exports.getContext = function getContext(resource) { + var path = parsePathQueryFragment(resource).path; + return dirname(path); +}; + +exports.runLoaders = function runLoaders(options, callback) { + // read options + var resource = options.resource || ""; + var loaders = options.loaders || []; + var loaderContext = options.context || {}; + var processResource = options.processResource || ((readResource, context, resource, callback) => { + context.addDependency(resource); + readResource(resource, callback); + }).bind(null, options.readResource || readFile); + + // + var splittedResource = resource && parsePathQueryFragment(resource); + var resourcePath = splittedResource ? splittedResource.path : undefined; + var resourceQuery = splittedResource ? splittedResource.query : undefined; + var resourceFragment = splittedResource ? splittedResource.fragment : undefined; + var contextDirectory = resourcePath ? dirname(resourcePath) : null; + + // execution state + var requestCacheable = true; + var fileDependencies = []; + var contextDependencies = []; + var missingDependencies = []; + + // prepare loader objects + loaders = loaders.map(createLoaderObject); + + loaderContext.context = contextDirectory; + loaderContext.loaderIndex = 0; + loaderContext.loaders = loaders; + loaderContext.resourcePath = resourcePath; + loaderContext.resourceQuery = resourceQuery; + loaderContext.resourceFragment = resourceFragment; + loaderContext.async = null; + loaderContext.callback = null; + loaderContext.cacheable = function cacheable(flag) { + if(flag === false) { + requestCacheable = false; + } + }; + loaderContext.dependency = loaderContext.addDependency = function addDependency(file) { + fileDependencies.push(file); + }; + loaderContext.addContextDependency = function addContextDependency(context) { + contextDependencies.push(context); + }; + loaderContext.addMissingDependency = function addMissingDependency(context) { + missingDependencies.push(context); + }; + loaderContext.getDependencies = function getDependencies() { + return fileDependencies.slice(); + }; + loaderContext.getContextDependencies = function getContextDependencies() { + return contextDependencies.slice(); + }; + loaderContext.getMissingDependencies = function getMissingDependencies() { + return missingDependencies.slice(); + }; + loaderContext.clearDependencies = function clearDependencies() { + fileDependencies.length = 0; + contextDependencies.length = 0; + missingDependencies.length = 0; + requestCacheable = true; + }; + Object.defineProperty(loaderContext, "resource", { + enumerable: true, + get: function() { + if(loaderContext.resourcePath === undefined) + return undefined; + return loaderContext.resourcePath.replace(/#/g, "\0#") + loaderContext.resourceQuery.replace(/#/g, "\0#") + loaderContext.resourceFragment; + }, + set: function(value) { + var splittedResource = value && parsePathQueryFragment(value); + loaderContext.resourcePath = splittedResource ? splittedResource.path : undefined; + loaderContext.resourceQuery = splittedResource ? splittedResource.query : undefined; + loaderContext.resourceFragment = splittedResource ? splittedResource.fragment : undefined; + } + }); + Object.defineProperty(loaderContext, "request", { + enumerable: true, + get: function() { + return loaderContext.loaders.map(function(o) { + return o.request; + }).concat(loaderContext.resource || "").join("!"); + } + }); + Object.defineProperty(loaderContext, "remainingRequest", { + enumerable: true, + get: function() { + if(loaderContext.loaderIndex >= loaderContext.loaders.length - 1 && !loaderContext.resource) + return ""; + return loaderContext.loaders.slice(loaderContext.loaderIndex + 1).map(function(o) { + return o.request; + }).concat(loaderContext.resource || "").join("!"); + } + }); + Object.defineProperty(loaderContext, "currentRequest", { + enumerable: true, + get: function() { + return loaderContext.loaders.slice(loaderContext.loaderIndex).map(function(o) { + return o.request; + }).concat(loaderContext.resource || "").join("!"); } - if (!copyAllExports) { - runtimeRequirements.add(RuntimeGlobals.exports); + }); + Object.defineProperty(loaderContext, "previousRequest", { + enumerable: true, + get: function() { + return loaderContext.loaders.slice(0, loaderContext.loaderIndex).map(function(o) { + return o.request; + }).join("!"); } + }); + Object.defineProperty(loaderContext, "query", { + enumerable: true, + get: function() { + var entry = loaderContext.loaders[loaderContext.loaderIndex]; + return entry.options && typeof entry.options === "object" ? entry.options : entry.query; + } + }); + Object.defineProperty(loaderContext, "data", { + enumerable: true, + get: function() { + return loaderContext.loaders[loaderContext.loaderIndex].data; + } + }); - // create source - const source = new RawSource( - [ - '"use strict";', - "// Instantiate WebAssembly module", - `var wasmExports = ${RuntimeGlobals.wasmInstances}[${module.moduleArgument}.id];`, - - exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused - ? `${RuntimeGlobals.makeNamespaceObject}(${module.exportsArgument});` - : "", - - // this must be before import for circular dependencies - "// export exports from WebAssembly module", - copyAllExports - ? `${module.moduleArgument}.exports = wasmExports;` - : "for(var name in wasmExports) " + - `if(name) ` + - `${module.exportsArgument}[name] = wasmExports[name];`, - "// exec imports from WebAssembly module (for esm order)", - importsCode, - "", - "// exec wasm module", - `wasmExports[""](${initParams.join(", ")})` - ].join("\n") - ); - return InitFragment.addToSource(source, initFragments, generateContext); + // finish loader context + if(Object.preventExtensions) { + Object.preventExtensions(loaderContext); } -} -module.exports = WebAssemblyJavascriptGenerator; + var processOptions = { + resourceBuffer: null, + processResource: processResource + }; + iteratePitchingLoaders(processOptions, loaderContext, function(err, result) { + if(err) { + return callback(err, { + cacheable: requestCacheable, + fileDependencies: fileDependencies, + contextDependencies: contextDependencies, + missingDependencies: missingDependencies + }); + } + callback(null, { + result: result, + resourceBuffer: processOptions.resourceBuffer, + cacheable: requestCacheable, + fileDependencies: fileDependencies, + contextDependencies: contextDependencies, + missingDependencies: missingDependencies + }); + }); +}; /***/ }), -/***/ 53639: +/***/ 44690: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +var LoaderLoadingError = __webpack_require__(39102); +var url; +module.exports = function loadLoader(loader, callback) { + if(loader.type === "module") { + try { + if(url === undefined) url = __webpack_require__(57310); + var loaderUrl = url.pathToFileURL(loader.path); + var modulePromise = eval("import(" + JSON.stringify(loaderUrl.toString()) + ")"); + modulePromise.then(function(module) { + handleResult(loader, module, callback); + }, callback); + return; + } catch(e) { + callback(e); + } + } else { + try { + var module = require(loader.path); + } catch(e) { + // it is possible for node to choke on a require if the FD descriptor + // limit has been reached. give it a chance to recover. + if(e instanceof Error && e.code === "EMFILE") { + var retry = loadLoader.bind(null, loader, callback); + if(typeof setImmediate === "function") { + // node >= 0.9.0 + return setImmediate(retry); + } else { + // node < 0.9.0 + return process.nextTick(retry); + } + } + return callback(e); + } + return handleResult(loader, module, callback); + } +}; +function handleResult(loader, module, callback) { + if(typeof module !== "function" && typeof module !== "object") { + return callback(new LoaderLoadingError( + "Module '" + loader.path + "' is not a loader (export function or es6 module)" + )); + } + loader.normal = typeof module === "function" ? module : module.default; + loader.pitch = module.pitch; + loader.raw = module.raw; + if(typeof loader.normal !== "function" && typeof loader.pitch !== "function") { + return callback(new LoaderLoadingError( + "Module '" + loader.path + "' is not a loader (must have normal or pitch function)" + )); + } + callback(); +} -const Generator = __webpack_require__(93401); -const WebAssemblyExportImportedDependency = __webpack_require__(52204); -const WebAssemblyImportDependency = __webpack_require__(5239); -const { compareModulesByIdentifier } = __webpack_require__(29579); -const memoize = __webpack_require__(78676); -const WebAssemblyInInitialChunkError = __webpack_require__(47342); -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleTemplate")} ModuleTemplate */ -/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */ +/***/ }), -const getWebAssemblyGenerator = memoize(() => - __webpack_require__(47012) -); -const getWebAssemblyJavascriptGenerator = memoize(() => - __webpack_require__(46545) -); -const getWebAssemblyParser = memoize(() => __webpack_require__(57059)); +/***/ 50569: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -class WebAssemblyModulesPlugin { - constructor(options) { - this.options = options; - } +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "WebAssemblyModulesPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - WebAssemblyImportDependency, - normalModuleFactory - ); +/** + * Module exports. + */ - compilation.dependencyFactories.set( - WebAssemblyExportImportedDependency, - normalModuleFactory - ); +module.exports = __webpack_require__(58750) - normalModuleFactory.hooks.createParser - .for("webassembly/sync") - .tap("WebAssemblyModulesPlugin", () => { - const WebAssemblyParser = getWebAssemblyParser(); - return new WebAssemblyParser(); - }); +/***/ }), - normalModuleFactory.hooks.createGenerator - .for("webassembly/sync") - .tap("WebAssemblyModulesPlugin", () => { - const WebAssemblyJavascriptGenerator = - getWebAssemblyJavascriptGenerator(); - const WebAssemblyGenerator = getWebAssemblyGenerator(); +/***/ 78585: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - return Generator.byType({ - javascript: new WebAssemblyJavascriptGenerator(), - webassembly: new WebAssemblyGenerator(this.options) - }); - }); +"use strict"; +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - compilation.hooks.renderManifest.tap( - "WebAssemblyModulesPlugin", - (result, options) => { - const { chunkGraph } = compilation; - const { chunk, outputOptions, codeGenerationResults } = options; - for (const module of chunkGraph.getOrderedChunkModulesIterable( - chunk, - compareModulesByIdentifier - )) { - if (module.type === "webassembly/sync") { - const filenameTemplate = - outputOptions.webassemblyModuleFilename; - result.push({ - render: () => - codeGenerationResults.getSource( - module, - chunk.runtime, - "webassembly" - ), - filenameTemplate, - pathOptions: { - module, - runtime: chunk.runtime, - chunkGraph - }, - auxiliary: true, - identifier: `webassemblyModule${chunkGraph.getModuleId( - module - )}`, - hash: chunkGraph.getModuleHash(module, chunk.runtime) - }); - } - } +/** + * Module dependencies. + * @private + */ - return result; - } - ); +var db = __webpack_require__(50569) +var extname = (__webpack_require__(71017).extname) - compilation.hooks.afterChunks.tap("WebAssemblyModulesPlugin", () => { - const chunkGraph = compilation.chunkGraph; - const initialWasmModules = new Set(); - for (const chunk of compilation.chunks) { - if (chunk.canBeInitial()) { - for (const module of chunkGraph.getChunkModulesIterable(chunk)) { - if (module.type === "webassembly/sync") { - initialWasmModules.add(module); - } - } - } - } - for (const module of initialWasmModules) { - compilation.errors.push( - new WebAssemblyInInitialChunkError( - module, - compilation.moduleGraph, - compilation.chunkGraph, - compilation.requestShortener - ) - ); - } - }); - } - ); - } -} +/** + * Module variables. + * @private + */ -module.exports = WebAssemblyModulesPlugin; +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i +/** + * Module exports. + * @public + */ -/***/ }), +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) -/***/ 57059: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] -const t = __webpack_require__(51826); -const { moduleContextFromModuleAST } = __webpack_require__(51826); -const { decode } = __webpack_require__(73726); -const Parser = __webpack_require__(11715); -const StaticExportsDependency = __webpack_require__(91418); -const WebAssemblyExportImportedDependency = __webpack_require__(52204); -const WebAssemblyImportDependency = __webpack_require__(5239); + if (mime && mime.charset) { + return mime.charset + } -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../Parser").ParserState} ParserState */ -/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } -const JS_COMPAT_TYPES = new Set(["i32", "f32", "f64"]); + return false +} /** - * @param {t.Signature} signature the func signature - * @returns {null | string} the type incompatible with js types + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} */ -const getJsIncompatibleType = signature => { - for (const param of signature.params) { - if (!JS_COMPAT_TYPES.has(param.valtype)) { - return `${param.valtype} as parameter`; - } - } - for (const type of signature.results) { - if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; - } - return null; -}; + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} /** - * TODO why are there two different Signature types? - * @param {t.FuncSignature} signature the func signature - * @returns {null | string} the type incompatible with js types + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} */ -const getJsIncompatibleTypeOfFuncSignature = signature => { - for (const param of signature.args) { - if (!JS_COMPAT_TYPES.has(param)) { - return `${param} as parameter`; - } - } - for (const type of signature.result) { - if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; - } - return null; -}; -const decoderOpts = { - ignoreCodeSection: true, - ignoreDataSection: true, +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } - // this will avoid having to lookup with identifiers in the ModuleContext - ignoreCustomNameSection: true -}; + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) -class WebAssemblyParser extends Parser { - constructor(options) { - super(); - this.hooks = Object.freeze({}); - this.options = options; - } + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] - /** - * @param {string | Buffer | PreparsedAst} source the source to parse - * @param {ParserState} state the parser state - * @returns {ParserState} the parser state - */ - parse(source, state) { - if (!Buffer.isBuffer(source)) { - throw new Error("WebAssemblyParser input must be a Buffer"); - } + if (!exts || !exts.length) { + return false + } - // flag it as ESM - state.module.buildInfo.strict = true; - state.module.buildMeta.exportsType = "namespace"; + return exts[0] +} - // parse it - const program = decode(source, decoderOpts); - const module = program.body[0]; +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ - const moduleContext = moduleContextFromModuleAST(module); +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } - // extract imports and exports - const exports = []; - let jsIncompatibleExports = (state.module.buildMeta.jsIncompatibleExports = - undefined); + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) - const importedGlobals = []; - t.traverse(module, { - ModuleExport({ node }) { - const descriptor = node.descr; + if (!extension) { + return false + } - if (descriptor.exportType === "Func") { - const funcIdx = descriptor.id.value; + return exports.types[extension] || false +} - /** @type {t.FuncSignature} */ - const funcSignature = moduleContext.getFunction(funcIdx); +/** + * Populate the extensions and types maps. + * @private + */ - const incompatibleType = - getJsIncompatibleTypeOfFuncSignature(funcSignature); +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] - if (incompatibleType) { - if (jsIncompatibleExports === undefined) { - jsIncompatibleExports = - state.module.buildMeta.jsIncompatibleExports = {}; - } - jsIncompatibleExports[node.name] = incompatibleType; - } - } + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions - exports.push(node.name); + if (!exts || !exts.length) { + return + } - if (node.descr && node.descr.exportType === "Global") { - const refNode = importedGlobals[node.descr.id.value]; - if (refNode) { - const dep = new WebAssemblyExportImportedDependency( - node.name, - refNode.module, - refNode.name, - refNode.descr.valtype - ); + // mime -> extensions + extensions[type] = exts - state.module.addDependency(dep); - } - } - }, + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] - Global({ node }) { - const init = node.init[0]; + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) - let importNode = null; + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } - if (init.id === "get_global") { - const globalIdx = init.args[0].value; + // set the extension -> mime + types[extension] = type + } + }) +} - if (globalIdx < importedGlobals.length) { - importNode = importedGlobals[globalIdx]; - } - } - importedGlobals.push(importNode); - }, +/***/ }), - ModuleImport({ node }) { - /** @type {false | string} */ - let onlyDirectImport = false; +/***/ 76297: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (t.isMemory(node.descr) === true) { - onlyDirectImport = "Memory"; - } else if (t.isTable(node.descr) === true) { - onlyDirectImport = "Table"; - } else if (t.isFuncImportDescr(node.descr) === true) { - const incompatibleType = getJsIncompatibleType(node.descr.signature); - if (incompatibleType) { - onlyDirectImport = `Non-JS-compatible Func Signature (${incompatibleType})`; - } - } else if (t.isGlobalType(node.descr) === true) { - const type = node.descr.valtype; - if (!JS_COMPAT_TYPES.has(type)) { - onlyDirectImport = `Non-JS-compatible Global Type (${type})`; - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const dep = new WebAssemblyImportDependency( - node.module, - node.name, - node.descr, - onlyDirectImport - ); - state.module.addDependency(dep); +const Hook = __webpack_require__(72258); +const HookCodeFactory = __webpack_require__(177); - if (t.isGlobalType(node.descr)) { - importedGlobals.push(node); +class AsyncParallelBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, onDone }) { + let code = ""; + code += `var _results = new Array(${this.options.taps.length});\n`; + code += "var _checkDone = function() {\n"; + code += "for(var i = 0; i < _results.length; i++) {\n"; + code += "var item = _results[i];\n"; + code += "if(item === undefined) return false;\n"; + code += "if(item.result !== undefined) {\n"; + code += onResult("item.result"); + code += "return true;\n"; + code += "}\n"; + code += "if(item.error) {\n"; + code += onError("item.error"); + code += "return true;\n"; + code += "}\n"; + code += "}\n"; + code += "return false;\n"; + code += "}\n"; + code += this.callTapsParallel({ + onError: (i, err, done, doneBreak) => { + let code = ""; + code += `if(${i} < _results.length && ((_results.length = ${i + + 1}), (_results[${i}] = { error: ${err} }), _checkDone())) {\n`; + code += doneBreak(true); + code += "} else {\n"; + code += done(); + code += "}\n"; + return code; + }, + onResult: (i, result, done, doneBreak) => { + let code = ""; + code += `if(${i} < _results.length && (${result} !== undefined && (_results.length = ${i + + 1}), (_results[${i}] = { result: ${result} }), _checkDone())) {\n`; + code += doneBreak(true); + code += "} else {\n"; + code += done(); + code += "}\n"; + return code; + }, + onTap: (i, run, done, doneBreak) => { + let code = ""; + if (i > 0) { + code += `if(${i} >= _results.length) {\n`; + code += done(); + code += "} else {\n"; } - } + code += run(); + if (i > 0) code += "}\n"; + return code; + }, + onDone }); + return code; + } +} - state.module.addDependency(new StaticExportsDependency(exports, false)); +const factory = new AsyncParallelBailHookCodeFactory(); - return state; - } +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncParallelBailHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncParallelBailHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; } -module.exports = WebAssemblyParser; +AsyncParallelBailHook.prototype = null; + +module.exports = AsyncParallelBailHook; /***/ }), -/***/ 18650: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 45874: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -139168,70 +139584,42 @@ module.exports = WebAssemblyParser; */ +const Hook = __webpack_require__(72258); +const HookCodeFactory = __webpack_require__(177); -const Template = __webpack_require__(39722); -const WebAssemblyImportDependency = __webpack_require__(5239); - -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../ModuleGraph")} ModuleGraph */ +class AsyncParallelHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsParallel({ + onError: (i, err, done, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} -/** @typedef {Object} UsedWasmDependency - * @property {WebAssemblyImportDependency} dependency the dependency - * @property {string} name the export name - * @property {string} module the module name - */ +const factory = new AsyncParallelHookCodeFactory(); -const MANGLED_MODULE = "a"; +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; -/** - * @param {ModuleGraph} moduleGraph the module graph - * @param {Module} module the module - * @param {boolean} mangle mangle module and export names - * @returns {UsedWasmDependency[]} used dependencies and (mangled) name - */ -const getUsedDependencies = (moduleGraph, module, mangle) => { - /** @type {UsedWasmDependency[]} */ - const array = []; - let importIndex = 0; - for (const dep of module.dependencies) { - if (dep instanceof WebAssemblyImportDependency) { - if ( - dep.description.type === "GlobalType" || - moduleGraph.getModule(dep) === null - ) { - continue; - } +function AsyncParallelHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncParallelHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} - const exportName = dep.name; - // TODO add the following 3 lines when removing of ModuleExport is possible - // const importedModule = moduleGraph.getModule(dep); - // const usedName = importedModule && moduleGraph.getExportsInfo(importedModule).getUsedName(exportName, runtime); - // if (usedName !== false) { - if (mangle) { - array.push({ - dependency: dep, - name: Template.numberToIdentifier(importIndex++), - module: MANGLED_MODULE - }); - } else { - array.push({ - dependency: dep, - name: exportName, - module: dep.request - }); - } - } - } - return array; -}; +AsyncParallelHook.prototype = null; -exports.getUsedDependencies = getUsedDependencies; -exports.MANGLED_MODULE = MANGLED_MODULE; +module.exports = AsyncParallelHook; /***/ }), -/***/ 78613: +/***/ 13633: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -139241,123 +139629,47 @@ exports.MANGLED_MODULE = MANGLED_MODULE; */ +const Hook = __webpack_require__(72258); +const HookCodeFactory = __webpack_require__(177); -/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */ -/** @typedef {import("../../declarations/WebpackOptions").WasmLoadingType} WasmLoadingType */ -/** @typedef {import("../Compiler")} Compiler */ - -/** @type {WeakMap>} */ -const enabledTypes = new WeakMap(); - -const getEnabledTypes = compiler => { - let set = enabledTypes.get(compiler); - if (set === undefined) { - set = new Set(); - enabledTypes.set(compiler, set); - } - return set; -}; - -class EnableWasmLoadingPlugin { - /** - * @param {WasmLoadingType} type library type that should be available - */ - constructor(type) { - this.type = type; - } - - /** - * @param {Compiler} compiler the compiler instance - * @param {WasmLoadingType} type type of library - * @returns {void} - */ - static setEnabled(compiler, type) { - getEnabledTypes(compiler).add(type); - } - - /** - * @param {Compiler} compiler the compiler instance - * @param {WasmLoadingType} type type of library - * @returns {void} - */ - static checkEnabled(compiler, type) { - if (!getEnabledTypes(compiler).has(type)) { - throw new Error( - `Library type "${type}" is not enabled. ` + - "EnableWasmLoadingPlugin need to be used to enable this type of wasm loading. " + - 'This usually happens through the "output.enabledWasmLoadingTypes" option. ' + - 'If you are using a function as entry which sets "wasmLoading", you need to add all potential library types to "output.enabledWasmLoadingTypes". ' + - "These types are enabled: " + - Array.from(getEnabledTypes(compiler)).join(", ") - ); - } +class AsyncSeriesBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, resultReturns, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onResult: (i, result, next) => + `if(${result} !== undefined) {\n${onResult( + result + )}\n} else {\n${next()}}\n`, + resultReturns, + onDone + }); } +} - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - const { type } = this; +const factory = new AsyncSeriesBailHookCodeFactory(); - // Only enable once - const enabled = getEnabledTypes(compiler); - if (enabled.has(type)) return; - enabled.add(type); +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; - if (typeof type === "string") { - switch (type) { - case "fetch": { - // TODO webpack 6 remove FetchCompileWasmPlugin - const FetchCompileWasmPlugin = __webpack_require__(35537); - const FetchCompileAsyncWasmPlugin = __webpack_require__(8437); - new FetchCompileWasmPlugin({ - mangleImports: compiler.options.optimization.mangleWasmImports - }).apply(compiler); - new FetchCompileAsyncWasmPlugin().apply(compiler); - break; - } - case "async-node": { - // TODO webpack 6 remove ReadFileCompileWasmPlugin - const ReadFileCompileWasmPlugin = __webpack_require__(98939); - // @ts-expect-error typescript bug for duplicate require - const ReadFileCompileAsyncWasmPlugin = __webpack_require__(73163); - new ReadFileCompileWasmPlugin({ - mangleImports: compiler.options.optimization.mangleWasmImports - }).apply(compiler); - new ReadFileCompileAsyncWasmPlugin({ type }).apply(compiler); - break; - } - case "async-node-module": { - // @ts-expect-error typescript bug for duplicate require - const ReadFileCompileAsyncWasmPlugin = __webpack_require__(73163); - new ReadFileCompileAsyncWasmPlugin({ type, import: true }).apply( - compiler - ); - break; - } - case "universal": - throw new Error( - "Universal WebAssembly Loading is not implemented yet" - ); - default: - throw new Error(`Unsupported wasm loading type ${type}. -Plugins which provide custom wasm loading types must call EnableWasmLoadingPlugin.setEnabled(compiler, type) to disable this error.`); - } - } else { - // TODO support plugin instances here - // apply them to the compiler - } - } +function AsyncSeriesBailHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesBailHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; } -module.exports = EnableWasmLoadingPlugin; +AsyncSeriesBailHook.prototype = null; + +module.exports = AsyncSeriesBailHook; /***/ }), -/***/ 8437: +/***/ 40436: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -139367,67 +139679,42 @@ module.exports = EnableWasmLoadingPlugin; */ +const Hook = __webpack_require__(72258); +const HookCodeFactory = __webpack_require__(177); -const RuntimeGlobals = __webpack_require__(16475); -const AsyncWasmLoadingRuntimeModule = __webpack_require__(5434); +class AsyncSeriesHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} -/** @typedef {import("../Compiler")} Compiler */ +const factory = new AsyncSeriesHookCodeFactory(); -class FetchCompileAsyncWasmPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "FetchCompileAsyncWasmPlugin", - compilation => { - const globalWasmLoading = compilation.outputOptions.wasmLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const wasmLoading = - options && options.wasmLoading !== undefined - ? options.wasmLoading - : globalWasmLoading; - return wasmLoading === "fetch"; - }; - const generateLoadBinaryCode = path => - `fetch(${RuntimeGlobals.publicPath} + ${path})`; +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.instantiateWasm) - .tap("FetchCompileAsyncWasmPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - const chunkGraph = compilation.chunkGraph; - if ( - !chunkGraph.hasModuleInGraph( - chunk, - m => m.type === "webassembly/async" - ) - ) { - return; - } - set.add(RuntimeGlobals.publicPath); - compilation.addRuntimeModule( - chunk, - new AsyncWasmLoadingRuntimeModule({ - generateLoadBinaryCode, - supportsStreaming: true - }) - ); - }); - } - ); - } +function AsyncSeriesHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; } -module.exports = FetchCompileAsyncWasmPlugin; +AsyncSeriesHook.prototype = null; + +module.exports = AsyncSeriesHook; /***/ }), -/***/ 35537: +/***/ 34656: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -139437,76 +139724,97 @@ module.exports = FetchCompileAsyncWasmPlugin; */ +const Hook = __webpack_require__(72258); +const HookCodeFactory = __webpack_require__(177); -const RuntimeGlobals = __webpack_require__(16475); -const WasmChunkLoadingRuntimeModule = __webpack_require__(87394); +class AsyncSeriesLoopHookCodeFactory extends HookCodeFactory { + content({ onError, onDone }) { + return this.callTapsLooping({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} -/** @typedef {import("../Compiler")} Compiler */ +const factory = new AsyncSeriesLoopHookCodeFactory(); -// TODO webpack 6 remove +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; -class FetchCompileWasmPlugin { - constructor(options) { - this.options = options || {}; - } +function AsyncSeriesLoopHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesLoopHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "FetchCompileWasmPlugin", - compilation => { - const globalWasmLoading = compilation.outputOptions.wasmLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const wasmLoading = - options && options.wasmLoading !== undefined - ? options.wasmLoading - : globalWasmLoading; - return wasmLoading === "fetch"; - }; - const generateLoadBinaryCode = path => - `fetch(${RuntimeGlobals.publicPath} + ${path})`; +AsyncSeriesLoopHook.prototype = null; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("FetchCompileWasmPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - const chunkGraph = compilation.chunkGraph; - if ( - !chunkGraph.hasModuleInGraph( - chunk, - m => m.type === "webassembly/sync" - ) - ) { - return; - } - set.add(RuntimeGlobals.moduleCache); - set.add(RuntimeGlobals.publicPath); - compilation.addRuntimeModule( - chunk, - new WasmChunkLoadingRuntimeModule({ - generateLoadBinaryCode, - supportsStreaming: true, - mangleImports: this.options.mangleImports, - runtimeRequirements: set - }) - ); - }); - } - ); +module.exports = AsyncSeriesLoopHook; + + +/***/ }), + +/***/ 47794: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Hook = __webpack_require__(72258); +const HookCodeFactory = __webpack_require__(177); + +class AsyncSeriesWaterfallHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onResult: (i, result, next) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += `${this._args[0]} = ${result};\n`; + code += `}\n`; + code += next(); + return code; + }, + onDone: () => onResult(this._args[0]) + }); } } -module.exports = FetchCompileWasmPlugin; +const factory = new AsyncSeriesWaterfallHookCodeFactory(); + +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function AsyncSeriesWaterfallHook(args = [], name = undefined) { + if (args.length < 1) + throw new Error("Waterfall hooks must have at least one argument"); + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesWaterfallHook; + hook.compile = COMPILE; + hook._call = undefined; + hook.call = undefined; + return hook; +} + +AsyncSeriesWaterfallHook.prototype = null; + +module.exports = AsyncSeriesWaterfallHook; /***/ }), -/***/ 83121: +/***/ 72258: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -139516,590 +139824,656 @@ module.exports = FetchCompileWasmPlugin; */ +const util = __webpack_require__(73837); -const RuntimeGlobals = __webpack_require__(16475); -const JsonpChunkLoadingRuntimeModule = __webpack_require__(84154); +const deprecateContext = util.deprecate(() => {}, +"Hook.context is deprecated and will be removed"); -/** @typedef {import("../Compiler")} Compiler */ +const CALL_DELEGATE = function(...args) { + this.call = this._createCall("sync"); + return this.call(...args); +}; +const CALL_ASYNC_DELEGATE = function(...args) { + this.callAsync = this._createCall("async"); + return this.callAsync(...args); +}; +const PROMISE_DELEGATE = function(...args) { + this.promise = this._createCall("promise"); + return this.promise(...args); +}; -class JsonpChunkLoadingPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "JsonpChunkLoadingPlugin", - compilation => { - const globalChunkLoading = compilation.outputOptions.chunkLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const chunkLoading = - options && options.chunkLoading !== undefined - ? options.chunkLoading - : globalChunkLoading; - return chunkLoading === "jsonp"; - }; - const onceForChunkSet = new WeakSet(); - const handler = (chunk, set) => { - if (onceForChunkSet.has(chunk)) return; - onceForChunkSet.add(chunk); - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.hasOwnProperty); - compilation.addRuntimeModule( - chunk, - new JsonpChunkLoadingRuntimeModule(set) - ); - }; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("JsonpChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap("JsonpChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadManifest) - .tap("JsonpChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.baseURI) - .tap("JsonpChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.onChunksLoaded) - .tap("JsonpChunkLoadingPlugin", handler); +class Hook { + constructor(args = [], name = undefined) { + this._args = args; + this.name = name; + this.taps = []; + this.interceptors = []; + this._call = CALL_DELEGATE; + this.call = CALL_DELEGATE; + this._callAsync = CALL_ASYNC_DELEGATE; + this.callAsync = CALL_ASYNC_DELEGATE; + this._promise = PROMISE_DELEGATE; + this.promise = PROMISE_DELEGATE; + this._x = undefined; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("JsonpChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.loadScript); - set.add(RuntimeGlobals.getChunkScriptFilename); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap("JsonpChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.loadScript); - set.add(RuntimeGlobals.getChunkUpdateScriptFilename); - set.add(RuntimeGlobals.moduleCache); - set.add(RuntimeGlobals.hmrModuleData); - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadManifest) - .tap("JsonpChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.getUpdateManifestFilename); - }); + this.compile = this.compile; + this.tap = this.tap; + this.tapAsync = this.tapAsync; + this.tapPromise = this.tapPromise; + } + + compile(options) { + throw new Error("Abstract: should be overridden"); + } + + _createCall(type) { + return this.compile({ + taps: this.taps, + interceptors: this.interceptors, + args: this._args, + type: type + }); + } + + _tap(type, options, fn) { + if (typeof options === "string") { + options = { + name: options.trim() + }; + } else if (typeof options !== "object" || options === null) { + throw new Error("Invalid tap options"); + } + if (typeof options.name !== "string" || options.name === "") { + throw new Error("Missing name for tap"); + } + if (typeof options.context !== "undefined") { + deprecateContext(); + } + options = Object.assign({ type, fn }, options); + options = this._runRegisterInterceptors(options); + this._insert(options); + } + + tap(options, fn) { + this._tap("sync", options, fn); + } + + tapAsync(options, fn) { + this._tap("async", options, fn); + } + + tapPromise(options, fn) { + this._tap("promise", options, fn); + } + + _runRegisterInterceptors(options) { + for (const interceptor of this.interceptors) { + if (interceptor.register) { + const newOptions = interceptor.register(options); + if (newOptions !== undefined) { + options = newOptions; + } } - ); + } + return options; + } + + withOptions(options) { + const mergeOptions = opt => + Object.assign({}, options, typeof opt === "string" ? { name: opt } : opt); + + return { + name: this.name, + tap: (opt, fn) => this.tap(mergeOptions(opt), fn), + tapAsync: (opt, fn) => this.tapAsync(mergeOptions(opt), fn), + tapPromise: (opt, fn) => this.tapPromise(mergeOptions(opt), fn), + intercept: interceptor => this.intercept(interceptor), + isUsed: () => this.isUsed(), + withOptions: opt => this.withOptions(mergeOptions(opt)) + }; + } + + isUsed() { + return this.taps.length > 0 || this.interceptors.length > 0; + } + + intercept(interceptor) { + this._resetCompilation(); + this.interceptors.push(Object.assign({}, interceptor)); + if (interceptor.register) { + for (let i = 0; i < this.taps.length; i++) { + this.taps[i] = interceptor.register(this.taps[i]); + } + } + } + + _resetCompilation() { + this.call = this._call; + this.callAsync = this._callAsync; + this.promise = this._promise; + } + + _insert(item) { + this._resetCompilation(); + let before; + if (typeof item.before === "string") { + before = new Set([item.before]); + } else if (Array.isArray(item.before)) { + before = new Set(item.before); + } + let stage = 0; + if (typeof item.stage === "number") { + stage = item.stage; + } + let i = this.taps.length; + while (i > 0) { + i--; + const x = this.taps[i]; + this.taps[i + 1] = x; + const xStage = x.stage || 0; + if (before) { + if (before.has(x.name)) { + before.delete(x.name); + continue; + } + if (before.size > 0) { + continue; + } + } + if (xStage > stage) { + continue; + } + i++; + break; + } + this.taps[i] = item; } } -module.exports = JsonpChunkLoadingPlugin; +Object.setPrototypeOf(Hook.prototype, null); + +module.exports = Hook; /***/ }), -/***/ 84154: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 177: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ +class HookCodeFactory { + constructor(config) { + this.config = config; + this.options = undefined; + this._args = undefined; + } -const { SyncWaterfallHook } = __webpack_require__(41242); -const Compilation = __webpack_require__(85720); -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); -const chunkHasJs = (__webpack_require__(89464).chunkHasJs); -const { getInitialChunkIds } = __webpack_require__(98124); -const compileBooleanMatcher = __webpack_require__(29404); - -/** @typedef {import("../Chunk")} Chunk */ - -/** - * @typedef {Object} JsonpCompilationPluginHooks - * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload - * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch - */ + create(options) { + this.init(options); + let fn; + switch (this.options.type) { + case "sync": + fn = new Function( + this.args(), + '"use strict";\n' + + this.header() + + this.contentWithInterceptors({ + onError: err => `throw ${err};\n`, + onResult: result => `return ${result};\n`, + resultReturns: true, + onDone: () => "", + rethrowIfPossible: true + }) + ); + break; + case "async": + fn = new Function( + this.args({ + after: "_callback" + }), + '"use strict";\n' + + this.header() + + this.contentWithInterceptors({ + onError: err => `_callback(${err});\n`, + onResult: result => `_callback(null, ${result});\n`, + onDone: () => "_callback();\n" + }) + ); + break; + case "promise": + let errorHelperUsed = false; + const content = this.contentWithInterceptors({ + onError: err => { + errorHelperUsed = true; + return `_error(${err});\n`; + }, + onResult: result => `_resolve(${result});\n`, + onDone: () => "_resolve();\n" + }); + let code = ""; + code += '"use strict";\n'; + code += this.header(); + code += "return new Promise((function(_resolve, _reject) {\n"; + if (errorHelperUsed) { + code += "var _sync = true;\n"; + code += "function _error(_err) {\n"; + code += "if(_sync)\n"; + code += + "_resolve(Promise.resolve().then((function() { throw _err; })));\n"; + code += "else\n"; + code += "_reject(_err);\n"; + code += "};\n"; + } + code += content; + if (errorHelperUsed) { + code += "_sync = false;\n"; + } + code += "}));\n"; + fn = new Function(this.args(), code); + break; + } + this.deinit(); + return fn; + } -/** @type {WeakMap} */ -const compilationHooksMap = new WeakMap(); + setup(instance, options) { + instance._x = options.taps.map(t => t.fn); + } -class JsonpChunkLoadingRuntimeModule extends RuntimeModule { /** - * @param {Compilation} compilation the compilation - * @returns {JsonpCompilationPluginHooks} hooks + * @param {{ type: "sync" | "promise" | "async", taps: Array, interceptors: Array }} options */ - static getCompilationHooks(compilation) { - if (!(compilation instanceof Compilation)) { - throw new TypeError( - "The 'compilation' argument must be an instance of Compilation" + init(options) { + this.options = options; + this._args = options.args.slice(); + } + + deinit() { + this.options = undefined; + this._args = undefined; + } + + contentWithInterceptors(options) { + if (this.options.interceptors.length > 0) { + const onError = options.onError; + const onResult = options.onResult; + const onDone = options.onDone; + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.call) { + code += `${this.getInterceptor(i)}.call(${this.args({ + before: interceptor.context ? "_context" : undefined + })});\n`; + } + } + code += this.content( + Object.assign(options, { + onError: + onError && + (err => { + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.error) { + code += `${this.getInterceptor(i)}.error(${err});\n`; + } + } + code += onError(err); + return code; + }), + onResult: + onResult && + (result => { + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.result) { + code += `${this.getInterceptor(i)}.result(${result});\n`; + } + } + code += onResult(result); + return code; + }), + onDone: + onDone && + (() => { + let code = ""; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.done) { + code += `${this.getInterceptor(i)}.done();\n`; + } + } + code += onDone(); + return code; + }) + }) ); + return code; + } else { + return this.content(options); } - let hooks = compilationHooksMap.get(compilation); - if (hooks === undefined) { - hooks = { - linkPreload: new SyncWaterfallHook(["source", "chunk"]), - linkPrefetch: new SyncWaterfallHook(["source", "chunk"]) - }; - compilationHooksMap.set(compilation, hooks); + } + + header() { + let code = ""; + if (this.needContext()) { + code += "var _context = {};\n"; + } else { + code += "var _context;\n"; } - return hooks; + code += "var _x = this._x;\n"; + if (this.options.interceptors.length > 0) { + code += "var _taps = this.taps;\n"; + code += "var _interceptors = this.interceptors;\n"; + } + return code; } - constructor(runtimeRequirements) { - super("jsonp chunk loading", RuntimeModule.STAGE_ATTACH); - this._runtimeRequirements = runtimeRequirements; + needContext() { + for (const tap of this.options.taps) if (tap.context) return true; + return false; } - /** - * @returns {string} runtime code - */ - generate() { - const { chunkGraph, compilation, chunk } = this; - const { - runtimeTemplate, - outputOptions: { - chunkLoadingGlobal, - hotUpdateGlobal, - crossOriginLoading, - scriptType + callTap(tapIndex, { onError, onResult, onDone, rethrowIfPossible }) { + let code = ""; + let hasTapCached = false; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.tap) { + if (!hasTapCached) { + code += `var _tap${tapIndex} = ${this.getTap(tapIndex)};\n`; + hasTapCached = true; + } + code += `${this.getInterceptor(i)}.tap(${ + interceptor.context ? "_context, " : "" + }_tap${tapIndex});\n`; } - } = compilation; - const globalObject = runtimeTemplate.globalObject; - const { linkPreload, linkPrefetch } = - JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation); - const fn = RuntimeGlobals.ensureChunkHandlers; - const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI); - const withLoading = this._runtimeRequirements.has( - RuntimeGlobals.ensureChunkHandlers - ); - const withCallback = this._runtimeRequirements.has( - RuntimeGlobals.chunkCallback - ); - const withOnChunkLoad = this._runtimeRequirements.has( - RuntimeGlobals.onChunksLoaded - ); - const withHmr = this._runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const withHmrManifest = this._runtimeRequirements.has( - RuntimeGlobals.hmrDownloadManifest - ); - const withPrefetch = this._runtimeRequirements.has( - RuntimeGlobals.prefetchChunkHandlers - ); - const withPreload = this._runtimeRequirements.has( - RuntimeGlobals.preloadChunkHandlers - ); - const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( - chunkLoadingGlobal - )}]`; - const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs); - const hasJsMatcher = compileBooleanMatcher(conditionMap); - const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); + } + code += `var _fn${tapIndex} = ${this.getTapFn(tapIndex)};\n`; + const tap = this.options.taps[tapIndex]; + switch (tap.type) { + case "sync": + if (!rethrowIfPossible) { + code += `var _hasError${tapIndex} = false;\n`; + code += "try {\n"; + } + if (onResult) { + code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + } else { + code += `_fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + } + if (!rethrowIfPossible) { + code += "} catch(_err) {\n"; + code += `_hasError${tapIndex} = true;\n`; + code += onError("_err"); + code += "}\n"; + code += `if(!_hasError${tapIndex}) {\n`; + } + if (onResult) { + code += onResult(`_result${tapIndex}`); + } + if (onDone) { + code += onDone(); + } + if (!rethrowIfPossible) { + code += "}\n"; + } + break; + case "async": + let cbCode = ""; + if (onResult) + cbCode += `(function(_err${tapIndex}, _result${tapIndex}) {\n`; + else cbCode += `(function(_err${tapIndex}) {\n`; + cbCode += `if(_err${tapIndex}) {\n`; + cbCode += onError(`_err${tapIndex}`); + cbCode += "} else {\n"; + if (onResult) { + cbCode += onResult(`_result${tapIndex}`); + } + if (onDone) { + cbCode += onDone(); + } + cbCode += "}\n"; + cbCode += "})"; + code += `_fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined, + after: cbCode + })});\n`; + break; + case "promise": + code += `var _hasResult${tapIndex} = false;\n`; + code += `var _promise${tapIndex} = _fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + code += `if (!_promise${tapIndex} || !_promise${tapIndex}.then)\n`; + code += ` throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise${tapIndex} + ')');\n`; + code += `_promise${tapIndex}.then((function(_result${tapIndex}) {\n`; + code += `_hasResult${tapIndex} = true;\n`; + if (onResult) { + code += onResult(`_result${tapIndex}`); + } + if (onDone) { + code += onDone(); + } + code += `}), function(_err${tapIndex}) {\n`; + code += `if(_hasResult${tapIndex}) throw _err${tapIndex};\n`; + code += onError(`_err${tapIndex}`); + code += "});\n"; + break; + } + return code; + } - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_jsonp` - : undefined; + callTapsSeries({ + onError, + onResult, + resultReturns, + onDone, + doneReturns, + rethrowIfPossible + }) { + if (this.options.taps.length === 0) return onDone(); + const firstAsync = this.options.taps.findIndex(t => t.type !== "sync"); + const somethingReturns = resultReturns || doneReturns; + let code = ""; + let current = onDone; + let unrollCounter = 0; + for (let j = this.options.taps.length - 1; j >= 0; j--) { + const i = j; + const unroll = + current !== onDone && + (this.options.taps[i].type !== "sync" || unrollCounter++ > 20); + if (unroll) { + unrollCounter = 0; + code += `function _next${i}() {\n`; + code += current(); + code += `}\n`; + current = () => `${somethingReturns ? "return " : ""}_next${i}();\n`; + } + const done = current; + const doneBreak = skipDone => { + if (skipDone) return ""; + return onDone(); + }; + const content = this.callTap(i, { + onError: error => onError(i, error, done, doneBreak), + onResult: + onResult && + (result => { + return onResult(i, result, done, doneBreak); + }), + onDone: !onResult && done, + rethrowIfPossible: + rethrowIfPossible && (firstAsync < 0 || i < firstAsync) + }); + current = () => content; + } + code += current(); + return code; + } - return Template.asString([ - withBaseURI - ? Template.asString([ - `${RuntimeGlobals.baseURI} = document.baseURI || self.location.href;` - ]) - : "// no baseURI", - "", - "// object to store loaded and loading chunks", - "// undefined = chunk not loaded, null = chunk preloaded/prefetched", - "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded", - `var installedChunks = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{`, - Template.indent( - Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join( - ",\n" - ) - ), - "};", - "", - withLoading - ? Template.asString([ - `${fn}.j = ${runtimeTemplate.basicFunction( - "chunkId, promises", - hasJsMatcher !== false - ? Template.indent([ - "// JSONP chunk loading for javascript", - `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, - 'if(installedChunkData !== 0) { // 0 means "already installed".', - Template.indent([ - "", - '// a Promise means "currently loading".', - "if(installedChunkData) {", - Template.indent([ - "promises.push(installedChunkData[2]);" - ]), - "} else {", - Template.indent([ - hasJsMatcher === true - ? "if(true) { // all chunks have JS" - : `if(${hasJsMatcher("chunkId")}) {`, - Template.indent([ - "// setup Promise in chunk cache", - `var promise = new Promise(${runtimeTemplate.expressionFunction( - `installedChunkData = installedChunks[chunkId] = [resolve, reject]`, - "resolve, reject" - )});`, - "promises.push(installedChunkData[2] = promise);", - "", - "// start chunk loading", - `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, - "// create error before stack unwound to get useful stacktrace later", - "var error = new Error();", - `var loadingEnded = ${runtimeTemplate.basicFunction( - "event", - [ - `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`, - Template.indent([ - "installedChunkData = installedChunks[chunkId];", - "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;", - "if(installedChunkData) {", - Template.indent([ - "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", - "var realSrc = event && event.target && event.target.src;", - "error.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", - "error.name = 'ChunkLoadError';", - "error.type = errorType;", - "error.request = realSrc;", - "installedChunkData[1](error);" - ]), - "}" - ]), - "}" - ] - )};`, - `${RuntimeGlobals.loadScript}(url, loadingEnded, "chunk-" + chunkId, chunkId);` - ]), - "} else installedChunks[chunkId] = 0;" - ]), - "}" - ]), - "}" - ]) - : Template.indent(["installedChunks[chunkId] = 0;"]) - )};` - ]) - : "// no chunk on demand loading", - "", - withPrefetch && hasJsMatcher !== false - ? `${ - RuntimeGlobals.prefetchChunkHandlers - }.j = ${runtimeTemplate.basicFunction("chunkId", [ - `if((!${ - RuntimeGlobals.hasOwnProperty - }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ - hasJsMatcher === true ? "true" : hasJsMatcher("chunkId") - }) {`, - Template.indent([ - "installedChunks[chunkId] = null;", - linkPrefetch.call( - Template.asString([ - "var link = document.createElement('link');", - crossOriginLoading - ? `link.crossOrigin = ${JSON.stringify( - crossOriginLoading - )};` - : "", - `if (${RuntimeGlobals.scriptNonce}) {`, - Template.indent( - `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` - ), - "}", - 'link.rel = "prefetch";', - 'link.as = "script";', - `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);` - ]), - chunk - ), - "document.head.appendChild(link);" - ]), - "}" - ])};` - : "// no prefetching", - "", - withPreload && hasJsMatcher !== false - ? `${ - RuntimeGlobals.preloadChunkHandlers - }.j = ${runtimeTemplate.basicFunction("chunkId", [ - `if((!${ - RuntimeGlobals.hasOwnProperty - }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${ - hasJsMatcher === true ? "true" : hasJsMatcher("chunkId") - }) {`, - Template.indent([ - "installedChunks[chunkId] = null;", - linkPreload.call( - Template.asString([ - "var link = document.createElement('link');", - scriptType - ? `link.type = ${JSON.stringify(scriptType)};` - : "", - "link.charset = 'utf-8';", - `if (${RuntimeGlobals.scriptNonce}) {`, - Template.indent( - `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});` - ), - "}", - 'link.rel = "preload";', - 'link.as = "script";', - `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, - crossOriginLoading - ? Template.asString([ - "if (link.href.indexOf(window.location.origin + '/') !== 0) {", - Template.indent( - `link.crossOrigin = ${JSON.stringify( - crossOriginLoading - )};` - ), - "}" - ]) - : "" - ]), - chunk - ), - "document.head.appendChild(link);" - ]), - "}" - ])};` - : "// no preloaded", - "", - withHmr - ? Template.asString([ - "var currentUpdatedModulesList;", - "var waitingUpdateResolves = {};", - "function loadUpdateChunk(chunkId) {", - Template.indent([ - `return new Promise(${runtimeTemplate.basicFunction( - "resolve, reject", - [ - "waitingUpdateResolves[chunkId] = resolve;", - "// start update chunk loading", - `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`, - "// create error before stack unwound to get useful stacktrace later", - "var error = new Error();", - `var loadingEnded = ${runtimeTemplate.basicFunction("event", [ - "if(waitingUpdateResolves[chunkId]) {", - Template.indent([ - "waitingUpdateResolves[chunkId] = undefined", - "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", - "var realSrc = event && event.target && event.target.src;", - "error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", - "error.name = 'ChunkLoadError';", - "error.type = errorType;", - "error.request = realSrc;", - "reject(error);" - ]), - "}" - ])};`, - `${RuntimeGlobals.loadScript}(url, loadingEnded);` - ] - )});` - ]), - "}", - "", - `${globalObject}[${JSON.stringify( - hotUpdateGlobal - )}] = ${runtimeTemplate.basicFunction( - "chunkId, moreModules, runtime", - [ - "for(var moduleId in moreModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, - Template.indent([ - "currentUpdate[moduleId] = moreModules[moduleId];", - "if(currentUpdatedModulesList) currentUpdatedModulesList.push(moduleId);" - ]), - "}" - ]), - "}", - "if(runtime) currentUpdateRuntime.push(runtime);", - "if(waitingUpdateResolves[chunkId]) {", - Template.indent([ - "waitingUpdateResolves[chunkId]();", - "waitingUpdateResolves[chunkId] = undefined;" - ]), - "}" - ] - )};`, - "", - Template.getFunctionContent( - require('./JavascriptHotModuleReplacement.runtime.js') - ) - .replace(/\$key\$/g, "jsonp") - .replace(/\$installedChunks\$/g, "installedChunks") - .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") - .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) - .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) - .replace( - /\$ensureChunkHandlers\$/g, - RuntimeGlobals.ensureChunkHandlers - ) - .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) - .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) - .replace( - /\$hmrDownloadUpdateHandlers\$/g, - RuntimeGlobals.hmrDownloadUpdateHandlers - ) - .replace( - /\$hmrInvalidateModuleHandlers\$/g, - RuntimeGlobals.hmrInvalidateModuleHandlers - ) - ]) - : "// no HMR", - "", - withHmrManifest - ? Template.asString([ - `${ - RuntimeGlobals.hmrDownloadManifest - } = ${runtimeTemplate.basicFunction("", [ - 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");', - `return fetch(${RuntimeGlobals.publicPath} + ${ - RuntimeGlobals.getUpdateManifestFilename - }()).then(${runtimeTemplate.basicFunction("response", [ - "if(response.status === 404) return; // no update available", - 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);', - "return response.json();" - ])});` - ])};` - ]) - : "// no HMR manifest", - "", - withOnChunkLoad - ? `${ - RuntimeGlobals.onChunksLoaded - }.j = ${runtimeTemplate.returningFunction( - "installedChunks[chunkId] === 0", - "chunkId" - )};` - : "// no on chunks loaded", - "", - withCallback || withLoading - ? Template.asString([ - "// install a JSONP callback for chunk loading", - `var webpackJsonpCallback = ${runtimeTemplate.basicFunction( - "parentChunkLoadingFunction, data", - [ - runtimeTemplate.destructureArray( - ["chunkIds", "moreModules", "runtime"], - "data" - ), - '// add "moreModules" to the modules object,', - '// then flag all "chunkIds" as loaded and fire callback', - "var moduleId, chunkId, i = 0;", - `if(chunkIds.some(${runtimeTemplate.returningFunction( - "installedChunks[id] !== 0", - "id" - )})) {`, - Template.indent([ - "for(moduleId in moreModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, - Template.indent( - `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` - ), - "}" - ]), - "}", - "if(runtime) var result = runtime(__webpack_require__);" - ]), - "}", - "if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);", - "for(;i < chunkIds.length; i++) {", - Template.indent([ - "chunkId = chunkIds[i];", - `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`, - Template.indent("installedChunks[chunkId][0]();"), - "}", - "installedChunks[chunkId] = 0;" - ]), - "}", - withOnChunkLoad - ? `return ${RuntimeGlobals.onChunksLoaded}(result);` - : "" - ] - )}`, - "", - `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, - "chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));", - "chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));" - ]) - : "// no jsonp function" - ]); + callTapsLooping({ onError, onDone, rethrowIfPossible }) { + if (this.options.taps.length === 0) return onDone(); + const syncOnly = this.options.taps.every(t => t.type === "sync"); + let code = ""; + if (!syncOnly) { + code += "var _looper = (function() {\n"; + code += "var _loopAsync = false;\n"; + } + code += "var _loop;\n"; + code += "do {\n"; + code += "_loop = false;\n"; + for (let i = 0; i < this.options.interceptors.length; i++) { + const interceptor = this.options.interceptors[i]; + if (interceptor.loop) { + code += `${this.getInterceptor(i)}.loop(${this.args({ + before: interceptor.context ? "_context" : undefined + })});\n`; + } + } + code += this.callTapsSeries({ + onError, + onResult: (i, result, next, doneBreak) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += "_loop = true;\n"; + if (!syncOnly) code += "if(_loopAsync) _looper();\n"; + code += doneBreak(true); + code += `} else {\n`; + code += next(); + code += `}\n`; + return code; + }, + onDone: + onDone && + (() => { + let code = ""; + code += "if(!_loop) {\n"; + code += onDone(); + code += "}\n"; + return code; + }), + rethrowIfPossible: rethrowIfPossible && syncOnly + }); + code += "} while(_loop);\n"; + if (!syncOnly) { + code += "_loopAsync = true;\n"; + code += "});\n"; + code += "_looper();\n"; + } + return code; } -} - -module.exports = JsonpChunkLoadingRuntimeModule; - - -/***/ }), - -/***/ 4607: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + callTapsParallel({ + onError, + onResult, + onDone, + rethrowIfPossible, + onTap = (i, run) => run() + }) { + if (this.options.taps.length <= 1) { + return this.callTapsSeries({ + onError, + onResult, + onDone, + rethrowIfPossible + }); + } + let code = ""; + code += "do {\n"; + code += `var _counter = ${this.options.taps.length};\n`; + if (onDone) { + code += "var _done = (function() {\n"; + code += onDone(); + code += "});\n"; + } + for (let i = 0; i < this.options.taps.length; i++) { + const done = () => { + if (onDone) return "if(--_counter === 0) _done();\n"; + else return "--_counter;"; + }; + const doneBreak = skipDone => { + if (skipDone || !onDone) return "_counter = 0;\n"; + else return "_counter = 0;\n_done();\n"; + }; + code += "if(_counter <= 0) break;\n"; + code += onTap( + i, + () => + this.callTap(i, { + onError: error => { + let code = ""; + code += "if(_counter > 0) {\n"; + code += onError(i, error, done, doneBreak); + code += "}\n"; + return code; + }, + onResult: + onResult && + (result => { + let code = ""; + code += "if(_counter > 0) {\n"; + code += onResult(i, result, done, doneBreak); + code += "}\n"; + return code; + }), + onDone: + !onResult && + (() => { + return done(); + }), + rethrowIfPossible + }), + done, + doneBreak + ); + } + code += "} while(false);\n"; + return code; + } -const ArrayPushCallbackChunkFormatPlugin = __webpack_require__(18535); -const EnableChunkLoadingPlugin = __webpack_require__(61291); -const JsonpChunkLoadingRuntimeModule = __webpack_require__(84154); + args({ before, after } = {}) { + let allArgs = this._args; + if (before) allArgs = [before].concat(allArgs); + if (after) allArgs = allArgs.concat(after); + if (allArgs.length === 0) { + return ""; + } else { + return allArgs.join(", "); + } + } -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../Compiler")} Compiler */ + getTapFn(idx) { + return `_x[${idx}]`; + } -class JsonpTemplatePlugin { - /** - * @deprecated use JsonpChunkLoadingRuntimeModule.getCompilationHooks instead - * @param {Compilation} compilation the compilation - * @returns {JsonpChunkLoadingRuntimeModule.JsonpCompilationPluginHooks} hooks - */ - static getCompilationHooks(compilation) { - return JsonpChunkLoadingRuntimeModule.getCompilationHooks(compilation); + getTap(idx) { + return `_taps[${idx}]`; } - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.options.output.chunkLoading = "jsonp"; - new ArrayPushCallbackChunkFormatPlugin().apply(compiler); - new EnableChunkLoadingPlugin("jsonp").apply(compiler); + getInterceptor(idx) { + return `_interceptors[${idx}]`; } } -module.exports = JsonpTemplatePlugin; +module.exports = HookCodeFactory; /***/ }), -/***/ 36243: +/***/ 5504: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -140109,176 +140483,66 @@ module.exports = JsonpTemplatePlugin; */ - const util = __webpack_require__(73837); -const webpackOptionsSchemaCheck = __webpack_require__(10382); -const webpackOptionsSchema = __webpack_require__(73342); -const Compiler = __webpack_require__(70845); -const MultiCompiler = __webpack_require__(33370); -const WebpackOptionsApply = __webpack_require__(88422); -const { - applyWebpackOptionsDefaults, - applyWebpackOptionsBaseDefaults -} = __webpack_require__(92988); -const { getNormalizedWebpackOptions } = __webpack_require__(26693); -const NodeEnvironmentPlugin = __webpack_require__(7553); -const memoize = __webpack_require__(78676); - -/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ -/** @typedef {import("./Compiler").WatchOptions} WatchOptions */ -/** @typedef {import("./MultiCompiler").MultiCompilerOptions} MultiCompilerOptions */ -/** @typedef {import("./MultiStats")} MultiStats */ -/** @typedef {import("./Stats")} Stats */ -const getValidateSchema = memoize(() => __webpack_require__(12047)); +const defaultFactory = (key, hook) => hook; -/** - * @template T - * @callback Callback - * @param {Error=} err - * @param {T=} stats - * @returns {void} - */ +class HookMap { + constructor(factory, name = undefined) { + this._map = new Map(); + this.name = name; + this._factory = factory; + this._interceptors = []; + } -/** - * @param {ReadonlyArray} childOptions options array - * @param {MultiCompilerOptions} options options - * @returns {MultiCompiler} a multi-compiler - */ -const createMultiCompiler = (childOptions, options) => { - const compilers = childOptions.map(options => createCompiler(options)); - const compiler = new MultiCompiler(compilers, options); - for (const childCompiler of compilers) { - if (childCompiler.options.dependencies) { - compiler.setDependencies( - childCompiler, - childCompiler.options.dependencies - ); - } + get(key) { + return this._map.get(key); } - return compiler; -}; -/** - * @param {WebpackOptions} rawOptions options object - * @returns {Compiler} a compiler - */ -const createCompiler = rawOptions => { - const options = getNormalizedWebpackOptions(rawOptions); - applyWebpackOptionsBaseDefaults(options); - const compiler = new Compiler(options.context, options); - new NodeEnvironmentPlugin({ - infrastructureLogging: options.infrastructureLogging - }).apply(compiler); - if (Array.isArray(options.plugins)) { - for (const plugin of options.plugins) { - if (typeof plugin === "function") { - plugin.call(compiler, compiler); - } else { - plugin.apply(compiler); - } + for(key) { + const hook = this.get(key); + if (hook !== undefined) { + return hook; + } + let newHook = this._factory(key); + const interceptors = this._interceptors; + for (let i = 0; i < interceptors.length; i++) { + newHook = interceptors[i].factory(key, newHook); } + this._map.set(key, newHook); + return newHook; } - applyWebpackOptionsDefaults(options); - compiler.hooks.environment.call(); - compiler.hooks.afterEnvironment.call(); - new WebpackOptionsApply().process(options, compiler); - compiler.hooks.initialize.call(); - return compiler; -}; -/** - * @callback WebpackFunctionSingle - * @param {WebpackOptions} options options object - * @param {Callback=} callback callback - * @returns {Compiler} the compiler object - */ + intercept(interceptor) { + this._interceptors.push( + Object.assign( + { + factory: defaultFactory + }, + interceptor + ) + ); + } +} -/** - * @callback WebpackFunctionMulti - * @param {ReadonlyArray & MultiCompilerOptions} options options objects - * @param {Callback=} callback callback - * @returns {MultiCompiler} the multi compiler object - */ +HookMap.prototype.tap = util.deprecate(function(key, options, fn) { + return this.for(key).tap(options, fn); +}, "HookMap#tap(key,…) is deprecated. Use HookMap#for(key).tap(…) instead."); -const asArray = options => - Array.isArray(options) ? Array.from(options) : [options]; +HookMap.prototype.tapAsync = util.deprecate(function(key, options, fn) { + return this.for(key).tapAsync(options, fn); +}, "HookMap#tapAsync(key,…) is deprecated. Use HookMap#for(key).tapAsync(…) instead."); -const webpack = /** @type {WebpackFunctionSingle & WebpackFunctionMulti} */ ( - /** - * @param {WebpackOptions | (ReadonlyArray & MultiCompilerOptions)} options options - * @param {Callback & Callback=} callback callback - * @returns {Compiler | MultiCompiler} - */ - (options, callback) => { - const create = () => { - if (!asArray(options).every(webpackOptionsSchemaCheck)) { - getValidateSchema()(webpackOptionsSchema, options); - util.deprecate( - () => {}, - "webpack bug: Pre-compiled schema reports error while real schema is happy. This has performance drawbacks.", - "DEP_WEBPACK_PRE_COMPILED_SCHEMA_INVALID" - )(); - } - /** @type {MultiCompiler|Compiler} */ - let compiler; - let watch = false; - /** @type {WatchOptions|WatchOptions[]} */ - let watchOptions; - if (Array.isArray(options)) { - /** @type {MultiCompiler} */ - compiler = createMultiCompiler( - options, - /** @type {MultiCompilerOptions} */ (options) - ); - watch = options.some(options => options.watch); - watchOptions = options.map(options => options.watchOptions || {}); - } else { - const webpackOptions = /** @type {WebpackOptions} */ (options); - /** @type {Compiler} */ - compiler = createCompiler(webpackOptions); - watch = webpackOptions.watch; - watchOptions = webpackOptions.watchOptions || {}; - } - return { compiler, watch, watchOptions }; - }; - if (callback) { - try { - const { compiler, watch, watchOptions } = create(); - if (watch) { - compiler.watch(watchOptions, callback); - } else { - compiler.run((err, stats) => { - compiler.close(err2 => { - callback(err || err2, stats); - }); - }); - } - return compiler; - } catch (err) { - process.nextTick(() => callback(err)); - return null; - } - } else { - const { compiler, watch } = create(); - if (watch) { - util.deprecate( - () => {}, - "A 'callback' argument needs to be provided to the 'webpack(options, callback)' function when the 'watch' option is set. There is no way to handle the 'watch' option without a callback.", - "DEP_WEBPACK_WATCH_WITHOUT_CALLBACK" - )(); - } - return compiler; - } - } -); +HookMap.prototype.tapPromise = util.deprecate(function(key, options, fn) { + return this.for(key).tapPromise(options, fn); +}, "HookMap#tapPromise(key,…) is deprecated. Use HookMap#for(key).tapPromise(…) instead."); -module.exports = webpack; +module.exports = HookMap; /***/ }), -/***/ 54182: +/***/ 1081: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -140288,335 +140552,118 @@ module.exports = webpack; */ +const Hook = __webpack_require__(72258); -const RuntimeGlobals = __webpack_require__(16475); -const StartupChunkDependenciesPlugin = __webpack_require__(22339); -const ImportScriptsChunkLoadingRuntimeModule = __webpack_require__(96952); +class MultiHook { + constructor(hooks, name = undefined) { + this.hooks = hooks; + this.name = name; + } -/** @typedef {import("../Compiler")} Compiler */ + tap(options, fn) { + for (const hook of this.hooks) { + hook.tap(options, fn); + } + } -class ImportScriptsChunkLoadingPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - new StartupChunkDependenciesPlugin({ - chunkLoading: "import-scripts", - asyncChunkLoading: true - }).apply(compiler); - compiler.hooks.thisCompilation.tap( - "ImportScriptsChunkLoadingPlugin", - compilation => { - const globalChunkLoading = compilation.outputOptions.chunkLoading; - const isEnabledForChunk = chunk => { - const options = chunk.getEntryOptions(); - const chunkLoading = - options && options.chunkLoading !== undefined - ? options.chunkLoading - : globalChunkLoading; - return chunkLoading === "import-scripts"; - }; - const onceForChunkSet = new WeakSet(); - const handler = (chunk, set) => { - if (onceForChunkSet.has(chunk)) return; - onceForChunkSet.add(chunk); - if (!isEnabledForChunk(chunk)) return; - const withCreateScriptUrl = !!compilation.outputOptions.trustedTypes; - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - set.add(RuntimeGlobals.hasOwnProperty); - if (withCreateScriptUrl) { - set.add(RuntimeGlobals.createScriptUrl); - } - compilation.addRuntimeModule( - chunk, - new ImportScriptsChunkLoadingRuntimeModule(set, withCreateScriptUrl) - ); - }; - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("ImportScriptsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap("ImportScriptsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadManifest) - .tap("ImportScriptsChunkLoadingPlugin", handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.baseURI) - .tap("ImportScriptsChunkLoadingPlugin", handler); + tapAsync(options, fn) { + for (const hook of this.hooks) { + hook.tapAsync(options, fn); + } + } - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap("ImportScriptsChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.getChunkScriptFilename); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap("ImportScriptsChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.getChunkUpdateScriptFilename); - set.add(RuntimeGlobals.moduleCache); - set.add(RuntimeGlobals.hmrModuleData); - set.add(RuntimeGlobals.moduleFactoriesAddOnly); - }); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadManifest) - .tap("ImportScriptsChunkLoadingPlugin", (chunk, set) => { - if (!isEnabledForChunk(chunk)) return; - set.add(RuntimeGlobals.publicPath); - set.add(RuntimeGlobals.getUpdateManifestFilename); - }); - } + tapPromise(options, fn) { + for (const hook of this.hooks) { + hook.tapPromise(options, fn); + } + } + + isUsed() { + for (const hook of this.hooks) { + if (hook.isUsed()) return true; + } + return false; + } + + intercept(interceptor) { + for (const hook of this.hooks) { + hook.intercept(interceptor); + } + } + + withOptions(options) { + return new MultiHook( + this.hooks.map(h => h.withOptions(options)), + this.name ); } } -module.exports = ImportScriptsChunkLoadingPlugin; + +module.exports = MultiHook; /***/ }), -/***/ 96952: +/***/ 79106: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ +const Hook = __webpack_require__(72258); +const HookCodeFactory = __webpack_require__(177); -const RuntimeGlobals = __webpack_require__(16475); -const RuntimeModule = __webpack_require__(16963); -const Template = __webpack_require__(39722); -const { - getChunkFilenameTemplate, - chunkHasJs -} = __webpack_require__(89464); -const { getInitialChunkIds } = __webpack_require__(98124); -const compileBooleanMatcher = __webpack_require__(29404); -const { getUndoPath } = __webpack_require__(82186); - -class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { - constructor(runtimeRequirements, withCreateScriptUrl) { - super("importScripts chunk loading", RuntimeModule.STAGE_ATTACH); - this.runtimeRequirements = runtimeRequirements; - this._withCreateScriptUrl = withCreateScriptUrl; +class SyncBailHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, resultReturns, onDone, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onResult: (i, result, next) => + `if(${result} !== undefined) {\n${onResult( + result + )};\n} else {\n${next()}}\n`, + resultReturns, + onDone, + rethrowIfPossible + }); } +} - /** - * @returns {string} runtime code - */ - generate() { - const { - chunk, - chunkGraph, - compilation: { - runtimeTemplate, - outputOptions: { chunkLoadingGlobal, hotUpdateGlobal } - }, - _withCreateScriptUrl: withCreateScriptUrl - } = this; - const globalObject = runtimeTemplate.globalObject; - const fn = RuntimeGlobals.ensureChunkHandlers; - const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); - const withLoading = this.runtimeRequirements.has( - RuntimeGlobals.ensureChunkHandlers - ); - const withHmr = this.runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - const withHmrManifest = this.runtimeRequirements.has( - RuntimeGlobals.hmrDownloadManifest - ); - const chunkLoadingGlobalExpr = `${globalObject}[${JSON.stringify( - chunkLoadingGlobal - )}]`; - const hasJsMatcher = compileBooleanMatcher( - chunkGraph.getChunkConditionMap(chunk, chunkHasJs) - ); - const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs); +const factory = new SyncBailHookCodeFactory(); - const outputName = this.compilation.getPath( - getChunkFilenameTemplate(chunk, this.compilation.outputOptions), - { - chunk, - contentHashType: "javascript" - } - ); - const rootOutputDir = getUndoPath( - outputName, - this.compilation.outputOptions.path, - false - ); +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncBailHook"); +}; - const stateExpression = withHmr - ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_importScripts` - : undefined; +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncBailHook"); +}; - return Template.asString([ - withBaseURI - ? Template.asString([ - `${RuntimeGlobals.baseURI} = self.location + ${JSON.stringify( - rootOutputDir ? "/../" + rootOutputDir : "" - )};` - ]) - : "// no baseURI", - "", - "// object to store loaded chunks", - '// "1" means "already loaded"', - `var installedChunks = ${ - stateExpression ? `${stateExpression} = ${stateExpression} || ` : "" - }{`, - Template.indent( - Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 1`).join( - ",\n" - ) - ), - "};", - "", - withLoading - ? Template.asString([ - "// importScripts chunk loading", - `var installChunk = ${runtimeTemplate.basicFunction("data", [ - runtimeTemplate.destructureArray( - ["chunkIds", "moreModules", "runtime"], - "data" - ), - "for(var moduleId in moreModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, - Template.indent( - `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];` - ), - "}" - ]), - "}", - "if(runtime) runtime(__webpack_require__);", - "while(chunkIds.length)", - Template.indent("installedChunks[chunkIds.pop()] = 1;"), - "parentChunkLoadingFunction(data);" - ])};` - ]) - : "// no chunk install function needed", - withLoading - ? Template.asString([ - `${fn}.i = ${runtimeTemplate.basicFunction( - "chunkId, promises", - hasJsMatcher !== false - ? [ - '// "1" is the signal for "already loaded"', - "if(!installedChunks[chunkId]) {", - Template.indent([ - hasJsMatcher === true - ? "if(true) { // all chunks have JS" - : `if(${hasJsMatcher("chunkId")}) {`, - Template.indent( - `importScripts(${ - withCreateScriptUrl - ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId))` - : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId)` - });` - ), - "}" - ]), - "}" - ] - : "installedChunks[chunkId] = 1;" - )};`, - "", - `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, - "var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);", - "chunkLoadingGlobal.push = installChunk;" - ]) - : "// no chunk loading", - "", - withHmr - ? Template.asString([ - "function loadUpdateChunk(chunkId, updatedModulesList) {", - Template.indent([ - "var success = false;", - `${globalObject}[${JSON.stringify( - hotUpdateGlobal - )}] = ${runtimeTemplate.basicFunction("_, moreModules, runtime", [ - "for(var moduleId in moreModules) {", - Template.indent([ - `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, - Template.indent([ - "currentUpdate[moduleId] = moreModules[moduleId];", - "if(updatedModulesList) updatedModulesList.push(moduleId);" - ]), - "}" - ]), - "}", - "if(runtime) currentUpdateRuntime.push(runtime);", - "success = true;" - ])};`, - "// start update chunk loading", - `importScripts(${ - withCreateScriptUrl - ? `${RuntimeGlobals.createScriptUrl}(${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId))` - : `${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId)` - });`, - 'if(!success) throw new Error("Loading update chunk failed for unknown reason");' - ]), - "}", - "", - Template.getFunctionContent( - require('./JavascriptHotModuleReplacement.runtime.js') - ) - .replace(/\$key\$/g, "importScrips") - .replace(/\$installedChunks\$/g, "installedChunks") - .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") - .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) - .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) - .replace( - /\$ensureChunkHandlers\$/g, - RuntimeGlobals.ensureChunkHandlers - ) - .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) - .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) - .replace( - /\$hmrDownloadUpdateHandlers\$/g, - RuntimeGlobals.hmrDownloadUpdateHandlers - ) - .replace( - /\$hmrInvalidateModuleHandlers\$/g, - RuntimeGlobals.hmrInvalidateModuleHandlers - ) - ]) - : "// no HMR", - "", - withHmrManifest - ? Template.asString([ - `${ - RuntimeGlobals.hmrDownloadManifest - } = ${runtimeTemplate.basicFunction("", [ - 'if (typeof fetch === "undefined") throw new Error("No browser support: need fetch API");', - `return fetch(${RuntimeGlobals.publicPath} + ${ - RuntimeGlobals.getUpdateManifestFilename - }()).then(${runtimeTemplate.basicFunction("response", [ - "if(response.status === 404) return; // no update available", - 'if(!response.ok) throw new Error("Failed to fetch update manifest " + response.statusText);', - "return response.json();" - ])});` - ])};` - ]) - : "// no HMR manifest" - ]); - } +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; + +function SyncBailHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = SyncBailHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; } -module.exports = ImportScriptsChunkLoadingRuntimeModule; +SyncBailHook.prototype = null; + +module.exports = SyncBailHook; /***/ }), -/***/ 68693: +/***/ 10533: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -140626,239 +140673,192 @@ module.exports = ImportScriptsChunkLoadingRuntimeModule; */ +const Hook = __webpack_require__(72258); +const HookCodeFactory = __webpack_require__(177); -const ArrayPushCallbackChunkFormatPlugin = __webpack_require__(18535); -const EnableChunkLoadingPlugin = __webpack_require__(61291); - -/** @typedef {import("../Compiler")} Compiler */ - -class WebWorkerTemplatePlugin { - /** - * Apply the plugin - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.options.output.chunkLoading = "import-scripts"; - new ArrayPushCallbackChunkFormatPlugin().apply(compiler); - new EnableChunkLoadingPlugin("import-scripts").apply(compiler); +class SyncHookCodeFactory extends HookCodeFactory { + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); } } -module.exports = WebWorkerTemplatePlugin; +const factory = new SyncHookCodeFactory(); -/***/ }), +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncHook"); +}; -/***/ 50569: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncHook"); +}; -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; -/** - * Module exports. - */ +function SyncHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = SyncHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; +} -module.exports = __webpack_require__(58750) +SyncHook.prototype = null; + +module.exports = SyncHook; /***/ }), -/***/ 78585: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 95854: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @private - */ - -var db = __webpack_require__(50569) -var extname = (__webpack_require__(71017).extname) - -/** - * Module variables. - * @private - */ - -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i - -/** - * Module exports. - * @public - */ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -exports.charset = charset -exports.charsets = { lookup: charset } -exports.contentType = contentType -exports.extension = extension -exports.extensions = Object.create(null) -exports.lookup = lookup -exports.types = Object.create(null) -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) +const Hook = __webpack_require__(72258); +const HookCodeFactory = __webpack_require__(177); -/** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ +class SyncLoopHookCodeFactory extends HookCodeFactory { + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsLooping({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); + } +} -function charset (type) { - if (!type || typeof type !== 'string') { - return false - } +const factory = new SyncLoopHookCodeFactory(); - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - var mime = match && db[match[1].toLowerCase()] +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncLoopHook"); +}; - if (mime && mime.charset) { - return mime.charset - } +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncLoopHook"); +}; - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; - return false +function SyncLoopHook(args = [], name = undefined) { + const hook = new Hook(args, name); + hook.constructor = SyncLoopHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; } -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ - -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false - } - - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str - - if (!mime) { - return false - } +SyncLoopHook.prototype = null; - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() - } +module.exports = SyncLoopHook; - return mime -} -/** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ +/***/ }), -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } +/***/ 60176: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] - if (!exts || !exts.length) { - return false - } +const Hook = __webpack_require__(72258); +const HookCodeFactory = __webpack_require__(177); - return exts[0] +class SyncWaterfallHookCodeFactory extends HookCodeFactory { + content({ onError, onResult, resultReturns, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onResult: (i, result, next) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += `${this._args[0]} = ${result};\n`; + code += `}\n`; + code += next(); + return code; + }, + onDone: () => onResult(this._args[0]), + doneReturns: resultReturns, + rethrowIfPossible + }); + } } -/** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} - */ +const factory = new SyncWaterfallHookCodeFactory(); -function lookup (path) { - if (!path || typeof path !== 'string') { - return false - } +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncWaterfallHook"); +}; - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncWaterfallHook"); +}; - if (!extension) { - return false - } +const COMPILE = function(options) { + factory.setup(this, options); + return factory.create(options); +}; - return exports.types[extension] || false +function SyncWaterfallHook(args = [], name = undefined) { + if (args.length < 1) + throw new Error("Waterfall hooks must have at least one argument"); + const hook = new Hook(args, name); + hook.constructor = SyncWaterfallHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return hook; } -/** - * Populate the extensions and types maps. - * @private - */ - -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] +SyncWaterfallHook.prototype = null; - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions +module.exports = SyncWaterfallHook; - if (!exts || !exts.length) { - return - } - // mime -> extensions - extensions[type] = exts +/***/ }), - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] +/***/ 6967: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } - // set the extension -> mime - types[extension] = type - } - }) -} +exports.__esModule = true; +exports.SyncHook = __webpack_require__(10533); +exports.SyncBailHook = __webpack_require__(79106); +exports.SyncWaterfallHook = __webpack_require__(60176); +exports.SyncLoopHook = __webpack_require__(95854); +exports.AsyncParallelHook = __webpack_require__(45874); +exports.AsyncParallelBailHook = __webpack_require__(76297); +exports.AsyncSeriesHook = __webpack_require__(40436); +exports.AsyncSeriesBailHook = __webpack_require__(13633); +exports.AsyncSeriesLoopHook = __webpack_require__(34656); +exports.AsyncSeriesWaterfallHook = __webpack_require__(47794); +exports.HookMap = __webpack_require__(5504); +exports.MultiHook = __webpack_require__(1081); /***/ }), From aa6ffbc77ee5835159fcd3bf844ac954dac3cd74 Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Thu, 27 Jan 2022 08:44:37 -0600 Subject: [PATCH 15/15] re-add updated acorn version --- packages/next/compiled/acorn/LICENSE | 2 +- packages/next/compiled/acorn/acorn.js | 2 +- packages/next/compiled/webpack/bundle5.js | 600 +++++++++++----------- packages/next/package.json | 1 + yarn.lock | 10 +- 5 files changed, 308 insertions(+), 307 deletions(-) diff --git a/packages/next/compiled/acorn/LICENSE b/packages/next/compiled/acorn/LICENSE index cc5272c966db..d6be6db2cfff 100644 --- a/packages/next/compiled/acorn/LICENSE +++ b/packages/next/compiled/acorn/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (C) 2012-2018 by various contributors (see AUTHORS) +Copyright (C) 2012-2020 by various contributors (see AUTHORS) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/packages/next/compiled/acorn/acorn.js b/packages/next/compiled/acorn/acorn.js index 316b82a62aa5..1b37fdba121b 100644 --- a/packages/next/compiled/acorn/acorn.js +++ b/packages/next/compiled/acorn/acorn.js @@ -1 +1 @@ -(()=>{var e={108:function(e,t){(function(e,i){true?i(t):0})(this,(function(e){"use strict";var t={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"};var i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var s={5:i,"5module":i+" export import",6:i+" const class extends export import super"};var r=/^in(stanceof)?$/;var a="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-鿼ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var n="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var o=new RegExp("["+a+"]");var h=new RegExp("["+a+n+"]");a=n=null;var p=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];var c=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];function isInAstralSet(e,t){var i=65536;for(var s=0;se){return false}i+=t[s+1];if(i>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&o.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,p)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&h.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,p)||isInAstralSet(e,c)}var u=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new u(e,{beforeExpr:true,binop:t})}var l={beforeExpr:true},f={startsExpr:true};var d={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return d[e]=new u(e,t)}var m={num:new u("num",f),regexp:new u("regexp",f),string:new u("string",f),name:new u("name",f),eof:new u("eof"),bracketL:new u("[",{beforeExpr:true,startsExpr:true}),bracketR:new u("]"),braceL:new u("{",{beforeExpr:true,startsExpr:true}),braceR:new u("}"),parenL:new u("(",{beforeExpr:true,startsExpr:true}),parenR:new u(")"),comma:new u(",",l),semi:new u(";",l),colon:new u(":",l),dot:new u("."),question:new u("?",l),questionDot:new u("?."),arrow:new u("=>",l),template:new u("template"),invalidTemplate:new u("invalidTemplate"),ellipsis:new u("...",l),backQuote:new u("`",f),dollarBraceL:new u("${",{beforeExpr:true,startsExpr:true}),eq:new u("=",{beforeExpr:true,isAssign:true}),assign:new u("_=",{beforeExpr:true,isAssign:true}),incDec:new u("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new u("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new u("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new u("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",l),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",l),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",l),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",f),_if:kw("if"),_return:kw("return",l),_switch:kw("switch"),_throw:kw("throw",l),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",f),_super:kw("super",f),_class:kw("class",f),_extends:kw("extends",l),_export:kw("export"),_import:kw("import",f),_null:kw("null",f),_true:kw("true",f),_false:kw("false",f),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var x=/\r\n?|\n|\u2028|\u2029/;var g=new RegExp(x.source,"g");function isNewLine(e,t){return e===10||e===13||!t&&(e===8232||e===8233)}var v=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var y=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var k=Object.prototype;var b=k.hasOwnProperty;var _=k.toString;function has(e,t){return b.call(e,t)}var w=Array.isArray||function(e){return _.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var S=function Position(e,t){this.line=e;this.column=t};S.prototype.offset=function offset(e){return new S(this.line,this.column+e)};var C=function SourceLocation(e,t,i){this.start=t;this.end=i;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var i=1,s=0;;){g.lastIndex=s;var r=g.exec(e);if(r&&r.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(w(t.onToken)){var s=t.onToken;t.onToken=function(e){return s.push(e)}}if(w(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(i,s,r,a,n,o){var h={type:i?"Block":"Line",value:s,start:r,end:a};if(e.locations){h.loc=new C(this,n,o)}if(e.ranges){h.range=[r,a]}t.push(h)}}var I=1,A=2,P=I|A,T=4,N=8,L=16,V=32,R=64,D=128;function functionFlags(e,t){return A|(e?T:0)|(t?N:0)}var O=0,B=1,M=2,U=3,F=4,q=5;var H=function Parser(e,i,r){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(s[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var a="";if(e.allowReserved!==true){for(var n=e.ecmaVersion;;n--){if(a=t[n]){break}}if(e.sourceType==="module"){a+=" await"}}this.reservedWords=wordsRegexp(a);var o=(a?a+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(o);this.reservedWordsStrictBind=wordsRegexp(o+" "+t.strictBind);this.input=String(i);this.containsEsc=false;if(r){this.pos=r;this.lineStart=this.input.lastIndexOf("\n",r-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(x).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=m.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(I);this.regexpState=null};var G={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true}};H.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};G.inFunction.get=function(){return(this.currentVarScope().flags&A)>0};G.inGenerator.get=function(){return(this.currentVarScope().flags&N)>0};G.inAsync.get=function(){return(this.currentVarScope().flags&T)>0};G.allowSuper.get=function(){return(this.currentThisScope().flags&R)>0};G.allowDirectSuper.get=function(){return(this.currentThisScope().flags&D)>0};G.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};H.prototype.inNonArrowFunction=function inNonArrowFunction(){return(this.currentThisScope().flags&A)>0};H.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var i=this;for(var s=0;s=,?^&]/.test(r)||r==="!"&&this.input.charAt(s+1)==="=")}e+=t[0].length;y.lastIndex=e;e+=y.exec(this.input)[0].length;if(this.input[e]===";"){e++}}};W.eat=function(e){if(this.type===e){this.next();return true}else{return false}};W.isContextual=function(e){return this.type===m.name&&this.value===e&&!this.containsEsc};W.eatContextual=function(e){if(!this.isContextual(e)){return false}this.next();return true};W.expectContextual=function(e){if(!this.eatContextual(e)){this.unexpected()}};W.canInsertSemicolon=function(){return this.type===m.eof||this.type===m.braceR||x.test(this.input.slice(this.lastTokEnd,this.start))};W.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};W.semicolon=function(){if(!this.eat(m.semi)&&!this.insertSemicolon()){this.unexpected()}};W.afterTrailingComma=function(e,t){if(this.type===e){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!t){this.next()}return true}};W.expect=function(e){this.eat(e)||this.unexpected()};W.unexpected=function(e){this.raise(e!=null?e:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}W.checkPatternErrors=function(e,t){if(!e){return}if(e.trailingComma>-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var i=t?e.parenthesizedAssign:e.parenthesizedBind;if(i>-1){this.raiseRecoverable(i,"Parenthesized pattern")}};W.checkExpressionErrors=function(e,t){if(!e){return false}var i=e.shorthandAssign;var s=e.doubleProto;if(!t){return i>=0||s>=0}if(i>=0){this.raise(i,"Shorthand property assignments are valid only in destructuring patterns")}if(s>=0){this.raiseRecoverable(s,"Redefinition of __proto__ property")}};W.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(r,false,!e);case m._class:if(e){this.unexpected()}return this.parseClass(r,true);case m._if:return this.parseIfStatement(r);case m._return:return this.parseReturnStatement(r);case m._switch:return this.parseSwitchStatement(r);case m._throw:return this.parseThrowStatement(r);case m._try:return this.parseTryStatement(r);case m._const:case m._var:a=a||this.value;if(e&&a!=="var"){this.unexpected()}return this.parseVarStatement(r,a);case m._while:return this.parseWhileStatement(r);case m._with:return this.parseWithStatement(r);case m.braceL:return this.parseBlock(true,r);case m.semi:return this.parseEmptyStatement(r);case m._export:case m._import:if(this.options.ecmaVersion>10&&s===m._import){y.lastIndex=this.pos;var n=y.exec(this.input);var o=this.pos+n[0].length,h=this.input.charCodeAt(o);if(h===40||h===46){return this.parseExpressionStatement(r,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return s===m._import?this.parseImport(r):this.parseExport(r,i);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(r,true,!e)}var p=this.value,c=this.parseExpression();if(s===m.name&&c.type==="Identifier"&&this.eat(m.colon)){return this.parseLabeledStatement(r,p,c,e)}else{return this.parseExpressionStatement(r,c)}}};z.parseBreakContinueStatement=function(e,t){var i=t==="break";this.next();if(this.eat(m.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==m.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var s=0;for(;s=6){this.eat(m.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};z.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(Q);this.enterScope(0);this.expect(m.parenL);if(this.type===m.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var i=this.isLet();if(this.type===m._var||this.type===m._const||i){var s=this.startNode(),r=i?"let":this.value;this.next();this.parseVar(s,true,r);this.finishNode(s,"VariableDeclaration");if((this.type===m._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&s.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===m._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,s)}if(t>-1){this.unexpected(t)}return this.parseFor(e,s)}var a=new DestructuringErrors;var n=this.parseExpression(true,a);if(this.type===m._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===m._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}this.toAssignable(n,false,a);this.checkLVal(n);return this.parseForIn(e,n)}else{this.checkExpressionErrors(a,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,n)};z.parseFunctionStatement=function(e,t,i){this.next();return this.parseFunction(e,Y|(i?0:Z),false,t)};z.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(m._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};z.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(m.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};z.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(m.braceL);this.labels.push(K);this.enterScope(0);var t;for(var i=false;this.type!==m.braceR;){if(this.type===m._case||this.type===m._default){var s=this.type===m._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(s){t.test=this.parseExpression()}else{if(i){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}i=true;t.test=null}this.expect(m.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};z.parseThrowStatement=function(e){this.next();if(x.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var X=[];z.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===m._catch){var t=this.startNode();this.next();if(this.eat(m.parenL)){t.param=this.parseBindingAtom();var i=t.param.type==="Identifier";this.enterScope(i?V:0);this.checkLVal(t.param,i?F:M);this.expect(m.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(m._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};z.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};z.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(Q);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};z.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};z.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};z.parseLabeledStatement=function(e,t,i,s){for(var r=0,a=this.labels;r=0;h--){var p=this.labels[h];if(p.statementStart===e.start){p.statementStart=this.start;p.kind=o}else{break}}this.labels.push({name:t,kind:o,statementStart:this.start});e.body=this.parseStatement(s?s.indexOf("label")===-1?s+"label":s:"label");this.labels.pop();e.label=i;return this.finishNode(e,"LabeledStatement")};z.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};z.parseBlock=function(e,t,i){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(m.braceL);if(e){this.enterScope(0)}while(this.type!==m.braceR){var s=this.parseStatement(null);t.body.push(s)}if(i){this.strict=false}this.next();if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};z.parseFor=function(e,t){e.init=t;this.expect(m.semi);e.test=this.type===m.semi?null:this.parseExpression();this.expect(m.semi);e.update=this.type===m.parenR?null:this.parseExpression();this.expect(m.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};z.parseForIn=function(e,t){var i=this.type===m._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!i||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(i?"for-in":"for-of")+" loop variable declaration may not have an initializer")}else if(t.type==="AssignmentPattern"){this.raise(t.start,"Invalid left-hand side in for-loop")}e.left=t;e.right=i?this.parseExpression():this.parseMaybeAssign();this.expect(m.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,i?"ForInStatement":"ForOfStatement")};z.parseVar=function(e,t,i){e.declarations=[];e.kind=i;for(;;){var s=this.startNode();this.parseVarId(s,i);if(this.eat(m.eq)){s.init=this.parseMaybeAssign(t)}else if(i==="const"&&!(this.type===m._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(s.id.type!=="Identifier"&&!(t&&(this.type===m._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{s.init=null}e.declarations.push(this.finishNode(s,"VariableDeclarator"));if(!this.eat(m.comma)){break}}return e};z.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLVal(e.id,t==="var"?B:M,false)};var Y=1,Z=2,$=4;z.parseFunction=function(e,t,i,s){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!s){if(this.type===m.star&&t&Z){this.unexpected()}e.generator=this.eat(m.star)}if(this.options.ecmaVersion>=8){e.async=!!s}if(t&Y){e.id=t&$&&this.type!==m.name?null:this.parseIdent();if(e.id&&!(t&Z)){this.checkLVal(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?B:M:U)}}var r=this.yieldPos,a=this.awaitPos,n=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&Y)){e.id=this.type===m.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,i,false);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=n;return this.finishNode(e,t&Y?"FunctionDeclaration":"FunctionExpression")};z.parseFunctionParams=function(e){this.expect(m.parenL);e.params=this.parseBindingList(m.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};z.parseClass=function(e,t){this.next();var i=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var s=this.startNode();var r=false;s.body=[];this.expect(m.braceL);while(this.type!==m.braceR){var a=this.parseClassElement(e.superClass!==null);if(a){s.body.push(a);if(a.type==="MethodDefinition"&&a.kind==="constructor"){if(r){this.raise(a.start,"Duplicate constructor in the same class")}r=true}}}this.strict=i;this.next();e.body=this.finishNode(s,"ClassBody");return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};z.parseClassElement=function(e){var t=this;if(this.eat(m.semi)){return null}var i=this.startNode();var tryContextual=function(e,s){if(s===void 0)s=false;var r=t.start,a=t.startLoc;if(!t.eatContextual(e)){return false}if(t.type!==m.parenL&&(!s||!t.canInsertSemicolon())){return true}if(i.key){t.unexpected()}i.computed=false;i.key=t.startNodeAt(r,a);i.key.name=e;t.finishNode(i.key,"Identifier");return false};i.kind="method";i.static=tryContextual("static");var s=this.eat(m.star);var r=false;if(!s){if(this.options.ecmaVersion>=8&&tryContextual("async",true)){r=true;s=this.options.ecmaVersion>=9&&this.eat(m.star)}else if(tryContextual("get")){i.kind="get"}else if(tryContextual("set")){i.kind="set"}}if(!i.key){this.parsePropertyName(i)}var a=i.key;var n=false;if(!i.computed&&!i.static&&(a.type==="Identifier"&&a.name==="constructor"||a.type==="Literal"&&a.value==="constructor")){if(i.kind!=="method"){this.raise(a.start,"Constructor can't have get/set modifier")}if(s){this.raise(a.start,"Constructor can't be a generator")}if(r){this.raise(a.start,"Constructor can't be an async method")}i.kind="constructor";n=e}else if(i.static&&a.type==="Identifier"&&a.name==="prototype"){this.raise(a.start,"Classes may not have a static property named prototype")}this.parseClassMethod(i,s,r,n);if(i.kind==="get"&&i.value.params.length!==0){this.raiseRecoverable(i.value.start,"getter should have no params")}if(i.kind==="set"&&i.value.params.length!==1){this.raiseRecoverable(i.value.start,"setter should have exactly one param")}if(i.kind==="set"&&i.value.params[0].type==="RestElement"){this.raiseRecoverable(i.value.params[0].start,"Setter cannot use rest params")}return i};z.parseClassMethod=function(e,t,i,s){e.value=this.parseMethod(t,i,s);return this.finishNode(e,"MethodDefinition")};z.parseClassId=function(e,t){if(this.type===m.name){e.id=this.parseIdent();if(t){this.checkLVal(e.id,M,false)}}else{if(t===true){this.unexpected()}e.id=null}};z.parseClassSuper=function(e){e.superClass=this.eat(m._extends)?this.parseExprSubscripts():null};z.parseExport=function(e,t){this.next();if(this.eat(m.star)){if(this.options.ecmaVersion>=11){if(this.eatContextual("as")){e.exported=this.parseIdent(true);this.checkExport(t,e.exported.name,this.lastTokStart)}else{e.exported=null}}this.expectContextual("from");if(this.type!==m.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(m._default)){this.checkExport(t,"default",this.lastTokStart);var i;if(this.type===m._function||(i=this.isAsyncFunction())){var s=this.startNode();this.next();if(i){this.next()}e.declaration=this.parseFunction(s,Y|$,false,i)}else if(this.type===m._class){var r=this.startNode();e.declaration=this.parseClass(r,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==m.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var a=0,n=e.specifiers;a=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(i){this.checkPatternErrors(i,true)}for(var s=0,r=e.properties;s=8&&!a&&n.name==="async"&&!this.canInsertSemicolon()&&this.eat(m._function)){return this.parseFunction(this.startNodeAt(s,r),0,false,true)}if(i&&!this.canInsertSemicolon()){if(this.eat(m.arrow)){return this.parseArrowExpression(this.startNodeAt(s,r),[n],false)}if(this.options.ecmaVersion>=8&&n.name==="async"&&this.type===m.name&&!a){n=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(m.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(s,r),[n],true)}}return n;case m.regexp:var o=this.value;t=this.parseLiteral(o.value);t.regex={pattern:o.pattern,flags:o.flags};return t;case m.num:case m.string:return this.parseLiteral(this.value);case m._null:case m._true:case m._false:t=this.startNode();t.value=this.type===m._null?null:this.type===m._true;t.raw=this.type.keyword;this.next();return this.finishNode(t,"Literal");case m.parenL:var h=this.start,p=this.parseParenAndDistinguishExpression(i);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(p)){e.parenthesizedAssign=h}if(e.parenthesizedBind<0){e.parenthesizedBind=h}}return p;case m.bracketL:t=this.startNode();this.next();t.elements=this.parseExprList(m.bracketR,true,true,e);return this.finishNode(t,"ArrayExpression");case m.braceL:return this.parseObj(false,e);case m._function:t=this.startNode();this.next();return this.parseFunction(t,0);case m._class:return this.parseClass(this.startNode(),false);case m._new:return this.parseNew();case m.backQuote:return this.parseTemplate();case m._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};ee.parseExprImport=function(){var e=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var t=this.parseIdent(true);switch(this.type){case m.parenL:return this.parseDynamicImport(e);case m.dot:e.meta=t;return this.parseImportMeta(e);default:this.unexpected()}};ee.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(m.parenR)){var t=this.start;if(this.eat(m.comma)&&this.eat(m.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};ee.parseImportMeta=function(e){this.next();var t=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="meta"){this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'")}if(t){this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"){this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(e,"MetaProperty")};ee.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(t,"Literal")};ee.parseParenExpression=function(){this.expect(m.parenL);var e=this.parseExpression();this.expect(m.parenR);return e};ee.parseParenAndDistinguishExpression=function(e){var t=this.start,i=this.startLoc,s,r=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a=this.start,n=this.startLoc;var o=[],h=true,p=false;var c=new DestructuringErrors,u=this.yieldPos,l=this.awaitPos,f;this.yieldPos=0;this.awaitPos=0;while(this.type!==m.parenR){h?h=false:this.expect(m.comma);if(r&&this.afterTrailingComma(m.parenR,true)){p=true;break}else if(this.type===m.ellipsis){f=this.start;o.push(this.parseParenItem(this.parseRestBinding()));if(this.type===m.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{o.push(this.parseMaybeAssign(false,c,this.parseParenItem))}}var d=this.start,x=this.startLoc;this.expect(m.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(m.arrow)){this.checkPatternErrors(c,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=u;this.awaitPos=l;return this.parseParenArrowList(t,i,o)}if(!o.length||p){this.unexpected(this.lastTokStart)}if(f){this.unexpected(f)}this.checkExpressionErrors(c,true);this.yieldPos=u||this.yieldPos;this.awaitPos=l||this.awaitPos;if(o.length>1){s=this.startNodeAt(a,n);s.expressions=o;this.finishNodeAt(s,"SequenceExpression",d,x)}else{s=o[0]}}else{s=this.parseParenExpression()}if(this.options.preserveParens){var g=this.startNodeAt(t,i);g.expression=s;return this.finishNode(g,"ParenthesizedExpression")}else{return s}};ee.parseParenItem=function(e){return e};ee.parseParenArrowList=function(e,t,i){return this.parseArrowExpression(this.startNodeAt(e,t),i)};var te=[];ee.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(m.dot)){e.meta=t;var i=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"){this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'")}if(i){this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters")}if(!this.inNonArrowFunction()){this.raiseRecoverable(e.start,"'new.target' can only be used in functions")}return this.finishNode(e,"MetaProperty")}var s=this.start,r=this.startLoc,a=this.type===m._import;e.callee=this.parseSubscripts(this.parseExprAtom(),s,r,true);if(a&&e.callee.type==="ImportExpression"){this.raise(s,"Cannot use new with import()")}if(this.eat(m.parenL)){e.arguments=this.parseExprList(m.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=te}return this.finishNode(e,"NewExpression")};ee.parseTemplateElement=function(e){var t=e.isTagged;var i=this.startNode();if(this.type===m.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}i.value={raw:this.value,cooked:null}}else{i.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();i.tail=this.type===m.backQuote;return this.finishNode(i,"TemplateElement")};ee.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var i=this.startNode();this.next();i.expressions=[];var s=this.parseTemplateElement({isTagged:t});i.quasis=[s];while(!s.tail){if(this.type===m.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(m.dollarBraceL);i.expressions.push(this.parseExpression());this.expect(m.braceR);i.quasis.push(s=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(i,"TemplateLiteral")};ee.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===m.name||this.type===m.num||this.type===m.string||this.type===m.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===m.star)&&!x.test(this.input.slice(this.lastTokEnd,this.start))};ee.parseObj=function(e,t){var i=this.startNode(),s=true,r={};i.properties=[];this.next();while(!this.eat(m.braceR)){if(!s){this.expect(m.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(m.braceR)){break}}else{s=false}var a=this.parseProperty(e,t);if(!e){this.checkPropClash(a,r,t)}i.properties.push(a)}return this.finishNode(i,e?"ObjectPattern":"ObjectExpression")};ee.parseProperty=function(e,t){var i=this.startNode(),s,r,a,n;if(this.options.ecmaVersion>=9&&this.eat(m.ellipsis)){if(e){i.argument=this.parseIdent(false);if(this.type===m.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(i,"RestElement")}if(this.type===m.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}i.argument=this.parseMaybeAssign(false,t);if(this.type===m.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(i,"SpreadElement")}if(this.options.ecmaVersion>=6){i.method=false;i.shorthand=false;if(e||t){a=this.start;n=this.startLoc}if(!e){s=this.eat(m.star)}}var o=this.containsEsc;this.parsePropertyName(i);if(!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(i)){r=true;s=this.options.ecmaVersion>=9&&this.eat(m.star);this.parsePropertyName(i,t)}else{r=false}this.parsePropertyValue(i,e,s,r,a,n,t,o);return this.finishNode(i,"Property")};ee.parsePropertyValue=function(e,t,i,s,r,a,n,o){if((i||s)&&this.type===m.colon){this.unexpected()}if(this.eat(m.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,n);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===m.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(i,s)}else if(!t&&!o&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==m.comma&&this.type!==m.braceR&&this.type!==m.eq)){if(i||s){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var h=e.kind==="get"?0:1;if(e.value.params.length!==h){var p=e.value.start;if(e.kind==="get"){this.raiseRecoverable(p,"getter should have no params")}else{this.raiseRecoverable(p,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(i||s){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=r}e.kind="init";if(t){e.value=this.parseMaybeDefault(r,a,e.key)}else if(this.type===m.eq&&n){if(n.shorthandAssign<0){n.shorthandAssign=this.start}e.value=this.parseMaybeDefault(r,a,e.key)}else{e.value=e.key}e.shorthand=true}else{this.unexpected()}};ee.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(m.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(m.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===m.num||this.type===m.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ee.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};ee.parseMethod=function(e,t,i){var s=this.startNode(),r=this.yieldPos,a=this.awaitPos,n=this.awaitIdentPos;this.initFunction(s);if(this.options.ecmaVersion>=6){s.generator=e}if(this.options.ecmaVersion>=8){s.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,s.generator)|R|(i?D:0));this.expect(m.parenL);s.params=this.parseBindingList(m.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(s,false,true);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=n;return this.finishNode(s,"FunctionExpression")};ee.parseArrowExpression=function(e,t,i){var s=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;this.enterScope(functionFlags(i,false)|L);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!i}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false);this.yieldPos=s;this.awaitPos=r;this.awaitIdentPos=a;return this.finishNode(e,"ArrowFunctionExpression")};ee.parseFunctionBody=function(e,t,i){var s=t&&this.type!==m.braceL;var r=this.strict,a=false;if(s){e.body=this.parseMaybeAssign();e.expression=true;this.checkParams(e,false)}else{var n=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!r||n){a=this.strictDirective(this.end);if(a&&n){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var o=this.labels;this.labels=[];if(a){this.strict=true}this.checkParams(e,!r&&!a&&!t&&!i&&this.isSimpleParamList(e.params));if(this.strict&&e.id){this.checkLVal(e.id,q)}e.body=this.parseBlock(false,undefined,a&&!r);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=o}this.exitScope()};ee.isSimpleParamList=function(e){for(var t=0,i=e;t-1||r.functions.indexOf(e)>-1||r.var.indexOf(e)>-1;r.lexical.push(e);if(this.inModule&&r.flags&I){delete this.undefinedExports[e]}}else if(t===F){var a=this.currentScope();a.lexical.push(e)}else if(t===U){var n=this.currentScope();if(this.treatFunctionsAsVar){s=n.lexical.indexOf(e)>-1}else{s=n.lexical.indexOf(e)>-1||n.var.indexOf(e)>-1}n.functions.push(e)}else{for(var o=this.scopeStack.length-1;o>=0;--o){var h=this.scopeStack[o];if(h.lexical.indexOf(e)>-1&&!(h.flags&V&&h.lexical[0]===e)||!this.treatFunctionsAsVarInScope(h)&&h.functions.indexOf(e)>-1){s=true;break}h.var.push(e);if(this.inModule&&h.flags&I){delete this.undefinedExports[e]}if(h.flags&P){break}}}if(s){this.raiseRecoverable(i,"Identifier '"+e+"' has already been declared")}};se.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};se.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};se.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&P){return t}}};se.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&P&&!(t.flags&L)){return t}}};var ae=function Node(e,t,i){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new C(e,i)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var ne=H.prototype;ne.startNode=function(){return new ae(this,this.start,this.startLoc)};ne.startNodeAt=function(e,t){return new ae(this,e,t)};function finishNodeAt(e,t,i,s){e.type=t;e.end=i;if(this.options.locations){e.loc.end=s}if(this.options.ranges){e.range[1]=i}return e}ne.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};ne.finishNodeAt=function(e,t,i,s){return finishNodeAt.call(this,e,t,i,s)};var oe=function TokContext(e,t,i,s,r){this.token=e;this.isExpr=!!t;this.preserveSpace=!!i;this.override=s;this.generator=!!r};var he={b_stat:new oe("{",false),b_expr:new oe("{",true),b_tmpl:new oe("${",false),p_stat:new oe("(",false),p_expr:new oe("(",true),q_tmpl:new oe("`",true,true,(function(e){return e.tryReadTemplateToken()})),f_stat:new oe("function",false),f_expr:new oe("function",true),f_expr_gen:new oe("function",true,false,null,true),f_gen:new oe("function",false,false,null,true)};var pe=H.prototype;pe.initialContext=function(){return[he.b_stat]};pe.braceIsBlock=function(e){var t=this.curContext();if(t===he.f_expr||t===he.f_stat){return true}if(e===m.colon&&(t===he.b_stat||t===he.b_expr)){return!t.isExpr}if(e===m._return||e===m.name&&this.exprAllowed){return x.test(this.input.slice(this.lastTokEnd,this.start))}if(e===m._else||e===m.semi||e===m.eof||e===m.parenR||e===m.arrow){return true}if(e===m.braceL){return t===he.b_stat}if(e===m._var||e===m._const||e===m.name){return false}return!this.exprAllowed};pe.inGeneratorContext=function(){for(var e=this.context.length-1;e>=1;e--){var t=this.context[e];if(t.token==="function"){return t.generator}}return false};pe.updateContext=function(e){var t,i=this.type;if(i.keyword&&e===m.dot){this.exprAllowed=false}else if(t=i.updateContext){t.call(this,e)}else{this.exprAllowed=i.beforeExpr}};m.parenR.updateContext=m.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var e=this.context.pop();if(e===he.b_stat&&this.curContext().token==="function"){e=this.context.pop()}this.exprAllowed=!e.isExpr};m.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?he.b_stat:he.b_expr);this.exprAllowed=true};m.dollarBraceL.updateContext=function(){this.context.push(he.b_tmpl);this.exprAllowed=true};m.parenL.updateContext=function(e){var t=e===m._if||e===m._for||e===m._with||e===m._while;this.context.push(t?he.p_stat:he.p_expr);this.exprAllowed=true};m.incDec.updateContext=function(){};m._function.updateContext=m._class.updateContext=function(e){if(e.beforeExpr&&e!==m.semi&&e!==m._else&&!(e===m._return&&x.test(this.input.slice(this.lastTokEnd,this.start)))&&!((e===m.colon||e===m.braceL)&&this.curContext()===he.b_stat)){this.context.push(he.f_expr)}else{this.context.push(he.f_stat)}this.exprAllowed=false};m.backQuote.updateContext=function(){if(this.curContext()===he.q_tmpl){this.context.pop()}else{this.context.push(he.q_tmpl)}this.exprAllowed=false};m.star.updateContext=function(e){if(e===m._function){var t=this.context.length-1;if(this.context[t]===he.f_expr){this.context[t]=he.f_expr_gen}else{this.context[t]=he.f_gen}}this.exprAllowed=true};m.name.updateContext=function(e){var t=false;if(this.options.ecmaVersion>=6&&e!==m.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){t=true}}this.exprAllowed=t};var ce="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var ue=ce+" Extended_Pictographic";var le=ue;var fe={9:ce,10:ue,11:le};var de="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var me="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var xe=me+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ge=xe+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var ve={9:me,10:xe,11:ge};var ye={};function buildUnicodeData(e){var t=ye[e]={binary:wordsRegexp(fe[e]+" "+de),nonBinary:{General_Category:wordsRegexp(de),Script:wordsRegexp(ve[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);var ke=H.prototype;var be=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"");this.unicodeProperties=ye[e.options.ecmaVersion>=11?11:e.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};be.prototype.reset=function reset(e,t,i){var s=i.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=i;this.switchU=s&&this.parser.options.ecmaVersion>=6;this.switchN=s&&this.parser.options.ecmaVersion>=9};be.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};be.prototype.at=function at(e,t){if(t===void 0)t=false;var i=this.source;var s=i.length;if(e>=s){return-1}var r=i.charCodeAt(e);if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=s){return r}var a=i.charCodeAt(e+1);return a>=56320&&a<=57343?(r<<10)+a-56613888:r};be.prototype.nextIndex=function nextIndex(e,t){if(t===void 0)t=false;var i=this.source;var s=i.length;if(e>=s){return s}var r=i.charCodeAt(e),a;if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=s||(a=i.charCodeAt(e+1))<56320||a>57343){return e+1}return e+2};be.prototype.current=function current(e){if(e===void 0)e=false;return this.at(this.pos,e)};be.prototype.lookahead=function lookahead(e){if(e===void 0)e=false;return this.at(this.nextIndex(this.pos,e),e)};be.prototype.advance=function advance(e){if(e===void 0)e=false;this.pos=this.nextIndex(this.pos,e)};be.prototype.eat=function eat(e,t){if(t===void 0)t=false;if(this.current(t)===e){this.advance(t);return true}return false};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}ke.validateRegExpFlags=function(e){var t=e.validFlags;var i=e.flags;for(var s=0;s-1){this.raise(e.start,"Duplicate regular expression flag")}}};ke.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};ke.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,i=e.backReferenceNames;t=9){i=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!i;return true}}e.pos=t;return false};ke.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};ke.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};ke.regexp_eatBracedQuantifier=function(e,t){var i=e.pos;if(e.eat(123)){var s=0,r=-1;if(this.regexp_eatDecimalDigits(e)){s=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){r=e.lastIntValue}if(e.eat(125)){if(r!==-1&&r=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};ke.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};ke.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};ke.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}ke.regexp_eatPatternCharacters=function(e){var t=e.pos;var i=0;while((i=e.current())!==-1&&!isSyntaxCharacter(i)){e.advance()}return e.pos!==t};ke.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};ke.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};ke.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};ke.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString(e.lastIntValue)}return true}return false};ke.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var i=this.options.ecmaVersion>=11;var s=e.current(i);e.advance(i);if(s===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)){s=e.lastIntValue}if(isRegExpIdentifierStart(s)){e.lastIntValue=s;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}ke.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var i=this.options.ecmaVersion>=11;var s=e.current(i);e.advance(i);if(s===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)){s=e.lastIntValue}if(isRegExpIdentifierPart(s)){e.lastIntValue=s;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}ke.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};ke.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var i=e.lastIntValue;if(e.switchU){if(i>e.maxBackReference){e.maxBackReference=i}return true}if(i<=e.numCapturingParens){return true}e.pos=t}return false};ke.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};ke.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,false)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};ke.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};ke.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};ke.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};ke.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}ke.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){if(t===void 0)t=false;var i=e.pos;var s=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var r=e.lastIntValue;if(s&&r>=55296&&r<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var n=e.lastIntValue;if(n>=56320&&n<=57343){e.lastIntValue=(r-55296)*1024+(n-56320)+65536;return true}}e.pos=a;e.lastIntValue=r}return true}if(s&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(s){e.raise("Invalid unicode escape")}e.pos=i}return false};function isValidUnicode(e){return e>=0&&e<=1114111}ke.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};ke.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};ke.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}ke.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var i=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var s=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,i,s);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var r=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,r);return true}return false};ke.regexp_validateUnicodePropertyNameAndValue=function(e,t,i){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(i)){e.raise("Invalid property value")}};ke.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};ke.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}ke.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}ke.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};ke.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};ke.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var i=e.lastIntValue;if(e.switchU&&(t===-1||i===-1)){e.raise("Invalid character class")}if(t!==-1&&i!==-1&&t>i){e.raise("Range out of order in character class")}}}};ke.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var i=e.current();if(i===99||isOctalDigit(i)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var s=e.current();if(s!==93){e.lastIntValue=s;e.advance();return true}return false};ke.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};ke.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};ke.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};ke.regexp_eatDecimalDigits=function(e){var t=e.pos;var i=0;e.lastIntValue=0;while(isDecimalDigit(i=e.current())){e.lastIntValue=10*e.lastIntValue+(i-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}ke.regexp_eatHexDigits=function(e){var t=e.pos;var i=0;e.lastIntValue=0;while(isHexDigit(i=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(i);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}ke.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var i=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+i*8+e.lastIntValue}else{e.lastIntValue=t*8+i}}else{e.lastIntValue=t}return true}return false};ke.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}ke.regexp_eatFixedHexDigits=function(e,t){var i=e.pos;e.lastIntValue=0;for(var s=0;s=this.input.length){return this.finishToken(m.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};we.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};we.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=57344){return e}var t=this.input.charCodeAt(this.pos+1);return(e<<10)+t-56613888};we.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,i=this.input.indexOf("*/",this.pos+=2);if(i===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=i+2;if(this.options.locations){g.lastIndex=t;var s;while((s=g.exec(this.input))&&s.index8&&e<14||e>=5760&&v.test(String.fromCharCode(e))){++this.pos}else{break e}}}};we.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var i=this.type;this.type=e;this.value=t;this.updateContext(i)};we.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(m.ellipsis)}else{++this.pos;return this.finishToken(m.dot)}};we.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(m.assign,2)}return this.finishOp(m.slash,1)};we.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var i=1;var s=e===42?m.star:m.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++i;s=m.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(m.assign,i+1)}return this.finishOp(s,i)};we.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var i=this.input.charCodeAt(this.pos+2);if(i===61){return this.finishOp(m.assign,3)}}return this.finishOp(e===124?m.logicalOR:m.logicalAND,2)}if(t===61){return this.finishOp(m.assign,2)}return this.finishOp(e===124?m.bitwiseOR:m.bitwiseAND,1)};we.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(m.assign,2)}return this.finishOp(m.bitwiseXOR,1)};we.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||x.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(m.incDec,2)}if(t===61){return this.finishOp(m.assign,2)}return this.finishOp(m.plusMin,1)};we.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var i=1;if(t===e){i=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+i)===61){return this.finishOp(m.assign,i+1)}return this.finishOp(m.bitShift,i)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){i=2}return this.finishOp(m.relational,i)};we.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(m.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(m.arrow)}return this.finishOp(e===61?m.eq:m.prefix,1)};we.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var i=this.input.charCodeAt(this.pos+2);if(i<48||i>57){return this.finishOp(m.questionDot,2)}}if(t===63){if(e>=12){var s=this.input.charCodeAt(this.pos+2);if(s===61){return this.finishOp(m.assign,3)}}return this.finishOp(m.coalesce,2)}}return this.finishOp(m.question,1)};we.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(m.parenL);case 41:++this.pos;return this.finishToken(m.parenR);case 59:++this.pos;return this.finishToken(m.semi);case 44:++this.pos;return this.finishToken(m.comma);case 91:++this.pos;return this.finishToken(m.bracketL);case 93:++this.pos;return this.finishToken(m.bracketR);case 123:++this.pos;return this.finishToken(m.braceL);case 125:++this.pos;return this.finishToken(m.braceR);case 58:++this.pos;return this.finishToken(m.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(m.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(m.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(e)+"'")};we.finishOp=function(e,t){var i=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,i)};we.readRegexp=function(){var e,t,i=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(i,"Unterminated regular expression")}var s=this.input.charAt(this.pos);if(x.test(s)){this.raise(i,"Unterminated regular expression")}if(!e){if(s==="["){t=true}else if(s==="]"&&t){t=false}else if(s==="/"&&!t){break}e=s==="\\"}else{e=false}++this.pos}var r=this.input.slice(i,this.pos);++this.pos;var a=this.pos;var n=this.readWord1();if(this.containsEsc){this.unexpected(a)}var o=this.regexpState||(this.regexpState=new be(this));o.reset(i,r,n);this.validateRegExpFlags(o);this.validateRegExpPattern(o);var h=null;try{h=new RegExp(r,n)}catch(e){}return this.finishToken(m.regexp,{pattern:r,flags:n,value:h})};we.readInt=function(e,t,i){var s=this.options.ecmaVersion>=12&&t===undefined;var r=i&&this.input.charCodeAt(this.pos)===48;var a=this.pos,n=0,o=0;for(var h=0,p=t==null?Infinity:t;h=97){u=c-97+10}else if(c>=65){u=c-65+10}else if(c>=48&&c<=57){u=c-48}else{u=Infinity}if(u>=e){break}o=c;n=n*e+u}if(s&&o===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===a||t!=null&&this.pos-a!==t){return null}return n};function stringToNumber(e,t){if(t){return parseInt(e,8)}return parseFloat(e.replace(/_/g,""))}function stringToBigInt(e){if(typeof BigInt!=="function"){return null}return BigInt(e.replace(/_/g,""))}we.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var i=this.readInt(e);if(i==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){i=stringToBigInt(this.input.slice(t,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(m.num,i)};we.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10,undefined,true)===null){this.raise(t,"Invalid number")}var i=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(i&&this.strict){this.raise(t,"Invalid number")}var s=this.input.charCodeAt(this.pos);if(!i&&!e&&this.options.ecmaVersion>=11&&s===110){var r=stringToBigInt(this.input.slice(t,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(m.num,r)}if(i&&/[89]/.test(this.input.slice(t,this.pos))){i=false}if(s===46&&!i){++this.pos;this.readInt(10);s=this.input.charCodeAt(this.pos)}if((s===69||s===101)&&!i){s=this.input.charCodeAt(++this.pos);if(s===43||s===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var a=stringToNumber(this.input.slice(t,this.pos),i);return this.finishToken(m.num,a)};we.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var i=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(i,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}we.readString=function(e){var t="",i=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var s=this.input.charCodeAt(this.pos);if(s===e){break}if(s===92){t+=this.input.slice(i,this.pos);t+=this.readEscapedChar(false);i=this.pos}else{if(isNewLine(s,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(i,this.pos++);return this.finishToken(m.string,t)};var Se={};we.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===Se){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};we.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw Se}else{this.raise(e,t)}};we.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var i=this.input.charCodeAt(this.pos);if(i===96||i===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===m.template||this.type===m.invalidTemplate)){if(i===36){this.pos+=2;return this.finishToken(m.dollarBraceL)}else{++this.pos;return this.finishToken(m.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(m.template,e)}if(i===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(i)){e+=this.input.slice(t,this.pos);++this.pos;switch(i){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(i);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};we.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var s=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var r=parseInt(s,8);if(r>255){s=s.slice(0,-1);r=parseInt(s,8)}this.pos+=s.length-1;t=this.input.charCodeAt(this.pos);if((s!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-s.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(r)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};we.readHexChar=function(e){var t=this.pos;var i=this.readInt(16,e);if(i===null){this.invalidStringToken(t,"Bad character escape sequence")}return i};we.readWord1=function(){this.containsEsc=false;var e="",t=true,i=this.pos;var s=this.options.ecmaVersion>=6;while(this.pos{var e={108:function(e,t){(function(e,i){true?i(t):0})(this,(function(e){"use strict";var t={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"};var i="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var s={5:i,"5module":i+" export import",6:i+" const class extends export import super"};var r=/^in(stanceof)?$/;var a="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-鿼ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var n="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var o=new RegExp("["+a+"]");var h=new RegExp("["+a+n+"]");a=n=null;var p=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];var c=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];function isInAstralSet(e,t){var i=65536;for(var s=0;se){return false}i+=t[s+1];if(i>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&o.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,p)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&h.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,p)||isInAstralSet(e,c)}var l=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new l(e,{beforeExpr:true,binop:t})}var u={beforeExpr:true},f={startsExpr:true};var d={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return d[e]=new l(e,t)}var m={num:new l("num",f),regexp:new l("regexp",f),string:new l("string",f),name:new l("name",f),privateId:new l("privateId",f),eof:new l("eof"),bracketL:new l("[",{beforeExpr:true,startsExpr:true}),bracketR:new l("]"),braceL:new l("{",{beforeExpr:true,startsExpr:true}),braceR:new l("}"),parenL:new l("(",{beforeExpr:true,startsExpr:true}),parenR:new l(")"),comma:new l(",",u),semi:new l(";",u),colon:new l(":",u),dot:new l("."),question:new l("?",u),questionDot:new l("?."),arrow:new l("=>",u),template:new l("template"),invalidTemplate:new l("invalidTemplate"),ellipsis:new l("...",u),backQuote:new l("`",f),dollarBraceL:new l("${",{beforeExpr:true,startsExpr:true}),eq:new l("=",{beforeExpr:true,isAssign:true}),assign:new l("_=",{beforeExpr:true,isAssign:true}),incDec:new l("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new l("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new l("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new l("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",u),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",u),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",u),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",f),_if:kw("if"),_return:kw("return",u),_switch:kw("switch"),_throw:kw("throw",u),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",f),_super:kw("super",f),_class:kw("class",f),_extends:kw("extends",u),_export:kw("export"),_import:kw("import",f),_null:kw("null",f),_true:kw("true",f),_false:kw("false",f),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var g=/\r\n?|\n|\u2028|\u2029/;var x=new RegExp(g.source,"g");function isNewLine(e){return e===10||e===13||e===8232||e===8233}var v=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var y=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var k=Object.prototype;var b=k.hasOwnProperty;var w=k.toString;function has(e,t){return b.call(e,t)}var _=Array.isArray||function(e){return w.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var S=function Position(e,t){this.line=e;this.column=t};S.prototype.offset=function offset(e){return new S(this.line,this.column+e)};var C=function SourceLocation(e,t,i){this.start=t;this.end=i;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var i=1,s=0;;){x.lastIndex=s;var r=x.exec(e);if(r&&r.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(_(t.onToken)){var s=t.onToken;t.onToken=function(e){return s.push(e)}}if(_(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(i,s,r,a,n,o){var h={type:i?"Block":"Line",value:s,start:r,end:a};if(e.locations){h.loc=new C(this,n,o)}if(e.ranges){h.range=[r,a]}t.push(h)}}var A=1,P=2,N=4,T=8,V=16,L=32,R=64,D=128,O=256,B=A|P|O;function functionFlags(e,t){return P|(e?N:0)|(t?T:0)}var M=0,F=1,U=2,q=3,H=4,G=5;var j=function Parser(e,i,r){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(s[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var a="";if(e.allowReserved!==true){a=t[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3];if(e.sourceType==="module"){a+=" await"}}this.reservedWords=wordsRegexp(a);var n=(a?a+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(n);this.reservedWordsStrictBind=wordsRegexp(n+" "+t.strictBind);this.input=String(i);this.containsEsc=false;if(r){this.pos=r;this.lineStart=this.input.lastIndexOf("\n",r-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(g).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=m.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.potentialArrowInForAwait=false;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports=Object.create(null);if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(A);this.regexpState=null;this.privateNameStack=[]};var z={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},canAwait:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true},allowNewDotTarget:{configurable:true},inClassStaticBlock:{configurable:true}};j.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};z.inFunction.get=function(){return(this.currentVarScope().flags&P)>0};z.inGenerator.get=function(){return(this.currentVarScope().flags&T)>0&&!this.currentVarScope().inClassFieldInit};z.inAsync.get=function(){return(this.currentVarScope().flags&N)>0&&!this.currentVarScope().inClassFieldInit};z.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e];if(t.inClassFieldInit||t.flags&O){return false}if(t.flags&P){return(t.flags&N)>0}}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};z.allowSuper.get=function(){var e=this.currentThisScope();var t=e.flags;var i=e.inClassFieldInit;return(t&R)>0||i||this.options.allowSuperOutsideMethod};z.allowDirectSuper.get=function(){return(this.currentThisScope().flags&D)>0};z.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};z.allowNewDotTarget.get=function(){var e=this.currentThisScope();var t=e.flags;var i=e.inClassFieldInit;return(t&(P|O))>0||i};z.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&O)>0};j.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var i=this;for(var s=0;s=,?^&]/.test(r)||r==="!"&&this.input.charAt(s+1)==="=")}e+=t[0].length;y.lastIndex=e;e+=y.exec(this.input)[0].length;if(this.input[e]===";"){e++}}};W.eat=function(e){if(this.type===e){this.next();return true}else{return false}};W.isContextual=function(e){return this.type===m.name&&this.value===e&&!this.containsEsc};W.eatContextual=function(e){if(!this.isContextual(e)){return false}this.next();return true};W.expectContextual=function(e){if(!this.eatContextual(e)){this.unexpected()}};W.canInsertSemicolon=function(){return this.type===m.eof||this.type===m.braceR||g.test(this.input.slice(this.lastTokEnd,this.start))};W.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};W.semicolon=function(){if(!this.eat(m.semi)&&!this.insertSemicolon()){this.unexpected()}};W.afterTrailingComma=function(e,t){if(this.type===e){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!t){this.next()}return true}};W.expect=function(e){this.eat(e)||this.unexpected()};W.unexpected=function(e){this.raise(e!=null?e:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}W.checkPatternErrors=function(e,t){if(!e){return}if(e.trailingComma>-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var i=t?e.parenthesizedAssign:e.parenthesizedBind;if(i>-1){this.raiseRecoverable(i,"Parenthesized pattern")}};W.checkExpressionErrors=function(e,t){if(!e){return false}var i=e.shorthandAssign;var s=e.doubleProto;if(!t){return i>=0||s>=0}if(i>=0){this.raise(i,"Shorthand property assignments are valid only in destructuring patterns")}if(s>=0){this.raiseRecoverable(s,"Redefinition of __proto__ property")}};W.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&s<56320){return true}if(e){return false}if(s===123){return true}if(isIdentifierStart(s,true)){var a=i+1;while(isIdentifierChar(s=this.input.charCodeAt(a),true)){++a}if(s===92||s>55295&&s<56320){return true}var n=this.input.slice(i,a);if(!r.test(n)){return true}}return false};K.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async")){return false}y.lastIndex=this.pos;var e=y.exec(this.input);var t=this.pos+e[0].length,i;return!g.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)==="function"&&(t+8===this.input.length||!(isIdentifierChar(i=this.input.charCodeAt(t+8))||i>55295&&i<56320))};K.parseStatement=function(e,t,i){var s=this.type,r=this.startNode(),a;if(this.isLet(e)){s=m._var;a="let"}switch(s){case m._break:case m._continue:return this.parseBreakContinueStatement(r,s.keyword);case m._debugger:return this.parseDebuggerStatement(r);case m._do:return this.parseDoStatement(r);case m._for:return this.parseForStatement(r);case m._function:if(e&&(this.strict||e!=="if"&&e!=="label")&&this.options.ecmaVersion>=6){this.unexpected()}return this.parseFunctionStatement(r,false,!e);case m._class:if(e){this.unexpected()}return this.parseClass(r,true);case m._if:return this.parseIfStatement(r);case m._return:return this.parseReturnStatement(r);case m._switch:return this.parseSwitchStatement(r);case m._throw:return this.parseThrowStatement(r);case m._try:return this.parseTryStatement(r);case m._const:case m._var:a=a||this.value;if(e&&a!=="var"){this.unexpected()}return this.parseVarStatement(r,a);case m._while:return this.parseWhileStatement(r);case m._with:return this.parseWithStatement(r);case m.braceL:return this.parseBlock(true,r);case m.semi:return this.parseEmptyStatement(r);case m._export:case m._import:if(this.options.ecmaVersion>10&&s===m._import){y.lastIndex=this.pos;var n=y.exec(this.input);var o=this.pos+n[0].length,h=this.input.charCodeAt(o);if(h===40||h===46){return this.parseExpressionStatement(r,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return s===m._import?this.parseImport(r):this.parseExport(r,i);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(r,true,!e)}var p=this.value,c=this.parseExpression();if(s===m.name&&c.type==="Identifier"&&this.eat(m.colon)){return this.parseLabeledStatement(r,p,c,e)}else{return this.parseExpressionStatement(r,c)}}};K.parseBreakContinueStatement=function(e,t){var i=t==="break";this.next();if(this.eat(m.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==m.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var s=0;for(;s=6){this.eat(m.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};K.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(Y);this.enterScope(0);this.expect(m.parenL);if(this.type===m.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var i=this.isLet();if(this.type===m._var||this.type===m._const||i){var s=this.startNode(),r=i?"let":this.value;this.next();this.parseVar(s,true,r);this.finishNode(s,"VariableDeclaration");if((this.type===m._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&s.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===m._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,s)}if(t>-1){this.unexpected(t)}return this.parseFor(e,s)}var a=this.isContextual("let"),n=false;var o=new DestructuringErrors;var h=this.parseExpression(t>-1?"await":true,o);if(this.type===m._in||(n=this.options.ecmaVersion>=6&&this.isContextual("of"))){if(this.options.ecmaVersion>=9){if(this.type===m._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}if(a&&n){this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'.")}this.toAssignable(h,false,o);this.checkLValPattern(h);return this.parseForIn(e,h)}else{this.checkExpressionErrors(o,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,h)};K.parseFunctionStatement=function(e,t,i){this.next();return this.parseFunction(e,Z|(i?0:J),false,t)};K.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(m._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};K.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(m.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};K.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(m.braceL);this.labels.push(X);this.enterScope(0);var t;for(var i=false;this.type!==m.braceR;){if(this.type===m._case||this.type===m._default){var s=this.type===m._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(s){t.test=this.parseExpression()}else{if(i){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}i=true;t.test=null}this.expect(m.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};K.parseThrowStatement=function(e){this.next();if(g.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var $=[];K.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===m._catch){var t=this.startNode();this.next();if(this.eat(m.parenL)){t.param=this.parseBindingAtom();var i=t.param.type==="Identifier";this.enterScope(i?L:0);this.checkLValPattern(t.param,i?H:U);this.expect(m.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(m._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};K.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};K.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(Y);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};K.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};K.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};K.parseLabeledStatement=function(e,t,i,s){for(var r=0,a=this.labels;r=0;h--){var p=this.labels[h];if(p.statementStart===e.start){p.statementStart=this.start;p.kind=o}else{break}}this.labels.push({name:t,kind:o,statementStart:this.start});e.body=this.parseStatement(s?s.indexOf("label")===-1?s+"label":s:"label");this.labels.pop();e.label=i;return this.finishNode(e,"LabeledStatement")};K.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};K.parseBlock=function(e,t,i){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(m.braceL);if(e){this.enterScope(0)}while(this.type!==m.braceR){var s=this.parseStatement(null);t.body.push(s)}if(i){this.strict=false}this.next();if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};K.parseFor=function(e,t){e.init=t;this.expect(m.semi);e.test=this.type===m.semi?null:this.parseExpression();this.expect(m.semi);e.update=this.type===m.parenR?null:this.parseExpression();this.expect(m.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};K.parseForIn=function(e,t){var i=this.type===m._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!i||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(i?"for-in":"for-of")+" loop variable declaration may not have an initializer")}e.left=t;e.right=i?this.parseExpression():this.parseMaybeAssign();this.expect(m.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,i?"ForInStatement":"ForOfStatement")};K.parseVar=function(e,t,i){e.declarations=[];e.kind=i;for(;;){var s=this.startNode();this.parseVarId(s,i);if(this.eat(m.eq)){s.init=this.parseMaybeAssign(t)}else if(i==="const"&&!(this.type===m._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(s.id.type!=="Identifier"&&!(t&&(this.type===m._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{s.init=null}e.declarations.push(this.finishNode(s,"VariableDeclarator"));if(!this.eat(m.comma)){break}}return e};K.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLValPattern(e.id,t==="var"?F:U,false)};var Z=1,J=2,ee=4;K.parseFunction=function(e,t,i,s,r){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!s){if(this.type===m.star&&t&J){this.unexpected()}e.generator=this.eat(m.star)}if(this.options.ecmaVersion>=8){e.async=!!s}if(t&Z){e.id=t&ee&&this.type!==m.name?null:this.parseIdent();if(e.id&&!(t&J)){this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?F:U:q)}}var a=this.yieldPos,n=this.awaitPos,o=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&Z)){e.id=this.type===m.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,i,false,r);this.yieldPos=a;this.awaitPos=n;this.awaitIdentPos=o;return this.finishNode(e,t&Z?"FunctionDeclaration":"FunctionExpression")};K.parseFunctionParams=function(e){this.expect(m.parenL);e.params=this.parseBindingList(m.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};K.parseClass=function(e,t){this.next();var i=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var s=this.enterClassBody();var r=this.startNode();var a=false;r.body=[];this.expect(m.braceL);while(this.type!==m.braceR){var n=this.parseClassElement(e.superClass!==null);if(n){r.body.push(n);if(n.type==="MethodDefinition"&&n.kind==="constructor"){if(a){this.raise(n.start,"Duplicate constructor in the same class")}a=true}else if(n.key&&n.key.type==="PrivateIdentifier"&&isPrivateNameConflicted(s,n)){this.raiseRecoverable(n.key.start,"Identifier '#"+n.key.name+"' has already been declared")}}}this.strict=i;this.next();e.body=this.finishNode(r,"ClassBody");this.exitClassBody();return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};K.parseClassElement=function(e){if(this.eat(m.semi)){return null}var t=this.options.ecmaVersion;var i=this.startNode();var s="";var r=false;var a=false;var n="method";var o=false;if(this.eatContextual("static")){if(t>=13&&this.eat(m.braceL)){this.parseClassStaticBlock(i);return i}if(this.isClassElementNameStart()||this.type===m.star){o=true}else{s="static"}}i.static=o;if(!s&&t>=8&&this.eatContextual("async")){if((this.isClassElementNameStart()||this.type===m.star)&&!this.canInsertSemicolon()){a=true}else{s="async"}}if(!s&&(t>=9||!a)&&this.eat(m.star)){r=true}if(!s&&!a&&!r){var h=this.value;if(this.eatContextual("get")||this.eatContextual("set")){if(this.isClassElementNameStart()){n=h}else{s=h}}}if(s){i.computed=false;i.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc);i.key.name=s;this.finishNode(i.key,"Identifier")}else{this.parseClassElementName(i)}if(t<13||this.type===m.parenL||n!=="method"||r||a){var p=!i.static&&checkKeyName(i,"constructor");var c=p&&e;if(p&&n!=="method"){this.raise(i.key.start,"Constructor can't have get/set modifier")}i.kind=p?"constructor":n;this.parseClassMethod(i,r,a,c)}else{this.parseClassField(i)}return i};K.isClassElementNameStart=function(){return this.type===m.name||this.type===m.privateId||this.type===m.num||this.type===m.string||this.type===m.bracketL||this.type.keyword};K.parseClassElementName=function(e){if(this.type===m.privateId){if(this.value==="constructor"){this.raise(this.start,"Classes can't have an element named '#constructor'")}e.computed=false;e.key=this.parsePrivateIdent()}else{this.parsePropertyName(e)}};K.parseClassMethod=function(e,t,i,s){var r=e.key;if(e.kind==="constructor"){if(t){this.raise(r.start,"Constructor can't be a generator")}if(i){this.raise(r.start,"Constructor can't be an async method")}}else if(e.static&&checkKeyName(e,"prototype")){this.raise(r.start,"Classes may not have a static property named prototype")}var a=e.value=this.parseMethod(t,i,s);if(e.kind==="get"&&a.params.length!==0){this.raiseRecoverable(a.start,"getter should have no params")}if(e.kind==="set"&&a.params.length!==1){this.raiseRecoverable(a.start,"setter should have exactly one param")}if(e.kind==="set"&&a.params[0].type==="RestElement"){this.raiseRecoverable(a.params[0].start,"Setter cannot use rest params")}return this.finishNode(e,"MethodDefinition")};K.parseClassField=function(e){if(checkKeyName(e,"constructor")){this.raise(e.key.start,"Classes can't have a field named 'constructor'")}else if(e.static&&checkKeyName(e,"prototype")){this.raise(e.key.start,"Classes can't have a static field named 'prototype'")}if(this.eat(m.eq)){var t=this.currentThisScope();var i=t.inClassFieldInit;t.inClassFieldInit=true;e.value=this.parseMaybeAssign();t.inClassFieldInit=i}else{e.value=null}this.semicolon();return this.finishNode(e,"PropertyDefinition")};K.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;this.labels=[];this.enterScope(O|R);while(this.type!==m.braceR){var i=this.parseStatement(null);e.body.push(i)}this.next();this.exitScope();this.labels=t;return this.finishNode(e,"StaticBlock")};K.parseClassId=function(e,t){if(this.type===m.name){e.id=this.parseIdent();if(t){this.checkLValSimple(e.id,U,false)}}else{if(t===true){this.unexpected()}e.id=null}};K.parseClassSuper=function(e){e.superClass=this.eat(m._extends)?this.parseExprSubscripts(false):null};K.enterClassBody=function(){var e={declared:Object.create(null),used:[]};this.privateNameStack.push(e);return e.declared};K.exitClassBody=function(){var e=this.privateNameStack.pop();var t=e.declared;var i=e.used;var s=this.privateNameStack.length;var r=s===0?null:this.privateNameStack[s-1];for(var a=0;a=11){if(this.eatContextual("as")){e.exported=this.parseIdent(true);this.checkExport(t,e.exported.name,this.lastTokStart)}else{e.exported=null}}this.expectContextual("from");if(this.type!==m.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(m._default)){this.checkExport(t,"default",this.lastTokStart);var i;if(this.type===m._function||(i=this.isAsyncFunction())){var s=this.startNode();this.next();if(i){this.next()}e.declaration=this.parseFunction(s,Z|ee,false,i)}else if(this.type===m._class){var r=this.startNode();e.declaration=this.parseClass(r,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==m.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var a=0,n=e.specifiers;a=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(i){this.checkPatternErrors(i,true)}for(var s=0,r=e.properties;s=8&&!n&&o.name==="async"&&!this.canInsertSemicolon()&&this.eat(m._function)){this.overrideContext(se.f_expr);return this.parseFunction(this.startNodeAt(r,a),0,false,true,t)}if(s&&!this.canInsertSemicolon()){if(this.eat(m.arrow)){return this.parseArrowExpression(this.startNodeAt(r,a),[o],false,t)}if(this.options.ecmaVersion>=8&&o.name==="async"&&this.type===m.name&&!n&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc)){o=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(m.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(r,a),[o],true,t)}}return o;case m.regexp:var h=this.value;i=this.parseLiteral(h.value);i.regex={pattern:h.pattern,flags:h.flags};return i;case m.num:case m.string:return this.parseLiteral(this.value);case m._null:case m._true:case m._false:i=this.startNode();i.value=this.type===m._null?null:this.type===m._true;i.raw=this.type.keyword;this.next();return this.finishNode(i,"Literal");case m.parenL:var p=this.start,c=this.parseParenAndDistinguishExpression(s,t);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)){e.parenthesizedAssign=p}if(e.parenthesizedBind<0){e.parenthesizedBind=p}}return c;case m.bracketL:i=this.startNode();this.next();i.elements=this.parseExprList(m.bracketR,true,true,e);return this.finishNode(i,"ArrayExpression");case m.braceL:this.overrideContext(se.b_expr);return this.parseObj(false,e);case m._function:i=this.startNode();this.next();return this.parseFunction(i,0);case m._class:return this.parseClass(this.startNode(),false);case m._new:return this.parseNew();case m.backQuote:return this.parseTemplate();case m._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};ae.parseExprImport=function(){var e=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var t=this.parseIdent(true);switch(this.type){case m.parenL:return this.parseDynamicImport(e);case m.dot:e.meta=t;return this.parseImportMeta(e);default:this.unexpected()}};ae.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(m.parenR)){var t=this.start;if(this.eat(m.comma)&&this.eat(m.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};ae.parseImportMeta=function(e){this.next();var t=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="meta"){this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'")}if(t){this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere){this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(e,"MetaProperty")};ae.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(t,"Literal")};ae.parseParenExpression=function(){this.expect(m.parenL);var e=this.parseExpression();this.expect(m.parenR);return e};ae.parseParenAndDistinguishExpression=function(e,t){var i=this.start,s=this.startLoc,r,a=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var n=this.start,o=this.startLoc;var h=[],p=true,c=false;var l=new DestructuringErrors,u=this.yieldPos,f=this.awaitPos,d;this.yieldPos=0;this.awaitPos=0;while(this.type!==m.parenR){p?p=false:this.expect(m.comma);if(a&&this.afterTrailingComma(m.parenR,true)){c=true;break}else if(this.type===m.ellipsis){d=this.start;h.push(this.parseParenItem(this.parseRestBinding()));if(this.type===m.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{h.push(this.parseMaybeAssign(false,l,this.parseParenItem))}}var g=this.lastTokEnd,x=this.lastTokEndLoc;this.expect(m.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(m.arrow)){this.checkPatternErrors(l,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=u;this.awaitPos=f;return this.parseParenArrowList(i,s,h,t)}if(!h.length||c){this.unexpected(this.lastTokStart)}if(d){this.unexpected(d)}this.checkExpressionErrors(l,true);this.yieldPos=u||this.yieldPos;this.awaitPos=f||this.awaitPos;if(h.length>1){r=this.startNodeAt(n,o);r.expressions=h;this.finishNodeAt(r,"SequenceExpression",g,x)}else{r=h[0]}}else{r=this.parseParenExpression()}if(this.options.preserveParens){var v=this.startNodeAt(i,s);v.expression=r;return this.finishNode(v,"ParenthesizedExpression")}else{return r}};ae.parseParenItem=function(e){return e};ae.parseParenArrowList=function(e,t,i,s){return this.parseArrowExpression(this.startNodeAt(e,t),i,s)};var ne=[];ae.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(m.dot)){e.meta=t;var i=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"){this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'")}if(i){this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters")}if(!this.allowNewDotTarget){this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block")}return this.finishNode(e,"MetaProperty")}var s=this.start,r=this.startLoc,a=this.type===m._import;e.callee=this.parseSubscripts(this.parseExprAtom(),s,r,true,false);if(a&&e.callee.type==="ImportExpression"){this.raise(s,"Cannot use new with import()")}if(this.eat(m.parenL)){e.arguments=this.parseExprList(m.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=ne}return this.finishNode(e,"NewExpression")};ae.parseTemplateElement=function(e){var t=e.isTagged;var i=this.startNode();if(this.type===m.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}i.value={raw:this.value,cooked:null}}else{i.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();i.tail=this.type===m.backQuote;return this.finishNode(i,"TemplateElement")};ae.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var i=this.startNode();this.next();i.expressions=[];var s=this.parseTemplateElement({isTagged:t});i.quasis=[s];while(!s.tail){if(this.type===m.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(m.dollarBraceL);i.expressions.push(this.parseExpression());this.expect(m.braceR);i.quasis.push(s=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(i,"TemplateLiteral")};ae.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===m.name||this.type===m.num||this.type===m.string||this.type===m.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===m.star)&&!g.test(this.input.slice(this.lastTokEnd,this.start))};ae.parseObj=function(e,t){var i=this.startNode(),s=true,r={};i.properties=[];this.next();while(!this.eat(m.braceR)){if(!s){this.expect(m.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(m.braceR)){break}}else{s=false}var a=this.parseProperty(e,t);if(!e){this.checkPropClash(a,r,t)}i.properties.push(a)}return this.finishNode(i,e?"ObjectPattern":"ObjectExpression")};ae.parseProperty=function(e,t){var i=this.startNode(),s,r,a,n;if(this.options.ecmaVersion>=9&&this.eat(m.ellipsis)){if(e){i.argument=this.parseIdent(false);if(this.type===m.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(i,"RestElement")}if(this.type===m.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}i.argument=this.parseMaybeAssign(false,t);if(this.type===m.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(i,"SpreadElement")}if(this.options.ecmaVersion>=6){i.method=false;i.shorthand=false;if(e||t){a=this.start;n=this.startLoc}if(!e){s=this.eat(m.star)}}var o=this.containsEsc;this.parsePropertyName(i);if(!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(i)){r=true;s=this.options.ecmaVersion>=9&&this.eat(m.star);this.parsePropertyName(i,t)}else{r=false}this.parsePropertyValue(i,e,s,r,a,n,t,o);return this.finishNode(i,"Property")};ae.parsePropertyValue=function(e,t,i,s,r,a,n,o){if((i||s)&&this.type===m.colon){this.unexpected()}if(this.eat(m.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,n);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===m.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(i,s)}else if(!t&&!o&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==m.comma&&this.type!==m.braceR&&this.type!==m.eq)){if(i||s){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var h=e.kind==="get"?0:1;if(e.value.params.length!==h){var p=e.value.start;if(e.kind==="get"){this.raiseRecoverable(p,"getter should have no params")}else{this.raiseRecoverable(p,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(i||s){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=r}e.kind="init";if(t){e.value=this.parseMaybeDefault(r,a,this.copyNode(e.key))}else if(this.type===m.eq&&n){if(n.shorthandAssign<0){n.shorthandAssign=this.start}e.value=this.parseMaybeDefault(r,a,this.copyNode(e.key))}else{e.value=this.copyNode(e.key)}e.shorthand=true}else{this.unexpected()}};ae.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(m.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(m.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===m.num||this.type===m.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ae.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};ae.parseMethod=function(e,t,i){var s=this.startNode(),r=this.yieldPos,a=this.awaitPos,n=this.awaitIdentPos;this.initFunction(s);if(this.options.ecmaVersion>=6){s.generator=e}if(this.options.ecmaVersion>=8){s.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,s.generator)|R|(i?D:0));this.expect(m.parenL);s.params=this.parseBindingList(m.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(s,false,true,false);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=n;return this.finishNode(s,"FunctionExpression")};ae.parseArrowExpression=function(e,t,i,s){var r=this.yieldPos,a=this.awaitPos,n=this.awaitIdentPos;this.enterScope(functionFlags(i,false)|V);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!i}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false,s);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=n;return this.finishNode(e,"ArrowFunctionExpression")};ae.parseFunctionBody=function(e,t,i,s){var r=t&&this.type!==m.braceL;var a=this.strict,n=false;if(r){e.body=this.parseMaybeAssign(s);e.expression=true;this.checkParams(e,false)}else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!a||o){n=this.strictDirective(this.end);if(n&&o){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var h=this.labels;this.labels=[];if(n){this.strict=true}this.checkParams(e,!a&&!n&&!t&&!i&&this.isSimpleParamList(e.params));if(this.strict&&e.id){this.checkLValSimple(e.id,G)}e.body=this.parseBlock(false,undefined,n&&!a);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=h}this.exitScope()};ae.isSimpleParamList=function(e){for(var t=0,i=e;t-1||r.functions.indexOf(e)>-1||r.var.indexOf(e)>-1;r.lexical.push(e);if(this.inModule&&r.flags&A){delete this.undefinedExports[e]}}else if(t===H){var a=this.currentScope();a.lexical.push(e)}else if(t===q){var n=this.currentScope();if(this.treatFunctionsAsVar){s=n.lexical.indexOf(e)>-1}else{s=n.lexical.indexOf(e)>-1||n.var.indexOf(e)>-1}n.functions.push(e)}else{for(var o=this.scopeStack.length-1;o>=0;--o){var h=this.scopeStack[o];if(h.lexical.indexOf(e)>-1&&!(h.flags&L&&h.lexical[0]===e)||!this.treatFunctionsAsVarInScope(h)&&h.functions.indexOf(e)>-1){s=true;break}h.var.push(e);if(this.inModule&&h.flags&A){delete this.undefinedExports[e]}if(h.flags&B){break}}}if(s){this.raiseRecoverable(i,"Identifier '"+e+"' has already been declared")}};he.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};he.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};he.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&B){return t}}};he.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&B&&!(t.flags&V)){return t}}};var ce=function Node(e,t,i){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new C(e,i)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var le=j.prototype;le.startNode=function(){return new ce(this,this.start,this.startLoc)};le.startNodeAt=function(e,t){return new ce(this,e,t)};function finishNodeAt(e,t,i,s){e.type=t;e.end=i;if(this.options.locations){e.loc.end=s}if(this.options.ranges){e.range[1]=i}return e}le.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};le.finishNodeAt=function(e,t,i,s){return finishNodeAt.call(this,e,t,i,s)};le.copyNode=function(e){var t=new ce(this,e.start,this.startLoc);for(var i in e){t[i]=e[i]}return t};var ue="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var fe=ue+" Extended_Pictographic";var de=fe;var me=de+" EBase EComp EMod EPres ExtPict";var ge={9:ue,10:fe,11:de,12:me};var xe="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ve="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ye=ve+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ke=ye+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var be=ke+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";var we={9:ve,10:ye,11:ke,12:be};var _e={};function buildUnicodeData(e){var t=_e[e]={binary:wordsRegexp(ge[e]+" "+xe),nonBinary:{General_Category:wordsRegexp(xe),Script:wordsRegexp(we[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);buildUnicodeData(12);var Se=j.prototype;var Ce=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"");this.unicodeProperties=_e[e.options.ecmaVersion>=12?12:e.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};Ce.prototype.reset=function reset(e,t,i){var s=i.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=i;this.switchU=s&&this.parser.options.ecmaVersion>=6;this.switchN=s&&this.parser.options.ecmaVersion>=9};Ce.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};Ce.prototype.at=function at(e,t){if(t===void 0)t=false;var i=this.source;var s=i.length;if(e>=s){return-1}var r=i.charCodeAt(e);if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=s){return r}var a=i.charCodeAt(e+1);return a>=56320&&a<=57343?(r<<10)+a-56613888:r};Ce.prototype.nextIndex=function nextIndex(e,t){if(t===void 0)t=false;var i=this.source;var s=i.length;if(e>=s){return s}var r=i.charCodeAt(e),a;if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=s||(a=i.charCodeAt(e+1))<56320||a>57343){return e+1}return e+2};Ce.prototype.current=function current(e){if(e===void 0)e=false;return this.at(this.pos,e)};Ce.prototype.lookahead=function lookahead(e){if(e===void 0)e=false;return this.at(this.nextIndex(this.pos,e),e)};Ce.prototype.advance=function advance(e){if(e===void 0)e=false;this.pos=this.nextIndex(this.pos,e)};Ce.prototype.eat=function eat(e,t){if(t===void 0)t=false;if(this.current(t)===e){this.advance(t);return true}return false};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Se.validateRegExpFlags=function(e){var t=e.validFlags;var i=e.flags;for(var s=0;s-1){this.raise(e.start,"Duplicate regular expression flag")}}};Se.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};Se.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,i=e.backReferenceNames;t=9){i=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!i;return true}}e.pos=t;return false};Se.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};Se.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};Se.regexp_eatBracedQuantifier=function(e,t){var i=e.pos;if(e.eat(123)){var s=0,r=-1;if(this.regexp_eatDecimalDigits(e)){s=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){r=e.lastIntValue}if(e.eat(125)){if(r!==-1&&r=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};Se.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};Se.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};Se.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}Se.regexp_eatPatternCharacters=function(e){var t=e.pos;var i=0;while((i=e.current())!==-1&&!isSyntaxCharacter(i)){e.advance()}return e.pos!==t};Se.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};Se.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};Se.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};Se.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString(e.lastIntValue)}return true}return false};Se.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var i=this.options.ecmaVersion>=11;var s=e.current(i);e.advance(i);if(s===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)){s=e.lastIntValue}if(isRegExpIdentifierStart(s)){e.lastIntValue=s;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}Se.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var i=this.options.ecmaVersion>=11;var s=e.current(i);e.advance(i);if(s===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)){s=e.lastIntValue}if(isRegExpIdentifierPart(s)){e.lastIntValue=s;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}Se.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};Se.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var i=e.lastIntValue;if(e.switchU){if(i>e.maxBackReference){e.maxBackReference=i}return true}if(i<=e.numCapturingParens){return true}e.pos=t}return false};Se.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};Se.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,false)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};Se.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};Se.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};Se.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};Se.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}Se.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){if(t===void 0)t=false;var i=e.pos;var s=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var r=e.lastIntValue;if(s&&r>=55296&&r<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var n=e.lastIntValue;if(n>=56320&&n<=57343){e.lastIntValue=(r-55296)*1024+(n-56320)+65536;return true}}e.pos=a;e.lastIntValue=r}return true}if(s&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(s){e.raise("Invalid unicode escape")}e.pos=i}return false};function isValidUnicode(e){return e>=0&&e<=1114111}Se.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};Se.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};Se.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}Se.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var i=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var s=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,i,s);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var r=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,r);return true}return false};Se.regexp_validateUnicodePropertyNameAndValue=function(e,t,i){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(i)){e.raise("Invalid property value")}};Se.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};Se.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}Se.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}Se.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};Se.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};Se.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var i=e.lastIntValue;if(e.switchU&&(t===-1||i===-1)){e.raise("Invalid character class")}if(t!==-1&&i!==-1&&t>i){e.raise("Range out of order in character class")}}}};Se.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var i=e.current();if(i===99||isOctalDigit(i)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var s=e.current();if(s!==93){e.lastIntValue=s;e.advance();return true}return false};Se.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};Se.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};Se.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};Se.regexp_eatDecimalDigits=function(e){var t=e.pos;var i=0;e.lastIntValue=0;while(isDecimalDigit(i=e.current())){e.lastIntValue=10*e.lastIntValue+(i-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}Se.regexp_eatHexDigits=function(e){var t=e.pos;var i=0;e.lastIntValue=0;while(isHexDigit(i=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(i);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}Se.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var i=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+i*8+e.lastIntValue}else{e.lastIntValue=t*8+i}}else{e.lastIntValue=t}return true}return false};Se.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}Se.regexp_eatFixedHexDigits=function(e,t){var i=e.pos;e.lastIntValue=0;for(var s=0;s=this.input.length){return this.finishToken(m.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};Ie.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};Ie.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320){return e}var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888};Ie.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,i=this.input.indexOf("*/",this.pos+=2);if(i===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=i+2;if(this.options.locations){x.lastIndex=t;var s;while((s=x.exec(this.input))&&s.index8&&e<14||e>=5760&&v.test(String.fromCharCode(e))){++this.pos}else{break e}}}};Ie.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var i=this.type;this.type=e;this.value=t;this.updateContext(i)};Ie.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(m.ellipsis)}else{++this.pos;return this.finishToken(m.dot)}};Ie.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(m.assign,2)}return this.finishOp(m.slash,1)};Ie.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var i=1;var s=e===42?m.star:m.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++i;s=m.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(m.assign,i+1)}return this.finishOp(s,i)};Ie.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var i=this.input.charCodeAt(this.pos+2);if(i===61){return this.finishOp(m.assign,3)}}return this.finishOp(e===124?m.logicalOR:m.logicalAND,2)}if(t===61){return this.finishOp(m.assign,2)}return this.finishOp(e===124?m.bitwiseOR:m.bitwiseAND,1)};Ie.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(m.assign,2)}return this.finishOp(m.bitwiseXOR,1)};Ie.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||g.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(m.incDec,2)}if(t===61){return this.finishOp(m.assign,2)}return this.finishOp(m.plusMin,1)};Ie.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var i=1;if(t===e){i=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+i)===61){return this.finishOp(m.assign,i+1)}return this.finishOp(m.bitShift,i)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){i=2}return this.finishOp(m.relational,i)};Ie.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(m.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(m.arrow)}return this.finishOp(e===61?m.eq:m.prefix,1)};Ie.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var i=this.input.charCodeAt(this.pos+2);if(i<48||i>57){return this.finishOp(m.questionDot,2)}}if(t===63){if(e>=12){var s=this.input.charCodeAt(this.pos+2);if(s===61){return this.finishOp(m.assign,3)}}return this.finishOp(m.coalesce,2)}}return this.finishOp(m.question,1)};Ie.readToken_numberSign=function(){var e=this.options.ecmaVersion;var t=35;if(e>=13){++this.pos;t=this.fullCharCodeAtPos();if(isIdentifierStart(t,true)||t===92){return this.finishToken(m.privateId,this.readWord1())}}this.raise(this.pos,"Unexpected character '"+codePointToString$1(t)+"'")};Ie.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(m.parenL);case 41:++this.pos;return this.finishToken(m.parenR);case 59:++this.pos;return this.finishToken(m.semi);case 44:++this.pos;return this.finishToken(m.comma);case 91:++this.pos;return this.finishToken(m.bracketL);case 93:++this.pos;return this.finishToken(m.bracketR);case 123:++this.pos;return this.finishToken(m.braceL);case 125:++this.pos;return this.finishToken(m.braceR);case 58:++this.pos;return this.finishToken(m.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(m.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(m.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+codePointToString$1(e)+"'")};Ie.finishOp=function(e,t){var i=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,i)};Ie.readRegexp=function(){var e,t,i=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(i,"Unterminated regular expression")}var s=this.input.charAt(this.pos);if(g.test(s)){this.raise(i,"Unterminated regular expression")}if(!e){if(s==="["){t=true}else if(s==="]"&&t){t=false}else if(s==="/"&&!t){break}e=s==="\\"}else{e=false}++this.pos}var r=this.input.slice(i,this.pos);++this.pos;var a=this.pos;var n=this.readWord1();if(this.containsEsc){this.unexpected(a)}var o=this.regexpState||(this.regexpState=new Ce(this));o.reset(i,r,n);this.validateRegExpFlags(o);this.validateRegExpPattern(o);var h=null;try{h=new RegExp(r,n)}catch(e){}return this.finishToken(m.regexp,{pattern:r,flags:n,value:h})};Ie.readInt=function(e,t,i){var s=this.options.ecmaVersion>=12&&t===undefined;var r=i&&this.input.charCodeAt(this.pos)===48;var a=this.pos,n=0,o=0;for(var h=0,p=t==null?Infinity:t;h=97){l=c-97+10}else if(c>=65){l=c-65+10}else if(c>=48&&c<=57){l=c-48}else{l=Infinity}if(l>=e){break}o=c;n=n*e+l}if(s&&o===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===a||t!=null&&this.pos-a!==t){return null}return n};function stringToNumber(e,t){if(t){return parseInt(e,8)}return parseFloat(e.replace(/_/g,""))}function stringToBigInt(e){if(typeof BigInt!=="function"){return null}return BigInt(e.replace(/_/g,""))}Ie.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var i=this.readInt(e);if(i==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){i=stringToBigInt(this.input.slice(t,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(m.num,i)};Ie.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10,undefined,true)===null){this.raise(t,"Invalid number")}var i=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(i&&this.strict){this.raise(t,"Invalid number")}var s=this.input.charCodeAt(this.pos);if(!i&&!e&&this.options.ecmaVersion>=11&&s===110){var r=stringToBigInt(this.input.slice(t,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(m.num,r)}if(i&&/[89]/.test(this.input.slice(t,this.pos))){i=false}if(s===46&&!i){++this.pos;this.readInt(10);s=this.input.charCodeAt(this.pos)}if((s===69||s===101)&&!i){s=this.input.charCodeAt(++this.pos);if(s===43||s===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var a=stringToNumber(this.input.slice(t,this.pos),i);return this.finishToken(m.num,a)};Ie.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var i=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(i,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Ie.readString=function(e){var t="",i=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var s=this.input.charCodeAt(this.pos);if(s===e){break}if(s===92){t+=this.input.slice(i,this.pos);t+=this.readEscapedChar(false);i=this.pos}else if(s===8232||s===8233){if(this.options.ecmaVersion<10){this.raise(this.start,"Unterminated string constant")}++this.pos;if(this.options.locations){this.curLine++;this.lineStart=this.pos}}else{if(isNewLine(s)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(i,this.pos++);return this.finishToken(m.string,t)};var Ae={};Ie.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===Ae){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};Ie.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw Ae}else{this.raise(e,t)}};Ie.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var i=this.input.charCodeAt(this.pos);if(i===96||i===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===m.template||this.type===m.invalidTemplate)){if(i===36){this.pos+=2;return this.finishToken(m.dollarBraceL)}else{++this.pos;return this.finishToken(m.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(m.template,e)}if(i===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(i)){e+=this.input.slice(t,this.pos);++this.pos;switch(i){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(i);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};Ie.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var s=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var r=parseInt(s,8);if(r>255){s=s.slice(0,-1);r=parseInt(s,8)}this.pos+=s.length-1;t=this.input.charCodeAt(this.pos);if((s!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-s.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(r)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};Ie.readHexChar=function(e){var t=this.pos;var i=this.readInt(16,e);if(i===null){this.invalidStringToken(t,"Bad character escape sequence")}return i};Ie.readWord1=function(){this.containsEsc=false;var e="",t=true,i=this.pos;var s=this.options.ecmaVersion>=6;while(this.pos= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseIdent(true); + this.checkExport(exports, node.exported.name, this.lastTokStart); + } else { + node.exported = null; + } + } + + this.expectContextual("from"); + + if (this.type !== tt.string) { + this.unexpected(); + } + + node.source = this.parseExprAtom(); + + if (this.type === this.assertToken) { + this.next(); + const assertions = this.parseImportAssertions(); + + if (assertions) { + node.assertions = assertions; + } + } + + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration"); + } + + if (this.eat(tt._default)) { + // export default ... + this.checkExport(exports, "default", this.lastTokStart); + var isAsync; + + if (this.type === tt._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + + if (isAsync) { + this.next(); + } + + node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); + } else if (this.type === tt._class) { + var cNode = this.startNode(); + node.declaration = this.parseClass(cNode, "nullableID"); + } else { + node.declaration = this.parseMaybeAssign(); + this.semicolon(); + } + + return this.finishNode(node, "ExportDefaultDeclaration"); + } // export var|const|let|function|class ... + + + if (this.shouldParseExportStatement()) { + node.declaration = this.parseStatement(null); + + if (node.declaration.type === "VariableDeclaration") { + this.checkVariableExport(exports, node.declaration.declarations); + } else { + this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); + } + + node.specifiers = []; + node.source = null; + } else { + // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + + if (this.eatContextual("from")) { + if (this.type !== tt.string) { + this.unexpected(); + } + + node.source = this.parseExprAtom(); + + if (this.type === this.assertToken) { + this.next(); + const assertions = this.parseImportAssertions(); + + if (assertions) { + node.assertions = assertions; + } + } + } else { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) { + // check for keywords used as local names + var spec = list[i]; + this.checkUnreserved(spec.local); // check if export is defined + + this.checkLocalExport(spec.local); + } + + node.source = null; + } + + this.semicolon(); + } + + return this.finishNode(node, "ExportNamedDeclaration"); + } + + parseImport(node) { + this.next(); // import '...' + + if (this.type === tt.string) { + node.specifiers = []; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected(); + } + + if (this.type === this.assertToken) { + this.next(); + const assertions = this.parseImportAssertions(); + + if (assertions) { + node.assertions = assertions; + } + } + + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); + } + + parseImportAssertions() { + this._eat(tt.braceL); + + const attrs = this.parseAssertEntries(); + + this._eat(tt.braceR); + + return attrs; + } + + parseAssertEntries() { + const attrs = []; + const attrNames = new Set(); + + do { + if (this.type === tt.braceR) { + break; + } + + const node = this.startNode(); // parse AssertionKey : IdentifierName, StringLiteral + + let assertionKeyNode; + + if (this.type === tt.string) { + assertionKeyNode = this.parseLiteral(this.value); + } else { + assertionKeyNode = this.parseIdent(true); + } + + this.next(); + node.key = assertionKeyNode; // for now we are only allowing `type` as the only allowed module attribute + + if (node.key.name !== "type") { + this.raise(this.pos, "The only accepted import assertion is `type`"); + } // check if we already have an entry for an attribute + // if a duplicate entry is found, throw an error + // for now this logic will come into play only when someone declares `type` twice + + + if (attrNames.has(node.key.name)) { + this.raise(this.pos, "Duplicated key in assertions"); + } + + attrNames.add(node.key.name); + + if (this.type !== tt.string) { + this.raise(this.pos, "Only string is supported as an assertion value"); + } + + node.value = this.parseLiteral(this.value); + attrs.push(this.finishNode(node, "ImportAttribute")); + } while (this.eat(tt.comma)); + + return attrs; + } + + }; +} + /***/ }), /***/ 5787: @@ -90755,7 +91054,7 @@ module.exports.chunkHasJs = chunkHasJs; const { Parser: AcornParser } = __webpack_require__(31988); -const { importAssertions } = __webpack_require__(50283); +const { importAssertions } = __webpack_require__(72617); const { SyncBailHook, HookMap } = __webpack_require__(6967); const vm = __webpack_require__(26144); const Parser = __webpack_require__(11715); @@ -133155,305 +133454,6 @@ class WebWorkerTemplatePlugin { module.exports = WebWorkerTemplatePlugin; -/***/ }), - -/***/ 50283: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.importAssertions = importAssertions; - -var _acorn = _interopRequireWildcard(__webpack_require__(31988)); - -function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } - -function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } - -const leftCurlyBrace = "{".charCodeAt(0); -const space = " ".charCodeAt(0); -const keyword = "assert"; -const FUNC_STATEMENT = 1, - FUNC_HANGING_STATEMENT = 2, - FUNC_NULLABLE_ID = 4; - -function importAssertions(Parser) { - // Use supplied version acorn version if present, to avoid - // reference mismatches due to different acorn versions. This - // allows this plugin to be used with Rollup which supplies - // its own internal version of acorn and thereby sidesteps - // the package manager. - const acorn = Parser.acorn || _acorn; - const { - tokTypes: tt, - TokenType - } = acorn; - return class extends Parser { - constructor(...args) { - super(...args); - this.assertToken = new TokenType(keyword); - } - - _codeAt(i) { - return this.input.charCodeAt(i); - } - - _eat(t) { - if (this.type !== t) { - this.unexpected(); - } - - this.next(); - } - - readToken(code) { - let i = 0; - - for (; i < keyword.length; i++) { - if (this._codeAt(this.pos + i) !== keyword.charCodeAt(i)) { - return super.readToken(code); - } - } // ensure that the keyword is at the correct location - // ie `assert{...` or `assert {...` - - - for (;; i++) { - if (this._codeAt(this.pos + i) === leftCurlyBrace) { - // Found '{' - break; - } else if (this._codeAt(this.pos + i) === space) { - // white space is allowed between `assert` and `{`, so continue. - continue; - } else { - return super.readToken(code); - } - } // If we're inside a dynamic import expression we'll parse - // the `assert` keyword as a standard object property name - // ie `import(""./foo.json", { assert: { type: "json" } })` - - - if (this.type.label === "{") { - return super.readToken(code); - } - - this.pos += keyword.length; - return this.finishToken(this.assertToken); - } - - parseDynamicImport(node) { - this.next(); // skip `(` - // Parse node.source. - - node.source = this.parseMaybeAssign(); - - if (this.eat(tt.comma)) { - const obj = this.parseObj(false); - node.arguments = [obj]; - } - - this._eat(tt.parenR); - - return this.finishNode(node, "ImportExpression"); - } // ported from acorn/src/statement.js pp.parseExport - - - parseExport(node, exports) { - this.next(); // export * from '...' - - if (this.eat(tt.star)) { - if (this.options.ecmaVersion >= 11) { - if (this.eatContextual("as")) { - node.exported = this.parseIdent(true); - this.checkExport(exports, node.exported.name, this.lastTokStart); - } else { - node.exported = null; - } - } - - this.expectContextual("from"); - - if (this.type !== tt.string) { - this.unexpected(); - } - - node.source = this.parseExprAtom(); - - if (this.type === this.assertToken) { - this.next(); - const assertions = this.parseImportAssertions(); - - if (assertions) { - node.assertions = assertions; - } - } - - this.semicolon(); - return this.finishNode(node, "ExportAllDeclaration"); - } - - if (this.eat(tt._default)) { - // export default ... - this.checkExport(exports, "default", this.lastTokStart); - var isAsync; - - if (this.type === tt._function || (isAsync = this.isAsyncFunction())) { - var fNode = this.startNode(); - this.next(); - - if (isAsync) { - this.next(); - } - - node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); - } else if (this.type === tt._class) { - var cNode = this.startNode(); - node.declaration = this.parseClass(cNode, "nullableID"); - } else { - node.declaration = this.parseMaybeAssign(); - this.semicolon(); - } - - return this.finishNode(node, "ExportDefaultDeclaration"); - } // export var|const|let|function|class ... - - - if (this.shouldParseExportStatement()) { - node.declaration = this.parseStatement(null); - - if (node.declaration.type === "VariableDeclaration") { - this.checkVariableExport(exports, node.declaration.declarations); - } else { - this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); - } - - node.specifiers = []; - node.source = null; - } else { - // export { x, y as z } [from '...'] - node.declaration = null; - node.specifiers = this.parseExportSpecifiers(exports); - - if (this.eatContextual("from")) { - if (this.type !== tt.string) { - this.unexpected(); - } - - node.source = this.parseExprAtom(); - - if (this.type === this.assertToken) { - this.next(); - const assertions = this.parseImportAssertions(); - - if (assertions) { - node.assertions = assertions; - } - } - } else { - for (var i = 0, list = node.specifiers; i < list.length; i += 1) { - // check for keywords used as local names - var spec = list[i]; - this.checkUnreserved(spec.local); // check if export is defined - - this.checkLocalExport(spec.local); - } - - node.source = null; - } - - this.semicolon(); - } - - return this.finishNode(node, "ExportNamedDeclaration"); - } - - parseImport(node) { - this.next(); // import '...' - - if (this.type === tt.string) { - node.specifiers = []; - node.source = this.parseExprAtom(); - } else { - node.specifiers = this.parseImportSpecifiers(); - this.expectContextual("from"); - node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected(); - } - - if (this.type === this.assertToken) { - this.next(); - const assertions = this.parseImportAssertions(); - - if (assertions) { - node.assertions = assertions; - } - } - - this.semicolon(); - return this.finishNode(node, "ImportDeclaration"); - } - - parseImportAssertions() { - this._eat(tt.braceL); - - const attrs = this.parseAssertEntries(); - - this._eat(tt.braceR); - - return attrs; - } - - parseAssertEntries() { - const attrs = []; - const attrNames = new Set(); - - do { - if (this.type === tt.braceR) { - break; - } - - const node = this.startNode(); // parse AssertionKey : IdentifierName, StringLiteral - - let assertionKeyNode; - - if (this.type === tt.string) { - assertionKeyNode = this.parseLiteral(this.value); - } else { - assertionKeyNode = this.parseIdent(true); - } - - this.next(); - node.key = assertionKeyNode; // for now we are only allowing `type` as the only allowed module attribute - - if (node.key.name !== "type") { - this.raise(this.pos, "The only accepted import assertion is `type`"); - } // check if we already have an entry for an attribute - // if a duplicate entry is found, throw an error - // for now this logic will come into play only when someone declares `type` twice - - - if (attrNames.has(node.key.name)) { - this.raise(this.pos, "Duplicated key in assertions"); - } - - attrNames.add(node.key.name); - - if (this.type !== tt.string) { - this.raise(this.pos, "Only string is supported as an assertion value"); - } - - node.value = this.parseLiteral(this.value); - attrs.push(this.finishNode(node, "ImportAttribute")); - } while (this.eat(tt.comma)); - - return attrs; - } - - }; -} - /***/ }), /***/ 14819: diff --git a/packages/next/package.json b/packages/next/package.json index 40624c88c93c..d66936dad338 100644 --- a/packages/next/package.json +++ b/packages/next/package.json @@ -162,6 +162,7 @@ "@types/ws": "8.2.0", "@vercel/ncc": "0.33.1", "@vercel/nft": "0.17.4", + "acorn": "8.5.0", "amphtml-validator": "1.0.33", "arg": "4.1.0", "assert": "2.0.0", diff --git a/yarn.lock b/yarn.lock index 73f4e90b3c7c..b376efc5417d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5508,6 +5508,11 @@ acorn-walk@^8.0.0: resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.0.0.tgz#56ae4c0f434a45fff4a125e7ea95fa9c98f67a16" integrity sha512-oZRad/3SMOI/pxbbmqyurIx7jHw1wZDcR9G44L8pUVFEomX/0dH89SrM1KaDXuv1NpzAXz6Op/Xu/Qd5XXzdEA== +acorn@8.5.0, acorn@^8.4.1: + version "8.5.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.5.0.tgz#4512ccb99b3698c752591e9bb4472e38ad43cee2" + integrity sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q== + acorn@^6.2.1: version "6.4.2" resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.4.2.tgz#35866fd710528e92de10cf06016498e47e39e1e6" @@ -5541,11 +5546,6 @@ acorn@^8.2.4: resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.4.1.tgz#56c36251fc7cabc7096adc18f05afe814321a28c" integrity sha512-asabaBSkEKosYKMITunzX177CXxQ4Q8BSSzMTKD+FefUhipQC70gfW5SiUDhYQ3vk8G+81HqQk7Fv9OXwwn9KA== -acorn@^8.4.1: - version "8.5.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.5.0.tgz#4512ccb99b3698c752591e9bb4472e38ad43cee2" - integrity sha512-yXbYeFy+jUuYd3/CDcg2NkIYE991XYX/bje7LmjJigUciaeO1JR4XxXgCIV1/Zc/dRuFEyw1L0pbA+qynJkW5Q== - acorn@^8.6.0: version "8.6.0" resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.6.0.tgz#e3692ba0eb1a0c83eaa4f37f5fa7368dd7142895"